prompt large_stringlengths 70 991k | completion large_stringlengths 0 1.02k |
|---|---|
<|file_name|>xmlrpcapi.py<|end_file_name|><|fim▁begin|>#
# SFA XML-RPC and SOAP interfaces
#
import string
import xmlrpclib
# SOAP support is optional
try:
import SOAPpy
from SOAPpy.Parser import parseSOAPRPC
from SOAPpy.Types import faultType
from SOAPpy.NS import NS
from SOAPpy.SOAPBuilder import buildSOAP
except ImportError:
SOAPpy = None
####################
#from sfa.util.faults import SfaNotImplemented, SfaAPIError, SfaInvalidAPIMethod, SfaFault
from sfa.util.faults import SfaInvalidAPIMethod, SfaAPIError, SfaFault
from sfa.util.sfalogging import logger
####################
# See "2.2 Characters" in the XML specification:
#
# #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
# avoiding
# [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
invalid_xml_ascii = map(chr, range(0x0, 0x8) + [0xB, 0xC] + range(0xE, 0x1F))
xml_escape_table = string.maketrans("".join(invalid_xml_ascii), "?" * len(invalid_xml_ascii))
def xmlrpclib_escape(s, replace = string.replace):
"""
xmlrpclib does not handle invalid 7-bit control characters. This
function augments xmlrpclib.escape, which by default only replaces
'&', '<', and '>' with entities.
"""
# This is the standard xmlrpclib.escape function
s = replace(s, "&", "&")
s = replace(s, "<", "<")
s = replace(s, ">", ">",)
# Replace invalid 7-bit control characters with '?'
return s.translate(xml_escape_table)
def xmlrpclib_dump(self, value, write):
"""
xmlrpclib cannot marshal instances of subclasses of built-in
types. This function overrides xmlrpclib.Marshaller.__dump so that
any value that is an instance of one of its acceptable types is
marshalled as that type.
xmlrpclib also cannot handle invalid 7-bit control characters. See
above.
"""
# Use our escape function
args = [self, value, write]
if isinstance(value, (str, unicode)):
args.append(xmlrpclib_escape)
try:
# Try for an exact match first
f = self.dispatch[type(value)]
except KeyError:
raise
# Try for an isinstance() match
for Type, f in self.dispatch.iteritems():
if isinstance(value, Type):
f(*args)
return
raise TypeError, "cannot marshal %s objects" % type(value)
else:
f(*args)
# You can't hide from me!
xmlrpclib.Marshaller._Marshaller__dump = xmlrpclib_dump
class XmlrpcApi:
"""
The XmlrpcApi class implements a basic xmlrpc (or soap) service
"""
protocol = None
def __init__ (self, encoding="utf-8", methods='sfa.methods'):
self.encoding = encoding
self.source = None
# flat list of method names
self.methods_module = methods_module = __import__(methods, fromlist=[methods])
self.methods = methods_module.all
self.logger = logger
def callable(self, method):
"""
Return a new instance of the specified method.
"""
# Look up method
if method not in self.methods:
raise SfaInvalidAPIMethod, method
# Get new instance of method
try:
classname = method.split(".")[-1]
module = __import__(self.methods_module.__name__ + "." + method, globals(), locals(), [classname])
callablemethod = getattr(module, classname)(self)
return getattr(module, classname)(self)
except (ImportError, AttributeError):
self.logger.log_exc("Error importing method: %s" % method)
raise SfaInvalidAPIMethod, method
def call(self, source, method, *args):
"""
Call the named method from the specified source with the
specified arguments.
"""
function = self.callable(method)
function.source = source
self.source = source
return function(*args)
def handle(self, source, data, method_map):
"""
Handle an XML-RPC or SOAP request from the specified source.
"""<|fim▁hole|> interface = xmlrpclib
self.protocol = 'xmlrpclib'
(args, method) = xmlrpclib.loads(data)
if method_map.has_key(method):
method = method_map[method]
methodresponse = True
except Exception, e:
if SOAPpy is not None:
self.protocol = 'soap'
interface = SOAPpy
(r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1)
method = r._name
args = r._aslist()
# XXX Support named arguments
else:
raise e
try:
result = self.call(source, method, *args)
except SfaFault, fault:
result = fault
self.logger.log_exc("XmlrpcApi.handle has caught Exception")
except Exception, fault:
self.logger.log_exc("XmlrpcApi.handle has caught Exception")
result = SfaAPIError(fault)
# Return result
response = self.prepare_response(result, method)
return response
def prepare_response(self, result, method=""):
"""
convert result to a valid xmlrpc or soap response
"""
if self.protocol == 'xmlrpclib':
if not isinstance(result, SfaFault):
result = (result,)
response = xmlrpclib.dumps(result, methodresponse = True, encoding = self.encoding, allow_none = 1)
elif self.protocol == 'soap':
if isinstance(result, Exception):
result = faultParameter(NS.ENV_T + ":Server", "Method Failed", method)
result._setDetail("Fault %d: %s" % (result.faultCode, result.faultString))
else:
response = buildSOAP(kw = {'%sResponse' % method: {'Result': result}}, encoding = self.encoding)
else:
if isinstance(result, Exception):
raise result
return response<|fim▁end|> | # Parse request into method name and arguments
try: |
<|file_name|>mutations.js<|end_file_name|><|fim▁begin|>const mutations = {
SET_ACTIVE_TAB(state, tab){
state.activeTab = tab;
},
SET_DATA_ACTIVE_TAB(state, tab){
state.hubActiveTab = tab;
},
SET_PROXY_STATE(state, proxy){
state.proxy_switch = proxy;
},
SET_INIT_INFO(state, info){
_.extend(state, info);
}
};<|fim▁hole|><|fim▁end|> |
export default mutations; |
<|file_name|>demo1.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# _*_ coding:utf-8 _*-_
############################
# File Name: demo.py
# Author: lza
# Created Time: 2016-08-30 16:29:35
############################
<|fim▁hole|>import dns.resolver
domain = raw_input ('Please input an domain: ') #输入域名地址
MX = dns.resolver.query(domain , "MX") #指定查询类型为A记录
for i in MX: # 遍历回应结果,输出MX记录的preference及exchanger信息
print 'MX preference =', i.preference, 'mail exchanger =', i.exchange
if __name__ == "__main__":
pass<|fim▁end|> | |
<|file_name|>factual_driver_test.go<|end_file_name|><|fim▁begin|>package factual
import (
"fmt"
"strings"
"testing"
)
func TestToken(t *testing.T) {
fR := NewToken("Pbu7jRdBErgLW07g9c25JtGcwwt1KmpoxRTfFL3x", "vC4AgocPBhxe0GFkTsetoiuEAJEgqz6MCbAnXEoO")
<|fim▁hole|> fmt.Println(err)
return
}
nR.AddQuery("pizza")
nR.AddLimit(5)
nR.AddSelect("factual_id")
//fmt.Println("frData", nR.GetReadURL())
s, err := nR.Get()
if err != nil {
fmt.Println(err)
t.Error(err)
}
if strings.Contains(s, "error") {
t.Error("response returned an error")
}
//fmt.Println(s)
}
/*
func TestSchema(t *testing.T) {
fR := NewToken("Pbu7jRdBErgLW07g9c25JtGcwwt1KmpoxRTfFL3x", "vC4AgocPBhxe0GFkTsetoiuEAJEgqz6MCbAnXEoO")
s, err := fR.Get("http://api.v3.factual.com/t/restaurants-us/schema")
if err != nil {
t.Error(err)
return
}
fmt.Println(s)
}*/<|fim▁end|> | nR, err := NewRead(fR, "restaurants-us")
if err != nil { |
<|file_name|>maquette.d.ts<|end_file_name|><|fim▁begin|>/**
* Welcome to the API documentation of the **maquette** library.
*
* [[http://maquettejs.org/|To the maquette homepage]]
*/
/**
* A virtual representation of a DOM Node. Maquette assumes that [[VNode]] objects are never modified externally.
* Instances of [[VNode]] can be created using [[h]].
*/
export interface VNode {
/**
* The CSS selector containing tagname, css classnames and id. An empty string is used to denote a text node.
*/
readonly vnodeSelector: string;
/**
* Object containing attributes, properties, event handlers and more, see [[h]].
*/
readonly properties: VNodeProperties | undefined;
/**
* Array of [[VNode]]s to be used as children. This array is already flattened.
*/
readonly children: Array<VNode> | undefined;
/**
* Used in a special case when a [[VNode]] only has one childnode which is a textnode. Only used in combination with children === undefined.
*/
readonly text: string | undefined;
/**
* Used by maquette to store the domNode that was produced from this [[VNode]].
*/
domNode: Node | null;
}
/**
* A projector is used to create the real DOM from the the virtual DOM and to keep it up-to-date afterwards.
*
* You can call [[append]], [[merge]], [[insertBefore]] and [[replace]] to add the virtual DOM to the real DOM.
* The `renderMaquetteFunction` callbacks will be called to create the real DOM immediately.
* Afterwards, the `renderMaquetteFunction` callbacks will be called again to update the DOM on the next animation-frame after:
*
* - The Projector's [[scheduleRender]] function was called
* - An event handler (like `onclick`) on a rendered [[VNode]] was called.
*
* The projector stops when [[stop]] is called or when an error is thrown during rendering.
* It is possible to use `window.onerror` to handle these errors.
* Instances of [[Projector]] can be created using [[createProjector]].
*/
export interface Projector {
/**
* Appends a new childnode to the DOM using the result from the provided `renderMaquetteFunction`.
* The `renderMaquetteFunction` will be invoked again to update the DOM when needed.
* @param parentNode - The parent node for the new childNode.
* @param renderMaquetteFunction - Function with zero arguments that returns a [[VNode]] tree.
*/
append(parentNode: Element, renderMaquetteFunction: () => VNode): void;
/**
* Inserts a new DOM node using the result from the provided `renderMaquetteFunction`.
* The `renderMaquetteFunction` will be invoked again to update the DOM when needed.
* @param beforeNode - The node that the DOM Node is inserted before.
* @param renderMaquetteFunction - Function with zero arguments that returns a [[VNode]] tree.
*/
insertBefore(beforeNode: Element, renderMaquetteFunction: () => VNode): void;
/**
* Merges a new DOM node using the result from the provided `renderMaquetteFunction` with an existing DOM Node.
* This means that the virtual DOM and real DOM have one overlapping element.
* Therefore the selector for the root [[VNode]] will be ignored, but its properties and children will be applied to the Element provided
* The `renderMaquetteFunction` will be invoked again to update the DOM when needed.
* @param domNode - The existing element to adopt as the root of the new virtual DOM. Existing attributes and childnodes are preserved.
* @param renderMaquetteFunction - Function with zero arguments that returns a [[VNode]] tree.
*/
merge(domNode: Element, renderMaquetteFunction: () => VNode): void;
/**
* Replaces an existing DOM node with the result from the provided `renderMaquetteFunction`.
* The `renderMaquetteFunction` will be invoked again to update the DOM when needed.
* @param domNode - The DOM node to replace.
* @param renderMaquetteFunction - Function with zero arguments that returns a [[VNode]] tree.
*/
replace(domNode: Element, renderMaquetteFunction: () => VNode): void;
/**
* Resumes the projector. Use this method to resume rendering after [[stop]] was called or an error occurred during rendering.
*/
resume(): void;
/**
* Instructs the projector to re-render to the DOM at the next animation-frame using the registered `renderMaquette` functions.
* This method is automatically called for you when event-handlers that are registered in the [[VNode]]s are invoked.
*
* You need to call this method when timeouts expire, when AJAX responses arrive or other asynchronous actions happen.
*/
scheduleRender(): void;
/**
* Synchronously re-renders to the DOM. You should normally call the `scheduleRender()` function to keep the
* user interface more performant. There is however one good reason to call renderNow(),
* when you want to put the focus into a newly created element in iOS.
* This is only allowed when triggered by a user-event, not during requestAnimationFrame.
*/
renderNow(): void;
/**
* Stops running the `renderMaquetteFunction` to update the DOM. The `renderMaquetteFunction` must have been
* registered using [[append]], [[merge]], [[insertBefore]] or [[replace]].
*
* @returns The [[Projection]] which was created using this `renderMaquetteFunction`.
* The [[Projection]] contains a reference to the DOM Node that was rendered.
*/
detach(renderMaquetteFunction: () => VNode): Projection;
/**
* Stops the projector. This means that the registered `renderMaquette` functions will not be called anymore.
*
* Note that calling [[stop]] is not mandatory. A projector is a passive object that will get garbage collected
* as usual if it is no longer in scope.
*/
stop(): void;
}
/**
* These functions are called when [[VNodeProperties.enterAnimation]] and [[VNodeProperties.exitAnimation]] are provided as strings.
* See [[ProjectionOptions.transitions]].
*/
export interface TransitionStrategy {
/**
* Function that is called when a [[VNode]] with an `enterAnimation` string is added to an already existing parent [[VNode]].
*
* @param element Element that was just added to the DOM.
* @param properties The properties object that was supplied to the [[h]] method
* @param enterAnimation The string that was passed to [[VNodeProperties.enterAnimation]].
*/
enter(element: Element, properties: VNodeProperties, enterAnimation: string): void;
/**
* Function that is called when a [[VNode]] with an `exitAnimation` string is removed from a existing parent [[VNode]] that remains.
*
* @param element Element that ought to be removed from to the DOM.
* @param properties The properties object that was supplied to the [[h]] method that rendered this [[VNode]] the previous time.
* @param exitAnimation The string that was passed to [[VNodeProperties.exitAnimation]].
* @param removeElement Function that removes the element from the DOM.
* This argument is provided purely for convenience.
* You may use this function to remove the element when the animation is done.
*/
exit(element: Element, properties: VNodeProperties, exitAnimation: string, removeElement: () => void): void;
}
/**
* Options that may be passed when creating the [[Projector]]
*/
export interface ProjectorOptions {
/**<|fim▁hole|> * The module `cssTransitions` in the provided `css-transitions.js` file provides such a strategy.
* A transition strategy is not needed when enterAnimation and exitAnimation properties are provided as functions.
*/
readonly transitions?: TransitionStrategy;
/**
* May be used to add vendor prefixes when applying inline styles when needed.
* This function is called when [[styles]] is used.
* This function should execute `domNode.style[styleName] = value` or do something smarter.
*
* @param domNode The DOM Node that needs to receive the style
* @param styleName The name of the style that should be applied, for example `transform`.
* @param value The value of this style, for example `rotate(45deg)`.
*/
styleApplyer?(domNode: HTMLElement, styleName: string, value: string): void;
}
/**
* Options that influence how the DOM is rendered and updated.
*/
export interface ProjectionOptions extends ProjectorOptions {
/**
* Only for internal use. Used for rendering SVG Nodes.
*/
readonly namespace?: string;
/**
* May be used to intercept registration of event-handlers.
*
* Used by the [[Projector]] to wrap eventHandler-calls to call [[scheduleRender]] as well.
*
* @param propertyName The name of the property to be assigned, for example onclick
* @param eventHandler The function that was registered on the [[VNode]]
* @param domNode The real DOM element
* @param properties The whole set of properties that was put on the VNode
* @returns The function that is to be placed on the DOM node as the event handler, instead of `eventHandler`.
*/
eventHandlerInterceptor?: (propertyName: string, eventHandler: Function, domNode: Node, properties: VNodeProperties) => Function;
}
/**
* Object containing attributes, properties, event handlers and more that can be put on DOM nodes.
*
* For your convenience, all common attributes, properties and event handlers are listed here and are
* type-checked when using Typescript.
*/
export interface VNodeProperties {
/**
* The animation to perform when this node is added to an already existing parent.
* When this value is a string, you must pass a `projectionOptions.transitions` object when creating the
* projector using [[createProjector]].
* {@link http://maquettejs.org/docs/animations.html|More about animations}.
* @param element - Element that was just added to the DOM.
* @param properties - The properties object that was supplied to the [[h]] method
*/
enterAnimation?: ((element: Element, properties?: VNodeProperties) => void) | string;
/**
* The animation to perform when this node is removed while its parent remains.
* When this value is a string, you must pass a `projectionOptions.transitions` object when creating the projector using [[createProjector]].
* {@link http://maquettejs.org/docs/animations.html|More about animations}.
* @param element - Element that ought to be removed from to the DOM.
* @param removeElement - Function that removes the element from the DOM.
* This argument is provided purely for convenience.
* You may use this function to remove the element when the animation is done.
* @param properties - The properties object that was supplied to the [[h]] method that rendered this [[VNode]] the previous time.
*/
exitAnimation?: ((element: Element, removeElement: () => void, properties?: VNodeProperties) => void) | string;
/**
* The animation to perform when the properties of this node change.
* This also includes attributes, styles, css classes. This callback is also invoked when node contains only text and that text changes.
* {@link http://maquettejs.org/docs/animations.html|More about animations}.
* @param element - Element that was modified in the DOM.
* @param properties - The last properties object that was supplied to the [[h]] method
* @param previousProperties - The previous properties object that was supplied to the [[h]] method
*/
updateAnimation?: (element: Element, properties?: VNodeProperties, previousProperties?: VNodeProperties) => void;
/**
* Callback that is executed after this node is added to the DOM. Childnodes and properties have
* already been applied.
* @param element - The element that was added to the DOM.
* @param projectionOptions - The projection options that were used see [[createProjector]].
* @param vnodeSelector - The selector passed to the [[h]] function.
* @param properties - The properties passed to the [[h]] function.
* @param children - The children that were created.
*/
afterCreate?(element: Element, projectionOptions: ProjectionOptions, vnodeSelector: string, properties: VNodeProperties, children: VNode[]): void;
/**
* Callback that is executed every time this node may have been updated. Childnodes and properties
* have already been updated.
* @param element - The element that may have been updated in the DOM.
* @param projectionOptions - The projection options that were used see [[createProjector]].
* @param vnodeSelector - The selector passed to the [[h]] function.
* @param properties - The properties passed to the [[h]] function.
* @param children - The children for this node.
*/
afterUpdate?(element: Element, projectionOptions: ProjectionOptions, vnodeSelector: string, properties: VNodeProperties, children: VNode[]): void;
/**
* When specified, the event handlers will be invoked with 'this' pointing to the value.
* This is useful when using the prototype/class based implementation of Components.
*
* When no [[key]] is present, this object is also used to uniquely identify a DOM node.
*/
readonly bind?: Object;
/**
* Used to uniquely identify a DOM node among siblings.
* A key is required when there are more children with the same selector and these children are added or removed dynamically.
* NOTE: this does not have to be a string or number, a [[Component]] Object for instance is also possible.
*/
readonly key?: Object;
/**
* An object literal like `{important:true}` which allows css classes, like `important` to be added and removed
* dynamically.
*/
readonly classes?: {
[index: string]: boolean | null | undefined;
};
/**
* An object literal like `{height:'100px'}` which allows styles to be changed dynamically. All values must be strings.
*/
readonly styles?: {
[index: string]: string | null | undefined;
};
ontouchcancel?(ev?: TouchEvent): boolean | void;
ontouchend?(ev?: TouchEvent): boolean | void;
ontouchmove?(ev?: TouchEvent): boolean | void;
ontouchstart?(ev?: TouchEvent): boolean | void;
readonly action?: string;
readonly encoding?: string;
readonly enctype?: string;
readonly method?: string;
readonly name?: string;
readonly target?: string;
readonly href?: string;
readonly rel?: string;
onblur?(ev?: FocusEvent): boolean | void;
onchange?(ev?: Event): boolean | void;
onclick?(ev?: MouseEvent): boolean | void;
ondblclick?(ev?: MouseEvent): boolean | void;
onfocus?(ev?: FocusEvent): boolean | void;
oninput?(ev?: Event): boolean | void;
onkeydown?(ev?: KeyboardEvent): boolean | void;
onkeypress?(ev?: KeyboardEvent): boolean | void;
onkeyup?(ev?: KeyboardEvent): boolean | void;
onload?(ev?: Event): boolean | void;
onmousedown?(ev?: MouseEvent): boolean | void;
onmouseenter?(ev?: MouseEvent): boolean | void;
onmouseleave?(ev?: MouseEvent): boolean | void;
onmousemove?(ev?: MouseEvent): boolean | void;
onmouseout?(ev?: MouseEvent): boolean | void;
onmouseover?(ev?: MouseEvent): boolean | void;
onmouseup?(ev?: MouseEvent): boolean | void;
onmousewheel?(ev?: WheelEvent | MouseWheelEvent): boolean | void;
onscroll?(ev?: UIEvent): boolean | void;
onsubmit?(ev?: Event): boolean | void;
readonly spellcheck?: boolean;
readonly tabIndex?: number;
readonly disabled?: boolean;
readonly title?: string;
readonly accessKey?: string;
readonly id?: string;
readonly type?: string;
readonly autocomplete?: string;
readonly checked?: boolean;
readonly placeholder?: string;
readonly readOnly?: boolean;
readonly src?: string;
readonly value?: string;
readonly alt?: string;
readonly srcset?: string;
/**
* Puts a non-interactive piece of html inside the DOM node.
*
* Note: if you use innerHTML, maquette cannot protect you from XSS vulnerabilities and you must make sure that the innerHTML value is safe.
*/
readonly innerHTML?: string;
/**
* Everything that is not explicitly listed (properties and attributes that are either uncommon or custom).
*/
readonly [index: string]: any;
}
/**
* Represents a [[VNode]] tree that has been rendered to a real DOM tree.
*/
export interface Projection {
/**
* The DOM node that is used as the root of this [[Projection]].
*/
readonly domNode: Element;
/**
* Updates the real DOM to match the new virtual DOM tree.
* @param updatedVnode The updated virtual DOM tree. Note: The selector for the root of the [[VNode]] tree may not change.
*/
update(updatedVnode: VNode): void;
}
/**
* Only needed for the definition of [[VNodeChild]].
*/
export interface VNodeChildren extends Array<VNodeChild> {
}
/**
* These are valid values for the children parameter of the [[h]] function.
*/
export declare type VNodeChild = string | VNode | VNodeChildren | null | undefined;
/**
* Contains all valid method signatures for the [[h]] function.
*/
export interface H {
/**
* @param selector Contains the tagName, id and fixed css classnames in CSS selector format.
* It is formatted as follows: `tagname.cssclass1.cssclass2#id`.
* @param properties An object literal containing properties that will be placed on the DOM node.
* @param children Virtual DOM nodes and strings to add as child nodes.
* `children` may contain [[VNode]]s, `string`s, nested arrays, `null` and `undefined`.
* Nested arrays are flattened, `null` and `undefined` are removed.
*
* @returns A VNode object, used to render a real DOM later.
*/
(selector: string, properties?: VNodeProperties, ...children: VNodeChild[]): VNode;
(selector: string, ...children: VNodeChild[]): VNode;
}
/**
* The `h` function is used to create a virtual DOM node.
* This function is largely inspired by the mercuryjs and mithril frameworks.
* The `h` stands for (virtual) hyperscript.
*
* All possible method signatures of this function can be found in the [[H]] 'interface'.
*
* NOTE: There are {@link http://maquettejs.org/docs/rules.html|three basic rules} you should be aware of when updating the virtual DOM.
*/
export declare let h: H;
/**
* Contains simple low-level utility functions to manipulate the real DOM.
*/
export declare let dom: {
create: (vnode: VNode, projectionOptions?: ProjectionOptions | undefined) => Projection;
append: (parentNode: Element, vnode: VNode, projectionOptions?: ProjectionOptions | undefined) => Projection;
insertBefore: (beforeNode: Element, vnode: VNode, projectionOptions?: ProjectionOptions | undefined) => Projection;
merge: (element: Element, vnode: VNode, projectionOptions?: ProjectionOptions | undefined) => Projection;
};
/**
* A CalculationCache object remembers the previous outcome of a calculation along with the inputs.
* On subsequent calls the previous outcome is returned if the inputs are identical.
* This object can be used to bypass both rendering and diffing of a virtual DOM subtree.
* Instances of CalculationCache can be created using [[createCache]].
*
* @param <Result> The type of the value that is cached.
*/
export interface CalculationCache<Result> {
/**
* Manually invalidates the cached outcome.
*/
invalidate(): void;
/**
* If the inputs array matches the inputs array from the previous invocation, this method returns the result of the previous invocation.
* Otherwise, the calculation function is invoked and its result is cached and returned.
* Objects in the inputs array are compared using ===.
* @param inputs - Array of objects that are to be compared using === with the inputs from the previous invocation.
* These objects are assumed to be immutable primitive values.
* @param calculation - Function that takes zero arguments and returns an object (A [[VNode]] presumably) that can be cached.
*/
result(inputs: Object[], calculation: () => Result): Result;
}
/**
* Creates a [[CalculationCache]] object, useful for caching [[VNode]] trees.
* In practice, caching of [[VNode]] trees is not needed, because achieving 60 frames per second is almost never a problem.
* For more information, see [[CalculationCache]].
*
* @param <Result> The type of the value that is cached.
*/
export declare let createCache: <Result>() => CalculationCache<Result>;
/**
* Keeps an array of result objects synchronized with an array of source objects.
* See {@link http://maquettejs.org/docs/arrays.html|Working with arrays}.
*
* Mapping provides a [[map]] function that updates its [[results]].
* The [[map]] function can be called multiple times and the results will get created, removed and updated accordingly.
* A Mapping can be used to keep an array of components (objects with a `renderMaquette` method) synchronized with an array of data.
* Instances of Mapping can be created using [[createMapping]].
*
* @param <Source> The type of source elements. Usually the data type.
* @param <Target> The type of target elements. Usually the component type.
*/
export interface Mapping<Source, Target> {
/**
* The array of results. These results will be synchronized with the latest array of sources that were provided using [[map]].
*/
results: Array<Target>;
/**
* Maps a new array of sources and updates [[results]].
*
* @param newSources The new array of sources.
*/
map(newSources: Array<Source>): void;
}
/**
* Creates a {@link Mapping} instance that keeps an array of result objects synchronized with an array of source objects.
* See {@link http://maquettejs.org/docs/arrays.html|Working with arrays}.
*
* @param <Source> The type of source items. A database-record for instance.
* @param <Target> The type of target items. A [[Component]] for instance.
* @param getSourceKey `function(source)` that must return a key to identify each source object. The result must either be a string or a number.
* @param createResult `function(source, index)` that must create a new result object from a given source. This function is identical
* to the `callback` argument in `Array.map(callback)`.
* @param updateResult `function(source, target, index)` that updates a result to an updated source.
*/
export declare let createMapping: <Source, Target>(getSourceKey: (source: Source) => string | number, createResult: (source: Source, index: number) => Target, updateResult: (source: Source, target: Target, index: number) => void) => Mapping<Source, Target>;
/**
* Creates a [[Projector]] instance using the provided projectionOptions.
*
* For more information, see [[Projector]].
*
* @param projectorOptions Options that influence how the DOM is rendered and updated.
*/
export declare let createProjector: (projectorOptions?: ProjectorOptions | undefined) => Projector;
/**
* A component is a pattern with which you can split up your web application into self-contained parts.
*
* A component may contain other components.
* This can be achieved by calling the subcomponents `renderMaquette` functions during the [[renderMaquette]] function and by using the
* resulting [[VNode]]s in the return value.
*
* This interface is not used anywhere in the maquette sourcecode, but this is a widely used pattern.
*/
export interface Component {
/**
* A function that returns the DOM representation of the component.
*/
renderMaquette(): VNode | null | undefined;
}<|fim▁end|> | * A transition strategy to invoke when enterAnimation and exitAnimation properties are provided as strings. |
<|file_name|>services_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Copyright 2012 Google Inc. All Rights Reserved.
"""Tests for grr.lib.flows.general.services."""
from grr.lib import aff4
from grr.lib import rdfvalue
from grr.lib import test_lib
class ServicesTest(test_lib.FlowTestsBaseclass):
def testEnumerateRunningServices(self):
<|fim▁hole|> service.osx_launchd.sessiontype = "Aqua"
service.osx_launchd.lastexitstatus = 0
service.osx_launchd.timeout = 30
service.osx_launchd.ondemand = 1
return [service]
# Run the flow in the emulated way.
for _ in test_lib.TestFlowHelper(
"EnumerateRunningServices", ClientMock(), client_id=self.client_id,
token=self.token):
pass
# Check the output file is created
fd = aff4.FACTORY.Open(rdfvalue.RDFURN(self.client_id)
.Add("analysis/Services"),
token=self.token)
self.assertEqual(fd.__class__.__name__, "RDFValueCollection")
jobs = list(fd)
self.assertEqual(len(fd), 1)
self.assertEqual(jobs[0].label, "org.openbsd.ssh-agent")
self.assertEqual(jobs[0].args, "/usr/bin/ssh-agent -l")
self.assertIsInstance(jobs[0], rdfvalue.Service)<|fim▁end|> | class ClientMock(object):
def EnumerateRunningServices(self, _):
service = rdfvalue.Service(label="org.openbsd.ssh-agent",
args="/usr/bin/ssh-agent -l") |
<|file_name|>mut_exclusive_violation1.rs<|end_file_name|><|fim▁begin|>fn demo_mut_advanced_unique(our: &mut i32) -> i32 {
unknown_code_1(&*our);
// This "re-asserts" uniqueness of the reference: After writing, we know
// our tag is at the top of the stack.
*our = 5;
unknown_code_2();
// We know this will return 5
*our
}
// Now comes the evil context
use std::ptr;
<|fim▁hole|>fn unknown_code_1(x: &i32) { unsafe {
LEAK = x as *const _ as *mut _;
} }
fn unknown_code_2() { unsafe {
*LEAK = 7; //~ ERROR borrow stack
} }
fn main() {
demo_mut_advanced_unique(&mut 0);
}<|fim▁end|> | static mut LEAK: *mut i32 = ptr::null_mut();
|
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'schwag.views.home', name='home'),
url(r'^about/$', 'schwag.views.about', name='about'),
url(r'^location/$', 'schwag.views.location', name='location'),
url(r'^contact/$', 'schwag.views.contact', name='contact'),<|fim▁hole|> url(r'^account/login/$', 'schwag.views.login', name='login'),
url(r'^account/logout/$', 'schwag.views.logout', name='logout'),
url(r'^account/register/$', 'schwag.views.register', name='register'),
url(r'^account/', include('django.contrib.auth.urls')),
url(r'^checkout/', include('senex_shop.checkout.urls')),
url(r'^cart/', include('senex_shop.cart.urls')),
url(r'^shop/', include('senex_shop.urls')),
url(r'^news/', include('senex_shop.news.urls')),
url(r'^admin/', include(admin.site.urls)),
)
# Uncomment the next line to serve media files in dev.
# urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
try:
import debug_toolbar
urlpatterns += patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
)
except ImportError:
pass
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}),
)<|fim▁end|> | url(r'^bmx/$', 'schwag.views.bmx', name='bmx'), |
<|file_name|>lub-glb-with-unbound-infer-var.rs<|end_file_name|><|fim▁begin|>// run-pass
// Test for a specific corner case: when we compute the LUB of two fn
// types and their parameters have unbound variables. In that case, we<|fim▁hole|>// wind up relating those two variables. This was causing an ICE in an
// in-progress PR.
fn main() {
let a_f: fn(_) = |_| ();
let b_f: fn(_) = |_| ();
let c_f = match 22 {
0 => a_f,
_ => b_f,
};
c_f(4);
}<|fim▁end|> | |
<|file_name|>TouchEvent.d.ts<|end_file_name|><|fim▁begin|>import { Event } from './Event';
import { Layer } from '../display/Layer';
export declare class TouchEvent extends Event {
/** @event touchStart */
static readonly TOUCH_START: string;
/** @event touchMove */
static readonly TOUCH_MOVE: string;
/** @event touchEnd */
static readonly TOUCH_END: string;
/** @event touchCancel */
static readonly TOUCH_CANCEL: string;
/** @event touchTap */
static readonly TOUCH_TAP: string;
target: Layer;
currentTarget: Layer;
targetX: number;
targetY: number;
localX: number;
localY: number;<|fim▁hole|> identifier: number;
cancelBubble: boolean;
protected constructor(type: string);
protected $init(type: string): this;
stopPropagation(): void;
release(): void;
protected static readonly $pool: Array<TouchEvent>;
static create(type: string): TouchEvent;
static recycle(e: TouchEvent): void;
}<|fim▁end|> | stageX: number;
stageY: number; |
<|file_name|>audioApp.py<|end_file_name|><|fim▁begin|>from flask import (Flask, session, render_template, request, redirect,
url_for, make_response, Blueprint, current_app)
import requests
import json
from datetime import datetime, timedelta
from flask.ext.cors import CORS, cross_origin
bp = Blueprint('audioTag', __name__)
def create_app(blueprint=bp):
app = Flask(__name__)
app.register_blueprint(blueprint)
app.config.from_pyfile('config.py')
CORS(app, allow_headers=('Content-Type', 'Authorization'))
return app
@bp.route('/', methods=['GET'])
@cross_origin()
def index():<|fim▁hole|>
# if auth_tok is in session already..
if 'auth_tok' in session:
auth_tok = session['auth_tok']
# check if it has expired
oauth_token_expires_in_endpoint = current_app.config.get(
'SWTSTORE_URL')+'/oauth/token-expires-in'
resp = requests.get(oauth_token_expires_in_endpoint)
expires_in = json.loads(resp.text)['expires_in']
# added for backwared compatibility. previous session stores did not
# have issued key
try:
check = datetime.utcnow() - auth_tok['issued']
if check > timedelta(seconds=expires_in):
# TODO: try to refresh the token before signing out the user
auth_tok = {'access_token': '', 'refresh_token': ''}
else:
"""access token did not expire"""
pass
# if issued key is not there, reset the session
except KeyError:
auth_tok = {'access_token': '', 'refresh_token': ''}
else:
auth_tok = {'access_token': '', 'refresh_token': ''}
# print 'existing tokens'
# print auth_tok
# payload = {'what': 'img-anno',
# 'access_token': auth_tok['access_token']}
# req = requests.get(current_app.config.get(
# 'SWTSTORE_URL', 'SWTSTORE_URL') + '/api/sweets/q', params=payload)
# sweets = req.json()
return render_template('index.html', access_token=auth_tok['access_token'],
refresh_token=auth_tok['refresh_token'],
config=current_app.config,
url=request.args.get('where'))
@bp.route('/authenticate', methods=['GET'])
def authenticateWithOAuth():
auth_tok = None
code = request.args.get('code')
# prepare the payload
payload = {
'scopes': 'email context',
'client_secret': current_app.config.get('APP_SECRET'),
'code': code,
'redirect_uri': current_app.config.get('REDIRECT_URI'),
'grant_type': 'authorization_code',
'client_id': current_app.config.get('APP_ID')
}
# token exchange endpoint
oauth_token_x_endpoint = current_app.config.get(
'SWTSTORE_URL', 'SWTSTORE_URL') + '/oauth/token'
resp = requests.post(oauth_token_x_endpoint, data=payload)
auth_tok = json.loads(resp.text)
if 'error' in auth_tok:
return make_response(auth_tok['error'], 200)
# set sessions etc
session['auth_tok'] = auth_tok
session['auth_tok']['issued'] = datetime.utcnow()
return redirect(url_for('audioTag.index'))
@bp.route('/admin', methods=['GET', 'POST'])
def admin():
if request.method == 'POST':
phone = request.form.get('usertel')
print repr(phone)
return render_template('admin.html')
@bp.route('/upload', methods=['GET', 'POST'])
def upload():
return render_template('upload_url.html')
if __name__ == '__main__':
app = create_app()
app.run(debug=app.config.get('DEBUG'),
host=app.config.get('HOST'))<|fim▁end|> | |
<|file_name|>collections.py<|end_file_name|><|fim▁begin|>def _iter(target, method, key):
iterable = target if method is None else getattr(target, method)()
iterator = iter(iterable)
if key is None:
return iterator
if not callable(key):<|fim▁hole|> return (each for each in iterator if key(each))
def iterate(target, key=None):
return _iter(target=target, method=None, key=key)
def iter_values(dict_, key=None):
return _iter(target=dict_, method='values', key=key)
def iter_items(dict_, key=None):
return _iter(target=dict_, method='items', key=key)<|fim▁end|> | raise TypeError('{!r} is not callable'.format(type(key).__name__))
|
<|file_name|>etl.py<|end_file_name|><|fim▁begin|># File: etl.py
# Purpose: To do the `Transform` step of an Extract-Transform-Load.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Thursday 22 September 2016, 03:40 PM
def transform(words):
new_words = dict()
for point, letters in words.items():<|fim▁hole|> new_words[letter.lower()] = point
return new_words<|fim▁end|> | for letter in letters: |
<|file_name|>mfcc_ops_test.py<|end_file_name|><|fim▁begin|># Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""Tests for mfcc_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import spectral_ops_test_util
from tensorflow.python.ops.signal import mfcc_ops
from tensorflow.python.platform import test
# TODO(rjryan): We have no open source tests for MFCCs at the moment. Internally
# at Google, this code is tested against a reference implementation that follows
# HTK conventions.
class MFCCTest(test.TestCase):
def test_error(self):
# num_mel_bins must be positive.
with self.assertRaises(ValueError):
signal = array_ops.zeros((2, 3, 0))
mfcc_ops.mfccs_from_log_mel_spectrograms(signal)
# signal must be float32
with self.assertRaises(ValueError):
signal = array_ops.zeros((2, 3, 5), dtype=dtypes.float64)
mfcc_ops.mfccs_from_log_mel_spectrograms(signal)
def test_basic(self):
"""A basic test that the op runs on random input."""
with spectral_ops_test_util.fft_kernel_label_map():
with self.session(use_gpu=True):
signal = random_ops.random_normal((2, 3, 5))
mfcc_ops.mfccs_from_log_mel_spectrograms(signal).eval()
<|fim▁hole|> signal = array_ops.placeholder_with_default(
random_ops.random_normal((2, 3, 5)), tensor_shape.TensorShape(None))
self.assertIsNone(signal.shape.ndims)
mfcc_ops.mfccs_from_log_mel_spectrograms(signal).eval()
if __name__ == "__main__":
test.main()<|fim▁end|> | def test_unknown_shape(self):
"""A test that the op runs when shape and rank are unknown."""
with spectral_ops_test_util.fft_kernel_label_map():
with self.session(use_gpu=True): |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
support for presenting detailed information in failing assertions.
"""
import py
import sys
import pytest
from _pytest.monkeypatch import monkeypatch
from _pytest.assertion import util
def pytest_addoption(parser):
group = parser.getgroup("debugconfig")
group.addoption('--assert', action="store", dest="assertmode",
choices=("rewrite", "reinterp", "plain",),
default="rewrite", metavar="MODE",
help="""control assertion debugging tools.
'plain' performs no assertion debugging.
'reinterp' reinterprets assert statements after they failed to provide assertion expression information.
'rewrite' (the default) rewrites assert statements in test modules on import
to provide assert expression information. """)
group.addoption('--no-assert', action="store_true", default=False,
dest="noassert", help="DEPRECATED equivalent to --assert=plain")
group.addoption('--nomagic', action="store_true", default=False,
dest="nomagic", help="DEPRECATED equivalent to --assert=plain")
class AssertionState:
"""State for the assertion plugin."""
def __init__(self, config, mode):
self.mode = mode
self.trace = config.trace.root.get("assertion")
def pytest_configure(config):
mode = config.getvalue("assertmode")
if config.getvalue("noassert") or config.getvalue("nomagic"):
mode = "plain"
if mode == "rewrite":
try:
import ast
except ImportError:
mode = "reinterp"
else:
if sys.platform.startswith('java'):
mode = "reinterp"
if mode != "plain":
_load_modules(mode)
m = monkeypatch()
config._cleanup.append(m.undo)
m.setattr(py.builtin.builtins, 'AssertionError',
reinterpret.AssertionError)
hook = None
if mode == "rewrite":
hook = rewrite.AssertionRewritingHook()
sys.meta_path.append(hook)
warn_about_missing_assertion(mode)
config._assertstate = AssertionState(config, mode)
config._assertstate.hook = hook
config._assertstate.trace("configured with mode set to %r" % (mode,))
def pytest_unconfigure(config):
hook = config._assertstate.hook
if hook is not None:
sys.meta_path.remove(hook)
def pytest_collection(session):<|fim▁hole|> # so for example not in the master process of pytest-xdist
# (which does not collect test modules)
hook = session.config._assertstate.hook
if hook is not None:
hook.set_session(session)
def pytest_runtest_setup(item):
def callbinrepr(op, left, right):
hook_result = item.ihook.pytest_assertrepr_compare(
config=item.config, op=op, left=left, right=right)
for new_expl in hook_result:
if new_expl:
res = '\n~'.join(new_expl)
if item.config.getvalue("assertmode") == "rewrite":
# The result will be fed back a python % formatting
# operation, which will fail if there are extraneous
# '%'s in the string. Escape them here.
res = res.replace("%", "%%")
return res
util._reprcompare = callbinrepr
def pytest_runtest_teardown(item):
util._reprcompare = None
def pytest_sessionfinish(session):
hook = session.config._assertstate.hook
if hook is not None:
hook.session = None
def _load_modules(mode):
"""Lazily import assertion related code."""
global rewrite, reinterpret
from _pytest.assertion import reinterpret
if mode == "rewrite":
from _pytest.assertion import rewrite
def warn_about_missing_assertion(mode):
try:
assert False
except AssertionError:
pass
else:
if mode == "rewrite":
specifically = ("assertions which are not in test modules "
"will be ignored")
else:
specifically = "failing tests may report as passing"
sys.stderr.write("WARNING: " + specifically +
" because assert statements are not executed "
"by the underlying Python interpreter "
"(are you using python -O?)\n")
pytest_assertrepr_compare = util.assertrepr_compare<|fim▁end|> | # this hook is only called when test modules are collected |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
TRANSACTION_STATUS = (
('P', _('pending')),
('F', _('failed')),
('C', _('complete')),
)<|fim▁hole|>
class Transaction(models.Model):
user = models.ForeignKey(User, blank = True, null = True, default = None,
verbose_name = _("user"), help_text = _("user who started transaction"))
description = models.CharField(_("reference description"), max_length = 255, help_text = _("reference description"))
amount = models.FloatField(_("amount"))
currency = models.CharField(_("currency"), max_length = 3)
details = models.CharField(_("details"), max_length = 255, help_text = _("payment details"))
created = models.DateTimeField(auto_now_add = True)
last_modified = models.DateTimeField(auto_now = True)
status = models.CharField(_("status"), max_length = 1, default = 'P')
redirect_after_success = models.CharField(max_length = 255, editable = False)
redirect_on_failure = models.CharField(max_length = 255, editable = False)
def __unicode__(self):
return _("transaction %s " % self.pk)
class Meta:
verbose_name = _("transaction")
ordering = ['-last_modified']<|fim▁end|> | |
<|file_name|>app.module.ts<|end_file_name|><|fim▁begin|>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrainSocketService } from './services/brain-socket.service';
import { StatusComponent } from './status/status.component';
import { EegDataComponent } from './eeg-data/eeg-data.component';
import { ESenseDataComponent } from './e-sense-data/e-sense-data.component';
@NgModule({
declarations: [
AppComponent,
StatusComponent,
EegDataComponent,
ESenseDataComponent,
],
imports: [
BrowserModule,
],<|fim▁hole|> ],
bootstrap: [AppComponent]
})
export class AppModule { }<|fim▁end|> | providers: [
BrainSocketService |
<|file_name|>BaseExample.java<|end_file_name|><|fim▁begin|>package sdk.chat.demo.examples.api;
import io.reactivex.functions.Consumer;
import sdk.guru.common.DisposableMap;
public class BaseExample implements Consumer<Throwable> {
// Add the disposables to a map so you can dispose of them all at one time
protected DisposableMap dm = new DisposableMap();
@Override
public void accept(Throwable throwable) throws Exception {
// Handle exception
}
<|fim▁hole|><|fim▁end|> | } |
<|file_name|>pressure.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import sys
import time
from envirophat import light, weather, motion, analog
def write():
try:
p = round(weather.pressure(),2)
c = light.light()
print('{"light": '+str(c)+', "pressure": '+str(p)+' }')
except KeyboardInterrupt:<|fim▁hole|>write()<|fim▁end|> | pass |
<|file_name|>CircleImpl.cpp<|end_file_name|><|fim▁begin|>/*
* Beautiful Capi generates beautiful C API wrappers for your C++ classes
* Copyright (C) 2015 Petr Petrovich Petrov
*<|fim▁hole|> * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Beautiful Capi 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 Beautiful Capi. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <iostream>
#include "CircleImpl.h"
Example::CircleImpl::CircleImpl() : m_radius(10.0)
{
std::cout << "Circle ctor" << std::endl;
}
Example::CircleImpl::CircleImpl(const CircleImpl& other) : m_radius(other.m_radius)
{
std::cout << "Circle copy ctor" << std::endl;
}
Example::CircleImpl::~CircleImpl()
{
std::cout << "Circle dtor" << std::endl;
}
void Example::CircleImpl::Show() const
{
std::cout << "CircleImpl::Show(), radius = " << m_radius << std::endl;
}
void Example::CircleImpl::SetRadius(double radius)
{
m_radius = radius;
}<|fim▁end|> | * This file is part of Beautiful Capi.
*
* Beautiful Capi is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by |
<|file_name|>freeze.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import
import logging
import re
import pip
from pip.req import InstallRequirement
from pip.req.req_file import COMMENT_RE
from pip.utils import get_installed_distributions
from pip._vendor import pkg_resources
from pip._vendor.packaging.utils import canonicalize_name
from pip._vendor.pkg_resources import RequirementParseError
logger = logging.getLogger(__name__)
def freeze(
requirement=None,
find_links=None, local_only=None, user_only=None, skip_regex=None,
default_vcs=None,
isolated=False,
wheel_cache=None,
skip=()):
find_links = find_links or []
skip_match = None
if skip_regex:
skip_match = re.compile(skip_regex).search
dependency_links = []
for dist in pkg_resources.working_set:
if dist.has_metadata('dependency_links.txt'):
dependency_links.extend(
dist.get_metadata_lines('dependency_links.txt')
)
for link in find_links:
if '#egg=' in link:
dependency_links.append(link)
for link in find_links:
yield '-f %s' % link
installations = {}
for dist in get_installed_distributions(local_only=local_only,
skip=(),
user_only=user_only):
try:
req = pip.FrozenRequirement.from_dist(
dist,
dependency_links
)
except RequirementParseError:
logger.warning(
"Could not parse requirement: %s",
dist.project_name<|fim▁hole|> continue
installations[req.name] = req
if requirement:
# the options that don't get turned into an InstallRequirement
# should only be emitted once, even if the same option is in multiple
# requirements files, so we need to keep track of what has been emitted
# so that we don't emit it again if it's seen again
emitted_options = set()
for req_file_path in requirement:
with open(req_file_path) as req_file:
for line in req_file:
if (not line.strip() or
line.strip().startswith('#') or
(skip_match and skip_match(line)) or
line.startswith((
'-r', '--requirement',
'-Z', '--always-unzip',
'-f', '--find-links',
'-i', '--index-url',
'--pre',
'--trusted-host',
'--process-dependency-links',
'--extra-index-url'))):
line = line.rstrip()
if line not in emitted_options:
emitted_options.add(line)
yield line
continue
if line.startswith('-e') or line.startswith('--editable'):
if line.startswith('-e'):
line = line[2:].strip()
else:
line = line[len('--editable'):].strip().lstrip('=')
line_req = InstallRequirement.from_editable(
line,
default_vcs=default_vcs,
isolated=isolated,
wheel_cache=wheel_cache,
)
else:
line_req = InstallRequirement.from_line(
COMMENT_RE.sub('', line).strip(),
isolated=isolated,
wheel_cache=wheel_cache,
)
if not line_req.name:
logger.info(
"Skipping line in requirement file [%s] because "
"it's not clear what it would install: %s",
req_file_path, line.strip(),
)
logger.info(
" (add #egg=PackageName to the URL to avoid"
" this warning)"
)
elif line_req.name not in installations:
logger.warning(
"Requirement file [%s] contains %s, but that "
"package is not installed",
req_file_path, COMMENT_RE.sub('', line).strip(),
)
else:
yield str(installations[line_req.name]).rstrip()
del installations[line_req.name]
yield(
'## The following requirements were added by '
'pip freeze:'
)
for installation in sorted(
installations.values(), key=lambda x: x.name.lower()):
if canonicalize_name(installation.name) not in skip:
yield str(installation).rstrip()<|fim▁end|> | ) |
<|file_name|>cellbuffer.rs<|end_file_name|><|fim▁begin|>use std::ops::{Index, IndexMut, Deref, DerefMut};
use core::position::{Pos, Size, HasSize};
// I tried really hard to implement Index + IndexMut directly in the trait, but I coudn't get it
// to compile...
pub trait CellAccessor: HasSize {
fn cellvec(&self) -> &Vec<Cell>;
fn cellvec_mut(&mut self) -> &mut Vec<Cell>;
/// Clears `self`, using the given `Cell` as a blank.
fn clear(&mut self, blank: Cell) {
for cell in self.cellvec_mut().iter_mut() {
*cell = blank;
}
}
fn pos_to_index(&self, x: usize, y: usize) -> Option<usize> {
let (cols, rows) = self.size();
if x < cols && y < rows {
Some((cols * y) + x)
} else {
None
}
}
/// Returns a reference to the `Cell` at the given coordinates, or `None` if the index is out of
/// bounds.
///
/// # Examples
///
/// ```no_run
/// use rustty::{Terminal, CellAccessor};
///
/// let mut term = Terminal::new().unwrap();
///
/// let a_cell = term.get(5, 5);
/// ```
fn get(&self, x: usize, y: usize) -> Option<&Cell> {
match self.pos_to_index(x, y) {
Some(i) => self.cellvec().get(i),
None => None,
}
}
/// Returns a mutable reference to the `Cell` at the given coordinates, or `None` if the index
/// is out of bounds.
///
/// # Examples
///
/// ```no_run
/// use rustty::{Terminal, CellAccessor};
///
/// let mut term = Terminal::new().unwrap();
///
/// let a_mut_cell = term.get_mut(5, 5);
/// ```
fn get_mut(&mut self, x: usize, y: usize) -> Option<&mut Cell> {
match self.pos_to_index(x, y) {
Some(i) => self.cellvec_mut().get_mut(i),
None => None,
}
}
}
/// An array of `Cell`s that represents a terminal display.
///
/// A `CellBuffer` is a two-dimensional array of `Cell`s, each pair of indices correspond to a
/// single point on the underlying terminal.
///
/// The first index, `Cellbuffer[y]`, corresponds to a row, and thus the y-axis. The second
/// index, `Cellbuffer[y][x]`, corresponds to a column within a row and thus the x-axis.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CellBuffer {
cols: usize,
rows: usize,
buf: Vec<Cell>,
}
impl CellBuffer {
/// Constructs a new `CellBuffer` with the given number of columns and rows, using the given
/// `cell` as a blank.
pub fn new(cols: usize, rows: usize, cell: Cell) -> CellBuffer {
CellBuffer {
cols: cols,
rows: rows,
buf: vec![cell; cols * rows],
}
}
/// Resizes `CellBuffer` to the given number of rows and columns, using the given `Cell` as
/// a blank.
pub fn resize(&mut self, newcols: usize, newrows: usize, blank: Cell) {
let newlen = newcols * newrows;
let mut newbuf: Vec<Cell> = Vec::with_capacity(newlen);
for y in 0..newrows {
for x in 0..newcols {
let cell = self.get(x, y).unwrap_or(&blank);
newbuf.push(*cell);
}
}
self.buf = newbuf;
self.cols = newcols;
self.rows = newrows;
}
}
impl HasSize for CellBuffer {
fn size(&self) -> Size {
(self.cols, self.rows)
}
}
impl CellAccessor for CellBuffer {
fn cellvec(&self) -> &Vec<Cell> {
&self.buf
}
fn cellvec_mut(&mut self) -> &mut Vec<Cell> {
&mut self.buf
}
}
impl Deref for CellBuffer {
type Target = [Cell];
fn deref<'a>(&'a self) -> &'a [Cell] {
&self.buf
}
}
impl DerefMut for CellBuffer {
fn deref_mut<'a>(&'a mut self) -> &'a mut [Cell] {
&mut self.buf
}
}
impl Index<Pos> for CellBuffer {
type Output = Cell;
fn index<'a>(&'a self, index: Pos) -> &'a Cell {
let (x, y) = index;
self.get(x, y).expect("index out of bounds")
}
}
impl IndexMut<Pos> for CellBuffer {
fn index_mut<'a>(&'a mut self, index: Pos) -> &'a mut Cell {
let (x, y) = index;
self.get_mut(x, y).expect("index out of bounds")
}
}
impl Default for CellBuffer {
/// Constructs a new `CellBuffer` with a size of `(0, 0)`, using the default `Cell` as a blank.
fn default() -> CellBuffer {
CellBuffer::new(0, 0, Cell::default())
}
}
/// A single point on a terminal display.
///
/// A `Cell` contains a character and style.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Cell {
ch: char,
fg: Color,
bg: Color,
attrs: Attr,
}
impl Cell {
/// Creates a new `Cell` with the given `char`, `Color`s and `Attr`.
///
/// # Examples
///
/// ```
/// use rustty::{Cell, Color, Attr};
///
/// let cell = Cell::new('x', Color::Default, Color::Green, Attr::Default);
/// assert_eq!(cell.ch(), 'x');
/// assert_eq!(cell.fg(), Color::Default);
/// assert_eq!(cell.bg(), Color::Green);
/// assert_eq!(cell.attrs(), Attr::Default);
/// ```
pub fn new(ch: char, fg: Color, bg: Color, attrs: Attr) -> Cell {
Cell {
ch: ch,
fg: fg,
bg: bg,
attrs: attrs,
}
}
/// Creates a new `Cell` with the given `char` and default style.
///
/// # Examples
///
/// ```
/// use rustty::{Cell, Color, Attr};
///
/// let mut cell = Cell::with_char('x');
/// assert_eq!(cell.ch(), 'x');
/// assert_eq!(cell.fg(), Color::Default);
/// assert_eq!(cell.bg(), Color::Default);
/// assert_eq!(cell.attrs(), Attr::Default);
/// ```
pub fn with_char(ch: char) -> Cell {
Cell::new(ch, Color::Default, Color::Default, Attr::Default)
}
/// Creates a new `Cell` with the given style and a blank `char`.
///
/// # Examples
///
/// ```
/// use rustty::{Cell, Color, Attr};
///
/// let mut cell = Cell::with_style(Color::Default, Color::Red, Attr::Bold);
/// assert_eq!(cell.fg(), Color::Default);
/// assert_eq!(cell.bg(), Color::Red);
/// assert_eq!(cell.attrs(), Attr::Bold);
/// assert_eq!(cell.ch(), ' ');
/// ```
pub fn with_style(fg: Color, bg: Color, attr: Attr) -> Cell {
Cell::new(' ', fg, bg, attr)
}
/// Returns the `Cell`'s character.
///
/// # Examples
///
/// ```
/// use rustty::Cell;
///
/// let mut cell = Cell::with_char('x');
/// assert_eq!(cell.ch(), 'x');
/// ```
pub fn ch(&self) -> char {
self.ch
}
/// Sets the `Cell`'s character to the given `char`
///
/// # Examples
///
/// ```
/// use rustty::Cell;
///
/// let mut cell = Cell::with_char('x');
/// assert_eq!(cell.ch(), 'x');
///
/// cell.set_ch('y');
/// assert_eq!(cell.ch(), 'y');
/// ```
pub fn set_ch(&mut self, newch: char) -> &mut Cell {
self.ch = newch;
self
}
/// Returns the `Cell`'s foreground `Color`.
///
/// # Examples
///
/// ```
/// use rustty::{Cell, Color, Attr};
///
/// let mut cell = Cell::with_style(Color::Blue, Color::Default, Attr::Default);
/// assert_eq!(cell.fg(), Color::Blue);
/// ```
pub fn fg(&self) -> Color {
self.fg
}
/// Sets the `Cell`'s foreground `Color` to the given `Color`.
///
/// # Examples
///
/// ```
/// use rustty::{Cell, Color, Attr};
///
/// let mut cell = Cell::default();
/// assert_eq!(cell.fg(), Color::Default);
///
/// cell.set_fg(Color::White);
/// assert_eq!(cell.fg(), Color::White);
/// ```
pub fn set_fg(&mut self, newfg: Color) -> &mut Cell {
self.fg = newfg;
self
}
/// Returns the `Cell`'s background `Color`.
///
/// # Examples
///
/// ```
/// use rustty::{Cell, Color, Attr};
///
/// let mut cell = Cell::with_style(Color::Default, Color::Green, Attr::Default);
/// assert_eq!(cell.bg(), Color::Green);
/// ```
pub fn bg(&self) -> Color {
self.bg
}
/// Sets the `Cell`'s background `Color` to the given `Color`.
///
/// # Examples
///
/// ```
/// use rustty::{Cell, Color, Attr};
///
/// let mut cell = Cell::default();
/// assert_eq!(cell.bg(), Color::Default);
///
/// cell.set_bg(Color::Black);
/// assert_eq!(cell.bg(), Color::Black);
/// ```
pub fn set_bg(&mut self, newbg: Color) -> &mut Cell {
self.bg = newbg;
self
}
pub fn attrs(&self) -> Attr {
self.attrs
}
pub fn set_attrs(&mut self, newattrs: Attr) -> &mut Cell {
self.attrs = newattrs;
self
}
}
impl Default for Cell {
/// Constructs a new `Cell` with a blank `char` and default `Color`s.
///
/// # Examples
///
/// ```
/// use rustty::{Cell, Color};
///
/// let mut cell = Cell::default();
/// assert_eq!(cell.ch(), ' ');
/// assert_eq!(cell.fg(), Color::Default);
/// assert_eq!(cell.bg(), Color::Default);
/// ```
fn default() -> Cell {
Cell::new(' ', Color::Default, Color::Default, Attr::Default)
}
}
/// The color of a `Cell`.
///
/// `Color::Default` represents the default color of the underlying terminal.
///
/// The eight basic colors may be used directly and correspond to 0x00..0x07 in the 8-bit (256)
/// color range; in addition, the eight basic colors coupled with `Attr::Bold` correspond to
/// 0x08..0x0f in the 8-bit color range.
///
/// `Color::Byte(..)` may be used to specify a color in the 8-bit range.
///
/// # Examples
///
/// ```
/// use rustty::Color;
///
/// // The default color.
/// let default = Color::Default;
///
/// // A basic color.
/// let red = Color::Red;
///
/// // An 8-bit color.
/// let fancy = Color::Byte(0x01);
///
/// // Basic colors are also 8-bit colors (but not vice-versa).
/// assert_eq!(red.as_byte(), fancy.as_byte())
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Color {
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
Byte(u8),
Default,
}
impl Color {
/// Returns the `u8` representation of the `Color`.
pub fn as_byte(&self) -> u8 {
match *self {
Color::Black => 0x00,
Color::Red => 0x01,
Color::Green => 0x02,
Color::Yellow => 0x03,
Color::Blue => 0x04,
Color::Magenta => 0x05,
Color::Cyan => 0x06,
Color::White => 0x07,
Color::Byte(b) => b,
Color::Default => panic!("Attempted to cast default color to u8"),
}
}
}
/// The attributes of a `Cell`.
///
/// `Attr` enumerates all combinations of attributes a given style may have.<|fim▁hole|>/// # Examples
///
/// ```
/// use rustty::Attr;
///
/// // Default attribute.
/// let def = Attr::Default;
///
/// // Base attribute.
/// let base = Attr::Bold;
///
/// // Combination.
/// let comb = Attr::UnderlineReverse;
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Attr {
Default = 0b000,
Bold = 0b001,
Underline = 0b010,
BoldUnderline = 0b011,
Reverse = 0b100,
BoldReverse = 0b101,
UnderlineReverse = 0b110,
BoldReverseUnderline = 0b111,
}<|fim▁end|> | ///
/// `Attr::Default` represents no attribute.
/// |
<|file_name|>arachnid.cpp<|end_file_name|><|fim▁begin|>// license:BSD-3-Clause
// copyright-holders:Jim Stolis
/*
Arachnid - English Mark Darts
Driver by Jim Stolis.
--- Technical Notes ---
Name: English Mark Darts
Company: Arachnid, Inc.
Year: 1987/88/89/90
--- Hardware ---
A 6809 CPU (U3) is clocked by a 556 (U2) circuit with 3 Pin addressing decoding via a 74LS138 (U14)
Program ROM is a 27256 (U15)
Two 6821 PIAs (U4/U17) are used for I/O
Video is processed via a TMS9118 (U11) with two TMS4416 (U12/U13) as RAM
Main RAM is a 2K 6116 (U23) chip
Sound is generated via a PTM 6840 (U16) directly to an amplified speaker
--- Target Interface Board ---
The target interface board is used to combine 33 conductors from the switch matrix
into 16 conductors. The middle 13 pin connector is common to all switches.
3 connectors and their labels
EFBHDACGH NMPLMNJOMIKOP EBACFDCEAHB
Switch Matrix Table
Score Single Double Triple
1 DN EN FN
2 AL BL CL
3 AN BN CN
4 DL EL FL
5 AP BP CP
6 GL HL GP
7 DO EO FO
8 GI HI GM
9 AO BO CO
10 AI BI CI
11 AK BK CK
12 DP EP FP
13 AM BM CM
14 GK HK GO
15 GJ HJ GN
16 AJ BJ CJ
17 DM EM FM
18 DI EI FI
19 DJ EJ FJ
20 DK EK FK
Bull -- HM --
TODO:
- Dip Switches (Controls credits per coin), Currently 2 coins per credit
- Test Mode Won't Activate
- Layout with Lamps
- Default monitor is yellow/amber, no colour (board does have an extra
composite-out connector though, allowing a standard tv)
*/
#include "emu.h"
#include "cpu/m6809/m6809.h"
#include "machine/6821pia.h"
#include "machine/ram.h"
#include "machine/6840ptm.h"
#include "video/tms9928a.h"
#include "sound/speaker.h"
#define SCREEN_TAG "screen"
#define M6809_TAG "u3"
#define TMS9118_TAG "u11"
#define PIA6821_U4_TAG "u4"
#define PIA6821_U17_TAG "u17"
#define PTM6840_TAG "u16"
#define SPEAKER_TAG "speaker"
class arachnid_state : public driver_device
{
public:
arachnid_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag),
m_maincpu(*this, M6809_TAG),
m_pia_u4(*this, PIA6821_U4_TAG),
m_pia_u17(*this, PIA6821_U17_TAG),
m_speaker(*this, SPEAKER_TAG)
{ }
required_device<cpu_device> m_maincpu;
required_device<pia6821_device> m_pia_u4;
required_device<pia6821_device> m_pia_u17;
required_device<speaker_sound_device> m_speaker;
virtual void machine_start() override;
DECLARE_READ8_MEMBER( pia_u4_pa_r );
DECLARE_READ8_MEMBER( pia_u4_pb_r );
DECLARE_READ_LINE_MEMBER( pia_u4_pca_r );
DECLARE_READ_LINE_MEMBER( pia_u4_pcb_r );
DECLARE_WRITE8_MEMBER( pia_u4_pa_w );
DECLARE_WRITE8_MEMBER( pia_u4_pb_w );
DECLARE_WRITE_LINE_MEMBER( pia_u4_pca_w );
DECLARE_WRITE_LINE_MEMBER( pia_u4_pcb_w );
DECLARE_READ8_MEMBER( pia_u17_pa_r );
DECLARE_READ_LINE_MEMBER( pia_u17_pca_r );
DECLARE_WRITE8_MEMBER( pia_u17_pb_w );
DECLARE_WRITE_LINE_MEMBER( pia_u17_pcb_w );
DECLARE_WRITE8_MEMBER(ptm_o1_callback);
UINT8 read_keyboard(int pa);
};
/***************************************************************************
MEMORY MAPS
***************************************************************************/
/*-------------------------------------------------
ADDRESS_MAP( arachnid_map )
-------------------------------------------------*/
static ADDRESS_MAP_START( arachnid_map, AS_PROGRAM, 8, arachnid_state )
AM_RANGE(0x0000, 0x1fff) AM_RAM
AM_RANGE(0x2000, 0x2007) AM_DEVREADWRITE(PTM6840_TAG, ptm6840_device, read, write)
AM_RANGE(0x4004, 0x4007) AM_DEVREADWRITE(PIA6821_U4_TAG, pia6821_device, read, write)
AM_RANGE(0x4008, 0x400b) AM_DEVREADWRITE(PIA6821_U17_TAG, pia6821_device, read, write)
AM_RANGE(0x6000, 0x6000) AM_DEVWRITE(TMS9118_TAG, tms9928a_device, vram_write)
AM_RANGE(0x6002, 0x6002) AM_DEVWRITE(TMS9118_TAG, tms9928a_device, register_write)
AM_RANGE(0x8000, 0xffff) AM_ROM AM_REGION(M6809_TAG, 0)
ADDRESS_MAP_END
/***************************************************************************
INPUT PORTS
***************************************************************************/
/*-------------------------------------------------
INPUT_PORTS( arachnid )
-------------------------------------------------*/
static INPUT_PORTS_START( arachnid )
PORT_START("PA0-0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Q) PORT_CHAR('Q') // SELECT
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-1")
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_W) PORT_CHAR('W') // PLAYER
PORT_BIT( 0xfd, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-2")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN1 ) // COIN
PORT_BIT( 0xfb, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-3")
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_T) PORT_CHAR('T') // TEST
PORT_BIT( 0xf7, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-4")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-5")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-6")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA0-7")
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("SW1")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Z) PORT_CHAR('Z') PORT_TOGGLE
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("SW2")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_X) PORT_CHAR('X') PORT_TOGGLE
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
// Matrix Switch Part I
PORT_START("PA1-0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_G) PORT_CHAR('G')
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-1")
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_H) PORT_CHAR('H')
PORT_BIT( 0xfd, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-2")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_E) PORT_CHAR('E')
PORT_BIT( 0xfb, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-3")
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F) PORT_CHAR('F')
PORT_BIT( 0xf7, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-4")
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_C) PORT_CHAR('C')
PORT_BIT( 0xef, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-5")
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_D) PORT_CHAR('D')
PORT_BIT( 0xdf, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-6")
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_A) PORT_CHAR('A')
PORT_BIT( 0xbf, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PA1-7")
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_B) PORT_CHAR('B')
PORT_BIT( 0x7f, IP_ACTIVE_LOW, IPT_UNUSED )
// Matrix Switch Part II
PORT_START("PB1-0")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_J) PORT_CHAR('J')
PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-1")
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_I) PORT_CHAR('I')
PORT_BIT( 0xfd, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-2")
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_L) PORT_CHAR('L')
PORT_BIT( 0xfb, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-3")
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_K) PORT_CHAR('K')
PORT_BIT( 0xf7, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-4")
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_N) PORT_CHAR('N')
PORT_BIT( 0xef, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-5")
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_M) PORT_CHAR('M')
PORT_BIT( 0xdf, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-6")
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_P) PORT_CHAR('P')
PORT_BIT( 0xbf, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("PB1-7")
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_O) PORT_CHAR('O')
PORT_BIT( 0x7f, IP_ACTIVE_LOW, IPT_UNUSED )
INPUT_PORTS_END
/***************************************************************************
DEVICE CONFIGURATION
***************************************************************************/
/*-------------------------------------------------
ptm6840_interface ptm_intf
-------------------------------------------------*/
WRITE8_MEMBER(arachnid_state::ptm_o1_callback)
{
m_speaker->level_w(data);
}
UINT8 arachnid_state::read_keyboard(int pa)
{
int i;
UINT8 value;
static const char *const keynames[3][8] =
{
{ "PA0-0", "PA0-1", "PA0-2", "PA0-3", "PA0-4", "PA0-5", "PA0-6", "PA0-7" },
{ "PA1-0", "PA1-1", "PA1-2", "PA1-3", "PA1-4", "PA1-5", "PA1-6", "PA1-7" },
{ "PB1-0", "PB1-1", "PB1-2", "PB1-3", "PB1-4", "PB1-5", "PB1-6", "PB1-7" }
};
for (i = 0; i < 8; i++)
{
value = ioport(keynames[pa][i])->read();
if (value != 0xff)
{
if (value == 0xff - (1 << i))
return value;
else
return value - (1 << i);
}
}
return 0xff;
}
READ8_MEMBER( arachnid_state::pia_u4_pa_r )
{
// Pulses from Switch Matrix Part I
// PA0 - G
// PA1 - H
// PA2 - E
// PA3 - F
// PA4 - C
// PA5 - D
// PA6 - A
// PA7 - B
UINT8 data = 0xff;
data &= read_keyboard(1);
return data;
}
READ8_MEMBER( arachnid_state::pia_u4_pb_r )
{
// Pulses from Switch Matrix Part II
// PB0 - J
// PB1 - I
// PB2 - L
// PB3 - K
// PB4 - N
// PB5 - M
// PB6 - P
// PB7 - O
UINT8 data = 0xff;
data &= read_keyboard(2);
return data;
}
READ_LINE_MEMBER( arachnid_state::pia_u4_pca_r )
{
// CA1 - SW1 Coin In (Coin Door)
UINT8 data = 1;
data &= ioport("SW1")->read();
return data;
}
READ_LINE_MEMBER( arachnid_state::pia_u4_pcb_r )
{
// CB1 - SW2 Test Mode (Coin Door)
UINT8 data = 1;
data &= ioport("SW2")->read();
return data;
}
READ8_MEMBER( arachnid_state::pia_u17_pa_r )
{
// PA0 - Select
// PA1 - Player Change
// PA2 - Coin
// PA3 - Test
// PA4 thru PA7 - DIP SW1
UINT8 data = 0xff;
data &= read_keyboard(0);
return data;
}
READ_LINE_MEMBER( arachnid_state::pia_u17_pca_r )
{
// CA1 - 1000 HZ Input
UINT8 data = 1;
return data;
}
WRITE8_MEMBER( arachnid_state::pia_u4_pa_w )
{
// PA0 thru PA7 Pulses to Switch Matrix Part I
}
WRITE8_MEMBER( arachnid_state::pia_u4_pb_w )
{
// PA0 thru PA7 Pulses to Switch Matrix Part II
}
WRITE_LINE_MEMBER( arachnid_state::pia_u4_pca_w )
{
// CA1 - Remove Darts Lamp
}
WRITE_LINE_MEMBER( arachnid_state::pia_u4_pcb_w )
{
// CB2 - Throw Darts Lamp
}
WRITE8_MEMBER( arachnid_state::pia_u17_pb_w )
{
// PB0 - Select Lamp
// PB1 - Player Change Lamp
// PB2 - Not Used
// PB3 - Not Used
// PB4 - Not Used
// PB5 - Not Used
// PB6 - Not Used
// PB7 - N/C
}
WRITE_LINE_MEMBER( arachnid_state::pia_u17_pcb_w )
{
// CB2 - Target Lamp
}
/***************************************************************************
MACHINE INITIALIZATION
***************************************************************************/
/*-------------------------------------------------<|fim▁hole|>void arachnid_state::machine_start()
{
}
/***************************************************************************
MACHINE DRIVERS
***************************************************************************/
/*-------------------------------------------------
MACHINE_CONFIG_START( arachnid, arachnid_state )
-------------------------------------------------*/
static MACHINE_CONFIG_START( arachnid, arachnid_state )
// basic machine hardware
MCFG_CPU_ADD(M6809_TAG, M6809, XTAL_1MHz)
MCFG_CPU_PROGRAM_MAP(arachnid_map)
// devices
MCFG_DEVICE_ADD(PIA6821_U4_TAG, PIA6821, 0)
MCFG_PIA_READPA_HANDLER(READ8(arachnid_state, pia_u4_pa_r))
MCFG_PIA_READPB_HANDLER(READ8(arachnid_state, pia_u4_pb_r))
MCFG_PIA_READCA1_HANDLER(READLINE(arachnid_state, pia_u4_pca_r))
MCFG_PIA_READCB1_HANDLER(READLINE(arachnid_state, pia_u4_pcb_r))
MCFG_PIA_WRITEPA_HANDLER(WRITE8(arachnid_state, pia_u4_pa_w))
MCFG_PIA_WRITEPB_HANDLER(WRITE8(arachnid_state, pia_u4_pb_w))
MCFG_PIA_CA2_HANDLER(WRITELINE(arachnid_state, pia_u4_pca_w))
MCFG_PIA_CB2_HANDLER(WRITELINE(arachnid_state, pia_u4_pcb_w))
MCFG_DEVICE_ADD(PIA6821_U17_TAG, PIA6821, 0)
MCFG_PIA_READPA_HANDLER(READ8(arachnid_state, pia_u17_pa_r))
MCFG_PIA_READCA1_HANDLER(READLINE(arachnid_state, pia_u17_pca_r))
MCFG_PIA_WRITEPB_HANDLER(WRITE8(arachnid_state, pia_u17_pb_w))
MCFG_PIA_CB2_HANDLER(WRITELINE(arachnid_state, pia_u17_pcb_w))
// video hardware
MCFG_DEVICE_ADD( TMS9118_TAG, TMS9118, XTAL_10_738635MHz / 2 )
MCFG_TMS9928A_VRAM_SIZE(0x4000)
MCFG_TMS9928A_OUT_INT_LINE_CB(INPUTLINE(M6809_TAG, INPUT_LINE_IRQ0))
MCFG_TMS9928A_SCREEN_ADD_NTSC( SCREEN_TAG )
MCFG_SCREEN_UPDATE_DEVICE( TMS9118_TAG, tms9118_device, screen_update )
// sound hardware
MCFG_SPEAKER_STANDARD_MONO("mono")
MCFG_SOUND_ADD("speaker", SPEAKER_SOUND, 0)
MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0)
MCFG_DEVICE_ADD(PTM6840_TAG, PTM6840, 0)
MCFG_PTM6840_INTERNAL_CLOCK(XTAL_8MHz / 4)
MCFG_PTM6840_EXTERNAL_CLOCKS(0, 0, 0)
MCFG_PTM6840_OUT0_CB(WRITE8(arachnid_state, ptm_o1_callback))
MACHINE_CONFIG_END
/***************************************************************************
ROMS
***************************************************************************/
ROM_START( arac6000 )
ROM_REGION( 0x8000, M6809_TAG, 0 )
ROM_LOAD( "01-0140-6300-v2.7-19910208.u15", 0x0000, 0x8000, CRC(f1c4412d) SHA1(6ff9a8f25f315c2df5c0785043521d036ec0964e) )
ROM_END
/***************************************************************************
SYSTEM DRIVERS
***************************************************************************/
/* YEAR NAME PARENT COMPAT MACHINE INPUT INIT COMPANY FULLNAME */
GAME( 1990, arac6000, 0, arachnid, arachnid, driver_device, 0, ROT0, "Arachnid", "Super Six Plus II English Mark Darts", MACHINE_MECHANICAL | MACHINE_NOT_WORKING )<|fim▁end|> | MACHINE_START( arachnid )
-------------------------------------------------*/
|
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from tornado.web import RequestHandler
class BaseHandler(RequestHandler):
def initialize(self):
_settings = self.application.settings
<|fim▁hole|> self.log = _settings["log"]<|fim▁end|> | self.db = self.application.db
#self.redis = _settings["redis"] |
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|>from django.utils import translation
from django.conf import settings
from froide.celery import app as celery_app
from froide.foirequest.models import FoiRequest
from .models import FoiRequestFollower
from .utils import run_batch_update<|fim▁hole|>
@celery_app.task
def update_followers(request_id, update_message, template=None):
translation.activate(settings.LANGUAGE_CODE)
try:
foirequest = FoiRequest.objects.get(id=request_id)
except FoiRequest.DoesNotExist:
return
followers = FoiRequestFollower.objects.filter(request=foirequest, confirmed=True)
for follower in followers:
FoiRequestFollower.objects.send_update(
follower.user or follower.email,
[
{
"request": foirequest,
"unfollow_link": follower.get_unfollow_link(),
"events": [update_message],
}
],
batch=False,
)
@celery_app.task
def batch_update():
return run_batch_update()<|fim▁end|> | |
<|file_name|>filterGroup.service.ts<|end_file_name|><|fim▁begin|>import { Observable } from 'rxjs';
import { each, filter, has, isUndefined, isFunction } from 'lodash';
import { IFilter, Filter } from '../filter';
export interface IFilterGroupSettings<TItemType> {
label: string;
type: string;
options: IFilterOption<TItemType>[];
serialize?: {( activeOption: IFilterOption<TItemType> ): any};
}
export interface IFilterOption<TItemType> {
active?: boolean;
label: string;
type?: string;
value?: any;
predicate: { (item: TItemType): boolean };
serialize?: {(): any};
}
interface IConfiguredFilterOption<TItemType> extends IFilterOption<TItemType> {
count?: number;
}<|fim▁hole|> label: string;
type: string;
options: IFilterOption<TItemType>[];
activeOption: IFilterOption<TItemType>;
setActiveOption(index: number): void;
setOptionCounts(counts: number[]): void;
}
export class FilterGroup<TItemType> extends Filter<TItemType, any> implements IFilterGroup<TItemType> {
label: string;
type: string;
options: IFilterOption<TItemType>[];
settings: IFilterGroupSettings<TItemType>;
private _activeOption: IFilterOption<TItemType>;
constructor(settings: IFilterGroupSettings<TItemType>) {
super();
this.settings = settings;
this.label = settings.label;
this.type = settings.type != null ? settings.type : settings.label;
this.initOptions();
}
initOptions():void {
this.options = this.settings.options;
this.activeOption = this.setDefaultOption();
each(this.options, (option: IFilterOption<TItemType>): void => {
if (isUndefined(option.type)) {
option.type = option.label;
}
option.type = (option.type || '').toString().toLowerCase();
});
}
get activeOption(): IFilterOption<TItemType> {
return this._activeOption;
}
set activeOption(value: IFilterOption<TItemType>) {
this._activeOption = value;
this.value$.next(value);
}
private setDefaultOption(): IFilterOption<TItemType> {
let defaultOption: IFilterOption<TItemType> = this.options[0];
each(this.options, (item: IFilterOption<TItemType>): void => {
if (item.active != null && item.active === true) {
defaultOption = item;
}
});
return defaultOption;
}
predicate = (item: any): boolean => {
return this.activeOption.predicate(item);
}
serialize(): Observable<any> {
return this.value$.asObservable().map(activeOption => {
if (isFunction(this.settings.serialize)) {
return this.settings.serialize(activeOption);
}
if (isFunction(activeOption.serialize)) {
return activeOption.serialize();
}
return activeOption.value;
});
}
setActiveOption(index: number): void {
if (index >= 0 && index < this.options.length) {
this.activeOption = this.options[index];
}
}
// filter counts not yet supported in the new card container
setOptionCounts(counts: number[]): void {
each(this.options, (option: IConfiguredFilterOption<TItemType>): void => {
if (has(counts, option.type)) {
option.count = counts[option.type];
}
});
}
updateOptionCounts<TDataType>(filteredDataSet: TDataType[]): void {
each(this.options, (option: IConfiguredFilterOption<TItemType>): void => {
option.count = filter(filteredDataSet, option.predicate.bind(option)).length;
});
}
}<|fim▁end|> |
export interface IFilterGroup<TItemType> extends IFilter<TItemType, any> { |
<|file_name|>Python_tutorial.py<|end_file_name|><|fim▁begin|># PPPPPPPP
# PP PP t hh
# PP - PP tt hh
# PP PP yy - yy tttttttt hh hhhh ooooooo nn nnnnn --------------
# PPPPPPP yy yy tt hhh hh oo - oo nnn nn -------------
# PP -- yy yy - tt - hh - hh oo - oo nn - nn -------------
# PP ------- yyy -- tt - hh - hh oo - oo nn - nn -------------
# PP -------- yy --- tt - hh - hh oo - oo nn - nn -------------
# PP ------- yy ----- tt - hh - hh oo - oo nn - nn -------------
# PP ----- yy ------- tt hh - hh ooooooo nn - nn -------------
# <== коментарий
input('Press \'Enter\' to exit') # Задержка вывода консоли
"""> python -m idlelib.idle """ # запуск IDLE из командный строки для текущей папки
"""> cd 1D\Python\ """
# pip => python install packeges
"""
pip --proxy http://192.168.1.37:2718
pip install --proxy=http://192.168.1.37:2718 package
pip install --proxy=http://192.168.1.37:2718 xlwings # exl
python get-pip.py --proxy="http://192.168.1.37:2718"
"""
# Run Python versions
"""
C:\Python33\python
py
py -2
py -3.1
"""
# PART 1 Getting Started
# Module Imports and Reloads
import script1 # one time import file
reload(script1) # reload scripts
import imp
imp.reload()
from imp import reload
reload(module)
script1.X # > Spam!
from script1 import X # recommend always using import instead of from
X # > Spam!
exec(open('script1').read()) # Run Module Files (код запущенного модуля вставляется в код, так он может перезаписать старые значения)
# PART 2 Types and Operations
# CHAPTER 4 Introducing Python Object Types
# Python's Core Data Types
"""
#Object type
Numbers 1234, 3.1415, 3+4j, 0b111, Decimal(), Fraction()
Strings 'spam', "Bob's", b'a\x01c', u'sp\xc4m'
Lists [1, [2, 'three'], 4.5], list(range(10))
Dictionaries {'food': 'spam', 'taste': 'yum'}, dict(hours=10)
Tuples (1, 'spam', 4, 'U'), tuple('spam'), namedtuple
Files open('eggs.txt'), open(r'C:\ham.bin', 'wb')
Sets set('abc'), {'a', 'b', 'c'}
Other core types Booleans, types, None
Program unit types Functions, modules, classes
Implementation-related types Compiled code, stack tracebacks
"""
# Numbers
print(3.1415 * 2) # => 6.283
123 + 222 # => 345
1.5 * 4 # => 6.0
2 ** 100 # => 126765060022~~~
len(str(2 ** 1000000)) # => 301030 How many digits in really BIG number
import math
math.pi # => 3.141592653589793
math.sqrt(85) # => 9.219544457292887
import random
random.random() # => 0.7335334012811705
random.choice([1, 2, 3, 4]) # => 3
# Strings
# Sequence Operations
S = 'Spam'
len(S) # => 4
S[0] # => 'S'
S[1] # => 'p'
S[-1] # => 'm'
S[len(S)-1] # => 'm' Negative indexing, the hard way
S[-2] # => 'a'
S[1:3] # => 'pa'
S[1:] # => 'pam' [1:len(S)]
S[0:3] # => 'Spa'
S[:3] # => 'Spa' [0:3]
S[:-1] # => 'Spa' [0:-1]
S[:] # => 'Spam' [0:len(S)]
S + 'xyz' # => 'Spamxyz' Concatenation
S * 4 # => 'SpamSpamSpamSpam' Repetition
# Immutability
S[0] = 'z' # => Error
S = 'z' + S[1:]
S # => 'zpam'
S.find('pa') # => 1
S.replace('pa', 'XYZ') # => 'zXYZm'
S # => 'zpam'
line = 'aaa,bbb,ccccc,dd\n'
line.split(',') # => ['aaa', 'bbb', 'ccccc', 'dd\n']
line.rstrip() # => 'aaa,bbb,ccccc,dd'
line.rstrip().split(',') # => ['aaa', 'bbb', 'ccccc', 'dd']
S.upper() # => ZPAM
S.isalpha() # => True
S.isdigit() # => False
S = 'shrubery'
L = list(S)
L # => ['s', 'h', 'r', 'u', 'b', 'b', 'e', 'r', 'y']
L[1] = 'c'
''.join(L) # => 'scrubbery'
B = bytearray(b'spam')
B.extend(b'eggs')
B # => bytearray(b'spameggs')
B.decode() # => 'spameggs'
# Formatting
'%s, eggs, and %s' % ('spam', 'SPAM!') # => 'spam, eggs, and SPAM!' #
'{0}, eggs, and {1}'.format('spam', 'SPAM!') # => 'spam, '
'{}, eggs, and {}'.format('sapm', 'SPAM!') # => 'spam, eggs, and SPAM!'
# numeric reports
'{:,.2f}'.format(296999.2567) # => '296,999.26' # Separators, decimal digits
'%.2f | %+05d' % (3.14159, -42) # => '3.14 | -0042'
# Getting Help
dir(S)
help(S.replace)
help(S)
# data type str, list, dict
# Other Ways to Code Strings
S = 'A\nB\tC'
# \n is end-of-line
# \t is tab
len(S) # => 5 # Each stands for just one character
ord('\n') # => 10 # binary value in ASCII
S = 'A\0B\0C'
len(S) # => 5
S # => 'A\x00B\x00C' # Non-printables are displayed as \xNN hex escapes
msg = """
aaaaaaaaaaaaa
bbb'''bbbbbbb""bbbbbb'bbb
ccccccccccc
"""
msg # => '\aaaaaaaaaaaaa\nbbb\'\'\'bbbbbbb""bbbbbb\'bbb\nccccccccccc\n'
# raw string literal
r'C:\text\new'
# Unicode Strings
'sp\xc4m' # => 'spÄm' # normal str string are Unicode text
b'a\xo1c' # => b'a\x01c' # bytes string are byte-based data
u'sp\u00c4m' # => 'spÄm' # The 2.X Unicode literal works in 3.3+: just str
'spam'.encode('utf8') # => b'spam'
'spam'.encode('utf16') # => b'\xff\xfes\x00p\x00a\x00m\x00'
'spam'.encode('ASCII') # => b'spam'
'sp\xc4\u00c4\U000000c4m' # => 'spÄÄÄm'
'x' + b'y'.decode()
'x'.encode() + b'y'
# Pattern Matching
import re
match = re.match('Hello[ \t]*(.*)world', 'Hello Python world')
match.group(1) # => 'Python '
match = re.match('[/:](.*)[/:](.*)[/:](.*)', '/usr/home:lumberjack')
match.groups() # => ('usr', 'home', 'lumberjack')
re.split('[/:]', '/usr/home:lumberjack') # => ['', 'usr', 'home', 'lumberjack']
a = 0
# Lists
# Sequence Operations
L = [123, 'spam', 1.23]
len(L) # => 3
L[0] # => 123
L[:-1] # => [123, 'spam']
L = [4, 5, 6] # => [123, 'spam', 1.23, 4, 5, 6]
L * 2 # => [123, 'spam', 1.23, 123, 'spam', 1.23]
L # => [123, 'spam', 1.23]
# Type-Specific Operations
L.append('NI')
L # => [123, 'spam', 1.23, 'NI']
L.pop(2) # => 1.23
L # => [123, 'spam', 'NI']
M = ['bb', 'aa', 'cc']
M.sort()
M # => ['aa', 'bb', 'cc']
M.reverse()
M # => ['cc', 'bb', 'aa']
# Nesting
M = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
M # => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
M[1] # => [4, 5, 6]
M[1][2] # => 6
# Comprehensions
col2 = [row[1] for row in M] # Collect the items in column 2
col2 # => [2, 5, 8]
[row[1] + 1 for row in M] # => [3, 6, 9] # Add 1 to each item in column 2
[row[1] for row in M if row[1] % 2 == 0] # => [2, 8] # Filter out odd items
diag = [M[i][i] for i in [0, 1, 2]] # Collect a diagonal from matrix
diag # => [1, 5, 9]
doubles = [c * 2 for c in 'spam'] # => Reapeat characters in string
doubles # => ['ss', 'pp', 'aa', 'mm']
list(range(4)) # => [0, 1, 2, 3]
list(range(-6, 7, 2)) # => [-6, -4, -2, 0, 2, 4, 6]
[[x ** 2, x ** 3] for x in range(4)] # => [[0, 0], [1, 1], [4, 8], [9, 27]]
[[x, x /2, x * 2] for x in range(-6, 7, 2) if x > 0] # => [[2, 1.0, 4], [4, 2.0, 8], [6, 3.0, 12]]
G = (sum(row) for row in M) # Create a generator of row sums
next(G) # => 6
next(G) # => 15 # Run the iteration prorocol next()
list(map(sum, M)) # => [6, 15, 24] # Map sum over items in M
# Dictionaries
# Mapping Operations
D = {'food': 'Spam', 'quantity': 4, 'color': 'pink'}
D['food'] # => 'Spam'
D['quantity'] += 1 # add 1 to 'quantity' value
D # => {'color': 'pink', 'food': 'Spam', 'quantity': 5}
D = {}
D['name'] = 'Bob'
D['job'] = 'dev'
D['age'] = 40
D # => {'name': 'Bob', 'age': 40, 'job': 'dev'}
print(D['name']) # => Bob
bob1 = dict(name='Bob', job='dev', age=40)
bob1 # => {'name': 'Bob', 'age': 40, 'job': 'dev'}
bob2 = dict(zip(['name', 'job', 'age'], ['Bob', 'dev', 40])) # Zipping
bob2 # => {'name': 'Bob', 'age': 40, 'job': 'dev'}
# Nesting Revisited
rec = {'name':{'first': 'Bob', 'last': 'Smith'},
'jobs': ['dev', 'mgr'],
'age' : 40.5}
rec['name'] # => {'last': 'Smith', 'first': 'Bob'}
rec['name']['last'] # => 'Smith'
rec['jobs'] # => ['dev', 'mgr']
rec['jobs'][-1] # => 'mgr'
rec['jobs'].append('janitor')
rec # => {'jobs': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first': 'Bob'}, 'age': 40.5}
# Sorting Keys:for loops
D = {'a': 1, 'b':2, 'c':3}
D # => {'b': 2, 'c': 3, 'a': 1}
Ks = list(D.keys())
Ks # => ['b', 'c', 'a']
Ks.sort()
Ks # => ['a', 'b', 'c']
for key in Ks:
print(key, '=>', D[key]) # => a => 1
# b => 2
# c => 3
for key in sorted(D):
print(key, '=>', D[key]) # => a => 1
# b => 2
# c => 3
# Tuples
T = (1, 2, 3, 4)
len(T) # => 4
T + (5, 6) # => (1, 2, 3, 4, 5, 6)
T[0] # => 1
T.index(4) # => 3
T.count(4) # => 1
T[0] = 2 # => ...error...
T = (2, ) + T[1:]
T # => (2, 2, 3, 4)
# Files
f = open('data.txt', 'w')
f.write('Hello\n') # => 6
f.write('world\n') # => 6
F.close()
# Binary Bytes Files
import struct
packed = struct.pack('>i4sh', 7, b'spam', 8)
packed # => b'\x00\x00\x00\x07spam\x00\x08'
file = open('data.bin', 'wb')
file.write(packed) # => 10
file.close()
data = open('data.bin', 'rb').read()
data # => b'\x00\x00\x00\x07spma\x00\x08'
data[4:8] # => b'spma'
list(data) # => [0, 0, 0, 7, 115, 112, 109, 97, 0, 8]
struct.unpack('>i4sh', data) # => (7, b'spma', 8)
# Unicode Text Files
S = 'sp\xc4m'
S # => 'spÄm'
S[2] # => 'Ä'
file = open('unidata.txt', 'w', encoding='utf-8')
file.write(S) # => 4
file.close()
text = open('unidata.txt',encoding='utf-8').read()
text # => 'spÄm'
len(text) # => 4
# Other Core Types
import decimal
d = decimal.Decimal('3.141')
d + 1 # => Decimal('4.141')
from fractions import Fraction
f = Fraction(2, 3)
f + 1 # => Fraction(5, 3)
1 > 2, 1 < 2 # => (False, True)
bool('spam') # => True
# User-Defined Classes
class Worker:
def __init__(self, name, pay):
self.name = name
self.pay = pay
def lastName(self):
return self.name.split()[-1]
def giveRaise(self, percent):
self.pay *= (1.0 + percent)
bob = Worker('Bob Smith', 50000)
sue = Worker('Sue Jones', 60000)
bob.lastName() # => 'Smith'
sue.lastName() # => 'Jones'
sue.giveRaise(.1)
sue.pay # => 66000.0
# CHAPTER 5 Numeric Types
# Numeric Type Basics
# Python Expression Operators
yield x # Generator function send protocol
lambda args: expression # Anonymous function generation
x if y else z # Ternary selection (x is evaluted only if y is true)
x or y # Logical OR (y is evaluted only if x if false)
x and y # Logical AND (y is evaluted only)
not x # Logical negation
x in y,x not in y # Membership (iterables, sets)
x is y, x is not y # Object identity tests
x < y, x <= y, x > y, x >= y # Magnitude comparison, set subset and superset;
x == y, x != y # Value equality ooperators
x | y # Bitwise OR, set union
x ^ y # Bitwise XOR, set symmetric difference
x & y # Bitwise AND, set intersection
x << y, x >> y # Shift x left or right by y bits
x + y # Addition, concatenation
x - y # Subtraction, set difference
x * y # Multilication, repetition
x % y # Remainder, format
x / y, x // y # Division: true and floor
-x, +x # Negation, identity
~x # Bitwise NOT (inversion)
x ** y # Power (exponentiation)
x[i] # Indexing (sequence, mapping, others)
x[i:j:k] # Slicing
x(...) # Call (function, method, calss, other callable)
a.attr # Attribute reference
(...) # Tulpe, expression, generator expression
[...] # List, list comprehension
{...} # Dictionary, set, set and dictionary comprehensions
# Numbers in Action
# Comparisons: Normal and Chained
1.1 + 2.2 == 3.3 # => False
1.1 + 2.2 # => 3.3000000000000003
int(1.1 + 2.2) == int(3.3) # => True
# Floor versus truncation
import math
math.floor(2.5) # => 2
math.floot(-2.5) # => -3
math.trunc(2.5) # => 2
math.trunc(-2.5) # => -2
# Complex Numbers
1j * 1J # => (-1+0j)
2 + 1j * 3 # => (2+3j)
# Hex, Octal, Binary: Literals and Conversions
oct(64), hex(64), bin(64) # => ('0o100', '0x40', '0b1000000')
64, 0o100, 0x40, 0b1000000 # => (64, 64, 64, 64)
int('64'), int('100', 8), int('40', 16), int('1000000', 2) # => (64, 64, 64, 64)
int('0x40', 16), int('0b1000000', 2) # => (64, 64)
eval('64'), eval('0o100'), eval('0x40'), eval('0b1000000') # => (64, 64, 64, 64)
'{0:o}, {1:x}, {2:b}'.format(64, 64, 64) # => '100, 40, 1000000'
'%o, %x, %x, %X' % (64, 64, 255, 255) # => '100, 40, ff, FF'
# Other Built-in Numeric Tools
import math
math.pi, math.e # =>(3.141592653589793, 2.718281828459045)
math.sin(2 * math.pi / 180) # => 0.03489949670250097
math.sqrt(144), math.sqrt(2) # => (12.0, 1.4142135623730951)
pow(2, 4), 2 ** 4, 2.0 ** 4.0 # => (16, 16, 16.0)
min(3, 1, 2, 4), max(3, 1, 2, 4) # => (1, 4)
math.floor(2.567), math.floor(-2.567) # => (2, -3)
math.trunc(2.567), math.trunc(-2.567) # => (2, -2)
int(2.567), int(-2.567) # => (2, -2)
round(2.567), round(2.467), round(2.567, 2) # => (3, 2, 2.57)
'%.1f' % 2.567, '{0:.2f}'.format(2.567) # => ('2.6', '2.57')
import random
random.random() # => 0.9726485651691155
random.randint(1, 10) # => 1
random.choice(['life of Brian', 'Holy Grail', 'Meaning of Life']) # => 'Holy Grail'
suits = ['hearts', 'clubs', 'diamonds', 'spades']
random.shuffle(suits)
suits # => ['clubs', 'diamonds', 'hearts', 'spades']
# Other Numeric Types
# Decimal Type
# Decimal basics
0.1 + 0.1 +0.1 - 0.3 # => 5.551115123125783e-17
Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3') # => Decimal('0.0')
# Fraction Type
# Fraction basics
from fractions import Fraction
x = Fraction(1, 3)
y = Fraction(4, 6)
x, y # => (Fraction(1, 3), Fraction(2, 3))
print(x, y) # => 1/3 2/3
print(x + y, x - y, x * y) # => 1 -1/3 2/9
Fraction('.25') # => Fraction(1, 4)
# Sets
engineers = {'bob', 'sue', 'ann', 'vic'}
managers = {'tom', 'sue'}
'bob' in engineers # => True
engineers & managers # => {'sue'}
engineers | managers # => {'bob', 'sue', 'ann', 'vic', 'tom'}
engineers - managers # => {'vic', 'bob', 'ann'}
managers - engineers # => {'tom'}
engineers > managers # => False
{'bob', 'sue'} < engineers # =>True
(managers | engineers) > managers # => True
managers ^ engineers # => {'vic', 'bob', 'ann', 'tom'}
(managers | engineers) - (managers ^ engineers) # => {'sue'}
# Booleans O_o
type(True) # => <class 'bool'>
isinstance(True, int) # => True
True == 1 # => True
True is 1 # => False
True or False # => True
True + 4 # => 5
# CHAPTER 6 The Dynamic Typing Interlude
# CHAPTER 7 String Fundamentals
# String Basics
S = '' # Empty string
S = "spam's" # Double quotes, same as single
S = 's\np\ta\x00m' # Escape sequences
S = """...multiline...""" # Triple-quoted block string
S = r'\temp\spam' # Raw string (no escapes)
B = b'sp\xc4m' # Byte strings
U = u'sp\u00c4m' # Unicdoe strings
S1 + S2, S * 3 # Concatenate, repeat
S[i], S[i:j], len(S) # Index, slice, length
"a %s parrot" % kind # String formatting учзкуыышщт
"a {0} parrot".format(kind) # String formatting method
S.find('pa') # String methods: search
S.rstrip() # remove whitespace
S.replace('pa', 'xx') # replacement
S.split(',') # split on delimiter
S.isdigit() # content test
S.lower() # case conversion
S.endswith('spam') # end test
'spam'.join(strlist) # delimiter join
S.encode('latin-1') # Unicode encoding
B.decode('utf8') # Unicode decoding
for x in S: print(x) # Iteration, membership
'spam' in S
[c * 2 for c in S]
map(ord, S)
re.match('sp(.*)am', line) # Pattern matching: library module
# String Literals
# Escape Sequences Represent Special Characters
# String backslash characters # Like in C, C++ and other
"\newline" # Ignored (continuation line)
"\\" # Backslash (stores one \)
"\'"
"\""
"\a" # Bell
"\b" # Backspace
"\f" # Formfeed
"\n" # Newline (linefeed)
"\r" # Carriage return
"\t" # Horizontal tab
"\v" # Vertical tab
"\xhh" # Cgaracter with hex value hh (exactly 2 digits)
"\ooo" # Character with octal value ooo (up to 3 digits)
"\0" # Null: binary 0 character (doesn't end string)
"\N{ id }" # Unicode database ID
"\uhhh" # Unicode character with 16-bit hex value
"\Uhhhhhh" # Unicode character with 32-bit hex value
"\other" # Not an escape (keeps both \ and other)
# Strings in Action
# Changing Strings
S = 'spam'
S[0] = 'x' # => TypeError # Raises an error!
S = S + 'SPAM!' # To change a string, make a new one
S # => 'spamSPAM!'
S = S[:4] + 'Burger' + S[-1]
S # => 'sapmBurger!'
S = 'splot'
S = S.replace('pl', 'pamal')
S # => 'spamalot'
# String Methods
str = 'String Methods'
str.capitalize() # => 'String methods'
str.casefold() # => 'string methods'
str.center(30, '-') # => '--------String Methods--------'
str.count('t',0,-1) # => 2 # (sub[,start[,end]])
# String Formatting Expressions
'My {1[king]} runs {0.platform}'.format(sys, {'king': 'laptop'}) # => 'My laptop runs win32'
'My {map[kind]} runs {sys.platform}'.format(sys=sys, map={'kind': 'laptop'}) # => 'My laptop runs win32'
# CHAPTER 8 Lists and Dictionates
# Lists
L = [] # An empty list
L = [123, 'abc', 1.23, {}] # Four items: indexes 0..3
L = ['Bob', 40.0, ['dev', 'mgr']] # Nested sublists
L = list('spam') # List of an iterable's items
L = list(range(-4, 4)) # list of successive integers
L[i] # Index
L[i][j] # Index of index
L[i:j] # slice
len(L) # length
L1 + L2 # Concatenate
L * 3 # repeat
for x in L: print(x) # Iteration
3 in L # membership
L.append(4) # Methods: growing
L.extend([5,6,7])
L.insert(i, X)
L.index(X) # Methods: searching
L.count(X)
L.sort() # Methods: sorting, reversing
L.reverse()
L.copy()
L.clear()
L.pop(i) # Methods, statements: shrinking
L.remove(X)
del L[i]
del L[i:j]
L[i:j] = []
L[i] = 3 # Index assignment, slice assignment
L[i:j] = [4,5,6]
L = [x**2 for x in range(5)] # List comprehensions and maps
List(map(ord, 'spam'))
# Dictionares
D = {} # Empty dictionary
D = {'name': 'Bob', 'age': 40} # Two-item dictionary
E = {'cto': {'name': 'Bob', 'age': 40}} # Nesting
D = dict(name='Bob', age=40) # Alternative construction techniques:
D = dict([('name', 'Bob'), ('age', 40)]) # keywords, key/value pairs, zipped key/value pairs, key lists
D = dict(zip(keyslist, valueslist))
D = dict.fromkeys(['name', 'age'])
D['name'] # Indexing by key
E['cto']['age']
'age' in D # Membership: key present test
D.keys() # Methods: all keys,
D.values() # all values,
D.items() # all key+value tuples,
D.copy() # copy (top-level),
D.clear() # clear (remove all items),
D.update(D2) # merge by keys,
D.get(key, default?) # fetch by key, if absent default (or None),
D.pop(key, default?) # remove by key, if absent default (or error)
D.setdefault(key, default?) # fetch by key, if absent set default (or None),
D.popitem() # remove/return any (key, value) pair; etc.
len(D) # Length: number of stored entries
D[key] = 42 # Adding/changing keys
del D[key] # Deleting entries by key
list(D.keys()) # Dictionary views (Python 3.X)
D1.keys() & D2.keys()
D.viewkeys(), D.viewvalues() # Dictionary views (Python 2.7)
D = {x: x*2 for x in range(10)} # Dictionary comprehensions (Python 3.X, 2.7)
# CHAPTER 9 Tuples, Files, and Everything Else
# Tuples
() # AN empty tuple
T = (0,) # A one-item tuple (not an expression)
T = (0, 'Ni', 1.2, 3) # A four-item tuple
T = 0, 'Ni', 1.2, 3 # Another four-item tuple (same as prior line)
T = ('Bob', ('dev', 'mgr')) # Nested tuples
T = tuple('spam') # Tuple of items in an iterable
T[i] # Index,
T[i][j] # index of index,
T[i:j] # slice,
len(T) # length
T1 + T2 # Concatenate
T * 3 # repeat
for x in T: print(x) # Iteration, membership
'spam' in T
[x ** 2 for x in T]
T.index('Ni') # Methods in 2.6, 2.7, and 3.X: search, count
T.count('Ni')
namedtuple('Emp', ['name', 'jobs']) # Named tuple extension type
# Files
output = open(r'C:\spam', 'w') # Create output file ('w' means write)
input = open('data', 'r') # Create input file ('r' means read)
input = open('data')
open('testjson.txt',, encoding='utf-8') # Same as prior line ('r' is the default)
aString = input.read() # Read entire file into a single string
aString = input.read(N) # Read up to next N characters (or bytes) into a string
aString = input.readline() # Read next line (including \n newline) into a string
aList = input.readlines() # Read entire file into list of line strings (with \n)
output.write(aString) # Write a string of characters (or bytes) into file
output.writelines(aList) # Write all line strings in a list into file
output.close() # Manual close (done for you when file is collected)
output.flush() # Flush output buffer to disk without closing
anyFile.seek(N) # Change file position to offset N for next operation
for line in open('data'): # use line File iterators read line by line
open('f.txt', encoding='latin-1') # Python 3.X Unicode text files (str strings)
open('f.bin', 'rb') # Python 3.X bytes files (bytes strings)
codecs.open('f.txt', encoding='utf8') # Python 2.X Unicode text files (unicode strings)
open('f.bin', 'rb') # Python 2.X bytes files (str strings)
# PART 3 Statements and Syntax
# CHAPTER 10 Introducing Python Statements
# Python statements
# \/ Example # \/ Statement # \/ Role
a, b = 'good', 'bad' # Assignment # Creating references
log.write("spam, ham") # Calls and other expressions # Running functions
print('The Killer', joke) # print calls # Printing objects
if "python" in text: # if/elif/else # Selecting actions
print(text)
for x in mylist: # for/else # Iteration
print(x)
while X > Y: # while/else # General loops
print('hello')
while True: # pass # Empty placeholder
pass
while True: # break # Loop exit
if exittest(): break
while True: # continue # Loop continue
if skiptest(): continue
def f(a, b, c=1, *d): # def # Functions and methods
print(a+b+c+d[0])
def f(a, b, c=1, *d): # return # Functions results
return a+b+c+d[0]
def gen(n): # yield # Generator functions
for i in n: yield i*2
x = 'old' # global # Namespaces
def function():
global x, y; x = 'new'
def outer(): # nonlocal # Namespaces (3.X)
x = 'old'
def function():
nonlocal x; x = 'new'
import sys # import # Module access
from sys import stdim # from # Attribute access
class Subclass(Superclass): # class # Building objects
staticData = []
def method(self): pass
try: # try/except/finally # Catching exceptions
action()
except:
print('action error')
raise EndSearch(location) # raise # Triggering exceptions
assert X > Y, 'X too small' # assert # Debugging checks
with open('data') as myfile:# with/as # Context managers
process(myfile)
del data[k] # del # Deleting references
del data[i:j]
del obj.attr
del variable
# CHAPTER 11 Assignments, Expressions, and Prints
# Assignment statement forms
spam = 'Spam' # Basic form
spam, ham = 'yum', 'YUM' # Tuple assignment (positional)
[spam, ham] = ['yum', 'YUM'] # List assignment (positional)
a, b, c, d = 'spam' # Sequence assignment, generalized
a, *b = 'spam' # Extended sequence unpacking (Python 3.X)
spam = ham = 'lunch' # Multiple-target assignment
spams += 42 # Augmented assignment (equivalent to spams = spams + 42)
# Augmented assignment statements
X += Y, X &= Y, X -= Y, X |= Y
X *= Y, X ^= Y, X /= Y, X >>=Y
X %= Y, X <<=Y, X **=Y, X //=Y
# Python reserved words
False; class; finally; is; return;
None; continue; for; lambda; try;
True; def; from; nonlocal; while;
and; del; global; not; with;
as; elif; if; or; yield;
assert; else; import; pass;
break; except; in; raise;
# Common Python expression statements
spam(eggs, ham) # Function calls
spam.ham(eggs) # Method calls
spam # Printing variables in the interactive interpreter
print(a, b, c, sep='') # Printing operations in Python 3.X
yield x ** 2 # Yielding expression statements
# Printing, the hard way
import sys
sys.stdout.write('hello world\n') # => hello world
sys.stdout = open('log.txt', 'a') # Redirects prints to a file
...
print(x, y, x) # Shows up in log.txt
log = open('log.txt', 'a') # 3.X
print(x, y, z, file=log) # Print to a file-like object
# CHAPTER 12 if Tests and Syntax Rules
# if Tests and Syntax Rules
if test1: # if test
statements1 # Associated block
elif test2: # Optional elifs
statements2
else: # Optio
statements3
# Loops
while test: # Loop test
statements # Loop body
else: # Optional else
statements # Run if didn't exit loop with break
break # Jumps out of the closest enclosing loop (past the entire loop statement)
continue # Jumps to the top of the closest enclosing loop (to the loop's header line)
pass # Does nothing at all: it's an empty statement placeholder
... # Alternative to pass
Loop else block # Runs if and only if the loop is exited normally (without hitting a break)
# CHAPTER 13 while and for Loops
# while Loops
while :
statements
if test: break # Exit loop now, skip else if present
if test: continue # Go to top of loop now, to test1
else:
statements # Run if we didn't hit a 'break'
# for Loops
for target in object: # Assign object items to target
statements # Repeated loop body: use target
else: # Optional else part
statements # If we didn't hit a 'break'
[a for a in dir(list) if not a.startswith('__')]
[x for x in ['spam', '', 'ni'] if bool(x)]
[x for x in ['spam', '', 'ni'] if x]
# Parallel Traversals: zip and map
L1 = [1,2,3,4]
L2 = [5,6,7,8]
zip(L1, L2) # => <zip object at 0x026523C8>
list(zip(L1, L2)) # => [(1, 5), (2, 6), (3, 7), (4, 8)] # list() required in 3.X, not 2.X
# CHAPTER 14 Iterations and Comprehensions
# iteration
L = [1, 2, 3, 4, 5]
for i in range(len(L)):
L[i] += 10
L # => [11, 12, 13, 14, 15]
L = [x + 10 for x in L]
L # => [21, 22, 23, 24, 25]
[x + y for x in 'abc' for y in 'lmn']
# => ['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn']
res = []
for x in 'abc':
for y in 'lmn':
res.append(x + y)
res
# => ['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn']
''' need to learn more'''
# CHAPTER 15 The Documentation Interlude
# Documentation
# Python documentation sources
# comments # In-file documentation
'The dir function '# Lists of attributes available in objects
'Docstrings:__doc__ '# In-file documentation attached to objects
'PyDoc: the help function '# Interactive help for objects
'PyDocy: HTML reports '# Module documentation in a browser
'Sphinx third-party tool '# Richer documentation for larger projects
'The standart manual set '# Official language and library descriptions
'Web resources '# Online tutorials, examples, and so on
'Published books '# Commercially polished reference texts
# PyDoc
"""
c:\code>
python -m pydoc -b
py -3 -m pydoc -b
C:\python33\python -m pydoc -b
"""# => Server ready at http://localhost:62135
# PART 4 Functions and Generators
# CHAPTER 16 Function Basics
# Examples # Statement or expression
myfunc('spam', 'eggs', meat=ham, *rest) # Call expressions
def printer(message): # def
print('Hello ' + str(message))
def adder(a, b=1, *c): # return
return a + b + c[0]
x = 'old' # global
def changer():
global x; x = 'new'
def outer(): # nonlocal (3.X)
x = 'old'
def changer():
nonlocal x; x = 'new'
def squares(x): # yield
for i in range(x): yield i ** 2
funcs = [lambda x: x**2, lambda x: x**3] # lambda
# def Statements
def name(arg1, arg2, ... argN):
statements
...
return value
for x in xrange(1,10):
pass
# def Executes at Runtime
if test:
def func(): # Define func this way
...
else:
def func(): # Or else this way
...
...
func() # Call the version selected and built
othername = func # Assign function object
othername() # Call func again
def func(): ... # Create function object
func() # Call object
func.attr = value # Attach attributes
#Definition
def intersect(seq1, seq2):
res = [] # Start empty
for x in seq1: # Scan seq1
if x in seq2: # Common item?
res.append(x) # Add to end
return res
s1 = "SPAM"
s2 = "SCAM"
intersect(s1, s2) # String
# => ['S', 'A', 'M']
[x for x in s1 if x in s2]
# => ['S', 'A', 'M']
x = intersect([1, 2, 3], (1, 4)) # Mixed types
x # Saved result object
# => [1]
# CHAPTER 17 Scopes
# Python Scope Basics
X = 99 # Global (module) scope X
def func():
X = 88 # Local (function) scope X: a different variable
# Name Resolution: The LEGB Rule
"""
Built-in (Python)
Names preassigned in the built-in names modules: open, range,
SyntaxError...
Global (module)
Names assigned at the top-level of module file, or declared
globla in a def within the file.
Enclosing function locals
Names in the local scope of any and all enclosing functions
(def or lambda), from inner to outer.
Local (function)
Names assigned in any way within a function (def
or lambda), and not declared global in that function.
"""
# Scope Example
# Global scope
X = 99 # X and func assigned in module: global
def func(Y): # Y and Z assigned in function: locals
# Local scope
Z = X + Y # X is a global
return Z
func(1) # func in module: result=100
# The global Statement
X = 88 # Global X
def func():
global X
X = 99 # Global X: outside def
func()
print(X) # Prints 99
y, z = 1, 2 # Global variables in module
def all_global():
global x # Declare globals assigned<|fim▁hole|> # Other Ways to Access Globals
# thismod.py
var = 99
def local():
var = 0 # Change local var
def glob1():
global var # Declare global (normal)
var += 1 # Change global var
def glob2():
var = 0 # Change local var
import thismod # Import myself
thismod.var += 1 # Change global var
def glob3():
var = 0 # Change local var
import sys # Import system table
glob = sys.modules['thismod'] # Get module object (or use __name__)
glob.var += 1 # Change global var
def test():
print(var)
local(); glob1(); glob2(); glob3()
print(var)
# consol
import thismod
thismod.test() # => 99 102
thismod.var # => 102
# Scopes and Nested Functions
# Function factory (a.k.a. closures)
# A simple function factory
def maker(N):
def action(X):
return X ** N # Make and return action
return action # action retains N from enclosing
f = maker(2)
g = maker(3) # g remembers 3, f remembers 2
g(4) # => 64 # 4 ** 3
f(4) # => 16 # 4 ** 2
def maker(N):
return lambda X: X ** N # lambda functions retain state too
# Retaining Enclosing Scope State with Defaults
def f1():
x = 88
def f2(x=x): # Remember enclosing scope X with defaults
print(x)
f2()
f1() # => 88
def f1():
x = 88
f2(x)
def f2(x):
print(x)
f1() # => 88
# The nonlocal Statement in 3.X
# nonlocal Basics
nonlocal # skip my local scope entirely
# CHAPTER 18 Arguments
# Argument-Passing Basics
# Special Argument-Mathching Modes
# Argument Matching Syntax
# Syntax # Location # Interpretation
func(value) # Caller # Normal argument: matched by position
func(name=value) # Caller # Keyword argument: matched by name
func(*iterable) # Caller # Pass all objects in iterable as individual positional arguments
func(**dict) # Caller # Pass all key/value pairs in dict as individual keyword arguments
def func(name): # Function # Normal argument: matches any passed value by position or name
def func(name=value): # Function # Default argument value, if not passed in the call
def func(*name): # Function # Matches and collects remaining positional arguments in a tuple
def func(**name): # Function # Matches and collects remaining keyword arguments in a dictionary
def func(*other, name): # Function # Arguments that must be passed by keyword only in calls (3.X)
def func(*, name=value):# Function # Arguments that must be passed by keyword only in calls (3.X)
# Combining keywords and defaults
def func(spam, eggs, toast=0, ham=0):
print((spam, eggs, toasr, ham))
func(1, 2) # => (1, 2, 0, 0)
func(1, ham=1, eggs=0) # => (1, 0, 0, 1)
func(spam=1, eggs=0) # => (1, 0, 0, 0)
func(toast=1, eggs=2, spam=3) # => (3, 2, 1, 0)
func(1, 2, 3, 4) # => (1, 2, 3, 4)
# Arbitrary Arguments Examples
# Headers: Collections aruments
def f(a, *pargs, **kargs): print(a, pargs, kargs)
f(1, 2, 3, 4, x=5, y=6) # => 1 (2, 3, 4) {'y': 6, 'x': 5}
# ┌──────────────────────────────────────────┐
# │ Learning Python 5E -- 546 (598 /1594) │
# ├──────────────────────────────────────────┤
# │ Изучаем Python 4E -- (463 / 1280) │
# └──────────────────────────────────────────┘<|fim▁end|> | x = y + z # No need to declare y, z: LEGB rule
|
<|file_name|>dialogs.module.ts<|end_file_name|><|fim▁begin|>import { Type } from '@angular/core';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatDialogModule } from '@angular/material/dialog';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import {
TdDialogComponent,
TdDialogTitleDirective,
TdDialogActionsDirective,
TdDialogContentDirective,
} from './dialog.component';
import { TdAlertDialogComponent } from './alert-dialog/alert-dialog.component';
import { TdConfirmDialogComponent } from './confirm-dialog/confirm-dialog.component';
import { TdPromptDialogComponent } from './prompt-dialog/prompt-dialog.component';
import { TdDialogService } from './services/dialog.service';
import { TdWindowDialogComponent } from './window-dialog/window-dialog.component';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatIconModule } from '@angular/material/icon';
const TD_DIALOGS: Type<any>[] = [
TdAlertDialogComponent,
TdConfirmDialogComponent,
TdPromptDialogComponent,
TdDialogComponent,
TdDialogTitleDirective,
TdDialogActionsDirective,
TdDialogContentDirective,
TdWindowDialogComponent,
];
const TD_DIALOGS_ENTRY_COMPONENTS: Type<any>[] = [
TdAlertDialogComponent,
TdConfirmDialogComponent,
TdPromptDialogComponent,
];
@NgModule({<|fim▁hole|> FormsModule,
CommonModule,
MatDialogModule,
MatInputModule,
MatButtonModule,
MatToolbarModule,
MatTooltipModule,
MatIconModule,
],
declarations: [TD_DIALOGS],
exports: [TD_DIALOGS],
providers: [TdDialogService],
})
export class CovalentDialogsModule {}<|fim▁end|> | imports: [ |
<|file_name|>text.py<|end_file_name|><|fim▁begin|>import nltk
class Text:
def __init__(self, raw_text):<|fim▁hole|> sentences = nltk.sent_tokenize(self.raw_text)
tokens = [nltk.word_tokenize(sentence) for sentence in sentences]
self.tagged_sentences = [self.tag(words) for words in tokens]
return self
def tag(self, sentence):
initial_tagged_words = nltk.pos_tag(sentence)
tagged_words = []
consecutive_names = []
last_tag = None
for tagged_word in initial_tagged_words:
if tagged_word[1].startswith('NNP'):
consecutive_names.append(tagged_word[0])
last_tag = tagged_word[1]
else:
if consecutive_names:
tagged_words.append((' '.join(consecutive_names), last_tag))
consecutive_names = []
tagged_words.append(tagged_word)
if consecutive_names:
tagged_words.append((' '.join(consecutive_names), last_tag))
return tagged_words<|fim▁end|> | self.raw_text = raw_text
def parse(self): |
<|file_name|>serializers.py<|end_file_name|><|fim▁begin|>from rest_framework import serializers
class AttachmentSerializer(serializers.Serializer):<|fim▁hole|>// As of 2017-06-13, up to 38 attachments can be worn per agent
// max of 328 bytes per attach point (if name and description are maxed out).
// x38 = 12464 bytes
// without descriptions: 188 * 38 = 7144 bytes top
// I measured a real outfit with 38 attachments; it's json encoding was 6877 bytes
string avatarAttachmentsJson(key id) {
list ans = [];
list attachments = llGetAttachedList(id);
debug((string)llGetListLength(attachments) + " attachments");
integer i;
for (i = llGetListLength(attachments) - 1; i >= 0; i--) {
key attachment = llList2Key(attachments, i);
list details = llGetObjectDetails(attachment, [OBJECT_NAME, OBJECT_DESC, OBJECT_CREATOR, OBJECT_ATTACHED_POINT]);
ans = [llList2Json(JSON_OBJECT, [
"id", attachment, // 6+2+36 = 44 bytes
"name", llList2String(details, 0), // 6+4+64 = 74 bytes
"desc", llList2String(details, 1), // 6+4+128 = 140 bytes
"creator", llList2String(details, 2), // 6+7+36 = 49 bytes
"attachPoint", llList2String(details, 3) // 6+11+2 = 19 bytes
])] + ans;
}
return llList2Json(JSON_ARRAY, ans);
}
"""<|fim▁end|> | pass
"""
//* |
<|file_name|>or.rs<|end_file_name|><|fim▁begin|>use super::{ToSharedPredicate};
#[derive(Clone)]<|fim▁hole|>}
pub trait ToOrPredicate {
fn or(&self, val: super::SharedPredicate) -> super::SharedPredicate;
}
impl super::Predicate for OrPredicate { }
impl ToOrPredicate for super::SharedPredicate {
fn or(&self, predicate: super::SharedPredicate) -> super::SharedPredicate {
OrPredicate{ left: self.clone(), right: predicate }.upcast()
}
}<|fim▁end|> | pub struct OrPredicate {
pub left: super::SharedPredicate,
pub right: super::SharedPredicate |
<|file_name|>misc.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use libc::{c_float, c_int};
use cast::GTK_MISC;
use ffi;
pub trait MiscTrait: ::WidgetTrait {
fn set_alignment(&self, x_align: f32, y_align: f32) -> () {
unsafe {
ffi::gtk_misc_set_alignment(GTK_MISC(self.unwrap_widget()), x_align as c_float, y_align as c_float);
}
}
fn set_padding(&self, x_pad: i32, y_pad: i32) -> () {
unsafe {
ffi::gtk_misc_set_padding(GTK_MISC(self.unwrap_widget()), x_pad as c_int, y_pad as c_int);
}
}
fn get_alignment(&self) -> (f32, f32) {
let mut x: c_float = 0.;
let mut y: c_float = 0.;
unsafe {
ffi::gtk_misc_get_alignment(GTK_MISC(self.unwrap_widget()), &mut x, &mut y);
}
(x as f32, y as f32)
}
<|fim▁hole|> let mut y: c_int = 0;
unsafe {
ffi::gtk_misc_get_padding(GTK_MISC(self.unwrap_widget()), &mut x, &mut y);
}
(x as i32, y as i32)
}
}<|fim▁end|> | fn get_padding(&self) -> (i32, i32) {
let mut x: c_int = 0; |
<|file_name|>notebook.py<|end_file_name|><|fim▁begin|>#! /usr/bin/ python
# -*- coding: utf-8 -*-
# Copyright (C) 2013 Deepin, Inc.
# 2013 Hailong Qiu
#
# Author: Hailong Qiu <356752238@qq.com>
# Maintainer: Hailong Qiu <356752238@qq.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 3 of the License, or
# 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, see <http://www.gnu.org/licenses/>.
import gtk
from gtk import gdk
import gobject
from draw import draw_text
from color import alpha_color_hex_to_cairo
class NoteBook(gtk.Container):
def __init__(self):
gtk.Container.__init__(self)
self.__init_values()
def __init_values(self):
self.add_events(gtk.gdk.ALL_EVENTS_MASK)
self.title_child1 = gtk.Button("本地列表")
self.title_child1.set_parent(self)
self.title_child2 = gtk.Button("网络列表")
self.title_child2.set_parent(self)
self.title_w = 120
self.title_h = 30
self.save_title_h = self.title_h
#
self.title_child1.connect("clicked", self.__title_child1_clicked)
self.title_child2.connect("clicked", self.__title_child2_clicked)
self.title_child1.connect("expose-event", self.__title_child1_expose_event)
self.title_child2.connect("expose-event", self.__title_child2_expose_event)
#
self.layout_show_check = True
self.layout1 = None
self.layout2 = None
self.children = []
# 添加子控件.
self.children.append(self.title_child1)
self.children.append(self.title_child2)
def __title_child1_clicked(self, widget):
if self.layout2 and self.layout1:
self.layout_show_check = True
def __title_child2_clicked(self, widget):
if self.layout1 and self.layout2:
self.layout_show_check = False
def __title_child1_expose_event(self, widget, event):
self.__title_expose_event(widget, event, self.layout_show_check)
return True
def __title_child2_expose_event(self, widget, event):
self.__title_expose_event(widget, event, not self.layout_show_check)
return True
def __title_expose_event(self, widget, event, show_check):
cr = widget.window.cairo_create()
rect = widget.allocation
# draw background.
if show_check:
bg_color = "#272727"
else:
bg_color = "#1b1b1b"
cr.set_source_rgba(*alpha_color_hex_to_cairo((bg_color,1.0)))
cr.rectangle(rect.x, rect.y, rect.width + 1, rect.height)
cr.fill()
# draw title name.
text = widget.get_label()
import pango
if show_check:
text_color = "#FFFFFF"
else:
text_color = "#A9A9A9"
draw_text(cr,
text,
rect.x, rect.y, rect.width, rect.height,
text_color=text_color,
text_size=9,
alignment=pango.ALIGN_CENTER)
def add_layout1(self, layout1):
self.layout1 = layout1
self.layout1.set_parent(self)
def add_layout2(self, layout2):
self.layout2 = layout2
self.layout2.set_parent(self)
def do_realize(self):
self.set_realized(True)
self.__init_window()
self.__init_children()
self.queue_resize()
def __init_window(self):
self.window = gdk.Window(
self.get_parent_window(),
window_type=gdk.WINDOW_CHILD,
x=self.allocation.x,
y=self.allocation.y,
width=self.allocation.width,
height=self.allocation.height,
colormap=self.get_colormap(),
wclass=gdk.INPUT_OUTPUT,
visual=self.get_visual(),
event_mask=(self.get_events()
| gtk.gdk.VISIBILITY_NOTIFY
| gdk.EXPOSURE_MASK
| gdk.SCROLL_MASK
| gdk.POINTER_MOTION_MASK
| gdk.ENTER_NOTIFY_MASK<|fim▁hole|> | gdk.BUTTON_PRESS_MASK
| gdk.BUTTON_RELEASE_MASK
| gdk.KEY_PRESS_MASK
| gdk.KEY_RELEASE_MASK
))
self.window.set_user_data(self)
self.style.set_background(self.window, gtk.STATE_NORMAL)
def __init_children(self):
if self.title_child1:
self.title_child1.set_parent_window(self.window)
if self.title_child2:
self.title_child2.set_parent_window(self.window)
self.layout1.set_parent_window(self.window)
self.layout2.set_parent_window(self.window)
def do_unrealize(self):
pass
def do_map(self):
gtk.Container.do_map(self)
self.set_flags(gtk.MAPPED)
#
self.window.show()
def do_umap(self):
gtk.Container.do_umap(self)
self.window.hide()
def do_expose_event(self, e):
#
gtk.Container.do_expose_event(self, e)
return False
def do_size_request(self, req):
self.title_child1.size_request()
self.title_child2.size_request()
self.layout1.size_request()
self.layout2.size_request()
def do_size_allocate(self, allocation):
gtk.Container.do_size_allocate(self, allocation)
self.allocation = allocation
#
title_w_padding = self.allocation.width/len(self.children)
allocation = gdk.Rectangle()
allocation.x = 0
allocation.y = 0
allocation.width = title_w_padding
allocation.height = self.title_h
self.title_child1.size_allocate(allocation)
allocation.x = 0 + allocation.width
self.title_child2.size_allocate(allocation)
#
if self.layout_show_check:
layout2_x = -self.allocation.width
else:
layout2_x = 0
allocation.x = layout2_x
allocation.y = 0 + self.title_h #self.layout2.allocation.y
allocation.width = self.allocation.width
allocation.height = self.allocation.height - self.title_h
self.layout2.size_allocate(allocation)
if not self.layout_show_check:
layout1_x = - self.allocation.width
else:
layout1_x = 0
allocation.x = layout1_x
allocation.y = 0 + self.title_h #self.layout1.allocation.y
self.layout1.size_allocate(allocation)
#
if self.get_realized():
self.window.move_resize(
self.allocation.x,
self.allocation.y,
self.allocation.width,
self.allocation.height)
def do_show(self):
gtk.Container.do_show(self)
def do_forall(self, include_internals, callback, data):
callback(self.title_child1, data)
callback(self.title_child2, data)
callback(self.layout1, data)
callback(self.layout2, data)
def do_remove(self, widget):
pass
def hide_title(self):
self.save_title_h = self.title_h
self.title_h = 0
def show_title(self):
self.title_h = self.save_title_h
gobject.type_register(NoteBook)
if __name__ == "__main__":
from treeview_base import TreeViewBase
win = gtk.Window(gtk.WINDOW_TOPLEVEL)
scroll_win = gtk.ScrolledWindow()
treeview_base = TreeViewBase()
scroll_win.add_with_viewport(treeview_base)
note_book = NoteBook()
note_book.add_layout1(scroll_win)
note_book.add_layout2(gtk.Button("测试一下"))
win.add(note_book)
#
node1 = treeview_base.nodes.add("优酷视频")
dianshiju = node1.nodes.add("电视剧")
node1.nodes.add("电影")
node1.nodes.add("综艺")
node1.nodes.add("音乐")
node1.nodes.add("动漫")
# 电视剧?
xinshangying = dianshiju.nodes.add("新上映")
dianshiju.nodes.add("明星")
dianshiju.nodes.add("大陆剧")
dianshiju.nodes.add("韩剧")
dianshiju.nodes.add("TVB")
#
xinshangying.nodes.add("桐柏英雄")
xinshangying.nodes.add("血雨母子情")
win.show_all()
gtk.main()<|fim▁end|> | | gdk.LEAVE_NOTIFY_MASK |
<|file_name|>parsing_logs_arun.py<|end_file_name|><|fim▁begin|>import re
def check_patterns():
patterns_list = []
#Read patterns file
with open("patterns.txt") as patterns1:
for line in patterns1:
line = line.rstrip("\n")
patterns_list.append(line)
print(patterns_list)
#Read log file
with open("Sample Logs.txt") as log1:
with open("matching_logs.txt", "w") as output_fh:
for log_line in log1:
log_line = log_line.rstrip("\n")
for pattern in patterns_list:
match = re.search(pattern, log_line)
if match != None:
log_line.lstrip(" ")
count = int(match.group(1))
host = match.group(2)
if count > 100:
print(host, " Has count > 100")<|fim▁hole|> print(log_line)
def rstrip_example():
s1 = "hello"
s1 = s1.rstrip("lo")
print(s1)
check_patterns()<|fim▁end|> | |
<|file_name|>utils_lib.py<|end_file_name|><|fim▁begin|># Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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.
# ==============================================================================
"""Utility functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import,line-too-long,wildcard-import
from tensorflow.contrib.kfac.python.ops.utils import *
from tensorflow.python.util.all_util import remove_undocumented
# pylint: enable=unused-import,line-too-long,wildcard-import
_allowed_symbols = [
"SequenceDict",
"setdefault",
"tensors_to_column",
"column_to_tensors",
"kronecker_product",
"layer_params_to_mat2d",
"mat2d_to_layer_params",
"compute_pi",
"posdef_inv",
"posdef_inv_matrix_inverse",
"posdef_inv_cholesky",
"posdef_inv_funcs",
"SubGraph",
"generate_random_signs",
"fwd_gradients",<|fim▁hole|><|fim▁end|> | ]
remove_undocumented(__name__, allowed_exception_list=_allowed_symbols) |
<|file_name|>compute_user_popularity.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# compute the times of action(rec|click|msg) for each user
from math import sqrt
def getActionScore(action):
if action == "rec":
return 0
elif action == "click" :
return 1
else:
return 2
def compute_interaction(data):
interaction = {}
for line in data:
(userA,userB,times,action) = line.split(' ')
action = action[:-1]
key = userB + " " + action
interaction.setdefault(key, 0)
interaction[key] += 1
return interaction
def compute_user_history_interaction(trainFile):
records = []
lineList = []
lineNum = 1
result = []
lineList = [line for line in file(trainFile)]
for line in lineList:
if lineNum == 1: #ignore the title in first line
lineNum += 1
continue
records.append(line)<|fim▁hole|>
interaction = compute_interaction(records)
out = file('user_interaction.txt', 'w')
for (key, times) in interaction.items():
out.write('%s %d' % (key, times))
out.write('\n')
for (key, times) in interaction.items():
user, action = key.split(' ');
result.append((user, action, times))
return result
#get the weight for each type of action
def get_action_weight(action):
pop = 0;
if action == "rec":
pop = 1
elif action == "click":
pop = 10
elif action == "msg":
pop = 100
return pop;
#trainFile line like: [userA, userB, action_times, action_type(rec|click|msg)]
def compute_user_popularity(trainFile, user_popularity_file):
popDict = {}
rankedscores = []
result = []
print "-----compute_user_history_interaction ... "
interaction = compute_user_history_interaction(trainFile)
print "-----compute_user_popularity ... "
for (user, action, times) in interaction[0:len(interaction)]:
popDict.setdefault(user, 0)
popDict[user] += get_action_weight(action) * times
ranked_popularity = [(popularity, user) for (user, popularity) in popDict.items()]
ranked_popularity.sort()
ranked_popularity.reverse()
print "-----ranking_user_popularity ... "
result = [(user, popularity) for (popularity, user) in ranked_popularity[0:len(ranked_popularity)]]
print "-----output user_popularity ... "
out = file(user_popularity_file, 'w')
for (user, popularity) in result[0:len(result)]:
out.write('%s %d\n' % (user, popularity))
print "-----Ending ... "
return result<|fim▁end|> | lineNum += 1 |
<|file_name|>_tarantula.py<|end_file_name|><|fim▁begin|># Copyright 2018-2020 by Christopher C. Little.
# This file is part of Abydos.
#
# Abydos 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.
#
# Abydos 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 Abydos. If not, see <http://www.gnu.org/licenses/>.
"""abydos.distance._tarantula.
Tarantula similarity
"""
<|fim▁hole|>from typing import Any, Counter as TCounter, Optional, Sequence, Set, Union
from ._token_distance import _TokenDistance
from ..tokenizer import _Tokenizer
__all__ = ['Tarantula']
class Tarantula(_TokenDistance):
r"""Tarantula similarity.
For two sets X and Y and a population N, Tarantula similarity
:cite:`Jones:2005` is
.. math::
sim_{Tarantula}(X, Y) =
\frac{\frac{|X \cap Y|}{|X \cap Y| + |X \setminus Y|}}
{\frac{|X \cap Y|}{|X \cap Y| + |X \setminus Y|} +
\frac{|Y \setminus X|}
{|Y \setminus X| + |(N \setminus X) \setminus Y|}}
In :ref:`2x2 confusion table terms <confusion_table>`, where a+b+c+d=n,
this is
.. math::
sim_{Tarantula} =
\frac{\frac{a}{a+b}}{\frac{a}{a+b} + \frac{c}{c+d}}
.. versionadded:: 0.4.0
"""
def __init__(
self,
alphabet: Optional[
Union[TCounter[str], Sequence[str], Set[str], int]
] = None,
tokenizer: Optional[_Tokenizer] = None,
intersection_type: str = 'crisp',
**kwargs: Any
) -> None:
"""Initialize Tarantula instance.
Parameters
----------
alphabet : Counter, collection, int, or None
This represents the alphabet of possible tokens.
See :ref:`alphabet <alphabet>` description in
:py:class:`_TokenDistance` for details.
tokenizer : _Tokenizer
A tokenizer instance from the :py:mod:`abydos.tokenizer` package
intersection_type : str
Specifies the intersection type, and set type as a result:
See :ref:`intersection_type <intersection_type>` description in
:py:class:`_TokenDistance` for details.
**kwargs
Arbitrary keyword arguments
Other Parameters
----------------
qval : int
The length of each q-gram. Using this parameter and tokenizer=None
will cause the instance to use the QGram tokenizer with this
q value.
metric : _Distance
A string distance measure class for use in the ``soft`` and
``fuzzy`` variants.
threshold : float
A threshold value, similarities above which are counted as
members of the intersection for the ``fuzzy`` variant.
.. versionadded:: 0.4.0
"""
super(Tarantula, self).__init__(
alphabet=alphabet,
tokenizer=tokenizer,
intersection_type=intersection_type,
**kwargs
)
def sim(self, src: str, tar: str) -> float:
"""Return the Tarantula similarity of two strings.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
Returns
-------
float
Tarantula similarity
Examples
--------
>>> cmp = Tarantula()
>>> cmp.sim('cat', 'hat')
0.9948979591836735
>>> cmp.sim('Niall', 'Neil')
0.98856416772554
>>> cmp.sim('aluminum', 'Catalan')
0.9249106078665077
>>> cmp.sim('ATCG', 'TAGC')
0.0
.. versionadded:: 0.4.0
"""
if src == tar:
return 1.0
self._tokenize(src, tar)
a = self._intersection_card()
b = self._src_only_card()
c = self._tar_only_card()
d = self._total_complement_card()
num = a * (c + d)
if num:
return num / (a * (2 * c + d) + b * c)
return 0.0
if __name__ == '__main__':
import doctest
doctest.testmod()<|fim▁end|> | |
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 thomasv@gitorious
#
# 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 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Note: The deserialization code originally comes from ABE.
from bitcoin import *
from util import print_error
import time
import struct
#
# Workalike python implementation of Bitcoin's CDataStream class.
#
import struct
import StringIO
import mmap
class SerializationError(Exception):
""" Thrown when there's a problem deserializing or serializing """
class BCDataStream(object):
def __init__(self):
self.input = None
self.read_cursor = 0
def clear(self):
self.input = None
self.read_cursor = 0
def write(self, bytes): # Initialize with string of bytes
if self.input is None:
self.input = bytes
else:
self.input += bytes
def map_file(self, file, start): # Initialize with bytes from file
self.input = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)
self.read_cursor = start
def seek_file(self, position):
self.read_cursor = position
def close_file(self):
self.input.close()
def read_string(self):
# Strings are encoded depending on length:
# 0 to 252 : 1-byte-length followed by bytes (if any)
# 253 to 65,535 : byte'253' 2-byte-length followed by bytes
# 65,536 to 4,294,967,295 : byte '254' 4-byte-length followed by bytes
# ... and the Bitcoin client is coded to understand:
# greater than 4,294,967,295 : byte '255' 8-byte-length followed by bytes of string
# ... but I don't think it actually handles any strings that big.
if self.input is None:
raise SerializationError("call write(bytes) before trying to deserialize")
try:
length = self.read_compact_size()
except IndexError:
raise SerializationError("attempt to read past end of buffer")
return self.read_bytes(length)
def write_string(self, string):
# Length-encoded as with read-string
self.write_compact_size(len(string))
self.write(string)
def read_bytes(self, length):
try:
result = self.input[self.read_cursor:self.read_cursor+length]
self.read_cursor += length
return result
except IndexError:
raise SerializationError("attempt to read past end of buffer")
return ''
def read_boolean(self): return self.read_bytes(1)[0] != chr(0)
def read_int16(self): return self._read_num('<h')
def read_uint16(self): return self._read_num('<H')
def read_int32(self): return self._read_num('<i')
def read_uint32(self): return self._read_num('<I')
def read_int64(self): return self._read_num('<q')
def read_uint64(self): return self._read_num('<Q')
def write_boolean(self, val): return self.write(chr(1) if val else chr(0))
def write_int16(self, val): return self._write_num('<h', val)
def write_uint16(self, val): return self._write_num('<H', val)
def write_int32(self, val): return self._write_num('<i', val)
def write_uint32(self, val): return self._write_num('<I', val)
def write_int64(self, val): return self._write_num('<q', val)
def write_uint64(self, val): return self._write_num('<Q', val)
def read_compact_size(self):
size = ord(self.input[self.read_cursor])
self.read_cursor += 1
if size == 253:
size = self._read_num('<H')
elif size == 254:
size = self._read_num('<I')
elif size == 255:
size = self._read_num('<Q')
return size
def write_compact_size(self, size):
if size < 0:
raise SerializationError("attempt to write size < 0")
elif size < 253:
self.write(chr(size))
elif size < 2**16:
self.write('\xfd')
self._write_num('<H', size)
elif size < 2**32:
self.write('\xfe')
self._write_num('<I', size)
elif size < 2**64:
self.write('\xff')
self._write_num('<Q', size)
def _read_num(self, format):
(i,) = struct.unpack_from(format, self.input, self.read_cursor)
self.read_cursor += struct.calcsize(format)
return i
def _write_num(self, format, num):
s = struct.pack(format, num)
self.write(s)
#
# enum-like type
# From the Python Cookbook, downloaded from http://code.activestate.com/recipes/67107/
#
import types, string, exceptions
class EnumException(exceptions.Exception):
pass
class Enumeration:
def __init__(self, name, enumList):
self.__doc__ = name
lookup = { }
reverseLookup = { }
i = 0
uniqueNames = [ ]
uniqueValues = [ ]
for x in enumList:
if type(x) == types.TupleType:
x, i = x
if type(x) != types.StringType:
raise EnumException, "enum name is not a string: " + x
if type(i) != types.IntType:
raise EnumException, "enum value is not an integer: " + i
if x in uniqueNames:
raise EnumException, "enum name is not unique: " + x
if i in uniqueValues:
raise EnumException, "enum value is not unique for " + x
uniqueNames.append(x)
uniqueValues.append(i)
lookup[x] = i
reverseLookup[i] = x
i = i + 1
self.lookup = lookup
self.reverseLookup = reverseLookup
def __getattr__(self, attr):
if not self.lookup.has_key(attr):
raise AttributeError
return self.lookup[attr]
def whatis(self, value):
return self.reverseLookup[value]
# This function comes from bitcointools, bct-LICENSE.txt.
def long_hex(bytes):
return bytes.encode('hex_codec')
# This function comes from bitcointools, bct-LICENSE.txt.
def short_hex(bytes):
t = bytes.encode('hex_codec')
if len(t) < 11:
return t
return t[0:4]+"..."+t[-4:]
def parse_redeemScript(bytes):
dec = [ x for x in script_GetOp(bytes.decode('hex')) ]
# 2 of 2
match = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_2, opcodes.OP_CHECKMULTISIG ]
if match_decoded(dec, match):
pubkeys = [ dec[1][1].encode('hex'), dec[2][1].encode('hex') ]
return 2, pubkeys
# 2 of 3
match = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_3, opcodes.OP_CHECKMULTISIG ]
if match_decoded(dec, match):
pubkeys = [ dec[1][1].encode('hex'), dec[2][1].encode('hex'), dec[3][1].encode('hex') ]
return 2, pubkeys
opcodes = Enumeration("Opcodes", [
("OP_0", 0), ("OP_PUSHDATA1",76), "OP_PUSHDATA2", "OP_PUSHDATA4", "OP_1NEGATE", "OP_RESERVED",
"OP_1", "OP_2", "OP_3", "OP_4", "OP_5", "OP_6", "OP_7",
"OP_8", "OP_9", "OP_10", "OP_11", "OP_12", "OP_13", "OP_14", "OP_15", "OP_16",
"OP_NOP", "OP_VER", "OP_IF", "OP_NOTIF", "OP_VERIF", "OP_VERNOTIF", "OP_ELSE", "OP_ENDIF", "OP_VERIFY",
"OP_RETURN", "OP_TOALTSTACK", "OP_FROMALTSTACK", "OP_2DROP", "OP_2DUP", "OP_3DUP", "OP_2OVER", "OP_2ROT", "OP_2SWAP",
"OP_IFDUP", "OP_DEPTH", "OP_DROP", "OP_DUP", "OP_NIP", "OP_OVER", "OP_PICK", "OP_ROLL", "OP_ROT",
"OP_SWAP", "OP_TUCK", "OP_CAT", "OP_SUBSTR", "OP_LEFT", "OP_RIGHT", "OP_SIZE", "OP_INVERT", "OP_AND",
"OP_OR", "OP_XOR", "OP_EQUAL", "OP_EQUALVERIFY", "OP_RESERVED1", "OP_RESERVED2", "OP_1ADD", "OP_1SUB", "OP_2MUL",
"OP_2DIV", "OP_NEGATE", "OP_ABS", "OP_NOT", "OP_0NOTEQUAL", "OP_ADD", "OP_SUB", "OP_MUL", "OP_DIV",
"OP_MOD", "OP_LSHIFT", "OP_RSHIFT", "OP_BOOLAND", "OP_BOOLOR",
"OP_NUMEQUAL", "OP_NUMEQUALVERIFY", "OP_NUMNOTEQUAL", "OP_LESSTHAN",
"OP_GREATERTHAN", "OP_LESSTHANOREQUAL", "OP_GREATERTHANOREQUAL", "OP_MIN", "OP_MAX",
"OP_WITHIN", "OP_RIPEMD160", "OP_SHA1", "OP_SHA256", "OP_HASH160",
"OP_HASH256", "OP_CODESEPARATOR", "OP_CHECKSIG", "OP_CHECKSIGVERIFY", "OP_CHECKMULTISIG",
"OP_CHECKMULTISIGVERIFY",
("OP_SINGLEBYTE_END", 0xF0),
("OP_DOUBLEBYTE_BEGIN", 0xF000),
"OP_PUBKEY", "OP_PUBKEYHASH",
("OP_INVALIDOPCODE", 0xFFFF),
])
def script_GetOp(bytes):
i = 0
while i < len(bytes):
vch = None
opcode = ord(bytes[i])
i += 1
if opcode >= opcodes.OP_SINGLEBYTE_END:
opcode <<= 8
opcode |= ord(bytes[i])
i += 1
if opcode <= opcodes.OP_PUSHDATA4:
nSize = opcode
if opcode == opcodes.OP_PUSHDATA1:
nSize = ord(bytes[i])
i += 1
elif opcode == opcodes.OP_PUSHDATA2:
(nSize,) = struct.unpack_from('<H', bytes, i)
i += 2
elif opcode == opcodes.OP_PUSHDATA4:
(nSize,) = struct.unpack_from('<I', bytes, i)
i += 4
vch = bytes[i:i+nSize]
i += nSize
yield (opcode, vch, i)
def script_GetOpName(opcode):
return (opcodes.whatis(opcode)).replace("OP_", "")
def decode_script(bytes):
result = ''
for (opcode, vch, i) in script_GetOp(bytes):
if len(result) > 0: result += " "
if opcode <= opcodes.OP_PUSHDATA4:
result += "%d:"%(opcode,)
result += short_hex(vch)
else:
result += script_GetOpName(opcode)
return result
def match_decoded(decoded, to_match):
if len(decoded) != len(to_match):
return False;
for i in range(len(decoded)):
if to_match[i] == opcodes.OP_PUSHDATA4 and decoded[i][0] <= opcodes.OP_PUSHDATA4 and decoded[i][0]>0:
continue # Opcodes below OP_PUSHDATA4 all just push data onto stack, and are equivalent.
if to_match[i] != decoded[i][0]:
return False
return True
def get_address_from_input_script(bytes):
try:
decoded = [ x for x in script_GetOp(bytes) ]
except Exception:
# coinbase transactions raise an exception
print_error("cannot find address in input script", bytes.encode('hex'))
return [], {}, "(None)"
# payto_pubkey
match = [ opcodes.OP_PUSHDATA4 ]
if match_decoded(decoded, match):
return None, {}, "(pubkey)"
# non-generated TxIn transactions push a signature
# (seventy-something bytes) and then their public key
# (65 bytes) onto the stack:
match = [ opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4 ]
if match_decoded(decoded, match):
sig = decoded[0][1].encode('hex')
pubkey = decoded[1][1].encode('hex')
if sig[-2:] == '01':
sig = sig[:-2]
return [pubkey], {pubkey:sig}, public_key_to_bc_address(pubkey.decode('hex'))
else:
print_error("cannot find address in input script", bytes.encode('hex'))
return [], {}, "(None)"
# p2sh transaction, 2 of n
match = [ opcodes.OP_0 ]
while len(match) < len(decoded):
match.append(opcodes.OP_PUSHDATA4)
if match_decoded(decoded, match):
redeemScript = decoded[-1][1]
num = len(match) - 2
signatures = map(lambda x:x[1][:-1].encode('hex'), decoded[1:-1])
dec2 = [ x for x in script_GetOp(redeemScript) ]
# 2 of 2
match2 = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_2, opcodes.OP_CHECKMULTISIG ]
if match_decoded(dec2, match2):
pubkeys = [ dec2[1][1].encode('hex'), dec2[2][1].encode('hex') ]
return pubkeys, signatures, hash_160_to_bc_address(hash_160(redeemScript), 5)
# 2 of 3
match2 = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_3, opcodes.OP_CHECKMULTISIG ]
if match_decoded(dec2, match2):
pubkeys = [ dec2[1][1].encode('hex'), dec2[2][1].encode('hex'), dec2[3][1].encode('hex') ]
return pubkeys, signatures, hash_160_to_bc_address(hash_160(redeemScript), 5)
print_error("cannot find address in input script", bytes.encode('hex'))
return [], {}, "(None)"
def get_address_from_output_script(bytes):
decoded = [ x for x in script_GetOp(bytes) ]
# The Genesis Block, self-payments, and pay-by-IP-address payments look like:
# 65 BYTES:... CHECKSIG
match = [ opcodes.OP_PUSHDATA4, opcodes.OP_CHECKSIG ]
if match_decoded(decoded, match):
return True, public_key_to_bc_address(decoded[0][1])
# Pay-by-Bitcoin-address TxOuts look like:
# DUP HASH160 20 BYTES:... EQUALVERIFY CHECKSIG
match = [ opcodes.OP_DUP, opcodes.OP_HASH160, opcodes.OP_PUSHDATA4, opcodes.OP_EQUALVERIFY, opcodes.OP_CHECKSIG ]
if match_decoded(decoded, match):
return False, hash_160_to_bc_address(decoded[2][1])
# p2sh
match = [ opcodes.OP_HASH160, opcodes.OP_PUSHDATA4, opcodes.OP_EQUAL ]
if match_decoded(decoded, match):
return False, hash_160_to_bc_address(decoded[1][1],5)
return False, "(None)"
class Transaction:
def __init__(self, raw):
self.raw = raw
self.deserialize()
self.inputs = self.d['inputs']
self.outputs = self.d['outputs']
self.outputs = map(lambda x: (x['address'],x['value']), self.outputs)
self.locktime = self.d['lockTime']
def __str__(self):
return self.raw
@classmethod
def from_io(klass, inputs, outputs):
raw = klass.serialize(inputs, outputs, for_sig = None) # for_sig=-1 means do not sign
self = klass(raw)
self.inputs = inputs
self.outputs = outputs
return self
@classmethod
def sweep(klass, privkeys, network, to_address, fee):
inputs = []
for privkey in privkeys:
pubkey = public_key_from_private_key(privkey)
address = address_from_private_key(privkey)
u = network.synchronous_get([ ('blockchain.address.listunspent',[address])])[0]
pay_script = klass.pay_script(address)
for item in u:
item['scriptPubKey'] = pay_script
item['redeemPubkey'] = pubkey
item['address'] = address
item['prevout_hash'] = item['tx_hash']
item['prevout_n'] = item['tx_pos']
inputs += u
if not inputs:
return
total = sum( map(lambda x:int(x.get('value')), inputs) ) - fee
outputs = [(to_address, total)]
self = klass.from_io(inputs, outputs)
self.sign({ pubkey:privkey })
return self
@classmethod
def multisig_script(klass, public_keys, num=None):
n = len(public_keys)
if num is None: num = n
# supports only "2 of 2", and "2 of 3" transactions
assert num <= n and n in [2,3]
if num==2:
s = '52'
elif num == 3:
s = '53'
else:
raise
for k in public_keys:
s += var_int(len(k)/2)
s += k
if n==2:
s += '52'
elif n==3:
s += '53'
else:
raise
s += 'ae'
return s
@classmethod
def pay_script(self, addr):
addrtype, hash_160 = bc_address_to_hash_160(addr)
if addrtype == 70:
script = '76a9' # op_dup, op_hash_160
script += '14' # push 0x14 bytes
script += hash_160.encode('hex')
script += '88ac' # op_equalverify, op_checksig
elif addrtype == 125:
script = 'a9' # op_hash_160
script += '14' # push 0x14 bytes
script += hash_160.encode('hex')
script += '87' # op_equal
else:
raise
return script
@classmethod
def serialize( klass, inputs, outputs, for_sig = None ):
push_script = lambda x: op_push(len(x)/2) + x
s = int_to_hex(1,4) # version
s += var_int( len(inputs) ) # number of inputs
for i in range(len(inputs)):
txin = inputs[i]
s += txin['prevout_hash'].decode('hex')[::-1].encode('hex') # prev hash
s += int_to_hex(txin['prevout_n'],4) # prev index
signatures = txin.get('signatures', {})
if for_sig is None and not signatures:
script = ''
elif for_sig is None:
pubkeys = txin['pubkeys']
sig_list = ''
for pubkey in pubkeys:
sig = signatures.get(pubkey)
if not sig:
continue
sig = sig + '01'
sig_list += push_script(sig)
if not txin.get('redeemScript'):
script = sig_list
script += push_script(pubkeys[0])
else:
script = '00' # op_0
script += sig_list
redeem_script = klass.multisig_script(pubkeys,2)
assert redeem_script == txin.get('redeemScript')
script += push_script(redeem_script)
elif for_sig==i:
if txin.get('redeemScript'):
script = txin['redeemScript'] # p2sh uses the inner script
else:
script = txin['scriptPubKey'] # scriptsig
else:
script = ''
s += var_int( len(script)/2 ) # script length
s += script
s += "ffffffff" # sequence
s += var_int( len(outputs) ) # number of outputs
for output in outputs:
addr, amount = output
s += int_to_hex( amount, 8) # amount
script = klass.pay_script(addr)
s += var_int( len(script)/2 ) # script length
s += script # script
s += int_to_hex(0,4) # lock time
if for_sig is not None and for_sig != -1:
s += int_to_hex(1, 4) # hash type
return s
def tx_for_sig(self,i):
return self.serialize(self.inputs, self.outputs, for_sig = i)
def hash(self):
return Hash(self.raw.decode('hex') )[::-1].encode('hex')
def add_signature(self, i, pubkey, sig):
txin = self.inputs[i]
signatures = txin.get("signatures",{})
signatures[pubkey] = sig
txin["signatures"] = signatures
self.inputs[i] = txin
print_error("adding signature for", pubkey)
self.raw = self.serialize( self.inputs, self.outputs )
def is_complete(self):
for i, txin in enumerate(self.inputs):
redeem_script = txin.get('redeemScript')
num, redeem_pubkeys = parse_redeemScript(redeem_script) if redeem_script else (1, [txin.get('redeemPubkey')])
signatures = txin.get("signatures",{})
if len(signatures) == num:
continue
else:
return False
return True
def sign(self, keypairs):
print_error("tx.sign(), keypairs:", keypairs)
for i, txin in enumerate(self.inputs):
# if the input is multisig, parse redeem script
redeem_script = txin.get('redeemScript')
num, redeem_pubkeys = parse_redeemScript(redeem_script) if redeem_script else (1, [txin.get('redeemPubkey')])
# add pubkeys
txin["pubkeys"] = redeem_pubkeys
# get list of already existing signatures
signatures = txin.get("signatures",{})
# continue if this txin is complete
if len(signatures) == num:
continue
for_sig = Hash(self.tx_for_sig(i).decode('hex'))
for pubkey in redeem_pubkeys:
if pubkey in keypairs.keys():
# add signature
sec = keypairs[pubkey]
pkey = regenerate_key(sec)
secexp = pkey.secret
private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
public_key = private_key.get_verifying_key()
sig = private_key.sign_digest_deterministic( for_sig, hashfunc=hashlib.sha256, sigencode = ecdsa.util.sigencode_der )
assert public_key.verify_digest( sig, for_sig, sigdecode = ecdsa.util.sigdecode_der)
self.add_signature(i, pubkey, sig.encode('hex'))
print_error("is_complete", self.is_complete())
self.raw = self.serialize( self.inputs, self.outputs )
def deserialize(self):
vds = BCDataStream()
vds.write(self.raw.decode('hex'))
d = {}
start = vds.read_cursor
d['version'] = vds.read_int32()
n_vin = vds.read_compact_size()
d['inputs'] = []
for i in xrange(n_vin):
d['inputs'].append(self.parse_input(vds))
n_vout = vds.read_compact_size()
d['outputs'] = []
for i in xrange(n_vout):
d['outputs'].append(self.parse_output(vds, i))
d['lockTime'] = vds.read_uint32()
self.d = d
return self.d
def parse_input(self, vds):
d = {}
prevout_hash = hash_encode(vds.read_bytes(32))
prevout_n = vds.read_uint32()
scriptSig = vds.read_bytes(vds.read_compact_size())
sequence = vds.read_uint32()
if prevout_hash == '00'*32:
d['is_coinbase'] = True
else:
d['is_coinbase'] = False
d['prevout_hash'] = prevout_hash
d['prevout_n'] = prevout_n
d['sequence'] = sequence
if scriptSig:
pubkeys, signatures, address = get_address_from_input_script(scriptSig)
else:
pubkeys = []
signatures = {}
address = None
d['address'] = address
d['pubkeys'] = pubkeys
d['signatures'] = signatures
return d
def parse_output(self, vds, i):
d = {}
d['value'] = vds.read_int64()
scriptPubKey = vds.read_bytes(vds.read_compact_size())
is_pubkey, address = get_address_from_output_script(scriptPubKey)
d['is_pubkey'] = is_pubkey
d['address'] = address
d['scriptPubKey'] = scriptPubKey.encode('hex')
d['prevout_n'] = i
return d
def add_extra_addresses(self, txlist):
for i in self.inputs:
if i.get("address") == "(pubkey)":
prev_tx = txlist.get(i.get('prevout_hash'))
if prev_tx:
address, value = prev_tx.outputs[i.get('prevout_n')]
print_error("found pay-to-pubkey address:", address)
i["address"] = address
def has_address(self, addr):
found = False
for txin in self.inputs:
if addr == txin.get('address'):
found = True
break
for txout in self.outputs:
if addr == txout[0]:
found = True
break
return found
def get_value(self, addresses, prevout_values):
# return the balance for that tx
is_relevant = False
is_send = False
is_pruned = False
is_partial = False
v_in = v_out = v_out_mine = 0
<|fim▁hole|> if addr in addresses:
is_send = True
is_relevant = True
key = item['prevout_hash'] + ':%d'%item['prevout_n']
value = prevout_values.get( key )
if value is None:
is_pruned = True
else:
v_in += value
else:
is_partial = True
if not is_send: is_partial = False
for item in self.outputs:
addr, value = item
v_out += value
if addr in addresses:
v_out_mine += value
is_relevant = True
if is_pruned:
# some inputs are mine:
fee = None
if is_send:
v = v_out_mine - v_out
else:
# no input is mine
v = v_out_mine
else:
v = v_out_mine - v_in
if is_partial:
# some inputs are mine, but not all
fee = None
is_send = v < 0
else:
# all inputs are mine
fee = v_out - v_in
return is_relevant, is_send, v, fee
def get_input_info(self):
keys = ['prevout_hash', 'prevout_n', 'address', 'KeyID', 'scriptPubKey', 'redeemScript', 'redeemPubkey', 'pubkeys', 'signatures', 'is_coinbase']
info = []
for i in self.inputs:
item = {}
for k in keys:
v = i.get(k)
if v is not None:
item[k] = v
info.append(item)
return info
def as_dict(self):
import json
out = {
"hex":self.raw,
"complete":self.is_complete()
}
if not self.is_complete():
input_info = self.get_input_info()
out['input_info'] = json.dumps(input_info).replace(' ','')
return out
def required_fee(self, verifier):
# see https://en.bitcoin.it/wiki/Transaction_fees
threshold = 57600000*4
size = len(self.raw)/2
fee = 0
for o in self.outputs:
value = o[1]
if value < DUST_SOFT_LIMIT:
fee += MIN_RELAY_TX_FEE
sum = 0
for i in self.inputs:
age = verifier.get_confirmations(i["prevout_hash"])[0]
sum += i["value"] * age
priority = sum / size
print_error(priority, threshold)
if size < 5000 and fee == 0 and priority > threshold:
return 0
fee += (1 + size / 1000) * MIN_RELAY_TX_FEE
print_error(fee)
return fee
def add_input_info(self, input_info):
for i, txin in enumerate(self.inputs):
item = input_info[i]
txin['scriptPubKey'] = item['scriptPubKey']
txin['redeemScript'] = item.get('redeemScript')
txin['redeemPubkey'] = item.get('redeemPubkey')
txin['KeyID'] = item.get('KeyID')
txin['signatures'] = item.get('signatures',{})<|fim▁end|> | for item in self.inputs:
addr = item.get('address') |
<|file_name|>unsized5.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test `?Sized` types not allowed in fields (except the last one).
struct S1<X: ?Sized> {
f1: X, //~ ERROR `core::marker::Sized` is not implemented
f2: int,
}
struct S2<X: ?Sized> {
f: int,
g: X, //~ ERROR `core::marker::Sized` is not implemented
h: int,
}
struct S3 {
f: str, //~ ERROR `core::marker::Sized` is not implemented
g: [uint]
}
struct S4 {
f: str, //~ ERROR `core::marker::Sized` is not implemented
g: uint
}
enum E<X: ?Sized> {<|fim▁hole|>enum F<X: ?Sized> {
V2{f1: X, f: int}, //~ERROR `core::marker::Sized` is not implemented
}
pub fn main() {
}<|fim▁end|> | V1(X, int), //~ERROR `core::marker::Sized` is not implemented
} |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.administrator_page),
url(r'^new_jd/$', views.new_jd_page),
url(r'^test_data/refresh/$', views.test_data_refresh),
url(r'^jd/(?P<jd_id>\d+)/delete/', views.delete_jd),
url(r'^jd/(?P<jd_id>\d+)/create/$', views.create_jd),<|fim▁hole|> url(r'^ssh_key/(?P<ssh_key_id>\d+)/delete/', views.delete_ssh_key),
url(r'^ssh_key/(?P<ssh_key_id>\d+)/create/$', views.create_ssh_key),
url(r'^new_parameter/$', views.new_parameter_page),
url(r'^parameters/(?P<param_id>\d+)/delete/', views.delete_parameter),
url(r'^parameters/(?P<param_id>\d+)/create/$', views.create_parameter),
]<|fim▁end|> | url(r'^new_ssh_key/$', views.new_ssh_key_page), |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># views
# Routes for the ELMR web application
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Thu Apr 09 09:13:29 2015 -0400
#
# Copyright (C) 2015 University of Maryland
# For license information, see LICENSE.txt
#
# ID: views.py [] benjamin@bengfort.com $
"""
Routes for the ELMR web application
"""
##########################################################################
## Imports
##########################################################################
import os
import StringIO
from elmr import get_version
from elmr import app, api, db
from elmr.models import IngestionRecord
from elmr.models import Series, SeriesRecord, StateSeries, USAState
from elmr.utils import JSON_FMT, utcnow, months_since, slugify, parse_bool
from elmr.fips import write_states_dataset
from flask import request, make_response
from flask.ext.restful import Resource, reqparse
from flask import render_template, send_from_directory
from urlparse import urljoin
from operator import itemgetter
from collections import defaultdict
from sqlalchemy import desc, extract
##########################################################################
## Configure Application Routes
##########################################################################
@app.route("/")
def index():
sources = (
("CPS", Series.query.filter_by(source="CPS").order_by('title')),
("CESN", Series.query.filter_by(source="CESN").order_by('title')),
("LAUS", Series.query.filter_by(source="LAUS").order_by('title')),
("CESSM", Series.query.filter_by(source="CESSM").order_by('title')),
)
return render_template('home.html', sources=sources)
@app.route("/admin/")
def admin():
ingestions = IngestionRecord.query.order_by(desc("id")).limit(20)
dbcounts = {
"series": Series.query.count(),
"records": SeriesRecord.query.count(),
"ingests": IngestionRecord.query.count(),
"states_series": StateSeries.query.count(),
}
dbversion = list(db.session.execute("SELECT * FROM migrate_version"))[0]
return render_template('admin.html', ingestlog=ingestions,
dbcounts=dbcounts, dbversion=dbversion)
@app.route('/favicon.ico')
def favicon():
dirname = os.path.join(app.root_path, 'static')
return send_from_directory(dirname, 'favicon.ico',
mimetype='image/vnd.microsoft.icon')
## Development Pages
@app.route('/assaf/')
def assaf_dev():
"""
Assaf - add any context you need for your page here.
"""
return render_template('development/assaf.html')
@app.route('/benjamin/')
def benjamin_dev():
"""
Used for Ben's independent development
"""
return render_template('development/benjamin.html')
##########################################################################
## Configure Series-Related API Resources
##########################################################################
class SeriesView(Resource):
"""
API for getting the detail of a single time series object, probably won't
be used for our project, but available so that we can quickly get info.
"""
@property
def parser(self):
"""
Returns the default parser for the SeriesView
"""
if not hasattr(self, '_parser'):
self._parser = reqparse.RequestParser()
self._parser.add_argument('start_year', type=int)
self._parser.add_argument('end_year', type=int)
self._parser.add_argument('delta', type=str)
return self._parser
@property
def detail_parser(self):
"""
Returns the detail parser for the SeriesView (for PUT)
"""
if not hasattr(self, '_detail_parser'):
self._detail_parser = reqparse.RequestParser()
self._detail_parser.add_argument('title', type=str, required=True)
return self._detail_parser
def get(self, blsid):
"""
Returns the Series detail for a given blsid.
"""
args = self.parser.parse_args()
series = Series.query.filter_by(blsid=blsid).first_or_404()
context = {
"blsid": series.blsid,
"source": series.source,
"title": series.title,
"data": [],
}
start = args.get('start_year', None)
finish = args.get('end_year', None)
delta = parse_bool(args.get('delta', False))
serid = series.id
if delta:
# Switch to the delta view of the time series
if series.delta:
serid = series.delta.id
# Start the records query
records = SeriesRecord.query.filter_by(series_id=serid)
ryear = extract('year', SeriesRecord.period)
if start is not None:
records = records.filter(ryear >= start)
if finish is not None:
records = records.filter(ryear <= finish)
# Serialize the records
for record in records.all():
context['data'].append({
"period": record.period.strftime("%b %Y"),
"value": record.value
})
return context
def put(self, blsid):
"""
Allows you to update the title of a BLS series
"""
series = Series.query.filter_by(blsid=blsid).first_or_404()
args = self.detail_parser.parse_args()
if not args.get('title', None):
return {"message": "[title]: cannot be an empty string or None"}, 400
series.title = args['title']
db.session.commit()
return {
'blsid': series.blsid,
'source': series.source,
'title': series.title,
}
class SeriesListView(Resource):
"""
API for returning a list of time series objects.
"""
@property
def parser(self):
"""
Returns the default parser for the SeriesView
"""
if not hasattr(self, '_parser'):
self._parser = reqparse.RequestParser()
self._parser.add_argument('page', type=int)
self._parser.add_argument('per_page', type=int)
self._parser.add_argument('source', type=str)
return self._parser
def get(self):
"""
Returns a list of the Series objects.
"""
args = self.parser.parse_args()
page = args.page or 1
per_page = args.per_page or 20
source = args.source
if source is not None:
series = Series.query.filter_by(source=source)
series = series.paginate(page, per_page)
else:
series = Series.query.paginate(page, per_page)
context = {
"page": series.page,
"pages": series.pages,
"per_page": series.per_page,
"total": series.total,
"series": [],
}
for item in series.items:
context["series"].append({
"url": self.get_detail_url(item.blsid),
"blsid": item.blsid,
"title": item.title,
"source": item.source,
})
return context
def get_detail_url(self, blsid):
"""
Returns the blsid from the request object.
"""
base = request.url_root
return urljoin(base, "/api/series/%s/" % blsid)
class SourceView(Resource):
"""
Another list view which returns all of the timeseries for a given source.
At the moment, only two sources are accepted: CESN (CES - National) and
CPS. LAUS and CESSM (CES - State and Metro) are state based APIs and
cannot be returned in aggregate as the national sources can.
TODO: Move allowed sources to the database.
"""
ALLOWED_SOURCES = set(["CESN", "CPS"])
FORBIDDEN_SOURCES = set(["LAUS", "CESSM"])
@property
def parser(self):
"""
Returns the default parser for the SeriesView
"""
if not hasattr(self, '_parser'):
self._parser = reqparse.RequestParser()
self._parser.add_argument('start_year', type=int)
self._parser.add_argument('end_year', type=int)
return self._parser
def get(self, source):
"""
For a single source, return a data detail view for all time series.
"""
# Ensure that source is allowed
source = source.upper()
if source in self.FORBIDDEN_SOURCES:
context = {
'success': False,
'message': "Source '%s' is not allowed." % source,
}
return context, 400
if source not in self.ALLOWED_SOURCES:
context = {
'success': False,
'message': "Source '%s' is not found." % source,
}
return context, 404
args = self.parser.parse_args()
series = Series.query.filter_by(source=source)
start = args.start_year or int(app.config['STARTYEAR'])
finish = args.end_year or int(app.config['ENDYEAR'])
context = {
"title": "ELMR Ingested %s Data" % source,
"version": get_version(),
"period": {
"start": start,
"end": finish,
},
"descriptions": {},
"data": [],
}
data = defaultdict(dict)
for s in series.all():
context["descriptions"][s.blsid] = s.title
records = SeriesRecord.query.filter_by(series_id=s.id)
ryear = extract('year', SeriesRecord.period)
records = records.filter(ryear >= start)
records = records.filter(ryear <= finish)
for record in records.all():
data[record.period][s.blsid] = record.value
data = sorted(data.items(), key=itemgetter(0))
for (date, values) in data:
values["YEAR"] = date.year
values["MONTH"] = date.month
values["DATE"] = date.strftime("%b %Y")
context["data"].append(values)
context['period']['start'] = data[0][0].strftime("%b %Y")
context['period']['end'] = data[-1][0].strftime("%b %Y")
return context
class SourceListView(Resource):
"""
API Resource for returning a list of sources.
"""
def get(self):
context = {
"sources": []
}
# Create sources model in the future
sql = "SELECT source, count(id) FROM series GROUP BY source"
for s in db.session.execute(sql):
context["sources"].append({
"url": self.get_detail_url(s[0]),
"name": s[0],
"records": s[1],
})
return context
def get_detail_url(self, name):
"""
Returns the blsid from the request object.
"""
base = request.url_root
return urljoin(base, "/api/source/%s/" % name)
##########################################################################
## Configure Geography-Related API Resources
##########################################################################
ALLOWED_GEO_SOURCES = set(["LAUS", "CESSM"])
FORBIDDEN_GEO_SOURCES = set(["CESN", "CPS"])
class GeoSourcesView(Resource):
"""
Returns the availabe sources for geography based API lookups.
"""
def get(self):
"""
Returns all the distinct sources and their urls
"""
context = {
"title": "Geographic BLS Sources",
"sources": [],
}
query = "SELECT DISTINCT source FROM states_series"
for row in db.session.execute(query):
context["sources"].append({
"name": row[0],
"url": self.get_detail_url(row[0]),
})
return context
def get_detail_url(self, source):
"""
Returns the blsid from the request object.
"""
base = request.url_root
return urljoin(base, "/api/geo/%s/" % source)
<|fim▁hole|> """
Returns the available datasets for a geo resource.
"""
def get(self, source):
"""
For a given source, returns the available datasets and their counts.
"""
# Ensure that source is allowed
source = source.upper()
if source in FORBIDDEN_GEO_SOURCES:
context = {
'success': False,
'message': "Source '%s' is not allowed." % source,
}
return context, 400
if source not in ALLOWED_GEO_SOURCES:
context = {
'success': False,
'message': "Source '%s' is not found." % source,
}
return context, 404
query = "SELECT distinct %s FROM states_series WHERE source='%s'"
field = {
"LAUS": "dataset",
"CESSM": "category",
}[source]
query = query % (field, source)
context = {
"title": "ELMR %s Datasets" % source,
"field": field,
"datasets": []
}
for row in db.session.execute(query):
context["datasets"].append({
"name": row[0],
"url": self.get_detail_url(source, row[0]),
})
return context
def get_detail_url(self, source, dataset):
"""
Returns the blsid from the request object.
"""
base = request.url_root
return urljoin(base, "/api/geo/%s/%s/" % (source, slugify(dataset)))
@app.route('/api/geo/<source>/<dataset>/')
def geography_csv(source, dataset):
"""
Returns a CSV data set for the specified source and dataset. Note that this
must be a Flask route function and not a RESTful class because the returned
datatype is CSV and not JSON.
"""
source = source.upper()
# Get arguments
start_year = request.args.get('start_year', app.config['STARTYEAR'])
end_year = request.args.get('end_year', app.config['ENDYEAR'])
is_adjust = parse_bool(request.args.get('is_adjusted', True))
is_delta = parse_bool(request.args.get('is_delta', False))
try:
start_year = int(start_year)
end_year = int(end_year)
except ValueError:
return make_response("Bad value for start or end year parameter"), 400
if source in FORBIDDEN_GEO_SOURCES:
return make_response("Source '%s' is not geographic." % source), 400
if source not in ALLOWED_GEO_SOURCES:
return make_response("Unknown data source -- '%s'" % source), 404
# Determine the series from the source and the dataset
# Create a file-like object for the CSV to return, then write the series
csv = StringIO.StringIO()
write_states_dataset(csv, source, dataset,
start_year, end_year,
is_adjust, is_delta)
output = make_response(csv.getvalue())
output.headers["Content-Disposition"] = "attachment; filename=%s.csv" % dataset
output.headers["Content-Type"] = "text/csv"
return output
##########################################################################
## Configure Wealth of Nations API Resources
##########################################################################
class WealthOfNationsView(Resource):
"""
Provides state information according to the Wealth of Nations format.
"""
@property
def parser(self):
"""
Returns the default parser for the WealthOfNationsView
"""
if not hasattr(self, '_parser'):
self._parser = reqparse.RequestParser()
self._parser.add_argument('start_year', type=int, default=2000)
self._parser.add_argument('end_year', type=int, default=2015)
self._parser.add_argument('adjusted', type=bool, default=False)
return self._parser
def get(self):
context = []
args = self.parser.parse_args()
adjusted = args.adjusted
for state in USAState.query.order_by('name').all():
context.append({
"name": state.name,
"region": state.region,
# Temporary names
"income": [],
"population": [],
"lifeExpectancy": [],
})
# Handle Datasets (temporary names for now)
datamap = {
"income": u"labor-force",
"population": u"employment",
"lifeExpectancy": u"unemployment-rate",
}
for key, slug in datamap.items():
ss = state.series.filter_by(slug=slug)
ss = ss.filter_by(adjusted=adjusted, source="LAUS")
ss = ss.first()
for record in ss.series.records.order_by('period'):
context[-1][key].append([
record.period.strftime("%b %Y"),
record.value
])
return context
##########################################################################
## Heartbeat resource
##########################################################################
class HeartbeatView(Resource):
"""
Keep alive endpoint, if you get a 200 response, you know ELMR is alive!
Also gives important status information like the version of ELMR, last
ingestion time and so forth.
"""
def get(self):
context = {
'status': "white",
'version': get_version(),
'timestamps': {
'current': utcnow().strftime(JSON_FMT),
}
}
latest = IngestionRecord.query.order_by(desc('finished')).first()
if latest is not None:
months = months_since(latest.finished)
if months < 2:
context["status"] = "green"
elif months < 7:
context["status"] = "yellow"
else:
context["status"] = "red"
tsfields = context['timestamps']
tsfields['ingestion'] = latest.finished.strftime(JSON_FMT)
tsfields['monthdelta'] = months
return context
##########################################################################
## API Endpoints resource
##########################################################################
class APIListView(Resource):
"""
Returns a list of API endpoints and their names. Currently hardcoded,
so this needs to be modified every time you add a resource to the API.
"""
RESOURCES = {
"heartbeat": "status",
"sources": "source",
"series": "series",
"geography": "geo",
"wealth of nations": "regions"
}
def get(self):
"""
Returns an object describing the API.
"""
return dict([(k, self.get_detail_url(v))
for (k, v) in self.RESOURCES.items()])
def get_detail_url(self, name):
"""
Returns the blsid from the request object.
"""
base = request.url_root
return urljoin(base, "/api/%s/" % name)
##########################################################################
## Configure API Endpoints
##########################################################################
# reduce the amount of typing
endpoint = api.add_resource
# configure api urls
endpoint(APIListView, '/api/')
endpoint(SourceListView, '/api/source/', endpoint='source-list')
endpoint(SourceView, '/api/source/<source>/', endpoint='source-detail')
endpoint(HeartbeatView, '/api/status/', endpoint="status-detail")
endpoint(SeriesListView, '/api/series/', endpoint='series-list')
endpoint(SeriesView, '/api/series/<blsid>/', endpoint='series-detail')
endpoint(GeoSourcesView, '/api/geo/', endpoint='geography-list')
endpoint(GeoDatasetsView, '/api/geo/<source>/', endpoint='geography-datasets')
endpoint(WealthOfNationsView, '/api/regions/', endpoint='wealth-of-nations')
# Did you forget to modify the API list view?<|fim▁end|> | class GeoDatasetsView(Resource): |
<|file_name|>filters.py<|end_file_name|><|fim▁begin|>import django_filters
from django_filters import rest_framework as filters<|fim▁hole|>
from django_rv_apps.apps.believe_his_prophets.models.book import Book
from django_rv_apps.apps.believe_his_prophets.models.bible_read import BibleRead
from django_rv_apps.apps.believe_his_prophets.models.testament import Testament
class BookFilter(django_filters.FilterSet):
testament = filters.ModelChoiceFilter(
queryset=Testament.objects.all())
class Meta:
model = Book
fields = ('id', 'testament',
'book_order')<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|># 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.
"""Race dataset."""
from tensorflow_datasets.text.race.race import Race<|fim▁end|> | # coding=utf-8
# Copyright 2022 The TensorFlow Datasets Authors.
# |
<|file_name|>analysis.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2013 Stanislav Bohm
#
# This file is part of Kaira.
#
# Kaira 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, version 3 of the License, or
# (at your option) any later version.
#
# Kaira 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 Kaira. If not, see <http://www.gnu.org/licenses/>.
#
import utils
def all_free_variables(edges):
return utils.unions(edges, lambda edge: edge.get_free_vars())
def get_variable_sources(inscriptions):
sources = {}
for inscription in inscriptions:
if not inscription.is_expr_variable():
continue
if sources.get(inscription.expr):
continue
if inscription.is_bulk():
sources[inscription.expr] = None
else:
sources[inscription.expr] = inscription.uid
return sources
def is_dependant(inscription1, inscription2):
if inscription1.edge is inscription2.edge and \
inscription2.index < inscription1.index:
return True
if not inscription2.is_expr_variable():
return False
return inscription2.expr in inscription1.get_foreign_variables()
def analyze_transition(tr):
variable_sources = {} # string -> uid - which inscriptions carry input variables
reuse_tokens = {} # uid -> uid - identification number of token for output inscpription
fresh_tokens = [] # (uid, type) - what tokens has to be created for output
used_tokens = [] # [uid] - Tokens from input inscriptions that are reused on output
variable_sources_out = {} # string -> uid or None
bulk_overtake = [] # [uid]
overtaken_variables = set()
def inscription_out_weight(inscription):
# Reorder edges, bulk edges first because we want them send first
# Otherwise it can cause problems like in sending results in "workers" example
s = inscription.config.get("seq")
if s is None:
seq = 0
else:
seq = int(s) * 3
if inscription.is_bulk():
return seq
# Unconditional edges has higher priority
if inscription.is_conditioned():
return seq + 2
else:
return seq + 1
def inscription_in_weight(inscription):
if inscription.is_conditioned():
return 1
else:
return 0
inscriptions_in = sum((edge.inscriptions for edge in tr.edges_in), [])
inscriptions_in.sort(key=inscription_in_weight)
inscriptions_out = sum((edge.inscriptions for edge in tr.edges_out), [])
inscriptions_out.sort(key=inscription_out_weight)
variable_sources = get_variable_sources(inscriptions_in)
# Order input inscriptions by variable dependancy
inscriptions_in = utils.topological_ordering(inscriptions_in, is_dependant)
if inscriptions_in is None:
raise utils.PtpException("Circle variable dependancy", tr.get_source())
# Try reuse tokens
for inscription in inscriptions_out:
if inscription.is_bulk() or not inscription.is_local():
continue # Bulk and nonlocal edge cannot use token reusage
if not inscription.is_expr_variable():
continue # Current implementation reuses tokens only for variable expression<|fim▁hole|> # Variable is not taken from input as token
# or token is already reused --> reusage not possible
continue
reuse_tokens[inscription.uid] = token_uid
used_tokens.append(token_uid)
# Setup fresh variables where token was not reused
for inscription in inscriptions_out:
if not inscription.is_expr_variable():
continue # We are interested only in variables
variable = inscription.expr
if variable in variable_sources:
# Variable take from input so we do not have to deal here with it
continue
if variable in variable_sources_out:
# Variable already prepared for output
continue
if inscription.is_bulk():
# No token, just build variable
variable_sources_out[variable] = None
continue
if inscription.is_local():
# Local send, we prepare token
fresh_tokens.append((inscription.uid, inscription.edge.place.type))
variable_sources_out[variable] = inscription.uid
reuse_tokens[inscription.uid] = inscription.uid # Use this fresh new token
else:
# Just create variable
variable_sources_out[variable] = None
for inscription in reversed(inscriptions_out):
# Now we are checking overtake. It has to be in reversed order
# becacase overtake has to be the last operation on variable
if not inscription.is_bulk() or not inscription.is_expr_variable():
continue # We are interested only in variables and bulk inscriptions
if inscription.expr not in overtaken_variables:
overtaken_variables.add(inscription.expr)
bulk_overtake.append(inscription.uid)
for inscription in inscriptions_out:
for variable in inscription.get_other_variables():
if variable not in variable_sources and \
variable not in variable_sources_out:
variable_sources_out[variable] = None
tr.inscriptions_in = inscriptions_in
tr.inscriptions_out = inscriptions_out
tr.variable_sources = variable_sources
tr.reuse_tokens = reuse_tokens
tr.variable_sources_out = variable_sources_out
tr.fresh_tokens = fresh_tokens
tr.bulk_overtake = bulk_overtake<|fim▁end|> | if inscription.is_collective():
continue # Collective operations cannot use token reusage
token_uid = variable_sources.get(inscription.expr)
if token_uid is None or token_uid in used_tokens: |
<|file_name|>createSections.js<|end_file_name|><|fim▁begin|>'use strict';
var path = require('path');
var fs = require('fs');
module.exports = function(gen,cb) {
var sections;
if (gen.config.get('framework')==='bigwheel') {
var model = require(path.join(process.cwd(),'src/model/index.js'));
sections = ['Preloader'];
Object.keys(model).forEach(function(key) {
if (key.charAt(0)==="/") sections.push(key.substr(1) || 'Landing');
});
} else {
sections = ['Landing'];
}
nextSection(sections,gen,cb);
};
function nextSection(arr,gen,cb) {
if (arr.length>0) {
createSection(arr.shift(),gen,function() {
nextSection(arr,gen,cb);
});
} else {
if (cb) cb();
}
}
function createSection(cur,gen,cb) {
var name = gen.config.get('sectionNames') ? '{{section}}.js' : 'index.js';
var style = gen.config.get('sectionNames') ? '{{section}}.{{css}}' : 'style.{{css}}';
var count = 0;
var total = 0;
var done = function() {
count++;
if (count>=total) cb();
};
fs.stat('src/sections/'+cur+'/',function(err,stat) {
if (err) {
gen.config.set('section',cur);
if (gen.config.get('framework')==='bigwheel') {
var type = cur==='Preloader' ? 'preloader' : 'normal';
gen.copy('templates/sections/{{framework}}/'+type+'/index.js','src/sections/{{section}}/'+name,done);
gen.copy('templates/sections/{{framework}}/'+type+'/style.css','src/sections/{{section}}/'+style,done);
gen.copy('templates/sections/{{framework}}/'+type+'/template.hbs','src/sections/{{section}}/template.hbs',done);
gen.copy('templates/.gitkeep','src/ui/{{section}}/.gitkeep',done);
total += 4;
} else if (gen.config.get('framework')==='react') {
gen.copy('templates/sections/{{framework}}/index.js','src/sections/{{section}}/'+name,done);
gen.copy('templates/sections/{{framework}}/style.css','src/sections/{{section}}/'+style,done);
total += 2;
}
} else {
done();
}<|fim▁hole|>};<|fim▁end|> | }); |
<|file_name|>AudioElement.js<|end_file_name|><|fim▁begin|>/* global PropertyFactory, extendPrototype, RenderableElement, BaseElement, FrameElement */
function AudioElement(data, globalData, comp) {
this.initFrame();
this.initRenderable();
this.assetData = globalData.getAssetData(data.refId);
this.initBaseData(data, globalData, comp);
this._isPlaying = false;
this._canPlay = false;
var assetPath = this.globalData.getAssetsPath(this.assetData);
this.audio = this.globalData.audioController.createAudio(assetPath);
this._currentTime = 0;
this.globalData.audioController.addAudio(this);
this.tm = data.tm ? PropertyFactory.getProp(this, data.tm, 0, globalData.frameRate, this) : { _placeholder: true };
}
AudioElement.prototype.prepareFrame = function (num) {
this.prepareRenderableFrame(num, true);
this.prepareProperties(num, true);
if (!this.tm._placeholder) {
var timeRemapped = this.tm.v;
this._currentTime = timeRemapped;
} else {
this._currentTime = num / this.data.sr;
}
};
extendPrototype([RenderableElement, BaseElement, FrameElement], AudioElement);
AudioElement.prototype.renderFrame = function () {
if (this.isInRange && this._canPlay) {
if (!this._isPlaying) {
this.audio.play();
this.audio.seek(this._currentTime / this.globalData.frameRate);
this._isPlaying = true;
} else if (!this.audio.playing()
|| Math.abs(this._currentTime / this.globalData.frameRate - this.audio.seek()) > 0.1
) {
this.audio.seek(this._currentTime / this.globalData.frameRate);
<|fim▁hole|>};
AudioElement.prototype.show = function () {
// this.audio.play()
};
AudioElement.prototype.hide = function () {
this.audio.pause();
this._isPlaying = false;
};
AudioElement.prototype.pause = function () {
this.audio.pause();
this._isPlaying = false;
this._canPlay = false;
};
AudioElement.prototype.resume = function () {
this._canPlay = true;
};
AudioElement.prototype.setRate = function (rateValue) {
this.audio.rate(rateValue);
};
AudioElement.prototype.volume = function (volumeValue) {
this.audio.volume(volumeValue);
};
AudioElement.prototype.getBaseElement = function () {
return null;
};
AudioElement.prototype.destroy = function () {
};
AudioElement.prototype.sourceRectAtTime = function () {
};
AudioElement.prototype.initExpressions = function () {
};<|fim▁end|> | }
}
|
<|file_name|>closure.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use back::abi;
use back::link::mangle_internal_name_by_path_and_seq;
use driver::config::FullDebugInfo;
use llvm::ValueRef;
use middle::def;
use middle::mem_categorization::Typer;
use middle::trans::adt;
use middle::trans::base::*;
use middle::trans::build::*;
use middle::trans::cleanup::{CleanupMethods, ScopeId};
use middle::trans::common::*;
use middle::trans::datum::{Datum, DatumBlock, Expr, Lvalue, rvalue_scratch_datum};
use middle::trans::debuginfo;
use middle::trans::expr;
use middle::trans::type_of::*;
use middle::trans::type_::Type;
use middle::ty;
use util::ppaux::Repr;
use util::ppaux::ty_to_string;
use arena::TypedArena;
use syntax::ast;
use syntax::ast_util;
// ___Good to know (tm)__________________________________________________
//
// The layout of a closure environment in memory is
// roughly as follows:
//
// struct rust_opaque_box { // see rust_internal.h
// unsigned ref_count; // obsolete (part of @T's header)
// fn(void*) *drop_glue; // destructor (for proc)
// rust_opaque_box *prev; // obsolete (part of @T's header)
// rust_opaque_box *next; // obsolete (part of @T's header)
// struct closure_data {
// upvar1_t upvar1;
// ...
// upvarN_t upvarN;
// }
// };
//
// Note that the closure is itself a rust_opaque_box. This is true
// even for ~fn and ||, because we wish to keep binary compatibility
// between all kinds of closures. The allocation strategy for this
// closure depends on the closure type. For a sendfn, the closure
// (and the referenced type descriptors) will be allocated in the
// exchange heap. For a fn, the closure is allocated in the task heap
// and is reference counted. For a block, the closure is allocated on
// the stack.
//
// ## Opaque closures and the embedded type descriptor ##
//
// One interesting part of closures is that they encapsulate the data
// that they close over. So when I have a ptr to a closure, I do not
// know how many type descriptors it contains nor what upvars are
// captured within. That means I do not know precisely how big it is
// nor where its fields are located. This is called an "opaque
// closure".
//
// Typically an opaque closure suffices because we only manipulate it
// by ptr. The routine Type::at_box().ptr_to() returns an appropriate
// type for such an opaque closure; it allows access to the box fields,
// but not the closure_data itself.
//
// But sometimes, such as when cloning or freeing a closure, we need
// to know the full information. That is where the type descriptor
// that defines the closure comes in handy. We can use its take and
// drop glue functions to allocate/free data as needed.
//
// ## Subtleties concerning alignment ##
//
// It is important that we be able to locate the closure data *without
// knowing the kind of data that is being bound*. This can be tricky
// because the alignment requirements of the bound data affects the
// alignment requires of the closure_data struct as a whole. However,
// right now this is a non-issue in any case, because the size of the
// rust_opaque_box header is always a multiple of 16-bytes, which is
// the maximum alignment requirement we ever have to worry about.
//
// The only reason alignment matters is that, in order to learn what data
// is bound, we would normally first load the type descriptors: but their
// location is ultimately depend on their content! There is, however, a
// workaround. We can load the tydesc from the rust_opaque_box, which
// describes the closure_data struct and has self-contained derived type
// descriptors, and read the alignment from there. It's just annoying to
// do. Hopefully should this ever become an issue we'll have monomorphized
// and type descriptors will all be a bad dream.
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pub struct EnvValue {
action: ast::CaptureClause,
datum: Datum<Lvalue>
}
impl EnvValue {
pub fn to_string(&self, ccx: &CrateContext) -> String {
format!("{}({})", self.action, self.datum.to_string(ccx))
}
}
// Given a closure ty, emits a corresponding tuple ty
pub fn mk_closure_tys(tcx: &ty::ctxt,
bound_values: &[EnvValue])
-> ty::t {
// determine the types of the values in the env. Note that this
// is the actual types that will be stored in the map, not the
// logical types as the user sees them, so by-ref upvars must be
// converted to ptrs.
let bound_tys = bound_values.iter().map(|bv| {
match bv.action {
ast::CaptureByValue => bv.datum.ty,
ast::CaptureByRef => ty::mk_mut_ptr(tcx, bv.datum.ty)
}
}).collect();
let cdata_ty = ty::mk_tup(tcx, bound_tys);
debug!("cdata_ty={}", ty_to_string(tcx, cdata_ty));
return cdata_ty;
}
fn tuplify_box_ty(tcx: &ty::ctxt, t: ty::t) -> ty::t {
let ptr = ty::mk_imm_ptr(tcx, ty::mk_i8());
ty::mk_tup(tcx, vec!(ty::mk_uint(), ty::mk_nil_ptr(tcx), ptr, ptr, t))
}
fn allocate_cbox<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
store: ty::TraitStore,
cdata_ty: ty::t)
-> Result<'blk, 'tcx> {
let _icx = push_ctxt("closure::allocate_cbox");
let tcx = bcx.tcx();
// Allocate and initialize the box:
let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
match store {
ty::UniqTraitStore => {
malloc_raw_dyn_proc(bcx, cbox_ty)
}
ty::RegionTraitStore(..) => {
let llbox = alloc_ty(bcx, cbox_ty, "__closure");
Result::new(bcx, llbox)
}
}
}
pub struct ClosureResult<'blk, 'tcx: 'blk> {
llbox: ValueRef, // llvalue of ptr to closure
cdata_ty: ty::t, // type of the closure data
bcx: Block<'blk, 'tcx> // final bcx
}
// Given a block context and a list of tydescs and values to bind
// construct a closure out of them. If copying is true, it is a
// heap allocated closure that copies the upvars into environment.
// Otherwise, it is stack allocated and copies pointers to the upvars.
pub fn store_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
bound_values: Vec<EnvValue> ,
store: ty::TraitStore)
-> ClosureResult<'blk, 'tcx> {
let _icx = push_ctxt("closure::store_environment");
let ccx = bcx.ccx();
let tcx = ccx.tcx();
// compute the type of the closure
let cdata_ty = mk_closure_tys(tcx, bound_values.as_slice());
// cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a
// tuple. This could be a ptr in uniq or a box or on stack,
// whatever.
let cbox_ty = tuplify_box_ty(tcx, cdata_ty);
let cboxptr_ty = ty::mk_ptr(tcx, ty::mt {ty:cbox_ty, mutbl:ast::MutImmutable});
let llboxptr_ty = type_of(ccx, cboxptr_ty);
// If there are no bound values, no point in allocating anything.
if bound_values.is_empty() {
return ClosureResult {llbox: C_null(llboxptr_ty),
cdata_ty: cdata_ty,
bcx: bcx};
}
// allocate closure in the heap
let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, store, cdata_ty);
let llbox = PointerCast(bcx, llbox, llboxptr_ty);
debug!("tuplify_box_ty = {}", ty_to_string(tcx, cbox_ty));
// Copy expr values into boxed bindings.
let mut bcx = bcx;
for (i, bv) in bound_values.into_iter().enumerate() {
debug!("Copy {} into closure", bv.to_string(ccx));
if ccx.sess().asm_comments() {
add_comment(bcx, format!("Copy {} into closure",
bv.to_string(ccx)).as_slice());
}
let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]);
match bv.action {
ast::CaptureByValue => {
bcx = bv.datum.store_to(bcx, bound_data);
}
ast::CaptureByRef => {
Store(bcx, bv.datum.to_llref(), bound_data);
}
}
}
ClosureResult { llbox: llbox, cdata_ty: cdata_ty, bcx: bcx }
}
// Given a context and a list of upvars, build a closure. This just
// collects the upvars and packages them up for store_environment.
fn build_closure<'blk, 'tcx>(bcx0: Block<'blk, 'tcx>,
freevar_mode: ast::CaptureClause,
freevars: &Vec<ty::Freevar>,
store: ty::TraitStore)
-> ClosureResult<'blk, 'tcx> {
let _icx = push_ctxt("closure::build_closure");
// If we need to, package up the iterator body to call
let bcx = bcx0;
// Package up the captured upvars
let mut env_vals = Vec::new();
for freevar in freevars.iter() {
let datum = expr::trans_local_var(bcx, freevar.def);
env_vals.push(EnvValue {action: freevar_mode, datum: datum});
}
store_environment(bcx, env_vals, store)
}
// Given an enclosing block context, a new function context, a closure type,
// and a list of upvars, generate code to load and populate the environment
// with the upvars and type descriptors.
fn load_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
cdata_ty: ty::t,
freevars: &Vec<ty::Freevar>,
store: ty::TraitStore)
-> Block<'blk, 'tcx> {
let _icx = push_ctxt("closure::load_environment");
// Don't bother to create the block if there's nothing to load
if freevars.len() == 0 {
return bcx;
}
// Load a pointer to the closure data, skipping over the box header:
let llcdata = at_box_body(bcx, cdata_ty, bcx.fcx.llenv.unwrap());
// Store the pointer to closure data in an alloca for debug info because that's what the
// llvm.dbg.declare intrinsic expects
let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo {
let alloc = alloc_ty(bcx, ty::mk_mut_ptr(bcx.tcx(), cdata_ty), "__debuginfo_env_ptr");
Store(bcx, llcdata, alloc);
Some(alloc)
} else {
None
};
// Populate the upvars from the environment
let mut i = 0u;
for freevar in freevars.iter() {
let mut upvarptr = GEPi(bcx, llcdata, [0u, i]);
match store {
ty::RegionTraitStore(..) => { upvarptr = Load(bcx, upvarptr); }
ty::UniqTraitStore => {}
}
let def_id = freevar.def.def_id();
bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr);
for &env_pointer_alloca in env_pointer_alloca.iter() {
debuginfo::create_captured_var_metadata(
bcx,
def_id.node,
cdata_ty,
env_pointer_alloca,
i,
store,
freevar.span);
}
i += 1u;
}
bcx
}
fn load_unboxed_closure_environment<'blk, 'tcx>(
bcx: Block<'blk, 'tcx>,
arg_scope_id: ScopeId,
freevar_mode: ast::CaptureClause,
freevars: &Vec<ty::Freevar>,
closure_id: ast::DefId)
-> Block<'blk, 'tcx> {
let _icx = push_ctxt("closure::load_environment");
if freevars.len() == 0 {
return bcx
}
// Special case for small by-value selfs.
let self_type = self_type_for_unboxed_closure(bcx.ccx(), closure_id);
let kind = kind_for_unboxed_closure(bcx.ccx(), closure_id);
let llenv = if kind == ty::FnOnceUnboxedClosureKind &&
!arg_is_indirect(bcx.ccx(), self_type) {
let datum = rvalue_scratch_datum(bcx,
self_type,
"unboxed_closure_env");
store_ty(bcx, bcx.fcx.llenv.unwrap(), datum.val, self_type);
assert!(freevars.len() <= 1);
datum.val
} else {
bcx.fcx.llenv.unwrap()
};
for (i, freevar) in freevars.iter().enumerate() {
let mut upvar_ptr = GEPi(bcx, llenv, [0, i]);
if freevar_mode == ast::CaptureByRef {
upvar_ptr = Load(bcx, upvar_ptr);
}
let def_id = freevar.def.def_id();
bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr);
if kind == ty::FnOnceUnboxedClosureKind && freevar_mode == ast::CaptureByValue {
bcx.fcx.schedule_drop_mem(arg_scope_id,
upvar_ptr,
node_id_type(bcx, def_id.node))
}
}
bcx
}
fn fill_fn_pair(bcx: Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) {
Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code]));
let llenvptr = PointerCast(bcx, llenvptr, Type::i8p(bcx.ccx()));
Store(bcx, llenvptr, GEPi(bcx, pair, [0u, abi::fn_field_box]));
}
pub fn trans_expr_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
store: ty::TraitStore,
decl: &ast::FnDecl,
body: &ast::Block,
id: ast::NodeId,
dest: expr::Dest)
-> Block<'blk, 'tcx> {
/*!
*
* Translates the body of a closure expression.
*
* - `store`
* - `decl`
* - `body`
* - `id`: The id of the closure expression.
* - `cap_clause`: information about captured variables, if any.
* - `dest`: where to write the closure value, which must be a
(fn ptr, env) pair
*/
let _icx = push_ctxt("closure::trans_expr_fn");
let dest_addr = match dest {
expr::SaveIn(p) => p,
expr::Ignore => {
return bcx; // closure construction is non-side-effecting
}
};
let ccx = bcx.ccx();
let tcx = bcx.tcx();
let fty = node_id_type(bcx, id);
let s = tcx.map.with_path(id, |path| {
mangle_internal_name_by_path_and_seq(path, "closure")
});
let llfn = decl_internal_rust_fn(ccx, fty, s.as_slice());
// set an inline hint for all closures
set_inline_hint(llfn);
let freevar_mode = tcx.capture_mode(id);
let freevars: Vec<ty::Freevar> =
ty::with_freevars(tcx, id, |fv| fv.iter().map(|&fv| fv).collect());
let ClosureResult {
llbox,
cdata_ty,
bcx
} = build_closure(bcx, freevar_mode, &freevars, store);
trans_closure(ccx,
decl,
body,
llfn,
bcx.fcx.param_substs,
id,
[],
ty::ty_fn_args(fty),
ty::ty_fn_ret(fty),
ty::ty_fn_abi(fty),
true,
NotUnboxedClosure,
|bcx, _| load_environment(bcx, cdata_ty, &freevars, store));
fill_fn_pair(bcx, dest_addr, llfn, llbox);
bcx
}
/// Returns the LLVM function declaration for an unboxed closure, creating it
/// if necessary. If the ID does not correspond to a closure ID, returns None.
pub fn get_or_create_declaration_if_unboxed_closure(ccx: &CrateContext,
closure_id: ast::DefId)
-> Option<ValueRef> {
if !ccx.tcx().unboxed_closures.borrow().contains_key(&closure_id) {
// Not an unboxed closure.
return None
}
match ccx.unboxed_closure_vals().borrow().find(&closure_id) {
Some(llfn) => {
debug!("get_or_create_declaration_if_unboxed_closure(): found \
closure");
return Some(*llfn)
}
None => {}
}
let function_type = ty::mk_unboxed_closure(ccx.tcx(),
closure_id,
ty::ReStatic);
let symbol = ccx.tcx().map.with_path(closure_id.node, |path| {
mangle_internal_name_by_path_and_seq(path, "unboxed_closure")
});
let llfn = decl_internal_rust_fn(ccx, function_type, symbol.as_slice());
// set an inline hint for all closures
set_inline_hint(llfn);
debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \
closure {} (type {})",
closure_id,
ccx.tn().type_to_string(val_ty(llfn)));
ccx.unboxed_closure_vals().borrow_mut().insert(closure_id, llfn);
Some(llfn)
}
pub fn trans_unboxed_closure<'blk, 'tcx>(
mut bcx: Block<'blk, 'tcx>,
decl: &ast::FnDecl,
body: &ast::Block,
id: ast::NodeId,
dest: expr::Dest)
-> Block<'blk, 'tcx> {
let _icx = push_ctxt("closure::trans_unboxed_closure");
debug!("trans_unboxed_closure()");
let closure_id = ast_util::local_def(id);
let llfn = get_or_create_declaration_if_unboxed_closure(
bcx.ccx(),
closure_id).unwrap();
let unboxed_closures = bcx.tcx().unboxed_closures.borrow();
let function_type = unboxed_closures.get(&closure_id)
.closure_type
.clone();
let function_type = ty::mk_closure(bcx.tcx(), function_type);
let freevars: Vec<ty::Freevar> =
ty::with_freevars(bcx.tcx(), id, |fv| fv.iter().map(|&fv| fv).collect());
let freevars_ptr = &freevars;
let freevar_mode = bcx.tcx().capture_mode(id);
trans_closure(bcx.ccx(),
decl,
body,
llfn,
bcx.fcx.param_substs,
id,
[],<|fim▁hole|> ty::ty_fn_abi(function_type),
true,
IsUnboxedClosure,
|bcx, arg_scope| {
load_unboxed_closure_environment(bcx,
arg_scope,
freevar_mode,
freevars_ptr,
closure_id)
});
// Don't hoist this to the top of the function. It's perfectly legitimate
// to have a zero-size unboxed closure (in which case dest will be
// `Ignore`) and we must still generate the closure body.
let dest_addr = match dest {
expr::SaveIn(p) => p,
expr::Ignore => {
debug!("trans_unboxed_closure() ignoring result");
return bcx
}
};
let repr = adt::represent_type(bcx.ccx(), node_id_type(bcx, id));
// Create the closure.
for (i, freevar) in freevars_ptr.iter().enumerate() {
let datum = expr::trans_local_var(bcx, freevar.def);
let upvar_slot_dest = adt::trans_field_ptr(bcx,
&*repr,
dest_addr,
0,
i);
match freevar_mode {
ast::CaptureByValue => {
bcx = datum.store_to(bcx, upvar_slot_dest);
}
ast::CaptureByRef => {
Store(bcx, datum.to_llref(), upvar_slot_dest);
}
}
}
adt::trans_set_discr(bcx, &*repr, dest_addr, 0);
bcx
}
pub fn get_wrapper_for_bare_fn(ccx: &CrateContext,
closure_ty: ty::t,
def: def::Def,
fn_ptr: ValueRef,
is_local: bool) -> ValueRef {
let def_id = match def {
def::DefFn(did, _, _) | def::DefStaticMethod(did, _, _) |
def::DefVariant(_, did, _) | def::DefStruct(did) => did,
_ => {
ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
expected a statically resolved fn, got \
{}",
def).as_slice());
}
};
match ccx.closure_bare_wrapper_cache().borrow().find(&fn_ptr) {
Some(&llval) => return llval,
None => {}
}
let tcx = ccx.tcx();
debug!("get_wrapper_for_bare_fn(closure_ty={})", closure_ty.repr(tcx));
let f = match ty::get(closure_ty).sty {
ty::ty_closure(ref f) => f,
_ => {
ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
expected a closure ty, got {}",
closure_ty.repr(tcx)).as_slice());
}
};
let name = ty::with_path(tcx, def_id, |path| {
mangle_internal_name_by_path_and_seq(path, "as_closure")
});
let llfn = if is_local {
decl_internal_rust_fn(ccx, closure_ty, name.as_slice())
} else {
decl_rust_fn(ccx, closure_ty, name.as_slice())
};
ccx.closure_bare_wrapper_cache().borrow_mut().insert(fn_ptr, llfn);
// This is only used by statics inlined from a different crate.
if !is_local {
// Don't regenerate the wrapper, just reuse the original one.
return llfn;
}
let _icx = push_ctxt("closure::get_wrapper_for_bare_fn");
let arena = TypedArena::new();
let empty_param_substs = param_substs::empty();
let fcx = new_fn_ctxt(ccx, llfn, ast::DUMMY_NODE_ID, true, f.sig.output,
&empty_param_substs, None, &arena);
let bcx = init_function(&fcx, true, f.sig.output);
let args = create_datums_for_fn_args(&fcx,
ty::ty_fn_args(closure_ty)
.as_slice());
let mut llargs = Vec::new();
match fcx.llretslotptr.get() {
Some(llretptr) => {
assert!(!fcx.needs_ret_allocas);
llargs.push(llretptr);
}
None => {}
}
llargs.extend(args.iter().map(|arg| arg.val));
let retval = Call(bcx, fn_ptr, llargs.as_slice(), None);
if type_is_zero_size(ccx, f.sig.output) || fcx.llretslotptr.get().is_some() {
RetVoid(bcx);
} else {
Ret(bcx, retval);
}
// HACK(eddyb) finish_fn cannot be used here, we returned directly.
debuginfo::clear_source_location(&fcx);
fcx.cleanup();
llfn
}
pub fn make_closure_from_bare_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
closure_ty: ty::t,
def: def::Def,
fn_ptr: ValueRef)
-> DatumBlock<'blk, 'tcx, Expr> {
let scratch = rvalue_scratch_datum(bcx, closure_ty, "__adjust");
let wrapper = get_wrapper_for_bare_fn(bcx.ccx(), closure_ty, def, fn_ptr, true);
fill_fn_pair(bcx, scratch.val, wrapper, C_null(Type::i8p(bcx.ccx())));
DatumBlock::new(bcx, scratch.to_expr_datum())
}<|fim▁end|> | ty::ty_fn_args(function_type),
ty::ty_fn_ret(function_type), |
<|file_name|>ovfenvelope.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated Fri Dec 2 15:05:18 2011 by generateDS.py version 2.7b.
#
import sys
import getopt
import re as re_
etree_ = None
Verbose_import_ = False
( XMLParser_import_none, XMLParser_import_lxml,
XMLParser_import_elementtree
) = range(3)
XMLParser_import_library = None
try:
# lxml
from lxml import etree as etree_
XMLParser_import_library = XMLParser_import_lxml
if Verbose_import_:
print("running with lxml.etree")
except ImportError:
try:
# cElementTree from Python 2.5+
import xml.etree.cElementTree as etree_
XMLParser_import_library = XMLParser_import_elementtree
if Verbose_import_:
print("running with cElementTree on Python 2.5+")
except ImportError:
try:
# ElementTree from Python 2.5+
import xml.etree.ElementTree as etree_
XMLParser_import_library = XMLParser_import_elementtree
if Verbose_import_:
print("running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree_
XMLParser_import_library = XMLParser_import_elementtree
if Verbose_import_:
print("running with cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree_
XMLParser_import_library = XMLParser_import_elementtree
if Verbose_import_:
print("running with ElementTree")
except ImportError:
raise ImportError("Failed to import ElementTree from any known place")
def parsexml_(*args, **kwargs):
if (XMLParser_import_library == XMLParser_import_lxml and
'parser' not in kwargs):
# Use the lxml ElementTree compatible parser so that, e.g.,
# we ignore comments.
kwargs['parser'] = etree_.ETCompatXMLParser()
doc = etree_.parse(*args, **kwargs)
return doc
#
# User methods
#
# Calls to the methods in these classes are generated by generateDS.py.
# You can replace these methods by re-implementing the following class
# in a module named generatedssuper.py.
try:
from generatedssuper import GeneratedsSuper
except ImportError, exp:
class GeneratedsSuper(object):
def gds_format_string(self, input_data, input_name=''):
return input_data
def gds_validate_string(self, input_data, node, input_name=''):
return input_data
def gds_format_integer(self, input_data, input_name=''):
return '%d' % input_data
def gds_validate_integer(self, input_data, node, input_name=''):
return input_data
def gds_format_integer_list(self, input_data, input_name=''):
return '%s' % input_data
def gds_validate_integer_list(self, input_data, node, input_name=''):
values = input_data.split()
for value in values:
try:
fvalue = float(value)
except (TypeError, ValueError), exp:
raise_parse_error(node, 'Requires sequence of integers')
return input_data
def gds_format_float(self, input_data, input_name=''):
return '%f' % input_data
def gds_validate_float(self, input_data, node, input_name=''):
return input_data
def gds_format_float_list(self, input_data, input_name=''):
return '%s' % input_data
def gds_validate_float_list(self, input_data, node, input_name=''):
values = input_data.split()
for value in values:
try:
fvalue = float(value)
except (TypeError, ValueError), exp:
raise_parse_error(node, 'Requires sequence of floats')
return input_data
def gds_format_double(self, input_data, input_name=''):
return '%e' % input_data
def gds_validate_double(self, input_data, node, input_name=''):
return input_data
def gds_format_double_list(self, input_data, input_name=''):
return '%s' % input_data
def gds_validate_double_list(self, input_data, node, input_name=''):
values = input_data.split()
for value in values:
try:
fvalue = float(value)
except (TypeError, ValueError), exp:
raise_parse_error(node, 'Requires sequence of doubles')
return input_data
def gds_format_boolean(self, input_data, input_name=''):
return '%s' % input_data
def gds_validate_boolean(self, input_data, node, input_name=''):
return input_data
def gds_format_boolean_list(self, input_data, input_name=''):
return '%s' % input_data
def gds_validate_boolean_list(self, input_data, node, input_name=''):
values = input_data.split()
for value in values:
if value not in ('true', '1', 'false', '0', ):
raise_parse_error(node, 'Requires sequence of booleans ("true", "1", "false", "0")')
return input_data
def gds_str_lower(self, instring):
return instring.lower()
def get_path_(self, node):
path_list = []
self.get_path_list_(node, path_list)
path_list.reverse()
path = '/'.join(path_list)
return path
Tag_strip_pattern_ = re_.compile(r'\{.*\}')
def get_path_list_(self, node, path_list):
if node is None:
return
tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag)
if tag:
path_list.append(tag)
self.get_path_list_(node.getparent(), path_list)
def get_class_obj_(self, node, default_class=None):
class_obj1 = default_class
if 'xsi' in node.nsmap:
classname = node.get('{%s}type' % node.nsmap['xsi'])
if classname is not None:
names = classname.split(':')
if len(names) == 2:
classname = names[1]
class_obj2 = globals().get(classname)
if class_obj2 is not None:
class_obj1 = class_obj2
return class_obj1
def gds_build_any(self, node, type_name=None):
return None
#
# If you have installed IPython you can uncomment and use the following.
# IPython is available from http://ipython.scipy.org/.
#
## from IPython.Shell import IPShellEmbed
## args = ''
## ipshell = IPShellEmbed(args,
## banner = 'Dropping into IPython',
## exit_msg = 'Leaving Interpreter, back to program.')
# Then use the following line where and when you want to drop into the
# IPython shell:
# ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit')
#
# Globals
#
ExternalEncoding = 'ascii'
Tag_pattern_ = re_.compile(r'({.*})?(.*)')
String_cleanup_pat_ = re_.compile(r"[\n\r\s]+")
Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)')
#
# Support/utility functions.
#
def showIndent(outfile, level):
for idx in range(level):
outfile.write(' ')
def quote_xml(inStr):
if not inStr:
return ''
s1 = (isinstance(inStr, basestring) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&')
s1 = s1.replace('<', '<')
s1 = s1.replace('>', '>')
return s1
def quote_attrib(inStr):
s1 = (isinstance(inStr, basestring) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&')
s1 = s1.replace('<', '<')
s1 = s1.replace('>', '>')
if '"' in s1:
if "'" in s1:
s1 = '"%s"' % s1.replace('"', """)
else:
s1 = "'%s'" % s1
else:
s1 = '"%s"' % s1
return s1
def quote_python(inStr):
s1 = inStr
if s1.find("'") == -1:
if s1.find('\n') == -1:
return "'%s'" % s1
else:
return "'''%s'''" % s1
else:
if s1.find('"') != -1:
s1 = s1.replace('"', '\\"')
if s1.find('\n') == -1:
return '"%s"' % s1
else:
return '"""%s"""' % s1
def get_all_text_(node):
if node.text is not None:
text = node.text
else:
text = ''
for child in node:
if child.tail is not None:
text += child.tail
return text
def find_attr_value_(attr_name, node):
attrs = node.attrib
attr_parts = attr_name.split(':')
value = None
if len(attr_parts) == 1:
value = attrs.get(attr_name)
elif len(attr_parts) == 2:
prefix, name = attr_parts
namespace = node.nsmap.get(prefix)
if namespace is not None:
value = attrs.get('{%s}%s' % (namespace, name, ))
return value
class GDSParseError(Exception):
pass
def raise_parse_error(node, msg):
if XMLParser_import_library == XMLParser_import_lxml:
msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, )
else:
msg = '%s (element %s)' % (msg, node.tag, )
raise GDSParseError(msg)
class MixedContainer:
# Constants for category:
CategoryNone = 0
CategoryText = 1
CategorySimple = 2
CategoryComplex = 3
# Constants for content_type:
TypeNone = 0
TypeText = 1
TypeString = 2
TypeInteger = 3
TypeFloat = 4
TypeDecimal = 5
TypeDouble = 6
TypeBoolean = 7
def __init__(self, category, content_type, name, value):
self.category = category
self.content_type = content_type
self.name = name
self.value = value
def getCategory(self):
return self.category
def getContenttype(self, content_type):
return self.content_type
def getValue(self):
return self.value
def getName(self):
return self.name
def export(self, outfile, level, name, namespace):
if self.category == MixedContainer.CategoryText:
# Prevent exporting empty content as empty lines.
if self.value.strip():
outfile.write(self.value)
elif self.category == MixedContainer.CategorySimple:
self.exportSimple(outfile, level, name)
else: # category == MixedContainer.CategoryComplex
self.value.export(outfile, level, namespace,name)
def exportSimple(self, outfile, level, name):
if self.content_type == MixedContainer.TypeString:
outfile.write('<%s>%s</%s>' % (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeInteger or \
self.content_type == MixedContainer.TypeBoolean:
outfile.write('<%s>%d</%s>' % (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeFloat or \
self.content_type == MixedContainer.TypeDecimal:
outfile.write('<%s>%f</%s>' % (self.name, self.value, self.name))
elif self.content_type == MixedContainer.TypeDouble:
outfile.write('<%s>%g</%s>' % (self.name, self.value, self.name))
def exportLiteral(self, outfile, level, name):
if self.category == MixedContainer.CategoryText:
showIndent(outfile, level)
outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % \
(self.category, self.content_type, self.name, self.value))
elif self.category == MixedContainer.CategorySimple:
showIndent(outfile, level)
outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % \
(self.category, self.content_type, self.name, self.value))
else: # category == MixedContainer.CategoryComplex
showIndent(outfile, level)
outfile.write('model_.MixedContainer(%d, %d, "%s",\n' % \
(self.category, self.content_type, self.name,))
self.value.exportLiteral(outfile, level + 1)
showIndent(outfile, level)
outfile.write(')\n')
class MemberSpec_(object):
def __init__(self, name='', data_type='', container=0):
self.name = name
self.data_type = data_type
self.container = container
def set_name(self, name): self.name = name
def get_name(self): return self.name
def set_data_type(self, data_type): self.data_type = data_type
def get_data_type_chain(self): return self.data_type
def get_data_type(self):
if isinstance(self.data_type, list):
if len(self.data_type) > 0:
return self.data_type[-1]
else:
return 'xs:string'
else:
return self.data_type
def set_container(self, container): self.container = container
def get_container(self): return self.container
def _cast(typ, value):
if typ is None or value is None:
return value
return typ(value)
#
# Data representation classes.
#
class EnvelopeType(GeneratedsSuper):
"""Root OVF descriptor type"""
subclass = None
superclass = None
def __init__(self, lang='en-US', References=None, Section=None, Content=None, Strings=None):
self.lang = _cast(None, lang)
self.References = References
if Section is None:
self.Section = []
else:
self.Section = Section
self.Content = Content
if Strings is None:
self.Strings = []
else:
self.Strings = Strings
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if EnvelopeType.subclass:
return EnvelopeType.subclass(*args_, **kwargs_)
else:
return EnvelopeType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_References(self): return self.References
def set_References(self, References): self.References = References
def get_Section(self): return self.Section
def set_Section(self, Section): self.Section = Section
def add_Section(self, value): self.Section.append(value)
def insert_Section(self, index, value): self.Section[index] = value
def get_Content(self): return self.Content
def set_Content(self, Content): self.Content = Content
def get_Strings(self): return self.Strings
def set_Strings(self, Strings): self.Strings = Strings
def add_Strings(self, value): self.Strings.append(value)
def insert_Strings(self, index, value): self.Strings[index] = value
def get_lang(self): return self.lang
def set_lang(self, lang): self.lang = lang
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='EnvelopeType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='EnvelopeType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='EnvelopeType'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.lang is not None and 'lang' not in already_processed:
already_processed.append('lang')
outfile.write(' lang=%s' % (self.gds_format_string(quote_attrib(self.lang).encode(ExternalEncoding), input_name='lang'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='EnvelopeType', fromsubclass_=False):
if self.References is not None:
self.References.export(outfile, level, namespace_, name_='References', )
for Section_ in self.Section:
Section_.export(outfile, level, namespace_, name_='Section')
if self.Content is not None:
self.Content.export(outfile, level, namespace_, name_='Content', )
for Strings_ in self.Strings:
Strings_.export(outfile, level, namespace_, name_='Strings')
def hasContent_(self):
if (
self.References is not None or
self.Section or
self.Content is not None or
self.Strings
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='EnvelopeType'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.lang is not None and 'lang' not in already_processed:
already_processed.append('lang')
showIndent(outfile, level)
outfile.write('lang = "%s",\n' % (self.lang,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
if self.References is not None:
showIndent(outfile, level)
outfile.write('References=model_.References_Type(\n')
self.References.exportLiteral(outfile, level, name_='References')
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('Section=[\n')
level += 1
for Section_ in self.Section:
showIndent(outfile, level)
outfile.write('model_.Section(\n')
Section_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
if self.Content is not None:
showIndent(outfile, level)
outfile.write('Content=model_.Content(\n')
self.Content.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('Strings=[\n')
level += 1
for Strings_ in self.Strings:
showIndent(outfile, level)
outfile.write('model_.Strings_Type(\n')
Strings_.exportLiteral(outfile, level, name_='Strings_Type')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('lang', node)
if value is not None and 'lang' not in already_processed:
already_processed.append('lang')
self.lang = value
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'References':
obj_ = References_Type.factory()
obj_.build(child_)
self.set_References(obj_)
elif nodeName_ == 'Section':
class_obj_ = self.get_class_obj_(child_, Section_Type)
obj_ = class_obj_.factory()
obj_.build(child_)
self.Section.append(obj_)
elif nodeName_ == 'Content':
class_obj_ = self.get_class_obj_(child_, Content_Type)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_Content(obj_)
elif nodeName_ == 'Strings':
obj_ = Strings_Type.factory()
obj_.build(child_)
self.Strings.append(obj_)
# end class EnvelopeType
class References_Type(GeneratedsSuper):
"""Type for list of external resources"""
subclass = None
superclass = None
def __init__(self, File=None, anytypeobjs_=None):
if File is None:
self.File = []
else:
self.File = File
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if References_Type.subclass:
return References_Type.subclass(*args_, **kwargs_)
else:
return References_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_File(self): return self.File
def set_File(self, File): self.File = File
def add_File(self, value): self.File.append(value)
def insert_File(self, index, value): self.File[index] = value
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='References_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='References_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='References_Type'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='References_Type', fromsubclass_=False):
for File_ in self.File:
File_.export(outfile, level, namespace_, name_='File')
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.File or
self.anytypeobjs_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='References_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('File=[\n')
level += 1
for File_ in self.File:
showIndent(outfile, level)
outfile.write('model_.File_Type(\n')
File_.exportLiteral(outfile, level, name_='File_Type')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'File':
obj_ = File_Type.factory()
obj_.build(child_)
self.File.append(obj_)
else:
obj_ = self.gds_build_any(child_, 'References_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
# end class References_Type
class File_Type(GeneratedsSuper):
"""Type for an external reference to a resourceReference key used in
other parts of the packageLocation of external resourceSize in
bytes of the files (if known)Compression type (gzip, bzip2, or
none if empty or not specified)Chunk size (except for last
chunk)"""
subclass = None
superclass = None
def __init__(self, compression='', href=None, chunkSize=None, id=None, size=None, anytypeobjs_=None):
self.compression = _cast(None, compression)
self.href = _cast(None, href)
self.chunkSize = _cast(int, chunkSize)
self.id = _cast(None, id)
self.size = _cast(int, size)
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if File_Type.subclass:
return File_Type.subclass(*args_, **kwargs_)
else:
return File_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def get_compression(self): return self.compression
def set_compression(self, compression): self.compression = compression
def get_href(self): return self.href
def set_href(self, href): self.href = href
def get_chunkSize(self): return self.chunkSize
def set_chunkSize(self, chunkSize): self.chunkSize = chunkSize
def get_id(self): return self.id
def set_id(self, id): self.id = id
def get_size(self): return self.size
def set_size(self, size): self.size = size
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='File_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='File_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='File_Type'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.compression is not None and 'compression' not in already_processed:
already_processed.append('compression')
outfile.write(' compression=%s' % (self.gds_format_string(quote_attrib(self.compression).encode(ExternalEncoding), input_name='compression'), ))
if self.href is not None and 'href' not in already_processed:
already_processed.append('href')
outfile.write(' href=%s' % (self.gds_format_string(quote_attrib(self.href).encode(ExternalEncoding), input_name='href'), ))
if self.chunkSize is not None and 'chunkSize' not in already_processed:
already_processed.append('chunkSize')
outfile.write(' chunkSize="%s"' % self.gds_format_integer(self.chunkSize, input_name='chunkSize'))
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
if self.size is not None and 'size' not in already_processed:
already_processed.append('size')
outfile.write(' size="%s"' % self.gds_format_integer(self.size, input_name='size'))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='File_Type', fromsubclass_=False):
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.anytypeobjs_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='File_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.compression is not None and 'compression' not in already_processed:
already_processed.append('compression')
showIndent(outfile, level)
outfile.write('compression = "%s",\n' % (self.compression,))
if self.href is not None and 'href' not in already_processed:
already_processed.append('href')
showIndent(outfile, level)
outfile.write('href = "%s",\n' % (self.href,))
if self.chunkSize is not None and 'chunkSize' not in already_processed:
already_processed.append('chunkSize')
showIndent(outfile, level)
outfile.write('chunkSize = %d,\n' % (self.chunkSize,))
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
showIndent(outfile, level)
outfile.write('id = "%s",\n' % (self.id,))
if self.size is not None and 'size' not in already_processed:
already_processed.append('size')
showIndent(outfile, level)
outfile.write('size = %d,\n' % (self.size,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('compression', node)
if value is not None and 'compression' not in already_processed:
already_processed.append('compression')
self.compression = value
value = find_attr_value_('href', node)
if value is not None and 'href' not in already_processed:
already_processed.append('href')
self.href = value
value = find_attr_value_('chunkSize', node)
if value is not None and 'chunkSize' not in already_processed:
already_processed.append('chunkSize')
try:
self.chunkSize = int(value)
except ValueError, exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
value = find_attr_value_('id', node)
if value is not None and 'id' not in already_processed:
already_processed.append('id')
self.id = value
value = find_attr_value_('size', node)
if value is not None and 'size' not in already_processed:
already_processed.append('size')
try:
self.size = int(value)
except ValueError, exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
obj_ = self.gds_build_any(child_, 'File_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
# end class File_Type
class Content_Type(GeneratedsSuper):
"""Base class for content"""
subclass = None
superclass = None
def __init__(self, id=None, Info=None, Name=None, Section=None, extensiontype_=None):
self.id = _cast(None, id)
self.Info = Info
self.Name = Name
if Section is None:
self.Section = []
else:
self.Section = Section
self.anyAttributes_ = {}
self.extensiontype_ = extensiontype_
def factory(*args_, **kwargs_):
if Content_Type.subclass:
return Content_Type.subclass(*args_, **kwargs_)
else:
return Content_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Info(self): return self.Info
def set_Info(self, Info): self.Info = Info
def get_Name(self): return self.Name
def set_Name(self, Name): self.Name = Name
def get_Section(self): return self.Section
def set_Section(self, Section): self.Section = Section
def add_Section(self, value): self.Section.append(value)
def insert_Section(self, index, value): self.Section[index] = value
def get_id(self): return self.id
def set_id(self, id): self.id = id
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def get_extensiontype_(self): return self.extensiontype_
def set_extensiontype_(self, extensiontype_): self.extensiontype_ = extensiontype_
def export(self, outfile, level, namespace_='ovf:', name_='Content_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='Content_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='Content_Type'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
if self.extensiontype_ is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
outfile.write(' xsi:type="%s"' % self.extensiontype_)
def exportChildren(self, outfile, level, namespace_='ovf:', name_='Content_Type', fromsubclass_=False):
if self.Info is not None:
self.Info.export(outfile, level, namespace_, name_='Info', )
if self.Name is not None:
self.Name.export(outfile, level, namespace_, name_='Name')
for Section_ in self.Section:
Section_.export(outfile, level, namespace_, name_='Section')
def hasContent_(self):
if (
self.Info is not None or
self.Name is not None or
self.Section
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Content_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
showIndent(outfile, level)
outfile.write('id = "%s",\n' % (self.id,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
if self.Info is not None:
showIndent(outfile, level)
outfile.write('Info=model_.Msg_Type(\n')
self.Info.exportLiteral(outfile, level, name_='Info')
showIndent(outfile, level)
outfile.write('),\n')
if self.Name is not None:
showIndent(outfile, level)
outfile.write('Name=model_.Msg_Type(\n')
self.Name.exportLiteral(outfile, level, name_='Name')
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('Section=[\n')
level += 1
for Section_ in self.Section:
showIndent(outfile, level)
outfile.write('model_.Section(\n')
Section_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('id', node)
if value is not None and 'id' not in already_processed:
already_processed.append('id')
self.id = value
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
value = find_attr_value_('xsi:type', node)
if value is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
self.extensiontype_ = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Info':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.set_Info(obj_)
elif nodeName_ == 'Name':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.set_Name(obj_)
elif nodeName_ == 'Section':
class_obj_ = self.get_class_obj_(child_, Section_Type)
obj_ = class_obj_.factory()
obj_.build(child_)
self.Section.append(obj_)
# end class Content_Type
class VirtualSystem_Type(Content_Type):
"""Content describing a virtual system"""
subclass = None
superclass = Content_Type
def __init__(self, id=None, Info=None, Name=None, Section=None):
super(VirtualSystem_Type, self).__init__(id, Info, Name, Section, )
pass
def factory(*args_, **kwargs_):
if VirtualSystem_Type.subclass:
return VirtualSystem_Type.subclass(*args_, **kwargs_)
else:
return VirtualSystem_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def export(self, outfile, level, namespace_='ovf:', name_='VirtualSystem_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='VirtualSystem_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='VirtualSystem_Type'):
super(VirtualSystem_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='VirtualSystem_Type')
def exportChildren(self, outfile, level, namespace_='ovf:', name_='VirtualSystem_Type', fromsubclass_=False):
super(VirtualSystem_Type, self).exportChildren(outfile, level, namespace_, name_, True)
def hasContent_(self):
if (
super(VirtualSystem_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='VirtualSystem_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
super(VirtualSystem_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(VirtualSystem_Type, self).exportLiteralChildren(outfile, level, name_)
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
super(VirtualSystem_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
super(VirtualSystem_Type, self).buildChildren(child_, node, nodeName_, True)
pass
# end class VirtualSystem_Type
class VirtualSystemCollection_Type(Content_Type):
"""A collection of Content."""
subclass = None
superclass = Content_Type
def __init__(self, id=None, Info=None, Name=None, Section=None, Content=None):
super(VirtualSystemCollection_Type, self).__init__(id, Info, Name, Section, )
if Content is None:
self.Content = []
else:
self.Content = Content
def factory(*args_, **kwargs_):
if VirtualSystemCollection_Type.subclass:
return VirtualSystemCollection_Type.subclass(*args_, **kwargs_)
else:
return VirtualSystemCollection_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Content(self): return self.Content
def set_Content(self, Content): self.Content = Content
def add_Content(self, value): self.Content.append(value)
def insert_Content(self, index, value): self.Content[index] = value
def export(self, outfile, level, namespace_='ovf:', name_='VirtualSystemCollection_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='VirtualSystemCollection_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='VirtualSystemCollection_Type'):
super(VirtualSystemCollection_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='VirtualSystemCollection_Type')
def exportChildren(self, outfile, level, namespace_='ovf:', name_='VirtualSystemCollection_Type', fromsubclass_=False):
super(VirtualSystemCollection_Type, self).exportChildren(outfile, level, namespace_, name_, True)
for Content_ in self.Content:
Content_.export(outfile, level, namespace_, name_='Content')
def hasContent_(self):
if (
self.Content or
super(VirtualSystemCollection_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='VirtualSystemCollection_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
super(VirtualSystemCollection_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(VirtualSystemCollection_Type, self).exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('Content=[\n')
level += 1
for Content_ in self.Content:
showIndent(outfile, level)
outfile.write('model_.Content(\n')
Content_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
super(VirtualSystemCollection_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Content':
class_obj_ = self.get_class_obj_(child_, Content_Type)
obj_ = class_obj_.factory()
obj_.build(child_)
self.Content.append(obj_)
super(VirtualSystemCollection_Type, self).buildChildren(child_, node, nodeName_, True)
# end class VirtualSystemCollection_Type
class Strings_Type(GeneratedsSuper):
"""Type for string resource bundleLocale for this string resource
bundleReference to external resource bundle"""
subclass = None
superclass = None
def __init__(self, lang=None, fileRef=None, Msg=None):
self.lang = _cast(None, lang)
self.fileRef = _cast(None, fileRef)
if Msg is None:
self.Msg = []
else:
self.Msg = Msg
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if Strings_Type.subclass:
return Strings_Type.subclass(*args_, **kwargs_)
else:
return Strings_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Msg(self): return self.Msg
def set_Msg(self, Msg): self.Msg = Msg
def add_Msg(self, value): self.Msg.append(value)
def insert_Msg(self, index, value): self.Msg[index] = value
def get_lang(self): return self.lang
def set_lang(self, lang): self.lang = lang
def get_fileRef(self): return self.fileRef
def set_fileRef(self, fileRef): self.fileRef = fileRef
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='Strings_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='Strings_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='Strings_Type'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.lang is not None and 'lang' not in already_processed:
already_processed.append('lang')
outfile.write(' lang=%s' % (self.gds_format_string(quote_attrib(self.lang).encode(ExternalEncoding), input_name='lang'), ))
if self.fileRef is not None and 'fileRef' not in already_processed:
already_processed.append('fileRef')
outfile.write(' fileRef=%s' % (self.gds_format_string(quote_attrib(self.fileRef).encode(ExternalEncoding), input_name='fileRef'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='Strings_Type', fromsubclass_=False):
for Msg_ in self.Msg:
Msg_.export(outfile, level, namespace_, name_='Msg')
def hasContent_(self):
if (
self.Msg
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Strings_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.lang is not None and 'lang' not in already_processed:
already_processed.append('lang')
showIndent(outfile, level)
outfile.write('lang = "%s",\n' % (self.lang,))
if self.fileRef is not None and 'fileRef' not in already_processed:
already_processed.append('fileRef')
showIndent(outfile, level)
outfile.write('fileRef = "%s",\n' % (self.fileRef,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('Msg=[\n')
level += 1
for Msg_ in self.Msg:
showIndent(outfile, level)
outfile.write('model_.MsgType(\n')
Msg_.exportLiteral(outfile, level, name_='MsgType')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('lang', node)
if value is not None and 'lang' not in already_processed:
already_processed.append('lang')
self.lang = value
value = find_attr_value_('fileRef', node)
if value is not None and 'fileRef' not in already_processed:
already_processed.append('fileRef')
self.fileRef = value
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Msg':
obj_ = MsgType.factory()
obj_.build(child_)
self.Msg.append(obj_)
# end class Strings_Type
class Section_Type(GeneratedsSuper):
"""Base type for Sections, subclassing this is the most common form of
extensibility. Subtypes define more specific elements."""
subclass = None
superclass = None
def __init__(self, required=None, Info=None, extensiontype_=None):
self.required = _cast(None, required)
self.Info = Info
self.anyAttributes_ = {}
self.extensiontype_ = extensiontype_
def factory(*args_, **kwargs_):
if Section_Type.subclass:
return Section_Type.subclass(*args_, **kwargs_)
else:
return Section_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Info(self): return self.Info
def set_Info(self, Info): self.Info = Info
def get_required(self): return self.required
def set_required(self, required): self.required = required
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def get_extensiontype_(self): return self.extensiontype_
def set_extensiontype_(self, extensiontype_): self.extensiontype_ = extensiontype_
def export(self, outfile, level, namespace_='ovf:', name_='Section_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='Section_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='Section_Type'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.required is not None and 'required' not in already_processed:
already_processed.append('required')
outfile.write(' required=%s' % (self.gds_format_string(quote_attrib(self.required).encode(ExternalEncoding), input_name='required'), ))
if self.extensiontype_ is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
outfile.write(' xsi:type="%s"' % self.extensiontype_)
def exportChildren(self, outfile, level, namespace_='ovf:', name_='Section_Type', fromsubclass_=False):
if self.Info is not None:
self.Info.export(outfile, level, namespace_, name_='Info', )
def hasContent_(self):
if (
self.Info is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Section_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.required is not None and 'required' not in already_processed:
already_processed.append('required')
showIndent(outfile, level)
outfile.write('required = "%s",\n' % (self.required,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
if self.Info is not None:
showIndent(outfile, level)
outfile.write('Info=model_.Msg_Type(\n')
self.Info.exportLiteral(outfile, level, name_='Info')
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('required', node)
if value is not None and 'required' not in already_processed:
already_processed.append('required')
self.required = value
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
value = find_attr_value_('xsi:type', node)
if value is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
self.extensiontype_ = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Info':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.set_Info(obj_)
# end class Section_Type
class Msg_Type(GeneratedsSuper):
"""Type for localizable stringDefault string valueIdentifier for lookup
in string resource bundle for alternate locale"""
subclass = None
superclass = None
def __init__(self, msgid='', valueOf_=None):
self.msgid = _cast(None, msgid)
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if Msg_Type.subclass:
return Msg_Type.subclass(*args_, **kwargs_)
else:
return Msg_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_msgid(self): return self.msgid
def set_msgid(self, msgid): self.msgid = msgid
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='Msg_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='Msg_Type')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='Msg_Type'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.msgid is not None and 'msgid' not in already_processed:
already_processed.append('msgid')
outfile.write(' msgid=%s' % (self.gds_format_string(quote_attrib(self.msgid).encode(ExternalEncoding), input_name='msgid'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='Msg_Type', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Msg_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.msgid is not None and 'msgid' not in already_processed:
already_processed.append('msgid')
showIndent(outfile, level)
outfile.write('msgid = "%s",\n' % (self.msgid,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('msgid', node)
if value is not None and 'msgid' not in already_processed:
already_processed.append('msgid')
self.msgid = value
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class Msg_Type
class AnnotationSection_Type(Section_Type):
"""User defined annotation"""
subclass = None
superclass = Section_Type
def __init__(self, required=None, Info=None, Annotation=None, anytypeobjs_=None):
super(AnnotationSection_Type, self).__init__(required, Info, )
self.Annotation = Annotation
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
def factory(*args_, **kwargs_):
if AnnotationSection_Type.subclass:
return AnnotationSection_Type.subclass(*args_, **kwargs_)
else:
return AnnotationSection_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Annotation(self): return self.Annotation
def set_Annotation(self, Annotation): self.Annotation = Annotation
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def export(self, outfile, level, namespace_='ovf:', name_='AnnotationSection_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='AnnotationSection_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='AnnotationSection_Type'):
super(AnnotationSection_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AnnotationSection_Type')
def exportChildren(self, outfile, level, namespace_='ovf:', name_='AnnotationSection_Type', fromsubclass_=False):
super(AnnotationSection_Type, self).exportChildren(outfile, level, namespace_, name_, True)
if self.Annotation is not None:
self.Annotation.export(outfile, level, namespace_, name_='Annotation', )
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.Annotation is not None or
self.anytypeobjs_ or
super(AnnotationSection_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='AnnotationSection_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
super(AnnotationSection_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(AnnotationSection_Type, self).exportLiteralChildren(outfile, level, name_)
if self.Annotation is not None:
showIndent(outfile, level)
outfile.write('Annotation=model_.Msg_Type(\n')
self.Annotation.exportLiteral(outfile, level, name_='Annotation')
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
super(AnnotationSection_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Annotation':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.set_Annotation(obj_)
else:
obj_ = self.gds_build_any(child_, 'AnnotationSection_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
super(AnnotationSection_Type, self).buildChildren(child_, node, nodeName_, True)
# end class AnnotationSection_Type
class ProductSection_Type(Section_Type):
"""Product information for a virtual applianceProperties for
application-level customizationProperty identifier
prefixProperty identifier suffix"""
subclass = None
superclass = Section_Type
def __init__(self, required=None, Info=None, instance='', classxx='', Product=None, Vendor=None, Version=None, FullVersion=None, ProductUrl=None, VendorUrl=None, AppUrl=None, Icon=None, Category=None, Property=None, anytypeobjs_=None):
super(ProductSection_Type, self).__init__(required, Info, )
self.instance = _cast(None, instance)
self.classxx = _cast(None, classxx)
self.Product = Product
self.Vendor = Vendor
self.Version = Version
self.FullVersion = FullVersion
self.ProductUrl = ProductUrl
self.VendorUrl = VendorUrl
self.AppUrl = AppUrl
if Icon is None:
self.Icon = []
else:
self.Icon = Icon
if Category is None:
self.Category = []
else:
self.Category = Category
if Property is None:
self.Property = []
else:
self.Property = Property
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
def factory(*args_, **kwargs_):
if ProductSection_Type.subclass:
return ProductSection_Type.subclass(*args_, **kwargs_)
else:
return ProductSection_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Product(self): return self.Product
def set_Product(self, Product): self.Product = Product
def get_Vendor(self): return self.Vendor
def set_Vendor(self, Vendor): self.Vendor = Vendor
def get_Version(self): return self.Version
def set_Version(self, Version): self.Version = Version
def get_FullVersion(self): return self.FullVersion
def set_FullVersion(self, FullVersion): self.FullVersion = FullVersion
def get_ProductUrl(self): return self.ProductUrl
def set_ProductUrl(self, ProductUrl): self.ProductUrl = ProductUrl
def get_VendorUrl(self): return self.VendorUrl
def set_VendorUrl(self, VendorUrl): self.VendorUrl = VendorUrl
def get_AppUrl(self): return self.AppUrl
def set_AppUrl(self, AppUrl): self.AppUrl = AppUrl
def get_Icon(self): return self.Icon
def set_Icon(self, Icon): self.Icon = Icon
def add_Icon(self, value): self.Icon.append(value)
def insert_Icon(self, index, value): self.Icon[index] = value
def get_Category(self): return self.Category
def set_Category(self, Category): self.Category = Category
def add_Category(self, value): self.Category.append(value)
def insert_Category(self, index, value): self.Category[index] = value
def get_Property(self): return self.Property
def set_Property(self, Property): self.Property = Property
def add_Property(self, value): self.Property.append(value)
def insert_Property(self, index, value): self.Property[index] = value
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def get_instance(self): return self.instance
def set_instance(self, instance): self.instance = instance
def get_class(self): return self.classxx
def set_class(self, classxx): self.classxx = classxx
def export(self, outfile, level, namespace_='ovf:', name_='ProductSection_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='ProductSection_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='ProductSection_Type'):
super(ProductSection_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ProductSection_Type')
if self.instance is not None and 'instance' not in already_processed:
already_processed.append('instance')
outfile.write(' instance=%s' % (self.gds_format_string(quote_attrib(self.instance).encode(ExternalEncoding), input_name='instance'), ))
if self.classxx is not None and 'classxx' not in already_processed:
already_processed.append('classxx')
outfile.write(' class=%s' % (self.gds_format_string(quote_attrib(self.classxx).encode(ExternalEncoding), input_name='class'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='ProductSection_Type', fromsubclass_=False):
super(ProductSection_Type, self).exportChildren(outfile, level, namespace_, name_, True)
if self.Product is not None:
self.Product.export(outfile, level, namespace_, name_='Product')
if self.Vendor is not None:
self.Vendor.export(outfile, level, namespace_, name_='Vendor')
if self.Version is not None:
self.Version.export(outfile, level, namespace_, name_='Version')
if self.FullVersion is not None:
self.FullVersion.export(outfile, level, namespace_, name_='FullVersion')
if self.ProductUrl is not None:
self.ProductUrl.export(outfile, level, namespace_, name_='ProductUrl')
if self.VendorUrl is not None:
self.VendorUrl.export(outfile, level, namespace_, name_='VendorUrl')
if self.AppUrl is not None:
self.AppUrl.export(outfile, level, namespace_, name_='AppUrl')
for Icon_ in self.Icon:
Icon_.export(outfile, level, namespace_, name_='Icon')
for Category_ in self.Category:
Category_.export(outfile, level, namespace_, name_='Category')
for Property_ in self.Property:
Property_.export(outfile, level, namespace_, name_='Property')
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.Product is not None or
self.Vendor is not None or
self.Version is not None or
self.FullVersion is not None or
self.ProductUrl is not None or
self.VendorUrl is not None or
self.AppUrl is not None or
self.Icon or
self.Category or
self.Property or
self.anytypeobjs_ or
super(ProductSection_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='ProductSection_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.instance is not None and 'instance' not in already_processed:
already_processed.append('instance')
showIndent(outfile, level)
outfile.write('instance = "%s",\n' % (self.instance,))
if self.classxx is not None and 'classxx' not in already_processed:
already_processed.append('classxx')
showIndent(outfile, level)
outfile.write('classxx = "%s",\n' % (self.classxx,))
super(ProductSection_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(ProductSection_Type, self).exportLiteralChildren(outfile, level, name_)
if self.Product is not None:
showIndent(outfile, level)
outfile.write('Product=model_.Msg_Type(\n')
self.Product.exportLiteral(outfile, level, name_='Product')
showIndent(outfile, level)
outfile.write('),\n')
if self.Vendor is not None:
showIndent(outfile, level)
outfile.write('Vendor=model_.Msg_Type(\n')
self.Vendor.exportLiteral(outfile, level, name_='Vendor')
showIndent(outfile, level)
outfile.write('),\n')
if self.Version is not None:
showIndent(outfile, level)
outfile.write('Version=model_.cimString(\n')
self.Version.exportLiteral(outfile, level, name_='Version')
showIndent(outfile, level)
outfile.write('),\n')
if self.FullVersion is not None:
showIndent(outfile, level)
outfile.write('FullVersion=model_.cimString(\n')
self.FullVersion.exportLiteral(outfile, level, name_='FullVersion')
showIndent(outfile, level)
outfile.write('),\n')
if self.ProductUrl is not None:
showIndent(outfile, level)
outfile.write('ProductUrl=model_.cimString(\n')
self.ProductUrl.exportLiteral(outfile, level, name_='ProductUrl')
showIndent(outfile, level)
outfile.write('),\n')
if self.VendorUrl is not None:
showIndent(outfile, level)
outfile.write('VendorUrl=model_.cimString(\n')
self.VendorUrl.exportLiteral(outfile, level, name_='VendorUrl')
showIndent(outfile, level)
outfile.write('),\n')
if self.AppUrl is not None:
showIndent(outfile, level)
outfile.write('AppUrl=model_.cimString(\n')
self.AppUrl.exportLiteral(outfile, level, name_='AppUrl')
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('Icon=[\n')
level += 1
for Icon_ in self.Icon:
showIndent(outfile, level)
outfile.write('model_.IconType(\n')
Icon_.exportLiteral(outfile, level, name_='IconType')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Category=[\n')
level += 1
for Category_ in self.Category:
showIndent(outfile, level)
outfile.write('model_.Msg_Type(\n')
Category_.exportLiteral(outfile, level, name_='Msg_Type')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('Property=[\n')
level += 1
for Property_ in self.Property:
showIndent(outfile, level)
outfile.write('model_.PropertyType(\n')
Property_.exportLiteral(outfile, level, name_='PropertyType')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('instance', node)
if value is not None and 'instance' not in already_processed:
already_processed.append('instance')
self.instance = value
value = find_attr_value_('class', node)
if value is not None and 'class' not in already_processed:
already_processed.append('class')
self.classxx = value
super(ProductSection_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Product':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.set_Product(obj_)
elif nodeName_ == 'Vendor':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.set_Vendor(obj_)
elif nodeName_ == 'Version':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_Version(obj_)
elif nodeName_ == 'FullVersion':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_FullVersion(obj_)
elif nodeName_ == 'ProductUrl':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_ProductUrl(obj_)
elif nodeName_ == 'VendorUrl':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_VendorUrl(obj_)
elif nodeName_ == 'AppUrl':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_AppUrl(obj_)
elif nodeName_ == 'Icon':
obj_ = IconType.factory()
obj_.build(child_)
self.Icon.append(obj_)
elif nodeName_ == 'Category':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.Category.append(obj_)
elif nodeName_ == 'Property':
obj_ = PropertyType.factory()
obj_.build(child_)
self.Property.append(obj_)
else:
obj_ = self.gds_build_any(child_, 'ProductSection_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
super(ProductSection_Type, self).buildChildren(child_, node, nodeName_, True)
# end class ProductSection_Type
class PropertyConfigurationValue_Type(GeneratedsSuper):
"""Type for alternative default values for properties when
DeploymentOptionSection is usedAlternative default property
valueConfiguration from DeploymentOptionSection in which this
value is default"""
subclass = None
superclass = None
def __init__(self, configuration=None, value=None, anytypeobjs_=None):
self.configuration = _cast(None, configuration)
self.value = _cast(None, value)
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if PropertyConfigurationValue_Type.subclass:
return PropertyConfigurationValue_Type.subclass(*args_, **kwargs_)
else:
return PropertyConfigurationValue_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def get_configuration(self): return self.configuration
def set_configuration(self, configuration): self.configuration = configuration
def get_value(self): return self.value
def set_value(self, value): self.value = value
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='PropertyConfigurationValue_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='PropertyConfigurationValue_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='PropertyConfigurationValue_Type'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.configuration is not None and 'configuration' not in already_processed:
already_processed.append('configuration')
outfile.write(' configuration=%s' % (self.gds_format_string(quote_attrib(self.configuration).encode(ExternalEncoding), input_name='configuration'), ))
if self.value is not None and 'value' not in already_processed:
already_processed.append('value')
outfile.write(' value=%s' % (self.gds_format_string(quote_attrib(self.value).encode(ExternalEncoding), input_name='value'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='PropertyConfigurationValue_Type', fromsubclass_=False):
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.anytypeobjs_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='PropertyConfigurationValue_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.configuration is not None and 'configuration' not in already_processed:
already_processed.append('configuration')
showIndent(outfile, level)
outfile.write('configuration = "%s",\n' % (self.configuration,))
if self.value is not None and 'value' not in already_processed:
already_processed.append('value')
showIndent(outfile, level)
outfile.write('value = "%s",\n' % (self.value,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('configuration', node)
if value is not None and 'configuration' not in already_processed:
already_processed.append('configuration')
self.configuration = value
value = find_attr_value_('value', node)
if value is not None and 'value' not in already_processed:
already_processed.append('value')
self.value = value
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
obj_ = self.gds_build_any(child_, 'PropertyConfigurationValue_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
# end class PropertyConfigurationValue_Type
class NetworkSection_Type(Section_Type):
"""Descriptions of logical networks used within the package"""
subclass = None
superclass = Section_Type
def __init__(self, required=None, Info=None, Network=None, anytypeobjs_=None):
super(NetworkSection_Type, self).__init__(required, Info, )
if Network is None:
self.Network = []
else:
self.Network = Network
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
def factory(*args_, **kwargs_):
if NetworkSection_Type.subclass:
return NetworkSection_Type.subclass(*args_, **kwargs_)
else:
return NetworkSection_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Network(self): return self.Network
def set_Network(self, Network): self.Network = Network
def add_Network(self, value): self.Network.append(value)
def insert_Network(self, index, value): self.Network[index] = value
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def export(self, outfile, level, namespace_='ovf:', name_='NetworkSection_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='NetworkSection_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='NetworkSection_Type'):
super(NetworkSection_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='NetworkSection_Type')
def exportChildren(self, outfile, level, namespace_='ovf:', name_='NetworkSection_Type', fromsubclass_=False):
super(NetworkSection_Type, self).exportChildren(outfile, level, namespace_, name_, True)
for Network_ in self.Network:
Network_.export(outfile, level, namespace_, name_='Network')
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.Network or
self.anytypeobjs_ or
super(NetworkSection_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='NetworkSection_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
super(NetworkSection_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(NetworkSection_Type, self).exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('Network=[\n')
level += 1
for Network_ in self.Network:
showIndent(outfile, level)
outfile.write('model_.NetworkType(\n')
Network_.exportLiteral(outfile, level, name_='NetworkType')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
super(NetworkSection_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Network':
obj_ = NetworkType.factory()
obj_.build(child_)
self.Network.append(obj_)
else:
obj_ = self.gds_build_any(child_, 'NetworkSection_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
super(NetworkSection_Type, self).buildChildren(child_, node, nodeName_, True)
# end class NetworkSection_Type
class DiskSection_Type(Section_Type):
"""Descriptions of virtual disks used within the package"""
subclass = None
superclass = Section_Type
def __init__(self, required=None, Info=None, Disk=None, anytypeobjs_=None):
super(DiskSection_Type, self).__init__(required, Info, )
if Disk is None:
self.Disk = []
else:
self.Disk = Disk
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
def factory(*args_, **kwargs_):
if DiskSection_Type.subclass:
return DiskSection_Type.subclass(*args_, **kwargs_)
else:
return DiskSection_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Disk(self): return self.Disk
def set_Disk(self, Disk): self.Disk = Disk
def add_Disk(self, value): self.Disk.append(value)
def insert_Disk(self, index, value): self.Disk[index] = value
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def export(self, outfile, level, namespace_='ovf:', name_='DiskSection_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='DiskSection_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='DiskSection_Type'):
super(DiskSection_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DiskSection_Type')
def exportChildren(self, outfile, level, namespace_='ovf:', name_='DiskSection_Type', fromsubclass_=False):
super(DiskSection_Type, self).exportChildren(outfile, level, namespace_, name_, True)
for Disk_ in self.Disk:
Disk_.export(outfile, level, namespace_, name_='Disk')
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.Disk or
self.anytypeobjs_ or
super(DiskSection_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='DiskSection_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
super(DiskSection_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(DiskSection_Type, self).exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('Disk=[\n')
level += 1
for Disk_ in self.Disk:
showIndent(outfile, level)
outfile.write('model_.VirtualDiskDesc_Type(\n')
Disk_.exportLiteral(outfile, level, name_='VirtualDiskDesc_Type')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
super(DiskSection_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Disk':
obj_ = VirtualDiskDesc_Type.factory()
obj_.build(child_)
self.Disk.append(obj_)
else:
obj_ = self.gds_build_any(child_, 'DiskSection_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
super(DiskSection_Type, self).buildChildren(child_, node, nodeName_, True)
# end class DiskSection_Type
class VirtualDiskDesc_Type(GeneratedsSuper):
"""Type for virtual disk descriptorIdentifier for virtual diskReference
to virtual disk content. If not specified a blank virtual disk
is created of size given by capacity attributeVirtual disk
capacity, can be specified as either an xs:long size or as a
reference to a property using ${property_name}. Unit of
allocation for ovf:capacity. If not specified default value is
bytes. Value shall match a recognized value for the UNITS
qualifier in DSP0004.Format of virtual disk given as a URI that
identifies the disk typeEstimated populated size of disk in
bytesReference to potential parent disk"""
subclass = None
superclass = None
def __init__(self, capacityAllocationUnits='byte', capacity=None, format=None, parentRef=None, fileRef=None, populatedSize=None, diskId=None, anytypeobjs_=None):
self.capacityAllocationUnits = _cast(None, capacityAllocationUnits)
self.capacity = _cast(None, capacity)
self.format = _cast(None, format)
self.parentRef = _cast(None, parentRef)
self.fileRef = _cast(None, fileRef)
self.populatedSize = _cast(int, populatedSize)
self.diskId = _cast(None, diskId)
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if VirtualDiskDesc_Type.subclass:
return VirtualDiskDesc_Type.subclass(*args_, **kwargs_)
else:
return VirtualDiskDesc_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def get_capacityAllocationUnits(self): return self.capacityAllocationUnits
def set_capacityAllocationUnits(self, capacityAllocationUnits): self.capacityAllocationUnits = capacityAllocationUnits
def get_capacity(self): return self.capacity
def set_capacity(self, capacity): self.capacity = capacity
def get_format(self): return self.format
def set_format(self, format): self.format = format
def get_parentRef(self): return self.parentRef
def set_parentRef(self, parentRef): self.parentRef = parentRef
def get_fileRef(self): return self.fileRef
def set_fileRef(self, fileRef): self.fileRef = fileRef
def get_populatedSize(self): return self.populatedSize
def set_populatedSize(self, populatedSize): self.populatedSize = populatedSize
def get_diskId(self): return self.diskId
def set_diskId(self, diskId): self.diskId = diskId
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='VirtualDiskDesc_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='VirtualDiskDesc_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='VirtualDiskDesc_Type'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.capacityAllocationUnits is not None and 'capacityAllocationUnits' not in already_processed:
already_processed.append('capacityAllocationUnits')
outfile.write(' capacityAllocationUnits=%s' % (self.gds_format_string(quote_attrib(self.capacityAllocationUnits).encode(ExternalEncoding), input_name='capacityAllocationUnits'), ))
if self.capacity is not None and 'capacity' not in already_processed:
already_processed.append('capacity')
outfile.write(' capacity=%s' % (self.gds_format_string(quote_attrib(self.capacity).encode(ExternalEncoding), input_name='capacity'), ))
if self.format is not None and 'format' not in already_processed:
already_processed.append('format')
outfile.write(' format=%s' % (self.gds_format_string(quote_attrib(self.format).encode(ExternalEncoding), input_name='format'), ))
if self.parentRef is not None and 'parentRef' not in already_processed:
already_processed.append('parentRef')
outfile.write(' parentRef=%s' % (self.gds_format_string(quote_attrib(self.parentRef).encode(ExternalEncoding), input_name='parentRef'), ))
if self.fileRef is not None and 'fileRef' not in already_processed:
already_processed.append('fileRef')
outfile.write(' fileRef=%s' % (self.gds_format_string(quote_attrib(self.fileRef).encode(ExternalEncoding), input_name='fileRef'), ))
if self.populatedSize is not None and 'populatedSize' not in already_processed:
already_processed.append('populatedSize')
outfile.write(' populatedSize="%s"' % self.gds_format_integer(self.populatedSize, input_name='populatedSize'))
if self.diskId is not None and 'diskId' not in already_processed:
already_processed.append('diskId')
outfile.write(' diskId=%s' % (self.gds_format_string(quote_attrib(self.diskId).encode(ExternalEncoding), input_name='diskId'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='VirtualDiskDesc_Type', fromsubclass_=False):
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.anytypeobjs_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='VirtualDiskDesc_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.capacityAllocationUnits is not None and 'capacityAllocationUnits' not in already_processed:
already_processed.append('capacityAllocationUnits')
showIndent(outfile, level)
outfile.write('capacityAllocationUnits = "%s",\n' % (self.capacityAllocationUnits,))
if self.capacity is not None and 'capacity' not in already_processed:
already_processed.append('capacity')
showIndent(outfile, level)
outfile.write('capacity = "%s",\n' % (self.capacity,))
if self.format is not None and 'format' not in already_processed:
already_processed.append('format')
showIndent(outfile, level)
outfile.write('format = "%s",\n' % (self.format,))
if self.parentRef is not None and 'parentRef' not in already_processed:
already_processed.append('parentRef')
showIndent(outfile, level)
outfile.write('parentRef = "%s",\n' % (self.parentRef,))
if self.fileRef is not None and 'fileRef' not in already_processed:
already_processed.append('fileRef')
showIndent(outfile, level)
outfile.write('fileRef = "%s",\n' % (self.fileRef,))
if self.populatedSize is not None and 'populatedSize' not in already_processed:
already_processed.append('populatedSize')
showIndent(outfile, level)
outfile.write('populatedSize = %d,\n' % (self.populatedSize,))
if self.diskId is not None and 'diskId' not in already_processed:
already_processed.append('diskId')
showIndent(outfile, level)
outfile.write('diskId = "%s",\n' % (self.diskId,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('capacityAllocationUnits', node)
if value is not None and 'capacityAllocationUnits' not in already_processed:
already_processed.append('capacityAllocationUnits')
self.capacityAllocationUnits = value
value = find_attr_value_('capacity', node)
if value is not None and 'capacity' not in already_processed:
already_processed.append('capacity')
self.capacity = value
value = find_attr_value_('format', node)
if value is not None and 'format' not in already_processed:
already_processed.append('format')
self.format = value
value = find_attr_value_('parentRef', node)
if value is not None and 'parentRef' not in already_processed:
already_processed.append('parentRef')
self.parentRef = value
value = find_attr_value_('fileRef', node)
if value is not None and 'fileRef' not in already_processed:
already_processed.append('fileRef')
self.fileRef = value
value = find_attr_value_('populatedSize', node)
if value is not None and 'populatedSize' not in already_processed:
already_processed.append('populatedSize')
try:
self.populatedSize = int(value)
except ValueError, exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
value = find_attr_value_('diskId', node)
if value is not None and 'diskId' not in already_processed:
already_processed.append('diskId')
self.diskId = value
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
obj_ = self.gds_build_any(child_, 'VirtualDiskDesc_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
# end class VirtualDiskDesc_Type
class OperatingSystemSection_Type(Section_Type):
"""Specification of the operating system installed in the
guestIdentifier defined by the CIM_OperatingSystem.OsType
enumerationVersion defined by the CIM_OperatingSystem.Version
field"""
subclass = None
superclass = Section_Type
def __init__(self, required=None, Info=None, version=None, id=None, Description=None, anytypeobjs_=None):
super(OperatingSystemSection_Type, self).__init__(required, Info, )
self.version = _cast(None, version)
self.id = _cast(int, id)
self.Description = Description
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
def factory(*args_, **kwargs_):
if OperatingSystemSection_Type.subclass:
return OperatingSystemSection_Type.subclass(*args_, **kwargs_)
else:
return OperatingSystemSection_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def get_version(self): return self.version
def set_version(self, version): self.version = version
def get_id(self): return self.id
def set_id(self, id): self.id = id
def export(self, outfile, level, namespace_='ovf:', name_='OperatingSystemSection_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='OperatingSystemSection_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='OperatingSystemSection_Type'):
super(OperatingSystemSection_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='OperatingSystemSection_Type')
if self.version is not None and 'version' not in already_processed:
already_processed.append('version')
outfile.write(' version=%s' % (self.gds_format_string(quote_attrib(self.version).encode(ExternalEncoding), input_name='version'), ))
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
outfile.write(' id="%s"' % self.gds_format_integer(self.id, input_name='id'))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='OperatingSystemSection_Type', fromsubclass_=False):
super(OperatingSystemSection_Type, self).exportChildren(outfile, level, namespace_, name_, True)
if self.Description is not None:
self.Description.export(outfile, level, namespace_, name_='Description')
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.Description is not None or
self.anytypeobjs_ or
super(OperatingSystemSection_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='OperatingSystemSection_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.version is not None and 'version' not in already_processed:
already_processed.append('version')
showIndent(outfile, level)
outfile.write('version = "%s",\n' % (self.version,))
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
showIndent(outfile, level)
outfile.write('id = %d,\n' % (self.id,))
super(OperatingSystemSection_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(OperatingSystemSection_Type, self).exportLiteralChildren(outfile, level, name_)
if self.Description is not None:
showIndent(outfile, level)
outfile.write('Description=model_.Msg_Type(\n')
self.Description.exportLiteral(outfile, level, name_='Description')
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('version', node)
if value is not None and 'version' not in already_processed:
already_processed.append('version')
self.version = value
value = find_attr_value_('id', node)
if value is not None and 'id' not in already_processed:
already_processed.append('id')
try:
self.id = int(value)
except ValueError, exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
super(OperatingSystemSection_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Description':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.set_Description(obj_)
else:
obj_ = self.gds_build_any(child_, 'OperatingSystemSection_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
super(OperatingSystemSection_Type, self).buildChildren(child_, node, nodeName_, True)
# end class OperatingSystemSection_Type
class EulaSection_Type(Section_Type):
"""End-User License Agreement"""
subclass = None
superclass = Section_Type
def __init__(self, required=None, Info=None, License=None, anytypeobjs_=None):
super(EulaSection_Type, self).__init__(required, Info, )
self.License = License
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
def factory(*args_, **kwargs_):
if EulaSection_Type.subclass:
return EulaSection_Type.subclass(*args_, **kwargs_)
else:
return EulaSection_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_License(self): return self.License
def set_License(self, License): self.License = License
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def export(self, outfile, level, namespace_='ovf:', name_='EulaSection_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='EulaSection_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='EulaSection_Type'):
super(EulaSection_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='EulaSection_Type')
def exportChildren(self, outfile, level, namespace_='ovf:', name_='EulaSection_Type', fromsubclass_=False):
super(EulaSection_Type, self).exportChildren(outfile, level, namespace_, name_, True)
if self.License is not None:
self.License.export(outfile, level, namespace_, name_='License', )
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.License is not None or
self.anytypeobjs_ or
super(EulaSection_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='EulaSection_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
super(EulaSection_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(EulaSection_Type, self).exportLiteralChildren(outfile, level, name_)
if self.License is not None:
showIndent(outfile, level)
outfile.write('License=model_.Msg_Type(\n')
self.License.exportLiteral(outfile, level, name_='License')
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
super(EulaSection_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'License':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.set_License(obj_)
else:
obj_ = self.gds_build_any(child_, 'EulaSection_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
super(EulaSection_Type, self).buildChildren(child_, node, nodeName_, True)
# end class EulaSection_Type
class VirtualHardwareSection_Type(Section_Type):
"""Specifies virtual hardware requirements for a virtual machineUnique
identifier of this VirtualHardwareSection (within a
VirtualSystem)"""
subclass = None
superclass = Section_Type
def __init__(self, required=None, Info=None, id='', transport=None, System=None, Item=None, anytypeobjs_=None):
super(VirtualHardwareSection_Type, self).__init__(required, Info, )
self.id = _cast(None, id)
self.transport = _cast(None, transport)
self.System = System
if Item is None:
self.Item = []
else:
self.Item = Item
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
def factory(*args_, **kwargs_):
if VirtualHardwareSection_Type.subclass:
return VirtualHardwareSection_Type.subclass(*args_, **kwargs_)
else:
return VirtualHardwareSection_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_System(self): return self.System
def set_System(self, System): self.System = System
def get_Item(self): return self.Item
def set_Item(self, Item): self.Item = Item
def add_Item(self, value): self.Item.append(value)
def insert_Item(self, index, value): self.Item[index] = value
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def get_id(self): return self.id
def set_id(self, id): self.id = id
def get_transport(self): return self.transport
def set_transport(self, transport): self.transport = transport
def export(self, outfile, level, namespace_='ovf:', name_='VirtualHardwareSection_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='VirtualHardwareSection_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='VirtualHardwareSection_Type'):
super(VirtualHardwareSection_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='VirtualHardwareSection_Type')
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
if self.transport is not None and 'transport' not in already_processed:
already_processed.append('transport')
outfile.write(' transport=%s' % (self.gds_format_string(quote_attrib(self.transport).encode(ExternalEncoding), input_name='transport'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='VirtualHardwareSection_Type', fromsubclass_=False):
super(VirtualHardwareSection_Type, self).exportChildren(outfile, level, namespace_, name_, True)
if self.System is not None:
self.System.export(outfile, level, namespace_, name_='System')
for Item_ in self.Item:
Item_.export(outfile, level, namespace_, name_='Item')
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.System is not None or
self.Item or
self.anytypeobjs_ or
super(VirtualHardwareSection_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='VirtualHardwareSection_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
showIndent(outfile, level)
outfile.write('id = "%s",\n' % (self.id,))
if self.transport is not None and 'transport' not in already_processed:
already_processed.append('transport')
showIndent(outfile, level)
outfile.write('transport = "%s",\n' % (self.transport,))
super(VirtualHardwareSection_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(VirtualHardwareSection_Type, self).exportLiteralChildren(outfile, level, name_)
if self.System is not None:
showIndent(outfile, level)
outfile.write('System=model_.VSSD_Type(\n')
self.System.exportLiteral(outfile, level, name_='System')
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('Item=[\n')
level += 1
for Item_ in self.Item:
showIndent(outfile, level)
outfile.write('model_.RASD_Type(\n')
Item_.exportLiteral(outfile, level, name_='RASD_Type')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('id', node)
if value is not None and 'id' not in already_processed:
already_processed.append('id')
self.id = value
value = find_attr_value_('transport', node)
if value is not None and 'transport' not in already_processed:
already_processed.append('transport')
self.transport = value
super(VirtualHardwareSection_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'System':
obj_ = VSSD_Type.factory()
obj_.build(child_)
self.set_System(obj_)
elif nodeName_ == 'Item':
obj_ = RASD_Type.factory()
obj_.build(child_)
self.Item.append(obj_)
else:
obj_ = self.gds_build_any(child_, 'VirtualHardwareSection_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
super(VirtualHardwareSection_Type, self).buildChildren(child_, node, nodeName_, True)
# end class VirtualHardwareSection_Type
class ResourceAllocationSection_Type(Section_Type):
"""Resource constraints on a VirtualSystemCollection"""
subclass = None
superclass = Section_Type
def __init__(self, required=None, Info=None, Item=None, anytypeobjs_=None):
super(ResourceAllocationSection_Type, self).__init__(required, Info, )
if Item is None:
self.Item = []
else:
self.Item = Item
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
def factory(*args_, **kwargs_):
if ResourceAllocationSection_Type.subclass:
return ResourceAllocationSection_Type.subclass(*args_, **kwargs_)
else:
return ResourceAllocationSection_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Item(self): return self.Item
def set_Item(self, Item): self.Item = Item
def add_Item(self, value): self.Item.append(value)
def insert_Item(self, index, value): self.Item[index] = value
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def export(self, outfile, level, namespace_='ovf:', name_='ResourceAllocationSection_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='ResourceAllocationSection_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='ResourceAllocationSection_Type'):
super(ResourceAllocationSection_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ResourceAllocationSection_Type')
def exportChildren(self, outfile, level, namespace_='ovf:', name_='ResourceAllocationSection_Type', fromsubclass_=False):
super(ResourceAllocationSection_Type, self).exportChildren(outfile, level, namespace_, name_, True)
for Item_ in self.Item:
Item_.export(outfile, level, namespace_, name_='Item')
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.Item or
self.anytypeobjs_ or
super(ResourceAllocationSection_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='ResourceAllocationSection_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
super(ResourceAllocationSection_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(ResourceAllocationSection_Type, self).exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('Item=[\n')
level += 1
for Item_ in self.Item:
showIndent(outfile, level)
outfile.write('model_.RASD_Type(\n')
Item_.exportLiteral(outfile, level, name_='RASD_Type')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
super(ResourceAllocationSection_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Item':
obj_ = RASD_Type.factory()
obj_.build(child_)
self.Item.append(obj_)
else:
obj_ = self.gds_build_any(child_, 'ResourceAllocationSection_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
super(ResourceAllocationSection_Type, self).buildChildren(child_, node, nodeName_, True)
# end class ResourceAllocationSection_Type
class InstallSection_Type(Section_Type):
"""If present indicates that the virtual machine needs to be initially
booted to install and configure the softwareDelay in seconds to
wait for power off to complete after initial boot"""
subclass = None
superclass = Section_Type
def __init__(self, required=None, Info=None, initialBootStopDelay=0, anytypeobjs_=None):
super(InstallSection_Type, self).__init__(required, Info, )
self.initialBootStopDelay = _cast(int, initialBootStopDelay)
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
def factory(*args_, **kwargs_):
if InstallSection_Type.subclass:
return InstallSection_Type.subclass(*args_, **kwargs_)
else:
return InstallSection_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def get_initialBootStopDelay(self): return self.initialBootStopDelay
def set_initialBootStopDelay(self, initialBootStopDelay): self.initialBootStopDelay = initialBootStopDelay
def export(self, outfile, level, namespace_='ovf:', name_='InstallSection_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='InstallSection_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='InstallSection_Type'):
super(InstallSection_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='InstallSection_Type')
if self.initialBootStopDelay is not None and 'initialBootStopDelay' not in already_processed:
already_processed.append('initialBootStopDelay')
outfile.write(' initialBootStopDelay="%s"' % self.gds_format_integer(self.initialBootStopDelay, input_name='initialBootStopDelay'))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='InstallSection_Type', fromsubclass_=False):
super(InstallSection_Type, self).exportChildren(outfile, level, namespace_, name_, True)
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.anytypeobjs_ or
super(InstallSection_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='InstallSection_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.initialBootStopDelay is not None and 'initialBootStopDelay' not in already_processed:
already_processed.append('initialBootStopDelay')
showIndent(outfile, level)
outfile.write('initialBootStopDelay = %d,\n' % (self.initialBootStopDelay,))
super(InstallSection_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(InstallSection_Type, self).exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('initialBootStopDelay', node)
if value is not None and 'initialBootStopDelay' not in already_processed:
already_processed.append('initialBootStopDelay')
try:
self.initialBootStopDelay = int(value)
except ValueError, exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
super(InstallSection_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
obj_ = self.gds_build_any(child_, 'InstallSection_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
super(InstallSection_Type, self).buildChildren(child_, node, nodeName_, True)
# end class InstallSection_Type
class StartupSection_Type(Section_Type):
"""Specifies the order in which entities in a VirtualSystemCollection
are powered on and shut down"""
subclass = None
superclass = Section_Type
def __init__(self, required=None, Info=None, Item=None, anytypeobjs_=None):
super(StartupSection_Type, self).__init__(required, Info, )
if Item is None:
self.Item = []
else:
self.Item = Item
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
def factory(*args_, **kwargs_):
if StartupSection_Type.subclass:
return StartupSection_Type.subclass(*args_, **kwargs_)
else:
return StartupSection_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Item(self): return self.Item
def set_Item(self, Item): self.Item = Item
def add_Item(self, value): self.Item.append(value)
def insert_Item(self, index, value): self.Item[index] = value
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def export(self, outfile, level, namespace_='ovf:', name_='StartupSection_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='StartupSection_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='StartupSection_Type'):
super(StartupSection_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StartupSection_Type')
def exportChildren(self, outfile, level, namespace_='ovf:', name_='StartupSection_Type', fromsubclass_=False):
super(StartupSection_Type, self).exportChildren(outfile, level, namespace_, name_, True)
for Item_ in self.Item:
Item_.export(outfile, level, namespace_, name_='Item')
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.Item or
self.anytypeobjs_ or
super(StartupSection_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='StartupSection_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
super(StartupSection_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(StartupSection_Type, self).exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('Item=[\n')
level += 1
for Item_ in self.Item:
showIndent(outfile, level)
outfile.write('model_.ItemType(\n')
Item_.exportLiteral(outfile, level, name_='ItemType')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
super(StartupSection_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Item':
obj_ = ItemType.factory()
obj_.build(child_)
self.Item.append(obj_)
else:
obj_ = self.gds_build_any(child_, 'StartupSection_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
super(StartupSection_Type, self).buildChildren(child_, node, nodeName_, True)
# end class StartupSection_Type
class DeploymentOptionSection_Type(Section_Type):
"""Enumeration of discrete deployment options"""
subclass = None
superclass = Section_Type
def __init__(self, required=None, Info=None, Configuration=None, anytypeobjs_=None):
super(DeploymentOptionSection_Type, self).__init__(required, Info, )
if Configuration is None:
self.Configuration = []
else:
self.Configuration = Configuration
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
def factory(*args_, **kwargs_):
if DeploymentOptionSection_Type.subclass:
return DeploymentOptionSection_Type.subclass(*args_, **kwargs_)
else:
return DeploymentOptionSection_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Configuration(self): return self.Configuration
def set_Configuration(self, Configuration): self.Configuration = Configuration
def add_Configuration(self, value): self.Configuration.append(value)
def insert_Configuration(self, index, value): self.Configuration[index] = value
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def export(self, outfile, level, namespace_='ovf:', name_='DeploymentOptionSection_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='DeploymentOptionSection_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='DeploymentOptionSection_Type'):
super(DeploymentOptionSection_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DeploymentOptionSection_Type')
def exportChildren(self, outfile, level, namespace_='ovf:', name_='DeploymentOptionSection_Type', fromsubclass_=False):
super(DeploymentOptionSection_Type, self).exportChildren(outfile, level, namespace_, name_, True)
for Configuration_ in self.Configuration:
Configuration_.export(outfile, level, namespace_, name_='Configuration')
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.Configuration or
self.anytypeobjs_ or
super(DeploymentOptionSection_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='DeploymentOptionSection_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
super(DeploymentOptionSection_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(DeploymentOptionSection_Type, self).exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('Configuration=[\n')
level += 1
for Configuration_ in self.Configuration:
showIndent(outfile, level)
outfile.write('model_.ConfigurationType(\n')
Configuration_.exportLiteral(outfile, level, name_='ConfigurationType')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
super(DeploymentOptionSection_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Configuration':
obj_ = ConfigurationType.factory()
obj_.build(child_)
self.Configuration.append(obj_)
else:
obj_ = self.gds_build_any(child_, 'DeploymentOptionSection_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
super(DeploymentOptionSection_Type, self).buildChildren(child_, node, nodeName_, True)
# end class DeploymentOptionSection_Type
class cimDateTime(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, CIM_DateTime=None, Interval=None, Date=None, Time=None, Datetime=None):
self.CIM_DateTime = CIM_DateTime
self.Interval = Interval
self.Date = Date
self.Time = Time
self.Datetime = Datetime
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimDateTime.subclass:
return cimDateTime.subclass(*args_, **kwargs_)
else:
return cimDateTime(*args_, **kwargs_)
factory = staticmethod(factory)
def get_CIM_DateTime(self): return self.CIM_DateTime
def set_CIM_DateTime(self, CIM_DateTime): self.CIM_DateTime = CIM_DateTime
def get_Interval(self): return self.Interval
def set_Interval(self, Interval): self.Interval = Interval
def get_Date(self): return self.Date
def set_Date(self, Date): self.Date = Date
def get_Time(self): return self.Time
def set_Time(self, Time): self.Time = Time
def get_Datetime(self): return self.Datetime
def set_Datetime(self, Datetime): self.Datetime = Datetime
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimDateTime', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimDateTime')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimDateTime'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimDateTime', fromsubclass_=False):
if self.CIM_DateTime is not None:
showIndent(outfile, level)
outfile.write('<%sCIM_DateTime>%s</%sCIM_DateTime>\n' % (namespace_, self.gds_format_string(quote_xml(self.CIM_DateTime).encode(ExternalEncoding), input_name='CIM_DateTime'), namespace_))
if self.Interval is not None:
showIndent(outfile, level)
outfile.write('<%sInterval>%s</%sInterval>\n' % (namespace_, self.gds_format_string(quote_xml(self.Interval).encode(ExternalEncoding), input_name='Interval'), namespace_))
if self.Date is not None:
showIndent(outfile, level)
outfile.write('<%sDate>%s</%sDate>\n' % (namespace_, self.gds_format_string(quote_xml(self.Date).encode(ExternalEncoding), input_name='Date'), namespace_))
if self.Time is not None:
showIndent(outfile, level)
outfile.write('<%sTime>%s</%sTime>\n' % (namespace_, self.gds_format_string(quote_xml(self.Time).encode(ExternalEncoding), input_name='Time'), namespace_))
if self.Datetime is not None:
showIndent(outfile, level)
outfile.write('<%sDatetime>%s</%sDatetime>\n' % (namespace_, self.gds_format_string(quote_xml(self.Datetime).encode(ExternalEncoding), input_name='Datetime'), namespace_))
def hasContent_(self):
if (
self.CIM_DateTime is not None or
self.Interval is not None or
self.Date is not None or
self.Time is not None or
self.Datetime is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimDateTime'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
if self.CIM_DateTime is not None:
showIndent(outfile, level)
outfile.write('CIM_DateTime=%s,\n' % quote_python(self.CIM_DateTime).encode(ExternalEncoding))
if self.Interval is not None:
showIndent(outfile, level)
outfile.write('Interval=%s,\n' % quote_python(self.Interval).encode(ExternalEncoding))
if self.Date is not None:
showIndent(outfile, level)
outfile.write('Date=%s,\n' % quote_python(self.Date).encode(ExternalEncoding))
if self.Time is not None:
showIndent(outfile, level)
outfile.write('Time=%s,\n' % quote_python(self.Time).encode(ExternalEncoding))
if self.Datetime is not None:
showIndent(outfile, level)
outfile.write('Datetime=%s,\n' % quote_python(self.Datetime).encode(ExternalEncoding))
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'CIM_DateTime':
CIM_DateTime_ = child_.text
CIM_DateTime_ = self.gds_validate_string(CIM_DateTime_, node, 'CIM_DateTime')
self.CIM_DateTime = CIM_DateTime_
elif nodeName_ == 'Interval':
Interval_ = child_.text
Interval_ = self.gds_validate_string(Interval_, node, 'Interval')
self.Interval = Interval_
elif nodeName_ == 'Date':
Date_ = child_.text
Date_ = self.gds_validate_string(Date_, node, 'Date')
self.Date = Date_
elif nodeName_ == 'Time':
Time_ = child_.text
Time_ = self.gds_validate_string(Time_, node, 'Time')
self.Time = Time_
elif nodeName_ == 'Datetime':
Datetime_ = child_.text
Datetime_ = self.gds_validate_string(Datetime_, node, 'Datetime')
self.Datetime = Datetime_
# end class cimDateTime
class cimUnsignedByte(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimUnsignedByte.subclass:
return cimUnsignedByte.subclass(*args_, **kwargs_)
else:
return cimUnsignedByte(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimUnsignedByte', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimUnsignedByte')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimUnsignedByte'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimUnsignedByte', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimUnsignedByte'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimUnsignedByte
class cimByte(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimByte.subclass:
return cimByte.subclass(*args_, **kwargs_)
else:
return cimByte(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimByte', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimByte')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimByte'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimByte', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimByte'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimByte
class cimUnsignedShort(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimUnsignedShort.subclass:
return cimUnsignedShort.subclass(*args_, **kwargs_)
else:
return cimUnsignedShort(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimUnsignedShort', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimUnsignedShort')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimUnsignedShort'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimUnsignedShort', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimUnsignedShort'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimUnsignedShort
class cimShort(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimShort.subclass:
return cimShort.subclass(*args_, **kwargs_)
else:
return cimShort(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimShort', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimShort')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimShort'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimShort', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimShort'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimShort
class cimUnsignedInt(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None, extensiontype_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
self.extensiontype_ = extensiontype_
def factory(*args_, **kwargs_):
if cimUnsignedInt.subclass:
return cimUnsignedInt.subclass(*args_, **kwargs_)
else:
return cimUnsignedInt(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def get_extensiontype_(self): return self.extensiontype_
def set_extensiontype_(self, extensiontype_): self.extensiontype_ = extensiontype_
def export(self, outfile, level, namespace_='ovf:', name_='cimUnsignedInt', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimUnsignedInt')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimUnsignedInt'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.extensiontype_ is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
outfile.write(' xsi:type="%s"' % self.extensiontype_)
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimUnsignedInt', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimUnsignedInt'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
value = find_attr_value_('xsi:type', node)
if value is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
self.extensiontype_ = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimUnsignedInt
class cimInt(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimInt.subclass:
return cimInt.subclass(*args_, **kwargs_)
else:
return cimInt(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimInt', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimInt')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimInt'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimInt', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimInt'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimInt
class cimUnsignedLong(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimUnsignedLong.subclass:
return cimUnsignedLong.subclass(*args_, **kwargs_)
else:
return cimUnsignedLong(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimUnsignedLong', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimUnsignedLong')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimUnsignedLong'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimUnsignedLong', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimUnsignedLong'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimUnsignedLong
class cimLong(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None, extensiontype_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
self.extensiontype_ = extensiontype_
def factory(*args_, **kwargs_):
if cimLong.subclass:
return cimLong.subclass(*args_, **kwargs_)
else:
return cimLong(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def get_extensiontype_(self): return self.extensiontype_
def set_extensiontype_(self, extensiontype_): self.extensiontype_ = extensiontype_
def export(self, outfile, level, namespace_='ovf:', name_='cimLong', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimLong')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimLong'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.extensiontype_ is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
outfile.write(' xsi:type="%s"' % self.extensiontype_)
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimLong', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimLong'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
value = find_attr_value_('xsi:type', node)
if value is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
self.extensiontype_ = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimLong
class cimString(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None, extensiontype_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
self.extensiontype_ = extensiontype_
def factory(*args_, **kwargs_):
if cimString.subclass:
return cimString.subclass(*args_, **kwargs_)
else:
return cimString(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def get_extensiontype_(self): return self.extensiontype_
def set_extensiontype_(self, extensiontype_): self.extensiontype_ = extensiontype_
def export(self, outfile, level, namespace_='ovf:', name_='cimString', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimString')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimString'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.extensiontype_ is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
outfile.write(' xsi:type="%s"' % self.extensiontype_)
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimString', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimString'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
value = find_attr_value_('xsi:type', node)
if value is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
self.extensiontype_ = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimString
class cimBoolean(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None, extensiontype_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
self.extensiontype_ = extensiontype_
def factory(*args_, **kwargs_):
if cimBoolean.subclass:
return cimBoolean.subclass(*args_, **kwargs_)
else:
return cimBoolean(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def get_extensiontype_(self): return self.extensiontype_
def set_extensiontype_(self, extensiontype_): self.extensiontype_ = extensiontype_
def export(self, outfile, level, namespace_='ovf:', name_='cimBoolean', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimBoolean')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimBoolean'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.extensiontype_ is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
outfile.write(' xsi:type="%s"' % self.extensiontype_)
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimBoolean', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimBoolean'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
value = find_attr_value_('xsi:type', node)
if value is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
self.extensiontype_ = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimBoolean
class cimFloat(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimFloat.subclass:
return cimFloat.subclass(*args_, **kwargs_)
else:
return cimFloat(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimFloat', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimFloat')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimFloat'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimFloat', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimFloat'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimFloat
class cimDouble(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimDouble.subclass:
return cimDouble.subclass(*args_, **kwargs_)
else:
return cimDouble(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimDouble', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimDouble')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimDouble'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimDouble', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimDouble'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimDouble
class cimChar16(cimString):
subclass = None
superclass = cimString
def __init__(self, valueOf_=None):
super(cimChar16, self).__init__(valueOf_, )
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimChar16.subclass:
return cimChar16.subclass(*args_, **kwargs_)
else:
return cimChar16(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimChar16', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimChar16')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimChar16'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
super(cimChar16, self).exportAttributes(outfile, level, already_processed, namespace_, name_='cimChar16')
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimChar16', fromsubclass_=False):
super(cimChar16, self).exportChildren(outfile, level, namespace_, name_, True)
pass
def hasContent_(self):
if (
self.valueOf_ or
super(cimChar16, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimChar16'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
super(cimChar16, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(cimChar16, self).exportLiteralChildren(outfile, level, name_)
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
super(cimChar16, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimChar16
class cimBase64Binary(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimBase64Binary.subclass:
return cimBase64Binary.subclass(*args_, **kwargs_)
else:
return cimBase64Binary(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimBase64Binary', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimBase64Binary')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimBase64Binary'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimBase64Binary', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimBase64Binary'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimBase64Binary
class cimReference(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, anytypeobjs_=None):
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimReference.subclass:
return cimReference.subclass(*args_, **kwargs_)
else:
return cimReference(*args_, **kwargs_)
factory = staticmethod(factory)
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimReference', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimReference')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimReference'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimReference', fromsubclass_=False):
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.anytypeobjs_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimReference'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
obj_ = self.gds_build_any(child_, 'cimReference')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
# end class cimReference
class cimHexBinary(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimHexBinary.subclass:
return cimHexBinary.subclass(*args_, **kwargs_)
else:
return cimHexBinary(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimHexBinary', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimHexBinary')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimHexBinary'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimHexBinary', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimHexBinary'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimHexBinary
class cimAnySimpleType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, valueOf_=None):
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if cimAnySimpleType.subclass:
return cimAnySimpleType.subclass(*args_, **kwargs_)
else:
return cimAnySimpleType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='cimAnySimpleType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='cimAnySimpleType')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='cimAnySimpleType'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='cimAnySimpleType', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='cimAnySimpleType'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class cimAnySimpleType
class qualifierString(cimString):
subclass = None
superclass = cimString
def __init__(self, qualifier=None, valueOf_=None, extensiontype_=None):
super(qualifierString, self).__init__(valueOf_, extensiontype_, )
self.qualifier = _cast(None, qualifier)
self.valueOf_ = valueOf_
self.extensiontype_ = extensiontype_
def factory(*args_, **kwargs_):
if qualifierString.subclass:
return qualifierString.subclass(*args_, **kwargs_)
else:
return qualifierString(*args_, **kwargs_)
factory = staticmethod(factory)
def get_qualifier(self): return self.qualifier
def set_qualifier(self, qualifier): self.qualifier = qualifier
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_extensiontype_(self): return self.extensiontype_
def set_extensiontype_(self, extensiontype_): self.extensiontype_ = extensiontype_
def export(self, outfile, level, namespace_='ovf:', name_='qualifierString', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='qualifierString')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='qualifierString'):
super(qualifierString, self).exportAttributes(outfile, level, already_processed, namespace_, name_='qualifierString')
if self.qualifier is not None and 'qualifier' not in already_processed:
already_processed.append('qualifier')
outfile.write(' qualifier=%s' % (self.gds_format_string(quote_attrib(self.qualifier).encode(ExternalEncoding), input_name='qualifier'), ))
if self.extensiontype_ is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
outfile.write(' xsi:type="%s"' % self.extensiontype_)
def exportChildren(self, outfile, level, namespace_='ovf:', name_='qualifierString', fromsubclass_=False):
super(qualifierString, self).exportChildren(outfile, level, namespace_, name_, True)
pass
def hasContent_(self):
if (
self.valueOf_ or
super(qualifierString, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='qualifierString'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.qualifier is not None and 'qualifier' not in already_processed:
already_processed.append('qualifier')
showIndent(outfile, level)
outfile.write('qualifier = "%s",\n' % (self.qualifier,))
super(qualifierString, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(qualifierString, self).exportLiteralChildren(outfile, level, name_)
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('qualifier', node)
if value is not None and 'qualifier' not in already_processed:
already_processed.append('qualifier')
self.qualifier = value
value = find_attr_value_('xsi:type', node)
if value is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
self.extensiontype_ = value
super(qualifierString, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class qualifierString
class qualifierBoolean(cimBoolean):
subclass = None
superclass = cimBoolean
def __init__(self, qualifier=None, valueOf_=None):
super(qualifierBoolean, self).__init__(valueOf_, )
self.qualifier = _cast(None, qualifier)
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if qualifierBoolean.subclass:
return qualifierBoolean.subclass(*args_, **kwargs_)
else:
return qualifierBoolean(*args_, **kwargs_)
factory = staticmethod(factory)
def get_qualifier(self): return self.qualifier
def set_qualifier(self, qualifier): self.qualifier = qualifier
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='ovf:', name_='qualifierBoolean', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='qualifierBoolean')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='qualifierBoolean'):
super(qualifierBoolean, self).exportAttributes(outfile, level, already_processed, namespace_, name_='qualifierBoolean')
if self.qualifier is not None and 'qualifier' not in already_processed:
already_processed.append('qualifier')
outfile.write(' qualifier=%s' % (self.gds_format_string(quote_attrib(self.qualifier).encode(ExternalEncoding), input_name='qualifier'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='qualifierBoolean', fromsubclass_=False):
super(qualifierBoolean, self).exportChildren(outfile, level, namespace_, name_, True)
pass
def hasContent_(self):
if (
self.valueOf_ or
super(qualifierBoolean, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='qualifierBoolean'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.qualifier is not None and 'qualifier' not in already_processed:
already_processed.append('qualifier')
showIndent(outfile, level)
outfile.write('qualifier = "%s",\n' % (self.qualifier,))
super(qualifierBoolean, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(qualifierBoolean, self).exportLiteralChildren(outfile, level, name_)
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('qualifier', node)
if value is not None and 'qualifier' not in already_processed:
already_processed.append('qualifier')
self.qualifier = value
super(qualifierBoolean, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class qualifierBoolean
class qualifierUInt32(cimUnsignedInt):
subclass = None
superclass = cimUnsignedInt
def __init__(self, qualifier=None, valueOf_=None):
super(qualifierUInt32, self).__init__(valueOf_, )
self.qualifier = _cast(None, qualifier)
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if qualifierUInt32.subclass:
return qualifierUInt32.subclass(*args_, **kwargs_)
else:
return qualifierUInt32(*args_, **kwargs_)
factory = staticmethod(factory)
def get_qualifier(self): return self.qualifier
def set_qualifier(self, qualifier): self.qualifier = qualifier
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='ovf:', name_='qualifierUInt32', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='qualifierUInt32')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='qualifierUInt32'):
super(qualifierUInt32, self).exportAttributes(outfile, level, already_processed, namespace_, name_='qualifierUInt32')
if self.qualifier is not None and 'qualifier' not in already_processed:
already_processed.append('qualifier')
outfile.write(' qualifier=%s' % (self.gds_format_string(quote_attrib(self.qualifier).encode(ExternalEncoding), input_name='qualifier'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='qualifierUInt32', fromsubclass_=False):
super(qualifierUInt32, self).exportChildren(outfile, level, namespace_, name_, True)
pass
def hasContent_(self):
if (
self.valueOf_ or
super(qualifierUInt32, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='qualifierUInt32'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.qualifier is not None and 'qualifier' not in already_processed:
already_processed.append('qualifier')
showIndent(outfile, level)
outfile.write('qualifier = "%s",\n' % (self.qualifier,))
super(qualifierUInt32, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(qualifierUInt32, self).exportLiteralChildren(outfile, level, name_)
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('qualifier', node)
if value is not None and 'qualifier' not in already_processed:
already_processed.append('qualifier')
self.qualifier = value
super(qualifierUInt32, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class qualifierUInt32
class qualifierSInt64(cimLong):
subclass = None
superclass = cimLong
def __init__(self, qualifier=None, valueOf_=None):
super(qualifierSInt64, self).__init__(valueOf_, )
self.qualifier = _cast(None, qualifier)
self.valueOf_ = valueOf_
def factory(*args_, **kwargs_):
if qualifierSInt64.subclass:
return qualifierSInt64.subclass(*args_, **kwargs_)
else:
return qualifierSInt64(*args_, **kwargs_)
factory = staticmethod(factory)
def get_qualifier(self): return self.qualifier
def set_qualifier(self, qualifier): self.qualifier = qualifier
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def export(self, outfile, level, namespace_='ovf:', name_='qualifierSInt64', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='qualifierSInt64')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='qualifierSInt64'):
super(qualifierSInt64, self).exportAttributes(outfile, level, already_processed, namespace_, name_='qualifierSInt64')
if self.qualifier is not None and 'qualifier' not in already_processed:
already_processed.append('qualifier')
outfile.write(' qualifier=%s' % (self.gds_format_string(quote_attrib(self.qualifier).encode(ExternalEncoding), input_name='qualifier'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='qualifierSInt64', fromsubclass_=False):
super(qualifierSInt64, self).exportChildren(outfile, level, namespace_, name_, True)
pass
def hasContent_(self):
if (
self.valueOf_ or
super(qualifierSInt64, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='qualifierSInt64'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.qualifier is not None and 'qualifier' not in already_processed:
already_processed.append('qualifier')
showIndent(outfile, level)
outfile.write('qualifier = "%s",\n' % (self.qualifier,))
super(qualifierSInt64, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(qualifierSInt64, self).exportLiteralChildren(outfile, level, name_)
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('qualifier', node)
if value is not None and 'qualifier' not in already_processed:
already_processed.append('qualifier')
self.qualifier = value
super(qualifierSInt64, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class qualifierSInt64
class qualifierSArray(qualifierString):
subclass = None
superclass = qualifierString
def __init__(self, qualifier=None):
super(qualifierSArray, self).__init__(qualifier, )
pass
def factory(*args_, **kwargs_):
if qualifierSArray.subclass:
return qualifierSArray.subclass(*args_, **kwargs_)
else:
return qualifierSArray(*args_, **kwargs_)
factory = staticmethod(factory)
def export(self, outfile, level, namespace_='ovf:', name_='qualifierSArray', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='qualifierSArray')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='qualifierSArray'):
super(qualifierSArray, self).exportAttributes(outfile, level, already_processed, namespace_, name_='qualifierSArray')
def exportChildren(self, outfile, level, namespace_='ovf:', name_='qualifierSArray', fromsubclass_=False):
super(qualifierSArray, self).exportChildren(outfile, level, namespace_, name_, True)
pass
def hasContent_(self):
if (
super(qualifierSArray, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='qualifierSArray'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
super(qualifierSArray, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(qualifierSArray, self).exportLiteralChildren(outfile, level, name_)
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
super(qualifierSArray, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
super(qualifierSArray, self).buildChildren(child_, node, nodeName_, True)
pass
# end class qualifierSArray
class Caption(cimString):
subclass = None
superclass = cimString
def __init__(self, valueOf_=None):
super(Caption, self).__init__(valueOf_, )
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if Caption.subclass:
return Caption.subclass(*args_, **kwargs_)
else:
return Caption(*args_, **kwargs_)
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='Caption', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='Caption')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='Caption'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
super(Caption, self).exportAttributes(outfile, level, already_processed, namespace_, name_='Caption')
def exportChildren(self, outfile, level, namespace_='ovf:', name_='Caption', fromsubclass_=False):
super(Caption, self).exportChildren(outfile, level, namespace_, name_, True)
pass
def hasContent_(self):
if (
self.valueOf_ or
super(Caption, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='Caption'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
super(Caption, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(Caption, self).exportLiteralChildren(outfile, level, name_)
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
super(Caption, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class Caption
class CIM_VirtualSystemSettingData_Type(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, AutomaticRecoveryAction=None, AutomaticShutdownAction=None, AutomaticStartupAction=None, AutomaticStartupActionDelay=None, AutomaticStartupActionSequenceNumber=None, Caption=None, ConfigurationDataRoot=None, ConfigurationFile=None, ConfigurationID=None, CreationTime=None, Description=None, ElementName=None, InstanceID=None, LogDataRoot=None, Notes=None, RecoveryFile=None, SnapshotDataRoot=None, SuspendDataRoot=None, SwapFileDataRoot=None, VirtualSystemIdentifier=None, VirtualSystemType=None, anytypeobjs_=None, extensiontype_=None):
self.AutomaticRecoveryAction = AutomaticRecoveryAction
self.AutomaticShutdownAction = AutomaticShutdownAction
self.AutomaticStartupAction = AutomaticStartupAction
self.AutomaticStartupActionDelay = AutomaticStartupActionDelay
self.AutomaticStartupActionSequenceNumber = AutomaticStartupActionSequenceNumber
self.Caption = Caption
self.ConfigurationDataRoot = ConfigurationDataRoot
self.ConfigurationFile = ConfigurationFile
self.ConfigurationID = ConfigurationID
self.CreationTime = CreationTime
self.Description = Description
self.ElementName = ElementName
self.InstanceID = InstanceID
self.LogDataRoot = LogDataRoot
if Notes is None:
self.Notes = []
else:
self.Notes = Notes
self.RecoveryFile = RecoveryFile
self.SnapshotDataRoot = SnapshotDataRoot
self.SuspendDataRoot = SuspendDataRoot
self.SwapFileDataRoot = SwapFileDataRoot
self.VirtualSystemIdentifier = VirtualSystemIdentifier
self.VirtualSystemType = VirtualSystemType
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
self.anyAttributes_ = {}
self.extensiontype_ = extensiontype_
def factory(*args_, **kwargs_):
if CIM_VirtualSystemSettingData_Type.subclass:
return CIM_VirtualSystemSettingData_Type.subclass(*args_, **kwargs_)
else:
return CIM_VirtualSystemSettingData_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_AutomaticRecoveryAction(self): return self.AutomaticRecoveryAction
def set_AutomaticRecoveryAction(self, AutomaticRecoveryAction): self.AutomaticRecoveryAction = AutomaticRecoveryAction
def validate_AutomaticRecoveryAction(self, value):
# Validate type AutomaticRecoveryAction, a restriction on xs:unsignedShort.
pass
def get_AutomaticShutdownAction(self): return self.AutomaticShutdownAction
def set_AutomaticShutdownAction(self, AutomaticShutdownAction): self.AutomaticShutdownAction = AutomaticShutdownAction
def validate_AutomaticShutdownAction(self, value):
# Validate type AutomaticShutdownAction, a restriction on xs:unsignedShort.
pass
def get_AutomaticStartupAction(self): return self.AutomaticStartupAction
def set_AutomaticStartupAction(self, AutomaticStartupAction): self.AutomaticStartupAction = AutomaticStartupAction
def validate_AutomaticStartupAction(self, value):
# Validate type AutomaticStartupAction, a restriction on xs:unsignedShort.
pass
def get_AutomaticStartupActionDelay(self): return self.AutomaticStartupActionDelay
def set_AutomaticStartupActionDelay(self, AutomaticStartupActionDelay): self.AutomaticStartupActionDelay = AutomaticStartupActionDelay
def get_AutomaticStartupActionSequenceNumber(self): return self.AutomaticStartupActionSequenceNumber
def set_AutomaticStartupActionSequenceNumber(self, AutomaticStartupActionSequenceNumber): self.AutomaticStartupActionSequenceNumber = AutomaticStartupActionSequenceNumber
def get_Caption(self): return self.Caption
def set_Caption(self, Caption): self.Caption = Caption
def get_ConfigurationDataRoot(self): return self.ConfigurationDataRoot
def set_ConfigurationDataRoot(self, ConfigurationDataRoot): self.ConfigurationDataRoot = ConfigurationDataRoot
def get_ConfigurationFile(self): return self.ConfigurationFile
def set_ConfigurationFile(self, ConfigurationFile): self.ConfigurationFile = ConfigurationFile
def get_ConfigurationID(self): return self.ConfigurationID
def set_ConfigurationID(self, ConfigurationID): self.ConfigurationID = ConfigurationID
def get_CreationTime(self): return self.CreationTime
def set_CreationTime(self, CreationTime): self.CreationTime = CreationTime
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def get_ElementName(self): return self.ElementName
def set_ElementName(self, ElementName): self.ElementName = ElementName
def get_InstanceID(self): return self.InstanceID
def set_InstanceID(self, InstanceID): self.InstanceID = InstanceID
def get_LogDataRoot(self): return self.LogDataRoot
def set_LogDataRoot(self, LogDataRoot): self.LogDataRoot = LogDataRoot
def get_Notes(self): return self.Notes
def set_Notes(self, Notes): self.Notes = Notes
def add_Notes(self, value): self.Notes.append(value)
def insert_Notes(self, index, value): self.Notes[index] = value
def get_RecoveryFile(self): return self.RecoveryFile
def set_RecoveryFile(self, RecoveryFile): self.RecoveryFile = RecoveryFile
def get_SnapshotDataRoot(self): return self.SnapshotDataRoot
def set_SnapshotDataRoot(self, SnapshotDataRoot): self.SnapshotDataRoot = SnapshotDataRoot
def get_SuspendDataRoot(self): return self.SuspendDataRoot
def set_SuspendDataRoot(self, SuspendDataRoot): self.SuspendDataRoot = SuspendDataRoot
def get_SwapFileDataRoot(self): return self.SwapFileDataRoot
def set_SwapFileDataRoot(self, SwapFileDataRoot): self.SwapFileDataRoot = SwapFileDataRoot
def get_VirtualSystemIdentifier(self): return self.VirtualSystemIdentifier
def set_VirtualSystemIdentifier(self, VirtualSystemIdentifier): self.VirtualSystemIdentifier = VirtualSystemIdentifier
def get_VirtualSystemType(self): return self.VirtualSystemType
def set_VirtualSystemType(self, VirtualSystemType): self.VirtualSystemType = VirtualSystemType
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def get_extensiontype_(self): return self.extensiontype_
def set_extensiontype_(self, extensiontype_): self.extensiontype_ = extensiontype_
def export(self, outfile, level, namespace_='ovf:', name_='CIM_VirtualSystemSettingData_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='CIM_VirtualSystemSettingData_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='CIM_VirtualSystemSettingData_Type'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.extensiontype_ is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
outfile.write(' xsi:type="%s"' % self.extensiontype_)
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='CIM_VirtualSystemSettingData_Type', fromsubclass_=False):
if self.AutomaticRecoveryAction is not None:
showIndent(outfile, level)
outfile.write('<%sAutomaticRecoveryAction>%s</%sAutomaticRecoveryAction>\n' % (namespace_, self.gds_format_integer(self.AutomaticRecoveryAction, input_name='AutomaticRecoveryAction'), namespace_))
if self.AutomaticShutdownAction is not None:
showIndent(outfile, level)
outfile.write('<%sAutomaticShutdownAction>%s</%sAutomaticShutdownAction>\n' % (namespace_, self.gds_format_integer(self.AutomaticShutdownAction, input_name='AutomaticShutdownAction'), namespace_))
if self.AutomaticStartupAction is not None:
showIndent(outfile, level)
outfile.write('<%sAutomaticStartupAction>%s</%sAutomaticStartupAction>\n' % (namespace_, self.gds_format_integer(self.AutomaticStartupAction, input_name='AutomaticStartupAction'), namespace_))
if self.AutomaticStartupActionDelay is not None:
self.AutomaticStartupActionDelay.export(outfile, level, namespace_, name_='AutomaticStartupActionDelay')
if self.AutomaticStartupActionSequenceNumber is not None:
self.AutomaticStartupActionSequenceNumber.export(outfile, level, namespace_, name_='AutomaticStartupActionSequenceNumber')
if self.Caption is not None:
self.Caption.export(outfile, level, namespace_, name_='Caption')
if self.ConfigurationDataRoot is not None:
self.ConfigurationDataRoot.export(outfile, level, namespace_, name_='ConfigurationDataRoot')
if self.ConfigurationFile is not None:
self.ConfigurationFile.export(outfile, level, namespace_, name_='ConfigurationFile')
if self.ConfigurationID is not None:
self.ConfigurationID.export(outfile, level, namespace_, name_='ConfigurationID')
if self.CreationTime is not None:
self.CreationTime.export(outfile, level, namespace_, name_='CreationTime')
if self.Description is not None:
self.Description.export(outfile, level, namespace_, name_='Description')
if self.ElementName is not None:
self.ElementName.export(outfile, level, namespace_, name_='ElementName', )
if self.InstanceID is not None:
self.InstanceID.export(outfile, level, namespace_, name_='InstanceID', )
if self.LogDataRoot is not None:
self.LogDataRoot.export(outfile, level, namespace_, name_='LogDataRoot')
for Notes_ in self.Notes:
Notes_.export(outfile, level, namespace_, name_='Notes')
if self.RecoveryFile is not None:
self.RecoveryFile.export(outfile, level, namespace_, name_='RecoveryFile')
if self.SnapshotDataRoot is not None:
self.SnapshotDataRoot.export(outfile, level, namespace_, name_='SnapshotDataRoot')
if self.SuspendDataRoot is not None:
self.SuspendDataRoot.export(outfile, level, namespace_, name_='SuspendDataRoot')
if self.SwapFileDataRoot is not None:
self.SwapFileDataRoot.export(outfile, level, namespace_, name_='SwapFileDataRoot')
if self.VirtualSystemIdentifier is not None:
self.VirtualSystemIdentifier.export(outfile, level, namespace_, name_='VirtualSystemIdentifier')
if self.VirtualSystemType is not None:
self.VirtualSystemType.export(outfile, level, namespace_, name_='VirtualSystemType')
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.AutomaticRecoveryAction is not None or
self.AutomaticShutdownAction is not None or
self.AutomaticStartupAction is not None or
self.AutomaticStartupActionDelay is not None or
self.AutomaticStartupActionSequenceNumber is not None or
self.Caption is not None or
self.ConfigurationDataRoot is not None or
self.ConfigurationFile is not None or
self.ConfigurationID is not None or
self.CreationTime is not None or
self.Description is not None or
self.ElementName is not None or
self.InstanceID is not None or
self.LogDataRoot is not None or
self.Notes or
self.RecoveryFile is not None or
self.SnapshotDataRoot is not None or
self.SuspendDataRoot is not None or
self.SwapFileDataRoot is not None or
self.VirtualSystemIdentifier is not None or
self.VirtualSystemType is not None or
self.anytypeobjs_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='CIM_VirtualSystemSettingData_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
if self.AutomaticRecoveryAction is not None:
showIndent(outfile, level)
outfile.write('AutomaticRecoveryAction=%d,\n' % self.AutomaticRecoveryAction)
if self.AutomaticShutdownAction is not None:
showIndent(outfile, level)
outfile.write('AutomaticShutdownAction=%d,\n' % self.AutomaticShutdownAction)
if self.AutomaticStartupAction is not None:
showIndent(outfile, level)
outfile.write('AutomaticStartupAction=%d,\n' % self.AutomaticStartupAction)
if self.AutomaticStartupActionDelay is not None:
showIndent(outfile, level)
outfile.write('AutomaticStartupActionDelay=model_.AutomaticStartupActionDelay(\n')
self.AutomaticStartupActionDelay.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.AutomaticStartupActionSequenceNumber is not None:
showIndent(outfile, level)
outfile.write('AutomaticStartupActionSequenceNumber=model_.AutomaticStartupActionSequenceNumber(\n')
self.AutomaticStartupActionSequenceNumber.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Caption is not None:
showIndent(outfile, level)
outfile.write('Caption=model_.Caption(\n')
self.Caption.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.ConfigurationDataRoot is not None:
showIndent(outfile, level)
outfile.write('ConfigurationDataRoot=model_.ConfigurationDataRoot(\n')
self.ConfigurationDataRoot.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.ConfigurationFile is not None:
showIndent(outfile, level)
outfile.write('ConfigurationFile=model_.ConfigurationFile(\n')
self.ConfigurationFile.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.ConfigurationID is not None:
showIndent(outfile, level)
outfile.write('ConfigurationID=model_.ConfigurationID(\n')
self.ConfigurationID.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.CreationTime is not None:
showIndent(outfile, level)
outfile.write('CreationTime=model_.CreationTime(\n')
self.CreationTime.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Description is not None:
showIndent(outfile, level)
outfile.write('Description=model_.Description(\n')
self.Description.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.ElementName is not None:
showIndent(outfile, level)
outfile.write('ElementName=model_.ElementName(\n')
self.ElementName.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.InstanceID is not None:
showIndent(outfile, level)
outfile.write('InstanceID=model_.InstanceID(\n')
self.InstanceID.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.LogDataRoot is not None:
showIndent(outfile, level)
outfile.write('LogDataRoot=model_.LogDataRoot(\n')
self.LogDataRoot.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('Notes=[\n')
level += 1
for Notes_ in self.Notes:
showIndent(outfile, level)
outfile.write('model_.Notes(\n')
Notes_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
if self.RecoveryFile is not None:
showIndent(outfile, level)
outfile.write('RecoveryFile=model_.RecoveryFile(\n')
self.RecoveryFile.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.SnapshotDataRoot is not None:
showIndent(outfile, level)
outfile.write('SnapshotDataRoot=model_.SnapshotDataRoot(\n')
self.SnapshotDataRoot.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.SuspendDataRoot is not None:
showIndent(outfile, level)
outfile.write('SuspendDataRoot=model_.SuspendDataRoot(\n')
self.SuspendDataRoot.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.SwapFileDataRoot is not None:
showIndent(outfile, level)
outfile.write('SwapFileDataRoot=model_.SwapFileDataRoot(\n')
self.SwapFileDataRoot.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.VirtualSystemIdentifier is not None:
showIndent(outfile, level)
outfile.write('VirtualSystemIdentifier=model_.VirtualSystemIdentifier(\n')
self.VirtualSystemIdentifier.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.VirtualSystemType is not None:
showIndent(outfile, level)
outfile.write('VirtualSystemType=model_.VirtualSystemType(\n')
self.VirtualSystemType.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
value = find_attr_value_('xsi:type', node)
if value is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
self.extensiontype_ = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'AutomaticRecoveryAction':
sval_ = child_.text
try:
ival_ = int(sval_)
except (TypeError, ValueError), exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'AutomaticRecoveryAction')
self.AutomaticRecoveryAction = ival_
self.validate_AutomaticRecoveryAction(self.AutomaticRecoveryAction) # validate type AutomaticRecoveryAction
elif nodeName_ == 'AutomaticShutdownAction':
sval_ = child_.text
try:
ival_ = int(sval_)
except (TypeError, ValueError), exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'AutomaticShutdownAction')
self.AutomaticShutdownAction = ival_
self.validate_AutomaticShutdownAction(self.AutomaticShutdownAction) # validate type AutomaticShutdownAction
elif nodeName_ == 'AutomaticStartupAction':
sval_ = child_.text
try:
ival_ = int(sval_)
except (TypeError, ValueError), exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'AutomaticStartupAction')
self.AutomaticStartupAction = ival_
self.validate_AutomaticStartupAction(self.AutomaticStartupAction) # validate type AutomaticStartupAction
elif nodeName_ == 'AutomaticStartupActionDelay':
obj_ = cimDateTime.factory()
obj_.build(child_)
self.set_AutomaticStartupActionDelay(obj_)
elif nodeName_ == 'AutomaticStartupActionSequenceNumber':
obj_ = cimUnsignedShort.factory()
obj_.build(child_)
self.set_AutomaticStartupActionSequenceNumber(obj_)
elif nodeName_ == 'Caption':
obj_ = Caption.factory()
obj_.build(child_)
self.set_Caption(obj_)
elif nodeName_ == 'ConfigurationDataRoot':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_ConfigurationDataRoot(obj_)
elif nodeName_ == 'ConfigurationFile':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_ConfigurationFile(obj_)
elif nodeName_ == 'ConfigurationID':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_ConfigurationID(obj_)
elif nodeName_ == 'CreationTime':
obj_ = cimDateTime.factory()
obj_.build(child_)
self.set_CreationTime(obj_)
elif nodeName_ == 'Description':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_Description(obj_)
elif nodeName_ == 'ElementName':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_ElementName(obj_)
elif nodeName_ == 'InstanceID':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_InstanceID(obj_)
elif nodeName_ == 'LogDataRoot':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_LogDataRoot(obj_)
elif nodeName_ == 'Notes':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.Notes.append(obj_)
elif nodeName_ == 'RecoveryFile':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_RecoveryFile(obj_)
elif nodeName_ == 'SnapshotDataRoot':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_SnapshotDataRoot(obj_)
elif nodeName_ == 'SuspendDataRoot':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_SuspendDataRoot(obj_)
elif nodeName_ == 'SwapFileDataRoot':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_SwapFileDataRoot(obj_)
elif nodeName_ == 'VirtualSystemIdentifier':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_VirtualSystemIdentifier(obj_)
elif nodeName_ == 'VirtualSystemType':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_VirtualSystemType(obj_)
else:
obj_ = self.gds_build_any(child_, 'CIM_VirtualSystemSettingData_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
# end class CIM_VirtualSystemSettingData_Type
class CIM_ResourceAllocationSettingData_Type(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, Address=None, AddressOnParent=None, AllocationUnits=None, AutomaticAllocation=None, AutomaticDeallocation=None, Caption=None, Connection=None, ConsumerVisibility=None, Description=None, ElementName=None, HostResource=None, InstanceID=None, Limit=None, MappingBehavior=None, OtherResourceType=None, Parent=None, PoolID=None, Reservation=None, ResourceSubType=None, ResourceType=None, VirtualQuantity=None, VirtualQuantityUnits=None, Weight=None, anytypeobjs_=None, extensiontype_=None):
self.Address = Address
self.AddressOnParent = AddressOnParent
self.AllocationUnits = AllocationUnits
self.AutomaticAllocation = AutomaticAllocation
self.AutomaticDeallocation = AutomaticDeallocation
self.Caption = Caption
if Connection is None:
self.Connection = []
else:
self.Connection = Connection
self.ConsumerVisibility = ConsumerVisibility
self.Description = Description
self.ElementName = ElementName
if HostResource is None:
self.HostResource = []
else:
self.HostResource = HostResource
self.InstanceID = InstanceID
self.Limit = Limit
self.MappingBehavior = MappingBehavior
self.OtherResourceType = OtherResourceType
self.Parent = Parent
self.PoolID = PoolID
self.Reservation = Reservation
self.ResourceSubType = ResourceSubType
self.ResourceType = ResourceType
self.VirtualQuantity = VirtualQuantity
self.VirtualQuantityUnits = VirtualQuantityUnits
self.Weight = Weight
if anytypeobjs_ is None:
self.anytypeobjs_ = []
else:
self.anytypeobjs_ = anytypeobjs_
self.anyAttributes_ = {}
self.extensiontype_ = extensiontype_
def factory(*args_, **kwargs_):
if CIM_ResourceAllocationSettingData_Type.subclass:
return CIM_ResourceAllocationSettingData_Type.subclass(*args_, **kwargs_)
else:
return CIM_ResourceAllocationSettingData_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Address(self): return self.Address
def set_Address(self, Address): self.Address = Address
def get_AddressOnParent(self): return self.AddressOnParent
def set_AddressOnParent(self, AddressOnParent): self.AddressOnParent = AddressOnParent
def get_AllocationUnits(self): return self.AllocationUnits
def set_AllocationUnits(self, AllocationUnits): self.AllocationUnits = AllocationUnits
def get_AutomaticAllocation(self): return self.AutomaticAllocation
def set_AutomaticAllocation(self, AutomaticAllocation): self.AutomaticAllocation = AutomaticAllocation
def get_AutomaticDeallocation(self): return self.AutomaticDeallocation
def set_AutomaticDeallocation(self, AutomaticDeallocation): self.AutomaticDeallocation = AutomaticDeallocation
def get_Caption(self): return self.Caption
def set_Caption(self, Caption): self.Caption = Caption
def get_Connection(self): return self.Connection
def set_Connection(self, Connection): self.Connection = Connection
def add_Connection(self, value): self.Connection.append(value)
def insert_Connection(self, index, value): self.Connection[index] = value
def get_ConsumerVisibility(self): return self.ConsumerVisibility
def set_ConsumerVisibility(self, ConsumerVisibility): self.ConsumerVisibility = ConsumerVisibility
def validate_ConsumerVisibility(self, value):
# Validate type ConsumerVisibility, a restriction on xs:unsignedShort.
pass
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def get_ElementName(self): return self.ElementName
def set_ElementName(self, ElementName): self.ElementName = ElementName
def get_HostResource(self): return self.HostResource
def set_HostResource(self, HostResource): self.HostResource = HostResource
def add_HostResource(self, value): self.HostResource.append(value)
def insert_HostResource(self, index, value): self.HostResource[index] = value
def get_InstanceID(self): return self.InstanceID
def set_InstanceID(self, InstanceID): self.InstanceID = InstanceID
def get_Limit(self): return self.Limit
def set_Limit(self, Limit): self.Limit = Limit
def get_MappingBehavior(self): return self.MappingBehavior
def set_MappingBehavior(self, MappingBehavior): self.MappingBehavior = MappingBehavior
def validate_MappingBehavior(self, value):
# Validate type MappingBehavior, a restriction on xs:unsignedShort.
pass
def get_OtherResourceType(self): return self.OtherResourceType
def set_OtherResourceType(self, OtherResourceType): self.OtherResourceType = OtherResourceType
def get_Parent(self): return self.Parent
def set_Parent(self, Parent): self.Parent = Parent
def get_PoolID(self): return self.PoolID
def set_PoolID(self, PoolID): self.PoolID = PoolID
def get_Reservation(self): return self.Reservation
def set_Reservation(self, Reservation): self.Reservation = Reservation
def get_ResourceSubType(self): return self.ResourceSubType
def set_ResourceSubType(self, ResourceSubType): self.ResourceSubType = ResourceSubType
def get_ResourceType(self): return self.ResourceType
def set_ResourceType(self, ResourceType): self.ResourceType = ResourceType
def validate_ResourceType(self, value):
# Validate type ResourceType, a restriction on xs:unsignedShort.
pass
def get_VirtualQuantity(self): return self.VirtualQuantity
def set_VirtualQuantity(self, VirtualQuantity): self.VirtualQuantity = VirtualQuantity
def get_VirtualQuantityUnits(self): return self.VirtualQuantityUnits
def set_VirtualQuantityUnits(self, VirtualQuantityUnits): self.VirtualQuantityUnits = VirtualQuantityUnits
def get_Weight(self): return self.Weight
def set_Weight(self, Weight): self.Weight = Weight
def get_anytypeobjs_(self): return self.anytypeobjs_
def set_anytypeobjs_(self, anytypeobjs_): self.anytypeobjs_ = anytypeobjs_
def add_anytypeobjs_(self, value): self.anytypeobjs_.append(value)
def insert_anytypeobjs_(self, index, value): self._anytypeobjs_[index] = value
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def get_extensiontype_(self): return self.extensiontype_
def set_extensiontype_(self, extensiontype_): self.extensiontype_ = extensiontype_
def export(self, outfile, level, namespace_='ovf:', name_='CIM_ResourceAllocationSettingData_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='CIM_ResourceAllocationSettingData_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='CIM_ResourceAllocationSettingData_Type'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.extensiontype_ is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
outfile.write(' xsi:type="%s"' % self.extensiontype_)
pass
def exportChildren(self, outfile, level, namespace_='ovf:', name_='CIM_ResourceAllocationSettingData_Type', fromsubclass_=False):
if self.Address is not None:
self.Address.export(outfile, level, namespace_, name_='Address')
if self.AddressOnParent is not None:
self.AddressOnParent.export(outfile, level, namespace_, name_='AddressOnParent')
if self.AllocationUnits is not None:
self.AllocationUnits.export(outfile, level, namespace_, name_='AllocationUnits')
if self.AutomaticAllocation is not None:
self.AutomaticAllocation.export(outfile, level, namespace_, name_='AutomaticAllocation')
if self.AutomaticDeallocation is not None:
self.AutomaticDeallocation.export(outfile, level, namespace_, name_='AutomaticDeallocation')
if self.Caption is not None:
self.Caption.export(outfile, level, namespace_, name_='Caption')
for Connection_ in self.Connection:
Connection_.export(outfile, level, namespace_, name_='Connection')
if self.ConsumerVisibility is not None:
showIndent(outfile, level)
outfile.write('<%sConsumerVisibility>%s</%sConsumerVisibility>\n' % (namespace_, self.gds_format_integer(self.ConsumerVisibility, input_name='ConsumerVisibility'), namespace_))
if self.Description is not None:
self.Description.export(outfile, level, namespace_, name_='Description')
if self.ElementName is not None:
self.ElementName.export(outfile, level, namespace_, name_='ElementName', )
for HostResource_ in self.HostResource:
HostResource_.export(outfile, level, namespace_, name_='HostResource')
if self.InstanceID is not None:
self.InstanceID.export(outfile, level, namespace_, name_='InstanceID', )
if self.Limit is not None:
self.Limit.export(outfile, level, namespace_, name_='Limit')
if self.MappingBehavior is not None:
showIndent(outfile, level)
outfile.write('<%sMappingBehavior>%s</%sMappingBehavior>\n' % (namespace_, self.gds_format_integer(self.MappingBehavior, input_name='MappingBehavior'), namespace_))
if self.OtherResourceType is not None:
self.OtherResourceType.export(outfile, level, namespace_, name_='OtherResourceType')
if self.Parent is not None:
self.Parent.export(outfile, level, namespace_, name_='Parent')
if self.PoolID is not None:
self.PoolID.export(outfile, level, namespace_, name_='PoolID')
if self.Reservation is not None:
self.Reservation.export(outfile, level, namespace_, name_='Reservation')
if self.ResourceSubType is not None:
self.ResourceSubType.export(outfile, level, namespace_, name_='ResourceSubType')
if self.ResourceType is not None:
showIndent(outfile, level)
outfile.write('<%sResourceType>%s</%sResourceType>\n' % (namespace_, self.gds_format_integer(self.ResourceType, input_name='ResourceType'), namespace_))
if self.VirtualQuantity is not None:
self.VirtualQuantity.export(outfile, level, namespace_, name_='VirtualQuantity')
if self.VirtualQuantityUnits is not None:
self.VirtualQuantityUnits.export(outfile, level, namespace_, name_='VirtualQuantityUnits')
if self.Weight is not None:
self.Weight.export(outfile, level, namespace_, name_='Weight')
for obj_ in self.anytypeobjs_:
obj_.export(outfile, level, namespace_)
def hasContent_(self):
if (
self.Address is not None or
self.AddressOnParent is not None or
self.AllocationUnits is not None or
self.AutomaticAllocation is not None or
self.AutomaticDeallocation is not None or
self.Caption is not None or
self.Connection or
self.ConsumerVisibility is not None or
self.Description is not None or
self.ElementName is not None or
self.HostResource or
self.InstanceID is not None or
self.Limit is not None or
self.MappingBehavior is not None or
self.OtherResourceType is not None or
self.Parent is not None or
self.PoolID is not None or
self.Reservation is not None or
self.ResourceSubType is not None or
self.ResourceType is not None or
self.VirtualQuantity is not None or
self.VirtualQuantityUnits is not None or
self.Weight is not None or
self.anytypeobjs_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='CIM_ResourceAllocationSettingData_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
if self.Address is not None:
showIndent(outfile, level)
outfile.write('Address=model_.Address(\n')
self.Address.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.AddressOnParent is not None:
showIndent(outfile, level)
outfile.write('AddressOnParent=model_.AddressOnParent(\n')
self.AddressOnParent.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.AllocationUnits is not None:
showIndent(outfile, level)
outfile.write('AllocationUnits=model_.AllocationUnits(\n')
self.AllocationUnits.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.AutomaticAllocation is not None:
showIndent(outfile, level)
outfile.write('AutomaticAllocation=model_.AutomaticAllocation(\n')
self.AutomaticAllocation.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.AutomaticDeallocation is not None:
showIndent(outfile, level)
outfile.write('AutomaticDeallocation=model_.AutomaticDeallocation(\n')
self.AutomaticDeallocation.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Caption is not None:
showIndent(outfile, level)
outfile.write('Caption=model_.Caption(\n')
self.Caption.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('Connection=[\n')
level += 1
for Connection_ in self.Connection:
showIndent(outfile, level)
outfile.write('model_.Connection(\n')
Connection_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
if self.ConsumerVisibility is not None:
showIndent(outfile, level)
outfile.write('ConsumerVisibility=%d,\n' % self.ConsumerVisibility)
if self.Description is not None:
showIndent(outfile, level)
outfile.write('Description=model_.Description(\n')
self.Description.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.ElementName is not None:
showIndent(outfile, level)
outfile.write('ElementName=model_.ElementName(\n')
self.ElementName.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('HostResource=[\n')
level += 1
for HostResource_ in self.HostResource:
showIndent(outfile, level)
outfile.write('model_.HostResource(\n')
HostResource_.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
if self.InstanceID is not None:
showIndent(outfile, level)
outfile.write('InstanceID=model_.InstanceID(\n')
self.InstanceID.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Limit is not None:
showIndent(outfile, level)
outfile.write('Limit=model_.Limit(\n')
self.Limit.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.MappingBehavior is not None:
showIndent(outfile, level)
outfile.write('MappingBehavior=%d,\n' % self.MappingBehavior)
if self.OtherResourceType is not None:
showIndent(outfile, level)
outfile.write('OtherResourceType=model_.OtherResourceType(\n')
self.OtherResourceType.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Parent is not None:
showIndent(outfile, level)
outfile.write('Parent=model_.Parent(\n')
self.Parent.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.PoolID is not None:
showIndent(outfile, level)
outfile.write('PoolID=model_.PoolID(\n')
self.PoolID.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Reservation is not None:
showIndent(outfile, level)
outfile.write('Reservation=model_.Reservation(\n')
self.Reservation.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.ResourceSubType is not None:
showIndent(outfile, level)
outfile.write('ResourceSubType=model_.ResourceSubType(\n')
self.ResourceSubType.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.ResourceType is not None:
showIndent(outfile, level)
outfile.write('ResourceType=%d,\n' % self.ResourceType)
if self.VirtualQuantity is not None:
showIndent(outfile, level)
outfile.write('VirtualQuantity=model_.VirtualQuantity(\n')
self.VirtualQuantity.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.VirtualQuantityUnits is not None:
showIndent(outfile, level)
outfile.write('VirtualQuantityUnits=model_.VirtualQuantityUnits(\n')
self.VirtualQuantityUnits.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
if self.Weight is not None:
showIndent(outfile, level)
outfile.write('Weight=model_.Weight(\n')
self.Weight.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('anytypeobjs_=[\n')
level += 1
for anytypeobjs_ in self.anytypeobjs_:
anytypeobjs_.exportLiteral(outfile, level)
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
value = find_attr_value_('xsi:type', node)
if value is not None and 'xsi:type' not in already_processed:
already_processed.append('xsi:type')
self.extensiontype_ = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Address':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_Address(obj_)
elif nodeName_ == 'AddressOnParent':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_AddressOnParent(obj_)
elif nodeName_ == 'AllocationUnits':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_AllocationUnits(obj_)
elif nodeName_ == 'AutomaticAllocation':
class_obj_ = self.get_class_obj_(child_, cimBoolean)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_AutomaticAllocation(obj_)
elif nodeName_ == 'AutomaticDeallocation':
class_obj_ = self.get_class_obj_(child_, cimBoolean)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_AutomaticDeallocation(obj_)
elif nodeName_ == 'Caption':
obj_ = Caption.factory()
obj_.build(child_)
self.set_Caption(obj_)
elif nodeName_ == 'Connection':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.Connection.append(obj_)
elif nodeName_ == 'ConsumerVisibility':
sval_ = child_.text
try:
ival_ = int(sval_)
except (TypeError, ValueError), exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'ConsumerVisibility')
self.ConsumerVisibility = ival_
self.validate_ConsumerVisibility(self.ConsumerVisibility) # validate type ConsumerVisibility
elif nodeName_ == 'Description':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_Description(obj_)
elif nodeName_ == 'ElementName':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_ElementName(obj_)
elif nodeName_ == 'HostResource':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.HostResource.append(obj_)
elif nodeName_ == 'InstanceID':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_InstanceID(obj_)
elif nodeName_ == 'Limit':
obj_ = cimUnsignedLong.factory()
obj_.build(child_)
self.set_Limit(obj_)
elif nodeName_ == 'MappingBehavior':
sval_ = child_.text
try:
ival_ = int(sval_)
except (TypeError, ValueError), exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'MappingBehavior')
self.MappingBehavior = ival_
self.validate_MappingBehavior(self.MappingBehavior) # validate type MappingBehavior
elif nodeName_ == 'OtherResourceType':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_OtherResourceType(obj_)
elif nodeName_ == 'Parent':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_Parent(obj_)
elif nodeName_ == 'PoolID':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_PoolID(obj_)
elif nodeName_ == 'Reservation':
obj_ = cimUnsignedLong.factory()
obj_.build(child_)
self.set_Reservation(obj_)
elif nodeName_ == 'ResourceSubType':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_ResourceSubType(obj_)
elif nodeName_ == 'ResourceType':
sval_ = child_.text
try:
ival_ = int(sval_)
except (TypeError, ValueError), exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'ResourceType')
self.ResourceType = ival_
self.validate_ResourceType(self.ResourceType) # validate type ResourceType
elif nodeName_ == 'VirtualQuantity':
obj_ = cimUnsignedLong.factory()
obj_.build(child_)
self.set_VirtualQuantity(obj_)
elif nodeName_ == 'VirtualQuantityUnits':
class_obj_ = self.get_class_obj_(child_, cimString)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_VirtualQuantityUnits(obj_)
elif nodeName_ == 'Weight':
class_obj_ = self.get_class_obj_(child_, cimUnsignedInt)
obj_ = class_obj_.factory()
obj_.build(child_)
self.set_Weight(obj_)
else:
obj_ = self.gds_build_any(child_, 'CIM_ResourceAllocationSettingData_Type')
if obj_ is not None:
self.add_anytypeobjs_(obj_)
# end class CIM_ResourceAllocationSettingData_Type
class MsgType(GeneratedsSuper):
"""String element valueString element identifier"""
subclass = None
superclass = None
def __init__(self, msgid=None, valueOf_=None):
self.msgid = _cast(None, msgid)
self.valueOf_ = valueOf_
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if MsgType.subclass:
return MsgType.subclass(*args_, **kwargs_)
else:
return MsgType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_msgid(self): return self.msgid
def set_msgid(self, msgid): self.msgid = msgid
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='MsgType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='MsgType')
if self.hasContent_():
outfile.write('>')
outfile.write(str(self.valueOf_).encode(ExternalEncoding))
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='MsgType'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.msgid is not None and 'msgid' not in already_processed:
already_processed.append('msgid')
outfile.write(' msgid=%s' % (self.gds_format_string(quote_attrib(self.msgid).encode(ExternalEncoding), input_name='msgid'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='MsgType', fromsubclass_=False):
pass
def hasContent_(self):
if (
self.valueOf_
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='MsgType'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
showIndent(outfile, level)
outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.msgid is not None and 'msgid' not in already_processed:
already_processed.append('msgid')
showIndent(outfile, level)
outfile.write('msgid = "%s",\n' % (self.msgid,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('msgid', node)
if value is not None and 'msgid' not in already_processed:
already_processed.append('msgid')
self.msgid = value
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class MsgType
class IconType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, mimeType=None, width=None, fileRef=None, height=None):
self.mimeType = _cast(None, mimeType)
self.width = _cast(int, width)
self.fileRef = _cast(None, fileRef)
self.height = _cast(int, height)
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if IconType.subclass:
return IconType.subclass(*args_, **kwargs_)
else:
return IconType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_mimeType(self): return self.mimeType
def set_mimeType(self, mimeType): self.mimeType = mimeType
def get_width(self): return self.width
def set_width(self, width): self.width = width
def get_fileRef(self): return self.fileRef
def set_fileRef(self, fileRef): self.fileRef = fileRef
def get_height(self): return self.height
def set_height(self, height): self.height = height
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='IconType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='IconType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='IconType'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.mimeType is not None and 'mimeType' not in already_processed:
already_processed.append('mimeType')
outfile.write(' mimeType=%s' % (self.gds_format_string(quote_attrib(self.mimeType).encode(ExternalEncoding), input_name='mimeType'), ))
if self.width is not None and 'width' not in already_processed:
already_processed.append('width')
outfile.write(' width="%s"' % self.gds_format_integer(self.width, input_name='width'))
if self.fileRef is not None and 'fileRef' not in already_processed:
already_processed.append('fileRef')
outfile.write(' fileRef=%s' % (self.gds_format_string(quote_attrib(self.fileRef).encode(ExternalEncoding), input_name='fileRef'), ))
if self.height is not None and 'height' not in already_processed:
already_processed.append('height')
outfile.write(' height="%s"' % self.gds_format_integer(self.height, input_name='height'))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='IconType', fromsubclass_=False):
pass
def hasContent_(self):
if (
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='IconType'):<|fim▁hole|> level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.mimeType is not None and 'mimeType' not in already_processed:
already_processed.append('mimeType')
showIndent(outfile, level)
outfile.write('mimeType = "%s",\n' % (self.mimeType,))
if self.width is not None and 'width' not in already_processed:
already_processed.append('width')
showIndent(outfile, level)
outfile.write('width = %d,\n' % (self.width,))
if self.fileRef is not None and 'fileRef' not in already_processed:
already_processed.append('fileRef')
showIndent(outfile, level)
outfile.write('fileRef = "%s",\n' % (self.fileRef,))
if self.height is not None and 'height' not in already_processed:
already_processed.append('height')
showIndent(outfile, level)
outfile.write('height = %d,\n' % (self.height,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('mimeType', node)
if value is not None and 'mimeType' not in already_processed:
already_processed.append('mimeType')
self.mimeType = value
value = find_attr_value_('width', node)
if value is not None and 'width' not in already_processed:
already_processed.append('width')
try:
self.width = int(value)
except ValueError, exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
value = find_attr_value_('fileRef', node)
if value is not None and 'fileRef' not in already_processed:
already_processed.append('fileRef')
self.fileRef = value
value = find_attr_value_('height', node)
if value is not None and 'height' not in already_processed:
already_processed.append('height')
try:
self.height = int(value)
except ValueError, exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class IconType
class PropertyType(GeneratedsSuper):
"""Property identifierProperty typeA comma-separated set of type
qualifiersDetermines whether the property value is configurable
during installationDefault value for propertyDetermines whether
the property value should be obscured during deployment"""
subclass = None
superclass = None
def __init__(self, userConfigurable=False, value='', key=None, password=False, type_=None, qualifiers=None, Label=None, Description=None, Value=None):
self.userConfigurable = _cast(bool, userConfigurable)
self.value = _cast(None, value)
self.key = _cast(None, key)
self.password = _cast(bool, password)
self.type_ = _cast(None, type_)
self.qualifiers = _cast(None, qualifiers)
self.Label = Label
self.Description = Description
if Value is None:
self.Value = []
else:
self.Value = Value
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if PropertyType.subclass:
return PropertyType.subclass(*args_, **kwargs_)
else:
return PropertyType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Label(self): return self.Label
def set_Label(self, Label): self.Label = Label
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def get_Value(self): return self.Value
def set_Value(self, Value): self.Value = Value
def add_Value(self, value): self.Value.append(value)
def insert_Value(self, index, value): self.Value[index] = value
def get_userConfigurable(self): return self.userConfigurable
def set_userConfigurable(self, userConfigurable): self.userConfigurable = userConfigurable
def get_value(self): return self.value
def set_value(self, value): self.value = value
def get_key(self): return self.key
def set_key(self, key): self.key = key
def get_password(self): return self.password
def set_password(self, password): self.password = password
def get_type(self): return self.type_
def set_type(self, type_): self.type_ = type_
def get_qualifiers(self): return self.qualifiers
def set_qualifiers(self, qualifiers): self.qualifiers = qualifiers
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='PropertyType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='PropertyType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='PropertyType'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.userConfigurable is not None and 'userConfigurable' not in already_processed:
already_processed.append('userConfigurable')
outfile.write(' userConfigurable="%s"' % self.gds_format_boolean(self.gds_str_lower(str(self.userConfigurable)), input_name='userConfigurable'))
if self.value is not None and 'value' not in already_processed:
already_processed.append('value')
outfile.write(' value=%s' % (self.gds_format_string(quote_attrib(self.value).encode(ExternalEncoding), input_name='value'), ))
if self.key is not None and 'key' not in already_processed:
already_processed.append('key')
outfile.write(' key=%s' % (self.gds_format_string(quote_attrib(self.key).encode(ExternalEncoding), input_name='key'), ))
if self.password is not None and 'password' not in already_processed:
already_processed.append('password')
outfile.write(' password="%s"' % self.gds_format_boolean(self.gds_str_lower(str(self.password)), input_name='password'))
if self.type_ is not None and 'type_' not in already_processed:
already_processed.append('type_')
outfile.write(' type=%s' % (self.gds_format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), ))
if self.qualifiers is not None and 'qualifiers' not in already_processed:
already_processed.append('qualifiers')
outfile.write(' qualifiers=%s' % (self.gds_format_string(quote_attrib(self.qualifiers).encode(ExternalEncoding), input_name='qualifiers'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='PropertyType', fromsubclass_=False):
if self.Label is not None:
self.Label.export(outfile, level, namespace_, name_='Label')
if self.Description is not None:
self.Description.export(outfile, level, namespace_, name_='Description')
for Value_ in self.Value:
Value_.export(outfile, level, namespace_, name_='Value')
def hasContent_(self):
if (
self.Label is not None or
self.Description is not None or
self.Value
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='PropertyType'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.userConfigurable is not None and 'userConfigurable' not in already_processed:
already_processed.append('userConfigurable')
showIndent(outfile, level)
outfile.write('userConfigurable = %s,\n' % (self.userConfigurable,))
if self.value is not None and 'value' not in already_processed:
already_processed.append('value')
showIndent(outfile, level)
outfile.write('value = "%s",\n' % (self.value,))
if self.key is not None and 'key' not in already_processed:
already_processed.append('key')
showIndent(outfile, level)
outfile.write('key = "%s",\n' % (self.key,))
if self.password is not None and 'password' not in already_processed:
already_processed.append('password')
showIndent(outfile, level)
outfile.write('password = %s,\n' % (self.password,))
if self.type_ is not None and 'type_' not in already_processed:
already_processed.append('type_')
showIndent(outfile, level)
outfile.write('type_ = "%s",\n' % (self.type_,))
if self.qualifiers is not None and 'qualifiers' not in already_processed:
already_processed.append('qualifiers')
showIndent(outfile, level)
outfile.write('qualifiers = "%s",\n' % (self.qualifiers,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
if self.Label is not None:
showIndent(outfile, level)
outfile.write('Label=model_.Msg_Type(\n')
self.Label.exportLiteral(outfile, level, name_='Label')
showIndent(outfile, level)
outfile.write('),\n')
if self.Description is not None:
showIndent(outfile, level)
outfile.write('Description=model_.Msg_Type(\n')
self.Description.exportLiteral(outfile, level, name_='Description')
showIndent(outfile, level)
outfile.write('),\n')
showIndent(outfile, level)
outfile.write('Value=[\n')
level += 1
for Value_ in self.Value:
showIndent(outfile, level)
outfile.write('model_.PropertyConfigurationValue_Type(\n')
Value_.exportLiteral(outfile, level, name_='PropertyConfigurationValue_Type')
showIndent(outfile, level)
outfile.write('),\n')
level -= 1
showIndent(outfile, level)
outfile.write('],\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('userConfigurable', node)
if value is not None and 'userConfigurable' not in already_processed:
already_processed.append('userConfigurable')
if value in ('true', '1'):
self.userConfigurable = True
elif value in ('false', '0'):
self.userConfigurable = False
else:
raise_parse_error(node, 'Bad boolean attribute')
value = find_attr_value_('value', node)
if value is not None and 'value' not in already_processed:
already_processed.append('value')
self.value = value
value = find_attr_value_('key', node)
if value is not None and 'key' not in already_processed:
already_processed.append('key')
self.key = value
value = find_attr_value_('password', node)
if value is not None and 'password' not in already_processed:
already_processed.append('password')
if value in ('true', '1'):
self.password = True
elif value in ('false', '0'):
self.password = False
else:
raise_parse_error(node, 'Bad boolean attribute')
value = find_attr_value_('type', node)
if value is not None and 'type' not in already_processed:
already_processed.append('type')
self.type_ = value
value = find_attr_value_('qualifiers', node)
if value is not None and 'qualifiers' not in already_processed:
already_processed.append('qualifiers')
self.qualifiers = value
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Label':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.set_Label(obj_)
elif nodeName_ == 'Description':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.set_Description(obj_)
elif nodeName_ == 'Value':
obj_ = PropertyConfigurationValue_Type.factory()
obj_.build(child_)
self.Value.append(obj_)
# end class PropertyType
class NetworkType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, name=None, Description=None):
self.name = _cast(None, name)
self.Description = Description
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if NetworkType.subclass:
return NetworkType.subclass(*args_, **kwargs_)
else:
return NetworkType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def get_name(self): return self.name
def set_name(self, name): self.name = name
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='NetworkType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='NetworkType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='NetworkType'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.name is not None and 'name' not in already_processed:
already_processed.append('name')
outfile.write(' name=%s' % (self.gds_format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='NetworkType', fromsubclass_=False):
if self.Description is not None:
self.Description.export(outfile, level, namespace_, name_='Description')
def hasContent_(self):
if (
self.Description is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='NetworkType'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.name is not None and 'name' not in already_processed:
already_processed.append('name')
showIndent(outfile, level)
outfile.write('name = "%s",\n' % (self.name,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
if self.Description is not None:
showIndent(outfile, level)
outfile.write('Description=model_.Msg_Type(\n')
self.Description.exportLiteral(outfile, level, name_='Description')
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('name', node)
if value is not None and 'name' not in already_processed:
already_processed.append('name')
self.name = value
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Description':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.set_Description(obj_)
# end class NetworkType
class ItemType(GeneratedsSuper):
"""Unique identifier of the content (within a VirtualSystemCollection)
Startup order. Entities are started up starting with lower-
numbers first, starting from 0. Items with same order identifier
may be started up concurrently or in any order. The order is
reversed for shutdown.Delay in seconds to wait for power on to
completeResumes power-on sequence if guest software reports
okDelay in seconds to wait for power off to completeStart action
to use, valid values are: 'powerOn', 'none' Stop action to use,
valid values are: ''powerOff' , 'guestShutdown', 'none'"""
subclass = None
superclass = None
def __init__(self, stopDelay=0, order=None, startAction='powerOn', startDelay=0, waitingForGuest=False, stopAction='powerOff', id=None):
self.stopDelay = _cast(int, stopDelay)
self.order = _cast(int, order)
self.startAction = _cast(None, startAction)
self.startDelay = _cast(int, startDelay)
self.waitingForGuest = _cast(bool, waitingForGuest)
self.stopAction = _cast(None, stopAction)
self.id = _cast(None, id)
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if ItemType.subclass:
return ItemType.subclass(*args_, **kwargs_)
else:
return ItemType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_stopDelay(self): return self.stopDelay
def set_stopDelay(self, stopDelay): self.stopDelay = stopDelay
def get_order(self): return self.order
def set_order(self, order): self.order = order
def get_startAction(self): return self.startAction
def set_startAction(self, startAction): self.startAction = startAction
def get_startDelay(self): return self.startDelay
def set_startDelay(self, startDelay): self.startDelay = startDelay
def get_waitingForGuest(self): return self.waitingForGuest
def set_waitingForGuest(self, waitingForGuest): self.waitingForGuest = waitingForGuest
def get_stopAction(self): return self.stopAction
def set_stopAction(self, stopAction): self.stopAction = stopAction
def get_id(self): return self.id
def set_id(self, id): self.id = id
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='ItemType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='ItemType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='ItemType'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.stopDelay is not None and 'stopDelay' not in already_processed:
already_processed.append('stopDelay')
outfile.write(' stopDelay="%s"' % self.gds_format_integer(self.stopDelay, input_name='stopDelay'))
if self.order is not None and 'order' not in already_processed:
already_processed.append('order')
outfile.write(' order="%s"' % self.gds_format_integer(self.order, input_name='order'))
if self.startAction is not None and 'startAction' not in already_processed:
already_processed.append('startAction')
outfile.write(' startAction=%s' % (self.gds_format_string(quote_attrib(self.startAction).encode(ExternalEncoding), input_name='startAction'), ))
if self.startDelay is not None and 'startDelay' not in already_processed:
already_processed.append('startDelay')
outfile.write(' startDelay="%s"' % self.gds_format_integer(self.startDelay, input_name='startDelay'))
if self.waitingForGuest is not None and 'waitingForGuest' not in already_processed:
already_processed.append('waitingForGuest')
outfile.write(' waitingForGuest="%s"' % self.gds_format_boolean(self.gds_str_lower(str(self.waitingForGuest)), input_name='waitingForGuest'))
if self.stopAction is not None and 'stopAction' not in already_processed:
already_processed.append('stopAction')
outfile.write(' stopAction=%s' % (self.gds_format_string(quote_attrib(self.stopAction).encode(ExternalEncoding), input_name='stopAction'), ))
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='ItemType', fromsubclass_=False):
pass
def hasContent_(self):
if (
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='ItemType'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.stopDelay is not None and 'stopDelay' not in already_processed:
already_processed.append('stopDelay')
showIndent(outfile, level)
outfile.write('stopDelay = %d,\n' % (self.stopDelay,))
if self.order is not None and 'order' not in already_processed:
already_processed.append('order')
showIndent(outfile, level)
outfile.write('order = %d,\n' % (self.order,))
if self.startAction is not None and 'startAction' not in already_processed:
already_processed.append('startAction')
showIndent(outfile, level)
outfile.write('startAction = "%s",\n' % (self.startAction,))
if self.startDelay is not None and 'startDelay' not in already_processed:
already_processed.append('startDelay')
showIndent(outfile, level)
outfile.write('startDelay = %d,\n' % (self.startDelay,))
if self.waitingForGuest is not None and 'waitingForGuest' not in already_processed:
already_processed.append('waitingForGuest')
showIndent(outfile, level)
outfile.write('waitingForGuest = %s,\n' % (self.waitingForGuest,))
if self.stopAction is not None and 'stopAction' not in already_processed:
already_processed.append('stopAction')
showIndent(outfile, level)
outfile.write('stopAction = "%s",\n' % (self.stopAction,))
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
showIndent(outfile, level)
outfile.write('id = "%s",\n' % (self.id,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
pass
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('stopDelay', node)
if value is not None and 'stopDelay' not in already_processed:
already_processed.append('stopDelay')
try:
self.stopDelay = int(value)
except ValueError, exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
value = find_attr_value_('order', node)
if value is not None and 'order' not in already_processed:
already_processed.append('order')
try:
self.order = int(value)
except ValueError, exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
value = find_attr_value_('startAction', node)
if value is not None and 'startAction' not in already_processed:
already_processed.append('startAction')
self.startAction = value
value = find_attr_value_('startDelay', node)
if value is not None and 'startDelay' not in already_processed:
already_processed.append('startDelay')
try:
self.startDelay = int(value)
except ValueError, exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
value = find_attr_value_('waitingForGuest', node)
if value is not None and 'waitingForGuest' not in already_processed:
already_processed.append('waitingForGuest')
if value in ('true', '1'):
self.waitingForGuest = True
elif value in ('false', '0'):
self.waitingForGuest = False
else:
raise_parse_error(node, 'Bad boolean attribute')
value = find_attr_value_('stopAction', node)
if value is not None and 'stopAction' not in already_processed:
already_processed.append('stopAction')
self.stopAction = value
value = find_attr_value_('id', node)
if value is not None and 'id' not in already_processed:
already_processed.append('id')
self.id = value
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
pass
# end class ItemType
class ConfigurationType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, default=False, id=None, Label=None, Description=None):
self.default = _cast(bool, default)
self.id = _cast(None, id)
self.Label = Label
self.Description = Description
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if ConfigurationType.subclass:
return ConfigurationType.subclass(*args_, **kwargs_)
else:
return ConfigurationType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Label(self): return self.Label
def set_Label(self, Label): self.Label = Label
def get_Description(self): return self.Description
def set_Description(self, Description): self.Description = Description
def get_default(self): return self.default
def set_default(self, default): self.default = default
def get_id(self): return self.id
def set_id(self, id): self.id = id
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='ConfigurationType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='ConfigurationType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='ConfigurationType'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
if self.default is not None and 'default' not in already_processed:
already_processed.append('default')
outfile.write(' default="%s"' % self.gds_format_boolean(self.gds_str_lower(str(self.default)), input_name='default'))
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='ConfigurationType', fromsubclass_=False):
if self.Label is not None:
self.Label.export(outfile, level, namespace_, name_='Label', )
if self.Description is not None:
self.Description.export(outfile, level, namespace_, name_='Description', )
def hasContent_(self):
if (
self.Label is not None or
self.Description is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='ConfigurationType'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.default is not None and 'default' not in already_processed:
already_processed.append('default')
showIndent(outfile, level)
outfile.write('default = %s,\n' % (self.default,))
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
showIndent(outfile, level)
outfile.write('id = "%s",\n' % (self.id,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
def exportLiteralChildren(self, outfile, level, name_):
if self.Label is not None:
showIndent(outfile, level)
outfile.write('Label=model_.Msg_Type(\n')
self.Label.exportLiteral(outfile, level, name_='Label')
showIndent(outfile, level)
outfile.write('),\n')
if self.Description is not None:
showIndent(outfile, level)
outfile.write('Description=model_.Msg_Type(\n')
self.Description.exportLiteral(outfile, level, name_='Description')
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('default', node)
if value is not None and 'default' not in already_processed:
already_processed.append('default')
if value in ('true', '1'):
self.default = True
elif value in ('false', '0'):
self.default = False
else:
raise_parse_error(node, 'Bad boolean attribute')
value = find_attr_value_('id', node)
if value is not None and 'id' not in already_processed:
already_processed.append('id')
self.id = value
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Label':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.set_Label(obj_)
elif nodeName_ == 'Description':
obj_ = Msg_Type.factory()
obj_.build(child_)
self.set_Description(obj_)
# end class ConfigurationType
class RASD_Type(CIM_ResourceAllocationSettingData_Type):
"""Wrapper for CIM_ResourceAllocationSettingData_TypeDetermines whether
import should fail if entry is not understoodConfiguration from
DeploymentOptionSection this entry is valid forStates that this
entry is a range marker"""
subclass = None
superclass = CIM_ResourceAllocationSettingData_Type
def __init__(self, Address=None, AddressOnParent=None, AllocationUnits=None, AutomaticAllocation=None, AutomaticDeallocation=None, Caption=None, Connection=None, ConsumerVisibility=None, Description=None, ElementName=None, HostResource=None, InstanceID=None, Limit=None, MappingBehavior=None, OtherResourceType=None, Parent=None, PoolID=None, Reservation=None, ResourceSubType=None, ResourceType=None, VirtualQuantity=None, VirtualQuantityUnits=None, Weight=None, anytypeobjs_=None, required=True, bound=None, configuration=None):
super(RASD_Type, self).__init__(Address, AddressOnParent, AllocationUnits, AutomaticAllocation, AutomaticDeallocation, Caption, Connection, ConsumerVisibility, Description, ElementName, HostResource, InstanceID, Limit, MappingBehavior, OtherResourceType, Parent, PoolID, Reservation, ResourceSubType, ResourceType, VirtualQuantity, VirtualQuantityUnits, Weight, anytypeobjs_, )
self.required = _cast(bool, required)
self.bound = _cast(None, bound)
self.configuration = _cast(None, configuration)
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if RASD_Type.subclass:
return RASD_Type.subclass(*args_, **kwargs_)
else:
return RASD_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_required(self): return self.required
def set_required(self, required): self.required = required
def get_bound(self): return self.bound
def set_bound(self, bound): self.bound = bound
def get_configuration(self): return self.configuration
def set_configuration(self, configuration): self.configuration = configuration
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='RASD_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='RASD_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='RASD_Type'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
super(RASD_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RASD_Type')
if self.required is not None and 'required' not in already_processed:
already_processed.append('required')
outfile.write(' required="%s"' % self.gds_format_boolean(self.gds_str_lower(str(self.required)), input_name='required'))
if self.bound is not None and 'bound' not in already_processed:
already_processed.append('bound')
outfile.write(' bound=%s' % (self.gds_format_string(quote_attrib(self.bound).encode(ExternalEncoding), input_name='bound'), ))
if self.configuration is not None and 'configuration' not in already_processed:
already_processed.append('configuration')
outfile.write(' configuration=%s' % (self.gds_format_string(quote_attrib(self.configuration).encode(ExternalEncoding), input_name='configuration'), ))
def exportChildren(self, outfile, level, namespace_='ovf:', name_='RASD_Type', fromsubclass_=False):
super(RASD_Type, self).exportChildren(outfile, level, namespace_, name_, True)
def hasContent_(self):
if (
super(RASD_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='RASD_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
if self.required is not None and 'required' not in already_processed:
already_processed.append('required')
showIndent(outfile, level)
outfile.write('required = %s,\n' % (self.required,))
if self.bound is not None and 'bound' not in already_processed:
already_processed.append('bound')
showIndent(outfile, level)
outfile.write('bound = "%s",\n' % (self.bound,))
if self.configuration is not None and 'configuration' not in already_processed:
already_processed.append('configuration')
showIndent(outfile, level)
outfile.write('configuration = "%s",\n' % (self.configuration,))
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
super(RASD_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(RASD_Type, self).exportLiteralChildren(outfile, level, name_)
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('required', node)
if value is not None and 'required' not in already_processed:
already_processed.append('required')
if value in ('true', '1'):
self.required = True
elif value in ('false', '0'):
self.required = False
else:
raise_parse_error(node, 'Bad boolean attribute')
value = find_attr_value_('bound', node)
if value is not None and 'bound' not in already_processed:
already_processed.append('bound')
self.bound = value
value = find_attr_value_('configuration', node)
if value is not None and 'configuration' not in already_processed:
already_processed.append('configuration')
self.configuration = value
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
super(RASD_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
super(RASD_Type, self).buildChildren(child_, node, nodeName_, True)
pass
# end class RASD_Type
class VSSD_Type(CIM_VirtualSystemSettingData_Type):
"""Wrapper for CIM_VirtualSystemSettingData_Type"""
subclass = None
superclass = CIM_VirtualSystemSettingData_Type
def __init__(self, AutomaticRecoveryAction=None, AutomaticShutdownAction=None, AutomaticStartupAction=None, AutomaticStartupActionDelay=None, AutomaticStartupActionSequenceNumber=None, Caption=None, ConfigurationDataRoot=None, ConfigurationFile=None, ConfigurationID=None, CreationTime=None, Description=None, ElementName=None, InstanceID=None, LogDataRoot=None, Notes=None, RecoveryFile=None, SnapshotDataRoot=None, SuspendDataRoot=None, SwapFileDataRoot=None, VirtualSystemIdentifier=None, VirtualSystemType=None, anytypeobjs_=None):
super(VSSD_Type, self).__init__(AutomaticRecoveryAction, AutomaticShutdownAction, AutomaticStartupAction, AutomaticStartupActionDelay, AutomaticStartupActionSequenceNumber, Caption, ConfigurationDataRoot, ConfigurationFile, ConfigurationID, CreationTime, Description, ElementName, InstanceID, LogDataRoot, Notes, RecoveryFile, SnapshotDataRoot, SuspendDataRoot, SwapFileDataRoot, VirtualSystemIdentifier, VirtualSystemType, anytypeobjs_, )
self.anyAttributes_ = {}
def factory(*args_, **kwargs_):
if VSSD_Type.subclass:
return VSSD_Type.subclass(*args_, **kwargs_)
else:
return VSSD_Type(*args_, **kwargs_)
factory = staticmethod(factory)
def get_anyAttributes_(self): return self.anyAttributes_
def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_
def export(self, outfile, level, namespace_='ovf:', name_='VSSD_Type', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='VSSD_Type')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='ovf:', name_='VSSD_Type'):
unique_counter = 0
for name, value in self.anyAttributes_.items():
xsinamespaceprefix = 'xsi'
xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance'
xsinamespace2 = '{%s}' % (xsinamespace1, )
if name.startswith(xsinamespace2):
name1 = name[len(xsinamespace2):]
name2 = '%s:%s' % (xsinamespaceprefix, name1, )
if name2 not in already_processed:
already_processed.append(name2)
outfile.write(' %s=%s' % (name2, quote_attrib(value), ))
else:
mo = re_.match(Namespace_extract_pat_, name)
if mo is not None:
namespace, name = mo.group(1, 2)
if name not in already_processed:
already_processed.append(name)
if namespace == 'http://www.w3.org/XML/1998/namespace':
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
else:
unique_counter += 1
outfile.write(' xmlns:yyy%d="%s"' % (unique_counter, namespace, ))
outfile.write(' yyy%d:%s=%s' % (unique_counter, name, quote_attrib(value), ))
else:
if name not in already_processed:
already_processed.append(name)
outfile.write(' %s=%s' % (name, quote_attrib(value), ))
super(VSSD_Type, self).exportAttributes(outfile, level, already_processed, namespace_, name_='VSSD_Type')
def exportChildren(self, outfile, level, namespace_='ovf:', name_='VSSD_Type', fromsubclass_=False):
super(VSSD_Type, self).exportChildren(outfile, level, namespace_, name_, True)
def hasContent_(self):
if (
super(VSSD_Type, self).hasContent_()
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='VSSD_Type'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
for name, value in self.anyAttributes_.items():
showIndent(outfile, level)
outfile.write('%s = "%s",\n' % (name, value,))
super(VSSD_Type, self).exportLiteralAttributes(outfile, level, already_processed, name_)
def exportLiteralChildren(self, outfile, level, name_):
super(VSSD_Type, self).exportLiteralChildren(outfile, level, name_)
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
self.anyAttributes_ = {}
for name, value in attrs.items():
if name not in already_processed:
self.anyAttributes_[name] = value
super(VSSD_Type, self).buildAttributes(node, attrs, already_processed)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
super(VSSD_Type, self).buildChildren(child_, node, nodeName_, True)
pass
# end class VSSD_Type
USAGE_TEXT = """
Usage: python <Parser>.py [ -s ] <in_xml_file>
"""
def usage():
print USAGE_TEXT
sys.exit(1)
def get_root_tag(node):
tag = Tag_pattern_.match(node.tag).groups()[-1]
rootClass = globals().get(tag)
return tag, rootClass
def parse(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
rootTag, rootClass = get_root_tag(rootNode)
if rootClass is None:
rootTag = 'Envelope'
rootClass = EnvelopeType
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
# sys.stdout.write('<?xml version="1.0" ?>\n')
# rootObj.export(sys.stdout, 0, name_=rootTag,
# namespacedef_='')
return rootObj
def parseString(inString):
from StringIO import StringIO
doc = parsexml_(StringIO(inString))
rootNode = doc.getroot()
rootTag, rootClass = get_root_tag(rootNode)
if rootClass is None:
rootTag = 'Envelope'
rootClass = EnvelopeType
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\n')
rootObj.export(sys.stdout, 0, name_="Envelope",
namespacedef_='')
return rootObj
def parseLiteral(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
rootTag, rootClass = get_root_tag(rootNode)
if rootClass is None:
rootTag = 'Envelope'
rootClass = EnvelopeType
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('#from ovfenvelope import *\n\n')
sys.stdout.write('import ovfenvelope as model_\n\n')
sys.stdout.write('rootObj = model_.rootTag(\n')
rootObj.exportLiteral(sys.stdout, 0, name_=rootTag)
sys.stdout.write(')\n')
return rootObj
def main():
args = sys.argv[1:]
if len(args) == 1:
parse(args[0])
else:
usage()
if __name__ == '__main__':
#import pdb; pdb.set_trace()
main()
__all__ = [
"AnnotationSection_Type",
"CIM_ResourceAllocationSettingData_Type",
"CIM_VirtualSystemSettingData_Type",
"Caption",
"ConfigurationType",
"Content_Type",
"DeploymentOptionSection_Type",
"DiskSection_Type",
"EnvelopeType",
"EulaSection_Type",
"File_Type",
"IconType",
"InstallSection_Type",
"ItemType",
"MsgType",
"Msg_Type",
"NetworkSection_Type",
"NetworkType",
"OperatingSystemSection_Type",
"ProductSection_Type",
"PropertyConfigurationValue_Type",
"PropertyType",
"RASD_Type",
"References_Type",
"ResourceAllocationSection_Type",
"Section_Type",
"StartupSection_Type",
"Strings_Type",
"VSSD_Type",
"VirtualDiskDesc_Type",
"VirtualHardwareSection_Type",
"VirtualSystemCollection_Type",
"VirtualSystem_Type",
"cimAnySimpleType",
"cimBase64Binary",
"cimBoolean",
"cimByte",
"cimChar16",
"cimDateTime",
"cimDouble",
"cimFloat",
"cimHexBinary",
"cimInt",
"cimLong",
"cimReference",
"cimShort",
"cimString",
"cimUnsignedByte",
"cimUnsignedInt",
"cimUnsignedLong",
"cimUnsignedShort",
"qualifierBoolean",
"qualifierSArray",
"qualifierSInt64",
"qualifierString",
"qualifierUInt32"
]<|fim▁end|> | |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>use anyhow::{Context, Error};
use next_swc::{custom_before_pass, TransformOptions};
use once_cell::sync::Lazy;
use std::sync::Arc;
use swc::{config::JsMinifyOptions, try_with_handler, Compiler};
use swc_common::{FileName, FilePathMapping, SourceMap};
use swc_ecmascript::transforms::pass::noop;
use wasm_bindgen::prelude::*;
fn convert_err(err: Error) -> JsValue {
format!("{:?}", err).into()
}
#[wasm_bindgen(js_name = "minifySync")]
pub fn minify_sync(s: &str, opts: JsValue) -> Result<JsValue, JsValue> {
console_error_panic_hook::set_once();
let c = compiler();
try_with_handler(c.cm.clone(), false, |handler| {
let opts: JsMinifyOptions = opts.into_serde().context("failed to parse options")?;<|fim▁hole|> let fm = c.cm.new_source_file(FileName::Anon, s.into());
let program = c
.minify(fm, handler, &opts)
.context("failed to minify file")?;
JsValue::from_serde(&program).context("failed to serialize json")
})
.map_err(convert_err)
}
#[wasm_bindgen(js_name = "transformSync")]
pub fn transform_sync(s: &str, opts: JsValue) -> Result<JsValue, JsValue> {
console_error_panic_hook::set_once();
let c = compiler();
try_with_handler(c.cm.clone(), false, |handler| {
let opts: TransformOptions = opts.into_serde().context("failed to parse options")?;
let fm = c.cm.new_source_file(
if opts.swc.filename.is_empty() {
FileName::Anon
} else {
FileName::Real(opts.swc.filename.clone().into())
},
s.into(),
);
let before_pass = custom_before_pass(c.cm.clone(), fm.clone(), &opts);
let out = c
.process_js_with_custom_pass(fm, None, handler, &opts.swc, |_| before_pass, |_| noop())
.context("failed to process js file")?;
JsValue::from_serde(&out).context("failed to serialize json")
})
.map_err(convert_err)
}
/// Get global sourcemap
fn compiler() -> Arc<Compiler> {
static C: Lazy<Arc<Compiler>> = Lazy::new(|| {
let cm = Arc::new(SourceMap::new(FilePathMapping::empty()));
Arc::new(Compiler::new(cm))
});
C.clone()
}<|fim▁end|> | |
<|file_name|>test_array.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
import tempfile
import warnings
import numpy
from numpy import testing as npt
import tables
from tables import Atom, ClosedNodeError, NoSuchNodeError
from tables.utils import byteorders
from tables.tests import common
from tables.tests.common import allequal
from tables.tests.common import unittest, test_filename
from tables.tests.common import PyTablesTestCase as TestCase
from six.moves import range
warnings.resetwarnings()
class BasicTestCase(TestCase):
"""Basic test for all the supported typecodes present in numpy.
All of them are included on pytables.
"""
endiancheck = False
def write_read(self, testarray):
a = testarray
if common.verbose:
print('\n', '-=' * 30)
print("Running test for array with type '%s'" % a.dtype.type,
end=' ')
print("for class check:", self.title)
# Create an instance of HDF5 file
filename = tempfile.mktemp(".h5")
try:
with tables.open_file(filename, mode="w") as fileh:
root = fileh.root
# Create the array under root and name 'somearray'
if self.endiancheck and a.dtype.kind != "S":
b = a.byteswap()
b.dtype = a.dtype.newbyteorder()
a = b
fileh.create_array(root, 'somearray', a, "Some array")
# Re-open the file in read-only mode
with tables.open_file(filename, mode="r") as fileh:
root = fileh.root
# Read the saved array
b = root.somearray.read()
# Compare them. They should be equal.
if common.verbose and not allequal(a, b):
print("Write and read arrays differ!")
# print("Array written:", a)
print("Array written shape:", a.shape)
print("Array written itemsize:", a.itemsize)
print("Array written type:", a.dtype.type)
# print("Array read:", b)
print("Array read shape:", b.shape)
print("Array read itemsize:", b.itemsize)
print("Array read type:", b.dtype.type)
if a.dtype.kind != "S":
print("Array written byteorder:", a.dtype.byteorder)
print("Array read byteorder:", b.dtype.byteorder)
# Check strictly the array equality
self.assertEqual(a.shape, b.shape)
self.assertEqual(a.shape, root.somearray.shape)
if a.dtype.kind == "S":
self.assertEqual(root.somearray.atom.type, "string")
else:
self.assertEqual(a.dtype.type, b.dtype.type)
self.assertEqual(a.dtype.type,
root.somearray.atom.dtype.type)
abo = byteorders[a.dtype.byteorder]
bbo = byteorders[b.dtype.byteorder]
if abo != "irrelevant":
self.assertEqual(abo, root.somearray.byteorder)
self.assertEqual(bbo, sys.byteorder)
if self.endiancheck:
self.assertNotEqual(bbo, abo)
obj = root.somearray
self.assertEqual(obj.flavor, 'numpy')
self.assertEqual(obj.shape, a.shape)
self.assertEqual(obj.ndim, a.ndim)
self.assertEqual(obj.chunkshape, None)
if a.shape:
nrows = a.shape[0]
else:
# scalar
nrows = 1
self.assertEqual(obj.nrows, nrows)
self.assertTrue(allequal(a, b))
finally:
# Then, delete the file
os.remove(filename)
def write_read_out_arg(self, testarray):
a = testarray
if common.verbose:
print('\n', '-=' * 30)
print("Running test for array with type '%s'" % a.dtype.type,
end=' ')
print("for class check:", self.title)
# Create an instance of HDF5 file
filename = tempfile.mktemp(".h5")
try:
with tables.open_file(filename, mode="w") as fileh:
root = fileh.root
# Create the array under root and name 'somearray'
if self.endiancheck and a.dtype.kind != "S":
b = a.byteswap()
b.dtype = a.dtype.newbyteorder()
a = b
fileh.create_array(root, 'somearray', a, "Some array")
# Re-open the file in read-only mode
with tables.open_file(filename, mode="r") as fileh:
root = fileh.root
# Read the saved array
b = numpy.empty_like(a, dtype=a.dtype)
root.somearray.read(out=b)
# Check strictly the array equality
self.assertEqual(a.shape, b.shape)
self.assertEqual(a.shape, root.somearray.shape)
if a.dtype.kind == "S":
self.assertEqual(root.somearray.atom.type, "string")
else:
self.assertEqual(a.dtype.type, b.dtype.type)
self.assertEqual(a.dtype.type,
root.somearray.atom.dtype.type)
abo = byteorders[a.dtype.byteorder]
bbo = byteorders[b.dtype.byteorder]
if abo != "irrelevant":
self.assertEqual(abo, root.somearray.byteorder)
self.assertEqual(abo, bbo)
if self.endiancheck:
self.assertNotEqual(bbo, sys.byteorder)
self.assertTrue(allequal(a, b))
finally:
# Then, delete the file
os.remove(filename)
def write_read_atom_shape_args(self, testarray):
a = testarray
atom = Atom.from_dtype(a.dtype)
shape = a.shape
byteorder = None
if common.verbose:
print('\n', '-=' * 30)
print("Running test for array with type '%s'" % a.dtype.type,
end=' ')
print("for class check:", self.title)
# Create an instance of HDF5 file
filename = tempfile.mktemp(".h5")
try:
with tables.open_file(filename, mode="w") as fileh:
root = fileh.root
# Create the array under root and name 'somearray'
if self.endiancheck and a.dtype.kind != "S":
b = a.byteswap()
b.dtype = a.dtype.newbyteorder()
if b.dtype.byteorder in ('>', '<'):
byteorder = byteorders[b.dtype.byteorder]
a = b
ptarr = fileh.create_array(root, 'somearray',
atom=atom, shape=shape,
title="Some array",
# specify the byteorder explicitly
# since there is no way to deduce
# it in this case
byteorder=byteorder)
self.assertEqual(shape, ptarr.shape)
self.assertEqual(atom, ptarr.atom)
ptarr[...] = a
# Re-open the file in read-only mode
with tables.open_file(filename, mode="r") as fileh:
root = fileh.root
# Read the saved array
b = root.somearray.read()
# Compare them. They should be equal.
if common.verbose and not allequal(a, b):
print("Write and read arrays differ!")
# print("Array written:", a)
print("Array written shape:", a.shape)
print("Array written itemsize:", a.itemsize)
print("Array written type:", a.dtype.type)
# print("Array read:", b)
print("Array read shape:", b.shape)
print("Array read itemsize:", b.itemsize)
print("Array read type:", b.dtype.type)
if a.dtype.kind != "S":
print("Array written byteorder:", a.dtype.byteorder)
print("Array read byteorder:", b.dtype.byteorder)
# Check strictly the array equality
self.assertEqual(a.shape, b.shape)
self.assertEqual(a.shape, root.somearray.shape)
if a.dtype.kind == "S":
self.assertEqual(root.somearray.atom.type, "string")
else:
self.assertEqual(a.dtype.type, b.dtype.type)
self.assertEqual(a.dtype.type,
root.somearray.atom.dtype.type)
abo = byteorders[a.dtype.byteorder]
bbo = byteorders[b.dtype.byteorder]
if abo != "irrelevant":
self.assertEqual(abo, root.somearray.byteorder)
self.assertEqual(bbo, sys.byteorder)
if self.endiancheck:
self.assertNotEqual(bbo, abo)
obj = root.somearray
self.assertEqual(obj.flavor, 'numpy')
self.assertEqual(obj.shape, a.shape)
self.assertEqual(obj.ndim, a.ndim)
self.assertEqual(obj.chunkshape, None)
if a.shape:
nrows = a.shape[0]
else:
# scalar
nrows = 1
self.assertEqual(obj.nrows, nrows)
self.assertTrue(allequal(a, b))
finally:
# Then, delete the file
os.remove(filename)
def setup00_char(self):
"""Data integrity during recovery (character objects)"""
if not isinstance(self.tupleChar, numpy.ndarray):
a = numpy.array(self.tupleChar, dtype="S")
else:
a = self.tupleChar
return a
def test00_char(self):
a = self.setup00_char()
self.write_read(a)
def test00_char_out_arg(self):
a = self.setup00_char()
self.write_read_out_arg(a)
def test00_char_atom_shape_args(self):
a = self.setup00_char()
self.write_read_atom_shape_args(a)
def test00b_char(self):
"""Data integrity during recovery (string objects)"""
a = self.tupleChar
filename = tempfile.mktemp(".h5")
try:
# Create an instance of HDF5 file
with tables.open_file(filename, mode="w") as fileh:
fileh.create_array(fileh.root, 'somearray', a, "Some array")
# Re-open the file in read-only mode
with tables.open_file(filename, mode="r") as fileh:
# Read the saved array
b = fileh.root.somearray.read()
if isinstance(a, bytes):
self.assertEqual(type(b), bytes)
self.assertEqual(a, b)
else:
# If a is not a python string, then it should be a list
# or ndarray
self.assertTrue(type(b) in [list, numpy.ndarray])
finally:
# Then, delete the file
os.remove(filename)
def test00b_char_out_arg(self):
"""Data integrity during recovery (string objects)"""
a = self.tupleChar
filename = tempfile.mktemp(".h5")
try:
# Create an instance of HDF5 file
with tables.open_file(filename, mode="w") as fileh:
fileh.create_array(fileh.root, 'somearray', a, "Some array")
# Re-open the file in read-only mode
with tables.open_file(filename, mode="r") as fileh:
# Read the saved array
b = numpy.empty_like(a)
if fileh.root.somearray.flavor != 'numpy':
self.assertRaises(TypeError,
lambda: fileh.root.somearray.read(out=b))
else:
fileh.root.somearray.read(out=b)
self.assertTrue(type(b), numpy.ndarray)
finally:
# Then, delete the file
os.remove(filename)
def test00b_char_atom_shape_args(self):
"""Data integrity during recovery (string objects)"""
a = self.tupleChar
filename = tempfile.mktemp(".h5")
try:
# Create an instance of HDF5 file
with tables.open_file(filename, mode="w") as fileh:
nparr = numpy.asarray(a)
atom = Atom.from_dtype(nparr.dtype)
shape = nparr.shape<|fim▁hole|> byteorder = byteorders[nparr.dtype.byteorder]
else:
byteorder = None
ptarr = fileh.create_array(fileh.root, 'somearray',
atom=atom, shape=shape,
byteorder=byteorder,
title="Some array")
self.assertEqual(shape, ptarr.shape)
self.assertEqual(atom, ptarr.atom)
ptarr[...] = a
# Re-open the file in read-only mode
with tables.open_file(filename, mode="r") as fileh:
# Read the saved array
b = numpy.empty_like(a)
if fileh.root.somearray.flavor != 'numpy':
self.assertRaises(TypeError,
lambda: fileh.root.somearray.read(out=b))
else:
fileh.root.somearray.read(out=b)
self.assertTrue(type(b), numpy.ndarray)
finally:
# Then, delete the file
os.remove(filename)
def setup01_char_nc(self):
"""Data integrity during recovery (non-contiguous character objects)"""
if not isinstance(self.tupleChar, numpy.ndarray):
a = numpy.array(self.tupleChar, dtype="S")
else:
a = self.tupleChar
if a.ndim == 0:
b = a.copy()
else:
b = a[::2]
# Ensure that this numpy string is non-contiguous
if len(b) > 1:
self.assertEqual(b.flags.contiguous, False)
return b
def test01_char_nc(self):
b = self.setup01_char_nc()
self.write_read(b)
def test01_char_nc_out_arg(self):
b = self.setup01_char_nc()
self.write_read_out_arg(b)
def test01_char_nc_atom_shape_args(self):
b = self.setup01_char_nc()
self.write_read_atom_shape_args(b)
def test02_types(self):
"""Data integrity during recovery (numerical types)"""
typecodes = ['int8', 'int16', 'int32', 'int64',
'uint8', 'uint16', 'uint32', 'uint64',
'float32', 'float64',
'complex64', 'complex128']
for name in ('float16', 'float96', 'float128',
'complex192', 'complex256'):
atomname = name.capitalize() + 'Atom'
if hasattr(tables, atomname):
typecodes.append(name)
for typecode in typecodes:
a = numpy.array(self.tupleInt, typecode)
self.write_read(a)
b = numpy.array(self.tupleInt, typecode)
self.write_read_out_arg(b)
c = numpy.array(self.tupleInt, typecode)
self.write_read_atom_shape_args(c)
def test03_types_nc(self):
"""Data integrity during recovery (non-contiguous numerical types)"""
typecodes = ['int8', 'int16', 'int32', 'int64',
'uint8', 'uint16', 'uint32', 'uint64',
'float32', 'float64',
'complex64', 'complex128', ]
for name in ('float16', 'float96', 'float128',
'complex192', 'complex256'):
atomname = name.capitalize() + 'Atom'
if hasattr(tables, atomname):
typecodes.append(name)
for typecode in typecodes:
a = numpy.array(self.tupleInt, typecode)
if a.ndim == 0:
b1 = a.copy()
b2 = a.copy()
b3 = a.copy()
else:
b1 = a[::2]
b2 = a[::2]
b3 = a[::2]
# Ensure that this array is non-contiguous
if len(b1) > 1:
self.assertEqual(b1.flags.contiguous, False)
if len(b2) > 1:
self.assertEqual(b2.flags.contiguous, False)
if len(b3) > 1:
self.assertEqual(b3.flags.contiguous, False)
self.write_read(b1)
self.write_read_out_arg(b2)
self.write_read_atom_shape_args(b3)
class Basic0DOneTestCase(BasicTestCase):
# Scalar case
title = "Rank-0 case 1"
tupleInt = 3
tupleChar = b"3"
endiancheck = True
class Basic0DTwoTestCase(BasicTestCase):
# Scalar case
title = "Rank-0 case 2"
tupleInt = 33
tupleChar = b"33"
endiancheck = True
class Basic1DZeroTestCase(BasicTestCase):
# This test case is not supported by PyTables (HDF5 limitations)
# 1D case
title = "Rank-1 case 0"
tupleInt = ()
tupleChar = ()
endiancheck = False
class Basic1DOneTestCase(BasicTestCase):
# 1D case
title = "Rank-1 case 1"
tupleInt = (3,)
tupleChar = (b"a",)
endiancheck = True
class Basic1DTwoTestCase(BasicTestCase):
# 1D case
title = "Rank-1 case 2"
tupleInt = (3, 4)
tupleChar = (b"aaa",)
endiancheck = True
class Basic1DThreeTestCase(BasicTestCase):
# 1D case
title = "Rank-1 case 3"
tupleInt = (3, 4, 5)
tupleChar = (b"aaa", b"bbb",)
endiancheck = True
class Basic2DOneTestCase(BasicTestCase):
# 2D case
title = "Rank-2 case 1"
tupleInt = numpy.array(numpy.arange((4)**2))
tupleInt.shape = (4,)*2
tupleChar = numpy.array(["abc"]*3**2, dtype="S3")
tupleChar.shape = (3,)*2
endiancheck = True
class Basic2DTwoTestCase(BasicTestCase):
# 2D case, with a multidimensional dtype
title = "Rank-2 case 2"
tupleInt = numpy.array(numpy.arange((4)), dtype=(numpy.int_, (4,)))
tupleChar = numpy.array(["abc"]*3, dtype=("S3", (3,)))
endiancheck = True
class Basic10DTestCase(BasicTestCase):
# 10D case
title = "Rank-10 test"
tupleInt = numpy.array(numpy.arange((2)**10))
tupleInt.shape = (2,)*10
tupleChar = numpy.array(
["abc"]*2**10, dtype="S3")
tupleChar.shape = (2,)*10
endiancheck = True
class Basic32DTestCase(BasicTestCase):
# 32D case (maximum)
title = "Rank-32 test"
tupleInt = numpy.array((32,))
tupleInt.shape = (1,)*32
tupleChar = numpy.array(["121"], dtype="S3")
tupleChar.shape = (1,)*32
class ReadOutArgumentTests(common.TempFileMixin, TestCase):
def setUp(self):
super(ReadOutArgumentTests, self).setUp()
self.size = 1000
def create_array(self):
array = numpy.arange(self.size, dtype='f8')
disk_array = self.h5file.create_array('/', 'array', array)
return array, disk_array
def test_read_entire_array(self):
array, disk_array = self.create_array()
out_buffer = numpy.empty((self.size, ), 'f8')
disk_array.read(out=out_buffer)
numpy.testing.assert_equal(out_buffer, array)
def test_read_contiguous_slice1(self):
array, disk_array = self.create_array()
out_buffer = numpy.arange(self.size, dtype='f8')
out_buffer = numpy.random.permutation(out_buffer)
out_buffer_orig = out_buffer.copy()
start = self.size // 2
disk_array.read(start=start, stop=self.size, out=out_buffer[start:])
numpy.testing.assert_equal(out_buffer[start:], array[start:])
numpy.testing.assert_equal(out_buffer[:start], out_buffer_orig[:start])
def test_read_contiguous_slice2(self):
array, disk_array = self.create_array()
out_buffer = numpy.arange(self.size, dtype='f8')
out_buffer = numpy.random.permutation(out_buffer)
out_buffer_orig = out_buffer.copy()
start = self.size // 4
stop = self.size - start
disk_array.read(start=start, stop=stop, out=out_buffer[start:stop])
numpy.testing.assert_equal(out_buffer[start:stop], array[start:stop])
numpy.testing.assert_equal(out_buffer[:start], out_buffer_orig[:start])
numpy.testing.assert_equal(out_buffer[stop:], out_buffer_orig[stop:])
def test_read_non_contiguous_slice_contiguous_buffer(self):
array, disk_array = self.create_array()
out_buffer = numpy.empty((self.size // 2, ), dtype='f8')
disk_array.read(start=0, stop=self.size, step=2, out=out_buffer)
numpy.testing.assert_equal(out_buffer, array[0:self.size:2])
def test_read_non_contiguous_buffer(self):
array, disk_array = self.create_array()
out_buffer = numpy.empty((self.size, ), 'f8')
out_buffer_slice = out_buffer[0:self.size:2]
# once Python 2.6 support is dropped, this could change
# to assertRaisesRegexp to check exception type and message at once
self.assertRaises(ValueError, disk_array.read, 0, self.size, 2,
out_buffer_slice)
try:
disk_array.read(0, self.size, 2, out_buffer_slice)
except ValueError as exc:
self.assertEqual('output array not C contiguous', str(exc))
def test_buffer_too_small(self):
array, disk_array = self.create_array()
out_buffer = numpy.empty((self.size // 2, ), 'f8')
self.assertRaises(ValueError, disk_array.read, 0, self.size, 1,
out_buffer)
try:
disk_array.read(0, self.size, 1, out_buffer)
except ValueError as exc:
self.assertTrue('output array size invalid, got' in str(exc))
def test_buffer_too_large(self):
array, disk_array = self.create_array()
out_buffer = numpy.empty((self.size + 1, ), 'f8')
self.assertRaises(ValueError, disk_array.read, 0, self.size, 1,
out_buffer)
try:
disk_array.read(0, self.size, 1, out_buffer)
except ValueError as exc:
self.assertTrue('output array size invalid, got' in str(exc))
class SizeOnDiskInMemoryPropertyTestCase(common.TempFileMixin, TestCase):
def setUp(self):
super(SizeOnDiskInMemoryPropertyTestCase, self).setUp()
self.array_size = (10, 10)
self.array = self.h5file.create_array(
'/', 'somearray', numpy.zeros(self.array_size, 'i4'))
def test_all_zeros(self):
self.assertEqual(self.array.size_on_disk, 10 * 10 * 4)
self.assertEqual(self.array.size_in_memory, 10 * 10 * 4)
class UnalignedAndComplexTestCase(common.TempFileMixin, TestCase):
"""Basic test for all the supported typecodes present in numpy.
Most of them are included on PyTables.
"""
def setUp(self):
super(UnalignedAndComplexTestCase, self).setUp()
self.root = self.h5file.root
def write_read(self, testArray):
if common.verbose:
print('\n', '-=' * 30)
print("\nRunning test for array with type '%s'" %
testArray.dtype.type)
# Create the array under root and name 'somearray'
a = testArray
if self.endiancheck:
byteorder = {"little": "big", "big": "little"}[sys.byteorder]
else:
byteorder = sys.byteorder
self.h5file.create_array(self.root, 'somearray', a, "Some array",
byteorder=byteorder)
if self.reopen:
self._reopen()
self.root = self.h5file.root
# Read the saved array
b = self.root.somearray.read()
# Get an array to be compared in the correct byteorder
c = a.newbyteorder(byteorder)
# Compare them. They should be equal.
if not allequal(c, b) and common.verbose:
print("Write and read arrays differ!")
print("Array written:", a)
print("Array written shape:", a.shape)
print("Array written itemsize:", a.itemsize)
print("Array written type:", a.dtype.type)
print("Array read:", b)
print("Array read shape:", b.shape)
print("Array read itemsize:", b.itemsize)
print("Array read type:", b.dtype.type)
# Check strictly the array equality
self.assertEqual(a.shape, b.shape)
self.assertEqual(a.shape, self.root.somearray.shape)
if a.dtype.byteorder != "|":
self.assertEqual(a.dtype, b.dtype)
self.assertEqual(a.dtype, self.root.somearray.atom.dtype)
self.assertEqual(byteorders[b.dtype.byteorder], sys.byteorder)
self.assertEqual(self.root.somearray.byteorder, byteorder)
self.assertTrue(allequal(c, b))
def test01_signedShort_unaligned(self):
"""Checking an unaligned signed short integer array"""
r = numpy.rec.array(b'a'*200, formats='i1,f4,i2', shape=10)
a = r["f2"]
# Ensure that this array is non-aligned
self.assertEqual(a.flags.aligned, False)
self.assertEqual(a.dtype.type, numpy.int16)
self.write_read(a)
def test02_float_unaligned(self):
"""Checking an unaligned single precision array"""
r = numpy.rec.array(b'a'*200, formats='i1,f4,i2', shape=10)
a = r["f1"]
# Ensure that this array is non-aligned
self.assertEqual(a.flags.aligned, 0)
self.assertEqual(a.dtype.type, numpy.float32)
self.write_read(a)
def test03_byte_offset(self):
"""Checking an offsetted byte array"""
r = numpy.arange(100, dtype=numpy.int8)
r.shape = (10, 10)
a = r[2]
self.write_read(a)
def test04_short_offset(self):
"""Checking an offsetted unsigned short int precision array"""
r = numpy.arange(100, dtype=numpy.uint32)
r.shape = (10, 10)
a = r[2]
self.write_read(a)
def test05_int_offset(self):
"""Checking an offsetted integer array"""
r = numpy.arange(100, dtype=numpy.int32)
r.shape = (10, 10)
a = r[2]
self.write_read(a)
def test06_longlongint_offset(self):
"""Checking an offsetted long long integer array"""
r = numpy.arange(100, dtype=numpy.int64)
r.shape = (10, 10)
a = r[2]
self.write_read(a)
def test07_float_offset(self):
"""Checking an offsetted single precision array"""
r = numpy.arange(100, dtype=numpy.float32)
r.shape = (10, 10)
a = r[2]
self.write_read(a)
def test08_double_offset(self):
"""Checking an offsetted double precision array"""
r = numpy.arange(100, dtype=numpy.float64)
r.shape = (10, 10)
a = r[2]
self.write_read(a)
def test09_float_offset_unaligned(self):
"""Checking an unaligned and offsetted single precision array"""
r = numpy.rec.array(b'a'*200, formats='i1,3f4,i2', shape=10)
a = r["f1"][3]
# Ensure that this array is non-aligned
self.assertEqual(a.flags.aligned, False)
self.assertEqual(a.dtype.type, numpy.float32)
self.write_read(a)
def test10_double_offset_unaligned(self):
"""Checking an unaligned and offsetted double precision array"""
r = numpy.rec.array(b'a'*400, formats='i1,3f8,i2', shape=10)
a = r["f1"][3]
# Ensure that this array is non-aligned
self.assertEqual(a.flags.aligned, False)
self.assertEqual(a.dtype.type, numpy.float64)
self.write_read(a)
def test11_int_byteorder(self):
"""Checking setting data with different byteorder in a range
(integer)"""
# Save an array with the reversed byteorder on it
a = numpy.arange(25, dtype=numpy.int32).reshape(5, 5)
a = a.byteswap()
a = a.newbyteorder()
array = self.h5file.create_array(
self.h5file.root, 'array', a, "byteorder (int)")
# Read a subarray (got an array with the machine byteorder)
b = array[2:4, 3:5]
b = b.byteswap()
b = b.newbyteorder()
# Set this subarray back to the array
array[2:4, 3:5] = b
b = b.byteswap()
b = b.newbyteorder()
# Set this subarray back to the array
array[2:4, 3:5] = b
# Check that the array is back in the correct byteorder
c = array[...]
if common.verbose:
print("byteorder of array on disk-->", array.byteorder)
print("byteorder of subarray-->", b.dtype.byteorder)
print("subarray-->", b)
print("retrieved array-->", c)
self.assertTrue(allequal(a, c))
def test12_float_byteorder(self):
"""Checking setting data with different byteorder in a range (float)"""
# Save an array with the reversed byteorder on it
a = numpy.arange(25, dtype=numpy.float64).reshape(5, 5)
a = a.byteswap()
a = a.newbyteorder()
array = self.h5file.create_array(
self.h5file.root, 'array', a, "byteorder (float)")
# Read a subarray (got an array with the machine byteorder)
b = array[2:4, 3:5]
b = b.byteswap()
b = b.newbyteorder()
# Set this subarray back to the array
array[2:4, 3:5] = b
b = b.byteswap()
b = b.newbyteorder()
# Set this subarray back to the array
array[2:4, 3:5] = b
# Check that the array is back in the correct byteorder
c = array[...]
if common.verbose:
print("byteorder of array on disk-->", array.byteorder)
print("byteorder of subarray-->", b.dtype.byteorder)
print("subarray-->", b)
print("retrieved array-->", c)
self.assertTrue(allequal(a, c))
class ComplexNotReopenNotEndianTestCase(UnalignedAndComplexTestCase):
endiancheck = False
reopen = False
class ComplexReopenNotEndianTestCase(UnalignedAndComplexTestCase):
endiancheck = False
reopen = True
class ComplexNotReopenEndianTestCase(UnalignedAndComplexTestCase):
endiancheck = True
reopen = False
class ComplexReopenEndianTestCase(UnalignedAndComplexTestCase):
endiancheck = True
reopen = True
class GroupsArrayTestCase(common.TempFileMixin, TestCase):
"""This test class checks combinations of arrays with groups."""
def test00_iterativeGroups(self):
"""Checking combinations of arrays with groups."""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test00_iterativeGroups..." %
self.__class__.__name__)
# Get the root group
group = self.h5file.root
# Set the type codes to test
# The typecodes below does expose an ambiguity that is reported in:
# http://projects.scipy.org/scipy/numpy/ticket/283 and
# http://projects.scipy.org/scipy/numpy/ticket/290
typecodes = ['b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'f', 'd',
'F', 'D']
if hasattr(tables, 'Float16Atom'):
typecodes.append('e')
if hasattr(tables, 'Float96Atom') or hasattr(tables, 'Float128Atom'):
typecodes.append('g')
if (hasattr(tables, 'Complex192Atom') or
hasattr(tables, 'Complex256Atom')):
typecodes.append('G')
for i, typecode in enumerate(typecodes):
a = numpy.ones((3,), typecode)
dsetname = 'array_' + typecode
if common.verbose:
print("Creating dataset:", group._g_join(dsetname))
self.h5file.create_array(group, dsetname, a, "Large array")
group = self.h5file.create_group(group, 'group' + str(i))
# Reopen the file
self._reopen()
# Get the root group
group = self.h5file.root
# Get the metadata on the previosly saved arrays
for i in range(len(typecodes)):
# Create an array for later comparison
a = numpy.ones((3,), typecodes[i])
# Get the dset object hanging from group
dset = getattr(group, 'array_' + typecodes[i])
# Get the actual array
b = dset.read()
if common.verbose:
print("Info from dataset:", dset._v_pathname)
print(" shape ==>", dset.shape, end=' ')
print(" type ==> %s" % dset.atom.dtype)
print("Array b read from file. Shape: ==>", b.shape, end=' ')
print(". Type ==> %s" % b.dtype)
self.assertEqual(a.shape, b.shape)
self.assertEqual(a.dtype, b.dtype)
self.assertTrue(allequal(a, b))
# Iterate over the next group
group = getattr(group, 'group' + str(i))
def test01_largeRankArrays(self):
"""Checking creation of large rank arrays (0 < rank <= 32)
It also uses arrays ranks which ranges until maxrank.
"""
# maximum level of recursivity (deepest group level) achieved:
# maxrank = 32 (for a effective maximum rank of 32)
# This limit is due to HDF5 library limitations.
minrank = 1
maxrank = 32
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test01_largeRankArrays..." %
self.__class__.__name__)
print("Maximum rank for tested arrays:", maxrank)
group = self.h5file.root
if common.verbose:
print("Rank array writing progress: ", end=' ')
for rank in range(minrank, maxrank + 1):
# Create an array of integers, with incrementally bigger ranges
a = numpy.ones((1,) * rank, numpy.int32)
if common.verbose:
print("%3d," % (rank), end=' ')
self.h5file.create_array(group, "array", a, "Rank: %s" % rank)
group = self.h5file.create_group(group, 'group' + str(rank))
# Reopen the file
self._reopen()
group = self.h5file.root
if common.verbose:
print()
print("Rank array reading progress: ")
# Get the metadata on the previosly saved arrays
for rank in range(minrank, maxrank + 1):
# Create an array for later comparison
a = numpy.ones((1,) * rank, numpy.int32)
# Get the actual array
b = group.array.read()
if common.verbose:
print("%3d," % (rank), end=' ')
if common.verbose and not allequal(a, b):
print("Info from dataset:", group.array._v_pathname)
print(" Shape: ==>", group.array.shape, end=' ')
print(" typecode ==> %c" % group.array.typecode)
print("Array b read from file. Shape: ==>", b.shape, end=' ')
print(". Type ==> %c" % b.dtype)
self.assertEqual(a.shape, b.shape)
self.assertEqual(a.dtype, b.dtype)
self.assertTrue(allequal(a, b))
# print(self.h5file)
# Iterate over the next group
group = self.h5file.get_node(group, 'group' + str(rank))
if common.verbose:
print() # This flush the stdout buffer
class CopyTestCase(common.TempFileMixin, TestCase):
def test01_copy(self):
"""Checking Array.copy() method."""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test01_copy..." % self.__class__.__name__)
# Create an Array
arr = numpy.array([[456, 2], [3, 457]], dtype='int16')
array1 = self.h5file.create_array(
self.h5file.root, 'array1', arr, "title array1")
# Copy to another Array
array2 = array1.copy('/', 'array2')
if self.close:
if common.verbose:
print("(closing file version)")
self._reopen()
array1 = self.h5file.root.array1
array2 = self.h5file.root.array2
if common.verbose:
print("array1-->", array1.read())
print("array2-->", array2.read())
# print("dirs-->", dir(array1), dir(array2))
print("attrs array1-->", repr(array1.attrs))
print("attrs array2-->", repr(array2.attrs))
# Check that all the elements are equal
self.assertTrue(allequal(array1.read(), array2.read()))
# Assert other properties in array
self.assertEqual(array1.nrows, array2.nrows)
self.assertEqual(array1.flavor, array2.flavor)
self.assertEqual(array1.atom.dtype, array2.atom.dtype)
self.assertEqual(array1.title, array2.title)
def test02_copy(self):
"""Checking Array.copy() method (where specified)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test02_copy..." % self.__class__.__name__)
# Create an Array
arr = numpy.array([[456, 2], [3, 457]], dtype='int16')
array1 = self.h5file.create_array(
self.h5file.root, 'array1', arr, "title array1")
# Copy to another Array
group1 = self.h5file.create_group("/", "group1")
array2 = array1.copy(group1, 'array2')
if self.close:
if common.verbose:
print("(closing file version)")
self._reopen()
array1 = self.h5file.root.array1
array2 = self.h5file.root.group1.array2
if common.verbose:
print("array1-->", array1.read())
print("array2-->", array2.read())
# print("dirs-->", dir(array1), dir(array2))
print("attrs array1-->", repr(array1.attrs))
print("attrs array2-->", repr(array2.attrs))
# Check that all the elements are equal
self.assertTrue(allequal(array1.read(), array2.read()))
# Assert other properties in array
self.assertEqual(array1.nrows, array2.nrows)
self.assertEqual(array1.flavor, array2.flavor)
self.assertEqual(array1.atom.dtype, array2.atom.dtype)
self.assertEqual(array1.title, array2.title)
def test03_copy(self):
"""Checking Array.copy() method (checking title copying)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test04_copy..." % self.__class__.__name__)
# Create an Array
arr = numpy.array([[456, 2], [3, 457]], dtype='int16')
array1 = self.h5file.create_array(
self.h5file.root, 'array1', arr, "title array1")
# Append some user attrs
array1.attrs.attr1 = "attr1"
array1.attrs.attr2 = 2
# Copy it to another Array
array2 = array1.copy('/', 'array2', title="title array2")
if self.close:
if common.verbose:
print("(closing file version)")
self._reopen()
array1 = self.h5file.root.array1
array2 = self.h5file.root.array2
# Assert user attributes
if common.verbose:
print("title of destination array-->", array2.title)
self.assertEqual(array2.title, "title array2")
def test04_copy(self):
"""Checking Array.copy() method (user attributes copied)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test05_copy..." % self.__class__.__name__)
# Create an Array
arr = numpy.array([[456, 2], [3, 457]], dtype='int16')
array1 = self.h5file.create_array(
self.h5file.root, 'array1', arr, "title array1")
# Append some user attrs
array1.attrs.attr1 = "attr1"
array1.attrs.attr2 = 2
# Copy it to another Array
array2 = array1.copy('/', 'array2', copyuserattrs=1)
if self.close:
if common.verbose:
print("(closing file version)")
self._reopen()
array1 = self.h5file.root.array1
array2 = self.h5file.root.array2
if common.verbose:
print("attrs array1-->", repr(array1.attrs))
print("attrs array2-->", repr(array2.attrs))
# Assert user attributes
self.assertEqual(array2.attrs.attr1, "attr1")
self.assertEqual(array2.attrs.attr2, 2)
def test04b_copy(self):
"""Checking Array.copy() method (user attributes not copied)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test05b_copy..." % self.__class__.__name__)
# Create an Array
arr = numpy.array([[456, 2], [3, 457]], dtype='int16')
array1 = self.h5file.create_array(
self.h5file.root, 'array1', arr, "title array1")
# Append some user attrs
array1.attrs.attr1 = "attr1"
array1.attrs.attr2 = 2
# Copy it to another Array
array2 = array1.copy('/', 'array2', copyuserattrs=0)
if self.close:
if common.verbose:
print("(closing file version)")
self._reopen()
array1 = self.h5file.root.array1
array2 = self.h5file.root.array2
if common.verbose:
print("attrs array1-->", repr(array1.attrs))
print("attrs array2-->", repr(array2.attrs))
# Assert user attributes
self.assertEqual(hasattr(array2.attrs, "attr1"), 0)
self.assertEqual(hasattr(array2.attrs, "attr2"), 0)
class CloseCopyTestCase(CopyTestCase):
close = 1
class OpenCopyTestCase(CopyTestCase):
close = 0
class CopyIndexTestCase(common.TempFileMixin, TestCase):
def test01_index(self):
"""Checking Array.copy() method with indexes."""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test01_index..." % self.__class__.__name__)
# Create a numpy
r = numpy.arange(200, dtype='int32')
r.shape = (100, 2)
# Save it in a array:
array1 = self.h5file.create_array(
self.h5file.root, 'array1', r, "title array1")
# Copy to another array
array2 = array1.copy("/", 'array2',
start=self.start,
stop=self.stop,
step=self.step)
if common.verbose:
print("array1-->", array1.read())
print("array2-->", array2.read())
print("attrs array1-->", repr(array1.attrs))
print("attrs array2-->", repr(array2.attrs))
# Check that all the elements are equal
r2 = r[self.start:self.stop:self.step]
self.assertTrue(allequal(r2, array2.read()))
# Assert the number of rows in array
if common.verbose:
print("nrows in array2-->", array2.nrows)
print("and it should be-->", r2.shape[0])
self.assertEqual(r2.shape[0], array2.nrows)
def test02_indexclosef(self):
"""Checking Array.copy() method with indexes (close file version)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test02_indexclosef..." % self.__class__.__name__)
# Create a numpy
r = numpy.arange(200, dtype='int32')
r.shape = (100, 2)
# Save it in a array:
array1 = self.h5file.create_array(
self.h5file.root, 'array1', r, "title array1")
# Copy to another array
array2 = array1.copy("/", 'array2',
start=self.start,
stop=self.stop,
step=self.step)
# Close and reopen the file
self._reopen()
array1 = self.h5file.root.array1
array2 = self.h5file.root.array2
if common.verbose:
print("array1-->", array1.read())
print("array2-->", array2.read())
print("attrs array1-->", repr(array1.attrs))
print("attrs array2-->", repr(array2.attrs))
# Check that all the elements are equal
r2 = r[self.start:self.stop:self.step]
self.assertTrue(allequal(r2, array2.read()))
# Assert the number of rows in array
if common.verbose:
print("nrows in array2-->", array2.nrows)
print("and it should be-->", r2.shape[0])
self.assertEqual(r2.shape[0], array2.nrows)
class CopyIndex1TestCase(CopyIndexTestCase):
start = 0
stop = 7
step = 1
class CopyIndex2TestCase(CopyIndexTestCase):
start = 0
stop = -1
step = 1
class CopyIndex3TestCase(CopyIndexTestCase):
start = 1
stop = 7
step = 1
class CopyIndex4TestCase(CopyIndexTestCase):
start = 0
stop = 6
step = 1
class CopyIndex5TestCase(CopyIndexTestCase):
start = 3
stop = 7
step = 1
class CopyIndex6TestCase(CopyIndexTestCase):
start = 3
stop = 6
step = 2
class CopyIndex7TestCase(CopyIndexTestCase):
start = 0
stop = 7
step = 10
class CopyIndex8TestCase(CopyIndexTestCase):
start = 6
stop = -1 # Negative values means starting from the end
step = 1
class CopyIndex9TestCase(CopyIndexTestCase):
start = 3
stop = 4
step = 1
class CopyIndex10TestCase(CopyIndexTestCase):
start = 3
stop = 4
step = 2
class CopyIndex11TestCase(CopyIndexTestCase):
start = -3
stop = -1
step = 2
class CopyIndex12TestCase(CopyIndexTestCase):
start = -1 # Should point to the last element
stop = None # None should mean the last element (including it)
step = 1
class GetItemTestCase(common.TempFileMixin, TestCase):
def test00_single(self):
"""Single element access (character types)"""
# Create the array under root and name 'somearray'
a = self.charList
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
if common.verbose:
print("Original first element:", a[0], type(a[0]))
print("Read first element:", arr[0], type(arr[0]))
self.assertTrue(allequal(a[0], arr[0]))
self.assertEqual(type(a[0]), type(arr[0]))
def test01_single(self):
"""Single element access (numerical types)"""
# Create the array under root and name 'somearray'
a = self.numericalList
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
if common.verbose:
print("Original first element:", a[0], type(a[0]))
print("Read first element:", arr[0], type(arr[0]))
self.assertEqual(a[0], arr[0])
self.assertEqual(type(a[0]), type(arr[0]))
def test02_range(self):
"""Range element access (character types)"""
# Create the array under root and name 'somearray'
a = self.charListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
if common.verbose:
print("Original elements:", a[1:4])
print("Read elements:", arr[1:4])
self.assertTrue(allequal(a[1:4], arr[1:4]))
def test03_range(self):
"""Range element access (numerical types)"""
# Create the array under root and name 'somearray'
a = self.numericalListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
if common.verbose:
print("Original elements:", a[1:4])
print("Read elements:", arr[1:4])
self.assertTrue(allequal(a[1:4], arr[1:4]))
def test04_range(self):
"""Range element access, strided (character types)"""
# Create the array under root and name 'somearray'
a = self.charListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
if common.verbose:
print("Original elements:", a[1:4:2])
print("Read elements:", arr[1:4:2])
self.assertTrue(allequal(a[1:4:2], arr[1:4:2]))
def test05_range(self):
"""Range element access, strided (numerical types)"""
# Create the array under root and name 'somearray'
a = self.numericalListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
if common.verbose:
print("Original elements:", a[1:4:2])
print("Read elements:", arr[1:4:2])
self.assertTrue(allequal(a[1:4:2], arr[1:4:2]))
def test06_negativeIndex(self):
"""Negative Index element access (character types)"""
# Create the array under root and name 'somearray'
a = self.charListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
if common.verbose:
print("Original last element:", a[-1])
print("Read last element:", arr[-1])
self.assertTrue(allequal(a[-1], arr[-1]))
def test07_negativeIndex(self):
"""Negative Index element access (numerical types)"""
# Create the array under root and name 'somearray'
a = self.numericalListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
if common.verbose:
print("Original before last element:", a[-2])
print("Read before last element:", arr[-2])
if isinstance(a[-2], numpy.ndarray):
self.assertTrue(allequal(a[-2], arr[-2]))
else:
self.assertEqual(a[-2], arr[-2])
def test08_negativeRange(self):
"""Negative range element access (character types)"""
# Create the array under root and name 'somearray'
a = self.charListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
if common.verbose:
print("Original last elements:", a[-4:-1])
print("Read last elements:", arr[-4:-1])
self.assertTrue(allequal(a[-4:-1], arr[-4:-1]))
def test09_negativeRange(self):
"""Negative range element access (numerical types)"""
# Create the array under root and name 'somearray'
a = self.numericalListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
if common.verbose:
print("Original last elements:", a[-4:-1])
print("Read last elements:", arr[-4:-1])
self.assertTrue(allequal(a[-4:-1], arr[-4:-1]))
class GI1NATestCase(GetItemTestCase, TestCase):
title = "Rank-1 case 1"
numericalList = numpy.array([3])
numericalListME = numpy.array([3, 2, 1, 0, 4, 5, 6])
charList = numpy.array(["3"], 'S')
charListME = numpy.array(
["321", "221", "121", "021", "421", "521", "621"], 'S')
class GI1NAOpenTestCase(GI1NATestCase):
close = 0
class GI1NACloseTestCase(GI1NATestCase):
close = 1
class GI2NATestCase(GetItemTestCase):
# A more complex example
title = "Rank-1,2 case 2"
numericalList = numpy.array([3, 4])
numericalListME = numpy.array([[3, 2, 1, 0, 4, 5, 6],
[2, 1, 0, 4, 5, 6, 7],
[4, 3, 2, 1, 0, 4, 5],
[3, 2, 1, 0, 4, 5, 6],
[3, 2, 1, 0, 4, 5, 6]])
charList = numpy.array(["a", "b"], 'S')
charListME = numpy.array(
[["321", "221", "121", "021", "421", "521", "621"],
["21", "21", "11", "02", "42", "21", "61"],
["31", "21", "12", "21", "41", "51", "621"],
["321", "221", "121", "021",
"421", "521", "621"],
["3241", "2321", "13216",
"0621", "4421", "5421", "a621"],
["a321", "s221", "d121", "g021", "b421", "5vvv21", "6zxzxs21"]], 'S')
class GI2NAOpenTestCase(GI2NATestCase):
close = 0
class GI2NACloseTestCase(GI2NATestCase):
close = 1
class SetItemTestCase(common.TempFileMixin, TestCase):
def test00_single(self):
"""Single element update (character types)"""
# Create the array under root and name 'somearray'
a = self.charList
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen('a')
arr = self.h5file.root.somearray
# Modify a single element of a and arr:
a[0] = b"b"
arr[0] = b"b"
# Get and compare an element
if common.verbose:
print("Original first element:", a[0])
print("Read first element:", arr[0])
self.assertTrue(allequal(a[0], arr[0]))
def test01_single(self):
"""Single element update (numerical types)"""
# Create the array under root and name 'somearray'
a = self.numericalList
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen('a')
arr = self.h5file.root.somearray
# Modify elements of a and arr:
a[0] = 333
arr[0] = 333
# Get and compare an element
if common.verbose:
print("Original first element:", a[0])
print("Read first element:", arr[0])
self.assertEqual(a[0], arr[0])
def test02_range(self):
"""Range element update (character types)"""
# Create the array under root and name 'somearray'
a = self.charListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen('a')
arr = self.h5file.root.somearray
# Modify elements of a and arr:
a[1:3] = b"xXx"
arr[1:3] = b"xXx"
# Get and compare an element
if common.verbose:
print("Original elements:", a[1:4])
print("Read elements:", arr[1:4])
self.assertTrue(allequal(a[1:4], arr[1:4]))
def test03_range(self):
"""Range element update (numerical types)"""
# Create the array under root and name 'somearray'
a = self.numericalListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen('a')
arr = self.h5file.root.somearray
# Modify elements of a and arr:
s = slice(1, 3, None)
rng = numpy.arange(a[s].size)*2 + 3
rng.shape = a[s].shape
a[s] = rng
arr[s] = rng
# Get and compare an element
if common.verbose:
print("Original elements:", a[1:4])
print("Read elements:", arr[1:4])
self.assertTrue(allequal(a[1:4], arr[1:4]))
def test04_range(self):
"""Range element update, strided (character types)"""
# Create the array under root and name 'somearray'
a = self.charListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen('a')
arr = self.h5file.root.somearray
# Modify elements of a and arr:
s = slice(1, 4, 2)
a[s] = b"xXx"
arr[s] = b"xXx"
# Get and compare an element
if common.verbose:
print("Original elements:", a[1:4:2])
print("Read elements:", arr[1:4:2])
self.assertTrue(allequal(a[1:4:2], arr[1:4:2]))
def test05_range(self):
"""Range element update, strided (numerical types)"""
# Create the array under root and name 'somearray'
a = self.numericalListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen('a')
arr = self.h5file.root.somearray
# Modify elements of a and arr:
s = slice(1, 4, 2)
rng = numpy.arange(a[s].size)*2 + 3
rng.shape = a[s].shape
a[s] = rng
arr[s] = rng
# Get and compare an element
if common.verbose:
print("Original elements:", a[1:4:2])
print("Read elements:", arr[1:4:2])
self.assertTrue(allequal(a[1:4:2], arr[1:4:2]))
def test06_negativeIndex(self):
"""Negative Index element update (character types)"""
# Create the array under root and name 'somearray'
a = self.charListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen('a')
arr = self.h5file.root.somearray
# Modify elements of a and arr:
s = -1
a[s] = b"xXx"
arr[s] = b"xXx"
# Get and compare an element
if common.verbose:
print("Original last element:", a[-1])
print("Read last element:", arr[-1])
self.assertTrue(allequal(a[-1], arr[-1]))
def test07_negativeIndex(self):
"""Negative Index element update (numerical types)"""
# Create the array under root and name 'somearray'
a = self.numericalListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen('a')
arr = self.h5file.root.somearray
# Modify elements of a and arr:
s = -2
a[s] = a[s]*2 + 3
arr[s] = arr[s]*2 + 3
# Get and compare an element
if common.verbose:
print("Original before last element:", a[-2])
print("Read before last element:", arr[-2])
if isinstance(a[-2], numpy.ndarray):
self.assertTrue(allequal(a[-2], arr[-2]))
else:
self.assertEqual(a[-2], arr[-2])
def test08_negativeRange(self):
"""Negative range element update (character types)"""
# Create the array under root and name 'somearray'
a = self.charListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen('a')
arr = self.h5file.root.somearray
# Modify elements of a and arr:
s = slice(-4, -1, None)
a[s] = b"xXx"
arr[s] = b"xXx"
# Get and compare an element
if common.verbose:
print("Original last elements:", a[-4:-1])
print("Read last elements:", arr[-4:-1])
self.assertTrue(allequal(a[-4:-1], arr[-4:-1]))
def test09_negativeRange(self):
"""Negative range element update (numerical types)"""
# Create the array under root and name 'somearray'
a = self.numericalListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen('a')
arr = self.h5file.root.somearray
# Modify elements of a and arr:
s = slice(-3, -1, None)
rng = numpy.arange(a[s].size)*2 + 3
rng.shape = a[s].shape
a[s] = rng
arr[s] = rng
# Get and compare an element
if common.verbose:
print("Original last elements:", a[-4:-1])
print("Read last elements:", arr[-4:-1])
self.assertTrue(allequal(a[-4:-1], arr[-4:-1]))
def test10_outOfRange(self):
"""Out of range update (numerical types)"""
# Create the array under root and name 'somearray'
a = self.numericalListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen('a')
arr = self.h5file.root.somearray
# Modify elements of arr that are out of range:
s = slice(1, a.shape[0]+1, None)
s2 = slice(1, 1000, None)
rng = numpy.arange(a[s].size)*2 + 3
rng.shape = a[s].shape
a[s] = rng
rng2 = numpy.arange(a[s2].size)*2 + 3
rng2.shape = a[s2].shape
arr[s2] = rng2
# Get and compare an element
if common.verbose:
print("Original last elements:", a[-4:-1])
print("Read last elements:", arr[-4:-1])
self.assertTrue(allequal(a[-4:-1], arr[-4:-1]))
class SI1NATestCase(SetItemTestCase, TestCase):
title = "Rank-1 case 1"
numericalList = numpy.array([3])
numericalListME = numpy.array([3, 2, 1, 0, 4, 5, 6])
charList = numpy.array(["3"], 'S')
charListME = numpy.array(
["321", "221", "121", "021", "421", "521", "621"], 'S')
class SI1NAOpenTestCase(SI1NATestCase):
close = 0
class SI1NACloseTestCase(SI1NATestCase):
close = 1
class SI2NATestCase(SetItemTestCase):
# A more complex example
title = "Rank-1,2 case 2"
numericalList = numpy.array([3, 4])
numericalListME = numpy.array([[3, 2, 1, 0, 4, 5, 6],
[2, 1, 0, 4, 5, 6, 7],
[4, 3, 2, 1, 0, 4, 5],
[3, 2, 1, 0, 4, 5, 6],
[3, 2, 1, 0, 4, 5, 6]])
charList = numpy.array(["a", "b"], 'S')
charListME = numpy.array(
[["321", "221", "121", "021", "421", "521", "621"],
["21", "21", "11", "02", "42", "21", "61"],
["31", "21", "12", "21", "41", "51", "621"],
["321", "221", "121", "021",
"421", "521", "621"],
["3241", "2321", "13216",
"0621", "4421", "5421", "a621"],
["a321", "s221", "d121", "g021", "b421", "5vvv21", "6zxzxs21"]], 'S')
class SI2NAOpenTestCase(SI2NATestCase):
close = 0
class SI2NACloseTestCase(SI2NATestCase):
close = 1
class GeneratorTestCase(common.TempFileMixin, TestCase):
def test00a_single(self):
"""Testing generator access to Arrays, single elements (char)"""
# Create the array under root and name 'somearray'
a = self.charList
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
ga = [i for i in a]
garr = [i for i in arr]
if common.verbose:
print("Result of original iterator:", ga)
print("Result of read generator:", garr)
self.assertEqual(ga, garr)
def test00b_me(self):
"""Testing generator access to Arrays, multiple elements (char)"""
# Create the array under root and name 'somearray'
a = self.charListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
ga = [i for i in a]
garr = [i for i in arr]
if common.verbose:
print("Result of original iterator:", ga)
print("Result of read generator:", garr)
for i in range(len(ga)):
self.assertTrue(allequal(ga[i], garr[i]))
def test01a_single(self):
"""Testing generator access to Arrays, single elements (numeric)"""
# Create the array under root and name 'somearray'
a = self.numericalList
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
ga = [i for i in a]
garr = [i for i in arr]
if common.verbose:
print("Result of original iterator:", ga)
print("Result of read generator:", garr)
self.assertEqual(ga, garr)
def test01b_me(self):
"""Testing generator access to Arrays, multiple elements (numeric)"""
# Create the array under root and name 'somearray'
a = self.numericalListME
arr = self.h5file.create_array(
self.h5file.root, 'somearray', a, "Some array")
if self.close:
self._reopen()
arr = self.h5file.root.somearray
# Get and compare an element
ga = [i for i in a]
garr = [i for i in arr]
if common.verbose:
print("Result of original iterator:", ga)
print("Result of read generator:", garr)
for i in range(len(ga)):
self.assertTrue(allequal(ga[i], garr[i]))
class GE1NATestCase(GeneratorTestCase):
title = "Rank-1 case 1"
numericalList = numpy.array([3])
numericalListME = numpy.array([3, 2, 1, 0, 4, 5, 6])
charList = numpy.array(["3"], 'S')
charListME = numpy.array(
["321", "221", "121", "021", "421", "521", "621"], 'S')
class GE1NAOpenTestCase(GE1NATestCase):
close = 0
class GE1NACloseTestCase(GE1NATestCase):
close = 1
class GE2NATestCase(GeneratorTestCase):
# A more complex example
title = "Rank-1,2 case 2"
numericalList = numpy.array([3, 4])
numericalListME = numpy.array([[3, 2, 1, 0, 4, 5, 6],
[2, 1, 0, 4, 5, 6, 7],
[4, 3, 2, 1, 0, 4, 5],
[3, 2, 1, 0, 4, 5, 6],
[3, 2, 1, 0, 4, 5, 6]])
charList = numpy.array(["a", "b"], 'S')
charListME = numpy.array(
[["321", "221", "121", "021", "421", "521", "621"],
["21", "21", "11", "02", "42", "21", "61"],
["31", "21", "12", "21", "41", "51", "621"],
["321", "221", "121", "021",
"421", "521", "621"],
["3241", "2321", "13216",
"0621", "4421", "5421", "a621"],
["a321", "s221", "d121", "g021", "b421", "5vvv21", "6zxzxs21"]], 'S')
class GE2NAOpenTestCase(GE2NATestCase):
close = 0
class GE2NACloseTestCase(GE2NATestCase):
close = 1
class NonHomogeneousTestCase(common.TempFileMixin, TestCase):
def test(self):
"""Test for creation of non-homogeneous arrays."""
# This checks ticket #12.
self.assertRaises(ValueError,
self.h5file.create_array, '/', 'test', [1, [2, 3]])
self.assertRaises(NoSuchNodeError, self.h5file.remove_node, '/test')
class TruncateTestCase(common.TempFileMixin, TestCase):
def test(self):
"""Test for unability to truncate Array objects."""
array1 = self.h5file.create_array('/', 'array1', [0, 2])
self.assertRaises(TypeError, array1.truncate, 0)
class PointSelectionTestCase(common.TempFileMixin, TestCase):
def setUp(self):
super(PointSelectionTestCase, self).setUp()
# Limits for selections
self.limits = [
(0, 1), # just one element
(20, -10), # no elements
(-10, 4), # several elements
(0, 10), # several elements (again)
]
# Create a sample array
size = numpy.prod(self.shape)
nparr = numpy.arange(size, dtype=numpy.int32).reshape(self.shape)
self.nparr = nparr
self.tbarr = self.h5file.create_array(self.h5file.root, 'array', nparr)
def test01a_read(self):
"""Test for point-selections (read, boolean keys)."""
nparr = self.nparr
tbarr = self.tbarr
for value1, value2 in self.limits:
key = (nparr >= value1) & (nparr < value2)
if common.verbose:
print("Selection to test:", key)
a = nparr[key]
b = tbarr[key]
self.assertTrue(
numpy.alltrue(a == b),
"NumPy array and PyTables selections does not match.")
def test01b_read(self):
"""Test for point-selections (read, integer keys)."""
nparr = self.nparr
tbarr = self.tbarr
for value1, value2 in self.limits:
key = numpy.where((nparr >= value1) & (nparr < value2))
if common.verbose:
print("Selection to test:", key)
a = nparr[key]
b = tbarr[key]
self.assertTrue(
numpy.alltrue(a == b),
"NumPy array and PyTables selections does not match.")
def test01c_read(self):
"""Test for point-selections (read, float keys)."""
nparr = self.nparr
tbarr = self.tbarr
for value1, value2 in self.limits:
key = numpy.where((nparr >= value1) & (nparr < value2))
if common.verbose:
print("Selection to test:", key)
# a = nparr[key]
fkey = numpy.array(key, "f4")
self.assertRaises((IndexError, TypeError), tbarr.__getitem__, fkey)
def test01d_read(self):
nparr = self.nparr
tbarr = self.tbarr
for key in self.working_keyset:
if common.verbose:
print("Selection to test:", key)
a = nparr[key]
b = tbarr[key]
npt.assert_array_equal(
a, b, "NumPy array and PyTables selections does not match.")
def test01e_read(self):
tbarr = self.tbarr
for key in self.not_working_keyset:
if common.verbose:
print("Selection to test:", key)
self.assertRaises(IndexError, tbarr.__getitem__, key)
def test02a_write(self):
"""Test for point-selections (write, boolean keys)."""
nparr = self.nparr
tbarr = self.tbarr
for value1, value2 in self.limits:
key = (nparr >= value1) & (nparr < value2)
if common.verbose:
print("Selection to test:", key)
s = nparr[key]
nparr[key] = s * 2
tbarr[key] = s * 2
a = nparr[:]
b = tbarr[:]
self.assertTrue(
numpy.alltrue(a == b),
"NumPy array and PyTables modifications does not match.")
def test02b_write(self):
"""Test for point-selections (write, integer keys)."""
nparr = self.nparr
tbarr = self.tbarr
for value1, value2 in self.limits:
key = numpy.where((nparr >= value1) & (nparr < value2))
if common.verbose:
print("Selection to test:", key)
s = nparr[key]
nparr[key] = s * 2
tbarr[key] = s * 2
a = nparr[:]
b = tbarr[:]
self.assertTrue(
numpy.alltrue(a == b),
"NumPy array and PyTables modifications does not match.")
def test02c_write(self):
"""Test for point-selections (write, integer values, broadcast)."""
nparr = self.nparr
tbarr = self.tbarr
for value1, value2 in self.limits:
key = numpy.where((nparr >= value1) & (nparr < value2))
if common.verbose:
print("Selection to test:", key)
# s = nparr[key]
nparr[key] = 2 # force a broadcast
tbarr[key] = 2 # force a broadcast
a = nparr[:]
b = tbarr[:]
self.assertTrue(
numpy.alltrue(a == b),
"NumPy array and PyTables modifications does not match.")
class PointSelection0(PointSelectionTestCase):
shape = (3,)
working_keyset = [
[0, 1],
[0, -1],
]
not_working_keyset = [
[0, 3],
[0, 4],
[0, -4],
]
class PointSelection1(PointSelectionTestCase):
shape = (5, 3, 3)
working_keyset = [
[(0, 0), (0, 1), (0, 0)],
[(0, 0), (0, -1), (0, 0)],
]
not_working_keyset = [
[(0, 0), (0, 3), (0, 0)],
[(0, 0), (0, 4), (0, 0)],
[(0, 0), (0, -4), (0, 0)],
[(0, 0), (0, -5), (0, 0)]
]
class PointSelection2(PointSelectionTestCase):
shape = (7, 3)
working_keyset = [
[(0, 0), (0, 1)],
[(0, 0), (0, -1)],
[(0, 0), (0, -2)],
]
not_working_keyset = [
[(0, 0), (0, 3)],
[(0, 0), (0, 4)],
[(0, 0), (0, -4)],
[(0, 0), (0, -5)],
]
class PointSelection3(PointSelectionTestCase):
shape = (4, 3, 2, 1)
working_keyset = [
[(0, 0), (0, 1), (0, 0), (0, 0)],
[(0, 0), (0, -1), (0, 0), (0, 0)],
]
not_working_keyset = [
[(0, 0), (0, 3), (0, 0), (0, 0)],
[(0, 0), (0, 4), (0, 0), (0, 0)],
[(0, 0), (0, -4), (0, 0), (0, 0)],
]
class PointSelection4(PointSelectionTestCase):
shape = (1, 3, 2, 5, 6)
working_keyset = [
[(0, 0), (0, 1), (0, 0), (0, 0), (0, 0)],
[(0, 0), (0, -1), (0, 0), (0, 0), (0, 0)],
]
not_working_keyset = [
[(0, 0), (0, 3), (0, 0), (0, 0), (0, 0)],
[(0, 0), (0, 4), (0, 0), (0, 0), (0, 0)],
[(0, 0), (0, -4), (0, 0), (0, 0), (0, 0)],
]
class FancySelectionTestCase(common.TempFileMixin, TestCase):
def setUp(self):
super(FancySelectionTestCase, self).setUp()
M, N, O = self.shape
# The next are valid selections for both NumPy and PyTables
self.working_keyset = [
([1, 3], slice(1, N-1), 2),
([M-1, 1, 3, 2], slice(None), 2), # unordered lists supported
(slice(M), [N-1, 1, 0], slice(None)),
(slice(1, M, 3), slice(1, N), [O-1, 1, 0]),
(M-1, [2, 1], 1),
(1, 2, 1), # regular selection
([1, 2], -2, -1), # negative indices
([1, -2], 2, -1), # more negative indices
([1, -2], 2, Ellipsis), # one ellipsis
(Ellipsis, [1, 2]), # one ellipsis
(numpy.array(
[1, -2], 'i4'), 2, -1), # array 32-bit instead of list
(numpy.array(
[-1, 2], 'i8'), 2, -1), # array 64-bit instead of list
]
# Using booleans instead of ints is deprecated since numpy 1.8
# Tests for keys that have to support the __index__ attribute
#if (sys.version_info[0] >= 2 and sys.version_info[1] >= 5):
# self.working_keyset.append(
# (False, True), # equivalent to (0,1) ;-)
# )
# Valid selections for NumPy, but not for PyTables (yet)
# The next should raise an IndexError
self.not_working_keyset = [
numpy.array([False, True], dtype="b1"), # boolean arrays
([1, 2, 1], 2, 1), # repeated values
([1, 2], 2, [1, 2]), # several lists
([], 2, 1), # empty selections
(Ellipsis, [1, 2], Ellipsis), # several ellipsis
# Using booleans instead of ints is deprecated since numpy 1.8
([False, True]), # boolean values with incompatible shape
]
# The next should raise an IndexError in both NumPy and PyTables
self.not_working_oob = [
([1, 2], 2, 1000), # out-of-bounds selections
([1, 2], 2000, 1), # out-of-bounds selections
]
# The next should raise a IndexError in both NumPy and PyTables
self.not_working_too_many = [
([1, 2], 2, 1, 1),
]
# Create a sample array
nparr = numpy.empty(self.shape, dtype=numpy.int32)
data = numpy.arange(N * O, dtype=numpy.int32).reshape(N, O)
for i in range(M):
nparr[i] = data * i
self.nparr = nparr
self.tbarr = self.h5file.create_array(self.h5file.root, 'array', nparr)
def test01a_read(self):
"""Test for fancy-selections (working selections, read)."""
nparr = self.nparr
tbarr = self.tbarr
for key in self.working_keyset:
if common.verbose:
print("Selection to test:", key)
a = nparr[key]
b = tbarr[key]
self.assertTrue(
numpy.alltrue(a == b),
"NumPy array and PyTables selections does not match.")
def test01b_read(self):
"""Test for fancy-selections (not working selections, read)."""
# nparr = self.nparr
tbarr = self.tbarr
for key in self.not_working_keyset:
if common.verbose:
print("Selection to test:", key)
# a = nparr[key]
self.assertRaises(IndexError, tbarr.__getitem__, key)
def test01c_read(self):
"""Test for fancy-selections (out-of-bound indexes, read)."""
nparr = self.nparr
tbarr = self.tbarr
for key in self.not_working_oob:
if common.verbose:
print("Selection to test:", key)
self.assertRaises(IndexError, nparr.__getitem__, key)
self.assertRaises(IndexError, tbarr.__getitem__, key)
def test01d_read(self):
"""Test for fancy-selections (too many indexes, read)."""
nparr = self.nparr
tbarr = self.tbarr
for key in self.not_working_too_many:
if common.verbose:
print("Selection to test:", key)
# ValueError for numpy 1.6.x and earlier
# IndexError in numpy > 1.8.0
self.assertRaises((ValueError, IndexError), nparr.__getitem__, key)
self.assertRaises(IndexError, tbarr.__getitem__, key)
def test02a_write(self):
"""Test for fancy-selections (working selections, write)."""
nparr = self.nparr
tbarr = self.tbarr
for key in self.working_keyset:
if common.verbose:
print("Selection to test:", key)
s = nparr[key]
nparr[key] = s * 2
tbarr[key] = s * 2
a = nparr[:]
b = tbarr[:]
self.assertTrue(
numpy.alltrue(a == b),
"NumPy array and PyTables modifications does not match.")
def test02b_write(self):
"""Test for fancy-selections (working selections, write, broadcast)."""
nparr = self.nparr
tbarr = self.tbarr
for key in self.working_keyset:
if common.verbose:
print("Selection to test:", key)
# s = nparr[key]
nparr[key] = 2 # broadcast value
tbarr[key] = 2 # broadcast value
a = nparr[:]
b = tbarr[:]
# if common.verbose:
# print("NumPy modified array:", a)
# print("PyTables modifyied array:", b)
self.assertTrue(
numpy.alltrue(a == b),
"NumPy array and PyTables modifications does not match.")
class FancySelection1(FancySelectionTestCase):
shape = (5, 3, 3) # Minimum values
class FancySelection2(FancySelectionTestCase):
# shape = (5, 3, 3) # Minimum values
shape = (7, 3, 3)
class FancySelection3(FancySelectionTestCase):
# shape = (5, 3, 3) # Minimum values
shape = (7, 4, 5)
class FancySelection4(FancySelectionTestCase):
# shape = (5, 3, 3) # Minimum values
shape = (5, 3, 10)
class CopyNativeHDF5MDAtom(TestCase):
def setUp(self):
super(CopyNativeHDF5MDAtom, self).setUp()
filename = test_filename("array_mdatom.h5")
self.h5file = tables.open_file(filename, "r")
self.arr = self.h5file.root.arr
self.copy = tempfile.mktemp(".h5")
self.copyh = tables.open_file(self.copy, mode="w")
self.arr2 = self.arr.copy(self.copyh.root, newname="arr2")
def tearDown(self):
self.h5file.close()
self.copyh.close()
os.remove(self.copy)
super(CopyNativeHDF5MDAtom, self).tearDown()
def test01_copy(self):
"""Checking that native MD atoms are copied as-is"""
self.assertEqual(self.arr.atom, self.arr2.atom)
self.assertEqual(self.arr.shape, self.arr2.shape)
def test02_reopen(self):
"""Checking that native MD atoms are copied as-is (re-open)"""
self.copyh.close()
self.copyh = tables.open_file(self.copy, mode="r")
self.arr2 = self.copyh.root.arr2
self.assertEqual(self.arr.atom, self.arr2.atom)
self.assertEqual(self.arr.shape, self.arr2.shape)
class AccessClosedTestCase(common.TempFileMixin, TestCase):
def setUp(self):
super(AccessClosedTestCase, self).setUp()
a = numpy.zeros((10, 10))
self.array = self.h5file.create_array(self.h5file.root, 'array', a)
def test_read(self):
self.h5file.close()
self.assertRaises(ClosedNodeError, self.array.read)
def test_getitem(self):
self.h5file.close()
self.assertRaises(ClosedNodeError, self.array.__getitem__, 0)
def test_setitem(self):
self.h5file.close()
self.assertRaises(ClosedNodeError, self.array.__setitem__, 0, 0)
class BroadcastTest(common.TempFileMixin, TestCase):
def test(self):
"""Test correct broadcasting when the array atom is not scalar."""
array_shape = (2, 3)
element_shape = (3,)
dtype = numpy.dtype((numpy.int, element_shape))
atom = Atom.from_dtype(dtype)
h5arr = self.h5file.create_carray(self.h5file.root, 'array',
atom, array_shape)
size = numpy.prod(element_shape)
nparr = numpy.arange(size).reshape(element_shape)
h5arr[0] = nparr
self.assertTrue(numpy.all(h5arr[0] == nparr))
class TestCreateArrayArgs(common.TempFileMixin, TestCase):
where = '/'
name = 'array'
obj = numpy.array([[1, 2], [3, 4]])
title = 'title'
byteorder = None
createparents = False
atom = Atom.from_dtype(obj.dtype)
shape = obj.shape
def test_positional_args(self):
self.h5file.create_array(self.where, self.name, self.obj, self.title)
self.h5file.close()
self.h5file = tables.open_file(self.h5fname)
ptarr = self.h5file.get_node(self.where, self.name)
nparr = ptarr.read()
self.assertEqual(ptarr.title, self.title)
self.assertEqual(ptarr.shape, self.shape)
self.assertEqual(ptarr.atom, self.atom)
self.assertEqual(ptarr.atom.dtype, self.atom.dtype)
self.assertTrue(allequal(self.obj, nparr))
def test_positional_args_atom_shape(self):
self.h5file.create_array(self.where, self.name, None, self.title,
self.byteorder, self.createparents,
self.atom, self.shape)
self.h5file.close()
self.h5file = tables.open_file(self.h5fname)
ptarr = self.h5file.get_node(self.where, self.name)
nparr = ptarr.read()
self.assertEqual(ptarr.title, self.title)
self.assertEqual(ptarr.shape, self.shape)
self.assertEqual(ptarr.atom, self.atom)
self.assertEqual(ptarr.atom.dtype, self.atom.dtype)
self.assertTrue(allequal(numpy.zeros_like(self.obj), nparr))
def test_kwargs_obj(self):
self.h5file.create_array(self.where, self.name, title=self.title,
obj=self.obj)
self.h5file.close()
self.h5file = tables.open_file(self.h5fname)
ptarr = self.h5file.get_node(self.where, self.name)
nparr = ptarr.read()
self.assertEqual(ptarr.title, self.title)
self.assertEqual(ptarr.shape, self.shape)
self.assertEqual(ptarr.atom, self.atom)
self.assertEqual(ptarr.atom.dtype, self.atom.dtype)
self.assertTrue(allequal(self.obj, nparr))
def test_kwargs_atom_shape_01(self):
ptarr = self.h5file.create_array(self.where, self.name,
title=self.title,
atom=self.atom, shape=self.shape)
ptarr[...] = self.obj
self.h5file.close()
self.h5file = tables.open_file(self.h5fname)
ptarr = self.h5file.get_node(self.where, self.name)
nparr = ptarr.read()
self.assertEqual(ptarr.title, self.title)
self.assertEqual(ptarr.shape, self.shape)
self.assertEqual(ptarr.atom, self.atom)
self.assertEqual(ptarr.atom.dtype, self.atom.dtype)
self.assertTrue(allequal(self.obj, nparr))
def test_kwargs_atom_shape_02(self):
ptarr = self.h5file.create_array(self.where, self.name,
title=self.title,
atom=self.atom, shape=self.shape)
#ptarr[...] = self.obj
self.h5file.close()
self.h5file = tables.open_file(self.h5fname)
ptarr = self.h5file.get_node(self.where, self.name)
nparr = ptarr.read()
self.assertEqual(ptarr.title, self.title)
self.assertEqual(ptarr.shape, self.shape)
self.assertEqual(ptarr.atom, self.atom)
self.assertEqual(ptarr.atom.dtype, self.atom.dtype)
self.assertTrue(allequal(numpy.zeros_like(self.obj), nparr))
def test_kwargs_obj_atom(self):
ptarr = self.h5file.create_array(self.where, self.name,
title=self.title,
obj=self.obj,
atom=self.atom)
self.h5file.close()
self.h5file = tables.open_file(self.h5fname)
ptarr = self.h5file.get_node(self.where, self.name)
nparr = ptarr.read()
self.assertEqual(ptarr.title, self.title)
self.assertEqual(ptarr.shape, self.shape)
self.assertEqual(ptarr.atom, self.atom)
self.assertEqual(ptarr.atom.dtype, self.atom.dtype)
self.assertTrue(allequal(self.obj, nparr))
def test_kwargs_obj_shape(self):
ptarr = self.h5file.create_array(self.where, self.name,
title=self.title,
obj=self.obj,
shape=self.shape)
self.h5file.close()
self.h5file = tables.open_file(self.h5fname)
ptarr = self.h5file.get_node(self.where, self.name)
nparr = ptarr.read()
self.assertEqual(ptarr.title, self.title)
self.assertEqual(ptarr.shape, self.shape)
self.assertEqual(ptarr.atom, self.atom)
self.assertEqual(ptarr.atom.dtype, self.atom.dtype)
self.assertTrue(allequal(self.obj, nparr))
def test_kwargs_obj_atom_shape(self):
ptarr = self.h5file.create_array(self.where, self.name,
title=self.title,
obj=self.obj,
atom=self.atom,
shape=self.shape)
self.h5file.close()
self.h5file = tables.open_file(self.h5fname)
ptarr = self.h5file.get_node(self.where, self.name)
nparr = ptarr.read()
self.assertEqual(ptarr.title, self.title)
self.assertEqual(ptarr.shape, self.shape)
self.assertEqual(ptarr.atom, self.atom)
self.assertEqual(ptarr.atom.dtype, self.atom.dtype)
self.assertTrue(allequal(self.obj, nparr))
def test_kwargs_obj_atom_error(self):
atom = Atom.from_dtype(numpy.dtype('complex'))
#shape = self.shape + self.shape
self.assertRaises(TypeError,
self.h5file.create_array,
self.where,
self.name,
title=self.title,
obj=self.obj,
atom=atom)
def test_kwargs_obj_shape_error(self):
#atom = Atom.from_dtype(numpy.dtype('complex'))
shape = self.shape + self.shape
self.assertRaises(TypeError,
self.h5file.create_array,
self.where,
self.name,
title=self.title,
obj=self.obj,
shape=shape)
def test_kwargs_obj_atom_shape_error_01(self):
atom = Atom.from_dtype(numpy.dtype('complex'))
#shape = self.shape + self.shape
self.assertRaises(TypeError,
self.h5file.create_array,
self.where,
self.name,
title=self.title,
obj=self.obj,
atom=atom,
shape=self.shape)
def test_kwargs_obj_atom_shape_error_02(self):
#atom = Atom.from_dtype(numpy.dtype('complex'))
shape = self.shape + self.shape
self.assertRaises(TypeError,
self.h5file.create_array,
self.where,
self.name,
title=self.title,
obj=self.obj,
atom=self.atom,
shape=shape)
def test_kwargs_obj_atom_shape_error_03(self):
atom = Atom.from_dtype(numpy.dtype('complex'))
shape = self.shape + self.shape
self.assertRaises(TypeError,
self.h5file.create_array,
self.where,
self.name,
title=self.title,
obj=self.obj,
atom=atom,
shape=shape)
def suite():
theSuite = unittest.TestSuite()
niter = 1
for i in range(niter):
# The scalar case test should be refined in order to work
theSuite.addTest(unittest.makeSuite(Basic0DOneTestCase))
theSuite.addTest(unittest.makeSuite(Basic0DTwoTestCase))
# theSuite.addTest(unittest.makeSuite(Basic1DZeroTestCase))
theSuite.addTest(unittest.makeSuite(Basic1DOneTestCase))
theSuite.addTest(unittest.makeSuite(Basic1DTwoTestCase))
theSuite.addTest(unittest.makeSuite(Basic1DThreeTestCase))
theSuite.addTest(unittest.makeSuite(Basic2DOneTestCase))
theSuite.addTest(unittest.makeSuite(Basic2DTwoTestCase))
theSuite.addTest(unittest.makeSuite(Basic10DTestCase))
# The 32 dimensions case is tested on GroupsArray
# theSuite.addTest(unittest.makeSuite(Basic32DTestCase))
theSuite.addTest(unittest.makeSuite(ReadOutArgumentTests))
theSuite.addTest(unittest.makeSuite(
SizeOnDiskInMemoryPropertyTestCase))
theSuite.addTest(unittest.makeSuite(GroupsArrayTestCase))
theSuite.addTest(unittest.makeSuite(ComplexNotReopenNotEndianTestCase))
theSuite.addTest(unittest.makeSuite(ComplexReopenNotEndianTestCase))
theSuite.addTest(unittest.makeSuite(ComplexNotReopenEndianTestCase))
theSuite.addTest(unittest.makeSuite(ComplexReopenEndianTestCase))
theSuite.addTest(unittest.makeSuite(CloseCopyTestCase))
theSuite.addTest(unittest.makeSuite(OpenCopyTestCase))
theSuite.addTest(unittest.makeSuite(CopyIndex1TestCase))
theSuite.addTest(unittest.makeSuite(CopyIndex2TestCase))
theSuite.addTest(unittest.makeSuite(CopyIndex3TestCase))
theSuite.addTest(unittest.makeSuite(CopyIndex4TestCase))
theSuite.addTest(unittest.makeSuite(CopyIndex5TestCase))
theSuite.addTest(unittest.makeSuite(CopyIndex6TestCase))
theSuite.addTest(unittest.makeSuite(CopyIndex7TestCase))
theSuite.addTest(unittest.makeSuite(CopyIndex8TestCase))
theSuite.addTest(unittest.makeSuite(CopyIndex9TestCase))
theSuite.addTest(unittest.makeSuite(CopyIndex10TestCase))
theSuite.addTest(unittest.makeSuite(CopyIndex11TestCase))
theSuite.addTest(unittest.makeSuite(CopyIndex12TestCase))
theSuite.addTest(unittest.makeSuite(GI1NAOpenTestCase))
theSuite.addTest(unittest.makeSuite(GI1NACloseTestCase))
theSuite.addTest(unittest.makeSuite(GI2NAOpenTestCase))
theSuite.addTest(unittest.makeSuite(GI2NACloseTestCase))
theSuite.addTest(unittest.makeSuite(SI1NAOpenTestCase))
theSuite.addTest(unittest.makeSuite(SI1NACloseTestCase))
theSuite.addTest(unittest.makeSuite(SI2NAOpenTestCase))
theSuite.addTest(unittest.makeSuite(SI2NACloseTestCase))
theSuite.addTest(unittest.makeSuite(GE1NAOpenTestCase))
theSuite.addTest(unittest.makeSuite(GE1NACloseTestCase))
theSuite.addTest(unittest.makeSuite(GE2NAOpenTestCase))
theSuite.addTest(unittest.makeSuite(GE2NACloseTestCase))
theSuite.addTest(unittest.makeSuite(NonHomogeneousTestCase))
theSuite.addTest(unittest.makeSuite(TruncateTestCase))
theSuite.addTest(unittest.makeSuite(FancySelection1))
theSuite.addTest(unittest.makeSuite(FancySelection2))
theSuite.addTest(unittest.makeSuite(FancySelection3))
theSuite.addTest(unittest.makeSuite(FancySelection4))
theSuite.addTest(unittest.makeSuite(PointSelection0))
theSuite.addTest(unittest.makeSuite(PointSelection1))
theSuite.addTest(unittest.makeSuite(PointSelection2))
theSuite.addTest(unittest.makeSuite(PointSelection3))
theSuite.addTest(unittest.makeSuite(PointSelection4))
theSuite.addTest(unittest.makeSuite(CopyNativeHDF5MDAtom))
theSuite.addTest(unittest.makeSuite(AccessClosedTestCase))
theSuite.addTest(unittest.makeSuite(TestCreateArrayArgs))
theSuite.addTest(unittest.makeSuite(BroadcastTest))
return theSuite
if __name__ == '__main__':
common.parse_argv(sys.argv)
common.print_versions()
unittest.main(defaultTest='suite')<|fim▁end|> | if nparr.dtype.byteorder in ('>', '<'): |
<|file_name|>0003_auto_20160317_1521.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-17 19:21
from __future__ import unicode_literals
from django.db import migrations
<|fim▁hole|> ('tilecache', '0002_auto_20160317_1519'),
]
operations = [
migrations.AlterModelOptions(
name='channel',
options={'managed': True},
),
migrations.AlterModelTable(
name='channel',
table='channels',
),
]<|fim▁end|> |
class Migration(migrations.Migration):
dependencies = [ |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>pub use self::error404::*;
pub use self::render::*;
pub use self::validator::*;
pub use self::db::*;
mod error404;
mod render;
mod validator;
mod db;
<|fim▁hole|><|fim▁end|> | mod validator_test; |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin
from Weather.models import *
from Weather.util import updateForecast
def update_forecast(modeladmin, request, queryset):
for forecast in queryset:
updateForecast(forecast)
<|fim▁hole|> actions = [update_forecast]
class WMSRadarOverlayAdmin(admin.ModelAdmin):
pass
admin.site.register(Forecast, forecastAdmin)
admin.site.register(WMSRadarOverlay, WMSRadarOverlayAdmin)<|fim▁end|> | update_forecast.short_description = "Force forecast update from NWS"
class forecastAdmin(admin.ModelAdmin): |
<|file_name|>inherited_text.mako.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Keyword %>
<% data.new_style_struct("InheritedText", inherited=True, gecko_name="Text") %>
<%helpers:longhand name="line-height" animatable="True"
spec="https://drafts.csswg.org/css2/visudet.html#propdef-line-height">
use std::fmt;
use style_traits::ToCss;
use values::{CSSFloat, HasViewportPercentage};
impl HasViewportPercentage for SpecifiedValue {
fn has_viewport_percentage(&self) -> bool {
match *self {
SpecifiedValue::LengthOrPercentage(ref length) => length.has_viewport_percentage(),
_ => false
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum SpecifiedValue {
Normal,
% if product == "gecko":
MozBlockHeight,
% endif
Number(CSSFloat),
LengthOrPercentage(specified::LengthOrPercentage),
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
SpecifiedValue::Normal => dest.write_str("normal"),
% if product == "gecko":
SpecifiedValue::MozBlockHeight => dest.write_str("-moz-block-height"),
% endif
SpecifiedValue::LengthOrPercentage(ref value) => value.to_css(dest),
SpecifiedValue::Number(number) => write!(dest, "{}", number),
}
}
}
/// normal | <number> | <length> | <percentage>
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
use cssparser::Token;
use std::ascii::AsciiExt;
// We try to parse as a Number first because, for 'line-height', we want "0" to be
// parsed as a plain Number rather than a Length (0px); this matches the behaviour
// of all major browsers
input.try(specified::Number::parse_non_negative)
.map(|n| SpecifiedValue::Number(n.0))
.or_else(|()| {
input.try(specified::LengthOrPercentage::parse_non_negative)
.map(SpecifiedValue::LengthOrPercentage)
.or_else(|()| {
match try!(input.next()) {
Token::Ident(ref value) if value.eq_ignore_ascii_case("normal") => {
Ok(SpecifiedValue::Normal)
}
% if product == "gecko":
Token::Ident(ref value) if value.eq_ignore_ascii_case("-moz-block-height") => {
Ok(SpecifiedValue::MozBlockHeight)
}
% endif
_ => Err(()),
}
})
})
}
pub mod computed_value {
use app_units::Au;
use std::fmt;
use values::CSSFloat;
#[derive(PartialEq, Copy, Clone, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum T {
Normal,
% if product == "gecko":
MozBlockHeight,
% endif
Length(Au),
Number(CSSFloat),
}
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
computed_value::T::Normal => dest.write_str("normal"),
% if product == "gecko":
computed_value::T::MozBlockHeight => dest.write_str("-moz-block-height"),
% endif
computed_value::T::Length(length) => length.to_css(dest),
computed_value::T::Number(number) => write!(dest, "{}", number),
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T { computed_value::T::Normal }
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue::Normal
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, context: &Context) -> computed_value::T {
match *self {
SpecifiedValue::Normal => computed_value::T::Normal,
% if product == "gecko":
SpecifiedValue::MozBlockHeight => computed_value::T::MozBlockHeight,
% endif
SpecifiedValue::Number(value) => computed_value::T::Number(value),
SpecifiedValue::LengthOrPercentage(ref value) => {
match *value {
specified::LengthOrPercentage::Length(ref value) =>
computed_value::T::Length(value.to_computed_value(context)),
specified::LengthOrPercentage::Percentage(specified::Percentage(value)) => {
let fr = specified::Length::NoCalc(specified::NoCalcLength::FontRelative(
specified::FontRelativeLength::Em(value)));
computed_value::T::Length(fr.to_computed_value(context))
},
specified::LengthOrPercentage::Calc(ref calc) => {
let calc = calc.to_computed_value(context);
let fr = specified::FontRelativeLength::Em(calc.percentage());
let fr = specified::Length::NoCalc(specified::NoCalcLength::FontRelative(fr));
computed_value::T::Length(calc.length() + fr.to_computed_value(context))
}
}
}
}
}
#[inline]
fn from_computed_value(computed: &computed_value::T) -> Self {
match *computed {
computed_value::T::Normal => SpecifiedValue::Normal,
% if product == "gecko":
computed_value::T::MozBlockHeight => SpecifiedValue::MozBlockHeight,
% endif
computed_value::T::Number(value) => SpecifiedValue::Number(value),
computed_value::T::Length(au) => {
SpecifiedValue::LengthOrPercentage(specified::LengthOrPercentage::Length(
ToComputedValue::from_computed_value(&au)
))
}
}
}
}
</%helpers:longhand>
// CSS Text Module Level 3
// TODO(pcwalton): `full-width`
${helpers.single_keyword("text-transform",
"none capitalize uppercase lowercase",
extra_gecko_values="full-width",
animatable=False,
spec="https://drafts.csswg.org/css-text/#propdef-text-transform")}
${helpers.single_keyword("hyphens", "manual none auto",
gecko_enum_prefix="StyleHyphens",
products="gecko", animatable=False, extra_prefixes="moz",
spec="https://drafts.csswg.org/css-text/#propdef-hyphens")}
${helpers.predefined_type("text-indent",
"LengthOrPercentage",
"computed::LengthOrPercentage::Length(Au(0))",
animatable=True,
spec="https://drafts.csswg.org/css-text/#propdef-text-indent")}
// Also known as "word-wrap" (which is more popular because of IE), but this is the preferred
// name per CSS-TEXT 6.2.
${helpers.single_keyword("overflow-wrap",
"normal break-word",
gecko_constant_prefix="NS_STYLE_OVERFLOWWRAP",
animatable=False,
spec="https://drafts.csswg.org/css-text/#propdef-overflow-wrap",
alias="word-wrap")}
// TODO(pcwalton): Support `word-break: keep-all` once we have better CJK support.
${helpers.single_keyword("word-break",
"normal break-all keep-all",
gecko_constant_prefix="NS_STYLE_WORDBREAK",
animatable=False,
spec="https://drafts.csswg.org/css-text/#propdef-word-break")}
// TODO(pcwalton): Support `text-justify: distribute`.
<%helpers:single_keyword_computed name="text-justify"
values="auto none inter-word"
extra_gecko_values="inter-character"
extra_specified="${'distribute' if product == 'gecko' else ''}"
gecko_enum_prefix="StyleTextJustify"
animatable="False"
spec="https://drafts.csswg.org/css-text/#propdef-text-justify">
use values::HasViewportPercentage;
no_viewport_percentage!(SpecifiedValue);
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, _: &Context) -> computed_value::T {
match *self {
% for value in "auto none inter_word".split():
SpecifiedValue::${value} => computed_value::T::${value},
% endfor
% if product == "gecko":
SpecifiedValue::inter_character => computed_value::T::inter_character,
// https://drafts.csswg.org/css-text-3/#valdef-text-justify-distribute
SpecifiedValue::distribute => computed_value::T::inter_character,
% endif
}
}
#[inline]
fn from_computed_value(computed: &computed_value::T) -> SpecifiedValue {
match *computed {
% for value in "auto none inter_word".split():
computed_value::T::${value} => SpecifiedValue::${value},
% endfor
% if product == "gecko":
computed_value::T::inter_character => SpecifiedValue::inter_character,
% endif
}
}
}
</%helpers:single_keyword_computed>
${helpers.single_keyword("text-align-last",
"auto start end left right center justify",
products="gecko",
gecko_constant_prefix="NS_STYLE_TEXT_ALIGN",
animatable=False,
spec="https://drafts.csswg.org/css-text/#propdef-text-align-last")}
// TODO make this a shorthand and implement text-align-last/text-align-all
<%helpers:longhand name="text-align" animatable="False" spec="https://drafts.csswg.org/css-text/#propdef-text-align">
pub use self::computed_value::T as SpecifiedValue;
use values::computed::ComputedValueAsSpecified;
use values::HasViewportPercentage;
impl ComputedValueAsSpecified for SpecifiedValue {}
no_viewport_percentage!(SpecifiedValue);
pub mod computed_value {
use style_traits::ToCss;
macro_rules! define_text_align {
( $( $name: ident ( $string: expr ) => $discriminant: expr, )+ ) => {
define_css_keyword_enum! { T:
$(
$string => $name,
)+
}
impl T {
pub fn to_u32(self) -> u32 {
match self {
$(
T::$name => $discriminant,
)+
}
}
pub fn from_u32(discriminant: u32) -> Option<T> {
match discriminant {
$(
$discriminant => Some(T::$name),
)+
_ => None
}
}
}
}
}
define_text_align! {
start("start") => 0,
end("end") => 1,
left("left") => 2,
right("right") => 3,
center("center") => 4,
justify("justify") => 5,
% if product == "servo":
servo_center("-servo-center") => 6,
servo_left("-servo-left") => 7,
servo_right("-servo-right") => 8,
% else:
_moz_center("-moz-center") => 6,
_moz_left("-moz-left") => 7,
_moz_right("-moz-right") => 8,
match_parent("match-parent") => 9,
char("char") => 10,
% endif
}
}
#[inline] pub fn get_initial_value() -> computed_value::T {
computed_value::T::start
}
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
computed_value::T::parse(input)
}
${helpers.gecko_keyword_conversion(Keyword('text-align',
"""left right center justify -moz-left -moz-right
-moz-center char end match-parent""",
gecko_strip_moz_prefix=False))}
</%helpers:longhand>
// FIXME: This prop should be animatable.
<%helpers:longhand name="letter-spacing" animatable="False"
spec="https://drafts.csswg.org/css-text/#propdef-letter-spacing">
use std::fmt;
use style_traits::ToCss;
use values::HasViewportPercentage;
impl HasViewportPercentage for SpecifiedValue {
fn has_viewport_percentage(&self) -> bool {
match *self {
SpecifiedValue::Specified(ref length) => length.has_viewport_percentage(),
_ => false
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum SpecifiedValue {
Normal,
Specified(specified::Length),
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
SpecifiedValue::Normal => dest.write_str("normal"),
SpecifiedValue::Specified(ref l) => l.to_css(dest),
}
}
}
pub mod computed_value {
use app_units::Au;
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct T(pub Option<Au>);
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match self.0 {
None => dest.write_str("normal"),
Some(l) => l.to_css(dest),
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(None)
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, context: &Context) -> computed_value::T {
match *self {
SpecifiedValue::Normal => computed_value::T(None),
SpecifiedValue::Specified(ref l) =>
computed_value::T(Some(l.to_computed_value(context)))
}
}
#[inline]
fn from_computed_value(computed: &computed_value::T) -> Self {
computed.0.map(|ref au| {
SpecifiedValue::Specified(ToComputedValue::from_computed_value(au))
}).unwrap_or(SpecifiedValue::Normal)
}
}
pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
if input.try(|input| input.expect_ident_matching("normal")).is_ok() {
Ok(SpecifiedValue::Normal)
} else {
specified::Length::parse(context, input).map(SpecifiedValue::Specified)
}
}
</%helpers:longhand>
<%helpers:longhand name="word-spacing" animatable="False"
spec="https://drafts.csswg.org/css-text/#propdef-word-spacing">
use std::fmt;
use style_traits::ToCss;
use values::HasViewportPercentage;
impl HasViewportPercentage for SpecifiedValue {
fn has_viewport_percentage(&self) -> bool {
match *self {
SpecifiedValue::Specified(ref length) => length.has_viewport_percentage(),
_ => false
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum SpecifiedValue {
Normal,
Specified(specified::LengthOrPercentage),
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
SpecifiedValue::Normal => dest.write_str("normal"),
SpecifiedValue::Specified(ref l) => l.to_css(dest),
}
}
}
pub mod computed_value {
use values::computed::LengthOrPercentage;
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct T(pub Option<LengthOrPercentage>);
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match self.0 {
None => dest.write_str("normal"),
Some(l) => l.to_css(dest),
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(None)
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, context: &Context) -> computed_value::T {
match *self {
SpecifiedValue::Normal => computed_value::T(None),
SpecifiedValue::Specified(ref l) =>
computed_value::T(Some(l.to_computed_value(context))),
}
}
#[inline]
fn from_computed_value(computed: &computed_value::T) -> Self {
computed.0.map(|ref lop| {
SpecifiedValue::Specified(ToComputedValue::from_computed_value(lop))
}).unwrap_or(SpecifiedValue::Normal)
}
}
pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
if input.try(|input| input.expect_ident_matching("normal")).is_ok() {
Ok(SpecifiedValue::Normal)
} else {
specified::LengthOrPercentage::parse(context, input)
.map(SpecifiedValue::Specified)
}
}
</%helpers:longhand>
<%helpers:longhand name="-servo-text-decorations-in-effect"
derived_from="display text-decoration"
need_clone="True" products="servo"
animatable="False"
spec="Nonstandard (Internal property used by Servo)">
use cssparser::RGBA;
use std::fmt;
use style_traits::ToCss;
use values::HasViewportPercentage;
use values::computed::ComputedValueAsSpecified;
impl ComputedValueAsSpecified for SpecifiedValue {}
no_viewport_percentage!(SpecifiedValue);
#[derive(Clone, PartialEq, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SpecifiedValue {
pub underline: Option<RGBA>,
pub overline: Option<RGBA>,
pub line_through: Option<RGBA>,
}
pub mod computed_value {
pub type T = super::SpecifiedValue;
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, _: &mut W) -> fmt::Result where W: fmt::Write {
// Web compat doesn't matter here.
Ok(())
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
SpecifiedValue {
underline: None,
overline: None,
line_through: None,
}
}
fn maybe(flag: bool, context: &Context) -> Option<RGBA> {
if flag {
Some(context.style().get_color().clone_color())
} else {
None
}
}
fn derive(context: &Context) -> computed_value::T {
// Start with no declarations if this is an atomic inline-level box; otherwise, start with the
// declarations in effect and add in the text decorations that this block specifies.
let mut result = match context.style().get_box().clone_display() {
super::display::computed_value::T::inline_block |
super::display::computed_value::T::inline_table => SpecifiedValue {
underline: None,
overline: None,
line_through: None,
},
_ => context.inherited_style().get_inheritedtext().clone__servo_text_decorations_in_effect()
};
result.underline = maybe(context.style().get_text().has_underline()
|| result.underline.is_some(), context);
result.overline = maybe(context.style().get_text().has_overline()
|| result.overline.is_some(), context);
result.line_through = maybe(context.style().get_text().has_line_through()
|| result.line_through.is_some(), context);
result
}
#[inline]
pub fn derive_from_text_decoration(context: &mut Context) {
let derived = derive(context);
context.mutate_style().mutate_inheritedtext().set__servo_text_decorations_in_effect(derived);
}
#[inline]
pub fn derive_from_display(context: &mut Context) {
let derived = derive(context);
context.mutate_style().mutate_inheritedtext().set__servo_text_decorations_in_effect(derived);
}
</%helpers:longhand>
<%helpers:single_keyword_computed name="white-space"
values="normal pre nowrap pre-wrap pre-line"
gecko_constant_prefix="NS_STYLE_WHITESPACE"
needs_conversion="True"
animatable="False"
spec="https://drafts.csswg.org/css-text/#propdef-white-space">
use values::computed::ComputedValueAsSpecified;
use values::HasViewportPercentage;
impl ComputedValueAsSpecified for SpecifiedValue {}
no_viewport_percentage!(SpecifiedValue);
impl SpecifiedValue {
pub fn allow_wrap(&self) -> bool {
match *self {
SpecifiedValue::nowrap |
SpecifiedValue::pre => false,
SpecifiedValue::normal |
SpecifiedValue::pre_wrap |
SpecifiedValue::pre_line => true,
}
}
pub fn preserve_newlines(&self) -> bool {
match *self {
SpecifiedValue::normal |
SpecifiedValue::nowrap => false,
SpecifiedValue::pre |
SpecifiedValue::pre_wrap |
SpecifiedValue::pre_line => true,
}
}
pub fn preserve_spaces(&self) -> bool {
match *self {
SpecifiedValue::normal |
SpecifiedValue::nowrap |
SpecifiedValue::pre_line => false,
SpecifiedValue::pre |
SpecifiedValue::pre_wrap => true,
}
}
}
</%helpers:single_keyword_computed>
<%helpers:longhand name="text-shadow" animatable="True"
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-shadow">
use cssparser;
use std::fmt;
use style_traits::ToCss;
use values::HasViewportPercentage;
impl HasViewportPercentage for SpecifiedValue {
fn has_viewport_percentage(&self) -> bool {
let &SpecifiedValue(ref vec) = self;
vec.iter().any(|ref x| x .has_viewport_percentage())
}
}
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SpecifiedValue(Vec<SpecifiedTextShadow>);
impl HasViewportPercentage for SpecifiedTextShadow {
fn has_viewport_percentage(&self) -> bool {
self.offset_x.has_viewport_percentage() ||
self.offset_y.has_viewport_percentage() ||
self.blur_radius.has_viewport_percentage()
}
}
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SpecifiedTextShadow {
pub offset_x: specified::Length,
pub offset_y: specified::Length,
pub blur_radius: specified::Length,
pub color: Option<specified::CSSColor>,
}
pub mod computed_value {
use app_units::Au;
use cssparser::Color;
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct T(pub Vec<TextShadow>);
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct TextShadow {
pub offset_x: Au,
pub offset_y: Au,
pub blur_radius: Au,
pub color: Color,
}
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut iter = self.0.iter();
if let Some(shadow) = iter.next() {
try!(shadow.to_css(dest));
} else {
try!(dest.write_str("none"));
return Ok(())
}
for shadow in iter {
try!(dest.write_str(", "));
try!(shadow.to_css(dest));
}
Ok(())
}
}
impl ToCss for computed_value::TextShadow {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.offset_x.to_css(dest));
try!(dest.write_str(" "));
try!(self.offset_y.to_css(dest));
try!(dest.write_str(" "));
try!(self.blur_radius.to_css(dest));
try!(dest.write_str(" "));
try!(self.color.to_css(dest));
Ok(())
}
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut iter = self.0.iter();
if let Some(shadow) = iter.next() {
try!(shadow.to_css(dest));
} else {
try!(dest.write_str("none"));
return Ok(())
}
for shadow in iter {
try!(dest.write_str(", "));
try!(shadow.to_css(dest));
}
Ok(())
}
}
impl ToCss for SpecifiedTextShadow {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.offset_x.to_css(dest));
try!(dest.write_str(" "));
try!(self.offset_y.to_css(dest));
try!(dest.write_str(" "));
try!(self.blur_radius.to_css(dest));
if let Some(ref color) = self.color {
try!(dest.write_str(" "));
try!(color.to_css(dest));
}
Ok(())
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(Vec::new())
}
pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
Ok(SpecifiedValue(Vec::new()))
} else {
input.parse_comma_separated(|i| parse_one_text_shadow(context, i)).map(SpecifiedValue)
}
}
fn parse_one_text_shadow(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedTextShadow,()> {
use app_units::Au;
let mut lengths = [specified::Length::zero(), specified::Length::zero(), specified::Length::zero()];
let mut lengths_parsed = false;
let mut color = None;
loop {
if !lengths_parsed {
if let Ok(value) = input.try(|i| specified::Length::parse(context, i)) {
lengths[0] = value;
let mut length_parsed_count = 1;
while length_parsed_count < 3 {
if let Ok(value) = input.try(|i| specified::Length::parse(context, i)) {
lengths[length_parsed_count] = value
} else {
break
}
length_parsed_count += 1;
}
// The first two lengths must be specified.
if length_parsed_count < 2 {
return Err(())
}
lengths_parsed = true;
continue
}
}
if color.is_none() {
if let Ok(value) = input.try(|i| specified::CSSColor::parse(context, i)) {
color = Some(value);
continue
}
}
break
}
// Lengths must be specified.
if !lengths_parsed {
return Err(())
}
Ok(SpecifiedTextShadow {
offset_x: lengths[0].take(),
offset_y: lengths[1].take(),
blur_radius: lengths[2].take(),
color: color,
})
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
fn to_computed_value(&self, context: &Context) -> computed_value::T {
computed_value::T(self.0.iter().map(|value| {
computed_value::TextShadow {
offset_x: value.offset_x.to_computed_value(context),
offset_y: value.offset_y.to_computed_value(context),
blur_radius: value.blur_radius.to_computed_value(context),
color: value.color
.as_ref()
.map(|color| color.parsed)
.unwrap_or(cssparser::Color::CurrentColor),
}
}).collect())
}
fn from_computed_value(computed: &computed_value::T) -> Self {
SpecifiedValue(computed.0.iter().map(|value| {
SpecifiedTextShadow {
offset_x: ToComputedValue::from_computed_value(&value.offset_x),
offset_y: ToComputedValue::from_computed_value(&value.offset_y),
blur_radius: ToComputedValue::from_computed_value(&value.blur_radius),
color: Some(ToComputedValue::from_computed_value(&value.color)),
}
}).collect())
}
}
</%helpers:longhand>
<%helpers:longhand name="text-emphasis-style" products="gecko" need_clone="True" animatable="False"
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-emphasis-style">
use computed_values::writing_mode::T as writing_mode;
use std::fmt;
use style_traits::ToCss;
use unicode_segmentation::UnicodeSegmentation;
use values::HasViewportPercentage;
no_viewport_percentage!(SpecifiedValue);
pub mod computed_value {
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum T {
Keyword(KeywordValue),
None,
String(String),
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeywordValue {
pub fill: bool,
pub shape: super::ShapeKeyword,
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum SpecifiedValue {
Keyword(KeywordValue),
None,
String(String),
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
computed_value::T::Keyword(ref keyword) => keyword.to_css(dest),
computed_value::T::None => dest.write_str("none"),
computed_value::T::String(ref string) => write!(dest, "\"{}\"", string),
}
}
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
SpecifiedValue::Keyword(ref keyword) => keyword.to_css(dest),
SpecifiedValue::None => dest.write_str("none"),
SpecifiedValue::String(ref string) => write!(dest, "\"{}\"", string),
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum KeywordValue {
Fill(bool),
Shape(ShapeKeyword),
FillAndShape(bool, ShapeKeyword),
}
impl ToCss for KeywordValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if let Some(fill) = self.fill() {
if fill {
try!(dest.write_str("filled"));
} else {
try!(dest.write_str("open"));
}
}
if let Some(shape) = self.shape() {
if self.fill().is_some() {
try!(dest.write_str(" "));
}
try!(shape.to_css(dest));
}
Ok(())
}
}
impl ToCss for computed_value::KeywordValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if self.fill {
try!(dest.write_str("filled"));
} else {
try!(dest.write_str("open"));
}
try!(dest.write_str(" "));
self.shape.to_css(dest)
}
}
impl KeywordValue {
fn fill(&self) -> Option<bool> {<|fim▁hole|> KeywordValue::Fill(fill) |
KeywordValue::FillAndShape(fill,_) => Some(fill),
_ => None,
}
}
fn shape(&self) -> Option<ShapeKeyword> {
match *self {
KeywordValue::Shape(shape) |
KeywordValue::FillAndShape(_, shape) => Some(shape),
_ => None,
}
}
}
define_css_keyword_enum!(ShapeKeyword:
"dot" => Dot,
"circle" => Circle,
"double-circle" => DoubleCircle,
"triangle" => Triangle,
"sesame" => Sesame);
impl ShapeKeyword {
pub fn char(&self, fill: bool) -> &str {
match *self {
ShapeKeyword::Dot => if fill { "\u{2022}" } else { "\u{25e6}" },
ShapeKeyword::Circle => if fill { "\u{25cf}" } else { "\u{25cb}" },
ShapeKeyword::DoubleCircle => if fill { "\u{25c9}" } else { "\u{25ce}" },
ShapeKeyword::Triangle => if fill { "\u{25b2}" } else { "\u{25b3}" },
ShapeKeyword::Sesame => if fill { "\u{fe45}" } else { "\u{fe46}" },
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T::None
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue::None
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, context: &Context) -> computed_value::T {
match *self {
SpecifiedValue::Keyword(ref keyword) => {
let default_shape = if context.style().get_inheritedbox()
.clone_writing_mode() == writing_mode::horizontal_tb {
ShapeKeyword::Circle
} else {
ShapeKeyword::Sesame
};
computed_value::T::Keyword(computed_value::KeywordValue {
fill: keyword.fill().unwrap_or(true),
shape: keyword.shape().unwrap_or(default_shape),
})
},
SpecifiedValue::None => computed_value::T::None,
SpecifiedValue::String(ref s) => {
// Passing `true` to iterate over extended grapheme clusters, following
// recommendation at http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
let string = s.graphemes(true).next().unwrap_or("").to_string();
computed_value::T::String(string)
}
}
}
#[inline]
fn from_computed_value(computed: &computed_value::T) -> Self {
match *computed {
computed_value::T::Keyword(ref keyword) =>
SpecifiedValue::Keyword(KeywordValue::FillAndShape(keyword.fill,keyword.shape)),
computed_value::T::None => SpecifiedValue::None,
computed_value::T::String(ref string) => SpecifiedValue::String(string.clone())
}
}
}
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(SpecifiedValue::None);
}
if let Ok(s) = input.try(|input| input.expect_string()) {
// Handle <string>
return Ok(SpecifiedValue::String(s.into_owned()));
}
// Handle a pair of keywords
let mut shape = input.try(ShapeKeyword::parse);
let fill = if input.try(|input| input.expect_ident_matching("filled")).is_ok() {
Some(true)
} else if input.try(|input| input.expect_ident_matching("open")).is_ok() {
Some(false)
} else { None };
if shape.is_err() {
shape = input.try(ShapeKeyword::parse);
}
// At least one of shape or fill must be handled
let keyword_value = match (fill, shape) {
(Some(fill), Ok(shape)) => KeywordValue::FillAndShape(fill,shape),
(Some(fill), Err(_)) => KeywordValue::Fill(fill),
(None, Ok(shape)) => KeywordValue::Shape(shape),
_ => return Err(()),
};
Ok(SpecifiedValue::Keyword(keyword_value))
}
</%helpers:longhand>
<%helpers:longhand name="text-emphasis-position" animatable="False" products="gecko"
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-emphasis-position">
use std::fmt;
use values::computed::ComputedValueAsSpecified;
use values::HasViewportPercentage;
use style_traits::ToCss;
define_css_keyword_enum!(HorizontalWritingModeValue:
"over" => Over,
"under" => Under);
define_css_keyword_enum!(VerticalWritingModeValue:
"right" => Right,
"left" => Left);
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SpecifiedValue(pub HorizontalWritingModeValue, pub VerticalWritingModeValue);
pub mod computed_value {
pub type T = super::SpecifiedValue;
}
impl ComputedValueAsSpecified for SpecifiedValue {}
no_viewport_percentage!(SpecifiedValue);
pub fn get_initial_value() -> computed_value::T {
SpecifiedValue(HorizontalWritingModeValue::Over, VerticalWritingModeValue::Right)
}
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
if let Ok(horizontal) = input.try(|input| HorizontalWritingModeValue::parse(input)) {
let vertical = try!(VerticalWritingModeValue::parse(input));
Ok(SpecifiedValue(horizontal, vertical))
} else {
let vertical = try!(VerticalWritingModeValue::parse(input));
let horizontal = try!(HorizontalWritingModeValue::parse(input));
Ok(SpecifiedValue(horizontal, vertical))
}
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let SpecifiedValue(horizontal, vertical) = *self;
try!(horizontal.to_css(dest));
try!(dest.write_char(' '));
vertical.to_css(dest)
}
}
</%helpers:longhand>
${helpers.predefined_type("text-emphasis-color", "CSSColor",
"::cssparser::Color::CurrentColor",
initial_specified_value="specified::CSSColor::currentcolor()",
products="gecko", animatable=True,
complex_color=True, need_clone=True,
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-emphasis-color")}
${helpers.predefined_type(
"-moz-tab-size", "LengthOrNumber",
"::values::Either::Second(8.0)",
"parse_non_negative",
products="gecko", animatable=False,
spec="https://drafts.csswg.org/css-text-3/#tab-size-property")}
// CSS Compatibility
// https://compat.spec.whatwg.org
${helpers.predefined_type(
"-webkit-text-fill-color", "CSSColor",
"CSSParserColor::CurrentColor",
products="gecko", animatable=True,
complex_color=True, need_clone=True,
spec="https://compat.spec.whatwg.org/#the-webkit-text-fill-color")}
${helpers.predefined_type(
"-webkit-text-stroke-color", "CSSColor",
"CSSParserColor::CurrentColor",
initial_specified_value="specified::CSSColor::currentcolor()",
products="gecko", animatable=True,
complex_color=True, need_clone=True,
spec="https://compat.spec.whatwg.org/#the-webkit-text-stroke-color")}
<%helpers:longhand products="gecko" name="-webkit-text-stroke-width" animatable="False"
spec="https://compat.spec.whatwg.org/#the-webkit-text-stroke-width">
use app_units::Au;
use std::fmt;
use style_traits::ToCss;
use values::HasViewportPercentage;
use values::specified::{BorderWidth, Length};
pub type SpecifiedValue = BorderWidth;
#[inline]
pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
BorderWidth::parse(context, input)
}
pub mod computed_value {
use app_units::Au;
pub type T = Au;
}
#[inline] pub fn get_initial_value() -> computed_value::T {
Au::from_px(0)
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
BorderWidth::from_length(Length::zero())
}
</%helpers:longhand>
// CSS Ruby Layout Module Level 1
// https://drafts.csswg.org/css-ruby/
${helpers.single_keyword("ruby-align", "space-around start center space-between",
products="gecko", animatable=False,
spec="https://drafts.csswg.org/css-ruby/#ruby-align-property")}
${helpers.single_keyword("ruby-position", "over under",
products="gecko", animatable=False,
spec="https://drafts.csswg.org/css-ruby/#ruby-position-property")}
// CSS Writing Modes Module Level 3
// https://drafts.csswg.org/css-writing-modes-3/
// The spec has "digits <integer>?" value in addition. But that value is
// at-risk, and Gecko's layout code doesn't support that either. So we
// can just take the easy way for now.
${helpers.single_keyword("text-combine-upright", "none all",
products="gecko", animatable=False,
spec="https://drafts.csswg.org/css-writing-modes-3/#text-combine-upright")}
// SVG 1.1: Section 11 - Painting: Filling, Stroking and Marker Symbols
${helpers.single_keyword("text-rendering",
"auto optimizespeed optimizelegibility geometricprecision",
animatable=False,
spec="https://www.w3.org/TR/SVG11/painting.html#TextRenderingProperty")}<|fim▁end|> | match *self { |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![cfg_attr(test, feature(net, alloc, path, io))]
extern crate net;
extern crate net_traits;
extern crate profile;
extern crate url;
extern crate util;
#[cfg(test)] mod cookie;<|fim▁hole|><|fim▁end|> | #[cfg(test)] mod data_loader;
#[cfg(test)] mod mime_classifier;
#[cfg(test)] mod resource_task; |
<|file_name|>dialog.service.ts<|end_file_name|><|fim▁begin|>import {Injectable} from 'angular2/core';
/**
* Async modal dialog service
* DialogService makes this app easier to test by faking this service.
* TODO: better modal implemenation that doesn't use window.confirm
*/<|fim▁hole|> * Ask user to confirm an action. `message` explains the action and choices.
* Returns promise resolving to `true`=confirm or `false`=cancel
*/
confirm(message?:string) {
return new Promise<boolean>((resolve, reject) =>
resolve(window.confirm(message || 'Is it OK?')));
};
alert(message?: string ) {
alert(message);
}
}<|fim▁end|> | @Injectable()
export class DialogService {
/** |
<|file_name|>soln.py<|end_file_name|><|fim▁begin|>from typing import List
class Solution:<|fim▁hole|> for i in range(0, 26):
c = chr(97+i)
lastPos[c] = S.rfind(c)
for i, c in enumerate(S):
# Encounter new index higher than currMax
if i > currMax:
res.append(currMax+1)
currMax = max(currMax, lastPos[c])
res.append(len(S))
ans = [res[i]-res[i-1] for i in range(1, len(res))]
return ans<|fim▁end|> | def partitionLabels(self, S: str) -> List[int]:
lastPos, seen, currMax = {}, set(), -1
res = [] |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .create2 import *
from .factory import *<|fim▁hole|><|fim▁end|> |
__all__ = ["FactoryCreate", "FactorySimulation"] |
<|file_name|>LoadStatisticsTest.java<|end_file_name|><|fim▁begin|>/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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.
*/
package hudson.model;
import hudson.model.MultiStageTimeSeries.TimeScale;
import hudson.model.queue.SubTask;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import org.jfree.chart.JFreeChart;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author Kohsuke Kawaguchi
*/
public class LoadStatisticsTest {
@Test
public void graph() throws IOException {
LoadStatistics ls = new LoadStatistics(0, 0) {
public int computeIdleExecutors() {
throw new UnsupportedOperationException();
}
public int computeTotalExecutors() {
throw new UnsupportedOperationException();
}
public int computeQueueLength() {
throw new UnsupportedOperationException();
}
@Override
protected Iterable<Node> getNodes() {
throw new UnsupportedOperationException();
}
@Override
protected boolean matches(Queue.Item item, SubTask subTask) {
throw new UnsupportedOperationException();
}
};
for (int i = 0; i < 50; i++) {
ls.onlineExecutors.update(4);
ls.busyExecutors.update(3);
ls.availableExecutors.update(1);
ls.queueLength.update(3);
}
for (int i = 0; i < 50; i++) {
ls.onlineExecutors.update(0);
ls.busyExecutors.update(0);
ls.availableExecutors.update(0);
ls.queueLength.update(1);
}
JFreeChart chart = ls.createTrendChart(TimeScale.SEC10).createChart();
BufferedImage image = chart.createBufferedImage(400, 200);
File tempFile = File.createTempFile("chart-", "png");
try (OutputStream os = Files.newOutputStream(tempFile.toPath(), StandardOpenOption.DELETE_ON_CLOSE)) {
ImageIO.write(image, "PNG", os);
} finally {
tempFile.delete();
}
}
@Test
public void isModernWorks() throws Exception {
assertThat(LoadStatistics.isModern(Modern.class), is(true));
assertThat(LoadStatistics.isModern(LoadStatistics.class), is(false));
}
private static class Modern extends LoadStatistics {
protected Modern(int initialOnlineExecutors, int initialBusyExecutors) {
super(initialOnlineExecutors, initialBusyExecutors);
}<|fim▁hole|> public int computeIdleExecutors() {
return 0;
}
@Override
public int computeTotalExecutors() {
return 0;
}
@Override
public int computeQueueLength() {
return 0;
}
@Override
protected Iterable<Node> getNodes() {
return null;
}
@Override
protected boolean matches(Queue.Item item, SubTask subTask) {
return false;
}
}
}<|fim▁end|> |
@Override |
<|file_name|>OrbeonForms.js<|end_file_name|><|fim▁begin|>$identify("org/mathdox/formulaeditor/OrbeonForms.js");
$require("org/mathdox/formulaeditor/FormulaEditor.js");
var ORBEON;
$main(function(){
if (ORBEON && ORBEON.xforms && ORBEON.xforms.Document) {
/**
* Extend the save function of the formula editor to use the orbeon update
* mechanism, see also:
* http://www.orbeon.com/ops/doc/reference-xforms-2#xforms-javascript
*/
org.mathdox.formulaeditor.FormulaEditor =<|fim▁hole|> // call the parent function
arguments.callee.parent.save.apply(this, arguments);
// let orbeon know about the change of textarea content
var textarea = this.textarea;
if (textarea.id) {
ORBEON.xforms.Document.setValue(textarea.id, textarea.value);
}
}
});
/**
* Override Orbeon's xformsHandleResponse method so that it initializes any
* canvases that might have been added by the xforms engine.
*/
/* prevent an error if the xformsHandleResponse doesn't exist */
var xformsHandleResponse;
var oldXformsHandleResponse;
var newXformsHandleResponse;
var ancientOrbeon;
if (xformsHandleResponse) {
oldXformsHandleResponse = xformsHandleResponse;
} else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponse) {
oldXformsHandleResponse = ORBEON.xforms.Server.handleResponse;
} else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponseDom) {
oldXformsHandleResponse = ORBEON.xforms.Server.handleResponseDom;
} else if (ORBEON.xforms.server && ORBEON.xforms.server.AjaxServer && ORBEON.xforms.server.AjaxServer.handleResponseDom) {
// orbeon 3.9
oldXformsHandleResponse = ORBEON.xforms.server.AjaxServer.handleResponseDom;
} else {
if (org.mathdox.formulaeditor.options.ancientOrbeon !== undefined &&
org.mathdox.formulaeditor.options.ancientOrbeon == true) {
ancientOrbeon = true;
} else {
ancientOrbeon = false;
alert("ERROR: detected orbeon, but could not add response handler");
}
}
newXformsHandleResponse = function(request) {
// call the overridden method
if (ancientOrbeon != true ) {
oldXformsHandleResponse.apply(this, arguments);
}
// go through all canvases in the document
var canvases = document.getElementsByTagName("canvas");
for (var i=0; i<canvases.length; i++) {
// initialize a FormulaEditor for each canvas
var canvas = canvases[i];
if (canvas.nextSibling) {
if (canvas.nextSibling.tagName.toLowerCase() == "textarea") {
var FormulaEditor = org.mathdox.formulaeditor.FormulaEditor;
var editor = new FormulaEditor(canvas.nextSibling, canvas);
// (re-)load the contents of the textarea into the editor
editor.load();
}
}
}
};
if (xformsHandleResponse) {
xformsHandleResponse = newXformsHandleResponse;
} else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponse) {
ORBEON.xforms.Server.handleResponse = newXformsHandleResponse;
} else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponseDom) {
ORBEON.xforms.Server.handleResponseDom = newXformsHandleResponse;
} else if (ORBEON.xforms.server && ORBEON.xforms.server.AjaxServer && ORBEON.xforms.server.AjaxServer.handleResponseDom) {
ORBEON.xforms.server.AjaxServer.handleResponseDom = newXformsHandleResponse;
}
}
});<|fim▁end|> | $extend(org.mathdox.formulaeditor.FormulaEditor, {
save : function() {
|
<|file_name|>rpc_apis.rs<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
use std::cmp::PartialEq;
use std::collections::{BTreeMap, HashSet};
use std::str::FromStr;
use std::sync::{Arc, Weak};
pub use parity_rpc::signer::SignerService;
pub use parity_rpc::dapps::{DappsService, LocalDapp};
use ethcore::account_provider::AccountProvider;
use ethcore::client::Client;
use ethcore::miner::{Miner, ExternalMiner};
use ethcore::snapshot::SnapshotService;
use ethcore_logger::RotatingLogger;
use ethsync::{ManageNetwork, SyncProvider, LightSync};
use hash_fetch::fetch::Client as FetchClient;
use jsonrpc_core::{self as core, MetaIoHandler};
use light::{TransactionQueue as LightTransactionQueue, Cache as LightDataCache};
use light::client::LightChainClient;
use node_health::NodeHealth;
use parity_reactor;
use parity_rpc::dispatch::{FullDispatcher, LightDispatcher};
use parity_rpc::informant::{ActivityNotifier, ClientNotifier};
use parity_rpc::{Metadata, NetworkSettings, Host};
use updater::Updater;
use parking_lot::{Mutex, RwLock};
#[derive(Debug, PartialEq, Clone, Eq, Hash)]
pub enum Api {
/// Web3 (Safe)
Web3,
/// Net (Safe)
Net,
/// Eth (Safe)
Eth,
/// Eth Pub-Sub (Safe)
EthPubSub,
/// Geth-compatible "personal" API (DEPRECATED; only used in `--geth` mode.)
Personal,
/// Signer - Confirm transactions in Signer (UNSAFE: Passwords, List of transactions)
Signer,
/// Parity - Custom extensions (Safe)
Parity,
/// Parity PubSub - Generic Publish-Subscriber (Safety depends on other APIs exposed).
ParityPubSub,
/// Parity Accounts extensions (UNSAFE: Passwords, Side Effects (new account))
ParityAccounts,
/// Parity - Set methods (UNSAFE: Side Effects affecting node operation)
ParitySet,
/// Traces (Safe)
Traces,
/// Rpc (Safe)
Rpc,
/// SecretStore (Safe)
SecretStore,
/// Whisper (Safe)
// TODO: _if_ someone guesses someone else's key or filter IDs they can remove
// BUT these are all ephemeral so it seems fine.
Whisper,
/// Whisper Pub-Sub (Safe but same concerns as above).
WhisperPubSub,
}
impl FromStr for Api {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use self::Api::*;
match s {
"web3" => Ok(Web3),
"net" => Ok(Net),
"eth" => Ok(Eth),
"pubsub" => Ok(EthPubSub),
"personal" => Ok(Personal),
"signer" => Ok(Signer),
"parity" => Ok(Parity),
"parity_pubsub" => Ok(ParityPubSub),
"parity_accounts" => Ok(ParityAccounts),
"parity_set" => Ok(ParitySet),
"traces" => Ok(Traces),
"rpc" => Ok(Rpc),
"secretstore" => Ok(SecretStore),
"shh" => Ok(Whisper),
"shh_pubsub" => Ok(WhisperPubSub),
api => Err(format!("Unknown api: {}", api))
}
}
}
#[derive(Debug, Clone)]
pub enum ApiSet {
// Safe context (like token-protected WS interface)
SafeContext,
// Unsafe context (like jsonrpc over http)
UnsafeContext,
// Public context (like public jsonrpc over http)
PublicContext,
// All possible APIs
All,
// Local "unsafe" context and accounts access
IpcContext,
// APIs for Parity Generic Pub-Sub
PubSub,
// Fixed list of APis
List(HashSet<Api>),
}
impl Default for ApiSet {
fn default() -> Self {
ApiSet::UnsafeContext
}
}
impl PartialEq for ApiSet {
fn eq(&self, other: &Self) -> bool {
self.list_apis() == other.list_apis()
}
}
impl FromStr for ApiSet {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut apis = HashSet::new();
for api in s.split(',') {
match api {
"all" => {
apis.extend(ApiSet::All.list_apis());
},
"safe" => {
// Safe APIs are those that are safe even in UnsafeContext.
apis.extend(ApiSet::UnsafeContext.list_apis());
},
// Remove the API
api if api.starts_with("-") => {
let api = api[1..].parse()?;
apis.remove(&api);
},
api => {
let api = api.parse()?;
apis.insert(api);
},
}
}
Ok(ApiSet::List(apis))
}
}
fn to_modules(apis: &HashSet<Api>) -> BTreeMap<String, String> {
let mut modules = BTreeMap::new();
for api in apis {
let (name, version) = match *api {
Api::Web3 => ("web3", "1.0"),
Api::Net => ("net", "1.0"),
Api::Eth => ("eth", "1.0"),
Api::EthPubSub => ("pubsub", "1.0"),
Api::Personal => ("personal", "1.0"),
Api::Signer => ("signer", "1.0"),
Api::Parity => ("parity", "1.0"),
Api::ParityAccounts => ("parity_accounts", "1.0"),
Api::ParityPubSub => ("parity_pubsub", "1.0"),
Api::ParitySet => ("parity_set", "1.0"),
Api::Traces => ("traces", "1.0"),
Api::Rpc => ("rpc", "1.0"),
Api::SecretStore => ("secretstore", "1.0"),
Api::Whisper => ("shh", "1.0"),
Api::WhisperPubSub => ("shh_pubsub", "1.0"),
};
modules.insert(name.into(), version.into());
}
modules
}
/// RPC dependencies can be used to initialize RPC endpoints from APIs.
pub trait Dependencies {
type Notifier: ActivityNotifier;
/// Create the activity notifier.
fn activity_notifier(&self) -> Self::Notifier;
/// Extend the given I/O handler with endpoints for each API.
fn extend_with_set<S>(
&self,
handler: &mut MetaIoHandler<Metadata, S>,
apis: &HashSet<Api>,
) where S: core::Middleware<Metadata>;
}
/// RPC dependencies for a full node.
pub struct FullDependencies {
pub signer_service: Arc<SignerService>,
pub client: Arc<Client>,
pub snapshot: Arc<SnapshotService>,
pub sync: Arc<SyncProvider>,
pub net: Arc<ManageNetwork>,
pub secret_store: Option<Arc<AccountProvider>>,
pub miner: Arc<Miner>,
pub external_miner: Arc<ExternalMiner>,
pub logger: Arc<RotatingLogger>,
pub settings: Arc<NetworkSettings>,
pub net_service: Arc<ManageNetwork>,
pub updater: Arc<Updater>,
pub health: NodeHealth,
pub geth_compatibility: bool,
pub dapps_service: Option<Arc<DappsService>>,
pub dapps_address: Option<Host>,
pub ws_address: Option<Host>,
pub fetch: FetchClient,
pub remote: parity_reactor::Remote,
pub whisper_rpc: Option<::whisper::RpcFactory>,
}
impl FullDependencies {
fn extend_api<S>(
&self,
handler: &mut MetaIoHandler<Metadata, S>,
apis: &HashSet<Api>,
for_generic_pubsub: bool,
) where S: core::Middleware<Metadata> {
use parity_rpc::v1::*;
macro_rules! add_signing_methods {
($namespace:ident, $handler:expr, $deps:expr, $nonces:expr) => {
{
let deps = &$deps;
let dispatcher = FullDispatcher::new(deps.client.clone(), deps.miner.clone(), $nonces);
if deps.signer_service.is_enabled() {
$handler.extend_with($namespace::to_delegate(SigningQueueClient::new(&deps.signer_service, dispatcher, deps.remote.clone(), &deps.secret_store)))
} else {
$handler.extend_with($namespace::to_delegate(SigningUnsafeClient::new(&deps.secret_store, dispatcher)))
}
}
}
}
let nonces = Arc::new(Mutex::new(dispatch::Reservations::with_pool(self.fetch.pool())));
let dispatcher = FullDispatcher::new(
self.client.clone(),
self.miner.clone(),
nonces.clone(),
);
for api in apis {
match *api {
Api::Web3 => {
handler.extend_with(Web3Client::new().to_delegate());
},
Api::Net => {
handler.extend_with(NetClient::new(&self.sync).to_delegate());
},
Api::Eth => {
let client = EthClient::new(
&self.client,
&self.snapshot,
&self.sync,
&self.secret_store,
&self.miner,
&self.external_miner,
EthClientOptions {
pending_nonce_from_queue: self.geth_compatibility,
allow_pending_receipt_query: !self.geth_compatibility,
send_block_number_in_get_work: !self.geth_compatibility,
}
);
handler.extend_with(client.to_delegate());
if !for_generic_pubsub {
let filter_client = EthFilterClient::new(self.client.clone(), self.miner.clone());
handler.extend_with(filter_client.to_delegate());
add_signing_methods!(EthSigning, handler, self, nonces.clone());
}
},
Api::EthPubSub => {
if !for_generic_pubsub {
let client = EthPubSubClient::new(self.client.clone(), self.remote.clone());
self.client.add_notify(client.handler());
handler.extend_with(client.to_delegate());
}
},
Api::Personal => {
handler.extend_with(PersonalClient::new(self.secret_store.clone(), dispatcher.clone(), self.geth_compatibility).to_delegate());
},
Api::Signer => {
handler.extend_with(SignerClient::new(&self.secret_store, dispatcher.clone(), &self.signer_service, self.remote.clone()).to_delegate());
},
Api::Parity => {
let signer = match self.signer_service.is_enabled() {
true => Some(self.signer_service.clone()),
false => None,
};
handler.extend_with(ParityClient::new(
self.client.clone(),
self.miner.clone(),
self.sync.clone(),
self.updater.clone(),
self.net_service.clone(),
self.health.clone(),
self.secret_store.clone(),
self.logger.clone(),
self.settings.clone(),
signer,
self.dapps_address.clone(),
self.ws_address.clone(),
).to_delegate());
if !for_generic_pubsub {
add_signing_methods!(ParitySigning, handler, self, nonces.clone());
}
},
Api::ParityPubSub => {
if !for_generic_pubsub {
let mut rpc = MetaIoHandler::default();
let apis = ApiSet::List(apis.clone()).retain(ApiSet::PubSub).list_apis();
self.extend_api(&mut rpc, &apis, true);
handler.extend_with(PubSubClient::new(rpc, self.remote.clone()).to_delegate());
}
},
Api::ParityAccounts => {
handler.extend_with(ParityAccountsClient::new(&self.secret_store).to_delegate());
},
Api::ParitySet => {
handler.extend_with(ParitySetClient::new(
&self.client,
&self.miner,
&self.updater,
&self.net_service,
self.dapps_service.clone(),
self.fetch.clone(),
).to_delegate())
},
Api::Traces => {
handler.extend_with(TracesClient::new(&self.client).to_delegate())
},
Api::Rpc => {
let modules = to_modules(&apis);
handler.extend_with(RpcClient::new(modules).to_delegate());
},
Api::SecretStore => {
handler.extend_with(SecretStoreClient::new(&self.secret_store).to_delegate());
},
Api::Whisper => {
if let Some(ref whisper_rpc) = self.whisper_rpc {
let whisper = whisper_rpc.make_handler(self.net.clone());
handler.extend_with(::parity_whisper::rpc::Whisper::to_delegate(whisper));
}
}
Api::WhisperPubSub => {
if !for_generic_pubsub {
if let Some(ref whisper_rpc) = self.whisper_rpc {
let whisper = whisper_rpc.make_handler(self.net.clone());
handler.extend_with(
::parity_whisper::rpc::WhisperPubSub::to_delegate(whisper)
);
}
}
}
}
}
}
}
impl Dependencies for FullDependencies {
type Notifier = ClientNotifier;
fn activity_notifier(&self) -> ClientNotifier {
ClientNotifier {
client: self.client.clone(),
}
}
fn extend_with_set<S>(
&self,
handler: &mut MetaIoHandler<Metadata, S>,
apis: &HashSet<Api>,
) where S: core::Middleware<Metadata> {
self.extend_api(handler, apis, false)
}
}
/// Light client notifier. Doesn't do anything yet, but might in the future.
pub struct LightClientNotifier;
impl ActivityNotifier for LightClientNotifier {
fn active(&self) {}
}
/// RPC dependencies for a light client.
pub struct LightDependencies<T> {
pub signer_service: Arc<SignerService>,
pub client: Arc<T>,
pub sync: Arc<LightSync>,
pub net: Arc<ManageNetwork>,
pub secret_store: Arc<AccountProvider>,
pub logger: Arc<RotatingLogger>,
pub settings: Arc<NetworkSettings>,
pub health: NodeHealth,
pub on_demand: Arc<::light::on_demand::OnDemand>,
pub cache: Arc<Mutex<LightDataCache>>,
pub transaction_queue: Arc<RwLock<LightTransactionQueue>>,
pub dapps_service: Option<Arc<DappsService>>,
pub dapps_address: Option<Host>,
pub ws_address: Option<Host>,
pub fetch: FetchClient,
pub geth_compatibility: bool,
pub remote: parity_reactor::Remote,
pub whisper_rpc: Option<::whisper::RpcFactory>,
}
impl<C: LightChainClient + 'static> LightDependencies<C> {
fn extend_api<T: core::Middleware<Metadata>>(
&self,
handler: &mut MetaIoHandler<Metadata, T>,
apis: &HashSet<Api>,
for_generic_pubsub: bool,
) {
use parity_rpc::v1::*;
let dispatcher = LightDispatcher::new(
self.sync.clone(),
self.client.clone(),
self.on_demand.clone(),
self.cache.clone(),
self.transaction_queue.clone(),
Arc::new(Mutex::new(dispatch::Reservations::with_pool(self.fetch.pool()))),
);
macro_rules! add_signing_methods {
($namespace:ident, $handler:expr, $deps:expr) => {
{
let deps = &$deps;
let dispatcher = dispatcher.clone();
let secret_store = Some(deps.secret_store.clone());
if deps.signer_service.is_enabled() {
$handler.extend_with($namespace::to_delegate(
SigningQueueClient::new(&deps.signer_service, dispatcher, deps.remote.clone(), &secret_store)
))
} else {
$handler.extend_with(
$namespace::to_delegate(SigningUnsafeClient::new(&secret_store, dispatcher))
)
}
}
}
}
for api in apis {
match *api {
Api::Web3 => {
handler.extend_with(Web3Client::new().to_delegate());
},
Api::Net => {
handler.extend_with(light::NetClient::new(self.sync.clone()).to_delegate());
},
Api::Eth => {
let client = light::EthClient::new(
self.sync.clone(),
self.client.clone(),
self.on_demand.clone(),
self.transaction_queue.clone(),
self.secret_store.clone(),
self.cache.clone(),
);
handler.extend_with(Eth::to_delegate(client.clone()));
if !for_generic_pubsub {
handler.extend_with(EthFilter::to_delegate(client));
add_signing_methods!(EthSigning, handler, self);
}
},
Api::EthPubSub => {
let client = EthPubSubClient::light(
self.client.clone(),
self.on_demand.clone(),
self.sync.clone(),
self.cache.clone(),
self.remote.clone(),
);
self.client.add_listener(
Arc::downgrade(&client.handler()) as Weak<::light::client::LightChainNotify>
);
handler.extend_with(EthPubSub::to_delegate(client));
},
Api::Personal => {
let secret_store = Some(self.secret_store.clone());
handler.extend_with(PersonalClient::new(secret_store, dispatcher.clone(), self.geth_compatibility).to_delegate());
},
Api::Signer => {
let secret_store = Some(self.secret_store.clone());
handler.extend_with(SignerClient::new(&secret_store, dispatcher.clone(), &self.signer_service, self.remote.clone()).to_delegate());
},
Api::Parity => {
let signer = match self.signer_service.is_enabled() {
true => Some(self.signer_service.clone()),
false => None,
};
handler.extend_with(light::ParityClient::new(
self.client.clone(),
Arc::new(dispatcher.clone()),
self.secret_store.clone(),
self.logger.clone(),
self.settings.clone(),
self.health.clone(),
signer,
self.dapps_address.clone(),
self.ws_address.clone(),
).to_delegate());
if !for_generic_pubsub {
add_signing_methods!(ParitySigning, handler, self);
}
},
Api::ParityPubSub => {
if !for_generic_pubsub {
let mut rpc = MetaIoHandler::default();
let apis = ApiSet::List(apis.clone()).retain(ApiSet::PubSub).list_apis();
self.extend_api(&mut rpc, &apis, true);
handler.extend_with(PubSubClient::new(rpc, self.remote.clone()).to_delegate());
}
},
Api::ParityAccounts => {
let secret_store = Some(self.secret_store.clone());
handler.extend_with(ParityAccountsClient::new(&secret_store).to_delegate());
},
Api::ParitySet => {
handler.extend_with(light::ParitySetClient::new(
self.sync.clone(),
self.dapps_service.clone(),
self.fetch.clone(),
).to_delegate())
},
Api::Traces => {
handler.extend_with(light::TracesClient.to_delegate())
},
Api::Rpc => {
let modules = to_modules(&apis);
handler.extend_with(RpcClient::new(modules).to_delegate());
},
Api::SecretStore => {
let secret_store = Some(self.secret_store.clone());
handler.extend_with(SecretStoreClient::new(&secret_store).to_delegate());
},
Api::Whisper => {
if let Some(ref whisper_rpc) = self.whisper_rpc {
let whisper = whisper_rpc.make_handler(self.net.clone());
handler.extend_with(::parity_whisper::rpc::Whisper::to_delegate(whisper));
}
}
Api::WhisperPubSub => {
if let Some(ref whisper_rpc) = self.whisper_rpc {
let whisper = whisper_rpc.make_handler(self.net.clone());
handler.extend_with(::parity_whisper::rpc::WhisperPubSub::to_delegate(whisper));
}
}
}
}
}
}
impl<T: LightChainClient + 'static> Dependencies for LightDependencies<T> {
type Notifier = LightClientNotifier;
fn activity_notifier(&self) -> Self::Notifier { LightClientNotifier }
fn extend_with_set<S>(
&self,
handler: &mut MetaIoHandler<Metadata, S>,
apis: &HashSet<Api>,
) where S: core::Middleware<Metadata> {
self.extend_api(handler, apis, false)
}
}
impl ApiSet {
/// Retains only APIs in given set.
pub fn retain(self, set: Self) -> Self {
ApiSet::List(&self.list_apis() & &set.list_apis())
}
pub fn list_apis(&self) -> HashSet<Api> {
let mut public_list = [
Api::Web3,
Api::Net,
Api::Eth,
Api::EthPubSub,
Api::Parity,
Api::Rpc,
Api::SecretStore,
Api::Whisper,
Api::WhisperPubSub,
].into_iter().cloned().collect();
match *self {
ApiSet::List(ref apis) => apis.clone(),
ApiSet::PublicContext => public_list,
ApiSet::UnsafeContext => {
public_list.insert(Api::Traces);
public_list.insert(Api::ParityPubSub);
public_list
},
ApiSet::IpcContext => {
public_list.insert(Api::Traces);
public_list.insert(Api::ParityPubSub);
public_list.insert(Api::ParityAccounts);
public_list
},
ApiSet::SafeContext => {
public_list.insert(Api::Traces);
public_list.insert(Api::ParityPubSub);
public_list.insert(Api::ParityAccounts);
public_list.insert(Api::ParitySet);
public_list.insert(Api::Signer);
public_list
},
ApiSet::All => {
public_list.insert(Api::Traces);
public_list.insert(Api::ParityPubSub);
public_list.insert(Api::ParityAccounts);
public_list.insert(Api::ParitySet);
public_list.insert(Api::Signer);
public_list.insert(Api::Personal);
public_list
},
ApiSet::PubSub => [
Api::Eth,
Api::Parity,
Api::ParityAccounts,
Api::ParitySet,
Api::Traces,
].into_iter().cloned().collect()
}
}
}
#[cfg(test)]
mod test {
use super::{Api, ApiSet};
#[test]
fn test_api_parsing() {
assert_eq!(Api::Web3, "web3".parse().unwrap());
assert_eq!(Api::Net, "net".parse().unwrap());
assert_eq!(Api::Eth, "eth".parse().unwrap());
assert_eq!(Api::EthPubSub, "pubsub".parse().unwrap());
assert_eq!(Api::Personal, "personal".parse().unwrap());
assert_eq!(Api::Signer, "signer".parse().unwrap());
assert_eq!(Api::Parity, "parity".parse().unwrap());
assert_eq!(Api::ParityAccounts, "parity_accounts".parse().unwrap());
assert_eq!(Api::ParitySet, "parity_set".parse().unwrap());
assert_eq!(Api::Traces, "traces".parse().unwrap());<|fim▁hole|> assert_eq!(Api::Rpc, "rpc".parse().unwrap());
assert_eq!(Api::SecretStore, "secretstore".parse().unwrap());
assert_eq!(Api::Whisper, "shh".parse().unwrap());
assert_eq!(Api::WhisperPubSub, "shh_pubsub".parse().unwrap());
assert!("rp".parse::<Api>().is_err());
}
#[test]
fn test_api_set_default() {
assert_eq!(ApiSet::UnsafeContext, ApiSet::default());
}
#[test]
fn test_api_set_parsing() {
assert_eq!(ApiSet::List(vec![Api::Web3, Api::Eth].into_iter().collect()), "web3,eth".parse().unwrap());
}
#[test]
fn test_api_set_unsafe_context() {
let expected = vec![
// make sure this list contains only SAFE methods
Api::Web3, Api::Net, Api::Eth, Api::EthPubSub, Api::Parity, Api::ParityPubSub, Api::Traces, Api::Rpc, Api::SecretStore, Api::Whisper, Api::WhisperPubSub,
].into_iter().collect();
assert_eq!(ApiSet::UnsafeContext.list_apis(), expected);
}
#[test]
fn test_api_set_ipc_context() {
let expected = vec![
// safe
Api::Web3, Api::Net, Api::Eth, Api::EthPubSub, Api::Parity, Api::ParityPubSub, Api::Traces, Api::Rpc, Api::SecretStore, Api::Whisper, Api::WhisperPubSub,
// semi-safe
Api::ParityAccounts
].into_iter().collect();
assert_eq!(ApiSet::IpcContext.list_apis(), expected);
}
#[test]
fn test_api_set_safe_context() {
let expected = vec![
// safe
Api::Web3, Api::Net, Api::Eth, Api::EthPubSub, Api::Parity, Api::ParityPubSub, Api::Traces, Api::Rpc, Api::SecretStore, Api::Whisper, Api::WhisperPubSub,
// semi-safe
Api::ParityAccounts,
// Unsafe
Api::ParitySet, Api::Signer,
].into_iter().collect();
assert_eq!(ApiSet::SafeContext.list_apis(), expected);
}
#[test]
fn test_all_apis() {
assert_eq!("all".parse::<ApiSet>().unwrap(), ApiSet::List(vec![
Api::Web3, Api::Net, Api::Eth, Api::EthPubSub, Api::Parity, Api::ParityPubSub, Api::Traces, Api::Rpc, Api::SecretStore, Api::Whisper, Api::WhisperPubSub,
Api::ParityAccounts,
Api::ParitySet, Api::Signer,
Api::Personal
].into_iter().collect()));
}
#[test]
fn test_all_without_personal_apis() {
assert_eq!("personal,all,-personal".parse::<ApiSet>().unwrap(), ApiSet::List(vec![
Api::Web3, Api::Net, Api::Eth, Api::EthPubSub, Api::Parity, Api::ParityPubSub, Api::Traces, Api::Rpc, Api::SecretStore, Api::Whisper, Api::WhisperPubSub,
Api::ParityAccounts,
Api::ParitySet, Api::Signer,
].into_iter().collect()));
}
#[test]
fn test_safe_parsing() {
assert_eq!("safe".parse::<ApiSet>().unwrap(), ApiSet::List(vec![
Api::Web3, Api::Net, Api::Eth, Api::EthPubSub, Api::Parity, Api::ParityPubSub, Api::Traces, Api::Rpc, Api::SecretStore, Api::Whisper, Api::WhisperPubSub,
].into_iter().collect()));
}
}<|fim▁end|> | |
<|file_name|>tsigkeys.py<|end_file_name|><|fim▁begin|># Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hpe.com>
#
# 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 pecan
from oslo_log import log as logging
from designate import utils
from designate.api.v2.controllers import rest
from designate.objects import TsigKey
from designate.objects.adapters import DesignateAdapter
LOG = logging.getLogger(__name__)
class TsigKeysController(rest.RestController):
SORT_KEYS = ['created_at', 'id', 'updated_at', 'name']
@pecan.expose(template='json:', content_type='application/json')
@utils.validate_uuid('tsigkey_id')
def get_one(self, tsigkey_id):
"""Get TsigKey"""
request = pecan.request
context = request.environ['context']
return DesignateAdapter.render(
'API_v2',
self.central_api.get_tsigkey(context, tsigkey_id),
request=request)
@pecan.expose(template='json:', content_type='application/json')
def get_all(self, **params):
"""List all TsigKeys"""
request = pecan.request
context = request.environ['context']
# Extract the pagination params
marker, limit, sort_key, sort_dir = utils.get_paging_params(
params, self.SORT_KEYS)
# Extract any filter params
accepted_filters = ('name', 'algorithm', 'scope')
criterion = self._apply_filter_params(
params, accepted_filters, {})
return DesignateAdapter.render(
'API_v2',
self.central_api.find_tsigkeys(
context, criterion, marker, limit, sort_key, sort_dir),
request=request)
@pecan.expose(template='json:', content_type='application/json')
def post_all(self):
"""Create TsigKey"""
request = pecan.request
response = pecan.response
context = request.environ['context']
body = request.body_dict<|fim▁hole|>
tsigkey.validate()
# Create the tsigkey
tsigkey = self.central_api.create_tsigkey(
context, tsigkey)
tsigkey = DesignateAdapter.render('API_v2', tsigkey, request=request)
response.headers['Location'] = tsigkey['links']['self']
response.status_int = 201
# Prepare and return the response body
return tsigkey
@pecan.expose(template='json:', content_type='application/json')
@pecan.expose(template='json:', content_type='application/json-patch+json')
@utils.validate_uuid('tsigkey_id')
def patch_one(self, tsigkey_id):
"""Update TsigKey"""
request = pecan.request
context = request.environ['context']
body = request.body_dict
response = pecan.response
if request.content_type == 'application/json-patch+json':
raise NotImplemented('json-patch not implemented')
# Fetch the existing tsigkey entry
tsigkey = self.central_api.get_tsigkey(context, tsigkey_id)
tsigkey = DesignateAdapter.parse('API_v2', body, tsigkey)
# Validate the new set of data
tsigkey.validate()
# Update and persist the resource
tsigkey = self.central_api.update_tsigkey(context, tsigkey)
response.status_int = 200
return DesignateAdapter.render('API_v2', tsigkey, request=request)
@pecan.expose(template=None, content_type='application/json')
@utils.validate_uuid('tsigkey_id')
def delete_one(self, tsigkey_id):
"""Delete TsigKey"""
request = pecan.request
response = pecan.response
context = request.environ['context']
self.central_api.delete_tsigkey(context, tsigkey_id)
response.status_int = 204
# NOTE: This is a hack and a half.. But Pecan needs it.
return ''<|fim▁end|> |
tsigkey = DesignateAdapter.parse('API_v2', body, TsigKey()) |
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>/*
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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,<|fim▁hole|>* 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.
*/
// TypeScript Version: 2.0
/**
* Returns an array of an object's own enumerable property names.
*
* ## Notes
*
* - Name order is not guaranteed, as object key enumeration is not specified according to the ECMAScript specification. In practice, however, most engines use insertion order to sort an object's keys, thus allowing for deterministic extraction.
* - If provided `null` or `undefined`, the function returns an empty array.
*
* @param value - input object
* @returns a list of own enumerable property names
*
* @example
* var obj = {
* 'beep': 'boop',
* 'foo': 3.14
* };
*
* var k = keys( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
declare function keys( value: any ): Array<string>;
// EXPORTS //
export = keys;<|fim▁end|> | |
<|file_name|>FindPhoneInterface.java<|end_file_name|><|fim▁begin|>package com.mc.phonefinder.usersettings;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.mc.phonefinder.R;
import com.mc.phonefinder.login.FindPhoneActivity;
import com.mc.phonefinder.login.SampleApplication;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.io.Serializable;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
public class FindPhoneInterface extends ActionBarActivity {
/*
For the below: check if the setting is set for the user and if so let the user use the functionality.
View location - Referes to location column in Settings table
Show Phone finder image - Displays the image of the person who find the phone
View nearby users - Refers to otherUsers in Settings table
Alert my phone - Rings the phone to easily identify it
*/
static final boolean[] nearByUserSetting = new boolean[1];
static final boolean[] locationSetting = new boolean[1];
AtomicBoolean nearByUserSetting_check = new AtomicBoolean();
AtomicBoolean locPrefs_check = new AtomicBoolean();
public static String test = "Class";
static final String TAG="bharathdebug";
public void savePrefs(String key, boolean value)
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putBoolean(key, value);
edit.commit();
}
public boolean loadBoolPrefs(String key)
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean cbVal = sp.getBoolean(key, false);
return cbVal;
}
public void savePrefs(String key, String value)
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_phone_interface);
final String ObjectId = (String)this.getIntent().getSerializableExtra("userObjectId");
nearByUserSetting[0] = false;
locationSetting[0] = false;
savePrefs("nearByUserSetting", false);
savePrefs("locationSetting", false);
Log.i(TAG,"Before inner class"+test);
// final String ObjectId = (String)this.getIntent().getSerializableExtra("userObjectId");
ParseQuery<ParseObject> getSettings = new ParseQuery<ParseObject>("Settings");
getSettings.whereEqualTo("userObjectId", ObjectId);
getSettings.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
if (objects != null) {
Log.i(TAG, "Object not null");
if(objects.size()>0){
// nearByUserSetting[0] = objects.get(0).getBoolean("otherUser");
// locationSetting[0] = objects.get(0).getBoolean("location");
// test = "Inner class";
nearByUserSetting_check.set( objects.get(0).getBoolean("otherUser"));<|fim▁hole|>//
// savePrefs("nearByUserSetting", nearByUserSetting[0]);
// savePrefs("locationSetting", locationSetting[0]);
}
}
}
});
// nearByUserSetting_check=loadBoolPrefs("nearByUserSetting");
// locPrefs_check = loadBoolPrefs("locationSetting");
//
// Log.i(TAG,"Final val after inner class "+test);
// System.out.print("Camera Setting " + nearByUserSetting[0]);
Log.i(TAG,"Near by user "+ (String.valueOf(nearByUserSetting_check.get())));
Log.i(TAG,"Location pref "+ (String.valueOf(locPrefs_check.get())));
((Button) findViewById(R.id.nearbyUsers)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(nearByUserSetting_check.get()) {
Intent i = new Intent();
savePrefs("findPhoneId", ObjectId);
Log.i(TAG, "FindPhoneInterface Object id " + ObjectId);
i.setClass(FindPhoneInterface.this, NearbyUserView.class);
//i.putExtra("userObjectId", ObjectId);
startActivity(i);
startActivity(new Intent(FindPhoneInterface.this, NearbyUserView.class));
}
else
{
Toast.makeText(FindPhoneInterface.this, "Find nearby user service not set ", Toast.LENGTH_SHORT).show();
}
}
});
((Button) findViewById(R.id.viewLocation)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(locPrefs_check.get()) {
Toast.makeText(FindPhoneInterface.this, "Getting Your Location", Toast.LENGTH_LONG)
.show();
String ObjectId = (String) FindPhoneInterface.this.getIntent().getSerializableExtra("userObjectId");
ParseQuery<ParseObject> query = ParseQuery.getQuery("Location");
if (!ObjectId.equals(null) && !ObjectId.equals("")) {
query.whereEqualTo("userId", ObjectId);
query.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
ParseGeoPoint userLocation;
for (int i = 0; i < objects.size(); i++) {
userLocation = objects.get(i).getParseGeoPoint("location");
String uri = String.format(Locale.ENGLISH, "geo:%f,%f?q=%f,%f", userLocation.getLatitude(), userLocation.getLongitude(), userLocation.getLatitude(), userLocation.getLongitude());
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:%f,%f?q=%f,%f",userLocation.getLatitude(), userLocation.getLongitude(),userLocation.getLatitude(), userLocation.getLongitude()));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
Toast.makeText(FindPhoneInterface.this, "Opening Maps", Toast.LENGTH_LONG)
.show();
}
}
});
}
}
else {
Toast.makeText(FindPhoneInterface.this, "Location Preference service not set ", Toast.LENGTH_SHORT).show();
}
}});
//Bharath - View image of person who picked phone
((Button) findViewById(R.id.btn_phonepicker)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Starts an intent of the log in activity
Log.i(TAG,"Find face object id "+ObjectId);
savePrefs("findfaceObjId",ObjectId);
startActivity(new Intent(FindPhoneInterface.this, ShowPhoneFinderImage.class));
}
});
//Change ringer alert
((Button) findViewById(R.id.triggerAlert)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Settings");
query.whereEqualTo("userObjectId", ObjectId);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> scoreList, ParseException e) {
//get current user
ParseUser user = ParseUser.getCurrentUser();
if (e == null) {
if (scoreList != null) {
if (scoreList.size() > 0) {
//store the location of the user with the objectId of the user
scoreList.get(0).put("alertPhone", true);
scoreList.get(0).saveInBackground();
Toast.makeText(FindPhoneInterface.this, "Phone Alerted", Toast.LENGTH_LONG)
.show();
}
} else {
ParseObject alertVal = new ParseObject("Settings");
alertVal.put("userObjectId", ObjectId);
alertVal.put("alertPhone", true);
scoreList.get(0).saveInBackground();
Toast.makeText(FindPhoneInterface.this, "Phone Alerted", Toast.LENGTH_LONG)
.show();
}
}
}
});
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_find_phone_interface, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}<|fim▁end|> | locPrefs_check.set(objects.get(0).getBoolean("location"));
Log.i(TAG, "Inner class neary by " + String.valueOf(nearByUserSetting_check.get()));
Log.i(TAG,"Inner class Location pref "+ (String.valueOf(locPrefs_check.get()))); |
<|file_name|>react-bootstrap-typeahead.js<|end_file_name|><|fim▁begin|>(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom'], factory) :
(global = global || self, factory(global.ReactBootstrapTypeahead = {}, global.React, global.ReactDOM));
}(this, (function (exports, React, ReactDOM) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
ReactDOM = ReactDOM && Object.prototype.hasOwnProperty.call(ReactDOM, 'default') ? ReactDOM['default'] : ReactDOM;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
}
}, fn(module, module.exports), module.exports;
}
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeMin = Math.min;
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = function() {
return root.Date.now();
};
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
result = wait - timeSinceLastCall;
return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now());
}
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
var lodash_debounce = debounce;
var reactIs_development = createCommonjsModule(function (module, exports) {
{
(function() {
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
// (unstable) APIs that have been removed. Can we remove the symbols?
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;
var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
function isValidElementType(type) {
return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
}
function typeOf(object) {
if (typeof object === 'object' && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_ASYNC_MODE_TYPE:
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return undefined;
} // AsyncMode is deprecated along with isAsyncMode
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint
console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
exports.AsyncMode = AsyncMode;
exports.ConcurrentMode = ConcurrentMode;
exports.ContextConsumer = ContextConsumer;
exports.ContextProvider = ContextProvider;
exports.Element = Element;
exports.ForwardRef = ForwardRef;
exports.Fragment = Fragment;
exports.Lazy = Lazy;
exports.Memo = Memo;
exports.Portal = Portal;
exports.Profiler = Profiler;
exports.StrictMode = StrictMode;
exports.Suspense = Suspense;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement;
exports.isForwardRef = isForwardRef;
exports.isFragment = isFragment;
exports.isLazy = isLazy;
exports.isMemo = isMemo;
exports.isPortal = isPortal;
exports.isProfiler = isProfiler;
exports.isStrictMode = isStrictMode;
exports.isSuspense = isSuspense;
exports.isValidElementType = isValidElementType;
exports.typeOf = typeOf;
})();
}
});
var reactIs_development_1 = reactIs_development.AsyncMode;
var reactIs_development_2 = reactIs_development.ConcurrentMode;
var reactIs_development_3 = reactIs_development.ContextConsumer;
var reactIs_development_4 = reactIs_development.ContextProvider;
var reactIs_development_5 = reactIs_development.Element;
var reactIs_development_6 = reactIs_development.ForwardRef;
var reactIs_development_7 = reactIs_development.Fragment;
var reactIs_development_8 = reactIs_development.Lazy;
var reactIs_development_9 = reactIs_development.Memo;
var reactIs_development_10 = reactIs_development.Portal;
var reactIs_development_11 = reactIs_development.Profiler;
var reactIs_development_12 = reactIs_development.StrictMode;
var reactIs_development_13 = reactIs_development.Suspense;
var reactIs_development_14 = reactIs_development.isAsyncMode;
var reactIs_development_15 = reactIs_development.isConcurrentMode;
var reactIs_development_16 = reactIs_development.isContextConsumer;
var reactIs_development_17 = reactIs_development.isContextProvider;
var reactIs_development_18 = reactIs_development.isElement;
var reactIs_development_19 = reactIs_development.isForwardRef;
var reactIs_development_20 = reactIs_development.isFragment;
var reactIs_development_21 = reactIs_development.isLazy;
var reactIs_development_22 = reactIs_development.isMemo;
var reactIs_development_23 = reactIs_development.isPortal;
var reactIs_development_24 = reactIs_development.isProfiler;
var reactIs_development_25 = reactIs_development.isStrictMode;
var reactIs_development_26 = reactIs_development.isSuspense;
var reactIs_development_27 = reactIs_development.isValidElementType;
var reactIs_development_28 = reactIs_development.typeOf;
var reactIs = createCommonjsModule(function (module) {
{
module.exports = reactIs_development;
}
});
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
var printWarning = function() {};
{
var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
var loggedTypeFailures = {};
var has = Function.call.bind(Object.prototype.hasOwnProperty);
printWarning = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
{
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
var err = Error(
(componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
);
err.name = 'Invariant Violation';
throw err;
}
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
} catch (ex) {
error = ex;
}
if (error && !(error instanceof Error)) {
printWarning(
(componentName || 'React class') + ': type specification of ' +
location + ' `' + typeSpecName + '` is invalid; the type checker ' +
'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
'You may have forgotten to pass an argument to the type checker ' +
'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
'shape all require an argument).'
);
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
printWarning(
'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
);
}
}
}
}
}
/**
* Resets warning cache when testing.
*
* @private
*/
checkPropTypes.resetWarningCache = function() {
{
loggedTypeFailures = {};
}
};
var checkPropTypes_1 = checkPropTypes;
var has$1 = Function.call.bind(Object.prototype.hasOwnProperty);
var printWarning$1 = function() {};
{
printWarning$1 = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
}
function emptyFunctionThatReturnsNull() {
return null;
}
var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
elementType: createElementTypeTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
exact: createStrictShapeTypeChecker,
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
{
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret_1) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use `PropTypes.checkPropTypes()` to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
} else if ( typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (
!manualPropTypeCallCache[cacheKey] &&
// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3
) {
printWarning$1(
'You are manually calling a React.PropTypes validation ' +
'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunctionThatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!reactIs.isValidElementType(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
{
if (arguments.length > 1) {
printWarning$1(
'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' +
'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'
);
} else {
printWarning$1('Invalid argument supplied to oneOf, expected an array.');
}
}
return emptyFunctionThatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
var type = getPreciseType(value);
if (type === 'symbol') {
return String(value);
}
return value;
});
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (has$1(propValue, key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
printWarning$1('Invalid argument supplied to oneOfType, expected an instance of array.') ;
return emptyFunctionThatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
printWarning$1(
'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'
);
return emptyFunctionThatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
// We need to check all keys in case some are required but missing from
// props.
var allKeys = objectAssign({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (!checker) {
return new PropTypeError(
'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
'\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
'\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
);
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// falsy value can't be a Symbol
if (!propValue) {
return false;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
if (typeof propValue === 'undefined' || propValue === null) {
return '' + propValue;
}
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case 'array':
case 'object':
return 'an ' + type;
case 'boolean':
case 'date':
case 'regexp':
return 'a ' + type;
default:
return type;
}
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes_1;
ReactPropTypes.resetWarningCache = checkPropTypes_1.resetWarningCache;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
var propTypes = createCommonjsModule(function (module) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
var ReactIs = reactIs;
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = factoryWithTypeCheckers(ReactIs.isElement, throwOnDirectAccess);
}
});
/**
* Returns a function that triggers a component update. the hook equivalent to
* `this.forceUpdate()` in a class component. In most cases using a state value directly
* is preferable but may be required in some advanced usages of refs for interop or
* when direct DOM manipulation is required.
*
* ```ts
* const forceUpdate = useForceUpdate();
*
* const updateOnClick = useCallback(() => {
* forceUpdate()
* }, [forceUpdate])
*
* return <button type="button" onClick={updateOnClick}>Hi there</button>
* ```
*/
function useForceUpdate() {
// The toggling state value is designed to defeat React optimizations for skipping
// updates when they are stricting equal to the last state value
var _useReducer = React.useReducer(function (state) {
return !state;
}, false),
dispatch = _useReducer[1];
return dispatch;
}
/**
* Store the last of some value. Tracked via a `Ref` only updating it
* after the component renders.
*
* Helpful if you need to compare a prop value to it's previous value during render.
*
* ```ts
* function Component(props) {
* const lastProps = usePrevious(props)
*
* if (lastProps.foo !== props.foo)
* resetValueFromProps(props.foo)
* }
* ```
*
* @param value the value to track
*/
function usePrevious(value) {
var ref = React.useRef(null);
React.useEffect(function () {
ref.current = value;
});
return ref.current;
}
// do not edit .js files directly - edit src/index.jst
var fastDeepEqual = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
// true if both NaN, false otherwise
return a!==a && b!==b;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
{
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
var invariant_1 = invariant;
/**
* Common (non-printable) keycodes for `keydown` and `keyup` events. Note that
* `keypress` handles things differently and may not return the same values.
*/
var BACKSPACE = 8;
var TAB = 9;
var RETURN = 13;
var ESC = 27;
var UP = 38;
var RIGHT = 39;
var DOWN = 40;
var DEFAULT_LABELKEY = 'label';
var ALIGN = {
JUSTIFY: 'justify',
LEFT: 'left',
RIGHT: 'right'
};
var SIZE = {
LARGE: 'large',
LG: 'lg',
SM: 'sm',
SMALL: 'small'
};
function getStringLabelKey(labelKey) {
return typeof labelKey === 'string' ? labelKey : DEFAULT_LABELKEY;
}
var idCounter = 0;
function head(arr) {
return Array.isArray(arr) && arr.length ? arr[0] : undefined;
}
function isFunction(value) {
return typeof value === 'function';
}
function isString(value) {
return typeof value === 'string';
}
function noop() {}
function pick(obj, keys) {
var result = {};
keys.forEach(function (k) {
if (Object.prototype.hasOwnProperty.call(obj, k)) {
result[k] = obj[k];
}
});
return result;
}
function uniqueId(prefix) {
idCounter += 1;
return (prefix == null ? '' : String(prefix)) + idCounter;
} // Export for testing purposes.
function valuesPolyfill(obj) {
return Object.keys(obj).reduce(function (accum, key) {
if (Object.prototype.propertyIsEnumerable.call(obj, key)) {
accum.push(obj[key]);
}
return accum;
}, []);
}
function values(obj) {
return isFunction(Object.values) ? Object.values(obj) : valuesPolyfill(obj);
}
/**
* Retrieves the display string from an option. Options can be the string
* themselves, or an object with a defined display string. Anything else throws
* an error.
*/
function getOptionLabel(option, labelKey) {
// Handle internally created options first.
if (!isString(option) && (option.paginationOption || option.customOption)) {
return option[getStringLabelKey(labelKey)];
}
var optionLabel;
if (isFunction(labelKey)) {
optionLabel = labelKey(option);
} else if (isString(option)) {
optionLabel = option;
} else {
// `option` is an object and `labelKey` is a string.
optionLabel = option[labelKey];
}
!isString(optionLabel) ? invariant_1(false, 'One or more options does not have a valid label string. Check the ' + '`labelKey` prop to ensure that it matches the correct option key and ' + 'provides a string for filtering and display.') : void 0;
return optionLabel;
}
function addCustomOption(results, props) {
var allowNew = props.allowNew,
labelKey = props.labelKey,
text = props.text;
if (!allowNew || !text.trim()) {
return false;
} // If the consumer has provided a callback, use that to determine whether or
// not to add the custom option.
if (typeof allowNew === 'function') {
return allowNew(results, props);
} // By default, don't add the custom option if there is an exact text match
// with an existing option.
return !results.some(function (o) {
return getOptionLabel(o, labelKey) === text;
});
}
function getOptionProperty(option, key) {
if (isString(option)) {
return undefined;
}
return option[key];
}
/**
* 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.
*
* Taken from: http://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript/18391901#18391901
*/
/* eslint-disable max-len */
var map = [{
base: 'A',
letters: "A\u24B6\uFF21\xC0\xC1\xC2\u1EA6\u1EA4\u1EAA\u1EA8\xC3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\xC4\u01DE\u1EA2\xC5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F"
}, {
base: 'AA',
letters: "\uA732"
}, {
base: 'AE',
letters: "\xC6\u01FC\u01E2"
}, {
base: 'AO',
letters: "\uA734"
}, {
base: 'AU',
letters: "\uA736"
}, {
base: 'AV',
letters: "\uA738\uA73A"
}, {
base: 'AY',
letters: "\uA73C"
}, {
base: 'B',
letters: "B\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181"
}, {
base: 'C',
letters: "C\u24B8\uFF23\u0106\u0108\u010A\u010C\xC7\u1E08\u0187\u023B\uA73E"
}, {
base: 'D',
letters: "D\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779\xD0"
}, {
base: 'DZ',
letters: "\u01F1\u01C4"
}, {
base: 'Dz',
letters: "\u01F2\u01C5"
}, {
base: 'E',
letters: "E\u24BA\uFF25\xC8\xC9\xCA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\xCB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E"
}, {
base: 'F',
letters: "F\u24BB\uFF26\u1E1E\u0191\uA77B"
}, {
base: 'G',
letters: "G\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E"
}, {
base: 'H',
letters: "H\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D"
}, {
base: 'I',
letters: "I\u24BE\uFF29\xCC\xCD\xCE\u0128\u012A\u012C\u0130\xCF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197"
}, {
base: 'J',
letters: "J\u24BF\uFF2A\u0134\u0248"
}, {
base: 'K',
letters: "K\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2"
}, {
base: 'L',
letters: "L\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780"
}, {
base: 'LJ',
letters: "\u01C7"
}, {
base: 'Lj',
letters: "\u01C8"
}, {
base: 'M',
letters: "M\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C"
}, {
base: 'N',
letters: "N\u24C3\uFF2E\u01F8\u0143\xD1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4"
}, {
base: 'NJ',
letters: "\u01CA"
}, {
base: 'Nj',
letters: "\u01CB"
}, {
base: 'O',
letters: "O\u24C4\uFF2F\xD2\xD3\xD4\u1ED2\u1ED0\u1ED6\u1ED4\xD5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\xD6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\xD8\u01FE\u0186\u019F\uA74A\uA74C"
}, {
base: 'OI',
letters: "\u01A2"
}, {
base: 'OO',
letters: "\uA74E"
}, {
base: 'OU',
letters: "\u0222"
}, {
base: 'OE',
letters: "\x8C\u0152"
}, {
base: 'oe',
letters: "\x9C\u0153"
}, {
base: 'P',
letters: "P\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754"
}, {
base: 'Q',
letters: "Q\u24C6\uFF31\uA756\uA758\u024A"
}, {
base: 'R',
letters: "R\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782"
}, {
base: 'S',
letters: "S\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784"
}, {
base: 'T',
letters: "T\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786"
}, {
base: 'TZ',
letters: "\uA728"
}, {
base: 'U',
letters: "U\u24CA\uFF35\xD9\xDA\xDB\u0168\u1E78\u016A\u1E7A\u016C\xDC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244"
}, {
base: 'V',
letters: "V\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245"
}, {
base: 'VY',
letters: "\uA760"
}, {
base: 'W',
letters: "W\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72"
}, {
base: 'X',
letters: "X\u24CD\uFF38\u1E8A\u1E8C"
}, {
base: 'Y',
letters: "Y\u24CE\uFF39\u1EF2\xDD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE"
}, {
base: 'Z',
letters: "Z\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762"
}, {
base: 'a',
letters: "a\u24D0\uFF41\u1E9A\xE0\xE1\xE2\u1EA7\u1EA5\u1EAB\u1EA9\xE3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\xE4\u01DF\u1EA3\xE5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250"
}, {
base: 'aa',
letters: "\uA733"
}, {
base: 'ae',
letters: "\xE6\u01FD\u01E3"
}, {
base: 'ao',
letters: "\uA735"
}, {
base: 'au',
letters: "\uA737"
}, {
base: 'av',
letters: "\uA739\uA73B"
}, {
base: 'ay',
letters: "\uA73D"
}, {
base: 'b',
letters: "b\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253"
}, {
base: 'c',
letters: "c\u24D2\uFF43\u0107\u0109\u010B\u010D\xE7\u1E09\u0188\u023C\uA73F\u2184"
}, {
base: 'd',
letters: "d\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A"
}, {
base: 'dz',
letters: "\u01F3\u01C6"
}, {
base: 'e',
letters: "e\u24D4\uFF45\xE8\xE9\xEA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\xEB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD"
}, {
base: 'f',
letters: "f\u24D5\uFF46\u1E1F\u0192\uA77C"
}, {
base: 'g',
letters: "g\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F"
}, {
base: 'h',
letters: "h\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265"
}, {
base: 'hv',
letters: "\u0195"
}, {
base: 'i',
letters: "i\u24D8\uFF49\xEC\xED\xEE\u0129\u012B\u012D\xEF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131"
}, {
base: 'j',
letters: "j\u24D9\uFF4A\u0135\u01F0\u0249"
}, {
base: 'k',
letters: "k\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3"
}, {
base: 'l',
letters: "l\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747"
}, {
base: 'lj',
letters: "\u01C9"
}, {
base: 'm',
letters: "m\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F"
}, {
base: 'n',
letters: "n\u24DD\uFF4E\u01F9\u0144\xF1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5"
}, {
base: 'nj',
letters: "\u01CC"
}, {
base: 'o',
letters: "o\u24DE\uFF4F\xF2\xF3\xF4\u1ED3\u1ED1\u1ED7\u1ED5\xF5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\xF6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\xF8\u01FF\u0254\uA74B\uA74D\u0275"
}, {
base: 'oi',
letters: "\u01A3"
}, {
base: 'ou',
letters: "\u0223"
}, {
base: 'oo',
letters: "\uA74F"
}, {
base: 'p',
letters: "p\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755"
}, {
base: 'q',
letters: "q\u24E0\uFF51\u024B\uA757\uA759"
}, {
base: 'r',
letters: "r\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783"
}, {
base: 's',
letters: "s\u24E2\uFF53\xDF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B"
}, {
base: 't',
letters: "t\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787"
}, {
base: 'tz',
letters: "\uA729"
}, {
base: 'u',
letters: "u\u24E4\uFF55\xF9\xFA\xFB\u0169\u1E79\u016B\u1E7B\u016D\xFC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289"
}, {
base: 'v',
letters: "v\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C"
}, {
base: 'vy',
letters: "\uA761"
}, {
base: 'w',
letters: "w\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73"
}, {
base: 'x',
letters: "x\u24E7\uFF58\u1E8B\u1E8D"
}, {
base: 'y',
letters: "y\u24E8\uFF59\u1EF3\xFD\u0177\u1EF9\u0233\u1E8F\xFF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF"
}, {
base: 'z',
letters: "z\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763"
}];
/* eslint-enable max-len */
var diacriticsMap = {};
for (var ii = 0; ii < map.length; ii++) {
var letters = map[ii].letters;
for (var jj = 0; jj < letters.length; jj++) {
diacriticsMap[letters[jj]] = map[ii].base;
}
} // "what?" version ... http://jsperf.com/diacritics/12
function stripDiacritics(str) {
return str.replace(/[\u0300-\u036F]/g, '') // Remove combining diacritics
/* eslint-disable-next-line no-control-regex */
.replace(/[^\u0000-\u007E]/g, function (a) {
return diacriticsMap[a] || a;
});
}
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var warning = function() {};
{
var printWarning$2 = function printWarning(format, args) {
var len = arguments.length;
args = new Array(len > 1 ? len - 1 : 0);
for (var key = 1; key < len; key++) {
args[key - 1] = arguments[key];
}
var argIndex = 0;
var message = 'Warning: ' +
format.replace(/%s/g, function() {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function(condition, format, args) {
var len = arguments.length;
args = new Array(len > 2 ? len - 2 : 0);
for (var key = 2; key < len; key++) {
args[key - 2] = arguments[key];
}
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (!condition) {
printWarning$2.apply(null, [format].concat(args));
}
};
}
var warning_1 = warning;
var warned = {};
/**
* Copied from: https://github.com/ReactTraining/react-router/blob/master/modules/routerWarning.js
*/
function warn(falseToWarn, message) {
// Only issue deprecation warnings once.
if (!falseToWarn && message.indexOf('deprecated') !== -1) {
if (warned[message]) {
return;
}
warned[message] = true;
}
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
warning_1.apply(void 0, [falseToWarn, "[react-bootstrap-typeahead] " + message].concat(args));
}
function isMatch(input, string, props) {
var searchStr = input;
var str = string;
if (!props.caseSensitive) {
searchStr = searchStr.toLowerCase();
str = str.toLowerCase();
}
if (props.ignoreDiacritics) {
searchStr = stripDiacritics(searchStr);
str = stripDiacritics(str);
}
return str.indexOf(searchStr) !== -1;
}
/**
* Default algorithm for filtering results.
*/
function defaultFilterBy(option, props) {
var filterBy = props.filterBy,
labelKey = props.labelKey,
multiple = props.multiple,
selected = props.selected,
text = props.text; // Don't show selected options in the menu for the multi-select case.
if (multiple && selected.some(function (o) {
return fastDeepEqual(o, option);
})) {
return false;
}
if (isFunction(labelKey) && isMatch(text, labelKey(option), props)) {
return true;
}
var fields = filterBy.slice();
if (isString(labelKey)) {
// Add the `labelKey` field to the list of fields if it isn't already there.
if (fields.indexOf(labelKey) === -1) {
fields.unshift(labelKey);
}
}
if (isString(option)) {
warn(fields.length <= 1, 'You cannot filter by properties when `option` is a string.');
return isMatch(text, option, props);
}
return fields.some(function (field) {
var value = getOptionProperty(option, field);
if (!isString(value)) {
warn(false, 'Fields passed to `filterBy` should have string values. Value will ' + 'be converted to a string; results may be unexpected.');
value = String(value);
}
return isMatch(text, value, props);
});
}
function getDisplayName(Component) {
return Component.displayName || Component.name || 'Component';
}
var CASE_INSENSITIVE = 'i';
var COMBINING_MARKS = /[\u0300-\u036F]/;
// Export for testing.
function escapeStringRegexp(str) {
!(typeof str === 'string') ? invariant_1(false, '`escapeStringRegexp` expected a string.') : void 0; // Escape characters with special meaning either inside or outside character
// sets. Use a simple backslash escape when it’s always valid, and a \unnnn
// escape when the simpler form would be disallowed by Unicode patterns’
// stricter grammar.
return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
}
function getMatchBounds(subject, str) {
var search = new RegExp(escapeStringRegexp(stripDiacritics(str)), CASE_INSENSITIVE);
var matches = search.exec(stripDiacritics(subject));
if (!matches) {
return null;
}
var start = matches.index;
var matchLength = matches[0].length; // Account for combining marks, which changes the indices.
if (COMBINING_MARKS.test(subject)) {
// Starting at the beginning of the subject string, check for the number of
// combining marks and increment the start index whenever one is found.
for (var ii = 0; ii <= start; ii++) {
if (COMBINING_MARKS.test(subject[ii])) {
start += 1;
}
} // Similarly, increment the length of the match string if it contains a
// combining mark.
for (var _ii = start; _ii <= start + matchLength; _ii++) {
if (COMBINING_MARKS.test(subject[_ii])) {
matchLength += 1;
}
}
}
return {
end: start + matchLength,
start: start
};
}
function getHintText(props) {
var activeIndex = props.activeIndex,
initialItem = props.initialItem,
isFocused = props.isFocused,
isMenuShown = props.isMenuShown,
labelKey = props.labelKey,
multiple = props.multiple,
selected = props.selected,
text = props.text; // Don't display a hint under the following conditions:
if ( // No text entered.
!text || // The input is not focused.
!isFocused || // The menu is hidden.
!isMenuShown || // No item in the menu.
!initialItem || // The initial item is a custom option.
initialItem.customOption || // One of the menu items is active.
activeIndex > -1 || // There's already a selection in single-select mode.
!!selected.length && !multiple) {
return '';
}
var initialItemStr = getOptionLabel(initialItem, labelKey);
var bounds = getMatchBounds(initialItemStr.toLowerCase(), text.toLowerCase());
if (!(bounds && bounds.start === 0)) {
return '';
} // Text matching is case- and accent-insensitive, so to display the hint
// correctly, splice the input string with the hint string.
return text + initialItemStr.slice(bounds.end, initialItemStr.length);
}
var classnames = createCommonjsModule(function (module) {
/*!
Copyright (c) 2017 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg) && arg.length) {
var inner = classNames.apply(null, arg);
if (inner) {
classes.push(inner);
}
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if ( module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else {
window.classNames = classNames;
}
}());
});
function getMenuItemId(id, position) {
return (id || '') + "-item-" + position;
}
var getInputProps = function getInputProps(_ref) {
var activeIndex = _ref.activeIndex,
id = _ref.id,
isFocused = _ref.isFocused,
isMenuShown = _ref.isMenuShown,
multiple = _ref.multiple,
onFocus = _ref.onFocus,
placeholder = _ref.placeholder,
rest = _objectWithoutPropertiesLoose(_ref, ["activeIndex", "id", "isFocused", "isMenuShown", "multiple", "onFocus", "placeholder"]);
return function (_temp) {
var _cx;
var _ref2 = _temp === void 0 ? {} : _temp,
className = _ref2.className,
inputProps = _objectWithoutPropertiesLoose(_ref2, ["className"]);
var props = _extends({
/* eslint-disable sort-keys */
// These props can be overridden by values in `inputProps`.
autoComplete: 'off',
placeholder: placeholder,
type: 'text'
}, inputProps, rest, {
'aria-activedescendant': activeIndex >= 0 ? getMenuItemId(id, activeIndex) : undefined,
'aria-autocomplete': 'both',
'aria-expanded': isMenuShown,
'aria-haspopup': 'listbox',
'aria-owns': isMenuShown ? id : undefined,
className: classnames((_cx = {}, _cx[className || ''] = !multiple, _cx.focus = isFocused, _cx)),
// Re-open the menu, eg: if it's closed via ESC.
onClick: onFocus,
onFocus: onFocus,
// Comboboxes are single-select by definition:
// https://www.w3.org/TR/wai-aria-practices-1.1/#combobox
role: 'combobox'
/* eslint-enable sort-keys */
});
if (!multiple) {
return props;
}
return _extends({}, props, {
'aria-autocomplete': 'list',
'aria-expanded': undefined,
inputClassName: className,
role: undefined
});
};
};
function getInputText(props) {
var activeItem = props.activeItem,
labelKey = props.labelKey,
multiple = props.multiple,
selected = props.selected,
text = props.text;
if (activeItem) {
// Display the input value if the pagination item is active.
return getOptionLabel(activeItem, labelKey);
}
var selectedItem = !multiple && !!selected.length && head(selected);
if (selectedItem) {
return getOptionLabel(selectedItem, labelKey);
}
return text;
}
function getIsOnlyResult(props) {
var allowNew = props.allowNew,
highlightOnlyResult = props.highlightOnlyResult,
results = props.results;
if (!highlightOnlyResult || allowNew) {
return false;
}
return results.length === 1 && !getOptionProperty(head(results), 'disabled');
}
/**
* Truncates the result set based on `maxResults` and returns the new set.
*/
function getTruncatedOptions(options, maxResults) {
if (!maxResults || maxResults >= options.length) {
return options;
}
return options.slice(0, maxResults);
}
function skipDisabledOptions(currentIndex, keyCode, items) {
var newIndex = currentIndex;
while (items[newIndex] && items[newIndex].disabled) {
newIndex += keyCode === UP ? -1 : 1;
}
return newIndex;
}
function getUpdatedActiveIndex(currentIndex, keyCode, items) {
var newIndex = currentIndex; // Increment or decrement index based on user keystroke.
newIndex += keyCode === UP ? -1 : 1; // Skip over any disabled options.
newIndex = skipDisabledOptions(newIndex, keyCode, items); // If we've reached the end, go back to the beginning or vice-versa.
if (newIndex === items.length) {
newIndex = -1;
} else if (newIndex === -2) {
newIndex = items.length - 1; // Skip over any disabled options.
newIndex = skipDisabledOptions(newIndex, keyCode, items);
}
return newIndex;
}
/**
* Check if an input type is selectable, based on WHATWG spec.
*
* See:
* - https://stackoverflow.com/questions/21177489/selectionstart-selectionend-on-input-type-number-no-longer-allowed-in-chrome/24175357
* - https://html.spec.whatwg.org/multipage/input.html#do-not-apply
*/
function isSelectable(inputNode) {
return inputNode.selectionStart != null;
}
function isShown(props) {
var open = props.open,
minLength = props.minLength,
showMenu = props.showMenu,
text = props.text; // If menu visibility is controlled via props, that value takes precedence.
if (open || open === false) {
return open;
}
if (text.length < minLength) {
return false;
}
return showMenu;
}
/**
* Prevent the main input from blurring when a menu item or the clear button is
* clicked. (#226 & #310)
*/
function preventInputBlur(e) {
e.preventDefault();
}
function isSizeLarge(size) {
return size === 'large' || size === 'lg';
}
function isSizeSmall(size) {
return size === 'small' || size === 'sm';
}
function validateSelectedPropChange(prevSelected, selected) {
var uncontrolledToControlled = !prevSelected && selected;
var controlledToUncontrolled = prevSelected && !selected;
var from, to, precedent;
if (uncontrolledToControlled) {
from = 'uncontrolled';
to = 'controlled';
precedent = 'an';
} else {
from = 'controlled';
to = 'uncontrolled';
precedent = 'a';
}
var message = "You are changing " + precedent + " " + from + " typeahead to be " + to + ". " + ("Input elements should not switch from " + from + " to " + to + " (or vice versa). ") + 'Decide between using a controlled or uncontrolled element for the ' + 'lifetime of the component.';
warn(!(uncontrolledToControlled || controlledToUncontrolled), message);
}
var TypeaheadContext = React.createContext({
activeIndex: -1,
hintText: '',
id: '',
initialItem: null,
inputNode: null,
isOnlyResult: false,
onActiveItemChange: noop,
onAdd: noop,
onInitialItemChange: noop,
onMenuItemClick: noop,
selectHintOnEnter: undefined,
setItem: noop
});
var useTypeaheadContext = function useTypeaheadContext() {
return React.useContext(TypeaheadContext);
};
var inputPropKeys = ['activeIndex', 'disabled', 'id', 'inputRef', 'isFocused', 'isMenuShown', 'multiple', 'onBlur', 'onChange', 'onFocus', 'onKeyDown', 'placeholder'];
var propKeys = ['activeIndex', 'hideMenu', 'isMenuShown', 'labelKey', 'onClear', 'onHide', 'onRemove', 'results', 'selected', 'text', 'toggleMenu'];
var contextKeys = ['activeIndex', 'id', 'initialItem', 'inputNode', 'onActiveItemChange', 'onAdd', 'onInitialItemChange', 'onMenuItemClick', 'selectHintOnEnter', 'setItem'];
var TypeaheadManager = function TypeaheadManager(props) {
var allowNew = props.allowNew,
children = props.children,
initialItem = props.initialItem,
isMenuShown = props.isMenuShown,
onAdd = props.onAdd,
onInitialItemChange = props.onInitialItemChange,
onKeyDown = props.onKeyDown,
onMenuToggle = props.onMenuToggle,
results = props.results;
var prevProps = usePrevious(props);
React.useEffect(function () {
// Clear the initial item when there are no results.
if (!(allowNew || results.length)) {
onInitialItemChange(null);
}
});
React.useEffect(function () {
if (prevProps && prevProps.isMenuShown !== isMenuShown) {
onMenuToggle(isMenuShown);
}
});
var handleKeyDown = function handleKeyDown(e) {
switch (e.keyCode) {
case RETURN:
if (initialItem && getIsOnlyResult(props)) {
onAdd(initialItem);
}
break;
}
onKeyDown(e);
};
var childProps = _extends({}, pick(props, propKeys), {
getInputProps: getInputProps(_extends({}, pick(props, inputPropKeys), {
onKeyDown: handleKeyDown,
value: getInputText(props)
}))
});
var contextValue = _extends({}, pick(props, contextKeys), {
hintText: getHintText(props),
isOnlyResult: getIsOnlyResult(props)
});
return /*#__PURE__*/React__default.createElement(TypeaheadContext.Provider, {
value: contextValue
}, children(childProps));
};
var INPUT_PROPS_BLACKLIST = [{
alt: 'onBlur',
prop: 'onBlur'
}, {
alt: 'onInputChange',
prop: 'onChange'
}, {
alt: 'onFocus',
prop: 'onFocus'
}, {
alt: 'onKeyDown',
prop: 'onKeyDown'
}];
var sizeType = propTypes.oneOf(values(SIZE));
/**
* Allows additional warnings or messaging related to prop validation.
*/
function checkPropType(validator, callback) {
return function (props, propName, componentName) {
var _PropTypes$checkPropT;
propTypes.checkPropTypes((_PropTypes$checkPropT = {}, _PropTypes$checkPropT[propName] = validator, _PropTypes$checkPropT), props, 'prop', componentName);
isFunction(callback) && callback(props, propName, componentName);
};
}
function caseSensitiveType(props, propName, componentName) {
var caseSensitive = props.caseSensitive,
filterBy = props.filterBy;
warn(!caseSensitive || typeof filterBy !== 'function', 'Your `filterBy` function will override the `caseSensitive` prop.');
}
function deprecated(validator, reason) {
return function (props, propName, componentName) {
var _PropTypes$checkPropT2;
if (props[propName] != null) {
warn(false, "The `" + propName + "` prop is deprecated. " + reason);
}
return propTypes.checkPropTypes((_PropTypes$checkPropT2 = {}, _PropTypes$checkPropT2[propName] = validator, _PropTypes$checkPropT2), props, 'prop', componentName);
};
}
function defaultInputValueType(props, propName, componentName) {
var defaultInputValue = props.defaultInputValue,
defaultSelected = props.defaultSelected,
multiple = props.multiple,
selected = props.selected;
var name = defaultSelected.length ? 'defaultSelected' : 'selected';
warn(!(!multiple && defaultInputValue && (defaultSelected.length || selected && selected.length)), "`defaultInputValue` will be overridden by the value from `" + name + "`.");
}
function defaultSelectedType(props, propName, componentName) {
var defaultSelected = props.defaultSelected,
multiple = props.multiple;
warn(multiple || defaultSelected.length <= 1, 'You are passing multiple options to the `defaultSelected` prop of a ' + 'Typeahead in single-select mode. The selections will be truncated to a ' + 'single selection.');
}
function highlightOnlyResultType(props, propName, componentName) {
var allowNew = props.allowNew,
highlightOnlyResult = props.highlightOnlyResult;
warn(!(highlightOnlyResult && allowNew), '`highlightOnlyResult` will not work with `allowNew`.');
}
function ignoreDiacriticsType(props, propName, componentName) {
var filterBy = props.filterBy,
ignoreDiacritics = props.ignoreDiacritics;
warn(ignoreDiacritics || typeof filterBy !== 'function', 'Your `filterBy` function will override the `ignoreDiacritics` prop.');
}
function inputPropsType(props, propName, componentName) {
var inputProps = props.inputProps;
if (!(inputProps && Object.prototype.toString.call(inputProps) === '[object Object]')) {
return;
} // Blacklisted properties.
INPUT_PROPS_BLACKLIST.forEach(function (_ref) {
var alt = _ref.alt,
prop = _ref.prop;
var msg = alt ? " Use the top-level `" + alt + "` prop instead." : null;
warn(!inputProps[prop], "The `" + prop + "` property of `inputProps` will be ignored." + msg);
});
}
function isRequiredForA11y(props, propName, componentName) {
warn(props[propName] != null, "The prop `" + propName + "` is required to make `" + componentName + "` " + 'accessible for users of assistive technologies such as screen readers.');
}
function labelKeyType(props, propName, componentName) {
var allowNew = props.allowNew,
labelKey = props.labelKey;
warn(!(isFunction(labelKey) && allowNew), '`labelKey` must be a string when `allowNew={true}`.');
}
var optionType = propTypes.oneOfType([propTypes.object, propTypes.string]);
function selectedType(props, propName, componentName) {
var multiple = props.multiple,
onChange = props.onChange,
selected = props.selected;
warn(multiple || !selected || selected.length <= 1, 'You are passing multiple options to the `selected` prop of a Typeahead ' + 'in single-select mode. This may lead to unexpected behaviors or errors.');
warn(!selected || selected && isFunction(onChange), 'You provided a `selected` prop without an `onChange` handler. If you ' + 'want the typeahead to be uncontrolled, use `defaultSelected`. ' + 'Otherwise, set `onChange`.');
}
var propTypes$1 = {
/**
* Allows the creation of new selections on the fly. Note that any new items
* will be added to the list of selections, but not the list of original
* options unless handled as such by `Typeahead`'s parent.
*
* If a function is specified, it will be used to determine whether a custom
* option should be included. The return value should be true or false.
*/
allowNew: propTypes.oneOfType([propTypes.bool, propTypes.func]),
/**
* Autofocus the input when the component initially mounts.
*/
autoFocus: propTypes.bool,
/**
* Whether or not filtering should be case-sensitive.
*/
caseSensitive: checkPropType(propTypes.bool, caseSensitiveType),
/**
* The initial value displayed in the text input.
*/
defaultInputValue: checkPropType(propTypes.string, defaultInputValueType),
/**
* Whether or not the menu is displayed upon initial render.
*/
defaultOpen: propTypes.bool,
/**
* Specify any pre-selected options. Use only if you want the component to
* be uncontrolled.
*/
defaultSelected: checkPropType(propTypes.arrayOf(optionType), defaultSelectedType),
/**
* Either an array of fields in `option` to search, or a custom filtering
* callback.
*/
filterBy: propTypes.oneOfType([propTypes.arrayOf(propTypes.string.isRequired), propTypes.func]),
/**
* Highlights the menu item if there is only one result and allows selecting
* that item by hitting enter. Does not work with `allowNew`.
*/
highlightOnlyResult: checkPropType(propTypes.bool, highlightOnlyResultType),
/**
* An html id attribute, required for assistive technologies such as screen
* readers.
*/
id: checkPropType(propTypes.oneOfType([propTypes.number, propTypes.string]), isRequiredForA11y),
/**
* Whether the filter should ignore accents and other diacritical marks.
*/
ignoreDiacritics: checkPropType(propTypes.bool, ignoreDiacriticsType),
/**
* Specify the option key to use for display or a function returning the
* display string. By default, the selector will use the `label` key.
*/
labelKey: checkPropType(propTypes.oneOfType([propTypes.string, propTypes.func]), labelKeyType),
/**
* Maximum number of results to display by default. Mostly done for
* performance reasons so as not to render too many DOM nodes in the case of
* large data sets.
*/
maxResults: propTypes.number,
/**
* Number of input characters that must be entered before showing results.
*/
minLength: propTypes.number,
/**
* Whether or not multiple selections are allowed.
*/
multiple: propTypes.bool,
/**
* Invoked when the input is blurred. Receives an event.
*/
onBlur: propTypes.func,
/**
* Invoked whenever items are added or removed. Receives an array of the
* selected options.
*/
onChange: propTypes.func,
/**
* Invoked when the input is focused. Receives an event.
*/
onFocus: propTypes.func,
/**
* Invoked when the input value changes. Receives the string value of the
* input.
*/
onInputChange: propTypes.func,
/**
* Invoked when a key is pressed. Receives an event.
*/
onKeyDown: propTypes.func,
/**
* Invoked when menu visibility changes.
*/
onMenuToggle: propTypes.func,
/**
* Invoked when the pagination menu item is clicked. Receives an event.
*/
onPaginate: propTypes.func,
/**
* Whether or not the menu should be displayed. `undefined` allows the
* component to control visibility, while `true` and `false` show and hide
* the menu, respectively.
*/
open: propTypes.bool,
/**
* Full set of options, including pre-selected options. Must either be an
* array of objects (recommended) or strings.
*/
options: propTypes.arrayOf(optionType).isRequired,
/**
* Give user the ability to display additional results if the number of
* results exceeds `maxResults`.
*/
paginate: propTypes.bool,
/**
* The selected option(s) displayed in the input. Use this prop if you want
* to control the component via its parent.
*/
selected: checkPropType(propTypes.arrayOf(optionType), selectedType),
/**
* Allows selecting the hinted result by pressing enter.
*/
selectHintOnEnter: deprecated(propTypes.bool, 'Use the `shouldSelect` prop on the `Hint` component to define which ' + 'keystrokes can select the hint.')
};
var defaultProps = {
allowNew: false,
autoFocus: false,
caseSensitive: false,
defaultInputValue: '',
defaultOpen: false,
defaultSelected: [],
filterBy: [],
highlightOnlyResult: false,
ignoreDiacritics: true,
labelKey: DEFAULT_LABELKEY,
maxResults: 100,
minLength: 0,
multiple: false,
onBlur: noop,
onFocus: noop,
onInputChange: noop,
onKeyDown: noop,
onMenuToggle: noop,
onPaginate: noop,
paginate: true
};
function getInitialState(props) {
var defaultInputValue = props.defaultInputValue,
defaultOpen = props.defaultOpen,
defaultSelected = props.defaultSelected,
maxResults = props.maxResults,
multiple = props.multiple;
var selected = props.selected ? props.selected.slice() : defaultSelected.slice();
var text = defaultInputValue;
if (!multiple && selected.length) {
// Set the text if an initial selection is passed in.
text = getOptionLabel(head(selected), props.labelKey);
if (selected.length > 1) {
// Limit to 1 selection in single-select mode.
selected = selected.slice(0, 1);
}
}
return {
activeIndex: -1,
activeItem: null,
initialItem: null,
isFocused: false,
selected: selected,
showMenu: defaultOpen,
shownResults: maxResults,
text: text
};
}
function clearTypeahead(state, props) {
return _extends({}, getInitialState(props), {
isFocused: state.isFocused,
selected: [],
text: ''
});
}
function hideMenu(state, props) {
var _getInitialState = getInitialState(props),
activeIndex = _getInitialState.activeIndex,
activeItem = _getInitialState.activeItem,
initialItem = _getInitialState.initialItem,
shownResults = _getInitialState.shownResults;
return {
activeIndex: activeIndex,
activeItem: activeItem,
initialItem: initialItem,
showMenu: false,
shownResults: shownResults
};
}
function toggleMenu(state, props) {
return state.showMenu ? hideMenu(state, props) : {
showMenu: true
};
}
var Typeahead = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(Typeahead, _React$Component);
function Typeahead() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "state", getInitialState(_this.props));
_defineProperty(_assertThisInitialized(_this), "inputNode", void 0);
_defineProperty(_assertThisInitialized(_this), "isMenuShown", false);
_defineProperty(_assertThisInitialized(_this), "items", []);
_defineProperty(_assertThisInitialized(_this), "blur", function () {
_this.inputNode && _this.inputNode.blur();
_this.hideMenu();
});
_defineProperty(_assertThisInitialized(_this), "clear", function () {
_this.setState(clearTypeahead);
});
_defineProperty(_assertThisInitialized(_this), "focus", function () {
_this.inputNode && _this.inputNode.focus();
});
_defineProperty(_assertThisInitialized(_this), "getInput", function () {
return _this.inputNode;
});
_defineProperty(_assertThisInitialized(_this), "inputRef", function (inputNode) {
_this.inputNode = inputNode;
});
_defineProperty(_assertThisInitialized(_this), "setItem", function (item, position) {
_this.items[position] = item;
});
_defineProperty(_assertThisInitialized(_this), "hideMenu", function () {
_this.setState(hideMenu);
});
_defineProperty(_assertThisInitialized(_this), "toggleMenu", function () {
_this.setState(toggleMenu);
});
_defineProperty(_assertThisInitialized(_this), "_handleActiveIndexChange", function (activeIndex) {
_this.setState(function (state) {
return {
activeIndex: activeIndex,
activeItem: activeIndex === -1 ? null : state.activeItem
};
});
});
_defineProperty(_assertThisInitialized(_this), "_handleActiveItemChange", function (activeItem) {
// Don't update the active item if it hasn't changed.
if (!fastDeepEqual(activeItem, _this.state.activeItem)) {
_this.setState({
activeItem: activeItem
});
}
});
_defineProperty(_assertThisInitialized(_this), "_handleBlur", function (e) {
e.persist();
_this.setState({
isFocused: false
}, function () {
return _this.props.onBlur(e);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleChange", function (selected) {
_this.props.onChange && _this.props.onChange(selected);
});
_defineProperty(_assertThisInitialized(_this), "_handleClear", function () {
_this.setState(clearTypeahead, function () {
return _this._handleChange([]);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleFocus", function (e) {
e.persist();
_this.setState({
isFocused: true,
showMenu: true
}, function () {
return _this.props.onFocus(e);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleInitialItemChange", function (initialItem) {
// Don't update the initial item if it hasn't changed.
if (!fastDeepEqual(initialItem, _this.state.initialItem)) {
_this.setState({
initialItem: initialItem
});
}
});
_defineProperty(_assertThisInitialized(_this), "_handleInputChange", function (e) {
e.persist();
var text = e.currentTarget.value;
var _this$props = _this.props,
multiple = _this$props.multiple,
onInputChange = _this$props.onInputChange; // Clear selections when the input value changes in single-select mode.
var shouldClearSelections = _this.state.selected.length && !multiple;
_this.setState(function (state, props) {
var _getInitialState2 = getInitialState(props),
activeIndex = _getInitialState2.activeIndex,
activeItem = _getInitialState2.activeItem,
shownResults = _getInitialState2.shownResults;
return {
activeIndex: activeIndex,
activeItem: activeItem,
selected: shouldClearSelections ? [] : state.selected,
showMenu: true,
shownResults: shownResults,
text: text
};
}, function () {
onInputChange(text, e);
shouldClearSelections && _this._handleChange([]);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleKeyDown", function (e) {
var activeItem = _this.state.activeItem; // Skip most actions when the menu is hidden.
if (!_this.isMenuShown) {
if (e.keyCode === UP || e.keyCode === DOWN) {
_this.setState({
showMenu: true
});
}
_this.props.onKeyDown(e);
return;
}
switch (e.keyCode) {
case UP:
case DOWN:
// Prevent input cursor from going to the beginning when pressing up.
e.preventDefault();
_this._handleActiveIndexChange(getUpdatedActiveIndex(_this.state.activeIndex, e.keyCode, _this.items));
break;
case RETURN:
// Prevent form submission while menu is open.
e.preventDefault();
activeItem && _this._handleMenuItemSelect(activeItem, e);
break;
case ESC:
case TAB:
// ESC simply hides the menu. TAB will blur the input and move focus to
// the next item; hide the menu so it doesn't gain focus.
_this.hideMenu();
break;
}
_this.props.onKeyDown(e);
});
_defineProperty(_assertThisInitialized(_this), "_handleMenuItemSelect", function (option, e) {
if (option.paginationOption) {
_this._handlePaginate(e);
} else {
_this._handleSelectionAdd(option);
}
});
_defineProperty(_assertThisInitialized(_this), "_handlePaginate", function (e) {
e.persist();
_this.setState(function (state, props) {
return {
shownResults: state.shownResults + props.maxResults
};
}, function () {
return _this.props.onPaginate(e, _this.state.shownResults);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleSelectionAdd", function (option) {
var _this$props2 = _this.props,
multiple = _this$props2.multiple,
labelKey = _this$props2.labelKey;
var selected;
var selection = option;
var text; // Add a unique id to the custom selection. Avoid doing this in `render` so
// the id doesn't increment every time.
if (!isString(selection) && selection.customOption) {
selection = _extends({}, selection, {
id: uniqueId('new-id-')
});
}
if (multiple) {
// If multiple selections are allowed, add the new selection to the
// existing selections.
selected = _this.state.selected.concat(selection);
text = '';
} else {
// If only a single selection is allowed, replace the existing selection
// with the new one.
selected = [selection];
text = getOptionLabel(selection, labelKey);
}
_this.setState(function (state, props) {
return _extends({}, hideMenu(state, props), {
initialItem: selection,
selected: selected,
text: text
});
}, function () {
return _this._handleChange(selected);
});
});
_defineProperty(_assertThisInitialized(_this), "_handleSelectionRemove", function (selection) {
var selected = _this.state.selected.filter(function (option) {
return !fastDeepEqual(option, selection);
}); // Make sure the input stays focused after the item is removed.
_this.focus();
_this.setState(function (state, props) {
return _extends({}, hideMenu(state, props), {
selected: selected
});
}, function () {
return _this._handleChange(selected);
});
});
return _this;
}
var _proto = Typeahead.prototype;
_proto.componentDidMount = function componentDidMount() {
this.props.autoFocus && this.focus();
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
var _this$props3 = this.props,
labelKey = _this$props3.labelKey,
multiple = _this$props3.multiple,
selected = _this$props3.selected;
validateSelectedPropChange(selected, prevProps.selected); // Sync selections in state with those in props.
if (selected && !fastDeepEqual(selected, prevState.selected)) {
this.setState({
selected: selected
});
if (!multiple) {
this.setState({
text: selected.length ? getOptionLabel(head(selected), labelKey) : ''
});
}
}
};
_proto.render = function render() {
// Omit `onChange` so Flow doesn't complain.
var _this$props4 = this.props,
onChange = _this$props4.onChange,
otherProps = _objectWithoutPropertiesLoose(_this$props4, ["onChange"]);
var mergedPropsAndState = _extends({}, otherProps, this.state);
var filterBy = mergedPropsAndState.filterBy,
labelKey = mergedPropsAndState.labelKey,
options = mergedPropsAndState.options,
paginate = mergedPropsAndState.paginate,
shownResults = mergedPropsAndState.shownResults,
text = mergedPropsAndState.text;
this.isMenuShown = isShown(mergedPropsAndState);
this.items = []; // Reset items on re-render.
var results = [];
if (this.isMenuShown) {
var cb = typeof filterBy === 'function' ? filterBy : defaultFilterBy;
results = options.filter(function (option) {
return cb(option, mergedPropsAndState);
}); // This must come before results are truncated.
var shouldPaginate = paginate && results.length > shownResults; // Truncate results if necessary.
results = getTruncatedOptions(results, shownResults); // Add the custom option if necessary.
if (addCustomOption(results, mergedPropsAndState)) {
var _results$push;
results.push((_results$push = {
customOption: true
}, _results$push[getStringLabelKey(labelKey)] = text, _results$push));
} // Add the pagination item if necessary.
if (shouldPaginate) {
var _results$push2;
results.push((_results$push2 = {}, _results$push2[getStringLabelKey(labelKey)] = '', _results$push2.paginationOption = true, _results$push2));
}
}
return /*#__PURE__*/React__default.createElement(TypeaheadManager, _extends({}, mergedPropsAndState, {
hideMenu: this.hideMenu,
inputNode: this.inputNode,
inputRef: this.inputRef,
isMenuShown: this.isMenuShown,
onActiveItemChange: this._handleActiveItemChange,
onAdd: this._handleSelectionAdd,
onBlur: this._handleBlur,
onChange: this._handleInputChange,
onClear: this._handleClear,
onFocus: this._handleFocus,
onHide: this.hideMenu,
onInitialItemChange: this._handleInitialItemChange,
onKeyDown: this._handleKeyDown,
onMenuItemClick: this._handleMenuItemSelect,
onRemove: this._handleSelectionRemove,
results: results,
setItem: this.setItem,
toggleMenu: this.toggleMenu
}));
};
return Typeahead;
}(React__default.Component);
_defineProperty(Typeahead, "propTypes", propTypes$1);
_defineProperty(Typeahead, "defaultProps", defaultProps);
var propTypes$2 = {
/**
* Delay, in milliseconds, before performing search.
*/
delay: propTypes.number,
/**
* Whether or not a request is currently pending. Necessary for the
* container to know when new results are available.
*/
isLoading: propTypes.bool.isRequired,
/**
* Number of input characters that must be entered before showing results.
*/
minLength: propTypes.number,
/**
* Callback to perform when the search is executed.
*/
onSearch: propTypes.func.isRequired,
/**
* Options to be passed to the typeahead. Will typically be the query
* results, but can also be initial default options.
*/
options: propTypes.arrayOf(optionType),
/**
* Message displayed in the menu when there is no user input.
*/
promptText: propTypes.node,
/**
* Message displayed in the menu while the request is pending.
*/
searchText: propTypes.node,
/**
* Whether or not the component should cache query results.
*/
useCache: propTypes.bool
};
var defaultProps$1 = {
delay: 200,
minLength: 2,
options: [],
promptText: 'Type to search...',
searchText: 'Searching...',
useCache: true
};
/**
* Logic that encapsulates common behavior and functionality around
* asynchronous searches, including:
*
* - Debouncing user input
* - Optional query caching
* - Search prompt and empty results behaviors
*/
function useAsync(props) {
var allowNew = props.allowNew,
delay = props.delay,
emptyLabel = props.emptyLabel,
isLoading = props.isLoading,
minLength = props.minLength,
onInputChange = props.onInputChange,
onSearch = props.onSearch,
options = props.options,
promptText = props.promptText,
searchText = props.searchText,
useCache = props.useCache,
otherProps = _objectWithoutPropertiesLoose(props, ["allowNew", "delay", "emptyLabel", "isLoading", "minLength", "onInputChange", "onSearch", "options", "promptText", "searchText", "useCache"]);
var cacheRef = React.useRef({});
var handleSearchDebouncedRef = React.useRef();
var queryRef = React.useRef(props.defaultInputValue || '');
var forceUpdate = useForceUpdate();
var prevProps = usePrevious(props);
var handleSearch = React.useCallback(function (query) {
queryRef.current = query;
if (!query || minLength && query.length < minLength) {
return;
} // Use cached results, if applicable.
if (useCache && cacheRef.current[query]) {
// Re-render the component with the cached results.
forceUpdate();
return;
} // Perform the search.
onSearch(query);
}, [forceUpdate, minLength, onSearch, useCache]); // Set the debounced search function.
React.useEffect(function () {
handleSearchDebouncedRef.current = lodash_debounce(handleSearch, delay);
return function () {
handleSearchDebouncedRef.current && handleSearchDebouncedRef.current.cancel();
};
}, [delay, handleSearch]);
React.useEffect(function () {
// Ensure that we've gone from a loading to a completed state. Otherwise
// an empty response could get cached if the component updates during the
// request (eg: if the parent re-renders for some reason).
if (!isLoading && prevProps && prevProps.isLoading && useCache) {
cacheRef.current[queryRef.current] = options;
}
});
var getEmptyLabel = function getEmptyLabel() {
if (!queryRef.current.length) {
return promptText;
}
if (isLoading) {
return searchText;
}
return emptyLabel;
};
var handleInputChange = React.useCallback(function (query, e) {
onInputChange && onInputChange(query, e);
handleSearchDebouncedRef.current && handleSearchDebouncedRef.current(query);
}, [onInputChange]);
var cachedQuery = cacheRef.current[queryRef.current];
return _extends({}, otherProps, {
// Disable custom selections during a search if `allowNew` isn't a function.
allowNew: isFunction(allowNew) ? allowNew : allowNew && !isLoading,
emptyLabel: getEmptyLabel(),
isLoading: isLoading,
minLength: minLength,
onInputChange: handleInputChange,
options: useCache && cachedQuery ? cachedQuery : options
});
}
function withAsync(Component) {
var AsyncTypeahead = /*#__PURE__*/React.forwardRef(function (props, ref) {
return /*#__PURE__*/React__default.createElement(Component, _extends({}, useAsync(props), {
ref: ref
}));
});
AsyncTypeahead.displayName = "withAsync(" + getDisplayName(Component) + ")"; // $FlowFixMe
AsyncTypeahead.propTypes = propTypes$2; // $FlowFixMe
AsyncTypeahead.defaultProps = defaultProps$1;
return AsyncTypeahead;
}
function asyncContainer(Component) {
/* istanbul ignore next */
warn(false, 'The `asyncContainer` export is deprecated; use `withAsync` instead.');
/* istanbul ignore next */
return withAsync(Component);
}
/* eslint-disable no-bitwise, no-cond-assign */
// HTML DOM and SVG DOM may have different support levels,
// so we need to check on context instead of a document root element.
function contains(context, node) {
if (context.contains) return context.contains(node);
if (context.compareDocumentPosition) return context === node || !!(context.compareDocumentPosition(node) & 16);
}
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/* eslint-disable no-return-assign */
var optionsSupported = false;
var onceSupported = false;
try {
var options = {
get passive() {
return optionsSupported = true;
},
get once() {
// eslint-disable-next-line no-multi-assign
return onceSupported = optionsSupported = true;
}
};
if (canUseDOM) {
window.addEventListener('test', options, options);
window.removeEventListener('test', options, true);
}
} catch (e) {
/* */
}
/**
* An `addEventListener` ponyfill, supports the `once` option
*/
function addEventListener(node, eventName, handler, options) {
if (options && typeof options !== 'boolean' && !onceSupported) {
var once = options.once,
capture = options.capture;
var wrappedHandler = handler;
if (!onceSupported && once) {
wrappedHandler = handler.__once || function onceHandler(event) {
this.removeEventListener(eventName, onceHandler, capture);
handler.call(this, event);
};
handler.__once = wrappedHandler;
}
node.addEventListener(eventName, wrappedHandler, optionsSupported ? options : capture);
}
node.addEventListener(eventName, handler, options);
}
function removeEventListener(node, eventName, handler, options) {
var capture = options && typeof options !== 'boolean' ? options.capture : options;
node.removeEventListener(eventName, handler, capture);
if (handler.__once) {
node.removeEventListener(eventName, handler.__once, capture);
}
}
function listen(node, eventName, handler, options) {
addEventListener(node, eventName, handler, options);
return function () {
removeEventListener(node, eventName, handler, options);
};
}
/**
* Creates a `Ref` whose value is updated in an effect, ensuring the most recent
* value is the one rendered with. Generally only required for Concurrent mode usage
* where previous work in `render()` may be discarded befor being used.
*
* This is safe to access in an event handler.
*
* @param value The `Ref` value
*/
function useCommittedRef(value) {
var ref = React.useRef(value);
React.useEffect(function () {
ref.current = value;
}, [value]);
return ref;
}
function useEventCallback(fn) {
var ref = useCommittedRef(fn);
return React.useCallback(function () {
return ref.current && ref.current.apply(ref, arguments);
}, [ref]);
}
function ownerDocument(node) {
return node && node.ownerDocument || document;
}
function ownerDocument$1 (componentOrElement) {
return ownerDocument(ReactDOM.findDOMNode(componentOrElement));
}
var escapeKeyCode = 27;
var noop$1 = function noop() {};
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
/**
* The `useRootClose` hook registers your callback on the document
* when rendered. Powers the `<Overlay/>` component. This is used achieve modal
* style behavior where your callback is triggered when the user tries to
* interact with the rest of the document or hits the `esc` key.
*
* @param {Ref<HTMLElement>|HTMLElement} ref The element boundary
* @param {function} onRootClose
* @param {object} options
* @param {boolean} options.disabled
* @param {string} options.clickTrigger The DOM event name (click, mousedown, etc) to attach listeners on
*/
function useRootClose(ref, onRootClose, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
disabled = _ref.disabled,
_ref$clickTrigger = _ref.clickTrigger,
clickTrigger = _ref$clickTrigger === void 0 ? 'click' : _ref$clickTrigger;
var preventMouseRootCloseRef = React.useRef(false);
var onClose = onRootClose || noop$1;
var handleMouseCapture = React.useCallback(function (e) {
var currentTarget = ref && ('current' in ref ? ref.current : ref);
warning_1(!!currentTarget, 'RootClose captured a close event but does not have a ref to compare it to. ' + 'useRootClose(), should be passed a ref that resolves to a DOM node');
preventMouseRootCloseRef.current = !currentTarget || isModifiedEvent(e) || !isLeftClickEvent(e) || contains(currentTarget, e.target);
}, [ref]);
var handleMouse = useEventCallback(function (e) {
if (!preventMouseRootCloseRef.current) {
onClose(e);
}
});
var handleKeyUp = useEventCallback(function (e) {
if (e.keyCode === escapeKeyCode) {
onClose(e);
}
});
React.useEffect(function () {
if (disabled || ref == null) return undefined;
var doc = ownerDocument$1(ref.current); // Use capture for this listener so it fires before React's listener, to
// avoid false positives in the contains() check below if the target DOM
// element is removed in the React mouse callback.
var removeMouseCaptureListener = listen(doc, clickTrigger, handleMouseCapture, true);
var removeMouseListener = listen(doc, clickTrigger, handleMouse);
var removeKeyupListener = listen(doc, 'keyup', handleKeyUp);
var mobileSafariHackListeners = [];
if ('ontouchstart' in doc.documentElement) {
mobileSafariHackListeners = [].slice.call(doc.body.children).map(function (el) {
return listen(el, 'mousemove', noop$1);
});
}
return function () {
removeMouseCaptureListener();
removeMouseListener();
removeKeyupListener();
mobileSafariHackListeners.forEach(function (remove) {
return remove();
});
};
}, [ref, disabled, clickTrigger, handleMouseCapture, handleMouse, handleKeyUp]);
}
var propTypes$3 = {
label: propTypes.string,
onClick: propTypes.func,
size: sizeType
};
var defaultProps$2 = {
label: 'Clear',
onClick: noop
};
/**
* ClearButton
*
* http://getbootstrap.com/css/#helper-classes-close
*/
var ClearButton = function ClearButton(_ref) {
var className = _ref.className,
label = _ref.label,
_onClick = _ref.onClick,
size = _ref.size,
props = _objectWithoutPropertiesLoose(_ref, ["className", "label", "onClick", "size"]);
return /*#__PURE__*/React__default.createElement("button", _extends({}, props, {
"aria-label": label,
className: classnames('close', 'rbt-close', {
'rbt-close-lg': isSizeLarge(size)
}, className),
onClick: function onClick(e) {
e.stopPropagation();
_onClick(e);
},
type: "button"
}), /*#__PURE__*/React__default.createElement("span", {
"aria-hidden": "true"
}, "\xD7"), /*#__PURE__*/React__default.createElement("span", {
className: "sr-only"
}, label));
};
ClearButton.propTypes = propTypes$3;
ClearButton.defaultProps = defaultProps$2;
var propTypes$4 = {
label: propTypes.string
};
var defaultProps$3 = {
label: 'Loading...'
};
var Loader = function Loader(_ref) {
var label = _ref.label;
return /*#__PURE__*/React__default.createElement("div", {
className: "rbt-loader spinner-border spinner-border-sm",
role: "status"
}, /*#__PURE__*/React__default.createElement("span", {
className: "sr-only"
}, label));
};
Loader.propTypes = propTypes$4;
Loader.defaultProps = defaultProps$3;
function _objectWithoutPropertiesLoose$1(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var objectWithoutPropertiesLoose = _objectWithoutPropertiesLoose$1;
var _extends_1 = createCommonjsModule(function (module) {
function _extends() {
module.exports = _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
module.exports = _extends;
});
function _assertThisInitialized$1(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var assertThisInitialized = _assertThisInitialized$1;
function _inheritsLoose$1(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
var inheritsLoose = _inheritsLoose$1;
function _defineProperty$1(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var defineProperty = _defineProperty$1;
var toStr = Object.prototype.toString;
var isArguments = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
var keysShim;
if (!Object.keys) {
// modified from https://github.com/es-shims/es5-shim
var has$2 = Object.prototype.hasOwnProperty;
var toStr$1 = Object.prototype.toString;
var isArgs = isArguments; // eslint-disable-line global-require
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$applicationCache: true,
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$onmozfullscreenchange: true,
$onmozfullscreenerror: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has$2.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr$1.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr$1.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has$2.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has$2.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has$2.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
}
var implementation = keysShim;
var slice = Array.prototype.slice;
var origKeys = Object.keys;
var keysShim$1 = origKeys ? function keys(o) { return origKeys(o); } : implementation;
var originalKeys = Object.keys;
keysShim$1.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
var args = Object.keys(arguments);
return args && args.length === arguments.length;
}(1, 2));
if (!keysWorksWithArguments) {
Object.keys = function keys(object) { // eslint-disable-line func-name-matching
if (isArguments(object)) {
return originalKeys(slice.call(object));
}
return originalKeys(object);
};
}
} else {
Object.keys = keysShim$1;
}
return Object.keys || keysShim$1;
};
var objectKeys = keysShim$1;
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
var toStr$2 = Object.prototype.toString;
var isStandardArguments = function isArguments(value) {
if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) {
return false;
}
return toStr$2.call(value) === '[object Arguments]';
};
var isLegacyArguments = function isArguments(value) {
if (isStandardArguments(value)) {
return true;
}
return value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr$2.call(value) !== '[object Array]' &&
toStr$2.call(value.callee) === '[object Function]';
};
var supportsStandardArguments = (function () {
return isStandardArguments(arguments);
}());
isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests
var isArguments$1 = supportsStandardArguments ? isStandardArguments : isLegacyArguments;
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
var toStr$3 = Object.prototype.toString;
var concat = Array.prototype.concat;
var origDefineProperty = Object.defineProperty;
var isFunction$1 = function (fn) {
return typeof fn === 'function' && toStr$3.call(fn) === '[object Function]';
};
var arePropertyDescriptorsSupported = function () {
var obj = {};
try {
origDefineProperty(obj, 'x', { enumerable: false, value: obj });
// eslint-disable-next-line no-unused-vars, no-restricted-syntax
for (var _ in obj) { // jscs:ignore disallowUnusedVariables
return false;
}
return obj.x === obj;
} catch (e) { /* this is IE 8. */
return false;
}
};
var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();
var defineProperty$1 = function (object, name, value, predicate) {
if (name in object && (!isFunction$1(predicate) || !predicate())) {
return;
}
if (supportsDescriptors) {
origDefineProperty(object, name, {
configurable: true,
enumerable: false,
value: value,
writable: true
});
} else {
object[name] = value;
}
};
var defineProperties = function (object, map) {
var predicates = arguments.length > 2 ? arguments[2] : {};
var props = objectKeys(map);
if (hasSymbols) {
props = concat.call(props, Object.getOwnPropertySymbols(map));
}
for (var i = 0; i < props.length; i += 1) {
defineProperty$1(object, props[i], map[props[i]], predicates[props[i]]);
}
};
defineProperties.supportsDescriptors = !!supportsDescriptors;
var defineProperties_1 = defineProperties;
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice$1 = Array.prototype.slice;
var toStr$4 = Object.prototype.toString;
var funcType = '[object Function]';
var implementation$1 = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr$4.call(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slice$1.call(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
args.concat(slice$1.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
args.concat(slice$1.call(arguments))
);
}
};
var boundLength = Math.max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs.push('$' + i);
}
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
var functionBind = Function.prototype.bind || implementation$1;
/* eslint complexity: [2, 18], max-statements: [2, 33] */
var shams = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
var origSymbol = commonjsGlobal.Symbol;
var hasSymbols$1 = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return shams();
};
/* globals
Atomics,
SharedArrayBuffer,
*/
var undefined$1;
var $TypeError = TypeError;
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () { throw new $TypeError(); };
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols$2 = hasSymbols$1();
var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
var generatorFunction = undefined$1;
var asyncFunction = undefined$1;
var asyncGenFunction = undefined$1;
var TypedArray = typeof Uint8Array === 'undefined' ? undefined$1 : getProto(Uint8Array);
var INTRINSICS = {
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer,
'%ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer.prototype,
'%ArrayIteratorPrototype%': hasSymbols$2 ? getProto([][Symbol.iterator]()) : undefined$1,
'%ArrayPrototype%': Array.prototype,
'%ArrayProto_entries%': Array.prototype.entries,
'%ArrayProto_forEach%': Array.prototype.forEach,
'%ArrayProto_keys%': Array.prototype.keys,
'%ArrayProto_values%': Array.prototype.values,
'%AsyncFromSyncIteratorPrototype%': undefined$1,
'%AsyncFunction%': asyncFunction,
'%AsyncFunctionPrototype%': undefined$1,
'%AsyncGenerator%': undefined$1,
'%AsyncGeneratorFunction%': asyncGenFunction,
'%AsyncGeneratorPrototype%': undefined$1,
'%AsyncIteratorPrototype%': undefined$1,
'%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics,
'%Boolean%': Boolean,
'%BooleanPrototype%': Boolean.prototype,
'%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView,
'%DataViewPrototype%': typeof DataView === 'undefined' ? undefined$1 : DataView.prototype,
'%Date%': Date,
'%DatePrototype%': Date.prototype,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': Error,
'%ErrorPrototype%': Error.prototype,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': EvalError,
'%EvalErrorPrototype%': EvalError.prototype,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array,
'%Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array.prototype,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array,
'%Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array.prototype,
'%Function%': Function,
'%FunctionPrototype%': Function.prototype,
'%Generator%': undefined$1,
'%GeneratorFunction%': generatorFunction,
'%GeneratorPrototype%': undefined$1,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array,
'%Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array.prototype,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array,
'%Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined$1 : Int8Array.prototype,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array,
'%Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array.prototype,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols$2 ? getProto(getProto([][Symbol.iterator]())) : undefined$1,
'%JSON%': typeof JSON === 'object' ? JSON : undefined$1,
'%JSONParse%': typeof JSON === 'object' ? JSON.parse : undefined$1,
'%Map%': typeof Map === 'undefined' ? undefined$1 : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols$2 ? undefined$1 : getProto(new Map()[Symbol.iterator]()),
'%MapPrototype%': typeof Map === 'undefined' ? undefined$1 : Map.prototype,
'%Math%': Math,
'%Number%': Number,
'%NumberPrototype%': Number.prototype,
'%Object%': Object,
'%ObjectPrototype%': Object.prototype,
'%ObjProto_toString%': Object.prototype.toString,
'%ObjProto_valueOf%': Object.prototype.valueOf,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise,
'%PromisePrototype%': typeof Promise === 'undefined' ? undefined$1 : Promise.prototype,
'%PromiseProto_then%': typeof Promise === 'undefined' ? undefined$1 : Promise.prototype.then,
'%Promise_all%': typeof Promise === 'undefined' ? undefined$1 : Promise.all,
'%Promise_reject%': typeof Promise === 'undefined' ? undefined$1 : Promise.reject,
'%Promise_resolve%': typeof Promise === 'undefined' ? undefined$1 : Promise.resolve,
'%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy,
'%RangeError%': RangeError,
'%RangeErrorPrototype%': RangeError.prototype,
'%ReferenceError%': ReferenceError,
'%ReferenceErrorPrototype%': ReferenceError.prototype,
'%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect,
'%RegExp%': RegExp,
'%RegExpPrototype%': RegExp.prototype,
'%Set%': typeof Set === 'undefined' ? undefined$1 : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols$2 ? undefined$1 : getProto(new Set()[Symbol.iterator]()),
'%SetPrototype%': typeof Set === 'undefined' ? undefined$1 : Set.prototype,
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer,
'%SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer.prototype,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols$2 ? getProto(''[Symbol.iterator]()) : undefined$1,
'%StringPrototype%': String.prototype,
'%Symbol%': hasSymbols$2 ? Symbol : undefined$1,
'%SymbolPrototype%': hasSymbols$2 ? Symbol.prototype : undefined$1,
'%SyntaxError%': SyntaxError,
'%SyntaxErrorPrototype%': SyntaxError.prototype,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined$1,
'%TypeError%': $TypeError,
'%TypeErrorPrototype%': $TypeError.prototype,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array,
'%Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array.prototype,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray,
'%Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray.prototype,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array,
'%Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array.prototype,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array,
'%Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array.prototype,
'%URIError%': URIError,
'%URIErrorPrototype%': URIError.prototype,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap,
'%WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap.prototype,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet,
'%WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet.prototype
};
var $replace = functionBind.call(Function.call, String.prototype.replace);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : (number || match);
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
if (!(name in INTRINSICS)) {
throw new SyntaxError('intrinsic ' + name + ' does not exist!');
}
// istanbul ignore if // hopefully this is impossible to test :-)
if (typeof INTRINSICS[name] === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return INTRINSICS[name];
};
var GetIntrinsic = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new TypeError('"allowMissing" argument must be a boolean');
}
var parts = stringToPath(name);
var value = getBaseIntrinsic('%' + (parts.length > 0 ? parts[0] : '') + '%', allowMissing);
for (var i = 1; i < parts.length; i += 1) {
if (value != null) {
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, parts[i]);
if (!allowMissing && !(parts[i] in value)) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
value = desc ? (desc.get || desc.value) : value[parts[i]];
} else {
value = value[parts[i]];
}
}
}
return value;
};
var $Function = GetIntrinsic('%Function%');
var $apply = $Function.apply;
var $call = $Function.call;
var callBind = function callBind() {
return functionBind.apply($call, arguments);
};
var apply = function applyBind() {
return functionBind.apply($apply, arguments);
};
callBind.apply = apply;
var numberIsNaN = function (value) {
return value !== value;
};
var implementation$2 = function is(a, b) {
if (a === 0 && b === 0) {
return 1 / a === 1 / b;
}
if (a === b) {
return true;
}
if (numberIsNaN(a) && numberIsNaN(b)) {
return true;
}
return false;
};
var polyfill = function getPolyfill() {
return typeof Object.is === 'function' ? Object.is : implementation$2;
};
var shim = function shimObjectIs() {
var polyfill$1 = polyfill();
defineProperties_1(Object, { is: polyfill$1 }, {
is: function testObjectIs() {
return Object.is !== polyfill$1;
}
});
return polyfill$1;
};
var polyfill$1 = callBind(polyfill(), Object);
defineProperties_1(polyfill$1, {
getPolyfill: polyfill,
implementation: implementation$2,
shim: shim
});
var objectIs = polyfill$1;
var src = functionBind.call(Function.call, Object.prototype.hasOwnProperty);
var regexExec = RegExp.prototype.exec;
var gOPD = Object.getOwnPropertyDescriptor;
var tryRegexExecCall = function tryRegexExec(value) {
try {
var lastIndex = value.lastIndex;
value.lastIndex = 0; // eslint-disable-line no-param-reassign
regexExec.call(value);
return true;
} catch (e) {
return false;
} finally {
value.lastIndex = lastIndex; // eslint-disable-line no-param-reassign
}
};
var toStr$5 = Object.prototype.toString;
var regexClass = '[object RegExp]';
var hasToStringTag$1 = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
var isRegex = function isRegex(value) {
if (!value || typeof value !== 'object') {
return false;
}
if (!hasToStringTag$1) {
return toStr$5.call(value) === regexClass;
}
var descriptor = gOPD(value, 'lastIndex');
var hasLastIndexDataProperty = descriptor && src(descriptor, 'value');
if (!hasLastIndexDataProperty) {
return false;
}
return tryRegexExecCall(value);
};
var $Object = Object;
var $TypeError$1 = TypeError;
var implementation$3 = function flags() {
if (this != null && this !== $Object(this)) {
throw new $TypeError$1('RegExp.prototype.flags getter called on non-object');
}
var result = '';
if (this.global) {
result += 'g';
}
if (this.ignoreCase) {
result += 'i';
}
if (this.multiline) {
result += 'm';
}
if (this.dotAll) {
result += 's';
}
if (this.unicode) {
result += 'u';
}
if (this.sticky) {
result += 'y';
}
return result;
};
var supportsDescriptors$1 = defineProperties_1.supportsDescriptors;
var $gOPD$1 = Object.getOwnPropertyDescriptor;
var $TypeError$2 = TypeError;
var polyfill$2 = function getPolyfill() {
if (!supportsDescriptors$1) {
throw new $TypeError$2('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors');
}
if ((/a/mig).flags === 'gim') {
var descriptor = $gOPD$1(RegExp.prototype, 'flags');
if (descriptor && typeof descriptor.get === 'function' && typeof (/a/).dotAll === 'boolean') {
return descriptor.get;
}
}
return implementation$3;
};
var supportsDescriptors$2 = defineProperties_1.supportsDescriptors;
var gOPD$1 = Object.getOwnPropertyDescriptor;
var defineProperty$2 = Object.defineProperty;
var TypeErr = TypeError;
var getProto$1 = Object.getPrototypeOf;
var regex = /a/;
var shim$1 = function shimFlags() {
if (!supportsDescriptors$2 || !getProto$1) {
throw new TypeErr('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors');
}
var polyfill = polyfill$2();
var proto = getProto$1(regex);
var descriptor = gOPD$1(proto, 'flags');
if (!descriptor || descriptor.get !== polyfill) {
defineProperty$2(proto, 'flags', {
configurable: true,
enumerable: false,
get: polyfill
});
}
return polyfill;
};
var flagsBound = callBind(implementation$3);
defineProperties_1(flagsBound, {
getPolyfill: polyfill$2,
implementation: implementation$3,
shim: shim$1
});
var regexp_prototype_flags = flagsBound;
var getDay = Date.prototype.getDay;
var tryDateObject = function tryDateGetDayCall(value) {
try {
getDay.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr$6 = Object.prototype.toString;
var dateClass = '[object Date]';
var hasToStringTag$2 = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
var isDateObject = function isDateObject(value) {
if (typeof value !== 'object' || value === null) {
return false;
}
return hasToStringTag$2 ? tryDateObject(value) : toStr$6.call(value) === dateClass;
};
var getTime = Date.prototype.getTime;
function deepEqual(actual, expected, options) {
var opts = options || {};
// 7.1. All identical values are equivalent, as determined by ===.
if (opts.strict ? objectIs(actual, expected) : actual === expected) {
return true;
}
// 7.3. Other pairs that do not both pass typeof value == 'object', equivalence is determined by ==.
if (!actual || !expected || (typeof actual !== 'object' && typeof expected !== 'object')) {
return opts.strict ? objectIs(actual, expected) : actual == expected;
}
/*
* 7.4. For all other Object pairs, including Array objects, equivalence is
* determined by having the same number of owned properties (as verified
* with Object.prototype.hasOwnProperty.call), the same set of keys
* (although not necessarily the same order), equivalent values for every
* corresponding key, and an identical 'prototype' property. Note: this
* accounts for both named and indexed properties on Arrays.
*/
// eslint-disable-next-line no-use-before-define
return objEquiv(actual, expected, opts);
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isBuffer(x) {
if (!x || typeof x !== 'object' || typeof x.length !== 'number') {
return false;
}
if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
return false;
}
if (x.length > 0 && typeof x[0] !== 'number') {
return false;
}
return true;
}
function objEquiv(a, b, opts) {
/* eslint max-statements: [2, 50] */
var i, key;
if (typeof a !== typeof b) { return false; }
if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) { return false; }
// an identical 'prototype' property.
if (a.prototype !== b.prototype) { return false; }
if (isArguments$1(a) !== isArguments$1(b)) { return false; }
var aIsRegex = isRegex(a);
var bIsRegex = isRegex(b);
if (aIsRegex !== bIsRegex) { return false; }
if (aIsRegex || bIsRegex) {
return a.source === b.source && regexp_prototype_flags(a) === regexp_prototype_flags(b);
}
if (isDateObject(a) && isDateObject(b)) {
return getTime.call(a) === getTime.call(b);
}
var aIsBuffer = isBuffer(a);
var bIsBuffer = isBuffer(b);
if (aIsBuffer !== bIsBuffer) { return false; }
if (aIsBuffer || bIsBuffer) { // && would work too, because both are true or both false here
if (a.length !== b.length) { return false; }
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) { return false; }
}
return true;
}
if (typeof a !== typeof b) { return false; }
try {
var ka = objectKeys(a);
var kb = objectKeys(b);
} catch (e) { // happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates hasOwnProperty)
if (ka.length !== kb.length) { return false; }
// the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
// ~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i]) { return false; }
}
// equivalent values for every corresponding key, and ~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!deepEqual(a[key], b[key], opts)) { return false; }
}
return true;
}
var deepEqual_1 = deepEqual;
/**!
* @fileOverview Kickass library to create and place poppers near their reference elements.
* @version 1.16.1
* @license
* Copyright (c) 2016 Federico Zivolo and contributors
*
* 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.
*/
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && typeof navigator !== 'undefined';
var timeoutDuration = function () {
var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox'];
for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) {
if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) {
return 1;
}
}
return 0;
}();
function microtaskDebounce(fn) {
var called = false;
return function () {
if (called) {
return;
}
called = true;
window.Promise.resolve().then(function () {
called = false;
fn();
});
};
}
function taskDebounce(fn) {
var scheduled = false;
return function () {
if (!scheduled) {
scheduled = true;
setTimeout(function () {
scheduled = false;
fn();
}, timeoutDuration);
}
};
}
var supportsMicroTasks = isBrowser && window.Promise;
/**
* Create a debounced version of a method, that's asynchronously deferred
* but called in the minimum time possible.
*
* @method
* @memberof Popper.Utils
* @argument {Function} fn
* @returns {Function}
*/
var debounce$1 = supportsMicroTasks ? microtaskDebounce : taskDebounce;
/**
* Check if the given variable is a function
* @method
* @memberof Popper.Utils
* @argument {Any} functionToCheck - variable to check
* @returns {Boolean} answer to: is a function?
*/
function isFunction$2(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
/**
* Get CSS computed property of the given element
* @method
* @memberof Popper.Utils
* @argument {Eement} element
* @argument {String} property
*/
function getStyleComputedProperty(element, property) {
if (element.nodeType !== 1) {
return [];
}
// NOTE: 1 DOM access here
var window = element.ownerDocument.defaultView;
var css = window.getComputedStyle(element, null);
return property ? css[property] : css;
}
/**
* Returns the parentNode or the host of the element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} parent
*/
function getParentNode(element) {
if (element.nodeName === 'HTML') {
return element;
}
return element.parentNode || element.host;
}
/**
* Returns the scrolling parent of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} scroll parent
*/
function getScrollParent(element) {
// Return body, `getScroll` will take care to get the correct `scrollTop` from it
if (!element) {
return document.body;
}
switch (element.nodeName) {
case 'HTML':
case 'BODY':
return element.ownerDocument.body;
case '#document':
return element.body;
}
// Firefox want us to check `-x` and `-y` variations as well
var _getStyleComputedProp = getStyleComputedProperty(element),
overflow = _getStyleComputedProp.overflow,
overflowX = _getStyleComputedProp.overflowX,
overflowY = _getStyleComputedProp.overflowY;
if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) {
return element;
}
return getScrollParent(getParentNode(element));
}
/**
* Returns the reference node of the reference object, or the reference object itself.
* @method
* @memberof Popper.Utils
* @param {Element|Object} reference - the reference element (the popper will be relative to this)
* @returns {Element} parent
*/
function getReferenceNode(reference) {
return reference && reference.referenceNode ? reference.referenceNode : reference;
}
var isIE11 = isBrowser && !!(window.MSInputMethodContext && document.documentMode);
var isIE10 = isBrowser && /MSIE 10/.test(navigator.userAgent);
/**
* Determines if the browser is Internet Explorer
* @method
* @memberof Popper.Utils
* @param {Number} version to check
* @returns {Boolean} isIE
*/
function isIE(version) {
if (version === 11) {
return isIE11;
}
if (version === 10) {
return isIE10;
}
return isIE11 || isIE10;
}
/**
* Returns the offset parent of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} offset parent
*/
function getOffsetParent(element) {
if (!element) {
return document.documentElement;
}
var noOffsetParent = isIE(10) ? document.body : null;
// NOTE: 1 DOM access here
var offsetParent = element.offsetParent || null;
// Skip hidden elements which don't have an offsetParent
while (offsetParent === noOffsetParent && element.nextElementSibling) {
offsetParent = (element = element.nextElementSibling).offsetParent;
}
var nodeName = offsetParent && offsetParent.nodeName;
if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {
return element ? element.ownerDocument.documentElement : document.documentElement;
}
// .offsetParent will return the closest TH, TD or TABLE in case
// no offsetParent is present, I hate this job...
if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {
return getOffsetParent(offsetParent);
}
return offsetParent;
}
function isOffsetContainer(element) {
var nodeName = element.nodeName;
if (nodeName === 'BODY') {
return false;
}
return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element;
}
/**
* Finds the root node (document, shadowDOM root) of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} node
* @returns {Element} root node
*/
function getRoot(node) {
if (node.parentNode !== null) {
return getRoot(node.parentNode);
}
return node;
}
/**
* Finds the offset parent common to the two provided nodes
* @method
* @memberof Popper.Utils
* @argument {Element} element1
* @argument {Element} element2
* @returns {Element} common offset parent
*/
function findCommonOffsetParent(element1, element2) {
// This check is needed to avoid errors in case one of the elements isn't defined for any reason
if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {
return document.documentElement;
}
// Here we make sure to give as "start" the element that comes first in the DOM
var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;
var start = order ? element1 : element2;
var end = order ? element2 : element1;
// Get common ancestor container
var range = document.createRange();
range.setStart(start, 0);
range.setEnd(end, 0);
var commonAncestorContainer = range.commonAncestorContainer;
// Both nodes are inside #document
if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {
if (isOffsetContainer(commonAncestorContainer)) {
return commonAncestorContainer;
}
return getOffsetParent(commonAncestorContainer);
}
// one of the nodes is inside shadowDOM, find which one
var element1root = getRoot(element1);
if (element1root.host) {
return findCommonOffsetParent(element1root.host, element2);
} else {
return findCommonOffsetParent(element1, getRoot(element2).host);
}
}
/**
* Gets the scroll value of the given element in the given side (top and left)
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @argument {String} side `top` or `left`
* @returns {number} amount of scrolled pixels
*/
function getScroll(element) {
var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top';
var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft';
var nodeName = element.nodeName;
if (nodeName === 'BODY' || nodeName === 'HTML') {
var html = element.ownerDocument.documentElement;
var scrollingElement = element.ownerDocument.scrollingElement || html;
return scrollingElement[upperSide];
}
return element[upperSide];
}
/*
* Sum or subtract the element scroll values (left and top) from a given rect object
* @method
* @memberof Popper.Utils
* @param {Object} rect - Rect object you want to change
* @param {HTMLElement} element - The element from the function reads the scroll values
* @param {Boolean} subtract - set to true if you want to subtract the scroll values
* @return {Object} rect - The modifier rect object
*/
function includeScroll(rect, element) {
var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var scrollTop = getScroll(element, 'top');
var scrollLeft = getScroll(element, 'left');
var modifier = subtract ? -1 : 1;
rect.top += scrollTop * modifier;
rect.bottom += scrollTop * modifier;
rect.left += scrollLeft * modifier;
rect.right += scrollLeft * modifier;
return rect;
}
/*
* Helper to detect borders of a given element
* @method
* @memberof Popper.Utils
* @param {CSSStyleDeclaration} styles
* Result of `getStyleComputedProperty` on the given element
* @param {String} axis - `x` or `y`
* @return {number} borders - The borders size of the given axis
*/<|fim▁hole|>
return parseFloat(styles['border' + sideA + 'Width']) + parseFloat(styles['border' + sideB + 'Width']);
}
function getSize(axis, body, html, computedStyle) {
return Math.max(body['offset' + axis], body['scroll' + axis], html['client' + axis], html['offset' + axis], html['scroll' + axis], isIE(10) ? parseInt(html['offset' + axis]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')]) : 0);
}
function getWindowSizes(document) {
var body = document.body;
var html = document.documentElement;
var computedStyle = isIE(10) && getComputedStyle(html);
return {
height: getSize('Height', body, html, computedStyle),
width: getSize('Width', body, html, computedStyle)
};
}
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty$3 = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
var _extends$1 = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
/**
* Given element offsets, generate an output similar to getBoundingClientRect
* @method
* @memberof Popper.Utils
* @argument {Object} offsets
* @returns {Object} ClientRect like output
*/
function getClientRect(offsets) {
return _extends$1({}, offsets, {
right: offsets.left + offsets.width,
bottom: offsets.top + offsets.height
});
}
/**
* Get bounding client rect of given element
* @method
* @memberof Popper.Utils
* @param {HTMLElement} element
* @return {Object} client rect
*/
function getBoundingClientRect(element) {
var rect = {};
// IE10 10 FIX: Please, don't ask, the element isn't
// considered in DOM in some circumstances...
// This isn't reproducible in IE10 compatibility mode of IE11
try {
if (isIE(10)) {
rect = element.getBoundingClientRect();
var scrollTop = getScroll(element, 'top');
var scrollLeft = getScroll(element, 'left');
rect.top += scrollTop;
rect.left += scrollLeft;
rect.bottom += scrollTop;
rect.right += scrollLeft;
} else {
rect = element.getBoundingClientRect();
}
} catch (e) {}
var result = {
left: rect.left,
top: rect.top,
width: rect.right - rect.left,
height: rect.bottom - rect.top
};
// subtract scrollbar size from sizes
var sizes = element.nodeName === 'HTML' ? getWindowSizes(element.ownerDocument) : {};
var width = sizes.width || element.clientWidth || result.width;
var height = sizes.height || element.clientHeight || result.height;
var horizScrollbar = element.offsetWidth - width;
var vertScrollbar = element.offsetHeight - height;
// if an hypothetical scrollbar is detected, we must be sure it's not a `border`
// we make this check conditional for performance reasons
if (horizScrollbar || vertScrollbar) {
var styles = getStyleComputedProperty(element);
horizScrollbar -= getBordersSize(styles, 'x');
vertScrollbar -= getBordersSize(styles, 'y');
result.width -= horizScrollbar;
result.height -= vertScrollbar;
}
return getClientRect(result);
}
function getOffsetRectRelativeToArbitraryNode(children, parent) {
var fixedPosition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var isIE10 = isIE(10);
var isHTML = parent.nodeName === 'HTML';
var childrenRect = getBoundingClientRect(children);
var parentRect = getBoundingClientRect(parent);
var scrollParent = getScrollParent(children);
var styles = getStyleComputedProperty(parent);
var borderTopWidth = parseFloat(styles.borderTopWidth);
var borderLeftWidth = parseFloat(styles.borderLeftWidth);
// In cases where the parent is fixed, we must ignore negative scroll in offset calc
if (fixedPosition && isHTML) {
parentRect.top = Math.max(parentRect.top, 0);
parentRect.left = Math.max(parentRect.left, 0);
}
var offsets = getClientRect({
top: childrenRect.top - parentRect.top - borderTopWidth,
left: childrenRect.left - parentRect.left - borderLeftWidth,
width: childrenRect.width,
height: childrenRect.height
});
offsets.marginTop = 0;
offsets.marginLeft = 0;
// Subtract margins of documentElement in case it's being used as parent
// we do this only on HTML because it's the only element that behaves
// differently when margins are applied to it. The margins are included in
// the box of the documentElement, in the other cases not.
if (!isIE10 && isHTML) {
var marginTop = parseFloat(styles.marginTop);
var marginLeft = parseFloat(styles.marginLeft);
offsets.top -= borderTopWidth - marginTop;
offsets.bottom -= borderTopWidth - marginTop;
offsets.left -= borderLeftWidth - marginLeft;
offsets.right -= borderLeftWidth - marginLeft;
// Attach marginTop and marginLeft because in some circumstances we may need them
offsets.marginTop = marginTop;
offsets.marginLeft = marginLeft;
}
if (isIE10 && !fixedPosition ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') {
offsets = includeScroll(offsets, parent);
}
return offsets;
}
function getViewportOffsetRectRelativeToArtbitraryNode(element) {
var excludeScroll = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var html = element.ownerDocument.documentElement;
var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html);
var width = Math.max(html.clientWidth, window.innerWidth || 0);
var height = Math.max(html.clientHeight, window.innerHeight || 0);
var scrollTop = !excludeScroll ? getScroll(html) : 0;
var scrollLeft = !excludeScroll ? getScroll(html, 'left') : 0;
var offset = {
top: scrollTop - relativeOffset.top + relativeOffset.marginTop,
left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft,
width: width,
height: height
};
return getClientRect(offset);
}
/**
* Check if the given element is fixed or is inside a fixed parent
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @argument {Element} customContainer
* @returns {Boolean} answer to "isFixed?"
*/
function isFixed(element) {
var nodeName = element.nodeName;
if (nodeName === 'BODY' || nodeName === 'HTML') {
return false;
}
if (getStyleComputedProperty(element, 'position') === 'fixed') {
return true;
}
var parentNode = getParentNode(element);
if (!parentNode) {
return false;
}
return isFixed(parentNode);
}
/**
* Finds the first parent of an element that has a transformed property defined
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} first transformed parent or documentElement
*/
function getFixedPositionOffsetParent(element) {
// This check is needed to avoid errors in case one of the elements isn't defined for any reason
if (!element || !element.parentElement || isIE()) {
return document.documentElement;
}
var el = element.parentElement;
while (el && getStyleComputedProperty(el, 'transform') === 'none') {
el = el.parentElement;
}
return el || document.documentElement;
}
/**
* Computed the boundaries limits and return them
* @method
* @memberof Popper.Utils
* @param {HTMLElement} popper
* @param {HTMLElement} reference
* @param {number} padding
* @param {HTMLElement} boundariesElement - Element used to define the boundaries
* @param {Boolean} fixedPosition - Is in fixed position mode
* @returns {Object} Coordinates of the boundaries
*/
function getBoundaries(popper, reference, padding, boundariesElement) {
var fixedPosition = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
// NOTE: 1 DOM access here
var boundaries = { top: 0, left: 0 };
var offsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference));
// Handle viewport case
if (boundariesElement === 'viewport') {
boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent, fixedPosition);
} else {
// Handle other cases based on DOM element used as boundaries
var boundariesNode = void 0;
if (boundariesElement === 'scrollParent') {
boundariesNode = getScrollParent(getParentNode(reference));
if (boundariesNode.nodeName === 'BODY') {
boundariesNode = popper.ownerDocument.documentElement;
}
} else if (boundariesElement === 'window') {
boundariesNode = popper.ownerDocument.documentElement;
} else {
boundariesNode = boundariesElement;
}
var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent, fixedPosition);
// In case of HTML, we need a different computation
if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) {
var _getWindowSizes = getWindowSizes(popper.ownerDocument),
height = _getWindowSizes.height,
width = _getWindowSizes.width;
boundaries.top += offsets.top - offsets.marginTop;
boundaries.bottom = height + offsets.top;
boundaries.left += offsets.left - offsets.marginLeft;
boundaries.right = width + offsets.left;
} else {
// for all the other DOM elements, this one is good
boundaries = offsets;
}
}
// Add paddings
padding = padding || 0;
var isPaddingNumber = typeof padding === 'number';
boundaries.left += isPaddingNumber ? padding : padding.left || 0;
boundaries.top += isPaddingNumber ? padding : padding.top || 0;
boundaries.right -= isPaddingNumber ? padding : padding.right || 0;
boundaries.bottom -= isPaddingNumber ? padding : padding.bottom || 0;
return boundaries;
}
function getArea(_ref) {
var width = _ref.width,
height = _ref.height;
return width * height;
}
/**
* Utility used to transform the `auto` placement to the placement with more
* available space.
* @method
* @memberof Popper.Utils
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) {
var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
if (placement.indexOf('auto') === -1) {
return placement;
}
var boundaries = getBoundaries(popper, reference, padding, boundariesElement);
var rects = {
top: {
width: boundaries.width,
height: refRect.top - boundaries.top
},
right: {
width: boundaries.right - refRect.right,
height: boundaries.height
},
bottom: {
width: boundaries.width,
height: boundaries.bottom - refRect.bottom
},
left: {
width: refRect.left - boundaries.left,
height: boundaries.height
}
};
var sortedAreas = Object.keys(rects).map(function (key) {
return _extends$1({
key: key
}, rects[key], {
area: getArea(rects[key])
});
}).sort(function (a, b) {
return b.area - a.area;
});
var filteredAreas = sortedAreas.filter(function (_ref2) {
var width = _ref2.width,
height = _ref2.height;
return width >= popper.clientWidth && height >= popper.clientHeight;
});
var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;
var variation = placement.split('-')[1];
return computedPlacement + (variation ? '-' + variation : '');
}
/**
* Get offsets to the reference element
* @method
* @memberof Popper.Utils
* @param {Object} state
* @param {Element} popper - the popper element
* @param {Element} reference - the reference element (the popper will be relative to this)
* @param {Element} fixedPosition - is in fixed position mode
* @returns {Object} An object containing the offsets which will be applied to the popper
*/
function getReferenceOffsets(state, popper, reference) {
var fixedPosition = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var commonOffsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference));
return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent, fixedPosition);
}
/**
* Get the outer sizes of the given element (offset size + margins)
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Object} object containing width and height properties
*/
function getOuterSizes(element) {
var window = element.ownerDocument.defaultView;
var styles = window.getComputedStyle(element);
var x = parseFloat(styles.marginTop || 0) + parseFloat(styles.marginBottom || 0);
var y = parseFloat(styles.marginLeft || 0) + parseFloat(styles.marginRight || 0);
var result = {
width: element.offsetWidth + y,
height: element.offsetHeight + x
};
return result;
}
/**
* Get the opposite placement of the given one
* @method
* @memberof Popper.Utils
* @argument {String} placement
* @returns {String} flipped placement
*/
function getOppositePlacement(placement) {
var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };
return placement.replace(/left|right|bottom|top/g, function (matched) {
return hash[matched];
});
}
/**
* Get offsets to the popper
* @method
* @memberof Popper.Utils
* @param {Object} position - CSS position the Popper will get applied
* @param {HTMLElement} popper - the popper element
* @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)
* @param {String} placement - one of the valid placement options
* @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
*/
function getPopperOffsets(popper, referenceOffsets, placement) {
placement = placement.split('-')[0];
// Get popper node sizes
var popperRect = getOuterSizes(popper);
// Add position, width and height to our offsets object
var popperOffsets = {
width: popperRect.width,
height: popperRect.height
};
// depending by the popper placement we have to compute its offsets slightly differently
var isHoriz = ['right', 'left'].indexOf(placement) !== -1;
var mainSide = isHoriz ? 'top' : 'left';
var secondarySide = isHoriz ? 'left' : 'top';
var measurement = isHoriz ? 'height' : 'width';
var secondaryMeasurement = !isHoriz ? 'height' : 'width';
popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;
if (placement === secondarySide) {
popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
} else {
popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];
}
return popperOffsets;
}
/**
* Mimics the `find` method of Array
* @method
* @memberof Popper.Utils
* @argument {Array} arr
* @argument prop
* @argument value
* @returns index or -1
*/
function find(arr, check) {
// use native find if supported
if (Array.prototype.find) {
return arr.find(check);
}
// use `filter` to obtain the same behavior of `find`
return arr.filter(check)[0];
}
/**
* Return the index of the matching object
* @method
* @memberof Popper.Utils
* @argument {Array} arr
* @argument prop
* @argument value
* @returns index or -1
*/
function findIndex(arr, prop, value) {
// use native findIndex if supported
if (Array.prototype.findIndex) {
return arr.findIndex(function (cur) {
return cur[prop] === value;
});
}
// use `find` + `indexOf` if `findIndex` isn't supported
var match = find(arr, function (obj) {
return obj[prop] === value;
});
return arr.indexOf(match);
}
/**
* Loop trough the list of modifiers and run them in order,
* each of them will then edit the data object.
* @method
* @memberof Popper.Utils
* @param {dataObject} data
* @param {Array} modifiers
* @param {String} ends - Optional modifier name used as stopper
* @returns {dataObject}
*/
function runModifiers(modifiers, data, ends) {
var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends));
modifiersToRun.forEach(function (modifier) {
if (modifier['function']) {
// eslint-disable-line dot-notation
console.warn('`modifier.function` is deprecated, use `modifier.fn`!');
}
var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation
if (modifier.enabled && isFunction$2(fn)) {
// Add properties to offsets to make them a complete clientRect object
// we do this before each modifier to make sure the previous one doesn't
// mess with these values
data.offsets.popper = getClientRect(data.offsets.popper);
data.offsets.reference = getClientRect(data.offsets.reference);
data = fn(data, modifier);
}
});
return data;
}
/**
* Updates the position of the popper, computing the new offsets and applying
* the new style.<br />
* Prefer `scheduleUpdate` over `update` because of performance reasons.
* @method
* @memberof Popper
*/
function update() {
// if popper is destroyed, don't perform any further update
if (this.state.isDestroyed) {
return;
}
var data = {
instance: this,
styles: {},
arrowStyles: {},
attributes: {},
flipped: false,
offsets: {}
};
// compute reference element offsets
data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference, this.options.positionFixed);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding);
// store the computed placement inside `originalPlacement`
data.originalPlacement = data.placement;
data.positionFixed = this.options.positionFixed;
// compute the popper offsets
data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement);
data.offsets.popper.position = this.options.positionFixed ? 'fixed' : 'absolute';
// run the modifiers
data = runModifiers(this.modifiers, data);
// the first `update` will call `onCreate` callback
// the other ones will call `onUpdate` callback
if (!this.state.isCreated) {
this.state.isCreated = true;
this.options.onCreate(data);
} else {
this.options.onUpdate(data);
}
}
/**
* Helper used to know if the given modifier is enabled.
* @method
* @memberof Popper.Utils
* @returns {Boolean}
*/
function isModifierEnabled(modifiers, modifierName) {
return modifiers.some(function (_ref) {
var name = _ref.name,
enabled = _ref.enabled;
return enabled && name === modifierName;
});
}
/**
* Get the prefixed supported property name
* @method
* @memberof Popper.Utils
* @argument {String} property (camelCase)
* @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)
*/
function getSupportedPropertyName(property) {
var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];
var upperProp = property.charAt(0).toUpperCase() + property.slice(1);
for (var i = 0; i < prefixes.length; i++) {
var prefix = prefixes[i];
var toCheck = prefix ? '' + prefix + upperProp : property;
if (typeof document.body.style[toCheck] !== 'undefined') {
return toCheck;
}
}
return null;
}
/**
* Destroys the popper.
* @method
* @memberof Popper
*/
function destroy() {
this.state.isDestroyed = true;
// touch DOM only if `applyStyle` modifier is enabled
if (isModifierEnabled(this.modifiers, 'applyStyle')) {
this.popper.removeAttribute('x-placement');
this.popper.style.position = '';
this.popper.style.top = '';
this.popper.style.left = '';
this.popper.style.right = '';
this.popper.style.bottom = '';
this.popper.style.willChange = '';
this.popper.style[getSupportedPropertyName('transform')] = '';
}
this.disableEventListeners();
// remove the popper if user explicitly asked for the deletion on destroy
// do not use `remove` because IE11 doesn't support it
if (this.options.removeOnDestroy) {
this.popper.parentNode.removeChild(this.popper);
}
return this;
}
/**
* Get the window associated with the element
* @argument {Element} element
* @returns {Window}
*/
function getWindow(element) {
var ownerDocument = element.ownerDocument;
return ownerDocument ? ownerDocument.defaultView : window;
}
function attachToScrollParents(scrollParent, event, callback, scrollParents) {
var isBody = scrollParent.nodeName === 'BODY';
var target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent;
target.addEventListener(event, callback, { passive: true });
if (!isBody) {
attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents);
}
scrollParents.push(target);
}
/**
* Setup needed event listeners used to update the popper position
* @method
* @memberof Popper.Utils
* @private
*/
function setupEventListeners(reference, options, state, updateBound) {
// Resize event listener on window
state.updateBound = updateBound;
getWindow(reference).addEventListener('resize', state.updateBound, { passive: true });
// Scroll event listener on scroll parents
var scrollElement = getScrollParent(reference);
attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents);
state.scrollElement = scrollElement;
state.eventsEnabled = true;
return state;
}
/**
* It will add resize/scroll events and start recalculating
* position of the popper element when they are triggered.
* @method
* @memberof Popper
*/
function enableEventListeners() {
if (!this.state.eventsEnabled) {
this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate);
}
}
/**
* Remove event listeners used to update the popper position
* @method
* @memberof Popper.Utils
* @private
*/
function removeEventListeners(reference, state) {
// Remove resize event listener on window
getWindow(reference).removeEventListener('resize', state.updateBound);
// Remove scroll event listener on scroll parents
state.scrollParents.forEach(function (target) {
target.removeEventListener('scroll', state.updateBound);
});
// Reset state
state.updateBound = null;
state.scrollParents = [];
state.scrollElement = null;
state.eventsEnabled = false;
return state;
}
/**
* It will remove resize/scroll events and won't recalculate popper position
* when they are triggered. It also won't trigger `onUpdate` callback anymore,
* unless you call `update` method manually.
* @method
* @memberof Popper
*/
function disableEventListeners() {
if (this.state.eventsEnabled) {
cancelAnimationFrame(this.scheduleUpdate);
this.state = removeEventListeners(this.reference, this.state);
}
}
/**
* Tells if a given input is a number
* @method
* @memberof Popper.Utils
* @param {*} input to check
* @return {Boolean}
*/
function isNumeric(n) {
return n !== '' && !isNaN(parseFloat(n)) && isFinite(n);
}
/**
* Set the style to the given popper
* @method
* @memberof Popper.Utils
* @argument {Element} element - Element to apply the style to
* @argument {Object} styles
* Object with a list of properties and values which will be applied to the element
*/
function setStyles(element, styles) {
Object.keys(styles).forEach(function (prop) {
var unit = '';
// add unit if the value is numeric and is one of the following
if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) {
unit = 'px';
}
element.style[prop] = styles[prop] + unit;
});
}
/**
* Set the attributes to the given popper
* @method
* @memberof Popper.Utils
* @argument {Element} element - Element to apply the attributes to
* @argument {Object} styles
* Object with a list of properties and values which will be applied to the element
*/
function setAttributes(element, attributes) {
Object.keys(attributes).forEach(function (prop) {
var value = attributes[prop];
if (value !== false) {
element.setAttribute(prop, attributes[prop]);
} else {
element.removeAttribute(prop);
}
});
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} data.styles - List of style properties - values to apply to popper element
* @argument {Object} data.attributes - List of attribute properties - values to apply to popper element
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The same data object
*/
function applyStyle(data) {
// any property present in `data.styles` will be applied to the popper,
// in this way we can make the 3rd party modifiers add custom styles to it
// Be aware, modifiers could override the properties defined in the previous
// lines of this modifier!
setStyles(data.instance.popper, data.styles);
// any property present in `data.attributes` will be applied to the popper,
// they will be set as HTML attributes of the element
setAttributes(data.instance.popper, data.attributes);
// if arrowElement is defined and arrowStyles has some properties
if (data.arrowElement && Object.keys(data.arrowStyles).length) {
setStyles(data.arrowElement, data.arrowStyles);
}
return data;
}
/**
* Set the x-placement attribute before everything else because it could be used
* to add margins to the popper margins needs to be calculated to get the
* correct popper offsets.
* @method
* @memberof Popper.modifiers
* @param {HTMLElement} reference - The reference element used to position the popper
* @param {HTMLElement} popper - The HTML element used as popper
* @param {Object} options - Popper.js options
*/
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) {
// compute reference element offsets
var referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);
popper.setAttribute('x-placement', placement);
// Apply `position` to popper before anything else because
// without the position applied we can't guarantee correct computations
setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' });
return options;
}
/**
* @function
* @memberof Popper.Utils
* @argument {Object} data - The data object generated by `update` method
* @argument {Boolean} shouldRound - If the offsets should be rounded at all
* @returns {Object} The popper's position offsets rounded
*
* The tale of pixel-perfect positioning. It's still not 100% perfect, but as
* good as it can be within reason.
* Discussion here: https://github.com/FezVrasta/popper.js/pull/715
*
* Low DPI screens cause a popper to be blurry if not using full pixels (Safari
* as well on High DPI screens).
*
* Firefox prefers no rounding for positioning and does not have blurriness on
* high DPI screens.
*
* Only horizontal placement and left/right values need to be considered.
*/
function getRoundedOffsets(data, shouldRound) {
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var round = Math.round,
floor = Math.floor;
var noRound = function noRound(v) {
return v;
};
var referenceWidth = round(reference.width);
var popperWidth = round(popper.width);
var isVertical = ['left', 'right'].indexOf(data.placement) !== -1;
var isVariation = data.placement.indexOf('-') !== -1;
var sameWidthParity = referenceWidth % 2 === popperWidth % 2;
var bothOddWidth = referenceWidth % 2 === 1 && popperWidth % 2 === 1;
var horizontalToInteger = !shouldRound ? noRound : isVertical || isVariation || sameWidthParity ? round : floor;
var verticalToInteger = !shouldRound ? noRound : round;
return {
left: horizontalToInteger(bothOddWidth && !isVariation && shouldRound ? popper.left - 1 : popper.left),
top: verticalToInteger(popper.top),
bottom: verticalToInteger(popper.bottom),
right: horizontalToInteger(popper.right)
};
}
var isFirefox = isBrowser && /Firefox/i.test(navigator.userAgent);
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function computeStyle(data, options) {
var x = options.x,
y = options.y;
var popper = data.offsets.popper;
// Remove this legacy support in Popper.js v2
var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) {
return modifier.name === 'applyStyle';
}).gpuAcceleration;
if (legacyGpuAccelerationOption !== undefined) {
console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!');
}
var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration;
var offsetParent = getOffsetParent(data.instance.popper);
var offsetParentRect = getBoundingClientRect(offsetParent);
// Styles
var styles = {
position: popper.position
};
var offsets = getRoundedOffsets(data, window.devicePixelRatio < 2 || !isFirefox);
var sideA = x === 'bottom' ? 'top' : 'bottom';
var sideB = y === 'right' ? 'left' : 'right';
// if gpuAcceleration is set to `true` and transform is supported,
// we use `translate3d` to apply the position to the popper we
// automatically use the supported prefixed version if needed
var prefixedProperty = getSupportedPropertyName('transform');
// now, let's make a step back and look at this code closely (wtf?)
// If the content of the popper grows once it's been positioned, it
// may happen that the popper gets misplaced because of the new content
// overflowing its reference element
// To avoid this problem, we provide two options (x and y), which allow
// the consumer to define the offset origin.
// If we position a popper on top of a reference element, we can set
// `x` to `top` to make the popper grow towards its top instead of
// its bottom.
var left = void 0,
top = void 0;
if (sideA === 'bottom') {
// when offsetParent is <html> the positioning is relative to the bottom of the screen (excluding the scrollbar)
// and not the bottom of the html element
if (offsetParent.nodeName === 'HTML') {
top = -offsetParent.clientHeight + offsets.bottom;
} else {
top = -offsetParentRect.height + offsets.bottom;
}
} else {
top = offsets.top;
}
if (sideB === 'right') {
if (offsetParent.nodeName === 'HTML') {
left = -offsetParent.clientWidth + offsets.right;
} else {
left = -offsetParentRect.width + offsets.right;
}
} else {
left = offsets.left;
}
if (gpuAcceleration && prefixedProperty) {
styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)';
styles[sideA] = 0;
styles[sideB] = 0;
styles.willChange = 'transform';
} else {
// othwerise, we use the standard `top`, `left`, `bottom` and `right` properties
var invertTop = sideA === 'bottom' ? -1 : 1;
var invertLeft = sideB === 'right' ? -1 : 1;
styles[sideA] = top * invertTop;
styles[sideB] = left * invertLeft;
styles.willChange = sideA + ', ' + sideB;
}
// Attributes
var attributes = {
'x-placement': data.placement
};
// Update `data` attributes, styles and arrowStyles
data.attributes = _extends$1({}, attributes, data.attributes);
data.styles = _extends$1({}, styles, data.styles);
data.arrowStyles = _extends$1({}, data.offsets.arrow, data.arrowStyles);
return data;
}
/**
* Helper used to know if the given modifier depends from another one.<br />
* It checks if the needed modifier is listed and enabled.
* @method
* @memberof Popper.Utils
* @param {Array} modifiers - list of modifiers
* @param {String} requestingName - name of requesting modifier
* @param {String} requestedName - name of requested modifier
* @returns {Boolean}
*/
function isModifierRequired(modifiers, requestingName, requestedName) {
var requesting = find(modifiers, function (_ref) {
var name = _ref.name;
return name === requestingName;
});
var isRequired = !!requesting && modifiers.some(function (modifier) {
return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order;
});
if (!isRequired) {
var _requesting = '`' + requestingName + '`';
var requested = '`' + requestedName + '`';
console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!');
}
return isRequired;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function arrow(data, options) {
var _data$offsets$arrow;
// arrow depends on keepTogether in order to work
if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) {
return data;
}
var arrowElement = options.element;
// if arrowElement is a string, suppose it's a CSS selector
if (typeof arrowElement === 'string') {
arrowElement = data.instance.popper.querySelector(arrowElement);
// if arrowElement is not found, don't run the modifier
if (!arrowElement) {
return data;
}
} else {
// if the arrowElement isn't a query selector we must check that the
// provided DOM node is child of its popper node
if (!data.instance.popper.contains(arrowElement)) {
console.warn('WARNING: `arrow.element` must be child of its popper element!');
return data;
}
}
var placement = data.placement.split('-')[0];
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var isVertical = ['left', 'right'].indexOf(placement) !== -1;
var len = isVertical ? 'height' : 'width';
var sideCapitalized = isVertical ? 'Top' : 'Left';
var side = sideCapitalized.toLowerCase();
var altSide = isVertical ? 'left' : 'top';
var opSide = isVertical ? 'bottom' : 'right';
var arrowElementSize = getOuterSizes(arrowElement)[len];
//
// extends keepTogether behavior making sure the popper and its
// reference have enough pixels in conjunction
//
// top/left side
if (reference[opSide] - arrowElementSize < popper[side]) {
data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize);
}
// bottom/right side
if (reference[side] + arrowElementSize > popper[opSide]) {
data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide];
}
data.offsets.popper = getClientRect(data.offsets.popper);
// compute center of the popper
var center = reference[side] + reference[len] / 2 - arrowElementSize / 2;
// Compute the sideValue using the updated popper offsets
// take popper margin in account because we don't have this info available
var css = getStyleComputedProperty(data.instance.popper);
var popperMarginSide = parseFloat(css['margin' + sideCapitalized]);
var popperBorderSide = parseFloat(css['border' + sideCapitalized + 'Width']);
var sideValue = center - data.offsets.popper[side] - popperMarginSide - popperBorderSide;
// prevent arrowElement from being placed not contiguously to its popper
sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0);
data.arrowElement = arrowElement;
data.offsets.arrow = (_data$offsets$arrow = {}, defineProperty$3(_data$offsets$arrow, side, Math.round(sideValue)), defineProperty$3(_data$offsets$arrow, altSide, ''), _data$offsets$arrow);
return data;
}
/**
* Get the opposite placement variation of the given one
* @method
* @memberof Popper.Utils
* @argument {String} placement variation
* @returns {String} flipped placement variation
*/
function getOppositeVariation(variation) {
if (variation === 'end') {
return 'start';
} else if (variation === 'start') {
return 'end';
}
return variation;
}
/**
* List of accepted placements to use as values of the `placement` option.<br />
* Valid placements are:
* - `auto`
* - `top`
* - `right`
* - `bottom`
* - `left`
*
* Each placement can have a variation from this list:
* - `-start`
* - `-end`
*
* Variations are interpreted easily if you think of them as the left to right
* written languages. Horizontally (`top` and `bottom`), `start` is left and `end`
* is right.<br />
* Vertically (`left` and `right`), `start` is top and `end` is bottom.
*
* Some valid examples are:
* - `top-end` (on top of reference, right aligned)
* - `right-start` (on right of reference, top aligned)
* - `bottom` (on bottom, centered)
* - `auto-end` (on the side with more space available, alignment depends by placement)
*
* @static
* @type {Array}
* @enum {String}
* @readonly
* @method placements
* @memberof Popper
*/
var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start'];
// Get rid of `auto` `auto-start` and `auto-end`
var validPlacements = placements.slice(3);
/**
* Given an initial placement, returns all the subsequent placements
* clockwise (or counter-clockwise).
*
* @method
* @memberof Popper.Utils
* @argument {String} placement - A valid placement (it accepts variations)
* @argument {Boolean} counter - Set to true to walk the placements counterclockwise
* @returns {Array} placements including their variations
*/
function clockwise(placement) {
var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var index = validPlacements.indexOf(placement);
var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index));
return counter ? arr.reverse() : arr;
}
var BEHAVIORS = {
FLIP: 'flip',
CLOCKWISE: 'clockwise',
COUNTERCLOCKWISE: 'counterclockwise'
};
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function flip(data, options) {
// if `inner` modifier is enabled, we can't use the `flip` modifier
if (isModifierEnabled(data.instance.modifiers, 'inner')) {
return data;
}
if (data.flipped && data.placement === data.originalPlacement) {
// seems like flip is trying to loop, probably there's not enough space on any of the flippable sides
return data;
}
var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement, data.positionFixed);
var placement = data.placement.split('-')[0];
var placementOpposite = getOppositePlacement(placement);
var variation = data.placement.split('-')[1] || '';
var flipOrder = [];
switch (options.behavior) {
case BEHAVIORS.FLIP:
flipOrder = [placement, placementOpposite];
break;
case BEHAVIORS.CLOCKWISE:
flipOrder = clockwise(placement);
break;
case BEHAVIORS.COUNTERCLOCKWISE:
flipOrder = clockwise(placement, true);
break;
default:
flipOrder = options.behavior;
}
flipOrder.forEach(function (step, index) {
if (placement !== step || flipOrder.length === index + 1) {
return data;
}
placement = data.placement.split('-')[0];
placementOpposite = getOppositePlacement(placement);
var popperOffsets = data.offsets.popper;
var refOffsets = data.offsets.reference;
// using floor because the reference offsets may contain decimals we are not going to consider here
var floor = Math.floor;
var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom);
var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left);
var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right);
var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top);
var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom);
var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom;
// flip the variation if required
var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
// flips variation if reference element overflows boundaries
var flippedVariationByRef = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom);
// flips variation if popper content overflows boundaries
var flippedVariationByContent = !!options.flipVariationsByContent && (isVertical && variation === 'start' && overflowsRight || isVertical && variation === 'end' && overflowsLeft || !isVertical && variation === 'start' && overflowsBottom || !isVertical && variation === 'end' && overflowsTop);
var flippedVariation = flippedVariationByRef || flippedVariationByContent;
if (overlapsRef || overflowsBoundaries || flippedVariation) {
// this boolean to detect any flip loop
data.flipped = true;
if (overlapsRef || overflowsBoundaries) {
placement = flipOrder[index + 1];
}
if (flippedVariation) {
variation = getOppositeVariation(variation);
}
data.placement = placement + (variation ? '-' + variation : '');
// this object contains `position`, we want to preserve it along with
// any additional property we may add in the future
data.offsets.popper = _extends$1({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement));
data = runModifiers(data.instance.modifiers, data, 'flip');
}
});
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function keepTogether(data) {
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var placement = data.placement.split('-')[0];
var floor = Math.floor;
var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
var side = isVertical ? 'right' : 'bottom';
var opSide = isVertical ? 'left' : 'top';
var measurement = isVertical ? 'width' : 'height';
if (popper[side] < floor(reference[opSide])) {
data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement];
}
if (popper[opSide] > floor(reference[side])) {
data.offsets.popper[opSide] = floor(reference[side]);
}
return data;
}
/**
* Converts a string containing value + unit into a px value number
* @function
* @memberof {modifiers~offset}
* @private
* @argument {String} str - Value + unit string
* @argument {String} measurement - `height` or `width`
* @argument {Object} popperOffsets
* @argument {Object} referenceOffsets
* @returns {Number|String}
* Value in pixels, or original string if no values were extracted
*/
function toValue(str, measurement, popperOffsets, referenceOffsets) {
// separate value from unit
var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/);
var value = +split[1];
var unit = split[2];
// If it's not a number it's an operator, I guess
if (!value) {
return str;
}
if (unit.indexOf('%') === 0) {
var element = void 0;
switch (unit) {
case '%p':
element = popperOffsets;
break;
case '%':
case '%r':
default:
element = referenceOffsets;
}
var rect = getClientRect(element);
return rect[measurement] / 100 * value;
} else if (unit === 'vh' || unit === 'vw') {
// if is a vh or vw, we calculate the size based on the viewport
var size = void 0;
if (unit === 'vh') {
size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
} else {
size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}
return size / 100 * value;
} else {
// if is an explicit pixel unit, we get rid of the unit and keep the value
// if is an implicit unit, it's px, and we return just the value
return value;
}
}
/**
* Parse an `offset` string to extrapolate `x` and `y` numeric offsets.
* @function
* @memberof {modifiers~offset}
* @private
* @argument {String} offset
* @argument {Object} popperOffsets
* @argument {Object} referenceOffsets
* @argument {String} basePlacement
* @returns {Array} a two cells array with x and y offsets in numbers
*/
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) {
var offsets = [0, 0];
// Use height if placement is left or right and index is 0 otherwise use width
// in this way the first offset will use an axis and the second one
// will use the other one
var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1;
// Split the offset string to obtain a list of values and operands
// The regex addresses values with the plus or minus sign in front (+10, -20, etc)
var fragments = offset.split(/(\+|\-)/).map(function (frag) {
return frag.trim();
});
// Detect if the offset string contains a pair of values or a single one
// they could be separated by comma or space
var divider = fragments.indexOf(find(fragments, function (frag) {
return frag.search(/,|\s/) !== -1;
}));
if (fragments[divider] && fragments[divider].indexOf(',') === -1) {
console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');
}
// If divider is found, we divide the list of values and operands to divide
// them by ofset X and Y.
var splitRegex = /\s*,\s*|\s+/;
var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments];
// Convert the values with units to absolute pixels to allow our computations
ops = ops.map(function (op, index) {
// Most of the units rely on the orientation of the popper
var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width';
var mergeWithPrevious = false;
return op
// This aggregates any `+` or `-` sign that aren't considered operators
// e.g.: 10 + +5 => [10, +, +5]
.reduce(function (a, b) {
if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) {
a[a.length - 1] = b;
mergeWithPrevious = true;
return a;
} else if (mergeWithPrevious) {
a[a.length - 1] += b;
mergeWithPrevious = false;
return a;
} else {
return a.concat(b);
}
}, [])
// Here we convert the string values into number values (in px)
.map(function (str) {
return toValue(str, measurement, popperOffsets, referenceOffsets);
});
});
// Loop trough the offsets arrays and execute the operations
ops.forEach(function (op, index) {
op.forEach(function (frag, index2) {
if (isNumeric(frag)) {
offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1);
}
});
});
return offsets;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @argument {Number|String} options.offset=0
* The offset value as described in the modifier description
* @returns {Object} The data object, properly modified
*/
function offset(data, _ref) {
var offset = _ref.offset;
var placement = data.placement,
_data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var basePlacement = placement.split('-')[0];
var offsets = void 0;
if (isNumeric(+offset)) {
offsets = [+offset, 0];
} else {
offsets = parseOffset(offset, popper, reference, basePlacement);
}
if (basePlacement === 'left') {
popper.top += offsets[0];
popper.left -= offsets[1];
} else if (basePlacement === 'right') {
popper.top += offsets[0];
popper.left += offsets[1];
} else if (basePlacement === 'top') {
popper.left += offsets[0];
popper.top -= offsets[1];
} else if (basePlacement === 'bottom') {
popper.left += offsets[0];
popper.top += offsets[1];
}
data.popper = popper;
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function preventOverflow(data, options) {
var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper);
// If offsetParent is the reference element, we really want to
// go one step up and use the next offsetParent as reference to
// avoid to make this modifier completely useless and look like broken
if (data.instance.reference === boundariesElement) {
boundariesElement = getOffsetParent(boundariesElement);
}
// NOTE: DOM access here
// resets the popper's position so that the document size can be calculated excluding
// the size of the popper element itself
var transformProp = getSupportedPropertyName('transform');
var popperStyles = data.instance.popper.style; // assignment to help minification
var top = popperStyles.top,
left = popperStyles.left,
transform = popperStyles[transformProp];
popperStyles.top = '';
popperStyles.left = '';
popperStyles[transformProp] = '';
var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement, data.positionFixed);
// NOTE: DOM access here
// restores the original style properties after the offsets have been computed
popperStyles.top = top;
popperStyles.left = left;
popperStyles[transformProp] = transform;
options.boundaries = boundaries;
var order = options.priority;
var popper = data.offsets.popper;
var check = {
primary: function primary(placement) {
var value = popper[placement];
if (popper[placement] < boundaries[placement] && !options.escapeWithReference) {
value = Math.max(popper[placement], boundaries[placement]);
}
return defineProperty$3({}, placement, value);
},
secondary: function secondary(placement) {
var mainSide = placement === 'right' ? 'left' : 'top';
var value = popper[mainSide];
if (popper[placement] > boundaries[placement] && !options.escapeWithReference) {
value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height));
}
return defineProperty$3({}, mainSide, value);
}
};
order.forEach(function (placement) {
var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary';
popper = _extends$1({}, popper, check[side](placement));
});
data.offsets.popper = popper;
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function shift(data) {
var placement = data.placement;
var basePlacement = placement.split('-')[0];
var shiftvariation = placement.split('-')[1];
// if shift shiftvariation is specified, run the modifier
if (shiftvariation) {
var _data$offsets = data.offsets,
reference = _data$offsets.reference,
popper = _data$offsets.popper;
var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;
var side = isVertical ? 'left' : 'top';
var measurement = isVertical ? 'width' : 'height';
var shiftOffsets = {
start: defineProperty$3({}, side, reference[side]),
end: defineProperty$3({}, side, reference[side] + reference[measurement] - popper[measurement])
};
data.offsets.popper = _extends$1({}, popper, shiftOffsets[shiftvariation]);
}
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function hide(data) {
if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) {
return data;
}
var refRect = data.offsets.reference;
var bound = find(data.instance.modifiers, function (modifier) {
return modifier.name === 'preventOverflow';
}).boundaries;
if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) {
// Avoid unnecessary DOM access if visibility hasn't changed
if (data.hide === true) {
return data;
}
data.hide = true;
data.attributes['x-out-of-boundaries'] = '';
} else {
// Avoid unnecessary DOM access if visibility hasn't changed
if (data.hide === false) {
return data;
}
data.hide = false;
data.attributes['x-out-of-boundaries'] = false;
}
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function inner(data) {
var placement = data.placement;
var basePlacement = placement.split('-')[0];
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1;
var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1;
popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0);
data.placement = getOppositePlacement(placement);
data.offsets.popper = getClientRect(popper);
return data;
}
/**
* Modifier function, each modifier can have a function of this type assigned
* to its `fn` property.<br />
* These functions will be called on each update, this means that you must
* make sure they are performant enough to avoid performance bottlenecks.
*
* @function ModifierFn
* @argument {dataObject} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {dataObject} The data object, properly modified
*/
/**
* Modifiers are plugins used to alter the behavior of your poppers.<br />
* Popper.js uses a set of 9 modifiers to provide all the basic functionalities
* needed by the library.
*
* Usually you don't want to override the `order`, `fn` and `onLoad` props.
* All the other properties are configurations that could be tweaked.
* @namespace modifiers
*/
var modifiers = {
/**
* Modifier used to shift the popper on the start or end of its reference
* element.<br />
* It will read the variation of the `placement` property.<br />
* It can be one either `-end` or `-start`.
* @memberof modifiers
* @inner
*/
shift: {
/** @prop {number} order=100 - Index used to define the order of execution */
order: 100,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: shift
},
/**
* The `offset` modifier can shift your popper on both its axis.
*
* It accepts the following units:
* - `px` or unit-less, interpreted as pixels
* - `%` or `%r`, percentage relative to the length of the reference element
* - `%p`, percentage relative to the length of the popper element
* - `vw`, CSS viewport width unit
* - `vh`, CSS viewport height unit
*
* For length is intended the main axis relative to the placement of the popper.<br />
* This means that if the placement is `top` or `bottom`, the length will be the
* `width`. In case of `left` or `right`, it will be the `height`.
*
* You can provide a single value (as `Number` or `String`), or a pair of values
* as `String` divided by a comma or one (or more) white spaces.<br />
* The latter is a deprecated method because it leads to confusion and will be
* removed in v2.<br />
* Additionally, it accepts additions and subtractions between different units.
* Note that multiplications and divisions aren't supported.
*
* Valid examples are:
* ```
* 10
* '10%'
* '10, 10'
* '10%, 10'
* '10 + 10%'
* '10 - 5vh + 3%'
* '-10px + 5vh, 5px - 6%'
* ```
* > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap
* > with their reference element, unfortunately, you will have to disable the `flip` modifier.
* > You can read more on this at this [issue](https://github.com/FezVrasta/popper.js/issues/373).
*
* @memberof modifiers
* @inner
*/
offset: {
/** @prop {number} order=200 - Index used to define the order of execution */
order: 200,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: offset,
/** @prop {Number|String} offset=0
* The offset value as described in the modifier description
*/
offset: 0
},
/**
* Modifier used to prevent the popper from being positioned outside the boundary.
*
* A scenario exists where the reference itself is not within the boundaries.<br />
* We can say it has "escaped the boundaries" — or just "escaped".<br />
* In this case we need to decide whether the popper should either:
*
* - detach from the reference and remain "trapped" in the boundaries, or
* - if it should ignore the boundary and "escape with its reference"
*
* When `escapeWithReference` is set to`true` and reference is completely
* outside its boundaries, the popper will overflow (or completely leave)
* the boundaries in order to remain attached to the edge of the reference.
*
* @memberof modifiers
* @inner
*/
preventOverflow: {
/** @prop {number} order=300 - Index used to define the order of execution */
order: 300,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: preventOverflow,
/**
* @prop {Array} [priority=['left','right','top','bottom']]
* Popper will try to prevent overflow following these priorities by default,
* then, it could overflow on the left and on top of the `boundariesElement`
*/
priority: ['left', 'right', 'top', 'bottom'],
/**
* @prop {number} padding=5
* Amount of pixel used to define a minimum distance between the boundaries
* and the popper. This makes sure the popper always has a little padding
* between the edges of its container
*/
padding: 5,
/**
* @prop {String|HTMLElement} boundariesElement='scrollParent'
* Boundaries used by the modifier. Can be `scrollParent`, `window`,
* `viewport` or any DOM element.
*/
boundariesElement: 'scrollParent'
},
/**
* Modifier used to make sure the reference and its popper stay near each other
* without leaving any gap between the two. Especially useful when the arrow is
* enabled and you want to ensure that it points to its reference element.
* It cares only about the first axis. You can still have poppers with margin
* between the popper and its reference element.
* @memberof modifiers
* @inner
*/
keepTogether: {
/** @prop {number} order=400 - Index used to define the order of execution */
order: 400,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: keepTogether
},
/**
* This modifier is used to move the `arrowElement` of the popper to make
* sure it is positioned between the reference element and its popper element.
* It will read the outer size of the `arrowElement` node to detect how many
* pixels of conjunction are needed.
*
* It has no effect if no `arrowElement` is provided.
* @memberof modifiers
* @inner
*/
arrow: {
/** @prop {number} order=500 - Index used to define the order of execution */
order: 500,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: arrow,
/** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */
element: '[x-arrow]'
},
/**
* Modifier used to flip the popper's placement when it starts to overlap its
* reference element.
*
* Requires the `preventOverflow` modifier before it in order to work.
*
* **NOTE:** this modifier will interrupt the current update cycle and will
* restart it if it detects the need to flip the placement.
* @memberof modifiers
* @inner
*/
flip: {
/** @prop {number} order=600 - Index used to define the order of execution */
order: 600,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: flip,
/**
* @prop {String|Array} behavior='flip'
* The behavior used to change the popper's placement. It can be one of
* `flip`, `clockwise`, `counterclockwise` or an array with a list of valid
* placements (with optional variations)
*/
behavior: 'flip',
/**
* @prop {number} padding=5
* The popper will flip if it hits the edges of the `boundariesElement`
*/
padding: 5,
/**
* @prop {String|HTMLElement} boundariesElement='viewport'
* The element which will define the boundaries of the popper position.
* The popper will never be placed outside of the defined boundaries
* (except if `keepTogether` is enabled)
*/
boundariesElement: 'viewport',
/**
* @prop {Boolean} flipVariations=false
* The popper will switch placement variation between `-start` and `-end` when
* the reference element overlaps its boundaries.
*
* The original placement should have a set variation.
*/
flipVariations: false,
/**
* @prop {Boolean} flipVariationsByContent=false
* The popper will switch placement variation between `-start` and `-end` when
* the popper element overlaps its reference boundaries.
*
* The original placement should have a set variation.
*/
flipVariationsByContent: false
},
/**
* Modifier used to make the popper flow toward the inner of the reference element.
* By default, when this modifier is disabled, the popper will be placed outside
* the reference element.
* @memberof modifiers
* @inner
*/
inner: {
/** @prop {number} order=700 - Index used to define the order of execution */
order: 700,
/** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */
enabled: false,
/** @prop {ModifierFn} */
fn: inner
},
/**
* Modifier used to hide the popper when its reference element is outside of the
* popper boundaries. It will set a `x-out-of-boundaries` attribute which can
* be used to hide with a CSS selector the popper when its reference is
* out of boundaries.
*
* Requires the `preventOverflow` modifier before it in order to work.
* @memberof modifiers
* @inner
*/
hide: {
/** @prop {number} order=800 - Index used to define the order of execution */
order: 800,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: hide
},
/**
* Computes the style that will be applied to the popper element to gets
* properly positioned.
*
* Note that this modifier will not touch the DOM, it just prepares the styles
* so that `applyStyle` modifier can apply it. This separation is useful
* in case you need to replace `applyStyle` with a custom implementation.
*
* This modifier has `850` as `order` value to maintain backward compatibility
* with previous versions of Popper.js. Expect the modifiers ordering method
* to change in future major versions of the library.
*
* @memberof modifiers
* @inner
*/
computeStyle: {
/** @prop {number} order=850 - Index used to define the order of execution */
order: 850,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: computeStyle,
/**
* @prop {Boolean} gpuAcceleration=true
* If true, it uses the CSS 3D transformation to position the popper.
* Otherwise, it will use the `top` and `left` properties
*/
gpuAcceleration: true,
/**
* @prop {string} [x='bottom']
* Where to anchor the X axis (`bottom` or `top`). AKA X offset origin.
* Change this if your popper should grow in a direction different from `bottom`
*/
x: 'bottom',
/**
* @prop {string} [x='left']
* Where to anchor the Y axis (`left` or `right`). AKA Y offset origin.
* Change this if your popper should grow in a direction different from `right`
*/
y: 'right'
},
/**
* Applies the computed styles to the popper element.
*
* All the DOM manipulations are limited to this modifier. This is useful in case
* you want to integrate Popper.js inside a framework or view library and you
* want to delegate all the DOM manipulations to it.
*
* Note that if you disable this modifier, you must make sure the popper element
* has its position set to `absolute` before Popper.js can do its work!
*
* Just disable this modifier and define your own to achieve the desired effect.
*
* @memberof modifiers
* @inner
*/
applyStyle: {
/** @prop {number} order=900 - Index used to define the order of execution */
order: 900,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: applyStyle,
/** @prop {Function} */
onLoad: applyStyleOnLoad,
/**
* @deprecated since version 1.10.0, the property moved to `computeStyle` modifier
* @prop {Boolean} gpuAcceleration=true
* If true, it uses the CSS 3D transformation to position the popper.
* Otherwise, it will use the `top` and `left` properties
*/
gpuAcceleration: undefined
}
};
/**
* The `dataObject` is an object containing all the information used by Popper.js.
* This object is passed to modifiers and to the `onCreate` and `onUpdate` callbacks.
* @name dataObject
* @property {Object} data.instance The Popper.js instance
* @property {String} data.placement Placement applied to popper
* @property {String} data.originalPlacement Placement originally defined on init
* @property {Boolean} data.flipped True if popper has been flipped by flip modifier
* @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper
* @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier
* @property {Object} data.styles Any CSS property defined here will be applied to the popper. It expects the JavaScript nomenclature (eg. `marginBottom`)
* @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow. It expects the JavaScript nomenclature (eg. `marginBottom`)
* @property {Object} data.boundaries Offsets of the popper boundaries
* @property {Object} data.offsets The measurements of popper, reference and arrow elements
* @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values
* @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values
* @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0
*/
/**
* Default options provided to Popper.js constructor.<br />
* These can be overridden using the `options` argument of Popper.js.<br />
* To override an option, simply pass an object with the same
* structure of the `options` object, as the 3rd argument. For example:
* ```
* new Popper(ref, pop, {
* modifiers: {
* preventOverflow: { enabled: false }
* }
* })
* ```
* @type {Object}
* @static
* @memberof Popper
*/
var Defaults = {
/**
* Popper's placement.
* @prop {Popper.placements} placement='bottom'
*/
placement: 'bottom',
/**
* Set this to true if you want popper to position it self in 'fixed' mode
* @prop {Boolean} positionFixed=false
*/
positionFixed: false,
/**
* Whether events (resize, scroll) are initially enabled.
* @prop {Boolean} eventsEnabled=true
*/
eventsEnabled: true,
/**
* Set to true if you want to automatically remove the popper when
* you call the `destroy` method.
* @prop {Boolean} removeOnDestroy=false
*/
removeOnDestroy: false,
/**
* Callback called when the popper is created.<br />
* By default, it is set to no-op.<br />
* Access Popper.js instance with `data.instance`.
* @prop {onCreate}
*/
onCreate: function onCreate() {},
/**
* Callback called when the popper is updated. This callback is not called
* on the initialization/creation of the popper, but only on subsequent
* updates.<br />
* By default, it is set to no-op.<br />
* Access Popper.js instance with `data.instance`.
* @prop {onUpdate}
*/
onUpdate: function onUpdate() {},
/**
* List of modifiers used to modify the offsets before they are applied to the popper.
* They provide most of the functionalities of Popper.js.
* @prop {modifiers}
*/
modifiers: modifiers
};
/**
* @callback onCreate
* @param {dataObject} data
*/
/**
* @callback onUpdate
* @param {dataObject} data
*/
// Utils
// Methods
var Popper = function () {
/**
* Creates a new Popper.js instance.
* @class Popper
* @param {Element|referenceObject} reference - The reference element used to position the popper
* @param {Element} popper - The HTML / XML element used as the popper
* @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults)
* @return {Object} instance - The generated Popper.js instance
*/
function Popper(reference, popper) {
var _this = this;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
classCallCheck(this, Popper);
this.scheduleUpdate = function () {
return requestAnimationFrame(_this.update);
};
// make update() debounced, so that it only runs at most once-per-tick
this.update = debounce$1(this.update.bind(this));
// with {} we create a new object with the options inside it
this.options = _extends$1({}, Popper.Defaults, options);
// init state
this.state = {
isDestroyed: false,
isCreated: false,
scrollParents: []
};
// get reference and popper elements (allow jQuery wrappers)
this.reference = reference && reference.jquery ? reference[0] : reference;
this.popper = popper && popper.jquery ? popper[0] : popper;
// Deep merge modifiers options
this.options.modifiers = {};
Object.keys(_extends$1({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) {
_this.options.modifiers[name] = _extends$1({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {});
});
// Refactoring modifiers' list (Object => Array)
this.modifiers = Object.keys(this.options.modifiers).map(function (name) {
return _extends$1({
name: name
}, _this.options.modifiers[name]);
})
// sort the modifiers by order
.sort(function (a, b) {
return a.order - b.order;
});
// modifiers have the ability to execute arbitrary code when Popper.js get inited
// such code is executed in the same order of its modifier
// they could add new properties to their options configuration
// BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`!
this.modifiers.forEach(function (modifierOptions) {
if (modifierOptions.enabled && isFunction$2(modifierOptions.onLoad)) {
modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state);
}
});
// fire the first update to position the popper in the right place
this.update();
var eventsEnabled = this.options.eventsEnabled;
if (eventsEnabled) {
// setup event listeners, they will take care of update the position in specific situations
this.enableEventListeners();
}
this.state.eventsEnabled = eventsEnabled;
}
// We can't use class properties because they don't get listed in the
// class prototype and break stuff like Sinon stubs
createClass(Popper, [{
key: 'update',
value: function update$$1() {
return update.call(this);
}
}, {
key: 'destroy',
value: function destroy$$1() {
return destroy.call(this);
}
}, {
key: 'enableEventListeners',
value: function enableEventListeners$$1() {
return enableEventListeners.call(this);
}
}, {
key: 'disableEventListeners',
value: function disableEventListeners$$1() {
return disableEventListeners.call(this);
}
/**
* Schedules an update. It will run on the next UI update available.
* @method scheduleUpdate
* @memberof Popper
*/
/**
* Collection of utilities useful when writing custom modifiers.
* Starting from version 1.7, this method is available only if you
* include `popper-utils.js` before `popper.js`.
*
* **DEPRECATION**: This way to access PopperUtils is deprecated
* and will be removed in v2! Use the PopperUtils module directly instead.
* Due to the high instability of the methods contained in Utils, we can't
* guarantee them to follow semver. Use them at your own risk!
* @static
* @private
* @type {Object}
* @deprecated since version 1.8
* @member Utils
* @memberof Popper
*/
}]);
return Popper;
}();
/**
* The `referenceObject` is an object that provides an interface compatible with Popper.js
* and lets you use it as replacement of a real DOM node.<br />
* You can use this method to position a popper relatively to a set of coordinates
* in case you don't have a DOM node to use as reference.
*
* ```
* new Popper(referenceObject, popperNode);
* ```
*
* NB: This feature isn't supported in Internet Explorer 10.
* @name referenceObject
* @property {Function} data.getBoundingClientRect
* A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method.
* @property {number} data.clientWidth
* An ES6 getter that will return the width of the virtual reference element.
* @property {number} data.clientHeight
* An ES6 getter that will return the height of the virtual reference element.
*/
Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils;
Popper.placements = placements;
Popper.Defaults = Defaults;
var key = '__global_unique_id__';
var gud = function() {
return commonjsGlobal[key] = (commonjsGlobal[key] || 0) + 1;
};
var implementation$4 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _react2 = _interopRequireDefault(React__default);
var _propTypes2 = _interopRequireDefault(propTypes);
var _gud2 = _interopRequireDefault(gud);
var _warning2 = _interopRequireDefault(warning_1);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MAX_SIGNED_31_BIT_INT = 1073741823;
// Inlined Object.is polyfill.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
function objectIs(x, y) {
if (x === y) {
return x !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function createEventEmitter(value) {
var handlers = [];
return {
on: function on(handler) {
handlers.push(handler);
},
off: function off(handler) {
handlers = handlers.filter(function (h) {
return h !== handler;
});
},
get: function get() {
return value;
},
set: function set(newValue, changedBits) {
value = newValue;
handlers.forEach(function (handler) {
return handler(value, changedBits);
});
}
};
}
function onlyChild(children) {
return Array.isArray(children) ? children[0] : children;
}
function createReactContext(defaultValue, calculateChangedBits) {
var _Provider$childContex, _Consumer$contextType;
var contextProp = '__create-react-context-' + (0, _gud2.default)() + '__';
var Provider = function (_Component) {
_inherits(Provider, _Component);
function Provider() {
var _temp, _this, _ret;
_classCallCheck(this, Provider);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.emitter = createEventEmitter(_this.props.value), _temp), _possibleConstructorReturn(_this, _ret);
}
Provider.prototype.getChildContext = function getChildContext() {
var _ref;
return _ref = {}, _ref[contextProp] = this.emitter, _ref;
};
Provider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.value !== nextProps.value) {
var oldValue = this.props.value;
var newValue = nextProps.value;
var changedBits = void 0;
if (objectIs(oldValue, newValue)) {
changedBits = 0; // No change
} else {
changedBits = typeof calculateChangedBits === 'function' ? calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
{
(0, _warning2.default)((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits);
}
changedBits |= 0;
if (changedBits !== 0) {
this.emitter.set(nextProps.value, changedBits);
}
}
}
};
Provider.prototype.render = function render() {
return this.props.children;
};
return Provider;
}(React__default.Component);
Provider.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[contextProp] = _propTypes2.default.object.isRequired, _Provider$childContex);
var Consumer = function (_Component2) {
_inherits(Consumer, _Component2);
function Consumer() {
var _temp2, _this2, _ret2;
_classCallCheck(this, Consumer);
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _ret2 = (_temp2 = (_this2 = _possibleConstructorReturn(this, _Component2.call.apply(_Component2, [this].concat(args))), _this2), _this2.state = {
value: _this2.getValue()
}, _this2.onUpdate = function (newValue, changedBits) {
var observedBits = _this2.observedBits | 0;
if ((observedBits & changedBits) !== 0) {
_this2.setState({ value: _this2.getValue() });
}
}, _temp2), _possibleConstructorReturn(_this2, _ret2);
}
Consumer.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var observedBits = nextProps.observedBits;
this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT // Subscribe to all changes by default
: observedBits;
};
Consumer.prototype.componentDidMount = function componentDidMount() {
if (this.context[contextProp]) {
this.context[contextProp].on(this.onUpdate);
}
var observedBits = this.props.observedBits;
this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT // Subscribe to all changes by default
: observedBits;
};
Consumer.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.context[contextProp]) {
this.context[contextProp].off(this.onUpdate);
}
};
Consumer.prototype.getValue = function getValue() {
if (this.context[contextProp]) {
return this.context[contextProp].get();
} else {
return defaultValue;
}
};
Consumer.prototype.render = function render() {
return onlyChild(this.props.children)(this.state.value);
};
return Consumer;
}(React__default.Component);
Consumer.contextTypes = (_Consumer$contextType = {}, _Consumer$contextType[contextProp] = _propTypes2.default.object, _Consumer$contextType);
return {
Provider: Provider,
Consumer: Consumer
};
}
exports.default = createReactContext;
module.exports = exports['default'];
});
unwrapExports(implementation$4);
var lib = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
var _react2 = _interopRequireDefault(React__default);
var _implementation2 = _interopRequireDefault(implementation$4);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _react2.default.createContext || _implementation2.default;
module.exports = exports['default'];
});
var createContext = unwrapExports(lib);
var ManagerReferenceNodeContext = createContext();
var ManagerReferenceNodeSetterContext = createContext();
/**
* Takes an argument and if it's an array, returns the first item in the array,
* otherwise returns the argument. Used for Preact compatibility.
*/
var unwrapArray = function unwrapArray(arg) {
return Array.isArray(arg) ? arg[0] : arg;
};
/**
* Takes a maybe-undefined function and arbitrary args and invokes the function
* only if it is defined.
*/
var safeInvoke = function safeInvoke(fn) {
if (typeof fn === "function") {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return fn.apply(void 0, args);
}
};
/**
* Does a shallow equality check of two objects by comparing the reference
* equality of each value.
*/
var shallowEqual = function shallowEqual(objA, objB) {
var aKeys = Object.keys(objA);
var bKeys = Object.keys(objB);
if (bKeys.length !== aKeys.length) {
return false;
}
for (var i = 0; i < bKeys.length; i++) {
var key = aKeys[i];
if (objA[key] !== objB[key]) {
return false;
}
}
return true;
};
/**
* Sets a ref using either a ref callback or a ref object
*/
var setRef = function setRef(ref, node) {
// if its a function call it
if (typeof ref === "function") {
return safeInvoke(ref, node);
} // otherwise we should treat it as a ref object
else if (ref != null) {
ref.current = node;
}
};
var initialStyle = {
position: 'absolute',
top: 0,
left: 0,
opacity: 0,
pointerEvents: 'none'
};
var initialArrowStyle = {};
var InnerPopper =
/*#__PURE__*/
function (_React$Component) {
inheritsLoose(InnerPopper, _React$Component);
function InnerPopper() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
defineProperty(assertThisInitialized(_this), "state", {
data: undefined,
placement: undefined
});
defineProperty(assertThisInitialized(_this), "popperInstance", void 0);
defineProperty(assertThisInitialized(_this), "popperNode", null);
defineProperty(assertThisInitialized(_this), "arrowNode", null);
defineProperty(assertThisInitialized(_this), "setPopperNode", function (popperNode) {
if (!popperNode || _this.popperNode === popperNode) return;
setRef(_this.props.innerRef, popperNode);
_this.popperNode = popperNode;
_this.updatePopperInstance();
});
defineProperty(assertThisInitialized(_this), "setArrowNode", function (arrowNode) {
_this.arrowNode = arrowNode;
});
defineProperty(assertThisInitialized(_this), "updateStateModifier", {
enabled: true,
order: 900,
fn: function fn(data) {
var placement = data.placement;
_this.setState({
data: data,
placement: placement
});
return data;
}
});
defineProperty(assertThisInitialized(_this), "getOptions", function () {
return {
placement: _this.props.placement,
eventsEnabled: _this.props.eventsEnabled,
positionFixed: _this.props.positionFixed,
modifiers: _extends_1({}, _this.props.modifiers, {
arrow: _extends_1({}, _this.props.modifiers && _this.props.modifiers.arrow, {
enabled: !!_this.arrowNode,
element: _this.arrowNode
}),
applyStyle: {
enabled: false
},
updateStateModifier: _this.updateStateModifier
})
};
});
defineProperty(assertThisInitialized(_this), "getPopperStyle", function () {
return !_this.popperNode || !_this.state.data ? initialStyle : _extends_1({
position: _this.state.data.offsets.popper.position
}, _this.state.data.styles);
});
defineProperty(assertThisInitialized(_this), "getPopperPlacement", function () {
return !_this.state.data ? undefined : _this.state.placement;
});
defineProperty(assertThisInitialized(_this), "getArrowStyle", function () {
return !_this.arrowNode || !_this.state.data ? initialArrowStyle : _this.state.data.arrowStyles;
});
defineProperty(assertThisInitialized(_this), "getOutOfBoundariesState", function () {
return _this.state.data ? _this.state.data.hide : undefined;
});
defineProperty(assertThisInitialized(_this), "destroyPopperInstance", function () {
if (!_this.popperInstance) return;
_this.popperInstance.destroy();
_this.popperInstance = null;
});
defineProperty(assertThisInitialized(_this), "updatePopperInstance", function () {
_this.destroyPopperInstance();
var _assertThisInitialize = assertThisInitialized(_this),
popperNode = _assertThisInitialize.popperNode;
var referenceElement = _this.props.referenceElement;
if (!referenceElement || !popperNode) return;
_this.popperInstance = new Popper(referenceElement, popperNode, _this.getOptions());
});
defineProperty(assertThisInitialized(_this), "scheduleUpdate", function () {
if (_this.popperInstance) {
_this.popperInstance.scheduleUpdate();
}
});
return _this;
}
var _proto = InnerPopper.prototype;
_proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
// If the Popper.js options have changed, update the instance (destroy + create)
if (this.props.placement !== prevProps.placement || this.props.referenceElement !== prevProps.referenceElement || this.props.positionFixed !== prevProps.positionFixed || !deepEqual_1(this.props.modifiers, prevProps.modifiers, {
strict: true
})) {
// develop only check that modifiers isn't being updated needlessly
{
if (this.props.modifiers !== prevProps.modifiers && this.props.modifiers != null && prevProps.modifiers != null && shallowEqual(this.props.modifiers, prevProps.modifiers)) {
console.warn("'modifiers' prop reference updated even though all values appear the same.\nConsider memoizing the 'modifiers' object to avoid needless rendering.");
}
}
this.updatePopperInstance();
} else if (this.props.eventsEnabled !== prevProps.eventsEnabled && this.popperInstance) {
this.props.eventsEnabled ? this.popperInstance.enableEventListeners() : this.popperInstance.disableEventListeners();
} // A placement difference in state means popper determined a new placement
// apart from the props value. By the time the popper element is rendered with
// the new position Popper has already measured it, if the place change triggers
// a size change it will result in a misaligned popper. So we schedule an update to be sure.
if (prevState.placement !== this.state.placement) {
this.scheduleUpdate();
}
};
_proto.componentWillUnmount = function componentWillUnmount() {
setRef(this.props.innerRef, null);
this.destroyPopperInstance();
};
_proto.render = function render() {
return unwrapArray(this.props.children)({
ref: this.setPopperNode,
style: this.getPopperStyle(),
placement: this.getPopperPlacement(),
outOfBoundaries: this.getOutOfBoundariesState(),
scheduleUpdate: this.scheduleUpdate,
arrowProps: {
ref: this.setArrowNode,
style: this.getArrowStyle()
}
});
};
return InnerPopper;
}(React.Component);
defineProperty(InnerPopper, "defaultProps", {
placement: 'bottom',
eventsEnabled: true,
referenceElement: undefined,
positionFixed: false
});
function Popper$1(_ref) {
var referenceElement = _ref.referenceElement,
props = objectWithoutPropertiesLoose(_ref, ["referenceElement"]);
return React.createElement(ManagerReferenceNodeContext.Consumer, null, function (referenceNode) {
return React.createElement(InnerPopper, _extends_1({
referenceElement: referenceElement !== undefined ? referenceElement : referenceNode
}, props));
});
}
// `Element` is not defined during server-side rendering, so shim it here.
/* istanbul ignore next */
var SafeElement = typeof Element === 'undefined' ? function () {} : Element;
var propTypes$5 = {
/**
* Specify menu alignment. The default value is `justify`, which makes the
* menu as wide as the input and truncates long values. Specifying `left`
* or `right` will align the menu to that side and the width will be
* determined by the length of menu item values.
*/
align: propTypes.oneOf(values(ALIGN)),
children: propTypes.func.isRequired,
/**
* Specify whether the menu should appear above the input.
*/
dropup: propTypes.bool,
/**
* Whether or not to automatically adjust the position of the menu when it
* reaches the viewport boundaries.
*/
flip: propTypes.bool,
isMenuShown: propTypes.bool,
positionFixed: propTypes.bool,
referenceElement: propTypes.instanceOf(SafeElement)
};
var defaultProps$4 = {
align: ALIGN.JUSTIFY,
dropup: false,
flip: false,
isMenuShown: false,
positionFixed: false
};
function getModifiers(_ref) {
var align = _ref.align,
flip = _ref.flip;
return {
computeStyles: {
enabled: true,
fn: function fn(_ref2) {
var styles = _ref2.styles,
data = _objectWithoutPropertiesLoose(_ref2, ["styles"]);
return _extends({}, data, {
styles: _extends({}, styles, {
// Use the following condition instead of `align === 'justify'`
// since it allows the component to fall back to justifying the
// menu width if `align` is undefined.
width: align !== ALIGN.RIGHT && align !== ALIGN.LEFT ? // Set the popper width to match the target width.
data.offsets.reference.width : styles.width
})
});
}
},
flip: {
enabled: flip
},
preventOverflow: {
escapeWithReference: true
}
};
} // Flow expects a string literal value for `placement`.
var PLACEMENT = {
bottom: {
end: 'bottom-end',
start: 'bottom-start'
},
top: {
end: 'top-end',
start: 'top-start'
}
};
function getPlacement(_ref3) {
var align = _ref3.align,
dropup = _ref3.dropup;
var x = align === ALIGN.RIGHT ? 'end' : 'start';
var y = dropup ? 'top' : 'bottom';
return PLACEMENT[y][x];
}
var Overlay = function Overlay(props) {
var children = props.children,
isMenuShown = props.isMenuShown,
positionFixed = props.positionFixed,
referenceElement = props.referenceElement;
if (!isMenuShown) {
return null;
}
return /*#__PURE__*/React.createElement(Popper$1, {
modifiers: getModifiers(props),
placement: getPlacement(props),
positionFixed: positionFixed,
referenceElement: referenceElement
}, function (_ref4) {
var ref = _ref4.ref,
popperProps = _objectWithoutPropertiesLoose(_ref4, ["ref"]);
return children(_extends({}, popperProps, {
innerRef: ref,
inputHeight: referenceElement ? referenceElement.offsetHeight : 0
}));
});
};
Overlay.propTypes = propTypes$5;
Overlay.defaultProps = defaultProps$4;
var propTypes$6 = {
onBlur: propTypes.func,
onClick: propTypes.func,
onFocus: propTypes.func,
onRemove: propTypes.func,
option: optionType.isRequired
};
var useToken = function useToken(_ref) {
var onBlur = _ref.onBlur,
onClick = _ref.onClick,
onFocus = _ref.onFocus,
onRemove = _ref.onRemove,
option = _ref.option,
props = _objectWithoutPropertiesLoose(_ref, ["onBlur", "onClick", "onFocus", "onRemove", "option"]);
var _useState = React.useState(false),
active = _useState[0],
setActive = _useState[1];
var _useState2 = React.useState(null),
rootElement = _useState2[0],
attachRef = _useState2[1];
var handleActiveChange = function handleActiveChange(e, isActive, callback) {
e.stopPropagation();
setActive(isActive);
typeof callback === 'function' && callback(e);
};
var handleBlur = function handleBlur(e) {
handleActiveChange(e, false, onBlur);
};
var handleClick = function handleClick(e) {
handleActiveChange(e, true, onClick);
};
var handleFocus = function handleFocus(e) {
handleActiveChange(e, true, onFocus);
};
var handleRemove = function handleRemove() {
onRemove && onRemove(option);
};
var handleKeyDown = function handleKeyDown(e) {
switch (e.keyCode) {
case BACKSPACE:
if (active) {
// Prevent backspace keypress from triggering the browser "back"
// action.
e.preventDefault();
handleRemove();
}
break;
}
};
useRootClose(rootElement, handleBlur, _extends({}, props, {
disabled: !active
}));
return _extends({}, props, {
active: active,
onBlur: handleBlur,
onClick: handleClick,
onFocus: handleFocus,
onKeyDown: handleKeyDown,
onRemove: isFunction(onRemove) ? handleRemove : undefined,
ref: attachRef
});
};
var withToken = function withToken(Component) {
var displayName = "withToken(" + getDisplayName(Component) + ")";
var WrappedToken = function WrappedToken(props) {
return /*#__PURE__*/React__default.createElement(Component, useToken(props));
};
WrappedToken.displayName = displayName;
WrappedToken.propTypes = propTypes$6;
return WrappedToken;
};
function tokenContainer(Component) {
/* istanbul ignore next */
warn(false, 'The `tokenContainer` export is deprecated; use `withToken` instead.');
/* istanbul ignore next */
return withToken(Component);
}
var InteractiveToken = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
var active = _ref.active,
children = _ref.children,
className = _ref.className,
onRemove = _ref.onRemove,
tabIndex = _ref.tabIndex,
props = _objectWithoutPropertiesLoose(_ref, ["active", "children", "className", "onRemove", "tabIndex"]);
return /*#__PURE__*/React__default.createElement("div", _extends({}, props, {
className: classnames('rbt-token', 'rbt-token-removeable', {
'rbt-token-active': !!active
}, className),
ref: ref,
tabIndex: tabIndex || 0
}), children, /*#__PURE__*/React__default.createElement(ClearButton, {
className: "rbt-token-remove-button",
label: "Remove",
onClick: onRemove,
tabIndex: -1
}));
});
var StaticToken = function StaticToken(_ref2) {
var children = _ref2.children,
className = _ref2.className,
disabled = _ref2.disabled,
href = _ref2.href;
var classnames$1 = classnames('rbt-token', {
'rbt-token-disabled': disabled
}, className);
if (href && !disabled) {
return /*#__PURE__*/React__default.createElement("a", {
className: classnames$1,
href: href
}, children);
}
return /*#__PURE__*/React__default.createElement("div", {
className: classnames$1
}, children);
};
/**
* Token
*
* Individual token component, generally displayed within the TokenizerInput
* component, but can also be rendered on its own.
*/
var Token = /*#__PURE__*/React.forwardRef(function (props, ref) {
var disabled = props.disabled,
onRemove = props.onRemove,
readOnly = props.readOnly;
return !disabled && !readOnly && isFunction(onRemove) ? /*#__PURE__*/React__default.createElement(InteractiveToken, _extends({}, props, {
ref: ref
})) : /*#__PURE__*/React__default.createElement(StaticToken, props);
});
var Token$1 = withToken(Token);
// IE doesn't seem to get the composite computed value (eg: 'padding',
// 'borderStyle', etc.), so generate these from the individual values.
function interpolateStyle(styles, attr, subattr) {
if (subattr === void 0) {
subattr = '';
}
// Title-case the sub-attribute.
if (subattr) {
/* eslint-disable-next-line no-param-reassign */
subattr = subattr.replace(subattr[0], subattr[0].toUpperCase());
}
return ['Top', 'Right', 'Bottom', 'Left'].map(function (dir) {
return styles[attr + dir + subattr];
}).join(' ');
}
function copyStyles(inputNode, hintNode) {
if (!inputNode || !hintNode) {
return;
}
var inputStyle = window.getComputedStyle(inputNode);
/* eslint-disable no-param-reassign */
hintNode.style.borderStyle = interpolateStyle(inputStyle, 'border', 'style');
hintNode.style.borderWidth = interpolateStyle(inputStyle, 'border', 'width');
hintNode.style.fontSize = inputStyle.fontSize;
hintNode.style.height = inputStyle.height;
hintNode.style.lineHeight = inputStyle.lineHeight;
hintNode.style.margin = interpolateStyle(inputStyle, 'margin');
hintNode.style.padding = interpolateStyle(inputStyle, 'padding');
/* eslint-enable no-param-reassign */
}
function defaultShouldSelect(e, state) {
var shouldSelectHint = false;
var currentTarget = e.currentTarget,
keyCode = e.keyCode;
if (keyCode === RIGHT) {
// For selectable input types ("text", "search"), only select the hint if
// it's at the end of the input value. For non-selectable types ("email",
// "number"), always select the hint.
shouldSelectHint = isSelectable(currentTarget) ? currentTarget.selectionStart === currentTarget.value.length : true;
}
if (keyCode === TAB) {
// Prevent input from blurring on TAB.
e.preventDefault();
shouldSelectHint = true;
}
if (keyCode === RETURN) {
shouldSelectHint = !!state.selectHintOnEnter;
}
return typeof state.shouldSelect === 'function' ? state.shouldSelect(shouldSelectHint, e) : shouldSelectHint;
}
var useHint = function useHint(_ref) {
var children = _ref.children,
shouldSelect = _ref.shouldSelect;
!(React__default.Children.count(children) === 1) ? invariant_1(false, '`useHint` expects one child.') : void 0;
var _useTypeaheadContext = useTypeaheadContext(),
hintText = _useTypeaheadContext.hintText,
initialItem = _useTypeaheadContext.initialItem,
inputNode = _useTypeaheadContext.inputNode,
onAdd = _useTypeaheadContext.onAdd,
selectHintOnEnter = _useTypeaheadContext.selectHintOnEnter;
var hintRef = React.useRef(null);
var onKeyDown = function onKeyDown(e) {
if (hintText && initialItem && defaultShouldSelect(e, {
selectHintOnEnter: selectHintOnEnter,
shouldSelect: shouldSelect
})) {
onAdd(initialItem);
}
children.props.onKeyDown && children.props.onKeyDown(e);
};
React.useEffect(function () {
copyStyles(inputNode, hintRef.current);
});
return {
child: /*#__PURE__*/React.cloneElement(children, _extends({}, children.props, {
onKeyDown: onKeyDown
})),
hintRef: hintRef,
hintText: hintText
};
};
var Hint = function Hint(_ref2) {
var className = _ref2.className,
props = _objectWithoutPropertiesLoose(_ref2, ["className"]);
var _useHint = useHint(props),
child = _useHint.child,
hintRef = _useHint.hintRef,
hintText = _useHint.hintText;
return /*#__PURE__*/React__default.createElement("div", {
className: className,
style: {
display: 'flex',
flex: 1,
height: '100%',
position: 'relative'
}
}, child, /*#__PURE__*/React__default.createElement("input", {
"aria-hidden": true,
className: "rbt-input-hint",
ref: hintRef,
readOnly: true,
style: {
backgroundColor: 'transparent',
borderColor: 'transparent',
boxShadow: 'none',
color: 'rgba(0, 0, 0, 0.35)',
left: 0,
pointerEvents: 'none',
position: 'absolute',
top: 0,
width: '100%'
},
tabIndex: -1,
value: hintText
}));
};
var Input = /*#__PURE__*/React__default.forwardRef(function (props, ref) {
return /*#__PURE__*/React__default.createElement("input", _extends({}, props, {
className: classnames('rbt-input-main', props.className),
ref: ref
}));
});
function withClassNames(Component) {
// Use a class instead of function component to support refs.
/* eslint-disable-next-line react/prefer-stateless-function */
var WrappedComponent = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(WrappedComponent, _React$Component);
function WrappedComponent() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = WrappedComponent.prototype;
_proto.render = function render() {
var _this$props = this.props,
className = _this$props.className,
isInvalid = _this$props.isInvalid,
isValid = _this$props.isValid,
size = _this$props.size,
props = _objectWithoutPropertiesLoose(_this$props, ["className", "isInvalid", "isValid", "size"]);
return /*#__PURE__*/React__default.createElement(Component, _extends({}, props, {
className: classnames('form-control', 'rbt-input', {
'form-control-lg': isSizeLarge(size),
'form-control-sm': isSizeSmall(size),
'is-invalid': isInvalid,
'is-valid': isValid
}, className)
}));
};
return WrappedComponent;
}(React__default.Component);
_defineProperty(WrappedComponent, "displayName", "withClassNames(" + getDisplayName(Component) + ")");
return WrappedComponent;
}
var TypeaheadInputMulti = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(TypeaheadInputMulti, _React$Component);
function TypeaheadInputMulti() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "wrapperRef", /*#__PURE__*/React__default.createRef());
_defineProperty(_assertThisInitialized(_this), "_input", void 0);
_defineProperty(_assertThisInitialized(_this), "getInputRef", function (input) {
_this._input = input;
_this.props.inputRef(input);
});
_defineProperty(_assertThisInitialized(_this), "_handleContainerClickOrFocus", function (e) {
// Don't focus the input if it's disabled.
if (_this.props.disabled) {
e.currentTarget.blur();
return;
} // Move cursor to the end if the user clicks outside the actual input.
var inputNode = _this._input;
if (!inputNode) {
return;
}
if (e.currentTarget !== inputNode && isSelectable(inputNode)) {
inputNode.selectionStart = inputNode.value.length;
}
inputNode.focus();
});
_defineProperty(_assertThisInitialized(_this), "_handleKeyDown", function (e) {
var _this$props = _this.props,
onKeyDown = _this$props.onKeyDown,
selected = _this$props.selected,
value = _this$props.value;
switch (e.keyCode) {
case BACKSPACE:
if (e.currentTarget === _this._input && selected.length && !value) {
// Prevent browser from going back.
e.preventDefault(); // If the input is selected and there is no text, focus the last
// token when the user hits backspace.
if (_this.wrapperRef.current) {
var children = _this.wrapperRef.current.children;
var lastToken = children[children.length - 2];
lastToken && lastToken.focus();
}
}
break;
}
onKeyDown(e);
});
return _this;
}
var _proto = TypeaheadInputMulti.prototype;
_proto.render = function render() {
var _this$props2 = this.props,
children = _this$props2.children,
className = _this$props2.className,
inputClassName = _this$props2.inputClassName,
inputRef = _this$props2.inputRef,
placeholder = _this$props2.placeholder,
referenceElementRef = _this$props2.referenceElementRef,
selected = _this$props2.selected,
shouldSelectHint = _this$props2.shouldSelectHint,
props = _objectWithoutPropertiesLoose(_this$props2, ["children", "className", "inputClassName", "inputRef", "placeholder", "referenceElementRef", "selected", "shouldSelectHint"]);
return /*#__PURE__*/React__default.createElement("div", {
className: classnames('rbt-input-multi', className),
disabled: props.disabled,
onClick: this._handleContainerClickOrFocus,
onFocus: this._handleContainerClickOrFocus,
ref: referenceElementRef,
tabIndex: -1
}, /*#__PURE__*/React__default.createElement("div", {
className: "rbt-input-wrapper",
ref: this.wrapperRef
}, children, /*#__PURE__*/React__default.createElement(Hint, {
shouldSelect: shouldSelectHint
}, /*#__PURE__*/React__default.createElement(Input, _extends({}, props, {
className: inputClassName,
onKeyDown: this._handleKeyDown,
placeholder: selected.length ? '' : placeholder,
ref: this.getInputRef,
style: {
backgroundColor: 'transparent',
border: 0,
boxShadow: 'none',
cursor: 'inherit',
outline: 'none',
padding: 0,
width: '100%',
zIndex: 1
}
})))));
};
return TypeaheadInputMulti;
}(React__default.Component);
var TypeaheadInputMulti$1 = withClassNames(TypeaheadInputMulti);
var TypeaheadInputSingle = withClassNames(function (_ref) {
var inputRef = _ref.inputRef,
referenceElementRef = _ref.referenceElementRef,
shouldSelectHint = _ref.shouldSelectHint,
props = _objectWithoutPropertiesLoose(_ref, ["inputRef", "referenceElementRef", "shouldSelectHint"]);
return /*#__PURE__*/React__default.createElement(Hint, {
shouldSelect: shouldSelectHint
}, /*#__PURE__*/React__default.createElement(Input, _extends({}, props, {
ref: function ref(node) {
inputRef(node);
referenceElementRef(node);
}
})));
});
var propTypes$7 = {
children: propTypes.string.isRequired,
highlightClassName: propTypes.string,
search: propTypes.string.isRequired
};
var defaultProps$5 = {
highlightClassName: 'rbt-highlight-text'
};
/**
* Stripped-down version of https://github.com/helior/react-highlighter
*
* Results are already filtered by the time the component is used internally so
* we can safely ignore case and diacritical marks for the purposes of matching.
*/
var Highlighter = /*#__PURE__*/function (_React$PureComponent) {
_inheritsLoose(Highlighter, _React$PureComponent);
function Highlighter() {
return _React$PureComponent.apply(this, arguments) || this;
}
var _proto = Highlighter.prototype;
_proto.render = function render() {
var _this$props = this.props,
children = _this$props.children,
highlightClassName = _this$props.highlightClassName,
search = _this$props.search;
if (!search || !children) {
return children;
}
var matchCount = 0;
var remaining = children;
var highlighterChildren = [];
while (remaining) {
var bounds = getMatchBounds(remaining, search); // No match anywhere in the remaining string, stop.
if (!bounds) {
highlighterChildren.push(remaining);
break;
} // Capture the string that leads up to a match.
var nonMatch = remaining.slice(0, bounds.start);
if (nonMatch) {
highlighterChildren.push(nonMatch);
} // Capture the matching string.
var match = remaining.slice(bounds.start, bounds.end);
highlighterChildren.push( /*#__PURE__*/React__default.createElement("mark", {
className: highlightClassName,
key: matchCount
}, match));
matchCount += 1; // And if there's anything left over, continue the loop.
remaining = remaining.slice(bounds.end);
}
return highlighterChildren;
};
return Highlighter;
}(React__default.PureComponent);
_defineProperty(Highlighter, "propTypes", propTypes$7);
_defineProperty(Highlighter, "defaultProps", defaultProps$5);
function isElement(el) {
return el != null && typeof el === 'object' && el.nodeType === 1;
}
function canOverflow(overflow, skipOverflowHiddenElements) {
if (skipOverflowHiddenElements && overflow === 'hidden') {
return false;
}
return overflow !== 'visible' && overflow !== 'clip';
}
function getFrameElement(el) {
if (!el.ownerDocument || !el.ownerDocument.defaultView) {
return null;
}
try {
return el.ownerDocument.defaultView.frameElement;
} catch (e) {
return null;
}
}
function isHiddenByFrame(el) {
var frame = getFrameElement(el);
if (!frame) {
return false;
}
return frame.clientHeight < el.scrollHeight || frame.clientWidth < el.scrollWidth;
}
function isScrollable(el, skipOverflowHiddenElements) {
if (el.clientHeight < el.scrollHeight || el.clientWidth < el.scrollWidth) {
var style = getComputedStyle(el, null);
return canOverflow(style.overflowY, skipOverflowHiddenElements) || canOverflow(style.overflowX, skipOverflowHiddenElements) || isHiddenByFrame(el);
}
return false;
}
function alignNearest(scrollingEdgeStart, scrollingEdgeEnd, scrollingSize, scrollingBorderStart, scrollingBorderEnd, elementEdgeStart, elementEdgeEnd, elementSize) {
if (elementEdgeStart < scrollingEdgeStart && elementEdgeEnd > scrollingEdgeEnd || elementEdgeStart > scrollingEdgeStart && elementEdgeEnd < scrollingEdgeEnd) {
return 0;
}
if (elementEdgeStart <= scrollingEdgeStart && elementSize <= scrollingSize || elementEdgeEnd >= scrollingEdgeEnd && elementSize >= scrollingSize) {
return elementEdgeStart - scrollingEdgeStart - scrollingBorderStart;
}
if (elementEdgeEnd > scrollingEdgeEnd && elementSize < scrollingSize || elementEdgeStart < scrollingEdgeStart && elementSize > scrollingSize) {
return elementEdgeEnd - scrollingEdgeEnd + scrollingBorderEnd;
}
return 0;
}
var compute = (function (target, options) {
var scrollMode = options.scrollMode,
block = options.block,
inline = options.inline,
boundary = options.boundary,
skipOverflowHiddenElements = options.skipOverflowHiddenElements;
var checkBoundary = typeof boundary === 'function' ? boundary : function (node) {
return node !== boundary;
};
if (!isElement(target)) {
throw new TypeError('Invalid target');
}
var scrollingElement = document.scrollingElement || document.documentElement;
var frames = [];
var cursor = target;
while (isElement(cursor) && checkBoundary(cursor)) {
cursor = cursor.parentNode;
if (cursor === scrollingElement) {
frames.push(cursor);
break;
}
if (cursor === document.body && isScrollable(cursor) && !isScrollable(document.documentElement)) {
continue;
}
if (isScrollable(cursor, skipOverflowHiddenElements)) {
frames.push(cursor);
}
}
var viewportWidth = window.visualViewport ? visualViewport.width : innerWidth;
var viewportHeight = window.visualViewport ? visualViewport.height : innerHeight;
var viewportX = window.scrollX || pageXOffset;
var viewportY = window.scrollY || pageYOffset;
var _target$getBoundingCl = target.getBoundingClientRect(),
targetHeight = _target$getBoundingCl.height,
targetWidth = _target$getBoundingCl.width,
targetTop = _target$getBoundingCl.top,
targetRight = _target$getBoundingCl.right,
targetBottom = _target$getBoundingCl.bottom,
targetLeft = _target$getBoundingCl.left;
var targetBlock = block === 'start' || block === 'nearest' ? targetTop : block === 'end' ? targetBottom : targetTop + targetHeight / 2;
var targetInline = inline === 'center' ? targetLeft + targetWidth / 2 : inline === 'end' ? targetRight : targetLeft;
var computations = [];
for (var index = 0; index < frames.length; index++) {
var frame = frames[index];
var _frame$getBoundingCli = frame.getBoundingClientRect(),
height = _frame$getBoundingCli.height,
width = _frame$getBoundingCli.width,
top = _frame$getBoundingCli.top,
right = _frame$getBoundingCli.right,
bottom = _frame$getBoundingCli.bottom,
left = _frame$getBoundingCli.left;
if (scrollMode === 'if-needed' && targetTop >= 0 && targetLeft >= 0 && targetBottom <= viewportHeight && targetRight <= viewportWidth && targetTop >= top && targetBottom <= bottom && targetLeft >= left && targetRight <= right) {
return computations;
}
var frameStyle = getComputedStyle(frame);
var borderLeft = parseInt(frameStyle.borderLeftWidth, 10);
var borderTop = parseInt(frameStyle.borderTopWidth, 10);
var borderRight = parseInt(frameStyle.borderRightWidth, 10);
var borderBottom = parseInt(frameStyle.borderBottomWidth, 10);
var blockScroll = 0;
var inlineScroll = 0;
var scrollbarWidth = 'offsetWidth' in frame ? frame.offsetWidth - frame.clientWidth - borderLeft - borderRight : 0;
var scrollbarHeight = 'offsetHeight' in frame ? frame.offsetHeight - frame.clientHeight - borderTop - borderBottom : 0;
if (scrollingElement === frame) {
if (block === 'start') {
blockScroll = targetBlock;
} else if (block === 'end') {
blockScroll = targetBlock - viewportHeight;
} else if (block === 'nearest') {
blockScroll = alignNearest(viewportY, viewportY + viewportHeight, viewportHeight, borderTop, borderBottom, viewportY + targetBlock, viewportY + targetBlock + targetHeight, targetHeight);
} else {
blockScroll = targetBlock - viewportHeight / 2;
}
if (inline === 'start') {
inlineScroll = targetInline;
} else if (inline === 'center') {
inlineScroll = targetInline - viewportWidth / 2;
} else if (inline === 'end') {
inlineScroll = targetInline - viewportWidth;
} else {
inlineScroll = alignNearest(viewportX, viewportX + viewportWidth, viewportWidth, borderLeft, borderRight, viewportX + targetInline, viewportX + targetInline + targetWidth, targetWidth);
}
blockScroll = Math.max(0, blockScroll + viewportY);
inlineScroll = Math.max(0, inlineScroll + viewportX);
} else {
if (block === 'start') {
blockScroll = targetBlock - top - borderTop;
} else if (block === 'end') {
blockScroll = targetBlock - bottom + borderBottom + scrollbarHeight;
} else if (block === 'nearest') {
blockScroll = alignNearest(top, bottom, height, borderTop, borderBottom + scrollbarHeight, targetBlock, targetBlock + targetHeight, targetHeight);
} else {
blockScroll = targetBlock - (top + height / 2) + scrollbarHeight / 2;
}
if (inline === 'start') {
inlineScroll = targetInline - left - borderLeft;
} else if (inline === 'center') {
inlineScroll = targetInline - (left + width / 2) + scrollbarWidth / 2;
} else if (inline === 'end') {
inlineScroll = targetInline - right + borderRight + scrollbarWidth;
} else {
inlineScroll = alignNearest(left, right, width, borderLeft, borderRight + scrollbarWidth, targetInline, targetInline + targetWidth, targetWidth);
}
var scrollLeft = frame.scrollLeft,
scrollTop = frame.scrollTop;
blockScroll = Math.max(0, Math.min(scrollTop + blockScroll, frame.scrollHeight - height + scrollbarHeight));
inlineScroll = Math.max(0, Math.min(scrollLeft + inlineScroll, frame.scrollWidth - width + scrollbarWidth));
targetBlock += scrollTop - blockScroll;
targetInline += scrollLeft - inlineScroll;
}
computations.push({
el: frame,
top: blockScroll,
left: inlineScroll
});
}
return computations;
});
function isOptionsObject(options) {
return options === Object(options) && Object.keys(options).length !== 0;
}
function defaultBehavior(actions, behavior) {
if (behavior === void 0) {
behavior = 'auto';
}
var canSmoothScroll = ('scrollBehavior' in document.body.style);
actions.forEach(function (_ref) {
var el = _ref.el,
top = _ref.top,
left = _ref.left;
if (el.scroll && canSmoothScroll) {
el.scroll({
top: top,
left: left,
behavior: behavior
});
} else {
el.scrollTop = top;
el.scrollLeft = left;
}
});
}
function getOptions(options) {
if (options === false) {
return {
block: 'end',
inline: 'nearest'
};
}
if (isOptionsObject(options)) {
return options;
}
return {
block: 'start',
inline: 'nearest'
};
}
function scrollIntoView(target, options) {
var targetIsDetached = !target.ownerDocument.documentElement.contains(target);
if (isOptionsObject(options) && typeof options.behavior === 'function') {
return options.behavior(targetIsDetached ? [] : compute(target, options));
}
if (targetIsDetached) {
return;
}
var computeOptions = getOptions(options);
return defaultBehavior(compute(target, computeOptions), computeOptions.behavior);
}
var propTypes$8 = {
option: optionType.isRequired,
position: propTypes.number
};
var useItem = function useItem(_ref) {
var label = _ref.label,
onClick = _ref.onClick,
option = _ref.option,
position = _ref.position,
props = _objectWithoutPropertiesLoose(_ref, ["label", "onClick", "option", "position"]);
var _useTypeaheadContext = useTypeaheadContext(),
activeIndex = _useTypeaheadContext.activeIndex,
id = _useTypeaheadContext.id,
isOnlyResult = _useTypeaheadContext.isOnlyResult,
onActiveItemChange = _useTypeaheadContext.onActiveItemChange,
onInitialItemChange = _useTypeaheadContext.onInitialItemChange,
onMenuItemClick = _useTypeaheadContext.onMenuItemClick,
setItem = _useTypeaheadContext.setItem;
var itemRef = React.useRef(null);
React.useEffect(function () {
if (position === 0) {
onInitialItemChange(option);
}
});
React.useEffect(function () {
if (position === activeIndex) {
onActiveItemChange(option); // Automatically scroll the menu as the user keys through it.
var node = itemRef.current;
node && scrollIntoView(node, {
block: 'nearest',
boundary: node.parentNode,
inline: 'nearest',
scrollMode: 'if-needed'
});
}
});
var handleClick = React.useCallback(function (e) {
onMenuItemClick(option, e);
onClick && onClick(e);
}, [onClick, onMenuItemClick, option]);
var active = isOnlyResult || activeIndex === position; // Update the item's position in the item stack.
setItem(option, position);
return _extends({}, props, {
active: active,
'aria-label': label,
'aria-selected': active,
id: getMenuItemId(id, position),
onClick: handleClick,
onMouseDown: preventInputBlur,
ref: itemRef,
role: 'option'
});
};
var withItem = function withItem(Component) {
var displayName = "withItem(" + getDisplayName(Component) + ")";
var WrappedMenuItem = function WrappedMenuItem(props) {
return /*#__PURE__*/React__default.createElement(Component, useItem(props));
};
WrappedMenuItem.displayName = displayName;
WrappedMenuItem.propTypes = propTypes$8;
return WrappedMenuItem;
};
function menuItemContainer(Component) {
/* istanbul ignore next */
warn(false, 'The `menuItemContainer` export is deprecated; use `withItem` instead.');
/* istanbul ignore next */
return withItem(Component);
}
var BaseMenuItem = /*#__PURE__*/React__default.forwardRef(function (_ref, ref) {
var active = _ref.active,
children = _ref.children,
className = _ref.className,
disabled = _ref.disabled,
_onClick = _ref.onClick,
onMouseDown = _ref.onMouseDown,
props = _objectWithoutPropertiesLoose(_ref, ["active", "children", "className", "disabled", "onClick", "onMouseDown"]);
return (
/*#__PURE__*/
/* eslint-disable jsx-a11y/anchor-is-valid */
React__default.createElement("a", _extends({}, props, {
className: classnames('dropdown-item', {
active: active,
disabled: disabled
}, className),
href: "#",
onClick: function onClick(e) {
e.preventDefault();
!disabled && _onClick && _onClick(e);
},
onMouseDown: onMouseDown,
ref: ref
}), children)
/* eslint-enable jsx-a11y/anchor-is-valid */
);
});
var MenuItem = withItem(BaseMenuItem);
var MenuDivider = function MenuDivider(props) {
return /*#__PURE__*/React__default.createElement("div", {
className: "dropdown-divider",
role: "separator"
});
};
var MenuHeader = function MenuHeader(props) {
return /*#__PURE__*/React__default.createElement("div", _extends({}, props, {
className: "dropdown-header",
role: "heading"
}));
};
var propTypes$9 = {
'aria-label': propTypes.string,
/**
* Message to display in the menu if there are no valid results.
*/
emptyLabel: propTypes.node,
/**
* Needed for accessibility.
*/
id: checkPropType(propTypes.oneOfType([propTypes.number, propTypes.string]), isRequiredForA11y),
/**
* Maximum height of the dropdown menu.
*/
maxHeight: propTypes.string
};
var defaultProps$6 = {
'aria-label': 'menu-options',
emptyLabel: 'No matches found.',
maxHeight: '300px'
};
/**
* Menu component that handles empty state when passed a set of results.
*/
var Menu = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(Menu, _React$Component);
function Menu() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Menu.prototype;
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this$props = this.props,
inputHeight = _this$props.inputHeight,
scheduleUpdate = _this$props.scheduleUpdate; // Update the menu position if the height of the input changes.
if (inputHeight !== prevProps.inputHeight) {
scheduleUpdate();
}
};
_proto.render = function render() {
var _this$props2 = this.props,
children = _this$props2.children,
className = _this$props2.className,
emptyLabel = _this$props2.emptyLabel,
id = _this$props2.id,
innerRef = _this$props2.innerRef,
maxHeight = _this$props2.maxHeight,
style = _this$props2.style,
text = _this$props2.text;
var contents = React.Children.count(children) === 0 ? /*#__PURE__*/React__default.createElement(BaseMenuItem, {
disabled: true,
role: "option"
}, emptyLabel) : children;
return /*#__PURE__*/React__default.createElement("div", {
"aria-label": this.props['aria-label'],
className: classnames('rbt-menu', 'dropdown-menu', 'show', className),
id: id,
key: // Force a re-render if the text changes to ensure that menu
// positioning updates correctly.
text,
ref: innerRef,
role: "listbox",
style: _extends({}, style, {
display: 'block',
maxHeight: maxHeight,
overflow: 'auto'
})
}, contents);
};
return Menu;
}(React__default.Component);
_defineProperty(Menu, "propTypes", propTypes$9);
_defineProperty(Menu, "defaultProps", defaultProps$6);
_defineProperty(Menu, "Divider", MenuDivider);
_defineProperty(Menu, "Header", MenuHeader);
var propTypes$a = {
/**
* Provides the ability to specify a prefix before the user-entered text to
* indicate that the selection will be new. No-op unless `allowNew={true}`.
*/
newSelectionPrefix: propTypes.node,
/**
* Prompt displayed when large data sets are paginated.
*/
paginationText: propTypes.node,
/**
* Provides a hook for customized rendering of menu item contents.
*/
renderMenuItemChildren: propTypes.func
};
var defaultProps$7 = {
newSelectionPrefix: 'New selection: ',
paginationText: 'Display additional results...',
renderMenuItemChildren: function renderMenuItemChildren(option, props, idx) {
return /*#__PURE__*/React__default.createElement(Highlighter, {
search: props.text
}, getOptionLabel(option, props.labelKey));
}
};
var TypeaheadMenu = function TypeaheadMenu(props) {
var labelKey = props.labelKey,
newSelectionPrefix = props.newSelectionPrefix,
options = props.options,
paginationText = props.paginationText,
renderMenuItemChildren = props.renderMenuItemChildren,
text = props.text,
menuProps = _objectWithoutPropertiesLoose(props, ["labelKey", "newSelectionPrefix", "options", "paginationText", "renderMenuItemChildren", "text"]);
var renderMenuItem = function renderMenuItem(option, position) {
var label = getOptionLabel(option, labelKey);
var menuItemProps = {
disabled: getOptionProperty(option, 'disabled'),
label: label,
option: option,
position: position
};
if (option.customOption) {
return /*#__PURE__*/React__default.createElement(MenuItem, _extends({}, menuItemProps, {
className: "rbt-menu-custom-option",
key: position,
label: newSelectionPrefix + label
}), newSelectionPrefix, /*#__PURE__*/React__default.createElement(Highlighter, {
search: text
}, label));
}
if (option.paginationOption) {
return /*#__PURE__*/React__default.createElement(React.Fragment, {
key: "pagination-item"
}, /*#__PURE__*/React__default.createElement(Menu.Divider, null), /*#__PURE__*/React__default.createElement(MenuItem, _extends({}, menuItemProps, {
className: "rbt-menu-pagination-option",
label: paginationText
}), paginationText));
}
return /*#__PURE__*/React__default.createElement(MenuItem, _extends({}, menuItemProps, {
key: position
}), renderMenuItemChildren(option, props, position));
};
return (
/*#__PURE__*/
// Explictly pass `text` so Flow doesn't complain...
React__default.createElement(Menu, _extends({}, menuProps, {
text: text
}), options.map(renderMenuItem))
);
};
TypeaheadMenu.propTypes = propTypes$a;
TypeaheadMenu.defaultProps = defaultProps$7;
var propTypes$b = {
/**
* Displays a button to clear the input when there are selections.
*/
clearButton: propTypes.bool,
/**
* Props to be applied directly to the input. `onBlur`, `onChange`,
* `onFocus`, and `onKeyDown` are ignored.
*/
inputProps: checkPropType(propTypes.object, inputPropsType),
/**
* Bootstrap 4 only. Adds the `is-invalid` classname to the `form-control`.
*/
isInvalid: propTypes.bool,
/**
* Indicate whether an asynchronous data fetch is happening.
*/
isLoading: propTypes.bool,
/**
* Bootstrap 4 only. Adds the `is-valid` classname to the `form-control`.
*/
isValid: propTypes.bool,
/**
* Callback for custom input rendering.
*/
renderInput: propTypes.func,
/**
* Callback for custom menu rendering.
*/
renderMenu: propTypes.func,
/**
* Callback for custom menu rendering.
*/
renderToken: propTypes.func,
/**
* Specifies the size of the input.
*/
size: sizeType
};
var defaultProps$8 = {
clearButton: false,
inputProps: {},
isInvalid: false,
isLoading: false,
isValid: false,
renderMenu: function renderMenu(results, menuProps, props) {
return /*#__PURE__*/React__default.createElement(TypeaheadMenu, _extends({}, menuProps, {
labelKey: props.labelKey,
options: results,
text: props.text
}));
},
renderToken: function renderToken(option, props, idx) {
return /*#__PURE__*/React__default.createElement(Token$1, {
disabled: props.disabled,
key: idx,
onRemove: props.onRemove,
option: option,
tabIndex: props.tabIndex
}, getOptionLabel(option, props.labelKey));
}
};
function getOverlayProps(props) {
return pick(props, ['align', 'dropup', 'flip', 'positionFixed']);
}
var RootClose = function RootClose(_ref) {
var children = _ref.children,
onRootClose = _ref.onRootClose,
props = _objectWithoutPropertiesLoose(_ref, ["children", "onRootClose"]);
var _useState = React.useState(null),
rootElement = _useState[0],
attachRef = _useState[1];
useRootClose(rootElement, onRootClose, props);
return children(attachRef);
};
var TypeaheadComponent = /*#__PURE__*/function (_React$Component) {
_inheritsLoose(TypeaheadComponent, _React$Component);
function TypeaheadComponent() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_defineProperty(_assertThisInitialized(_this), "_referenceElement", void 0);
_defineProperty(_assertThisInitialized(_this), "referenceElementRef", function (referenceElement) {
_this._referenceElement = referenceElement;
});
_defineProperty(_assertThisInitialized(_this), "_renderInput", function (inputProps, props) {
var _this$props = _this.props,
isInvalid = _this$props.isInvalid,
isValid = _this$props.isValid,
multiple = _this$props.multiple,
renderInput = _this$props.renderInput,
renderToken = _this$props.renderToken,
size = _this$props.size;
if (isFunction(renderInput)) {
return renderInput(inputProps, props);
}
var commonProps = _extends({}, inputProps, {
isInvalid: isInvalid,
isValid: isValid,
size: size
});
if (!multiple) {
return /*#__PURE__*/React__default.createElement(TypeaheadInputSingle, commonProps);
}
var labelKey = props.labelKey,
onRemove = props.onRemove,
selected = props.selected;
return /*#__PURE__*/React__default.createElement(TypeaheadInputMulti$1, _extends({}, commonProps, {
selected: selected
}), selected.map(function (option, idx) {
return renderToken(option, _extends({}, commonProps, {
labelKey: labelKey,
onRemove: onRemove
}), idx);
}));
});
_defineProperty(_assertThisInitialized(_this), "_renderMenu", function (results, menuProps, props) {
var _this$props2 = _this.props,
emptyLabel = _this$props2.emptyLabel,
id = _this$props2.id,
maxHeight = _this$props2.maxHeight,
newSelectionPrefix = _this$props2.newSelectionPrefix,
paginationText = _this$props2.paginationText,
renderMenu = _this$props2.renderMenu,
renderMenuItemChildren = _this$props2.renderMenuItemChildren;
return renderMenu(results, _extends({}, menuProps, {
emptyLabel: emptyLabel,
id: id,
maxHeight: maxHeight,
newSelectionPrefix: newSelectionPrefix,
paginationText: paginationText,
renderMenuItemChildren: renderMenuItemChildren
}), props);
});
_defineProperty(_assertThisInitialized(_this), "_renderAux", function (_ref2) {
var onClear = _ref2.onClear,
selected = _ref2.selected;
var _this$props3 = _this.props,
clearButton = _this$props3.clearButton,
disabled = _this$props3.disabled,
isLoading = _this$props3.isLoading,
size = _this$props3.size;
var content;
if (isLoading) {
content = /*#__PURE__*/React__default.createElement(Loader, null);
} else if (clearButton && !disabled && selected.length) {
content = /*#__PURE__*/React__default.createElement(ClearButton, {
onClick: onClear,
onFocus: function onFocus(e) {
// Prevent the main input from auto-focusing again.
e.stopPropagation();
},
onMouseDown: preventInputBlur,
size: size
});
}
return content ? /*#__PURE__*/React__default.createElement("div", {
className: classnames('rbt-aux', {
'rbt-aux-lg': isSizeLarge(size)
})
}, content) : null;
});
return _this;
}
var _proto = TypeaheadComponent.prototype;
_proto.render = function render() {
var _this2 = this;
var _this$props4 = this.props,
children = _this$props4.children,
className = _this$props4.className,
instanceRef = _this$props4.instanceRef,
open = _this$props4.open,
options = _this$props4.options,
style = _this$props4.style;
return /*#__PURE__*/React__default.createElement(Typeahead, _extends({}, this.props, {
options: options,
ref: instanceRef
}), function (_ref3) {
var getInputProps = _ref3.getInputProps,
props = _objectWithoutPropertiesLoose(_ref3, ["getInputProps"]);
var hideMenu = props.hideMenu,
isMenuShown = props.isMenuShown,
results = props.results;
var auxContent = _this2._renderAux(props);
return /*#__PURE__*/React__default.createElement(RootClose, {
disabled: open || !isMenuShown,
onRootClose: hideMenu
}, function (ref) {
return /*#__PURE__*/React__default.createElement("div", {
className: classnames('rbt', {
'has-aux': !!auxContent
}, className),
ref: ref,
style: _extends({}, style, {
outline: 'none',
position: 'relative'
}),
tabIndex: -1
}, _this2._renderInput(_extends({}, getInputProps(_this2.props.inputProps), {
referenceElementRef: _this2.referenceElementRef
}), props), /*#__PURE__*/React__default.createElement(Overlay, _extends({}, getOverlayProps(_this2.props), {
isMenuShown: isMenuShown,
referenceElement: _this2._referenceElement
}), function (menuProps) {
return _this2._renderMenu(results, menuProps, props);
}), auxContent, isFunction(children) ? children(props) : children);
});
});
};
return TypeaheadComponent;
}(React__default.Component);
_defineProperty(TypeaheadComponent, "propTypes", propTypes$b);
_defineProperty(TypeaheadComponent, "defaultProps", defaultProps$8);
var Typeahead$1 = /*#__PURE__*/React.forwardRef(function (props, ref) {
return /*#__PURE__*/React__default.createElement(TypeaheadComponent, _extends({}, props, {
instanceRef: ref
}));
});
var AsyncTypeahead = withAsync(Typeahead$1);
exports.AsyncTypeahead = AsyncTypeahead;
exports.ClearButton = ClearButton;
exports.Highlighter = Highlighter;
exports.Hint = Hint;
exports.Input = Input;
exports.Loader = Loader;
exports.Menu = Menu;
exports.MenuItem = MenuItem;
exports.Token = Token$1;
exports.Typeahead = Typeahead$1;
exports.TypeaheadInputMulti = TypeaheadInputMulti$1;
exports.TypeaheadInputSingle = TypeaheadInputSingle;
exports.TypeaheadMenu = TypeaheadMenu;
exports.asyncContainer = asyncContainer;
exports.menuItemContainer = menuItemContainer;
exports.tokenContainer = tokenContainer;
exports.useAsync = useAsync;
exports.useHint = useHint;
exports.useItem = useItem;
exports.useToken = useToken;
exports.withAsync = withAsync;
exports.withItem = withItem;
exports.withToken = withToken;
Object.defineProperty(exports, '__esModule', { value: true });
})));<|fim▁end|> |
function getBordersSize(styles, axis) {
var sideA = axis === 'x' ? 'Left' : 'Top';
var sideB = sideA === 'Left' ? 'Right' : 'Bottom'; |
<|file_name|>test_forms.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.test import TestCase
from ..forms import QuoteForm<|fim▁hole|>class TestQuoteForm(TestCase):
def setUp(self):
pass
def test_validate_emtpy_quote(self):
form = QuoteForm({'message': ''})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': ' '})
self.assertFalse(form.is_valid())
def test_validate_invalid_quote(self):
form = QuoteForm({'message': 'Mensaje invalido'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'mensaje invalido'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'me nsaje invalido'})
self.assertFalse(form.is_valid())
def test_urls_in_quote(self):
form = QuoteForm({'message': 'http://122.33.43.322'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'Me caga http://sabesquemecaga.com'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'http://sabesquemecaga.com'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'http://sabesquemecaga.com/asdfads/'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'Me caga http://www.sabesquemecaga.com'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'Me caga http://www.sabesquemecaga.com/test/12'})
self.assertFalse(form.is_valid())
def test_emails_in_quote(self):
form = QuoteForm({'message': 'Me caga test@test.com'})
self.assertFalse(form.is_valid())
form = QuoteForm({'message': 'Me caga test.this@test.asdfas.com'})
self.assertFalse(form.is_valid())
def test_validate_short_quote(self):
form = QuoteForm({'message': 'Me caga '})
self.assertFalse(form.is_valid())
def test_validate_long_quote(self):
form = QuoteForm({'message': 'Me caga que sea que Este mensaje es demasiado largo y no pase las pruebas de lo que tenemos que probar asdfadfa adsfasdfa. Me caga que sea que Este mensaje es demasiado largo y no pase las pruebas de lo que tenemos que probar.'})
self.assertFalse(form.is_valid())
def test_valid_message(self):
form = QuoteForm({'message': 'Me caga probar esto'})
self.assertTrue(form.is_valid())<|fim▁end|> | |
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>// Type definitions for csso 3.5
// Project: https://github.com/css/csso
// Definitions by: Christian Rackerseder <https://github.com/screendriver>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
declare namespace csso {
interface Result {
/**
* Resulting CSS.
*/
css: string;
/**
* Instance of SourceMapGenerator or null.
*/
map: object | null;
}
interface CompressOptions {
/**
* Disable or enable a structure optimisations.<|fim▁hole|> /**
* Enables merging of @media rules with the same media query by splitted by other rules.
* The optimisation is unsafe in general, but should work fine in most cases. Use it on your own risk.
* @default false
*/
forceMediaMerge?: boolean;
/**
* Transform a copy of input AST if true. Useful in case of AST reuse.
* @default false
*/
clone?: boolean;
/**
* Specify what comments to leave:
* - 'exclamation' or true – leave all exclamation comments
* - 'first-exclamation' – remove every comment except first one
* - false – remove all comments
* @default true
*/
comments?: string | boolean;
/**
* Usage data for advanced optimisations.
*/
usage?: object;
/**
* Function to track every step of transformation.
*/
logger?: () => void;
}
interface MinifyOptions {
/**
* Generate a source map when true.
* @default false
*/
sourceMap?: boolean;
/**
* Filename of input CSS, uses for source map generation.
* @default '<unknown>'
*/
filename?: string;
/**
* Output debug information to stderr.
* @default false
*/
debug?: boolean;
/**
* Called right after parse is run.
*/
beforeCompress?: BeforeCompressFn | BeforeCompressFn[];
/**
* Called right after compress() is run.
*/
afterCompress?: AfterCompressFn | AfterCompressFn[];
restructure?: boolean;
}
type BeforeCompressFn = (ast: object, options: CompressOptions) => void;
type AfterCompressFn = (compressResult: string, options: CompressOptions) => void;
}
interface Csso {
/**
* Minify source CSS passed as String
* @param source
* @param options
*/
minify(source: string, options?: csso.MinifyOptions & csso.CompressOptions): csso.Result;
/**
* The same as minify() but for list of declarations. Usually it's a style attribute value.
* @param source
* @param options
*/
minifyBlock(source: string, options?: csso.MinifyOptions & csso.CompressOptions): csso.Result;
/**
* Does the main task – compress an AST.
*/
compress(ast: object, options?: csso.CompressOptions): { ast: object };
}
declare const csso: Csso;
export = csso;<|fim▁end|> | * @default true
*/
restructure?: boolean; |
<|file_name|>pass-by-copy.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate debug;
use std::gc::{GC, Gc};
fn magic(x: A) { println!("{:?}", x); }
fn magic2(x: Gc<int>) { println!("{:?}", x); }
struct A { a: Gc<int> }
pub fn main() {
let a = A {a: box(GC) 10};
let b = box(GC) 10;
magic(a); magic(A {a: box(GC) 20});
magic2(b); magic2(box(GC) 20);<|fim▁hole|><|fim▁end|> | } |
<|file_name|>t0288.cc<|end_file_name|><|fim▁begin|>// t0288.cc
// "ambiguous function template instantiation"
// 2005-08-03: This appears to be fixed by the switch to
// the new mtype module.
namespace std
{
template < class _CharT > struct char_traits;
}
typedef int ptrdiff_t;
extern "C"
{
typedef struct __locale_struct
{
}
*__locale_t;
};
typedef struct __pthread_attr_s
{
}
pthread_barrierattr_t;
namespace std
{
typedef ptrdiff_t streamsize;
template < typename _CharT, typename _Traits =
char_traits < _CharT > >class basic_ios;
template < typename _CharT, typename _Traits =
char_traits < _CharT > >class basic_streambuf;
}
extern "C++"
{
namespace std
{
class exception<|fim▁hole|>namespace std
{
template < typename _CharT, typename _Traits > class basic_streambuf
{
public:typedef _CharT char_type;
typedef _Traits traits_type;
typedef basic_streambuf < char_type, traits_type > __streambuf_type;
friend streamsize __copy_streambufs <> (basic_ios < char_type,
traits_type > &__ios,
__streambuf_type * __sbin,
__streambuf_type * __sbout);
};
template < typename _CharT,
typename _Traits > streamsize __copy_streambufs (basic_ios < _CharT,
_Traits > &__ios,
basic_streambuf < _CharT,
_Traits > *__sbin,
basic_streambuf < _CharT,
_Traits > *__sbout)
{
try
{
}
catch (exception & __fail)
{
}
}
extern template streamsize __copy_streambufs (basic_ios < wchar_t > &,
basic_streambuf < wchar_t > *,
basic_streambuf < wchar_t >
*);
}<|fim▁end|> | {
};
}
} |
<|file_name|>file.go<|end_file_name|><|fim▁begin|>package fs
import (
"errors"
"os"
"strings"
"io/ioutil"
"path/filepath"
)
func IsSymLink(m os.FileMode) bool {
return (m & os.ModeSymlink) == os.ModeSymlink
}
func buildCheckSuffix(suffix string) func(string) bool {
suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写
if suffix == "" {
return func(filename string) bool {
return true
}
} else {
return func(filename string) bool {
return strings.HasSuffix(strings.ToUpper(filename), suffix)
}
}
}
//获取指定目录下的所有文件,不进入下一级目录搜索,可以匹配后缀过滤。
func DoListDir(dirPth string, suffix string, f func(fileName string) error) error {
checkSuffix := buildCheckSuffix(suffix)
dir, err := ioutil.ReadDir(dirPth)
if err != nil { //忽略错误
return nil
}
PthSep := string(os.PathSeparator)
for _, fi := range dir {
if fi.IsDir() { // 忽略目录
continue
}
newFile := dirPth + PthSep + fi.Name()
if !checkSuffix(newFile) {
continue
}
if f(newFile) != nil {
return errors.New("user quit")
}
}
return nil
}
//获取指定目录下的所有文件,不进入下一级目录搜索,可以匹配后缀过滤。
func DoListDirEx(dirPth string, suffix string, f func(fullpath string, fileName string) error) error {
checkSuffix := buildCheckSuffix(suffix)
dir, err := ioutil.ReadDir(dirPth)
if err != nil { //忽略错误
return nil
}
PthSep := string(os.PathSeparator)
for _, fi := range dir {
if fi.IsDir() { // 忽略目录
continue
}
newFile := dirPth + PthSep + fi.Name()
if !checkSuffix(newFile) {
continue
}
if f(newFile, fi.Name()) != nil {
return errors.New("user quit")
}
}
return nil
}
//获取指定目录下的所有文件,不进入下一级目录搜索,可以匹配后缀过滤。
func ListDir(dirPth string, suffix string, ch chan<- string) error {
checkSuffix := buildCheckSuffix(suffix)
defer close(ch)
dir, err := ioutil.ReadDir(dirPth)
if err != nil { //忽略错误
return nil
}
PthSep := string(os.PathSeparator)
for _, fi := range dir {
if fi.IsDir() { // 忽略目录
continue
}
newFile := dirPth + PthSep + fi.Name()
if !checkSuffix(newFile) {
continue
}
ch <- newFile
}
return nil
}
func DoWalkDir(dirPth, suffix string, f func(fileName string, isdir bool) error) error {
checkSuffix := buildCheckSuffix(suffix)
err := filepath.Walk(dirPth,
func(filename string, fi os.FileInfo, err error) error { //遍历目录
if err != nil { //忽略错误
// return err
return nil
}
if fi.IsDir() { // 忽略目录
f(filename, true)
return nil
}<|fim▁hole|> f(filename, false)
return nil
})
return err
}
//获取指定目录及所有子目录下的所有文件,可以匹配后缀过滤。
func WalkDir(dirPth, suffix string, ch chan<- string) error {
checkSuffix := buildCheckSuffix(suffix)
defer close(ch)
err := filepath.Walk(dirPth,
func(filename string, fi os.FileInfo, err error) error { //遍历目录
if err != nil { //忽略错误
// return err
return nil
}
if fi.IsDir() { // 忽略目录
return nil
}
if !checkSuffix(filename) {
return nil
}
if fi.Mode().IsRegular() {
ch <- filename
}
return nil
})
return err
}
func PathExists(filename string) bool {
_, err := os.Stat(filename)
return err == nil || os.IsExist(err)
}
func PathExists2(filename string) (bool, error) {
_, err := os.Stat(filename)
if err == nil {
return true, nil
}
if e, ok := err.(*os.PathError); ok && e.Error() == os.ErrNotExist.Error() {
return false, nil
}
return false, err
}<|fim▁end|> | if !checkSuffix(filename) {
return nil
} |
<|file_name|>list.js<|end_file_name|><|fim▁begin|>"use strict";
var Construct = require("can-construct");
var define = require("can-define");
var make = define.make;
var queues = require("can-queues");
var addTypeEvents = require("can-event-queue/type/type");
var ObservationRecorder = require("can-observation-recorder");
var canLog = require("can-log");
var canLogDev = require("can-log/dev/dev");
var defineHelpers = require("../define-helpers/define-helpers");
var assign = require("can-assign");
var diff = require("can-diff/list/list");
var ns = require("can-namespace");
var canReflect = require("can-reflect");
var canSymbol = require("can-symbol");
var singleReference = require("can-single-reference");
var splice = [].splice;
var runningNative = false;
var identity = function(x) {
return x;
};
// symbols aren't enumerable ... we'd need a version of Object that treats them that way
var localOnPatchesSymbol = "can.patches";
var makeFilterCallback = function(props) {
return function(item) {
for (var prop in props) {
if (item[prop] !== props[prop]) {
return false;
}
}
return true;
};
};
var onKeyValue = define.eventsProto[canSymbol.for("can.onKeyValue")];
var offKeyValue = define.eventsProto[canSymbol.for("can.offKeyValue")];
var getSchemaSymbol = canSymbol.for("can.getSchema");
var inSetupSymbol = canSymbol.for("can.initializing");
function getSchema() {
var definitions = this.prototype._define.definitions;
var schema = {
type: "list",
keys: {}
};
schema = define.updateSchemaKeys(schema, definitions);
if(schema.keys["#"]) {
schema.values = definitions["#"].Type;
delete schema.keys["#"];
}
return schema;
}
/** @add can-define/list/list */
var DefineList = Construct.extend("DefineList",
/** @static */
{
setup: function(base) {
if (DefineList) {
addTypeEvents(this);
var prototype = this.prototype;
var result = define(prototype, prototype, base.prototype._define);
define.makeDefineInstanceKey(this, result);
var itemsDefinition = result.definitions["#"] || result.defaultDefinition;
if (itemsDefinition) {
if (itemsDefinition.Type) {
this.prototype.__type = make.set.Type("*", itemsDefinition.Type, identity);
} else if (itemsDefinition.type) {
this.prototype.__type = make.set.type("*", itemsDefinition.type, identity);
}
}
this[getSchemaSymbol] = getSchema;
}
}
},
/** @prototype */
{
// setup for only dynamic DefineMap instances
setup: function(items) {
if (!this._define) {
Object.defineProperty(this, "_define", {
enumerable: false,
value: {
definitions: {
length: { type: "number" },
_length: { type: "number" }
}
}
});
Object.defineProperty(this, "_data", {
enumerable: false,
value: {}
});
}
define.setup.call(this, {}, false);
Object.defineProperty(this, "_length", {
enumerable: false,
configurable: true,
writable: true,
value: 0
});
if (items) {
this.splice.apply(this, [ 0, 0 ].concat(canReflect.toArray(items)));
}
},
__type: define.types.observable,
_triggerChange: function(attr, how, newVal, oldVal) {
var index = +attr;
// `batchTrigger` direct add and remove events...
// Make sure this is not nested and not an expando
if ( !isNaN(index)) {
var itemsDefinition = this._define.definitions["#"];
var patches, dispatched;
if (how === 'add') {
if (itemsDefinition && typeof itemsDefinition.added === 'function') {
ObservationRecorder.ignore(itemsDefinition.added).call(this, newVal, index);
}
patches = [{type: "splice", insert: newVal, index: index, deleteCount: 0}];
dispatched = {
type: how,
action: "splice",
insert: newVal,
index: index,
deleteCount: 0,
patches: patches
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
dispatched.reasonLog = [ canReflect.getName(this), "added", newVal, "at", index ];
}
//!steal-remove-end
this.dispatch(dispatched, [ newVal, index ]);
} else if (how === 'remove') {
if (itemsDefinition && typeof itemsDefinition.removed === 'function') {
ObservationRecorder.ignore(itemsDefinition.removed).call(this, oldVal, index);
}
patches = [{type: "splice", index: index, deleteCount: oldVal.length}];
dispatched = {
type: how,
patches: patches,
action: "splice",
index: index, deleteCount: oldVal.length,
target: this
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
dispatched.reasonLog = [ canReflect.getName(this), "remove", oldVal, "at", index ];
}
//!steal-remove-end
this.dispatch(dispatched, [ oldVal, index ]);
} else {
this.dispatch(how, [ newVal, index ]);
}
} else {
this.dispatch({
type: "" + attr,
target: this
}, [ newVal, oldVal ]);
}
},
get: function(index) {
if (arguments.length) {
if(isNaN(index)) {
ObservationRecorder.add(this, index);
} else {
ObservationRecorder.add(this, "length");
}
return this[index];
} else {
return canReflect.unwrap(this, Map);
}
},
set: function(prop, value) {
// if we are setting a single value
if (typeof prop !== "object") {
// We want change events to notify using integers if we're
// setting an integer index. Note that <float> % 1 !== 0;
prop = isNaN(+prop) || (prop % 1) ? prop : +prop;
if (typeof prop === "number") {
// Check to see if we're doing a .attr() on an out of
// bounds index property.
if (typeof prop === "number" &&
prop > this._length - 1) {
var newArr = new Array((prop + 1) - this._length);
newArr[newArr.length - 1] = value;
this.push.apply(this, newArr);
return newArr;
}
this.splice(prop, 1, value);
} else {
var defined = defineHelpers.defineExpando(this, prop, value);
if (!defined) {
this[prop] = value;
}
}
}
// otherwise we are setting multiple
else {
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
canLogDev.warn('can-define/list/list.prototype.set is deprecated; please use can-define/list/list.prototype.assign or can-define/list/list.prototype.update instead');
}
//!steal-remove-end
//we are deprecating this in #245
if (canReflect.isListLike(prop)) {
if (value) {
this.replace(prop);
} else {
canReflect.assignList(this, prop);
}
} else {
canReflect.assignMap(this, prop);
}
}
return this;
},
assign: function(prop) {
if (canReflect.isListLike(prop)) {
canReflect.assignList(this, prop);
} else {
canReflect.assignMap(this, prop);
}
return this;
},
update: function(prop) {
if (canReflect.isListLike(prop)) {
canReflect.updateList(this, prop);
} else {
canReflect.updateMap(this, prop);
}
return this;
},
assignDeep: function(prop) {
if (canReflect.isListLike(prop)) {
canReflect.assignDeepList(this, prop);
} else {
canReflect.assignDeepMap(this, prop);
}
return this;
},
updateDeep: function(prop) {
if (canReflect.isListLike(prop)) {
canReflect.updateDeepList(this, prop);
} else {
canReflect.updateDeepMap(this, prop);
}
return this;
},
_items: function() {
var arr = [];
this._each(function(item) {
arr.push(item);
});
return arr;
},
_each: function(callback) {
for (var i = 0, len = this._length; i < len; i++) {
callback(this[i], i);
}
},
splice: function(index, howMany) {
var args = canReflect.toArray(arguments),
added = [],
i, len, listIndex,
allSame = args.length > 2,
oldLength = this._length;
index = index || 0;
// converting the arguments to the right type
for (i = 0, len = args.length - 2; i < len; i++) {
listIndex = i + 2;
args[listIndex] = this.__type(args[listIndex], listIndex);
added.push(args[listIndex]);
// Now lets check if anything will change
if (this[i + index] !== args[listIndex]) {
allSame = false;
}
}
// if nothing has changed, then return
if (allSame && this._length <= added.length) {
return added;
}
// default howMany if not provided
if (howMany === undefined) {
howMany = args[1] = this._length - index;
}
runningNative = true;
var removed = splice.apply(this, args);
runningNative = false;
queues.batch.start();
if (howMany > 0) {
// tears down bubbling
this._triggerChange("" + index, "remove", undefined, removed);
}
if (args.length > 2) {
this._triggerChange("" + index, "add", added, removed);
}
this.dispatch('length', [ this._length, oldLength ]);
queues.batch.stop();
return removed;
},
/**
*/
serialize: function() {
return canReflect.serialize(this, Map);
}
}
);
for(var prop in define.eventsProto) {
Object.defineProperty(DefineList.prototype, prop, {
enumerable:false,
value: define.eventsProto[prop],
writable: true
});
}
var eventsProtoSymbols = ("getOwnPropertySymbols" in Object) ?
Object.getOwnPropertySymbols(define.eventsProto) :
[canSymbol.for("can.onKeyValue"), canSymbol.for("can.offKeyValue")];
eventsProtoSymbols.forEach(function(sym) {
Object.defineProperty(DefineList.prototype, sym, {
configurable: true,
enumerable:false,
value: define.eventsProto[sym],
writable: true
});
});
// Converts to an `array` of arguments.
var getArgs = function(args) {
return args[0] && Array.isArray(args[0]) ?
args[0] :
canReflect.toArray(args);
};
// Create `push`, `pop`, `shift`, and `unshift`
canReflect.eachKey({
push: "length",
unshift: 0
},
// Adds a method
// `name` - The method name.
// `where` - Where items in the `array` should be added.
function(where, name) {
var orig = [][name];
DefineList.prototype[name] = function() {
// Get the items being added.
var args = [],
// Where we are going to add items.
len = where ? this._length : 0,
i = arguments.length,
res, val;
// Go through and convert anything to a `map` that needs to be converted.
while (i--) {
val = arguments[i];
args[i] = this.__type(val, i);
}
// Call the original method.
runningNative = true;
res = orig.apply(this, args);
runningNative = false;
if (!this.comparator || args.length) {
queues.batch.start();
this._triggerChange("" + len, "add", args, undefined);
this.dispatch('length', [ this._length, len ]);
queues.batch.stop();
}
return res;
};
});
canReflect.eachKey({
pop: "length",
shift: 0
},
// Creates a `remove` type method
function(where, name) {
var orig = [][name];
DefineList.prototype[name] = function() {
if (!this._length) {
// For shift and pop, we just return undefined without
// triggering events.
return undefined;
}
var args = getArgs(arguments),
len = where && this._length ? this._length - 1 : 0,
oldLength = this._length ? this._length : 0,
res;
// Call the original method.
runningNative = true;
res = orig.apply(this, args);
runningNative = false;
// Create a change where the args are
// `len` - Where these items were removed.
// `remove` - Items removed.
// `undefined` - The new values (there are none).
// `res` - The old, removed values (should these be unbound).
queues.batch.start();
this._triggerChange("" + len, "remove", undefined, [ res ]);
this.dispatch('length', [ this._length, oldLength ]);
queues.batch.stop();
return res;
};
});
canReflect.eachKey({
"map": 3,
"filter": 3,
"reduce": 4,
"reduceRight": 4,
"every": 3,
"some": 3
},
function a(fnLength, fnName) {
DefineList.prototype[fnName] = function() {
var self = this;
var args = [].slice.call(arguments, 0);
var callback = args[0];
var thisArg = args[fnLength - 1] || self;
if (typeof callback === "object") {
callback = makeFilterCallback(callback);
}
args[0] = function() {
var cbArgs = [].slice.call(arguments, 0);
// use .get(index) to ensure observation added.
// the arguments are (item, index) or (result, item, index)
cbArgs[fnLength - 3] = self.get(cbArgs[fnLength - 2]);
return callback.apply(thisArg, cbArgs);
};
var ret = Array.prototype[fnName].apply(this, args);
if(fnName === "map") {
return new DefineList(ret);
}
else if(fnName === "filter") {
return new self.constructor(ret);
} else {
return ret;
}
};
});
assign(DefineList.prototype, {
includes: (function(){
var arrayIncludes = Array.prototype.includes;
if(arrayIncludes){
return function includes() {
return arrayIncludes.apply(this, arguments);
};
} else {
return function includes() {
throw new Error("DefineList.prototype.includes must have Array.prototype.includes available. Please add a polyfill to this environment.");
};
}
})(),
indexOf: function(item, fromIndex) {
for (var i = fromIndex || 0, len = this.length; i < len; i++) {
if (this.get(i) === item) {
return i;
}
}
return -1;
},
lastIndexOf: function(item, fromIndex) {
fromIndex = typeof fromIndex === "undefined" ? this.length - 1: fromIndex;
for (var i = fromIndex; i >= 0; i--) {
if (this.get(i) === item) {
return i;
}
}
return -1;
},
join: function() {
ObservationRecorder.add(this, "length");
return [].join.apply(this, arguments);
},
reverse: function() {
// this shouldn't be observable
var list = [].reverse.call(this._items());
return this.replace(list);
},
slice: function() {
// tells computes to listen on length for changes.
ObservationRecorder.add(this, "length");
var temp = Array.prototype.slice.apply(this, arguments);
return new this.constructor(temp);
},
concat: function() {
var args = [];
// Go through each of the passed `arguments` and
// see if it is list-like, an array, or something else
canReflect.eachIndex(arguments, function(arg) {
if (canReflect.isListLike(arg)) {
// If it is list-like we want convert to a JS array then
// pass each item of the array to this.__type
var arr = Array.isArray(arg) ? arg : canReflect.toArray(arg);
arr.forEach(function(innerArg) {
args.push(this.__type(innerArg));
}, this);
} else {
// If it is a Map, Object, or some primitive
// just pass arg to this.__type
args.push(this.__type(arg));
}
}, this);
// We will want to make `this` list into a JS array
// as well (We know it should be list-like), then
// concat with our passed in args, then pass it to
// list constructor to make it back into a list
return new this.constructor(Array.prototype.concat.apply(canReflect.toArray(this), args));
},
forEach: function(cb, thisarg) {
var item;
for (var i = 0, len = this.length; i < len; i++) {
item = this.get(i);
if (cb.call(thisarg || item, item, i, this) === false) {
break;
}
}
return this;
},
replace: function(newList) {
var patches = diff(this, newList);
queues.batch.start();
for (var i = 0, len = patches.length; i < len; i++) {
this.splice.apply(this, [
patches[i].index,
patches[i].deleteCount
].concat(patches[i].insert));
}
queues.batch.stop();
return this;
},
sort: function(compareFunction) {
var sorting = Array.prototype.slice.call(this);
Array.prototype.sort.call(sorting, compareFunction);
this.splice.apply(this, [0,sorting.length].concat(sorting) );
return this;
}
});
// Add necessary event methods to this object.
for (var prop in define.eventsProto) {
DefineList[prop] = define.eventsProto[prop];
Object.defineProperty(DefineList.prototype, prop, {
enumerable: false,
value: define.eventsProto[prop],
writable: true
});
}
Object.defineProperty(DefineList.prototype, "length", {
get: function() {
if (!this[inSetupSymbol]) {
ObservationRecorder.add(this, "length");
}
return this._length;
},
set: function(newVal) {
if (runningNative) {
this._length = newVal;
return;
}
// Don't set _length if:
// - null or undefined
// - a string that doesn't convert to number
// - already the length being set
if (newVal == null || isNaN(+newVal) || newVal === this._length) {
return;
}
if (newVal > this._length - 1) {
var newArr = new Array(newVal - this._length);
this.push.apply(this, newArr);
}
else {
this.splice(newVal);
}
},
enumerable: true
});
DefineList.prototype.attr = function(prop, value) {
canLog.warn("DefineMap::attr shouldn't be called");
if (arguments.length === 0) {
return this.get();
} else if (prop && typeof prop === "object") {
return this.set.apply(this, arguments);
} else if (arguments.length === 1) {
return this.get(prop);
} else {
return this.set(prop, value);
}
};
DefineList.prototype.item = function(index, value) {
if (arguments.length === 1) {
return this.get(index);
} else {
return this.set(index, value);
}
};
DefineList.prototype.items = function() {
canLog.warn("DefineList::get should should be used instead of DefineList::items");
return this.get();
};
var defineListProto = {
// type
"can.isMoreListLikeThanMapLike": true,
"can.isMapLike": true,
"can.isListLike": true,
"can.isValueLike": false,
// get/set
"can.getKeyValue": DefineList.prototype.get,
"can.setKeyValue": DefineList.prototype.set,
// Called for every reference to a property in a template
// if a key is a numerical index then translate to length event
"can.onKeyValue": function(key, handler, queue) {
var translationHandler;
if (isNaN(key)) {
return onKeyValue.apply(this, arguments);
}
else {
translationHandler = function() {
handler(this[key]);
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
Object.defineProperty(translationHandler, "name", {
value: "translationHandler(" + key + ")::" + canReflect.getName(this) + ".onKeyValue('length'," + canReflect.getName(handler) + ")",
});
}
//!steal-remove-end
singleReference.set(handler, this, translationHandler, key);
return onKeyValue.call(this, 'length', translationHandler, queue);
}
},
// Called when a property reference is removed
"can.offKeyValue": function(key, handler, queue) {
var translationHandler;
if ( isNaN(key)) {
return offKeyValue.apply(this, arguments);
}
else {
translationHandler = singleReference.getAndDelete(handler, this, key);
return offKeyValue.call(this, 'length', translationHandler, queue);
}
},
"can.deleteKeyValue": function(prop) {
// convert string key to number index if key can be an integer:
// isNaN if prop isn't a numeric representation
// (prop % 1) if numeric representation is a float
// In both of the above cases, leave as string.
prop = isNaN(+prop) || (prop % 1) ? prop : +prop;
if(typeof prop === "number") {
this.splice(prop, 1);
} else if(prop === "length" || prop === "_length") {
return; // length must not be deleted
} else {
this.set(prop, undefined);
}
return this;
},
// shape get/set
"can.assignDeep": function(source){
queues.batch.start();
canReflect.assignList(this, source);
queues.batch.stop();
},
"can.updateDeep": function(source){
queues.batch.start();
this.replace(source);
queues.batch.stop();
},
// observability
"can.keyHasDependencies": function(key) {
return !!(this._computed && this._computed[key] && this._computed[key].compute);
},
"can.getKeyDependencies": function(key) {
var ret;
if(this._computed && this._computed[key] && this._computed[key].compute) {
ret = {};
ret.valueDependencies = new Set();
ret.valueDependencies.add(this._computed[key].compute);
}
return ret;
},
/*"can.onKeysAdded": function(handler,queue) {
this[canSymbol.for("can.onKeyValue")]("add", handler,queue);
},
"can.onKeysRemoved": function(handler,queue) {
this[canSymbol.for("can.onKeyValue")]("remove", handler,queue);
},*/
"can.splice": function(index, deleteCount, insert){
this.splice.apply(this, [index, deleteCount].concat(insert));
},
"can.onPatches": function(handler,queue){
this[canSymbol.for("can.onKeyValue")](localOnPatchesSymbol, handler,queue);
},
"can.offPatches": function(handler,queue) {
this[canSymbol.for("can.offKeyValue")](localOnPatchesSymbol, handler,queue);
}
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
defineListProto["can.getName"] = function() {
return canReflect.getName(this.constructor) + "[]";<|fim▁hole|>canReflect.assignSymbols(DefineList.prototype, defineListProto);
canReflect.setKeyValue(DefineList.prototype, canSymbol.iterator, function() {
var index = -1;
if(typeof this.length !== "number") {
this.length = 0;
}
return {
next: function() {
index++;
return {
value: this[index],
done: index >= this.length
};
}.bind(this)
};
});
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
// call `list.log()` to log all event changes
// pass `key` to only log the matching event, e.g: `list.log("add")`
DefineList.prototype.log = defineHelpers.log;
}
//!steal-remove-end
define.DefineList = DefineList;
module.exports = ns.DefineList = DefineList;<|fim▁end|> | };
}
//!steal-remove-end
|
<|file_name|>plot_kmeans_digits.py<|end_file_name|><|fim▁begin|>"""
===========================================================
A demo of K-Means clustering on the handwritten digits data
===========================================================
In this example with compare the various initialization strategies for
K-means in terms of runtime and quality of the results.
As the ground truth is known here, we also apply different cluster
quality metrics to judge the goodness of fit of the cluster labels to the
ground truth.
Cluster quality metrics evaluated (see :ref:`clustering_evaluation` for
definitions and discussions of the metrics):
=========== ========================================================
Shorthand full name
=========== ========================================================
homo homogeneity score
compl completeness score
v-meas V measure
ARI adjusted Rand index
AMI adjusted mutual information
silhouette silhouette coefficient
=========== ========================================================
"""
print(__doc__)
from time import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale
np.random.seed(42)
digits = load_digits()
data = scale(digits.data)
n_samples, n_features = data.shape
n_digits = len(np.unique(digits.target))
labels = digits.target
<|fim▁hole|>sample_size = 300
print("n_digits: %d, \t n_samples %d, \t n_features %d"
% (n_digits, n_samples, n_features))
print(79 * '_')
print('% 9s' % 'init'
' time inertia homo compl v-meas ARI AMI silhouette')
def bench_k_means(estimator, name, data):
t0 = time()
estimator.fit(data)
print('% 9s %.2fs %i %.3f %.3f %.3f %.3f %.3f %.3f'
% (name, (time() - t0), estimator.inertia_,
metrics.homogeneity_score(labels, estimator.labels_),
metrics.completeness_score(labels, estimator.labels_),
metrics.v_measure_score(labels, estimator.labels_),
metrics.adjusted_rand_score(labels, estimator.labels_),
metrics.adjusted_mutual_info_score(labels, estimator.labels_),
metrics.silhouette_score(data, estimator.labels_,
metric='euclidean',
sample_size=sample_size)))
bench_k_means(KMeans(init='k-means++', n_clusters=n_digits, n_init=10),
name="k-means++", data=data)
bench_k_means(KMeans(init='random', n_clusters=n_digits, n_init=10),
name="random", data=data)
# in this case the seeding of the centers is deterministic, hence we run the
# kmeans algorithm only once with n_init=1
pca = PCA(n_components=n_digits).fit(data)
bench_k_means(KMeans(init=pca.components_, n_clusters=n_digits, n_init=1),
name="PCA-based",
data=data)
print(79 * '_')
###############################################################################
# Visualize the results on PCA-reduced data
reduced_data = PCA(n_components=2).fit_transform(data)
kmeans = KMeans(init='k-means++', n_clusters=n_digits, n_init=10)
kmeans.fit(reduced_data)
# Step size of the mesh. Decrease to increase the quality of the VQ.
h = .02 # point in the mesh [x_min, m_max]x[y_min, y_max].
# Plot the decision boundary. For that, we will assign a color to each
x_min, x_max = reduced_data[:, 0].min() + 1, reduced_data[:, 0].max() - 1
y_min, y_max = reduced_data[:, 1].min() + 1, reduced_data[:, 1].max() - 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# Obtain labels for each point in mesh. Use last trained model.
Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(1)
plt.clf()
plt.imshow(Z, interpolation='nearest',
extent=(xx.min(), xx.max(), yy.min(), yy.max()),
cmap=plt.cm.Paired,
aspect='auto', origin='lower')
plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2)
# Plot the centroids as a white X
centroids = kmeans.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1],
marker='x', s=169, linewidths=3,
color='w', zorder=10)
plt.title('K-means clustering on the digits dataset (PCA-reduced data)\n'
'Centroids are marked with white cross')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
plt.show()<|fim▁end|> | |
<|file_name|>socket.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import errno
import json
import logging
import threading
import time
import websocket
import parlai.chat_service.utils.logging as log_utils
SOCKET_TIMEOUT = 6
# Socket handler
class ChatServiceMessageSocket:
"""
ChatServiceMessageSocket is a wrapper around websocket to forward messages from the
remote server to the ChatServiceManager.
"""
def __init__(self, server_url, port, message_callback):
"""
server_url: url at which the server is to be run
port: port for the socket to operate on
message_callback: function to be called on incoming message objects (format: message_callback(self, data))
"""
self.server_url = server_url
self.port = port
self.message_callback = message_callback
self.ws = None
self.last_pong = None
self.alive = False
# initialize the state
self.listen_thread = None
# setup the socket
self.keep_running = True
self._setup_socket()
def _safe_send(self, data, force=False):
if not self.alive and not force:
# Try to wait a second to send a packet
timeout = 1
while timeout > 0 and not self.alive:
time.sleep(0.1)
timeout -= 0.1
if not self.alive:
# don't try to send a packet if we're still dead
return False
try:
self.ws.send(data)
except websocket.WebSocketConnectionClosedException:
# The channel died mid-send, wait for it to come back up
return False
return True
def _ensure_closed(self):
try:
self.ws.close()
except websocket.WebSocketConnectionClosedException:
pass
def _send_world_alive(self):
"""
Registers world with the passthrough server.
"""
self._safe_send(
json.dumps(
{
'type': 'world_alive',
'content': {'id': 'WORLD_ALIVE', 'sender_id': 'world'},
}
),
force=True,
)
def _setup_socket(self):
"""
Create socket handlers and registers the socket.
"""
def on_socket_open(*args):
log_utils.print_and_log(logging.DEBUG, 'Socket open: {}'.format(args))
self._send_world_alive()
def on_error(ws, error):
try:
if error.errno == errno.ECONNREFUSED:
self._ensure_closed()
self.use_socket = False
raise Exception("Socket refused connection, cancelling")
else:
log_utils.print_and_log(
logging.WARN, 'Socket logged error: {}'.format(repr(error))
)
except BaseException:
if type(error) is websocket.WebSocketConnectionClosedException:
return # Connection closed is noop
log_utils.print_and_log(
logging.WARN,
'Socket logged error: {} Restarting'.format(repr(error)),
)
self._ensure_closed()
def on_disconnect(*args):
"""
Disconnect event is a no-op for us, as the server reconnects automatically
on a retry.
"""
log_utils.print_and_log(
logging.INFO, 'World server disconnected: {}'.format(args)
)
self.alive = False
self._ensure_closed()
def on_message(*args):
"""
Incoming message handler for messages from the FB user.
"""
packet_dict = json.loads(args[1])
if packet_dict['type'] == 'conn_success':
self.alive = True
return # No action for successful connection
if packet_dict['type'] == 'pong':
self.last_pong = time.time()
return # No further action for pongs
message_data = packet_dict['content']
log_utils.print_and_log(
logging.DEBUG, 'Message data received: {}'.format(message_data)
)
for message_packet in message_data['entry']:
for message in message_packet['messaging']:
self.message_callback(message)
def run_socket(*args):
url_base_name = self.server_url.split('https://')[1]
while self.keep_running:
try:
sock_addr = "wss://{}/".format(url_base_name)
self.ws = websocket.WebSocketApp(
sock_addr,
on_message=on_message,
on_error=on_error,
on_close=on_disconnect,
)
self.ws.on_open = on_socket_open
self.ws.run_forever(ping_interval=1, ping_timeout=0.9)
except Exception as e:
log_utils.print_and_log(
logging.WARN,
'Socket error {}, attempting restart'.format(repr(e)),
)
time.sleep(0.2)
# Start listening thread
self.listen_thread = threading.Thread(<|fim▁hole|> target=run_socket, name='Main-Socket-Thread'
)
self.listen_thread.daemon = True
self.listen_thread.start()
time.sleep(1.2)
while not self.alive:
try:
self._send_world_alive()
except Exception:
pass
time.sleep(0.8)<|fim▁end|> | |
<|file_name|>Header.spec.js<|end_file_name|><|fim▁begin|>import React from 'react'
import { Header } from 'components/Header/Header'
import { IndexLink, Link } from 'react-router'
import { shallow } from 'enzyme'
describe('(Component) Header', () => {
let _wrapper
beforeEach(() => {
_wrapper = shallow(<Header />)
})
it('Renders a welcome message', () => {
const welcome = _wrapper.find('h1')
expect(welcome).to.exist
expect(welcome.text()).to.match(/React Redux Starter Kit/)
})
<|fim▁hole|> describe('Navigation links...', () => {
it('Should render a Link to home route', () => {
expect(_wrapper.contains(
<IndexLink activeClassName='route--active' to='/'>
Home
</IndexLink>
)).to.be.true
})
it('Should render a Link to Counter route', () => {
expect(_wrapper.contains(
<Link activeClassName='route--active' to='/counter'>
Counter
</Link>
)).to.be.true
})
})
})<|fim▁end|> | |
<|file_name|>confirmbox.js<|end_file_name|><|fim▁begin|>/**
* This file is part of "PCPIN Chat 6".
*
* "PCPIN Chat 6" 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.
*
* "PCPIN Chat 6" 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, see <http://www.gnu.org/licenses/>.
*/
/**
* Callback function to execute after confirm box receives "OK".
*/
var confirmboxCallback='';
/**
* Display confirm box
* @param string $text Text to display
* @param int top_offset Optional. How many pixels to add to the top position. Can be negative or positive.
* @param int left_offset Optional. How many pixels to add to the left position. Can be negative or positive.
* @param string callback Optional. Callback function to execute after confirm box receives "OK".
*/
function confirm(text, top_offset, left_offset, callback) {
if (typeof(text)!='undefined' && typeof(text)!='string') {
try {
text=text.toString();
} catch (e) {}
}
if (typeof(text)=='string') {
document.onkeyup_confirmbox=document.onkeyup;
document.onkeyup=function(e) {
switch (getKC(e)) {
case 27:
hideConfirmBox(false);<|fim▁hole|> }
};
if (typeof(top_offset)!='number') top_offset=0;
if (typeof(left_offset)!='number') left_offset=0;
$('confirmbox_text').innerHTML=nl2br(htmlspecialchars(text));
$('confirmbox').style.display='';
$('confirmbox_btn_ok').focus();
setTimeout("moveToCenter($('confirmbox'), "+top_offset+", "+left_offset+"); $('confirmbox_btn_ok').focus();", 25);
if (typeof(callback)=='string') {
confirmboxCallback=callback;
} else {
confirmboxCallback='';
}
setTimeout("$('confirmbox').style.display='none'; $('confirmbox').style.display='';", 200);
}
}
/**
* Hide confirm box
@param boolean ok TRUE, if "OK" button was clicked
*/
function hideConfirmBox(ok) {
document.onkeyup=document.onkeyup_confirmbox;
$('confirmbox').style.display='none';
if (typeof(ok)=='boolean' && ok && confirmboxCallback!='') {
eval('try { '+confirmboxCallback+' } catch(e) {}');
}
}<|fim▁end|> | break; |
<|file_name|>delete-link-handler.ts<|end_file_name|><|fim▁begin|>// (C) Copyright 2015 Moodle Pty 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
//<|fim▁hole|>// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { CoreContentLinksHandlerBase } from '@core/contentlinks/classes/base-handler';
import { CoreContentLinksAction } from '@core/contentlinks/providers/delegate';
import { AddonModDataProvider } from './data';
import { AddonModDataHelperProvider } from './helper';
/**
* Content links handler for database delete entry.
* Match mod/data/view.php?d=6&delete=5 with a valid data id and entryid.
*/
@Injectable()
export class AddonModDataDeleteLinkHandler extends CoreContentLinksHandlerBase {
name = 'AddonModDataDeleteLinkHandler';
featureName = 'CoreCourseModuleDelegate_AddonModData';
pattern = /\/mod\/data\/view\.php.*([\?\&](d|delete)=\d+)/;
constructor(private dataProvider: AddonModDataProvider, private dataHelper: AddonModDataHelperProvider) {
super();
}
/**
* Get the list of actions for a link (url).
*
* @param siteIds List of sites the URL belongs to.
* @param url The URL to treat.
* @param params The params of the URL. E.g. 'mysite.com?id=1' -> {id: 1}
* @param courseId Course ID related to the URL. Optional but recommended.
* @return List of (or promise resolved with list of) actions.
*/
getActions(siteIds: string[], url: string, params: any, courseId?: number):
CoreContentLinksAction[] | Promise<CoreContentLinksAction[]> {
return [{
action: (siteId, navCtrl?): void => {
const dataId = parseInt(params.d, 10);
const entryId = parseInt(params.delete, 10);
this.dataHelper.showDeleteEntryModal(dataId, entryId, courseId);
}
}];
}
/**
* Check if the handler is enabled for a certain site (site + user) and a URL.
* If not defined, defaults to true.
*
* @param siteId The site ID.
* @param url The URL to treat.
* @param params The params of the URL. E.g. 'mysite.com?id=1' -> {id: 1}
* @param courseId Course ID related to the URL. Optional but recommended.
* @return Whether the handler is enabled for the URL and site.
*/
isEnabled(siteId: string, url: string, params: any, courseId?: number): boolean | Promise<boolean> {
if (typeof params.d == 'undefined' || typeof params.delete == 'undefined') {
// Required fields not defined. Cannot treat the URL.
return false;
}
return this.dataProvider.isPluginEnabled(siteId);
}
}<|fim▁end|> | // 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. |
<|file_name|>EnergyConsumer.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010-2011 Richard Lincoln
#
# 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<|fim▁hole|>
from CIM15.CDPSM.Balanced.IEC61970.Core.IdentifiedObject import IdentifiedObject
class EnergyConsumer(IdentifiedObject):
"""Generic user of energy - a point of consumption on the power system model
"""
def __init__(self, customerCount=0, pfixedPct=0.0, qfixedPct=0.0, qfixed=0.0, pfixed=0.0, LoadResponse=None, *args, **kw_args):
"""Initialises a new 'EnergyConsumer' instance.
@param customerCount: Number of individual customers represented by this Demand
@param pfixedPct: Fixed active power as per cent of load group fixed active power. Load sign convention is used, i.e. positive sign means flow out from a node.
@param qfixedPct: Fixed reactive power as per cent of load group fixed reactive power. Load sign convention is used, i.e. positive sign means flow out from a node.
@param qfixed: Reactive power of the load that is a fixed quantity. Load sign convention is used, i.e. positive sign means flow out from a node.
@param pfixed: Active power of the load that is a fixed quantity. Load sign convention is used, i.e. positive sign means flow out from a node.
@param LoadResponse: The load response characteristic of this load.
"""
#: Number of individual customers represented by this Demand
self.customerCount = customerCount
#: Fixed active power as per cent of load group fixed active power. Load sign convention is used, i.e. positive sign means flow out from a node.
self.pfixedPct = pfixedPct
#: Fixed reactive power as per cent of load group fixed reactive power. Load sign convention is used, i.e. positive sign means flow out from a node.
self.qfixedPct = qfixedPct
#: Reactive power of the load that is a fixed quantity. Load sign convention is used, i.e. positive sign means flow out from a node.
self.qfixed = qfixed
#: Active power of the load that is a fixed quantity. Load sign convention is used, i.e. positive sign means flow out from a node.
self.pfixed = pfixed
self._LoadResponse = None
self.LoadResponse = LoadResponse
super(EnergyConsumer, self).__init__(*args, **kw_args)
_attrs = ["customerCount", "pfixedPct", "qfixedPct", "qfixed", "pfixed"]
_attr_types = {"customerCount": int, "pfixedPct": float, "qfixedPct": float, "qfixed": float, "pfixed": float}
_defaults = {"customerCount": 0, "pfixedPct": 0.0, "qfixedPct": 0.0, "qfixed": 0.0, "pfixed": 0.0}
_enums = {}
_refs = ["LoadResponse"]
_many_refs = []
def getLoadResponse(self):
"""The load response characteristic of this load.
"""
return self._LoadResponse
def setLoadResponse(self, value):
if self._LoadResponse is not None:
filtered = [x for x in self.LoadResponse.EnergyConsumer if x != self]
self._LoadResponse._EnergyConsumer = filtered
self._LoadResponse = value
if self._LoadResponse is not None:
if self not in self._LoadResponse._EnergyConsumer:
self._LoadResponse._EnergyConsumer.append(self)
LoadResponse = property(getLoadResponse, setLoadResponse)<|fim▁end|> | # 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. |
<|file_name|>scheduler.py<|end_file_name|><|fim▁begin|># Copyright (c) Mathias Kaerlev 2012.
# This file is part of pyspades.
# pyspades 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.
# pyspades 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 pyspades. If not, see <http://www.gnu.org/licenses/>.
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
try:
from weakref import WeakSet
except ImportError:
# python 2.6 support (sigh)
from weakref import WeakKeyDictionary
class WeakSet(object):
def __init__(self):
self._dict = WeakKeyDictionary()
def add(self, value):
self._dict[value] = True
def remove(self, value):
del self._dict[value]
def __iter__(self):
for key in self._dict.keys():
yield key
def __contains__(self, other):
return other in self._dict
def __len__(self):
return len(self._dict)
class Scheduler(object):
def __init__(self, protocol):
self.protocol = protocol
self.calls = WeakSet()
self.loops = WeakSet()
def call_later(self, *arg, **kw):
call = reactor.callLater(*arg, **kw)
self.calls.add(call)
return call
def call_end(self, *arg, **kw):
call = self.protocol.call_end(*arg, **kw)
self.calls.add(call)
return call
<|fim▁hole|> loop = LoopingCall(func, *arg, **kw)
loop.start(delay, False)
self.loops.add(loop)
return loop
def reset(self):
for call in self.calls:
if call.active():
call.cancel()
for loop in self.loops:
if loop.running:
loop.stop()
self.calls = WeakSet()
self.loops = WeakSet()<|fim▁end|> | def loop_call(self, delay, func, *arg, **kw):
|
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>from django.forms import ModelForm
from django import forms
from crispy_forms import layout
from crispy_forms.layout import Layout, HTML
from hs_core.forms import BaseFormHelper, Helper
from hs_core.hydroshare import users
from hs_modelinstance.models import ModelOutput, ExecutedBy
from hs_modflow_modelinstance.models import StudyArea, GridDimensions, StressPeriod, \
GroundWaterFlow, BoundaryCondition, ModelCalibration, ModelInput, GeneralElements
class MetadataField(layout.Field):
def __init__(self, *args, **kwargs):
kwargs['css_class'] = 'form-control input-sm'
super(MetadataField, self).__init__(*args, **kwargs)
<|fim▁hole|> *args, **kwargs):
# the order in which the model fields are listed for the FieldSet is the order these fields
# will be displayed
layout = Layout(
MetadataField('includes_output'),
)
kwargs['element_name_label'] = 'Includes output files?'
super(ModelOutputFormHelper, self).__init__(allow_edit, res_short_id, element_id,
element_name, layout, *args, **kwargs)
class ModelOutputForm(ModelForm):
includes_output = forms.TypedChoiceField(choices=((True, 'Yes'), (False, 'No')),
widget=forms.RadioSelect(
attrs={'style': 'width:auto;margin-top:-5px'}))
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, *args, **kwargs):
super(ModelOutputForm, self).__init__(*args, **kwargs)
self.helper = ModelOutputFormHelper(allow_edit, res_short_id, element_id,
element_name='ModelOutput')
class Meta:
model = ModelOutput
fields = ('includes_output',)
class ModelOutputValidationForm(forms.Form):
includes_output = forms.TypedChoiceField(choices=((True, 'Yes'), (False, 'No')), required=False)
def clean_includes_output(self):
data = self.cleaned_data['includes_output']
if data == u'False':
return False
else:
return True
# ExecutedBy element forms
class ExecutedByFormHelper(BaseFormHelper):
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, element_name=None,
*args, **kwargs):
# pop the model program shortid out of the kwargs dictionary
mp_id = kwargs.pop('mpshortid')
# get all model program resources and build option HTML elements for each one.
# ModelProgram shortid is concatenated to the selectbox id so that it is accessible in the
# template.
mp_resource = users.get_resource_list(type=['ModelProgramResource'])
options = '\n'.join(['<option value=%s>%s</option>' % (r.short_id, r.title) for r in
mp_resource])
options = '<option value=Unspecified>Unspecified</option>' + options
selectbox = HTML('<div class="div-selectbox">'
' <select class="selectbox" id="selectbox_'+mp_id+'">' + options +
'</select>'
'</div><br>')
# the order in which the model fields are listed for the FieldSet is the order these fields
# will be displayed
layout = Layout(
MetadataField('model_name', style="display:none"),
selectbox,
HTML("""
<div id=program_details_div style="display:none">
<table id="program_details_table" class="modelprogram">
<tr><td>Description: </td><td></td></tr>
<tr><td>Release Date: </td><td></td></tr>
<tr><td>Version: </td><td></td></tr>
<tr><td>Language: </td><td></td></tr>
<tr><td>Operating System: </td><td></td></tr>
<tr><td>Url: </td><td></td></tr>
</table>
</div>
"""),
)
kwargs['element_name_label'] = 'Model Program used for execution'
super(ExecutedByFormHelper, self).__init__(allow_edit, res_short_id, element_id,
element_name, layout, *args, **kwargs)
class ExecutedByForm(ModelForm):
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, *args, **kwargs):
super(ExecutedByForm, self).__init__(*args, **kwargs)
# set mpshort id to 'Unspecified' if a foreign key has not been established yet,
# otherwise use mp short id
mpshortid = 'Unspecified'
if self.instance.model_program_fk is not None:
mpshortid = self.instance.model_program_fk.short_id
kwargs = dict(mpshortid=mpshortid)
self.helper = ExecutedByFormHelper(allow_edit, res_short_id, element_id,
element_name='ExecutedBy', **kwargs)
class Meta:
model = ExecutedBy
exclude = ('content_object', 'model_program_fk',)
class ExecutedByValidationForm(forms.Form):
model_name = forms.CharField(max_length=200)
# StudyArea element forms
class StudyAreaFormHelper(BaseFormHelper):
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, element_name=None,
*args, **kwargs):
# the order in which the model fields are listed for the FieldSet is the order these fields
# will be displayed
layout = Layout(
MetadataField('totalLength'),
MetadataField('totalWidth'),
MetadataField('maximumElevation'),
MetadataField('minimumElevation'),
)
kwargs['element_name_label'] = 'Study Area'
super(StudyAreaFormHelper, self).__init__(allow_edit, res_short_id, element_id,
element_name, layout, *args, **kwargs)
class StudyAreaForm(ModelForm):
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, *args, **kwargs):
super(StudyAreaForm, self).__init__(*args, **kwargs)
self.helper = StudyAreaFormHelper(allow_edit, res_short_id, element_id,
element_name='StudyArea')
class Meta:
model = StudyArea
fields = ('totalLength',
'totalWidth',
'maximumElevation',
'minimumElevation',
)
class StudyAreaValidationForm(forms.Form):
totalLength = forms.CharField(max_length=100, required=False)
totalWidth = forms.CharField(max_length=100, required=False)
maximumElevation = forms.CharField(max_length=100, required=False)
minimumElevation = forms.CharField(max_length=100, required=False)
# GridDimensions element forms
class GridDimensionsFormHelper(BaseFormHelper):
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, element_name=None,
*args, **kwargs):
# the order in which the model fields are listed for the FieldSet is the order these fields
# will be displayed
layout = Layout(
MetadataField('numberOfLayers'),
MetadataField('typeOfRows'),
MetadataField('numberOfRows'),
MetadataField('typeOfColumns'),
MetadataField('numberOfColumns'),
)
kwargs['element_name_label'] = 'Grid Dimensions'
super(GridDimensionsFormHelper, self).__init__(allow_edit, res_short_id, element_id,
element_name, layout, *args, **kwargs)
class GridDimensionsForm(ModelForm):
grid_type_choices = (('Choose a type', 'Choose a type'),) + GridDimensions.gridTypeChoices
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, *args, **kwargs):
super(GridDimensionsForm, self).__init__(*args, **kwargs)
self.helper = GridDimensionsFormHelper(allow_edit, res_short_id, element_id,
element_name='GridDimensions')
self.fields['typeOfRows'].choices = self.grid_type_choices
self.fields['typeOfColumns'].choices = self.grid_type_choices
class Meta:
model = GridDimensions
fields = ('numberOfLayers',
'typeOfRows',
'numberOfRows',
'typeOfColumns',
'numberOfColumns',
)
class GridDimensionsValidationForm(forms.Form):
numberOfLayers = forms.CharField(max_length=100, required=False)
typeOfRows = forms.CharField(max_length=100, required=False)
numberOfRows = forms.CharField(max_length=100, required=False)
typeOfColumns = forms.CharField(max_length=100, required=False)
numberOfColumns = forms.CharField(max_length=100, required=False)
# StressPeriod element forms
class StressPeriodFormHelper(BaseFormHelper):
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, element_name=None,
*args, **kwargs):
# the order in which the model fields are listed for the FieldSet is the order these fields
# will be displayed
layout = Layout(
MetadataField('stressPeriodType'),
MetadataField('steadyStateValue'),
MetadataField('transientStateValueType'),
MetadataField('transientStateValue'),
)
kwargs['element_name_label'] = 'Stress Period'
super(StressPeriodFormHelper, self).__init__(allow_edit, res_short_id, element_id,
element_name, layout, *args, **kwargs)
class StressPeriodForm(ModelForm):
stress_period_type_choices = \
(('Choose a type', 'Choose a type'),) + StressPeriod.stressPeriodTypeChoices
transient_state_value_type_choices = \
(('Choose a type', 'Choose a type'),) + StressPeriod.transientStateValueTypeChoices
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, *args, **kwargs):
super(StressPeriodForm, self).__init__(*args, **kwargs)
self.helper = StressPeriodFormHelper(allow_edit, res_short_id, element_id,
element_name='StressPeriod')
self.fields['stressPeriodType'].choices = self.stress_period_type_choices
self.fields['transientStateValueType'].choices = self.transient_state_value_type_choices
class Meta:
model = StressPeriod
fields = ('stressPeriodType',
'steadyStateValue',
'transientStateValueType',
'transientStateValue',
)
class StressPeriodValidationForm(forms.Form):
stressPeriodType = forms.CharField(max_length=100, required=False)
steadyStateValue = forms.CharField(max_length=100, required=False)
transientStateValueType = forms.CharField(max_length=100, required=False)
transientStateValue = forms.CharField(max_length=100, required=False)
# GroundWaterFlow element forms
class GroundWaterFlowFormHelper(BaseFormHelper):
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, element_name=None,
*args, **kwargs):
# the order in which the model fields are listed for the FieldSet is the order these fields
# will be displayed
layout = Layout(
MetadataField('flowPackage'),
MetadataField('unsaturatedZonePackage'),
MetadataField('horizontalFlowBarrierPackage'),
MetadataField('seawaterIntrusionPackage'),
MetadataField('flowParameter'),
)
kwargs['element_name_label'] = 'Groundwater Flow'
super(GroundWaterFlowFormHelper, self).__init__(allow_edit, res_short_id, element_id,
element_name, layout, *args, **kwargs)
class GroundWaterFlowForm(ModelForm):
flow_package_choices = \
(('Choose a package', 'Choose a package'),) + GroundWaterFlow.flowPackageChoices
flow_parameter_choices = \
(('Choose a parameter', 'Choose a parameter'),) + GroundWaterFlow.flowParameterChoices
unsaturatedZonePackage = forms.BooleanField(
label='Includes Unsaturated Zone Package package (UZF) ', widget=forms.CheckboxInput(
attrs={'style': 'width:auto;margin-top:-5px'}))
horizontalFlowBarrierPackage = forms.BooleanField(
label='Includes Horizontal Flow Barrier package (HFB6)', widget=forms.CheckboxInput(
attrs={'style': 'width:auto;margin-top:-5px'}))
seawaterIntrusionPackage = forms.BooleanField(
label='Includes Seawater Intrusion package (SWI2)', widget=forms.CheckboxInput(
attrs={'style': 'width:auto;margin-top:-5px'}))
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, *args, **kwargs):
super(GroundWaterFlowForm, self).__init__(*args, **kwargs)
self.helper = GroundWaterFlowFormHelper(allow_edit, res_short_id, element_id,
element_name='GroundWaterFlow')
self.fields['flowPackage'].choices = self.flow_package_choices
self.fields['flowParameter'].choices = self.flow_parameter_choices
class Meta:
model = GroundWaterFlow
fields = ('flowPackage',
'unsaturatedZonePackage',
'horizontalFlowBarrierPackage',
'seawaterIntrusionPackage',
'flowParameter',
)
class GroundWaterFlowValidationForm(forms.Form):
flowPackage = forms.CharField(max_length=100, required=False)
unsaturatedZonePackage = forms.BooleanField(required=False)
horizontalFlowBarrierPackage = forms.BooleanField(required=False)
seawaterIntrusionPackage = forms.BooleanField(required=False)
flowParameter = forms.CharField(max_length=100, required=False)
# BoundaryCondition element forms
class BoundaryConditionFormHelper(BaseFormHelper):
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, element_name=None,
*args, **kwargs):
# the order in which the model fields are listed for the FieldSet is the order these fields
# will be displayed
layout = Layout(
MetadataField('specified_head_boundary_packages'),
MetadataField('other_specified_head_boundary_packages'),
MetadataField('specified_flux_boundary_packages'),
MetadataField('other_specified_flux_boundary_packages'),
MetadataField('head_dependent_flux_boundary_packages'),
MetadataField('other_head_dependent_flux_boundary_packages'),
)
kwargs['element_name_label'] = 'Boundary Condition'
super(BoundaryConditionFormHelper, self).__init__(allow_edit, res_short_id, element_id,
element_name, layout, *args, **kwargs)
class BoundaryConditionForm(ModelForm):
specified_head_boundary_packages = forms.MultipleChoiceField(
choices=BoundaryCondition.specifiedHeadBoundaryPackageChoices,
widget=forms.CheckboxSelectMultiple(attrs={'style': 'width:auto;margin-top:-5px'}))
specified_flux_boundary_packages = forms.MultipleChoiceField(
choices=BoundaryCondition.specifiedFluxBoundaryPackageChoices,
widget=forms.CheckboxSelectMultiple(attrs={'style': 'width:auto;margin-top:-5px'}))
head_dependent_flux_boundary_packages = forms.MultipleChoiceField(
choices=BoundaryCondition.headDependentFluxBoundaryPackageChoices,
widget=forms.CheckboxSelectMultiple(attrs={'style': 'width:auto;margin-top:-5px'}))
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, *args, **kwargs):
super(BoundaryConditionForm, self).__init__(*args, **kwargs)
self.helper = BoundaryConditionFormHelper(allow_edit, res_short_id, element_id,
element_name='BoundaryCondition')
if self.instance:
if self.instance.id:
self.fields['specified_head_boundary_packages'].initial = \
[types.description for types in
self.instance.specified_head_boundary_packages.all()]
self.fields['specified_flux_boundary_packages'].initial = \
[packages.description for packages in
self.instance.specified_flux_boundary_packages.all()]
self.fields['head_dependent_flux_boundary_packages'].initial = \
[packages.description for packages in
self.instance.head_dependent_flux_boundary_packages.all()]
class Meta:
model = BoundaryCondition
exclude = ('specified_head_boundary_packages',
'specified_flux_boundary_packages',
'head_dependent_flux_boundary_packages',
)
fields = ('other_specified_head_boundary_packages',
'other_specified_flux_boundary_packages',
'other_head_dependent_flux_boundary_packages',
)
class BoundaryConditionValidationForm(forms.Form):
specified_head_boundary_packages = forms.MultipleChoiceField(
choices=BoundaryCondition.specifiedHeadBoundaryPackageChoices, required=False)
specified_flux_boundary_packages = forms.MultipleChoiceField(
choices=BoundaryCondition.specifiedFluxBoundaryPackageChoices, required=False)
head_dependent_flux_boundary_packages = forms.MultipleChoiceField(
choices=BoundaryCondition.headDependentFluxBoundaryPackageChoices, required=False)
other_specified_head_boundary_packages = forms.CharField(max_length=200, required=False)
other_specified_flux_boundary_packages = forms.CharField(max_length=200, required=False)
other_head_dependent_flux_boundary_packages = forms.CharField(max_length=200, required=False)
# ModelCalibration element forms
class ModelCalibrationFormHelper(BaseFormHelper):
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, element_name=None,
*args, **kwargs):
# the order in which the model fields are listed for the FieldSet is the order these fields
# will be displayed
layout = Layout(
MetadataField('calibratedParameter'),
MetadataField('observationType'),
MetadataField('observationProcessPackage'),
MetadataField('calibrationMethod'),
)
kwargs['element_name_label'] = 'Model Calibration'
super(ModelCalibrationFormHelper, self).__init__(allow_edit, res_short_id, element_id,
element_name, layout, *args, **kwargs)
class ModelCalibrationForm(ModelForm):
observation_process_package_choices = (('Choose a package', 'Choose a package'),) + \
ModelCalibration.observationProcessPackageChoices
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, *args, **kwargs):
super(ModelCalibrationForm, self).__init__(*args, **kwargs)
self.helper = ModelCalibrationFormHelper(allow_edit, res_short_id, element_id,
element_name='ModelCalibration')
self.fields['observationProcessPackage'].choices = self.observation_process_package_choices
class Meta:
model = ModelCalibration
fields = ('calibratedParameter',
'observationType',
'observationProcessPackage',
'calibrationMethod',
)
class ModelCalibrationValidationForm(forms.Form):
calibratedParameter = forms.CharField(max_length=100, required=False)
observationType = forms.CharField(max_length=100, required=False)
observationProcessPackage = forms.CharField(max_length=100, required=False)
calibrationMethod = forms.CharField(max_length=100, required=False)
# ModelInput element forms
class ModelInputFormHelper(BaseFormHelper):
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, element_name=None,
*args, **kwargs):
# the order in which the model fields are listed for the FieldSet is the order these fields
# will be displayed
layout = Layout(
MetadataField('inputType'),
MetadataField('inputSourceName'),
MetadataField('inputSourceURL'),
)
kwargs['element_name_label'] = 'Model Input'
super(ModelInputFormHelper, self).__init__(allow_edit, res_short_id, element_id,
element_name, layout, *args, **kwargs)
class ModelInputForm(ModelForm):
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, *args, **kwargs):
super(ModelInputForm, self).__init__(*args, **kwargs)
self.helper = ModelInputFormHelper(allow_edit, res_short_id, element_id,
element_name='ModelInput')
if res_short_id:
self.action = "/hydroshare/hsapi/_internal/%s/modelinput/add-metadata/" % res_short_id
else:
self.action = ""
@property
def form_id(self):
form_id = 'id_modelinput_%s' % self.number
return form_id
@property
def form_id_button(self):
return "'" + self.form_id + "'"
class Meta:
model = ModelInput
fields = ('inputType',
'inputSourceName',
'inputSourceURL',
)
class ModelInputValidationForm(forms.Form):
inputType = forms.CharField(max_length=100, required=False)
inputSourceName = forms.CharField(max_length=100, required=False)
inputSourceURL = forms.URLField(required=False)
# GeneralElements element forms
class GeneralElementsFormHelper(BaseFormHelper):
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, element_name=None,
*args, **kwargs):
# the order in which the model fields are listed for the FieldSet is the order these fields
# will be displayed
layout = Layout(
MetadataField('modelParameter'),
MetadataField('modelSolver'),
MetadataField('output_control_package'),
MetadataField('subsidencePackage'),
)
kwargs['element_name_label'] = 'General'
super(GeneralElementsFormHelper, self).__init__(allow_edit, res_short_id, element_id,
element_name, layout, *args, **kwargs)
class GeneralElementsForm(ModelForm):
model_solver_choices = \
(('Choose a solver', 'Choose a solver'),) + GeneralElements.modelSolverChoices
output_control_package = forms.MultipleChoiceField(
choices=GeneralElements.outputControlPackageChoices,
widget=forms.CheckboxSelectMultiple(attrs={'style': 'width:auto;margin-top:-5px'}))
subsidence_package_choices = \
(('Choose a package', 'Choose a package'),) + GeneralElements.subsidencePackageChoices
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, *args, **kwargs):
super(GeneralElementsForm, self).__init__(*args, **kwargs)
self.helper = GeneralElementsFormHelper(allow_edit, res_short_id, element_id,
element_name='GeneralElements')
self.fields['modelSolver'].choices = self.model_solver_choices
self.fields['subsidencePackage'].choices = self.subsidence_package_choices
if self.instance:
if self.instance.id:
self.fields['output_control_package'].initial = \
[types.description for types in self.instance.output_control_package.all()]
class Meta:
model = GeneralElements
exclude = ('output_control_package',)
fields = ('modelParameter',
'modelSolver',
'subsidencePackage',
)
class GeneralElementsValidationForm(forms.Form):
modelParameter = forms.CharField(max_length=100, required=False)
modelSolver = forms.CharField(max_length=100, required=False)
output_control_package = forms.MultipleChoiceField(
choices=GeneralElements.outputControlPackageChoices,
required=False)
subsidencePackage = forms.CharField(max_length=100, required=False)
ModelInputLayoutEdit = Layout(
HTML('<div class="col-xs-12 col-sm-6"> '
'<div class="form-group" id="modelinput"> '
'{% load crispy_forms_tags %} '
'{% for form in model_input_formset.forms %} '
'<form id="{{form.form_id}}" action="{{ form.action }}" '
'method="POST" enctype="multipart/form-data"> '
'{% crispy form %} '
'<div class="row" style="margin-top:10px">'
'<div class="col-md-12">'
'<span class="glyphicon glyphicon-trash icon-button btn-remove" data-toggle="modal" '
'data-placement="auto" title="Delete Model Input" '
'data-target="#delete-modelinput-element-dialog_{{ form.number }}"></span>'
'</div>'
'<div class="col-md-3">'
'<button type="button" class="btn btn-primary pull-right btn-form-submit">'
'Save changes</button>' # TODO: TESTING
'</div>'
'</div>'
'{% crispy form.delete_modal_form %} '
'</form> '
'{% endfor %}</div>'
'</div> '
),
HTML('<div style="margin-top:10px" class="col-md-2">'
'<p><a id="add-modelinput" class="btn btn-success" data-toggle="modal" '
'data-target="#add-modelinput-dialog">'
'<i class="fa fa-plus"></i>Add Model Input</a>'
'</div>'
),
)
ModalDialogLayoutAddModelInput = Helper.get_element_add_modal_form('ModelInput',
'add_modelinput_modal_form')<|fim▁end|> |
# ModelOutput element forms
class ModelOutputFormHelper(BaseFormHelper):
def __init__(self, allow_edit=True, res_short_id=None, element_id=None, element_name=None,
|
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>#![allow(unused)]
use std::env;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
fn wasi_sdk() -> PathBuf {
Path::new(&env::var("WASI_SDK").unwrap_or("/opt/wasi-sdk".to_owned())).to_path_buf()
}
fn wasi_sysroot() -> PathBuf {
match env::var("WASI_SYSROOT") {
Ok(wasi_sysroot) => Path::new(&wasi_sysroot).to_path_buf(),
Err(_) => {
let mut path = wasi_sdk();
path.push("share");
path.push("wasi-sysroot");
path
}
}
}
fn wasm_clang_root() -> PathBuf {
match env::var("CLANG_ROOT") {
Ok(clang) => Path::new(&clang).to_path_buf(),
Err(_) => {
let mut path = wasi_sdk();
path.push("lib");
path.push("clang");
path.push("8.0.1");
path
}
}
}
// `src/wasi_host.rs` is automatically generated using clang and
// wasi-libc headers. This requires these to be present, and installed
// at specific paths, which is not something we can rely on outside
// of our environment.
// So, we follow what most other tools using `bindgen` do, and provide
// a pre-generated version of the file, along with a way to update it.
// This is what the `update-bindings` feature do. It requires the WASI SDK
// to be either installed in `/opt/wasi-sdk`, or at a location defined by
// a `WASI_SDK` environment variable, as well as `clang` headers either
// being part of `WASI_SDK`, or found in a path defined by a
// `CLANG_ROOT` environment variable.
#[cfg(not(feature = "update-bindings"))]
fn main() {}
#[cfg(feature = "update-bindings")]
fn main() {
let wasi_sysroot = wasi_sysroot();
let wasm_clang_root = wasm_clang_root();
assert!(
wasi_sysroot.exists(),
"wasi-sysroot not present at {:?}",
wasi_sysroot
);
assert!(
wasm_clang_root.exists(),
"clang-root not present at {:?}",
wasm_clang_root
);
let wasi_sysroot_core_h = wasi_sysroot.join("include/wasi/core.h");
assert!(
wasi_sysroot_core_h.exists(),
"wasi-sysroot core.h not present at {:?}",
wasi_sysroot_core_h
);
println!("cargo:rerun-if-changed={}", wasi_sysroot_core_h.display());
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
let core_h_path = out_path.join("core.h");
let core_h = File::create(&core_h_path).unwrap();
// `bindgen` doesn't understand typed constant macros like `UINT8_C(123)`, so this fun regex
// strips them off to yield a copy of `wasi/core.h` with bare constants.
let sed_result = Command::new("sed")
.arg("-E")<|fim▁hole|> .stdout(Stdio::from(core_h))
.status()
.expect("can execute sed");
if !sed_result.success() {
// something failed, but how?
match sed_result.code() {
Some(code) => panic!("sed failed with code {}", code),
None => panic!("sed exited abnormally"),
}
}
let host_builder = bindgen::Builder::default()
.clang_arg("-nostdinc")
.clang_arg("-D__wasi__")
.clang_arg(format!("-isystem={}/include/", wasi_sysroot.display()))
.clang_arg(format!("-I{}/include/", wasm_clang_root.display()))
.header(core_h_path.to_str().unwrap())
.whitelist_type("__wasi_.*")
.whitelist_var("__WASI_.*");
let src_path = Path::new("src");
host_builder
.generate()
.expect("can generate host bindings")
.write_to_file(src_path.join("wasi_host.rs"))
.expect("can write host bindings");
}<|fim▁end|> | .arg(r#"s/U?INT[0-9]+_C\(((0x)?[0-9]+)\)/\1/g"#)
.arg(wasi_sysroot_core_h) |
<|file_name|>mlp_learn.py<|end_file_name|><|fim▁begin|>__author__ = 'USER'
from learning.mlp.neuralnetwork import NeuralNetwork
from learning.mlp import learning
number_of_layers = 3
size_array = [2, 2, 1]
learning_rate = 0.3
momentum = 0.1
bnn = NeuralNetwork(number_of_layers, size_array, learning_rate, momentum)
<|fim▁hole|> [0, 0],
[0, 1],
[1, 0],
[1, 1]
]
xor_out = [
[1],
[0],
[0],
[1]
]
learning.learning(bnn, xor_in, xor_out)
print("************** Result ****************")
learning.predict(bnn, xor_in)<|fim▁end|> | xor_in = [ |
<|file_name|>listener.py<|end_file_name|><|fim▁begin|>#
# Copyright 2015 IBM Corp.
#
# 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 heat.common import exception
from heat.common.i18n import _
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine.resources.openstack.neutron import neutron
from heat.engine import support
from heat.engine import translation
class Listener(neutron.NeutronResource):
"""A resource for managing LBaaS v2 Listeners.
This resource creates and manages Neutron LBaaS v2 Listeners,
which represent a listening endpoint for the vip.
"""
support_status = support.SupportStatus(version='6.0.0')
required_service_extension = 'lbaasv2'
PROPERTIES = (
PROTOCOL_PORT, PROTOCOL, LOADBALANCER, NAME,
ADMIN_STATE_UP, DESCRIPTION, DEFAULT_TLS_CONTAINER_REF,
SNI_CONTAINER_REFS, CONNECTION_LIMIT, TENANT_ID
) = (
'protocol_port', 'protocol', 'loadbalancer', 'name',
'admin_state_up', 'description', 'default_tls_container_ref',
'sni_container_refs', 'connection_limit', 'tenant_id'
)
PROTOCOLS = (
TCP, HTTP, HTTPS, TERMINATED_HTTPS,
) = (
'TCP', 'HTTP', 'HTTPS', 'TERMINATED_HTTPS',
)
ATTRIBUTES = (
LOADBALANCERS_ATTR, DEFAULT_POOL_ID_ATTR
) = (
'loadbalancers', 'default_pool_id'
)
properties_schema = {
PROTOCOL_PORT: properties.Schema(
properties.Schema.INTEGER,
_('TCP or UDP port on which to listen for client traffic.'),
required=True,
constraints=[
constraints.Range(1, 65535),
]
),
PROTOCOL: properties.Schema(
properties.Schema.STRING,
_('Protocol on which to listen for the client traffic.'),
required=True,
constraints=[
constraints.AllowedValues(PROTOCOLS),
]
),
LOADBALANCER: properties.Schema(
properties.Schema.STRING,
_('ID or name of the load balancer with which listener '
'is associated.'),
required=True,
constraints=[
constraints.CustomConstraint('neutron.lbaas.loadbalancer')
]
),
NAME: properties.Schema(
properties.Schema.STRING,
_('Name of this listener.'),
update_allowed=True
),
ADMIN_STATE_UP: properties.Schema(
properties.Schema.BOOLEAN,
_('The administrative state of this listener.'),
update_allowed=True,
default=True
),
DESCRIPTION: properties.Schema(
properties.Schema.STRING,
_('Description of this listener.'),
update_allowed=True,
default=''
),
DEFAULT_TLS_CONTAINER_REF: properties.Schema(
properties.Schema.STRING,
_('Default TLS container reference to retrieve TLS '
'information.'),
update_allowed=True
),
SNI_CONTAINER_REFS: properties.Schema(
properties.Schema.LIST,
_('List of TLS container references for SNI.'),
update_allowed=True
),
CONNECTION_LIMIT: properties.Schema(
properties.Schema.INTEGER,
_('The maximum number of connections permitted for this '
'load balancer. Defaults to -1, which is infinite.'),
update_allowed=True,
default=-1,
constraints=[
constraints.Range(min=-1),
]
),
TENANT_ID: properties.Schema(
properties.Schema.STRING,
_('The ID of the tenant who owns the listener.')
),
}
attributes_schema = {
LOADBALANCERS_ATTR: attributes.Schema(
_('ID of the load balancer this listener is associated to.'),
type=attributes.Schema.LIST
),<|fim▁hole|> }
def translation_rules(self, props):
return [
translation.TranslationRule(
props,
translation.TranslationRule.RESOLVE,
[self.LOADBALANCER],
client_plugin=self.client_plugin(),
finder='find_resourceid_by_name_or_id',
entity='loadbalancer'
),
]
def validate(self):
res = super(Listener, self).validate()
if res:
return res
if self.properties[self.PROTOCOL] == self.TERMINATED_HTTPS:
if self.properties[self.DEFAULT_TLS_CONTAINER_REF] is None:
msg = (_('Property %(ref)s required when protocol is '
'%(term)s.') % {'ref': self.DEFAULT_TLS_CONTAINER_REF,
'term': self.TERMINATED_HTTPS})
raise exception.StackValidationFailed(message=msg)
def _check_lb_status(self):
lb_id = self.properties[self.LOADBALANCER]
return self.client_plugin().check_lb_status(lb_id)
def handle_create(self):
properties = self.prepare_properties(
self.properties,
self.physical_resource_name())
properties['loadbalancer_id'] = properties.pop(self.LOADBALANCER)
return properties
def check_create_complete(self, properties):
if self.resource_id is None:
try:
listener = self.client().create_listener(
{'listener': properties})['listener']
self.resource_id_set(listener['id'])
except Exception as ex:
if self.client_plugin().is_invalid(ex):
return False
raise
return self._check_lb_status()
def _show_resource(self):
return self.client().show_listener(
self.resource_id)['listener']
def handle_update(self, json_snippet, tmpl_diff, prop_diff):
self._update_called = False
return prop_diff
def check_update_complete(self, prop_diff):
if not prop_diff:
return True
if not self._update_called:
try:
self.client().update_listener(self.resource_id,
{'listener': prop_diff})
self._update_called = True
except Exception as ex:
if self.client_plugin().is_invalid(ex):
return False
raise
return self._check_lb_status()
def handle_delete(self):
self._delete_called = False
def check_delete_complete(self, data):
if self.resource_id is None:
return True
if not self._delete_called:
try:
self.client().delete_listener(self.resource_id)
self._delete_called = True
except Exception as ex:
if self.client_plugin().is_invalid(ex):
return False
elif self.client_plugin().is_not_found(ex):
return True
raise
return self._check_lb_status()
def resource_mapping():
return {
'OS::Neutron::LBaaS::Listener': Listener,
}<|fim▁end|> | DEFAULT_POOL_ID_ATTR: attributes.Schema(
_('ID of the default pool this listener is associated to.'),
type=attributes.Schema.STRING
) |
<|file_name|>realness_tests.py<|end_file_name|><|fim▁begin|># coding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import re
import poetryutils2
# this is all for use within ipython
def sample_words():
lines = poetryutils2.utils.debug_lines()
words = list()
for l in lines:
words.extend(w.lower() for w in l.split())
# maybe we want to clean words up more? let's just do that I think
# words = [w[:-1] for w in words if w[-1] in {'.',',','!','?'}]
# tofix = [w for w in words if w[-1] in {'.',',','!','?'}]
# words = [w for w in words if w[-1] not in {'.',',','!','?'}]
# words.extend([w[:-1] for w in tofix])
words = [re.sub(r'[^a-zA-Z\']', '', w) for w in words]
return [w for w in words if len(w)]
def realness(sample):
fails = [w for w in sample if not poetryutils2.utils.is_real_word(w)]
return fails
def main():
# print(len(sample_words()))
sample = sample_words()
print(len(sample))
fails = realness(sample)
# for f in fails:
# print(f)
from collections import Counter
counter = Counter(fails)
for word, count in counter.most_common():
if count > 1:
print(word, count)
# import argparse<|fim▁hole|> # parser.add_argument('arg2', '--argument-2', help='optional boolean argument', action="store_true")
# args = parser.parse_args()
"""
okay so what we're having trouble with:
-est
-ies
-py
"""
if __name__ == "__main__":
main()<|fim▁end|> | # parser = argparse.ArgumentParser()
# parser.add_argument('arg1', type=str, help="required argument") |
<|file_name|>SettingsTest.java<|end_file_name|><|fim▁begin|>/*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2012 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar 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 3 of the License, or (at your option) any later version.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.api.config;
import com.google.common.collect.ImmutableMap;
import org.fest.assertions.Delta;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.Properties;
import org.sonar.api.Property;
import org.sonar.api.PropertyType;
import static org.fest.assertions.Assertions.assertThat;
public class SettingsTest {
private PropertyDefinitions definitions;
@Properties({
@Property(key = "hello", name = "Hello", defaultValue = "world"),
@Property(key = "date", name = "Date", defaultValue = "2010-05-18"),
@Property(key = "datetime", name = "DateTime", defaultValue = "2010-05-18T15:50:45+0100"),
@Property(key = "boolean", name = "Boolean", defaultValue = "true"),
@Property(key = "falseboolean", name = "False Boolean", defaultValue = "false"),
@Property(key = "integer", name = "Integer", defaultValue = "12345"),
@Property(key = "array", name = "Array", defaultValue = "one,two,three"),
@Property(key = "multi_values", name = "Array", defaultValue = "1,2,3", multiValues = true),
@Property(key = "sonar.jira", name = "Jira Server", type = PropertyType.PROPERTY_SET, propertySetKey = "jira"),
@Property(key = "newKey", name = "New key", deprecatedKey = "oldKey"),
@Property(key = "newKeyWithDefaultValue", name = "New key with default value", deprecatedKey = "oldKeyWithDefaultValue", defaultValue = "default_value"),
@Property(key = "new_multi_values", name = "New multi values", defaultValue = "1,2,3", multiValues = true, deprecatedKey = "old_multi_values")
})
static class Init {
}
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void initDefinitions() {
definitions = new PropertyDefinitions();
definitions.addComponent(Init.class);
}
@Test
public void defaultValuesShouldBeLoadedFromDefinitions() {
Settings settings = new Settings(definitions);
assertThat(settings.getDefaultValue("hello")).isEqualTo("world");
}
@Test
public void setProperty_int() {
Settings settings = new Settings();
settings.setProperty("foo", 123);
assertThat(settings.getInt("foo")).isEqualTo(123);
assertThat(settings.getString("foo")).isEqualTo("123");
assertThat(settings.getBoolean("foo")).isFalse();
}
@Test
public void setProperty_boolean() {
Settings settings = new Settings();
settings.setProperty("foo", true);
settings.setProperty("bar", false);
assertThat(settings.getBoolean("foo")).isTrue();
assertThat(settings.getBoolean("bar")).isFalse();
assertThat(settings.getString("foo")).isEqualTo("true");
assertThat(settings.getString("bar")).isEqualTo("false");
}
@Test
public void default_number_values_are_zero() {
Settings settings = new Settings();
assertThat(settings.getInt("foo")).isEqualTo(0);
assertThat(settings.getLong("foo")).isEqualTo(0L);
}
@Test
public void getInt_value_must_be_valid() {
thrown.expect(NumberFormatException.class);<|fim▁hole|>
Settings settings = new Settings();
settings.setProperty("foo", "not a number");
settings.getInt("foo");
}
@Test
public void allValuesShouldBeTrimmed_set_property() {
Settings settings = new Settings();
settings.setProperty("foo", " FOO ");
assertThat(settings.getString("foo")).isEqualTo("FOO");
}
@Test
public void allValuesShouldBeTrimmed_set_properties() {
Settings settings = new Settings();
settings.setProperties(ImmutableMap.of("foo", " FOO "));
assertThat(settings.getString("foo")).isEqualTo("FOO");
}
@Test
public void testGetDefaultValue() {
Settings settings = new Settings(definitions);
assertThat(settings.getDefaultValue("unknown")).isNull();
}
@Test
public void testGetString() {
Settings settings = new Settings(definitions);
settings.setProperty("hello", "Russia");
assertThat(settings.getString("hello")).isEqualTo("Russia");
}
@Test
public void testGetDate() {
Settings settings = new Settings(definitions);
assertThat(settings.getDate("unknown")).isNull();
assertThat(settings.getDate("date").getDate()).isEqualTo(18);
assertThat(settings.getDate("date").getMonth()).isEqualTo(4);
}
@Test
public void testGetDateNotFound() {
Settings settings = new Settings(definitions);
assertThat(settings.getDate("unknown")).isNull();
}
@Test
public void testGetDateTime() {
Settings settings = new Settings(definitions);
assertThat(settings.getDateTime("unknown")).isNull();
assertThat(settings.getDateTime("datetime").getDate()).isEqualTo(18);
assertThat(settings.getDateTime("datetime").getMonth()).isEqualTo(4);
assertThat(settings.getDateTime("datetime").getMinutes()).isEqualTo(50);
}
@Test
public void testGetDouble() {
Settings settings = new Settings();
settings.setProperty("from_double", 3.14159);
settings.setProperty("from_string", "3.14159");
assertThat(settings.getDouble("from_double")).isEqualTo(3.14159, Delta.delta(0.00001));
assertThat(settings.getDouble("from_string")).isEqualTo(3.14159, Delta.delta(0.00001));
assertThat(settings.getDouble("unknown")).isNull();
}
@Test
public void testGetFloat() {
Settings settings = new Settings();
settings.setProperty("from_float", 3.14159f);
settings.setProperty("from_string", "3.14159");
assertThat(settings.getDouble("from_float")).isEqualTo(3.14159f, Delta.delta(0.00001));
assertThat(settings.getDouble("from_string")).isEqualTo(3.14159f, Delta.delta(0.00001));
assertThat(settings.getDouble("unknown")).isNull();
}
@Test
public void testGetBadFloat() {
Settings settings = new Settings();
settings.setProperty("foo", "bar");
thrown.expect(IllegalStateException.class);
thrown.expectMessage("The property 'foo' is not a float value");
settings.getFloat("foo");
}
@Test
public void testGetBadDouble() {
Settings settings = new Settings();
settings.setProperty("foo", "bar");
thrown.expect(IllegalStateException.class);
thrown.expectMessage("The property 'foo' is not a double value");
settings.getDouble("foo");
}
@Test
public void testSetNullFloat() {
Settings settings = new Settings();
settings.setProperty("foo", (Float) null);
assertThat(settings.getFloat("foo")).isNull();
}
@Test
public void testSetNullDouble() {
Settings settings = new Settings();
settings.setProperty("foo", (Double) null);
assertThat(settings.getDouble("foo")).isNull();
}
@Test
public void getStringArray() {
Settings settings = new Settings(definitions);
String[] array = settings.getStringArray("array");
assertThat(array).isEqualTo(new String[]{"one", "two", "three"});
}
@Test
public void setStringArray() {
Settings settings = new Settings(definitions);
settings.setProperty("multi_values", new String[]{"A", "B"});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A", "B"});
}
@Test
public void setStringArrayTrimValues() {
Settings settings = new Settings(definitions);
settings.setProperty("multi_values", new String[]{" A ", " B "});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A", "B"});
}
@Test
public void setStringArrayEscapeCommas() {
Settings settings = new Settings(definitions);
settings.setProperty("multi_values", new String[]{"A,B", "C,D"});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A,B", "C,D"});
}
@Test
public void setStringArrayWithEmptyValues() {
Settings settings = new Settings(definitions);
settings.setProperty("multi_values", new String[]{"A,B", "", "C,D"});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A,B", "", "C,D"});
}
@Test
public void setStringArrayWithNullValues() {
Settings settings = new Settings(definitions);
settings.setProperty("multi_values", new String[]{"A,B", null, "C,D"});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A,B", "", "C,D"});
}
@Test(expected = IllegalStateException.class)
public void shouldFailToSetArrayValueOnSingleValueProperty() {
Settings settings = new Settings(definitions);
settings.setProperty("array", new String[]{"A", "B", "C"});
}
@Test
public void getStringArray_no_value() {
Settings settings = new Settings();
String[] array = settings.getStringArray("array");
assertThat(array).isEmpty();
}
@Test
public void shouldTrimArray() {
Settings settings = new Settings();
settings.setProperty("foo", " one, two, three ");
String[] array = settings.getStringArray("foo");
assertThat(array).isEqualTo(new String[]{"one", "two", "three"});
}
@Test
public void shouldKeepEmptyValuesWhenSplitting() {
Settings settings = new Settings();
settings.setProperty("foo", " one, , two");
String[] array = settings.getStringArray("foo");
assertThat(array).isEqualTo(new String[]{"one", "", "two"});
}
@Test
public void testDefaultValueOfGetString() {
Settings settings = new Settings(definitions);
assertThat(settings.getString("hello")).isEqualTo("world");
}
@Test
public void testGetBoolean() {
Settings settings = new Settings(definitions);
assertThat(settings.getBoolean("boolean")).isTrue();
assertThat(settings.getBoolean("falseboolean")).isFalse();
assertThat(settings.getBoolean("unknown")).isFalse();
assertThat(settings.getBoolean("hello")).isFalse();
}
@Test
public void shouldCreateByIntrospectingComponent() {
Settings settings = Settings.createForComponent(MyComponent.class);
// property definition has been loaded, ie for default value
assertThat(settings.getDefaultValue("foo")).isEqualTo("bar");
}
@Property(key = "foo", name = "Foo", defaultValue = "bar")
public static class MyComponent {
}
@Test
public void cloneSettings() {
Settings target = new Settings(definitions).setProperty("foo", "bar");
Settings settings = new Settings(target);
assertThat(settings.getString("foo")).isEqualTo("bar");
assertThat(settings.getDefinitions()).isSameAs(definitions);
// do not propagate changes
settings.setProperty("foo", "changed");
settings.setProperty("new", "value");
assertThat(settings.getString("foo")).isEqualTo("changed");
assertThat(settings.getString("new")).isEqualTo("value");
assertThat(target.getString("foo")).isEqualTo("bar");
assertThat(target.getString("new")).isNull();
}
@Test
public void getStringLines_no_value() {
assertThat(new Settings().getStringLines("foo")).hasSize(0);
}
@Test
public void getStringLines_single_line() {
Settings settings = new Settings();
settings.setProperty("foo", "the line");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"the line"});
}
@Test
public void getStringLines_linux() {
Settings settings = new Settings();
settings.setProperty("foo", "one\ntwo");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two"});
settings.setProperty("foo", "one\ntwo\n");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two"});
}
@Test
public void getStringLines_windows() {
Settings settings = new Settings();
settings.setProperty("foo", "one\r\ntwo");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two"});
settings.setProperty("foo", "one\r\ntwo\r\n");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two"});
}
@Test
public void getStringLines_mix() {
Settings settings = new Settings();
settings.setProperty("foo", "one\r\ntwo\nthree");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two", "three"});
}
@Test
public void getKeysStartingWith() {
Settings settings = new Settings();
settings.setProperty("sonar.jdbc.url", "foo");
settings.setProperty("sonar.jdbc.username", "bar");
settings.setProperty("sonar.security", "admin");
assertThat(settings.getKeysStartingWith("sonar")).containsOnly("sonar.jdbc.url", "sonar.jdbc.username", "sonar.security");
assertThat(settings.getKeysStartingWith("sonar.jdbc")).containsOnly("sonar.jdbc.url", "sonar.jdbc.username");
assertThat(settings.getKeysStartingWith("other")).hasSize(0);
}
@Test
public void should_fallback_deprecated_key_to_default_value_of_new_key() {
Settings settings = new Settings(definitions);
assertThat(settings.getString("newKeyWithDefaultValue")).isEqualTo("default_value");
assertThat(settings.getString("oldKeyWithDefaultValue")).isEqualTo("default_value");
}
@Test
public void should_fallback_deprecated_key_to_new_key() {
Settings settings = new Settings(definitions);
settings.setProperty("newKey", "value of newKey");
assertThat(settings.getString("newKey")).isEqualTo("value of newKey");
assertThat(settings.getString("oldKey")).isEqualTo("value of newKey");
}
@Test
public void should_load_value_of_deprecated_key() {
// it's used for example when deprecated settings are set through command-line
Settings settings = new Settings(definitions);
settings.setProperty("oldKey", "value of oldKey");
assertThat(settings.getString("newKey")).isEqualTo("value of oldKey");
assertThat(settings.getString("oldKey")).isEqualTo("value of oldKey");
}
@Test
public void should_load_values_of_deprecated_key() {
Settings settings = new Settings(definitions);
settings.setProperty("oldKey", "a,b");
assertThat(settings.getStringArray("newKey")).containsOnly("a", "b");
assertThat(settings.getStringArray("oldKey")).containsOnly("a", "b");
}
@Test
public void should_support_deprecated_props_with_multi_values() {
Settings settings = new Settings(definitions);
settings.setProperty("new_multi_values", new String[]{" A ", " B "});
assertThat(settings.getStringArray("new_multi_values")).isEqualTo(new String[]{"A", "B"});
assertThat(settings.getStringArray("old_multi_values")).isEqualTo(new String[]{"A", "B"});
}
}<|fim▁end|> | |
<|file_name|>corpscore.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python<|fim▁hole|>import csv
import json
import sys
import click
def score(company, sexbiases):
"""
Given a company record with board of directors and executive names,
return our guess of the % of governance that is male.
Since names are not always unambiguous determinants of sex, we also
return an error bound, with 0.0 being perfect and 1.0 being possibly 100%
wrong.
"""
men = 0
error = 0.0
governors = company['board'] + company['executives']
# Get all governor names, de-duping since board/exec team may overlap
names = set([governor.get('name', '') for governor in governors])
for name in names:
first_name = name.split(' ')[0].strip().title()
bias = sexbiases.get(first_name, 0.0) # Assume male if not known, with maximal error bound
if bias <= 0.0:
men += 1
error += 1.0 - abs(bias)
count = len(names)
return (men/count, error/count)
@click.command()
@click.option('--companies', type=click.File(mode='rt'), required=True, help="A companies data file, as created by symbol-to-company-details.")
@click.option('--sexbiases', type=click.File(mode='rt'), required=True, help="A sex bias CSV datafile, as in first_name_sex_bias.csv")
def corpscore(companies, sexbiases):
sexbias_reader = csv.reader(sexbiases)
sexbiases = dict([item[0], float(item[1])] for item in sexbias_reader)
fieldnames = ['symbol', 'url', 'percent_men', 'error', 'description']
writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames)
writer.writeheader()
for company_json in companies:
company = json.loads(company_json)
percent_men, error = score(company, sexbiases)
writer.writerow({
'symbol': company['symbol'],
'url': company.get('url'),
'percent_men': percent_men,
'error': error,
'description': company.get('description'),
})
sys.stdout.flush()
if __name__ == '__main__':
corpscore()<|fim▁end|> | |
<|file_name|>conversions.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Conversions of Rust values to and from `JSVal`.
//!
//! | IDL type | Type |
//! |-------------------------|----------------------------------|
//! | any | `JSVal` |
//! | boolean | `bool` |
//! | byte | `i8` |
//! | octet | `u8` |
//! | short | `i16` |
//! | unsigned short | `u16` |
//! | long | `i32` |
//! | unsigned long | `u32` |
//! | long long | `i64` |
//! | unsigned long long | `u64` |
//! | unrestricted float | `f32` |
//! | float | `Finite<f32>` |
//! | unrestricted double | `f64` |
//! | double | `Finite<f64>` |
//! | USVString | `String` |
//! | object | `*mut JSObject` |
//! | nullable types | `Option<T>` |
//! | sequences | `Vec<T>` |
#![deny(missing_docs)]
use core::nonzero::NonZero;
use error::throw_type_error;
use glue::RUST_JS_NumberValue;
use jsapi::{ForOfIterator, ForOfIterator_NonIterableBehavior, HandleValue};
use jsapi::{Heap, JS_DefineElement, JS_GetLatin1StringCharsAndLength};
use jsapi::{JS_GetTwoByteStringCharsAndLength, JS_NewArrayObject1};
use jsapi::{JS_NewUCStringCopyN, JSPROP_ENUMERATE, JS_StringHasLatin1Chars};
use jsapi::{JSContext, JSObject, JSString, MutableHandleValue, RootedObject};
use jsval::{BooleanValue, Int32Value, NullValue, UInt32Value, UndefinedValue};
use jsval::{JSVal, ObjectValue, ObjectOrNullValue, StringValue};
use rust::{ToBoolean, ToInt32, ToInt64, ToNumber, ToUint16, ToUint32, ToUint64};
use rust::{ToString, maybe_wrap_object_or_null_value};
use rust::{maybe_wrap_object_value, maybe_wrap_value};
use libc;
use num_traits::{Bounded, Zero};
use std::borrow::Cow;
use std::rc::Rc;
use std::{ptr, slice};
trait As<O>: Copy {
fn cast(self) -> O;
}
macro_rules! impl_as {
($I:ty, $O:ty) => (
impl As<$O> for $I {
fn cast(self) -> $O {
self as $O
}
}
)
}
impl_as!(f64, u8);
impl_as!(f64, u16);
impl_as!(f64, u32);
impl_as!(f64, u64);
impl_as!(f64, i8);
impl_as!(f64, i16);
impl_as!(f64, i32);
impl_as!(f64, i64);
impl_as!(u8, f64);
impl_as!(u16, f64);
impl_as!(u32, f64);
impl_as!(u64, f64);
impl_as!(i8, f64);
impl_as!(i16, f64);
impl_as!(i32, f64);
impl_as!(i64, f64);
impl_as!(i32, i8);
impl_as!(i32, u8);
impl_as!(i32, i16);
impl_as!(u16, u16);
impl_as!(i32, i32);
impl_as!(u32, u32);
impl_as!(i64, i64);
impl_as!(u64, u64);
/// A trait to convert Rust types to `JSVal`s.
pub trait ToJSValConvertible {
/// Convert `self` to a `JSVal`. JSAPI failure causes a panic.
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue);
}
/// An enum to better support enums through FromJSValConvertible::from_jsval.
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum ConversionResult<T> {
/// Everything went fine.
Success(T),
/// Pending exception.
Failure(Cow<'static, str>),
}
impl<T> ConversionResult<T> {
/// Returns Some(value) if it is `ConversionResult::Success`.
pub fn get_success_value(&self) -> Option<&T> {
match *self {
ConversionResult::Success(ref v) => Some(v),
_ => None,
}
}
}
/// A trait to convert `JSVal`s to Rust types.
pub trait FromJSValConvertible: Sized {
/// Optional configurable behaviour switch; use () for no configuration.
type Config;
/// Convert `val` to type `Self`.
/// Optional configuration of type `T` can be passed as the `option`
/// argument.
/// If it returns `Err(())`, a JSAPI exception is pending.
unsafe fn from_jsval(cx: *mut JSContext,
val: HandleValue,
option: Self::Config)
-> Result<ConversionResult<Self>, ()>;
}
/// Behavior for converting out-of-range integers.
#[derive(PartialEq, Eq, Clone)]
pub enum ConversionBehavior {
/// Wrap into the integer's range.
Default,
/// Throw an exception.
EnforceRange,
/// Clamp into the integer's range.
Clamp,
}
/// Try to cast the number to a smaller type, but
/// if it doesn't fit, it will return an error.
unsafe fn enforce_range<D>(cx: *mut JSContext, d: f64) -> Result<ConversionResult<D>, ()>
where D: Bounded + As<f64>,
f64: As<D>
{
if d.is_infinite() {
throw_type_error(cx, "value out of range in an EnforceRange argument");
return Err(());
}
let rounded = d.round();
if D::min_value().cast() <= rounded && rounded <= D::max_value().cast() {
Ok(ConversionResult::Success(rounded.cast()))
} else {
throw_type_error(cx, "value out of range in an EnforceRange argument");
Err(())
}
}
/// Try to cast the number to a smaller type, but if it doesn't fit,
/// round it to the MAX or MIN of the source type before casting it to
/// the destination type.
fn clamp_to<D>(d: f64) -> D
where D: Bounded + As<f64> + Zero,
f64: As<D>
{
if d.is_nan() {
D::zero()
} else if d > D::max_value().cast() {
D::max_value()
} else if d < D::min_value().cast() {
D::min_value()
} else {
d.cast()
}
}
// https://heycam.github.io/webidl/#es-void
impl ToJSValConvertible for () {
#[inline]
unsafe fn to_jsval(&self, _cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(UndefinedValue());
}
}
impl FromJSValConvertible for JSVal {
type Config = ();
unsafe fn from_jsval(_cx: *mut JSContext,
value: HandleValue,
_option: ())
-> Result<ConversionResult<JSVal>, ()> {
Ok(ConversionResult::Success(value.get()))
}
}
impl FromJSValConvertible for Heap<JSVal> {
type Config = ();
unsafe fn from_jsval(_cx: *mut JSContext,
value: HandleValue,
_option: ())
-> Result<ConversionResult<Self>, ()> {
Ok(ConversionResult::Success(Heap::new(value.get())))
}
}
impl ToJSValConvertible for JSVal {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(*self);
maybe_wrap_value(cx, rval);
}
}
impl ToJSValConvertible for HandleValue {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(self.get());
maybe_wrap_value(cx, rval);
}
}
impl ToJSValConvertible for Heap<JSVal> {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(self.get());
maybe_wrap_value(cx, rval);
}
}
#[inline]
unsafe fn convert_int_from_jsval<T, M>(cx: *mut JSContext, value: HandleValue,
option: ConversionBehavior,
convert_fn: unsafe fn(*mut JSContext, HandleValue) -> Result<M, ()>)
-> Result<ConversionResult<T>, ()>
where T: Bounded + Zero + As<f64>,
M: Zero + As<T>,
f64: As<T>
{
match option {
ConversionBehavior::Default => Ok(ConversionResult::Success(try!(convert_fn(cx, value)).cast())),
ConversionBehavior::EnforceRange => enforce_range(cx, try!(ToNumber(cx, value))),
ConversionBehavior::Clamp => Ok(ConversionResult::Success(clamp_to(try!(ToNumber(cx, value))))),
}
}
// https://heycam.github.io/webidl/#es-boolean
impl ToJSValConvertible for bool {
#[inline]
unsafe fn to_jsval(&self, _cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(BooleanValue(*self));
}
}
// https://heycam.github.io/webidl/#es-boolean
impl FromJSValConvertible for bool {
type Config = ();
unsafe fn from_jsval(_cx: *mut JSContext, val: HandleValue, _option: ()) -> Result<ConversionResult<bool>, ()> {
Ok(ToBoolean(val)).map(ConversionResult::Success)
}
}
// https://heycam.github.io/webidl/#es-byte
impl ToJSValConvertible for i8 {
#[inline]
unsafe fn to_jsval(&self, _cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(Int32Value(*self as i32));
}
}
// https://heycam.github.io/webidl/#es-byte
impl FromJSValConvertible for i8 {
type Config = ConversionBehavior;
unsafe fn from_jsval(cx: *mut JSContext,
val: HandleValue,
option: ConversionBehavior)
-> Result<ConversionResult<i8>, ()> {
convert_int_from_jsval(cx, val, option, ToInt32)
}
}
// https://heycam.github.io/webidl/#es-octet
impl ToJSValConvertible for u8 {
#[inline]
unsafe fn to_jsval(&self, _cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(Int32Value(*self as i32));
}
}
// https://heycam.github.io/webidl/#es-octet
impl FromJSValConvertible for u8 {
type Config = ConversionBehavior;
unsafe fn from_jsval(cx: *mut JSContext,
val: HandleValue,
option: ConversionBehavior)
-> Result<ConversionResult<u8>, ()> {
convert_int_from_jsval(cx, val, option, ToInt32)
}
}
// https://heycam.github.io/webidl/#es-short
impl ToJSValConvertible for i16 {
#[inline]
unsafe fn to_jsval(&self, _cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(Int32Value(*self as i32));
}
}
// https://heycam.github.io/webidl/#es-short
impl FromJSValConvertible for i16 {
type Config = ConversionBehavior;
unsafe fn from_jsval(cx: *mut JSContext,
val: HandleValue,
option: ConversionBehavior)
-> Result<ConversionResult<i16>, ()> {
convert_int_from_jsval(cx, val, option, ToInt32)
}
}
// https://heycam.github.io/webidl/#es-unsigned-short
impl ToJSValConvertible for u16 {
#[inline]
unsafe fn to_jsval(&self, _cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(Int32Value(*self as i32));
}
}
// https://heycam.github.io/webidl/#es-unsigned-short
impl FromJSValConvertible for u16 {
type Config = ConversionBehavior;
unsafe fn from_jsval(cx: *mut JSContext,
val: HandleValue,
option: ConversionBehavior)
-> Result<ConversionResult<u16>, ()> {
convert_int_from_jsval(cx, val, option, ToUint16)
}
}
// https://heycam.github.io/webidl/#es-long
impl ToJSValConvertible for i32 {
#[inline]
unsafe fn to_jsval(&self, _cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(Int32Value(*self));
}
}
// https://heycam.github.io/webidl/#es-long
impl FromJSValConvertible for i32 {
type Config = ConversionBehavior;
unsafe fn from_jsval(cx: *mut JSContext,
val: HandleValue,
option: ConversionBehavior)
-> Result<ConversionResult<i32>, ()> {
convert_int_from_jsval(cx, val, option, ToInt32)
}
}
// https://heycam.github.io/webidl/#es-unsigned-long
impl ToJSValConvertible for u32 {
#[inline]
unsafe fn to_jsval(&self, _cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(UInt32Value(*self));
}
}
// https://heycam.github.io/webidl/#es-unsigned-long
impl FromJSValConvertible for u32 {
type Config = ConversionBehavior;
unsafe fn from_jsval(cx: *mut JSContext,
val: HandleValue,
option: ConversionBehavior)
-> Result<ConversionResult<u32>, ()> {
convert_int_from_jsval(cx, val, option, ToUint32)
}
}
// https://heycam.github.io/webidl/#es-long-long
impl ToJSValConvertible for i64 {
#[inline]
unsafe fn to_jsval(&self, _cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(RUST_JS_NumberValue(*self as f64));
}
}
// https://heycam.github.io/webidl/#es-long-long
impl FromJSValConvertible for i64 {
type Config = ConversionBehavior;
unsafe fn from_jsval(cx: *mut JSContext,
val: HandleValue,
option: ConversionBehavior)
-> Result<ConversionResult<i64>, ()> {
convert_int_from_jsval(cx, val, option, ToInt64)
}
}
// https://heycam.github.io/webidl/#es-unsigned-long-long
impl ToJSValConvertible for u64 {
#[inline]
unsafe fn to_jsval(&self, _cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(RUST_JS_NumberValue(*self as f64));
}
}
// https://heycam.github.io/webidl/#es-unsigned-long-long
impl FromJSValConvertible for u64 {
type Config = ConversionBehavior;
unsafe fn from_jsval(cx: *mut JSContext,
val: HandleValue,
option: ConversionBehavior)
-> Result<ConversionResult<u64>, ()> {
convert_int_from_jsval(cx, val, option, ToUint64)
}
}
// https://heycam.github.io/webidl/#es-float
impl ToJSValConvertible for f32 {
#[inline]
unsafe fn to_jsval(&self, _cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(RUST_JS_NumberValue(*self as f64));
}
}
// https://heycam.github.io/webidl/#es-float
impl FromJSValConvertible for f32 {
type Config = ();
unsafe fn from_jsval(cx: *mut JSContext, val: HandleValue, _option: ()) -> Result<ConversionResult<f32>, ()> {
let result = ToNumber(cx, val);
result.map(|f| f as f32).map(ConversionResult::Success)
}
}
// https://heycam.github.io/webidl/#es-double
impl ToJSValConvertible for f64 {
#[inline]
unsafe fn to_jsval(&self, _cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(RUST_JS_NumberValue(*self));
}
}
// https://heycam.github.io/webidl/#es-double
impl FromJSValConvertible for f64 {
type Config = ();
unsafe fn from_jsval(cx: *mut JSContext, val: HandleValue, _option: ()) -> Result<ConversionResult<f64>, ()> {
ToNumber(cx, val).map(ConversionResult::Success)
}
}
/// Converts a `JSString`, encoded in "Latin1" (i.e. U+0000-U+00FF encoded as 0x00-0xFF) into a
/// `String`.
pub unsafe fn latin1_to_string(cx: *mut JSContext, s: *mut JSString) -> String {
assert!(JS_StringHasLatin1Chars(s));
let mut length = 0;
let chars = JS_GetLatin1StringCharsAndLength(cx, ptr::null(), s, &mut length);
assert!(!chars.is_null());
let chars = slice::from_raw_parts(chars, length as usize);
let mut s = String::with_capacity(length as usize);
s.extend(chars.iter().map(|&c| c as char));
s
}
// https://heycam.github.io/webidl/#es-USVString
impl ToJSValConvertible for str {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
let mut string_utf16: Vec<u16> = Vec::with_capacity(self.len());
string_utf16.extend(self.encode_utf16());
let jsstr = JS_NewUCStringCopyN(cx,
string_utf16.as_ptr(),
string_utf16.len() as libc::size_t);
if jsstr.is_null() {
panic!("JS_NewUCStringCopyN failed");
}
rval.set(StringValue(&*jsstr));
}
}
// https://heycam.github.io/webidl/#es-USVString
impl ToJSValConvertible for String {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
(**self).to_jsval(cx, rval);
}
}
// https://heycam.github.io/webidl/#es-USVString
impl FromJSValConvertible for String {
type Config = ();
unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, _: ()) -> Result<ConversionResult<String>, ()> {
let jsstr = ToString(cx, value);
if jsstr.is_null() {
debug!("ToString failed");
return Err(());
}
if JS_StringHasLatin1Chars(jsstr) {
return Ok(latin1_to_string(cx, jsstr)).map(ConversionResult::Success);
}
let mut length = 0;
let chars = JS_GetTwoByteStringCharsAndLength(cx, ptr::null(), jsstr, &mut length);
assert!(!chars.is_null());
let char_vec = slice::from_raw_parts(chars, length as usize);
Ok(String::from_utf16_lossy(char_vec)).map(ConversionResult::Success)
}
}
impl<T: ToJSValConvertible> ToJSValConvertible for Option<T> {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
match self {
&Some(ref value) => value.to_jsval(cx, rval),
&None => rval.set(NullValue()),
}
}
}
impl<T: ToJSValConvertible> ToJSValConvertible for Rc<T> {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
(**self).to_jsval(cx, rval)
}
}
impl<T: FromJSValConvertible> FromJSValConvertible for Option<T> {
type Config = T::Config;
unsafe fn from_jsval(cx: *mut JSContext,
value: HandleValue,
option: T::Config)
-> Result<ConversionResult<Option<T>>, ()> {
if value.get().is_null_or_undefined() {
Ok(ConversionResult::Success(None))
} else {
Ok(match try!(FromJSValConvertible::from_jsval(cx, value, option)) {
ConversionResult::Success(v) => ConversionResult::Success(Some(v)),
ConversionResult::Failure(v) => ConversionResult::Failure(v),
})
}
}
}
// https://heycam.github.io/webidl/#es-sequence
impl<T: ToJSValConvertible> ToJSValConvertible for Vec<T> {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
rooted!(in(cx) let js_array = JS_NewArrayObject1(cx, self.len() as libc::size_t));
assert!(!js_array.handle().is_null());
rooted!(in(cx) let mut val = UndefinedValue());
for (index, obj) in self.iter().enumerate() {
obj.to_jsval(cx, val.handle_mut());
assert!(JS_DefineElement(cx, js_array.handle(),
index as u32, val.handle(), JSPROP_ENUMERATE, None, None));
}
rval.set(ObjectValue(js_array.handle().get()));
}
}
/// Rooting guard for the iterator field of ForOfIterator.
/// Behaves like RootedGuard (roots on creation, unroots on drop),
/// but borrows and allows access to the whole ForOfIterator, so
/// that methods on ForOfIterator can still be used through it.
struct ForOfIteratorGuard<'a> {
root: &'a mut ForOfIterator
}
impl<'a> ForOfIteratorGuard<'a> {
fn new(cx: *mut JSContext, root: &'a mut ForOfIterator) -> Self {
unsafe {
root.iterator.add_to_root_stack(cx);
}
ForOfIteratorGuard {
root: root
}
}
}
impl<'a> Drop for ForOfIteratorGuard<'a> {
fn drop(&mut self) {
unsafe {
self.root.iterator.remove_from_root_stack();
}
}
}
impl<C: Clone, T: FromJSValConvertible<Config=C>> FromJSValConvertible for Vec<T> {
type Config = C;
unsafe fn from_jsval(cx: *mut JSContext,
value: HandleValue,
option: C)
-> Result<ConversionResult<Vec<T>>, ()> {
let mut iterator = ForOfIterator {
cx_: cx,
iterator: RootedObject::new_unrooted(),
index: ::std::u32::MAX, // NOT_ARRAY
};
let mut iterator = ForOfIteratorGuard::new(cx, &mut iterator);
let iterator = &mut *iterator.root;
if !iterator.init(value, ForOfIterator_NonIterableBehavior::AllowNonIterable) {
return Err(())
}
if iterator.iterator.ptr.is_null() {
return Ok(ConversionResult::Failure("Value is not iterable".into()));
}
let mut ret = vec![];
loop {
let mut done = false;
rooted!(in(cx) let mut val = UndefinedValue());
if !iterator.next(val.handle_mut(), &mut done) {
return Err(())
}
if done {
break;
}<|fim▁hole|>
ret.push(match try!(T::from_jsval(cx, val.handle(), option.clone())) {
ConversionResult::Success(v) => v,
ConversionResult::Failure(e) => return Ok(ConversionResult::Failure(e)),
});
}
Ok(ret).map(ConversionResult::Success)
}
}
// https://heycam.github.io/webidl/#es-object
impl ToJSValConvertible for *mut JSObject {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(ObjectOrNullValue(*self));
maybe_wrap_object_or_null_value(cx, rval);
}
}
// https://heycam.github.io/webidl/#es-object
impl ToJSValConvertible for NonZero<*mut JSObject> {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(ObjectValue(**self));
maybe_wrap_object_value(cx, rval);
}
}
// https://heycam.github.io/webidl/#es-object
impl ToJSValConvertible for Heap<*mut JSObject> {
#[inline]
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
rval.set(ObjectOrNullValue(self.get()));
maybe_wrap_object_or_null_value(cx, rval);
}
}<|fim▁end|> | |
<|file_name|>test_igorio.py<|end_file_name|><|fim▁begin|>"""
Tests of neo.io.igorproio
"""
import unittest
try:
import igor
HAVE_IGOR = True
except ImportError:
HAVE_IGOR = False
from neo.io.igorproio import IgorIO
from neo.test.iotest.common_io_test import BaseTestIO
@unittest.skipUnless(HAVE_IGOR, "requires igor")
class TestIgorIO(BaseTestIO, unittest.TestCase):
ioclass = IgorIO
entities_to_download = [
'igor'
]
entities_to_test = [
'igor/mac-version2.ibw',
'igor/win-version2.ibw'
]
<|fim▁hole|> unittest.main()<|fim▁end|> | if __name__ == "__main__": |
<|file_name|>UserAccountPlace.java<|end_file_name|><|fim▁begin|>/*******************************************************************************
* Copyright (c) 2010, 2012 Tasktop Technologies
* Copyright (c) 2010, 2011 SpringSource, a division of VMware
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
******************************************************************************/
package com.tasktop.c2c.server.profile.web.ui.client.place;
import java.util.Arrays;
import java.util.List;
import com.tasktop.c2c.server.common.profile.web.client.navigation.AbstractPlaceTokenizer;
import com.tasktop.c2c.server.common.profile.web.client.navigation.PageMapping;
import com.tasktop.c2c.server.common.profile.web.client.place.Breadcrumb;<|fim▁hole|>import com.tasktop.c2c.server.common.profile.web.client.place.BreadcrumbPlace;
import com.tasktop.c2c.server.common.profile.web.client.place.HeadingPlace;
import com.tasktop.c2c.server.common.profile.web.client.place.LoggedInPlace;
import com.tasktop.c2c.server.common.profile.web.client.place.WindowTitlePlace;
import com.tasktop.c2c.server.common.profile.web.client.util.WindowTitleBuilder;
import com.tasktop.c2c.server.common.profile.web.shared.actions.GetSshPublicKeysAction;
import com.tasktop.c2c.server.common.profile.web.shared.actions.GetSshPublicKeysResult;
import com.tasktop.c2c.server.profile.domain.project.Profile;
import com.tasktop.c2c.server.profile.domain.project.SshPublicKey;
import com.tasktop.c2c.server.profile.web.ui.client.gin.AppGinjector;
public class UserAccountPlace extends LoggedInPlace implements HeadingPlace, WindowTitlePlace, BreadcrumbPlace {
public static PageMapping Account = new PageMapping(new UserAccountPlace.Tokenizer(), "account");
@Override
public String getHeading() {
return "Account Settings";
}
private static class Tokenizer extends AbstractPlaceTokenizer<UserAccountPlace> {
@Override
public UserAccountPlace getPlace(String token) {
return UserAccountPlace.createPlace();
}
}
private Profile profile;
private List<SshPublicKey> sshPublicKeys;
public static UserAccountPlace createPlace() {
return new UserAccountPlace();
}
private UserAccountPlace() {
}
public Profile getProfile() {
return profile;
}
public List<SshPublicKey> getSshPublicKeys() {
return sshPublicKeys;
}
@Override
public String getPrefix() {
return Account.getUrl();
}
@Override
protected void addActions() {
super.addActions();
addAction(new GetSshPublicKeysAction());
}
@Override
protected void handleBatchResults() {
super.handleBatchResults();
profile = AppGinjector.get.instance().getAppState().getCredentials().getProfile();
sshPublicKeys = getResult(GetSshPublicKeysResult.class).get();
onPlaceDataFetched();
}
@Override
public String getWindowTitle() {
return WindowTitleBuilder.createWindowTitle("Account Settings");
}
@Override
public List<Breadcrumb> getBreadcrumbs() {
return Arrays.asList(new Breadcrumb("", "Projects"), new Breadcrumb(getHref(), "Account"));
}
}<|fim▁end|> | |
<|file_name|>issue-16922.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::any::Any;
fn foo<T: Any>(value: &T) -> Box<Any> {
Box::new(value) as Box<Any>
//~^ ERROR: cannot infer an appropriate lifetime
}
<|fim▁hole|><|fim▁end|> | fn main() {
let _ = foo(&5);
} |
<|file_name|>alerts.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import copy
import datetime
import json
import logging
import subprocess
import sys
import warnings
from email.mime.text import MIMEText
from email.utils import formatdate
from smtplib import SMTP
from smtplib import SMTP_SSL
from smtplib import SMTPAuthenticationError
from smtplib import SMTPException
from socket import error
import boto.sns as sns
import requests
import stomp
from exotel import Exotel
from jira.client import JIRA
from jira.exceptions import JIRAError
from requests.exceptions import RequestException
from staticconf.loader import yaml_loader
from texttable import Texttable
from twilio import TwilioRestException
from twilio.rest import TwilioRestClient
from util import EAException
from util import elastalert_logger
from util import lookup_es_key
from util import pretty_ts
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
return json.JSONEncoder.default(self, obj)
class BasicMatchString(object):
""" Creates a string containing fields in match for the given rule. """
def __init__(self, rule, match):
self.rule = rule
self.match = match
def _ensure_new_line(self):
while self.text[-2:] != '\n\n':
self.text += '\n'
def _add_custom_alert_text(self):
missing = '<MISSING VALUE>'
alert_text = unicode(self.rule.get('alert_text', ''))
if 'alert_text_args' in self.rule:
alert_text_args = self.rule.get('alert_text_args')
alert_text_values = [lookup_es_key(self.match, arg) for arg in alert_text_args]
# Support referencing other top-level rule properties
# This technically may not work if there is a top-level rule property with the same name
# as an es result key, since it would have been matched in the lookup_es_key call above
for i in xrange(len(alert_text_values)):
if alert_text_values[i] is None:
alert_value = self.rule.get(alert_text_args[i])
if alert_value:
alert_text_values[i] = alert_value
alert_text_values = [missing if val is None else val for val in alert_text_values]
alert_text = alert_text.format(*alert_text_values)
elif 'alert_text_kw' in self.rule:
kw = {}
for name, kw_name in self.rule.get('alert_text_kw').items():
val = lookup_es_key(self.match, name)
# Support referencing other top-level rule properties
# This technically may not work if there is a top-level rule property with the same name
# as an es result key, since it would have been matched in the lookup_es_key call above
if val is None:
val = self.rule.get(name)
kw[kw_name] = missing if val is None else val
alert_text = alert_text.format(**kw)
self.text += alert_text
def _add_rule_text(self):
self.text += self.rule['type'].get_match_str(self.match)
def _add_top_counts(self):
for key, counts in self.match.items():
if key.startswith('top_events_'):
self.text += '%s:\n' % (key[11:])
top_events = counts.items()
if not top_events:
self.text += 'No events found.\n'
else:
top_events.sort(key=lambda x: x[1], reverse=True)
for term, count in top_events:
self.text += '%s: %s\n' % (term, count)
self.text += '\n'
def _add_match_items(self):
match_items = self.match.items()
match_items.sort(key=lambda x: x[0])
for key, value in match_items:
if key.startswith('top_events_'):
continue
value_str = unicode(value)
if type(value) in [list, dict]:
try:
value_str = self._pretty_print_as_json(value)
except TypeError:
# Non serializable object, fallback to str
pass
self.text += '%s: %s\n' % (key, value_str)
def _pretty_print_as_json(self, blob):
try:
return json.dumps(blob, cls=DateTimeEncoder, sort_keys=True, indent=4, ensure_ascii=False)
except UnicodeDecodeError:
# This blob contains non-unicode, so lets pretend it's Latin-1 to show something
return json.dumps(blob, cls=DateTimeEncoder, sort_keys=True, indent=4, encoding='Latin-1', ensure_ascii=False)
def __str__(self):
self.text = ''
if 'alert_text' not in self.rule:
self.text += self.rule['name'] + '\n\n'
self._add_custom_alert_text()
self._ensure_new_line()
if self.rule.get('alert_text_type') != 'alert_text_only':
self._add_rule_text()
self._ensure_new_line()
if self.rule.get('top_count_keys'):
self._add_top_counts()
if self.rule.get('alert_text_type') != 'exclude_fields':
self._add_match_items()
return self.text
class JiraFormattedMatchString(BasicMatchString):
def _add_match_items(self):
match_items = dict([(x, y) for x, y in self.match.items() if not x.startswith('top_events_')])
json_blob = self._pretty_print_as_json(match_items)
preformatted_text = u'{{code:json}}{0}{{code}}'.format(json_blob)
self.text += preformatted_text
class Alerter(object):
""" Base class for types of alerts.
:param rule: The rule configuration.
"""
required_options = frozenset([])
def __init__(self, rule):
elastalert_logger.info("Starting up method:---alerts.__init__---")
self.rule = rule
# pipeline object is created by ElastAlerter.send_alert()
# and attached to each alerters used by a rule before calling alert()
self.pipeline = None
self.resolve_rule_references(self.rule)
def resolve_rule_references(self, root):
# Support referencing other top-level rule properties to avoid redundant copy/paste
if type(root) == list:
# Make a copy since we may be modifying the contents of the structure we're walking
for i, item in enumerate(copy.copy(root)):
if type(item) == dict or type(item) == list:
self.resolve_rule_references(root[i])
else:
root[i] = self.resolve_rule_reference(item)
elif type(root) == dict:
# Make a copy since we may be modifying the contents of the structure we're walking
for key, value in root.copy().iteritems():
if type(value) == dict or type(value) == list:
self.resolve_rule_references(root[key])
else:
root[key] = self.resolve_rule_reference(value)
def resolve_rule_reference(self, value):
strValue = unicode(value)
if strValue.startswith('$') and strValue.endswith('$') and strValue[1:-1] in self.rule:
if type(value) == int:
return int(self.rule[strValue[1:-1]])
else:
return self.rule[strValue[1:-1]]
else:
return value
def alert(self, match):
""" Send an alert. Match is a dictionary of information about the alert.
:param match: A dictionary of relevant information to the alert.
"""
raise NotImplementedError()
def get_info(self):
""" Returns a dictionary of data related to this alert. At minimum, this should contain
a field type corresponding to the type of Alerter. """
return {'type': 'Unknown'}
def create_title(self, matches):
""" Creates custom alert title to be used, e.g. as an e-mail subject or JIRA issue summary.
:param matches: A list of dictionaries of relevant information to the alert.
"""
if 'alert_subject' in self.rule:
return self.create_custom_title(matches)
return self.create_default_title(matches)
def create_custom_title(self, matches):
alert_subject = unicode(self.rule['alert_subject'])
if 'alert_subject_args' in self.rule:
alert_subject_args = self.rule['alert_subject_args']
alert_subject_values = [lookup_es_key(matches[0], arg) for arg in alert_subject_args]
# Support referencing other top-level rule properties
# This technically may not work if there is a top-level rule property with the same name
# as an es result key, since it would have been matched in the lookup_es_key call above
for i in xrange(len(alert_subject_values)):
if alert_subject_values[i] is None:
alert_value = self.rule.get(alert_subject_args[i])
if alert_value:
alert_subject_values[i] = alert_value
alert_subject_values = ['<MISSING VALUE>' if val is None else val for val in alert_subject_values]
return alert_subject.format(*alert_subject_values)
return alert_subject
def create_alert_body(self, matches):
body = self.get_aggregation_summary_text(matches)
for match in matches:
body += unicode(BasicMatchString(self.rule, match))
# Separate text of aggregated alerts with dashes
if len(matches) > 1:
body += '\n----------------------------------------\n'
return body
def get_aggregation_summary_text(self, matches):
text = ''
if 'aggregation' in self.rule and 'summary_table_fields' in self.rule:
summary_table_fields = self.rule['summary_table_fields']
if not isinstance(summary_table_fields, list):
summary_table_fields = [summary_table_fields]
# Include a count aggregation so that we can see at a glance how many of each aggregation_key were encountered
summary_table_fields_with_count = summary_table_fields + ['count']
text += "Aggregation resulted in the following data for summary_table_fields ==> {0}:\n\n".format(summary_table_fields_with_count)
text_table = Texttable()
text_table.header(summary_table_fields_with_count)
match_aggregation = {}
# Maintain an aggregate count for each unique key encountered in the aggregation period
for match in matches:
key_tuple = tuple([unicode(lookup_es_key(match, key)) for key in summary_table_fields])
if key_tuple not in match_aggregation:
match_aggregation[key_tuple] = 1
else:
match_aggregation[key_tuple] = match_aggregation[key_tuple] + 1
for keys, count in match_aggregation.iteritems():
text_table.add_row([key for key in keys] + [count])
text += text_table.draw() + '\n\n'
return unicode(text)
def create_default_title(self, matches):
return self.rule['name']
def get_account(self, account_file):
""" Gets the username and password from an account file.
:param account_file: Name of the file which contains user and password information.
"""
account_conf = yaml_loader(account_file)
if 'user' not in account_conf or 'password' not in account_conf:
raise EAException('Account file must have user and password fields')
self.user = account_conf['user']
self.password = account_conf['password']
class StompAlerter(Alerter):
""" The stomp alerter publishes alerts via stomp to a broker. """
required_options = frozenset(['stomp_hostname', 'stomp_hostport', 'stomp_login', 'stomp_password'])
def alert(self, matches):
alerts = []
qk = self.rule.get('query_key', None)
fullmessage = {}
for match in matches:
if qk in match:
elastalert_logger.info(
'Alert for %s, %s at %s:' % (self.rule['name'], match[qk], lookup_es_key(match, self.rule['timestamp_field'])))
alerts.append('1)Alert for %s, %s at %s:' % (self.rule['name'], match[qk], lookup_es_key(match, self.rule['timestamp_field'])))
fullmessage['match'] = match[qk]
else:
elastalert_logger.info('Alert for %s at %s:' % (self.rule['name'], lookup_es_key(match, self.rule['timestamp_field'])))
alerts.append(
'2)Alert for %s at %s:' % (self.rule['name'], lookup_es_key(match, self.rule['timestamp_field']))
)
fullmessage['match'] = lookup_es_key(match, self.rule['timestamp_field'])
elastalert_logger.info(unicode(BasicMatchString(self.rule, match)))
fullmessage['alerts'] = alerts
fullmessage['rule'] = self.rule['name']
fullmessage['matching'] = unicode(BasicMatchString(self.rule, match))
fullmessage['alertDate'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
fullmessage['body'] = self.create_alert_body(matches)
self.stomp_hostname = self.rule.get('stomp_hostname', 'localhost')
self.stomp_hostport = self.rule.get('stomp_hostport', '61613')
self.stomp_login = self.rule.get('stomp_login', 'admin')
self.stomp_password = self.rule.get('stomp_password', 'admin')
self.stomp_destination = self.rule.get('stomp_destination', '/queue/ALERT')
conn = stomp.Connection([(self.stomp_hostname, self.stomp_hostport)])
conn.start()
conn.connect(self.stomp_login, self.stomp_password)
conn.send(self.stomp_destination, json.dumps(fullmessage))
conn.disconnect()
def get_info(self):
return {'type': 'stomp'}
class DebugAlerter(Alerter):
""" The debug alerter uses a Python logger (by default, alerting to terminal). """
def alert(self, matches):
qk = self.rule.get('query_key', None)
for match in matches:
if qk in match:
elastalert_logger.info(
'Alert for %s, %s at %s:' % (self.rule['name'], match[qk], lookup_es_key(match, self.rule['timestamp_field'])))
else:
elastalert_logger.info('Alert for %s at %s:' % (self.rule['name'], lookup_es_key(match, self.rule['timestamp_field'])))
elastalert_logger.info(unicode(BasicMatchString(self.rule, match)))
def get_info(self):
return {'type': 'debug'}
class EmailAlerter(Alerter):
""" Sends an email alert """
required_options = frozenset(['email'])
def __init__(self, *args):
super(EmailAlerter, self).__init__(*args)
self.smtp_host = self.rule.get('smtp_host', 'localhost')
self.smtp_ssl = self.rule.get('smtp_ssl', False)
self.from_addr = self.rule.get('from_addr', 'ElastAlert')
self.smtp_port = self.rule.get('smtp_port')
self.user = self.rule.get('user')
self.password = self.rule.get('password')
# Convert email to a list if it isn't already
if isinstance(self.rule['email'], basestring):
self.rule['email'] = [self.rule['email']]
# If there is a cc then also convert it a list if it isn't
cc = self.rule.get('cc')
if cc and isinstance(cc, basestring):
self.rule['cc'] = [self.rule['cc']]
# If there is a bcc then also convert it to a list if it isn't
bcc = self.rule.get('bcc')
if bcc and isinstance(bcc, basestring):
self.rule['bcc'] = [self.rule['bcc']]
add_suffix = self.rule.get('email_add_domain')
if add_suffix and not add_suffix.startswith('@'):
self.rule['email_add_domain'] = '@' + add_suffix
def alert(self, matches):
body = self.create_alert_body(matches)
# Add JIRA ticket if it exists
if self.pipeline is not None and 'jira_ticket' in self.pipeline:
url = '%s/browse/%s' % (self.pipeline['jira_server'], self.pipeline['jira_ticket'])
body += '\nJIRA ticket: %s' % (url)
to_addr = self.rule['email']
if 'email_from_field' in self.rule:
recipient = lookup_es_key(matches[0], self.rule['email_from_field'])
if isinstance(recipient, basestring):
if '@' in recipient:
to_addr = [recipient]
elif 'email_add_domain' in self.rule:
to_addr = [recipient + self.rule['email_add_domain']]
email_msg = MIMEText(body.encode('UTF-8'), _charset='UTF-8')
email_msg['Subject'] = self.create_title(matches)
email_msg['To'] = ', '.join(to_addr)
email_msg['From'] = self.from_addr
email_msg['Reply-To'] = self.rule.get('email_reply_to', email_msg['To'])
email_msg['Date'] = formatdate()
if self.rule.get('cc'):
email_msg['CC'] = ','.join(self.rule['cc'])
to_addr = to_addr + self.rule['cc']
if self.rule.get('bcc'):
to_addr = to_addr + self.rule['bcc']
try:
if self.smtp_ssl:
if self.smtp_port:
self.smtp = SMTP_SSL(self.smtp_host, self.smtp_port)
else:
self.smtp = SMTP_SSL(self.smtp_host)
else:
if self.smtp_port:
self.smtp = SMTP(self.smtp_host, self.smtp_port)
else:
self.smtp = SMTP(self.smtp_host)
self.smtp.ehlo()
if self.smtp.has_extn('STARTTLS'):
self.smtp.starttls()
#邮箱认证
self.smtp.login(self.user, self.password)
except (SMTPException, error) as e:
raise EAException("Error connecting to SMTP host: %s" % (e))
except SMTPAuthenticationError as e:
raise EAException("SMTP username/password rejected: %s" % (e))
self.smtp.sendmail(self.from_addr, to_addr, email_msg.as_string())
self.smtp.close()
elastalert_logger.info("Sent email to %s" % (to_addr))
def create_default_title(self, matches):
subject = 'ElastAlert: %s' % (self.rule['name'])
# If the rule has a query_key, add that value plus timestamp to subject
if 'query_key' in self.rule:
qk = matches[0].get(self.rule['query_key'])
if qk:
subject += ' - %s' % (qk)
return subject
def get_info(self):
return {'type': 'email',
'recipients': self.rule['email']}
class JiraAlerter(Alerter):
""" Creates a Jira ticket for each alert """
required_options = frozenset(['jira_server', 'jira_account_file', 'jira_project', 'jira_issuetype'])
# Maintain a static set of built-in fields that we explicitly know how to set
# For anything else, we will do best-effort and try to set a string value
known_field_list = [
'jira_account_file',
'jira_assignee',
'jira_bump_in_statuses',
'jira_bump_not_in_statuses',
'jira_bump_tickets',
'jira_component',
'jira_components',
'jira_description',
'jira_ignore_in_title',
'jira_issuetype',
'jira_label',
'jira_labels',
'jira_max_age',
'jira_priority',
'jira_project',
'jira_server',
'jira_watchers',
]
# Some built-in jira types that can be used as custom fields require special handling
# Here is a sample of one of them:
# {"id":"customfield_12807","name":"My Custom Field","custom":true,"orderable":true,"navigable":true,"searchable":true,
# "clauseNames":["cf[12807]","My Custom Field"],"schema":{"type":"array","items":"string",
# "custom":"com.atlassian.jira.plugin.system.customfieldtypes:multiselect","customId":12807}}
# There are likely others that will need to be updated on a case-by-case basis
custom_string_types_with_special_handling = [
'com.atlassian.jira.plugin.system.customfieldtypes:multicheckboxes',
'com.atlassian.jira.plugin.system.customfieldtypes:multiselect',
'com.atlassian.jira.plugin.system.customfieldtypes:radiobuttons',
]
def __init__(self, rule):
super(JiraAlerter, self).__init__(rule)
self.server = self.rule['jira_server']
self.get_account(self.rule['jira_account_file'])
self.project = self.rule['jira_project']
self.issue_type = self.rule['jira_issuetype']
# We used to support only a single component. This allows us to maintain backwards compatibility
# while also giving the user-facing API a more representative name
self.components = self.rule.get('jira_components', self.rule.get('jira_component'))
# We used to support only a single label. This allows us to maintain backwards compatibility
# while also giving the user-facing API a more representative name
self.labels = self.rule.get('jira_labels', self.rule.get('jira_label'))
self.description = self.rule.get('jira_description', '')
self.assignee = self.rule.get('jira_assignee')
self.max_age = self.rule.get('jira_max_age', 30)
self.priority = self.rule.get('jira_priority')
self.bump_tickets = self.rule.get('jira_bump_tickets', False)
self.bump_not_in_statuses = self.rule.get('jira_bump_not_in_statuses')
self.bump_in_statuses = self.rule.get('jira_bump_in_statuses')
self.watchers = self.rule.get('jira_watchers')
if self.bump_in_statuses and self.bump_not_in_statuses:
msg = 'Both jira_bump_in_statuses (%s) and jira_bump_not_in_statuses (%s) are set.' % \
(','.join(self.bump_in_statuses), ','.join(self.bump_not_in_statuses))
intersection = list(set(self.bump_in_statuses) & set(self.bump_in_statuses))
if intersection:
msg = '%s Both have common statuses of (%s). As such, no tickets will ever be found.' % (
msg, ','.join(intersection))
msg += ' This should be simplified to use only one or the other.'
logging.warning(msg)
self.jira_args = {'project': {'key': self.project},
'issuetype': {'name': self.issue_type}}
if self.components:
# Support single component or list
if type(self.components) != list:<|fim▁hole|> self.jira_args['components'] = [{'name': self.components}]
else:
self.jira_args['components'] = [{'name': component} for component in self.components]
if self.labels:
# Support single label or list
if type(self.labels) != list:
self.labels = [self.labels]
self.jira_args['labels'] = self.labels
if self.watchers:
# Support single watcher or list
if type(self.watchers) != list:
self.watchers = [self.watchers]
if self.assignee:
self.jira_args['assignee'] = {'name': self.assignee}
try:
self.client = JIRA(self.server, basic_auth=(self.user, self.password))
self.get_priorities()
self.get_arbitrary_fields()
except JIRAError as e:
# JIRAError may contain HTML, pass along only first 1024 chars
raise EAException("Error connecting to JIRA: %s" % (str(e)[:1024]))
try:
if self.priority is not None:
self.jira_args['priority'] = {'id': self.priority_ids[self.priority]}
except KeyError:
logging.error("Priority %s not found. Valid priorities are %s" % (self.priority, self.priority_ids.keys()))
def get_arbitrary_fields(self):
# This API returns metadata about all the fields defined on the jira server (built-ins and custom ones)
fields = self.client.fields()
for jira_field, value in self.rule.iteritems():
# If we find a field that is not covered by the set that we are aware of, it means it is either:
# 1. A built-in supported field in JIRA that we don't have on our radar
# 2. A custom field that a JIRA admin has configured
if jira_field.startswith('jira_') and jira_field not in self.known_field_list:
# Remove the jira_ part. Convert underscores to spaces
normalized_jira_field = jira_field[5:].replace('_', ' ').lower()
# All jira fields should be found in the 'id' or the 'name' field. Therefore, try both just in case
for identifier in ['name', 'id']:
field = next((f for f in fields if normalized_jira_field == f[identifier].replace('_', ' ').lower()), None)
if field:
break
if not field:
# Log a warning to ElastAlert saying that we couldn't find that type?
# OR raise and fail to load the alert entirely? Probably the latter...
raise Exception("Could not find a definition for the jira field '{0}'".format(normalized_jira_field))
arg_name = field['id']
# Check the schema information to decide how to set the value correctly
# If the schema information is not available, raise an exception since we don't know how to set it
# Note this is only the case for two built-in types, id: issuekey and id: thumbnail
if not ('schema' in field or 'type' in field['schema']):
raise Exception("Could not determine schema information for the jira field '{0}'".format(normalized_jira_field))
arg_type = field['schema']['type']
# Handle arrays of simple types like strings or numbers
if arg_type == 'array':
# As a convenience, support the scenario wherein the user only provides
# a single value for a multi-value field e.g. jira_labels: Only_One_Label
if type(value) != list:
value = [value]
array_items = field['schema']['items']
# Simple string types
if array_items in ['string', 'date', 'datetime']:
# Special case for multi-select custom types (the JIRA metadata says that these are strings, but
# in reality, they are required to be provided as an object.
if 'custom' in field['schema'] and field['schema']['custom'] in self.custom_string_types_with_special_handling:
self.jira_args[arg_name] = [{'value': v} for v in value]
else:
self.jira_args[arg_name] = value
elif array_items == 'number':
self.jira_args[arg_name] = [int(v) for v in value]
# Also attempt to handle arrays of complex types that have to be passed as objects with an identifier 'key'
elif array_items == 'option':
self.jira_args[arg_name] = [{'value': v} for v in value]
else:
# Try setting it as an object, using 'name' as the key
# This may not work, as the key might actually be 'key', 'id', 'value', or something else
# If it works, great! If not, it will manifest itself as an API error that will bubble up
self.jira_args[arg_name] = [{'name': v} for v in value]
# Handle non-array types
else:
# Simple string types
if arg_type in ['string', 'date', 'datetime']:
# Special case for custom types (the JIRA metadata says that these are strings, but
# in reality, they are required to be provided as an object.
if 'custom' in field['schema'] and field['schema']['custom'] in self.custom_string_types_with_special_handling:
self.jira_args[arg_name] = {'value': value}
else:
self.jira_args[arg_name] = value
# Number type
elif arg_type == 'number':
self.jira_args[arg_name] = int(value)
elif arg_type == 'option':
self.jira_args[arg_name] = {'value': value}
# Complex type
else:
self.jira_args[arg_name] = {'name': value}
def get_priorities(self):
""" Creates a mapping of priority index to id. """
priorities = self.client.priorities()
self.priority_ids = {}
for x in range(len(priorities)):
self.priority_ids[x] = priorities[x].id
def set_assignee(self, assignee):
self.assignee = assignee
if assignee:
self.jira_args['assignee'] = {'name': assignee}
elif 'assignee' in self.jira_args:
self.jira_args.pop('assignee')
def find_existing_ticket(self, matches):
# Default title, get stripped search version
if 'alert_subject' not in self.rule:
title = self.create_default_title(matches, True)
else:
title = self.create_title(matches)
if 'jira_ignore_in_title' in self.rule:
title = title.replace(matches[0].get(self.rule['jira_ignore_in_title'], ''), '')
# This is necessary for search to work. Other special characters and dashes
# directly adjacent to words appear to be ok
title = title.replace(' - ', ' ')
title = title.replace('\\', '\\\\')
date = (datetime.datetime.now() - datetime.timedelta(days=self.max_age)).strftime('%Y-%m-%d')
jql = 'project=%s AND summary~"%s" and created >= "%s"' % (self.project, title, date)
if self.bump_in_statuses:
jql = '%s and status in (%s)' % (jql, ','.join(self.bump_in_statuses))
if self.bump_not_in_statuses:
jql = '%s and status not in (%s)' % (jql, ','.join(self.bump_not_in_statuses))
try:
issues = self.client.search_issues(jql)
except JIRAError as e:
logging.exception("Error while searching for JIRA ticket using jql '%s': %s" % (jql, e))
return None
if len(issues):
return issues[0]
def comment_on_ticket(self, ticket, match):
text = unicode(JiraFormattedMatchString(self.rule, match))
timestamp = pretty_ts(lookup_es_key(match, self.rule['timestamp_field']))
comment = "This alert was triggered again at %s\n%s" % (timestamp, text)
self.client.add_comment(ticket, comment)
def alert(self, matches):
elastalert_logger.info("Starting up method:---alerts.start---")
title = self.create_title(matches)
if self.bump_tickets:
ticket = self.find_existing_ticket(matches)
if ticket:
elastalert_logger.info('Commenting on existing ticket %s' % (ticket.key))
for match in matches:
try:
self.comment_on_ticket(ticket, match)
except JIRAError as e:
logging.exception("Error while commenting on ticket %s: %s" % (ticket, e))
if self.pipeline is not None:
self.pipeline['jira_ticket'] = ticket
self.pipeline['jira_server'] = self.server
return None
self.jira_args['summary'] = title
self.jira_args['description'] = self.create_alert_body(matches)
try:
self.issue = self.client.create_issue(**self.jira_args)
# You can not add watchers on initial creation. Only as a follow-up action
if self.watchers:
for watcher in self.watchers:
try:
self.client.add_watcher(self.issue.key, watcher)
except Exception as ex:
# Re-raise the exception, preserve the stack-trace, and give some
# context as to which watcher failed to be added
raise Exception("Exception encountered when trying to add '{0}' as a watcher. Does the user exist?\n{1}" .format(watcher, ex)), None, sys.exc_info()[2]
except JIRAError as e:
raise EAException("Error creating JIRA ticket: %s" % (e))
elastalert_logger.info("Opened Jira ticket: %s" % (self.issue))
if self.pipeline is not None:
self.pipeline['jira_ticket'] = self.issue
self.pipeline['jira_server'] = self.server
def create_alert_body(self, matches):
body = self.description + '\n'
body += self.get_aggregation_summary_text(matches)
for match in matches:
body += unicode(JiraFormattedMatchString(self.rule, match))
if len(matches) > 1:
body += '\n----------------------------------------\n'
return body
def get_aggregation_summary_text(self, matches):
text = super(JiraAlerter, self).get_aggregation_summary_text(matches)
if text:
text = u'{{noformat}}{0}{{noformat}}'.format(text)
return text
def create_default_title(self, matches, for_search=False):
# If there is a query_key, use that in the title
if 'query_key' in self.rule and self.rule['query_key'] in matches[0]:
title = 'ElastAlert: %s matched %s' % (matches[0][self.rule['query_key']], self.rule['name'])
else:
title = 'ElastAlert: %s' % (self.rule['name'])
if for_search:
return title
title += ' - %s' % (pretty_ts(matches[0][self.rule['timestamp_field']], self.rule.get('use_local_time')))
# Add count for spikes
count = matches[0].get('spike_count')
if count:
title += ' - %s+ events' % (count)
return title
def get_info(self):
return {'type': 'jira'}
class CommandAlerter(Alerter):
required_options = set(['command'])
def __init__(self, *args):
super(CommandAlerter, self).__init__(*args)
self.last_command = []
self.shell = False
if isinstance(self.rule['command'], basestring):
self.shell = True
if '%' in self.rule['command']:
logging.warning('Warning! You could be vulnerable to shell injection!')
self.rule['command'] = [self.rule['command']]
self.new_style_string_format = False
if 'new_style_string_format' in self.rule and self.rule['new_style_string_format']:
self.new_style_string_format = True
def alert(self, matches):
elastalert_logger.info("Starting up method:---alerts.command.alert---")
# Format the command and arguments
try:
if self.new_style_string_format:
command = [command_arg.format(match=matches[0]) for command_arg in self.rule['command']]
else:
command = [command_arg % matches[0] for command_arg in self.rule['command']]
self.last_command = command
except KeyError as e:
raise EAException("Error formatting command: %s" % (e))
# Run command and pipe data
try:
subp = subprocess.Popen(command, stdin=subprocess.PIPE, shell=self.shell)
if self.rule.get('pipe_match_json'):
match_json = json.dumps(matches, cls=DateTimeEncoder) + '\n'
stdout, stderr = subp.communicate(input=match_json)
if self.rule.get("fail_on_non_zero_exit", False) and subp.wait():
raise EAException("Non-zero exit code while running command %s" % (' '.join(command)))
except OSError as e:
raise EAException("Error while running command %s: %s" % (' '.join(command), e))
def get_info(self):
return {'type': 'command',
'command': ' '.join(self.last_command)}
class SnsAlerter(Alerter):
"""send alert using AWS SNS service"""
required_options = frozenset(['sns_topic_arn'])
def __init__(self, *args):
super(SnsAlerter, self).__init__(*args)
self.sns_topic_arn = self.rule.get('sns_topic_arn', '')
self.aws_access_key = self.rule.get('aws_access_key', '')
self.aws_secret_key = self.rule.get('aws_secret_key', '')
self.aws_region = self.rule.get('aws_region', 'us-east-1')
self.boto_profile = self.rule.get('boto_profile', '')
def create_default_title(self, matches):
subject = 'ElastAlert: %s' % (self.rule['name'])
return subject
def alert(self, matches):
body = self.create_alert_body(matches)
# use aws_access_key and aws_secret_key if specified; then use boto profile if specified;
# otherwise use instance role
if not self.aws_access_key and not self.aws_secret_key:
if not self.boto_profile:
sns_client = sns.connect_to_region(self.aws_region)
else:
sns_client = sns.connect_to_region(self.aws_region,
profile_name=self.boto_profile)
else:
sns_client = sns.connect_to_region(self.aws_region,
aws_access_key_id=self.aws_access_key,
aws_secret_access_key=self.aws_secret_key)
sns_client.publish(self.sns_topic_arn, body, subject=self.create_title(matches))
elastalert_logger.info("Sent sns notification to %s" % (self.sns_topic_arn))
class HipChatAlerter(Alerter):
""" Creates a HipChat room notification for each alert """
required_options = frozenset(['hipchat_auth_token', 'hipchat_room_id'])
def __init__(self, rule):
super(HipChatAlerter, self).__init__(rule)
self.hipchat_msg_color = self.rule.get('hipchat_msg_color', 'red')
self.hipchat_message_format = self.rule.get('hipchat_message_format', 'html')
self.hipchat_auth_token = self.rule['hipchat_auth_token']
self.hipchat_room_id = self.rule['hipchat_room_id']
self.hipchat_domain = self.rule.get('hipchat_domain', 'api.hipchat.com')
self.hipchat_ignore_ssl_errors = self.rule.get('hipchat_ignore_ssl_errors', False)
self.hipchat_notify = self.rule.get('hipchat_notify', True)
self.hipchat_from = self.rule.get('hipchat_from', '')
self.url = 'https://%s/v2/room/%s/notification?auth_token=%s' % (
self.hipchat_domain, self.hipchat_room_id, self.hipchat_auth_token)
self.hipchat_proxy = self.rule.get('hipchat_proxy', None)
def alert(self, matches):
body = self.create_alert_body(matches)
# HipChat sends 400 bad request on messages longer than 10000 characters
if (len(body) > 9999):
body = body[:9980] + '..(truncated)'
# Use appropriate line ending for text/html
if self.hipchat_message_format == 'html':
body = body.replace('\n', '<br />')
# Post to HipChat
headers = {'content-type': 'application/json'}
# set https proxy, if it was provided
proxies = {'https': self.hipchat_proxy} if self.hipchat_proxy else None
payload = {
'color': self.hipchat_msg_color,
'message': body,
'message_format': self.hipchat_message_format,
'notify': self.hipchat_notify,
'from': self.hipchat_from
}
try:
if self.hipchat_ignore_ssl_errors:
requests.packages.urllib3.disable_warnings()
response = requests.post(self.url, data=json.dumps(payload, cls=DateTimeEncoder), headers=headers,
verify=not self.hipchat_ignore_ssl_errors,
proxies=proxies)
warnings.resetwarnings()
response.raise_for_status()
except RequestException as e:
raise EAException("Error posting to HipChat: %s" % e)
elastalert_logger.info("Alert sent to HipChat room %s" % self.hipchat_room_id)
def get_info(self):
return {'type': 'hipchat',
'hipchat_room_id': self.hipchat_room_id}
class SlackAlerter(Alerter):
""" Creates a Slack room message for each alert """
required_options = frozenset(['slack_webhook_url'])
def __init__(self, rule):
super(SlackAlerter, self).__init__(rule)
self.slack_webhook_url = self.rule['slack_webhook_url']
if isinstance(self.slack_webhook_url, basestring):
self.slack_webhook_url = [self.slack_webhook_url]
self.slack_proxy = self.rule.get('slack_proxy', None)
self.slack_username_override = self.rule.get('slack_username_override', 'elastalert')
self.slack_channel_override = self.rule.get('slack_channel_override', '')
self.slack_emoji_override = self.rule.get('slack_emoji_override', ':ghost:')
self.slack_icon_url_override = self.rule.get('slack_icon_url_override', '')
self.slack_msg_color = self.rule.get('slack_msg_color', 'danger')
self.slack_parse_override = self.rule.get('slack_parse_override', 'none')
self.slack_text_string = self.rule.get('slack_text_string', '')
def format_body(self, body):
# https://api.slack.com/docs/formatting
body = body.encode('UTF-8')
body = body.replace('&', '&')
body = body.replace('<', '<')
body = body.replace('>', '>')
return body
def alert(self, matches):
body = self.create_alert_body(matches)
body = self.format_body(body)
# post to slack
headers = {'content-type': 'application/json'}
# set https proxy, if it was provided
proxies = {'https': self.slack_proxy} if self.slack_proxy else None
payload = {
'username': self.slack_username_override,
'channel': self.slack_channel_override,
'parse': self.slack_parse_override,
'text': self.slack_text_string,
'attachments': [
{
'color': self.slack_msg_color,
'title': self.create_title(matches),
'text': body,
'fields': []
}
]
}
if self.slack_icon_url_override != '':
payload['icon_url'] = self.slack_icon_url_override
else:
payload['icon_emoji'] = self.slack_emoji_override
for url in self.slack_webhook_url:
try:
response = requests.post(url, data=json.dumps(payload, cls=DateTimeEncoder), headers=headers, proxies=proxies)
response.raise_for_status()
except RequestException as e:
raise EAException("Error posting to slack: %s" % e)
elastalert_logger.info("Alert sent to Slack")
def get_info(self):
return {'type': 'slack',
'slack_username_override': self.slack_username_override,
'slack_webhook_url': self.slack_webhook_url}
class PagerDutyAlerter(Alerter):
""" Create an incident on PagerDuty for each alert """
required_options = frozenset(['pagerduty_service_key', 'pagerduty_client_name'])
def __init__(self, rule):
super(PagerDutyAlerter, self).__init__(rule)
self.pagerduty_service_key = self.rule['pagerduty_service_key']
self.pagerduty_client_name = self.rule['pagerduty_client_name']
self.pagerduty_incident_key = self.rule.get('pagerduty_incident_key', '')
self.pagerduty_proxy = self.rule.get('pagerduty_proxy', None)
self.url = 'https://events.pagerduty.com/generic/2010-04-15/create_event.json'
def alert(self, matches):
body = self.create_alert_body(matches)
# post to pagerduty
headers = {'content-type': 'application/json'}
payload = {
'service_key': self.pagerduty_service_key,
'description': self.rule['name'],
'event_type': 'trigger',
'incident_key': self.pagerduty_incident_key,
'client': self.pagerduty_client_name,
'details': {
"information": body.encode('UTF-8'),
},
}
# set https proxy, if it was provided
proxies = {'https': self.pagerduty_proxy} if self.pagerduty_proxy else None
try:
response = requests.post(self.url, data=json.dumps(payload, cls=DateTimeEncoder, ensure_ascii=False), headers=headers, proxies=proxies)
response.raise_for_status()
except RequestException as e:
raise EAException("Error posting to pagerduty: %s" % e)
elastalert_logger.info("Trigger sent to PagerDuty")
def get_info(self):
return {'type': 'pagerduty',
'pagerduty_client_name': self.pagerduty_client_name}
class ExotelAlerter(Alerter):
required_options = frozenset(['exotel_account_sid', 'exotel_auth_token', 'exotel_to_number', 'exotel_from_number'])
def __init__(self, rule):
super(ExotelAlerter, self).__init__(rule)
self.exotel_account_sid = self.rule['exotel_account_sid']
self.exotel_auth_token = self.rule['exotel_auth_token']
self.exotel_to_number = self.rule['exotel_to_number']
self.exotel_from_number = self.rule['exotel_from_number']
self.sms_body = self.rule.get('exotel_message_body', '')
def alert(self, matches):
client = Exotel(self.exotel_account_sid, self.exotel_auth_token)
try:
message_body = self.rule['name'] + self.sms_body
response = client.sms(self.rule['exotel_from_number'], self.rule['exotel_to_number'], message_body)
if response != 200:
raise EAException("Error posting to Exotel, response code is %s" % response)
except:
raise EAException("Error posting to Exotel")
elastalert_logger.info("Trigger sent to Exotel")
def get_info(self):
return {'type': 'exotel', 'exotel_account': self.exotel_account_sid}
class TwilioAlerter(Alerter):
required_options = frozenset(['twilio_accout_sid', 'twilio_auth_token', 'twilio_to_number', 'twilio_from_number'])
def __init__(self, rule):
super(TwilioAlerter, self).__init__(rule)
self.twilio_accout_sid = self.rule['twilio_accout_sid']
self.twilio_auth_token = self.rule['twilio_auth_token']
self.twilio_to_number = self.rule['twilio_to_number']
self.twilio_from_number = self.rule['twilio_from_number']
def alert(self, matches):
client = TwilioRestClient(self.twilio_accout_sid, self.twilio_auth_token)
try:
client.messages.create(body=self.rule['name'],
to=self.twilio_to_number,
from_=self.twilio_to_number)
except TwilioRestException as e:
raise EAException("Error posting to twilio: %s" % e)
elastalert_logger.info("Trigger sent to Twilio")
def get_info(self):
return {'type': 'twilio',
'twilio_client_name': self.twilio_from_number}
class VictorOpsAlerter(Alerter):
""" Creates a VictorOps Incident for each alert """
required_options = frozenset(['victorops_api_key', 'victorops_routing_key', 'victorops_message_type'])
def __init__(self, rule):
super(VictorOpsAlerter, self).__init__(rule)
self.victorops_api_key = self.rule['victorops_api_key']
self.victorops_routing_key = self.rule['victorops_routing_key']
self.victorops_message_type = self.rule['victorops_message_type']
self.victorops_entity_display_name = self.rule.get('victorops_entity_display_name', 'no entity display name')
self.url = 'https://alert.victorops.com/integrations/generic/20131114/alert/%s/%s' % (
self.victorops_api_key, self.victorops_routing_key)
self.victorops_proxy = self.rule.get('victorops_proxy', None)
def alert(self, matches):
body = self.create_alert_body(matches)
# post to victorops
headers = {'content-type': 'application/json'}
# set https proxy, if it was provided
proxies = {'https': self.victorops_proxy} if self.victorops_proxy else None
payload = {
"message_type": self.victorops_message_type,
"entity_display_name": self.victorops_entity_display_name,
"monitoring_tool": "ElastAlert",
"state_message": body
}
try:
response = requests.post(self.url, data=json.dumps(payload, cls=DateTimeEncoder), headers=headers, proxies=proxies)
response.raise_for_status()
except RequestException as e:
raise EAException("Error posting to VictorOps: %s" % e)
elastalert_logger.info("Trigger sent to VictorOps")
def get_info(self):
return {'type': 'victorops',
'victorops_routing_key': self.victorops_routing_key}
class TelegramAlerter(Alerter):
""" Send a Telegram message via bot api for each alert """
required_options = frozenset(['telegram_bot_token', 'telegram_room_id'])
def __init__(self, rule):
super(TelegramAlerter, self).__init__(rule)
self.telegram_bot_token = self.rule['telegram_bot_token']
self.telegram_room_id = self.rule['telegram_room_id']
self.telegram_api_url = self.rule.get('telegram_api_url', 'api.telegram.org')
self.url = 'https://%s/bot%s/%s' % (self.telegram_api_url, self.telegram_bot_token, "sendMessage")
self.telegram_proxy = self.rule.get('telegram_proxy', None)
def alert(self, matches):
body = u'⚠ *%s* ⚠ ```\n' % (self.create_title(matches))
for match in matches:
body += unicode(BasicMatchString(self.rule, match))
# Separate text of aggregated alerts with dashes
if len(matches) > 1:
body += '\n----------------------------------------\n'
body += u' ```'
headers = {'content-type': 'application/json'}
# set https proxy, if it was provided
proxies = {'https': self.telegram_proxy} if self.telegram_proxy else None
payload = {
'chat_id': self.telegram_room_id,
'text': body,
'parse_mode': 'markdown',
'disable_web_page_preview': True
}
try:
response = requests.post(self.url, data=json.dumps(payload, cls=DateTimeEncoder), headers=headers, proxies=proxies)
warnings.resetwarnings()
response.raise_for_status()
except RequestException as e:
raise EAException("Error posting to Telegram: %s" % e)
elastalert_logger.info(
"Alert sent to Telegram room %s" % self.telegram_room_id)
def get_info(self):
return {'type': 'telegram',
'telegram_room_id': self.telegram_room_id}
class GitterAlerter(Alerter):
""" Creates a Gitter activity message for each alert """
required_options = frozenset(['gitter_webhook_url'])
def __init__(self, rule):
super(GitterAlerter, self).__init__(rule)
self.gitter_webhook_url = self.rule['gitter_webhook_url']
self.gitter_proxy = self.rule.get('gitter_proxy', None)
self.gitter_msg_level = self.rule.get('gitter_msg_level', 'error')
def alert(self, matches):
body = self.create_alert_body(matches)
# post to Gitter
headers = {'content-type': 'application/json'}
# set https proxy, if it was provided
proxies = {'https': self.gitter_proxy} if self.gitter_proxy else None
payload = {
'message': body,
'level': self.gitter_msg_level
}
try:
response = requests.post(self.gitter_webhook_url, json.dumps(payload, cls=DateTimeEncoder), headers=headers, proxies=proxies)
response.raise_for_status()
except RequestException as e:
raise EAException("Error posting to Gitter: %s" % e)
elastalert_logger.info("Alert sent to Gitter")
def get_info(self):
return {'type': 'gitter',
'gitter_webhook_url': self.gitter_webhook_url}
class ServiceNowAlerter(Alerter):
""" Creates a ServiceNow alert """
required_options = set(['username', 'password', 'servicenow_rest_url', 'short_description', 'comments', 'assignment_group', 'category', 'subcategory', 'cmdb_ci', 'caller_id'])
def __init__(self, rule):
super(GitterAlerter, self).__init__(rule)
self.servicenow_rest_url = self.rule['servicenow_rest_url']
self.servicenow_proxy = self.rule.get('servicenow_proxy', None)
def alert(self, matches):
for match in matches:
# Parse everything into description.
description = str(BasicMatchString(self.rule, match))
# Set proper headers
headers = {
"Content-Type": "application/json",
"Accept": "application/json;charset=utf-8"
}
proxies = {'https': self.servicenow_proxy} if self.servicenow_proxy else None
payload = {
"description": description,
"short_description": self.rule['short_description'],
"comments": self.rule['comments'],
"assignment_group": self.rule['assignment_group'],
"category": self.rule['category'],
"subcategory": self.rule['subcategory'],
"cmdb_ci": self.rule['cmdb_ci'],
"caller_id": self.rule["caller_id"]
}
try:
response = requests.post(self.servicenow_rest_url, auth=(self.rule['username'], self.rule['password']), headers=headers, data=json.dumps(payload, cls=DateTimeEncoder), proxies=proxies)
response.raise_for_status()
except RequestException as e:
raise EAException("Error posting to ServiceNow: %s" % e)
elastalert_logger.info("Alert sent to ServiceNow")
def get_info(self):
return {'type': 'ServiceNow',
'self.servicenow_rest_url': self.servicenow_rest_url}
class SimplePostAlerter(Alerter):
def __init__(self, rule):
super(SimplePostAlerter, self).__init__(rule)
simple_webhook_url = self.rule.get('simple_webhook_url')
if isinstance(simple_webhook_url, basestring):
simple_webhook_url = [simple_webhook_url]
self.simple_webhook_url = simple_webhook_url
self.simple_proxy = self.rule.get('simple_proxy')
def alert(self, matches):
payload = {
'rule': self.rule['name'],
'matches': matches
}
headers = {
"Content-Type": "application/json",
"Accept": "application/json;charset=utf-8"
}
proxies = {'https': self.simple_proxy} if self.simple_proxy else None
for url in self.simple_webhook_url:
try:
response = requests.post(url, data=json.dumps(payload, cls=DateTimeEncoder), headers=headers, proxies=proxies)
response.raise_for_status()
except RequestException as e:
raise EAException("Error posting simple alert: %s" % e)
elastalert_logger.info("Simple alert sent")
def get_info(self):
return {'type': 'simple',
'simple_webhook_url': self.simple_webhook_url}<|fim▁end|> | |
<|file_name|>align_return_type.rs<|end_file_name|><|fim▁begin|>fn foo(x: i32, y: String)
-> String {<|fim▁hole|>fn foo(x: i32,
y: String)
-> String {
y + x.to_string()
}
fn foo(
x: i32,
y: String)
-> String {
y + x.to_string()
}
fn foo(
x: i32,
y: String
) -> String {
y + x.to_string()
}
fn foo<T>(t: T)
-> T
where T: Clone { }<|fim▁end|> | y + x.to_string()
}
|
<|file_name|>L2LoginClient.java<|end_file_name|><|fim▁begin|>/*
* 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, 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., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
package l2s.authserver.network.l2;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.interfaces.RSAPrivateKey;
import l2s.authserver.Config;
import l2s.authserver.accounts.Account;
import l2s.authserver.crypt.LoginCrypt;
import l2s.authserver.crypt.ScrambledKeyPair;
import l2s.authserver.network.l2.s2c.AccountKicked;
import l2s.authserver.network.l2.s2c.AccountKicked.AccountKickedReason;
import l2s.authserver.network.l2.s2c.L2LoginServerPacket;
import l2s.authserver.network.l2.s2c.LoginFail;
import l2s.authserver.network.l2.s2c.LoginFail.LoginFailReason;
import l2s.commons.net.nio.impl.MMOClient;
import l2s.commons.net.nio.impl.MMOConnection;<|fim▁hole|>public final class L2LoginClient extends MMOClient<MMOConnection<L2LoginClient>>
{
private final static Logger _log = LoggerFactory.getLogger(L2LoginClient.class);
public static enum LoginClientState
{
CONNECTED,
AUTHED_GG,
AUTHED,
DISCONNECTED
}
private static final int PROTOCOL_VERSION = 0xc621;
private LoginClientState _state;
private LoginCrypt _loginCrypt;
private ScrambledKeyPair _scrambledPair;
private byte[] _blowfishKey;
private String _login;
private SessionKey _skey;
private Account _account;
private String _ipAddr;
private int _sessionId;
private boolean _passwordCorrect;
public L2LoginClient(MMOConnection<L2LoginClient> con)
{
super(con);
_state = LoginClientState.CONNECTED;
_scrambledPair = Config.getScrambledRSAKeyPair();
_blowfishKey = Config.getBlowfishKey();
_loginCrypt = new LoginCrypt();
_loginCrypt.setKey(_blowfishKey);
_sessionId = con.hashCode();
_ipAddr = getConnection().getSocket().getInetAddress().getHostAddress();
_passwordCorrect = false;
}
@Override
public boolean decrypt(ByteBuffer buf, int size)
{
boolean ret;
try
{
ret = _loginCrypt.decrypt(buf.array(), buf.position(), size);
}
catch(IOException e)
{
_log.error("", e);
closeNow(true);
return false;
}
if(!ret)
closeNow(true);
return ret;
}
@Override
public boolean encrypt(ByteBuffer buf, int size)
{
final int offset = buf.position();
try
{
size = _loginCrypt.encrypt(buf.array(), offset, size);
}
catch(IOException e)
{
_log.error("", e);
return false;
}
buf.position(offset + size);
return true;
}
public LoginClientState getState()
{
return _state;
}
public void setState(LoginClientState state)
{
_state = state;
}
public byte[] getBlowfishKey()
{
return _blowfishKey;
}
public byte[] getScrambledModulus()
{
return _scrambledPair.getScrambledModulus();
}
public RSAPrivateKey getRSAPrivateKey()
{
return (RSAPrivateKey) _scrambledPair.getKeyPair().getPrivate();
}
public String getLogin()
{
return _login;
}
public void setLogin(String login)
{
_login = login;
}
public Account getAccount()
{
return _account;
}
public void setAccount(Account account)
{
_account = account;
}
public SessionKey getSessionKey()
{
return _skey;
}
public void setSessionKey(SessionKey skey)
{
_skey = skey;
}
public void setSessionId(int val)
{
_sessionId = val;
}
public int getSessionId()
{
return _sessionId;
}
public void setPasswordCorrect(boolean val)
{
_passwordCorrect = val;
}
public boolean isPasswordCorrect()
{
return _passwordCorrect;
}
public void sendPacket(L2LoginServerPacket lsp)
{
if(isConnected())
getConnection().sendPacket(lsp);
}
public void close(LoginFailReason reason)
{
if(isConnected())
getConnection().close(new LoginFail(reason));
}
public void close(AccountKickedReason reason)
{
if(isConnected())
getConnection().close(new AccountKicked(reason));
}
public void close(L2LoginServerPacket lsp)
{
if(isConnected())
getConnection().close(lsp);
}
@Override
public void onDisconnection()
{
_state = LoginClientState.DISCONNECTED;
_skey = null;
_loginCrypt = null;
_scrambledPair = null;
_blowfishKey = null;
}
@Override
public String toString()
{
switch(_state)
{
case AUTHED:
return "[ Account : " + getLogin() + " IP: " + getIpAddress() + "]";
default:
return "[ State : " + getState() + " IP: " + getIpAddress() + "]";
}
}
public String getIpAddress()
{
return _ipAddr;
}
@Override
protected void onForcedDisconnection()
{
}
public int getProtocol()
{
return PROTOCOL_VERSION;
}
}<|fim▁end|> | import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
|
<|file_name|>script.py<|end_file_name|><|fim▁begin|># Orca
#
# Copyright 2006-2009 Sun Microsystems Inc.
# Copyright 2010 Joanmarie Diggs
#
# 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., Franklin Street, Fifth Floor,
# Boston MA 02110-1301 USA.
__id__ = "$Id$"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright (c) 2005-2009 Sun Microsystems Inc., " \
"Copyright (c) 2010 Joanmarie Diggs"
__license__ = "LGPL"
import pyatspi
import orca.scripts.default as default
import orca.input_event as input_event
import orca.orca as orca
import orca.orca_state as orca_state
from .script_utilities import Utilities
from .speech_generator import SpeechGenerator
from .formatting import Formatting
########################################################################
# #
# The Java script class. #
# #
########################################################################
class Script(default.Script):
def __init__(self, app):
"""Creates a new script for Java applications.
Arguments:
- app: the application to create a script for.
"""
default.Script.__init__(self, app)
# Some objects which issue descendant changed events lack
# STATE_MANAGES_DESCENDANTS. As a result, onSelectionChanged
# doesn't ignore these objects. That in turn causes Orca to
# double-speak some items and/or set the locusOfFocus to a
# parent it shouldn't. See bgo#616582. [[[TODO - JD: remove
# this hack if and when we get a fix for that bug]]]
#
self.lastDescendantChangedSource = None
def getSpeechGenerator(self):
"""Returns the speech generator for this script."""
return SpeechGenerator(self)
def getFormatting(self):
"""Returns the formatting strings for this script."""
return Formatting(self)
def getUtilities(self):
"""Returns the utilites for this script."""
return Utilities(self)
def checkKeyboardEventData(self, keyboardEvent):
"""Checks the data on the keyboard event.
Some toolkits don't fill all the key event fields, and/or fills
them out with unexpected data. This method tries to fill in the
missing fields and validate/standardize the data we've been given.
While any script can override this method, it is expected that
this will only be done at the toolkit script level.
Arguments:
- keyboardEvent: an instance of input_event.KeyboardEvent
"""
default.Script.checkKeyboardEventData(self, keyboardEvent)
if not keyboardEvent.keyval_name:
return
from gi.repository import Gdk
keymap = Gdk.Keymap.get_default()
keyval = Gdk.keyval_from_name(keyboardEvent.keyval_name)
success, entries = keymap.get_entries_for_keyval(keyval)
for entry in entries:
if entry.group == 0:
keyboardEvent.hw_code = entry.keycode
break
# Put the event_string back to what it was prior to the Java
# Atk Wrapper hack which gives us the keyname and not the
# expected and needed printable character for punctuation
# marks.
#
if keyboardEvent.event_string == keyboardEvent.keyval_name \
and len(keyboardEvent.event_string) > 1:
keyval = Gdk.keyval_from_name(keyboardEvent.keyval_name)
if 0 < keyval < 256:
keyboardEvent.event_string = chr(keyval)
def onCaretMoved(self, event):<|fim▁hole|> # back to the beginning. It's a very excitable little widget.
# Luckily, it only issues one value changed event. So, we'll
# ignore caret movement events caused by value changes and
# just process the single value changed event.
#
isSpinBox = self.utilities.hasMatchingHierarchy(
event.source, [pyatspi.ROLE_TEXT,
pyatspi.ROLE_PANEL,
pyatspi.ROLE_SPIN_BUTTON])
if isSpinBox:
eventStr, mods = self.utilities.lastKeyAndModifiers()
if eventStr in ["Up", "Down"] or isinstance(
orca_state.lastInputEvent, input_event.MouseButtonEvent):
return
default.Script.onCaretMoved(self, event)
def onSelectionChanged(self, event):
"""Called when an object's selection changes.
Arguments:
- event: the Event
"""
# Avoid doing this with objects that manage their descendants
# because they'll issue a descendant changed event. (Note: This
# equality check is intentional; utilities.isSameObject() is
# especially thorough with trees and tables, which is not
# performant.
#
if event.source == self.lastDescendantChangedSource:
return
# We treat selected children as the locus of focus. When the
# selection changes in a list we want to update the locus of
# focus. If there is no selection, we default the locus of
# focus to the containing object.
#
if (event.source.getRole() in [pyatspi.ROLE_LIST,
pyatspi.ROLE_PAGE_TAB_LIST,
pyatspi.ROLE_TREE]) \
and event.source.getState().contains(pyatspi.STATE_FOCUSED):
newFocus = event.source
if event.source.childCount:
selection = event.source.querySelection()
if selection.nSelectedChildren > 0:
newFocus = selection.getSelectedChild(0)
orca.setLocusOfFocus(event, newFocus)
else:
default.Script.onSelectionChanged(self, event)
def onFocusedChanged(self, event):
"""Callback for object:state-changed:focused accessibility events."""
if not event.detail1:
return
obj = event.source
role = obj.getRole()
# Accessibility support for menus in Java is badly broken: Missing
# events, missing states, bogus events from other objects, etc.
# Therefore if we get an event, however broken, for menus or their
# their items that suggests they are selected, we'll just cross our
# fingers and hope that's true.
menuRoles = [pyatspi.ROLE_MENU,
pyatspi.ROLE_MENU_BAR,
pyatspi.ROLE_MENU_ITEM,
pyatspi.ROLE_CHECK_MENU_ITEM,
pyatspi.ROLE_RADIO_MENU_ITEM,
pyatspi.ROLE_POPUP_MENU]
if role in menuRoles or obj.parent.getRole() in menuRoles:
orca.setLocusOfFocus(event, obj)
return
try:
focusRole = orca_state.locusOfFocus.getRole()
except:
focusRole = None
if focusRole in menuRoles and role == pyatspi.ROLE_ROOT_PANE:
return
default.Script.onFocusedChanged(self, event)
def onValueChanged(self, event):
"""Called whenever an object's value changes.
Arguments:
- event: the Event
"""
# We'll ignore value changed events for Java's toggle buttons since
# they also send a redundant object:state-changed:checked event.
#
ignoreRoles = [pyatspi.ROLE_TOGGLE_BUTTON,
pyatspi.ROLE_RADIO_BUTTON,
pyatspi.ROLE_CHECK_BOX]
if event.source.getRole() in ignoreRoles:
return
# Java's SpinButtons are the most caret movement happy thing
# I've seen to date. If you Up or Down on the keyboard to
# change the value, they typically emit three caret movement
# events, first to the beginning, then to the end, and then
# back to the beginning. It's a very excitable little widget.
# Luckily, it only issues one value changed event. So, we'll
# ignore caret movement events caused by value changes and
# just process the single value changed event.
#
if event.source.getRole() == pyatspi.ROLE_SPIN_BUTTON:
try:
thisBox = orca_state.locusOfFocus.parent.parent == event.source
except:
thisBox = False
if thisBox:
self._presentTextAtNewCaretPosition(event,
orca_state.locusOfFocus)
return
default.Script.onValueChanged(self, event)
def skipObjectEvent(self, event):
# Accessibility support for menus in Java is badly broken. One problem
# is bogus focus claims following menu-related focus claims. Therefore
# in this particular toolkit, we mustn't skip events for menus.
menuRoles = [pyatspi.ROLE_MENU,
pyatspi.ROLE_MENU_BAR,
pyatspi.ROLE_MENU_ITEM,
pyatspi.ROLE_CHECK_MENU_ITEM,
pyatspi.ROLE_RADIO_MENU_ITEM,
pyatspi.ROLE_POPUP_MENU]
if event.source.getRole() in menuRoles:
return False
return default.Script.skipObjectEvent(self, event)<|fim▁end|> | # Java's SpinButtons are the most caret movement happy thing
# I've seen to date. If you Up or Down on the keyboard to
# change the value, they typically emit three caret movement
# events, first to the beginning, then to the end, and then |
<|file_name|>qtmailwindow.cpp<|end_file_name|><|fim▁begin|>/****************************************************************************
**
** This file is part of the Qtopia Opensource Edition Package.
**
** Copyright (C) 2008 Trolltech ASA.
**
** Contact: Qt Extended Information (info@qtextended.org)
**
** This file may be used under the terms of the GNU General Public License
** versions 2.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file.
**
** Please review the following information to ensure GNU General Public
** Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html.
**
**
****************************************************************************/
#include "qtmailwindow.h"
#include "statusdisplay.h"
#include "writemail.h"
#include <qtopiaipcenvelope.h>
#include <qtopiaapplication.h>
#include <qdatetime.h>
#include <qtimer.h>
#include <QDebug>
#include <QStackedWidget>
QTMailWindow *QTMailWindow::self = 0;
QTMailWindow::QTMailWindow(QWidget *parent, Qt::WFlags fl)
: QMainWindow(parent, fl), noShow(false)
{
qLog(Messaging) << "QTMailWindow ctor begin";
QtopiaApplication::loadTranslations("libqtopiamail");
init();
}
void QTMailWindow::init()
{
self = this;
// Pass in an incorrect parent, a warning
// "QLayout::addChildWidget: EmailClient "client" in wrong parent; "
// "moved to correct parent" will be shown, but this is necessary
// to make the emailClient QMainWindow display.
// This seems to be a QMainWindow in a QStackedWidget bug
emailClient = new EmailClient(this, "client"); // No tr
status = new StatusDisplay;
connect(emailClient, SIGNAL(raiseWidget(QWidget*,QString)),
this, SLOT(raiseWidget(QWidget*,QString)) );
connect(emailClient, SIGNAL(statusVisible(bool)),
status, SLOT(showStatus(bool)) );
connect(emailClient, SIGNAL(updateStatus(QString)),
status, SLOT(displayStatus(QString)) );
connect(emailClient, SIGNAL(updateProgress(uint, uint)),
status, SLOT(displayProgress(uint, uint)) );
connect(emailClient, SIGNAL(clearStatus()),
status, SLOT(clearStatus()) );
views = new QStackedWidget;
views->addWidget(emailClient);
views->setCurrentWidget(emailClient);
QFrame* vbox = new QFrame(this);
vbox->setFrameStyle(QFrame::NoFrame);
QVBoxLayout* vboxLayout = new QVBoxLayout(vbox);
vboxLayout->setContentsMargins( 0, 0, 0, 0 );
vboxLayout->setSpacing( 0 );
vboxLayout->addWidget( views );
vboxLayout->addWidget( status );
setCentralWidget( vbox );
setWindowTitle( emailClient->windowTitle() );
}
QTMailWindow::~QTMailWindow()
{
if (emailClient)
emailClient->cleanExit( true );
qLog(Messaging) << "QTMailWindow dtor end";
}
void QTMailWindow::closeEvent(QCloseEvent *e)
{
if (WriteMail* writeMail = emailClient->mWriteMail) {
if ((views->currentWidget() == writeMail) && (writeMail->hasContent())) {
// We need to save whatever is currently being worked on
writeMail->forcedClosure();
}
}
if (emailClient->isTransmitting()) {
emailClient->closeAfterTransmissionsFinished();
hide();
e->ignore();
} else {
e->accept();
}
}
void QTMailWindow::forceHidden(bool hidden)
{
noShow = hidden;
}
void QTMailWindow::setVisible(bool visible)
{
if (noShow && visible)
return;
QMainWindow::setVisible(visible);
}
void QTMailWindow::setDocument(const QString &_address)
{
emailClient->setDocument(_address);
}
void QTMailWindow::raiseWidget(QWidget *w, const QString &caption)<|fim▁hole|> if (!isVisible())
showMaximized();
views->setCurrentWidget(w);
if (!caption.isEmpty())
setWindowTitle( caption );
raise();
activateWindow();
// needed to work with context-help
setObjectName( w->objectName() );
}
QWidget* QTMailWindow::currentWidget() const
{
return views->currentWidget();
}
QTMailWindow* QTMailWindow::singleton()
{
return self;
}<|fim▁end|> | { |
<|file_name|>core.js<|end_file_name|><|fim▁begin|>var request = require('request');
module.exports = function(args) {
var opts = {
API_URL:'http://en.wikipedia.org/w/api.php',
RATE_LIMIT:false,
RATE_LIMIT_MIN_WAIT:false,
RATE_LIMIT_LAST_CALL:false,
USER_AGENT:'wikipedia (https://github.com/meadowstream/wikipedia.js/)'
};
for (var i in args) {
opts[i] = args[i];
}
return {
// variables
'cache':new Cache(),
// Functions
'opts':opts,
'search':search,
'set_caching':set_caching,
'suggest':suggest,
'page':page,
'geosearch':geosearch,
'languages':languages,
'set_lang':set_lang,
'set_rate_limiting':set_rate_limiting,
'random':random,
// Classes
'WikipediaPage':WikipediaPage
};<|fim▁hole|>};<|fim▁end|> | |
<|file_name|>holdings.py<|end_file_name|><|fim▁begin|>from libraries import JSONDictionary
holdingsData = {
'defense': {
'superiorCastle': 50,
'castle': 40,
'smallCastle': 30,
'hall': 20,
'tower': 10
},
'influence': {
'firstBorn': 20,
'secondBorn': 10,
'otherChildren': 5
},
'lands': {
'terrainCosts': {
'hills': 7,
'mountains': 9,
'plains': 5,
'wetlands': 3
},
'featureCost': {
'population': {
'hamlet': 10,
'smallTown': 20,
'largeTown': 30,
'smallCity': 40,
'largeCity': 50
},
'waterBodies': {
'stream': 1,
'river': 3,
'pond': 5,
'lake': 7
},
'seaAccess': {
'coast': 3,
'island': 10
},
'woods': {
'lightWoods': 3,
'denseWoods': 5
},
'extras': {
'grassland': 1,
'road': 5,
'ruin': 3,
}
},
'realms': {
'dorne': (
'hills',
'mountains',
'plains'
),
'dragonstone': (
'hills',
'plains',
'wetlands'
),
'theIronIslands': (
'hills',
'plains'
),
'kingslanding': (
'plains'
),
'mountainsOfTheMoon': (
'hills',
'mountains'
),
'theNorth': (
'plains',
'hills',
'mountains',
'wetlands'
),
'theReach': (
'plains'
),
'riverlands': (
'hills',
'plains',
'wetlands'
),
'theStormlands': (
'hills',
'mountains',
'plains',
'wetlands'
),
'westernlands': (
'hills',
'mountains',
'plains'
)
}
}
}
class Holdings(object):
defenseHoldings = None
influenceHoldings = None
landTerrains = None
def __init__(self, holdingsDict):
self.defenseHoldings = list()
self.influenceHoldings = list()
self.landTerrains = list()
self.defense = JSONDictionary(holdingsDict).getKeyValue('defense')
self.influence = JSONDictionary(holdingsDict).getKeyValue('influence')
self.lands = JSONDictionary(holdingsDict).getKeyValue('lands')
def generateAllHoldings(self, houseDict, realm):
'''Function to generate all holdings in one process,
takes the house dict generated by the house Stat generator
and the house realm'''
self.generateDefense(houseDict)
self.generateInfluence(houseDict)
self.generateLand(houseDict, realm)
return houseDict
def generateDefense(self, houseDict, *args):
'''Buys defense holdings for the house and returns
the remaining unspend points. Takes a house dictonary to add
items to it and can take a specific defense dictionary
in case you don't want to use the standard one.'''
if len(args) < 1:
defenseDict = self.defense
else:
defenseDict = args[0]
defenseTotal = houseDict['defense']
if defenseTotal > defenseDict['superiorCastle']:
self.defenseHoldings.append('Superior Castle')
defenseTotal -= defenseDict['superiorCastle']
if self.defenseHoldings.count('Superior Castle') > 0:
while defenseTotal > defenseDict['smallCastle']:
self.defenseHoldings.append('Small Castle')
defenseTotal -= defenseDict['smallCastle']
while defenseTotal > defenseDict['hall']:
self.defenseHoldings.append('Hall')
defenseTotal -= defenseDict['hall']
while defenseTotal > defenseDict['tower']:
self.defenseHoldings.append('Tower')
defenseTotal -= defenseDict['tower']
else:
if defenseTotal > defenseDict['castle']:
self.defenseHoldings.append('Castle')
defenseTotal -= defenseDict['castle']
if self.defenseHoldings.count('Castle') > 0:
while defenseTotal > defenseDict['hall']:
self.defenseHoldings.append('Hall')
defenseTotal -= defenseDict['hall']
while defenseTotal > defenseDict['tower']:
self.defenseHoldings.append('Tower')
defenseTotal -= defenseDict['tower']
else:
while defenseTotal > defenseDict['smallCastle']:
self.defenseHoldings.append('Small Castle')
defenseTotal -= defenseDict['smallCastle']
while defenseTotal > defenseDict['hall']:
self.defenseHoldings.append('Hall')
defenseTotal -= defenseDict['hall']
while defenseTotal > defenseDict['tower']:
self.defenseHoldings.append('Tower')
defenseTotal -= defenseDict['tower']
houseDict['defenseHoldings'] = self.defenseHoldings
houseDict['remainingDefense'] = defenseTotal
return houseDict
def generateInfluence(self, houseDict, *args):
if len(args) < 1:
influenceDict = self.influence
else:
influenceDict = args[0]
influenceTotal = houseDict['influence']
if influenceTotal < 11:
houseDict['maxStatus'] = 2
elif influenceTotal < 21:
houseDict['maxStatus'] = 3
elif influenceTotal < 41:
houseDict['maxStatus'] = 4
elif influenceTotal < 51:
houseDict['maxStatus'] = 5
elif influenceTotal < 61:
houseDict['maxStatus'] = 6
elif influenceTotal < 71:
houseDict['maxStatus'] = 7
if influenceTotal < influenceDict['firstBorn']:
houseDict['influenceHoldings'] = self.influenceHoldings
houseDict['remainingInfluence'] = influenceTotal
return houseDict
else:
self.influenceHoldings.append('First Born')
influenceTotal -= influenceDict['firstBorn']
if influenceTotal < influenceDict['secondBorn']:
houseDict['influenceHoldings'] = self.influenceHoldings
houseDict['remainingInfluence'] = influenceTotal
return houseDict
else:
self.influenceHoldings.append('Second Born')<|fim▁hole|> while influenceTotal > influenceDict['otherChildren']:
self.influenceHoldings.append('Other child')
influenceTotal -= influenceDict['otherChildren']
houseDict['influenceHoldings'] = self.influenceHoldings
houseDict['remainingInfluence'] = influenceTotal
return houseDict
def generateLand(self, houseDict, realm, *args):
if len(args) < 1:
terrainsDict = self.lands
else:
terrainsDict = args[0]
print realm
print type(realm)
print JSONDictionary(terrainsDict).getKeyValue(realm)<|fim▁end|> | influenceTotal -= influenceDict['secondBorn'] |
<|file_name|>tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import slopos
class TestTagger(unittest.TestCase):
def setUp(self):
slopos.load_from_path("slopos/sl-tagger.pickle")
def testSentenceTagging(self):
tagged = slopos.tag("To je test.")
self.assertEqual(tagged, [('To', 'ZK-SEI'), ('je', 'GP-STE-N'), ('test', 'SOMETN'), ('.', '-None-')])
def testListTagging(self):
tagged = slopos.tag(["To", "je", "test"])
self.assertEqual(tagged, [('To', 'ZK-SEI'), ('je', 'GP-STE-N'), ('test', 'SOMETN')])
def testUnicodeSentenceTagging(self):
tagged = slopos.tag("V kožuščku zelene lisice stopiclja jezen otrok.")
self.assertEqual(tagged, [('V', 'DM'), ('kožuščku', 'SOMEM'), ('zelene', 'PPNZER'), ('lisice', 'SOZER,'),
('stopiclja', 'GGNSTE'), ('jezen', 'PPNMEIN'), ('otrok', 'SOMEI.'), ('.', '-None-')])<|fim▁hole|><|fim▁end|> |
if __name__ == "__main__":
unittest.main() |
<|file_name|>ProtocolEncoder.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2013 OpenJST Project
*
* 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/>.
*/
package org.openjst.protocols.basic.encoder;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
import org.openjst.commons.io.buffer.DataBufferException;
import org.openjst.commons.security.checksum.CRC16;
import org.openjst.protocols.basic.constants.ProtocolBasicConstants;
import org.openjst.protocols.basic.pdu.PDU;
public class ProtocolEncoder extends OneToOneEncoder {
public static final byte[] RESERVED = new byte[]{0, 0, 0, 0, 0};
@Override<|fim▁hole|> if (msg instanceof PDU) {
return encodePacket((PDU) msg);
} else {
return msg;
}
}
public static ChannelBuffer encodePacket(final PDU packet) throws DataBufferException {
final byte[] msgBody = packet.encode();
final ChannelBuffer buffer = ChannelBuffers.buffer(16 + msgBody.length);
buffer.writeByte(ProtocolBasicConstants.VERSION);
buffer.writeShort(0);
buffer.writeShort(packet.getType());
buffer.writeInt(msgBody.length);
buffer.writeBytes(RESERVED);
buffer.writeShort(CRC16.checksum(msgBody));
if (msgBody.length > 0) {
buffer.writeBytes(msgBody);
}
return buffer;
}
}<|fim▁end|> | protected Object encode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) throws Exception { |
<|file_name|>aliased.rs<|end_file_name|><|fim▁begin|>use backend::Backend;
use expression::{Expression, NonAggregate, SelectableExpression};
use query_builder::*;
use query_builder::nodes::{Identifier, InfixNode};
use query_source::*;
#[derive(Debug, Clone, Copy)]
pub struct Aliased<'a, Expr> {
expr: Expr,
alias: &'a str,
}
impl<'a, Expr> Aliased<'a, Expr> {
pub fn new(expr: Expr, alias: &'a str) -> Self {
Aliased {
expr: expr,
alias: alias,
}
}
}
pub struct FromEverywhere;
impl<'a, T> Expression for Aliased<'a, T> where
T: Expression,
{
type SqlType = T::SqlType;
}
impl<'a, T, DB> QueryFragment<DB> for Aliased<'a, T> where
DB: Backend,
T: QueryFragment<DB>,
{
fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult {
out.push_identifier(&self.alias)
}
}
// FIXME This is incorrect, should only be selectable from WithQuerySource
impl<'a, T, QS> SelectableExpression<QS> for Aliased<'a, T> where
Aliased<'a, T>: Expression,
{
}
impl<'a, T: Expression + Copy> QuerySource for Aliased<'a, T> {
type FromClause = InfixNode<'static, T, Identifier<'a>>;
fn from_clause(&self) -> Self::FromClause {
InfixNode::new(self.expr, Identifier(self.alias), " ")<|fim▁hole|>
impl<'a, T> NonAggregate for Aliased<'a, T> where Aliased<'a, T>: Expression {
}<|fim▁end|> | }
} |
<|file_name|>AnimDownloadProgressButton.java<|end_file_name|><|fim▁begin|>package com.xiaochen.progressroundbutton;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.animation.PathInterpolatorCompat;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by tanfujun on 15/9/4.
*/
public class AnimDownloadProgressButton extends TextView {
private Context mContext;
//背景画笔
private Paint mBackgroundPaint;
//按钮文字画笔
private volatile Paint mTextPaint;
//第一个点画笔
private Paint mDot1Paint;
//第二个点画笔
private Paint mDot2Paint;
//背景颜色
private int[] mBackgroundColor;
private int[] mOriginBackgroundColor;
//下载中后半部分后面背景颜色
private int mBackgroundSecondColor;
//文字颜色
private int mTextColor;
//覆盖后颜色
private int mTextCoverColor;
//文字大小
private float mAboveTextSize = 50;
private float mProgress = -1;
private float mToProgress;
private int mMaxProgress;
private int mMinProgress;
private float mProgressPercent;
private float mButtonRadius;
//两个点向右移动距离
private float mDot1transX;
private float mDot2transX;
private RectF mBackgroundBounds;
private LinearGradient mFillBgGradient;
private LinearGradient mProgressBgGradient;
private LinearGradient mProgressTextGradient;
//点运动动画
private AnimatorSet mDotAnimationSet;
//下载平滑动画
private ValueAnimator mProgressAnimation;
//记录当前文字
private CharSequence mCurrentText;
//普通状态
public static final int NORMAL = 0;
//下载中
public static final int DOWNLOADING = 1;
//有点运动状态
public static final int INSTALLING = 2;
private ButtonController mDefaultController;
private ButtonController mCustomerController;
private int mState;
public AnimDownloadProgressButton(Context context) {
this(context, null);
}
public AnimDownloadProgressButton(Context context, AttributeSet attrs) {
super(context, attrs);
if (!isInEditMode()) {
mContext = context;
initController();
initAttrs(context, attrs);
init();
setupAnimations();
}else {
initController();
}
}
private void initController() {
mDefaultController = new DefaultButtonController();
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
ButtonController buttonController = switchController();
if (buttonController.enablePress()) {
if (mOriginBackgroundColor == null) {
mOriginBackgroundColor = new int[2];
mOriginBackgroundColor[0] = mBackgroundColor[0];
mOriginBackgroundColor[1] = mBackgroundColor[1];
}
if (this.isPressed()) {
int pressColorleft = buttonController.getPressedColor(mBackgroundColor[0]);
int pressColorright = buttonController.getPressedColor(mBackgroundColor[1]);
if (buttonController.enableGradient()) {
initGradientColor(pressColorleft, pressColorright);
} else {
initGradientColor(pressColorleft, pressColorleft);
}
} else {
if (buttonController.enableGradient()) {
initGradientColor(mOriginBackgroundColor[0], mOriginBackgroundColor[1]);
} else {
initGradientColor(mOriginBackgroundColor[0], mOriginBackgroundColor[0]);
}
}
invalidate();
}
}
<|fim▁hole|> //初始化背景颜色数组
initGradientColor(bgColor, bgColor);
mBackgroundSecondColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_backgroud_second_color, Color.LTGRAY);
mButtonRadius = a.getFloat(R.styleable.AnimDownloadProgressButton_progressbtn_radius, getMeasuredHeight() / 2);
mAboveTextSize = a.getFloat(R.styleable.AnimDownloadProgressButton_progressbtn_text_size, 50);
mTextColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_text_color, bgColor);
mTextCoverColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_text_covercolor, Color.WHITE);
boolean enableGradient = a.getBoolean(R.styleable.AnimDownloadProgressButton_progressbtn_enable_gradient, false);
boolean enablePress = a.getBoolean(R.styleable.AnimDownloadProgressButton_progressbtn_enable_press, false);
((DefaultButtonController) mDefaultController).setEnableGradient(enableGradient).setEnablePress(enablePress);
if (enableGradient){
initGradientColor(mDefaultController.getLighterColor(mBackgroundColor[0]),mBackgroundColor[0]);
}
a.recycle();
}
private void init() {
mMaxProgress = 100;
mMinProgress = 0;
mProgress = 0;
//设置背景画笔
mBackgroundPaint = new Paint();
mBackgroundPaint.setAntiAlias(true);
mBackgroundPaint.setStyle(Paint.Style.FILL);
//设置文字画笔
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(mAboveTextSize);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//解决文字有时候画不出问题
setLayerType(LAYER_TYPE_SOFTWARE, mTextPaint);
}
//设置第一个点画笔
mDot1Paint = new Paint();
mDot1Paint.setAntiAlias(true);
mDot1Paint.setTextSize(mAboveTextSize);
//设置第二个点画笔
mDot2Paint = new Paint();
mDot2Paint.setAntiAlias(true);
mDot2Paint.setTextSize(mAboveTextSize);
//初始化状态设为NORMAL
mState = NORMAL;
invalidate();
}
//初始化渐变色
private int[] initGradientColor(int leftColor, int rightColor) {
mBackgroundColor = new int[2];
mBackgroundColor[0] = leftColor;
mBackgroundColor[1] = rightColor;
return mBackgroundColor;
}
private void setupAnimations() {
//两个点向右移动动画
ValueAnimator dotMoveAnimation = ValueAnimator.ofFloat(0, 20);
TimeInterpolator pathInterpolator = PathInterpolatorCompat.create(0.11f, 0f, 0.12f, 1f);
dotMoveAnimation.setInterpolator(pathInterpolator);
dotMoveAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float transX = (float) animation.getAnimatedValue();
mDot1transX = transX;
mDot2transX = transX;
invalidate();
}
});
dotMoveAnimation.setDuration(1243);
dotMoveAnimation.setRepeatMode(ValueAnimator.RESTART);
dotMoveAnimation.setRepeatCount(ValueAnimator.INFINITE);
//两个点渐显渐隐动画
final ValueAnimator dotAlphaAnim = ValueAnimator.ofInt(0, 1243).setDuration(1243);
dotAlphaAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int time = (int) dotAlphaAnim.getAnimatedValue();
int dot1Alpha = calculateDot1AlphaByTime(time);
int dot2Alpha = calculateDot2AlphaByTime(time);
mDot1Paint.setColor(mTextCoverColor);
mDot2Paint.setColor(mTextCoverColor);
mDot1Paint.setAlpha(dot1Alpha);
mDot2Paint.setAlpha(dot2Alpha);
}
});
dotAlphaAnim.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
mDot1Paint.setAlpha(0);
mDot2Paint.setAlpha(0);
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
dotAlphaAnim.setRepeatMode(ValueAnimator.RESTART);
dotAlphaAnim.setRepeatCount(ValueAnimator.INFINITE);
//两个点的动画集合
mDotAnimationSet = new AnimatorSet();
mDotAnimationSet.playTogether(dotAlphaAnim, dotMoveAnimation);
//ProgressBar的动画
mProgressAnimation = ValueAnimator.ofFloat(0, 1).setDuration(500);
mProgressAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float timepercent = (float) animation.getAnimatedValue();
mProgress = ((mToProgress - mProgress) * timepercent + mProgress);
invalidate();
}
});
}
//第一个点透明度计算函数
private int calculateDot2AlphaByTime(int time) {
int alpha;
if (0 <= time && time <= 83) {
double DAlpha = 255.0 / 83.0 * time;
alpha = (int) DAlpha;
} else if (83 < time && time <= 1000) {
alpha = 255;
} else if (1000 < time && time <= 1083) {
double DAlpha = -255.0 / 83.0 * (time - 1083);
alpha = (int) DAlpha;
} else if (1083 < time && time <= 1243) {
alpha = 0;
} else {
alpha = 255;
}
return alpha;
}
//第二个点透明度计算函数
private int calculateDot1AlphaByTime(int time) {
int alpha;
if (0 <= time && time <= 160) {
alpha = 0;
} else if (160 < time && time <= 243) {
double DAlpha = 255.0 / 83.0 * (time - 160);
alpha = (int) DAlpha;
} else if (243 < time && time <= 1160) {
alpha = 255;
} else if (1160 < time && time <= 1243) {
double DAlpha = -255.0 / 83.0 * (time - 1243);
alpha = (int) DAlpha;
} else {
alpha = 255;
}
return alpha;
}
private ValueAnimator createDotAlphaAnimation(int i, Paint mDot1Paint, int i1, int i2, int i3) {
return new ValueAnimator();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!isInEditMode()) {
drawing(canvas);
}
}
private void drawing(Canvas canvas) {
drawBackground(canvas);
drawTextAbove(canvas);
}
private void drawBackground(Canvas canvas) {
mBackgroundBounds = new RectF();
if (mButtonRadius == 0) {
mButtonRadius = getMeasuredHeight() / 2;
}
mBackgroundBounds.left = 2;
mBackgroundBounds.top = 2;
mBackgroundBounds.right = getMeasuredWidth() - 2;
mBackgroundBounds.bottom = getMeasuredHeight() - 2;
ButtonController buttonController = switchController();
//color
switch (mState) {
case NORMAL:
if (buttonController.enableGradient()) {
mFillBgGradient = new LinearGradient(0, getMeasuredHeight() / 2, getMeasuredWidth(), getMeasuredHeight() / 2,
mBackgroundColor,
null,
Shader.TileMode.CLAMP);
mBackgroundPaint.setShader(mFillBgGradient);
} else {
if (mBackgroundPaint.getShader() != null) {
mBackgroundPaint.setShader(null);
}
mBackgroundPaint.setColor(mBackgroundColor[0]);
}
canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint);
break;
case DOWNLOADING:
if (buttonController.enableGradient()) {
mProgressPercent = mProgress / (mMaxProgress + 0f);
int[] colorList = new int[]{mBackgroundColor[0], mBackgroundColor[1], mBackgroundSecondColor};
mProgressBgGradient = new LinearGradient(0, 0, getMeasuredWidth(), 0,
colorList,
new float[]{0, mProgressPercent, mProgressPercent + 0.001f},
Shader.TileMode.CLAMP
);
mBackgroundPaint.setShader(mProgressBgGradient);
} else {
mProgressPercent = mProgress / (mMaxProgress + 0f);
mProgressBgGradient = new LinearGradient(0, 0, getMeasuredWidth(), 0,
new int[]{mBackgroundColor[0], mBackgroundSecondColor},
new float[]{mProgressPercent, mProgressPercent + 0.001f},
Shader.TileMode.CLAMP
);
mBackgroundPaint.setColor(mBackgroundColor[0]);
mBackgroundPaint.setShader(mProgressBgGradient);
}
canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint);
break;
case INSTALLING:
if (buttonController.enableGradient()) {
mFillBgGradient = new LinearGradient(0, getMeasuredHeight() / 2, getMeasuredWidth(), getMeasuredHeight() / 2,
mBackgroundColor,
null,
Shader.TileMode.CLAMP);
mBackgroundPaint.setShader(mFillBgGradient);
} else {
mBackgroundPaint.setShader(null);
mBackgroundPaint.setColor(mBackgroundColor[0]);
}
canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint);
break;
}
}
private void drawTextAbove(Canvas canvas) {
final float y = canvas.getHeight() / 2 - (mTextPaint.descent() / 2 + mTextPaint.ascent() / 2);
if (mCurrentText == null) {
mCurrentText = "";
}
final float textWidth = mTextPaint.measureText(mCurrentText.toString());
//color
switch (mState) {
case NORMAL:
mTextPaint.setShader(null);
mTextPaint.setColor(mTextCoverColor);
canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint);
break;
case DOWNLOADING:
//进度条压过距离
float coverlength = getMeasuredWidth() * mProgressPercent;
//开始渐变指示器
float indicator1 = getMeasuredWidth() / 2 - textWidth / 2;
//结束渐变指示器
float indicator2 = getMeasuredWidth() / 2 + textWidth / 2;
//文字变色部分的距离
float coverTextLength = textWidth / 2 - getMeasuredWidth() / 2 + coverlength;
float textProgress = coverTextLength / textWidth;
if (coverlength <= indicator1) {
mTextPaint.setShader(null);
mTextPaint.setColor(mTextColor);
} else if (indicator1 < coverlength && coverlength <= indicator2) {
mProgressTextGradient = new LinearGradient((getMeasuredWidth() - textWidth) / 2, 0, (getMeasuredWidth() + textWidth) / 2, 0,
new int[]{mTextCoverColor, mTextColor},
new float[]{textProgress, textProgress + 0.001f},
Shader.TileMode.CLAMP);
mTextPaint.setColor(mTextColor);
mTextPaint.setShader(mProgressTextGradient);
} else {
mTextPaint.setShader(null);
mTextPaint.setColor(mTextCoverColor);
}
canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint);
break;
case INSTALLING:
mTextPaint.setColor(mTextCoverColor);
canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint);
canvas.drawCircle((getMeasuredWidth() + textWidth) / 2 + 4 + mDot1transX, y, 4, mDot1Paint);
canvas.drawCircle((getMeasuredWidth() + textWidth) / 2 + 24 + mDot2transX, y, 4, mDot2Paint);
break;
}
}
private ButtonController switchController() {
if (mCustomerController != null) {
return mCustomerController;
} else {
return mDefaultController;
}
}
public int getState() {
return mState;
}
public void setState(int state) {
if (mState != state) {//状态确实有改变
this.mState = state;
invalidate();
if (state == AnimDownloadProgressButton.INSTALLING) {
//开启两个点动画
mDotAnimationSet.start();
} else if (state == NORMAL) {
mDotAnimationSet.cancel();
} else if (state == DOWNLOADING) {
mDotAnimationSet.cancel();
}
}
}
/**
* 设置按钮文字
*/
public void setCurrentText(CharSequence charSequence) {
mCurrentText = charSequence;
invalidate();
}
/**
* 设置带下载进度的文字
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
public void setProgressText(String text, float progress) {
if (progress >= mMinProgress && progress < mMaxProgress) {
mCurrentText = text + getResources().getString(R.string.downloaded, (int) progress);
mToProgress = progress;
if (mProgressAnimation.isRunning()) {
mProgressAnimation.start();
} else {
mProgressAnimation.start();
}
} else if (progress < mMinProgress) {
mProgress = 0;
} else if (progress >= mMaxProgress) {
mProgress = 100;
mCurrentText = text + getResources().getString(R.string.downloaded, (int) mProgress);
invalidate();
}
}
public float getProgress() {
return mProgress;
}
public void setProgress(float progress) {
this.mProgress = progress;
}
/**
* Sometimes you should use the method to avoid memory leak
*/
public void removeAllAnim() {
mDotAnimationSet.cancel();
mDotAnimationSet.removeAllListeners();
mProgressAnimation.cancel();
mProgressAnimation.removeAllListeners();
}
public void setProgressBtnBackgroundColor(int color){
initGradientColor(color, color);
}
public void setProgressBtnBackgroundSecondColor(int color){
mBackgroundSecondColor = color;
}
public float getButtonRadius() {
return mButtonRadius;
}
public void setButtonRadius(float buttonRadius) {
mButtonRadius = buttonRadius;
}
public int getTextColor() {
return mTextColor;
}
@Override
public void setTextColor(int textColor) {
mTextColor = textColor;
}
public int getTextCoverColor() {
return mTextCoverColor;
}
public void setTextCoverColor(int textCoverColor) {
mTextCoverColor = textCoverColor;
}
public int getMinProgress() {
return mMinProgress;
}
public void setMinProgress(int minProgress) {
mMinProgress = minProgress;
}
public int getMaxProgress() {
return mMaxProgress;
}
public void setMaxProgress(int maxProgress) {
mMaxProgress = maxProgress;
}
public void enabelDefaultPress(boolean enable) {
if (mDefaultController != null) {
((DefaultButtonController) mDefaultController).setEnablePress(enable);
}
}
public void enabelDefaultGradient(boolean enable) {
if (mDefaultController != null) {
((DefaultButtonController) mDefaultController).setEnableGradient(enable);
initGradientColor(mDefaultController.getLighterColor(mBackgroundColor[0]),mBackgroundColor[0]);
}
}
@Override
public void setTextSize(float size) {
mAboveTextSize = size;
mTextPaint.setTextSize(size);
}
@Override
public float getTextSize() {
return mAboveTextSize;
}
public AnimDownloadProgressButton setCustomerController(ButtonController customerController) {
mCustomerController = customerController;
return this;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
mState = ss.state;
mProgress = ss.progress;
mCurrentText = ss.currentText;
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
return new SavedState(superState, (int) mProgress, mState, mCurrentText.toString());
}
public static class SavedState extends BaseSavedState {
private int progress;
private int state;
private String currentText;
public SavedState(Parcelable parcel, int progress, int state, String currentText) {
super(parcel);
this.progress = progress;
this.state = state;
this.currentText = currentText;
}
private SavedState(Parcel in) {
super(in);
progress = in.readInt();
state = in.readInt();
currentText = in.readString();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(progress);
out.writeInt(state);
out.writeString(currentText);
}
public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}<|fim▁end|> | private void initAttrs(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AnimDownloadProgressButton);
int bgColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_backgroud_color, Color.parseColor("#6699ff")); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.