file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
variables.py | # Copyright 2015 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.
# ==============================================================================
"""Variable class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import enum # pylint: disable=g-bad-import-order
import functools
import os
import six
from tensorflow.core.framework import attr_value_pb2
from tensorflow.core.framework import variable_pb2
from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import gen_array_ops
from tensorflow.python.ops import gen_state_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.training.checkpointable import base as checkpointable
from tensorflow.python.util import compat
from tensorflow.python.util import tf_should_use
from tensorflow.python.util.deprecation import deprecated
from tensorflow.python.util.tf_export import tf_export
def default_variable_creator(_, **kwds):
del kwds
raise NotImplementedError("variable_scope needs to be imported")
def default_variable_creator_v2(_, **kwds):
del kwds
raise NotImplementedError("variable_scope needs to be imported")
def _make_getter(captured_getter, captured_previous):
"""To avoid capturing loop variables."""
def getter(**kwargs):
return captured_getter(captured_previous, **kwargs)
return getter
def _has_cycle(op, path):
"""Detect cycles in the dependencies of `initial_value`."""
if op.name in path:
return True
path.add(op.name)
for op_input in op.inputs:
if _has_cycle(op_input.op, path):
return True
for op_control_input in op.control_inputs:
if _has_cycle(op_control_input, path):
return True
path.remove(op.name)
return False
@tf_export("VariableSynchronization")
class VariableSynchronization(enum.Enum):
"""Indicates when a distributed variable will be synced.
* `AUTO`: Indicates that the synchronization will be determined by the current
`DistributionStrategy` (eg. With `MirroredStrategy` this would be
`ON_WRITE`).
* `NONE`: Indicates that there will only be one copy of the variable, so
there is no need to sync.
* `ON_WRITE`: Indicates that the variable will be updated across devices
every time it is written.
* `ON_READ`: Indicates that the variable will be aggregated across devices
when it is read (eg. when checkpointing or when evaluating an op that uses
the variable).
"""
AUTO = 0
NONE = 1
ON_WRITE = 2
ON_READ = 3
@tf_export("VariableAggregation", v1=[])
class VariableAggregationV2(enum.Enum):
"""Indicates how a distributed variable will be aggregated.
`tf.contrib.distribute.DistributionStrategy` distributes a model by making
multiple copies (called "replicas") acting data-parallel on different elements
of the input batch. When performing some variable-update operation, say
`var.assign_add(x)`, in a model, we need to resolve how to combine the
different values for `x` computed in the different replicas.
* `NONE`: This is the default, giving an error if you use a
variable-update operation with multiple replicas.
* `SUM`: Add the updates across replicas.
* `MEAN`: Take the arithmetic mean ("average") of the updates across replicas.
* `ONLY_FIRST_REPLICA`: This is for when every replica is performing the same
update, but we only want to perform the update once. Used, e.g., for the
global step counter.
"""
NONE = 0
SUM = 1
MEAN = 2
ONLY_FIRST_REPLICA = 3
@tf_export(v1=["VariableAggregation"])
class VariableAggregation(enum.Enum):
NONE = 0
SUM = 1
MEAN = 2
ONLY_FIRST_REPLICA = 3
ONLY_FIRST_TOWER = 3 # DEPRECATED
VariableAggregation.__doc__ = (
VariableAggregationV2.__doc__ +
"* `ONLY_FIRST_TOWER`: Deprecated alias for `ONLY_FIRST_REPLICA`.\n ")
class VariableMetaclass(type):
"""Metaclass to allow construction of tf.Variable to be overridden."""
def _variable_v1_call(cls,
initial_value=None,
trainable=None,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
variable_def=None,
dtype=None,
expected_shape=None,
import_scope=None,
constraint=None,
use_resource=None,
synchronization=VariableSynchronization.AUTO,
aggregation=VariableAggregation.NONE):
"""Call on Variable class. Useful to force the signature."""
previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs)
for getter in ops.get_default_graph()._variable_creator_stack: # pylint: disable=protected-access
previous_getter = _make_getter(getter, previous_getter)
# Reset `aggregation` that is explicitly set as `None` to the enum NONE.
if aggregation is None:
aggregation = VariableAggregation.NONE
return previous_getter(
initial_value=initial_value,
trainable=trainable,
collections=collections,
validate_shape=validate_shape,
caching_device=caching_device,
name=name,
variable_def=variable_def,
dtype=dtype,
expected_shape=expected_shape,
import_scope=import_scope,
constraint=constraint,
use_resource=use_resource,
synchronization=synchronization,
aggregation=aggregation)
def _variable_v2_call(cls,
initial_value=None,
trainable=None,
validate_shape=True,
caching_device=None,
name=None,
variable_def=None,
dtype=None,
import_scope=None,
constraint=None,
synchronization=VariableSynchronization.AUTO,
aggregation=VariableAggregation.NONE):
"""Call on Variable class. Useful to force the signature."""
previous_getter = lambda **kws: default_variable_creator_v2(None, **kws)
for getter in ops.get_default_graph()._variable_creator_stack: # pylint: disable=protected-access
previous_getter = _make_getter(getter, previous_getter)
# Reset `aggregation` that is explicitly set as `None` to the enum NONE.
if aggregation is None:
aggregation = VariableAggregation.NONE
return previous_getter(
initial_value=initial_value,
trainable=trainable,
validate_shape=validate_shape,
caching_device=caching_device,
name=name,
variable_def=variable_def,
dtype=dtype,
import_scope=import_scope,
constraint=constraint,
synchronization=synchronization,
aggregation=aggregation)
def __call__(cls, *args, **kwargs):
if cls is VariableV1:
return cls._variable_v1_call(*args, **kwargs)
elif cls is Variable:
return cls._variable_v2_call(*args, **kwargs)
else:
return super(VariableMetaclass, cls).__call__(*args, **kwargs)
@tf_export("Variable", v1=[])
class Variable(six.with_metaclass(VariableMetaclass,
checkpointable.CheckpointableBase)):
"""See the [Variables Guide](https://tensorflow.org/guide/variables).
A variable maintains state in the graph across calls to `run()`. You add a
variable to the graph by constructing an instance of the class `Variable`.
The `Variable()` constructor requires an initial value for the variable,
which can be a `Tensor` of any type and shape. The initial value defines the
type and shape of the variable. After construction, the type and shape of
the variable are fixed. The value can be changed using one of the assign
methods.
If you want to change the shape of a variable later you have to use an
`assign` Op with `validate_shape=False`.
Just like any `Tensor`, variables created with `Variable()` can be used as
inputs for other Ops in the graph. Additionally, all the operators
overloaded for the `Tensor` class are carried over to variables, so you can
also add nodes to the graph by just doing arithmetic on variables.
```python
import tensorflow as tf
# Create a variable.
w = tf.Variable(<initial-value>, name=<optional-name>)
# Use the variable in the graph like any Tensor.
y = tf.matmul(w, ...another variable or tensor...)
# The overloaded operators are available too.
z = tf.sigmoid(w + y)
# Assign a new value to the variable with `assign()` or a related method.
w.assign(w + 1.0)
w.assign_add(1.0)
```
When you launch the graph, variables have to be explicitly initialized before
you can run Ops that use their value. You can initialize a variable by
running its *initializer op*, restoring the variable from a save file, or
simply running an `assign` Op that assigns a value to the variable. In fact,
the variable *initializer op* is just an `assign` Op that assigns the
variable's initial value to the variable itself.
```python
# Launch the graph in a session.
with tf.Session() as sess:
# Run the variable initializer.
sess.run(w.initializer)
# ...you now can run ops that use the value of 'w'...
```
The most common initialization pattern is to use the convenience function
`global_variables_initializer()` to add an Op to the graph that initializes
all the variables. You then run that Op after launching the graph.
```python
# Add an Op to initialize global variables.
init_op = tf.global_variables_initializer()
# Launch the graph in a session.
with tf.Session() as sess:
# Run the Op that initializes global variables.
sess.run(init_op)
# ...you can now run any Op that uses variable values...
```
If you need to create a variable with an initial value dependent on another
variable, use the other variable's `initialized_value()`. This ensures that
variables are initialized in the right order.
All variables are automatically collected in the graph where they are
created. By default, the constructor adds the new variable to the graph
collection `GraphKeys.GLOBAL_VARIABLES`. The convenience function
`global_variables()` returns the contents of that collection.
When building a machine learning model it is often convenient to distinguish
between variables holding the trainable model parameters and other variables
such as a `global step` variable used to count training steps. To make this
easier, the variable constructor supports a `trainable=<bool>` parameter. If
`True`, the new variable is also added to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`. The convenience function
`trainable_variables()` returns the contents of this collection. The
various `Optimizer` classes use this collection as the default list of
variables to optimize.
WARNING: tf.Variable objects by default have a non-intuitive memory model. A
Variable is represented internally as a mutable Tensor which can
non-deterministically alias other Tensors in a graph. The set of operations
which consume a Variable and can lead to aliasing is undetermined and can
change across TensorFlow versions. Avoid writing code which relies on the
value of a Variable either changing or not changing as other operations
happen. For example, using Variable objects or simple functions thereof as
predicates in a `tf.cond` is dangerous and error-prone:
```
v = tf.Variable(True)
tf.cond(v, lambda: v.assign(False), my_false_fn) # Note: this is broken.
```
Here replacing adding `use_resource=True` when constructing the variable will
fix any nondeterminism issues:
```
v = tf.Variable(True, use_resource=True)
tf.cond(v, lambda: v.assign(False), my_false_fn)
```
To use the replacement for variables which does
not have these issues:
* Add `use_resource=True` when constructing `tf.Variable`;
* Call `tf.get_variable_scope().set_use_resource(True)` inside a
`tf.variable_scope` before the `tf.get_variable()` call.
"""
def __init__(self,
initial_value=None,
trainable=True,
validate_shape=True,
caching_device=None,
name=None,
variable_def=None,
dtype=None,
import_scope=None,
constraint=None,
synchronization=VariableSynchronization.AUTO,
aggregation=VariableAggregation.NONE):
"""Creates a new variable with value `initial_value`.
The new variable is added to the graph collections listed in `collections`,
which defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
If `trainable` is `True` the variable is also added to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`.
This constructor creates both a `variable` Op and an `assign` Op to set the
variable to its initial value.
Args:
initial_value: A `Tensor`, or Python object convertible to a `Tensor`,
which is the initial value for the Variable. The initial value must have
a shape specified unless `validate_shape` is set to False. Can also be a
callable with no argument that returns the initial value when called. In
that case, `dtype` must be specified. (Note that initializer functions
from init_ops.py must first be bound to a shape before being used here.)
trainable: If `True`, the default, GradientTapes automatically watch uses
of this variable.
validate_shape: If `False`, allows the variable to be initialized with a
value of unknown shape. If `True`, the default, the shape of
`initial_value` must be known.
caching_device: Optional device string describing where the Variable
should be cached for reading. Defaults to the Variable's device.
If not `None`, caches on another device. Typical use is to cache
on the device where the Ops using the Variable reside, to deduplicate
copying through `Switch` and other conditional statements.
name: Optional name for the variable. Defaults to `'Variable'` and gets
uniquified automatically.
variable_def: `VariableDef` protocol buffer. If not `None`, recreates
the Variable object with its contents, referencing the variable's nodes
in the graph, which must already exist. The graph is not changed.
`variable_def` and the other arguments are mutually exclusive.
dtype: If set, initial_value will be converted to the given type.
If `None`, either the datatype will be kept (if `initial_value` is
a Tensor), or `convert_to_tensor` will decide.
import_scope: Optional `string`. Name scope to add to the
`Variable.` Only used when initializing from protocol buffer.
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value
(which must have the same shape). Constraints are not safe to
use when doing asynchronous distributed training.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses
when to synchronize. If `synchronization` is set to `ON_READ`,
`trainable` must not be set to `True`.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
Raises:
ValueError: If both `variable_def` and initial_value are specified.
ValueError: If the initial value is not specified, or does not have a
shape and `validate_shape` is `True`.
RuntimeError: If eager execution is enabled.
"""
raise NotImplementedError
def __repr__(self):
raise NotImplementedError
def value(self):
"""Returns the last snapshot of this variable.
You usually do not need to call this method as all ops that need the value
of the variable call it automatically through a `convert_to_tensor()` call.
Returns a `Tensor` which holds the value of the variable. You can not
assign a new value to this tensor as it is not a reference to the variable.
To avoid copies, if the consumer of the returned value is on the same device
as the variable, this actually returns the live value of the variable, not
a copy. Updates to the variable are seen by the consumer. If the consumer
is on a different device it will get a copy of the variable.
Returns:
A `Tensor` containing the value of the variable.
"""
raise NotImplementedError
def read_value(self):
"""Returns the value of this variable, read in the current context.
Can be different from value() if it's on another device, with control
dependencies, etc.
Returns:
A `Tensor` containing the value of the variable.
"""
raise NotImplementedError
def set_shape(self, shape):
"""Overrides the shape for this variable.
Args:
shape: the `TensorShape` representing the overridden shape.
"""
raise NotImplementedError
@property
def trainable(self):
raise NotImplementedError
def eval(self, session=None):
"""In a session, computes and returns the value of this variable.
This is not a graph construction method, it does not add ops to the graph.
This convenience method requires a session where the graph
containing this variable has been launched. If no session is
passed, the default session is used. See `tf.Session` for more
information on launching a graph and on sessions.
```python
v = tf.Variable([1, 2])
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# Usage passing the session explicitly.
print(v.eval(sess))
# Usage with the default session. The 'with' block
# above makes 'sess' the default session.
print(v.eval())
```
Args:
session: The session to use to evaluate this variable. If
none, the default session is used.
Returns:
A numpy `ndarray` with a copy of the value of this variable.
"""
raise NotImplementedError
def initialized_value(self):
"""Returns the value of the initialized variable.
You should use this instead of the variable itself to initialize another
variable with a value that depends on the value of this variable.
```python
# Initialize 'v' with a random tensor.
v = tf.Variable(tf.truncated_normal([10, 40]))
# Use `initialized_value` to guarantee that `v` has been
# initialized before its value is used to initialize `w`.
# The random values are picked only once.
w = tf.Variable(v.initialized_value() * 2.0)
```
Returns:
A `Tensor` holding the value of this variable after its initializer
has run.
"""
raise NotImplementedError
@property
def initial_value(self):
"""Returns the Tensor used as the initial value for the variable.
Note that this is different from `initialized_value()` which runs
the op that initializes the variable before returning its value.
This method returns the tensor that is used by the op that initializes
the variable.
Returns:
A `Tensor`.
"""
raise NotImplementedError
@property
def constraint(self):
"""Returns the constraint function associated with this variable.
Returns:
The constraint function that was passed to the variable constructor.
Can be `None` if no constraint was passed.
"""
raise NotImplementedError
def assign(self, value, use_locking=False, name=None, read_value=True):
"""Assigns a new value to the variable.
This is essentially a shortcut for `assign(self, value)`.
Args:
value: A `Tensor`. The new value for this variable.
use_locking: If `True`, use locking during the assignment.
name: The name of the operation to be created
read_value: if True, will return something which evaluates to the
new value of the variable; if False will return the assign op.
Returns:
A `Tensor` that will hold the new value of this variable after
the assignment has completed.
"""
raise NotImplementedError
def assign_add(self, delta, use_locking=False, name=None, read_value=True):
"""Adds a value to this variable.
This is essentially a shortcut for `assign_add(self, delta)`.
Args:
delta: A `Tensor`. The value to add to this variable.
use_locking: If `True`, use locking during the operation.
name: The name of the operation to be created
read_value: if True, will return something which evaluates to the
new value of the variable; if False will return the assign op.
Returns:
A `Tensor` that will hold the new value of this variable after
the addition has completed.
"""
raise NotImplementedError
def assign_sub(self, delta, use_locking=False, name=None, read_value=True):
"""Subtracts a value from this variable.
This is essentially a shortcut for `assign_sub(self, delta)`.
Args:
delta: A `Tensor`. The value to subtract from this variable.
use_locking: If `True`, use locking during the operation.
name: The name of the operation to be created
read_value: if True, will return something which evaluates to the
new value of the variable; if False will return the assign op.
Returns:
A `Tensor` that will hold the new value of this variable after
the subtraction has completed.
"""
raise NotImplementedError
def scatter_sub(self, sparse_delta, use_locking=False, name=None):
"""Subtracts `IndexedSlices` from this variable.
Args:
sparse_delta: `IndexedSlices` to be subtracted from this variable.
use_locking: If `True`, use locking during the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered subtraction has completed.
Raises:
ValueError: if `sparse_delta` is not an `IndexedSlices`.
"""
raise NotImplementedError
def scatter_add(self, sparse_delta, use_locking=False, name=None):
"""Adds `IndexedSlices` to this variable.
Args:
sparse_delta: `IndexedSlices` to be assigned to this variable.
use_locking: If `True`, use locking during the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered subtraction has completed.
Raises:
ValueError: if `sparse_delta` is not an `IndexedSlices`.
"""
raise NotImplementedError
def scatter_update(self, sparse_delta, use_locking=False, name=None):
"""Assigns `IndexedSlices` to this variable.
Args:
sparse_delta: `IndexedSlices` to be assigned to this variable.
use_locking: If `True`, use locking during the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered subtraction has completed.
Raises:
ValueError: if `sparse_delta` is not an `IndexedSlices`.
"""
raise NotImplementedError
def scatter_nd_sub(self, indices, updates, name=None):
"""Applies sparse subtraction to individual values or slices in a Variable.
`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.
`indices` must be integer tensor, containing indices into `ref`.
It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.
The innermost dimension of `indices` (with length `K`) corresponds to
indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th
dimension of `ref`.
`updates` is `Tensor` of rank `Q-1+P-K` with shape:
```
[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].
```
For example, say we want to add 4 scattered elements to a rank-1 tensor to
8 elements. In Python, that update would look like this:
```python
ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1] ,[7]])
updates = tf.constant([9, 10, 11, 12])
op = ref.scatter_nd_sub(indices, updates)
with tf.Session() as sess:
print sess.run(op)
```
The resulting update to ref would look like this:
[1, -9, 3, -6, -6, 6, 7, -4]
See `tf.scatter_nd` for more details about how to make updates to
slices.
Args: | updates: The values to be used in the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered subtraction has completed.
Raises:
ValueError: if `sparse_delta` is not an `IndexedSlices`.
"""
raise NotImplementedError
def scatter_nd_add(self, indices, updates, name=None):
"""Applies sparse addition to individual values or slices in a Variable.
`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.
`indices` must be integer tensor, containing indices into `ref`.
It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.
The innermost dimension of `indices` (with length `K`) corresponds to
indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th
dimension of `ref`.
`updates` is `Tensor` of rank `Q-1+P-K` with shape:
```
[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].
```
For example, say we want to add 4 scattered elements to a rank-1 tensor to
8 elements. In Python, that update would look like this:
```python
ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1] ,[7]])
updates = tf.constant([9, 10, 11, 12])
add = ref.scatter_nd_add(indices, updates)
with tf.Session() as sess:
print sess.run(add)
```
The resulting update to ref would look like this:
[1, 13, 3, 14, 14, 6, 7, 20]
See `tf.scatter_nd` for more details about how to make updates to
slices.
Args:
indices: The indices to be used in the operation.
updates: The values to be used in the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered subtraction has completed.
Raises:
ValueError: if `sparse_delta` is not an `IndexedSlices`.
"""
raise NotImplementedError
def scatter_nd_update(self, indices, updates, name=None):
"""Applies sparse assignment to individual values or slices in a Variable.
`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.
`indices` must be integer tensor, containing indices into `ref`.
It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.
The innermost dimension of `indices` (with length `K`) corresponds to
indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th
dimension of `ref`.
`updates` is `Tensor` of rank `Q-1+P-K` with shape:
```
[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].
```
For example, say we want to add 4 scattered elements to a rank-1 tensor to
8 elements. In Python, that update would look like this:
```python
ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1] ,[7]])
updates = tf.constant([9, 10, 11, 12])
op = ref.scatter_nd_assign(indices, updates)
with tf.Session() as sess:
print sess.run(op)
```
The resulting update to ref would look like this:
[1, 11, 3, 10, 9, 6, 7, 12]
See `tf.scatter_nd` for more details about how to make updates to
slices.
Args:
indices: The indices to be used in the operation.
updates: The values to be used in the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered subtraction has completed.
Raises:
ValueError: if `sparse_delta` is not an `IndexedSlices`.
"""
raise NotImplementedError
def count_up_to(self, limit):
"""Increments this variable until it reaches `limit`.
When that Op is run it tries to increment the variable by `1`. If
incrementing the variable would bring it above `limit` then the Op raises
the exception `OutOfRangeError`.
If no error is raised, the Op outputs the value of the variable before
the increment.
This is essentially a shortcut for `count_up_to(self, limit)`.
Args:
limit: value at which incrementing the variable raises an error.
Returns:
A `Tensor` that will hold the variable value before the increment. If no
other Op modifies this variable, the values produced will all be
distinct.
"""
raise NotImplementedError
def load(self, value, session=None):
"""Load new value into this variable.
Writes new value to variable's memory. Doesn't add ops to the graph.
This convenience method requires a session where the graph
containing this variable has been launched. If no session is
passed, the default session is used. See `tf.Session` for more
information on launching a graph and on sessions.
```python
v = tf.Variable([1, 2])
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# Usage passing the session explicitly.
v.load([2, 3], sess)
print(v.eval(sess)) # prints [2 3]
# Usage with the default session. The 'with' block
# above makes 'sess' the default session.
v.load([3, 4], sess)
print(v.eval()) # prints [3 4]
```
Args:
value: New variable value
session: The session to use to evaluate this variable. If
none, the default session is used.
Raises:
ValueError: Session is not passed and no default session
"""
raise NotImplementedError
# Conversion to tensor.
@staticmethod
def _TensorConversionFunction(v, dtype=None, name=None, as_ref=False): # pylint: disable=invalid-name
"""Utility function for converting a Variable to a Tensor."""
_ = name
if dtype and not dtype.is_compatible_with(v.dtype):
raise ValueError(
"Incompatible type conversion requested to type '%s' for variable "
"of type '%s'" % (dtype.name, v.dtype.name))
if as_ref:
return v._ref() # pylint: disable=protected-access
else:
return v.value()
@classmethod
def _OverloadAllOperators(cls): # pylint: disable=invalid-name
"""Register overloads for all operators."""
for operator in ops.Tensor.OVERLOADABLE_OPERATORS:
cls._OverloadOperator(operator)
# For slicing, bind getitem differently than a tensor (use SliceHelperVar
# instead)
# pylint: disable=protected-access
setattr(cls, "__getitem__", array_ops._SliceHelperVar)
@classmethod
def _OverloadOperator(cls, operator): # pylint: disable=invalid-name
"""Defer an operator overload to `ops.Tensor`.
We pull the operator out of ops.Tensor dynamically to avoid ordering issues.
Args:
operator: string. The operator name.
"""
tensor_oper = getattr(ops.Tensor, operator)
def _run_op(a, *args, **kwargs):
# pylint: disable=protected-access
return tensor_oper(a._AsTensor(), *args, **kwargs)
functools.update_wrapper(_run_op, tensor_oper)
setattr(cls, operator, _run_op)
def __iter__(self):
"""Dummy method to prevent iteration. Do not call.
NOTE(mrry): If we register __getitem__ as an overloaded operator,
Python will valiantly attempt to iterate over the variable's Tensor from 0
to infinity. Declaring this method prevents this unintended behavior.
Raises:
TypeError: when invoked.
"""
raise TypeError("'Variable' object is not iterable.")
# NOTE(mrry): This enables the Variable's overloaded "right" binary
# operators to run when the left operand is an ndarray, because it
# accords the Variable class higher priority than an ndarray, or a
# numpy matrix.
# TODO(mrry): Convert this to using numpy's __numpy_ufunc__
# mechanism, which allows more control over how Variables interact
# with ndarrays.
__array_priority__ = 100
@property
def name(self):
"""The name of this variable."""
raise NotImplementedError
@property
def initializer(self):
"""The initializer operation for this variable."""
raise NotImplementedError
@property
def device(self):
"""The device of this variable."""
raise NotImplementedError
@property
def dtype(self):
"""The `DType` of this variable."""
raise NotImplementedError
@property
def op(self):
"""The `Operation` of this variable."""
raise NotImplementedError
@property
def graph(self):
"""The `Graph` of this variable."""
raise NotImplementedError
@property
def shape(self):
"""The `TensorShape` of this variable.
Returns:
A `TensorShape`.
"""
raise NotImplementedError
def get_shape(self):
"""Alias of Variable.shape."""
raise NotImplementedError
def to_proto(self, export_scope=None):
"""Converts a `Variable` to a `VariableDef` protocol buffer.
Args:
export_scope: Optional `string`. Name scope to remove.
Returns:
A `VariableDef` protocol buffer, or `None` if the `Variable` is not
in the specified name scope.
"""
raise NotImplementedError
@staticmethod
def from_proto(variable_def, import_scope=None):
"""Returns a `Variable` object created from `variable_def`."""
return RefVariable(variable_def=variable_def,
import_scope=import_scope)
class SaveSliceInfo(object):
"""Information on how to save this Variable as a slice.
Provides internal support for saving variables as slices of a larger
variable. This API is not public and is subject to change.
Available properties:
* full_name
* full_shape
* var_offset
* var_shape
"""
def __init__(self,
full_name=None,
full_shape=None,
var_offset=None,
var_shape=None,
save_slice_info_def=None,
import_scope=None):
"""Create a `SaveSliceInfo`.
Args:
full_name: Name of the full variable of which this `Variable` is a
slice.
full_shape: Shape of the full variable, as a list of int.
var_offset: Offset of this `Variable` into the full variable, as a
list of int.
var_shape: Shape of this `Variable`, as a list of int.
save_slice_info_def: `SaveSliceInfoDef` protocol buffer. If not `None`,
recreates the SaveSliceInfo object its contents.
`save_slice_info_def` and other arguments are mutually
exclusive.
import_scope: Optional `string`. Name scope to add. Only used
when initializing from protocol buffer.
"""
if save_slice_info_def:
assert isinstance(save_slice_info_def, variable_pb2.SaveSliceInfoDef)
self.full_name = ops.prepend_name_scope(
save_slice_info_def.full_name, import_scope=import_scope)
self.full_shape = [i for i in save_slice_info_def.full_shape]
self.var_offset = [i for i in save_slice_info_def.var_offset]
self.var_shape = [i for i in save_slice_info_def.var_shape]
else:
self.full_name = full_name
self.full_shape = full_shape
self.var_offset = var_offset
self.var_shape = var_shape
@property
def spec(self):
"""Computes the spec string used for saving."""
full_shape_str = " ".join(["%d" % d for d in self.full_shape]) + " "
sl_spec = ":".join([
"%d,%d" % (o, s) for o, s in zip(self.var_offset, self.var_shape)
])
return full_shape_str + sl_spec
def to_proto(self, export_scope=None):
"""Returns a SaveSliceInfoDef() proto.
Args:
export_scope: Optional `string`. Name scope to remove.
Returns:
A `SaveSliceInfoDef` protocol buffer, or None if the `Variable` is not
in the specified name scope.
"""
if (export_scope is None or
self.full_name.startswith(export_scope)):
save_slice_info_def = variable_pb2.SaveSliceInfoDef()
save_slice_info_def.full_name = ops.strip_name_scope(
self.full_name, export_scope)
for i in self.full_shape:
save_slice_info_def.full_shape.append(i)
for i in self.var_offset:
save_slice_info_def.var_offset.append(i)
for i in self.var_shape:
save_slice_info_def.var_shape.append(i)
return save_slice_info_def
else:
return None
def __iadd__(self, other):
raise NotImplementedError
def __isub__(self, other):
raise NotImplementedError
def __imul__(self, other):
raise NotImplementedError
def __idiv__(self, other):
raise NotImplementedError
def __itruediv__(self, other):
raise NotImplementedError
def __irealdiv__(self, other):
raise NotImplementedError
def __ipow__(self, other):
raise NotImplementedError
@tf_export(v1=["Variable"])
class VariableV1(Variable):
"""See the [Variables Guide](https://tensorflow.org/guide/variables).
A variable maintains state in the graph across calls to `run()`. You add a
variable to the graph by constructing an instance of the class `Variable`.
The `Variable()` constructor requires an initial value for the variable,
which can be a `Tensor` of any type and shape. The initial value defines the
type and shape of the variable. After construction, the type and shape of
the variable are fixed. The value can be changed using one of the assign
methods.
If you want to change the shape of a variable later you have to use an
`assign` Op with `validate_shape=False`.
Just like any `Tensor`, variables created with `Variable()` can be used as
inputs for other Ops in the graph. Additionally, all the operators
overloaded for the `Tensor` class are carried over to variables, so you can
also add nodes to the graph by just doing arithmetic on variables.
```python
import tensorflow as tf
# Create a variable.
w = tf.Variable(<initial-value>, name=<optional-name>)
# Use the variable in the graph like any Tensor.
y = tf.matmul(w, ...another variable or tensor...)
# The overloaded operators are available too.
z = tf.sigmoid(w + y)
# Assign a new value to the variable with `assign()` or a related method.
w.assign(w + 1.0)
w.assign_add(1.0)
```
When you launch the graph, variables have to be explicitly initialized before
you can run Ops that use their value. You can initialize a variable by
running its *initializer op*, restoring the variable from a save file, or
simply running an `assign` Op that assigns a value to the variable. In fact,
the variable *initializer op* is just an `assign` Op that assigns the
variable's initial value to the variable itself.
```python
# Launch the graph in a session.
with tf.Session() as sess:
# Run the variable initializer.
sess.run(w.initializer)
# ...you now can run ops that use the value of 'w'...
```
The most common initialization pattern is to use the convenience function
`global_variables_initializer()` to add an Op to the graph that initializes
all the variables. You then run that Op after launching the graph.
```python
# Add an Op to initialize global variables.
init_op = tf.global_variables_initializer()
# Launch the graph in a session.
with tf.Session() as sess:
# Run the Op that initializes global variables.
sess.run(init_op)
# ...you can now run any Op that uses variable values...
```
If you need to create a variable with an initial value dependent on another
variable, use the other variable's `initialized_value()`. This ensures that
variables are initialized in the right order.
All variables are automatically collected in the graph where they are
created. By default, the constructor adds the new variable to the graph
collection `GraphKeys.GLOBAL_VARIABLES`. The convenience function
`global_variables()` returns the contents of that collection.
When building a machine learning model it is often convenient to distinguish
between variables holding the trainable model parameters and other variables
such as a `global step` variable used to count training steps. To make this
easier, the variable constructor supports a `trainable=<bool>` parameter. If
`True`, the new variable is also added to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`. The convenience function
`trainable_variables()` returns the contents of this collection. The
various `Optimizer` classes use this collection as the default list of
variables to optimize.
WARNING: tf.Variable objects by default have a non-intuitive memory model. A
Variable is represented internally as a mutable Tensor which can
non-deterministically alias other Tensors in a graph. The set of operations
which consume a Variable and can lead to aliasing is undetermined and can
change across TensorFlow versions. Avoid writing code which relies on the
value of a Variable either changing or not changing as other operations
happen. For example, using Variable objects or simple functions thereof as
predicates in a `tf.cond` is dangerous and error-prone:
```
v = tf.Variable(True)
tf.cond(v, lambda: v.assign(False), my_false_fn) # Note: this is broken.
```
Here replacing adding `use_resource=True` when constructing the variable will
fix any nondeterminism issues:
```
v = tf.Variable(True, use_resource=True)
tf.cond(v, lambda: v.assign(False), my_false_fn)
```
To use the replacement for variables which does
not have these issues:
* Add `use_resource=True` when constructing `tf.Variable`;
* Call `tf.get_variable_scope().set_use_resource(True)` inside a
`tf.variable_scope` before the `tf.get_variable()` call.
"""
def __init__(self, # pylint: disable=super-init-not-called
initial_value=None,
trainable=True,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
variable_def=None,
dtype=None,
expected_shape=None,
import_scope=None,
constraint=None,
use_resource=None,
synchronization=VariableSynchronization.AUTO,
aggregation=VariableAggregation.NONE):
"""Creates a new variable with value `initial_value`.
The new variable is added to the graph collections listed in `collections`,
which defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
If `trainable` is `True` the variable is also added to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`.
This constructor creates both a `variable` Op and an `assign` Op to set the
variable to its initial value.
Args:
initial_value: A `Tensor`, or Python object convertible to a `Tensor`,
which is the initial value for the Variable. The initial value must have
a shape specified unless `validate_shape` is set to False. Can also be a
callable with no argument that returns the initial value when called. In
that case, `dtype` must be specified. (Note that initializer functions
from init_ops.py must first be bound to a shape before being used here.)
trainable: If `True`, the default, also adds the variable to the graph
collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as
the default list of variables to use by the `Optimizer` classes.
collections: List of graph collections keys. The new variable is added to
these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
validate_shape: If `False`, allows the variable to be initialized with a
value of unknown shape. If `True`, the default, the shape of
`initial_value` must be known.
caching_device: Optional device string describing where the Variable
should be cached for reading. Defaults to the Variable's device.
If not `None`, caches on another device. Typical use is to cache
on the device where the Ops using the Variable reside, to deduplicate
copying through `Switch` and other conditional statements.
name: Optional name for the variable. Defaults to `'Variable'` and gets
uniquified automatically.
variable_def: `VariableDef` protocol buffer. If not `None`, recreates
the Variable object with its contents, referencing the variable's nodes
in the graph, which must already exist. The graph is not changed.
`variable_def` and the other arguments are mutually exclusive.
dtype: If set, initial_value will be converted to the given type.
If `None`, either the datatype will be kept (if `initial_value` is
a Tensor), or `convert_to_tensor` will decide.
expected_shape: A TensorShape. If set, initial_value is expected
to have this shape.
import_scope: Optional `string`. Name scope to add to the
`Variable.` Only used when initializing from protocol buffer.
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value
(which must have the same shape). Constraints are not safe to
use when doing asynchronous distributed training.
use_resource: whether to use resource variables.
synchronization: unused
aggregation: unused
Raises:
ValueError: If both `variable_def` and initial_value are specified.
ValueError: If the initial value is not specified, or does not have a
shape and `validate_shape` is `True`.
RuntimeError: If eager execution is enabled.
"""
SaveSliceInfo = Variable.SaveSliceInfo
# TODO(apassos): do not repeat all comments here
class RefVariable(VariableV1):
"""Ref-based implementation of variables."""
def __init__(self, # pylint: disable=super-init-not-called
initial_value=None,
trainable=True,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
variable_def=None,
dtype=None,
expected_shape=None,
import_scope=None,
constraint=None):
"""Creates a new variable with value `initial_value`.
The new variable is added to the graph collections listed in `collections`,
which defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
If `trainable` is `True` the variable is also added to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`.
This constructor creates both a `variable` Op and an `assign` Op to set the
variable to its initial value.
Args:
initial_value: A `Tensor`, or Python object convertible to a `Tensor`,
which is the initial value for the Variable. The initial value must have
a shape specified unless `validate_shape` is set to False. Can also be a
callable with no argument that returns the initial value when called. In
that case, `dtype` must be specified. (Note that initializer functions
from init_ops.py must first be bound to a shape before being used here.)
trainable: If `True`, the default, also adds the variable to the graph
collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as
the default list of variables to use by the `Optimizer` classes.
collections: List of graph collections keys. The new variable is added to
these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
validate_shape: If `False`, allows the variable to be initialized with a
value of unknown shape. If `True`, the default, the shape of
`initial_value` must be known.
caching_device: Optional device string describing where the Variable
should be cached for reading. Defaults to the Variable's device.
If not `None`, caches on another device. Typical use is to cache
on the device where the Ops using the Variable reside, to deduplicate
copying through `Switch` and other conditional statements.
name: Optional name for the variable. Defaults to `'Variable'` and gets
uniquified automatically.
variable_def: `VariableDef` protocol buffer. If not `None`, recreates
the Variable object with its contents, referencing the variable's nodes
in the graph, which must already exist. The graph is not changed.
`variable_def` and the other arguments are mutually exclusive.
dtype: If set, initial_value will be converted to the given type.
If `None`, either the datatype will be kept (if `initial_value` is
a Tensor), or `convert_to_tensor` will decide.
expected_shape: A TensorShape. If set, initial_value is expected
to have this shape.
import_scope: Optional `string`. Name scope to add to the
`Variable.` Only used when initializing from protocol buffer.
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value
(which must have the same shape). Constraints are not safe to
use when doing asynchronous distributed training.
Raises:
ValueError: If both `variable_def` and initial_value are specified.
ValueError: If the initial value is not specified, or does not have a
shape and `validate_shape` is `True`.
RuntimeError: If eager execution is enabled.
"""
self._in_graph_mode = True
if variable_def:
# If variable_def is provided, recreates the variable from its fields.
if initial_value:
raise ValueError("variable_def and initial_value are mutually "
"exclusive.")
self._init_from_proto(variable_def, import_scope=import_scope)
else:
# Create from initial_value.
self._init_from_args(
initial_value=initial_value,
trainable=trainable,
collections=collections,
validate_shape=validate_shape,
caching_device=caching_device,
name=name,
dtype=dtype,
expected_shape=expected_shape,
constraint=constraint)
def __repr__(self):
if context.executing_eagerly() and not self._in_graph_mode:
return "<tf.Variable '%s' shape=%s dtype=%s, numpy=%s>" % (
self.name, self.get_shape(), self.dtype.name,
ops.numpy_text(self.read_value(), is_repr=True))
else:
return "<tf.Variable '%s' shape=%s dtype=%s>" % (
self.name, self.get_shape(), self.dtype.name)
def _init_from_args(self,
initial_value=None,
trainable=True,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
dtype=None,
expected_shape=None,
constraint=None):
"""Creates a new variable from arguments.
Args:
initial_value: A `Tensor`, or Python object convertible to a `Tensor`,
which is the initial value for the Variable. The initial value must have
a shape specified unless `validate_shape` is set to False. Can also be a
callable with no argument that returns the initial value when called.
(Note that initializer functions from init_ops.py must first be bound
to a shape before being used here.)
trainable: If `True`, the default, also adds the variable to the graph
collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as
the default list of variables to use by the `Optimizer` classes.
collections: List of graph collections keys. The new variable is added to
these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
validate_shape: If `False`, allows the variable to be initialized with a
value of unknown shape. If `True`, the default, the shape of
`initial_value` must be known.
caching_device: Optional device string or function describing where the
Variable should be cached for reading. Defaults to the Variable's
device. If not `None`, caches on another device. Typical use is to
cache on the device where the Ops using the Variable reside, to
deduplicate copying through `Switch` and other conditional statements.
name: Optional name for the variable. Defaults to `'Variable'` and gets
uniquified automatically.
dtype: If set, initial_value will be converted to the given type.
If None, either the datatype will be kept (if initial_value is
a Tensor) or float32 will be used (if it is a Python object convertible
to a Tensor).
expected_shape: Deprecated. Ignored.
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value
(which must have the same shape). Constraints are not safe to
use when doing asynchronous distributed training.
Raises:
ValueError: If the initial value is not specified, or does not have a
shape and `validate_shape` is `True`.
RuntimeError: If lifted into the eager context.
"""
_ = expected_shape
if initial_value is None:
raise ValueError("initial_value must be specified.")
init_from_fn = callable(initial_value)
if collections is None:
collections = [ops.GraphKeys.GLOBAL_VARIABLES]
if not isinstance(collections, (list, tuple, set)):
raise ValueError(
"collections argument to Variable constructor must be a list, tuple, "
"or set. Got %s of type %s" % (collections, type(collections)))
if constraint is not None and not callable(constraint):
raise ValueError("The `constraint` argument must be a callable.")
# Store the graph key so optimizers know how to only retrieve variables from
# this graph.
self._graph_key = ops.get_default_graph()._graph_key # pylint: disable=protected-access
if isinstance(initial_value, checkpointable.CheckpointInitialValue):
self._maybe_initialize_checkpointable()
self._update_uid = initial_value.checkpoint_position.restore_uid
initial_value = initial_value.wrapped_value
self._trainable = trainable
if trainable and ops.GraphKeys.TRAINABLE_VARIABLES not in collections:
collections = list(collections) + [ops.GraphKeys.TRAINABLE_VARIABLES]
with ops.init_scope():
# Ensure that we weren't lifted into the eager context.
if context.executing_eagerly():
raise RuntimeError(
"RefVariable not supported when eager execution is enabled. ")
with ops.name_scope(name, "Variable", [] if init_from_fn else
[initial_value]) as name:
if init_from_fn:
# Use attr_scope and device(None) to simulate the behavior of
# colocate_with when the variable we want to colocate with doesn't
# yet exist.
true_name = ops._name_from_scope_name(name) # pylint: disable=protected-access
attr = attr_value_pb2.AttrValue(
list=attr_value_pb2.AttrValue.ListValue(
s=[compat.as_bytes("loc:@%s" % true_name)]))
# pylint: disable=protected-access
with ops.get_default_graph()._attr_scope({"_class": attr}):
with ops.name_scope("Initializer"), ops.device(None):
self._initial_value = ops.convert_to_tensor(
initial_value(), name="initial_value", dtype=dtype)
shape = (self._initial_value.get_shape()
if validate_shape else tensor_shape.unknown_shape())
self._variable = state_ops.variable_op_v2(
shape,
self._initial_value.dtype.base_dtype,
name=name)
# pylint: enable=protected-access
# Or get the initial value from a Tensor or Python object.
else:
self._initial_value = ops.convert_to_tensor(
initial_value, name="initial_value", dtype=dtype)
# pylint: disable=protected-access
if self._initial_value.op._get_control_flow_context() is not None:
raise ValueError(
"Initializer for variable %s is from inside a control-flow "
"construct, such as a loop or conditional. When creating a "
"variable inside a loop or conditional, use a lambda as the "
"initializer." % name)
# pylint: enable=protected-access
shape = (self._initial_value.get_shape()
if validate_shape else tensor_shape.unknown_shape())
# In this case, the variable op can't be created until after the
# initial_value has been converted to a Tensor with a known type.
self._variable = state_ops.variable_op_v2(
shape,
self._initial_value.dtype.base_dtype,
name=name)
# Manually overrides the variable's shape with the initial value's.
if validate_shape:
initial_value_shape = self._initial_value.get_shape()
if not initial_value_shape.is_fully_defined():
raise ValueError("initial_value must have a shape specified: %s" %
self._initial_value)
# If 'initial_value' makes use of other variables, make sure we don't
# have an issue if these other variables aren't initialized first by
# using their initialized_value() method.
self._initializer_op = state_ops.assign(
self._variable,
self._try_guard_against_uninitialized_dependencies(
self._initial_value),
validate_shape=validate_shape).op
# TODO(vrv): Change this class to not take caching_device, but
# to take the op to colocate the snapshot with, so we can use
# colocation rather than devices.
if caching_device is not None:
with ops.device(caching_device):
self._snapshot = array_ops.identity(self._variable, name="read")
else:
with ops.colocate_with(self._variable.op):
self._snapshot = array_ops.identity(self._variable, name="read")
ops.add_to_collections(collections, self)
self._caching_device = caching_device
self._save_slice_info = None
self._constraint = constraint
def _init_from_proto(self, variable_def, import_scope=None):
"""Recreates the Variable object from a `VariableDef` protocol buffer.
Args:
variable_def: `VariableDef` protocol buffer, describing a variable
whose nodes already exists in the graph.
import_scope: Optional `string`. Name scope to add.
"""
assert isinstance(variable_def, variable_pb2.VariableDef)
# Create from variable_def.
g = ops.get_default_graph()
self._variable = g.as_graph_element(
ops.prepend_name_scope(variable_def.variable_name,
import_scope=import_scope))
self._initializer_op = g.as_graph_element(
ops.prepend_name_scope(variable_def.initializer_name,
import_scope=import_scope))
# Tests whether initial_value_name exists first for backwards compatibility.
if (hasattr(variable_def, "initial_value_name") and
variable_def.initial_value_name):
self._initial_value = g.as_graph_element(
ops.prepend_name_scope(variable_def.initial_value_name,
import_scope=import_scope))
else:
self._initial_value = None
self._trainable = getattr(variable_def, "trainable", True)
self._snapshot = g.as_graph_element(
ops.prepend_name_scope(variable_def.snapshot_name,
import_scope=import_scope))
if variable_def.HasField("save_slice_info_def"):
self._save_slice_info = Variable.SaveSliceInfo(
save_slice_info_def=variable_def.save_slice_info_def,
import_scope=import_scope)
else:
self._save_slice_info = None
self._caching_device = None
self._constraint = None
def _as_graph_element(self):
"""Conversion function for Graph.as_graph_element()."""
return self._variable
def _AsTensor(self): # pylint: disable=invalid-name
"""Converts this variable to a Tensor.
See `tf.Variable.value`.
Returns:
A `Tensor` containing the value of the variable.
"""
return self._snapshot
def value(self):
"""Returns the last snapshot of this variable.
You usually do not need to call this method as all ops that need the value
of the variable call it automatically through a `convert_to_tensor()` call.
Returns a `Tensor` which holds the value of the variable. You can not
assign a new value to this tensor as it is not a reference to the variable.
To avoid copies, if the consumer of the returned value is on the same device
as the variable, this actually returns the live value of the variable, not
a copy. Updates to the variable are seen by the consumer. If the consumer
is on a different device it will get a copy of the variable.
Returns:
A `Tensor` containing the value of the variable.
"""
return self._snapshot
def read_value(self):
"""Returns the value of this variable, read in the current context.
Can be different from value() if it's on another device, with control
dependencies, etc.
Returns:
A `Tensor` containing the value of the variable.
"""
return array_ops.identity(self._variable, name="read")
def _ref(self):
"""Returns a reference to this variable.
You usually do not need to call this method as all ops that need a reference
to the variable call it automatically.
Returns is a `Tensor` which holds a reference to the variable. You can
assign a new value to the variable by passing the tensor to an assign op.
See `tf.Variable.value` if you want to get the value of the
variable.
Returns:
A `Tensor` that is a reference to the variable.
"""
return self._variable
def set_shape(self, shape):
"""Overrides the shape for this variable.
Args:
shape: the `TensorShape` representing the overridden shape.
"""
self._ref().set_shape(shape)
self.value().set_shape(shape)
@property
def trainable(self):
return self._trainable
def eval(self, session=None):
"""In a session, computes and returns the value of this variable.
This is not a graph construction method, it does not add ops to the graph.
This convenience method requires a session where the graph
containing this variable has been launched. If no session is
passed, the default session is used. See `tf.Session` for more
information on launching a graph and on sessions.
```python
v = tf.Variable([1, 2])
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# Usage passing the session explicitly.
print(v.eval(sess))
# Usage with the default session. The 'with' block
# above makes 'sess' the default session.
print(v.eval())
```
Args:
session: The session to use to evaluate this variable. If
none, the default session is used.
Returns:
A numpy `ndarray` with a copy of the value of this variable.
"""
return self._variable.eval(session=session)
def initialized_value(self):
"""Returns the value of the initialized variable.
You should use this instead of the variable itself to initialize another
variable with a value that depends on the value of this variable.
```python
# Initialize 'v' with a random tensor.
v = tf.Variable(tf.truncated_normal([10, 40]))
# Use `initialized_value` to guarantee that `v` has been
# initialized before its value is used to initialize `w`.
# The random values are picked only once.
w = tf.Variable(v.initialized_value() * 2.0)
```
Returns:
A `Tensor` holding the value of this variable after its initializer
has run.
"""
with ops.init_scope():
return control_flow_ops.cond(is_variable_initialized(self),
self.read_value,
lambda: self.initial_value)
@property
def initial_value(self):
"""Returns the Tensor used as the initial value for the variable.
Note that this is different from `initialized_value()` which runs
the op that initializes the variable before returning its value.
This method returns the tensor that is used by the op that initializes
the variable.
Returns:
A `Tensor`.
"""
return self._initial_value
@property
def constraint(self):
"""Returns the constraint function associated with this variable.
Returns:
The constraint function that was passed to the variable constructor.
Can be `None` if no constraint was passed.
"""
return self._constraint
def assign(self, value, use_locking=False, name=None, read_value=True):
"""Assigns a new value to the variable.
This is essentially a shortcut for `assign(self, value)`.
Args:
value: A `Tensor`. The new value for this variable.
use_locking: If `True`, use locking during the assignment.
name: The name of the operation to be created
read_value: if True, will return something which evaluates to the
new value of the variable; if False will return the assign op.
Returns:
A `Tensor` that will hold the new value of this variable after
the assignment has completed.
"""
assign = state_ops.assign(self._variable, value, use_locking=use_locking,
name=name)
if read_value:
return assign
return assign.op
def assign_add(self, delta, use_locking=False, name=None, read_value=True):
"""Adds a value to this variable.
This is essentially a shortcut for `assign_add(self, delta)`.
Args:
delta: A `Tensor`. The value to add to this variable.
use_locking: If `True`, use locking during the operation.
name: The name of the operation to be created
read_value: if True, will return something which evaluates to the
new value of the variable; if False will return the assign op.
Returns:
A `Tensor` that will hold the new value of this variable after
the addition has completed.
"""
assign = state_ops.assign_add(
self._variable, delta, use_locking=use_locking, name=name)
if read_value:
return assign
return assign.op
def assign_sub(self, delta, use_locking=False, name=None, read_value=True):
"""Subtracts a value from this variable.
This is essentially a shortcut for `assign_sub(self, delta)`.
Args:
delta: A `Tensor`. The value to subtract from this variable.
use_locking: If `True`, use locking during the operation.
name: The name of the operation to be created
read_value: if True, will return something which evaluates to the
new value of the variable; if False will return the assign op.
Returns:
A `Tensor` that will hold the new value of this variable after
the subtraction has completed.
"""
assign = state_ops.assign_sub(
self._variable, delta, use_locking=use_locking, name=name)
if read_value:
return assign
return assign.op
def scatter_sub(self, sparse_delta, use_locking=False, name=None):
"""Subtracts `IndexedSlices` from this variable.
Args:
sparse_delta: `IndexedSlices` to be subtracted from this variable.
use_locking: If `True`, use locking during the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered subtraction has completed.
Raises:
ValueError: if `sparse_delta` is not an `IndexedSlices`.
"""
if not isinstance(sparse_delta, ops.IndexedSlices):
raise ValueError("sparse_delta is not IndexedSlices: %s" % sparse_delta)
return gen_state_ops.scatter_sub(
self._variable,
sparse_delta.indices,
sparse_delta.values,
use_locking=use_locking,
name=name)
def scatter_add(self, sparse_delta, use_locking=False, name=None):
"""Adds `IndexedSlices` from this variable.
Args:
sparse_delta: `IndexedSlices` to be added to this variable.
use_locking: If `True`, use locking during the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered subtraction has completed.
Raises:
ValueError: if `sparse_delta` is not an `IndexedSlices`.
"""
if not isinstance(sparse_delta, ops.IndexedSlices):
raise ValueError("sparse_delta is not IndexedSlices: %s" % sparse_delta)
return gen_state_ops.scatter_add(
self._variable,
sparse_delta.indices,
sparse_delta.values,
use_locking=use_locking,
name=name)
def scatter_update(self, sparse_delta, use_locking=False, name=None):
"""Assigns `IndexedSlices` to this variable.
Args:
sparse_delta: `IndexedSlices` to be assigned to this variable.
use_locking: If `True`, use locking during the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered subtraction has completed.
Raises:
ValueError: if `sparse_delta` is not an `IndexedSlices`.
"""
if not isinstance(sparse_delta, ops.IndexedSlices):
raise ValueError("sparse_delta is not IndexedSlices: %s" % sparse_delta)
return gen_state_ops.scatter_update(
self._variable,
sparse_delta.indices,
sparse_delta.values,
use_locking=use_locking,
name=name)
def scatter_nd_sub(self, indices, updates, name=None):
"""Applies sparse subtraction to individual values or slices in a Variable.
`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.
`indices` must be integer tensor, containing indices into `ref`.
It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.
The innermost dimension of `indices` (with length `K`) corresponds to
indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th
dimension of `ref`.
`updates` is `Tensor` of rank `Q-1+P-K` with shape:
```
[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].
```
For example, say we want to add 4 scattered elements to a rank-1 tensor to
8 elements. In Python, that update would look like this:
```python
ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1] ,[7]])
updates = tf.constant([9, 10, 11, 12])
op = ref.scatter_nd_sub(indices, updates)
with tf.Session() as sess:
print sess.run(op)
```
The resulting update to ref would look like this:
[1, -9, 3, -6, -6, 6, 7, -4]
See `tf.scatter_nd` for more details about how to make updates to
slices.
Args:
indices: The indices to be used in the operation.
updates: The values to be used in the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered subtraction has completed.
Raises:
ValueError: if `sparse_delta` is not an `IndexedSlices`.
"""
return gen_state_ops.scatter_nd_sub(
self._variable, indices, updates, use_locking=True, name=name)
def scatter_nd_add(self, indices, updates, name=None):
"""Applies sparse addition to individual values or slices in a Variable.
`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.
`indices` must be integer tensor, containing indices into `ref`.
It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.
The innermost dimension of `indices` (with length `K`) corresponds to
indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th
dimension of `ref`.
`updates` is `Tensor` of rank `Q-1+P-K` with shape:
```
[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].
```
For example, say we want to add 4 scattered elements to a rank-1 tensor to
8 elements. In Python, that update would look like this:
```python
ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1] ,[7]])
updates = tf.constant([9, 10, 11, 12])
add = ref.scatter_nd_add(indices, updates)
with tf.Session() as sess:
print sess.run(add)
```
The resulting update to ref would look like this:
[1, 13, 3, 14, 14, 6, 7, 20]
See `tf.scatter_nd` for more details about how to make updates to
slices.
Args:
indices: The indices to be used in the operation.
updates: The values to be used in the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered subtraction has completed.
Raises:
ValueError: if `sparse_delta` is not an `IndexedSlices`.
"""
return gen_state_ops.scatter_nd_add(
self._variable, indices, updates, use_locking=True, name=name)
def scatter_nd_update(self, indices, updates, name=None):
"""Applies sparse assignment to individual values or slices in a Variable.
`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.
`indices` must be integer tensor, containing indices into `ref`.
It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.
The innermost dimension of `indices` (with length `K`) corresponds to
indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th
dimension of `ref`.
`updates` is `Tensor` of rank `Q-1+P-K` with shape:
```
[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].
```
For example, say we want to add 4 scattered elements to a rank-1 tensor to
8 elements. In Python, that update would look like this:
```python
ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1] ,[7]])
updates = tf.constant([9, 10, 11, 12])
op = ref.scatter_nd_update(indices, updates)
with tf.Session() as sess:
print sess.run(op)
```
The resulting update to ref would look like this:
[1, 11, 3, 10, 9, 6, 7, 12]
See `tf.scatter_nd` for more details about how to make updates to
slices.
Args:
indices: The indices to be used in the operation.
updates: The values to be used in the operation.
name: the name of the operation.
Returns:
A `Tensor` that will hold the new value of this variable after
the scattered subtraction has completed.
Raises:
ValueError: if `sparse_delta` is not an `IndexedSlices`.
"""
return gen_state_ops.scatter_nd_update(
self._variable, indices, updates, use_locking=True, name=name)
def _strided_slice_assign(self,
begin,
end,
strides,
value,
name,
begin_mask,
end_mask,
ellipsis_mask,
new_axis_mask,
shrink_axis_mask):
return gen_array_ops.strided_slice_assign(ref=self._ref(),
begin=begin,
end=end,
strides=strides,
value=value,
name=name,
begin_mask=begin_mask,
end_mask=end_mask,
ellipsis_mask=ellipsis_mask,
new_axis_mask=new_axis_mask,
shrink_axis_mask=shrink_axis_mask)
def count_up_to(self, limit):
"""Increments this variable until it reaches `limit`.
When that Op is run it tries to increment the variable by `1`. If
incrementing the variable would bring it above `limit` then the Op raises
the exception `OutOfRangeError`.
If no error is raised, the Op outputs the value of the variable before
the increment.
This is essentially a shortcut for `count_up_to(self, limit)`.
Args:
limit: value at which incrementing the variable raises an error.
Returns:
A `Tensor` that will hold the variable value before the increment. If no
other Op modifies this variable, the values produced will all be
distinct.
"""
return state_ops.count_up_to(self._variable, limit=limit)
def load(self, value, session=None):
"""Load new value into this variable.
Writes new value to variable's memory. Doesn't add ops to the graph.
This convenience method requires a session where the graph
containing this variable has been launched. If no session is
passed, the default session is used. See `tf.Session` for more
information on launching a graph and on sessions.
```python
v = tf.Variable([1, 2])
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# Usage passing the session explicitly.
v.load([2, 3], sess)
print(v.eval(sess)) # prints [2 3]
# Usage with the default session. The 'with' block
# above makes 'sess' the default session.
v.load([3, 4], sess)
print(v.eval()) # prints [3 4]
```
Args:
value: New variable value
session: The session to use to evaluate this variable. If
none, the default session is used.
Raises:
ValueError: Session is not passed and no default session
"""
if context.executing_eagerly():
self.assign(value)
else:
session = session or ops.get_default_session()
if session is None:
raise ValueError(
"Either session argument should be provided or default session "
"should be established")
session.run(self._initializer_op, {self._initializer_op.inputs[1]: value})
# Conversion to tensor.
@staticmethod
def _TensorConversionFunction(v, dtype=None, name=None, as_ref=False): # pylint: disable=invalid-name
"""Utility function for converting a Variable to a Tensor."""
_ = name
if dtype and not dtype.is_compatible_with(v.dtype):
raise ValueError(
"Incompatible type conversion requested to type '%s' for variable "
"of type '%s'" % (dtype.name, v.dtype.name))
if as_ref:
return v._ref() # pylint: disable=protected-access
else:
return v.value()
def _gather_saveables_for_checkpoint(self):
"""For implementing `Checkpointable`. This object is saveable on its own."""
return {checkpointable.VARIABLE_VALUE_KEY: self}
def _try_guard_against_uninitialized_dependencies(self, initial_value):
"""Attempt to guard against dependencies on uninitialized variables.
Replace references to variables in `initial_value` with references to the
variable's initialized values. The initialized values are essentially
conditional TensorFlow graphs that return a variable's value if it is
initialized or its `initial_value` if it hasn't been initialized. This
replacement is done on a best effort basis:
- If the `initial_value` graph contains cycles, we don't do any
replacements for that graph.
- If the variables that `initial_value` depends on are not present in the
`GLOBAL_VARIABLES` or `LOCAL_VARIABLES` we don't replace them.
In these cases, it is up to the caller to ensure that the `initial_value`
graph uses initialized variables or that they guard access to variables
using their `initialized_value` method.
Args:
initial_value: `Tensor`. The initial value.
Returns:
A `Tensor` suitable to initialize a variable.
Raises:
TypeError: If `initial_value` is not a `Tensor`.
"""
if not isinstance(initial_value, ops.Tensor):
raise TypeError("initial_value needs to be a Tensor: %s" % initial_value)
# Don't modify initial_value if it contains any cyclic dependencies.
if _has_cycle(initial_value.op, path=set()):
return initial_value
return self._safe_initial_value_from_tensor(initial_value, op_cache={})
def _safe_initial_value_from_tensor(self, tensor, op_cache):
"""Replace dependencies on variables with their initialized values.
Args:
tensor: A `Tensor`. The tensor to replace.
op_cache: A dict mapping operation names to `Operation`s. Used to memoize
the results so as to avoid creating redundant operations.
Returns:
A `Tensor` compatible with `tensor`. Any inputs that lead to variable
values will be replaced with a corresponding graph that uses the
variable's initialized values. This is done on a best-effort basis. If no
modifications need to be made then `tensor` will be returned unchanged.
"""
op = tensor.op
new_op = op_cache.get(op.name)
if new_op is None:
new_op = self._safe_initial_value_from_op(op, op_cache)
op_cache[op.name] = new_op
return new_op.outputs[tensor.value_index]
def _safe_initial_value_from_op(self, op, op_cache):
"""Replace dependencies on variables with their initialized values.
Args:
op: An `Operation`. The operation to replace.
op_cache: A dict mapping operation names to `Operation`s. Used to memoize
the results so as to avoid creating redundant operations.
Returns:
An `Operation` compatible with `op`. Any inputs that lead to variable
values will be replaced with a corresponding graph that uses the
variable's initialized values. This is done on a best-effort basis. If no
modifications need to be made then `op` will be returned unchanged.
"""
op_type = op.node_def.op
if op_type in ("IsVariableInitialized", "VarIsInitializedOp",
"ReadVariableOp"):
return op
# Attempt to find the initialized_value of any variable reference / handles.
# TODO(b/70206927): Fix handling of ResourceVariables.
if op_type in ("Variable", "VariableV2", "VarHandleOp"):
initialized_value = self._find_initialized_value_for_variable(op)
return op if initialized_value is None else initialized_value.op
# Recursively build initializer expressions for inputs.
modified = False
new_op_inputs = []
for op_input in op.inputs:
new_op_input = self._safe_initial_value_from_tensor(op_input, op_cache)
new_op_inputs.append(new_op_input)
modified = modified or (new_op_input != op_input)
# If at least one input was modified, replace the op.
if modified:
new_op_type = op_type
if new_op_type == "RefSwitch":
new_op_type = "Switch"
new_op_name = op.node_def.name + "_" + self.name
new_op_name = new_op_name.replace(":", "_")
return self.graph.create_op(
new_op_type, new_op_inputs,
op._output_types, # pylint: disable=protected-access
name=new_op_name, attrs=op.node_def.attr)
return op
def _find_initialized_value_for_variable(self, variable_op):
"""Find the initialized value for a variable op.
To do so, lookup the variable op in the variables collection.
Args:
variable_op: A variable `Operation`.
Returns:
A `Tensor` representing the initialized value for the variable or `None`
if the initialized value could not be found.
"""
try:
var_names = [variable_op.node_def.name, variable_op.node_def.name + ":0"]
for collection_name in (ops.GraphKeys.GLOBAL_VARIABLES,
ops.GraphKeys.LOCAL_VARIABLES):
for var in self.graph.get_collection(collection_name):
if var.name in var_names:
return var.initialized_value()
except AttributeError:
# Return None when an incomplete user-defined variable type was put in
# the collection.
return None
return None
# NOTE(mrry): This enables the Variable's overloaded "right" binary
# operators to run when the left operand is an ndarray, because it
# accords the Variable class higher priority than an ndarray, or a
# numpy matrix.
# TODO(mrry): Convert this to using numpy's __numpy_ufunc__
# mechanism, which allows more control over how Variables interact
# with ndarrays.
__array_priority__ = 100
@property
def name(self):
"""The name of this variable."""
return self._variable.name
@property
def _shared_name(self):
"""The shared name of the variable.
Unlike name(), shared_name doesn't have ":0" suffix. It is user-specified
name with name scope prefix.
Returns:
variable name.
"""
return self.name[:-2]
@property
def initializer(self):
"""The initializer operation for this variable."""
return self._initializer_op
@property
def device(self):
"""The device of this variable."""
return self._variable.device
@property
def dtype(self):
"""The `DType` of this variable."""
return self._variable.dtype
@property
def op(self):
"""The `Operation` of this variable."""
return self._variable.op
@property
def graph(self):
"""The `Graph` of this variable."""
return self._variable.graph
@property
def shape(self):
"""The `TensorShape` of this variable.
Returns:
A `TensorShape`.
"""
return self._variable.get_shape()
def get_shape(self):
"""Alias of Variable.shape."""
return self.shape
def to_proto(self, export_scope=None):
"""Converts a `Variable` to a `VariableDef` protocol buffer.
Args:
export_scope: Optional `string`. Name scope to remove.
Returns:
A `VariableDef` protocol buffer, or `None` if the `Variable` is not
in the specified name scope.
"""
if (export_scope is None or
self._variable.name.startswith(export_scope)):
var_def = variable_pb2.VariableDef()
var_def.variable_name = ops.strip_name_scope(
self._variable.name, export_scope)
if self._initial_value is not None:
# For backwards compatibility.
var_def.initial_value_name = ops.strip_name_scope(
self._initial_value.name, export_scope)
var_def.trainable = self.trainable
var_def.initializer_name = ops.strip_name_scope(
self.initializer.name, export_scope)
var_def.snapshot_name = ops.strip_name_scope(
self._snapshot.name, export_scope)
if self._save_slice_info:
var_def.save_slice_info_def.MergeFrom(self._save_slice_info.to_proto(
export_scope=export_scope))
return var_def
else:
return None
def __iadd__(self, other):
logging.log_first_n(
logging.WARN,
"Variable += will be deprecated. Use variable.assign_add"
" if you want assignment to the variable value or 'x = x + y'"
" if you want a new python Tensor object.", 1)
return self + other
def __isub__(self, other):
logging.log_first_n(
logging.WARN,
"Variable -= will be deprecated. Use variable.assign_sub"
" if you want assignment to the variable value or 'x = x - y'"
" if you want a new python Tensor object.", 1)
return self - other
def __imul__(self, other):
logging.log_first_n(
logging.WARN,
"Variable *= will be deprecated. Use `var.assign(var * other)`"
" if you want assignment to the variable value or `x = x * y`"
" if you want a new python Tensor object.", 1)
return self * other
def __idiv__(self, other):
logging.log_first_n(
logging.WARN,
"Variable /= will be deprecated. Use `var.assign(var / other)`"
" if you want assignment to the variable value or `x = x / y`"
" if you want a new python Tensor object.", 1)
return self / other
def __itruediv__(self, other):
logging.log_first_n(
logging.WARN,
"Variable /= will be deprecated. Use `var.assign(var / other)`"
" if you want assignment to the variable value or `x = x / y`"
" if you want a new python Tensor object.", 1)
return self / other
def __irealdiv__(self, other):
logging.log_first_n(
logging.WARN,
"Variable /= will be deprecated. Use `var.assign(var / other)`"
" if you want assignment to the variable value or `x = x / y`"
" if you want a new python Tensor object.", 1)
return self / other
def __ipow__(self, other):
logging.log_first_n(
logging.WARN,
"Variable **= will be deprecated. Use `var.assign(var ** other)`"
" if you want assignment to the variable value or `x = x ** y`"
" if you want a new python Tensor object.", 1)
return self ** other
def _set_save_slice_info(self, save_slice_info):
"""Sets the slice info for this `Variable`.
Args:
save_slice_info: A `Variable.SaveSliceInfo` object.
"""
self._save_slice_info = save_slice_info
def _get_save_slice_info(self):
return self._save_slice_info
class PartitionedVariable(object):
"""A container for partitioned `Variable` objects.
@compatibility(eager) `tf.PartitionedVariable` is not compatible with
eager execution. Use `tf.Variable` instead which is compatible
with both eager execution and graph construction. See [the
TensorFlow Eager Execution
guide](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/g3doc/guide.md#variables-and-optimizers)
for details on how variables work in eager execution.
@end_compatibility
"""
def __init__(self, name, shape, dtype, variable_list, partitions):
"""Creates a new partitioned variable wrapper.
Variables passed via the variable_list must contain a save_slice_info
field. Concatenation and iteration is in lexicographic order according
to the var_offset property of the save_slice_info.
Args:
name: String. Overall name of the variables.
shape: List of integers. Overall shape of the variables.
dtype: Type of the variables.
variable_list: List of `Variable` that comprise this partitioned variable.
partitions: List of integers. Number of partitions for each dimension.
Raises:
TypeError: If `variable_list` is not a list of `Variable` objects, or
`partitions` is not a list.
ValueError: If `variable_list` is empty, or the `Variable` shape
information does not match `shape`, or `partitions` has invalid values.
"""
if not isinstance(variable_list, (list, tuple)):
raise TypeError(
"variable_list is not a list or tuple: %s" % variable_list)
if not isinstance(partitions, (list, tuple)):
raise TypeError("partitions is not a list or tuple: %s" % partitions)
if not all(p >= 1 for p in partitions):
raise ValueError("partition values must be positive: %s" % partitions)
if not variable_list:
raise ValueError("variable_list may not be empty")
# pylint: disable=protected-access
for v in variable_list:
# Sort the variable_list lexicographically according to var offset value.
if not all(v._get_save_slice_info() is not None for v in variable_list):
raise ValueError(
"All variables must have a save_slice_info available: %s"
% [v.name for v in variable_list])
if len(shape) != len(partitions):
raise ValueError("len(shape) != len(partitions): %s vs. %s"
% (shape, partitions))
if v._get_save_slice_info().full_shape != shape:
raise ValueError(
"All variables' full shapes must match shape: %s; "
"but full shapes were: %s"
% (shape, str([v._get_save_slice_info().full_shape])))
self._variable_list = sorted(
variable_list, key=lambda v: v._get_save_slice_info().var_offset)
# pylint: enable=protected-access
self._name = name
self._shape = shape
self._dtype = dtype
self._partitions = partitions
self._as_tensor = None
def __iter__(self):
"""Return an iterable for accessing the underlying partition Variables."""
return iter(self._variable_list)
def __len__(self):
num_partition_axes = len(self._partition_axes())
if num_partition_axes > 1:
raise ValueError("Cannot get a length for %d > 1 partition axes"
% num_partition_axes)
return len(self._variable_list)
def _partition_axes(self):
if all(p == 1 for p in self._partitions):
return [0]
else:
return [i for i, p in enumerate(self._partitions) if p > 1]
def _concat(self):
"""Returns the overall concatenated value as a `Tensor`.
This is different from using the partitioned variable directly as a tensor
(through tensor conversion and `as_tensor`) in that it creates a new set of
operations that keeps the control dependencies from its scope.
Returns:
`Tensor` containing the concatenated value.
"""
if len(self._variable_list) == 1:
with ops.name_scope(None):
return array_ops.identity(self._variable_list[0], name=self._name)
partition_axes = self._partition_axes()
if len(partition_axes) > 1:
raise NotImplementedError(
"Cannot concatenate along more than one dimension: %s. "
"Multi-axis partition concat is not supported" % str(partition_axes))
partition_ix = partition_axes[0]
with ops.name_scope(self._name + "/ConcatPartitions/"):
concatenated = array_ops.concat(self._variable_list, partition_ix)
with ops.name_scope(None):
return array_ops.identity(concatenated, name=self._name)
def as_tensor(self):
"""Returns the overall concatenated value as a `Tensor`.
The returned tensor will not inherit the control dependencies from the scope
where the value is used, which is similar to getting the value of
`Variable`.
Returns:
`Tensor` containing the concatenated value.
"""
with ops.control_dependencies(None):
return self._concat()
@staticmethod
def _TensorConversionFunction(v, dtype=None, name=None, as_ref=False):
# pylint: disable=invalid-name
_ = name
if dtype is not None and not dtype.is_compatible_with(v.dtype):
raise ValueError(
"Incompatible type conversion requested to type '%s' for variable "
"of type '%s'" % (dtype.name, v.dtype.name))
if as_ref:
raise NotImplementedError(
"PartitionedVariable doesn't support being used as a reference.")
else:
return v.as_tensor()
@property
def name(self):
return self._name
@property
def dtype(self):
return self._dtype
@property
def shape(self):
return self.get_shape()
def get_shape(self):
return self._shape
def _get_variable_list(self):
return self._variable_list
def _get_partitions(self):
return self._partitions
def _apply_assign_fn(self, assign_fn, value):
partition_axes = self._partition_axes()
if len(partition_axes) > 1:
raise NotImplementedError(
"Cannot do assign action along more than one dimension: %s. "
"Multi-axis partition assign action is not supported " %
str(partition_axes))
if isinstance(value, list):
assert len(value) == len(self._variable_list)
value_list = value
elif isinstance(value, PartitionedVariable):
value_list = [var_part for var_part in value]
else:
partition_ix = partition_axes[0]
size_splits_list = [
tensor_shape.dimension_value(var.shape[partition_ix])
for var in self._variable_list
]
value_list = array_ops.split(value, size_splits_list, axis=partition_ix)
op_list = [
assign_fn(var, value_list[idx])
for idx, var in enumerate(self._variable_list)
]
return op_list
def assign(self, value, use_locking=False, name=None, read_value=True):
assign_fn = lambda var, r_value: var.assign(
r_value, use_locking=use_locking,
name=name, read_value=read_value)
assign_list = self._apply_assign_fn(assign_fn, value)
if read_value:
return assign_list
return [assign.op for assign in assign_list]
def assign_add(self, value, use_locking=False, name=None, read_value=True):
assign_fn = lambda var, r_value: var.assign_add(
r_value, use_locking=use_locking,
name=name, read_value=read_value)
assign_list = self._apply_assign_fn(assign_fn, value)
if read_value:
return assign_list
return [assign.op for assign in assign_list]
def assign_sub(self, value, use_locking=False, name=None, read_value=True):
assign_fn = lambda var, r_value: var.assign_sub(
r_value, use_locking=use_locking,
name=name, read_value=read_value)
assign_list = self._apply_assign_fn(assign_fn, value)
if read_value:
return assign_list
return [assign.op for assign in assign_list]
@tf_export(v1=["global_variables"])
def global_variables(scope=None):
"""Returns global variables.
Global variables are variables that are shared across machines in a
distributed environment. The `Variable()` constructor or `get_variable()`
automatically adds new variables to the graph collection
`GraphKeys.GLOBAL_VARIABLES`.
This convenience function returns the contents of that collection.
An alternative to global variables are local variables. See
`tf.local_variables`
Args:
scope: (Optional.) A string. If supplied, the resulting list is filtered
to include only items whose `name` attribute matches `scope` using
`re.match`. Items without a `name` attribute are never returned if a
scope is supplied. The choice of `re.match` means that a `scope` without
special tokens filters by prefix.
Returns:
A list of `Variable` objects.
"""
return ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, scope)
@tf_export(v1=["all_variables"])
@deprecated("2017-03-02", "Please use tf.global_variables instead.")
def all_variables():
"""See `tf.global_variables`."""
return global_variables()
def _all_saveable_objects(scope=None):
"""Returns all variables and `SaveableObject`s that must be checkpointed.
Args:
scope: (Optional.) A string. If supplied, the resulting list is filtered
to include only items whose `name` attribute matches `scope` using
`re.match`. Items without a `name` attribute are never returned if a
scope is supplied. The choice of `re.match` means that a `scope` without
special tokens filters by prefix.
Returns:
A list of `Variable` and `SaveableObject` to be checkpointed
"""
# TODO(andreasst): make this function public once things are settled.
return (ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, scope) +
ops.get_collection(ops.GraphKeys.SAVEABLE_OBJECTS, scope))
@tf_export(v1=["local_variables"])
def local_variables(scope=None):
"""Returns local variables.
Local variables - per process variables, usually not saved/restored to
checkpoint and used for temporary or intermediate values.
For example, they can be used as counters for metrics computation or
number of epochs this machine has read data.
The `tf.contrib.framework.local_variable()` function automatically adds the
new variable to `GraphKeys.LOCAL_VARIABLES`.
This convenience function returns the contents of that collection.
An alternative to local variables are global variables. See
`tf.global_variables`
Args:
scope: (Optional.) A string. If supplied, the resulting list is filtered
to include only items whose `name` attribute matches `scope` using
`re.match`. Items without a `name` attribute are never returned if a
scope is supplied. The choice of `re.match` means that a `scope` without
special tokens filters by prefix.
Returns:
A list of local `Variable` objects.
"""
return ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES, scope)
@tf_export(v1=["model_variables"])
def model_variables(scope=None):
"""Returns all variables in the MODEL_VARIABLES collection.
Args:
scope: (Optional.) A string. If supplied, the resulting list is filtered
to include only items whose `name` attribute matches `scope` using
`re.match`. Items without a `name` attribute are never returned if a
scope is supplied. The choice of `re.match` means that a `scope` without
special tokens filters by prefix.
Returns:
A list of local Variable objects.
"""
return ops.get_collection(ops.GraphKeys.MODEL_VARIABLES, scope)
@tf_export(v1=["trainable_variables"])
def trainable_variables(scope=None):
"""Returns all variables created with `trainable=True`.
When passed `trainable=True`, the `Variable()` constructor automatically
adds new variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`. This convenience function returns the
contents of that collection.
Args:
scope: (Optional.) A string. If supplied, the resulting list is filtered
to include only items whose `name` attribute matches `scope` using
`re.match`. Items without a `name` attribute are never returned if a
scope is supplied. The choice of `re.match` means that a `scope` without
special tokens filters by prefix.
Returns:
A list of Variable objects.
"""
return ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES, scope)
@tf_export(v1=["moving_average_variables"])
def moving_average_variables(scope=None):
"""Returns all variables that maintain their moving averages.
If an `ExponentialMovingAverage` object is created and the `apply()`
method is called on a list of variables, these variables will
be added to the `GraphKeys.MOVING_AVERAGE_VARIABLES` collection.
This convenience function returns the contents of that collection.
Args:
scope: (Optional.) A string. If supplied, the resulting list is filtered
to include only items whose `name` attribute matches `scope` using
`re.match`. Items without a `name` attribute are never returned if a
scope is supplied. The choice of `re.match` means that a `scope` without
special tokens filters by prefix.
Returns:
A list of Variable objects.
"""
return ops.get_collection(ops.GraphKeys.MOVING_AVERAGE_VARIABLES, scope)
@tf_export(v1=["initializers.variables", "variables_initializer"])
def variables_initializer(var_list, name="init"):
"""Returns an Op that initializes a list of variables.
After you launch the graph in a session, you can run the returned Op to
initialize all the variables in `var_list`. This Op runs all the
initializers of the variables in `var_list` in parallel.
Calling `initialize_variables()` is equivalent to passing the list of
initializers to `Group()`.
If `var_list` is empty, however, the function still returns an Op that can
be run. That Op just has no effect.
Args:
var_list: List of `Variable` objects to initialize.
name: Optional name for the returned operation.
Returns:
An Op that run the initializers of all the specified variables.
"""
if var_list and not context.executing_eagerly():
return control_flow_ops.group(*[v.initializer for v in var_list], name=name)
return control_flow_ops.no_op(name=name)
@tf_export(v1=["initialize_variables"])
@tf_should_use.should_use_result
@deprecated("2017-03-02", "Use `tf.variables_initializer` instead.")
def initialize_variables(var_list, name="init"):
"""See `tf.variables_initializer`."""
return variables_initializer(var_list, name=name)
@tf_export(v1=["initializers.global_variables", "global_variables_initializer"])
def global_variables_initializer():
"""Returns an Op that initializes global variables.
This is just a shortcut for `variables_initializer(global_variables())`
Returns:
An Op that initializes global variables in the graph.
"""
if context.executing_eagerly():
return control_flow_ops.no_op(name="global_variables_initializer")
return variables_initializer(global_variables())
@tf_export(v1=["initialize_all_variables"])
@tf_should_use.should_use_result
@deprecated("2017-03-02", "Use `tf.global_variables_initializer` instead.")
def initialize_all_variables():
"""See `tf.global_variables_initializer`."""
return global_variables_initializer()
@tf_export(v1=["initializers.local_variables", "local_variables_initializer"])
def local_variables_initializer():
"""Returns an Op that initializes all local variables.
This is just a shortcut for `variables_initializer(local_variables())`
Returns:
An Op that initializes all local variables in the graph.
"""
if context.executing_eagerly():
return control_flow_ops.no_op(name="local_variables_initializer")
return variables_initializer(local_variables())
@tf_export(v1=["initialize_local_variables"])
@tf_should_use.should_use_result
@deprecated("2017-03-02", "Use `tf.local_variables_initializer` instead.")
def initialize_local_variables():
"""See `tf.local_variables_initializer`."""
return local_variables_initializer()
@tf_export(v1=["is_variable_initialized"])
@tf_should_use.should_use_result
def is_variable_initialized(variable):
"""Tests if a variable has been initialized.
Args:
variable: A `Variable`.
Returns:
Returns a scalar boolean Tensor, `True` if the variable has been
initialized, `False` otherwise.
"""
return state_ops.is_variable_initialized(variable)
@tf_export(v1=["assert_variables_initialized"])
@tf_should_use.should_use_result
def assert_variables_initialized(var_list=None):
"""Returns an Op to check if variables are initialized.
NOTE: This function is obsolete and will be removed in 6 months. Please
change your implementation to use `report_uninitialized_variables()`.
When run, the returned Op will raise the exception `FailedPreconditionError`
if any of the variables has not yet been initialized.
Note: This function is implemented by trying to fetch the values of the
variables. If one of the variables is not initialized a message may be
logged by the C++ runtime. This is expected.
Args:
var_list: List of `Variable` objects to check. Defaults to the
value of `global_variables().`
Returns:
An Op, or None if there are no variables.
"""
if var_list is None:
var_list = global_variables() + local_variables()
# Backwards compatibility for old-style variables. TODO(touts): remove.
if not var_list:
var_list = []
for op in ops.get_default_graph().get_operations():
if op.type in ["Variable", "VariableV2", "AutoReloadVariable"]:
var_list.append(op.outputs[0])
if not var_list:
return None
else:
ranks = []
for var in var_list:
with ops.colocate_with(var.op):
ranks.append(array_ops.rank_internal(var, optimize=False))
if len(ranks) == 1:
return ranks[0]
else:
return array_ops.stack(ranks)
@tf_export(v1=["report_uninitialized_variables"])
@tf_should_use.should_use_result
def report_uninitialized_variables(var_list=None,
name="report_uninitialized_variables"):
"""Adds ops to list the names of uninitialized variables.
When run, it returns a 1-D tensor containing the names of uninitialized
variables if there are any, or an empty array if there are none.
Args:
var_list: List of `Variable` objects to check. Defaults to the
value of `global_variables() + local_variables()`
name: Optional name of the `Operation`.
Returns:
A 1-D tensor containing names of the uninitialized variables, or an empty
1-D tensor if there are no variables or no uninitialized variables.
"""
if var_list is None:
var_list = global_variables() + local_variables()
# Backwards compatibility for old-style variables. TODO(touts): remove.
if not var_list:
var_list = []
for op in ops.get_default_graph().get_operations():
if op.type in ["Variable", "VariableV2", "AutoReloadVariable"]:
var_list.append(op.outputs[0])
with ops.name_scope(name):
# Run all operations on CPU
if var_list:
init_vars = [state_ops.is_variable_initialized(v) for v in var_list]
local_device = os.environ.get(
"TF_DEVICE_FOR_UNINITIALIZED_VARIABLE_REPORTING", "/cpu:0")
with ops.device(local_device):
if not var_list:
# Return an empty tensor so we only need to check for returned tensor
# size being 0 as an indication of model ready.
return array_ops.constant([], dtype=dtypes.string)
else:
# Get a 1-D boolean tensor listing whether each variable is initialized.
variables_mask = math_ops.logical_not(array_ops.stack(init_vars))
# Get a 1-D string tensor containing all the variable names.
variable_names_tensor = array_ops.constant(
[s.op.name for s in var_list])
# Return a 1-D tensor containing all the names of
# uninitialized variables.
return array_ops.boolean_mask(variable_names_tensor, variables_mask)
# pylint: disable=protected-access
Variable._OverloadAllOperators()
ops.register_tensor_conversion_function(
PartitionedVariable, PartitionedVariable._TensorConversionFunction)
# pylint: enable=protected-access
ops.register_dense_tensor_like_type(Variable) | indices: The indices to be used in the operation. |
client.go | // Copyright 2020, OpenTelemetry 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,
// 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.
package kubelet
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/pkg/errors"
"go.uber.org/zap"
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/k8sconfig"
)
const svcAcctCACertPath = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
const svcAcctTokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token"
type Client interface {
Get(path string) ([]byte, error)
}
func NewClientProvider(endpoint string, cfg *ClientConfig, logger *zap.Logger) (ClientProvider, error) {
switch cfg.APIConfig.AuthType {
case k8sconfig.AuthTypeTLS:
return &tlsClientProvider{
endpoint: endpoint,
cfg: cfg,
logger: logger,
}, nil
case k8sconfig.AuthTypeServiceAccount:
return &saClientProvider{
endpoint: endpoint,
caCertPath: svcAcctCACertPath,
tokenPath: svcAcctTokenPath,
logger: logger,
}, nil
default:
return nil, fmt.Errorf("AuthType [%s] not supported", cfg.APIConfig.AuthType)
}
}
type ClientProvider interface {
BuildClient() (Client, error)
}
type tlsClientProvider struct {
endpoint string
cfg *ClientConfig
logger *zap.Logger
}
func (p *tlsClientProvider) BuildClient() (Client, error) {
rootCAs, err := systemCertPoolPlusPath(p.cfg.CAFile)
if err != nil {
return nil, err
}
clientCert, err := tls.LoadX509KeyPair(p.cfg.CertFile, p.cfg.KeyFile)
if err != nil {
return nil, err
}
return defaultTLSClient(
p.endpoint,
p.cfg.InsecureSkipVerify,
rootCAs,
[]tls.Certificate{clientCert},
nil,
p.logger,
)
}
type saClientProvider struct {
endpoint string
caCertPath string
tokenPath string
logger *zap.Logger
}
func (p *saClientProvider) BuildClient() (Client, error) {
rootCAs, err := systemCertPoolPlusPath(p.caCertPath)
if err != nil {
return nil, err
}
tok, err := ioutil.ReadFile(p.tokenPath)
if err != nil {
return nil, errors.WithMessagef(err, "Unable to read token file %s", p.tokenPath)
}
tr := defaultTransport()
tr.TLSClientConfig = &tls.Config{
RootCAs: rootCAs,
}
return defaultTLSClient(p.endpoint, true, rootCAs, nil, tok, p.logger)
}
func defaultTLSClient(
endpoint string,
insecureSkipVerify bool,
rootCAs *x509.CertPool,
certificates []tls.Certificate,
tok []byte,
logger *zap.Logger,
) (*clientImpl, error) {
tr := defaultTransport()
tr.TLSClientConfig = &tls.Config{
RootCAs: rootCAs,
Certificates: certificates,
InsecureSkipVerify: insecureSkipVerify,
}
if endpoint == "" {
var err error
endpoint, err = defaultEndpoint()
if err != nil {
return nil, err
}
logger.Warn("Kubelet endpoint not defined, using default endpoint " + endpoint)
}
return &clientImpl{
baseURL: "https://" + endpoint,
httpClient: http.Client{Transport: tr},
tok: tok,
logger: logger,
}, nil
}
// This will work if hostNetwork is turned on, in which case the pod has access
// to the node's loopback device.
// https://kubernetes.io/docs/concepts/policy/pod-security-policy/#host-namespaces
func defaultEndpoint() (string, error) {
hostname, err := os.Hostname()
if err != nil |
const kubeletPort = "10250"
return hostname + ":" + kubeletPort, nil
}
func defaultTransport() *http.Transport {
return http.DefaultTransport.(*http.Transport).Clone()
}
// clientImpl
var _ Client = (*clientImpl)(nil)
type clientImpl struct {
baseURL string
httpClient http.Client
logger *zap.Logger
tok []byte
}
func (c *clientImpl) Get(path string) ([]byte, error) {
req, err := c.buildReq(path)
if err != nil {
return nil, err
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() {
closeErr := resp.Body.Close()
if closeErr != nil {
c.logger.Warn("failed to close response body", zap.Error(closeErr))
}
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.WithMessage(err, "failed to read Kubelet response body")
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("kubelet request GET %s failed - %q, response: %q",
req.URL.String(), resp.Status, string(body))
}
return body, nil
}
func (c *clientImpl) buildReq(path string) (*http.Request, error) {
url := c.baseURL + path
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
if c.tok != nil {
req.Header.Set("Authorization", fmt.Sprintf("bearer %s", c.tok))
}
return req, nil
}
| {
return "", errors.WithMessage(err, "Unable to get hostname for default endpoint")
} |
preallocate_unix.go | //+build linux
package local
import (
"os"
"golang.org/x/sys/unix"
)
// preAllocate the file for performance reasons
func preAllocate(size int64, out *os.File) error {
if size <= 0 |
err := unix.Fallocate(int(out.Fd()), unix.FALLOC_FL_KEEP_SIZE, 0, size)
// FIXME could be doing something here
// if err == unix.ENOSPC {
// log.Printf("No space")
// }
return err
}
| {
return nil
} |
widget.py | from datetime import timedelta
from rest_framework import serializers
from ..models.widget import Widget
class | (serializers.ModelSerializer):
"""
This is the base serializer class for Widget model.
Other widget serializers must be inherited from it.
"""
class Meta:
model = Widget
fields = (
'id',
'category',
'limit',
'duration',
'criteria',
'color',
'creation_date',
)
class CreateWidgetSerializer(BaseWidgetSerializer):
color = serializers.CharField(max_length=10)
def validate_duration(self, value: timedelta):
"""
Check that duration is acceptable quantity of days.
"""
if value.days not in Widget.VALID_DURATION:
raise serializers.ValidationError(
f"You can chose only this day-periods {Widget.VALID_DURATION}."
)
return timedelta(days=value.days)
def validate_color(self, value):
"""
Check that color specified in hex correctly.
"""
if value.startswith('0x'):
return value[2:]
return value
def create(self, validated_data):
validated_data['owner'] = self.context['request'].user
return Widget.objects.create(**validated_data)
class DestroyWidgetSerializer(BaseWidgetSerializer):
pass
class ListWidgetSerializer(BaseWidgetSerializer):
class Meta(BaseWidgetSerializer.Meta):
fields = (
'id',
'category',
'limit',
'duration',
'criteria',
'color',
'creation_date',
'ending_date',
'sum',
'owner',
)
| BaseWidgetSerializer |
etcd.go | // Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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.
package etcd
import (
"context"
"fmt"
"time"
druidv1alpha1 "github.com/gardener/etcd-druid/api/v1alpha1"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
v1beta1constants "github.com/gardener/gardener/pkg/apis/core/v1beta1/constants"
"github.com/gardener/gardener/pkg/client/kubernetes"
"github.com/gardener/gardener/pkg/controllerutils"
"github.com/gardener/gardener/pkg/operation/botanist/component"
"github.com/gardener/gardener/pkg/operation/botanist/component/monitoring"
"github.com/gardener/gardener/pkg/utils"
gutil "github.com/gardener/gardener/pkg/utils/gardener"
kutil "github.com/gardener/gardener/pkg/utils/kubernetes"
hvpav1alpha1 "github.com/gardener/hvpa-controller/api/v1alpha1"
"github.com/sirupsen/logrus"
appsv1 "k8s.io/api/apps/v1"
autoscalingv2beta1 "k8s.io/api/autoscaling/v2beta1"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/util/intstr"
autoscalingv1beta2 "k8s.io/autoscaler/vertical-pod-autoscaler/pkg/apis/autoscaling.k8s.io/v1beta2"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// Class is a string type alias for etcd classes.
type Class string
const (
// ClassNormal is a constant for a normal etcd (without extensive metrics or higher resource settings, etc.)
ClassNormal Class = "normal"
// ClassImportant is a constant for an important etcd (with extensive metrics or higher resource settings, etc.).
// Such etcds are also unsafe to evict (from the PoV of the cluster-autoscaler when trying to scale down).
ClassImportant Class = "important"
// SecretNameCA is the name of the secret containing the CA certificate and key for the etcd.
SecretNameCA = v1beta1constants.SecretNameCAETCD
// SecretNameServer is the name of the secret containing the server certificate and key for the etcd.
SecretNameServer = "etcd-server-cert"
// SecretNameClient is the name of the secret containing the client certificate and key for the etcd.
SecretNameClient = "etcd-client-tls"
// LabelAppValue is the value of a label whose key is 'app'.
LabelAppValue = "etcd-statefulset"
// NetworkPolicyName is the name of a network policy that allows ingress traffic to etcd from certain sources.
NetworkPolicyName = "allow-etcd"
portNameClient = "client"
portNameBackupRestore = "backuprestore"
statefulSetNamePrefix = "etcd"
containerNameEtcd = "etcd"
containerNameBackupRestore = "backup-restore"
)
var (
// TimeNow is a function returning the current time exposed for testing.
TimeNow = time.Now
// PortEtcdServer is the port exposed by etcd for server-to-server communication.
PortEtcdServer = int32(2380)
// PortEtcdClient is the port exposed by etcd for client communication.
PortEtcdClient = int32(2379)
// PortBackupRestore is the client port exposed by the backup-restore sidecar container.
PortBackupRestore = int32(8080)
)
// ServiceName returns the service name for an etcd for the given role.
func ServiceName(role string) string {
return fmt.Sprintf("etcd-%s-client", role)
}
// Interface contains functions for a etcd deployer.
type Interface interface {
component.DeployWaiter
component.MonitoringComponent
// ServiceDNSNames returns the service DNS names for the etcd.
ServiceDNSNames() []string
// Snapshot triggers the backup-restore sidecar to perform a full snapshot in case backup configuration is provided.
Snapshot(context.Context, kubernetes.PodExecutor) error
// SetSecrets sets the secrets.
SetSecrets(Secrets)
// SetBackupConfig sets the backup configuration.
SetBackupConfig(config *BackupConfig)
// SetHVPAConfig sets the HVPA configuration.
SetHVPAConfig(config *HVPAConfig)
// Get retrieves the Etcd resource
Get(context.Context) (*druidv1alpha1.Etcd, error)
// SetOwnerCheckConfig sets the owner check configuration.
SetOwnerCheckConfig(config *OwnerCheckConfig)
}
// New creates a new instance of DeployWaiter for the Etcd.
func New(
c client.Client,
logger logrus.FieldLogger,
namespace string,
role string,
class Class,
retainReplicas bool,
storageCapacity string,
defragmentationSchedule *string,
) Interface {
name := "etcd-" + role
var etcdLog logrus.FieldLogger
if logger != nil |
return &etcd{
client: c,
logger: etcdLog,
namespace: namespace,
role: role,
class: class,
retainReplicas: retainReplicas,
storageCapacity: storageCapacity,
defragmentationSchedule: defragmentationSchedule,
etcd: &druidv1alpha1.Etcd{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
},
}
}
type etcd struct {
client client.Client
logger logrus.FieldLogger
namespace string
role string
class Class
retainReplicas bool
storageCapacity string
defragmentationSchedule *string
etcd *druidv1alpha1.Etcd
secrets Secrets
backupConfig *BackupConfig
hvpaConfig *HVPAConfig
ownerCheckConfig *OwnerCheckConfig
}
func (e *etcd) Deploy(ctx context.Context) error {
if e.secrets.CA.Name == "" || e.secrets.CA.Checksum == "" {
return fmt.Errorf("missing CA secret information")
}
if e.secrets.Server.Name == "" || e.secrets.Server.Checksum == "" {
return fmt.Errorf("missing server secret information")
}
if e.secrets.Client.Name == "" || e.secrets.Client.Checksum == "" {
return fmt.Errorf("missing client secret information")
}
var (
networkPolicy = e.emptyNetworkPolicy()
hvpa = e.emptyHVPA()
existingEtcd *druidv1alpha1.Etcd
existingSts *appsv1.StatefulSet
)
if err := e.client.Get(ctx, client.ObjectKeyFromObject(e.etcd), e.etcd); err != nil {
if !apierrors.IsNotFound(err) {
return err
}
} else {
existingEtcd = e.etcd.DeepCopy()
}
stsName := e.etcd.Name
if existingEtcd != nil && existingEtcd.Status.Etcd != nil && existingEtcd.Status.Etcd.Name != "" {
stsName = existingEtcd.Status.Etcd.Name
}
var sts appsv1.StatefulSet
if err := e.client.Get(ctx, client.ObjectKey{Namespace: e.namespace, Name: stsName}, &sts); err != nil {
if !apierrors.IsNotFound(err) {
return err
}
} else {
existingSts = &sts
}
var (
replicas = e.computeReplicas(existingEtcd)
protocolTCP = corev1.ProtocolTCP
intStrPortEtcdClient = intstr.FromInt(int(PortEtcdClient))
intStrPortBackupRestore = intstr.FromInt(int(PortBackupRestore))
resourcesEtcd, resourcesBackupRestore = e.computeContainerResources(existingSts)
quota = resource.MustParse("8Gi")
storageCapacity = resource.MustParse(e.storageCapacity)
garbageCollectionPolicy = druidv1alpha1.GarbageCollectionPolicy(druidv1alpha1.GarbageCollectionPolicyExponential)
garbageCollectionPeriod = metav1.Duration{Duration: 12 * time.Hour}
compressionPolicy = druidv1alpha1.GzipCompression
compressionSpec = druidv1alpha1.CompressionSpec{
Enabled: true,
Policy: &compressionPolicy,
}
annotations = map[string]string{
"checksum/secret-etcd-ca": e.secrets.CA.Checksum,
"checksum/secret-etcd-server-cert": e.secrets.Server.Checksum,
"checksum/secret-etcd-client-tls": e.secrets.Client.Checksum,
}
metrics = druidv1alpha1.Basic
volumeClaimTemplate = e.etcd.Name
minAllowed = corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("50m"),
corev1.ResourceMemory: resource.MustParse("200M"),
}
)
if e.class == ClassImportant {
annotations["cluster-autoscaler.kubernetes.io/safe-to-evict"] = "false"
metrics = druidv1alpha1.Extensive
volumeClaimTemplate = e.role + "-etcd"
minAllowed = corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("200m"),
corev1.ResourceMemory: resource.MustParse("700M"),
}
}
if _, err := controllerutils.GetAndCreateOrMergePatch(ctx, e.client, networkPolicy, func() error {
networkPolicy.Annotations = map[string]string{
v1beta1constants.GardenerDescription: "Allows Ingress to etcd pods from the Shoot's Kubernetes API Server.",
}
networkPolicy.Labels = map[string]string{
v1beta1constants.GardenRole: v1beta1constants.GardenRoleControlPlane,
}
networkPolicy.Spec.PodSelector = metav1.LabelSelector{
MatchLabels: map[string]string{
v1beta1constants.DeprecatedGardenRole: v1beta1constants.GardenRoleControlPlane,
v1beta1constants.LabelApp: LabelAppValue,
},
}
networkPolicy.Spec.Ingress = []networkingv1.NetworkPolicyIngressRule{
{
From: []networkingv1.NetworkPolicyPeer{
{
PodSelector: &metav1.LabelSelector{
// TODO: Replace below map with a function call to the to-be-introduced kubeapiserver package.
MatchLabels: map[string]string{
v1beta1constants.GardenRole: v1beta1constants.GardenRoleControlPlane,
v1beta1constants.LabelApp: v1beta1constants.LabelKubernetes,
v1beta1constants.LabelRole: v1beta1constants.LabelAPIServer,
},
},
},
{
PodSelector: &metav1.LabelSelector{
MatchLabels: monitoring.GetPrometheusLabels(),
},
},
},
Ports: []networkingv1.NetworkPolicyPort{
{
Protocol: &protocolTCP,
Port: &intStrPortEtcdClient,
},
{
Protocol: &protocolTCP,
Port: &intStrPortBackupRestore,
},
},
},
}
networkPolicy.Spec.Egress = nil
networkPolicy.Spec.PolicyTypes = []networkingv1.PolicyType{networkingv1.PolicyTypeIngress}
return nil
}); err != nil {
return err
}
if _, err := controllerutils.GetAndCreateOrMergePatch(ctx, e.client, e.etcd, func() error {
e.etcd.Annotations = map[string]string{
v1beta1constants.GardenerOperation: v1beta1constants.GardenerOperationReconcile,
v1beta1constants.GardenerTimestamp: TimeNow().UTC().String(),
}
e.etcd.Labels = map[string]string{
v1beta1constants.LabelRole: e.role,
v1beta1constants.GardenRole: v1beta1constants.GardenRoleControlPlane,
}
e.etcd.Spec.Replicas = replicas
e.etcd.Spec.PriorityClassName = pointer.String(v1beta1constants.PriorityClassNameShootControlPlane)
e.etcd.Spec.Annotations = annotations
e.etcd.Spec.Labels = utils.MergeStringMaps(e.getLabels(), map[string]string{
v1beta1constants.LabelApp: LabelAppValue,
v1beta1constants.LabelNetworkPolicyToDNS: v1beta1constants.LabelNetworkPolicyAllowed,
v1beta1constants.LabelNetworkPolicyToPublicNetworks: v1beta1constants.LabelNetworkPolicyAllowed,
v1beta1constants.LabelNetworkPolicyToPrivateNetworks: v1beta1constants.LabelNetworkPolicyAllowed,
v1beta1constants.LabelNetworkPolicyToSeedAPIServer: v1beta1constants.LabelNetworkPolicyAllowed,
})
e.etcd.Spec.Selector = &metav1.LabelSelector{
MatchLabels: utils.MergeStringMaps(e.getLabels(), map[string]string{
v1beta1constants.LabelApp: LabelAppValue,
}),
}
e.etcd.Spec.Etcd = druidv1alpha1.EtcdConfig{
Resources: resourcesEtcd,
TLS: &druidv1alpha1.TLSConfig{
TLSCASecretRef: corev1.SecretReference{
Name: e.secrets.CA.Name,
Namespace: e.namespace,
},
ServerTLSSecretRef: corev1.SecretReference{
Name: e.secrets.Server.Name,
Namespace: e.namespace,
},
ClientTLSSecretRef: corev1.SecretReference{
Name: e.secrets.Client.Name,
Namespace: e.namespace,
},
},
ServerPort: &PortEtcdServer,
ClientPort: &PortEtcdClient,
Metrics: &metrics,
DefragmentationSchedule: e.computeDefragmentationSchedule(existingEtcd),
Quota: "a,
}
e.etcd.Spec.Backup = druidv1alpha1.BackupSpec{
Port: &PortBackupRestore,
Resources: resourcesBackupRestore,
GarbageCollectionPolicy: &garbageCollectionPolicy,
GarbageCollectionPeriod: &garbageCollectionPeriod,
SnapshotCompression: &compressionSpec,
}
if e.backupConfig != nil {
var (
provider = druidv1alpha1.StorageProvider(e.backupConfig.Provider)
deltaSnapshotPeriod = metav1.Duration{Duration: 5 * time.Minute}
deltaSnapshotMemoryLimit = resource.MustParse("100Mi")
)
e.etcd.Spec.Backup.Store = &druidv1alpha1.StoreSpec{
SecretRef: &corev1.SecretReference{Name: e.backupConfig.SecretRefName},
Container: &e.backupConfig.Container,
Provider: &provider,
Prefix: fmt.Sprintf("%s/etcd-%s", e.backupConfig.Prefix, e.role),
}
e.etcd.Spec.Backup.FullSnapshotSchedule = e.computeFullSnapshotSchedule(existingEtcd)
e.etcd.Spec.Backup.DeltaSnapshotPeriod = &deltaSnapshotPeriod
e.etcd.Spec.Backup.DeltaSnapshotMemoryLimit = &deltaSnapshotMemoryLimit
}
if e.ownerCheckConfig != nil {
e.etcd.Spec.Backup.OwnerCheck = &druidv1alpha1.OwnerCheckSpec{
Name: e.ownerCheckConfig.Name,
ID: e.ownerCheckConfig.ID,
Interval: &metav1.Duration{Duration: 30 * time.Second},
Timeout: &metav1.Duration{Duration: 2 * time.Minute},
DNSCacheTTL: &metav1.Duration{Duration: 1 * time.Minute},
}
}
e.etcd.Spec.StorageCapacity = &storageCapacity
e.etcd.Spec.VolumeClaimTemplate = &volumeClaimTemplate
return nil
}); err != nil {
return err
}
if e.hvpaConfig != nil && e.hvpaConfig.Enabled {
var (
hpaLabels = map[string]string{v1beta1constants.LabelRole: "etcd-hpa-" + e.role}
vpaLabels = map[string]string{v1beta1constants.LabelRole: "etcd-vpa-" + e.role}
updateModeAuto = hvpav1alpha1.UpdateModeAuto
containerPolicyOff = autoscalingv1beta2.ContainerScalingModeOff
)
scaleDownUpdateMode := e.hvpaConfig.ScaleDownUpdateMode
if scaleDownUpdateMode == nil {
scaleDownUpdateMode = pointer.String(hvpav1alpha1.UpdateModeMaintenanceWindow)
}
if _, err := controllerutils.GetAndCreateOrMergePatch(ctx, e.client, hvpa, func() error {
hvpa.Labels = utils.MergeStringMaps(e.getLabels(), map[string]string{
v1beta1constants.LabelApp: LabelAppValue,
})
hvpa.Spec.Replicas = pointer.Int32(1)
hvpa.Spec.MaintenanceTimeWindow = &hvpav1alpha1.MaintenanceTimeWindow{
Begin: e.hvpaConfig.MaintenanceTimeWindow.Begin,
End: e.hvpaConfig.MaintenanceTimeWindow.End,
}
hvpa.Spec.Hpa = hvpav1alpha1.HpaSpec{
Selector: &metav1.LabelSelector{MatchLabels: hpaLabels},
Deploy: false,
Template: hvpav1alpha1.HpaTemplate{
ObjectMeta: metav1.ObjectMeta{
Labels: hpaLabels,
},
Spec: hvpav1alpha1.HpaTemplateSpec{
MinReplicas: pointer.Int32(int32(replicas)),
MaxReplicas: int32(replicas),
Metrics: []autoscalingv2beta1.MetricSpec{
{
Type: autoscalingv2beta1.ResourceMetricSourceType,
Resource: &autoscalingv2beta1.ResourceMetricSource{
Name: corev1.ResourceCPU,
TargetAverageUtilization: pointer.Int32(80),
},
},
{
Type: autoscalingv2beta1.ResourceMetricSourceType,
Resource: &autoscalingv2beta1.ResourceMetricSource{
Name: corev1.ResourceMemory,
TargetAverageUtilization: pointer.Int32(80),
},
},
},
},
},
}
hvpa.Spec.Vpa = hvpav1alpha1.VpaSpec{
Selector: &metav1.LabelSelector{MatchLabels: vpaLabels},
Deploy: true,
ScaleUp: hvpav1alpha1.ScaleType{
UpdatePolicy: hvpav1alpha1.UpdatePolicy{
UpdateMode: &updateModeAuto,
},
StabilizationDuration: pointer.String("5m"),
MinChange: hvpav1alpha1.ScaleParams{
CPU: hvpav1alpha1.ChangeParams{
Value: pointer.String("1"),
Percentage: pointer.Int32(80),
},
Memory: hvpav1alpha1.ChangeParams{
Value: pointer.String("2G"),
Percentage: pointer.Int32(80),
},
},
},
ScaleDown: hvpav1alpha1.ScaleType{
UpdatePolicy: hvpav1alpha1.UpdatePolicy{
UpdateMode: scaleDownUpdateMode,
},
StabilizationDuration: pointer.String("15m"),
MinChange: hvpav1alpha1.ScaleParams{
CPU: hvpav1alpha1.ChangeParams{
Value: pointer.String("1"),
Percentage: pointer.Int32(80),
},
Memory: hvpav1alpha1.ChangeParams{
Value: pointer.String("2G"),
Percentage: pointer.Int32(80),
},
},
},
LimitsRequestsGapScaleParams: hvpav1alpha1.ScaleParams{
CPU: hvpav1alpha1.ChangeParams{
Value: pointer.String("2"),
Percentage: pointer.Int32(40),
},
Memory: hvpav1alpha1.ChangeParams{
Value: pointer.String("5G"),
Percentage: pointer.Int32(40),
},
},
Template: hvpav1alpha1.VpaTemplate{
ObjectMeta: metav1.ObjectMeta{
Labels: vpaLabels,
},
Spec: hvpav1alpha1.VpaTemplateSpec{
ResourcePolicy: &autoscalingv1beta2.PodResourcePolicy{
ContainerPolicies: []autoscalingv1beta2.ContainerResourcePolicy{
{
ContainerName: containerNameEtcd,
MinAllowed: minAllowed,
MaxAllowed: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("4"),
corev1.ResourceMemory: resource.MustParse("30G"),
},
},
{
ContainerName: containerNameBackupRestore,
Mode: &containerPolicyOff,
},
},
},
},
},
}
hvpa.Spec.WeightBasedScalingIntervals = []hvpav1alpha1.WeightBasedScalingInterval{
{
VpaWeight: hvpav1alpha1.VpaOnly,
StartReplicaCount: int32(replicas),
LastReplicaCount: int32(replicas),
},
}
hvpa.Spec.TargetRef = &autoscalingv2beta1.CrossVersionObjectReference{
APIVersion: appsv1.SchemeGroupVersion.String(),
Kind: "StatefulSet",
Name: stsName,
}
return nil
}); err != nil {
return err
}
} else {
if err := kutil.DeleteObjects(ctx, e.client, hvpa); err != nil {
return err
}
}
return nil
}
func (e *etcd) Destroy(ctx context.Context) error {
if err := gutil.ConfirmDeletion(ctx, e.client, e.etcd); client.IgnoreNotFound(err) != nil {
return err
}
return kutil.DeleteObjects(
ctx,
e.client,
e.emptyHVPA(),
e.etcd,
e.emptyNetworkPolicy(),
)
}
func (e *etcd) getLabels() map[string]string {
return map[string]string{
v1beta1constants.DeprecatedGardenRole: v1beta1constants.GardenRoleControlPlane,
v1beta1constants.LabelRole: e.role,
}
}
func (e *etcd) emptyNetworkPolicy() *networkingv1.NetworkPolicy {
return &networkingv1.NetworkPolicy{ObjectMeta: metav1.ObjectMeta{Name: NetworkPolicyName, Namespace: e.namespace}}
}
func (e *etcd) emptyHVPA() *hvpav1alpha1.Hvpa {
return &hvpav1alpha1.Hvpa{ObjectMeta: metav1.ObjectMeta{Name: e.etcd.Name, Namespace: e.namespace}}
}
func (e *etcd) Snapshot(ctx context.Context, podExecutor kubernetes.PodExecutor) error {
if e.backupConfig == nil {
return fmt.Errorf("no backup is configured for this etcd, cannot make a snapshot")
}
etcdMainSelector := e.podLabelSelector()
podsList := &corev1.PodList{}
if err := e.client.List(ctx, podsList, client.InNamespace(e.namespace), client.MatchingLabelsSelector{Selector: etcdMainSelector}); err != nil {
return err
}
if len(podsList.Items) == 0 {
return fmt.Errorf("didn't find any pods for selector: %v", etcdMainSelector)
}
if len(podsList.Items) > 1 {
return fmt.Errorf("multiple ETCD Pods found. Pod list found: %v", podsList.Items)
}
_, err := podExecutor.Execute(
e.namespace,
podsList.Items[0].GetName(),
containerNameBackupRestore,
"/bin/sh",
fmt.Sprintf("curl -k https://etcd-%s-local:%d/snapshot/full?final=true", e.role, PortBackupRestore),
)
return err
}
func (e *etcd) ServiceDNSNames() []string {
return append(
[]string{fmt.Sprintf("etcd-%s-local", e.role)},
kutil.DNSNamesForService(fmt.Sprintf("etcd-%s-client", e.role), e.namespace)...,
)
}
// Get retrieves the Etcd resource
func (e *etcd) Get(ctx context.Context) (*druidv1alpha1.Etcd, error) {
if err := e.client.Get(ctx, client.ObjectKeyFromObject(e.etcd), e.etcd); err != nil {
return nil, err
}
return e.etcd, nil
}
func (e *etcd) SetSecrets(secrets Secrets) { e.secrets = secrets }
func (e *etcd) SetBackupConfig(backupConfig *BackupConfig) { e.backupConfig = backupConfig }
func (e *etcd) SetHVPAConfig(hvpaConfig *HVPAConfig) { e.hvpaConfig = hvpaConfig }
func (e *etcd) SetOwnerCheckConfig(ownerCheckConfig *OwnerCheckConfig) {
e.ownerCheckConfig = ownerCheckConfig
}
func (e *etcd) podLabelSelector() labels.Selector {
app, _ := labels.NewRequirement(v1beta1constants.LabelApp, selection.Equals, []string{LabelAppValue})
role, _ := labels.NewRequirement(v1beta1constants.LabelRole, selection.Equals, []string{e.role})
return labels.NewSelector().Add(*role, *app)
}
func (e *etcd) computeContainerResources(existingSts *appsv1.StatefulSet) (*corev1.ResourceRequirements, *corev1.ResourceRequirements) {
var (
resourcesEtcd = &corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("300m"),
corev1.ResourceMemory: resource.MustParse("1G"),
},
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("2300m"),
corev1.ResourceMemory: resource.MustParse("6G"),
},
}
resourcesBackupRestore = &corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("23m"),
corev1.ResourceMemory: resource.MustParse("128Mi"),
},
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("1"),
corev1.ResourceMemory: resource.MustParse("10G"),
},
}
)
if existingSts != nil && e.hvpaConfig != nil && e.hvpaConfig.Enabled {
for k := range existingSts.Spec.Template.Spec.Containers {
v := existingSts.Spec.Template.Spec.Containers[k]
switch v.Name {
case containerNameEtcd:
resourcesEtcd = v.Resources.DeepCopy()
case containerNameBackupRestore:
resourcesBackupRestore = v.Resources.DeepCopy()
}
}
}
return resourcesEtcd, resourcesBackupRestore
}
func (e *etcd) computeReplicas(existingEtcd *druidv1alpha1.Etcd) int {
if !e.retainReplicas {
return 1
}
if existingEtcd != nil {
return existingEtcd.Spec.Replicas
}
return 0
}
func (e *etcd) computeDefragmentationSchedule(existingEtcd *druidv1alpha1.Etcd) *string {
defragmentationSchedule := e.defragmentationSchedule
if existingEtcd != nil && existingEtcd.Spec.Etcd.DefragmentationSchedule != nil {
defragmentationSchedule = existingEtcd.Spec.Etcd.DefragmentationSchedule
}
return defragmentationSchedule
}
func (e *etcd) computeFullSnapshotSchedule(existingEtcd *druidv1alpha1.Etcd) *string {
fullSnapshotSchedule := &e.backupConfig.FullSnapshotSchedule
if existingEtcd != nil && existingEtcd.Spec.Backup.FullSnapshotSchedule != nil {
fullSnapshotSchedule = existingEtcd.Spec.Backup.FullSnapshotSchedule
}
return fullSnapshotSchedule
}
// Secrets is collection of secrets for the etcd.
type Secrets struct {
// CA is a secret containing the CA certificate and key.
CA component.Secret
// Server is a secret containing the server certificate and key.
Server component.Secret
// Client is a secret containing the client certificate and key.
Client component.Secret
}
// BackupConfig contains information for configuring the backup-restore sidecar so that it takes regularly backups of
// the etcd's data directory.
type BackupConfig struct {
// Provider is the name of the infrastructure provider for the blob storage bucket.
Provider string
// Container is the name of the blob storage bucket.
Container string
// SecretRefName is the name of a Secret object containing the credentials of the selected infrastructure provider.
SecretRefName string
// Prefix is a prefix that shall be used for the filename of the backups of this etcd.
Prefix string
// FullSnapshotSchedule is a cron schedule that declares how frequent full snapshots shall be taken.
FullSnapshotSchedule string
}
// HVPAConfig contains information for configuring the HVPA object for the etcd.
type HVPAConfig struct {
// Enabled states whether an HVPA object shall be deployed.
Enabled bool
// MaintenanceTimeWindow contains begin and end of a time window that allows down-scaling the etcd in case its
// resource requests/limits are unnecessarily high.
MaintenanceTimeWindow gardencorev1beta1.MaintenanceTimeWindow
// The update mode to use for scale down.
ScaleDownUpdateMode *string
}
// OwnerCheckConfig contains parameters related to checking if the seed is an owner
// of the shoot. The ownership can change during control plane migration.
type OwnerCheckConfig struct {
// Name is the domain name of the owner DNS record.
Name string
// ID is the seed ID value that is expected to be found in the owner DNS record.
ID string
}
| {
etcdLog = logger.WithField("etcd", client.ObjectKey{Namespace: namespace, Name: name})
} |
Cities.js | import React from 'react'
import PropTypes from 'prop-types'
class Cities extends React.Component {
constructor (props) {
super(props)
}
render () {
const { cities, increment } = this.props
return ( | <button className='btn btn-primary' onClick={increment}>
Increment
</button>
</div>
)
}
}
Cities.propTypes = {
increment: PropTypes.func.isRequired,
cities: PropTypes.object.isRequired
}
export default Cities | <div style={{ margin: '0 auto' }}>
<h2>Counter: { cities.counter }</h2> |
User.test.ts | import request from 'supertest';
import { getConnection } from 'typeorm';
import { app } from '../app';
import createConnection from '../database'
// é o que acontece no /Surveys.test.ts
// Começo do bloco de testes
describe("User", () => {
beforeAll(async () => { // Isso aqui é pra começar os testes, antes de tudo é necessário criar um banco de dados
const connection = await createConnection(); // pra poder fazer os testes sem danificar o BD da aplicação.
await connection.runMigrations();
});
afterAll(async () => { // Aqui é ele falando que depois de tudo, é necessário dropar a DB de testes criada.
const connection = getConnection();
await connection.dropDatabase();
await connection.close();
});
// Primeiro teste
it("Should be able to create a new user", async () => { // Esse teste é para criar um novo usuário. Pra isso,
const response = await request(app).post("/users") // a rota "/users" é acessada no método POST e espera-se
.send({ // que a o status da resposta seja 201, de 'criado'.
email: "[email protected]",
name: "User Example"
});
expect(response.status).toBe(201);
});
// Segundo teste
it("Should not be able to create a user with an email which a already exists", async () => {
const response = await request(app).post("/users") // Já esse segundo teste é pra não deixar criar um usuário
.send({ // com um email já usado. Pra isso, ele cria um usuário igual | expect(response.status).toBe(400);
})
}); | email: "[email protected]", // o do teste 1, e espera-se que o status da resposta seja 400.
name: "User Example"
});
|
surface_distance.py | # Copyright 2020 - 2021 MONAI Consortium
# 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 warnings
from typing import Union
import numpy as np
import torch
from monai.metrics.utils import *
from monai.utils import MetricReduction
class | :
"""
Compute Surface Distance between two tensors. It can support both multi-classes and multi-labels tasks.
It supports both symmetric and asymmetric surface distance calculation.
Input `y_pred` (BNHW[D] where N is number of classes) is compared with ground truth `y` (BNHW[D]).
`y_preds` is expected to have binarized predictions and `y` should be in one-hot format.
You can use suitable transforms in ``monai.transforms.post`` first to achieve binarized values.
Args:
include_background: whether to skip distance computation on the first channel of
the predicted output. Defaults to ``False``.
symmetric: whether to calculate the symmetric average surface distance between
`seg_pred` and `seg_gt`. Defaults to ``False``.
distance_metric: : [``"euclidean"``, ``"chessboard"``, ``"taxicab"``]
the metric used to compute surface distance. Defaults to ``"euclidean"``.
reduction: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``,
``"mean_channel"``, ``"sum_channel"``}
Define the mode to reduce computation result of 1 batch data. Defaults to ``"mean"``.
"""
def __init__(
self,
include_background: bool = False,
symmetric: bool = False,
distance_metric: str = "euclidean",
reduction: Union[MetricReduction, str] = MetricReduction.MEAN,
) -> None:
super().__init__()
self.include_background = include_background
self.distance_metric = distance_metric
self.symmetric = symmetric
self.reduction = reduction
def __call__(self, y_pred: torch.Tensor, y: torch.Tensor):
"""
Args:
y_pred: input data to compute, typical segmentation model output.
It must be one-hot format and first dim is batch, example shape: [16, 3, 32, 32]. The values
should be binarized.
y: ground truth to compute the distance. It must be one-hot format and first dim is batch.
The values should be binarized.
Raises:
ValueError: when `y` is not a binarized tensor.
ValueError: when `y_pred` has less than three dimensions.
"""
if not torch.all(y_pred.byte() == y_pred):
warnings.warn("y_pred is not a binarized tensor here!")
if not torch.all(y.byte() == y):
raise ValueError("y should be a binarized tensor.")
dims = y_pred.ndimension()
if dims < 3:
raise ValueError("y_pred should have at least three dimensions.")
# compute (BxC) for each channel for each batch
f = compute_average_surface_distance(
y_pred=y_pred,
y=y,
include_background=self.include_background,
symmetric=self.symmetric,
distance_metric=self.distance_metric,
)
# do metric reduction
f, not_nans = do_metric_reduction(f, self.reduction)
return f, not_nans
def compute_average_surface_distance(
y_pred: Union[np.ndarray, torch.Tensor],
y: Union[np.ndarray, torch.Tensor],
include_background: bool = False,
symmetric: bool = False,
distance_metric: str = "euclidean",
):
"""
This function is used to compute the Average Surface Distance from `y_pred` to `y`
under the default setting.
In addition, if sets ``symmetric = True``, the average symmetric surface distance between
these two inputs will be returned.
Args:
y_pred: input data to compute, typical segmentation model output.
It must be one-hot format and first dim is batch, example shape: [16, 3, 32, 32]. The values
should be binarized.
y: ground truth to compute mean the distance. It must be one-hot format and first dim is batch.
The values should be binarized.
include_background: whether to skip distance computation on the first channel of
the predicted output. Defaults to ``False``.
symmetric: whether to calculate the symmetric average surface distance between
`seg_pred` and `seg_gt`. Defaults to ``False``.
distance_metric: : [``"euclidean"``, ``"chessboard"``, ``"taxicab"``]
the metric used to compute surface distance. Defaults to ``"euclidean"``.
"""
if not include_background:
y_pred, y = ignore_background(
y_pred=y_pred,
y=y,
)
y = y.float()
y_pred = y_pred.float()
if y.shape != y_pred.shape:
raise ValueError("y_pred and y should have same shapes.")
batch_size, n_class = y_pred.shape[:2]
asd = np.empty((batch_size, n_class))
for b, c in np.ndindex(batch_size, n_class):
(edges_pred, edges_gt) = get_mask_edges(y_pred[b, c], y[b, c])
surface_distance = get_surface_distance(edges_pred, edges_gt, distance_metric=distance_metric)
if surface_distance.shape == (0,):
avg_surface_distance = np.nan
else:
avg_surface_distance = surface_distance.mean()
if not symmetric:
asd[b, c] = avg_surface_distance
else:
surface_distance_2 = get_surface_distance(edges_gt, edges_pred, distance_metric=distance_metric)
if surface_distance_2.shape == (0,):
avg_surface_distance_2 = np.nan
else:
avg_surface_distance_2 = surface_distance_2.mean()
asd[b, c] = np.mean((avg_surface_distance, avg_surface_distance_2))
return torch.from_numpy(asd)
| SurfaceDistanceMetric |
index.js | import './style.css';
import React from 'react';
import ContactLinks from '../../components/ContactLinks';
import contactBaby from '../../assets/images/contact/cool-baby-square.PNG';
import cloudFade from '../../assets/images/contact/cloudfade.JPG';
export default function | () {
return (
<div className='page-body' id='contact-page'>
<div className='page-header'>contact.</div>
<ContactLinks />
<div className='blurb-flex'>
<p id='blurb1' className='contact-blurb'>Have you ever had a dream, that you were so sure was real? </p>
<p id='blurb2' className='contact-blurb'>What if you were unable to wake from that dream? </p>
<p id='blurb3' className='contact-blurb'>How would you know the difference between the dream world and real world?</p>
<img id='contact-baby' alt='' src={contactBaby}/>
</div>
<img className='fade-img' alt='' src={cloudFade}/>
</div>
);
}
| Contact |
cairo_png.rs | //! # Cairo drawing to PNG
//!
//! This sample demonstrates how to create `ImageSurface`, draw on it
//! and then save result to PNG file.
//! Analog of C# example http://www.mgsloan.com/cairo_tut/stroke.cs
extern crate cairo;
use std::fs::File;
use cairo::{Context, Format, ImageSurface};
fn main() | {
let surface = ImageSurface::create(Format::ARgb32, 120, 120).expect("Can't create surface");
let cr = Context::new(&surface);
// Examples are in 1.0 x 1.0 coordinate space
cr.scale(120.0, 120.0);
// Drawing code goes here
cr.set_line_width(0.1);
cr.set_source_rgb(0.0, 0.0, 0.0);
cr.rectangle(0.25, 0.25, 0.5, 0.5);
cr.stroke();
let mut file = File::create("file.png").expect("Couldn't create 'file.png'");
match surface.write_to_png(&mut file) {
Ok(_) => println!("file.png created"),
Err(_) => println!("Error create file.png"),
}
} |
|
bash_completions.go | package cobra
import (
"fmt"
"io"
"os"
"sort"
"strings"
"github.com/spf13/pflag"
)
const (
BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extentions"
BashCompCustom = "cobra_annotation_bash_completion_custom"
BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"
)
func preamble(out io.Writer, name string) error {
_, err := fmt.Fprintf(out, "# bash completion for %-36s -*- shell-script -*-\n", name)
if err != nil {
return err
}
_, err = fmt.Fprint(out, `
__debug()
{
if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
fi
}
# Homebrew on Macs have version 1.3 of bash-completion which doesn't include
# _init_completion. This is a very minimal version of that function.
__my_init_completion()
{
COMPREPLY=()
_get_comp_words_by_ref "$@" cur prev words cword
}
__index_of_word()
{
local w word=$1
shift
index=0
for w in "$@"; do
[[ $w = "$word" ]] && return
index=$((index+1))
done
index=-1
}
__contains_word()
{
local w word=$1; shift
for w in "$@"; do
[[ $w = "$word" ]] && return
done
return 1
}
__handle_reply()
{
__debug "${FUNCNAME[0]}"
case $cur in
-*)
if [[ $(type -t compopt) = "builtin" ]]; then
compopt -o nospace
fi
local allflags
if [ ${#must_have_one_flag[@]} -ne 0 ]; then
allflags=("${must_have_one_flag[@]}")
else
allflags=("${flags[*]} ${two_word_flags[*]}")
fi
COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") )
if [[ $(type -t compopt) = "builtin" ]]; then
[[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace
fi
# complete after --flag=abc
if [[ $cur == *=* ]]; then
if [[ $(type -t compopt) = "builtin" ]]; then
compopt +o nospace
fi
local index flag
flag="${cur%%=*}"
__index_of_word "${flag}" "${flags_with_completion[@]}"
if [[ ${index} -ge 0 ]]; then
COMPREPLY=()
PREFIX=""
cur="${cur#*=}"
${flags_completion[${index}]}
if [ -n "${ZSH_VERSION}" ]; then
# zfs completion needs --flag= prefix
eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"
fi
fi
fi
return 0;
;;
esac
# check if we are handling a flag with special work handling
local index
__index_of_word "${prev}" "${flags_with_completion[@]}"
if [[ ${index} -ge 0 ]]; then
${flags_completion[${index}]}
return
fi
# we are parsing a flag and don't have a special handler, no completion
if [[ ${cur} != "${words[cword]}" ]]; then
return
fi
local completions
completions=("${commands[@]}")
if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
completions=("${must_have_one_noun[@]}")
fi
if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
completions+=("${must_have_one_flag[@]}")
fi
COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") )
if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then
COMPREPLY=( $(compgen -W "${noun_aliases[*]}" -- "$cur") )
fi
if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
declare -F __custom_func >/dev/null && __custom_func
fi
__ltrim_colon_completions "$cur"
}
# The arguments should be in the form "ext1|ext2|extn"
__handle_filename_extension_flag()
{
local ext="$1"
_filedir "@(${ext})"
}
__handle_subdirs_in_dir_flag()
{
local dir="$1"
pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1
}
__handle_flag()
{
__debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
# if a command required a flag, and we found it, unset must_have_one_flag()
local flagname=${words[c]}
local flagvalue
# if the word contained an =
if [[ ${words[c]} == *"="* ]]; then
flagvalue=${flagname#*=} # take in as flagvalue after the =
flagname=${flagname%%=*} # strip everything after the =
flagname="${flagname}=" # but put the = back
fi
__debug "${FUNCNAME[0]}: looking for ${flagname}"
if __contains_word "${flagname}" "${must_have_one_flag[@]}"; then
must_have_one_flag=()
fi
# if you set a flag which only applies to this command, don't show subcommands
if __contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then
commands=()
fi
# keep flag value with flagname as flaghash
if [ -n "${flagvalue}" ] ; then
flaghash[${flagname}]=${flagvalue}
elif [ -n "${words[ $((c+1)) ]}" ] ; then
flaghash[${flagname}]=${words[ $((c+1)) ]}
else
flaghash[${flagname}]="true" # pad "true" for bool flag
fi
# skip the argument to a two word flag
if __contains_word "${words[c]}" "${two_word_flags[@]}"; then
c=$((c+1))
# if we are looking for a flags value, don't show commands
if [[ $c -eq $cword ]]; then
commands=()
fi
fi
c=$((c+1))
}
__handle_noun()
{
__debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then
must_have_one_noun=()
elif __contains_word "${words[c]}" "${noun_aliases[@]}"; then
must_have_one_noun=()
fi
nouns+=("${words[c]}")
c=$((c+1))
}
__handle_command()
{
__debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
local next_command
if [[ -n ${last_command} ]]; then
next_command="_${last_command}_${words[c]//:/__}"
else
if [[ $c -eq 0 ]]; then
next_command="_$(basename "${words[c]//:/__}")"
else
next_command="_${words[c]//:/__}"
fi
fi
c=$((c+1))
__debug "${FUNCNAME[0]}: looking for ${next_command}"
declare -F $next_command >/dev/null && $next_command
}
__handle_word()
{
if [[ $c -ge $cword ]]; then
__handle_reply
return
fi
__debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
if [[ "${words[c]}" == -* ]]; then
__handle_flag
elif __contains_word "${words[c]}" "${commands[@]}"; then
__handle_command
elif [[ $c -eq 0 ]] && __contains_word "$(basename "${words[c]}")" "${commands[@]}"; then
__handle_command
else
__handle_noun
fi
__handle_word
}
`)
return err
}
func postscript(w io.Writer, name string) error {
name = strings.Replace(name, ":", "__", -1)
_, err := fmt.Fprintf(w, "__start_%s()\n", name)
if err != nil {
return err
}
_, err = fmt.Fprintf(w, `{
local cur prev words cword
declare -A flaghash 2>/dev/null || :
if declare -F _init_completion >/dev/null 2>&1; then
_init_completion -s || return
else
__my_init_completion -n "=" || return
fi
local c=0
local flags=()
local two_word_flags=()
local local_nonpersistent_flags=()
local flags_with_completion=()
local flags_completion=()
local commands=("%s")
local must_have_one_flag=()
local must_have_one_noun=()
local last_command
local nouns=()
__handle_word
}
`, name)
if err != nil {
return err
}
_, err = fmt.Fprintf(w, `if [[ $(type -t compopt) = "builtin" ]]; then
complete -o default -F __start_%s %s
else
complete -o default -o nospace -F __start_%s %s
fi
`, name, name, name, name)
if err != nil {
return err
}
_, err = fmt.Fprintf(w, "# ex: ts=4 sw=4 et filetype=sh\n")
return err
}
func writeCommands(cmd *Command, w io.Writer) error {
if _, err := fmt.Fprintf(w, " commands=()\n"); err != nil {
return err
}
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() || c == cmd.helpCommand {
continue
}
if _, err := fmt.Fprintf(w, " commands+=(%q)\n", c.Name()); err != nil {
return err
}
}
_, err := fmt.Fprintf(w, "\n")
return err
}
func writeFlagHandler(name string, annotations map[string][]string, w io.Writer) error {
for key, value := range annotations {
switch key {
case BashCompFilenameExt:
_, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name)
if err != nil {
return err
}
if len(value) > 0 {
ext := "__handle_filename_extension_flag " + strings.Join(value, "|")
_, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", ext)
} else {
ext := "_filedir"
_, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", ext)
}
if err != nil {
return err
}
case BashCompCustom:
_, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name)
if err != nil {
return err
}
if len(value) > 0 {
handlers := strings.Join(value, "; ")
_, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", handlers)
} else {
_, err = fmt.Fprintf(w, " flags_completion+=(:)\n")
}
if err != nil {
return err
}
case BashCompSubdirsInDir:
_, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name)
if len(value) == 1 {
ext := "__handle_subdirs_in_dir_flag " + value[0]
_, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", ext)
} else {
ext := "_filedir -d"
_, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", ext)
}
if err != nil {
return err
}
}
}
return nil
}
func writeShortFlag(flag *pflag.Flag, w io.Writer) error {
b := (len(flag.NoOptDefVal) > 0)
name := flag.Shorthand
format := " "
if !b {
format += "two_word_"
}
format += "flags+=(\"-%s\")\n"
if _, err := fmt.Fprintf(w, format, name); err != nil {
return err
}
return writeFlagHandler("-"+name, flag.Annotations, w)
}
func | (flag *pflag.Flag, w io.Writer) error {
b := (len(flag.NoOptDefVal) > 0)
name := flag.Name
format := " flags+=(\"--%s"
if !b {
format += "="
}
format += "\")\n"
if _, err := fmt.Fprintf(w, format, name); err != nil {
return err
}
return writeFlagHandler("--"+name, flag.Annotations, w)
}
func writeLocalNonPersistentFlag(flag *pflag.Flag, w io.Writer) error {
b := (len(flag.NoOptDefVal) > 0)
name := flag.Name
format := " local_nonpersistent_flags+=(\"--%s"
if !b {
format += "="
}
format += "\")\n"
if _, err := fmt.Fprintf(w, format, name); err != nil {
return err
}
return nil
}
func writeFlags(cmd *Command, w io.Writer) error {
_, err := fmt.Fprintf(w, ` flags=()
two_word_flags=()
local_nonpersistent_flags=()
flags_with_completion=()
flags_completion=()
`)
if err != nil {
return err
}
localNonPersistentFlags := cmd.LocalNonPersistentFlags()
var visitErr error
cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
if err := writeFlag(flag, w); err != nil {
visitErr = err
return
}
if len(flag.Shorthand) > 0 {
if err := writeShortFlag(flag, w); err != nil {
visitErr = err
return
}
}
if localNonPersistentFlags.Lookup(flag.Name) != nil {
if err := writeLocalNonPersistentFlag(flag, w); err != nil {
visitErr = err
return
}
}
})
if visitErr != nil {
return visitErr
}
cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
if err := writeFlag(flag, w); err != nil {
visitErr = err
return
}
if len(flag.Shorthand) > 0 {
if err := writeShortFlag(flag, w); err != nil {
visitErr = err
return
}
}
})
if visitErr != nil {
return visitErr
}
_, err = fmt.Fprintf(w, "\n")
return err
}
func writeRequiredFlag(cmd *Command, w io.Writer) error {
if _, err := fmt.Fprintf(w, " must_have_one_flag=()\n"); err != nil {
return err
}
flags := cmd.NonInheritedFlags()
var visitErr error
flags.VisitAll(func(flag *pflag.Flag) {
for key := range flag.Annotations {
switch key {
case BashCompOneRequiredFlag:
format := " must_have_one_flag+=(\"--%s"
b := (flag.Value.Type() == "bool")
if !b {
format += "="
}
format += "\")\n"
if _, err := fmt.Fprintf(w, format, flag.Name); err != nil {
visitErr = err
return
}
if len(flag.Shorthand) > 0 {
if _, err := fmt.Fprintf(w, " must_have_one_flag+=(\"-%s\")\n", flag.Shorthand); err != nil {
visitErr = err
return
}
}
}
}
})
return visitErr
}
func writeRequiredNouns(cmd *Command, w io.Writer) error {
if _, err := fmt.Fprintf(w, " must_have_one_noun=()\n"); err != nil {
return err
}
sort.Sort(sort.StringSlice(cmd.ValidArgs))
for _, value := range cmd.ValidArgs {
if _, err := fmt.Fprintf(w, " must_have_one_noun+=(%q)\n", value); err != nil {
return err
}
}
return nil
}
func writeArgAliases(cmd *Command, w io.Writer) error {
if _, err := fmt.Fprintf(w, " noun_aliases=()\n"); err != nil {
return err
}
sort.Sort(sort.StringSlice(cmd.ArgAliases))
for _, value := range cmd.ArgAliases {
if _, err := fmt.Fprintf(w, " noun_aliases+=(%q)\n", value); err != nil {
return err
}
}
return nil
}
func gen(cmd *Command, w io.Writer) error {
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() || c == cmd.helpCommand {
continue
}
if err := gen(c, w); err != nil {
return err
}
}
commandName := cmd.CommandPath()
commandName = strings.Replace(commandName, " ", "_", -1)
commandName = strings.Replace(commandName, ":", "__", -1)
if _, err := fmt.Fprintf(w, "_%s()\n{\n", commandName); err != nil {
return err
}
if _, err := fmt.Fprintf(w, " last_command=%q\n", commandName); err != nil {
return err
}
if err := writeCommands(cmd, w); err != nil {
return err
}
if err := writeFlags(cmd, w); err != nil {
return err
}
if err := writeRequiredFlag(cmd, w); err != nil {
return err
}
if err := writeRequiredNouns(cmd, w); err != nil {
return err
}
if err := writeArgAliases(cmd, w); err != nil {
return err
}
if _, err := fmt.Fprintf(w, "}\n\n"); err != nil {
return err
}
return nil
}
func (cmd *Command) GenBashCompletion(w io.Writer) error {
if err := preamble(w, cmd.Name()); err != nil {
return err
}
if len(cmd.BashCompletionFunction) > 0 {
if _, err := fmt.Fprintf(w, "%s\n", cmd.BashCompletionFunction); err != nil {
return err
}
}
if err := gen(cmd, w); err != nil {
return err
}
return postscript(w, cmd.Name())
}
func (cmd *Command) GenBashCompletionFile(filename string) error {
outFile, err := os.Create(filename)
if err != nil {
return err
}
defer outFile.Close()
return cmd.GenBashCompletion(outFile)
}
// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag, if it exists.
func (cmd *Command) MarkFlagRequired(name string) error {
return MarkFlagRequired(cmd.Flags(), name)
}
// MarkPersistentFlagRequired adds the BashCompOneRequiredFlag annotation to the named persistent flag, if it exists.
func (cmd *Command) MarkPersistentFlagRequired(name string) error {
return MarkFlagRequired(cmd.PersistentFlags(), name)
}
// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag in the flag set, if it exists.
func MarkFlagRequired(flags *pflag.FlagSet, name string) error {
return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"})
}
// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag, if it exists.
// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
func (cmd *Command) MarkFlagFilename(name string, extensions ...string) error {
return MarkFlagFilename(cmd.Flags(), name, extensions...)
}
// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.
// Generated bash autocompletion will call the bash function f for the flag.
func (cmd *Command) MarkFlagCustom(name string, f string) error {
return MarkFlagCustom(cmd.Flags(), name, f)
}
// MarkPersistentFlagFilename adds the BashCompFilenameExt annotation to the named persistent flag, if it exists.
// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
func (cmd *Command) MarkPersistentFlagFilename(name string, extensions ...string) error {
return MarkFlagFilename(cmd.PersistentFlags(), name, extensions...)
}
// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag in the flag set, if it exists.
// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error {
return flags.SetAnnotation(name, BashCompFilenameExt, extensions)
}
// MarkFlagCustom adds the BashCompCustom annotation to the named flag in the flag set, if it exists.
// Generated bash autocompletion will call the bash function f for the flag.
func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error {
return flags.SetAnnotation(name, BashCompCustom, []string{f})
}
| writeFlag |
ui_customization_unit.js | /** @license
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
describe('UI Customization', () => {
const UiUtils = shaka.test.UiUtils;
/** @type {!Element} */
let cssLink;
/** @type {!HTMLElement} */
let container;
/** @type {!HTMLMediaElement} */
let video;
beforeAll(async () => {
// Add css file
cssLink = document.createElement('link');
await UiUtils.setupCSS(cssLink);
});
afterEach(async () => {
await UiUtils.cleanupUI();
});
afterAll(() => {
document.head.removeChild(cssLink);
});
beforeEach(() => {
container =
/** @type {!HTMLElement} */ (document.createElement('div'));
document.body.appendChild(container);
video = shaka.test.UiUtils.createVideoElement();
container.appendChild(video);
});
it('only the specified controls are created', () => {
const config = {controlPanelElements: ['time_and_duration', 'mute']};
UiUtils.createUIThroughAPI(container, video, config);
// Only current time and mute button should've been created
UiUtils.confirmElementFound(container, 'shaka-current-time');
UiUtils.confirmElementFound(container, 'shaka-mute-button');
UiUtils.confirmElementMissing(container, 'shaka-volume-bar');
UiUtils.confirmElementMissing(container, 'shaka-fullscreen-button');
UiUtils.confirmElementMissing(container, 'shaka-overflow-menu-button');
});
it('only the specified overflow menu buttons are created', () => {
const config = {overflowMenuButtons: ['cast']};
UiUtils.createUIThroughAPI(container, video, config);
UiUtils.confirmElementFound(container, 'shaka-cast-button');
UiUtils.confirmElementMissing(container, 'shaka-caption-button');
});
it('seek bar only created when configured', () => {
UiUtils.createUIThroughAPI(container, video, {addSeekBar: false});
UiUtils.confirmElementMissing(container, 'shaka-seek-bar');
UiUtils.createUIThroughAPI(container, video, {addSeekBar: true});
UiUtils.confirmElementFound(container, 'shaka-seek-bar');
});
it('big play button only created when configured', () => {
UiUtils.createUIThroughAPI(container, video, {addBigPlayButton: false});
UiUtils.confirmElementMissing(container, 'shaka-play-button-container');
UiUtils.confirmElementMissing(container, 'shaka-play-button');
UiUtils.createUIThroughAPI(container, video, {addBigPlayButton: true});
UiUtils.confirmElementFound(container, 'shaka-play-button-container');
UiUtils.confirmElementFound(container, 'shaka-play-button');
});
it('settings menus are positioned lower when seek bar is absent', () => {
const config = {addSeekBar: false};
UiUtils.createUIThroughAPI(container, video, config);
function | (className) {
const elements =
container.getElementsByClassName(className);
expect(elements.length).toBe(1);
expect(
elements[0].classList.contains('shaka-low-position')).toBe(true);
}
UiUtils.confirmElementMissing(container, 'shaka-seek-bar');
confirmLowPosition('shaka-overflow-menu');
confirmLowPosition('shaka-resolutions');
confirmLowPosition('shaka-audio-languages');
confirmLowPosition('shaka-text-languages');
});
it('controls are created in specified order', () => {
const config = {
controlPanelElements: [
'mute',
'time_and_duration',
'fullscreen',
],
};
UiUtils.createUIThroughAPI(container, video, config);
const controlsButtonPanels =
container.getElementsByClassName('shaka-controls-button-panel');
expect(controlsButtonPanels.length).toBe(1);
const controlsButtonPanel =
/** @type {!HTMLElement} */ (controlsButtonPanels[0]);
const buttons = controlsButtonPanel.childNodes;
expect(buttons.length).toBe(3);
expect( /** @type {!HTMLElement} */ (buttons[0]).className)
.toContain('shaka-mute-button');
expect( /** @type {!HTMLElement} */ (buttons[1]).className)
.toContain('shaka-current-time');
expect( /** @type {!HTMLElement} */ (buttons[2]).className)
.toContain('shaka-fullscreen');
});
it('layout can be re-configured after the creation', async () => {
const config = {controlPanelElements: ['time_and_duration', 'mute']};
const ui = UiUtils.createUIThroughAPI(container, video, config);
// Only current time and mute button should've been created
UiUtils.confirmElementFound(container, 'shaka-current-time');
UiUtils.confirmElementFound(container, 'shaka-mute-button');
UiUtils.confirmElementFound(container, 'shaka-seek-bar');
UiUtils.confirmElementMissing(container, 'shaka-volume-bar');
UiUtils.confirmElementMissing(container, 'shaka-fullscreen-button');
UiUtils.confirmElementMissing(container, 'shaka-overflow-menu-button');
// Reconfigure the layout
const newConfig = {
controlPanelElements: [
'volume',
'fullscreen',
],
addSeekBar: false,
};
const eventManager = new shaka.util.EventManager();
const waiter = new shaka.test.Waiter(eventManager);
const controls = ui.getControls();
goog.asserts.assert(controls != null, 'Should have a controls object!');
const p = waiter.waitForEvent(controls, 'uiupdated');
ui.configure(newConfig);
// Wait for the change to take effect
await p;
// New elements should be there
UiUtils.confirmElementFound(container, 'shaka-volume-bar');
UiUtils.confirmElementFound(container, 'shaka-fullscreen-button');
// Old elements should not be there
UiUtils.confirmElementMissing(container, 'shaka-current-time');
UiUtils.confirmElementMissing(container, 'shaka-mute-button');
UiUtils.confirmElementMissing(container, 'shaka-seek-bar');
});
// Regression for #1948
it('cast proxy and controls are unchanged by reconfiguration', async () => {
const config = {controlPanelElements: ['time_and_duration', 'mute']};
/** @type {!shaka.ui.Overlay} */
const ui = UiUtils.createUIThroughAPI(container, video, config);
const eventManager = new shaka.util.EventManager();
const waiter = new shaka.test.Waiter(eventManager);
// Save controls and cast proxy objects
const controls = ui.getControls();
const castProxy = controls.getCastProxy();
goog.asserts.assert(controls != null, 'Should have a controls object!');
const p = waiter.waitForEvent(controls, 'uiupdated');
const newConfig = {controlPanelElements: ['volume']};
ui.configure(newConfig);
// Wait for the change to take effect
// The fact that this resolves is implicit proof that the controls
// object stayed the same, but we check it again below to be explicit.
await p;
const newControls = ui.getControls();
const newCastProxy = newControls.getCastProxy();
expect(newControls).toBe(controls);
expect(newCastProxy).toBe(castProxy);
});
});
| confirmLowPosition |
param_config_gen.py | import json
import os
import warnings
from pathlib import Path
from typing import Union, Dict, Any
from .parameter_matrix_parsing import ParameterMatrixProxy
class ParamConfigGenerator:
FIXED_KEY = "fixed_params"
SHARED_KEY = "shared_params"
DEPENDENT_KEY = "dependent_params"
OPTIMIZED_KEY = "optimized_params"
HEURISTIC_MAPPING_KEY = "__heuristic_function_mapping"
OVERWRITES_KEY = "__algorithm_overwrites"
def __init__(self, matrix_path: Union[str, Path]):
self.pmp = ParameterMatrixProxy(matrix_path)
def generate_template(self, target: Union[str, Path]) -> None:
target = Path(target)
config = {
self.FIXED_KEY: self.pmp.fixed_params(),
self.SHARED_KEY: self.pmp.shared_params(),
self.DEPENDENT_KEY: self.pmp.dependent_params(),
self.OPTIMIZED_KEY: self.pmp.optimized_params(),
self.HEURISTIC_MAPPING_KEY: {},
self.OVERWRITES_KEY: {}
}
self._write(config, target)
def generate(self, target: Union[str, Path], overwrite: bool = False) -> None:
target = Path(target)
if overwrite or not target.exists():
self.generate_template(target)
return
config = {}
if target.exists() and target.is_file():
with target.open("r") as fh:
config = json.load(fh)
config[self.FIXED_KEY] = self.pmp.fixed_params()
if self.SHARED_KEY in config:
self._merge_shared(config)
else:
config[self.SHARED_KEY] = self.pmp.shared_params()
config[self.DEPENDENT_KEY] = self.pmp.dependent_params()
if self.OPTIMIZED_KEY in config:
self._merge_optimized(config)
else:
config[self.OPTIMIZED_KEY] = self.pmp.optimized_params()
self._write(config, target)
def _merge_shared(self, config: Dict[str, Any]) -> None:
shared_params = config[self.SHARED_KEY]
new_shared_params = self.pmp.shared_params()
params = set(list(shared_params.keys()) + list(new_shared_params.keys()))
for param in params:
if param in shared_params and param in new_shared_params:
shared_params[param]["algorithms"] = new_shared_params[param]["algorithms"]
shared_params[param]["search_space"] = new_shared_params[param]["search_space"]
elif param not in shared_params:
shared_params[param] = new_shared_params[param]
else: # param not in new_shared_params:
del shared_params[param]
config[self.SHARED_KEY] = shared_params
def _merge_optimized(self, config: Dict[str, Any]) -> None:
|
@staticmethod
def _write(config: Dict[str, Any], target: Path) -> None:
with target.open("w") as fh:
json.dump(config, fh, sort_keys=True, indent=2)
fh.write(os.linesep)
if __name__ == "__main__":
p = ParamConfigGenerator("timeeval_experiments/parameter-matrix.csv")
p.generate("timeeval_experiments/params.json")
| optim_params = config[self.OPTIMIZED_KEY]
new_optim_params = self.pmp.optimized_params()
params = set(list(optim_params.keys()) + list(new_optim_params.keys()))
for param in params:
if param not in new_optim_params:
del optim_params[param]
continue
if param in new_optim_params:
new_param_config = new_optim_params[param]
if isinstance(new_param_config, dict) and "MANUAL" in new_param_config.values():
if param in optim_params and isinstance(optim_params[param], dict):
warnings.warn(f"{self.OPTIMIZED_KEY}: Found 'MANUAL' marker for parameter {param}. "
"Using existing value(s).")
param_config = optim_params[param]
to_change_algos = []
for algo in new_param_config:
if new_param_config[algo] == "MANUAL" and algo not in param_config:
to_change_algos.append(algo)
for algo in to_change_algos:
param_config[algo] = new_param_config[algo]
warnings.warn(f"{self.OPTIMIZED_KEY}: Found 'MANUAL' marker for parameter {param} and "
f"algorithm {algo}. Please set value(s) after the generation step manually!")
continue
else:
warnings.warn(f"{self.OPTIMIZED_KEY}: Found 'MANUAL' marker for parameter {param}. Please "
"set value(s) after the generation step manually!")
# for everything else:
optim_params[param] = new_optim_params[param]
config[self.OPTIMIZED_KEY] = optim_params |
number.go | // Package types contains structs/interfaces representing TypeScript types
package types
import "github.com/go-generalize/go-easyparser/types"
// RawNumberEnumCandidate represents a raw candidate for number enum
// Deprecated: github.com/go-generalize/go-easyparser/types.RawNumberEnumCandidate
type RawNumberEnumCandidate = types.RawNumberEnumCandidate
// Number - number in TypeScript
// Deprecated: github.com/go-generalize/go-easyparser/types.Number | type Number = types.Number |
|
server.go | // Copyright 2020 Google LLC
//
// 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.
// Package mirror implements the export file mirroring job.
package mirror
import (
"context"
"fmt"
"github.com/google/exposure-notifications-server/internal/middleware"
mirrordb "github.com/google/exposure-notifications-server/internal/mirror/database"
"github.com/google/exposure-notifications-server/internal/serverenv"
"github.com/google/exposure-notifications-server/pkg/database"
"github.com/google/exposure-notifications-server/pkg/logging"
"github.com/google/exposure-notifications-server/pkg/render"
"github.com/google/exposure-notifications-server/pkg/server"
"github.com/gorilla/mux"
)
// Server hosts end points to manage key rotation
type Server struct {
config *Config
env *serverenv.ServerEnv
db *database.DB
mirrorDB *mirrordb.MirrorDB
h *render.Renderer
}
// NewServer creates a Server that manages deletion of
// old export files that are no longer needed by clients for download.
func | (config *Config, env *serverenv.ServerEnv) (*Server, error) {
if env.Database() == nil {
return nil, fmt.Errorf("missing database in server environment")
}
if env.Blobstore() == nil {
return nil, fmt.Errorf("missing blobstore in server environment")
}
db := env.Database()
mdb := mirrordb.New(db)
return &Server{
config: config,
env: env,
db: db,
mirrorDB: mdb,
h: render.NewRenderer(),
}, nil
}
// Routes defines and returns the routes for this server.
func (s *Server) Routes(ctx context.Context) *mux.Router {
logger := logging.FromContext(ctx).Named("mirror")
r := mux.NewRouter()
r.Use(middleware.Recovery())
r.Use(middleware.PopulateRequestID())
r.Use(middleware.PopulateObservability())
r.Use(middleware.PopulateLogger(logger))
r.Handle("/health", server.HandleHealthz(s.env.Database()))
r.Handle("/", s.handleMirror())
return r
}
| NewServer |
main.go | package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/reusee/e/v2"
"github.com/rjeczalik/notify"
)
var (
pt = fmt.Printf
me = e.Default.WithStack().WithName("afftesting")
ce, he = e.New(me)
)
type (
M = map[string]interface{}
)
func init() {
go func() {
c := make(chan notify.EventInfo, 32)
for _, watchDir := range []string{
".", "./aff",
} {
if err := notify.Watch(watchDir, c, notify.Create, notify.Write); err != nil {
panic(err)
}
defer notify.Stop(c)
pt("watching %s\n", watchDir)
}
build:
buildUI()
wait:
ev := <-c
path := ev.Path()
if !strings.HasSuffix(path, ".ts") {
goto wait
}
after := time.NewTimer(time.Millisecond * 50)
batch:
for {
select {
case ev := <-c:
_ = ev
if !after.Stop() {
<-after.C
}
after.Reset(time.Millisecond * 50)
case <-after.C:
break batch
}
}
goto build
}()
}
func copyDir(src, dest string) error {
stat, err := os.Stat(src)
if err != nil {
return err
}
if stat.IsDir() {
stat, err = os.Stat(dest)
if os.IsNotExist(err) {
if err := os.Mkdir(dest, 0655); err != nil {
return err
}
} else if !stat.IsDir() {
return fmt.Errorf("%s is not dir", dest)
}
f, err := os.Open(src)
if err != nil {
return err
}
defer f.Close()
names, err := f.Readdirnames(-1)
if err != nil {
return err
}
for _, name := range names {
if err := copyDir(
filepath.Join(src, name),
filepath.Join(dest, name),
); err != nil {
return err
}
}
} else {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dest)
if err != nil {
return err
}
defer out.Close()
if _, err := io.Copy(out, in); err != nil {
return err
}
}
return nil
}
func buildUI() {
t0 := time.Now()
pt("%v rebuilding...", time.Now().Format("15:04:05.000000"))
os.Stdout.Sync()
d1 := "build"
cmd := exec.Command("tsc",
"--build", "tsconfig.json",
)
if out, err := cmd.CombinedOutput(); err != nil {
pt("build error: %v\n", err)
pt("%s\n", out)
return
}
// istanbul coverage
d2 := "static"
if out, err := exec.Command(
"nyc", "instrument",
d1, d2,
).CombinedOutput(); err != nil {
pt("%v\n", err)
pt("%s\n", out)
return
}
pt("done in %v\n", time.Since(t0))
waits.Lock()
for _, c := range waits.waits {
close(c)
}
waits.waits = waits.waits[0:0]
waits.Unlock()
}
type Dir struct {
dir http.Dir
}
func (d Dir) Open(filename string) (http.File, error) {
if filename != "/" {
ext := path.Ext(filename)
if ext == "" {
filename = filename + ".js"
}
}
return d.dir.Open(filename)
}
var waits struct {
sync.Mutex
waits []chan bool
}
func handleWait(w http.ResponseWriter, req *http.Request) {
c := make(chan bool)
waits.Lock()
waits.waits = append(waits.waits, c)
waits.Unlock()
<-c
}
func handleInit(w http.ResponseWriter, req *http.Request) {
ce(json.NewEncoder(w).Encode(M{
"Now": time.Now().Format("2006-01-02 15:04:05.000"),
}))
}
func handleCoverage(w http.ResponseWriter, req *http.Request) {
pt("%s coverage report\n", time.Now().Format("15:04:05"))
cmd := exec.Command(
"remap-istanbul",
"-o", filepath.Join("..", ".nyc_output", "cover.json"),
)
cmd.Dir = "build"
cmd.Stdin = req.Body
out, err := cmd.CombinedOutput()
if err != nil || bytes.Contains(out, []byte("Error")) {
pt("%s\n", out)
pt("%v\n", err)
return
}
cmd = exec.Command(
"nyc", "report",
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
pt("%v\n", err)
}
}
func | () {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(Dir{http.Dir("static")}))
mux.HandleFunc("/wait", handleWait)
mux.HandleFunc("/init", handleInit)
mux.HandleFunc("/coverage", handleCoverage)
pt("open localhost:23456 in browser to run tests\n")
if err := http.ListenAndServe(":23456", mux); err != nil {
panic(err)
}
}
| main |
stddev.go | package indicators
//#include "../tulipindicators/indicators/stddev.c"
import "C"
import "fmt"
// STDDEV function wraps `stddev' function that provides "Standard Deviation Over Period"
//
// Reference: https://tulipindicators.org/stddev
func STDDEV(real []float64, period int) (stddev []float64, err error) { | input_length := len(real)
options := []float64{float64(period)}
option_input := (*C.double)(&options[0])
start, err := C.ti_stddev_start(option_input)
if err != nil {
return
}
all_input_data := newIndicatorData(input_length, 1)
all_input_data.Set([][]float64{real})
defer all_input_data.Destroy()
output_length := input_length - int(start)
all_output_data := newIndicatorData(output_length, 1)
defer all_output_data.Destroy()
ret, err := C.ti_stddev(
(C.int)(input_length),
(**C.double)(all_input_data.buffer),
(*C.double)(&options[0]),
(**C.double)(all_output_data.buffer),
)
if err != nil {
return
}
if ret != C.TI_OKAY {
err = fmt.Errorf("ret = %d", ret)
return
}
outputs := all_output_data.Get()
stddev = outputs[0]
return
} | |
shootout-nbody.rs | use std::f64;
use std::from_str::FromStr;
use std::os;
use std::uint::range;
use std::vec;
static PI: f64 = 3.141592653589793;
static SOLAR_MASS: f64 = 4.0 * PI * PI;
static YEAR: f64 = 365.24;
static N_BODIES: uint = 5;
static BODIES: [Planet, ..N_BODIES] = [
// Sun
Planet {
x: [ 0.0, 0.0, 0.0 ],
v: [ 0.0, 0.0, 0.0 ],
mass: SOLAR_MASS,
},
// Jupiter
Planet {
x: [
4.84143144246472090e+00,
-1.16032004402742839e+00,
-1.03622044471123109e-01,
],
v: [
1.66007664274403694e-03 * YEAR,
7.69901118419740425e-03 * YEAR,
-6.90460016972063023e-05 * YEAR,
],
mass: 9.54791938424326609e-04 * SOLAR_MASS,
},
// Saturn
Planet {
x: [
8.34336671824457987e+00,
4.12479856412430479e+00,
-4.03523417114321381e-01,
],
v: [
-2.76742510726862411e-03 * YEAR,
4.99852801234917238e-03 * YEAR,
2.30417297573763929e-05 * YEAR,
],
mass: 2.85885980666130812e-04 * SOLAR_MASS,
},
// Uranus
Planet {
x: [
1.28943695621391310e+01,
-1.51111514016986312e+01,
-2.23307578892655734e-01,
],
v: [
2.96460137564761618e-03 * YEAR,
2.37847173959480950e-03 * YEAR,
-2.96589568540237556e-05 * YEAR,
],
mass: 4.36624404335156298e-05 * SOLAR_MASS,
},
// Neptune
Planet {
x: [
1.53796971148509165e+01,
-2.59193146099879641e+01,
1.79258772950371181e-01,
],
v: [
2.68067772490389322e-03 * YEAR,
1.62824170038242295e-03 * YEAR,
-9.51592254519715870e-05 * YEAR,
],
mass: 5.15138902046611451e-05 * SOLAR_MASS,
},
];
struct Planet {
x: [f64, ..3],
v: [f64, ..3],
mass: f64,
}
fn advance(bodies: &mut [Planet, ..N_BODIES], dt: f64, steps: i32) {
let mut d = [ 0.0, ..3 ];
for (steps as uint).times {
for range(0, N_BODIES) |i| {
for range(i + 1, N_BODIES) |j| {
d[0] = bodies[i].x[0] - bodies[j].x[0];
d[1] = bodies[i].x[1] - bodies[j].x[1];
d[2] = bodies[i].x[2] - bodies[j].x[2];
let d2 = d[0]*d[0] + d[1]*d[1] + d[2]*d[2];
let mag = dt / (d2 * f64::sqrt(d2));
let a_mass = bodies[i].mass;
let b_mass = bodies[j].mass;
bodies[i].v[0] -= d[0] * b_mass * mag;
bodies[i].v[1] -= d[1] * b_mass * mag;
bodies[i].v[2] -= d[2] * b_mass * mag;
bodies[j].v[0] += d[0] * a_mass * mag;
bodies[j].v[1] += d[1] * a_mass * mag;
bodies[j].v[2] += d[2] * a_mass * mag;
}
}
for bodies.mut_iter().advance |a| {
a.x[0] += dt * a.v[0];
a.x[1] += dt * a.v[1];
a.x[2] += dt * a.v[2];
}
}
}
fn energy(bodies: &[Planet, ..N_BODIES]) -> f64 |
}
e
}
fn offset_momentum(bodies: &mut [Planet, ..N_BODIES]) {
for range(0, N_BODIES) |i| {
for range(0, 3) |k| {
bodies[0].v[k] -= bodies[i].v[k] * bodies[i].mass / SOLAR_MASS;
}
}
}
fn main() {
let n: i32 = FromStr::from_str(os::args()[1]).get();
let mut bodies = BODIES;
offset_momentum(&mut bodies);
println(fmt!("%.9f", energy(&bodies) as float));
advance(&mut bodies, 0.01, n);
println(fmt!("%.9f", energy(&bodies) as float));
}
| {
let mut e = 0.0;
let mut d = [ 0.0, ..3 ];
for range(0, N_BODIES) |i| {
for range(0, 3) |k| {
e += bodies[i].mass * bodies[i].v[k] * bodies[i].v[k] / 2.0;
}
for range(i + 1, N_BODIES) |j| {
for range(0, 3) |k| {
d[k] = bodies[i].x[k] - bodies[j].x[k];
}
let dist = f64::sqrt(d[0]*d[0] + d[1]*d[1] + d[2]*d[2]);
e -= bodies[i].mass * bodies[j].mass / dist;
} |
outbound.rs | use std::collections::HashMap;
use flatbuffers_gen::runner_outbound_msg_generated::root_as_runner_outbound_msg;
use super::TargetedRunnerTaskMsg;
use crate::{
hash_types::worker,
proto::SimulationShortId,
types::TaskId,
worker::{runner::comms::SentTask, Error, Result},
Language,
};
#[derive(Debug, Default, Clone)]
pub struct RunnerError {
pub message: Option<String>,
pub details: Option<String>,
pub file_name: Option<String>,
pub line_number: Option<i32>,
}
impl RunnerError {
pub fn into_sendable(self, is_warning: bool) -> worker::RunnerError {
worker::RunnerError {
message: self.message,
code: None,
line_number: self.line_number,
file_name: self.file_name,
details: self.details,
is_warning,
is_internal: false,
}
}
}
impl From<flatbuffers_gen::runner_error_generated::RunnerError<'_>> for RunnerError {
fn from(runner_error: flatbuffers_gen::runner_error_generated::RunnerError<'_>) -> Self {
Self {
message: runner_error.msg().map(|msg| msg.to_string()),
// TODO: these are currently not encapsulated within the Flatbuffers
details: None,
file_name: None,
line_number: None,
}
}
}
impl From<flatbuffers_gen::runner_warning_generated::RunnerWarning<'_>> for RunnerError {
fn from(runner_warning: flatbuffers_gen::runner_warning_generated::RunnerWarning<'_>) -> Self {
Self {
message: Some(runner_warning.msg().to_string()),
details: runner_warning.details().map(|details| details.to_string()),
// TODO: these are currently not encapsulated within the Flatbuffers
file_name: None,
line_number: None,
}
}
}
#[derive(Debug)]
pub enum OutboundFromRunnerMsgPayload {
TaskMsg(TargetedRunnerTaskMsg),
TaskCancelled(TaskId),
RunnerError(RunnerError),
RunnerErrors(Vec<RunnerError>),
RunnerWarning(RunnerError),
RunnerWarnings(Vec<RunnerError>),
RunnerLog(String),
RunnerLogs(Vec<String>),
/* TODO: add
* PackageError
* UserErrors
* UserWarnings */
}
impl OutboundFromRunnerMsgPayload {
pub fn try_from_fbs(
parsed_msg: flatbuffers_gen::runner_outbound_msg_generated::RunnerOutboundMsg<'_>,
sent_tasks: &mut HashMap<TaskId, SentTask>,
) -> Result<Self> {
Ok(match parsed_msg.payload_type() {
flatbuffers_gen::runner_outbound_msg_generated::RunnerOutboundMsgPayload::NONE => |
flatbuffers_gen::runner_outbound_msg_generated::RunnerOutboundMsgPayload::TaskMsg => {
let payload = parsed_msg.payload_as_task_msg().ok_or_else(|| {
Error::from(
"Message from runner should have had a TaskMsg payload but it was missing",
)
})?;
Self::TaskMsg(TargetedRunnerTaskMsg::try_from_fbs(payload, sent_tasks)?)
}
flatbuffers_gen::runner_outbound_msg_generated::RunnerOutboundMsgPayload::TaskCancelled => {
let payload = parsed_msg.payload_as_task_cancelled().ok_or_else(|| {
Error::from(
"Message from runner should have had a TaskCancelled payload but it was \
missing",
)
})?;
let task_id = payload.task_id().ok_or_else(|| {
Error::from("Message from runner should have had a task_id but it was missing")
})?;
Self::TaskCancelled(uuid::Uuid::from_slice(&task_id.0)?.as_u128())
}
flatbuffers_gen::runner_outbound_msg_generated::RunnerOutboundMsgPayload::RunnerError => {
let payload = parsed_msg.payload_as_runner_error().ok_or_else(|| {
Error::from(
"Message from runner should have had a RunnerError payload but it was \
missing",
)
})?;
Self::RunnerError(payload.into())
}
flatbuffers_gen::runner_outbound_msg_generated::RunnerOutboundMsgPayload::RunnerErrors => {
let payload = parsed_msg.payload_as_runner_errors().ok_or_else(|| {
Error::from(
"Message from runner should have had a RunnerErrors payload but it was \
missing",
)
})?;
let runner_errors = payload
.inner()
.iter()
.map(|runner_error| runner_error.into())
.collect();
Self::RunnerErrors(runner_errors)
}
flatbuffers_gen::runner_outbound_msg_generated::RunnerOutboundMsgPayload::RunnerWarning => {
let payload = parsed_msg.payload_as_runner_warning().ok_or_else(|| {
Error::from(
"Message from runner should have had a RunnerWarning payload but it was \
missing",
)
})?;
Self::RunnerWarning(payload.into())
}
flatbuffers_gen::runner_outbound_msg_generated::RunnerOutboundMsgPayload::RunnerWarnings => {
let payload = parsed_msg.payload_as_runner_warnings().ok_or_else(|| {
Error::from(
"Message from runner should have had a RunnerWarnings payload but it was \
missing",
)
})?;
let runner_warnings = payload
.inner()
.iter()
.map(|runner_warning| runner_warning.into())
.collect();
Self::RunnerWarnings(runner_warnings)
}
flatbuffers_gen::runner_outbound_msg_generated::RunnerOutboundMsgPayload::PackageError => {
let _payload = parsed_msg.payload_as_package_error().ok_or_else(|| {
Error::from(
"Message from runner should have had a PackageError payload but it was \
missing",
)
})?;
todo!() // TODO: there is no Self::PackageError
}
flatbuffers_gen::runner_outbound_msg_generated::RunnerOutboundMsgPayload::UserErrors => {
let _payload = parsed_msg.payload_as_user_errors().ok_or_else(|| {
Error::from(
"Message from runner should have had a UserErrors payload but it was \
missing",
)
})?;
todo!() // TODO: there is no Self::UserErrors
}
flatbuffers_gen::runner_outbound_msg_generated::RunnerOutboundMsgPayload::UserWarnings => {
let _payload = parsed_msg.payload_as_user_warnings().ok_or_else(|| {
Error::from(
"Message from runner should have had a UserWarnings payload but it was \
missing",
)
})?;
todo!() // TODO: there is no Self::UserWarnings
}
_ => return Err(Error::from("Invalid outbound flatbuffers message payload")),
})
}
}
#[derive(Debug)]
pub struct OutboundFromRunnerMsg {
pub source: Language,
pub sim_id: SimulationShortId,
pub payload: OutboundFromRunnerMsgPayload,
// shared state
}
impl OutboundFromRunnerMsg {
pub fn try_from_nng(
msg: nng::Message,
source: Language,
sent_tasks: &mut HashMap<TaskId, SentTask>,
) -> Result<Self> {
let msg = msg.as_slice();
let msg = root_as_runner_outbound_msg(msg);
let msg = msg.map_err(|err| {
Error::from(format!(
"Flatbuffers failed to parse message bytes as a RunnerOutboundMsg: {err}"
))
})?;
let payload = OutboundFromRunnerMsgPayload::try_from_fbs(msg, sent_tasks)?;
Ok(Self {
source,
sim_id: msg.sim_sid(),
payload,
})
}
}
| {
return Err(Error::from("Message from runner had no payload"));
} |
ionic.bundle.min.js | /*!
* ionic.bundle.js is a concatenation of:
* ionic.js, angular.js, angular-animate.js,
* angular-sanitize.js, angular-ui-router.js,
* and ionic-angular.js
*/
/*!
* Copyright 2014 Drifty Co.
* http://drifty.com/
*
* Ionic, v1.1.1
* A powerful HTML5 mobile app framework.
* http://ionicframework.com/
*
* By @maxlynch, @benjsperry, @adamdbradley <3
*
* Licensed under the MIT license. Please see LICENSE for more information.
*
*/
!function(){function e(e,t,n){t!==!1?F.addEventListener(e,J[e],n):F.removeEventListener(e,J[e])}function t(e){var t=T(e.target),i=E(t);if(ionic.tap.requiresNativeClick(i)||$)return!1;var o=ionic.tap.pointerCoord(e);n("click",i,o.x,o.y),h(i)}function n(e,t,n,i){var o=document.createEvent("MouseEvents");o.initMouseEvent(e,!0,!0,window,1,0,0,n,i,!1,!1,!1,!1,0,null),o.isIonicTap=!0,t.dispatchEvent(o)}function i(e){return"submit"==e.target.type&&0===e.detail?null:ionic.scroll.isScrolling&&ionic.tap.containsOrIsTextInput(e.target)||!e.isIonicTap&&!ionic.tap.requiresNativeClick(e.target)?(e.stopPropagation(),ionic.tap.isLabelWithTextInput(e.target)||e.preventDefault(),!1):void 0}function o(t){return t.isIonicTap||_(t)?null:X?(t.stopPropagation(),ionic.tap.isTextInput(t.target)&&B===t.target||/^(select|option)$/i.test(t.target.tagName)||t.preventDefault(),!1):($=!1,U=ionic.tap.pointerCoord(t),e("mousemove"),void ionic.activator.start(t))}function r(n){return X?(n.stopPropagation(),n.preventDefault(),!1):_(n)||/^(select|option)$/i.test(n.target.tagName)?!1:(v(n)||t(n),e("mousemove",!1),ionic.activator.end(),void($=!1))}function s(t){return v(t)?(e("mousemove",!1),ionic.activator.end(),$=!0,!1):void 0}function a(t){if(!_(t)&&($=!1,d(),U=ionic.tap.pointerCoord(t),e(K),ionic.activator.start(t),ionic.Platform.isIOS()&&ionic.tap.isLabelWithTextInput(t.target))){var n=E(T(t.target));n!==Y&&t.preventDefault()}}function l(e){_(e)||(d(),v(e)||(t(e),/^(select|option)$/i.test(e.target.tagName)&&e.preventDefault()),B=e.target,u())}function c(t){return v(t)?($=!0,e(K,!1),ionic.activator.end(),!1):void 0}function u(){e(K,!1),ionic.activator.end(),$=!1}function d(){X=!0,clearTimeout(W),W=setTimeout(function(){X=!1},600)}function _(e){return e.isTapHandled?!0:(e.isTapHandled=!0,ionic.scroll.isScrolling&&ionic.tap.containsOrIsTextInput(e.target)?(e.preventDefault(),!0):void 0)}function h(e){q=null;var t=!1;"SELECT"==e.tagName?(n("mousedown",e,0,0),e.focus&&e.focus(),t=!0):g()===e?t=!0:/^(input|textarea)$/i.test(e.tagName)||e.isContentEditable?(t=!0,e.focus&&e.focus(),e.value=e.value,X&&(q=e)):f(),t&&(g(e),ionic.trigger("ionic.focusin",{target:e},!0))}function f(){var e=g();e&&(/^(input|textarea|select)$/i.test(e.tagName)||e.isContentEditable)&&e.blur(),g(null)}function p(e){X&&ionic.tap.isTextInput(g())&&ionic.tap.isTextInput(q)&&q!==e.target&&(q.focus(),q=null),ionic.scroll.isScrolling=!1}function m(){g(null)}function g(e){return arguments.length&&(Y=e),Y||document.activeElement}function v(e){if(!e||1!==e.target.nodeType||!U||0===U.x&&0===U.y)return!1;var t=ionic.tap.pointerCoord(e),n=!(!e.target.classList||!e.target.classList.contains||"function"!=typeof e.target.classList.contains),i=n&&e.target.classList.contains("button")?j:Z;return Math.abs(U.x-t.x)>i||Math.abs(U.y-t.y)>i}function T(e,t){for(var n=e,i=0;6>i&&n;i++){if("LABEL"===n.tagName)return n;n=n.parentElement}return t!==!1?e:void 0}function E(e){if(e&&"LABEL"===e.tagName){if(e.control)return e.control;if(e.querySelector){var t=e.querySelector("input,textarea,select");if(t)return t}}return e}function S(){ionic.keyboard.isInitialized||(V()?(window.addEventListener("native.keyboardshow",ue),window.addEventListener("native.keyboardhide",y)):document.body.addEventListener("focusout",y),document.body.addEventListener("ionic.focusin",ce),document.body.addEventListener("focusin",ce),window.navigator.msPointerEnabled?document.removeEventListener("MSPointerDown",S):document.removeEventListener("touchstart",S),ionic.keyboard.isInitialized=!0)}function b(e){clearTimeout(ne),(!ionic.keyboard.isOpen||ionic.keyboard.isClosing)&&(ionic.keyboard.isOpening=!0,ionic.keyboard.isClosing=!1),ionic.keyboard.height=e.keyboardHeight,se?M(A,!0):M(I,!0)}function w(e){return clearTimeout(ne),e.target&&!e.target.readOnly&&ionic.tap.isKeyboardElement(e.target)&&(ee=ionic.DomUtil.getParentWithClass(e.target,le))?(Q=e.target,ee.classList.contains("overflow-scroll")||(document.body.scrollTop=0,ee.scrollTop=0,ionic.requestAnimationFrame(function(){document.body.scrollTop=0,ee.scrollTop=0}),window.navigator.msPointerEnabled?document.addEventListener("MSPointerMove",x,!1):document.addEventListener("touchmove",x,!1)),(!ionic.keyboard.isOpen||ionic.keyboard.isClosing)&&(ionic.keyboard.isOpening=!0,ionic.keyboard.isClosing=!1),document.addEventListener("keydown",L,!1),void(ionic.keyboard.isOpen||V()?ionic.keyboard.isOpen&&I():M(I,!0))):void(Q=null)}function y(){clearTimeout(ne),(ionic.keyboard.isOpen||ionic.keyboard.isOpening)&&(ionic.keyboard.isClosing=!0,ionic.keyboard.isOpening=!1),ne=setTimeout(function(){ionic.requestAnimationFrame(function(){se?M(function(){A(),N()},!1):M(N,!1)})},50)}function D(){ionic.keyboard.isLandscape=!ionic.keyboard.isLandscape,ionic.Platform.isIOS()&&A(),ionic.Platform.isAndroid()&&(ionic.keyboard.isOpen&&V()?se=!0:M(A,!1))}function L(e){ionic.scroll.isScrolling&&x(e)}function x(e){"TEXTAREA"!==e.target.tagName&&e.preventDefault()}function M(e,t){clearInterval(te);var n,i=0,o=k(),r=o;return n=ionic.Platform.isAndroid()&&ionic.Platform.version()<4.4?30:ionic.Platform.isAndroid()?10:1,te=setInterval(function(){r=k(),(!(++i<n)||(O(r)||P(r))&&ionic.keyboard.height)&&(V()||(ionic.keyboard.height=Math.abs(o-window.innerHeight)),ionic.keyboard.isOpen=t,clearInterval(te),e())},50),n}function N(){clearTimeout(ne),ionic.keyboard.isOpen=!1,ionic.keyboard.isClosing=!1,Q&&ionic.trigger("resetScrollView",{target:Q},!0),ionic.requestAnimationFrame(function(){document.body.classList.remove(ae)}),window.navigator.msPointerEnabled?document.removeEventListener("MSPointerMove",x):document.removeEventListener("touchmove",x),document.removeEventListener("keydown",L),ionic.Platform.isAndroid()&&(V()&&cordova.plugins.Keyboard.close(),Q&&Q.blur()),Q=null}function I(){ionic.keyboard.isOpen=!0,ionic.keyboard.isOpening=!1;var e={keyboardHeight:C(),viewportHeight:ie};if(Q){e.target=Q;var t=Q.getBoundingClientRect();e.elementTop=Math.round(t.top),e.elementBottom=Math.round(t.bottom),e.windowHeight=e.viewportHeight-e.keyboardHeight,e.isElementUnderKeyboard=e.elementBottom>e.windowHeight,ionic.trigger("scrollChildIntoView",e,!0)}return setTimeout(function(){document.body.classList.add(ae)},400),e}function C(){if(ionic.keyboard.height)return ionic.keyboard.height;if(ionic.Platform.isAndroid()){if(ionic.Platform.isFullScreen)return 275;var e=window.innerHeight;return ie>e?ie-e:0}return ionic.Platform.isIOS()?ionic.keyboard.isLandscape?206:ionic.Platform.isWebView()?260:216:275}function O(e){return!!(!ionic.keyboard.isLandscape&&oe&&Math.abs(oe-e)<2)}function P(e){return!!(ionic.keyboard.isLandscape&&re&&Math.abs(re-e)<2)}function A(){se=!1,ie=k(),ionic.keyboard.isLandscape&&!re?re=ie:ionic.keyboard.isLandscape||oe||(oe=ie),Q&&ionic.trigger("resetScrollView",{target:Q},!0),ionic.keyboard.isOpen&&ionic.tap.isTextInput(Q)&&I()}function G(){var e=k();e/window.innerWidth<1&&(ionic.keyboard.isLandscape=!0),ie=e,ionic.keyboard.isLandscape&&!re?re=ie:ionic.keyboard.isLandscape||oe||(oe=ie)}function k(){var e=window.innerHeight;return ionic.Platform.isAndroid()&&ionic.Platform.isFullScreen||!ionic.keyboard.isOpen&&!ionic.keyboard.isOpening||ionic.keyboard.isClosing?e:e+C()}function V(){return!!(window.cordova&&cordova.plugins&&cordova.plugins.Keyboard)}function R(){var e;for(e=0;e<document.head.children.length;e++)if("viewport"==document.head.children[e].name){de=document.head.children[e];break}if(de){var t,n=de.content.toLowerCase().replace(/\s+/g,"").split(",");for(e=0;e<n.length;e++)n[e]&&(t=n[e].split("="),_e[t[0]]=t.length>1?t[1]:"_");z()}}function z(){var e=_e.width,t=_e.height,n=ionic.Platform,i=n.version(),o="device-width",r="device-height",s=ionic.viewport.orientation();delete _e.height,_e.width=o,n.isIPad()?i>7?delete _e.width:n.isWebView()?90==s?_e.height="0":7==i&&(_e.height=r):7>i&&(_e.height="0"):n.isIOS()&&(n.isWebView()?i>7?delete _e.width:7>i?t&&(_e.height="0"):7==i&&(_e.height=r):7>i&&t&&(_e.height="0")),(e!==_e.width||t!==_e.height)&&H()}function H(){var e,t=[];for(e in _e)_e[e]&&t.push(e+("_"==_e[e]?"":"="+_e[e]));de.content=t.join(", ")}window.ionic=window.ionic||{},window.ionic.views={},window.ionic.version="1.1.1",function(e){e.DelegateService=function(e){function t(){return!0}if(e.indexOf("$getByHandle")>-1)throw new Error("Method '$getByHandle' is implicitly added to each delegate service. Do not list it as a method.");return["$log",function(n){function i(e,t){this._instances=e,this.handle=t}function o(){this._instances=[]}function r(e){return function(){var t,i=this.handle,o=arguments,r=0;return this._instances.forEach(function(n){if((!i||i==n.$$delegateHandle)&&n.$$filterFn(n)){r++;var s=n[e].apply(n,o);1===r&&(t=s)}}),!r&&i?n.warn('Delegate for handle "'+i+'" could not find a corresponding element with delegate-handle="'+i+'"! '+e+"() was not called!\nPossible cause: If you are calling "+e+'() immediately, and your element with delegate-handle="'+i+'" is a child of your controller, then your element may not be compiled yet. Put a $timeout around your call to '+e+"() and try again."):t}}return e.forEach(function(e){i.prototype[e]=r(e)}),o.prototype=i.prototype,o.prototype._registerInstance=function(e,n,i){var o=this._instances;return e.$$delegateHandle=n,e.$$filterFn=i||t,o.push(e),function(){var t=o.indexOf(e);-1!==t&&o.splice(t,1)}},o.prototype.$getByHandle=function(e){return new i(this._instances,e)},new o}]}}(window.ionic),function(e,t,n){function i(){r=!0;for(var e=0;e<o.length;e++)n.requestAnimationFrame(o[e]);o=[],t.removeEventListener("DOMContentLoaded",i)}var o=[],r="complete"===t.readyState||"interactive"===t.readyState;r||t.addEventListener("DOMContentLoaded",i),e._rAF=function(){return e.requestAnimationFrame||e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||function(t){e.setTimeout(t,16)}}();var s=e.cancelAnimationFrame||e.webkitCancelAnimationFrame||e.mozCancelAnimationFrame||e.webkitCancelRequestAnimationFrame;n.DomUtil={requestAnimationFrame:function(t){return e._rAF(t)},cancelAnimationFrame:function(e){s(e)},animationFrameThrottle:function(e){var t,i,o;return function(){t=arguments,o=this,i||(i=!0,n.requestAnimationFrame(function(){e.apply(o,t),i=!1}))}},contains:function(e,t){for(var n=t;n;){if(n===e)return!0;n=n.parentNode}},getPositionInParent:function(e){return{left:e.offsetLeft,top:e.offsetTop}},ready:function(e){r?n.requestAnimationFrame(e):o.push(e)},getTextBounds:function(n){if(t.createRange){var i=t.createRange();if(i.selectNodeContents(n),i.getBoundingClientRect){var o=i.getBoundingClientRect();if(o){var r=e.scrollX,s=e.scrollY;return{top:o.top+s,left:o.left+r,right:o.left+r+o.width,bottom:o.top+s+o.height,width:o.width,height:o.height}}}}return null},getChildIndex:function(e,t){if(t)for(var n,i=e.parentNode.children,o=0,r=0,s=i.length;s>o;o++)if(n=i[o],n.nodeName&&n.nodeName.toLowerCase()==t){if(n==e)return r;r++}return Array.prototype.slice.call(e.parentNode.children).indexOf(e)},swapNodes:function(e,t){t.parentNode.insertBefore(e,t)},elementIsDescendant:function(e,t,n){var i=e;do{if(i===t)return!0;i=i.parentNode}while(i&&i!==n);return!1},getParentWithClass:function(e,t,n){for(n=n||10;e.parentNode&&n--;){if(e.parentNode.classList&&e.parentNode.classList.contains(t))return e.parentNode;e=e.parentNode}return null},getParentOrSelfWithClass:function(e,t,n){for(n=n||10;e&&n--;){if(e.classList&&e.classList.contains(t))return e;e=e.parentNode}return null},rectContains:function(e,t,n,i,o,r){return n>e||e>o?!1:i>t||t>r?!1:!0},blurAll:function(){return t.activeElement&&t.activeElement!=t.body?(t.activeElement.blur(),t.activeElement):null},cachedAttr:function(e,t,n){if(e=e&&e.length&&e[0]||e,e&&e.setAttribute){var i="$attr-"+t;return arguments.length>2?e[i]!==n&&(e.setAttribute(t,n),e[i]=n):"undefined"==typeof e[i]&&(e[i]=e.getAttribute(t)),e[i]}},cachedStyles:function(e,t){if(e=e&&e.length&&e[0]||e,e&&e.style)for(var n in t)e["$style-"+n]!==t[n]&&(e.style[n]=e["$style-"+n]=t[n])}},n.requestAnimationFrame=n.DomUtil.requestAnimationFrame,n.cancelAnimationFrame=n.DomUtil.cancelAnimationFrame,n.animationFrameThrottle=n.DomUtil.animationFrameThrottle}(window,document,ionic),function(e){e.CustomEvent=function(){if("function"==typeof window.CustomEvent)return CustomEvent;var e=function(e,t){var n;t=t||{bubbles:!1,cancelable:!1,detail:void 0};try{n=document.createEvent("CustomEvent"),n.initCustomEvent(e,t.bubbles,t.cancelable,t.detail)}catch(i){n=document.createEvent("Event");for(var o in t)n[o]=t[o];n.initEvent(e,t.bubbles,t.cancelable)}return n};return e.prototype=window.Event.prototype,e}(),e.EventController={VIRTUALIZED_EVENTS:["tap","swipe","swiperight","swipeleft","drag","hold","release"],trigger:function(t,n,i,o){var r=new e.CustomEvent(t,{detail:n,bubbles:!!i,cancelable:!!o});n&&n.target&&n.target.dispatchEvent&&n.target.dispatchEvent(r)||window.dispatchEvent(r)},on:function(t,n,i){for(var o=i||window,r=0,s=this.VIRTUALIZED_EVENTS.length;s>r;r++)if(t==this.VIRTUALIZED_EVENTS[r]){var a=new e.Gesture(i);return a.on(t,n),a}o.addEventListener(t,n)},off:function(e,t,n){n.removeEventListener(e,t)},onGesture:function(t,n,i,o){var r=new e.Gesture(i,o);return r.on(t,n),r},offGesture:function(e,t,n){e&&e.off(t,n)},handlePopState:function(){}},e.on=function(){e.EventController.on.apply(e.EventController,arguments)},e.off=function(){e.EventController.off.apply(e.EventController,arguments)},e.trigger=e.EventController.trigger,e.onGesture=function(){return e.EventController.onGesture.apply(e.EventController.onGesture,arguments)},e.offGesture=function(){return e.EventController.offGesture.apply(e.EventController.offGesture,arguments)}}(window.ionic),function(e){function t(){if(!e.Gestures.READY){e.Gestures.event.determineEventTypes();for(var t in e.Gestures.gestures)e.Gestures.gestures.hasOwnProperty(t)&&e.Gestures.detection.register(e.Gestures.gestures[t]);e.Gestures.event.onTouch(e.Gestures.DOCUMENT,e.Gestures.EVENT_MOVE,e.Gestures.detection.detect),e.Gestures.event.onTouch(e.Gestures.DOCUMENT,e.Gestures.EVENT_END,e.Gestures.detection.detect),e.Gestures.READY=!0}}e.Gesture=function(t,n){return new e.Gestures.Instance(t,n||{})},e.Gestures={},e.Gestures.defaults={stop_browser_behavior:"disable-user-behavior"},e.Gestures.HAS_POINTEREVENTS=window.navigator.pointerEnabled||window.navigator.msPointerEnabled,e.Gestures.HAS_TOUCHEVENTS="ontouchstart"in window,e.Gestures.MOBILE_REGEX=/mobile|tablet|ip(ad|hone|od)|android|silk/i,e.Gestures.NO_MOUSEEVENTS=e.Gestures.HAS_TOUCHEVENTS&&window.navigator.userAgent.match(e.Gestures.MOBILE_REGEX),e.Gestures.EVENT_TYPES={},e.Gestures.DIRECTION_DOWN="down",e.Gestures.DIRECTION_LEFT="left",e.Gestures.DIRECTION_UP="up",e.Gestures.DIRECTION_RIGHT="right",e.Gestures.POINTER_MOUSE="mouse",e.Gestures.POINTER_TOUCH="touch",e.Gestures.POINTER_PEN="pen",e.Gestures.EVENT_START="start",e.Gestures.EVENT_MOVE="move",e.Gestures.EVENT_END="end",e.Gestures.DOCUMENT=window.document,e.Gestures.plugins={},e.Gestures.READY=!1,e.Gestures.Instance=function(n,i){var o=this;return null===n?this:(t(),this.element=n,this.enabled=!0,this.options=e.Gestures.utils.extend(e.Gestures.utils.extend({},e.Gestures.defaults),i||{}),this.options.stop_browser_behavior&&e.Gestures.utils.stopDefaultBrowserBehavior(this.element,this.options.stop_browser_behavior),e.Gestures.event.onTouch(n,e.Gestures.EVENT_START,function(t){o.enabled&&e.Gestures.detection.startDetect(o,t)}),this)},e.Gestures.Instance.prototype={on:function(e,t){for(var n=e.split(" "),i=0;i<n.length;i++)this.element.addEventListener(n[i],t,!1);return this},off:function(e,t){for(var n=e.split(" "),i=0;i<n.length;i++)this.element.removeEventListener(n[i],t,!1);return this},trigger:function(t,n){var i=e.Gestures.DOCUMENT.createEvent("Event");i.initEvent(t,!0,!0),i.gesture=n;var o=this.element;return e.Gestures.utils.hasParent(n.target,o)&&(o=n.target),o.dispatchEvent(i),this},enable:function(e){return this.enabled=e,this}};var n=null,i=!1,o=!1;e.Gestures.event={bindDom:function(e,t,n){for(var i=t.split(" "),o=0;o<i.length;o++)e.addEventListener(i[o],n,!1)},onTouch:function(t,r,s){var a=this;this.bindDom(t,e.Gestures.EVENT_TYPES[r],function(l){var c=l.type.toLowerCase();if(!c.match(/mouse/)||!o){c.match(/touch/)||c.match(/pointerdown/)||c.match(/mouse/)&&1===l.which?i=!0:c.match(/mouse/)&&1!==l.which&&(i=!1),c.match(/touch|pointer/)&&(o=!0);var u=0;i&&(e.Gestures.HAS_POINTEREVENTS&&r!=e.Gestures.EVENT_END?u=e.Gestures.PointerEvent.updatePointer(r,l):c.match(/touch/)?u=l.touches.length:o||(u=c.match(/up/)?0:1),u>0&&r==e.Gestures.EVENT_END?r=e.Gestures.EVENT_MOVE:u||(r=e.Gestures.EVENT_END),(u||null===n)&&(n=l),s.call(e.Gestures.detection,a.collectEventData(t,r,a.getTouchList(n,r),l)),e.Gestures.HAS_POINTEREVENTS&&r==e.Gestures.EVENT_END&&(u=e.Gestures.PointerEvent.updatePointer(r,l))),u||(n=null,i=!1,o=!1,e.Gestures.PointerEvent.reset())}})},determineEventTypes:function(){var t;t=e.Gestures.HAS_POINTEREVENTS?e.Gestures.PointerEvent.getEvents():e.Gestures.NO_MOUSEEVENTS?["touchstart","touchmove","touchend touchcancel"]:["touchstart mousedown","touchmove mousemove","touchend touchcancel mouseup"],e.Gestures.EVENT_TYPES[e.Gestures.EVENT_START]=t[0],e.Gestures.EVENT_TYPES[e.Gestures.EVENT_MOVE]=t[1],e.Gestures.EVENT_TYPES[e.Gestures.EVENT_END]=t[2]},getTouchList:function(t){return e.Gestures.HAS_POINTEREVENTS?e.Gestures.PointerEvent.getTouchList():t.touches?t.touches:(t.identifier=1,[t])},collectEventData:function(t,n,i,o){var r=e.Gestures.POINTER_TOUCH;return(o.type.match(/mouse/)||e.Gestures.PointerEvent.matchType(e.Gestures.POINTER_MOUSE,o))&&(r=e.Gestures.POINTER_MOUSE),{center:e.Gestures.utils.getCenter(i),timeStamp:(new Date).getTime(),target:o.target,touches:i,eventType:n,pointerType:r,srcEvent:o,preventDefault:function(){this.srcEvent.preventManipulation&&this.srcEvent.preventManipulation(),this.srcEvent.preventDefault},stopPropagation:function(){this.srcEvent.stopPropagation()},stopDetect:function(){return e.Gestures.detection.stopDetect()}}}},e.Gestures.PointerEvent={pointers:{},getTouchList:function(){var e=this,t=[];return Object.keys(e.pointers).sort().forEach(function(n){t.push(e.pointers[n])}),t},updatePointer:function(t,n){return t==e.Gestures.EVENT_END?this.pointers={}:(n.identifier=n.pointerId,this.pointers[n.pointerId]=n),Object.keys(this.pointers).length},matchType:function(t,n){if(!n.pointerType)return!1;var i={};return i[e.Gestures.POINTER_MOUSE]=n.pointerType==n.MSPOINTER_TYPE_MOUSE||n.pointerType==e.Gestures.POINTER_MOUSE,i[e.Gestures.POINTER_TOUCH]=n.pointerType==n.MSPOINTER_TYPE_TOUCH||n.pointerType==e.Gestures.POINTER_TOUCH,i[e.Gestures.POINTER_PEN]=n.pointerType==n.MSPOINTER_TYPE_PEN||n.pointerType==e.Gestures.POINTER_PEN,i[t]},getEvents:function(){return["pointerdown MSPointerDown","pointermove MSPointerMove","pointerup pointercancel MSPointerUp MSPointerCancel"]},reset:function(){this.pointers={}}},e.Gestures.utils={extend:function(e,t,n){for(var i in t)void 0!==e[i]&&n||(e[i]=t[i]);return e},hasParent:function(e,t){for(;e;){if(e==t)return!0;e=e.parentNode}return!1},getCenter:function(e){for(var t=[],n=[],i=0,o=e.length;o>i;i++)t.push(e[i].pageX),n.push(e[i].pageY);return{pageX:(Math.min.apply(Math,t)+Math.max.apply(Math,t))/2,pageY:(Math.min.apply(Math,n)+Math.max.apply(Math,n))/2}},getVelocity:function(e,t,n){return{x:Math.abs(t/e)||0,y:Math.abs(n/e)||0}},getAngle:function(e,t){var n=t.pageY-e.pageY,i=t.pageX-e.pageX;return 180*Math.atan2(n,i)/Math.PI},getDirection:function(t,n){var i=Math.abs(t.pageX-n.pageX),o=Math.abs(t.pageY-n.pageY);return i>=o?t.pageX-n.pageX>0?e.Gestures.DIRECTION_LEFT:e.Gestures.DIRECTION_RIGHT:t.pageY-n.pageY>0?e.Gestures.DIRECTION_UP:e.Gestures.DIRECTION_DOWN},getDistance:function(e,t){var n=t.pageX-e.pageX,i=t.pageY-e.pageY;return Math.sqrt(n*n+i*i)},getScale:function(e,t){return e.length>=2&&t.length>=2?this.getDistance(t[0],t[1])/this.getDistance(e[0],e[1]):1},getRotation:function(e,t){return e.length>=2&&t.length>=2?this.getAngle(t[1],t[0])-this.getAngle(e[1],e[0]):0},isVertical:function(t){return t==e.Gestures.DIRECTION_UP||t==e.Gestures.DIRECTION_DOWN},stopDefaultBrowserBehavior:function(e,t){e&&e.classList&&(e.classList.add(t),e.onselectstart=function(){return!1})}},e.Gestures.detection={gestures:[],current:null,previous:null,stopped:!1,startDetect:function(t,n){this.current||(this.stopped=!1,this.current={inst:t,startEvent:e.Gestures.utils.extend({},n),lastEvent:!1,name:""},this.detect(n))},detect:function(t){if(!this.current||this.stopped)return null;t=this.extendEventData(t);for(var n=this.current.inst.options,i=0,o=this.gestures.length;o>i;i++){var r=this.gestures[i];if(!this.stopped&&n[r.name]!==!1&&r.handler.call(r,t,this.current.inst)===!1){this.stopDetect();break}}return this.current&&(this.current.lastEvent=t),t.eventType==e.Gestures.EVENT_END&&!t.touches.length-1&&this.stopDetect(),t},stopDetect:function(){this.previous=e.Gestures.utils.extend({},this.current),this.current=null,this.stopped=!0},extendEventData:function(t){var n=this.current.startEvent;if(n&&(t.touches.length!=n.touches.length||t.touches===n.touches)){n.touches=[];for(var i=0,o=t.touches.length;o>i;i++)n.touches.push(e.Gestures.utils.extend({},t.touches[i]))}var r=t.timeStamp-n.timeStamp,s=t.center.pageX-n.center.pageX,a=t.center.pageY-n.center.pageY,l=e.Gestures.utils.getVelocity(r,s,a);return e.Gestures.utils.extend(t,{deltaTime:r,deltaX:s,deltaY:a,velocityX:l.x,velocityY:l.y,distance:e.Gestures.utils.getDistance(n.center,t.center),angle:e.Gestures.utils.getAngle(n.center,t.center),direction:e.Gestures.utils.getDirection(n.center,t.center),scale:e.Gestures.utils.getScale(n.touches,t.touches),rotation:e.Gestures.utils.getRotation(n.touches,t.touches),startEvent:n}),t},register:function(t){var n=t.defaults||{};return void 0===n[t.name]&&(n[t.name]=!0),e.Gestures.utils.extend(e.Gestures.defaults,n,!0),t.index=t.index||1e3,this.gestures.push(t),this.gestures.sort(function(e,t){return e.index<t.index?-1:e.index>t.index?1:0}),this.gestures}},e.Gestures.gestures=e.Gestures.gestures||{},e.Gestures.gestures.Hold={name:"hold",index:10,defaults:{hold_timeout:500,hold_threshold:1},timer:null,handler:function(t,n){switch(t.eventType){case e.Gestures.EVENT_START:clearTimeout(this.timer),e.Gestures.detection.current.name=this.name,this.timer=setTimeout(function(){"hold"==e.Gestures.detection.current.name&&(e.tap.cancelClick(),n.trigger("hold",t))},n.options.hold_timeout);break;case e.Gestures.EVENT_MOVE:t.distance>n.options.hold_threshold&&clearTimeout(this.timer);break;case e.Gestures.EVENT_END:clearTimeout(this.timer)}}},e.Gestures.gestures.Tap={name:"tap",index:100,defaults:{tap_max_touchtime:250,tap_max_distance:10,tap_always:!0,doubletap_distance:20,doubletap_interval:300},handler:function(t,n){if(t.eventType==e.Gestures.EVENT_END&&"touchcancel"!=t.srcEvent.type){var i=e.Gestures.detection.previous,o=!1;if(t.deltaTime>n.options.tap_max_touchtime||t.distance>n.options.tap_max_distance)return;i&&"tap"==i.name&&t.timeStamp-i.lastEvent.timeStamp<n.options.doubletap_interval&&t.distance<n.options.doubletap_distance&&(n.trigger("doubletap",t),o=!0),(!o||n.options.tap_always)&&(e.Gestures.detection.current.name="tap",n.trigger("tap",t))}}},e.Gestures.gestures.Swipe={name:"swipe",index:40,defaults:{swipe_max_touches:1,swipe_velocity:.4},handler:function(t,n){if(t.eventType==e.Gestures.EVENT_END){if(n.options.swipe_max_touches>0&&t.touches.length>n.options.swipe_max_touches)return;(t.velocityX>n.options.swipe_velocity||t.velocityY>n.options.swipe_velocity)&&(n.trigger(this.name,t),n.trigger(this.name+t.direction,t))}}},e.Gestures.gestures.Drag={name:"drag",index:50,defaults:{drag_min_distance:10,correct_for_drag_min_distance:!0,drag_max_touches:1,drag_block_horizontal:!0,drag_block_vertical:!0,drag_lock_to_axis:!1,drag_lock_min_distance:25,prevent_default_directions:[]},triggered:!1,handler:function(t,n){if("touchstart"==t.srcEvent.type||"touchend"==t.srcEvent.type?this.preventedFirstMove=!1:this.preventedFirstMove||"touchmove"!=t.srcEvent.type||(n.options.prevent_default_directions.length>0&&-1!=n.options.prevent_default_directions.indexOf(t.direction)&&t.srcEvent.preventDefault(),this.preventedFirstMove=!0),e.Gestures.detection.current.name!=this.name&&this.triggered)return n.trigger(this.name+"end",t),void(this.triggered=!1);if(!(n.options.drag_max_touches>0&&t.touches.length>n.options.drag_max_touches))switch(t.eventType){case e.Gestures.EVENT_START:this.triggered=!1;break;case e.Gestures.EVENT_MOVE:if(t.distance<n.options.drag_min_distance&&e.Gestures.detection.current.name!=this.name)return;if(e.Gestures.detection.current.name!=this.name&&(e.Gestures.detection.current.name=this.name,n.options.correct_for_drag_min_distance)){var i=Math.abs(n.options.drag_min_distance/t.distance);e.Gestures.detection.current.startEvent.center.pageX+=t.deltaX*i,e.Gestures.detection.current.startEvent.center.pageY+=t.deltaY*i,t=e.Gestures.detection.extendEventData(t)}(e.Gestures.detection.current.lastEvent.drag_locked_to_axis||n.options.drag_lock_to_axis&&n.options.drag_lock_min_distance<=t.distance)&&(t.drag_locked_to_axis=!0);var o=e.Gestures.detection.current.lastEvent.direction;t.drag_locked_to_axis&&o!==t.direction&&(e.Gestures.utils.isVertical(o)?t.direction=t.deltaY<0?e.Gestures.DIRECTION_UP:e.Gestures.DIRECTION_DOWN:t.direction=t.deltaX<0?e.Gestures.DIRECTION_LEFT:e.Gestures.DIRECTION_RIGHT),this.triggered||(n.trigger(this.name+"start",t),this.triggered=!0),n.trigger(this.name,t),n.trigger(this.name+t.direction,t),(n.options.drag_block_vertical&&e.Gestures.utils.isVertical(t.direction)||n.options.drag_block_horizontal&&!e.Gestures.utils.isVertical(t.direction))&&t.preventDefault();break;case e.Gestures.EVENT_END:this.triggered&&n.trigger(this.name+"end",t),this.triggered=!1}}},e.Gestures.gestures.Transform={name:"transform",index:45,defaults:{transform_min_scale:.01,transform_min_rotation:1,transform_always_block:!1},triggered:!1,handler:function(t,n){if(e.Gestures.detection.current.name!=this.name&&this.triggered)return n.trigger(this.name+"end",t),void(this.triggered=!1);if(!(t.touches.length<2))switch(n.options.transform_always_block&&t.preventDefault(),t.eventType){case e.Gestures.EVENT_START:this.triggered=!1;break;case e.Gestures.EVENT_MOVE:var i=Math.abs(1-t.scale),o=Math.abs(t.rotation);if(i<n.options.transform_min_scale&&o<n.options.transform_min_rotation)return;e.Gestures.detection.current.name=this.name,this.triggered||(n.trigger(this.name+"start",t),this.triggered=!0),n.trigger(this.name,t),o>n.options.transform_min_rotation&&n.trigger("rotate",t),i>n.options.transform_min_scale&&(n.trigger("pinch",t),n.trigger("pinch"+(t.scale<1?"in":"out"),t));break;case e.Gestures.EVENT_END:this.triggered&&n.trigger(this.name+"end",t),this.triggered=!1}}},e.Gestures.gestures.Touch={name:"touch",index:-(1/0),defaults:{prevent_default:!1,prevent_mouseevents:!1},handler:function(t,n){return n.options.prevent_mouseevents&&t.pointerType==e.Gestures.POINTER_MOUSE?void t.stopDetect():(n.options.prevent_default&&t.preventDefault(),void(t.eventType==e.Gestures.EVENT_START&&n.trigger(this.name,t)))}},e.Gestures.gestures.Release={name:"release",index:1/0,handler:function(t,n){t.eventType==e.Gestures.EVENT_END&&n.trigger(this.name,t)}}}(window.ionic),function(e,t,n){function i(e){e=e.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var t=new RegExp("[\\?&]"+e+"=([^&#]*)"),n=t.exec(location.search);return null===n?"":decodeURIComponent(n[1].replace(/\+/g," "))}function o(){d.isWebView()?t.addEventListener("deviceready",r,!1):r(),s&&e.removeEventListener("load",o,!1)}function r(){d.isReady=!0,d.detect();for(var e=0;e<f.length;e++)f[e]();f=[],n.trigger("platformready",{target:t}),u(function(){t.body.classList.add("platform-ready")})}var s,a="ios",l="android",c="windowsphone",u=n.requestAnimationFrame,d=n.Platform={navigator:e.navigator,isReady:!1,isFullScreen:!1,platforms:null,grade:null,ua:navigator.userAgent,ready:function(e){d.isReady?e():f.push(e)},detect:function(){d._checkPlatforms(),u(function(){for(var e=0;e<d.platforms.length;e++)t.body.classList.add("platform-"+d.platforms[e])})},setGrade:function(e){var n=d.grade;d.grade=e,u(function(){n&&t.body.classList.remove("grade-"+n),t.body.classList.add("grade-"+e)})},device:function(){return e.device||{}},_checkPlatforms:function(){d.platforms=[];var t="a";d.isWebView()?(d.platforms.push("webview"),e.cordova||e.PhoneGap||e.phonegap?d.platforms.push("cordova"):e.forge&&d.platforms.push("trigger")):d.platforms.push("browser"),d.isIPad()&&d.platforms.push("ipad");var n=d.platform();if(n){d.platforms.push(n);var i=d.version();if(i){var o=i.toString();o.indexOf(".")>0?o=o.replace(".","_"):o+="_0",d.platforms.push(n+o.split("_")[0]),d.platforms.push(n+o),d.isAndroid()&&4.4>i?t=4>i?"c":"b":d.isWindowsPhone()&&(t="b")}}d.setGrade(t)},isWebView:function(){return!!(e.cordova||e.PhoneGap||e.phonegap||e.forge)},isIPad:function(){return/iPad/i.test(d.navigator.platform)?!0:/iPad/i.test(d.ua)},isIOS:function(){return d.is(a)},isAndroid:function(){return d.is(l)},isWindowsPhone:function(){return d.is(c)},platform:function(){return null===_&&d.setPlatform(d.device().platform),_},setPlatform:function(e){_="undefined"!=typeof e&&null!==e&&e.length?e.toLowerCase():i("ionicplatform")?i("ionicplatform"):d.ua.indexOf("Android")>0?l:/iPhone|iPad|iPod/.test(d.ua)?a:d.ua.indexOf("Windows Phone")>-1?c:d.navigator.platform&&navigator.platform.toLowerCase().split(" ")[0]||""},version:function(){return null===h&&d.setVersion(d.device().version),h},setVersion:function(e){if("undefined"!=typeof e&&null!==e&&(e=e.split("."),e=parseFloat(e[0]+"."+(e.length>1?e[1]:0)),!isNaN(e)))return void(h=e);h=0;var t=d.platform(),n={android:/Android (\d+).(\d+)?/,ios:/OS (\d+)_(\d+)?/,windowsphone:/Windows Phone (\d+).(\d+)?/};n[t]&&(e=d.ua.match(n[t]),e&&e.length>2&&(h=parseFloat(e[1]+"."+e[2])))},is:function(e){if(e=e.toLowerCase(),d.platforms)for(var t=0;t<d.platforms.length;t++)if(d.platforms[t]===e)return!0;var n=d.platform();return n?n===e.toLowerCase():d.ua.toLowerCase().indexOf(e)>=0},exitApp:function(){d.ready(function(){navigator.app&&navigator.app.exitApp&&navigator.app.exitApp()})},showStatusBar:function(n){d._showStatusBar=n,d.ready(function(){u(function(){d._showStatusBar?(e.StatusBar&&e.StatusBar.show(),t.body.classList.remove("status-bar-hide")):(e.StatusBar&&e.StatusBar.hide(),t.body.classList.add("status-bar-hide"))})})},fullScreen:function(e,i){d.isFullScreen=e!==!1,n.DomUtil.ready(function(){u(function(){d.isFullScreen?t.body.classList.add("fullscreen"):t.body.classList.remove("fullscreen")}),d.showStatusBar(i===!0)})}},_=null,h=null,f=[];"complete"===t.readyState?o():(s=!0,e.addEventListener("load",o,!1))}(this,document,ionic),function(e,t){"use strict";t.CSS={},function(){var n,i=["webkitTransform","transform","-webkit-transform","webkit-transform","-moz-transform","moz-transform","MozTransform","mozTransform","msTransform"];for(n=0;n<i.length;n++)if(void 0!==e.documentElement.style[i[n]]){t.CSS.TRANSFORM=i[n];break}for(i=["webkitTransition","mozTransition","msTransition","transition"],n=0;n<i.length;n++)if(void 0!==e.documentElement.style[i[n]]){t.CSS.TRANSITION=i[n];break}var o=t.CSS.TRANSITION.indexOf("webkit")>-1;t.CSS.TRANSITION_DURATION=(o?"-webkit-":"")+"transition-duration",t.CSS.TRANSITIONEND=(o?"webkitTransitionEnd ":"")+"transitionend"}(),"classList"in e.documentElement||!Object.defineProperty||"undefined"==typeof HTMLElement||Object.defineProperty(HTMLElement.prototype,"classList",{get:function(){function e(e){return function(){var n,i=t.className.split(/\s+/);for(n=0;n<arguments.length;n++)e(i,i.indexOf(arguments[n]),arguments[n]);t.className=i.join(" ")}}var t=this;return{add:e(function(e,t,n){~t||e.push(n)}),remove:e(function(e,t){~t&&e.splice(t,1)}),toggle:e(function(e,t,n){~t?e.splice(t,1):e.push(n)}),contains:function(e){return!!~t.className.split(/\s+/).indexOf(e)},item:function(e){return t.className.split(/\s+/)[e]||null}}}})}(document,ionic);var F,Y,X,W,$,U,q,B,K="touchmove",Z=12,j=50,J={
click:i,mousedown:o,mouseup:r,mousemove:s,touchstart:a,touchend:l,touchcancel:u,touchmove:c,pointerdown:a,pointerup:l,pointercancel:u,pointermove:c,MSPointerDown:a,MSPointerUp:l,MSPointerCancel:u,MSPointerMove:c,focusin:p,focusout:m};ionic.tap={register:function(t){return F=t,e("click",!0,!0),e("mouseup"),e("mousedown"),window.navigator.pointerEnabled?(e("pointerdown"),e("pointerup"),e("pointcancel"),K="pointermove"):window.navigator.msPointerEnabled?(e("MSPointerDown"),e("MSPointerUp"),e("MSPointerCancel"),K="MSPointerMove"):(e("touchstart"),e("touchend"),e("touchcancel")),e("focusin"),e("focusout"),function(){for(var t in J)e(t,!1);F=null,Y=null,X=!1,$=!1,U=null}},ignoreScrollStart:function(e){return e.defaultPrevented||/^(file|range)$/i.test(e.target.type)||"true"==(e.target.dataset?e.target.dataset.preventScroll:e.target.getAttribute("data-prevent-scroll"))||!!/^(object|embed)$/i.test(e.target.tagName)||ionic.tap.isElementTapDisabled(e.target)},isTextInput:function(e){return!!e&&("TEXTAREA"==e.tagName||"true"===e.contentEditable||"INPUT"==e.tagName&&!/^(radio|checkbox|range|file|submit|reset|color|image|button)$/i.test(e.type))},isDateInput:function(e){return!!e&&"INPUT"==e.tagName&&/^(date|time|datetime-local|month|week)$/i.test(e.type)},isKeyboardElement:function(e){return!ionic.Platform.isIOS()||ionic.Platform.isIPad()?ionic.tap.isTextInput(e)&&!ionic.tap.isDateInput(e):ionic.tap.isTextInput(e)||!!e&&"SELECT"==e.tagName},isLabelWithTextInput:function(e){var t=T(e,!1);return!!t&&ionic.tap.isTextInput(E(t))},containsOrIsTextInput:function(e){return ionic.tap.isTextInput(e)||ionic.tap.isLabelWithTextInput(e)},cloneFocusedInput:function(e){ionic.tap.hasCheckedClone||(ionic.tap.hasCheckedClone=!0,ionic.requestAnimationFrame(function(){var t=e.querySelector(":focus");if(ionic.tap.isTextInput(t)&&!ionic.tap.isDateInput(t)){var n=t.cloneNode(!0);n.value=t.value,n.classList.add("cloned-text-input"),n.readOnly=!0,t.isContentEditable&&(n.contentEditable=t.contentEditable,n.innerHTML=t.innerHTML),t.parentElement.insertBefore(n,t),t.classList.add("previous-input-focus"),n.scrollTop=t.scrollTop}}))},hasCheckedClone:!1,removeClonedInputs:function(e){ionic.tap.hasCheckedClone=!1,ionic.requestAnimationFrame(function(){var t,n=e.querySelectorAll(".cloned-text-input"),i=e.querySelectorAll(".previous-input-focus");for(t=0;t<n.length;t++)n[t].parentElement.removeChild(n[t]);for(t=0;t<i.length;t++)i[t].classList.remove("previous-input-focus"),i[t].style.top="",ionic.keyboard.isOpen&&!ionic.keyboard.isClosing&&i[t].focus()})},requiresNativeClick:function(e){return!e||e.disabled||/^(file|range)$/i.test(e.type)||/^(object|video)$/i.test(e.tagName)||ionic.tap.isLabelContainingFileInput(e)?!0:ionic.tap.isElementTapDisabled(e)},isLabelContainingFileInput:function(e){var t=T(e);if("LABEL"!==t.tagName)return!1;var n=t.querySelector("input[type=file]");return n&&n.disabled===!1?!0:!1},isElementTapDisabled:function(e){if(e&&1===e.nodeType)for(var t=e;t;){if("true"==(t.dataset?t.dataset.tapDisabled:t.getAttribute("data-tap-disabled")))return!0;t=t.parentElement}return!1},setTolerance:function(e,t){Z=e,j=t},cancelClick:function(){$=!0},pointerCoord:function(e){var t={x:0,y:0};if(e){var n=e.touches&&e.touches.length?e.touches:[e],i=e.changedTouches&&e.changedTouches[0]||n[0];i&&(t.x=i.clientX||i.pageX||0,t.y=i.clientY||i.pageY||0)}return t}},ionic.DomUtil.ready(function(){var e="undefined"!=typeof angular?angular:null;(!e||e&&!e.scenario)&&ionic.tap.register(document)}),function(e,t){"use strict";function n(){r={},t.requestAnimationFrame(o)}function i(){for(var e in r)r[e]&&(r[e].classList.add(l),s[e]=r[e]);r={}}function o(){if(t.transition&&t.transition.isActive)return void setTimeout(o,400);for(var e in s)s[e]&&(s[e].classList.remove(l),delete s[e])}var r={},s={},a=0,l="activated";t.activator={start:function(e){var n=t.tap.pointerCoord(e).x;n>0&&30>n||t.requestAnimationFrame(function(){if(!(t.scroll&&t.scroll.isScrolling||t.tap.requiresNativeClick(e.target))){for(var n,o=e.target,s=0;6>s&&(o&&1===o.nodeType);s++){if(n&&o.classList&&o.classList.contains("item")){n=o;break}if("A"==o.tagName||"BUTTON"==o.tagName||o.hasAttribute("ng-click")){n=o;break}if(o.classList.contains("button")){n=o;break}if("ION-CONTENT"==o.tagName||o.classList&&o.classList.contains("pane")||"BODY"==o.tagName)break;o=o.parentElement}n&&(r[a]=n,t.requestAnimationFrame(i),a=a>29?0:a+1)}})},end:function(){setTimeout(n,200)}}}(document,ionic),function(e){var t=0;e.Utils={arrayMove:function(e,t,n){if(n>=e.length)for(var i=n-e.length;i--+1;)e.push(void 0);return e.splice(n,0,e.splice(t,1)[0]),e},proxy:function(e,t){var n=Array.prototype.slice.call(arguments,2);return function(){return e.apply(t,n.concat(Array.prototype.slice.call(arguments)))}},debounce:function(e,t,n){var i,o,r,s,a;return function(){r=this,o=arguments,s=new Date;var l=function(){var c=new Date-s;t>c?i=setTimeout(l,t-c):(i=null,n||(a=e.apply(r,o)))},c=n&&!i;return i||(i=setTimeout(l,t)),c&&(a=e.apply(r,o)),a}},throttle:function(e,t,n){var i,o,r,s=null,a=0;n||(n={});var l=function(){a=n.leading===!1?0:Date.now(),s=null,r=e.apply(i,o)};return function(){var c=Date.now();a||n.leading!==!1||(a=c);var u=t-(c-a);return i=this,o=arguments,0>=u?(clearTimeout(s),s=null,a=c,r=e.apply(i,o)):s||n.trailing===!1||(s=setTimeout(l,u)),r}},inherit:function(t,n){var i,o=this;i=t&&t.hasOwnProperty("constructor")?t.constructor:function(){return o.apply(this,arguments)},e.extend(i,o,n);var r=function(){this.constructor=i};return r.prototype=o.prototype,i.prototype=new r,t&&e.extend(i.prototype,t),i.__super__=o.prototype,i},extend:function(e){for(var t=Array.prototype.slice.call(arguments,1),n=0;n<t.length;n++){var i=t[n];if(i)for(var o in i)e[o]=i[o]}return e},nextUid:function(){return"ion"+t++},disconnectScope:function(e){if(e&&e.$root!==e){var t=e.$parent;e.$$disconnected=!0,e.$broadcast("$ionic.disconnectScope",e),t.$$childHead===e&&(t.$$childHead=e.$$nextSibling),t.$$childTail===e&&(t.$$childTail=e.$$prevSibling),e.$$prevSibling&&(e.$$prevSibling.$$nextSibling=e.$$nextSibling),e.$$nextSibling&&(e.$$nextSibling.$$prevSibling=e.$$prevSibling),e.$$nextSibling=e.$$prevSibling=null}},reconnectScope:function(e){if(e&&e.$root!==e&&e.$$disconnected){var t=e.$parent;e.$$disconnected=!1,e.$broadcast("$ionic.reconnectScope",e),e.$$prevSibling=t.$$childTail,t.$$childHead?(t.$$childTail.$$nextSibling=e,t.$$childTail=e):t.$$childHead=t.$$childTail=e}},isScopeDisconnected:function(e){for(var t=e;t;){if(t.$$disconnected)return!0;t=t.$parent}return!1}},e.inherit=e.Utils.inherit,e.extend=e.Utils.extend,e.throttle=e.Utils.throttle,e.proxy=e.Utils.proxy,e.debounce=e.Utils.debounce}(window.ionic);var Q,ee,te,ne,ie=0,oe=0,re=0,se=!1,ae="keyboard-open",le="scroll-content",ce=ionic.debounce(w,200,!0),ue=ionic.debounce(b,100,!0);ionic.keyboard={isOpen:!1,isClosing:!1,isOpening:!1,height:0,isLandscape:!1,isInitialized:!1,hide:function(){V()&&cordova.plugins.Keyboard.close(),Q&&Q.blur()},show:function(){V()&&cordova.plugins.Keyboard.show()},disable:function(){V()?(window.removeEventListener("native.keyboardshow",ue),window.removeEventListener("native.keyboardhide",y)):document.body.removeEventListener("focusout",y),document.body.removeEventListener("ionic.focusin",ce),document.body.removeEventListener("focusin",ce),window.removeEventListener("orientationchange",D),window.navigator.msPointerEnabled?document.removeEventListener("MSPointerDown",S):document.removeEventListener("touchstart",S),ionic.keyboard.isInitialized=!1},enable:function(){S()}},ie=k(),ionic.Platform.ready(function(){G(),window.addEventListener("orientationchange",D),setTimeout(G,999),window.navigator.msPointerEnabled?document.addEventListener("MSPointerDown",S,!1):document.addEventListener("touchstart",S,!1)});var de,_e={};ionic.viewport={orientation:function(){return window.innerWidth>window.innerHeight?90:0}},ionic.Platform.ready(function(){R(),window.addEventListener("orientationchange",function(){setTimeout(z,1e3)},!1)}),function(e){"use strict";e.views.View=function(){this.initialize.apply(this,arguments)},e.views.View.inherit=e.inherit,e.extend(e.views.View.prototype,{initialize:function(){}})}(window.ionic);var he={effect:{}};!function(e){var t=Date.now||function(){return+new Date},n=60,i=1e3,o={},r=1;he.effect.Animate={requestAnimationFrame:function(){var t=e.requestAnimationFrame||e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame,n=!!t;if(t&&!/requestAnimationFrame\(\)\s*\{\s*\[native code\]\s*\}/i.test(t.toString())&&(n=!1),n)return function(e,n){t(e,n)};var i=60,o={},r=0,s=1,a=null,l=+new Date;return function(e){var t=s++;return o[t]=e,r++,null===a&&(a=setInterval(function(){var e=+new Date,t=o;o={},r=0;for(var n in t)t.hasOwnProperty(n)&&(t[n](e),l=e);e-l>2500&&(clearInterval(a),a=null)},1e3/i)),t}}(),stop:function(e){var t=null!=o[e];return t&&(o[e]=null),t},isRunning:function(e){return null!=o[e]},start:function(e,s,a,l,c,u){var d=t(),_=d,h=0,f=0,p=r++;if(u||(u=document.body),p%20===0){var m={};for(var g in o)m[g]=!0;o=m}var v=function(r){var m=r!==!0,g=t();if(!o[p]||s&&!s(p))return o[p]=null,void(a&&a(n-f/((g-d)/i),p,!1));if(m)for(var T=Math.round((g-_)/(i/n))-1,E=0;E<Math.min(T,4);E++)v(!0),f++;l&&(h=(g-d)/l,h>1&&(h=1));var S=c?c(h):h;e(S,g,m)!==!1&&1!==h||!m?m&&(_=g,he.effect.Animate.requestAnimationFrame(v,u)):(o[p]=null,a&&a(n-f/((g-d)/i),p,1===h||null==l))};return o[p]=!0,he.effect.Animate.requestAnimationFrame(v,u),p}}}(this),function(e){var t=function(){},n=function(e){return Math.pow(e-1,3)+1},i=function(e){return(e/=.5)<1?.5*Math.pow(e,3):.5*(Math.pow(e-2,3)+2)};e.views.Scroll=e.views.View.inherit({initialize:function(n){var i=this;i.__container=n.el,i.__content=n.el.firstElementChild,setTimeout(function(){i.__container&&i.__content&&(i.__container.scrollTop=0,i.__content.scrollTop=0)}),i.options={scrollingX:!1,scrollbarX:!0,scrollingY:!0,scrollbarY:!0,startX:0,startY:0,wheelDampen:6,minScrollbarSizeX:5,minScrollbarSizeY:5,scrollbarsFade:!0,scrollbarFadeDelay:300,scrollbarResizeFadeDelay:1e3,animating:!0,animationDuration:250,decelVelocityThreshold:4,decelVelocityThresholdPaging:4,bouncing:!0,locking:!0,paging:!1,snapping:!1,zooming:!1,minZoom:.5,maxZoom:3,speedMultiplier:1,deceleration:.97,preventDefault:!1,scrollingComplete:t,penetrationDeceleration:.03,penetrationAcceleration:.08,scrollEventInterval:10,freeze:!1,getContentWidth:function(){return Math.max(i.__content.scrollWidth,i.__content.offsetWidth)},getContentHeight:function(){return Math.max(i.__content.scrollHeight,i.__content.offsetHeight+2*i.__content.offsetTop)}};for(var o in n)i.options[o]=n[o];i.hintResize=e.debounce(function(){i.resize()},1e3,!0),i.onScroll=function(){e.scroll.isScrolling?(clearTimeout(i.scrollTimer),i.scrollTimer=setTimeout(i.setScrollStop,80)):setTimeout(i.setScrollStart,50)},i.freeze=function(e){return arguments.length&&(i.options.freeze=e),i.options.freeze},i.setScrollStart=function(){e.scroll.isScrolling=Math.abs(e.scroll.lastTop-i.__scrollTop)>1,clearTimeout(i.scrollTimer),i.scrollTimer=setTimeout(i.setScrollStop,80)},i.setScrollStop=function(){e.scroll.isScrolling=!1,e.scroll.lastTop=i.__scrollTop},i.triggerScrollEvent=e.throttle(function(){i.onScroll(),e.trigger("scroll",{scrollTop:i.__scrollTop,scrollLeft:i.__scrollLeft,target:i.__container})},i.options.scrollEventInterval),i.triggerScrollEndEvent=function(){e.trigger("scrollend",{scrollTop:i.__scrollTop,scrollLeft:i.__scrollLeft,target:i.__container})},i.__scrollLeft=i.options.startX,i.__scrollTop=i.options.startY,i.__callback=i.getRenderFn(),i.__initEventHandlers(),i.__createScrollbars()},run:function(){this.resize(),this.__fadeScrollbars("out",this.options.scrollbarResizeFadeDelay)},__isSingleTouch:!1,__isTracking:!1,__didDecelerationComplete:!1,__isGesturing:!1,__isDragging:!1,__isDecelerating:!1,__isAnimating:!1,__clientLeft:0,__clientTop:0,__clientWidth:0,__clientHeight:0,__contentWidth:0,__contentHeight:0,__snapWidth:100,__snapHeight:100,__refreshHeight:null,__refreshActive:!1,__refreshActivate:null,__refreshDeactivate:null,__refreshStart:null,__zoomLevel:1,__scrollLeft:0,__scrollTop:0,__maxScrollLeft:0,__maxScrollTop:0,__scheduledLeft:0,__scheduledTop:0,__scheduledZoom:0,__lastTouchLeft:null,__lastTouchTop:null,__lastTouchMove:null,__positions:null,__minDecelerationScrollLeft:null,__minDecelerationScrollTop:null,__maxDecelerationScrollLeft:null,__maxDecelerationScrollTop:null,__decelerationVelocityX:null,__decelerationVelocityY:null,__transformProperty:null,__perspectiveProperty:null,__indicatorX:null,__indicatorY:null,__scrollbarFadeTimeout:null,__didWaitForSize:null,__sizerTimeout:null,__initEventHandlers:function(){function t(e){return e.touches&&e.touches.length?e.touches:[{pageX:e.pageX,pageY:e.pageY}]}var n,i=this,o=i.__container;if(i.scrollChildIntoView=function(t){var r=o.getBoundingClientRect().bottom;n=o.offsetHeight;var s=i.isShrunkForKeyboard,a=o.parentNode.classList.contains("modal"),l=a&&window.innerWidth>=680;if(!s){if(e.Platform.isIOS()||e.Platform.isFullScreen||l){var c=t.detail.viewportHeight-r,u=Math.max(0,t.detail.keyboardHeight-c);e.requestAnimationFrame(function(){n-=u,o.style.height=n+"px",o.style.overflow="visible",i.resize()})}i.isShrunkForKeyboard=!0}t.detail.isElementUnderKeyboard&&e.requestAnimationFrame(function(){o.scrollTop=0,i.isShrunkForKeyboard&&!s&&(r=o.getBoundingClientRect().bottom);var a=.5*n,l=(t.detail.elementBottom+t.detail.elementTop)/2,c=l-r,u=c+a;u>0&&(e.Platform.isIOS()&&e.tap.cloneFocusedInput(o,i),i.scrollBy(0,u,!0),i.onScroll())}),t.stopPropagation()},i.resetScrollView=function(){i.isShrunkForKeyboard&&(i.isShrunkForKeyboard=!1,o.style.height="",o.style.overflow=""),i.resize()},o.addEventListener("scrollChildIntoView",i.scrollChildIntoView),document.addEventListener("resetScrollView",i.resetScrollView),i.touchStart=function(n){if(i.startCoordinates=e.tap.pointerCoord(n),!e.tap.ignoreScrollStart(n)){if(i.__isDown=!0,e.tap.containsOrIsTextInput(n.target)||"SELECT"===n.target.tagName)return void(i.__hasStarted=!1);i.__isSelectable=!0,i.__enableScrollY=!0,i.__hasStarted=!0,i.doTouchStart(t(n),n.timeStamp),n.preventDefault()}},i.touchMove=function(n){if(!(i.options.freeze||!i.__isDown||!i.__isDown&&n.defaultPrevented||"TEXTAREA"===n.target.tagName&&n.target.parentElement.querySelector(":focus"))){if(!i.__hasStarted&&(e.tap.containsOrIsTextInput(n.target)||"SELECT"===n.target.tagName))return i.__hasStarted=!0,i.doTouchStart(t(n),n.timeStamp),void n.preventDefault();if(i.startCoordinates){var r=e.tap.pointerCoord(n);i.__isSelectable&&e.tap.isTextInput(n.target)&&Math.abs(i.startCoordinates.x-r.x)>20&&(i.__enableScrollY=!1,i.__isSelectable=!0),i.__enableScrollY&&Math.abs(i.startCoordinates.y-r.y)>10&&(i.__isSelectable=!1,e.tap.cloneFocusedInput(o,i))}i.doTouchMove(t(n),n.timeStamp,n.scale),i.__isDown=!0}},i.touchMoveBubble=function(e){i.__isDown&&i.options.preventDefault&&e.preventDefault()},i.touchEnd=function(t){i.__isDown&&(i.doTouchEnd(t,t.timeStamp),i.__isDown=!1,i.__hasStarted=!1,i.__isSelectable=!0,i.__enableScrollY=!0,i.__isDragging||i.__isDecelerating||i.__isAnimating||e.tap.removeClonedInputs(o,i))},i.mouseWheel=e.animationFrameThrottle(function(t){var n=e.DomUtil.getParentOrSelfWithClass(t.target,"ionic-scroll");i.options.freeze||n!==i.__container||(i.hintResize(),i.scrollBy((t.wheelDeltaX||t.deltaX||0)/i.options.wheelDampen,(-t.wheelDeltaY||t.deltaY||0)/i.options.wheelDampen),i.__fadeScrollbars("in"),clearTimeout(i.__wheelHideBarTimeout),i.__wheelHideBarTimeout=setTimeout(function(){i.__fadeScrollbars("out")},100))}),"ontouchstart"in window)o.addEventListener("touchstart",i.touchStart,!1),i.options.preventDefault&&o.addEventListener("touchmove",i.touchMoveBubble,!1),document.addEventListener("touchmove",i.touchMove,!1),document.addEventListener("touchend",i.touchEnd,!1),document.addEventListener("touchcancel",i.touchEnd,!1);else if(window.navigator.pointerEnabled)o.addEventListener("pointerdown",i.touchStart,!1),i.options.preventDefault&&o.addEventListener("pointermove",i.touchMoveBubble,!1),document.addEventListener("pointermove",i.touchMove,!1),document.addEventListener("pointerup",i.touchEnd,!1),document.addEventListener("pointercancel",i.touchEnd,!1),document.addEventListener("wheel",i.mouseWheel,!1);else if(window.navigator.msPointerEnabled)o.addEventListener("MSPointerDown",i.touchStart,!1),i.options.preventDefault&&o.addEventListener("MSPointerMove",i.touchMoveBubble,!1),document.addEventListener("MSPointerMove",i.touchMove,!1),document.addEventListener("MSPointerUp",i.touchEnd,!1),document.addEventListener("MSPointerCancel",i.touchEnd,!1),document.addEventListener("wheel",i.mouseWheel,!1);else{var r=!1;i.mouseDown=function(n){e.tap.ignoreScrollStart(n)||"SELECT"===n.target.tagName||(i.doTouchStart(t(n),n.timeStamp),e.tap.isTextInput(n.target)||n.preventDefault(),r=!0)},i.mouseMove=function(e){i.options.freeze||!r||!r&&e.defaultPrevented||(i.doTouchMove(t(e),e.timeStamp),r=!0)},i.mouseMoveBubble=function(e){r&&i.options.preventDefault&&e.preventDefault()},i.mouseUp=function(e){r&&(i.doTouchEnd(e,e.timeStamp),r=!1)},o.addEventListener("mousedown",i.mouseDown,!1),i.options.preventDefault&&o.addEventListener("mousemove",i.mouseMoveBubble,!1),document.addEventListener("mousemove",i.mouseMove,!1),document.addEventListener("mouseup",i.mouseUp,!1),document.addEventListener("mousewheel",i.mouseWheel,!1),document.addEventListener("wheel",i.mouseWheel,!1)}},__cleanup:function(){var n=this,i=n.__container;i.removeEventListener("touchstart",n.touchStart),i.removeEventListener("touchmove",n.touchMoveBubble),document.removeEventListener("touchmove",n.touchMove),document.removeEventListener("touchend",n.touchEnd),document.removeEventListener("touchcancel",n.touchEnd),i.removeEventListener("pointerdown",n.touchStart),i.removeEventListener("pointermove",n.touchMoveBubble),document.removeEventListener("pointermove",n.touchMove),document.removeEventListener("pointerup",n.touchEnd),document.removeEventListener("pointercancel",n.touchEnd),i.removeEventListener("MSPointerDown",n.touchStart),i.removeEventListener("MSPointerMove",n.touchMoveBubble),document.removeEventListener("MSPointerMove",n.touchMove),document.removeEventListener("MSPointerUp",n.touchEnd),document.removeEventListener("MSPointerCancel",n.touchEnd),i.removeEventListener("mousedown",n.mouseDown),i.removeEventListener("mousemove",n.mouseMoveBubble),document.removeEventListener("mousemove",n.mouseMove),document.removeEventListener("mouseup",n.mouseUp),document.removeEventListener("mousewheel",n.mouseWheel),document.removeEventListener("wheel",n.mouseWheel),i.removeEventListener("scrollChildIntoView",n.scrollChildIntoView),document.removeEventListener("resetScrollView",n.resetScrollView),e.tap.removeClonedInputs(i,n),delete n.__container,delete n.__content,delete n.__indicatorX,delete n.__indicatorY,delete n.options.el,n.__callback=n.scrollChildIntoView=n.resetScrollView=t,n.mouseMove=n.mouseDown=n.mouseUp=n.mouseWheel=n.touchStart=n.touchMove=n.touchEnd=n.touchCancel=t,n.resize=n.scrollTo=n.zoomTo=n.__scrollingComplete=t,i=null},__createScrollbar:function(e){var t=document.createElement("div"),n=document.createElement("div");return n.className="scroll-bar-indicator scroll-bar-fade-out","h"==e?t.className="scroll-bar scroll-bar-h":t.className="scroll-bar scroll-bar-v",t.appendChild(n),t},__createScrollbars:function(){var e,t,n=this;n.options.scrollingX&&(e={el:n.__createScrollbar("h"),sizeRatio:1},e.indicator=e.el.children[0],n.options.scrollbarX&&n.__container.appendChild(e.el),n.__indicatorX=e),n.options.scrollingY&&(t={el:n.__createScrollbar("v"),sizeRatio:1},t.indicator=t.el.children[0],n.options.scrollbarY&&n.__container.appendChild(t.el),n.__indicatorY=t)},__resizeScrollbars:function(){var t=this;if(t.__indicatorX){var n=Math.max(Math.round(t.__clientWidth*t.__clientWidth/t.__contentWidth),20);n>t.__contentWidth&&(n=0),n!==t.__indicatorX.size&&e.requestAnimationFrame(function(){t.__indicatorX.indicator.style.width=n+"px"}),t.__indicatorX.size=n,t.__indicatorX.minScale=t.options.minScrollbarSizeX/n,t.__indicatorX.maxPos=t.__clientWidth-n,t.__indicatorX.sizeRatio=t.__maxScrollLeft?t.__indicatorX.maxPos/t.__maxScrollLeft:1}if(t.__indicatorY){var i=Math.max(Math.round(t.__clientHeight*t.__clientHeight/t.__contentHeight),20);i>t.__contentHeight&&(i=0),i!==t.__indicatorY.size&&e.requestAnimationFrame(function(){t.__indicatorY&&(t.__indicatorY.indicator.style.height=i+"px")}),t.__indicatorY.size=i,t.__indicatorY.minScale=t.options.minScrollbarSizeY/i,t.__indicatorY.maxPos=t.__clientHeight-i,t.__indicatorY.sizeRatio=t.__maxScrollTop?t.__indicatorY.maxPos/t.__maxScrollTop:1}},__repositionScrollbars:function(){var e,t,n,i,o,r,s=this,a=0,l=0;if(s.__indicatorX){s.__indicatorY&&(a=10),o=Math.round(s.__indicatorX.sizeRatio*s.__scrollLeft)||0,n=s.__scrollLeft-(s.__maxScrollLeft-a),s.__scrollLeft<0?(t=Math.max(s.__indicatorX.minScale,(s.__indicatorX.size-Math.abs(s.__scrollLeft))/s.__indicatorX.size),o=0,s.__indicatorX.indicator.style[s.__transformOriginProperty]="left center"):n>0?(t=Math.max(s.__indicatorX.minScale,(s.__indicatorX.size-n)/s.__indicatorX.size),o=s.__indicatorX.maxPos-a,s.__indicatorX.indicator.style[s.__transformOriginProperty]="right center"):(o=Math.min(s.__maxScrollLeft,Math.max(0,o)),t=1);var c="translate3d("+o+"px, 0, 0) scaleX("+t+")";s.__indicatorX.transformProp!==c&&(s.__indicatorX.indicator.style[s.__transformProperty]=c,s.__indicatorX.transformProp=c)}if(s.__indicatorY){r=Math.round(s.__indicatorY.sizeRatio*s.__scrollTop)||0,s.__indicatorX&&(l=10),i=s.__scrollTop-(s.__maxScrollTop-l),s.__scrollTop<0?(e=Math.max(s.__indicatorY.minScale,(s.__indicatorY.size-Math.abs(s.__scrollTop))/s.__indicatorY.size),r=0,"center top"!==s.__indicatorY.originProp&&(s.__indicatorY.indicator.style[s.__transformOriginProperty]="center top",s.__indicatorY.originProp="center top")):i>0?(e=Math.max(s.__indicatorY.minScale,(s.__indicatorY.size-i)/s.__indicatorY.size),r=s.__indicatorY.maxPos-l,"center bottom"!==s.__indicatorY.originProp&&(s.__indicatorY.indicator.style[s.__transformOriginProperty]="center bottom",s.__indicatorY.originProp="center bottom")):(r=Math.min(s.__maxScrollTop,Math.max(0,r)),e=1);var u="translate3d(0,"+r+"px, 0) scaleY("+e+")";s.__indicatorY.transformProp!==u&&(s.__indicatorY.indicator.style[s.__transformProperty]=u,s.__indicatorY.transformProp=u)}},__fadeScrollbars:function(e,t){var n=this;if(n.options.scrollbarsFade){var i="scroll-bar-fade-out";n.options.scrollbarsFade===!0&&(clearTimeout(n.__scrollbarFadeTimeout),"in"==e?(n.__indicatorX&&n.__indicatorX.indicator.classList.remove(i),n.__indicatorY&&n.__indicatorY.indicator.classList.remove(i)):n.__scrollbarFadeTimeout=setTimeout(function(){n.__indicatorX&&n.__indicatorX.indicator.classList.add(i),n.__indicatorY&&n.__indicatorY.indicator.classList.add(i)},t||n.options.scrollbarFadeDelay))}},__scrollingComplete:function(){this.options.scrollingComplete(),e.tap.removeClonedInputs(this.__container,this),this.__fadeScrollbars("out")},resize:function(e){var t=this;t.__container&&t.options&&t.setDimensions(t.__container.clientWidth,t.__container.clientHeight,t.options.getContentWidth(),t.options.getContentHeight(),e)},getRenderFn:function(){var e,t=this,n=t.__content,i=document.documentElement.style;"MozAppearance"in i?e="gecko":"WebkitAppearance"in i?e="webkit":"string"==typeof navigator.cpuClass&&(e="trident");var o,r={trident:"ms",gecko:"Moz",webkit:"Webkit",presto:"O"}[e],s=document.createElement("div"),a=r+"Perspective",l=r+"Transform",c=r+"TransformOrigin";return t.__perspectiveProperty=l,t.__transformProperty=l,t.__transformOriginProperty=c,s.style[a]!==o?function(e,i,o,r){var s="translate3d("+-e+"px,"+-i+"px,0) scale("+o+")";s!==t.contentTransform&&(n.style[l]=s,t.contentTransform=s),t.__repositionScrollbars(),r||t.triggerScrollEvent()}:s.style[l]!==o?function(e,i,o,r){n.style[l]="translate("+-e+"px,"+-i+"px) scale("+o+")",t.__repositionScrollbars(),r||t.triggerScrollEvent()}:function(e,i,o,r){n.style.marginLeft=e?-e/o+"px":"",n.style.marginTop=i?-i/o+"px":"",n.style.zoom=o||"",t.__repositionScrollbars(),r||t.triggerScrollEvent()}},setDimensions:function(e,t,n,i,o){var r=this;(e||t||n||i)&&(e===+e&&(r.__clientWidth=e),t===+t&&(r.__clientHeight=t),n===+n&&(r.__contentWidth=n),i===+i&&(r.__contentHeight=i),r.__computeScrollMax(),r.__resizeScrollbars(),o||r.scrollTo(r.__scrollLeft,r.__scrollTop,!0,null,!0))},setPosition:function(e,t){this.__clientLeft=e||0,this.__clientTop=t||0},setSnapSize:function(e,t){this.__snapWidth=e,this.__snapHeight=t},activatePullToRefresh:function(t,n){var i=this;i.__refreshHeight=t,i.__refreshActivate=function(){e.requestAnimationFrame(n.activate)},i.__refreshDeactivate=function(){e.requestAnimationFrame(n.deactivate)},i.__refreshStart=function(){e.requestAnimationFrame(n.start)},i.__refreshShow=function(){e.requestAnimationFrame(n.show)},i.__refreshHide=function(){e.requestAnimationFrame(n.hide)},i.__refreshTail=function(){e.requestAnimationFrame(n.tail)},i.__refreshTailTime=100,i.__minSpinTime=600},triggerPullToRefresh:function(){this.__publish(this.__scrollLeft,-this.__refreshHeight,this.__zoomLevel,!0);var e=new Date;this.refreshStartTime=e.getTime(),this.__refreshStart&&this.__refreshStart()},finishPullToRefresh:function(){var e=this,t=new Date,n=0;e.refreshStartTime+e.__minSpinTime>t.getTime()&&(n=e.refreshStartTime+e.__minSpinTime-t.getTime()),setTimeout(function(){e.__refreshTail&&e.__refreshTail(),setTimeout(function(){e.__refreshActive=!1,e.__refreshDeactivate&&e.__refreshDeactivate(),e.__refreshHide&&e.__refreshHide(),e.scrollTo(e.__scrollLeft,e.__scrollTop,!0)},e.__refreshTailTime)},n)},getValues:function(){return{left:this.__scrollLeft,top:this.__scrollTop,zoom:this.__zoomLevel}},getScrollMax:function(){return{left:this.__maxScrollLeft,top:this.__maxScrollTop}},zoomTo:function(e,t,n,i){var o=this;if(!o.options.zooming)throw new Error("Zooming is not enabled!");o.__isDecelerating&&(he.effect.Animate.stop(o.__isDecelerating),o.__isDecelerating=!1);var r=o.__zoomLevel;null==n&&(n=o.__clientWidth/2),null==i&&(i=o.__clientHeight/2),e=Math.max(Math.min(e,o.options.maxZoom),o.options.minZoom),o.__computeScrollMax(e);var s=(n+o.__scrollLeft)*e/r-n,a=(i+o.__scrollTop)*e/r-i;s>o.__maxScrollLeft?s=o.__maxScrollLeft:0>s&&(s=0),a>o.__maxScrollTop?a=o.__maxScrollTop:0>a&&(a=0),o.__publish(s,a,e,t)},zoomBy:function(e,t,n,i){this.zoomTo(this.__zoomLevel*e,t,n,i)},scrollTo:function(e,t,n,i,o){var r=this;if(r.__isDecelerating&&(he.effect.Animate.stop(r.__isDecelerating),r.__isDecelerating=!1),null!=i&&i!==r.__zoomLevel){if(!r.options.zooming)throw new Error("Zooming is not enabled!");e*=i,t*=i,r.__computeScrollMax(i)}else i=r.__zoomLevel;r.options.scrollingX?r.options.paging?e=Math.round(e/r.__clientWidth)*r.__clientWidth:r.options.snapping&&(e=Math.round(e/r.__snapWidth)*r.__snapWidth):e=r.__scrollLeft,r.options.scrollingY?r.options.paging?t=Math.round(t/r.__clientHeight)*r.__clientHeight:r.options.snapping&&(t=Math.round(t/r.__snapHeight)*r.__snapHeight):t=r.__scrollTop,e=Math.max(Math.min(r.__maxScrollLeft,e),0),t=Math.max(Math.min(r.__maxScrollTop,t),0),e===r.__scrollLeft&&t===r.__scrollTop&&(n=!1),r.__publish(e,t,i,n,o)},scrollBy:function(e,t,n){var i=this,o=i.__isAnimating?i.__scheduledLeft:i.__scrollLeft,r=i.__isAnimating?i.__scheduledTop:i.__scrollTop;i.scrollTo(o+(e||0),r+(t||0),n)},doMouseZoom:function(e,t,n,i){var o=e>0?.97:1.03;return this.zoomTo(this.__zoomLevel*o,!1,n-this.__clientLeft,i-this.__clientTop)},doTouchStart:function(e,t){var n=this;n.__decStopped=!(!n.__isDecelerating&&!n.__isAnimating),n.hintResize(),t instanceof Date&&(t=t.valueOf()),"number"!=typeof t&&(t=Date.now()),n.__interruptedAnimation=!0,n.__isDecelerating&&(he.effect.Animate.stop(n.__isDecelerating),n.__isDecelerating=!1,n.__interruptedAnimation=!0),n.__isAnimating&&(he.effect.Animate.stop(n.__isAnimating),n.__isAnimating=!1,n.__interruptedAnimation=!0);var i,o,r=1===e.length;r?(i=e[0].pageX,o=e[0].pageY):(i=Math.abs(e[0].pageX+e[1].pageX)/2,o=Math.abs(e[0].pageY+e[1].pageY)/2),n.__initialTouchLeft=i,n.__initialTouchTop=o,n.__initialTouches=e,n.__zoomLevelStart=n.__zoomLevel,n.__lastTouchLeft=i,n.__lastTouchTop=o,n.__lastTouchMove=t,n.__lastScale=1,n.__enableScrollX=!r&&n.options.scrollingX,n.__enableScrollY=!r&&n.options.scrollingY,n.__isTracking=!0,n.__didDecelerationComplete=!1,n.__isDragging=!r,n.__isSingleTouch=r,n.__positions=[]},doTouchMove:function(e,t,n){t instanceof Date&&(t=t.valueOf()),"number"!=typeof t&&(t=Date.now());var i=this;if(i.__isTracking){var o,r;2===e.length?(o=Math.abs(e[0].pageX+e[1].pageX)/2,r=Math.abs(e[0].pageY+e[1].pageY)/2,!n&&i.options.zooming&&(n=i.__getScale(i.__initialTouches,e))):(o=e[0].pageX,r=e[0].pageY);var s=i.__positions;if(i.__isDragging){i.__decStopped=!1;var a=o-i.__lastTouchLeft,l=r-i.__lastTouchTop,c=i.__scrollLeft,u=i.__scrollTop,d=i.__zoomLevel;if(null!=n&&i.options.zooming){var _=d;if(d=d/i.__lastScale*n,d=Math.max(Math.min(d,i.options.maxZoom),i.options.minZoom),_!==d){var h=o-i.__clientLeft,f=r-i.__clientTop;c=(h+c)*d/_-h,u=(f+u)*d/_-f,i.__computeScrollMax(d)}}if(i.__enableScrollX){c-=a*i.options.speedMultiplier;var p=i.__maxScrollLeft;(c>p||0>c)&&(i.options.bouncing?c+=a/2*i.options.speedMultiplier:c=c>p?p:0)}if(i.__enableScrollY){u-=l*i.options.speedMultiplier;var m=i.__maxScrollTop;u>m||0>u?i.options.bouncing||i.__refreshHeight&&0>u?(u+=l/2*i.options.speedMultiplier,i.__enableScrollX||null==i.__refreshHeight||(0>u?(i.__refreshHidden=!1,i.__refreshShow()):(i.__refreshHide(),i.__refreshHidden=!0),!i.__refreshActive&&u<=-i.__refreshHeight?(i.__refreshActive=!0,i.__refreshActivate&&i.__refreshActivate()):i.__refreshActive&&u>-i.__refreshHeight&&(i.__refreshActive=!1,i.__refreshDeactivate&&i.__refreshDeactivate()))):u=u>m?m:0:i.__refreshHeight&&!i.__refreshHidden&&(i.__refreshHide(),i.__refreshHidden=!0)}s.length>60&&s.splice(0,30),s.push(c,u,t),i.__publish(c,u,d)}else{var g=i.options.locking?3:0,v=5,T=Math.abs(o-i.__initialTouchLeft),E=Math.abs(r-i.__initialTouchTop);i.__enableScrollX=i.options.scrollingX&&T>=g,i.__enableScrollY=i.options.scrollingY&&E>=g,s.push(i.__scrollLeft,i.__scrollTop,t),i.__isDragging=(i.__enableScrollX||i.__enableScrollY)&&(T>=v||E>=v),i.__isDragging&&(i.__interruptedAnimation=!1,i.__fadeScrollbars("in"))}i.__lastTouchLeft=o,i.__lastTouchTop=r,i.__lastTouchMove=t,i.__lastScale=n}},doTouchEnd:function(t,n){n instanceof Date&&(n=n.valueOf()),"number"!=typeof n&&(n=Date.now());var i=this;if(i.__isTracking){if(i.__isTracking=!1,i.__isDragging)if(i.__isDragging=!1,i.__isSingleTouch&&i.options.animating&&n-i.__lastTouchMove<=100){for(var o=i.__positions,r=o.length-1,s=r,a=r;a>0&&o[a]>i.__lastTouchMove-100;a-=3)s=a;if(s!==r){var l=o[r]-o[s],c=i.__scrollLeft-o[s-2],u=i.__scrollTop-o[s-1];i.__decelerationVelocityX=c/l*(1e3/60),i.__decelerationVelocityY=u/l*(1e3/60);var d=i.options.paging||i.options.snapping?i.options.decelVelocityThresholdPaging:i.options.decelVelocityThreshold;(Math.abs(i.__decelerationVelocityX)>d||Math.abs(i.__decelerationVelocityY)>d)&&(i.__refreshActive||i.__startDeceleration(n))}else i.__scrollingComplete()}else n-i.__lastTouchMove>100&&i.__scrollingComplete();else i.__decStopped&&(t.isTapHandled=!0,i.__decStopped=!1);if(!i.__isDecelerating)if(i.__refreshActive&&i.__refreshStart){i.__publish(i.__scrollLeft,-i.__refreshHeight,i.__zoomLevel,!0);var _=new Date;i.refreshStartTime=_.getTime(),i.__refreshStart&&i.__refreshStart(),e.Platform.isAndroid()||i.__startDeceleration()}else(i.__interruptedAnimation||i.__isDragging)&&i.__scrollingComplete(),i.scrollTo(i.__scrollLeft,i.__scrollTop,!0,i.__zoomLevel),i.__refreshActive&&(i.__refreshActive=!1,i.__refreshDeactivate&&i.__refreshDeactivate());i.__positions.length=0}},__publish:function(e,t,o,r,s){var a=this,l=a.__isAnimating;if(l&&(he.effect.Animate.stop(l),a.__isAnimating=!1),r&&a.options.animating){a.__scheduledLeft=e,a.__scheduledTop=t,
a.__scheduledZoom=o;var c=a.__scrollLeft,u=a.__scrollTop,d=a.__zoomLevel,_=e-c,h=t-u,f=o-d,p=function(e,t,n){n&&(a.__scrollLeft=c+_*e,a.__scrollTop=u+h*e,a.__zoomLevel=d+f*e,a.__callback&&a.__callback(a.__scrollLeft,a.__scrollTop,a.__zoomLevel,s))},m=function(e){return a.__isAnimating===e},g=function(e,t,n){t===a.__isAnimating&&(a.__isAnimating=!1),(a.__didDecelerationComplete||n)&&a.__scrollingComplete(),a.options.zooming&&a.__computeScrollMax()};a.__isAnimating=he.effect.Animate.start(p,m,g,a.options.animationDuration,l?n:i)}else a.__scheduledLeft=a.__scrollLeft=e,a.__scheduledTop=a.__scrollTop=t,a.__scheduledZoom=a.__zoomLevel=o,a.__callback&&a.__callback(e,t,o,s),a.options.zooming&&a.__computeScrollMax()},__computeScrollMax:function(e){var t=this;null==e&&(e=t.__zoomLevel),t.__maxScrollLeft=Math.max(t.__contentWidth*e-t.__clientWidth,0),t.__maxScrollTop=Math.max(t.__contentHeight*e-t.__clientHeight,0),t.__didWaitForSize||t.__maxScrollLeft||t.__maxScrollTop||(t.__didWaitForSize=!0,t.__waitForSize())},__waitForSize:function(){var e=this;clearTimeout(e.__sizerTimeout);var t=function(){e.resize(!0)};t(),e.__sizerTimeout=setTimeout(t,500)},__startDeceleration:function(){var e=this;if(e.options.paging){var t=Math.max(Math.min(e.__scrollLeft,e.__maxScrollLeft),0),n=Math.max(Math.min(e.__scrollTop,e.__maxScrollTop),0),i=e.__clientWidth,o=e.__clientHeight;e.__minDecelerationScrollLeft=Math.floor(t/i)*i,e.__minDecelerationScrollTop=Math.floor(n/o)*o,e.__maxDecelerationScrollLeft=Math.ceil(t/i)*i,e.__maxDecelerationScrollTop=Math.ceil(n/o)*o}else e.__minDecelerationScrollLeft=0,e.__minDecelerationScrollTop=0,e.__maxDecelerationScrollLeft=e.__maxScrollLeft,e.__maxDecelerationScrollTop=e.__maxScrollTop,e.__refreshActive&&(e.__minDecelerationScrollTop=-1*e.__refreshHeight);var r=function(t,n,i){e.__stepThroughDeceleration(i)};e.__minVelocityToKeepDecelerating=e.options.snapping?4:.1;var s=function(){var t=Math.abs(e.__decelerationVelocityX)>=e.__minVelocityToKeepDecelerating||Math.abs(e.__decelerationVelocityY)>=e.__minVelocityToKeepDecelerating;return t||(e.__didDecelerationComplete=!0,e.options.bouncing&&!e.__refreshActive&&e.scrollTo(Math.min(Math.max(e.__scrollLeft,0),e.__maxScrollLeft),Math.min(Math.max(e.__scrollTop,0),e.__maxScrollTop),e.__refreshActive)),t},a=function(){e.__isDecelerating=!1,e.__didDecelerationComplete&&e.__scrollingComplete(),e.options.paging&&e.scrollTo(e.__scrollLeft,e.__scrollTop,e.options.snapping)};e.__isDecelerating=he.effect.Animate.start(r,s,a)},__stepThroughDeceleration:function(e){var t=this,n=t.__scrollLeft+t.__decelerationVelocityX,i=t.__scrollTop+t.__decelerationVelocityY;if(!t.options.bouncing){var o=Math.max(Math.min(t.__maxDecelerationScrollLeft,n),t.__minDecelerationScrollLeft);o!==n&&(n=o,t.__decelerationVelocityX=0);var r=Math.max(Math.min(t.__maxDecelerationScrollTop,i),t.__minDecelerationScrollTop);r!==i&&(i=r,t.__decelerationVelocityY=0)}if(e?t.__publish(n,i,t.__zoomLevel):(t.__scrollLeft=n,t.__scrollTop=i),!t.options.paging){var s=t.options.deceleration;t.__decelerationVelocityX*=s,t.__decelerationVelocityY*=s}if(t.options.bouncing){var a=0,l=0,c=t.options.penetrationDeceleration,u=t.options.penetrationAcceleration;if(n<t.__minDecelerationScrollLeft?a=t.__minDecelerationScrollLeft-n:n>t.__maxDecelerationScrollLeft&&(a=t.__maxDecelerationScrollLeft-n),i<t.__minDecelerationScrollTop?l=t.__minDecelerationScrollTop-i:i>t.__maxDecelerationScrollTop&&(l=t.__maxDecelerationScrollTop-i),0!==a){var d=a*t.__decelerationVelocityX<=t.__minDecelerationScrollLeft;d&&(t.__decelerationVelocityX+=a*c);var _=Math.abs(t.__decelerationVelocityX)<=t.__minVelocityToKeepDecelerating;(!d||_)&&(t.__decelerationVelocityX=a*u)}if(0!==l){var h=l*t.__decelerationVelocityY<=t.__minDecelerationScrollTop;h&&(t.__decelerationVelocityY+=l*c);var f=Math.abs(t.__decelerationVelocityY)<=t.__minVelocityToKeepDecelerating;(!h||f)&&(t.__decelerationVelocityY=l*u)}}},__getDistance:function(e,t){var n=t.pageX-e.pageX,i=t.pageY-e.pageY;return Math.sqrt(n*n+i*i)},__getScale:function(e,t){return e.length>=2&&t.length>=2?this.__getDistance(t[0],t[1])/this.__getDistance(e[0],e[1]):1}}),e.scroll={isScrolling:!1,lastTop:0}}(ionic),function(e){var t=function(){},n=function(e){};e.views.ScrollNative=e.views.View.inherit({initialize:function(n){var i=this;i.__container=i.el=n.el,i.__content=n.el.firstElementChild,i.isNative=!0,i.__scrollTop=i.el.scrollTop,i.__scrollLeft=i.el.scrollLeft,i.__clientHeight=i.__content.clientHeight,i.__clientWidth=i.__content.clientWidth,i.__maxScrollTop=Math.max(i.__contentHeight-i.__clientHeight,0),i.__maxScrollLeft=Math.max(i.__contentWidth-i.__clientWidth,0),i.options={freeze:!1,getContentWidth:function(){return Math.max(i.__content.scrollWidth,i.__content.offsetWidth)},getContentHeight:function(){return Math.max(i.__content.scrollHeight,i.__content.offsetHeight+2*i.__content.offsetTop)}};for(var o in n)i.options[o]=n[o];i.onScroll=function(){e.scroll.isScrolling||(e.scroll.isScrolling=!0),clearTimeout(i.scrollTimer),i.scrollTimer=setTimeout(function(){e.scroll.isScrolling=!1},80)},i.freeze=t,i.__initEventHandlers()},__callback:function(){n("__callback")},zoomTo:function(){n("zoomTo")},zoomBy:function(){n("zoomBy")},activatePullToRefresh:function(){n("activatePullToRefresh")},resize:function(e){var t=this;t.__container&&t.options&&t.setDimensions(t.__container.clientWidth,t.__container.clientHeight,t.options.getContentWidth(),t.options.getContentHeight(),e)},run:function(){this.resize()},getValues:function(){var e=this;return e.update(),{left:e.__scrollLeft,top:e.__scrollTop,zoom:1}},update:function(){var e=this;e.__scrollLeft=e.el.scrollLeft,e.__scrollTop=e.el.scrollTop},setDimensions:function(e,t,n,i){var o=this;(e||t||n||i)&&(e===+e&&(o.__clientWidth=e),t===+t&&(o.__clientHeight=t),n===+n&&(o.__contentWidth=n),i===+i&&(o.__contentHeight=i),o.__computeScrollMax())},getScrollMax:function(){return{left:this.__maxScrollLeft,top:this.__maxScrollTop}},scrollBy:function(e,t,n){var i=this;i.update();var o=i.__isAnimating?i.__scheduledLeft:i.__scrollLeft,r=i.__isAnimating?i.__scheduledTop:i.__scrollTop;i.scrollTo(o+(e||0),r+(t||0),n)},scrollTo:function(t,n,i){function o(t,n){function i(e){return--e*e*e+1}function o(){var u=Date.now(),d=Math.min(1,(u-s)/a),_=i(d);l!=t&&(r.el.scrollTop=parseInt(_*(t-l)+l,10)),c!=n&&(r.el.scrollLeft=parseInt(_*(n-c)+c,10)),1>d?e.requestAnimationFrame(o):(e.tap.removeClonedInputs(r.__container,r),r.resize())}var s=Date.now(),a=250,l=r.el.scrollTop,c=r.el.scrollLeft;return l===t&&c===n?void r.resize():void e.requestAnimationFrame(o)}var r=this;return i?void o(n,t):(r.el.scrollTop=n,r.el.scrollLeft=t,void r.resize())},__waitForSize:function(){var e=this;clearTimeout(e.__sizerTimeout);var t=function(){e.resize(!0)};t(),e.__sizerTimeout=setTimeout(t,500)},__computeScrollMax:function(){var e=this;e.__maxScrollLeft=Math.max(e.__contentWidth-e.__clientWidth,0),e.__maxScrollTop=Math.max(e.__contentHeight-e.__clientHeight,0),e.__didWaitForSize||e.__maxScrollLeft||e.__maxScrollTop||(e.__didWaitForSize=!0,e.__waitForSize())},__initEventHandlers:function(){var t,n=this,i=n.__container;n.scrollChildIntoView=function(o){var r=i.getBoundingClientRect().bottom;t=i.offsetHeight;var s=n.isShrunkForKeyboard,a=i.parentNode.classList.contains("modal"),l=a&&window.innerWidth>=680;if(!s){if(e.Platform.isIOS()||e.Platform.isFullScreen||l){var c=o.detail.viewportHeight-r,u=Math.max(0,o.detail.keyboardHeight-c);e.requestAnimationFrame(function(){t-=u,i.style.height=t+"px",n.resize()})}n.isShrunkForKeyboard=!0}o.detail.isElementUnderKeyboard&&e.requestAnimationFrame(function(){n.isShrunkForKeyboard&&!s&&(r=i.getBoundingClientRect().bottom);var a=.5*t,l=(o.detail.elementBottom+o.detail.elementTop)/2,c=l-r,u=c+a;u>0&&(e.Platform.isIOS()?setTimeout(function(){e.tap.cloneFocusedInput(i,n),n.scrollBy(0,u,!0),n.onScroll()},32):(n.scrollBy(0,u,!0),n.onScroll()))}),o.stopPropagation()},n.resetScrollView=function(){n.isShrunkForKeyboard&&(n.isShrunkForKeyboard=!1,i.style.height=""),n.resize()},i.addEventListener("scroll",n.onScroll),i.addEventListener("scrollChildIntoView",n.scrollChildIntoView),document.addEventListener("resetScrollView",n.resetScrollView)},__cleanup:function(){var n=this,i=n.__container;i.removeEventListener("resetScrollView",n.resetScrollView),i.removeEventListener("scroll",n.onScroll),i.removeEventListener("scrollChildIntoView",n.scrollChildIntoView),i.removeEventListener("resetScrollView",n.resetScrollView),e.tap.removeClonedInputs(i,n),delete n.__container,delete n.__content,delete n.__indicatorX,delete n.__indicatorY,delete n.options.el,n.resize=n.scrollTo=n.onScroll=n.resetScrollView=t,n.scrollChildIntoView=t,i=null}})}(ionic),function(e){"use strict";var t="item",n="item-content",i="item-sliding",o="item-options",r="item-placeholder",s="item-reordering",a="item-reorder",l=function(){};l.prototype={start:function(){},drag:function(){},end:function(){},isSameItem:function(){return!1}};var c=function(e){this.dragThresholdX=e.dragThresholdX||10,this.el=e.el,this.item=e.item,this.canSwipe=e.canSwipe};c.prototype=new l,c.prototype.start=function(r){var s,a,l,c;this.canSwipe()&&(s=r.target.classList.contains(n)?r.target:r.target.classList.contains(t)?r.target.querySelector("."+n):e.DomUtil.getParentWithClass(r.target,n),s&&(s.classList.remove(i),l=parseFloat(s.style[e.CSS.TRANSFORM].replace("translate3d(","").split(",")[0])||0,a=s.parentNode.querySelector("."+o),a&&(a.classList.remove("invisible"),c=a.offsetWidth,this._currentDrag={buttons:a,buttonsWidth:c,content:s,startOffsetX:l})))},c.prototype.isSameItem=function(e){return e._lastDrag&&this._currentDrag?this._currentDrag.content==e._lastDrag.content:!1},c.prototype.clean=function(t){function n(){i.buttons&&i.buttons.classList.add("invisible")}var i=this._lastDrag;i&&i.content&&(i.content.style[e.CSS.TRANSITION]="",i.content.style[e.CSS.TRANSFORM]="",t?(i.content.style[e.CSS.TRANSITION]="none",n(),e.requestAnimationFrame(function(){i.content.style[e.CSS.TRANSITION]=""})):e.requestAnimationFrame(function(){setTimeout(n,250)}))},c.prototype.drag=e.animationFrameThrottle(function(t){var n;if(this._currentDrag&&(!this._isDragging&&(Math.abs(t.gesture.deltaX)>this.dragThresholdX||Math.abs(this._currentDrag.startOffsetX)>0)&&(this._isDragging=!0),this._isDragging)){n=this._currentDrag.buttonsWidth;var i=Math.min(0,this._currentDrag.startOffsetX+t.gesture.deltaX);-n>i&&(i=Math.min(-n,-n+.4*(t.gesture.deltaX+n))),this._currentDrag.content.$$ionicOptionsOpen=0!==i,this._currentDrag.content.style[e.CSS.TRANSFORM]="translate3d("+i+"px, 0, 0)",this._currentDrag.content.style[e.CSS.TRANSITION]="none"}}),c.prototype.end=function(t,n){var i=this;if(!i._currentDrag)return void(n&&n());var o=-i._currentDrag.buttonsWidth;t.gesture.deltaX>-(i._currentDrag.buttonsWidth/2)&&("left"==t.gesture.direction&&Math.abs(t.gesture.velocityX)<.3?o=0:"right"==t.gesture.direction&&(o=0)),e.requestAnimationFrame(function(){if(0===o){i._currentDrag.content.style[e.CSS.TRANSFORM]="";var t=i._currentDrag.buttons;setTimeout(function(){t&&t.classList.add("invisible")},250)}else i._currentDrag.content.style[e.CSS.TRANSFORM]="translate3d("+o+"px,0,0)";i._currentDrag.content.style[e.CSS.TRANSITION]="",i._lastDrag||(i._lastDrag={}),e.extend(i._lastDrag,i._currentDrag),i._currentDrag&&(i._currentDrag.buttons=null,i._currentDrag.content=null),i._currentDrag=null,n&&n()})};var u=function(e){var t=this;if(t.dragThresholdY=e.dragThresholdY||0,t.onReorder=e.onReorder,t.listEl=e.listEl,t.el=t.item=e.el,t.scrollEl=e.scrollEl,t.scrollView=e.scrollView,t.listElTrueTop=0,t.listEl.offsetParent){var n=t.listEl;do t.listElTrueTop+=n.offsetTop,n=n.offsetParent;while(n)}};u.prototype=new l,u.prototype._moveElement=function(t){var n=t.gesture.center.pageY+this.scrollView.getValues().top-this._currentDrag.elementHeight/2-this.listElTrueTop;this.el.style[e.CSS.TRANSFORM]="translate3d(0, "+n+"px, 0)"},u.prototype.deregister=function(){this.listEl=this.el=this.scrollEl=this.scrollView=null},u.prototype.start=function(t){var n=e.DomUtil.getChildIndex(this.el,this.el.nodeName.toLowerCase()),i=this.el.scrollHeight,o=this.el.cloneNode(!0);o.classList.add(r),this.el.parentNode.insertBefore(o,this.el),this.el.classList.add(s),this._currentDrag={elementHeight:i,startIndex:n,placeholder:o,scrollHeight:scroll,list:o.parentNode},this._moveElement(t)},u.prototype.drag=e.animationFrameThrottle(function(t){var n=this;if(this._currentDrag){var i=0,o=t.gesture.center.pageY,r=this.listElTrueTop;if(this.scrollView){var s=this.scrollView.__container;i=this.scrollView.getValues().top;var a=s.offsetTop,l=a-o+this._currentDrag.elementHeight/2,c=o+this._currentDrag.elementHeight/2-a-s.offsetHeight;t.gesture.deltaY<0&&l>0&&i>0&&(this.scrollView.scrollBy(null,-l),e.requestAnimationFrame(function(){n.drag(t)})),t.gesture.deltaY>0&&c>0&&i<this.scrollView.getScrollMax().top&&(this.scrollView.scrollBy(null,c),e.requestAnimationFrame(function(){n.drag(t)}))}!this._isDragging&&Math.abs(t.gesture.deltaY)>this.dragThresholdY&&(this._isDragging=!0),this._isDragging&&(this._moveElement(t),this._currentDrag.currentY=i+o-r)}}),u.prototype._getReorderIndex=function(){for(var e,t=this,n=Array.prototype.slice.call(t._currentDrag.placeholder.parentNode.children).filter(function(e){return e.nodeName===t.el.nodeName&&e!==t.el}),i=t._currentDrag.currentY,o=0,r=n.length;r>o;o++)if(e=n[o],o===r-1){if(i>e.offsetTop)return o}else if(0===o){if(i<e.offsetTop+e.offsetHeight)return o}else if(i>e.offsetTop-e.offsetHeight/2&&i<e.offsetTop+e.offsetHeight)return o;return t._currentDrag.startIndex},u.prototype.end=function(t,n){if(!this._currentDrag)return void(n&&n());var i=this._currentDrag.placeholder,o=this._getReorderIndex();this.el.classList.remove(s),this.el.style[e.CSS.TRANSFORM]="",i.parentNode.insertBefore(this.el,i),i.parentNode.removeChild(i),this.onReorder&&this.onReorder(this.el,this._currentDrag.startIndex,o),this._currentDrag={placeholder:null,content:null},this._currentDrag=null,n&&n()},e.views.ListView=e.views.View.inherit({initialize:function(t){var n=this;t=e.extend({onReorder:function(){},virtualRemoveThreshold:-200,virtualAddThreshold:200,canSwipe:function(){return!0}},t),e.extend(n,t),!n.itemHeight&&n.listEl&&(n.itemHeight=n.listEl.children[0]&&parseInt(n.listEl.children[0].style.height,10)),n.onRefresh=t.onRefresh||function(){},n.onRefreshOpening=t.onRefreshOpening||function(){},n.onRefreshHolding=t.onRefreshHolding||function(){};var i={};e.DomUtil.getParentOrSelfWithClass(n.el,"overflow-scroll")&&(i.prevent_default_directions=["left","right"]),window.ionic.onGesture("release",function(e){n._handleEndDrag(e)},n.el,i),window.ionic.onGesture("drag",function(e){n._handleDrag(e)},n.el,i),n._initDrag()},deregister:function(){this.el=this.listEl=this.scrollEl=this.scrollView=null,this.isScrollFreeze&&self.scrollView.freeze(!1)},stopRefreshing:function(){var e=this.el.querySelector(".list-refresher");e.style.height="0"},didScroll:function(e){var t=this;if(t.isVirtual){var n=t.itemHeight,i=e.target.scrollHeight,o=t.el.parentNode.offsetHeight,r=Math.max(0,e.scrollTop+t.virtualRemoveThreshold),s=Math.min(i,Math.abs(e.scrollTop)+o+t.virtualAddThreshold),a=parseInt(Math.abs(r/n),10),l=parseInt(Math.abs(s/n),10);t._virtualItemsToRemove=Array.prototype.slice.call(t.listEl.children,0,a),t.renderViewport&&t.renderViewport(r,s,a,l)}},didStopScrolling:function(){if(this.isVirtual)for(var e=0;e<this._virtualItemsToRemove.length;e++)this.didHideItem&&this.didHideItem(e)},clearDragEffects:function(e){this._lastDragOp&&(this._lastDragOp.clean&&this._lastDragOp.clean(e),this._lastDragOp.deregister&&this._lastDragOp.deregister(),this._lastDragOp=null)},_initDrag:function(){this._lastDragOp&&this._lastDragOp.deregister&&this._lastDragOp.deregister(),this._lastDragOp=this._dragOp,this._dragOp=null},_getItem:function(e){for(;e;){if(e.classList&&e.classList.contains(t))return e;e=e.parentNode}return null},_startDrag:function(t){var n=this;n._isDragging=!1;var i,o=n._lastDragOp;n._didDragUpOrDown&&o instanceof c&&o.clean&&o.clean(),!e.DomUtil.getParentOrSelfWithClass(t.target,a)||"up"!=t.gesture.direction&&"down"!=t.gesture.direction?!n._didDragUpOrDown&&("left"==t.gesture.direction||"right"==t.gesture.direction)&&Math.abs(t.gesture.deltaX)>5&&(i=n._getItem(t.target),i&&i.querySelector(".item-options")&&(n._dragOp=new c({el:n.el,item:i,canSwipe:n.canSwipe}),n._dragOp.start(t),t.preventDefault(),n.isScrollFreeze=n.scrollView.freeze(!0))):(i=n._getItem(t.target),i&&(n._dragOp=new u({listEl:n.el,el:i,scrollEl:n.scrollEl,scrollView:n.scrollView,onReorder:function(e,t,i){n.onReorder&&n.onReorder(e,t,i)}}),n._dragOp.start(t),t.preventDefault())),o&&n._dragOp&&!n._dragOp.isSameItem(o)&&t.defaultPrevented&&o.clean&&o.clean()},_handleEndDrag:function(e){var t=this;t.scrollView&&(t.isScrollFreeze=t.scrollView.freeze(!1)),t._didDragUpOrDown=!1,t._dragOp&&t._dragOp.end(e,function(){t._initDrag()})},_handleDrag:function(e){var t=this;Math.abs(e.gesture.deltaY)>5&&(t._didDragUpOrDown=!0),t.isDragging||t._dragOp||t._startDrag(e),t._dragOp&&(e.gesture.srcEvent.preventDefault(),t._dragOp.drag(e))}})}(ionic),function(e){"use strict";e.views.Modal=e.views.View.inherit({initialize:function(t){t=e.extend({focusFirstInput:!1,unfocusOnHide:!0,focusFirstDelay:600,backdropClickToClose:!0,hardwareBackButtonClose:!0},t),e.extend(this,t),this.el=t.el},show:function(){var e=this;e.focusFirstInput&&window.setTimeout(function(){var t=e.el.querySelector("input, textarea");t&&t.focus&&t.focus()},e.focusFirstDelay)},hide:function(){if(this.unfocusOnHide){var e=this.el.querySelectorAll("input, textarea");window.setTimeout(function(){for(var t=0;t<e.length;t++)e[t].blur&&e[t].blur()})}}})}(ionic),function(e){"use strict";e.views.SideMenu=e.views.View.inherit({initialize:function(e){this.el=e.el,this.isEnabled="undefined"==typeof e.isEnabled?!0:e.isEnabled,this.setWidth(e.width)},getFullWidth:function(){return this.width},setWidth:function(e){this.width=e,this.el.style.width=e+"px"},setIsEnabled:function(e){this.isEnabled=e},bringUp:function(){"0"!==this.el.style.zIndex&&(this.el.style.zIndex="0")},pushDown:function(){"-1"!==this.el.style.zIndex&&(this.el.style.zIndex="-1")}}),e.views.SideMenuContent=e.views.View.inherit({initialize:function(t){e.extend(this,{animationClass:"menu-animated",onDrag:function(){},onEndDrag:function(){}},t),e.onGesture("drag",e.proxy(this._onDrag,this),this.el),e.onGesture("release",e.proxy(this._onEndDrag,this),this.el)},_onDrag:function(e){this.onDrag&&this.onDrag(e)},_onEndDrag:function(e){this.onEndDrag&&this.onEndDrag(e)},disableAnimation:function(){this.el.classList.remove(this.animationClass)},enableAnimation:function(){this.el.classList.add(this.animationClass)},getTranslateX:function(){return parseFloat(this.el.style[e.CSS.TRANSFORM].replace("translate3d(","").split(",")[0])},setTranslateX:e.animationFrameThrottle(function(t){this.el.style[e.CSS.TRANSFORM]="translate3d("+t+"px, 0, 0)"})})}(ionic),function(e){"use strict";e.views.Slider=e.views.View.inherit({initialize:function(e){function t(){if(p.offsetWidth){m=E.children,T=m.length,m.length<2&&(e.continuous=!1),f.transitions&&e.continuous&&m.length<3&&(E.appendChild(m[0].cloneNode(!0)),E.appendChild(E.children[1].cloneNode(!0)),m=E.children),g=new Array(m.length),v=p.offsetWidth||p.getBoundingClientRect().width,E.style.width=m.length*v+"px";for(var t=m.length;t--;){var n=m[t];n.style.width=v+"px",n.setAttribute("data-index",t),f.transitions&&(n.style.left=t*-v+"px",s(t,S>t?-v:t>S?v:0,0))}e.continuous&&f.transitions&&(s(o(S-1),-v,0),s(o(S+1),v,0)),f.transitions||(E.style.left=S*-v+"px"),p.style.visibility="visible",e.slidesChanged&&e.slidesChanged()}}function n(t){e.continuous?r(S-1,t):S&&r(S-1,t)}function i(t){e.continuous?r(S+1,t):S<m.length-1&&r(S+1,t)}function o(e){return(m.length+e%m.length)%m.length}function r(t,n){if(S!=t){if(f.transitions){var i=Math.abs(S-t)/(S-t);if(e.continuous){var r=i;i=-g[o(t)]/v,i!==r&&(t=-i*m.length+t)}for(var a=Math.abs(S-t)-1;a--;)s(o((t>S?t:S)-a-1),v*i,0);t=o(t),s(S,v*i,n||b),s(t,0,n||b),e.continuous&&s(o(t-i),-(v*i),0)}else t=o(t),l(S*-v,t*-v,n||b);S=t,h(e.callback&&e.callback(S,m[S]))}}function s(e,t,n){a(e,t,n),g[e]=t}function a(e,t,n){var i=m[e],o=i&&i.style;o&&(o.webkitTransitionDuration=o.MozTransitionDuration=o.msTransitionDuration=o.OTransitionDuration=o.transitionDuration=n+"ms",o.webkitTransform="translate("+t+"px,0)translateZ(0)",o.msTransform=o.MozTransform=o.OTransform="translateX("+t+"px)")}function l(t,n,i){if(!i)return void(E.style.left=n+"px");var o=+new Date,r=setInterval(function(){var s=+new Date-o;return s>i?(E.style.left=n+"px",D&&c(),e.transitionEnd&&e.transitionEnd.call(event,S,m[S]),void clearInterval(r)):void(E.style.left=(n-t)*(Math.floor(s/i*100)/100)+t+"px")},4)}function c(){w=setTimeout(i,D)}function u(){D=e.auto||0,clearTimeout(w)}var d=this,_=function(){},h=function(e){setTimeout(e||_,0)},f={addEventListener:!!window.addEventListener,touch:"ontouchstart"in window||window.DocumentTouch&&document instanceof DocumentTouch,transitions:function(e){var t=["transitionProperty","WebkitTransition","MozTransition","OTransition","msTransition"];for(var n in t)if(void 0!==e.style[t[n]])return!0;return!1}(document.createElement("swipe"))},p=e.el;if(p){var m,g,v,T,E=p.children[0];e=e||{};var S=parseInt(e.startSlide,10)||0,b=e.speed||300;e.continuous=void 0!==e.continuous?e.continuous:!0;var w,y,D=e.auto||0,L={},x={},M={handleEvent:function(n){switch(("mousedown"==n.type||"mouseup"==n.type||"mousemove"==n.type)&&(n.touches=[{pageX:n.pageX,pageY:n.pageY}]),n.type){case"mousedown":this.start(n);break;case"touchstart":this.start(n);break;case"touchmove":this.touchmove(n);break;case"mousemove":this.touchmove(n);break;case"touchend":h(this.end(n));break;case"mouseup":h(this.end(n));break;case"webkitTransitionEnd":case"msTransitionEnd":case"oTransitionEnd":case"otransitionend":case"transitionend":h(this.transitionEnd(n));break;case"resize":h(t)}e.stopPropagation&&n.stopPropagation()},start:function(e){var t=e.touches[0];L={x:t.pageX,y:t.pageY,time:+new Date},y=void 0,x={},f.touch?(E.addEventListener("touchmove",this,!1),E.addEventListener("touchend",this,!1)):(E.addEventListener("mousemove",this,!1),E.addEventListener("mouseup",this,!1),document.addEventListener("mouseup",this,!1))},touchmove:function(t){if(!(t.touches.length>1||t.scale&&1!==t.scale||d.slideIsDisabled)){e.disableScroll&&t.preventDefault();var n=t.touches[0];x={x:n.pageX-L.x,y:n.pageY-L.y},"undefined"==typeof y&&(y=!!(y||Math.abs(x.x)<Math.abs(x.y))),y||(t.preventDefault(),u(),e.continuous?(a(o(S-1),x.x+g[o(S-1)],0),a(S,x.x+g[S],0),a(o(S+1),x.x+g[o(S+1)],0)):(x.x=x.x/(!S&&x.x>0||S==m.length-1&&x.x<0?Math.abs(x.x)/v+1:1),a(S-1,x.x+g[S-1],0),a(S,x.x+g[S],0),a(S+1,x.x+g[S+1],0)),e.onDrag&&e.onDrag())}},end:function(){var t=+new Date-L.time,n=Number(t)<250&&Math.abs(x.x)>20||Math.abs(x.x)>v/2,i=!S&&x.x>0||S==m.length-1&&x.x<0;e.continuous&&(i=!1);var r=x.x<0;y||(n&&!i?(r?(e.continuous?(s(o(S-1),-v,0),s(o(S+2),v,0)):s(S-1,-v,0),s(S,g[S]-v,b),s(o(S+1),g[o(S+1)]-v,b),S=o(S+1)):(e.continuous?(s(o(S+1),v,0),s(o(S-2),-v,0)):s(S+1,v,0),s(S,g[S]+v,b),s(o(S-1),g[o(S-1)]+v,b),S=o(S-1)),e.callback&&e.callback(S,m[S])):e.continuous?(s(o(S-1),-v,b),s(S,0,b),s(o(S+1),v,b)):(s(S-1,-v,b),s(S,0,b),s(S+1,v,b))),f.touch?(E.removeEventListener("touchmove",M,!1),E.removeEventListener("touchend",M,!1)):(E.removeEventListener("mousemove",M,!1),E.removeEventListener("mouseup",M,!1),document.removeEventListener("mouseup",M,!1)),e.onDragEnd&&e.onDragEnd()},transitionEnd:function(t){parseInt(t.target.getAttribute("data-index"),10)==S&&(D&&c(),e.transitionEnd&&e.transitionEnd.call(t,S,m[S]))}};this.update=function(){setTimeout(t)},this.setup=function(){t()},this.loop=function(t){return arguments.length&&(e.continuous=!!t),e.continuous},this.enableSlide=function(e){return arguments.length&&(this.slideIsDisabled=!e),!this.slideIsDisabled},this.slide=this.select=function(e,t){u(),r(e,t)},this.prev=this.previous=function(){u(),n()},this.next=function(){u(),i()},this.stop=function(){u()},this.start=function(){c()},this.autoPlay=function(e){!D||0>D?u():(D=e,c())},this.currentIndex=this.selected=function(){return S},this.slidesCount=this.count=function(){return T},this.kill=function(){u(),E.style.width="",E.style.left="",m&&(m=[]),f.addEventListener?(E.removeEventListener("touchstart",M,!1),E.removeEventListener("webkitTransitionEnd",M,!1),E.removeEventListener("msTransitionEnd",M,!1),E.removeEventListener("oTransitionEnd",M,!1),E.removeEventListener("otransitionend",M,!1),E.removeEventListener("transitionend",M,!1),window.removeEventListener("resize",M,!1)):window.onresize=null},this.load=function(){t(),D&&c(),f.addEventListener?(f.touch?E.addEventListener("touchstart",M,!1):E.addEventListener("mousedown",M,!1),f.transitions&&(E.addEventListener("webkitTransitionEnd",M,!1),E.addEventListener("msTransitionEnd",M,!1),E.addEventListener("oTransitionEnd",M,!1),E.addEventListener("otransitionend",M,!1),E.addEventListener("transitionend",M,!1)),window.addEventListener("resize",M,!1)):window.onresize=function(){t()}}}}})}(ionic),function(e){"use strict";e.views.Toggle=e.views.View.inherit({initialize:function(t){var n=this;this.el=t.el,this.checkbox=t.checkbox,this.track=t.track,this.handle=t.handle,this.openPercent=-1,this.onChange=t.onChange||function(){},this.triggerThreshold=t.triggerThreshold||20,this.dragStartHandler=function(e){n.dragStart(e)},this.dragHandler=function(e){n.drag(e)},this.holdHandler=function(e){n.hold(e)},this.releaseHandler=function(e){n.release(e)},this.dragStartGesture=e.onGesture("dragstart",this.dragStartHandler,this.el),this.dragGesture=e.onGesture("drag",this.dragHandler,this.el),this.dragHoldGesture=e.onGesture("hold",this.holdHandler,this.el),this.dragReleaseGesture=e.onGesture("release",this.releaseHandler,this.el)},destroy:function(){e.offGesture(this.dragStartGesture,"dragstart",this.dragStartGesture),e.offGesture(this.dragGesture,"drag",this.dragGesture),e.offGesture(this.dragHoldGesture,"hold",this.holdHandler),e.offGesture(this.dragReleaseGesture,"release",this.releaseHandler)},tap:function(){"disabled"!==this.el.getAttribute("disabled")&&this.val(!this.checkbox.checked)},dragStart:function(e){this.checkbox.disabled||(this._dragInfo={width:this.el.offsetWidth,left:this.el.offsetLeft,right:this.el.offsetLeft+this.el.offsetWidth,triggerX:this.el.offsetWidth/2,initialState:this.checkbox.checked},e.gesture.srcEvent.preventDefault(),this.hold(e))},drag:function(t){var n=this;this._dragInfo&&(t.gesture.srcEvent.preventDefault(),e.requestAnimationFrame(function(){if(n._dragInfo){var e=t.gesture.touches[0].pageX-n._dragInfo.left,i=n._dragInfo.width-n.triggerThreshold;n._dragInfo.initialState?e<n.triggerThreshold?n.setOpenPercent(0):e>n._dragInfo.triggerX&&n.setOpenPercent(100):e<n._dragInfo.triggerX?n.setOpenPercent(0):e>i&&n.setOpenPercent(100)}}))},endDrag:function(){this._dragInfo=null},hold:function(){this.el.classList.add("dragging")},release:function(e){this.el.classList.remove("dragging"),this.endDrag(e)},setOpenPercent:function(t){if(this.openPercent<0||t<this.openPercent-3||t>this.openPercent+3)if(this.openPercent=t,0===t)this.val(!1);else if(100===t)this.val(!0);else{var n=Math.round(t/100*this.track.offsetWidth-this.handle.offsetWidth);n=1>n?0:n,this.handle.style[e.CSS.TRANSFORM]="translate3d("+n+"px,0,0)"}},val:function(t){return(t===!0||t===!1)&&(""!==this.handle.style[e.CSS.TRANSFORM]&&(this.handle.style[e.CSS.TRANSFORM]=""),this.checkbox.checked=t,this.openPercent=t?100:0,this.onChange&&this.onChange()),this.checkbox.checked}})}(ionic)}();
/*!
* ionic.bundle.js is a concatenation of:
* ionic.js, angular.js, angular-animate.js,
* angular-sanitize.js, angular-ui-router.js,
* and ionic-angular.js
*/
/*
AngularJS v1.4.3
(c) 2010-2015 Google, Inc. http://angularjs.org
License: MIT
*/
(function(O,U,t){'use strict';function J(b){return function(){var a=arguments[0],c;c="["+(b?b+":":"")+a+"] http://errors.angularjs.org/1.4.3/"+(b?b+"/":"")+a;for(a=1;a<arguments.length;a++){c=c+(1==a?"?":"&")+"p"+(a-1)+"=";var d=encodeURIComponent,e;e=arguments[a];e="function"==typeof e?e.toString().replace(/ \{[\s\S]*$/,""):"undefined"==typeof e?"undefined":"string"!=typeof e?JSON.stringify(e):e;c+=d(e)}return Error(c)}}function Ea(b){if(null==b||Wa(b))return!1;var a="length"in Object(b)&&b.length;
return b.nodeType===qa&&a?!0:L(b)||G(b)||0===a||"number"===typeof a&&0<a&&a-1 in b}function m(b,a,c){var d,e;if(b)if(z(b))for(d in b)"prototype"==d||"length"==d||"name"==d||b.hasOwnProperty&&!b.hasOwnProperty(d)||a.call(c,b[d],d,b);else if(G(b)||Ea(b)){var f="object"!==typeof b;d=0;for(e=b.length;d<e;d++)(f||d in b)&&a.call(c,b[d],d,b)}else if(b.forEach&&b.forEach!==m)b.forEach(a,c,b);else if(nc(b))for(d in b)a.call(c,b[d],d,b);else if("function"===typeof b.hasOwnProperty)for(d in b)b.hasOwnProperty(d)&&
a.call(c,b[d],d,b);else for(d in b)Xa.call(b,d)&&a.call(c,b[d],d,b);return b}function oc(b,a,c){for(var d=Object.keys(b).sort(),e=0;e<d.length;e++)a.call(c,b[d[e]],d[e]);return d}function pc(b){return function(a,c){b(c,a)}}function Ud(){return++nb}function qc(b,a){a?b.$$hashKey=a:delete b.$$hashKey}function Nb(b,a,c){for(var d=b.$$hashKey,e=0,f=a.length;e<f;++e){var g=a[e];if(H(g)||z(g))for(var h=Object.keys(g),l=0,k=h.length;l<k;l++){var n=h[l],r=g[n];c&&H(r)?aa(r)?b[n]=new Date(r.valueOf()):(H(b[n])||
(b[n]=G(r)?[]:{}),Nb(b[n],[r],!0)):b[n]=r}}qc(b,d);return b}function P(b){return Nb(b,za.call(arguments,1),!1)}function Vd(b){return Nb(b,za.call(arguments,1),!0)}function W(b){return parseInt(b,10)}function Ob(b,a){return P(Object.create(b),a)}function v(){}function Ya(b){return b}function ra(b){return function(){return b}}function rc(b){return z(b.toString)&&b.toString!==Object.prototype.toString}function A(b){return"undefined"===typeof b}function w(b){return"undefined"!==typeof b}function H(b){return null!==
b&&"object"===typeof b}function nc(b){return null!==b&&"object"===typeof b&&!sc(b)}function L(b){return"string"===typeof b}function V(b){return"number"===typeof b}function aa(b){return"[object Date]"===sa.call(b)}function z(b){return"function"===typeof b}function Za(b){return"[object RegExp]"===sa.call(b)}function Wa(b){return b&&b.window===b}function $a(b){return b&&b.$evalAsync&&b.$watch}function ab(b){return"boolean"===typeof b}function tc(b){return!(!b||!(b.nodeName||b.prop&&b.attr&&b.find))}
function Wd(b){var a={};b=b.split(",");var c;for(c=0;c<b.length;c++)a[b[c]]=!0;return a}function ta(b){return M(b.nodeName||b[0]&&b[0].nodeName)}function bb(b,a){var c=b.indexOf(a);0<=c&&b.splice(c,1);return c}function fa(b,a,c,d){if(Wa(b)||$a(b))throw Fa("cpws");if(uc.test(sa.call(a)))throw Fa("cpta");if(a){if(b===a)throw Fa("cpi");c=c||[];d=d||[];H(b)&&(c.push(b),d.push(a));var e;if(G(b))for(e=a.length=0;e<b.length;e++)a.push(fa(b[e],null,c,d));else{var f=a.$$hashKey;G(a)?a.length=0:m(a,function(b,
c){delete a[c]});if(nc(b))for(e in b)a[e]=fa(b[e],null,c,d);else if(b&&"function"===typeof b.hasOwnProperty)for(e in b)b.hasOwnProperty(e)&&(a[e]=fa(b[e],null,c,d));else for(e in b)Xa.call(b,e)&&(a[e]=fa(b[e],null,c,d));qc(a,f)}}else if(a=b,H(b)){if(c&&-1!==(f=c.indexOf(b)))return d[f];if(G(b))return fa(b,[],c,d);if(uc.test(sa.call(b)))a=new b.constructor(b);else if(aa(b))a=new Date(b.getTime());else if(Za(b))a=new RegExp(b.source,b.toString().match(/[^\/]*$/)[0]),a.lastIndex=b.lastIndex;else return e=
Object.create(sc(b)),fa(b,e,c,d);d&&(c.push(b),d.push(a))}return a}function ia(b,a){if(G(b)){a=a||[];for(var c=0,d=b.length;c<d;c++)a[c]=b[c]}else if(H(b))for(c in a=a||{},b)if("$"!==c.charAt(0)||"$"!==c.charAt(1))a[c]=b[c];return a||b}function ka(b,a){if(b===a)return!0;if(null===b||null===a)return!1;if(b!==b&&a!==a)return!0;var c=typeof b,d;if(c==typeof a&&"object"==c)if(G(b)){if(!G(a))return!1;if((c=b.length)==a.length){for(d=0;d<c;d++)if(!ka(b[d],a[d]))return!1;return!0}}else{if(aa(b))return aa(a)?
ka(b.getTime(),a.getTime()):!1;if(Za(b))return Za(a)?b.toString()==a.toString():!1;if($a(b)||$a(a)||Wa(b)||Wa(a)||G(a)||aa(a)||Za(a))return!1;c=ga();for(d in b)if("$"!==d.charAt(0)&&!z(b[d])){if(!ka(b[d],a[d]))return!1;c[d]=!0}for(d in a)if(!(d in c||"$"===d.charAt(0)||a[d]===t||z(a[d])))return!1;return!0}return!1}function cb(b,a,c){return b.concat(za.call(a,c))}function vc(b,a){var c=2<arguments.length?za.call(arguments,2):[];return!z(a)||a instanceof RegExp?a:c.length?function(){return arguments.length?
a.apply(b,cb(c,arguments,0)):a.apply(b,c)}:function(){return arguments.length?a.apply(b,arguments):a.call(b)}}function Xd(b,a){var c=a;"string"===typeof b&&"$"===b.charAt(0)&&"$"===b.charAt(1)?c=t:Wa(a)?c="$WINDOW":a&&U===a?c="$DOCUMENT":$a(a)&&(c="$SCOPE");return c}function db(b,a){if("undefined"===typeof b)return t;V(a)||(a=a?2:null);return JSON.stringify(b,Xd,a)}function wc(b){return L(b)?JSON.parse(b):b}function xc(b,a){var c=Date.parse("Jan 01, 1970 00:00:00 "+b)/6E4;return isNaN(c)?a:c}function Pb(b,
a,c){c=c?-1:1;var d=xc(a,b.getTimezoneOffset());a=b;b=c*(d-b.getTimezoneOffset());a=new Date(a.getTime());a.setMinutes(a.getMinutes()+b);return a}function ua(b){b=y(b).clone();try{b.empty()}catch(a){}var c=y("<div>").append(b).html();try{return b[0].nodeType===Na?M(c):c.match(/^(<[^>]+>)/)[1].replace(/^<([\w\-]+)/,function(a,b){return"<"+M(b)})}catch(d){return M(c)}}function yc(b){try{return decodeURIComponent(b)}catch(a){}}function zc(b){var a={},c,d;m((b||"").split("&"),function(b){b&&(c=b.replace(/\+/g,
"%20").split("="),d=yc(c[0]),w(d)&&(b=w(c[1])?yc(c[1]):!0,Xa.call(a,d)?G(a[d])?a[d].push(b):a[d]=[a[d],b]:a[d]=b))});return a}function Qb(b){var a=[];m(b,function(b,d){G(b)?m(b,function(b){a.push(ma(d,!0)+(!0===b?"":"="+ma(b,!0)))}):a.push(ma(d,!0)+(!0===b?"":"="+ma(b,!0)))});return a.length?a.join("&"):""}function ob(b){return ma(b,!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+")}function ma(b,a){return encodeURIComponent(b).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,
"$").replace(/%2C/gi,",").replace(/%3B/gi,";").replace(/%20/g,a?"%20":"+")}function Yd(b,a){var c,d,e=Oa.length;for(d=0;d<e;++d)if(c=Oa[d]+a,L(c=b.getAttribute(c)))return c;return null}function Zd(b,a){var c,d,e={};m(Oa,function(a){a+="app";!c&&b.hasAttribute&&b.hasAttribute(a)&&(c=b,d=b.getAttribute(a))});m(Oa,function(a){a+="app";var e;!c&&(e=b.querySelector("["+a.replace(":","\\:")+"]"))&&(c=e,d=e.getAttribute(a))});c&&(e.strictDi=null!==Yd(c,"strict-di"),a(c,d?[d]:[],e))}function Ac(b,a,c){H(c)||
(c={});c=P({strictDi:!1},c);var d=function(){b=y(b);if(b.injector()){var d=b[0]===U?"document":ua(b);throw Fa("btstrpd",d.replace(/</,"<").replace(/>/,">"));}a=a||[];a.unshift(["$provide",function(a){a.value("$rootElement",b)}]);c.debugInfoEnabled&&a.push(["$compileProvider",function(a){a.debugInfoEnabled(!0)}]);a.unshift("ng");d=eb(a,c.strictDi);d.invoke(["$rootScope","$rootElement","$compile","$injector",function(a,b,c,d){a.$apply(function(){b.data("$injector",d);c(b)(a)})}]);return d},e=
/^NG_ENABLE_DEBUG_INFO!/,f=/^NG_DEFER_BOOTSTRAP!/;O&&e.test(O.name)&&(c.debugInfoEnabled=!0,O.name=O.name.replace(e,""));if(O&&!f.test(O.name))return d();O.name=O.name.replace(f,"");ca.resumeBootstrap=function(b){m(b,function(b){a.push(b)});return d()};z(ca.resumeDeferredBootstrap)&&ca.resumeDeferredBootstrap()}function $d(){O.name="NG_ENABLE_DEBUG_INFO!"+O.name;O.location.reload()}function ae(b){b=ca.element(b).injector();if(!b)throw Fa("test");return b.get("$$testability")}function Bc(b,a){a=a||
"_";return b.replace(be,function(b,d){return(d?a:"")+b.toLowerCase()})}function ce(){var b;if(!Cc){var a=pb();la=O.jQuery;w(a)&&(la=null===a?t:O[a]);la&&la.fn.on?(y=la,P(la.fn,{scope:Pa.scope,isolateScope:Pa.isolateScope,controller:Pa.controller,injector:Pa.injector,inheritedData:Pa.inheritedData}),b=la.cleanData,la.cleanData=function(a){var d;if(Rb)Rb=!1;else for(var e=0,f;null!=(f=a[e]);e++)(d=la._data(f,"events"))&&d.$destroy&&la(f).triggerHandler("$destroy");b(a)}):y=Q;ca.element=y;Cc=!0}}function Sb(b,
a,c){if(!b)throw Fa("areq",a||"?",c||"required");return b}function Qa(b,a,c){c&&G(b)&&(b=b[b.length-1]);Sb(z(b),a,"not a function, got "+(b&&"object"===typeof b?b.constructor.name||"Object":typeof b));return b}function Ra(b,a){if("hasOwnProperty"===b)throw Fa("badname",a);}function Dc(b,a,c){if(!a)return b;a=a.split(".");for(var d,e=b,f=a.length,g=0;g<f;g++)d=a[g],b&&(b=(e=b)[d]);return!c&&z(b)?vc(e,b):b}function qb(b){var a=b[0];b=b[b.length-1];var c=[a];do{a=a.nextSibling;if(!a)break;c.push(a)}while(a!==
b);return y(c)}function ga(){return Object.create(null)}function de(b){function a(a,b,c){return a[b]||(a[b]=c())}var c=J("$injector"),d=J("ng");b=a(b,"angular",Object);b.$$minErr=b.$$minErr||J;return a(b,"module",function(){var b={};return function(f,g,h){if("hasOwnProperty"===f)throw d("badname","module");g&&b.hasOwnProperty(f)&&(b[f]=null);return a(b,f,function(){function a(b,c,e,f){f||(f=d);return function(){f[e||"push"]([b,c,arguments]);return C}}function b(a,c){return function(b,e){e&&z(e)&&
(e.$$moduleName=f);d.push([a,c,arguments]);return C}}if(!g)throw c("nomod",f);var d=[],e=[],s=[],x=a("$injector","invoke","push",e),C={_invokeQueue:d,_configBlocks:e,_runBlocks:s,requires:g,name:f,provider:b("$provide","provider"),factory:b("$provide","factory"),service:b("$provide","service"),value:a("$provide","value"),constant:a("$provide","constant","unshift"),decorator:b("$provide","decorator"),animation:b("$animateProvider","register"),filter:b("$filterProvider","register"),controller:b("$controllerProvider",
"register"),directive:b("$compileProvider","directive"),config:x,run:function(a){s.push(a);return this}};h&&x(h);return C})}})}function ee(b){P(b,{bootstrap:Ac,copy:fa,extend:P,merge:Vd,equals:ka,element:y,forEach:m,injector:eb,noop:v,bind:vc,toJson:db,fromJson:wc,identity:Ya,isUndefined:A,isDefined:w,isString:L,isFunction:z,isObject:H,isNumber:V,isElement:tc,isArray:G,version:fe,isDate:aa,lowercase:M,uppercase:rb,callbacks:{counter:0},getTestability:ae,$$minErr:J,$$csp:fb,reloadWithDebugInfo:$d});
gb=de(O);try{gb("ngLocale")}catch(a){gb("ngLocale",[]).provider("$locale",ge)}gb("ng",["ngLocale"],["$provide",function(a){a.provider({$$sanitizeUri:he});a.provider("$compile",Ec).directive({a:ie,input:Fc,textarea:Fc,form:je,script:ke,select:le,style:me,option:ne,ngBind:oe,ngBindHtml:pe,ngBindTemplate:qe,ngClass:re,ngClassEven:se,ngClassOdd:te,ngCloak:ue,ngController:ve,ngForm:we,ngHide:xe,ngIf:ye,ngInclude:ze,ngInit:Ae,ngNonBindable:Be,ngPluralize:Ce,ngRepeat:De,ngShow:Ee,ngStyle:Fe,ngSwitch:Ge,
ngSwitchWhen:He,ngSwitchDefault:Ie,ngOptions:Je,ngTransclude:Ke,ngModel:Le,ngList:Me,ngChange:Ne,pattern:Gc,ngPattern:Gc,required:Hc,ngRequired:Hc,minlength:Ic,ngMinlength:Ic,maxlength:Jc,ngMaxlength:Jc,ngValue:Oe,ngModelOptions:Pe}).directive({ngInclude:Qe}).directive(sb).directive(Kc);a.provider({$anchorScroll:Re,$animate:Se,$$animateQueue:Te,$$AnimateRunner:Ue,$browser:Ve,$cacheFactory:We,$controller:Xe,$document:Ye,$exceptionHandler:Ze,$filter:Lc,$interpolate:$e,$interval:af,$http:bf,$httpParamSerializer:cf,
$httpParamSerializerJQLike:df,$httpBackend:ef,$location:ff,$log:gf,$parse:hf,$rootScope:jf,$q:kf,$$q:lf,$sce:mf,$sceDelegate:nf,$sniffer:of,$templateCache:pf,$templateRequest:qf,$$testability:rf,$timeout:sf,$window:tf,$$rAF:uf,$$jqLite:vf,$$HashMap:wf,$$cookieReader:xf})}])}function hb(b){return b.replace(yf,function(a,b,d,e){return e?d.toUpperCase():d}).replace(zf,"Moz$1")}function Mc(b){b=b.nodeType;return b===qa||!b||9===b}function Nc(b,a){var c,d,e=a.createDocumentFragment(),f=[];if(Tb.test(b)){c=
c||e.appendChild(a.createElement("div"));d=(Af.exec(b)||["",""])[1].toLowerCase();d=na[d]||na._default;c.innerHTML=d[1]+b.replace(Bf,"<$1></$2>")+d[2];for(d=d[0];d--;)c=c.lastChild;f=cb(f,c.childNodes);c=e.firstChild;c.textContent=""}else f.push(a.createTextNode(b));e.textContent="";e.innerHTML="";m(f,function(a){e.appendChild(a)});return e}function Q(b){if(b instanceof Q)return b;var a;L(b)&&(b=R(b),a=!0);if(!(this instanceof Q)){if(a&&"<"!=b.charAt(0))throw Ub("nosel");return new Q(b)}if(a){a=U;
var c;b=(c=Cf.exec(b))?[a.createElement(c[1])]:(c=Nc(b,a))?c.childNodes:[]}Oc(this,b)}function Vb(b){return b.cloneNode(!0)}function tb(b,a){a||ub(b);if(b.querySelectorAll)for(var c=b.querySelectorAll("*"),d=0,e=c.length;d<e;d++)ub(c[d])}function Pc(b,a,c,d){if(w(d))throw Ub("offargs");var e=(d=vb(b))&&d.events,f=d&&d.handle;if(f)if(a)m(a.split(" "),function(a){if(w(c)){var d=e[a];bb(d||[],c);if(d&&0<d.length)return}b.removeEventListener(a,f,!1);delete e[a]});else for(a in e)"$destroy"!==a&&b.removeEventListener(a,
f,!1),delete e[a]}function ub(b,a){var c=b.ng339,d=c&&ib[c];d&&(a?delete d.data[a]:(d.handle&&(d.events.$destroy&&d.handle({},"$destroy"),Pc(b)),delete ib[c],b.ng339=t))}function vb(b,a){var c=b.ng339,c=c&&ib[c];a&&!c&&(b.ng339=c=++Df,c=ib[c]={events:{},data:{},handle:t});return c}function Wb(b,a,c){if(Mc(b)){var d=w(c),e=!d&&a&&!H(a),f=!a;b=(b=vb(b,!e))&&b.data;if(d)b[a]=c;else{if(f)return b;if(e)return b&&b[a];P(b,a)}}}function wb(b,a){return b.getAttribute?-1<(" "+(b.getAttribute("class")||"")+
" ").replace(/[\n\t]/g," ").indexOf(" "+a+" "):!1}function xb(b,a){a&&b.setAttribute&&m(a.split(" "),function(a){b.setAttribute("class",R((" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").replace(" "+R(a)+" "," ")))})}function yb(b,a){if(a&&b.setAttribute){var c=(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ");m(a.split(" "),function(a){a=R(a);-1===c.indexOf(" "+a+" ")&&(c+=a+" ")});b.setAttribute("class",R(c))}}function Oc(b,a){if(a)if(a.nodeType)b[b.length++]=a;else{var c=
a.length;if("number"===typeof c&&a.window!==a){if(c)for(var d=0;d<c;d++)b[b.length++]=a[d]}else b[b.length++]=a}}function Qc(b,a){return zb(b,"$"+(a||"ngController")+"Controller")}function zb(b,a,c){9==b.nodeType&&(b=b.documentElement);for(a=G(a)?a:[a];b;){for(var d=0,e=a.length;d<e;d++)if((c=y.data(b,a[d]))!==t)return c;b=b.parentNode||11===b.nodeType&&b.host}}function Rc(b){for(tb(b,!0);b.firstChild;)b.removeChild(b.firstChild)}function Xb(b,a){a||tb(b);var c=b.parentNode;c&&c.removeChild(b)}function Ef(b,
a){a=a||O;if("complete"===a.document.readyState)a.setTimeout(b);else y(a).on("load",b)}function Sc(b,a){var c=Ab[a.toLowerCase()];return c&&Tc[ta(b)]&&c}function Ff(b,a){var c=b.nodeName;return("INPUT"===c||"TEXTAREA"===c)&&Uc[a]}function Gf(b,a){var c=function(c,e){c.isDefaultPrevented=function(){return c.defaultPrevented};var f=a[e||c.type],g=f?f.length:0;if(g){if(A(c.immediatePropagationStopped)){var h=c.stopImmediatePropagation;c.stopImmediatePropagation=function(){c.immediatePropagationStopped=
!0;c.stopPropagation&&c.stopPropagation();h&&h.call(c)}}c.isImmediatePropagationStopped=function(){return!0===c.immediatePropagationStopped};1<g&&(f=ia(f));for(var l=0;l<g;l++)c.isImmediatePropagationStopped()||f[l].call(b,c)}};c.elem=b;return c}function vf(){this.$get=function(){return P(Q,{hasClass:function(b,a){b.attr&&(b=b[0]);return wb(b,a)},addClass:function(b,a){b.attr&&(b=b[0]);return yb(b,a)},removeClass:function(b,a){b.attr&&(b=b[0]);return xb(b,a)}})}}function Ga(b,a){var c=b&&b.$$hashKey;
if(c)return"function"===typeof c&&(c=b.$$hashKey()),c;c=typeof b;return c="function"==c||"object"==c&&null!==b?b.$$hashKey=c+":"+(a||Ud)():c+":"+b}function Sa(b,a){if(a){var c=0;this.nextUid=function(){return++c}}m(b,this.put,this)}function Hf(b){return(b=b.toString().replace(Vc,"").match(Wc))?"function("+(b[1]||"").replace(/[\s\r\n]+/," ")+")":"fn"}function eb(b,a){function c(a){return function(b,c){if(H(b))m(b,pc(a));else return a(b,c)}}function d(a,b){Ra(a,"service");if(z(b)||G(b))b=s.instantiate(b);
if(!b.$get)throw Ha("pget",a);return r[a+"Provider"]=b}function e(a,b){return function(){var c=C.invoke(b,this);if(A(c))throw Ha("undef",a);return c}}function f(a,b,c){return d(a,{$get:!1!==c?e(a,b):b})}function g(a){var b=[],c;m(a,function(a){function d(a){var b,c;b=0;for(c=a.length;b<c;b++){var e=a[b],f=s.get(e[0]);f[e[1]].apply(f,e[2])}}if(!n.get(a)){n.put(a,!0);try{L(a)?(c=gb(a),b=b.concat(g(c.requires)).concat(c._runBlocks),d(c._invokeQueue),d(c._configBlocks)):z(a)?b.push(s.invoke(a)):G(a)?
b.push(s.invoke(a)):Qa(a,"module")}catch(e){throw G(a)&&(a=a[a.length-1]),e.message&&e.stack&&-1==e.stack.indexOf(e.message)&&(e=e.message+"\n"+e.stack),Ha("modulerr",a,e.stack||e.message||e);}}});return b}function h(b,c){function d(a,e){if(b.hasOwnProperty(a)){if(b[a]===l)throw Ha("cdep",a+" <- "+k.join(" <- "));return b[a]}try{return k.unshift(a),b[a]=l,b[a]=c(a,e)}catch(f){throw b[a]===l&&delete b[a],f;}finally{k.shift()}}function e(b,c,f,g){"string"===typeof f&&(g=f,f=null);var h=[],k=eb.$$annotate(b,
a,g),l,s,n;s=0;for(l=k.length;s<l;s++){n=k[s];if("string"!==typeof n)throw Ha("itkn",n);h.push(f&&f.hasOwnProperty(n)?f[n]:d(n,g))}G(b)&&(b=b[l]);return b.apply(c,h)}return{invoke:e,instantiate:function(a,b,c){var d=Object.create((G(a)?a[a.length-1]:a).prototype||null);a=e(a,d,b,c);return H(a)||z(a)?a:d},get:d,annotate:eb.$$annotate,has:function(a){return r.hasOwnProperty(a+"Provider")||b.hasOwnProperty(a)}}}a=!0===a;var l={},k=[],n=new Sa([],!0),r={$provide:{provider:c(d),factory:c(f),service:c(function(a,
b){return f(a,["$injector",function(a){return a.instantiate(b)}])}),value:c(function(a,b){return f(a,ra(b),!1)}),constant:c(function(a,b){Ra(a,"constant");r[a]=b;x[a]=b}),decorator:function(a,b){var c=s.get(a+"Provider"),d=c.$get;c.$get=function(){var a=C.invoke(d,c);return C.invoke(b,null,{$delegate:a})}}}},s=r.$injector=h(r,function(a,b){ca.isString(b)&&k.push(b);throw Ha("unpr",k.join(" <- "));}),x={},C=x.$injector=h(x,function(a,b){var c=s.get(a+"Provider",b);return C.invoke(c.$get,c,t,a)});m(g(b),
function(a){a&&C.invoke(a)});return C}function Re(){var b=!0;this.disableAutoScrolling=function(){b=!1};this.$get=["$window","$location","$rootScope",function(a,c,d){function e(a){var b=null;Array.prototype.some.call(a,function(a){if("a"===ta(a))return b=a,!0});return b}function f(b){if(b){b.scrollIntoView();var c;c=g.yOffset;z(c)?c=c():tc(c)?(c=c[0],c="fixed"!==a.getComputedStyle(c).position?0:c.getBoundingClientRect().bottom):V(c)||(c=0);c&&(b=b.getBoundingClientRect().top,a.scrollBy(0,b-c))}else a.scrollTo(0,
0)}function g(a){a=L(a)?a:c.hash();var b;a?(b=h.getElementById(a))?f(b):(b=e(h.getElementsByName(a)))?f(b):"top"===a&&f(null):f(null)}var h=a.document;b&&d.$watch(function(){return c.hash()},function(a,b){a===b&&""===a||Ef(function(){d.$evalAsync(g)})});return g}]}function jb(b,a){if(!b&&!a)return"";if(!b)return a;if(!a)return b;G(b)&&(b=b.join(" "));G(a)&&(a=a.join(" "));return b+" "+a}function If(b){L(b)&&(b=b.split(" "));var a=ga();m(b,function(b){b.length&&(a[b]=!0)});return a}function Ia(b){return H(b)?
b:{}}function Jf(b,a,c,d){function e(a){try{a.apply(null,za.call(arguments,1))}finally{if(C--,0===C)for(;F.length;)try{F.pop()()}catch(b){c.error(b)}}}function f(){g();h()}function g(){a:{try{u=n.state;break a}catch(a){}u=void 0}u=A(u)?null:u;ka(u,D)&&(u=D);D=u}function h(){if(K!==l.url()||p!==u)K=l.url(),p=u,m(B,function(a){a(l.url(),u)})}var l=this,k=b.location,n=b.history,r=b.setTimeout,s=b.clearTimeout,x={};l.isMock=!1;var C=0,F=[];l.$$completeOutstandingRequest=e;l.$$incOutstandingRequestCount=
function(){C++};l.notifyWhenNoOutstandingRequests=function(a){0===C?a():F.push(a)};var u,p,K=k.href,q=a.find("base"),I=null;g();p=u;l.url=function(a,c,e){A(e)&&(e=null);k!==b.location&&(k=b.location);n!==b.history&&(n=b.history);if(a){var f=p===e;if(K===a&&(!d.history||f))return l;var h=K&&Ja(K)===Ja(a);K=a;p=e;if(!d.history||h&&f){if(!h||I)I=a;c?k.replace(a):h?(c=k,e=a.indexOf("#"),a=-1===e?"":a.substr(e),c.hash=a):k.href=a}else n[c?"replaceState":"pushState"](e,"",a),g(),p=u;return l}return I||
k.href.replace(/%27/g,"'")};l.state=function(){return u};var B=[],N=!1,D=null;l.onUrlChange=function(a){if(!N){if(d.history)y(b).on("popstate",f);y(b).on("hashchange",f);N=!0}B.push(a);return a};l.$$applicationDestroyed=function(){y(b).off("hashchange popstate",f)};l.$$checkUrlChange=h;l.baseHref=function(){var a=q.attr("href");return a?a.replace(/^(https?\:)?\/\/[^\/]*/,""):""};l.defer=function(a,b){var c;C++;c=r(function(){delete x[c];e(a)},b||0);x[c]=!0;return c};l.defer.cancel=function(a){return x[a]?
(delete x[a],s(a),e(v),!0):!1}}function Ve(){this.$get=["$window","$log","$sniffer","$document",function(b,a,c,d){return new Jf(b,d,a,c)}]}function We(){this.$get=function(){function b(b,d){function e(a){a!=r&&(s?s==a&&(s=a.n):s=a,f(a.n,a.p),f(a,r),r=a,r.n=null)}function f(a,b){a!=b&&(a&&(a.p=b),b&&(b.n=a))}if(b in a)throw J("$cacheFactory")("iid",b);var g=0,h=P({},d,{id:b}),l={},k=d&&d.capacity||Number.MAX_VALUE,n={},r=null,s=null;return a[b]={put:function(a,b){if(!A(b)){if(k<Number.MAX_VALUE){var c=
n[a]||(n[a]={key:a});e(c)}a in l||g++;l[a]=b;g>k&&this.remove(s.key);return b}},get:function(a){if(k<Number.MAX_VALUE){var b=n[a];if(!b)return;e(b)}return l[a]},remove:function(a){if(k<Number.MAX_VALUE){var b=n[a];if(!b)return;b==r&&(r=b.p);b==s&&(s=b.n);f(b.n,b.p);delete n[a]}delete l[a];g--},removeAll:function(){l={};g=0;n={};r=s=null},destroy:function(){n=h=l=null;delete a[b]},info:function(){return P({},h,{size:g})}}}var a={};b.info=function(){var b={};m(a,function(a,e){b[e]=a.info()});return b};
b.get=function(b){return a[b]};return b}}function pf(){this.$get=["$cacheFactory",function(b){return b("templates")}]}function Ec(b,a){function c(a,b,c){var d=/^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/,e={};m(a,function(a,f){var g=a.match(d);if(!g)throw ea("iscp",b,f,a,c?"controller bindings definition":"isolate scope definition");e[f]={mode:g[1][0],collection:"*"===g[2],optional:"?"===g[3],attrName:g[4]||f}});return e}function d(a){var b=a.charAt(0);if(!b||b!==M(b))throw ea("baddir",a);if(a!==a.trim())throw ea("baddir",
a);}var e={},f=/^\s*directive\:\s*([\w\-]+)\s+(.*)$/,g=/(([\w\-]+)(?:\:([^;]+))?;?)/,h=Wd("ngSrc,ngSrcset,src,srcset"),l=/^(?:(\^\^?)?(\?)?(\^\^?)?)?/,k=/^(on[a-z]+|formaction)$/;this.directive=function s(a,f){Ra(a,"directive");L(a)?(d(a),Sb(f,"directiveFactory"),e.hasOwnProperty(a)||(e[a]=[],b.factory(a+"Directive",["$injector","$exceptionHandler",function(b,d){var f=[];m(e[a],function(e,g){try{var h=b.invoke(e);z(h)?h={compile:ra(h)}:!h.compile&&h.link&&(h.compile=ra(h.link));h.priority=h.priority||
0;h.index=g;h.name=h.name||a;h.require=h.require||h.controller&&h.name;h.restrict=h.restrict||"EA";var k=h,l=h,s=h.name,n={isolateScope:null,bindToController:null};H(l.scope)&&(!0===l.bindToController?(n.bindToController=c(l.scope,s,!0),n.isolateScope={}):n.isolateScope=c(l.scope,s,!1));H(l.bindToController)&&(n.bindToController=c(l.bindToController,s,!0));if(H(n.bindToController)){var C=l.controller,$=l.controllerAs;if(!C)throw ea("noctrl",s);var ha;a:if($&&L($))ha=$;else{if(L(C)){var m=Xc.exec(C);
if(m){ha=m[3];break a}}ha=void 0}if(!ha)throw ea("noident",s);}var q=k.$$bindings=n;H(q.isolateScope)&&(h.$$isolateBindings=q.isolateScope);h.$$moduleName=e.$$moduleName;f.push(h)}catch(t){d(t)}});return f}])),e[a].push(f)):m(a,pc(s));return this};this.aHrefSanitizationWhitelist=function(b){return w(b)?(a.aHrefSanitizationWhitelist(b),this):a.aHrefSanitizationWhitelist()};this.imgSrcSanitizationWhitelist=function(b){return w(b)?(a.imgSrcSanitizationWhitelist(b),this):a.imgSrcSanitizationWhitelist()};
var n=!0;this.debugInfoEnabled=function(a){return w(a)?(n=a,this):n};this.$get=["$injector","$interpolate","$exceptionHandler","$templateRequest","$parse","$controller","$rootScope","$document","$sce","$animate","$$sanitizeUri",function(a,b,c,d,u,p,K,q,I,B,N){function D(a,b){try{a.addClass(b)}catch(c){}}function Z(a,b,c,d,e){a instanceof y||(a=y(a));m(a,function(b,c){b.nodeType==Na&&b.nodeValue.match(/\S+/)&&(a[c]=y(b).wrap("<span></span>").parent()[0])});var f=S(a,b,a,c,d,e);Z.$$addScopeClass(a);
var g=null;return function(b,c,d){Sb(b,"scope");d=d||{};var e=d.parentBoundTranscludeFn,h=d.transcludeControllers;d=d.futureParentElement;e&&e.$$boundTransclude&&(e=e.$$boundTransclude);g||(g=(d=d&&d[0])?"foreignobject"!==ta(d)&&d.toString().match(/SVG/)?"svg":"html":"html");d="html"!==g?y(Yb(g,y("<div>").append(a).html())):c?Pa.clone.call(a):a;if(h)for(var k in h)d.data("$"+k+"Controller",h[k].instance);Z.$$addScopeInfo(d,b);c&&c(d,b);f&&f(b,d,d,e);return d}}function S(a,b,c,d,e,f){function g(a,
c,d,e){var f,k,l,s,n,B,C;if(p)for(C=Array(c.length),s=0;s<h.length;s+=3)f=h[s],C[f]=c[f];else C=c;s=0;for(n=h.length;s<n;)if(k=C[h[s++]],c=h[s++],f=h[s++],c){if(c.scope){if(l=a.$new(),Z.$$addScopeInfo(y(k),l),B=c.$$destroyBindings)c.$$destroyBindings=null,l.$on("$destroyed",B)}else l=a;B=c.transcludeOnThisElement?$(a,c.transclude,e):!c.templateOnThisElement&&e?e:!e&&b?$(a,b):null;c(f,l,k,d,B,c)}else f&&f(a,k.childNodes,t,e)}for(var h=[],k,l,s,n,p,B=0;B<a.length;B++){k=new aa;l=ha(a[B],[],k,0===B?
d:t,e);(f=l.length?E(l,a[B],k,b,c,null,[],[],f):null)&&f.scope&&Z.$$addScopeClass(k.$$element);k=f&&f.terminal||!(s=a[B].childNodes)||!s.length?null:S(s,f?(f.transcludeOnThisElement||!f.templateOnThisElement)&&f.transclude:b);if(f||k)h.push(B,f,k),n=!0,p=p||f;f=null}return n?g:null}function $(a,b,c){return function(d,e,f,g,h){d||(d=a.$new(!1,h),d.$$transcluded=!0);return b(d,e,{parentBoundTranscludeFn:c,transcludeControllers:f,futureParentElement:g})}}function ha(a,b,c,d,e){var h=c.$attr,k;switch(a.nodeType){case qa:w(b,
wa(ta(a)),"E",d,e);for(var l,s,n,p=a.attributes,B=0,C=p&&p.length;B<C;B++){var x=!1,S=!1;l=p[B];k=l.name;s=R(l.value);l=wa(k);if(n=ia.test(l))k=k.replace(Zc,"").substr(8).replace(/_(.)/g,function(a,b){return b.toUpperCase()});var F=l.replace(/(Start|End)$/,"");A(F)&&l===F+"Start"&&(x=k,S=k.substr(0,k.length-5)+"end",k=k.substr(0,k.length-6));l=wa(k.toLowerCase());h[l]=k;if(n||!c.hasOwnProperty(l))c[l]=s,Sc(a,l)&&(c[l]=!0);V(a,b,s,l,n);w(b,l,"A",d,e,x,S)}a=a.className;H(a)&&(a=a.animVal);if(L(a)&&
""!==a)for(;k=g.exec(a);)l=wa(k[2]),w(b,l,"C",d,e)&&(c[l]=R(k[3])),a=a.substr(k.index+k[0].length);break;case Na:if(11===Ua)for(;a.parentNode&&a.nextSibling&&a.nextSibling.nodeType===Na;)a.nodeValue+=a.nextSibling.nodeValue,a.parentNode.removeChild(a.nextSibling);xa(b,a.nodeValue);break;case 8:try{if(k=f.exec(a.nodeValue))l=wa(k[1]),w(b,l,"M",d,e)&&(c[l]=R(k[2]))}catch($){}}b.sort(Aa);return b}function va(a,b,c){var d=[],e=0;if(b&&a.hasAttribute&&a.hasAttribute(b)){do{if(!a)throw ea("uterdir",b,c);
a.nodeType==qa&&(a.hasAttribute(b)&&e++,a.hasAttribute(c)&&e--);d.push(a);a=a.nextSibling}while(0<e)}else d.push(a);return y(d)}function Yc(a,b,c){return function(d,e,f,g,h){e=va(e[0],b,c);return a(d,e,f,g,h)}}function E(a,b,d,e,f,g,h,k,s){function n(a,b,c,d){if(a){c&&(a=Yc(a,c,d));a.require=E.require;a.directiveName=w;if(u===E||E.$$isolateScope)a=X(a,{isolateScope:!0});h.push(a)}if(b){c&&(b=Yc(b,c,d));b.require=E.require;b.directiveName=w;if(u===E||E.$$isolateScope)b=X(b,{isolateScope:!0});k.push(b)}}
function B(a,b,c,d){var e;if(L(b)){var f=b.match(l);b=b.substring(f[0].length);var g=f[1]||f[3],f="?"===f[2];"^^"===g?c=c.parent():e=(e=d&&d[b])&&e.instance;e||(d="$"+b+"Controller",e=g?c.inheritedData(d):c.data(d));if(!e&&!f)throw ea("ctreq",b,a);}else if(G(b))for(e=[],g=0,f=b.length;g<f;g++)e[g]=B(a,b[g],c,d);return e||null}function x(a,b,c,d,e,f){var g=ga(),h;for(h in d){var k=d[h],l={$scope:k===u||k.$$isolateScope?e:f,$element:a,$attrs:b,$transclude:c},s=k.controller;"@"==s&&(s=b[k.name]);l=p(s,
l,!0,k.controllerAs);g[k.name]=l;q||a.data("$"+k.name+"Controller",l.instance)}return g}function S(a,c,e,f,g,l){function s(a,b,c){var d;$a(a)||(c=b,b=a,a=t);q&&(d=m);c||(c=q?ja.parent():ja);return g(a,b,d,c,va)}var n,p,C,F,m,ha,ja;b===e?(f=d,ja=d.$$element):(ja=y(e),f=new aa(ja,d));u&&(F=c.$new(!0));g&&(ha=s,ha.$$boundTransclude=g);N&&(m=x(ja,f,ha,N,F,c));u&&(Z.$$addScopeInfo(ja,F,!0,!(D&&(D===u||D===u.$$originalDirective))),Z.$$addScopeClass(ja,!0),F.$$isolateBindings=u.$$isolateBindings,W(c,f,F,
F.$$isolateBindings,u,F));if(m){var K=u||$,I;K&&m[K.name]&&(p=K.$$bindings.bindToController,(C=m[K.name])&&C.identifier&&p&&(I=C,l.$$destroyBindings=W(c,f,C.instance,p,K)));for(n in m){C=m[n];var E=C();E!==C.instance&&(C.instance=E,ja.data("$"+n+"Controller",E),C===I&&(l.$$destroyBindings(),l.$$destroyBindings=W(c,f,E,p,K)))}}n=0;for(l=h.length;n<l;n++)p=h[n],Y(p,p.isolateScope?F:c,ja,f,p.require&&B(p.directiveName,p.require,ja,m),ha);var va=c;u&&(u.template||null===u.templateUrl)&&(va=F);a&&a(va,
e.childNodes,t,g);for(n=k.length-1;0<=n;n--)p=k[n],Y(p,p.isolateScope?F:c,ja,f,p.require&&B(p.directiveName,p.require,ja,m),ha)}s=s||{};for(var F=-Number.MAX_VALUE,$=s.newScopeDirective,N=s.controllerDirectives,u=s.newIsolateScopeDirective,D=s.templateDirective,m=s.nonTlbTranscludeDirective,K=!1,I=!1,q=s.hasElementTranscludeDirective,ba=d.$$element=y(b),E,w,v,A=e,Aa,xa=0,Ta=a.length;xa<Ta;xa++){E=a[xa];var M=E.$$start,P=E.$$end;M&&(ba=va(b,M,P));v=t;if(F>E.priority)break;if(v=E.scope)E.templateUrl||
(H(v)?(O("new/isolated scope",u||$,E,ba),u=E):O("new/isolated scope",u,E,ba)),$=$||E;w=E.name;!E.templateUrl&&E.controller&&(v=E.controller,N=N||ga(),O("'"+w+"' controller",N[w],E,ba),N[w]=E);if(v=E.transclude)K=!0,E.$$tlb||(O("transclusion",m,E,ba),m=E),"element"==v?(q=!0,F=E.priority,v=ba,ba=d.$$element=y(U.createComment(" "+w+": "+d[w]+" ")),b=ba[0],T(f,za.call(v,0),b),A=Z(v,e,F,g&&g.name,{nonTlbTranscludeDirective:m})):(v=y(Vb(b)).contents(),ba.empty(),A=Z(v,e));if(E.template)if(I=!0,O("template",
D,E,ba),D=E,v=z(E.template)?E.template(ba,d):E.template,v=fa(v),E.replace){g=E;v=Tb.test(v)?$c(Yb(E.templateNamespace,R(v))):[];b=v[0];if(1!=v.length||b.nodeType!==qa)throw ea("tplrt",w,"");T(f,ba,b);Ta={$attr:{}};v=ha(b,[],Ta);var Q=a.splice(xa+1,a.length-(xa+1));u&&ad(v);a=a.concat(v).concat(Q);J(d,Ta);Ta=a.length}else ba.html(v);if(E.templateUrl)I=!0,O("template",D,E,ba),D=E,E.replace&&(g=E),S=Lf(a.splice(xa,a.length-xa),ba,d,f,K&&A,h,k,{controllerDirectives:N,newScopeDirective:$!==E&&$,newIsolateScopeDirective:u,
templateDirective:D,nonTlbTranscludeDirective:m}),Ta=a.length;else if(E.compile)try{Aa=E.compile(ba,d,A),z(Aa)?n(null,Aa,M,P):Aa&&n(Aa.pre,Aa.post,M,P)}catch(Kf){c(Kf,ua(ba))}E.terminal&&(S.terminal=!0,F=Math.max(F,E.priority))}S.scope=$&&!0===$.scope;S.transcludeOnThisElement=K;S.templateOnThisElement=I;S.transclude=A;s.hasElementTranscludeDirective=q;return S}function ad(a){for(var b=0,c=a.length;b<c;b++)a[b]=Ob(a[b],{$$isolateScope:!0})}function w(b,d,f,g,h,k,l){if(d===h)return null;h=null;if(e.hasOwnProperty(d)){var n;
d=a.get(d+"Directive");for(var p=0,B=d.length;p<B;p++)try{n=d[p],(g===t||g>n.priority)&&-1!=n.restrict.indexOf(f)&&(k&&(n=Ob(n,{$$start:k,$$end:l})),b.push(n),h=n)}catch(x){c(x)}}return h}function A(b){if(e.hasOwnProperty(b))for(var c=a.get(b+"Directive"),d=0,f=c.length;d<f;d++)if(b=c[d],b.multiElement)return!0;return!1}function J(a,b){var c=b.$attr,d=a.$attr,e=a.$$element;m(a,function(d,e){"$"!=e.charAt(0)&&(b[e]&&b[e]!==d&&(d+=("style"===e?";":" ")+b[e]),a.$set(e,d,!0,c[e]))});m(b,function(b,f){"class"==
f?(D(e,b),a["class"]=(a["class"]?a["class"]+" ":"")+b):"style"==f?(e.attr("style",e.attr("style")+";"+b),a.style=(a.style?a.style+";":"")+b):"$"==f.charAt(0)||a.hasOwnProperty(f)||(a[f]=b,d[f]=c[f])})}function Lf(a,b,c,e,f,g,h,k){var l=[],s,n,p=b[0],B=a.shift(),C=Ob(B,{templateUrl:null,transclude:null,replace:null,$$originalDirective:B}),x=z(B.templateUrl)?B.templateUrl(b,c):B.templateUrl,N=B.templateNamespace;b.empty();d(x).then(function(d){var F,u;d=fa(d);if(B.replace){d=Tb.test(d)?$c(Yb(N,R(d))):
[];F=d[0];if(1!=d.length||F.nodeType!==qa)throw ea("tplrt",B.name,x);d={$attr:{}};T(e,b,F);var K=ha(F,[],d);H(B.scope)&&ad(K);a=K.concat(a);J(c,d)}else F=p,b.html(d);a.unshift(C);s=E(a,F,c,f,b,B,g,h,k);m(e,function(a,c){a==F&&(e[c]=b[0])});for(n=S(b[0].childNodes,f);l.length;){d=l.shift();u=l.shift();var I=l.shift(),va=l.shift(),K=b[0];if(!d.$$destroyed){if(u!==p){var Z=u.className;k.hasElementTranscludeDirective&&B.replace||(K=Vb(F));T(I,y(u),K);D(y(K),Z)}u=s.transcludeOnThisElement?$(d,s.transclude,
va):va;s(n,d,K,e,u,s)}}l=null});return function(a,b,c,d,e){a=e;b.$$destroyed||(l?l.push(b,c,d,a):(s.transcludeOnThisElement&&(a=$(b,s.transclude,e)),s(n,b,c,d,a,s)))}}function Aa(a,b){var c=b.priority-a.priority;return 0!==c?c:a.name!==b.name?a.name<b.name?-1:1:a.index-b.index}function O(a,b,c,d){function e(a){return a?" (module: "+a+")":""}if(b)throw ea("multidir",b.name,e(b.$$moduleName),c.name,e(c.$$moduleName),a,ua(d));}function xa(a,c){var d=b(c,!0);d&&a.push({priority:0,compile:function(a){a=
a.parent();var b=!!a.length;b&&Z.$$addBindingClass(a);return function(a,c){var e=c.parent();b||Z.$$addBindingClass(e);Z.$$addBindingInfo(e,d.expressions);a.$watch(d,function(a){c[0].nodeValue=a})}}})}function Yb(a,b){a=M(a||"html");switch(a){case "svg":case "math":var c=U.createElement("div");c.innerHTML="<"+a+">"+b+"</"+a+">";return c.childNodes[0].childNodes;default:return b}}function Q(a,b){if("srcdoc"==b)return I.HTML;var c=ta(a);if("xlinkHref"==b||"form"==c&&"action"==b||"img"!=c&&("src"==b||
"ngSrc"==b))return I.RESOURCE_URL}function V(a,c,d,e,f){var g=Q(a,e);f=h[e]||f;var l=b(d,!0,g,f);if(l){if("multiple"===e&&"select"===ta(a))throw ea("selmulti",ua(a));c.push({priority:100,compile:function(){return{pre:function(a,c,h){c=h.$$observers||(h.$$observers={});if(k.test(e))throw ea("nodomevents");var s=h[e];s!==d&&(l=s&&b(s,!0,g,f),d=s);l&&(h[e]=l(a),(c[e]||(c[e]=[])).$$inter=!0,(h.$$observers&&h.$$observers[e].$$scope||a).$watch(l,function(a,b){"class"===e&&a!=b?h.$updateClass(a,b):h.$set(e,
a)}))}}}})}}function T(a,b,c){var d=b[0],e=b.length,f=d.parentNode,g,h;if(a)for(g=0,h=a.length;g<h;g++)if(a[g]==d){a[g++]=c;h=g+e-1;for(var k=a.length;g<k;g++,h++)h<k?a[g]=a[h]:delete a[g];a.length-=e-1;a.context===d&&(a.context=c);break}f&&f.replaceChild(c,d);a=U.createDocumentFragment();a.appendChild(d);y.hasData(d)&&(y(c).data(y(d).data()),la?(Rb=!0,la.cleanData([d])):delete y.cache[d[y.expando]]);d=1;for(e=b.length;d<e;d++)f=b[d],y(f).remove(),a.appendChild(f),delete b[d];b[0]=c;b.length=1}function X(a,
b){return P(function(){return a.apply(null,arguments)},a,b)}function Y(a,b,d,e,f,g){try{a(b,d,e,f,g)}catch(h){c(h,ua(d))}}function W(a,c,d,e,f,g){var h;m(e,function(e,g){var k=e.attrName,l=e.optional,s=e.mode,n,p,B,C;Xa.call(c,k)||(c[k]=t);switch(s){case "@":c[k]||l||(d[g]=t);c.$observe(k,function(a){d[g]=a});c.$$observers[k].$$scope=a;c[k]&&(d[g]=b(c[k])(a));break;case "=":if(l&&!c[k])break;p=u(c[k]);C=p.literal?ka:function(a,b){return a===b||a!==a&&b!==b};B=p.assign||function(){n=d[g]=p(a);throw ea("nonassign",
c[k],f.name);};n=d[g]=p(a);l=function(b){C(b,d[g])||(C(b,n)?B(a,b=d[g]):d[g]=b);return n=b};l.$stateful=!0;l=e.collection?a.$watchCollection(c[k],l):a.$watch(u(c[k],l),null,p.literal);h=h||[];h.push(l);break;case "&":p=u(c[k]);if(p===v&&l)break;d[g]=function(b){return p(a,b)}}});e=h?function(){for(var a=0,b=h.length;a<b;++a)h[a]()}:v;return g&&e!==v?(g.$on("$destroy",e),v):e}var aa=function(a,b){if(b){var c=Object.keys(b),d,e,f;d=0;for(e=c.length;d<e;d++)f=c[d],this[f]=b[f]}else this.$attr={};this.$$element=
a};aa.prototype={$normalize:wa,$addClass:function(a){a&&0<a.length&&B.addClass(this.$$element,a)},$removeClass:function(a){a&&0<a.length&&B.removeClass(this.$$element,a)},$updateClass:function(a,b){var c=bd(a,b);c&&c.length&&B.addClass(this.$$element,c);(c=bd(b,a))&&c.length&&B.removeClass(this.$$element,c)},$set:function(a,b,d,e){var f=this.$$element[0],g=Sc(f,a),h=Ff(f,a),f=a;g?(this.$$element.prop(a,b),e=g):h&&(this[h]=b,f=h);this[a]=b;e?this.$attr[a]=e:(e=this.$attr[a])||(this.$attr[a]=e=Bc(a,
"-"));g=ta(this.$$element);if("a"===g&&"href"===a||"img"===g&&"src"===a)this[a]=b=N(b,"src"===a);else if("img"===g&&"srcset"===a){for(var g="",h=R(b),k=/(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/,k=/\s/.test(h)?k:/(,)/,h=h.split(k),k=Math.floor(h.length/2),l=0;l<k;l++)var s=2*l,g=g+N(R(h[s]),!0),g=g+(" "+R(h[s+1]));h=R(h[2*l]).split(/\s/);g+=N(R(h[0]),!0);2===h.length&&(g+=" "+R(h[1]));this[a]=b=g}!1!==d&&(null===b||b===t?this.$$element.removeAttr(e):this.$$element.attr(e,b));(a=this.$$observers)&&m(a[f],
function(a){try{a(b)}catch(d){c(d)}})},$observe:function(a,b){var c=this,d=c.$$observers||(c.$$observers=ga()),e=d[a]||(d[a]=[]);e.push(b);K.$evalAsync(function(){!e.$$inter&&c.hasOwnProperty(a)&&b(c[a])});return function(){bb(e,b)}}};var ca=b.startSymbol(),da=b.endSymbol(),fa="{{"==ca||"}}"==da?Ya:function(a){return a.replace(/\{\{/g,ca).replace(/}}/g,da)},ia=/^ngAttr[A-Z]/;Z.$$addBindingInfo=n?function(a,b){var c=a.data("$binding")||[];G(b)?c=c.concat(b):c.push(b);a.data("$binding",c)}:v;Z.$$addBindingClass=
n?function(a){D(a,"ng-binding")}:v;Z.$$addScopeInfo=n?function(a,b,c,d){a.data(c?d?"$isolateScopeNoTemplate":"$isolateScope":"$scope",b)}:v;Z.$$addScopeClass=n?function(a,b){D(a,b?"ng-isolate-scope":"ng-scope")}:v;return Z}]}function wa(b){return hb(b.replace(Zc,""))}function bd(b,a){var c="",d=b.split(/\s+/),e=a.split(/\s+/),f=0;a:for(;f<d.length;f++){for(var g=d[f],h=0;h<e.length;h++)if(g==e[h])continue a;c+=(0<c.length?" ":"")+g}return c}function $c(b){b=y(b);var a=b.length;if(1>=a)return b;for(;a--;)8===
b[a].nodeType&&Mf.call(b,a,1);return b}function Xe(){var b={},a=!1;this.register=function(a,d){Ra(a,"controller");H(a)?P(b,a):b[a]=d};this.allowGlobals=function(){a=!0};this.$get=["$injector","$window",function(c,d){function e(a,b,c,d){if(!a||!H(a.$scope))throw J("$controller")("noscp",d,b);a.$scope[b]=c}return function(f,g,h,l){var k,n,r;h=!0===h;l&&L(l)&&(r=l);if(L(f)){l=f.match(Xc);if(!l)throw Nf("ctrlfmt",f);n=l[1];r=r||l[3];f=b.hasOwnProperty(n)?b[n]:Dc(g.$scope,n,!0)||(a?Dc(d,n,!0):t);Qa(f,
n,!0)}if(h)return h=(G(f)?f[f.length-1]:f).prototype,k=Object.create(h||null),r&&e(g,r,k,n||f.name),P(function(){var a=c.invoke(f,k,g,n);a!==k&&(H(a)||z(a))&&(k=a,r&&e(g,r,k,n||f.name));return k},{instance:k,identifier:r});k=c.instantiate(f,g,n);r&&e(g,r,k,n||f.name);return k}}]}function Ye(){this.$get=["$window",function(b){return y(b.document)}]}function Ze(){this.$get=["$log",function(b){return function(a,c){b.error.apply(b,arguments)}}]}function Zb(b){return H(b)?aa(b)?b.toISOString():db(b):b}
function cf(){this.$get=function(){return function(b){if(!b)return"";var a=[];oc(b,function(b,d){null===b||A(b)||(G(b)?m(b,function(b,c){a.push(ma(d)+"="+ma(Zb(b)))}):a.push(ma(d)+"="+ma(Zb(b))))});return a.join("&")}}}function df(){this.$get=function(){return function(b){function a(b,e,f){null===b||A(b)||(G(b)?m(b,function(b){a(b,e+"[]")}):H(b)&&!aa(b)?oc(b,function(b,c){a(b,e+(f?"":"[")+c+(f?"":"]"))}):c.push(ma(e)+"="+ma(Zb(b))))}if(!b)return"";var c=[];a(b,"",!0);return c.join("&")}}}function $b(b,
a){if(L(b)){var c=b.replace(Of,"").trim();if(c){var d=a("Content-Type");(d=d&&0===d.indexOf(cd))||(d=(d=c.match(Pf))&&Qf[d[0]].test(c));d&&(b=wc(c))}}return b}function dd(b){var a=ga(),c;L(b)?m(b.split("\n"),function(b){c=b.indexOf(":");var e=M(R(b.substr(0,c)));b=R(b.substr(c+1));e&&(a[e]=a[e]?a[e]+", "+b:b)}):H(b)&&m(b,function(b,c){var f=M(c),g=R(b);f&&(a[f]=a[f]?a[f]+", "+g:g)});return a}function ed(b){var a;return function(c){a||(a=dd(b));return c?(c=a[M(c)],void 0===c&&(c=null),c):a}}function fd(b,
a,c,d){if(z(d))return d(b,a,c);m(d,function(d){b=d(b,a,c)});return b}function bf(){var b=this.defaults={transformResponse:[$b],transformRequest:[function(a){return H(a)&&"[object File]"!==sa.call(a)&&"[object Blob]"!==sa.call(a)&&"[object FormData]"!==sa.call(a)?db(a):a}],headers:{common:{Accept:"application/json, text/plain, */*"},post:ia(ac),put:ia(ac),patch:ia(ac)},xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",paramSerializer:"$httpParamSerializer"},a=!1;this.useApplyAsync=function(b){return w(b)?
(a=!!b,this):a};var c=this.interceptors=[];this.$get=["$httpBackend","$$cookieReader","$cacheFactory","$rootScope","$q","$injector",function(d,e,f,g,h,l){function k(a){function c(a){var b=P({},a);b.data=a.data?fd(a.data,a.headers,a.status,e.transformResponse):a.data;a=a.status;return 200<=a&&300>a?b:h.reject(b)}function d(a,b){var c,e={};m(a,function(a,d){z(a)?(c=a(b),null!=c&&(e[d]=c)):e[d]=a});return e}if(!ca.isObject(a))throw J("$http")("badreq",a);var e=P({method:"get",transformRequest:b.transformRequest,
transformResponse:b.transformResponse,paramSerializer:b.paramSerializer},a);e.headers=function(a){var c=b.headers,e=P({},a.headers),f,g,h,c=P({},c.common,c[M(a.method)]);a:for(f in c){g=M(f);for(h in e)if(M(h)===g)continue a;e[f]=c[f]}return d(e,ia(a))}(a);e.method=rb(e.method);e.paramSerializer=L(e.paramSerializer)?l.get(e.paramSerializer):e.paramSerializer;var f=[function(a){var d=a.headers,e=fd(a.data,ed(d),t,a.transformRequest);A(e)&&m(d,function(a,b){"content-type"===M(b)&&delete d[b]});A(a.withCredentials)&&
!A(b.withCredentials)&&(a.withCredentials=b.withCredentials);return n(a,e).then(c,c)},t],g=h.when(e);for(m(x,function(a){(a.request||a.requestError)&&f.unshift(a.request,a.requestError);(a.response||a.responseError)&&f.push(a.response,a.responseError)});f.length;){a=f.shift();var k=f.shift(),g=g.then(a,k)}g.success=function(a){Qa(a,"fn");g.then(function(b){a(b.data,b.status,b.headers,e)});return g};g.error=function(a){Qa(a,"fn");g.then(null,function(b){a(b.data,b.status,b.headers,e)});return g};return g}
function n(c,f){function l(b,c,d,e){function f(){n(c,b,d,e)}N&&(200<=b&&300>b?N.put(S,[b,c,dd(d),e]):N.remove(S));a?g.$applyAsync(f):(f(),g.$$phase||g.$apply())}function n(a,b,d,e){b=Math.max(b,0);(200<=b&&300>b?I.resolve:I.reject)({data:a,status:b,headers:ed(d),config:c,statusText:e})}function x(a){n(a.data,a.status,ia(a.headers()),a.statusText)}function m(){var a=k.pendingRequests.indexOf(c);-1!==a&&k.pendingRequests.splice(a,1)}var I=h.defer(),B=I.promise,N,D,q=c.headers,S=r(c.url,c.paramSerializer(c.params));
k.pendingRequests.push(c);B.then(m,m);!c.cache&&!b.cache||!1===c.cache||"GET"!==c.method&&"JSONP"!==c.method||(N=H(c.cache)?c.cache:H(b.cache)?b.cache:s);N&&(D=N.get(S),w(D)?D&&z(D.then)?D.then(x,x):G(D)?n(D[1],D[0],ia(D[2]),D[3]):n(D,200,{},"OK"):N.put(S,B));A(D)&&((D=gd(c.url)?e()[c.xsrfCookieName||b.xsrfCookieName]:t)&&(q[c.xsrfHeaderName||b.xsrfHeaderName]=D),d(c.method,S,f,l,q,c.timeout,c.withCredentials,c.responseType));return B}function r(a,b){0<b.length&&(a+=(-1==a.indexOf("?")?"?":"&")+b);
return a}var s=f("$http");b.paramSerializer=L(b.paramSerializer)?l.get(b.paramSerializer):b.paramSerializer;var x=[];m(c,function(a){x.unshift(L(a)?l.get(a):l.invoke(a))});k.pendingRequests=[];(function(a){m(arguments,function(a){k[a]=function(b,c){return k(P({},c||{},{method:a,url:b}))}})})("get","delete","head","jsonp");(function(a){m(arguments,function(a){k[a]=function(b,c,d){return k(P({},d||{},{method:a,url:b,data:c}))}})})("post","put","patch");k.defaults=b;return k}]}function Rf(){return new O.XMLHttpRequest}
function ef(){this.$get=["$browser","$window","$document",function(b,a,c){return Sf(b,Rf,b.defer,a.angular.callbacks,c[0])}]}function Sf(b,a,c,d,e){function f(a,b,c){var f=e.createElement("script"),n=null;f.type="text/javascript";f.src=a;f.async=!0;n=function(a){f.removeEventListener("load",n,!1);f.removeEventListener("error",n,!1);e.body.removeChild(f);f=null;var g=-1,x="unknown";a&&("load"!==a.type||d[b].called||(a={type:"error"}),x=a.type,g="error"===a.type?404:200);c&&c(g,x)};f.addEventListener("load",
n,!1);f.addEventListener("error",n,!1);e.body.appendChild(f);return n}return function(e,h,l,k,n,r,s,x){function C(){p&&p();K&&K.abort()}function F(a,d,e,f,g){I!==t&&c.cancel(I);p=K=null;a(d,e,f,g);b.$$completeOutstandingRequest(v)}b.$$incOutstandingRequestCount();h=h||b.url();if("jsonp"==M(e)){var u="_"+(d.counter++).toString(36);d[u]=function(a){d[u].data=a;d[u].called=!0};var p=f(h.replace("JSON_CALLBACK","angular.callbacks."+u),u,function(a,b){F(k,a,d[u].data,"",b);d[u]=v})}else{var K=a();K.open(e,
h,!0);m(n,function(a,b){w(a)&&K.setRequestHeader(b,a)});K.onload=function(){var a=K.statusText||"",b="response"in K?K.response:K.responseText,c=1223===K.status?204:K.status;0===c&&(c=b?200:"file"==Ba(h).protocol?404:0);F(k,c,b,K.getAllResponseHeaders(),a)};e=function(){F(k,-1,null,null,"")};K.onerror=e;K.onabort=e;s&&(K.withCredentials=!0);if(x)try{K.responseType=x}catch(q){if("json"!==x)throw q;}K.send(l)}if(0<r)var I=c(C,r);else r&&z(r.then)&&r.then(C)}}function $e(){var b="{{",a="}}";this.startSymbol=
function(a){return a?(b=a,this):b};this.endSymbol=function(b){return b?(a=b,this):a};this.$get=["$parse","$exceptionHandler","$sce",function(c,d,e){function f(a){return"\\\\\\"+a}function g(c){return c.replace(n,b).replace(r,a)}function h(f,h,n,r){function u(a){try{var b=a;a=n?e.getTrusted(n,b):e.valueOf(b);var c;if(r&&!w(a))c=a;else if(null==a)c="";else{switch(typeof a){case "string":break;case "number":a=""+a;break;default:a=db(a)}c=a}return c}catch(g){d(Ka.interr(f,g))}}r=!!r;for(var p,m,q=0,I=
[],B=[],N=f.length,D=[],t=[];q<N;)if(-1!=(p=f.indexOf(b,q))&&-1!=(m=f.indexOf(a,p+l)))q!==p&&D.push(g(f.substring(q,p))),q=f.substring(p+l,m),I.push(q),B.push(c(q,u)),q=m+k,t.push(D.length),D.push("");else{q!==N&&D.push(g(f.substring(q)));break}n&&1<D.length&&Ka.throwNoconcat(f);if(!h||I.length){var S=function(a){for(var b=0,c=I.length;b<c;b++){if(r&&A(a[b]))return;D[t[b]]=a[b]}return D.join("")};return P(function(a){var b=0,c=I.length,e=Array(c);try{for(;b<c;b++)e[b]=B[b](a);return S(e)}catch(g){d(Ka.interr(f,
g))}},{exp:f,expressions:I,$$watchDelegate:function(a,b){var c;return a.$watchGroup(B,function(d,e){var f=S(d);z(b)&&b.call(this,f,d!==e?c:f,a);c=f})}})}}var l=b.length,k=a.length,n=new RegExp(b.replace(/./g,f),"g"),r=new RegExp(a.replace(/./g,f),"g");h.startSymbol=function(){return b};h.endSymbol=function(){return a};return h}]}function af(){this.$get=["$rootScope","$window","$q","$$q",function(b,a,c,d){function e(e,h,l,k){var n=4<arguments.length,r=n?za.call(arguments,4):[],s=a.setInterval,x=a.clearInterval,
C=0,F=w(k)&&!k,u=(F?d:c).defer(),p=u.promise;l=w(l)?l:0;p.then(null,null,n?function(){e.apply(null,r)}:e);p.$$intervalId=s(function(){u.notify(C++);0<l&&C>=l&&(u.resolve(C),x(p.$$intervalId),delete f[p.$$intervalId]);F||b.$apply()},h);f[p.$$intervalId]=u;return p}var f={};e.cancel=function(b){return b&&b.$$intervalId in f?(f[b.$$intervalId].reject("canceled"),a.clearInterval(b.$$intervalId),delete f[b.$$intervalId],!0):!1};return e}]}function ge(){this.$get=function(){return{id:"en-us",NUMBER_FORMATS:{DECIMAL_SEP:".",
GROUP_SEP:",",PATTERNS:[{minInt:1,minFrac:0,maxFrac:3,posPre:"",posSuf:"",negPre:"-",negSuf:"",gSize:3,lgSize:3},{minInt:1,minFrac:2,maxFrac:2,posPre:"\u00a4",posSuf:"",negPre:"(\u00a4",negSuf:")",gSize:3,lgSize:3}],CURRENCY_SYM:"$"},DATETIME_FORMATS:{MONTH:"January February March April May June July August September October November December".split(" "),SHORTMONTH:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),DAY:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),
SHORTDAY:"Sun Mon Tue Wed Thu Fri Sat".split(" "),AMPMS:["AM","PM"],medium:"MMM d, y h:mm:ss a","short":"M/d/yy h:mm a",fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",mediumDate:"MMM d, y",shortDate:"M/d/yy",mediumTime:"h:mm:ss a",shortTime:"h:mm a",ERANAMES:["Before Christ","Anno Domini"],ERAS:["BC","AD"]},pluralCat:function(b){return 1===b?"one":"other"}}}}function bc(b){b=b.split("/");for(var a=b.length;a--;)b[a]=ob(b[a]);return b.join("/")}function hd(b,a){var c=Ba(b);a.$$protocol=c.protocol;
a.$$host=c.hostname;a.$$port=W(c.port)||Tf[c.protocol]||null}function id(b,a){var c="/"!==b.charAt(0);c&&(b="/"+b);var d=Ba(b);a.$$path=decodeURIComponent(c&&"/"===d.pathname.charAt(0)?d.pathname.substring(1):d.pathname);a.$$search=zc(d.search);a.$$hash=decodeURIComponent(d.hash);a.$$path&&"/"!=a.$$path.charAt(0)&&(a.$$path="/"+a.$$path)}function ya(b,a){if(0===a.indexOf(b))return a.substr(b.length)}function Ja(b){var a=b.indexOf("#");return-1==a?b:b.substr(0,a)}function Bb(b){return b.replace(/(#.+)|#$/,
"$1")}function cc(b){return b.substr(0,Ja(b).lastIndexOf("/")+1)}function dc(b,a){this.$$html5=!0;a=a||"";var c=cc(b);hd(b,this);this.$$parse=function(a){var b=ya(c,a);if(!L(b))throw Cb("ipthprfx",a,c);id(b,this);this.$$path||(this.$$path="/");this.$$compose()};this.$$compose=function(){var a=Qb(this.$$search),b=this.$$hash?"#"+ob(this.$$hash):"";this.$$url=bc(this.$$path)+(a?"?"+a:"")+b;this.$$absUrl=c+this.$$url.substr(1)};this.$$parseLinkUrl=function(d,e){if(e&&"#"===e[0])return this.hash(e.slice(1)),
!0;var f,g;(f=ya(b,d))!==t?(g=f,g=(f=ya(a,f))!==t?c+(ya("/",f)||f):b+g):(f=ya(c,d))!==t?g=c+f:c==d+"/"&&(g=c);g&&this.$$parse(g);return!!g}}function ec(b,a){var c=cc(b);hd(b,this);this.$$parse=function(d){var e=ya(b,d)||ya(c,d),f;A(e)||"#"!==e.charAt(0)?this.$$html5?f=e:(f="",A(e)&&(b=d,this.replace())):(f=ya(a,e),A(f)&&(f=e));id(f,this);d=this.$$path;var e=b,g=/^\/[A-Z]:(\/.*)/;0===f.indexOf(e)&&(f=f.replace(e,""));g.exec(f)||(d=(f=g.exec(d))?f[1]:d);this.$$path=d;this.$$compose()};this.$$compose=
function(){var c=Qb(this.$$search),e=this.$$hash?"#"+ob(this.$$hash):"";this.$$url=bc(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=b+(this.$$url?a+this.$$url:"")};this.$$parseLinkUrl=function(a,c){return Ja(b)==Ja(a)?(this.$$parse(a),!0):!1}}function jd(b,a){this.$$html5=!0;ec.apply(this,arguments);var c=cc(b);this.$$parseLinkUrl=function(d,e){if(e&&"#"===e[0])return this.hash(e.slice(1)),!0;var f,g;b==Ja(d)?f=d:(g=ya(c,d))?f=b+a+g:c===d+"/"&&(f=c);f&&this.$$parse(f);return!!f};this.$$compose=function(){var c=
Qb(this.$$search),e=this.$$hash?"#"+ob(this.$$hash):"";this.$$url=bc(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=b+a+this.$$url}}function Db(b){return function(){return this[b]}}function kd(b,a){return function(c){if(A(c))return this[b];this[b]=a(c);this.$$compose();return this}}function ff(){var b="",a={enabled:!1,requireBase:!0,rewriteLinks:!0};this.hashPrefix=function(a){return w(a)?(b=a,this):b};this.html5Mode=function(b){return ab(b)?(a.enabled=b,this):H(b)?(ab(b.enabled)&&(a.enabled=b.enabled),
ab(b.requireBase)&&(a.requireBase=b.requireBase),ab(b.rewriteLinks)&&(a.rewriteLinks=b.rewriteLinks),this):a};this.$get=["$rootScope","$browser","$sniffer","$rootElement","$window",function(c,d,e,f,g){function h(a,b,c){var e=k.url(),f=k.$$state;try{d.url(a,b,c),k.$$state=d.state()}catch(g){throw k.url(e),k.$$state=f,g;}}function l(a,b){c.$broadcast("$locationChangeSuccess",k.absUrl(),a,k.$$state,b)}var k,n;n=d.baseHref();var r=d.url(),s;if(a.enabled){if(!n&&a.requireBase)throw Cb("nobase");s=r.substring(0,
r.indexOf("/",r.indexOf("//")+2))+(n||"/");n=e.history?dc:jd}else s=Ja(r),n=ec;k=new n(s,"#"+b);k.$$parseLinkUrl(r,r);k.$$state=d.state();var x=/^\s*(javascript|mailto):/i;f.on("click",function(b){if(a.rewriteLinks&&!b.ctrlKey&&!b.metaKey&&!b.shiftKey&&2!=b.which&&2!=b.button){for(var e=y(b.target);"a"!==ta(e[0]);)if(e[0]===f[0]||!(e=e.parent())[0])return;var h=e.prop("href"),l=e.attr("href")||e.attr("xlink:href");H(h)&&"[object SVGAnimatedString]"===h.toString()&&(h=Ba(h.animVal).href);x.test(h)||
!h||e.attr("target")||b.isDefaultPrevented()||!k.$$parseLinkUrl(h,l)||(b.preventDefault(),k.absUrl()!=d.url()&&(c.$apply(),g.angular["ff-684208-preventDefault"]=!0))}});Bb(k.absUrl())!=Bb(r)&&d.url(k.absUrl(),!0);var C=!0;d.onUrlChange(function(a,b){c.$evalAsync(function(){var d=k.absUrl(),e=k.$$state,f;k.$$parse(a);k.$$state=b;f=c.$broadcast("$locationChangeStart",a,d,b,e).defaultPrevented;k.absUrl()===a&&(f?(k.$$parse(d),k.$$state=e,h(d,!1,e)):(C=!1,l(d,e)))});c.$$phase||c.$digest()});c.$watch(function(){var a=
Bb(d.url()),b=Bb(k.absUrl()),f=d.state(),g=k.$$replace,n=a!==b||k.$$html5&&e.history&&f!==k.$$state;if(C||n)C=!1,c.$evalAsync(function(){var b=k.absUrl(),d=c.$broadcast("$locationChangeStart",b,a,k.$$state,f).defaultPrevented;k.absUrl()===b&&(d?(k.$$parse(a),k.$$state=f):(n&&h(b,g,f===k.$$state?null:k.$$state),l(a,f)))});k.$$replace=!1});return k}]}function gf(){var b=!0,a=this;this.debugEnabled=function(a){return w(a)?(b=a,this):b};this.$get=["$window",function(c){function d(a){a instanceof Error&&
(a.stack?a=a.message&&-1===a.stack.indexOf(a.message)?"Error: "+a.message+"\n"+a.stack:a.stack:a.sourceURL&&(a=a.message+"\n"+a.sourceURL+":"+a.line));return a}function e(a){var b=c.console||{},e=b[a]||b.log||v;a=!1;try{a=!!e.apply}catch(l){}return a?function(){var a=[];m(arguments,function(b){a.push(d(b))});return e.apply(b,a)}:function(a,b){e(a,null==b?"":b)}}return{log:e("log"),info:e("info"),warn:e("warn"),error:e("error"),debug:function(){var c=e("debug");return function(){b&&c.apply(a,arguments)}}()}}]}
function Ca(b,a){if("__defineGetter__"===b||"__defineSetter__"===b||"__lookupGetter__"===b||"__lookupSetter__"===b||"__proto__"===b)throw da("isecfld",a);return b}function oa(b,a){if(b){if(b.constructor===b)throw da("isecfn",a);if(b.window===b)throw da("isecwindow",a);if(b.children&&(b.nodeName||b.prop&&b.attr&&b.find))throw da("isecdom",a);if(b===Object)throw da("isecobj",a);}return b}function ld(b,a){if(b){if(b.constructor===b)throw da("isecfn",a);if(b===Uf||b===Vf||b===Wf)throw da("isecff",a);
}}function Xf(b,a){return"undefined"!==typeof b?b:a}function md(b,a){return"undefined"===typeof b?a:"undefined"===typeof a?b:b+a}function T(b,a){var c,d;switch(b.type){case q.Program:c=!0;m(b.body,function(b){T(b.expression,a);c=c&&b.expression.constant});b.constant=c;break;case q.Literal:b.constant=!0;b.toWatch=[];break;case q.UnaryExpression:T(b.argument,a);b.constant=b.argument.constant;b.toWatch=b.argument.toWatch;break;case q.BinaryExpression:T(b.left,a);T(b.right,a);b.constant=b.left.constant&&
b.right.constant;b.toWatch=b.left.toWatch.concat(b.right.toWatch);break;case q.LogicalExpression:T(b.left,a);T(b.right,a);b.constant=b.left.constant&&b.right.constant;b.toWatch=b.constant?[]:[b];break;case q.ConditionalExpression:T(b.test,a);T(b.alternate,a);T(b.consequent,a);b.constant=b.test.constant&&b.alternate.constant&&b.consequent.constant;b.toWatch=b.constant?[]:[b];break;case q.Identifier:b.constant=!1;b.toWatch=[b];break;case q.MemberExpression:T(b.object,a);b.computed&&T(b.property,a);
b.constant=b.object.constant&&(!b.computed||b.property.constant);b.toWatch=[b];break;case q.CallExpression:c=b.filter?!a(b.callee.name).$stateful:!1;d=[];m(b.arguments,function(b){T(b,a);c=c&&b.constant;b.constant||d.push.apply(d,b.toWatch)});b.constant=c;b.toWatch=b.filter&&!a(b.callee.name).$stateful?d:[b];break;case q.AssignmentExpression:T(b.left,a);T(b.right,a);b.constant=b.left.constant&&b.right.constant;b.toWatch=[b];break;case q.ArrayExpression:c=!0;d=[];m(b.elements,function(b){T(b,a);c=
c&&b.constant;b.constant||d.push.apply(d,b.toWatch)});b.constant=c;b.toWatch=d;break;case q.ObjectExpression:c=!0;d=[];m(b.properties,function(b){T(b.value,a);c=c&&b.value.constant;b.value.constant||d.push.apply(d,b.value.toWatch)});b.constant=c;b.toWatch=d;break;case q.ThisExpression:b.constant=!1,b.toWatch=[]}}function nd(b){if(1==b.length){b=b[0].expression;var a=b.toWatch;return 1!==a.length?a:a[0]!==b?a:t}}function od(b){return b.type===q.Identifier||b.type===q.MemberExpression}function pd(b){if(1===
b.body.length&&od(b.body[0].expression))return{type:q.AssignmentExpression,left:b.body[0].expression,right:{type:q.NGValueParameter},operator:"="}}function qd(b){return 0===b.body.length||1===b.body.length&&(b.body[0].expression.type===q.Literal||b.body[0].expression.type===q.ArrayExpression||b.body[0].expression.type===q.ObjectExpression)}function rd(b,a){this.astBuilder=b;this.$filter=a}function sd(b,a){this.astBuilder=b;this.$filter=a}function Eb(b,a,c,d){oa(b,d);a=a.split(".");for(var e,f=0;1<
a.length;f++){e=Ca(a.shift(),d);var g=oa(b[e],d);g||(g={},b[e]=g);b=g}e=Ca(a.shift(),d);oa(b[e],d);return b[e]=c}function Fb(b){return"constructor"==b}function fc(b){return z(b.valueOf)?b.valueOf():Yf.call(b)}function hf(){var b=ga(),a=ga();this.$get=["$filter","$sniffer",function(c,d){function e(a,b){return null==a||null==b?a===b:"object"===typeof a&&(a=fc(a),"object"===typeof a)?!1:a===b||a!==a&&b!==b}function f(a,b,c,d,f){var g=d.inputs,h;if(1===g.length){var k=e,g=g[0];return a.$watch(function(a){var b=
g(a);e(b,k)||(h=d(a,t,t,[b]),k=b&&fc(b));return h},b,c,f)}for(var l=[],n=[],r=0,m=g.length;r<m;r++)l[r]=e,n[r]=null;return a.$watch(function(a){for(var b=!1,c=0,f=g.length;c<f;c++){var k=g[c](a);if(b||(b=!e(k,l[c])))n[c]=k,l[c]=k&&fc(k)}b&&(h=d(a,t,t,n));return h},b,c,f)}function g(a,b,c,d){var e,f;return e=a.$watch(function(a){return d(a)},function(a,c,d){f=a;z(b)&&b.apply(this,arguments);w(a)&&d.$$postDigest(function(){w(f)&&e()})},c)}function h(a,b,c,d){function e(a){var b=!0;m(a,function(a){w(a)||
(b=!1)});return b}var f,g;return f=a.$watch(function(a){return d(a)},function(a,c,d){g=a;z(b)&&b.call(this,a,c,d);e(a)&&d.$$postDigest(function(){e(g)&&f()})},c)}function l(a,b,c,d){var e;return e=a.$watch(function(a){return d(a)},function(a,c,d){z(b)&&b.apply(this,arguments);e()},c)}function k(a,b){if(!b)return a;var c=a.$$watchDelegate,c=c!==h&&c!==g?function(c,d,e,f){e=a(c,d,e,f);return b(e,c,d)}:function(c,d,e,f){e=a(c,d,e,f);c=b(e,c,d);return w(e)?c:e};a.$$watchDelegate&&a.$$watchDelegate!==
f?c.$$watchDelegate=a.$$watchDelegate:b.$stateful||(c.$$watchDelegate=f,c.inputs=a.inputs?a.inputs:[a]);return c}var n={csp:d.csp,expensiveChecks:!1},r={csp:d.csp,expensiveChecks:!0};return function(d,e,C){var m,u,p;switch(typeof d){case "string":p=d=d.trim();var q=C?a:b;m=q[p];m||(":"===d.charAt(0)&&":"===d.charAt(1)&&(u=!0,d=d.substring(2)),C=C?r:n,m=new gc(C),m=(new hc(m,c,C)).parse(d),m.constant?m.$$watchDelegate=l:u?m.$$watchDelegate=m.literal?h:g:m.inputs&&(m.$$watchDelegate=f),q[p]=m);return k(m,
e);case "function":return k(d,e);default:return v}}}]}function kf(){this.$get=["$rootScope","$exceptionHandler",function(b,a){return td(function(a){b.$evalAsync(a)},a)}]}function lf(){this.$get=["$browser","$exceptionHandler",function(b,a){return td(function(a){b.defer(a)},a)}]}function td(b,a){function c(a,b,c){function d(b){return function(c){e||(e=!0,b.call(a,c))}}var e=!1;return[d(b),d(c)]}function d(){this.$$state={status:0}}function e(a,b){return function(c){b.call(a,c)}}function f(c){!c.processScheduled&&
c.pending&&(c.processScheduled=!0,b(function(){var b,d,e;e=c.pending;c.processScheduled=!1;c.pending=t;for(var f=0,g=e.length;f<g;++f){d=e[f][0];b=e[f][c.status];try{z(b)?d.resolve(b(c.value)):1===c.status?d.resolve(c.value):d.reject(c.value)}catch(h){d.reject(h),a(h)}}}))}function g(){this.promise=new d;this.resolve=e(this,this.resolve);this.reject=e(this,this.reject);this.notify=e(this,this.notify)}var h=J("$q",TypeError);d.prototype={then:function(a,b,c){var d=new g;this.$$state.pending=this.$$state.pending||
[];this.$$state.pending.push([d,a,b,c]);0<this.$$state.status&&f(this.$$state);return d.promise},"catch":function(a){return this.then(null,a)},"finally":function(a,b){return this.then(function(b){return k(b,!0,a)},function(b){return k(b,!1,a)},b)}};g.prototype={resolve:function(a){this.promise.$$state.status||(a===this.promise?this.$$reject(h("qcycle",a)):this.$$resolve(a))},$$resolve:function(b){var d,e;e=c(this,this.$$resolve,this.$$reject);try{if(H(b)||z(b))d=b&&b.then;z(d)?(this.promise.$$state.status=
-1,d.call(b,e[0],e[1],this.notify)):(this.promise.$$state.value=b,this.promise.$$state.status=1,f(this.promise.$$state))}catch(g){e[1](g),a(g)}},reject:function(a){this.promise.$$state.status||this.$$reject(a)},$$reject:function(a){this.promise.$$state.value=a;this.promise.$$state.status=2;f(this.promise.$$state)},notify:function(c){var d=this.promise.$$state.pending;0>=this.promise.$$state.status&&d&&d.length&&b(function(){for(var b,e,f=0,g=d.length;f<g;f++){e=d[f][0];b=d[f][3];try{e.notify(z(b)?
b(c):c)}catch(h){a(h)}}})}};var l=function(a,b){var c=new g;b?c.resolve(a):c.reject(a);return c.promise},k=function(a,b,c){var d=null;try{z(c)&&(d=c())}catch(e){return l(e,!1)}return d&&z(d.then)?d.then(function(){return l(a,b)},function(a){return l(a,!1)}):l(a,b)},n=function(a,b,c,d){var e=new g;e.resolve(a);return e.promise.then(b,c,d)},r=function x(a){if(!z(a))throw h("norslvr",a);if(!(this instanceof x))return new x(a);var b=new g;a(function(a){b.resolve(a)},function(a){b.reject(a)});return b.promise};
r.defer=function(){return new g};r.reject=function(a){var b=new g;b.reject(a);return b.promise};r.when=n;r.resolve=n;r.all=function(a){var b=new g,c=0,d=G(a)?[]:{};m(a,function(a,e){c++;n(a).then(function(a){d.hasOwnProperty(e)||(d[e]=a,--c||b.resolve(d))},function(a){d.hasOwnProperty(e)||b.reject(a)})});0===c&&b.resolve(d);return b.promise};return r}function uf(){this.$get=["$window","$timeout",function(b,a){function c(){for(var a=0;a<n.length;a++){var b=n[a];b&&(n[a]=null,b())}k=n.length=0}function d(a){var b=
n.length;k++;n.push(a);0===b&&(l=h(c));return function(){0<=b&&(b=n[b]=null,0===--k&&l&&(l(),l=null,n.length=0))}}var e=b.requestAnimationFrame||b.webkitRequestAnimationFrame,f=b.cancelAnimationFrame||b.webkitCancelAnimationFrame||b.webkitCancelRequestAnimationFrame,g=!!e,h=g?function(a){var b=e(a);return function(){f(b)}}:function(b){var c=a(b,16.66,!1);return function(){a.cancel(c)}};d.supported=g;var l,k=0,n=[];return d}]}function jf(){function b(a){function b(){this.$$watchers=this.$$nextSibling=
this.$$childHead=this.$$childTail=null;this.$$listeners={};this.$$listenerCount={};this.$$watchersCount=0;this.$id=++nb;this.$$ChildScope=null}b.prototype=a;return b}var a=10,c=J("$rootScope"),d=null,e=null;this.digestTtl=function(b){arguments.length&&(a=b);return a};this.$get=["$injector","$exceptionHandler","$parse","$browser",function(f,g,h,l){function k(a){a.currentScope.$$destroyed=!0}function n(){this.$id=++nb;this.$$phase=this.$parent=this.$$watchers=this.$$nextSibling=this.$$prevSibling=this.$$childHead=
this.$$childTail=null;this.$root=this;this.$$destroyed=!1;this.$$listeners={};this.$$listenerCount={};this.$$watchersCount=0;this.$$isolateBindings=null}function r(a){if(p.$$phase)throw c("inprog",p.$$phase);p.$$phase=a}function s(a,b){do a.$$watchersCount+=b;while(a=a.$parent)}function x(a,b,c){do a.$$listenerCount[c]-=b,0===a.$$listenerCount[c]&&delete a.$$listenerCount[c];while(a=a.$parent)}function q(){}function F(){for(;I.length;)try{I.shift()()}catch(a){g(a)}e=null}function u(){null===e&&(e=
l.defer(function(){p.$apply(F)}))}n.prototype={constructor:n,$new:function(a,c){var d;c=c||this;a?(d=new n,d.$root=this.$root):(this.$$ChildScope||(this.$$ChildScope=b(this)),d=new this.$$ChildScope);d.$parent=c;d.$$prevSibling=c.$$childTail;c.$$childHead?(c.$$childTail.$$nextSibling=d,c.$$childTail=d):c.$$childHead=c.$$childTail=d;(a||c!=this)&&d.$on("$destroy",k);return d},$watch:function(a,b,c,e){var f=h(a);if(f.$$watchDelegate)return f.$$watchDelegate(this,b,c,f,a);var g=this,k=g.$$watchers,l=
{fn:b,last:q,get:f,exp:e||a,eq:!!c};d=null;z(b)||(l.fn=v);k||(k=g.$$watchers=[]);k.unshift(l);s(this,1);return function(){0<=bb(k,l)&&s(g,-1);d=null}},$watchGroup:function(a,b){function c(){h=!1;k?(k=!1,b(e,e,g)):b(e,d,g)}var d=Array(a.length),e=Array(a.length),f=[],g=this,h=!1,k=!0;if(!a.length){var l=!0;g.$evalAsync(function(){l&&b(e,e,g)});return function(){l=!1}}if(1===a.length)return this.$watch(a[0],function(a,c,f){e[0]=a;d[0]=c;b(e,a===c?e:d,f)});m(a,function(a,b){var k=g.$watch(a,function(a,
f){e[b]=a;d[b]=f;h||(h=!0,g.$evalAsync(c))});f.push(k)});return function(){for(;f.length;)f.shift()()}},$watchCollection:function(a,b){function c(a){e=a;var b,d,g,h;if(!A(e)){if(H(e))if(Ea(e))for(f!==r&&(f=r,m=f.length=0,l++),a=e.length,m!==a&&(l++,f.length=m=a),b=0;b<a;b++)h=f[b],g=e[b],d=h!==h&&g!==g,d||h===g||(l++,f[b]=g);else{f!==s&&(f=s={},m=0,l++);a=0;for(b in e)e.hasOwnProperty(b)&&(a++,g=e[b],h=f[b],b in f?(d=h!==h&&g!==g,d||h===g||(l++,f[b]=g)):(m++,f[b]=g,l++));if(m>a)for(b in l++,f)e.hasOwnProperty(b)||
(m--,delete f[b])}else f!==e&&(f=e,l++);return l}}c.$stateful=!0;var d=this,e,f,g,k=1<b.length,l=0,n=h(a,c),r=[],s={},p=!0,m=0;return this.$watch(n,function(){p?(p=!1,b(e,e,d)):b(e,g,d);if(k)if(H(e))if(Ea(e)){g=Array(e.length);for(var a=0;a<e.length;a++)g[a]=e[a]}else for(a in g={},e)Xa.call(e,a)&&(g[a]=e[a]);else g=e})},$digest:function(){var b,f,h,k,n,s,m=a,x,u=[],E,I;r("$digest");l.$$checkUrlChange();this===p&&null!==e&&(l.defer.cancel(e),F());d=null;do{s=!1;for(x=this;t.length;){try{I=t.shift(),
I.scope.$eval(I.expression,I.locals)}catch(v){g(v)}d=null}a:do{if(k=x.$$watchers)for(n=k.length;n--;)try{if(b=k[n])if((f=b.get(x))!==(h=b.last)&&!(b.eq?ka(f,h):"number"===typeof f&&"number"===typeof h&&isNaN(f)&&isNaN(h)))s=!0,d=b,b.last=b.eq?fa(f,null):f,b.fn(f,h===q?f:h,x),5>m&&(E=4-m,u[E]||(u[E]=[]),u[E].push({msg:z(b.exp)?"fn: "+(b.exp.name||b.exp.toString()):b.exp,newVal:f,oldVal:h}));else if(b===d){s=!1;break a}}catch(A){g(A)}if(!(k=x.$$watchersCount&&x.$$childHead||x!==this&&x.$$nextSibling))for(;x!==
this&&!(k=x.$$nextSibling);)x=x.$parent}while(x=k);if((s||t.length)&&!m--)throw p.$$phase=null,c("infdig",a,u);}while(s||t.length);for(p.$$phase=null;w.length;)try{w.shift()()}catch(y){g(y)}},$destroy:function(){if(!this.$$destroyed){var a=this.$parent;this.$broadcast("$destroy");this.$$destroyed=!0;this===p&&l.$$applicationDestroyed();s(this,-this.$$watchersCount);for(var b in this.$$listenerCount)x(this,this.$$listenerCount[b],b);a&&a.$$childHead==this&&(a.$$childHead=this.$$nextSibling);a&&a.$$childTail==
this&&(a.$$childTail=this.$$prevSibling);this.$$prevSibling&&(this.$$prevSibling.$$nextSibling=this.$$nextSibling);this.$$nextSibling&&(this.$$nextSibling.$$prevSibling=this.$$prevSibling);this.$destroy=this.$digest=this.$apply=this.$evalAsync=this.$applyAsync=v;this.$on=this.$watch=this.$watchGroup=function(){return v};this.$$listeners={};this.$parent=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=this.$root=this.$$watchers=null}},$eval:function(a,b){return h(a)(this,b)},
$evalAsync:function(a,b){p.$$phase||t.length||l.defer(function(){t.length&&p.$digest()});t.push({scope:this,expression:a,locals:b})},$$postDigest:function(a){w.push(a)},$apply:function(a){try{return r("$apply"),this.$eval(a)}catch(b){g(b)}finally{p.$$phase=null;try{p.$digest()}catch(c){throw g(c),c;}}},$applyAsync:function(a){function b(){c.$eval(a)}var c=this;a&&I.push(b);u()},$on:function(a,b){var c=this.$$listeners[a];c||(this.$$listeners[a]=c=[]);c.push(b);var d=this;do d.$$listenerCount[a]||
(d.$$listenerCount[a]=0),d.$$listenerCount[a]++;while(d=d.$parent);var e=this;return function(){var d=c.indexOf(b);-1!==d&&(c[d]=null,x(e,1,a))}},$emit:function(a,b){var c=[],d,e=this,f=!1,h={name:a,targetScope:e,stopPropagation:function(){f=!0},preventDefault:function(){h.defaultPrevented=!0},defaultPrevented:!1},k=cb([h],arguments,1),l,n;do{d=e.$$listeners[a]||c;h.currentScope=e;l=0;for(n=d.length;l<n;l++)if(d[l])try{d[l].apply(null,k)}catch(r){g(r)}else d.splice(l,1),l--,n--;if(f)return h.currentScope=
null,h;e=e.$parent}while(e);h.currentScope=null;return h},$broadcast:function(a,b){var c=this,d=this,e={name:a,targetScope:this,preventDefault:function(){e.defaultPrevented=!0},defaultPrevented:!1};if(!this.$$listenerCount[a])return e;for(var f=cb([e],arguments,1),h,k;c=d;){e.currentScope=c;d=c.$$listeners[a]||[];h=0;for(k=d.length;h<k;h++)if(d[h])try{d[h].apply(null,f)}catch(l){g(l)}else d.splice(h,1),h--,k--;if(!(d=c.$$listenerCount[a]&&c.$$childHead||c!==this&&c.$$nextSibling))for(;c!==this&&!(d=
c.$$nextSibling);)c=c.$parent}e.currentScope=null;return e}};var p=new n,t=p.$$asyncQueue=[],w=p.$$postDigestQueue=[],I=p.$$applyAsyncQueue=[];return p}]}function he(){var b=/^\s*(https?|ftp|mailto|tel|file):/,a=/^\s*((https?|ftp|file|blob):|data:image\/)/;this.aHrefSanitizationWhitelist=function(a){return w(a)?(b=a,this):b};this.imgSrcSanitizationWhitelist=function(b){return w(b)?(a=b,this):a};this.$get=function(){return function(c,d){var e=d?a:b,f;f=Ba(c).href;return""===f||f.match(e)?c:"unsafe:"+
f}}}function Zf(b){if("self"===b)return b;if(L(b)){if(-1<b.indexOf("***"))throw Da("iwcard",b);b=ud(b).replace("\\*\\*",".*").replace("\\*","[^:/.?&;]*");return new RegExp("^"+b+"$")}if(Za(b))return new RegExp("^"+b.source+"$");throw Da("imatcher");}function vd(b){var a=[];w(b)&&m(b,function(b){a.push(Zf(b))});return a}function nf(){this.SCE_CONTEXTS=pa;var b=["self"],a=[];this.resourceUrlWhitelist=function(a){arguments.length&&(b=vd(a));return b};this.resourceUrlBlacklist=function(b){arguments.length&&
(a=vd(b));return a};this.$get=["$injector",function(c){function d(a,b){return"self"===a?gd(b):!!a.exec(b.href)}function e(a){var b=function(a){this.$$unwrapTrustedValue=function(){return a}};a&&(b.prototype=new a);b.prototype.valueOf=function(){return this.$$unwrapTrustedValue()};b.prototype.toString=function(){return this.$$unwrapTrustedValue().toString()};return b}var f=function(a){throw Da("unsafe");};c.has("$sanitize")&&(f=c.get("$sanitize"));var g=e(),h={};h[pa.HTML]=e(g);h[pa.CSS]=e(g);h[pa.URL]=
e(g);h[pa.JS]=e(g);h[pa.RESOURCE_URL]=e(h[pa.URL]);return{trustAs:function(a,b){var c=h.hasOwnProperty(a)?h[a]:null;if(!c)throw Da("icontext",a,b);if(null===b||b===t||""===b)return b;if("string"!==typeof b)throw Da("itype",a);return new c(b)},getTrusted:function(c,e){if(null===e||e===t||""===e)return e;var g=h.hasOwnProperty(c)?h[c]:null;if(g&&e instanceof g)return e.$$unwrapTrustedValue();if(c===pa.RESOURCE_URL){var g=Ba(e.toString()),r,s,m=!1;r=0;for(s=b.length;r<s;r++)if(d(b[r],g)){m=!0;break}if(m)for(r=
0,s=a.length;r<s;r++)if(d(a[r],g)){m=!1;break}if(m)return e;throw Da("insecurl",e.toString());}if(c===pa.HTML)return f(e);throw Da("unsafe");},valueOf:function(a){return a instanceof g?a.$$unwrapTrustedValue():a}}}]}function mf(){var b=!0;this.enabled=function(a){arguments.length&&(b=!!a);return b};this.$get=["$parse","$sceDelegate",function(a,c){if(b&&8>Ua)throw Da("iequirks");var d=ia(pa);d.isEnabled=function(){return b};d.trustAs=c.trustAs;d.getTrusted=c.getTrusted;d.valueOf=c.valueOf;b||(d.trustAs=
d.getTrusted=function(a,b){return b},d.valueOf=Ya);d.parseAs=function(b,c){var e=a(c);return e.literal&&e.constant?e:a(c,function(a){return d.getTrusted(b,a)})};var e=d.parseAs,f=d.getTrusted,g=d.trustAs;m(pa,function(a,b){var c=M(b);d[hb("parse_as_"+c)]=function(b){return e(a,b)};d[hb("get_trusted_"+c)]=function(b){return f(a,b)};d[hb("trust_as_"+c)]=function(b){return g(a,b)}});return d}]}function of(){this.$get=["$window","$document",function(b,a){var c={},d=W((/android (\d+)/.exec(M((b.navigator||
{}).userAgent))||[])[1]),e=/Boxee/i.test((b.navigator||{}).userAgent),f=a[0]||{},g,h=/^(Moz|webkit|ms)(?=[A-Z])/,l=f.body&&f.body.style,k=!1,n=!1;if(l){for(var r in l)if(k=h.exec(r)){g=k[0];g=g.substr(0,1).toUpperCase()+g.substr(1);break}g||(g="WebkitOpacity"in l&&"webkit");k=!!("transition"in l||g+"Transition"in l);n=!!("animation"in l||g+"Animation"in l);!d||k&&n||(k=L(l.webkitTransition),n=L(l.webkitAnimation))}return{history:!(!b.history||!b.history.pushState||4>d||e),hasEvent:function(a){if("input"===
a&&11>=Ua)return!1;if(A(c[a])){var b=f.createElement("div");c[a]="on"+a in b}return c[a]},csp:fb(),vendorPrefix:g,transitions:k,animations:n,android:d}}]}function qf(){this.$get=["$templateCache","$http","$q","$sce",function(b,a,c,d){function e(f,g){e.totalPendingRequests++;L(f)&&b.get(f)||(f=d.getTrustedResourceUrl(f));var h=a.defaults&&a.defaults.transformResponse;G(h)?h=h.filter(function(a){return a!==$b}):h===$b&&(h=null);return a.get(f,{cache:b,transformResponse:h})["finally"](function(){e.totalPendingRequests--}).then(function(a){b.put(f,
a.data);return a.data},function(a){if(!g)throw ea("tpload",f,a.status,a.statusText);return c.reject(a)})}e.totalPendingRequests=0;return e}]}function rf(){this.$get=["$rootScope","$browser","$location",function(b,a,c){return{findBindings:function(a,b,c){a=a.getElementsByClassName("ng-binding");var g=[];m(a,function(a){var d=ca.element(a).data("$binding");d&&m(d,function(d){c?(new RegExp("(^|\\s)"+ud(b)+"(\\s|\\||$)")).test(d)&&g.push(a):-1!=d.indexOf(b)&&g.push(a)})});return g},findModels:function(a,
b,c){for(var g=["ng-","data-ng-","ng\\:"],h=0;h<g.length;++h){var l=a.querySelectorAll("["+g[h]+"model"+(c?"=":"*=")+'"'+b+'"]');if(l.length)return l}},getLocation:function(){return c.url()},setLocation:function(a){a!==c.url()&&(c.url(a),b.$digest())},whenStable:function(b){a.notifyWhenNoOutstandingRequests(b)}}}]}function sf(){this.$get=["$rootScope","$browser","$q","$$q","$exceptionHandler",function(b,a,c,d,e){function f(f,l,k){z(f)||(k=l,l=f,f=v);var n=za.call(arguments,3),r=w(k)&&!k,s=(r?d:c).defer(),
m=s.promise,q;q=a.defer(function(){try{s.resolve(f.apply(null,n))}catch(a){s.reject(a),e(a)}finally{delete g[m.$$timeoutId]}r||b.$apply()},l);m.$$timeoutId=q;g[q]=s;return m}var g={};f.cancel=function(b){return b&&b.$$timeoutId in g?(g[b.$$timeoutId].reject("canceled"),delete g[b.$$timeoutId],a.defer.cancel(b.$$timeoutId)):!1};return f}]}function Ba(b){Ua&&(X.setAttribute("href",b),b=X.href);X.setAttribute("href",b);return{href:X.href,protocol:X.protocol?X.protocol.replace(/:$/,""):"",host:X.host,
search:X.search?X.search.replace(/^\?/,""):"",hash:X.hash?X.hash.replace(/^#/,""):"",hostname:X.hostname,port:X.port,pathname:"/"===X.pathname.charAt(0)?X.pathname:"/"+X.pathname}}function gd(b){b=L(b)?Ba(b):b;return b.protocol===wd.protocol&&b.host===wd.host}function tf(){this.$get=ra(O)}function xd(b){function a(a){try{return decodeURIComponent(a)}catch(b){return a}}var c=b[0]||{},d={},e="";return function(){var b,g,h,l,k;b=c.cookie||"";if(b!==e)for(e=b,b=e.split("; "),d={},h=0;h<b.length;h++)g=
b[h],l=g.indexOf("="),0<l&&(k=a(g.substring(0,l)),d[k]===t&&(d[k]=a(g.substring(l+1))));return d}}function xf(){this.$get=xd}function Lc(b){function a(c,d){if(H(c)){var e={};m(c,function(b,c){e[c]=a(c,b)});return e}return b.factory(c+"Filter",d)}this.register=a;this.$get=["$injector",function(a){return function(b){return a.get(b+"Filter")}}];a("currency",yd);a("date",zd);a("filter",$f);a("json",ag);a("limitTo",bg);a("lowercase",cg);a("number",Ad);a("orderBy",Bd);a("uppercase",dg)}function $f(){return function(b,
a,c){if(!Ea(b)){if(null==b)return b;throw J("filter")("notarray",b);}var d;switch(ic(a)){case "function":break;case "boolean":case "null":case "number":case "string":d=!0;case "object":a=eg(a,c,d);break;default:return b}return Array.prototype.filter.call(b,a)}}function eg(b,a,c){var d=H(b)&&"$"in b;!0===a?a=ka:z(a)||(a=function(a,b){if(A(a))return!1;if(null===a||null===b)return a===b;if(H(b)||H(a)&&!rc(a))return!1;a=M(""+a);b=M(""+b);return-1!==a.indexOf(b)});return function(e){return d&&!H(e)?La(e,
b.$,a,!1):La(e,b,a,c)}}function La(b,a,c,d,e){var f=ic(b),g=ic(a);if("string"===g&&"!"===a.charAt(0))return!La(b,a.substring(1),c,d);if(G(b))return b.some(function(b){return La(b,a,c,d)});switch(f){case "object":var h;if(d){for(h in b)if("$"!==h.charAt(0)&&La(b[h],a,c,!0))return!0;return e?!1:La(b,a,c,!1)}if("object"===g){for(h in a)if(e=a[h],!z(e)&&!A(e)&&(f="$"===h,!La(f?b:b[h],e,c,f,f)))return!1;return!0}return c(b,a);case "function":return!1;default:return c(b,a)}}function ic(b){return null===
b?"null":typeof b}function yd(b){var a=b.NUMBER_FORMATS;return function(b,d,e){A(d)&&(d=a.CURRENCY_SYM);A(e)&&(e=a.PATTERNS[1].maxFrac);return null==b?b:Cd(b,a.PATTERNS[1],a.GROUP_SEP,a.DECIMAL_SEP,e).replace(/\u00A4/g,d)}}function Ad(b){var a=b.NUMBER_FORMATS;return function(b,d){return null==b?b:Cd(b,a.PATTERNS[0],a.GROUP_SEP,a.DECIMAL_SEP,d)}}function Cd(b,a,c,d,e){if(H(b))return"";var f=0>b;b=Math.abs(b);var g=Infinity===b;if(!g&&!isFinite(b))return"";var h=b+"",l="",k=!1,n=[];g&&(l="\u221e");
if(!g&&-1!==h.indexOf("e")){var r=h.match(/([\d\.]+)e(-?)(\d+)/);r&&"-"==r[2]&&r[3]>e+1?b=0:(l=h,k=!0)}if(g||k)0<e&&1>b&&(l=b.toFixed(e),b=parseFloat(l));else{g=(h.split(Dd)[1]||"").length;A(e)&&(e=Math.min(Math.max(a.minFrac,g),a.maxFrac));b=+(Math.round(+(b.toString()+"e"+e)).toString()+"e"+-e);var g=(""+b).split(Dd),h=g[0],g=g[1]||"",r=0,s=a.lgSize,m=a.gSize;if(h.length>=s+m)for(r=h.length-s,k=0;k<r;k++)0===(r-k)%m&&0!==k&&(l+=c),l+=h.charAt(k);for(k=r;k<h.length;k++)0===(h.length-k)%s&&0!==k&&
(l+=c),l+=h.charAt(k);for(;g.length<e;)g+="0";e&&"0"!==e&&(l+=d+g.substr(0,e))}0===b&&(f=!1);n.push(f?a.negPre:a.posPre,l,f?a.negSuf:a.posSuf);return n.join("")}function Gb(b,a,c){var d="";0>b&&(d="-",b=-b);for(b=""+b;b.length<a;)b="0"+b;c&&(b=b.substr(b.length-a));return d+b}function Y(b,a,c,d){c=c||0;return function(e){e=e["get"+b]();if(0<c||e>-c)e+=c;0===e&&-12==c&&(e=12);return Gb(e,a,d)}}function Hb(b,a){return function(c,d){var e=c["get"+b](),f=rb(a?"SHORT"+b:b);return d[f][e]}}function Ed(b){var a=
(new Date(b,0,1)).getDay();return new Date(b,0,(4>=a?5:12)-a)}function Fd(b){return function(a){var c=Ed(a.getFullYear());a=+new Date(a.getFullYear(),a.getMonth(),a.getDate()+(4-a.getDay()))-+c;a=1+Math.round(a/6048E5);return Gb(a,b)}}function jc(b,a){return 0>=b.getFullYear()?a.ERAS[0]:a.ERAS[1]}function zd(b){function a(a){var b;if(b=a.match(c)){a=new Date(0);var f=0,g=0,h=b[8]?a.setUTCFullYear:a.setFullYear,l=b[8]?a.setUTCHours:a.setHours;b[9]&&(f=W(b[9]+b[10]),g=W(b[9]+b[11]));h.call(a,W(b[1]),
W(b[2])-1,W(b[3]));f=W(b[4]||0)-f;g=W(b[5]||0)-g;h=W(b[6]||0);b=Math.round(1E3*parseFloat("0."+(b[7]||0)));l.call(a,f,g,h,b)}return a}var c=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;return function(c,e,f){var g="",h=[],l,k;e=e||"mediumDate";e=b.DATETIME_FORMATS[e]||e;L(c)&&(c=fg.test(c)?W(c):a(c));V(c)&&(c=new Date(c));if(!aa(c)||!isFinite(c.getTime()))return c;for(;e;)(k=gg.exec(e))?(h=cb(h,k,1),e=h.pop()):(h.push(e),e=null);var n=c.getTimezoneOffset();
f&&(n=xc(f,c.getTimezoneOffset()),c=Pb(c,f,!0));m(h,function(a){l=hg[a];g+=l?l(c,b.DATETIME_FORMATS,n):a.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return g}}function ag(){return function(b,a){A(a)&&(a=2);return db(b,a)}}function bg(){return function(b,a,c){a=Infinity===Math.abs(Number(a))?Number(a):W(a);if(isNaN(a))return b;V(b)&&(b=b.toString());if(!G(b)&&!L(b))return b;c=!c||isNaN(c)?0:W(c);c=0>c&&c>=-b.length?b.length+c:c;return 0<=a?b.slice(c,c+a):0===c?b.slice(a,b.length):b.slice(Math.max(0,
c+a),c)}}function Bd(b){function a(a,c){c=c?-1:1;return a.map(function(a){var d=1,h=Ya;if(z(a))h=a;else if(L(a)){if("+"==a.charAt(0)||"-"==a.charAt(0))d="-"==a.charAt(0)?-1:1,a=a.substring(1);if(""!==a&&(h=b(a),h.constant))var l=h(),h=function(a){return a[l]}}return{get:h,descending:d*c}})}function c(a){switch(typeof a){case "number":case "boolean":case "string":return!0;default:return!1}}return function(b,e,f){if(!Ea(b))return b;G(e)||(e=[e]);0===e.length&&(e=["+"]);var g=a(e,f);b=Array.prototype.map.call(b,
function(a,b){return{value:a,predicateValues:g.map(function(d){var e=d.get(a);d=typeof e;if(null===e)d="string",e="null";else if("string"===d)e=e.toLowerCase();else if("object"===d)a:{if("function"===typeof e.valueOf&&(e=e.valueOf(),c(e)))break a;if(rc(e)&&(e=e.toString(),c(e)))break a;e=b}return{value:e,type:d}})}});b.sort(function(a,b){for(var c=0,d=0,e=g.length;d<e;++d){var c=a.predicateValues[d],f=b.predicateValues[d],m=0;c.type===f.type?c.value!==f.value&&(m=c.value<f.value?-1:1):m=c.type<f.type?
-1:1;if(c=m*g[d].descending)break}return c});return b=b.map(function(a){return a.value})}}function Ma(b){z(b)&&(b={link:b});b.restrict=b.restrict||"AC";return ra(b)}function Gd(b,a,c,d,e){var f=this,g=[],h=f.$$parentForm=b.parent().controller("form")||Ib;f.$error={};f.$$success={};f.$pending=t;f.$name=e(a.name||a.ngForm||"")(c);f.$dirty=!1;f.$pristine=!0;f.$valid=!0;f.$invalid=!1;f.$submitted=!1;h.$addControl(f);f.$rollbackViewValue=function(){m(g,function(a){a.$rollbackViewValue()})};f.$commitViewValue=
function(){m(g,function(a){a.$commitViewValue()})};f.$addControl=function(a){Ra(a.$name,"input");g.push(a);a.$name&&(f[a.$name]=a)};f.$$renameControl=function(a,b){var c=a.$name;f[c]===a&&delete f[c];f[b]=a;a.$name=b};f.$removeControl=function(a){a.$name&&f[a.$name]===a&&delete f[a.$name];m(f.$pending,function(b,c){f.$setValidity(c,null,a)});m(f.$error,function(b,c){f.$setValidity(c,null,a)});m(f.$$success,function(b,c){f.$setValidity(c,null,a)});bb(g,a)};Hd({ctrl:this,$element:b,set:function(a,b,
c){var d=a[b];d?-1===d.indexOf(c)&&d.push(c):a[b]=[c]},unset:function(a,b,c){var d=a[b];d&&(bb(d,c),0===d.length&&delete a[b])},parentForm:h,$animate:d});f.$setDirty=function(){d.removeClass(b,Va);d.addClass(b,Jb);f.$dirty=!0;f.$pristine=!1;h.$setDirty()};f.$setPristine=function(){d.setClass(b,Va,Jb+" ng-submitted");f.$dirty=!1;f.$pristine=!0;f.$submitted=!1;m(g,function(a){a.$setPristine()})};f.$setUntouched=function(){m(g,function(a){a.$setUntouched()})};f.$setSubmitted=function(){d.addClass(b,
"ng-submitted");f.$submitted=!0;h.$setSubmitted()}}function kc(b){b.$formatters.push(function(a){return b.$isEmpty(a)?a:a.toString()})}function kb(b,a,c,d,e,f){var g=M(a[0].type);if(!e.android){var h=!1;a.on("compositionstart",function(a){h=!0});a.on("compositionend",function(){h=!1;l()})}var l=function(b){k&&(f.defer.cancel(k),k=null);if(!h){var e=a.val();b=b&&b.type;"password"===g||c.ngTrim&&"false"===c.ngTrim||(e=R(e));(d.$viewValue!==e||""===e&&d.$$hasNativeValidators)&&d.$setViewValue(e,b)}};
if(e.hasEvent("input"))a.on("input",l);else{var k,n=function(a,b,c){k||(k=f.defer(function(){k=null;b&&b.value===c||l(a)}))};a.on("keydown",function(a){var b=a.keyCode;91===b||15<b&&19>b||37<=b&&40>=b||n(a,this,this.value)});if(e.hasEvent("paste"))a.on("paste cut",n)}a.on("change",l);d.$render=function(){a.val(d.$isEmpty(d.$viewValue)?"":d.$viewValue)}}function Kb(b,a){return function(c,d){var e,f;if(aa(c))return c;if(L(c)){'"'==c.charAt(0)&&'"'==c.charAt(c.length-1)&&(c=c.substring(1,c.length-1));
if(ig.test(c))return new Date(c);b.lastIndex=0;if(e=b.exec(c))return e.shift(),f=d?{yyyy:d.getFullYear(),MM:d.getMonth()+1,dd:d.getDate(),HH:d.getHours(),mm:d.getMinutes(),ss:d.getSeconds(),sss:d.getMilliseconds()/1E3}:{yyyy:1970,MM:1,dd:1,HH:0,mm:0,ss:0,sss:0},m(e,function(b,c){c<a.length&&(f[a[c]]=+b)}),new Date(f.yyyy,f.MM-1,f.dd,f.HH,f.mm,f.ss||0,1E3*f.sss||0)}return NaN}}function lb(b,a,c,d){return function(e,f,g,h,l,k,n){function r(a){return a&&!(a.getTime&&a.getTime()!==a.getTime())}function s(a){return w(a)?
aa(a)?a:c(a):t}Id(e,f,g,h);kb(e,f,g,h,l,k);var m=h&&h.$options&&h.$options.timezone,q;h.$$parserName=b;h.$parsers.push(function(b){return h.$isEmpty(b)?null:a.test(b)?(b=c(b,q),m&&(b=Pb(b,m)),b):t});h.$formatters.push(function(a){if(a&&!aa(a))throw Lb("datefmt",a);if(r(a))return(q=a)&&m&&(q=Pb(q,m,!0)),n("date")(a,d,m);q=null;return""});if(w(g.min)||g.ngMin){var F;h.$validators.min=function(a){return!r(a)||A(F)||c(a)>=F};g.$observe("min",function(a){F=s(a);h.$validate()})}if(w(g.max)||g.ngMax){var u;
h.$validators.max=function(a){return!r(a)||A(u)||c(a)<=u};g.$observe("max",function(a){u=s(a);h.$validate()})}}}function Id(b,a,c,d){(d.$$hasNativeValidators=H(a[0].validity))&&d.$parsers.push(function(b){var c=a.prop("validity")||{};return c.badInput&&!c.typeMismatch?t:b})}function Jd(b,a,c,d,e){if(w(d)){b=b(d);if(!b.constant)throw J("ngModel")("constexpr",c,d);return b(a)}return e}function lc(b,a){b="ngClass"+b;return["$animate",function(c){function d(a,b){var c=[],d=0;a:for(;d<a.length;d++){for(var e=
a[d],n=0;n<b.length;n++)if(e==b[n])continue a;c.push(e)}return c}function e(a){var b=[];return G(a)?(m(a,function(a){b=b.concat(e(a))}),b):L(a)?a.split(" "):H(a)?(m(a,function(a,c){a&&(b=b.concat(c.split(" ")))}),b):a}return{restrict:"AC",link:function(f,g,h){function l(a,b){var c=g.data("$classCounts")||ga(),d=[];m(a,function(a){if(0<b||c[a])c[a]=(c[a]||0)+b,c[a]===+(0<b)&&d.push(a)});g.data("$classCounts",c);return d.join(" ")}function k(b){if(!0===a||f.$index%2===a){var k=e(b||[]);if(!n){var m=
l(k,1);h.$addClass(m)}else if(!ka(b,n)){var q=e(n),m=d(k,q),k=d(q,k),m=l(m,1),k=l(k,-1);m&&m.length&&c.addClass(g,m);k&&k.length&&c.removeClass(g,k)}}n=ia(b)}var n;f.$watch(h[b],k,!0);h.$observe("class",function(a){k(f.$eval(h[b]))});"ngClass"!==b&&f.$watch("$index",function(c,d){var g=c&1;if(g!==(d&1)){var k=e(f.$eval(h[b]));g===a?(g=l(k,1),h.$addClass(g)):(g=l(k,-1),h.$removeClass(g))}})}}}]}function Hd(b){function a(a,b){b&&!f[a]?(k.addClass(e,a),f[a]=!0):!b&&f[a]&&(k.removeClass(e,a),f[a]=!1)}
function c(b,c){b=b?"-"+Bc(b,"-"):"";a(mb+b,!0===c);a(Kd+b,!1===c)}var d=b.ctrl,e=b.$element,f={},g=b.set,h=b.unset,l=b.parentForm,k=b.$animate;f[Kd]=!(f[mb]=e.hasClass(mb));d.$setValidity=function(b,e,f){e===t?(d.$pending||(d.$pending={}),g(d.$pending,b,f)):(d.$pending&&h(d.$pending,b,f),Ld(d.$pending)&&(d.$pending=t));ab(e)?e?(h(d.$error,b,f),g(d.$$success,b,f)):(g(d.$error,b,f),h(d.$$success,b,f)):(h(d.$error,b,f),h(d.$$success,b,f));d.$pending?(a(Md,!0),d.$valid=d.$invalid=t,c("",null)):(a(Md,
!1),d.$valid=Ld(d.$error),d.$invalid=!d.$valid,c("",d.$valid));e=d.$pending&&d.$pending[b]?t:d.$error[b]?!1:d.$$success[b]?!0:null;c(b,e);l.$setValidity(b,e,d)}}function Ld(b){if(b)for(var a in b)if(b.hasOwnProperty(a))return!1;return!0}var jg=/^\/(.+)\/([a-z]*)$/,M=function(b){return L(b)?b.toLowerCase():b},Xa=Object.prototype.hasOwnProperty,rb=function(b){return L(b)?b.toUpperCase():b},Ua,y,la,za=[].slice,Mf=[].splice,kg=[].push,sa=Object.prototype.toString,sc=Object.getPrototypeOf,Fa=J("ng"),ca=
O.angular||(O.angular={}),gb,nb=0;Ua=U.documentMode;v.$inject=[];Ya.$inject=[];var G=Array.isArray,uc=/^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/,R=function(b){return L(b)?b.trim():b},ud=function(b){return b.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08")},fb=function(){if(w(fb.isActive_))return fb.isActive_;var b=!(!U.querySelector("[ng-csp]")&&!U.querySelector("[data-ng-csp]"));if(!b)try{new Function("")}catch(a){b=!0}return fb.isActive_=
b},pb=function(){if(w(pb.name_))return pb.name_;var b,a,c=Oa.length,d,e;for(a=0;a<c;++a)if(d=Oa[a],b=U.querySelector("["+d.replace(":","\\:")+"jq]")){e=b.getAttribute(d+"jq");break}return pb.name_=e},Oa=["ng-","data-ng-","ng:","x-ng-"],be=/[A-Z]/g,Cc=!1,Rb,qa=1,Na=3,fe={full:"1.4.3",major:1,minor:4,dot:3,codeName:"foam-acceleration"};Q.expando="ng339";var ib=Q.cache={},Df=1;Q._data=function(b){return this.cache[b[this.expando]]||{}};var yf=/([\:\-\_]+(.))/g,zf=/^moz([A-Z])/,lg={mouseleave:"mouseout",
mouseenter:"mouseover"},Ub=J("jqLite"),Cf=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,Tb=/<|&#?\w+;/,Af=/<([\w:]+)/,Bf=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,na={option:[1,'<select multiple="multiple">',"</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};na.optgroup=na.option;na.tbody=na.tfoot=na.colgroup=na.caption=na.thead;
na.th=na.td;var Pa=Q.prototype={ready:function(b){function a(){c||(c=!0,b())}var c=!1;"complete"===U.readyState?setTimeout(a):(this.on("DOMContentLoaded",a),Q(O).on("load",a))},toString:function(){var b=[];m(this,function(a){b.push(""+a)});return"["+b.join(", ")+"]"},eq:function(b){return 0<=b?y(this[b]):y(this[this.length+b])},length:0,push:kg,sort:[].sort,splice:[].splice},Ab={};m("multiple selected checked disabled readOnly required open".split(" "),function(b){Ab[M(b)]=b});var Tc={};m("input select option textarea button form details".split(" "),
function(b){Tc[b]=!0});var Uc={ngMinlength:"minlength",ngMaxlength:"maxlength",ngMin:"min",ngMax:"max",ngPattern:"pattern"};m({data:Wb,removeData:ub,hasData:function(b){for(var a in ib[b.ng339])return!0;return!1}},function(b,a){Q[a]=b});m({data:Wb,inheritedData:zb,scope:function(b){return y.data(b,"$scope")||zb(b.parentNode||b,["$isolateScope","$scope"])},isolateScope:function(b){return y.data(b,"$isolateScope")||y.data(b,"$isolateScopeNoTemplate")},controller:Qc,injector:function(b){return zb(b,
"$injector")},removeAttr:function(b,a){b.removeAttribute(a)},hasClass:wb,css:function(b,a,c){a=hb(a);if(w(c))b.style[a]=c;else return b.style[a]},attr:function(b,a,c){var d=b.nodeType;if(d!==Na&&2!==d&&8!==d)if(d=M(a),Ab[d])if(w(c))c?(b[a]=!0,b.setAttribute(a,d)):(b[a]=!1,b.removeAttribute(d));else return b[a]||(b.attributes.getNamedItem(a)||v).specified?d:t;else if(w(c))b.setAttribute(a,c);else if(b.getAttribute)return b=b.getAttribute(a,2),null===b?t:b},prop:function(b,a,c){if(w(c))b[a]=c;else return b[a]},
text:function(){function b(a,b){if(A(b)){var d=a.nodeType;return d===qa||d===Na?a.textContent:""}a.textContent=b}b.$dv="";return b}(),val:function(b,a){if(A(a)){if(b.multiple&&"select"===ta(b)){var c=[];m(b.options,function(a){a.selected&&c.push(a.value||a.text)});return 0===c.length?null:c}return b.value}b.value=a},html:function(b,a){if(A(a))return b.innerHTML;tb(b,!0);b.innerHTML=a},empty:Rc},function(b,a){Q.prototype[a]=function(a,d){var e,f,g=this.length;if(b!==Rc&&(2==b.length&&b!==wb&&b!==Qc?
a:d)===t){if(H(a)){for(e=0;e<g;e++)if(b===Wb)b(this[e],a);else for(f in a)b(this[e],f,a[f]);return this}e=b.$dv;g=e===t?Math.min(g,1):g;for(f=0;f<g;f++){var h=b(this[f],a,d);e=e?e+h:h}return e}for(e=0;e<g;e++)b(this[e],a,d);return this}});m({removeData:ub,on:function a(c,d,e,f){if(w(f))throw Ub("onargs");if(Mc(c)){var g=vb(c,!0);f=g.events;var h=g.handle;h||(h=g.handle=Gf(c,f));for(var g=0<=d.indexOf(" ")?d.split(" "):[d],l=g.length;l--;){d=g[l];var k=f[d];k||(f[d]=[],"mouseenter"===d||"mouseleave"===
d?a(c,lg[d],function(a){var c=a.relatedTarget;c&&(c===this||this.contains(c))||h(a,d)}):"$destroy"!==d&&c.addEventListener(d,h,!1),k=f[d]);k.push(e)}}},off:Pc,one:function(a,c,d){a=y(a);a.on(c,function f(){a.off(c,d);a.off(c,f)});a.on(c,d)},replaceWith:function(a,c){var d,e=a.parentNode;tb(a);m(new Q(c),function(c){d?e.insertBefore(c,d.nextSibling):e.replaceChild(c,a);d=c})},children:function(a){var c=[];m(a.childNodes,function(a){a.nodeType===qa&&c.push(a)});return c},contents:function(a){return a.contentDocument||
a.childNodes||[]},append:function(a,c){var d=a.nodeType;if(d===qa||11===d){c=new Q(c);for(var d=0,e=c.length;d<e;d++)a.appendChild(c[d])}},prepend:function(a,c){if(a.nodeType===qa){var d=a.firstChild;m(new Q(c),function(c){a.insertBefore(c,d)})}},wrap:function(a,c){c=y(c).eq(0).clone()[0];var d=a.parentNode;d&&d.replaceChild(c,a);c.appendChild(a)},remove:Xb,detach:function(a){Xb(a,!0)},after:function(a,c){var d=a,e=a.parentNode;c=new Q(c);for(var f=0,g=c.length;f<g;f++){var h=c[f];e.insertBefore(h,
d.nextSibling);d=h}},addClass:yb,removeClass:xb,toggleClass:function(a,c,d){c&&m(c.split(" "),function(c){var f=d;A(f)&&(f=!wb(a,c));(f?yb:xb)(a,c)})},parent:function(a){return(a=a.parentNode)&&11!==a.nodeType?a:null},next:function(a){return a.nextElementSibling},find:function(a,c){return a.getElementsByTagName?a.getElementsByTagName(c):[]},clone:Vb,triggerHandler:function(a,c,d){var e,f,g=c.type||c,h=vb(a);if(h=(h=h&&h.events)&&h[g])e={preventDefault:function(){this.defaultPrevented=!0},isDefaultPrevented:function(){return!0===
this.defaultPrevented},stopImmediatePropagation:function(){this.immediatePropagationStopped=!0},isImmediatePropagationStopped:function(){return!0===this.immediatePropagationStopped},stopPropagation:v,type:g,target:a},c.type&&(e=P(e,c)),c=ia(h),f=d?[e].concat(d):[e],m(c,function(c){e.isImmediatePropagationStopped()||c.apply(a,f)})}},function(a,c){Q.prototype[c]=function(c,e,f){for(var g,h=0,l=this.length;h<l;h++)A(g)?(g=a(this[h],c,e,f),w(g)&&(g=y(g))):Oc(g,a(this[h],c,e,f));return w(g)?g:this};Q.prototype.bind=
Q.prototype.on;Q.prototype.unbind=Q.prototype.off});Sa.prototype={put:function(a,c){this[Ga(a,this.nextUid)]=c},get:function(a){return this[Ga(a,this.nextUid)]},remove:function(a){var c=this[a=Ga(a,this.nextUid)];delete this[a];return c}};var wf=[function(){this.$get=[function(){return Sa}]}],Wc=/^function\s*[^\(]*\(\s*([^\)]*)\)/m,mg=/,/,ng=/^\s*(_?)(\S+?)\1\s*$/,Vc=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,Ha=J("$injector");eb.$$annotate=function(a,c,d){var e;if("function"===typeof a){if(!(e=a.$inject)){e=
[];if(a.length){if(c)throw L(d)&&d||(d=a.name||Hf(a)),Ha("strictdi",d);c=a.toString().replace(Vc,"");c=c.match(Wc);m(c[1].split(mg),function(a){a.replace(ng,function(a,c,d){e.push(d)})})}a.$inject=e}}else G(a)?(c=a.length-1,Qa(a[c],"fn"),e=a.slice(0,c)):Qa(a,"fn",!0);return e};var Nd=J("$animate"),Ue=function(){this.$get=["$q","$$rAF",function(a,c){function d(){}d.all=v;d.chain=v;d.prototype={end:v,cancel:v,resume:v,pause:v,complete:v,then:function(d,f){return a(function(a){c(function(){a()})}).then(d,
f)}};return d}]},Te=function(){var a=new Sa,c=[];this.$get=["$$AnimateRunner","$rootScope",function(d,e){function f(d,f,l){var k=a.get(d);k||(a.put(d,k={}),c.push(d));f&&m(f.split(" "),function(a){a&&(k[a]=!0)});l&&m(l.split(" "),function(a){a&&(k[a]=!1)});1<c.length||e.$$postDigest(function(){m(c,function(c){var d=a.get(c);if(d){var e=If(c.attr("class")),f="",g="";m(d,function(a,c){a!==!!e[c]&&(a?f+=(f.length?" ":"")+c:g+=(g.length?" ":"")+c)});m(c,function(a){f&&yb(a,f);g&&xb(a,g)});a.remove(c)}});
c.length=0})}return{enabled:v,on:v,off:v,pin:v,push:function(a,c,e,k){k&&k();e=e||{};e.from&&a.css(e.from);e.to&&a.css(e.to);(e.addClass||e.removeClass)&&f(a,e.addClass,e.removeClass);return new d}}}]},Se=["$provide",function(a){var c=this;this.$$registeredAnimations=Object.create(null);this.register=function(d,e){if(d&&"."!==d.charAt(0))throw Nd("notcsel",d);var f=d+"-animation";c.$$registeredAnimations[d.substr(1)]=f;a.factory(f,e)};this.classNameFilter=function(a){if(1===arguments.length&&(this.$$classNameFilter=
a instanceof RegExp?a:null)&&/(\s+|\/)ng-animate(\s+|\/)/.test(this.$$classNameFilter.toString()))throw Nd("nongcls","ng-animate");return this.$$classNameFilter};this.$get=["$$animateQueue",function(a){function c(a,d,e){if(e){var l;a:{for(l=0;l<e.length;l++){var k=e[l];if(1===k.nodeType){l=k;break a}}l=void 0}!l||l.parentNode||l.previousElementSibling||(e=null)}e?e.after(a):d.prepend(a)}return{on:a.on,off:a.off,pin:a.pin,enabled:a.enabled,cancel:function(a){a.end&&a.end()},enter:function(f,g,h,l){g=
g&&y(g);h=h&&y(h);g=g||h.parent();c(f,g,h);return a.push(f,"enter",Ia(l))},move:function(f,g,h,l){g=g&&y(g);h=h&&y(h);g=g||h.parent();c(f,g,h);return a.push(f,"move",Ia(l))},leave:function(c,e){return a.push(c,"leave",Ia(e),function(){c.remove()})},addClass:function(c,e,h){h=Ia(h);h.addClass=jb(h.addclass,e);return a.push(c,"addClass",h)},removeClass:function(c,e,h){h=Ia(h);h.removeClass=jb(h.removeClass,e);return a.push(c,"removeClass",h)},setClass:function(c,e,h,l){l=Ia(l);l.addClass=jb(l.addClass,
e);l.removeClass=jb(l.removeClass,h);return a.push(c,"setClass",l)},animate:function(c,e,h,l,k){k=Ia(k);k.from=k.from?P(k.from,e):e;k.to=k.to?P(k.to,h):h;k.tempClasses=jb(k.tempClasses,l||"ng-inline-animate");return a.push(c,"animate",k)}}}]}],ea=J("$compile");Ec.$inject=["$provide","$$sanitizeUriProvider"];var Zc=/^((?:x|data)[\:\-_])/i,Nf=J("$controller"),Xc=/^(\S+)(\s+as\s+(\w+))?$/,cd="application/json",ac={"Content-Type":cd+";charset=utf-8"},Pf=/^\[|^\{(?!\{)/,Qf={"[":/]$/,"{":/}$/},Of=/^\)\]\}',?\n/,
Ka=ca.$interpolateMinErr=J("$interpolate");Ka.throwNoconcat=function(a){throw Ka("noconcat",a);};Ka.interr=function(a,c){return Ka("interr",a,c.toString())};var og=/^([^\?#]*)(\?([^#]*))?(#(.*))?$/,Tf={http:80,https:443,ftp:21},Cb=J("$location"),pg={$$html5:!1,$$replace:!1,absUrl:Db("$$absUrl"),url:function(a){if(A(a))return this.$$url;var c=og.exec(a);(c[1]||""===a)&&this.path(decodeURIComponent(c[1]));(c[2]||c[1]||""===a)&&this.search(c[3]||"");this.hash(c[5]||"");return this},protocol:Db("$$protocol"),
host:Db("$$host"),port:Db("$$port"),path:kd("$$path",function(a){a=null!==a?a.toString():"";return"/"==a.charAt(0)?a:"/"+a}),search:function(a,c){switch(arguments.length){case 0:return this.$$search;case 1:if(L(a)||V(a))a=a.toString(),this.$$search=zc(a);else if(H(a))a=fa(a,{}),m(a,function(c,e){null==c&&delete a[e]}),this.$$search=a;else throw Cb("isrcharg");break;default:A(c)||null===c?delete this.$$search[a]:this.$$search[a]=c}this.$$compose();return this},hash:kd("$$hash",function(a){return null!==
a?a.toString():""}),replace:function(){this.$$replace=!0;return this}};m([jd,ec,dc],function(a){a.prototype=Object.create(pg);a.prototype.state=function(c){if(!arguments.length)return this.$$state;if(a!==dc||!this.$$html5)throw Cb("nostate");this.$$state=A(c)?null:c;return this}});var da=J("$parse"),Uf=Function.prototype.call,Vf=Function.prototype.apply,Wf=Function.prototype.bind,Mb=ga();m("+ - * / % === !== == != < > <= >= && || ! = |".split(" "),function(a){Mb[a]=!0});var qg={n:"\n",f:"\f",r:"\r",
t:"\t",v:"\v","'":"'",'"':'"'},gc=function(a){this.options=a};gc.prototype={constructor:gc,lex:function(a){this.text=a;this.index=0;for(this.tokens=[];this.index<this.text.length;)if(a=this.text.charAt(this.index),'"'===a||"'"===a)this.readString(a);else if(this.isNumber(a)||"."===a&&this.isNumber(this.peek()))this.readNumber();else if(this.isIdent(a))this.readIdent();else if(this.is(a,"(){}[].,;:?"))this.tokens.push({index:this.index,text:a}),this.index++;else if(this.isWhitespace(a))this.index++;
else{var c=a+this.peek(),d=c+this.peek(2),e=Mb[c],f=Mb[d];Mb[a]||e||f?(a=f?d:e?c:a,this.tokens.push({index:this.index,text:a,operator:!0}),this.index+=a.length):this.throwError("Unexpected next character ",this.index,this.index+1)}return this.tokens},is:function(a,c){return-1!==c.indexOf(a)},peek:function(a){a=a||1;return this.index+a<this.text.length?this.text.charAt(this.index+a):!1},isNumber:function(a){return"0"<=a&&"9">=a&&"string"===typeof a},isWhitespace:function(a){return" "===a||"\r"===a||
"\t"===a||"\n"===a||"\v"===a||"\u00a0"===a},isIdent:function(a){return"a"<=a&&"z">=a||"A"<=a&&"Z">=a||"_"===a||"$"===a},isExpOperator:function(a){return"-"===a||"+"===a||this.isNumber(a)},throwError:function(a,c,d){d=d||this.index;c=w(c)?"s "+c+"-"+this.index+" ["+this.text.substring(c,d)+"]":" "+d;throw da("lexerr",a,c,this.text);},readNumber:function(){for(var a="",c=this.index;this.index<this.text.length;){var d=M(this.text.charAt(this.index));if("."==d||this.isNumber(d))a+=d;else{var e=this.peek();
if("e"==d&&this.isExpOperator(e))a+=d;else if(this.isExpOperator(d)&&e&&this.isNumber(e)&&"e"==a.charAt(a.length-1))a+=d;else if(!this.isExpOperator(d)||e&&this.isNumber(e)||"e"!=a.charAt(a.length-1))break;else this.throwError("Invalid exponent")}this.index++}this.tokens.push({index:c,text:a,constant:!0,value:Number(a)})},readIdent:function(){for(var a=this.index;this.index<this.text.length;){var c=this.text.charAt(this.index);if(!this.isIdent(c)&&!this.isNumber(c))break;this.index++}this.tokens.push({index:a,
text:this.text.slice(a,this.index),identifier:!0})},readString:function(a){var c=this.index;this.index++;for(var d="",e=a,f=!1;this.index<this.text.length;){var g=this.text.charAt(this.index),e=e+g;if(f)"u"===g?(f=this.text.substring(this.index+1,this.index+5),f.match(/[\da-f]{4}/i)||this.throwError("Invalid unicode escape [\\u"+f+"]"),this.index+=4,d+=String.fromCharCode(parseInt(f,16))):d+=qg[g]||g,f=!1;else if("\\"===g)f=!0;else{if(g===a){this.index++;this.tokens.push({index:c,text:e,constant:!0,
value:d});return}d+=g}this.index++}this.throwError("Unterminated quote",c)}};var q=function(a,c){this.lexer=a;this.options=c};q.Program="Program";q.ExpressionStatement="ExpressionStatement";q.AssignmentExpression="AssignmentExpression";q.ConditionalExpression="ConditionalExpression";q.LogicalExpression="LogicalExpression";q.BinaryExpression="BinaryExpression";q.UnaryExpression="UnaryExpression";q.CallExpression="CallExpression";q.MemberExpression="MemberExpression";q.Identifier="Identifier";q.Literal=
"Literal";q.ArrayExpression="ArrayExpression";q.Property="Property";q.ObjectExpression="ObjectExpression";q.ThisExpression="ThisExpression";q.NGValueParameter="NGValueParameter";q.prototype={ast:function(a){this.text=a;this.tokens=this.lexer.lex(a);a=this.program();0!==this.tokens.length&&this.throwError("is an unexpected token",this.tokens[0]);return a},program:function(){for(var a=[];;)if(0<this.tokens.length&&!this.peek("}",")",";","]")&&a.push(this.expressionStatement()),!this.expect(";"))return{type:q.Program,
body:a}},expressionStatement:function(){return{type:q.ExpressionStatement,expression:this.filterChain()}},filterChain:function(){for(var a=this.expression();this.expect("|");)a=this.filter(a);return a},expression:function(){return this.assignment()},assignment:function(){var a=this.ternary();this.expect("=")&&(a={type:q.AssignmentExpression,left:a,right:this.assignment(),operator:"="});return a},ternary:function(){var a=this.logicalOR(),c,d;return this.expect("?")&&(c=this.expression(),this.consume(":"))?
(d=this.expression(),{type:q.ConditionalExpression,test:a,alternate:c,consequent:d}):a},logicalOR:function(){for(var a=this.logicalAND();this.expect("||");)a={type:q.LogicalExpression,operator:"||",left:a,right:this.logicalAND()};return a},logicalAND:function(){for(var a=this.equality();this.expect("&&");)a={type:q.LogicalExpression,operator:"&&",left:a,right:this.equality()};return a},equality:function(){for(var a=this.relational(),c;c=this.expect("==","!=","===","!==");)a={type:q.BinaryExpression,
operator:c.text,left:a,right:this.relational()};return a},relational:function(){for(var a=this.additive(),c;c=this.expect("<",">","<=",">=");)a={type:q.BinaryExpression,operator:c.text,left:a,right:this.additive()};return a},additive:function(){for(var a=this.multiplicative(),c;c=this.expect("+","-");)a={type:q.BinaryExpression,operator:c.text,left:a,right:this.multiplicative()};return a},multiplicative:function(){for(var a=this.unary(),c;c=this.expect("*","/","%");)a={type:q.BinaryExpression,operator:c.text,
left:a,right:this.unary()};return a},unary:function(){var a;return(a=this.expect("+","-","!"))?{type:q.UnaryExpression,operator:a.text,prefix:!0,argument:this.unary()}:this.primary()},primary:function(){var a;this.expect("(")?(a=this.filterChain(),this.consume(")")):this.expect("[")?a=this.arrayDeclaration():this.expect("{")?a=this.object():this.constants.hasOwnProperty(this.peek().text)?a=fa(this.constants[this.consume().text]):this.peek().identifier?a=this.identifier():this.peek().constant?a=this.constant():
this.throwError("not a primary expression",this.peek());for(var c;c=this.expect("(","[",".");)"("===c.text?(a={type:q.CallExpression,callee:a,arguments:this.parseArguments()},this.consume(")")):"["===c.text?(a={type:q.MemberExpression,object:a,property:this.expression(),computed:!0},this.consume("]")):"."===c.text?a={type:q.MemberExpression,object:a,property:this.identifier(),computed:!1}:this.throwError("IMPOSSIBLE");return a},filter:function(a){a=[a];for(var c={type:q.CallExpression,callee:this.identifier(),
arguments:a,filter:!0};this.expect(":");)a.push(this.expression());return c},parseArguments:function(){var a=[];if(")"!==this.peekToken().text){do a.push(this.expression());while(this.expect(","))}return a},identifier:function(){var a=this.consume();a.identifier||this.throwError("is not a valid identifier",a);return{type:q.Identifier,name:a.text}},constant:function(){return{type:q.Literal,value:this.consume().value}},arrayDeclaration:function(){var a=[];if("]"!==this.peekToken().text){do{if(this.peek("]"))break;
a.push(this.expression())}while(this.expect(","))}this.consume("]");return{type:q.ArrayExpression,elements:a}},object:function(){var a=[],c;if("}"!==this.peekToken().text){do{if(this.peek("}"))break;c={type:q.Property,kind:"init"};this.peek().constant?c.key=this.constant():this.peek().identifier?c.key=this.identifier():this.throwError("invalid key",this.peek());this.consume(":");c.value=this.expression();a.push(c)}while(this.expect(","))}this.consume("}");return{type:q.ObjectExpression,properties:a}},
throwError:function(a,c){throw da("syntax",c.text,a,c.index+1,this.text,this.text.substring(c.index));},consume:function(a){if(0===this.tokens.length)throw da("ueoe",this.text);var c=this.expect(a);c||this.throwError("is unexpected, expecting ["+a+"]",this.peek());return c},peekToken:function(){if(0===this.tokens.length)throw da("ueoe",this.text);return this.tokens[0]},peek:function(a,c,d,e){return this.peekAhead(0,a,c,d,e)},peekAhead:function(a,c,d,e,f){if(this.tokens.length>a){a=this.tokens[a];
var g=a.text;if(g===c||g===d||g===e||g===f||!(c||d||e||f))return a}return!1},expect:function(a,c,d,e){return(a=this.peek(a,c,d,e))?(this.tokens.shift(),a):!1},constants:{"true":{type:q.Literal,value:!0},"false":{type:q.Literal,value:!1},"null":{type:q.Literal,value:null},undefined:{type:q.Literal,value:t},"this":{type:q.ThisExpression}}};rd.prototype={compile:function(a,c){var d=this,e=this.astBuilder.ast(a);this.state={nextId:0,filters:{},expensiveChecks:c,fn:{vars:[],body:[],own:{}},assign:{vars:[],
body:[],own:{}},inputs:[]};T(e,d.$filter);var f="",g;this.stage="assign";if(g=pd(e))this.state.computing="assign",f=this.nextId(),this.recurse(g,f),f="fn.assign="+this.generateFunction("assign","s,v,l");g=nd(e.body);d.stage="inputs";m(g,function(a,c){var e="fn"+c;d.state[e]={vars:[],body:[],own:{}};d.state.computing=e;var f=d.nextId();d.recurse(a,f);d.return_(f);d.state.inputs.push(e);a.watchId=c});this.state.computing="fn";this.stage="main";this.recurse(e);f='"'+this.USE+" "+this.STRICT+'";\n'+this.filterPrefix()+
"var fn="+this.generateFunction("fn","s,l,a,i")+f+this.watchFns()+"return fn;";f=(new Function("$filter","ensureSafeMemberName","ensureSafeObject","ensureSafeFunction","ifDefined","plus","text",f))(this.$filter,Ca,oa,ld,Xf,md,a);this.state=this.stage=t;f.literal=qd(e);f.constant=e.constant;return f},USE:"use",STRICT:"strict",watchFns:function(){var a=[],c=this.state.inputs,d=this;m(c,function(c){a.push("var "+c+"="+d.generateFunction(c,"s"))});c.length&&a.push("fn.inputs=["+c.join(",")+"];");return a.join("")},
generateFunction:function(a,c){return"function("+c+"){"+this.varsPrefix(a)+this.body(a)+"};"},filterPrefix:function(){var a=[],c=this;m(this.state.filters,function(d,e){a.push(d+"=$filter("+c.escape(e)+")")});return a.length?"var "+a.join(",")+";":""},varsPrefix:function(a){return this.state[a].vars.length?"var "+this.state[a].vars.join(",")+";":""},body:function(a){return this.state[a].body.join("")},recurse:function(a,c,d,e,f,g){var h,l,k=this,n,r;e=e||v;if(!g&&w(a.watchId))c=c||this.nextId(),this.if_("i",
this.lazyAssign(c,this.computedMember("i",a.watchId)),this.lazyRecurse(a,c,d,e,f,!0));else switch(a.type){case q.Program:m(a.body,function(c,d){k.recurse(c.expression,t,t,function(a){l=a});d!==a.body.length-1?k.current().body.push(l,";"):k.return_(l)});break;case q.Literal:r=this.escape(a.value);this.assign(c,r);e(r);break;case q.UnaryExpression:this.recurse(a.argument,t,t,function(a){l=a});r=a.operator+"("+this.ifDefined(l,0)+")";this.assign(c,r);e(r);break;case q.BinaryExpression:this.recurse(a.left,
t,t,function(a){h=a});this.recurse(a.right,t,t,function(a){l=a});r="+"===a.operator?this.plus(h,l):"-"===a.operator?this.ifDefined(h,0)+a.operator+this.ifDefined(l,0):"("+h+")"+a.operator+"("+l+")";this.assign(c,r);e(r);break;case q.LogicalExpression:c=c||this.nextId();k.recurse(a.left,c);k.if_("&&"===a.operator?c:k.not(c),k.lazyRecurse(a.right,c));e(c);break;case q.ConditionalExpression:c=c||this.nextId();k.recurse(a.test,c);k.if_(c,k.lazyRecurse(a.alternate,c),k.lazyRecurse(a.consequent,c));e(c);
break;case q.Identifier:c=c||this.nextId();d&&(d.context="inputs"===k.stage?"s":this.assign(this.nextId(),this.getHasOwnProperty("l",a.name)+"?l:s"),d.computed=!1,d.name=a.name);Ca(a.name);k.if_("inputs"===k.stage||k.not(k.getHasOwnProperty("l",a.name)),function(){k.if_("inputs"===k.stage||"s",function(){f&&1!==f&&k.if_(k.not(k.nonComputedMember("s",a.name)),k.lazyAssign(k.nonComputedMember("s",a.name),"{}"));k.assign(c,k.nonComputedMember("s",a.name))})},c&&k.lazyAssign(c,k.nonComputedMember("l",
a.name)));(k.state.expensiveChecks||Fb(a.name))&&k.addEnsureSafeObject(c);e(c);break;case q.MemberExpression:h=d&&(d.context=this.nextId())||this.nextId();c=c||this.nextId();k.recurse(a.object,h,t,function(){k.if_(k.notNull(h),function(){if(a.computed)l=k.nextId(),k.recurse(a.property,l),k.addEnsureSafeMemberName(l),f&&1!==f&&k.if_(k.not(k.computedMember(h,l)),k.lazyAssign(k.computedMember(h,l),"{}")),r=k.ensureSafeObject(k.computedMember(h,l)),k.assign(c,r),d&&(d.computed=!0,d.name=l);else{Ca(a.property.name);
f&&1!==f&&k.if_(k.not(k.nonComputedMember(h,a.property.name)),k.lazyAssign(k.nonComputedMember(h,a.property.name),"{}"));r=k.nonComputedMember(h,a.property.name);if(k.state.expensiveChecks||Fb(a.property.name))r=k.ensureSafeObject(r);k.assign(c,r);d&&(d.computed=!1,d.name=a.property.name)}},function(){k.assign(c,"undefined")});e(c)},!!f);break;case q.CallExpression:c=c||this.nextId();a.filter?(l=k.filter(a.callee.name),n=[],m(a.arguments,function(a){var c=k.nextId();k.recurse(a,c);n.push(c)}),r=l+
"("+n.join(",")+")",k.assign(c,r),e(c)):(l=k.nextId(),h={},n=[],k.recurse(a.callee,l,h,function(){k.if_(k.notNull(l),function(){k.addEnsureSafeFunction(l);m(a.arguments,function(a){k.recurse(a,k.nextId(),t,function(a){n.push(k.ensureSafeObject(a))})});h.name?(k.state.expensiveChecks||k.addEnsureSafeObject(h.context),r=k.member(h.context,h.name,h.computed)+"("+n.join(",")+")"):r=l+"("+n.join(",")+")";r=k.ensureSafeObject(r);k.assign(c,r)},function(){k.assign(c,"undefined")});e(c)}));break;case q.AssignmentExpression:l=
this.nextId();h={};if(!od(a.left))throw da("lval");this.recurse(a.left,t,h,function(){k.if_(k.notNull(h.context),function(){k.recurse(a.right,l);k.addEnsureSafeObject(k.member(h.context,h.name,h.computed));r=k.member(h.context,h.name,h.computed)+a.operator+l;k.assign(c,r);e(c||r)})},1);break;case q.ArrayExpression:n=[];m(a.elements,function(a){k.recurse(a,k.nextId(),t,function(a){n.push(a)})});r="["+n.join(",")+"]";this.assign(c,r);e(r);break;case q.ObjectExpression:n=[];m(a.properties,function(a){k.recurse(a.value,
k.nextId(),t,function(c){n.push(k.escape(a.key.type===q.Identifier?a.key.name:""+a.key.value)+":"+c)})});r="{"+n.join(",")+"}";this.assign(c,r);e(r);break;case q.ThisExpression:this.assign(c,"s");e("s");break;case q.NGValueParameter:this.assign(c,"v"),e("v")}},getHasOwnProperty:function(a,c){var d=a+"."+c,e=this.current().own;e.hasOwnProperty(d)||(e[d]=this.nextId(!1,a+"&&("+this.escape(c)+" in "+a+")"));return e[d]},assign:function(a,c){if(a)return this.current().body.push(a,"=",c,";"),a},filter:function(a){this.state.filters.hasOwnProperty(a)||
(this.state.filters[a]=this.nextId(!0));return this.state.filters[a]},ifDefined:function(a,c){return"ifDefined("+a+","+this.escape(c)+")"},plus:function(a,c){return"plus("+a+","+c+")"},return_:function(a){this.current().body.push("return ",a,";")},if_:function(a,c,d){if(!0===a)c();else{var e=this.current().body;e.push("if(",a,"){");c();e.push("}");d&&(e.push("else{"),d(),e.push("}"))}},not:function(a){return"!("+a+")"},notNull:function(a){return a+"!=null"},nonComputedMember:function(a,c){return a+
"."+c},computedMember:function(a,c){return a+"["+c+"]"},member:function(a,c,d){return d?this.computedMember(a,c):this.nonComputedMember(a,c)},addEnsureSafeObject:function(a){this.current().body.push(this.ensureSafeObject(a),";")},addEnsureSafeMemberName:function(a){this.current().body.push(this.ensureSafeMemberName(a),";")},addEnsureSafeFunction:function(a){this.current().body.push(this.ensureSafeFunction(a),";")},ensureSafeObject:function(a){return"ensureSafeObject("+a+",text)"},ensureSafeMemberName:function(a){return"ensureSafeMemberName("+
a+",text)"},ensureSafeFunction:function(a){return"ensureSafeFunction("+a+",text)"},lazyRecurse:function(a,c,d,e,f,g){var h=this;return function(){h.recurse(a,c,d,e,f,g)}},lazyAssign:function(a,c){var d=this;return function(){d.assign(a,c)}},stringEscapeRegex:/[^ a-zA-Z0-9]/g,stringEscapeFn:function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)},escape:function(a){if(L(a))return"'"+a.replace(this.stringEscapeRegex,this.stringEscapeFn)+"'";if(V(a))return a.toString();if(!0===a)return"true";
if(!1===a)return"false";if(null===a)return"null";if("undefined"===typeof a)return"undefined";throw da("esc");},nextId:function(a,c){var d="v"+this.state.nextId++;a||this.current().vars.push(d+(c?"="+c:""));return d},current:function(){return this.state[this.state.computing]}};sd.prototype={compile:function(a,c){var d=this,e=this.astBuilder.ast(a);this.expression=a;this.expensiveChecks=c;T(e,d.$filter);var f,g;if(f=pd(e))g=this.recurse(f);f=nd(e.body);var h;f&&(h=[],m(f,function(a,c){var e=d.recurse(a);
a.input=e;h.push(e);a.watchId=c}));var l=[];m(e.body,function(a){l.push(d.recurse(a.expression))});f=0===e.body.length?function(){}:1===e.body.length?l[0]:function(a,c){var d;m(l,function(e){d=e(a,c)});return d};g&&(f.assign=function(a,c,d){return g(a,d,c)});h&&(f.inputs=h);f.literal=qd(e);f.constant=e.constant;return f},recurse:function(a,c,d){var e,f,g=this,h;if(a.input)return this.inputs(a.input,a.watchId);switch(a.type){case q.Literal:return this.value(a.value,c);case q.UnaryExpression:return f=
this.recurse(a.argument),this["unary"+a.operator](f,c);case q.BinaryExpression:return e=this.recurse(a.left),f=this.recurse(a.right),this["binary"+a.operator](e,f,c);case q.LogicalExpression:return e=this.recurse(a.left),f=this.recurse(a.right),this["binary"+a.operator](e,f,c);case q.ConditionalExpression:return this["ternary?:"](this.recurse(a.test),this.recurse(a.alternate),this.recurse(a.consequent),c);case q.Identifier:return Ca(a.name,g.expression),g.identifier(a.name,g.expensiveChecks||Fb(a.name),
c,d,g.expression);case q.MemberExpression:return e=this.recurse(a.object,!1,!!d),a.computed||(Ca(a.property.name,g.expression),f=a.property.name),a.computed&&(f=this.recurse(a.property)),a.computed?this.computedMember(e,f,c,d,g.expression):this.nonComputedMember(e,f,g.expensiveChecks,c,d,g.expression);case q.CallExpression:return h=[],m(a.arguments,function(a){h.push(g.recurse(a))}),a.filter&&(f=this.$filter(a.callee.name)),a.filter||(f=this.recurse(a.callee,!0)),a.filter?function(a,d,e,g){for(var m=
[],q=0;q<h.length;++q)m.push(h[q](a,d,e,g));a=f.apply(t,m,g);return c?{context:t,name:t,value:a}:a}:function(a,d,e,r){var m=f(a,d,e,r),q;if(null!=m.value){oa(m.context,g.expression);ld(m.value,g.expression);q=[];for(var t=0;t<h.length;++t)q.push(oa(h[t](a,d,e,r),g.expression));q=oa(m.value.apply(m.context,q),g.expression)}return c?{value:q}:q};case q.AssignmentExpression:return e=this.recurse(a.left,!0,1),f=this.recurse(a.right),function(a,d,h,r){var m=e(a,d,h,r);a=f(a,d,h,r);oa(m.value,g.expression);
m.context[m.name]=a;return c?{value:a}:a};case q.ArrayExpression:return h=[],m(a.elements,function(a){h.push(g.recurse(a))}),function(a,d,e,f){for(var g=[],m=0;m<h.length;++m)g.push(h[m](a,d,e,f));return c?{value:g}:g};case q.ObjectExpression:return h=[],m(a.properties,function(a){h.push({key:a.key.type===q.Identifier?a.key.name:""+a.key.value,value:g.recurse(a.value)})}),function(a,d,e,f){for(var g={},m=0;m<h.length;++m)g[h[m].key]=h[m].value(a,d,e,f);return c?{value:g}:g};case q.ThisExpression:return function(a){return c?
{value:a}:a};case q.NGValueParameter:return function(a,d,e,f){return c?{value:e}:e}}},"unary+":function(a,c){return function(d,e,f,g){d=a(d,e,f,g);d=w(d)?+d:0;return c?{value:d}:d}},"unary-":function(a,c){return function(d,e,f,g){d=a(d,e,f,g);d=w(d)?-d:0;return c?{value:d}:d}},"unary!":function(a,c){return function(d,e,f,g){d=!a(d,e,f,g);return c?{value:d}:d}},"binary+":function(a,c,d){return function(e,f,g,h){var l=a(e,f,g,h);e=c(e,f,g,h);l=md(l,e);return d?{value:l}:l}},"binary-":function(a,c,d){return function(e,
f,g,h){var l=a(e,f,g,h);e=c(e,f,g,h);l=(w(l)?l:0)-(w(e)?e:0);return d?{value:l}:l}},"binary*":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)*c(e,f,g,h);return d?{value:e}:e}},"binary/":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)/c(e,f,g,h);return d?{value:e}:e}},"binary%":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)%c(e,f,g,h);return d?{value:e}:e}},"binary===":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)===c(e,f,g,h);return d?{value:e}:e}},"binary!==":function(a,
c,d){return function(e,f,g,h){e=a(e,f,g,h)!==c(e,f,g,h);return d?{value:e}:e}},"binary==":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)==c(e,f,g,h);return d?{value:e}:e}},"binary!=":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)!=c(e,f,g,h);return d?{value:e}:e}},"binary<":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)<c(e,f,g,h);return d?{value:e}:e}},"binary>":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)>c(e,f,g,h);return d?{value:e}:e}},"binary<=":function(a,c,d){return function(e,
f,g,h){e=a(e,f,g,h)<=c(e,f,g,h);return d?{value:e}:e}},"binary>=":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)>=c(e,f,g,h);return d?{value:e}:e}},"binary&&":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)&&c(e,f,g,h);return d?{value:e}:e}},"binary||":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)||c(e,f,g,h);return d?{value:e}:e}},"ternary?:":function(a,c,d,e){return function(f,g,h,l){f=a(f,g,h,l)?c(f,g,h,l):d(f,g,h,l);return e?{value:f}:f}},value:function(a,c){return function(){return c?
{context:t,name:t,value:a}:a}},identifier:function(a,c,d,e,f){return function(g,h,l,k){g=h&&a in h?h:g;e&&1!==e&&g&&!g[a]&&(g[a]={});h=g?g[a]:t;c&&oa(h,f);return d?{context:g,name:a,value:h}:h}},computedMember:function(a,c,d,e,f){return function(g,h,l,k){var n=a(g,h,l,k),m,s;null!=n&&(m=c(g,h,l,k),Ca(m,f),e&&1!==e&&n&&!n[m]&&(n[m]={}),s=n[m],oa(s,f));return d?{context:n,name:m,value:s}:s}},nonComputedMember:function(a,c,d,e,f,g){return function(h,l,k,n){h=a(h,l,k,n);f&&1!==f&&h&&!h[c]&&(h[c]={});
l=null!=h?h[c]:t;(d||Fb(c))&&oa(l,g);return e?{context:h,name:c,value:l}:l}},inputs:function(a,c){return function(d,e,f,g){return g?g[c]:a(d,e,f)}}};var hc=function(a,c,d){this.lexer=a;this.$filter=c;this.options=d;this.ast=new q(this.lexer);this.astCompiler=d.csp?new sd(this.ast,c):new rd(this.ast,c)};hc.prototype={constructor:hc,parse:function(a){return this.astCompiler.compile(a,this.options.expensiveChecks)}};ga();ga();var Yf=Object.prototype.valueOf,Da=J("$sce"),pa={HTML:"html",CSS:"css",URL:"url",
RESOURCE_URL:"resourceUrl",JS:"js"},ea=J("$compile"),X=U.createElement("a"),wd=Ba(O.location.href);xd.$inject=["$document"];Lc.$inject=["$provide"];yd.$inject=["$locale"];Ad.$inject=["$locale"];var Dd=".",hg={yyyy:Y("FullYear",4),yy:Y("FullYear",2,0,!0),y:Y("FullYear",1),MMMM:Hb("Month"),MMM:Hb("Month",!0),MM:Y("Month",2,1),M:Y("Month",1,1),dd:Y("Date",2),d:Y("Date",1),HH:Y("Hours",2),H:Y("Hours",1),hh:Y("Hours",2,-12),h:Y("Hours",1,-12),mm:Y("Minutes",2),m:Y("Minutes",1),ss:Y("Seconds",2),s:Y("Seconds",
1),sss:Y("Milliseconds",3),EEEE:Hb("Day"),EEE:Hb("Day",!0),a:function(a,c){return 12>a.getHours()?c.AMPMS[0]:c.AMPMS[1]},Z:function(a,c,d){a=-1*d;return a=(0<=a?"+":"")+(Gb(Math[0<a?"floor":"ceil"](a/60),2)+Gb(Math.abs(a%60),2))},ww:Fd(2),w:Fd(1),G:jc,GG:jc,GGG:jc,GGGG:function(a,c){return 0>=a.getFullYear()?c.ERANAMES[0]:c.ERANAMES[1]}},gg=/((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,fg=/^\-?\d+$/;zd.$inject=["$locale"];var cg=ra(M),dg=ra(rb);Bd.$inject=
["$parse"];var ie=ra({restrict:"E",compile:function(a,c){if(!c.href&&!c.xlinkHref)return function(a,c){if("a"===c[0].nodeName.toLowerCase()){var f="[object SVGAnimatedString]"===sa.call(c.prop("href"))?"xlink:href":"href";c.on("click",function(a){c.attr(f)||a.preventDefault()})}}}}),sb={};m(Ab,function(a,c){function d(a,d,f){a.$watch(f[e],function(a){f.$set(c,!!a)})}if("multiple"!=a){var e=wa("ng-"+c),f=d;"checked"===a&&(f=function(a,c,f){f.ngModel!==f[e]&&d(a,c,f)});sb[e]=function(){return{restrict:"A",
priority:100,link:f}}}});m(Uc,function(a,c){sb[c]=function(){return{priority:100,link:function(a,e,f){if("ngPattern"===c&&"/"==f.ngPattern.charAt(0)&&(e=f.ngPattern.match(jg))){f.$set("ngPattern",new RegExp(e[1],e[2]));return}a.$watch(f[c],function(a){f.$set(c,a)})}}}});m(["src","srcset","href"],function(a){var c=wa("ng-"+a);sb[c]=function(){return{priority:99,link:function(d,e,f){var g=a,h=a;"href"===a&&"[object SVGAnimatedString]"===sa.call(e.prop("href"))&&(h="xlinkHref",f.$attr[h]="xlink:href",
g=null);f.$observe(c,function(c){c?(f.$set(h,c),Ua&&g&&e.prop(g,f[h])):"href"===a&&f.$set(h,null)})}}}});var Ib={$addControl:v,$$renameControl:function(a,c){a.$name=c},$removeControl:v,$setValidity:v,$setDirty:v,$setPristine:v,$setSubmitted:v};Gd.$inject=["$element","$attrs","$scope","$animate","$interpolate"];var Od=function(a){return["$timeout",function(c){return{name:"form",restrict:a?"EAC":"E",controller:Gd,compile:function(d,e){d.addClass(Va).addClass(mb);var f=e.name?"name":a&&e.ngForm?"ngForm":
!1;return{pre:function(a,d,e,k){if(!("action"in e)){var n=function(c){a.$apply(function(){k.$commitViewValue();k.$setSubmitted()});c.preventDefault()};d[0].addEventListener("submit",n,!1);d.on("$destroy",function(){c(function(){d[0].removeEventListener("submit",n,!1)},0,!1)})}var m=k.$$parentForm;f&&(Eb(a,k.$name,k,k.$name),e.$observe(f,function(c){k.$name!==c&&(Eb(a,k.$name,t,k.$name),m.$$renameControl(k,c),Eb(a,k.$name,k,k.$name))}));d.on("$destroy",function(){m.$removeControl(k);f&&Eb(a,e[f],t,
k.$name);P(k,Ib)})}}}}}]},je=Od(),we=Od(!0),ig=/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/,rg=/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,sg=/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i,tg=/^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/,Pd=/^(\d{4})-(\d{2})-(\d{2})$/,Qd=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,mc=/^(\d{4})-W(\d\d)$/,Rd=/^(\d{4})-(\d\d)$/,
Sd=/^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,Td={text:function(a,c,d,e,f,g){kb(a,c,d,e,f,g);kc(e)},date:lb("date",Pd,Kb(Pd,["yyyy","MM","dd"]),"yyyy-MM-dd"),"datetime-local":lb("datetimelocal",Qd,Kb(Qd,"yyyy MM dd HH mm ss sss".split(" ")),"yyyy-MM-ddTHH:mm:ss.sss"),time:lb("time",Sd,Kb(Sd,["HH","mm","ss","sss"]),"HH:mm:ss.sss"),week:lb("week",mc,function(a,c){if(aa(a))return a;if(L(a)){mc.lastIndex=0;var d=mc.exec(a);if(d){var e=+d[1],f=+d[2],g=d=0,h=0,l=0,k=Ed(e),f=7*(f-1);c&&(d=c.getHours(),g=
c.getMinutes(),h=c.getSeconds(),l=c.getMilliseconds());return new Date(e,0,k.getDate()+f,d,g,h,l)}}return NaN},"yyyy-Www"),month:lb("month",Rd,Kb(Rd,["yyyy","MM"]),"yyyy-MM"),number:function(a,c,d,e,f,g){Id(a,c,d,e);kb(a,c,d,e,f,g);e.$$parserName="number";e.$parsers.push(function(a){return e.$isEmpty(a)?null:tg.test(a)?parseFloat(a):t});e.$formatters.push(function(a){if(!e.$isEmpty(a)){if(!V(a))throw Lb("numfmt",a);a=a.toString()}return a});if(w(d.min)||d.ngMin){var h;e.$validators.min=function(a){return e.$isEmpty(a)||
A(h)||a>=h};d.$observe("min",function(a){w(a)&&!V(a)&&(a=parseFloat(a,10));h=V(a)&&!isNaN(a)?a:t;e.$validate()})}if(w(d.max)||d.ngMax){var l;e.$validators.max=function(a){return e.$isEmpty(a)||A(l)||a<=l};d.$observe("max",function(a){w(a)&&!V(a)&&(a=parseFloat(a,10));l=V(a)&&!isNaN(a)?a:t;e.$validate()})}},url:function(a,c,d,e,f,g){kb(a,c,d,e,f,g);kc(e);e.$$parserName="url";e.$validators.url=function(a,c){var d=a||c;return e.$isEmpty(d)||rg.test(d)}},email:function(a,c,d,e,f,g){kb(a,c,d,e,f,g);kc(e);
e.$$parserName="email";e.$validators.email=function(a,c){var d=a||c;return e.$isEmpty(d)||sg.test(d)}},radio:function(a,c,d,e){A(d.name)&&c.attr("name",++nb);c.on("click",function(a){c[0].checked&&e.$setViewValue(d.value,a&&a.type)});e.$render=function(){c[0].checked=d.value==e.$viewValue};d.$observe("value",e.$render)},checkbox:function(a,c,d,e,f,g,h,l){var k=Jd(l,a,"ngTrueValue",d.ngTrueValue,!0),n=Jd(l,a,"ngFalseValue",d.ngFalseValue,!1);c.on("click",function(a){e.$setViewValue(c[0].checked,a&&
a.type)});e.$render=function(){c[0].checked=e.$viewValue};e.$isEmpty=function(a){return!1===a};e.$formatters.push(function(a){return ka(a,k)});e.$parsers.push(function(a){return a?k:n})},hidden:v,button:v,submit:v,reset:v,file:v},Fc=["$browser","$sniffer","$filter","$parse",function(a,c,d,e){return{restrict:"E",require:["?ngModel"],link:{pre:function(f,g,h,l){l[0]&&(Td[M(h.type)]||Td.text)(f,g,h,l[0],c,a,d,e)}}}}],ug=/^(true|false|\d+)$/,Oe=function(){return{restrict:"A",priority:100,compile:function(a,
c){return ug.test(c.ngValue)?function(a,c,f){f.$set("value",a.$eval(f.ngValue))}:function(a,c,f){a.$watch(f.ngValue,function(a){f.$set("value",a)})}}}},oe=["$compile",function(a){return{restrict:"AC",compile:function(c){a.$$addBindingClass(c);return function(c,e,f){a.$$addBindingInfo(e,f.ngBind);e=e[0];c.$watch(f.ngBind,function(a){e.textContent=a===t?"":a})}}}}],qe=["$interpolate","$compile",function(a,c){return{compile:function(d){c.$$addBindingClass(d);return function(d,f,g){d=a(f.attr(g.$attr.ngBindTemplate));
c.$$addBindingInfo(f,d.expressions);f=f[0];g.$observe("ngBindTemplate",function(a){f.textContent=a===t?"":a})}}}}],pe=["$sce","$parse","$compile",function(a,c,d){return{restrict:"A",compile:function(e,f){var g=c(f.ngBindHtml),h=c(f.ngBindHtml,function(a){return(a||"").toString()});d.$$addBindingClass(e);return function(c,e,f){d.$$addBindingInfo(e,f.ngBindHtml);c.$watch(h,function(){e.html(a.getTrustedHtml(g(c))||"")})}}}}],Ne=ra({restrict:"A",require:"ngModel",link:function(a,c,d,e){e.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}),
re=lc("",!0),te=lc("Odd",0),se=lc("Even",1),ue=Ma({compile:function(a,c){c.$set("ngCloak",t);a.removeClass("ng-cloak")}}),ve=[function(){return{restrict:"A",scope:!0,controller:"@",priority:500}}],Kc={},vg={blur:!0,focus:!0};m("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" "),function(a){var c=wa("ng-"+a);Kc[c]=["$parse","$rootScope",function(d,e){return{restrict:"A",compile:function(f,g){var h=
d(g[c],null,!0);return function(c,d){d.on(a,function(d){var f=function(){h(c,{$event:d})};vg[a]&&e.$$phase?c.$evalAsync(f):c.$apply(f)})}}}}]});var ye=["$animate",function(a){return{multiElement:!0,transclude:"element",priority:600,terminal:!0,restrict:"A",$$tlb:!0,link:function(c,d,e,f,g){var h,l,k;c.$watch(e.ngIf,function(c){c?l||g(function(c,f){l=f;c[c.length++]=U.createComment(" end ngIf: "+e.ngIf+" ");h={clone:c};a.enter(c,d.parent(),d)}):(k&&(k.remove(),k=null),l&&(l.$destroy(),l=null),h&&(k=
qb(h.clone),a.leave(k).then(function(){k=null}),h=null))})}}}],ze=["$templateRequest","$anchorScroll","$animate",function(a,c,d){return{restrict:"ECA",priority:400,terminal:!0,transclude:"element",controller:ca.noop,compile:function(e,f){var g=f.ngInclude||f.src,h=f.onload||"",l=f.autoscroll;return function(e,f,m,s,q){var t=0,F,u,p,v=function(){u&&(u.remove(),u=null);F&&(F.$destroy(),F=null);p&&(d.leave(p).then(function(){u=null}),u=p,p=null)};e.$watch(g,function(g){var m=function(){!w(l)||l&&!e.$eval(l)||
c()},r=++t;g?(a(g,!0).then(function(a){if(r===t){var c=e.$new();s.template=a;a=q(c,function(a){v();d.enter(a,null,f).then(m)});F=c;p=a;F.$emit("$includeContentLoaded",g);e.$eval(h)}},function(){r===t&&(v(),e.$emit("$includeContentError",g))}),e.$emit("$includeContentRequested",g)):(v(),s.template=null)})}}}}],Qe=["$compile",function(a){return{restrict:"ECA",priority:-400,require:"ngInclude",link:function(c,d,e,f){/SVG/.test(d[0].toString())?(d.empty(),a(Nc(f.template,U).childNodes)(c,function(a){d.append(a)},
{futureParentElement:d})):(d.html(f.template),a(d.contents())(c))}}}],Ae=Ma({priority:450,compile:function(){return{pre:function(a,c,d){a.$eval(d.ngInit)}}}}),Me=function(){return{restrict:"A",priority:100,require:"ngModel",link:function(a,c,d,e){var f=c.attr(d.$attr.ngList)||", ",g="false"!==d.ngTrim,h=g?R(f):f;e.$parsers.push(function(a){if(!A(a)){var c=[];a&&m(a.split(h),function(a){a&&c.push(g?R(a):a)});return c}});e.$formatters.push(function(a){return G(a)?a.join(f):t});e.$isEmpty=function(a){return!a||
!a.length}}}},mb="ng-valid",Kd="ng-invalid",Va="ng-pristine",Jb="ng-dirty",Md="ng-pending",Lb=new J("ngModel"),wg=["$scope","$exceptionHandler","$attrs","$element","$parse","$animate","$timeout","$rootScope","$q","$interpolate",function(a,c,d,e,f,g,h,l,k,n){this.$modelValue=this.$viewValue=Number.NaN;this.$$rawModelValue=t;this.$validators={};this.$asyncValidators={};this.$parsers=[];this.$formatters=[];this.$viewChangeListeners=[];this.$untouched=!0;this.$touched=!1;this.$pristine=!0;this.$dirty=
!1;this.$valid=!0;this.$invalid=!1;this.$error={};this.$$success={};this.$pending=t;this.$name=n(d.name||"",!1)(a);var r=f(d.ngModel),s=r.assign,q=r,C=s,F=null,u,p=this;this.$$setOptions=function(a){if((p.$options=a)&&a.getterSetter){var c=f(d.ngModel+"()"),g=f(d.ngModel+"($$$p)");q=function(a){var d=r(a);z(d)&&(d=c(a));return d};C=function(a,c){z(r(a))?g(a,{$$$p:p.$modelValue}):s(a,p.$modelValue)}}else if(!r.assign)throw Lb("nonassign",d.ngModel,ua(e));};this.$render=v;this.$isEmpty=function(a){return A(a)||
""===a||null===a||a!==a};var K=e.inheritedData("$formController")||Ib,y=0;Hd({ctrl:this,$element:e,set:function(a,c){a[c]=!0},unset:function(a,c){delete a[c]},parentForm:K,$animate:g});this.$setPristine=function(){p.$dirty=!1;p.$pristine=!0;g.removeClass(e,Jb);g.addClass(e,Va)};this.$setDirty=function(){p.$dirty=!0;p.$pristine=!1;g.removeClass(e,Va);g.addClass(e,Jb);K.$setDirty()};this.$setUntouched=function(){p.$touched=!1;p.$untouched=!0;g.setClass(e,"ng-untouched","ng-touched")};this.$setTouched=
function(){p.$touched=!0;p.$untouched=!1;g.setClass(e,"ng-touched","ng-untouched")};this.$rollbackViewValue=function(){h.cancel(F);p.$viewValue=p.$$lastCommittedViewValue;p.$render()};this.$validate=function(){if(!V(p.$modelValue)||!isNaN(p.$modelValue)){var a=p.$$rawModelValue,c=p.$valid,d=p.$modelValue,e=p.$options&&p.$options.allowInvalid;p.$$runValidators(a,p.$$lastCommittedViewValue,function(f){e||c===f||(p.$modelValue=f?a:t,p.$modelValue!==d&&p.$$writeModelToScope())})}};this.$$runValidators=
function(a,c,d){function e(){var d=!0;m(p.$validators,function(e,f){var h=e(a,c);d=d&&h;g(f,h)});return d?!0:(m(p.$asyncValidators,function(a,c){g(c,null)}),!1)}function f(){var d=[],e=!0;m(p.$asyncValidators,function(f,h){var k=f(a,c);if(!k||!z(k.then))throw Lb("$asyncValidators",k);g(h,t);d.push(k.then(function(){g(h,!0)},function(a){e=!1;g(h,!1)}))});d.length?k.all(d).then(function(){h(e)},v):h(!0)}function g(a,c){l===y&&p.$setValidity(a,c)}function h(a){l===y&&d(a)}y++;var l=y;(function(){var a=
p.$$parserName||"parse";if(u===t)g(a,null);else return u||(m(p.$validators,function(a,c){g(c,null)}),m(p.$asyncValidators,function(a,c){g(c,null)})),g(a,u),u;return!0})()?e()?f():h(!1):h(!1)};this.$commitViewValue=function(){var a=p.$viewValue;h.cancel(F);if(p.$$lastCommittedViewValue!==a||""===a&&p.$$hasNativeValidators)p.$$lastCommittedViewValue=a,p.$pristine&&this.$setDirty(),this.$$parseAndValidate()};this.$$parseAndValidate=function(){var c=p.$$lastCommittedViewValue;if(u=A(c)?t:!0)for(var d=
0;d<p.$parsers.length;d++)if(c=p.$parsers[d](c),A(c)){u=!1;break}V(p.$modelValue)&&isNaN(p.$modelValue)&&(p.$modelValue=q(a));var e=p.$modelValue,f=p.$options&&p.$options.allowInvalid;p.$$rawModelValue=c;f&&(p.$modelValue=c,p.$modelValue!==e&&p.$$writeModelToScope());p.$$runValidators(c,p.$$lastCommittedViewValue,function(a){f||(p.$modelValue=a?c:t,p.$modelValue!==e&&p.$$writeModelToScope())})};this.$$writeModelToScope=function(){C(a,p.$modelValue);m(p.$viewChangeListeners,function(a){try{a()}catch(d){c(d)}})};
this.$setViewValue=function(a,c){p.$viewValue=a;p.$options&&!p.$options.updateOnDefault||p.$$debounceViewValueCommit(c)};this.$$debounceViewValueCommit=function(c){var d=0,e=p.$options;e&&w(e.debounce)&&(e=e.debounce,V(e)?d=e:V(e[c])?d=e[c]:V(e["default"])&&(d=e["default"]));h.cancel(F);d?F=h(function(){p.$commitViewValue()},d):l.$$phase?p.$commitViewValue():a.$apply(function(){p.$commitViewValue()})};a.$watch(function(){var c=q(a);if(c!==p.$modelValue&&(p.$modelValue===p.$modelValue||c===c)){p.$modelValue=
p.$$rawModelValue=c;u=t;for(var d=p.$formatters,e=d.length,f=c;e--;)f=d[e](f);p.$viewValue!==f&&(p.$viewValue=p.$$lastCommittedViewValue=f,p.$render(),p.$$runValidators(c,f,v))}return c})}],Le=["$rootScope",function(a){return{restrict:"A",require:["ngModel","^?form","^?ngModelOptions"],controller:wg,priority:1,compile:function(c){c.addClass(Va).addClass("ng-untouched").addClass(mb);return{pre:function(a,c,f,g){var h=g[0],l=g[1]||Ib;h.$$setOptions(g[2]&&g[2].$options);l.$addControl(h);f.$observe("name",
function(a){h.$name!==a&&l.$$renameControl(h,a)});a.$on("$destroy",function(){l.$removeControl(h)})},post:function(c,e,f,g){var h=g[0];if(h.$options&&h.$options.updateOn)e.on(h.$options.updateOn,function(a){h.$$debounceViewValueCommit(a&&a.type)});e.on("blur",function(e){h.$touched||(a.$$phase?c.$evalAsync(h.$setTouched):c.$apply(h.$setTouched))})}}}}}],xg=/(\s+|^)default(\s+|$)/,Pe=function(){return{restrict:"A",controller:["$scope","$attrs",function(a,c){var d=this;this.$options=fa(a.$eval(c.ngModelOptions));
this.$options.updateOn!==t?(this.$options.updateOnDefault=!1,this.$options.updateOn=R(this.$options.updateOn.replace(xg,function(){d.$options.updateOnDefault=!0;return" "}))):this.$options.updateOnDefault=!0}]}},Be=Ma({terminal:!0,priority:1E3}),yg=J("ngOptions"),zg=/^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/,
Je=["$compile","$parse",function(a,c){function d(a,d,e){function f(a,c,d,e,g){this.selectValue=a;this.viewValue=c;this.label=d;this.group=e;this.disabled=g}function n(a){var c;if(!q&&Ea(a))c=a;else{c=[];for(var d in a)a.hasOwnProperty(d)&&"$"!==d.charAt(0)&&c.push(d)}return c}var m=a.match(zg);if(!m)throw yg("iexp",a,ua(d));var s=m[5]||m[7],q=m[6];a=/ as /.test(m[0])&&m[1];var t=m[9];d=c(m[2]?m[1]:s);var v=a&&c(a)||d,u=t&&c(t),p=t?function(a,c){return u(e,c)}:function(a){return Ga(a)},w=function(a,
c){return p(a,z(a,c))},y=c(m[2]||m[1]),A=c(m[3]||""),B=c(m[4]||""),N=c(m[8]),D={},z=q?function(a,c){D[q]=c;D[s]=a;return D}:function(a){D[s]=a;return D};return{trackBy:t,getTrackByValue:w,getWatchables:c(N,function(a){var c=[];a=a||[];for(var d=n(a),f=d.length,g=0;g<f;g++){var h=a===d?g:d[g],k=z(a[h],h),h=p(a[h],k);c.push(h);if(m[2]||m[1])h=y(e,k),c.push(h);m[4]&&(k=B(e,k),c.push(k))}return c}),getOptions:function(){for(var a=[],c={},d=N(e)||[],g=n(d),h=g.length,m=0;m<h;m++){var r=d===g?m:g[m],s=
z(d[r],r),q=v(e,s),r=p(q,s),u=y(e,s),x=A(e,s),s=B(e,s),q=new f(r,q,u,x,s);a.push(q);c[r]=q}return{items:a,selectValueMap:c,getOptionFromViewValue:function(a){return c[w(a)]},getViewValueFromOption:function(a){return t?ca.copy(a.viewValue):a.viewValue}}}}}var e=U.createElement("option"),f=U.createElement("optgroup");return{restrict:"A",terminal:!0,require:["select","?ngModel"],link:function(c,h,l,k){function n(a,c){a.element=c;c.disabled=a.disabled;a.value!==c.value&&(c.value=a.selectValue);a.label!==
c.label&&(c.label=a.label,c.textContent=a.label)}function r(a,c,d,e){c&&M(c.nodeName)===d?d=c:(d=e.cloneNode(!1),c?a.insertBefore(d,c):a.appendChild(d));return d}function s(a){for(var c;a;)c=a.nextSibling,Xb(a),a=c}function q(a){var c=p&&p[0],d=N&&N[0];if(c||d)for(;a&&(a===c||a===d);)a=a.nextSibling;return a}function t(){var a=D&&u.readValue();D=z.getOptions();var c={},d=h[0].firstChild;B&&h.prepend(p);d=q(d);D.items.forEach(function(a){var g,k;a.group?(g=c[a.group],g||(g=r(h[0],d,"optgroup",f),d=
g.nextSibling,g.label=a.group,g=c[a.group]={groupElement:g,currentOptionElement:g.firstChild}),k=r(g.groupElement,g.currentOptionElement,"option",e),n(a,k),g.currentOptionElement=k.nextSibling):(k=r(h[0],d,"option",e),n(a,k),d=k.nextSibling)});Object.keys(c).forEach(function(a){s(c[a].currentOptionElement)});s(d);v.$render();if(!v.$isEmpty(a)){var g=u.readValue();(z.trackBy?ka(a,g):a===g)||(v.$setViewValue(g),v.$render())}}var v=k[1];if(v){var u=k[0];k=l.multiple;for(var p,w=0,A=h.children(),I=A.length;w<
I;w++)if(""===A[w].value){p=A.eq(w);break}var B=!!p,N=y(e.cloneNode(!1));N.val("?");var D,z=d(l.ngOptions,h,c);k?(v.$isEmpty=function(a){return!a||0===a.length},u.writeValue=function(a){D.items.forEach(function(a){a.element.selected=!1});a&&a.forEach(function(a){(a=D.getOptionFromViewValue(a))&&!a.disabled&&(a.element.selected=!0)})},u.readValue=function(){var a=h.val()||[],c=[];m(a,function(a){a=D.selectValueMap[a];a.disabled||c.push(D.getViewValueFromOption(a))});return c},z.trackBy&&c.$watchCollection(function(){if(G(v.$viewValue))return v.$viewValue.map(function(a){return z.getTrackByValue(a)})},
function(){v.$render()})):(u.writeValue=function(a){var c=D.getOptionFromViewValue(a);c&&!c.disabled?h[0].value!==c.selectValue&&(N.remove(),B||p.remove(),h[0].value=c.selectValue,c.element.selected=!0,c.element.setAttribute("selected","selected")):null===a||B?(N.remove(),B||h.prepend(p),h.val(""),p.prop("selected",!0),p.attr("selected",!0)):(B||p.remove(),h.prepend(N),h.val("?"),N.prop("selected",!0),N.attr("selected",!0))},u.readValue=function(){var a=D.selectValueMap[h.val()];return a&&!a.disabled?
(B||p.remove(),N.remove(),D.getViewValueFromOption(a)):null},z.trackBy&&c.$watch(function(){return z.getTrackByValue(v.$viewValue)},function(){v.$render()}));B?(p.remove(),a(p)(c),p.removeClass("ng-scope")):p=y(e.cloneNode(!1));t();c.$watchCollection(z.getWatchables,t)}}}}],Ce=["$locale","$interpolate","$log",function(a,c,d){var e=/{}/g,f=/^when(Minus)?(.+)$/;return{link:function(g,h,l){function k(a){h.text(a||"")}var n=l.count,r=l.$attr.when&&h.attr(l.$attr.when),s=l.offset||0,q=g.$eval(r)||{},t=
{},w=c.startSymbol(),u=c.endSymbol(),p=w+n+"-"+s+u,y=ca.noop,z;m(l,function(a,c){var d=f.exec(c);d&&(d=(d[1]?"-":"")+M(d[2]),q[d]=h.attr(l.$attr[c]))});m(q,function(a,d){t[d]=c(a.replace(e,p))});g.$watch(n,function(c){var e=parseFloat(c),f=isNaN(e);f||e in q||(e=a.pluralCat(e-s));e===z||f&&V(z)&&isNaN(z)||(y(),f=t[e],A(f)?(null!=c&&d.debug("ngPluralize: no rule defined for '"+e+"' in "+r),y=v,k()):y=g.$watch(f,k),z=e)})}}}],De=["$parse","$animate",function(a,c){var d=J("ngRepeat"),e=function(a,c,
d,e,k,m,r){a[d]=e;k&&(a[k]=m);a.$index=c;a.$first=0===c;a.$last=c===r-1;a.$middle=!(a.$first||a.$last);a.$odd=!(a.$even=0===(c&1))};return{restrict:"A",multiElement:!0,transclude:"element",priority:1E3,terminal:!0,$$tlb:!0,compile:function(f,g){var h=g.ngRepeat,l=U.createComment(" end ngRepeat: "+h+" "),k=h.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);if(!k)throw d("iexp",h);var n=k[1],r=k[2],s=k[3],q=k[4],k=n.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
if(!k)throw d("iidexp",n);var v=k[3]||k[1],w=k[2];if(s&&(!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(s)||/^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(s)))throw d("badident",s);var u,p,z,A,I={$id:Ga};q?u=a(q):(z=function(a,c){return Ga(c)},A=function(a){return a});return function(a,f,g,k,n){u&&(p=function(c,d,e){w&&(I[w]=c);I[v]=d;I.$index=e;return u(a,I)});var q=ga();a.$watchCollection(r,function(g){var k,r,u=f[0],x,D=ga(),I,H,L,G,M,J,O;s&&(a[s]=g);if(Ea(g))M=
g,r=p||z;else for(O in r=p||A,M=[],g)g.hasOwnProperty(O)&&"$"!==O.charAt(0)&&M.push(O);I=M.length;O=Array(I);for(k=0;k<I;k++)if(H=g===M?k:M[k],L=g[H],G=r(H,L,k),q[G])J=q[G],delete q[G],D[G]=J,O[k]=J;else{if(D[G])throw m(O,function(a){a&&a.scope&&(q[a.id]=a)}),d("dupes",h,G,L);O[k]={id:G,scope:t,clone:t};D[G]=!0}for(x in q){J=q[x];G=qb(J.clone);c.leave(G);if(G[0].parentNode)for(k=0,r=G.length;k<r;k++)G[k].$$NG_REMOVED=!0;J.scope.$destroy()}for(k=0;k<I;k++)if(H=g===M?k:M[k],L=g[H],J=O[k],J.scope){x=
u;do x=x.nextSibling;while(x&&x.$$NG_REMOVED);J.clone[0]!=x&&c.move(qb(J.clone),null,y(u));u=J.clone[J.clone.length-1];e(J.scope,k,v,L,w,H,I)}else n(function(a,d){J.scope=d;var f=l.cloneNode(!1);a[a.length++]=f;c.enter(a,null,y(u));u=f;J.clone=a;D[J.id]=J;e(J.scope,k,v,L,w,H,I)});q=D})}}}}],Ee=["$animate",function(a){return{restrict:"A",multiElement:!0,link:function(c,d,e){c.$watch(e.ngShow,function(c){a[c?"removeClass":"addClass"](d,"ng-hide",{tempClasses:"ng-hide-animate"})})}}}],xe=["$animate",
function(a){return{restrict:"A",multiElement:!0,link:function(c,d,e){c.$watch(e.ngHide,function(c){a[c?"addClass":"removeClass"](d,"ng-hide",{tempClasses:"ng-hide-animate"})})}}}],Fe=Ma(function(a,c,d){a.$watch(d.ngStyle,function(a,d){d&&a!==d&&m(d,function(a,d){c.css(d,"")});a&&c.css(a)},!0)}),Ge=["$animate",function(a){return{require:"ngSwitch",controller:["$scope",function(){this.cases={}}],link:function(c,d,e,f){var g=[],h=[],l=[],k=[],n=function(a,c){return function(){a.splice(c,1)}};c.$watch(e.ngSwitch||
e.on,function(c){var d,e;d=0;for(e=l.length;d<e;++d)a.cancel(l[d]);d=l.length=0;for(e=k.length;d<e;++d){var q=qb(h[d].clone);k[d].$destroy();(l[d]=a.leave(q)).then(n(l,d))}h.length=0;k.length=0;(g=f.cases["!"+c]||f.cases["?"])&&m(g,function(c){c.transclude(function(d,e){k.push(e);var f=c.element;d[d.length++]=U.createComment(" end ngSwitchWhen: ");h.push({clone:d});a.enter(d,f.parent(),f)})})})}}}],He=Ma({transclude:"element",priority:1200,require:"^ngSwitch",multiElement:!0,link:function(a,c,d,e,
f){e.cases["!"+d.ngSwitchWhen]=e.cases["!"+d.ngSwitchWhen]||[];e.cases["!"+d.ngSwitchWhen].push({transclude:f,element:c})}}),Ie=Ma({transclude:"element",priority:1200,require:"^ngSwitch",multiElement:!0,link:function(a,c,d,e,f){e.cases["?"]=e.cases["?"]||[];e.cases["?"].push({transclude:f,element:c})}}),Ke=Ma({restrict:"EAC",link:function(a,c,d,e,f){if(!f)throw J("ngTransclude")("orphan",ua(c));f(function(a){c.empty();c.append(a)})}}),ke=["$templateCache",function(a){return{restrict:"E",terminal:!0,
compile:function(c,d){"text/ng-template"==d.type&&a.put(d.id,c[0].text)}}}],Ag={$setViewValue:v,$render:v},Bg=["$element","$scope","$attrs",function(a,c,d){var e=this,f=new Sa;e.ngModelCtrl=Ag;e.unknownOption=y(U.createElement("option"));e.renderUnknownOption=function(c){c="? "+Ga(c)+" ?";e.unknownOption.val(c);a.prepend(e.unknownOption);a.val(c)};c.$on("$destroy",function(){e.renderUnknownOption=v});e.removeUnknownOption=function(){e.unknownOption.parent()&&e.unknownOption.remove()};e.readValue=
function(){e.removeUnknownOption();return a.val()};e.writeValue=function(c){e.hasOption(c)?(e.removeUnknownOption(),a.val(c),""===c&&e.emptyOption.prop("selected",!0)):null==c&&e.emptyOption?(e.removeUnknownOption(),a.val("")):e.renderUnknownOption(c)};e.addOption=function(a,c){Ra(a,'"option value"');""===a&&(e.emptyOption=c);var d=f.get(a)||0;f.put(a,d+1)};e.removeOption=function(a){var c=f.get(a);c&&(1===c?(f.remove(a),""===a&&(e.emptyOption=t)):f.put(a,c-1))};e.hasOption=function(a){return!!f.get(a)}}],
le=function(){return{restrict:"E",require:["select","?ngModel"],controller:Bg,link:function(a,c,d,e){var f=e[1];if(f){var g=e[0];g.ngModelCtrl=f;f.$render=function(){g.writeValue(f.$viewValue)};c.on("change",function(){a.$apply(function(){f.$setViewValue(g.readValue())})});if(d.multiple){g.readValue=function(){var a=[];m(c.find("option"),function(c){c.selected&&a.push(c.value)});return a};g.writeValue=function(a){var d=new Sa(a);m(c.find("option"),function(a){a.selected=w(d.get(a.value))})};var h,
l=NaN;a.$watch(function(){l!==f.$viewValue||ka(h,f.$viewValue)||(h=ia(f.$viewValue),f.$render());l=f.$viewValue});f.$isEmpty=function(a){return!a||0===a.length}}}}}},ne=["$interpolate",function(a){function c(a){a[0].hasAttribute("selected")&&(a[0].selected=!0)}return{restrict:"E",priority:100,compile:function(d,e){if(A(e.value)){var f=a(d.text(),!0);f||e.$set("value",d.text())}return function(a,d,e){var k=d.parent(),m=k.data("$selectController")||k.parent().data("$selectController");m&&m.ngModelCtrl&&
(f?a.$watch(f,function(a,f){e.$set("value",a);f!==a&&m.removeOption(f);m.addOption(a,d);m.ngModelCtrl.$render();c(d)}):(m.addOption(e.value,d),m.ngModelCtrl.$render(),c(d)),d.on("$destroy",function(){m.removeOption(e.value);m.ngModelCtrl.$render()}))}}}}],me=ra({restrict:"E",terminal:!1}),Hc=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){e&&(d.required=!0,e.$validators.required=function(a,c){return!d.required||!e.$isEmpty(c)},d.$observe("required",function(){e.$validate()}))}}},
Gc=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){if(e){var f,g=d.ngPattern||d.pattern;d.$observe("pattern",function(a){L(a)&&0<a.length&&(a=new RegExp("^"+a+"$"));if(a&&!a.test)throw J("ngPattern")("noregexp",g,a,ua(c));f=a||t;e.$validate()});e.$validators.pattern=function(a){return e.$isEmpty(a)||A(f)||f.test(a)}}}}},Jc=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){if(e){var f=-1;d.$observe("maxlength",function(a){a=W(a);f=isNaN(a)?-1:a;e.$validate()});
e.$validators.maxlength=function(a,c){return 0>f||e.$isEmpty(c)||c.length<=f}}}}},Ic=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){if(e){var f=0;d.$observe("minlength",function(a){f=W(a)||0;e.$validate()});e.$validators.minlength=function(a,c){return e.$isEmpty(c)||c.length>=f}}}}};O.angular.bootstrap?console.log("WARNING: Tried to load angular more than once."):(ce(),ee(ca),y(U).ready(function(){Zd(U,Ac)}))})(window,document);!window.angular.$$csp()&&window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');
//# sourceMappingURL=angular.min.js.map
/*!
* ionic.bundle.js is a concatenation of:
* ionic.js, angular.js, angular-animate.js,
* angular-sanitize.js, angular-ui-router.js,
* and ionic-angular.js
*/
/*
AngularJS v1.4.3
(c) 2010-2015 Google, Inc. http://angularjs.org
License: MIT
*/
(function(F,t,W){'use strict';function ua(a,b,c){if(!a)throw ngMinErr("areq",b||"?",c||"required");return a}function va(a,b){if(!a&&!b)return"";if(!a)return b;if(!b)return a;X(a)&&(a=a.join(" "));X(b)&&(b=b.join(" "));return a+" "+b}function Ea(a){var b={};a&&(a.to||a.from)&&(b.to=a.to,b.from=a.from);return b}function ba(a,b,c){var d="";a=X(a)?a:a&&U(a)&&a.length?a.split(/\s+/):[];u(a,function(a,s){a&&0<a.length&&(d+=0<s?" ":"",d+=c?b+a:a+b)});return d}function Fa(a){if(a instanceof G)switch(a.length){case 0:return[];
case 1:if(1===a[0].nodeType)return a;break;default:return G(ka(a))}if(1===a.nodeType)return G(a)}function ka(a){if(!a[0])return a;for(var b=0;b<a.length;b++){var c=a[b];if(1==c.nodeType)return c}}function Ga(a,b,c){u(b,function(b){a.addClass(b,c)})}function Ha(a,b,c){u(b,function(b){a.removeClass(b,c)})}function ha(a){return function(b,c){c.addClass&&(Ga(a,b,c.addClass),c.addClass=null);c.removeClass&&(Ha(a,b,c.removeClass),c.removeClass=null)}}function ia(a){a=a||{};if(!a.$$prepared){var b=a.domOperation||
H;a.domOperation=function(){a.$$domOperationFired=!0;b();b=H};a.$$prepared=!0}return a}function ca(a,b){wa(a,b);xa(a,b)}function wa(a,b){b.from&&(a.css(b.from),b.from=null)}function xa(a,b){b.to&&(a.css(b.to),b.to=null)}function R(a,b,c){var d=(b.addClass||"")+" "+(c.addClass||""),e=(b.removeClass||"")+" "+(c.removeClass||"");a=Ia(a.attr("class"),d,e);ya(b,c);b.addClass=a.addClass?a.addClass:null;b.removeClass=a.removeClass?a.removeClass:null;return b}function Ia(a,b,c){function d(a){U(a)&&(a=a.split(" "));
var b={};u(a,function(a){a.length&&(b[a]=!0)});return b}var e={};a=d(a);b=d(b);u(b,function(a,b){e[b]=1});c=d(c);u(c,function(a,b){e[b]=1===e[b]?null:-1});var s={addClass:"",removeClass:""};u(e,function(b,c){var d,e;1===b?(d="addClass",e=!a[c]):-1===b&&(d="removeClass",e=a[c]);e&&(s[d].length&&(s[d]+=" "),s[d]+=c)});return s}function z(a){return a instanceof t.element?a[0]:a}function za(a,b,c){var d=Object.create(null),e=a.getComputedStyle(b)||{};u(c,function(a,b){var c=e[a];if(c){var k=c.charAt(0);
if("-"===k||"+"===k||0<=k)c=Ja(c);0===c&&(c=null);d[b]=c}});return d}function Ja(a){var b=0;a=a.split(/\s*,\s*/);u(a,function(a){"s"==a.charAt(a.length-1)&&(a=a.substring(0,a.length-1));a=parseFloat(a)||0;b=b?Math.max(a,b):a});return b}function la(a){return 0===a||null!=a}function Aa(a,b){var c=O,d=a+"s";b?c+="Duration":d+=" linear all";return[c,d]}function ja(a,b){var c=b?"-"+b+"s":"";da(a,[ea,c]);return[ea,c]}function ma(a,b){var c=b?"paused":"",d=V+"PlayState";da(a,[d,c]);return[d,c]}function da(a,
b){a.style[b[0]]=b[1]}function Ba(){var a=Object.create(null);return{flush:function(){a=Object.create(null)},count:function(b){return(b=a[b])?b.total:0},get:function(b){return(b=a[b])&&b.value},put:function(b,c){a[b]?a[b].total++:a[b]={total:1,value:c}}}}var H=t.noop,ya=t.extend,G=t.element,u=t.forEach,X=t.isArray,U=t.isString,na=t.isObject,Ka=t.isUndefined,La=t.isDefined,Ca=t.isFunction,oa=t.isElement,O,pa,V,qa;F.ontransitionend===W&&F.onwebkittransitionend!==W?(O="WebkitTransition",pa="webkitTransitionEnd transitionend"):
(O="transition",pa="transitionend");F.onanimationend===W&&F.onwebkitanimationend!==W?(V="WebkitAnimation",qa="webkitAnimationEnd animationend"):(V="animation",qa="animationend");var ra=V+"Delay",sa=V+"Duration",ea=O+"Delay";F=O+"Duration";var Ma={transitionDuration:F,transitionDelay:ea,transitionProperty:O+"Property",animationDuration:sa,animationDelay:ra,animationIterationCount:V+"IterationCount"},Na={transitionDuration:F,transitionDelay:ea,animationDuration:sa,animationDelay:ra};t.module("ngAnimate",
[]).directive("ngAnimateChildren",[function(){return function(a,b,c){a=c.ngAnimateChildren;t.isString(a)&&0===a.length?b.data("$$ngAnimateChildren",!0):c.$observe("ngAnimateChildren",function(a){b.data("$$ngAnimateChildren","on"===a||"true"===a)})}}]).factory("$$rAFMutex",["$$rAF",function(a){return function(){var b=!1;a(function(){b=!0});return function(c){b?c():a(c)}}}]).factory("$$rAFScheduler",["$$rAF",function(a){function b(a){d.push([].concat(a));c()}function c(){if(d.length){for(var b=[],n=
0;n<d.length;n++){var h=d[n];h.shift()();h.length&&b.push(h)}d=b;e||a(function(){e||c()})}}var d=[],e;b.waitUntilQuiet=function(b){e&&e();e=a(function(){e=null;b();c()})};return b}]).factory("$$AnimateRunner",["$q","$$rAFMutex",function(a,b){function c(a){this.setHost(a);this._doneCallbacks=[];this._runInAnimationFrame=b();this._state=0}c.chain=function(a,b){function c(){if(n===a.length)b(!0);else a[n](function(a){!1===a?b(!1):(n++,c())})}var n=0;c()};c.all=function(a,b){function c(s){h=h&&s;++n===
a.length&&b(h)}var n=0,h=!0;u(a,function(a){a.done(c)})};c.prototype={setHost:function(a){this.host=a||{}},done:function(a){2===this._state?a():this._doneCallbacks.push(a)},progress:H,getPromise:function(){if(!this.promise){var b=this;this.promise=a(function(a,c){b.done(function(b){!1===b?c():a()})})}return this.promise},then:function(a,b){return this.getPromise().then(a,b)},"catch":function(a){return this.getPromise()["catch"](a)},"finally":function(a){return this.getPromise()["finally"](a)},pause:function(){this.host.pause&&
this.host.pause()},resume:function(){this.host.resume&&this.host.resume()},end:function(){this.host.end&&this.host.end();this._resolve(!0)},cancel:function(){this.host.cancel&&this.host.cancel();this._resolve(!1)},complete:function(a){var b=this;0===b._state&&(b._state=1,b._runInAnimationFrame(function(){b._resolve(a)}))},_resolve:function(a){2!==this._state&&(u(this._doneCallbacks,function(b){b(a)}),this._doneCallbacks.length=0,this._state=2)}};return c}]).provider("$$animateQueue",["$animateProvider",
function(a){function b(a,b,c,h){return d[a].some(function(a){return a(b,c,h)})}function c(a,b){a=a||{};var c=0<(a.addClass||"").length,d=0<(a.removeClass||"").length;return b?c&&d:c||d}var d=this.rules={skip:[],cancel:[],join:[]};d.join.push(function(a,b,d){return!b.structural&&c(b.options)});d.skip.push(function(a,b,d){return!b.structural&&!c(b.options)});d.skip.push(function(a,b,c){return"leave"==c.event&&b.structural});d.skip.push(function(a,b,c){return c.structural&&!b.structural});d.cancel.push(function(a,
b,c){return c.structural&&b.structural});d.cancel.push(function(a,b,c){return 2===c.state&&b.structural});d.cancel.push(function(a,b,c){a=b.options;c=c.options;return a.addClass&&a.addClass===c.removeClass||a.removeClass&&a.removeClass===c.addClass});this.$get=["$$rAF","$rootScope","$rootElement","$document","$$HashMap","$$animation","$$AnimateRunner","$templateRequest","$$jqLite",function(d,s,n,h,k,D,A,Z,I){function w(a,b){var c=z(a),f=[],m=l[b];m&&u(m,function(a){a.node.contains(c)&&f.push(a.callback)});
return f}function B(a,b,c,f){d(function(){u(w(b,a),function(a){a(b,c,f)})})}function r(a,S,p){function d(b,c,f,p){B(c,a,f,p);b.progress(c,f,p)}function g(b){Da(a,p);ca(a,p);p.domOperation();l.complete(!b)}var P,E;if(a=Fa(a))P=z(a),E=a.parent();p=ia(p);var l=new A;if(!P)return g(),l;X(p.addClass)&&(p.addClass=p.addClass.join(" "));X(p.removeClass)&&(p.removeClass=p.removeClass.join(" "));p.from&&!na(p.from)&&(p.from=null);p.to&&!na(p.to)&&(p.to=null);var e=[P.className,p.addClass,p.removeClass].join(" ");
if(!v(e))return g(),l;var M=0<=["enter","move","leave"].indexOf(S),h=!x||L.get(P),e=!h&&m.get(P)||{},k=!!e.state;h||k&&1==e.state||(h=!ta(a,E,S));if(h)return g(),l;M&&K(a);h={structural:M,element:a,event:S,close:g,options:p,runner:l};if(k){if(b("skip",a,h,e)){if(2===e.state)return g(),l;R(a,e.options,p);return e.runner}if(b("cancel",a,h,e))2===e.state?e.runner.end():e.structural?e.close():R(a,h.options,e.options);else if(b("join",a,h,e))if(2===e.state)R(a,p,{});else return S=h.event=e.event,p=R(a,
e.options,h.options),l}else R(a,p,{});(k=h.structural)||(k="animate"===h.event&&0<Object.keys(h.options.to||{}).length||c(h.options));if(!k)return g(),C(a),l;M&&f(E);var r=(e.counter||0)+1;h.counter=r;ga(a,1,h);s.$$postDigest(function(){var b=m.get(P),v=!b,b=b||{},e=a.parent()||[],E=0<e.length&&("animate"===b.event||b.structural||c(b.options));if(v||b.counter!==r||!E){v&&(Da(a,p),ca(a,p));if(v||M&&b.event!==S)p.domOperation(),l.end();E||C(a)}else S=!b.structural&&c(b.options,!0)?"setClass":b.event,
b.structural&&f(e),ga(a,2),b=D(a,S,b.options),b.done(function(b){g(!b);(b=m.get(P))&&b.counter===r&&C(z(a));d(l,S,"close",{})}),l.setHost(b),d(l,S,"start",{})});return l}function K(a){a=z(a).querySelectorAll("[data-ng-animate]");u(a,function(a){var b=parseInt(a.getAttribute("data-ng-animate")),c=m.get(a);switch(b){case 2:c.runner.end();case 1:c&&m.remove(a)}})}function C(a){a=z(a);a.removeAttribute("data-ng-animate");m.remove(a)}function E(a,b){return z(a)===z(b)}function f(a){a=z(a);do{if(!a||1!==
a.nodeType)break;var b=m.get(a);if(b){var f=a;!b.structural&&c(b.options)&&(2===b.state&&b.runner.end(),C(f))}a=a.parentNode}while(1)}function ta(a,b,c){var f=c=!1,d=!1,v;for((a=a.data("$ngAnimatePin"))&&(b=a);b&&b.length;){f||(f=E(b,n));a=b[0];if(1!==a.nodeType)break;var e=m.get(a)||{};d||(d=e.structural||L.get(a));if(Ka(v)||!0===v)a=b.data("$$ngAnimateChildren"),La(a)&&(v=a);if(d&&!1===v)break;f||(f=E(b,n),f||(a=b.data("$ngAnimatePin"))&&(b=a));c||(c=E(b,g));b=b.parent()}return(!d||v)&&f&&c}function ga(a,
b,c){c=c||{};c.state=b;a=z(a);a.setAttribute("data-ng-animate",b);c=(b=m.get(a))?ya(b,c):c;m.put(a,c)}var m=new k,L=new k,x=null,M=s.$watch(function(){return 0===Z.totalPendingRequests},function(a){a&&(M(),s.$$postDigest(function(){s.$$postDigest(function(){null===x&&(x=!0)})}))}),g=G(h[0].body),l={},P=a.classNameFilter(),v=P?function(a){return P.test(a)}:function(){return!0},Da=ha(I);return{on:function(a,b,c){b=ka(b);l[a]=l[a]||[];l[a].push({node:b,callback:c})},off:function(a,b,c){function f(a,
b,c){var d=ka(b);return a.filter(function(a){return!(a.node===d&&(!c||a.callback===c))})}var d=l[a];d&&(l[a]=1===arguments.length?null:f(d,b,c))},pin:function(a,b){ua(oa(a),"element","not an element");ua(oa(b),"parentElement","not an element");a.data("$ngAnimatePin",b)},push:function(a,b,c,f){c=c||{};c.domOperation=f;return r(a,b,c)},enabled:function(a,b){var c=arguments.length;if(0===c)b=!!x;else if(oa(a)){var f=z(a),d=L.get(f);1===c?b=!d:(b=!!b)?d&&L.remove(f):L.put(f,!0)}else b=x=!!a;return b}}}]}]).provider("$$animation",
["$animateProvider",function(a){function b(a){return a.data("$$animationRunner")}var c=this.drivers=[];this.$get=["$$jqLite","$rootScope","$injector","$$AnimateRunner","$$rAFScheduler",function(a,e,s,n,h){var k=[],D=ha(a),A=0,Z=0,I=[];return function(w,B,r){function K(a){a=a.hasAttribute("ng-animate-ref")?[a]:a.querySelectorAll("[ng-animate-ref]");var b=[];u(a,function(a){var c=a.getAttribute("ng-animate-ref");c&&c.length&&b.push(a)});return b}function C(a){var b=[],c={};u(a,function(a,f){var d=z(a.element),
m=0<=["enter","move"].indexOf(a.event),d=a.structural?K(d):[];if(d.length){var g=m?"to":"from";u(d,function(a){var b=a.getAttribute("ng-animate-ref");c[b]=c[b]||{};c[b][g]={animationID:f,element:G(a)}})}else b.push(a)});var f={},d={};u(c,function(c,m){var g=c.from,e=c.to;if(g&&e){var l=a[g.animationID],h=a[e.animationID],x=g.animationID.toString();if(!d[x]){var B=d[x]={structural:!0,beforeStart:function(){l.beforeStart();h.beforeStart()},close:function(){l.close();h.close()},classes:E(l.classes,h.classes),
from:l,to:h,anchors:[]};B.classes.length?b.push(B):(b.push(l),b.push(h))}d[x].anchors.push({out:g.element,"in":e.element})}else g=g?g.animationID:e.animationID,e=g.toString(),f[e]||(f[e]=!0,b.push(a[g]))});return b}function E(a,b){a=a.split(" ");b=b.split(" ");for(var c=[],f=0;f<a.length;f++){var d=a[f];if("ng-"!==d.substring(0,3))for(var g=0;g<b.length;g++)if(d===b[g]){c.push(d);break}}return c.join(" ")}function f(a){for(var b=c.length-1;0<=b;b--){var f=c[b];if(s.has(f)&&(f=s.get(f)(a)))return f}}
function ta(a,c){a.from&&a.to?(b(a.from.element).setHost(c),b(a.to.element).setHost(c)):b(a.element).setHost(c)}function ga(){var a=b(w);!a||"leave"===B&&r.$$domOperationFired||a.end()}function m(b){w.off("$destroy",ga);w.removeData("$$animationRunner");D(w,r);ca(w,r);r.domOperation();g&&a.removeClass(w,g);w.removeClass("ng-animate");x.complete(!b)}r=ia(r);var L=0<=["enter","move","leave"].indexOf(B),x=new n({end:function(){m()},cancel:function(){m(!0)}});if(!c.length)return m(),x;w.data("$$animationRunner",
x);var M=va(w.attr("class"),va(r.addClass,r.removeClass)),g=r.tempClasses;g&&(M+=" "+g,r.tempClasses=null);var l;L||(l=A,A+=1);k.push({element:w,classes:M,event:B,classBasedIndex:l,structural:L,options:r,beforeStart:function(){w.addClass("ng-animate");g&&a.addClass(w,g)},close:m});w.on("$destroy",ga);if(1<k.length)return x;e.$$postDigest(function(){Z=A;A=0;I.length=0;var a=[];u(k,function(c){b(c.element)&&a.push(c)});k.length=0;u(C(a),function(a){function c(){a.beforeStart();var d,g=a.close,e=a.anchors?
a.from.element||a.to.element:a.element;b(e)&&z(e).parentNode&&(e=f(a))&&(d=e.start);d?(d=d(),d.done(function(a){g(!a)}),ta(a,d)):g()}a.structural?c():(I.push({node:z(a.element),fn:c}),a.classBasedIndex===Z-1&&(I=I.sort(function(a,b){return b.node.contains(a.node)}).map(function(a){return a.fn}),h(I)))})});return x}}]}]).provider("$animateCss",["$animateProvider",function(a){var b=Ba(),c=Ba();this.$get=["$window","$$jqLite","$$AnimateRunner","$timeout","$document","$sniffer","$$rAFScheduler",function(a,
e,s,n,h,k,D){function A(a,b){var c=a.parentNode;return(c.$$ngAnimateParentKey||(c.$$ngAnimateParentKey=++r))+"-"+a.getAttribute("class")+"-"+b}function Z(h,f,B,k){var m;0<b.count(B)&&(m=c.get(B),m||(f=ba(f,"-stagger"),e.addClass(h,f),m=za(a,h,k),m.animationDuration=Math.max(m.animationDuration,0),m.transitionDuration=Math.max(m.transitionDuration,0),e.removeClass(h,f),c.put(B,m)));return m||{}}function I(a){C.push(a);D.waitUntilQuiet(function(){b.flush();c.flush();for(var a=K.offsetWidth+1,d=0;d<
C.length;d++)C[d](a);C.length=0})}function w(c,f,e){f=b.get(e);f||(f=za(a,c,Ma),"infinite"===f.animationIterationCount&&(f.animationIterationCount=1));b.put(e,f);c=f;e=c.animationDelay;f=c.transitionDelay;c.maxDelay=e&&f?Math.max(e,f):e||f;c.maxDuration=Math.max(c.animationDuration*c.animationIterationCount,c.transitionDuration);return c}var B=ha(e),r=0,K=z(h).body,C=[];return function(a,c){function d(){m()}function h(){m(!0)}function m(b){if(!(K||C&&D)){K=!0;D=!1;e.removeClass(a,Y);e.removeClass(a,
W);ma(g,!1);ja(g,!1);u(l,function(a){g.style[a[0]]=""});B(a,c);ca(a,c);if(c.onDone)c.onDone();p&&p.complete(!b)}}function L(a){q.blockTransition&&ja(g,a);q.blockKeyframeAnimation&&ma(g,!!a)}function x(){p=new s({end:d,cancel:h});m();return{$$willAnimate:!1,start:function(){return p},end:d}}function M(){function b(){if(!K){L(!1);u(l,function(a){g.style[a[0]]=a[1]});B(a,c);e.addClass(a,W);if(q.recalculateTimingStyles){fa=g.className+" "+Y;$=A(g,fa);y=w(g,fa,$);Q=y.maxDelay;H=Math.max(Q,0);J=y.maxDuration;
if(0===J){m();return}q.hasTransitions=0<y.transitionDuration;q.hasAnimations=0<y.animationDuration}if(q.applyTransitionDelay||q.applyAnimationDelay){Q="boolean"!==typeof c.delay&&la(c.delay)?parseFloat(c.delay):Q;H=Math.max(Q,0);var k;q.applyTransitionDelay&&(y.transitionDelay=Q,k=[ea,Q+"s"],l.push(k),g.style[k[0]]=k[1]);q.applyAnimationDelay&&(y.animationDelay=Q,k=[ra,Q+"s"],l.push(k),g.style[k[0]]=k[1])}F=1E3*H;G=1E3*J;if(c.easing){var r=c.easing;q.hasTransitions&&(k=O+"TimingFunction",l.push([k,
r]),g.style[k]=r);q.hasAnimations&&(k=V+"TimingFunction",l.push([k,r]),g.style[k]=r)}y.transitionDuration&&p.push(pa);y.animationDuration&&p.push(qa);x=Date.now();a.on(p.join(" "),h);n(d,F+1.5*G);xa(a,c)}}function d(){m()}function h(a){a.stopPropagation();var b=a.originalEvent||a;a=b.$manualTimeStamp||b.timeStamp||Date.now();b=parseFloat(b.elapsedTime.toFixed(3));Math.max(a-x,0)>=F&&b>=J&&(C=!0,m())}if(!K)if(g.parentNode){var x,p=[],k=function(a){if(C)D&&a&&(D=!1,m());else if(D=!a,y.animationDuration)if(a=
ma(g,D),D)l.push(a);else{var b=l,c=b.indexOf(a);0<=a&&b.splice(c,1)}},r=0<U&&(y.transitionDuration&&0===T.transitionDuration||y.animationDuration&&0===T.animationDuration)&&Math.max(T.animationDelay,T.transitionDelay);r?n(b,Math.floor(r*U*1E3),!1):b();t.resume=function(){k(!0)};t.pause=function(){k(!1)}}else m()}var g=z(a);if(!g||!g.parentNode)return x();c=ia(c);var l=[],r=a.attr("class"),v=Ea(c),K,D,C,p,t,H,F,J,G;if(0===c.duration||!k.animations&&!k.transitions)return x();var aa=c.event&&X(c.event)?
c.event.join(" "):c.event,R="",N="";aa&&c.structural?R=ba(aa,"ng-",!0):aa&&(R=aa);c.addClass&&(N+=ba(c.addClass,"-add"));c.removeClass&&(N.length&&(N+=" "),N+=ba(c.removeClass,"-remove"));c.applyClassesEarly&&N.length&&(B(a,c),N="");var Y=[R,N].join(" ").trim(),fa=r+" "+Y,W=ba(Y,"-active"),r=v.to&&0<Object.keys(v.to).length;if(!(0<(c.keyframeStyle||"").length||r||Y))return x();var $,T;0<c.stagger?(v=parseFloat(c.stagger),T={transitionDelay:v,animationDelay:v,transitionDuration:0,animationDuration:0}):
($=A(g,fa),T=Z(g,Y,$,Na));e.addClass(a,Y);c.transitionStyle&&(v=[O,c.transitionStyle],da(g,v),l.push(v));0<=c.duration&&(v=0<g.style[O].length,v=Aa(c.duration,v),da(g,v),l.push(v));c.keyframeStyle&&(v=[V,c.keyframeStyle],da(g,v),l.push(v));var U=T?0<=c.staggerIndex?c.staggerIndex:b.count($):0;(aa=0===U)&&ja(g,9999);var y=w(g,fa,$),Q=y.maxDelay;H=Math.max(Q,0);J=y.maxDuration;var q={};q.hasTransitions=0<y.transitionDuration;q.hasAnimations=0<y.animationDuration;q.hasTransitionAll=q.hasTransitions&&
"all"==y.transitionProperty;q.applyTransitionDuration=r&&(q.hasTransitions&&!q.hasTransitionAll||q.hasAnimations&&!q.hasTransitions);q.applyAnimationDuration=c.duration&&q.hasAnimations;q.applyTransitionDelay=la(c.delay)&&(q.applyTransitionDuration||q.hasTransitions);q.applyAnimationDelay=la(c.delay)&&q.hasAnimations;q.recalculateTimingStyles=0<N.length;if(q.applyTransitionDuration||q.applyAnimationDuration)J=c.duration?parseFloat(c.duration):J,q.applyTransitionDuration&&(q.hasTransitions=!0,y.transitionDuration=
J,v=0<g.style[O+"Property"].length,l.push(Aa(J,v))),q.applyAnimationDuration&&(q.hasAnimations=!0,y.animationDuration=J,l.push([sa,J+"s"]));if(0===J&&!q.recalculateTimingStyles)return x();null==c.duration&&0<y.transitionDuration&&(q.recalculateTimingStyles=q.recalculateTimingStyles||aa);F=1E3*H;G=1E3*J;c.skipBlocking||(q.blockTransition=0<y.transitionDuration,q.blockKeyframeAnimation=0<y.animationDuration&&0<T.animationDelay&&0===T.animationDuration);wa(a,c);q.blockTransition||ja(g,!1);L(J);return{$$willAnimate:!0,
end:d,start:function(){if(!K)return t={end:d,cancel:h,resume:null,pause:null},p=new s(t),I(M),p}}}}]}]).provider("$$animateCssDriver",["$$animationProvider",function(a){a.drivers.push("$$animateCssDriver");this.$get=["$animateCss","$rootScope","$$AnimateRunner","$rootElement","$document","$sniffer",function(a,c,d,e,s,n){function h(a){return a.replace(/\bng-\S+\b/g,"")}function k(a,b){U(a)&&(a=a.split(" "));U(b)&&(b=b.split(" "));return a.filter(function(a){return-1===b.indexOf(a)}).join(" ")}function D(c,
e,A){function D(a){var b={},c=z(a).getBoundingClientRect();u(["width","height","top","left"],function(a){var d=c[a];switch(a){case "top":d+=I.scrollTop;break;case "left":d+=I.scrollLeft}b[a]=Math.floor(d)+"px"});return b}function s(){var c=h(A.attr("class")||""),d=k(c,t),c=k(t,c),d=a(n,{to:D(A),addClass:"ng-anchor-in "+d,removeClass:"ng-anchor-out "+c,delay:!0});return d.$$willAnimate?d:null}function f(){n.remove();e.removeClass("ng-animate-shim");A.removeClass("ng-animate-shim")}var n=G(z(e).cloneNode(!0)),
t=h(n.attr("class")||"");e.addClass("ng-animate-shim");A.addClass("ng-animate-shim");n.addClass("ng-anchor");w.append(n);var m;c=function(){var c=a(n,{addClass:"ng-anchor-out",delay:!0,from:D(e)});return c.$$willAnimate?c:null}();if(!c&&(m=s(),!m))return f();var L=c||m;return{start:function(){function a(){c&&c.end()}var b,c=L.start();c.done(function(){c=null;if(!m&&(m=s()))return c=m.start(),c.done(function(){c=null;f();b.complete()}),c;f();b.complete()});return b=new d({end:a,cancel:a})}}}function A(a,
b,c,e){var h=t(a),f=t(b),k=[];u(e,function(a){(a=D(c,a.out,a["in"]))&&k.push(a)});if(h||f||0!==k.length)return{start:function(){function a(){u(b,function(a){a.end()})}var b=[];h&&b.push(h.start());f&&b.push(f.start());u(k,function(a){b.push(a.start())});var c=new d({end:a,cancel:a});d.all(b,function(a){c.complete(a)});return c}}}function t(c){var d=c.element,e=c.options||{};c.structural?(e.structural=e.applyClassesEarly=!0,e.event=c.event,"leave"===e.event&&(e.onDone=e.domOperation)):e.event=null;
c=a(d,e);return c.$$willAnimate?c:null}if(!n.animations&&!n.transitions)return H;var I=z(s).body;c=z(e);var w=G(I.parentNode===c?I:c);return function(a){return a.from&&a.to?A(a.from,a.to,a.classes,a.anchors):t(a)}}]}]).provider("$$animateJs",["$animateProvider",function(a){this.$get=["$injector","$$AnimateRunner","$$rAFMutex","$$jqLite",function(b,c,d,e){function s(c){c=X(c)?c:c.split(" ");for(var d=[],e={},A=0;A<c.length;A++){var n=c[A],s=a.$$registeredAnimations[n];s&&!e[n]&&(d.push(b.get(s)),e[n]=
!0)}return d}var n=ha(e);return function(a,b,d,e){function t(){e.domOperation();n(a,e)}function z(a,b,d,e,g){switch(d){case "animate":b=[b,e.from,e.to,g];break;case "setClass":b=[b,r,K,g];break;case "addClass":b=[b,r,g];break;case "removeClass":b=[b,K,g];break;default:b=[b,g]}b.push(e);if(a=a.apply(a,b))if(Ca(a.start)&&(a=a.start()),a instanceof c)a.done(g);else if(Ca(a))return a;return H}function w(a,b,d,e,g){var f=[];u(e,function(e){var h=e[g];h&&f.push(function(){var e,g,f=!1,l=function(a){f||
(f=!0,(g||H)(a),e.complete(!a))};e=new c({end:function(){l()},cancel:function(){l(!0)}});g=z(h,a,b,d,function(a){l(!1===a)});return e})});return f}function B(a,b,d,e,g){var f=w(a,b,d,e,g);if(0===f.length){var h,k;"beforeSetClass"===g?(h=w(a,"removeClass",d,e,"beforeRemoveClass"),k=w(a,"addClass",d,e,"beforeAddClass")):"setClass"===g&&(h=w(a,"removeClass",d,e,"removeClass"),k=w(a,"addClass",d,e,"addClass"));h&&(f=f.concat(h));k&&(f=f.concat(k))}if(0!==f.length)return function(a){var b=[];f.length&&
u(f,function(a){b.push(a())});b.length?c.all(b,a):a();return function(a){u(b,function(b){a?b.cancel():b.end()})}}}3===arguments.length&&na(d)&&(e=d,d=null);e=ia(e);d||(d=a.attr("class")||"",e.addClass&&(d+=" "+e.addClass),e.removeClass&&(d+=" "+e.removeClass));var r=e.addClass,K=e.removeClass,C=s(d),E,f;if(C.length){var F,G;"leave"==b?(G="leave",F="afterLeave"):(G="before"+b.charAt(0).toUpperCase()+b.substr(1),F=b);"enter"!==b&&"move"!==b&&(E=B(a,b,e,C,G));f=B(a,b,e,C,F)}if(E||f)return{start:function(){function b(c){n=
!0;t();ca(a,e);g.complete(c)}var d,k=[];E&&k.push(function(a){d=E(a)});k.length?k.push(function(a){t();a(!0)}):t();f&&k.push(function(a){d=f(a)});var n=!1,g=new c({end:function(){n||((d||H)(void 0),b(void 0))},cancel:function(){n||((d||H)(!0),b(!0))}});c.chain(k,b);return g}}}}]}]).provider("$$animateJsDriver",["$$animationProvider",function(a){a.drivers.push("$$animateJsDriver");this.$get=["$$animateJs","$$AnimateRunner",function(a,c){function d(c){return a(c.element,c.event,c.classes,c.options)}
return function(a){if(a.from&&a.to){var b=d(a.from),n=d(a.to);if(b||n)return{start:function(){function a(){return function(){u(d,function(a){a.end()})}}var d=[];b&&d.push(b.start());n&&d.push(n.start());c.all(d,function(a){e.complete(a)});var e=new c({end:a(),cancel:a()});return e}}}else return d(a)}}]}])})(window,window.angular);
//# sourceMappingURL=angular-animate.min.js.map
/*!
* ionic.bundle.js is a concatenation of:
* ionic.js, angular.js, angular-animate.js,
* angular-sanitize.js, angular-ui-router.js,
* and ionic-angular.js
*/
/*
AngularJS v1.4.3
(c) 2010-2015 Google, Inc. http://angularjs.org
License: MIT
*/
(function(n,h,p){'use strict';function E(a){var f=[];r(f,h.noop).chars(a);return f.join("")}function g(a,f){var d={},c=a.split(","),b;for(b=0;b<c.length;b++)d[f?h.lowercase(c[b]):c[b]]=!0;return d}function F(a,f){function d(a,b,d,l){b=h.lowercase(b);if(s[b])for(;e.last()&&t[e.last()];)c("",e.last());u[b]&&e.last()==b&&c("",b);(l=v[b]||!!l)||e.push(b);var m={};d.replace(G,function(b,a,f,c,d){m[a]=q(f||c||d||"")});f.start&&f.start(b,m,l)}function c(b,a){var c=0,d;if(a=h.lowercase(a))for(c=e.length-
1;0<=c&&e[c]!=a;c--);if(0<=c){for(d=e.length-1;d>=c;d--)f.end&&f.end(e[d]);e.length=c}}"string"!==typeof a&&(a=null===a||"undefined"===typeof a?"":""+a);var b,k,e=[],m=a,l;for(e.last=function(){return e[e.length-1]};a;){l="";k=!0;if(e.last()&&w[e.last()])a=a.replace(new RegExp("([\\W\\w]*)<\\s*\\/\\s*"+e.last()+"[^>]*>","i"),function(a,b){b=b.replace(H,"$1").replace(I,"$1");f.chars&&f.chars(q(b));return""}),c("",e.last());else{if(0===a.indexOf("\x3c!--"))b=a.indexOf("--",4),0<=b&&a.lastIndexOf("--\x3e",
b)===b&&(f.comment&&f.comment(a.substring(4,b)),a=a.substring(b+3),k=!1);else if(x.test(a)){if(b=a.match(x))a=a.replace(b[0],""),k=!1}else if(J.test(a)){if(b=a.match(y))a=a.substring(b[0].length),b[0].replace(y,c),k=!1}else K.test(a)&&((b=a.match(z))?(b[4]&&(a=a.substring(b[0].length),b[0].replace(z,d)),k=!1):(l+="<",a=a.substring(1)));k&&(b=a.indexOf("<"),l+=0>b?a:a.substring(0,b),a=0>b?"":a.substring(b),f.chars&&f.chars(q(l)))}if(a==m)throw L("badparse",a);m=a}c()}function q(a){if(!a)return"";A.innerHTML=
a.replace(/</g,"<");return A.textContent}function B(a){return a.replace(/&/g,"&").replace(M,function(a){var d=a.charCodeAt(0);a=a.charCodeAt(1);return"&#"+(1024*(d-55296)+(a-56320)+65536)+";"}).replace(N,function(a){return"&#"+a.charCodeAt(0)+";"}).replace(/</g,"<").replace(/>/g,">")}function r(a,f){var d=!1,c=h.bind(a,a.push);return{start:function(a,k,e){a=h.lowercase(a);!d&&w[a]&&(d=a);d||!0!==C[a]||(c("<"),c(a),h.forEach(k,function(d,e){var k=h.lowercase(e),g="img"===a&&"src"===k||
"background"===k;!0!==O[k]||!0===D[k]&&!f(d,g)||(c(" "),c(e),c('="'),c(B(d)),c('"'))}),c(e?"/>":">"))},end:function(a){a=h.lowercase(a);d||!0!==C[a]||(c("</"),c(a),c(">"));a==d&&(d=!1)},chars:function(a){d||c(B(a))}}}var L=h.$$minErr("$sanitize"),z=/^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/,y=/^<\/\s*([\w:-]+)[^>]*>/,G=/([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,K=/^</,J=/^<\//,H=/\x3c!--(.*?)--\x3e/g,x=/<!DOCTYPE([^>]*?)>/i,
I=/<!\[CDATA\[(.*?)]]\x3e/g,M=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,N=/([^\#-~| |!])/g,v=g("area,br,col,hr,img,wbr");n=g("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr");p=g("rp,rt");var u=h.extend({},p,n),s=h.extend({},n,g("address,article,aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")),t=h.extend({},p,g("a,abbr,acronym,b,bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small,span,strike,strong,sub,sup,time,tt,u,var"));
n=g("circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,stop,svg,switch,text,title,tspan,use");var w=g("script,style"),C=h.extend({},v,s,t,u,n),D=g("background,cite,href,longdesc,src,usemap,xlink:href");n=g("abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,valign,value,vspace,width");
p=g("accent-height,accumulate,additive,alphabetic,arabic-form,ascent,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan",
!0);var O=h.extend({},D,p,n),A=document.createElement("pre");h.module("ngSanitize",[]).provider("$sanitize",function(){this.$get=["$$sanitizeUri",function(a){return function(f){var d=[];F(f,r(d,function(c,b){return!/^unsafe/.test(a(c,b))}));return d.join("")}}]});h.module("ngSanitize").filter("linky",["$sanitize",function(a){var f=/((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,d=/^mailto:/i;return function(c,b){function k(a){a&&g.push(E(a))}function e(a,
c){g.push("<a ");h.isDefined(b)&&g.push('target="',b,'" ');g.push('href="',a.replace(/"/g,"""),'">');k(c);g.push("</a>")}if(!c)return c;for(var m,l=c,g=[],n,p;m=l.match(f);)n=m[0],m[2]||m[4]||(n=(m[3]?"http://":"mailto:")+n),p=m.index,k(l.substr(0,p)),e(n,m[0].replace(d,"")),l=l.substring(p+m[0].length);k(l);return a(g.join(""))}}])})(window,window.angular);
//# sourceMappingURL=angular-sanitize.min.js.map
/*!
* ionic.bundle.js is a concatenation of:
* ionic.js, angular.js, angular-animate.js,
* angular-sanitize.js, angular-ui-router.js,
* and ionic-angular.js
*/
/**
* State-based routing for AngularJS
* @version v0.2.13
* @link http://angular-ui.github.com/
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
"undefined"!=typeof module&&"undefined"!=typeof exports&&module.exports===exports&&(module.exports="ui.router"),function(a,b,c){"use strict";function d(a,b){return M(new(M(function(){},{prototype:a})),b)}function e(a){return L(arguments,function(b){b!==a&&L(b,function(b,c){a.hasOwnProperty(c)||(a[c]=b)})}),a}function f(a,b){var c=[];for(var d in a.path){if(a.path[d]!==b.path[d])break;c.push(a.path[d])}return c}function g(a){if(Object.keys)return Object.keys(a);var c=[];return b.forEach(a,function(a,b){c.push(b)}),c}function h(a,b){if(Array.prototype.indexOf)return a.indexOf(b,Number(arguments[2])||0);var c=a.length>>>0,d=Number(arguments[2])||0;for(d=0>d?Math.ceil(d):Math.floor(d),0>d&&(d+=c);c>d;d++)if(d in a&&a[d]===b)return d;return-1}function i(a,b,c,d){var e,i=f(c,d),j={},k=[];for(var l in i)if(i[l].params&&(e=g(i[l].params),e.length))for(var m in e)h(k,e[m])>=0||(k.push(e[m]),j[e[m]]=a[e[m]]);return M({},j,b)}function j(a,b,c){if(!c){c=[];for(var d in a)c.push(d)}for(var e=0;e<c.length;e++){var f=c[e];if(a[f]!=b[f])return!1}return!0}function k(a,b){var c={};return L(a,function(a){c[a]=b[a]}),c}function l(a){var b={},c=Array.prototype.concat.apply(Array.prototype,Array.prototype.slice.call(arguments,1));for(var d in a)-1==h(c,d)&&(b[d]=a[d]);return b}function m(a,b){var c=K(a),d=c?[]:{};return L(a,function(a,e){b(a,e)&&(d[c?d.length:e]=a)}),d}function n(a,b){var c=K(a)?[]:{};return L(a,function(a,d){c[d]=b(a,d)}),c}function o(a,b){var d=1,f=2,i={},j=[],k=i,m=M(a.when(i),{$$promises:i,$$values:i});this.study=function(i){function n(a,c){if(s[c]!==f){if(r.push(c),s[c]===d)throw r.splice(0,h(r,c)),new Error("Cyclic dependency: "+r.join(" -> "));if(s[c]=d,I(a))q.push(c,[function(){return b.get(a)}],j);else{var e=b.annotate(a);L(e,function(a){a!==c&&i.hasOwnProperty(a)&&n(i[a],a)}),q.push(c,a,e)}r.pop(),s[c]=f}}function o(a){return J(a)&&a.then&&a.$$promises}if(!J(i))throw new Error("'invocables' must be an object");var p=g(i||{}),q=[],r=[],s={};return L(i,n),i=r=s=null,function(d,f,g){function h(){--u||(v||e(t,f.$$values),r.$$values=t,r.$$promises=r.$$promises||!0,delete r.$$inheritedValues,n.resolve(t))}function i(a){r.$$failure=a,n.reject(a)}function j(c,e,f){function j(a){l.reject(a),i(a)}function k(){if(!G(r.$$failure))try{l.resolve(b.invoke(e,g,t)),l.promise.then(function(a){t[c]=a,h()},j)}catch(a){j(a)}}var l=a.defer(),m=0;L(f,function(a){s.hasOwnProperty(a)&&!d.hasOwnProperty(a)&&(m++,s[a].then(function(b){t[a]=b,--m||k()},j))}),m||k(),s[c]=l.promise}if(o(d)&&g===c&&(g=f,f=d,d=null),d){if(!J(d))throw new Error("'locals' must be an object")}else d=k;if(f){if(!o(f))throw new Error("'parent' must be a promise returned by $resolve.resolve()")}else f=m;var n=a.defer(),r=n.promise,s=r.$$promises={},t=M({},d),u=1+q.length/3,v=!1;if(G(f.$$failure))return i(f.$$failure),r;f.$$inheritedValues&&e(t,l(f.$$inheritedValues,p)),M(s,f.$$promises),f.$$values?(v=e(t,l(f.$$values,p)),r.$$inheritedValues=l(f.$$values,p),h()):(f.$$inheritedValues&&(r.$$inheritedValues=l(f.$$inheritedValues,p)),f.then(h,i));for(var w=0,x=q.length;x>w;w+=3)d.hasOwnProperty(q[w])?h():j(q[w],q[w+1],q[w+2]);return r}},this.resolve=function(a,b,c,d){return this.study(a)(b,c,d)}}function p(a,b,c){this.fromConfig=function(a,b,c){return G(a.template)?this.fromString(a.template,b):G(a.templateUrl)?this.fromUrl(a.templateUrl,b):G(a.templateProvider)?this.fromProvider(a.templateProvider,b,c):null},this.fromString=function(a,b){return H(a)?a(b):a},this.fromUrl=function(c,d){return H(c)&&(c=c(d)),null==c?null:a.get(c,{cache:b,headers:{Accept:"text/html"}}).then(function(a){return a.data})},this.fromProvider=function(a,b,d){return c.invoke(a,null,d||{params:b})}}function q(a,b,e){function f(b,c,d,e){if(q.push(b),o[b])return o[b];if(!/^\w+(-+\w+)*(?:\[\])?$/.test(b))throw new Error("Invalid parameter name '"+b+"' in pattern '"+a+"'");if(p[b])throw new Error("Duplicate parameter name '"+b+"' in pattern '"+a+"'");return p[b]=new O.Param(b,c,d,e),p[b]}function g(a,b,c){var d=["",""],e=a.replace(/[\\\[\]\^$*+?.()|{}]/g,"\\$&");if(!b)return e;switch(c){case!1:d=["(",")"];break;case!0:d=["?(",")?"];break;default:d=["("+c+"|",")?"]}return e+d[0]+b+d[1]}function h(c,e){var f,g,h,i,j;return f=c[2]||c[3],j=b.params[f],h=a.substring(m,c.index),g=e?c[4]:c[4]||("*"==c[1]?".*":null),i=O.type(g||"string")||d(O.type("string"),{pattern:new RegExp(g)}),{id:f,regexp:g,segment:h,type:i,cfg:j}}b=M({params:{}},J(b)?b:{});var i,j=/([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,k=/([:]?)([\w\[\]-]+)|\{([\w\[\]-]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,l="^",m=0,n=this.segments=[],o=e?e.params:{},p=this.params=e?e.params.$$new():new O.ParamSet,q=[];this.source=a;for(var r,s,t;(i=j.exec(a))&&(r=h(i,!1),!(r.segment.indexOf("?")>=0));)s=f(r.id,r.type,r.cfg,"path"),l+=g(r.segment,s.type.pattern.source,s.squash),n.push(r.segment),m=j.lastIndex;t=a.substring(m);var u=t.indexOf("?");if(u>=0){var v=this.sourceSearch=t.substring(u);if(t=t.substring(0,u),this.sourcePath=a.substring(0,m+u),v.length>0)for(m=0;i=k.exec(v);)r=h(i,!0),s=f(r.id,r.type,r.cfg,"search"),m=j.lastIndex}else this.sourcePath=a,this.sourceSearch="";l+=g(t)+(b.strict===!1?"/?":"")+"$",n.push(t),this.regexp=new RegExp(l,b.caseInsensitive?"i":c),this.prefix=n[0],this.$$paramNames=q}function r(a){M(this,a)}function s(){function a(a){return null!=a?a.toString().replace(/\//g,"%2F"):a}function e(a){return null!=a?a.toString().replace(/%2F/g,"/"):a}function f(a){return this.pattern.test(a)}function i(){return{strict:t,caseInsensitive:p}}function j(a){return H(a)||K(a)&&H(a[a.length-1])}function k(){for(;x.length;){var a=x.shift();if(a.pattern)throw new Error("You cannot override a type's .pattern at runtime.");b.extend(v[a.name],o.invoke(a.def))}}function l(a){M(this,a||{})}O=this;var o,p=!1,t=!0,u=!1,v={},w=!0,x=[],y={string:{encode:a,decode:e,is:f,pattern:/[^/]*/},"int":{encode:a,decode:function(a){return parseInt(a,10)},is:function(a){return G(a)&&this.decode(a.toString())===a},pattern:/\d+/},bool:{encode:function(a){return a?1:0},decode:function(a){return 0!==parseInt(a,10)},is:function(a){return a===!0||a===!1},pattern:/0|1/},date:{encode:function(a){return this.is(a)?[a.getFullYear(),("0"+(a.getMonth()+1)).slice(-2),("0"+a.getDate()).slice(-2)].join("-"):c},decode:function(a){if(this.is(a))return a;var b=this.capture.exec(a);return b?new Date(b[1],b[2]-1,b[3]):c},is:function(a){return a instanceof Date&&!isNaN(a.valueOf())},equals:function(a,b){return this.is(a)&&this.is(b)&&a.toISOString()===b.toISOString()},pattern:/[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,capture:/([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/},json:{encode:b.toJson,decode:b.fromJson,is:b.isObject,equals:b.equals,pattern:/[^/]*/},any:{encode:b.identity,decode:b.identity,is:b.identity,equals:b.equals,pattern:/.*/}};s.$$getDefaultValue=function(a){if(!j(a.value))return a.value;if(!o)throw new Error("Injectable functions cannot be called at configuration time");return o.invoke(a.value)},this.caseInsensitive=function(a){return G(a)&&(p=a),p},this.strictMode=function(a){return G(a)&&(t=a),t},this.defaultSquashPolicy=function(a){if(!G(a))return u;if(a!==!0&&a!==!1&&!I(a))throw new Error("Invalid squash policy: "+a+". Valid policies: false, true, arbitrary-string");return u=a,a},this.compile=function(a,b){return new q(a,M(i(),b))},this.isMatcher=function(a){if(!J(a))return!1;var b=!0;return L(q.prototype,function(c,d){H(c)&&(b=b&&G(a[d])&&H(a[d]))}),b},this.type=function(a,b,c){if(!G(b))return v[a];if(v.hasOwnProperty(a))throw new Error("A type named '"+a+"' has already been defined.");return v[a]=new r(M({name:a},b)),c&&(x.push({name:a,def:c}),w||k()),this},L(y,function(a,b){v[b]=new r(M({name:b},a))}),v=d(v,{}),this.$get=["$injector",function(a){return o=a,w=!1,k(),L(y,function(a,b){v[b]||(v[b]=new r(a))}),this}],this.Param=function(a,b,d,e){function f(a){var b=J(a)?g(a):[],c=-1===h(b,"value")&&-1===h(b,"type")&&-1===h(b,"squash")&&-1===h(b,"array");return c&&(a={value:a}),a.$$fn=j(a.value)?a.value:function(){return a.value},a}function i(b,c,d){if(b.type&&c)throw new Error("Param '"+a+"' has two type configurations.");return c?c:b.type?b.type instanceof r?b.type:new r(b.type):"config"===d?v.any:v.string}function k(){var b={array:"search"===e?"auto":!1},c=a.match(/\[\]$/)?{array:!0}:{};return M(b,c,d).array}function l(a,b){var c=a.squash;if(!b||c===!1)return!1;if(!G(c)||null==c)return u;if(c===!0||I(c))return c;throw new Error("Invalid squash policy: '"+c+"'. Valid policies: false, true, or arbitrary string")}function p(a,b,d,e){var f,g,i=[{from:"",to:d||b?c:""},{from:null,to:d||b?c:""}];return f=K(a.replace)?a.replace:[],I(e)&&f.push({from:e,to:c}),g=n(f,function(a){return a.from}),m(i,function(a){return-1===h(g,a.from)}).concat(f)}function q(){if(!o)throw new Error("Injectable functions cannot be called at configuration time");return o.invoke(d.$$fn)}function s(a){function b(a){return function(b){return b.from===a}}function c(a){var c=n(m(w.replace,b(a)),function(a){return a.to});return c.length?c[0]:a}return a=c(a),G(a)?w.type.decode(a):q()}function t(){return"{Param:"+a+" "+b+" squash: '"+z+"' optional: "+y+"}"}var w=this;d=f(d),b=i(d,b,e);var x=k();b=x?b.$asArray(x,"search"===e):b,"string"!==b.name||x||"path"!==e||d.value!==c||(d.value="");var y=d.value!==c,z=l(d,y),A=p(d,x,y,z);M(this,{id:a,type:b,location:e,array:x,squash:z,replace:A,isOptional:y,value:s,dynamic:c,config:d,toString:t})},l.prototype={$$new:function(){return d(this,M(new l,{$$parent:this}))},$$keys:function(){for(var a=[],b=[],c=this,d=g(l.prototype);c;)b.push(c),c=c.$$parent;return b.reverse(),L(b,function(b){L(g(b),function(b){-1===h(a,b)&&-1===h(d,b)&&a.push(b)})}),a},$$values:function(a){var b={},c=this;return L(c.$$keys(),function(d){b[d]=c[d].value(a&&a[d])}),b},$$equals:function(a,b){var c=!0,d=this;return L(d.$$keys(),function(e){var f=a&&a[e],g=b&&b[e];d[e].type.equals(f,g)||(c=!1)}),c},$$validates:function(a){var b,c,d,e=!0,f=this;return L(this.$$keys(),function(g){d=f[g],c=a[g],b=!c&&d.isOptional,e=e&&(b||!!d.type.is(c))}),e},$$parent:c},this.ParamSet=l}function t(a,d){function e(a){var b=/^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(a.source);return null!=b?b[1].replace(/\\(.)/g,"$1"):""}function f(a,b){return a.replace(/\$(\$|\d{1,2})/,function(a,c){return b["$"===c?0:Number(c)]})}function g(a,b,c){if(!c)return!1;var d=a.invoke(b,b,{$match:c});return G(d)?d:!0}function h(d,e,f,g){function h(a,b,c){return"/"===p?a:b?p.slice(0,-1)+a:c?p.slice(1)+a:a}function m(a){function b(a){var b=a(f,d);return b?(I(b)&&d.replace().url(b),!0):!1}if(!a||!a.defaultPrevented){var e=o&&d.url()===o;if(o=c,e)return!0;var g,h=j.length;for(g=0;h>g;g++)if(b(j[g]))return;k&&b(k)}}function n(){return i=i||e.$on("$locationChangeSuccess",m)}var o,p=g.baseHref(),q=d.url();return l||n(),{sync:function(){m()},listen:function(){return n()},update:function(a){return a?void(q=d.url()):void(d.url()!==q&&(d.url(q),d.replace()))},push:function(a,b,e){d.url(a.format(b||{})),o=e&&e.$$avoidResync?d.url():c,e&&e.replace&&d.replace()},href:function(c,e,f){if(!c.validates(e))return null;var g=a.html5Mode();b.isObject(g)&&(g=g.enabled);var i=c.format(e);if(f=f||{},g||null===i||(i="#"+a.hashPrefix()+i),i=h(i,g,f.absolute),!f.absolute||!i)return i;var j=!g&&i?"/":"",k=d.port();return k=80===k||443===k?"":":"+k,[d.protocol(),"://",d.host(),k,j,i].join("")}}}var i,j=[],k=null,l=!1;this.rule=function(a){if(!H(a))throw new Error("'rule' must be a function");return j.push(a),this},this.otherwise=function(a){if(I(a)){var b=a;a=function(){return b}}else if(!H(a))throw new Error("'rule' must be a function");return k=a,this},this.when=function(a,b){var c,h=I(b);if(I(a)&&(a=d.compile(a)),!h&&!H(b)&&!K(b))throw new Error("invalid 'handler' in when()");var i={matcher:function(a,b){return h&&(c=d.compile(b),b=["$match",function(a){return c.format(a)}]),M(function(c,d){return g(c,b,a.exec(d.path(),d.search()))},{prefix:I(a.prefix)?a.prefix:""})},regex:function(a,b){if(a.global||a.sticky)throw new Error("when() RegExp must not be global or sticky");return h&&(c=b,b=["$match",function(a){return f(c,a)}]),M(function(c,d){return g(c,b,a.exec(d.path()))},{prefix:e(a)})}},j={matcher:d.isMatcher(a),regex:a instanceof RegExp};for(var k in j)if(j[k])return this.rule(i[k](a,b));throw new Error("invalid 'what' in when()")},this.deferIntercept=function(a){a===c&&(a=!0),l=a},this.$get=h,h.$inject=["$location","$rootScope","$injector","$browser"]}function u(a,e){function f(a){return 0===a.indexOf(".")||0===a.indexOf("^")}function l(a,b){if(!a)return c;var d=I(a),e=d?a:a.name,g=f(e);if(g){if(!b)throw new Error("No reference point given for path '"+e+"'");b=l(b);for(var h=e.split("."),i=0,j=h.length,k=b;j>i;i++)if(""!==h[i]||0!==i){if("^"!==h[i])break;if(!k.parent)throw new Error("Path '"+e+"' not valid for state '"+b.name+"'");k=k.parent}else k=b;h=h.slice(i).join("."),e=k.name+(k.name&&h?".":"")+h}var m=y[e];return!m||!d&&(d||m!==a&&m.self!==a)?c:m}function m(a,b){z[a]||(z[a]=[]),z[a].push(b)}function o(a){for(var b=z[a]||[];b.length;)p(b.shift())}function p(b){b=d(b,{self:b,resolve:b.resolve||{},toString:function(){return this.name}});var c=b.name;if(!I(c)||c.indexOf("@")>=0)throw new Error("State must have a valid name");if(y.hasOwnProperty(c))throw new Error("State '"+c+"'' is already defined");var e=-1!==c.indexOf(".")?c.substring(0,c.lastIndexOf(".")):I(b.parent)?b.parent:J(b.parent)&&I(b.parent.name)?b.parent.name:"";if(e&&!y[e])return m(e,b.self);for(var f in B)H(B[f])&&(b[f]=B[f](b,B.$delegates[f]));return y[c]=b,!b[A]&&b.url&&a.when(b.url,["$match","$stateParams",function(a,c){x.$current.navigable==b&&j(a,c)||x.transitionTo(b,a,{inherit:!0,location:!1})}]),o(c),b}function q(a){return a.indexOf("*")>-1}function r(a){var b=a.split("."),c=x.$current.name.split(".");if("**"===b[0]&&(c=c.slice(h(c,b[1])),c.unshift("**")),"**"===b[b.length-1]&&(c.splice(h(c,b[b.length-2])+1,Number.MAX_VALUE),c.push("**")),b.length!=c.length)return!1;for(var d=0,e=b.length;e>d;d++)"*"===b[d]&&(c[d]="*");return c.join("")===b.join("")}function s(a,b){return I(a)&&!G(b)?B[a]:H(b)&&I(a)?(B[a]&&!B.$delegates[a]&&(B.$delegates[a]=B[a]),B[a]=b,this):this}function t(a,b){return J(a)?b=a:b.name=a,p(b),this}function u(a,e,f,h,m,o,p){function s(b,c,d,f){var g=a.$broadcast("$stateNotFound",b,c,d);if(g.defaultPrevented)return p.update(),B;if(!g.retry)return null;if(f.$retry)return p.update(),C;var h=x.transition=e.when(g.retry);return h.then(function(){return h!==x.transition?u:(b.options.$retry=!0,x.transitionTo(b.to,b.toParams,b.options))},function(){return B}),p.update(),h}function t(a,c,d,g,i,j){var l=d?c:k(a.params.$$keys(),c),n={$stateParams:l};i.resolve=m.resolve(a.resolve,n,i.resolve,a);var o=[i.resolve.then(function(a){i.globals=a})];return g&&o.push(g),L(a.views,function(c,d){var e=c.resolve&&c.resolve!==a.resolve?c.resolve:{};e.$template=[function(){return f.load(d,{view:c,locals:n,params:l,notify:j.notify})||""}],o.push(m.resolve(e,n,i.resolve,a).then(function(f){if(H(c.controllerProvider)||K(c.controllerProvider)){var g=b.extend({},e,n);f.$$controller=h.invoke(c.controllerProvider,null,g)}else f.$$controller=c.controller;f.$$state=a,f.$$controllerAs=c.controllerAs,i[d]=f}))}),e.all(o).then(function(){return i})}var u=e.reject(new Error("transition superseded")),z=e.reject(new Error("transition prevented")),B=e.reject(new Error("transition aborted")),C=e.reject(new Error("transition failed"));return w.locals={resolve:null,globals:{$stateParams:{}}},x={params:{},current:w.self,$current:w,transition:null},x.reload=function(){return x.transitionTo(x.current,o,{reload:!0,inherit:!1,notify:!0})},x.go=function(a,b,c){return x.transitionTo(a,b,M({inherit:!0,relative:x.$current},c))},x.transitionTo=function(b,c,f){c=c||{},f=M({location:!0,inherit:!1,relative:null,notify:!0,reload:!1,$retry:!1},f||{});var g,j=x.$current,m=x.params,n=j.path,q=l(b,f.relative);if(!G(q)){var r={to:b,toParams:c,options:f},y=s(r,j.self,m,f);if(y)return y;if(b=r.to,c=r.toParams,f=r.options,q=l(b,f.relative),!G(q)){if(!f.relative)throw new Error("No such state '"+b+"'");throw new Error("Could not resolve '"+b+"' from state '"+f.relative+"'")}}if(q[A])throw new Error("Cannot transition to abstract state '"+b+"'");if(f.inherit&&(c=i(o,c||{},x.$current,q)),!q.params.$$validates(c))return C;c=q.params.$$values(c),b=q;var B=b.path,D=0,E=B[D],F=w.locals,H=[];if(!f.reload)for(;E&&E===n[D]&&E.ownParams.$$equals(c,m);)F=H[D]=E.locals,D++,E=B[D];if(v(b,j,F,f))return b.self.reloadOnSearch!==!1&&p.update(),x.transition=null,e.when(x.current);if(c=k(b.params.$$keys(),c||{}),f.notify&&a.$broadcast("$stateChangeStart",b.self,c,j.self,m).defaultPrevented)return p.update(),z;for(var I=e.when(F),J=D;J<B.length;J++,E=B[J])F=H[J]=d(F),I=t(E,c,E===b,I,F,f);var K=x.transition=I.then(function(){var d,e,g;if(x.transition!==K)return u;for(d=n.length-1;d>=D;d--)g=n[d],g.self.onExit&&h.invoke(g.self.onExit,g.self,g.locals.globals),g.locals=null;for(d=D;d<B.length;d++)e=B[d],e.locals=H[d],e.self.onEnter&&h.invoke(e.self.onEnter,e.self,e.locals.globals);return x.transition!==K?u:(x.$current=b,x.current=b.self,x.params=c,N(x.params,o),x.transition=null,f.location&&b.navigable&&p.push(b.navigable.url,b.navigable.locals.globals.$stateParams,{$$avoidResync:!0,replace:"replace"===f.location}),f.notify&&a.$broadcast("$stateChangeSuccess",b.self,c,j.self,m),p.update(!0),x.current)},function(d){return x.transition!==K?u:(x.transition=null,g=a.$broadcast("$stateChangeError",b.self,c,j.self,m,d),g.defaultPrevented||p.update(),e.reject(d))});return K},x.is=function(a,b,d){d=M({relative:x.$current},d||{});var e=l(a,d.relative);return G(e)?x.$current!==e?!1:b?j(e.params.$$values(b),o):!0:c},x.includes=function(a,b,d){if(d=M({relative:x.$current},d||{}),I(a)&&q(a)){if(!r(a))return!1;a=x.$current.name}var e=l(a,d.relative);return G(e)?G(x.$current.includes[e.name])?b?j(e.params.$$values(b),o,g(b)):!0:!1:c},x.href=function(a,b,d){d=M({lossy:!0,inherit:!0,absolute:!1,relative:x.$current},d||{});var e=l(a,d.relative);if(!G(e))return null;d.inherit&&(b=i(o,b||{},x.$current,e));var f=e&&d.lossy?e.navigable:e;return f&&f.url!==c&&null!==f.url?p.href(f.url,k(e.params.$$keys(),b||{}),{absolute:d.absolute}):null},x.get=function(a,b){if(0===arguments.length)return n(g(y),function(a){return y[a].self});var c=l(a,b||x.$current);return c&&c.self?c.self:null},x}function v(a,b,c,d){return a!==b||(c!==b.locals||d.reload)&&a.self.reloadOnSearch!==!1?void 0:!0}var w,x,y={},z={},A="abstract",B={parent:function(a){if(G(a.parent)&&a.parent)return l(a.parent);var b=/^(.+)\.[^.]+$/.exec(a.name);return b?l(b[1]):w},data:function(a){return a.parent&&a.parent.data&&(a.data=a.self.data=M({},a.parent.data,a.data)),a.data},url:function(a){var b=a.url,c={params:a.params||{}};if(I(b))return"^"==b.charAt(0)?e.compile(b.substring(1),c):(a.parent.navigable||w).url.concat(b,c);if(!b||e.isMatcher(b))return b;throw new Error("Invalid url '"+b+"' in state '"+a+"'")},navigable:function(a){return a.url?a:a.parent?a.parent.navigable:null},ownParams:function(a){var b=a.url&&a.url.params||new O.ParamSet;return L(a.params||{},function(a,c){b[c]||(b[c]=new O.Param(c,null,a,"config"))}),b},params:function(a){return a.parent&&a.parent.params?M(a.parent.params.$$new(),a.ownParams):new O.ParamSet},views:function(a){var b={};return L(G(a.views)?a.views:{"":a},function(c,d){d.indexOf("@")<0&&(d+="@"+a.parent.name),b[d]=c}),b},path:function(a){return a.parent?a.parent.path.concat(a):[]},includes:function(a){var b=a.parent?M({},a.parent.includes):{};return b[a.name]=!0,b},$delegates:{}};w=p({name:"",url:"^",views:null,"abstract":!0}),w.navigable=null,this.decorator=s,this.state=t,this.$get=u,u.$inject=["$rootScope","$q","$view","$injector","$resolve","$stateParams","$urlRouter","$location","$urlMatcherFactory"]}function v(){function a(a,b){return{load:function(c,d){var e,f={template:null,controller:null,view:null,locals:null,notify:!0,async:!0,params:{}};return d=M(f,d),d.view&&(e=b.fromConfig(d.view,d.params,d.locals)),e&&d.notify&&a.$broadcast("$viewContentLoading",d),e}}}this.$get=a,a.$inject=["$rootScope","$templateFactory"]}function w(){var a=!1;this.useAnchorScroll=function(){a=!0},this.$get=["$anchorScroll","$timeout",function(b,c){return a?b:function(a){c(function(){a[0].scrollIntoView()},0,!1)}}]}function x(a,c,d,e){function f(){return c.has?function(a){return c.has(a)?c.get(a):null}:function(a){try{return c.get(a)}catch(b){return null}}}function g(a,b){var c=function(){return{enter:function(a,b,c){b.after(a),c()},leave:function(a,b){a.remove(),b()}}};if(j)return{enter:function(a,b,c){var d=j.enter(a,null,b,c);d&&d.then&&d.then(c)},leave:function(a,b){var c=j.leave(a,b);c&&c.then&&c.then(b)}};if(i){var d=i&&i(b,a);return{enter:function(a,b,c){d.enter(a,null,b),c()},leave:function(a,b){d.leave(a),b()}}}return c()}var h=f(),i=h("$animator"),j=h("$animate"),k={restrict:"ECA",terminal:!0,priority:400,transclude:"element",compile:function(c,f,h){return function(c,f,i){function j(){l&&(l.remove(),l=null),n&&(n.$destroy(),n=null),m&&(r.leave(m,function(){l=null}),l=m,m=null)}function k(g){var k,l=z(c,i,f,e),s=l&&a.$current&&a.$current.locals[l];if(g||s!==o){k=c.$new(),o=a.$current.locals[l];var t=h(k,function(a){r.enter(a,f,function(){n&&n.$emit("$viewContentAnimationEnded"),(b.isDefined(q)&&!q||c.$eval(q))&&d(a)}),j()});m=t,n=k,n.$emit("$viewContentLoaded"),n.$eval(p)}}var l,m,n,o,p=i.onload||"",q=i.autoscroll,r=g(i,c);c.$on("$stateChangeSuccess",function(){k(!1)}),c.$on("$viewContentLoading",function(){k(!1)}),k(!0)}}};return k}function y(a,b,c,d){return{restrict:"ECA",priority:-400,compile:function(e){var f=e.html();return function(e,g,h){var i=c.$current,j=z(e,h,g,d),k=i&&i.locals[j];if(k){g.data("$uiView",{name:j,state:k.$$state}),g.html(k.$template?k.$template:f);var l=a(g.contents());if(k.$$controller){k.$scope=e;var m=b(k.$$controller,k);k.$$controllerAs&&(e[k.$$controllerAs]=m),g.data("$ngControllerController",m),g.children().data("$ngControllerController",m)}l(e)}}}}}function z(a,b,c,d){var e=d(b.uiView||b.name||"")(a),f=c.inheritedData("$uiView");return e.indexOf("@")>=0?e:e+"@"+(f?f.state.name:"")}function A(a,b){var c,d=a.match(/^\s*({[^}]*})\s*$/);if(d&&(a=b+"("+d[1]+")"),c=a.replace(/\n/g," ").match(/^([^(]+?)\s*(\((.*)\))?$/),!c||4!==c.length)throw new Error("Invalid state ref '"+a+"'");return{state:c[1],paramExpr:c[3]||null}}function B(a){var b=a.parent().inheritedData("$uiView");return b&&b.state&&b.state.name?b.state:void 0}function C(a,c){var d=["location","inherit","reload"];return{restrict:"A",require:["?^uiSrefActive","?^uiSrefActiveEq"],link:function(e,f,g,h){var i=A(g.uiSref,a.current.name),j=null,k=B(f)||a.$current,l=null,m="A"===f.prop("tagName"),n="FORM"===f[0].nodeName,o=n?"action":"href",p=!0,q={relative:k,inherit:!0},r=e.$eval(g.uiSrefOpts)||{};b.forEach(d,function(a){a in r&&(q[a]=r[a])});var s=function(c){if(c&&(j=b.copy(c)),p){l=a.href(i.state,j,q);var d=h[1]||h[0];return d&&d.$$setStateInfo(i.state,j),null===l?(p=!1,!1):void g.$set(o,l)}};i.paramExpr&&(e.$watch(i.paramExpr,function(a){a!==j&&s(a)},!0),j=b.copy(e.$eval(i.paramExpr))),s(),n||f.bind("click",function(b){var d=b.which||b.button;if(!(d>1||b.ctrlKey||b.metaKey||b.shiftKey||f.attr("target"))){var e=c(function(){a.go(i.state,j,q)});b.preventDefault();var g=m&&!l?1:0;b.preventDefault=function(){g--<=0&&c.cancel(e)}}})}}}function D(a,b,c){return{restrict:"A",controller:["$scope","$element","$attrs",function(b,d,e){function f(){g()?d.addClass(j):d.removeClass(j)}function g(){return"undefined"!=typeof e.uiSrefActiveEq?h&&a.is(h.name,i):h&&a.includes(h.name,i)}var h,i,j;j=c(e.uiSrefActiveEq||e.uiSrefActive||"",!1)(b),this.$$setStateInfo=function(b,c){h=a.get(b,B(d)),i=c,f()},b.$on("$stateChangeSuccess",f)}]}}function E(a){var b=function(b){return a.is(b)};return b.$stateful=!0,b}function F(a){var b=function(b){return a.includes(b)};return b.$stateful=!0,b}var G=b.isDefined,H=b.isFunction,I=b.isString,J=b.isObject,K=b.isArray,L=b.forEach,M=b.extend,N=b.copy;b.module("ui.router.util",["ng"]),b.module("ui.router.router",["ui.router.util"]),b.module("ui.router.state",["ui.router.router","ui.router.util"]),b.module("ui.router",["ui.router.state"]),b.module("ui.router.compat",["ui.router"]),o.$inject=["$q","$injector"],b.module("ui.router.util").service("$resolve",o),p.$inject=["$http","$templateCache","$injector"],b.module("ui.router.util").service("$templateFactory",p);var O;q.prototype.concat=function(a,b){var c={caseInsensitive:O.caseInsensitive(),strict:O.strictMode(),squash:O.defaultSquashPolicy()};return new q(this.sourcePath+a+this.sourceSearch,M(c,b),this)},q.prototype.toString=function(){return this.source},q.prototype.exec=function(a,b){function c(a){function b(a){return a.split("").reverse().join("")}function c(a){return a.replace(/\\-/,"-")}var d=b(a).split(/-(?!\\)/),e=n(d,b);return n(e,c).reverse()}var d=this.regexp.exec(a);if(!d)return null;b=b||{};var e,f,g,h=this.parameters(),i=h.length,j=this.segments.length-1,k={};if(j!==d.length-1)throw new Error("Unbalanced capture group in route '"+this.source+"'");for(e=0;j>e;e++){g=h[e];var l=this.params[g],m=d[e+1];for(f=0;f<l.replace;f++)l.replace[f].from===m&&(m=l.replace[f].to);m&&l.array===!0&&(m=c(m)),k[g]=l.value(m)}for(;i>e;e++)g=h[e],k[g]=this.params[g].value(b[g]);return k},q.prototype.parameters=function(a){return G(a)?this.params[a]||null:this.$$paramNames},q.prototype.validates=function(a){return this.params.$$validates(a)},q.prototype.format=function(a){function b(a){return encodeURIComponent(a).replace(/-/g,function(a){return"%5C%"+a.charCodeAt(0).toString(16).toUpperCase()})}a=a||{};var c=this.segments,d=this.parameters(),e=this.params;if(!this.validates(a))return null;var f,g=!1,h=c.length-1,i=d.length,j=c[0];for(f=0;i>f;f++){var k=h>f,l=d[f],m=e[l],o=m.value(a[l]),p=m.isOptional&&m.type.equals(m.value(),o),q=p?m.squash:!1,r=m.type.encode(o);if(k){var s=c[f+1];if(q===!1)null!=r&&(j+=K(r)?n(r,b).join("-"):encodeURIComponent(r)),j+=s;else if(q===!0){var t=j.match(/\/$/)?/\/?(.*)/:/(.*)/;j+=s.match(t)[1]}else I(q)&&(j+=q+s)}else{if(null==r||p&&q!==!1)continue;K(r)||(r=[r]),r=n(r,encodeURIComponent).join("&"+l+"="),j+=(g?"&":"?")+(l+"="+r),g=!0}}return j},r.prototype.is=function(){return!0},r.prototype.encode=function(a){return a},r.prototype.decode=function(a){return a},r.prototype.equals=function(a,b){return a==b},r.prototype.$subPattern=function(){var a=this.pattern.toString();return a.substr(1,a.length-2)},r.prototype.pattern=/.*/,r.prototype.toString=function(){return"{Type:"+this.name+"}"},r.prototype.$asArray=function(a,b){function d(a,b){function d(a,b){return function(){return a[b].apply(a,arguments)}}function e(a){return K(a)?a:G(a)?[a]:[]}function f(a){switch(a.length){case 0:return c;case 1:return"auto"===b?a[0]:a;default:return a}}function g(a){return!a}function h(a,b){return function(c){c=e(c);var d=n(c,a);return b===!0?0===m(d,g).length:f(d)}}function i(a){return function(b,c){var d=e(b),f=e(c);if(d.length!==f.length)return!1;for(var g=0;g<d.length;g++)if(!a(d[g],f[g]))return!1;return!0}}this.encode=h(d(a,"encode")),this.decode=h(d(a,"decode")),this.is=h(d(a,"is"),!0),this.equals=i(d(a,"equals")),this.pattern=a.pattern,this.$arrayMode=b}if(!a)return this;if("auto"===a&&!b)throw new Error("'auto' array mode is for query parameters only");return new d(this,a)},b.module("ui.router.util").provider("$urlMatcherFactory",s),b.module("ui.router.util").run(["$urlMatcherFactory",function(){}]),t.$inject=["$locationProvider","$urlMatcherFactoryProvider"],b.module("ui.router.router").provider("$urlRouter",t),u.$inject=["$urlRouterProvider","$urlMatcherFactoryProvider"],b.module("ui.router.state").value("$stateParams",{}).provider("$state",u),v.$inject=[],b.module("ui.router.state").provider("$view",v),b.module("ui.router.state").provider("$uiViewScroll",w),x.$inject=["$state","$injector","$uiViewScroll","$interpolate"],y.$inject=["$compile","$controller","$state","$interpolate"],b.module("ui.router.state").directive("uiView",x),b.module("ui.router.state").directive("uiView",y),C.$inject=["$state","$timeout"],D.$inject=["$state","$stateParams","$interpolate"],b.module("ui.router.state").directive("uiSref",C).directive("uiSrefActive",D).directive("uiSrefActiveEq",D),E.$inject=["$state"],F.$inject=["$state"],b.module("ui.router.state").filter("isState",E).filter("includedByState",F)}(window,window.angular);
/*!
* ionic.bundle.js is a concatenation of:
* ionic.js, angular.js, angular-animate.js,
* angular-sanitize.js, angular-ui-router.js,
* and ionic-angular.js
*/
/*!
* Copyright 2014 Drifty Co.
* http://drifty.com/
*
* Ionic, v1.1.1
* A powerful HTML5 mobile app framework.
* http://ionicframework.com/
*
* By @maxlynch, @benjsperry, @adamdbradley <3
*
* Licensed under the MIT license. Please see LICENSE for more information.
*
*/
!function(){function e(e,t,n,i,o,r){function a(i,a,c,s,l){function d(){N.resizeRequiresRefresh(w.__clientWidth,w.__clientHeight)&&g()}function f(){var e;return e={dataLength:0,width:0,height:0,resizeRequiresRefresh:function(t,n){var i=e.dataLength&&t&&n&&(t!==e.width||n!==e.height);return e.width=t,e.height=n,!!i},dataChangeRequiresRefresh:function(t){var n=t.length>0||t.length<e.dataLength;return e.dataLength=t.length,!!n}}}function h(){return T||(T=new e({afterItemsNode:M[0],containerNode:y,heightData:A,widthData:E,forceRefreshImages:!(!u(c.forceRefreshImages)||"false"===c.forceRefreshImages),keyExpression:B,renderBuffer:_,scope:i,scrollView:s.scrollView,transclude:l}))}function p(){var e=angular.element(w.__content.querySelector(".collection-repeat-after-container"));if(!e.length){var t=!1,n=[].filter.call(w.__content.childNodes,function(e){return ionic.DomUtil.contains(e,y)?(t=!0,!1):t});e=angular.element('<span class="collection-repeat-after-container">'),w.options.scrollingX&&e.addClass("horizontal"),e.append(n),w.__content.appendChild(e[0])}return e}function v(){R?m(R,A):A.computed=!0,L?m(L,E):E.computed=!0}function g(){var e=P.length>0;if(e&&(A.computed||E.computed)&&$(),e&&A.computed){if(A.value=V.height,!A.value)throw new Error('collection-repeat tried to compute the height of repeated elements "'+k+'", but was unable to. Please provide the "item-height" attribute. http://ionicframework.com/docs/api/directive/collectionRepeat/')}else!A.dynamic&&A.getValue&&(A.value=A.getValue());if(e&&E.computed){if(E.value=V.width,!E.value)throw new Error('collection-repeat tried to compute the width of repeated elements "'+k+'", but was unable to. Please provide the "item-width" attribute. http://ionicframework.com/docs/api/directive/collectionRepeat/')}else!E.dynamic&&E.getValue&&(E.value=E.getValue());h().refreshLayout()}function m(e,n){if(e){var i;try{i=t(e)}catch(o){e.trim().match(/\d+(px|%)$/)&&(e='"'+e+'"'),i=t(e)}var r=e.replace(/(\'|\"|px|%)/g,"").trim(),a=r.length&&!/([a-zA-Z]|\$|:|\?)/.test(r);if(n.attrValue=e,a){var c=parseInt(i());if(e.indexOf("%")>-1){var s=c/100;n.getValue=n===A?function(){return Math.floor(s*w.__clientHeight)}:function(){return Math.floor(s*w.__clientWidth)}}else n.value=c}else n.dynamic=!0,n.getValue=n===A?function(e,t){var n=i(e,t);return n.charAt&&"%"===n.charAt(n.length-1)?Math.floor(parseInt(n)/100*w.__clientHeight):parseInt(n)}:function(e,t){var n=i(e,t);return n.charAt&&"%"===n.charAt(n.length-1)?Math.floor(parseInt(n)/100*w.__clientWidth):parseInt(n)}}}function $(){O||l(H=i.$new(),function(e){e[0].removeAttribute("collection-repeat"),O=e[0]}),H[B]=(x(i)||[])[0],o.$$phase||H.$digest(),y.appendChild(O);var e=n.getComputedStyle(O);V.width=parseInt(e.width),V.height=parseInt(e.height),y.removeChild(O)}var w=s.scrollView,b=a[0],y=angular.element('<div class="collection-repeat-container">')[0];if(b.parentNode.replaceChild(y,b),w.options.scrollingX&&w.options.scrollingY)throw new Error("collection-repeat expected a parent x or y scrollView, not an xy scrollView.");var k=c.collectionRepeat,C=k.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);if(!C)throw new Error("collection-repeat expected expression in form of '_item_ in _collection_[ track by _id_]' but got '"+c.collectionRepeat+"'.");var T,B=C[1],I=C[2],x=t(I),A={},E={},V={},P=[],D=c.itemRenderBuffer||c.collectionBufferSize,_=angular.isDefined(D)?parseInt(D):S,R=c.itemHeight||c.collectionItemHeight,L=c.itemWidth||c.collectionItemWidth,M=p(),N=f();v(),s.$element.on("scroll-resize",g),angular.element(n).on("resize",d);var z=o.$on("$ionicExposeAside",ionic.animationFrameThrottle(function(){s.scrollView.resize(),d()}));r(g,0,!1),i.$watchCollection(x,function(e){if(P=e||(e=[]),!angular.isArray(e))throw new Error("collection-repeat expected an array for '"+I+"', but got a "+typeof value);i.$$postDigest(function(){h().setData(P),N.dataChangeRequiresRefresh(P)&&g()})}),i.$on("$destroy",function(){angular.element(n).off("resize",d),z(),s.$element&&s.$element.off("scroll-resize",g),O&&O.parentNode&&O.parentNode.removeChild(O),H&&H.$destroy(),H=O=null,T&&T.destroy(),T=null});var O,H}return{restrict:"A",priority:1e3,transclude:"element",$$tlb:!0,require:"^^$ionicScroll",link:a}}function t(e,t,n){var i={primaryPos:0,secondaryPos:0,primarySize:0,secondarySize:0,rowPrimarySize:0};return function(o){function r(){return a(!0)}function a(t){if(!a.destroyed){var n,o,r,l,u,d=ee.getScrollValue(),f=d+ee.scrollPrimarySize;ee.updateRenderRange(d,f),F=Math.max(0,F-T),W=Math.min(A.length-1,W+T);for(n in Z)(F>n||n>W)&&(r=Z[n],delete Z[n],j.push(r),r.isShown=!1);for(n=F;W>=n;n++)n>=A.length||Z[n]&&!t||(r=Z[n]||(Z[n]=j.length?j.pop():G.length?G.shift():new s),K.push(r),r.isShown=!0,u=r.scope,u.$index=n,u[C]=A[n],u.$first=0===n,u.$last=n===A.length-1,u.$middle=!(u.$first||u.$last),u.$odd=!(u.$even=0===(1&n)),u.$$disconnected&&ionic.Utils.reconnectScope(r.scope),l=ee.getDimensions(n),(r.secondaryPos!==l.secondaryPos||r.primaryPos!==l.primaryPos)&&(r.node.style[ionic.CSS.TRANSFORM]=O.replace(N,r.primaryPos=l.primaryPos).replace(z,r.secondaryPos=l.secondaryPos)),(r.secondarySize!==l.secondarySize||r.primarySize!==l.primarySize)&&(r.node.style.cssText=r.node.style.cssText.replace(y,H.replace(N,(r.primarySize=l.primarySize)+1).replace(z,r.secondarySize=l.secondarySize))));for(W===A.length-1&&(l=ee.getDimensions(A.length-1)||i,m.style[ionic.CSS.TRANSFORM]=O.replace(N,l.primaryPos+l.primarySize).replace(z,0));j.length;)r=j.pop(),r.scope.$broadcast("$collectionRepeatLeave"),ionic.Utils.disconnectScope(r.scope),G.push(r),r.node.style[ionic.CSS.TRANSFORM]="translate3d(-9999px,-9999px,0)",r.primaryPos=r.secondaryPos=null;if(w)for(n=0,o=K.length;o>n&&(r=K[n]);n++)if(r.images)for(var h,p=0,v=r.images.length;v>p&&(h=r.images[p]);p++){var g=h.src;h.src=b,h.src=g}if(t)for(var $=e.$$phase;K.length;)r=K.pop(),$||r.scope.$digest();else c()}}function c(){var t;c.running||(c.running=!0,n(function(){for(var n=e.$$phase;K.length;)t=K.pop(),t.isShown&&(n||t.scope.$digest());c.running=!1}))}function s(){var e=this;this.scope=B.$new(),this.id="item"+J++,x(this.scope,function(t){e.element=t,e.element.data("$$collectionRepeatItem",e),e.node=t[0],e.node.style[ionic.CSS.TRANSFORM]="translate3d(-9999px,-9999px,0)",e.node.style.cssText+=" height: 0px; width: 0px;",ionic.Utils.disconnectScope(e.scope),$.appendChild(e.node),e.images=t[0].getElementsByTagName("img")})}function l(){this.getItemPrimarySize=P,this.getItemSecondarySize=_,this.getScrollValue=function(){return Math.max(0,Math.min(I.__scrollTop-q,I.__maxScrollTop-q-U))},this.refreshDirection=function(){this.scrollPrimarySize=I.__clientHeight,this.scrollSecondarySize=I.__clientWidth,this.estimatedPrimarySize=v,this.estimatedSecondarySize=g,this.estimatedItemsAcross=L&&Math.floor(I.__clientWidth/g)||1}}function u(){this.getItemPrimarySize=_,this.getItemSecondarySize=P,this.getScrollValue=function(){return Math.max(0,Math.min(I.__scrollLeft-q,I.__maxScrollLeft-q-U))},this.refreshDirection=function(){this.scrollPrimarySize=I.__clientWidth,this.scrollSecondarySize=I.__clientHeight,this.estimatedPrimarySize=g,this.estimatedSecondarySize=v,this.estimatedItemsAcross=L&&Math.floor(I.__clientHeight/v)||1}}function d(){this.getEstimatedSecondaryPos=function(e){return e%this.estimatedItemsAcross*this.estimatedSecondarySize},this.getEstimatedPrimaryPos=function(e){return Math.floor(e/this.estimatedItemsAcross)*this.estimatedPrimarySize},this.getEstimatedIndex=function(e){return Math.floor(e/this.estimatedPrimarySize)*this.estimatedItemsAcross}}function f(){this.getEstimatedSecondaryPos=function(){return 0},this.getEstimatedPrimaryPos=function(e){return e*this.estimatedPrimarySize},this.getEstimatedIndex=function(e){return Math.floor(e/this.estimatedPrimarySize)}}function h(){this.getContentSize=function(){return this.getEstimatedPrimaryPos(A.length-1)+this.estimatedPrimarySize+q+U};var e={};this.getDimensions=function(t){return e.primaryPos=this.getEstimatedPrimaryPos(t),e.secondaryPos=this.getEstimatedSecondaryPos(t),e.primarySize=this.estimatedPrimarySize,e.secondarySize=this.estimatedSecondarySize,e},this.updateRenderRange=function(e,t){F=Math.max(0,this.getEstimatedIndex(e)),W=Math.min(A.length-1,this.getEstimatedIndex(t)+this.estimatedItemsAcross-1),Y=Math.max(0,this.getEstimatedPrimaryPos(F)),X=this.getEstimatedPrimaryPos(W)+this.estimatedPrimarySize}}function p(){function e(e){var t,r,a;for(t=Math.max(0,n);e>=t&&(a=c[t]);t++)r=c[t-1]||i,a.primarySize=o.getItemPrimarySize(t,A[t]),a.secondarySize=o.scrollSecondarySize,a.primaryPos=r.primaryPos+r.primarySize,a.secondaryPos=0}function t(e){var t,r,a;for(t=Math.max(n,0);e>=t&&(a=c[t]);t++)r=c[t-1]||i,a.secondarySize=Math.min(o.getItemSecondarySize(t,A[t]),o.scrollSecondarySize),a.secondaryPos=r.secondaryPos+r.secondarySize,0===t||a.secondaryPos+a.secondarySize>o.scrollSecondarySize?(a.secondaryPos=0,a.primarySize=o.getItemPrimarySize(t,A[t]),a.primaryPos=r.primaryPos+r.rowPrimarySize,a.rowStartIndex=t,a.rowPrimarySize=a.primarySize):(a.primarySize=o.getItemPrimarySize(t,A[t]),a.primaryPos=r.primaryPos,a.rowStartIndex=r.rowStartIndex,c[a.rowStartIndex].rowPrimarySize=a.rowPrimarySize=Math.max(c[a.rowStartIndex].rowPrimarySize,a.primarySize),a.rowPrimarySize=Math.max(a.primarySize,a.rowPrimarySize))}var n,o=this,r=ionic.debounce(Q,25,!0),a=L?t:e,c=[];this.getContentSize=function(){var e=c[n]||i;return(e.primaryPos+e.primarySize||0)+this.getEstimatedPrimaryPos(A.length-n-1)+q+U},this.onDestroy=function(){c.length=0},this.onRefreshData=function(){var e,t;for(e=c.length,t=A.length;t>e;e++)c.push({});n=-1},this.onRefreshLayout=function(){n=-1},this.getDimensions=function(e){return e=Math.min(e,A.length-1),e>n&&(e>.9*A.length?(a(A.length-1),n=A.length-1,Q()):(a(e),n=e,r())),c[e]};var s=-1,l=-1;this.updateRenderRange=function(e,t){var n,i,o;if(this.getDimensions(2*this.getEstimatedIndex(t)),-1===s||0===e)n=0;else if(e>=l)for(n=s,i=A.length;i>n&&!((o=this.getDimensions(n))&&o.primaryPos+o.rowPrimarySize>=e);n++);else for(n=s;n>=0;n--)if((o=this.getDimensions(n))&&o.primaryPos<=e){n=L?o.rowStartIndex:n;break}F=Math.min(Math.max(0,n),A.length-1),Y=-1!==F?this.getDimensions(F).primaryPos:-1;var r;for(n=F+1,i=A.length;i>n;n++)if((o=this.getDimensions(n))&&o.primaryPos+o.rowPrimarySize>t){if(L)for(r=o;i-1>n&&(o=this.getDimensions(n+1)).primaryPos===r.primaryPos;)n++;break}W=Math.min(n,A.length-1),X=-1!==W?(o=this.getDimensions(W)).primaryPos+(o.rowPrimarySize||o.primarySize):-1,l=e,s=F}}var v,g,m=o.afterItemsNode,$=o.containerNode,w=o.forceRefreshImages,S=o.heightData,k=o.widthData,C=o.keyExpression,T=o.renderBuffer,B=o.scope,I=o.scrollView,x=o.transclude,A=[],E={},V=S.getValue||function(){return S.value},P=function(e,t){return E[C]=t,E.$index=e,V(B,E)},D=k.getValue||function(){return k.value},_=function(e,t){return E[C]=t,E.$index=e,D(B,E)},R=!!I.options.scrollingY,L=R?k.dynamic||k.value!==I.__clientWidth:S.dynamic||S.value!==I.__clientHeight,M=!S.dynamic&&!k.dynamic,N="PRIMARY",z="SECONDARY",O=R?"translate3d(SECONDARYpx,PRIMARYpx,0)":"translate3d(PRIMARYpx,SECONDARYpx,0)",H=R?"height: PRIMARYpx; width: SECONDARYpx;":"height: SECONDARYpx; width: PRIMARYpx;",q=0,U=0,F=-1,W=-1,X=-1,Y=-1,G=[],j=[],K=[],Z={},J=0,Q=R?function(){I.setDimensions(null,null,null,ee.getContentSize(),!0)}:function(){I.setDimensions(null,null,ee.getContentSize(),null,!0)},ee=R?new l:new u;(L?d:f).call(ee),(M?h:p).call(ee);var te=R?"getContentHeight":"getContentWidth",ne=I.options[te];I.options[te]=angular.bind(ee,ee.getContentSize),I.__$callback=I.__callback,I.__callback=function(e,t,n,i){var o=ee.getScrollValue();(-1===F||o+ee.scrollPrimarySize>X||Y>o)&&a(),I.__$callback(e,t,n,i)};var ie=!1,oe=!1;this.refreshLayout=function(){A.length?(v=P(0,A[0]),g=_(0,A[0])):(v=100,g=100);var e=getComputedStyle(m)||{},n=m.firstElementChild&&getComputedStyle(m.firstElementChild)||{},i=m.lastElementChild&&getComputedStyle(m.lastElementChild)||{};U=(parseInt(e[R?"height":"width"])||0)+(n&&parseInt(n[R?"marginTop":"marginLeft"])||0)+(i&&parseInt(i[R?"marginBottom":"marginRight"])||0),q=0;var o=$;do q+=o[R?"offsetTop":"offsetLeft"];while(ionic.DomUtil.contains(I.__content,o=o.offsetParent));var a=$.previousElementSibling,c=a?t.getComputedStyle(a):{},l=parseInt(c[R?"marginBottom":"marginRight"]||0);if($.style[ionic.CSS.TRANSFORM]=O.replace(N,-l).replace(z,0),q-=l,I.__clientHeight&&I.__clientWidth||(I.__clientWidth=I.__container.clientWidth,I.__clientHeight=I.__container.clientHeight),(ee.onRefreshLayout||angular.noop)(),ee.refreshDirection(),Q(),!ie)for(var u=Math.max(20,3*T),d=0;u>d;d++)G.push(new s);ie=!0,ie&&oe&&((I.__scrollLeft>I.__maxScrollLeft||I.__scrollTop>I.__maxScrollTop)&&I.resize(),r(!0))},this.setData=function(e){A=e,(ee.onRefreshData||angular.noop)(),oe=!0},this.destroy=function(){a.destroyed=!0,G.forEach(function(e){e.scope.$destroy(),e.scope=e.element=e.node=e.images=null}),G.length=K.length=j.length=0,Z={},I.options[te]=ne,I.__callback=I.__$callback,I.resize(),(ee.onDestroy||angular.noop)()}}}function n(e){return["$ionicGesture","$parse",function(t,n){var i=e.substr(2).toLowerCase();return function(o,r,a){var c=n(a[e]),s=function(e){o.$apply(function(){c(o,{$event:e})})},l=t.on(i,s,r);o.$on("$destroy",function(){t.off(l,i,s)})}}]}function i(){return["$ionicScrollDelegate",function(e){return{restrict:"E",link:function(t,n,i){function o(t){for(var i=3,o=t.target;i--&&o;){if(o.classList.contains("button")||o.tagName.match(/input|textarea|select/i)||o.isContentEditable)return;o=o.parentNode}var r=t.gesture&&t.gesture.touches[0]||t.detail.touches[0],a=n[0].getBoundingClientRect();ionic.DomUtil.rectContains(r.pageX,r.pageY,a.left,a.top-20,a.left+a.width,a.top+a.height)&&e.scrollTop(!0)}"true"!=i.noTapScroll&&(ionic.on("tap",o,n[0]),t.$on("$destroy",function(){ionic.off("tap",o,n[0])}))}}}]}function o(e){return["$document","$timeout",function(t,n){return{restrict:"E",controller:"$ionicHeaderBar",compile:function(i){function o(t,n,i,o){e?(t.$watch(function(){return n[0].className},function(e){var n=-1===e.indexOf("ng-hide"),i=-1!==e.indexOf("bar-subheader");t.$hasHeader=n&&!i,t.$hasSubheader=n&&i,t.$emit("$ionicSubheader",t.$hasSubheader)}),t.$on("$destroy",function(){delete t.$hasHeader,delete t.$hasSubheader}),o.align(),t.$on("$ionicHeader.align",function(){ionic.requestAnimationFrame(function(){o.align()})})):(t.$watch(function(){return n[0].className},function(e){var n=-1===e.indexOf("ng-hide"),i=-1!==e.indexOf("bar-subfooter");t.$hasFooter=n&&!i,t.$hasSubfooter=n&&i}),t.$on("$destroy",function(){delete t.$hasFooter,delete t.$hasSubfooter}),t.$watch("$hasTabs",function(e){n.toggleClass("has-tabs",!!e)}),o.align(),t.$on("$ionicFooter.align",function(){ionic.requestAnimationFrame(function(){o.align()})}))}return i.addClass(e?"bar bar-header":"bar bar-footer"),n(function(){e&&t[0].getElementsByClassName("tabs-top").length&&i.addClass("has-tabs-top")}),{pre:o}}}}]}function r(e){return e.clientHeight}function a(e){e.stopPropagation()}var c=angular.module("ionic",["ngAnimate","ngSanitize","ui.router","ngIOS9UIWebViewPatch"]),s=angular.extend,l=angular.forEach,u=angular.isDefined,d=angular.isNumber,f=angular.isString,h=angular.element,p=angular.noop;c.factory("$ionicActionSheet",["$rootScope","$compile","$animate","$timeout","$ionicTemplateLoader","$ionicPlatform","$ionicBody","IONIC_BACK_PRIORITY",function(e,t,n,i,o,r,a,c){function l(o){function l(e){e&&/icon/.test(e)&&(u.$actionSheetHasIcon=!0)}var u=e.$new(!0);s(u,{cancel:p,destructiveButtonClicked:p,buttonClicked:p,$deregisterBackButton:p,buttons:[],cancelOnStateChange:!0},o||{});for(var d=0;d<u.buttons.length;d++)l(u.buttons[d].text);l(u.cancelText),l(u.destructiveText);var f=u.element=t('<ion-action-sheet ng-class="cssClass" buttons="buttons"></ion-action-sheet>')(u),v=h(f[0].querySelector(".action-sheet-wrapper")),g=u.cancelOnStateChange?e.$on("$stateChangeSuccess",function(){u.cancel()}):p;return u.removeSheet=function(e){u.removed||(u.removed=!0,v.removeClass("action-sheet-up"),i(function(){a.removeClass("action-sheet-open")},400),u.$deregisterBackButton(),g(),n.removeClass(f,"active").then(function(){u.$destroy(),f.remove(),u.cancel.$scope=v=null,(e||p)()}))},u.showSheet=function(e){u.removed||(a.append(f).addClass("action-sheet-open"),n.addClass(f,"active").then(function(){u.removed||(e||p)()}),i(function(){u.removed||v.addClass("action-sheet-up")},20,!1))},u.$deregisterBackButton=r.registerBackButtonAction(function(){i(u.cancel)},c.actionSheet),u.cancel=function(){u.removeSheet(o.cancel)},u.buttonClicked=function(e){o.buttonClicked(e,o.buttons[e])===!0&&u.removeSheet()},u.destructiveButtonClicked=function(){o.destructiveButtonClicked()===!0&&u.removeSheet()},u.showSheet(),u.cancel.$scope=u,u.cancel}return{show:l}}]),h.prototype.addClass=function(e){var t,n,i,o,r,a;if(e&&"ng-scope"!=e&&"ng-isolate-scope"!=e)for(t=0;t<this.length;t++)if(o=this[t],o.setAttribute)if(e.indexOf(" ")<0&&o.classList.add)o.classList.add(e);else{for(a=(" "+(o.getAttribute("class")||"")+" ").replace(/[\n\t]/g," "),r=e.split(" "),n=0;n<r.length;n++)i=r[n].trim(),-1===a.indexOf(" "+i+" ")&&(a+=i+" ");o.setAttribute("class",a.trim())}return this},h.prototype.removeClass=function(e){var t,n,i,o,r;if(e)for(t=0;t<this.length;t++)if(r=this[t],r.getAttribute)if(e.indexOf(" ")<0&&r.classList.remove)r.classList.remove(e);else for(i=e.split(" "),n=0;n<i.length;n++)o=i[n],r.setAttribute("class",(" "+(r.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").replace(" "+o.trim()+" "," ").trim());return this},c.factory("$ionicBackdrop",["$document","$timeout","$$rAF",function(e,t,n){function i(){c++,1===c&&(a.addClass("visible"),n(function(){c>=1&&a.addClass("active")}))}function o(){1===c&&(a.removeClass("active"),t(function(){0===c&&a.removeClass("visible")},400,!1)),c=Math.max(0,c-1)}function r(){return a}var a=h('<div class="backdrop">'),c=0;return e[0].body.appendChild(a[0]),{retain:i,release:o,getElement:r,_element:a}}]),c.factory("$ionicBind",["$parse","$interpolate",function(e,t){var n=/^\s*([@=&])(\??)\s*(\w*)\s*$/;return function(i,o,r){l(r||{},function(r,a){var c,s,l=r.match(n)||[],u=l[3]||a,d=l[1];switch(d){case"@":if(!o[u])return;o.$observe(u,function(e){i[a]=e}),o[u]&&(i[a]=t(o[u])(i));break;case"=":if(!o[u])return;s=i.$watch(o[u],function(e){i[a]=e}),i.$on("$destroy",s);break;case"&":if(o[u]&&o[u].match(RegExp(a+"(.*?)")))throw new Error('& expression binding "'+a+'" looks like it will recursively call "'+o[u]+'" and cause a stack overflow! Please choose a different scopeName.');c=e(o[u]),i[a]=function(e){return c(i,e)}}})}}]),c.factory("$ionicBody",["$document",function(e){return{addClass:function(){for(var t=0;t<arguments.length;t++)e[0].body.classList.add(arguments[t]);return this},removeClass:function(){for(var t=0;t<arguments.length;t++)e[0].body.classList.remove(arguments[t]);return this},enableClass:function(e){var t=Array.prototype.slice.call(arguments).slice(1);return e?this.addClass.apply(this,t):this.removeClass.apply(this,t),this},append:function(t){return e[0].body.appendChild(t.length?t[0]:t),this},get:function(){return e[0].body}}}]),c.factory("$ionicClickBlock",["$document","$ionicBody","$timeout",function(e,t,n){function i(e){e.preventDefault(),e.stopPropagation()}function o(){s&&(a?a.classList.remove(l):(a=e[0].createElement("div"),a.className="click-block",t.append(a),a.addEventListener("touchstart",i),a.addEventListener("mousedown",i)),s=!1)}function r(){a&&a.classList.add(l)}var a,c,s,l="click-block-hide";return{show:function(e){s=!0,n.cancel(c),c=n(this.hide,e||310,!1),o()},hide:function(){s=!1,n.cancel(c),r()}}}]),c.factory("$ionicGesture",[function(){return{on:function(e,t,n,i){return window.ionic.onGesture(e,t,n[0],i)},off:function(e,t,n){return window.ionic.offGesture(e,t,n)}}}]),c.factory("$ionicHistory",["$rootScope","$state","$location","$window","$timeout","$ionicViewSwitcher","$ionicNavViewDelegate",function(e,t,n,i,o,r,a){function c(e){return e?L.views[e]:null}function l(e){return e?c(e.backViewId):null}function d(e){return e?c(e.forwardViewId):null}function f(e){return e?L.histories[e]:null}function h(e){var t=p(e);return L.histories[t.historyId]||(L.histories[t.historyId]={historyId:t.historyId,parentHistoryId:p(t.scope.$parent).historyId,stack:[],cursor:-1}),f(t.historyId)}function p(t){for(var n=t;n;){if(n.hasOwnProperty("$historyId"))return{historyId:n.$historyId,scope:n};n=n.$parent}return{historyId:"root",scope:e}}function v(e){L.currentView=c(e),L.backView=l(L.currentView),L.forwardView=d(L.currentView)}function g(){var e;if(t&&t.current&&t.current.name){if(e=t.current.name,t.params)for(var n in t.params)t.params.hasOwnProperty(n)&&t.params[n]&&(e+="_"+n+"="+t.params[n]);return e}return ionic.Utils.nextUid()}function m(){var e;if(t&&t.params)for(var n in t.params)t.params.hasOwnProperty(n)&&(e=e||{},e[n]=t.params[n]);return e}function $(e){return e&&e.length&&/ion-side-menus|ion-tabs/i.test(e[0].tagName)}function w(e,t){return t&&t.$$state&&t.$$state.self.canSwipeBack===!1?!1:e&&"false"===e.attr("can-swipe-back")?!1:!0}var b,y,S,k,C,T="initialView",B="newView",I="moveBack",x="moveForward",A="back",E="forward",V="enter",P="exit",D="swap",_="none",R=0,L={histories:{root:{historyId:"root",parentHistoryId:null,stack:[],cursor:-1}},views:{},backView:null,forwardView:null,currentView:null},M=function(){};return M.prototype.initialize=function(e){if(e){for(var t in e)this[t]=e[t];return this}return null},M.prototype.go=function(){if(this.stateName)return t.go(this.stateName,this.stateParams);if(this.url&&this.url!==n.url()){if(L.backView===this)return i.history.go(-1);if(L.forwardView===this)return i.history.go(1);n.url(this.url)}return null},M.prototype.destroy=function(){this.scope&&(this.scope.$destroy&&this.scope.$destroy(),this.scope=null)},{register:function(e,t){var i,a,s,u=g(),d=h(e),$=L.currentView,M=L.backView,N=L.forwardView,z=null,O=null,H=_,q=d.historyId,U=n.url();if(b!==u&&(b=u,R++),C)z=C.viewId,O=C.action,H=C.direction,C=null;else if(M&&M.stateId===u)z=M.viewId,q=M.historyId,O=I,M.historyId===$.historyId?H=A:$&&(H=P,i=f(M.historyId),i&&i.parentHistoryId===$.historyId?H=V:(i=f($.historyId),i&&i.parentHistoryId===d.parentHistoryId&&(H=D)));else if(N&&N.stateId===u)z=N.viewId,q=N.historyId,O=x,N.historyId===$.historyId?H=E:$&&(H=P,$.historyId===d.parentHistoryId?H=V:(i=f($.historyId),i&&i.parentHistoryId===d.parentHistoryId&&(H=D))),i=p(e),N.historyId&&i.scope&&(i.scope.$historyId=N.historyId,q=N.historyId);else if($&&$.historyId!==q&&d.cursor>-1&&d.stack.length>0&&d.cursor<d.stack.length&&d.stack[d.cursor].stateId===u){var F=d.stack[d.cursor];z=F.viewId,q=F.historyId,O=I,H=D,i=f($.historyId),i&&i.parentHistoryId===q?H=P:(i=f(q),i&&i.parentHistoryId===$.historyId&&(H=V)),i=c(F.backViewId),i&&F.historyId!==i.historyId&&(d.stack[d.cursor].backViewId=$.viewId)}else{if(s=r.createViewEle(t),this.isAbstractEle(s,t))return{action:"abstractView",direction:_,ele:s};if(z=ionic.Utils.nextUid(),$){if($.forwardViewId=z,O=B,N&&$.stateId!==N.stateId&&$.historyId===N.historyId&&(i=f(N.historyId))){for(a=i.stack.length-1;a>=N.index;a--){var W=i.stack[a];W&&W.destroy&&W.destroy(),i.stack.splice(a)}q=N.historyId}d.historyId===$.historyId?H=E:$.historyId!==d.historyId&&(H=V,i=f($.historyId),i&&i.parentHistoryId===d.parentHistoryId?H=D:(i=f(i.parentHistoryId),i&&i.historyId===d.historyId&&(H=P)))}else O=T;2>R&&(H=_),L.views[z]=this.createView({viewId:z,index:d.stack.length,historyId:d.historyId,backViewId:$&&$.viewId?$.viewId:null,forwardViewId:null,stateId:u,stateName:this.currentStateName(),stateParams:m(),url:U,canSwipeBack:w(s,t)}),d.stack.push(L.views[z])}if(S&&S(),o.cancel(k),y){if(y.disableAnimate&&(H=_),y.disableBack&&(L.views[z].backViewId=null),y.historyRoot){for(a=0;a<d.stack.length;a++)d.stack[a].viewId===z?(d.stack[a].index=0,d.stack[a].backViewId=d.stack[a].forwardViewId=null):delete L.views[d.stack[a].viewId];d.stack=[L.views[z]]}y=null}if(v(z),L.backView&&q==L.backView.historyId&&u==L.backView.stateId&&U==L.backView.url)for(a=0;a<d.stack.length;a++)if(d.stack[a].viewId==z){O="dupNav",H=_,a>0&&(d.stack[a-1].forwardViewId=null),L.forwardView=null,L.currentView.index=L.backView.index,L.currentView.backViewId=L.backView.backViewId,L.backView=l(L.backView),d.stack.splice(a,1);break}return d.cursor=L.currentView.index,{viewId:z,action:O,direction:H,historyId:q,enableBack:this.enabledBack(L.currentView),isHistoryRoot:0===L.currentView.index,ele:s}},registerHistory:function(e){e.$historyId=ionic.Utils.nextUid()},createView:function(e){var t=new M;return t.initialize(e)},getViewById:c,viewHistory:function(){return L},currentView:function(e){return arguments.length&&(L.currentView=e),L.currentView},currentHistoryId:function(){return L.currentView?L.currentView.historyId:null},currentTitle:function(e){return L.currentView?(arguments.length&&(L.currentView.title=e),L.currentView.title):void 0},backView:function(e){return arguments.length&&(L.backView=e),L.backView},backTitle:function(e){var t=e&&c(e.backViewId)||L.backView;return t&&t.title},forwardView:function(e){return arguments.length&&(L.forwardView=e),L.forwardView},currentStateName:function(){return t&&t.current?t.current.name:null},isCurrentStateNavView:function(e){return!!(t&&t.current&&t.current.views&&t.current.views[e])},goToHistoryRoot:function(e){if(e){var t=f(e);if(t&&t.stack.length){if(L.currentView&&L.currentView.viewId===t.stack[0].viewId)return;C={viewId:t.stack[0].viewId,action:I,direction:A},t.stack[0].go()}}},goBack:function(e){if(u(e)&&-1!==e){if(e>-1)return;var t=L.histories[this.currentHistoryId()],n=t.cursor+e+1;1>n&&(n=1),t.cursor=n,v(t.stack[n].viewId);for(var i=n-1,r=[],a=c(t.stack[i].forwardViewId);a&&(r.push(a.stateId||a.viewId),i++,!(i>=t.stack.length));)a=c(t.stack[i].forwardViewId);var s=this;r.length&&o(function(){s.clearCache(r)},600)}L.backView&&L.backView.go()},enabledBack:function(e){var t=l(e);return!(!t||t.historyId!==e.historyId)},clearHistory:function(){var e=L.histories,t=L.currentView;if(e)for(var n in e)e[n].stack&&(e[n].stack=[],e[n].cursor=-1),t&&t.historyId===n?(t.backViewId=t.forwardViewId=null,e[n].stack.push(t)):e[n].destroy&&e[n].destroy();for(var i in L.views)i!==t.viewId&&delete L.views[i];t&&v(t.viewId)},clearCache:function(e){return o(function(){a._instances.forEach(function(t){t.clearCache(e)})})},nextViewOptions:function(t){return S&&S(),arguments.length&&(o.cancel(k),null===t?y=t:(y=y||{},s(y,t),y.expire&&(S=e.$on("$stateChangeSuccess",function(){k=o(function(){y=null},y.expire)})))),y},isAbstractEle:function(e,t){return t&&t.$$state&&t.$$state.self["abstract"]?!0:!(!e||!$(e)&&!$(e.children()))},isActiveScope:function(e){if(!e)return!1;for(var t,n=e,i=this.currentHistoryId();n;){if(n.$$disconnected)return!1;if(!t&&n.hasOwnProperty("$historyId")&&(t=!0),i){if(n.hasOwnProperty("$historyId")&&i==n.$historyId)return!0;if(n.hasOwnProperty("$activeHistoryId")&&i==n.$activeHistoryId){if(n.hasOwnProperty("$historyId"))return!0;if(!t)return!0}}t&&n.hasOwnProperty("$activeHistoryId")&&(t=!1),n=n.$parent}return i?"root"==i:!0}}}]).run(["$rootScope","$state","$location","$document","$ionicPlatform","$ionicHistory","IONIC_BACK_PRIORITY",function(e,t,n,i,o,r,a){function c(e){var t=r.backView();return t?t.go():ionic.Platform.exitApp(),e.preventDefault(),!1}e.$on("$ionicView.beforeEnter",function(){ionic.keyboard&&ionic.keyboard.hide&&ionic.keyboard.hide()}),e.$on("$ionicHistory.change",function(e,i){if(!i)return null;var o=r.viewHistory(),a=i.historyId?o.histories[i.historyId]:null;if(a&&a.cursor>-1&&a.cursor<a.stack.length){var c=a.stack[a.cursor];return c.go(i)}!i.url&&i.uiSref&&(i.url=t.href(i.uiSref)),i.url&&(0===i.url.indexOf("#")&&(i.url=i.url.replace("#","")),i.url!==n.url()&&n.url(i.url))}),e.$ionicGoBack=function(e){r.goBack(e)},e.$on("$ionicView.afterEnter",function(e,t){t&&t.title&&(i[0].title=t.title)}),o.registerBackButtonAction(c,a.view)}]),c.provider("$ionicConfig",function(){function e(e,i){a.platform[e]=i,o.platform[e]={},t(a,a.platform[e]),n(a.platform[e],o.platform[e],"")}function t(e,n){for(var i in e)i!=r&&e.hasOwnProperty(i)&&(angular.isObject(e[i])?(u(n[i])||(n[i]={}),t(e[i],n[i])):u(n[i])||(n[i]=null))}function n(e,t,o){l(e,function(c,s){angular.isObject(e[s])?(t[s]={},n(e[s],t[s],o+"."+s)):t[s]=function(n){if(arguments.length)return e[s]=n,t;if(e[s]==r){var c=i(a.platform,ionic.Platform.platform()+o+"."+s);return c||c===!1?c:i(a.platform,"default"+o+"."+s)}return e[s]}})}function i(e,t){t=t.split(".");for(var n=0;n<t.length;n++){if(!e||!u(e[t[n]]))return null;e=e[t[n]]}return e}var o=this;o.platform={};var r="platform",a={views:{maxCache:r,forwardCache:r,transition:r,swipeBackEnabled:r,swipeBackHitWidth:r},navBar:{alignTitle:r,positionPrimaryButtons:r,positionSecondaryButtons:r,transition:r},backButton:{icon:r,text:r,previousTitleText:r},form:{checkbox:r,toggle:r},scrolling:{jsScrolling:r},spinner:{icon:r},tabs:{style:r,position:r},templates:{maxPrefetch:r},platform:{}};n(a,o,""),e("default",{views:{maxCache:10,forwardCache:!1,transition:"ios",swipeBackEnabled:!0,swipeBackHitWidth:45},navBar:{alignTitle:"center",positionPrimaryButtons:"left",positionSecondaryButtons:"right",transition:"view"},backButton:{icon:"ion-ios-arrow-back",text:"Back",previousTitleText:!0},form:{checkbox:"circle",toggle:"large"},scrolling:{jsScrolling:!0},spinner:{icon:"ios"},tabs:{style:"standard",position:"bottom"},templates:{maxPrefetch:30}}),e("ios",{}),e("android",{views:{transition:"android",swipeBackEnabled:!1},navBar:{alignTitle:"left",positionPrimaryButtons:"right",positionSecondaryButtons:"right"},backButton:{icon:"ion-android-arrow-back",text:!1,previousTitleText:!1},form:{checkbox:"square",toggle:"small"},spinner:{icon:"android"},tabs:{style:"striped",position:"top"}}),e("windowsphone",{spinner:{icon:"android"}}),o.transitions={views:{},navBar:{}},o.transitions.views.ios=function(e,t,n,i){function o(e,t,n,i){var o={};o[ionic.CSS.TRANSITION_DURATION]=r.shouldAnimate?"":0,o.opacity=t,i>-1&&(o.boxShadow="0 0 10px rgba(0,0,0,"+(r.shouldAnimate?.45*i:.3)+")"),o[ionic.CSS.TRANSFORM]="translate3d("+n+"%,0,0)",ionic.DomUtil.cachedStyles(e,o)}var r={run:function(i){"forward"==n?(o(e,1,99*(1-i),1-i),o(t,1-.1*i,-33*i,-1)):"back"==n?(o(e,1-.1*(1-i),-33*(1-i),-1),o(t,1,100*i,1-i)):(o(e,1,0,-1),o(t,0,0,-1))},shouldAnimate:i&&("forward"==n||"back"==n)};return r},o.transitions.navBar.ios=function(e,t,n,i){function o(e,t,n,i){var o={};o[ionic.CSS.TRANSITION_DURATION]=c.shouldAnimate?"":"0ms",o.opacity=1===t?"":t,e.setCss("buttons-left",o),e.setCss("buttons-right",o),e.setCss("back-button",o),o[ionic.CSS.TRANSFORM]="translate3d("+i+"px,0,0)",e.setCss("back-text",o),o[ionic.CSS.TRANSFORM]="translate3d("+n+"px,0,0)",e.setCss("title",o)}function r(e,t,n){if(e&&t){var i=(e.titleTextX()+e.titleWidth())*(1-n),r=t&&(t.titleTextX()-e.backButtonTextLeft())*(1-n)||0;o(e,n,i,r)}}function a(e,t,n){if(e&&t){var i=(-(e.titleTextX()-t.backButtonTextLeft())-e.titleLeftRight())*n;o(e,1-n,i,0)}}var c={run:function(n){var i=e.controller(),o=t&&t.controller();"back"==c.direction?(a(i,o,1-n),r(o,i,1-n)):(r(i,o,n),a(o,i,n))},direction:n,shouldAnimate:i&&("forward"==n||"back"==n)};return c},o.transitions.views.android=function(e,t,n,i){function o(e,t){var n={};n[ionic.CSS.TRANSITION_DURATION]=r.shouldAnimate?"":0,n[ionic.CSS.TRANSFORM]="translate3d("+t+"%,0,0)",ionic.DomUtil.cachedStyles(e,n)}i=i&&("forward"==n||"back"==n);var r={run:function(i){"forward"==n?(o(e,99*(1-i)),o(t,-100*i)):"back"==n?(o(e,-100*(1-i)),o(t,100*i)):(o(e,0),o(t,0))},shouldAnimate:i};return r},o.transitions.navBar.android=function(e,t,n,i){function o(e,t){if(e){var n={};n.opacity=1===t?"":t,e.setCss("buttons-left",n),e.setCss("buttons-right",n),e.setCss("back-button",n),e.setCss("back-text",n),e.setCss("title",n)}}return{run:function(n){o(e.controller(),n),o(t&&t.controller(),1-n)},shouldAnimate:i&&("forward"==n||"back"==n)}},o.transitions.views.none=function(e,t){return{run:function(n){o.transitions.views.android(e,t,!1,!1).run(n);
},shouldAnimate:!1}},o.transitions.navBar.none=function(e,t){return{run:function(n){o.transitions.navBar.ios(e,t,!1,!1).run(n),o.transitions.navBar.android(e,t,!1,!1).run(n)},shouldAnimate:!1}},o.setPlatformConfig=e,o.$get=function(){return o}}).config(["$compileProvider",function(e){e.aHrefSanitizationWhitelist(/^\s*(https?|sms|tel|geo|ftp|mailto|file|ghttps?|ms-appx|x-wmapp0):/),e.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file|content|blob|ms-appx|x-wmapp0):|data:image\//)}]);var v='<div class="loading-container"><div class="loading"></div></div>',g="$ionicLoading instance.hide() has been deprecated. Use $ionicLoading.hide().",m="$ionicLoading instance.show() has been deprecated. Use $ionicLoading.show().",$="$ionicLoading instance.setContent() has been deprecated. Use $ionicLoading.show({ template: 'my content' }).";c.constant("$ionicLoadingConfig",{template:"<ion-spinner></ion-spinner>"}).factory("$ionicLoading",["$ionicLoadingConfig","$ionicBody","$ionicTemplateLoader","$ionicBackdrop","$timeout","$q","$log","$compile","$ionicPlatform","$rootScope","IONIC_BACK_PRIORITY",function(e,t,n,i,o,r,a,c,l,u,d){function f(){return b||(b=n.compile({template:v,appendTo:t.get()}).then(function(e){return e.show=function(a){var s=a.templateUrl?n.load(a.templateUrl):r.when(a.template||a.content||"");e.scope=a.scope||e.scope,e.isShown||(e.hasBackdrop=!a.noBackdrop&&a.showBackdrop!==!1,e.hasBackdrop&&(i.retain(),i.getElement().addClass("backdrop-loading"))),a.duration&&(o.cancel(e.durationTimeout),e.durationTimeout=o(angular.bind(e,e.hide),+a.duration)),y(),y=l.registerBackButtonAction(p,d.loading),s.then(function(n){if(n){var i=e.element.children();i.html(n),c(i.contents())(e.scope)}e.isShown&&(e.element.addClass("visible"),ionic.requestAnimationFrame(function(){e.isShown&&(e.element.addClass("active"),t.addClass("loading-active"))}))}),e.isShown=!0},e.hide=function(){y(),e.isShown&&(e.hasBackdrop&&(i.release(),i.getElement().removeClass("backdrop-loading")),e.element.removeClass("active"),t.removeClass("loading-active"),setTimeout(function(){!e.isShown&&e.element.removeClass("visible")},200)),o.cancel(e.durationTimeout),e.isShown=!1},e})),b}function h(t){t=s({},e||{},t||{});var n=t.delay||t.showDelay||0;return S(),k(),t.hideOnStateChange&&(S=u.$on("$stateChangeSuccess",w),k=u.$on("$stateChangeError",w)),o.cancel(C),C=o(p,n),C.then(f).then(function(e){return e.show(t)}),{hide:function(){return a.error(g),w.apply(this,arguments)},show:function(){return a.error(m),h.apply(this,arguments)},setContent:function(e){return a.error($),f().then(function(t){t.show({template:e})})}}}function w(){S(),k(),o.cancel(C),f().then(function(e){e.hide()})}var b,y=p,S=p,k=p,C=r.when();return{show:h,hide:w,_getLoader:f}}]),c.factory("$ionicModal",["$rootScope","$ionicBody","$compile","$timeout","$ionicPlatform","$ionicTemplateLoader","$$q","$log","$ionicClickBlock","$window","IONIC_BACK_PRIORITY",function(e,t,n,i,o,r,a,c,l,u,d){var f=ionic.views.Modal.inherit({initialize:function(e){ionic.views.Modal.prototype.initialize.call(this,e),this.animation=e.animation||"slide-in-up"},show:function(e){var n=this;if(n.scope.$$destroyed)return c.error("Cannot call "+n.viewType+".show() after remove(). Please create a new "+n.viewType+" instance."),a.when();l.show(600),m.add(n);var r=h(n.modalEl);n.el.classList.remove("hide"),i(function(){n._isShown&&t.addClass(n.viewType+"-open")},400,!1),n.el.parentElement||(r.addClass(n.animation),t.append(n.el));var s=r.data("$$ionicScrollController");return s&&s.resize(),e&&n.positionView&&(n.positionView(e,r),n._onWindowResize=function(){n._isShown&&n.positionView(e,r)},ionic.on("resize",n._onWindowResize,window)),r.addClass("ng-enter active").removeClass("ng-leave ng-leave-active"),n._isShown=!0,n._deregisterBackButton=o.registerBackButtonAction(n.hardwareBackButtonClose?angular.bind(n,n.hide):p,d.modal),ionic.views.Modal.prototype.show.call(n),i(function(){n._isShown&&(r.addClass("ng-enter-active"),ionic.trigger("resize"),n.scope.$parent&&n.scope.$parent.$broadcast(n.viewType+".shown",n),n.el.classList.add("active"),n.scope.$broadcast("$ionicHeader.align"),n.scope.$broadcast("$ionicFooter.align"))},20),i(function(){n._isShown&&n.$el.on("click",function(e){n.backdropClickToClose&&e.target===n.el&&m.isHighest(n)&&n.hide()})},400)},hide:function(){var e=this,n=h(e.modalEl);return l.show(600),m.remove(e),e.el.classList.remove("active"),n.addClass("ng-leave"),i(function(){e._isShown||n.addClass("ng-leave-active").removeClass("ng-enter ng-enter-active active")},20,!1),e.$el.off("click"),e._isShown=!1,e.scope.$parent&&e.scope.$parent.$broadcast(e.viewType+".hidden",e),e._deregisterBackButton&&e._deregisterBackButton(),ionic.views.Modal.prototype.hide.call(e),e.positionView&&ionic.off("resize",e._onWindowResize,window),i(function(){t.removeClass(e.viewType+"-open"),e.el.classList.add("hide")},e.hideDelay||320)},remove:function(){var e=this;return e.scope.$parent&&e.scope.$parent.$broadcast(e.viewType+".removed",e),e.hide().then(function(){e.scope.$destroy(),e.$el.remove()})},isShown:function(){return!!this._isShown}}),v=function(t,i){var o=i.scope&&i.scope.$new()||e.$new(!0);i.viewType=i.viewType||"modal",s(o,{$hasHeader:!1,$hasSubheader:!1,$hasFooter:!1,$hasSubfooter:!1,$hasTabs:!1,$hasTabsTop:!1});var r=n("<ion-"+i.viewType+">"+t+"</ion-"+i.viewType+">")(o);i.$el=r,i.el=r[0],i.modalEl=i.el.querySelector("."+i.viewType);var a=new f(i);return a.scope=o,i.scope||(o[i.viewType]=a),a},g=[],m={add:function(e){g.push(e)},remove:function(e){var t=g.indexOf(e);t>-1&&t<g.length&&g.splice(t,1)},isHighest:function(e){var t=g.indexOf(e);return t>-1&&t===g.length-1}};return{fromTemplate:function(e,t){var n=v(e,t||{});return n},fromTemplateUrl:function(e,t,n){var i;return angular.isFunction(t)&&(i=t,t=n),r.load(e).then(function(e){var n=v(e,t||{});return i&&i(n),n})},stack:m}}]),c.service("$ionicNavBarDelegate",ionic.DelegateService(["align","showBackButton","showBar","title","changeTitle","setTitle","getTitle","back","getPreviousTitle"])),c.service("$ionicNavViewDelegate",ionic.DelegateService(["clearCache"])),c.constant("IONIC_BACK_PRIORITY",{view:100,sideMenu:150,modal:200,actionSheet:300,popup:400,loading:500}).provider("$ionicPlatform",function(){return{$get:["$q",function(e){var t={onHardwareBackButton:function(e){ionic.Platform.ready(function(){document.addEventListener("backbutton",e,!1)})},offHardwareBackButton:function(e){ionic.Platform.ready(function(){document.removeEventListener("backbutton",e)})},$backButtonActions:{},registerBackButtonAction:function(e,n,i){t._hasBackButtonHandler||(t.$backButtonActions={},t.onHardwareBackButton(t.hardwareBackButtonClick),t._hasBackButtonHandler=!0);var o={id:i?i:ionic.Utils.nextUid(),priority:n?n:0,fn:e};return t.$backButtonActions[o.id]=o,function(){delete t.$backButtonActions[o.id]}},hardwareBackButtonClick:function(e){var n,i;for(i in t.$backButtonActions)(!n||t.$backButtonActions[i].priority>=n.priority)&&(n=t.$backButtonActions[i]);return n?(n.fn(e),n):void 0},is:function(e){return ionic.Platform.is(e)},on:function(e,t){return ionic.Platform.ready(function(){document.addEventListener(e,t,!1)}),function(){ionic.Platform.ready(function(){document.removeEventListener(e,t)})}},ready:function(t){var n=e.defer();return ionic.Platform.ready(function(){n.resolve(),t&&t()}),n.promise}};return t}]}}),c.factory("$ionicPopover",["$ionicModal","$ionicPosition","$document","$window",function(e,t,n,i){function o(e,n){var o=h(e.target||e),a=t.offset(o),c=n.prop("offsetWidth"),s=n.prop("offsetHeight"),l=i.innerWidth,u=i.innerHeight,d={left:a.left+a.width/2-c/2},f=h(n[0].querySelector(".popover-arrow"));d.left<r?d.left=r:d.left+c+r>l&&(d.left=l-c-r),a.top+a.height+s>u&&a.top-s>0?(d.top=a.top-s,n.addClass("popover-bottom")):(d.top=a.top+a.height,n.removeClass("popover-bottom")),f.css({left:a.left+a.width/2-f.prop("offsetWidth")/2-d.left+"px"}),n.css({top:d.top+"px",left:d.left+"px",marginLeft:"0",opacity:"1"})}var r=6,a={viewType:"popover",hideDelay:1,animation:"none",positionView:o};return{fromTemplate:function(t,n){return e.fromTemplate(t,ionic.Utils.extend(a,n||{}))},fromTemplateUrl:function(t,n){return e.fromTemplateUrl(t,ionic.Utils.extend(a,n||{}))}}}]);var w='<div class="popup-container" ng-class="cssClass"><div class="popup"><div class="popup-head"><h3 class="popup-title" ng-bind-html="title"></h3><h5 class="popup-sub-title" ng-bind-html="subTitle" ng-if="subTitle"></h5></div><div class="popup-body"></div><div class="popup-buttons" ng-show="buttons.length"><button ng-repeat="button in buttons" ng-click="$buttonTapped(button, $event)" class="button" ng-class="button.type || \'button-default\'" ng-bind-html="button.text"></button></div></div></div>';c.factory("$ionicPopup",["$ionicTemplateLoader","$ionicBackdrop","$q","$timeout","$rootScope","$ionicBody","$compile","$ionicPlatform","$ionicModal","IONIC_BACK_PRIORITY",function(e,t,n,i,o,r,a,c,l,u){function d(t){t=s({scope:null,title:"",buttons:[]},t||{});var c={};return c.scope=(t.scope||o).$new(),c.element=h(w),c.responseDeferred=n.defer(),r.get().appendChild(c.element[0]),a(c.element)(c.scope),s(c.scope,{title:t.title,buttons:t.buttons,subTitle:t.subTitle,cssClass:t.cssClass,$buttonTapped:function(e,t){var n=(e.onTap||p)(t);t=t.originalEvent||t,t.defaultPrevented||c.responseDeferred.resolve(n)}}),n.when(t.templateUrl?e.load(t.templateUrl):t.template||t.content||"").then(function(e){var t=h(c.element[0].querySelector(".popup-body"));e?(t.html(e),a(t.contents())(c.scope)):t.remove()}),c.show=function(){c.isShown||c.removed||(l.stack.add(c),c.isShown=!0,ionic.requestAnimationFrame(function(){c.isShown&&(c.element.removeClass("popup-hidden"),c.element.addClass("popup-showing active"),g(c.element))}))},c.hide=function(e){return e=e||p,c.isShown?(l.stack.remove(c),c.isShown=!1,c.element.removeClass("active"),c.element.addClass("popup-hidden"),void i(e,250,!1)):e()},c.remove=function(){c.removed||(c.hide(function(){c.element.remove(),c.scope.$destroy()}),c.removed=!0)},c}function f(){var e=S[S.length-1];e&&e.responseDeferred.resolve()}function v(e){function n(){S.push(o),i(o.show,a,!1),o.responseDeferred.promise.then(function(e){var n=S.indexOf(o);return-1!==n&&S.splice(n,1),o.remove(),S.length>0?S[S.length-1].show():(t.release(),i(function(){S.length||r.removeClass("popup-open")},400,!1),(k._backButtonActionDone||p)()),e})}var o=k._createPopup(e),a=0;return S.length>0?(a=y.stackPushDelay,i(S[S.length-1].hide,a,!1)):(r.addClass("popup-open"),t.retain(),k._backButtonActionDone=c.registerBackButtonAction(f,u.popup)),o.responseDeferred.promise.close=function(e){o.removed||o.responseDeferred.resolve(e)},o.responseDeferred.notify({close:o.responseDeferred.close}),n(),o.responseDeferred.promise}function g(e){var t=e[0].querySelector("[autofocus]");t&&t.focus()}function m(e){return v(s({buttons:[{text:e.okText||"OK",type:e.okType||"button-positive",onTap:function(){return!0}}]},e||{}))}function $(e){return v(s({buttons:[{text:e.cancelText||"Cancel",type:e.cancelType||"button-default",onTap:function(){return!1}},{text:e.okText||"OK",type:e.okType||"button-positive",onTap:function(){return!0}}]},e||{}))}function b(e){var t=o.$new(!0);t.data={};var n="";return e.template&&/<[a-z][\s\S]*>/i.test(e.template)===!1&&(n="<span>"+e.template+"</span>",delete e.template),v(s({template:n+'<input ng-model="data.response" type="'+(e.inputType||"text")+'" placeholder="'+(e.inputPlaceholder||"")+'">',scope:t,buttons:[{text:e.cancelText||"Cancel",type:e.cancelType||"button-default",onTap:function(){}},{text:e.okText||"OK",type:e.okType||"button-positive",onTap:function(){return t.data.response||""}}]},e||{}))}var y={stackPushDelay:75},S=[],k={show:v,alert:m,confirm:$,prompt:b,_createPopup:d,_popupStack:S};return k}]),c.factory("$ionicPosition",["$document","$window",function(e,t){function n(e,n){return e.currentStyle?e.currentStyle[n]:t.getComputedStyle?t.getComputedStyle(e)[n]:e.style[n]}function i(e){return"static"===(n(e,"position")||"static")}var o=function(t){for(var n=e[0],o=t.offsetParent||n;o&&o!==n&&i(o);)o=o.offsetParent;return o||n};return{position:function(t){var n=this.offset(t),i={top:0,left:0},r=o(t[0]);r!=e[0]&&(i=this.offset(h(r)),i.top+=r.clientTop-r.scrollTop,i.left+=r.clientLeft-r.scrollLeft);var a=t[0].getBoundingClientRect();return{width:a.width||t.prop("offsetWidth"),height:a.height||t.prop("offsetHeight"),top:n.top-i.top,left:n.left-i.left}},offset:function(n){var i=n[0].getBoundingClientRect();return{width:i.width||n.prop("offsetWidth"),height:i.height||n.prop("offsetHeight"),top:i.top+(t.pageYOffset||e[0].documentElement.scrollTop),left:i.left+(t.pageXOffset||e[0].documentElement.scrollLeft)}}}}]),c.service("$ionicScrollDelegate",ionic.DelegateService(["resize","scrollTop","scrollBottom","scrollTo","scrollBy","zoomTo","zoomBy","getScrollPosition","anchorScroll","freezeScroll","freezeAllScrolls","getScrollView"])),c.service("$ionicSideMenuDelegate",ionic.DelegateService(["toggleLeft","toggleRight","getOpenRatio","isOpen","isOpenLeft","isOpenRight","canDragContent","edgeDragThreshold"])),c.service("$ionicSlideBoxDelegate",ionic.DelegateService(["update","slide","select","enableSlide","previous","next","stop","autoPlay","start","currentIndex","selected","slidesCount","count","loop"])),c.service("$ionicTabsDelegate",ionic.DelegateService(["select","selectedIndex"])),function(){var e=[];c.factory("$ionicTemplateCache",["$http","$templateCache","$timeout",function(t,n,i){function o(e){return"undefined"==typeof e?r():(f(e)&&(e=[e]),l(e,function(e){c.push(e)}),void(a&&r()))}function r(){var e;if(o._runCount++,a=!0,0!==c.length){for(var s=0;4>s&&(e=c.pop());)f(e)&&t.get(e,{cache:n}),s++;c.length&&i(r,1e3)}}var a,c=e;return o._runCount=0,o}]).config(["$stateProvider","$ionicConfigProvider",function(t,n){var i=t.state;t.state=function(o,r){if("object"==typeof r){var a=r.prefetchTemplate!==!1&&e.length<n.templates.maxPrefetch();if(a&&f(r.templateUrl)&&e.push(r.templateUrl),angular.isObject(r.views))for(var c in r.views)a=r.views[c].prefetchTemplate!==!1&&e.length<n.templates.maxPrefetch(),a&&f(r.views[c].templateUrl)&&e.push(r.views[c].templateUrl)}return i.call(t,o,r)}}]).run(["$ionicTemplateCache",function(e){e()}])}(),c.factory("$ionicTemplateLoader",["$compile","$controller","$http","$q","$rootScope","$templateCache",function(e,t,n,i,o,r){function a(e){return n.get(e,{cache:r}).then(function(e){return e.data&&e.data.trim()})}function c(n){n=s({template:"",templateUrl:"",scope:null,controller:null,locals:{},appendTo:null},n||{});var r=n.templateUrl?this.load(n.templateUrl):i.when(n.template);return r.then(function(i){var r,a=n.scope||o.$new(),c=h("<div>").html(i).contents();return n.controller&&(r=t(n.controller,s(n.locals,{$scope:a})),c.children().data("$ngControllerController",r)),n.appendTo&&h(n.appendTo).append(c),e(c)(a),{element:c,scope:a}})}return{load:a,compile:c}}]),c.factory("$ionicViewService",["$ionicHistory","$log",function(e,t){function n(e,n){t.warn("$ionicViewService"+e+" is deprecated, please use $ionicHistory"+n+" instead: http://ionicframework.com/docs/nightly/api/service/$ionicHistory/")}n("","");var i={getCurrentView:"currentView",getBackView:"backView",getForwardView:"forwardView",getCurrentStateName:"currentStateName",nextViewOptions:"nextViewOptions",clearHistory:"clearHistory"};return l(i,function(t,o){i[o]=function(){return n("."+o,"."+t),e[t].apply(this,arguments)}}),i}]),c.factory("$ionicViewSwitcher",["$timeout","$document","$q","$ionicClickBlock","$ionicConfig","$ionicNavBarDelegate",function(e,t,n,i,o,r){function a(e,t){return c(e)["abstract"]?c(e).name:t?t.stateId||t.viewId:ionic.Utils.nextUid()}function c(e){return e&&e.$$state&&e.$$state.self||{}}function d(e,t,n,i){var r=c(e),a=g||V(t,"view-transition")||r.viewTransition||o.views.transition()||"ios",l=o.navBar.transition();return n=m||V(t,"view-direction")||r.viewDirection||n||"none",s(f(i),{transition:a,navBarTransition:"view"===l?a:l,direction:n,shouldAnimate:"none"!==a&&"none"!==n})}function f(e){return e=e||{},{viewId:e.viewId,historyId:e.historyId,stateId:e.stateId,stateName:e.stateName,stateParams:e.stateParams}}function p(e,t){return arguments.length>1?void V(e,T,t):V(e,T)}function v(e){if(e&&e.length){var t=e.scope();t&&(t.$emit("$ionicView.unloaded",e.data(C)),t.$destroy()),e.remove()}}var g,m,$="webkitTransitionEnd transitionend",w="$noCache",b="$destroyEle",y="$eleId",S="$accessed",k="$fallbackTimer",C="$viewData",T="nav-view",B="active",I="cached",x="stage",A=0;ionic.transition=ionic.transition||{},ionic.transition.isActive=!1;var E,V=ionic.DomUtil.cachedAttr,P=[],D=1100,_={create:function(t,l,h,T,E,R){var L,M,N,z=++A,O={init:function(e,t){_.isTransitioning(!0),O.loadViewElements(e),O.render(e,function(){t&&t()})},loadViewElements:function(e){var n,i,o,r=t.getViewElements(),c=a(l,h),s=t.activeEleId();for(n=0,i=r.length;i>n&&(o=r.eq(n),o.data(y)===c?o.data(w)?(o.data(y,c+ionic.Utils.nextUid()),o.data(b,!0)):L=o:u(s)&&o.data(y)===s&&(M=o),!L||!M);n++);N=!!L,N||(L=e.ele||_.createViewEle(l),L.data(y,c)),R&&t.activeEleId(c),e.ele=null},render:function(e,n){if(N)ionic.Utils.reconnectScope(L.scope());else{p(L,x);var i=d(l,L,e.direction,h),r=o.transitions.views[i.transition]||o.transitions.views.none;r(L,null,i.direction,!0).run(0),L.data(C,{viewId:i.viewId,historyId:i.historyId,stateName:i.stateName,stateParams:i.stateParams}),(c(l).cache===!1||"false"===c(l).cache||"false"==L.attr("cache-view")||0===o.views.maxCache())&&L.data(w,!0);var a=t.appendViewElement(L,l);delete i.direction,delete i.transition,a.$emit("$ionicView.loaded",i)}L.data(S,Date.now()),n&&n()},transition:function(a,c,u){function v(){p(L,F.shouldAnimate?"entering":B),p(M,F.shouldAnimate?"leaving":I),F.run(1),r._instances.forEach(function(e){e.triggerTransitionStart(z)}),F.shouldAnimate||b()}function w(e){e.target===this&&b()}function b(){b.x||(b.x=!0,L.off($,w),e.cancel(L.data(k)),M&&e.cancel(M.data(k)),O.emit("after",H,q),C&&C.resolve(t),z===A&&(n.all(P).then(_.transitionEnd),O.cleanup(H)),r._instances.forEach(function(e){e.triggerTransitionEnd()}),g=m=h=T=L=M=null)}function y(e){e.target===this&&S()}function S(){p(L,I),p(M,B),L.off($,y),e.cancel(L.data(k)),_.transitionEnd([t])}var C,H=d(l,L,a,h),q=s(s({},H),f(T));H.transitionId=q.transitionId=z,H.fromCache=!!N,H.enableBack=!!c,H.renderStart=E,H.renderEnd=R,V(L.parent(),"nav-view-transition",H.transition),V(L.parent(),"nav-view-direction",H.direction),e.cancel(L.data(k));var U=o.transitions.views[H.transition]||o.transitions.views.none,F=U(L,M,H.direction,H.shouldAnimate&&u&&R);if(F.shouldAnimate&&(L.on($,w),L.data(k,e(b,D)),i.show(D)),E&&(O.emit("before",H,q),p(L,x),F.run(0)),R&&(C=n.defer(),P.push(C.promise)),E&&R)e(v,16);else{if(!R)return p(L,"entering"),p(M,"leaving"),{run:F.run,cancel:function(t){t?(L.on($,y),L.data(k,e(S,D)),i.show(D)):S(),F.shouldAnimate=t,F.run(0),F=null}};R&&v()}},emit:function(e,t,n){var i=L.scope(),o=M&&M.scope();"after"==e&&(i&&i.$emit("$ionicView.enter",t),o?o.$emit("$ionicView.leave",n):i&&n&&n.viewId&&i.$emit("$ionicNavView.leave",n)),i&&i.$emit("$ionicView."+e+"Enter",t),o?o.$emit("$ionicView."+e+"Leave",n):i&&n&&n.viewId&&i.$emit("$ionicNavView."+e+"Leave",n)},cleanup:function(e){M&&"back"==e.direction&&!o.views.forwardCache()&&v(M);var n,i,r,a=t.getViewElements(),c=a.length,s=c-1>o.views.maxCache(),l=Date.now();for(n=0;c>n;n++)i=a.eq(n),s&&i.data(S)<l?(l=i.data(S),r=a.eq(n)):i.data(b)&&p(i)!=B&&v(i);v(r),L.data(w)&&L.data(b,!0)},enteringEle:function(){return L},leavingEle:function(){return M}};return O},transitionEnd:function(e){l(e,function(e){e.transitionEnd()}),_.isTransitioning(!1),i.hide(),P=[]},nextTransition:function(e){g=e},nextDirection:function(e){m=e},isTransitioning:function(t){return arguments.length&&(ionic.transition.isActive=!!t,e.cancel(E),t&&(E=e(function(){_.isTransitioning(!1)},999))),ionic.transition.isActive},createViewEle:function(e){var n=t[0].createElement("div");return e&&e.$template&&(n.innerHTML=e.$template,1===n.children.length)?(n.children[0].classList.add("pane"),h(n.children[0])):(n.className="pane",h(n))},viewEleIsActive:function(e,t){p(e,t?B:I)},getTransitionData:d,navViewAttr:p,destroyViewEle:v};return _}]),angular.module("ngIOS9UIWebViewPatch",["ng"]).config(["$provide",function(e){"use strict";e.decorator("$browser",["$delegate","$window",function(e,t){function n(e){return/(iPhone|iPad|iPod).* OS 9_\d/.test(e)&&!/Version\/9\./.test(e)}function i(e){function t( | {n=null}var n=null,i=e.url;return e.url=function(){return arguments.length?(n=arguments[0],i.apply(e,arguments)):n||i.apply(e,arguments)},window.addEventListener("popstate",t,!1),window.addEventListener("hashchange",t,!1),e}return n(t.navigator.userAgent)?i(e):e}])}]),c.config(["$provide",function(e){e.decorator("$compile",["$delegate",function(e){return e.$$addScopeInfo=function(e,t,n,i){var o=n?i?"$isolateScopeNoTemplate":"$isolateScope":"$scope";e.data(o,t)},e}])}]),c.config(["$provide",function(e){function t(e,t){return e.__hash=e.hash,e.hash=function(n){return u(n)&&n.length>0&&t(function(){var e=document.querySelector(".scroll-content");e&&(e.scrollTop=0)},0,!1),e.__hash(n)},e}e.decorator("$location",["$delegate","$timeout",t])}]),c.controller("$ionicHeaderBar",["$scope","$element","$attrs","$q","$ionicConfig","$ionicHistory",function(e,t,n,i,o,r){function a(e){return C[e]||(C[e]=t[0].querySelector("."+e)),C[e]}var c="title",s="back-text",l="back-button",u="default-title",d="previous-title",f="hide",h=this,p="",v="",g=0,m=0,$="",w=!1,b=!0,y=!0,S=!1,k=0;h.beforeEnter=function(t){e.$broadcast("$ionicView.beforeEnter",t)},h.title=function(e){return arguments.length&&e!==p&&(a(c).innerHTML=e,p=e,k=0),p},h.enableBack=function(e,t){return arguments.length&&(w=e,t||h.updateBackButton()),w},h.showBack=function(e,t){return arguments.length&&(b=e,t||h.updateBackButton()),b},h.showNavBack=function(e){y=e,h.updateBackButton()},h.updateBackButton=function(){var e;(b&&y&&w)!==S&&(S=b&&y&&w,e=a(l),e&&e.classList[S?"remove":"add"](f)),w&&(e=e||a(l),e&&(h.backButtonIcon!==o.backButton.icon()&&(e=a(l+" .icon"),e&&(h.backButtonIcon=o.backButton.icon(),e.className="icon "+h.backButtonIcon)),h.backButtonText!==o.backButton.text()&&(e=a(l+" .back-text"),e&&(e.textContent=h.backButtonText=o.backButton.text()))))},h.titleTextWidth=function(){if(!k){var e=ionic.DomUtil.getTextBounds(a(c));k=Math.min(e&&e.width||30)}return k},h.titleWidth=function(){var e=h.titleTextWidth(),t=a(c).offsetWidth;return e>t&&(e=t+(g-m-5)),e},h.titleTextX=function(){return t[0].offsetWidth/2-h.titleWidth()/2},h.titleLeftRight=function(){return g-m},h.backButtonTextLeft=function(){for(var e=0,t=a(s);t;)e+=t.offsetLeft,t=t.parentElement;return e},h.resetBackButton=function(e){if(o.backButton.previousTitleText()){var t=a(d);if(t){t.classList.remove(f);var n=e&&r.getViewById(e.viewId),i=r.backTitle(n);i!==v&&(v=t.innerHTML=i)}var c=a(u);c&&c.classList.remove(f)}},h.align=function(e){var i=a(c);e=e||n.alignTitle||o.navBar.alignTitle();var r=h.calcWidths(e,!1);if(b&&v&&o.backButton.previousTitleText()){var s=h.calcWidths(e,!0),l=t[0].offsetWidth-s.titleLeft-s.titleRight;h.titleTextWidth()<=l&&(r=s)}return h.updatePositions(i,r.titleLeft,r.titleRight,r.buttonsLeft,r.buttonsRight,r.css,r.showPrevTitle)},h.calcWidths=function(e,n){var i,o,r,h,p,v,g,m,$,w=a(c),y=a(l),S=t[0].childNodes,k=0,C=0,T=0,B=0,I="",x=0;for(i=0;i<S.length;i++){if(p=S[i],g=0,1==p.nodeType){if(p===w){$=!0;continue}if(p.classList.contains(f))continue;if(b&&p===y){for(o=0;o<p.childNodes.length;o++)if(h=p.childNodes[o],1==h.nodeType)if(h.classList.contains(s))for(r=0;r<h.children.length;r++)if(v=h.children[r],n){if(v.classList.contains(u))continue;x+=v.offsetWidth}else{if(v.classList.contains(d))continue;x+=v.offsetWidth}else x+=h.offsetWidth;else 3==h.nodeType&&h.nodeValue.trim()&&(m=ionic.DomUtil.getTextBounds(h),x+=m&&m.width||0);g=x||p.offsetWidth}else g=p.offsetWidth}else 3==p.nodeType&&p.nodeValue.trim()&&(m=ionic.DomUtil.getTextBounds(p),g=m&&m.width||0);$?C+=g:k+=g}if("left"==e)I="title-left",k&&(T=k+15),C&&(B=C+15);else if("right"==e)I="title-right",k&&(T=k+15),C&&(B=C+15);else{var A=Math.max(k,C)+10;A>10&&(T=B=A)}return{backButtonWidth:x,buttonsLeft:k,buttonsRight:C,titleLeft:T,titleRight:B,showPrevTitle:n,css:I}},h.updatePositions=function(e,n,r,c,s,l,p){var v=i.defer();if(e&&(n!==g&&(e.style.left=n?n+"px":"",g=n),r!==m&&(e.style.right=r?r+"px":"",m=r),l!==$&&(l&&e.classList.add(l),$&&e.classList.remove($),$=l)),o.backButton.previousTitleText()){var w=a(d),b=a(u);w&&w.classList[p?"remove":"add"](f),b&&b.classList[p?"add":"remove"](f)}return ionic.requestAnimationFrame(function(){if(e&&e.offsetWidth+10<e.scrollWidth){var n=s+5,i=t[0].offsetWidth-g-h.titleTextWidth()-20;r=n>i?n:i,r!==m&&(e.style.right=r+"px",m=r)}v.resolve()}),v.promise},h.setCss=function(e,t){ionic.DomUtil.cachedStyles(a(e),t)};var C={};e.$on("$destroy",function(){for(var e in C)C[e]=null})}]),c.controller("$ionInfiniteScroll",["$scope","$attrs","$element","$timeout",function(e,t,n,i){function o(){ionic.requestAnimationFrame(function(){n[0].classList.add("active")}),s.isLoading=!0,e.$parent&&e.$parent.$apply(t.onInfinite||"")}function r(){ionic.requestAnimationFrame(function(){n[0].classList.remove("active")}),i(function(){s.jsScrolling&&s.scrollView.resize(),(s.jsScrolling&&s.scrollView.__container&&s.scrollView.__container.offsetHeight>0||!s.jsScrolling)&&s.checkBounds()},30,!1),s.isLoading=!1}function a(){if(!s.isLoading){var e={};if(s.jsScrolling){e=s.getJSMaxScroll();var t=s.scrollView.getValues();(-1!==e.left&&t.left>=e.left||-1!==e.top&&t.top>=e.top)&&o()}else e=s.getNativeMaxScroll(),(-1!==e.left&&s.scrollEl.scrollLeft>=e.left-s.scrollEl.clientWidth||-1!==e.top&&s.scrollEl.scrollTop>=e.top-s.scrollEl.clientHeight)&&o()}}function c(e){var n=(t.distance||"2.5%").trim(),i=-1!==n.indexOf("%");return i?e*(1-parseFloat(n)/100):e-parseFloat(n)}var s=this;s.isLoading=!1,e.icon=function(){return u(t.icon)?t.icon:"ion-load-d"},e.spinner=function(){return u(t.spinner)?t.spinner:""},e.$on("scroll.infiniteScrollComplete",function(){r()}),e.$on("$destroy",function(){s.scrollCtrl&&s.scrollCtrl.$element&&s.scrollCtrl.$element.off("scroll",s.checkBounds),s.scrollEl&&s.scrollEl.removeEventListener&&s.scrollEl.removeEventListener("scroll",s.checkBounds)}),s.checkBounds=ionic.Utils.throttle(a,300),s.getJSMaxScroll=function(){var e=s.scrollView.getScrollMax();return{left:s.scrollView.options.scrollingX?c(e.left):-1,top:s.scrollView.options.scrollingY?c(e.top):-1}},s.getNativeMaxScroll=function(){var e={left:s.scrollEl.scrollWidth,top:s.scrollEl.scrollHeight},t=window.getComputedStyle(s.scrollEl)||{};return{left:"scroll"===t.overflowX||"auto"===t.overflowX||"scroll"===s.scrollEl.style["overflow-x"]?c(e.left):-1,top:"scroll"===t.overflowY||"auto"===t.overflowY||"scroll"===s.scrollEl.style["overflow-y"]?c(e.top):-1}},s.__finishInfiniteScroll=r}]),c.service("$ionicListDelegate",ionic.DelegateService(["showReorder","showDelete","canSwipeItems","closeOptionButtons"])).controller("$ionicList",["$scope","$attrs","$ionicListDelegate","$ionicHistory",function(e,t,n,i){var o=this,r=!0,a=!1,c=!1,s=n._registerInstance(o,t.delegateHandle,function(){return i.isActiveScope(e)});e.$on("$destroy",s),o.showReorder=function(e){return arguments.length&&(a=!!e),a},o.showDelete=function(e){return arguments.length&&(c=!!e),c},o.canSwipeItems=function(e){return arguments.length&&(r=!!e),r},o.closeOptionButtons=function(){o.listView&&o.listView.clearDragEffects()}}]),c.controller("$ionicNavBar",["$scope","$element","$attrs","$compile","$timeout","$ionicNavBarDelegate","$ionicConfig","$ionicHistory",function(e,t,n,i,o,r,a,c){function s(e,t){var n=console.warn||console.log;n&&n.call(console,"navBarController."+e+" is deprecated, please use "+t+" instead")}function d(e){return x[e]?h(x[e]):void 0}function f(){for(var e=0;e<I.length;e++)if(I[e].isActive)return I[e]}function p(){for(var e=0;e<I.length;e++)if(!I[e].isActive)return I[e]}function v(e,t){e&&ionic.DomUtil.cachedAttr(e.containerEle(),"nav-bar",t)}function g(e){ionic.DomUtil.cachedAttr(t,"nav-swipe",e)}var m,$,w,b="hide",y="$ionNavBarController",S="primaryButtons",k="secondaryButtons",C="backButton",T="primaryButtons secondaryButtons leftButtons rightButtons title".split(" "),B=this,I=[],x={},A=!0;t.parent().data(y,B);var E=n.delegateHandle||"navBar"+ionic.Utils.nextUid(),V=r._registerInstance(B,E);B.init=function(){t.addClass("nav-bar-container"),ionic.DomUtil.cachedAttr(t,"nav-bar-transition",a.views.transition()),B.createHeaderBar(!1),B.createHeaderBar(!0),e.$emit("ionNavBar.init",E)},B.createHeaderBar=function(o){function r(e,t){e&&("title"===t?g.append(e):"rightButtons"==t||t==k&&"left"!=a.navBar.positionSecondaryButtons()||t==S&&"right"==a.navBar.positionPrimaryButtons()?(v||(v=h('<div class="buttons buttons-right">'),f.append(v)),t==k?v.append(e):v.prepend(e)):(p||(p=h('<div class="buttons buttons-left">'),m[C]?m[C].after(p):f.prepend(p)),t==k?p.append(e):p.prepend(e)))}var c=h('<div class="nav-bar-block">');ionic.DomUtil.cachedAttr(c,"nav-bar",o?"active":"cached");var s=n.alignTitle||a.navBar.alignTitle(),f=h("<ion-header-bar>").addClass(n["class"]).attr("align-title",s);u(n.noTapScroll)&&f.attr("no-tap-scroll",n.noTapScroll);var p,v,g=h('<div class="title title-'+s+'">'),m={},$={};m[C]=d(C),m[C]&&f.append(m[C]),f.append(g),l(T,function(e){m[e]=d(e),r(m[e],e)});for(var w=0;w<f[0].children.length;w++)f[0].children[w].classList.add("header-item");c.append(f),t.append(i(c)(e.$new()));var y=f.data("$ionHeaderBarController");y.backButtonIcon=a.backButton.icon(),y.backButtonText=a.backButton.text();var B={isActive:o,title:function(e){y.title(e)},setItem:function(e,t){B.removeItem(t),e?("title"===t&&B.title(""),r(e,t),m[t]&&m[t].addClass(b),$[t]=e):m[t]&&m[t].removeClass(b)},removeItem:function(e){$[e]&&($[e].scope().$destroy(),$[e].remove(),$[e]=null)},containerEle:function(){return c},headerBarEle:function(){return f},afterLeave:function(){l(T,function(e){B.removeItem(e)}),y.resetBackButton()},controller:function(){return y},destroy:function(){l(T,function(e){B.removeItem(e)}),c.scope().$destroy();for(var e in m)m[e]&&(m[e].removeData(),m[e]=null);p&&p.removeData(),v&&v.removeData(),g.removeData(),f.removeData(),c.remove(),c=f=g=p=v=null}};return I.push(B),B},B.navElement=function(e,t){return u(t)&&(x[e]=t),x[e]},B.update=function(e){var t=!e.hasHeaderBar&&e.showNavBar;e.transition=a.views.transition(),t||(e.direction="none"),B.enable(t);var n=B.isInitialized?p():f(),i=B.isInitialized?f():null,o=n.controller();o.enableBack(e.enableBack,!0),o.showBack(e.showBack,!0),o.updateBackButton(),B.title(e.title,n),B.showBar(t),e.navBarItems&&l(T,function(t){n.setItem(e.navBarItems[t],t)}),B.transition(n,i,e),B.isInitialized=!0,g("")},B.transition=function(n,i,r){function c(){for(var e=0;e<I.length;e++)I[e].isActive=!1;n.isActive=!0,v(n,"active"),v(i,"cached"),B.activeTransition=d=$=null}var s=n.controller(),l=a.transitions.navBar[r.navBarTransition]||a.transitions.navBar.none,u=r.transitionId;s.beforeEnter(r);var d=l(n,i,r.direction,r.shouldAnimate&&B.isInitialized);ionic.DomUtil.cachedAttr(t,"nav-bar-transition",r.navBarTransition),ionic.DomUtil.cachedAttr(t,"nav-bar-direction",r.direction),d.shouldAnimate&&r.renderEnd?v(n,"stage"):(v(n,"entering"),v(i,"leaving")),s.resetBackButton(r),d.run(0),B.activeTransition={run:function(e){d.shouldAnimate=!1,d.direction="back",d.run(e)},cancel:function(t,o,r){g(o),v(i,"active"),v(n,"cached"),d.shouldAnimate=t,d.run(0),B.activeTransition=d=null;var a;r.showBar!==B.showBar()&&B.showBar(r.showBar),r.showBackButton!==B.showBackButton()&&B.showBackButton(r.showBackButton),a&&e.$apply()},complete:function(e,t){g(t),d.shouldAnimate=e,d.run(1),$=c}},o(s.align,16),(m=function(){w===u&&(v(n,"entering"),v(i,"leaving"),d.run(1),$=function(){w!=u&&d.shouldAnimate||c()},m=null)})()},B.triggerTransitionStart=function(e){w=e,m&&m()},B.triggerTransitionEnd=function(){
$&&$()},B.showBar=function(t){return arguments.length&&(B.visibleBar(t),e.$parent.$hasHeader=!!t),!!e.$parent.$hasHeader},B.visibleBar=function(e){e&&!A?(t.removeClass(b),B.align()):!e&&A&&t.addClass(b),A=e},B.enable=function(e){B.visibleBar(e);for(var t=0;t<r._instances.length;t++)r._instances[t]!==B&&r._instances[t].visibleBar(!1)},B.showBackButton=function(t){if(arguments.length){for(var n=0;n<I.length;n++)I[n].controller().showNavBack(!!t);e.$isBackButtonShown=!!t}return e.$isBackButtonShown},B.showActiveBackButton=function(e){var t=f();return t?arguments.length?t.controller().showBack(e):t.controller().showBack():void 0},B.title=function(t,n){return u(t)&&(t=t||"",n=n||f(),n&&n.title(t),e.$title=t,c.currentTitle(t)),e.$title},B.align=function(e,t){t=t||f(),t&&t.controller().align(e)},B.hasTabsTop=function(e){t[e?"addClass":"removeClass"]("nav-bar-tabs-top")},B.hasBarSubheader=function(e){t[e?"addClass":"removeClass"]("nav-bar-has-subheader")},B.changeTitle=function(e){s("changeTitle(val)","title(val)"),B.title(e)},B.setTitle=function(e){s("setTitle(val)","title(val)"),B.title(e)},B.getTitle=function(){return s("getTitle()","title()"),B.title()},B.back=function(){s("back()","$ionicHistory.goBack()"),c.goBack()},B.getPreviousTitle=function(){s("getPreviousTitle()","$ionicHistory.backTitle()"),c.goBack()},e.$on("$destroy",function(){e.$parent.$hasHeader=!1,t.parent().removeData(y);for(var n=0;n<I.length;n++)I[n].destroy();t.remove(),t=I=null,V()})}]),c.controller("$ionicNavView",["$scope","$element","$attrs","$compile","$controller","$ionicNavBarDelegate","$ionicNavViewDelegate","$ionicHistory","$ionicViewSwitcher","$ionicConfig","$ionicScrollDelegate",function(e,t,n,i,o,r,a,c,l,u,d){function f(e,n){for(var i,o,r=t.children(),a=0,c=r.length;c>a;a++)if(i=r.eq(a),A(i)==T){o=i.scope(),o&&o.$emit(e.name.replace("Tabs","View"),n);break}}function h(e){ionic.DomUtil.cachedAttr(t,"nav-swipe",e)}function p(e,t){var n=g();n&&n.hasTabsTop(t)}function v(e,t){var n=g();n&&n.hasBarSubheader(t)}function g(){if($)for(var e=0;e<r._instances.length;e++)if(r._instances[e].$$delegateHandle==$)return r._instances[e];return t.inheritedData("$ionNavBarController")}var m,$,w,b,y,S="$eleId",k="$destroyEle",C="$noCache",T="active",B="cached",I=this,x=!1,A=l.navViewAttr;I.scope=e,I.element=t,I.init=function(){var i=n.name||"",o=t.parent().inheritedData("$uiView"),r=o&&o.state?o.state.name:"";i.indexOf("@")<0&&(i=i+"@"+r);var c={name:i,state:null};t.data("$uiView",c);var s=a._registerInstance(I,n.delegateHandle);return e.$on("$destroy",function(){s(),I.isSwipeFreeze&&d.freezeAllScrolls(!1)}),e.$on("$ionicHistory.deselect",I.cacheCleanup),e.$on("$ionicTabs.top",p),e.$on("$ionicSubheader",v),e.$on("$ionicTabs.beforeLeave",f),e.$on("$ionicTabs.afterLeave",f),e.$on("$ionicTabs.leave",f),ionic.Platform.ready(function(){ionic.Platform.isWebView()&&u.views.swipeBackEnabled()&&I.initSwipeBack()}),c},I.register=function(t){var n=s({},c.currentView()),i=c.register(e,t);I.update(i);var o=c.getViewById(i.viewId)||{},r=b!==i.viewId;I.render(i,t,o,n,r,!0)},I.update=function(e){x=!0,m=e.direction;var n=t.parent().inheritedData("$ionNavViewController");n&&(n.isPrimary(!1),("enter"===m||"exit"===m)&&(n.direction(m),"enter"===m&&(m="none")))},I.render=function(e,t,n,i,o,r){var a=l.create(I,t,n,i,o,r);a.init(e,function(){a.transition(I.direction(),e.enableBack,!y),b=y=null})},I.beforeEnter=function(e){if(x){$=e.navBarDelegate;var t=g();t&&t.update(e),h("")}},I.activeEleId=function(e){return arguments.length&&(w=e),w},I.transitionEnd=function(){var e,n,i,o=t.children();for(e=0,n=o.length;n>e;e++)i=o.eq(e),i.data(S)===w?A(i,T):("leaving"===A(i)||A(i)===T||A(i)===B)&&(i.data(k)||i.data(C)?l.destroyViewEle(i):(A(i,B),ionic.Utils.disconnectScope(i.scope())));h(""),I.isSwipeFreeze&&d.freezeAllScrolls(!1)},I.cacheCleanup=function(){for(var e=t.children(),n=0,i=e.length;i>n;n++)e.eq(n).data(k)&&l.destroyViewEle(e.eq(n))},I.clearCache=function(e){var n,i,o,r,a,c,s=t.children();for(o=0,r=s.length;r>o;o++)if(n=s.eq(o),e)for(c=n.data(S),a=0;a<e.length;a++)c===e[a]&&l.destroyViewEle(n);else A(n)==B?l.destroyViewEle(n):A(n)==T&&(i=n.scope(),i&&i.$broadcast("$ionicView.clearCache"))},I.getViewElements=function(){return t.children()},I.appendViewElement=function(n,r){var a=i(n);t.append(n);var c=e.$new();if(r&&r.$$controller){r.$scope=c;var s=o(r.$$controller,r);r.$$controllerAs&&(c[r.$$controllerAs]=s),t.children().data("$ngControllerController",s)}return a(c),c},I.title=function(e){var t=g();t&&t.title(e)},I.enableBackButton=function(e){var t=g();t&&t.enableBackButton(e)},I.showBackButton=function(e){var t=g();return t?arguments.length?t.showActiveBackButton(e):t.showActiveBackButton():!0},I.showBar=function(e){var t=g();return t?arguments.length?t.showBar(e):t.showBar():!0},I.isPrimary=function(e){return arguments.length&&(x=e),x},I.direction=function(e){return arguments.length&&(m=e),m},I.initSwipeBack=function(){function n(e){if(x&&(S=r(e),!(S>C))){p=c.backView();var n=c.currentView();if(p&&p.historyId===n.historyId&&n.canSwipeBack!==!1){w||(w=window.innerWidth),I.isSwipeFreeze=d.freezeAllScrolls(!0);var a={direction:"back"};k=[],T={showBar:I.showBar(),showBackButton:I.showBackButton()};var u=l.create(I,a,p,n,!0,!1);u.loadViewElements(a),u.render(a),s=u.transition("back",c.enabledBack(p),!0),f=g(),m=ionic.onGesture("drag",i,t[0]),$=ionic.onGesture("release",o,t[0])}}}function i(e){if(x&&s){var t=r(e);if(k.push({t:Date.now(),x:t}),t>=w-15)o(e);else{var n=Math.min(Math.max(a(t),0),1);s.run(n),f&&f.activeTransition&&f.activeTransition.run(n)}}}function o(e){if(x&&s&&k&&k.length>1){for(var t=Date.now(),n=r(e),c=k[k.length-1],l=k.length-2;l>=0&&!(t-c.t>200);l--)c=k[l];var u=n>=k[k.length-2].x,v=a(n),g=Math.abs(c.x-n)/(t-c.t);if(b=p.viewId,y=.03>v||v>.97,u&&(v>.5||g>.1)){var S=g>.5||.05>g||n>w-45?"fast":"slow";h(y?"":S),p.go(),f&&f.activeTransition&&f.activeTransition.complete(!y,S)}else h(y?"":"fast"),b=null,s.cancel(!y),f&&f.activeTransition&&f.activeTransition.cancel(!y,"fast",T),y=null}ionic.offGesture(m,"drag",i),ionic.offGesture($,"release",o),w=s=k=null,I.isSwipeFreeze=d.freezeAllScrolls(!1)}function r(e){return ionic.tap.pointerCoord(e.gesture.srcEvent).x}function a(e){return(e-S)/w}var s,f,p,v,m,$,w,S,k,C=u.views.swipeBackHitWidth(),T={};v=ionic.onGesture("dragstart",n,t[0]),e.$on("$destroy",function(){ionic.offGesture(v,"dragstart",n),ionic.offGesture(m,"drag",i),ionic.offGesture($,"release",o),I.element=s=f=null})}}]),c.controller("$ionicRefresher",["$scope","$attrs","$element","$ionicBind","$timeout",function(e,t,n,i,o){function r(){(P||k)&&(E=null,k?(k=!1,T=0,B>I?(g(),f(I,A)):(f(0,A,v),C=!1)):(T=0,C=!1,d(!1)))}function a(e){if(P&&!(e.touches.length>1)){if(null===E&&(E=parseInt(e.touches[0].screenY,10)),ionic.Platform.isAndroid()&&4.4===ionic.Platform.version()&&0===b.scrollTop&&(k=!0,e.preventDefault()),V=parseInt(e.touches[0].screenY,10)-E,0>=V-T||0!==b.scrollTop)return C&&(C=!1,d(!1)),k&&l(b,-1*parseInt(V-T,10)),void(0!==B&&s(0));V>0&&0===b.scrollTop&&!C&&(T=V),e.preventDefault(),C||(C=!0,d(!0)),k=!0,s(parseInt((V-T)/3,10)),!x&&B>I?(x=!0,ionic.requestAnimationFrame(p)):x&&I>B&&(x=!1,ionic.requestAnimationFrame(v))}}function c(e){P=0===e.target.scrollTop||k}function s(e){y.style[ionic.CSS.TRANSFORM]="translateY("+e+"px)",B=e}function l(e,t){e.scrollTop=t;var n=document.createEvent("UIEvents");n.initUIEvent("scroll",!0,!0,window,1),e.dispatchEvent(n)}function d(e){e?ionic.requestAnimationFrame(function(){y.classList.add("overscroll"),m()}):ionic.requestAnimationFrame(function(){y.classList.remove("overscroll"),$(),v()})}function f(e,t,n){function i(e){return--e*e*e+1}function o(){var c=Date.now(),l=Math.min(1,(c-r)/t),u=i(l);s(parseInt(u*(e-a)+a,10)),1>l?ionic.requestAnimationFrame(o):(5>e&&e>-5&&(C=!1,d(!1)),n&&n())}var r=Date.now(),a=B;return a===e?void n():void ionic.requestAnimationFrame(o)}function h(){ionic.off("touchmove",a,y),ionic.off("touchend",r,y),ionic.off("scroll",c,b),b=null,y=null}function p(){n[0].classList.add("active"),e.$onPulling()}function v(){o(function(){n.removeClass("active refreshing refreshing-tail"),x&&(x=!1)},150)}function g(){n[0].classList.add("refreshing"),e.$onRefresh()}function m(){n[0].classList.remove("invisible")}function $(){n[0].classList.add("invisible")}function w(){n[0].classList.add("refreshing-tail")}var b,y,S=this,k=!1,C=!1,T=0,B=0,I=60,x=!1,A=500,E=null,V=null,P=!0;u(t.pullingIcon)||t.$set("pullingIcon","ion-android-arrow-down"),e.showSpinner=!u(t.refreshingIcon)&&"none"!=t.spinner,e.showIcon=u(t.refreshingIcon),i(e,t,{pullingIcon:"@",pullingText:"@",refreshingIcon:"@",refreshingText:"@",spinner:"@",disablePullingRotation:"@",$onRefresh:"&onRefresh",$onPulling:"&onPulling"}),e.$on("scroll.refreshComplete",function(){o(function(){ionic.requestAnimationFrame(w),f(0,A,v),o(function(){C&&(C=!1,d(!1))},A)},A)}),S.init=function(){if(b=n.parent().parent()[0],y=n.parent()[0],!(b&&b.classList.contains("ionic-scroll")&&y&&y.classList.contains("scroll")))throw new Error("Refresher must be immediate child of ion-content or ion-scroll");ionic.on("touchmove",a,y),ionic.on("touchend",r,y),ionic.on("scroll",c,b),e.$on("$destroy",h)},S.getRefresherDomMethods=function(){return{activate:p,deactivate:v,start:g,show:m,hide:$,tail:w}},S.__handleTouchmove=a,S.__getScrollChild=function(){return y},S.__getScrollParent=function(){return b}}]),c.controller("$ionicScroll",["$scope","scrollViewOptions","$timeout","$window","$location","$document","$ionicScrollDelegate","$ionicHistory",function(e,t,n,i,o,r,a,c){var s=this;s.__timeout=n,s._scrollViewOptions=t,s.isNative=function(){return!!t.nativeScrolling};var l,d=s.element=t.el,f=s.$element=h(d);l=s.isNative()?s.scrollView=new ionic.views.ScrollNative(t):s.scrollView=new ionic.views.Scroll(t),(f.parent().length?f.parent():f).data("$$ionicScrollController",s);var p=a._registerInstance(s,t.delegateHandle,function(){return c.isActiveScope(e)});u(t.bouncing)||ionic.Platform.ready(function(){l.options&&(l.options.bouncing=!0,ionic.Platform.isAndroid()&&(l.options.bouncing=!1,l.options.deceleration=.95))});var v=angular.bind(l,l.resize);angular.element(i).on("resize",v);var g=function(t){var n=(t.originalEvent||t).detail||{};e.$onScroll&&e.$onScroll({event:t,scrollTop:n.scrollTop||0,scrollLeft:n.scrollLeft||0})};f.on("scroll",g),e.$on("$destroy",function(){p(),l&&l.__cleanup&&l.__cleanup(),angular.element(i).off("resize",v),f.off("scroll",g),l=s.scrollView=t=s._scrollViewOptions=t.el=s._scrollViewOptions.el=f=s.$element=d=null}),n(function(){l&&l.run&&l.run()}),s.getScrollView=function(){return l},s.getScrollPosition=function(){return l.getValues()},s.resize=function(){return n(v,0,!1).then(function(){f&&f.triggerHandler("scroll-resize")})},s.scrollTop=function(e){s.resize().then(function(){l.scrollTo(0,0,!!e)})},s.scrollBottom=function(e){s.resize().then(function(){var t=l.getScrollMax();l.scrollTo(t.left,t.top,!!e)})},s.scrollTo=function(e,t,n){s.resize().then(function(){l.scrollTo(e,t,!!n)})},s.zoomTo=function(e,t,n,i){s.resize().then(function(){l.zoomTo(e,!!t,n,i)})},s.zoomBy=function(e,t,n,i){s.resize().then(function(){l.zoomBy(e,!!t,n,i)})},s.scrollBy=function(e,t,n){s.resize().then(function(){l.scrollBy(e,t,!!n)})},s.anchorScroll=function(e){s.resize().then(function(){var t=o.hash(),n=t&&r[0].getElementById(t);if(!t||!n)return void l.scrollTo(0,0,!!e);var i=n,a=0,c=0;do null!==i&&(a+=i.offsetLeft),null!==i&&(c+=i.offsetTop),i=i.offsetParent;while(i.attributes!=s.element.attributes&&i.offsetParent);l.scrollTo(a,c,!!e)})},s.freezeScroll=l.freeze,s.freezeAllScrolls=function(e){for(var t=0;t<a._instances.length;t++)a._instances[t].freezeScroll(e)},s._setRefresher=function(e,t,n){s.refresher=t;var i=s.refresher.clientHeight||60;l.activatePullToRefresh(i,n)}}]),c.controller("$ionicSideMenus",["$scope","$attrs","$ionicSideMenuDelegate","$ionicPlatform","$ionicBody","$ionicHistory","$ionicScrollDelegate","IONIC_BACK_PRIORITY","$rootScope",function(e,t,n,i,o,r,a,c,s){function l(e){e&&!w.isScrollFreeze?a.freezeAllScrolls(e):!e&&w.isScrollFreeze&&a.freezeAllScrolls(!1),w.isScrollFreeze=e}var u,f,h,v,g,m,$,w=this,b=!0;w.$scope=e,w.initialize=function(e){w.left=e.left,w.right=e.right,w.setContent(e.content),w.dragThresholdX=e.dragThresholdX||10,r.registerHistory(w.$scope)},w.setContent=function(e){e&&(w.content=e,w.content.onDrag=function(e){w._handleDrag(e)},w.content.endDrag=function(e){w._endDrag(e)})},w.isOpenLeft=function(){return w.getOpenAmount()>0},w.isOpenRight=function(){return w.getOpenAmount()<0},w.toggleLeft=function(e){if(!$&&w.left.isEnabled){var t=w.getOpenAmount();0===arguments.length&&(e=0>=t),w.content.enableAnimation(),e?(w.openPercentage(100),s.$emit("$ionicSideMenuOpen","left")):(w.openPercentage(0),s.$emit("$ionicSideMenuClose","left"))}},w.toggleRight=function(e){if(!$&&w.right.isEnabled){var t=w.getOpenAmount();0===arguments.length&&(e=t>=0),w.content.enableAnimation(),e?(w.openPercentage(-100),s.$emit("$ionicSideMenuOpen","right")):(w.openPercentage(0),s.$emit("$ionicSideMenuClose","right"))}},w.toggle=function(e){"right"==e?w.toggleRight():w.toggleLeft()},w.close=function(){w.openPercentage(0),s.$emit("$ionicSideMenuClose","left"),s.$emit("$ionicSideMenuClose","right")},w.getOpenAmount=function(){return w.content&&w.content.getTranslateX()||0},w.getOpenRatio=function(){var e=w.getOpenAmount();return e>=0?e/w.left.width:e/w.right.width},w.isOpen=function(){return 0!==w.getOpenAmount()},w.getOpenPercentage=function(){return 100*w.getOpenRatio()},w.openPercentage=function(e){var t=e/100;w.left&&e>=0?w.openAmount(w.left.width*t):w.right&&0>e&&w.openAmount(w.right.width*t),o.enableClass(0!==e,"menu-open"),l(!1)},w.openAmount=function(e){var t=w.left&&w.left.width||0,n=w.right&&w.right.width||0;return(w.left&&w.left.isEnabled||!(e>0))&&(w.right&&w.right.isEnabled||!(0>e))?f&&e>t?void w.content.setTranslateX(t):u&&-n>e?void w.content.setTranslateX(-n):(w.content.setTranslateX(e),void(e>=0?(f=!0,u=!1,e>0&&(w.right&&w.right.pushDown&&w.right.pushDown(),w.left&&w.left.bringUp&&w.left.bringUp())):(u=!0,f=!1,w.right&&w.right.bringUp&&w.right.bringUp(),w.left&&w.left.pushDown&&w.left.pushDown()))):void w.content.setTranslateX(0)},w.snapToRest=function(e){w.content.enableAnimation(),h=!1;var t=w.getOpenRatio();if(0===t)return void w.openPercentage(0);var n=.3,i=e.gesture.velocityX,o=e.gesture.direction;t>0&&.5>t&&"right"==o&&n>i?w.openPercentage(0):t>.5&&"left"==o&&n>i?w.openPercentage(100):0>t&&t>-.5&&"left"==o&&n>i?w.openPercentage(0):.5>t&&"right"==o&&n>i?w.openPercentage(-100):"right"==o&&t>=0&&(t>=.5||i>n)?w.openPercentage(100):"left"==o&&0>=t&&(-.5>=t||i>n)?w.openPercentage(-100):w.openPercentage(0)},w.enableMenuWithBackViews=function(e){return arguments.length&&(b=!!e),b},w.isAsideExposed=function(){return!!$},w.exposeAside=function(e){(w.left&&w.left.isEnabled||w.right&&w.right.isEnabled)&&(w.close(),$=e,w.left&&w.left.isEnabled?w.content.setMarginLeft($?w.left.width:0):w.right&&w.right.isEnabled&&w.content.setMarginRight($?w.right.width:0),w.$scope.$emit("$ionicExposeAside",$))},w.activeAsideResizing=function(e){o.enableClass(e,"aside-resizing")},w._endDrag=function(e){l(!1),$||(h&&w.snapToRest(e),v=null,g=null,m=null)},w._handleDrag=function(t){!$&&e.dragContent&&(v?g=t.gesture.touches[0].pageX:(v=t.gesture.touches[0].pageX,g=v),!h&&Math.abs(g-v)>w.dragThresholdX&&(v=g,h=!0,w.content.disableAnimation(),m=w.getOpenAmount()),h&&(w.openAmount(m+(g-v)),l(!0)))},w.canDragContent=function(t){return arguments.length&&(e.dragContent=!!t),e.dragContent},w.edgeThreshold=25,w.edgeThresholdEnabled=!1,w.edgeDragThreshold=function(e){return arguments.length&&(d(e)&&e>0?(w.edgeThreshold=e,w.edgeThresholdEnabled=!0):w.edgeThresholdEnabled=!!e),w.edgeThresholdEnabled},w.isDraggableTarget=function(t){var n=w.edgeThresholdEnabled&&!w.isOpen(),i=t.gesture.startEvent&&t.gesture.startEvent.center&&t.gesture.startEvent.center.pageX,o=!n||i<=w.edgeThreshold||i>=w.content.element.offsetWidth-w.edgeThreshold,a=r.backView(),c=b?!0:!a;if(!c){var s=r.currentView()||{};return a.historyId!==s.historyId}return(e.dragContent||w.isOpen())&&o&&!t.gesture.srcEvent.defaultPrevented&&c&&!t.target.tagName.match(/input|textarea|select|object|embed/i)&&!t.target.isContentEditable&&!(t.target.dataset?t.target.dataset.preventScroll:"true"==t.target.getAttribute("data-prevent-scroll"))},e.sideMenuContentTranslateX=0;var y=p,S=angular.bind(w,w.close);e.$watch(function(){return 0!==w.getOpenAmount()},function(e){y(),e&&(y=i.registerBackButtonAction(S,c.sideMenu))});var k=n._registerInstance(w,t.delegateHandle,function(){return r.isActiveScope(e)});e.$on("$destroy",function(){k(),y(),w.$scope=null,w.content&&(w.content.element=null,w.content=null),l(!1)}),w.initialize({left:{width:275},right:{width:275}})}]),function(e){function t(e,i,o,r){var a,c,s,l=document.createElement(f[e]||e);for(a in i)if(angular.isArray(i[a]))for(c=0;c<i[a].length;c++)if(i[a][c].fn)for(s=0;s<i[a][c].t;s++)t(a,i[a][c].fn(s,r),l,r);else t(a,i[a][c],l,r);else n(l,a,i[a]);o.appendChild(l)}function n(e,t,n){e.setAttribute(f[t]||t,n)}function i(e,t){var n=e.split(";"),i=n.slice(t),o=n.slice(0,n.length-i.length);return n=i.concat(o).reverse(),n.join(";")+";"+n[0]}function o(e,t){return e/=t/2,1>e?.5*e*e*e:(e-=2,.5*(e*e*e+2))}var r="translate(32,32)",a="stroke-opacity",s="round",l="indefinite",u="750ms",d="none",f={a:"animate",an:"attributeName",at:"animateTransform",c:"circle",da:"stroke-dasharray",os:"stroke-dashoffset",f:"fill",lc:"stroke-linecap",rc:"repeatCount",sw:"stroke-width",t:"transform",v:"values"},h={v:"0,32,32;360,32,32",an:"transform",type:"rotate",rc:l,dur:u},p={sw:4,lc:s,line:[{fn:function(e,t){return{y1:"ios"==t?17:12,y2:"ios"==t?29:20,t:r+" rotate("+(30*e+(6>e?180:-180))+")",a:[{fn:function(){return{an:a,dur:u,v:i("0;.1;.15;.25;.35;.45;.55;.65;.7;.85;1",e),rc:l}},t:1}]}},t:12}]},v={android:{c:[{sw:6,da:128,os:82,r:26,cx:32,cy:32,f:d}]},ios:p,"ios-small":p,bubbles:{sw:0,c:[{fn:function(e){return{cx:24*Math.cos(2*Math.PI*e/8),cy:24*Math.sin(2*Math.PI*e/8),t:r,a:[{fn:function(){return{an:"r",dur:u,v:i("1;2;3;4;5;6;7;8",e),rc:l}},t:1}]}},t:8}]},circles:{c:[{fn:function(e){return{r:5,cx:24*Math.cos(2*Math.PI*e/8),cy:24*Math.sin(2*Math.PI*e/8),t:r,sw:0,a:[{fn:function(){return{an:"fill-opacity",dur:u,v:i(".3;.3;.3;.4;.7;.85;.9;1",e),rc:l}},t:1}]}},t:8}]},crescent:{c:[{sw:4,da:128,os:82,r:26,cx:32,cy:32,f:d,at:[h]}]},dots:{c:[{fn:function(e){return{cx:16+16*e,cy:32,sw:0,a:[{fn:function(){return{an:"fill-opacity",dur:u,v:i(".5;.6;.8;1;.8;.6;.5",e),rc:l}},t:1},{fn:function(){return{an:"r",dur:u,v:i("4;5;6;5;4;3;3",e),rc:l}},t:1}]}},t:3}]},lines:{sw:7,lc:s,line:[{fn:function(e){return{x1:10+14*e,x2:10+14*e,a:[{fn:function(){return{an:"y1",dur:u,v:i("16;18;28;18;16",e),rc:l}},t:1},{fn:function(){return{an:"y2",dur:u,v:i("48;44;36;46;48",e),rc:l}},t:1},{fn:function(){return{an:a,dur:u,v:i("1;.8;.5;.4;1",e),rc:l}},t:1}]}},t:4}]},ripple:{f:d,"fill-rule":"evenodd",sw:3,circle:[{fn:function(e){return{cx:32,cy:32,a:[{fn:function(){return{an:"r",begin:-1*e+"s",dur:"2s",v:"0;24",keyTimes:"0;1",keySplines:"0.1,0.2,0.3,1",calcMode:"spline",rc:l}},t:1},{fn:function(){return{an:a,begin:-1*e+"s",dur:"2s",v:".2;1;.2;0",rc:l}},t:1}]}},t:2}]},spiral:{defs:[{linearGradient:[{id:"sGD",gradientUnits:"userSpaceOnUse",x1:55,y1:46,x2:2,y2:46,stop:[{offset:.1,"class":"stop1"},{offset:1,"class":"stop2"}]}]}],g:[{sw:4,lc:s,f:d,path:[{stroke:"url(#sGD)",d:"M4,32 c0,15,12,28,28,28c8,0,16-4,21-9"},{d:"M60,32 C60,16,47.464,4,32,4S4,16,4,32"}],at:[h]}]}},g={android:function(t){function i(){var t=o(Date.now()-r,650),u=1,d=0,f=188-58*t,h=182-182*t;a%2&&(u=-1,d=-64,f=128- -58*t,h=182*t);var p=[0,-101,-90,-11,-180,79,-270,-191][a];n(l,"da",Math.max(Math.min(f,188),128)),n(l,"os",Math.max(Math.min(h,182),0)),n(l,"t","scale("+u+",1) translate("+d+",0) rotate("+p+",32,32)"),c+=4.1,c>359&&(c=0),n(s,"t","rotate("+c+",32,32)"),t>=1&&(a++,a>7&&(a=0),r=Date.now()),e.requestAnimationFrame(i)}var r,a=0,c=0,s=t.querySelector("g"),l=t.querySelector("circle");return function(){r=Date.now(),i()}}};c.controller("$ionicSpinner",["$element","$attrs","$ionicConfig",function(e,n,i){var o;this.init=function(){o=n.icon||i.spinner.icon();var r=document.createElement("div");return t("svg",{viewBox:"0 0 64 64",g:[v[o]]},r,o),e.html(r.innerHTML),this.start(),o},this.start=function(){g[o]&&g[o](e[0])()}}])}(ionic),c.controller("$ionicTab",["$scope","$ionicHistory","$attrs","$location","$state",function(e,t,n,i,o){this.$scope=e,this.hrefMatchesState=function(){return n.href&&0===i.path().indexOf(n.href.replace(/^#/,"").replace(/\/$/,""))},this.srefMatchesState=function(){return n.uiSref&&o.includes(n.uiSref.split("(")[0])},this.navNameMatchesState=function(){return this.navViewName&&t.isCurrentStateNavView(this.navViewName)},this.tabMatchesState=function(){return this.hrefMatchesState()||this.srefMatchesState()||this.navNameMatchesState()}}]),c.controller("$ionicTabs",["$scope","$element","$ionicHistory",function(e,t,n){var i,o=this,r=null,a=null;o.tabs=[],o.selectedIndex=function(){return o.tabs.indexOf(r)},o.selectedTab=function(){return r},o.previousSelectedTab=function(){return a},o.add=function(e){n.registerHistory(e),o.tabs.push(e)},o.remove=function(e){var t=o.tabs.indexOf(e);if(-1!==t){if(e.$tabSelected)if(o.deselect(e),1===o.tabs.length);else{var n=t===o.tabs.length-1?t-1:t+1;o.select(o.tabs[n])}o.tabs.splice(t,1)}},o.deselect=function(e){e.$tabSelected&&(a=r,r=i=null,e.$tabSelected=!1,(e.onDeselect||p)(),e.$broadcast&&e.$broadcast("$ionicHistory.deselect"))},o.select=function(t,a){var c;if(d(t)){if(c=t,c>=o.tabs.length)return;t=o.tabs[c]}else c=o.tabs.indexOf(t);1===arguments.length&&(a=!(!t.navViewName&&!t.uiSref)),r&&r.$historyId==t.$historyId?a&&n.goToHistoryRoot(t.$historyId):i!==c&&(l(o.tabs,function(e){o.deselect(e)}),r=t,i=c,o.$scope&&o.$scope.$parent&&(o.$scope.$parent.$activeHistoryId=t.$historyId),t.$tabSelected=!0,(t.onSelect||p)(),a&&e.$emit("$ionicHistory.change",{type:"tab",tabIndex:c,historyId:t.$historyId,navViewName:t.navViewName,hasNavView:!!t.navViewName,title:t.title,url:t.href,uiSref:t.uiSref}))},o.hasActiveScope=function(){for(var e=0;e<o.tabs.length;e++)if(n.isActiveScope(o.tabs[e]))return!0;return!1}}]),c.controller("$ionicView",["$scope","$element","$attrs","$compile","$rootScope",function(e,t,n,i,o){function r(){var t=u(n.viewTitle)&&"viewTitle"||u(n.title)&&"title";t&&(a(n[t]),$.push(n.$observe(t,a))),u(n.hideBackButton)&&$.push(e.$watch(n.hideBackButton,function(e){f.showBackButton(!e)})),u(n.hideNavBar)&&$.push(e.$watch(n.hideNavBar,function(e){f.showBar(!e)}))}function a(e){u(e)&&e!==v&&(v=e,f.title(v))}function c(){for(var e=0;e<$.length;e++)$[e]();$=[]}function l(t){return t?i(t)(e.$new()):void 0}function d(t){return!!e.$eval(n[t])}var f,h,p,v,g=this,m={},$=[],w=e.$on("ionNavBar.init",function(e,t){e.stopPropagation(),h=t});g.init=function(){w();var n=t.inheritedData("$ionModalController");f=t.inheritedData("$ionNavViewController"),f&&!n&&(e.$on("$ionicView.beforeEnter",g.beforeEnter),e.$on("$ionicView.afterEnter",r),e.$on("$ionicView.beforeLeave",c))},g.beforeEnter=function(t,i){if(i&&!i.viewNotified){i.viewNotified=!0,o.$$phase||e.$digest(),v=u(n.viewTitle)?n.viewTitle:n.title;var r={};for(var a in m)r[a]=l(m[a]);f.beforeEnter(s(i,{title:v,showBack:!d("hideBackButton"),navBarItems:r,navBarDelegate:h||null,showNavBar:!d("hideNavBar"),hasHeaderBar:!!p})),c()}},g.navElement=function(e,t){m[e]=t}}]),c.directive("ionActionSheet",["$document",function(e){return{restrict:"E",scope:!0,replace:!0,link:function(t,n){var i=function(e){27==e.which&&(t.cancel(),t.$apply())},o=function(e){e.target==n[0]&&(t.cancel(),t.$apply())};t.$on("$destroy",function(){n.remove(),e.unbind("keyup",i)}),e.bind("keyup",i),n.bind("click",o)},template:'<div class="action-sheet-backdrop"><div class="action-sheet-wrapper"><div class="action-sheet" ng-class="{\'action-sheet-has-icons\': $actionSheetHasIcon}"><div class="action-sheet-group action-sheet-options"><div class="action-sheet-title" ng-if="titleText" ng-bind-html="titleText"></div><button class="button action-sheet-option" ng-click="buttonClicked($index)" ng-repeat="b in buttons" ng-bind-html="b.text"></button><button class="button destructive action-sheet-destructive" ng-if="destructiveText" ng-click="destructiveButtonClicked()" ng-bind-html="destructiveText"></button></div><div class="action-sheet-group action-sheet-cancel" ng-if="cancelText"><button class="button" ng-click="cancel()" ng-bind-html="cancelText"></button></div></div></div></div>'}}]),c.directive("ionCheckbox",["$ionicConfig",function(e){return{restrict:"E",replace:!0,require:"?ngModel",transclude:!0,template:'<label class="item item-checkbox"><div class="checkbox checkbox-input-hidden disable-pointer-events"><input type="checkbox"><i class="checkbox-icon"></i></div><div class="item-content disable-pointer-events" ng-transclude></div></label>',compile:function(t,n){var i=t.find("input");l({name:n.name,"ng-value":n.ngValue,"ng-model":n.ngModel,"ng-checked":n.ngChecked,"ng-disabled":n.ngDisabled,"ng-true-value":n.ngTrueValue,"ng-false-value":n.ngFalseValue,"ng-change":n.ngChange,"ng-required":n.ngRequired,required:n.required},function(e,t){u(e)&&i.attr(t,e)});var o=t[0].querySelector(".checkbox");o.classList.add("checkbox-"+e.form.checkbox())}}}]),c.directive("collectionRepeat",e).factory("$ionicCollectionManager",t);var b="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",y=/height:.*?px;\s*width:.*?px/,S=3;e.$inject=["$ionicCollectionManager","$parse","$window","$$rAF","$rootScope","$timeout"],t.$inject=["$rootScope","$window","$$rAF"],c.directive("ionContent",["$timeout","$controller","$ionicBind","$ionicConfig",function(e,t,n,i){return{restrict:"E",require:"^?ionNavView",scope:!0,priority:800,compile:function(e,o){function r(e,i,r){function l(){e.$onScrollComplete({scrollTop:c.scrollView.__scrollTop,scrollLeft:c.scrollView.__scrollLeft})}var d=e.$parent;if(e.$watch(function(){return(d.$hasHeader?" has-header":"")+(d.$hasSubheader?" has-subheader":"")+(d.$hasFooter?" has-footer":"")+(d.$hasSubfooter?" has-subfooter":"")+(d.$hasTabs?" has-tabs":"")+(d.$hasTabsTop?" has-tabs-top":"")},function(e,t){i.removeClass(t),i.addClass(e)}),e.$hasHeader=e.$hasSubheader=e.$hasFooter=e.$hasSubfooter=e.$hasTabs=e.$hasTabsTop=!1,n(e,r,{$onScroll:"&onScroll",$onScrollComplete:"&onScrollComplete",hasBouncing:"@",padding:"@",direction:"@",scrollbarX:"@",scrollbarY:"@",startX:"@",startY:"@",scrollEventInterval:"@"}),e.direction=e.direction||"y",u(r.padding)&&e.$watch(r.padding,function(e){(a||i).toggleClass("padding",!!e)}),"false"===r.scroll);else{var f={};s?(i.addClass("overflow-scroll"),f={el:i[0],delegateHandle:o.delegateHandle,startX:e.$eval(e.startX)||0,startY:e.$eval(e.startY)||0,nativeScrolling:!0}):f={el:i[0],delegateHandle:o.delegateHandle,locking:"true"===(o.locking||"true"),bouncing:e.$eval(e.hasBouncing),startX:e.$eval(e.startX)||0,startY:e.$eval(e.startY)||0,scrollbarX:e.$eval(e.scrollbarX)!==!1,scrollbarY:e.$eval(e.scrollbarY)!==!1,scrollingX:e.direction.indexOf("x")>=0,scrollingY:e.direction.indexOf("y")>=0,scrollEventInterval:parseInt(e.scrollEventInterval,10)||10,scrollingComplete:l},c=t("$ionicScroll",{$scope:e,scrollViewOptions:f}),e.$on("$destroy",function(){f&&(f.scrollingComplete=p,delete f.el),a=null,i=null,o.$$element=null})}}var a,c;e.addClass("scroll-content ionic-scroll"),"false"!=o.scroll?(a=h('<div class="scroll"></div>'),a.append(e.contents()),e.append(a)):e.addClass("scroll-content-false");var s="true"===o.overflowScroll||!i.scrolling.jsScrolling();return s&&(s=!e[0].querySelector("[collection-repeat]")),{pre:r}}}}]),c.directive("exposeAsideWhen",["$window",function(e){return{restrict:"A",require:"^ionSideMenus",link:function(t,n,i,o){function r(){var t="large"==i.exposeAsideWhen?"(min-width:768px)":i.exposeAsideWhen;o.exposeAside(e.matchMedia(t).matches),o.activeAsideResizing(!1)}function a(){o.activeAsideResizing(!0),c()}var c=ionic.debounce(function(){t.$apply(r)},300,!1);t.$evalAsync(r),ionic.on("resize",a,e),t.$on("$destroy",function(){ionic.off("resize",a,e)})}}}]);var k="onHold onTap onDoubleTap onTouch onRelease onDragStart onDrag onDragEnd onDragUp onDragRight onDragDown onDragLeft onSwipe onSwipeUp onSwipeRight onSwipeDown onSwipeLeft".split(" ");k.forEach(function(e){c.directive(e,n(e))}),c.directive("ionHeaderBar",i()).directive("ionHeaderBar",o(!0)).directive("ionFooterBar",o(!1)),c.directive("ionInfiniteScroll",["$timeout",function(e){return{restrict:"E",require:["?^$ionicScroll","ionInfiniteScroll"],template:function(e,t){return t.icon?'<i class="icon {{icon()}} icon-refreshing {{scrollingType}}"></i>':'<ion-spinner icon="{{spinner()}}"></ion-spinner>'},scope:!0,controller:"$ionInfiniteScroll",link:function(t,n,i,o){var r=o[1],a=r.scrollCtrl=o[0],c=r.jsScrolling=!a.isNative();if(c)r.scrollView=a.scrollView,t.scrollingType="js-scrolling",a.$element.on("scroll",r.checkBounds);else{var s=ionic.DomUtil.getParentOrSelfWithClass(n[0].parentNode,"overflow-scroll");if(r.scrollEl=s,!s)throw"Infinite scroll must be used inside a scrollable div";r.scrollEl.addEventListener("scroll",r.checkBounds)}var l=u(i.immediateCheck)?t.$eval(i.immediateCheck):!0;l&&e(function(){r.checkBounds()})}}}]),c.directive("ionItem",["$$rAF",function(e){return{restrict:"E",controller:["$scope","$element",function(e,t){this.$scope=e,this.$element=t}],scope:!0,compile:function(t,n){var i=u(n.href)||u(n.ngHref)||u(n.uiSref),o=i||/ion-(delete|option|reorder)-button/i.test(t.html());if(o){var r=h(i?"<a></a>":"<div></div>");r.addClass("item-content"),(u(n.href)||u(n.ngHref))&&(r.attr("ng-href","{{$href()}}"),u(n.target)&&r.attr("target","{{$target()}}")),r.append(t.contents()),t.addClass("item item-complex").append(r)}else t.addClass("item");return function(t,n,i){t.$href=function(){return i.href||i.ngHref},t.$target=function(){return i.target};var o=n[0].querySelector(".item-content");o&&t.$on("$collectionRepeatLeave",function(){o&&o.$$ionicOptionsOpen&&(o.style[ionic.CSS.TRANSFORM]="",o.style[ionic.CSS.TRANSITION]="none",e(function(){o.style[ionic.CSS.TRANSITION]=""}),o.$$ionicOptionsOpen=!1)})}}}}]);var C='<div class="item-left-edit item-delete enable-pointer-events"></div>';c.directive("ionDeleteButton",function(){function e(e){e.stopPropagation()}return{restrict:"E",require:["^^ionItem","^?ionList"],priority:Number.MAX_VALUE,compile:function(t,n){return n.$set("class",(n["class"]||"")+" button icon button-icon",!0),function(t,n,i,o){function r(){c=c||n.controller("ionList"),c&&c.showDelete()&&s.addClass("visible active")}var a=o[0],c=o[1],s=h(C);s.append(n),a.$element.append(s).addClass("item-left-editable"),n.on("click",e),r(),t.$on("$ionic.reconnectScope",r)}}}}),c.directive("itemFloatingLabel",function(){return{restrict:"C",link:function(e,t){var n=t[0],i=n.querySelector("input, textarea"),o=n.querySelector(".input-label");if(i&&o){var r=function(){i.value?o.classList.add("has-input"):o.classList.remove("has-input")};i.addEventListener("input",r);var a=h(i).controller("ngModel");a&&(a.$render=function(){i.value=a.$viewValue||"",r()}),e.$on("$destroy",function(){i.removeEventListener("input",r)})}}}});var T='<div class="item-options invisible"></div>';c.directive("ionOptionButton",[function(){function e(e){e.stopPropagation()}return{restrict:"E",require:"^ionItem",priority:Number.MAX_VALUE,compile:function(t,n){return n.$set("class",(n["class"]||"")+" button",!0),function(t,n,i,o){o.optionsContainer||(o.optionsContainer=h(T),o.$element.append(o.optionsContainer)),o.optionsContainer.append(n),o.$element.addClass("item-right-editable"),n.on("click",e)}}}}]);var B='<div data-prevent-scroll="true" class="item-right-edit item-reorder enable-pointer-events"></div>';c.directive("ionReorderButton",["$parse",function(e){return{restrict:"E",require:["^ionItem","^?ionList"],priority:Number.MAX_VALUE,compile:function(t,n){return n.$set("class",(n["class"]||"")+" button icon button-icon",!0),
t[0].setAttribute("data-prevent-scroll",!0),function(t,n,i,o){var r=o[0],a=o[1],c=e(i.onReorder);t.$onReorder=function(e,n){c(t,{$fromIndex:e,$toIndex:n})},i.ngClick||i.onClick||i.onclick||(n[0].onclick=function(e){return e.stopPropagation(),!1});var s=h(B);s.append(n),r.$element.append(s).addClass("item-right-editable"),a&&a.showReorder()&&s.addClass("visible active")}}}}]),c.directive("keyboardAttach",function(){return function(e,t){function n(e){if(!ionic.Platform.isAndroid()||ionic.Platform.isFullScreen){var n=e.keyboardHeight||e.detail.keyboardHeight;t.css("bottom",n+"px"),o=t.controller("$ionicScroll"),o&&(o.scrollView.__container.style.bottom=n+r(t[0])+"px")}}function i(){(!ionic.Platform.isAndroid()||ionic.Platform.isFullScreen)&&(t.css("bottom",""),o&&(o.scrollView.__container.style.bottom=""))}ionic.on("native.keyboardshow",n,window),ionic.on("native.keyboardhide",i,window),ionic.on("native.showkeyboard",n,window),ionic.on("native.hidekeyboard",i,window);var o;e.$on("$destroy",function(){ionic.off("native.keyboardshow",n,window),ionic.off("native.keyboardhide",i,window),ionic.off("native.showkeyboard",n,window),ionic.off("native.hidekeyboard",i,window)})}}),c.directive("ionList",["$timeout",function(e){return{restrict:"E",require:["ionList","^?$ionicScroll"],controller:"$ionicList",compile:function(t,n){var i=h('<div class="list">').append(t.contents()).addClass(n.type);return t.append(i),function(t,i,o,r){function a(){function o(e,t){t()&&e.addClass("visible")||e.removeClass("active"),ionic.requestAnimationFrame(function(){t()&&e.addClass("active")||e.removeClass("visible")})}var r=c.listView=new ionic.views.ListView({el:i[0],listEl:i.children()[0],scrollEl:s&&s.element,scrollView:s&&s.scrollView,onReorder:function(t,n,i){var o=h(t).scope();o&&o.$onReorder&&e(function(){o.$onReorder(n,i)})},canSwipe:function(){return c.canSwipeItems()}});t.$on("$destroy",function(){r&&(r.deregister&&r.deregister(),r=null)}),u(n.canSwipe)&&t.$watch("!!("+n.canSwipe+")",function(e){c.canSwipeItems(e)}),u(n.showDelete)&&t.$watch("!!("+n.showDelete+")",function(e){c.showDelete(e)}),u(n.showReorder)&&t.$watch("!!("+n.showReorder+")",function(e){c.showReorder(e)}),t.$watch(function(){return c.showDelete()},function(e,t){if(e||t){e&&c.closeOptionButtons(),c.canSwipeItems(!e),i.children().toggleClass("list-left-editing",e),i.toggleClass("disable-pointer-events",e);var n=h(i[0].getElementsByClassName("item-delete"));o(n,c.showDelete)}}),t.$watch(function(){return c.showReorder()},function(e,t){if(e||t){e&&c.closeOptionButtons(),c.canSwipeItems(!e),i.children().toggleClass("list-right-editing",e),i.toggleClass("disable-pointer-events",e);var n=h(i[0].getElementsByClassName("item-reorder"));o(n,c.showReorder)}})}var c=r[0],s=r[1];e(a)}}}}]),c.directive("menuClose",["$ionicHistory","$timeout",function(e,t){return{restrict:"AC",link:function(n,i){i.bind("click",function(){var n=i.inheritedData("$ionSideMenusController");n&&(e.nextViewOptions({historyRoot:!0,disableAnimate:!0,expire:300}),t(function(){e.nextViewOptions({historyRoot:!1,disableAnimate:!1})},300),n.close())})}}}]),c.directive("menuToggle",function(){return{restrict:"AC",link:function(e,t,n){e.$on("$ionicView.beforeEnter",function(e,n){if(n.enableBack){var i=t.inheritedData("$ionSideMenusController");i.enableMenuWithBackViews()||t.addClass("hide")}else t.removeClass("hide")}),t.bind("click",function(){var e=t.inheritedData("$ionSideMenusController");e&&e.toggle(n.menuToggle)})}}}),c.directive("ionModal",[function(){return{restrict:"E",transclude:!0,replace:!0,controller:[function(){}],template:'<div class="modal-backdrop"><div class="modal-backdrop-bg"></div><div class="modal-wrapper" ng-transclude></div></div>'}}]),c.directive("ionModalView",function(){return{restrict:"E",compile:function(e){e.addClass("modal")}}}),c.directive("ionNavBackButton",["$ionicConfig","$document",function(e,t){return{restrict:"E",require:"^ionNavBar",compile:function(n,i){function o(e){return/ion-|icon/.test(e.className)}var r=t[0].createElement("button");for(var a in i.$attr)r.setAttribute(i.$attr[a],i[a]);i.ngClick||r.setAttribute("ng-click","$ionicGoBack()"),r.className="button back-button hide buttons "+(n.attr("class")||""),r.innerHTML=n.html()||"";for(var c,s,l,u,d=o(n[0]),f=0;f<n[0].childNodes.length;f++)c=n[0].childNodes[f],1===c.nodeType?o(c)?d=!0:c.classList.contains("default-title")?l=!0:c.classList.contains("previous-title")&&(u=!0):s||3!==c.nodeType||(s=!!c.nodeValue.trim());var h=e.backButton.icon();if(!d&&h&&"none"!==h&&(r.innerHTML='<i class="icon '+h+'"></i> '+r.innerHTML,r.className+=" button-clear"),!s){var p=t[0].createElement("span");p.className="back-text",!l&&e.backButton.text()&&(p.innerHTML+='<span class="default-title">'+e.backButton.text()+"</span>"),!u&&e.backButton.previousTitleText()&&(p.innerHTML+='<span class="previous-title"></span>'),r.appendChild(p)}return n.attr("class","hide"),n.empty(),{pre:function(e,t,n,i){i.navElement("backButton",r.outerHTML),r=null}}}}}]),c.directive("ionNavBar",function(){return{restrict:"E",controller:"$ionicNavBar",scope:!0,link:function(e,t,n,i){i.init()}}}),c.directive("ionNavButtons",["$document",function(e){return{require:"^ionNavBar",restrict:"E",compile:function(t,n){var i="left";/^primary|secondary|right$/i.test(n.side||"")&&(i=n.side.toLowerCase());var o=e[0].createElement("span");o.className=i+"-buttons",o.innerHTML=t.html();var r=i+"Buttons";return t.attr("class","hide"),t.empty(),{pre:function(e,t,n,i){var a=t.parent().data("$ionViewController");a?a.navElement(r,o.outerHTML):i.navElement(r,o.outerHTML),o=null}}}}}]),c.directive("navDirection",["$ionicViewSwitcher",function(e){return{restrict:"A",priority:1e3,link:function(t,n,i){n.bind("click",function(){e.nextDirection(i.navDirection)})}}}]),c.directive("ionNavTitle",["$document",function(e){return{require:"^ionNavBar",restrict:"E",compile:function(t,n){var i="title",o=e[0].createElement("span");for(var r in n.$attr)o.setAttribute(n.$attr[r],n[r]);return o.classList.add("nav-bar-title"),o.innerHTML=t.html(),t.attr("class","hide"),t.empty(),{pre:function(e,t,n,r){var a=t.parent().data("$ionViewController");a?a.navElement(i,o.outerHTML):r.navElement(i,o.outerHTML),o=null}}}}}]),c.directive("navTransition",["$ionicViewSwitcher",function(e){return{restrict:"A",priority:1e3,link:function(t,n,i){n.bind("click",function(){e.nextTransition(i.navTransition)})}}}]),c.directive("ionNavView",["$state","$ionicConfig",function(e,t){return{restrict:"E",terminal:!0,priority:2e3,transclude:!0,controller:"$ionicNavView",compile:function(n,i,o){return n.addClass("view-container"),ionic.DomUtil.cachedAttr(n,"nav-view-transition",t.views.transition()),function(t,n,i,r){function a(t){var n=e.$current&&e.$current.locals[s.name];n&&(t||n!==c)&&(c=n,s.state=n.$$state,r.register(n))}var c;o(t,function(e){n.append(e)});var s=r.init();t.$on("$stateChangeSuccess",function(){a(!1)}),t.$on("$viewContentLoading",function(){a(!1)}),a(!0)}}}}]),c.config(["$provide",function(e){e.decorator("ngClickDirective",["$delegate",function(e){return e.shift(),e}])}]).factory("$ionicNgClick",["$parse",function(e){return function(t,n,i){var o=angular.isFunction(i)?i:e(i);n.on("click",function(e){t.$apply(function(){o(t,{$event:e})})}),n.onclick=p}}]).directive("ngClick",["$ionicNgClick",function(e){return function(t,n,i){e(t,n,i.ngClick)}}]).directive("ionStopEvent",function(){return{restrict:"A",link:function(e,t,n){t.bind(n.ionStopEvent,a)}}}),c.directive("ionPane",function(){return{restrict:"E",link:function(e,t){t.addClass("pane")}}}),c.directive("ionPopover",[function(){return{restrict:"E",transclude:!0,replace:!0,controller:[function(){}],template:'<div class="popover-backdrop"><div class="popover-wrapper" ng-transclude></div></div>'}}]),c.directive("ionPopoverView",function(){return{restrict:"E",compile:function(e){e.append(h('<div class="popover-arrow">')),e.addClass("popover")}}}),c.directive("ionRadio",function(){return{restrict:"E",replace:!0,require:"?ngModel",transclude:!0,template:'<label class="item item-radio"><input type="radio" name="radio-group"><div class="radio-content"><div class="item-content disable-pointer-events" ng-transclude></div><i class="radio-icon disable-pointer-events icon ion-checkmark"></i></div></label>',compile:function(e,t){if(t.icon){var n=e.find("i");n.removeClass("ion-checkmark").addClass(t.icon)}var i=e.find("input");return l({name:t.name,value:t.value,disabled:t.disabled,"ng-value":t.ngValue,"ng-model":t.ngModel,"ng-disabled":t.ngDisabled,"ng-change":t.ngChange,"ng-required":t.ngRequired,required:t.required},function(e,t){u(e)&&i.attr(t,e)}),function(e,t,n){e.getValue=function(){return e.ngValue||n.value}}}}}),c.directive("ionRefresher",[function(){return{restrict:"E",replace:!0,require:["?^$ionicScroll","ionRefresher"],controller:"$ionicRefresher",template:'<div class="scroll-refresher invisible" collection-repeat-ignore><div class="ionic-refresher-content" ng-class="{\'ionic-refresher-with-text\': pullingText || refreshingText}"><div class="icon-pulling" ng-class="{\'pulling-rotation-disabled\':disablePullingRotation}"><i class="icon {{pullingIcon}}"></i></div><div class="text-pulling" ng-bind-html="pullingText"></div><div class="icon-refreshing"><ion-spinner ng-if="showSpinner" icon="{{spinner}}"></ion-spinner><i ng-if="showIcon" class="icon {{refreshingIcon}}"></i></div><div class="text-refreshing" ng-bind-html="refreshingText"></div></div></div>',link:function(e,t,n,i){var o=i[0],r=i[1];!o||o.isNative()?r.init():(t[0].classList.add("js-scrolling"),o._setRefresher(e,t[0],r.getRefresherDomMethods()),e.$on("scroll.refreshComplete",function(){e.$evalAsync(function(){o.scrollView.finishPullToRefresh()})}))}}}]),c.directive("ionScroll",["$timeout","$controller","$ionicBind",function(e,t,n){return{restrict:"E",scope:!0,controller:function(){},compile:function(e){function i(e,i,r){n(e,r,{direction:"@",paging:"@",$onScroll:"&onScroll",scroll:"@",scrollbarX:"@",scrollbarY:"@",zooming:"@",minZoom:"@",maxZoom:"@"}),e.direction=e.direction||"y",u(r.padding)&&e.$watch(r.padding,function(e){o.toggleClass("padding",!!e)}),e.$eval(e.paging)===!0&&o.addClass("scroll-paging"),e.direction||(e.direction="y");var a=e.$eval(e.paging)===!0,c={el:i[0],delegateHandle:r.delegateHandle,locking:"true"===(r.locking||"true"),bouncing:e.$eval(r.hasBouncing),paging:a,scrollbarX:e.$eval(e.scrollbarX)!==!1,scrollbarY:e.$eval(e.scrollbarY)!==!1,scrollingX:e.direction.indexOf("x")>=0,scrollingY:e.direction.indexOf("y")>=0,zooming:e.$eval(e.zooming)===!0,maxZoom:e.$eval(e.maxZoom)||3,minZoom:e.$eval(e.minZoom)||.5,preventDefault:!0};a&&(c.speedMultiplier=.8,c.bouncing=!1),t("$ionicScroll",{$scope:e,scrollViewOptions:c})}e.addClass("scroll-view ionic-scroll");var o=h('<div class="scroll"></div>');return o.append(e.contents()),e.append(o),{pre:i}}}}]),c.directive("ionSideMenu",function(){return{restrict:"E",require:"^ionSideMenus",scope:!0,compile:function(e,t){return angular.isUndefined(t.isEnabled)&&t.$set("isEnabled","true"),angular.isUndefined(t.width)&&t.$set("width","275"),e.addClass("menu menu-"+t.side),function(e,n,i,o){e.side=i.side||"left";var r=o[e.side]=new ionic.views.SideMenu({width:t.width,el:n[0],isEnabled:!0});e.$watch(i.width,function(e){var t=+e;t&&t==e&&r.setWidth(+e)}),e.$watch(i.isEnabled,function(e){r.setIsEnabled(!!e)})}}}}),c.directive("ionSideMenuContent",["$timeout","$ionicGesture","$window",function(e,t,n){return{restrict:"EA",require:"^ionSideMenus",scope:!0,compile:function(i,o){function r(r,a,c,s){function l(e){0!==s.getOpenAmount()?(s.close(),e.gesture.srcEvent.preventDefault(),v=null,g=null):v||(v=ionic.tap.pointerCoord(e.gesture.srcEvent))}function d(e){s.isDraggableTarget(e)&&"x"==p(e)&&(s._handleDrag(e),e.gesture.srcEvent.preventDefault())}function f(e){"x"==p(e)&&e.gesture.srcEvent.preventDefault()}function h(e){s._endDrag(e),v=null,g=null}function p(e){if(g)return g;if(e&&e.gesture){if(v){var t=ionic.tap.pointerCoord(e.gesture.srcEvent),n=Math.abs(t.x-v.x),i=Math.abs(t.y-v.y),o=i>n?"y":"x";return Math.max(n,i)>30&&(g=o),o}v=ionic.tap.pointerCoord(e.gesture.srcEvent)}return"y"}var v=null,g=null;u(o.dragContent)?r.$watch(o.dragContent,function(e){s.canDragContent(e)}):s.canDragContent(!0),u(o.edgeDragThreshold)&&r.$watch(o.edgeDragThreshold,function(e){s.edgeDragThreshold(e)});var m={element:i[0],onDrag:function(){},endDrag:function(){},getTranslateX:function(){return r.sideMenuContentTranslateX||0},setTranslateX:ionic.animationFrameThrottle(function(t){var n=m.offsetX+t;a[0].style[ionic.CSS.TRANSFORM]="translate3d("+n+"px,0,0)",e(function(){r.sideMenuContentTranslateX=t})}),setMarginLeft:ionic.animationFrameThrottle(function(e){e?(e=parseInt(e,10),a[0].style[ionic.CSS.TRANSFORM]="translate3d("+e+"px,0,0)",a[0].style.width=n.innerWidth-e+"px",m.offsetX=e):(a[0].style[ionic.CSS.TRANSFORM]="translate3d(0,0,0)",a[0].style.width="",m.offsetX=0)}),setMarginRight:ionic.animationFrameThrottle(function(e){e?(e=parseInt(e,10),a[0].style.width=n.innerWidth-e+"px",m.offsetX=e):(a[0].style.width="",m.offsetX=0),a[0].style[ionic.CSS.TRANSFORM]="translate3d(0,0,0)"}),enableAnimation:function(){r.animationEnabled=!0,a[0].classList.add("menu-animated")},disableAnimation:function(){r.animationEnabled=!1,a[0].classList.remove("menu-animated")},offsetX:0};s.setContent(m);var $={stop_browser_behavior:!1};ionic.DomUtil.getParentOrSelfWithClass(a[0],"overflow-scroll")&&($.prevent_default_directions=["left","right"]);var w=t.on("tap",l,a,$),b=t.on("dragright",d,a,$),y=t.on("dragleft",d,a,$),S=t.on("dragup",f,a,$),k=t.on("dragdown",f,a,$),C=t.on("release",h,a,$);r.$on("$destroy",function(){m&&(m.element=null,m=null),t.off(y,"dragleft",d),t.off(b,"dragright",d),t.off(S,"dragup",f),t.off(k,"dragdown",f),t.off(C,"release",h),t.off(w,"tap",l)})}return i.addClass("menu-content pane"),{pre:r}}}}]),c.directive("ionSideMenus",["$ionicBody",function(e){return{restrict:"ECA",controller:"$ionicSideMenus",compile:function(t,n){function i(t,n,i,o){o.enableMenuWithBackViews(t.$eval(i.enableMenuWithBackViews)),t.$on("$ionicExposeAside",function(n,i){t.$exposeAside||(t.$exposeAside={}),t.$exposeAside.active=i,e.enableClass(i,"aside-open")}),t.$on("$ionicView.beforeEnter",function(e,n){n.historyId&&(t.$activeHistoryId=n.historyId)}),t.$on("$destroy",function(){e.removeClass("menu-open","aside-open")})}return n.$set("class",(n["class"]||"")+" view"),{pre:i}}}}]),c.directive("ionSlideBox",["$timeout","$compile","$ionicSlideBoxDelegate","$ionicHistory","$ionicScrollDelegate",function(e,t,n,i,o){return{restrict:"E",replace:!0,transclude:!0,scope:{autoPlay:"=",doesContinue:"@",slideInterval:"@",showPager:"@",pagerClick:"&",disableScroll:"@",onSlideChanged:"&",activeSlide:"=?"},controller:["$scope","$element","$attrs",function(t,r,a){function c(e){e&&!s.isScrollFreeze?o.freezeAllScrolls(e):!e&&s.isScrollFreeze&&o.freezeAllScrolls(!1),s.isScrollFreeze=e}var s=this,l=t.$eval(t.doesContinue)===!0,d=u(a.autoPlay)?!!t.autoPlay:!1,f=d?t.$eval(t.slideInterval)||4e3:0,h=new ionic.views.Slider({el:r[0],auto:f,continuous:l,startSlide:t.activeSlide,slidesChanged:function(){t.currentSlide=h.currentIndex(),e(function(){})},callback:function(n){t.currentSlide=n,t.onSlideChanged({index:t.currentSlide,$index:t.currentSlide}),t.$parent.$broadcast("slideBox.slideChanged",n),t.activeSlide=n,e(function(){})},onDrag:function(){c(!0)},onDragEnd:function(){c(!1)}});h.enableSlide(t.$eval(a.disableScroll)!==!0),t.$watch("activeSlide",function(e){u(e)&&h.slide(e)}),t.$on("slideBox.nextSlide",function(){h.next()}),t.$on("slideBox.prevSlide",function(){h.prev()}),t.$on("slideBox.setSlide",function(e,t){h.slide(t)}),this.__slider=h;var p=n._registerInstance(h,a.delegateHandle,function(){return i.isActiveScope(t)});t.$on("$destroy",function(){p(),h.kill()}),this.slidesCount=function(){return h.slidesCount()},this.onPagerClick=function(e){t.pagerClick({index:e})},e(function(){h.load()})}],template:'<div class="slider"><div class="slider-slides" ng-transclude></div></div>',link:function(e,n,i){function o(){if(!r){var i=e.$new();r=h("<ion-pager></ion-pager>"),n.append(r),r=t(r)(i)}return r}u(i.showPager)||(e.showPager=!0,o().toggleClass("hide",!1)),i.$observe("showPager",function(t){void 0!==t&&(t=e.$eval(t),o().toggleClass("hide",!t))});var r}}}]).directive("ionSlide",function(){return{restrict:"E",require:"^ionSlideBox",compile:function(e){e.addClass("slider-slide")}}}).directive("ionPager",function(){return{restrict:"E",replace:!0,require:"^ionSlideBox",template:'<div class="slider-pager"><span class="slider-pager-page" ng-repeat="slide in numSlides() track by $index" ng-class="{active: $index == currentSlide}" ng-click="pagerClick($index)"><i class="icon ion-record"></i></span></div>',link:function(e,t,n,i){var o=function(e){for(var n=t[0].children,i=n.length,o=0;i>o;o++)o==e?n[o].classList.add("active"):n[o].classList.remove("active")};e.pagerClick=function(e){i.onPagerClick(e)},e.numSlides=function(){return new Array(i.slidesCount())},e.$watch("currentSlide",function(e){o(e)})}}}),c.directive("ionSpinner",function(){return{restrict:"E",controller:"$ionicSpinner",link:function(e,t,n,i){var o=i.init();t.addClass("spinner spinner-"+o)}}}),c.directive("ionTab",["$compile","$ionicConfig","$ionicBind","$ionicViewSwitcher",function(e,t,n,i){function o(e,t){return u(t)?" "+e+'="'+t+'"':""}return{restrict:"E",require:["^ionTabs","ionTab"],controller:"$ionicTab",scope:!0,compile:function(r,a){for(var c="<ion-tab-nav"+o("ng-click",a.ngClick)+o("title",a.title)+o("icon",a.icon)+o("icon-on",a.iconOn)+o("icon-off",a.iconOff)+o("badge",a.badge)+o("badge-style",a.badgeStyle)+o("hidden",a.hidden)+o("disabled",a.disabled)+o("class",a["class"])+"></ion-tab-nav>",s=document.createElement("div"),l=0;l<r[0].children.length;l++)s.appendChild(r[0].children[l].cloneNode(!0));var u=s.childElementCount;r.empty();var d,f;return u&&("ION-NAV-VIEW"===s.children[0].tagName&&(d=s.children[0].getAttribute("name"),s.children[0].classList.add("view-container"),f=!0),1===u&&(s=s.children[0]),f||s.classList.add("pane"),s.classList.add("tab-content")),function(o,r,a,l){function f(){w.tabMatchesState()&&$.select(o,!1)}function p(n){n&&u?(b||(g=o.$new(),m=h(s),i.viewEleIsActive(m,!0),$.$element.append(m),e(m)(g),b=!0),i.viewEleIsActive(m,!0)):b&&m&&(t.views.maxCache()>0?i.viewEleIsActive(m,!1):v())}function v(){g&&g.$destroy(),b&&m&&m.remove(),s.innerHTML="",b=g=m=null}var g,m,$=l[0],w=l[1],b=!1;o.$tabSelected=!1,n(o,a,{onSelect:"&",onDeselect:"&",title:"@",uiSref:"@",href:"@"}),$.add(o),o.$on("$destroy",function(){o.$tabsDestroy||$.remove(o),y.isolateScope().$destroy(),y.remove(),y=s=m=null}),r[0].removeAttribute("title"),d&&(w.navViewName=o.navViewName=d),o.$on("$stateChangeSuccess",f),f();var y=h(c);y.data("$ionTabsController",$),y.data("$ionTabController",w),$.$tabsElement.append(e(y)(o)),o.$watch("$tabSelected",p),o.$on("$ionicView.afterEnter",function(){i.viewEleIsActive(m,o.$tabSelected)}),o.$on("$ionicView.clearCache",function(){o.$tabSelected||v()})}}}}]),c.directive("ionTabNav",[function(){return{restrict:"E",replace:!0,require:["^ionTabs","^ionTab"],template:"<a ng-class=\"{'tab-item-active': isTabActive(), 'has-badge':badge, 'tab-hidden':isHidden()}\" "+' ng-disabled="disabled()" class="tab-item"><span class="badge {{badgeStyle}}" ng-if="badge">{{badge}}</span><i class="icon {{getIconOn()}}" ng-if="getIconOn() && isTabActive()"></i><i class="icon {{getIconOff()}}" ng-if="getIconOff() && !isTabActive()"></i><span class="tab-title" ng-bind-html="title"></span></a>',scope:{title:"@",icon:"@",iconOn:"@",iconOff:"@",badge:"=",hidden:"@",disabled:"&",badgeStyle:"@","class":"@"},link:function(e,t,n,i){var o=i[0],r=i[1];t[0].removeAttribute("title"),e.selectTab=function(e){e.preventDefault(),o.select(r.$scope,!0)},n.ngClick||t.on("click",function(t){e.$apply(function(){e.selectTab(t)})}),e.isHidden=function(){return"true"===n.hidden||n.hidden===!0?!0:!1},e.getIconOn=function(){return e.iconOn||e.icon},e.getIconOff=function(){return e.iconOff||e.icon},e.isTabActive=function(){return o.selectedTab()===r.$scope}}}}]),c.directive("ionTabs",["$ionicTabsDelegate","$ionicConfig",function(e,t){return{restrict:"E",scope:!0,controller:"$ionicTabs",compile:function(n){function i(t,n,i,o){function a(e,t){e.stopPropagation();var n=o.previousSelectedTab();n&&n.$broadcast(e.name.replace("NavView","Tabs"),t)}var c=e._registerInstance(o,i.delegateHandle,o.hasActiveScope);o.$scope=t,o.$element=n,o.$tabsElement=h(n[0].querySelector(".tabs")),t.$watch(function(){return n[0].className},function(e){var n=-1!==e.indexOf("tabs-top"),i=-1!==e.indexOf("tabs-item-hide");t.$hasTabs=!n&&!i,t.$hasTabsTop=n&&!i,t.$emit("$ionicTabs.top",t.$hasTabsTop)}),t.$on("$ionicNavView.beforeLeave",a),t.$on("$ionicNavView.afterLeave",a),t.$on("$ionicNavView.leave",a),t.$on("$destroy",function(){t.$tabsDestroy=!0,c(),o.$tabsElement=o.$element=o.$scope=r=null,delete t.$hasTabs,delete t.$hasTabsTop})}function o(e,t,n,i){i.selectedTab()||i.select(0)}var r=h('<div class="tab-nav tabs">');return r.append(n.contents()),n.append(r).addClass("tabs-"+t.tabs.position()+" tabs-"+t.tabs.style()),{pre:i,post:o}}}}]),c.directive("ionToggle",["$timeout","$ionicConfig",function(e,t){return{restrict:"E",replace:!0,require:"?ngModel",transclude:!0,template:'<div class="item item-toggle"><div ng-transclude></div><label class="toggle"><input type="checkbox"><div class="track"><div class="handle"></div></div></label></div>',compile:function(e,n){var i=e.find("input");return l({name:n.name,"ng-value":n.ngValue,"ng-model":n.ngModel,"ng-checked":n.ngChecked,"ng-disabled":n.ngDisabled,"ng-true-value":n.ngTrueValue,"ng-false-value":n.ngFalseValue,"ng-change":n.ngChange,"ng-required":n.ngRequired,required:n.required},function(e,t){u(e)&&i.attr(t,e)}),n.toggleClass&&e[0].getElementsByTagName("label")[0].classList.add(n.toggleClass),e.addClass("toggle-"+t.form.toggle()),function(e,t){var n=t[0].getElementsByTagName("label")[0],i=n.children[0],o=n.children[1],r=o.children[0],a=h(i).controller("ngModel");e.toggle=new ionic.views.Toggle({el:n,track:o,checkbox:i,handle:r,onChange:function(){a&&(a.$setViewValue(i.checked),e.$apply())}}),e.$on("$destroy",function(){e.toggle.destroy()})}}}}]),c.directive("ionView",function(){return{restrict:"EA",priority:1e3,controller:"$ionicView",compile:function(e){return e.addClass("pane"),e[0].removeAttribute("title"),function(e,t,n,i){i.init()}}}})}(); | ) |
partition_types.rs | //! Parition type constants
use log::trace;
use std::str::FromStr;
/// The type
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Type {
/// Type-GUID for a GPT partition.
pub guid: &'static str,
/// well-known OS label for this type-GUID.
pub os: OperatingSystem,
}
/// Operating System
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum | {
/// No OS
None,
/// ANDROID OS
Android,
/// Atari
Atari,
/// Ceph
Ceph,
/// ChromeOS
Chrome,
/// CoreOs
CoreOs,
/// Custom
Custom(String),
/// FreeBsd
FreeBsd,
/// FreeDesktop
FreeDesktop,
/// Haiku
Haiku,
/// Hp Unix
HpUnix,
/// Linux
Linux,
/// MidnightBsd
MidnightBsd,
/// MacOs
MacOs,
/// NetBsd
NetBsd,
/// Onie
Onie,
/// OpenBSD
OpenBsd,
/// Plan9
Plan9,
/// PowerPC
PowerPc,
/// Solaris
Solaris,
/// VmWare
VmWare,
/// Windows
Windows,
/// QNX
QNX,
}
impl FromStr for OperatingSystem {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"unused" => Ok(OperatingSystem::None),
"android" => Ok(OperatingSystem::Android),
"atari" => Ok(OperatingSystem::Atari),
"Ceph" => Ok(OperatingSystem::Ceph),
"Chrome" => Ok(OperatingSystem::Chrome),
"FreeBsd" => Ok(OperatingSystem::FreeBsd),
"FreeDesktop" => Ok(OperatingSystem::FreeDesktop),
"Haiku" => Ok(OperatingSystem::Haiku),
"HP-UX" => Ok(OperatingSystem::HpUnix),
"Linux" => Ok(OperatingSystem::Linux),
"MacOS" => Ok(OperatingSystem::MacOs),
"MidnightBsd" => Ok(OperatingSystem::MidnightBsd),
"Onie" => Ok(OperatingSystem::Onie),
"PowerPc" => Ok(OperatingSystem::PowerPc),
"Solaris Illumos" => Ok(OperatingSystem::Solaris),
_ => Err(format!("Unknown operating system: {}", s)),
}
}
}
#[test]
fn test_partition_fromstr_guid() {
let p = "0FC63DAF-8483-4772-8E79-3D69D8477DE4";
let t = Type::from_str(p).unwrap();
println!("result: {:?}", t);
assert_eq!(t, LINUX_FS);
}
#[test]
fn test_partition_from_name() {
// mix case as part of the test
let p = "Linux_FS";
let t = Type::from_name(p).unwrap();
println!("result: {:?}", t);
assert_eq!(t, LINUX_FS);
}
impl Type {
/// Lookup a partition type by uuid
pub fn from_uuid(u: &uuid::Uuid) -> Result<Self, String> {
let uuid_str = u.to_hyphenated().to_string().to_uppercase();
trace!("looking up partition type guid {}", uuid_str);
Type::from_str(&uuid_str)
}
/// Lookup a partition type by name
pub fn from_name(name: &str) -> Result<Self, String> {
let name_str = name.to_uppercase();
trace!("looking up partition type by name {}", name_str);
Type::from_str(&name_str)
}
}
impl Default for Type {
fn default() -> Type {
Type { guid: "00000000-0000-0000-0000-000000000000", os: OperatingSystem::None }
}
}
partition_types! {
/// unused
(UNUSED, "00000000-0000-0000-0000-000000000000", OperatingSystem::None),
/// MBR Partition Scheme
(MBR, "024DEE41-33E7-11D3-9D69-0008C781F39F", OperatingSystem::None),
/// EFI System Partition
(EFI, "C12A7328-F81F-11D2-BA4B-00A0C93EC93B", OperatingSystem::None),
/// BIOS Boot Partition
(BIOS, "21686148-6449-6E6F-744E-656564454649", OperatingSystem::None),
/// Intel Fast Flash (iFFS) Partition
(FLASH, "D3BFE2DE-3DAF-11DF-BA40-E3A556D89593",OperatingSystem::None),
/// Sony Boot Partition
(SONY_BOOT, "F4019732-066E-4E12-8273-346C5641494F", OperatingSystem::None),
/// Lenovo Boot Partition
(LENOVO_BOOT, "BFBFAFE7-A34F-448A-9A5B-6213EB736C22", OperatingSystem::None),
/// Microsoft Reserved Partition
(MICROSOFT_RESERVED, "E3C9E316-0B5C-4DB8-817D-F92DF00215AE", OperatingSystem::Windows),
/// Basic Data Partition
(BASIC, "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7", OperatingSystem::Windows),
/// Logical Disk Manager Metadata Partition
(WINDOWS_METADATA, "5808C8AA-7E8F-42E0-85D2-E1E90434CFB3", OperatingSystem::Windows),
/// Logical Disk Manager Data Partition
(WINDOWS_DATA, "AF9B60A0-1431-4F62-BC68-3311714A69AD", OperatingSystem::Windows),
/// Windows Recovery Environment
(WINDOWS_RECOVERY, "DE94BBA4-06D1-4D40-A16A-BFD50179D6AC", OperatingSystem::Windows),
/// IBM General Parallel File System Partition
(WINDOWS_PARALLEL, "37AFFC90-EF7D-4E96-91C3-2D7AE055B174", OperatingSystem::Windows),
/// Storage Spaces Partition
(WINDOWS_STORAGESPACES, "E75CAF8F-F680-4CEE-AFA3-B001E56EFC2D", OperatingSystem::Windows),
/// HP Unix Data Partition
(HPUNIX_DATA, "75894C1E-3AEB-11D3-B7C1-7B03A0000000", OperatingSystem::HpUnix),
/// HP Unix Service Partition
(HPUNIX_SERVICE, "E2A1E728-32E3-11D6-A682-7B03A0000000", OperatingSystem::HpUnix),
/// Linux Filesystem Data
(LINUX_FS, "0FC63DAF-8483-4772-8E79-3D69D8477DE4", OperatingSystem::Linux),
/// Linux RAID Partition
(LINUX_RAID, "A19D880F-05FC-4D3B-A006-743F0F84911E", OperatingSystem::Linux),
/// Linux Root Partition (x86)
(LINUX_ROOT_X86, "44479540-F297-41B2-9AF7-D131D5F0458A", OperatingSystem::Linux),
/// Linux Root Partition (x86-64)
(LINUX_ROOT_X64, "4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709", OperatingSystem::Linux),
/// Linux Root Partition (32-bit ARM)
(LINUX_ROOT_ARM_32, "69DAD710-2CE4-4E3C-B16C-21A1D49ABED3", OperatingSystem::Linux),
/// Linux Root Partition (64-bit ARM/AArch64)
(LINUX_ROOT_ARM_64, "B921B045-1DF0-41C3-AF44-4C6F280D3FAE", OperatingSystem::Linux),
/// Linux Swap Partition
(LINUX_SWAP, "0657FD6D-A4AB-43C4-84E5-0933C84B4F4F", OperatingSystem::Linux),
/// Linux Logical Volume Manager Partition
(LINUX_LVM, "E6D6D379-F507-44C2-A23C-238F2A3DF928", OperatingSystem::Linux),
/// Linux /home Partition
(LINUX_HOME, "933AC7E1-2EB4-4F13-B844-0E14E2AEF915", OperatingSystem::Linux),
/// Linux /srv (Server Data) Partition
(LINUX_SRV, "3B8F8425-20E0-4F3B-907F-1A25A76F98E8", OperatingSystem::Linux),
/// Linux Plain dm-crypt Partition
(LINUX_DMCRYPT, "7FFEC5C9-2D00-49B7-8941-3EA10A5586B7", OperatingSystem::Linux),
/// Linux LUKS Partition
(LINUX_LUKS, "CA7D7CCB-63ED-4C53-861C-1742536059CC", OperatingSystem::Linux),
/// Linux Reserved
(LINUX_RESERVED, "8DA63339-0007-60C0-C436-083AC8230908", OperatingSystem::Linux),
/// FreeBSD Data Partition
(FREEBSD_DATA, "516E7CB4-6ECF-11D6-8FF8-00022D09712B", OperatingSystem::FreeBsd),
/// FreeBSD Boot Partition
(FREEBSD_BOOT, "83BD6B9D-7F41-11DC-BE0B-001560B84F0F", OperatingSystem::FreeBsd),
/// FreeBSD Swap Partition
(FREEBSD_SWAP, "516E7CB5-6ECF-11D6-8FF8-00022D09712B", OperatingSystem::FreeBsd),
/// FreeBSD Unix File System (UFS) Partition
(FREEBSD_UFS, "516E7CB6-6ECF-11D6-8FF8-00022D09712B", OperatingSystem::FreeBsd),
/// FreeBSD Vinium Volume Manager Partition
(FREEBSD_VINIUM, "516E7CB8-6ECF-11D6-8FF8-00022D09712B", OperatingSystem::FreeBsd),
/// FreeBSD ZFS Partition
(FREEBSD_ZFS, "516E7CBA-6ECF-11D6-8FF8-00022D09712B", OperatingSystem::FreeBsd),
/// Apple Hierarchical File System Plus (HFS+) Partition
(MACOS_HFSPLUS, "48465300-0000-11AA-AA11-00306543ECAC", OperatingSystem::MacOs),
/// Apple UFS
(MACOS_UFS, "55465300-0000-11AA-AA11-00306543ECAC", OperatingSystem::MacOs),
/// Apple ZFS
(MACOS_ZFS, "6A898CC3-1DD2-11B2-99A6-080020736631", OperatingSystem::MacOs),
/// Apple RAID Partition
(MACOS_RAID, "52414944-0000-11AA-AA11-00306543ECAC", OperatingSystem::MacOs),
/// APple RAID Partition, offline
(MACOS_RAID_OFFLINE, "52414944-5F4F-11AA-AA11-00306543ECAC", OperatingSystem::MacOs),
/// Apple Boot Partition (Recovery HD)
(MACOS_RECOVERY, "426F6F74-0000-11AA-AA11-00306543ECAC", OperatingSystem::MacOs),
/// Apple Label
(MACOS_LABEL, "4C616265-6C00-11AA-AA11-00306543ECAC", OperatingSystem::MacOs),
/// Apple TV Recovery Partition
(MACOS_TV_RECOVERY, "5265636F-7665-11AA-AA11-00306543ECAC", OperatingSystem::MacOs),
/// Apple Core Storage Partition
(MACOS_CORE, "53746F72-6167-11AA-AA11-00306543ECAC", OperatingSystem::MacOs),
/// Apple SoftRAID_Status
(MACOS_SOFTRAID_STATUS, "B6FA30DA-92D2-4A9A-96F1-871EC6486200", OperatingSystem::MacOs),
/// Apple SoftRAID_Scratch
(MACOS_SOFTRAID_SCRATCH, "2E313465-19B9-463F-8126-8A7993773801", OperatingSystem::MacOs),
/// Apple SoftRAID_Volume
(MACOS_SOFTRAID_VOLUME, "FA709C7E-65B1-4593-BFD5-E71D61DE9B02", OperatingSystem::MacOs),
/// Apple SOftRAID_Cache
(MACOS_SOFTRAID_CACHE, "BBBA6DF5-F46F-4A89-8F59-8765B2727503", OperatingSystem::MacOs),
/// Apple APFS
(MACOS_APFS, "7C3457EF-0000-11AA-AA11-00306543ECAC", OperatingSystem::MacOs),
/// Solaris Boot Partition
(SOLARIS_BOOT, "6A82CB45-1DD2-11B2-99A6-080020736631", OperatingSystem::Solaris),
/// Solaris Root Partition
(SOLARIS_ROOT, "6A85CF4D-1DD2-11B2-99A6-080020736631", OperatingSystem::Solaris),
/// Solaris Swap Partition
(SOLARIS_SWAP, "6A87C46F-1DD2-11B2-99A6-080020736631", OperatingSystem::Solaris),
/// Solaris Backup Partition
(SOLARIS_BACKUP, "6A8B642B-1DD2-11B2-99A6-080020736631", OperatingSystem::Solaris),
/// Solaris /var Partition
(SOLARIS_VAR, "6A8EF2E9-1DD2-11B2-99A6-080020736631", OperatingSystem::Solaris),
/// Solaris /home Partition
(SOLARIS_HOME, "6A90BA39-1DD2-11B2-99A6-080020736631", OperatingSystem::Solaris),
/// Solaris Alternate Sector
(SOLARIS_ALT, "6A9283A5-1DD2-11B2-99A6-080020736631", OperatingSystem::Solaris),
/// Solaris Reserved
(SOLARIS_RESERVED1, "6A945A3B-1DD2-11B2-99A6-080020736631", OperatingSystem::Solaris),
/// Solaris Reserved
(SOLARIS_RESERVED2, "6A9630D1-1DD2-11B2-99A6-080020736631", OperatingSystem::Solaris),
/// Solaris Reserved
(SOLARIS_RESERVED3, "6A980767-1DD2-11B2-99A6-080020736631", OperatingSystem::Solaris),
/// Solaris Reserved
(SOLARIS_RESERVED4, "6A96237F-1DD2-11B2-99A6-080020736631", OperatingSystem::Solaris),
/// Solaris Reserved
(SOLARIS_RESERVED5, "6A8D2AC7-1DD2-11B2-99A6-080020736631", OperatingSystem::Solaris),
/// NetBSD Swap Partition
(NETBSD_SWAP, "49F48D32-B10E-11DC-B99B-0019D1879648", OperatingSystem::NetBsd),
/// NetBSD FFS Partition
(NETBSD_FFS, "49F48D5A-B10E-11DC-B99B-0019D1879648", OperatingSystem::NetBsd),
/// NetBSD LFS Partition
(NETBSD_LFS, "49F48D82-B10E-11DC-B99B-0019D1879648", OperatingSystem::NetBsd),
/// NetBSD RAID Partition
(NETBSD_RAID, "49F48DAA-B10E-11DC-B99B-0019D1879648", OperatingSystem::NetBsd),
/// NetBSD Concatenated Partition
(NETBSD_CONCAT, "2DB519C4-B10F-11DC-B99B-0019D1879648", OperatingSystem::NetBsd),
/// NetBSD Encrypted Partition
(NETBSD_ENCRYPTED, "2DB519EC-B10F-11DC-B99B-0019D1879648", OperatingSystem::NetBsd),
/// ChromeOS Kernel
(CHROME_KERNEL, "FE3A2A5D-4F32-41A7-B725-ACCC3285A309", OperatingSystem::Chrome),
/// ChromeOS rootfs
(CHROME_ROOTFS, "3CB8E202-3B7E-47DD-8A3C-7FF2A13CFCEC",OperatingSystem::Chrome),
/// ChromeOS Future Use
(CHROME_FUTURE, "2E0A753D-9E48-43B0-8337-B15192CB1B5E",OperatingSystem::Chrome),
/// CoreOS /usr partition (coreos-usr)
(COREOS_USR, "5DFBF5F4-2848-4BAC-AA5E-0D9A20B745A6", OperatingSystem::CoreOs),
/// CoreOS Resizable rootfs (coreos-resize)
(COREOS_ROOTFS_RESIZE, "3884DD41-8582-4404-B9A8-E9B84F2DF50E", OperatingSystem::CoreOs),
/// CoreOS OEM customizations (coreos-reserved)
(COREOS_OEM, "C95DC21A-DF0E-4340-8D7B-26CBFA9A03E0", OperatingSystem::CoreOs),
/// CoreOS Root filesystem on RAID (coreos-root-raid)
(COREOS_ROOT_RAID, "BE9067B9-EA49-4F15-B4F6-F36F8C9E1818", OperatingSystem::CoreOs),
/// Haiku BFS
(HAIKU_BFS, "42465331-3BA3-10F1-802A-4861696B7521", OperatingSystem::Haiku),
/// MidnightBSD Boot Partition
(MIDNIGHT_BOOT, "85D5E45E-237C-11E1-B4B3-E89A8F7FC3A7", OperatingSystem::MidnightBsd),
/// MidnightBSD Data Partition
(MIDNIGHT_DATA, "85D5E45A-237C-11E1-B4B3-E89A8F7FC3A7", OperatingSystem::MidnightBsd),
/// MidnightBSD Swap Partition
(MIDNIGHT_SWAP, "85D5E45B-237C-11E1-B4B3-E89A8F7FC3A7", OperatingSystem::MidnightBsd),
/// MidnightBSD Unix File System (UFS) Partition
(MIDNIGHT_UFS, "0394EF8B-237E-11E1-B4B3-E89A8F7FC3A7", OperatingSystem::MidnightBsd),
/// MidnightBSD Vinium Volume Manager Partition
(MIDNIGHT_VINIUM, "85D5E45C-237C-11E1-B4B3-E89A8F7FC3A7", OperatingSystem::MidnightBsd),
/// MidnightBSD ZFS Partition
(MIDNIGHT_ZFS, "85D5E45D-237C-11E1-B4B3-E89A8F7FC3A7", OperatingSystem::MidnightBsd),
/// Ceph Journal
(CEPH_JOURNAL, "45B0969E-9B03-4F30-B4C6-B4B80CEFF106", OperatingSystem::Ceph),
/// Ceph dm-crypt Encryted Journal
(CEPH_CRYPT_JOURNAL, "45B0969E-9B03-4F30-B4C6-5EC00CEFF106", OperatingSystem::Ceph),
/// Ceph OSD
(CEPH_OSD, "4FBD7E29-9D25-41B8-AFD0-062C0CEFF05D", OperatingSystem::Ceph),
/// Ceph dm-crypt OSD
(CEPH_CRYPT, "4FBD7E29-9D25-41B8-AFD0-5EC00CEFF05D", OperatingSystem::Ceph),
/// Ceph Disk In Creation
(CEPH_DISK_CREATION, "89C57F98-2FE5-4DC0-89C1-F3AD0CEFF2BE", OperatingSystem::Ceph),
/// Ceph dm-crypt Disk In Creation
(CEPH_CRYPT_CREATION, "89C57F98-2FE5-4DC0-89C1-5EC00CEFF2BE", OperatingSystem::Ceph),
/// OpenBSD Data Partition
(OPENBSD_DATA, "824CC7A0-36A8-11E3-890A-952519AD3F61", OperatingSystem::OpenBsd),
/// QNX Power-safe (QNX6) File System
(QNX_FS, "CEF5A9AD-73BC-4601-89F3-CDEEEEE321A1", OperatingSystem::QNX),
/// Plan 9 Partition
(PLAN9_PART, "C91818F9-8025-47AF-89D2-F030D7000C2C", OperatingSystem::Plan9),
/// VMWare vmkcore (coredump partition)
(VMWARE_COREDUMP, "9D275380-40AD-11DB-BF97-000C2911D1B8", OperatingSystem::VmWare),
/// VMWare VMFS Filesystem Partition
(VMWARE_VMFS, "AA31E02A-400F-11DB-9590-000C2911D1B8", OperatingSystem::VmWare),
/// VMware Reserved
(VMWARE_RESERVED, "9198EFFC-31C0-11DB-8F78-000C2911D1B8", OperatingSystem::VmWare),
/// ANDROID Bootloader
(ANDROID_BOOTLOADER, "2568845D-2332-4675-BC39-8FA5A4748D15", OperatingSystem::Android),
/// ANDROID Bootloader2
(ANDROID_BOOTLOADER2, "114EAFFE-1552-4022-B26E-9B053604CF84", OperatingSystem::Android),
/// ANDROID Boot
(ANDROID_BOOT, "49A4D17F-93A3-45C1-A0DE-F50B2EBE2599", OperatingSystem::Android),
/// ANDROID Recovery
(ANDROID_RECOVERY, "4177C722-9E92-4AAB-8644-43502BFD5506", OperatingSystem::Android),
/// ANDROID Misc
(ANDROID_MISC, "EF32A33B-A409-486C-9141-9FFB711F6266", OperatingSystem::Android),
/// ANDROID Metadata
(ANDROID_META, "20AC26BE-20B7-11E3-84C5-6CFDB94711E9", OperatingSystem::Android),
/// ANDROID System
(ANDROID_SYSTEM, "38F428E6-D326-425D-9140-6E0EA133647C", OperatingSystem::Android),
/// ANDROID Cache
(ANDROID_CACHE, "A893EF21-E428-470A-9E55-0668FD91A2D9", OperatingSystem::Android),
/// ANDROID Data
(ANDROID_DATA, "DC76DDA9-5AC1-491C-AF42-A82591580C0D", OperatingSystem::Android),
/// ANDROID Persistent
(ANDROID_PERSISTENT, "EBC597D0-2053-4B15-8B64-E0AAC75F4DB1", OperatingSystem::Android),
/// ANDROID Factory
(ANDROID_FACTORY, "8F68CC74-C5E5-48DA-BE91-A0C8C15E9C80", OperatingSystem::Android),
/// ANDROID Fastboot/Tertiary
(ANDROID_FASTBOOT, "767941D0-2085-11E3-AD3B-6CFDB94711E9", OperatingSystem::Android),
/// ANDROID OEM
(ANDROID_OEM, "AC6D7924-EB71-4DF8-B48D-E267B27148FF", OperatingSystem::Android),
/// ONIE Boot
(ONIE_BOOT, "7412F7D5-A156-4B13-81DC-867174929325", OperatingSystem::Onie),
/// ONIE Config
(ONIE_CONFIG, "D4E6E2CD-4469-46F3-B5CB-1BFF57AFC149", OperatingSystem::Onie),
/// PowerPC PReP Boot
(PPC_BOOT, "9E1A2D38-C612-4316-AA26-8B49521E5A8B", OperatingSystem::PowerPc),
/// FreeDesktop Shared Boot Loader Configuration
(FREEDESK_BOOT, "BC13C2FF-59E6-4262-A352-B275FD6F7172", OperatingSystem::FreeDesktop),
/// Atari Basic Data Partition (GEM, BGM, F32)
(ATARI_DATA, "734E5AFE-F61A-11E6-BC64-92361F002671", OperatingSystem::Atari),
/// ANDROID ssd partition
(ANDROID_SSD_MISC, "2C86E742-745E-4FDD-BFD8-B6A7AC638772", OperatingSystem::Android),
/// ANDROID PERSIST partition
(ANDROID_PERSIST_MISC, "6C95E238-E343-4BA8-B489-8681ED22AD0B", OperatingSystem::Android),
/// ANDROID MISC partition
(ANDROID_MISC_MISC, "82ACC91F-357C-4A68-9C8F-689E1B1A23A1", OperatingSystem::Android),
/// ANDROID PARAM partition
(ANDROID_PARAM_MISC, "6D679BAB-23C7-466E-90AC-A39897C15640", OperatingSystem::Android),
/// ANDROID KEYSTORE partition
(ANDROID_KEYSTORE_MISC, "DE7D4029-0F5B-41C8-AE7E-F6C023A02B33", OperatingSystem::Android),
/// ANDROID FRP partition
(ANDROID_FRP_MISC, "91B72D4D-71E0-4CBF-9B8E-236381CFF17A", OperatingSystem::Android),
/// ANDROID OP2 partition
(ANDROID_OP2_MISC, "5594C694-C871-4B5F-90B1-690A6F68E0F7", OperatingSystem::Android),
/// ANDROID OEM_DYCNVBK partition
(ANDROID_OEM_DYCNVBK_MISC, "EBBEADAE-22C9-E33B-8F5D-0E81686A68CC", OperatingSystem::Android),
/// ANDROID OEM_STANVBK partition
(ANDROID_OEM_STANVBK_MISC, "0A288B1E-22C9-E33B-8F5D-0E81686A68CC", OperatingSystem::Android),
/// ANDROID RESERVE1 partition
(ANDROID_RESERVE1_MISC, "004A6838-062A-44DF-8152-4F340C052255", OperatingSystem::Android),
/// ANDROID CONFIG partition
(ANDROID_CONFIG, "04377754-DE64-4ADB-852F-F01E702DF13B", OperatingSystem::Android),
/// ANDROID SYSTEM_A partition
(ANDROID_SYSTEM_A_MISC, "97D7B011-54DA-4835-B3C4-917AD6E73D74", OperatingSystem::Android),
/// ANDROID SYSTEM_B partition
(ANDROID_SYSTEM_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID ODM_B partition
(ANDROID_ODM_B, "E4B6514E-2577-495D-A484-1A0C460C6101", OperatingSystem::Android),
/// ANDROID USERDATA partition
(ANDROID_USERDATA_MISC, "1B81E7E6-F50D-419B-A739-2AEEF8DA3335", OperatingSystem::Android),
/// ANDROID XBL_A partition
(ANDROID_XBL_A_MISC, "DEA0BA2C-CBDD-4805-B4F9-F428251C3E98", OperatingSystem::Android),
/// ANDROID XBL_CONFIG_A partition
(ANDROID_XBL_CONFIG_A_MISC, "5A325AE4-4276-B66D-0ADD-3494DF27706A", OperatingSystem::Android),
/// ANDROID XBL_CONFIG_B partition
(ANDROID_XBL_CONFIG_B_MISC, "5A325AE4-4276-B66D-0ADD-3494DF27706A", OperatingSystem::Android),
/// ANDROID ALIGN_TO_128K_1 partition
(ANDROID_ALIGN_TO_128K_1_MISC, "FDE1604B-D68B-4BD4-973D-962AE7A1ED88", OperatingSystem::Android),
/// ANDROID CDT partition
(ANDROID_CDT_MISC, "A19F205F-CCD8-4B6D-8F1E-2D9BC24CFFB1", OperatingSystem::Android),
/// ANDROID DDR partition
(ANDROID_DDR_MISC, "20A0C19C-286A-42FA-9CE7-F64C3226A794", OperatingSystem::Android),
/// ANDROID AOP_A partition
(ANDROID_AOP_A_MISC, "D69E90A5-4CAB-0071-F6DF-AB977F141A7F", OperatingSystem::Android),
/// ANDROID TZ_A partition
(ANDROID_TZ_A_MISC, "A053AA7F-40B8-4B1C-BA08-2F68AC71A4F4", OperatingSystem::Android),
/// ANDROID HYP_A partition
(ANDROID_HYP_A_MISC, "E1A6A689-0C8D-4CC6-B4E8-55A4320FBD8A", OperatingSystem::Android),
/// ANDROID MODEM_A partition
(ANDROID_MODEM_A_MISC, "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7", OperatingSystem::Android),
/// ANDROID BLUETOOTH_A partition
(ANDROID_BLUETOOTH_A_MISC, "6CB747F1-C2EF-4092-ADD0-CA39F79C7AF4", OperatingSystem::Android),
/// ANDROID MDTPSECAPP_A partition
(ANDROID_MDTPSECAPP_A_MISC, "EA02D680-8712-4552-A3BE-E6087829C1E6", OperatingSystem::Android),
/// ANDROID MDTP_A partition
(ANDROID_MDTP_A_MISC, "3878408A-E263-4B67-B878-6340B35B11E3", OperatingSystem::Android),
/// ANDROID ABL_A partition
(ANDROID_ABL_A_MISC, "BD6928A1-4CE0-A038-4F3A-1495E3EDDFFB", OperatingSystem::Android),
/// ANDROID DSP_A partition
(ANDROID_DSP_A_MISC, "7EFE5010-2A1A-4A1A-B8BC-990257813512", OperatingSystem::Android),
/// ANDROID KEYMASTER_A partition
(ANDROID_KEYMASTER_A_MISC, "A11D2A7C-D82A-4C2F-8A01-1805240E6626", OperatingSystem::Android),
/// ANDROID BOOT_A partition
(ANDROID_BOOT_A_MISC, "20117F86-E985-4357-B9EE-374BC1D8487D", OperatingSystem::Android),
/// ANDROID CMNLIB_A partition
(ANDROID_CMNLIB_A_MISC, "73471795-AB54-43F9-A847-4F72EA5CBEF5", OperatingSystem::Android),
/// ANDROID CMNLIB64_A partition
(ANDROID_CMNLIB64_A_MISC, "8EA64893-1267-4A1B-947C-7C362ACAAD2C", OperatingSystem::Android),
/// ANDROID DEVCFG_A partition
(ANDROID_DEVCFG_A_MISC, "F65D4B16-343D-4E25-AAFC-BE99B6556A6D", OperatingSystem::Android),
/// ANDROID QUPFW_A partition
(ANDROID_QUPFW_A_MISC, "21D1219F-2ED1-4AB4-930A-41A16AE75F7F", OperatingSystem::Android),
/// ANDROID VBMETA_A partition
(ANDROID_VBMETA_A, "4B7A15D6-322C-42AC-8110-88B7DA0C5D77", OperatingSystem::Android),
/// ANDROID DTBO_A partition
(ANDROID_DTBO_A_MISC, "24D0D418-D31D-4D8D-AC2C-4D4305188450", OperatingSystem::Android),
/// ANDROID STORSEC_A partition
(ANDROID_STORSEC_A_MISC, "02DB45FE-AD1B-4CB6-AECC-0042C637DEFA", OperatingSystem::Android),
/// ANDROID LOGO_A partition
(ANDROID_LOGO_A_MISC, "9AD51E4D-3088-43EA-8EC7-991AD619F88E", OperatingSystem::Android),
/// ANDROID FW_4J1ED_A partition
(ANDROID_FW_4J1ED_A_MISC, "9846625A-FE09-425B-A08F-2BF5F1F8D838", OperatingSystem::Android),
/// ANDROID FW_4U1EA_A partition
(ANDROID_FW_4U1EA_A_MISC, "9846625A-FE09-425B-A08F-2BF5F1F8D839", OperatingSystem::Android),
/// ANDROID FW_UFS3_A partition
(ANDROID_FW_UFS3_A_MISC, "9846625A-FE09-425B-A08F-2BF5F1F8D83A", OperatingSystem::Android),
/// ANDROID FW_UFS4_A partition
(ANDROID_FW_UFS4_A_MISC, "9846625A-FE09-425B-A08F-2BF5F1F8D83B", OperatingSystem::Android),
/// ANDROID FW_UFS5_A partition
(ANDROID_FW_UFS5_A_MISC, "9846625A-FE09-425B-A08F-2BF5F1F8D83C", OperatingSystem::Android),
/// ANDROID FW_UFS6_A partition
(ANDROID_FW_UFS6_A_MISC, "9846625A-FE09-425B-A08F-2BF5F1F8D83D", OperatingSystem::Android),
/// ANDROID FW_UFS7_A partition
(ANDROID_FW_UFS7_A_MISC, "9846625A-FE09-425B-A08F-2BF5F1F8D83E", OperatingSystem::Android),
/// ANDROID FW_UFS8_A partition
(ANDROID_FW_UFS8_A_MISC, "9846625A-FE09-425B-A08F-2BF5F1F8D83F", OperatingSystem::Android),
/// ANDROID TZ_B partition
(ANDROID_TZ_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID MODEM_B partition
(ANDROID_MODEM_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID MDTPSECAPP_B partition
(ANDROID_MDTPSECAPP_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID ABL_B partition
(ANDROID_ABL_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID KEYMASTER_B partition
(ANDROID_KEYMASTER_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID CMNLIB_B partition
(ANDROID_CMNLIB_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID DEVCFG_B partition
(ANDROID_DEVCFG_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID VENDOR_B partition
(ANDROID_VENDOR_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID DTBO_B partition
(ANDROID_DTBO_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID LOGO_B partition
(ANDROID_LOGO_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID FW_4U1EA_B partition
(ANDROID_FW_4U1EA_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID FW_UFS4_B partition
(ANDROID_FW_UFS4_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID FW_UFS6_B partition
(ANDROID_FW_UFS6_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID FW_UFS8_B partition
(ANDROID_FW_UFS8_B_MISC, "77036CD4-03D5-42BB-8ED1-37E5A88BAA34", OperatingSystem::Android),
/// ANDROID MINIDUMP partition
(ANDROID_MINIDUMP_MISC, "961743CA-BD08-48D5-BD8C-25EFEB7C7AC2", OperatingSystem::Android),
/// ANDROID BOOT_AGING partition
(ANDROID_BOOT_AGING_MISC, "CA98971A-A88F-4342-BC74-58D1B639B636", OperatingSystem::Android),
/// ANDROID OP1 partition
(ANDROID_OP1_MISC, "D1E30BCB-7D78-4FB6-B598-55FC4892644C", OperatingSystem::Android),
/// ANDROID SEC partition
(ANDROID_SEC_MISC, "303E6AC3-AF15-4C54-9E9B-D9A8FBECF401", OperatingSystem::Android),
/// ANDROID DEVINFO partition
(ANDROID_DEVINFO_MISC, "65ADDCF4-0C5C-4D9A-AC2D-D90B5CBFCD03", OperatingSystem::Android),
/// ANDROID DIP partition
(ANDROID_DIP_MISC, "4114B077-005D-4E12-AC8C-B493BDA684FB", OperatingSystem::Android),
/// ANDROID APDP partition
(ANDROID_APDP_MISC, "E6E98DA2-E22A-4D12-AB33-169E7DEAA507", OperatingSystem::Android),
/// ANDROID MSADP partition
(ANDROID_MSADP_MISC, "ED9E8101-05FA-46B7-82AA-8D58770D200B", OperatingSystem::Android),
/// ANDROID SPUNVM partition
(ANDROID_SPUNVM_MISC, "E42E2B4C-33B0-429B-B1EF-D341C547022C", OperatingSystem::Android),
/// ANDROID SPLASH partition
(ANDROID_SPLASH_MISC, "AD99F201-DC71-4E30-9630-E19EEF553D1B", OperatingSystem::Android),
/// ANDROID LIMITS partition
(ANDROID_LIMITS_MISC, "10A0C19C-516A-5444-5CE3-664C3226A794", OperatingSystem::Android),
/// ANDROID TOOLSFV partition
(ANDROID_TOOLSFV_MISC, "97745ABA-135A-44C3-9ADC-05616173C24C", OperatingSystem::Android),
/// ANDROID LOGFS partition
(ANDROID_LOGFS_MISC, "BC0330EB-3410-4951-A617-03898DBE3372", OperatingSystem::Android),
/// ANDROID STI partition
(ANDROID_STI_MISC, "AA9A5C4C-4F1F-7D3A-014A-22BD33BF7191", OperatingSystem::Android),
/// ANDROID LOGDUMP partition
(ANDROID_LOGDUMP_MISC, "5AF80809-AABB-4943-9168-CDFC38742598", OperatingSystem::Android),
/// ANDROID IMAGEFV partition
(ANDROID_IMAGEFV_MISC, "17911177-C9E6-4372-933C-804B678E666F", OperatingSystem::Android),
/// ANDROID ALIGN_TO_128K_2 partition
(ANDROID_ALIGN_TO_128K_2_MISC, "6891A3B7-0CCC-4705-BB53-2673CAC193BD", OperatingSystem::Android),
/// ANDROID MODEMST1 partition
(ANDROID_MODEMST1_MISC, "EBBEADAF-22C9-E33B-8F5D-0E81686A68CB", OperatingSystem::Android),
/// ANDROID MODEMST2 partition
(ANDROID_MODEMST2_MISC, "0A288B1F-22C9-E33B-8F5D-0E81686A68CB", OperatingSystem::Android),
/// ANDROID FSG partition
(ANDROID_FSG_MISC, "638FF8E2-22C9-E33B-8F5D-0E81686A68CB", OperatingSystem::Android),
/// ANDROID FSC partition
(ANDROID_FSC_MISC, "57B90A16-22C9-E33B-8F5D-0E81686A68CB", OperatingSystem::Android),
}
| OperatingSystem |
valid-sudoku.py | class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
BZip = list(zip(*board))
def Checkline(li):
temp = [i for i in li if i!="."]
return len(set(temp))==len(temp)
def check_row(board):
for i in board:
if not Checkline(i):return False
return True
def check_col(board):
for i in BZip:
if not Checkline(i):return False
return True
def square(board):
for i in range(0,9,3):
for j in range(0,9,3):
sqr = [board[x][y] for x in range(i,i+3) for y in range(j,j+3)]
if not Checkline(sqr):return False
return True
def checkmat():
return (check_row(board) and check_col(board) and square(board)) |
return checkmat() |
|
doozerd.go | package main
import (
"crypto/tls"
"doozer/peer"
"flag"
"fmt"
"github.com/ha/doozer"
"net"
"os"
"log"
_ "expvar"
"strconv"
)
const defWebPort = 8000
type strings []string
func (a *strings) Set(s string) bool {
*a = append(*a, s)
return true
}
func (a *strings) String() string {
return fmt.Sprint(*a)
}
var (
laddr = flag.String("l", "127.0.0.1:8046", "The address to bind to.")
aaddrs = strings{}
buri = flag.String("b", "", "boot cluster uri (tried after -a)")
waddr = flag.String("w", "", "web listen addr (default: see below)")
name = flag.String("c", "local", "The non-empty cluster name.")
showVersion = flag.Bool("v", false, "print doozerd's version string")
pi = flag.Float64("pulse", 1, "how often (in seconds) to set applied key")
fd = flag.Float64("fill", .1, "delay (in seconds) to fill unowned seqns")
kt = flag.Float64("timeout", 60, "timeout (in seconds) to kick inactive nodes")
hi = flag.Int64("hist", 2000, "length of history/revisions to keep")
certFile = flag.String("tlscert", "", "TLS public certificate")
keyFile = flag.String("tlskey", "", "TLS private key")
)
var (
rwsk = os.Getenv("DOOZER_RWSECRET")
rosk = os.Getenv("DOOZER_ROSECRET")
)
func init() {
flag.Var(&aaddrs, "a", "attach address (may be given multiple times)")
}
func Usage() {
fmt.Fprintf(os.Stderr, "Usage: %s [OPTIONS]\n", os.Args[0])
fmt.Fprintf(os.Stderr, "\nOptions:\n")
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, `
The default for -w is to use the addr from -l,
and change the port to 8000. If you give "-w false",
doozerd will not listen for for web connections.
`)
}
func main() {
*buri = os.Getenv("DOOZER_BOOT_URI")
flag.Usage = Usage
flag.Parse()
if *showVersion {
fmt.Println("doozerd", peer.Version)
return
}
if *laddr == "" {
fmt.Fprintln(os.Stderr, "require a listen address")
flag.Usage()
os.Exit(1)
}
log.SetPrefix("DOOZER ")
log.SetFlags(log.Ldate | log.Lmicroseconds)
tsock, err := net.Listen("tcp", *laddr)
if err != nil {
panic(err)
}
if *certFile != "" || *keyFile != "" {
tsock = tlsWrap(tsock, *certFile, *keyFile)
}
uaddr, err := net.ResolveUDPAddr("udp", *laddr)
if err != nil {
panic(err)
}
usock, err := net.ListenUDP("udp", uaddr)
if err != nil {
panic(err)
}
var wsock net.Listener
if *waddr == "" {
wa, err := net.ResolveTCPAddr("tcp", *laddr)
if err != nil {
panic(err)
}
wa.Port = defWebPort
*waddr = wa.String()
}
if b, err := strconv.Atob(*waddr); err != nil && !b {
wsock, err = net.Listen("tcp", *waddr)
if err != nil {
panic(err)
}
}
id := randId()
var cl *doozer.Conn
switch {
case len(aaddrs) > 0 && *buri != "":
cl = attach(*name, aaddrs)
if cl == nil {
cl = boot(*name, id, *laddr, *buri)
}
case len(aaddrs) > 0:
cl = attach(*name, aaddrs)
if cl == nil {
panic("failed to attach")
}
case *buri != "":
cl = boot(*name, id, *laddr, *buri)
}
peer.Main(*name, id, *buri, rwsk, rosk, cl, usock, tsock, wsock, ns(*pi), ns(*fd), ns(*kt), *hi)
panic("main exit")
}
func | (x float64) int64 {
return int64(x * 1e9)
}
func tlsWrap(l net.Listener, cfile, kfile string) net.Listener {
if cfile == "" || kfile == "" {
panic("need both cert file and key file")
}
cert, err := tls.LoadX509KeyPair(cfile, kfile)
if err != nil {
panic(err)
}
tc := new(tls.Config)
tc.Certificates = append(tc.Certificates, cert)
return tls.NewListener(l, tc)
}
| ns |
migrate.py | from markdown2 import markdown
from frappe.utils import validate_email_add
def migrate():
pass | import frappe
from frappe.database import Database |
|
liquid.ts | import { Context } from './context/context'
import * as fs from './fs/node'
import { forOwn, snakeCase } from './util/underscore'
import { Template } from './template/template'
import { Tokenizer } from './parser/tokenizer'
import { Render } from './render/render'
import Parser from './parser/parser'
import { TagImplOptions } from './template/tag/tag-impl-options'
import { Value } from './template/value'
import builtinTags from './builtin/tags'
import * as builtinFilters from './builtin/filters'
import { TagMap } from './template/tag/tag-map'
import { FilterMap } from './template/filter/filter-map'
import { LiquidOptions, normalizeStringArray, NormalizedFullOptions, applyDefault, normalize } from './liquid-options'
import { FilterImplOptions } from './template/filter/filter-impl-options'
import { FS } from './fs/fs'
import { toThenable, toValue } from './util/async'
export * from './types'
export class | {
public options: NormalizedFullOptions
public renderer: Render
public parser: Parser
public filters: FilterMap
public tags: TagMap
private fs: FS
public constructor (opts: LiquidOptions = {}) {
this.options = applyDefault(normalize(opts))
this.parser = new Parser(this)
this.renderer = new Render()
this.fs = opts.fs || fs
this.filters = new FilterMap(this.options.strictFilters)
this.tags = new TagMap()
forOwn(builtinTags, (conf: TagImplOptions, name: string) => this.registerTag(snakeCase(name), conf))
forOwn(builtinFilters, (handler: FilterImplOptions, name: string) => this.registerFilter(snakeCase(name), handler))
}
public parse (html: string, filepath?: string): Template[] {
const tokenizer = new Tokenizer(html, filepath)
const tokens = tokenizer.readTopLevelTokens(this.options)
return this.parser.parse(tokens)
}
public _render (tpl: Template[], scope?: object, opts?: LiquidOptions, sync?: boolean): IterableIterator<string> {
const options = { ...this.options, ...normalize(opts) }
const ctx = new Context(scope, options, sync)
return this.renderer.renderTemplates(tpl, ctx)
}
public async render (tpl: Template[], scope?: object, opts?: LiquidOptions): Promise<string> {
return toThenable(this._render(tpl, scope, opts, false))
}
public renderSync (tpl: Template[], scope?: object, opts?: LiquidOptions): string {
return toValue(this._render(tpl, scope, opts, true))
}
public _parseAndRender (html: string, scope?: object, opts?: LiquidOptions, sync?: boolean): IterableIterator<string> {
const tpl = this.parse(html)
return this._render(tpl, scope, opts, sync)
}
public async parseAndRender (html: string, scope?: object, opts?: LiquidOptions): Promise<string> {
return toThenable(this._parseAndRender(html, scope, opts, false))
}
public parseAndRenderSync (html: string, scope?: object, opts?: LiquidOptions): string {
return toValue(this._parseAndRender(html, scope, opts, true))
}
public * _parseFile (file: string, opts?: LiquidOptions, sync?: boolean) {
const options = { ...this.options, ...normalize(opts) }
const paths = options.root.map(root => this.fs.resolve(root, file, options.extname))
if (this.fs.fallback !== undefined) {
const filepath = this.fs.fallback(file)
if (filepath !== undefined) paths.push(filepath)
}
for (const filepath of paths) {
const { cache } = this.options
if (cache) {
const tpls = yield cache.read(filepath)
if (tpls) return tpls
}
if (!(sync ? this.fs.existsSync(filepath) : yield this.fs.exists(filepath))) continue
const tpl = this.parse(sync ? this.fs.readFileSync(filepath) : yield this.fs.readFile(filepath), filepath)
if (cache) cache.write(filepath, tpl)
return tpl
}
throw this.lookupError(file, options.root)
}
public async parseFile (file: string, opts?: LiquidOptions): Promise<Template[]> {
return toThenable(this._parseFile(file, opts, false))
}
public parseFileSync (file: string, opts?: LiquidOptions): Template[] {
return toValue(this._parseFile(file, opts, true))
}
public async renderFile (file: string, ctx?: object, opts?: LiquidOptions) {
const templates = await this.parseFile(file, opts)
return this.render(templates, ctx, opts)
}
public renderFileSync (file: string, ctx?: object, opts?: LiquidOptions) {
const options = normalize(opts)
const templates = this.parseFileSync(file, options)
return this.renderSync(templates, ctx, opts)
}
public _evalValue (str: string, ctx: Context): IterableIterator<any> {
const value = new Value(str, this.filters)
return value.value(ctx)
}
public async evalValue (str: string, ctx: Context): Promise<any> {
return toThenable(this._evalValue(str, ctx))
}
public evalValueSync (str: string, ctx: Context): any {
return toValue(this._evalValue(str, ctx))
}
public registerFilter (name: string, filter: FilterImplOptions) {
this.filters.set(name, filter)
}
public registerTag (name: string, tag: TagImplOptions) {
this.tags.set(name, tag)
}
public plugin (plugin: (this: Liquid, L: typeof Liquid) => void) {
return plugin.call(this, Liquid)
}
public express () {
const self = this // eslint-disable-line
return function (this: any, filePath: string, ctx: object, callback: (err: Error | null, rendered: string) => void) {
const opts = { root: [...normalizeStringArray(this.root), ...self.options.root] }
self.renderFile(filePath, ctx, opts).then(html => callback(null, html) as any, callback as any)
}
}
private lookupError (file: string, roots: string[]) {
const err = new Error('ENOENT') as any
err.message = `ENOENT: Failed to lookup "${file}" in "${roots}"`
err.code = 'ENOENT'
return err
}
/**
* @deprecated use parseFile instead
*/
public async getTemplate (file: string, opts?: LiquidOptions): Promise<Template[]> {
return this.parseFile(file, opts)
}
/**
* @deprecated use parseFileSync instead
*/
public getTemplateSync (file: string, opts?: LiquidOptions): Template[] {
return this.parseFileSync(file, opts)
}
}
| Liquid |
protocol_xmlrpc.py | #!/usr/bin/env python3
#-*- coding: iso-8859-1 -*-
################################################################################
#
# This module contains an implementation of XMLRPC interface/resource.
#
# Sample XMLRPC interface configuration (config_interface_xmlrpc_1.py):
#
# config = dict \
# (
# protocol = "xmlrpc", # meta
# request_timeout = None, # meta, optional
# listener_address = ("127.0.0.1", 8000), # tcp
# max_connections = 100, # tcp
# ssl_key_cert_file = None, # ssl, optional filename
# ssl_ca_cert_file = None, # ssl, optional filename
# ssl_ciphers = None, # ssl, optional str
# ssl_protocol = None, # ssl, optional "SSLv23", "TLSv1", "TLSv1_1", "TLSv1_2" or "TLS"
# response_encoding = "windows-1251", # http
# original_ip_header_fields = ("X-Forwarded-For", ), # http
# keep_alive_support = True, # http
# keep_alive_idle_timeout = 120.0, # http
# keep_alive_max_requests = 10, # http
# allow_none = False, # xmlrpc, Python-specific, optional
# )
#
# Sample processing module (interface_xmlrpc_1.py):
#
# def process_request(request, response):
# module, method = request["method"].split(".")
# args = request["args"]
# result = pmnc.__getattr__(module).__getattr__(method)(*args)
# response["result"] = result
#
# Sample XMLRPC resource configuration (config_resource_xmlrpc_1.py)
#
# config = dict \
# (
# protocol = "xmlrpc", # meta
# server_address = ("127.0.0.1", 8000), # tcp
# connect_timeout = 3.0, # tcp
# ssl_key_cert_file = None, # ssl, optional filename
# ssl_ca_cert_file = None, # ssl, optional filename
# ssl_ciphers = None, # ssl, optional str
# ssl_protocol = None, # ssl, optional "SSLv23", "TLSv1", "TLSv1_1", "TLSv1_2" or "TLS"
# ssl_server_hostname = None, # ssl, optional str
# ssl_ignore_hostname = False, # ssl, ignore certificate common/alt name name mismatch
# extra_headers = { "Authorization": "Basic dXNlcjpwYXNz" }, # http
# http_version = "HTTP/1.1", # http
# server_uri = "/xmlrpc", # xmlrpc
# request_encoding = "windows-1251", # xmlrpc
# allow_none = False, # xmlrpc, Python-specific, optional
# )
#
# Sample resource usage (anywhere):
#
# xa = pmnc.transaction.create()
# xa.xmlrpc_1.Module.Method(*args)
# result = xa.execute()[0]
#
# or if the only transaction participant:
#
# result = pmnc.transaction.xmlrpc_1.Module.Method(*args)
#
# Pythomnic3k project
# (c) 2005-2019, Dmitry Dvoinikov <[email protected]>
# Distributed under BSD license
#
###############################################################################
__all__ = [ "Interface", "Resource", "process_http_request" ]
###############################################################################
import os; from os import path as os_path
import xmlrpc.client; from xmlrpc.client import loads, dumps, Fault
if __name__ == "__main__": # add pythomnic/lib to sys.path
import os; import sys
main_module_dir = os.path.dirname(sys.modules["__main__"].__file__) or os.getcwd()
sys.path.insert(0, os.path.normpath(os.path.join(main_module_dir, "..", "..", "lib")))
import typecheck; from typecheck import typecheck, typecheck_with_exceptions, \
optional, tuple_of, dict_of, callable, one_of
import exc_string; from exc_string import exc_string
import pmnc.resource_pool; from pmnc.resource_pool import TransactionalResource, ResourceError
###############################################################################
class Interface: # XMLRPC interface built on top of HTTP interface
@typecheck
def __init__(self, name: str, *,
listener_address: (str, int),
max_connections: int,
ssl_key_cert_file: optional(os_path.isfile),
ssl_ca_cert_file: optional(os_path.isfile),
ssl_ciphers: optional(str) = None,
ssl_protocol: optional(one_of("SSLv23", "TLSv1", "TLSv1_1", "TLSv1_2", "TLS")) = None,
response_encoding: str,
original_ip_header_fields: tuple_of(str),
keep_alive_support: bool,
keep_alive_idle_timeout: float,
keep_alive_max_requests: int,
request_timeout: optional(float) = None,
allow_none: optional(bool) = False,
**kwargs): # this kwargs allows for extra application-specific
# settings in config_interface_xmlrpc_X.py
# create an instance of underlying HTTP interface
request_timeout = request_timeout or \
pmnc.config_interfaces.get("request_timeout") # this is now static
self._http_interface = \
pmnc.protocol_http.Interface(name,
listener_address = listener_address,
max_connections = max_connections,
ssl_key_cert_file = ssl_key_cert_file,
ssl_ca_cert_file = ssl_ca_cert_file,
ssl_ciphers = ssl_ciphers,
ssl_protocol = ssl_protocol,
response_encoding = response_encoding,
original_ip_header_fields = original_ip_header_fields,
allowed_methods = ("POST", ),
keep_alive_support = keep_alive_support,
keep_alive_idle_timeout = keep_alive_idle_timeout,
keep_alive_max_requests = keep_alive_max_requests,
gzip_content_types = (),
request_timeout = request_timeout)
# override the default process_http_request method of the created HTTP interface,
# having the HTTP handler method to be called through a pmnc call allows
# online modifications to this module, when it is reloaded
if pmnc.request.self_test == __name__: # self-test
self.process_xmlrpc_request = kwargs["process_xmlrpc_request"]
self._http_interface.process_http_request = \
lambda http_request, http_response: \
pmnc.__getattr__(__name__).process_http_request(http_request, http_response,
self.process_xmlrpc_request,
response_encoding = response_encoding,
allow_none = allow_none or False)
name = property(lambda self: self._http_interface.name)
listener_address = property(lambda self: self._http_interface.listener_address)
###################################
def start(self):
self._http_interface.start()
def cease(self):
self._http_interface.cease()
def stop(self):
self._http_interface.stop()
###################################
def process_xmlrpc_request(self, request, response):
handler_module_name = "interface_{0:s}".format(self.name)
pmnc.__getattr__(handler_module_name).process_request(request, response)
###############################################################################
def process_http_request(http_request: dict, http_response: dict,
process_xmlrpc_request: callable, *,
response_encoding: str, allow_none: bool):
assert http_request["method"] == "POST"
headers = http_request["headers"]
content = http_request["content"]
content_type = headers.get("content-type", "application/octet-stream")
if not content_type.startswith("text/xml"):
http_response["status_code"] = 415 # unsupported media type
return
# extract xmlrpc request from http request content, the parser
# will deduce the bytes encoding from the <?xml encoding attribute
try:
args, method = loads(content)
except:
raise Exception("invalid XMLRPC request: {0:s}".format(exc_string()))
# now we know more about the request
auth_tokens = pmnc.request.parameters["auth_tokens"]
pmnc.request.describe("XMLRPC{0:s} request {1:s} from {2:s}".\
format(auth_tokens["encrypted"] and "S" or "",
method, auth_tokens["peer_ip"]))
# the request contained a valid xmlrpc packet,
# it would be polite to respond with one as well
try:
# populate the request parameters with XMLRPC-specific values
pmnc.request.protocol = "xmlrpc"
xmlrpc_request = dict(method = method, args = args)
xmlrpc_response = dict(result = None)
# invoke the application handler
process_xmlrpc_request(xmlrpc_request, xmlrpc_response)
# fetch the XMLRPC call result
result = xmlrpc_response["result"]
if result is None:
result = ()
# marshal the result in an XMLRPC packet
content = dumps((result, ), methodresponse = True,
encoding = response_encoding, allow_none = allow_none)
except:
error = exc_string()
content = dumps(Fault(500, error), methodresponse = True, # 500 as in "Internal Server Error"
encoding = response_encoding, allow_none = allow_none)
pmnc.log.error("returning XMLRPC fault: {0:s}".format(error))
else:
if pmnc.log.debug:
pmnc.log.debug("returning XMLRPC response")
http_response["headers"]["content-type"] = "text/xml"
http_response["content"] = content
###############################################################################
class Resource(TransactionalResource): # XMLRPC resource
@typecheck
def __init__(self, name, *,
server_address: (str, int),
connect_timeout: float,
ssl_key_cert_file: optional(os_path.isfile),
ssl_ca_cert_file: optional(os_path.isfile),
ssl_ciphers: optional(str) = None,
ssl_protocol: optional(one_of("SSLv23", "TLSv1", "TLSv1_1", "TLSv1_2", "TLS")) = None,
ssl_server_hostname: optional(str) = None,
ssl_ignore_hostname: optional(bool) = False,
extra_headers: dict_of(str, str),
http_version: str,
server_uri: str,
request_encoding: str,
allow_none: optional(bool) = False):
TransactionalResource.__init__(self, name)
self._server_uri = server_uri
self._request_encoding = request_encoding
self._allow_none = allow_none
self._http_resource = \
pmnc.protocol_http.Resource(name,
server_address = server_address,
connect_timeout = connect_timeout,
ssl_key_cert_file = ssl_key_cert_file,
ssl_ca_cert_file = ssl_ca_cert_file,
ssl_ciphers = ssl_ciphers,
ssl_protocol = ssl_protocol,
ssl_server_hostname = ssl_server_hostname,
ssl_ignore_hostname = ssl_ignore_hostname,
extra_headers = extra_headers,
http_version = http_version)
###################################
def connect(self):
TransactionalResource.connect(self)
self._attrs = []
self._http_resource.connect()
def disconnect(self):
try:
self._http_resource.disconnect()
finally:
TransactionalResource.disconnect(self)
###################################
# overriding the following methods allows the contained HTTP
# resource to time out at the same time with this resource
def set_idle_timeout(self, idle_timeout):
self._http_resource.set_idle_timeout(idle_timeout)
TransactionalResource.set_idle_timeout(self, idle_timeout)
def reset_idle_timeout(self):
self._http_resource.reset_idle_timeout()
TransactionalResource.reset_idle_timeout(self)
def set_max_age(self, max_age):
self._http_resource.set_max_age(max_age)
TransactionalResource.set_max_age(self, max_age)
def _expired(self):
return self._http_resource.expired or \
TransactionalResource._expired(self)
###################################
def __getattr__(self, name):
self._attrs.append(name)
return self
###################################
def __call__(self, *args):
try:
method, self._attrs = ".".join(self._attrs), []
request = dumps(args, methodname = method,
encoding = self._request_encoding, allow_none = self._allow_none)
request_description = "XMLRPC request {0:s} to {1:s}".\
format(method, self._http_resource.server_info)
except:
ResourceError.rethrow(recoverable = True)
pmnc.log.info("sending {0:s}".format(request_description))
try:
status_code, headers, content = \
self._http_resource.post(self._server_uri, request.encode(self._request_encoding),
{ "Content-Type": "text/xml" })
if status_code != 200:
raise Exception("HTTP request returned code {0:d}".format(status_code))
result = loads(content)[0][0]
except Fault as e:
pmnc.log.warning("{0:s} returned fault {1:d}: {2:s}".\
format(request_description, e.faultCode, e.faultString))
ResourceError.rethrow(code = e.faultCode,
description = e.faultString, terminal = False)
except:
pmnc.log.warning("{0:s} failed: {1:s}".\
format(request_description, exc_string()))
raise
else:
pmnc.log.info("XMLRPC request returned successfully")
return result
###############################################################################
def self_test():
from socket import socket, AF_INET, SOCK_STREAM
from pmnc.request import fake_request
from pmnc.self_test import active_interface
def sendall(ifc, data):
s = socket(AF_INET, SOCK_STREAM)
s.connect(ifc.listener_address)
s.sendall(data)
return s
def | (s):
result = b""
data = s.recv(1024)
while data:
result += data
data = s.recv(1024)
return result
rus = "\u0410\u0411\u0412\u0413\u0414\u0415\u0401\u0416\u0417\u0418\u0419" \
"\u041a\u041b\u041c\u041d\u041e\u041f\u0420\u0421\u0422\u0423\u0424" \
"\u0425\u0426\u0427\u0428\u0429\u042c\u042b\u042a\u042d\u042e\u042f" \
"\u0430\u0431\u0432\u0433\u0434\u0435\u0451\u0436\u0437\u0438\u0439" \
"\u043a\u043b\u043c\u043d\u043e\u043f\u0440\u0441\u0442\u0443\u0444" \
"\u0445\u0446\u0447\u0448\u0449\u044c\u044b\u044a\u044d\u044e\u044f"
def post_string(ifc, method, s, request_encoding):
req = "<?xml version=\"1.0\" encoding=\"{0:s}\"?>" \
"<methodCall><methodName>{1:s}</methodName>" \
"<params><param><value><string>{2:s}</string>" \
"</value></param></params></methodCall>".format(request_encoding, method, s).encode(request_encoding)
hdr = "POST / HTTP/1.0\nContent-Type: text/xml\nContent-Length: {0:d}\n\n".format(len(req))
s = sendall(ifc, hdr.encode(request_encoding) + req)
resp = recvall(s)
assert resp.startswith(b"HTTP/1.1 200 OK\r\n")
resp = resp.split(b"\r\n\r\n", 1)[1]
return loads(resp)[0][0]
###################################
test_interface_config = dict \
(
protocol = "xmlrpc",
listener_address = ("127.0.0.1", 23673),
max_connections = 100,
ssl_key_cert_file = None,
ssl_ca_cert_file = None,
ssl_ciphers = None,
ssl_protocol = None,
response_encoding = "windows-1251",
original_ip_header_fields = ("X-Forwarded-For", ),
keep_alive_support = True,
keep_alive_idle_timeout = 3.0,
keep_alive_max_requests = 3,
allow_none = True
)
def interface_config(**kwargs):
result = test_interface_config.copy()
result.update(kwargs)
return result
###################################
def test_interface_start_stop():
def process_xmlrpc_request(request, response):
pass
with active_interface("xmlrpc_1", **interface_config(process_xmlrpc_request = process_xmlrpc_request)):
pass
test_interface_start_stop()
###################################
def test_interface_broken_requests():
def process_xmlrpc_request(request, response):
pass
with active_interface("xmlrpc_1", **interface_config(process_xmlrpc_request = process_xmlrpc_request)) as ifc:
s = sendall(ifc, b"POST / HTTP/1.0\nContent-Type: text/plain\n\n")
resp = recvall(s)
assert resp.startswith(b"HTTP/1.1 415 Unsupported Media Type\r\n")
s = sendall(ifc, b"POST / HTTP/1.0\nContent-Type: text/xml\nContent-Length: 3\n\nfoo")
resp = recvall(s)
assert resp.startswith(b"HTTP/1.1 500 Internal Server Error\r\n")
assert b"invalid XMLRPC request" in resp
test_interface_broken_requests()
###################################
def test_interface_marshaling():
def process_xmlrpc_request(request, response):
if request["method"] == "raise":
raise Exception(request["args"][0])
response["result"] = [request["method"], request["args"]]
with active_interface("xmlrpc_1", **interface_config(process_xmlrpc_request = process_xmlrpc_request)) as ifc:
assert post_string(ifc, "MethodName", "foo", "utf-8") == ["MethodName", ["foo"]]
assert post_string(ifc, rus, rus, "cp866") == [rus, [rus]]
try:
post_string(ifc, "raise", "foo", "iso-8859-5")
except Fault as e:
assert e.faultCode == 500 and e.faultString.startswith("Exception(\"foo\")")
else:
assert False
try:
post_string(ifc, "raise", rus, "utf-8")
except Fault as e:
assert e.faultCode == 500 and e.faultString.startswith("Exception(\"" + rus + "\")")
else:
assert False
test_interface_marshaling()
################################### TESTING RESOURCE
def test_resource():
def process_xmlrpc_request(request, response):
if request["method"] == "ShouldBe.Failing":
raise Exception(request["args"][0])
else:
response["result"] = request, pmnc.request.parameters["auth_tokens"]
with active_interface("xmlrpc_1", **interface_config(process_xmlrpc_request = process_xmlrpc_request)):
fake_request(10.0)
for i in range(16):
s = "*" * 2 ** i
n = "n" + str(i)
result = pmnc.transaction.xmlrpc_1.Module.Method(i, s, [ s ], { s: i, n: None })
assert result == [ { "method": "Module.Method", "args": [ i, s, [ s ], { s: i, n: None } ] },
{ "username": "user", "peer_ip": "127.0.0.1", "password": "pass", "encrypted": False } ]
try:
pmnc.transaction.xmlrpc_1.ShouldBe.Failing("some error")
except ResourceError as e:
assert e.code == 500 and e.description.startswith("Exception(\"some error\")")
assert not e.recoverable and not e.terminal
test_resource()
###################################
if __name__ == "__main__": import pmnc.self_test; pmnc.self_test.run()
###############################################################################
# EOF
| recvall |
apiserver.go | package runtime
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"strings"
"time"
// link to github.com/Litekube/kine, we have make some addition
"github.com/litekube/LiteKube/pkg/options/leader/apiserver"
"k8s.io/klog/v2"
"k8s.io/kubernetes/cmd/kube-apiserver/app"
)
type Apiserver struct {
ctx context.Context
LogPath string
Options *apiserver.ApiserverOptions
// Handler *http.Handler
// Authenticator *authenticator.Request
}
func NewApiserver(ctx context.Context, opt *apiserver.ApiserverOptions, logPath string) *Apiserver |
// start run in routine and no wait
func (s *Apiserver) Run() error {
klog.Info("run kube-apiserver")
args, err := s.Options.ToMap()
if err != nil {
return err
}
argsValue := make([]string, 0, len(args))
for k, v := range args {
if v == "-" || v == "" {
continue
}
argsValue = append(argsValue, fmt.Sprintf("--%s=%s", k, v))
}
command := app.NewAPIServerCommand(s.ctx.Done())
command.SetArgs(argsValue)
go func() {
for i := 0; i < 10; i++ {
etcdServer := strings.Split(apiserver.DefaultAPO.EtcdServers, ",")
if len(etcdServer) < 1 || etcdServer[0] == "" {
klog.Errorf("bad etcd servers.")
}
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}
if resp, err := client.Get(fmt.Sprintf("%s/health", etcdServer[0])); err != nil {
klog.Infof("waiting ETCD ready")
time.Sleep(1 * time.Second)
if i == 9 {
klog.Errorf("error to start check ETCD health: error: %s", err.Error())
return
}
continue
} else {
if 200 <= resp.StatusCode && resp.StatusCode < 300 {
klog.Infof("check ETCD ok.")
break
} else {
klog.Error("ETCD meet some error, error code: %d", resp.StatusCode)
return
}
}
}
klog.Infof("==>kube-apiserver: %s\n", argsValue)
err := command.ExecuteContext(s.ctx)
if err != nil {
klog.Fatalf("kube-apiserver exited: %v", err)
}
}()
// startupConfig := <-app.StartupConfig
// s.Handler = &startupConfig.Handler
// s.Authenticator = &startupConfig.Authenticator
return nil
}
// func (s *Apiserver) StartUpConfig() (*http.Handler, *authenticator.Request) {
// return s.Handler, s.Authenticator
// }
| {
return &Apiserver{
ctx: ctx,
Options: opt,
LogPath: logPath,
// Handler: nil,
// Authenticator: nil,
}
} |
authorize.go | package service
import (
"dev-test/nubank-dev-test-2k21/app/builder"
"dev-test/nubank-dev-test-2k21/app/dto/input"
"dev-test/nubank-dev-test-2k21/app/entity"
"dev-test/nubank-dev-test-2k21/app/validator"
)
type AuthorizeService struct {
validatorManager validator.Manager
}
func | (validatorManager validator.Manager) AuthorizeService {
return AuthorizeService{
validatorManager: validatorManager,
}
}
func (a AuthorizeService) HandleOperations(inputOperations input.Operations) entity.Operations {
operations := entity.NewOperations()
account := entity.NewAccountEmpty()
for _, operationLine := range inputOperations.Lines {
if operationLine.IsAccount() && account.IsInitialized() {
operations.RegisterViolationEvent(account, entity.NewViolationAccountAlreadyInitialized())
continue
}
if operationLine.IsTransaction() && !account.IsInitialized() {
operations.RegisterViolationEvent(account, entity.NewViolationAccountNotInitialized())
continue
}
if operationLine.IsTransaction() && !account.IsActiveCard() {
operations.RegisterViolationEvent(account, entity.NewViolationCardNotActive())
continue
}
if operationLine.IsAccount() {
account = builder.CreateAccountFromInputDTO(operationLine.(input.AccountLine))
operations.RegisterEvent(account, entity.NewViolationsEmpty())
continue
}
if operationLine.IsTransaction() {
transaction := builder.CreateTransactionFromInputDTO(operationLine)
violations := a.validatorManager.GetViolations(account, transaction)
if 1 > len(violations) {
account = entity.NewAccountSubtractLimit(account, transaction)
}
operations.RegisterEvent(account, violations)
}
}
return operations
}
| NewAuthorizeService |
edit_ramen.py | from django.shortcuts import render,HttpResponse, HttpResponseRedirect
from django.template import loader
from django.conf import settings
from rameniaapp.forms import EditNoodleForm
from rameniaapp.models import Noodle, NoodleImage, Edit, Tag
from .edit_util import apply_change
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.contrib import messages
@login_required(login_url="/app/login")
def ramen_edit_view(request, noodle_id):
| '''View for handling edit noodle form'''
noodle = Noodle.objects.get(pk=noodle_id)
# If this is a POST request then process the Form data
if request.method == 'POST':
user = request.user
# Create a form instance and populate it with data from the request of the user
form = EditNoodleForm(request.POST or None, request.FILES)
# Check if the form is valid
if form.is_valid():
# There's not a clean looking way to turn form data into JSON
# unfortunately
metadata = { "Name": form.cleaned_data["name"], "Description": form.cleaned_data["description"], \
"Flavor": form.cleaned_data["flavor"], \
"Manufacturer": form.cleaned_data["manufacturer"], \
"Released": form.cleaned_data["released"], "Line": form.cleaned_data["line"], \
"Tags": form.cleaned_data["tags"] }
# Create Edit object and associate image if added
edit = Edit(editor = user, change = metadata, noodle = noodle)
if request.FILES:
file = list(request.FILES.keys())[0]
edit.image = request.FILES[file]
edit.save()
messages.add_message(request, messages.SUCCESS, "Edit submitted successfully- please wait for moderator approval")
#apply_change(edit)
return HttpResponseRedirect(reverse('noodle', kwargs={"noodle_id" : noodle.id}))
else:
# Prepopulate initial values for edit form- otherwise it's not a very good
# edit form
# Yes this is the best way to turn the tags into a string, I do not
# like it either
tags = ",".join(noodle.tags.values_list("name", flat=True))
initial = {"name": noodle.name, "description": noodle.metadata["Description"], \
"flavor": noodle.metadata["Flavor"], \
"manufacturer": noodle.metadata["Manufacturer"], \
"released": noodle.metadata["Released"], "line": noodle.metadata["Line"], \
"tags": tags}
form = EditNoodleForm(initial = initial)
template = loader.get_template('edit_ramen.html')
context = {
'form': form, 'noodle' : noodle
}
return HttpResponse(template.render(context, request)) |
|
html-has-lang.js | /**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in 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.
*/
'use strict';
/**
* @fileoverview Ensures every HTML document has a `lang` attribute.
* See base class in axe-audit.js for audit() implementation.
*/
const AxeAudit = require('./axe-audit');
class | extends AxeAudit {
/**
* @return {!AuditMeta}
*/
static get meta() {
return {
category: 'Accessibility',
name: 'html-has-lang',
description: '`<html>` element has a `[lang]` attribute.',
failureDescription: '`<html>` element does not have a `[lang]` attribute.',
helpText: 'If a page doesn\'t specify a lang attribute, a screen reader assumes ' +
'that the page is in the default language that the user chose when setting up the ' +
'screen reader. If the page isn\'t actually in the default language, then the screen ' +
'reader might not announce the page\'s text correctly. ' +
'[Learn more](https://dequeuniversity.com/rules/axe/2.2/html-lang?application=lighthouse).',
requiredArtifacts: ['Accessibility']
};
}
}
module.exports = HTMLHasLang;
| HTMLHasLang |
toka_physics.js | //*****Physics constants and variables*************
var K_BOLT = 1.6021e-16; // Boltzmann's constant
var MU_0 = 4.0e-7 * Math.PI; // Permittivity
var E_ALPHA_0 = 3.5e3; // Alpha energy (keV)
var elon= 2.0;
var zEff = 1.65; // Z-effective
var zImp = 6.0; // Z of dominant impurity
var rnDnDT = 0.5; // deuterium / (deuterium + tritium) ratio
var cTau = 1.80; // Confinement enhancement multiplier
var tauPHe = 15.; // Helium ash particle confinement time (seconds)
var rmin = 0.795;
var rmaj = 2.59;
var q = 2.3;
// var q=Math.E*2/3;
var Nhe = 0; //Helium ash
var cAsh = 0; //Helium ash coefficient
var area = Math.PI*rmin*rmin*elon;
var volume = 2*Math.PI*rmaj*area;
var b_c_ratio = q * 1.e6 * MU_0 * rmaj / (Math.PI * rmin*rmin * (1. + elon*elon));
//************Programatic variables***********
var finalOut = {};
var finalTemp = 0;
var finalScore = 0;
// var magVal = 14;
var magVal = 1;
var densVal = 2.5;
var powVal = 0.19;
var magMax = 20;
var densMax = 10;
var powMax = 10;
var aliens = [];
var totalDudes = 500;
var ParticleSpread = 0; //20
var LarmourRadius = 0; //5
var ThetaMax = 23; // as multiples of (2PI)
// var ThetaMax = 92; // as multiples of (2PI)
| layer.draw();
}
function displayScore(){
finalTemp = bisection();
//finalTemp = 250;
finalOut = calcScore(finalTemp);
finalScore = finalOut.score;
iter.tween = new Konva.Tween({
node:iter,
opacity:finalScore/169,
duration:0
}).play();
layer.draw();
writeMessage('Mag: ' + magVal + '\n' + 'Dens: ' + densVal + '\n' + 'Pow: ' + powVal + '\n\n' + 'Temp: ' + finalTemp + '\n' + 'Score: ' + finalScore + '\n\n' + 'P_oh: ' + finalOut.P_oh * 1.e-6 + '\n' + 'P_alpha: ' + finalOut.P_alpha * 1.e-6 + '\n' + 'P_cond: ' + finalOut.P_cond * 1.e-6 + '\n' + 'P_rad: ' + finalOut.P_rad * 1.e-6 + '\n\n' + 'Beta thermal: ' + finalOut.beta_th + '\n' + 'Beta alpha: ' + finalOut.beta_falpha + '\n'+ 'Beta: ' + finalOut.beta + '\n' + 'Beta max: ' + finalOut.betamax + '\n\n' + 'Density: ' + finalOut.densreal*1.e-20 + '\n' + 'Dens_max: ' + finalOut.densmax*1.e-20 + '\n');
}
// displayScore();
//**************************Physics**********************************
function bisection() {
var Tmin = 1.;
var Tmax = 1000.;
var Dt = Tmax - Tmin;
var maxloops = 20;
var t_left = Tmin;
var t_right = Tmax;
var t_mid = Tmin + Dt/2.;
var f_left = calcdwdt(t_left);
var f_right = calcdwdt(t_right);
var f_mid = calcdwdt(t_mid);
var t_final;
if (f_left*f_right >= 0) {
return (-1.)
console.log('returned in bisection');
}
for (i=0 ; i<maxloops ; i++) {
if (f_left * f_mid >= 0) {
t_left = t_mid;
} else {
t_right = t_mid;
}
Dt = (t_right-t_left)/2.;
t_mid = t_left + Dt;
f_left = calcdwdt(t_left);
f_right = calcdwdt(t_right);
f_mid = calcdwdt(t_mid);
if (i == (maxloops-1)) {
t_final = t_mid;
}
}
return(t_final);
}
function calcdwdt(temperature) {
var mag = magVal;
var P_aux_MW = powVal;
var dens = densVal;
var densreal = dens * 1.e20; //in m^-3
var tempkev = temperature / 11.604; //in keV
var P_aux= P_aux_MW * 1.e6; //in Watts
//density ratio calculations
var rnHene = Nhe / (dens * 1.e20 * volume);
var rnDTne = (zImp - zEff - 2.*(zImp - 2.)*rnHene) / (zImp - 1.);
var rnZne = (zEff - rnDTne - 4.*rnHene) / (zImp * zImp);
var rnine = rnDTne + rnHene + rnZne;
//Wtot calculation
var Wtot = 1.5 * densreal * K_BOLT * tempkev * ( 1. + rnine) * volume;
//P_alpha calculation
var za1=-21.377692;
var za2=-25.204054;
var za3=-7.1013427E-2;
var za4=1.9375451E-4;
var za5=4.9246592E-6;
var za6=-3.9836572E-8;
var zrsg=.2935;
var s5 = 1.e20 * Math.exp(za1 / Math.pow(tempkev,zrsg) + za2 + tempkev*(za3 + tempkev*(za4 + tempkev*(za5 + tempkev*za6)))) * 1.e20 * 1.e-6;
var den20 = rnDTne * densreal / 1.e20;
var P_alpha = E_ALPHA_0 * K_BOLT * rnDnDT * (1. - rnDnDT) * den20 * den20 * s5 * volume;
//P_oh calculation
var current = mag/b_c_ratio*1.e6; //current in amps
var CoulLog = 37.8 - Math.log(Math.sqrt(densreal)/tempkev);
var J0 = current / area; // Central current density, Eq. 26
var resnc = 2.5; // Neoclassical resistivity correction
var P_oh = 1.65e-9 * zEff * CoulLog * resnc * Math.pow(tempkev,-1.5) * J0 * J0 * volume;
//P_rad calculation
var P_rad = 1.0e06 * 0.0168 * dens * dens * Math.sqrt(tempkev/10.) * zEff * volume;
//tau_E, tau_eff and P_cond calculation
var aibar = 2.5; //average ion mass (amu)
var P_in = P_alpha + P_oh + P_aux - P_rad;
var P_in_max = Math.max(P_in*1.e-6,1.);
var tau_array = [aibar, elon, current*1.e-6, densreal*1.e-19, mag, rmin, rmaj, P_in_max];
var exps = [0.0381, 0.5, 0.5, 0.85, 0.1, 0.2, 0.3, 1.2, -0.5];
var tau_E = exps[0]
* Math.pow(tau_array[0],exps[1])
* Math.pow(tau_array[1],exps[2])
* Math.pow(tau_array[2],exps[3])
* Math.pow(tau_array[3],exps[4])
* Math.pow(tau_array[4],exps[5])
* Math.pow(tau_array[5],exps[6])
* Math.pow(tau_array[6],exps[7])
* Math.pow(tau_array[7],exps[8]);
var tau_na = 7.e-22 * densreal * rmin * rmaj * rmaj * q;
var tau_eff = 1. / Math.sqrt(1./(tau_na*tau_na) + Math.pow(cTau * tau_E,-2));
var P_cond = Wtot / tau_eff;
var dwdt = P_in - P_cond; // = dW/dt This is what must be found to be zero
return(dwdt);
}
function calcScore(temperature){
//***This is all the same as the calcdwdt function****
var mag = magVal
var P_aux_MW = powVal;
var dens = densVal;
var densreal = dens * 1.e20; //in m^-3
var tempkev = temperature / 11.604; //in keV
var P_aux= P_aux_MW * 1.e6; //in Watts
//density ratio calculations
var rnHene = Nhe / (dens * 1.e20 * volume);
var rnDTne = (zImp - zEff - 2.*(zImp - 2.)*rnHene) / (zImp - 1.);
var rnZne = (zEff - rnDTne - 4.*rnHene) / (zImp * zImp);
var rnine = rnDTne + rnHene + rnZne;
//Wtot calculation
var Wtot = 1.5 * densreal * K_BOLT * tempkev * ( 1. + rnine) * volume;
//P_alpha calculation
var za1=-21.377692;
var za2=-25.204054;
var za3=-7.1013427E-2;
var za4=1.9375451E-4;
var za5=4.9246592E-6;
var za6=-3.9836572E-8;
var zrsg=.2935;
var s5 = 1.e20 * Math.exp(za1 / Math.pow(tempkev,zrsg) + za2 + tempkev*(za3 + tempkev*(za4 + tempkev*(za5 + tempkev*za6)))) * 1.e20 * 1.e-6;
var den20 = rnDTne * densreal / 1.e20;
var P_alpha = E_ALPHA_0 * K_BOLT * rnDnDT * (1. - rnDnDT) * den20 * den20 * s5 * volume;
//P_oh calculation
var current = mag/b_c_ratio*1.e6; //current in amps
var CoulLog = 37.8 - Math.log(Math.sqrt(densreal)/tempkev);
var J0 = current / area; // Central current density, Eq. 26
var resnc = 2.5; // Neoclassical resistivity correction
var P_oh = 1.65e-9 * zEff * CoulLog * resnc * Math.pow(tempkev,-1.5) * J0 * J0 * volume;
//P_rad calculation
var P_rad = 1.0e06 * 0.0168 * dens * dens * Math.sqrt(tempkev/10.) * zEff * volume;
//tau_E, tau_eff and P_cond calculation
var aibar = 2.5; //average ion mass (amu)
var P_in = P_alpha + P_oh + P_aux - P_rad;
var P_in_max = Math.max(P_in*1.e-6,1.);
var tau_array = [aibar, elon, current*1.e-6, densreal*1.e-19, mag, rmin, rmaj, P_in_max];
var exps = [0.0381, 0.5, 0.5, 0.85, 0.1, 0.2, 0.3, 1.2, -0.5];
var tau_E = exps[0]
* Math.pow(tau_array[0],exps[1])
* Math.pow(tau_array[1],exps[2])
* Math.pow(tau_array[2],exps[3])
* Math.pow(tau_array[3],exps[4])
* Math.pow(tau_array[4],exps[5])
* Math.pow(tau_array[5],exps[6])
* Math.pow(tau_array[6],exps[7])
* Math.pow(tau_array[7],exps[8]);
var tau_na = 7.e-22 * densreal * rmin * rmaj * rmaj * q;
var tau_eff = 1. / Math.sqrt(1./(tau_na*tau_na) + Math.pow(cTau * tau_E,-2));
var P_cond = Wtot / tau_eff;
var dwdt = P_in - P_cond;
//****Up to here it's the same as calcdwdt
//Calculation of rate of change of Helium Ash (this is a placeholder for when He values are included)
var dNHedt = cAsh * (P_alpha / (E_ALPHA_0 * K_BOLT)- Nhe/ tauPHe);
//************Beta calculation**************
// Source rate of alpha particles.
var znsour = P_alpha / (E_ALPHA_0 * K_BOLT * volume);
// Compute electron, deuterium, tritium, and impurity Coulomb
// logarithms, Eq. 63. The impurity mass (zamimp) is approximately
// twice its nuclear charge.
var zlame = 37.8 - Math.log(Math.sqrt(densreal)/tempkev);
var zlamd = 45.5 + Math.log(Math.sqrt(tempkev / densreal) * 4.*2./(4.+2.));
var zlamt = 45.5 + Math.log(Math.sqrt(tempkev / densreal) * 4.*3./(4.+3.));
var zamimp = 2. * zImp;
var zlamz = 45.5 + Math.log(Math.sqrt(tempkev / densreal) * 4.*zamimp/(4.+zamimp));
/*
* Critical slowing down energy at which loss of energy to electrons
* equals the loss to ions, Eq. 62.
*/
var zecrit = 4.0*14.8 * tempkev * Math.pow((((rnDnDT * zlamd / 2. + (1.-rnDnDT) * zlamt / 3.) * rnDTne + rnZne * zlamz * zImp*zImp / zamimp) / zlame),(2./3.));
var zvcrat = Math.sqrt(E_ALPHA_0 / zecrit); // Velocity ratio, Eq. 64
var ztauth = 0.371 * Math.pow(tempkev/10.,1.5) * (1.0e20/densreal) * (17./zlame);//Slowing down time, Eq. 65
var zeavg = E_ALPHA_0*K_BOLT * 0.5 * (1.-Math.pow(zvcrat,(-2.)) * (Math.log((1.+Math.pow(zvcrat,3.))/Math.pow((1.+zvcrat),3.)) / 3. + (2. * Math.atan((2.*zvcrat - 1.) / Math.sqrt(3.)) + Math.PI / 3.) / Math.sqrt(3.))); // Avg. alpha energy, Eq. 66
/*
* Time to thermalize, Eq. 67
*/
var ztaunf = ztauth * Math.log( 1. + Math.pow(zvcrat,3.) ) / 3.;
/*
* Alpha beta, Eq. 69; thermal beta, Eq. 61; total beta, Eq. 70;
* alpha density, Eq. 68; alpha / electron density:
*/
var pbetfa = (2.*MU_0/(mag*mag))*(2./3.)*(znsour*ztauth*zeavg);
var zbetth = (2.*MU_0/(mag*mag))*densreal * ( 1. + rnine)*K_BOLT*tempkev;
var beta = 100 * (pbetfa + zbetth); //In percentage
//***********************************************
//Beta limit Using the Troyon limit with a coefficient of 3.0
var betamax = (3.0 * current*1.e-6 / (rmin * mag));
//Density limit
/*
* This is the Greenwald limit; it's normally taken to
* be the line-averaged density. But, here, we have effectively
* flat profiles.
*/
var densmax = 1.e20 * current*1.e-6 / (Math.PI * rmin * rmin);
var Q_phy = 0.;
var score = 0.;
//Calculate score
if (densreal < densmax && beta < betamax) {
Q_phy = 5. * P_alpha / (P_aux + P_oh);
score = 100. * Math.pow(Q_phy/100.,0.3);
}
var out = {
score:score,
beta:beta,
beta_falpha:pbetfa,
beta_th:zbetth,
betamax:betamax,
densreal:densreal,
densmax:densmax,
Q_phy:Q_phy,
P_in:P_in,
P_alpha:P_alpha,
P_oh:P_oh,
P_cond:P_cond,
P_rad:P_rad
}
return(out);
} |
function writeMessage(message) {
text.setText(message); |
0003_auto_20180507_0734.py | # Generated by Django 2.0.4 on 2018-05-07 07:34
from django.db import migrations, models
class | (migrations.Migration):
dependencies = [
('blog', '0002_auto_20180507_0653'),
]
operations = [
migrations.AlterField(
model_name='post',
name='banner_photo',
field=models.ImageField(upload_to='static/media', verbose_name='Image'),
),
]
| Migration |
countBy.ts | /**
* 根据函数对数组进行分组, 返回分组的对象信息
* @param arr
* @param fn
*/
const countBy = (arr: any, fn: any) =>
arr
.map(typeof fn === "function" ? fn : (val: { [x: string]: any }) => val[fn]) | acc[val] = (acc[val] || 0) + 1
return acc
}, {})
export default countBy | .reduce((acc: { [x: string]: any }, val: string | number) => { |
prod-webpack.config.js | const path = require("path");
const themeEntries = require('./themes.js').themeEntries;
const extractThemesPlugin = require('./themes.js').extractThemesPlugin;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ModuleFederationPlugin = require('./moduleFederation').plugin;
const paths = {
base: path.join(__dirname, ".."),
dist: path.join(__dirname, "..", "web", "client", "dist"),
framework: path.join(__dirname, "..", "web", "client"),
code: path.join(__dirname, "..", "web", "client")
};
module.exports = require('./buildConfig')(
{
"mapstore2": path.join(paths.code, "product", "app"),
"embedded": path.join(paths.code, "product", "embedded"),
"ms2-api": path.join(paths.code, "product", "api"),
"dashboard-embedded": path.join(paths.code, "product", "dashboardEmbedded"),
"geostory-embedded": path.join(paths.code, "product", "geostoryEmbedded")
},
themeEntries,
paths,
[extractThemesPlugin, ModuleFederationPlugin],
true,
"dist/",
undefined,
[
new HtmlWebpackPlugin({
template: path.join(paths.framework, 'indexTemplate.html'),
chunks: ['mapstore2'],
inject: "body",
hash: true
}),
new HtmlWebpackPlugin({
template: path.join(paths.framework, 'embeddedTemplate.html'),
chunks: ['embedded'],
inject: "body",
hash: true,
filename: 'embedded.html'
}),
new HtmlWebpackPlugin({
template: path.join(paths.framework, 'apiTemplate.html'),
chunks: ['ms2-api'],
inject: 'head',
hash: true,
filename: 'api.html'
}),
new HtmlWebpackPlugin({
template: path.join(paths.framework, 'geostory-embedded-template.html'),
chunks: ['geostory-embedded'],
inject: "body",
hash: true,
filename: 'geostory-embedded.html'
}),
new HtmlWebpackPlugin({
template: path.join(paths.framework, 'dashboard-embedded-template.html'),
chunks: ['dashboard-embedded'],
inject: 'body',
hash: true,
filename: 'dashboard-embedded.html'
}) | ]
); |
|
text-input.scss.d.ts | export const container: string;
export const label: string;
export const active: string;
export const inputWrapper: string;
export const input: string; | export const inputHelp: string;
export const helpIcon: string;
export const helpMessage: string; | |
TestSuite.py | """
Interface to a test suite module (one or more runs) used by ProductModelProgram
"""
from operator import concat
from .model import Model
from functools import reduce
class TestSuite(Model):
def __init__(self, module, exclude, include):
Model.__init__(self, module, exclude, include)
def post_init(self):
"""
Now that all modules have been imported and executed their __init__
do a postprocessing pass
to process metadata that might be affected by configuration modules
"""
# Do all of this work here rather than in __init__
# so it can include the effects of any pymodel config modules
# recognize PEP-8 style names (all lowercase) if present
if hasattr(self.module, 'testsuite'):
self.module.testSuite = self.module.testsuite
if hasattr(self.module, 'test_suite'):
self.module.testSuite = self.module.test_suite
if hasattr(self.module, 'actions'):
self.actions = list(self.module.actions) # copy, actions from cmd line
else:
self.actions = list(self.actions_in_suite()) # default, copy
Model.post_init(self) # uses self.actions
# Revise the test suite to account for excluded, included actions
self.test_suite = list()
for run in self.module.testSuite:
new_run = list() # list not tuple, must mutable
for action in run:
if action[0] in self.actions:
new_run.append(action)
else:
break # truncate the run before the excluded action
self.test_suite.append(new_run)
# prepare for first run
self.irun = 0 # index of current test run in test suite
self.pc = 0 # program counter
def actions_in_suite(self):
# there might be two or three items in action_tuple
return tuple(set(reduce(concat,[[action_tuple[0] for action_tuple in run]
for run in self.module.testSuite])))
def Accepting(self):
# In a test suite, the only accepting states are at ends of runs
# NB Here Accepting() is called *after* DoAction() that advances self.pc
length = len(self.test_suite[self.irun]) # number of tuples in run
return (self.pc == length)
def make_properties(self, accepting):
return { 'accepting': accepting, 'statefilter': True,
'stateinvariant': True }
def Properties(self):
return self.make_properties(self.Accepting())
def Reset(self): # needed by stepper
self.pc = 0
if self.irun < len(self.test_suite) - 1:
self.irun += 1
else:
raise StopIteration # no more runs in test suite
def ActionEnabled(self, a, args):
"""
action a with args is enabled in the current state
"""
step = self.test_suite[self.irun][self.pc]
action, arguments = step[0:2] # works whether or not step has result
return (a == action and args == arguments)
def EnabledTransitions(self, cleanup=False):
"""
Return list of all tuples for enabled actions. Here, there is just one.
(action, args, next state, next state is accepting state)
Next state is a list of two elements:the run number and step within the run
In a test suite, there is always just *one* next action, or *none*
Ignore cleanup, test suite should always end in accepting state.
"""
run = self.test_suite[self.irun]
length = len(run)
if self.pc < length:
step = run[self.pc]
action, args = step[0:2]
result = step[2] if len(step) > 2 else None # result is optional
next = self.pc + 1
accepting = (next == length)
return([(action, args, result, (self.irun,next),
self.make_properties(accepting))])
else:
return list() # test run finished, nothing enabled,
def DoAction(self, a, args):
|
def Current(self):
return (self.irun, self.pc)
def Restore(self, state):
"""
Restore state
"""
self.irun, self.pc = state
# GetNext not needed
| step = self.test_suite[self.irun][self.pc]
result = step[2] if len(step) > 2 else None # result is optional
self.pc += 1
return result |
signal_augment.py | import os
import subprocess
import numpy as np
from tqdm import tqdm
from typing import Dict
MAX_FREQ = 7999
def to_str(v):
if isinstance(v, tuple):
s = " ".join(str(x) for x in v)
elif isinstance(v, float) or isinstance(v, int):
s = str(v)
else:
assert False
return s
def build_sox_distortions(audio_file, params):
param_str = " ".join([k + " " + to_str(v) for k, v in params.items()])
sox_params = "sox {} -p {} ".format(audio_file, param_str)
return sox_params
def build_sox_noise(
audio_file,
amod_lowpass_cutoff=0.1,
lowpass_cutoff=MAX_FREQ,
highpass_cutoff=1,
noise_gain=-4,
):
"""
play original.wav synth whitenoise lowpass 0.1 synth whitenoise amod gain -n 0 lowpass 100 highpass 1
"""
sox_params = "sox {audio_file} -p synth whitenoise lowpass {amod_lowpass_cutoff} synth whitenoise amod gain -n {noise_gain} lowpass {lowpass_cutoff} highpass {highpass_cutoff}".format(
audio_file=audio_file,
amod_lowpass_cutoff=amod_lowpass_cutoff,
lowpass_cutoff=lowpass_cutoff,
highpass_cutoff=highpass_cutoff,
noise_gain=noise_gain,
)
return sox_params
def build_varying_amplitude_factor(audio_file, lowpass_cutoff=1, ac_gain=-9):
ac = "sox {} -p synth whitenoise lowpass {} gain -n {}".format(
audio_file, lowpass_cutoff, ac_gain
)
dc = "sox {} -p gain -90 dcshift 0.5".format(audio_file)
return "sox -m <({}) <({}) -p".format(ac, dc)
def multiply_signals(signal_a, signal_b):
return ("sox -T <({signal_a}) <({signal_b}) -p").format(
signal_a=signal_a, signal_b=signal_b,
)
def build_sox_interference(
interfere_file, interfere_signal, lowpass_cutoff=1, ac_gain=-6
):
factor = build_varying_amplitude_factor(interfere_file, lowpass_cutoff, ac_gain)
return multiply_signals(factor, interfere_signal)
def add_signals_trim_to_len(original, signals, augmented):
signals_to_add = " ".join(["<(%s)" % s for s in signals])
sox_cmd = "sox -m {signals} -b 16 {augmented} trim 0 $(soxi -D {original})".format(
signals=signals_to_add, original=original, augmented=augmented
)
return sox_cmd
def build_random_bandpass(min_low=50, min_band_width=100, max_high=1000) -> Dict:
d = {}
max_high_cutoff = MAX_FREQ
if np.random.choice([True, False], p=[0.5, 0.5]):
lowpass = int(round(np.random.uniform(low=min_low, high=MAX_FREQ)))
d["lowpass"] = lowpass
max_high_cutoff = lowpass - min_band_width
if np.random.choice([True, False], p=[0.5, 0.5]):
highpass = int(
round(np.random.uniform(low=1, high=min(max_high, max_high_cutoff)))
)
d["highpass"] = highpass
return d
def augment_with_sox(original_file, audio_files, augmented_file):
interfere_file = np.random.choice(audio_files)
min_SNR = 20 # normal:20, less:30, evenless:40
min_SIR = 5 # normal:10, less:20, evenless:30
signal_gain = round(np.random.uniform(low=-10, high=0), 2)
signal_params = {
"tempo": round(np.random.triangular(left=0.7, mode=1.0, right=1.3), 2),
"pitch": int(
round(np.random.triangular(left=-200, mode=0, right=200))
), # normal 100, less: 50, evenless: 30
"reverb": (int(round(np.random.uniform(low=0, high=50))), 50, 100, 100, 0, 0,),
"gain -n": signal_gain,
}
signal_params.update(build_random_bandpass(1000, 1000, 100))
interfere_params = {
"tempo": round(np.random.uniform(low=0.6, high=1.4), 2),
"pitch": int(round(np.random.uniform(low=-500, high=500))),
"reverb": (int(round(np.random.uniform(low=0, high=100))), 50, 100, 100, 0, 0),
"gain -n": round(np.random.uniform(low=-50, high=signal_gain - min_SIR), 2),
}
interfere_params.update(build_random_bandpass(50, 100, 1000))
# params = {'signal_params':signal_params,'interfere_params':interfere_params,'noise_power':noise_power}
# pprint(params)
signal = build_sox_distortions(original_file, signal_params)
interfere_signal = build_sox_distortions(interfere_file, interfere_params)
noise_power = round(np.random.uniform(-60, signal_gain - min_SNR), 2)
lowpass = int(round(np.random.uniform(low=100, high=MAX_FREQ)))
highpass = int(round(np.random.uniform(low=1, high=lowpass)))
noise = build_sox_noise(
original_file, np.random.uniform(0.1, 2), lowpass, highpass, noise_power
)
interf = build_sox_interference(
interfere_file,
interfere_signal,
lowpass_cutoff=np.random.uniform(0.5, 2),
ac_gain=int(round(np.random.uniform(-9, -3))),
)
sox_cmd = add_signals_trim_to_len(
original_file, [signal, noise, interf], augmented_file
)
FNULL = open(os.devnull, "w")
subprocess.call(["bash", "-c", sox_cmd], stdout=FNULL, stderr=subprocess.STDOUT)
# subprocess.call(["bash", "-c", sox_cmd])
# output = subprocess.check_output(["bash", "-c", sox_cmd])
# if len(output)>0 and 'FAIL' in output:
# print(output)
# return 1 if len(output)>0 else 0
def augment_with_specific_params():
|
if __name__ == "__main__":
import librosa
original = "../../original.wav"
augmented = "/tmp/augmented.wav"
interfering = "../../interference.wav"
# augment_with_specific_params()
for k in range(9):
augment_with_sox(original, [interfering], "/tmp/augmented_%d.wav" % k)
# assert False
# path = os.environ['HOME']+"/data/asr_data/SPANISH"
# audio_files = librosa.util.find_files(path)
#
# with open('spanish_train_manifest.csv') as f:
# audio_text_files = f.readlines()
# audio_files = [x.strip().split(",")[0] for x in audio_text_files]
#
# for k in tqdm(range(100000)):
# original = np.random.choice(audio_files)
# random_augmentation(original, audio_files, augmented)
| signal_gain = 0
signal_params = dict(tempo=1.0, pitch=0, reverb=0)
signal_params["gain -n"] = 0
signal = build_sox_distortions(original, signal_params)
interfere_signal = build_sox_distortions(
interfering, dict(gain=signal_gain - 10, tempo=0.8, pitch=100, reverb=50)
)
noise = build_sox_noise(
original, noise_gain=signal_gain - 20, lowpass_cutoff=6000, highpass_cutoff=10
)
interf = build_sox_interference(interfering, interfere_signal)
sox_cmd = add_signals_trim_to_len(original, [signal, noise, interf], augmented)
subprocess.call(["bash", "-c", sox_cmd]) |
preview_features.rs | use once_cell::sync::Lazy;
use serde::{Serialize, Serializer};
use PreviewFeature::*;
macro_rules! features {
($( $variant:ident $(,)? ),*) => {
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum PreviewFeature {
$(
$variant,
)*
}
impl PreviewFeature {
pub fn parse_opt(s: &str) -> Option<Self> {
$(
if s.eq_ignore_ascii_case(stringify!($variant)) { return Some(Self::$variant) }
)*
None
}
}
impl ToString for PreviewFeature {
fn to_string(&self) -> String {
match self {
$(
Self::$variant => decapitalize(stringify!($variant)),
)*
}
}
}
};
}
// (Usually) Append-only list of features.
features!(
ConnectOrCreate,
TransactionApi,
NativeTypes,
GroupBy,
CreateMany,
AtomicNumberOperations,
AggregateApi,
Middlewares,
Distinct,
UncheckedScalarInputs,
MicrosoftSqlServer,
MongoDb,
OrderByRelation,
NApi,
SelectRelationCount,
OrderByAggregateGroup,
FilterJson,
PlanetScaleMode,
);
// Mapping of which active, deprecated and hidden
// features are valid in which place in the datamodel.
/// Generator preview features
pub static GENERATOR: Lazy<FeatureMap> = Lazy::new(|| {
FeatureMap::default()
.with_active(vec![
MicrosoftSqlServer,
OrderByRelation,
NApi,
SelectRelationCount,
OrderByAggregateGroup,
FilterJson,
PlanetScaleMode,
])
.with_hidden(vec![MongoDb])
.with_deprecated(vec![
AtomicNumberOperations,
AggregateApi,
Middlewares,
NativeTypes,
Distinct,
ConnectOrCreate,
TransactionApi,
UncheckedScalarInputs,
GroupBy,
CreateMany,
])
});
/// Datasource preview features.
pub static DATASOURCE: Lazy<FeatureMap> = Lazy::new(FeatureMap::default);
#[derive(Debug, Default)]
pub struct FeatureMap {
/// Valid, visible features.
active: Vec<PreviewFeature>,
/// Deprecated features.
deprecated: Vec<PreviewFeature>,
/// Hidden preview features are valid features, but are not propagated into the tooling
/// (as autocomplete or similar) or into error messages (eg. showing a list of valid features).
hidden: Vec<PreviewFeature>,
}
impl FeatureMap {
pub fn active_features(&self) -> &[PreviewFeature] {
&self.active
}
pub fn hidden_features(&self) -> &[PreviewFeature] {
&self.hidden
}
fn with_active(mut self, active: Vec<PreviewFeature>) -> Self {
self.active = active;
self
}
fn with_hidden(mut self, hidden: Vec<PreviewFeature>) -> Self {
self.hidden = hidden;
self
}
fn with_deprecated(mut self, deprecated: Vec<PreviewFeature>) -> Self {
self.deprecated = deprecated;
self
}
pub fn is_valid(&self, flag: &PreviewFeature) -> bool {
self.active.contains(flag) || self.hidden.contains(flag)
}
pub fn is_deprecated(&self, flag: &PreviewFeature) -> bool {
self.deprecated.contains(flag)
}
}
impl Serialize for PreviewFeature {
fn | <S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
/// Lowercases first character.
/// Assumes 1-byte characters!
pub fn decapitalize(s: &str) -> String {
let first_char = s.chars().next().unwrap();
format!("{}{}", first_char.to_lowercase(), &s[1..])
}
| serialize |
User.js | const { Model, DataTypes } = require('sequelize');
const bcrypt = require('bcrypt');
const sequelize = require('../config/connection');
class User extends Model {
checkPassword(loginPw) {
return bcrypt.compareSync(loginPw, this.password);
}
}
User.init(
{
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true,
},
},
password: {
type: DataTypes.STRING,
allowNull: false,
validate: {
lens: [8],
},
},
is_trainer: { | defaultValue: true
},
},
{
hooks: {
beforeCreate: async (newUserData) => {
newUserData.password = await bcrypt.hash(newUserData.password, 10);
return newUserData;
},
beforeUpdate: async (updateUserData) => {
updateUserData.password = await bcrypt.hash(updateUserData.password, 10);
return updateUserData;
},
},
sequelize,
timestamps: false,
freezeTableName: true,
underscored: true,
modelName: 'user',
}
);
module.exports = User; | type: DataTypes.BOOLEAN, |
test_subscription_with_monitored_items_boolean_string_bytestring.js | /*global require,describe,it,before,beforeEach,after,afterEach*/
"use strict";
const should = require("should");
const sinon = require("sinon");
const subscription_service = require("node-opcua-service-subscription");
const StatusCodes = require("node-opcua-status-code").StatusCodes;
const TimestampsToReturn = require("node-opcua-service-read").TimestampsToReturn;
const MonitoredItemCreateRequest = subscription_service.MonitoredItemCreateRequest;
const DataType = require("node-opcua-variant").DataType;
const DataValue = require("node-opcua-data-value").DataValue;
const Variant = require("node-opcua-variant").Variant;
const VariantArrayType = require("node-opcua-variant").VariantArrayType;
const AttributeIds = require("node-opcua-data-model").AttributeIds;
const NodeId = require("node-opcua-nodeid").NodeId;
const coerceNodeId = require("node-opcua-nodeid").coerceNodeId;
const SessionContext = require("node-opcua-address-space").SessionContext;
const MonitoredItem = require("..").MonitoredItem;
const Subscription = require("..").Subscription;
const ServerEngine = require("..").ServerEngine;
const mini_nodeset_filename = require("node-opcua-address-space").get_mini_nodeset_filename();
const context = SessionContext.defaultContext;
const now = (new Date()).getTime();
const fake_publish_engine = {
pendingPublishRequestCount: 0,
send_notification_message: function () {
},
send_keep_alive_response: function () {
if (this.pendingPublishRequestCount <= 0) {
return false;
}
this.pendingPublishRequestCount -= 1;
return true;
},
on_close_subscription: function (/*subscription*/) {
},
cancelPendingPublishRequestBeforeChannelChange: function() {
}
};
let dataSourceFrozen = false;
function freeze_data_source() {
dataSourceFrozen = true;
}
function unfreeze_data_source() {
dataSourceFrozen = false;
}
function install_spying_samplingFunc() {
unfreeze_data_source();
let sample_value = 0;
const spy_samplingEventCall = sinon.spy(function (oldValue, callback) {
if (!dataSourceFrozen) {
sample_value++;
}
//xx console.log(" OOOOO ----- OOOOOOO");
const dataValue = new DataValue({value: {dataType: DataType.UInt32, value: sample_value}});
callback(null, dataValue);
});
return spy_samplingEventCall;
}
describe("Subscriptions and MonitoredItems", function () {
this.timeout(Math.max(300000, this._timeout));
let addressSpace , namespace;
let engine;
const test = this;
before(function (done) {
engine = new ServerEngine();
engine.initialize({nodeset_filename: mini_nodeset_filename}, function () {
addressSpace = engine.addressSpace;
namespace = addressSpace.getOwnNamespace();
function addVar(typeName, value) {
namespace.addVariable({
organizedBy: "RootFolder",
nodeId: "s=Static_" + typeName,
browseName: "Static_" + typeName,
dataType: typeName,
value: {dataType: DataType[typeName], value: value}
});
}
addVar("LocalizedText", {text: "Hello"});
addVar("ByteString", Buffer.from("AZERTY"));
// addVar("SByte", 0);
// addVar("Int16", 0);
// addVar("Int32", 0);
// addVar("Int64", 0);
// addVar("Byte", 0);
// addVar("UInt16", 0);
// addVar("UInt32", 0);
// addVar("UInt64", 0);
// //xx addVar("Duration" , 0);
// addVar("Float", 0);
// addVar("Double", 0);
addVar("Boolean", false);
addVar("String", "Hello");
done();
});
});
after(function () {
if (engine) {
engine.shutdown();
engine.dispose();
engine = null;
}
});
beforeEach(function () {
this.clock = sinon.useFakeTimers(now);
});
afterEach(function () {
this.clock.restore();
});
it("should return Good if DeadBandFilter is NOT specified on boolean value monitored item", function () {
const subscription = new Subscription({
publishingInterval: 1000,
maxKeepAliveCount: 20,
publishEngine: fake_publish_engine
});
subscription.on("monitoredItem", function (monitoredItem) {
monitoredItem.samplingFunc = install_spying_samplingFunc();
});
function test_with_nodeId(nodeId) {
const monitoredItemCreateRequest = new MonitoredItemCreateRequest({
itemToMonitor: {
nodeId: nodeId,
attributeId: AttributeIds.Value
},
monitoringMode: subscription_service.MonitoringMode.Reporting,
requestedParameters: {
queueSize: 10,
samplingInterval: 100,
filter: new subscription_service.DataChangeFilter({
trigger: subscription_service.DataChangeTrigger.Status,
deadbandType: subscription_service.DeadbandType.None,
})
}
});
const monitoredItemCreateResult = subscription.createMonitoredItem(addressSpace, TimestampsToReturn.Both, monitoredItemCreateRequest);
return monitoredItemCreateResult.statusCode;
}
const namespaceSimulationIndex = 1;
const nodeIdBoolean = coerceNodeId("s=Static_Boolean",namespaceSimulationIndex);
test_with_nodeId(nodeIdBoolean).should.eql(StatusCodes.Good);
subscription.terminate();
subscription.dispose();
});
it("should return Good if DeadBandFilter is NOT specified on String value monitored item", function () {
const subscription = new Subscription({
publishingInterval: 1000,
maxKeepAliveCount: 20,
publishEngine: fake_publish_engine
});
subscription.on("monitoredItem", function (monitoredItem) {
monitoredItem.samplingFunc = install_spying_samplingFunc();
});
function test_with_nodeId(nodeId, statusCode) {
const monitoredItemCreateRequest = new MonitoredItemCreateRequest({
itemToMonitor: {
nodeId: nodeId,
attributeId: AttributeIds.Value
},
monitoringMode: subscription_service.MonitoringMode.Reporting,
requestedParameters: {
queueSize: 10,
samplingInterval: 100,
filter: new subscription_service.DataChangeFilter({
trigger: subscription_service.DataChangeTrigger.Status,
deadbandType: subscription_service.DeadbandType.None,
})
}
});
const monitoredItemCreateResult = subscription.createMonitoredItem(addressSpace, TimestampsToReturn.Both, monitoredItemCreateRequest);
return monitoredItemCreateResult.statusCode;
}
test_with_nodeId("ns=1;s=Static_String").should.eql(StatusCodes.Good);
subscription.terminate();
subscription.dispose();
});
it("should return Good if DeadBandFilter is NOT specified on ByteString value monitored item", function () {
const subscription = new Subscription({
publishingInterval: 1000,
maxKeepAliveCount: 20,
publishEngine: fake_publish_engine
});
subscription.on("monitoredItem", function (monitoredItem) {
monitoredItem.samplingFunc = install_spying_samplingFunc();
});
function test_with_nodeId(nodeId, statusCode) {
const monitoredItemCreateRequest = new MonitoredItemCreateRequest({
itemToMonitor: {
nodeId: nodeId,
attributeId: AttributeIds.Value
},
monitoringMode: subscription_service.MonitoringMode.Reporting,
requestedParameters: {
queueSize: 10,
samplingInterval: 100,
filter: new subscription_service.DataChangeFilter({
trigger: subscription_service.DataChangeTrigger.Status,
deadbandType: subscription_service.DeadbandType.None,
})
}
});
const monitoredItemCreateResult = subscription.createMonitoredItem(addressSpace, TimestampsToReturn.Both, monitoredItemCreateRequest);
return monitoredItemCreateResult.statusCode;
}
test_with_nodeId("ns=1;s=Static_ByteString").should.eql(StatusCodes.Good);
subscription.terminate();
subscription.dispose();
});
it("should return Good if DeadBandFilter is NOT specified on LocalizedText value monitored item", function () {
const subscription = new Subscription({
publishingInterval: 1000,
maxKeepAliveCount: 20,
publishEngine: fake_publish_engine
});
subscription.on("monitoredItem", function (monitoredItem) {
monitoredItem.samplingFunc = install_spying_samplingFunc();
});
function test_with_nodeId(nodeId, statusCode) {
const monitoredItemCreateRequest = new MonitoredItemCreateRequest({
itemToMonitor: {
nodeId: nodeId,
attributeId: AttributeIds.Value
},
monitoringMode: subscription_service.MonitoringMode.Reporting,
requestedParameters: {
queueSize: 10,
samplingInterval: 100,
filter: new subscription_service.DataChangeFilter({
trigger: subscription_service.DataChangeTrigger.Status,
deadbandType: subscription_service.DeadbandType.None,
})
}
});
const monitoredItemCreateResult = subscription.createMonitoredItem(addressSpace, TimestampsToReturn.Both, monitoredItemCreateRequest);
return monitoredItemCreateResult.statusCode;
}
test_with_nodeId("ns=1;s=Static_LocalizedText").should.eql(StatusCodes.Good);
subscription.terminate();
subscription.dispose();
});
it("should return BadFilterNotAllowed if DeadBandFilter is specified on boolean value monitored item", function () {
const subscription = new Subscription({
publishingInterval: 1000,
maxKeepAliveCount: 20,
publishEngine: fake_publish_engine
});
subscription.on("monitoredItem", function (monitoredItem) {
monitoredItem.samplingFunc = install_spying_samplingFunc();
});
function test_with_nodeId(nodeId, statusCode) {
const monitoredItemCreateRequest = new MonitoredItemCreateRequest({
itemToMonitor: {
nodeId: nodeId,
attributeId: AttributeIds.Value
},
monitoringMode: subscription_service.MonitoringMode.Reporting,
requestedParameters: {
queueSize: 10,
samplingInterval: 100,
filter: new subscription_service.DataChangeFilter({
trigger: subscription_service.DataChangeTrigger.Status,
deadbandType: subscription_service.DeadbandType.Percent,
deadbandValue: 10
})
}
});
const monitoredItemCreateResult = subscription.createMonitoredItem(addressSpace, TimestampsToReturn.Both, monitoredItemCreateRequest);
return monitoredItemCreateResult.statusCode;
}
test_with_nodeId("ns=1;s=Static_Boolean").should.eql(StatusCodes.BadFilterNotAllowed);
subscription.terminate();
subscription.dispose();
});
it("should return BadFilterNotAllowed if DeadBandFilter is specified on String value monitored item", function () {
const subscription = new Subscription({
publishingInterval: 1000,
maxKeepAliveCount: 20,
publishEngine: fake_publish_engine
});
subscription.on("monitoredItem", function (monitoredItem) {
monitoredItem.samplingFunc = install_spying_samplingFunc();
});
function test_with_nodeId(nodeId, statusCode) {
const monitoredItemCreateRequest = new MonitoredItemCreateRequest({
itemToMonitor: {
nodeId: nodeId,
attributeId: AttributeIds.Value
},
monitoringMode: subscription_service.MonitoringMode.Reporting,
requestedParameters: {
queueSize: 10,
samplingInterval: 100,
filter: new subscription_service.DataChangeFilter({
trigger: subscription_service.DataChangeTrigger.Status,
deadbandType: subscription_service.DeadbandType.Percent,
deadbandValue: 10
})
}
});
const monitoredItemCreateResult = subscription.createMonitoredItem(addressSpace, TimestampsToReturn.Both, monitoredItemCreateRequest);
return monitoredItemCreateResult.statusCode;
}
test_with_nodeId("ns=1;s=Static_String").should.eql(StatusCodes.BadFilterNotAllowed);
subscription.terminate();
subscription.dispose();
});
it("should return BadFilterNotAllowed if DeadBandFilter is specified on ByteString value monitored item", function () {
const subscription = new Subscription({
publishingInterval: 1000,
maxKeepAliveCount: 20,
publishEngine: fake_publish_engine
});
subscription.on("monitoredItem", function (monitoredItem) {
monitoredItem.samplingFunc = install_spying_samplingFunc();
});
function test_with_nodeId(nodeId, statusCode) {
const monitoredItemCreateRequest = new MonitoredItemCreateRequest({
itemToMonitor: {
nodeId: nodeId,
attributeId: AttributeIds.Value
},
monitoringMode: subscription_service.MonitoringMode.Reporting,
requestedParameters: {
queueSize: 10,
samplingInterval: 100,
filter: new subscription_service.DataChangeFilter({
trigger: subscription_service.DataChangeTrigger.Status,
deadbandType: subscription_service.DeadbandType.Percent,
deadbandValue: 10
})
}
});
const monitoredItemCreateResult = subscription.createMonitoredItem(addressSpace, TimestampsToReturn.Both, monitoredItemCreateRequest);
return monitoredItemCreateResult.statusCode;
}
|
subscription.terminate();
subscription.dispose();
});
it("should return BadFilterNotAllowed if DeadBandFilter is specified on LocalizedText value monitored item", function () {
const subscription = new Subscription({
publishingInterval: 1000,
maxKeepAliveCount: 20,
publishEngine: fake_publish_engine
});
subscription.on("monitoredItem", function (monitoredItem) {
monitoredItem.samplingFunc = install_spying_samplingFunc();
});
function test_with_nodeId(nodeId, statusCode) {
const monitoredItemCreateRequest = new MonitoredItemCreateRequest({
itemToMonitor: {
nodeId: nodeId,
attributeId: AttributeIds.Value
},
monitoringMode: subscription_service.MonitoringMode.Reporting,
requestedParameters: {
queueSize: 10,
samplingInterval: 100,
filter: new subscription_service.DataChangeFilter({
trigger: subscription_service.DataChangeTrigger.Status,
deadbandType: subscription_service.DeadbandType.Percent,
deadbandValue: 10
})
}
});
const monitoredItemCreateResult = subscription.createMonitoredItem(addressSpace, TimestampsToReturn.Both, monitoredItemCreateRequest);
return monitoredItemCreateResult.statusCode;
}
test_with_nodeId("ns=1;s=Static_LocalizedText").should.eql(StatusCodes.BadFilterNotAllowed);
subscription.terminate();
subscription.dispose();
});
}); |
test_with_nodeId("ns=1;s=Static_ByteString").should.eql(StatusCodes.BadFilterNotAllowed); |
minion.py | # -*- coding: utf-8 -*-
'''
Routines to set up a minion
'''
# Import python libs
from __future__ import print_function
import copy
import errno
import fnmatch
import hashlib
import logging
import multiprocessing
import os
import re
import salt
import signal
import sys
import threading
import time
import traceback
import types
from random import randint, shuffle
# Import third party libs
try:
import zmq
HAS_ZMQ = True
except ImportError:
# Running in local, zmq not needed
HAS_ZMQ = False
HAS_RANGE = False
try:
import seco.range
HAS_RANGE = True
except ImportError:
pass
HAS_PSUTIL = False
try:
import psutil
HAS_PSUTIL = True
except ImportError:
pass
HAS_RESOURCE = False
try:
import resource
HAS_RESOURCE = True
except ImportError:
pass
# Import salt libs
from salt.exceptions import (
AuthenticationError, CommandExecutionError, CommandNotFoundError,
SaltInvocationError, SaltReqTimeoutError, SaltClientError,
SaltSystemExit, SaltSyndicMasterError
)
import salt.client
import salt.crypt
import salt.loader
import salt.payload
import salt.utils
import salt.utils.args
import salt.utils.event
import salt.utils.minion
import salt.utils.schedule
import salt.exitcodes
from salt.defaults import DEFAULT_TARGET_DELIM
from salt._compat import string_types
from salt.utils.debug import enable_sigusr1_handler
from salt.utils.event import tagify
import salt.syspaths
log = logging.getLogger(__name__)
# To set up a minion:
# 1. Read in the configuration
# 2. Generate the function mapping dict
# 3. Authenticate with the master
# 4. Store the AES key
# 5. Connect to the publisher
# 6. Handle publications
def resolve_dns(opts):
'''
Resolves the master_ip and master_uri options
'''
ret = {}
check_dns = True
if opts.get('file_client', 'remote') == 'local' and check_dns:
check_dns = False
if check_dns is True:
# Because I import salt.log below I need to re-import salt.utils here
import salt.utils
try:
ret['master_ip'] = \
salt.utils.dns_check(opts['master'], True, opts['ipv6'])
except SaltClientError:
if opts['retry_dns']:
while True:
import salt.log
msg = ('Master hostname: {0} not found. Retrying in {1} '
'seconds').format(opts['master'], opts['retry_dns'])
if salt.log.is_console_configured():
log.warn(msg)
else:
print('WARNING: {0}'.format(msg))
time.sleep(opts['retry_dns'])
try:
ret['master_ip'] = salt.utils.dns_check(
opts['master'], True, opts['ipv6']
)
break
except SaltClientError:
pass
else:
ret['master_ip'] = '127.0.0.1'
except SaltSystemExit:
err = 'Master address: {0} could not be resolved. Invalid or unresolveable address.'.format(
opts.get('master', 'Unknown'))
log.error(err)
raise SaltSystemExit(code=42, msg=err)
else:
ret['master_ip'] = '127.0.0.1'
if 'master_ip' in ret and 'master_ip' in opts:
if ret['master_ip'] != opts['master_ip']:
log.warning('Master ip address changed from {0} to {1}'.format(opts['master_ip'],
ret['master_ip'])
)
ret['master_uri'] = 'tcp://{ip}:{port}'.format(ip=ret['master_ip'],
port=opts['master_port'])
return ret
def get_proc_dir(cachedir):
'''
Given the cache directory, return the directory that process data is
stored in, creating it if it doesn't exist.
'''
fn_ = os.path.join(cachedir, 'proc')
if not os.path.isdir(fn_):
# proc_dir is not present, create it
os.makedirs(fn_)
return fn_
def parse_args_and_kwargs(func, args, data=None):
'''
Wrap load_args_and_kwargs
'''
salt.utils.warn_until(
'Boron',
'salt.minion.parse_args_and_kwargs() has been renamed to '
'salt.minion.load_args_and_kwargs(). Please change this function call '
'before the Boron release of Salt.'
)
return load_args_and_kwargs(func, args, data=data)
def load_args_and_kwargs(func, args, data=None):
'''
Detect the args and kwargs that need to be passed to a function call, and
check them against what was passed.
'''
argspec = salt.utils.get_function_argspec(func)
_args = []
_kwargs = {}
invalid_kwargs = []
for arg in args:
if isinstance(arg, string_types):
string_arg, string_kwarg = salt.utils.args.parse_input([arg], condition=False) # pylint: disable=W0632
if string_arg:
# Don't append the version that was just derived from parse_cli
# above, that would result in a 2nd call to
# salt.utils.cli.yamlify_arg(), which could mangle the input.
_args.append(arg)
elif string_kwarg:
salt.utils.warn_until(
'Boron',
'The list of function args and kwargs should be parsed '
'by salt.utils.args.parse_input() before calling '
'salt.minion.load_args_and_kwargs().'
)
if argspec.keywords or string_kwarg.keys()[0] in argspec.args:
# Function supports **kwargs or is a positional argument to
# the function.
_kwargs.update(string_kwarg)
else:
# **kwargs not in argspec and parsed argument name not in
# list of positional arguments. This keyword argument is
# invalid.
invalid_kwargs.append('{0}'.format(arg))
continue
# if the arg is a dict with __kwarg__ == True, then its a kwarg
elif isinstance(arg, dict) and arg.pop('__kwarg__', False) is True:
for key, val in arg.iteritems():
if argspec.keywords or key in argspec.args:
# Function supports **kwargs or is a positional argument to
# the function.
_kwargs[key] = val
else:
# **kwargs not in argspec and parsed argument name not in
# list of positional arguments. This keyword argument is
# invalid.
invalid_kwargs.append('{0}'.format(arg))
continue
else:
_args.append(arg)
if invalid_kwargs:
raise SaltInvocationError(
'The following keyword arguments are not valid: {0}'
.format(', '.join(invalid_kwargs))
)
if argspec.keywords and isinstance(data, dict):
# this function accepts **kwargs, pack in the publish data
for key, val in data.items():
_kwargs['__pub_{0}'.format(key)] = val
return _args, _kwargs
class SMinion(object):
'''
Create an object that has loaded all of the minion module functions,
grains, modules, returners etc. The SMinion allows developers to
generate all of the salt minion functions and present them with these
functions for general use.
'''
def __init__(self, opts):
# Late setup of the opts grains, so we can log from the grains module
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
# Clean out the proc directory (default /var/cache/salt/minion/proc)
if self.opts.get('file_client', 'remote') == 'remote':
if isinstance(self.opts['master'], list):
masters = self.opts['master']
if self.opts['random_master'] is True:
shuffle(masters)
for master in masters:
self.opts['master'] = master
self.opts.update(resolve_dns(opts))
try:
self.gen_modules()
break
except SaltClientError:
log.warning(('Attempted to authenticate with master '
'{0} and failed'.format(master)))
continue
else:
if self.opts['random_master'] is True:
log.warning('random_master is True but there is only one master specified. Ignoring.')
self.opts.update(resolve_dns(opts))
self.gen_modules()
else:
self.gen_modules()
def gen_modules(self):
'''
Load all of the modules for the minion
'''
self.opts['pillar'] = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['environment'],
).compile_pillar()
self.functions = salt.loader.minion_mods(self.opts)
self.returners = salt.loader.returners(self.opts, self.functions)
self.states = salt.loader.states(self.opts, self.functions)
self.rend = salt.loader.render(self.opts, self.functions)
self.matcher = Matcher(self.opts, self.functions)
self.functions['sys.reload_modules'] = self.gen_modules
class MinionBase(object):
def __init__(self, opts):
self.opts = opts
def _init_context_and_poller(self):
self.context = zmq.Context()
self.poller = zmq.Poller()
def _prepare_minion_event_system(self):
# Prepare the minion event system
#
# Start with the publish socket
self._init_context_and_poller()
hash_type = getattr(hashlib, self.opts.get('hash_type', 'md5'))
# Only use the first 10 chars to keep longer hashes from exceeding the
# max socket path length.
id_hash = hash_type(self.opts['id']).hexdigest()[:10]
epub_sock_path = os.path.join(
self.opts['sock_dir'],
'minion_event_{0}_pub.ipc'.format(id_hash)
)
if os.path.exists(epub_sock_path):
os.unlink(epub_sock_path)
epull_sock_path = os.path.join(
self.opts['sock_dir'],
'minion_event_{0}_pull.ipc'.format(id_hash)
)
if os.path.exists(epull_sock_path):
os.unlink(epull_sock_path)
self.epub_sock = self.context.socket(zmq.PUB)
if self.opts.get('ipc_mode', '') == 'tcp':
epub_uri = 'tcp://127.0.0.1:{0}'.format(
self.opts['tcp_pub_port']
)
epull_uri = 'tcp://127.0.0.1:{0}'.format(
self.opts['tcp_pull_port']
)
else:
epub_uri = 'ipc://{0}'.format(epub_sock_path)
salt.utils.check_ipc_path_max_len(epub_uri)
epull_uri = 'ipc://{0}'.format(epull_sock_path)
salt.utils.check_ipc_path_max_len(epull_uri)
log.debug(
'{0} PUB socket URI: {1}'.format(
self.__class__.__name__, epub_uri
)
)
log.debug(
'{0} PULL socket URI: {1}'.format(
self.__class__.__name__, epull_uri
)
)
# Check to make sure the sock_dir is available, create if not
default_minion_sock_dir = os.path.join(
salt.syspaths.SOCK_DIR,
'minion'
)
minion_sock_dir = self.opts.get('sock_dir', default_minion_sock_dir)
if not os.path.isdir(minion_sock_dir):
# Let's try to create the directory defined on the configuration
# file
try:
os.makedirs(minion_sock_dir, 0755)
except OSError as exc:
log.error('Could not create SOCK_DIR: {0}'.format(exc))
# Let's not fail yet and try using the default path
if minion_sock_dir == default_minion_sock_dir:
# We're already trying the default system path, stop now!
raise
if not os.path.isdir(default_minion_sock_dir):
try:
os.makedirs(default_minion_sock_dir, 0755)
except OSError as exc:
log.error('Could not create SOCK_DIR: {0}'.format(exc))
# Let's stop at this stage
raise
# Create the pull socket
self.epull_sock = self.context.socket(zmq.PULL)
# Securely bind the event sockets
if self.opts.get('ipc_mode', '') != 'tcp':
old_umask = os.umask(0177)
try:
log.info('Starting pub socket on {0}'.format(epub_uri))
self.epub_sock.bind(epub_uri)
log.info('Starting pull socket on {0}'.format(epull_uri))
self.epull_sock.bind(epull_uri)
finally:
if self.opts.get('ipc_mode', '') != 'tcp':
os.umask(old_umask)
@staticmethod
def process_schedule(minion, loop_interval):
try:
minion.schedule.eval()
# Check if scheduler requires lower loop interval than
# the loop_interval setting
if minion.schedule.loop_interval < loop_interval:
loop_interval = minion.schedule.loop_interval
log.debug(
'Overriding loop_interval because of scheduled jobs.'
)
except Exception as exc:
log.error(
'Exception {0} occurred in scheduled job'.format(exc)
)
return loop_interval
class MasterMinion(object):
'''
Create a fully loaded minion function object for generic use on the
master. What makes this class different is that the pillar is
omitted, otherwise everything else is loaded cleanly.
'''
def __init__(
self,
opts,
returners=True,
states=True,
rend=True,
matcher=True,
whitelist=None):
self.opts = salt.config.minion_config(opts['conf_file'])
self.opts.update(opts)
self.whitelist = whitelist
self.opts['grains'] = salt.loader.grains(opts)
self.opts['pillar'] = {}
self.mk_returners = returners
self.mk_states = states
self.mk_rend = rend
self.mk_matcher = matcher
self.gen_modules()
def gen_modules(self):
'''
Load all of the modules for the minion
'''
self.functions = salt.loader.minion_mods(
self.opts,
whitelist=self.whitelist)
if self.mk_returners:
self.returners = salt.loader.returners(self.opts, self.functions)
if self.mk_states:
self.states = salt.loader.states(self.opts, self.functions)
if self.mk_rend:
self.rend = salt.loader.render(self.opts, self.functions)
if self.mk_matcher:
self.matcher = Matcher(self.opts, self.functions)
self.functions['sys.reload_modules'] = self.gen_modules
class MultiMinion(MinionBase):
'''
Create a multi minion interface, this creates as many minions as are
defined in the master option and binds each minion object to a respective
master.
'''
# timeout for one of the minions to auth with a master
MINION_CONNECT_TIMEOUT = 5
def __init__(self, opts):
super(MultiMinion, self).__init__(opts)
def minions(self):
'''
Return a dict of minion generators bound to the tune_in method
dict of master -> minion_mapping, the mapping contains:
opts: options used to create the minion
last: last auth attempt time
auth_wait: time to wait for next auth attempt
minion: minion object
generator: generator function (non-blocking tune_in)
'''
if not isinstance(self.opts['master'], list):
log.error(
'Attempting to start a multimaster system with one master')
sys.exit(salt.exitcodes.EX_GENERIC)
ret = {}
for master in set(self.opts['master']):
s_opts = copy.copy(self.opts)
s_opts['master'] = master
ret[master] = {'opts': s_opts,
'last': time.time(),
'auth_wait': s_opts['acceptance_wait_time']}
try:
minion = Minion(s_opts, self.MINION_CONNECT_TIMEOUT, False)
ret[master]['minion'] = minion
ret[master]['generator'] = minion.tune_in_no_block()
except SaltClientError as exc:
log.error('Error while bringing up minion for multi-master. Is master at {0} responding?'.format(master))
return ret
# Multi Master Tune In
def tune_in(self):
'''
Bind to the masters
This loop will attempt to create connections to masters it hasn't connected
to yet, but once the initial connection is made it is up to ZMQ to do the
reconnect (don't know of an API to get the state here in salt)
'''
self._prepare_minion_event_system()
self.poller.register(self.epull_sock, zmq.POLLIN)
# Prepare the minion generators
minions = self.minions()
loop_interval = int(self.opts['loop_interval'])
auth_wait = self.opts['acceptance_wait_time']
max_wait = self.opts['acceptance_wait_time_max']
while True:
package = None
socks = dict(self.poller.poll(1))
if socks.get(self.epull_sock) == zmq.POLLIN:
try:
package = self.epull_sock.recv(zmq.NOBLOCK)
except Exception:
pass
masters = minions.keys()
shuffle(masters)
# Do stuff per minion that we have
for master in masters:
minion = minions[master]
# if we haven't connected yet, lets attempt some more.
# make sure to keep separate auth_wait times, since these
# are separate masters
if 'generator' not in minion:
if time.time() - minion['auth_wait'] > minion['last']:
minion['last'] = time.time()
if minion['auth_wait'] < max_wait:
minion['auth_wait'] += auth_wait
try:
t_minion = Minion(minion['opts'], self.MINION_CONNECT_TIMEOUT, False)
minions[master]['minion'] = t_minion
minions[master]['generator'] = t_minion.tune_in_no_block()
minions[master]['auth_wait'] = self.opts['acceptance_wait_time']
except SaltClientError:
log.error('Error while bring up minion for multi-master. Is master {0} responding?'.format(master))
continue
else:
continue
# run scheduled jobs if you have them
loop_interval = self.process_schedule(minion['minion'], loop_interval)
# if you have an event to handle, do it on a single minion
# (first one to not throw an exception)
if package:
try:
minion['minion'].handle_event(package)
package = None
self.epub_sock.send(package)
except Exception:
pass
# have the Minion class run anything it has to run
minion['generator'].next()
class Minion(MinionBase):
'''
This class instantiates a minion, runs connections for a minion,
and loads all of the functions into the minion
'''
def __init__(self, opts, timeout=60, safe=True): # pylint: disable=W0231
'''
Pass in the options dict
'''
self._running = None
# Warn if ZMQ < 3.2
if HAS_ZMQ:
try:
zmq_version_info = zmq.zmq_version_info()
except AttributeError:
# PyZMQ <= 2.1.9 does not have zmq_version_info, fall back to
# using zmq.zmq_version() and build a version info tuple.
zmq_version_info = tuple(
[int(x) for x in zmq.zmq_version().split('.')]
)
if zmq_version_info < (3, 2):
log.warning(
'You have a version of ZMQ less than ZMQ 3.2! There are '
'known connection keep-alive issues with ZMQ < 3.2 which '
'may result in loss of contact with minions. Please '
'upgrade your ZMQ!'
)
# Late setup the of the opts grains, so we can log from the grains
# module
opts['grains'] = salt.loader.grains(opts)
# evaluate the master to connect to and authenticate with it
opts['master'] = self.eval_master(opts,
timeout,
safe)
self.opts['pillar'] = salt.pillar.get_pillar(
opts,
opts['grains'],
opts['id'],
opts['environment'],
).compile_pillar()
self.serial = salt.payload.Serial(self.opts)
self.mod_opts = self._prep_mod_opts()
self.functions, self.returners = self._load_modules()
self.matcher = Matcher(self.opts, self.functions)
self.proc_dir = get_proc_dir(opts['cachedir'])
self.schedule = salt.utils.schedule.Schedule(
self.opts,
self.functions,
self.returners)
# add default scheduling jobs to the minions scheduler
self.schedule.add_job({
'__mine_interval':
{
'function': 'mine.update',
'minutes': opts['mine_interval'],
'jid_include': True,
'maxrunning': 2
}
})
# add master_alive job if enabled | if self.opts['master_alive_interval'] > 0:
self.schedule.add_job({
'__master_alive':
{
'function': 'status.master',
'seconds': opts['master_alive_interval'],
'jid_include': True,
'maxrunning': 1,
'kwargs': {'master_ip': self.opts['master'],
'connected': True}
}
})
self.grains_cache = self.opts['grains']
# store your hexid to subscribe to zmq, hash since zmq filters are prefix
# matches this way we can avoid collisions
self.hexid = hashlib.sha1(self.opts['id']).hexdigest()
if 'proxy' in self.opts['pillar']:
log.debug('I am {0} and I need to start some proxies for {1}'.format(self.opts['id'],
self.opts['pillar']['proxy']))
for p in self.opts['pillar']['proxy']:
log.debug('Starting {0} proxy.'.format(p))
pid = os.fork()
if pid > 0:
continue
else:
proxyminion = salt.ProxyMinion()
proxyminion.start(self.opts['pillar']['proxy'][p])
self.clean_die(signal.SIGTERM, None)
else:
log.debug('I am {0} and I am not supposed to start any proxies. '
'(Likely not a problem)'.format(self.opts['id']))
# __init__() from MinionBase is called in Minion.eval_master()
def eval_master(self,
opts,
timeout=60,
safe=True,
failed=False):
'''
Evaluates and returns the current master address. In standard mode, just calls
authenticate() with the given master address.
With master_type=func evaluates the current master address from the given
module and then calls authenticate().
With master_type=failover takes the list of masters and loops through them.
The first one that allows the minion to connect is used to authenticate() and
then returned. If this function is called outside the minions initialization
phase (for example from the minions main event-loop when a master connection
loss was detected), 'failed' should be set to True. The current
(possibly failed) master will then be removed from the list of masters.
'''
# check if master_type was altered from its default
if opts['master_type'] != 'str':
# check for a valid keyword
if opts['master_type'] == 'func':
# split module and function and try loading the module
mod, fun = opts['master'].split('.')
try:
master_mod = salt.loader.raw_mod(opts, mod, fun)
if not master_mod:
raise TypeError
# we take whatever the module returns as master address
opts['master'] = master_mod[mod + '.' + fun]()
except TypeError:
msg = ('Failed to evaluate master address from '
'module \'{0}\''.format(opts['master']))
log.error(msg)
sys.exit(salt.exitcodes.EX_GENERIC)
log.info('Evaluated master from module: {0}'.format(master_mod))
# if failover is set, master has to be of type list
elif opts['master_type'] == 'failover':
if isinstance(opts['master'], list):
log.info('Got list of available master addresses:'
' {0}'.format(opts['master']))
if opts['master_shuffle']:
shuffle(opts['master'])
# if failed=True, the minion was previously connected
# we're probably called from the minions main-event-loop
# because a master connection loss was detected. remove
# the possibly failed master from the list of masters.
elif failed:
log.info('Removing possibly failed master {0} from list of'
' masters'.format(opts['master']))
# create new list of master with the possibly failed one removed
opts['master'] = [x for x in opts['master_list'] if opts['master'] != x]
else:
msg = ('master_type set to \'failover\' but \'master\' '
'is not of type list but of type '
'{0}'.format(type(opts['master'])))
log.error(msg)
sys.exit(salt.exitcodes.EX_GENERIC)
else:
msg = ('Invalid keyword \'{0}\' for variable '
'\'master_type\''.format(opts['master_type']))
log.error(msg)
sys.exit(salt.exitcodes.EX_GENERIC)
# if we have a list of masters, loop through them and be
# happy with the first one that allows us to connect
if isinstance(opts['master'], list):
conn = False
# shuffle the masters and then loop through them
local_masters = copy.copy(opts['master'])
for master in local_masters:
opts['master'] = master
opts.update(resolve_dns(opts))
super(Minion, self).__init__(opts)
# on first run, update self.opts with the whole master list
# to enable a minion to re-use old masters if they get fixed
if 'master_list' not in self.opts:
self.opts['master_list'] = local_masters
try:
if self.authenticate(timeout, safe) != 'full':
conn = True
break
except SaltClientError:
msg = ('Master {0} could not be reached, trying '
'next master (if any)'.format(opts['master']))
log.info(msg)
continue
if not conn:
self.connected = False
msg = ('No master could be reached or all masters denied '
'the minions connection attempt.')
log.error(msg)
else:
self.connected = True
return opts['master']
# single master sign in
else:
opts.update(resolve_dns(opts))
super(Minion, self).__init__(opts)
if self.authenticate(timeout, safe) == 'full':
self.connected = False
msg = ('master {0} rejected the minions connection because too '
'many minions are already connected.'.format(opts['master']))
log.error(msg)
sys.exit(salt.exitcodes.EX_GENERIC)
else:
self.connected = True
return opts['master']
def _prep_mod_opts(self):
'''
Returns a copy of the opts with key bits stripped out
'''
mod_opts = {}
for key, val in self.opts.items():
if key == 'logger':
continue
mod_opts[key] = val
return mod_opts
def _load_modules(self, force_refresh=False):
'''
Return the functions and the returners loaded up from the loader
module
'''
# if this is a *nix system AND modules_max_memory is set, lets enforce
# a memory limit on module imports
# this feature ONLY works on *nix like OSs (resource module doesn't work on windows)
modules_max_memory = False
if self.opts.get('modules_max_memory', -1) > 0 and HAS_PSUTIL and HAS_RESOURCE:
log.debug('modules_max_memory set, enforcing a maximum of {0}'.format(self.opts['modules_max_memory']))
modules_max_memory = True
old_mem_limit = resource.getrlimit(resource.RLIMIT_AS)
rss, vms = psutil.Process(os.getpid()).get_memory_info()
mem_limit = rss + vms + self.opts['modules_max_memory']
resource.setrlimit(resource.RLIMIT_AS, (mem_limit, mem_limit))
elif self.opts.get('modules_max_memory', -1) > 0:
if not HAS_PSUTIL:
log.error('Unable to enforce modules_max_memory because psutil is missing')
if not HAS_RESOURCE:
log.error('Unable to enforce modules_max_memory because resource is missing')
self.opts['grains'] = salt.loader.grains(self.opts, force_refresh)
functions = salt.loader.minion_mods(self.opts)
returners = salt.loader.returners(self.opts, functions)
# we're done, reset the limits!
if modules_max_memory is True:
resource.setrlimit(resource.RLIMIT_AS, old_mem_limit)
return functions, returners
def _fire_master(self, data=None, tag=None, events=None, pretag=None):
'''
Fire an event on the master, or drop message if unable to send.
'''
load = {'id': self.opts['id'],
'cmd': '_minion_event',
'pretag': pretag,
'tok': self.tok}
if events:
load['events'] = events
elif data and tag:
load['data'] = data
load['tag'] = tag
elif not data and tag:
load['data'] = {}
load['tag'] = tag
else:
return
channel = salt.transport.Channel.factory(self.opts)
try:
result = channel.send(load)
except AuthenticationError:
log.info("AES key changed, re-authenticating")
self.authenticate()
except SaltReqTimeoutError:
log.info("Master failed to respond. Preforming re-authenticating")
self.authenticate()
except Exception:
log.info("fire_master failed: {0}".format(traceback.format_exc()))
def _handle_payload(self, payload):
'''
Takes a payload from the master publisher and does whatever the
master wants done.
'''
{'aes': self._handle_aes,
'pub': self._handle_pub,
'clear': self._handle_clear}[payload['enc']](payload['load'],
payload['sig'] if 'sig' in payload else None)
def _handle_aes(self, load, sig=None):
'''
Takes the AES encrypted load, checks the signature if pub signatures
are turned on, decrypts it, and runs the encapsulated instructions
'''
# Verify that the signature is valid
master_pubkey_path = os.path.join(self.opts['pki_dir'], 'minion_master.pub')
if sig and self.functions['config.get']('sign_pub_messages'):
if not salt.crypt.verify_signature(master_pubkey_path, load, sig):
raise AuthenticationError('Message signature failed to validate.')
try:
data = self.crypticle.loads(load)
except AuthenticationError:
# decryption of the payload failed, try to re-auth but wait
# random seconds if set in config with random_reauth_delay
if 'random_reauth_delay' in self.opts:
reauth_delay = randint(0, float(self.opts['random_reauth_delay']))
# This mitigates the issue wherein a long-running job might not return
# on a master key rotation. However, new commands issued during the re-auth
# splay period will still fail to return.
if not salt.utils.minion.running(self.opts):
log.debug('Waiting {0} seconds to re-authenticate'.format(reauth_delay))
time.sleep(reauth_delay)
else:
log.warning('Ignoring re-auth delay because jobs are running')
self.authenticate()
data = self.crypticle.loads(load)
# Verify that the publication is valid
if 'tgt' not in data or 'jid' not in data or 'fun' not in data \
or 'arg' not in data:
return
# Verify that the publication applies to this minion
# It's important to note that the master does some pre-processing
# to determine which minions to send a request to. So for example,
# a "salt -G 'grain_key:grain_val' test.ping" will invoke some
# pre-processing on the master and this minion should not see the
# publication if the master does not determine that it should.
if 'tgt_type' in data:
match_func = getattr(self.matcher,
'{0}_match'.format(data['tgt_type']), None)
if match_func is None:
return
if data['tgt_type'] in ('grain', 'grain_pcre', 'pillar'):
delimiter = data.get('delimiter', DEFAULT_TARGET_DELIM)
if not match_func(data['tgt'], delimiter=delimiter):
return
elif not match_func(data['tgt']):
return
else:
if not self.matcher.glob_match(data['tgt']):
return
# If the minion does not have the function, don't execute,
# this prevents minions that could not load a minion module
# from returning a predictable exception
#if data['fun'] not in self.functions:
# return
if 'user' in data:
log.info(
'User {0[user]} Executing command {0[fun]} with jid '
'{0[jid]}'.format(data)
)
else:
log.info(
'Executing command {0[fun]} with jid {0[jid]}'.format(data)
)
log.debug('Command details {0}'.format(data))
self._handle_decoded_payload(data)
def _handle_pub(self, load):
'''
Handle public key payloads
'''
pass
def _handle_clear(self, load):
'''
Handle un-encrypted transmissions
'''
pass
def _handle_decoded_payload(self, data):
'''
Override this method if you wish to handle the decoded data
differently.
'''
if isinstance(data['fun'], string_types):
if data['fun'] == 'sys.reload_modules':
self.functions, self.returners = self._load_modules()
self.schedule.functions = self.functions
self.schedule.returners = self.returners
if isinstance(data['fun'], tuple) or isinstance(data['fun'], list):
target = Minion._thread_multi_return
else:
target = Minion._thread_return
# We stash an instance references to allow for the socket
# communication in Windows. You can't pickle functions, and thus
# python needs to be able to reconstruct the reference on the other
# side.
instance = self
if self.opts['multiprocessing']:
if sys.platform.startswith('win'):
# let python reconstruct the minion on the other side if we're
# running on windows
instance = None
process = multiprocessing.Process(
target=target, args=(instance, self.opts, data)
)
else:
process = threading.Thread(
target=target, args=(instance, self.opts, data),
name=data['jid']
)
process.start()
if not sys.platform.startswith('win'):
process.join()
@classmethod
def _thread_return(cls, minion_instance, opts, data):
'''
This method should be used as a threading target, start the actual
minion side execution.
'''
# this seems awkward at first, but it's a workaround for Windows
# multiprocessing communication.
if not minion_instance:
minion_instance = cls(opts)
fn_ = os.path.join(minion_instance.proc_dir, data['jid'])
if opts['multiprocessing']:
salt.utils.daemonize_if(opts)
salt.utils.appendproctitle(data['jid'])
sdata = {'pid': os.getpid()}
sdata.update(data)
log.info('Starting a new job with PID {0}'.format(sdata['pid']))
with salt.utils.fopen(fn_, 'w+b') as fp_:
fp_.write(minion_instance.serial.dumps(sdata))
ret = {'success': False}
function_name = data['fun']
if function_name in minion_instance.functions:
try:
func = minion_instance.functions[data['fun']]
args, kwargs = load_args_and_kwargs(
func,
data['arg'],
data)
sys.modules[func.__module__].__context__['retcode'] = 0
return_data = func(*args, **kwargs)
if isinstance(return_data, types.GeneratorType):
ind = 0
iret = {}
for single in return_data:
if isinstance(single, dict) and isinstance(iret, dict):
iret.update(single)
else:
if not iret:
iret = []
iret.append(single)
tag = tagify([data['jid'], 'prog', opts['id'], str(ind)], 'job')
event_data = {'return': single}
minion_instance._fire_master(event_data, tag)
ind += 1
ret['return'] = iret
else:
ret['return'] = return_data
ret['retcode'] = sys.modules[func.__module__].__context__.get(
'retcode',
0
)
ret['success'] = True
except CommandNotFoundError as exc:
msg = 'Command required for {0!r} not found'.format(
function_name
)
log.debug(msg, exc_info=True)
ret['return'] = '{0}: {1}'.format(msg, exc)
ret['out'] = 'nested'
except CommandExecutionError as exc:
log.error(
'A command in {0!r} had a problem: {1}'.format(
function_name,
exc
),
exc_info_on_loglevel=logging.DEBUG
)
ret['return'] = 'ERROR: {0}'.format(exc)
ret['out'] = 'nested'
except SaltInvocationError as exc:
log.error(
'Problem executing {0!r}: {1}'.format(
function_name,
exc
),
exc_info_on_loglevel=logging.DEBUG
)
ret['return'] = 'ERROR executing {0!r}: {1}'.format(
function_name, exc
)
ret['out'] = 'nested'
except TypeError as exc:
trb = traceback.format_exc()
aspec = salt.utils.get_function_argspec(
minion_instance.functions[data['fun']]
)
msg = ('TypeError encountered executing {0}: {1}. See '
'debug log for more info. Possibly a missing '
'arguments issue: {2}').format(function_name,
exc,
aspec)
log.warning(msg, exc_info_on_loglevel=logging.DEBUG)
ret['return'] = msg
ret['out'] = 'nested'
except Exception:
msg = 'The minion function caused an exception'
log.warning(msg, exc_info_on_loglevel=logging.DEBUG)
ret['return'] = '{0}: {1}'.format(msg, traceback.format_exc())
ret['out'] = 'nested'
else:
ret['return'] = '{0!r} is not available.'.format(function_name)
ret['out'] = 'nested'
ret['jid'] = data['jid']
ret['fun'] = data['fun']
ret['fun_args'] = data['arg']
if 'master_id' in data:
ret['master_id'] = data['master_id']
minion_instance._return_pub(ret)
if data['ret']:
if 'ret_config' in data:
ret['ret_config'] = data['ret_config']
ret['id'] = opts['id']
for returner in set(data['ret'].split(',')):
try:
minion_instance.returners['{0}.returner'.format(
returner
)](ret)
except Exception as exc:
log.error(
'The return failed for job {0} {1}'.format(
data['jid'],
exc
)
)
log.error(traceback.format_exc())
@classmethod
def _thread_multi_return(cls, minion_instance, opts, data):
'''
This method should be used as a threading target, start the actual
minion side execution.
'''
salt.utils.appendproctitle(data['jid'])
# this seems awkward at first, but it's a workaround for Windows
# multiprocessing communication.
if not minion_instance:
minion_instance = cls(opts)
ret = {
'return': {},
'success': {},
}
for ind in range(0, len(data['fun'])):
ret['success'][data['fun'][ind]] = False
try:
func = minion_instance.functions[data['fun'][ind]]
args, kwargs = load_args_and_kwargs(
func,
data['arg'][ind],
data)
ret['return'][data['fun'][ind]] = func(*args, **kwargs)
ret['success'][data['fun'][ind]] = True
except Exception as exc:
trb = traceback.format_exc()
log.warning(
'The minion function caused an exception: {0}'.format(
exc
)
)
ret['return'][data['fun'][ind]] = trb
ret['jid'] = data['jid']
ret['fun'] = data['fun']
ret['fun_args'] = data['arg']
minion_instance._return_pub(ret)
if data['ret']:
if 'ret_config' in data:
ret['ret_config'] = data['ret_config']
for returner in set(data['ret'].split(',')):
ret['id'] = opts['id']
try:
minion_instance.returners['{0}.returner'.format(
returner
)](ret)
except Exception as exc:
log.error(
'The return failed for job {0} {1}'.format(
data['jid'],
exc
)
)
def _return_pub(self, ret, ret_cmd='_return'):
'''
Return the data from the executed command to the master server
'''
jid = ret.get('jid', ret.get('__jid__'))
fun = ret.get('fun', ret.get('__fun__'))
if self.opts['multiprocessing']:
fn_ = os.path.join(self.proc_dir, jid)
if os.path.isfile(fn_):
try:
os.remove(fn_)
except (OSError, IOError):
# The file is gone already
pass
log.info('Returning information for job: {0}'.format(jid))
channel = salt.transport.Channel.factory(self.opts)
if ret_cmd == '_syndic_return':
load = {'cmd': ret_cmd,
'id': self.opts['id'],
'jid': jid,
'fun': fun,
'load': ret.get('__load__')}
load['return'] = {}
for key, value in ret.items():
if key.startswith('__'):
continue
load['return'][key] = value
else:
load = {'cmd': ret_cmd,
'id': self.opts['id']}
for key, value in ret.items():
load[key] = value
if 'out' in ret:
if isinstance(ret['out'], string_types):
load['out'] = ret['out']
else:
log.error('Invalid outputter {0}. This is likely a bug.'
.format(ret['out']))
else:
try:
oput = self.functions[fun].__outputter__
except (KeyError, AttributeError, TypeError):
pass
else:
if isinstance(oput, string_types):
load['out'] = oput
if self.opts['cache_jobs']:
# Local job cache has been enabled
fn_ = os.path.join(
self.opts['cachedir'],
'minion_jobs',
load['jid'],
'return.p')
jdir = os.path.dirname(fn_)
if not os.path.isdir(jdir):
os.makedirs(jdir)
salt.utils.fopen(fn_, 'w+b').write(self.serial.dumps(ret))
try:
ret_val = channel.send(load)
except SaltReqTimeoutError:
msg = ('The minion failed to return the job information for job '
'{0}. This is often due to the master being shut down or '
'overloaded. If the master is running consider increasing '
'the worker_threads value.').format(jid)
log.warn(msg)
return ''
log.trace('ret_val = {0}'.format(ret_val))
return ret_val
def _state_run(self):
'''
Execute a state run based on information set in the minion config file
'''
if self.opts['startup_states']:
data = {'jid': 'req', 'ret': self.opts.get('ext_job_cache', '')}
if self.opts['startup_states'] == 'sls':
data['fun'] = 'state.sls'
data['arg'] = [self.opts['sls_list']]
elif self.opts['startup_states'] == 'top':
data['fun'] = 'state.top'
data['arg'] = [self.opts['top_file']]
else:
data['fun'] = 'state.highstate'
data['arg'] = []
self._handle_decoded_payload(data)
def _refresh_grains_watcher(self, refresh_interval_in_minutes):
'''
Create a loop that will fire a pillar refresh to inform a master about a change in the grains of this minion
:param refresh_interval_in_minutes:
:return: None
'''
if '__update_grains' not in self.opts.get('schedule', {}):
if 'schedule' not in self.opts:
self.opts['schedule'] = {}
self.opts['schedule'].update({
'__update_grains':
{
'function': 'event.fire',
'args': [{}, 'grains_refresh'],
'minutes': refresh_interval_in_minutes
}
})
def _set_tcp_keepalive(self):
if hasattr(zmq, 'TCP_KEEPALIVE'):
self.socket.setsockopt(
zmq.TCP_KEEPALIVE, self.opts['tcp_keepalive']
)
self.socket.setsockopt(
zmq.TCP_KEEPALIVE_IDLE, self.opts['tcp_keepalive_idle']
)
self.socket.setsockopt(
zmq.TCP_KEEPALIVE_CNT, self.opts['tcp_keepalive_cnt']
)
self.socket.setsockopt(
zmq.TCP_KEEPALIVE_INTVL, self.opts['tcp_keepalive_intvl']
)
def _set_reconnect_ivl(self):
recon_delay = self.opts['recon_default']
if self.opts['recon_randomize']:
recon_delay = randint(self.opts['recon_default'],
self.opts['recon_default'] + self.opts['recon_max']
)
log.debug("Generated random reconnect delay between '{0}ms' and '{1}ms' ({2})".format(
self.opts['recon_default'],
self.opts['recon_default'] + self.opts['recon_max'],
recon_delay)
)
log.debug("Setting zmq_reconnect_ivl to '{0}ms'".format(recon_delay))
self.socket.setsockopt(zmq.RECONNECT_IVL, recon_delay)
def _set_reconnect_ivl_max(self):
if hasattr(zmq, 'RECONNECT_IVL_MAX'):
log.debug("Setting zmq_reconnect_ivl_max to '{0}ms'".format(
self.opts['recon_default'] + self.opts['recon_max'])
)
self.socket.setsockopt(
zmq.RECONNECT_IVL_MAX, self.opts['recon_max']
)
def _set_ipv4only(self):
if self.opts['ipv6'] is True and hasattr(zmq, 'IPV4ONLY'):
# IPv6 sockets work for both IPv6 and IPv4 addresses
self.socket.setsockopt(zmq.IPV4ONLY, 0)
def _fire_master_minion_start(self):
# Send an event to the master that the minion is live
self._fire_master(
'Minion {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
'minion_start'
)
# dup name spaced event
self._fire_master(
'Minion {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
tagify([self.opts['id'], 'start'], 'minion'),
)
def _setsockopts(self):
if self.opts['zmq_filtering']:
# TODO: constants file for "broadcast"
self.socket.setsockopt(zmq.SUBSCRIBE, 'broadcast')
self.socket.setsockopt(zmq.SUBSCRIBE, self.hexid)
else:
self.socket.setsockopt(zmq.SUBSCRIBE, '')
self.socket.setsockopt(zmq.IDENTITY, self.opts['id'])
self._set_ipv4only()
self._set_reconnect_ivl_max()
self._set_tcp_keepalive()
@property
def master_pub(self):
'''
Return the master publish port
'''
return 'tcp://{ip}:{port}'.format(ip=self.opts['master_ip'],
port=self.publish_port)
def authenticate(self, timeout=60, safe=True):
'''
Authenticate with the master, this method breaks the functional
paradigm, it will update the master information from a fresh sign
in, signing in can occur as often as needed to keep up with the
revolving master AES key.
'''
log.debug(
'Attempting to authenticate with the Salt Master at {0}'.format(
self.opts['master_ip']
)
)
auth = salt.crypt.Auth(self.opts)
self.tok = auth.gen_token('salt')
acceptance_wait_time = self.opts['acceptance_wait_time']
acceptance_wait_time_max = self.opts['acceptance_wait_time_max']
if not acceptance_wait_time_max:
acceptance_wait_time_max = acceptance_wait_time
while True:
creds = auth.sign_in(timeout, safe)
if creds == 'full':
return creds
elif creds != 'retry':
log.info('Authentication with master at {0} successful!'.format(self.opts['master_ip']))
break
log.info('Waiting for minion key to be accepted by the master.')
if acceptance_wait_time:
log.info('Waiting {0} seconds before retry.'.format(acceptance_wait_time))
time.sleep(acceptance_wait_time)
if acceptance_wait_time < acceptance_wait_time_max:
acceptance_wait_time += acceptance_wait_time
log.debug('Authentication wait time is {0}'.format(acceptance_wait_time))
self.aes = creds['aes']
if self.opts.get('syndic_master_publish_port'):
self.publish_port = self.opts.get('syndic_master_publish_port')
else:
self.publish_port = creds['publish_port']
self.crypticle = salt.crypt.Crypticle(self.opts, self.aes)
def module_refresh(self, force_refresh=False):
'''
Refresh the functions and returners.
'''
self.functions, self.returners = self._load_modules(force_refresh)
self.schedule.functions = self.functions
self.schedule.returners = self.returners
def pillar_refresh(self, force_refresh=False):
'''
Refresh the pillar
'''
self.opts['pillar'] = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['environment'],
).compile_pillar()
self.module_refresh(force_refresh)
def manage_schedule(self, package):
'''
Refresh the functions and returners.
'''
tag, data = salt.utils.event.MinionEvent.unpack(package)
func = data.get('func', None)
name = data.get('name', None)
schedule = data.get('schedule', None)
where = data.get('where', None)
if func == 'delete':
self.schedule.delete_job(name)
elif func == 'add':
self.schedule.add_job(schedule)
elif func == 'modify':
self.schedule.modify_job(name, schedule, where)
elif func == 'enable':
self.schedule.enable_schedule()
elif func == 'disable':
self.schedule.disable_schedule()
elif func == 'enable_job':
self.schedule.enable_job(name, where)
elif func == 'run_job':
self.schedule.run_job(name, where)
elif func == 'disable_job':
self.schedule.disable_job(name, where)
elif func == 'reload':
self.schedule.reload(schedule)
def environ_setenv(self, package):
'''
Set the salt-minion main process environment according to
the data contained in the minion event data
'''
tag, data = salt.utils.event.MinionEvent.unpack(package)
environ = data.get('environ', None)
if environ is None:
return False
false_unsets = data.get('false_unsets', False)
clear_all = data.get('clear_all', False)
import salt.modules.environ as mod_environ
return mod_environ.setenv(environ, false_unsets, clear_all)
def clean_die(self, signum, frame):
'''
Python does not handle the SIGTERM cleanly, if it is signaled exit
the minion process cleanly
'''
self._running = False
exit(0)
def _pre_tune(self):
'''
Set the minion running flag and issue the appropriate warnings if
the minion cannot be started or is already running
'''
if self._running is None:
self._running = True
elif self._running is False:
log.error(
'This {0} was scheduled to stop. Not running '
'{0}.tune_in()'.format(self.__class__.__name__)
)
return
elif self._running is True:
log.error(
'This {0} is already running. Not running '
'{0}.tune_in()'.format(self.__class__.__name__)
)
return
try:
log.info(
'{0} is starting as user \'{1}\''.format(
self.__class__.__name__,
salt.utils.get_user()
)
)
except Exception as err:
# Only windows is allowed to fail here. See #3189. Log as debug in
# that case. Else, error.
log.log(
salt.utils.is_windows() and logging.DEBUG or logging.ERROR,
'Failed to get the user who is starting {0}'.format(
self.__class__.__name__
),
exc_info=err
)
def handle_event(self, package):
'''
Handle an event from the epull_sock (all local minion events)
'''
log.debug('Handling event {0!r}'.format(package))
if package.startswith('module_refresh'):
self.module_refresh()
elif package.startswith('pillar_refresh'):
self.pillar_refresh()
elif package.startswith('manage_schedule'):
self.manage_schedule(package)
elif package.startswith('grains_refresh'):
if self.grains_cache != self.opts['grains']:
self.pillar_refresh(force_refresh=True)
self.grains_cache = self.opts['grains']
elif package.startswith('environ_setenv'):
self.environ_setenv(package)
elif package.startswith('fire_master'):
tag, data = salt.utils.event.MinionEvent.unpack(package)
log.debug('Forwarding master event tag={tag}'.format(tag=data['tag']))
self._fire_master(data['data'], data['tag'], data['events'], data['pretag'])
elif package.startswith('__master_disconnected'):
tag, data = salt.utils.event.MinionEvent.unpack(package)
# if the master disconnect event is for a different master, raise an exception
if data['master'] != self.opts['master']:
raise Exception()
if self.connected:
# we are not connected anymore
self.connected = False
# modify the scheduled job to fire only on reconnect
schedule = {
'function': 'status.master',
'seconds': self.opts['master_alive_interval'],
'jid_include': True,
'maxrunning': 2,
'kwargs': {'master_ip': self.opts['master'],
'connected': False}
}
self.schedule.modify_job(name='__master_alive',
schedule=schedule)
log.info('Connection to master {0} lost'.format(self.opts['master']))
if self.opts['master_type'] == 'failover':
log.info('Trying to tune in to next master from master-list')
# if eval_master finds a new master for us, self.connected
# will be True again on successfull master authentication
self.opts['master'] = self.eval_master(opts=self.opts,
failed=True)
if self.connected:
# re-init the subsystems to work with the new master
log.info('Re-initialising subsystems for new '
'master {0}'.format(self.opts['master']))
del self.socket
del self.context
del self.poller
self._init_context_and_poller()
self.socket = self.context.socket(zmq.SUB)
self._set_reconnect_ivl()
self._setsockopts()
self.socket.connect(self.master_pub)
self.poller.register(self.socket, zmq.POLLIN)
self.poller.register(self.epull_sock, zmq.POLLIN)
self._fire_master_minion_start()
log.info('Minion is ready to receive requests!')
# update scheduled job to run with the new master addr
schedule = {
'function': 'status.master',
'seconds': self.opts['master_alive_interval'],
'jid_include': True,
'maxrunning': 2,
'kwargs': {'master_ip': self.opts['master'],
'connected': True}
}
self.schedule.modify_job(name='__master_alive',
schedule=schedule)
elif package.startswith('__master_connected'):
# handle this event only once. otherwise it will polute the log
if not self.connected:
log.info('Connection to master {0} re-established'.format(self.opts['master']))
self.connected = True
# modify the __master_alive job to only fire,
# if the connection is lost again
schedule = {
'function': 'status.master',
'seconds': self.opts['master_alive_interval'],
'jid_include': True,
'maxrunning': 2,
'kwargs': {'master_ip': self.opts['master'],
'connected': True}
}
self.schedule.modify_job(name='__master_alive',
schedule=schedule)
# Main Minion Tune In
def tune_in(self):
'''
Lock onto the publisher. This is the main event loop for the minion
:rtype : None
'''
self._pre_tune()
# Properly exit if a SIGTERM is signalled
signal.signal(signal.SIGTERM, self.clean_die)
log.debug('Minion {0!r} trying to tune in'.format(self.opts['id']))
self._prepare_minion_event_system()
self.socket = self.context.socket(zmq.SUB)
self._set_reconnect_ivl()
self._setsockopts()
self.socket.connect(self.master_pub)
self.poller.register(self.socket, zmq.POLLIN)
self.poller.register(self.epull_sock, zmq.POLLIN)
self._fire_master_minion_start()
log.info('Minion is ready to receive requests!')
# Make sure to gracefully handle SIGUSR1
enable_sigusr1_handler()
# Make sure to gracefully handle CTRL_LOGOFF_EVENT
salt.utils.enable_ctrl_logoff_handler()
# On first startup execute a state run if configured to do so
self._state_run()
loop_interval = int(self.opts['loop_interval'])
try:
if self.opts['grains_refresh_every']: # If exists and is not zero. In minutes, not seconds!
if self.opts['grains_refresh_every'] > 1:
log.debug(
'Enabling the grains refresher. Will run every {0} minutes.'.format(
self.opts['grains_refresh_every'])
)
else: # Clean up minute vs. minutes in log message
log.debug(
'Enabling the grains refresher. Will run every {0} minute.'.format(
self.opts['grains_refresh_every'])
)
self._refresh_grains_watcher(
abs(self.opts['grains_refresh_every'])
)
except Exception as exc:
log.error(
'Exception occurred in attempt to initialize grain refresh routine during minion tune-in: {0}'.format(
exc)
)
ping_interval = self.opts.get('ping_interval', 0) * 60
ping_at = None
while self._running is True:
loop_interval = self.process_schedule(self, loop_interval)
try:
socks = self._do_poll(loop_interval)
if ping_interval > 0:
if socks or not ping_at:
ping_at = time.time() + ping_interval
if ping_at < time.time():
log.debug('Ping master')
self._fire_master('ping', 'minion_ping')
ping_at = time.time() + ping_interval
self._do_socket_recv(socks)
# Check the event system
if socks.get(self.epull_sock) == zmq.POLLIN:
package = self.epull_sock.recv(zmq.NOBLOCK)
try:
self.handle_event(package)
self.epub_sock.send(package)
except Exception:
log.debug('Exception while handling events', exc_info=True)
# Add an extra fallback in case a forked process leeks through
multiprocessing.active_children()
except zmq.ZMQError as exc:
# The interrupt caused by python handling the
# SIGCHLD. Throws this error with errno == EINTR.
# Nothing to receive on the zmq socket throws this error
# with EAGAIN.
# Both are safe to ignore
if exc.errno != errno.EAGAIN and exc.errno != errno.EINTR:
log.critical('Unexpected ZMQError while polling minion',
exc_info=True)
continue
except SaltClientError:
raise
except Exception:
log.critical(
'An exception occurred while polling the minion',
exc_info=True
)
def tune_in_no_block(self):
'''
Executes the tune_in sequence but omits extra logging and the
management of the event bus assuming that these are handled outside
the tune_in sequence
'''
self._pre_tune()
self._init_context_and_poller()
self.socket = self.context.socket(zmq.SUB)
self._setsockopts()
self.socket.connect(self.master_pub)
self.poller.register(self.socket, zmq.POLLIN)
self._fire_master_minion_start()
loop_interval = int(self.opts['loop_interval'])
# On first startup execute a state run if configured to do so
self._state_run()
while self._running is True:
try:
socks = self._do_poll(loop_interval)
self._do_socket_recv(socks)
# Check the event system
except zmq.ZMQError:
# If a zeromq error happens recover
yield True
except Exception:
log.critical(
'An exception occurred while polling the minion',
exc_info=True
)
yield True
def _do_poll(self, loop_interval):
log.trace('Check main poller timeout {0}'.format(loop_interval))
return dict(self.poller.poll(
loop_interval * 1000)
)
def _do_socket_recv(self, socks):
if socks.get(self.socket) == zmq.POLLIN:
# topic filtering is done at the zmq level, so we just strip it
messages = self.socket.recv_multipart(zmq.NOBLOCK)
messages_len = len(messages)
# if it was one message, then its old style
if messages_len == 1:
payload = self.serial.loads(messages[0])
# 2 includes a header which says who should do it
elif messages_len == 2:
payload = self.serial.loads(messages[1])
else:
raise Exception(('Invalid number of messages ({0}) in zeromq pub'
'message from master').format(len(messages_len)))
log.trace('Handling payload')
self._handle_payload(payload)
def destroy(self):
'''
Tear down the minion
'''
self._running = False
if getattr(self, 'poller', None) is not None:
if isinstance(self.poller.sockets, dict):
for socket in self.poller.sockets.keys():
if socket.closed is False:
socket.close()
self.poller.unregister(socket)
else:
for socket in self.poller.sockets:
if socket[0].closed is False:
socket[0].close()
self.poller.unregister(socket[0])
if hasattr(self, 'epub_sock') and self.epub_sock.closed is False:
self.epub_sock.close()
if hasattr(self, 'epull_sock') and self.epull_sock.closed is False:
self.epull_sock.close()
if hasattr(self, 'socket') and self.socket.closed is False:
self.socket.close()
if hasattr(self, 'context') and self.context.closed is False:
self.context.term()
def __del__(self):
self.destroy()
class Syndic(Minion):
'''
Make a Syndic minion, this minion will use the minion keys on the
master to authenticate with a higher level master.
'''
def __init__(self, opts, **kwargs):
self._syndic_interface = opts.get('interface')
self._syndic = True
# force auth_safemode True because Syndic don't support autorestart
opts['auth_safemode'] = True
opts['loop_interval'] = 1
super(Syndic, self).__init__(opts, **kwargs)
self.mminion = salt.minion.MasterMinion(opts)
def _handle_aes(self, load, sig=None):
'''
Takes the AES encrypted load, decrypts it, and runs the encapsulated
instructions
'''
# If the AES authentication has changed, re-authenticate
try:
data = self.crypticle.loads(load)
except AuthenticationError:
self.authenticate()
data = self.crypticle.loads(load)
# Verify that the publication is valid
if 'tgt' not in data or 'jid' not in data or 'fun' not in data \
or 'arg' not in data:
return
data['to'] = int(data['to']) - 1
if 'user' in data:
log.debug(
'User {0[user]} Executing syndic command {0[fun]} with '
'jid {0[jid]}'.format(
data
)
)
else:
log.debug(
'Executing syndic command {0[fun]} with jid {0[jid]}'.format(
data
)
)
log.debug('Command details: {0}'.format(data))
self._handle_decoded_payload(data)
def _handle_decoded_payload(self, data):
'''
Override this method if you wish to handle the decoded data
differently.
'''
self.syndic_cmd(data)
def syndic_cmd(self, data):
'''
Take the now clear load and forward it on to the client cmd
'''
# Set up default tgt_type
if 'tgt_type' not in data:
data['tgt_type'] = 'glob'
kwargs = {}
# if a master_id is in the data, add it to publish job
if 'master_id' in data:
kwargs['master_id'] = data['master_id']
# Send out the publication
self.local.pub(data['tgt'],
data['fun'],
data['arg'],
data['tgt_type'],
data['ret'],
data['jid'],
data['to'],
**kwargs)
def _setsockopts(self):
# no filters for syndication masters, unless we want to maintain a
# list of all connected minions and update the filter
self.socket.setsockopt(zmq.SUBSCRIBE, '')
self.socket.setsockopt(zmq.IDENTITY, self.opts['id'])
self._set_reconnect_ivl_max()
self._set_tcp_keepalive()
self._set_ipv4only()
def _fire_master_syndic_start(self):
# Send an event to the master that the minion is live
self._fire_master(
'Syndic {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
'syndic_start'
)
self._fire_master(
'Syndic {0} started at {1}'.format(
self.opts['id'],
time.asctime()
),
tagify([self.opts['id'], 'start'], 'syndic'),
)
def tune_in_no_block(self):
'''
Executes the tune_in sequence but omits extra logging and the
management of the event bus assuming that these are handled outside
the tune_in sequence
'''
# Instantiate the local client
self.local = salt.client.get_local_client(self.opts['_minion_conf_file'])
self.local.event.subscribe('')
self._init_context_and_poller()
self.socket = self.context.socket(zmq.SUB)
self._setsockopts()
self.socket.connect(self.master_pub)
self.poller.register(self.socket, zmq.POLLIN)
loop_interval = int(self.opts['loop_interval'])
self._fire_master_syndic_start()
while True:
try:
socks = dict(self.poller.poll(loop_interval * 1000))
if socks.get(self.socket) == zmq.POLLIN:
self._process_cmd_socket()
except zmq.ZMQError:
yield True
except Exception:
log.critical(
'An exception occurred while polling the minion',
exc_info=True
)
yield True
# Syndic Tune In
def tune_in(self):
'''
Lock onto the publisher. This is the main event loop for the syndic
'''
# Instantiate the local client
self.local = salt.client.get_local_client(self.opts['_minion_conf_file'])
self.local.event.subscribe('')
self.local.opts['interface'] = self._syndic_interface
signal.signal(signal.SIGTERM, self.clean_die)
log.debug('Syndic {0!r} trying to tune in'.format(self.opts['id']))
self._init_context_and_poller()
# Start with the publish socket
# Share the poller with the event object
self.socket = self.context.socket(zmq.SUB)
self._setsockopts()
self.socket.connect(self.master_pub)
self.poller.register(self.socket, zmq.POLLIN)
# Send an event to the master that the minion is live
self._fire_master_syndic_start()
# Make sure to gracefully handle SIGUSR1
enable_sigusr1_handler()
loop_interval = int(self.opts['loop_interval'])
self._reset_event_aggregation()
while True:
try:
# Do all the maths in seconds
timeout = loop_interval
if self.event_forward_timeout is not None:
timeout = min(timeout,
self.event_forward_timeout - time.time())
if timeout >= 0:
log.trace('Polling timeout: %f', timeout)
socks = dict(self.poller.poll(timeout * 1000))
else:
# This shouldn't really happen.
# But there's no harm being defensive
log.warning('Negative timeout in syndic main loop')
socks = {}
if socks.get(self.socket) == zmq.POLLIN:
self._process_cmd_socket()
if socks.get(self.local.event.sub) == zmq.POLLIN:
self._process_event_socket()
if self.event_forward_timeout is not None and \
self.event_forward_timeout < time.time():
self._forward_events()
# We don't handle ZMQErrors like the other minions
# I've put explicit handling around the receive calls
# in the process_*_socket methods. If we see any other
# errors they may need some kind of handling so log them
# for now.
except Exception:
log.critical(
'An exception occurred while polling the syndic',
exc_info=True
)
def _process_cmd_socket(self):
try:
messages = self.socket.recv_multipart(zmq.NOBLOCK)
messages_len = len(messages)
idx = None
if messages_len == 1:
idx = 0
elif messages_len == 2:
idx = 1
else:
raise SaltSyndicMasterError('Syndication master received message of invalid len ({0}/2)'.format(messages_len))
payload = self.serial.loads(messages[idx])
except zmq.ZMQError as e:
# Swallow errors for bad wakeups or signals needing processing
if e.errno != errno.EAGAIN and e.errno != errno.EINTR:
raise
log.trace('Handling payload')
self._handle_payload(payload)
def _reset_event_aggregation(self):
self.jids = {}
self.raw_events = []
self.event_forward_timeout = None
def _process_event_socket(self):
tout = time.time() + self.opts['syndic_max_event_process_time']
while tout > time.time():
try:
event = self.local.event.get_event_noblock()
except zmq.ZMQError as e:
# EAGAIN indicates no more events at the moment
# EINTR some kind of signal maybe someone trying
# to get us to quit so escape our timeout
if e.errno == errno.EAGAIN or e.errno == errno.EINTR:
break
raise
log.trace('Got event {0}'.format(event['tag']))
if self.event_forward_timeout is None:
self.event_forward_timeout = (
time.time() + self.opts['syndic_event_forward_timeout']
)
if salt.utils.is_jid(event['tag']) and 'return' in event['data']:
if 'jid' not in event['data']:
# Not a job return
continue
jdict = self.jids.setdefault(event['tag'], {})
if not jdict:
jdict['__fun__'] = event['data'].get('fun')
jdict['__jid__'] = event['data']['jid']
jdict['__load__'] = {}
fstr = '{0}.get_jid'.format(self.opts['master_job_cache'])
jdict['__load__'].update(
self.mminion.returners[fstr](event['data']['jid'])
)
if 'master_id' in event['data']:
jdict['master_id'] = event['data']['master_id']
jdict[event['data']['id']] = event['data']['return']
else:
# Add generic event aggregation here
if 'retcode' not in event['data']:
self.raw_events.append(event)
def _forward_events(self):
log.trace('Forwarding events')
if self.raw_events:
self._fire_master(events=self.raw_events,
pretag=tagify(self.opts['id'], base='syndic'),
)
for jid in self.jids:
self._return_pub(self.jids[jid], '_syndic_return')
self._reset_event_aggregation()
def destroy(self):
'''
Tear down the syndic minion
'''
# We borrowed the local clients poller so give it back before
# it's destroyed. Reset the local poller reference.
self.poller = None
super(Syndic, self).destroy()
if hasattr(self, 'local'):
del self.local
class MultiSyndic(MinionBase):
'''
Make a MultiSyndic minion, this minion will handle relaying jobs and returns from
all minions connected to it to the list of masters it is connected to.
Note: jobs will be returned best-effort to the requesting master. This also means
(since we are using zmq) that if a job was fired and the master disconnects
between the publish and return, that the return will end up in a zmq buffer
in this Syndic headed to that original master.
In addition, since these classes all seem to use a mix of blocking and non-blocking
calls (with varying timeouts along the way) this daemon does not handle failure well,
it will (under most circumstances) stall the daemon for ~60s attempting to re-auth
with the down master
'''
# time to connect to upstream master
SYNDIC_CONNECT_TIMEOUT = 5
def __init__(self, opts):
opts['loop_interval'] = 1
super(MultiSyndic, self).__init__(opts)
self.mminion = salt.minion.MasterMinion(opts)
# create all of the syndics you need
self.master_syndics = {}
for master in set(self.opts['master']):
s_opts = copy.copy(self.opts)
s_opts['master'] = master
self.master_syndics[master] = {'opts': s_opts,
'auth_wait': s_opts['acceptance_wait_time'],
'dead_until': 0}
self._connect_to_master(master)
# TODO: do we need all of this?
def _connect_to_master(self, master):
'''
Attempt to connect to master, including back-off for each one
return boolean of wether you connected or not
'''
if master not in self.master_syndics:
log.error('Unable to connect to {0}, not in the list of masters'.format(master))
return False
minion = self.master_syndics[master]
# if we need to be dead for a while, stay that way
if minion['dead_until'] > time.time():
return False
if time.time() - minion['auth_wait'] > minion.get('last', 0):
try:
t_minion = Syndic(minion['opts'],
timeout=self.SYNDIC_CONNECT_TIMEOUT,
safe=False,
)
self.master_syndics[master]['syndic'] = t_minion
self.master_syndics[master]['generator'] = t_minion.tune_in_no_block()
self.master_syndics[master]['auth_wait'] = self.opts['acceptance_wait_time']
self.master_syndics[master]['dead_until'] = 0
return True
except SaltClientError:
log.error('Error while bring up minion for multi-syndic. Is master {0} responding?'.format(master))
# re-use auth-wait as backoff for syndic
minion['dead_until'] = time.time() + minion['auth_wait']
if minion['auth_wait'] < self.opts['acceptance_wait_time_max']:
minion['auth_wait'] += self.opts['acceptance_wait_time']
return False
def _call_syndic(self, func, args=(), kwargs=None, master_id=None):
'''
Wrapper to call a given func on a syndic, best effort to get the one you asked for
'''
if kwargs is None:
kwargs = {}
for master, syndic_dict in self.iter_master_options(master_id):
if 'syndic' not in syndic_dict:
continue
if syndic_dict['dead_until'] > time.time():
log.error('Unable to call {0} on {1}, that syndic is dead for now'.format(func, master_id))
continue
try:
getattr(syndic_dict['syndic'], func)(*args, **kwargs)
return
except SaltClientError:
log.error('Unable to call {0} on {1}, trying another...'.format(func, master_id))
# re-use auth-wait as backoff for syndic
syndic_dict['dead_until'] = time.time() + syndic_dict['auth_wait']
if syndic_dict['auth_wait'] < self.opts['acceptance_wait_time_max']:
syndic_dict['auth_wait'] += self.opts['acceptance_wait_time']
continue
log.critical('Unable to call {0} on any masters!'.format(func))
def iter_master_options(self, master_id=None):
'''
Iterate (in order) over your options for master
'''
masters = self.master_syndics.keys()
shuffle(masters)
if master_id not in self.master_syndics:
master_id = masters.pop(0)
else:
masters.remove(master_id)
while True:
yield master_id, self.master_syndics[master_id]
if len(masters) == 0:
break
master_id = masters.pop(0)
def _reset_event_aggregation(self):
self.jids = {}
self.raw_events = []
self.event_forward_timeout = None
# Syndic Tune In
def tune_in(self):
'''
Lock onto the publisher. This is the main event loop for the syndic
'''
# Instantiate the local client
self.local = salt.client.get_local_client(self.opts['_minion_conf_file'])
self.local.event.subscribe('')
log.debug('MultiSyndic {0!r} trying to tune in'.format(self.opts['id']))
# Share the poller with the event object
self.poller = self.local.event.poller
# Make sure to gracefully handle SIGUSR1
enable_sigusr1_handler()
loop_interval = int(self.opts['loop_interval'])
self._reset_event_aggregation()
while True:
try:
# Do all the maths in seconds
timeout = loop_interval
if self.event_forward_timeout is not None:
timeout = min(timeout,
self.event_forward_timeout - time.time())
if timeout >= 0:
log.trace('Polling timeout: %f', timeout)
socks = dict(self.poller.poll(timeout * 1000))
else:
# This shouldn't really happen.
# But there's no harm being defensive
log.warning('Negative timeout in syndic main loop')
socks = {}
# check all of your master_syndics, have them do their thing
for master_id, syndic_dict in self.master_syndics.iteritems():
# if not connected, lets try
if 'generator' not in syndic_dict:
# if we couldn't connect, lets try later
if not self._connect_to_master(master_id):
continue
syndic_dict['generator'].next()
# events
if socks.get(self.local.event.sub) == zmq.POLLIN:
self._process_event_socket()
if self.event_forward_timeout is not None and \
self.event_forward_timeout < time.time():
self._forward_events()
# We don't handle ZMQErrors like the other minions
# I've put explicit handling around the receive calls
# in the process_*_socket methods. If we see any other
# errors they may need some kind of handling so log them
# for now.
except Exception:
log.critical(
'An exception occurred while polling the syndic',
exc_info=True
)
def _process_event_socket(self):
tout = time.time() + self.opts['syndic_max_event_process_time']
while tout > time.time():
try:
event = self.local.event.get_event_noblock()
except zmq.ZMQError as e:
# EAGAIN indicates no more events at the moment
# EINTR some kind of signal maybe someone trying
# to get us to quit so escape our timeout
if e.errno == errno.EAGAIN or e.errno == errno.EINTR:
break
raise
log.trace('Got event {0}'.format(event['tag']))
if self.event_forward_timeout is None:
self.event_forward_timeout = (
time.time() + self.opts['syndic_event_forward_timeout']
)
if salt.utils.is_jid(event['tag']) and 'return' in event['data']:
if 'jid' not in event['data']:
# Not a job return
continue
jdict = self.jids.setdefault(event['tag'], {})
if not jdict:
jdict['__fun__'] = event['data'].get('fun')
jdict['__jid__'] = event['data']['jid']
jdict['__load__'] = {}
fstr = '{0}.get_jid'.format(self.opts['master_job_cache'])
jdict['__load__'].update(
self.mminion.returners[fstr](event['data']['jid'])
)
if 'master_id' in event['data']:
# __'s to make sure it doesn't print out on the master cli
jdict['__master_id__'] = event['data']['master_id']
jdict[event['data']['id']] = event['data']['return']
else:
# Add generic event aggregation here
if 'retcode' not in event['data']:
self.raw_events.append(event)
def _forward_events(self):
log.trace('Forwarding events')
if self.raw_events:
self._call_syndic('_fire_master',
kwargs={'events': self.raw_events,
'pretag': tagify(self.opts['id'], base='syndic')},
)
for jid, jid_ret in self.jids.iteritems():
self._call_syndic('_return_pub', args=(jid_ret, '_syndic_return'), master_id=jid_ret.get('__master_id__'))
self._reset_event_aggregation()
class Matcher(object):
'''
Use to return the value for matching calls from the master
'''
def __init__(self, opts, functions=None):
self.opts = opts
if functions is None:
functions = salt.loader.minion_mods(self.opts)
self.functions = functions
def confirm_top(self, match, data, nodegroups=None):
'''
Takes the data passed to a top file environment and determines if the
data matches this minion
'''
matcher = 'compound'
if not data:
log.error('Received bad data when setting the match from the top '
'file')
return False
for item in data:
if isinstance(item, dict):
if 'match' in item:
matcher = item['match']
if hasattr(self, matcher + '_match'):
funcname = '{0}_match'.format(matcher)
if matcher == 'nodegroup':
return getattr(self, funcname)(match, nodegroups)
return getattr(self, funcname)(match)
else:
log.error('Attempting to match with unknown matcher: {0}'.format(
matcher
))
return False
def glob_match(self, tgt):
'''
Returns true if the passed glob matches the id
'''
if not isinstance(tgt, str):
return False
return fnmatch.fnmatch(self.opts['id'], tgt)
def pcre_match(self, tgt):
'''
Returns true if the passed pcre regex matches
'''
return bool(re.match(tgt, self.opts['id']))
def list_match(self, tgt):
'''
Determines if this host is on the list
'''
if isinstance(tgt, string_types):
tgt = tgt.split(',')
return bool(self.opts['id'] in tgt)
def grain_match(self, tgt, delimiter=DEFAULT_TARGET_DELIM):
'''
Reads in the grains glob match
'''
log.debug('grains target: {0}'.format(tgt))
if delimiter not in tgt:
log.error('Got insufficient arguments for grains match '
'statement from master')
return False
return salt.utils.subdict_match(
self.opts['grains'], tgt, delimiter=delimiter
)
def grain_pcre_match(self, tgt, delimiter=DEFAULT_TARGET_DELIM):
'''
Matches a grain based on regex
'''
log.debug('grains pcre target: {0}'.format(tgt))
if delimiter not in tgt:
log.error('Got insufficient arguments for grains pcre match '
'statement from master')
return False
return salt.utils.subdict_match(self.opts['grains'], tgt,
delimiter=delimiter, regex_match=True)
def data_match(self, tgt):
'''
Match based on the local data store on the minion
'''
comps = tgt.split(':')
if len(comps) < 2:
return False
val = self.functions['data.getval'](comps[0])
if val is None:
# The value is not defined
return False
if isinstance(val, list):
# We are matching a single component to a single list member
for member in val:
if fnmatch.fnmatch(str(member).lower(), comps[1].lower()):
return True
return False
if isinstance(val, dict):
if comps[1] in val:
return True
return False
return bool(fnmatch.fnmatch(
val,
comps[1],
))
def pillar_match(self, tgt, delimiter=DEFAULT_TARGET_DELIM):
'''
Reads in the pillar glob match
'''
log.debug('pillar target: {0}'.format(tgt))
if delimiter not in tgt:
log.error('Got insufficient arguments for pillar match '
'statement from master')
return False
return salt.utils.subdict_match(
self.opts['pillar'], tgt, delimiter=delimiter
)
def ipcidr_match(self, tgt):
'''
Matches based on ip address or CIDR notation
'''
num_parts = len(tgt.split('/'))
if num_parts > 2:
# Target is not valid CIDR
return False
elif num_parts == 2:
# Target is CIDR
return salt.utils.network.in_subnet(
tgt,
addrs=self.opts['grains'].get('ipv4', [])
)
else:
# Target is an IPv4 address
import socket
try:
socket.inet_aton(tgt)
except socket.error:
# Not a valid IPv4 address
return False
else:
return tgt in self.opts['grains'].get('ipv4', [])
def range_match(self, tgt):
'''
Matches based on range cluster
'''
if HAS_RANGE:
range_ = seco.range.Range(self.opts['range_server'])
try:
return self.opts['grains']['fqdn'] in range_.expand(tgt)
except seco.range.RangeException as exc:
log.debug('Range exception in compound match: {0}'.format(exc))
return False
return False
def compound_match(self, tgt):
'''
Runs the compound target check
'''
if not isinstance(tgt, string_types):
log.debug('Compound target received that is not a string')
return False
ref = {'G': 'grain',
'P': 'grain_pcre',
'I': 'pillar',
'L': 'list',
'S': 'ipcidr',
'E': 'pcre'}
if HAS_RANGE:
ref['R'] = 'range'
results = []
opers = ['and', 'or', 'not', '(', ')']
tokens = tgt.split()
for match in tokens:
# Try to match tokens from the compound target, first by using
# the 'G, X, I, L, S, E' matcher types, then by hostname glob.
if '@' in match and match[1] == '@':
comps = match.split('@')
matcher = ref.get(comps[0])
if not matcher:
# If an unknown matcher is called at any time, fail out
return False
results.append(
str(
getattr(self, '{0}_match'.format(matcher))(
'@'.join(comps[1:])
)
)
)
elif match in opers:
# We didn't match a target, so append a boolean operator or
# subexpression
if results or match in ['(', ')']:
if match == 'not':
if results[-1] == 'and':
pass
elif results[-1] == 'or':
pass
else:
results.append('and')
results.append(match)
else:
# seq start with oper, fail
if match not in ['(', ')']:
return False
else:
# The match is not explicitly defined, evaluate it as a glob
results.append(str(self.glob_match(match)))
results = ' '.join(results)
try:
return eval(results) # pylint: disable=W0123
except Exception:
log.error('Invalid compound target: {0} for results: {1}'.format(tgt, results))
return False
return False
def nodegroup_match(self, tgt, nodegroups):
'''
This is a compatibility matcher and is NOT called when using
nodegroups for remote execution, but is called when the nodegroups
matcher is used in states
'''
if tgt in nodegroups:
return self.compound_match(
salt.utils.minions.nodegroup_comp(tgt, nodegroups)
)
return False
class ProxyMinion(Minion):
'''
This class instantiates a 'proxy' minion--a minion that does not manipulate
the host it runs on, but instead manipulates a device that cannot run a minion.
'''
def __init__(self, opts, timeout=60, safe=True): # pylint: disable=W0231
'''
Pass in the options dict
'''
self._running = None
# Warn if ZMQ < 3.2
if HAS_ZMQ:
try:
zmq_version_info = zmq.zmq_version_info()
except AttributeError:
# PyZMQ <= 2.1.9 does not have zmq_version_info, fall back to
# using zmq.zmq_version() and build a version info tuple.
zmq_version_info = tuple(
[int(x) for x in zmq.zmq_version().split('.')]
)
if zmq_version_info < (3, 2):
log.warning(
'You have a version of ZMQ less than ZMQ 3.2! There are '
'known connection keep-alive issues with ZMQ < 3.2 which '
'may result in loss of contact with minions. Please '
'upgrade your ZMQ!'
)
# Late setup the of the opts grains, so we can log from the grains
# module
# print opts['proxymodule']
fq_proxyname = 'proxy.'+opts['proxy']['proxytype']
self.proxymodule = salt.loader.proxy(opts, fq_proxyname)
opts['proxyobject'] = self.proxymodule[opts['proxy']['proxytype']+'.Proxyconn'](opts['proxy'])
opts['id'] = opts['proxyobject'].id(opts)
opts.update(resolve_dns(opts))
self.opts = opts
self.authenticate(timeout, safe)
self.opts['pillar'] = salt.pillar.get_pillar(
opts,
opts['grains'],
opts['id'],
opts['environment'],
).compile_pillar()
self.serial = salt.payload.Serial(self.opts)
self.mod_opts = self._prep_mod_opts()
self.functions, self.returners = self._load_modules()
self.matcher = Matcher(self.opts, self.functions)
self.proc_dir = get_proc_dir(opts['cachedir'])
self.schedule = salt.utils.schedule.Schedule(
self.opts,
self.functions,
self.returners)
self.grains_cache = self.opts['grains']
# self._running = True
def _prep_mod_opts(self):
'''
Returns a copy of the opts with key bits stripped out
'''
return super(ProxyMinion, self)._prep_mod_opts()
def _load_modules(self, force_refresh=False):
'''
Return the functions and the returners loaded up from the loader
module
'''
return super(ProxyMinion, self)._load_modules(force_refresh=force_refresh) | |
__init__.py | __import__("pkg_resources").declare_namespace(__name__)
import ctypes
import os
from . import api
class File(object):
def __init__(self, filepath):
super(File, self).__init__()
self._path = filepath
def _get_version_info_size(self):
filepath = ctypes.create_unicode_buffer(self._path)
size = api.GetFileVersionInfoSizeW(filepath)
return size
def _extract_version_info_from_block(self, block):
sub_block = ctypes.create_unicode_buffer("\\")
size = ctypes.c_ulong(api.VS_FIXEDFILEINFO.min_max_sizeof().max)
pointer = ctypes.c_void_p()
api.VerQueryValueW(block, sub_block, pointer, size)
buffer = ctypes.string_at(pointer, size.value)
return api.VS_FIXEDFILEINFO.create_from_string(buffer)
def _get_version_info(self):
size = ctypes.c_ulong(self._get_version_info_size())
block = ctypes.c_buffer(b'\x00' * size.value, size.value)
filepath = ctypes.create_unicode_buffer(self._path)
api.GetFileVersionInfoW(filepath, ctypes.c_ulong(0), size, block)
return block
def | (self):
assert os.path.exists(self._path)
block = self._get_version_info()
info = self._extract_version_info_from_block(block)
items = [api.HIWORD(info.dwFileVersionMS), api.LOWORD(info.dwFileVersionMS),
api.HIWORD(info.dwFileVersionLS), api.LOWORD(info.dwFileVersionLS)]
return ".".join([str(item) for item in items])
| get_version |
network.go | // Package network is for creating internetworks
package network
import (
"time"
"xinhari.com/xinhari/client"
"xinhari.com/xinhari/server"
)
var (
// DefaultName is default network name
DefaultName = "go.micro"
// DefaultAddress is default network address
DefaultAddress = ":0"
// ResolveTime defines time interval to periodically resolve network nodes
ResolveTime = 1 * time.Minute
// AnnounceTime defines time interval to periodically announce node neighbours
AnnounceTime = 1 * time.Second
// KeepAliveTime is the time in which we want to have sent a message to a peer
KeepAliveTime = 30 * time.Second
// SyncTime is the time a network node requests full sync from the network
SyncTime = 1 * time.Minute
// PruneTime defines time interval to periodically check nodes that need to be pruned
// due to their not announcing their presence within this time interval
PruneTime = 90 * time.Second
)
// Error is network node errors
type Error interface {
// Count is current count of errors
Count() int
// Msg is last error message
Msg() string
}
// Status is node status
type Status interface {
// Error reports error status
Error() Error
}
// Node is network node
type Node interface {
// Id is node id
Id() string
// Address is node bind address
Address() string
// Peers returns node peers
Peers() []Node
// Network is the network node is in
Network() Network
// Status returns node status
Status() Status
}
// Network is xinhari network
type Network interface {
// Node is network node
Node
// Initialise options
Init(...Option) error
// Options returns the network options
Options() Options
// Name of the network
Name() string
// Connect starts the resolver and tunnel server
Connect() error
// Close stops the tunnel and resolving
Close() error
// Client is xinhari client
Client() client.Client
// Server is xinhari server
Server() server.Server
}
// NewNetwork returns a new network interface
func | (opts ...Option) Network {
return newNetwork(opts...)
}
| NewNetwork |
powerclr.rs | #[doc = "Writer for register POWERCLR"]
pub type W = crate::W<u32, super::POWERCLR>;
#[doc = "Register POWERCLR `reset()`'s with value 0xffff"]
impl crate::ResetValue for super::POWERCLR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0xffff
}
}
#[doc = "Keep RAM section S0 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S0POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S0POWER_AW> for bool {
#[inline(always)]
fn from(variant: S0POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S0POWER`"]
pub struct S0POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S0POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S0POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S0POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Keep RAM section S1 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S1POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S1POWER_AW> for bool {
#[inline(always)]
fn from(variant: S1POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S1POWER`"]
pub struct S1POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S1POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S1POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S1POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Keep RAM section S2 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S2POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S2POWER_AW> for bool {
#[inline(always)]
fn from(variant: S2POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S2POWER`"]
pub struct S2POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S2POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S2POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S2POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
} | self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Keep RAM section S3 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S3POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S3POWER_AW> for bool {
#[inline(always)]
fn from(variant: S3POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S3POWER`"]
pub struct S3POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S3POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S3POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S3POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Keep RAM section S4 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S4POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S4POWER_AW> for bool {
#[inline(always)]
fn from(variant: S4POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S4POWER`"]
pub struct S4POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S4POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S4POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S4POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Keep RAM section S5 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S5POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S5POWER_AW> for bool {
#[inline(always)]
fn from(variant: S5POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S5POWER`"]
pub struct S5POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S5POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S5POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S5POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Keep RAM section S6 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S6POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S6POWER_AW> for bool {
#[inline(always)]
fn from(variant: S6POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S6POWER`"]
pub struct S6POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S6POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S6POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S6POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Keep RAM section S7 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S7POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S7POWER_AW> for bool {
#[inline(always)]
fn from(variant: S7POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S7POWER`"]
pub struct S7POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S7POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S7POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S7POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Keep RAM section S8 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S8POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S8POWER_AW> for bool {
#[inline(always)]
fn from(variant: S8POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S8POWER`"]
pub struct S8POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S8POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S8POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S8POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Keep RAM section S9 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S9POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S9POWER_AW> for bool {
#[inline(always)]
fn from(variant: S9POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S9POWER`"]
pub struct S9POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S9POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S9POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S9POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Keep RAM section S10 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S10POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S10POWER_AW> for bool {
#[inline(always)]
fn from(variant: S10POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S10POWER`"]
pub struct S10POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S10POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S10POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S10POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Keep RAM section S11 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S11POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S11POWER_AW> for bool {
#[inline(always)]
fn from(variant: S11POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S11POWER`"]
pub struct S11POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S11POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S11POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S11POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Keep RAM section S12 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S12POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S12POWER_AW> for bool {
#[inline(always)]
fn from(variant: S12POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S12POWER`"]
pub struct S12POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S12POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S12POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S12POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Keep RAM section S13 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S13POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S13POWER_AW> for bool {
#[inline(always)]
fn from(variant: S13POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S13POWER`"]
pub struct S13POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S13POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S13POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S13POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Keep RAM section S14 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S14POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S14POWER_AW> for bool {
#[inline(always)]
fn from(variant: S14POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S14POWER`"]
pub struct S14POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S14POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S14POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S14POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Keep RAM section S15 of RAMn on or off in System ON mode\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S15POWER_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S15POWER_AW> for bool {
#[inline(always)]
fn from(variant: S15POWER_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S15POWER`"]
pub struct S15POWER_W<'a> {
w: &'a mut W,
}
impl<'a> S15POWER_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S15POWER_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S15POWER_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Keep retention on RAM section S0 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S0RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S0RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S0RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S0RETENTION`"]
pub struct S0RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S0RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S0RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S0RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Keep retention on RAM section S1 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S1RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S1RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S1RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S1RETENTION`"]
pub struct S1RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S1RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S1RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S1RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Keep retention on RAM section S2 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S2RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S2RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S2RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S2RETENTION`"]
pub struct S2RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S2RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S2RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S2RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Keep retention on RAM section S3 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S3RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S3RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S3RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S3RETENTION`"]
pub struct S3RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S3RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S3RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S3RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Keep retention on RAM section S4 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S4RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S4RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S4RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S4RETENTION`"]
pub struct S4RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S4RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S4RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S4RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Keep retention on RAM section S5 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S5RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S5RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S5RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S5RETENTION`"]
pub struct S5RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S5RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S5RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S5RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "Keep retention on RAM section S6 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S6RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S6RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S6RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S6RETENTION`"]
pub struct S6RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S6RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S6RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S6RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "Keep retention on RAM section S7 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S7RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S7RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S7RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S7RETENTION`"]
pub struct S7RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S7RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S7RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S7RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "Keep retention on RAM section S8 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S8RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S8RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S8RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S8RETENTION`"]
pub struct S8RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S8RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S8RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S8RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Keep retention on RAM section S9 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S9RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S9RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S9RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S9RETENTION`"]
pub struct S9RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S9RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S9RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S9RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Keep retention on RAM section S10 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S10RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S10RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S10RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S10RETENTION`"]
pub struct S10RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S10RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S10RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S10RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "Keep retention on RAM section S11 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S11RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S11RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S11RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S11RETENTION`"]
pub struct S11RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S11RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S11RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S11RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "Keep retention on RAM section S12 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S12RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S12RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S12RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S12RETENTION`"]
pub struct S12RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S12RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S12RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S12RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "Keep retention on RAM section S13 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S13RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S13RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S13RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S13RETENTION`"]
pub struct S13RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S13RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S13RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S13RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
#[doc = "Keep retention on RAM section S14 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S14RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S14RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S14RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S14RETENTION`"]
pub struct S14RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S14RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S14RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S14RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Keep retention on RAM section S15 when RAM section is switched off\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum S15RETENTION_AW {
#[doc = "1: Off"]
OFF = 1,
}
impl From<S15RETENTION_AW> for bool {
#[inline(always)]
fn from(variant: S15RETENTION_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Write proxy for field `S15RETENTION`"]
pub struct S15RETENTION_W<'a> {
w: &'a mut W,
}
impl<'a> S15RETENTION_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: S15RETENTION_AW) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Off"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(S15RETENTION_AW::OFF)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl W {
#[doc = "Bit 0 - Keep RAM section S0 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s0power(&mut self) -> S0POWER_W {
S0POWER_W { w: self }
}
#[doc = "Bit 1 - Keep RAM section S1 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s1power(&mut self) -> S1POWER_W {
S1POWER_W { w: self }
}
#[doc = "Bit 2 - Keep RAM section S2 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s2power(&mut self) -> S2POWER_W {
S2POWER_W { w: self }
}
#[doc = "Bit 3 - Keep RAM section S3 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s3power(&mut self) -> S3POWER_W {
S3POWER_W { w: self }
}
#[doc = "Bit 4 - Keep RAM section S4 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s4power(&mut self) -> S4POWER_W {
S4POWER_W { w: self }
}
#[doc = "Bit 5 - Keep RAM section S5 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s5power(&mut self) -> S5POWER_W {
S5POWER_W { w: self }
}
#[doc = "Bit 6 - Keep RAM section S6 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s6power(&mut self) -> S6POWER_W {
S6POWER_W { w: self }
}
#[doc = "Bit 7 - Keep RAM section S7 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s7power(&mut self) -> S7POWER_W {
S7POWER_W { w: self }
}
#[doc = "Bit 8 - Keep RAM section S8 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s8power(&mut self) -> S8POWER_W {
S8POWER_W { w: self }
}
#[doc = "Bit 9 - Keep RAM section S9 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s9power(&mut self) -> S9POWER_W {
S9POWER_W { w: self }
}
#[doc = "Bit 10 - Keep RAM section S10 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s10power(&mut self) -> S10POWER_W {
S10POWER_W { w: self }
}
#[doc = "Bit 11 - Keep RAM section S11 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s11power(&mut self) -> S11POWER_W {
S11POWER_W { w: self }
}
#[doc = "Bit 12 - Keep RAM section S12 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s12power(&mut self) -> S12POWER_W {
S12POWER_W { w: self }
}
#[doc = "Bit 13 - Keep RAM section S13 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s13power(&mut self) -> S13POWER_W {
S13POWER_W { w: self }
}
#[doc = "Bit 14 - Keep RAM section S14 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s14power(&mut self) -> S14POWER_W {
S14POWER_W { w: self }
}
#[doc = "Bit 15 - Keep RAM section S15 of RAMn on or off in System ON mode"]
#[inline(always)]
pub fn s15power(&mut self) -> S15POWER_W {
S15POWER_W { w: self }
}
#[doc = "Bit 16 - Keep retention on RAM section S0 when RAM section is switched off"]
#[inline(always)]
pub fn s0retention(&mut self) -> S0RETENTION_W {
S0RETENTION_W { w: self }
}
#[doc = "Bit 17 - Keep retention on RAM section S1 when RAM section is switched off"]
#[inline(always)]
pub fn s1retention(&mut self) -> S1RETENTION_W {
S1RETENTION_W { w: self }
}
#[doc = "Bit 18 - Keep retention on RAM section S2 when RAM section is switched off"]
#[inline(always)]
pub fn s2retention(&mut self) -> S2RETENTION_W {
S2RETENTION_W { w: self }
}
#[doc = "Bit 19 - Keep retention on RAM section S3 when RAM section is switched off"]
#[inline(always)]
pub fn s3retention(&mut self) -> S3RETENTION_W {
S3RETENTION_W { w: self }
}
#[doc = "Bit 20 - Keep retention on RAM section S4 when RAM section is switched off"]
#[inline(always)]
pub fn s4retention(&mut self) -> S4RETENTION_W {
S4RETENTION_W { w: self }
}
#[doc = "Bit 21 - Keep retention on RAM section S5 when RAM section is switched off"]
#[inline(always)]
pub fn s5retention(&mut self) -> S5RETENTION_W {
S5RETENTION_W { w: self }
}
#[doc = "Bit 22 - Keep retention on RAM section S6 when RAM section is switched off"]
#[inline(always)]
pub fn s6retention(&mut self) -> S6RETENTION_W {
S6RETENTION_W { w: self }
}
#[doc = "Bit 23 - Keep retention on RAM section S7 when RAM section is switched off"]
#[inline(always)]
pub fn s7retention(&mut self) -> S7RETENTION_W {
S7RETENTION_W { w: self }
}
#[doc = "Bit 24 - Keep retention on RAM section S8 when RAM section is switched off"]
#[inline(always)]
pub fn s8retention(&mut self) -> S8RETENTION_W {
S8RETENTION_W { w: self }
}
#[doc = "Bit 25 - Keep retention on RAM section S9 when RAM section is switched off"]
#[inline(always)]
pub fn s9retention(&mut self) -> S9RETENTION_W {
S9RETENTION_W { w: self }
}
#[doc = "Bit 26 - Keep retention on RAM section S10 when RAM section is switched off"]
#[inline(always)]
pub fn s10retention(&mut self) -> S10RETENTION_W {
S10RETENTION_W { w: self }
}
#[doc = "Bit 27 - Keep retention on RAM section S11 when RAM section is switched off"]
#[inline(always)]
pub fn s11retention(&mut self) -> S11RETENTION_W {
S11RETENTION_W { w: self }
}
#[doc = "Bit 28 - Keep retention on RAM section S12 when RAM section is switched off"]
#[inline(always)]
pub fn s12retention(&mut self) -> S12RETENTION_W {
S12RETENTION_W { w: self }
}
#[doc = "Bit 29 - Keep retention on RAM section S13 when RAM section is switched off"]
#[inline(always)]
pub fn s13retention(&mut self) -> S13RETENTION_W {
S13RETENTION_W { w: self }
}
#[doc = "Bit 30 - Keep retention on RAM section S14 when RAM section is switched off"]
#[inline(always)]
pub fn s14retention(&mut self) -> S14RETENTION_W {
S14RETENTION_W { w: self }
}
#[doc = "Bit 31 - Keep retention on RAM section S15 when RAM section is switched off"]
#[inline(always)]
pub fn s15retention(&mut self) -> S15RETENTION_W {
S15RETENTION_W { w: self }
}
} | #[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { |
children_vec.rs | // Copyright 2018-2021 Parity Technologies (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Provides an interface around the vector used to store elements of the
//! [`BinaryHeap`](`super::BinaryHeap`) in storage. This is necessary since
//! we don't just store each element in it's own storage cell, but rather
//! optimize storage access by putting children together in one storage cell.
use super::{
children,
children::Children,
StorageVec,
};
use crate::{
traits::{
KeyPtr,
PackedLayout,
SpreadLayout,
},
Lazy,
};
/// Provides an interface for accessing elements in the `BinaryHeap`.
///
/// Elements of the heap are stored in a vector of `Children` objects, whereby
/// each `Children` object contains two elements. When operating on indices of
/// the `BinaryHeap` this interface transposes heap indices to the child inside
/// the `Children` object, in which the element is stored.
#[derive(Default, PartialEq, Eq, Debug)]
pub struct ChildrenVec<T>
where
T: PackedLayout + Ord,
{
/// The number of elements stored in the heap.
/// We cannot use the length of the storage vector, since each entry (i.e. each
/// `Children` object) in the vector contains two child elements (except the root
/// element which occupies a `Children` object on its own.
len: Lazy<u32>,
/// The underlying storage vec containing the `Children`.
children: StorageVec<Children<T>>,
}
/// Encapsulates information regarding a particular child.
pub(super) struct ChildInfo<'a, T> {
/// A reference to the value in this child, if existent.
pub child: &'a Option<T>,
}
impl<'a, T> ChildInfo<'a, T> {
/// Creates a new `ChildInfo` object.
fn new(child: &'a Option<T>) -> Self {
Self { child }
}
}
/// Encapsulates information regarding a particular child.
pub(super) struct ChildInfoMut<'a, T> {
/// A mutable reference to the value in this child, if existent.
pub child: &'a mut Option<T>,
/// The number of children which are set in this `Children` object.
///
/// This property exists only in `ChildInfoMut`, but not in `ChildInfo`.
/// The reason is that in the case of pop-ping a child from a `Children`
/// object we need to check if the child count of that object is `0` after
/// the pop operation. In that case no children are left in the object
/// and it can be removed altogether from the heap.
pub child_count: usize,
}
impl<'a, T> ChildInfoMut<'a, T> {
/// Creates a new `ChildInfoMut` object.
fn new(child: &'a mut Option<T>, child_count: usize) -> Self {
Self { child, child_count }
}
}
impl<T> ChildrenVec<T>
where
T: PackedLayout + Ord,
{
/// Creates a new empty storage heap.
#[inline]
pub fn new() -> Self {
Self {
len: Lazy::new(0),
children: StorageVec::new(),
}
}
/// Returns the number of elements in the heap, also referred to as its 'length'.
#[inline]
pub fn len(&self) -> u32 {
*self.len
}
/// Returns the amount of `Children` objects stored in the vector.
#[allow(dead_code)]
#[cfg(all(test, feature = "ink-fuzz-tests"))]
pub fn children_count(&self) -> u32 {
self.children.len()
}
/// Returns `true` if the heap contains no elements.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns a shared reference to the indexed element.
///
/// Returns `None` if `index` is out of bounds.
pub fn get(&self, index: u32) -> Option<&T> {
self.get_child(index)?.child.as_ref()
}
/// Returns an exclusive reference to the indexed element.
/// The element in a `Children` is an `Option<T>`.
///
/// Returns `None` if `index` is out of bounds.
pub fn get_mut(&mut self, index: u32) -> Option<&mut T> {
let child_info = self.get_child_mut(index)?;
child_info.child.as_mut()
}
/// Swaps the elements at the given indices.
///
/// # Panics
///
/// If one or both indices are out of bounds.
pub fn swap(&mut self, a: u32, b: u32) {
if a == b {
return
}
assert!(a < self.len(), "a is out of bounds");
assert!(b < self.len(), "b is out of bounds");
let child_info_a = self.get_child_mut(a).expect("index a must exist");
let a_opt = child_info_a.child.take();
let child_info_b = self.get_child_mut(b).expect("index b must exist");
let b_opt = core::mem::replace(child_info_b.child, a_opt);
let child_info_a = self.get_child_mut(a).expect("index a must exist");
*child_info_a.child = b_opt;
}
/// Removes the element at `index` from the heap and returns it.
///
/// The last element of the heap is put into the slot at `index`.
/// Returns `None` and does not mutate the heap if it is empty.
pub fn swap_remove(&mut self, index: u32) -> Option<T> {
if self.is_empty() {
return None
}
self.swap(index, self.len() - 1);
self.pop()
}
/// Returns an iterator yielding shared references to all elements of the heap.
///
/// # Note
///
/// Avoid unbounded iteration over big storage heaps.
/// Prefer using methods like `Iterator::take` in order to limit the number
/// of yielded elements.
pub fn iter(&self) -> Iter<T> {
Iter::new(&self)
}
/// Returns a shared reference to the first element if any.
pub fn first(&self) -> Option<&T> {
if self.is_empty() {
return None
}
self.get(0)
}
/// Returns an exclusive reference to the first element if any.
pub fn first_mut(&mut self) -> Option<&mut T> {
if self.is_empty() {
return None
}
self.get_mut(0)
}
/// Removes all elements from this heap.
///
/// # Note
///
/// Use this method to clear the heap instead of e.g. iterative `pop()`.
/// This method performs significantly better and does not actually read
/// any of the elements (whereas `pop()` does).
pub fn clear(&mut self) {
if self.is_empty() {
return
}
self.children.clear();
self.len = Lazy::new(0);
}
/// Appends an element to the back of the heap.
pub fn push(&mut self, value: T) {
assert!(
self.len() < core::u32::MAX,
"cannot push more elements into the storage heap"
);
let last_index = self.len();
*self.len += 1;
self.insert(last_index, Some(value));
}
/// Returns information about the child at the heap index if any.
pub(super) fn get_child(&self, index: u32) -> Option<ChildInfo<T>> {
let storage_index = children::get_children_storage_index(index);
let child_pos = children::get_child_pos(index);
let children = self.children.get(storage_index)?;
let child = children.child(child_pos);
Some(ChildInfo::new(child))
}
/// Returns information about the child at the heap index if any.
///
/// The returned `ChildInfoMut` contains a mutable reference to the value `T`.
pub(super) fn get_child_mut(&mut self, index: u32) -> Option<ChildInfoMut<T>> {
let storage_index = children::get_children_storage_index(index);
let child_pos = children::get_child_pos(index);
let children = self.children.get_mut(storage_index)?;
let count = children.count();
let child = children.child_mut(child_pos);
Some(ChildInfoMut::new(child, count))
}
/// Inserts `value` at the heap index `index`.
///
/// If there is already a child in storage which `index` resolves to
/// then `value` is inserted there. Otherwise a new child is created.
fn insert(&mut self, index: u32, value: Option<T>) {
let info = self.get_child_mut(index);
if let Some(info) = info {
*info.child = value;
return
}
self.children.push(Children::new(value, None));
debug_assert!(
{
let storage_index = children::get_children_storage_index(index);
self.children.get(storage_index).is_some()
},
"the new children were not placed at children_index!"
);
}
/// Pops the last element from the heap and returns it.
//
/// Returns `None` if the heap is empty.
fn pop(&mut self) -> Option<T> {
if self.is_empty() {
return None
}
let last_index = self.len() - 1;
*self.len = last_index;
let info = self
.get_child_mut(last_index)
.expect("children must exist at last_index");
let popped_val = info.child.take();
if info.child_count == 1 {
// if both children are non-existent the entire `Children` object can be removed
self.children.pop();
}
popped_val
}
}
impl<T> SpreadLayout for ChildrenVec<T>
where
T: SpreadLayout + Ord + PackedLayout,
{
const FOOTPRINT: u64 = 1 + <StorageVec<Children<T>> as SpreadLayout>::FOOTPRINT;
fn pull_spread(ptr: &mut KeyPtr) -> Self |
fn push_spread(&self, ptr: &mut KeyPtr) {
SpreadLayout::push_spread(&self.len, ptr);
SpreadLayout::push_spread(&self.children, ptr);
}
fn clear_spread(&self, ptr: &mut KeyPtr) {
SpreadLayout::clear_spread(&self.len, ptr);
SpreadLayout::clear_spread(&self.children, ptr);
}
}
/// An iterator over shared references to the elements of the `BinaryHeap`.
#[derive(Debug, Clone, Copy)]
pub struct Iter<'a, T>
where
T: PackedLayout + Ord,
{
/// The heap elements to iterate over.
elements: &'a ChildrenVec<T>,
/// The current begin of the iteration.
begin: u32,
/// The current end of the iteration.
end: u32,
}
impl<'a, T> Iter<'a, T>
where
T: PackedLayout + Ord,
{
/// Creates a new iterator for the given heap elements.
pub fn new(elements: &'a ChildrenVec<T>) -> Self {
Self {
elements,
begin: 0,
end: elements.len(),
}
}
/// Returns the amount of remaining elements to yield by the iterator.
fn remaining(&self) -> u32 {
self.end - self.begin
}
}
impl<'a, T> Iterator for Iter<'a, T>
where
T: PackedLayout + Ord,
{
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
<Self as Iterator>::nth(self, 0)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.remaining() as usize;
(remaining, Some(remaining))
}
fn count(self) -> usize {
self.remaining() as usize
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
debug_assert!(self.begin <= self.end);
let n = n as u32;
if self.begin + n >= self.end {
return None
}
let cur = self.begin + n;
self.begin += 1 + n;
self.elements.get_child(cur)?.child.as_ref()
}
}
| {
let len = SpreadLayout::pull_spread(ptr);
let children = SpreadLayout::pull_spread(ptr);
Self { len, children }
} |
klaytn.subscriptions.example.ts | import { TatumKlaytnSDK } from '@tatumio/klaytn'
import { REPLACE_ME_WITH_TATUM_API_KEY } from '@tatumio/shared-testing-common'
const klaytnSDK = TatumKlaytnSDK({ apiKey: REPLACE_ME_WITH_TATUM_API_KEY })
| const id = await klaytnSDK.subscriptions.createSubscription({
// TODO openapi bug
type: 'ACCOUNT_INCOMING_BLOCKCHAIN_TRANSACTION',
attr: {
id: '5e6be8e9e6aa436299950c41',
url: 'https://webhook.tatum.io/account',
},
})
await klaytnSDK.subscriptions.deleteSubscription('5e68c66581f2ee32bc354087')
await klaytnSDK.subscriptions.disableWebHookHmac()
await klaytnSDK.subscriptions.enableWebHookHmac({
hmacSecret: '1f7f7c0c-3906-4aa1-9dfe-4b67c43918f6',
})
const subscriptionReport = await klaytnSDK.subscriptions.getSubscriptionReport('5e68c66581f2ee32bc354087')
const subscriptions = await klaytnSDK.subscriptions.getSubscriptions(10)
} | export async function klaytnSubscriptionsExample() { |
properties.rs | use crate::{
bindings::{
fpgaCloneProperties, fpgaDestroyProperties, fpgaEnumerate, fpgaGetProperties,
fpgaPropertiesGetAcceleratorState, fpgaPropertiesGetBBSID, fpgaPropertiesGetBBSVersion,
fpgaPropertiesGetBus, fpgaPropertiesGetCapabilities, fpgaPropertiesGetDevice,
fpgaPropertiesGetDeviceID, fpgaPropertiesGetFunction, fpgaPropertiesGetGUID,
fpgaPropertiesGetLocalMemorySize, fpgaPropertiesGetModel, fpgaPropertiesGetNumErrors,
fpgaPropertiesGetNumInterrupts, fpgaPropertiesGetNumMMIO, fpgaPropertiesGetNumSlots,
fpgaPropertiesGetObjectID, fpgaPropertiesGetSegment, fpgaPropertiesGetSocketID,
fpgaPropertiesGetVendorID, fpgaPropertiesSetAcceleratorState, fpgaPropertiesSetBBSID,
fpgaPropertiesSetBBSVersion, fpgaPropertiesSetBus, fpgaPropertiesSetCapabilities,
fpgaPropertiesSetDevice, fpgaPropertiesSetDeviceID, fpgaPropertiesSetFunction,
fpgaPropertiesSetGUID, fpgaPropertiesSetLocalMemorySize, fpgaPropertiesSetModel,
fpgaPropertiesSetNumErrors, fpgaPropertiesSetNumInterrupts, fpgaPropertiesSetNumMMIO,
fpgaPropertiesSetNumSlots, fpgaPropertiesSetObjectID, fpgaPropertiesSetObjectType,
fpgaPropertiesSetSegment, fpgaPropertiesSetSocketID, fpgaPropertiesSetVendorID,
fpga_accelerator_state, fpga_properties, fpga_version,
},
Filter, Result, Token,
};
use log::{error, trace};
use std::{
ffi::CString,
ops::{Deref, DerefMut, Not},
ptr,
};
use uuid::Uuid;
#[derive(Debug)]
pub struct Properties(fpga_properties);
impl Properties {
pub fn from_raw(properties: fpga_properties) -> Self {
Properties(properties)
} | Result::from(unsafe { fpgaGetProperties(**token, &mut properties) })?;
Ok(Self::from_raw(properties))
}
pub fn num_matches(&mut self) -> usize {
let mut num_matches = 0;
Result::from(unsafe { fpgaEnumerate(&**self, 1, ptr::null_mut(), 0, &mut num_matches) })
.map(|_| num_matches as usize)
.unwrap_or(0)
}
pub fn from_filter(filter: Filter) -> Result<Self> {
let mut properties: fpga_properties = ptr::null_mut();
Result::from(unsafe { fpgaGetProperties(ptr::null_mut(), &mut properties) })?;
if let Some(pci_bus_nr) = filter.pci_bus_nr {
Result::from(unsafe { fpgaPropertiesSetBus(properties, pci_bus_nr) })?;
}
if let Some(guid) = filter.guid {
Result::from(unsafe {
fpgaPropertiesSetGUID(properties, guid.as_bytes().to_owned().as_mut_ptr())
})?;
}
if let Some(bbs_id) = filter.bbs_id {
Result::from(unsafe { fpgaPropertiesSetBBSID(properties, bbs_id) })?;
}
if let Some(model) = filter.model {
Result::from(unsafe { fpgaPropertiesSetModel(properties, model.into_raw()) })?;
}
if let Some(pci_device_nr) = filter.pci_device_nr {
Result::from(unsafe { fpgaPropertiesSetDevice(properties, pci_device_nr) })?;
}
if let Some(num_mmio_spaces) = filter.num_mmio_spaces {
Result::from(unsafe { fpgaPropertiesSetNumMMIO(properties, num_mmio_spaces) })?;
}
if let Some(pci_segment_nr) = filter.pci_segment_nr {
Result::from(unsafe { fpgaPropertiesSetSegment(properties, pci_segment_nr) })?;
}
if let Some(device_id) = filter.device_id {
Result::from(unsafe { fpgaPropertiesSetDeviceID(properties, device_id) })?;
}
if let Some(pci_function_nr) = filter.pci_function_nr {
Result::from(unsafe { fpgaPropertiesSetFunction(properties, pci_function_nr) })?;
}
if let Some(num_slots) = filter.num_slots {
Result::from(unsafe { fpgaPropertiesSetNumSlots(properties, num_slots) })?;
}
if let Some(object_id) = filter.object_id {
Result::from(unsafe { fpgaPropertiesSetObjectID(properties, object_id) })?;
}
if let Some(socket_id) = filter.socket_id {
Result::from(unsafe { fpgaPropertiesSetSocketID(properties, socket_id) })?;
}
if let Some(vendor_id) = filter.vendor_id {
Result::from(unsafe { fpgaPropertiesSetVendorID(properties, vendor_id) })?;
}
if let Some(num_error_registers) = filter.num_error_registers {
Result::from(unsafe { fpgaPropertiesSetNumErrors(properties, num_error_registers) })?;
}
if let Some(bbs_version) = filter.bbs_version {
Result::from(unsafe { fpgaPropertiesSetBBSVersion(properties, bbs_version) })?;
}
if let Some(obj_type) = filter.obj_type {
Result::from(unsafe { fpgaPropertiesSetObjectType(properties, obj_type) })?;
}
if let Some(capabilities) = filter.capabilities {
Result::from(unsafe { fpgaPropertiesSetCapabilities(properties, capabilities) })?;
}
if let Some(num_interrupts) = filter.num_interrupts {
Result::from(unsafe { fpgaPropertiesSetNumInterrupts(properties, num_interrupts) })?;
}
if let Some(local_memory_size) = filter.local_memory_size {
Result::from(unsafe {
fpgaPropertiesSetLocalMemorySize(properties, local_memory_size)
})?;
}
if let Some(accelerator_state) = filter.accelerator_state {
Result::from(unsafe {
fpgaPropertiesSetAcceleratorState(properties, accelerator_state)
})?;
}
Ok(Self(properties))
}
}
impl Clone for Properties {
fn clone(&self) -> Self {
let mut properties = ptr::null_mut();
Result::from(unsafe { fpgaCloneProperties(self.0, &mut properties) }).unwrap();
Self(properties)
}
}
impl Deref for Properties {
type Target = fpga_properties;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Properties {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Drop for Properties {
fn drop(&mut self) {
trace!("Dropping Properties: {:p}", self.0);
if Result::from(unsafe { fpgaDestroyProperties(&mut self.0) }).is_err() {
error!("Failed to destroy properties object");
}
}
}
pub trait ResourceProperties {
fn properties(&self) -> &Properties;
fn device_id(&self) -> Result<u16> {
let mut device_id = Default::default();
Result::from(unsafe { fpgaPropertiesGetDeviceID(**self.properties(), &mut device_id) })
.map(|_| device_id)
}
fn guid(&self) -> Result<Uuid> {
let mut guid = [Default::default(); 16];
Result::from(unsafe { fpgaPropertiesGetGUID(**self.properties(), &mut guid) })
.map(|_| Uuid::from_bytes(guid))
}
fn object_id(&self) -> Result<u64> {
let mut object_id = Default::default();
Result::from(unsafe { fpgaPropertiesGetObjectID(**self.properties(), &mut object_id) })
.map(|_| object_id)
}
fn pci_bus_nr(&self) -> Result<u8> {
let mut pci_bus_nr = Default::default();
Result::from(unsafe { fpgaPropertiesGetBus(**self.properties(), &mut pci_bus_nr) })
.map(|_| pci_bus_nr)
}
fn pci_device_nr(&self) -> Result<u8> {
let mut pci_device_nr = Default::default();
Result::from(unsafe { fpgaPropertiesGetDevice(**self.properties(), &mut pci_device_nr) })
.map(|_| pci_device_nr)
}
fn pci_function_nr(&self) -> Result<u8> {
let mut pci_function_nr = Default::default();
Result::from(unsafe {
fpgaPropertiesGetFunction(**self.properties(), &mut pci_function_nr)
})
.map(|_| pci_function_nr)
}
fn pci_segment_nr(&self) -> Result<u16> {
let mut pci_segment_nr = Default::default();
Result::from(unsafe { fpgaPropertiesGetSegment(**self.properties(), &mut pci_segment_nr) })
.map(|_| pci_segment_nr)
}
fn socket_id(&self) -> Result<u8> {
let mut socket_id = Default::default();
Result::from(unsafe { fpgaPropertiesGetSocketID(**self.properties(), &mut socket_id) })
.map(|_| socket_id)
}
}
pub trait DeviceProperties: ResourceProperties {
fn bbs_id(&self) -> Result<u64> {
let mut bbs_id = Default::default();
Result::from(unsafe { fpgaPropertiesGetBBSID(**self.properties(), &mut bbs_id) })
.map(|_| bbs_id)
}
fn bbs_version(&self) -> Result<fpga_version> {
let mut bbs_version = Default::default();
Result::from(unsafe { fpgaPropertiesGetBBSVersion(**self.properties(), &mut bbs_version) })
.map(|_| bbs_version)
}
fn capabilities(&self) -> Result<u64> {
let mut capabilities = Default::default();
Result::from(unsafe {
fpgaPropertiesGetCapabilities(**self.properties(), &mut capabilities)
})
.map(|_| capabilities)
}
fn local_memory_size(&self) -> Result<u64> {
let mut local_memory_size = Default::default();
Result::from(unsafe {
fpgaPropertiesGetLocalMemorySize(**self.properties(), &mut local_memory_size)
})
.map(|_| local_memory_size)
}
fn model(&self) -> Result<String> {
let mut model = Vec::with_capacity(u8::MAX as usize); // FPGA_MODEL_LENGTH not defined;
Result::from(unsafe { fpgaPropertiesGetModel(**self.properties(), model.as_mut_ptr()) })
.map(|_| {
unsafe { CString::from_raw(model.as_mut_ptr()) }
.into_string()
.unwrap_or_else(|_| String::from("?"))
})
}
fn num_slots(&self) -> Result<u32> {
let mut num_slots = Default::default();
Result::from(unsafe { fpgaPropertiesGetNumSlots(**self.properties(), &mut num_slots) })
.map(|_| num_slots)
}
fn vendor_id(&self) -> Result<u16> {
let mut vendor_id = Default::default();
Result::from(unsafe { fpgaPropertiesGetVendorID(**self.properties(), &mut vendor_id) })
.map(|_| vendor_id)
}
}
pub trait AcceleratorProperties: ResourceProperties {
fn is_assigned(&self) -> Result<bool> {
let mut state = fpga_accelerator_state::FPGA_ACCELERATOR_UNASSIGNED;
Result::from(unsafe { fpgaPropertiesGetAcceleratorState(**self.properties(), &mut state) })
.map(|_| matches!(state, fpga_accelerator_state::FPGA_ACCELERATOR_ASSIGNED))
}
fn is_unassigned(&self) -> Result<bool> {
self.is_assigned().map(Not::not)
}
fn num_error_registers(&self) -> Result<u32> {
let mut num_error_registers = Default::default();
Result::from(unsafe {
fpgaPropertiesGetNumErrors(**self.properties(), &mut num_error_registers)
})
.map(|_| num_error_registers)
}
fn num_interrupts(&self) -> Result<u32> {
let mut num_interrupts = Default::default();
Result::from(unsafe {
fpgaPropertiesGetNumInterrupts(**self.properties(), &mut num_interrupts)
})
.map(|_| num_interrupts)
}
fn num_mmio_spaces(&self) -> Result<u32> {
let mut num_mmio_spaces = Default::default();
Result::from(unsafe { fpgaPropertiesGetNumMMIO(**self.properties(), &mut num_mmio_spaces) })
.map(|_| num_mmio_spaces)
}
} |
pub fn from_token(token: &Token) -> Result<Self> {
let mut properties = ptr::null_mut(); |
accounts.py | """
bank.accounts
~~~~~~~~~~~~~
This module contains code for managing accounts.
"""
from .cards import Card
from .exceptions import InsufficientBalance, AccountError, ExceedsLimit
import time, datetime
class Account:
"""
Base class for accounts, handles balances & transactions.
:param account_id: Unique ID associated with the account.
:param account_type: Type of account (savings, checkings, credit).
:param holder_accounts: An AccountHolder.Accounts() class.
:param accountholder_id: Unique ID of the account holder.
:param opening_balance: When account is created the opening amount of $.
:param open_date: Date the account was opened.
:param status: Status of the account (open, closed, locked).
"""
def __init__(
self,
account_id: int,
account_type: str,
holder_accounts,
accountholder_id: str,
opening_balance=0,
open_date=datetime.date.today(),
status: str = "open",
):
self.account_id = account_id
self.account_type = account_type
self.holder_accounts = holder_accounts
self.accountholder_id = account_id
self.balance = opening_balance if opening_balance >= 0 else 0
self.open_date = open_date
self.status = status
self.linked_cards = {}
self.withdrawal_limit = 5000
def withdraw(self, amount: float) -> dict:
"""'
Method to withdraw funds from account.
:param amount: Transaction amount.
"""
# Assuming there can be $0.
if self.status != "open":
raise AccountError(self.account_id, self.status)
elif amount > self.withdrawal_limit:
raise ExceedsLimit(self.withdrawal_limit)
elif amount > self.balance:
raise InsufficientBalance(self.balance, amount)
else:
self.balance -= amount
return {
"status": True,
"new_balance": self.balance,
"transaction_time": time.time(),
}
def deposit(self, amount: float) -> dict:
"""
Method to deposit funds to an account.
:param amount: Transaction amount.
"""
if self.status != "open":
raise AccountError(self.account_id, self.status)
self.balance += amount
return {
"status": True,
"new_balance": self.balance,
"transaction_time": time.time(),
}
class CheckingAccount(Account):
|
class SavingsAccount(Account):
"""
Class for savings accounts, inherits base account class.
:param account_id: Unique ID associated with the account.
:param account_type: Type of account (savings, checkings, credit).
:param holder_accounts: An AccountHolder.Accounts() class.
:param accountholder_id: Unique ID of the account holder.
:param opening_balance: When account is created the opening amount of $.
:param open_date: Date the account was opened.
:param status: Status of the account (open, closed, frozen).
:kwarg interest: The interest of the savings account.
"""
def __init__(
self,
account_id: int,
account_type: str,
holder_accounts,
accountholder_id: str,
opening_balance=0,
open_date=datetime.date.today(),
status: str = "open",
interest_rate=0.001,
):
super().__init__(
account_id,
account_type,
holder_accounts,
accountholder_id,
opening_balance,
open_date,
status,
)
self.account_type = account_type
self.interest_rate = interest_rate
self.holder_accounts.saving_accounts[self.account_id] = self
class CreditAccount(Account):
"""
Class for credit accounts, inherits base account class.
:param account_id: Unique ID associated with the account.
:param account_type: Type of account (savings, checkings, credit).
:param holder_accounts: An AccountHolder.Accounts() class.
:param accountholder_id: Unique ID of the account holder.
:param opening_balance: When account is created the opening amount of $.
:param open_date: Date the account was opened.
:param status: Status of the account (open, closed, frozen).
:kwarg apr: the APR charged on outstanding balance.
"""
def __init__(
self,
account_id: int,
account_type: str,
holder_accounts,
accountholder_id: str,
opening_balance=0,
open_date=datetime.date.today(),
status: str = "open",
apr_rate=0.15,
):
super().__init__(
account_id,
account_type,
accountholder_id,
opening_balance,
open_date,
status,
)
self.account_type = account_type
self.apr_rate = apr_rate
self.holderaccounts.credit_accounts[self.account_id] = self
# self.billing_end =
# self.balance_due =
# .
# .
# etc etc.
class Accounts:
"""
Class that maintains the relations between account holders, accounts and cards.
:param holder: AccountHolder object holding account holder information.
:param accountholder_id: ID of account holder.
"""
def __init__(self, holder, accountholder_id: str):
self.holder = holder
self.accountholder_id = accountholder_id
self.checking_accounts = {}
self.saving_accounts = {}
self.credit_accounts = {}
self.issued_cards = {}
@property
def holder_info(self):
"""
Summary of the account holder who is linked with the accounts.
"""
return self.holder.__repr__
@property
def accounts(self):
"""
Str summary of number of accounts.
"""
return "".join(
[
f"Accounts: Checking: {len(self.checking_accounts)}, ",
f"Savings: {len(self.saving_accounts)}, ",
f"Credit: {len(self.credit_accounts)}",
]
)
@property
def total_balance(self) -> int:
"""
Total balance of all accounts.
"""
return self._checking_balance + self._savings_balance + self._credit_balance
@property
def _checking_balance(self) -> int:
"""
Total balance of all checking accounts.
"""
bal = 0
for id, obj in self.checking_accounts.items():
bal += obj.balance
return bal
@property
def _savings_balance(self) -> int:
"""
Total balance of all savings accounts.
"""
bal = 0
for id, obj in self.saving_accounts.items():
bal += obj.balance
return bal
@property
def _credit_balance(self) -> int:
"""
Total balance of all credit accounts.
"""
bal = 0
for id, obj in self.credit_accounts.items():
bal += obj.balance
return bal
| """
Class for checking accounts, inherits base account class.
:param account_id: Unique ID associated with the account.
:param account_type: Type of account (savings, checkings, credit).
:param holder_accounts: An AccountHolder.Accounts() class.
:param accountholder_id: Unique ID of the account holder.
:param opening_balance: When account is created the opening amount of $.
:param open_date: Date the account was opened.
:param status: Status of the account (open, closed, frozen).
"""
def __init__(
self,
account_id: int,
account_type: str,
holder_accounts,
accountholder_id: str,
opening_balance=0,
open_date=datetime.date.today(),
status: str = "open",
):
super().__init__(
account_id,
account_type,
holder_accounts,
accountholder_id,
opening_balance,
open_date,
status,
)
self.account_type = "checking"
self.holder_accounts.checking_accounts[self.account_id] = self |
party_coordinator_test_with_leader_test.go | package p2p
import (
"context"
"math/rand"
"sort"
"sync"
"testing"
"time"
"github.com/libp2p/go-libp2p-core/host"
tnet "github.com/libp2p/go-libp2p-testing/net"
mocknet "github.com/libp2p/go-libp2p/p2p/net/mock"
"github.com/stretchr/testify/assert"
"github.com/akildemir/moneroTss/conversion"
)
func setupHosts(t *testing.T, n int) []host.Host {
mn := mocknet.New(context.Background())
var hosts []host.Host
for i := 0; i < n; i++ {
id := tnet.RandIdentityOrFatal(t)
a := tnet.RandLocalTCPAddress()
h, err := mn.AddPeer(id.PrivateKey(), a)
if err != nil {
t.Fatal(err)
}
hosts = append(hosts, h)
}
if err := mn.LinkAll(); err != nil {
t.Error(err)
}
if err := mn.ConnectAllButSelf(); err != nil {
t.Error(err)
}
return hosts
}
func leaderAppearsLastTest(t *testing.T, msgID string, peers []string, pcs []*PartyCoordinator) {
wg := sync.WaitGroup{}
for _, el := range pcs[1:] {
wg.Add(1)
go func(coordinator *PartyCoordinator) {
defer wg.Done()
// we simulate different nodes join at different time
time.Sleep(time.Millisecond * time.Duration(rand.Int()%100))
sigChan := make(chan string)
onlinePeers, _, err := coordinator.JoinPartyWithLeader(msgID, 10, peers, 3, sigChan)
assert.Nil(t, err)
assert.Len(t, onlinePeers, 4)
}(el)
}
time.Sleep(time.Second * 2)
// we start the leader firstly
wg.Add(1)
go func(coordinator *PartyCoordinator) {
defer wg.Done()
sigChan := make(chan string)
// we simulate different nodes join at different time
onlinePeers, _, err := coordinator.JoinPartyWithLeader(msgID, 10, peers, 3, sigChan)
assert.Nil(t, err)
assert.Len(t, onlinePeers, 4)
}(pcs[0])
wg.Wait()
}
func leaderAppersFirstTest(t *testing.T, msgID string, peers []string, pcs []*PartyCoordinator) {
wg := sync.WaitGroup{}
wg.Add(1)
// we start the leader firstly
go func(coordinator *PartyCoordinator) {
defer wg.Done()
// we simulate different nodes join at different time
sigChan := make(chan string)
onlinePeers, _, err := coordinator.JoinPartyWithLeader(msgID, 10, peers, 3, sigChan)
assert.Nil(t, err)
assert.Len(t, onlinePeers, 4)
}(pcs[0])
time.Sleep(time.Second)
for _, el := range pcs[1:] {
wg.Add(1)
go func(coordinator *PartyCoordinator) {
defer wg.Done()
// we simulate different nodes join at different time
time.Sleep(time.Millisecond * time.Duration(rand.Int()%100))
sigChan := make(chan string)
onlinePeers, _, err := coordinator.JoinPartyWithLeader(msgID, 10, peers, 3, sigChan)
assert.Nil(t, err)
assert.Len(t, onlinePeers, 4)
}(el) |
func TestNewPartyCoordinator(t *testing.T) {
ApplyDeadline = false
hosts := setupHosts(t, 4)
var pcs []*PartyCoordinator
var peers []string
timeout := time.Second * 4
for _, el := range hosts {
pcs = append(pcs, NewPartyCoordinator(el, timeout))
peers = append(peers, el.ID().String())
}
defer func() {
for _, el := range pcs {
el.Stop()
}
}()
msgID := conversion.RandStringBytesMask(64)
leader, err := LeaderNode(msgID, 10, peers)
assert.Nil(t, err)
// we sort the slice to ensure the leader is the first one easy for testing
for i, el := range pcs {
if el.host.ID().String() == leader {
if i == 0 {
break
}
temp := pcs[0]
pcs[0] = el
pcs[i] = temp
break
}
}
assert.Equal(t, pcs[0].host.ID().String(), leader)
// now we test the leader appears firstly and the the members
leaderAppersFirstTest(t, msgID, peers, pcs)
leaderAppearsLastTest(t, msgID, peers, pcs)
}
func TestNewPartyCoordinatorTimeOut(t *testing.T) {
ApplyDeadline = false
timeout := time.Second * 3
hosts := setupHosts(t, 4)
var pcs []*PartyCoordinator
var peers []string
for _, el := range hosts {
pcs = append(pcs, NewPartyCoordinator(el, timeout))
}
sort.Slice(pcs, func(i, j int) bool {
return pcs[i].host.ID().String() > pcs[j].host.ID().String()
})
for _, el := range pcs {
peers = append(peers, el.host.ID().String())
}
defer func() {
for _, el := range pcs {
el.Stop()
}
}()
msgID := conversion.RandStringBytesMask(64)
wg := sync.WaitGroup{}
leader, err := LeaderNode(msgID, 10, peers)
assert.Nil(t, err)
// we sort the slice to ensure the leader is the first one easy for testing
for i, el := range pcs {
if el.host.ID().String() == leader {
if i == 0 {
break
}
temp := pcs[0]
pcs[0] = el
pcs[i] = temp
break
}
}
assert.Equal(t, pcs[0].host.ID().String(), leader)
// we test the leader is offline
for _, el := range pcs[1:] {
wg.Add(1)
go func(coordinator *PartyCoordinator) {
defer wg.Done()
sigChan := make(chan string)
_, _, err := coordinator.JoinPartyWithLeader(msgID, 10, peers, 3, sigChan)
assert.Equal(t, err, ErrLeaderNotReady)
}(el)
}
wg.Wait()
// we test one of node is not ready
var expected []string
for _, el := range pcs[:3] {
expected = append(expected, el.host.ID().String())
wg.Add(1)
go func(coordinator *PartyCoordinator) {
defer wg.Done()
sigChan := make(chan string)
onlinePeers, _, err := coordinator.JoinPartyWithLeader(msgID, 10, peers, 3, sigChan)
assert.Equal(t, ErrJoinPartyTimeout, err)
var onlinePeersStr []string
for _, el := range onlinePeers {
onlinePeersStr = append(onlinePeersStr, el.String())
}
sort.Strings(onlinePeersStr)
sort.Strings(expected)
sort.Strings(expected[:3])
assert.EqualValues(t, expected, onlinePeersStr)
}(el)
}
wg.Wait()
}
func TestGetPeerIDs(t *testing.T) {
ApplyDeadline = false
id1 := tnet.RandIdentityOrFatal(t)
mn := mocknet.New(context.Background())
// add peers to mock net
a1 := tnet.RandLocalTCPAddress()
h1, err := mn.AddPeer(id1.PrivateKey(), a1)
if err != nil {
t.Fatal(err)
}
p1 := h1.ID()
timeout := time.Second * 2
pc := NewPartyCoordinator(h1, timeout)
r, err := pc.getPeerIDs([]string{})
assert.Nil(t, err)
assert.Len(t, r, 0)
input := []string{
p1.String(),
}
r1, err := pc.getPeerIDs(input)
assert.Nil(t, err)
assert.Len(t, r1, 1)
assert.Equal(t, r1[0], p1)
input = append(input, "whatever")
r2, err := pc.getPeerIDs(input)
assert.NotNil(t, err)
assert.Len(t, r2, 0)
} | }
wg.Wait()
} |
mgr.go | /*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package cceventmgmt
import (
"sync"
"github.com/hyperledger/fabric/common/flogging"
"github.com/hyperledger/fabric/core/ledger"
)
var logger = flogging.MustGetLogger("cceventmgmt")
var mgr *Mgr
// Initialize initializes event mgmt
func Initialize(ccInfoProvider ChaincodeInfoProvider) {
initialize(ccInfoProvider)
}
func initialize(ccInfoProvider ChaincodeInfoProvider) {
mgr = newMgr(ccInfoProvider)
}
// GetMgr returns the reference to singleton event manager
func GetMgr() *Mgr {
return mgr
}
// Mgr encapsulate important interactions for events related to the interest of ledger
type Mgr struct {
// rwlock is mainly used to synchronize across deploy transaction, chaincode install, and channel creation
// Ideally, different services in the peer should be designed such that they expose locks for different important
// events so that a code on top can synchronize across if needs to. However, in the lack of any such system-wide design,
// we use this lock for contextual use
rwlock sync.RWMutex
infoProvider ChaincodeInfoProvider
ccLifecycleListeners map[string][]ChaincodeLifecycleEventListener
callbackStatus *callbackStatus
}
func newMgr(chaincodeInfoProvider ChaincodeInfoProvider) *Mgr {
return &Mgr{
infoProvider: chaincodeInfoProvider,
ccLifecycleListeners: make(map[string][]ChaincodeLifecycleEventListener),
callbackStatus: newCallbackStatus()}
}
// Register registers a ChaincodeLifecycleEventListener for given ledgerid
// Since, `Register` is expected to be invoked when creating/opening a ledger instance
func (m *Mgr) Register(ledgerid string, l ChaincodeLifecycleEventListener) {
// write lock to synchronize concurrent 'chaincode install' operations with ledger creation/open
m.rwlock.Lock()
defer m.rwlock.Unlock()
m.ccLifecycleListeners[ledgerid] = append(m.ccLifecycleListeners[ledgerid], l)
}
// HandleChaincodeDeploy is expected to be invoked when a chaincode is deployed via a deploy transaction
// The `chaincodeDefinitions` parameter contains all the chaincodes deployed in a block
// We need to store the last received `chaincodeDefinitions` because this function is expected to be invoked
// after the deploy transactions validation is performed but not committed yet to the ledger. Further, we
// release the read lock after this function. This leaves a small window when a `chaincode install` can happen
// before the deploy transaction is committed and hence the function `HandleChaincodeInstall` may miss finding
// the deployed chaincode. So, in function `HandleChaincodeInstall`, we explicitly check for chaincode deployed
// in this stored `chaincodeDefinitions`
func (m *Mgr) HandleChaincodeDeploy(chainid string, chaincodeDefinitions []*ChaincodeDefinition) error {
logger.Debugf("Channel [%s]: Handling chaincode deploy event for chaincode [%s]", chainid, chaincodeDefinitions)
// Read lock to allow concurrent deploy on multiple channels but to synchronize concurrent `chaincode install` operation
m.rwlock.RLock()
for _, chaincodeDefinition := range chaincodeDefinitions {
installed, dbArtifacts, err := m.infoProvider.RetrieveChaincodeArtifacts(chaincodeDefinition)
if err != nil {
return err
}
if !installed {
logger.Infof("Channel [%s]: Chaincode [%s] is not installed hence no need to create chaincode artifacts for endorsement",
chainid, chaincodeDefinition)
continue
}
m.callbackStatus.setDeployPending(chainid)
if err := m.invokeHandler(chainid, chaincodeDefinition, dbArtifacts); err != nil {
logger.Warningf("Channel [%s]: Error while invoking a listener for handling chaincode install event: %s", chainid, err)
return err
}
logger.Debugf("Channel [%s]: Handled chaincode deploy event for chaincode [%s]", chainid, chaincodeDefinitions)
}
return nil
}
// ChaincodeDeployDone is expected to be called when the deploy transaction state is committed
func (m *Mgr) ChaincodeDeployDone(chainid string) {
// release the lock acquired in function `HandleChaincodeDeploy`
defer m.rwlock.RUnlock()
if m.callbackStatus.isDeployPending(chainid) {
m.invokeDoneOnHandlers(chainid, true)
m.callbackStatus.unsetDeployPending(chainid)
}
}
// HandleChaincodeInstall is expected to get invoked during installation of a chaincode package
func (m *Mgr) HandleChaincodeInstall(chaincodeDefinition *ChaincodeDefinition, dbArtifacts []byte) error {
logger.Debugf("HandleChaincodeInstall() - chaincodeDefinition=%#v", chaincodeDefinition)
// Write lock prevents concurrent deploy operations
m.rwlock.Lock()
for chainid := range m.ccLifecycleListeners {
logger.Debugf("Channel [%s]: Handling chaincode install event for chaincode [%s]", chainid, chaincodeDefinition)
var deployedCCInfo *ledger.DeployedChaincodeInfo
var err error
if deployedCCInfo, err = m.infoProvider.GetDeployedChaincodeInfo(chainid, chaincodeDefinition); err != nil {
logger.Warningf("Channel [%s]: Error while getting the deployment status of chaincode: %s", chainid, err)
return err
}
if deployedCCInfo == nil {
logger.Debugf("Channel [%s]: Chaincode [%s] is not deployed on channel hence not creating chaincode artifacts.",
chainid, chaincodeDefinition)
continue
}
m.callbackStatus.setInstallPending(chainid)
chaincodeDefinition.CollectionConfigs = deployedCCInfo.CollectionConfigPkg
if err := m.invokeHandler(chainid, chaincodeDefinition, dbArtifacts); err != nil {
logger.Warningf("Channel [%s]: Error while invoking a listener for handling chaincode install event: %s", chainid, err)
return err
}
logger.Debugf("Channel [%s]: Handled chaincode install event for chaincode [%s]", chainid, chaincodeDefinition)
}
return nil
}
// ChaincodeInstallDone is expected to get invoked when chaincode install finishes
func (m *Mgr) ChaincodeInstallDone(succeeded bool) {
// release the lock acquired in function `HandleChaincodeInstall`
defer m.rwlock.Unlock()
for chainid := range m.callbackStatus.installPending {
m.invokeDoneOnHandlers(chainid, succeeded)
m.callbackStatus.unsetInstallPending(chainid)
}
}
func (m *Mgr) invokeHandler(chainid string, chaincodeDefinition *ChaincodeDefinition, dbArtifactsTar []byte) error {
listeners := m.ccLifecycleListeners[chainid]
for _, listener := range listeners {
if err := listener.HandleChaincodeDeploy(chaincodeDefinition, dbArtifactsTar); err != nil {
return err
}
}
return nil
}
func (m *Mgr) invokeDoneOnHandlers(chainid string, succeeded bool) {
listeners := m.ccLifecycleListeners[chainid]
for _, listener := range listeners {
listener.ChaincodeDeployDone(succeeded)
}
}
type callbackStatus struct {
l sync.Mutex
deployPending map[string]bool
installPending map[string]bool
}
func | () *callbackStatus {
return &callbackStatus{
deployPending: make(map[string]bool),
installPending: make(map[string]bool)}
}
func (s *callbackStatus) setDeployPending(channelID string) {
s.l.Lock()
defer s.l.Unlock()
s.deployPending[channelID] = true
}
func (s *callbackStatus) unsetDeployPending(channelID string) {
s.l.Lock()
defer s.l.Unlock()
delete(s.deployPending, channelID)
}
func (s *callbackStatus) isDeployPending(channelID string) bool {
s.l.Lock()
defer s.l.Unlock()
return s.deployPending[channelID]
}
func (s *callbackStatus) setInstallPending(channelID string) {
s.l.Lock()
defer s.l.Unlock()
s.installPending[channelID] = true
}
func (s *callbackStatus) unsetInstallPending(channelID string) {
s.l.Lock()
defer s.l.Unlock()
delete(s.installPending, channelID)
}
func (s *callbackStatus) isInstallPending(channelID string) bool {
s.l.Lock()
defer s.l.Unlock()
return s.installPending[channelID]
}
| newCallbackStatus |
main.rs | use advent_of_code_traits::{days::*, Solution};
use boilerplate::AdventOfCode2020; // swap `boilerplate` with the name of your library crate
fn | (day: u32) -> for<'r> fn(&'r str) {
match day {
1 => <AdventOfCode2020 as Solution<Day1>>::run,
// add more match arms as you complete solutions
// adding arms early will fail to compile
// 4 => <AdventOfCode2020 as Solution<Day4>>::run,
_ => unimplemented!("no solution available for that day"),
}
}
fn main() {
let day = std::env::args()
.skip(1)
.next()
.expect(
"need a day to know which solution to run, e.g. `advent_2020 1` to run day 1 solutions",
)
.parse()
.expect("unable to parse day, just use a number like `1`");
let input = std::fs::read_to_string(format!("./input/2020/day{}.txt", day))
// change the year here -------------------------^^^^
.expect("no input available for that day");
call_solution_for_day(day)(&input)
}
| call_solution_for_day |
DeviceCapability.rs | // This file is part of security-keys-rust. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/security-keys-rust/master/COPYRIGHT. No part of security-keys-rust, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2021 The developers of security-keys-rust. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/security-keys-rust/master/COPYRIGHT.
/// An USB 3.0 concept.
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub enum DeviceCapability
{
/// Wireless USB
WirelessUsb(Vec<u8>),
/// USB 2.0 Extension.
Usb2Extension(Usb2ExtensionDeviceCapability),
/// SuperSpeed.
SuperSpeed(SuperSpeedDeviceCapability),
/// Container Identifier.
ContainerIdentifier(ContainerIdentifierDeviceCapability),
/// Platform.
Platform(PlatformDeviceCapability),
/// Power Delivery (PD).
PowerDelivery(Vec<u8>),
/// Battery information.
BatteryInformation(Vec<u8>),
/// Power Delivery (PD) consumer port.
PowerDeliveryConsumerPort(Vec<u8>),
/// Power Delivery (PD) provider port.
PowerDeliveryProviderPort(Vec<u8>),
/// SuperSpeed Plus.
SuperSpeedPlus(SuperSpeedPlusDeviceCapability),
/// Precision time measurement.
PrecisionTimeMeasurement,
/// Wireless USB extended.
WirelessUsbExtended(Vec<u8>),
/// Billboard.
Billboard(BillboardDeviceCapability),
/// Authentication.
Authentication(Vec<u8>),
/// Billboard alternate mode.
BillboardAlternateMode(BillboardAlternateModeDeviceCapability),
/// Configuration summary.
ConfigurationSummary(ConfigurationSummaryDeviceCapability),
/// Reserved.
Reserved(ReservedDeviceCapability),
}
impl DeviceCapability
{
const DeviceCapabilityHeaderSize: usize = DescriptorHeaderLength + 1;
#[inline(always)]
fn parse(device_capabilities_bytes: &[u8], device_connection: &DeviceConnection, has_microsoft_operating_system_descriptors_version_2_0: &mut bool) -> Result<DeadOrAlive<(usize, DeviceCapability)>, DeviceCapabilityParseError>
{ |
#[inline(always)]
fn parse_blob(device_capability_bytes: &[u8], error: impl FnOnce(TryReserveError) -> DeviceCapabilityParseError) -> Result<Vec<u8>, DeviceCapabilityParseError>
{
Vec::new_from(device_capability_bytes).map_err(error)
}
}
|
use DeviceCapability::*;
use DeviceCapabilityParseError::*;
let remaining_length = device_capabilities_bytes.len();
if unlikely!(remaining_length < Self::DeviceCapabilityHeaderSize)
{
return Err(DescriptorTooShort { remaining_length })
}
let bDescriptorType = device_capabilities_bytes.u8(1);
if unlikely!(bDescriptorType != 0x10)
{
return Err(DescriptorTypeWasInvalid { bDescriptorType })
}
let bLength = device_capabilities_bytes.u8(0);
let length = bLength as usize;
if unlikely!(length < Self::DeviceCapabilityHeaderSize)
{
return Err(BLengthTooShort { bLength })
}
if unlikely!(length > remaining_length)
{
return Err(BLengthTooLong { bLength })
}
let bDevCapabilityType = device_capabilities_bytes.u8(DescriptorHeaderLength);
let device_capability_bytes = device_capabilities_bytes.get_unchecked_range_safe(Self::DeviceCapabilityHeaderSize .. length);
let device_capability = match bDevCapabilityType
{
0x01 => WirelessUsb(Self::parse_blob(device_capability_bytes, ParseWirelessUsbDeviceCapability)?),
0x02 => Usb2Extension(Usb2ExtensionDeviceCapability::parse(device_capability_bytes)?),
0x03 => SuperSpeed(SuperSpeedDeviceCapability::parse(device_capability_bytes)?),
0x04 => ContainerIdentifier(ContainerIdentifierDeviceCapability::parse(device_capability_bytes)?),
0x05 =>
{
let dead_or_alive = PlatformDeviceCapability::parse(device_capability_bytes, device_connection, has_microsoft_operating_system_descriptors_version_2_0)?;
Platform(return_ok_if_dead!(dead_or_alive))
},
0x06 => PowerDelivery(Self::parse_blob(device_capability_bytes, ParsePowerDeliveryDeviceCapability)?),
0x07 => BatteryInformation(Self::parse_blob(device_capability_bytes, ParseBatteryInformationDeviceCapability)?),
0x08 => PowerDeliveryConsumerPort(Self::parse_blob(device_capability_bytes, PowerDeliveryConsumerPortDeviceCapability)?),
0x09 => PowerDeliveryProviderPort(Self::parse_blob(device_capability_bytes, PowerDeliveryProducerPortDeviceCapability)?),
0x0A => SuperSpeedPlus(SuperSpeedPlusDeviceCapability::parse(device_capability_bytes)?),
0x0B => PrecisionTimeMeasurement,
0x0C => WirelessUsbExtended(Self::parse_blob(device_capability_bytes, ParseWirelessUsbExtendedDeviceCapability)?),
0x0D =>
{
let dead_or_alive = BillboardDeviceCapability::parse(device_capability_bytes, device_connection)?;
Billboard(return_ok_if_dead!(dead_or_alive))
},
0x0E => Authentication(Self::parse_blob(device_capability_bytes, ParseAuthenticationDeviceCapability)?),
0x0F => BillboardAlternateMode(BillboardAlternateModeDeviceCapability::parse(device_capability_bytes)?),
0x10 => ConfigurationSummary(ConfigurationSummaryDeviceCapability::parse(device_capability_bytes)?),
0x00 | 0x11 ..= 0xFF => Reserved(ReservedDeviceCapability::parse(bDescriptorType, device_capability_bytes).map_err(ParseReservedDeviceCapability)?),
};
Ok(Alive((length, device_capability)))
}
|
translator_test.go | // Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package translation
import (
"context"
"testing"
"github.com/apache/apisix-ingress-controller/pkg/kube"
discoveryv1 "k8s.io/api/discovery/v1"
apisixv1 "github.com/apache/apisix-ingress-controller/pkg/types/apisix/v1"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes/fake"
"k8s.io/client-go/tools/cache"
configv1 "github.com/apache/apisix-ingress-controller/pkg/kube/apisix/apis/config/v1"
)
func TestTranslateUpstreamConfig(t *testing.T) |
func TestTranslateUpstreamNodes(t *testing.T) {
svc := &corev1.Service{
TypeMeta: metav1.TypeMeta{},
ObjectMeta: metav1.ObjectMeta{
Name: "svc",
Namespace: "test",
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
Name: "port1",
Port: 80,
TargetPort: intstr.IntOrString{
Type: intstr.Int,
IntVal: 9080,
},
},
{
Name: "port2",
Port: 443,
TargetPort: intstr.IntOrString{
Type: intstr.Int,
IntVal: 9443,
},
},
},
},
}
endpoints := &corev1.Endpoints{
TypeMeta: metav1.TypeMeta{},
ObjectMeta: metav1.ObjectMeta{
Name: "svc",
Namespace: "test",
},
Subsets: []corev1.EndpointSubset{
{
Ports: []corev1.EndpointPort{
{
Name: "port1",
Port: 9080,
},
{
Name: "port2",
Port: 9443,
},
},
Addresses: []corev1.EndpointAddress{
{IP: "192.168.1.1"},
{IP: "192.168.1.2"},
},
},
},
}
client := fake.NewSimpleClientset()
informersFactory := informers.NewSharedInformerFactory(client, 0)
svcInformer := informersFactory.Core().V1().Services().Informer()
svcLister := informersFactory.Core().V1().Services().Lister()
processCh := make(chan struct{})
svcInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
processCh <- struct{}{}
},
})
stopCh := make(chan struct{})
defer close(stopCh)
go svcInformer.Run(stopCh)
cache.WaitForCacheSync(stopCh, svcInformer.HasSynced)
_, err := client.CoreV1().Services("test").Create(context.Background(), svc, metav1.CreateOptions{})
assert.Nil(t, err)
tr := &translator{&TranslatorOptions{
ServiceLister: svcLister,
}}
<-processCh
nodes, err := tr.TranslateUpstreamNodes(kube.NewEndpoint(endpoints), 10080, nil)
assert.Nil(t, nodes)
assert.Equal(t, err, &translateError{
field: "service.spec.ports",
reason: "port not defined",
})
nodes, err = tr.TranslateUpstreamNodes(kube.NewEndpoint(endpoints), 80, nil)
assert.Nil(t, err)
assert.Equal(t, nodes, apisixv1.UpstreamNodes{
{
Host: "192.168.1.1",
Port: 9080,
Weight: 100,
},
{
Host: "192.168.1.2",
Port: 9080,
Weight: 100,
},
})
nodes, err = tr.TranslateUpstreamNodes(kube.NewEndpoint(endpoints), 443, nil)
assert.Nil(t, err)
assert.Equal(t, nodes, apisixv1.UpstreamNodes{
{
Host: "192.168.1.1",
Port: 9443,
Weight: 100,
},
{
Host: "192.168.1.2",
Port: 9443,
Weight: 100,
},
})
}
func TestTranslateUpstreamNodesWithEndpointSlices(t *testing.T) {
svc := &corev1.Service{
TypeMeta: metav1.TypeMeta{},
ObjectMeta: metav1.ObjectMeta{
Name: "svc",
Namespace: "test",
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
Name: "port1",
Port: 80,
TargetPort: intstr.IntOrString{
Type: intstr.Int,
IntVal: 9080,
},
},
{
Name: "port2",
Port: 443,
TargetPort: intstr.IntOrString{
Type: intstr.Int,
IntVal: 9443,
},
},
},
},
}
isTrue := true
port1 := int32(9080)
port2 := int32(9443)
port1Name := "port1"
port2Name := "port2"
ep := &discoveryv1.EndpointSlice{
ObjectMeta: metav1.ObjectMeta{
Name: "svc",
Namespace: "test",
Labels: map[string]string{
discoveryv1.LabelManagedBy: "endpointslice-controller.k8s.io",
discoveryv1.LabelServiceName: "svc",
},
},
AddressType: discoveryv1.AddressTypeIPv4,
Endpoints: []discoveryv1.Endpoint{
{
Addresses: []string{
"192.168.1.1",
"192.168.1.2",
},
Conditions: discoveryv1.EndpointConditions{
Ready: &isTrue,
},
},
},
Ports: []discoveryv1.EndpointPort{
{
Name: &port1Name,
Port: &port1,
},
{
Name: &port2Name,
Port: &port2,
},
},
}
client := fake.NewSimpleClientset()
informersFactory := informers.NewSharedInformerFactory(client, 0)
svcInformer := informersFactory.Core().V1().Services().Informer()
svcLister := informersFactory.Core().V1().Services().Lister()
processCh := make(chan struct{})
svcInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
processCh <- struct{}{}
},
})
stopCh := make(chan struct{})
defer close(stopCh)
go svcInformer.Run(stopCh)
cache.WaitForCacheSync(stopCh, svcInformer.HasSynced)
_, err := client.CoreV1().Services("test").Create(context.Background(), svc, metav1.CreateOptions{})
assert.Nil(t, err)
tr := &translator{&TranslatorOptions{
ServiceLister: svcLister,
}}
<-processCh
nodes, err := tr.TranslateUpstreamNodes(kube.NewEndpointWithSlice(ep), 10080, nil)
assert.Nil(t, nodes)
assert.Equal(t, err, &translateError{
field: "service.spec.ports",
reason: "port not defined",
})
nodes, err = tr.TranslateUpstreamNodes(kube.NewEndpointWithSlice(ep), 80, nil)
assert.Nil(t, err)
assert.Equal(t, nodes, apisixv1.UpstreamNodes{
{
Host: "192.168.1.1",
Port: 9080,
Weight: 100,
},
{
Host: "192.168.1.2",
Port: 9080,
Weight: 100,
},
})
nodes, err = tr.TranslateUpstreamNodes(kube.NewEndpointWithSlice(ep), 443, nil)
assert.Nil(t, err)
assert.Equal(t, nodes, apisixv1.UpstreamNodes{
{
Host: "192.168.1.1",
Port: 9443,
Weight: 100,
},
{
Host: "192.168.1.2",
Port: 9443,
Weight: 100,
},
})
}
| {
tr := &translator{}
au := &configv1.ApisixUpstreamConfig{
LoadBalancer: nil,
Scheme: apisixv1.SchemeGRPC,
}
ups, err := tr.TranslateUpstreamConfig(au)
assert.Nil(t, err, "checking upstream config translating")
assert.Equal(t, ups.Type, apisixv1.LbRoundRobin)
assert.Equal(t, ups.Scheme, apisixv1.SchemeGRPC)
au = &configv1.ApisixUpstreamConfig{
LoadBalancer: &configv1.LoadBalancer{
Type: apisixv1.LbConsistentHash,
HashOn: apisixv1.HashOnHeader,
Key: "user-agent",
},
Scheme: apisixv1.SchemeHTTP,
}
ups, err = tr.TranslateUpstreamConfig(au)
assert.Nil(t, err, "checking upstream config translating")
assert.Equal(t, ups.Type, apisixv1.LbConsistentHash)
assert.Equal(t, ups.Key, "user-agent")
assert.Equal(t, ups.HashOn, apisixv1.HashOnHeader)
assert.Equal(t, ups.Scheme, apisixv1.SchemeHTTP)
au = &configv1.ApisixUpstreamConfig{
LoadBalancer: &configv1.LoadBalancer{
Type: apisixv1.LbConsistentHash,
HashOn: apisixv1.HashOnHeader,
Key: "user-agent",
},
Scheme: "dns",
}
_, err = tr.TranslateUpstreamConfig(au)
assert.Error(t, err, &translateError{
field: "scheme",
reason: "invalid value",
})
au = &configv1.ApisixUpstreamConfig{
LoadBalancer: &configv1.LoadBalancer{
Type: "hash",
},
}
_, err = tr.TranslateUpstreamConfig(au)
assert.Error(t, err, &translateError{
field: "loadbalancer.type",
reason: "invalid value",
})
au = &configv1.ApisixUpstreamConfig{
LoadBalancer: &configv1.LoadBalancer{
Type: apisixv1.LbConsistentHash,
HashOn: "arg",
},
}
_, err = tr.TranslateUpstreamConfig(au)
assert.Error(t, err, &translateError{
field: "loadbalancer.hashOn",
reason: "invalid value",
})
} |
index.js | const config = {
projectName: 'myapp',
date: '2021-3-1',
designWidth: 750,
deviceRatio: {
640: 2.34 / 2,
750: 1,
828: 1.81 / 2
},
sourceRoot: 'src',
outputRoot: 'dist',
plugins: [],
defineConstants: {
},
copy: {
patterns: [
],
options: {
}
},
framework: 'react',
mini: {
postcss: {
pxtransform: {
enable: true,
config: {
}
},
url: {
enable: true,
config: {
limit: 1024 // 设定转换尺寸上限
}
},
cssModules: {
enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
config: {
namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: '[name]__[local]___[hash:base64:5]'
}
}
}
},
h5: {
publicPath: '/',
staticDirectory: 'static',
postcss: {
autoprefixer: {
enable: true, | config: {
}
},
cssModules: {
enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
config: {
namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: '[name]__[local]___[hash:base64:5]'
}
}
}
}
}
module.exports = function (merge) {
if (process.env.NODE_ENV === 'development') {
return merge({}, config, require('./dev'))
}
return merge({}, config, require('./prod'))
} | |
AmsNetId.go | //
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package model
import (
"encoding/xml"
"github.com/apache/plc4x/plc4go/internal/plc4go/spi/utils"
"github.com/pkg/errors"
"io"
)
// Code generated by build-utils. DO NOT EDIT.
// The data-structure of this message
type AmsNetId struct {
Octet1 uint8
Octet2 uint8
Octet3 uint8
Octet4 uint8
Octet5 uint8
Octet6 uint8
}
// The corresponding interface
type IAmsNetId interface {
LengthInBytes() uint16
LengthInBits() uint16
Serialize(io utils.WriteBuffer) error
xml.Marshaler
xml.Unmarshaler
}
func NewAmsNetId(octet1 uint8, octet2 uint8, octet3 uint8, octet4 uint8, octet5 uint8, octet6 uint8) *AmsNetId {
return &AmsNetId{Octet1: octet1, Octet2: octet2, Octet3: octet3, Octet4: octet4, Octet5: octet5, Octet6: octet6}
}
func CastAmsNetId(structType interface{}) *AmsNetId {
castFunc := func(typ interface{}) *AmsNetId {
if casted, ok := typ.(AmsNetId); ok {
return &casted
}
if casted, ok := typ.(*AmsNetId); ok {
return casted
}
return nil
}
return castFunc(structType)
}
func (m *AmsNetId) GetTypeName() string {
return "AmsNetId"
}
func (m *AmsNetId) LengthInBits() uint16 {
return m.LengthInBitsConditional(false)
}
func (m *AmsNetId) LengthInBitsConditional(lastItem bool) uint16 {
lengthInBits := uint16(0)
// Simple field (octet1)
lengthInBits += 8
// Simple field (octet2)
lengthInBits += 8
// Simple field (octet3)
lengthInBits += 8
// Simple field (octet4)
lengthInBits += 8
// Simple field (octet5)
lengthInBits += 8
// Simple field (octet6)
lengthInBits += 8
return lengthInBits
}
func (m *AmsNetId) LengthInBytes() uint16 { | func AmsNetIdParse(io utils.ReadBuffer) (*AmsNetId, error) {
// Simple Field (octet1)
octet1, _octet1Err := io.ReadUint8(8)
if _octet1Err != nil {
return nil, errors.Wrap(_octet1Err, "Error parsing 'octet1' field")
}
// Simple Field (octet2)
octet2, _octet2Err := io.ReadUint8(8)
if _octet2Err != nil {
return nil, errors.Wrap(_octet2Err, "Error parsing 'octet2' field")
}
// Simple Field (octet3)
octet3, _octet3Err := io.ReadUint8(8)
if _octet3Err != nil {
return nil, errors.Wrap(_octet3Err, "Error parsing 'octet3' field")
}
// Simple Field (octet4)
octet4, _octet4Err := io.ReadUint8(8)
if _octet4Err != nil {
return nil, errors.Wrap(_octet4Err, "Error parsing 'octet4' field")
}
// Simple Field (octet5)
octet5, _octet5Err := io.ReadUint8(8)
if _octet5Err != nil {
return nil, errors.Wrap(_octet5Err, "Error parsing 'octet5' field")
}
// Simple Field (octet6)
octet6, _octet6Err := io.ReadUint8(8)
if _octet6Err != nil {
return nil, errors.Wrap(_octet6Err, "Error parsing 'octet6' field")
}
// Create the instance
return NewAmsNetId(octet1, octet2, octet3, octet4, octet5, octet6), nil
}
func (m *AmsNetId) Serialize(io utils.WriteBuffer) error {
io.PushContext("AmsNetId")
// Simple Field (octet1)
octet1 := uint8(m.Octet1)
_octet1Err := io.WriteUint8("octet1", 8, (octet1))
if _octet1Err != nil {
return errors.Wrap(_octet1Err, "Error serializing 'octet1' field")
}
// Simple Field (octet2)
octet2 := uint8(m.Octet2)
_octet2Err := io.WriteUint8("octet2", 8, (octet2))
if _octet2Err != nil {
return errors.Wrap(_octet2Err, "Error serializing 'octet2' field")
}
// Simple Field (octet3)
octet3 := uint8(m.Octet3)
_octet3Err := io.WriteUint8("octet3", 8, (octet3))
if _octet3Err != nil {
return errors.Wrap(_octet3Err, "Error serializing 'octet3' field")
}
// Simple Field (octet4)
octet4 := uint8(m.Octet4)
_octet4Err := io.WriteUint8("octet4", 8, (octet4))
if _octet4Err != nil {
return errors.Wrap(_octet4Err, "Error serializing 'octet4' field")
}
// Simple Field (octet5)
octet5 := uint8(m.Octet5)
_octet5Err := io.WriteUint8("octet5", 8, (octet5))
if _octet5Err != nil {
return errors.Wrap(_octet5Err, "Error serializing 'octet5' field")
}
// Simple Field (octet6)
octet6 := uint8(m.Octet6)
_octet6Err := io.WriteUint8("octet6", 8, (octet6))
if _octet6Err != nil {
return errors.Wrap(_octet6Err, "Error serializing 'octet6' field")
}
io.PopContext("AmsNetId")
return nil
}
func (m *AmsNetId) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var token xml.Token
var err error
foundContent := false
for {
token, err = d.Token()
if err != nil {
if err == io.EOF && foundContent {
return nil
}
return err
}
switch token.(type) {
case xml.StartElement:
foundContent = true
tok := token.(xml.StartElement)
switch tok.Name.Local {
case "octet1":
var data uint8
if err := d.DecodeElement(&data, &tok); err != nil {
return err
}
m.Octet1 = data
case "octet2":
var data uint8
if err := d.DecodeElement(&data, &tok); err != nil {
return err
}
m.Octet2 = data
case "octet3":
var data uint8
if err := d.DecodeElement(&data, &tok); err != nil {
return err
}
m.Octet3 = data
case "octet4":
var data uint8
if err := d.DecodeElement(&data, &tok); err != nil {
return err
}
m.Octet4 = data
case "octet5":
var data uint8
if err := d.DecodeElement(&data, &tok); err != nil {
return err
}
m.Octet5 = data
case "octet6":
var data uint8
if err := d.DecodeElement(&data, &tok); err != nil {
return err
}
m.Octet6 = data
}
}
}
}
func (m *AmsNetId) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
className := "org.apache.plc4x.java.ads.readwrite.AmsNetId"
if err := e.EncodeToken(xml.StartElement{Name: start.Name, Attr: []xml.Attr{
{Name: xml.Name{Local: "className"}, Value: className},
}}); err != nil {
return err
}
if err := e.EncodeElement(m.Octet1, xml.StartElement{Name: xml.Name{Local: "octet1"}}); err != nil {
return err
}
if err := e.EncodeElement(m.Octet2, xml.StartElement{Name: xml.Name{Local: "octet2"}}); err != nil {
return err
}
if err := e.EncodeElement(m.Octet3, xml.StartElement{Name: xml.Name{Local: "octet3"}}); err != nil {
return err
}
if err := e.EncodeElement(m.Octet4, xml.StartElement{Name: xml.Name{Local: "octet4"}}); err != nil {
return err
}
if err := e.EncodeElement(m.Octet5, xml.StartElement{Name: xml.Name{Local: "octet5"}}); err != nil {
return err
}
if err := e.EncodeElement(m.Octet6, xml.StartElement{Name: xml.Name{Local: "octet6"}}); err != nil {
return err
}
if err := e.EncodeToken(xml.EndElement{Name: start.Name}); err != nil {
return err
}
return nil
}
func (m AmsNetId) String() string {
return string(m.Box("", 120))
}
func (m AmsNetId) Box(name string, width int) utils.AsciiBox {
boxName := "AmsNetId"
if name != "" {
boxName += "/" + name
}
boxes := make([]utils.AsciiBox, 0)
// Simple field (case simple)
// uint8 can be boxed as anything with the least amount of space
boxes = append(boxes, utils.BoxAnything("Octet1", m.Octet1, -1))
// Simple field (case simple)
// uint8 can be boxed as anything with the least amount of space
boxes = append(boxes, utils.BoxAnything("Octet2", m.Octet2, -1))
// Simple field (case simple)
// uint8 can be boxed as anything with the least amount of space
boxes = append(boxes, utils.BoxAnything("Octet3", m.Octet3, -1))
// Simple field (case simple)
// uint8 can be boxed as anything with the least amount of space
boxes = append(boxes, utils.BoxAnything("Octet4", m.Octet4, -1))
// Simple field (case simple)
// uint8 can be boxed as anything with the least amount of space
boxes = append(boxes, utils.BoxAnything("Octet5", m.Octet5, -1))
// Simple field (case simple)
// uint8 can be boxed as anything with the least amount of space
boxes = append(boxes, utils.BoxAnything("Octet6", m.Octet6, -1))
return utils.BoxBox(boxName, utils.AlignBoxes(boxes, width-2), 0)
} | return m.LengthInBits() / 8
}
|
config.ts | import { resolve } from 'pathe'
import type { ResolvedConfig as ResolvedViteConfig, UserConfig as ViteUserConfig } from 'vite'
import type { ApiConfig, ResolvedConfig, UserConfig } from '../types'
import { defaultExclude, defaultInclude, defaultPort } from '../constants'
import { resolveC8Options } from '../coverage'
import { deepMerge, toArray } from '../utils'
export function resolveApiConfig<Options extends ApiConfig & UserConfig>(
options: Options,
viteOverrides?: ViteUserConfig,
): ApiConfig | undefined {
let api: ApiConfig | undefined
if (options.api === true)
api = { port: defaultPort } |
if (typeof options.api === 'object') {
if (api) {
if (options.api.port)
api.port = options.api.port
if (options.api.strictPort)
api.strictPort = options.api.strictPort
if (options.api.host)
api.host = options.api.host
}
else {
api = { ...options.api }
}
}
if (api) {
if (!api.port)
api.port = defaultPort
if (viteOverrides)
viteOverrides.server = Object.assign(viteOverrides.server || {}, api)
}
return api
}
export function resolveConfig(
options: UserConfig,
viteConfig: ResolvedViteConfig,
): ResolvedConfig {
if (options.dom)
options.environment = 'happy-dom'
const resolved = {
...deepMerge(options, viteConfig.test || {}),
root: viteConfig.root,
} as ResolvedConfig
if (viteConfig.base !== '/')
resolved.base = viteConfig.base
resolved.coverage = resolveC8Options(resolved.coverage, resolved.root)
resolved.depsInline = [...resolved.deps?.inline || []]
resolved.depsExternal = [...resolved.deps?.external || []]
resolved.fallbackCJS = resolved.deps?.fallbackCJS ?? true
resolved.interpretDefault = resolved.deps?.interpretDefault ?? true
resolved.environment = resolved.environment || 'node'
resolved.threads = resolved.threads ?? true
resolved.clearMocks = resolved.clearMocks ?? false
resolved.restoreMocks = resolved.restoreMocks ?? false
resolved.mockReset = resolved.mockReset ?? false
resolved.include = resolved.include ?? defaultInclude
resolved.exclude = resolved.exclude ?? defaultExclude
resolved.testTimeout = resolved.testTimeout ?? 5_000
resolved.hookTimeout = resolved.hookTimeout ?? 10_000
resolved.isolate = resolved.isolate ?? true
resolved.testNamePattern = resolved.testNamePattern
? resolved.testNamePattern instanceof RegExp
? resolved.testNamePattern
: new RegExp(resolved.testNamePattern)
: undefined
resolved.watchIgnore = resolved.watchIgnore ?? [/\/node_modules\//, /\/dist\//]
const CI = !!process.env.CI
const UPDATE_SNAPSHOT = resolved.update || process.env.UPDATE_SNAPSHOT
resolved.snapshotOptions = {
updateSnapshot: CI && !UPDATE_SNAPSHOT
? 'none'
: UPDATE_SNAPSHOT
? 'all'
: 'new',
}
if (process.env.VITEST_MAX_THREADS)
resolved.maxThreads = parseInt(process.env.VITEST_MAX_THREADS)
if (process.env.VITEST_MIN_THREADS)
resolved.minThreads = parseInt(process.env.VITEST_MIN_THREADS)
resolved.setupFiles = toArray(resolved.setupFiles || []).map(file => resolve(resolved.root, file))
// the server has been created, we don't need to override vite.server options
resolved.api = resolveApiConfig(options)
if (options.related)
resolved.related = toArray(options.related).map(file => resolve(resolved.root, file))
return resolved
} | else if (typeof options.api === 'number')
api = { port: options.api } |
rpc.ts | // Copyright 2017-2021 @polkadot/typegen authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { TypeRegistry } from '@5ire/types/create';
import type { Definitions } from '@5ire/types/types';
import type { ExtraTypes } from './types';
import Handlebars from 'handlebars';
import * as defaultDefinitions from '@5ire/types/interfaces/definitions';
import { createImports, formatType, getSimilarTypes, initMeta, readTemplate, setImports, writeFile } from '../util';
interface ItemDef {
args: string;
docs: string[];
generic: string | undefined;
name: string; | }
interface ModuleDef {
items: ItemDef[];
name: string;
}
const StorageKeyTye = 'StorageKey | string | Uint8Array | any';
const template = readTemplate('rpc');
const generateRpcTypesTemplate = Handlebars.compile(template);
/** @internal */
export function generateRpcTypes (registry: TypeRegistry, importDefinitions: Record<string, Definitions>, dest: string, extraTypes: ExtraTypes = {}): void {
writeFile(dest, (): string => {
const allTypes: ExtraTypes = { '@5ire/types/interfaces': importDefinitions, ...extraTypes };
const imports = createImports(allTypes);
const definitions = imports.definitions as Record<string, Definitions>;
const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => {
return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs);
}, {});
const rpcKeys = Object
.keys(definitions)
.filter((key) => Object.keys(definitions[key].rpc || {}).length !== 0)
.sort();
const additional: Record<string, ModuleDef> = {};
const modules = rpcKeys.map((sectionFullName) => {
const rpc = definitions[sectionFullName].rpc;
const section = sectionFullName.split('/').pop();
const allMethods = Object.keys(rpc).sort().map((methodName) => {
const def = rpc[methodName];
let args;
let type;
let generic;
// These are too hard to type with generics, do manual overrides
if (section === 'state') {
setImports(allDefs, imports, ['Codec', 'Hash', 'StorageKey', 'Vec']);
if (methodName === 'getStorage') {
generic = 'T = Codec';
args = [`key: ${StorageKeyTye}, block?: Hash | Uint8Array | string`];
type = 'T';
} else if (methodName === 'queryStorage') {
generic = 'T = Codec[]';
args = [`keys: Vec<StorageKey> | (${StorageKeyTye})[], fromBlock?: Hash | Uint8Array | string, toBlock?: Hash | Uint8Array | string`];
type = '[Hash, T][]';
} else if (methodName === 'queryStorageAt') {
generic = 'T = Codec[]';
args = [`keys: Vec<StorageKey> | (${StorageKeyTye})[], at?: Hash | Uint8Array | string`];
type = 'T';
} else if (methodName === 'subscribeStorage') {
generic = 'T = Codec[]';
args = [`keys?: Vec<StorageKey> | (${StorageKeyTye})[]`];
type = 'T';
}
}
if (args === undefined) {
setImports(allDefs, imports, [def.type]);
args = def.params.map((param) => {
const similarTypes = getSimilarTypes(registry, definitions, param.type, imports);
setImports(allDefs, imports, [param.type, ...similarTypes]);
return `${param.name}${param.isOptional ? '?' : ''}: ${similarTypes.join(' | ')}`;
});
type = formatType(registry, allDefs, def.type, imports);
generic = '';
}
const item = {
args: args.join(', '),
docs: [def.description],
generic,
name: methodName,
type
};
if (def.aliasSection) {
if (!additional[def.aliasSection]) {
additional[def.aliasSection] = {
items: [],
name: def.aliasSection
};
}
additional[def.aliasSection].items.push(item);
return null;
}
return item;
}).filter((item): item is ItemDef => !!item);
return {
items: allMethods,
name: section || 'unknown'
};
}).concat(...Object.values(additional)).sort((a, b) => a.name.localeCompare(b.name));
imports.typesTypes.Observable = true;
return generateRpcTypesTemplate({
headerType: 'chain',
imports,
modules,
types: [
...Object.keys(imports.localTypes).sort().map((packagePath): { file: string; types: string[] } => ({
file: packagePath.replace('@5ire/types/augment', '@5ire/types'),
types: Object.keys(imports.localTypes[packagePath])
}))
]
});
});
}
export function generateDefaultRpc (dest = 'packages/api/src/augment/rpc.ts', extraTypes: ExtraTypes = {}): void {
const { registry } = initMeta(undefined, extraTypes);
generateRpcTypes(
registry,
defaultDefinitions,
dest,
extraTypes
);
} | type: string | undefined; |
pre_commit.py | # Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import re
import subprocess
import sys
from trace_viewer import trace_viewer_project
class AffectedFile(object):
def __init__(self, input_api, filename):
self._filename = filename
self._input_api = input_api
self._cached_contents = None
self._cached_changed_contents = None
self._cached_new_contents = None
def __repr__(self):
return self._filename
@property
def filename(self):
return self._filename
@property
def contents(self):
if self._cached_contents is None:
self._cached_contents = self._input_api._git(
['show', ':%s' % self._filename])
return self._cached_contents
@property
def is_added(self):
return self.fileame in self._input_api.added_files
@property
def contents_as_lines(self):
"""Returns an iterator over the lines in the new version of file.
The new version is the file in the user's workspace, i.e. the "right hand
side".
Contents will be empty if the file is a directory or does not exist.
Note: The carriage returns (LF or CR) are stripped off.
"""
if self._cached_new_contents is None:
self._cached_new_contents = self.contents.splitlines()
return self._cached_new_contents[:]
@property
def changed_lines(self):
"""Returns a list of tuples (line number, line text) of all new lines.
This relies on the scm diff output describing each changed code section
with a line of the form
^@@ <old line num>,<old size> <new line num>,<new size> @@$
"""
if self._cached_changed_contents is not None:
return self._cached_changed_contents[:]
self._cached_changed_contents = []
line_num = 0
for line in self.GenerateDiff().splitlines():
m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
if m:
line_num = int(m.groups(1)[0])
continue
if line.startswith('+') and not line.startswith('++'):
self._cached_changed_contents.append((line_num, line[1:]))
if not line.startswith('-'):
line_num += 1
return self._cached_changed_contents[:]
def GenerateDiff(self):
return self._input_api._git(['diff', '--cached', self.filename])
class InputAPI(object):
def __init__(self, tvp):
self.DEFAULT_BLACK_LIST = []
self._tvp = tvp
self._filename_statuses = None
self._added_files = None
def _git(self, args):
assert isinstance(args, list)
args = ['git'] + args
p = subprocess.Popen(
args,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=self.repository_root)
res = p.communicate()
if p.wait() != 0:
raise Exception(res[1]) |
@property
def repository_root(self):
return self._tvp.trace_viewer_path
@property
def added_files(self):
if not self._added_files:
self._added_files = set()
for filename, status_char in filename_statuses:
if status_char == 'A':
self._added_files.Add(filename)
return self._added_files
@property
def affected_files(self):
return self.AffectedFiles(include_deletes=True)
def AffectedFiles(self,
include_deletes=False,
file_filter=lambda t: True):
filename_statuses = self._GetFilenameStatuses()
for filename, status_char in filename_statuses:
if status_char == 'D':
if include_deletes:
if file_filter(filename):
yield AffectedFile(self, filename)
else:
if file_filter(filename):
yield AffectedFile(self, filename)
def _GetFilenameStatuses(self):
if self._filename_statuses != None:
return self._filename_statuses
self._filename_statuses = []
stdout = self._git(['diff', '--cached', '--name-status'])
for line in stdout.split('\n'):
line = line.strip()
if len(line) == 0:
continue
m = re.match('([ACDMRTUXB])\s+(.+)', line)
if not m:
import pdb; pdb.set_trace()
assert m
status_char = m.group(1)
filename = m.group(2)
self._filename_statuses.append((filename, status_char))
return self._filename_statuses
def RunChecks(input_api):
results = []
from hooks import pre_commit_checks
results += pre_commit_checks.RunChecks(input_api)
from trace_viewer.build import check_gyp
err = check_gyp.GypCheck()
if err:
results += [err]
from trace_viewer.build import check_gn
err = check_gn.GnCheck()
if err:
results += [err]
from trace_viewer.build import check_modules
err = check_modules.CheckModules()
if err:
results += [err]
from hooks import js_checks
results += js_checks.RunChecks(input_api)
return results
def Main(args):
tvp = trace_viewer_project.TraceViewerProject()
input_api = InputAPI(tvp)
results = RunChecks(input_api)
print '\n\n'.join(results)
if len(results):
return 255
return 0 | return res[0] |
subscreen.py | import numpy as np
class SubScreen():
def __init__(self, x, y, width, height, curses):
self.x = x
self.y = y
self.width = width
self.height = height
self.curses = curses
def put_char(self, x, y, char=' ', foreground='white', background='transparent'):
if x < self.width and x >= self.x and y < self.height and y >= self.y:
self.curses.put_char(self.x + x, self.y + y, char, foreground, background)
else:
raise ValueError('Error: Out of SubScreen boundary.')
def put_message(self, x, y , message, foreground='white', background='transparent', auto=True, align='left'):
self.curses.put_message(self.x + x, self.y + y , message, foreground, background, auto, align, box_x=self.x, box_y=self.y, box_width=self.width, box_height=self.height)
def fill_char(self, char=' ', foreground='white', background='transparent'):
for i in range(self.x, self.x + self.width):
for j in range(self.y, self.y + self.height):
self.curses.put_char(i, j, char, foreground, background)
class MessageScreen(SubScreen):
def | (self, x, y, width, height, curses):
super(MessageScreen, self).__init__(x, y, width, height, curses)
self.initialization()
def initialization(self):
self.message_id = 1
self.message_size = self.height
self.message_storage = ['']*self.message_size
self.color_storage = ['transparent']*self.message_size
self.idx_storage = ['']*self.message_size
def add_message(self, message, color='white'):
idx = '[%d] '%(self.message_id)
message = message
self.message_id += 1
self.message_storage.append(message)
self.color_storage.append(color)
self.idx_storage.append(idx)
self.message_storage.pop(0)
self.color_storage.pop(0)
self.idx_storage.pop(0)
def draw(self):
self.fill_char()
for i in range(len(self.message_storage)):
self.put_message(0, i, self.idx_storage[i], foreground='white', background='transparent', auto=True, align='left')
self.put_message(len(self.idx_storage[i]), i , self.message_storage[i], foreground=self.color_storage[i], background='transparent', auto=True, align='left')
class PlayerInfoScreen(SubScreen):
def __init__(self, x, y, width, height, curses, player):
super(PlayerInfoScreen, self).__init__(x, y, width, height, curses)
self.player = player
self.initialization()
def initialization(self):
self.full_health_bar_length = 15
self.draw()
def draw(self):
# Draw background
self.fill_char(char='█', foreground='peru', background='transparent')
# Draw HP bar
health = self.player.current_health
interval = self.player.health / self.full_health_bar_length / 3
level = int(np.ceil(health / interval))
health_title = 'HP '
if level % 3 == 0:
remainder = ''
elif level % 3 == 1:
remainder = '░'
elif level % 3 == 2:
remainder = '▒'
health_message = '█' * int((level - level%3)/3) + remainder
self.put_message(0, 0, health_title, foreground='red', background='peru', auto=True, align='left')
self.put_message(len(health_title), 0, ' '*self.full_health_bar_length, foreground='red', background='transparent', auto=True, align='left')
self.put_message(len(health_title), 0, health_message, foreground='red', background='transparent', auto=True, align='left')
| __init__ |
router2.rs | //! Implementation of command line option for running router2
use std::sync::Arc; | use crate::{
clap_blocks::run_config::RunConfig,
influxdb_ioxd::{
self,
server_type::{
common_state::{CommonServerState, CommonServerStateError},
router2::RouterServerType,
},
},
};
use observability_deps::tracing::*;
use router2::{
dml_handler::nop::NopDmlHandler,
server::{http::HttpDelegate, RouterServer},
};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("Run: {0}")]
Run(#[from] influxdb_ioxd::Error),
#[error("Cannot setup server: {0}")]
Setup(#[from] crate::influxdb_ioxd::server_type::database::setup::Error),
#[error("Invalid config: {0}")]
InvalidConfig(#[from] CommonServerStateError),
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, clap::Parser)]
#[clap(
name = "run",
about = "Runs in router2 mode",
long_about = "Run the IOx router2 server.\n\nThe configuration options below can be \
set either with the command line flags or with the specified environment \
variable. If there is a file named '.env' in the current working directory, \
it is sourced before loading the configuration.
Configuration is loaded from the following sources (highest precedence first):
- command line arguments
- user set environment variables
- .env file contents
- pre-configured default values"
)]
pub struct Config {
#[clap(flatten)]
pub(crate) run_config: RunConfig,
}
pub async fn command(config: Config) -> Result<()> {
let common_state = CommonServerState::from_config(config.run_config.clone())?;
let http = HttpDelegate::new(
config.run_config.max_http_request_size,
NopDmlHandler::default(),
);
let router_server = RouterServer::new(http, Default::default());
let server_type = Arc::new(RouterServerType::new(router_server, &common_state));
info!("starting router2");
Ok(influxdb_ioxd::main(common_state, server_type).await?)
} | |
listers_rbac.go | /*
Copyright 2016 The Kubernetes 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,
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.
*/
package listers
import (
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
rbac "k8s.io/kubernetes/pkg/apis/rbac"
"k8s.io/kubernetes/pkg/client/cache"
)
// TODO: generate these classes and methods for all resources of interest using
// a script. Can use "go generate" once 1.4 is supported by all users.
// Lister makes an Index have the List method. The Stores must contain only the expected type
// Example:
// s := cache.NewStore()
// lw := cache.ListWatch{Client: c, FieldSelector: sel, Resource: "pods"}
// r := cache.NewReflector(lw, &rbac.ClusterRole{}, s).Run()
// l := clusterRoleLister{s}
// l.List()
func NewClusterRoleLister(indexer cache.Indexer) ClusterRoleLister {
return &clusterRoleLister{indexer: indexer}
}
func NewClusterRoleBindingLister(indexer cache.Indexer) ClusterRoleBindingLister |
func NewRoleLister(indexer cache.Indexer) RoleLister {
return &roleLister{indexer: indexer}
}
func NewRoleBindingLister(indexer cache.Indexer) RoleBindingLister {
return &roleBindingLister{indexer: indexer}
}
// these interfaces are used by the rbac authorizer
type authorizerClusterRoleGetter interface {
GetClusterRole(name string) (*rbac.ClusterRole, error)
}
type authorizerClusterRoleBindingLister interface {
ListClusterRoleBindings() ([]*rbac.ClusterRoleBinding, error)
}
type authorizerRoleGetter interface {
GetRole(namespace, name string) (*rbac.Role, error)
}
type authorizerRoleBindingLister interface {
ListRoleBindings(namespace string) ([]*rbac.RoleBinding, error)
}
type ClusterRoleLister interface {
authorizerClusterRoleGetter
List(selector labels.Selector) (ret []*rbac.ClusterRole, err error)
Get(name string) (*rbac.ClusterRole, error)
}
type clusterRoleLister struct {
indexer cache.Indexer
}
func (s *clusterRoleLister) List(selector labels.Selector) (ret []*rbac.ClusterRole, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*rbac.ClusterRole))
})
return ret, err
}
func (s clusterRoleLister) Get(name string) (*rbac.ClusterRole, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(rbac.Resource("clusterrole"), name)
}
return obj.(*rbac.ClusterRole), nil
}
func (s clusterRoleLister) GetClusterRole(name string) (*rbac.ClusterRole, error) {
return s.Get(name)
}
type ClusterRoleBindingLister interface {
authorizerClusterRoleBindingLister
List(selector labels.Selector) (ret []*rbac.ClusterRoleBinding, err error)
Get(name string) (*rbac.ClusterRoleBinding, error)
}
type clusterRoleBindingLister struct {
indexer cache.Indexer
}
func (s *clusterRoleBindingLister) List(selector labels.Selector) (ret []*rbac.ClusterRoleBinding, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*rbac.ClusterRoleBinding))
})
return ret, err
}
func (s clusterRoleBindingLister) Get(name string) (*rbac.ClusterRoleBinding, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(rbac.Resource("clusterrolebinding"), name)
}
return obj.(*rbac.ClusterRoleBinding), nil
}
func (s clusterRoleBindingLister) ListClusterRoleBindings() ([]*rbac.ClusterRoleBinding, error) {
return s.List(labels.Everything())
}
type RoleLister interface {
authorizerRoleGetter
List(selector labels.Selector) (ret []*rbac.Role, err error)
Roles(namespace string) RoleNamespaceLister
}
type RoleNamespaceLister interface {
List(selector labels.Selector) (ret []*rbac.Role, err error)
Get(name string) (*rbac.Role, error)
}
type roleLister struct {
indexer cache.Indexer
}
func (s *roleLister) List(selector labels.Selector) (ret []*rbac.Role, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*rbac.Role))
})
return ret, err
}
func (s *roleLister) Roles(namespace string) RoleNamespaceLister {
return roleNamespaceLister{indexer: s.indexer, namespace: namespace}
}
func (s roleLister) GetRole(namespace, name string) (*rbac.Role, error) {
return s.Roles(namespace).Get(name)
}
type roleNamespaceLister struct {
indexer cache.Indexer
namespace string
}
func (s roleNamespaceLister) List(selector labels.Selector) (ret []*rbac.Role, err error) {
err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*rbac.Role))
})
return ret, err
}
func (s roleNamespaceLister) Get(name string) (*rbac.Role, error) {
obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(rbac.Resource("role"), name)
}
return obj.(*rbac.Role), nil
}
type RoleBindingLister interface {
authorizerRoleBindingLister
List(selector labels.Selector) (ret []*rbac.RoleBinding, err error)
RoleBindings(namespace string) RoleBindingNamespaceLister
}
type RoleBindingNamespaceLister interface {
List(selector labels.Selector) (ret []*rbac.RoleBinding, err error)
Get(name string) (*rbac.RoleBinding, error)
}
type roleBindingLister struct {
indexer cache.Indexer
}
func (s *roleBindingLister) List(selector labels.Selector) (ret []*rbac.RoleBinding, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*rbac.RoleBinding))
})
return ret, err
}
func (s *roleBindingLister) RoleBindings(namespace string) RoleBindingNamespaceLister {
return roleBindingNamespaceLister{indexer: s.indexer, namespace: namespace}
}
func (s roleBindingLister) ListRoleBindings(namespace string) ([]*rbac.RoleBinding, error) {
return s.RoleBindings(namespace).List(labels.Everything())
}
type roleBindingNamespaceLister struct {
indexer cache.Indexer
namespace string
}
func (s roleBindingNamespaceLister) List(selector labels.Selector) (ret []*rbac.RoleBinding, err error) {
err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*rbac.RoleBinding))
})
return ret, err
}
func (s roleBindingNamespaceLister) Get(name string) (*rbac.RoleBinding, error) {
obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(rbac.Resource("rolebinding"), name)
}
return obj.(*rbac.RoleBinding), nil
}
| {
return &clusterRoleBindingLister{indexer: indexer}
} |
init.go | package server
import (
"barf/internal/com/channel"
"barf/internal/com/protocol"
"barf/internal/com/socket"
)
func onMessage(socket *socket.Socket, message *protocol.Message) |
func init() {
channel.OnMessage(onMessage)
}
| {
if message.RequestCreate != nil {
onRequestCreate(socket, message.RequestCreate)
} else if message.RequestAbort != nil {
onRequestAbort(socket, message.RequestAbort)
} else if message.RequestStatus != nil {
onRequestStatus(socket, message.RequestStatus)
} else if message.RequestList != nil {
onRequestList(socket, message.RequestList)
}
} |
utils.py | import re
from django.template.defaultfilters import force_escape
import django
from cms.models import CMSPlugin
from cms.plugins.utils import downcast_plugins
from distutils.version import LooseVersion
from django.utils.functional import LazyObject
from django.core.files.storage import get_storage_class
import os
OBJ_ADMIN_RE_PATTERN = r'<img [^>]*\bid="plugin_obj_(\d+)"[^>]*/?>'
OBJ_ADMIN_RE = re.compile(OBJ_ADMIN_RE_PATTERN)
def plugin_to_tag(obj):
return u'<img src="%(icon_src)s" alt="%(icon_alt)s" title="%(icon_alt)s" id="plugin_obj_%(id)d" />' % \
dict(id=obj.id,
icon_src=force_escape(obj.get_instance_icon_src()),
icon_alt=force_escape(obj.get_instance_icon_alt()),
)
def plugin_tags_to_id_list(text, regex=OBJ_ADMIN_RE):
|
def plugin_tags_to_user_html(text, context, placeholder):
"""
Convert plugin object 'tags' into the form for public site.
context is the template context to use, placeholder is the placeholder name
"""
plugin_map = _plugin_dict(text)
def _render_tag(m):
plugin_id = int(m.groups()[0])
try:
obj = plugin_map[plugin_id]
obj._render_meta.text_enabled = True
except KeyError:
# Object must have been deleted. It cannot be rendered to
# end user so just remove it from the HTML altogether
return u''
return obj.render_plugin(context, placeholder)
return OBJ_ADMIN_RE.sub(_render_tag, text)
def replace_plugin_tags(text, id_dict):
def _replace_tag(m):
plugin_id = int(m.groups()[0])
new_id = id_dict.get(plugin_id)
try:
obj = CMSPlugin.objects.get(pk=new_id)
except CMSPlugin.DoesNotExist:
# Object must have been deleted. It cannot be rendered to
# end user, or edited, so just remove it from the HTML
# altogether
return u''
return u'<img src="%(icon_src)s" alt="%(icon_alt)s" title="%(icon_alt)s" id="plugin_obj_%(id)d" />' % \
dict(id=new_id,
icon_src=force_escape(obj.get_instance_icon_src()),
icon_alt=force_escape(obj.get_instance_icon_alt()),
)
return OBJ_ADMIN_RE.sub(_replace_tag, text)
def _plugin_dict(text, regex=OBJ_ADMIN_RE):
plugin_ids = plugin_tags_to_id_list(text, regex)
plugin_list = downcast_plugins(CMSPlugin.objects.filter(pk__in=plugin_ids), select_placeholder=True)
return dict((plugin.pk, plugin) for plugin in plugin_list)
"""
The following class is taken from https://github.com/jezdez/django/compare/feature/staticfiles-templatetag
and should be removed and replaced by the django-core version in 1.4
"""
default_storage = 'django.contrib.staticfiles.storage.StaticFilesStorage'
if LooseVersion(django.get_version()) < LooseVersion('1.3'):
default_storage = 'staticfiles.storage.StaticFilesStorage'
class ConfiguredStorage(LazyObject):
def _setup(self):
from django.conf import settings
self._wrapped = get_storage_class(getattr(settings, 'STATICFILES_STORAGE', default_storage))()
configured_storage = ConfiguredStorage()
def static_url(path):
'''
Helper that prefixes a URL with STATIC_URL and cms
'''
if not path:
return ''
return configured_storage.url(os.path.join('', path))
| ids = regex.findall(text)
return [int(id) for id in ids if id.isdigit()] |
reader_test.go | // Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package ranger
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"testing"
"github.com/stretchr/testify/assert"
)
func TestByteRanger(t *testing.T) {
for _, example := range []struct {
data string
size, offset, length int64
substr string
fail bool
}{
{"", 0, 0, 0, "", false},
{"abcdef", 6, 0, 0, "", false},
{"abcdef", 6, 3, 0, "", false},
{"abcdef", 6, 0, 6, "abcdef", false},
{"abcdef", 6, 0, 5, "abcde", false},
{"abcdef", 6, 0, 4, "abcd", false},
{"abcdef", 6, 1, 4, "bcde", false},
{"abcdef", 6, 2, 4, "cdef", false},
{"abcdefg", 7, 1, 4, "bcde", false},
{"abcdef", 6, 0, 7, "", true},
{"abcdef", 6, -1, 7, "abcde", true},
{"abcdef", 6, 0, -1, "abcde", true},
} {
rr := ByteRanger([]byte(example.data))
if rr.Size() != example.size {
t.Fatalf("invalid size: %v != %v", rr.Size(), example.size)
}
r, err := rr.Range(context.Background(), example.offset, example.length)
if example.fail {
if err == nil {
t.Fatalf("expected error")
}
continue
}
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
data, err := ioutil.ReadAll(r)
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
if !bytes.Equal(data, []byte(example.substr)) {
t.Fatalf("invalid subrange: %#v != %#v", string(data), example.substr)
}
}
}
func TestConcatReader(t *testing.T) |
func TestSubranger(t *testing.T) {
for _, example := range []struct {
data string
offset1, length1 int64
offset2, length2 int64
substr string
}{
{"abcdefghijkl", 0, 4, 0, 4, "abcd"},
{"abcdefghijkl", 0, 4, 0, 3, "abc"},
{"abcdefghijkl", 0, 4, 1, 3, "bcd"},
{"abcdefghijkl", 1, 4, 0, 4, "bcde"},
{"abcdefghijkl", 1, 4, 0, 3, "bcd"},
{"abcdefghijkl", 1, 4, 1, 3, "cde"},
{"abcdefghijkl", 8, 4, 0, 4, "ijkl"},
{"abcdefghijkl", 8, 4, 0, 3, "ijk"},
{"abcdefghijkl", 8, 4, 1, 3, "jkl"},
} {
rr, err := Subrange(ByteRanger([]byte(example.data)), example.offset1, example.length1)
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
if rr.Size() != example.length1 {
t.Fatalf("invalid size: %v != %v", rr.Size(), example.length1)
}
r, err := rr.Range(context.Background(), example.offset2, example.length2)
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
data, err := ioutil.ReadAll(r)
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
if !bytes.Equal(data, []byte(example.substr)) {
t.Fatalf("invalid subrange: %#v != %#v", string(data), example.substr)
}
}
}
func TestSubrangerError(t *testing.T) {
for i, tt := range []struct {
data string
offset int64
length int64
}{
{data: "abcd", offset: -1}, // Negative offset
{data: "abcd", offset: 5}, // Offset is bigger than data size
{data: "abcd", offset: 4, length: 1}, // LSength and offset is bigger than DataSize
} {
tag := fmt.Sprintf("#%d. %+v", i, tt)
rr, err := Subrange(ByteRanger([]byte(tt.data)), tt.offset, tt.length)
assert.Nil(t, rr, tag)
assert.NotNil(t, err, tag)
}
}
| {
for _, example := range []struct {
data []string
size, offset, length int64
substr string
}{
{[]string{}, 0, 0, 0, ""},
{[]string{""}, 0, 0, 0, ""},
{[]string{"abcdefghijkl"}, 12, 1, 4, "bcde"},
{[]string{"abcdef", "ghijkl"}, 12, 1, 4, "bcde"},
{[]string{"abcdef", "ghijkl"}, 12, 1, 5, "bcdef"},
{[]string{"abcdef", "ghijkl"}, 12, 1, 6, "bcdefg"},
{[]string{"abcdef", "ghijkl"}, 12, 5, 4, "fghi"},
{[]string{"abcdef", "ghijkl"}, 12, 6, 4, "ghij"},
{[]string{"abcdef", "ghijkl"}, 12, 7, 4, "hijk"},
{[]string{"abcdef", "ghijkl"}, 12, 7, 5, "hijkl"},
{[]string{"abcdef", "ghijkl", "mnopqr"}, 18, 7, 7, "hijklmn"},
{[]string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"}, 12, 7, 3, "hij"},
} {
var readers []Ranger
for _, data := range example.data {
readers = append(readers, ByteRanger([]byte(data)))
}
rr := Concat(readers...)
if rr.Size() != example.size {
t.Fatalf("invalid size: %v != %v", rr.Size(), example.size)
}
r, err := rr.Range(context.Background(), example.offset, example.length)
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
data, err := ioutil.ReadAll(r)
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
if !bytes.Equal(data, []byte(example.substr)) {
t.Fatalf("invalid subrange: %#v != %#v", string(data), example.substr)
}
}
} |
walking_turns.rs | use std::collections::{BTreeMap, BTreeSet};
use abstutil::wraparound_get;
use geom::{Distance, Line, PolyLine, Pt2D, Ring};
use crate::{
Direction, DrivingSide, Intersection, IntersectionID, Lane, LaneID, LaneType, Map, Road, Turn,
TurnID, TurnType,
};
/// Generate Crosswalk and SharedSidewalkCorner (places where two sidewalks directly meet) turns
pub fn make_walking_turns(map: &Map, i: &Intersection) -> Vec<Turn> {
if i.is_footway(map) {
return make_footway_turns(map, i);
}
let driving_side = map.config.driving_side;
let all_roads = map.all_roads();
let lanes = map.all_lanes();
let roads: Vec<&Road> = i
.get_roads_sorted_by_incoming_angle(all_roads)
.into_iter()
.map(|id| &all_roads[id.0])
.collect();
let mut result: Vec<Turn> = Vec::new();
// I'm a bit confused when to do -1 and +1 honestly, but this works in practice. Angle sorting
// may be a little backwards.
let idx_offset = if driving_side == DrivingSide::Right {
-1
} else {
1
};
if roads.len() == 2 {
if let Some(turns) = make_degenerate_crosswalks(i.id, lanes, roads[0], roads[1]) {
result.extend(turns);
}
// TODO Argh, duplicate logic for SharedSidewalkCorners
for idx1 in 0..roads.len() {
if let Some(l1) = get_sidewalk(lanes, roads[idx1].incoming_lanes(i.id)) {
if let Some(l2) = get_sidewalk(
lanes,
wraparound_get(&roads, (idx1 as isize) + idx_offset).outgoing_lanes(i.id),
) {
if l1.last_pt() != l2.first_pt() {
let geom = make_shared_sidewalk_corner(driving_side, i, l1, l2);
result.push(Turn {
id: turn_id(i.id, l1.id, l2.id),
turn_type: TurnType::SharedSidewalkCorner,
other_crosswalk_ids: BTreeSet::new(),
geom: geom.clone(),
});
result.push(Turn {
id: turn_id(i.id, l2.id, l1.id),
turn_type: TurnType::SharedSidewalkCorner,
other_crosswalk_ids: BTreeSet::new(),
geom: geom.reversed(),
});
}
}
}
}
return result;
}
if roads.len() == 1 {
if let Some(l1) = get_sidewalk(lanes, roads[0].incoming_lanes(i.id)) {
if let Some(l2) = get_sidewalk(lanes, roads[0].outgoing_lanes(i.id)) {
let geom = make_shared_sidewalk_corner(driving_side, i, l1, l2);
result.push(Turn {
id: turn_id(i.id, l1.id, l2.id),
turn_type: TurnType::SharedSidewalkCorner,
other_crosswalk_ids: BTreeSet::new(),
geom: geom.clone(),
});
result.push(Turn {
id: turn_id(i.id, l2.id, l1.id),
turn_type: TurnType::SharedSidewalkCorner,
other_crosswalk_ids: BTreeSet::new(),
geom: geom.reversed(),
});
}
}
return result;
}
for idx1 in 0..roads.len() {
if let Some(l1) = get_sidewalk(lanes, roads[idx1].incoming_lanes(i.id)) {
// Make the crosswalk to the other side
if let Some(l2) = get_sidewalk(lanes, roads[idx1].outgoing_lanes(i.id)) {
result.extend(
make_crosswalks(i.id, l1, l2, driving_side)
.into_iter()
.flatten(),
);
}
// Find the shared corner
if let Some(l2) = get_sidewalk(
lanes,
wraparound_get(&roads, (idx1 as isize) + idx_offset).outgoing_lanes(i.id),
) {
if l1.last_pt() != l2.first_pt() {
let geom = make_shared_sidewalk_corner(driving_side, i, l1, l2);
result.push(Turn {
id: turn_id(i.id, l1.id, l2.id),
turn_type: TurnType::SharedSidewalkCorner,
other_crosswalk_ids: BTreeSet::new(),
geom: geom.clone(),
});
result.push(Turn {
id: turn_id(i.id, l2.id, l1.id),
turn_type: TurnType::SharedSidewalkCorner,
other_crosswalk_ids: BTreeSet::new(),
geom: geom.reversed(),
});
}
} else if let Some(l2) = get_sidewalk(
lanes,
wraparound_get(&roads, (idx1 as isize) + idx_offset).incoming_lanes(i.id),
) {
// Adjacent road is missing a sidewalk on the near side, but has one on the far
// side
result.extend(
make_crosswalks(i.id, l1, l2, driving_side)
.into_iter()
.flatten(),
);
} else {
// We may need to add a crosswalk over this intermediate road that has no
// sidewalks at all. There might be a few in the way -- think highway onramps.
// TODO Refactor and loop until we find something to connect it to?
if let Some(l2) = get_sidewalk(
lanes,
wraparound_get(&roads, (idx1 as isize) + 2 * idx_offset).outgoing_lanes(i.id),
) {
result.extend(
make_crosswalks(i.id, l1, l2, driving_side)
.into_iter()
.flatten(),
);
} else if let Some(l2) = get_sidewalk(
lanes,
wraparound_get(&roads, (idx1 as isize) + 2 * idx_offset).incoming_lanes(i.id),
) {
result.extend(
make_crosswalks(i.id, l1, l2, driving_side)
.into_iter()
.flatten(),
);
} else if roads.len() > 3 {
if let Some(l2) = get_sidewalk(
lanes,
wraparound_get(&roads, (idx1 as isize) + 3 * idx_offset)
.outgoing_lanes(i.id),
) {
result.extend(
make_crosswalks(i.id, l1, l2, driving_side)
.into_iter()
.flatten(),
);
}
}
}
}
}
result
}
/// Filter out crosswalks on really short roads. In reality, these roads are usually located within
/// an intersection, which isn't a valid place for a pedestrian crossing.
pub fn filter_turns(mut input: Vec<Turn>, map: &Map, i: &Intersection) -> Vec<Turn> {
for r in &i.roads {
if map.get_r(*r).is_extremely_short() {
input.retain(|t| {
!(map.get_l(t.id.src).parent == *r
&& map.get_l(t.id.dst).parent == *r
&& t.turn_type == TurnType::Crosswalk)
});
}
}
input
}
// TODO Need to filter out extraneous crosswalks. Why weren't they being created before?
pub fn _make_walking_turns_v2(map: &Map, i: &Intersection) -> Vec<Turn> {
let driving_side = map.config.driving_side;
let all_roads = map.all_roads();
let all_lanes = map.all_lanes();
// Consider all roads in counter-clockwise order. Every road has up to two sidewalks. Gather
// those in order, remembering what roads don't have them.
let mut lanes: Vec<Option<&Lane>> = Vec::new();
let mut num_sidewalks = 0;
for r in i.get_roads_sorted_by_incoming_angle(all_roads) {
let r = &all_roads[r.0];
let mut fwd = None;
let mut back = None;
for (l, dir, lt) in r.lanes_ltr() {
if lt.is_walkable() {
if dir == Direction::Fwd {
fwd = Some(&all_lanes[&l]);
} else {
back = Some(&all_lanes[&l]);
}
}
}
if fwd.is_some() {
num_sidewalks += 1;
}
if back.is_some() {
num_sidewalks += 1;
}
let (in_lane, out_lane) = if r.src_i == i.id {
(back, fwd)
} else {
(fwd, back)
};
lanes.push(in_lane);
lanes.push(out_lane);
}
if num_sidewalks <= 1 {
return Vec::new();
}
// Make sure we start with a sidewalk.
while lanes[0].is_none() {
lanes.rotate_left(1);
}
let mut result: Vec<Turn> = Vec::new();
let mut from: Option<&Lane> = lanes[0];
let first_from = from.unwrap().id;
let mut adj = true;
for l in lanes.iter().skip(1).chain(lanes.iter()) {
if i.id.0 == 284 {
println!(
"looking at {:?}. from is {:?}, first_from is {}, adj is {}",
l.map(|l| l.id),
from.map(|l| l.id),
first_from,
adj
);
}
if from.is_none() {
from = *l;
adj = true;
continue;
}
let l1 = from.unwrap();
if l.is_none() {
adj = false;
continue;
}
let l2 = l.unwrap();
if adj && l1.parent != l2.parent {
// Because of the order we go, have to swap l1 and l2 here. l1 is the outgoing, l2 the
// incoming.
let geom = make_shared_sidewalk_corner(driving_side, i, l2, l1);
result.push(Turn {
id: turn_id(i.id, l1.id, l2.id),
turn_type: TurnType::SharedSidewalkCorner,
other_crosswalk_ids: BTreeSet::new(),
geom: geom.reversed(),
});
result.push(Turn {
id: turn_id(i.id, l2.id, l1.id),
turn_type: TurnType::SharedSidewalkCorner,
other_crosswalk_ids: BTreeSet::new(),
geom,
});
from = Some(l2);
// adj stays true
} else {
// TODO Just one for degenerate intersections
result.extend(
make_crosswalks(i.id, l1, l2, driving_side)
.into_iter()
.flatten(),
);
from = Some(l2);
adj = true;
}
// Have we made it all the way around?
if first_from == from.unwrap().id {
break;
}
}
result
}
/// At an intersection of footpaths only, just generate a turn between every pair of lanes.
fn make_footway_turns(map: &Map, i: &Intersection) -> Vec<Turn> {
let lanes = i
.incoming_lanes
.iter()
.chain(&i.outgoing_lanes)
.filter_map(|l| {
let l = map.get_l(*l);
if l.is_walkable() {
Some(l)
} else {
None
}
})
.collect::<Vec<&Lane>>();
let mut results = Vec::new();
for l1 in &lanes {
for l2 in &lanes {
if l1.id == l2.id {
continue;
}
let maybe_geom = PolyLine::new(vec![l1.endpoint(i.id), l2.endpoint(i.id)]);
let geom = maybe_geom.unwrap_or_else(|_| {
// TODO Gross! After improving intersection geometry where these cases are
// happening, if this still happens, maybe it's time to make turn geometry be
// optional.
PolyLine::must_new(vec![l1.endpoint(i.id), l1.endpoint(i.id).offset(0.1, 0.1)])
});
results.push(Turn {
id: turn_id(i.id, l1.id, l2.id),
turn_type: TurnType::SharedSidewalkCorner,
other_crosswalk_ids: BTreeSet::new(),
geom,
});
}
}
results
}
fn make_crosswalks(
i: IntersectionID,
l1: &Lane,
l2: &Lane,
driving_side: DrivingSide,
) -> Option<Vec<Turn>> {
let l1_pt = l1.endpoint(i);
let l2_pt = l2.endpoint(i);
// This is one of those uncomfortably "trial-and-error" kind of things.
let mut direction = if (l1.dst_i == i) == (l2.dst_i == i) {
-1.0
} else {
1.0
};
if driving_side == DrivingSide::Left {
direction *= -1.0;
}
// Jut out a bit into the intersection, cross over, then jut back in. Assumes sidewalks are the
// same width.
let line = Line::new(l1_pt, l2_pt)?.shift_either_direction(direction * l1.width / 2.0);
let geom_fwds = PolyLine::deduping_new(vec![l1_pt, line.pt1(), line.pt2(), l2_pt]).ok()?;
Some(vec![
Turn {
id: turn_id(i, l1.id, l2.id),
turn_type: TurnType::Crosswalk,
other_crosswalk_ids: vec![turn_id(i, l2.id, l1.id)].into_iter().collect(),
geom: geom_fwds.clone(),
},
Turn {
id: turn_id(i, l2.id, l1.id),
turn_type: TurnType::Crosswalk,
other_crosswalk_ids: vec![turn_id(i, l1.id, l2.id)].into_iter().collect(),
geom: geom_fwds.reversed(),
},
])
}
// Only one physical crosswalk for degenerate intersections, right in the middle.
fn make_degenerate_crosswalks(
i: IntersectionID,
lanes: &BTreeMap<LaneID, Lane>,
r1: &Road,
r2: &Road,
) -> Option<Vec<Turn>> {
let l1_in = get_sidewalk(lanes, r1.incoming_lanes(i))?;
let l1_out = get_sidewalk(lanes, r1.outgoing_lanes(i))?;
let l2_in = get_sidewalk(lanes, r2.incoming_lanes(i))?;
let l2_out = get_sidewalk(lanes, r2.outgoing_lanes(i))?;
let pt1 = Line::new(l1_in.last_pt(), l2_out.first_pt())?.percent_along(0.5)?;
let pt2 = Line::new(l1_out.first_pt(), l2_in.last_pt())?.percent_along(0.5)?;
if pt1 == pt2 {
return None;
}
let mut all_ids = BTreeSet::new();
all_ids.insert(turn_id(i, l1_in.id, l1_out.id));
all_ids.insert(turn_id(i, l1_out.id, l1_in.id));
all_ids.insert(turn_id(i, l2_in.id, l2_out.id));
all_ids.insert(turn_id(i, l2_out.id, l2_in.id));
Some(
vec![
Turn {
id: turn_id(i, l1_in.id, l1_out.id),
turn_type: TurnType::Crosswalk,
other_crosswalk_ids: all_ids.clone(),
geom: PolyLine::deduping_new(vec![l1_in.last_pt(), pt1, pt2, l1_out.first_pt()])
.ok()?,
},
Turn {
id: turn_id(i, l1_out.id, l1_in.id),
turn_type: TurnType::Crosswalk,
other_crosswalk_ids: all_ids.clone(),
geom: PolyLine::deduping_new(vec![l1_out.first_pt(), pt2, pt1, l1_in.last_pt()])
.ok()?,
},
Turn {
id: turn_id(i, l2_in.id, l2_out.id),
turn_type: TurnType::Crosswalk,
other_crosswalk_ids: all_ids.clone(),
geom: PolyLine::deduping_new(vec![l2_in.last_pt(), pt2, pt1, l2_out.first_pt()])
.ok()?,
},
Turn {
id: turn_id(i, l2_out.id, l2_in.id),
turn_type: TurnType::Crosswalk,
other_crosswalk_ids: all_ids.clone(),
geom: PolyLine::deduping_new(vec![l2_out.first_pt(), pt1, pt2, l2_in.last_pt()])
.ok()?,
},
]
.into_iter()
.map(|mut t| {
t.other_crosswalk_ids.remove(&t.id);
t
})
.collect(),
)
}
// TODO This doesn't handle sidewalk/shoulder transitions
fn make_shared_sidewalk_corner(
driving_side: DrivingSide,
i: &Intersection,
l1: &Lane,
l2: &Lane,
) -> PolyLine {
let baseline = PolyLine::must_new(vec![l1.last_pt(), l2.first_pt()]);
// Find all of the points on the intersection polygon between the two sidewalks. Assumes
// sidewalks are the same length.
let corner1 = l1.last_line().shift_right(l1.width / 2.0).pt2();
let corner2 = l2.first_line().shift_right(l2.width / 2.0).pt1();
// TODO Something like this will be MUCH simpler and avoid going around the long way sometimes.
if false {
return Ring::must_new(i.polygon.points().clone())
.get_shorter_slice_btwn(corner1, corner2)
.unwrap();
}
// The order of the points here seems backwards, but it's because we scan from corner2
// to corner1 below.
let mut pts_between = vec![l2.first_pt()];
// Intersection polygons are constructed in clockwise order, so do corner2 to corner1.
let mut i_pts = i.polygon.points().clone();
if driving_side == DrivingSide::Left {
i_pts.reverse();
}
if let Some(pts) = Pt2D::find_pts_between(&i_pts, corner2, corner1, Distance::meters(0.5)) {
let mut deduped = pts.clone();
deduped.dedup();
if deduped.len() >= 2 {
if abstutil::contains_duplicates(&deduped.iter().map(|pt| pt.to_hashable()).collect()) {
warn!(
"SharedSidewalkCorner between {} and {} has weird duplicate geometry, so just \
doing straight line",
l1.id, l2.id
);
return baseline;
}
if let Ok(pl) = PolyLine::must_new(deduped).shift_right(l1.width.min(l2.width) / 2.0) {
pts_between.extend(pl.points());
} else {
warn!(
"SharedSidewalkCorner between {} and {} has weird collapsing geometry, so \
just doing straight line",
l1.id, l2.id
);
return baseline;
}
}
}
pts_between.push(l1.last_pt());
pts_between.reverse();
// Pretty big smoothing; I'm observing funky backtracking about 0.5m long.
let mut final_pts = Pt2D::approx_dedupe(pts_between.clone(), Distance::meters(1.0));
if final_pts.len() < 2 {
warn!(
"SharedSidewalkCorner between {} and {} couldn't do final smoothing",
l1.id, l2.id
);
final_pts = pts_between;
final_pts.dedup()
}
// The last point might be removed as a duplicate, but we want the start/end to exactly match
// up at least.
if *final_pts.last().unwrap() != l2.first_pt() {
final_pts.pop();
final_pts.push(l2.first_pt());
}
if abstutil::contains_duplicates(&final_pts.iter().map(|pt| pt.to_hashable()).collect()) |
let result = PolyLine::must_new(final_pts);
if result.length() > 10.0 * baseline.length() {
warn!(
"SharedSidewalkCorner between {} and {} explodes to {} long, so just doing straight \
line",
l1.id,
l2.id,
result.length()
);
return baseline;
}
result
}
fn turn_id(parent: IntersectionID, src: LaneID, dst: LaneID) -> TurnID {
TurnID { parent, src, dst }
}
fn get_sidewalk<'a>(
lanes: &'a BTreeMap<LaneID, Lane>,
children: Vec<(LaneID, LaneType)>,
) -> Option<&'a Lane> {
for (id, lt) in children {
if lt.is_walkable() {
return Some(&lanes[&id]);
}
}
None
}
| {
warn!(
"SharedSidewalkCorner between {} and {} has weird duplicate geometry, so just doing \
straight line",
l1.id, l2.id
);
return baseline;
} |
batch_netmeta.py | ################################################################
# System's dependencies
################################################################
import os
import sys
import time
import argparse
################################################################
# Local dependencies
################################################################
from org.gesis.lib import io
from org.gesis.lib import graph
from org.gesis.lib import homophily
################################################################
# Constants
################################################################
DATASETS = ['aps','hate','blogs','wikipedia']
################################################################
# Main
################################################################
def run(datapath, dataset, steps, njobs, output):
if dataset not in DATASETS:
raise Exception("dataset " + dataset +" does not exist.") | N, fm, d, plo_M, plo_m, pli_M, pli_m, EMM, EMm, EmM, Emm, hMM, hmm, _N, _d, _mindiff = homophily.get_metadata(g, steps,
njobs=njobs, verbose=True, seed=None)
print("N:{}".format(N))
print("fm:{}".format(fm))
print("d:{}".format(d))
print("plo_M:{}".format(plo_M))
print("plo_m:{}".format(plo_m))
print("pli_M:{}".format(pli_M))
print("pli_m:{}".format(pli_m))
print("EMM:{}".format(EMM))
print("EMm:{}".format(EMm))
print("EmM:{}".format(EmM))
print("Emm:{}".format(Emm))
print("hMM:{}".format(hMM))
print("hmm:{}".format(hmm))
print("_N:{}".format(_N))
print("_d:{}".format(_d))
print("_mindiff:{}".format(_mindiff))
### Storing metadata info into .csv file
t1 = "dataset,N,fm,d,plo_M,plo_m,pli_M,pli_m,EMM,EMm,EmM,Emm,hMM,hmm,_N,_d,_mindiff"
t2 = ",".join([dataset, str(N), str(fm), str(d), str(plo_M), str(plo_m), str(pli_M), str(pli_m),
str(EMM), str(EMm), str(EmM), str(Emm), str(hMM), str(hmm), str(_N), str(_d), str(_mindiff)])
path = os.path.join(output,dataset,"network_metadata.csv")
io.save_text("{}\n{}".format(t1,t2), path)
################################################################
# Main
################################################################
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", help=",".join(DATASETS), type=str, required=True)
parser.add_argument("--steps", help="decimals (eg. 0.01, 0.05) to compute homophily", type=float, required=True)
parser.add_argument("--njobs", help="parallel jobs", type=int, default=1)
parser.add_argument("--datapath", help="path/folder where the .gpickle files are.", type=str, required=True)
parser.add_argument("--output", help="path/folder where to store csv file", type=str, default='.')
args = parser.parse_args()
start_time = time.time()
run(args.datapath, args.dataset, args.steps, args.njobs, args.output)
print("--- %s seconds ---" % (time.time() - start_time)) |
print(dataset, steps, njobs)
g = graph.get_graph(datapath, dataset) |
main.go | package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"time"
"blockworker/core/common"
"blockworker/core/config"
"blockworker/core/datastore"
"blockworker/core/encryption"
"blockworker/core/logging"
. "blockworker/core/logging"
"blockworker/blockworkercore/worker"
"blockworker/blockworkercore/zcn"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/spf13/viper"
"go.uber.org/zap"
)
func initializeConfig() {
config.Configuration.ChainID = viper.GetString("server_chain.id")
config.Configuration.SignatureScheme = viper.GetString("server_chain.signature_scheme")
config.Configuration.Port = viper.GetInt("port")
config.Configuration.Miners = viper.GetStringSlice("miners")
config.Configuration.Sharders = viper.GetStringSlice("sharders")
| config.Configuration.MongoURL = viper.GetString("mongo.url")
config.Configuration.DBName = viper.GetString("mongo.db_name")
config.Configuration.MongoPoolSize = viper.GetInt64("mongo.pool_size")
config.Configuration.RoundFetchDelayInMilliSeconds = viper.GetInt64("worker.round_fetch_delay")
}
func initHandlers(r *mux.Router) {
r.HandleFunc("/", HomePageHandler)
}
var startTime time.Time
func main() {
deploymentMode := flag.Int("deployment_mode", 2, "deployment_mode")
keysFile := flag.String("keys_file", "", "keys_file")
flag.Parse()
config.Configuration.DeploymentMode = byte(*deploymentMode)
config.SetupDefaultConfig()
config.SetupConfig()
if config.Development() {
logging.InitLogging("development")
} else {
logging.InitLogging("production")
}
initializeConfig()
reader, err := os.Open(*keysFile)
if err != nil {
panic(err)
}
publicKey, privateKey := encryption.ReadKeys(reader)
config.Configuration.SetWallet(publicKey, privateKey)
common.SetupRootContext(context.Background())
checkForDBConnection(context.Background())
zcn.InitZCN()
address := fmt.Sprintf(":%v", config.Configuration.Port)
var server *http.Server
r := mux.NewRouter()
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET"})
rHandler := handlers.CORS(originsOk, headersOk, methodsOk)(r)
if config.Development() {
server = &http.Server{
Addr: address,
ReadTimeout: 30 * time.Second,
MaxHeaderBytes: 1 << 20,
Handler: rHandler,
}
} else {
server = &http.Server{
Addr: address,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
MaxHeaderBytes: 1 << 20,
Handler: rHandler,
}
}
common.HandleShutdown(server)
initHandlers(r)
go worker.SetupWorkers(context.Background())
startTime = time.Now().UTC()
Logger.Info("Ready to listen to the requests on ", zap.Any("port", config.Configuration.Port))
log.Fatal(server.ListenAndServe())
}
// HomePageHandler for blockworker
func HomePageHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<div>Running since %v ...\n", startTime)
fmt.Fprintf(w, "<div>Working on the chain: %v</div>\n", config.Configuration.ChainID)
fmt.Fprintf(w, "<div>I am blockWorker with <ul><li>miners:%v</li><li>sharders:%v</li></ul></div>\n",
config.Configuration.Miners, config.Configuration.Sharders)
}
func checkForDBConnection(ctx context.Context) {
retries := 0
var err error
for retries < 600 {
Logger.Info("Trying to connect to mongoDB ...")
err = datastore.GetStore().Open(ctx)
if err != nil {
time.Sleep(1 * time.Second)
retries++
continue
}
Logger.Info("DB Connection done.")
break
}
if err != nil {
Logger.Error("Error in opening the database. Shutting the server down")
panic(err)
}
} | |
application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs | //= require angular-cookies
//= require angular-ui-router
//= require angular-bootstrap
//= require angular-rails-templates
//= require_tree .
//= require_tree ../templates | //= require bootstrap
//= require angular |
main.go | // stellar-sign is a small interactive utility to help you contribute a
// signature to a transaction envelope.
//
// It prompts you for a key
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/howeyc/gopass"
"github.com/danielnapierski/go-alt/build"
"github.com/danielnapierski/go-alt/xdr"
)
var in *bufio.Reader
var infile = flag.String("infile", "", "transaction envelope")
func | () {
flag.Parse()
in = bufio.NewReader(os.Stdin)
var (
env string
err error
)
if *infile == "" {
// read envelope
env, err = readLine("Enter envelope (base64): ", false)
if err != nil {
log.Fatal(err)
}
} else {
file, err := os.Open(*infile)
if err != nil {
log.Fatal(err)
}
defer file.Close()
raw, err := ioutil.ReadAll(file)
if err != nil {
log.Fatal(err)
}
env = string(raw)
}
// parse the envelope
var txe xdr.TransactionEnvelope
err = xdr.SafeUnmarshalBase64(env, &txe)
if err != nil {
log.Fatal(err)
}
fmt.Println("")
fmt.Println("Transaction Summary:")
fmt.Printf(" source: %s\n", txe.Tx.SourceAccount.Address())
fmt.Printf(" ops: %d\n", len(txe.Tx.Operations))
fmt.Printf(" sigs: %d\n", len(txe.Signatures))
fmt.Println("")
// TODO: add operation details
// read seed
seed, err := readLine("Enter seed: ", true)
if err != nil {
log.Fatal(err)
}
// sign the transaction
b := &build.TransactionEnvelopeBuilder{E: &txe}
b.Init()
err = b.MutateTX(build.PublicNetwork)
if err != nil {
log.Fatal(err)
}
err = b.Mutate(build.Sign{seed})
if err != nil {
log.Fatal(err)
}
newEnv, err := xdr.MarshalBase64(b.E)
if err != nil {
log.Fatal(err)
}
fmt.Print("\n==== Result ====\n\n")
fmt.Print("```\n")
fmt.Println(newEnv)
fmt.Print("```\n")
}
func readLine(prompt string, private bool) (string, error) {
fmt.Fprintf(os.Stdout, prompt)
var line string
var err error
if private {
str, err := gopass.GetPasswdMasked()
if err != nil {
return "", err
}
line = string(str)
} else {
line, err = in.ReadString('\n')
if err != nil {
return "", err
}
}
return strings.Trim(line, "\n"), nil
}
| main |
hover.rs | use context::*;
use languageserver_types::request::Request;
use languageserver_types::*;
use serde::Deserialize;
use std::str;
use types::*;
use url::Url;
pub fn text_document_hover(params: EditorParams, meta: &EditorMeta, ctx: &mut Context) {
let req_params = PositionParams::deserialize(params.clone());
if req_params.is_err() {
error!("Params should follow PositionParams structure");
return;
}
let req_params = req_params.unwrap();
let position = req_params.position;
let req_params = TextDocumentPositionParams {
text_document: TextDocumentIdentifier {
uri: Url::from_file_path(&meta.buffile).unwrap(),
},
position,
};
let id = ctx.next_request_id();
ctx.response_waitlist.insert(
id.clone(),
(meta.clone(), request::HoverRequest::METHOD.into(), params),
);
ctx.call(id, request::HoverRequest::METHOD.into(), req_params);
}
pub fn editor_hover(
meta: &EditorMeta,
params: &PositionParams,
result: Option<Hover>,
ctx: &mut Context,
) {
let diagnostics = ctx.diagnostics.get(&meta.buffile);
let pos = params.position;
let diagnostics = diagnostics
.and_then(|x| {
Some(
x.iter()
.filter(|x| {
let start = x.range.start;
let end = x.range.end;
(start.line < pos.line && pos.line < end.line)
|| (start.line == pos.line
&& pos.line == end.line
&& start.character <= pos.character
&& pos.character <= end.character)
|| (start.line == pos.line
&& pos.line <= end.line
&& start.character <= pos.character)
|| (start.line <= pos.line
&& end.line == pos.line
&& pos.character <= end.character)
}).map(|x| format!("• {}", str::trim(&x.message)))
.collect::<Vec<String>>()
.join("\n"),
)
}).unwrap_or_else(String::new);
let contents = match result {
None => "".to_string(),
Some(result) => match result.contents {
HoverContents::Scalar(contents) => contents.plaintext(),
HoverContents::Array(contents) => contents
.into_iter()
.map(|x| format!("• {}", str::trim(&x.plaintext())))
.collect::<Vec<String>>()
.join("\n"),
HoverContents::Markup(contents) => contents.value,
},
};
if contents.is_empty() && diagnostics.is_empty() {
| let position = format!("{}.{}", pos.line + 1, pos.character + 1);
let command = if diagnostics.is_empty() {
format!("lsp-show-hover {} %§{}§", position, contents)
} else if contents.is_empty() {
format!("lsp-show-hover {} %§{}§", position, diagnostics)
} else {
format!(
"lsp-show-hover {} %§{}\n\n{}§",
position, contents, diagnostics
)
};
ctx.exec(meta.clone(), command);
}
trait PlainText {
fn plaintext(self) -> String;
}
impl PlainText for MarkedString {
fn plaintext(self) -> String {
match self {
MarkedString::String(contents) => contents,
MarkedString::LanguageString(contents) => contents.value,
}
}
}
| return;
}
|
mod.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// from gst-gir-files (https://gitlab.freedesktop.org/gstreamer/gir-files-rs.git)
// DO NOT EDIT
mod color_balance;
pub use self::color_balance::ColorBalance;
mod color_balance_channel;
pub use self::color_balance_channel::ColorBalanceChannel;
mod navigation;
pub use self::navigation::Navigation;
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
mod video_aggregator_parallel_convert_pad;
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
pub use self::video_aggregator_parallel_convert_pad::VideoAggregatorParallelConvertPad;
mod video_buffer_pool;
pub use self::video_buffer_pool::VideoBufferPool;
mod video_decoder;
pub use self::video_decoder::VideoDecoder;
mod video_encoder;
pub use self::video_encoder::VideoEncoder;
mod video_filter;
pub use self::video_filter::VideoFilter;
mod video_orientation;
pub use self::video_orientation::VideoOrientation;
mod video_overlay;
pub use self::video_overlay::VideoOverlay;
mod video_sink;
pub use self::video_sink::VideoSink;
mod enums;
pub use self::enums::ColorBalanceType;
pub use self::enums::NavigationCommand;
pub use self::enums::NavigationEventType;
pub use self::enums::NavigationMessageType;
pub use self::enums::NavigationQueryType;
#[cfg(any(feature = "v1_18", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_18")))]
pub use self::enums::VideoAFDSpec;
#[cfg(any(feature = "v1_18", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_18")))]
pub use self::enums::VideoAFDValue;
pub use self::enums::VideoAlphaMode;
#[cfg(any(feature = "v1_16", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))]
pub use self::enums::VideoCaptionType;
pub use self::enums::VideoChromaMode;
pub use self::enums::VideoColorMatrix;
pub use self::enums::VideoColorPrimaries;
pub use self::enums::VideoDitherMethod;
#[cfg(any(feature = "v1_12", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_12")))]
pub use self::enums::VideoFieldOrder;
pub use self::enums::VideoFormat;
pub use self::enums::VideoGammaMode;
pub use self::enums::VideoInterlaceMode;
pub use self::enums::VideoMatrixMode;
pub use self::enums::VideoMultiviewFramePacking;
pub use self::enums::VideoMultiviewMode;
#[cfg(any(feature = "v1_10", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))]
pub use self::enums::VideoOrientationMethod;
pub use self::enums::VideoPrimariesMode;
pub use self::enums::VideoResamplerMethod;
pub use self::enums::VideoTileMode;
pub use self::enums::VideoTransferFunction;
mod flags; | pub use self::flags::VideoChromaSite;
pub use self::flags::VideoCodecFrameFlags;
#[cfg(any(feature = "v1_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))]
pub use self::flags::VideoDecoderRequestSyncPointFlags;
pub use self::flags::VideoFlags;
pub use self::flags::VideoFormatFlags;
pub use self::flags::VideoFrameFlags;
pub use self::flags::VideoMultiviewFlags;
pub use self::flags::VideoOverlayFormatFlags;
pub use self::flags::VideoPackFlags;
#[cfg(any(feature = "v1_10", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))]
pub use self::flags::VideoTimeCodeFlags;
#[doc(hidden)]
pub mod traits {
pub use super::color_balance::ColorBalanceExt;
pub use super::color_balance_channel::ColorBalanceChannelExt;
pub use super::navigation::NavigationExt;
pub use super::video_decoder::VideoDecoderExt;
pub use super::video_encoder::VideoEncoderExt;
pub use super::video_orientation::VideoOrientationExt;
pub use super::video_overlay::VideoOverlayExt;
pub use super::video_sink::VideoSinkExt;
} | pub use self::flags::VideoBufferFlags; |
stick.component.ts | import { Component, ElementRef, Input } from '@angular/core';
@Component({
selector: 'stick',
template: `<div class="stick">
<svg>
<circle [attr.cx]="left" [attr.cy]="top" [attr.r]="radius" fill="green"/>
</svg>
</div>`,
styles: [`
.stick {
position: absolute;
width: 100%;
height: 100%;
z-index: 1;
}
.stick > svg {
width: 100%;
height: 100%;
}`]
})
export class | {
@Input('radius') radius: number;
@Input('width') width: number;
@Input('height') height: number;
@Input('center')
set theCenter(center: number[]) {
this.left = center[0];
this.top = center[1];
}
left: number = 20;
top: number = 20;
constructor(private element: ElementRef) {}
} | StickComponent |
clean_imu_data.py | #!/usr/bin/env python
import rospy
import math
from sensor_msgs.msg import Imu
import tf
import tf2_ros
import tf2_geometry_msgs
import geometry_msgs.msg
lastPub = 0
lastClean = 0
def callbackRaw(imu_in):
global lastPub, lastClean
if (lastClean != 0 and lastClean > rospy.Time.now() - rospy.Duration(1)):
return #Don't publish raw data if clean data is available from estimator
if (lastPub == 0 or imu_in.header.stamp > lastPub):
lastPub = imu_in.header.stamp
pub.publish(imu_in)
def callbackData(imu_in):
global lastPub, lastClean
if (lastPub == 0 or imu_in.header.stamp > lastPub):
lastPub = imu_in.header.stamp
lastClean = imu_in.header.stamp
pub.publish(imu_in)
def | ():
rospy.init_node('clean_imu_data', anonymous=True)
subRaw = rospy.Subscriber('/mavros/imu/data_raw', Imu, callbackRaw)
subData = rospy.Subscriber('/mavros/imu/data', Imu, callbackData)
rospy.spin()
if __name__ == '__main__':
rospy.sleep(1)
pub = rospy.Publisher('filtered_imu', Imu, queue_size=10)
filter_imu()
tf_buffer = tf2_ros.Buffer(rospy.Duration(10.0)) #tf buffer length
tf_listener = tf2_ros.TransformListener(tf_buffer)
| filter_imu |
horiz.rs | use super::*;
use ascii_canvas::AsciiView;
use itertools::Itertools;
#[derive(Debug)]
pub struct | {
items: Vec<Box<dyn Content>>,
separate: usize, // 0 => overlapping, 1 => each on its own line, 2 => paragraphs
}
impl Horiz {
pub fn new(items: Vec<Box<dyn Content>>, separate: usize) -> Self {
Horiz { items, separate }
}
}
impl Content for Horiz {
fn min_width(&self) -> usize {
self.items
.iter()
.map(|c| c.min_width())
.intersperse(self.separate)
.sum()
}
fn emit(&self, view: &mut dyn AsciiView) {
emit_horiz(view, &self.items, self.separate);
}
fn into_wrap_items(self: Box<Self>, wrap_items: &mut Vec<Box<dyn Content>>) {
wrap_items.push(self);
}
}
pub fn emit_horiz(view: &mut dyn AsciiView, items: &[Box<dyn Content>], separate: usize) {
let mut column = 0;
for item in items {
let (_, end_column) = item.emit_at(view, 0, column);
column = end_column + separate;
}
}
| Horiz |
wasm_tar.d.ts | /* tslint:disable */
/* eslint-disable */
/**
*/
export class | {
free(): void;
/**
* @returns {WasmTar}
*/
static new(): WasmTar;
/**
* @param {number} length
*/
allocate(length: number): void;
/**
* @returns {number}
*/
memory_pos(): number;
/**
* @returns {Array<any>}
*/
get_entries(): Array<any>;
}
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
export interface InitOutput {
readonly memory: WebAssembly.Memory;
readonly __wbg_wasmtar_free: (a: number) => void;
readonly wasmtar_new: () => number;
readonly wasmtar_allocate: (a: number, b: number) => void;
readonly wasmtar_memory_pos: (a: number) => number;
readonly wasmtar_get_entries: (a: number) => number;
}
/**
* If `module_or_path` is {RequestInfo} or {URL}, makes a request and
* for everything else, calls `WebAssembly.instantiate` directly.
*
* @param {InitInput | Promise<InitInput>} module_or_path
*
* @returns {Promise<InitOutput>}
*/
export default function init (module_or_path?: InitInput | Promise<InitInput>): Promise<InitOutput>;
| WasmTar |
debugging.py | # Copyright 2018 The TensorFlow Probability 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,
# 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.
# ============================================================================
"""Experimental Numpy backend."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import six
from tensorflow_probability.python.internal.backend.numpy import _utils as utils
from tensorflow_probability.python.internal.backend.numpy.ops import convert_to_tensor
from tensorflow_probability.python.internal.backend.numpy.ops import is_tensor
from tensorflow_probability.python.internal.backend.numpy.ops import Tensor
__all__ = [
'Assert',
'assert_equal',
'assert_greater',
'assert_greater_equal',
'assert_integer',
'assert_less',
'assert_less_equal',
'assert_near',
'assert_negative',
'assert_non_negative',
'assert_non_positive',
'assert_none_equal',
'assert_positive',
'assert_proper_iterable',
'assert_rank',
'assert_rank_at_least',
'assert_rank_in',
'assert_scalar',
'check_numerics',
]
JAX_MODE = False
def skip_assert_for_tracers(f):
"""Function decorator that returns None if JAX tracers are detected."""
if not JAX_MODE:
return f
from jax import core as jax_core # pylint: disable=g-import-not-at-top
def wrapped(*args, **kwargs):
if any(isinstance(arg, jax_core.Tracer) for arg
in args + tuple(kwargs.values())):
print('skip assert ' + f.__name__)
return None
return f(*args, **kwargs)
return wrapped
@skip_assert_for_tracers
def _assert_binary(
x, y, comparator, sym, summarize=None, message=None, name=None):
del summarize
del name
x = convert_to_tensor(x)
y = convert_to_tensor(y)
if not np.all(comparator(x, y)):
raise ValueError('Condition x {} y did not hold element-wise. {}'.format(
sym, message or ''))
@skip_assert_for_tracers
def _assert_equal(x, y, summarize=None, message=None, name=None):
del summarize
del name
x = convert_to_tensor(x)
y = convert_to_tensor(y)
if not np.all(np.equal(x, y)):
raise ValueError('Expected x == y but got {} vs {} {}'.format(
x, y, message or ''))
def _assert_greater(x, y, summarize=None, message=None, name=None):
return _assert_binary(
x, y, np.greater, '>', summarize=summarize,
message=message, name=name)
def _assert_less(x, y, summarize=None, message=None, name=None):
return _assert_binary(
x, y, np.less, '<', summarize=summarize,
message=message, name=name)
def _assert_greater_equal(
x, y, summarize=None, message=None, name=None):
return _assert_binary(
x, y, np.greater_equal, '>=', summarize=summarize,
message=message, name=name)
def _assert_less_equal(
x, y, summarize=None, message=None, name=None):
return _assert_binary(
x, y, np.less_equal, '<=', summarize=summarize,
message=message, name=name)
@skip_assert_for_tracers
def _assert_compare_to_zero(
x, comparator, sym, summarize=None, message=None, name=None):
del summarize
del name
x = convert_to_tensor(x)
if not np.all(comparator(x, 0)):
raise ValueError(
'Condition x {} 0 did not hold element-wise; got {} {}'.format(
sym, x, message or ''))
def _assert_positive(x, summarize=None, message=None, name=None):
return _assert_compare_to_zero(
x, np.greater, '>', summarize=summarize, message=message, name=name)
def _assert_negative(x, summarize=None, message=None, name=None):
return _assert_compare_to_zero(
x, np.less, '<', summarize=summarize, message=message, name=name)
def _assert_non_negative(x, summarize=None, message=None, name=None):
return _assert_compare_to_zero(
x, np.greater_equal, '>=',
summarize=summarize, message=message, name=name)
def _assert_non_positive(x, summarize=None, message=None, name=None):
return _assert_compare_to_zero(
x, np.less_equal, '<=', summarize=summarize, message=message, name=name)
def _assert_rank(x, rank, message=None, name=None): # pylint: disable=unused-argument
return _assert_equal(x=len(np.shape(x)), y=rank, message=message)
def _assert_scalar(*_, **__): # pylint: disable=unused-argument
pass
def _assert_integer(*_, **__): # pylint: disable=unused-argument
pass
@skip_assert_for_tracers
def _assert_near(x, y, rtol=None, atol=None,
message=None, summarize=None, name=None): # pylint: disable=unused-argument
"""Raises an error if abs(x - y) > atol + rtol * abs(y)."""
del summarize
del name
x = convert_to_tensor(x)
y = convert_to_tensor(y)
rtol = rtol if rtol else 10 * np.finfo(x.dtype).eps
atol = atol if atol else 10 * np.finfo(x.dtype).eps
if np.any(np.abs(x - y) > atol + rtol * np.abs(y)):
raise ValueError('x = {} and y = {} are not equal to tolerance rtol = {}, '
'atol = {} {}'.format(x, y, rtol, atol, message or ''))
@skip_assert_for_tracers
def _assert_none_equal(x, y, summarize=None, message=None, name=None):
del summarize
del name
x = convert_to_tensor(x)
y = convert_to_tensor(y)
if np.any(np.equal(x, y)):
raise ValueError('Expected x != y but got {} vs {} {}'.format(
x, y, message or ''))
def _assert_proper_iterable(values):
unintentional_iterables = (Tensor, np.ndarray, bytes, six.text_type)
if isinstance(values, unintentional_iterables):
raise TypeError(
'Expected argument "values" to be a "proper" iterable. Found: %s' %
type(values))
if not hasattr(values, '__iter__'):
raise TypeError(
'Expected argument "values" to be iterable. Found: %s' % type(values))
def _assert_rank_at_least(x, rank, message=None, name=None):
del name
if len(x.shape) < rank:
raise ValueError('Expected rank at least {} but got shape {} {}'.format(
rank, x.shape, message or ''))
def _assert_rank_in(*_, **__): # pylint: disable=unused-argument
pass
| 'tf.debugging.Assert',
lambda condition, data, summarize=None, name=None: None)
assert_equal = utils.copy_docstring(
'tf.debugging.assert_equal',
_assert_equal)
assert_greater = utils.copy_docstring(
'tf.debugging.assert_greater',
_assert_greater)
assert_less = utils.copy_docstring(
'tf.debugging.assert_less',
_assert_less)
assert_rank = utils.copy_docstring(
'tf.debugging.assert_rank',
_assert_rank)
assert_scalar = utils.copy_docstring(
'tf.debugging.assert_scalar',
_assert_scalar)
assert_greater_equal = utils.copy_docstring(
'tf.debugging.assert_greater_equal',
_assert_greater_equal)
assert_integer = utils.copy_docstring(
'tf.debugging.assert_integer',
_assert_integer)
assert_less_equal = utils.copy_docstring(
'tf.debugging.assert_less_equal',
_assert_less_equal)
assert_near = utils.copy_docstring(
'tf.debugging.assert_near',
_assert_near)
assert_negative = utils.copy_docstring(
'tf.debugging.assert_negative',
_assert_negative)
assert_non_negative = utils.copy_docstring(
'tf.debugging.assert_non_negative',
_assert_non_negative)
assert_non_positive = utils.copy_docstring(
'tf.debugging.assert_non_positive',
_assert_non_positive)
assert_none_equal = utils.copy_docstring(
'tf.debugging.assert_none_equal',
_assert_none_equal)
assert_positive = utils.copy_docstring(
'tf.debugging.assert_positive',
_assert_positive)
assert_proper_iterable = utils.copy_docstring(
'tf.debugging.assert_proper_iterable',
_assert_proper_iterable)
assert_rank_at_least = utils.copy_docstring(
'tf.debugging.assert_rank_at_least',
_assert_rank_at_least)
assert_rank_in = utils.copy_docstring(
'tf.debugging.assert_rank_in',
_assert_rank_in)
check_numerics = utils.copy_docstring(
'tf.debugging.check_numerics',
lambda x, *_, **__: x)
is_numeric_tensor = utils.copy_docstring(
'tf.debugging.is_numeric_tensor',
lambda x: is_tensor(x) and np.issubdtype(x.dtype, np.number)) | # --- Begin Public Functions --------------------------------------------------
Assert = utils.copy_docstring( # pylint: disable=invalid-name |
response.py | # coding: utf-8
from __future__ import unicode_literals
from django.http import HttpResponse
from django.utils.encoding import smart_str, smart_bytes
class | (HttpResponse):
"""
DRF Response to render data as a PDF File.
kwargs:
- pdf (byte array). The PDF file content.
- file_name (string). The default downloaded file name.
"""
def __init__(self, file_content, file_name, download=True, content_type=None, *args, **kwargs):
disposition = 'filename="{}"'.format(smart_str(file_name))
if download:
disposition = 'attachment; ' + disposition
headers = {
'Content-Disposition': smart_bytes(disposition),
'Content-Length': len(file_content),
}
super(FileResponse, self).__init__(
file_content,
content_type=content_type or 'application/octet-stream',
*args,
**kwargs
)
for h, v in headers.items():
self[h] = v
| FileResponse |
diff_utils.go | /*
Copyright 2019 The Vitess 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,
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.
*/
package worker
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"io"
"strings"
"time"
"google.golang.org/protobuf/proto"
"vitess.io/vitess/go/vt/vtgate/evalengine"
"vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/vttablet/tmclient"
"vitess.io/vitess/go/vt/wrangler"
"context"
"vitess.io/vitess/go/sqlescape"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/vt/grpcclient"
"vitess.io/vitess/go/vt/key"
"vitess.io/vitess/go/vt/logutil"
"vitess.io/vitess/go/vt/proto/query"
"vitess.io/vitess/go/vt/topo"
"vitess.io/vitess/go/vt/topo/topoproto"
"vitess.io/vitess/go/vt/vtgate/vindexes"
"vitess.io/vitess/go/vt/vttablet/queryservice"
"vitess.io/vitess/go/vt/vttablet/tabletconn"
querypb "vitess.io/vitess/go/vt/proto/query"
tabletmanagerdatapb "vitess.io/vitess/go/vt/proto/tabletmanagerdata"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
)
// QueryResultReader will stream rows towards the output channel.
// TODO(mberlin): Delete this in favor of RestartableResultReader once
// we are confident that the new SplitClone code produces the same diff results
// as the old diff code.
type QueryResultReader struct {
output sqltypes.ResultStream
fields []*querypb.Field
conn queryservice.QueryService
}
// NewQueryResultReaderForTablet creates a new QueryResultReader for
// the provided tablet / sql query
func NewQueryResultReaderForTablet(ctx context.Context, ts *topo.Server, tabletAlias *topodatapb.TabletAlias, sql string) (*QueryResultReader, error) {
shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
tablet, err := ts.GetTablet(shortCtx, tabletAlias)
cancel()
if err != nil {
return nil, err
}
conn, err := tabletconn.GetDialer()(tablet.Tablet, grpcclient.FailFast(false))
if err != nil {
return nil, err
}
stream := queryservice.ExecuteWithStreamer(ctx, conn, &querypb.Target{
Keyspace: tablet.Tablet.Keyspace,
Shard: tablet.Tablet.Shard,
TabletType: tablet.Tablet.Type,
}, sql, make(map[string]*querypb.BindVariable), nil)
// read the columns, or grab the error
cols, err := stream.Recv()
if err != nil {
return nil, vterrors.Wrapf(err, "Cannot read Fields for query '%v'", sql)
}
return &QueryResultReader{
output: stream,
fields: cols.Fields,
conn: conn,
}, nil
}
// NewTransactionalQueryResultReaderForTablet creates a new QueryResultReader for
// the provided tablet / sql query, and runs it in an existing transaction
func NewTransactionalQueryResultReaderForTablet(ctx context.Context, ts *topo.Server, tabletAlias *topodatapb.TabletAlias, sql string, txID int64) (*QueryResultReader, error) {
shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
tablet, err := ts.GetTablet(shortCtx, tabletAlias)
cancel()
if err != nil {
return nil, err
}
conn, err := tabletconn.GetDialer()(tablet.Tablet, grpcclient.FailFast(false))
if err != nil {
return nil, err
}
stream := queryservice.ExecuteWithTransactionalStreamer(ctx, conn, &querypb.Target{
Keyspace: tablet.Tablet.Keyspace,
Shard: tablet.Tablet.Shard,
TabletType: tablet.Tablet.Type,
}, sql, make(map[string]*querypb.BindVariable), txID, nil)
// read the columns, or grab the error
cols, err := stream.Recv()
if err != nil {
return nil, vterrors.Wrapf(err, "cannot read Fields for query '%v'", sql)
}
return &QueryResultReader{
output: stream,
fields: cols.Fields,
conn: conn,
}, nil
}
// Next returns the next result on the stream. It implements ResultReader.
func (qrr *QueryResultReader) Next() (*sqltypes.Result, error) {
return qrr.output.Recv()
}
// Fields returns the field data. It implements ResultReader.
func (qrr *QueryResultReader) Fields() []*querypb.Field {
return qrr.fields
}
// Close closes the connection to the tablet.
func (qrr *QueryResultReader) Close(ctx context.Context) {
qrr.conn.Close(ctx)
}
// v3KeyRangeFilter is a sqltypes.ResultStream implementation that filters
// the underlying results to match the keyrange using a v3 resolver.
type v3KeyRangeFilter struct {
input sqltypes.ResultStream
resolver *v3Resolver
keyRange *topodatapb.KeyRange
}
// Recv is part of sqltypes.ResultStream interface.
func (f *v3KeyRangeFilter) Recv() (*sqltypes.Result, error) {
r, err := f.input.Recv()
if err != nil {
return nil, err
}
rows := make([][]sqltypes.Value, 0, len(r.Rows))
for _, row := range r.Rows {
ksid, err := f.resolver.keyspaceID(row)
if err != nil {
return nil, err
}
if key.KeyRangeContains(f.keyRange, ksid) {
rows = append(rows, row)
}
}
r.Rows = rows
return r, nil
}
// reorderColumnsPrimaryKeyFirst returns a copy of "td" with the only difference
// that the Columns field is reordered such that the primary key columns come
// first. See orderedColumns() for details on the ordering.
func reorderColumnsPrimaryKeyFirst(td *tabletmanagerdatapb.TableDefinition) *tabletmanagerdatapb.TableDefinition {
reorderedTd := proto.Clone(td).(*tabletmanagerdatapb.TableDefinition)
reorderedTd.Columns = orderedColumns(td)
return reorderedTd
}
// orderedColumns returns the list of columns:
// - first the primary key columns in the right order
// - then the rest of the columns
// Within the partition of non primary key columns, the order is not changed
// in comparison to the original order of "td.Columns".
func orderedColumns(td *tabletmanagerdatapb.TableDefinition) []string {
return orderedColumnsHelper(td, true)
}
// orderedColumnsWithoutPrimaryKeyColumns is identical to orderedColumns but
// leaves the primary key columns out.
func orderedColumnsWithoutPrimaryKeyColumns(td *tabletmanagerdatapb.TableDefinition) []string {
return orderedColumnsHelper(td, false)
}
func orderedColumnsHelper(td *tabletmanagerdatapb.TableDefinition, includePrimaryKey bool) []string {
var result []string
if includePrimaryKey {
result = append(result, td.PrimaryKeyColumns...)
}
for _, column := range td.Columns {
found := false
for _, primaryKey := range td.PrimaryKeyColumns {
if primaryKey == column {
found = true
break
}
}
if !found {
result = append(result, column)
}
}
return result
}
// uint64FromKeyspaceID returns the 64 bit number representation
// of the keyspaceID.
func uint64FromKeyspaceID(keyspaceID []byte) uint64 {
// Copy into 8 bytes because keyspaceID could be shorter.
bits := make([]byte, 8)
copy(bits, keyspaceID)
return binary.BigEndian.Uint64(bits)
}
// TableScan returns a QueryResultReader that gets all the rows from a
// table, ordered by Primary Key. The returned columns are ordered
// with the Primary Key columns in front.
func TableScan(ctx context.Context, log logutil.Logger, ts *topo.Server, tabletAlias *topodatapb.TabletAlias, td *tabletmanagerdatapb.TableDefinition) (*QueryResultReader, error) {
sql := fmt.Sprintf("SELECT %v FROM %v", strings.Join(escapeAll(orderedColumns(td)), ", "), sqlescape.EscapeID(td.Name))
if len(td.PrimaryKeyColumns) > 0 {
sql += fmt.Sprintf(" ORDER BY %v", strings.Join(escapeAll(td.PrimaryKeyColumns), ", "))
}
log.Infof("SQL query for %v/%v: %v", topoproto.TabletAliasString(tabletAlias), td.Name, sql)
return NewQueryResultReaderForTablet(ctx, ts, tabletAlias, sql)
}
// TransactionalTableScan does the same thing as TableScan, but runs inside a transaction
func TransactionalTableScan(ctx context.Context, log logutil.Logger, ts *topo.Server, tabletAlias *topodatapb.TabletAlias, txID int64, td *tabletmanagerdatapb.TableDefinition) (*QueryResultReader, error) {
sql := fmt.Sprintf("SELECT %v FROM %v", strings.Join(escapeAll(orderedColumns(td)), ", "), sqlescape.EscapeID(td.Name))
if len(td.PrimaryKeyColumns) > 0 {
sql += fmt.Sprintf(" ORDER BY %v", strings.Join(escapeAll(td.PrimaryKeyColumns), ", "))
}
log.Infof("SQL query for %v/%v: %v", topoproto.TabletAliasString(tabletAlias), td.Name, sql)
return NewTransactionalQueryResultReaderForTablet(ctx, ts, tabletAlias, sql, txID)
}
// CreateTargetFrom is a helper function
func CreateTargetFrom(tablet *topodatapb.Tablet) *query.Target {
return &query.Target{
Cell: tablet.Alias.Cell,
Keyspace: tablet.Keyspace,
Shard: tablet.Shard,
TabletType: tablet.Type,
}
}
// TableScanByKeyRange returns a QueryResultReader that gets all the
// rows from a table that match the supplied KeyRange, ordered by
// Primary Key. The returned columns are ordered with the Primary Key
// columns in front.
// If keyspaceSchema is passed in, we go into v3 mode, and we ask for all
// source data, and filter here. Otherwise we stick with v2 mode, where we can
// ask the source tablet to do the filtering.
func TableScanByKeyRange(ctx context.Context, log logutil.Logger, ts *topo.Server, tabletAlias *topodatapb.TabletAlias, td *tabletmanagerdatapb.TableDefinition, keyRange *topodatapb.KeyRange, keyspaceSchema *vindexes.KeyspaceSchema, shardingColumnName string, shardingColumnType topodatapb.KeyspaceIdType) (*QueryResultReader, error) {
if keyspaceSchema != nil {
// switch to v3 mode.
keyResolver, err := newV3ResolverFromColumnList(keyspaceSchema, td.Name, orderedColumns(td))
if err != nil {
return nil, vterrors.Wrapf(err, "cannot resolve v3 sharding keys for table %v", td.Name)
}
// full table scan
scan, err := TableScan(ctx, log, ts, tabletAlias, td)
if err != nil {
return nil, err
}
// with extra filter
scan.output = &v3KeyRangeFilter{
input: scan.output, | }
// in v2 mode, we can do the filtering at the source
where := ""
switch shardingColumnType {
case topodatapb.KeyspaceIdType_UINT64:
if len(keyRange.Start) > 0 {
if len(keyRange.End) > 0 {
// have start & end
where = fmt.Sprintf("WHERE %v >= %v AND %v < %v", sqlescape.EscapeID(shardingColumnName), uint64FromKeyspaceID(keyRange.Start), sqlescape.EscapeID(shardingColumnName), uint64FromKeyspaceID(keyRange.End))
} else {
// have start only
where = fmt.Sprintf("WHERE %v >= %v", sqlescape.EscapeID(shardingColumnName), uint64FromKeyspaceID(keyRange.Start))
}
} else {
if len(keyRange.End) > 0 {
// have end only
where = fmt.Sprintf("WHERE %v < %v", sqlescape.EscapeID(shardingColumnName), uint64FromKeyspaceID(keyRange.End))
}
}
case topodatapb.KeyspaceIdType_BYTES:
if len(keyRange.Start) > 0 {
if len(keyRange.End) > 0 {
// have start & end
where = fmt.Sprintf("WHERE HEX(%v) >= '%v' AND HEX(%v) < '%v'", sqlescape.EscapeID(shardingColumnName), hex.EncodeToString(keyRange.Start), sqlescape.EscapeID(shardingColumnName), hex.EncodeToString(keyRange.End))
} else {
// have start only
where = fmt.Sprintf("WHERE HEX(%v) >= '%v'", sqlescape.EscapeID(shardingColumnName), hex.EncodeToString(keyRange.Start))
}
} else {
if len(keyRange.End) > 0 {
// have end only
where = fmt.Sprintf("WHERE HEX(%v) < '%v'", sqlescape.EscapeID(shardingColumnName), hex.EncodeToString(keyRange.End))
}
}
default:
return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "unsupported ShardingColumnType: %v", shardingColumnType)
}
sql := fmt.Sprintf("SELECT %v FROM %v %v", strings.Join(escapeAll(orderedColumns(td)), ", "), sqlescape.EscapeID(td.Name), where)
if len(td.PrimaryKeyColumns) > 0 {
sql += fmt.Sprintf(" ORDER BY %v", strings.Join(escapeAll(td.PrimaryKeyColumns), ", "))
}
log.Infof("SQL query for %v/%v: %v", topoproto.TabletAliasString(tabletAlias), td.Name, sql)
return NewQueryResultReaderForTablet(ctx, ts, tabletAlias, sql)
}
// ErrStoppedRowReader is returned by RowReader.Next() when
// StopAfterCurrentResult() and it finished the current result.
var ErrStoppedRowReader = vterrors.New(vtrpc.Code_ABORTED, "RowReader won't advance to the next Result because StopAfterCurrentResult() was called")
// RowReader returns individual rows from a ResultReader.
type RowReader struct {
resultReader ResultReader
currentResult *sqltypes.Result
currentIndex int
stopAfterCurrentResult bool
}
// NewRowReader returns a RowReader based on the QueryResultReader
func NewRowReader(resultReader ResultReader) *RowReader {
return &RowReader{
resultReader: resultReader,
}
}
// Next will return:
// (row, nil) for the next row
// (nil, nil) for EOF
// (nil, error) if an error occurred
func (rr *RowReader) Next() ([]sqltypes.Value, error) {
for rr.currentResult == nil || rr.currentIndex == len(rr.currentResult.Rows) {
if rr.stopAfterCurrentResult {
return nil, ErrStoppedRowReader
}
var err error
rr.currentResult, err = rr.resultReader.Next()
if err != nil {
if err != io.EOF {
return nil, err
}
return nil, nil
}
rr.currentIndex = 0
}
row := rr.currentResult.Rows[rr.currentIndex]
rr.currentIndex++
return row, nil
}
// Fields returns the types for the rows
func (rr *RowReader) Fields() []*querypb.Field {
return rr.resultReader.Fields()
}
// Drain will empty the RowReader and return how many rows we got
func (rr *RowReader) Drain() (int, error) {
count := 0
for {
row, err := rr.Next()
if err != nil {
return 0, err
}
if row == nil {
return count, nil
}
count++
}
}
// StopAfterCurrentResult tells RowReader to keep returning rows in Next()
// until it has finished the current Result. Once there, Next() will always
// return the "StoppedRowReader" error.
// This is feature is necessary for an optimization where the underlying
// ResultReader is the last input in a merge and we want to switch from reading
// rows to reading Results.
func (rr *RowReader) StopAfterCurrentResult() {
rr.stopAfterCurrentResult = true
}
// DiffReport has the stats for a diff job
type DiffReport struct {
// general stats
processedRows int
// stats about the diff
matchingRows int
mismatchedRows int
extraRowsLeft int
extraRowsRight int
// QPS variables and stats
startingTime time.Time
processingQPS int
}
// HasDifferences returns true if the diff job recorded any difference
func (dr *DiffReport) HasDifferences() bool {
return dr.mismatchedRows > 0 || dr.extraRowsLeft > 0 || dr.extraRowsRight > 0
}
// ComputeQPS fills in processingQPS
func (dr *DiffReport) ComputeQPS() {
if dr.processedRows > 0 {
dr.processingQPS = int(time.Duration(dr.processedRows) * time.Second / time.Since(dr.startingTime))
}
}
func (dr *DiffReport) String() string {
return fmt.Sprintf("DiffReport{%v processed, %v matching, %v mismatched, %v extra left, %v extra right, %v q/s}", dr.processedRows, dr.matchingRows, dr.mismatchedRows, dr.extraRowsLeft, dr.extraRowsRight, dr.processingQPS)
}
// RowsEqual returns the index of the first different column, or -1 if
// both rows are the same.
func RowsEqual(left, right []sqltypes.Value) int {
for i, l := range left {
if !bytes.Equal(l.Raw(), right[i].Raw()) {
return i
}
}
return -1
}
// CompareRows returns:
// -1 if left is smaller than right
// 0 if left and right are equal
// +1 if left is bigger than right
// It compares only up to and including the first "compareCount" columns of each
// row.
// TODO: This can panic if types for left and right don't match.
func CompareRows(fields []*querypb.Field, compareCount int, left, right []sqltypes.Value) (int, error) {
for i := 0; i < compareCount; i++ {
lv, _ := evalengine.ToNative(left[i])
rv, _ := evalengine.ToNative(right[i])
switch l := lv.(type) {
case int64:
r := rv.(int64)
if l < r {
return -1, nil
} else if l > r {
return 1, nil
}
case uint64:
r := rv.(uint64)
if l < r {
return -1, nil
} else if l > r {
return 1, nil
}
case float64:
r := rv.(float64)
if l < r {
return -1, nil
} else if l > r {
return 1, nil
}
case []byte:
r := rv.([]byte)
return bytes.Compare(l, r), nil
default:
return 0, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "unsupported type %T returned by mysql.proto.Convert", l)
}
}
return 0, nil
}
// RowDiffer will consume rows on both sides, and compare them.
// It assumes left and right are sorted by ascending primary key.
// it will record errors if extra rows exist on either side.
type RowDiffer struct {
left *RowReader
right *RowReader
tableDefinition *tabletmanagerdatapb.TableDefinition
}
// NewRowDiffer returns a new RowDiffer
func NewRowDiffer(left, right ResultReader, tableDefinition *tabletmanagerdatapb.TableDefinition) (*RowDiffer, error) {
leftFields := left.Fields()
rightFields := right.Fields()
if len(leftFields) != len(rightFields) {
return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "[table=%v] Cannot diff inputs with different types", tableDefinition.Name)
}
for i, field := range leftFields {
if field.Type != rightFields[i].Type {
return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "[table=%v] Cannot diff inputs with different types: field %v types are %v and %v", tableDefinition.Name, i, field.Type, rightFields[i].Type)
}
}
return &RowDiffer{
left: NewRowReader(left),
right: NewRowReader(right),
tableDefinition: tableDefinition,
}, nil
}
// Go runs the diff. If there is no error, it will drain both sides.
// If an error occurs, it will just return it and stop.
func (rd *RowDiffer) Go(log logutil.Logger) (dr DiffReport, err error) {
dr.startingTime = time.Now()
defer dr.ComputeQPS()
var left []sqltypes.Value
var right []sqltypes.Value
advanceLeft := true
advanceRight := true
for {
if advanceLeft {
left, err = rd.left.Next()
if err != nil {
return
}
advanceLeft = false
}
if advanceRight {
right, err = rd.right.Next()
if err != nil {
return
}
advanceRight = false
}
dr.processedRows++
if left == nil {
// no more rows from the left
if right == nil {
// no more rows from right either, we're done
return
}
// drain right, update count
log.Errorf("Draining extra row(s) found on the right starting with: %v", right)
var count int
if count, err = rd.right.Drain(); err != nil {
return dr, err
}
dr.extraRowsRight += 1 + count
return
}
if right == nil {
// no more rows from the right
// we know we have rows from left, drain, update count
log.Errorf("Draining extra row(s) found on the left starting with: %v", left)
var count int
if count, err = rd.left.Drain(); err != nil {
return dr, err
}
dr.extraRowsLeft += 1 + count
return
}
// we have both left and right, compare
f := RowsEqual(left, right)
if f == -1 {
// rows are the same, next
dr.matchingRows++
advanceLeft = true
advanceRight = true
continue
}
if f >= len(rd.tableDefinition.PrimaryKeyColumns) {
// rows have the same primary key, only content is different
if dr.mismatchedRows < 10 {
log.Errorf("[table=%v] Different content %v in same PK: %v != %v", rd.tableDefinition.Name, dr.mismatchedRows, left, right)
}
dr.mismatchedRows++
advanceLeft = true
advanceRight = true
continue
}
// have to find the 'smallest' row and advance it
c, err := CompareRows(rd.left.Fields(), len(rd.tableDefinition.PrimaryKeyColumns), left, right)
if err != nil {
return dr, err
}
if c < 0 {
if dr.extraRowsLeft < 10 {
log.Errorf("[table=%v] Extra row %v on left: %v", rd.tableDefinition.Name, dr.extraRowsLeft, left)
}
dr.extraRowsLeft++
advanceLeft = true
continue
} else if c > 0 {
if dr.extraRowsRight < 10 {
log.Errorf("[table=%v] Extra row %v on right: %v", rd.tableDefinition.Name, dr.extraRowsRight, right)
}
dr.extraRowsRight++
advanceRight = true
continue
}
// After looking at primary keys more carefully,
// they're the same. Logging a regular difference
// then, and advancing both.
if dr.mismatchedRows < 10 {
log.Errorf("[table=%v] Different content %v in same PK: %v != %v", rd.tableDefinition.Name, dr.mismatchedRows, left, right)
}
dr.mismatchedRows++
advanceLeft = true
advanceRight = true
}
}
// createTransactions returns an array of transactions that all share the same view of the data.
// It will check that no new transactions have been seen between the creation of the underlying transactions,
// to guarantee that all TransactionalTableScanner are pointing to the same point
func createTransactions(ctx context.Context, numberOfScanners int, wr *wrangler.Wrangler, cleaner *wrangler.Cleaner, queryService queryservice.QueryService, target *query.Target, tabletInfo *topodatapb.Tablet) ([]int64, error) {
scanners := make([]int64, numberOfScanners)
for i := 0; i < numberOfScanners; i++ {
tx, _, err := queryService.Begin(ctx, target, &query.ExecuteOptions{
// Make sure our tx is not killed by tx sniper
Workload: query.ExecuteOptions_DBA,
TransactionIsolation: query.ExecuteOptions_CONSISTENT_SNAPSHOT_READ_ONLY,
})
if err != nil {
return nil, vterrors.Wrapf(err, "could not open transaction on %v", topoproto.TabletAliasString(tabletInfo.Alias))
}
// Remember to rollback the transactions
cleaner.Record("CloseTransaction", topoproto.TabletAliasString(tabletInfo.Alias), func(ctx context.Context, wr *wrangler.Wrangler) error {
queryService, err := tabletconn.GetDialer()(tabletInfo, true)
if err != nil {
return err
}
_, err = queryService.Rollback(ctx, target, tx)
return err
})
scanners[i] = tx
}
return scanners, nil
}
// TableScanner is a simple abstraction that allows a TableScanner user to remain impervious
// by the transactionality of the connection
type TableScanner interface {
ScanTable(ctx context.Context, td *tabletmanagerdatapb.TableDefinition) (*QueryResultReader, error)
}
// TransactionalTableScanner works inside of a transaction set up with CONSISTENT SNAPSHOT
type TransactionalTableScanner struct {
wr *wrangler.Wrangler
cleaner *wrangler.Cleaner
tabletAlias *topodatapb.TabletAlias
queryService queryservice.QueryService
tx int64
}
// ScanTable performs a full table scan, ordered by the primary keys, if any
func (tt TransactionalTableScanner) ScanTable(ctx context.Context, td *tabletmanagerdatapb.TableDefinition) (*QueryResultReader, error) {
return TransactionalTableScan(ctx, tt.wr.Logger(), tt.wr.TopoServer(), tt.tabletAlias, tt.tx, td)
}
// NonTransactionalTableScanner just passes through the queries, and relies on paused replication traffic taking care of the consistent snapshot part
type NonTransactionalTableScanner struct {
wr *wrangler.Wrangler
cleaner *wrangler.Cleaner
tabletAlias *topodatapb.TabletAlias
queryService queryservice.QueryService
}
// ScanTable performs a full table scan, ordered by the primary keys, if any
func (ntts NonTransactionalTableScanner) ScanTable(ctx context.Context, td *tabletmanagerdatapb.TableDefinition) (*QueryResultReader, error) {
return TableScan(ctx, ntts.wr.Logger(), ntts.wr.TopoServer(), ntts.tabletAlias, td)
}
// CreateConsistentTableScanners will momentarily stop updates on the tablet, and then create connections that are all
// consistent snapshots of the same point in the transaction history
func CreateConsistentTableScanners(ctx context.Context, tablet *topo.TabletInfo, wr *wrangler.Wrangler, cleaner *wrangler.Cleaner, numberOfScanners int) ([]TableScanner, string, error) {
txs, gtid, err := CreateConsistentTransactions(ctx, tablet, wr, cleaner, numberOfScanners)
if err != nil {
return nil, "", err
}
queryService, _ := tabletconn.GetDialer()(tablet.Tablet, true)
defer queryService.Close(ctx)
scanners := make([]TableScanner, numberOfScanners)
for i, tx := range txs {
scanners[i] = TransactionalTableScanner{
wr: wr,
cleaner: cleaner,
tabletAlias: tablet.Alias,
queryService: queryService,
tx: tx,
}
}
return scanners, gtid, nil
}
// CreateConsistentTransactions creates a number of consistent snapshot transactions,
// all starting from the same spot in the tx log
func CreateConsistentTransactions(ctx context.Context, tablet *topo.TabletInfo, wr *wrangler.Wrangler, cleaner *wrangler.Cleaner, numberOfScanners int) ([]int64, string, error) {
if numberOfScanners < 1 {
return nil, "", vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "need more than zero scanners: %d", numberOfScanners)
}
tm := tmclient.NewTabletManagerClient()
defer tm.Close()
// Lock all tables with a read lock to pause replication
err := tm.LockTables(ctx, tablet.Tablet)
if err != nil {
return nil, "", vterrors.Wrapf(err, "could not lock tables on %v", topoproto.TabletAliasString(tablet.Tablet.Alias))
}
defer func() {
tm := tmclient.NewTabletManagerClient()
defer tm.Close()
tm.UnlockTables(ctx, tablet.Tablet)
wr.Logger().Infof("tables unlocked on %v", topoproto.TabletAliasString(tablet.Tablet.Alias))
}()
wr.Logger().Infof("tables locked on %v", topoproto.TabletAliasString(tablet.Tablet.Alias))
target := CreateTargetFrom(tablet.Tablet)
// Create transactions
queryService, _ := tabletconn.GetDialer()(tablet.Tablet, true)
defer queryService.Close(ctx)
connections, err := createTransactions(ctx, numberOfScanners, wr, cleaner, queryService, target, tablet.Tablet)
if err != nil {
return nil, "", vterrors.Wrapf(err, "failed to create transactions on %v", topoproto.TabletAliasString(tablet.Tablet.Alias))
}
wr.Logger().Infof("transactions created on %v", topoproto.TabletAliasString(tablet.Tablet.Alias))
executedGtid, err := tm.PrimaryPosition(ctx, tablet.Tablet)
if err != nil {
return nil, "", vterrors.Wrapf(err, "could not read executed GTID set on %v", topoproto.TabletAliasString(tablet.Tablet.Alias))
}
return connections, executedGtid, nil
} | resolver: keyResolver.(*v3Resolver),
keyRange: keyRange,
}
return scan, nil |
websocket.py | """A module for the websockets-based Client for Jina."""
from typing import Callable, Optional
from contextlib import nullcontext, AsyncExitStack
from ..helper import callback_exec
from .helper import WebsocketClientlet
from ...importer import ImportExtensions
from ..base import BaseClient, InputType
from ...logging.profile import ProgressBar
from ...peapods.stream.client import WebsocketClientStreamer
class WebSocketBaseClient(BaseClient):
| """A Websocket Client."""
async def _get_results(
self,
inputs: InputType,
on_done: Callable,
on_error: Optional[Callable] = None,
on_always: Optional[Callable] = None,
**kwargs,
):
"""
:param inputs: the callable
:param on_done: the callback for on_done
:param on_error: the callback for on_error
:param on_always: the callback for on_always
:param kwargs: kwargs for _get_task_name and _get_requests
:yields: generator over results
"""
with ImportExtensions(required=True):
import aiohttp
self.inputs = inputs
request_iterator = self._get_requests(**kwargs)
async with AsyncExitStack() as stack:
try:
cm1 = (
ProgressBar(total_length=self._inputs_length)
if self.show_progress
else nullcontext()
)
p_bar = stack.enter_context(cm1)
proto = 'wss' if self.args.https else 'ws'
url = f'{proto}://{self.args.host}:{self.args.port}/'
iolet = await stack.enter_async_context(
WebsocketClientlet(url=url, logger=self.logger)
)
streamer = WebsocketClientStreamer(self.args, iolet=iolet)
async for response in streamer.stream(request_iterator):
callback_exec(
response=response,
on_error=on_error,
on_done=on_done,
on_always=on_always,
continue_on_error=self.continue_on_error,
logger=self.logger,
)
if self.show_progress:
p_bar.update()
yield response
except aiohttp.ClientError as e:
self.logger.error(
f'Error while streaming response from websocket server {e!r}'
) |
|
settings_store.py | import os
from PyQt4 import QtCore, QtGui
from epubcreator.epubbase.ebook import Ebook
from epubcreator.converters.converter_factory import ConverterFactory
class | (QtCore.QSettings):
"""
Permite guardar y recuperar las diversas opciones de configuración. Expone además
todos los atributos relacionados con las preferencias generales del usuario, que pueden
ser leídos desde cualquier parte de la aplicación. Los atributos de la clase son:
-- Un atributo por cada opción de cada converter. El nombre del atributo resulta
de concatenar el tipo de archivo sobre el que opera el converter, más el nombre
de la opción capitalizando la primer letra. Ejemplo: la opción "ignoreEmptyParagraphs"
del docx converter, se traduce en: "docxIgnoreEmptyParagraphs". Con ese nombre es como
la opción se guarda en disco, y como el consumer debe leer el atributo de la clase.
-- Un atributo por cada opción de la clase Ebook. La diferencia en el nombre del atributo
con el procedimiento descrito arriba radica en que el prefijo de cada atributo
es: "epubOutput".
-- Todas las keys del diccionario _SETTINGS.
"""
_SETTINGS_GROUP = "userPreferences"
# Lista de atributos que SettingsStore expone.
# Key = nombre de atributo.
# Value = valor por defecto.
_SETTINGS = dict(editor="",
sigilPath="",
allowImageProcessing=True)
# Agrego todas las opciones posibles de todos los converters.
_SETTINGS.update({c.FILE_TYPE + o.name[0].upper() + o.name[1:]: o.value for c in ConverterFactory.getAllConverters() for o in c.OPTIONS})
# Agrego todas las opciones posibles de la clase Ebook.
_SETTINGS.update({"epubOutput" + o.name[0].upper() + o.name[1:]: o.value for o in Ebook.OPTIONS})
def getAllSettingsForConverter(self, fileType):
"""
Retorna todas las opciones de un converter dado. Es más que nada un
método que facilita el poder pasarle a un converter todas las opciones guardadas, sin
necesidad de que el consumer tenga que realizar esto:
op1 = settings.op1
op2 = settings.op2
...
@param fileType: un string, que indica de qué converter retornar las opciones.
Ejemplo: "docx", "fb2".
@return: un diccionario.
Key: el nombre la opción.
Value: el valor almacenado de la opción.
"""
return self._getAllSettingsByPrefix(fileType)
def getAllSettingsForEbook(self):
"""
Similar al método getAllSettingsForConverter, pero para las opciones de
la clase Ebook.
"""
return self._getAllSettingsByPrefix("epubOutput")
def __getattr__(self, item):
if item not in SettingsStore._SETTINGS:
raise AttributeError("'{0}' object has no attribute '{1}'".format(self.__class__.__name__, item))
defaultValue = SettingsStore._SETTINGS[item]
return self.value("{0}/{1}".format(SettingsStore._SETTINGS_GROUP, item), defaultValue, type(defaultValue))
def __setattr__(self, key, value):
if key in SettingsStore._SETTINGS:
self.setValue("{0}/{1}".format(SettingsStore._SETTINGS_GROUP, key), value)
else:
object.__setattr__(self, key, value)
def _getAllSettingsByPrefix(self, prefix):
i = len(prefix)
return {s[i].lower() + s[i + 1:]: getattr(self, s) for s in SettingsStore._SETTINGS if s.startswith(prefix)}
def __init__(self):
iniPath = os.path.join(QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.DataLocation), "epubcreator.ini")
super().__init__(iniPath, QtCore.QSettings.IniFormat) | SettingsStore |
errors.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use failure::Fail;
use solana_libra_types::vm_error::VMStatus;
#[derive(Clone, Debug, Eq, Fail, Ord, PartialEq, PartialOrd)]
pub enum | {
#[fail(display = "Post-compile bounds check errors: {:?}", _0)]
BoundsCheckErrors(Vec<VMStatus>),
}
| InternalCompilerError |
vocab_utils.py | # -*- coding: utf-8 -*-
from __future__ import print_function
import os
import re
import pickle
import numpy as np
from collections import Counter
from functools import lru_cache
from . import constants
from .data_utils import tokenize
word_detector = re.compile('\w')
class VocabModel(object):
def __init__(self, data_set, config):
print('Building vocabs...')
(allWords, allEdgeTypes) = collect_vocabs(data_set)
print('Number of words: {}'.format(len(allWords)))
print('Number of edge types: {}'.format(len(allEdgeTypes)))
self.word_vocab = Vocab()
self.word_vocab.build_vocab(allWords, vocab_size=config['top_word_vocab'], min_freq=config['min_word_freq'])
if config.get('pretrained_word_embed_file', None):
self.word_vocab.load_embeddings(config['pretrained_word_embed_file'])
print('Using pretrained word embeddings')
else:
self.word_vocab.randomize_embeddings(config['word_embed_dim'])
print('Using randomized word embeddings')
print('word_vocab: {}'.format(self.word_vocab.embeddings.shape))
self.edge_vocab = Vocab()
self.edge_vocab.build_vocab(allEdgeTypes)
print('edge_vocab: {}'.format((self.edge_vocab.get_vocab_size())))
@classmethod
def build(cls, saved_vocab_file=None, data_set=None, config=None):
"""
Loads a Vocabulary from disk.
Args:
saved_vocab_file (str): path to the saved vocab file
data_set:
config:
Returns:
Vocabulary: loaded Vocabulary
"""
if os.path.exists(saved_vocab_file):
print('Loading pre-built vocab model stored in {}'.format(saved_vocab_file))
vocab_model = pickle.load(open(saved_vocab_file, 'rb'))
else:
vocab_model = VocabModel(data_set, config)
print('Saving vocab model to {}'.format(saved_vocab_file))
pickle.dump(vocab_model, open(saved_vocab_file, 'wb'))
return vocab_model
class Vocab(object):
def __init__(self):
self.PAD = 0
self.SOS = 1
self.EOS = 2
self.UNK = 3
self.pad_token = constants._PAD_TOKEN
self.sos_token = constants._SOS_TOKEN
self.eos_token = constants._EOS_TOKEN
self.unk_token = constants._UNK_TOKEN
self.reserved = [self.pad_token, self.sos_token, self.eos_token, self.unk_token]
self.index2word = self.reserved[:]
self.word2index = dict(zip(self.reserved, range(len(self.reserved))))
self.word2count = Counter()
self.embeddings = None
def build_vocab(self, vocab_counter, vocab_size=None, min_freq=1):
self.word2count = vocab_counter
self._add_words(vocab_counter.keys())
self._trim(vocab_size=vocab_size, min_freq=min_freq)
def _add_words(self, words):
for word in words:
if word not in self.word2index:
self.word2index[word] = len(self.index2word)
self.index2word.append(word)
assert len(self.word2index) == len(self.index2word)
def _trim(self, vocab_size: int=None, min_freq: int=1):
if min_freq <= 1 and (vocab_size is None or vocab_size >= len(self.word2index)):
return
ordered_words = sorted(((c, w) for (w, c) in self.word2count.items()), reverse=True)
if vocab_size:
ordered_words = ordered_words[:vocab_size]
self.index2word = self.reserved[:]
self.word2index = dict(zip(self.reserved, range(len(self.reserved))))
self.word2count = Counter()
for count, word in ordered_words:
if count < min_freq: break
if word not in self.word2index:
self.word2index[word] = len(self.index2word) | def load_embeddings(self, file_path, scale=0.08, dtype=np.float32):
hit_words = set()
vocab_size = len(self)
with open(file_path, 'rb') as f:
for line in f:
line = line.split()
word = line[0].decode('utf-8')
idx = self.word2index.get(word.lower(), None)
if idx is None or idx in hit_words:
continue
vec = np.array(line[1:], dtype=dtype)
if self.embeddings is None:
n_dims = len(vec)
self.embeddings = np.array(np.random.uniform(low=-scale, high=scale, size=(vocab_size, n_dims)), dtype=dtype)
self.embeddings[self.PAD] = np.zeros(n_dims)
self.embeddings[idx] = vec
hit_words.add(idx)
print('Pretrained word embeddings hit ratio: {}'.format(len(hit_words) / len(self.index2word)))
def randomize_embeddings(self, n_dims, scale=0.08):
vocab_size = self.get_vocab_size()
shape = (vocab_size, n_dims)
self.embeddings = np.array(np.random.uniform(low=-scale, high=scale, size=shape), dtype=np.float32)
self.embeddings[self.PAD] = np.zeros(n_dims)
def __getitem__(self, item):
if type(item) is int:
return self.index2word[item]
return self.word2index.get(item, self.UNK)
def __len__(self):
return len(self.index2word)
@lru_cache(maxsize=None)
def is_word(self, token_id: int) -> bool:
"""Return whether the token at `token_id` is a word; False for punctuations."""
if token_id < 4: return False
if token_id >= len(self): return True # OOV is assumed to be words
token_str = self.index2word[token_id]
if not word_detector.search(token_str) or token_str == '<P>':
return False
return True
def get_vocab_size(self):
return len(self.index2word)
def getIndex(self, word):
return self.word2index.get(word, self.UNK)
def getWord(self, idx):
return self.index2word[idx] if idx < len(self.index2word) else self.unk_token
def to_word_sequence(self, seq):
sentence = []
for idx in seq:
word = self.getWord(idx)
sentence.append(word)
return sentence
def to_index_sequence(self, sentence):
sentence = sentence.strip()
seq = []
for word in tokenize(sentence):
idx = self.getIndex(word)
seq.append(idx)
return seq
def to_index_sequence_for_list(self, words):
seq = []
for word in words:
idx = self.getIndex(word)
seq.append(idx)
return seq
def collect_vocabs(all_instances):
all_words = Counter()
all_edge_types = Counter()
for (sent1, sent2) in all_instances:
# for each in sent1.words:
# all_words.update(each)
for each in sent1.graph['g_features']:
all_words.update(each)
all_words.update(sent2.words)
# for node, value in sent1.graph['g_adj'].items():
# all_edge_types.update([each['edge'] for each in value])
return all_words, all_edge_types | self.word2count[word] = count
self.index2word.append(word)
assert len(self.word2index) == len(self.index2word)
|
__init__.py | import unittest
class CacheTestMixin:
Cache = None
def test_defaults(self):
cache = self.Cache(maxsize=1)
self.assertEqual(0, len(cache))
self.assertEqual(1, cache.maxsize)
self.assertEqual(0, cache.currsize)
self.assertEqual(1, cache.getsizeof(None))
self.assertEqual(1, cache.getsizeof(""))
self.assertEqual(1, cache.getsizeof(0))
self.assertTrue(repr(cache).startswith(cache.__class__.__name__))
def test_insert(self):
|
def test_update(self):
cache = self.Cache(maxsize=2)
cache.update({1: 1, 2: 2})
self.assertEqual(2, len(cache))
self.assertEqual(1, cache[1])
self.assertEqual(2, cache[2])
cache.update({1: 1, 2: 2})
self.assertEqual(2, len(cache))
self.assertEqual(1, cache[1])
self.assertEqual(2, cache[2])
cache.update({1: "a", 2: "b"})
self.assertEqual(2, len(cache))
self.assertEqual("a", cache[1])
self.assertEqual("b", cache[2])
def test_delete(self):
cache = self.Cache(maxsize=2)
cache.update({1: 1, 2: 2})
self.assertEqual(2, len(cache))
self.assertEqual(1, cache[1])
self.assertEqual(2, cache[2])
del cache[2]
self.assertEqual(1, len(cache))
self.assertEqual(1, cache[1])
self.assertNotIn(2, cache)
del cache[1]
self.assertEqual(0, len(cache))
self.assertNotIn(1, cache)
self.assertNotIn(2, cache)
with self.assertRaises(KeyError):
del cache[1]
self.assertEqual(0, len(cache))
self.assertNotIn(1, cache)
self.assertNotIn(2, cache)
def test_pop(self):
cache = self.Cache(maxsize=2)
cache.update({1: 1, 2: 2})
self.assertEqual(2, cache.pop(2))
self.assertEqual(1, len(cache))
self.assertEqual(1, cache.pop(1))
self.assertEqual(0, len(cache))
with self.assertRaises(KeyError):
cache.pop(2)
with self.assertRaises(KeyError):
cache.pop(1)
with self.assertRaises(KeyError):
cache.pop(0)
self.assertEqual(None, cache.pop(2, None))
self.assertEqual(None, cache.pop(1, None))
self.assertEqual(None, cache.pop(0, None))
def test_popitem(self):
cache = self.Cache(maxsize=2)
cache.update({1: 1, 2: 2})
self.assertIn(cache.pop(1), {1: 1, 2: 2})
self.assertEqual(1, len(cache))
self.assertIn(cache.pop(2), {1: 1, 2: 2})
self.assertEqual(0, len(cache))
with self.assertRaises(KeyError):
cache.popitem()
def test_popitem_exception_context(self):
# since Python 3.7, MutableMapping.popitem() suppresses
# exception context as implementation detail
exception = None
try:
self.Cache(maxsize=2).popitem()
except Exception as e:
exception = e
self.assertIsNone(exception.__cause__)
self.assertTrue(exception.__suppress_context__)
def test_missing(self):
class DefaultCache(self.Cache):
def __missing__(self, key):
self[key] = key
return key
cache = DefaultCache(maxsize=2)
self.assertEqual(0, cache.currsize)
self.assertEqual(2, cache.maxsize)
self.assertEqual(0, len(cache))
self.assertEqual(1, cache[1])
self.assertEqual(2, cache[2])
self.assertEqual(2, len(cache))
self.assertTrue(1 in cache and 2 in cache)
self.assertEqual(3, cache[3])
self.assertEqual(2, len(cache))
self.assertTrue(3 in cache)
self.assertTrue(1 in cache or 2 in cache)
self.assertTrue(1 not in cache or 2 not in cache)
self.assertEqual(4, cache[4])
self.assertEqual(2, len(cache))
self.assertTrue(4 in cache)
self.assertTrue(1 in cache or 2 in cache or 3 in cache)
# verify __missing__() is *not* called for any operations
# besides __getitem__()
self.assertEqual(4, cache.get(4))
self.assertEqual(None, cache.get(5))
self.assertEqual(5 * 5, cache.get(5, 5 * 5))
self.assertEqual(2, len(cache))
self.assertEqual(4, cache.pop(4))
with self.assertRaises(KeyError):
cache.pop(5)
self.assertEqual(None, cache.pop(5, None))
self.assertEqual(5 * 5, cache.pop(5, 5 * 5))
self.assertEqual(1, len(cache))
cache.clear()
cache[1] = 1 + 1
self.assertEqual(1 + 1, cache.setdefault(1))
self.assertEqual(1 + 1, cache.setdefault(1, 1))
self.assertEqual(1 + 1, cache[1])
self.assertEqual(2 + 2, cache.setdefault(2, 2 + 2))
self.assertEqual(2 + 2, cache.setdefault(2, None))
self.assertEqual(2 + 2, cache.setdefault(2))
self.assertEqual(2 + 2, cache[2])
self.assertEqual(2, len(cache))
self.assertTrue(1 in cache and 2 in cache)
self.assertEqual(None, cache.setdefault(3))
self.assertEqual(2, len(cache))
self.assertTrue(3 in cache)
self.assertTrue(1 in cache or 2 in cache)
self.assertTrue(1 not in cache or 2 not in cache)
def test_missing_getsizeof(self):
class DefaultCache(self.Cache):
def __missing__(self, key):
try:
self[key] = key
except ValueError:
pass # not stored
return key
cache = DefaultCache(maxsize=2, getsizeof=lambda x: x)
self.assertEqual(0, cache.currsize)
self.assertEqual(2, cache.maxsize)
self.assertEqual(1, cache[1])
self.assertEqual(1, len(cache))
self.assertEqual(1, cache.currsize)
self.assertIn(1, cache)
self.assertEqual(2, cache[2])
self.assertEqual(1, len(cache))
self.assertEqual(2, cache.currsize)
self.assertNotIn(1, cache)
self.assertIn(2, cache)
self.assertEqual(3, cache[3]) # not stored
self.assertEqual(1, len(cache))
self.assertEqual(2, cache.currsize)
self.assertEqual(1, cache[1])
self.assertEqual(1, len(cache))
self.assertEqual(1, cache.currsize)
self.assertEqual((1, 1), cache.popitem())
def _test_getsizeof(self, cache):
self.assertEqual(0, cache.currsize)
self.assertEqual(3, cache.maxsize)
self.assertEqual(1, cache.getsizeof(1))
self.assertEqual(2, cache.getsizeof(2))
self.assertEqual(3, cache.getsizeof(3))
cache.update({1: 1, 2: 2})
self.assertEqual(2, len(cache))
self.assertEqual(3, cache.currsize)
self.assertEqual(1, cache[1])
self.assertEqual(2, cache[2])
cache[1] = 2
self.assertEqual(1, len(cache))
self.assertEqual(2, cache.currsize)
self.assertEqual(2, cache[1])
self.assertNotIn(2, cache)
cache.update({1: 1, 2: 2})
self.assertEqual(2, len(cache))
self.assertEqual(3, cache.currsize)
self.assertEqual(1, cache[1])
self.assertEqual(2, cache[2])
cache[3] = 3
self.assertEqual(1, len(cache))
self.assertEqual(3, cache.currsize)
self.assertEqual(3, cache[3])
self.assertNotIn(1, cache)
self.assertNotIn(2, cache)
with self.assertRaises(ValueError):
cache[3] = 4
self.assertEqual(1, len(cache))
self.assertEqual(3, cache.currsize)
self.assertEqual(3, cache[3])
with self.assertRaises(ValueError):
cache[4] = 4
self.assertEqual(1, len(cache))
self.assertEqual(3, cache.currsize)
self.assertEqual(3, cache[3])
def test_getsizeof_param(self):
self._test_getsizeof(self.Cache(maxsize=3, getsizeof=lambda x: x))
def test_getsizeof_subclass(self):
class Cache(self.Cache):
def getsizeof(self, value):
return value
self._test_getsizeof(Cache(maxsize=3))
def test_pickle(self):
import pickle
source = self.Cache(maxsize=2)
source.update({1: 1, 2: 2})
cache = pickle.loads(pickle.dumps(source))
self.assertEqual(source, cache)
self.assertEqual(2, len(cache))
self.assertEqual(1, cache[1])
self.assertEqual(2, cache[2])
cache[3] = 3
self.assertEqual(2, len(cache))
self.assertEqual(3, cache[3])
self.assertTrue(1 in cache or 2 in cache)
cache[4] = 4
self.assertEqual(2, len(cache))
self.assertEqual(4, cache[4])
self.assertTrue(1 in cache or 2 in cache or 3 in cache)
self.assertEqual(cache, pickle.loads(pickle.dumps(cache)))
def test_pickle_maxsize(self):
import pickle
import sys
# test empty cache, single element, large cache (recursion limit)
for n in [0, 1, sys.getrecursionlimit() * 2]:
source = self.Cache(maxsize=n)
source.update((i, i) for i in range(n))
cache = pickle.loads(pickle.dumps(source))
self.assertEqual(n, len(cache))
self.assertEqual(source, cache)
| cache = self.Cache(maxsize=2)
cache.update({1: 1, 2: 2})
self.assertEqual(2, len(cache))
self.assertEqual(1, cache[1])
self.assertEqual(2, cache[2])
cache[3] = 3
self.assertEqual(2, len(cache))
self.assertEqual(3, cache[3])
self.assertTrue(1 in cache or 2 in cache)
cache[4] = 4
self.assertEqual(2, len(cache))
self.assertEqual(4, cache[4])
self.assertTrue(1 in cache or 2 in cache or 3 in cache) |
config.rs | use std::{fs, net::SocketAddr, path::Path};
use anyhow::Result;
use http::Uri;
use serde::{de, Deserialize};
#[derive(Deserialize)]
pub struct Configuration {
/// Configuration for the Matrix server.
pub matrix: MatrixConfig,
/// Configuration for the HTTP API.
pub api: ApiConfig,
/// Configuration for the backend
pub backend: BackendConfig,
}
#[derive(Deserialize)]
pub struct MatrixConfig {
/// The bot's homeserver.
#[serde(deserialize_with = "deserialize_uri")]
pub homeserver: Uri,
/// The bot's account name.
pub user: String,
/// The bot's password.
pub password: String,
/// List of Matrix accounts with admin privileges for this bot.
pub admins: Vec<String>,
}
#[derive(Deserialize)]
pub struct ApiConfig {
/// The host and port to listen on.
pub listen: SocketAddr,
/// The API secret.
pub secret: String,
}
#[derive(Deserialize)]
pub struct BackendConfig {
pub host: String,
pub integrations_endpoint: Option<String>,
pub user: String,
pub password: String,
}
/// Read the configuration from the provided file.
pub fn parse<P: AsRef<Path>>(file: P) -> Result<Configuration> {
let content = fs::read_to_string(file)?;
let cfg = toml::from_str(&content)?;
Ok(cfg)
}
fn deserialize_uri<'de, D>(deserializer: D) -> Result<Uri, D::Error>
where
D: de::Deserializer<'de>,
{
let uri: &str = de::Deserialize::deserialize(deserializer)?;
uri.parse().map_err(de::Error::custom) | } |
|
index.tsx | export { choiceCardDefault } from '@guardian/src-foundations/themes';
| export { ChoiceCard } from './ChoiceCard';
export type { ChoiceCardProps } from './ChoiceCard';
export { ChoiceCardGroup } from './ChoiceCardGroup';
export type {
ChoiceCardGroupProps,
ChoiceCardColumns,
} from './ChoiceCardGroup'; | |
index.js | const Discord = require('discord.js');
const { token, id } = require('./config.json');
global.client = new Discord.Client({ | partials: ['MESSAGE', 'CHANNEL', 'REACTION']
});
client.on('ready', () => {
client.user.setActivity('mh!help', {
type: 'STREAMING',
url: 'https://www.twitch.tv/ '
});
require('./commands.js');
});
client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.log('Something went wrong when fetching the message: ', error);
return;
}
}
if (user.id == id) return;
const users = await reaction.users.fetch();
if (reaction.message.author.id == id || users.has(id)) reaction.users.remove(user.id);
});
client.login(token); | |
calc_fid_stats.py | import argparse
import os
import numpy as np
from torch.utils.data import DataLoader
from . import ImageDataset
from .core import get_inception_feature
def calc_and_save_stats(path, output, batch_size):
|
if __name__ == '__main__':
parser = argparse.ArgumentParser("Pre-calculate statistics of images")
parser.add_argument("--path", type=str, required=True,
help='path to image directory')
parser.add_argument("--output", type=str, required=True,
help="output path")
parser.add_argument("--batch_size", type=int, default=50,
help="batch size (default=50)")
args = parser.parse_args()
calc_and_save_stats(args.path, args.output, args.batch_size)
| dataset = ImageDataset(path, exts=['png', 'jpg'])
loader = DataLoader(dataset, batch_size=batch_size, num_workers=4)
acts, = get_inception_feature(loader, dims=[2048], verbose=True)
mu = np.mean(acts, axis=0)
sigma = np.cov(acts, rowvar=False)
if os.path.dirname(output) != "":
os.makedirs(os.path.dirname(output), exist_ok=True)
np.savez_compressed(output, mu=mu, sigma=sigma) |
auth_cache.go | package cmd
import (
"errors"
"fmt"
resty "github.com/go-resty/resty/v2"
helper "github.com/home-assistant/cli/client"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var authCacheCmd = &cobra.Command{
Use: "cache",
Aliases: []string{"data", "ca"},
Short: "Reset the auth cache of Home Assistant on Supervisor.",
Long: `
This command allows you to reset the internal password cache of a Home Assistant auth.
`,
Example: `
ha auth cache
`,
Run: func(cmd *cobra.Command, args []string) {
log.WithField("args", args).Debug("auth cache")
section := "auth"
command := "cache"
base := viper.GetString("endpoint")
url, err := helper.URLHelper(base, section, command)
if err != nil {
fmt.Println(err)
ExitWithError = true
return
}
request := helper.GetJSONRequest()
resp, err := request.Delete(url)
// returns 200 OK or 400, everything else is wrong
if err == nil {
if resp.StatusCode() != 200 && resp.StatusCode() != 400 {
err = errors.New("Unexpected server response")
log.Error(err)
} else if !resty.IsJSONType(resp.Header().Get("Content-Type")) {
err = errors.New("API did not return a JSON response")
log.Error(err)
}
}
if err != nil {
fmt.Println(err)
ExitWithError = true
} else {
ExitWithError = !helper.ShowJSONResponse(resp)
}
},
}
func | () {
authCmd.AddCommand(authCacheCmd)
}
| init |
root.go | // Copyright © 2018 NAME HERE <EMAIL ADDRESS>
//
// 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.
package cmd
import (
"fmt"
"os"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "dblux",
Short: "A brief description of your application",
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.dblux.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".dblux" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".dblux")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
} | ||
worker.go | package worker
import (
"context"
sha "crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/packethost/pkg/log"
"github.com/pkg/errors"
pb "github.com/tinkerbell/tink/protos/workflow"
"google.golang.org/grpc/status"
)
const (
dataFile = "data"
defaultDataDir = "/worker"
errGetWfContext = "failed to get workflow context"
errGetWfActions = "failed to get actions for workflow"
errReportActionStatus = "failed to report action status"
msgTurn = "it's turn for a different worker: %s"
)
type loggingContext string
var loggingContextKey loggingContext = "logger"
var (
workflowcontexts = map[string]*pb.WorkflowContext{}
workflowDataSHA = map[string]string{}
)
// WorkflowMetadata is the metadata related to workflow data.
type WorkflowMetadata struct {
WorkerID string `json:"workerID"`
Action string `json:"actionName"`
Task string `json:"taskName"`
UpdatedAt time.Time `json:"updatedAt"`
SHA string `json:"sha256"`
}
// Option is a type for modifying a worker.
type Option func(*Worker)
// WithRetries adds custom retries to a worker.
func WithRetries(interval time.Duration, retries int) Option {
return func(w *Worker) {
w.retries = retries
w.retryInterval = interval
}
}
// WithDataDir changes the default directory for a worker.
func WithDataDir(dir string) Option {
return func(w *Worker) {
w.dataDir = dir
}
}
// WithMaxFileSize changes the max file size for a worker.
func WithMaxFileSize(maxSize int64) Option {
return func(w *Worker) {
w.maxSize = maxSize
}
}
// WithLogCapture enables capture of container logs.
func WithLogCapture(capture bool) Option {
return func(w *Worker) {
w.captureLogs = capture
}
}
// WithPrivileged enables containers to be privileged.
func WithPrivileged(privileged bool) Option {
return func(w *Worker) {
w.createPrivileged = privileged
}
}
// LogCapturer emits container logs.
type LogCapturer interface {
CaptureLogs(ctx context.Context, containerID string)
}
// ContainerManager manages linux containers for Tinkerbell workers.
type ContainerManager interface {
CreateContainer(ctx context.Context, cmd []string, wfID string, action *pb.WorkflowAction, captureLogs, privileged bool) (string, error)
StartContainer(ctx context.Context, id string) error
WaitForContainer(ctx context.Context, id string) (pb.State, error)
WaitForFailedContainer(ctx context.Context, id string, failedActionStatus chan pb.State)
RemoveContainer(ctx context.Context, id string) error
PullImage(ctx context.Context, image string) error
}
// Worker details provide all the context needed to run workflows.
type Worker struct {
workerID string
logCapturer LogCapturer
containerManager ContainerManager
tinkClient pb.WorkflowServiceClient
logger log.Logger
dataDir string
maxSize int64
createPrivileged bool
captureLogs bool
retries int
retryInterval time.Duration
}
// NewWorker creates a new Worker, creating a new Docker registry client.
func NewWorker(
workerID string,
tinkClient pb.WorkflowServiceClient,
containerManager ContainerManager,
logCapturer LogCapturer,
logger log.Logger,
opts ...Option) *Worker {
w := &Worker{
workerID: workerID,
dataDir: defaultDataDir,
containerManager: containerManager,
logCapturer: logCapturer,
tinkClient: tinkClient,
logger: logger,
captureLogs: false,
createPrivileged: false,
retries: 3,
retryInterval: time.Second * 3,
maxSize: 1 << 20,
}
for _, opt := range opts {
opt(w)
}
return w
}
// getLogger is a helper function to get logging out of a context, or use the default logger.
func (w Worker) getLogger(ctx context.Context) *log.Logger {
loggerIface := ctx.Value(loggingContextKey)
if loggerIface == nil {
return &w.logger
}
return loggerIface.(*log.Logger)
}
// execute executes a workflow action, optionally capturing logs.
func (w *Worker) execute(ctx context.Context, wfID string, action *pb.WorkflowAction) (pb.State, error) {
l := w.getLogger(ctx).With("workflowID", wfID, "workerID", action.GetWorkerId(), "actionName", action.GetName(), "actionImage", action.GetImage())
if err := w.containerManager.PullImage(ctx, action.GetImage()); err != nil {
return pb.State_STATE_RUNNING, errors.Wrap(err, "pull image")
}
id, err := w.containerManager.CreateContainer(ctx, action.Command, wfID, action, w.captureLogs, w.createPrivileged)
if err != nil {
return pb.State_STATE_RUNNING, errors.Wrap(err, "create container")
}
l.With("containerID", id, "command", action.GetOnTimeout()).Info("container created")
var timeCtx context.Context
var cancel context.CancelFunc
if action.Timeout > 0 {
timeCtx, cancel = context.WithTimeout(ctx, time.Duration(action.Timeout)*time.Second)
} else {
timeCtx, cancel = context.WithTimeout(ctx, 1*time.Hour)
}
defer cancel()
err = w.containerManager.StartContainer(timeCtx, id)
if err != nil {
return pb.State_STATE_RUNNING, errors.Wrap(err, "start container")
}
if w.captureLogs {
go w.logCapturer.CaptureLogs(ctx, id)
}
st, err := w.containerManager.WaitForContainer(timeCtx, id)
l.With("status", st.String()).Info("wait container completed")
// If we've made it this far, the container has successfully completed.
// Everything after this is just cleanup.
defer func() {
if err := w.containerManager.RemoveContainer(ctx, id); err != nil {
l.With("containerID", id).Error(err)
}
l.With("status", st.String()).Info("container removed")
}()
if err != nil {
return st, errors.Wrap(err, "wait container")
}
if st == pb.State_STATE_SUCCESS {
l.With("status", st).Info("action container exited with success")
return st, nil
}
if st == pb.State_STATE_TIMEOUT && action.OnTimeout != nil {
rst := w.executeReaction(ctx, st.String(), action.OnTimeout, wfID, action)
l.With("status", rst).Info("action timeout")
} else if action.OnFailure != nil {
rst := w.executeReaction(ctx, st.String(), action.OnFailure, wfID, action)
l.With("status", rst).Info("action failed")
}
l.Info(infoWaitFinished)
if err != nil {
l.Error(errors.Wrap(err, errFailedToWait))
}
l.With("status", st).Info("action container exited")
return st, nil
}
// executeReaction executes special case OnTimeout/OnFailure actions.
func (w *Worker) executeReaction(ctx context.Context, reaction string, cmd []string, wfID string, action *pb.WorkflowAction) pb.State {
l := w.getLogger(ctx)
id, err := w.containerManager.CreateContainer(ctx, cmd, wfID, action, w.captureLogs, w.createPrivileged)
if err != nil {
l.Error(errors.Wrap(err, errFailedToRunCmd))
}
l.With("containerID", id, "actionStatus", reaction, "command", cmd).Info("container created")
if w.captureLogs {
go w.logCapturer.CaptureLogs(ctx, id)
}
st := make(chan pb.State)
go w.containerManager.WaitForFailedContainer(ctx, id, st)
err = w.containerManager.StartContainer(ctx, id)
if err != nil {
l.Error(errors.Wrap(err, errFailedToRunCmd))
}
return <-st
}
// ProcessWorkflowActions gets all Workflow contexts and processes their actions.
func (w *Worker) ProcessWorkflowActions(ctx context.Context) error {
l := w.logger.With("workerID", w.workerID)
for {
res, err := w.tinkClient.GetWorkflowContexts(ctx, &pb.WorkflowContextRequest{WorkerId: w.workerID})
if err != nil {
return errors.Wrap(err, errGetWfContext)
}
for wfContext, err := res.Recv(); err == nil && wfContext != nil; wfContext, err = res.Recv() {
wfID := wfContext.GetWorkflowId()
l = l.With("workflowID", wfID)
ctx := context.WithValue(ctx, loggingContextKey, &l)
actions, err := w.tinkClient.GetWorkflowActions(ctx, &pb.WorkflowActionsRequest{WorkflowId: wfID})
if err != nil {
return errors.Wrap(err, errGetWfActions)
}
turn := false
actionIndex := 0
var nextAction *pb.WorkflowAction
if wfContext.GetCurrentAction() == "" {
if actions.GetActionList()[0].GetWorkerId() == w.workerID {
actionIndex = 0
turn = true
}
} else {
switch wfContext.GetCurrentActionState() {
case pb.State_STATE_SUCCESS:
if isLastAction(wfContext, actions) |
nextAction = actions.GetActionList()[wfContext.GetCurrentActionIndex()+1]
actionIndex = int(wfContext.GetCurrentActionIndex()) + 1
case pb.State_STATE_FAILED:
continue
case pb.State_STATE_TIMEOUT:
continue
default:
nextAction = actions.GetActionList()[wfContext.GetCurrentActionIndex()]
actionIndex = int(wfContext.GetCurrentActionIndex())
}
if nextAction.GetWorkerId() == w.workerID {
turn = true
}
}
if turn {
wfDir := filepath.Join(w.dataDir, wfID)
l := l.With("actionName", actions.GetActionList()[actionIndex].GetName(),
"taskName", actions.GetActionList()[actionIndex].GetTaskName(),
)
if _, err := os.Stat(wfDir); os.IsNotExist(err) {
err := os.MkdirAll(wfDir, os.FileMode(0o755))
if err != nil {
l.Error(err)
os.Exit(1)
}
f := openDataFile(wfDir, l)
_, err = f.Write([]byte("{}"))
if err != nil {
l.Error(err)
os.Exit(1)
}
err = f.Close()
if err != nil {
l.Error(err)
os.Exit(1)
}
}
l.Info("starting action")
}
for turn {
action := actions.GetActionList()[actionIndex]
l := l.With(
"actionName", action.GetName(),
"taskName", action.GetTaskName(),
)
ctx := context.WithValue(ctx, loggingContextKey, &l)
if wfContext.GetCurrentActionState() != pb.State_STATE_RUNNING {
actionStatus := &pb.WorkflowActionStatus{
WorkflowId: wfID,
TaskName: action.GetTaskName(),
ActionName: action.GetName(),
ActionStatus: pb.State_STATE_RUNNING,
Seconds: 0,
Message: "Started execution",
WorkerId: action.GetWorkerId(),
}
err := w.reportActionStatus(ctx, actionStatus)
if err != nil {
exitWithGrpcError(err, l)
}
l.With("status", actionStatus.ActionStatus, "duration", strconv.FormatInt(actionStatus.Seconds, 10)).Info("sent action status")
}
// get workflow data
w.getWorkflowData(ctx, wfID)
// start executing the action
start := time.Now()
st, err := w.execute(ctx, wfID, action)
elapsed := time.Since(start)
actionStatus := &pb.WorkflowActionStatus{
WorkflowId: wfID,
TaskName: action.GetTaskName(),
ActionName: action.GetName(),
Seconds: int64(elapsed.Seconds()),
WorkerId: action.GetWorkerId(),
}
if err != nil || st != pb.State_STATE_SUCCESS {
if st == pb.State_STATE_TIMEOUT {
actionStatus.ActionStatus = pb.State_STATE_TIMEOUT
} else {
actionStatus.ActionStatus = pb.State_STATE_FAILED
}
l = l.With("actionStatus", actionStatus.ActionStatus.String())
l.Error(err)
if reportErr := w.reportActionStatus(ctx, actionStatus); reportErr != nil {
exitWithGrpcError(reportErr, l)
}
delete(workflowcontexts, wfID)
return err
}
actionStatus.ActionStatus = pb.State_STATE_SUCCESS
actionStatus.Message = "finished execution successfully"
err = w.reportActionStatus(ctx, actionStatus)
if err != nil {
exitWithGrpcError(err, l)
}
l.Info("sent action status")
// send workflow data, if updated
w.updateWorkflowData(ctx, actionStatus)
if len(actions.GetActionList()) == actionIndex+1 {
l.Info("reached to end of workflow")
delete(workflowcontexts, wfID)
turn = false // nolint:wastedassign // assigned to turn, but reassigned without using the value
break
}
nextAction := actions.GetActionList()[actionIndex+1]
if nextAction.GetWorkerId() != w.workerID {
l.Debug(fmt.Sprintf(msgTurn, nextAction.GetWorkerId()))
turn = false
} else {
actionIndex++
}
}
}
// sleep before asking for new workflows
<-time.After(w.retryInterval)
}
}
func exitWithGrpcError(err error, l log.Logger) {
if err != nil {
errStatus, _ := status.FromError(err)
l.With("errorCode", errStatus.Code()).Error(err)
os.Exit(1)
}
}
func isLastAction(wfContext *pb.WorkflowContext, actions *pb.WorkflowActionList) bool {
return int(wfContext.GetCurrentActionIndex()) == len(actions.GetActionList())-1
}
func (w *Worker) reportActionStatus(ctx context.Context, actionStatus *pb.WorkflowActionStatus) error {
l := w.getLogger(ctx).With("workflowID", actionStatus.GetWorkflowId(),
"workerID", actionStatus.GetWorkerId(),
"actionName", actionStatus.GetActionName(),
"taskName", actionStatus.GetTaskName(),
"status", actionStatus.ActionStatus,
)
var err error
for r := 1; r <= w.retries; r++ {
l.Info("reporting Action Status")
_, err = w.tinkClient.ReportActionStatus(ctx, actionStatus)
if err != nil {
l.Error(errors.Wrap(err, errReportActionStatus))
<-time.After(w.retryInterval)
continue
}
return nil
}
return err
}
func (w *Worker) getWorkflowData(ctx context.Context, workflowID string) {
l := w.getLogger(ctx).With("workflowID", workflowID,
"workerID", w.workerID,
)
res, err := w.tinkClient.GetWorkflowData(ctx, &pb.GetWorkflowDataRequest{WorkflowId: workflowID})
if err != nil {
l.Error(err)
}
if len(res.GetData()) != 0 {
wfDir := filepath.Join(w.dataDir, workflowID)
f := openDataFile(wfDir, l)
defer func() {
if err := f.Close(); err != nil {
l.With("file", f.Name()).Error(err)
}
}()
_, err := f.Write(res.GetData())
if err != nil {
l.Error(err)
}
h := sha.New()
workflowDataSHA[workflowID] = base64.StdEncoding.EncodeToString(h.Sum(res.Data))
}
}
func (w *Worker) updateWorkflowData(ctx context.Context, actionStatus *pb.WorkflowActionStatus) {
l := w.getLogger(ctx).With("workflowID", actionStatus.GetWorkflowId,
"workerID", actionStatus.GetWorkerId(),
"actionName", actionStatus.GetActionName(),
"taskName", actionStatus.GetTaskName(),
)
wfDir := filepath.Join(w.dataDir, actionStatus.GetWorkflowId())
f := openDataFile(wfDir, l)
defer func() {
if err := f.Close(); err != nil {
l.With("file", f.Name()).Error(err)
}
}()
data, err := ioutil.ReadAll(f)
if err != nil {
l.Error(err)
}
if isValidDataFile(f, w.maxSize, data, l) {
h := sha.New()
if _, ok := workflowDataSHA[actionStatus.GetWorkflowId()]; !ok {
checksum := base64.StdEncoding.EncodeToString(h.Sum(data))
workflowDataSHA[actionStatus.GetWorkflowId()] = checksum
w.sendUpdate(ctx, actionStatus, data, checksum)
} else {
newSHA := base64.StdEncoding.EncodeToString(h.Sum(data))
if !strings.EqualFold(workflowDataSHA[actionStatus.GetWorkflowId()], newSHA) {
w.sendUpdate(ctx, actionStatus, data, newSHA)
}
}
}
}
func (w *Worker) sendUpdate(ctx context.Context, st *pb.WorkflowActionStatus, data []byte, checksum string) {
l := w.getLogger(ctx).With("workflowID", st.GetWorkflowId,
"workerID", st.GetWorkerId(),
"actionName", st.GetActionName(),
"taskName", st.GetTaskName(),
)
meta := WorkflowMetadata{
WorkerID: st.GetWorkerId(),
Action: st.GetActionName(),
Task: st.GetTaskName(),
UpdatedAt: time.Now(),
SHA: checksum,
}
metadata, err := json.Marshal(meta)
if err != nil {
l.Error(err)
os.Exit(1)
}
_, err = w.tinkClient.UpdateWorkflowData(ctx, &pb.UpdateWorkflowDataRequest{
WorkflowId: st.GetWorkflowId(),
Data: data,
Metadata: metadata,
})
if err != nil {
l.Error(err)
os.Exit(1)
}
}
func openDataFile(wfDir string, l log.Logger) *os.File {
f, err := os.OpenFile(filepath.Clean(wfDir+string(os.PathSeparator)+dataFile), os.O_RDWR|os.O_CREATE, 0o600)
if err != nil {
l.Error(err)
os.Exit(1)
}
return f
}
func isValidDataFile(f *os.File, maxSize int64, data []byte, l log.Logger) bool {
var dataMap map[string]interface{}
err := json.Unmarshal(data, &dataMap)
if err != nil {
l.Error(err)
return false
}
stat, err := f.Stat()
if err != nil {
l.Error(err)
return false
}
return stat.Size() <= maxSize
}
| {
continue
} |
selection.ts | import { EventEmitter } from 'events';
import { obx, makeObservable } from '@alilc/lowcode-editor-core';
import { Node, comparePosition, PositionNO } from './node/node';
import { DocumentModel } from './document-model';
export class | {
private emitter = new EventEmitter();
@obx.shallow private _selected: string[] = [];
constructor(readonly doc: DocumentModel) {
makeObservable(this);
}
/**
* 选中的节点 id
*/
get selected(): string[] {
return this._selected;
}
/**
* 选中
*/
select(id: string) {
if (this._selected.length === 1 && this._selected.indexOf(id) > -1) {
// avoid cause reaction
return;
}
this._selected = [id];
this.emitter.emit('selectionchange', this._selected);
}
/**
* 批量选中
*/
selectAll(ids: string[]) {
this._selected = ids;
this.emitter.emit('selectionchange', this._selected);
}
/**
* 清除选中
*/
clear() {
if (this._selected.length < 1) {
return;
}
this._selected = [];
this.emitter.emit('selectionchange', this._selected);
}
/**
* 整理选中
*/
dispose() {
const l = this._selected.length;
let i = l;
while (i-- > 0) {
const id = this._selected[i];
if (!this.doc.hasNode(id)) {
this._selected.splice(i, 1);
}
}
if (this._selected.length !== l) {
this.emitter.emit('selectionchange', this._selected);
}
}
/**
* 添加选中
*/
add(id: string) {
if (this._selected.indexOf(id) > -1) {
return;
}
this._selected.push(id);
this.emitter.emit('selectionchange', this._selected);
}
/**
* 是否选中
*/
has(id: string) {
return this._selected.indexOf(id) > -1;
}
/**
* 移除选中
*/
remove(id: string) {
const i = this._selected.indexOf(id);
if (i > -1) {
this._selected.splice(i, 1);
this.emitter.emit('selectionchange', this._selected);
}
}
/**
* 选区是否包含节点
*/
containsNode(node: Node, excludeRoot = false) {
for (const id of this._selected) {
const parent = this.doc.getNode(id);
if (excludeRoot && parent?.contains(this.doc.focusNode)) {
continue;
}
if (parent?.contains(node)) {
return true;
}
}
return false;
}
/**
* 获取选中的节点
*/
getNodes() {
const nodes = [];
for (const id of this._selected) {
const node = this.doc.getNode(id);
if (node) {
nodes.push(node);
}
}
return nodes;
}
/**
* 获取顶层选区节点, 场景:拖拽时,建立蒙层,只蒙在最上层
*/
getTopNodes(includeRoot = false) {
const nodes = [];
for (const id of this._selected) {
const node = this.doc.getNode(id);
// 排除根节点
if (!node || (!includeRoot && node.contains(this.doc.focusNode))) {
continue;
}
let i = nodes.length;
let isTop = true;
while (i-- > 0) {
const n = comparePosition(nodes[i], node);
// nodes[i] contains node
if (n === PositionNO.Contains || n === PositionNO.TheSame) {
isTop = false;
break;
}
// node contains nodes[i], delete nodes[i]
if (n === PositionNO.ContainedBy) {
nodes.splice(i, 1);
}
}
// node is top item, push to nodes
if (isTop) {
nodes.push(node);
}
}
return nodes;
}
onSelectionChange(fn: (ids: string[]) => void): () => void {
this.emitter.on('selectionchange', fn);
return () => {
this.emitter.removeListener('selectionchange', fn);
};
}
}
| Selection |
audiofile_processor.py | from os import listdir
import os.path as osp
class AudiofileProcessor(object):
SECONDS = 60
POMADORO_LENGTH_IN_SECONDS = 25 * SECONDS | def __init__(self, directory, filter_by_ext, length_calculator):
self.directory = directory
self.filter_by_ext = filter_by_ext
self.length_calculator = length_calculator
def _get_files(self):
files = []
if osp.isdir(self.directory):
for f in listdir(self.directory):
if osp.isfile(osp.join(self.directory, f)) and self.filter_by_ext(f):
files.append(osp.join(self.directory, f))
return files
def pomodoro(self):
files = self._get_files()
length = 0
for f in files:
length += self.length_calculator(f)
l = round(length)
print("Pomodoros listened: #{}. Time remained: {}:{}"
.format(l // self.POMADORO_LENGTH_IN_SECONDS,
(l % self.POMADORO_LENGTH_IN_SECONDS) // self.SECONDS,
(l % self.POMADORO_LENGTH_IN_SECONDS) % self.SECONDS)) | |
finder_opponent_tab.py | from tests.src import BasePage
from tests.src.elements.select import SelectList
from tests.src.validator_error import ValidatorPhoneMixin
class FinderOpponentTab(BasePage):
| def __init__(self, phone: str, district: str, category: str, datetime_: str,):
super().__init__()
self.phone = phone
self.district = district
self.category = category
self.datetime_ = datetime_
self.select = SelectList
def fill_form(self) -> None:
if ValidatorPhoneMixin().check_phone(self.phone):
self.set_value('phone', self.phone)
self.select(name='district').select_by_text(self.district)
self.select(name='category').select_by_text(self.category)
self.set_datetime(self.datetime_) |
|
export.rs | use std::path::Path;
use crate::{
constants::{AWS_DEFAULT_REGION, DEFAULT_FILENAME_LENGTH},
fs::S3FileSystem,
};
use async_trait::async_trait;
use pipebase::{
common::{ConfigInto, FromConfig, FromPath},
export::Export,
};
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use s3::{ByteStream, Client, Config, Region};
use serde::Deserialize;
#[derive(Deserialize)]
pub struct S3WriterConfig {
region: Option<String>,
bucket: String,
directory: String,
filename_length: Option<usize>,
filename_ext: Option<String>,
}
impl FromPath for S3WriterConfig {}
impl ConfigInto<S3Writer> for S3WriterConfig {}
pub struct S3Writer {
fs: S3FileSystem,
bucket: String,
// key prefix
directory: String,
filename_length: usize,
filename_ext: Option<String>,
}
#[async_trait]
impl FromConfig<S3WriterConfig> for S3Writer {
async fn from_config(config: S3WriterConfig) -> anyhow::Result<Self> {
let region = config
.region
.unwrap_or_else(|| AWS_DEFAULT_REGION.to_owned());
let region = Region::new(region);
let conf = Config::builder().region(region).build();
let client = Client::from_conf(conf);
let filename_length = config.filename_length.unwrap_or(DEFAULT_FILENAME_LENGTH);
let mut directory = config.directory;
if !directory.ends_with('/') {
directory.push('/')
}
Ok(S3Writer {
fs: S3FileSystem::new(client), | filename_length,
filename_ext: config.filename_ext,
})
}
}
#[async_trait]
impl<T> Export<T, S3WriterConfig> for S3Writer
where
T: AsRef<Path> + Send + 'static,
{
async fn export(&mut self, t: T) -> anyhow::Result<()> {
self.write(t).await
}
}
impl S3Writer {
async fn write<P>(&self, path: P) -> anyhow::Result<()>
where
P: AsRef<Path>,
{
let bytes = ByteStream::from_path(path).await?;
let key = self.generate_file_path();
self.fs.put_object(self.bucket.to_owned(), key, bytes).await
}
fn generate_file_path(&self) -> String {
let filename: String = thread_rng()
.sample_iter(&Alphanumeric)
.take(self.filename_length)
.map(char::from)
.collect();
let filename = match self.filename_ext {
Some(ref ext) => format!("{}.{}", filename, ext),
None => filename,
};
format!("{}{}", self.directory, filename)
}
} | bucket: config.bucket,
directory, |
test_queue.py | from guillotina.async_util import IAsyncJobPool
from guillotina.async_util import IQueueUtility
from guillotina.browser import View
from guillotina.component import get_utility
from guillotina.tests import utils
import asyncio
class AsyncMockView(View):
|
async def test_add_sync_utility(guillotina, loop):
util = get_utility(IQueueUtility)
var = []
async def printHi(msg):
await asyncio.sleep(0.01)
var.append(msg)
request = utils.get_mocked_request(guillotina.db)
root = await utils.get_root(request)
await util.add(AsyncMockView(root, request, printHi, 'hola1'))
await util.add(AsyncMockView(root, request, printHi, 'hola2'))
await util.add(AsyncMockView(root, request, printHi, 'hola3'))
await util.add(AsyncMockView(root, request, printHi, 'hola4'))
await util._queue.join()
assert 'hola1' in var
assert 'hola2' in var
assert 'hola3' in var
assert 'hola4' in var
assert len(var) == 4
class JobRunner:
def __init__(self):
self.done = False
self.wait = True
async def __call__(self, arg1):
while self.wait:
await asyncio.sleep(0.05)
self.done = True
async def test_run_jobs(guillotina):
pool = get_utility(IAsyncJobPool)
job = pool.add_job(JobRunner(), args=['foobar'])
assert pool.num_running == 1
assert pool.num_pending == 0
await asyncio.sleep(0.1)
assert pool.num_running == 1
job.func.wait = False
await asyncio.sleep(0.1)
assert pool.num_running == 0
assert pool.num_pending == 0
assert job.func.done
async def test_run_many_jobs(guillotina, dummy_request):
pool = get_utility(IAsyncJobPool)
jobs = [pool.add_job(JobRunner(), args=['foobar'], request=dummy_request)
for _ in range(20)]
assert pool.num_running == 5
assert pool.num_pending == 15
for job in jobs:
job.func.wait = False
await asyncio.sleep(0.1)
assert pool.num_running == 0
assert pool.num_pending == 0
for job in jobs:
assert job.func.done
| def __init__(self, context, request, func, *args, **kwargs):
self.context = context
self.request = request
self.func = func
self.args = args
self.kwargs = kwargs
async def __call__(self):
await self.func(*self.args, **self.kwargs) |
sqlite3.go | // Copyright (C) 2014 Yasuhiro Matsumoto <[email protected]>.
// Copyright (C) 2018 G.J.R. Timmer <[email protected]>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// +build cgo
package sqlite3
/*
#cgo CFLAGS: -std=gnu99
#cgo CFLAGS: -DSQLITE_ENABLE_RTREE
#cgo CFLAGS: -DSQLITE_THREADSAFE=1
#cgo CFLAGS: -DHAVE_USLEEP=1
#cgo CFLAGS: -DSQLITE_ENABLE_FTS3
#cgo CFLAGS: -DSQLITE_ENABLE_FTS3_PARENTHESIS
#cgo CFLAGS: -DSQLITE_ENABLE_FTS4_UNICODE61
#cgo CFLAGS: -DSQLITE_TRACE_SIZE_LIMIT=15
#cgo CFLAGS: -DSQLITE_OMIT_DEPRECATED
#cgo CFLAGS: -DSQLITE_DISABLE_INTRINSIC
#cgo CFLAGS: -DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1
#cgo CFLAGS: -DSQLITE_ENABLE_UPDATE_DELETE_LIMIT
#cgo CFLAGS: -Wno-deprecated-declarations
#cgo linux,!android CFLAGS: -DHAVE_PREAD64=1 -DHAVE_PWRITE64=1
#ifndef USE_LIBSQLITE3
#include <sqlite3-binding.h>
#else
#include <sqlite3.h>
#endif
#include <stdlib.h>
#include <string.h>
#ifdef __CYGWIN__
# include <errno.h>
#endif
#ifndef SQLITE_OPEN_READWRITE
# define SQLITE_OPEN_READWRITE 0
#endif
#ifndef SQLITE_OPEN_FULLMUTEX
# define SQLITE_OPEN_FULLMUTEX 0
#endif
#ifndef SQLITE_DETERMINISTIC
# define SQLITE_DETERMINISTIC 0
#endif
static int
_sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs) {
#ifdef SQLITE_OPEN_URI
return sqlite3_open_v2(filename, ppDb, flags | SQLITE_OPEN_URI, zVfs);
#else
return sqlite3_open_v2(filename, ppDb, flags, zVfs);
#endif
}
static int
_sqlite3_bind_text(sqlite3_stmt *stmt, int n, char *p, int np) {
return sqlite3_bind_text(stmt, n, p, np, SQLITE_TRANSIENT);
}
static int
_sqlite3_bind_blob(sqlite3_stmt *stmt, int n, void *p, int np) {
return sqlite3_bind_blob(stmt, n, p, np, SQLITE_TRANSIENT);
}
#include <stdio.h>
#include <stdint.h>
static int
_sqlite3_exec(sqlite3* db, const char* pcmd, long long* rowid, long long* changes)
{
int rv = sqlite3_exec(db, pcmd, 0, 0, 0);
*rowid = (long long) sqlite3_last_insert_rowid(db);
*changes = (long long) sqlite3_changes(db);
return rv;
}
#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
extern int _sqlite3_step_blocking(sqlite3_stmt *stmt);
extern int _sqlite3_step_row_blocking(sqlite3_stmt* stmt, long long* rowid, long long* changes);
extern int _sqlite3_prepare_v2_blocking(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail);
static int
_sqlite3_step_internal(sqlite3_stmt *stmt)
{
return _sqlite3_step_blocking(stmt);
}
static int
_sqlite3_step_row_internal(sqlite3_stmt* stmt, long long* rowid, long long* changes)
{
return _sqlite3_step_row_blocking(stmt, rowid, changes);
}
static int
_sqlite3_prepare_v2_internal(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail)
{
return _sqlite3_prepare_v2_blocking(db, zSql, nBytes, ppStmt, pzTail);
}
#else
static int
_sqlite3_step_internal(sqlite3_stmt *stmt)
{
return sqlite3_step(stmt);
}
static int
_sqlite3_step_row_internal(sqlite3_stmt* stmt, long long* rowid, long long* changes)
{
int rv = sqlite3_step(stmt);
sqlite3* db = sqlite3_db_handle(stmt);
*rowid = (long long) sqlite3_last_insert_rowid(db);
*changes = (long long) sqlite3_changes(db);
return rv;
}
static int
_sqlite3_prepare_v2_internal(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail)
{
return sqlite3_prepare_v2(db, zSql, nBytes, ppStmt, pzTail);
}
#endif
void _sqlite3_result_text(sqlite3_context* ctx, const char* s) {
sqlite3_result_text(ctx, s, -1, &free);
}
void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l) {
sqlite3_result_blob(ctx, b, l, SQLITE_TRANSIENT);
}
int _sqlite3_create_function(
sqlite3 *db,
const char *zFunctionName,
int nArg,
int eTextRep,
uintptr_t pApp,
void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
void (*xStep)(sqlite3_context*,int,sqlite3_value**),
void (*xFinal)(sqlite3_context*)
) {
return sqlite3_create_function(db, zFunctionName, nArg, eTextRep, (void*) pApp, xFunc, xStep, xFinal);
}
void callbackTrampoline(sqlite3_context*, int, sqlite3_value**);
void stepTrampoline(sqlite3_context*, int, sqlite3_value**);
void doneTrampoline(sqlite3_context*);
int compareTrampoline(void*, int, char*, int, char*);
int commitHookTrampoline(void*);
void rollbackHookTrampoline(void*);
void updateHookTrampoline(void*, int, char*, char*, sqlite3_int64);
int authorizerTrampoline(void*, int, char*, char*, char*, char*);
#ifdef SQLITE_LIMIT_WORKER_THREADS
# define _SQLITE_HAS_LIMIT
# define SQLITE_LIMIT_LENGTH 0
# define SQLITE_LIMIT_SQL_LENGTH 1
# define SQLITE_LIMIT_COLUMN 2
# define SQLITE_LIMIT_EXPR_DEPTH 3
# define SQLITE_LIMIT_COMPOUND_SELECT 4
# define SQLITE_LIMIT_VDBE_OP 5
# define SQLITE_LIMIT_FUNCTION_ARG 6
# define SQLITE_LIMIT_ATTACHED 7
# define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
# define SQLITE_LIMIT_VARIABLE_NUMBER 9
# define SQLITE_LIMIT_TRIGGER_DEPTH 10
# define SQLITE_LIMIT_WORKER_THREADS 11
# else
# define SQLITE_LIMIT_WORKER_THREADS 11
#endif
static int _sqlite3_limit(sqlite3* db, int limitId, int newLimit) {
#ifndef _SQLITE_HAS_LIMIT
return -1;
#else
return sqlite3_limit(db, limitId, newLimit);
#endif
}
*/
import "C"
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"io"
"net/url"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"time"
"unsafe"
)
// SQLiteTimestampFormats is timestamp formats understood by both this module
// and SQLite. The first format in the slice will be used when saving time
// values into the database. When parsing a string from a timestamp or datetime
// column, the formats are tried in order.
var SQLiteTimestampFormats = []string{
// By default, store timestamps with whatever timezone they come with.
// When parsed, they will be returned with the same timezone.
"2006-01-02 15:04:05.999999999-07:00",
"2006-01-02T15:04:05.999999999-07:00",
"2006-01-02 15:04:05.999999999",
"2006-01-02T15:04:05.999999999",
"2006-01-02 15:04:05",
"2006-01-02T15:04:05",
"2006-01-02 15:04",
"2006-01-02T15:04",
"2006-01-02",
}
const (
columnDate string = "date"
columnDatetime string = "datetime"
columnTimestamp string = "timestamp"
)
func init() {
sql.Register("sqlite3", &SQLiteDriver{})
}
// Version returns SQLite library version information.
func Version() (libVersion string, libVersionNumber int, sourceID string) {
libVersion = C.GoString(C.sqlite3_libversion())
libVersionNumber = int(C.sqlite3_libversion_number())
sourceID = C.GoString(C.sqlite3_sourceid())
return libVersion, libVersionNumber, sourceID
}
const (
// used by authorizer and pre_update_hook
SQLITE_DELETE = C.SQLITE_DELETE
SQLITE_INSERT = C.SQLITE_INSERT
SQLITE_UPDATE = C.SQLITE_UPDATE
// used by authorzier - as return value
SQLITE_OK = C.SQLITE_OK
SQLITE_IGNORE = C.SQLITE_IGNORE
SQLITE_DENY = C.SQLITE_DENY
// different actions query tries to do - passed as argument to authorizer
SQLITE_CREATE_INDEX = C.SQLITE_CREATE_INDEX
SQLITE_CREATE_TABLE = C.SQLITE_CREATE_TABLE
SQLITE_CREATE_TEMP_INDEX = C.SQLITE_CREATE_TEMP_INDEX
SQLITE_CREATE_TEMP_TABLE = C.SQLITE_CREATE_TEMP_TABLE
SQLITE_CREATE_TEMP_TRIGGER = C.SQLITE_CREATE_TEMP_TRIGGER
SQLITE_CREATE_TEMP_VIEW = C.SQLITE_CREATE_TEMP_VIEW
SQLITE_CREATE_TRIGGER = C.SQLITE_CREATE_TRIGGER
SQLITE_CREATE_VIEW = C.SQLITE_CREATE_VIEW
SQLITE_CREATE_VTABLE = C.SQLITE_CREATE_VTABLE
SQLITE_DROP_INDEX = C.SQLITE_DROP_INDEX
SQLITE_DROP_TABLE = C.SQLITE_DROP_TABLE
SQLITE_DROP_TEMP_INDEX = C.SQLITE_DROP_TEMP_INDEX
SQLITE_DROP_TEMP_TABLE = C.SQLITE_DROP_TEMP_TABLE
SQLITE_DROP_TEMP_TRIGGER = C.SQLITE_DROP_TEMP_TRIGGER
SQLITE_DROP_TEMP_VIEW = C.SQLITE_DROP_TEMP_VIEW
SQLITE_DROP_TRIGGER = C.SQLITE_DROP_TRIGGER
SQLITE_DROP_VIEW = C.SQLITE_DROP_VIEW
SQLITE_DROP_VTABLE = C.SQLITE_DROP_VTABLE
SQLITE_PRAGMA = C.SQLITE_PRAGMA
SQLITE_READ = C.SQLITE_READ
SQLITE_SELECT = C.SQLITE_SELECT
SQLITE_TRANSACTION = C.SQLITE_TRANSACTION
SQLITE_ATTACH = C.SQLITE_ATTACH
SQLITE_DETACH = C.SQLITE_DETACH
SQLITE_ALTER_TABLE = C.SQLITE_ALTER_TABLE
SQLITE_REINDEX = C.SQLITE_REINDEX
SQLITE_ANALYZE = C.SQLITE_ANALYZE
SQLITE_FUNCTION = C.SQLITE_FUNCTION
SQLITE_SAVEPOINT = C.SQLITE_SAVEPOINT
SQLITE_COPY = C.SQLITE_COPY
/*SQLITE_RECURSIVE = C.SQLITE_RECURSIVE*/
)
// SQLiteDriver implements driver.Driver.
type SQLiteDriver struct {
Extensions []string
ConnectHook func(*SQLiteConn) error
}
// SQLiteConn implements driver.Conn.
type SQLiteConn struct {
mu sync.Mutex
db *C.sqlite3
loc *time.Location
txlock string
funcs []*functionInfo
aggregators []*aggInfo
}
// SQLiteTx implements driver.Tx.
type SQLiteTx struct {
c *SQLiteConn
}
// SQLiteStmt implements driver.Stmt.
type SQLiteStmt struct {
mu sync.Mutex
c *SQLiteConn
s *C.sqlite3_stmt
t string
closed bool
cls bool
}
// SQLiteResult implements sql.Result.
type SQLiteResult struct {
id int64
changes int64
}
// SQLiteRows implements driver.Rows.
type SQLiteRows struct {
s *SQLiteStmt
nc int
cols []string
decltype []string
cls bool
closed bool
done chan struct{}
}
type functionInfo struct {
f reflect.Value
argConverters []callbackArgConverter
variadicConverter callbackArgConverter
retConverter callbackRetConverter
}
func (fi *functionInfo) Call(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
args, err := callbackConvertArgs(argv, fi.argConverters, fi.variadicConverter)
if err != nil {
callbackError(ctx, err)
return
}
ret := fi.f.Call(args)
if len(ret) == 2 && ret[1].Interface() != nil {
callbackError(ctx, ret[1].Interface().(error))
return
}
err = fi.retConverter(ctx, ret[0])
if err != nil {
callbackError(ctx, err)
return
}
}
type aggInfo struct {
constructor reflect.Value
// Active aggregator objects for aggregations in flight. The
// aggregators are indexed by a counter stored in the aggregation
// user data space provided by sqlite.
active map[int64]reflect.Value
next int64
stepArgConverters []callbackArgConverter
stepVariadicConverter callbackArgConverter
doneRetConverter callbackRetConverter
}
func (ai *aggInfo) agg(ctx *C.sqlite3_context) (int64, reflect.Value, error) {
aggIdx := (*int64)(C.sqlite3_aggregate_context(ctx, C.int(8)))
if *aggIdx == 0 {
*aggIdx = ai.next
ret := ai.constructor.Call(nil)
if len(ret) == 2 && ret[1].Interface() != nil {
return 0, reflect.Value{}, ret[1].Interface().(error)
}
if ret[0].IsNil() {
return 0, reflect.Value{}, errors.New("aggregator constructor returned nil state")
}
ai.next++
ai.active[*aggIdx] = ret[0]
}
return *aggIdx, ai.active[*aggIdx], nil
}
func (ai *aggInfo) Step(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
_, agg, err := ai.agg(ctx)
if err != nil {
callbackError(ctx, err)
return
}
args, err := callbackConvertArgs(argv, ai.stepArgConverters, ai.stepVariadicConverter)
if err != nil {
callbackError(ctx, err)
return
}
ret := agg.MethodByName("Step").Call(args)
if len(ret) == 1 && ret[0].Interface() != nil {
callbackError(ctx, ret[0].Interface().(error))
return
}
}
func (ai *aggInfo) Done(ctx *C.sqlite3_context) {
idx, agg, err := ai.agg(ctx)
if err != nil {
callbackError(ctx, err)
return
}
defer func() { delete(ai.active, idx) }()
ret := agg.MethodByName("Done").Call(nil)
if len(ret) == 2 && ret[1].Interface() != nil {
callbackError(ctx, ret[1].Interface().(error))
return
}
err = ai.doneRetConverter(ctx, ret[0])
if err != nil {
callbackError(ctx, err)
return
}
}
// Commit transaction.
func (tx *SQLiteTx) Commit() error {
_, err := tx.c.exec(context.Background(), "COMMIT", nil)
if err != nil && err.(Error).Code == C.SQLITE_BUSY {
// sqlite3 will leave the transaction open in this scenario.
// However, database/sql considers the transaction complete once we
// return from Commit() - we must clean up to honour its semantics.
tx.c.exec(context.Background(), "ROLLBACK", nil)
}
return err
}
// Rollback transaction.
func (tx *SQLiteTx) Rollback() error {
_, err := tx.c.exec(context.Background(), "ROLLBACK", nil)
return err
}
// RegisterCollation makes a Go function available as a collation.
//
// cmp receives two UTF-8 strings, a and b. The result should be 0 if
// a==b, -1 if a < b, and +1 if a > b.
//
// cmp must always return the same result given the same
// inputs. Additionally, it must have the following properties for all
// strings A, B and C: if A==B then B==A; if A==B and B==C then A==C;
// if A<B then B>A; if A<B and B<C then A<C.
//
// If cmp does not obey these constraints, sqlite3's behavior is
// undefined when the collation is used.
func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int) error {
handle := newHandle(c, cmp)
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
rv := C.sqlite3_create_collation(c.db, cname, C.SQLITE_UTF8, unsafe.Pointer(handle), (*[0]byte)(unsafe.Pointer(C.compareTrampoline)))
if rv != C.SQLITE_OK {
return c.lastError()
}
return nil
}
// RegisterCommitHook sets the commit hook for a connection.
//
// If the callback returns non-zero the transaction will become a rollback.
//
// If there is an existing commit hook for this connection, it will be
// removed. If callback is nil the existing hook (if any) will be removed
// without creating a new one.
func (c *SQLiteConn) RegisterCommitHook(callback func() int) {
if callback == nil {
C.sqlite3_commit_hook(c.db, nil, nil)
} else {
C.sqlite3_commit_hook(c.db, (*[0]byte)(C.commitHookTrampoline), unsafe.Pointer(newHandle(c, callback)))
}
}
// RegisterRollbackHook sets the rollback hook for a connection.
//
// If there is an existing rollback hook for this connection, it will be
// removed. If callback is nil the existing hook (if any) will be removed
// without creating a new one.
func (c *SQLiteConn) RegisterRollbackHook(callback func()) {
if callback == nil {
C.sqlite3_rollback_hook(c.db, nil, nil)
} else {
C.sqlite3_rollback_hook(c.db, (*[0]byte)(C.rollbackHookTrampoline), unsafe.Pointer(newHandle(c, callback)))
}
}
// RegisterUpdateHook sets the update hook for a connection.
//
// The parameters to the callback are the operation (one of the constants
// SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), the database name, the
// table name, and the rowid.
//
// If there is an existing update hook for this connection, it will be
// removed. If callback is nil the existing hook (if any) will be removed
// without creating a new one.
func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64)) {
if callback == nil {
C.sqlite3_update_hook(c.db, nil, nil)
} else {
C.sqlite3_update_hook(c.db, (*[0]byte)(C.updateHookTrampoline), unsafe.Pointer(newHandle(c, callback)))
}
}
// RegisterAuthorizer sets the authorizer for connection.
//
// The parameters to the callback are the operation (one of the constants
// SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), and 1 to 3 arguments,
// depending on operation. More details see:
// https://www.sqlite.org/c3ref/c_alter_table.html
func (c *SQLiteConn) RegisterAuthorizer(callback func(int, string, string, string) int) {
if callback == nil {
C.sqlite3_set_authorizer(c.db, nil, nil)
} else {
C.sqlite3_set_authorizer(c.db, (*[0]byte)(C.authorizerTrampoline), unsafe.Pointer(newHandle(c, callback)))
}
}
// RegisterFunc makes a Go function available as a SQLite function.
//
// The Go function can have arguments of the following types: any
// numeric type except complex, bool, []byte, string and
// interface{}. interface{} arguments are given the direct translation
// of the SQLite data type: int64 for INTEGER, float64 for FLOAT,
// []byte for BLOB, string for TEXT.
//
// The function can additionally be variadic, as long as the type of
// the variadic argument is one of the above.
//
// If pure is true. SQLite will assume that the function's return
// value depends only on its inputs, and make more aggressive
// optimizations in its queries.
//
// See _example/go_custom_funcs for a detailed example.
func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error {
var fi functionInfo
fi.f = reflect.ValueOf(impl)
t := fi.f.Type()
if t.Kind() != reflect.Func {
return errors.New("Non-function passed to RegisterFunc")
}
if t.NumOut() != 1 && t.NumOut() != 2 {
return errors.New("SQLite functions must return 1 or 2 values")
}
if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
return errors.New("Second return value of SQLite function must be error")
}
numArgs := t.NumIn()
if t.IsVariadic() {
numArgs--
}
for i := 0; i < numArgs; i++ {
conv, err := callbackArg(t.In(i))
if err != nil {
return err
}
fi.argConverters = append(fi.argConverters, conv)
}
if t.IsVariadic() {
conv, err := callbackArg(t.In(numArgs).Elem())
if err != nil {
return err
}
fi.variadicConverter = conv
// Pass -1 to sqlite so that it allows any number of
// arguments. The call helper verifies that the minimum number
// of arguments is present for variadic functions.
numArgs = -1
}
conv, err := callbackRet(t.Out(0))
if err != nil {
return err
}
fi.retConverter = conv
// fi must outlast the database connection, or we'll have dangling pointers.
c.funcs = append(c.funcs, &fi)
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
opts := C.SQLITE_UTF8
if pure {
opts |= C.SQLITE_DETERMINISTIC
}
rv := sqlite3CreateFunction(c.db, cname, C.int(numArgs), C.int(opts), newHandle(c, &fi), C.callbackTrampoline, nil, nil)
if rv != C.SQLITE_OK {
return c.lastError()
}
return nil
}
func sqlite3CreateFunction(db *C.sqlite3, zFunctionName *C.char, nArg C.int, eTextRep C.int, pApp uintptr, xFunc unsafe.Pointer, xStep unsafe.Pointer, xFinal unsafe.Pointer) C.int {
return C._sqlite3_create_function(db, zFunctionName, nArg, eTextRep, C.uintptr_t(pApp), (*[0]byte)(xFunc), (*[0]byte)(xStep), (*[0]byte)(xFinal))
}
// RegisterAggregator makes a Go type available as a SQLite aggregation function.
//
// Because aggregation is incremental, it's implemented in Go with a
// type that has 2 methods: func Step(values) accumulates one row of
// data into the accumulator, and func Done() ret finalizes and
// returns the aggregate value. "values" and "ret" may be any type
// supported by RegisterFunc.
//
// RegisterAggregator takes as implementation a constructor function
// that constructs an instance of the aggregator type each time an
// aggregation begins. The constructor must return a pointer to a
// type, or an interface that implements Step() and Done().
//
// The constructor function and the Step/Done methods may optionally
// return an error in addition to their other return values.
//
// See _example/go_custom_funcs for a detailed example.
func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error {
var ai aggInfo
ai.constructor = reflect.ValueOf(impl)
t := ai.constructor.Type()
if t.Kind() != reflect.Func {
return errors.New("non-function passed to RegisterAggregator")
}
if t.NumOut() != 1 && t.NumOut() != 2 {
return errors.New("SQLite aggregator constructors must return 1 or 2 values")
}
if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
return errors.New("Second return value of SQLite function must be error")
}
if t.NumIn() != 0 {
return errors.New("SQLite aggregator constructors must not have arguments")
}
agg := t.Out(0)
switch agg.Kind() {
case reflect.Ptr, reflect.Interface:
default:
return errors.New("SQlite aggregator constructor must return a pointer object")
}
stepFn, found := agg.MethodByName("Step")
if !found {
return errors.New("SQlite aggregator doesn't have a Step() function")
}
step := stepFn.Type
if step.NumOut() != 0 && step.NumOut() != 1 {
return errors.New("SQlite aggregator Step() function must return 0 or 1 values")
}
if step.NumOut() == 1 && !step.Out(0).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
return errors.New("type of SQlite aggregator Step() return value must be error")
}
stepNArgs := step.NumIn()
start := 0
if agg.Kind() == reflect.Ptr {
// Skip over the method receiver
stepNArgs--
start++
}
if step.IsVariadic() {
stepNArgs--
}
for i := start; i < start+stepNArgs; i++ {
conv, err := callbackArg(step.In(i))
if err != nil {
return err
}
ai.stepArgConverters = append(ai.stepArgConverters, conv)
}
if step.IsVariadic() {
conv, err := callbackArg(t.In(start + stepNArgs).Elem())
if err != nil {
return err
}
ai.stepVariadicConverter = conv
// Pass -1 to sqlite so that it allows any number of
// arguments. The call helper verifies that the minimum number
// of arguments is present for variadic functions.
stepNArgs = -1
}
doneFn, found := agg.MethodByName("Done")
if !found {
return errors.New("SQlite aggregator doesn't have a Done() function")
}
done := doneFn.Type
doneNArgs := done.NumIn()
if agg.Kind() == reflect.Ptr {
// Skip over the method receiver
doneNArgs--
}
if doneNArgs != 0 {
return errors.New("SQlite aggregator Done() function must have no arguments")
}
if done.NumOut() != 1 && done.NumOut() != 2 {
return errors.New("SQLite aggregator Done() function must return 1 or 2 values")
}
if done.NumOut() == 2 && !done.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
return errors.New("second return value of SQLite aggregator Done() function must be error")
}
conv, err := callbackRet(done.Out(0))
if err != nil {
return err
}
ai.doneRetConverter = conv
ai.active = make(map[int64]reflect.Value)
ai.next = 1
// ai must outlast the database connection, or we'll have dangling pointers.
c.aggregators = append(c.aggregators, &ai)
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
opts := C.SQLITE_UTF8
if pure {
opts |= C.SQLITE_DETERMINISTIC
}
rv := sqlite3CreateFunction(c.db, cname, C.int(stepNArgs), C.int(opts), newHandle(c, &ai), nil, C.stepTrampoline, C.doneTrampoline)
if rv != C.SQLITE_OK {
return c.lastError()
}
return nil
}
// AutoCommit return which currently auto commit or not.
func (c *SQLiteConn) AutoCommit() bool {
c.mu.Lock()
defer c.mu.Unlock()
return int(C.sqlite3_get_autocommit(c.db)) != 0
}
func (c *SQLiteConn) lastError() error {
return lastError(c.db)
}
func lastError(db *C.sqlite3) error {
rv := C.sqlite3_errcode(db)
if rv == C.SQLITE_OK {
return nil
}
return Error{
Code: ErrNo(rv),
ExtendedCode: ErrNoExtended(C.sqlite3_extended_errcode(db)),
err: C.GoString(C.sqlite3_errmsg(db)),
}
}
// Exec implements Execer.
func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) {
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return c.exec(context.Background(), query, list)
}
func (c *SQLiteConn) exec(ctx context.Context, query string, args []namedValue) (driver.Result, error) {
start := 0
for {
s, err := c.prepare(ctx, query)
if err != nil {
return nil, err
}
var res driver.Result
if s.(*SQLiteStmt).s != nil {
na := s.NumInput()
if len(args) < na {
s.Close()
return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
}
for i := 0; i < na; i++ {
args[i].Ordinal -= start
}
res, err = s.(*SQLiteStmt).exec(ctx, args[:na])
if err != nil && err != driver.ErrSkip {
s.Close()
return nil, err
}
args = args[na:]
start += na
}
tail := s.(*SQLiteStmt).t
s.Close()
if tail == "" {
return res, nil
}
query = tail
}
}
type namedValue struct {
Name string
Ordinal int
Value driver.Value
}
// Query implements Queryer.
func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) {
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return c.query(context.Background(), query, list)
}
func (c *SQLiteConn) query(ctx context.Context, query string, args []namedValue) (driver.Rows, error) {
start := 0
for {
s, err := c.prepare(ctx, query)
if err != nil {
return nil, err
}
s.(*SQLiteStmt).cls = true
na := s.NumInput()
if len(args) < na {
return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
}
for i := 0; i < na; i++ {
args[i].Ordinal -= start
}
rows, err := s.(*SQLiteStmt).query(ctx, args[:na])
if err != nil && err != driver.ErrSkip {
s.Close()
return rows, err
}
args = args[na:]
start += na
tail := s.(*SQLiteStmt).t
if tail == "" {
return rows, nil
}
rows.Close()
s.Close()
query = tail
}
}
// Begin transaction.
func (c *SQLiteConn) Begin() (driver.Tx, error) {
return c.begin(context.Background())
}
func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) {
if _, err := c.exec(ctx, c.txlock, nil); err != nil {
return nil, err
}
return &SQLiteTx{c}, nil
}
func errorString(err Error) string {
return C.GoString(C.sqlite3_errstr(C.int(err.Code)))
}
// Open database and return a new connection.
//
// A pragma can take either zero or one argument.
// The argument is may be either in parentheses or it may be separated from
// the pragma name by an equal sign. The two syntaxes yield identical results.
// In many pragmas, the argument is a boolean. The boolean can be one of:
// 1 yes true on
// 0 no false off
//
// You can specify a DSN string using a URI as the filename.
// test.db
// file:test.db?cache=shared&mode=memory
// :memory:
// file::memory:
//
// mode
// Access mode of the database.
// https://www.sqlite.org/c3ref/open.html
// Values:
// - ro
// - rw
// - rwc
// - memory
//
// shared
// SQLite Shared-Cache Mode
// https://www.sqlite.org/sharedcache.html
// Values:
// - shared
// - private
//
// immutable=Boolean
// The immutable parameter is a boolean query parameter that indicates
// that the database file is stored on read-only media. When immutable is set,
// SQLite assumes that the database file cannot be changed,
// even by a process with higher privilege,
// and so the database is opened read-only and all locking and change detection is disabled.
// Caution: Setting the immutable property on a database file that
// does in fact change can result in incorrect query results and/or SQLITE_CORRUPT errors.
//
// go-sqlite3 adds the following query parameters to those used by SQLite:
// _loc=XXX
// Specify location of time format. It's possible to specify "auto".
//
// _mutex=XXX
// Specify mutex mode. XXX can be "no", "full".
//
// _txlock=XXX
// Specify locking behavior for transactions. XXX can be "immediate",
// "deferred", "exclusive".
//
// _auto_vacuum=X | _vacuum=X
// 0 | none - Auto Vacuum disabled
// 1 | full - Auto Vacuum FULL
// 2 | incremental - Auto Vacuum Incremental
//
// _busy_timeout=XXX"| _timeout=XXX
// Specify value for sqlite3_busy_timeout.
//
// _case_sensitive_like=Boolean | _cslike=Boolean
// https://www.sqlite.org/pragma.html#pragma_case_sensitive_like
// Default or disabled the LIKE operation is case-insensitive.
// When enabling this options behaviour of LIKE will become case-sensitive.
//
// _defer_foreign_keys=Boolean | _defer_fk=Boolean
// Defer Foreign Keys until outermost transaction is committed.
//
// _foreign_keys=Boolean | _fk=Boolean
// Enable or disable enforcement of foreign keys.
//
// _ignore_check_constraints=Boolean
// This pragma enables or disables the enforcement of CHECK constraints.
// The default setting is off, meaning that CHECK constraints are enforced by default.
//
// _journal_mode=MODE | _journal=MODE
// Set journal mode for the databases associated with the current connection.
// https://www.sqlite.org/pragma.html#pragma_journal_mode
//
// _locking_mode=X | _locking=X
// Sets the database connection locking-mode.
// The locking-mode is either NORMAL or EXCLUSIVE.
// https://www.sqlite.org/pragma.html#pragma_locking_mode
//
// _query_only=Boolean
// The query_only pragma prevents all changes to database files when enabled.
//
// _recursive_triggers=Boolean | _rt=Boolean
// Enable or disable recursive triggers.
//
// _secure_delete=Boolean|FAST
// When secure_delete is on, SQLite overwrites deleted content with zeros.
// https://www.sqlite.org/pragma.html#pragma_secure_delete
//
// _synchronous=X | _sync=X
// Change the setting of the "synchronous" flag.
// https://www.sqlite.org/pragma.html#pragma_synchronous
//
// _writable_schema=Boolean
// When this pragma is on, the SQLITE_MASTER tables in which database
// can be changed using ordinary UPDATE, INSERT, and DELETE statements.
// Warning: misuse of this pragma can easily result in a corrupt database file.
//
//
func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
if C.sqlite3_threadsafe() == 0 {
return nil, errors.New("sqlite library was not compiled for thread-safe operation")
}
var pkey string
// Options
var loc *time.Location
authCreate := false
authUser := ""
authPass := ""
authCrypt := ""
authSalt := ""
mutex := C.int(C.SQLITE_OPEN_FULLMUTEX)
txlock := "BEGIN"
// PRAGMA's
autoVacuum := -1
busyTimeout := 5000
caseSensitiveLike := -1
deferForeignKeys := -1
foreignKeys := -1
ignoreCheckConstraints := -1
journalMode := "DELETE"
lockingMode := "NORMAL"
queryOnly := -1
recursiveTriggers := -1
secureDelete := "DEFAULT"
synchronousMode := "NORMAL"
writableSchema := -1
pos := strings.IndexRune(dsn, '?')
if pos >= 1 {
params, err := url.ParseQuery(dsn[pos+1:])
if err != nil {
return nil, err
}
// Authentication
if _, ok := params["_auth"]; ok {
authCreate = true
}
if val := params.Get("_auth_user"); val != "" {
authUser = val
}
if val := params.Get("_auth_pass"); val != "" {
authPass = val
}
if val := params.Get("_auth_crypt"); val != "" {
authCrypt = val
}
if val := params.Get("_auth_salt"); val != "" {
authSalt = val
}
// _loc
if val := params.Get("_loc"); val != "" {
switch strings.ToLower(val) {
case "auto":
loc = time.Local
default:
loc, err = time.LoadLocation(val)
if err != nil {
return nil, fmt.Errorf("Invalid _loc: %v: %v", val, err)
}
}
}
// _mutex
if val := params.Get("_mutex"); val != "" {
switch strings.ToLower(val) {
case "no":
mutex = C.SQLITE_OPEN_NOMUTEX
case "full":
mutex = C.SQLITE_OPEN_FULLMUTEX
default:
return nil, fmt.Errorf("Invalid _mutex: %v", val)
}
}
// _txlock
if val := params.Get("_txlock"); val != "" {
switch strings.ToLower(val) {
case "immediate":
txlock = "BEGIN IMMEDIATE"
case "exclusive":
txlock = "BEGIN EXCLUSIVE"
case "deferred":
txlock = "BEGIN"
default:
return nil, fmt.Errorf("Invalid _txlock: %v", val)
}
}
// Auto Vacuum (_vacuum)
//
// https://www.sqlite.org/pragma.html#pragma_auto_vacuum
//
pkey = "" // Reset pkey
if _, ok := params["_auto_vacuum"]; ok {
pkey = "_auto_vacuum"
}
if _, ok := params["_vacuum"]; ok {
pkey = "_vacuum"
}
if val := params.Get(pkey); val != "" {
switch strings.ToLower(val) {
case "0", "none":
autoVacuum = 0
case "1", "full":
autoVacuum = 1
case "2", "incremental":
autoVacuum = 2
default:
return nil, fmt.Errorf("Invalid _auto_vacuum: %v, expecting value of '0 NONE 1 FULL 2 INCREMENTAL'", val)
}
}
// Busy Timeout (_busy_timeout)
//
// https://www.sqlite.org/pragma.html#pragma_busy_timeout
//
pkey = "" // Reset pkey
if _, ok := params["_busy_timeout"]; ok {
pkey = "_busy_timeout"
}
if _, ok := params["_timeout"]; ok {
pkey = "_timeout"
}
if val := params.Get(pkey); val != "" {
iv, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return nil, fmt.Errorf("Invalid _busy_timeout: %v: %v", val, err)
}
busyTimeout = int(iv)
}
// Case Sensitive Like (_cslike)
//
// https://www.sqlite.org/pragma.html#pragma_case_sensitive_like
//
pkey = "" // Reset pkey
if _, ok := params["_case_sensitive_like"]; ok {
pkey = "_case_sensitive_like"
}
if _, ok := params["_cslike"]; ok {
pkey = "_cslike"
}
if val := params.Get(pkey); val != "" {
switch strings.ToLower(val) {
case "0", "no", "false", "off":
caseSensitiveLike = 0
case "1", "yes", "true", "on":
caseSensitiveLike = 1
default:
return nil, fmt.Errorf("Invalid _case_sensitive_like: %v, expecting boolean value of '0 1 false true no yes off on'", val)
}
}
// Defer Foreign Keys (_defer_foreign_keys | _defer_fk)
//
// https://www.sqlite.org/pragma.html#pragma_defer_foreign_keys
//
pkey = "" // Reset pkey
if _, ok := params["_defer_foreign_keys"]; ok {
pkey = "_defer_foreign_keys"
}
if _, ok := params["_defer_fk"]; ok {
pkey = "_defer_fk"
}
if val := params.Get(pkey); val != "" {
switch strings.ToLower(val) {
case "0", "no", "false", "off":
deferForeignKeys = 0
case "1", "yes", "true", "on":
deferForeignKeys = 1
default:
return nil, fmt.Errorf("Invalid _defer_foreign_keys: %v, expecting boolean value of '0 1 false true no yes off on'", val)
}
}
// Foreign Keys (_foreign_keys | _fk)
//
// https://www.sqlite.org/pragma.html#pragma_foreign_keys
//
pkey = "" // Reset pkey
if _, ok := params["_foreign_keys"]; ok {
pkey = "_foreign_keys"
}
if _, ok := params["_fk"]; ok {
pkey = "_fk"
}
if val := params.Get(pkey); val != "" {
switch strings.ToLower(val) {
case "0", "no", "false", "off":
foreignKeys = 0
case "1", "yes", "true", "on":
foreignKeys = 1
default:
return nil, fmt.Errorf("Invalid _foreign_keys: %v, expecting boolean value of '0 1 false true no yes off on'", val)
}
}
// Ignore CHECK Constrains (_ignore_check_constraints)
//
// https://www.sqlite.org/pragma.html#pragma_ignore_check_constraints
//
if val := params.Get("_ignore_check_constraints"); val != "" {
switch strings.ToLower(val) {
case "0", "no", "false", "off":
ignoreCheckConstraints = 0
case "1", "yes", "true", "on":
ignoreCheckConstraints = 1
default:
return nil, fmt.Errorf("Invalid _ignore_check_constraints: %v, expecting boolean value of '0 1 false true no yes off on'", val)
}
}
// Journal Mode (_journal_mode | _journal)
//
// https://www.sqlite.org/pragma.html#pragma_journal_mode
//
pkey = "" // Reset pkey
if _, ok := params["_journal_mode"]; ok {
pkey = "_journal_mode"
}
if _, ok := params["_journal"]; ok {
pkey = "_journal"
}
if val := params.Get(pkey); val != "" {
switch strings.ToUpper(val) {
case "DELETE", "TRUNCATE", "PERSIST", "MEMORY", "OFF":
journalMode = strings.ToUpper(val)
case "WAL":
journalMode = strings.ToUpper(val)
// For WAL Mode set Synchronous Mode to 'NORMAL'
// See https://www.sqlite.org/pragma.html#pragma_synchronous
synchronousMode = "NORMAL"
default:
return nil, fmt.Errorf("Invalid _journal: %v, expecting value of 'DELETE TRUNCATE PERSIST MEMORY WAL OFF'", val)
}
}
// Locking Mode (_locking)
//
// https://www.sqlite.org/pragma.html#pragma_locking_mode
//
pkey = "" // Reset pkey
if _, ok := params["_locking_mode"]; ok {
pkey = "_locking_mode"
}
if _, ok := params["_locking"]; ok {
pkey = "_locking"
}
if val := params.Get("_locking"); val != "" {
switch strings.ToUpper(val) {
case "NORMAL", "EXCLUSIVE":
lockingMode = strings.ToUpper(val)
default:
return nil, fmt.Errorf("Invalid _locking_mode: %v, expecting value of 'NORMAL EXCLUSIVE", val)
}
}
// Query Only (_query_only)
//
// https://www.sqlite.org/pragma.html#pragma_query_only
//
if val := params.Get("_query_only"); val != "" {
switch strings.ToLower(val) {
case "0", "no", "false", "off":
queryOnly = 0
case "1", "yes", "true", "on":
queryOnly = 1
default:
return nil, fmt.Errorf("Invalid _query_only: %v, expecting boolean value of '0 1 false true no yes off on'", val)
}
}
// Recursive Triggers (_recursive_triggers)
//
// https://www.sqlite.org/pragma.html#pragma_recursive_triggers
//
pkey = "" // Reset pkey
if _, ok := params["_recursive_triggers"]; ok {
pkey = "_recursive_triggers"
}
if _, ok := params["_rt"]; ok {
pkey = "_rt"
}
if val := params.Get(pkey); val != "" {
switch strings.ToLower(val) {
case "0", "no", "false", "off":
recursiveTriggers = 0
case "1", "yes", "true", "on":
recursiveTriggers = 1
default:
return nil, fmt.Errorf("Invalid _recursive_triggers: %v, expecting boolean value of '0 1 false true no yes off on'", val)
}
}
// Secure Delete (_secure_delete)
//
// https://www.sqlite.org/pragma.html#pragma_secure_delete
//
if val := params.Get("_secure_delete"); val != "" {
switch strings.ToLower(val) {
case "0", "no", "false", "off":
secureDelete = "OFF"
case "1", "yes", "true", "on":
secureDelete = "ON"
case "fast":
secureDelete = "FAST"
default:
return nil, fmt.Errorf("Invalid _secure_delete: %v, expecting boolean value of '0 1 false true no yes off on fast'", val)
}
}
// Synchronous Mode (_synchronous | _sync)
//
// https://www.sqlite.org/pragma.html#pragma_synchronous | //
pkey = "" // Reset pkey
if _, ok := params["_synchronous"]; ok {
pkey = "_synchronous"
}
if _, ok := params["_sync"]; ok {
pkey = "_sync"
}
if val := params.Get(pkey); val != "" {
switch strings.ToUpper(val) {
case "0", "OFF", "1", "NORMAL", "2", "FULL", "3", "EXTRA":
synchronousMode = strings.ToUpper(val)
default:
return nil, fmt.Errorf("Invalid _synchronous: %v, expecting value of '0 OFF 1 NORMAL 2 FULL 3 EXTRA'", val)
}
}
// Writable Schema (_writeable_schema)
//
// https://www.sqlite.org/pragma.html#pragma_writeable_schema
//
if val := params.Get("_writable_schema"); val != "" {
switch strings.ToLower(val) {
case "0", "no", "false", "off":
writableSchema = 0
case "1", "yes", "true", "on":
writableSchema = 1
default:
return nil, fmt.Errorf("Invalid _writable_schema: %v, expecting boolean value of '0 1 false true no yes off on'", val)
}
}
if !strings.HasPrefix(dsn, "file:") {
dsn = dsn[:pos]
}
}
var db *C.sqlite3
name := C.CString(dsn)
defer C.free(unsafe.Pointer(name))
rv := C._sqlite3_open_v2(name, &db,
mutex|C.SQLITE_OPEN_READWRITE|C.SQLITE_OPEN_CREATE,
nil)
if rv != 0 {
if db != nil {
C.sqlite3_close_v2(db)
}
return nil, Error{Code: ErrNo(rv)}
}
if db == nil {
return nil, errors.New("sqlite succeeded without returning a database")
}
rv = C.sqlite3_busy_timeout(db, C.int(busyTimeout))
if rv != C.SQLITE_OK {
C.sqlite3_close_v2(db)
return nil, Error{Code: ErrNo(rv)}
}
exec := func(s string) error {
cs := C.CString(s)
rv := C.sqlite3_exec(db, cs, nil, nil, nil)
C.free(unsafe.Pointer(cs))
if rv != C.SQLITE_OK {
return lastError(db)
}
return nil
}
// USER AUTHENTICATION
//
// User Authentication is always performed even when
// sqlite_userauth is not compiled in, because without user authentication
// the authentication is a no-op.
//
// Workflow
// - Authenticate
// ON::SUCCESS => Continue
// ON::SQLITE_AUTH => Return error and exit Open(...)
//
// - Activate User Authentication
// Check if the user wants to activate User Authentication.
// If so then first create a temporary AuthConn to the database
// This is possible because we are already successfully authenticated.
//
// - Check if `sqlite_user`` table exists
// YES => Add the provided user from DSN as Admin User and
// activate user authentication.
// NO => Continue
//
// Create connection to SQLite
conn := &SQLiteConn{db: db, loc: loc, txlock: txlock}
// Password Cipher has to be registered before authentication
if len(authCrypt) > 0 {
switch strings.ToUpper(authCrypt) {
case "SHA1":
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA1, true); err != nil {
return nil, fmt.Errorf("CryptEncoderSHA1: %s", err)
}
case "SSHA1":
if len(authSalt) == 0 {
return nil, fmt.Errorf("_auth_crypt=ssha1, requires _auth_salt")
}
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA1(authSalt), true); err != nil {
return nil, fmt.Errorf("CryptEncoderSSHA1: %s", err)
}
case "SHA256":
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA256, true); err != nil {
return nil, fmt.Errorf("CryptEncoderSHA256: %s", err)
}
case "SSHA256":
if len(authSalt) == 0 {
return nil, fmt.Errorf("_auth_crypt=ssha256, requires _auth_salt")
}
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA256(authSalt), true); err != nil {
return nil, fmt.Errorf("CryptEncoderSSHA256: %s", err)
}
case "SHA384":
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA384, true); err != nil {
return nil, fmt.Errorf("CryptEncoderSHA384: %s", err)
}
case "SSHA384":
if len(authSalt) == 0 {
return nil, fmt.Errorf("_auth_crypt=ssha384, requires _auth_salt")
}
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA384(authSalt), true); err != nil {
return nil, fmt.Errorf("CryptEncoderSSHA384: %s", err)
}
case "SHA512":
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA512, true); err != nil {
return nil, fmt.Errorf("CryptEncoderSHA512: %s", err)
}
case "SSHA512":
if len(authSalt) == 0 {
return nil, fmt.Errorf("_auth_crypt=ssha512, requires _auth_salt")
}
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA512(authSalt), true); err != nil {
return nil, fmt.Errorf("CryptEncoderSSHA512: %s", err)
}
}
}
// Preform Authentication
if err := conn.Authenticate(authUser, authPass); err != nil {
return nil, err
}
// Register: authenticate
// Authenticate will perform an authentication of the provided username
// and password against the database.
//
// If a database contains the SQLITE_USER table, then the
// call to Authenticate must be invoked with an
// appropriate username and password prior to enable read and write
//access to the database.
//
// Return SQLITE_OK on success or SQLITE_ERROR if the username/password
// combination is incorrect or unknown.
//
// If the SQLITE_USER table is not present in the database file, then
// this interface is a harmless no-op returnning SQLITE_OK.
if err := conn.RegisterFunc("authenticate", conn.authenticate, true); err != nil {
return nil, err
}
//
// Register: auth_user_add
// auth_user_add can be used (by an admin user only)
// to create a new user. When called on a no-authentication-required
// database, this routine converts the database into an authentication-
// required database, automatically makes the added user an
// administrator, and logs in the current connection as that user.
// The AuthUserAdd only works for the "main" database, not
// for any ATTACH-ed databases. Any call to AuthUserAdd by a
// non-admin user results in an error.
if err := conn.RegisterFunc("auth_user_add", conn.authUserAdd, true); err != nil {
return nil, err
}
//
// Register: auth_user_change
// auth_user_change can be used to change a users
// login credentials or admin privilege. Any user can change their own
// login credentials. Only an admin user can change another users login
// credentials or admin privilege setting. No user may change their own
// admin privilege setting.
if err := conn.RegisterFunc("auth_user_change", conn.authUserChange, true); err != nil {
return nil, err
}
//
// Register: auth_user_delete
// auth_user_delete can be used (by an admin user only)
// to delete a user. The currently logged-in user cannot be deleted,
// which guarantees that there is always an admin user and hence that
// the database cannot be converted into a no-authentication-required
// database.
if err := conn.RegisterFunc("auth_user_delete", conn.authUserDelete, true); err != nil {
return nil, err
}
// Register: auth_enabled
// auth_enabled can be used to check if user authentication is enabled
if err := conn.RegisterFunc("auth_enabled", conn.authEnabled, true); err != nil {
return nil, err
}
// Auto Vacuum
// Moved auto_vacuum command, the user preference for auto_vacuum needs to be implemented directly after
// the authentication and before the sqlite_user table gets created if the user
// decides to activate User Authentication because
// auto_vacuum needs to be set before any tables are created
// and activating user authentication creates the internal table `sqlite_user`.
if autoVacuum > -1 {
if err := exec(fmt.Sprintf("PRAGMA auto_vacuum = %d;", autoVacuum)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
}
// Check if user wants to activate User Authentication
if authCreate {
// Before going any further, we need to check that the user
// has provided an username and password within the DSN.
// We are not allowed to continue.
if len(authUser) < 0 {
return nil, fmt.Errorf("Missing '_auth_user' while user authentication was requested with '_auth'")
}
if len(authPass) < 0 {
return nil, fmt.Errorf("Missing '_auth_pass' while user authentication was requested with '_auth'")
}
// Check if User Authentication is Enabled
authExists := conn.AuthEnabled()
if !authExists {
if err := conn.AuthUserAdd(authUser, authPass, true); err != nil {
return nil, err
}
}
}
// Case Sensitive LIKE
if caseSensitiveLike > -1 {
if err := exec(fmt.Sprintf("PRAGMA case_sensitive_like = %d;", caseSensitiveLike)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
}
// Defer Foreign Keys
if deferForeignKeys > -1 {
if err := exec(fmt.Sprintf("PRAGMA defer_foreign_keys = %d;", deferForeignKeys)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
}
// Forgein Keys
if foreignKeys > -1 {
if err := exec(fmt.Sprintf("PRAGMA foreign_keys = %d;", foreignKeys)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
}
// Ignore CHECK Constraints
if ignoreCheckConstraints > -1 {
if err := exec(fmt.Sprintf("PRAGMA ignore_check_constraints = %d;", ignoreCheckConstraints)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
}
// Journal Mode
// Because default Journal Mode is DELETE this PRAGMA can always be executed.
if err := exec(fmt.Sprintf("PRAGMA journal_mode = %s;", journalMode)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
// Locking Mode
// Because the default is NORMAL and this is not changed in this package
// by using the compile time SQLITE_DEFAULT_LOCKING_MODE this PRAGMA can always be executed
if err := exec(fmt.Sprintf("PRAGMA locking_mode = %s;", lockingMode)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
// Query Only
if queryOnly > -1 {
if err := exec(fmt.Sprintf("PRAGMA query_only = %d;", queryOnly)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
}
// Recursive Triggers
if recursiveTriggers > -1 {
if err := exec(fmt.Sprintf("PRAGMA recursive_triggers = %d;", recursiveTriggers)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
}
// Secure Delete
//
// Because this package can set the compile time flag SQLITE_SECURE_DELETE with a build tag
// the default value for secureDelete var is 'DEFAULT' this way
// you can compile with secure_delete 'ON' and disable it for a specific database connection.
if secureDelete != "DEFAULT" {
if err := exec(fmt.Sprintf("PRAGMA secure_delete = %s;", secureDelete)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
}
// Synchronous Mode
//
// Because default is NORMAL this statement is always executed
if err := exec(fmt.Sprintf("PRAGMA synchronous = %s;", synchronousMode)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
// Writable Schema
if writableSchema > -1 {
if err := exec(fmt.Sprintf("PRAGMA writable_schema = %d;", writableSchema)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
}
}
if len(d.Extensions) > 0 {
if err := conn.loadExtensions(d.Extensions); err != nil {
conn.Close()
return nil, err
}
}
if d.ConnectHook != nil {
if err := d.ConnectHook(conn); err != nil {
conn.Close()
return nil, err
}
}
runtime.SetFinalizer(conn, (*SQLiteConn).Close)
return conn, nil
}
// Close the connection.
func (c *SQLiteConn) Close() error {
rv := C.sqlite3_close_v2(c.db)
if rv != C.SQLITE_OK {
return c.lastError()
}
deleteHandles(c)
c.mu.Lock()
c.db = nil
c.mu.Unlock()
runtime.SetFinalizer(c, nil)
return nil
}
func (c *SQLiteConn) dbConnOpen() bool {
if c == nil {
return false
}
c.mu.Lock()
defer c.mu.Unlock()
return c.db != nil
}
// Prepare the query string. Return a new statement.
func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
return c.prepare(context.Background(), query)
}
func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, error) {
pquery := C.CString(query)
defer C.free(unsafe.Pointer(pquery))
var s *C.sqlite3_stmt
var tail *C.char
rv := C._sqlite3_prepare_v2_internal(c.db, pquery, C.int(-1), &s, &tail)
if rv != C.SQLITE_OK {
return nil, c.lastError()
}
var t string
if tail != nil && *tail != '\000' {
t = strings.TrimSpace(C.GoString(tail))
}
ss := &SQLiteStmt{c: c, s: s, t: t}
runtime.SetFinalizer(ss, (*SQLiteStmt).Close)
return ss, nil
}
// Run-Time Limit Categories.
// See: http://www.sqlite.org/c3ref/c_limit_attached.html
const (
SQLITE_LIMIT_LENGTH = C.SQLITE_LIMIT_LENGTH
SQLITE_LIMIT_SQL_LENGTH = C.SQLITE_LIMIT_SQL_LENGTH
SQLITE_LIMIT_COLUMN = C.SQLITE_LIMIT_COLUMN
SQLITE_LIMIT_EXPR_DEPTH = C.SQLITE_LIMIT_EXPR_DEPTH
SQLITE_LIMIT_COMPOUND_SELECT = C.SQLITE_LIMIT_COMPOUND_SELECT
SQLITE_LIMIT_VDBE_OP = C.SQLITE_LIMIT_VDBE_OP
SQLITE_LIMIT_FUNCTION_ARG = C.SQLITE_LIMIT_FUNCTION_ARG
SQLITE_LIMIT_ATTACHED = C.SQLITE_LIMIT_ATTACHED
SQLITE_LIMIT_LIKE_PATTERN_LENGTH = C.SQLITE_LIMIT_LIKE_PATTERN_LENGTH
SQLITE_LIMIT_VARIABLE_NUMBER = C.SQLITE_LIMIT_VARIABLE_NUMBER
SQLITE_LIMIT_TRIGGER_DEPTH = C.SQLITE_LIMIT_TRIGGER_DEPTH
SQLITE_LIMIT_WORKER_THREADS = C.SQLITE_LIMIT_WORKER_THREADS
)
// GetFilename returns the absolute path to the file containing
// the requested schema. When passed an empty string, it will
// instead use the database's default schema: "main".
// See: sqlite3_db_filename, https://www.sqlite.org/c3ref/db_filename.html
func (c *SQLiteConn) GetFilename(schemaName string) string {
if schemaName == "" {
schemaName = "main"
}
return C.GoString(C.sqlite3_db_filename(c.db, C.CString(schemaName)))
}
// GetLimit returns the current value of a run-time limit.
// See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
func (c *SQLiteConn) GetLimit(id int) int {
return int(C._sqlite3_limit(c.db, C.int(id), C.int(-1)))
}
// SetLimit changes the value of a run-time limits.
// Then this method returns the prior value of the limit.
// See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
func (c *SQLiteConn) SetLimit(id int, newVal int) int {
return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal)))
}
// Close the statement.
func (s *SQLiteStmt) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil
}
s.closed = true
if !s.c.dbConnOpen() {
return errors.New("sqlite statement with already closed database connection")
}
rv := C.sqlite3_finalize(s.s)
s.s = nil
if rv != C.SQLITE_OK {
return s.c.lastError()
}
runtime.SetFinalizer(s, nil)
return nil
}
// NumInput return a number of parameters.
func (s *SQLiteStmt) NumInput() int {
return int(C.sqlite3_bind_parameter_count(s.s))
}
type bindArg struct {
n int
v driver.Value
}
var placeHolder = []byte{0}
func (s *SQLiteStmt) bind(args []namedValue) error {
rv := C.sqlite3_reset(s.s)
if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
return s.c.lastError()
}
for i, v := range args {
if v.Name != "" {
cname := C.CString(":" + v.Name)
args[i].Ordinal = int(C.sqlite3_bind_parameter_index(s.s, cname))
C.free(unsafe.Pointer(cname))
}
}
for _, arg := range args {
n := C.int(arg.Ordinal)
switch v := arg.Value.(type) {
case nil:
rv = C.sqlite3_bind_null(s.s, n)
case string:
if len(v) == 0 {
rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.int(0))
} else {
b := []byte(v)
rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
}
case int64:
rv = C.sqlite3_bind_int64(s.s, n, C.sqlite3_int64(v))
case bool:
if v {
rv = C.sqlite3_bind_int(s.s, n, 1)
} else {
rv = C.sqlite3_bind_int(s.s, n, 0)
}
case float64:
rv = C.sqlite3_bind_double(s.s, n, C.double(v))
case []byte:
if v == nil {
rv = C.sqlite3_bind_null(s.s, n)
} else {
ln := len(v)
if ln == 0 {
v = placeHolder
}
rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(ln))
}
case time.Time:
b := []byte(v.Format(SQLiteTimestampFormats[0]))
rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
}
if rv != C.SQLITE_OK {
return s.c.lastError()
}
}
return nil
}
// Query the statement with arguments. Return records.
func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) {
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return s.query(context.Background(), list)
}
func (s *SQLiteStmt) query(ctx context.Context, args []namedValue) (driver.Rows, error) {
if err := s.bind(args); err != nil {
return nil, err
}
rows := &SQLiteRows{
s: s,
nc: int(C.sqlite3_column_count(s.s)),
cols: nil,
decltype: nil,
cls: s.cls,
closed: false,
done: make(chan struct{}),
}
if ctxdone := ctx.Done(); ctxdone != nil {
go func(db *C.sqlite3) {
select {
case <-ctxdone:
select {
case <-rows.done:
default:
C.sqlite3_interrupt(db)
rows.Close()
}
case <-rows.done:
}
}(s.c.db)
}
return rows, nil
}
// LastInsertId teturn last inserted ID.
func (r *SQLiteResult) LastInsertId() (int64, error) {
return r.id, nil
}
// RowsAffected return how many rows affected.
func (r *SQLiteResult) RowsAffected() (int64, error) {
return r.changes, nil
}
// Exec execute the statement with arguments. Return result object.
func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) {
list := make([]namedValue, len(args))
for i, v := range args {
list[i] = namedValue{
Ordinal: i + 1,
Value: v,
}
}
return s.exec(context.Background(), list)
}
func (s *SQLiteStmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) {
if err := s.bind(args); err != nil {
C.sqlite3_reset(s.s)
C.sqlite3_clear_bindings(s.s)
return nil, err
}
if ctxdone := ctx.Done(); ctxdone != nil {
done := make(chan struct{})
defer close(done)
go func(db *C.sqlite3) {
select {
case <-done:
case <-ctxdone:
select {
case <-done:
default:
C.sqlite3_interrupt(db)
}
}
}(s.c.db)
}
var rowid, changes C.longlong
rv := C._sqlite3_step_row_internal(s.s, &rowid, &changes)
if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
err := s.c.lastError()
C.sqlite3_reset(s.s)
C.sqlite3_clear_bindings(s.s)
return nil, err
}
return &SQLiteResult{id: int64(rowid), changes: int64(changes)}, nil
}
// Close the rows.
func (rc *SQLiteRows) Close() error {
rc.s.mu.Lock()
if rc.s.closed || rc.closed {
rc.s.mu.Unlock()
return nil
}
rc.closed = true
if rc.done != nil {
close(rc.done)
}
if rc.cls {
rc.s.mu.Unlock()
return rc.s.Close()
}
rv := C.sqlite3_reset(rc.s.s)
if rv != C.SQLITE_OK {
rc.s.mu.Unlock()
return rc.s.c.lastError()
}
rc.s.mu.Unlock()
return nil
}
// Columns return column names.
func (rc *SQLiteRows) Columns() []string {
rc.s.mu.Lock()
defer rc.s.mu.Unlock()
if rc.s.s != nil && rc.nc != len(rc.cols) {
rc.cols = make([]string, rc.nc)
for i := 0; i < rc.nc; i++ {
rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i)))
}
}
return rc.cols
}
func (rc *SQLiteRows) declTypes() []string {
if rc.s.s != nil && rc.decltype == nil {
rc.decltype = make([]string, rc.nc)
for i := 0; i < rc.nc; i++ {
rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))))
}
}
return rc.decltype
}
// DeclTypes return column types.
func (rc *SQLiteRows) DeclTypes() []string {
rc.s.mu.Lock()
defer rc.s.mu.Unlock()
return rc.declTypes()
}
// Next move cursor to next.
func (rc *SQLiteRows) Next(dest []driver.Value) error {
rc.s.mu.Lock()
defer rc.s.mu.Unlock()
if rc.s.closed {
return io.EOF
}
rv := C._sqlite3_step_internal(rc.s.s)
if rv == C.SQLITE_DONE {
return io.EOF
}
if rv != C.SQLITE_ROW {
rv = C.sqlite3_reset(rc.s.s)
if rv != C.SQLITE_OK {
return rc.s.c.lastError()
}
return nil
}
rc.declTypes()
for i := range dest {
switch C.sqlite3_column_type(rc.s.s, C.int(i)) {
case C.SQLITE_INTEGER:
val := int64(C.sqlite3_column_int64(rc.s.s, C.int(i)))
switch rc.decltype[i] {
case columnTimestamp, columnDatetime, columnDate:
var t time.Time
// Assume a millisecond unix timestamp if it's 13 digits -- too
// large to be a reasonable timestamp in seconds.
if val > 1e12 || val < -1e12 {
val *= int64(time.Millisecond) // convert ms to nsec
t = time.Unix(0, val)
} else {
t = time.Unix(val, 0)
}
t = t.UTC()
if rc.s.c.loc != nil {
t = t.In(rc.s.c.loc)
}
dest[i] = t
case "boolean":
dest[i] = val > 0
default:
dest[i] = val
}
case C.SQLITE_FLOAT:
dest[i] = float64(C.sqlite3_column_double(rc.s.s, C.int(i)))
case C.SQLITE_BLOB:
p := C.sqlite3_column_blob(rc.s.s, C.int(i))
if p == nil {
dest[i] = []byte{}
continue
}
n := C.sqlite3_column_bytes(rc.s.s, C.int(i))
dest[i] = C.GoBytes(p, n)
case C.SQLITE_NULL:
dest[i] = nil
case C.SQLITE_TEXT:
var err error
var timeVal time.Time
n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))
s := C.GoStringN((*C.char)(unsafe.Pointer(C.sqlite3_column_text(rc.s.s, C.int(i)))), C.int(n))
switch rc.decltype[i] {
case columnTimestamp, columnDatetime, columnDate:
var t time.Time
s = strings.TrimSuffix(s, "Z")
for _, format := range SQLiteTimestampFormats {
if timeVal, err = time.ParseInLocation(format, s, time.UTC); err == nil {
t = timeVal
break
}
}
if err != nil {
// The column is a time value, so return the zero time on parse failure.
t = time.Time{}
}
if rc.s.c.loc != nil {
t = t.In(rc.s.c.loc)
}
dest[i] = t
default:
dest[i] = []byte(s)
}
}
}
return nil
} | |
stack_queue.py | from .node import Node
from .stack import Stack
class Stack_Queue:
def | (self):
self.stack_front = Stack()
self.stack_back = Stack()
self._size = 0
def enqueue(self, val):
"""This will add a node the back of the queue and increment the ._size"""
try:
node = Node(val)
except TypeError:
raise TypeError('Cannot enqueue a value of none')
node._next = self.stack_back.top
self.stack_back.top = node
self._size += 1
return self.stack_back.top
def dequeue(self):
"""remove the node at the front of the queue, decrement the ._size and return the value"""
while self.stack_back.top._next:
self.stack_front.push(self.stack_back.pop())
val = self.stack_back.pop()
while self.stack_front.top._next:
self.stack_back.push(self.stack_front.pop())
self.stack_back.push(self.stack_front.pop())
self._size -= 1
return val
| __init__ |
defer.rs | use crate::prelude::*;
/// Creates an observable that will on subscription defer to another observable
/// that is supplied by a supplier-function which will be run once at each
/// subscription
///
/// ```rust
/// # use rxrust::prelude::*;
///
/// observable::defer(|| {
/// println!("Hi!");
/// observable::of("Hello!")
/// })
/// .subscribe(move |v| {
/// println!("{}", v);
/// });
/// // Prints: Hi!\nHello!\n
/// ```
pub fn defer<F, Item, Err, Emit>(
observable_supplier: F,
) -> ObservableBase<DeferEmitter<F, Item, Err>>
where
F: FnOnce() -> ObservableBase<Emit>,
Emit: Emitter,
{
ObservableBase::new(DeferEmitter(observable_supplier, TypeHint::new()))
}
#[derive(Clone)]
pub struct DeferEmitter<F, Item, Err>(F, TypeHint<(Item, Err)>);
impl<F, Item, Err> Emitter for DeferEmitter<F, Item, Err> {
type Item = Item;
type Err = Err;
}
impl<'a, F, Emit, Item, Err> LocalEmitter<'a> for DeferEmitter<F, Item, Err>
where
F: FnOnce() -> Emit,
Emit: LocalObservable<'a> + observable::Observable<Item = Item, Err = Err>,
{
fn emit<O>(self, subscriber: Subscriber<O, LocalSubscription>)
where
O: Observer<Item = Self::Item, Err = Self::Err> + 'a,
{
(self.0)().actual_subscribe(subscriber);
}
}
impl<F, Item: 'static, Emit, Err: 'static> SharedEmitter
for DeferEmitter<F, Item, Err>
where
F: FnOnce() -> Emit,
Emit: SharedObservable + observable::Observable<Item = Item, Err = Err>,
{
fn emit<O>(self, subscriber: Subscriber<O, SharedSubscription>)
where
O: Observer<Item = Self::Item, Err = Self::Err> + Send + Sync + 'static,
{
(self.0)().actual_subscribe(subscriber);
}
}
#[cfg(test)]
mod test {
use std::ops::Deref;
use std::sync::{Arc, Mutex};
use crate::prelude::*;
use bencher::Bencher;
#[test]
fn no_results_before_deferred_subscribe() {
let calls = Arc::new(Mutex::new(0));
let sum = Arc::new(Mutex::new(0));
let errs = Arc::new(Mutex::new(0));
let completes = Arc::new(Mutex::new(0));
let deferred = observable::defer(|| {
*calls.lock().unwrap() += 1;
observable::of(&2)
})
.into_shared(); |
for i in 1..4 {
let sum_copy = Arc::clone(&sum);
let errs_copy = Arc::clone(&errs);
let completes_copy = Arc::clone(&completes);
deferred.clone().subscribe_all(
move |v| *sum_copy.lock().unwrap() += v,
move |_| *errs_copy.lock().unwrap() += 1,
move || *completes_copy.lock().unwrap() += 1,
);
assert_eq!(*calls.lock().unwrap(), i);
}
assert_eq!(*calls.lock().unwrap().deref(), 3);
assert_eq!(*sum.lock().unwrap().deref(), 6);
assert_eq!(*errs.lock().unwrap().deref(), 0);
assert_eq!(*completes.lock().unwrap().deref(), 3);
}
#[test]
fn support_fork() {
let calls = Arc::new(Mutex::new(0));
let o = observable::defer(|| {
*calls.lock().unwrap() += 1;
observable::of(10)
});
let sum1 = Arc::new(Mutex::new(0));
let sum2 = Arc::new(Mutex::new(0));
let c_sum1 = sum1.clone();
let c_sum2 = sum2.clone();
o.clone().subscribe(move |v| *sum1.lock().unwrap() += v);
o.clone().subscribe(move |v| *sum2.lock().unwrap() += v);
assert_eq!(*c_sum1.lock().unwrap(), 10);
assert_eq!(*c_sum2.lock().unwrap(), 10);
assert_eq!(*calls.lock().unwrap().deref(), 2);
}
#[test]
fn fork_and_share() {
let observable = observable::defer(|| observable::empty());
observable.clone().into_shared().subscribe(|_: i32| {});
observable.clone().into_shared().subscribe(|_| {});
let observable = observable::defer(|| observable::empty()).into_shared();
observable.clone().subscribe(|_: i32| {});
observable.clone().subscribe(|_| {});
}
#[test]
fn bench() { do_bench(); }
benchmark_group!(do_bench, bench_deref);
fn bench_deref(b: &mut Bencher) {
b.iter(no_results_before_deferred_subscribe);
}
} |
assert_eq!(calls.lock().unwrap().deref(), &0); |
security_group_ingress_prop.py | from ipaddress import IPv4Network, IPv6Network
from typing import Optional
from pydantic import validator
from pycfmodel.constants import IPV4_ZERO_VALUE, IPV6_ZERO_VALUE
from pycfmodel.model.resources.properties.property import Property
from pycfmodel.model.types import (
ResolvableInt,
ResolvableIntOrStr,
ResolvableIPv4Network,
ResolvableIPv6Network,
ResolvableStr,
)
class SecurityGroupIngressProp(Property):
"""
An inbound rule permits instances to receive traffic from the specified IPv4 or IPv6 CIDR address range, or from the instances associated with the specified security group.
Properties:
- CidrIp: The IPv4 ranges.
- CidrIpv6: The IPv6 ranges.
- Description: The description of an egress (outbound) security group rule.
- FromPort: The start of port range for the TCP and UDP protocols.
- IpProtocol: The IP protocol name (tcp, udp, icmp, icmpv6) or number ([see Protocol Numbers](http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml)).
- SourcePrefixListId: The prefix list IDs for an AWS service.
- SourceSecurityGroupId: The ID of the security group.
- SourceSecurityGroupName: The name of the source security group.
- SourceSecurityGroupOwnerId: The AWS account ID for the source security group.
- ToPort: The end of port range for the TCP and UDP protocols.
More info at [AWS Docs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html) |
CidrIp: Optional[ResolvableIPv4Network] = None
CidrIpv6: Optional[ResolvableIPv6Network] = None
Description: Optional[ResolvableStr] = None
FromPort: Optional[ResolvableInt] = None
IpProtocol: ResolvableIntOrStr
SourcePrefixListId: Optional[ResolvableStr] = None
SourceSecurityGroupId: Optional[ResolvableStr] = None
SourceSecurityGroupName: Optional[ResolvableStr] = None
SourceSecurityGroupOwnerId: Optional[ResolvableStr] = None
ToPort: Optional[ResolvableInt] = None
@validator("CidrIp", pre=True)
def set_CidrIp(cls, v):
return IPv4Network(v, strict=False)
@validator("CidrIpv6", pre=True)
def set_CidrIpv6(cls, v):
return IPv6Network(v, strict=False)
def ipv4_slash_zero(self) -> bool:
"""Returns True if `CidrIp` matches `0.0.0.0/0`, otherwise False."""
# Remove after this is fixed https://bugs.python.org/issue38655
if not self.CidrIp:
return False
return self.CidrIp == IPv4Network(IPV4_ZERO_VALUE)
def ipv6_slash_zero(self) -> bool:
"""Returns True if `CidrIpv6` matches `::/0`, otherwise False."""
# Remove after this is fixed https://bugs.python.org/issue38655
if not self.CidrIpv6:
return False
return self.CidrIpv6 == IPv6Network(IPV6_ZERO_VALUE) | """ |
request.py | # Certipy - Active Directory certificate abuse
#
# Description:
# Request a new certificate
#
# Authors:
# @ollypwn (https://github.com/ollypwn)
#
# References:
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-icpr/d98e6cfb-87ba-4915-b3ec-a1b7c6129a53
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wcce/d6bee093-d862-4122-8f2b-7b49102097dc
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-icpr/0c6f150e-3ead-4006-b37f-ebbf9e2cf2e7
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-icpr/0c6f150e-3ead-4006-b37f-ebbf9e2cf2e7
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wcce/ea9ef420-4cbf-44bc-b093-c4175139f90f
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-icpr/9f0b251b-c722-4851-9a45-4e912660b458
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wcce/13b7f3f7-c809-4c1e-97fd-52f2ed044c7e
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-icpr/0c6f150e-3ead-4006-b37f-ebbf9e2cf2e
#
import argparse
import logging
from typing import Tuple
from asn1crypto import algos, core, csr, keys, x509
try:
from Cryptodome.Hash import SHA256
from Cryptodome.PublicKey import RSA
from Cryptodome.Signature import PKCS1_v1_5
except ImportError:
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from impacket import hresult_errors, ntlm
from impacket.dcerpc.v5 import transport
from impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, PBYTE, ULONG
from impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT
from impacket.dcerpc.v5.nrpc import checkNullString
from impacket.dcerpc.v5.rpcrt import DCERPCException
from impacket.smbconnection import SMBConnection
from impacket.uuid import string_to_bin
from certipy.pkinit import upn_from_certificate
from certipy.target import Target
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-icpr/d98e6cfb-87ba-4915-b3ec-a1b7c6129a53
MSRPC_UUID_ICPR = string_to_bin("91ae6020-9e3c-11cf-8d7c-00aa00c091be")
class DCERPCSessionError(DCERPCException):
def __init__(self, error_string=None, error_code=None, packet=None):
|
def __str__(self):
key = self.error_code
if key in hresult_errors.ERROR_MESSAGES:
error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]
error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]
return "Cert SessionError: code: 0x%x - %s - %s" % (
self.error_code,
error_msg_short,
error_msg_verbose,
)
else:
return "Cert SessionError: unknown error code: 0x%x" % self.error_code
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wcce/d6bee093-d862-4122-8f2b-7b49102097dc
class CERTTRANSBLOB(NDRSTRUCT):
structure = (
("cb", ULONG),
("pb", PBYTE),
)
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-icpr/0c6f150e-3ead-4006-b37f-ebbf9e2cf2e7
class CertServerRequest(NDRCALL):
opnum = 0
structure = (
("dwFlags", DWORD),
("pwszAuthority", LPWSTR),
("pdwRequestId", DWORD),
("pctbAttribs", CERTTRANSBLOB),
("pctbRequest", CERTTRANSBLOB),
)
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-icpr/0c6f150e-3ead-4006-b37f-ebbf9e2cf2e7
class CertServerRequestResponse(NDRCALL):
structure = (
("pdwRequestId", DWORD),
("pdwDisposition", ULONG),
("pctbCert", CERTTRANSBLOB),
("pctbEncodedCert", CERTTRANSBLOB),
("pctbDispositionMessage", CERTTRANSBLOB),
)
def create_csr(username: str, alt_name: str = None) -> Tuple[bytes, "RSA.RsaKey"]:
logging.info("Generating RSA key")
rsa_key = RSA.generate(2048)
certification_request = csr.CertificationRequest()
certification_request_info = csr.CertificationRequestInfo(
{
"version": csr.Version("v1"),
}
)
# TODO: Create the subject from the DN of the user
subject = x509.Name.build({"common_name": username})
certification_request_info["subject"] = subject
certification_request_info["subject_pk_info"] = keys.PublicKeyInfo.wrap(
keys.RSAPublicKey({"modulus": rsa_key.n, "public_exponent": rsa_key.e}), "rsa"
)
if alt_name is not None:
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wcce/ea9ef420-4cbf-44bc-b093-c4175139f90f
extensions = x509.Extensions(
[
x509.Extension(
{
"extn_id": "subject_alt_name",
"extn_value": x509.GeneralNames(
[
x509.GeneralName(
"other_name",
{
"type_id": "1.3.6.1.4.1.311.20.2.3",
"value": core.UTF8String(alt_name).retag(
{
"explicit": 0,
"optional": True,
}
),
},
)
]
),
}
)
]
)
attributes = csr.CRIAttributes(
[
csr.CRIAttribute(
{
"type": "extension_request",
"values": csr.SetOfExtensions([extensions]),
}
)
]
)
certification_request_info["attributes"] = attributes
certification_request["certification_request_info"] = certification_request_info
certification_request["signature_algorithm"] = algos.SignedDigestAlgorithm(
{"algorithm": "sha256_rsa"}
)
hashvalue = SHA256.new(certification_request["certification_request_info"].dump())
signer = PKCS1_v1_5.new(rsa_key)
signature = signer.sign(hashvalue)
certification_request["signature"] = signature
return (
certification_request.dump(),
rsa_key,
)
class Request:
def __init__(self, options: argparse.Namespace, target: Target = None):
self.options = options
if target is None:
self.target = Target(options)
else:
self.target = target
self.certificate = None
self.key = None
def connect(self):
target = self.target
logging.debug(
"Connecting to SMB at %s (%s)"
% (repr(target.remote_name), target.target_ip)
)
smb_connection = SMBConnection(target.remote_name, target.target_ip)
if not target.do_kerberos:
smb_connection.login(
target.username,
target.password,
target.domain,
target.lmhash,
target.nthash,
)
else:
smb_connection.kerberosLogin(
target.username,
target.password,
target.domain,
target.lmhash,
target.nthash,
kdcHost=target.dc_ip,
)
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-icpr/9f0b251b-c722-4851-9a45-4e912660b458
rpc = transport.DCERPCTransportFactory("ncacn_np:445[\\pipe\\cert]")
rpc.set_smb_connection(smb_connection)
dce = rpc.get_dce_rpc()
dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY)
dce.connect()
dce.bind(MSRPC_UUID_ICPR)
self.dce = dce
def run(self):
self.connect()
alt_name = self.options.alt
if alt_name is None:
alt_name = self.target.username
csr, rsa_key = create_csr(self.target.username, alt_name=alt_name)
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wcce/13b7f3f7-c809-4c1e-97fd-52f2ed044c7e
attributes = ["CertificateTemplate:%s" % self.options.template]
if alt_name is not None:
attributes.append("SAN:upn=%s" % alt_name)
attributes = checkNullString("\n".join(attributes)).encode("utf-16le")
attribs = CERTTRANSBLOB()
attribs["cb"] = len(attributes)
attribs["pb"] = attributes
pctb_request = CERTTRANSBLOB()
pctb_request["cb"] = len(csr)
pctb_request["pb"] = csr
request = CertServerRequest()
request["dwFlags"] = 0
request["pwszAuthority"] = checkNullString(self.options.ca)
request["pdwRequestId"] = 0
request["pctbAttribs"] = attribs
request["pctbRequest"] = pctb_request
logging.info("Requesting certificate")
resp = self.dce.request(request)
return_code = resp["pdwDisposition"]
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-icpr/0c6f150e-3ead-4006-b37f-ebbf9e2cf2e7
if return_code == 5:
logging.warning("Request is pending approval")
return False
elif return_code != 3:
if return_code not in hresult_errors.ERROR_MESSAGES:
logging.error(
"Got unknown error while requesting certificate: %#x" % return_code
)
return False
error_msg_short = hresult_errors.ERROR_MESSAGES[return_code][0]
error_msg_verbose = hresult_errors.ERROR_MESSAGES[return_code][1]
logging.error(
"Got error while requesting certificate: code: %#x - %s - %s"
% (
return_code,
error_msg_short,
error_msg_verbose,
)
)
return False
request_id = resp["pdwRequestId"]
certificate = x509.Certificate.load(b"".join(resp["pctbEncodedCert"]["pb"]))
try:
# Some certificates does not contain a UPN
upn = upn_from_certificate(certificate)
logging.info("Got certificate with UPN %s" % repr(upn))
except Exception:
logging.info("Got certificate")
with open("%i.crt" % request_id, "wb") as f:
f.write(certificate.dump())
logging.info("Saved certificate to '%i.crt'" % request_id)
with open("%i.key" % request_id, "wb") as f:
f.write(rsa_key.export_key("DER"))
logging.info("Saved private key to '%i.key'" % request_id)
self.certificate = certificate
self.key = rsa_key
return True
def request(options: argparse.Namespace):
req = Request(options)
req.run()
| DCERPCException.__init__(self, error_string, error_code, packet) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.