Merge pull request #123 from gunjan5/patch-4
dir didn't match the command
diff --git a/.gitignore b/.gitignore
index 451dd79..61b07cd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,9 +3,13 @@
*.swp
profile
*.moved-aside
+.idea
+xos.iml
xos/configurations/frontend/Dockerfile
xos/core/xoslib/karma-*
xos/core/xoslib/docs
xos/core/xoslib/coverage
node_modules
xos/xos_configuration/*
+.idea/*
+xos.iml
diff --git a/Makefile b/Makefile
deleted file mode 100644
index 2b55526..0000000
--- a/Makefile
+++ /dev/null
@@ -1,55 +0,0 @@
-NAME = xos
-SPECFILE = $(NAME).spec
-VERSION = $(shell rpm -q --specfile $(SPECFILE) --qf '%{VERSION}\n' | head -n 1)
-RELEASE = $(shell rpm -q --specfile $(SPECFILE) --qf '%{RELEASE}\n' | head -n 1)
-
-UPLOAD_SLICE=princeton_planetstack
-
-PWD = $(shell pwd)
-
-dist rpm: $(NAME)-$(VERSION)-$(RELEASE).rpm
-
-$(NAME)-$(VERSION).tar.gz:
- mkdir -p $(NAME)-$(VERSION)
- rsync -av --exclude=.svn --exclude=.git --exclude=*.tar.gz --exclude=*.rpm --exclude=__history --exclude=$(NAME)-$(VERSION)/ ./ $(NAME)-$(VERSION)
- tar -czf $@ $(NAME)-$(VERSION)
- rm -fr $(NAME)-$(VERSION)
-
-$(NAME)-$(VERSION)-$(RELEASE).rpm: $(NAME)-$(VERSION).tar.gz
- mkdir -p build
- rpmbuild -bb --define '_sourcedir $(PWD)' \
- --define '_builddir $(PWD)/build' \
- --define '_srcrpmdir $(PWD)' \
- --define '_rpmdir $(PWD)' \
- --define '_build_name_fmt %%{NAME}-%%{VERSION}-%%{RELEASE}.%%{ARCH}.rpm' \
- $(SPECFILE)
-
-srpm: $(NAME)-$(VERSION)-$(RELEASE).src.rpm
-$(NAME)-$(VERSION)-$(RELEASE).src.rpm: $(NAME)-$(VERSION).tar.gz
- rpmbuild -bs --define "_sourcedir $$(pwd)" \
- --define "_srcrpmdir $$(pwd)" \
- $(SPECFILE)
-
-clean:
- rm -f $(NAME)-$(VERSION).tar.gz $(NAME)-$(VERSION)-$(RELEASE).src.rpm $(NAME)-$(VERSION)-$(RELEASE).noarch.rpm
- rm -rf build
-
-upload: $(NAME)-$(VERSION)-$(RELEASE).rpm
-ifndef UPLOAD_HOST
- $(error please specify UPLOAD_HOST=<hostname> on make command line)
-endif
- scp $(NAME)-$(VERSION)-$(RELEASE).x86_64.rpm $(UPLOAD_SLICE)@$(UPLOAD_HOST):/root/
-
-install: upload
- ssh $(UPLOAD_SLICE)@$(UPLOAD_HOST) yum -y install gcc graphviz-devel graphviz-python postgresql postgresql-server python-pip python-psycopg2 libxslt-devel python-httplib2 GeoIP
- ssh $(UPLOAD_SLICE)@$(UPLOAD_HOST) rpm --install --upgrade --replacefiles --replacepkgs /root/$(NAME)-$(VERSION)-$(RELEASE).x86_64.rpm
- scp /opt/planetstack/hpc_wizard/bigquery_credentials.dat /opt/planetstack/hpc_wizard/client_secrets.json $(UPLOAD_SLICE)@$(UPLOAD_HOST):/opt/planetstack/hpc_wizard/
-
-install-keys:
-ifndef UPLOAD_HOST
- $(error please specify UPLOAD_HOST=<hostname> on make command line)
-endif
- scp /opt/planetstack/hpc_wizard/bigquery_credentials.dat /opt/planetstack/hpc_wizard/client_secrets.json $(UPLOAD_SLICE)@$(UPLOAD_HOST):/opt/planetstack/hpc_wizard/
-
-.PHONY: dist
-
diff --git a/ansible-hosts b/ansible-hosts
deleted file mode 100644
index 0dd74f1..0000000
--- a/ansible-hosts
+++ /dev/null
@@ -1,2 +0,0 @@
-[localhost]
-127.0.0.1
diff --git a/containers/README.md b/containers/README.md
index ec141d9..46f970e 100644
--- a/containers/README.md
+++ b/containers/README.md
@@ -29,7 +29,7 @@
```
You should now be able to access the login page by visiting
-`http://localhost:80` and log in using the default `paadmin@vicci.org` account
+`http://localhost:8000` and log in using the default `padmin@vicci.org` account
with password `letmein`. It may be helpful to bootstrap xos with some sample
data; deployment, controllers, sites, slices, etc. You can get started by
loading tosca configuration for the opencloud demo dataset:
@@ -73,5 +73,5 @@
using a single command. To start the instance you can use the command:
```
-$ docker-compose -f xos-compose.yml up -d
+$ docker-compose up -d
```
diff --git a/containers/xos-compose.yml b/containers/docker-compose.yml
similarity index 100%
rename from containers/xos-compose.yml
rename to containers/docker-compose.yml
diff --git a/containers/synchronizer/Dockerfile b/containers/synchronizer/Dockerfile
index 7170e1c..011e8dd 100644
--- a/containers/synchronizer/Dockerfile
+++ b/containers/synchronizer/Dockerfile
@@ -1,6 +1,5 @@
FROM xosproject/xos
-# Install custom Ansible
RUN DEBIAN_FRONTEND=noninteractive apt-get update && apt-get install -y \
openssh-client \
python-crypto \
@@ -8,11 +7,13 @@
python-paramiko \
python-yaml \
python-httplib2 \
+ rsync \
supervisor
RUN pip install -U \
jinja2
+# Install custom Ansible
RUN \
git clone -b release1.8.2 git://github.com/ansible/ansible.git /opt/ansible && \
git clone -b release1.8.2 git://github.com/ansible/ansible-modules-extras.git /opt/ansible/lib/ansible/modules/extras && \
@@ -28,7 +29,7 @@
# For Observer
RUN mkdir -p /usr/local/share /bin /etc/ansible
-RUN cp /tmp/xos/containers/synchronizer/conf/ansible-hosts /etc/ansible/hosts
+COPY conf/ansible-hosts /etc/ansible/hosts
ADD http://phantomjs.googlecode.com/files/phantomjs-1.7.0-linux-x86_64.tar.bz2 /usr/local/share/
@@ -42,6 +43,6 @@
# Supervisor
-RUN cp /tmp/xos/containers/synchronizer/conf/synchronizer.conf /etc/supervisor/conf.d/
+COPY conf/synchronizer.conf /etc/supervisor/conf.d/
CMD update-ca-certificates && /usr/bin/supervisord -c /etc/supervisor/conf.d/synchronizer.conf
diff --git a/containers/synchronizer/conf/synchronizer.conf b/containers/synchronizer/conf/synchronizer.conf
index cda6716..2131a25 100644
--- a/containers/synchronizer/conf/synchronizer.conf
+++ b/containers/synchronizer/conf/synchronizer.conf
@@ -4,6 +4,6 @@
nodaemon=true
[program:synchronizer]
-command=python /opt/xos/xos-observer.py
+command=python /opt/xos/synchronizers/openstack/xos-synchronizer.py
stderr_logfile=/var/log/supervisor/synchronizer.err.log
stdout_logfile=/var/log/supervisor/synchronizer.out.log
diff --git a/containers/xos/Dockerfile b/containers/xos/Dockerfile
index 639cbd5..0fd7565 100644
--- a/containers/xos/Dockerfile
+++ b/containers/xos/Dockerfile
@@ -29,7 +29,7 @@
python-setuptools \
tar \
wget \
-##### observer dependencies
+##### observer dependencies
python-keystoneclient \
python-novaclient \
python-neutronclient \
@@ -42,7 +42,7 @@
django-crispy-forms \
django-encrypted-fields \
django-extensions \
- django-filter \
+ django-filter==0.11.0 \
django-geoposition \
django-ipware \
django_rest_swagger \
@@ -50,11 +50,11 @@
django-timezones \
djangorestframework==2.4.4 \
dnslib \
- lxml \
+ lxml \
markdown \
netaddr \
pyOpenSSL \
- psycopg2 \
+ psycopg2 \
python-ceilometerclient \
python-dateutil \
python-keyczar \
@@ -66,18 +66,17 @@
RUN easy_install --upgrade httplib2
RUN easy_install \
- django_evolution \
python_gflags \
google_api_python_client \
httplib2.ca_certs_locater
-ADD http://code.jquery.com/jquery-1.9.1.min.js /usr/local/lib/python2.7/dist-packages/suit/static/suit/js/
+ADD http://code.jquery.com/jquery-1.9.1.min.js /usr/local/lib/python2.7/site-packages/suit/static/suit/js/
# Install XOS
RUN git clone git://github.com/open-cloud/xos.git /tmp/xos && \
mv /tmp/xos/xos /opt/ && \
- chmod +x /opt/xos/scripts/opencloud && \
- /opt/xos/scripts/opencloud genkeys
+ chmod +x /opt/xos/tools/xos-manage && \
+ /opt/xos/tools/xos-manage genkeys
# install Tosca engine
RUN chmod +x /opt/xos/tosca/run.py
@@ -87,6 +86,7 @@
# Set environment variables.
ENV HOME /root
+ENV PYTHONPATH /usr/local/lib/python2.7/site-packages:/usr/lib/python2.7/dist-packages
# Define working directory.
WORKDIR /opt/xos
diff --git a/containers/xos/Dockerfile.devel b/containers/xos/Dockerfile.devel
new file mode 100644
index 0000000..93f5025
--- /dev/null
+++ b/containers/xos/Dockerfile.devel
@@ -0,0 +1,94 @@
+FROM python:2.7.11
+
+# XXX Workaround for docker bug:
+# https://github.com/docker/docker/issues/6345
+# Kernel 3.15 breaks docker, uss the line below as a workaround
+# until there is a fix
+RUN ln -s -f /bin/true /usr/bin/chfn
+# XXX End workaround
+
+# Install.
+RUN DEBIAN_FRONTEND=noninteractive apt-get update && apt-get install -y \
+ curl \
+ gcc \
+ geoip-database \
+ git \
+ graphviz \
+ graphviz-dev \
+ libgeoip1 \
+ libxslt1.1 \
+ libxslt1-dev \
+ libyaml-dev \
+ m4 \
+ pkg-config \
+ python-dev \
+ python-httplib2 \
+ python-pip \
+ python-psycopg2 \
+ python-pycurl \
+ python-setuptools \
+ tar \
+ wget \
+##### observer dependencies
+ python-keystoneclient \
+ python-novaclient \
+ python-neutronclient \
+ python-glanceclient \
+ python-ceilometerclient
+
+RUN pip install \
+ django==1.7 \
+ django-bitfield \
+ django-crispy-forms \
+ django-encrypted-fields \
+ django-extensions \
+ django-filter==0.11.0 \
+ django-geoposition \
+ django-ipware \
+ django_rest_swagger \
+ django-suit==0.3a1 \
+ django-timezones \
+ djangorestframework==2.4.4 \
+ dnslib \
+ lxml \
+ markdown \
+ netaddr \
+ pyOpenSSL \
+ psycopg2 \
+ python-ceilometerclient \
+ python-dateutil \
+ python-keyczar \
+ pygraphviz \
+ pytz \
+ pyyaml \
+ requests
+
+RUN easy_install --upgrade httplib2
+
+RUN easy_install \
+ python_gflags \
+ google_api_python_client \
+ httplib2.ca_certs_locater
+
+ADD http://code.jquery.com/jquery-1.9.1.min.js /usr/local/lib/python2.7/site-packages/suit/static/suit/js/
+
+# Install XOS
+ADD xos /opt/xos
+RUN chmod +x /opt/xos/tools/xos-manage
+RUN /opt/xos/tools/xos-manage genkeys
+
+# install Tosca engine
+RUN chmod +x /opt/xos/tosca/run.py
+RUN bash /opt/xos/tosca/install_tosca.sh
+
+EXPOSE 8000
+
+# Set environment variables.
+ENV HOME /root
+ENV PYTHONPATH /usr/local/lib/python2.7/site-packages:/usr/lib/python2.7/dist-packages
+
+# Define working directory.
+WORKDIR /opt/xos
+
+# Define default command.
+CMD update-ca-certificates && python manage.py runserver 0.0.0.0:8000 --insecure
diff --git a/containers/xos/Dockerfile.templ b/containers/xos/Dockerfile.templ
index 5071f68..828c16b 100644
--- a/containers/xos/Dockerfile.templ
+++ b/containers/xos/Dockerfile.templ
@@ -29,7 +29,7 @@
python-setuptools \
tar \
wget \
-##### observer dependencies
+##### observer dependencies
python-keystoneclient \
python-novaclient \
python-neutronclient \
@@ -43,7 +43,7 @@
django-encrypted-fields \
django_evolution \
django-extensions \
- django-filter \
+ django-filter==0.11.0 \
django-geoposition \
django-ipware \
django_rest_swagger \
@@ -54,7 +54,7 @@
google_api_python_client \
httplib2 \
httplib2.ca_certs_locater \
- lxml \
+ lxml \
markdown \
netaddr \
python-dateutil \
@@ -65,13 +65,13 @@
pyyaml \
requests
-ADD http://code.jquery.com/jquery-1.9.1.min.js /usr/local/lib/python2.7/dist-packages/suit/static/suit/js/
+ADD http://code.jquery.com/jquery-1.9.1.min.js /usr/local/lib/python2.7/site-packages/suit/static/suit/js/
# Install XOS
RUN git clone XOS_GIT_REPO -b XOS_GIT_BRANCH /tmp/xos && \
mv /tmp/xos/xos /opt/ && \
- chmod +x /opt/xos/scripts/opencloud && \
- /opt/xos/scripts/opencloud genkeys
+ chmod +x /opt/xos/tools/xos-manage && \
+ /opt/xos/tools/xos-manage genkeys
# install Tosca engine
RUN bash /opt/xos/tosca/install_tosca.sh
@@ -80,6 +80,7 @@
# Set environment variables.
ENV HOME /root
+ENV PYTHONPATH /usr/local/lib/python2.7/site-packages:/usr/lib/python2.7/dist-packages
# Define working directory.
WORKDIR /root
diff --git a/containers/xos/Makefile b/containers/xos/Makefile
index 833046b..8efcf60 100644
--- a/containers/xos/Makefile
+++ b/containers/xos/Makefile
@@ -6,10 +6,13 @@
NO_DOCKER_CACHE?=false
.PHONY: build
-build: ; make -C ../../xos/configurations/common -f Makefile.cloudlab; docker build --no-cache=${NO_DOCKER_CACHE} --rm -t ${IMAGE_NAME} .
+build: ; docker build --no-cache=${NO_DOCKER_CACHE} --rm -t ${IMAGE_NAME} .
.PHONY: custom
-custom: ; cat Dockerfile.templ | sed -e "s|XOS_GIT_REPO|${XOS_GIT_REPO}|g" -e "s|XOS_GIT_BRANCH|${XOS_GIT_BRANCH}|g" | docker build --no-cache=${NO_DOCKER_CACHE} -
+custom: ; cat Dockerfile.templ | sed -e "s|XOS_GIT_REPO|${XOS_GIT_REPO}|g" -e "s|XOS_GIT_BRANCH|${XOS_GIT_BRANCH}|g" | docker build --no-cache=${NO_DOCKER_CACHE} --rm -t ${IMAGE_NAME} -
+
+.PHONY: devel
+devel: ; cd ../..; ls; docker build -f containers/xos/Dockerfile.devel --no-cache=${NO_DOCKER_CACHE} --rm -t ${IMAGE_NAME} .
.PHONY: run
run: ; docker run -d --name ${CONTAINER_NAME} -p 80:8000 -v /usr/local/share/ca-certificates:/usr/local/share/ca-certificates:ro ${IMAGE_NAME}
diff --git a/containers/xos/initdb b/containers/xos/initdb
index 3252747..1f5b770 100755
--- a/containers/xos/initdb
+++ b/containers/xos/initdb
@@ -10,7 +10,7 @@
docker rm $CONTAINER_NAME
# init db schema
-docker run -it --name=$CONTAINER_NAME $IMAGE_NAME /opt/xos/scripts/opencloud makemigrations
+docker run -it --name=$CONTAINER_NAME $IMAGE_NAME /opt/xos/tools/xos-manage makemigrations
# run overrides the CMD specifed in the Dockerfile, so we re-set the CMD in the final commit"
docker commit --change="CMD update-ca-certificates && python /opt/xos/manage.py runserver 0.0.0.0:8000 --insecure" $CONTAINER_NAME $IMAGE_NAME
docker rm $CONTAINER_NAME
diff --git a/docker-cp.sh b/docker-cp.sh
deleted file mode 100755
index bec511d..0000000
--- a/docker-cp.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-#! /bin/bash
-# script for copying stuff into running Docker container
-# usage: docker-cp.sh <src> <dest>
-# example: docker-cp.sh foo /tmp/foo
-
-XOS=$( docker ps|grep "xos"|awk '{print $NF}' )
-FOLDER=`docker inspect -f '{{.Id}}' $XOS`
-#cp $1 /var/lib/docker/aufs/mnt/$FOLDER/$2
-docker cp $1 $XOS:$2
diff --git a/external/keystone_user.py b/external/keystone_user.py
deleted file mode 100644
index 1245eec..0000000
--- a/external/keystone_user.py
+++ /dev/null
@@ -1,407 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-# Based on Jimmy Tang's implementation
-
-DOCUMENTATION = '''
----
-module: keystone_user
-version_added: "1.2"
-short_description: Manage OpenStack Identity (keystone) users, tenants and roles
-description:
- - Manage users,tenants, roles from OpenStack.
-options:
- login_user:
- description:
- - login username to authenticate to keystone
- required: false
- default: admin
- login_password:
- description:
- - Password of login user
- required: false
- default: 'yes'
- login_tenant_name:
- description:
- - The tenant login_user belongs to
- required: false
- default: None
- version_added: "1.3"
- token:
- description:
- - The token to be uses in case the password is not specified
- required: false
- default: None
- endpoint:
- description:
- - The keystone url for authentication
- required: false
- default: 'http://127.0.0.1:35357/v2.0/'
- user:
- description:
- - The name of the user that has to added/removed from OpenStack
- required: false
- default: None
- password:
- description:
- - The password to be assigned to the user
- required: false
- default: None
- tenant:
- description:
- - The tenant name that has be added/removed
- required: false
- default: None
- tenant_description:
- description:
- - A description for the tenant
- required: false
- default: None
- email:
- description:
- - An email address for the user
- required: false
- default: None
- role:
- description:
- - The name of the role to be assigned or created
- required: false
- default: None
- state:
- description:
- - Indicate desired state of the resource
- choices: ['present', 'absent']
- default: present
-requirements: [ python-keystoneclient ]
-author: Lorin Hochstein
-'''
-
-EXAMPLES = '''
-# Create a tenant
-- keystone_user: tenant=demo tenant_description="Default Tenant"
-
-# Create a user
-- keystone_user: user=john tenant=demo password=secrete
-
-# Apply the admin role to the john user in the demo tenant
-- keystone_user: role=admin user=john tenant=demo
-'''
-
-try:
- from keystoneclient.v2_0 import client
-except ImportError:
- keystoneclient_found = False
-else:
- keystoneclient_found = True
-
-
-def authenticate(endpoint, token, login_user, login_password, login_tenant_name):
- """Return a keystone client object"""
-
- if token:
- return client.Client(endpoint=endpoint, token=token)
- else:
- return client.Client(auth_url=endpoint, username=login_user,
- password=login_password, tenant_name=login_tenant_name)
-
-
-def tenant_exists(keystone, tenant):
- """ Return True if tenant already exists"""
- return tenant in [x.name for x in keystone.tenants.list()]
-
-
-def user_exists(keystone, user):
- """" Return True if user already exists"""
- return user in [x.name for x in keystone.users.list()]
-
-
-def get_tenant(keystone, name):
- """ Retrieve a tenant by name"""
- tenants = [x for x in keystone.tenants.list() if x.name == name]
- count = len(tenants)
- if count == 0:
- raise KeyError("No keystone tenants with name %s" % name)
- elif count > 1:
- raise ValueError("%d tenants with name %s" % (count, name))
- else:
- return tenants[0]
-
-
-def get_user(keystone, name):
- """ Retrieve a user by name"""
- users = [x for x in keystone.users.list() if x.name == name]
- count = len(users)
- if count == 0:
- raise KeyError("No keystone users with name %s" % name)
- elif count > 1:
- raise ValueError("%d users with name %s" % (count, name))
- else:
- return users[0]
-
-
-def get_role(keystone, name):
- """ Retrieve a role by name"""
- roles = [x for x in keystone.roles.list() if x.name == name]
- count = len(roles)
- if count == 0:
- raise KeyError("No keystone roles with name %s" % name)
- elif count > 1:
- raise ValueError("%d roles with name %s" % (count, name))
- else:
- return roles[0]
-
-
-def get_tenant_id(keystone, name):
- return get_tenant(keystone, name).id
-
-
-def get_user_id(keystone, name):
- return get_user(keystone, name).id
-
-
-def ensure_tenant_exists(keystone, tenant_name, tenant_description,
- check_mode):
- """ Ensure that a tenant exists.
-
- Return (True, id) if a new tenant was created, (False, None) if it
- already existed.
- """
-
- # Check if tenant already exists
- try:
- tenant = get_tenant(keystone, tenant_name)
- except KeyError:
- # Tenant doesn't exist yet
- pass
- else:
- if tenant.description == tenant_description:
- return (False, tenant.id)
- else:
- # We need to update the tenant description
- if check_mode:
- return (True, tenant.id)
- else:
- tenant.update(description=tenant_description)
- return (True, tenant.id)
-
- # We now know we will have to create a new tenant
- if check_mode:
- return (True, None)
-
- ks_tenant = keystone.tenants.create(tenant_name=tenant_name,
- description=tenant_description,
- enabled=True)
- return (True, ks_tenant.id)
-
-
-def ensure_tenant_absent(keystone, tenant, check_mode):
- """ Ensure that a tenant does not exist
-
- Return True if the tenant was removed, False if it didn't exist
- in the first place
- """
- if not tenant_exists(keystone, tenant):
- return False
-
- # We now know we will have to delete the tenant
- if check_mode:
- return True
-
-def ensure_user_exists_and_is_current(keystone, endpoint, user_name, password, email, tenant_name,
- check_mode):
- """ Check if user exists and has the same email and password
-
- Return (True, id) if a new user was created or one was updated, (False, id) if the user is
- up to date
- """
-
- # Check if tenant already exists
- try:
- user = get_user(keystone, user_name)
- except KeyError:
- # Tenant doesn't exist yet
- user = None
- pass
- else:
- # User does exist, check if it's current
- try:
- authenticate(endpoint, None, user_name, password, tenant_name)
- except:
- pass
- else:
- # It's current, we're done
- return (False, user.id)
-
- # We now know we will have to create a new user
- if check_mode:
- return (True, None)
-
- tenant = get_tenant(keystone, tenant_name)
-
- if (not user):
- user = keystone.users.create(name=user_name, password=password,
- email=email, tenant_id=tenant.id)
- else:
- user = keystone.users.update_password(user.id, password)
-
- return (True, user.id)
-
-
-def ensure_role_exists(keystone, user_name, tenant_name, role_name,
- check_mode):
- """ Check if role exists
-
- Return (True, id) if a new role was created or if the role was newly
- assigned to the user for the tenant. (False, id) if the role already
- exists and was already assigned to the user ofr the tenant.
-
- """
- # Check if the user has the role in the tenant
- user = get_user(keystone, user_name)
- tenant = get_tenant(keystone, tenant_name)
- roles = [x for x in keystone.roles.roles_for_user(user, tenant)
- if x.name == role_name]
- count = len(roles)
-
- if count == 1:
- # If the role is in there, we are done
- role = roles[0]
- return (False, role.id)
- elif count > 1:
- # Too many roles with the same name, throw an error
- raise ValueError("%d roles with name %s" % (count, role_name))
-
- # At this point, we know we will need to make changes
- if check_mode:
- return (True, None)
-
- # Get the role if it exists
- try:
- role = get_role(keystone, role_name)
- except KeyError:
- # Role doesn't exist yet
- role = keystone.roles.create(role_name)
-
- # Associate the role with the user in the admin
- keystone.roles.add_user_role(user, role, tenant)
- return (True, role.id)
-
-
-def ensure_user_absent(keystone, user, check_mode):
- raise NotImplementedError("Not yet implemented")
-
-
-def ensure_role_absent(keystone, uesr, tenant, role, check_mode):
- raise NotImplementedError("Not yet implemented")
-
-
-def main():
-
- argument_spec = openstack_argument_spec()
- argument_spec.update(dict(
- tenant_description=dict(required=False),
- email=dict(required=False),
- user=dict(required=False),
- tenant=dict(required=False),
- password=dict(required=False),
- role=dict(required=False),
- state=dict(default='present', choices=['present', 'absent']),
- endpoint=dict(required=False,
- default="http://127.0.0.1:35357/v2.0"),
- token=dict(required=False),
- login_user=dict(required=False),
- login_password=dict(required=False),
- login_tenant_name=dict(required=False)
- ))
- # keystone operations themselves take an endpoint, not a keystone auth_url
- del(argument_spec['auth_url'])
- module = AnsibleModule(
- argument_spec=argument_spec,
- supports_check_mode=True,
- mutually_exclusive=[['token', 'login_user'],
- ['token', 'login_password'],
- ['token', 'login_tenant_name']]
- )
-
- if not keystoneclient_found:
- module.fail_json(msg="the python-keystoneclient module is required")
-
- user = module.params['user']
- password = module.params['password']
- tenant = module.params['tenant']
- tenant_description = module.params['tenant_description']
- email = module.params['email']
- role = module.params['role']
- state = module.params['state']
- endpoint = module.params['endpoint']
- token = module.params['token']
- login_user = module.params['login_user']
- login_password = module.params['login_password']
- login_tenant_name = module.params['login_tenant_name']
-
- keystone = authenticate(endpoint, token, login_user, login_password, login_tenant_name)
-
- check_mode = module.check_mode
-
- try:
- d = dispatch(keystone, user, password, tenant, tenant_description,
- email, role, state, endpoint, token, login_user,
- login_password, check_mode)
- except Exception, e:
- if check_mode:
- # If we have a failure in check mode
- module.exit_json(changed=True,
- msg="exception: %s" % e)
- else:
- module.fail_json(msg="exception: %s" % e)
- else:
- module.exit_json(**d)
-
-
-def dispatch(keystone, user=None, password=None, tenant=None,
- tenant_description=None, email=None, role=None,
- state="present", endpoint=None, token=None, login_user=None,
- login_password=None, check_mode=False):
- """ Dispatch to the appropriate method.
-
- Returns a dict that will be passed to exit_json
-
- tenant user role state
- ------ ---- ---- --------
- X present ensure_tenant_exists
- X absent ensure_tenant_absent
- X X present ensure_user_exists
- X X absent ensure_user_absent
- X X X present ensure_role_exists
- X X X absent ensure_role_absent
-
-
- """
- changed = False
- id = None
- if tenant and not user and not role and state == "present":
- changed, id = ensure_tenant_exists(keystone, tenant,
- tenant_description, check_mode)
- elif tenant and not user and not role and state == "absent":
- changed = ensure_tenant_absent(keystone, tenant, check_mode)
- elif tenant and user and not role and state == "present":
- changed, id = ensure_user_exists_and_is_current(keystone, endpoint, user, password,
- email, tenant, check_mode)
- elif tenant and user and not role and state == "absent":
- changed = ensure_user_absent(keystone, user, check_mode)
- elif tenant and user and role and state == "present":
- changed, id = ensure_role_exists(keystone, user, tenant, role,
- check_mode)
- elif tenant and user and role and state == "absent":
- changed = ensure_role_absent(keystone, user, tenant, role, check_mode)
- else:
- # Should never reach here
- raise ValueError("Code should never reach here")
-
- return dict(changed=changed, id=id)
-
-# import module snippets
-from ansible.module_utils.basic import *
-from ansible.module_utils.openstack import *
-if __name__ == '__main__':
- main()
diff --git a/install_opencloud b/install_opencloud
deleted file mode 100755
index ec0e0ab..0000000
--- a/install_opencloud
+++ /dev/null
@@ -1,52 +0,0 @@
-#!/bin/sh
-yum -y install postgresql postgresql-server
-yum -y install python-psycopg2
-yum -y install graphviz
-yum -y install graphviz-devel
-yum -y install graphviz-python
-yum -y install libxslt-devel
-yum -y install python-pip
-yum -y install wget
-yum -y install tar
-yum -y install gcc
-yum -y install libxml2-dev
-yum -y install libxslt1-dev
-yum -y install python-devel
-
-
-pip-python install django==1.5
-pip-python install djangorestframework
-pip-python install markdown # Markdown support for the browseable API.
-pip-python install pyyaml # YAML content-type support.
-pip-python install django-filter # Filtering support
-pip-python install lxml # XML manipulation library
-pip-python install netaddr # IP Addr library
-pip-python install pytz
-pip-python install django-timezones
-pip-python install requests
-pip-python install django-crispy-forms
-pip-python install django-geoposition
-pip-python install django-extensions
-pip-python install django-suit
-pip-python install django-evolution
-pip-python install docutils
-pip-python install cython
-pip-python install bitfield
-pip-python install pygments
-
-easy_install django_evolution
-
-wget http://phantomjs.googlecode.com/files/phantomjs-1.7.0-linux-x86_64.tar.bz2
-
-mv ./phantomjs-1.7.0-linux-x86_64.tar.bz2 /usr/local/share
-
-cd /usr/local/share
-
-tar xvf phantomjs-1.7.0-linux-x86_64.tar.bz2
-
-ln -s /usr/local/share/phantomjs-1.7.0-linux-x86_64 /usr/local/share/phantomjs
-
-ln -s /usr/local/share/phantomjs/bin/phantomjs /usr/local/bin/phantomjs
-
-phantomjs --version
-
diff --git a/observer-initscript b/observer-initscript
deleted file mode 100755
index d1466b2..0000000
--- a/observer-initscript
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/bin/bash
-#
-# observer Starts and stops Observer daemon
-#
-
-# Source function library.
-. /etc/init.d/functions
-
-[ -f /etc/sysconfig/xosobserver ] && . /etc/sysconfig/xosobserver
-
-
-xosobserver=${NODEMANAGER-"python /opt/xos/xos-observer.py -d"}
-prog="OpenCloud Observer"
-pidfile=${PIDFILE-/var/run/xosobserver.pid}
-
-RETVAL=0
-
-function start() {
- action $"Starting $prog: " daemon --pidfile=$pidfile --check=xosobserver $xosobserver "$@"
-}
-
-function stop() {
- action $"Stopping $prog: " killproc -p $pidfile xosobserver
-}
-
-case "$1" in
- start)
- start $options
- ;;
- stop)
- stop
- ;;
- status)
- status -p $pidfile xosobserver
- RETVAL=$?
- ;;
- restart|reload)
- shift
- stop
- start $options "$@"
- ;;
- condrestart)
- shift
- [ -f ${pidfile} ] && { stop; start $options "$@"; }
- ;;
- restartverbose)
- shift
- stop
- $xosobserver $verboseoptions "$@"
- ;;
- restartdebug)
- shift
- stop
- echo "Restarting with $debugoptions $@ .."
- $xosobserver $debugoptions "$@"
- ;;
- *)
- echo $"Usage: $0 {start|stop|status|restart|condrestart|restartdebug [-d]}"
- exit 1
- ;;
-esac
-
-exit $RETVAL
diff --git a/observer.conf b/observer.conf
deleted file mode 100644
index 92545eb..0000000
--- a/observer.conf
+++ /dev/null
@@ -1,2 +0,0 @@
-[program:observer]
-command=python /opt/xos/xos-observer.py
diff --git a/setup.py b/setup.py
deleted file mode 100644
index 1162279..0000000
--- a/setup.py
+++ /dev/null
@@ -1,25 +0,0 @@
-import os
-import shutil
-from distutils.core import setup
-
-def copytree(src, dst, symlinks=False, ignore=None):
- if not os.path.exists(dst):
- os.makedirs(dst)
- for item in os.listdir(src):
- s = os.path.join(src, item)
- d = os.path.join(dst, item)
- if os.path.isdir(s):
- copytree(s, d, symlinks, ignore)
- else:
- if not os.path.exists(d) or os.stat(src).st_mtime - os.stat(dst).st_mtime > 1:
- shutil.copy2(s, d)
-
-setup(name='planetstack',
- version='0.1',
- description='PlanetStack',
- scripts=['xos/xos-observer.py'],
- data_files=[
- ('/lib/systemd/system/', ['xos/redhat/xos-observer.service']),
- ])
-
-copytree('xos/', '/opt/xos')
diff --git a/synchronizers b/synchronizers
deleted file mode 120000
index d587898..0000000
--- a/synchronizers
+++ /dev/null
@@ -1 +0,0 @@
-observers
\ No newline at end of file
diff --git a/upgrade-container.sh b/upgrade-container.sh
deleted file mode 100755
index 09c639d..0000000
--- a/upgrade-container.sh
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/bin/bash
-
-TMPDIR="/tmp/initdata"
-XOSDIR="/home/ubuntu/xos"
-
-mkdir -p $TMPDIR
-rm -f $TMPDIR/*.json
-
-XOS=$( docker ps|grep "xos:latest"|awk '{print $NF}' )
-docker exec $XOS /opt/xos/scripts/opencloud dumpdata
-docker cp $XOS:/opt/xos_backups/dumpdata-latest.json $TMPDIR
-docker cp $XOS:/opt/xos/xos_config $TMPDIR
-cp $TMPDIR/*.json $XOSDIR/xos/core/fixtures/initial_data.json
-cp $TMPDIR/xos_config $XOSDIR/xos/
-
-git pull
-
-if [[ $? != 0 ]]; then
- echo "git pull" failed
- exit
-fi
-
-docker build -t xos .
-
-docker stop $XOS
-docker run -p 8000:8000 xos
diff --git a/wiki/figures/modeling-services-fig1.png b/wiki/figures/modeling-services-fig1.png
deleted file mode 100644
index 6df4b43..0000000
--- a/wiki/figures/modeling-services-fig1.png
+++ /dev/null
Binary files differ
diff --git a/wiki/figures/modeling-services-fig2.png b/wiki/figures/modeling-services-fig2.png
deleted file mode 100644
index a854b19..0000000
--- a/wiki/figures/modeling-services-fig2.png
+++ /dev/null
Binary files differ
diff --git a/xos-apps/README.md b/xos-apps/README.md
new file mode 100644
index 0000000..66d71eb
--- /dev/null
+++ b/xos-apps/README.md
@@ -0,0 +1,10 @@
+## Applications on XOS
+
+This directory may prove to be unnecessary, but for now we
+are using it for applications that run on top of the XOS API.
+Initially, this includes only an auto-scaling app that uses
+monitoring data to decide when to scale a service up/down.
+
+This is treated as an application rather than yet another
+service because it offers only a GUI front-end; it is not
+modelled as a service that other services can build upon.
diff --git a/xos-apps/auto-scale/README.md b/xos-apps/auto-scale/README.md
new file mode 100644
index 0000000..3985719
--- /dev/null
+++ b/xos-apps/auto-scale/README.md
@@ -0,0 +1,77 @@
+#How to
+
+Ensure that the CORD config is installed and then run:
+
+`python xos_auto_scaling_app.py`
+
+This command will start the autoscaling application and start REST server on 9991 port.
+
+## To verify the autoscaling application:
+1) Login to cloudlab compute nodes <br/>
+2) On each compute node, open /etc/ceilometer/pipeline.yaml file<br/>
+3) Change the polling interval for "cpu_source" meters from 600 to poll interval period that u wish (eg. 60) as shown below.<br/>
+From:
+```
+ - name: cpu_source
+ interval: 600
+ meters:
+ - "cpu"
+ sinks:
+ - cpu_sink
+```
+
+To:
+```
+ - name: cpu_source
+ interval: 60
+ meters:
+ - "cpu"
+ sinks:
+ - cpu_sink
+```
+3b) Also ensure the publisher in "cpu_sink" contains the following URL "udp://"IP of Ceilometer PUB-SUB":5004" as shown below.<br/>
+```
+ - name: cpu_sink
+ transformers:
+ - name: "rate_of_change"
+ parameters:
+ target:
+ name: "cpu_util"
+ unit: "%"
+ type: "gauge"
+ scale: "100.0 / (10**9 * (resource_metadata.cpu_number or 1))"
+ publishers:
+ - notifier://
+```
+
+To:
+```
+ - name: cpu_sink
+ transformers:
+ - name: "rate_of_change"
+ parameters:
+ target:
+ name: "cpu_util"
+ unit: "%"
+ type: "gauge"
+ scale: "100.0 / (10**9 * (resource_metadata.cpu_number or 1))"
+ publishers:
+ - notifier://
+ - udp://10.11.10.1:5004
+```
+4) sudo service ceilometer-agent-compute restart<br/>
+5) With this change, the autoscaling application should start receiving the CPU utilization samples every 60 seconds<br/>
+6) The REST API to retrieve the cpu utilization samples from autoscaling application: http://<app_ip>:9991/autoscaledata
+
+## GUI (early development stage)
+
+To run this sample you need to have `nodejs >= 4.0` installed on your local system. You can get it [here](https://nodejs.org/en/)
+
+- Clone the repository locally
+- Open `xos-apps/auto-scale/gui/env/default` and change it to:
+```
+module.exports = {
+ host: 'http://<your.cord.installation.ip>:9991'
+}
+```
+- From `xos-apps/auto-scale/gui` run `npm start`
diff --git a/xos-apps/auto-scale/gui/.bowerrc b/xos-apps/auto-scale/gui/.bowerrc
new file mode 100644
index 0000000..e491038
--- /dev/null
+++ b/xos-apps/auto-scale/gui/.bowerrc
@@ -0,0 +1,3 @@
+{
+ "directory": "src/vendor/"
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/.editorconfig b/xos-apps/auto-scale/gui/.editorconfig
new file mode 100644
index 0000000..e717f5e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/.editorconfig
@@ -0,0 +1,13 @@
+# http://editorconfig.org
+root = true
+
+[*]
+indent_style = space
+indent_size = 2
+end_of_line = lf
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+
+[*.md]
+trim_trailing_whitespace = false
diff --git a/xos-apps/auto-scale/gui/.eslintrc b/xos-apps/auto-scale/gui/.eslintrc
new file mode 100644
index 0000000..868fd4b
--- /dev/null
+++ b/xos-apps/auto-scale/gui/.eslintrc
@@ -0,0 +1,44 @@
+{
+ "ecmaFeatures": {
+ "blockBindings": true,
+ "forOf": true,
+ "destructuring": true,
+ "arrowFunctions": true,
+ "templateStrings": true
+ },
+ "env": {
+ "browser": true,
+ "node": true,
+ "es6": true
+ },
+ "plugins": [
+ //"angular"
+ ],
+ "rules": {
+ "quotes": [2, "single"],
+ "camelcase": [0, {"properties": "always"}],
+ "no-underscore-dangle": 1,
+ "eqeqeq": [2, "smart"],
+ "no-alert": 1,
+ "key-spacing": [1, { "beforeColon": false, "afterColon": true }],
+ "indent": [2, 2],
+ "no-irregular-whitespace": 1,
+ "eol-last": 0,
+ "max-nested-callbacks": [2, 4],
+ "comma-spacing": [1, {"before": false, "after": true}],
+ "no-trailing-spaces": [1, { skipBlankLines: true }],
+ "no-unused-vars": [1, {"vars": "all", "args": "after-used"}],
+ "new-cap": 0,
+ "no-undef": 2,
+
+ //"angular/ng_module_name": [2, '/^xos\.*[a-z]*$/'],
+ //"angular/ng_controller_name": [2, '/^[a-z].*Ctrl$/'],
+ //"angular/ng_service_name": [2, '/^[A-Z].*Service$/'],
+ //"angular/ng_directive_name": [2, '/^[a-z]+[[A-Z].*]*$/'],
+ //"angular/ng_di": [0, "function or array"]
+ },
+ "globals" :{
+ "angular": true,
+ "Chart": true
+ }
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/.gitignore b/xos-apps/auto-scale/gui/.gitignore
new file mode 100644
index 0000000..01b919d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/.gitignore
@@ -0,0 +1,7 @@
+node_modules/
+bower_components/
+coverage/
+.sass-cache/
+.idea/
+.tmp/
+dist/
diff --git a/xos-apps/auto-scale/gui/bower.json b/xos-apps/auto-scale/gui/bower.json
new file mode 100644
index 0000000..0ec36ae
--- /dev/null
+++ b/xos-apps/auto-scale/gui/bower.json
@@ -0,0 +1,38 @@
+{
+ "name": "xos-ceilometerDashboard",
+ "version": "0.0.0",
+ "authors": [
+ "Matteo Scandolo <teo@onlab.us>"
+ ],
+ "description": "The ceilometerDashboard view",
+ "license": "MIT",
+ "ignore": [
+ "**/.*",
+ "node_modules",
+ "bower_components",
+ "static/js/vendor/",
+ "test",
+ "tests"
+ ],
+ "dependencies": {
+ "angular-chart.js": "~0.8.7",
+ "angular-animate": "~1.4.8",
+ "ui.bootstrap": "~0.14.3",
+ "jquery": "~2.1.4",
+ "angular": "~1.4.7",
+ "angular-ui-router": "~0.2.15",
+ "ng-lodash": "~0.3.0",
+ "bootstrap-css": "3.3.4"
+ },
+ "overrides": {
+ "ui.bootstrap": {
+ "main": [
+ "src/accordion/accordion.js",
+ "src/collapse/collapse.js"
+ ]
+ }
+ },
+ "devDependencies": {
+ "angular-mocks": "~1.4.8"
+ }
+}
diff --git a/xos-apps/auto-scale/gui/env/default.js b/xos-apps/auto-scale/gui/env/default.js
new file mode 100644
index 0000000..8d4546d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/env/default.js
@@ -0,0 +1,3 @@
+module.exports = {
+ host: 'http://clnode015.clemson.cloudlab.us:9991'
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/env/srikanth.js b/xos-apps/auto-scale/gui/env/srikanth.js
new file mode 100644
index 0000000..0489fb9
--- /dev/null
+++ b/xos-apps/auto-scale/gui/env/srikanth.js
@@ -0,0 +1,3 @@
+module.exports = {
+ host: 'http://128.104.222.16:9991'
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/gulp/build.js b/xos-apps/auto-scale/gui/gulp/build.js
new file mode 100644
index 0000000..9f9bfb8
--- /dev/null
+++ b/xos-apps/auto-scale/gui/gulp/build.js
@@ -0,0 +1,149 @@
+'use strict';
+
+// BUILD
+//
+// The only purpose of this gulpfile is to build a XOS view and copy the correct files into
+// .html => dashboards
+// .js (minified and concat) => static/js
+//
+// The template are parsed and added to js with angular $templateCache
+
+var gulp = require('gulp');
+var ngAnnotate = require('gulp-ng-annotate');
+var uglify = require('gulp-uglify');
+var templateCache = require('gulp-angular-templatecache');
+var runSequence = require('run-sequence');
+var concat = require('gulp-concat');
+var del = require('del');
+var wiredep = require('wiredep');
+var angularFilesort = require('gulp-angular-filesort');
+var _ = require('lodash');
+var eslint = require('gulp-eslint');
+var inject = require('gulp-inject');
+var rename = require('gulp-rename');
+var replace = require('gulp-replace');
+var postcss = require('gulp-postcss');
+var autoprefixer = require('autoprefixer');
+var mqpacker = require('css-mqpacker');
+var csswring = require('csswring');
+
+var TEMPLATE_FOOTER = `}]);
+angular.module('xos.ceilometerDashboard').run(function($location){$location.path('/')});
+angular.bootstrap(angular.element('#xosCeilometerDashboard'), ['xos.ceilometerDashboard']);`;
+
+module.exports = function(options){
+
+ // delete previous builded file
+ gulp.task('clean', function(){
+ return del(
+ [options.dashboards + 'xosCeilometerDashboard.html'],
+ {force: true}
+ );
+ });
+
+ // minify css
+ gulp.task('css', function () {
+ var processors = [
+ autoprefixer({browsers: ['last 1 version']}),
+ mqpacker,
+ csswring
+ ];
+
+ gulp.src([
+ `${options.css}**/*.css`,
+ `!${options.css}dev.css`
+ ])
+ .pipe(postcss(processors))
+ .pipe(gulp.dest(options.tmp + '/css/'));
+ });
+
+ gulp.task('copyCss', ['css'], function(){
+ return gulp.src([`${options.tmp}/css/*.css`])
+ .pipe(concat('xosCeilometerDashboard.css'))
+ .pipe(gulp.dest(options.static + 'css/'))
+ });
+
+ // compile and minify scripts
+ gulp.task('scripts', function() {
+ return gulp.src([
+ options.tmp + '**/*.js'
+ ])
+ .pipe(ngAnnotate())
+ .pipe(angularFilesort())
+ .pipe(concat('xosCeilometerDashboard.js'))
+ .pipe(uglify())
+ .pipe(gulp.dest(options.static + 'js/'));
+ });
+
+ // set templates in cache
+ gulp.task('templates', function(){
+ return gulp.src('./src/templates/*.html')
+ .pipe(templateCache({
+ module: 'xos.ceilometerDashboard',
+ root: 'templates/',
+ templateFooter: TEMPLATE_FOOTER
+ }))
+ .pipe(gulp.dest(options.tmp));
+ });
+
+ // copy html index to Django Folder
+ gulp.task('copyHtml', ['clean'], function(){
+ return gulp.src(options.src + 'index.html')
+ // remove dev dependencies from html
+ .pipe(replace(/<!-- bower:css -->(\n.*)*\n<!-- endbower --><!-- endcss -->/, ''))
+ .pipe(replace(/<!-- bower:js -->(\n.*)*\n<!-- endbower --><!-- endjs -->/, ''))
+ .pipe(replace(/ng-app=".*"\s/, ''))
+ //rewriting css path
+ // .pipe(replace(/(<link.*">)/, ''))
+ // injecting minified files
+ .pipe(
+ inject(
+ gulp.src([
+ options.static + 'js/vendor/xosCeilometerDashboardVendor.js',
+ options.static + 'js/xosCeilometerDashboard.js',
+ options.static + 'css/xosCeilometerDashboard.css'
+ ])
+ )
+ )
+ .pipe(rename('xosCeilometerDashboard.html'))
+ .pipe(gulp.dest(options.dashboards));
+ });
+
+ // minify vendor js files
+ gulp.task('wiredep', function(){
+ var bowerDeps = wiredep().js;
+ if(!bowerDeps){
+ return;
+ }
+
+ // remove angular (it's already loaded)
+ _.remove(bowerDeps, function(dep){
+ return dep.indexOf('angular/angular.js') !== -1;
+ });
+
+ return gulp.src(bowerDeps)
+ .pipe(concat('xosCeilometerDashboardVendor.js'))
+ .pipe(uglify())
+ .pipe(gulp.dest(options.static + 'js/vendor/'));
+ });
+
+ gulp.task('lint', function () {
+ return gulp.src(['src/js/**/*.js'])
+ .pipe(eslint())
+ .pipe(eslint.format())
+ .pipe(eslint.failAfterError());
+ });
+
+ gulp.task('build', function() {
+ runSequence(
+ 'lint',
+ 'templates',
+ 'babel',
+ 'scripts',
+ 'wiredep',
+ 'copyHtml',
+ 'copyCss',
+ 'cleanTmp'
+ );
+ });
+};
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/gulp/server.js b/xos-apps/auto-scale/gui/gulp/server.js
new file mode 100644
index 0000000..0f69064
--- /dev/null
+++ b/xos-apps/auto-scale/gui/gulp/server.js
@@ -0,0 +1,149 @@
+'use strict';
+
+var gulp = require('gulp');
+var browserSync = require('browser-sync').create();
+var inject = require('gulp-inject');
+var runSequence = require('run-sequence');
+var angularFilesort = require('gulp-angular-filesort');
+var babel = require('gulp-babel');
+var wiredep = require('wiredep').stream;
+var del = require('del');
+var httpProxy = require('http-proxy');
+
+const environment = process.env.NODE_ENV;
+
+if (environment){
+ var conf = require(`../env/${environment}.js`);
+}
+else{
+ var conf = require('../env/default.js')
+}
+
+console.log(conf);
+
+var proxy = httpProxy.createProxyServer({
+ target: conf.host || 'http://0.0.0.0:9999'
+});
+
+proxy.on('error', function(error, req, res) {
+ res.writeHead(500, {
+ 'Content-Type': 'text/plain'
+ });
+
+ console.error('[Proxy]', error);
+});
+
+module.exports = function(options){
+
+ // open in browser with sync and proxy to 0.0.0.0
+ gulp.task('browser', function() {
+ browserSync.init({
+ // reloadDelay: 500,
+ // logLevel: 'debug',
+ // logConnections: true,
+ // directory: true,
+ startPath: '#/',
+ snippetOptions: {
+ rule: {
+ match: /<!-- browserSync -->/i
+ }
+ },
+ server: {
+ baseDir: options.src,
+ middleware: function(req, res, next){
+ if(
+ req.url.indexOf('autoscaledata') !== -1
+ ){
+ proxy.web(req, res);
+ }
+ else{
+ next();
+ }
+ }
+ }
+ });
+
+ gulp.watch(options.src + 'js/**/*.js', ['js-watch']);
+
+ gulp.watch(options.src + 'vendor/**/*.js', ['bower'], function(){
+ browserSync.reload();
+ });
+ gulp.watch(options.src + '**/*.html', function(){
+ browserSync.reload();
+ });
+ gulp.watch(options.src + '**/*.css', function(){
+ browserSync.reload();
+ });
+ });
+
+ // transpile js with sourceMaps
+ gulp.task('babel', function(){
+ return gulp.src([options.scripts + '**/*.js'])
+ .pipe(babel({sourceMaps: true}))
+ .pipe(gulp.dest(options.tmp));
+ });
+
+ // inject scripts
+ gulp.task('injectScript', function(){
+ runSequence(
+ 'cleanTmp',
+ 'babel',
+ function() {
+ return gulp.src(options.src + 'index.html')
+ .pipe(
+ inject(
+ gulp.src([
+ options.tmp + '**/*.js',
+ options.api + '*.js',
+ options.helpers + '**/*.js'
+ ])
+ // .pipe(debug({title: 'unicorn:'}))
+ .pipe(angularFilesort()),
+ {
+ ignorePath: [options.src, '/../../ngXosLib']
+ }
+ )
+ )
+ .pipe(gulp.dest(options.src));
+ }
+ );
+ });
+
+ // inject CSS
+ gulp.task('injectCss', function(){
+ return gulp.src(options.src + 'index.html')
+ .pipe(
+ inject(
+ gulp.src(options.src + 'css/*.css'),
+ {
+ ignorePath: [options.src]
+ }
+ )
+ )
+ .pipe(gulp.dest(options.src));
+ });
+
+ // inject bower dependencies with wiredep
+ gulp.task('bower', function () {
+ return gulp.src(options.src + 'index.html')
+ .pipe(wiredep({devDependencies: true}))
+ .pipe(gulp.dest(options.src));
+ });
+
+ gulp.task('js-watch', ['injectScript'], function(){
+ browserSync.reload();
+ });
+
+ gulp.task('cleanTmp', function(){
+ return del([options.tmp + '**/*']);
+ });
+
+ gulp.task('serve', function() {
+ runSequence(
+ 'bower',
+ 'injectScript',
+ 'injectCss',
+ ['browser']
+ );
+ });
+};
diff --git a/xos-apps/auto-scale/gui/gulpfile.js b/xos-apps/auto-scale/gui/gulpfile.js
new file mode 100644
index 0000000..de911e9
--- /dev/null
+++ b/xos-apps/auto-scale/gui/gulpfile.js
@@ -0,0 +1,25 @@
+'use strict';
+
+var gulp = require('gulp');
+var wrench = require('wrench');
+
+var options = {
+ src: 'src/',
+ css: 'src/css/',
+ scripts: 'src/js/',
+ tmp: 'src/.tmp',
+ dist: 'dist/',
+ api: '../../ngXosLib/api/',
+ helpers: '../../ngXosLib/xosHelpers/src/',
+ static: '../../static/', // this is the django static folder
+ dashboards: '../../dashboards/' // this is the django html folder
+};
+
+wrench.readdirSyncRecursive('./gulp')
+.map(function(file) {
+ require('./gulp/' + file)(options);
+});
+
+gulp.task('default', function () {
+ gulp.start('build');
+});
diff --git a/xos-apps/auto-scale/gui/karma.conf.js b/xos-apps/auto-scale/gui/karma.conf.js
new file mode 100644
index 0000000..b67c208
--- /dev/null
+++ b/xos-apps/auto-scale/gui/karma.conf.js
@@ -0,0 +1,94 @@
+// Karma configuration
+// Generated on Tue Oct 06 2015 09:27:10 GMT+0000 (UTC)
+
+/* eslint indent: [2,2], quotes: [2, "single"]*/
+
+/*eslint-disable*/
+var wiredep = require('wiredep');
+var path = require('path');
+
+var bowerComponents = wiredep( {devDependencies: true} )[ 'js' ].map(function( file ){
+ return path.relative(process.cwd(), file);
+});
+/*eslint-enable*/
+module.exports = function(config) {
+ config.set({
+
+ // base path that will be used to resolve all patterns (eg. files, exclude)
+ basePath: '',
+
+
+ // frameworks to use
+ // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
+ frameworks: ['jasmine'],
+
+
+ // list of files / patterns to load in the browser
+ files: bowerComponents.concat([
+ 'src/css/**/*.css',
+ 'src/js/main.js',
+ 'src/js/**/*.js',
+ 'spec/**/*.mock.js',
+ 'spec/**/*.test.js',
+ 'src/**/*.html'
+ ]),
+
+
+ // list of files to exclude
+ exclude: [
+ ],
+
+
+ // preprocess matching files before serving them to the browser
+ // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
+ preprocessors: {
+ 'src/js/**/*.js': ['babel'],
+ 'spec/**/*.js': ['babel'],
+ 'src/**/*.html': ['ng-html2js']
+ },
+
+ babelPreprocessor: {
+ options: {
+ presets: ['es2015'],
+ sourceMap: 'inline'
+ }
+ },
+
+ ngHtml2JsPreprocessor: {
+ stripPrefix: 'src/', //strip the src path from template url (http://stackoverflow.com/questions/22869668/karma-unexpected-request-when-testing-angular-directive-even-with-ng-html2js)
+ moduleName: 'templates' // define the template module name
+ },
+
+ // test results reporter to use
+ // possible values: 'dots', 'progress'
+ // available reporters: https://npmjs.org/browse/keyword/karma-reporter
+ reporters: ['mocha'],
+
+
+ // web server port
+ port: 9876,
+
+
+ // enable / disable colors in the output (reporters and logs)
+ colors: true,
+
+
+ // level of logging
+ // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
+ logLevel: config.LOG_INFO,
+
+
+ // enable / disable watching file and executing tests whenever any file changes
+ autoWatch: true,
+
+
+ // start these browsers
+ // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
+ browsers: ['PhantomJS'],
+
+
+ // Continuous Integration mode
+ // if true, Karma captures browsers, runs the tests and exits
+ singleRun: false
+ });
+};
diff --git a/xos-apps/auto-scale/gui/package.json b/xos-apps/auto-scale/gui/package.json
new file mode 100644
index 0000000..0a9ccae
--- /dev/null
+++ b/xos-apps/auto-scale/gui/package.json
@@ -0,0 +1,62 @@
+{
+ "name": "xos-ceilometerDashboard",
+ "version": "1.0.0",
+ "description": "Angular Application for XOS, created with generator-xos",
+ "scripts": {
+ "prestart": "npm install && bower install",
+ "start": "gulp serve",
+ "prebuild": "npm install && bower install",
+ "build": "gulp",
+ "pretest": "npm install",
+ "test": "karma start",
+ "lint": "eslint src/js/"
+ },
+ "keywords": [
+ "XOS",
+ "Angular",
+ "XOSlib"
+ ],
+ "author": "Matteo Scandolo",
+ "license": "MIT",
+ "dependencies": {},
+ "devDependencies": {
+ "autoprefixer": "^6.1.2",
+ "babel": "^6.3.13",
+ "babel-preset-es2015": "^6.3.13",
+ "browser-sync": "^2.9.11",
+ "css-mqpacker": "^4.0.0",
+ "csswring": "^4.1.1",
+ "del": "^2.0.2",
+ "eslint": "^1.8.0",
+ "eslint-plugin-angular": "linkmesrl/eslint-plugin-angular",
+ "gulp": "^3.9.0",
+ "gulp-angular-filesort": "^1.1.1",
+ "gulp-angular-templatecache": "^1.8.0",
+ "gulp-babel": "^5.3.0",
+ "gulp-concat": "^2.6.0",
+ "gulp-debug": "^2.1.2",
+ "gulp-eslint": "^1.0.0",
+ "gulp-inject": "^3.0.0",
+ "gulp-minify-html": "^1.0.4",
+ "gulp-ng-annotate": "^1.1.0",
+ "gulp-postcss": "^6.0.1",
+ "gulp-rename": "^1.2.2",
+ "gulp-replace": "^0.5.4",
+ "gulp-uglify": "^1.4.2",
+ "http-proxy": "^1.12.0",
+ "jasmine-core": "^2.4.1",
+ "karma": "^0.13.15",
+ "karma-babel-preprocessor": "^6.0.1",
+ "karma-jasmine": "^0.3.6",
+ "karma-mocha-reporter": "^1.1.3",
+ "karma-ng-html2js-preprocessor": "^0.2.0",
+ "karma-phantomjs-launcher": "^0.2.1",
+ "lodash": "^3.10.1",
+ "mocha": "^2.3.4",
+ "phantomjs": "^1.9.19",
+ "proxy-middleware": "^0.15.0",
+ "run-sequence": "^1.1.4",
+ "wiredep": "^3.0.0-beta",
+ "wrench": "^1.5.8"
+ }
+}
diff --git a/xos-apps/auto-scale/gui/spec/.eslintrc b/xos-apps/auto-scale/gui/spec/.eslintrc
new file mode 100644
index 0000000..ad4bc2d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/spec/.eslintrc
@@ -0,0 +1,9 @@
+{
+ "globals" :{
+ "describe": true,
+ "beforeEach": true,
+ "it": true,
+ "inject": true,
+ "expect": true
+ }
+}
diff --git a/xos-apps/auto-scale/gui/spec/autoscaling.test.js b/xos-apps/auto-scale/gui/spec/autoscaling.test.js
new file mode 100644
index 0000000..54caf0e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/spec/autoscaling.test.js
@@ -0,0 +1,48 @@
+'use strict';
+
+describe('In autoscaling app', () => {
+ var scope, element, vm, httpBackend, Service;
+
+
+
+ beforeEach(module('autoscaling'));
+ beforeEach(module('templates'));
+
+ beforeEach(inject(($httpBackend, $rootScope, Autoscaling) => {
+ httpBackend = $httpBackend;
+ scope = $rootScope.$new();
+ Service = Autoscaling;
+ }));
+
+ describe('the serviceContainer', () => {
+ beforeEach(inject(function($httpBackend, $compile){
+
+ httpBackend.whenGET('/autoscaledata').respond(200, autoscalingMock);
+
+ element = angular.element('<service-container></service-container>');
+ $compile(element)(scope);
+
+ scope.$digest();
+ vm = element.isolateScope().vm;
+ httpBackend.flush();
+ }));
+
+ it('should correctly format data', () => {
+ expect(vm.services['service1']).toBeDefined();
+ expect(vm.services['service1']['slice1']).toBeDefined();
+ expect(vm.services['service1']['slice1']['instance1']).toBeDefined();
+
+ expect(vm.services['service1']['slice1']['instance1'][0].counter_volume).toBe(10);
+ expect(vm.services['service1']['slice1']['instance1'][1].counter_volume).toBe(11);
+
+ // triggering the function with 2 resources
+ vm.printData(Service.formatData(autoscalingMock2instances));
+
+ const keys = Object.keys(vm.services['service1']['slice1']);
+
+ expect(vm.services['service1']['slice1'][keys[0]][0].counter_volume).toBe(10);
+ expect(vm.services['service1']['slice1'][keys[0]][1].counter_volume).toBe(11);
+
+ });
+ });
+});
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/spec/autoscaling_data.mock.js b/xos-apps/auto-scale/gui/spec/autoscaling_data.mock.js
new file mode 100644
index 0000000..e9f637a
--- /dev/null
+++ b/xos-apps/auto-scale/gui/spec/autoscaling_data.mock.js
@@ -0,0 +1,64 @@
+var autoscalingMock =[
+ {
+ 'slice': 'slice1',
+ 'service': 'service1',
+ 'project_id': 'project1',
+ 'resources': {
+ 'resource1': {
+ 'queue': [
+ {
+ 'timestamp': '2015-12-17T22:55:36Z',
+ 'counter_volume': 10,
+ },
+ {
+ 'timestamp': '2015-12-17T22:55:46Z',
+ 'counter_volume': 11,
+ }
+ ],
+ 'xos_instance_info': {
+ 'instance_name': 'instance1'
+ }
+ }
+ }
+ }
+];
+
+var autoscalingMock2instances =[
+ {
+ 'slice': 'slice1',
+ 'service': 'service1',
+ 'project_id': 'project1',
+ 'resources': {
+ 'resource2': {
+ 'queue': [
+ {
+ 'timestamp': '2015-12-17T22:55:36Z',
+ 'counter_volume': 20,
+ },
+ {
+ 'timestamp': '2015-12-17T22:55:46Z',
+ 'counter_volume': 21,
+ }
+ ],
+ 'xos_instance_info': {
+ 'instance_name': 'instance2'
+ }
+ },
+ 'resource1': {
+ 'queue': [
+ {
+ 'timestamp': '2015-12-17T22:55:36Z',
+ 'counter_volume': 10,
+ },
+ {
+ 'timestamp': '2015-12-17T22:55:46Z',
+ 'counter_volume': 11,
+ }
+ ],
+ 'xos_instance_info': {
+ 'instance_name': 'instance1'
+ }
+ },
+ }
+ }
+];
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/css/style.css b/xos-apps/auto-scale/gui/src/css/style.css
new file mode 100644
index 0000000..260b6df
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/css/style.css
@@ -0,0 +1,134 @@
+body {
+ padding-top: 50px;
+}
+
+.list-group-item.active > a {
+ color: white;
+}
+
+/* ANIMATION */
+.animate-repeat{
+ /*background: red;*/
+}
+
+.animate-repeat.ng-move,
+.animate-repeat.ng-enter,
+.animate-repeat.ng-leave {
+ transition:all linear 0.5s;
+}
+
+/* Element Exit */
+.animate-repeat.ng-leave.ng-leave-active,
+.animate-repeat.ng-move,
+.animate-repeat.ng-enter {
+ /*opacity:0;*/
+ /*animation:1.5s bounceOutDown ease;*/
+}
+
+/* Element Enter */
+.animate-repeat.ng-leave,
+.animate-repeat.ng-move.ng-move-active,
+.animate-repeat.ng-enter.ng-enter-active {
+ /*opacity:1;*/
+ /*animation:1.5s bounceOutUp ease;*/
+}
+
+@keyframes bounceInUp {
+ from, 60%, 75%, 90%, to {
+ animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
+ }
+
+ from {
+ opacity: 0;
+ transform: translate3d(0, 3000px, 0);
+ }
+
+ 60% {
+ opacity: 1;
+ transform: translate3d(0, -20px, 0);
+ }
+
+ 75% {
+ transform: translate3d(0, 10px, 0);
+ }
+
+ 90% {
+ transform: translate3d(0, -5px, 0);
+ }
+
+ to {
+ transform: translate3d(0, 0, 0);
+ }
+}
+
+@keyframes bounceOutUp {
+ 20% {
+ transform: translate3d(0, -10px, 0);
+ }
+
+ 40%, 45% {
+ opacity: 1;
+ transform: translate3d(0, 20px, 0);
+ }
+
+ to {
+ opacity: 0;
+ transform: translate3d(0, -2000px, 0);
+ }
+}
+
+/* LOADER */
+.loader {
+ font-size: 10px;
+ margin: 150px auto;
+ text-indent: -9999em;
+ width: 11em;
+ height: 11em;
+ border-radius: 50%;
+ background: #ffffff;
+ background: -moz-linear-gradient(left, #ffffff 10%, rgba(255, 255, 255, 0) 42%);
+ background: -webkit-linear-gradient(left, #ffffff 10%, rgba(255, 255, 255, 0) 42%);
+ background: -o-linear-gradient(left, #ffffff 10%, rgba(255, 255, 255, 0) 42%);
+ background: -ms-linear-gradient(left, #ffffff 10%, rgba(255, 255, 255, 0) 42%);
+ background: linear-gradient(to right, #ffffff 10%, rgba(255, 255, 255, 0) 42%);
+ position: relative;
+ -webkit-animation: load3 1.4s infinite linear;
+ animation: load3 1.4s infinite linear;
+ -webkit-transform: translateZ(0);
+ -ms-transform: translateZ(0);
+ transform: translateZ(0);
+}
+.loader:before {
+ width: 50%;
+ height: 50%;
+ background: #105E9E;
+ border-radius: 100% 0 0 0;
+ position: absolute;
+ top: 0;
+ left: 0;
+ content: '';
+}
+.loader:after {
+ background: #fff;
+ width: 75%;
+ height: 75%;
+ border-radius: 50%;
+ content: '';
+ margin: auto;
+ position: absolute;
+ top: 0;
+ left: 0;
+ bottom: 0;
+ right: 0;
+}
+
+@keyframes load3 {
+ 0% {
+ -webkit-transform: rotate(0deg);
+ transform: rotate(0deg);
+ }
+ 100% {
+ -webkit-transform: rotate(360deg);
+ transform: rotate(360deg);
+ }
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/index.html b/xos-apps/auto-scale/gui/src/index.html
new file mode 100644
index 0000000..51bad93
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/index.html
@@ -0,0 +1,72 @@
+<!-- browserSync -->
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <title>XOS - Autoscaling Framework</title>
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1, max-scale=1">
+ <!-- bower:css -->
+ <link rel="stylesheet" href="vendor/angular-chart.js/dist/angular-chart.css" />
+ <link rel="stylesheet" href="vendor/bootstrap-css/css/bootstrap.min.css" />
+ <!-- endbower --><!-- endcss -->
+ <!-- inject:css -->
+ <link rel="stylesheet" href="/css/style.css">
+ <!-- endinject -->
+</head>
+<body>
+
+</body>
+</html>
+
+<div ng-app="autoscaling">
+
+ <nav class="navbar navbar-inverse navbar-fixed-top">
+ <div class="container">
+ <div class="navbar-header">
+ <!-- <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
+ <span class="sr-only">Toggle navigation</span>
+ <span class="icon-bar"></span>
+ <span class="icon-bar"></span>
+ <span class="icon-bar"></span>
+ </button> -->
+ <a class="navbar-brand" href="#">XOS - Autoscaling Framework</a>
+ </div>
+ <!-- <div id="navbar" class="collapse navbar-collapse">
+ <ul class="nav navbar-nav">
+ <li class="active"><a href="#">Home</a></li>
+ <li><a href="#about">About</a></li>
+ <li><a href="#contact">Contact</a></li>
+ </ul>
+ </div><!--/.nav-collapse --> -->
+ </div>
+ </nav>
+
+ <div class="container">
+ <div class="row">
+ <div class="col-xs-12">
+ <div ui-view ng-class="stateName"></div>
+ </div>
+ </div>
+ </div>
+ <!-- bower:js -->
+ <script src="vendor/angular/angular.js"></script>
+ <script src="vendor/Chart.js/Chart.js"></script>
+ <script src="vendor/angular-chart.js/dist/angular-chart.js"></script>
+ <script src="vendor/angular-animate/angular-animate.js"></script>
+ <script src="vendor/ui.bootstrap/src/accordion/accordion.js"></script>
+ <script src="vendor/ui.bootstrap/src/collapse/collapse.js"></script>
+ <script src="vendor/jquery/dist/jquery.js"></script>
+ <script src="vendor/angular-ui-router/release/angular-ui-router.js"></script>
+ <script src="vendor/ng-lodash/build/ng-lodash.js"></script>
+ <script src="vendor/bootstrap-css/js/bootstrap.min.js"></script>
+ <script src="vendor/angular-mocks/angular-mocks.js"></script>
+ <!-- endbower --><!-- endjs -->
+
+ <!-- inject:js -->
+ <script src="/.tmp/main.js"></script>
+ <script src="/.tmp/autoscaling_details.directive.js"></script>
+ <script src="/.tmp/autoscaling.service.js"></script>
+ <!-- endinject -->
+</div>
+
diff --git a/xos-apps/auto-scale/gui/src/js/autoscaling.service.js b/xos-apps/auto-scale/gui/src/js/autoscaling.service.js
new file mode 100644
index 0000000..2762fe7
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/js/autoscaling.service.js
@@ -0,0 +1,71 @@
+'use strict';
+
+angular.module('autoscaling')
+.service('Autoscaling', function($http, $interval, $rootScope, lodash, $q){
+
+ const pollingFrequency = 10;
+ var pollinginterval;
+
+ /**
+ * Convert data to a flat array of resources
+ */
+
+ this.formatData = (data) => {
+ const list = [];
+ // cicle trough all slices
+ lodash.map(data, (item) => {
+ // cicle trough every resource
+ item.resources = lodash.forEach(
+ Object.keys(item.resources),
+ (resource) => {
+ const tmp = item.resources[resource];
+ tmp.service = item.service;
+ tmp.slice = item.slice;
+ tmp.project_id = item.project_id;
+ tmp.instance_name = tmp.xos_instance_info.instance_name;
+ delete tmp.xos_instance_info;
+ list.push(tmp);
+ }
+ )
+ });
+ return list;
+ };
+
+ function requestData(url){
+
+ const deferred = $q.defer();
+
+ $http.get(url)
+ .success((res) => {
+ deferred.resolve(res);
+ })
+ .error((e) => {
+ deferred.reject(e);
+ });
+
+ return deferred.promise;
+ };
+
+
+ // TODO Move to Websocket
+ this.getAutoscalingData = () => {
+
+ requestData('/autoscaledata')
+ .then((res) => {
+ $rootScope.$emit('autoscaling.update', this.formatData(res));
+ })
+ .catch((e) => {
+ $rootScope.$emit('autoscaling.error', this.formatData(e));
+ });
+
+ pollinginterval = $interval(() => {
+ requestData('/autoscaledata')
+ .then((res) => {
+ $rootScope.$emit('autoscaling.update', this.formatData(res));
+ })
+ .catch((e) => {
+ $rootScope.$emit('autoscaling.error', this.formatData(e));
+ });
+ }, pollingFrequency * 1000)
+ };
+});
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/js/autoscaling_details.directive.js b/xos-apps/auto-scale/gui/src/js/autoscaling_details.directive.js
new file mode 100644
index 0000000..76cce2d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/js/autoscaling_details.directive.js
@@ -0,0 +1,197 @@
+angular.module('autoscaling')
+.directive('serviceContainer', function(lodash, Autoscaling){
+ return {
+ restrict: 'E',
+ scope: {},
+ bindToController: true,
+ controllerAs: 'vm',
+ templateUrl: 'templates/service-container.tpl.html',
+ controller: function($rootScope) {
+
+ this.loader = true;
+
+ // set to true when a service is manually selected
+ this.manualSelect = false;
+
+ // start polling
+ Autoscaling.getAutoscalingData();
+
+ // list to polling events
+ $rootScope.$on('autoscaling.update', (evt, data) => {
+
+ if (data.length > 0) {
+ this.loader = false;
+ };
+ this.printData(data);
+ });
+
+ // handle errors
+ $rootScope.$on('autoscaling.error', (evt, err) => {
+ this.loader = false;
+ this.error = err.data.message;
+ });
+
+ /**
+ * Group resources by service and slice
+ */
+ this.printData = (data) => {
+ this.services = lodash.groupBy(data, 'service');
+ lodash.forEach(Object.keys(this.services), (service) => {
+ this.services[service] = lodash.groupBy(this.services[service], 'slice');
+ lodash.forEach(Object.keys(this.services[service]), (slice) => {
+ // grouping instance by name
+ this.services[service][slice] = lodash.groupBy(this.services[service][slice], 'instance_name');
+ // instance can't have the same name,
+ // so take them out of an array
+ // and keep only the sample data
+ lodash.forEach(Object.keys(this.services[service][slice]), (instance) => {
+ // TODO maintain the instance order
+ this.services[service][slice][instance] = this.services[service][slice][instance][0].queue;
+ });
+
+ })
+ });
+ // arbitrary set the first service in the list as the selected one
+ if(!this.manualSelect){
+ this.serviceName = Object.keys(this.services)[0];
+ this.selectedService = this.services[Object.keys(this.services)[0]];
+ }
+ else{
+ this.selectedService = this.services[this.serviceName]
+ }
+ };
+
+ /**
+ * Change the current selected service
+ */
+
+ this.selectService = (serviceName) => {
+ this.serviceName = serviceName;
+ this.selectedService = this.services[serviceName];
+ this.manualSelect = true;
+ };
+ }
+ };
+})
+.directive('serviceDetail', function(lodash){
+ return {
+ restrict: 'E',
+ scope: {
+ service: '=service'
+ },
+ bindToController: true,
+ controllerAs: 'vm',
+ templateUrl: 'templates/service-detail.tpl.html',
+ controller: function($scope) {
+
+ }
+ };
+})
+.directive('sliceDetail', function(lodash){
+ return {
+ restrict: 'E',
+ scope: {
+ instances: '=instances'
+ },
+ bindToController: true,
+ controllerAs: 'vm',
+ templateUrl: 'templates/slice-detail.tpl.html',
+ controller: function($scope, $timeout) {
+
+ this.chart = {
+ options: {
+ datasetFill: false,
+ animation: true,
+ // animationEasing: 'easeInBack'
+ }
+ };
+
+ this.chartColors = [
+ '#286090',
+ '#F7464A',
+ '#46BFBD',
+ '#FDB45C',
+ '#97BBCD',
+ '#4D5360',
+ '#8c4f9f'
+ ];
+
+ Chart.defaults.global.colours = this.chartColors;
+
+ /**
+ * Goes trough the array and format date to be used as labels
+ *
+ * @param Array data
+ * @returns Array a list of labels
+ */
+
+ this.getLabels = (data) => {
+ // we should compare the labels and get the last available
+ return this.prependValues(
+ data.reduce((list, item) => {
+ let date = new Date(item.timestamp);
+ list.push(`${date.getHours()}:${(date.getMinutes()<10?'0':'') + date.getMinutes()}:${date.getSeconds()}`);
+ return list;
+ }, [])
+ , '');
+ };
+
+ /**
+ * Prepend value if the array is less than 10 element
+ */
+ this.prependValues = (list, value) => {
+ if(list.length < 10){
+ list.unshift(value);
+ // call itself to check again
+ return this.prependValues(list, value);
+ }
+ return list;
+ }
+
+ /**
+ * Convert an object of array,
+ * in an array of arrays of values
+ */
+ this.getData = (data, instanceNames) => {
+ return lodash.map(instanceNames, (item) => {
+ return this.prependValues(lodash.reduce(data[item], (list, sample) => {
+ // console.log(data[item], sample);
+ list.push(sample.counter_volume);
+ return list;
+ }, []), null);
+ });
+ };
+
+ this.getMostRecentSeries = (instances) => {
+ // console.log(instances);
+ const newestValues = [];
+ instances = lodash.toArray(instances)
+ lodash.forEach(instances, (values) => {
+ newestValues.push(lodash.max(values, item => new Date(item.timestamp)));
+ });
+
+ var highestValue = 0;
+ var newestInstanceIndex = lodash.findIndex(newestValues, (val) => {
+ return new Date(val.timestamp) > highestValue;
+ });
+
+ return instances[newestInstanceIndex]
+ }
+
+ this.drawChart = (data) => {
+
+ const instanceNames = Object.keys(data);
+
+ this.chart.labels = this.getLabels(this.getMostRecentSeries(data));
+ this.chart.series = instanceNames;
+ this.chart.data = this.getData(data, instanceNames);
+ }
+
+ $scope.$watch(() => this.instances, (val) => {
+ $timeout(()=>{this.chart.options.animation = false}, 1000);
+ this.drawChart(val)
+ });
+
+ }
+ };
+});
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/js/main.js b/xos-apps/auto-scale/gui/src/js/main.js
new file mode 100644
index 0000000..468f355
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/js/main.js
@@ -0,0 +1,17 @@
+'use strict';
+
+angular.module('autoscaling', [
+ 'ngLodash',
+ 'ui.router',
+ 'ngAnimate',
+ 'chart.js'
+])
+.config(($stateProvider, $urlRouterProvider) => {
+ $stateProvider
+ .state('ceilometerDashboard', {
+ url: '/',
+ template: '<service-container></service-container>'
+ });
+
+ $urlRouterProvider.otherwise('/');
+});
diff --git a/xos-apps/auto-scale/gui/src/mocks/mock.json b/xos-apps/auto-scale/gui/src/mocks/mock.json
new file mode 100644
index 0000000..aa91dd2
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/mocks/mock.json
@@ -0,0 +1 @@
+[{"slice": "mysite_onos_volt", "service": "service_ONOS_vOLT", "lthreadshold_count": 1, "alarm": "scale_down_eval", "uthreadshold_count": 0, "project_id": "bfef8341327245d682c7bada50aceecb", "resources": {"71863bc9-1840-4014-9a7c-fee8d94d3f77": {"queue": [{"counter_name": "cpu_util", "resource_id": "71863bc9-1840-4014-9a7c-fee8d94d3f77", "timestamp": "2015-12-16T23:44:02Z", "counter_unit": "%", "counter_volume": 10.6, "project_id": "bfef8341327245d682c7bada50aceecb"}, {"counter_name": "cpu_util", "resource_id": "71863bc9-1840-4014-9a7c-fee8d94d3f77", "timestamp": "2015-12-16T23:44:12Z", "counter_unit": "%", "counter_volume": 11.1, "project_id": "bfef8341327245d682c7bada50aceecb"}, {"counter_name": "cpu_util", "resource_id": "71863bc9-1840-4014-9a7c-fee8d94d3f77", "timestamp": "2015-12-16T23:44:22Z", "counter_unit": "%", "counter_volume": 10.799999999999999, "project_id": "bfef8341327245d682c7bada50aceecb"}, {"counter_name": "cpu_util", "resource_id": "71863bc9-1840-4014-9a7c-fee8d94d3f77", "timestamp": "2015-12-16T23:44:32Z", "counter_unit": "%", "counter_volume": 9.9, "project_id": "bfef8341327245d682c7bada50aceecb"}, {"counter_name": "cpu_util", "resource_id": "71863bc9-1840-4014-9a7c-fee8d94d3f77", "timestamp": "2015-12-16T23:44:42Z", "counter_unit": "%", "counter_volume": 11.2, "project_id": "bfef8341327245d682c7bada50aceecb"}, {"counter_name": "cpu_util", "resource_id": "71863bc9-1840-4014-9a7c-fee8d94d3f77", "timestamp": "2015-12-16T23:44:52Z", "counter_unit": "%", "counter_volume": 11.1, "project_id": "bfef8341327245d682c7bada50aceecb"}], "xos_instance_info": {"instance_name": "mysite_onos_volt-4"}}}}, {"slice": "mysite_onos_vbng", "service": "service_ONOS_vBNG", "lthreadshold_count": 1, "alarm": "scale_down_eval", "uthreadshold_count": 0, "project_id": "7c918e6765c24ee281f3ee8692fd102c", "resources": {"4065c7d0-62bc-486a-ad3e-87603d2ab33b": {"queue": [{"counter_name": "cpu_util", "resource_id": "4065c7d0-62bc-486a-ad3e-87603d2ab33b", "timestamp": "2015-12-16T23:44:02Z", "counter_unit": "%", "counter_volume": 9.7, "project_id": "7c918e6765c24ee281f3ee8692fd102c"}, {"counter_name": "cpu_util", "resource_id": "4065c7d0-62bc-486a-ad3e-87603d2ab33b", "timestamp": "2015-12-16T23:44:12Z", "counter_unit": "%", "counter_volume": 11.5, "project_id": "7c918e6765c24ee281f3ee8692fd102c"}, {"counter_name": "cpu_util", "resource_id": "4065c7d0-62bc-486a-ad3e-87603d2ab33b", "timestamp": "2015-12-16T23:44:22Z", "counter_unit": "%", "counter_volume": 12.399999999999999, "project_id": "7c918e6765c24ee281f3ee8692fd102c"}, {"counter_name": "cpu_util", "resource_id": "4065c7d0-62bc-486a-ad3e-87603d2ab33b", "timestamp": "2015-12-16T23:44:32Z", "counter_unit": "%", "counter_volume": 11.299999999999999, "project_id": "7c918e6765c24ee281f3ee8692fd102c"}, {"counter_name": "cpu_util", "resource_id": "4065c7d0-62bc-486a-ad3e-87603d2ab33b", "timestamp": "2015-12-16T23:44:42Z", "counter_unit": "%", "counter_volume": 11.799999999999999, "project_id": "7c918e6765c24ee281f3ee8692fd102c"}, {"counter_name": "cpu_util", "resource_id": "4065c7d0-62bc-486a-ad3e-87603d2ab33b", "timestamp": "2015-12-16T23:44:52Z", "counter_unit": "%", "counter_volume": 12.299999999999999, "project_id": "7c918e6765c24ee281f3ee8692fd102c"}], "xos_instance_info": {"instance_name": "mysite_onos_vbng-2"}}}}, {"slice": "mysite_vcpe", "service": "service_vcpe", "lthreadshold_count": 1, "alarm": "scale_down_eval", "uthreadshold_count": 0, "project_id": "61a5d4b37b5d43718854916079760c0d", "resources": {"41625531-8243-4471-b435-574618df0484": {"queue": [{"counter_name": "cpu_util", "resource_id": "41625531-8243-4471-b435-574618df0484", "timestamp": "2015-12-16T23:44:02Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "61a5d4b37b5d43718854916079760c0d"}, {"counter_name": "cpu_util", "resource_id": "41625531-8243-4471-b435-574618df0484", "timestamp": "2015-12-16T23:44:12Z", "counter_unit": "%", "counter_volume": 0.0, "project_id": "61a5d4b37b5d43718854916079760c0d"}, {"counter_name": "cpu_util", "resource_id": "41625531-8243-4471-b435-574618df0484", "timestamp": "2015-12-16T23:44:22Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "61a5d4b37b5d43718854916079760c0d"}, {"counter_name": "cpu_util", "resource_id": "41625531-8243-4471-b435-574618df0484", "timestamp": "2015-12-16T23:44:32Z", "counter_unit": "%", "counter_volume": 0.0, "project_id": "61a5d4b37b5d43718854916079760c0d"}, {"counter_name": "cpu_util", "resource_id": "41625531-8243-4471-b435-574618df0484", "timestamp": "2015-12-16T23:44:42Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "61a5d4b37b5d43718854916079760c0d"}, {"counter_name": "cpu_util", "resource_id": "41625531-8243-4471-b435-574618df0484", "timestamp": "2015-12-16T23:44:52Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "61a5d4b37b5d43718854916079760c0d"}], "xos_instance_info": {"instance_name": "mysite_vcpe-7"}}}}, {"slice": "mysite_volt", "service": null, "lthreadshold_count": 1, "alarm": "scale_down_eval", "uthreadshold_count": 0, "project_id": "f506380a49a24389ae0d8469274e3279", "resources": {"9452c9e2-e358-4302-ba79-0d19b7b9be84": {"queue": [{"counter_name": "cpu_util", "resource_id": "9452c9e2-e358-4302-ba79-0d19b7b9be84", "timestamp": "2015-12-16T23:44:02Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "f506380a49a24389ae0d8469274e3279"}, {"counter_name": "cpu_util", "resource_id": "9452c9e2-e358-4302-ba79-0d19b7b9be84", "timestamp": "2015-12-16T23:44:12Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "f506380a49a24389ae0d8469274e3279"}, {"counter_name": "cpu_util", "resource_id": "9452c9e2-e358-4302-ba79-0d19b7b9be84", "timestamp": "2015-12-16T23:44:22Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "f506380a49a24389ae0d8469274e3279"}, {"counter_name": "cpu_util", "resource_id": "9452c9e2-e358-4302-ba79-0d19b7b9be84", "timestamp": "2015-12-16T23:44:32Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "f506380a49a24389ae0d8469274e3279"}, {"counter_name": "cpu_util", "resource_id": "9452c9e2-e358-4302-ba79-0d19b7b9be84", "timestamp": "2015-12-16T23:44:42Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "f506380a49a24389ae0d8469274e3279"}, {"counter_name": "cpu_util", "resource_id": "9452c9e2-e358-4302-ba79-0d19b7b9be84", "timestamp": "2015-12-16T23:44:52Z", "counter_unit": "%", "counter_volume": 0.0, "project_id": "f506380a49a24389ae0d8469274e3279"}], "xos_instance_info": {"instance_name": "mysite_volt-5"}}}}, {"slice": "mysite_vbng", "service": null, "lthreadshold_count": 1, "alarm": "scale_down_eval", "uthreadshold_count": 0, "project_id": "c92cf450df4640d6952c0276730e5048", "resources": {"40aec721-b7bc-49b2-9e1f-1f2a9005cb41": {"queue": [{"counter_name": "cpu_util", "resource_id": "40aec721-b7bc-49b2-9e1f-1f2a9005cb41", "timestamp": "2015-12-16T23:44:02Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "c92cf450df4640d6952c0276730e5048"}, {"counter_name": "cpu_util", "resource_id": "40aec721-b7bc-49b2-9e1f-1f2a9005cb41", "timestamp": "2015-12-16T23:44:12Z", "counter_unit": "%", "counter_volume": 0.19999999999999998, "project_id": "c92cf450df4640d6952c0276730e5048"}, {"counter_name": "cpu_util", "resource_id": "40aec721-b7bc-49b2-9e1f-1f2a9005cb41", "timestamp": "2015-12-16T23:44:22Z", "counter_unit": "%", "counter_volume": 0.0, "project_id": "c92cf450df4640d6952c0276730e5048"}, {"counter_name": "cpu_util", "resource_id": "40aec721-b7bc-49b2-9e1f-1f2a9005cb41", "timestamp": "2015-12-16T23:44:32Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "c92cf450df4640d6952c0276730e5048"}, {"counter_name": "cpu_util", "resource_id": "40aec721-b7bc-49b2-9e1f-1f2a9005cb41", "timestamp": "2015-12-16T23:44:42Z", "counter_unit": "%", "counter_volume": 0.0, "project_id": "c92cf450df4640d6952c0276730e5048"}, {"counter_name": "cpu_util", "resource_id": "40aec721-b7bc-49b2-9e1f-1f2a9005cb41", "timestamp": "2015-12-16T23:44:52Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "c92cf450df4640d6952c0276730e5048"}], "xos_instance_info": {"instance_name": "mysite_vbng-6"}}}}, {"slice": "mysite_clients", "service": null, "lthreadshold_count": 1, "alarm": "scale_down_eval", "uthreadshold_count": 0, "project_id": "f884c440474b40808a8adcdece5f45ef", "resources": {"036742d1-ff67-4c5b-8bde-58d0fc752b1d": {"queue": [{"counter_name": "cpu_util", "resource_id": "036742d1-ff67-4c5b-8bde-58d0fc752b1d", "timestamp": "2015-12-16T23:44:02Z", "counter_unit": "%", "counter_volume": 0.19999999999999998, "project_id": "f884c440474b40808a8adcdece5f45ef"}, {"counter_name": "cpu_util", "resource_id": "036742d1-ff67-4c5b-8bde-58d0fc752b1d", "timestamp": "2015-12-16T23:44:12Z", "counter_unit": "%", "counter_volume": 0.0, "project_id": "f884c440474b40808a8adcdece5f45ef"}, {"counter_name": "cpu_util", "resource_id": "036742d1-ff67-4c5b-8bde-58d0fc752b1d", "timestamp": "2015-12-16T23:44:22Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "f884c440474b40808a8adcdece5f45ef"}, {"counter_name": "cpu_util", "resource_id": "036742d1-ff67-4c5b-8bde-58d0fc752b1d", "timestamp": "2015-12-16T23:44:32Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "f884c440474b40808a8adcdece5f45ef"}, {"counter_name": "cpu_util", "resource_id": "036742d1-ff67-4c5b-8bde-58d0fc752b1d", "timestamp": "2015-12-16T23:44:42Z", "counter_unit": "%", "counter_volume": 0.0, "project_id": "f884c440474b40808a8adcdece5f45ef"}, {"counter_name": "cpu_util", "resource_id": "036742d1-ff67-4c5b-8bde-58d0fc752b1d", "timestamp": "2015-12-16T23:44:52Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "f884c440474b40808a8adcdece5f45ef"}], "xos_instance_info": {"instance_name": "mysite_clients-3"}}}}, {"slice": "mysite_ceilometer", "service": "service_ceilometer", "lthreadshold_count": 1, "alarm": "scale_down_eval", "uthreadshold_count": 0, "project_id": "920d70bc63574552bbb3c3fb262ee1bc", "resources": {"627f7de4-634a-4205-8eb4-93c40a34e862": {"queue": [{"counter_name": "cpu_util", "resource_id": "627f7de4-634a-4205-8eb4-93c40a34e862", "timestamp": "2015-12-16T23:44:02Z", "counter_unit": "%", "counter_volume": 0.19999999999999998, "project_id": "920d70bc63574552bbb3c3fb262ee1bc"}, {"counter_name": "cpu_util", "resource_id": "627f7de4-634a-4205-8eb4-93c40a34e862", "timestamp": "2015-12-16T23:44:12Z", "counter_unit": "%", "counter_volume": 0.19999999999999998, "project_id": "920d70bc63574552bbb3c3fb262ee1bc"}, {"counter_name": "cpu_util", "resource_id": "627f7de4-634a-4205-8eb4-93c40a34e862", "timestamp": "2015-12-16T23:44:22Z", "counter_unit": "%", "counter_volume": 0.19999999999999998, "project_id": "920d70bc63574552bbb3c3fb262ee1bc"}, {"counter_name": "cpu_util", "resource_id": "627f7de4-634a-4205-8eb4-93c40a34e862", "timestamp": "2015-12-16T23:44:32Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "920d70bc63574552bbb3c3fb262ee1bc"}, {"counter_name": "cpu_util", "resource_id": "627f7de4-634a-4205-8eb4-93c40a34e862", "timestamp": "2015-12-16T23:44:42Z", "counter_unit": "%", "counter_volume": 0.09999999999999999, "project_id": "920d70bc63574552bbb3c3fb262ee1bc"}, {"counter_name": "cpu_util", "resource_id": "627f7de4-634a-4205-8eb4-93c40a34e862", "timestamp": "2015-12-16T23:44:52Z", "counter_unit": "%", "counter_volume": 0.19999999999999998, "project_id": "920d70bc63574552bbb3c3fb262ee1bc"}], "xos_instance_info": {"instance_name": "mysite_ceilometer-8"}}}}]
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/templates/service-container.tpl.html b/xos-apps/auto-scale/gui/src/templates/service-container.tpl.html
new file mode 100644
index 0000000..34cdcca
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/templates/service-container.tpl.html
@@ -0,0 +1,26 @@
+<div class="row">
+ <div class="col-xs-12">
+ <h1>Service detail</h1>
+ </div>
+</div>
+<div class="row">
+ <div class="col-sm-12" ng-show="vm.loader">
+ <div class="loader"></div>
+ </div>
+ <div class="col-sm-3">
+ <ul class="list-group">
+ <li class="list-group-item" ng-class="{active: vm.serviceName == service}" ng-repeat="(service, slices) in vm.services">
+ <a href="" ng-click="vm.selectService(service)">{{service}}</a>
+ </li>
+ </ul>
+ </div>
+
+ <div class="col-sm-9 repeat-container" ng-show="!vm.error">
+ <service-detail service="vm.selectedService"></service-detail>
+ </div>
+ <div class="col-sm-9" ng-show="vm.error">
+ <div class="alert alert-danger">
+ {{vm.error}}
+ </div>
+ </div>
+</div>
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/templates/service-detail.tpl.html b/xos-apps/auto-scale/gui/src/templates/service-detail.tpl.html
new file mode 100644
index 0000000..f0e3636
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/templates/service-detail.tpl.html
@@ -0,0 +1,8 @@
+<div class="animate-repeat panel panel-default" ng-repeat="(slice, instances) in vm.service">
+ <div class="panel-heading">
+ <h3 class="panel-title">{{slice}}</h3>
+ </div>
+ <div class="panel-body">
+ <slice-detail instances="instances"></slice-detail>
+ </div>
+</div>
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/templates/slice-detail.tpl.html b/xos-apps/auto-scale/gui/src/templates/slice-detail.tpl.html
new file mode 100644
index 0000000..6e63d5b
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/templates/slice-detail.tpl.html
@@ -0,0 +1,4 @@
+<canvas id="line" class="chart chart-line" chart-data="vm.chart.data"
+ chart-labels="vm.chart.labels" chart-legend="true" chart-series="vm.chart.series"
+ chart-options="vm.chart.options">
+</canvas>
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/.bower.json b/xos-apps/auto-scale/gui/src/vendor/Chart.js/.bower.json
new file mode 100644
index 0000000..6173781
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/.bower.json
@@ -0,0 +1,20 @@
+{
+ "name": "Chart.js",
+ "version": "1.0.2",
+ "description": "Simple HTML5 Charts using the canvas element",
+ "homepage": "https://github.com/nnnick/Chart.js",
+ "author": "nnnick",
+ "main": [
+ "Chart.js"
+ ],
+ "dependencies": {},
+ "_release": "1.0.2",
+ "_resolution": {
+ "type": "version",
+ "tag": "v1.0.2",
+ "commit": "930b16a0af59201dcfcd1594b0e7540db4d04c9f"
+ },
+ "_source": "git://github.com/nnnick/Chart.js.git",
+ "_target": "~1.0.1",
+ "_originalSource": "Chart.js"
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/.gitignore b/xos-apps/auto-scale/gui/src/vendor/Chart.js/.gitignore
new file mode 100644
index 0000000..3969d0a
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/.gitignore
@@ -0,0 +1,7 @@
+
+.DS_Store
+
+node_modules/*
+custom/*
+
+docs/index.md
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/.travis.yml b/xos-apps/auto-scale/gui/src/vendor/Chart.js/.travis.yml
new file mode 100644
index 0000000..c66ea5f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/.travis.yml
@@ -0,0 +1,13 @@
+language: node_js
+node_js:
+ - "0.11"
+ - "0.10"
+
+before_script:
+ - npm install
+
+script:
+ - gulp test
+
+notifications:
+ slack: chartjs:pcfCZR6ugg5TEcaLtmIfQYuA
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/CONTRIBUTING.md b/xos-apps/auto-scale/gui/src/vendor/Chart.js/CONTRIBUTING.md
new file mode 100644
index 0000000..714bdd2
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/CONTRIBUTING.md
@@ -0,0 +1,55 @@
+Contributing to Chart.js
+========================
+
+Contributions to Chart.js are welcome and encouraged, but please have a look through the guidelines in this document before raising an issue, or writing code for the project.
+
+
+Using issues
+------------
+
+The [issue tracker](https://github.com/nnnick/Chart.js/issues) is the preferred channel for reporting bugs, requesting new features and submitting pull requests.
+
+If you're suggesting a new chart type, please take a look at [writing new chart types](https://github.com/nnnick/Chart.js/blob/master/docs/06-Advanced.md#writing-new-chart-types) in the documentation, and some of the [community extensions](https://github.com/nnnick/Chart.js/blob/master/docs/06-Advanced.md#community-extensions) that have been created already.
+
+To keep the library lightweight for everyone, it's unlikely we'll add many more chart types to the core of Chart.js, but issues are a good medium to design and spec out how new chart types could work and look.
+
+Please do not use issues for support requests. For help using Chart.js, please take a look at the [`chartjs`](http://stackoverflow.com/questions/tagged/chartjs) tag on Stack Overflow.
+
+
+Reporting bugs
+--------------
+
+Well structured, detailed bug reports are hugely valuable for the project.
+
+Guidlines for reporting bugs:
+
+ - Check the issue search to see if it has already been reported
+ - Isolate the problem to a simple test case
+ - Provide a demonstration of the problem on [JS Bin](http://jsbin.com) or similar
+
+Please provide any additional details associated with the bug, if it's browser or screen density specific, or only happens with a certain configuration or data.
+
+
+Pull requests
+-------------
+
+Clear, concise pull requests are excellent at continuing the project's community driven growth. But please review [these guidelines](https://github.com/blog/1943-how-to-write-the-perfect-pull-request) and the guidelines below before starting work on the project.
+
+Guidlines:
+
+ - Please create an issue first:
+ - For bugs, we can discuss the fixing approach
+ - For enhancements, we can discuss if it is within the project scope and avoid duplicate effort
+ - Please make changes to the files in [`/src`](https://github.com/nnnick/Chart.js/tree/master/src), not `Chart.js` or `Chart.min.js` in the repo root directory, this avoids merge conflicts
+ - Tabs for indentation, not spaces please
+ - If adding new functionality, please also update the relevant `.md` file in [`/docs`](https://github.com/nnnick/Chart.js/tree/master/docs)
+ - Please make your commits in logical sections with clear commit messages
+
+Joining the Project
+-------------
+ - Active committers and contributors are invited to introduce yourself and request commit access to this project. Please send an email to hello@nickdownie.com or file an issue.
+
+License
+-------
+
+By contributing your code, you agree to license your contribution under the [MIT license](https://github.com/nnnick/Chart.js/blob/master/LICENSE.md).
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/Chart.js b/xos-apps/auto-scale/gui/src/vendor/Chart.js/Chart.js
new file mode 100644
index 0000000..c264262
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/Chart.js
@@ -0,0 +1,3477 @@
+/*!
+ * Chart.js
+ * http://chartjs.org/
+ * Version: 1.0.2
+ *
+ * Copyright 2015 Nick Downie
+ * Released under the MIT license
+ * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
+ */
+
+
+(function(){
+
+ "use strict";
+
+ //Declare root variable - window in the browser, global on the server
+ var root = this,
+ previous = root.Chart;
+
+ //Occupy the global variable of Chart, and create a simple base class
+ var Chart = function(context){
+ var chart = this;
+ this.canvas = context.canvas;
+
+ this.ctx = context;
+
+ //Variables global to the chart
+ var computeDimension = function(element,dimension)
+ {
+ if (element['offset'+dimension])
+ {
+ return element['offset'+dimension];
+ }
+ else
+ {
+ return document.defaultView.getComputedStyle(element).getPropertyValue(dimension);
+ }
+ }
+
+ var width = this.width = computeDimension(context.canvas,'Width');
+ var height = this.height = computeDimension(context.canvas,'Height');
+
+ // Firefox requires this to work correctly
+ context.canvas.width = width;
+ context.canvas.height = height;
+
+ var width = this.width = context.canvas.width;
+ var height = this.height = context.canvas.height;
+ this.aspectRatio = this.width / this.height;
+ //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
+ helpers.retinaScale(this);
+
+ return this;
+ };
+ //Globally expose the defaults to allow for user updating/changing
+ Chart.defaults = {
+ global: {
+ // Boolean - Whether to animate the chart
+ animation: true,
+
+ // Number - Number of animation steps
+ animationSteps: 60,
+
+ // String - Animation easing effect
+ animationEasing: "easeOutQuart",
+
+ // Boolean - If we should show the scale at all
+ showScale: true,
+
+ // Boolean - If we want to override with a hard coded scale
+ scaleOverride: false,
+
+ // ** Required if scaleOverride is true **
+ // Number - The number of steps in a hard coded scale
+ scaleSteps: null,
+ // Number - The value jump in the hard coded scale
+ scaleStepWidth: null,
+ // Number - The scale starting value
+ scaleStartValue: null,
+
+ // String - Colour of the scale line
+ scaleLineColor: "rgba(0,0,0,.1)",
+
+ // Number - Pixel width of the scale line
+ scaleLineWidth: 1,
+
+ // Boolean - Whether to show labels on the scale
+ scaleShowLabels: true,
+
+ // Interpolated JS string - can access value
+ scaleLabel: "<%=value%>",
+
+ // Boolean - Whether the scale should stick to integers, and not show any floats even if drawing space is there
+ scaleIntegersOnly: true,
+
+ // Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
+ scaleBeginAtZero: false,
+
+ // String - Scale label font declaration for the scale label
+ scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
+
+ // Number - Scale label font size in pixels
+ scaleFontSize: 12,
+
+ // String - Scale label font weight style
+ scaleFontStyle: "normal",
+
+ // String - Scale label font colour
+ scaleFontColor: "#666",
+
+ // Boolean - whether or not the chart should be responsive and resize when the browser does.
+ responsive: false,
+
+ // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
+ maintainAspectRatio: true,
+
+ // Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove
+ showTooltips: true,
+
+ // Boolean - Determines whether to draw built-in tooltip or call custom tooltip function
+ customTooltips: false,
+
+ // Array - Array of string names to attach tooltip events
+ tooltipEvents: ["mousemove", "touchstart", "touchmove", "mouseout"],
+
+ // String - Tooltip background colour
+ tooltipFillColor: "rgba(0,0,0,0.8)",
+
+ // String - Tooltip label font declaration for the scale label
+ tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
+
+ // Number - Tooltip label font size in pixels
+ tooltipFontSize: 14,
+
+ // String - Tooltip font weight style
+ tooltipFontStyle: "normal",
+
+ // String - Tooltip label font colour
+ tooltipFontColor: "#fff",
+
+ // String - Tooltip title font declaration for the scale label
+ tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
+
+ // Number - Tooltip title font size in pixels
+ tooltipTitleFontSize: 14,
+
+ // String - Tooltip title font weight style
+ tooltipTitleFontStyle: "bold",
+
+ // String - Tooltip title font colour
+ tooltipTitleFontColor: "#fff",
+
+ // Number - pixel width of padding around tooltip text
+ tooltipYPadding: 6,
+
+ // Number - pixel width of padding around tooltip text
+ tooltipXPadding: 6,
+
+ // Number - Size of the caret on the tooltip
+ tooltipCaretSize: 8,
+
+ // Number - Pixel radius of the tooltip border
+ tooltipCornerRadius: 6,
+
+ // Number - Pixel offset from point x to tooltip edge
+ tooltipXOffset: 10,
+
+ // String - Template string for single tooltips
+ tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
+
+ // String - Template string for single tooltips
+ multiTooltipTemplate: "<%= value %>",
+
+ // String - Colour behind the legend colour block
+ multiTooltipKeyBackground: '#fff',
+
+ // Function - Will fire on animation progression.
+ onAnimationProgress: function(){},
+
+ // Function - Will fire on animation completion.
+ onAnimationComplete: function(){}
+
+ }
+ };
+
+ //Create a dictionary of chart types, to allow for extension of existing types
+ Chart.types = {};
+
+ //Global Chart helpers object for utility methods and classes
+ var helpers = Chart.helpers = {};
+
+ //-- Basic js utility methods
+ var each = helpers.each = function(loopable,callback,self){
+ var additionalArgs = Array.prototype.slice.call(arguments, 3);
+ // Check to see if null or undefined firstly.
+ if (loopable){
+ if (loopable.length === +loopable.length){
+ var i;
+ for (i=0; i<loopable.length; i++){
+ callback.apply(self,[loopable[i], i].concat(additionalArgs));
+ }
+ }
+ else{
+ for (var item in loopable){
+ callback.apply(self,[loopable[item],item].concat(additionalArgs));
+ }
+ }
+ }
+ },
+ clone = helpers.clone = function(obj){
+ var objClone = {};
+ each(obj,function(value,key){
+ if (obj.hasOwnProperty(key)) objClone[key] = value;
+ });
+ return objClone;
+ },
+ extend = helpers.extend = function(base){
+ each(Array.prototype.slice.call(arguments,1), function(extensionObject) {
+ each(extensionObject,function(value,key){
+ if (extensionObject.hasOwnProperty(key)) base[key] = value;
+ });
+ });
+ return base;
+ },
+ merge = helpers.merge = function(base,master){
+ //Merge properties in left object over to a shallow clone of object right.
+ var args = Array.prototype.slice.call(arguments,0);
+ args.unshift({});
+ return extend.apply(null, args);
+ },
+ indexOf = helpers.indexOf = function(arrayToSearch, item){
+ if (Array.prototype.indexOf) {
+ return arrayToSearch.indexOf(item);
+ }
+ else{
+ for (var i = 0; i < arrayToSearch.length; i++) {
+ if (arrayToSearch[i] === item) return i;
+ }
+ return -1;
+ }
+ },
+ where = helpers.where = function(collection, filterCallback){
+ var filtered = [];
+
+ helpers.each(collection, function(item){
+ if (filterCallback(item)){
+ filtered.push(item);
+ }
+ });
+
+ return filtered;
+ },
+ findNextWhere = helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex){
+ // Default to start of the array
+ if (!startIndex){
+ startIndex = -1;
+ }
+ for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
+ var currentItem = arrayToSearch[i];
+ if (filterCallback(currentItem)){
+ return currentItem;
+ }
+ }
+ },
+ findPreviousWhere = helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex){
+ // Default to end of the array
+ if (!startIndex){
+ startIndex = arrayToSearch.length;
+ }
+ for (var i = startIndex - 1; i >= 0; i--) {
+ var currentItem = arrayToSearch[i];
+ if (filterCallback(currentItem)){
+ return currentItem;
+ }
+ }
+ },
+ inherits = helpers.inherits = function(extensions){
+ //Basic javascript inheritance based on the model created in Backbone.js
+ var parent = this;
+ var ChartElement = (extensions && extensions.hasOwnProperty("constructor")) ? extensions.constructor : function(){ return parent.apply(this, arguments); };
+
+ var Surrogate = function(){ this.constructor = ChartElement;};
+ Surrogate.prototype = parent.prototype;
+ ChartElement.prototype = new Surrogate();
+
+ ChartElement.extend = inherits;
+
+ if (extensions) extend(ChartElement.prototype, extensions);
+
+ ChartElement.__super__ = parent.prototype;
+
+ return ChartElement;
+ },
+ noop = helpers.noop = function(){},
+ uid = helpers.uid = (function(){
+ var id=0;
+ return function(){
+ return "chart-" + id++;
+ };
+ })(),
+ warn = helpers.warn = function(str){
+ //Method for warning of errors
+ if (window.console && typeof window.console.warn == "function") console.warn(str);
+ },
+ amd = helpers.amd = (typeof define == 'function' && define.amd),
+ //-- Math methods
+ isNumber = helpers.isNumber = function(n){
+ return !isNaN(parseFloat(n)) && isFinite(n);
+ },
+ max = helpers.max = function(array){
+ return Math.max.apply( Math, array );
+ },
+ min = helpers.min = function(array){
+ return Math.min.apply( Math, array );
+ },
+ cap = helpers.cap = function(valueToCap,maxValue,minValue){
+ if(isNumber(maxValue)) {
+ if( valueToCap > maxValue ) {
+ return maxValue;
+ }
+ }
+ else if(isNumber(minValue)){
+ if ( valueToCap < minValue ){
+ return minValue;
+ }
+ }
+ return valueToCap;
+ },
+ getDecimalPlaces = helpers.getDecimalPlaces = function(num){
+ if (num%1!==0 && isNumber(num)){
+ return num.toString().split(".")[1].length;
+ }
+ else {
+ return 0;
+ }
+ },
+ toRadians = helpers.radians = function(degrees){
+ return degrees * (Math.PI/180);
+ },
+ // Gets the angle from vertical upright to the point about a centre.
+ getAngleFromPoint = helpers.getAngleFromPoint = function(centrePoint, anglePoint){
+ var distanceFromXCenter = anglePoint.x - centrePoint.x,
+ distanceFromYCenter = anglePoint.y - centrePoint.y,
+ radialDistanceFromCenter = Math.sqrt( distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
+
+
+ var angle = Math.PI * 2 + Math.atan2(distanceFromYCenter, distanceFromXCenter);
+
+ //If the segment is in the top left quadrant, we need to add another rotation to the angle
+ if (distanceFromXCenter < 0 && distanceFromYCenter < 0){
+ angle += Math.PI*2;
+ }
+
+ return {
+ angle: angle,
+ distance: radialDistanceFromCenter
+ };
+ },
+ aliasPixel = helpers.aliasPixel = function(pixelWidth){
+ return (pixelWidth % 2 === 0) ? 0 : 0.5;
+ },
+ splineCurve = helpers.splineCurve = function(FirstPoint,MiddlePoint,AfterPoint,t){
+ //Props to Rob Spencer at scaled innovation for his post on splining between points
+ //http://scaledinnovation.com/analytics/splines/aboutSplines.html
+ var d01=Math.sqrt(Math.pow(MiddlePoint.x-FirstPoint.x,2)+Math.pow(MiddlePoint.y-FirstPoint.y,2)),
+ d12=Math.sqrt(Math.pow(AfterPoint.x-MiddlePoint.x,2)+Math.pow(AfterPoint.y-MiddlePoint.y,2)),
+ fa=t*d01/(d01+d12),// scaling factor for triangle Ta
+ fb=t*d12/(d01+d12);
+ return {
+ inner : {
+ x : MiddlePoint.x-fa*(AfterPoint.x-FirstPoint.x),
+ y : MiddlePoint.y-fa*(AfterPoint.y-FirstPoint.y)
+ },
+ outer : {
+ x: MiddlePoint.x+fb*(AfterPoint.x-FirstPoint.x),
+ y : MiddlePoint.y+fb*(AfterPoint.y-FirstPoint.y)
+ }
+ };
+ },
+ calculateOrderOfMagnitude = helpers.calculateOrderOfMagnitude = function(val){
+ return Math.floor(Math.log(val) / Math.LN10);
+ },
+ calculateScaleRange = helpers.calculateScaleRange = function(valuesArray, drawingSize, textSize, startFromZero, integersOnly){
+
+ //Set a minimum step of two - a point at the top of the graph, and a point at the base
+ var minSteps = 2,
+ maxSteps = Math.floor(drawingSize/(textSize * 1.5)),
+ skipFitting = (minSteps >= maxSteps);
+
+ var maxValue = max(valuesArray),
+ minValue = min(valuesArray);
+
+ // We need some degree of seperation here to calculate the scales if all the values are the same
+ // Adding/minusing 0.5 will give us a range of 1.
+ if (maxValue === minValue){
+ maxValue += 0.5;
+ // So we don't end up with a graph with a negative start value if we've said always start from zero
+ if (minValue >= 0.5 && !startFromZero){
+ minValue -= 0.5;
+ }
+ else{
+ // Make up a whole number above the values
+ maxValue += 0.5;
+ }
+ }
+
+ var valueRange = Math.abs(maxValue - minValue),
+ rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange),
+ graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
+ graphMin = (startFromZero) ? 0 : Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
+ graphRange = graphMax - graphMin,
+ stepValue = Math.pow(10, rangeOrderOfMagnitude),
+ numberOfSteps = Math.round(graphRange / stepValue);
+
+ //If we have more space on the graph we'll use it to give more definition to the data
+ while((numberOfSteps > maxSteps || (numberOfSteps * 2) < maxSteps) && !skipFitting) {
+ if(numberOfSteps > maxSteps){
+ stepValue *=2;
+ numberOfSteps = Math.round(graphRange/stepValue);
+ // Don't ever deal with a decimal number of steps - cancel fitting and just use the minimum number of steps.
+ if (numberOfSteps % 1 !== 0){
+ skipFitting = true;
+ }
+ }
+ //We can fit in double the amount of scale points on the scale
+ else{
+ //If user has declared ints only, and the step value isn't a decimal
+ if (integersOnly && rangeOrderOfMagnitude >= 0){
+ //If the user has said integers only, we need to check that making the scale more granular wouldn't make it a float
+ if(stepValue/2 % 1 === 0){
+ stepValue /=2;
+ numberOfSteps = Math.round(graphRange/stepValue);
+ }
+ //If it would make it a float break out of the loop
+ else{
+ break;
+ }
+ }
+ //If the scale doesn't have to be an int, make the scale more granular anyway.
+ else{
+ stepValue /=2;
+ numberOfSteps = Math.round(graphRange/stepValue);
+ }
+
+ }
+ }
+
+ if (skipFitting){
+ numberOfSteps = minSteps;
+ stepValue = graphRange / numberOfSteps;
+ }
+
+ return {
+ steps : numberOfSteps,
+ stepValue : stepValue,
+ min : graphMin,
+ max : graphMin + (numberOfSteps * stepValue)
+ };
+
+ },
+ /* jshint ignore:start */
+ // Blows up jshint errors based on the new Function constructor
+ //Templating methods
+ //Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/
+ template = helpers.template = function(templateString, valuesObject){
+
+ // If templateString is function rather than string-template - call the function for valuesObject
+
+ if(templateString instanceof Function){
+ return templateString(valuesObject);
+ }
+
+ var cache = {};
+ function tmpl(str, data){
+ // Figure out if we're getting a template, or if we need to
+ // load the template - and be sure to cache the result.
+ var fn = !/\W/.test(str) ?
+ cache[str] = cache[str] :
+
+ // Generate a reusable function that will serve as a template
+ // generator (and which will be cached).
+ new Function("obj",
+ "var p=[],print=function(){p.push.apply(p,arguments);};" +
+
+ // Introduce the data as local variables using with(){}
+ "with(obj){p.push('" +
+
+ // Convert the template into pure JavaScript
+ str
+ .replace(/[\r\t\n]/g, " ")
+ .split("<%").join("\t")
+ .replace(/((^|%>)[^\t]*)'/g, "$1\r")
+ .replace(/\t=(.*?)%>/g, "',$1,'")
+ .split("\t").join("');")
+ .split("%>").join("p.push('")
+ .split("\r").join("\\'") +
+ "');}return p.join('');"
+ );
+
+ // Provide some basic currying to the user
+ return data ? fn( data ) : fn;
+ }
+ return tmpl(templateString,valuesObject);
+ },
+ /* jshint ignore:end */
+ generateLabels = helpers.generateLabels = function(templateString,numberOfSteps,graphMin,stepValue){
+ var labelsArray = new Array(numberOfSteps);
+ if (labelTemplateString){
+ each(labelsArray,function(val,index){
+ labelsArray[index] = template(templateString,{value: (graphMin + (stepValue*(index+1)))});
+ });
+ }
+ return labelsArray;
+ },
+ //--Animation methods
+ //Easing functions adapted from Robert Penner's easing equations
+ //http://www.robertpenner.com/easing/
+ easingEffects = helpers.easingEffects = {
+ linear: function (t) {
+ return t;
+ },
+ easeInQuad: function (t) {
+ return t * t;
+ },
+ easeOutQuad: function (t) {
+ return -1 * t * (t - 2);
+ },
+ easeInOutQuad: function (t) {
+ if ((t /= 1 / 2) < 1) return 1 / 2 * t * t;
+ return -1 / 2 * ((--t) * (t - 2) - 1);
+ },
+ easeInCubic: function (t) {
+ return t * t * t;
+ },
+ easeOutCubic: function (t) {
+ return 1 * ((t = t / 1 - 1) * t * t + 1);
+ },
+ easeInOutCubic: function (t) {
+ if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t;
+ return 1 / 2 * ((t -= 2) * t * t + 2);
+ },
+ easeInQuart: function (t) {
+ return t * t * t * t;
+ },
+ easeOutQuart: function (t) {
+ return -1 * ((t = t / 1 - 1) * t * t * t - 1);
+ },
+ easeInOutQuart: function (t) {
+ if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t;
+ return -1 / 2 * ((t -= 2) * t * t * t - 2);
+ },
+ easeInQuint: function (t) {
+ return 1 * (t /= 1) * t * t * t * t;
+ },
+ easeOutQuint: function (t) {
+ return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
+ },
+ easeInOutQuint: function (t) {
+ if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t * t;
+ return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
+ },
+ easeInSine: function (t) {
+ return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1;
+ },
+ easeOutSine: function (t) {
+ return 1 * Math.sin(t / 1 * (Math.PI / 2));
+ },
+ easeInOutSine: function (t) {
+ return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1);
+ },
+ easeInExpo: function (t) {
+ return (t === 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1));
+ },
+ easeOutExpo: function (t) {
+ return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
+ },
+ easeInOutExpo: function (t) {
+ if (t === 0) return 0;
+ if (t === 1) return 1;
+ if ((t /= 1 / 2) < 1) return 1 / 2 * Math.pow(2, 10 * (t - 1));
+ return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
+ },
+ easeInCirc: function (t) {
+ if (t >= 1) return t;
+ return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
+ },
+ easeOutCirc: function (t) {
+ return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
+ },
+ easeInOutCirc: function (t) {
+ if ((t /= 1 / 2) < 1) return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
+ return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
+ },
+ easeInElastic: function (t) {
+ var s = 1.70158;
+ var p = 0;
+ var a = 1;
+ if (t === 0) return 0;
+ if ((t /= 1) == 1) return 1;
+ if (!p) p = 1 * 0.3;
+ if (a < Math.abs(1)) {
+ a = 1;
+ s = p / 4;
+ } else s = p / (2 * Math.PI) * Math.asin(1 / a);
+ return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
+ },
+ easeOutElastic: function (t) {
+ var s = 1.70158;
+ var p = 0;
+ var a = 1;
+ if (t === 0) return 0;
+ if ((t /= 1) == 1) return 1;
+ if (!p) p = 1 * 0.3;
+ if (a < Math.abs(1)) {
+ a = 1;
+ s = p / 4;
+ } else s = p / (2 * Math.PI) * Math.asin(1 / a);
+ return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
+ },
+ easeInOutElastic: function (t) {
+ var s = 1.70158;
+ var p = 0;
+ var a = 1;
+ if (t === 0) return 0;
+ if ((t /= 1 / 2) == 2) return 1;
+ if (!p) p = 1 * (0.3 * 1.5);
+ if (a < Math.abs(1)) {
+ a = 1;
+ s = p / 4;
+ } else s = p / (2 * Math.PI) * Math.asin(1 / a);
+ if (t < 1) return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
+ return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1;
+ },
+ easeInBack: function (t) {
+ var s = 1.70158;
+ return 1 * (t /= 1) * t * ((s + 1) * t - s);
+ },
+ easeOutBack: function (t) {
+ var s = 1.70158;
+ return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1);
+ },
+ easeInOutBack: function (t) {
+ var s = 1.70158;
+ if ((t /= 1 / 2) < 1) return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
+ return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
+ },
+ easeInBounce: function (t) {
+ return 1 - easingEffects.easeOutBounce(1 - t);
+ },
+ easeOutBounce: function (t) {
+ if ((t /= 1) < (1 / 2.75)) {
+ return 1 * (7.5625 * t * t);
+ } else if (t < (2 / 2.75)) {
+ return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75);
+ } else if (t < (2.5 / 2.75)) {
+ return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375);
+ } else {
+ return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375);
+ }
+ },
+ easeInOutBounce: function (t) {
+ if (t < 1 / 2) return easingEffects.easeInBounce(t * 2) * 0.5;
+ return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5;
+ }
+ },
+ //Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
+ requestAnimFrame = helpers.requestAnimFrame = (function(){
+ return window.requestAnimationFrame ||
+ window.webkitRequestAnimationFrame ||
+ window.mozRequestAnimationFrame ||
+ window.oRequestAnimationFrame ||
+ window.msRequestAnimationFrame ||
+ function(callback) {
+ return window.setTimeout(callback, 1000 / 60);
+ };
+ })(),
+ cancelAnimFrame = helpers.cancelAnimFrame = (function(){
+ return window.cancelAnimationFrame ||
+ window.webkitCancelAnimationFrame ||
+ window.mozCancelAnimationFrame ||
+ window.oCancelAnimationFrame ||
+ window.msCancelAnimationFrame ||
+ function(callback) {
+ return window.clearTimeout(callback, 1000 / 60);
+ };
+ })(),
+ animationLoop = helpers.animationLoop = function(callback,totalSteps,easingString,onProgress,onComplete,chartInstance){
+
+ var currentStep = 0,
+ easingFunction = easingEffects[easingString] || easingEffects.linear;
+
+ var animationFrame = function(){
+ currentStep++;
+ var stepDecimal = currentStep/totalSteps;
+ var easeDecimal = easingFunction(stepDecimal);
+
+ callback.call(chartInstance,easeDecimal,stepDecimal, currentStep);
+ onProgress.call(chartInstance,easeDecimal,stepDecimal);
+ if (currentStep < totalSteps){
+ chartInstance.animationFrame = requestAnimFrame(animationFrame);
+ } else{
+ onComplete.apply(chartInstance);
+ }
+ };
+ requestAnimFrame(animationFrame);
+ },
+ //-- DOM methods
+ getRelativePosition = helpers.getRelativePosition = function(evt){
+ var mouseX, mouseY;
+ var e = evt.originalEvent || evt,
+ canvas = evt.currentTarget || evt.srcElement,
+ boundingRect = canvas.getBoundingClientRect();
+
+ if (e.touches){
+ mouseX = e.touches[0].clientX - boundingRect.left;
+ mouseY = e.touches[0].clientY - boundingRect.top;
+
+ }
+ else{
+ mouseX = e.clientX - boundingRect.left;
+ mouseY = e.clientY - boundingRect.top;
+ }
+
+ return {
+ x : mouseX,
+ y : mouseY
+ };
+
+ },
+ addEvent = helpers.addEvent = function(node,eventType,method){
+ if (node.addEventListener){
+ node.addEventListener(eventType,method);
+ } else if (node.attachEvent){
+ node.attachEvent("on"+eventType, method);
+ } else {
+ node["on"+eventType] = method;
+ }
+ },
+ removeEvent = helpers.removeEvent = function(node, eventType, handler){
+ if (node.removeEventListener){
+ node.removeEventListener(eventType, handler, false);
+ } else if (node.detachEvent){
+ node.detachEvent("on"+eventType,handler);
+ } else{
+ node["on" + eventType] = noop;
+ }
+ },
+ bindEvents = helpers.bindEvents = function(chartInstance, arrayOfEvents, handler){
+ // Create the events object if it's not already present
+ if (!chartInstance.events) chartInstance.events = {};
+
+ each(arrayOfEvents,function(eventName){
+ chartInstance.events[eventName] = function(){
+ handler.apply(chartInstance, arguments);
+ };
+ addEvent(chartInstance.chart.canvas,eventName,chartInstance.events[eventName]);
+ });
+ },
+ unbindEvents = helpers.unbindEvents = function (chartInstance, arrayOfEvents) {
+ each(arrayOfEvents, function(handler,eventName){
+ removeEvent(chartInstance.chart.canvas, eventName, handler);
+ });
+ },
+ getMaximumWidth = helpers.getMaximumWidth = function(domNode){
+ var container = domNode.parentNode;
+ // TODO = check cross browser stuff with this.
+ return container.clientWidth;
+ },
+ getMaximumHeight = helpers.getMaximumHeight = function(domNode){
+ var container = domNode.parentNode;
+ // TODO = check cross browser stuff with this.
+ return container.clientHeight;
+ },
+ getMaximumSize = helpers.getMaximumSize = helpers.getMaximumWidth, // legacy support
+ retinaScale = helpers.retinaScale = function(chart){
+ var ctx = chart.ctx,
+ width = chart.canvas.width,
+ height = chart.canvas.height;
+
+ if (window.devicePixelRatio) {
+ ctx.canvas.style.width = width + "px";
+ ctx.canvas.style.height = height + "px";
+ ctx.canvas.height = height * window.devicePixelRatio;
+ ctx.canvas.width = width * window.devicePixelRatio;
+ ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
+ }
+ },
+ //-- Canvas methods
+ clear = helpers.clear = function(chart){
+ chart.ctx.clearRect(0,0,chart.width,chart.height);
+ },
+ fontString = helpers.fontString = function(pixelSize,fontStyle,fontFamily){
+ return fontStyle + " " + pixelSize+"px " + fontFamily;
+ },
+ longestText = helpers.longestText = function(ctx,font,arrayOfStrings){
+ ctx.font = font;
+ var longest = 0;
+ each(arrayOfStrings,function(string){
+ var textWidth = ctx.measureText(string).width;
+ longest = (textWidth > longest) ? textWidth : longest;
+ });
+ return longest;
+ },
+ drawRoundedRectangle = helpers.drawRoundedRectangle = function(ctx,x,y,width,height,radius){
+ ctx.beginPath();
+ ctx.moveTo(x + radius, y);
+ ctx.lineTo(x + width - radius, y);
+ ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
+ ctx.lineTo(x + width, y + height - radius);
+ ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
+ ctx.lineTo(x + radius, y + height);
+ ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
+ ctx.lineTo(x, y + radius);
+ ctx.quadraticCurveTo(x, y, x + radius, y);
+ ctx.closePath();
+ };
+
+
+ //Store a reference to each instance - allowing us to globally resize chart instances on window resize.
+ //Destroy method on the chart will remove the instance of the chart from this reference.
+ Chart.instances = {};
+
+ Chart.Type = function(data,options,chart){
+ this.options = options;
+ this.chart = chart;
+ this.id = uid();
+ //Add the chart instance to the global namespace
+ Chart.instances[this.id] = this;
+
+ // Initialize is always called when a chart type is created
+ // By default it is a no op, but it should be extended
+ if (options.responsive){
+ this.resize();
+ }
+ this.initialize.call(this,data);
+ };
+
+ //Core methods that'll be a part of every chart type
+ extend(Chart.Type.prototype,{
+ initialize : function(){return this;},
+ clear : function(){
+ clear(this.chart);
+ return this;
+ },
+ stop : function(){
+ // Stops any current animation loop occuring
+ cancelAnimFrame(this.animationFrame);
+ return this;
+ },
+ resize : function(callback){
+ this.stop();
+ var canvas = this.chart.canvas,
+ newWidth = getMaximumWidth(this.chart.canvas),
+ newHeight = this.options.maintainAspectRatio ? newWidth / this.chart.aspectRatio : getMaximumHeight(this.chart.canvas);
+
+ canvas.width = this.chart.width = newWidth;
+ canvas.height = this.chart.height = newHeight;
+
+ retinaScale(this.chart);
+
+ if (typeof callback === "function"){
+ callback.apply(this, Array.prototype.slice.call(arguments, 1));
+ }
+ return this;
+ },
+ reflow : noop,
+ render : function(reflow){
+ if (reflow){
+ this.reflow();
+ }
+ if (this.options.animation && !reflow){
+ helpers.animationLoop(
+ this.draw,
+ this.options.animationSteps,
+ this.options.animationEasing,
+ this.options.onAnimationProgress,
+ this.options.onAnimationComplete,
+ this
+ );
+ }
+ else{
+ this.draw();
+ this.options.onAnimationComplete.call(this);
+ }
+ return this;
+ },
+ generateLegend : function(){
+ return template(this.options.legendTemplate,this);
+ },
+ destroy : function(){
+ this.clear();
+ unbindEvents(this, this.events);
+ var canvas = this.chart.canvas;
+
+ // Reset canvas height/width attributes starts a fresh with the canvas context
+ canvas.width = this.chart.width;
+ canvas.height = this.chart.height;
+
+ // < IE9 doesn't support removeProperty
+ if (canvas.style.removeProperty) {
+ canvas.style.removeProperty('width');
+ canvas.style.removeProperty('height');
+ } else {
+ canvas.style.removeAttribute('width');
+ canvas.style.removeAttribute('height');
+ }
+
+ delete Chart.instances[this.id];
+ },
+ showTooltip : function(ChartElements, forceRedraw){
+ // Only redraw the chart if we've actually changed what we're hovering on.
+ if (typeof this.activeElements === 'undefined') this.activeElements = [];
+
+ var isChanged = (function(Elements){
+ var changed = false;
+
+ if (Elements.length !== this.activeElements.length){
+ changed = true;
+ return changed;
+ }
+
+ each(Elements, function(element, index){
+ if (element !== this.activeElements[index]){
+ changed = true;
+ }
+ }, this);
+ return changed;
+ }).call(this, ChartElements);
+
+ if (!isChanged && !forceRedraw){
+ return;
+ }
+ else{
+ this.activeElements = ChartElements;
+ }
+ this.draw();
+ if(this.options.customTooltips){
+ this.options.customTooltips(false);
+ }
+ if (ChartElements.length > 0){
+ // If we have multiple datasets, show a MultiTooltip for all of the data points at that index
+ if (this.datasets && this.datasets.length > 1) {
+ var dataArray,
+ dataIndex;
+
+ for (var i = this.datasets.length - 1; i >= 0; i--) {
+ dataArray = this.datasets[i].points || this.datasets[i].bars || this.datasets[i].segments;
+ dataIndex = indexOf(dataArray, ChartElements[0]);
+ if (dataIndex !== -1){
+ break;
+ }
+ }
+ var tooltipLabels = [],
+ tooltipColors = [],
+ medianPosition = (function(index) {
+
+ // Get all the points at that particular index
+ var Elements = [],
+ dataCollection,
+ xPositions = [],
+ yPositions = [],
+ xMax,
+ yMax,
+ xMin,
+ yMin;
+ helpers.each(this.datasets, function(dataset){
+ dataCollection = dataset.points || dataset.bars || dataset.segments;
+ if (dataCollection[dataIndex] && dataCollection[dataIndex].hasValue()){
+ Elements.push(dataCollection[dataIndex]);
+ }
+ });
+
+ helpers.each(Elements, function(element) {
+ xPositions.push(element.x);
+ yPositions.push(element.y);
+
+
+ //Include any colour information about the element
+ tooltipLabels.push(helpers.template(this.options.multiTooltipTemplate, element));
+ tooltipColors.push({
+ fill: element._saved.fillColor || element.fillColor,
+ stroke: element._saved.strokeColor || element.strokeColor
+ });
+
+ }, this);
+
+ yMin = min(yPositions);
+ yMax = max(yPositions);
+
+ xMin = min(xPositions);
+ xMax = max(xPositions);
+
+ return {
+ x: (xMin > this.chart.width/2) ? xMin : xMax,
+ y: (yMin + yMax)/2
+ };
+ }).call(this, dataIndex);
+
+ new Chart.MultiTooltip({
+ x: medianPosition.x,
+ y: medianPosition.y,
+ xPadding: this.options.tooltipXPadding,
+ yPadding: this.options.tooltipYPadding,
+ xOffset: this.options.tooltipXOffset,
+ fillColor: this.options.tooltipFillColor,
+ textColor: this.options.tooltipFontColor,
+ fontFamily: this.options.tooltipFontFamily,
+ fontStyle: this.options.tooltipFontStyle,
+ fontSize: this.options.tooltipFontSize,
+ titleTextColor: this.options.tooltipTitleFontColor,
+ titleFontFamily: this.options.tooltipTitleFontFamily,
+ titleFontStyle: this.options.tooltipTitleFontStyle,
+ titleFontSize: this.options.tooltipTitleFontSize,
+ cornerRadius: this.options.tooltipCornerRadius,
+ labels: tooltipLabels,
+ legendColors: tooltipColors,
+ legendColorBackground : this.options.multiTooltipKeyBackground,
+ title: ChartElements[0].label,
+ chart: this.chart,
+ ctx: this.chart.ctx,
+ custom: this.options.customTooltips
+ }).draw();
+
+ } else {
+ each(ChartElements, function(Element) {
+ var tooltipPosition = Element.tooltipPosition();
+ new Chart.Tooltip({
+ x: Math.round(tooltipPosition.x),
+ y: Math.round(tooltipPosition.y),
+ xPadding: this.options.tooltipXPadding,
+ yPadding: this.options.tooltipYPadding,
+ fillColor: this.options.tooltipFillColor,
+ textColor: this.options.tooltipFontColor,
+ fontFamily: this.options.tooltipFontFamily,
+ fontStyle: this.options.tooltipFontStyle,
+ fontSize: this.options.tooltipFontSize,
+ caretHeight: this.options.tooltipCaretSize,
+ cornerRadius: this.options.tooltipCornerRadius,
+ text: template(this.options.tooltipTemplate, Element),
+ chart: this.chart,
+ custom: this.options.customTooltips
+ }).draw();
+ }, this);
+ }
+ }
+ return this;
+ },
+ toBase64Image : function(){
+ return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments);
+ }
+ });
+
+ Chart.Type.extend = function(extensions){
+
+ var parent = this;
+
+ var ChartType = function(){
+ return parent.apply(this,arguments);
+ };
+
+ //Copy the prototype object of the this class
+ ChartType.prototype = clone(parent.prototype);
+ //Now overwrite some of the properties in the base class with the new extensions
+ extend(ChartType.prototype, extensions);
+
+ ChartType.extend = Chart.Type.extend;
+
+ if (extensions.name || parent.prototype.name){
+
+ var chartName = extensions.name || parent.prototype.name;
+ //Assign any potential default values of the new chart type
+
+ //If none are defined, we'll use a clone of the chart type this is being extended from.
+ //I.e. if we extend a line chart, we'll use the defaults from the line chart if our new chart
+ //doesn't define some defaults of their own.
+
+ var baseDefaults = (Chart.defaults[parent.prototype.name]) ? clone(Chart.defaults[parent.prototype.name]) : {};
+
+ Chart.defaults[chartName] = extend(baseDefaults,extensions.defaults);
+
+ Chart.types[chartName] = ChartType;
+
+ //Register this new chart type in the Chart prototype
+ Chart.prototype[chartName] = function(data,options){
+ var config = merge(Chart.defaults.global, Chart.defaults[chartName], options || {});
+ return new ChartType(data,config,this);
+ };
+ } else{
+ warn("Name not provided for this chart, so it hasn't been registered");
+ }
+ return parent;
+ };
+
+ Chart.Element = function(configuration){
+ extend(this,configuration);
+ this.initialize.apply(this,arguments);
+ this.save();
+ };
+ extend(Chart.Element.prototype,{
+ initialize : function(){},
+ restore : function(props){
+ if (!props){
+ extend(this,this._saved);
+ } else {
+ each(props,function(key){
+ this[key] = this._saved[key];
+ },this);
+ }
+ return this;
+ },
+ save : function(){
+ this._saved = clone(this);
+ delete this._saved._saved;
+ return this;
+ },
+ update : function(newProps){
+ each(newProps,function(value,key){
+ this._saved[key] = this[key];
+ this[key] = value;
+ },this);
+ return this;
+ },
+ transition : function(props,ease){
+ each(props,function(value,key){
+ this[key] = ((value - this._saved[key]) * ease) + this._saved[key];
+ },this);
+ return this;
+ },
+ tooltipPosition : function(){
+ return {
+ x : this.x,
+ y : this.y
+ };
+ },
+ hasValue: function(){
+ return isNumber(this.value);
+ }
+ });
+
+ Chart.Element.extend = inherits;
+
+
+ Chart.Point = Chart.Element.extend({
+ display: true,
+ inRange: function(chartX,chartY){
+ var hitDetectionRange = this.hitDetectionRadius + this.radius;
+ return ((Math.pow(chartX-this.x, 2)+Math.pow(chartY-this.y, 2)) < Math.pow(hitDetectionRange,2));
+ },
+ draw : function(){
+ if (this.display){
+ var ctx = this.ctx;
+ ctx.beginPath();
+
+ ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
+ ctx.closePath();
+
+ ctx.strokeStyle = this.strokeColor;
+ ctx.lineWidth = this.strokeWidth;
+
+ ctx.fillStyle = this.fillColor;
+
+ ctx.fill();
+ ctx.stroke();
+ }
+
+
+ //Quick debug for bezier curve splining
+ //Highlights control points and the line between them.
+ //Handy for dev - stripped in the min version.
+
+ // ctx.save();
+ // ctx.fillStyle = "black";
+ // ctx.strokeStyle = "black"
+ // ctx.beginPath();
+ // ctx.arc(this.controlPoints.inner.x,this.controlPoints.inner.y, 2, 0, Math.PI*2);
+ // ctx.fill();
+
+ // ctx.beginPath();
+ // ctx.arc(this.controlPoints.outer.x,this.controlPoints.outer.y, 2, 0, Math.PI*2);
+ // ctx.fill();
+
+ // ctx.moveTo(this.controlPoints.inner.x,this.controlPoints.inner.y);
+ // ctx.lineTo(this.x, this.y);
+ // ctx.lineTo(this.controlPoints.outer.x,this.controlPoints.outer.y);
+ // ctx.stroke();
+
+ // ctx.restore();
+
+
+
+ }
+ });
+
+ Chart.Arc = Chart.Element.extend({
+ inRange : function(chartX,chartY){
+
+ var pointRelativePosition = helpers.getAngleFromPoint(this, {
+ x: chartX,
+ y: chartY
+ });
+
+ //Check if within the range of the open/close angle
+ var betweenAngles = (pointRelativePosition.angle >= this.startAngle && pointRelativePosition.angle <= this.endAngle),
+ withinRadius = (pointRelativePosition.distance >= this.innerRadius && pointRelativePosition.distance <= this.outerRadius);
+
+ return (betweenAngles && withinRadius);
+ //Ensure within the outside of the arc centre, but inside arc outer
+ },
+ tooltipPosition : function(){
+ var centreAngle = this.startAngle + ((this.endAngle - this.startAngle) / 2),
+ rangeFromCentre = (this.outerRadius - this.innerRadius) / 2 + this.innerRadius;
+ return {
+ x : this.x + (Math.cos(centreAngle) * rangeFromCentre),
+ y : this.y + (Math.sin(centreAngle) * rangeFromCentre)
+ };
+ },
+ draw : function(animationPercent){
+
+ var easingDecimal = animationPercent || 1;
+
+ var ctx = this.ctx;
+
+ ctx.beginPath();
+
+ ctx.arc(this.x, this.y, this.outerRadius, this.startAngle, this.endAngle);
+
+ ctx.arc(this.x, this.y, this.innerRadius, this.endAngle, this.startAngle, true);
+
+ ctx.closePath();
+ ctx.strokeStyle = this.strokeColor;
+ ctx.lineWidth = this.strokeWidth;
+
+ ctx.fillStyle = this.fillColor;
+
+ ctx.fill();
+ ctx.lineJoin = 'bevel';
+
+ if (this.showStroke){
+ ctx.stroke();
+ }
+ }
+ });
+
+ Chart.Rectangle = Chart.Element.extend({
+ draw : function(){
+ var ctx = this.ctx,
+ halfWidth = this.width/2,
+ leftX = this.x - halfWidth,
+ rightX = this.x + halfWidth,
+ top = this.base - (this.base - this.y),
+ halfStroke = this.strokeWidth / 2;
+
+ // Canvas doesn't allow us to stroke inside the width so we can
+ // adjust the sizes to fit if we're setting a stroke on the line
+ if (this.showStroke){
+ leftX += halfStroke;
+ rightX -= halfStroke;
+ top += halfStroke;
+ }
+
+ ctx.beginPath();
+
+ ctx.fillStyle = this.fillColor;
+ ctx.strokeStyle = this.strokeColor;
+ ctx.lineWidth = this.strokeWidth;
+
+ // It'd be nice to keep this class totally generic to any rectangle
+ // and simply specify which border to miss out.
+ ctx.moveTo(leftX, this.base);
+ ctx.lineTo(leftX, top);
+ ctx.lineTo(rightX, top);
+ ctx.lineTo(rightX, this.base);
+ ctx.fill();
+ if (this.showStroke){
+ ctx.stroke();
+ }
+ },
+ height : function(){
+ return this.base - this.y;
+ },
+ inRange : function(chartX,chartY){
+ return (chartX >= this.x - this.width/2 && chartX <= this.x + this.width/2) && (chartY >= this.y && chartY <= this.base);
+ }
+ });
+
+ Chart.Tooltip = Chart.Element.extend({
+ draw : function(){
+
+ var ctx = this.chart.ctx;
+
+ ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
+
+ this.xAlign = "center";
+ this.yAlign = "above";
+
+ //Distance between the actual element.y position and the start of the tooltip caret
+ var caretPadding = this.caretPadding = 2;
+
+ var tooltipWidth = ctx.measureText(this.text).width + 2*this.xPadding,
+ tooltipRectHeight = this.fontSize + 2*this.yPadding,
+ tooltipHeight = tooltipRectHeight + this.caretHeight + caretPadding;
+
+ if (this.x + tooltipWidth/2 >this.chart.width){
+ this.xAlign = "left";
+ } else if (this.x - tooltipWidth/2 < 0){
+ this.xAlign = "right";
+ }
+
+ if (this.y - tooltipHeight < 0){
+ this.yAlign = "below";
+ }
+
+
+ var tooltipX = this.x - tooltipWidth/2,
+ tooltipY = this.y - tooltipHeight;
+
+ ctx.fillStyle = this.fillColor;
+
+ // Custom Tooltips
+ if(this.custom){
+ this.custom(this);
+ }
+ else{
+ switch(this.yAlign)
+ {
+ case "above":
+ //Draw a caret above the x/y
+ ctx.beginPath();
+ ctx.moveTo(this.x,this.y - caretPadding);
+ ctx.lineTo(this.x + this.caretHeight, this.y - (caretPadding + this.caretHeight));
+ ctx.lineTo(this.x - this.caretHeight, this.y - (caretPadding + this.caretHeight));
+ ctx.closePath();
+ ctx.fill();
+ break;
+ case "below":
+ tooltipY = this.y + caretPadding + this.caretHeight;
+ //Draw a caret below the x/y
+ ctx.beginPath();
+ ctx.moveTo(this.x, this.y + caretPadding);
+ ctx.lineTo(this.x + this.caretHeight, this.y + caretPadding + this.caretHeight);
+ ctx.lineTo(this.x - this.caretHeight, this.y + caretPadding + this.caretHeight);
+ ctx.closePath();
+ ctx.fill();
+ break;
+ }
+
+ switch(this.xAlign)
+ {
+ case "left":
+ tooltipX = this.x - tooltipWidth + (this.cornerRadius + this.caretHeight);
+ break;
+ case "right":
+ tooltipX = this.x - (this.cornerRadius + this.caretHeight);
+ break;
+ }
+
+ drawRoundedRectangle(ctx,tooltipX,tooltipY,tooltipWidth,tooltipRectHeight,this.cornerRadius);
+
+ ctx.fill();
+
+ ctx.fillStyle = this.textColor;
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ ctx.fillText(this.text, tooltipX + tooltipWidth/2, tooltipY + tooltipRectHeight/2);
+ }
+ }
+ });
+
+ Chart.MultiTooltip = Chart.Element.extend({
+ initialize : function(){
+ this.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
+
+ this.titleFont = fontString(this.titleFontSize,this.titleFontStyle,this.titleFontFamily);
+
+ this.height = (this.labels.length * this.fontSize) + ((this.labels.length-1) * (this.fontSize/2)) + (this.yPadding*2) + this.titleFontSize *1.5;
+
+ this.ctx.font = this.titleFont;
+
+ var titleWidth = this.ctx.measureText(this.title).width,
+ //Label has a legend square as well so account for this.
+ labelWidth = longestText(this.ctx,this.font,this.labels) + this.fontSize + 3,
+ longestTextWidth = max([labelWidth,titleWidth]);
+
+ this.width = longestTextWidth + (this.xPadding*2);
+
+
+ var halfHeight = this.height/2;
+
+ //Check to ensure the height will fit on the canvas
+ if (this.y - halfHeight < 0 ){
+ this.y = halfHeight;
+ } else if (this.y + halfHeight > this.chart.height){
+ this.y = this.chart.height - halfHeight;
+ }
+
+ //Decide whether to align left or right based on position on canvas
+ if (this.x > this.chart.width/2){
+ this.x -= this.xOffset + this.width;
+ } else {
+ this.x += this.xOffset;
+ }
+
+
+ },
+ getLineHeight : function(index){
+ var baseLineHeight = this.y - (this.height/2) + this.yPadding,
+ afterTitleIndex = index-1;
+
+ //If the index is zero, we're getting the title
+ if (index === 0){
+ return baseLineHeight + this.titleFontSize/2;
+ } else{
+ return baseLineHeight + ((this.fontSize*1.5*afterTitleIndex) + this.fontSize/2) + this.titleFontSize * 1.5;
+ }
+
+ },
+ draw : function(){
+ // Custom Tooltips
+ if(this.custom){
+ this.custom(this);
+ }
+ else{
+ drawRoundedRectangle(this.ctx,this.x,this.y - this.height/2,this.width,this.height,this.cornerRadius);
+ var ctx = this.ctx;
+ ctx.fillStyle = this.fillColor;
+ ctx.fill();
+ ctx.closePath();
+
+ ctx.textAlign = "left";
+ ctx.textBaseline = "middle";
+ ctx.fillStyle = this.titleTextColor;
+ ctx.font = this.titleFont;
+
+ ctx.fillText(this.title,this.x + this.xPadding, this.getLineHeight(0));
+
+ ctx.font = this.font;
+ helpers.each(this.labels,function(label,index){
+ ctx.fillStyle = this.textColor;
+ ctx.fillText(label,this.x + this.xPadding + this.fontSize + 3, this.getLineHeight(index + 1));
+
+ //A bit gnarly, but clearing this rectangle breaks when using explorercanvas (clears whole canvas)
+ //ctx.clearRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
+ //Instead we'll make a white filled block to put the legendColour palette over.
+
+ ctx.fillStyle = this.legendColorBackground;
+ ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
+
+ ctx.fillStyle = this.legendColors[index].fill;
+ ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
+
+
+ },this);
+ }
+ }
+ });
+
+ Chart.Scale = Chart.Element.extend({
+ initialize : function(){
+ this.fit();
+ },
+ buildYLabels : function(){
+ this.yLabels = [];
+
+ var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
+
+ for (var i=0; i<=this.steps; i++){
+ this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
+ }
+ this.yLabelWidth = (this.display && this.showLabels) ? longestText(this.ctx,this.font,this.yLabels) : 0;
+ },
+ addXLabel : function(label){
+ this.xLabels.push(label);
+ this.valuesCount++;
+ this.fit();
+ },
+ removeXLabel : function(){
+ this.xLabels.shift();
+ this.valuesCount--;
+ this.fit();
+ },
+ // Fitting loop to rotate x Labels and figure out what fits there, and also calculate how many Y steps to use
+ fit: function(){
+ // First we need the width of the yLabels, assuming the xLabels aren't rotated
+
+ // To do that we need the base line at the top and base of the chart, assuming there is no x label rotation
+ this.startPoint = (this.display) ? this.fontSize : 0;
+ this.endPoint = (this.display) ? this.height - (this.fontSize * 1.5) - 5 : this.height; // -5 to pad labels
+
+ // Apply padding settings to the start and end point.
+ this.startPoint += this.padding;
+ this.endPoint -= this.padding;
+
+ // Cache the starting height, so can determine if we need to recalculate the scale yAxis
+ var cachedHeight = this.endPoint - this.startPoint,
+ cachedYLabelWidth;
+
+ // Build the current yLabels so we have an idea of what size they'll be to start
+ /*
+ * This sets what is returned from calculateScaleRange as static properties of this class:
+ *
+ this.steps;
+ this.stepValue;
+ this.min;
+ this.max;
+ *
+ */
+ this.calculateYRange(cachedHeight);
+
+ // With these properties set we can now build the array of yLabels
+ // and also the width of the largest yLabel
+ this.buildYLabels();
+
+ this.calculateXLabelRotation();
+
+ while((cachedHeight > this.endPoint - this.startPoint)){
+ cachedHeight = this.endPoint - this.startPoint;
+ cachedYLabelWidth = this.yLabelWidth;
+
+ this.calculateYRange(cachedHeight);
+ this.buildYLabels();
+
+ // Only go through the xLabel loop again if the yLabel width has changed
+ if (cachedYLabelWidth < this.yLabelWidth){
+ this.calculateXLabelRotation();
+ }
+ }
+
+ },
+ calculateXLabelRotation : function(){
+ //Get the width of each grid by calculating the difference
+ //between x offsets between 0 and 1.
+
+ this.ctx.font = this.font;
+
+ var firstWidth = this.ctx.measureText(this.xLabels[0]).width,
+ lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width,
+ firstRotated,
+ lastRotated;
+
+
+ this.xScalePaddingRight = lastWidth/2 + 3;
+ this.xScalePaddingLeft = (firstWidth/2 > this.yLabelWidth + 10) ? firstWidth/2 : this.yLabelWidth + 10;
+
+ this.xLabelRotation = 0;
+ if (this.display){
+ var originalLabelWidth = longestText(this.ctx,this.font,this.xLabels),
+ cosRotation,
+ firstRotatedWidth;
+ this.xLabelWidth = originalLabelWidth;
+ //Allow 3 pixels x2 padding either side for label readability
+ var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6;
+
+ //Max label rotate should be 90 - also act as a loop counter
+ while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)){
+ cosRotation = Math.cos(toRadians(this.xLabelRotation));
+
+ firstRotated = cosRotation * firstWidth;
+ lastRotated = cosRotation * lastWidth;
+
+ // We're right aligning the text now.
+ if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8){
+ this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
+ }
+ this.xScalePaddingRight = this.fontSize/2;
+
+
+ this.xLabelRotation++;
+ this.xLabelWidth = cosRotation * originalLabelWidth;
+
+ }
+ if (this.xLabelRotation > 0){
+ this.endPoint -= Math.sin(toRadians(this.xLabelRotation))*originalLabelWidth + 3;
+ }
+ }
+ else{
+ this.xLabelWidth = 0;
+ this.xScalePaddingRight = this.padding;
+ this.xScalePaddingLeft = this.padding;
+ }
+
+ },
+ // Needs to be overidden in each Chart type
+ // Otherwise we need to pass all the data into the scale class
+ calculateYRange: noop,
+ drawingArea: function(){
+ return this.startPoint - this.endPoint;
+ },
+ calculateY : function(value){
+ var scalingFactor = this.drawingArea() / (this.min - this.max);
+ return this.endPoint - (scalingFactor * (value - this.min));
+ },
+ calculateX : function(index){
+ var isRotated = (this.xLabelRotation > 0),
+ // innerWidth = (this.offsetGridLines) ? this.width - offsetLeft - this.padding : this.width - (offsetLeft + halfLabelWidth * 2) - this.padding,
+ innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight),
+ valueWidth = innerWidth/Math.max((this.valuesCount - ((this.offsetGridLines) ? 0 : 1)), 1),
+ valueOffset = (valueWidth * index) + this.xScalePaddingLeft;
+
+ if (this.offsetGridLines){
+ valueOffset += (valueWidth/2);
+ }
+
+ return Math.round(valueOffset);
+ },
+ update : function(newProps){
+ helpers.extend(this, newProps);
+ this.fit();
+ },
+ draw : function(){
+ var ctx = this.ctx,
+ yLabelGap = (this.endPoint - this.startPoint) / this.steps,
+ xStart = Math.round(this.xScalePaddingLeft);
+ if (this.display){
+ ctx.fillStyle = this.textColor;
+ ctx.font = this.font;
+ each(this.yLabels,function(labelString,index){
+ var yLabelCenter = this.endPoint - (yLabelGap * index),
+ linePositionY = Math.round(yLabelCenter),
+ drawHorizontalLine = this.showHorizontalLines;
+
+ ctx.textAlign = "right";
+ ctx.textBaseline = "middle";
+ if (this.showLabels){
+ ctx.fillText(labelString,xStart - 10,yLabelCenter);
+ }
+
+ // This is X axis, so draw it
+ if (index === 0 && !drawHorizontalLine){
+ drawHorizontalLine = true;
+ }
+
+ if (drawHorizontalLine){
+ ctx.beginPath();
+ }
+
+ if (index > 0){
+ // This is a grid line in the centre, so drop that
+ ctx.lineWidth = this.gridLineWidth;
+ ctx.strokeStyle = this.gridLineColor;
+ } else {
+ // This is the first line on the scale
+ ctx.lineWidth = this.lineWidth;
+ ctx.strokeStyle = this.lineColor;
+ }
+
+ linePositionY += helpers.aliasPixel(ctx.lineWidth);
+
+ if(drawHorizontalLine){
+ ctx.moveTo(xStart, linePositionY);
+ ctx.lineTo(this.width, linePositionY);
+ ctx.stroke();
+ ctx.closePath();
+ }
+
+ ctx.lineWidth = this.lineWidth;
+ ctx.strokeStyle = this.lineColor;
+ ctx.beginPath();
+ ctx.moveTo(xStart - 5, linePositionY);
+ ctx.lineTo(xStart, linePositionY);
+ ctx.stroke();
+ ctx.closePath();
+
+ },this);
+
+ each(this.xLabels,function(label,index){
+ var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
+ // Check to see if line/bar here and decide where to place the line
+ linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
+ isRotated = (this.xLabelRotation > 0),
+ drawVerticalLine = this.showVerticalLines;
+
+ // This is Y axis, so draw it
+ if (index === 0 && !drawVerticalLine){
+ drawVerticalLine = true;
+ }
+
+ if (drawVerticalLine){
+ ctx.beginPath();
+ }
+
+ if (index > 0){
+ // This is a grid line in the centre, so drop that
+ ctx.lineWidth = this.gridLineWidth;
+ ctx.strokeStyle = this.gridLineColor;
+ } else {
+ // This is the first line on the scale
+ ctx.lineWidth = this.lineWidth;
+ ctx.strokeStyle = this.lineColor;
+ }
+
+ if (drawVerticalLine){
+ ctx.moveTo(linePos,this.endPoint);
+ ctx.lineTo(linePos,this.startPoint - 3);
+ ctx.stroke();
+ ctx.closePath();
+ }
+
+
+ ctx.lineWidth = this.lineWidth;
+ ctx.strokeStyle = this.lineColor;
+
+
+ // Small lines at the bottom of the base grid line
+ ctx.beginPath();
+ ctx.moveTo(linePos,this.endPoint);
+ ctx.lineTo(linePos,this.endPoint + 5);
+ ctx.stroke();
+ ctx.closePath();
+
+ ctx.save();
+ ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
+ ctx.rotate(toRadians(this.xLabelRotation)*-1);
+ ctx.font = this.font;
+ ctx.textAlign = (isRotated) ? "right" : "center";
+ ctx.textBaseline = (isRotated) ? "middle" : "top";
+ ctx.fillText(label, 0, 0);
+ ctx.restore();
+ },this);
+
+ }
+ }
+
+ });
+
+ Chart.RadialScale = Chart.Element.extend({
+ initialize: function(){
+ this.size = min([this.height, this.width]);
+ this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
+ },
+ calculateCenterOffset: function(value){
+ // Take into account half font size + the yPadding of the top value
+ var scalingFactor = this.drawingArea / (this.max - this.min);
+
+ return (value - this.min) * scalingFactor;
+ },
+ update : function(){
+ if (!this.lineArc){
+ this.setScaleSize();
+ } else {
+ this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
+ }
+ this.buildYLabels();
+ },
+ buildYLabels: function(){
+ this.yLabels = [];
+
+ var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
+
+ for (var i=0; i<=this.steps; i++){
+ this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
+ }
+ },
+ getCircumference : function(){
+ return ((Math.PI*2) / this.valuesCount);
+ },
+ setScaleSize: function(){
+ /*
+ * Right, this is really confusing and there is a lot of maths going on here
+ * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
+ *
+ * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
+ *
+ * Solution:
+ *
+ * We assume the radius of the polygon is half the size of the canvas at first
+ * at each index we check if the text overlaps.
+ *
+ * Where it does, we store that angle and that index.
+ *
+ * After finding the largest index and angle we calculate how much we need to remove
+ * from the shape radius to move the point inwards by that x.
+ *
+ * We average the left and right distances to get the maximum shape radius that can fit in the box
+ * along with labels.
+ *
+ * Once we have that, we can find the centre point for the chart, by taking the x text protrusion
+ * on each side, removing that from the size, halving it and adding the left x protrusion width.
+ *
+ * This will mean we have a shape fitted to the canvas, as large as it can be with the labels
+ * and position it in the most space efficient manner
+ *
+ * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
+ */
+
+
+ // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
+ // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
+ var largestPossibleRadius = min([(this.height/2 - this.pointLabelFontSize - 5), this.width/2]),
+ pointPosition,
+ i,
+ textWidth,
+ halfTextWidth,
+ furthestRight = this.width,
+ furthestRightIndex,
+ furthestRightAngle,
+ furthestLeft = 0,
+ furthestLeftIndex,
+ furthestLeftAngle,
+ xProtrusionLeft,
+ xProtrusionRight,
+ radiusReductionRight,
+ radiusReductionLeft,
+ maxWidthRadius;
+ this.ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
+ for (i=0;i<this.valuesCount;i++){
+ // 5px to space the text slightly out - similar to what we do in the draw function.
+ pointPosition = this.getPointPosition(i, largestPossibleRadius);
+ textWidth = this.ctx.measureText(template(this.templateString, { value: this.labels[i] })).width + 5;
+ if (i === 0 || i === this.valuesCount/2){
+ // If we're at index zero, or exactly the middle, we're at exactly the top/bottom
+ // of the radar chart, so text will be aligned centrally, so we'll half it and compare
+ // w/left and right text sizes
+ halfTextWidth = textWidth/2;
+ if (pointPosition.x + halfTextWidth > furthestRight) {
+ furthestRight = pointPosition.x + halfTextWidth;
+ furthestRightIndex = i;
+ }
+ if (pointPosition.x - halfTextWidth < furthestLeft) {
+ furthestLeft = pointPosition.x - halfTextWidth;
+ furthestLeftIndex = i;
+ }
+ }
+ else if (i < this.valuesCount/2) {
+ // Less than half the values means we'll left align the text
+ if (pointPosition.x + textWidth > furthestRight) {
+ furthestRight = pointPosition.x + textWidth;
+ furthestRightIndex = i;
+ }
+ }
+ else if (i > this.valuesCount/2){
+ // More than half the values means we'll right align the text
+ if (pointPosition.x - textWidth < furthestLeft) {
+ furthestLeft = pointPosition.x - textWidth;
+ furthestLeftIndex = i;
+ }
+ }
+ }
+
+ xProtrusionLeft = furthestLeft;
+
+ xProtrusionRight = Math.ceil(furthestRight - this.width);
+
+ furthestRightAngle = this.getIndexAngle(furthestRightIndex);
+
+ furthestLeftAngle = this.getIndexAngle(furthestLeftIndex);
+
+ radiusReductionRight = xProtrusionRight / Math.sin(furthestRightAngle + Math.PI/2);
+
+ radiusReductionLeft = xProtrusionLeft / Math.sin(furthestLeftAngle + Math.PI/2);
+
+ // Ensure we actually need to reduce the size of the chart
+ radiusReductionRight = (isNumber(radiusReductionRight)) ? radiusReductionRight : 0;
+ radiusReductionLeft = (isNumber(radiusReductionLeft)) ? radiusReductionLeft : 0;
+
+ this.drawingArea = largestPossibleRadius - (radiusReductionLeft + radiusReductionRight)/2;
+
+ //this.drawingArea = min([maxWidthRadius, (this.height - (2 * (this.pointLabelFontSize + 5)))/2])
+ this.setCenterPoint(radiusReductionLeft, radiusReductionRight);
+
+ },
+ setCenterPoint: function(leftMovement, rightMovement){
+
+ var maxRight = this.width - rightMovement - this.drawingArea,
+ maxLeft = leftMovement + this.drawingArea;
+
+ this.xCenter = (maxLeft + maxRight)/2;
+ // Always vertically in the centre as the text height doesn't change
+ this.yCenter = (this.height/2);
+ },
+
+ getIndexAngle : function(index){
+ var angleMultiplier = (Math.PI * 2) / this.valuesCount;
+ // Start from the top instead of right, so remove a quarter of the circle
+
+ return index * angleMultiplier - (Math.PI/2);
+ },
+ getPointPosition : function(index, distanceFromCenter){
+ var thisAngle = this.getIndexAngle(index);
+ return {
+ x : (Math.cos(thisAngle) * distanceFromCenter) + this.xCenter,
+ y : (Math.sin(thisAngle) * distanceFromCenter) + this.yCenter
+ };
+ },
+ draw: function(){
+ if (this.display){
+ var ctx = this.ctx;
+ each(this.yLabels, function(label, index){
+ // Don't draw a centre value
+ if (index > 0){
+ var yCenterOffset = index * (this.drawingArea/this.steps),
+ yHeight = this.yCenter - yCenterOffset,
+ pointPosition;
+
+ // Draw circular lines around the scale
+ if (this.lineWidth > 0){
+ ctx.strokeStyle = this.lineColor;
+ ctx.lineWidth = this.lineWidth;
+
+ if(this.lineArc){
+ ctx.beginPath();
+ ctx.arc(this.xCenter, this.yCenter, yCenterOffset, 0, Math.PI*2);
+ ctx.closePath();
+ ctx.stroke();
+ } else{
+ ctx.beginPath();
+ for (var i=0;i<this.valuesCount;i++)
+ {
+ pointPosition = this.getPointPosition(i, this.calculateCenterOffset(this.min + (index * this.stepValue)));
+ if (i === 0){
+ ctx.moveTo(pointPosition.x, pointPosition.y);
+ } else {
+ ctx.lineTo(pointPosition.x, pointPosition.y);
+ }
+ }
+ ctx.closePath();
+ ctx.stroke();
+ }
+ }
+ if(this.showLabels){
+ ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
+ if (this.showLabelBackdrop){
+ var labelWidth = ctx.measureText(label).width;
+ ctx.fillStyle = this.backdropColor;
+ ctx.fillRect(
+ this.xCenter - labelWidth/2 - this.backdropPaddingX,
+ yHeight - this.fontSize/2 - this.backdropPaddingY,
+ labelWidth + this.backdropPaddingX*2,
+ this.fontSize + this.backdropPaddingY*2
+ );
+ }
+ ctx.textAlign = 'center';
+ ctx.textBaseline = "middle";
+ ctx.fillStyle = this.fontColor;
+ ctx.fillText(label, this.xCenter, yHeight);
+ }
+ }
+ }, this);
+
+ if (!this.lineArc){
+ ctx.lineWidth = this.angleLineWidth;
+ ctx.strokeStyle = this.angleLineColor;
+ for (var i = this.valuesCount - 1; i >= 0; i--) {
+ if (this.angleLineWidth > 0){
+ var outerPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max));
+ ctx.beginPath();
+ ctx.moveTo(this.xCenter, this.yCenter);
+ ctx.lineTo(outerPosition.x, outerPosition.y);
+ ctx.stroke();
+ ctx.closePath();
+ }
+ // Extra 3px out for some label spacing
+ var pointLabelPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max) + 5);
+ ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
+ ctx.fillStyle = this.pointLabelFontColor;
+
+ var labelsCount = this.labels.length,
+ halfLabelsCount = this.labels.length/2,
+ quarterLabelsCount = halfLabelsCount/2,
+ upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount),
+ exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount);
+ if (i === 0){
+ ctx.textAlign = 'center';
+ } else if(i === halfLabelsCount){
+ ctx.textAlign = 'center';
+ } else if (i < halfLabelsCount){
+ ctx.textAlign = 'left';
+ } else {
+ ctx.textAlign = 'right';
+ }
+
+ // Set the correct text baseline based on outer positioning
+ if (exactQuarter){
+ ctx.textBaseline = 'middle';
+ } else if (upperHalf){
+ ctx.textBaseline = 'bottom';
+ } else {
+ ctx.textBaseline = 'top';
+ }
+
+ ctx.fillText(this.labels[i], pointLabelPosition.x, pointLabelPosition.y);
+ }
+ }
+ }
+ }
+ });
+
+ // Attach global event to resize each chart instance when the browser resizes
+ helpers.addEvent(window, "resize", (function(){
+ // Basic debounce of resize function so it doesn't hurt performance when resizing browser.
+ var timeout;
+ return function(){
+ clearTimeout(timeout);
+ timeout = setTimeout(function(){
+ each(Chart.instances,function(instance){
+ // If the responsive flag is set in the chart instance config
+ // Cascade the resize event down to the chart.
+ if (instance.options.responsive){
+ instance.resize(instance.render, true);
+ }
+ });
+ }, 50);
+ };
+ })());
+
+
+ if (amd) {
+ define(function(){
+ return Chart;
+ });
+ } else if (typeof module === 'object' && module.exports) {
+ module.exports = Chart;
+ }
+
+ root.Chart = Chart;
+
+ Chart.noConflict = function(){
+ root.Chart = previous;
+ return Chart;
+ };
+
+}).call(this);
+
+(function(){
+ "use strict";
+
+ var root = this,
+ Chart = root.Chart,
+ helpers = Chart.helpers;
+
+
+ var defaultConfig = {
+ //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
+ scaleBeginAtZero : true,
+
+ //Boolean - Whether grid lines are shown across the chart
+ scaleShowGridLines : true,
+
+ //String - Colour of the grid lines
+ scaleGridLineColor : "rgba(0,0,0,.05)",
+
+ //Number - Width of the grid lines
+ scaleGridLineWidth : 1,
+
+ //Boolean - Whether to show horizontal lines (except X axis)
+ scaleShowHorizontalLines: true,
+
+ //Boolean - Whether to show vertical lines (except Y axis)
+ scaleShowVerticalLines: true,
+
+ //Boolean - If there is a stroke on each bar
+ barShowStroke : true,
+
+ //Number - Pixel width of the bar stroke
+ barStrokeWidth : 2,
+
+ //Number - Spacing between each of the X value sets
+ barValueSpacing : 5,
+
+ //Number - Spacing between data sets within X values
+ barDatasetSpacing : 1,
+
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
+
+ };
+
+
+ Chart.Type.extend({
+ name: "Bar",
+ defaults : defaultConfig,
+ initialize: function(data){
+
+ //Expose options as a scope variable here so we can access it in the ScaleClass
+ var options = this.options;
+
+ this.ScaleClass = Chart.Scale.extend({
+ offsetGridLines : true,
+ calculateBarX : function(datasetCount, datasetIndex, barIndex){
+ //Reusable method for calculating the xPosition of a given bar based on datasetIndex & width of the bar
+ var xWidth = this.calculateBaseWidth(),
+ xAbsolute = this.calculateX(barIndex) - (xWidth/2),
+ barWidth = this.calculateBarWidth(datasetCount);
+
+ return xAbsolute + (barWidth * datasetIndex) + (datasetIndex * options.barDatasetSpacing) + barWidth/2;
+ },
+ calculateBaseWidth : function(){
+ return (this.calculateX(1) - this.calculateX(0)) - (2*options.barValueSpacing);
+ },
+ calculateBarWidth : function(datasetCount){
+ //The padding between datasets is to the right of each bar, providing that there are more than 1 dataset
+ var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing);
+
+ return (baseWidth / datasetCount);
+ }
+ });
+
+ this.datasets = [];
+
+ //Set up tooltip events on the chart
+ if (this.options.showTooltips){
+ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
+ var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : [];
+
+ this.eachBars(function(bar){
+ bar.restore(['fillColor', 'strokeColor']);
+ });
+ helpers.each(activeBars, function(activeBar){
+ activeBar.fillColor = activeBar.highlightFill;
+ activeBar.strokeColor = activeBar.highlightStroke;
+ });
+ this.showTooltip(activeBars);
+ });
+ }
+
+ //Declare the extension of the default point, to cater for the options passed in to the constructor
+ this.BarClass = Chart.Rectangle.extend({
+ strokeWidth : this.options.barStrokeWidth,
+ showStroke : this.options.barShowStroke,
+ ctx : this.chart.ctx
+ });
+
+ //Iterate through each of the datasets, and build this into a property of the chart
+ helpers.each(data.datasets,function(dataset,datasetIndex){
+
+ var datasetObject = {
+ label : dataset.label || null,
+ fillColor : dataset.fillColor,
+ strokeColor : dataset.strokeColor,
+ bars : []
+ };
+
+ this.datasets.push(datasetObject);
+
+ helpers.each(dataset.data,function(dataPoint,index){
+ //Add a new point for each piece of data, passing any required data to draw.
+ datasetObject.bars.push(new this.BarClass({
+ value : dataPoint,
+ label : data.labels[index],
+ datasetLabel: dataset.label,
+ strokeColor : dataset.strokeColor,
+ fillColor : dataset.fillColor,
+ highlightFill : dataset.highlightFill || dataset.fillColor,
+ highlightStroke : dataset.highlightStroke || dataset.strokeColor
+ }));
+ },this);
+
+ },this);
+
+ this.buildScale(data.labels);
+
+ this.BarClass.prototype.base = this.scale.endPoint;
+
+ this.eachBars(function(bar, index, datasetIndex){
+ helpers.extend(bar, {
+ width : this.scale.calculateBarWidth(this.datasets.length),
+ x: this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
+ y: this.scale.endPoint
+ });
+ bar.save();
+ }, this);
+
+ this.render();
+ },
+ update : function(){
+ this.scale.update();
+ // Reset any highlight colours before updating.
+ helpers.each(this.activeElements, function(activeElement){
+ activeElement.restore(['fillColor', 'strokeColor']);
+ });
+
+ this.eachBars(function(bar){
+ bar.save();
+ });
+ this.render();
+ },
+ eachBars : function(callback){
+ helpers.each(this.datasets,function(dataset, datasetIndex){
+ helpers.each(dataset.bars, callback, this, datasetIndex);
+ },this);
+ },
+ getBarsAtEvent : function(e){
+ var barsArray = [],
+ eventPosition = helpers.getRelativePosition(e),
+ datasetIterator = function(dataset){
+ barsArray.push(dataset.bars[barIndex]);
+ },
+ barIndex;
+
+ for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) {
+ for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) {
+ if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){
+ helpers.each(this.datasets, datasetIterator);
+ return barsArray;
+ }
+ }
+ }
+
+ return barsArray;
+ },
+ buildScale : function(labels){
+ var self = this;
+
+ var dataTotal = function(){
+ var values = [];
+ self.eachBars(function(bar){
+ values.push(bar.value);
+ });
+ return values;
+ };
+
+ var scaleOptions = {
+ templateString : this.options.scaleLabel,
+ height : this.chart.height,
+ width : this.chart.width,
+ ctx : this.chart.ctx,
+ textColor : this.options.scaleFontColor,
+ fontSize : this.options.scaleFontSize,
+ fontStyle : this.options.scaleFontStyle,
+ fontFamily : this.options.scaleFontFamily,
+ valuesCount : labels.length,
+ beginAtZero : this.options.scaleBeginAtZero,
+ integersOnly : this.options.scaleIntegersOnly,
+ calculateYRange: function(currentHeight){
+ var updatedRanges = helpers.calculateScaleRange(
+ dataTotal(),
+ currentHeight,
+ this.fontSize,
+ this.beginAtZero,
+ this.integersOnly
+ );
+ helpers.extend(this, updatedRanges);
+ },
+ xLabels : labels,
+ font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
+ lineWidth : this.options.scaleLineWidth,
+ lineColor : this.options.scaleLineColor,
+ showHorizontalLines : this.options.scaleShowHorizontalLines,
+ showVerticalLines : this.options.scaleShowVerticalLines,
+ gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
+ gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
+ padding : (this.options.showScale) ? 0 : (this.options.barShowStroke) ? this.options.barStrokeWidth : 0,
+ showLabels : this.options.scaleShowLabels,
+ display : this.options.showScale
+ };
+
+ if (this.options.scaleOverride){
+ helpers.extend(scaleOptions, {
+ calculateYRange: helpers.noop,
+ steps: this.options.scaleSteps,
+ stepValue: this.options.scaleStepWidth,
+ min: this.options.scaleStartValue,
+ max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
+ });
+ }
+
+ this.scale = new this.ScaleClass(scaleOptions);
+ },
+ addData : function(valuesArray,label){
+ //Map the values array for each of the datasets
+ helpers.each(valuesArray,function(value,datasetIndex){
+ //Add a new point for each piece of data, passing any required data to draw.
+ this.datasets[datasetIndex].bars.push(new this.BarClass({
+ value : value,
+ label : label,
+ x: this.scale.calculateBarX(this.datasets.length, datasetIndex, this.scale.valuesCount+1),
+ y: this.scale.endPoint,
+ width : this.scale.calculateBarWidth(this.datasets.length),
+ base : this.scale.endPoint,
+ strokeColor : this.datasets[datasetIndex].strokeColor,
+ fillColor : this.datasets[datasetIndex].fillColor
+ }));
+ },this);
+
+ this.scale.addXLabel(label);
+ //Then re-render the chart.
+ this.update();
+ },
+ removeData : function(){
+ this.scale.removeXLabel();
+ //Then re-render the chart.
+ helpers.each(this.datasets,function(dataset){
+ dataset.bars.shift();
+ },this);
+ this.update();
+ },
+ reflow : function(){
+ helpers.extend(this.BarClass.prototype,{
+ y: this.scale.endPoint,
+ base : this.scale.endPoint
+ });
+ var newScaleProps = helpers.extend({
+ height : this.chart.height,
+ width : this.chart.width
+ });
+ this.scale.update(newScaleProps);
+ },
+ draw : function(ease){
+ var easingDecimal = ease || 1;
+ this.clear();
+
+ var ctx = this.chart.ctx;
+
+ this.scale.draw(easingDecimal);
+
+ //Draw all the bars for each dataset
+ helpers.each(this.datasets,function(dataset,datasetIndex){
+ helpers.each(dataset.bars,function(bar,index){
+ if (bar.hasValue()){
+ bar.base = this.scale.endPoint;
+ //Transition then draw
+ bar.transition({
+ x : this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
+ y : this.scale.calculateY(bar.value),
+ width : this.scale.calculateBarWidth(this.datasets.length)
+ }, easingDecimal).draw();
+ }
+ },this);
+
+ },this);
+ }
+ });
+
+
+}).call(this);
+
+(function(){
+ "use strict";
+
+ var root = this,
+ Chart = root.Chart,
+ //Cache a local reference to Chart.helpers
+ helpers = Chart.helpers;
+
+ var defaultConfig = {
+ //Boolean - Whether we should show a stroke on each segment
+ segmentShowStroke : true,
+
+ //String - The colour of each segment stroke
+ segmentStrokeColor : "#fff",
+
+ //Number - The width of each segment stroke
+ segmentStrokeWidth : 2,
+
+ //The percentage of the chart that we cut out of the middle.
+ percentageInnerCutout : 50,
+
+ //Number - Amount of animation steps
+ animationSteps : 100,
+
+ //String - Animation easing effect
+ animationEasing : "easeOutBounce",
+
+ //Boolean - Whether we animate the rotation of the Doughnut
+ animateRotate : true,
+
+ //Boolean - Whether we animate scaling the Doughnut from the centre
+ animateScale : false,
+
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
+
+ };
+
+
+ Chart.Type.extend({
+ //Passing in a name registers this chart in the Chart namespace
+ name: "Doughnut",
+ //Providing a defaults will also register the deafults in the chart namespace
+ defaults : defaultConfig,
+ //Initialize is fired when the chart is initialized - Data is passed in as a parameter
+ //Config is automatically merged by the core of Chart.js, and is available at this.options
+ initialize: function(data){
+
+ //Declare segments as a static property to prevent inheriting across the Chart type prototype
+ this.segments = [];
+ this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2;
+
+ this.SegmentArc = Chart.Arc.extend({
+ ctx : this.chart.ctx,
+ x : this.chart.width/2,
+ y : this.chart.height/2
+ });
+
+ //Set up tooltip events on the chart
+ if (this.options.showTooltips){
+ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
+ var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];
+
+ helpers.each(this.segments,function(segment){
+ segment.restore(["fillColor"]);
+ });
+ helpers.each(activeSegments,function(activeSegment){
+ activeSegment.fillColor = activeSegment.highlightColor;
+ });
+ this.showTooltip(activeSegments);
+ });
+ }
+ this.calculateTotal(data);
+
+ helpers.each(data,function(datapoint, index){
+ this.addData(datapoint, index, true);
+ },this);
+
+ this.render();
+ },
+ getSegmentsAtEvent : function(e){
+ var segmentsArray = [];
+
+ var location = helpers.getRelativePosition(e);
+
+ helpers.each(this.segments,function(segment){
+ if (segment.inRange(location.x,location.y)) segmentsArray.push(segment);
+ },this);
+ return segmentsArray;
+ },
+ addData : function(segment, atIndex, silent){
+ var index = atIndex || this.segments.length;
+ this.segments.splice(index, 0, new this.SegmentArc({
+ value : segment.value,
+ outerRadius : (this.options.animateScale) ? 0 : this.outerRadius,
+ innerRadius : (this.options.animateScale) ? 0 : (this.outerRadius/100) * this.options.percentageInnerCutout,
+ fillColor : segment.color,
+ highlightColor : segment.highlight || segment.color,
+ showStroke : this.options.segmentShowStroke,
+ strokeWidth : this.options.segmentStrokeWidth,
+ strokeColor : this.options.segmentStrokeColor,
+ startAngle : Math.PI * 1.5,
+ circumference : (this.options.animateRotate) ? 0 : this.calculateCircumference(segment.value),
+ label : segment.label
+ }));
+ if (!silent){
+ this.reflow();
+ this.update();
+ }
+ },
+ calculateCircumference : function(value){
+ return (Math.PI*2)*(Math.abs(value) / this.total);
+ },
+ calculateTotal : function(data){
+ this.total = 0;
+ helpers.each(data,function(segment){
+ this.total += Math.abs(segment.value);
+ },this);
+ },
+ update : function(){
+ this.calculateTotal(this.segments);
+
+ // Reset any highlight colours before updating.
+ helpers.each(this.activeElements, function(activeElement){
+ activeElement.restore(['fillColor']);
+ });
+
+ helpers.each(this.segments,function(segment){
+ segment.save();
+ });
+ this.render();
+ },
+
+ removeData: function(atIndex){
+ var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1;
+ this.segments.splice(indexToDelete, 1);
+ this.reflow();
+ this.update();
+ },
+
+ reflow : function(){
+ helpers.extend(this.SegmentArc.prototype,{
+ x : this.chart.width/2,
+ y : this.chart.height/2
+ });
+ this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2;
+ helpers.each(this.segments, function(segment){
+ segment.update({
+ outerRadius : this.outerRadius,
+ innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout
+ });
+ }, this);
+ },
+ draw : function(easeDecimal){
+ var animDecimal = (easeDecimal) ? easeDecimal : 1;
+ this.clear();
+ helpers.each(this.segments,function(segment,index){
+ segment.transition({
+ circumference : this.calculateCircumference(segment.value),
+ outerRadius : this.outerRadius,
+ innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout
+ },animDecimal);
+
+ segment.endAngle = segment.startAngle + segment.circumference;
+
+ segment.draw();
+ if (index === 0){
+ segment.startAngle = Math.PI * 1.5;
+ }
+ //Check to see if it's the last segment, if not get the next and update the start angle
+ if (index < this.segments.length-1){
+ this.segments[index+1].startAngle = segment.endAngle;
+ }
+ },this);
+
+ }
+ });
+
+ Chart.types.Doughnut.extend({
+ name : "Pie",
+ defaults : helpers.merge(defaultConfig,{percentageInnerCutout : 0})
+ });
+
+}).call(this);
+(function(){
+ "use strict";
+
+ var root = this,
+ Chart = root.Chart,
+ helpers = Chart.helpers;
+
+ var defaultConfig = {
+
+ ///Boolean - Whether grid lines are shown across the chart
+ scaleShowGridLines : true,
+
+ //String - Colour of the grid lines
+ scaleGridLineColor : "rgba(0,0,0,.05)",
+
+ //Number - Width of the grid lines
+ scaleGridLineWidth : 1,
+
+ //Boolean - Whether to show horizontal lines (except X axis)
+ scaleShowHorizontalLines: true,
+
+ //Boolean - Whether to show vertical lines (except Y axis)
+ scaleShowVerticalLines: true,
+
+ //Boolean - Whether the line is curved between points
+ bezierCurve : true,
+
+ //Number - Tension of the bezier curve between points
+ bezierCurveTension : 0.4,
+
+ //Boolean - Whether to show a dot for each point
+ pointDot : true,
+
+ //Number - Radius of each point dot in pixels
+ pointDotRadius : 4,
+
+ //Number - Pixel width of point dot stroke
+ pointDotStrokeWidth : 1,
+
+ //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
+ pointHitDetectionRadius : 20,
+
+ //Boolean - Whether to show a stroke for datasets
+ datasetStroke : true,
+
+ //Number - Pixel width of dataset stroke
+ datasetStrokeWidth : 2,
+
+ //Boolean - Whether to fill the dataset with a colour
+ datasetFill : true,
+
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
+
+ };
+
+
+ Chart.Type.extend({
+ name: "Line",
+ defaults : defaultConfig,
+ initialize: function(data){
+ //Declare the extension of the default point, to cater for the options passed in to the constructor
+ this.PointClass = Chart.Point.extend({
+ strokeWidth : this.options.pointDotStrokeWidth,
+ radius : this.options.pointDotRadius,
+ display: this.options.pointDot,
+ hitDetectionRadius : this.options.pointHitDetectionRadius,
+ ctx : this.chart.ctx,
+ inRange : function(mouseX){
+ return (Math.pow(mouseX-this.x, 2) < Math.pow(this.radius + this.hitDetectionRadius,2));
+ }
+ });
+
+ this.datasets = [];
+
+ //Set up tooltip events on the chart
+ if (this.options.showTooltips){
+ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
+ var activePoints = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
+ this.eachPoints(function(point){
+ point.restore(['fillColor', 'strokeColor']);
+ });
+ helpers.each(activePoints, function(activePoint){
+ activePoint.fillColor = activePoint.highlightFill;
+ activePoint.strokeColor = activePoint.highlightStroke;
+ });
+ this.showTooltip(activePoints);
+ });
+ }
+
+ //Iterate through each of the datasets, and build this into a property of the chart
+ helpers.each(data.datasets,function(dataset){
+
+ var datasetObject = {
+ label : dataset.label || null,
+ fillColor : dataset.fillColor,
+ strokeColor : dataset.strokeColor,
+ pointColor : dataset.pointColor,
+ pointStrokeColor : dataset.pointStrokeColor,
+ points : []
+ };
+
+ this.datasets.push(datasetObject);
+
+
+ helpers.each(dataset.data,function(dataPoint,index){
+ //Add a new point for each piece of data, passing any required data to draw.
+ datasetObject.points.push(new this.PointClass({
+ value : dataPoint,
+ label : data.labels[index],
+ datasetLabel: dataset.label,
+ strokeColor : dataset.pointStrokeColor,
+ fillColor : dataset.pointColor,
+ highlightFill : dataset.pointHighlightFill || dataset.pointColor,
+ highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor
+ }));
+ },this);
+
+ this.buildScale(data.labels);
+
+
+ this.eachPoints(function(point, index){
+ helpers.extend(point, {
+ x: this.scale.calculateX(index),
+ y: this.scale.endPoint
+ });
+ point.save();
+ }, this);
+
+ },this);
+
+
+ this.render();
+ },
+ update : function(){
+ this.scale.update();
+ // Reset any highlight colours before updating.
+ helpers.each(this.activeElements, function(activeElement){
+ activeElement.restore(['fillColor', 'strokeColor']);
+ });
+ this.eachPoints(function(point){
+ point.save();
+ });
+ this.render();
+ },
+ eachPoints : function(callback){
+ helpers.each(this.datasets,function(dataset){
+ helpers.each(dataset.points,callback,this);
+ },this);
+ },
+ getPointsAtEvent : function(e){
+ var pointsArray = [],
+ eventPosition = helpers.getRelativePosition(e);
+ helpers.each(this.datasets,function(dataset){
+ helpers.each(dataset.points,function(point){
+ if (point.inRange(eventPosition.x,eventPosition.y)) pointsArray.push(point);
+ });
+ },this);
+ return pointsArray;
+ },
+ buildScale : function(labels){
+ var self = this;
+
+ var dataTotal = function(){
+ var values = [];
+ self.eachPoints(function(point){
+ values.push(point.value);
+ });
+
+ return values;
+ };
+
+ var scaleOptions = {
+ templateString : this.options.scaleLabel,
+ height : this.chart.height,
+ width : this.chart.width,
+ ctx : this.chart.ctx,
+ textColor : this.options.scaleFontColor,
+ fontSize : this.options.scaleFontSize,
+ fontStyle : this.options.scaleFontStyle,
+ fontFamily : this.options.scaleFontFamily,
+ valuesCount : labels.length,
+ beginAtZero : this.options.scaleBeginAtZero,
+ integersOnly : this.options.scaleIntegersOnly,
+ calculateYRange : function(currentHeight){
+ var updatedRanges = helpers.calculateScaleRange(
+ dataTotal(),
+ currentHeight,
+ this.fontSize,
+ this.beginAtZero,
+ this.integersOnly
+ );
+ helpers.extend(this, updatedRanges);
+ },
+ xLabels : labels,
+ font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
+ lineWidth : this.options.scaleLineWidth,
+ lineColor : this.options.scaleLineColor,
+ showHorizontalLines : this.options.scaleShowHorizontalLines,
+ showVerticalLines : this.options.scaleShowVerticalLines,
+ gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
+ gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
+ padding: (this.options.showScale) ? 0 : this.options.pointDotRadius + this.options.pointDotStrokeWidth,
+ showLabels : this.options.scaleShowLabels,
+ display : this.options.showScale
+ };
+
+ if (this.options.scaleOverride){
+ helpers.extend(scaleOptions, {
+ calculateYRange: helpers.noop,
+ steps: this.options.scaleSteps,
+ stepValue: this.options.scaleStepWidth,
+ min: this.options.scaleStartValue,
+ max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
+ });
+ }
+
+
+ this.scale = new Chart.Scale(scaleOptions);
+ },
+ addData : function(valuesArray,label){
+ //Map the values array for each of the datasets
+
+ helpers.each(valuesArray,function(value,datasetIndex){
+ //Add a new point for each piece of data, passing any required data to draw.
+ this.datasets[datasetIndex].points.push(new this.PointClass({
+ value : value,
+ label : label,
+ x: this.scale.calculateX(this.scale.valuesCount+1),
+ y: this.scale.endPoint,
+ strokeColor : this.datasets[datasetIndex].pointStrokeColor,
+ fillColor : this.datasets[datasetIndex].pointColor
+ }));
+ },this);
+
+ this.scale.addXLabel(label);
+ //Then re-render the chart.
+ this.update();
+ },
+ removeData : function(){
+ this.scale.removeXLabel();
+ //Then re-render the chart.
+ helpers.each(this.datasets,function(dataset){
+ dataset.points.shift();
+ },this);
+ this.update();
+ },
+ reflow : function(){
+ var newScaleProps = helpers.extend({
+ height : this.chart.height,
+ width : this.chart.width
+ });
+ this.scale.update(newScaleProps);
+ },
+ draw : function(ease){
+ var easingDecimal = ease || 1;
+ this.clear();
+
+ var ctx = this.chart.ctx;
+
+ // Some helper methods for getting the next/prev points
+ var hasValue = function(item){
+ return item.value !== null;
+ },
+ nextPoint = function(point, collection, index){
+ return helpers.findNextWhere(collection, hasValue, index) || point;
+ },
+ previousPoint = function(point, collection, index){
+ return helpers.findPreviousWhere(collection, hasValue, index) || point;
+ };
+
+ this.scale.draw(easingDecimal);
+
+
+ helpers.each(this.datasets,function(dataset){
+ var pointsWithValues = helpers.where(dataset.points, hasValue);
+
+ //Transition each point first so that the line and point drawing isn't out of sync
+ //We can use this extra loop to calculate the control points of this dataset also in this loop
+
+ helpers.each(dataset.points, function(point, index){
+ if (point.hasValue()){
+ point.transition({
+ y : this.scale.calculateY(point.value),
+ x : this.scale.calculateX(index)
+ }, easingDecimal);
+ }
+ },this);
+
+
+ // Control points need to be calculated in a seperate loop, because we need to know the current x/y of the point
+ // This would cause issues when there is no animation, because the y of the next point would be 0, so beziers would be skewed
+ if (this.options.bezierCurve){
+ helpers.each(pointsWithValues, function(point, index){
+ var tension = (index > 0 && index < pointsWithValues.length - 1) ? this.options.bezierCurveTension : 0;
+ point.controlPoints = helpers.splineCurve(
+ previousPoint(point, pointsWithValues, index),
+ point,
+ nextPoint(point, pointsWithValues, index),
+ tension
+ );
+
+ // Prevent the bezier going outside of the bounds of the graph
+
+ // Cap puter bezier handles to the upper/lower scale bounds
+ if (point.controlPoints.outer.y > this.scale.endPoint){
+ point.controlPoints.outer.y = this.scale.endPoint;
+ }
+ else if (point.controlPoints.outer.y < this.scale.startPoint){
+ point.controlPoints.outer.y = this.scale.startPoint;
+ }
+
+ // Cap inner bezier handles to the upper/lower scale bounds
+ if (point.controlPoints.inner.y > this.scale.endPoint){
+ point.controlPoints.inner.y = this.scale.endPoint;
+ }
+ else if (point.controlPoints.inner.y < this.scale.startPoint){
+ point.controlPoints.inner.y = this.scale.startPoint;
+ }
+ },this);
+ }
+
+
+ //Draw the line between all the points
+ ctx.lineWidth = this.options.datasetStrokeWidth;
+ ctx.strokeStyle = dataset.strokeColor;
+ ctx.beginPath();
+
+ helpers.each(pointsWithValues, function(point, index){
+ if (index === 0){
+ ctx.moveTo(point.x, point.y);
+ }
+ else{
+ if(this.options.bezierCurve){
+ var previous = previousPoint(point, pointsWithValues, index);
+
+ ctx.bezierCurveTo(
+ previous.controlPoints.outer.x,
+ previous.controlPoints.outer.y,
+ point.controlPoints.inner.x,
+ point.controlPoints.inner.y,
+ point.x,
+ point.y
+ );
+ }
+ else{
+ ctx.lineTo(point.x,point.y);
+ }
+ }
+ }, this);
+
+ ctx.stroke();
+
+ if (this.options.datasetFill && pointsWithValues.length > 0){
+ //Round off the line by going to the base of the chart, back to the start, then fill.
+ ctx.lineTo(pointsWithValues[pointsWithValues.length - 1].x, this.scale.endPoint);
+ ctx.lineTo(pointsWithValues[0].x, this.scale.endPoint);
+ ctx.fillStyle = dataset.fillColor;
+ ctx.closePath();
+ ctx.fill();
+ }
+
+ //Now draw the points over the line
+ //A little inefficient double looping, but better than the line
+ //lagging behind the point positions
+ helpers.each(pointsWithValues,function(point){
+ point.draw();
+ });
+ },this);
+ }
+ });
+
+
+}).call(this);
+
+(function(){
+ "use strict";
+
+ var root = this,
+ Chart = root.Chart,
+ //Cache a local reference to Chart.helpers
+ helpers = Chart.helpers;
+
+ var defaultConfig = {
+ //Boolean - Show a backdrop to the scale label
+ scaleShowLabelBackdrop : true,
+
+ //String - The colour of the label backdrop
+ scaleBackdropColor : "rgba(255,255,255,0.75)",
+
+ // Boolean - Whether the scale should begin at zero
+ scaleBeginAtZero : true,
+
+ //Number - The backdrop padding above & below the label in pixels
+ scaleBackdropPaddingY : 2,
+
+ //Number - The backdrop padding to the side of the label in pixels
+ scaleBackdropPaddingX : 2,
+
+ //Boolean - Show line for each value in the scale
+ scaleShowLine : true,
+
+ //Boolean - Stroke a line around each segment in the chart
+ segmentShowStroke : true,
+
+ //String - The colour of the stroke on each segement.
+ segmentStrokeColor : "#fff",
+
+ //Number - The width of the stroke value in pixels
+ segmentStrokeWidth : 2,
+
+ //Number - Amount of animation steps
+ animationSteps : 100,
+
+ //String - Animation easing effect.
+ animationEasing : "easeOutBounce",
+
+ //Boolean - Whether to animate the rotation of the chart
+ animateRotate : true,
+
+ //Boolean - Whether to animate scaling the chart from the centre
+ animateScale : false,
+
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
+ };
+
+
+ Chart.Type.extend({
+ //Passing in a name registers this chart in the Chart namespace
+ name: "PolarArea",
+ //Providing a defaults will also register the deafults in the chart namespace
+ defaults : defaultConfig,
+ //Initialize is fired when the chart is initialized - Data is passed in as a parameter
+ //Config is automatically merged by the core of Chart.js, and is available at this.options
+ initialize: function(data){
+ this.segments = [];
+ //Declare segment class as a chart instance specific class, so it can share props for this instance
+ this.SegmentArc = Chart.Arc.extend({
+ showStroke : this.options.segmentShowStroke,
+ strokeWidth : this.options.segmentStrokeWidth,
+ strokeColor : this.options.segmentStrokeColor,
+ ctx : this.chart.ctx,
+ innerRadius : 0,
+ x : this.chart.width/2,
+ y : this.chart.height/2
+ });
+ this.scale = new Chart.RadialScale({
+ display: this.options.showScale,
+ fontStyle: this.options.scaleFontStyle,
+ fontSize: this.options.scaleFontSize,
+ fontFamily: this.options.scaleFontFamily,
+ fontColor: this.options.scaleFontColor,
+ showLabels: this.options.scaleShowLabels,
+ showLabelBackdrop: this.options.scaleShowLabelBackdrop,
+ backdropColor: this.options.scaleBackdropColor,
+ backdropPaddingY : this.options.scaleBackdropPaddingY,
+ backdropPaddingX: this.options.scaleBackdropPaddingX,
+ lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0,
+ lineColor: this.options.scaleLineColor,
+ lineArc: true,
+ width: this.chart.width,
+ height: this.chart.height,
+ xCenter: this.chart.width/2,
+ yCenter: this.chart.height/2,
+ ctx : this.chart.ctx,
+ templateString: this.options.scaleLabel,
+ valuesCount: data.length
+ });
+
+ this.updateScaleRange(data);
+
+ this.scale.update();
+
+ helpers.each(data,function(segment,index){
+ this.addData(segment,index,true);
+ },this);
+
+ //Set up tooltip events on the chart
+ if (this.options.showTooltips){
+ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
+ var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];
+ helpers.each(this.segments,function(segment){
+ segment.restore(["fillColor"]);
+ });
+ helpers.each(activeSegments,function(activeSegment){
+ activeSegment.fillColor = activeSegment.highlightColor;
+ });
+ this.showTooltip(activeSegments);
+ });
+ }
+
+ this.render();
+ },
+ getSegmentsAtEvent : function(e){
+ var segmentsArray = [];
+
+ var location = helpers.getRelativePosition(e);
+
+ helpers.each(this.segments,function(segment){
+ if (segment.inRange(location.x,location.y)) segmentsArray.push(segment);
+ },this);
+ return segmentsArray;
+ },
+ addData : function(segment, atIndex, silent){
+ var index = atIndex || this.segments.length;
+
+ this.segments.splice(index, 0, new this.SegmentArc({
+ fillColor: segment.color,
+ highlightColor: segment.highlight || segment.color,
+ label: segment.label,
+ value: segment.value,
+ outerRadius: (this.options.animateScale) ? 0 : this.scale.calculateCenterOffset(segment.value),
+ circumference: (this.options.animateRotate) ? 0 : this.scale.getCircumference(),
+ startAngle: Math.PI * 1.5
+ }));
+ if (!silent){
+ this.reflow();
+ this.update();
+ }
+ },
+ removeData: function(atIndex){
+ var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1;
+ this.segments.splice(indexToDelete, 1);
+ this.reflow();
+ this.update();
+ },
+ calculateTotal: function(data){
+ this.total = 0;
+ helpers.each(data,function(segment){
+ this.total += segment.value;
+ },this);
+ this.scale.valuesCount = this.segments.length;
+ },
+ updateScaleRange: function(datapoints){
+ var valuesArray = [];
+ helpers.each(datapoints,function(segment){
+ valuesArray.push(segment.value);
+ });
+
+ var scaleSizes = (this.options.scaleOverride) ?
+ {
+ steps: this.options.scaleSteps,
+ stepValue: this.options.scaleStepWidth,
+ min: this.options.scaleStartValue,
+ max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
+ } :
+ helpers.calculateScaleRange(
+ valuesArray,
+ helpers.min([this.chart.width, this.chart.height])/2,
+ this.options.scaleFontSize,
+ this.options.scaleBeginAtZero,
+ this.options.scaleIntegersOnly
+ );
+
+ helpers.extend(
+ this.scale,
+ scaleSizes,
+ {
+ size: helpers.min([this.chart.width, this.chart.height]),
+ xCenter: this.chart.width/2,
+ yCenter: this.chart.height/2
+ }
+ );
+
+ },
+ update : function(){
+ this.calculateTotal(this.segments);
+
+ helpers.each(this.segments,function(segment){
+ segment.save();
+ });
+
+ this.reflow();
+ this.render();
+ },
+ reflow : function(){
+ helpers.extend(this.SegmentArc.prototype,{
+ x : this.chart.width/2,
+ y : this.chart.height/2
+ });
+ this.updateScaleRange(this.segments);
+ this.scale.update();
+
+ helpers.extend(this.scale,{
+ xCenter: this.chart.width/2,
+ yCenter: this.chart.height/2
+ });
+
+ helpers.each(this.segments, function(segment){
+ segment.update({
+ outerRadius : this.scale.calculateCenterOffset(segment.value)
+ });
+ }, this);
+
+ },
+ draw : function(ease){
+ var easingDecimal = ease || 1;
+ //Clear & draw the canvas
+ this.clear();
+ helpers.each(this.segments,function(segment, index){
+ segment.transition({
+ circumference : this.scale.getCircumference(),
+ outerRadius : this.scale.calculateCenterOffset(segment.value)
+ },easingDecimal);
+
+ segment.endAngle = segment.startAngle + segment.circumference;
+
+ // If we've removed the first segment we need to set the first one to
+ // start at the top.
+ if (index === 0){
+ segment.startAngle = Math.PI * 1.5;
+ }
+
+ //Check to see if it's the last segment, if not get the next and update the start angle
+ if (index < this.segments.length - 1){
+ this.segments[index+1].startAngle = segment.endAngle;
+ }
+ segment.draw();
+ }, this);
+ this.scale.draw();
+ }
+ });
+
+}).call(this);
+(function(){
+ "use strict";
+
+ var root = this,
+ Chart = root.Chart,
+ helpers = Chart.helpers;
+
+
+
+ Chart.Type.extend({
+ name: "Radar",
+ defaults:{
+ //Boolean - Whether to show lines for each scale point
+ scaleShowLine : true,
+
+ //Boolean - Whether we show the angle lines out of the radar
+ angleShowLineOut : true,
+
+ //Boolean - Whether to show labels on the scale
+ scaleShowLabels : false,
+
+ // Boolean - Whether the scale should begin at zero
+ scaleBeginAtZero : true,
+
+ //String - Colour of the angle line
+ angleLineColor : "rgba(0,0,0,.1)",
+
+ //Number - Pixel width of the angle line
+ angleLineWidth : 1,
+
+ //String - Point label font declaration
+ pointLabelFontFamily : "'Arial'",
+
+ //String - Point label font weight
+ pointLabelFontStyle : "normal",
+
+ //Number - Point label font size in pixels
+ pointLabelFontSize : 10,
+
+ //String - Point label font colour
+ pointLabelFontColor : "#666",
+
+ //Boolean - Whether to show a dot for each point
+ pointDot : true,
+
+ //Number - Radius of each point dot in pixels
+ pointDotRadius : 3,
+
+ //Number - Pixel width of point dot stroke
+ pointDotStrokeWidth : 1,
+
+ //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
+ pointHitDetectionRadius : 20,
+
+ //Boolean - Whether to show a stroke for datasets
+ datasetStroke : true,
+
+ //Number - Pixel width of dataset stroke
+ datasetStrokeWidth : 2,
+
+ //Boolean - Whether to fill the dataset with a colour
+ datasetFill : true,
+
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
+
+ },
+
+ initialize: function(data){
+ this.PointClass = Chart.Point.extend({
+ strokeWidth : this.options.pointDotStrokeWidth,
+ radius : this.options.pointDotRadius,
+ display: this.options.pointDot,
+ hitDetectionRadius : this.options.pointHitDetectionRadius,
+ ctx : this.chart.ctx
+ });
+
+ this.datasets = [];
+
+ this.buildScale(data);
+
+ //Set up tooltip events on the chart
+ if (this.options.showTooltips){
+ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
+ var activePointsCollection = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
+
+ this.eachPoints(function(point){
+ point.restore(['fillColor', 'strokeColor']);
+ });
+ helpers.each(activePointsCollection, function(activePoint){
+ activePoint.fillColor = activePoint.highlightFill;
+ activePoint.strokeColor = activePoint.highlightStroke;
+ });
+
+ this.showTooltip(activePointsCollection);
+ });
+ }
+
+ //Iterate through each of the datasets, and build this into a property of the chart
+ helpers.each(data.datasets,function(dataset){
+
+ var datasetObject = {
+ label: dataset.label || null,
+ fillColor : dataset.fillColor,
+ strokeColor : dataset.strokeColor,
+ pointColor : dataset.pointColor,
+ pointStrokeColor : dataset.pointStrokeColor,
+ points : []
+ };
+
+ this.datasets.push(datasetObject);
+
+ helpers.each(dataset.data,function(dataPoint,index){
+ //Add a new point for each piece of data, passing any required data to draw.
+ var pointPosition;
+ if (!this.scale.animation){
+ pointPosition = this.scale.getPointPosition(index, this.scale.calculateCenterOffset(dataPoint));
+ }
+ datasetObject.points.push(new this.PointClass({
+ value : dataPoint,
+ label : data.labels[index],
+ datasetLabel: dataset.label,
+ x: (this.options.animation) ? this.scale.xCenter : pointPosition.x,
+ y: (this.options.animation) ? this.scale.yCenter : pointPosition.y,
+ strokeColor : dataset.pointStrokeColor,
+ fillColor : dataset.pointColor,
+ highlightFill : dataset.pointHighlightFill || dataset.pointColor,
+ highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor
+ }));
+ },this);
+
+ },this);
+
+ this.render();
+ },
+ eachPoints : function(callback){
+ helpers.each(this.datasets,function(dataset){
+ helpers.each(dataset.points,callback,this);
+ },this);
+ },
+
+ getPointsAtEvent : function(evt){
+ var mousePosition = helpers.getRelativePosition(evt),
+ fromCenter = helpers.getAngleFromPoint({
+ x: this.scale.xCenter,
+ y: this.scale.yCenter
+ }, mousePosition);
+
+ var anglePerIndex = (Math.PI * 2) /this.scale.valuesCount,
+ pointIndex = Math.round((fromCenter.angle - Math.PI * 1.5) / anglePerIndex),
+ activePointsCollection = [];
+
+ // If we're at the top, make the pointIndex 0 to get the first of the array.
+ if (pointIndex >= this.scale.valuesCount || pointIndex < 0){
+ pointIndex = 0;
+ }
+
+ if (fromCenter.distance <= this.scale.drawingArea){
+ helpers.each(this.datasets, function(dataset){
+ activePointsCollection.push(dataset.points[pointIndex]);
+ });
+ }
+
+ return activePointsCollection;
+ },
+
+ buildScale : function(data){
+ this.scale = new Chart.RadialScale({
+ display: this.options.showScale,
+ fontStyle: this.options.scaleFontStyle,
+ fontSize: this.options.scaleFontSize,
+ fontFamily: this.options.scaleFontFamily,
+ fontColor: this.options.scaleFontColor,
+ showLabels: this.options.scaleShowLabels,
+ showLabelBackdrop: this.options.scaleShowLabelBackdrop,
+ backdropColor: this.options.scaleBackdropColor,
+ backdropPaddingY : this.options.scaleBackdropPaddingY,
+ backdropPaddingX: this.options.scaleBackdropPaddingX,
+ lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0,
+ lineColor: this.options.scaleLineColor,
+ angleLineColor : this.options.angleLineColor,
+ angleLineWidth : (this.options.angleShowLineOut) ? this.options.angleLineWidth : 0,
+ // Point labels at the edge of each line
+ pointLabelFontColor : this.options.pointLabelFontColor,
+ pointLabelFontSize : this.options.pointLabelFontSize,
+ pointLabelFontFamily : this.options.pointLabelFontFamily,
+ pointLabelFontStyle : this.options.pointLabelFontStyle,
+ height : this.chart.height,
+ width: this.chart.width,
+ xCenter: this.chart.width/2,
+ yCenter: this.chart.height/2,
+ ctx : this.chart.ctx,
+ templateString: this.options.scaleLabel,
+ labels: data.labels,
+ valuesCount: data.datasets[0].data.length
+ });
+
+ this.scale.setScaleSize();
+ this.updateScaleRange(data.datasets);
+ this.scale.buildYLabels();
+ },
+ updateScaleRange: function(datasets){
+ var valuesArray = (function(){
+ var totalDataArray = [];
+ helpers.each(datasets,function(dataset){
+ if (dataset.data){
+ totalDataArray = totalDataArray.concat(dataset.data);
+ }
+ else {
+ helpers.each(dataset.points, function(point){
+ totalDataArray.push(point.value);
+ });
+ }
+ });
+ return totalDataArray;
+ })();
+
+
+ var scaleSizes = (this.options.scaleOverride) ?
+ {
+ steps: this.options.scaleSteps,
+ stepValue: this.options.scaleStepWidth,
+ min: this.options.scaleStartValue,
+ max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
+ } :
+ helpers.calculateScaleRange(
+ valuesArray,
+ helpers.min([this.chart.width, this.chart.height])/2,
+ this.options.scaleFontSize,
+ this.options.scaleBeginAtZero,
+ this.options.scaleIntegersOnly
+ );
+
+ helpers.extend(
+ this.scale,
+ scaleSizes
+ );
+
+ },
+ addData : function(valuesArray,label){
+ //Map the values array for each of the datasets
+ this.scale.valuesCount++;
+ helpers.each(valuesArray,function(value,datasetIndex){
+ var pointPosition = this.scale.getPointPosition(this.scale.valuesCount, this.scale.calculateCenterOffset(value));
+ this.datasets[datasetIndex].points.push(new this.PointClass({
+ value : value,
+ label : label,
+ x: pointPosition.x,
+ y: pointPosition.y,
+ strokeColor : this.datasets[datasetIndex].pointStrokeColor,
+ fillColor : this.datasets[datasetIndex].pointColor
+ }));
+ },this);
+
+ this.scale.labels.push(label);
+
+ this.reflow();
+
+ this.update();
+ },
+ removeData : function(){
+ this.scale.valuesCount--;
+ this.scale.labels.shift();
+ helpers.each(this.datasets,function(dataset){
+ dataset.points.shift();
+ },this);
+ this.reflow();
+ this.update();
+ },
+ update : function(){
+ this.eachPoints(function(point){
+ point.save();
+ });
+ this.reflow();
+ this.render();
+ },
+ reflow: function(){
+ helpers.extend(this.scale, {
+ width : this.chart.width,
+ height: this.chart.height,
+ size : helpers.min([this.chart.width, this.chart.height]),
+ xCenter: this.chart.width/2,
+ yCenter: this.chart.height/2
+ });
+ this.updateScaleRange(this.datasets);
+ this.scale.setScaleSize();
+ this.scale.buildYLabels();
+ },
+ draw : function(ease){
+ var easeDecimal = ease || 1,
+ ctx = this.chart.ctx;
+ this.clear();
+ this.scale.draw();
+
+ helpers.each(this.datasets,function(dataset){
+
+ //Transition each point first so that the line and point drawing isn't out of sync
+ helpers.each(dataset.points,function(point,index){
+ if (point.hasValue()){
+ point.transition(this.scale.getPointPosition(index, this.scale.calculateCenterOffset(point.value)), easeDecimal);
+ }
+ },this);
+
+
+
+ //Draw the line between all the points
+ ctx.lineWidth = this.options.datasetStrokeWidth;
+ ctx.strokeStyle = dataset.strokeColor;
+ ctx.beginPath();
+ helpers.each(dataset.points,function(point,index){
+ if (index === 0){
+ ctx.moveTo(point.x,point.y);
+ }
+ else{
+ ctx.lineTo(point.x,point.y);
+ }
+ },this);
+ ctx.closePath();
+ ctx.stroke();
+
+ ctx.fillStyle = dataset.fillColor;
+ ctx.fill();
+
+ //Now draw the points over the line
+ //A little inefficient double looping, but better than the line
+ //lagging behind the point positions
+ helpers.each(dataset.points,function(point){
+ if (point.hasValue()){
+ point.draw();
+ }
+ });
+
+ },this);
+
+ }
+
+ });
+
+
+
+
+
+}).call(this);
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/Chart.min.js b/xos-apps/auto-scale/gui/src/vendor/Chart.js/Chart.min.js
new file mode 100644
index 0000000..3a0a2c8
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/Chart.min.js
@@ -0,0 +1,11 @@
+/*!
+ * Chart.js
+ * http://chartjs.org/
+ * Version: 1.0.2
+ *
+ * Copyright 2015 Nick Downie
+ * Released under the MIT license
+ * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
+ */
+(function(){"use strict";var t=this,i=t.Chart,e=function(t){this.canvas=t.canvas,this.ctx=t;var i=function(t,i){return t["offset"+i]?t["offset"+i]:document.defaultView.getComputedStyle(t).getPropertyValue(i)},e=this.width=i(t.canvas,"Width"),n=this.height=i(t.canvas,"Height");t.canvas.width=e,t.canvas.height=n;var e=this.width=t.canvas.width,n=this.height=t.canvas.height;return this.aspectRatio=this.width/this.height,s.retinaScale(this),this};e.defaults={global:{animation:!0,animationSteps:60,animationEasing:"easeOutQuart",showScale:!0,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleIntegersOnly:!0,scaleBeginAtZero:!1,scaleFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",responsive:!1,maintainAspectRatio:!0,showTooltips:!0,customTooltips:!1,tooltipEvents:["mousemove","touchstart","touchmove","mouseout"],tooltipFillColor:"rgba(0,0,0,0.8)",tooltipFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",tooltipFontSize:14,tooltipFontStyle:"normal",tooltipFontColor:"#fff",tooltipTitleFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",tooltipTitleFontSize:14,tooltipTitleFontStyle:"bold",tooltipTitleFontColor:"#fff",tooltipYPadding:6,tooltipXPadding:6,tooltipCaretSize:8,tooltipCornerRadius:6,tooltipXOffset:10,tooltipTemplate:"<%if (label){%><%=label%>: <%}%><%= value %>",multiTooltipTemplate:"<%= value %>",multiTooltipKeyBackground:"#fff",onAnimationProgress:function(){},onAnimationComplete:function(){}}},e.types={};var s=e.helpers={},n=s.each=function(t,i,e){var s=Array.prototype.slice.call(arguments,3);if(t)if(t.length===+t.length){var n;for(n=0;n<t.length;n++)i.apply(e,[t[n],n].concat(s))}else for(var o in t)i.apply(e,[t[o],o].concat(s))},o=s.clone=function(t){var i={};return n(t,function(e,s){t.hasOwnProperty(s)&&(i[s]=e)}),i},a=s.extend=function(t){return n(Array.prototype.slice.call(arguments,1),function(i){n(i,function(e,s){i.hasOwnProperty(s)&&(t[s]=e)})}),t},h=s.merge=function(){var t=Array.prototype.slice.call(arguments,0);return t.unshift({}),a.apply(null,t)},l=s.indexOf=function(t,i){if(Array.prototype.indexOf)return t.indexOf(i);for(var e=0;e<t.length;e++)if(t[e]===i)return e;return-1},r=(s.where=function(t,i){var e=[];return s.each(t,function(t){i(t)&&e.push(t)}),e},s.findNextWhere=function(t,i,e){e||(e=-1);for(var s=e+1;s<t.length;s++){var n=t[s];if(i(n))return n}},s.findPreviousWhere=function(t,i,e){e||(e=t.length);for(var s=e-1;s>=0;s--){var n=t[s];if(i(n))return n}},s.inherits=function(t){var i=this,e=t&&t.hasOwnProperty("constructor")?t.constructor:function(){return i.apply(this,arguments)},s=function(){this.constructor=e};return s.prototype=i.prototype,e.prototype=new s,e.extend=r,t&&a(e.prototype,t),e.__super__=i.prototype,e}),c=s.noop=function(){},u=s.uid=function(){var t=0;return function(){return"chart-"+t++}}(),d=s.warn=function(t){window.console&&"function"==typeof window.console.warn&&console.warn(t)},p=s.amd="function"==typeof define&&define.amd,f=s.isNumber=function(t){return!isNaN(parseFloat(t))&&isFinite(t)},g=s.max=function(t){return Math.max.apply(Math,t)},m=s.min=function(t){return Math.min.apply(Math,t)},v=(s.cap=function(t,i,e){if(f(i)){if(t>i)return i}else if(f(e)&&e>t)return e;return t},s.getDecimalPlaces=function(t){return t%1!==0&&f(t)?t.toString().split(".")[1].length:0}),S=s.radians=function(t){return t*(Math.PI/180)},x=(s.getAngleFromPoint=function(t,i){var e=i.x-t.x,s=i.y-t.y,n=Math.sqrt(e*e+s*s),o=2*Math.PI+Math.atan2(s,e);return 0>e&&0>s&&(o+=2*Math.PI),{angle:o,distance:n}},s.aliasPixel=function(t){return t%2===0?0:.5}),y=(s.splineCurve=function(t,i,e,s){var n=Math.sqrt(Math.pow(i.x-t.x,2)+Math.pow(i.y-t.y,2)),o=Math.sqrt(Math.pow(e.x-i.x,2)+Math.pow(e.y-i.y,2)),a=s*n/(n+o),h=s*o/(n+o);return{inner:{x:i.x-a*(e.x-t.x),y:i.y-a*(e.y-t.y)},outer:{x:i.x+h*(e.x-t.x),y:i.y+h*(e.y-t.y)}}},s.calculateOrderOfMagnitude=function(t){return Math.floor(Math.log(t)/Math.LN10)}),C=(s.calculateScaleRange=function(t,i,e,s,n){var o=2,a=Math.floor(i/(1.5*e)),h=o>=a,l=g(t),r=m(t);l===r&&(l+=.5,r>=.5&&!s?r-=.5:l+=.5);for(var c=Math.abs(l-r),u=y(c),d=Math.ceil(l/(1*Math.pow(10,u)))*Math.pow(10,u),p=s?0:Math.floor(r/(1*Math.pow(10,u)))*Math.pow(10,u),f=d-p,v=Math.pow(10,u),S=Math.round(f/v);(S>a||a>2*S)&&!h;)if(S>a)v*=2,S=Math.round(f/v),S%1!==0&&(h=!0);else if(n&&u>=0){if(v/2%1!==0)break;v/=2,S=Math.round(f/v)}else v/=2,S=Math.round(f/v);return h&&(S=o,v=f/S),{steps:S,stepValue:v,min:p,max:p+S*v}},s.template=function(t,i){function e(t,i){var e=/\W/.test(t)?new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('"+t.replace(/[\r\t\n]/g," ").split("<%").join(" ").replace(/((^|%>)[^\t]*)'/g,"$1\r").replace(/\t=(.*?)%>/g,"',$1,'").split(" ").join("');").split("%>").join("p.push('").split("\r").join("\\'")+"');}return p.join('');"):s[t]=s[t];return i?e(i):e}if(t instanceof Function)return t(i);var s={};return e(t,i)}),w=(s.generateLabels=function(t,i,e,s){var o=new Array(i);return labelTemplateString&&n(o,function(i,n){o[n]=C(t,{value:e+s*(n+1)})}),o},s.easingEffects={linear:function(t){return t},easeInQuad:function(t){return t*t},easeOutQuad:function(t){return-1*t*(t-2)},easeInOutQuad:function(t){return(t/=.5)<1?.5*t*t:-0.5*(--t*(t-2)-1)},easeInCubic:function(t){return t*t*t},easeOutCubic:function(t){return 1*((t=t/1-1)*t*t+1)},easeInOutCubic:function(t){return(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2)},easeInQuart:function(t){return t*t*t*t},easeOutQuart:function(t){return-1*((t=t/1-1)*t*t*t-1)},easeInOutQuart:function(t){return(t/=.5)<1?.5*t*t*t*t:-0.5*((t-=2)*t*t*t-2)},easeInQuint:function(t){return 1*(t/=1)*t*t*t*t},easeOutQuint:function(t){return 1*((t=t/1-1)*t*t*t*t+1)},easeInOutQuint:function(t){return(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)},easeInSine:function(t){return-1*Math.cos(t/1*(Math.PI/2))+1},easeOutSine:function(t){return 1*Math.sin(t/1*(Math.PI/2))},easeInOutSine:function(t){return-0.5*(Math.cos(Math.PI*t/1)-1)},easeInExpo:function(t){return 0===t?1:1*Math.pow(2,10*(t/1-1))},easeOutExpo:function(t){return 1===t?1:1*(-Math.pow(2,-10*t/1)+1)},easeInOutExpo:function(t){return 0===t?0:1===t?1:(t/=.5)<1?.5*Math.pow(2,10*(t-1)):.5*(-Math.pow(2,-10*--t)+2)},easeInCirc:function(t){return t>=1?t:-1*(Math.sqrt(1-(t/=1)*t)-1)},easeOutCirc:function(t){return 1*Math.sqrt(1-(t=t/1-1)*t)},easeInOutCirc:function(t){return(t/=.5)<1?-0.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)},easeInElastic:function(t){var i=1.70158,e=0,s=1;return 0===t?0:1==(t/=1)?1:(e||(e=.3),s<Math.abs(1)?(s=1,i=e/4):i=e/(2*Math.PI)*Math.asin(1/s),-(s*Math.pow(2,10*(t-=1))*Math.sin(2*(1*t-i)*Math.PI/e)))},easeOutElastic:function(t){var i=1.70158,e=0,s=1;return 0===t?0:1==(t/=1)?1:(e||(e=.3),s<Math.abs(1)?(s=1,i=e/4):i=e/(2*Math.PI)*Math.asin(1/s),s*Math.pow(2,-10*t)*Math.sin(2*(1*t-i)*Math.PI/e)+1)},easeInOutElastic:function(t){var i=1.70158,e=0,s=1;return 0===t?0:2==(t/=.5)?1:(e||(e=.3*1.5),s<Math.abs(1)?(s=1,i=e/4):i=e/(2*Math.PI)*Math.asin(1/s),1>t?-.5*s*Math.pow(2,10*(t-=1))*Math.sin(2*(1*t-i)*Math.PI/e):s*Math.pow(2,-10*(t-=1))*Math.sin(2*(1*t-i)*Math.PI/e)*.5+1)},easeInBack:function(t){var i=1.70158;return 1*(t/=1)*t*((i+1)*t-i)},easeOutBack:function(t){var i=1.70158;return 1*((t=t/1-1)*t*((i+1)*t+i)+1)},easeInOutBack:function(t){var i=1.70158;return(t/=.5)<1?.5*t*t*(((i*=1.525)+1)*t-i):.5*((t-=2)*t*(((i*=1.525)+1)*t+i)+2)},easeInBounce:function(t){return 1-w.easeOutBounce(1-t)},easeOutBounce:function(t){return(t/=1)<1/2.75?7.5625*t*t:2/2.75>t?1*(7.5625*(t-=1.5/2.75)*t+.75):2.5/2.75>t?1*(7.5625*(t-=2.25/2.75)*t+.9375):1*(7.5625*(t-=2.625/2.75)*t+.984375)},easeInOutBounce:function(t){return.5>t?.5*w.easeInBounce(2*t):.5*w.easeOutBounce(2*t-1)+.5}}),b=s.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(t){return window.setTimeout(t,1e3/60)}}(),P=s.cancelAnimFrame=function(){return window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame||function(t){return window.clearTimeout(t,1e3/60)}}(),L=(s.animationLoop=function(t,i,e,s,n,o){var a=0,h=w[e]||w.linear,l=function(){a++;var e=a/i,r=h(e);t.call(o,r,e,a),s.call(o,r,e),i>a?o.animationFrame=b(l):n.apply(o)};b(l)},s.getRelativePosition=function(t){var i,e,s=t.originalEvent||t,n=t.currentTarget||t.srcElement,o=n.getBoundingClientRect();return s.touches?(i=s.touches[0].clientX-o.left,e=s.touches[0].clientY-o.top):(i=s.clientX-o.left,e=s.clientY-o.top),{x:i,y:e}},s.addEvent=function(t,i,e){t.addEventListener?t.addEventListener(i,e):t.attachEvent?t.attachEvent("on"+i,e):t["on"+i]=e}),k=s.removeEvent=function(t,i,e){t.removeEventListener?t.removeEventListener(i,e,!1):t.detachEvent?t.detachEvent("on"+i,e):t["on"+i]=c},F=(s.bindEvents=function(t,i,e){t.events||(t.events={}),n(i,function(i){t.events[i]=function(){e.apply(t,arguments)},L(t.chart.canvas,i,t.events[i])})},s.unbindEvents=function(t,i){n(i,function(i,e){k(t.chart.canvas,e,i)})}),R=s.getMaximumWidth=function(t){var i=t.parentNode;return i.clientWidth},T=s.getMaximumHeight=function(t){var i=t.parentNode;return i.clientHeight},A=(s.getMaximumSize=s.getMaximumWidth,s.retinaScale=function(t){var i=t.ctx,e=t.canvas.width,s=t.canvas.height;window.devicePixelRatio&&(i.canvas.style.width=e+"px",i.canvas.style.height=s+"px",i.canvas.height=s*window.devicePixelRatio,i.canvas.width=e*window.devicePixelRatio,i.scale(window.devicePixelRatio,window.devicePixelRatio))}),M=s.clear=function(t){t.ctx.clearRect(0,0,t.width,t.height)},W=s.fontString=function(t,i,e){return i+" "+t+"px "+e},z=s.longestText=function(t,i,e){t.font=i;var s=0;return n(e,function(i){var e=t.measureText(i).width;s=e>s?e:s}),s},B=s.drawRoundedRectangle=function(t,i,e,s,n,o){t.beginPath(),t.moveTo(i+o,e),t.lineTo(i+s-o,e),t.quadraticCurveTo(i+s,e,i+s,e+o),t.lineTo(i+s,e+n-o),t.quadraticCurveTo(i+s,e+n,i+s-o,e+n),t.lineTo(i+o,e+n),t.quadraticCurveTo(i,e+n,i,e+n-o),t.lineTo(i,e+o),t.quadraticCurveTo(i,e,i+o,e),t.closePath()};e.instances={},e.Type=function(t,i,s){this.options=i,this.chart=s,this.id=u(),e.instances[this.id]=this,i.responsive&&this.resize(),this.initialize.call(this,t)},a(e.Type.prototype,{initialize:function(){return this},clear:function(){return M(this.chart),this},stop:function(){return P(this.animationFrame),this},resize:function(t){this.stop();var i=this.chart.canvas,e=R(this.chart.canvas),s=this.options.maintainAspectRatio?e/this.chart.aspectRatio:T(this.chart.canvas);return i.width=this.chart.width=e,i.height=this.chart.height=s,A(this.chart),"function"==typeof t&&t.apply(this,Array.prototype.slice.call(arguments,1)),this},reflow:c,render:function(t){return t&&this.reflow(),this.options.animation&&!t?s.animationLoop(this.draw,this.options.animationSteps,this.options.animationEasing,this.options.onAnimationProgress,this.options.onAnimationComplete,this):(this.draw(),this.options.onAnimationComplete.call(this)),this},generateLegend:function(){return C(this.options.legendTemplate,this)},destroy:function(){this.clear(),F(this,this.events);var t=this.chart.canvas;t.width=this.chart.width,t.height=this.chart.height,t.style.removeProperty?(t.style.removeProperty("width"),t.style.removeProperty("height")):(t.style.removeAttribute("width"),t.style.removeAttribute("height")),delete e.instances[this.id]},showTooltip:function(t,i){"undefined"==typeof this.activeElements&&(this.activeElements=[]);var o=function(t){var i=!1;return t.length!==this.activeElements.length?i=!0:(n(t,function(t,e){t!==this.activeElements[e]&&(i=!0)},this),i)}.call(this,t);if(o||i){if(this.activeElements=t,this.draw(),this.options.customTooltips&&this.options.customTooltips(!1),t.length>0)if(this.datasets&&this.datasets.length>1){for(var a,h,r=this.datasets.length-1;r>=0&&(a=this.datasets[r].points||this.datasets[r].bars||this.datasets[r].segments,h=l(a,t[0]),-1===h);r--);var c=[],u=[],d=function(){var t,i,e,n,o,a=[],l=[],r=[];return s.each(this.datasets,function(i){t=i.points||i.bars||i.segments,t[h]&&t[h].hasValue()&&a.push(t[h])}),s.each(a,function(t){l.push(t.x),r.push(t.y),c.push(s.template(this.options.multiTooltipTemplate,t)),u.push({fill:t._saved.fillColor||t.fillColor,stroke:t._saved.strokeColor||t.strokeColor})},this),o=m(r),e=g(r),n=m(l),i=g(l),{x:n>this.chart.width/2?n:i,y:(o+e)/2}}.call(this,h);new e.MultiTooltip({x:d.x,y:d.y,xPadding:this.options.tooltipXPadding,yPadding:this.options.tooltipYPadding,xOffset:this.options.tooltipXOffset,fillColor:this.options.tooltipFillColor,textColor:this.options.tooltipFontColor,fontFamily:this.options.tooltipFontFamily,fontStyle:this.options.tooltipFontStyle,fontSize:this.options.tooltipFontSize,titleTextColor:this.options.tooltipTitleFontColor,titleFontFamily:this.options.tooltipTitleFontFamily,titleFontStyle:this.options.tooltipTitleFontStyle,titleFontSize:this.options.tooltipTitleFontSize,cornerRadius:this.options.tooltipCornerRadius,labels:c,legendColors:u,legendColorBackground:this.options.multiTooltipKeyBackground,title:t[0].label,chart:this.chart,ctx:this.chart.ctx,custom:this.options.customTooltips}).draw()}else n(t,function(t){var i=t.tooltipPosition();new e.Tooltip({x:Math.round(i.x),y:Math.round(i.y),xPadding:this.options.tooltipXPadding,yPadding:this.options.tooltipYPadding,fillColor:this.options.tooltipFillColor,textColor:this.options.tooltipFontColor,fontFamily:this.options.tooltipFontFamily,fontStyle:this.options.tooltipFontStyle,fontSize:this.options.tooltipFontSize,caretHeight:this.options.tooltipCaretSize,cornerRadius:this.options.tooltipCornerRadius,text:C(this.options.tooltipTemplate,t),chart:this.chart,custom:this.options.customTooltips}).draw()},this);return this}},toBase64Image:function(){return this.chart.canvas.toDataURL.apply(this.chart.canvas,arguments)}}),e.Type.extend=function(t){var i=this,s=function(){return i.apply(this,arguments)};if(s.prototype=o(i.prototype),a(s.prototype,t),s.extend=e.Type.extend,t.name||i.prototype.name){var n=t.name||i.prototype.name,l=e.defaults[i.prototype.name]?o(e.defaults[i.prototype.name]):{};e.defaults[n]=a(l,t.defaults),e.types[n]=s,e.prototype[n]=function(t,i){var o=h(e.defaults.global,e.defaults[n],i||{});return new s(t,o,this)}}else d("Name not provided for this chart, so it hasn't been registered");return i},e.Element=function(t){a(this,t),this.initialize.apply(this,arguments),this.save()},a(e.Element.prototype,{initialize:function(){},restore:function(t){return t?n(t,function(t){this[t]=this._saved[t]},this):a(this,this._saved),this},save:function(){return this._saved=o(this),delete this._saved._saved,this},update:function(t){return n(t,function(t,i){this._saved[i]=this[i],this[i]=t},this),this},transition:function(t,i){return n(t,function(t,e){this[e]=(t-this._saved[e])*i+this._saved[e]},this),this},tooltipPosition:function(){return{x:this.x,y:this.y}},hasValue:function(){return f(this.value)}}),e.Element.extend=r,e.Point=e.Element.extend({display:!0,inRange:function(t,i){var e=this.hitDetectionRadius+this.radius;return Math.pow(t-this.x,2)+Math.pow(i-this.y,2)<Math.pow(e,2)},draw:function(){if(this.display){var t=this.ctx;t.beginPath(),t.arc(this.x,this.y,this.radius,0,2*Math.PI),t.closePath(),t.strokeStyle=this.strokeColor,t.lineWidth=this.strokeWidth,t.fillStyle=this.fillColor,t.fill(),t.stroke()}}}),e.Arc=e.Element.extend({inRange:function(t,i){var e=s.getAngleFromPoint(this,{x:t,y:i}),n=e.angle>=this.startAngle&&e.angle<=this.endAngle,o=e.distance>=this.innerRadius&&e.distance<=this.outerRadius;return n&&o},tooltipPosition:function(){var t=this.startAngle+(this.endAngle-this.startAngle)/2,i=(this.outerRadius-this.innerRadius)/2+this.innerRadius;return{x:this.x+Math.cos(t)*i,y:this.y+Math.sin(t)*i}},draw:function(t){var i=this.ctx;i.beginPath(),i.arc(this.x,this.y,this.outerRadius,this.startAngle,this.endAngle),i.arc(this.x,this.y,this.innerRadius,this.endAngle,this.startAngle,!0),i.closePath(),i.strokeStyle=this.strokeColor,i.lineWidth=this.strokeWidth,i.fillStyle=this.fillColor,i.fill(),i.lineJoin="bevel",this.showStroke&&i.stroke()}}),e.Rectangle=e.Element.extend({draw:function(){var t=this.ctx,i=this.width/2,e=this.x-i,s=this.x+i,n=this.base-(this.base-this.y),o=this.strokeWidth/2;this.showStroke&&(e+=o,s-=o,n+=o),t.beginPath(),t.fillStyle=this.fillColor,t.strokeStyle=this.strokeColor,t.lineWidth=this.strokeWidth,t.moveTo(e,this.base),t.lineTo(e,n),t.lineTo(s,n),t.lineTo(s,this.base),t.fill(),this.showStroke&&t.stroke()},height:function(){return this.base-this.y},inRange:function(t,i){return t>=this.x-this.width/2&&t<=this.x+this.width/2&&i>=this.y&&i<=this.base}}),e.Tooltip=e.Element.extend({draw:function(){var t=this.chart.ctx;t.font=W(this.fontSize,this.fontStyle,this.fontFamily),this.xAlign="center",this.yAlign="above";var i=this.caretPadding=2,e=t.measureText(this.text).width+2*this.xPadding,s=this.fontSize+2*this.yPadding,n=s+this.caretHeight+i;this.x+e/2>this.chart.width?this.xAlign="left":this.x-e/2<0&&(this.xAlign="right"),this.y-n<0&&(this.yAlign="below");var o=this.x-e/2,a=this.y-n;if(t.fillStyle=this.fillColor,this.custom)this.custom(this);else{switch(this.yAlign){case"above":t.beginPath(),t.moveTo(this.x,this.y-i),t.lineTo(this.x+this.caretHeight,this.y-(i+this.caretHeight)),t.lineTo(this.x-this.caretHeight,this.y-(i+this.caretHeight)),t.closePath(),t.fill();break;case"below":a=this.y+i+this.caretHeight,t.beginPath(),t.moveTo(this.x,this.y+i),t.lineTo(this.x+this.caretHeight,this.y+i+this.caretHeight),t.lineTo(this.x-this.caretHeight,this.y+i+this.caretHeight),t.closePath(),t.fill()}switch(this.xAlign){case"left":o=this.x-e+(this.cornerRadius+this.caretHeight);break;case"right":o=this.x-(this.cornerRadius+this.caretHeight)}B(t,o,a,e,s,this.cornerRadius),t.fill(),t.fillStyle=this.textColor,t.textAlign="center",t.textBaseline="middle",t.fillText(this.text,o+e/2,a+s/2)}}}),e.MultiTooltip=e.Element.extend({initialize:function(){this.font=W(this.fontSize,this.fontStyle,this.fontFamily),this.titleFont=W(this.titleFontSize,this.titleFontStyle,this.titleFontFamily),this.height=this.labels.length*this.fontSize+(this.labels.length-1)*(this.fontSize/2)+2*this.yPadding+1.5*this.titleFontSize,this.ctx.font=this.titleFont;var t=this.ctx.measureText(this.title).width,i=z(this.ctx,this.font,this.labels)+this.fontSize+3,e=g([i,t]);this.width=e+2*this.xPadding;var s=this.height/2;this.y-s<0?this.y=s:this.y+s>this.chart.height&&(this.y=this.chart.height-s),this.x>this.chart.width/2?this.x-=this.xOffset+this.width:this.x+=this.xOffset},getLineHeight:function(t){var i=this.y-this.height/2+this.yPadding,e=t-1;return 0===t?i+this.titleFontSize/2:i+(1.5*this.fontSize*e+this.fontSize/2)+1.5*this.titleFontSize},draw:function(){if(this.custom)this.custom(this);else{B(this.ctx,this.x,this.y-this.height/2,this.width,this.height,this.cornerRadius);var t=this.ctx;t.fillStyle=this.fillColor,t.fill(),t.closePath(),t.textAlign="left",t.textBaseline="middle",t.fillStyle=this.titleTextColor,t.font=this.titleFont,t.fillText(this.title,this.x+this.xPadding,this.getLineHeight(0)),t.font=this.font,s.each(this.labels,function(i,e){t.fillStyle=this.textColor,t.fillText(i,this.x+this.xPadding+this.fontSize+3,this.getLineHeight(e+1)),t.fillStyle=this.legendColorBackground,t.fillRect(this.x+this.xPadding,this.getLineHeight(e+1)-this.fontSize/2,this.fontSize,this.fontSize),t.fillStyle=this.legendColors[e].fill,t.fillRect(this.x+this.xPadding,this.getLineHeight(e+1)-this.fontSize/2,this.fontSize,this.fontSize)},this)}}}),e.Scale=e.Element.extend({initialize:function(){this.fit()},buildYLabels:function(){this.yLabels=[];for(var t=v(this.stepValue),i=0;i<=this.steps;i++)this.yLabels.push(C(this.templateString,{value:(this.min+i*this.stepValue).toFixed(t)}));this.yLabelWidth=this.display&&this.showLabels?z(this.ctx,this.font,this.yLabels):0},addXLabel:function(t){this.xLabels.push(t),this.valuesCount++,this.fit()},removeXLabel:function(){this.xLabels.shift(),this.valuesCount--,this.fit()},fit:function(){this.startPoint=this.display?this.fontSize:0,this.endPoint=this.display?this.height-1.5*this.fontSize-5:this.height,this.startPoint+=this.padding,this.endPoint-=this.padding;var t,i=this.endPoint-this.startPoint;for(this.calculateYRange(i),this.buildYLabels(),this.calculateXLabelRotation();i>this.endPoint-this.startPoint;)i=this.endPoint-this.startPoint,t=this.yLabelWidth,this.calculateYRange(i),this.buildYLabels(),t<this.yLabelWidth&&this.calculateXLabelRotation()},calculateXLabelRotation:function(){this.ctx.font=this.font;var t,i,e=this.ctx.measureText(this.xLabels[0]).width,s=this.ctx.measureText(this.xLabels[this.xLabels.length-1]).width;if(this.xScalePaddingRight=s/2+3,this.xScalePaddingLeft=e/2>this.yLabelWidth+10?e/2:this.yLabelWidth+10,this.xLabelRotation=0,this.display){var n,o=z(this.ctx,this.font,this.xLabels);this.xLabelWidth=o;for(var a=Math.floor(this.calculateX(1)-this.calculateX(0))-6;this.xLabelWidth>a&&0===this.xLabelRotation||this.xLabelWidth>a&&this.xLabelRotation<=90&&this.xLabelRotation>0;)n=Math.cos(S(this.xLabelRotation)),t=n*e,i=n*s,t+this.fontSize/2>this.yLabelWidth+8&&(this.xScalePaddingLeft=t+this.fontSize/2),this.xScalePaddingRight=this.fontSize/2,this.xLabelRotation++,this.xLabelWidth=n*o;this.xLabelRotation>0&&(this.endPoint-=Math.sin(S(this.xLabelRotation))*o+3)}else this.xLabelWidth=0,this.xScalePaddingRight=this.padding,this.xScalePaddingLeft=this.padding},calculateYRange:c,drawingArea:function(){return this.startPoint-this.endPoint},calculateY:function(t){var i=this.drawingArea()/(this.min-this.max);return this.endPoint-i*(t-this.min)},calculateX:function(t){var i=(this.xLabelRotation>0,this.width-(this.xScalePaddingLeft+this.xScalePaddingRight)),e=i/Math.max(this.valuesCount-(this.offsetGridLines?0:1),1),s=e*t+this.xScalePaddingLeft;return this.offsetGridLines&&(s+=e/2),Math.round(s)},update:function(t){s.extend(this,t),this.fit()},draw:function(){var t=this.ctx,i=(this.endPoint-this.startPoint)/this.steps,e=Math.round(this.xScalePaddingLeft);this.display&&(t.fillStyle=this.textColor,t.font=this.font,n(this.yLabels,function(n,o){var a=this.endPoint-i*o,h=Math.round(a),l=this.showHorizontalLines;t.textAlign="right",t.textBaseline="middle",this.showLabels&&t.fillText(n,e-10,a),0!==o||l||(l=!0),l&&t.beginPath(),o>0?(t.lineWidth=this.gridLineWidth,t.strokeStyle=this.gridLineColor):(t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor),h+=s.aliasPixel(t.lineWidth),l&&(t.moveTo(e,h),t.lineTo(this.width,h),t.stroke(),t.closePath()),t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor,t.beginPath(),t.moveTo(e-5,h),t.lineTo(e,h),t.stroke(),t.closePath()},this),n(this.xLabels,function(i,e){var s=this.calculateX(e)+x(this.lineWidth),n=this.calculateX(e-(this.offsetGridLines?.5:0))+x(this.lineWidth),o=this.xLabelRotation>0,a=this.showVerticalLines;0!==e||a||(a=!0),a&&t.beginPath(),e>0?(t.lineWidth=this.gridLineWidth,t.strokeStyle=this.gridLineColor):(t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor),a&&(t.moveTo(n,this.endPoint),t.lineTo(n,this.startPoint-3),t.stroke(),t.closePath()),t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor,t.beginPath(),t.moveTo(n,this.endPoint),t.lineTo(n,this.endPoint+5),t.stroke(),t.closePath(),t.save(),t.translate(s,o?this.endPoint+12:this.endPoint+8),t.rotate(-1*S(this.xLabelRotation)),t.font=this.font,t.textAlign=o?"right":"center",t.textBaseline=o?"middle":"top",t.fillText(i,0,0),t.restore()},this))}}),e.RadialScale=e.Element.extend({initialize:function(){this.size=m([this.height,this.width]),this.drawingArea=this.display?this.size/2-(this.fontSize/2+this.backdropPaddingY):this.size/2},calculateCenterOffset:function(t){var i=this.drawingArea/(this.max-this.min);return(t-this.min)*i},update:function(){this.lineArc?this.drawingArea=this.display?this.size/2-(this.fontSize/2+this.backdropPaddingY):this.size/2:this.setScaleSize(),this.buildYLabels()},buildYLabels:function(){this.yLabels=[];for(var t=v(this.stepValue),i=0;i<=this.steps;i++)this.yLabels.push(C(this.templateString,{value:(this.min+i*this.stepValue).toFixed(t)}))},getCircumference:function(){return 2*Math.PI/this.valuesCount},setScaleSize:function(){var t,i,e,s,n,o,a,h,l,r,c,u,d=m([this.height/2-this.pointLabelFontSize-5,this.width/2]),p=this.width,g=0;for(this.ctx.font=W(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily),i=0;i<this.valuesCount;i++)t=this.getPointPosition(i,d),e=this.ctx.measureText(C(this.templateString,{value:this.labels[i]})).width+5,0===i||i===this.valuesCount/2?(s=e/2,t.x+s>p&&(p=t.x+s,n=i),t.x-s<g&&(g=t.x-s,a=i)):i<this.valuesCount/2?t.x+e>p&&(p=t.x+e,n=i):i>this.valuesCount/2&&t.x-e<g&&(g=t.x-e,a=i);l=g,r=Math.ceil(p-this.width),o=this.getIndexAngle(n),h=this.getIndexAngle(a),c=r/Math.sin(o+Math.PI/2),u=l/Math.sin(h+Math.PI/2),c=f(c)?c:0,u=f(u)?u:0,this.drawingArea=d-(u+c)/2,this.setCenterPoint(u,c)},setCenterPoint:function(t,i){var e=this.width-i-this.drawingArea,s=t+this.drawingArea;this.xCenter=(s+e)/2,this.yCenter=this.height/2},getIndexAngle:function(t){var i=2*Math.PI/this.valuesCount;return t*i-Math.PI/2},getPointPosition:function(t,i){var e=this.getIndexAngle(t);return{x:Math.cos(e)*i+this.xCenter,y:Math.sin(e)*i+this.yCenter}},draw:function(){if(this.display){var t=this.ctx;if(n(this.yLabels,function(i,e){if(e>0){var s,n=e*(this.drawingArea/this.steps),o=this.yCenter-n;if(this.lineWidth>0)if(t.strokeStyle=this.lineColor,t.lineWidth=this.lineWidth,this.lineArc)t.beginPath(),t.arc(this.xCenter,this.yCenter,n,0,2*Math.PI),t.closePath(),t.stroke();else{t.beginPath();for(var a=0;a<this.valuesCount;a++)s=this.getPointPosition(a,this.calculateCenterOffset(this.min+e*this.stepValue)),0===a?t.moveTo(s.x,s.y):t.lineTo(s.x,s.y);t.closePath(),t.stroke()}if(this.showLabels){if(t.font=W(this.fontSize,this.fontStyle,this.fontFamily),this.showLabelBackdrop){var h=t.measureText(i).width;t.fillStyle=this.backdropColor,t.fillRect(this.xCenter-h/2-this.backdropPaddingX,o-this.fontSize/2-this.backdropPaddingY,h+2*this.backdropPaddingX,this.fontSize+2*this.backdropPaddingY)}t.textAlign="center",t.textBaseline="middle",t.fillStyle=this.fontColor,t.fillText(i,this.xCenter,o)}}},this),!this.lineArc){t.lineWidth=this.angleLineWidth,t.strokeStyle=this.angleLineColor;for(var i=this.valuesCount-1;i>=0;i--){if(this.angleLineWidth>0){var e=this.getPointPosition(i,this.calculateCenterOffset(this.max));t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(e.x,e.y),t.stroke(),t.closePath()}var s=this.getPointPosition(i,this.calculateCenterOffset(this.max)+5);t.font=W(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily),t.fillStyle=this.pointLabelFontColor;var o=this.labels.length,a=this.labels.length/2,h=a/2,l=h>i||i>o-h,r=i===h||i===o-h;t.textAlign=0===i?"center":i===a?"center":a>i?"left":"right",t.textBaseline=r?"middle":l?"bottom":"top",t.fillText(this.labels[i],s.x,s.y)}}}}}),s.addEvent(window,"resize",function(){var t;return function(){clearTimeout(t),t=setTimeout(function(){n(e.instances,function(t){t.options.responsive&&t.resize(t.render,!0)})},50)}}()),p?define(function(){return e}):"object"==typeof module&&module.exports&&(module.exports=e),t.Chart=e,e.noConflict=function(){return t.Chart=i,e}}).call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={scaleBeginAtZero:!0,scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,scaleShowHorizontalLines:!0,scaleShowVerticalLines:!0,barShowStroke:!0,barStrokeWidth:2,barValueSpacing:5,barDatasetSpacing:1,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].fillColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>'};i.Type.extend({name:"Bar",defaults:s,initialize:function(t){var s=this.options;this.ScaleClass=i.Scale.extend({offsetGridLines:!0,calculateBarX:function(t,i,e){var n=this.calculateBaseWidth(),o=this.calculateX(e)-n/2,a=this.calculateBarWidth(t);return o+a*i+i*s.barDatasetSpacing+a/2},calculateBaseWidth:function(){return this.calculateX(1)-this.calculateX(0)-2*s.barValueSpacing},calculateBarWidth:function(t){var i=this.calculateBaseWidth()-(t-1)*s.barDatasetSpacing;return i/t}}),this.datasets=[],this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getBarsAtEvent(t):[];this.eachBars(function(t){t.restore(["fillColor","strokeColor"])}),e.each(i,function(t){t.fillColor=t.highlightFill,t.strokeColor=t.highlightStroke}),this.showTooltip(i)}),this.BarClass=i.Rectangle.extend({strokeWidth:this.options.barStrokeWidth,showStroke:this.options.barShowStroke,ctx:this.chart.ctx}),e.each(t.datasets,function(i){var s={label:i.label||null,fillColor:i.fillColor,strokeColor:i.strokeColor,bars:[]};this.datasets.push(s),e.each(i.data,function(e,n){s.bars.push(new this.BarClass({value:e,label:t.labels[n],datasetLabel:i.label,strokeColor:i.strokeColor,fillColor:i.fillColor,highlightFill:i.highlightFill||i.fillColor,highlightStroke:i.highlightStroke||i.strokeColor}))},this)},this),this.buildScale(t.labels),this.BarClass.prototype.base=this.scale.endPoint,this.eachBars(function(t,i,s){e.extend(t,{width:this.scale.calculateBarWidth(this.datasets.length),x:this.scale.calculateBarX(this.datasets.length,s,i),y:this.scale.endPoint}),t.save()},this),this.render()},update:function(){this.scale.update(),e.each(this.activeElements,function(t){t.restore(["fillColor","strokeColor"])}),this.eachBars(function(t){t.save()}),this.render()},eachBars:function(t){e.each(this.datasets,function(i,s){e.each(i.bars,t,this,s)},this)},getBarsAtEvent:function(t){for(var i,s=[],n=e.getRelativePosition(t),o=function(t){s.push(t.bars[i])},a=0;a<this.datasets.length;a++)for(i=0;i<this.datasets[a].bars.length;i++)if(this.datasets[a].bars[i].inRange(n.x,n.y))return e.each(this.datasets,o),s;return s},buildScale:function(t){var i=this,s=function(){var t=[];return i.eachBars(function(i){t.push(i.value)}),t},n={templateString:this.options.scaleLabel,height:this.chart.height,width:this.chart.width,ctx:this.chart.ctx,textColor:this.options.scaleFontColor,fontSize:this.options.scaleFontSize,fontStyle:this.options.scaleFontStyle,fontFamily:this.options.scaleFontFamily,valuesCount:t.length,beginAtZero:this.options.scaleBeginAtZero,integersOnly:this.options.scaleIntegersOnly,calculateYRange:function(t){var i=e.calculateScaleRange(s(),t,this.fontSize,this.beginAtZero,this.integersOnly);e.extend(this,i)},xLabels:t,font:e.fontString(this.options.scaleFontSize,this.options.scaleFontStyle,this.options.scaleFontFamily),lineWidth:this.options.scaleLineWidth,lineColor:this.options.scaleLineColor,showHorizontalLines:this.options.scaleShowHorizontalLines,showVerticalLines:this.options.scaleShowVerticalLines,gridLineWidth:this.options.scaleShowGridLines?this.options.scaleGridLineWidth:0,gridLineColor:this.options.scaleShowGridLines?this.options.scaleGridLineColor:"rgba(0,0,0,0)",padding:this.options.showScale?0:this.options.barShowStroke?this.options.barStrokeWidth:0,showLabels:this.options.scaleShowLabels,display:this.options.showScale};this.options.scaleOverride&&e.extend(n,{calculateYRange:e.noop,steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}),this.scale=new this.ScaleClass(n)},addData:function(t,i){e.each(t,function(t,e){this.datasets[e].bars.push(new this.BarClass({value:t,label:i,x:this.scale.calculateBarX(this.datasets.length,e,this.scale.valuesCount+1),y:this.scale.endPoint,width:this.scale.calculateBarWidth(this.datasets.length),base:this.scale.endPoint,strokeColor:this.datasets[e].strokeColor,fillColor:this.datasets[e].fillColor}))
+},this),this.scale.addXLabel(i),this.update()},removeData:function(){this.scale.removeXLabel(),e.each(this.datasets,function(t){t.bars.shift()},this),this.update()},reflow:function(){e.extend(this.BarClass.prototype,{y:this.scale.endPoint,base:this.scale.endPoint});var t=e.extend({height:this.chart.height,width:this.chart.width});this.scale.update(t)},draw:function(t){var i=t||1;this.clear();this.chart.ctx;this.scale.draw(i),e.each(this.datasets,function(t,s){e.each(t.bars,function(t,e){t.hasValue()&&(t.base=this.scale.endPoint,t.transition({x:this.scale.calculateBarX(this.datasets.length,s,e),y:this.scale.calculateY(t.value),width:this.scale.calculateBarWidth(this.datasets.length)},i).draw())},this)},this)}})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,percentageInnerCutout:50,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'};i.Type.extend({name:"Doughnut",defaults:s,initialize:function(t){this.segments=[],this.outerRadius=(e.min([this.chart.width,this.chart.height])-this.options.segmentStrokeWidth/2)/2,this.SegmentArc=i.Arc.extend({ctx:this.chart.ctx,x:this.chart.width/2,y:this.chart.height/2}),this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getSegmentsAtEvent(t):[];e.each(this.segments,function(t){t.restore(["fillColor"])}),e.each(i,function(t){t.fillColor=t.highlightColor}),this.showTooltip(i)}),this.calculateTotal(t),e.each(t,function(t,i){this.addData(t,i,!0)},this),this.render()},getSegmentsAtEvent:function(t){var i=[],s=e.getRelativePosition(t);return e.each(this.segments,function(t){t.inRange(s.x,s.y)&&i.push(t)},this),i},addData:function(t,i,e){var s=i||this.segments.length;this.segments.splice(s,0,new this.SegmentArc({value:t.value,outerRadius:this.options.animateScale?0:this.outerRadius,innerRadius:this.options.animateScale?0:this.outerRadius/100*this.options.percentageInnerCutout,fillColor:t.color,highlightColor:t.highlight||t.color,showStroke:this.options.segmentShowStroke,strokeWidth:this.options.segmentStrokeWidth,strokeColor:this.options.segmentStrokeColor,startAngle:1.5*Math.PI,circumference:this.options.animateRotate?0:this.calculateCircumference(t.value),label:t.label})),e||(this.reflow(),this.update())},calculateCircumference:function(t){return 2*Math.PI*(Math.abs(t)/this.total)},calculateTotal:function(t){this.total=0,e.each(t,function(t){this.total+=Math.abs(t.value)},this)},update:function(){this.calculateTotal(this.segments),e.each(this.activeElements,function(t){t.restore(["fillColor"])}),e.each(this.segments,function(t){t.save()}),this.render()},removeData:function(t){var i=e.isNumber(t)?t:this.segments.length-1;this.segments.splice(i,1),this.reflow(),this.update()},reflow:function(){e.extend(this.SegmentArc.prototype,{x:this.chart.width/2,y:this.chart.height/2}),this.outerRadius=(e.min([this.chart.width,this.chart.height])-this.options.segmentStrokeWidth/2)/2,e.each(this.segments,function(t){t.update({outerRadius:this.outerRadius,innerRadius:this.outerRadius/100*this.options.percentageInnerCutout})},this)},draw:function(t){var i=t?t:1;this.clear(),e.each(this.segments,function(t,e){t.transition({circumference:this.calculateCircumference(t.value),outerRadius:this.outerRadius,innerRadius:this.outerRadius/100*this.options.percentageInnerCutout},i),t.endAngle=t.startAngle+t.circumference,t.draw(),0===e&&(t.startAngle=1.5*Math.PI),e<this.segments.length-1&&(this.segments[e+1].startAngle=t.endAngle)},this)}}),i.types.Doughnut.extend({name:"Pie",defaults:e.merge(s,{percentageInnerCutout:0})})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,scaleShowHorizontalLines:!0,scaleShowVerticalLines:!0,bezierCurve:!0,bezierCurveTension:.4,pointDot:!0,pointDotRadius:4,pointDotStrokeWidth:1,pointHitDetectionRadius:20,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].strokeColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>'};i.Type.extend({name:"Line",defaults:s,initialize:function(t){this.PointClass=i.Point.extend({strokeWidth:this.options.pointDotStrokeWidth,radius:this.options.pointDotRadius,display:this.options.pointDot,hitDetectionRadius:this.options.pointHitDetectionRadius,ctx:this.chart.ctx,inRange:function(t){return Math.pow(t-this.x,2)<Math.pow(this.radius+this.hitDetectionRadius,2)}}),this.datasets=[],this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getPointsAtEvent(t):[];this.eachPoints(function(t){t.restore(["fillColor","strokeColor"])}),e.each(i,function(t){t.fillColor=t.highlightFill,t.strokeColor=t.highlightStroke}),this.showTooltip(i)}),e.each(t.datasets,function(i){var s={label:i.label||null,fillColor:i.fillColor,strokeColor:i.strokeColor,pointColor:i.pointColor,pointStrokeColor:i.pointStrokeColor,points:[]};this.datasets.push(s),e.each(i.data,function(e,n){s.points.push(new this.PointClass({value:e,label:t.labels[n],datasetLabel:i.label,strokeColor:i.pointStrokeColor,fillColor:i.pointColor,highlightFill:i.pointHighlightFill||i.pointColor,highlightStroke:i.pointHighlightStroke||i.pointStrokeColor}))},this),this.buildScale(t.labels),this.eachPoints(function(t,i){e.extend(t,{x:this.scale.calculateX(i),y:this.scale.endPoint}),t.save()},this)},this),this.render()},update:function(){this.scale.update(),e.each(this.activeElements,function(t){t.restore(["fillColor","strokeColor"])}),this.eachPoints(function(t){t.save()}),this.render()},eachPoints:function(t){e.each(this.datasets,function(i){e.each(i.points,t,this)},this)},getPointsAtEvent:function(t){var i=[],s=e.getRelativePosition(t);return e.each(this.datasets,function(t){e.each(t.points,function(t){t.inRange(s.x,s.y)&&i.push(t)})},this),i},buildScale:function(t){var s=this,n=function(){var t=[];return s.eachPoints(function(i){t.push(i.value)}),t},o={templateString:this.options.scaleLabel,height:this.chart.height,width:this.chart.width,ctx:this.chart.ctx,textColor:this.options.scaleFontColor,fontSize:this.options.scaleFontSize,fontStyle:this.options.scaleFontStyle,fontFamily:this.options.scaleFontFamily,valuesCount:t.length,beginAtZero:this.options.scaleBeginAtZero,integersOnly:this.options.scaleIntegersOnly,calculateYRange:function(t){var i=e.calculateScaleRange(n(),t,this.fontSize,this.beginAtZero,this.integersOnly);e.extend(this,i)},xLabels:t,font:e.fontString(this.options.scaleFontSize,this.options.scaleFontStyle,this.options.scaleFontFamily),lineWidth:this.options.scaleLineWidth,lineColor:this.options.scaleLineColor,showHorizontalLines:this.options.scaleShowHorizontalLines,showVerticalLines:this.options.scaleShowVerticalLines,gridLineWidth:this.options.scaleShowGridLines?this.options.scaleGridLineWidth:0,gridLineColor:this.options.scaleShowGridLines?this.options.scaleGridLineColor:"rgba(0,0,0,0)",padding:this.options.showScale?0:this.options.pointDotRadius+this.options.pointDotStrokeWidth,showLabels:this.options.scaleShowLabels,display:this.options.showScale};this.options.scaleOverride&&e.extend(o,{calculateYRange:e.noop,steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}),this.scale=new i.Scale(o)},addData:function(t,i){e.each(t,function(t,e){this.datasets[e].points.push(new this.PointClass({value:t,label:i,x:this.scale.calculateX(this.scale.valuesCount+1),y:this.scale.endPoint,strokeColor:this.datasets[e].pointStrokeColor,fillColor:this.datasets[e].pointColor}))},this),this.scale.addXLabel(i),this.update()},removeData:function(){this.scale.removeXLabel(),e.each(this.datasets,function(t){t.points.shift()},this),this.update()},reflow:function(){var t=e.extend({height:this.chart.height,width:this.chart.width});this.scale.update(t)},draw:function(t){var i=t||1;this.clear();var s=this.chart.ctx,n=function(t){return null!==t.value},o=function(t,i,s){return e.findNextWhere(i,n,s)||t},a=function(t,i,s){return e.findPreviousWhere(i,n,s)||t};this.scale.draw(i),e.each(this.datasets,function(t){var h=e.where(t.points,n);e.each(t.points,function(t,e){t.hasValue()&&t.transition({y:this.scale.calculateY(t.value),x:this.scale.calculateX(e)},i)},this),this.options.bezierCurve&&e.each(h,function(t,i){var s=i>0&&i<h.length-1?this.options.bezierCurveTension:0;t.controlPoints=e.splineCurve(a(t,h,i),t,o(t,h,i),s),t.controlPoints.outer.y>this.scale.endPoint?t.controlPoints.outer.y=this.scale.endPoint:t.controlPoints.outer.y<this.scale.startPoint&&(t.controlPoints.outer.y=this.scale.startPoint),t.controlPoints.inner.y>this.scale.endPoint?t.controlPoints.inner.y=this.scale.endPoint:t.controlPoints.inner.y<this.scale.startPoint&&(t.controlPoints.inner.y=this.scale.startPoint)},this),s.lineWidth=this.options.datasetStrokeWidth,s.strokeStyle=t.strokeColor,s.beginPath(),e.each(h,function(t,i){if(0===i)s.moveTo(t.x,t.y);else if(this.options.bezierCurve){var e=a(t,h,i);s.bezierCurveTo(e.controlPoints.outer.x,e.controlPoints.outer.y,t.controlPoints.inner.x,t.controlPoints.inner.y,t.x,t.y)}else s.lineTo(t.x,t.y)},this),s.stroke(),this.options.datasetFill&&h.length>0&&(s.lineTo(h[h.length-1].x,this.scale.endPoint),s.lineTo(h[0].x,this.scale.endPoint),s.fillStyle=t.fillColor,s.closePath(),s.fill()),e.each(h,function(t){t.draw()})},this)}})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={scaleShowLabelBackdrop:!0,scaleBackdropColor:"rgba(255,255,255,0.75)",scaleBeginAtZero:!0,scaleBackdropPaddingY:2,scaleBackdropPaddingX:2,scaleShowLine:!0,segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'};i.Type.extend({name:"PolarArea",defaults:s,initialize:function(t){this.segments=[],this.SegmentArc=i.Arc.extend({showStroke:this.options.segmentShowStroke,strokeWidth:this.options.segmentStrokeWidth,strokeColor:this.options.segmentStrokeColor,ctx:this.chart.ctx,innerRadius:0,x:this.chart.width/2,y:this.chart.height/2}),this.scale=new i.RadialScale({display:this.options.showScale,fontStyle:this.options.scaleFontStyle,fontSize:this.options.scaleFontSize,fontFamily:this.options.scaleFontFamily,fontColor:this.options.scaleFontColor,showLabels:this.options.scaleShowLabels,showLabelBackdrop:this.options.scaleShowLabelBackdrop,backdropColor:this.options.scaleBackdropColor,backdropPaddingY:this.options.scaleBackdropPaddingY,backdropPaddingX:this.options.scaleBackdropPaddingX,lineWidth:this.options.scaleShowLine?this.options.scaleLineWidth:0,lineColor:this.options.scaleLineColor,lineArc:!0,width:this.chart.width,height:this.chart.height,xCenter:this.chart.width/2,yCenter:this.chart.height/2,ctx:this.chart.ctx,templateString:this.options.scaleLabel,valuesCount:t.length}),this.updateScaleRange(t),this.scale.update(),e.each(t,function(t,i){this.addData(t,i,!0)},this),this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getSegmentsAtEvent(t):[];e.each(this.segments,function(t){t.restore(["fillColor"])}),e.each(i,function(t){t.fillColor=t.highlightColor}),this.showTooltip(i)}),this.render()},getSegmentsAtEvent:function(t){var i=[],s=e.getRelativePosition(t);return e.each(this.segments,function(t){t.inRange(s.x,s.y)&&i.push(t)},this),i},addData:function(t,i,e){var s=i||this.segments.length;this.segments.splice(s,0,new this.SegmentArc({fillColor:t.color,highlightColor:t.highlight||t.color,label:t.label,value:t.value,outerRadius:this.options.animateScale?0:this.scale.calculateCenterOffset(t.value),circumference:this.options.animateRotate?0:this.scale.getCircumference(),startAngle:1.5*Math.PI})),e||(this.reflow(),this.update())},removeData:function(t){var i=e.isNumber(t)?t:this.segments.length-1;this.segments.splice(i,1),this.reflow(),this.update()},calculateTotal:function(t){this.total=0,e.each(t,function(t){this.total+=t.value},this),this.scale.valuesCount=this.segments.length},updateScaleRange:function(t){var i=[];e.each(t,function(t){i.push(t.value)});var s=this.options.scaleOverride?{steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}:e.calculateScaleRange(i,e.min([this.chart.width,this.chart.height])/2,this.options.scaleFontSize,this.options.scaleBeginAtZero,this.options.scaleIntegersOnly);e.extend(this.scale,s,{size:e.min([this.chart.width,this.chart.height]),xCenter:this.chart.width/2,yCenter:this.chart.height/2})},update:function(){this.calculateTotal(this.segments),e.each(this.segments,function(t){t.save()}),this.reflow(),this.render()},reflow:function(){e.extend(this.SegmentArc.prototype,{x:this.chart.width/2,y:this.chart.height/2}),this.updateScaleRange(this.segments),this.scale.update(),e.extend(this.scale,{xCenter:this.chart.width/2,yCenter:this.chart.height/2}),e.each(this.segments,function(t){t.update({outerRadius:this.scale.calculateCenterOffset(t.value)})},this)},draw:function(t){var i=t||1;this.clear(),e.each(this.segments,function(t,e){t.transition({circumference:this.scale.getCircumference(),outerRadius:this.scale.calculateCenterOffset(t.value)},i),t.endAngle=t.startAngle+t.circumference,0===e&&(t.startAngle=1.5*Math.PI),e<this.segments.length-1&&(this.segments[e+1].startAngle=t.endAngle),t.draw()},this),this.scale.draw()}})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers;i.Type.extend({name:"Radar",defaults:{scaleShowLine:!0,angleShowLineOut:!0,scaleShowLabels:!1,scaleBeginAtZero:!0,angleLineColor:"rgba(0,0,0,.1)",angleLineWidth:1,pointLabelFontFamily:"'Arial'",pointLabelFontStyle:"normal",pointLabelFontSize:10,pointLabelFontColor:"#666",pointDot:!0,pointDotRadius:3,pointDotStrokeWidth:1,pointHitDetectionRadius:20,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].strokeColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>'},initialize:function(t){this.PointClass=i.Point.extend({strokeWidth:this.options.pointDotStrokeWidth,radius:this.options.pointDotRadius,display:this.options.pointDot,hitDetectionRadius:this.options.pointHitDetectionRadius,ctx:this.chart.ctx}),this.datasets=[],this.buildScale(t),this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getPointsAtEvent(t):[];this.eachPoints(function(t){t.restore(["fillColor","strokeColor"])}),e.each(i,function(t){t.fillColor=t.highlightFill,t.strokeColor=t.highlightStroke}),this.showTooltip(i)}),e.each(t.datasets,function(i){var s={label:i.label||null,fillColor:i.fillColor,strokeColor:i.strokeColor,pointColor:i.pointColor,pointStrokeColor:i.pointStrokeColor,points:[]};this.datasets.push(s),e.each(i.data,function(e,n){var o;this.scale.animation||(o=this.scale.getPointPosition(n,this.scale.calculateCenterOffset(e))),s.points.push(new this.PointClass({value:e,label:t.labels[n],datasetLabel:i.label,x:this.options.animation?this.scale.xCenter:o.x,y:this.options.animation?this.scale.yCenter:o.y,strokeColor:i.pointStrokeColor,fillColor:i.pointColor,highlightFill:i.pointHighlightFill||i.pointColor,highlightStroke:i.pointHighlightStroke||i.pointStrokeColor}))},this)},this),this.render()},eachPoints:function(t){e.each(this.datasets,function(i){e.each(i.points,t,this)},this)},getPointsAtEvent:function(t){var i=e.getRelativePosition(t),s=e.getAngleFromPoint({x:this.scale.xCenter,y:this.scale.yCenter},i),n=2*Math.PI/this.scale.valuesCount,o=Math.round((s.angle-1.5*Math.PI)/n),a=[];return(o>=this.scale.valuesCount||0>o)&&(o=0),s.distance<=this.scale.drawingArea&&e.each(this.datasets,function(t){a.push(t.points[o])}),a},buildScale:function(t){this.scale=new i.RadialScale({display:this.options.showScale,fontStyle:this.options.scaleFontStyle,fontSize:this.options.scaleFontSize,fontFamily:this.options.scaleFontFamily,fontColor:this.options.scaleFontColor,showLabels:this.options.scaleShowLabels,showLabelBackdrop:this.options.scaleShowLabelBackdrop,backdropColor:this.options.scaleBackdropColor,backdropPaddingY:this.options.scaleBackdropPaddingY,backdropPaddingX:this.options.scaleBackdropPaddingX,lineWidth:this.options.scaleShowLine?this.options.scaleLineWidth:0,lineColor:this.options.scaleLineColor,angleLineColor:this.options.angleLineColor,angleLineWidth:this.options.angleShowLineOut?this.options.angleLineWidth:0,pointLabelFontColor:this.options.pointLabelFontColor,pointLabelFontSize:this.options.pointLabelFontSize,pointLabelFontFamily:this.options.pointLabelFontFamily,pointLabelFontStyle:this.options.pointLabelFontStyle,height:this.chart.height,width:this.chart.width,xCenter:this.chart.width/2,yCenter:this.chart.height/2,ctx:this.chart.ctx,templateString:this.options.scaleLabel,labels:t.labels,valuesCount:t.datasets[0].data.length}),this.scale.setScaleSize(),this.updateScaleRange(t.datasets),this.scale.buildYLabels()},updateScaleRange:function(t){var i=function(){var i=[];return e.each(t,function(t){t.data?i=i.concat(t.data):e.each(t.points,function(t){i.push(t.value)})}),i}(),s=this.options.scaleOverride?{steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}:e.calculateScaleRange(i,e.min([this.chart.width,this.chart.height])/2,this.options.scaleFontSize,this.options.scaleBeginAtZero,this.options.scaleIntegersOnly);e.extend(this.scale,s)},addData:function(t,i){this.scale.valuesCount++,e.each(t,function(t,e){var s=this.scale.getPointPosition(this.scale.valuesCount,this.scale.calculateCenterOffset(t));this.datasets[e].points.push(new this.PointClass({value:t,label:i,x:s.x,y:s.y,strokeColor:this.datasets[e].pointStrokeColor,fillColor:this.datasets[e].pointColor}))},this),this.scale.labels.push(i),this.reflow(),this.update()},removeData:function(){this.scale.valuesCount--,this.scale.labels.shift(),e.each(this.datasets,function(t){t.points.shift()},this),this.reflow(),this.update()},update:function(){this.eachPoints(function(t){t.save()}),this.reflow(),this.render()},reflow:function(){e.extend(this.scale,{width:this.chart.width,height:this.chart.height,size:e.min([this.chart.width,this.chart.height]),xCenter:this.chart.width/2,yCenter:this.chart.height/2}),this.updateScaleRange(this.datasets),this.scale.setScaleSize(),this.scale.buildYLabels()},draw:function(t){var i=t||1,s=this.chart.ctx;this.clear(),this.scale.draw(),e.each(this.datasets,function(t){e.each(t.points,function(t,e){t.hasValue()&&t.transition(this.scale.getPointPosition(e,this.scale.calculateCenterOffset(t.value)),i)},this),s.lineWidth=this.options.datasetStrokeWidth,s.strokeStyle=t.strokeColor,s.beginPath(),e.each(t.points,function(t,i){0===i?s.moveTo(t.x,t.y):s.lineTo(t.x,t.y)},this),s.closePath(),s.stroke(),s.fillStyle=t.fillColor,s.fill(),e.each(t.points,function(t){t.hasValue()&&t.draw()})},this)}})}.call(this);
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/LICENSE.md b/xos-apps/auto-scale/gui/src/vendor/Chart.js/LICENSE.md
new file mode 100644
index 0000000..e10bc0f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/LICENSE.md
@@ -0,0 +1,7 @@
+Copyright (c) 2013-2015 Nick Downie
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/README.md b/xos-apps/auto-scale/gui/src/vendor/Chart.js/README.md
new file mode 100644
index 0000000..7c4fa8b
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/README.md
@@ -0,0 +1,20 @@
+# Chart.js
+
+[![Build Status](https://travis-ci.org/nnnick/Chart.js.svg?branch=master)](https://travis-ci.org/nnnick/Chart.js) [![Code Climate](https://codeclimate.com/github/nnnick/Chart.js/badges/gpa.svg)](https://codeclimate.com/github/nnnick/Chart.js)
+
+
+*Simple HTML5 Charts using the canvas element* [chartjs.org](http://www.chartjs.org)
+
+## Documentation
+
+You can find documentation at [chartjs.org/docs](http://www.chartjs.org/docs/). The markdown files that build the site are available under `/docs`. Please note - in some of the json examples of configuration you might notice some liquid tags - this is just for the generating the site html, please disregard.
+
+## Bugs, issues and contributing
+
+Before submitting an issue or a pull request to the project, please take a moment to look over the [contributing guidelines](https://github.com/nnnick/Chart.js/blob/master/CONTRIBUTING.md) first.
+
+For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](http://stackoverflow.com/questions/tagged/chartjs).
+
+## License
+
+Chart.js is available under the [MIT license](http://opensource.org/licenses/MIT).
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/bower.json b/xos-apps/auto-scale/gui/src/vendor/Chart.js/bower.json
new file mode 100644
index 0000000..f26f81e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/bower.json
@@ -0,0 +1,11 @@
+{
+ "name": "Chart.js",
+ "version": "1.0.2",
+ "description": "Simple HTML5 Charts using the canvas element",
+ "homepage": "https://github.com/nnnick/Chart.js",
+ "author": "nnnick",
+ "main": [
+ "Chart.js"
+ ],
+ "dependencies": {}
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/00-Getting-Started.md b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/00-Getting-Started.md
new file mode 100644
index 0000000..273b10f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/00-Getting-Started.md
@@ -0,0 +1,203 @@
+---
+title: Getting started
+anchor: getting-started
+---
+
+###Include Chart.js
+
+First we need to include the Chart.js library on the page. The library occupies a global variable of `Chart`.
+
+```html
+<script src="Chart.js"></script>
+```
+
+Alternatively, if you're using an AMD loader for JavaScript modules, that is also supported in the Chart.js core. Please note: the library will still occupy a global variable of `Chart`, even if it detects `define` and `define.amd`. If this is a problem, you can call `noConflict` to restore the global Chart variable to it's previous owner.
+
+```javascript
+// Using requirejs
+require(['path/to/Chartjs'], function(Chart){
+ // Use Chart.js as normal here.
+
+ // Chart.noConflict restores the Chart global variable to it's previous owner
+ // The function returns what was previously Chart, allowing you to reassign.
+ var Chartjs = Chart.noConflict();
+
+});
+```
+
+You can also grab Chart.js using bower:
+
+```bash
+bower install Chart.js --save
+```
+
+###Creating a chart
+
+To create a chart, we need to instantiate the `Chart` class. To do this, we need to pass in the 2d context of where we want to draw the chart. Here's an example.
+
+```html
+<canvas id="myChart" width="400" height="400"></canvas>
+```
+
+```javascript
+// Get the context of the canvas element we want to select
+var ctx = document.getElementById("myChart").getContext("2d");
+var myNewChart = new Chart(ctx).PolarArea(data);
+```
+
+We can also get the context of our canvas with jQuery. To do this, we need to get the DOM node out of the jQuery collection, and call the `getContext("2d")` method on that.
+
+```javascript
+// Get context with jQuery - using jQuery's .get() method.
+var ctx = $("#myChart").get(0).getContext("2d");
+// This will get the first returned node in the jQuery collection.
+var myNewChart = new Chart(ctx);
+```
+
+After we've instantiated the Chart class on the canvas we want to draw on, Chart.js will handle the scaling for retina displays.
+
+With the Chart class set up, we can go on to create one of the charts Chart.js has available. In the example below, we would be drawing a Polar area chart.
+
+```javascript
+new Chart(ctx).PolarArea(data, options);
+```
+
+We call a method of the name of the chart we want to create. We pass in the data for that chart type, and the options for that chart as parameters. Chart.js will merge the global defaults with chart type specific defaults, then merge any options passed in as a second argument after data.
+
+###Global chart configuration
+
+This concept was introduced in Chart.js 1.0 to keep configuration DRY, and allow for changing options globally across chart types, avoiding the need to specify options for each instance, or the default for a particular chart type.
+
+```javascript
+Chart.defaults.global = {
+ // Boolean - Whether to animate the chart
+ animation: true,
+
+ // Number - Number of animation steps
+ animationSteps: 60,
+
+ // String - Animation easing effect
+ animationEasing: "easeOutQuart",
+
+ // Boolean - If we should show the scale at all
+ showScale: true,
+
+ // Boolean - If we want to override with a hard coded scale
+ scaleOverride: false,
+
+ // ** Required if scaleOverride is true **
+ // Number - The number of steps in a hard coded scale
+ scaleSteps: null,
+ // Number - The value jump in the hard coded scale
+ scaleStepWidth: null,
+ // Number - The scale starting value
+ scaleStartValue: null,
+
+ // String - Colour of the scale line
+ scaleLineColor: "rgba(0,0,0,.1)",
+
+ // Number - Pixel width of the scale line
+ scaleLineWidth: 1,
+
+ // Boolean - Whether to show labels on the scale
+ scaleShowLabels: true,
+
+ // Interpolated JS string - can access value
+ scaleLabel: "<%=value%>",
+
+ // Boolean - Whether the scale should stick to integers, not floats even if drawing space is there
+ scaleIntegersOnly: true,
+
+ // Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
+ scaleBeginAtZero: false,
+
+ // String - Scale label font declaration for the scale label
+ scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
+
+ // Number - Scale label font size in pixels
+ scaleFontSize: 12,
+
+ // String - Scale label font weight style
+ scaleFontStyle: "normal",
+
+ // String - Scale label font colour
+ scaleFontColor: "#666",
+
+ // Boolean - whether or not the chart should be responsive and resize when the browser does.
+ responsive: false,
+
+ // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
+ maintainAspectRatio: true,
+
+ // Boolean - Determines whether to draw tooltips on the canvas or not
+ showTooltips: true,
+
+ // Function - Determines whether to execute the customTooltips function instead of drawing the built in tooltips (See [Advanced - External Tooltips](#advanced-usage-custom-tooltips))
+ customTooltips: false,
+
+ // Array - Array of string names to attach tooltip events
+ tooltipEvents: ["mousemove", "touchstart", "touchmove"],
+
+ // String - Tooltip background colour
+ tooltipFillColor: "rgba(0,0,0,0.8)",
+
+ // String - Tooltip label font declaration for the scale label
+ tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
+
+ // Number - Tooltip label font size in pixels
+ tooltipFontSize: 14,
+
+ // String - Tooltip font weight style
+ tooltipFontStyle: "normal",
+
+ // String - Tooltip label font colour
+ tooltipFontColor: "#fff",
+
+ // String - Tooltip title font declaration for the scale label
+ tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
+
+ // Number - Tooltip title font size in pixels
+ tooltipTitleFontSize: 14,
+
+ // String - Tooltip title font weight style
+ tooltipTitleFontStyle: "bold",
+
+ // String - Tooltip title font colour
+ tooltipTitleFontColor: "#fff",
+
+ // Number - pixel width of padding around tooltip text
+ tooltipYPadding: 6,
+
+ // Number - pixel width of padding around tooltip text
+ tooltipXPadding: 6,
+
+ // Number - Size of the caret on the tooltip
+ tooltipCaretSize: 8,
+
+ // Number - Pixel radius of the tooltip border
+ tooltipCornerRadius: 6,
+
+ // Number - Pixel offset from point x to tooltip edge
+ tooltipXOffset: 10,
+ {% raw %}
+ // String - Template string for single tooltips
+ tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
+ {% endraw %}
+ // String - Template string for multiple tooltips
+ multiTooltipTemplate: "<%= value %>",
+
+ // Function - Will fire on animation progression.
+ onAnimationProgress: function(){},
+
+ // Function - Will fire on animation completion.
+ onAnimationComplete: function(){}
+}
+```
+
+If for example, you wanted all charts created to be responsive, and resize when the browser window does, the following setting can be changed:
+
+```javascript
+Chart.defaults.global.responsive = true;
+```
+
+Now, every time we create a chart, `options.responsive` will be `true`.
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/01-Line-Chart.md b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/01-Line-Chart.md
new file mode 100644
index 0000000..1a5ae84
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/01-Line-Chart.md
@@ -0,0 +1,166 @@
+---
+title: Line Chart
+anchor: line-chart
+---
+###Introduction
+A line chart is a way of plotting data points on a line.
+
+Often, it is used to show trend data, and the comparison of two data sets.
+
+<div class="canvas-holder">
+ <canvas width="250" height="125"></canvas>
+</div>
+
+###Example usage
+```javascript
+var myLineChart = new Chart(ctx).Line(data, options);
+```
+###Data structure
+
+```javascript
+var data = {
+ labels: ["January", "February", "March", "April", "May", "June", "July"],
+ datasets: [
+ {
+ label: "My First dataset",
+ fillColor: "rgba(220,220,220,0.2)",
+ strokeColor: "rgba(220,220,220,1)",
+ pointColor: "rgba(220,220,220,1)",
+ pointStrokeColor: "#fff",
+ pointHighlightFill: "#fff",
+ pointHighlightStroke: "rgba(220,220,220,1)",
+ data: [65, 59, 80, 81, 56, 55, 40]
+ },
+ {
+ label: "My Second dataset",
+ fillColor: "rgba(151,187,205,0.2)",
+ strokeColor: "rgba(151,187,205,1)",
+ pointColor: "rgba(151,187,205,1)",
+ pointStrokeColor: "#fff",
+ pointHighlightFill: "#fff",
+ pointHighlightStroke: "rgba(151,187,205,1)",
+ data: [28, 48, 40, 19, 86, 27, 90]
+ }
+ ]
+};
+```
+
+The line chart requires an array of labels for each of the data points. This is shown on the X axis.
+The data for line charts is broken up into an array of datasets. Each dataset has a colour for the fill, a colour for the line and colours for the points and strokes of the points. These colours are strings just like CSS. You can use RGBA, RGB, HEX or HSL notation.
+
+The label key on each dataset is optional, and can be used when generating a scale for the chart.
+
+### Chart options
+
+These are the customisation options specific to Line charts. These options are merged with the [global chart configuration options](#getting-started-global-chart-configuration), and form the options of the chart.
+
+```javascript
+{
+
+ ///Boolean - Whether grid lines are shown across the chart
+ scaleShowGridLines : true,
+
+ //String - Colour of the grid lines
+ scaleGridLineColor : "rgba(0,0,0,.05)",
+
+ //Number - Width of the grid lines
+ scaleGridLineWidth : 1,
+
+ //Boolean - Whether to show horizontal lines (except X axis)
+ scaleShowHorizontalLines: true,
+
+ //Boolean - Whether to show vertical lines (except Y axis)
+ scaleShowVerticalLines: true,
+
+ //Boolean - Whether the line is curved between points
+ bezierCurve : true,
+
+ //Number - Tension of the bezier curve between points
+ bezierCurveTension : 0.4,
+
+ //Boolean - Whether to show a dot for each point
+ pointDot : true,
+
+ //Number - Radius of each point dot in pixels
+ pointDotRadius : 4,
+
+ //Number - Pixel width of point dot stroke
+ pointDotStrokeWidth : 1,
+
+ //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
+ pointHitDetectionRadius : 20,
+
+ //Boolean - Whether to show a stroke for datasets
+ datasetStroke : true,
+
+ //Number - Pixel width of dataset stroke
+ datasetStrokeWidth : 2,
+
+ //Boolean - Whether to fill the dataset with a colour
+ datasetFill : true,
+ {% raw %}
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
+ {% endraw %}
+};
+```
+
+You can override these for your `Chart` instance by passing a second argument into the `Line` method as an object with the keys you want to override.
+
+For example, we could have a line chart without bezier curves between points by doing the following:
+
+```javascript
+new Chart(ctx).Line(data, {
+ bezierCurve: false
+});
+// This will create a chart with all of the default options, merged from the global config,
+// and the Line chart defaults, but this particular instance will have `bezierCurve` set to false.
+```
+
+We can also change these defaults values for each Line type that is created, this object is available at `Chart.defaults.Line`.
+
+
+### Prototype methods
+
+#### .getPointsAtEvent( event )
+
+Calling `getPointsAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the point elements that are at that the same position of that event.
+
+```javascript
+canvas.onclick = function(evt){
+ var activePoints = myLineChart.getPointsAtEvent(evt);
+ // => activePoints is an array of points on the canvas that are at the same position as the click event.
+};
+```
+
+This functionality may be useful for implementing DOM based tooltips, or triggering custom behaviour in your application.
+
+#### .update( )
+
+Calling `update()` on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.
+
+```javascript
+myLineChart.datasets[0].points[2].value = 50;
+// Would update the first dataset's value of 'March' to be 50
+myLineChart.update();
+// Calling update now animates the position of March from 90 to 50.
+```
+
+#### .addData( valuesArray, label )
+
+Calling `addData(valuesArray, label)` on your Chart instance passing an array of values for each dataset, along with a label for those points.
+
+```javascript
+// The values array passed into addData should be one for each dataset in the chart
+myLineChart.addData([40, 60], "August");
+// This new data will now animate at the end of the chart.
+```
+
+#### .removeData( )
+
+Calling `removeData()` on your Chart instance will remove the first value for all datasets on the chart.
+
+```javascript
+myLineChart.removeData();
+// The chart will remove the first point and animate other points into place
+```
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/02-Bar-Chart.md b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/02-Bar-Chart.md
new file mode 100644
index 0000000..cc23f38
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/02-Bar-Chart.md
@@ -0,0 +1,149 @@
+---
+title: Bar Chart
+anchor: bar-chart
+---
+
+### Introduction
+A bar chart is a way of showing data as bars.
+
+It is sometimes used to show trend data, and the comparison of multiple data sets side by side.
+
+<div class="canvas-holder">
+ <canvas width="250" height="125"></canvas>
+</div>
+
+### Example usage
+```javascript
+var myBarChart = new Chart(ctx).Bar(data, options);
+```
+
+### Data structure
+
+```javascript
+var data = {
+ labels: ["January", "February", "March", "April", "May", "June", "July"],
+ datasets: [
+ {
+ label: "My First dataset",
+ fillColor: "rgba(220,220,220,0.5)",
+ strokeColor: "rgba(220,220,220,0.8)",
+ highlightFill: "rgba(220,220,220,0.75)",
+ highlightStroke: "rgba(220,220,220,1)",
+ data: [65, 59, 80, 81, 56, 55, 40]
+ },
+ {
+ label: "My Second dataset",
+ fillColor: "rgba(151,187,205,0.5)",
+ strokeColor: "rgba(151,187,205,0.8)",
+ highlightFill: "rgba(151,187,205,0.75)",
+ highlightStroke: "rgba(151,187,205,1)",
+ data: [28, 48, 40, 19, 86, 27, 90]
+ }
+ ]
+};
+```
+The bar chart has the a very similar data structure to the line chart, and has an array of datasets, each with colours and an array of data. Again, colours are in CSS format.
+We have an array of labels too for display. In the example, we are showing the same data as the previous line chart example.
+
+The label key on each dataset is optional, and can be used when generating a scale for the chart.
+
+### Chart Options
+
+These are the customisation options specific to Bar charts. These options are merged with the [global chart configuration options](#getting-started-global-chart-configuration), and form the options of the chart.
+
+```javascript
+{
+ //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
+ scaleBeginAtZero : true,
+
+ //Boolean - Whether grid lines are shown across the chart
+ scaleShowGridLines : true,
+
+ //String - Colour of the grid lines
+ scaleGridLineColor : "rgba(0,0,0,.05)",
+
+ //Number - Width of the grid lines
+ scaleGridLineWidth : 1,
+
+ //Boolean - Whether to show horizontal lines (except X axis)
+ scaleShowHorizontalLines: true,
+
+ //Boolean - Whether to show vertical lines (except Y axis)
+ scaleShowVerticalLines: true,
+
+ //Boolean - If there is a stroke on each bar
+ barShowStroke : true,
+
+ //Number - Pixel width of the bar stroke
+ barStrokeWidth : 2,
+
+ //Number - Spacing between each of the X value sets
+ barValueSpacing : 5,
+
+ //Number - Spacing between data sets within X values
+ barDatasetSpacing : 1,
+ {% raw %}
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
+ {% endraw %}
+}
+```
+
+You can override these for your `Chart` instance by passing a second argument into the `Bar` method as an object with the keys you want to override.
+
+For example, we could have a bar chart without a stroke on each bar by doing the following:
+
+```javascript
+new Chart(ctx).Bar(data, {
+ barShowStroke: false
+});
+// This will create a chart with all of the default options, merged from the global config,
+// and the Bar chart defaults but this particular instance will have `barShowStroke` set to false.
+```
+
+We can also change these defaults values for each Bar type that is created, this object is available at `Chart.defaults.Bar`.
+
+### Prototype methods
+
+#### .getBarsAtEvent( event )
+
+Calling `getBarsAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the bar elements that are at that the same position of that event.
+
+```javascript
+canvas.onclick = function(evt){
+ var activeBars = myBarChart.getBarsAtEvent(evt);
+ // => activeBars is an array of bars on the canvas that are at the same position as the click event.
+};
+```
+
+This functionality may be useful for implementing DOM based tooltips, or triggering custom behaviour in your application.
+
+#### .update( )
+
+Calling `update()` on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.
+
+```javascript
+myBarChart.datasets[0].bars[2].value = 50;
+// Would update the first dataset's value of 'March' to be 50
+myBarChart.update();
+// Calling update now animates the position of March from 90 to 50.
+```
+
+#### .addData( valuesArray, label )
+
+Calling `addData(valuesArray, label)` on your Chart instance passing an array of values for each dataset, along with a label for those bars.
+
+```javascript
+// The values array passed into addData should be one for each dataset in the chart
+myBarChart.addData([40, 60], "August");
+// The new data will now animate at the end of the chart.
+```
+
+#### .removeData( )
+
+Calling `removeData()` on your Chart instance will remove the first value for all datasets on the chart.
+
+```javascript
+myBarChart.removeData();
+// The chart will now animate and remove the first bar
+```
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/03-Radar-Chart.md b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/03-Radar-Chart.md
new file mode 100644
index 0000000..03dcf6e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/03-Radar-Chart.md
@@ -0,0 +1,177 @@
+---
+title: Radar Chart
+anchor: radar-chart
+---
+
+###Introduction
+A radar chart is a way of showing multiple data points and the variation between them.
+
+They are often useful for comparing the points of two or more different data sets.
+
+<div class="canvas-holder">
+ <canvas width="250" height="125"></canvas>
+</div>
+
+###Example usage
+
+```javascript
+var myRadarChart = new Chart(ctx).Radar(data, options);
+```
+
+###Data structure
+```javascript
+var data = {
+ labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],
+ datasets: [
+ {
+ label: "My First dataset",
+ fillColor: "rgba(220,220,220,0.2)",
+ strokeColor: "rgba(220,220,220,1)",
+ pointColor: "rgba(220,220,220,1)",
+ pointStrokeColor: "#fff",
+ pointHighlightFill: "#fff",
+ pointHighlightStroke: "rgba(220,220,220,1)",
+ data: [65, 59, 90, 81, 56, 55, 40]
+ },
+ {
+ label: "My Second dataset",
+ fillColor: "rgba(151,187,205,0.2)",
+ strokeColor: "rgba(151,187,205,1)",
+ pointColor: "rgba(151,187,205,1)",
+ pointStrokeColor: "#fff",
+ pointHighlightFill: "#fff",
+ pointHighlightStroke: "rgba(151,187,205,1)",
+ data: [28, 48, 40, 19, 96, 27, 100]
+ }
+ ]
+};
+```
+For a radar chart, to provide context of what each point means, we include an array of strings that show around each point in the chart.
+For the radar chart data, we have an array of datasets. Each of these is an object, with a fill colour, a stroke colour, a colour for the fill of each point, and a colour for the stroke of each point. We also have an array of data values.
+
+The label key on each dataset is optional, and can be used when generating a scale for the chart.
+
+### Chart options
+
+These are the customisation options specific to Radar charts. These options are merged with the [global chart configuration options](#getting-started-global-chart-configuration), and form the options of the chart.
+
+
+```javascript
+{
+ //Boolean - Whether to show lines for each scale point
+ scaleShowLine : true,
+
+ //Boolean - Whether we show the angle lines out of the radar
+ angleShowLineOut : true,
+
+ //Boolean - Whether to show labels on the scale
+ scaleShowLabels : false,
+
+ // Boolean - Whether the scale should begin at zero
+ scaleBeginAtZero : true,
+
+ //String - Colour of the angle line
+ angleLineColor : "rgba(0,0,0,.1)",
+
+ //Number - Pixel width of the angle line
+ angleLineWidth : 1,
+
+ //String - Point label font declaration
+ pointLabelFontFamily : "'Arial'",
+
+ //String - Point label font weight
+ pointLabelFontStyle : "normal",
+
+ //Number - Point label font size in pixels
+ pointLabelFontSize : 10,
+
+ //String - Point label font colour
+ pointLabelFontColor : "#666",
+
+ //Boolean - Whether to show a dot for each point
+ pointDot : true,
+
+ //Number - Radius of each point dot in pixels
+ pointDotRadius : 3,
+
+ //Number - Pixel width of point dot stroke
+ pointDotStrokeWidth : 1,
+
+ //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
+ pointHitDetectionRadius : 20,
+
+ //Boolean - Whether to show a stroke for datasets
+ datasetStroke : true,
+
+ //Number - Pixel width of dataset stroke
+ datasetStrokeWidth : 2,
+
+ //Boolean - Whether to fill the dataset with a colour
+ datasetFill : true,
+ {% raw %}
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
+ {% endraw %}
+}
+```
+
+
+You can override these for your `Chart` instance by passing a second argument into the `Radar` method as an object with the keys you want to override.
+
+For example, we could have a radar chart without a point for each on piece of data by doing the following:
+
+```javascript
+new Chart(ctx).Radar(data, {
+ pointDot: false
+});
+// This will create a chart with all of the default options, merged from the global config,
+// and the Bar chart defaults but this particular instance will have `pointDot` set to false.
+```
+
+We can also change these defaults values for each Radar type that is created, this object is available at `Chart.defaults.Radar`.
+
+
+### Prototype methods
+
+#### .getPointsAtEvent( event )
+
+Calling `getPointsAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the point elements that are at that the same position of that event.
+
+```javascript
+canvas.onclick = function(evt){
+ var activePoints = myRadarChart.getPointsAtEvent(evt);
+ // => activePoints is an array of points on the canvas that are at the same position as the click event.
+};
+```
+
+This functionality may be useful for implementing DOM based tooltips, or triggering custom behaviour in your application.
+
+#### .update( )
+
+Calling `update()` on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.
+
+```javascript
+myRadarChart.datasets[0].points[2].value = 50;
+// Would update the first dataset's value of 'Sleeping' to be 50
+myRadarChart.update();
+// Calling update now animates the position of Sleeping from 90 to 50.
+```
+
+#### .addData( valuesArray, label )
+
+Calling `addData(valuesArray, label)` on your Chart instance passing an array of values for each dataset, along with a label for those points.
+
+```javascript
+// The values array passed into addData should be one for each dataset in the chart
+myRadarChart.addData([40, 60], "Dancing");
+// The new data will now animate at the end of the chart.
+```
+
+#### .removeData( )
+
+Calling `removeData()` on your Chart instance will remove the first value for all datasets on the chart.
+
+```javascript
+myRadarChart.removeData();
+// Other points will now animate to their correct positions.
+```
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/04-Polar-Area-Chart.md b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/04-Polar-Area-Chart.md
new file mode 100644
index 0000000..658da54
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/04-Polar-Area-Chart.md
@@ -0,0 +1,172 @@
+---
+title: Polar Area Chart
+anchor: polar-area-chart
+---
+### Introduction
+Polar area charts are similar to pie charts, but each segment has the same angle - the radius of the segment differs depending on the value.
+
+This type of chart is often useful when we want to show a comparison data similar to a pie chart, but also show a scale of values for context.
+
+<div class="canvas-holder">
+ <canvas width="250" height="125"></canvas>
+</div>
+
+### Example usage
+
+```javascript
+new Chart(ctx).PolarArea(data, options);
+```
+
+### Data structure
+
+```javascript
+var data = [
+ {
+ value: 300,
+ color:"#F7464A",
+ highlight: "#FF5A5E",
+ label: "Red"
+ },
+ {
+ value: 50,
+ color: "#46BFBD",
+ highlight: "#5AD3D1",
+ label: "Green"
+ },
+ {
+ value: 100,
+ color: "#FDB45C",
+ highlight: "#FFC870",
+ label: "Yellow"
+ },
+ {
+ value: 40,
+ color: "#949FB1",
+ highlight: "#A8B3C5",
+ label: "Grey"
+ },
+ {
+ value: 120,
+ color: "#4D5360",
+ highlight: "#616774",
+ label: "Dark Grey"
+ }
+
+];
+```
+As you can see, for the chart data you pass in an array of objects, with a value and a colour. The value attribute should be a number, while the color attribute should be a string. Similar to CSS, for this string you can use HEX notation, RGB, RGBA or HSL.
+
+### Chart options
+
+These are the customisation options specific to Polar Area charts. These options are merged with the [global chart configuration options](#getting-started-global-chart-configuration), and form the options of the chart.
+
+```javascript
+{
+ //Boolean - Show a backdrop to the scale label
+ scaleShowLabelBackdrop : true,
+
+ //String - The colour of the label backdrop
+ scaleBackdropColor : "rgba(255,255,255,0.75)",
+
+ // Boolean - Whether the scale should begin at zero
+ scaleBeginAtZero : true,
+
+ //Number - The backdrop padding above & below the label in pixels
+ scaleBackdropPaddingY : 2,
+
+ //Number - The backdrop padding to the side of the label in pixels
+ scaleBackdropPaddingX : 2,
+
+ //Boolean - Show line for each value in the scale
+ scaleShowLine : true,
+
+ //Boolean - Stroke a line around each segment in the chart
+ segmentShowStroke : true,
+
+ //String - The colour of the stroke on each segement.
+ segmentStrokeColor : "#fff",
+
+ //Number - The width of the stroke value in pixels
+ segmentStrokeWidth : 2,
+
+ //Number - Amount of animation steps
+ animationSteps : 100,
+
+ //String - Animation easing effect.
+ animationEasing : "easeOutBounce",
+
+ //Boolean - Whether to animate the rotation of the chart
+ animateRotate : true,
+
+ //Boolean - Whether to animate scaling the chart from the centre
+ animateScale : false,
+ {% raw %}
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
+ {% endraw %}
+}
+```
+
+You can override these for your `Chart` instance by passing a second argument into the `PolarArea` method as an object with the keys you want to override.
+
+For example, we could have a polar area chart with a black stroke on each segment like so:
+
+```javascript
+new Chart(ctx).PolarArea(data, {
+ segmentStrokeColor: "#000000"
+});
+// This will create a chart with all of the default options, merged from the global config,
+// and the PolarArea chart defaults but this particular instance will have `segmentStrokeColor` set to `"#000000"`.
+```
+
+We can also change these defaults values for each PolarArea type that is created, this object is available at `Chart.defaults.PolarArea`.
+
+### Prototype methods
+
+#### .getSegmentsAtEvent( event )
+
+Calling `getSegmentsAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the segment elements that are at that the same position of that event.
+
+```javascript
+canvas.onclick = function(evt){
+ var activePoints = myPolarAreaChart.getSegmentsAtEvent(evt);
+ // => activePoints is an array of segments on the canvas that are at the same position as the click event.
+};
+```
+
+This functionality may be useful for implementing DOM based tooltips, or triggering custom behaviour in your application.
+
+#### .update( )
+
+Calling `update()` on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.
+
+```javascript
+myPolarAreaChart.segments[1].value = 10;
+// Would update the first dataset's value of 'Green' to be 10
+myPolarAreaChart.update();
+// Calling update now animates the position of Green from 50 to 10.
+```
+
+#### .addData( segmentData, index )
+
+Calling `addData(segmentData, index)` on your Chart instance passing an object in the same format as in the constructor. There is an option second argument of 'index', this determines at what index the new segment should be inserted into the chart.
+
+```javascript
+// An object in the same format as the original data source
+myPolarAreaChart.addData({
+ value: 130,
+ color: "#B48EAD",
+ highlight: "#C69CBE",
+ label: "Purple"
+});
+// The new segment will now animate in.
+```
+
+#### .removeData( index )
+
+Calling `removeData(index)` on your Chart instance will remove segment at that particular index. If none is provided, it will default to the last segment.
+
+```javascript
+myPolarAreaChart.removeData();
+// Other segments will update to fill the empty space left.
+```
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/05-Pie-Doughnut-Chart.md b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/05-Pie-Doughnut-Chart.md
new file mode 100644
index 0000000..dd9de6f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/05-Pie-Doughnut-Chart.md
@@ -0,0 +1,158 @@
+---
+title: Pie & Doughnut Charts
+anchor: doughnut-pie-chart
+---
+###Introduction
+Pie and doughnut charts are probably the most commonly used chart there are. They are divided into segments, the arc of each segment shows the proportional value of each piece of data.
+
+They are excellent at showing the relational proportions between data.
+
+Pie and doughnut charts are effectively the same class in Chart.js, but have one different default value - their `percentageInnerCutout`. This equates what percentage of the inner should be cut out. This defaults to `0` for pie charts, and `50` for doughnuts.
+
+They are also registered under two aliases in the `Chart` core. Other than their different default value, and different alias, they are exactly the same.
+
+<div class="canvas-holder half">
+ <canvas width="250" height="125"></canvas>
+</div>
+
+<div class="canvas-holder half">
+ <canvas width="250" height="125"></canvas>
+</div>
+
+
+### Example usage
+
+```javascript
+// For a pie chart
+var myPieChart = new Chart(ctx[0]).Pie(data,options);
+
+// And for a doughnut chart
+var myDoughnutChart = new Chart(ctx[1]).Doughnut(data,options);
+```
+
+### Data structure
+
+```javascript
+var data = [
+ {
+ value: 300,
+ color:"#F7464A",
+ highlight: "#FF5A5E",
+ label: "Red"
+ },
+ {
+ value: 50,
+ color: "#46BFBD",
+ highlight: "#5AD3D1",
+ label: "Green"
+ },
+ {
+ value: 100,
+ color: "#FDB45C",
+ highlight: "#FFC870",
+ label: "Yellow"
+ }
+]
+```
+
+For a pie chart, you must pass in an array of objects with a value and a color property. The value attribute should be a number, Chart.js will total all of the numbers and calculate the relative proportion of each. The color attribute should be a string. Similar to CSS, for this string you can use HEX notation, RGB, RGBA or HSL.
+
+### Chart options
+
+These are the customisation options specific to Pie & Doughnut charts. These options are merged with the [global chart configuration options](#getting-started-global-chart-configuration), and form the options of the chart.
+
+```javascript
+{
+ //Boolean - Whether we should show a stroke on each segment
+ segmentShowStroke : true,
+
+ //String - The colour of each segment stroke
+ segmentStrokeColor : "#fff",
+
+ //Number - The width of each segment stroke
+ segmentStrokeWidth : 2,
+
+ //Number - The percentage of the chart that we cut out of the middle
+ percentageInnerCutout : 50, // This is 0 for Pie charts
+
+ //Number - Amount of animation steps
+ animationSteps : 100,
+
+ //String - Animation easing effect
+ animationEasing : "easeOutBounce",
+
+ //Boolean - Whether we animate the rotation of the Doughnut
+ animateRotate : true,
+
+ //Boolean - Whether we animate scaling the Doughnut from the centre
+ animateScale : false,
+ {% raw %}
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
+ {% endraw %}
+}
+```
+You can override these for your `Chart` instance by passing a second argument into the `Doughnut` method as an object with the keys you want to override.
+
+For example, we could have a doughnut chart that animates by scaling out from the centre like so:
+
+```javascript
+new Chart(ctx).Doughnut(data, {
+ animateScale: true
+});
+// This will create a chart with all of the default options, merged from the global config,
+// and the Doughnut chart defaults but this particular instance will have `animateScale` set to `true`.
+```
+
+We can also change these default values for each Doughnut type that is created, this object is available at `Chart.defaults.Doughnut`. Pie charts also have a clone of these defaults available to change at `Chart.defaults.Pie`, with the only difference being `percentageInnerCutout` being set to 0.
+
+### Prototype methods
+
+#### .getSegmentsAtEvent( event )
+
+Calling `getSegmentsAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the segment elements that are at the same position of that event.
+
+```javascript
+canvas.onclick = function(evt){
+ var activePoints = myDoughnutChart.getSegmentsAtEvent(evt);
+ // => activePoints is an array of segments on the canvas that are at the same position as the click event.
+};
+```
+
+This functionality may be useful for implementing DOM based tooltips, or triggering custom behaviour in your application.
+
+#### .update( )
+
+Calling `update()` on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.
+
+```javascript
+myDoughnutChart.segments[1].value = 10;
+// Would update the first dataset's value of 'Green' to be 10
+myDoughnutChart.update();
+// Calling update now animates the circumference of the segment 'Green' from 50 to 10.
+// and transitions other segment widths
+```
+
+#### .addData( segmentData, index )
+
+Calling `addData(segmentData, index)` on your Chart instance passing an object in the same format as in the constructor. There is an optional second argument of 'index', this determines at what index the new segment should be inserted into the chart.
+
+```javascript
+// An object in the same format as the original data source
+myDoughnutChart.addData({
+ value: 130,
+ color: "#B48EAD",
+ highlight: "#C69CBE",
+ label: "Purple"
+});
+// The new segment will now animate in.
+```
+
+#### .removeData( index )
+
+Calling `removeData(index)` on your Chart instance will remove segment at that particular index. If none is provided, it will default to the last segment.
+
+```javascript
+myDoughnutChart.removeData();
+// Other segments will update to fill the empty space left.
+```
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/06-Advanced.md b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/06-Advanced.md
new file mode 100644
index 0000000..f0495bf
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/06-Advanced.md
@@ -0,0 +1,185 @@
+---
+title: Advanced usage
+anchor: advanced-usage
+---
+
+
+### Prototype methods
+
+For each chart, there are a set of global prototype methods on the shared `ChartType` which you may find useful. These are available on all charts created with Chart.js, but for the examples, let's use a line chart we've made.
+
+```javascript
+// For example:
+var myLineChart = new Chart(ctx).Line(data);
+```
+
+#### .clear()
+
+Will clear the chart canvas. Used extensively internally between animation frames, but you might find it useful.
+
+```javascript
+// Will clear the canvas that myLineChart is drawn on
+myLineChart.clear();
+// => returns 'this' for chainability
+```
+
+#### .stop()
+
+Use this to stop any current animation loop. This will pause the chart during any current animation frame. Call `.render()` to re-animate.
+
+```javascript
+// Stops the charts animation loop at its current frame
+myLineChart.stop();
+// => returns 'this' for chainability
+```
+
+#### .resize()
+
+Use this to manually resize the canvas element. This is run each time the browser is resized, but you can call this method manually if you change the size of the canvas nodes container element.
+
+```javascript
+// Resizes & redraws to fill its container element
+myLineChart.resize();
+// => returns 'this' for chainability
+```
+
+#### .destroy()
+
+Use this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart.js, along with any associated event listeners attached by Chart.js.
+
+```javascript
+// Destroys a specific chart instance
+myLineChart.destroy();
+```
+
+#### .toBase64Image()
+
+This returns a base 64 encoded string of the chart in it's current state.
+
+```javascript
+myLineChart.toBase64Image();
+// => returns png data url of the image on the canvas
+```
+
+#### .generateLegend()
+
+Returns an HTML string of a legend for that chart. The template for this legend is at `legendTemplate` in the chart options.
+
+```javascript
+myLineChart.generateLegend();
+// => returns HTML string of a legend for this chart
+```
+
+### External Tooltips
+
+You can enable custom tooltips in the global or chart configuration like so:
+
+```javascript
+var myPieChart = new Chart(ctx).Pie(data, {
+ customTooltips: function(tooltip) {
+
+ // tooltip will be false if tooltip is not visible or should be hidden
+ if (!tooltip) {
+ return;
+ }
+
+ // Otherwise, tooltip will be an object with all tooltip properties like:
+
+ // tooltip.caretHeight
+ // tooltip.caretPadding
+ // tooltip.chart
+ // tooltip.cornerRadius
+ // tooltip.fillColor
+ // tooltip.font...
+ // tooltip.text
+ // tooltip.x
+ // tooltip.y
+ // etc...
+
+ };
+});
+```
+
+See files `sample/pie-customTooltips.html` and `sample/line-customTooltips.html` for examples on how to get started.
+
+
+### Writing new chart types
+
+Chart.js 1.0 has been rewritten to provide a platform for developers to create their own custom chart types, and be able to share and utilise them through the Chart.js API.
+
+The format is relatively simple, there are a set of utility helper methods under `Chart.helpers`, including things such as looping over collections, requesting animation frames, and easing equations.
+
+On top of this, there are also some simple base classes of Chart elements, these all extend from `Chart.Element`, and include things such as points, bars and scales.
+
+```javascript
+Chart.Type.extend({
+ // Passing in a name registers this chart in the Chart namespace
+ name: "Scatter",
+ // Providing a defaults will also register the deafults in the chart namespace
+ defaults : {
+ options: "Here",
+ available: "at this.options"
+ },
+ // Initialize is fired when the chart is initialized - Data is passed in as a parameter
+ // Config is automatically merged by the core of Chart.js, and is available at this.options
+ initialize: function(data){
+ this.chart.ctx // The drawing context for this chart
+ this.chart.canvas // the canvas node for this chart
+ },
+ // Used to draw something on the canvas
+ draw: function() {
+ }
+});
+
+// Now we can create a new instance of our chart, using the Chart.js API
+new Chart(ctx).Scatter(data);
+// initialize is now run
+```
+
+### Extending existing chart types
+
+We can also extend existing chart types, and expose them to the API in the same way. Let's say for example, we might want to run some more code when we initialize every Line chart.
+
+```javascript
+// Notice now we're extending the particular Line chart type, rather than the base class.
+Chart.types.Line.extend({
+ // Passing in a name registers this chart in the Chart namespace in the same way
+ name: "LineAlt",
+ initialize: function(data){
+ console.log('My Line chart extension');
+ Chart.types.Line.prototype.initialize.apply(this, arguments);
+ }
+});
+
+// Creates a line chart in the same way
+new Chart(ctx).LineAlt(data);
+// but this logs 'My Line chart extension' in the console.
+```
+
+### Community extensions
+
+- <a href="https://github.com/Regaddi/Chart.StackedBar.js" target"_blank">Stacked Bar Chart</a> by <a href="https://twitter.com/Regaddi" target="_blank">@Regaddi</a>
+- <a href="https://github.com/CAYdenberg/Chart.js" target"_blank">Error bars (bar and line charts)</a> by <a href="https://twitter.com/CAYdenberg" target="_blank">@CAYdenberg</a>
+
+### Creating custom builds
+
+Chart.js uses <a href="http://gulpjs.com/" target="_blank">gulp</a> to build the library into a single JavaScript file. We can use this same build script with custom parameters in order to build a custom version.
+
+Firstly, we need to ensure development dependencies are installed. With node and npm installed, after cloning the Chart.js repo to a local directory, and navigating to that directory in the command line, we can run the following:
+
+```bash
+npm install
+npm install -g gulp
+```
+
+This will install the local development dependencies for Chart.js, along with a CLI for the JavaScript task runner <a href="http://gulpjs.com/" target="_blank">gulp</a>.
+
+Now, we can run the `gulp build` task, and pass in a comma seperated list of types as an argument to build a custom version of Chart.js with only specified chart types.
+
+Here we will create a version of Chart.js with only Line, Radar and Bar charts included:
+
+```bash
+gulp build --types=Line,Radar,Bar
+```
+
+This will output to the `/custom` directory, and write two files, Chart.js, and Chart.min.js with only those chart types included.
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/07-Notes.md b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/07-Notes.md
new file mode 100644
index 0000000..8ba5a59
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/docs/07-Notes.md
@@ -0,0 +1,42 @@
+---
+title: Notes
+anchor: notes
+---
+
+### Browser support
+Browser support for the canvas element is available in all modern & major mobile browsers <a href="http://caniuse.com/canvas" target="_blank">(caniuse.com/canvas)</a>.
+
+For IE8 & below, I would recommend using the polyfill ExplorerCanvas - available at <a href="https://code.google.com/p/explorercanvas/" target="_blank">https://code.google.com/p/explorercanvas/</a>. It falls back to Internet explorer's format VML when canvas support is not available. Example use:
+
+```html
+<head>
+ <!--[if lte IE 8]>
+ <script src="excanvas.js"></script>
+ <![endif]-->
+</head>
+```
+
+Usually I would recommend feature detection to choose whether or not to load a polyfill, rather than IE conditional comments, however in this case, VML is a Microsoft proprietary format, so it will only work in IE.
+
+Some important points to note in my experience using ExplorerCanvas as a fallback.
+
+- Initialise charts on load rather than DOMContentReady when using the library, as sometimes a race condition will occur, and it will result in an error when trying to get the 2d context of a canvas.
+- New VML DOM elements are being created for each animation frame and there is no hardware acceleration. As a result animation is usually slow and jerky, with flashing text. It is a good idea to dynamically turn off animation based on canvas support. I recommend using the excellent <a href="http://modernizr.com/" target="_blank">Modernizr</a> to do this.
+- When declaring fonts, the library explorercanvas requires the font name to be in single quotes inside the string. For example, instead of your scaleFontFamily property being simply "Arial", explorercanvas support, use "'Arial'" instead. Chart.js does this for default values.
+
+### Bugs & issues
+
+Please report these on the GitHub page - at <a href="https://github.com/nnnick/Chart.js" target="_blank">github.com/nnnick/Chart.js</a>. If you could include a link to a simple <a href="http://jsbin.com/" target="_blank">jsbin</a> or similar to demonstrate the issue, that'd be really helpful.
+
+
+### Contributing
+New contributions to the library are welcome, just a couple of guidelines:
+
+- Tabs for indentation, not spaces please.
+- Please ensure you're changing the individual files in `/src`, not the concatenated output in the `Chart.js` file in the root of the repo.
+- Please check that your code will pass `jshint` code standards, `gulp jshint` will run this for you.
+- Please keep pull requests concise, and document new functionality in the relevant `.md` file.
+- Consider whether your changes are useful for all users, or if creating a Chart.js extension would be more appropriate.
+
+### License
+Chart.js is open source and available under the <a href="http://opensource.org/licenses/MIT" target="_blank">MIT license</a>.
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/gulpfile.js b/xos-apps/auto-scale/gui/src/vendor/Chart.js/gulpfile.js
new file mode 100644
index 0000000..e8fe1c7
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/gulpfile.js
@@ -0,0 +1,137 @@
+var gulp = require('gulp'),
+ concat = require('gulp-concat'),
+ uglify = require('gulp-uglify'),
+ util = require('gulp-util'),
+ jshint = require('gulp-jshint'),
+ size = require('gulp-size'),
+ connect = require('gulp-connect'),
+ replace = require('gulp-replace'),
+ htmlv = require('gulp-html-validator'),
+ inquirer = require('inquirer'),
+ semver = require('semver'),
+ exec = require('child_process').exec,
+ fs = require('fs'),
+ package = require('./package.json'),
+ bower = require('./bower.json');
+
+var srcDir = './src/';
+/*
+ * Usage : gulp build --types=Bar,Line,Doughnut
+ * Output: - A built Chart.js file with Core and types Bar, Line and Doughnut concatenated together
+ * - A minified version of this code, in Chart.min.js
+ */
+
+gulp.task('build', function(){
+
+ // Default to all of the chart types, with Chart.Core first
+ var srcFiles = [FileName('Core')],
+ isCustom = !!(util.env.types),
+ outputDir = (isCustom) ? 'custom' : '.';
+ if (isCustom){
+ util.env.types.split(',').forEach(function(type){ return srcFiles.push(FileName(type))});
+ }
+ else{
+ // Seems gulp-concat remove duplicates - nice!
+ // So we can use this to sort out dependency order - aka include Core first!
+ srcFiles.push(srcDir+'*');
+ }
+
+ return gulp.src(srcFiles)
+ .pipe(concat('Chart.js'))
+ .pipe(replace('{{ version }}', package.version))
+ .pipe(gulp.dest(outputDir))
+ .pipe(uglify({preserveComments:'some'}))
+ .pipe(concat('Chart.min.js'))
+ .pipe(gulp.dest(outputDir));
+
+ function FileName(moduleName){
+ return srcDir+'Chart.'+moduleName+'.js';
+ };
+});
+
+/*
+ * Usage : gulp bump
+ * Prompts: Version increment to bump
+ * Output: - New version number written into package.json & bower.json
+ */
+
+gulp.task('bump', function(complete){
+ util.log('Current version:', util.colors.cyan(package.version));
+ var choices = ['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'].map(function(versionType){
+ return versionType + ' (v' + semver.inc(package.version, versionType) + ')';
+ });
+ inquirer.prompt({
+ type: 'list',
+ name: 'version',
+ message: 'What version update would you like?',
+ choices: choices
+ }, function(res){
+ var increment = res.version.split(' ')[0],
+ newVersion = semver.inc(package.version, increment);
+
+ // Set the new versions into the bower/package object
+ package.version = newVersion;
+ bower.version = newVersion;
+
+ // Write these to their own files, then build the output
+ fs.writeFileSync('package.json', JSON.stringify(package, null, 2));
+ fs.writeFileSync('bower.json', JSON.stringify(bower, null, 2));
+
+ complete();
+ });
+});
+
+gulp.task('release', ['build'], function(){
+ exec('git tag -a v' + package.version);
+});
+
+gulp.task('jshint', function(){
+ return gulp.src(srcDir + '*.js')
+ .pipe(jshint())
+ .pipe(jshint.reporter('default'));
+});
+
+gulp.task('valid', function(){
+ return gulp.src('samples/*.html')
+ .pipe(htmlv());
+});
+
+gulp.task('library-size', function(){
+ return gulp.src('Chart.min.js')
+ .pipe(size({
+ gzip: true
+ }));
+});
+
+gulp.task('module-sizes', function(){
+ return gulp.src(srcDir + '*.js')
+ .pipe(uglify({preserveComments:'some'}))
+ .pipe(size({
+ showFiles: true,
+ gzip: true
+ }))
+});
+
+gulp.task('watch', function(){
+ gulp.watch('./src/*', ['build']);
+});
+
+gulp.task('test', ['jshint', 'valid']);
+
+gulp.task('size', ['library-size', 'module-sizes']);
+
+gulp.task('default', ['build', 'watch']);
+
+gulp.task('server', function(){
+ connect.server({
+ port: 8000
+ });
+});
+
+// Convenience task for opening the project straight from the command line
+gulp.task('_open', function(){
+ exec('open http://localhost:8000');
+ exec('subl .');
+});
+
+gulp.task('dev', ['server', 'default']);
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/package.json b/xos-apps/auto-scale/gui/src/vendor/Chart.js/package.json
new file mode 100644
index 0000000..9ac4a0e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/package.json
@@ -0,0 +1,28 @@
+{
+ "name": "chart.js",
+ "homepage": "http://www.chartjs.org",
+ "description": "Simple HTML5 charts using the canvas element.",
+ "version": "1.0.2",
+ "main": "Chart.js",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/nnnick/Chart.js.git"
+ },
+ "dependences": {},
+ "devDependencies": {
+ "gulp": "3.5.x",
+ "gulp-concat": "~2.1.x",
+ "gulp-connect": "~2.0.5",
+ "gulp-jshint": "~1.5.1",
+ "gulp-replace": "^0.4.0",
+ "gulp-size": "~0.4.0",
+ "gulp-uglify": "~0.2.x",
+ "gulp-util": "~2.2.x",
+ "gulp-html-validator": "^0.0.2",
+ "inquirer": "^0.5.1",
+ "semver": "^3.0.1"
+ },
+ "spm": {
+ "main": "Chart.js"
+ }
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/bar.html b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/bar.html
new file mode 100644
index 0000000..5bf4b5b
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/bar.html
@@ -0,0 +1,45 @@
+<!doctype html>
+<html>
+ <head>
+ <title>Bar Chart</title>
+ <script src="../Chart.js"></script>
+ </head>
+ <body>
+ <div style="width: 50%">
+ <canvas id="canvas" height="450" width="600"></canvas>
+ </div>
+
+
+ <script>
+ var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
+
+ var barChartData = {
+ labels : ["January","February","March","April","May","June","July"],
+ datasets : [
+ {
+ fillColor : "rgba(220,220,220,0.5)",
+ strokeColor : "rgba(220,220,220,0.8)",
+ highlightFill: "rgba(220,220,220,0.75)",
+ highlightStroke: "rgba(220,220,220,1)",
+ data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
+ },
+ {
+ fillColor : "rgba(151,187,205,0.5)",
+ strokeColor : "rgba(151,187,205,0.8)",
+ highlightFill : "rgba(151,187,205,0.75)",
+ highlightStroke : "rgba(151,187,205,1)",
+ data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
+ }
+ ]
+
+ }
+ window.onload = function(){
+ var ctx = document.getElementById("canvas").getContext("2d");
+ window.myBar = new Chart(ctx).Bar(barChartData, {
+ responsive : true
+ });
+ }
+
+ </script>
+ </body>
+</html>
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/doughnut.html b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/doughnut.html
new file mode 100644
index 0000000..fdf7539
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/doughnut.html
@@ -0,0 +1,67 @@
+<!doctype html>
+<html>
+ <head>
+ <title>Doughnut Chart</title>
+ <script src="../Chart.js"></script>
+ <style>
+ body{
+ padding: 0;
+ margin: 0;
+ }
+ #canvas-holder{
+ width:30%;
+ }
+ </style>
+ </head>
+ <body>
+ <div id="canvas-holder">
+ <canvas id="chart-area" width="500" height="500"/>
+ </div>
+
+
+ <script>
+
+ var doughnutData = [
+ {
+ value: 300,
+ color:"#F7464A",
+ highlight: "#FF5A5E",
+ label: "Red"
+ },
+ {
+ value: 50,
+ color: "#46BFBD",
+ highlight: "#5AD3D1",
+ label: "Green"
+ },
+ {
+ value: 100,
+ color: "#FDB45C",
+ highlight: "#FFC870",
+ label: "Yellow"
+ },
+ {
+ value: 40,
+ color: "#949FB1",
+ highlight: "#A8B3C5",
+ label: "Grey"
+ },
+ {
+ value: 120,
+ color: "#4D5360",
+ highlight: "#616774",
+ label: "Dark Grey"
+ }
+
+ ];
+
+ window.onload = function(){
+ var ctx = document.getElementById("chart-area").getContext("2d");
+ window.myDoughnut = new Chart(ctx).Doughnut(doughnutData, {responsive : true});
+ };
+
+
+
+ </script>
+ </body>
+</html>
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/line-customTooltips.html b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/line-customTooltips.html
new file mode 100644
index 0000000..4dc46e1
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/line-customTooltips.html
@@ -0,0 +1,129 @@
+<!doctype html>
+<html>
+
+<head>
+ <title>Line Chart with Custom Tooltips</title>
+ <script src="../Chart.js"></script>
+ <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
+
+ <style>
+ #canvas-holder1 {
+ width: 300px;
+ margin: 20px auto;
+ }
+ #canvas-holder2 {
+ width: 50%;
+ margin: 20px 25%;
+ }
+ #chartjs-tooltip {
+ opacity: 1;
+ position: absolute;
+ background: rgba(0, 0, 0, .7);
+ color: white;
+ padding: 3px;
+ border-radius: 3px;
+ -webkit-transition: all .1s ease;
+ transition: all .1s ease;
+ pointer-events: none;
+ -webkit-transform: translate(-50%, 0);
+ transform: translate(-50%, 0);
+ }
+ .chartjs-tooltip-key{
+ display:inline-block;
+ width:10px;
+ height:10px;
+ }
+ </style>
+</head>
+
+<body>
+ <div id="canvas-holder1">
+ <canvas id="chart1" width="300" height="30" />
+ </div>
+ <div id="canvas-holder2">
+ <canvas id="chart2" width="450" height="600" />
+ </div>
+
+ <div id="chartjs-tooltip"></div>
+
+
+ <script>
+
+ Chart.defaults.global.pointHitDetectionRadius = 1;
+ Chart.defaults.global.customTooltips = function(tooltip) {
+
+ var tooltipEl = $('#chartjs-tooltip');
+
+ if (!tooltip) {
+ tooltipEl.css({
+ opacity: 0
+ });
+ return;
+ }
+
+ tooltipEl.removeClass('above below');
+ tooltipEl.addClass(tooltip.yAlign);
+
+ var innerHtml = '';
+ for (var i = tooltip.labels.length - 1; i >= 0; i--) {
+ innerHtml += [
+ '<div class="chartjs-tooltip-section">',
+ ' <span class="chartjs-tooltip-key" style="background-color:' + tooltip.legendColors[i].fill + '"></span>',
+ ' <span class="chartjs-tooltip-value">' + tooltip.labels[i] + '</span>',
+ '</div>'
+ ].join('');
+ }
+ tooltipEl.html(innerHtml);
+
+ tooltipEl.css({
+ opacity: 1,
+ left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
+ top: tooltip.chart.canvas.offsetTop + tooltip.y + 'px',
+ fontFamily: tooltip.fontFamily,
+ fontSize: tooltip.fontSize,
+ fontStyle: tooltip.fontStyle,
+ });
+ };
+ var randomScalingFactor = function() {
+ return Math.round(Math.random() * 100);
+ };
+ var lineChartData = {
+ labels: ["January", "February", "March", "April", "May", "June", "July"],
+ datasets: [{
+ label: "My First dataset",
+ fillColor: "rgba(220,220,220,0.2)",
+ strokeColor: "rgba(220,220,220,1)",
+ pointColor: "rgba(220,220,220,1)",
+ pointStrokeColor: "#fff",
+ pointHighlightFill: "#fff",
+ pointHighlightStroke: "rgba(220,220,220,1)",
+ data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
+ }, {
+ label: "My Second dataset",
+ fillColor: "rgba(151,187,205,0.2)",
+ strokeColor: "rgba(151,187,205,1)",
+ pointColor: "rgba(151,187,205,1)",
+ pointStrokeColor: "#fff",
+ pointHighlightFill: "#fff",
+ pointHighlightStroke: "rgba(151,187,205,1)",
+ data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
+ }]
+ };
+
+ window.onload = function() {
+ var ctx1 = document.getElementById("chart1").getContext("2d");
+ window.myLine = new Chart(ctx1).Line(lineChartData, {
+ showScale: false,
+ pointDot : true,
+ responsive: true
+ });
+
+ var ctx2 = document.getElementById("chart2").getContext("2d");
+ window.myLine = new Chart(ctx2).Line(lineChartData, {
+ responsive: true
+ });
+ };
+ </script>
+</body>
+
+</html>
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/line.html b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/line.html
new file mode 100644
index 0000000..ccd0dad
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/line.html
@@ -0,0 +1,54 @@
+<!doctype html>
+<html>
+ <head>
+ <title>Line Chart</title>
+ <script src="../Chart.js"></script>
+ </head>
+ <body>
+ <div style="width:30%">
+ <div>
+ <canvas id="canvas" height="450" width="600"></canvas>
+ </div>
+ </div>
+
+
+ <script>
+ var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
+ var lineChartData = {
+ labels : ["January","February","March","April","May","June","July"],
+ datasets : [
+ {
+ label: "My First dataset",
+ fillColor : "rgba(220,220,220,0.2)",
+ strokeColor : "rgba(220,220,220,1)",
+ pointColor : "rgba(220,220,220,1)",
+ pointStrokeColor : "#fff",
+ pointHighlightFill : "#fff",
+ pointHighlightStroke : "rgba(220,220,220,1)",
+ data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
+ },
+ {
+ label: "My Second dataset",
+ fillColor : "rgba(151,187,205,0.2)",
+ strokeColor : "rgba(151,187,205,1)",
+ pointColor : "rgba(151,187,205,1)",
+ pointStrokeColor : "#fff",
+ pointHighlightFill : "#fff",
+ pointHighlightStroke : "rgba(151,187,205,1)",
+ data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
+ }
+ ]
+
+ }
+
+ window.onload = function(){
+ var ctx = document.getElementById("canvas").getContext("2d");
+ window.myLine = new Chart(ctx).Line(lineChartData, {
+ responsive: true
+ });
+ }
+
+
+ </script>
+ </body>
+</html>
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/pie-customTooltips.html b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/pie-customTooltips.html
new file mode 100644
index 0000000..732317d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/pie-customTooltips.html
@@ -0,0 +1,156 @@
+<!doctype html>
+<html>
+
+<head>
+ <title>Pie Chart with Custom Tooltips</title>
+ <script src="../Chart.js"></script>
+ <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
+
+ <style>
+ #canvas-holder {
+ width: 100%;
+ margin-top: 50px;
+ text-align: center;
+ }
+ #chartjs-tooltip {
+ opacity: 1;
+ position: absolute;
+ background: rgba(0, 0, 0, .7);
+ color: white;
+ padding: 3px;
+ border-radius: 3px;
+ -webkit-transition: all .1s ease;
+ transition: all .1s ease;
+ pointer-events: none;
+ -webkit-transform: translate(-50%, 0);
+ transform: translate(-50%, 0);
+ }
+ #chartjs-tooltip.below {
+ -webkit-transform: translate(-50%, 0);
+ transform: translate(-50%, 0);
+ }
+ #chartjs-tooltip.below:before {
+ border: solid;
+ border-color: #111 transparent;
+ border-color: rgba(0, 0, 0, .8) transparent;
+ border-width: 0 8px 8px 8px;
+ bottom: 1em;
+ content: "";
+ display: block;
+ left: 50%;
+ position: absolute;
+ z-index: 99;
+ -webkit-transform: translate(-50%, -100%);
+ transform: translate(-50%, -100%);
+ }
+ #chartjs-tooltip.above {
+ -webkit-transform: translate(-50%, -100%);
+ transform: translate(-50%, -100%);
+ }
+ #chartjs-tooltip.above:before {
+ border: solid;
+ border-color: #111 transparent;
+ border-color: rgba(0, 0, 0, .8) transparent;
+ border-width: 8px 8px 0 8px;
+ bottom: 1em;
+ content: "";
+ display: block;
+ left: 50%;
+ top: 100%;
+ position: absolute;
+ z-index: 99;
+ -webkit-transform: translate(-50%, 0);
+ transform: translate(-50%, 0);
+ }
+ </style>
+</head>
+
+<body>
+ <div id="canvas-holder">
+ <canvas id="chart-area1" width="50" height="50" />
+ </div>
+ <div id="canvas-holder">
+ <canvas id="chart-area2" width="300" height="300" />
+ </div>
+
+ <div id="chartjs-tooltip"></div>
+
+
+ <script>
+ Chart.defaults.global.customTooltips = function(tooltip) {
+
+ // Tooltip Element
+ var tooltipEl = $('#chartjs-tooltip');
+
+ // Hide if no tooltip
+ if (!tooltip) {
+ tooltipEl.css({
+ opacity: 0
+ });
+ return;
+ }
+
+ // Set caret Position
+ tooltipEl.removeClass('above below');
+ tooltipEl.addClass(tooltip.yAlign);
+
+ // Set Text
+ tooltipEl.html(tooltip.text);
+
+ // Find Y Location on page
+ var top;
+ if (tooltip.yAlign == 'above') {
+ top = tooltip.y - tooltip.caretHeight - tooltip.caretPadding;
+ } else {
+ top = tooltip.y + tooltip.caretHeight + tooltip.caretPadding;
+ }
+
+ // Display, position, and set styles for font
+ tooltipEl.css({
+ opacity: 1,
+ left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
+ top: tooltip.chart.canvas.offsetTop + top + 'px',
+ fontFamily: tooltip.fontFamily,
+ fontSize: tooltip.fontSize,
+ fontStyle: tooltip.fontStyle,
+ });
+ };
+
+ var pieData = [{
+ value: 300,
+ color: "#F7464A",
+ highlight: "#FF5A5E",
+ label: "Red"
+ }, {
+ value: 50,
+ color: "#46BFBD",
+ highlight: "#5AD3D1",
+ label: "Green"
+ }, {
+ value: 100,
+ color: "#FDB45C",
+ highlight: "#FFC870",
+ label: "Yellow"
+ }, {
+ value: 40,
+ color: "#949FB1",
+ highlight: "#A8B3C5",
+ label: "Grey"
+ }, {
+ value: 120,
+ color: "#4D5360",
+ highlight: "#616774",
+ label: "Dark Grey"
+ }];
+
+ window.onload = function() {
+ var ctx1 = document.getElementById("chart-area1").getContext("2d");
+ window.myPie = new Chart(ctx1).Pie(pieData);
+
+ var ctx2 = document.getElementById("chart-area2").getContext("2d");
+ window.myPie = new Chart(ctx2).Pie(pieData);
+ };
+ </script>
+</body>
+
+</html>
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/pie.html b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/pie.html
new file mode 100644
index 0000000..255a499
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/pie.html
@@ -0,0 +1,58 @@
+<!doctype html>
+<html>
+ <head>
+ <title>Pie Chart</title>
+ <script src="../Chart.js"></script>
+ </head>
+ <body>
+ <div id="canvas-holder">
+ <canvas id="chart-area" width="300" height="300"/>
+ </div>
+
+
+ <script>
+
+ var pieData = [
+ {
+ value: 300,
+ color:"#F7464A",
+ highlight: "#FF5A5E",
+ label: "Red"
+ },
+ {
+ value: 50,
+ color: "#46BFBD",
+ highlight: "#5AD3D1",
+ label: "Green"
+ },
+ {
+ value: 100,
+ color: "#FDB45C",
+ highlight: "#FFC870",
+ label: "Yellow"
+ },
+ {
+ value: 40,
+ color: "#949FB1",
+ highlight: "#A8B3C5",
+ label: "Grey"
+ },
+ {
+ value: 120,
+ color: "#4D5360",
+ highlight: "#616774",
+ label: "Dark Grey"
+ }
+
+ ];
+
+ window.onload = function(){
+ var ctx = document.getElementById("chart-area").getContext("2d");
+ window.myPie = new Chart(ctx).Pie(pieData);
+ };
+
+
+
+ </script>
+ </body>
+</html>
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/polar-area.html b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/polar-area.html
new file mode 100644
index 0000000..d3d3f01
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/polar-area.html
@@ -0,0 +1,60 @@
+<!doctype html>
+<html>
+ <head>
+ <title>Polar Area Chart</title>
+ <script src="../Chart.js"></script>
+ </head>
+ <body>
+ <div id="canvas-holder" style="width:30%">
+ <canvas id="chart-area" width="300" height="300"/>
+ </div>
+
+
+ <script>
+
+ var polarData = [
+ {
+ value: 300,
+ color:"#F7464A",
+ highlight: "#FF5A5E",
+ label: "Red"
+ },
+ {
+ value: 50,
+ color: "#46BFBD",
+ highlight: "#5AD3D1",
+ label: "Green"
+ },
+ {
+ value: 100,
+ color: "#FDB45C",
+ highlight: "#FFC870",
+ label: "Yellow"
+ },
+ {
+ value: 40,
+ color: "#949FB1",
+ highlight: "#A8B3C5",
+ label: "Grey"
+ },
+ {
+ value: 120,
+ color: "#4D5360",
+ highlight: "#616774",
+ label: "Dark Grey"
+ }
+
+ ];
+
+ window.onload = function(){
+ var ctx = document.getElementById("chart-area").getContext("2d");
+ window.myPolarArea = new Chart(ctx).PolarArea(polarData, {
+ responsive:true
+ });
+ };
+
+
+
+ </script>
+ </body>
+</html>
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/radar.html b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/radar.html
new file mode 100644
index 0000000..6a04f87
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/samples/radar.html
@@ -0,0 +1,53 @@
+<!doctype html>
+<html>
+ <head>
+ <title>Radar Chart</title>
+ <script src="../Chart.js"></script>
+ <meta name = "viewport" content = "initial-scale = 1, user-scalable = no">
+ <style>
+ canvas{
+ }
+ </style>
+ </head>
+ <body>
+ <div style="width:30%">
+ <canvas id="canvas" height="450" width="450"></canvas>
+ </div>
+
+
+ <script>
+ var radarChartData = {
+ labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],
+ datasets: [
+ {
+ label: "My First dataset",
+ fillColor: "rgba(220,220,220,0.2)",
+ strokeColor: "rgba(220,220,220,1)",
+ pointColor: "rgba(220,220,220,1)",
+ pointStrokeColor: "#fff",
+ pointHighlightFill: "#fff",
+ pointHighlightStroke: "rgba(220,220,220,1)",
+ data: [65,59,90,81,56,55,40]
+ },
+ {
+ label: "My Second dataset",
+ fillColor: "rgba(151,187,205,0.2)",
+ strokeColor: "rgba(151,187,205,1)",
+ pointColor: "rgba(151,187,205,1)",
+ pointStrokeColor: "#fff",
+ pointHighlightFill: "#fff",
+ pointHighlightStroke: "rgba(151,187,205,1)",
+ data: [28,48,40,19,96,27,100]
+ }
+ ]
+ };
+
+ window.onload = function(){
+ window.myRadar = new Chart(document.getElementById("canvas").getContext("2d")).Radar(radarChartData, {
+ responsive: true
+ });
+ }
+
+ </script>
+ </body>
+</html>
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Bar.js b/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Bar.js
new file mode 100644
index 0000000..87fb26d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Bar.js
@@ -0,0 +1,302 @@
+(function(){
+ "use strict";
+
+ var root = this,
+ Chart = root.Chart,
+ helpers = Chart.helpers;
+
+
+ var defaultConfig = {
+ //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
+ scaleBeginAtZero : true,
+
+ //Boolean - Whether grid lines are shown across the chart
+ scaleShowGridLines : true,
+
+ //String - Colour of the grid lines
+ scaleGridLineColor : "rgba(0,0,0,.05)",
+
+ //Number - Width of the grid lines
+ scaleGridLineWidth : 1,
+
+ //Boolean - Whether to show horizontal lines (except X axis)
+ scaleShowHorizontalLines: true,
+
+ //Boolean - Whether to show vertical lines (except Y axis)
+ scaleShowVerticalLines: true,
+
+ //Boolean - If there is a stroke on each bar
+ barShowStroke : true,
+
+ //Number - Pixel width of the bar stroke
+ barStrokeWidth : 2,
+
+ //Number - Spacing between each of the X value sets
+ barValueSpacing : 5,
+
+ //Number - Spacing between data sets within X values
+ barDatasetSpacing : 1,
+
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
+
+ };
+
+
+ Chart.Type.extend({
+ name: "Bar",
+ defaults : defaultConfig,
+ initialize: function(data){
+
+ //Expose options as a scope variable here so we can access it in the ScaleClass
+ var options = this.options;
+
+ this.ScaleClass = Chart.Scale.extend({
+ offsetGridLines : true,
+ calculateBarX : function(datasetCount, datasetIndex, barIndex){
+ //Reusable method for calculating the xPosition of a given bar based on datasetIndex & width of the bar
+ var xWidth = this.calculateBaseWidth(),
+ xAbsolute = this.calculateX(barIndex) - (xWidth/2),
+ barWidth = this.calculateBarWidth(datasetCount);
+
+ return xAbsolute + (barWidth * datasetIndex) + (datasetIndex * options.barDatasetSpacing) + barWidth/2;
+ },
+ calculateBaseWidth : function(){
+ return (this.calculateX(1) - this.calculateX(0)) - (2*options.barValueSpacing);
+ },
+ calculateBarWidth : function(datasetCount){
+ //The padding between datasets is to the right of each bar, providing that there are more than 1 dataset
+ var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing);
+
+ return (baseWidth / datasetCount);
+ }
+ });
+
+ this.datasets = [];
+
+ //Set up tooltip events on the chart
+ if (this.options.showTooltips){
+ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
+ var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : [];
+
+ this.eachBars(function(bar){
+ bar.restore(['fillColor', 'strokeColor']);
+ });
+ helpers.each(activeBars, function(activeBar){
+ activeBar.fillColor = activeBar.highlightFill;
+ activeBar.strokeColor = activeBar.highlightStroke;
+ });
+ this.showTooltip(activeBars);
+ });
+ }
+
+ //Declare the extension of the default point, to cater for the options passed in to the constructor
+ this.BarClass = Chart.Rectangle.extend({
+ strokeWidth : this.options.barStrokeWidth,
+ showStroke : this.options.barShowStroke,
+ ctx : this.chart.ctx
+ });
+
+ //Iterate through each of the datasets, and build this into a property of the chart
+ helpers.each(data.datasets,function(dataset,datasetIndex){
+
+ var datasetObject = {
+ label : dataset.label || null,
+ fillColor : dataset.fillColor,
+ strokeColor : dataset.strokeColor,
+ bars : []
+ };
+
+ this.datasets.push(datasetObject);
+
+ helpers.each(dataset.data,function(dataPoint,index){
+ //Add a new point for each piece of data, passing any required data to draw.
+ datasetObject.bars.push(new this.BarClass({
+ value : dataPoint,
+ label : data.labels[index],
+ datasetLabel: dataset.label,
+ strokeColor : dataset.strokeColor,
+ fillColor : dataset.fillColor,
+ highlightFill : dataset.highlightFill || dataset.fillColor,
+ highlightStroke : dataset.highlightStroke || dataset.strokeColor
+ }));
+ },this);
+
+ },this);
+
+ this.buildScale(data.labels);
+
+ this.BarClass.prototype.base = this.scale.endPoint;
+
+ this.eachBars(function(bar, index, datasetIndex){
+ helpers.extend(bar, {
+ width : this.scale.calculateBarWidth(this.datasets.length),
+ x: this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
+ y: this.scale.endPoint
+ });
+ bar.save();
+ }, this);
+
+ this.render();
+ },
+ update : function(){
+ this.scale.update();
+ // Reset any highlight colours before updating.
+ helpers.each(this.activeElements, function(activeElement){
+ activeElement.restore(['fillColor', 'strokeColor']);
+ });
+
+ this.eachBars(function(bar){
+ bar.save();
+ });
+ this.render();
+ },
+ eachBars : function(callback){
+ helpers.each(this.datasets,function(dataset, datasetIndex){
+ helpers.each(dataset.bars, callback, this, datasetIndex);
+ },this);
+ },
+ getBarsAtEvent : function(e){
+ var barsArray = [],
+ eventPosition = helpers.getRelativePosition(e),
+ datasetIterator = function(dataset){
+ barsArray.push(dataset.bars[barIndex]);
+ },
+ barIndex;
+
+ for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) {
+ for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) {
+ if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){
+ helpers.each(this.datasets, datasetIterator);
+ return barsArray;
+ }
+ }
+ }
+
+ return barsArray;
+ },
+ buildScale : function(labels){
+ var self = this;
+
+ var dataTotal = function(){
+ var values = [];
+ self.eachBars(function(bar){
+ values.push(bar.value);
+ });
+ return values;
+ };
+
+ var scaleOptions = {
+ templateString : this.options.scaleLabel,
+ height : this.chart.height,
+ width : this.chart.width,
+ ctx : this.chart.ctx,
+ textColor : this.options.scaleFontColor,
+ fontSize : this.options.scaleFontSize,
+ fontStyle : this.options.scaleFontStyle,
+ fontFamily : this.options.scaleFontFamily,
+ valuesCount : labels.length,
+ beginAtZero : this.options.scaleBeginAtZero,
+ integersOnly : this.options.scaleIntegersOnly,
+ calculateYRange: function(currentHeight){
+ var updatedRanges = helpers.calculateScaleRange(
+ dataTotal(),
+ currentHeight,
+ this.fontSize,
+ this.beginAtZero,
+ this.integersOnly
+ );
+ helpers.extend(this, updatedRanges);
+ },
+ xLabels : labels,
+ font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
+ lineWidth : this.options.scaleLineWidth,
+ lineColor : this.options.scaleLineColor,
+ showHorizontalLines : this.options.scaleShowHorizontalLines,
+ showVerticalLines : this.options.scaleShowVerticalLines,
+ gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
+ gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
+ padding : (this.options.showScale) ? 0 : (this.options.barShowStroke) ? this.options.barStrokeWidth : 0,
+ showLabels : this.options.scaleShowLabels,
+ display : this.options.showScale
+ };
+
+ if (this.options.scaleOverride){
+ helpers.extend(scaleOptions, {
+ calculateYRange: helpers.noop,
+ steps: this.options.scaleSteps,
+ stepValue: this.options.scaleStepWidth,
+ min: this.options.scaleStartValue,
+ max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
+ });
+ }
+
+ this.scale = new this.ScaleClass(scaleOptions);
+ },
+ addData : function(valuesArray,label){
+ //Map the values array for each of the datasets
+ helpers.each(valuesArray,function(value,datasetIndex){
+ //Add a new point for each piece of data, passing any required data to draw.
+ this.datasets[datasetIndex].bars.push(new this.BarClass({
+ value : value,
+ label : label,
+ x: this.scale.calculateBarX(this.datasets.length, datasetIndex, this.scale.valuesCount+1),
+ y: this.scale.endPoint,
+ width : this.scale.calculateBarWidth(this.datasets.length),
+ base : this.scale.endPoint,
+ strokeColor : this.datasets[datasetIndex].strokeColor,
+ fillColor : this.datasets[datasetIndex].fillColor
+ }));
+ },this);
+
+ this.scale.addXLabel(label);
+ //Then re-render the chart.
+ this.update();
+ },
+ removeData : function(){
+ this.scale.removeXLabel();
+ //Then re-render the chart.
+ helpers.each(this.datasets,function(dataset){
+ dataset.bars.shift();
+ },this);
+ this.update();
+ },
+ reflow : function(){
+ helpers.extend(this.BarClass.prototype,{
+ y: this.scale.endPoint,
+ base : this.scale.endPoint
+ });
+ var newScaleProps = helpers.extend({
+ height : this.chart.height,
+ width : this.chart.width
+ });
+ this.scale.update(newScaleProps);
+ },
+ draw : function(ease){
+ var easingDecimal = ease || 1;
+ this.clear();
+
+ var ctx = this.chart.ctx;
+
+ this.scale.draw(easingDecimal);
+
+ //Draw all the bars for each dataset
+ helpers.each(this.datasets,function(dataset,datasetIndex){
+ helpers.each(dataset.bars,function(bar,index){
+ if (bar.hasValue()){
+ bar.base = this.scale.endPoint;
+ //Transition then draw
+ bar.transition({
+ x : this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
+ y : this.scale.calculateY(bar.value),
+ width : this.scale.calculateBarWidth(this.datasets.length)
+ }, easingDecimal).draw();
+ }
+ },this);
+
+ },this);
+ }
+ });
+
+
+}).call(this);
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Core.js b/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Core.js
new file mode 100755
index 0000000..5dccd2e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Core.js
@@ -0,0 +1,2021 @@
+/*!
+ * Chart.js
+ * http://chartjs.org/
+ * Version: {{ version }}
+ *
+ * Copyright 2015 Nick Downie
+ * Released under the MIT license
+ * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
+ */
+
+
+(function(){
+
+ "use strict";
+
+ //Declare root variable - window in the browser, global on the server
+ var root = this,
+ previous = root.Chart;
+
+ //Occupy the global variable of Chart, and create a simple base class
+ var Chart = function(context){
+ var chart = this;
+ this.canvas = context.canvas;
+
+ this.ctx = context;
+
+ //Variables global to the chart
+ var computeDimension = function(element,dimension)
+ {
+ if (element['offset'+dimension])
+ {
+ return element['offset'+dimension];
+ }
+ else
+ {
+ return document.defaultView.getComputedStyle(element).getPropertyValue(dimension);
+ }
+ }
+
+ var width = this.width = computeDimension(context.canvas,'Width');
+ var height = this.height = computeDimension(context.canvas,'Height');
+
+ // Firefox requires this to work correctly
+ context.canvas.width = width;
+ context.canvas.height = height;
+
+ var width = this.width = context.canvas.width;
+ var height = this.height = context.canvas.height;
+ this.aspectRatio = this.width / this.height;
+ //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
+ helpers.retinaScale(this);
+
+ return this;
+ };
+ //Globally expose the defaults to allow for user updating/changing
+ Chart.defaults = {
+ global: {
+ // Boolean - Whether to animate the chart
+ animation: true,
+
+ // Number - Number of animation steps
+ animationSteps: 60,
+
+ // String - Animation easing effect
+ animationEasing: "easeOutQuart",
+
+ // Boolean - If we should show the scale at all
+ showScale: true,
+
+ // Boolean - If we want to override with a hard coded scale
+ scaleOverride: false,
+
+ // ** Required if scaleOverride is true **
+ // Number - The number of steps in a hard coded scale
+ scaleSteps: null,
+ // Number - The value jump in the hard coded scale
+ scaleStepWidth: null,
+ // Number - The scale starting value
+ scaleStartValue: null,
+
+ // String - Colour of the scale line
+ scaleLineColor: "rgba(0,0,0,.1)",
+
+ // Number - Pixel width of the scale line
+ scaleLineWidth: 1,
+
+ // Boolean - Whether to show labels on the scale
+ scaleShowLabels: true,
+
+ // Interpolated JS string - can access value
+ scaleLabel: "<%=value%>",
+
+ // Boolean - Whether the scale should stick to integers, and not show any floats even if drawing space is there
+ scaleIntegersOnly: true,
+
+ // Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
+ scaleBeginAtZero: false,
+
+ // String - Scale label font declaration for the scale label
+ scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
+
+ // Number - Scale label font size in pixels
+ scaleFontSize: 12,
+
+ // String - Scale label font weight style
+ scaleFontStyle: "normal",
+
+ // String - Scale label font colour
+ scaleFontColor: "#666",
+
+ // Boolean - whether or not the chart should be responsive and resize when the browser does.
+ responsive: false,
+
+ // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
+ maintainAspectRatio: true,
+
+ // Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove
+ showTooltips: true,
+
+ // Boolean - Determines whether to draw built-in tooltip or call custom tooltip function
+ customTooltips: false,
+
+ // Array - Array of string names to attach tooltip events
+ tooltipEvents: ["mousemove", "touchstart", "touchmove", "mouseout"],
+
+ // String - Tooltip background colour
+ tooltipFillColor: "rgba(0,0,0,0.8)",
+
+ // String - Tooltip label font declaration for the scale label
+ tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
+
+ // Number - Tooltip label font size in pixels
+ tooltipFontSize: 14,
+
+ // String - Tooltip font weight style
+ tooltipFontStyle: "normal",
+
+ // String - Tooltip label font colour
+ tooltipFontColor: "#fff",
+
+ // String - Tooltip title font declaration for the scale label
+ tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
+
+ // Number - Tooltip title font size in pixels
+ tooltipTitleFontSize: 14,
+
+ // String - Tooltip title font weight style
+ tooltipTitleFontStyle: "bold",
+
+ // String - Tooltip title font colour
+ tooltipTitleFontColor: "#fff",
+
+ // Number - pixel width of padding around tooltip text
+ tooltipYPadding: 6,
+
+ // Number - pixel width of padding around tooltip text
+ tooltipXPadding: 6,
+
+ // Number - Size of the caret on the tooltip
+ tooltipCaretSize: 8,
+
+ // Number - Pixel radius of the tooltip border
+ tooltipCornerRadius: 6,
+
+ // Number - Pixel offset from point x to tooltip edge
+ tooltipXOffset: 10,
+
+ // String - Template string for single tooltips
+ tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
+
+ // String - Template string for single tooltips
+ multiTooltipTemplate: "<%= value %>",
+
+ // String - Colour behind the legend colour block
+ multiTooltipKeyBackground: '#fff',
+
+ // Function - Will fire on animation progression.
+ onAnimationProgress: function(){},
+
+ // Function - Will fire on animation completion.
+ onAnimationComplete: function(){}
+
+ }
+ };
+
+ //Create a dictionary of chart types, to allow for extension of existing types
+ Chart.types = {};
+
+ //Global Chart helpers object for utility methods and classes
+ var helpers = Chart.helpers = {};
+
+ //-- Basic js utility methods
+ var each = helpers.each = function(loopable,callback,self){
+ var additionalArgs = Array.prototype.slice.call(arguments, 3);
+ // Check to see if null or undefined firstly.
+ if (loopable){
+ if (loopable.length === +loopable.length){
+ var i;
+ for (i=0; i<loopable.length; i++){
+ callback.apply(self,[loopable[i], i].concat(additionalArgs));
+ }
+ }
+ else{
+ for (var item in loopable){
+ callback.apply(self,[loopable[item],item].concat(additionalArgs));
+ }
+ }
+ }
+ },
+ clone = helpers.clone = function(obj){
+ var objClone = {};
+ each(obj,function(value,key){
+ if (obj.hasOwnProperty(key)) objClone[key] = value;
+ });
+ return objClone;
+ },
+ extend = helpers.extend = function(base){
+ each(Array.prototype.slice.call(arguments,1), function(extensionObject) {
+ each(extensionObject,function(value,key){
+ if (extensionObject.hasOwnProperty(key)) base[key] = value;
+ });
+ });
+ return base;
+ },
+ merge = helpers.merge = function(base,master){
+ //Merge properties in left object over to a shallow clone of object right.
+ var args = Array.prototype.slice.call(arguments,0);
+ args.unshift({});
+ return extend.apply(null, args);
+ },
+ indexOf = helpers.indexOf = function(arrayToSearch, item){
+ if (Array.prototype.indexOf) {
+ return arrayToSearch.indexOf(item);
+ }
+ else{
+ for (var i = 0; i < arrayToSearch.length; i++) {
+ if (arrayToSearch[i] === item) return i;
+ }
+ return -1;
+ }
+ },
+ where = helpers.where = function(collection, filterCallback){
+ var filtered = [];
+
+ helpers.each(collection, function(item){
+ if (filterCallback(item)){
+ filtered.push(item);
+ }
+ });
+
+ return filtered;
+ },
+ findNextWhere = helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex){
+ // Default to start of the array
+ if (!startIndex){
+ startIndex = -1;
+ }
+ for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
+ var currentItem = arrayToSearch[i];
+ if (filterCallback(currentItem)){
+ return currentItem;
+ }
+ }
+ },
+ findPreviousWhere = helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex){
+ // Default to end of the array
+ if (!startIndex){
+ startIndex = arrayToSearch.length;
+ }
+ for (var i = startIndex - 1; i >= 0; i--) {
+ var currentItem = arrayToSearch[i];
+ if (filterCallback(currentItem)){
+ return currentItem;
+ }
+ }
+ },
+ inherits = helpers.inherits = function(extensions){
+ //Basic javascript inheritance based on the model created in Backbone.js
+ var parent = this;
+ var ChartElement = (extensions && extensions.hasOwnProperty("constructor")) ? extensions.constructor : function(){ return parent.apply(this, arguments); };
+
+ var Surrogate = function(){ this.constructor = ChartElement;};
+ Surrogate.prototype = parent.prototype;
+ ChartElement.prototype = new Surrogate();
+
+ ChartElement.extend = inherits;
+
+ if (extensions) extend(ChartElement.prototype, extensions);
+
+ ChartElement.__super__ = parent.prototype;
+
+ return ChartElement;
+ },
+ noop = helpers.noop = function(){},
+ uid = helpers.uid = (function(){
+ var id=0;
+ return function(){
+ return "chart-" + id++;
+ };
+ })(),
+ warn = helpers.warn = function(str){
+ //Method for warning of errors
+ if (window.console && typeof window.console.warn == "function") console.warn(str);
+ },
+ amd = helpers.amd = (typeof define == 'function' && define.amd),
+ //-- Math methods
+ isNumber = helpers.isNumber = function(n){
+ return !isNaN(parseFloat(n)) && isFinite(n);
+ },
+ max = helpers.max = function(array){
+ return Math.max.apply( Math, array );
+ },
+ min = helpers.min = function(array){
+ return Math.min.apply( Math, array );
+ },
+ cap = helpers.cap = function(valueToCap,maxValue,minValue){
+ if(isNumber(maxValue)) {
+ if( valueToCap > maxValue ) {
+ return maxValue;
+ }
+ }
+ else if(isNumber(minValue)){
+ if ( valueToCap < minValue ){
+ return minValue;
+ }
+ }
+ return valueToCap;
+ },
+ getDecimalPlaces = helpers.getDecimalPlaces = function(num){
+ if (num%1!==0 && isNumber(num)){
+ return num.toString().split(".")[1].length;
+ }
+ else {
+ return 0;
+ }
+ },
+ toRadians = helpers.radians = function(degrees){
+ return degrees * (Math.PI/180);
+ },
+ // Gets the angle from vertical upright to the point about a centre.
+ getAngleFromPoint = helpers.getAngleFromPoint = function(centrePoint, anglePoint){
+ var distanceFromXCenter = anglePoint.x - centrePoint.x,
+ distanceFromYCenter = anglePoint.y - centrePoint.y,
+ radialDistanceFromCenter = Math.sqrt( distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
+
+
+ var angle = Math.PI * 2 + Math.atan2(distanceFromYCenter, distanceFromXCenter);
+
+ //If the segment is in the top left quadrant, we need to add another rotation to the angle
+ if (distanceFromXCenter < 0 && distanceFromYCenter < 0){
+ angle += Math.PI*2;
+ }
+
+ return {
+ angle: angle,
+ distance: radialDistanceFromCenter
+ };
+ },
+ aliasPixel = helpers.aliasPixel = function(pixelWidth){
+ return (pixelWidth % 2 === 0) ? 0 : 0.5;
+ },
+ splineCurve = helpers.splineCurve = function(FirstPoint,MiddlePoint,AfterPoint,t){
+ //Props to Rob Spencer at scaled innovation for his post on splining between points
+ //http://scaledinnovation.com/analytics/splines/aboutSplines.html
+ var d01=Math.sqrt(Math.pow(MiddlePoint.x-FirstPoint.x,2)+Math.pow(MiddlePoint.y-FirstPoint.y,2)),
+ d12=Math.sqrt(Math.pow(AfterPoint.x-MiddlePoint.x,2)+Math.pow(AfterPoint.y-MiddlePoint.y,2)),
+ fa=t*d01/(d01+d12),// scaling factor for triangle Ta
+ fb=t*d12/(d01+d12);
+ return {
+ inner : {
+ x : MiddlePoint.x-fa*(AfterPoint.x-FirstPoint.x),
+ y : MiddlePoint.y-fa*(AfterPoint.y-FirstPoint.y)
+ },
+ outer : {
+ x: MiddlePoint.x+fb*(AfterPoint.x-FirstPoint.x),
+ y : MiddlePoint.y+fb*(AfterPoint.y-FirstPoint.y)
+ }
+ };
+ },
+ calculateOrderOfMagnitude = helpers.calculateOrderOfMagnitude = function(val){
+ return Math.floor(Math.log(val) / Math.LN10);
+ },
+ calculateScaleRange = helpers.calculateScaleRange = function(valuesArray, drawingSize, textSize, startFromZero, integersOnly){
+
+ //Set a minimum step of two - a point at the top of the graph, and a point at the base
+ var minSteps = 2,
+ maxSteps = Math.floor(drawingSize/(textSize * 1.5)),
+ skipFitting = (minSteps >= maxSteps);
+
+ var maxValue = max(valuesArray),
+ minValue = min(valuesArray);
+
+ // We need some degree of seperation here to calculate the scales if all the values are the same
+ // Adding/minusing 0.5 will give us a range of 1.
+ if (maxValue === minValue){
+ maxValue += 0.5;
+ // So we don't end up with a graph with a negative start value if we've said always start from zero
+ if (minValue >= 0.5 && !startFromZero){
+ minValue -= 0.5;
+ }
+ else{
+ // Make up a whole number above the values
+ maxValue += 0.5;
+ }
+ }
+
+ var valueRange = Math.abs(maxValue - minValue),
+ rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange),
+ graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
+ graphMin = (startFromZero) ? 0 : Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
+ graphRange = graphMax - graphMin,
+ stepValue = Math.pow(10, rangeOrderOfMagnitude),
+ numberOfSteps = Math.round(graphRange / stepValue);
+
+ //If we have more space on the graph we'll use it to give more definition to the data
+ while((numberOfSteps > maxSteps || (numberOfSteps * 2) < maxSteps) && !skipFitting) {
+ if(numberOfSteps > maxSteps){
+ stepValue *=2;
+ numberOfSteps = Math.round(graphRange/stepValue);
+ // Don't ever deal with a decimal number of steps - cancel fitting and just use the minimum number of steps.
+ if (numberOfSteps % 1 !== 0){
+ skipFitting = true;
+ }
+ }
+ //We can fit in double the amount of scale points on the scale
+ else{
+ //If user has declared ints only, and the step value isn't a decimal
+ if (integersOnly && rangeOrderOfMagnitude >= 0){
+ //If the user has said integers only, we need to check that making the scale more granular wouldn't make it a float
+ if(stepValue/2 % 1 === 0){
+ stepValue /=2;
+ numberOfSteps = Math.round(graphRange/stepValue);
+ }
+ //If it would make it a float break out of the loop
+ else{
+ break;
+ }
+ }
+ //If the scale doesn't have to be an int, make the scale more granular anyway.
+ else{
+ stepValue /=2;
+ numberOfSteps = Math.round(graphRange/stepValue);
+ }
+
+ }
+ }
+
+ if (skipFitting){
+ numberOfSteps = minSteps;
+ stepValue = graphRange / numberOfSteps;
+ }
+
+ return {
+ steps : numberOfSteps,
+ stepValue : stepValue,
+ min : graphMin,
+ max : graphMin + (numberOfSteps * stepValue)
+ };
+
+ },
+ /* jshint ignore:start */
+ // Blows up jshint errors based on the new Function constructor
+ //Templating methods
+ //Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/
+ template = helpers.template = function(templateString, valuesObject){
+
+ // If templateString is function rather than string-template - call the function for valuesObject
+
+ if(templateString instanceof Function){
+ return templateString(valuesObject);
+ }
+
+ var cache = {};
+ function tmpl(str, data){
+ // Figure out if we're getting a template, or if we need to
+ // load the template - and be sure to cache the result.
+ var fn = !/\W/.test(str) ?
+ cache[str] = cache[str] :
+
+ // Generate a reusable function that will serve as a template
+ // generator (and which will be cached).
+ new Function("obj",
+ "var p=[],print=function(){p.push.apply(p,arguments);};" +
+
+ // Introduce the data as local variables using with(){}
+ "with(obj){p.push('" +
+
+ // Convert the template into pure JavaScript
+ str
+ .replace(/[\r\t\n]/g, " ")
+ .split("<%").join("\t")
+ .replace(/((^|%>)[^\t]*)'/g, "$1\r")
+ .replace(/\t=(.*?)%>/g, "',$1,'")
+ .split("\t").join("');")
+ .split("%>").join("p.push('")
+ .split("\r").join("\\'") +
+ "');}return p.join('');"
+ );
+
+ // Provide some basic currying to the user
+ return data ? fn( data ) : fn;
+ }
+ return tmpl(templateString,valuesObject);
+ },
+ /* jshint ignore:end */
+ generateLabels = helpers.generateLabels = function(templateString,numberOfSteps,graphMin,stepValue){
+ var labelsArray = new Array(numberOfSteps);
+ if (labelTemplateString){
+ each(labelsArray,function(val,index){
+ labelsArray[index] = template(templateString,{value: (graphMin + (stepValue*(index+1)))});
+ });
+ }
+ return labelsArray;
+ },
+ //--Animation methods
+ //Easing functions adapted from Robert Penner's easing equations
+ //http://www.robertpenner.com/easing/
+ easingEffects = helpers.easingEffects = {
+ linear: function (t) {
+ return t;
+ },
+ easeInQuad: function (t) {
+ return t * t;
+ },
+ easeOutQuad: function (t) {
+ return -1 * t * (t - 2);
+ },
+ easeInOutQuad: function (t) {
+ if ((t /= 1 / 2) < 1) return 1 / 2 * t * t;
+ return -1 / 2 * ((--t) * (t - 2) - 1);
+ },
+ easeInCubic: function (t) {
+ return t * t * t;
+ },
+ easeOutCubic: function (t) {
+ return 1 * ((t = t / 1 - 1) * t * t + 1);
+ },
+ easeInOutCubic: function (t) {
+ if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t;
+ return 1 / 2 * ((t -= 2) * t * t + 2);
+ },
+ easeInQuart: function (t) {
+ return t * t * t * t;
+ },
+ easeOutQuart: function (t) {
+ return -1 * ((t = t / 1 - 1) * t * t * t - 1);
+ },
+ easeInOutQuart: function (t) {
+ if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t;
+ return -1 / 2 * ((t -= 2) * t * t * t - 2);
+ },
+ easeInQuint: function (t) {
+ return 1 * (t /= 1) * t * t * t * t;
+ },
+ easeOutQuint: function (t) {
+ return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
+ },
+ easeInOutQuint: function (t) {
+ if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t * t;
+ return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
+ },
+ easeInSine: function (t) {
+ return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1;
+ },
+ easeOutSine: function (t) {
+ return 1 * Math.sin(t / 1 * (Math.PI / 2));
+ },
+ easeInOutSine: function (t) {
+ return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1);
+ },
+ easeInExpo: function (t) {
+ return (t === 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1));
+ },
+ easeOutExpo: function (t) {
+ return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
+ },
+ easeInOutExpo: function (t) {
+ if (t === 0) return 0;
+ if (t === 1) return 1;
+ if ((t /= 1 / 2) < 1) return 1 / 2 * Math.pow(2, 10 * (t - 1));
+ return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
+ },
+ easeInCirc: function (t) {
+ if (t >= 1) return t;
+ return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
+ },
+ easeOutCirc: function (t) {
+ return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
+ },
+ easeInOutCirc: function (t) {
+ if ((t /= 1 / 2) < 1) return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
+ return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
+ },
+ easeInElastic: function (t) {
+ var s = 1.70158;
+ var p = 0;
+ var a = 1;
+ if (t === 0) return 0;
+ if ((t /= 1) == 1) return 1;
+ if (!p) p = 1 * 0.3;
+ if (a < Math.abs(1)) {
+ a = 1;
+ s = p / 4;
+ } else s = p / (2 * Math.PI) * Math.asin(1 / a);
+ return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
+ },
+ easeOutElastic: function (t) {
+ var s = 1.70158;
+ var p = 0;
+ var a = 1;
+ if (t === 0) return 0;
+ if ((t /= 1) == 1) return 1;
+ if (!p) p = 1 * 0.3;
+ if (a < Math.abs(1)) {
+ a = 1;
+ s = p / 4;
+ } else s = p / (2 * Math.PI) * Math.asin(1 / a);
+ return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
+ },
+ easeInOutElastic: function (t) {
+ var s = 1.70158;
+ var p = 0;
+ var a = 1;
+ if (t === 0) return 0;
+ if ((t /= 1 / 2) == 2) return 1;
+ if (!p) p = 1 * (0.3 * 1.5);
+ if (a < Math.abs(1)) {
+ a = 1;
+ s = p / 4;
+ } else s = p / (2 * Math.PI) * Math.asin(1 / a);
+ if (t < 1) return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
+ return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1;
+ },
+ easeInBack: function (t) {
+ var s = 1.70158;
+ return 1 * (t /= 1) * t * ((s + 1) * t - s);
+ },
+ easeOutBack: function (t) {
+ var s = 1.70158;
+ return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1);
+ },
+ easeInOutBack: function (t) {
+ var s = 1.70158;
+ if ((t /= 1 / 2) < 1) return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
+ return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
+ },
+ easeInBounce: function (t) {
+ return 1 - easingEffects.easeOutBounce(1 - t);
+ },
+ easeOutBounce: function (t) {
+ if ((t /= 1) < (1 / 2.75)) {
+ return 1 * (7.5625 * t * t);
+ } else if (t < (2 / 2.75)) {
+ return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75);
+ } else if (t < (2.5 / 2.75)) {
+ return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375);
+ } else {
+ return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375);
+ }
+ },
+ easeInOutBounce: function (t) {
+ if (t < 1 / 2) return easingEffects.easeInBounce(t * 2) * 0.5;
+ return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5;
+ }
+ },
+ //Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
+ requestAnimFrame = helpers.requestAnimFrame = (function(){
+ return window.requestAnimationFrame ||
+ window.webkitRequestAnimationFrame ||
+ window.mozRequestAnimationFrame ||
+ window.oRequestAnimationFrame ||
+ window.msRequestAnimationFrame ||
+ function(callback) {
+ return window.setTimeout(callback, 1000 / 60);
+ };
+ })(),
+ cancelAnimFrame = helpers.cancelAnimFrame = (function(){
+ return window.cancelAnimationFrame ||
+ window.webkitCancelAnimationFrame ||
+ window.mozCancelAnimationFrame ||
+ window.oCancelAnimationFrame ||
+ window.msCancelAnimationFrame ||
+ function(callback) {
+ return window.clearTimeout(callback, 1000 / 60);
+ };
+ })(),
+ animationLoop = helpers.animationLoop = function(callback,totalSteps,easingString,onProgress,onComplete,chartInstance){
+
+ var currentStep = 0,
+ easingFunction = easingEffects[easingString] || easingEffects.linear;
+
+ var animationFrame = function(){
+ currentStep++;
+ var stepDecimal = currentStep/totalSteps;
+ var easeDecimal = easingFunction(stepDecimal);
+
+ callback.call(chartInstance,easeDecimal,stepDecimal, currentStep);
+ onProgress.call(chartInstance,easeDecimal,stepDecimal);
+ if (currentStep < totalSteps){
+ chartInstance.animationFrame = requestAnimFrame(animationFrame);
+ } else{
+ onComplete.apply(chartInstance);
+ }
+ };
+ requestAnimFrame(animationFrame);
+ },
+ //-- DOM methods
+ getRelativePosition = helpers.getRelativePosition = function(evt){
+ var mouseX, mouseY;
+ var e = evt.originalEvent || evt,
+ canvas = evt.currentTarget || evt.srcElement,
+ boundingRect = canvas.getBoundingClientRect();
+
+ if (e.touches){
+ mouseX = e.touches[0].clientX - boundingRect.left;
+ mouseY = e.touches[0].clientY - boundingRect.top;
+
+ }
+ else{
+ mouseX = e.clientX - boundingRect.left;
+ mouseY = e.clientY - boundingRect.top;
+ }
+
+ return {
+ x : mouseX,
+ y : mouseY
+ };
+
+ },
+ addEvent = helpers.addEvent = function(node,eventType,method){
+ if (node.addEventListener){
+ node.addEventListener(eventType,method);
+ } else if (node.attachEvent){
+ node.attachEvent("on"+eventType, method);
+ } else {
+ node["on"+eventType] = method;
+ }
+ },
+ removeEvent = helpers.removeEvent = function(node, eventType, handler){
+ if (node.removeEventListener){
+ node.removeEventListener(eventType, handler, false);
+ } else if (node.detachEvent){
+ node.detachEvent("on"+eventType,handler);
+ } else{
+ node["on" + eventType] = noop;
+ }
+ },
+ bindEvents = helpers.bindEvents = function(chartInstance, arrayOfEvents, handler){
+ // Create the events object if it's not already present
+ if (!chartInstance.events) chartInstance.events = {};
+
+ each(arrayOfEvents,function(eventName){
+ chartInstance.events[eventName] = function(){
+ handler.apply(chartInstance, arguments);
+ };
+ addEvent(chartInstance.chart.canvas,eventName,chartInstance.events[eventName]);
+ });
+ },
+ unbindEvents = helpers.unbindEvents = function (chartInstance, arrayOfEvents) {
+ each(arrayOfEvents, function(handler,eventName){
+ removeEvent(chartInstance.chart.canvas, eventName, handler);
+ });
+ },
+ getMaximumWidth = helpers.getMaximumWidth = function(domNode){
+ var container = domNode.parentNode;
+ // TODO = check cross browser stuff with this.
+ return container.clientWidth;
+ },
+ getMaximumHeight = helpers.getMaximumHeight = function(domNode){
+ var container = domNode.parentNode;
+ // TODO = check cross browser stuff with this.
+ return container.clientHeight;
+ },
+ getMaximumSize = helpers.getMaximumSize = helpers.getMaximumWidth, // legacy support
+ retinaScale = helpers.retinaScale = function(chart){
+ var ctx = chart.ctx,
+ width = chart.canvas.width,
+ height = chart.canvas.height;
+
+ if (window.devicePixelRatio) {
+ ctx.canvas.style.width = width + "px";
+ ctx.canvas.style.height = height + "px";
+ ctx.canvas.height = height * window.devicePixelRatio;
+ ctx.canvas.width = width * window.devicePixelRatio;
+ ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
+ }
+ },
+ //-- Canvas methods
+ clear = helpers.clear = function(chart){
+ chart.ctx.clearRect(0,0,chart.width,chart.height);
+ },
+ fontString = helpers.fontString = function(pixelSize,fontStyle,fontFamily){
+ return fontStyle + " " + pixelSize+"px " + fontFamily;
+ },
+ longestText = helpers.longestText = function(ctx,font,arrayOfStrings){
+ ctx.font = font;
+ var longest = 0;
+ each(arrayOfStrings,function(string){
+ var textWidth = ctx.measureText(string).width;
+ longest = (textWidth > longest) ? textWidth : longest;
+ });
+ return longest;
+ },
+ drawRoundedRectangle = helpers.drawRoundedRectangle = function(ctx,x,y,width,height,radius){
+ ctx.beginPath();
+ ctx.moveTo(x + radius, y);
+ ctx.lineTo(x + width - radius, y);
+ ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
+ ctx.lineTo(x + width, y + height - radius);
+ ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
+ ctx.lineTo(x + radius, y + height);
+ ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
+ ctx.lineTo(x, y + radius);
+ ctx.quadraticCurveTo(x, y, x + radius, y);
+ ctx.closePath();
+ };
+
+
+ //Store a reference to each instance - allowing us to globally resize chart instances on window resize.
+ //Destroy method on the chart will remove the instance of the chart from this reference.
+ Chart.instances = {};
+
+ Chart.Type = function(data,options,chart){
+ this.options = options;
+ this.chart = chart;
+ this.id = uid();
+ //Add the chart instance to the global namespace
+ Chart.instances[this.id] = this;
+
+ // Initialize is always called when a chart type is created
+ // By default it is a no op, but it should be extended
+ if (options.responsive){
+ this.resize();
+ }
+ this.initialize.call(this,data);
+ };
+
+ //Core methods that'll be a part of every chart type
+ extend(Chart.Type.prototype,{
+ initialize : function(){return this;},
+ clear : function(){
+ clear(this.chart);
+ return this;
+ },
+ stop : function(){
+ // Stops any current animation loop occuring
+ cancelAnimFrame(this.animationFrame);
+ return this;
+ },
+ resize : function(callback){
+ this.stop();
+ var canvas = this.chart.canvas,
+ newWidth = getMaximumWidth(this.chart.canvas),
+ newHeight = this.options.maintainAspectRatio ? newWidth / this.chart.aspectRatio : getMaximumHeight(this.chart.canvas);
+
+ canvas.width = this.chart.width = newWidth;
+ canvas.height = this.chart.height = newHeight;
+
+ retinaScale(this.chart);
+
+ if (typeof callback === "function"){
+ callback.apply(this, Array.prototype.slice.call(arguments, 1));
+ }
+ return this;
+ },
+ reflow : noop,
+ render : function(reflow){
+ if (reflow){
+ this.reflow();
+ }
+ if (this.options.animation && !reflow){
+ helpers.animationLoop(
+ this.draw,
+ this.options.animationSteps,
+ this.options.animationEasing,
+ this.options.onAnimationProgress,
+ this.options.onAnimationComplete,
+ this
+ );
+ }
+ else{
+ this.draw();
+ this.options.onAnimationComplete.call(this);
+ }
+ return this;
+ },
+ generateLegend : function(){
+ return template(this.options.legendTemplate,this);
+ },
+ destroy : function(){
+ this.clear();
+ unbindEvents(this, this.events);
+ var canvas = this.chart.canvas;
+
+ // Reset canvas height/width attributes starts a fresh with the canvas context
+ canvas.width = this.chart.width;
+ canvas.height = this.chart.height;
+
+ // < IE9 doesn't support removeProperty
+ if (canvas.style.removeProperty) {
+ canvas.style.removeProperty('width');
+ canvas.style.removeProperty('height');
+ } else {
+ canvas.style.removeAttribute('width');
+ canvas.style.removeAttribute('height');
+ }
+
+ delete Chart.instances[this.id];
+ },
+ showTooltip : function(ChartElements, forceRedraw){
+ // Only redraw the chart if we've actually changed what we're hovering on.
+ if (typeof this.activeElements === 'undefined') this.activeElements = [];
+
+ var isChanged = (function(Elements){
+ var changed = false;
+
+ if (Elements.length !== this.activeElements.length){
+ changed = true;
+ return changed;
+ }
+
+ each(Elements, function(element, index){
+ if (element !== this.activeElements[index]){
+ changed = true;
+ }
+ }, this);
+ return changed;
+ }).call(this, ChartElements);
+
+ if (!isChanged && !forceRedraw){
+ return;
+ }
+ else{
+ this.activeElements = ChartElements;
+ }
+ this.draw();
+ if(this.options.customTooltips){
+ this.options.customTooltips(false);
+ }
+ if (ChartElements.length > 0){
+ // If we have multiple datasets, show a MultiTooltip for all of the data points at that index
+ if (this.datasets && this.datasets.length > 1) {
+ var dataArray,
+ dataIndex;
+
+ for (var i = this.datasets.length - 1; i >= 0; i--) {
+ dataArray = this.datasets[i].points || this.datasets[i].bars || this.datasets[i].segments;
+ dataIndex = indexOf(dataArray, ChartElements[0]);
+ if (dataIndex !== -1){
+ break;
+ }
+ }
+ var tooltipLabels = [],
+ tooltipColors = [],
+ medianPosition = (function(index) {
+
+ // Get all the points at that particular index
+ var Elements = [],
+ dataCollection,
+ xPositions = [],
+ yPositions = [],
+ xMax,
+ yMax,
+ xMin,
+ yMin;
+ helpers.each(this.datasets, function(dataset){
+ dataCollection = dataset.points || dataset.bars || dataset.segments;
+ if (dataCollection[dataIndex] && dataCollection[dataIndex].hasValue()){
+ Elements.push(dataCollection[dataIndex]);
+ }
+ });
+
+ helpers.each(Elements, function(element) {
+ xPositions.push(element.x);
+ yPositions.push(element.y);
+
+
+ //Include any colour information about the element
+ tooltipLabels.push(helpers.template(this.options.multiTooltipTemplate, element));
+ tooltipColors.push({
+ fill: element._saved.fillColor || element.fillColor,
+ stroke: element._saved.strokeColor || element.strokeColor
+ });
+
+ }, this);
+
+ yMin = min(yPositions);
+ yMax = max(yPositions);
+
+ xMin = min(xPositions);
+ xMax = max(xPositions);
+
+ return {
+ x: (xMin > this.chart.width/2) ? xMin : xMax,
+ y: (yMin + yMax)/2
+ };
+ }).call(this, dataIndex);
+
+ new Chart.MultiTooltip({
+ x: medianPosition.x,
+ y: medianPosition.y,
+ xPadding: this.options.tooltipXPadding,
+ yPadding: this.options.tooltipYPadding,
+ xOffset: this.options.tooltipXOffset,
+ fillColor: this.options.tooltipFillColor,
+ textColor: this.options.tooltipFontColor,
+ fontFamily: this.options.tooltipFontFamily,
+ fontStyle: this.options.tooltipFontStyle,
+ fontSize: this.options.tooltipFontSize,
+ titleTextColor: this.options.tooltipTitleFontColor,
+ titleFontFamily: this.options.tooltipTitleFontFamily,
+ titleFontStyle: this.options.tooltipTitleFontStyle,
+ titleFontSize: this.options.tooltipTitleFontSize,
+ cornerRadius: this.options.tooltipCornerRadius,
+ labels: tooltipLabels,
+ legendColors: tooltipColors,
+ legendColorBackground : this.options.multiTooltipKeyBackground,
+ title: ChartElements[0].label,
+ chart: this.chart,
+ ctx: this.chart.ctx,
+ custom: this.options.customTooltips
+ }).draw();
+
+ } else {
+ each(ChartElements, function(Element) {
+ var tooltipPosition = Element.tooltipPosition();
+ new Chart.Tooltip({
+ x: Math.round(tooltipPosition.x),
+ y: Math.round(tooltipPosition.y),
+ xPadding: this.options.tooltipXPadding,
+ yPadding: this.options.tooltipYPadding,
+ fillColor: this.options.tooltipFillColor,
+ textColor: this.options.tooltipFontColor,
+ fontFamily: this.options.tooltipFontFamily,
+ fontStyle: this.options.tooltipFontStyle,
+ fontSize: this.options.tooltipFontSize,
+ caretHeight: this.options.tooltipCaretSize,
+ cornerRadius: this.options.tooltipCornerRadius,
+ text: template(this.options.tooltipTemplate, Element),
+ chart: this.chart,
+ custom: this.options.customTooltips
+ }).draw();
+ }, this);
+ }
+ }
+ return this;
+ },
+ toBase64Image : function(){
+ return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments);
+ }
+ });
+
+ Chart.Type.extend = function(extensions){
+
+ var parent = this;
+
+ var ChartType = function(){
+ return parent.apply(this,arguments);
+ };
+
+ //Copy the prototype object of the this class
+ ChartType.prototype = clone(parent.prototype);
+ //Now overwrite some of the properties in the base class with the new extensions
+ extend(ChartType.prototype, extensions);
+
+ ChartType.extend = Chart.Type.extend;
+
+ if (extensions.name || parent.prototype.name){
+
+ var chartName = extensions.name || parent.prototype.name;
+ //Assign any potential default values of the new chart type
+
+ //If none are defined, we'll use a clone of the chart type this is being extended from.
+ //I.e. if we extend a line chart, we'll use the defaults from the line chart if our new chart
+ //doesn't define some defaults of their own.
+
+ var baseDefaults = (Chart.defaults[parent.prototype.name]) ? clone(Chart.defaults[parent.prototype.name]) : {};
+
+ Chart.defaults[chartName] = extend(baseDefaults,extensions.defaults);
+
+ Chart.types[chartName] = ChartType;
+
+ //Register this new chart type in the Chart prototype
+ Chart.prototype[chartName] = function(data,options){
+ var config = merge(Chart.defaults.global, Chart.defaults[chartName], options || {});
+ return new ChartType(data,config,this);
+ };
+ } else{
+ warn("Name not provided for this chart, so it hasn't been registered");
+ }
+ return parent;
+ };
+
+ Chart.Element = function(configuration){
+ extend(this,configuration);
+ this.initialize.apply(this,arguments);
+ this.save();
+ };
+ extend(Chart.Element.prototype,{
+ initialize : function(){},
+ restore : function(props){
+ if (!props){
+ extend(this,this._saved);
+ } else {
+ each(props,function(key){
+ this[key] = this._saved[key];
+ },this);
+ }
+ return this;
+ },
+ save : function(){
+ this._saved = clone(this);
+ delete this._saved._saved;
+ return this;
+ },
+ update : function(newProps){
+ each(newProps,function(value,key){
+ this._saved[key] = this[key];
+ this[key] = value;
+ },this);
+ return this;
+ },
+ transition : function(props,ease){
+ each(props,function(value,key){
+ this[key] = ((value - this._saved[key]) * ease) + this._saved[key];
+ },this);
+ return this;
+ },
+ tooltipPosition : function(){
+ return {
+ x : this.x,
+ y : this.y
+ };
+ },
+ hasValue: function(){
+ return isNumber(this.value);
+ }
+ });
+
+ Chart.Element.extend = inherits;
+
+
+ Chart.Point = Chart.Element.extend({
+ display: true,
+ inRange: function(chartX,chartY){
+ var hitDetectionRange = this.hitDetectionRadius + this.radius;
+ return ((Math.pow(chartX-this.x, 2)+Math.pow(chartY-this.y, 2)) < Math.pow(hitDetectionRange,2));
+ },
+ draw : function(){
+ if (this.display){
+ var ctx = this.ctx;
+ ctx.beginPath();
+
+ ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
+ ctx.closePath();
+
+ ctx.strokeStyle = this.strokeColor;
+ ctx.lineWidth = this.strokeWidth;
+
+ ctx.fillStyle = this.fillColor;
+
+ ctx.fill();
+ ctx.stroke();
+ }
+
+
+ //Quick debug for bezier curve splining
+ //Highlights control points and the line between them.
+ //Handy for dev - stripped in the min version.
+
+ // ctx.save();
+ // ctx.fillStyle = "black";
+ // ctx.strokeStyle = "black"
+ // ctx.beginPath();
+ // ctx.arc(this.controlPoints.inner.x,this.controlPoints.inner.y, 2, 0, Math.PI*2);
+ // ctx.fill();
+
+ // ctx.beginPath();
+ // ctx.arc(this.controlPoints.outer.x,this.controlPoints.outer.y, 2, 0, Math.PI*2);
+ // ctx.fill();
+
+ // ctx.moveTo(this.controlPoints.inner.x,this.controlPoints.inner.y);
+ // ctx.lineTo(this.x, this.y);
+ // ctx.lineTo(this.controlPoints.outer.x,this.controlPoints.outer.y);
+ // ctx.stroke();
+
+ // ctx.restore();
+
+
+
+ }
+ });
+
+ Chart.Arc = Chart.Element.extend({
+ inRange : function(chartX,chartY){
+
+ var pointRelativePosition = helpers.getAngleFromPoint(this, {
+ x: chartX,
+ y: chartY
+ });
+
+ //Check if within the range of the open/close angle
+ var betweenAngles = (pointRelativePosition.angle >= this.startAngle && pointRelativePosition.angle <= this.endAngle),
+ withinRadius = (pointRelativePosition.distance >= this.innerRadius && pointRelativePosition.distance <= this.outerRadius);
+
+ return (betweenAngles && withinRadius);
+ //Ensure within the outside of the arc centre, but inside arc outer
+ },
+ tooltipPosition : function(){
+ var centreAngle = this.startAngle + ((this.endAngle - this.startAngle) / 2),
+ rangeFromCentre = (this.outerRadius - this.innerRadius) / 2 + this.innerRadius;
+ return {
+ x : this.x + (Math.cos(centreAngle) * rangeFromCentre),
+ y : this.y + (Math.sin(centreAngle) * rangeFromCentre)
+ };
+ },
+ draw : function(animationPercent){
+
+ var easingDecimal = animationPercent || 1;
+
+ var ctx = this.ctx;
+
+ ctx.beginPath();
+
+ ctx.arc(this.x, this.y, this.outerRadius, this.startAngle, this.endAngle);
+
+ ctx.arc(this.x, this.y, this.innerRadius, this.endAngle, this.startAngle, true);
+
+ ctx.closePath();
+ ctx.strokeStyle = this.strokeColor;
+ ctx.lineWidth = this.strokeWidth;
+
+ ctx.fillStyle = this.fillColor;
+
+ ctx.fill();
+ ctx.lineJoin = 'bevel';
+
+ if (this.showStroke){
+ ctx.stroke();
+ }
+ }
+ });
+
+ Chart.Rectangle = Chart.Element.extend({
+ draw : function(){
+ var ctx = this.ctx,
+ halfWidth = this.width/2,
+ leftX = this.x - halfWidth,
+ rightX = this.x + halfWidth,
+ top = this.base - (this.base - this.y),
+ halfStroke = this.strokeWidth / 2;
+
+ // Canvas doesn't allow us to stroke inside the width so we can
+ // adjust the sizes to fit if we're setting a stroke on the line
+ if (this.showStroke){
+ leftX += halfStroke;
+ rightX -= halfStroke;
+ top += halfStroke;
+ }
+
+ ctx.beginPath();
+
+ ctx.fillStyle = this.fillColor;
+ ctx.strokeStyle = this.strokeColor;
+ ctx.lineWidth = this.strokeWidth;
+
+ // It'd be nice to keep this class totally generic to any rectangle
+ // and simply specify which border to miss out.
+ ctx.moveTo(leftX, this.base);
+ ctx.lineTo(leftX, top);
+ ctx.lineTo(rightX, top);
+ ctx.lineTo(rightX, this.base);
+ ctx.fill();
+ if (this.showStroke){
+ ctx.stroke();
+ }
+ },
+ height : function(){
+ return this.base - this.y;
+ },
+ inRange : function(chartX,chartY){
+ return (chartX >= this.x - this.width/2 && chartX <= this.x + this.width/2) && (chartY >= this.y && chartY <= this.base);
+ }
+ });
+
+ Chart.Tooltip = Chart.Element.extend({
+ draw : function(){
+
+ var ctx = this.chart.ctx;
+
+ ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
+
+ this.xAlign = "center";
+ this.yAlign = "above";
+
+ //Distance between the actual element.y position and the start of the tooltip caret
+ var caretPadding = this.caretPadding = 2;
+
+ var tooltipWidth = ctx.measureText(this.text).width + 2*this.xPadding,
+ tooltipRectHeight = this.fontSize + 2*this.yPadding,
+ tooltipHeight = tooltipRectHeight + this.caretHeight + caretPadding;
+
+ if (this.x + tooltipWidth/2 >this.chart.width){
+ this.xAlign = "left";
+ } else if (this.x - tooltipWidth/2 < 0){
+ this.xAlign = "right";
+ }
+
+ if (this.y - tooltipHeight < 0){
+ this.yAlign = "below";
+ }
+
+
+ var tooltipX = this.x - tooltipWidth/2,
+ tooltipY = this.y - tooltipHeight;
+
+ ctx.fillStyle = this.fillColor;
+
+ // Custom Tooltips
+ if(this.custom){
+ this.custom(this);
+ }
+ else{
+ switch(this.yAlign)
+ {
+ case "above":
+ //Draw a caret above the x/y
+ ctx.beginPath();
+ ctx.moveTo(this.x,this.y - caretPadding);
+ ctx.lineTo(this.x + this.caretHeight, this.y - (caretPadding + this.caretHeight));
+ ctx.lineTo(this.x - this.caretHeight, this.y - (caretPadding + this.caretHeight));
+ ctx.closePath();
+ ctx.fill();
+ break;
+ case "below":
+ tooltipY = this.y + caretPadding + this.caretHeight;
+ //Draw a caret below the x/y
+ ctx.beginPath();
+ ctx.moveTo(this.x, this.y + caretPadding);
+ ctx.lineTo(this.x + this.caretHeight, this.y + caretPadding + this.caretHeight);
+ ctx.lineTo(this.x - this.caretHeight, this.y + caretPadding + this.caretHeight);
+ ctx.closePath();
+ ctx.fill();
+ break;
+ }
+
+ switch(this.xAlign)
+ {
+ case "left":
+ tooltipX = this.x - tooltipWidth + (this.cornerRadius + this.caretHeight);
+ break;
+ case "right":
+ tooltipX = this.x - (this.cornerRadius + this.caretHeight);
+ break;
+ }
+
+ drawRoundedRectangle(ctx,tooltipX,tooltipY,tooltipWidth,tooltipRectHeight,this.cornerRadius);
+
+ ctx.fill();
+
+ ctx.fillStyle = this.textColor;
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ ctx.fillText(this.text, tooltipX + tooltipWidth/2, tooltipY + tooltipRectHeight/2);
+ }
+ }
+ });
+
+ Chart.MultiTooltip = Chart.Element.extend({
+ initialize : function(){
+ this.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
+
+ this.titleFont = fontString(this.titleFontSize,this.titleFontStyle,this.titleFontFamily);
+
+ this.height = (this.labels.length * this.fontSize) + ((this.labels.length-1) * (this.fontSize/2)) + (this.yPadding*2) + this.titleFontSize *1.5;
+
+ this.ctx.font = this.titleFont;
+
+ var titleWidth = this.ctx.measureText(this.title).width,
+ //Label has a legend square as well so account for this.
+ labelWidth = longestText(this.ctx,this.font,this.labels) + this.fontSize + 3,
+ longestTextWidth = max([labelWidth,titleWidth]);
+
+ this.width = longestTextWidth + (this.xPadding*2);
+
+
+ var halfHeight = this.height/2;
+
+ //Check to ensure the height will fit on the canvas
+ if (this.y - halfHeight < 0 ){
+ this.y = halfHeight;
+ } else if (this.y + halfHeight > this.chart.height){
+ this.y = this.chart.height - halfHeight;
+ }
+
+ //Decide whether to align left or right based on position on canvas
+ if (this.x > this.chart.width/2){
+ this.x -= this.xOffset + this.width;
+ } else {
+ this.x += this.xOffset;
+ }
+
+
+ },
+ getLineHeight : function(index){
+ var baseLineHeight = this.y - (this.height/2) + this.yPadding,
+ afterTitleIndex = index-1;
+
+ //If the index is zero, we're getting the title
+ if (index === 0){
+ return baseLineHeight + this.titleFontSize/2;
+ } else{
+ return baseLineHeight + ((this.fontSize*1.5*afterTitleIndex) + this.fontSize/2) + this.titleFontSize * 1.5;
+ }
+
+ },
+ draw : function(){
+ // Custom Tooltips
+ if(this.custom){
+ this.custom(this);
+ }
+ else{
+ drawRoundedRectangle(this.ctx,this.x,this.y - this.height/2,this.width,this.height,this.cornerRadius);
+ var ctx = this.ctx;
+ ctx.fillStyle = this.fillColor;
+ ctx.fill();
+ ctx.closePath();
+
+ ctx.textAlign = "left";
+ ctx.textBaseline = "middle";
+ ctx.fillStyle = this.titleTextColor;
+ ctx.font = this.titleFont;
+
+ ctx.fillText(this.title,this.x + this.xPadding, this.getLineHeight(0));
+
+ ctx.font = this.font;
+ helpers.each(this.labels,function(label,index){
+ ctx.fillStyle = this.textColor;
+ ctx.fillText(label,this.x + this.xPadding + this.fontSize + 3, this.getLineHeight(index + 1));
+
+ //A bit gnarly, but clearing this rectangle breaks when using explorercanvas (clears whole canvas)
+ //ctx.clearRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
+ //Instead we'll make a white filled block to put the legendColour palette over.
+
+ ctx.fillStyle = this.legendColorBackground;
+ ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
+
+ ctx.fillStyle = this.legendColors[index].fill;
+ ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
+
+
+ },this);
+ }
+ }
+ });
+
+ Chart.Scale = Chart.Element.extend({
+ initialize : function(){
+ this.fit();
+ },
+ buildYLabels : function(){
+ this.yLabels = [];
+
+ var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
+
+ for (var i=0; i<=this.steps; i++){
+ this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
+ }
+ this.yLabelWidth = (this.display && this.showLabels) ? longestText(this.ctx,this.font,this.yLabels) : 0;
+ },
+ addXLabel : function(label){
+ this.xLabels.push(label);
+ this.valuesCount++;
+ this.fit();
+ },
+ removeXLabel : function(){
+ this.xLabels.shift();
+ this.valuesCount--;
+ this.fit();
+ },
+ // Fitting loop to rotate x Labels and figure out what fits there, and also calculate how many Y steps to use
+ fit: function(){
+ // First we need the width of the yLabels, assuming the xLabels aren't rotated
+
+ // To do that we need the base line at the top and base of the chart, assuming there is no x label rotation
+ this.startPoint = (this.display) ? this.fontSize : 0;
+ this.endPoint = (this.display) ? this.height - (this.fontSize * 1.5) - 5 : this.height; // -5 to pad labels
+
+ // Apply padding settings to the start and end point.
+ this.startPoint += this.padding;
+ this.endPoint -= this.padding;
+
+ // Cache the starting height, so can determine if we need to recalculate the scale yAxis
+ var cachedHeight = this.endPoint - this.startPoint,
+ cachedYLabelWidth;
+
+ // Build the current yLabels so we have an idea of what size they'll be to start
+ /*
+ * This sets what is returned from calculateScaleRange as static properties of this class:
+ *
+ this.steps;
+ this.stepValue;
+ this.min;
+ this.max;
+ *
+ */
+ this.calculateYRange(cachedHeight);
+
+ // With these properties set we can now build the array of yLabels
+ // and also the width of the largest yLabel
+ this.buildYLabels();
+
+ this.calculateXLabelRotation();
+
+ while((cachedHeight > this.endPoint - this.startPoint)){
+ cachedHeight = this.endPoint - this.startPoint;
+ cachedYLabelWidth = this.yLabelWidth;
+
+ this.calculateYRange(cachedHeight);
+ this.buildYLabels();
+
+ // Only go through the xLabel loop again if the yLabel width has changed
+ if (cachedYLabelWidth < this.yLabelWidth){
+ this.calculateXLabelRotation();
+ }
+ }
+
+ },
+ calculateXLabelRotation : function(){
+ //Get the width of each grid by calculating the difference
+ //between x offsets between 0 and 1.
+
+ this.ctx.font = this.font;
+
+ var firstWidth = this.ctx.measureText(this.xLabels[0]).width,
+ lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width,
+ firstRotated,
+ lastRotated;
+
+
+ this.xScalePaddingRight = lastWidth/2 + 3;
+ this.xScalePaddingLeft = (firstWidth/2 > this.yLabelWidth + 10) ? firstWidth/2 : this.yLabelWidth + 10;
+
+ this.xLabelRotation = 0;
+ if (this.display){
+ var originalLabelWidth = longestText(this.ctx,this.font,this.xLabels),
+ cosRotation,
+ firstRotatedWidth;
+ this.xLabelWidth = originalLabelWidth;
+ //Allow 3 pixels x2 padding either side for label readability
+ var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6;
+
+ //Max label rotate should be 90 - also act as a loop counter
+ while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)){
+ cosRotation = Math.cos(toRadians(this.xLabelRotation));
+
+ firstRotated = cosRotation * firstWidth;
+ lastRotated = cosRotation * lastWidth;
+
+ // We're right aligning the text now.
+ if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8){
+ this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
+ }
+ this.xScalePaddingRight = this.fontSize/2;
+
+
+ this.xLabelRotation++;
+ this.xLabelWidth = cosRotation * originalLabelWidth;
+
+ }
+ if (this.xLabelRotation > 0){
+ this.endPoint -= Math.sin(toRadians(this.xLabelRotation))*originalLabelWidth + 3;
+ }
+ }
+ else{
+ this.xLabelWidth = 0;
+ this.xScalePaddingRight = this.padding;
+ this.xScalePaddingLeft = this.padding;
+ }
+
+ },
+ // Needs to be overidden in each Chart type
+ // Otherwise we need to pass all the data into the scale class
+ calculateYRange: noop,
+ drawingArea: function(){
+ return this.startPoint - this.endPoint;
+ },
+ calculateY : function(value){
+ var scalingFactor = this.drawingArea() / (this.min - this.max);
+ return this.endPoint - (scalingFactor * (value - this.min));
+ },
+ calculateX : function(index){
+ var isRotated = (this.xLabelRotation > 0),
+ // innerWidth = (this.offsetGridLines) ? this.width - offsetLeft - this.padding : this.width - (offsetLeft + halfLabelWidth * 2) - this.padding,
+ innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight),
+ valueWidth = innerWidth/Math.max((this.valuesCount - ((this.offsetGridLines) ? 0 : 1)), 1),
+ valueOffset = (valueWidth * index) + this.xScalePaddingLeft;
+
+ if (this.offsetGridLines){
+ valueOffset += (valueWidth/2);
+ }
+
+ return Math.round(valueOffset);
+ },
+ update : function(newProps){
+ helpers.extend(this, newProps);
+ this.fit();
+ },
+ draw : function(){
+ var ctx = this.ctx,
+ yLabelGap = (this.endPoint - this.startPoint) / this.steps,
+ xStart = Math.round(this.xScalePaddingLeft);
+ if (this.display){
+ ctx.fillStyle = this.textColor;
+ ctx.font = this.font;
+ each(this.yLabels,function(labelString,index){
+ var yLabelCenter = this.endPoint - (yLabelGap * index),
+ linePositionY = Math.round(yLabelCenter),
+ drawHorizontalLine = this.showHorizontalLines;
+
+ ctx.textAlign = "right";
+ ctx.textBaseline = "middle";
+ if (this.showLabels){
+ ctx.fillText(labelString,xStart - 10,yLabelCenter);
+ }
+
+ // This is X axis, so draw it
+ if (index === 0 && !drawHorizontalLine){
+ drawHorizontalLine = true;
+ }
+
+ if (drawHorizontalLine){
+ ctx.beginPath();
+ }
+
+ if (index > 0){
+ // This is a grid line in the centre, so drop that
+ ctx.lineWidth = this.gridLineWidth;
+ ctx.strokeStyle = this.gridLineColor;
+ } else {
+ // This is the first line on the scale
+ ctx.lineWidth = this.lineWidth;
+ ctx.strokeStyle = this.lineColor;
+ }
+
+ linePositionY += helpers.aliasPixel(ctx.lineWidth);
+
+ if(drawHorizontalLine){
+ ctx.moveTo(xStart, linePositionY);
+ ctx.lineTo(this.width, linePositionY);
+ ctx.stroke();
+ ctx.closePath();
+ }
+
+ ctx.lineWidth = this.lineWidth;
+ ctx.strokeStyle = this.lineColor;
+ ctx.beginPath();
+ ctx.moveTo(xStart - 5, linePositionY);
+ ctx.lineTo(xStart, linePositionY);
+ ctx.stroke();
+ ctx.closePath();
+
+ },this);
+
+ each(this.xLabels,function(label,index){
+ var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
+ // Check to see if line/bar here and decide where to place the line
+ linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
+ isRotated = (this.xLabelRotation > 0),
+ drawVerticalLine = this.showVerticalLines;
+
+ // This is Y axis, so draw it
+ if (index === 0 && !drawVerticalLine){
+ drawVerticalLine = true;
+ }
+
+ if (drawVerticalLine){
+ ctx.beginPath();
+ }
+
+ if (index > 0){
+ // This is a grid line in the centre, so drop that
+ ctx.lineWidth = this.gridLineWidth;
+ ctx.strokeStyle = this.gridLineColor;
+ } else {
+ // This is the first line on the scale
+ ctx.lineWidth = this.lineWidth;
+ ctx.strokeStyle = this.lineColor;
+ }
+
+ if (drawVerticalLine){
+ ctx.moveTo(linePos,this.endPoint);
+ ctx.lineTo(linePos,this.startPoint - 3);
+ ctx.stroke();
+ ctx.closePath();
+ }
+
+
+ ctx.lineWidth = this.lineWidth;
+ ctx.strokeStyle = this.lineColor;
+
+
+ // Small lines at the bottom of the base grid line
+ ctx.beginPath();
+ ctx.moveTo(linePos,this.endPoint);
+ ctx.lineTo(linePos,this.endPoint + 5);
+ ctx.stroke();
+ ctx.closePath();
+
+ ctx.save();
+ ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
+ ctx.rotate(toRadians(this.xLabelRotation)*-1);
+ ctx.font = this.font;
+ ctx.textAlign = (isRotated) ? "right" : "center";
+ ctx.textBaseline = (isRotated) ? "middle" : "top";
+ ctx.fillText(label, 0, 0);
+ ctx.restore();
+ },this);
+
+ }
+ }
+
+ });
+
+ Chart.RadialScale = Chart.Element.extend({
+ initialize: function(){
+ this.size = min([this.height, this.width]);
+ this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
+ },
+ calculateCenterOffset: function(value){
+ // Take into account half font size + the yPadding of the top value
+ var scalingFactor = this.drawingArea / (this.max - this.min);
+
+ return (value - this.min) * scalingFactor;
+ },
+ update : function(){
+ if (!this.lineArc){
+ this.setScaleSize();
+ } else {
+ this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
+ }
+ this.buildYLabels();
+ },
+ buildYLabels: function(){
+ this.yLabels = [];
+
+ var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
+
+ for (var i=0; i<=this.steps; i++){
+ this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
+ }
+ },
+ getCircumference : function(){
+ return ((Math.PI*2) / this.valuesCount);
+ },
+ setScaleSize: function(){
+ /*
+ * Right, this is really confusing and there is a lot of maths going on here
+ * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
+ *
+ * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
+ *
+ * Solution:
+ *
+ * We assume the radius of the polygon is half the size of the canvas at first
+ * at each index we check if the text overlaps.
+ *
+ * Where it does, we store that angle and that index.
+ *
+ * After finding the largest index and angle we calculate how much we need to remove
+ * from the shape radius to move the point inwards by that x.
+ *
+ * We average the left and right distances to get the maximum shape radius that can fit in the box
+ * along with labels.
+ *
+ * Once we have that, we can find the centre point for the chart, by taking the x text protrusion
+ * on each side, removing that from the size, halving it and adding the left x protrusion width.
+ *
+ * This will mean we have a shape fitted to the canvas, as large as it can be with the labels
+ * and position it in the most space efficient manner
+ *
+ * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
+ */
+
+
+ // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
+ // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
+ var largestPossibleRadius = min([(this.height/2 - this.pointLabelFontSize - 5), this.width/2]),
+ pointPosition,
+ i,
+ textWidth,
+ halfTextWidth,
+ furthestRight = this.width,
+ furthestRightIndex,
+ furthestRightAngle,
+ furthestLeft = 0,
+ furthestLeftIndex,
+ furthestLeftAngle,
+ xProtrusionLeft,
+ xProtrusionRight,
+ radiusReductionRight,
+ radiusReductionLeft,
+ maxWidthRadius;
+ this.ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
+ for (i=0;i<this.valuesCount;i++){
+ // 5px to space the text slightly out - similar to what we do in the draw function.
+ pointPosition = this.getPointPosition(i, largestPossibleRadius);
+ textWidth = this.ctx.measureText(template(this.templateString, { value: this.labels[i] })).width + 5;
+ if (i === 0 || i === this.valuesCount/2){
+ // If we're at index zero, or exactly the middle, we're at exactly the top/bottom
+ // of the radar chart, so text will be aligned centrally, so we'll half it and compare
+ // w/left and right text sizes
+ halfTextWidth = textWidth/2;
+ if (pointPosition.x + halfTextWidth > furthestRight) {
+ furthestRight = pointPosition.x + halfTextWidth;
+ furthestRightIndex = i;
+ }
+ if (pointPosition.x - halfTextWidth < furthestLeft) {
+ furthestLeft = pointPosition.x - halfTextWidth;
+ furthestLeftIndex = i;
+ }
+ }
+ else if (i < this.valuesCount/2) {
+ // Less than half the values means we'll left align the text
+ if (pointPosition.x + textWidth > furthestRight) {
+ furthestRight = pointPosition.x + textWidth;
+ furthestRightIndex = i;
+ }
+ }
+ else if (i > this.valuesCount/2){
+ // More than half the values means we'll right align the text
+ if (pointPosition.x - textWidth < furthestLeft) {
+ furthestLeft = pointPosition.x - textWidth;
+ furthestLeftIndex = i;
+ }
+ }
+ }
+
+ xProtrusionLeft = furthestLeft;
+
+ xProtrusionRight = Math.ceil(furthestRight - this.width);
+
+ furthestRightAngle = this.getIndexAngle(furthestRightIndex);
+
+ furthestLeftAngle = this.getIndexAngle(furthestLeftIndex);
+
+ radiusReductionRight = xProtrusionRight / Math.sin(furthestRightAngle + Math.PI/2);
+
+ radiusReductionLeft = xProtrusionLeft / Math.sin(furthestLeftAngle + Math.PI/2);
+
+ // Ensure we actually need to reduce the size of the chart
+ radiusReductionRight = (isNumber(radiusReductionRight)) ? radiusReductionRight : 0;
+ radiusReductionLeft = (isNumber(radiusReductionLeft)) ? radiusReductionLeft : 0;
+
+ this.drawingArea = largestPossibleRadius - (radiusReductionLeft + radiusReductionRight)/2;
+
+ //this.drawingArea = min([maxWidthRadius, (this.height - (2 * (this.pointLabelFontSize + 5)))/2])
+ this.setCenterPoint(radiusReductionLeft, radiusReductionRight);
+
+ },
+ setCenterPoint: function(leftMovement, rightMovement){
+
+ var maxRight = this.width - rightMovement - this.drawingArea,
+ maxLeft = leftMovement + this.drawingArea;
+
+ this.xCenter = (maxLeft + maxRight)/2;
+ // Always vertically in the centre as the text height doesn't change
+ this.yCenter = (this.height/2);
+ },
+
+ getIndexAngle : function(index){
+ var angleMultiplier = (Math.PI * 2) / this.valuesCount;
+ // Start from the top instead of right, so remove a quarter of the circle
+
+ return index * angleMultiplier - (Math.PI/2);
+ },
+ getPointPosition : function(index, distanceFromCenter){
+ var thisAngle = this.getIndexAngle(index);
+ return {
+ x : (Math.cos(thisAngle) * distanceFromCenter) + this.xCenter,
+ y : (Math.sin(thisAngle) * distanceFromCenter) + this.yCenter
+ };
+ },
+ draw: function(){
+ if (this.display){
+ var ctx = this.ctx;
+ each(this.yLabels, function(label, index){
+ // Don't draw a centre value
+ if (index > 0){
+ var yCenterOffset = index * (this.drawingArea/this.steps),
+ yHeight = this.yCenter - yCenterOffset,
+ pointPosition;
+
+ // Draw circular lines around the scale
+ if (this.lineWidth > 0){
+ ctx.strokeStyle = this.lineColor;
+ ctx.lineWidth = this.lineWidth;
+
+ if(this.lineArc){
+ ctx.beginPath();
+ ctx.arc(this.xCenter, this.yCenter, yCenterOffset, 0, Math.PI*2);
+ ctx.closePath();
+ ctx.stroke();
+ } else{
+ ctx.beginPath();
+ for (var i=0;i<this.valuesCount;i++)
+ {
+ pointPosition = this.getPointPosition(i, this.calculateCenterOffset(this.min + (index * this.stepValue)));
+ if (i === 0){
+ ctx.moveTo(pointPosition.x, pointPosition.y);
+ } else {
+ ctx.lineTo(pointPosition.x, pointPosition.y);
+ }
+ }
+ ctx.closePath();
+ ctx.stroke();
+ }
+ }
+ if(this.showLabels){
+ ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
+ if (this.showLabelBackdrop){
+ var labelWidth = ctx.measureText(label).width;
+ ctx.fillStyle = this.backdropColor;
+ ctx.fillRect(
+ this.xCenter - labelWidth/2 - this.backdropPaddingX,
+ yHeight - this.fontSize/2 - this.backdropPaddingY,
+ labelWidth + this.backdropPaddingX*2,
+ this.fontSize + this.backdropPaddingY*2
+ );
+ }
+ ctx.textAlign = 'center';
+ ctx.textBaseline = "middle";
+ ctx.fillStyle = this.fontColor;
+ ctx.fillText(label, this.xCenter, yHeight);
+ }
+ }
+ }, this);
+
+ if (!this.lineArc){
+ ctx.lineWidth = this.angleLineWidth;
+ ctx.strokeStyle = this.angleLineColor;
+ for (var i = this.valuesCount - 1; i >= 0; i--) {
+ if (this.angleLineWidth > 0){
+ var outerPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max));
+ ctx.beginPath();
+ ctx.moveTo(this.xCenter, this.yCenter);
+ ctx.lineTo(outerPosition.x, outerPosition.y);
+ ctx.stroke();
+ ctx.closePath();
+ }
+ // Extra 3px out for some label spacing
+ var pointLabelPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max) + 5);
+ ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
+ ctx.fillStyle = this.pointLabelFontColor;
+
+ var labelsCount = this.labels.length,
+ halfLabelsCount = this.labels.length/2,
+ quarterLabelsCount = halfLabelsCount/2,
+ upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount),
+ exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount);
+ if (i === 0){
+ ctx.textAlign = 'center';
+ } else if(i === halfLabelsCount){
+ ctx.textAlign = 'center';
+ } else if (i < halfLabelsCount){
+ ctx.textAlign = 'left';
+ } else {
+ ctx.textAlign = 'right';
+ }
+
+ // Set the correct text baseline based on outer positioning
+ if (exactQuarter){
+ ctx.textBaseline = 'middle';
+ } else if (upperHalf){
+ ctx.textBaseline = 'bottom';
+ } else {
+ ctx.textBaseline = 'top';
+ }
+
+ ctx.fillText(this.labels[i], pointLabelPosition.x, pointLabelPosition.y);
+ }
+ }
+ }
+ }
+ });
+
+ // Attach global event to resize each chart instance when the browser resizes
+ helpers.addEvent(window, "resize", (function(){
+ // Basic debounce of resize function so it doesn't hurt performance when resizing browser.
+ var timeout;
+ return function(){
+ clearTimeout(timeout);
+ timeout = setTimeout(function(){
+ each(Chart.instances,function(instance){
+ // If the responsive flag is set in the chart instance config
+ // Cascade the resize event down to the chart.
+ if (instance.options.responsive){
+ instance.resize(instance.render, true);
+ }
+ });
+ }, 50);
+ };
+ })());
+
+
+ if (amd) {
+ define(function(){
+ return Chart;
+ });
+ } else if (typeof module === 'object' && module.exports) {
+ module.exports = Chart;
+ }
+
+ root.Chart = Chart;
+
+ Chart.noConflict = function(){
+ root.Chart = previous;
+ return Chart;
+ };
+
+}).call(this);
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Doughnut.js b/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Doughnut.js
new file mode 100644
index 0000000..a892b0e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Doughnut.js
@@ -0,0 +1,184 @@
+(function(){
+ "use strict";
+
+ var root = this,
+ Chart = root.Chart,
+ //Cache a local reference to Chart.helpers
+ helpers = Chart.helpers;
+
+ var defaultConfig = {
+ //Boolean - Whether we should show a stroke on each segment
+ segmentShowStroke : true,
+
+ //String - The colour of each segment stroke
+ segmentStrokeColor : "#fff",
+
+ //Number - The width of each segment stroke
+ segmentStrokeWidth : 2,
+
+ //The percentage of the chart that we cut out of the middle.
+ percentageInnerCutout : 50,
+
+ //Number - Amount of animation steps
+ animationSteps : 100,
+
+ //String - Animation easing effect
+ animationEasing : "easeOutBounce",
+
+ //Boolean - Whether we animate the rotation of the Doughnut
+ animateRotate : true,
+
+ //Boolean - Whether we animate scaling the Doughnut from the centre
+ animateScale : false,
+
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
+
+ };
+
+
+ Chart.Type.extend({
+ //Passing in a name registers this chart in the Chart namespace
+ name: "Doughnut",
+ //Providing a defaults will also register the deafults in the chart namespace
+ defaults : defaultConfig,
+ //Initialize is fired when the chart is initialized - Data is passed in as a parameter
+ //Config is automatically merged by the core of Chart.js, and is available at this.options
+ initialize: function(data){
+
+ //Declare segments as a static property to prevent inheriting across the Chart type prototype
+ this.segments = [];
+ this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2;
+
+ this.SegmentArc = Chart.Arc.extend({
+ ctx : this.chart.ctx,
+ x : this.chart.width/2,
+ y : this.chart.height/2
+ });
+
+ //Set up tooltip events on the chart
+ if (this.options.showTooltips){
+ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
+ var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];
+
+ helpers.each(this.segments,function(segment){
+ segment.restore(["fillColor"]);
+ });
+ helpers.each(activeSegments,function(activeSegment){
+ activeSegment.fillColor = activeSegment.highlightColor;
+ });
+ this.showTooltip(activeSegments);
+ });
+ }
+ this.calculateTotal(data);
+
+ helpers.each(data,function(datapoint, index){
+ this.addData(datapoint, index, true);
+ },this);
+
+ this.render();
+ },
+ getSegmentsAtEvent : function(e){
+ var segmentsArray = [];
+
+ var location = helpers.getRelativePosition(e);
+
+ helpers.each(this.segments,function(segment){
+ if (segment.inRange(location.x,location.y)) segmentsArray.push(segment);
+ },this);
+ return segmentsArray;
+ },
+ addData : function(segment, atIndex, silent){
+ var index = atIndex || this.segments.length;
+ this.segments.splice(index, 0, new this.SegmentArc({
+ value : segment.value,
+ outerRadius : (this.options.animateScale) ? 0 : this.outerRadius,
+ innerRadius : (this.options.animateScale) ? 0 : (this.outerRadius/100) * this.options.percentageInnerCutout,
+ fillColor : segment.color,
+ highlightColor : segment.highlight || segment.color,
+ showStroke : this.options.segmentShowStroke,
+ strokeWidth : this.options.segmentStrokeWidth,
+ strokeColor : this.options.segmentStrokeColor,
+ startAngle : Math.PI * 1.5,
+ circumference : (this.options.animateRotate) ? 0 : this.calculateCircumference(segment.value),
+ label : segment.label
+ }));
+ if (!silent){
+ this.reflow();
+ this.update();
+ }
+ },
+ calculateCircumference : function(value){
+ return (Math.PI*2)*(Math.abs(value) / this.total);
+ },
+ calculateTotal : function(data){
+ this.total = 0;
+ helpers.each(data,function(segment){
+ this.total += Math.abs(segment.value);
+ },this);
+ },
+ update : function(){
+ this.calculateTotal(this.segments);
+
+ // Reset any highlight colours before updating.
+ helpers.each(this.activeElements, function(activeElement){
+ activeElement.restore(['fillColor']);
+ });
+
+ helpers.each(this.segments,function(segment){
+ segment.save();
+ });
+ this.render();
+ },
+
+ removeData: function(atIndex){
+ var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1;
+ this.segments.splice(indexToDelete, 1);
+ this.reflow();
+ this.update();
+ },
+
+ reflow : function(){
+ helpers.extend(this.SegmentArc.prototype,{
+ x : this.chart.width/2,
+ y : this.chart.height/2
+ });
+ this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2;
+ helpers.each(this.segments, function(segment){
+ segment.update({
+ outerRadius : this.outerRadius,
+ innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout
+ });
+ }, this);
+ },
+ draw : function(easeDecimal){
+ var animDecimal = (easeDecimal) ? easeDecimal : 1;
+ this.clear();
+ helpers.each(this.segments,function(segment,index){
+ segment.transition({
+ circumference : this.calculateCircumference(segment.value),
+ outerRadius : this.outerRadius,
+ innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout
+ },animDecimal);
+
+ segment.endAngle = segment.startAngle + segment.circumference;
+
+ segment.draw();
+ if (index === 0){
+ segment.startAngle = Math.PI * 1.5;
+ }
+ //Check to see if it's the last segment, if not get the next and update the start angle
+ if (index < this.segments.length-1){
+ this.segments[index+1].startAngle = segment.endAngle;
+ }
+ },this);
+
+ }
+ });
+
+ Chart.types.Doughnut.extend({
+ name : "Pie",
+ defaults : helpers.merge(defaultConfig,{percentageInnerCutout : 0})
+ });
+
+}).call(this);
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Line.js b/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Line.js
new file mode 100644
index 0000000..34ad85b
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Line.js
@@ -0,0 +1,374 @@
+(function(){
+ "use strict";
+
+ var root = this,
+ Chart = root.Chart,
+ helpers = Chart.helpers;
+
+ var defaultConfig = {
+
+ ///Boolean - Whether grid lines are shown across the chart
+ scaleShowGridLines : true,
+
+ //String - Colour of the grid lines
+ scaleGridLineColor : "rgba(0,0,0,.05)",
+
+ //Number - Width of the grid lines
+ scaleGridLineWidth : 1,
+
+ //Boolean - Whether to show horizontal lines (except X axis)
+ scaleShowHorizontalLines: true,
+
+ //Boolean - Whether to show vertical lines (except Y axis)
+ scaleShowVerticalLines: true,
+
+ //Boolean - Whether the line is curved between points
+ bezierCurve : true,
+
+ //Number - Tension of the bezier curve between points
+ bezierCurveTension : 0.4,
+
+ //Boolean - Whether to show a dot for each point
+ pointDot : true,
+
+ //Number - Radius of each point dot in pixels
+ pointDotRadius : 4,
+
+ //Number - Pixel width of point dot stroke
+ pointDotStrokeWidth : 1,
+
+ //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
+ pointHitDetectionRadius : 20,
+
+ //Boolean - Whether to show a stroke for datasets
+ datasetStroke : true,
+
+ //Number - Pixel width of dataset stroke
+ datasetStrokeWidth : 2,
+
+ //Boolean - Whether to fill the dataset with a colour
+ datasetFill : true,
+
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
+
+ };
+
+
+ Chart.Type.extend({
+ name: "Line",
+ defaults : defaultConfig,
+ initialize: function(data){
+ //Declare the extension of the default point, to cater for the options passed in to the constructor
+ this.PointClass = Chart.Point.extend({
+ strokeWidth : this.options.pointDotStrokeWidth,
+ radius : this.options.pointDotRadius,
+ display: this.options.pointDot,
+ hitDetectionRadius : this.options.pointHitDetectionRadius,
+ ctx : this.chart.ctx,
+ inRange : function(mouseX){
+ return (Math.pow(mouseX-this.x, 2) < Math.pow(this.radius + this.hitDetectionRadius,2));
+ }
+ });
+
+ this.datasets = [];
+
+ //Set up tooltip events on the chart
+ if (this.options.showTooltips){
+ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
+ var activePoints = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
+ this.eachPoints(function(point){
+ point.restore(['fillColor', 'strokeColor']);
+ });
+ helpers.each(activePoints, function(activePoint){
+ activePoint.fillColor = activePoint.highlightFill;
+ activePoint.strokeColor = activePoint.highlightStroke;
+ });
+ this.showTooltip(activePoints);
+ });
+ }
+
+ //Iterate through each of the datasets, and build this into a property of the chart
+ helpers.each(data.datasets,function(dataset){
+
+ var datasetObject = {
+ label : dataset.label || null,
+ fillColor : dataset.fillColor,
+ strokeColor : dataset.strokeColor,
+ pointColor : dataset.pointColor,
+ pointStrokeColor : dataset.pointStrokeColor,
+ points : []
+ };
+
+ this.datasets.push(datasetObject);
+
+
+ helpers.each(dataset.data,function(dataPoint,index){
+ //Add a new point for each piece of data, passing any required data to draw.
+ datasetObject.points.push(new this.PointClass({
+ value : dataPoint,
+ label : data.labels[index],
+ datasetLabel: dataset.label,
+ strokeColor : dataset.pointStrokeColor,
+ fillColor : dataset.pointColor,
+ highlightFill : dataset.pointHighlightFill || dataset.pointColor,
+ highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor
+ }));
+ },this);
+
+ this.buildScale(data.labels);
+
+
+ this.eachPoints(function(point, index){
+ helpers.extend(point, {
+ x: this.scale.calculateX(index),
+ y: this.scale.endPoint
+ });
+ point.save();
+ }, this);
+
+ },this);
+
+
+ this.render();
+ },
+ update : function(){
+ this.scale.update();
+ // Reset any highlight colours before updating.
+ helpers.each(this.activeElements, function(activeElement){
+ activeElement.restore(['fillColor', 'strokeColor']);
+ });
+ this.eachPoints(function(point){
+ point.save();
+ });
+ this.render();
+ },
+ eachPoints : function(callback){
+ helpers.each(this.datasets,function(dataset){
+ helpers.each(dataset.points,callback,this);
+ },this);
+ },
+ getPointsAtEvent : function(e){
+ var pointsArray = [],
+ eventPosition = helpers.getRelativePosition(e);
+ helpers.each(this.datasets,function(dataset){
+ helpers.each(dataset.points,function(point){
+ if (point.inRange(eventPosition.x,eventPosition.y)) pointsArray.push(point);
+ });
+ },this);
+ return pointsArray;
+ },
+ buildScale : function(labels){
+ var self = this;
+
+ var dataTotal = function(){
+ var values = [];
+ self.eachPoints(function(point){
+ values.push(point.value);
+ });
+
+ return values;
+ };
+
+ var scaleOptions = {
+ templateString : this.options.scaleLabel,
+ height : this.chart.height,
+ width : this.chart.width,
+ ctx : this.chart.ctx,
+ textColor : this.options.scaleFontColor,
+ fontSize : this.options.scaleFontSize,
+ fontStyle : this.options.scaleFontStyle,
+ fontFamily : this.options.scaleFontFamily,
+ valuesCount : labels.length,
+ beginAtZero : this.options.scaleBeginAtZero,
+ integersOnly : this.options.scaleIntegersOnly,
+ calculateYRange : function(currentHeight){
+ var updatedRanges = helpers.calculateScaleRange(
+ dataTotal(),
+ currentHeight,
+ this.fontSize,
+ this.beginAtZero,
+ this.integersOnly
+ );
+ helpers.extend(this, updatedRanges);
+ },
+ xLabels : labels,
+ font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
+ lineWidth : this.options.scaleLineWidth,
+ lineColor : this.options.scaleLineColor,
+ showHorizontalLines : this.options.scaleShowHorizontalLines,
+ showVerticalLines : this.options.scaleShowVerticalLines,
+ gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
+ gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
+ padding: (this.options.showScale) ? 0 : this.options.pointDotRadius + this.options.pointDotStrokeWidth,
+ showLabels : this.options.scaleShowLabels,
+ display : this.options.showScale
+ };
+
+ if (this.options.scaleOverride){
+ helpers.extend(scaleOptions, {
+ calculateYRange: helpers.noop,
+ steps: this.options.scaleSteps,
+ stepValue: this.options.scaleStepWidth,
+ min: this.options.scaleStartValue,
+ max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
+ });
+ }
+
+
+ this.scale = new Chart.Scale(scaleOptions);
+ },
+ addData : function(valuesArray,label){
+ //Map the values array for each of the datasets
+
+ helpers.each(valuesArray,function(value,datasetIndex){
+ //Add a new point for each piece of data, passing any required data to draw.
+ this.datasets[datasetIndex].points.push(new this.PointClass({
+ value : value,
+ label : label,
+ x: this.scale.calculateX(this.scale.valuesCount+1),
+ y: this.scale.endPoint,
+ strokeColor : this.datasets[datasetIndex].pointStrokeColor,
+ fillColor : this.datasets[datasetIndex].pointColor
+ }));
+ },this);
+
+ this.scale.addXLabel(label);
+ //Then re-render the chart.
+ this.update();
+ },
+ removeData : function(){
+ this.scale.removeXLabel();
+ //Then re-render the chart.
+ helpers.each(this.datasets,function(dataset){
+ dataset.points.shift();
+ },this);
+ this.update();
+ },
+ reflow : function(){
+ var newScaleProps = helpers.extend({
+ height : this.chart.height,
+ width : this.chart.width
+ });
+ this.scale.update(newScaleProps);
+ },
+ draw : function(ease){
+ var easingDecimal = ease || 1;
+ this.clear();
+
+ var ctx = this.chart.ctx;
+
+ // Some helper methods for getting the next/prev points
+ var hasValue = function(item){
+ return item.value !== null;
+ },
+ nextPoint = function(point, collection, index){
+ return helpers.findNextWhere(collection, hasValue, index) || point;
+ },
+ previousPoint = function(point, collection, index){
+ return helpers.findPreviousWhere(collection, hasValue, index) || point;
+ };
+
+ this.scale.draw(easingDecimal);
+
+
+ helpers.each(this.datasets,function(dataset){
+ var pointsWithValues = helpers.where(dataset.points, hasValue);
+
+ //Transition each point first so that the line and point drawing isn't out of sync
+ //We can use this extra loop to calculate the control points of this dataset also in this loop
+
+ helpers.each(dataset.points, function(point, index){
+ if (point.hasValue()){
+ point.transition({
+ y : this.scale.calculateY(point.value),
+ x : this.scale.calculateX(index)
+ }, easingDecimal);
+ }
+ },this);
+
+
+ // Control points need to be calculated in a seperate loop, because we need to know the current x/y of the point
+ // This would cause issues when there is no animation, because the y of the next point would be 0, so beziers would be skewed
+ if (this.options.bezierCurve){
+ helpers.each(pointsWithValues, function(point, index){
+ var tension = (index > 0 && index < pointsWithValues.length - 1) ? this.options.bezierCurveTension : 0;
+ point.controlPoints = helpers.splineCurve(
+ previousPoint(point, pointsWithValues, index),
+ point,
+ nextPoint(point, pointsWithValues, index),
+ tension
+ );
+
+ // Prevent the bezier going outside of the bounds of the graph
+
+ // Cap puter bezier handles to the upper/lower scale bounds
+ if (point.controlPoints.outer.y > this.scale.endPoint){
+ point.controlPoints.outer.y = this.scale.endPoint;
+ }
+ else if (point.controlPoints.outer.y < this.scale.startPoint){
+ point.controlPoints.outer.y = this.scale.startPoint;
+ }
+
+ // Cap inner bezier handles to the upper/lower scale bounds
+ if (point.controlPoints.inner.y > this.scale.endPoint){
+ point.controlPoints.inner.y = this.scale.endPoint;
+ }
+ else if (point.controlPoints.inner.y < this.scale.startPoint){
+ point.controlPoints.inner.y = this.scale.startPoint;
+ }
+ },this);
+ }
+
+
+ //Draw the line between all the points
+ ctx.lineWidth = this.options.datasetStrokeWidth;
+ ctx.strokeStyle = dataset.strokeColor;
+ ctx.beginPath();
+
+ helpers.each(pointsWithValues, function(point, index){
+ if (index === 0){
+ ctx.moveTo(point.x, point.y);
+ }
+ else{
+ if(this.options.bezierCurve){
+ var previous = previousPoint(point, pointsWithValues, index);
+
+ ctx.bezierCurveTo(
+ previous.controlPoints.outer.x,
+ previous.controlPoints.outer.y,
+ point.controlPoints.inner.x,
+ point.controlPoints.inner.y,
+ point.x,
+ point.y
+ );
+ }
+ else{
+ ctx.lineTo(point.x,point.y);
+ }
+ }
+ }, this);
+
+ ctx.stroke();
+
+ if (this.options.datasetFill && pointsWithValues.length > 0){
+ //Round off the line by going to the base of the chart, back to the start, then fill.
+ ctx.lineTo(pointsWithValues[pointsWithValues.length - 1].x, this.scale.endPoint);
+ ctx.lineTo(pointsWithValues[0].x, this.scale.endPoint);
+ ctx.fillStyle = dataset.fillColor;
+ ctx.closePath();
+ ctx.fill();
+ }
+
+ //Now draw the points over the line
+ //A little inefficient double looping, but better than the line
+ //lagging behind the point positions
+ helpers.each(pointsWithValues,function(point){
+ point.draw();
+ });
+ },this);
+ }
+ });
+
+
+}).call(this);
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.PolarArea.js b/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.PolarArea.js
new file mode 100644
index 0000000..8f2b9c5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.PolarArea.js
@@ -0,0 +1,250 @@
+(function(){
+ "use strict";
+
+ var root = this,
+ Chart = root.Chart,
+ //Cache a local reference to Chart.helpers
+ helpers = Chart.helpers;
+
+ var defaultConfig = {
+ //Boolean - Show a backdrop to the scale label
+ scaleShowLabelBackdrop : true,
+
+ //String - The colour of the label backdrop
+ scaleBackdropColor : "rgba(255,255,255,0.75)",
+
+ // Boolean - Whether the scale should begin at zero
+ scaleBeginAtZero : true,
+
+ //Number - The backdrop padding above & below the label in pixels
+ scaleBackdropPaddingY : 2,
+
+ //Number - The backdrop padding to the side of the label in pixels
+ scaleBackdropPaddingX : 2,
+
+ //Boolean - Show line for each value in the scale
+ scaleShowLine : true,
+
+ //Boolean - Stroke a line around each segment in the chart
+ segmentShowStroke : true,
+
+ //String - The colour of the stroke on each segement.
+ segmentStrokeColor : "#fff",
+
+ //Number - The width of the stroke value in pixels
+ segmentStrokeWidth : 2,
+
+ //Number - Amount of animation steps
+ animationSteps : 100,
+
+ //String - Animation easing effect.
+ animationEasing : "easeOutBounce",
+
+ //Boolean - Whether to animate the rotation of the chart
+ animateRotate : true,
+
+ //Boolean - Whether to animate scaling the chart from the centre
+ animateScale : false,
+
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
+ };
+
+
+ Chart.Type.extend({
+ //Passing in a name registers this chart in the Chart namespace
+ name: "PolarArea",
+ //Providing a defaults will also register the deafults in the chart namespace
+ defaults : defaultConfig,
+ //Initialize is fired when the chart is initialized - Data is passed in as a parameter
+ //Config is automatically merged by the core of Chart.js, and is available at this.options
+ initialize: function(data){
+ this.segments = [];
+ //Declare segment class as a chart instance specific class, so it can share props for this instance
+ this.SegmentArc = Chart.Arc.extend({
+ showStroke : this.options.segmentShowStroke,
+ strokeWidth : this.options.segmentStrokeWidth,
+ strokeColor : this.options.segmentStrokeColor,
+ ctx : this.chart.ctx,
+ innerRadius : 0,
+ x : this.chart.width/2,
+ y : this.chart.height/2
+ });
+ this.scale = new Chart.RadialScale({
+ display: this.options.showScale,
+ fontStyle: this.options.scaleFontStyle,
+ fontSize: this.options.scaleFontSize,
+ fontFamily: this.options.scaleFontFamily,
+ fontColor: this.options.scaleFontColor,
+ showLabels: this.options.scaleShowLabels,
+ showLabelBackdrop: this.options.scaleShowLabelBackdrop,
+ backdropColor: this.options.scaleBackdropColor,
+ backdropPaddingY : this.options.scaleBackdropPaddingY,
+ backdropPaddingX: this.options.scaleBackdropPaddingX,
+ lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0,
+ lineColor: this.options.scaleLineColor,
+ lineArc: true,
+ width: this.chart.width,
+ height: this.chart.height,
+ xCenter: this.chart.width/2,
+ yCenter: this.chart.height/2,
+ ctx : this.chart.ctx,
+ templateString: this.options.scaleLabel,
+ valuesCount: data.length
+ });
+
+ this.updateScaleRange(data);
+
+ this.scale.update();
+
+ helpers.each(data,function(segment,index){
+ this.addData(segment,index,true);
+ },this);
+
+ //Set up tooltip events on the chart
+ if (this.options.showTooltips){
+ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
+ var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];
+ helpers.each(this.segments,function(segment){
+ segment.restore(["fillColor"]);
+ });
+ helpers.each(activeSegments,function(activeSegment){
+ activeSegment.fillColor = activeSegment.highlightColor;
+ });
+ this.showTooltip(activeSegments);
+ });
+ }
+
+ this.render();
+ },
+ getSegmentsAtEvent : function(e){
+ var segmentsArray = [];
+
+ var location = helpers.getRelativePosition(e);
+
+ helpers.each(this.segments,function(segment){
+ if (segment.inRange(location.x,location.y)) segmentsArray.push(segment);
+ },this);
+ return segmentsArray;
+ },
+ addData : function(segment, atIndex, silent){
+ var index = atIndex || this.segments.length;
+
+ this.segments.splice(index, 0, new this.SegmentArc({
+ fillColor: segment.color,
+ highlightColor: segment.highlight || segment.color,
+ label: segment.label,
+ value: segment.value,
+ outerRadius: (this.options.animateScale) ? 0 : this.scale.calculateCenterOffset(segment.value),
+ circumference: (this.options.animateRotate) ? 0 : this.scale.getCircumference(),
+ startAngle: Math.PI * 1.5
+ }));
+ if (!silent){
+ this.reflow();
+ this.update();
+ }
+ },
+ removeData: function(atIndex){
+ var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1;
+ this.segments.splice(indexToDelete, 1);
+ this.reflow();
+ this.update();
+ },
+ calculateTotal: function(data){
+ this.total = 0;
+ helpers.each(data,function(segment){
+ this.total += segment.value;
+ },this);
+ this.scale.valuesCount = this.segments.length;
+ },
+ updateScaleRange: function(datapoints){
+ var valuesArray = [];
+ helpers.each(datapoints,function(segment){
+ valuesArray.push(segment.value);
+ });
+
+ var scaleSizes = (this.options.scaleOverride) ?
+ {
+ steps: this.options.scaleSteps,
+ stepValue: this.options.scaleStepWidth,
+ min: this.options.scaleStartValue,
+ max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
+ } :
+ helpers.calculateScaleRange(
+ valuesArray,
+ helpers.min([this.chart.width, this.chart.height])/2,
+ this.options.scaleFontSize,
+ this.options.scaleBeginAtZero,
+ this.options.scaleIntegersOnly
+ );
+
+ helpers.extend(
+ this.scale,
+ scaleSizes,
+ {
+ size: helpers.min([this.chart.width, this.chart.height]),
+ xCenter: this.chart.width/2,
+ yCenter: this.chart.height/2
+ }
+ );
+
+ },
+ update : function(){
+ this.calculateTotal(this.segments);
+
+ helpers.each(this.segments,function(segment){
+ segment.save();
+ });
+
+ this.reflow();
+ this.render();
+ },
+ reflow : function(){
+ helpers.extend(this.SegmentArc.prototype,{
+ x : this.chart.width/2,
+ y : this.chart.height/2
+ });
+ this.updateScaleRange(this.segments);
+ this.scale.update();
+
+ helpers.extend(this.scale,{
+ xCenter: this.chart.width/2,
+ yCenter: this.chart.height/2
+ });
+
+ helpers.each(this.segments, function(segment){
+ segment.update({
+ outerRadius : this.scale.calculateCenterOffset(segment.value)
+ });
+ }, this);
+
+ },
+ draw : function(ease){
+ var easingDecimal = ease || 1;
+ //Clear & draw the canvas
+ this.clear();
+ helpers.each(this.segments,function(segment, index){
+ segment.transition({
+ circumference : this.scale.getCircumference(),
+ outerRadius : this.scale.calculateCenterOffset(segment.value)
+ },easingDecimal);
+
+ segment.endAngle = segment.startAngle + segment.circumference;
+
+ // If we've removed the first segment we need to set the first one to
+ // start at the top.
+ if (index === 0){
+ segment.startAngle = Math.PI * 1.5;
+ }
+
+ //Check to see if it's the last segment, if not get the next and update the start angle
+ if (index < this.segments.length - 1){
+ this.segments[index+1].startAngle = segment.endAngle;
+ }
+ segment.draw();
+ }, this);
+ this.scale.draw();
+ }
+ });
+
+}).call(this);
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Radar.js b/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Radar.js
new file mode 100644
index 0000000..134fd2d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/Chart.js/src/Chart.Radar.js
@@ -0,0 +1,343 @@
+(function(){
+ "use strict";
+
+ var root = this,
+ Chart = root.Chart,
+ helpers = Chart.helpers;
+
+
+
+ Chart.Type.extend({
+ name: "Radar",
+ defaults:{
+ //Boolean - Whether to show lines for each scale point
+ scaleShowLine : true,
+
+ //Boolean - Whether we show the angle lines out of the radar
+ angleShowLineOut : true,
+
+ //Boolean - Whether to show labels on the scale
+ scaleShowLabels : false,
+
+ // Boolean - Whether the scale should begin at zero
+ scaleBeginAtZero : true,
+
+ //String - Colour of the angle line
+ angleLineColor : "rgba(0,0,0,.1)",
+
+ //Number - Pixel width of the angle line
+ angleLineWidth : 1,
+
+ //String - Point label font declaration
+ pointLabelFontFamily : "'Arial'",
+
+ //String - Point label font weight
+ pointLabelFontStyle : "normal",
+
+ //Number - Point label font size in pixels
+ pointLabelFontSize : 10,
+
+ //String - Point label font colour
+ pointLabelFontColor : "#666",
+
+ //Boolean - Whether to show a dot for each point
+ pointDot : true,
+
+ //Number - Radius of each point dot in pixels
+ pointDotRadius : 3,
+
+ //Number - Pixel width of point dot stroke
+ pointDotStrokeWidth : 1,
+
+ //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
+ pointHitDetectionRadius : 20,
+
+ //Boolean - Whether to show a stroke for datasets
+ datasetStroke : true,
+
+ //Number - Pixel width of dataset stroke
+ datasetStrokeWidth : 2,
+
+ //Boolean - Whether to fill the dataset with a colour
+ datasetFill : true,
+
+ //String - A legend template
+ legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
+
+ },
+
+ initialize: function(data){
+ this.PointClass = Chart.Point.extend({
+ strokeWidth : this.options.pointDotStrokeWidth,
+ radius : this.options.pointDotRadius,
+ display: this.options.pointDot,
+ hitDetectionRadius : this.options.pointHitDetectionRadius,
+ ctx : this.chart.ctx
+ });
+
+ this.datasets = [];
+
+ this.buildScale(data);
+
+ //Set up tooltip events on the chart
+ if (this.options.showTooltips){
+ helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
+ var activePointsCollection = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
+
+ this.eachPoints(function(point){
+ point.restore(['fillColor', 'strokeColor']);
+ });
+ helpers.each(activePointsCollection, function(activePoint){
+ activePoint.fillColor = activePoint.highlightFill;
+ activePoint.strokeColor = activePoint.highlightStroke;
+ });
+
+ this.showTooltip(activePointsCollection);
+ });
+ }
+
+ //Iterate through each of the datasets, and build this into a property of the chart
+ helpers.each(data.datasets,function(dataset){
+
+ var datasetObject = {
+ label: dataset.label || null,
+ fillColor : dataset.fillColor,
+ strokeColor : dataset.strokeColor,
+ pointColor : dataset.pointColor,
+ pointStrokeColor : dataset.pointStrokeColor,
+ points : []
+ };
+
+ this.datasets.push(datasetObject);
+
+ helpers.each(dataset.data,function(dataPoint,index){
+ //Add a new point for each piece of data, passing any required data to draw.
+ var pointPosition;
+ if (!this.scale.animation){
+ pointPosition = this.scale.getPointPosition(index, this.scale.calculateCenterOffset(dataPoint));
+ }
+ datasetObject.points.push(new this.PointClass({
+ value : dataPoint,
+ label : data.labels[index],
+ datasetLabel: dataset.label,
+ x: (this.options.animation) ? this.scale.xCenter : pointPosition.x,
+ y: (this.options.animation) ? this.scale.yCenter : pointPosition.y,
+ strokeColor : dataset.pointStrokeColor,
+ fillColor : dataset.pointColor,
+ highlightFill : dataset.pointHighlightFill || dataset.pointColor,
+ highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor
+ }));
+ },this);
+
+ },this);
+
+ this.render();
+ },
+ eachPoints : function(callback){
+ helpers.each(this.datasets,function(dataset){
+ helpers.each(dataset.points,callback,this);
+ },this);
+ },
+
+ getPointsAtEvent : function(evt){
+ var mousePosition = helpers.getRelativePosition(evt),
+ fromCenter = helpers.getAngleFromPoint({
+ x: this.scale.xCenter,
+ y: this.scale.yCenter
+ }, mousePosition);
+
+ var anglePerIndex = (Math.PI * 2) /this.scale.valuesCount,
+ pointIndex = Math.round((fromCenter.angle - Math.PI * 1.5) / anglePerIndex),
+ activePointsCollection = [];
+
+ // If we're at the top, make the pointIndex 0 to get the first of the array.
+ if (pointIndex >= this.scale.valuesCount || pointIndex < 0){
+ pointIndex = 0;
+ }
+
+ if (fromCenter.distance <= this.scale.drawingArea){
+ helpers.each(this.datasets, function(dataset){
+ activePointsCollection.push(dataset.points[pointIndex]);
+ });
+ }
+
+ return activePointsCollection;
+ },
+
+ buildScale : function(data){
+ this.scale = new Chart.RadialScale({
+ display: this.options.showScale,
+ fontStyle: this.options.scaleFontStyle,
+ fontSize: this.options.scaleFontSize,
+ fontFamily: this.options.scaleFontFamily,
+ fontColor: this.options.scaleFontColor,
+ showLabels: this.options.scaleShowLabels,
+ showLabelBackdrop: this.options.scaleShowLabelBackdrop,
+ backdropColor: this.options.scaleBackdropColor,
+ backdropPaddingY : this.options.scaleBackdropPaddingY,
+ backdropPaddingX: this.options.scaleBackdropPaddingX,
+ lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0,
+ lineColor: this.options.scaleLineColor,
+ angleLineColor : this.options.angleLineColor,
+ angleLineWidth : (this.options.angleShowLineOut) ? this.options.angleLineWidth : 0,
+ // Point labels at the edge of each line
+ pointLabelFontColor : this.options.pointLabelFontColor,
+ pointLabelFontSize : this.options.pointLabelFontSize,
+ pointLabelFontFamily : this.options.pointLabelFontFamily,
+ pointLabelFontStyle : this.options.pointLabelFontStyle,
+ height : this.chart.height,
+ width: this.chart.width,
+ xCenter: this.chart.width/2,
+ yCenter: this.chart.height/2,
+ ctx : this.chart.ctx,
+ templateString: this.options.scaleLabel,
+ labels: data.labels,
+ valuesCount: data.datasets[0].data.length
+ });
+
+ this.scale.setScaleSize();
+ this.updateScaleRange(data.datasets);
+ this.scale.buildYLabels();
+ },
+ updateScaleRange: function(datasets){
+ var valuesArray = (function(){
+ var totalDataArray = [];
+ helpers.each(datasets,function(dataset){
+ if (dataset.data){
+ totalDataArray = totalDataArray.concat(dataset.data);
+ }
+ else {
+ helpers.each(dataset.points, function(point){
+ totalDataArray.push(point.value);
+ });
+ }
+ });
+ return totalDataArray;
+ })();
+
+
+ var scaleSizes = (this.options.scaleOverride) ?
+ {
+ steps: this.options.scaleSteps,
+ stepValue: this.options.scaleStepWidth,
+ min: this.options.scaleStartValue,
+ max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
+ } :
+ helpers.calculateScaleRange(
+ valuesArray,
+ helpers.min([this.chart.width, this.chart.height])/2,
+ this.options.scaleFontSize,
+ this.options.scaleBeginAtZero,
+ this.options.scaleIntegersOnly
+ );
+
+ helpers.extend(
+ this.scale,
+ scaleSizes
+ );
+
+ },
+ addData : function(valuesArray,label){
+ //Map the values array for each of the datasets
+ this.scale.valuesCount++;
+ helpers.each(valuesArray,function(value,datasetIndex){
+ var pointPosition = this.scale.getPointPosition(this.scale.valuesCount, this.scale.calculateCenterOffset(value));
+ this.datasets[datasetIndex].points.push(new this.PointClass({
+ value : value,
+ label : label,
+ x: pointPosition.x,
+ y: pointPosition.y,
+ strokeColor : this.datasets[datasetIndex].pointStrokeColor,
+ fillColor : this.datasets[datasetIndex].pointColor
+ }));
+ },this);
+
+ this.scale.labels.push(label);
+
+ this.reflow();
+
+ this.update();
+ },
+ removeData : function(){
+ this.scale.valuesCount--;
+ this.scale.labels.shift();
+ helpers.each(this.datasets,function(dataset){
+ dataset.points.shift();
+ },this);
+ this.reflow();
+ this.update();
+ },
+ update : function(){
+ this.eachPoints(function(point){
+ point.save();
+ });
+ this.reflow();
+ this.render();
+ },
+ reflow: function(){
+ helpers.extend(this.scale, {
+ width : this.chart.width,
+ height: this.chart.height,
+ size : helpers.min([this.chart.width, this.chart.height]),
+ xCenter: this.chart.width/2,
+ yCenter: this.chart.height/2
+ });
+ this.updateScaleRange(this.datasets);
+ this.scale.setScaleSize();
+ this.scale.buildYLabels();
+ },
+ draw : function(ease){
+ var easeDecimal = ease || 1,
+ ctx = this.chart.ctx;
+ this.clear();
+ this.scale.draw();
+
+ helpers.each(this.datasets,function(dataset){
+
+ //Transition each point first so that the line and point drawing isn't out of sync
+ helpers.each(dataset.points,function(point,index){
+ if (point.hasValue()){
+ point.transition(this.scale.getPointPosition(index, this.scale.calculateCenterOffset(point.value)), easeDecimal);
+ }
+ },this);
+
+
+
+ //Draw the line between all the points
+ ctx.lineWidth = this.options.datasetStrokeWidth;
+ ctx.strokeStyle = dataset.strokeColor;
+ ctx.beginPath();
+ helpers.each(dataset.points,function(point,index){
+ if (index === 0){
+ ctx.moveTo(point.x,point.y);
+ }
+ else{
+ ctx.lineTo(point.x,point.y);
+ }
+ },this);
+ ctx.closePath();
+ ctx.stroke();
+
+ ctx.fillStyle = dataset.fillColor;
+ ctx.fill();
+
+ //Now draw the points over the line
+ //A little inefficient double looping, but better than the line
+ //lagging behind the point positions
+ helpers.each(dataset.points,function(point){
+ if (point.hasValue()){
+ point.draw();
+ }
+ });
+
+ },this);
+
+ }
+
+ });
+
+
+
+
+
+}).call(this);
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-animate/.bower.json b/xos-apps/auto-scale/gui/src/vendor/angular-animate/.bower.json
new file mode 100644
index 0000000..fd1a3db
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-animate/.bower.json
@@ -0,0 +1,19 @@
+{
+ "name": "angular-animate",
+ "version": "1.4.8",
+ "main": "./angular-animate.js",
+ "ignore": [],
+ "dependencies": {
+ "angular": "1.4.8"
+ },
+ "homepage": "https://github.com/angular/bower-angular-animate",
+ "_release": "1.4.8",
+ "_resolution": {
+ "type": "version",
+ "tag": "v1.4.8",
+ "commit": "cc1d9740059f5e8fd43abf0e2e80695d43b3b6b1"
+ },
+ "_source": "git://github.com/angular/bower-angular-animate.git",
+ "_target": "~1.4.8",
+ "_originalSource": "angular-animate"
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-animate/README.md b/xos-apps/auto-scale/gui/src/vendor/angular-animate/README.md
new file mode 100644
index 0000000..8313da6
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-animate/README.md
@@ -0,0 +1,68 @@
+# packaged angular-animate
+
+This repo is for distribution on `npm` and `bower`. The source for this module is in the
+[main AngularJS repo](https://github.com/angular/angular.js/tree/master/src/ngAnimate).
+Please file issues and pull requests against that repo.
+
+## Install
+
+You can install this package either with `npm` or with `bower`.
+
+### npm
+
+```shell
+npm install angular-animate
+```
+
+Then add `ngAnimate` as a dependency for your app:
+
+```javascript
+angular.module('myApp', [require('angular-animate')]);
+```
+
+### bower
+
+```shell
+bower install angular-animate
+```
+
+Then add a `<script>` to your `index.html`:
+
+```html
+<script src="/bower_components/angular-animate/angular-animate.js"></script>
+```
+
+Then add `ngAnimate` as a dependency for your app:
+
+```javascript
+angular.module('myApp', ['ngAnimate']);
+```
+
+## Documentation
+
+Documentation is available on the
+[AngularJS docs site](http://docs.angularjs.org/api/ngAnimate).
+
+## License
+
+The MIT License
+
+Copyright (c) 2010-2015 Google, Inc. http://angularjs.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-animate/angular-animate.js b/xos-apps/auto-scale/gui/src/vendor/angular-animate/angular-animate.js
new file mode 100644
index 0000000..3061004
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-animate/angular-animate.js
@@ -0,0 +1,3930 @@
+/**
+ * @license AngularJS v1.4.8
+ * (c) 2010-2015 Google, Inc. http://angularjs.org
+ * License: MIT
+ */
+(function(window, angular, undefined) {'use strict';
+
+/* jshint ignore:start */
+var noop = angular.noop;
+var extend = angular.extend;
+var jqLite = angular.element;
+var forEach = angular.forEach;
+var isArray = angular.isArray;
+var isString = angular.isString;
+var isObject = angular.isObject;
+var isUndefined = angular.isUndefined;
+var isDefined = angular.isDefined;
+var isFunction = angular.isFunction;
+var isElement = angular.isElement;
+
+var ELEMENT_NODE = 1;
+var COMMENT_NODE = 8;
+
+var ADD_CLASS_SUFFIX = '-add';
+var REMOVE_CLASS_SUFFIX = '-remove';
+var EVENT_CLASS_PREFIX = 'ng-';
+var ACTIVE_CLASS_SUFFIX = '-active';
+
+var NG_ANIMATE_CLASSNAME = 'ng-animate';
+var NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren';
+
+// Detect proper transitionend/animationend event names.
+var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;
+
+// If unprefixed events are not supported but webkit-prefixed are, use the latter.
+// Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
+// Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`
+// but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
+// Register both events in case `window.onanimationend` is not supported because of that,
+// do the same for `transitionend` as Safari is likely to exhibit similar behavior.
+// Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
+// therefore there is no reason to test anymore for other vendor prefixes:
+// http://caniuse.com/#search=transition
+if (isUndefined(window.ontransitionend) && isDefined(window.onwebkittransitionend)) {
+ CSS_PREFIX = '-webkit-';
+ TRANSITION_PROP = 'WebkitTransition';
+ TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
+} else {
+ TRANSITION_PROP = 'transition';
+ TRANSITIONEND_EVENT = 'transitionend';
+}
+
+if (isUndefined(window.onanimationend) && isDefined(window.onwebkitanimationend)) {
+ CSS_PREFIX = '-webkit-';
+ ANIMATION_PROP = 'WebkitAnimation';
+ ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
+} else {
+ ANIMATION_PROP = 'animation';
+ ANIMATIONEND_EVENT = 'animationend';
+}
+
+var DURATION_KEY = 'Duration';
+var PROPERTY_KEY = 'Property';
+var DELAY_KEY = 'Delay';
+var TIMING_KEY = 'TimingFunction';
+var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';
+var ANIMATION_PLAYSTATE_KEY = 'PlayState';
+var SAFE_FAST_FORWARD_DURATION_VALUE = 9999;
+
+var ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY;
+var ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY;
+var TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY;
+var TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY;
+
+var isPromiseLike = function(p) {
+ return p && p.then ? true : false;
+};
+
+function assertArg(arg, name, reason) {
+ if (!arg) {
+ throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
+ }
+ return arg;
+}
+
+function mergeClasses(a,b) {
+ if (!a && !b) return '';
+ if (!a) return b;
+ if (!b) return a;
+ if (isArray(a)) a = a.join(' ');
+ if (isArray(b)) b = b.join(' ');
+ return a + ' ' + b;
+}
+
+function packageStyles(options) {
+ var styles = {};
+ if (options && (options.to || options.from)) {
+ styles.to = options.to;
+ styles.from = options.from;
+ }
+ return styles;
+}
+
+function pendClasses(classes, fix, isPrefix) {
+ var className = '';
+ classes = isArray(classes)
+ ? classes
+ : classes && isString(classes) && classes.length
+ ? classes.split(/\s+/)
+ : [];
+ forEach(classes, function(klass, i) {
+ if (klass && klass.length > 0) {
+ className += (i > 0) ? ' ' : '';
+ className += isPrefix ? fix + klass
+ : klass + fix;
+ }
+ });
+ return className;
+}
+
+function removeFromArray(arr, val) {
+ var index = arr.indexOf(val);
+ if (val >= 0) {
+ arr.splice(index, 1);
+ }
+}
+
+function stripCommentsFromElement(element) {
+ if (element instanceof jqLite) {
+ switch (element.length) {
+ case 0:
+ return [];
+ break;
+
+ case 1:
+ // there is no point of stripping anything if the element
+ // is the only element within the jqLite wrapper.
+ // (it's important that we retain the element instance.)
+ if (element[0].nodeType === ELEMENT_NODE) {
+ return element;
+ }
+ break;
+
+ default:
+ return jqLite(extractElementNode(element));
+ break;
+ }
+ }
+
+ if (element.nodeType === ELEMENT_NODE) {
+ return jqLite(element);
+ }
+}
+
+function extractElementNode(element) {
+ if (!element[0]) return element;
+ for (var i = 0; i < element.length; i++) {
+ var elm = element[i];
+ if (elm.nodeType == ELEMENT_NODE) {
+ return elm;
+ }
+ }
+}
+
+function $$addClass($$jqLite, element, className) {
+ forEach(element, function(elm) {
+ $$jqLite.addClass(elm, className);
+ });
+}
+
+function $$removeClass($$jqLite, element, className) {
+ forEach(element, function(elm) {
+ $$jqLite.removeClass(elm, className);
+ });
+}
+
+function applyAnimationClassesFactory($$jqLite) {
+ return function(element, options) {
+ if (options.addClass) {
+ $$addClass($$jqLite, element, options.addClass);
+ options.addClass = null;
+ }
+ if (options.removeClass) {
+ $$removeClass($$jqLite, element, options.removeClass);
+ options.removeClass = null;
+ }
+ }
+}
+
+function prepareAnimationOptions(options) {
+ options = options || {};
+ if (!options.$$prepared) {
+ var domOperation = options.domOperation || noop;
+ options.domOperation = function() {
+ options.$$domOperationFired = true;
+ domOperation();
+ domOperation = noop;
+ };
+ options.$$prepared = true;
+ }
+ return options;
+}
+
+function applyAnimationStyles(element, options) {
+ applyAnimationFromStyles(element, options);
+ applyAnimationToStyles(element, options);
+}
+
+function applyAnimationFromStyles(element, options) {
+ if (options.from) {
+ element.css(options.from);
+ options.from = null;
+ }
+}
+
+function applyAnimationToStyles(element, options) {
+ if (options.to) {
+ element.css(options.to);
+ options.to = null;
+ }
+}
+
+function mergeAnimationOptions(element, target, newOptions) {
+ var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || '');
+ var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || '');
+ var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove);
+
+ if (newOptions.preparationClasses) {
+ target.preparationClasses = concatWithSpace(newOptions.preparationClasses, target.preparationClasses);
+ delete newOptions.preparationClasses;
+ }
+
+ // noop is basically when there is no callback; otherwise something has been set
+ var realDomOperation = target.domOperation !== noop ? target.domOperation : null;
+
+ extend(target, newOptions);
+
+ // TODO(matsko or sreeramu): proper fix is to maintain all animation callback in array and call at last,but now only leave has the callback so no issue with this.
+ if (realDomOperation) {
+ target.domOperation = realDomOperation;
+ }
+
+ if (classes.addClass) {
+ target.addClass = classes.addClass;
+ } else {
+ target.addClass = null;
+ }
+
+ if (classes.removeClass) {
+ target.removeClass = classes.removeClass;
+ } else {
+ target.removeClass = null;
+ }
+
+ return target;
+}
+
+function resolveElementClasses(existing, toAdd, toRemove) {
+ var ADD_CLASS = 1;
+ var REMOVE_CLASS = -1;
+
+ var flags = {};
+ existing = splitClassesToLookup(existing);
+
+ toAdd = splitClassesToLookup(toAdd);
+ forEach(toAdd, function(value, key) {
+ flags[key] = ADD_CLASS;
+ });
+
+ toRemove = splitClassesToLookup(toRemove);
+ forEach(toRemove, function(value, key) {
+ flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS;
+ });
+
+ var classes = {
+ addClass: '',
+ removeClass: ''
+ };
+
+ forEach(flags, function(val, klass) {
+ var prop, allow;
+ if (val === ADD_CLASS) {
+ prop = 'addClass';
+ allow = !existing[klass];
+ } else if (val === REMOVE_CLASS) {
+ prop = 'removeClass';
+ allow = existing[klass];
+ }
+ if (allow) {
+ if (classes[prop].length) {
+ classes[prop] += ' ';
+ }
+ classes[prop] += klass;
+ }
+ });
+
+ function splitClassesToLookup(classes) {
+ if (isString(classes)) {
+ classes = classes.split(' ');
+ }
+
+ var obj = {};
+ forEach(classes, function(klass) {
+ // sometimes the split leaves empty string values
+ // incase extra spaces were applied to the options
+ if (klass.length) {
+ obj[klass] = true;
+ }
+ });
+ return obj;
+ }
+
+ return classes;
+}
+
+function getDomNode(element) {
+ return (element instanceof angular.element) ? element[0] : element;
+}
+
+function applyGeneratedPreparationClasses(element, event, options) {
+ var classes = '';
+ if (event) {
+ classes = pendClasses(event, EVENT_CLASS_PREFIX, true);
+ }
+ if (options.addClass) {
+ classes = concatWithSpace(classes, pendClasses(options.addClass, ADD_CLASS_SUFFIX));
+ }
+ if (options.removeClass) {
+ classes = concatWithSpace(classes, pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX));
+ }
+ if (classes.length) {
+ options.preparationClasses = classes;
+ element.addClass(classes);
+ }
+}
+
+function clearGeneratedClasses(element, options) {
+ if (options.preparationClasses) {
+ element.removeClass(options.preparationClasses);
+ options.preparationClasses = null;
+ }
+ if (options.activeClasses) {
+ element.removeClass(options.activeClasses);
+ options.activeClasses = null;
+ }
+}
+
+function blockTransitions(node, duration) {
+ // we use a negative delay value since it performs blocking
+ // yet it doesn't kill any existing transitions running on the
+ // same element which makes this safe for class-based animations
+ var value = duration ? '-' + duration + 's' : '';
+ applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]);
+ return [TRANSITION_DELAY_PROP, value];
+}
+
+function blockKeyframeAnimations(node, applyBlock) {
+ var value = applyBlock ? 'paused' : '';
+ var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY;
+ applyInlineStyle(node, [key, value]);
+ return [key, value];
+}
+
+function applyInlineStyle(node, styleTuple) {
+ var prop = styleTuple[0];
+ var value = styleTuple[1];
+ node.style[prop] = value;
+}
+
+function concatWithSpace(a,b) {
+ if (!a) return b;
+ if (!b) return a;
+ return a + ' ' + b;
+}
+
+var $$rAFSchedulerFactory = ['$$rAF', function($$rAF) {
+ var queue, cancelFn;
+
+ function scheduler(tasks) {
+ // we make a copy since RAFScheduler mutates the state
+ // of the passed in array variable and this would be difficult
+ // to track down on the outside code
+ queue = queue.concat(tasks);
+ nextTick();
+ }
+
+ queue = scheduler.queue = [];
+
+ /* waitUntilQuiet does two things:
+ * 1. It will run the FINAL `fn` value only when an uncancelled RAF has passed through
+ * 2. It will delay the next wave of tasks from running until the quiet `fn` has run.
+ *
+ * The motivation here is that animation code can request more time from the scheduler
+ * before the next wave runs. This allows for certain DOM properties such as classes to
+ * be resolved in time for the next animation to run.
+ */
+ scheduler.waitUntilQuiet = function(fn) {
+ if (cancelFn) cancelFn();
+
+ cancelFn = $$rAF(function() {
+ cancelFn = null;
+ fn();
+ nextTick();
+ });
+ };
+
+ return scheduler;
+
+ function nextTick() {
+ if (!queue.length) return;
+
+ var items = queue.shift();
+ for (var i = 0; i < items.length; i++) {
+ items[i]();
+ }
+
+ if (!cancelFn) {
+ $$rAF(function() {
+ if (!cancelFn) nextTick();
+ });
+ }
+ }
+}];
+
+var $$AnimateChildrenDirective = [function() {
+ return function(scope, element, attrs) {
+ var val = attrs.ngAnimateChildren;
+ if (angular.isString(val) && val.length === 0) { //empty attribute
+ element.data(NG_ANIMATE_CHILDREN_DATA, true);
+ } else {
+ attrs.$observe('ngAnimateChildren', function(value) {
+ value = value === 'on' || value === 'true';
+ element.data(NG_ANIMATE_CHILDREN_DATA, value);
+ });
+ }
+ };
+}];
+
+var ANIMATE_TIMER_KEY = '$$animateCss';
+
+/**
+ * @ngdoc service
+ * @name $animateCss
+ * @kind object
+ *
+ * @description
+ * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes
+ * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT
+ * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or
+ * directives to create more complex animations that can be purely driven using CSS code.
+ *
+ * Note that only browsers that support CSS transitions and/or keyframe animations are capable of
+ * rendering animations triggered via `$animateCss` (bad news for IE9 and lower).
+ *
+ * ## Usage
+ * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that
+ * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however,
+ * any automatic control over cancelling animations and/or preventing animations from being run on
+ * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to
+ * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger
+ * the CSS animation.
+ *
+ * The example below shows how we can create a folding animation on an element using `ng-if`:
+ *
+ * ```html
+ * <!-- notice the `fold-animation` CSS class -->
+ * <div ng-if="onOff" class="fold-animation">
+ * This element will go BOOM
+ * </div>
+ * <button ng-click="onOff=true">Fold In</button>
+ * ```
+ *
+ * Now we create the **JavaScript animation** that will trigger the CSS transition:
+ *
+ * ```js
+ * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
+ * return {
+ * enter: function(element, doneFn) {
+ * var height = element[0].offsetHeight;
+ * return $animateCss(element, {
+ * from: { height:'0px' },
+ * to: { height:height + 'px' },
+ * duration: 1 // one second
+ * });
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * ## More Advanced Uses
+ *
+ * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks
+ * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code.
+ *
+ * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation,
+ * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with
+ * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order
+ * to provide a working animation that will run in CSS.
+ *
+ * The example below showcases a more advanced version of the `.fold-animation` from the example above:
+ *
+ * ```js
+ * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
+ * return {
+ * enter: function(element, doneFn) {
+ * var height = element[0].offsetHeight;
+ * return $animateCss(element, {
+ * addClass: 'red large-text pulse-twice',
+ * easing: 'ease-out',
+ * from: { height:'0px' },
+ * to: { height:height + 'px' },
+ * duration: 1 // one second
+ * });
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * Since we're adding/removing CSS classes then the CSS transition will also pick those up:
+ *
+ * ```css
+ * /* since a hardcoded duration value of 1 was provided in the JavaScript animation code,
+ * the CSS classes below will be transitioned despite them being defined as regular CSS classes */
+ * .red { background:red; }
+ * .large-text { font-size:20px; }
+ *
+ * /* we can also use a keyframe animation and $animateCss will make it work alongside the transition */
+ * .pulse-twice {
+ * animation: 0.5s pulse linear 2;
+ * -webkit-animation: 0.5s pulse linear 2;
+ * }
+ *
+ * @keyframes pulse {
+ * from { transform: scale(0.5); }
+ * to { transform: scale(1.5); }
+ * }
+ *
+ * @-webkit-keyframes pulse {
+ * from { -webkit-transform: scale(0.5); }
+ * to { -webkit-transform: scale(1.5); }
+ * }
+ * ```
+ *
+ * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen.
+ *
+ * ## How the Options are handled
+ *
+ * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation
+ * works with the options provided. Say for example we were adding a class that contained a keyframe value and we wanted to also animate some inline
+ * styles using the `from` and `to` properties.
+ *
+ * ```js
+ * var animator = $animateCss(element, {
+ * from: { background:'red' },
+ * to: { background:'blue' }
+ * });
+ * animator.start();
+ * ```
+ *
+ * ```css
+ * .rotating-animation {
+ * animation:0.5s rotate linear;
+ * -webkit-animation:0.5s rotate linear;
+ * }
+ *
+ * @keyframes rotate {
+ * from { transform: rotate(0deg); }
+ * to { transform: rotate(360deg); }
+ * }
+ *
+ * @-webkit-keyframes rotate {
+ * from { -webkit-transform: rotate(0deg); }
+ * to { -webkit-transform: rotate(360deg); }
+ * }
+ * ```
+ *
+ * The missing pieces here are that we do not have a transition set (within the CSS code nor within the `$animateCss` options) and the duration of the animation is
+ * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition
+ * style matching the duration detected from the keyframe style (which is present in the CSS class that is being added) and then prepare both the transition
+ * and keyframe animations to run in parallel on the element. Then when the animation is underway the provided `from` and `to` CSS styles will be applied
+ * and spread across the transition and keyframe animation.
+ *
+ * ## What is returned
+ *
+ * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually
+ * start the animation. All that is going on here is that the element is being prepared for the animation (which means that the generated CSS classes are
+ * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties:
+ *
+ * ```js
+ * var animator = $animateCss(element, { ... });
+ * ```
+ *
+ * Now what do the contents of our `animator` variable look like:
+ *
+ * ```js
+ * {
+ * // starts the animation
+ * start: Function,
+ *
+ * // ends (aborts) the animation
+ * end: Function
+ * }
+ * ```
+ *
+ * To actually start the animation we need to run `animation.start()` which will then return a promise that we can hook into to detect when the animation ends.
+ * If we choose not to run the animation then we MUST run `animation.end()` to perform a cleanup on the element (since some CSS classes and stlyes may have been
+ * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties
+ * and that changing them will not reconfigure the parameters of the animation.
+ *
+ * ### runner.done() vs runner.then()
+ * It is documented that `animation.start()` will return a promise object and this is true, however, there is also an additional method available on the
+ * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**.
+ * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()`
+ * unless you really need a digest to kick off afterwards.
+ *
+ * Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss
+ * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code).
+ * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works.
+ *
+ * @param {DOMElement} element the element that will be animated
+ * @param {object} options the animation-related options that will be applied during the animation
+ *
+ * * `event` - The DOM event (e.g. enter, leave, move). When used, a generated CSS class of `ng-EVENT` and `ng-EVENT-active` will be applied
+ * to the element during the animation. Multiple events can be provided when spaces are used as a separator. (Note that this will not perform any DOM operation.)
+ * * `structural` - Indicates that the `ng-` prefix will be added to the event class. Setting to `false` or omitting will turn `ng-EVENT` and
+ * `ng-EVENT-active` in `EVENT` and `EVENT-active`. Unused if `event` is omitted.
+ * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both).
+ * * `transitionStyle` - The raw CSS transition style that will be used (e.g. `1s linear all`).
+ * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`).
+ * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation.
+ * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
+ * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation.
+ * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation.
+ * * `duration` - A number value representing the total duration of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `0`
+ * is provided then the animation will be skipped entirely.
+ * * `delay` - A number value representing the total delay of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `true` is
+ * used then whatever delay value is detected from the CSS classes will be mirrored on the elements styles (e.g. by setting delay true then the style value
+ * of the element will be `transition-delay: DETECTED_VALUE`). Using `true` is useful when you want the CSS classes and inline styles to all share the same
+ * CSS delay value.
+ * * `stagger` - A numeric time value representing the delay between successively animated elements
+ * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.})
+ * * `staggerIndex` - The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item in the stagger; therefore when a
+ * * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`)
+ * * `applyClassesEarly` - Whether or not the classes being added or removed will be used when detecting the animation. This is set by `$animate` when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. (Note that this will prevent any transitions from occuring on the classes being added and removed.)
+ * * `cleanupStyles` - Whether or not the provided `from` and `to` styles will be removed once
+ * the animation is closed. This is useful for when the styles are used purely for the sake of
+ * the animation and do not have a lasting visual effect on the element (e.g. a colapse and open animation).
+ * By default this value is set to `false`.
+ *
+ * @return {object} an object with start and end methods and details about the animation.
+ *
+ * * `start` - The method to start the animation. This will return a `Promise` when called.
+ * * `end` - This method will cancel the animation and remove all applied CSS classes and styles.
+ */
+var ONE_SECOND = 1000;
+var BASE_TEN = 10;
+
+var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
+var CLOSING_TIME_BUFFER = 1.5;
+
+var DETECT_CSS_PROPERTIES = {
+ transitionDuration: TRANSITION_DURATION_PROP,
+ transitionDelay: TRANSITION_DELAY_PROP,
+ transitionProperty: TRANSITION_PROP + PROPERTY_KEY,
+ animationDuration: ANIMATION_DURATION_PROP,
+ animationDelay: ANIMATION_DELAY_PROP,
+ animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY
+};
+
+var DETECT_STAGGER_CSS_PROPERTIES = {
+ transitionDuration: TRANSITION_DURATION_PROP,
+ transitionDelay: TRANSITION_DELAY_PROP,
+ animationDuration: ANIMATION_DURATION_PROP,
+ animationDelay: ANIMATION_DELAY_PROP
+};
+
+function getCssKeyframeDurationStyle(duration) {
+ return [ANIMATION_DURATION_PROP, duration + 's'];
+}
+
+function getCssDelayStyle(delay, isKeyframeAnimation) {
+ var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP;
+ return [prop, delay + 's'];
+}
+
+function computeCssStyles($window, element, properties) {
+ var styles = Object.create(null);
+ var detectedStyles = $window.getComputedStyle(element) || {};
+ forEach(properties, function(formalStyleName, actualStyleName) {
+ var val = detectedStyles[formalStyleName];
+ if (val) {
+ var c = val.charAt(0);
+
+ // only numerical-based values have a negative sign or digit as the first value
+ if (c === '-' || c === '+' || c >= 0) {
+ val = parseMaxTime(val);
+ }
+
+ // by setting this to null in the event that the delay is not set or is set directly as 0
+ // then we can still allow for zegative values to be used later on and not mistake this
+ // value for being greater than any other negative value.
+ if (val === 0) {
+ val = null;
+ }
+ styles[actualStyleName] = val;
+ }
+ });
+
+ return styles;
+}
+
+function parseMaxTime(str) {
+ var maxValue = 0;
+ var values = str.split(/\s*,\s*/);
+ forEach(values, function(value) {
+ // it's always safe to consider only second values and omit `ms` values since
+ // getComputedStyle will always handle the conversion for us
+ if (value.charAt(value.length - 1) == 's') {
+ value = value.substring(0, value.length - 1);
+ }
+ value = parseFloat(value) || 0;
+ maxValue = maxValue ? Math.max(value, maxValue) : value;
+ });
+ return maxValue;
+}
+
+function truthyTimingValue(val) {
+ return val === 0 || val != null;
+}
+
+function getCssTransitionDurationStyle(duration, applyOnlyDuration) {
+ var style = TRANSITION_PROP;
+ var value = duration + 's';
+ if (applyOnlyDuration) {
+ style += DURATION_KEY;
+ } else {
+ value += ' linear all';
+ }
+ return [style, value];
+}
+
+function createLocalCacheLookup() {
+ var cache = Object.create(null);
+ return {
+ flush: function() {
+ cache = Object.create(null);
+ },
+
+ count: function(key) {
+ var entry = cache[key];
+ return entry ? entry.total : 0;
+ },
+
+ get: function(key) {
+ var entry = cache[key];
+ return entry && entry.value;
+ },
+
+ put: function(key, value) {
+ if (!cache[key]) {
+ cache[key] = { total: 1, value: value };
+ } else {
+ cache[key].total++;
+ }
+ }
+ };
+}
+
+// we do not reassign an already present style value since
+// if we detect the style property value again we may be
+// detecting styles that were added via the `from` styles.
+// We make use of `isDefined` here since an empty string
+// or null value (which is what getPropertyValue will return
+// for a non-existing style) will still be marked as a valid
+// value for the style (a falsy value implies that the style
+// is to be removed at the end of the animation). If we had a simple
+// "OR" statement then it would not be enough to catch that.
+function registerRestorableStyles(backup, node, properties) {
+ forEach(properties, function(prop) {
+ backup[prop] = isDefined(backup[prop])
+ ? backup[prop]
+ : node.style.getPropertyValue(prop);
+ });
+}
+
+var $AnimateCssProvider = ['$animateProvider', function($animateProvider) {
+ var gcsLookup = createLocalCacheLookup();
+ var gcsStaggerLookup = createLocalCacheLookup();
+
+ this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout',
+ '$$forceReflow', '$sniffer', '$$rAFScheduler', '$animate',
+ function($window, $$jqLite, $$AnimateRunner, $timeout,
+ $$forceReflow, $sniffer, $$rAFScheduler, $animate) {
+
+ var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
+
+ var parentCounter = 0;
+ function gcsHashFn(node, extraClasses) {
+ var KEY = "$$ngAnimateParentKey";
+ var parentNode = node.parentNode;
+ var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter);
+ return parentID + '-' + node.getAttribute('class') + '-' + extraClasses;
+ }
+
+ function computeCachedCssStyles(node, className, cacheKey, properties) {
+ var timings = gcsLookup.get(cacheKey);
+
+ if (!timings) {
+ timings = computeCssStyles($window, node, properties);
+ if (timings.animationIterationCount === 'infinite') {
+ timings.animationIterationCount = 1;
+ }
+ }
+
+ // we keep putting this in multiple times even though the value and the cacheKey are the same
+ // because we're keeping an interal tally of how many duplicate animations are detected.
+ gcsLookup.put(cacheKey, timings);
+ return timings;
+ }
+
+ function computeCachedCssStaggerStyles(node, className, cacheKey, properties) {
+ var stagger;
+
+ // if we have one or more existing matches of matching elements
+ // containing the same parent + CSS styles (which is how cacheKey works)
+ // then staggering is possible
+ if (gcsLookup.count(cacheKey) > 0) {
+ stagger = gcsStaggerLookup.get(cacheKey);
+
+ if (!stagger) {
+ var staggerClassName = pendClasses(className, '-stagger');
+
+ $$jqLite.addClass(node, staggerClassName);
+
+ stagger = computeCssStyles($window, node, properties);
+
+ // force the conversion of a null value to zero incase not set
+ stagger.animationDuration = Math.max(stagger.animationDuration, 0);
+ stagger.transitionDuration = Math.max(stagger.transitionDuration, 0);
+
+ $$jqLite.removeClass(node, staggerClassName);
+
+ gcsStaggerLookup.put(cacheKey, stagger);
+ }
+ }
+
+ return stagger || {};
+ }
+
+ var cancelLastRAFRequest;
+ var rafWaitQueue = [];
+ function waitUntilQuiet(callback) {
+ rafWaitQueue.push(callback);
+ $$rAFScheduler.waitUntilQuiet(function() {
+ gcsLookup.flush();
+ gcsStaggerLookup.flush();
+
+ // DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable.
+ // PLEASE EXAMINE THE `$$forceReflow` service to understand why.
+ var pageWidth = $$forceReflow();
+
+ // we use a for loop to ensure that if the queue is changed
+ // during this looping then it will consider new requests
+ for (var i = 0; i < rafWaitQueue.length; i++) {
+ rafWaitQueue[i](pageWidth);
+ }
+ rafWaitQueue.length = 0;
+ });
+ }
+
+ function computeTimings(node, className, cacheKey) {
+ var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES);
+ var aD = timings.animationDelay;
+ var tD = timings.transitionDelay;
+ timings.maxDelay = aD && tD
+ ? Math.max(aD, tD)
+ : (aD || tD);
+ timings.maxDuration = Math.max(
+ timings.animationDuration * timings.animationIterationCount,
+ timings.transitionDuration);
+
+ return timings;
+ }
+
+ return function init(element, options) {
+ var restoreStyles = {};
+ var node = getDomNode(element);
+ if (!node
+ || !node.parentNode
+ || !$animate.enabled()) {
+ return closeAndReturnNoopAnimator();
+ }
+
+ options = prepareAnimationOptions(options);
+
+ var temporaryStyles = [];
+ var classes = element.attr('class');
+ var styles = packageStyles(options);
+ var animationClosed;
+ var animationPaused;
+ var animationCompleted;
+ var runner;
+ var runnerHost;
+ var maxDelay;
+ var maxDelayTime;
+ var maxDuration;
+ var maxDurationTime;
+
+ if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) {
+ return closeAndReturnNoopAnimator();
+ }
+
+ var method = options.event && isArray(options.event)
+ ? options.event.join(' ')
+ : options.event;
+
+ var isStructural = method && options.structural;
+ var structuralClassName = '';
+ var addRemoveClassName = '';
+
+ if (isStructural) {
+ structuralClassName = pendClasses(method, EVENT_CLASS_PREFIX, true);
+ } else if (method) {
+ structuralClassName = method;
+ }
+
+ if (options.addClass) {
+ addRemoveClassName += pendClasses(options.addClass, ADD_CLASS_SUFFIX);
+ }
+
+ if (options.removeClass) {
+ if (addRemoveClassName.length) {
+ addRemoveClassName += ' ';
+ }
+ addRemoveClassName += pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX);
+ }
+
+ // there may be a situation where a structural animation is combined together
+ // with CSS classes that need to resolve before the animation is computed.
+ // However this means that there is no explicit CSS code to block the animation
+ // from happening (by setting 0s none in the class name). If this is the case
+ // we need to apply the classes before the first rAF so we know to continue if
+ // there actually is a detected transition or keyframe animation
+ if (options.applyClassesEarly && addRemoveClassName.length) {
+ applyAnimationClasses(element, options);
+ }
+
+ var preparationClasses = [structuralClassName, addRemoveClassName].join(' ').trim();
+ var fullClassName = classes + ' ' + preparationClasses;
+ var activeClasses = pendClasses(preparationClasses, ACTIVE_CLASS_SUFFIX);
+ var hasToStyles = styles.to && Object.keys(styles.to).length > 0;
+ var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0;
+
+ // there is no way we can trigger an animation if no styles and
+ // no classes are being applied which would then trigger a transition,
+ // unless there a is raw keyframe value that is applied to the element.
+ if (!containsKeyframeAnimation
+ && !hasToStyles
+ && !preparationClasses) {
+ return closeAndReturnNoopAnimator();
+ }
+
+ var cacheKey, stagger;
+ if (options.stagger > 0) {
+ var staggerVal = parseFloat(options.stagger);
+ stagger = {
+ transitionDelay: staggerVal,
+ animationDelay: staggerVal,
+ transitionDuration: 0,
+ animationDuration: 0
+ };
+ } else {
+ cacheKey = gcsHashFn(node, fullClassName);
+ stagger = computeCachedCssStaggerStyles(node, preparationClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES);
+ }
+
+ if (!options.$$skipPreparationClasses) {
+ $$jqLite.addClass(element, preparationClasses);
+ }
+
+ var applyOnlyDuration;
+
+ if (options.transitionStyle) {
+ var transitionStyle = [TRANSITION_PROP, options.transitionStyle];
+ applyInlineStyle(node, transitionStyle);
+ temporaryStyles.push(transitionStyle);
+ }
+
+ if (options.duration >= 0) {
+ applyOnlyDuration = node.style[TRANSITION_PROP].length > 0;
+ var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration);
+
+ // we set the duration so that it will be picked up by getComputedStyle later
+ applyInlineStyle(node, durationStyle);
+ temporaryStyles.push(durationStyle);
+ }
+
+ if (options.keyframeStyle) {
+ var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle];
+ applyInlineStyle(node, keyframeStyle);
+ temporaryStyles.push(keyframeStyle);
+ }
+
+ var itemIndex = stagger
+ ? options.staggerIndex >= 0
+ ? options.staggerIndex
+ : gcsLookup.count(cacheKey)
+ : 0;
+
+ var isFirst = itemIndex === 0;
+
+ // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY
+ // without causing any combination of transitions to kick in. By adding a negative delay value
+ // it forces the setup class' transition to end immediately. We later then remove the negative
+ // transition delay to allow for the transition to naturally do it's thing. The beauty here is
+ // that if there is no transition defined then nothing will happen and this will also allow
+ // other transitions to be stacked on top of each other without any chopping them out.
+ if (isFirst && !options.skipBlocking) {
+ blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE);
+ }
+
+ var timings = computeTimings(node, fullClassName, cacheKey);
+ var relativeDelay = timings.maxDelay;
+ maxDelay = Math.max(relativeDelay, 0);
+ maxDuration = timings.maxDuration;
+
+ var flags = {};
+ flags.hasTransitions = timings.transitionDuration > 0;
+ flags.hasAnimations = timings.animationDuration > 0;
+ flags.hasTransitionAll = flags.hasTransitions && timings.transitionProperty == 'all';
+ flags.applyTransitionDuration = hasToStyles && (
+ (flags.hasTransitions && !flags.hasTransitionAll)
+ || (flags.hasAnimations && !flags.hasTransitions));
+ flags.applyAnimationDuration = options.duration && flags.hasAnimations;
+ flags.applyTransitionDelay = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions);
+ flags.applyAnimationDelay = truthyTimingValue(options.delay) && flags.hasAnimations;
+ flags.recalculateTimingStyles = addRemoveClassName.length > 0;
+
+ if (flags.applyTransitionDuration || flags.applyAnimationDuration) {
+ maxDuration = options.duration ? parseFloat(options.duration) : maxDuration;
+
+ if (flags.applyTransitionDuration) {
+ flags.hasTransitions = true;
+ timings.transitionDuration = maxDuration;
+ applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0;
+ temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration));
+ }
+
+ if (flags.applyAnimationDuration) {
+ flags.hasAnimations = true;
+ timings.animationDuration = maxDuration;
+ temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration));
+ }
+ }
+
+ if (maxDuration === 0 && !flags.recalculateTimingStyles) {
+ return closeAndReturnNoopAnimator();
+ }
+
+ if (options.delay != null) {
+ var delayStyle = parseFloat(options.delay);
+
+ if (flags.applyTransitionDelay) {
+ temporaryStyles.push(getCssDelayStyle(delayStyle));
+ }
+
+ if (flags.applyAnimationDelay) {
+ temporaryStyles.push(getCssDelayStyle(delayStyle, true));
+ }
+ }
+
+ // we need to recalculate the delay value since we used a pre-emptive negative
+ // delay value and the delay value is required for the final event checking. This
+ // property will ensure that this will happen after the RAF phase has passed.
+ if (options.duration == null && timings.transitionDuration > 0) {
+ flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst;
+ }
+
+ maxDelayTime = maxDelay * ONE_SECOND;
+ maxDurationTime = maxDuration * ONE_SECOND;
+ if (!options.skipBlocking) {
+ flags.blockTransition = timings.transitionDuration > 0;
+ flags.blockKeyframeAnimation = timings.animationDuration > 0 &&
+ stagger.animationDelay > 0 &&
+ stagger.animationDuration === 0;
+ }
+
+ if (options.from) {
+ if (options.cleanupStyles) {
+ registerRestorableStyles(restoreStyles, node, Object.keys(options.from));
+ }
+ applyAnimationFromStyles(element, options);
+ }
+
+ if (flags.blockTransition || flags.blockKeyframeAnimation) {
+ applyBlocking(maxDuration);
+ } else if (!options.skipBlocking) {
+ blockTransitions(node, false);
+ }
+
+ // TODO(matsko): for 1.5 change this code to have an animator object for better debugging
+ return {
+ $$willAnimate: true,
+ end: endFn,
+ start: function() {
+ if (animationClosed) return;
+
+ runnerHost = {
+ end: endFn,
+ cancel: cancelFn,
+ resume: null, //this will be set during the start() phase
+ pause: null
+ };
+
+ runner = new $$AnimateRunner(runnerHost);
+
+ waitUntilQuiet(start);
+
+ // we don't have access to pause/resume the animation
+ // since it hasn't run yet. AnimateRunner will therefore
+ // set noop functions for resume and pause and they will
+ // later be overridden once the animation is triggered
+ return runner;
+ }
+ };
+
+ function endFn() {
+ close();
+ }
+
+ function cancelFn() {
+ close(true);
+ }
+
+ function close(rejected) { // jshint ignore:line
+ // if the promise has been called already then we shouldn't close
+ // the animation again
+ if (animationClosed || (animationCompleted && animationPaused)) return;
+ animationClosed = true;
+ animationPaused = false;
+
+ if (!options.$$skipPreparationClasses) {
+ $$jqLite.removeClass(element, preparationClasses);
+ }
+ $$jqLite.removeClass(element, activeClasses);
+
+ blockKeyframeAnimations(node, false);
+ blockTransitions(node, false);
+
+ forEach(temporaryStyles, function(entry) {
+ // There is only one way to remove inline style properties entirely from elements.
+ // By using `removeProperty` this works, but we need to convert camel-cased CSS
+ // styles down to hyphenated values.
+ node.style[entry[0]] = '';
+ });
+
+ applyAnimationClasses(element, options);
+ applyAnimationStyles(element, options);
+
+ if (Object.keys(restoreStyles).length) {
+ forEach(restoreStyles, function(value, prop) {
+ value ? node.style.setProperty(prop, value)
+ : node.style.removeProperty(prop);
+ });
+ }
+
+ // the reason why we have this option is to allow a synchronous closing callback
+ // that is fired as SOON as the animation ends (when the CSS is removed) or if
+ // the animation never takes off at all. A good example is a leave animation since
+ // the element must be removed just after the animation is over or else the element
+ // will appear on screen for one animation frame causing an overbearing flicker.
+ if (options.onDone) {
+ options.onDone();
+ }
+
+ // if the preparation function fails then the promise is not setup
+ if (runner) {
+ runner.complete(!rejected);
+ }
+ }
+
+ function applyBlocking(duration) {
+ if (flags.blockTransition) {
+ blockTransitions(node, duration);
+ }
+
+ if (flags.blockKeyframeAnimation) {
+ blockKeyframeAnimations(node, !!duration);
+ }
+ }
+
+ function closeAndReturnNoopAnimator() {
+ runner = new $$AnimateRunner({
+ end: endFn,
+ cancel: cancelFn
+ });
+
+ // should flush the cache animation
+ waitUntilQuiet(noop);
+ close();
+
+ return {
+ $$willAnimate: false,
+ start: function() {
+ return runner;
+ },
+ end: endFn
+ };
+ }
+
+ function start() {
+ if (animationClosed) return;
+ if (!node.parentNode) {
+ close();
+ return;
+ }
+
+ var startTime, events = [];
+
+ // even though we only pause keyframe animations here the pause flag
+ // will still happen when transitions are used. Only the transition will
+ // not be paused since that is not possible. If the animation ends when
+ // paused then it will not complete until unpaused or cancelled.
+ var playPause = function(playAnimation) {
+ if (!animationCompleted) {
+ animationPaused = !playAnimation;
+ if (timings.animationDuration) {
+ var value = blockKeyframeAnimations(node, animationPaused);
+ animationPaused
+ ? temporaryStyles.push(value)
+ : removeFromArray(temporaryStyles, value);
+ }
+ } else if (animationPaused && playAnimation) {
+ animationPaused = false;
+ close();
+ }
+ };
+
+ // checking the stagger duration prevents an accidently cascade of the CSS delay style
+ // being inherited from the parent. If the transition duration is zero then we can safely
+ // rely that the delay value is an intential stagger delay style.
+ var maxStagger = itemIndex > 0
+ && ((timings.transitionDuration && stagger.transitionDuration === 0) ||
+ (timings.animationDuration && stagger.animationDuration === 0))
+ && Math.max(stagger.animationDelay, stagger.transitionDelay);
+ if (maxStagger) {
+ $timeout(triggerAnimationStart,
+ Math.floor(maxStagger * itemIndex * ONE_SECOND),
+ false);
+ } else {
+ triggerAnimationStart();
+ }
+
+ // this will decorate the existing promise runner with pause/resume methods
+ runnerHost.resume = function() {
+ playPause(true);
+ };
+
+ runnerHost.pause = function() {
+ playPause(false);
+ };
+
+ function triggerAnimationStart() {
+ // just incase a stagger animation kicks in when the animation
+ // itself was cancelled entirely
+ if (animationClosed) return;
+
+ applyBlocking(false);
+
+ forEach(temporaryStyles, function(entry) {
+ var key = entry[0];
+ var value = entry[1];
+ node.style[key] = value;
+ });
+
+ applyAnimationClasses(element, options);
+ $$jqLite.addClass(element, activeClasses);
+
+ if (flags.recalculateTimingStyles) {
+ fullClassName = node.className + ' ' + preparationClasses;
+ cacheKey = gcsHashFn(node, fullClassName);
+
+ timings = computeTimings(node, fullClassName, cacheKey);
+ relativeDelay = timings.maxDelay;
+ maxDelay = Math.max(relativeDelay, 0);
+ maxDuration = timings.maxDuration;
+
+ if (maxDuration === 0) {
+ close();
+ return;
+ }
+
+ flags.hasTransitions = timings.transitionDuration > 0;
+ flags.hasAnimations = timings.animationDuration > 0;
+ }
+
+ if (flags.applyAnimationDelay) {
+ relativeDelay = typeof options.delay !== "boolean" && truthyTimingValue(options.delay)
+ ? parseFloat(options.delay)
+ : relativeDelay;
+
+ maxDelay = Math.max(relativeDelay, 0);
+ timings.animationDelay = relativeDelay;
+ delayStyle = getCssDelayStyle(relativeDelay, true);
+ temporaryStyles.push(delayStyle);
+ node.style[delayStyle[0]] = delayStyle[1];
+ }
+
+ maxDelayTime = maxDelay * ONE_SECOND;
+ maxDurationTime = maxDuration * ONE_SECOND;
+
+ if (options.easing) {
+ var easeProp, easeVal = options.easing;
+ if (flags.hasTransitions) {
+ easeProp = TRANSITION_PROP + TIMING_KEY;
+ temporaryStyles.push([easeProp, easeVal]);
+ node.style[easeProp] = easeVal;
+ }
+ if (flags.hasAnimations) {
+ easeProp = ANIMATION_PROP + TIMING_KEY;
+ temporaryStyles.push([easeProp, easeVal]);
+ node.style[easeProp] = easeVal;
+ }
+ }
+
+ if (timings.transitionDuration) {
+ events.push(TRANSITIONEND_EVENT);
+ }
+
+ if (timings.animationDuration) {
+ events.push(ANIMATIONEND_EVENT);
+ }
+
+ startTime = Date.now();
+ var timerTime = maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime;
+ var endTime = startTime + timerTime;
+
+ var animationsData = element.data(ANIMATE_TIMER_KEY) || [];
+ var setupFallbackTimer = true;
+ if (animationsData.length) {
+ var currentTimerData = animationsData[0];
+ setupFallbackTimer = endTime > currentTimerData.expectedEndTime;
+ if (setupFallbackTimer) {
+ $timeout.cancel(currentTimerData.timer);
+ } else {
+ animationsData.push(close);
+ }
+ }
+
+ if (setupFallbackTimer) {
+ var timer = $timeout(onAnimationExpired, timerTime, false);
+ animationsData[0] = {
+ timer: timer,
+ expectedEndTime: endTime
+ };
+ animationsData.push(close);
+ element.data(ANIMATE_TIMER_KEY, animationsData);
+ }
+
+ element.on(events.join(' '), onAnimationProgress);
+ if (options.to) {
+ if (options.cleanupStyles) {
+ registerRestorableStyles(restoreStyles, node, Object.keys(options.to));
+ }
+ applyAnimationToStyles(element, options);
+ }
+ }
+
+ function onAnimationExpired() {
+ var animationsData = element.data(ANIMATE_TIMER_KEY);
+
+ // this will be false in the event that the element was
+ // removed from the DOM (via a leave animation or something
+ // similar)
+ if (animationsData) {
+ for (var i = 1; i < animationsData.length; i++) {
+ animationsData[i]();
+ }
+ element.removeData(ANIMATE_TIMER_KEY);
+ }
+ }
+
+ function onAnimationProgress(event) {
+ event.stopPropagation();
+ var ev = event.originalEvent || event;
+ var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now();
+
+ /* Firefox (or possibly just Gecko) likes to not round values up
+ * when a ms measurement is used for the animation */
+ var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));
+
+ /* $manualTimeStamp is a mocked timeStamp value which is set
+ * within browserTrigger(). This is only here so that tests can
+ * mock animations properly. Real events fallback to event.timeStamp,
+ * or, if they don't, then a timeStamp is automatically created for them.
+ * We're checking to see if the timeStamp surpasses the expected delay,
+ * but we're using elapsedTime instead of the timeStamp on the 2nd
+ * pre-condition since animations sometimes close off early */
+ if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
+ // we set this flag to ensure that if the transition is paused then, when resumed,
+ // the animation will automatically close itself since transitions cannot be paused.
+ animationCompleted = true;
+ close();
+ }
+ }
+ }
+ };
+ }];
+}];
+
+var $$AnimateCssDriverProvider = ['$$animationProvider', function($$animationProvider) {
+ $$animationProvider.drivers.push('$$animateCssDriver');
+
+ var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim';
+ var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor';
+
+ var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out';
+ var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in';
+
+ function isDocumentFragment(node) {
+ return node.parentNode && node.parentNode.nodeType === 11;
+ }
+
+ this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$sniffer', '$$jqLite', '$document',
+ function($animateCss, $rootScope, $$AnimateRunner, $rootElement, $sniffer, $$jqLite, $document) {
+
+ // only browsers that support these properties can render animations
+ if (!$sniffer.animations && !$sniffer.transitions) return noop;
+
+ var bodyNode = $document[0].body;
+ var rootNode = getDomNode($rootElement);
+
+ var rootBodyElement = jqLite(
+ // this is to avoid using something that exists outside of the body
+ // we also special case the doc fragement case because our unit test code
+ // appends the $rootElement to the body after the app has been bootstrapped
+ isDocumentFragment(rootNode) || bodyNode.contains(rootNode) ? rootNode : bodyNode
+ );
+
+ var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
+
+ return function initDriverFn(animationDetails) {
+ return animationDetails.from && animationDetails.to
+ ? prepareFromToAnchorAnimation(animationDetails.from,
+ animationDetails.to,
+ animationDetails.classes,
+ animationDetails.anchors)
+ : prepareRegularAnimation(animationDetails);
+ };
+
+ function filterCssClasses(classes) {
+ //remove all the `ng-` stuff
+ return classes.replace(/\bng-\S+\b/g, '');
+ }
+
+ function getUniqueValues(a, b) {
+ if (isString(a)) a = a.split(' ');
+ if (isString(b)) b = b.split(' ');
+ return a.filter(function(val) {
+ return b.indexOf(val) === -1;
+ }).join(' ');
+ }
+
+ function prepareAnchoredAnimation(classes, outAnchor, inAnchor) {
+ var clone = jqLite(getDomNode(outAnchor).cloneNode(true));
+ var startingClasses = filterCssClasses(getClassVal(clone));
+
+ outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
+ inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
+
+ clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME);
+
+ rootBodyElement.append(clone);
+
+ var animatorIn, animatorOut = prepareOutAnimation();
+
+ // the user may not end up using the `out` animation and
+ // only making use of the `in` animation or vice-versa.
+ // In either case we should allow this and not assume the
+ // animation is over unless both animations are not used.
+ if (!animatorOut) {
+ animatorIn = prepareInAnimation();
+ if (!animatorIn) {
+ return end();
+ }
+ }
+
+ var startingAnimator = animatorOut || animatorIn;
+
+ return {
+ start: function() {
+ var runner;
+
+ var currentAnimation = startingAnimator.start();
+ currentAnimation.done(function() {
+ currentAnimation = null;
+ if (!animatorIn) {
+ animatorIn = prepareInAnimation();
+ if (animatorIn) {
+ currentAnimation = animatorIn.start();
+ currentAnimation.done(function() {
+ currentAnimation = null;
+ end();
+ runner.complete();
+ });
+ return currentAnimation;
+ }
+ }
+ // in the event that there is no `in` animation
+ end();
+ runner.complete();
+ });
+
+ runner = new $$AnimateRunner({
+ end: endFn,
+ cancel: endFn
+ });
+
+ return runner;
+
+ function endFn() {
+ if (currentAnimation) {
+ currentAnimation.end();
+ }
+ }
+ }
+ };
+
+ function calculateAnchorStyles(anchor) {
+ var styles = {};
+
+ var coords = getDomNode(anchor).getBoundingClientRect();
+
+ // we iterate directly since safari messes up and doesn't return
+ // all the keys for the coods object when iterated
+ forEach(['width','height','top','left'], function(key) {
+ var value = coords[key];
+ switch (key) {
+ case 'top':
+ value += bodyNode.scrollTop;
+ break;
+ case 'left':
+ value += bodyNode.scrollLeft;
+ break;
+ }
+ styles[key] = Math.floor(value) + 'px';
+ });
+ return styles;
+ }
+
+ function prepareOutAnimation() {
+ var animator = $animateCss(clone, {
+ addClass: NG_OUT_ANCHOR_CLASS_NAME,
+ delay: true,
+ from: calculateAnchorStyles(outAnchor)
+ });
+
+ // read the comment within `prepareRegularAnimation` to understand
+ // why this check is necessary
+ return animator.$$willAnimate ? animator : null;
+ }
+
+ function getClassVal(element) {
+ return element.attr('class') || '';
+ }
+
+ function prepareInAnimation() {
+ var endingClasses = filterCssClasses(getClassVal(inAnchor));
+ var toAdd = getUniqueValues(endingClasses, startingClasses);
+ var toRemove = getUniqueValues(startingClasses, endingClasses);
+
+ var animator = $animateCss(clone, {
+ to: calculateAnchorStyles(inAnchor),
+ addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd,
+ removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove,
+ delay: true
+ });
+
+ // read the comment within `prepareRegularAnimation` to understand
+ // why this check is necessary
+ return animator.$$willAnimate ? animator : null;
+ }
+
+ function end() {
+ clone.remove();
+ outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
+ inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
+ }
+ }
+
+ function prepareFromToAnchorAnimation(from, to, classes, anchors) {
+ var fromAnimation = prepareRegularAnimation(from, noop);
+ var toAnimation = prepareRegularAnimation(to, noop);
+
+ var anchorAnimations = [];
+ forEach(anchors, function(anchor) {
+ var outElement = anchor['out'];
+ var inElement = anchor['in'];
+ var animator = prepareAnchoredAnimation(classes, outElement, inElement);
+ if (animator) {
+ anchorAnimations.push(animator);
+ }
+ });
+
+ // no point in doing anything when there are no elements to animate
+ if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return;
+
+ return {
+ start: function() {
+ var animationRunners = [];
+
+ if (fromAnimation) {
+ animationRunners.push(fromAnimation.start());
+ }
+
+ if (toAnimation) {
+ animationRunners.push(toAnimation.start());
+ }
+
+ forEach(anchorAnimations, function(animation) {
+ animationRunners.push(animation.start());
+ });
+
+ var runner = new $$AnimateRunner({
+ end: endFn,
+ cancel: endFn // CSS-driven animations cannot be cancelled, only ended
+ });
+
+ $$AnimateRunner.all(animationRunners, function(status) {
+ runner.complete(status);
+ });
+
+ return runner;
+
+ function endFn() {
+ forEach(animationRunners, function(runner) {
+ runner.end();
+ });
+ }
+ }
+ };
+ }
+
+ function prepareRegularAnimation(animationDetails) {
+ var element = animationDetails.element;
+ var options = animationDetails.options || {};
+
+ if (animationDetails.structural) {
+ options.event = animationDetails.event;
+ options.structural = true;
+ options.applyClassesEarly = true;
+
+ // we special case the leave animation since we want to ensure that
+ // the element is removed as soon as the animation is over. Otherwise
+ // a flicker might appear or the element may not be removed at all
+ if (animationDetails.event === 'leave') {
+ options.onDone = options.domOperation;
+ }
+ }
+
+ // We assign the preparationClasses as the actual animation event since
+ // the internals of $animateCss will just suffix the event token values
+ // with `-active` to trigger the animation.
+ if (options.preparationClasses) {
+ options.event = concatWithSpace(options.event, options.preparationClasses);
+ }
+
+ var animator = $animateCss(element, options);
+
+ // the driver lookup code inside of $$animation attempts to spawn a
+ // driver one by one until a driver returns a.$$willAnimate animator object.
+ // $animateCss will always return an object, however, it will pass in
+ // a flag as a hint as to whether an animation was detected or not
+ return animator.$$willAnimate ? animator : null;
+ }
+ }];
+}];
+
+// TODO(matsko): use caching here to speed things up for detection
+// TODO(matsko): add documentation
+// by the time...
+
+var $$AnimateJsProvider = ['$animateProvider', function($animateProvider) {
+ this.$get = ['$injector', '$$AnimateRunner', '$$jqLite',
+ function($injector, $$AnimateRunner, $$jqLite) {
+
+ var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
+ // $animateJs(element, 'enter');
+ return function(element, event, classes, options) {
+ // the `classes` argument is optional and if it is not used
+ // then the classes will be resolved from the element's className
+ // property as well as options.addClass/options.removeClass.
+ if (arguments.length === 3 && isObject(classes)) {
+ options = classes;
+ classes = null;
+ }
+
+ options = prepareAnimationOptions(options);
+ if (!classes) {
+ classes = element.attr('class') || '';
+ if (options.addClass) {
+ classes += ' ' + options.addClass;
+ }
+ if (options.removeClass) {
+ classes += ' ' + options.removeClass;
+ }
+ }
+
+ var classesToAdd = options.addClass;
+ var classesToRemove = options.removeClass;
+
+ // the lookupAnimations function returns a series of animation objects that are
+ // matched up with one or more of the CSS classes. These animation objects are
+ // defined via the module.animation factory function. If nothing is detected then
+ // we don't return anything which then makes $animation query the next driver.
+ var animations = lookupAnimations(classes);
+ var before, after;
+ if (animations.length) {
+ var afterFn, beforeFn;
+ if (event == 'leave') {
+ beforeFn = 'leave';
+ afterFn = 'afterLeave'; // TODO(matsko): get rid of this
+ } else {
+ beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1);
+ afterFn = event;
+ }
+
+ if (event !== 'enter' && event !== 'move') {
+ before = packageAnimations(element, event, options, animations, beforeFn);
+ }
+ after = packageAnimations(element, event, options, animations, afterFn);
+ }
+
+ // no matching animations
+ if (!before && !after) return;
+
+ function applyOptions() {
+ options.domOperation();
+ applyAnimationClasses(element, options);
+ }
+
+ return {
+ start: function() {
+ var closeActiveAnimations;
+ var chain = [];
+
+ if (before) {
+ chain.push(function(fn) {
+ closeActiveAnimations = before(fn);
+ });
+ }
+
+ if (chain.length) {
+ chain.push(function(fn) {
+ applyOptions();
+ fn(true);
+ });
+ } else {
+ applyOptions();
+ }
+
+ if (after) {
+ chain.push(function(fn) {
+ closeActiveAnimations = after(fn);
+ });
+ }
+
+ var animationClosed = false;
+ var runner = new $$AnimateRunner({
+ end: function() {
+ endAnimations();
+ },
+ cancel: function() {
+ endAnimations(true);
+ }
+ });
+
+ $$AnimateRunner.chain(chain, onComplete);
+ return runner;
+
+ function onComplete(success) {
+ animationClosed = true;
+ applyOptions();
+ applyAnimationStyles(element, options);
+ runner.complete(success);
+ }
+
+ function endAnimations(cancelled) {
+ if (!animationClosed) {
+ (closeActiveAnimations || noop)(cancelled);
+ onComplete(cancelled);
+ }
+ }
+ }
+ };
+
+ function executeAnimationFn(fn, element, event, options, onDone) {
+ var args;
+ switch (event) {
+ case 'animate':
+ args = [element, options.from, options.to, onDone];
+ break;
+
+ case 'setClass':
+ args = [element, classesToAdd, classesToRemove, onDone];
+ break;
+
+ case 'addClass':
+ args = [element, classesToAdd, onDone];
+ break;
+
+ case 'removeClass':
+ args = [element, classesToRemove, onDone];
+ break;
+
+ default:
+ args = [element, onDone];
+ break;
+ }
+
+ args.push(options);
+
+ var value = fn.apply(fn, args);
+ if (value) {
+ if (isFunction(value.start)) {
+ value = value.start();
+ }
+
+ if (value instanceof $$AnimateRunner) {
+ value.done(onDone);
+ } else if (isFunction(value)) {
+ // optional onEnd / onCancel callback
+ return value;
+ }
+ }
+
+ return noop;
+ }
+
+ function groupEventedAnimations(element, event, options, animations, fnName) {
+ var operations = [];
+ forEach(animations, function(ani) {
+ var animation = ani[fnName];
+ if (!animation) return;
+
+ // note that all of these animations will run in parallel
+ operations.push(function() {
+ var runner;
+ var endProgressCb;
+
+ var resolved = false;
+ var onAnimationComplete = function(rejected) {
+ if (!resolved) {
+ resolved = true;
+ (endProgressCb || noop)(rejected);
+ runner.complete(!rejected);
+ }
+ };
+
+ runner = new $$AnimateRunner({
+ end: function() {
+ onAnimationComplete();
+ },
+ cancel: function() {
+ onAnimationComplete(true);
+ }
+ });
+
+ endProgressCb = executeAnimationFn(animation, element, event, options, function(result) {
+ var cancelled = result === false;
+ onAnimationComplete(cancelled);
+ });
+
+ return runner;
+ });
+ });
+
+ return operations;
+ }
+
+ function packageAnimations(element, event, options, animations, fnName) {
+ var operations = groupEventedAnimations(element, event, options, animations, fnName);
+ if (operations.length === 0) {
+ var a,b;
+ if (fnName === 'beforeSetClass') {
+ a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass');
+ b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass');
+ } else if (fnName === 'setClass') {
+ a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass');
+ b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass');
+ }
+
+ if (a) {
+ operations = operations.concat(a);
+ }
+ if (b) {
+ operations = operations.concat(b);
+ }
+ }
+
+ if (operations.length === 0) return;
+
+ // TODO(matsko): add documentation
+ return function startAnimation(callback) {
+ var runners = [];
+ if (operations.length) {
+ forEach(operations, function(animateFn) {
+ runners.push(animateFn());
+ });
+ }
+
+ runners.length ? $$AnimateRunner.all(runners, callback) : callback();
+
+ return function endFn(reject) {
+ forEach(runners, function(runner) {
+ reject ? runner.cancel() : runner.end();
+ });
+ };
+ };
+ }
+ };
+
+ function lookupAnimations(classes) {
+ classes = isArray(classes) ? classes : classes.split(' ');
+ var matches = [], flagMap = {};
+ for (var i=0; i < classes.length; i++) {
+ var klass = classes[i],
+ animationFactory = $animateProvider.$$registeredAnimations[klass];
+ if (animationFactory && !flagMap[klass]) {
+ matches.push($injector.get(animationFactory));
+ flagMap[klass] = true;
+ }
+ }
+ return matches;
+ }
+ }];
+}];
+
+var $$AnimateJsDriverProvider = ['$$animationProvider', function($$animationProvider) {
+ $$animationProvider.drivers.push('$$animateJsDriver');
+ this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) {
+ return function initDriverFn(animationDetails) {
+ if (animationDetails.from && animationDetails.to) {
+ var fromAnimation = prepareAnimation(animationDetails.from);
+ var toAnimation = prepareAnimation(animationDetails.to);
+ if (!fromAnimation && !toAnimation) return;
+
+ return {
+ start: function() {
+ var animationRunners = [];
+
+ if (fromAnimation) {
+ animationRunners.push(fromAnimation.start());
+ }
+
+ if (toAnimation) {
+ animationRunners.push(toAnimation.start());
+ }
+
+ $$AnimateRunner.all(animationRunners, done);
+
+ var runner = new $$AnimateRunner({
+ end: endFnFactory(),
+ cancel: endFnFactory()
+ });
+
+ return runner;
+
+ function endFnFactory() {
+ return function() {
+ forEach(animationRunners, function(runner) {
+ // at this point we cannot cancel animations for groups just yet. 1.5+
+ runner.end();
+ });
+ };
+ }
+
+ function done(status) {
+ runner.complete(status);
+ }
+ }
+ };
+ } else {
+ return prepareAnimation(animationDetails);
+ }
+ };
+
+ function prepareAnimation(animationDetails) {
+ // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations
+ var element = animationDetails.element;
+ var event = animationDetails.event;
+ var options = animationDetails.options;
+ var classes = animationDetails.classes;
+ return $$animateJs(element, event, classes, options);
+ }
+ }];
+}];
+
+var NG_ANIMATE_ATTR_NAME = 'data-ng-animate';
+var NG_ANIMATE_PIN_DATA = '$ngAnimatePin';
+var $$AnimateQueueProvider = ['$animateProvider', function($animateProvider) {
+ var PRE_DIGEST_STATE = 1;
+ var RUNNING_STATE = 2;
+
+ var rules = this.rules = {
+ skip: [],
+ cancel: [],
+ join: []
+ };
+
+ function isAllowed(ruleType, element, currentAnimation, previousAnimation) {
+ return rules[ruleType].some(function(fn) {
+ return fn(element, currentAnimation, previousAnimation);
+ });
+ }
+
+ function hasAnimationClasses(options, and) {
+ options = options || {};
+ var a = (options.addClass || '').length > 0;
+ var b = (options.removeClass || '').length > 0;
+ return and ? a && b : a || b;
+ }
+
+ rules.join.push(function(element, newAnimation, currentAnimation) {
+ // if the new animation is class-based then we can just tack that on
+ return !newAnimation.structural && hasAnimationClasses(newAnimation.options);
+ });
+
+ rules.skip.push(function(element, newAnimation, currentAnimation) {
+ // there is no need to animate anything if no classes are being added and
+ // there is no structural animation that will be triggered
+ return !newAnimation.structural && !hasAnimationClasses(newAnimation.options);
+ });
+
+ rules.skip.push(function(element, newAnimation, currentAnimation) {
+ // why should we trigger a new structural animation if the element will
+ // be removed from the DOM anyway?
+ return currentAnimation.event == 'leave' && newAnimation.structural;
+ });
+
+ rules.skip.push(function(element, newAnimation, currentAnimation) {
+ // if there is an ongoing current animation then don't even bother running the class-based animation
+ return currentAnimation.structural && currentAnimation.state === RUNNING_STATE && !newAnimation.structural;
+ });
+
+ rules.cancel.push(function(element, newAnimation, currentAnimation) {
+ // there can never be two structural animations running at the same time
+ return currentAnimation.structural && newAnimation.structural;
+ });
+
+ rules.cancel.push(function(element, newAnimation, currentAnimation) {
+ // if the previous animation is already running, but the new animation will
+ // be triggered, but the new animation is structural
+ return currentAnimation.state === RUNNING_STATE && newAnimation.structural;
+ });
+
+ rules.cancel.push(function(element, newAnimation, currentAnimation) {
+ var nO = newAnimation.options;
+ var cO = currentAnimation.options;
+
+ // if the exact same CSS class is added/removed then it's safe to cancel it
+ return (nO.addClass && nO.addClass === cO.removeClass) || (nO.removeClass && nO.removeClass === cO.addClass);
+ });
+
+ this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap',
+ '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite', '$$forceReflow',
+ function($$rAF, $rootScope, $rootElement, $document, $$HashMap,
+ $$animation, $$AnimateRunner, $templateRequest, $$jqLite, $$forceReflow) {
+
+ var activeAnimationsLookup = new $$HashMap();
+ var disabledElementsLookup = new $$HashMap();
+ var animationsEnabled = null;
+
+ function postDigestTaskFactory() {
+ var postDigestCalled = false;
+ return function(fn) {
+ // we only issue a call to postDigest before
+ // it has first passed. This prevents any callbacks
+ // from not firing once the animation has completed
+ // since it will be out of the digest cycle.
+ if (postDigestCalled) {
+ fn();
+ } else {
+ $rootScope.$$postDigest(function() {
+ postDigestCalled = true;
+ fn();
+ });
+ }
+ };
+ }
+
+ // Wait until all directive and route-related templates are downloaded and
+ // compiled. The $templateRequest.totalPendingRequests variable keeps track of
+ // all of the remote templates being currently downloaded. If there are no
+ // templates currently downloading then the watcher will still fire anyway.
+ var deregisterWatch = $rootScope.$watch(
+ function() { return $templateRequest.totalPendingRequests === 0; },
+ function(isEmpty) {
+ if (!isEmpty) return;
+ deregisterWatch();
+
+ // Now that all templates have been downloaded, $animate will wait until
+ // the post digest queue is empty before enabling animations. By having two
+ // calls to $postDigest calls we can ensure that the flag is enabled at the
+ // very end of the post digest queue. Since all of the animations in $animate
+ // use $postDigest, it's important that the code below executes at the end.
+ // This basically means that the page is fully downloaded and compiled before
+ // any animations are triggered.
+ $rootScope.$$postDigest(function() {
+ $rootScope.$$postDigest(function() {
+ // we check for null directly in the event that the application already called
+ // .enabled() with whatever arguments that it provided it with
+ if (animationsEnabled === null) {
+ animationsEnabled = true;
+ }
+ });
+ });
+ }
+ );
+
+ var callbackRegistry = {};
+
+ // remember that the classNameFilter is set during the provider/config
+ // stage therefore we can optimize here and setup a helper function
+ var classNameFilter = $animateProvider.classNameFilter();
+ var isAnimatableClassName = !classNameFilter
+ ? function() { return true; }
+ : function(className) {
+ return classNameFilter.test(className);
+ };
+
+ var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
+
+ function normalizeAnimationOptions(element, options) {
+ return mergeAnimationOptions(element, options, {});
+ }
+
+ function findCallbacks(parent, element, event) {
+ var targetNode = getDomNode(element);
+ var targetParentNode = getDomNode(parent);
+
+ var matches = [];
+ var entries = callbackRegistry[event];
+ if (entries) {
+ forEach(entries, function(entry) {
+ if (entry.node.contains(targetNode)) {
+ matches.push(entry.callback);
+ } else if (event === 'leave' && entry.node.contains(targetParentNode)) {
+ matches.push(entry.callback);
+ }
+ });
+ }
+
+ return matches;
+ }
+
+ return {
+ on: function(event, container, callback) {
+ var node = extractElementNode(container);
+ callbackRegistry[event] = callbackRegistry[event] || [];
+ callbackRegistry[event].push({
+ node: node,
+ callback: callback
+ });
+ },
+
+ off: function(event, container, callback) {
+ var entries = callbackRegistry[event];
+ if (!entries) return;
+
+ callbackRegistry[event] = arguments.length === 1
+ ? null
+ : filterFromRegistry(entries, container, callback);
+
+ function filterFromRegistry(list, matchContainer, matchCallback) {
+ var containerNode = extractElementNode(matchContainer);
+ return list.filter(function(entry) {
+ var isMatch = entry.node === containerNode &&
+ (!matchCallback || entry.callback === matchCallback);
+ return !isMatch;
+ });
+ }
+ },
+
+ pin: function(element, parentElement) {
+ assertArg(isElement(element), 'element', 'not an element');
+ assertArg(isElement(parentElement), 'parentElement', 'not an element');
+ element.data(NG_ANIMATE_PIN_DATA, parentElement);
+ },
+
+ push: function(element, event, options, domOperation) {
+ options = options || {};
+ options.domOperation = domOperation;
+ return queueAnimation(element, event, options);
+ },
+
+ // this method has four signatures:
+ // () - global getter
+ // (bool) - global setter
+ // (element) - element getter
+ // (element, bool) - element setter<F37>
+ enabled: function(element, bool) {
+ var argCount = arguments.length;
+
+ if (argCount === 0) {
+ // () - Global getter
+ bool = !!animationsEnabled;
+ } else {
+ var hasElement = isElement(element);
+
+ if (!hasElement) {
+ // (bool) - Global setter
+ bool = animationsEnabled = !!element;
+ } else {
+ var node = getDomNode(element);
+ var recordExists = disabledElementsLookup.get(node);
+
+ if (argCount === 1) {
+ // (element) - Element getter
+ bool = !recordExists;
+ } else {
+ // (element, bool) - Element setter
+ bool = !!bool;
+ if (!bool) {
+ disabledElementsLookup.put(node, true);
+ } else if (recordExists) {
+ disabledElementsLookup.remove(node);
+ }
+ }
+ }
+ }
+
+ return bool;
+ }
+ };
+
+ function queueAnimation(element, event, options) {
+ var node, parent;
+ element = stripCommentsFromElement(element);
+ if (element) {
+ node = getDomNode(element);
+ parent = element.parent();
+ }
+
+ options = prepareAnimationOptions(options);
+
+ // we create a fake runner with a working promise.
+ // These methods will become available after the digest has passed
+ var runner = new $$AnimateRunner();
+
+ // this is used to trigger callbacks in postDigest mode
+ var runInNextPostDigestOrNow = postDigestTaskFactory();
+
+ if (isArray(options.addClass)) {
+ options.addClass = options.addClass.join(' ');
+ }
+
+ if (options.addClass && !isString(options.addClass)) {
+ options.addClass = null;
+ }
+
+ if (isArray(options.removeClass)) {
+ options.removeClass = options.removeClass.join(' ');
+ }
+
+ if (options.removeClass && !isString(options.removeClass)) {
+ options.removeClass = null;
+ }
+
+ if (options.from && !isObject(options.from)) {
+ options.from = null;
+ }
+
+ if (options.to && !isObject(options.to)) {
+ options.to = null;
+ }
+
+ // there are situations where a directive issues an animation for
+ // a jqLite wrapper that contains only comment nodes... If this
+ // happens then there is no way we can perform an animation
+ if (!node) {
+ close();
+ return runner;
+ }
+
+ var className = [node.className, options.addClass, options.removeClass].join(' ');
+ if (!isAnimatableClassName(className)) {
+ close();
+ return runner;
+ }
+
+ var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
+
+ // this is a hard disable of all animations for the application or on
+ // the element itself, therefore there is no need to continue further
+ // past this point if not enabled
+ var skipAnimations = !animationsEnabled || disabledElementsLookup.get(node);
+ var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {};
+ var hasExistingAnimation = !!existingAnimation.state;
+
+ // there is no point in traversing the same collection of parent ancestors if a followup
+ // animation will be run on the same element that already did all that checking work
+ if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state != PRE_DIGEST_STATE)) {
+ skipAnimations = !areAnimationsAllowed(element, parent, event);
+ }
+
+ if (skipAnimations) {
+ close();
+ return runner;
+ }
+
+ if (isStructural) {
+ closeChildAnimations(element);
+ }
+
+ var newAnimation = {
+ structural: isStructural,
+ element: element,
+ event: event,
+ close: close,
+ options: options,
+ runner: runner
+ };
+
+ if (hasExistingAnimation) {
+ var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation);
+ if (skipAnimationFlag) {
+ if (existingAnimation.state === RUNNING_STATE) {
+ close();
+ return runner;
+ } else {
+ mergeAnimationOptions(element, existingAnimation.options, options);
+ return existingAnimation.runner;
+ }
+ }
+
+ var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation);
+ if (cancelAnimationFlag) {
+ if (existingAnimation.state === RUNNING_STATE) {
+ // this will end the animation right away and it is safe
+ // to do so since the animation is already running and the
+ // runner callback code will run in async
+ existingAnimation.runner.end();
+ } else if (existingAnimation.structural) {
+ // this means that the animation is queued into a digest, but
+ // hasn't started yet. Therefore it is safe to run the close
+ // method which will call the runner methods in async.
+ existingAnimation.close();
+ } else {
+ // this will merge the new animation options into existing animation options
+ mergeAnimationOptions(element, existingAnimation.options, newAnimation.options);
+ return existingAnimation.runner;
+ }
+ } else {
+ // a joined animation means that this animation will take over the existing one
+ // so an example would involve a leave animation taking over an enter. Then when
+ // the postDigest kicks in the enter will be ignored.
+ var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation);
+ if (joinAnimationFlag) {
+ if (existingAnimation.state === RUNNING_STATE) {
+ normalizeAnimationOptions(element, options);
+ } else {
+ applyGeneratedPreparationClasses(element, isStructural ? event : null, options);
+
+ event = newAnimation.event = existingAnimation.event;
+ options = mergeAnimationOptions(element, existingAnimation.options, newAnimation.options);
+
+ //we return the same runner since only the option values of this animation will
+ //be fed into the `existingAnimation`.
+ return existingAnimation.runner;
+ }
+ }
+ }
+ } else {
+ // normalization in this case means that it removes redundant CSS classes that
+ // already exist (addClass) or do not exist (removeClass) on the element
+ normalizeAnimationOptions(element, options);
+ }
+
+ // when the options are merged and cleaned up we may end up not having to do
+ // an animation at all, therefore we should check this before issuing a post
+ // digest callback. Structural animations will always run no matter what.
+ var isValidAnimation = newAnimation.structural;
+ if (!isValidAnimation) {
+ // animate (from/to) can be quickly checked first, otherwise we check if any classes are present
+ isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0)
+ || hasAnimationClasses(newAnimation.options);
+ }
+
+ if (!isValidAnimation) {
+ close();
+ clearElementAnimationState(element);
+ return runner;
+ }
+
+ // the counter keeps track of cancelled animations
+ var counter = (existingAnimation.counter || 0) + 1;
+ newAnimation.counter = counter;
+
+ markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation);
+
+ $rootScope.$$postDigest(function() {
+ var animationDetails = activeAnimationsLookup.get(node);
+ var animationCancelled = !animationDetails;
+ animationDetails = animationDetails || {};
+
+ // if addClass/removeClass is called before something like enter then the
+ // registered parent element may not be present. The code below will ensure
+ // that a final value for parent element is obtained
+ var parentElement = element.parent() || [];
+
+ // animate/structural/class-based animations all have requirements. Otherwise there
+ // is no point in performing an animation. The parent node must also be set.
+ var isValidAnimation = parentElement.length > 0
+ && (animationDetails.event === 'animate'
+ || animationDetails.structural
+ || hasAnimationClasses(animationDetails.options));
+
+ // this means that the previous animation was cancelled
+ // even if the follow-up animation is the same event
+ if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) {
+ // if another animation did not take over then we need
+ // to make sure that the domOperation and options are
+ // handled accordingly
+ if (animationCancelled) {
+ applyAnimationClasses(element, options);
+ applyAnimationStyles(element, options);
+ }
+
+ // if the event changed from something like enter to leave then we do
+ // it, otherwise if it's the same then the end result will be the same too
+ if (animationCancelled || (isStructural && animationDetails.event !== event)) {
+ options.domOperation();
+ runner.end();
+ }
+
+ // in the event that the element animation was not cancelled or a follow-up animation
+ // isn't allowed to animate from here then we need to clear the state of the element
+ // so that any future animations won't read the expired animation data.
+ if (!isValidAnimation) {
+ clearElementAnimationState(element);
+ }
+
+ return;
+ }
+
+ // this combined multiple class to addClass / removeClass into a setClass event
+ // so long as a structural event did not take over the animation
+ event = !animationDetails.structural && hasAnimationClasses(animationDetails.options, true)
+ ? 'setClass'
+ : animationDetails.event;
+
+ markElementAnimationState(element, RUNNING_STATE);
+ var realRunner = $$animation(element, event, animationDetails.options);
+
+ realRunner.done(function(status) {
+ close(!status);
+ var animationDetails = activeAnimationsLookup.get(node);
+ if (animationDetails && animationDetails.counter === counter) {
+ clearElementAnimationState(getDomNode(element));
+ }
+ notifyProgress(runner, event, 'close', {});
+ });
+
+ // this will update the runner's flow-control events based on
+ // the `realRunner` object.
+ runner.setHost(realRunner);
+ notifyProgress(runner, event, 'start', {});
+ });
+
+ return runner;
+
+ function notifyProgress(runner, event, phase, data) {
+ runInNextPostDigestOrNow(function() {
+ var callbacks = findCallbacks(parent, element, event);
+ if (callbacks.length) {
+ // do not optimize this call here to RAF because
+ // we don't know how heavy the callback code here will
+ // be and if this code is buffered then this can
+ // lead to a performance regression.
+ $$rAF(function() {
+ forEach(callbacks, function(callback) {
+ callback(element, phase, data);
+ });
+ });
+ }
+ });
+ runner.progress(event, phase, data);
+ }
+
+ function close(reject) { // jshint ignore:line
+ clearGeneratedClasses(element, options);
+ applyAnimationClasses(element, options);
+ applyAnimationStyles(element, options);
+ options.domOperation();
+ runner.complete(!reject);
+ }
+ }
+
+ function closeChildAnimations(element) {
+ var node = getDomNode(element);
+ var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']');
+ forEach(children, function(child) {
+ var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME));
+ var animationDetails = activeAnimationsLookup.get(child);
+ switch (state) {
+ case RUNNING_STATE:
+ animationDetails.runner.end();
+ /* falls through */
+ case PRE_DIGEST_STATE:
+ if (animationDetails) {
+ activeAnimationsLookup.remove(child);
+ }
+ break;
+ }
+ });
+ }
+
+ function clearElementAnimationState(element) {
+ var node = getDomNode(element);
+ node.removeAttribute(NG_ANIMATE_ATTR_NAME);
+ activeAnimationsLookup.remove(node);
+ }
+
+ function isMatchingElement(nodeOrElmA, nodeOrElmB) {
+ return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB);
+ }
+
+ function areAnimationsAllowed(element, parentElement, event) {
+ var bodyElement = jqLite($document[0].body);
+ var bodyElementDetected = isMatchingElement(element, bodyElement) || element[0].nodeName === 'HTML';
+ var rootElementDetected = isMatchingElement(element, $rootElement);
+ var parentAnimationDetected = false;
+ var animateChildren;
+
+ var parentHost = element.data(NG_ANIMATE_PIN_DATA);
+ if (parentHost) {
+ parentElement = parentHost;
+ }
+
+ while (parentElement && parentElement.length) {
+ if (!rootElementDetected) {
+ // angular doesn't want to attempt to animate elements outside of the application
+ // therefore we need to ensure that the rootElement is an ancestor of the current element
+ rootElementDetected = isMatchingElement(parentElement, $rootElement);
+ }
+
+ var parentNode = parentElement[0];
+ if (parentNode.nodeType !== ELEMENT_NODE) {
+ // no point in inspecting the #document element
+ break;
+ }
+
+ var details = activeAnimationsLookup.get(parentNode) || {};
+ // either an enter, leave or move animation will commence
+ // therefore we can't allow any animations to take place
+ // but if a parent animation is class-based then that's ok
+ if (!parentAnimationDetected) {
+ parentAnimationDetected = details.structural || disabledElementsLookup.get(parentNode);
+ }
+
+ if (isUndefined(animateChildren) || animateChildren === true) {
+ var value = parentElement.data(NG_ANIMATE_CHILDREN_DATA);
+ if (isDefined(value)) {
+ animateChildren = value;
+ }
+ }
+
+ // there is no need to continue traversing at this point
+ if (parentAnimationDetected && animateChildren === false) break;
+
+ if (!rootElementDetected) {
+ // angular doesn't want to attempt to animate elements outside of the application
+ // therefore we need to ensure that the rootElement is an ancestor of the current element
+ rootElementDetected = isMatchingElement(parentElement, $rootElement);
+ if (!rootElementDetected) {
+ parentHost = parentElement.data(NG_ANIMATE_PIN_DATA);
+ if (parentHost) {
+ parentElement = parentHost;
+ }
+ }
+ }
+
+ if (!bodyElementDetected) {
+ // we also need to ensure that the element is or will be apart of the body element
+ // otherwise it is pointless to even issue an animation to be rendered
+ bodyElementDetected = isMatchingElement(parentElement, bodyElement);
+ }
+
+ parentElement = parentElement.parent();
+ }
+
+ var allowAnimation = !parentAnimationDetected || animateChildren;
+ return allowAnimation && rootElementDetected && bodyElementDetected;
+ }
+
+ function markElementAnimationState(element, state, details) {
+ details = details || {};
+ details.state = state;
+
+ var node = getDomNode(element);
+ node.setAttribute(NG_ANIMATE_ATTR_NAME, state);
+
+ var oldValue = activeAnimationsLookup.get(node);
+ var newValue = oldValue
+ ? extend(oldValue, details)
+ : details;
+ activeAnimationsLookup.put(node, newValue);
+ }
+ }];
+}];
+
+var $$AnimateAsyncRunFactory = ['$$rAF', function($$rAF) {
+ var waitQueue = [];
+
+ function waitForTick(fn) {
+ waitQueue.push(fn);
+ if (waitQueue.length > 1) return;
+ $$rAF(function() {
+ for (var i = 0; i < waitQueue.length; i++) {
+ waitQueue[i]();
+ }
+ waitQueue = [];
+ });
+ }
+
+ return function() {
+ var passed = false;
+ waitForTick(function() {
+ passed = true;
+ });
+ return function(callback) {
+ passed ? callback() : waitForTick(callback);
+ };
+ };
+}];
+
+var $$AnimateRunnerFactory = ['$q', '$sniffer', '$$animateAsyncRun',
+ function($q, $sniffer, $$animateAsyncRun) {
+
+ var INITIAL_STATE = 0;
+ var DONE_PENDING_STATE = 1;
+ var DONE_COMPLETE_STATE = 2;
+
+ AnimateRunner.chain = function(chain, callback) {
+ var index = 0;
+
+ next();
+ function next() {
+ if (index === chain.length) {
+ callback(true);
+ return;
+ }
+
+ chain[index](function(response) {
+ if (response === false) {
+ callback(false);
+ return;
+ }
+ index++;
+ next();
+ });
+ }
+ };
+
+ AnimateRunner.all = function(runners, callback) {
+ var count = 0;
+ var status = true;
+ forEach(runners, function(runner) {
+ runner.done(onProgress);
+ });
+
+ function onProgress(response) {
+ status = status && response;
+ if (++count === runners.length) {
+ callback(status);
+ }
+ }
+ };
+
+ function AnimateRunner(host) {
+ this.setHost(host);
+
+ this._doneCallbacks = [];
+ this._runInAnimationFrame = $$animateAsyncRun();
+ this._state = 0;
+ }
+
+ AnimateRunner.prototype = {
+ setHost: function(host) {
+ this.host = host || {};
+ },
+
+ done: function(fn) {
+ if (this._state === DONE_COMPLETE_STATE) {
+ fn();
+ } else {
+ this._doneCallbacks.push(fn);
+ }
+ },
+
+ progress: noop,
+
+ getPromise: function() {
+ if (!this.promise) {
+ var self = this;
+ this.promise = $q(function(resolve, reject) {
+ self.done(function(status) {
+ status === false ? reject() : resolve();
+ });
+ });
+ }
+ return this.promise;
+ },
+
+ then: function(resolveHandler, rejectHandler) {
+ return this.getPromise().then(resolveHandler, rejectHandler);
+ },
+
+ 'catch': function(handler) {
+ return this.getPromise()['catch'](handler);
+ },
+
+ 'finally': function(handler) {
+ return this.getPromise()['finally'](handler);
+ },
+
+ pause: function() {
+ if (this.host.pause) {
+ this.host.pause();
+ }
+ },
+
+ resume: function() {
+ if (this.host.resume) {
+ this.host.resume();
+ }
+ },
+
+ end: function() {
+ if (this.host.end) {
+ this.host.end();
+ }
+ this._resolve(true);
+ },
+
+ cancel: function() {
+ if (this.host.cancel) {
+ this.host.cancel();
+ }
+ this._resolve(false);
+ },
+
+ complete: function(response) {
+ var self = this;
+ if (self._state === INITIAL_STATE) {
+ self._state = DONE_PENDING_STATE;
+ self._runInAnimationFrame(function() {
+ self._resolve(response);
+ });
+ }
+ },
+
+ _resolve: function(response) {
+ if (this._state !== DONE_COMPLETE_STATE) {
+ forEach(this._doneCallbacks, function(fn) {
+ fn(response);
+ });
+ this._doneCallbacks.length = 0;
+ this._state = DONE_COMPLETE_STATE;
+ }
+ }
+ };
+
+ return AnimateRunner;
+}];
+
+var $$AnimationProvider = ['$animateProvider', function($animateProvider) {
+ var NG_ANIMATE_REF_ATTR = 'ng-animate-ref';
+
+ var drivers = this.drivers = [];
+
+ var RUNNER_STORAGE_KEY = '$$animationRunner';
+
+ function setRunner(element, runner) {
+ element.data(RUNNER_STORAGE_KEY, runner);
+ }
+
+ function removeRunner(element) {
+ element.removeData(RUNNER_STORAGE_KEY);
+ }
+
+ function getRunner(element) {
+ return element.data(RUNNER_STORAGE_KEY);
+ }
+
+ this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$HashMap', '$$rAFScheduler',
+ function($$jqLite, $rootScope, $injector, $$AnimateRunner, $$HashMap, $$rAFScheduler) {
+
+ var animationQueue = [];
+ var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
+
+ function sortAnimations(animations) {
+ var tree = { children: [] };
+ var i, lookup = new $$HashMap();
+
+ // this is done first beforehand so that the hashmap
+ // is filled with a list of the elements that will be animated
+ for (i = 0; i < animations.length; i++) {
+ var animation = animations[i];
+ lookup.put(animation.domNode, animations[i] = {
+ domNode: animation.domNode,
+ fn: animation.fn,
+ children: []
+ });
+ }
+
+ for (i = 0; i < animations.length; i++) {
+ processNode(animations[i]);
+ }
+
+ return flatten(tree);
+
+ function processNode(entry) {
+ if (entry.processed) return entry;
+ entry.processed = true;
+
+ var elementNode = entry.domNode;
+ var parentNode = elementNode.parentNode;
+ lookup.put(elementNode, entry);
+
+ var parentEntry;
+ while (parentNode) {
+ parentEntry = lookup.get(parentNode);
+ if (parentEntry) {
+ if (!parentEntry.processed) {
+ parentEntry = processNode(parentEntry);
+ }
+ break;
+ }
+ parentNode = parentNode.parentNode;
+ }
+
+ (parentEntry || tree).children.push(entry);
+ return entry;
+ }
+
+ function flatten(tree) {
+ var result = [];
+ var queue = [];
+ var i;
+
+ for (i = 0; i < tree.children.length; i++) {
+ queue.push(tree.children[i]);
+ }
+
+ var remainingLevelEntries = queue.length;
+ var nextLevelEntries = 0;
+ var row = [];
+
+ for (i = 0; i < queue.length; i++) {
+ var entry = queue[i];
+ if (remainingLevelEntries <= 0) {
+ remainingLevelEntries = nextLevelEntries;
+ nextLevelEntries = 0;
+ result.push(row);
+ row = [];
+ }
+ row.push(entry.fn);
+ entry.children.forEach(function(childEntry) {
+ nextLevelEntries++;
+ queue.push(childEntry);
+ });
+ remainingLevelEntries--;
+ }
+
+ if (row.length) {
+ result.push(row);
+ }
+
+ return result;
+ }
+ }
+
+ // TODO(matsko): document the signature in a better way
+ return function(element, event, options) {
+ options = prepareAnimationOptions(options);
+ var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
+
+ // there is no animation at the current moment, however
+ // these runner methods will get later updated with the
+ // methods leading into the driver's end/cancel methods
+ // for now they just stop the animation from starting
+ var runner = new $$AnimateRunner({
+ end: function() { close(); },
+ cancel: function() { close(true); }
+ });
+
+ if (!drivers.length) {
+ close();
+ return runner;
+ }
+
+ setRunner(element, runner);
+
+ var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass));
+ var tempClasses = options.tempClasses;
+ if (tempClasses) {
+ classes += ' ' + tempClasses;
+ options.tempClasses = null;
+ }
+
+ animationQueue.push({
+ // this data is used by the postDigest code and passed into
+ // the driver step function
+ element: element,
+ classes: classes,
+ event: event,
+ structural: isStructural,
+ options: options,
+ beforeStart: beforeStart,
+ close: close
+ });
+
+ element.on('$destroy', handleDestroyedElement);
+
+ // we only want there to be one function called within the post digest
+ // block. This way we can group animations for all the animations that
+ // were apart of the same postDigest flush call.
+ if (animationQueue.length > 1) return runner;
+
+ $rootScope.$$postDigest(function() {
+ var animations = [];
+ forEach(animationQueue, function(entry) {
+ // the element was destroyed early on which removed the runner
+ // form its storage. This means we can't animate this element
+ // at all and it already has been closed due to destruction.
+ if (getRunner(entry.element)) {
+ animations.push(entry);
+ } else {
+ entry.close();
+ }
+ });
+
+ // now any future animations will be in another postDigest
+ animationQueue.length = 0;
+
+ var groupedAnimations = groupAnimations(animations);
+ var toBeSortedAnimations = [];
+
+ forEach(groupedAnimations, function(animationEntry) {
+ toBeSortedAnimations.push({
+ domNode: getDomNode(animationEntry.from ? animationEntry.from.element : animationEntry.element),
+ fn: function triggerAnimationStart() {
+ // it's important that we apply the `ng-animate` CSS class and the
+ // temporary classes before we do any driver invoking since these
+ // CSS classes may be required for proper CSS detection.
+ animationEntry.beforeStart();
+
+ var startAnimationFn, closeFn = animationEntry.close;
+
+ // in the event that the element was removed before the digest runs or
+ // during the RAF sequencing then we should not trigger the animation.
+ var targetElement = animationEntry.anchors
+ ? (animationEntry.from.element || animationEntry.to.element)
+ : animationEntry.element;
+
+ if (getRunner(targetElement)) {
+ var operation = invokeFirstDriver(animationEntry);
+ if (operation) {
+ startAnimationFn = operation.start;
+ }
+ }
+
+ if (!startAnimationFn) {
+ closeFn();
+ } else {
+ var animationRunner = startAnimationFn();
+ animationRunner.done(function(status) {
+ closeFn(!status);
+ });
+ updateAnimationRunners(animationEntry, animationRunner);
+ }
+ }
+ });
+ });
+
+ // we need to sort each of the animations in order of parent to child
+ // relationships. This ensures that the child classes are applied at the
+ // right time.
+ $$rAFScheduler(sortAnimations(toBeSortedAnimations));
+ });
+
+ return runner;
+
+ // TODO(matsko): change to reference nodes
+ function getAnchorNodes(node) {
+ var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']';
+ var items = node.hasAttribute(NG_ANIMATE_REF_ATTR)
+ ? [node]
+ : node.querySelectorAll(SELECTOR);
+ var anchors = [];
+ forEach(items, function(node) {
+ var attr = node.getAttribute(NG_ANIMATE_REF_ATTR);
+ if (attr && attr.length) {
+ anchors.push(node);
+ }
+ });
+ return anchors;
+ }
+
+ function groupAnimations(animations) {
+ var preparedAnimations = [];
+ var refLookup = {};
+ forEach(animations, function(animation, index) {
+ var element = animation.element;
+ var node = getDomNode(element);
+ var event = animation.event;
+ var enterOrMove = ['enter', 'move'].indexOf(event) >= 0;
+ var anchorNodes = animation.structural ? getAnchorNodes(node) : [];
+
+ if (anchorNodes.length) {
+ var direction = enterOrMove ? 'to' : 'from';
+
+ forEach(anchorNodes, function(anchor) {
+ var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR);
+ refLookup[key] = refLookup[key] || {};
+ refLookup[key][direction] = {
+ animationID: index,
+ element: jqLite(anchor)
+ };
+ });
+ } else {
+ preparedAnimations.push(animation);
+ }
+ });
+
+ var usedIndicesLookup = {};
+ var anchorGroups = {};
+ forEach(refLookup, function(operations, key) {
+ var from = operations.from;
+ var to = operations.to;
+
+ if (!from || !to) {
+ // only one of these is set therefore we can't have an
+ // anchor animation since all three pieces are required
+ var index = from ? from.animationID : to.animationID;
+ var indexKey = index.toString();
+ if (!usedIndicesLookup[indexKey]) {
+ usedIndicesLookup[indexKey] = true;
+ preparedAnimations.push(animations[index]);
+ }
+ return;
+ }
+
+ var fromAnimation = animations[from.animationID];
+ var toAnimation = animations[to.animationID];
+ var lookupKey = from.animationID.toString();
+ if (!anchorGroups[lookupKey]) {
+ var group = anchorGroups[lookupKey] = {
+ structural: true,
+ beforeStart: function() {
+ fromAnimation.beforeStart();
+ toAnimation.beforeStart();
+ },
+ close: function() {
+ fromAnimation.close();
+ toAnimation.close();
+ },
+ classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes),
+ from: fromAnimation,
+ to: toAnimation,
+ anchors: [] // TODO(matsko): change to reference nodes
+ };
+
+ // the anchor animations require that the from and to elements both have at least
+ // one shared CSS class which effictively marries the two elements together to use
+ // the same animation driver and to properly sequence the anchor animation.
+ if (group.classes.length) {
+ preparedAnimations.push(group);
+ } else {
+ preparedAnimations.push(fromAnimation);
+ preparedAnimations.push(toAnimation);
+ }
+ }
+
+ anchorGroups[lookupKey].anchors.push({
+ 'out': from.element, 'in': to.element
+ });
+ });
+
+ return preparedAnimations;
+ }
+
+ function cssClassesIntersection(a,b) {
+ a = a.split(' ');
+ b = b.split(' ');
+ var matches = [];
+
+ for (var i = 0; i < a.length; i++) {
+ var aa = a[i];
+ if (aa.substring(0,3) === 'ng-') continue;
+
+ for (var j = 0; j < b.length; j++) {
+ if (aa === b[j]) {
+ matches.push(aa);
+ break;
+ }
+ }
+ }
+
+ return matches.join(' ');
+ }
+
+ function invokeFirstDriver(animationDetails) {
+ // we loop in reverse order since the more general drivers (like CSS and JS)
+ // may attempt more elements, but custom drivers are more particular
+ for (var i = drivers.length - 1; i >= 0; i--) {
+ var driverName = drivers[i];
+ if (!$injector.has(driverName)) continue; // TODO(matsko): remove this check
+
+ var factory = $injector.get(driverName);
+ var driver = factory(animationDetails);
+ if (driver) {
+ return driver;
+ }
+ }
+ }
+
+ function beforeStart() {
+ element.addClass(NG_ANIMATE_CLASSNAME);
+ if (tempClasses) {
+ $$jqLite.addClass(element, tempClasses);
+ }
+ }
+
+ function updateAnimationRunners(animation, newRunner) {
+ if (animation.from && animation.to) {
+ update(animation.from.element);
+ update(animation.to.element);
+ } else {
+ update(animation.element);
+ }
+
+ function update(element) {
+ getRunner(element).setHost(newRunner);
+ }
+ }
+
+ function handleDestroyedElement() {
+ var runner = getRunner(element);
+ if (runner && (event !== 'leave' || !options.$$domOperationFired)) {
+ runner.end();
+ }
+ }
+
+ function close(rejected) { // jshint ignore:line
+ element.off('$destroy', handleDestroyedElement);
+ removeRunner(element);
+
+ applyAnimationClasses(element, options);
+ applyAnimationStyles(element, options);
+ options.domOperation();
+
+ if (tempClasses) {
+ $$jqLite.removeClass(element, tempClasses);
+ }
+
+ element.removeClass(NG_ANIMATE_CLASSNAME);
+ runner.complete(!rejected);
+ }
+ };
+ }];
+}];
+
+/* global angularAnimateModule: true,
+
+ $$AnimateAsyncRunFactory,
+ $$rAFSchedulerFactory,
+ $$AnimateChildrenDirective,
+ $$AnimateRunnerFactory,
+ $$AnimateQueueProvider,
+ $$AnimationProvider,
+ $AnimateCssProvider,
+ $$AnimateCssDriverProvider,
+ $$AnimateJsProvider,
+ $$AnimateJsDriverProvider,
+*/
+
+/**
+ * @ngdoc module
+ * @name ngAnimate
+ * @description
+ *
+ * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via
+ * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` the animation hooks are enabled for an Angular app.
+ *
+ * <div doc-module-components="ngAnimate"></div>
+ *
+ * # Usage
+ * Simply put, there are two ways to make use of animations when ngAnimate is used: by using **CSS** and **JavaScript**. The former works purely based
+ * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For
+ * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within
+ * the HTML element that the animation will be triggered on.
+ *
+ * ## Directive Support
+ * The following directives are "animation aware":
+ *
+ * | Directive | Supported Animations |
+ * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|
+ * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move |
+ * | {@link ngRoute.directive:ngView#animations ngView} | enter and leave |
+ * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave |
+ * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave |
+ * | {@link ng.directive:ngIf#animations ngIf} | enter and leave |
+ * | {@link ng.directive:ngClass#animations ngClass} | add and remove (the CSS class(es) present) |
+ * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide} | add and remove (the ng-hide class value) |
+ * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) |
+ * | {@link module:ngMessages#animations ngMessages} | add and remove (ng-active & ng-inactive) |
+ * | {@link module:ngMessages#animations ngMessage} | enter and leave |
+ *
+ * (More information can be found by visiting each the documentation associated with each directive.)
+ *
+ * ## CSS-based Animations
+ *
+ * CSS-based animations with ngAnimate are unique since they require no JavaScript code at all. By using a CSS class that we reference between our HTML
+ * and CSS code we can create an animation that will be picked up by Angular when an the underlying directive performs an operation.
+ *
+ * The example below shows how an `enter` animation can be made possible on an element using `ng-if`:
+ *
+ * ```html
+ * <div ng-if="bool" class="fade">
+ * Fade me in out
+ * </div>
+ * <button ng-click="bool=true">Fade In!</button>
+ * <button ng-click="bool=false">Fade Out!</button>
+ * ```
+ *
+ * Notice the CSS class **fade**? We can now create the CSS transition code that references this class:
+ *
+ * ```css
+ * /* The starting CSS styles for the enter animation */
+ * .fade.ng-enter {
+ * transition:0.5s linear all;
+ * opacity:0;
+ * }
+ *
+ * /* The finishing CSS styles for the enter animation */
+ * .fade.ng-enter.ng-enter-active {
+ * opacity:1;
+ * }
+ * ```
+ *
+ * The key thing to remember here is that, depending on the animation event (which each of the directives above trigger depending on what's going on) two
+ * generated CSS classes will be applied to the element; in the example above we have `.ng-enter` and `.ng-enter-active`. For CSS transitions, the transition
+ * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards.
+ *
+ * If for example we wanted to create animations for `leave` and `move` (ngRepeat triggers move) then we can do so using the same CSS naming conventions:
+ *
+ * ```css
+ * /* now the element will fade out before it is removed from the DOM */
+ * .fade.ng-leave {
+ * transition:0.5s linear all;
+ * opacity:1;
+ * }
+ * .fade.ng-leave.ng-leave-active {
+ * opacity:0;
+ * }
+ * ```
+ *
+ * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class:
+ *
+ * ```css
+ * /* there is no need to define anything inside of the destination
+ * CSS class since the keyframe will take charge of the animation */
+ * .fade.ng-leave {
+ * animation: my_fade_animation 0.5s linear;
+ * -webkit-animation: my_fade_animation 0.5s linear;
+ * }
+ *
+ * @keyframes my_fade_animation {
+ * from { opacity:1; }
+ * to { opacity:0; }
+ * }
+ *
+ * @-webkit-keyframes my_fade_animation {
+ * from { opacity:1; }
+ * to { opacity:0; }
+ * }
+ * ```
+ *
+ * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element.
+ *
+ * ### CSS Class-based Animations
+ *
+ * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different
+ * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added
+ * and removed.
+ *
+ * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class:
+ *
+ * ```html
+ * <div ng-show="bool" class="fade">
+ * Show and hide me
+ * </div>
+ * <button ng-click="bool=true">Toggle</button>
+ *
+ * <style>
+ * .fade.ng-hide {
+ * transition:0.5s linear all;
+ * opacity:0;
+ * }
+ * </style>
+ * ```
+ *
+ * All that is going on here with ngShow/ngHide behind the scenes is the `.ng-hide` class is added/removed (when the hidden state is valid). Since
+ * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest.
+ *
+ * In addition the addition and removal of the CSS class, ngAnimate also provides two helper methods that we can use to further decorate the animation
+ * with CSS styles.
+ *
+ * ```html
+ * <div ng-class="{on:onOff}" class="highlight">
+ * Highlight this box
+ * </div>
+ * <button ng-click="onOff=!onOff">Toggle</button>
+ *
+ * <style>
+ * .highlight {
+ * transition:0.5s linear all;
+ * }
+ * .highlight.on-add {
+ * background:white;
+ * }
+ * .highlight.on {
+ * background:yellow;
+ * }
+ * .highlight.on-remove {
+ * background:black;
+ * }
+ * </style>
+ * ```
+ *
+ * We can also make use of CSS keyframes by placing them within the CSS classes.
+ *
+ *
+ * ### CSS Staggering Animations
+ * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a
+ * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be
+ * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for
+ * the animation. The style property expected within the stagger class can either be a **transition-delay** or an
+ * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).
+ *
+ * ```css
+ * .my-animation.ng-enter {
+ * /* standard transition code */
+ * transition: 1s linear all;
+ * opacity:0;
+ * }
+ * .my-animation.ng-enter-stagger {
+ * /* this will have a 100ms delay between each successive leave animation */
+ * transition-delay: 0.1s;
+ *
+ * /* As of 1.4.4, this must always be set: it signals ngAnimate
+ * to not accidentally inherit a delay property from another CSS class */
+ * transition-duration: 0s;
+ * }
+ * .my-animation.ng-enter.ng-enter-active {
+ * /* standard transition styles */
+ * opacity:1;
+ * }
+ * ```
+ *
+ * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations
+ * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this
+ * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation
+ * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired.
+ *
+ * The following code will issue the **ng-leave-stagger** event on the element provided:
+ *
+ * ```js
+ * var kids = parent.children();
+ *
+ * $animate.leave(kids[0]); //stagger index=0
+ * $animate.leave(kids[1]); //stagger index=1
+ * $animate.leave(kids[2]); //stagger index=2
+ * $animate.leave(kids[3]); //stagger index=3
+ * $animate.leave(kids[4]); //stagger index=4
+ *
+ * window.requestAnimationFrame(function() {
+ * //stagger has reset itself
+ * $animate.leave(kids[5]); //stagger index=0
+ * $animate.leave(kids[6]); //stagger index=1
+ *
+ * $scope.$digest();
+ * });
+ * ```
+ *
+ * Stagger animations are currently only supported within CSS-defined animations.
+ *
+ * ### The `ng-animate` CSS class
+ *
+ * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation.
+ * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations).
+ *
+ * Therefore, animations can be applied to an element using this temporary class directly via CSS.
+ *
+ * ```css
+ * .zipper.ng-animate {
+ * transition:0.5s linear all;
+ * }
+ * .zipper.ng-enter {
+ * opacity:0;
+ * }
+ * .zipper.ng-enter.ng-enter-active {
+ * opacity:1;
+ * }
+ * .zipper.ng-leave {
+ * opacity:1;
+ * }
+ * .zipper.ng-leave.ng-leave-active {
+ * opacity:0;
+ * }
+ * ```
+ *
+ * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove
+ * the CSS class once an animation has completed.)
+ *
+ *
+ * ## JavaScript-based Animations
+ *
+ * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared
+ * CSS class that is referenced in our HTML code) but in addition we need to register the JavaScript animation on the module. By making use of the
+ * `module.animation()` module function we can register the ainmation.
+ *
+ * Let's see an example of a enter/leave animation using `ngRepeat`:
+ *
+ * ```html
+ * <div ng-repeat="item in items" class="slide">
+ * {{ item }}
+ * </div>
+ * ```
+ *
+ * See the **slide** CSS class? Let's use that class to define an animation that we'll structure in our module code by using `module.animation`:
+ *
+ * ```js
+ * myModule.animation('.slide', [function() {
+ * return {
+ * // make note that other events (like addClass/removeClass)
+ * // have different function input parameters
+ * enter: function(element, doneFn) {
+ * jQuery(element).fadeIn(1000, doneFn);
+ *
+ * // remember to call doneFn so that angular
+ * // knows that the animation has concluded
+ * },
+ *
+ * move: function(element, doneFn) {
+ * jQuery(element).fadeIn(1000, doneFn);
+ * },
+ *
+ * leave: function(element, doneFn) {
+ * jQuery(element).fadeOut(1000, doneFn);
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as
+ * greensock.js and velocity.js.
+ *
+ * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define
+ * our animations inside of the same registered animation, however, the function input arguments are a bit different:
+ *
+ * ```html
+ * <div ng-class="color" class="colorful">
+ * this box is moody
+ * </div>
+ * <button ng-click="color='red'">Change to red</button>
+ * <button ng-click="color='blue'">Change to blue</button>
+ * <button ng-click="color='green'">Change to green</button>
+ * ```
+ *
+ * ```js
+ * myModule.animation('.colorful', [function() {
+ * return {
+ * addClass: function(element, className, doneFn) {
+ * // do some cool animation and call the doneFn
+ * },
+ * removeClass: function(element, className, doneFn) {
+ * // do some cool animation and call the doneFn
+ * },
+ * setClass: function(element, addedClass, removedClass, doneFn) {
+ * // do some cool animation and call the doneFn
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * ## CSS + JS Animations Together
+ *
+ * AngularJS 1.4 and higher has taken steps to make the amalgamation of CSS and JS animations more flexible. However, unlike earlier versions of Angular,
+ * defining CSS and JS animations to work off of the same CSS class will not work anymore. Therefore the example below will only result in **JS animations taking
+ * charge of the animation**:
+ *
+ * ```html
+ * <div ng-if="bool" class="slide">
+ * Slide in and out
+ * </div>
+ * ```
+ *
+ * ```js
+ * myModule.animation('.slide', [function() {
+ * return {
+ * enter: function(element, doneFn) {
+ * jQuery(element).slideIn(1000, doneFn);
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * ```css
+ * .slide.ng-enter {
+ * transition:0.5s linear all;
+ * transform:translateY(-100px);
+ * }
+ * .slide.ng-enter.ng-enter-active {
+ * transform:translateY(0);
+ * }
+ * ```
+ *
+ * Does this mean that CSS and JS animations cannot be used together? Do JS-based animations always have higher priority? We can make up for the
+ * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from
+ * our own JS-based animation code:
+ *
+ * ```js
+ * myModule.animation('.slide', ['$animateCss', function($animateCss) {
+ * return {
+ * enter: function(element) {
+* // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`.
+ * return $animateCss(element, {
+ * event: 'enter',
+ * structural: true
+ * });
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * The nice thing here is that we can save bandwidth by sticking to our CSS-based animation code and we don't need to rely on a 3rd-party animation framework.
+ *
+ * The `$animateCss` service is very powerful since we can feed in all kinds of extra properties that will be evaluated and fed into a CSS transition or
+ * keyframe animation. For example if we wanted to animate the height of an element while adding and removing classes then we can do so by providing that
+ * data into `$animateCss` directly:
+ *
+ * ```js
+ * myModule.animation('.slide', ['$animateCss', function($animateCss) {
+ * return {
+ * enter: function(element) {
+ * return $animateCss(element, {
+ * event: 'enter',
+ * structural: true,
+ * addClass: 'maroon-setting',
+ * from: { height:0 },
+ * to: { height: 200 }
+ * });
+ * }
+ * }
+ * }]);
+ * ```
+ *
+ * Now we can fill in the rest via our transition CSS code:
+ *
+ * ```css
+ * /* the transition tells ngAnimate to make the animation happen */
+ * .slide.ng-enter { transition:0.5s linear all; }
+ *
+ * /* this extra CSS class will be absorbed into the transition
+ * since the $animateCss code is adding the class */
+ * .maroon-setting { background:red; }
+ * ```
+ *
+ * And `$animateCss` will figure out the rest. Just make sure to have the `done()` callback fire the `doneFn` function to signal when the animation is over.
+ *
+ * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}.
+ *
+ * ## Animation Anchoring (via `ng-animate-ref`)
+ *
+ * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between
+ * structural areas of an application (like views) by pairing up elements using an attribute
+ * called `ng-animate-ref`.
+ *
+ * Let's say for example we have two views that are managed by `ng-view` and we want to show
+ * that there is a relationship between two components situated in within these views. By using the
+ * `ng-animate-ref` attribute we can identify that the two components are paired together and we
+ * can then attach an animation, which is triggered when the view changes.
+ *
+ * Say for example we have the following template code:
+ *
+ * ```html
+ * <!-- index.html -->
+ * <div ng-view class="view-animation">
+ * </div>
+ *
+ * <!-- home.html -->
+ * <a href="#/banner-page">
+ * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
+ * </a>
+ *
+ * <!-- banner-page.html -->
+ * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
+ * ```
+ *
+ * Now, when the view changes (once the link is clicked), ngAnimate will examine the
+ * HTML contents to see if there is a match reference between any components in the view
+ * that is leaving and the view that is entering. It will scan both the view which is being
+ * removed (leave) and inserted (enter) to see if there are any paired DOM elements that
+ * contain a matching ref value.
+ *
+ * The two images match since they share the same ref value. ngAnimate will now create a
+ * transport element (which is a clone of the first image element) and it will then attempt
+ * to animate to the position of the second image element in the next view. For the animation to
+ * work a special CSS class called `ng-anchor` will be added to the transported element.
+ *
+ * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then
+ * ngAnimate will handle the entire transition for us as well as the addition and removal of
+ * any changes of CSS classes between the elements:
+ *
+ * ```css
+ * .banner.ng-anchor {
+ * /* this animation will last for 1 second since there are
+ * two phases to the animation (an `in` and an `out` phase) */
+ * transition:0.5s linear all;
+ * }
+ * ```
+ *
+ * We also **must** include animations for the views that are being entered and removed
+ * (otherwise anchoring wouldn't be possible since the new view would be inserted right away).
+ *
+ * ```css
+ * .view-animation.ng-enter, .view-animation.ng-leave {
+ * transition:0.5s linear all;
+ * position:fixed;
+ * left:0;
+ * top:0;
+ * width:100%;
+ * }
+ * .view-animation.ng-enter {
+ * transform:translateX(100%);
+ * }
+ * .view-animation.ng-leave,
+ * .view-animation.ng-enter.ng-enter-active {
+ * transform:translateX(0%);
+ * }
+ * .view-animation.ng-leave.ng-leave-active {
+ * transform:translateX(-100%);
+ * }
+ * ```
+ *
+ * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur:
+ * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away
+ * from its origin. Once that animation is over then the `in` stage occurs which animates the
+ * element to its destination. The reason why there are two animations is to give enough time
+ * for the enter animation on the new element to be ready.
+ *
+ * The example above sets up a transition for both the in and out phases, but we can also target the out or
+ * in phases directly via `ng-anchor-out` and `ng-anchor-in`.
+ *
+ * ```css
+ * .banner.ng-anchor-out {
+ * transition: 0.5s linear all;
+ *
+ * /* the scale will be applied during the out animation,
+ * but will be animated away when the in animation runs */
+ * transform: scale(1.2);
+ * }
+ *
+ * .banner.ng-anchor-in {
+ * transition: 1s linear all;
+ * }
+ * ```
+ *
+ *
+ *
+ *
+ * ### Anchoring Demo
+ *
+ <example module="anchoringExample"
+ name="anchoringExample"
+ id="anchoringExample"
+ deps="angular-animate.js;angular-route.js"
+ animations="true">
+ <file name="index.html">
+ <a href="#/">Home</a>
+ <hr />
+ <div class="view-container">
+ <div ng-view class="view"></div>
+ </div>
+ </file>
+ <file name="script.js">
+ angular.module('anchoringExample', ['ngAnimate', 'ngRoute'])
+ .config(['$routeProvider', function($routeProvider) {
+ $routeProvider.when('/', {
+ templateUrl: 'home.html',
+ controller: 'HomeController as home'
+ });
+ $routeProvider.when('/profile/:id', {
+ templateUrl: 'profile.html',
+ controller: 'ProfileController as profile'
+ });
+ }])
+ .run(['$rootScope', function($rootScope) {
+ $rootScope.records = [
+ { id:1, title: "Miss Beulah Roob" },
+ { id:2, title: "Trent Morissette" },
+ { id:3, title: "Miss Ava Pouros" },
+ { id:4, title: "Rod Pouros" },
+ { id:5, title: "Abdul Rice" },
+ { id:6, title: "Laurie Rutherford Sr." },
+ { id:7, title: "Nakia McLaughlin" },
+ { id:8, title: "Jordon Blanda DVM" },
+ { id:9, title: "Rhoda Hand" },
+ { id:10, title: "Alexandrea Sauer" }
+ ];
+ }])
+ .controller('HomeController', [function() {
+ //empty
+ }])
+ .controller('ProfileController', ['$rootScope', '$routeParams', function($rootScope, $routeParams) {
+ var index = parseInt($routeParams.id, 10);
+ var record = $rootScope.records[index - 1];
+
+ this.title = record.title;
+ this.id = record.id;
+ }]);
+ </file>
+ <file name="home.html">
+ <h2>Welcome to the home page</h1>
+ <p>Please click on an element</p>
+ <a class="record"
+ ng-href="#/profile/{{ record.id }}"
+ ng-animate-ref="{{ record.id }}"
+ ng-repeat="record in records">
+ {{ record.title }}
+ </a>
+ </file>
+ <file name="profile.html">
+ <div class="profile record" ng-animate-ref="{{ profile.id }}">
+ {{ profile.title }}
+ </div>
+ </file>
+ <file name="animations.css">
+ .record {
+ display:block;
+ font-size:20px;
+ }
+ .profile {
+ background:black;
+ color:white;
+ font-size:100px;
+ }
+ .view-container {
+ position:relative;
+ }
+ .view-container > .view.ng-animate {
+ position:absolute;
+ top:0;
+ left:0;
+ width:100%;
+ min-height:500px;
+ }
+ .view.ng-enter, .view.ng-leave,
+ .record.ng-anchor {
+ transition:0.5s linear all;
+ }
+ .view.ng-enter {
+ transform:translateX(100%);
+ }
+ .view.ng-enter.ng-enter-active, .view.ng-leave {
+ transform:translateX(0%);
+ }
+ .view.ng-leave.ng-leave-active {
+ transform:translateX(-100%);
+ }
+ .record.ng-anchor-out {
+ background:red;
+ }
+ </file>
+ </example>
+ *
+ * ### How is the element transported?
+ *
+ * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting
+ * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element
+ * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The
+ * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match
+ * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied
+ * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class
+ * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element
+ * will become visible since the shim class will be removed.
+ *
+ * ### How is the morphing handled?
+ *
+ * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out
+ * what CSS classes differ between the starting element and the destination element. These different CSS classes
+ * will be added/removed on the anchor element and a transition will be applied (the transition that is provided
+ * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will
+ * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that
+ * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since
+ * the cloned element is placed inside of root element which is likely close to the body element).
+ *
+ * Note that if the root element is on the `<html>` element then the cloned node will be placed inside of body.
+ *
+ *
+ * ## Using $animate in your directive code
+ *
+ * So far we've explored how to feed in animations into an Angular application, but how do we trigger animations within our own directives in our application?
+ * By injecting the `$animate` service into our directive code, we can trigger structural and class-based hooks which can then be consumed by animations. Let's
+ * imagine we have a greeting box that shows and hides itself when the data changes
+ *
+ * ```html
+ * <greeting-box active="onOrOff">Hi there</greeting-box>
+ * ```
+ *
+ * ```js
+ * ngModule.directive('greetingBox', ['$animate', function($animate) {
+ * return function(scope, element, attrs) {
+ * attrs.$observe('active', function(value) {
+ * value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on');
+ * });
+ * });
+ * }]);
+ * ```
+ *
+ * Now the `on` CSS class is added and removed on the greeting box component. Now if we add a CSS class on top of the greeting box element
+ * in our HTML code then we can trigger a CSS or JS animation to happen.
+ *
+ * ```css
+ * /* normally we would create a CSS class to reference on the element */
+ * greeting-box.on { transition:0.5s linear all; background:green; color:white; }
+ * ```
+ *
+ * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's
+ * possible be sure to visit the {@link ng.$animate $animate service API page}.
+ *
+ *
+ * ### Preventing Collisions With Third Party Libraries
+ *
+ * Some third-party frameworks place animation duration defaults across many element or className
+ * selectors in order to make their code small and reuseable. This can lead to issues with ngAnimate, which
+ * is expecting actual animations on these elements and has to wait for their completion.
+ *
+ * You can prevent this unwanted behavior by using a prefix on all your animation classes:
+ *
+ * ```css
+ * /* prefixed with animate- */
+ * .animate-fade-add.animate-fade-add-active {
+ * transition:1s linear all;
+ * opacity:0;
+ * }
+ * ```
+ *
+ * You then configure `$animate` to enforce this prefix:
+ *
+ * ```js
+ * $animateProvider.classNameFilter(/animate-/);
+ * ```
+ *
+ * This also may provide your application with a speed boost since only specific elements containing CSS class prefix
+ * will be evaluated for animation when any DOM changes occur in the application.
+ *
+ * ## Callbacks and Promises
+ *
+ * When `$animate` is called it returns a promise that can be used to capture when the animation has ended. Therefore if we were to trigger
+ * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has
+ * ended by chaining onto the returned promise that animation method returns.
+ *
+ * ```js
+ * // somewhere within the depths of the directive
+ * $animate.enter(element, parent).then(function() {
+ * //the animation has completed
+ * });
+ * ```
+ *
+ * (Note that earlier versions of Angular prior to v1.4 required the promise code to be wrapped using `$scope.$apply(...)`. This is not the case
+ * anymore.)
+ *
+ * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering
+ * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view
+ * routing controller to hook into that:
+ *
+ * ```js
+ * ngModule.controller('HomePageController', ['$animate', function($animate) {
+ * $animate.on('enter', ngViewElement, function(element) {
+ * // the animation for this route has completed
+ * }]);
+ * }])
+ * ```
+ *
+ * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.)
+ */
+
+/**
+ * @ngdoc service
+ * @name $animate
+ * @kind object
+ *
+ * @description
+ * The ngAnimate `$animate` service documentation is the same for the core `$animate` service.
+ *
+ * Click here {@link ng.$animate to learn more about animations with `$animate`}.
+ */
+angular.module('ngAnimate', [])
+ .directive('ngAnimateChildren', $$AnimateChildrenDirective)
+ .factory('$$rAFScheduler', $$rAFSchedulerFactory)
+
+ .factory('$$AnimateRunner', $$AnimateRunnerFactory)
+ .factory('$$animateAsyncRun', $$AnimateAsyncRunFactory)
+
+ .provider('$$animateQueue', $$AnimateQueueProvider)
+ .provider('$$animation', $$AnimationProvider)
+
+ .provider('$animateCss', $AnimateCssProvider)
+ .provider('$$animateCssDriver', $$AnimateCssDriverProvider)
+
+ .provider('$$animateJs', $$AnimateJsProvider)
+ .provider('$$animateJsDriver', $$AnimateJsDriverProvider);
+
+
+})(window, window.angular);
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-animate/angular-animate.min.js b/xos-apps/auto-scale/gui/src/vendor/angular-animate/angular-animate.min.js
new file mode 100644
index 0000000..9461603
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-animate/angular-animate.min.js
@@ -0,0 +1,56 @@
+/*
+ AngularJS v1.4.8
+ (c) 2010-2015 Google, Inc. http://angularjs.org
+ License: MIT
+*/
+(function(H,u,Sa){'use strict';function wa(a,b,c){if(!a)throw ngMinErr("areq",b||"?",c||"required");return a}function xa(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 Ia(a){var b={};a&&(a.to||a.from)&&(b.to=a.to,b.from=a.from);return b}function T(a,b,c){var d="";a=X(a)?a:a&&I(a)&&a.length?a.split(/\s+/):[];q(a,function(a,s){a&&0<a.length&&(d+=0<s?" ":"",d+=c?b+a:a+b)});return d}function Ja(a){if(a instanceof L)switch(a.length){case 0:return[];
+case 1:if(1===a[0].nodeType)return a;break;default:return L(ma(a))}if(1===a.nodeType)return L(a)}function ma(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 Ka(a,b,c){q(b,function(b){a.addClass(b,c)})}function La(a,b,c){q(b,function(b){a.removeClass(b,c)})}function N(a){return function(b,c){c.addClass&&(Ka(a,b,c.addClass),c.addClass=null);c.removeClass&&(La(a,b,c.removeClass),c.removeClass=null)}}function ia(a){a=a||{};if(!a.$$prepared){var b=a.domOperation||
+M;a.domOperation=function(){a.$$domOperationFired=!0;b();b=M};a.$$prepared=!0}return a}function da(a,b){ya(a,b);za(a,b)}function ya(a,b){b.from&&(a.css(b.from),b.from=null)}function za(a,b){b.to&&(a.css(b.to),b.to=null)}function Q(a,b,c){var d=(b.addClass||"")+" "+(c.addClass||""),e=(b.removeClass||"")+" "+(c.removeClass||"");a=Ma(a.attr("class"),d,e);c.preparationClasses&&(b.preparationClasses=Y(c.preparationClasses,b.preparationClasses),delete c.preparationClasses);d=b.domOperation!==M?b.domOperation:
+null;Aa(b,c);d&&(b.domOperation=d);b.addClass=a.addClass?a.addClass:null;b.removeClass=a.removeClass?a.removeClass:null;return b}function Ma(a,b,c){function d(a){I(a)&&(a=a.split(" "));var b={};q(a,function(a){a.length&&(b[a]=!0)});return b}var e={};a=d(a);b=d(b);q(b,function(a,b){e[b]=1});c=d(c);q(c,function(a,b){e[b]=1===e[b]?null:-1});var s={addClass:"",removeClass:""};q(e,function(b,c){var e,d;1===b?(e="addClass",d=!a[c]):-1===b&&(e="removeClass",d=a[c]);d&&(s[e].length&&(s[e]+=" "),s[e]+=c)});
+return s}function B(a){return a instanceof u.element?a[0]:a}function Na(a,b,c){var d="";b&&(d=T(b,"ng-",!0));c.addClass&&(d=Y(d,T(c.addClass,"-add")));c.removeClass&&(d=Y(d,T(c.removeClass,"-remove")));d.length&&(c.preparationClasses=d,a.addClass(d))}function ja(a,b){var c=b?"-"+b+"s":"";ea(a,[fa,c]);return[fa,c]}function na(a,b){var c=b?"paused":"",d=U+"PlayState";ea(a,[d,c]);return[d,c]}function ea(a,b){a.style[b[0]]=b[1]}function Y(a,b){return a?b?a+" "+b:a:b}function Ba(a,b,c){var d=Object.create(null),
+e=a.getComputedStyle(b)||{};q(c,function(a,b){var c=e[a];if(c){var v=c.charAt(0);if("-"===v||"+"===v||0<=v)c=Oa(c);0===c&&(c=null);d[b]=c}});return d}function Oa(a){var b=0;a=a.split(/\s*,\s*/);q(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 oa(a){return 0===a||null!=a}function Ca(a,b){var c=O,d=a+"s";b?c+="Duration":d+=" linear all";return[c,d]}function Da(){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}}}}function Ea(a,b,c){q(c,function(c){a[c]=V(a[c])?a[c]:b.style.getPropertyValue(c)})}var M=u.noop,Aa=u.extend,L=u.element,q=u.forEach,X=u.isArray,I=u.isString,pa=u.isObject,qa=u.isUndefined,V=u.isDefined,Fa=u.isFunction,ra=u.isElement,O,sa,U,ta;qa(H.ontransitionend)&&V(H.onwebkittransitionend)?(O="WebkitTransition",sa="webkitTransitionEnd transitionend"):
+(O="transition",sa="transitionend");qa(H.onanimationend)&&V(H.onwebkitanimationend)?(U="WebkitAnimation",ta="webkitAnimationEnd animationend"):(U="animation",ta="animationend");var ka=U+"Delay",ua=U+"Duration",fa=O+"Delay";H=O+"Duration";var Pa={transitionDuration:H,transitionDelay:fa,transitionProperty:O+"Property",animationDuration:ua,animationDelay:ka,animationIterationCount:U+"IterationCount"},Qa={transitionDuration:H,transitionDelay:fa,animationDuration:ua,animationDelay:ka};u.module("ngAnimate",
+[]).directive("ngAnimateChildren",[function(){return function(a,b,c){a=c.ngAnimateChildren;u.isString(a)&&0===a.length?b.data("$$ngAnimateChildren",!0):c.$observe("ngAnimateChildren",function(a){b.data("$$ngAnimateChildren","on"===a||"true"===a)})}}]).factory("$$rAFScheduler",["$$rAF",function(a){function b(a){d=d.concat(a);c()}function c(){if(d.length){for(var b=d.shift(),h=0;h<b.length;h++)b[h]();e||a(function(){e||c()})}}var d,e;d=b.queue=[];b.waitUntilQuiet=function(b){e&&e();e=a(function(){e=
+null;b();c()})};return b}]).factory("$$AnimateRunner",["$q","$sniffer","$$animateAsyncRun",function(a,b,c){function d(a){this.setHost(a);this._doneCallbacks=[];this._runInAnimationFrame=c();this._state=0}d.chain=function(a,b){function c(){if(d===a.length)b(!0);else a[d](function(a){!1===a?b(!1):(d++,c())})}var d=0;c()};d.all=function(a,b){function c(h){v=v&&h;++d===a.length&&b(v)}var d=0,v=!0;q(a,function(a){a.done(c)})};d.prototype={setHost:function(a){this.host=a||{}},done:function(a){2===this._state?
+a():this._doneCallbacks.push(a)},progress:M,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&&(q(this._doneCallbacks,function(b){b(a)}),this._doneCallbacks.length=0,this._state=2)}};return d}]).factory("$$animateAsyncRun",["$$rAF",function(a){function b(b){c.push(b);1<c.length||a(function(){for(var a=0;a<c.length;a++)c[a]();c=[]})}var c=[];return function(){var a=
+!1;b(function(){a=!0});return function(c){a?c():b(c)}}}]).provider("$$animateQueue",["$animateProvider",function(a){function b(a,b,c,q){return d[a].some(function(a){return a(b,c,q)})}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&&2===c.state&&!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",
+"$$forceReflow",function(d,s,h,g,v,r,$,u,R,C){function D(){var a=!1;return function(b){a?b():s.$$postDigest(function(){a=!0;b()})}}function K(a,b,c){var f=B(b),d=B(a),n=[];(a=t[c])&&q(a,function(a){a.node.contains(f)?n.push(a.callback):"leave"===c&&a.node.contains(d)&&n.push(a.callback)});return n}function l(a,f,k){function n(b,c,f,t){R(function(){var b=K(v,a,c);b.length&&d(function(){q(b,function(b){b(a,f,t)})})});b.progress(c,f,t)}function t(b){var c=a,f=k;f.preparationClasses&&(c.removeClass(f.preparationClasses),
+f.preparationClasses=null);f.activeClasses&&(c.removeClass(f.activeClasses),f.activeClasses=null);Ha(a,k);da(a,k);k.domOperation();h.complete(!b)}var A,v;if(a=Ja(a))A=B(a),v=a.parent();k=ia(k);var h=new $,R=D();X(k.addClass)&&(k.addClass=k.addClass.join(" "));k.addClass&&!I(k.addClass)&&(k.addClass=null);X(k.removeClass)&&(k.removeClass=k.removeClass.join(" "));k.removeClass&&!I(k.removeClass)&&(k.removeClass=null);k.from&&!pa(k.from)&&(k.from=null);k.to&&!pa(k.to)&&(k.to=null);if(!A)return t(),h;
+var z=[A.className,k.addClass,k.removeClass].join(" ");if(!Ra(z))return t(),h;var l=0<=["enter","move","leave"].indexOf(f),g=!G||F.get(A),z=!g&&m.get(A)||{},C=!!z.state;g||C&&1==z.state||(g=!la(a,v,f));if(g)return t(),h;l&&y(a);g={structural:l,element:a,event:f,close:t,options:k,runner:h};if(C){if(b("skip",a,g,z)){if(2===z.state)return t(),h;Q(a,z.options,k);return z.runner}if(b("cancel",a,g,z))if(2===z.state)z.runner.end();else if(z.structural)z.close();else return Q(a,z.options,g.options),z.runner;
+else if(b("join",a,g,z))if(2===z.state)Q(a,k,{});else return Na(a,l?f:null,k),f=g.event=z.event,k=Q(a,z.options,g.options),z.runner}else Q(a,k,{});(C=g.structural)||(C="animate"===g.event&&0<Object.keys(g.options.to||{}).length||c(g.options));if(!C)return t(),w(a),h;var u=(z.counter||0)+1;g.counter=u;x(a,1,g);s.$$postDigest(function(){var b=m.get(A),d=!b,b=b||{},K=0<(a.parent()||[]).length&&("animate"===b.event||b.structural||c(b.options));if(d||b.counter!==u||!K){d&&(Ha(a,k),da(a,k));if(d||l&&b.event!==
+f)k.domOperation(),h.end();K||w(a)}else f=!b.structural&&c(b.options,!0)?"setClass":b.event,x(a,2),b=r(a,f,b.options),b.done(function(b){t(!b);(b=m.get(A))&&b.counter===u&&w(B(a));n(h,f,"close",{})}),h.setHost(b),n(h,f,"start",{})});return h}function y(a){a=B(a).querySelectorAll("[data-ng-animate]");q(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 w(a){a=B(a);a.removeAttribute("data-ng-animate");m.remove(a)}
+function f(a,b){return B(a)===B(b)}function la(a,b,c){c=L(g[0].body);var d=f(a,c)||"HTML"===a[0].nodeName,t=f(a,h),n=!1,w;for((a=a.data("$ngAnimatePin"))&&(b=a);b&&b.length;){t||(t=f(b,h));a=b[0];if(1!==a.nodeType)break;var x=m.get(a)||{};n||(n=x.structural||F.get(a));if(qa(w)||!0===w)a=b.data("$$ngAnimateChildren"),V(a)&&(w=a);if(n&&!1===w)break;t||(t=f(b,h),t||(a=b.data("$ngAnimatePin"))&&(b=a));d||(d=f(b,c));b=b.parent()}return(!n||w)&&t&&d}function x(a,b,c){c=c||{};c.state=b;a=B(a);a.setAttribute("data-ng-animate",
+b);c=(b=m.get(a))?Aa(b,c):c;m.put(a,c)}var m=new v,F=new v,G=null,A=s.$watch(function(){return 0===u.totalPendingRequests},function(a){a&&(A(),s.$$postDigest(function(){s.$$postDigest(function(){null===G&&(G=!0)})}))}),t={},n=a.classNameFilter(),Ra=n?function(a){return n.test(a)}:function(){return!0},Ha=N(R);return{on:function(a,b,c){b=ma(b);t[a]=t[a]||[];t[a].push({node:b,callback:c})},off:function(a,b,c){function f(a,b,c){var d=ma(b);return a.filter(function(a){return!(a.node===d&&(!c||a.callback===
+c))})}var d=t[a];d&&(t[a]=1===arguments.length?null:f(d,b,c))},pin:function(a,b){wa(ra(a),"element","not an element");wa(ra(b),"parentElement","not an element");a.data("$ngAnimatePin",b)},push:function(a,b,c,f){c=c||{};c.domOperation=f;return l(a,b,c)},enabled:function(a,b){var c=arguments.length;if(0===c)b=!!G;else if(ra(a)){var f=B(a),d=F.get(f);1===c?b=!d:(b=!!b)?d&&F.remove(f):F.put(f,!0)}else b=G=!!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","$$HashMap","$$rAFScheduler",function(a,e,s,h,g,v){function r(a){function b(a){if(a.processed)return a;a.processed=!0;var f=a.domNode,d=f.parentNode;e.put(f,a);for(var x;d;){if(x=e.get(d)){x.processed||(x=b(x));break}d=d.parentNode}(x||c).children.push(a);return a}var c={children:[]},d,e=new g;for(d=0;d<a.length;d++){var h=a[d];e.put(h.domNode,a[d]={domNode:h.domNode,fn:h.fn,children:[]})}for(d=0;d<a.length;d++)b(a[d]);
+return function(a){var b=[],c=[],d;for(d=0;d<a.children.length;d++)c.push(a.children[d]);a=c.length;var m=0,e=[];for(d=0;d<c.length;d++){var h=c[d];0>=a&&(a=m,m=0,b.push(e),e=[]);e.push(h.fn);h.children.forEach(function(a){m++;c.push(a)});a--}e.length&&b.push(e);return b}(c)}var $=[],u=N(a);return function(g,C,D){function K(a){a=a.hasAttribute("ng-animate-ref")?[a]:a.querySelectorAll("[ng-animate-ref]");var b=[];q(a,function(a){var c=a.getAttribute("ng-animate-ref");c&&c.length&&b.push(a)});return b}
+function l(a){var b=[],c={};q(a,function(a,f){var d=B(a.element),t=0<=["enter","move"].indexOf(a.event),d=a.structural?K(d):[];if(d.length){var m=t?"to":"from";q(d,function(a){var b=a.getAttribute("ng-animate-ref");c[b]=c[b]||{};c[b][m]={animationID:f,element:L(a)}})}else b.push(a)});var f={},d={};q(c,function(c,m){var w=c.from,e=c.to;if(w&&e){var h=a[w.animationID],g=a[e.animationID],x=w.animationID.toString();if(!d[x]){var A=d[x]={structural:!0,beforeStart:function(){h.beforeStart();g.beforeStart()},
+close:function(){h.close();g.close()},classes:y(h.classes,g.classes),from:h,to:g,anchors:[]};A.classes.length?b.push(A):(b.push(h),b.push(g))}d[x].anchors.push({out:w.element,"in":e.element})}else w=w?w.animationID:e.animationID,e=w.toString(),f[e]||(f[e]=!0,b.push(a[w]))});return b}function y(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 m=0;m<b.length;m++)if(d===b[m]){c.push(d);break}}return c.join(" ")}function w(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 f(a,c){a.from&&a.to?(b(a.from.element).setHost(c),b(a.to.element).setHost(c)):b(a.element).setHost(c)}function la(){var a=b(g);!a||"leave"===C&&D.$$domOperationFired||a.end()}function x(b){g.off("$destroy",la);g.removeData("$$animationRunner");u(g,D);da(g,D);D.domOperation();A&&a.removeClass(g,A);g.removeClass("ng-animate");F.complete(!b)}D=ia(D);var m=0<=["enter","move","leave"].indexOf(C),F=new h({end:function(){x()},
+cancel:function(){x(!0)}});if(!c.length)return x(),F;g.data("$$animationRunner",F);var G=xa(g.attr("class"),xa(D.addClass,D.removeClass)),A=D.tempClasses;A&&(G+=" "+A,D.tempClasses=null);$.push({element:g,classes:G,event:C,structural:m,options:D,beforeStart:function(){g.addClass("ng-animate");A&&a.addClass(g,A)},close:x});g.on("$destroy",la);if(1<$.length)return F;e.$$postDigest(function(){var a=[];q($,function(c){b(c.element)?a.push(c):c.close()});$.length=0;var c=l(a),d=[];q(c,function(a){d.push({domNode:B(a.from?
+a.from.element:a.element),fn:function(){a.beforeStart();var c,d=a.close;if(b(a.anchors?a.from.element||a.to.element:a.element)){var m=w(a);m&&(c=m.start)}c?(c=c(),c.done(function(a){d(!a)}),f(a,c)):d()}})});v(r(d))});return F}}]}]).provider("$animateCss",["$animateProvider",function(a){var b=Da(),c=Da();this.$get=["$window","$$jqLite","$$AnimateRunner","$timeout","$$forceReflow","$sniffer","$$rAFScheduler","$animate",function(a,e,s,h,g,v,r,u){function Ga(a,b){var c=a.parentNode;return(c.$$ngAnimateParentKey||
+(c.$$ngAnimateParentKey=++l))+"-"+a.getAttribute("class")+"-"+b}function R(w,f,h,g){var m;0<b.count(h)&&(m=c.get(h),m||(f=T(f,"-stagger"),e.addClass(w,f),m=Ba(a,w,g),m.animationDuration=Math.max(m.animationDuration,0),m.transitionDuration=Math.max(m.transitionDuration,0),e.removeClass(w,f),c.put(h,m)));return m||{}}function C(a){y.push(a);r.waitUntilQuiet(function(){b.flush();c.flush();for(var a=g(),d=0;d<y.length;d++)y[d](a);y.length=0})}function D(c,f,e){f=b.get(e);f||(f=Ba(a,c,Pa),"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 K=N(e),l=0,y=[];return function(a,c){function d(){m()}function g(){m(!0)}function m(b){if(!(ga||va&&k)){ga=!0;k=!1;c.$$skipPreparationClasses||e.removeClass(a,Z);e.removeClass(a,Y);na(n,!1);ja(n,!1);q(y,function(a){n.style[a[0]]=""});K(a,c);da(a,c);Object.keys(t).length&&
+q(t,function(a,b){a?n.style.setProperty(b,a):n.style.removeProperty(b)});if(c.onDone)c.onDone();H&&H.complete(!b)}}function F(a){p.blockTransition&&ja(n,a);p.blockKeyframeAnimation&&na(n,!!a)}function G(){H=new s({end:d,cancel:g});C(M);m();return{$$willAnimate:!1,start:function(){return H},end:d}}function A(){function b(){if(!ga){F(!1);q(y,function(a){n.style[a[0]]=a[1]});K(a,c);e.addClass(a,Y);if(p.recalculateTimingStyles){ha=n.className+" "+Z;aa=Ga(n,ha);E=D(n,ha,aa);W=E.maxDelay;I=Math.max(W,0);
+J=E.maxDuration;if(0===J){m();return}p.hasTransitions=0<E.transitionDuration;p.hasAnimations=0<E.animationDuration}p.applyAnimationDelay&&(W="boolean"!==typeof c.delay&&oa(c.delay)?parseFloat(c.delay):W,I=Math.max(W,0),E.animationDelay=W,ca=[ka,W+"s"],y.push(ca),n.style[ca[0]]=ca[1]);N=1E3*I;z=1E3*J;if(c.easing){var k,l=c.easing;p.hasTransitions&&(k=O+"TimingFunction",y.push([k,l]),n.style[k]=l);p.hasAnimations&&(k=U+"TimingFunction",y.push([k,l]),n.style[k]=l)}E.transitionDuration&&x.push(sa);E.animationDuration&&
+x.push(ta);A=Date.now();var v=N+1.5*z;k=A+v;var l=a.data("$$animateCss")||[],r=!0;if(l.length){var G=l[0];(r=k>G.expectedEndTime)?h.cancel(G.timer):l.push(m)}r&&(v=h(d,v,!1),l[0]={timer:v,expectedEndTime:k},l.push(m),a.data("$$animateCss",l));a.on(x.join(" "),g);c.to&&(c.cleanupStyles&&Ea(t,n,Object.keys(c.to)),za(a,c))}}function d(){var b=a.data("$$animateCss");if(b){for(var c=1;c<b.length;c++)b[c]();a.removeData("$$animateCss")}}function g(a){a.stopPropagation();var b=a.originalEvent||a;a=b.$manualTimeStamp||
+b.timeStamp||Date.now();b=parseFloat(b.elapsedTime.toFixed(3));Math.max(a-A,0)>=N&&b>=J&&(va=!0,m())}if(!ga)if(n.parentNode){var A,x=[],l=function(a){if(va)k&&a&&(k=!1,m());else if(k=!a,E.animationDuration)if(a=na(n,k),k)y.push(a);else{var b=y,c=b.indexOf(a);0<=a&&b.splice(c,1)}},v=0<V&&(E.transitionDuration&&0===S.transitionDuration||E.animationDuration&&0===S.animationDuration)&&Math.max(S.animationDelay,S.transitionDelay);v?h(b,Math.floor(v*V*1E3),!1):b();L.resume=function(){l(!0)};L.pause=function(){l(!1)}}else m()}
+var t={},n=B(a);if(!n||!n.parentNode||!u.enabled())return G();c=ia(c);var y=[],r=a.attr("class"),l=Ia(c),ga,k,va,H,L,I,N,J,z;if(0===c.duration||!v.animations&&!v.transitions)return G();var ba=c.event&&X(c.event)?c.event.join(" "):c.event,Q="",P="";ba&&c.structural?Q=T(ba,"ng-",!0):ba&&(Q=ba);c.addClass&&(P+=T(c.addClass,"-add"));c.removeClass&&(P.length&&(P+=" "),P+=T(c.removeClass,"-remove"));c.applyClassesEarly&&P.length&&K(a,c);var Z=[Q,P].join(" ").trim(),ha=r+" "+Z,Y=T(Z,"-active"),r=l.to&&0<
+Object.keys(l.to).length;if(!(0<(c.keyframeStyle||"").length||r||Z))return G();var aa,S;0<c.stagger?(l=parseFloat(c.stagger),S={transitionDelay:l,animationDelay:l,transitionDuration:0,animationDuration:0}):(aa=Ga(n,ha),S=R(n,Z,aa,Qa));c.$$skipPreparationClasses||e.addClass(a,Z);c.transitionStyle&&(l=[O,c.transitionStyle],ea(n,l),y.push(l));0<=c.duration&&(l=0<n.style[O].length,l=Ca(c.duration,l),ea(n,l),y.push(l));c.keyframeStyle&&(l=[U,c.keyframeStyle],ea(n,l),y.push(l));var V=S?0<=c.staggerIndex?
+c.staggerIndex:b.count(aa):0;(ba=0===V)&&!c.skipBlocking&&ja(n,9999);var E=D(n,ha,aa),W=E.maxDelay;I=Math.max(W,0);J=E.maxDuration;var p={};p.hasTransitions=0<E.transitionDuration;p.hasAnimations=0<E.animationDuration;p.hasTransitionAll=p.hasTransitions&&"all"==E.transitionProperty;p.applyTransitionDuration=r&&(p.hasTransitions&&!p.hasTransitionAll||p.hasAnimations&&!p.hasTransitions);p.applyAnimationDuration=c.duration&&p.hasAnimations;p.applyTransitionDelay=oa(c.delay)&&(p.applyTransitionDuration||
+p.hasTransitions);p.applyAnimationDelay=oa(c.delay)&&p.hasAnimations;p.recalculateTimingStyles=0<P.length;if(p.applyTransitionDuration||p.applyAnimationDuration)J=c.duration?parseFloat(c.duration):J,p.applyTransitionDuration&&(p.hasTransitions=!0,E.transitionDuration=J,l=0<n.style[O+"Property"].length,y.push(Ca(J,l))),p.applyAnimationDuration&&(p.hasAnimations=!0,E.animationDuration=J,y.push([ua,J+"s"]));if(0===J&&!p.recalculateTimingStyles)return G();if(null!=c.delay){var ca=parseFloat(c.delay);
+p.applyTransitionDelay&&y.push([fa,ca+"s"]);p.applyAnimationDelay&&y.push([ka,ca+"s"])}null==c.duration&&0<E.transitionDuration&&(p.recalculateTimingStyles=p.recalculateTimingStyles||ba);N=1E3*I;z=1E3*J;c.skipBlocking||(p.blockTransition=0<E.transitionDuration,p.blockKeyframeAnimation=0<E.animationDuration&&0<S.animationDelay&&0===S.animationDuration);c.from&&(c.cleanupStyles&&Ea(t,n,Object.keys(c.from)),ya(a,c));p.blockTransition||p.blockKeyframeAnimation?F(J):c.skipBlocking||ja(n,!1);return{$$willAnimate:!0,
+end:d,start:function(){if(!ga)return L={end:d,cancel:g,resume:null,pause:null},H=new s(L),C(A),H}}}}]}]).provider("$$animateCssDriver",["$$animationProvider",function(a){a.drivers.push("$$animateCssDriver");this.$get=["$animateCss","$rootScope","$$AnimateRunner","$rootElement","$sniffer","$$jqLite","$document",function(a,c,d,e,s,h,g){function v(a){return a.replace(/\bng-\S+\b/g,"")}function r(a,b){I(a)&&(a=a.split(" "));I(b)&&(b=b.split(" "));return a.filter(function(a){return-1===b.indexOf(a)}).join(" ")}
+function u(c,e,g){function h(a){var b={},c=B(a).getBoundingClientRect();q(["width","height","top","left"],function(a){var d=c[a];switch(a){case "top":d+=C.scrollTop;break;case "left":d+=C.scrollLeft}b[a]=Math.floor(d)+"px"});return b}function f(){var c=v(g.attr("class")||""),d=r(c,m),c=r(m,c),d=a(x,{to:h(g),addClass:"ng-anchor-in "+d,removeClass:"ng-anchor-out "+c,delay:!0});return d.$$willAnimate?d:null}function s(){x.remove();e.removeClass("ng-animate-shim");g.removeClass("ng-animate-shim")}var x=
+L(B(e).cloneNode(!0)),m=v(x.attr("class")||"");e.addClass("ng-animate-shim");g.addClass("ng-animate-shim");x.addClass("ng-anchor");D.append(x);var F;c=function(){var c=a(x,{addClass:"ng-anchor-out",delay:!0,from:h(e)});return c.$$willAnimate?c:null}();if(!c&&(F=f(),!F))return s();var G=c||F;return{start:function(){function a(){c&&c.end()}var b,c=G.start();c.done(function(){c=null;if(!F&&(F=f()))return c=F.start(),c.done(function(){c=null;s();b.complete()}),c;s();b.complete()});return b=new d({end:a,
+cancel:a})}}}function H(a,b,c,e){var f=R(a,M),g=R(b,M),h=[];q(e,function(a){(a=u(c,a.out,a["in"]))&&h.push(a)});if(f||g||0!==h.length)return{start:function(){function a(){q(b,function(a){a.end()})}var b=[];f&&b.push(f.start());g&&b.push(g.start());q(h,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 R(c){var d=c.element,e=c.options||{};c.structural&&(e.event=c.event,e.structural=!0,e.applyClassesEarly=!0,"leave"===c.event&&(e.onDone=
+e.domOperation));e.preparationClasses&&(e.event=Y(e.event,e.preparationClasses));c=a(d,e);return c.$$willAnimate?c:null}if(!s.animations&&!s.transitions)return M;var C=g[0].body;c=B(e);var D=L(c.parentNode&&11===c.parentNode.nodeType||C.contains(c)?c:C);N(h);return function(a){return a.from&&a.to?H(a.from,a.to,a.classes,a.anchors):R(a)}}]}]).provider("$$animateJs",["$animateProvider",function(a){this.$get=["$injector","$$AnimateRunner","$$jqLite",function(b,c,d){function e(c){c=X(c)?c:c.split(" ");
+for(var d=[],e={},r=0;r<c.length;r++){var q=c[r],s=a.$$registeredAnimations[q];s&&!e[q]&&(d.push(b.get(s)),e[q]=!0)}return d}var s=N(d);return function(a,b,d,r){function u(){r.domOperation();s(a,r)}function H(a,b,d,e,f){switch(d){case "animate":b=[b,e.from,e.to,f];break;case "setClass":b=[b,D,K,f];break;case "addClass":b=[b,D,f];break;case "removeClass":b=[b,K,f];break;default:b=[b,f]}b.push(e);if(a=a.apply(a,b))if(Fa(a.start)&&(a=a.start()),a instanceof c)a.done(f);else if(Fa(a))return a;return M}
+function B(a,b,d,e,f){var g=[];q(e,function(e){var h=e[f];h&&g.push(function(){var e,f,g=!1,k=function(a){g||(g=!0,(f||M)(a),e.complete(!a))};e=new c({end:function(){k()},cancel:function(){k(!0)}});f=H(h,a,b,d,function(a){k(!1===a)});return e})});return g}function C(a,b,d,e,f){var g=B(a,b,d,e,f);if(0===g.length){var h,l;"beforeSetClass"===f?(h=B(a,"removeClass",d,e,"beforeRemoveClass"),l=B(a,"addClass",d,e,"beforeAddClass")):"setClass"===f&&(h=B(a,"removeClass",d,e,"removeClass"),l=B(a,"addClass",
+d,e,"addClass"));h&&(g=g.concat(h));l&&(g=g.concat(l))}if(0!==g.length)return function(a){var b=[];g.length&&q(g,function(a){b.push(a())});b.length?c.all(b,a):a();return function(a){q(b,function(b){a?b.cancel():b.end()})}}}3===arguments.length&&pa(d)&&(r=d,d=null);r=ia(r);d||(d=a.attr("class")||"",r.addClass&&(d+=" "+r.addClass),r.removeClass&&(d+=" "+r.removeClass));var D=r.addClass,K=r.removeClass,l=e(d),y,w;if(l.length){var f,I;"leave"==b?(I="leave",f="afterLeave"):(I="before"+b.charAt(0).toUpperCase()+
+b.substr(1),f=b);"enter"!==b&&"move"!==b&&(y=C(a,b,r,l,I));w=C(a,b,r,l,f)}if(y||w)return{start:function(){function b(c){f=!0;u();da(a,r);g.complete(c)}var d,e=[];y&&e.push(function(a){d=y(a)});e.length?e.push(function(a){u();a(!0)}):u();w&&e.push(function(a){d=w(a)});var f=!1,g=new c({end:function(){f||((d||M)(void 0),b(void 0))},cancel:function(){f||((d||M)(!0),b(!0))}});c.chain(e,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),h=d(a.to);if(b||h)return{start:function(){function a(){return function(){q(d,function(a){a.end()})}}var d=[];b&&d.push(b.start());h&&d.push(h.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
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-animate/angular-animate.min.js.map b/xos-apps/auto-scale/gui/src/vendor/angular-animate/angular-animate.min.js.map
new file mode 100644
index 0000000..11d5fe5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-animate/angular-animate.min.js.map
@@ -0,0 +1,8 @@
+{
+"version":3,
+"file":"angular-animate.min.js",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AD,CAAS,CACpBC,CAAAsB,SAAA,CAAgBvB,CAAhB,CADoB,CAlBtB,CAEA,KAAIC,EAAS,IAAIqD,CAAJ,CAAoB,CAC/BlC,IAAKqX,CAAA,EAD0B,CAE/BnX,OAAQmX,CAAA,EAFuB,CAApB,CAKb,OAAOxY,EAlBS,CADb,CALyC,CAAlD,IAyCE,OAAOuY,EAAA,CAAiBxS,CAAjB,CA1CoC,CADqC,CAA1E,CAFwE,CAAtDsS,CAs7DhC,CAn0HsC,CAArC,CAAD,CAo1HGxkB,MAp1HH,CAo1HWA,MAAAC,QAp1HX;",
+"sources":["angular-animate.js"],
+"names":["window","angular","undefined","assertArg","arg","name","reason","ngMinErr","mergeClasses","a","b","isArray","join","packageStyles","options","styles","to","from","pendClasses","classes","fix","isPrefix","className","isString","length","split","forEach","klass","i","stripCommentsFromElement","element","jqLite","ELEMENT_NODE","nodeType","extractElementNode","elm","$$addClass","$$jqLite","addClass","$$removeClass","removeClass","applyAnimationClassesFactory","prepareAnimationOptions","$$prepared","domOperation","noop","options.domOperation","$$domOperationFired","applyAnimationStyles","applyAnimationFromStyles","applyAnimationToStyles","css","mergeAnimationOptions","target","newOptions","toAdd","toRemove","resolveElementClasses","attr","preparationClasses","concatWithSpace","realDomOperation","extend","existing","splitClassesToLookup","obj","flags","value","key","ADD_CLASS","REMOVE_CLASS","val","prop","allow","getDomNode","applyGeneratedPreparationClasses","event","EVENT_CLASS_PREFIX","ADD_CLASS_SUFFIX","REMOVE_CLASS_SUFFIX","blockTransitions","node","duration","applyInlineStyle","TRANSITION_DELAY_PROP","blockKeyframeAnimations","applyBlock","ANIMATION_PROP","ANIMATION_PLAYSTATE_KEY","styleTuple","style","computeCssStyles","$window","properties","Object","create","detectedStyles","getComputedStyle","formalStyleName","actualStyleName","c","charAt","parseMaxTime","str","maxValue","values","substring","parseFloat","Math","max","truthyTimingValue","getCssTransitionDurationStyle","applyOnlyDuration","TRANSITION_PROP","DURATION_KEY","createLocalCacheLookup","cache","flush","count","entry","total","get","put","registerRestorableStyles","backup","isDefined","getPropertyValue","isObject","isUndefined","isFunction","isElement","TRANSITIONEND_EVENT","ANIMATIONEND_EVENT","ontransitionend","onwebkittransitionend","onanimationend","onwebkitanimationend","ANIMATION_DELAY_PROP","DELAY_KEY","ANIMATION_DURATION_PROP","TRANSITION_DURATION_PROP","DETECT_CSS_PROPERTIES","transitionDuration","transitionDelay","transitionProperty","PROPERTY_KEY","animationDuration","animationDelay","animationIterationCount","ANIMATION_ITERATION_COUNT_KEY","DETECT_STAGGER_CSS_PROPERTIES","module","directive","$$AnimateChildrenDirective","scope","attrs","ngAnimateChildren","data","NG_ANIMATE_CHILDREN_DATA","$observe","factory","$$rAFSchedulerFactory","$$rAF","scheduler","tasks","queue","concat","nextTick","items","shift","cancelFn","waitUntilQuiet","scheduler.waitUntilQuiet","fn","$$AnimateRunnerFactory","$q","$sniffer","$$animateAsyncRun","AnimateRunner","host","setHost","_doneCallbacks","_runInAnimationFrame","_state","chain","AnimateRunner.chain","callback","next","index","response","all","AnimateRunner.all","runners","onProgress","status","runner","done","prototype","DONE_COMPLETE_STATE","push","progress","getPromise","promise","self","resolve","reject","then","resolveHandler","rejectHandler","catch","handler","finally","pause","resume","end","_resolve","cancel","complete","INITIAL_STATE","DONE_PENDING_STATE","$$AnimateAsyncRunFactory","waitForTick","waitQueue","passed","provider","$$AnimateQueueProvider","$animateProvider","isAllowed","ruleType","currentAnimation","previousAnimation","rules","some","hasAnimationClasses","and","skip","newAnimation","structural","RUNNING_STATE","state","nO","cO","$get","$rootScope","$rootElement","$document","$$HashMap","$$animation","$$AnimateRunner","$templateRequest","$$forceReflow","postDigestTaskFactory","postDigestCalled","$$postDigest","findCallbacks","parent","targetNode","targetParentNode","matches","entries","callbackRegistry","contains","queueAnimation","notifyProgress","phase","runInNextPostDigestOrNow","callbacks","close","activeClasses","applyAnimationClasses","isAnimatableClassName","isStructural","indexOf","skipAnimations","animationsEnabled","disabledElementsLookup","existingAnimation","activeAnimationsLookup","hasExistingAnimation","PRE_DIGEST_STATE","areAnimationsAllowed","closeChildAnimations","skipAnimationFlag","cancelAnimationFlag","joinAnimationFlag","isValidAnimation","keys","clearElementAnimationState","counter","markElementAnimationState","animationDetails","animationCancelled","realRunner","children","querySelectorAll","child","parseInt","getAttribute","NG_ANIMATE_ATTR_NAME","remove","removeAttribute","isMatchingElement","nodeOrElmA","nodeOrElmB","parentElement","bodyElement","body","bodyElementDetected","nodeName","rootElementDetected","parentAnimationDetected","animateChildren","parentHost","NG_ANIMATE_PIN_DATA","parentNode","details","setAttribute","newValue","oldValue","deregisterWatch","$watch","totalPendingRequests","isEmpty","classNameFilter","test","on","container","off","filterFromRegistry","list","matchContainer","matchCallback","containerNode","filter","arguments","pin","enabled","bool","argCount","hasElement","recordExists","$$AnimationProvider","getRunner","RUNNER_STORAGE_KEY","drivers","$injector","$$rAFScheduler","sortAnimations","animations","processNode","processed","elementNode","domNode","lookup","parentEntry","tree","animation","flatten","result","remainingLevelEntries","nextLevelEntries","row","childEntry","animationQueue","getAnchorNodes","hasAttribute","NG_ANIMATE_REF_ATTR","SELECTOR","anchors","groupAnimations","preparedAnimations","refLookup","enterOrMove","anchorNodes","direction","anchor","animationID","usedIndicesLookup","anchorGroups","operations","fromAnimation","toAnimation","lookupKey","toString","group","beforeStart","cssClassesIntersection","indexKey","aa","j","invokeFirstDriver","driverName","has","driver","updateAnimationRunners","newRunner","handleDestroyedElement","rejected","removeData","tempClasses","NG_ANIMATE_CLASSNAME","groupedAnimations","toBeSortedAnimations","animationEntry","triggerAnimationStart","startAnimationFn","closeFn","targetElement","operation","start","animationRunner","$AnimateCssProvider","gcsLookup","gcsStaggerLookup","$timeout","$animate","gcsHashFn","extraClasses","parentCounter","computeCachedCssStaggerStyles","cacheKey","stagger","staggerClassName","rafWaitQueue","pageWidth","computeTimings","timings","aD","tD","maxDelay","maxDuration","init","endFn","animationClosed","animationCompleted","animationPaused","$$skipPreparationClasses","temporaryStyles","restoreStyles","setProperty","removeProperty","onDone","applyBlocking","blockTransition","blockKeyframeAnimation","closeAndReturnNoopAnimator","$$willAnimate","recalculateTimingStyles","fullClassName","relativeDelay","hasTransitions","hasAnimations","applyAnimationDelay","delay","delayStyle","maxDelayTime","ONE_SECOND","maxDurationTime","easing","easeProp","easeVal","TIMING_KEY","events","startTime","Date","now","timerTime","CLOSING_TIME_BUFFER","endTime","animationsData","ANIMATE_TIMER_KEY","setupFallbackTimer","currentTimerData","expectedEndTime","timer","onAnimationExpired","onAnimationProgress","cleanupStyles","stopPropagation","ev","originalEvent","timeStamp","$manualTimeStamp","elapsedTime","toFixed","ELAPSED_TIME_MAX_DECIMAL_PLACES","playPause","playAnimation","arr","splice","maxStagger","itemIndex","floor","runnerHost","runnerHost.resume","runnerHost.pause","transitions","method","structuralClassName","addRemoveClassName","applyClassesEarly","trim","ACTIVE_CLASS_SUFFIX","hasToStyles","keyframeStyle","staggerVal","transitionStyle","durationStyle","staggerIndex","isFirst","skipBlocking","SAFE_FAST_FORWARD_DURATION_VALUE","hasTransitionAll","applyTransitionDuration","applyAnimationDuration","applyTransitionDelay","$$AnimateCssDriverProvider","$$animationProvider","$animateCss","filterCssClasses","replace","getUniqueValues","prepareAnchoredAnimation","outAnchor","inAnchor","calculateAnchorStyles","coords","getBoundingClientRect","bodyNode","scrollTop","scrollLeft","prepareInAnimation","endingClasses","startingClasses","animator","clone","NG_ANIMATE_SHIM_CLASS_NAME","cloneNode","NG_ANIMATE_ANCHOR_CLASS_NAME","rootBodyElement","append","animatorIn","animatorOut","prepareOutAnimation","NG_OUT_ANCHOR_CLASS_NAME","startingAnimator","prepareFromToAnchorAnimation","prepareRegularAnimation","anchorAnimations","outElement","inElement","animationRunners","rootNode","initDriverFn","$$AnimateJsProvider","lookupAnimations","flagMap","animationFactory","$$registeredAnimations","applyOptions","executeAnimationFn","args","classesToAdd","classesToRemove","apply","groupEventedAnimations","fnName","ani","endProgressCb","resolved","onAnimationComplete","packageAnimations","startAnimation","animateFn","before","after","afterFn","beforeFn","toUpperCase","substr","onComplete","success","closeActiveAnimations","cancelled","$$AnimateJsDriverProvider","$$animateJs","prepareAnimation","endFnFactory"]
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-animate/bower.json b/xos-apps/auto-scale/gui/src/vendor/angular-animate/bower.json
new file mode 100644
index 0000000..7137037
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-animate/bower.json
@@ -0,0 +1,9 @@
+{
+ "name": "angular-animate",
+ "version": "1.4.8",
+ "main": "./angular-animate.js",
+ "ignore": [],
+ "dependencies": {
+ "angular": "1.4.8"
+ }
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-animate/index.js b/xos-apps/auto-scale/gui/src/vendor/angular-animate/index.js
new file mode 100644
index 0000000..6ec0a35
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-animate/index.js
@@ -0,0 +1,2 @@
+require('./angular-animate');
+module.exports = 'ngAnimate';
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-animate/package.json b/xos-apps/auto-scale/gui/src/vendor/angular-animate/package.json
new file mode 100644
index 0000000..d732075
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-animate/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "angular-animate",
+ "version": "1.4.8",
+ "description": "AngularJS module for animations",
+ "main": "index.js",
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/angular/angular.js.git"
+ },
+ "keywords": [
+ "angular",
+ "framework",
+ "browser",
+ "animation",
+ "client-side"
+ ],
+ "author": "Angular Core Team <angular-core+npm@google.com>",
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/angular/angular.js/issues"
+ },
+ "homepage": "http://angularjs.org"
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/.bower.json b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/.bower.json
new file mode 100644
index 0000000..b8a080f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/.bower.json
@@ -0,0 +1,68 @@
+{
+ "name": "angular-chart.js",
+ "version": "0.8.8",
+ "main": [
+ "./dist/angular-chart.js",
+ "./dist/angular-chart.css"
+ ],
+ "authors": [
+ "Jerome Touffe-Blin <jtblin@gmail.com>"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/jtblin/angular-chart.js.git"
+ },
+ "description": "An angular.js wrapper for Chart.js - reactive, responsive, beautiful charts.",
+ "moduleType": [
+ "globals"
+ ],
+ "keywords": [
+ "angular",
+ "angular.js",
+ "chartjs",
+ "chart",
+ "reactive",
+ "responsive",
+ "graph",
+ "bar",
+ "line",
+ "area",
+ "donut"
+ ],
+ "license": "BSD",
+ "ignore": [
+ "**/.*",
+ "node_modules",
+ "bower_components",
+ "examples",
+ "test",
+ "tests"
+ ],
+ "dependencies": {
+ "angular": "1.x",
+ "Chart.js": "~1.0.1"
+ },
+ "devDependencies": {
+ "Chart.StackedBar.js": "~1.0.1",
+ "angular-bootstrap": "~0.11.0",
+ "angular-mocks": "1.x",
+ "font-awesome": "~4.1.0",
+ "rainbow": "~1.1.9",
+ "requirejs": "~2.1.20"
+ },
+ "resolutions": {
+ "Chart.js": "~1.0.1",
+ "angular": "1.x",
+ "angular-mocks": "1.3.10"
+ },
+ "homepage": "https://github.com/jtblin/angular-chart.js",
+ "_release": "0.8.8",
+ "_resolution": {
+ "type": "version",
+ "tag": "0.8.8",
+ "commit": "25739e972b519676fed7e0bd4c9d1ec6b8bb92f0"
+ },
+ "_source": "git://github.com/jtblin/angular-chart.js.git",
+ "_target": "~0.8.7",
+ "_originalSource": "angular-chart.js"
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/LICENSE b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/LICENSE
new file mode 100644
index 0000000..f3bd714
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) Jerome Touffe-Blin ("Author")
+All rights reserved.
+
+The BSD License
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/README.md b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/README.md
new file mode 100644
index 0000000..d2044e8
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/README.md
@@ -0,0 +1,209 @@
+# angular-chart.js
+
+[![Bower version](https://badge.fury.io/bo/angular-chart.js.svg)](http://badge.fury.io/bo/angular-chart.js)
+[![npm version](https://badge.fury.io/js/angular-chart.js.svg)](http://badge.fury.io/js/angular-chart.js)
+[![Build Status](https://travis-ci.org/jtblin/angular-chart.js.png)](https://travis-ci.org/jtblin/angular-chart.js)
+[![Code Climate](https://codeclimate.com/github/jtblin/angular-chart.js/badges/gpa.svg)](https://codeclimate.com/github/jtblin/angular-chart.js)
+[![Code Coverage](https://d3s6mut3hikguw.cloudfront.net/github/jtblin/angular-chart.js/badges/coverage.svg)](https://codeclimate.com/github/jtblin/angular-chart.js)
+
+Beautiful, reactive, responsive charts for Angular.JS using [Chart.js](http://www.chartjs.org/).
+
+[Demo](http://jtblin.github.io/angular-chart.js/)
+
+# Installation
+
+### bower
+
+ bower install --save angular-chart.js
+
+### npm
+
+ npm install --save angular-chart.js
+
+### cdn
+
+ //cdn.jsdelivr.net/angular.chartjs/latest/angular-chart.min.js
+ //cdn.jsdelivr.net/angular.chartjs/latest/angular-chart.css
+
+### manually
+
+or copy the files from `dist/`.
+
+Then add the sources to your code (adjust paths as needed) after
+adding the dependencies for Angular and Chart.js first:
+
+```html
+<head>
+ <link rel="stylesheet" href="bower_components/angular-chart.js/dist/angular-chart.css" />
+<head>
+<body>
+ ...
+</body>
+ <script src="bower_components/angular/angular.min.js"></script>
+ <script src="bower_components/Chart.js/Chart.min.js"></script>
+ <script src="bower_components/angular-chart.js/dist/angular-chart.min.js"></script>
+```
+
+# Utilisation
+
+There are 6 types of charts so 6 directives: `chart-line`, `chart-bar`, `chart-radar`, `chart-pie`,
+`chart-polar-area`, `chart-doughnut`.
+
+They all use mostly the same API (`[chart-]` indicates an optional but recommended prefix):
+
+- `[chart-]data`: series data
+- `[chart-]labels`: x axis labels (line, bar, radar) or series labels (pie, doughnut, polar area)
+- `[chart-]options`: chart options (as from [Chart.js documentation](http://www.chartjs.org/docs/))
+- `[chart-]series`: (default: `[]`): series labels (line, bar, radar)
+- `[chart-]colours`: data colours (will use default colours if not specified)
+- `getColour`: function that returns a colour in case there are not enough (will use random colours if not specified)
+- `[chart-]click`: onclick event handler
+- `[chart-]hover`: onmousemove event handler
+- `[chart-]legend`: (default: `false`): show legend below the chart
+
+*DEPRECATION WARNING*: Note that all attributes which do *not* use the `[chart-]` prefix are deprecated
+and may be removed in a future version.
+
+There is another directive `chart-base` that takes an extra attribute `chart-type` to define the type
+dynamically, see [stacked bar example](http://jtblin.github.io/angular-chart.js/examples/stacked-bars.html).
+
+# Example
+
+## Markup
+
+```html
+<canvas id="line" class="chart chart-line" chart-data="data" chart-labels="labels"
+ chart-legend="true" chart-series="series" chart-click="onClick"></canvas>
+```
+
+## Javascript
+
+```javascript
+angular.module("app", ["chart.js"])
+ // Optional configuration
+ .config(['ChartJsProvider', function (ChartJsProvider) {
+ // Configure all charts
+ ChartJsProvider.setOptions({
+ colours: ['#FF5252', '#FF8A80'],
+ responsive: false
+ });
+ // Configure all line charts
+ ChartJsProvider.setOptions('Line', {
+ datasetFill: false
+ });
+ }])
+ .controller("LineCtrl", ['$scope', '$timeout', function ($scope, $timeout) {
+
+ $scope.labels = ["January", "February", "March", "April", "May", "June", "July"];
+ $scope.series = ['Series A', 'Series B'];
+ $scope.data = [
+ [65, 59, 80, 81, 56, 55, 40],
+ [28, 48, 40, 19, 86, 27, 90]
+ ];
+ $scope.onClick = function (points, evt) {
+ console.log(points, evt);
+ };
+
+ // Simulate async data update
+ $timeout(function () {
+ $scope.data = [
+ [28, 48, 40, 19, 86, 27, 90],
+ [65, 59, 80, 81, 56, 55, 40]
+ ];
+ }, 3000);
+}]);
+```
+
+## AMD RequireJS
+
+See [a simple AMD example](examples/amd.js)
+
+## CommonJS e.g. webpack
+
+Module should work with CommonJS out of the box e.g. [browserify](http://browserify.org/) or
+[webpack](http://webpack.github.io/), see a [webpack example](examples/webpack.config.js).
+
+# Reactive
+
+angular-chart.js watch updates on data, series, labels, colours and options and will update, or destroy and recreate,
+the chart on changes.
+
+# Events
+
+angular-chart.js emits the following events on the `scope` and pass the chart as argument:
+
+* `create`: when chart is created
+* `update`: when chart is updated
+
+```
+$scope.$on('create', function (event, chart) {
+ console.log(chart);
+});
+```
+
+**Note**: the event can be emitted multiple times for each chart as the chart can be destroyed and
+created multiple times during angular `watch` lifecycle.
+
+angular-chart.js listen to the scope `destroy` event and destroy the chart when it happens.
+
+# Colours
+
+There are a set of 7 default colours. Colours can be replaced using the `colours` attribute.
+If there is more data than colours, colours are generated randomly or can be provided
+via a function through the `getColour` attribute.
+
+Hex colours are converted to Chart.js colours automatically,
+including different shades for highlight, fill, stroke, etc.
+
+# Issues
+
+**Issues or feature requests for Chart.js (e.g. new chart type, new axis, etc.) need to be opened on
+[Chart.js issues tracker](https://github.com/nnnick/Chart.js/issues)**
+
+**For general questions about usage, please use [http://stackoverflow.com/](http://stackoverflow.com/)**
+
+Please check if issue exists first, otherwise open issue in [github](https://github.com/jtblin/angular-chart.js/issues).
+**Ensure you add a link to a plunker, jsbin, or equivalent.**
+Here is a [jsbin template](http://jsbin.com/dufibi/3/edit?html,js,output) for convenience.
+
+## Browser compatibility
+
+For IE8 and older browsers, you will need
+to include [excanvas](https://code.google.com/p/explorercanvas/wiki/Instructions).
+You will also need a [shim](https://github.com/es-shims/es5-shim) for ES5 functions.
+
+You also need to have ```height``` and ```width``` attributes for the ```<canvas>``` tag of your chart if using IE8 and older browsers. If you *do not* have these attributes, you will need a
+[getComputedStyle shim](https://github.com/Financial-Times/polyfill-service/blob/master/polyfills/getComputedStyle/polyfill.js) and the line ```document.defaultView = window;```, but there still may be errors (due to code in Chart.js).
+
+```html
+<head>
+<!--[if lt IE 9]>
+ <script src="excanvas.js"></script>
+ <script src="es5-shim.js"></script>
+<![endif]-->
+</head>
+```
+
+# Contributing
+
+Pull requests welcome!
+
+1. Fork the repo
+1. Install dependencies: `npm install` and `bower install`
+1. Make your changes
+1. Install [GraphicsMagick](http://www.graphicsmagick.org/)
+1. Run tests: `npm test`
+1. Submit pull request
+
+## Contributors
+
+Thank you to the [contributors](https://github.com/jtblin/angular-chart.js/graphs/contributors)!
+
+# Author
+
+Jerome Touffe-Blin, [@jtblin](https://twitter.com/jtblin), [About me](http://about.me/jtblin)
+
+# License
+
+angular-chart.js is copyright 2015 Jerome Touffe-Blin and contributors.
+It is licensed under the BSD license. See the include LICENSE file for details.
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/angular-chart.js b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/angular-chart.js
new file mode 100644
index 0000000..d6df1cd
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/angular-chart.js
@@ -0,0 +1,362 @@
+(function (factory) {
+ 'use strict';
+ if (typeof exports === 'object') {
+ // Node/CommonJS
+ module.exports = factory(
+ typeof angular !== 'undefined' ? angular : require('angular'),
+ typeof Chart !== 'undefined' ? Chart : require('chart.js'));
+ } else if (typeof define === 'function' && define.amd) {
+ // AMD. Register as an anonymous module.
+ define(['angular', 'chart'], factory);
+ } else {
+ // Browser globals
+ factory(angular, Chart);
+ }
+}(function (angular, Chart) {
+ 'use strict';
+
+ Chart.defaults.global.responsive = true;
+ Chart.defaults.global.multiTooltipTemplate = '<%if (datasetLabel){%><%=datasetLabel%>: <%}%><%= value %>';
+
+ Chart.defaults.global.colours = [
+ '#97BBCD', // blue
+ '#DCDCDC', // light grey
+ '#F7464A', // red
+ '#46BFBD', // green
+ '#FDB45C', // yellow
+ '#949FB1', // grey
+ '#4D5360' // dark grey
+ ];
+
+ var usingExcanvas = typeof window.G_vmlCanvasManager === 'object' &&
+ window.G_vmlCanvasManager !== null &&
+ typeof window.G_vmlCanvasManager.initElement === 'function';
+
+ if (usingExcanvas) Chart.defaults.global.animation = false;
+
+ return angular.module('chart.js', [])
+ .provider('ChartJs', ChartJsProvider)
+ .factory('ChartJsFactory', ['ChartJs', '$timeout', ChartJsFactory])
+ .directive('chartBase', function (ChartJsFactory) { return new ChartJsFactory(); })
+ .directive('chartLine', function (ChartJsFactory) { return new ChartJsFactory('Line'); })
+ .directive('chartBar', function (ChartJsFactory) { return new ChartJsFactory('Bar'); })
+ .directive('chartRadar', function (ChartJsFactory) { return new ChartJsFactory('Radar'); })
+ .directive('chartDoughnut', function (ChartJsFactory) { return new ChartJsFactory('Doughnut'); })
+ .directive('chartPie', function (ChartJsFactory) { return new ChartJsFactory('Pie'); })
+ .directive('chartPolarArea', function (ChartJsFactory) { return new ChartJsFactory('PolarArea'); });
+
+ /**
+ * Wrapper for chart.js
+ * Allows configuring chart js using the provider
+ *
+ * angular.module('myModule', ['chart.js']).config(function(ChartJsProvider) {
+ * ChartJsProvider.setOptions({ responsive: true });
+ * ChartJsProvider.setOptions('Line', { responsive: false });
+ * })))
+ */
+ function ChartJsProvider () {
+ var options = {};
+ var ChartJs = {
+ Chart: Chart,
+ getOptions: function (type) {
+ var typeOptions = type && options[type] || {};
+ return angular.extend({}, options, typeOptions);
+ }
+ };
+
+ /**
+ * Allow to set global options during configuration
+ */
+ this.setOptions = function (type, customOptions) {
+ // If no type was specified set option for the global object
+ if (! customOptions) {
+ customOptions = type;
+ options = angular.extend(options, customOptions);
+ return;
+ }
+ // Set options for the specific chart
+ options[type] = angular.extend(options[type] || {}, customOptions);
+ };
+
+ this.$get = function () {
+ return ChartJs;
+ };
+ }
+
+ function ChartJsFactory (ChartJs, $timeout) {
+ return function chart (type) {
+ return {
+ restrict: 'CA',
+ scope: {
+ data: '=?',
+ labels: '=?',
+ options: '=?',
+ series: '=?',
+ colours: '=?',
+ getColour: '=?',
+ chartType: '=',
+ legend: '@',
+ click: '=?',
+ hover: '=?',
+
+ chartData: '=?',
+ chartLabels: '=?',
+ chartOptions: '=?',
+ chartSeries: '=?',
+ chartColours: '=?',
+ chartLegend: '@',
+ chartClick: '=?',
+ chartHover: '=?'
+ },
+ link: function (scope, elem/*, attrs */) {
+ var chart, container = document.createElement('div');
+ container.className = 'chart-container';
+ elem.replaceWith(container);
+ container.appendChild(elem[0]);
+
+ if (usingExcanvas) window.G_vmlCanvasManager.initElement(elem[0]);
+
+ ['data', 'labels', 'options', 'series', 'colours', 'legend', 'click', 'hover'].forEach(deprecated);
+ function aliasVar (fromName, toName) {
+ scope.$watch(fromName, function (newVal) {
+ if (typeof newVal === 'undefined') return;
+ scope[toName] = newVal;
+ });
+ }
+ /* provide backward compatibility to "old" directive names, by
+ * having an alias point from the new names to the old names. */
+ aliasVar('chartData', 'data');
+ aliasVar('chartLabels', 'labels');
+ aliasVar('chartOptions', 'options');
+ aliasVar('chartSeries', 'series');
+ aliasVar('chartColours', 'colours');
+ aliasVar('chartLegend', 'legend');
+ aliasVar('chartClick', 'click');
+ aliasVar('chartHover', 'hover');
+
+ // Order of setting "watch" matter
+
+ scope.$watch('data', function (newVal, oldVal) {
+ if (! newVal || ! newVal.length || (Array.isArray(newVal[0]) && ! newVal[0].length)) return;
+ var chartType = type || scope.chartType;
+ if (! chartType) return;
+
+ if (chart) {
+ if (canUpdateChart(newVal, oldVal)) return updateChart(chart, newVal, scope, elem);
+ chart.destroy();
+ }
+
+ createChart(chartType);
+ }, true);
+
+ scope.$watch('series', resetChart, true);
+ scope.$watch('labels', resetChart, true);
+ scope.$watch('options', resetChart, true);
+ scope.$watch('colours', resetChart, true);
+
+ scope.$watch('chartType', function (newVal, oldVal) {
+ if (isEmpty(newVal)) return;
+ if (angular.equals(newVal, oldVal)) return;
+ if (chart) chart.destroy();
+ createChart(newVal);
+ });
+
+ scope.$on('$destroy', function () {
+ if (chart) chart.destroy();
+ });
+
+ function resetChart (newVal, oldVal) {
+ if (isEmpty(newVal)) return;
+ if (angular.equals(newVal, oldVal)) return;
+ var chartType = type || scope.chartType;
+ if (! chartType) return;
+
+ // chart.update() doesn't work for series and labels
+ // so we have to re-create the chart entirely
+ if (chart) chart.destroy();
+
+ createChart(chartType);
+ }
+
+ function createChart (type) {
+ if (isResponsive(type, scope) && elem[0].clientHeight === 0 && container.clientHeight === 0) {
+ return $timeout(function () {
+ createChart(type);
+ }, 50, false);
+ }
+ if (! scope.data || ! scope.data.length) return;
+ scope.getColour = typeof scope.getColour === 'function' ? scope.getColour : getRandomColour;
+ scope.colours = getColours(type, scope);
+ var cvs = elem[0], ctx = cvs.getContext('2d');
+ var data = Array.isArray(scope.data[0]) ?
+ getDataSets(scope.labels, scope.data, scope.series || [], scope.colours) :
+ getData(scope.labels, scope.data, scope.colours);
+ var options = angular.extend({}, ChartJs.getOptions(type), scope.options);
+ chart = new ChartJs.Chart(ctx)[type](data, options);
+ scope.$emit('create', chart);
+
+ // Bind events
+ cvs.onclick = scope.click ? getEventHandler(scope, chart, 'click', false) : angular.noop;
+ cvs.onmousemove = scope.hover ? getEventHandler(scope, chart, 'hover', true) : angular.noop;
+
+ if (scope.legend && scope.legend !== 'false') setLegend(elem, chart);
+ }
+
+ function deprecated (attr) {
+ if (typeof console !== 'undefined' && ChartJs.getOptions().env !== 'test') {
+ var warn = typeof console.warn === 'function' ? console.warn : console.log;
+ if (!! scope[attr]) {
+ warn.call(console, '"%s" is deprecated and will be removed in a future version. ' +
+ 'Please use "chart-%s" instead.', attr, attr);
+ }
+ }
+ }
+ }
+ };
+ };
+
+ function canUpdateChart (newVal, oldVal) {
+ if (newVal && oldVal && newVal.length && oldVal.length) {
+ return Array.isArray(newVal[0]) ?
+ newVal.length === oldVal.length && newVal.every(function (element, index) {
+ return element.length === oldVal[index].length; }) :
+ oldVal.reduce(sum, 0) > 0 ? newVal.length === oldVal.length : false;
+ }
+ return false;
+ }
+
+ function sum (carry, val) {
+ return carry + val;
+ }
+
+ function getEventHandler (scope, chart, action, triggerOnlyOnChange) {
+ var lastState = null;
+ return function (evt) {
+ var atEvent = chart.getPointsAtEvent || chart.getBarsAtEvent || chart.getSegmentsAtEvent;
+ if (atEvent) {
+ var activePoints = atEvent.call(chart, evt);
+ if (triggerOnlyOnChange === false || angular.equals(lastState, activePoints) === false) {
+ lastState = activePoints;
+ scope[action](activePoints, evt);
+ scope.$apply();
+ }
+ }
+ };
+ }
+
+ function getColours (type, scope) {
+ var colours = angular.copy(scope.colours ||
+ ChartJs.getOptions(type).colours ||
+ Chart.defaults.global.colours
+ );
+ while (colours.length < scope.data.length) {
+ colours.push(scope.getColour());
+ }
+ return colours.map(convertColour);
+ }
+
+ function convertColour (colour) {
+ if (typeof colour === 'object' && colour !== null) return colour;
+ if (typeof colour === 'string' && colour[0] === '#') return getColour(hexToRgb(colour.substr(1)));
+ return getRandomColour();
+ }
+
+ function getRandomColour () {
+ var colour = [getRandomInt(0, 255), getRandomInt(0, 255), getRandomInt(0, 255)];
+ return getColour(colour);
+ }
+
+ function getColour (colour) {
+ return {
+ fillColor: rgba(colour, 0.2),
+ strokeColor: rgba(colour, 1),
+ pointColor: rgba(colour, 1),
+ pointStrokeColor: '#fff',
+ pointHighlightFill: '#fff',
+ pointHighlightStroke: rgba(colour, 0.8)
+ };
+ }
+
+ function getRandomInt (min, max) {
+ return Math.floor(Math.random() * (max - min + 1)) + min;
+ }
+
+ function rgba (colour, alpha) {
+ if (usingExcanvas) {
+ // rgba not supported by IE8
+ return 'rgb(' + colour.join(',') + ')';
+ } else {
+ return 'rgba(' + colour.concat(alpha).join(',') + ')';
+ }
+ }
+
+ // Credit: http://stackoverflow.com/a/11508164/1190235
+ function hexToRgb (hex) {
+ var bigint = parseInt(hex, 16),
+ r = (bigint >> 16) & 255,
+ g = (bigint >> 8) & 255,
+ b = bigint & 255;
+
+ return [r, g, b];
+ }
+
+ function getDataSets (labels, data, series, colours) {
+ return {
+ labels: labels,
+ datasets: data.map(function (item, i) {
+ return angular.extend({}, colours[i], {
+ label: series[i],
+ data: item
+ });
+ })
+ };
+ }
+
+ function getData (labels, data, colours) {
+ return labels.map(function (label, i) {
+ return angular.extend({}, colours[i], {
+ label: label,
+ value: data[i],
+ color: colours[i].strokeColor,
+ highlight: colours[i].pointHighlightStroke
+ });
+ });
+ }
+
+ function setLegend (elem, chart) {
+ var $parent = elem.parent(),
+ $oldLegend = $parent.find('chart-legend'),
+ legend = '<chart-legend>' + chart.generateLegend() + '</chart-legend>';
+ if ($oldLegend.length) $oldLegend.replaceWith(legend);
+ else $parent.append(legend);
+ }
+
+ function updateChart (chart, values, scope, elem) {
+ if (Array.isArray(scope.data[0])) {
+ chart.datasets.forEach(function (dataset, i) {
+ (dataset.points || dataset.bars).forEach(function (dataItem, j) {
+ dataItem.value = values[i][j];
+ });
+ });
+ } else {
+ chart.segments.forEach(function (segment, i) {
+ segment.value = values[i];
+ });
+ }
+ chart.update();
+ scope.$emit('update', chart);
+ if (scope.legend && scope.legend !== 'false') setLegend(elem, chart);
+ }
+
+ function isEmpty (value) {
+ return ! value ||
+ (Array.isArray(value) && ! value.length) ||
+ (typeof value === 'object' && ! Object.keys(value).length);
+ }
+
+ function isResponsive (type, scope) {
+ var options = angular.extend({}, Chart.defaults.global, ChartJs.getOptions(type), scope.options);
+ return options.responsive;
+ }
+ }
+}));
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/angular-chart.less b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/angular-chart.less
new file mode 100644
index 0000000..ba6b18d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/angular-chart.less
@@ -0,0 +1,30 @@
+.chart-legend, .bar-legend, .line-legend, .pie-legend, .radar-legend, .polararea-legend, .doughnut-legend {
+ list-style-type: none;
+ margin-top: 5px;
+ text-align: center;
+ /* NOTE: Browsers automatically add 40px of padding-left to all lists, so we should offset that, otherwise the legend is off-center */
+ -webkit-padding-start:0; /* Webkit */
+ -moz-padding-start:0; /* Mozilla */
+ padding-left:0; /* IE (handles all cases, really, but we should also include the vendor-specific properties just to be safe) */
+
+ li {
+ display: inline-block;
+ white-space: nowrap;
+ position: relative;
+ margin-bottom: 4px;
+ border-radius: 5px;
+ padding: 2px 8px 2px 28px;
+ font-size: smaller;
+ cursor: default;
+
+ span {
+ display: block;
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 20px;
+ height: 20px;
+ border-radius: 5px;
+ }
+ }
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/bower.json b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/bower.json
new file mode 100644
index 0000000..6ada4e5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/bower.json
@@ -0,0 +1,58 @@
+{
+ "name": "angular-chart.js",
+ "version": "0.8.8",
+ "main": [
+ "./dist/angular-chart.js",
+ "./dist/angular-chart.css"
+ ],
+ "authors": [
+ "Jerome Touffe-Blin <jtblin@gmail.com>"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/jtblin/angular-chart.js.git"
+ },
+ "description": "An angular.js wrapper for Chart.js - reactive, responsive, beautiful charts.",
+ "moduleType": [
+ "globals"
+ ],
+ "keywords": [
+ "angular",
+ "angular.js",
+ "chartjs",
+ "chart",
+ "reactive",
+ "responsive",
+ "graph",
+ "bar",
+ "line",
+ "area",
+ "donut"
+ ],
+ "license": "BSD",
+ "ignore": [
+ "**/.*",
+ "node_modules",
+ "bower_components",
+ "examples",
+ "test",
+ "tests"
+ ],
+ "dependencies": {
+ "angular": "1.x",
+ "Chart.js": "~1.0.1"
+ },
+ "devDependencies": {
+ "Chart.StackedBar.js": "~1.0.1",
+ "angular-bootstrap": "~0.11.0",
+ "angular-mocks": "1.x",
+ "font-awesome": "~4.1.0",
+ "rainbow": "~1.1.9",
+ "requirejs": "~2.1.20"
+ },
+ "resolutions": {
+ "Chart.js": "~1.0.1",
+ "angular": "1.x",
+ "angular-mocks": "1.3.10"
+ }
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/gulpfile.js b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/gulpfile.js
new file mode 100644
index 0000000..d32d007
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/gulpfile.js
@@ -0,0 +1,171 @@
+(function () {
+ 'use strict';
+
+ var fs = require('fs');
+ var path = require('path');
+ var gulp = require('gulp');
+ var less = require('gulp-less');
+ var sourcemaps = require('gulp-sourcemaps');
+ var uglify = require('gulp-uglify');
+ var csso = require('gulp-csso');
+ var jshint = require('gulp-jshint');
+ var stylish = require('jshint-stylish');
+ var jscs = require('gulp-jscs');
+ var mocha = require('gulp-spawn-mocha');
+ var tar = require('gulp-tar');
+ var gzip = require('gulp-gzip');
+ var bumper = require('gulp-bump');
+ var git = require('gulp-git');
+ var shell = require('gulp-shell');
+ var rename = require('gulp-rename');
+ var sequence = require('gulp-sequence');
+ var ngAnnotate = require('gulp-ng-annotate');
+ var rimraf = require('gulp-rimraf');
+ var istanbul = require('gulp-istanbul');
+ var istanbulReport = require('gulp-istanbul-report');
+ var mochaPhantomJS = require('gulp-mocha-phantomjs');
+
+ gulp.task('clean', function () {
+ return gulp.src('./dist/*', { read: false })
+ .pipe(rimraf());
+ });
+
+ gulp.task('less', function () {
+ return gulp.src('./*.less')
+ .pipe(less())
+ .pipe(gulp.dest('./dist'));
+ });
+
+ gulp.task('css-min', function () {
+ return gulp.src('./dist/*.css')
+ .pipe(sourcemaps.init())
+ .pipe(csso())
+ .pipe(rename({ suffix: '.min' }))
+ .pipe(sourcemaps.write('./'))
+ .pipe(gulp.dest('./dist'));
+ });
+
+ gulp.task('lint', function () {
+ return gulp.src('**/*.js')
+ .pipe(jshint())
+ .pipe(jshint.reporter(stylish));
+ });
+
+ gulp.task('style', function () {
+ return gulp.src('**/*.js')
+ .pipe(jscs());
+ });
+
+ gulp.task('cover', function () {
+ return gulp.src('angular-chart.js')
+ .pipe(istanbul({ coverageVariable: '__coverage__' }))
+ .pipe(rename('coverage.js'))
+ .pipe(gulp.dest('test/fixtures'));
+ });
+
+ gulp.task('unit', function () {
+ return gulp.src('test/index.html', { read: false })
+ .pipe(mochaPhantomJS({
+ phantomjs: {
+ hooks: 'mocha-phantomjs-istanbul',
+ coverageFile: 'coverage/coverage.json'
+ },
+ reporter: 'spec'
+ }));
+ });
+
+ gulp.task('integration', function () {
+ return gulp.src(path.join('test', 'test.integration.js'), { read: false })
+ .pipe(mocha({ reporter: 'list', timeout: 20000, require: 'test/support/setup.js' }));
+ });
+
+ gulp.task('report', function () {
+ return gulp.src('coverage/coverage.json')
+ .pipe(istanbulReport({ reporters: ['lcov'] }));
+ });
+
+ gulp.task('bump-patch', bump('patch'));
+ gulp.task('bump-minor', bump('minor'));
+ gulp.task('bump-major', bump('major'));
+
+ gulp.task('bower', function () {
+ return gulp.src('./angular-chart.js')
+ .pipe(ngAnnotate({ single_quotes: true }))
+ .pipe(gulp.dest('./dist'));
+ });
+
+ gulp.task('js', ['lint', 'style', 'bower'], function () {
+ return gulp.src('./angular-chart.js')
+ .pipe(rename('angular-chart.min.js'))
+ .pipe(ngAnnotate({ single_quotes: true }))
+ .pipe(sourcemaps.init())
+ .pipe(uglify())
+ .pipe(sourcemaps.write('./'))
+ .pipe(gulp.dest('./dist'));
+ });
+
+ gulp.task('build', function () {
+ return gulp.src(['dist/*', '!./dist/*.tar.gz'])
+ .pipe(tar('angular-chart.js.tar'))
+ .pipe(gzip({ gzipOptions: { level: 9 } }))
+ .pipe(gulp.dest('dist/'));
+ });
+
+ gulp.task('update', function (cb) {
+ fs.readFile('./examples/charts.template.html', 'utf8', function (err, file) {
+ if (err) return cb(err);
+ file = file.replace('<!-- version -->', version());
+ fs.writeFile('./examples/charts.html', file, cb);
+ });
+ });
+
+ gulp.task('git-commit', function () {
+ var v = version();
+ gulp.src(['./dist/*', './package.json', './bower.json', './examples/charts.html', './test/fixtures/coverage.js'])
+ .pipe(git.add())
+ .pipe(git.commit(v))
+ ;
+ });
+
+ gulp.task('git-push', function (cb) {
+ var v = version();
+ git.push('origin', 'master', function (err) {
+ if (err) return cb(err);
+ git.tag(v, v, function (err) {
+ if (err) return cb(err);
+ git.push('origin', 'master', {args: '--tags' }, cb);
+ });
+ });
+ });
+
+ gulp.task('npm', shell.task([
+ 'npm publish'
+ ]));
+
+ gulp.task('watch', function () {
+ gulp.watch('./*.js', ['js']);
+ gulp.watch('./*.less', ['less']);
+ return true;
+ });
+
+ function bump (level) {
+ return function () {
+ return gulp.src(['./package.json', './bower.json'])
+ .pipe(bumper({type: level}))
+ .pipe(gulp.dest('./'));
+ };
+ }
+
+ function version () {
+ return JSON.parse(fs.readFileSync('package.json', 'utf8')).version;
+ }
+
+ gulp.task('default', sequence('check', 'assets'));
+ gulp.task('assets', sequence('clean', ['less', 'js'], 'css-min', 'build'));
+ gulp.task('test', sequence('cover', 'unit', 'integration', 'report'));
+ gulp.task('check', sequence(['lint', 'style'], 'test'));
+ gulp.task('deploy-patch', sequence('default', 'bump-patch', 'update', 'git-commit', 'git-push', 'npm'));
+ gulp.task('deploy-minor', sequence('default', 'bump-minor', 'update', 'git-commit', 'git-push', 'npm'));
+ gulp.task('deploy-major', sequence('default', 'bump-patch', 'update', 'git-commit', 'git-push', 'npm'));
+
+})();
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/package.json b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/package.json
new file mode 100644
index 0000000..650c9c7
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-chart.js/package.json
@@ -0,0 +1,60 @@
+{
+ "name": "angular-chart.js",
+ "version": "0.8.8",
+ "description": "An angular.js wrapper for Chart.js",
+ "main": "dist/angular-chart.js",
+ "directories": {
+ "example": "examples"
+ },
+ "scripts": {
+ "test": "gulp check"
+ },
+ "author": "Jerome Touffe-Blin <jtblin@gmail.com>",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/jtblin/angular-chart.js.git"
+ },
+ "license": "BSD-2-Clause",
+ "devDependencies": {
+ "chai": "^3.4.1",
+ "chai-string": "^1.1.1",
+ "codeclimate-test-reporter": "^0.1.0",
+ "cp": "^0.2.0",
+ "gm": "^1.17.0",
+ "gulp": "^3.9.0",
+ "gulp-bump": "^1.0.0",
+ "gulp-csso": "^1.0.1",
+ "gulp-git": "^1.6.0",
+ "gulp-gzip": "^1.2.0",
+ "gulp-istanbul": "^0.10.3",
+ "gulp-istanbul-report": "^0.0.1",
+ "gulp-jscs": "^3.0.2",
+ "gulp-jshint": "^1.9.2",
+ "gulp-less": "^3.0.3",
+ "gulp-mocha-phantomjs": "^0.10.1",
+ "gulp-ng-annotate": "^1.1.0",
+ "gulp-rename": "^1.2.0",
+ "gulp-rimraf": "^0.2.0",
+ "gulp-sequence": "^0.4.1",
+ "gulp-shell": "^0.5.1",
+ "gulp-sourcemaps": "^1.0.0",
+ "gulp-spawn-mocha": "^2.0.1",
+ "gulp-tar": "^1.5.0",
+ "gulp-uglify": "^1.4.2",
+ "imgur-node-api": "^0.1.0",
+ "jshint-stylish": "^2.0.1",
+ "mkdirp": "^0.5.0",
+ "mocha": "^2.1.0",
+ "mocha-phantomjs-istanbul": "^0.0.2",
+ "sinon": "^1.12.2",
+ "sinon-chai": "^2.7.0",
+ "testatic": "^0.1.0",
+ "tmp-sync": "^1.1.0",
+ "webpack": "^1.12.0",
+ "webshot": "^0.16.0"
+ },
+ "dependencies": {
+ "angular": "^1.4.5",
+ "chart.js": "^1.0.2"
+ }
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-mocks/.bower.json b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/.bower.json
new file mode 100644
index 0000000..43f6085
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/.bower.json
@@ -0,0 +1,20 @@
+{
+ "name": "angular-mocks",
+ "version": "1.4.8",
+ "main": "./angular-mocks.js",
+ "ignore": [],
+ "dependencies": {
+ "angular": "1.4.8"
+ },
+ "homepage": "https://github.com/angular/bower-angular-mocks",
+ "_release": "1.4.8",
+ "_resolution": {
+ "type": "version",
+ "tag": "v1.4.8",
+ "commit": "5f04a609ad4544f0e93344e10e9a402fdb33a5ad"
+ },
+ "_source": "git://github.com/angular/bower-angular-mocks.git",
+ "_target": "~1.4.8",
+ "_originalSource": "angular-mocks",
+ "_direct": true
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-mocks/README.md b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/README.md
new file mode 100644
index 0000000..440cce9
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/README.md
@@ -0,0 +1,63 @@
+# packaged angular-mocks
+
+This repo is for distribution on `npm` and `bower`. The source for this module is in the
+[main AngularJS repo](https://github.com/angular/angular.js/tree/master/src/ngMock).
+Please file issues and pull requests against that repo.
+
+## Install
+
+You can install this package either with `npm` or with `bower`.
+
+### npm
+
+```shell
+npm install angular-mocks
+```
+
+You can `require` ngMock modules:
+
+```js
+var angular = require('angular');
+angular.module('myMod', [
+ require('angular-animate'),
+ require('angular-mocks/ngMock')
+ require('angular-mocks/ngAnimateMock')
+]);
+```
+
+### bower
+
+```shell
+bower install angular-mocks
+```
+
+The mocks are then available at `bower_components/angular-mocks/angular-mocks.js`.
+
+## Documentation
+
+Documentation is available on the
+[AngularJS docs site](https://docs.angularjs.org/guide/unit-testing).
+
+## License
+
+The MIT License
+
+Copyright (c) 2010-2015 Google, Inc. http://angularjs.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-mocks/angular-mocks.js b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/angular-mocks.js
new file mode 100644
index 0000000..917d842
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/angular-mocks.js
@@ -0,0 +1,2471 @@
+/**
+ * @license AngularJS v1.4.8
+ * (c) 2010-2015 Google, Inc. http://angularjs.org
+ * License: MIT
+ */
+(function(window, angular, undefined) {
+
+'use strict';
+
+/**
+ * @ngdoc object
+ * @name angular.mock
+ * @description
+ *
+ * Namespace from 'angular-mocks.js' which contains testing related code.
+ */
+angular.mock = {};
+
+/**
+ * ! This is a private undocumented service !
+ *
+ * @name $browser
+ *
+ * @description
+ * This service is a mock implementation of {@link ng.$browser}. It provides fake
+ * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
+ * cookies, etc...
+ *
+ * The api of this service is the same as that of the real {@link ng.$browser $browser}, except
+ * that there are several helper methods available which can be used in tests.
+ */
+angular.mock.$BrowserProvider = function() {
+ this.$get = function() {
+ return new angular.mock.$Browser();
+ };
+};
+
+angular.mock.$Browser = function() {
+ var self = this;
+
+ this.isMock = true;
+ self.$$url = "http://server/";
+ self.$$lastUrl = self.$$url; // used by url polling fn
+ self.pollFns = [];
+
+ // TODO(vojta): remove this temporary api
+ self.$$completeOutstandingRequest = angular.noop;
+ self.$$incOutstandingRequestCount = angular.noop;
+
+
+ // register url polling fn
+
+ self.onUrlChange = function(listener) {
+ self.pollFns.push(
+ function() {
+ if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) {
+ self.$$lastUrl = self.$$url;
+ self.$$lastState = self.$$state;
+ listener(self.$$url, self.$$state);
+ }
+ }
+ );
+
+ return listener;
+ };
+
+ self.$$applicationDestroyed = angular.noop;
+ self.$$checkUrlChange = angular.noop;
+
+ self.deferredFns = [];
+ self.deferredNextId = 0;
+
+ self.defer = function(fn, delay) {
+ delay = delay || 0;
+ self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});
+ self.deferredFns.sort(function(a, b) { return a.time - b.time;});
+ return self.deferredNextId++;
+ };
+
+
+ /**
+ * @name $browser#defer.now
+ *
+ * @description
+ * Current milliseconds mock time.
+ */
+ self.defer.now = 0;
+
+
+ self.defer.cancel = function(deferId) {
+ var fnIndex;
+
+ angular.forEach(self.deferredFns, function(fn, index) {
+ if (fn.id === deferId) fnIndex = index;
+ });
+
+ if (angular.isDefined(fnIndex)) {
+ self.deferredFns.splice(fnIndex, 1);
+ return true;
+ }
+
+ return false;
+ };
+
+
+ /**
+ * @name $browser#defer.flush
+ *
+ * @description
+ * Flushes all pending requests and executes the defer callbacks.
+ *
+ * @param {number=} number of milliseconds to flush. See {@link #defer.now}
+ */
+ self.defer.flush = function(delay) {
+ if (angular.isDefined(delay)) {
+ self.defer.now += delay;
+ } else {
+ if (self.deferredFns.length) {
+ self.defer.now = self.deferredFns[self.deferredFns.length - 1].time;
+ } else {
+ throw new Error('No deferred tasks to be flushed');
+ }
+ }
+
+ while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
+ self.deferredFns.shift().fn();
+ }
+ };
+
+ self.$$baseHref = '/';
+ self.baseHref = function() {
+ return this.$$baseHref;
+ };
+};
+angular.mock.$Browser.prototype = {
+
+/**
+ * @name $browser#poll
+ *
+ * @description
+ * run all fns in pollFns
+ */
+ poll: function poll() {
+ angular.forEach(this.pollFns, function(pollFn) {
+ pollFn();
+ });
+ },
+
+ url: function(url, replace, state) {
+ if (angular.isUndefined(state)) {
+ state = null;
+ }
+ if (url) {
+ this.$$url = url;
+ // Native pushState serializes & copies the object; simulate it.
+ this.$$state = angular.copy(state);
+ return this;
+ }
+
+ return this.$$url;
+ },
+
+ state: function() {
+ return this.$$state;
+ },
+
+ notifyWhenNoOutstandingRequests: function(fn) {
+ fn();
+ }
+};
+
+
+/**
+ * @ngdoc provider
+ * @name $exceptionHandlerProvider
+ *
+ * @description
+ * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors
+ * passed to the `$exceptionHandler`.
+ */
+
+/**
+ * @ngdoc service
+ * @name $exceptionHandler
+ *
+ * @description
+ * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed
+ * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
+ * information.
+ *
+ *
+ * ```js
+ * describe('$exceptionHandlerProvider', function() {
+ *
+ * it('should capture log messages and exceptions', function() {
+ *
+ * module(function($exceptionHandlerProvider) {
+ * $exceptionHandlerProvider.mode('log');
+ * });
+ *
+ * inject(function($log, $exceptionHandler, $timeout) {
+ * $timeout(function() { $log.log(1); });
+ * $timeout(function() { $log.log(2); throw 'banana peel'; });
+ * $timeout(function() { $log.log(3); });
+ * expect($exceptionHandler.errors).toEqual([]);
+ * expect($log.assertEmpty());
+ * $timeout.flush();
+ * expect($exceptionHandler.errors).toEqual(['banana peel']);
+ * expect($log.log.logs).toEqual([[1], [2], [3]]);
+ * });
+ * });
+ * });
+ * ```
+ */
+
+angular.mock.$ExceptionHandlerProvider = function() {
+ var handler;
+
+ /**
+ * @ngdoc method
+ * @name $exceptionHandlerProvider#mode
+ *
+ * @description
+ * Sets the logging mode.
+ *
+ * @param {string} mode Mode of operation, defaults to `rethrow`.
+ *
+ * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log`
+ * mode stores an array of errors in `$exceptionHandler.errors`, to allow later
+ * assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and
+ * {@link ngMock.$log#reset reset()}
+ * - `rethrow`: If any errors are passed to the handler in tests, it typically means that there
+ * is a bug in the application or test, so this mock will make these tests fail.
+ * For any implementations that expect exceptions to be thrown, the `rethrow` mode
+ * will also maintain a log of thrown errors.
+ */
+ this.mode = function(mode) {
+
+ switch (mode) {
+ case 'log':
+ case 'rethrow':
+ var errors = [];
+ handler = function(e) {
+ if (arguments.length == 1) {
+ errors.push(e);
+ } else {
+ errors.push([].slice.call(arguments, 0));
+ }
+ if (mode === "rethrow") {
+ throw e;
+ }
+ };
+ handler.errors = errors;
+ break;
+ default:
+ throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
+ }
+ };
+
+ this.$get = function() {
+ return handler;
+ };
+
+ this.mode('rethrow');
+};
+
+
+/**
+ * @ngdoc service
+ * @name $log
+ *
+ * @description
+ * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays
+ * (one array per logging level). These arrays are exposed as `logs` property of each of the
+ * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
+ *
+ */
+angular.mock.$LogProvider = function() {
+ var debug = true;
+
+ function concat(array1, array2, index) {
+ return array1.concat(Array.prototype.slice.call(array2, index));
+ }
+
+ this.debugEnabled = function(flag) {
+ if (angular.isDefined(flag)) {
+ debug = flag;
+ return this;
+ } else {
+ return debug;
+ }
+ };
+
+ this.$get = function() {
+ var $log = {
+ log: function() { $log.log.logs.push(concat([], arguments, 0)); },
+ warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
+ info: function() { $log.info.logs.push(concat([], arguments, 0)); },
+ error: function() { $log.error.logs.push(concat([], arguments, 0)); },
+ debug: function() {
+ if (debug) {
+ $log.debug.logs.push(concat([], arguments, 0));
+ }
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name $log#reset
+ *
+ * @description
+ * Reset all of the logging arrays to empty.
+ */
+ $log.reset = function() {
+ /**
+ * @ngdoc property
+ * @name $log#log.logs
+ *
+ * @description
+ * Array of messages logged using {@link ng.$log#log `log()`}.
+ *
+ * @example
+ * ```js
+ * $log.log('Some Log');
+ * var first = $log.log.logs.unshift();
+ * ```
+ */
+ $log.log.logs = [];
+ /**
+ * @ngdoc property
+ * @name $log#info.logs
+ *
+ * @description
+ * Array of messages logged using {@link ng.$log#info `info()`}.
+ *
+ * @example
+ * ```js
+ * $log.info('Some Info');
+ * var first = $log.info.logs.unshift();
+ * ```
+ */
+ $log.info.logs = [];
+ /**
+ * @ngdoc property
+ * @name $log#warn.logs
+ *
+ * @description
+ * Array of messages logged using {@link ng.$log#warn `warn()`}.
+ *
+ * @example
+ * ```js
+ * $log.warn('Some Warning');
+ * var first = $log.warn.logs.unshift();
+ * ```
+ */
+ $log.warn.logs = [];
+ /**
+ * @ngdoc property
+ * @name $log#error.logs
+ *
+ * @description
+ * Array of messages logged using {@link ng.$log#error `error()`}.
+ *
+ * @example
+ * ```js
+ * $log.error('Some Error');
+ * var first = $log.error.logs.unshift();
+ * ```
+ */
+ $log.error.logs = [];
+ /**
+ * @ngdoc property
+ * @name $log#debug.logs
+ *
+ * @description
+ * Array of messages logged using {@link ng.$log#debug `debug()`}.
+ *
+ * @example
+ * ```js
+ * $log.debug('Some Error');
+ * var first = $log.debug.logs.unshift();
+ * ```
+ */
+ $log.debug.logs = [];
+ };
+
+ /**
+ * @ngdoc method
+ * @name $log#assertEmpty
+ *
+ * @description
+ * Assert that all of the logging methods have no logged messages. If any messages are present,
+ * an exception is thrown.
+ */
+ $log.assertEmpty = function() {
+ var errors = [];
+ angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) {
+ angular.forEach($log[logLevel].logs, function(log) {
+ angular.forEach(log, function(logItem) {
+ errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' +
+ (logItem.stack || ''));
+ });
+ });
+ });
+ if (errors.length) {
+ errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or " +
+ "an expected log message was not checked and removed:");
+ errors.push('');
+ throw new Error(errors.join('\n---------\n'));
+ }
+ };
+
+ $log.reset();
+ return $log;
+ };
+};
+
+
+/**
+ * @ngdoc service
+ * @name $interval
+ *
+ * @description
+ * Mock implementation of the $interval service.
+ *
+ * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
+ * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
+ * time.
+ *
+ * @param {function()} fn A function that should be called repeatedly.
+ * @param {number} delay Number of milliseconds between each function call.
+ * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
+ * indefinitely.
+ * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
+ * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
+ * @param {...*=} Pass additional parameters to the executed function.
+ * @returns {promise} A promise which will be notified on each iteration.
+ */
+angular.mock.$IntervalProvider = function() {
+ this.$get = ['$browser', '$rootScope', '$q', '$$q',
+ function($browser, $rootScope, $q, $$q) {
+ var repeatFns = [],
+ nextRepeatId = 0,
+ now = 0;
+
+ var $interval = function(fn, delay, count, invokeApply) {
+ var hasParams = arguments.length > 4,
+ args = hasParams ? Array.prototype.slice.call(arguments, 4) : [],
+ iteration = 0,
+ skipApply = (angular.isDefined(invokeApply) && !invokeApply),
+ deferred = (skipApply ? $$q : $q).defer(),
+ promise = deferred.promise;
+
+ count = (angular.isDefined(count)) ? count : 0;
+ promise.then(null, null, (!hasParams) ? fn : function() {
+ fn.apply(null, args);
+ });
+
+ promise.$$intervalId = nextRepeatId;
+
+ function tick() {
+ deferred.notify(iteration++);
+
+ if (count > 0 && iteration >= count) {
+ var fnIndex;
+ deferred.resolve(iteration);
+
+ angular.forEach(repeatFns, function(fn, index) {
+ if (fn.id === promise.$$intervalId) fnIndex = index;
+ });
+
+ if (angular.isDefined(fnIndex)) {
+ repeatFns.splice(fnIndex, 1);
+ }
+ }
+
+ if (skipApply) {
+ $browser.defer.flush();
+ } else {
+ $rootScope.$apply();
+ }
+ }
+
+ repeatFns.push({
+ nextTime:(now + delay),
+ delay: delay,
+ fn: tick,
+ id: nextRepeatId,
+ deferred: deferred
+ });
+ repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});
+
+ nextRepeatId++;
+ return promise;
+ };
+ /**
+ * @ngdoc method
+ * @name $interval#cancel
+ *
+ * @description
+ * Cancels a task associated with the `promise`.
+ *
+ * @param {promise} promise A promise from calling the `$interval` function.
+ * @returns {boolean} Returns `true` if the task was successfully cancelled.
+ */
+ $interval.cancel = function(promise) {
+ if (!promise) return false;
+ var fnIndex;
+
+ angular.forEach(repeatFns, function(fn, index) {
+ if (fn.id === promise.$$intervalId) fnIndex = index;
+ });
+
+ if (angular.isDefined(fnIndex)) {
+ repeatFns[fnIndex].deferred.reject('canceled');
+ repeatFns.splice(fnIndex, 1);
+ return true;
+ }
+
+ return false;
+ };
+
+ /**
+ * @ngdoc method
+ * @name $interval#flush
+ * @description
+ *
+ * Runs interval tasks scheduled to be run in the next `millis` milliseconds.
+ *
+ * @param {number=} millis maximum timeout amount to flush up until.
+ *
+ * @return {number} The amount of time moved forward.
+ */
+ $interval.flush = function(millis) {
+ now += millis;
+ while (repeatFns.length && repeatFns[0].nextTime <= now) {
+ var task = repeatFns[0];
+ task.fn();
+ task.nextTime += task.delay;
+ repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});
+ }
+ return millis;
+ };
+
+ return $interval;
+ }];
+};
+
+
+/* jshint -W101 */
+/* The R_ISO8061_STR regex is never going to fit into the 100 char limit!
+ * This directive should go inside the anonymous function but a bug in JSHint means that it would
+ * not be enacted early enough to prevent the warning.
+ */
+var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
+
+function jsonStringToDate(string) {
+ var match;
+ if (match = string.match(R_ISO8061_STR)) {
+ var date = new Date(0),
+ tzHour = 0,
+ tzMin = 0;
+ if (match[9]) {
+ tzHour = toInt(match[9] + match[10]);
+ tzMin = toInt(match[9] + match[11]);
+ }
+ date.setUTCFullYear(toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
+ date.setUTCHours(toInt(match[4] || 0) - tzHour,
+ toInt(match[5] || 0) - tzMin,
+ toInt(match[6] || 0),
+ toInt(match[7] || 0));
+ return date;
+ }
+ return string;
+}
+
+function toInt(str) {
+ return parseInt(str, 10);
+}
+
+function padNumber(num, digits, trim) {
+ var neg = '';
+ if (num < 0) {
+ neg = '-';
+ num = -num;
+ }
+ num = '' + num;
+ while (num.length < digits) num = '0' + num;
+ if (trim) {
+ num = num.substr(num.length - digits);
+ }
+ return neg + num;
+}
+
+
+/**
+ * @ngdoc type
+ * @name angular.mock.TzDate
+ * @description
+ *
+ * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
+ *
+ * Mock of the Date type which has its timezone specified via constructor arg.
+ *
+ * The main purpose is to create Date-like instances with timezone fixed to the specified timezone
+ * offset, so that we can test code that depends on local timezone settings without dependency on
+ * the time zone settings of the machine where the code is running.
+ *
+ * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
+ * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
+ *
+ * @example
+ * !!!! WARNING !!!!!
+ * This is not a complete Date object so only methods that were implemented can be called safely.
+ * To make matters worse, TzDate instances inherit stuff from Date via a prototype.
+ *
+ * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
+ * incomplete we might be missing some non-standard methods. This can result in errors like:
+ * "Date.prototype.foo called on incompatible Object".
+ *
+ * ```js
+ * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
+ * newYearInBratislava.getTimezoneOffset() => -60;
+ * newYearInBratislava.getFullYear() => 2010;
+ * newYearInBratislava.getMonth() => 0;
+ * newYearInBratislava.getDate() => 1;
+ * newYearInBratislava.getHours() => 0;
+ * newYearInBratislava.getMinutes() => 0;
+ * newYearInBratislava.getSeconds() => 0;
+ * ```
+ *
+ */
+angular.mock.TzDate = function(offset, timestamp) {
+ var self = new Date(0);
+ if (angular.isString(timestamp)) {
+ var tsStr = timestamp;
+
+ self.origDate = jsonStringToDate(timestamp);
+
+ timestamp = self.origDate.getTime();
+ if (isNaN(timestamp)) {
+ throw {
+ name: "Illegal Argument",
+ message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
+ };
+ }
+ } else {
+ self.origDate = new Date(timestamp);
+ }
+
+ var localOffset = new Date(timestamp).getTimezoneOffset();
+ self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60;
+ self.date = new Date(timestamp + self.offsetDiff);
+
+ self.getTime = function() {
+ return self.date.getTime() - self.offsetDiff;
+ };
+
+ self.toLocaleDateString = function() {
+ return self.date.toLocaleDateString();
+ };
+
+ self.getFullYear = function() {
+ return self.date.getFullYear();
+ };
+
+ self.getMonth = function() {
+ return self.date.getMonth();
+ };
+
+ self.getDate = function() {
+ return self.date.getDate();
+ };
+
+ self.getHours = function() {
+ return self.date.getHours();
+ };
+
+ self.getMinutes = function() {
+ return self.date.getMinutes();
+ };
+
+ self.getSeconds = function() {
+ return self.date.getSeconds();
+ };
+
+ self.getMilliseconds = function() {
+ return self.date.getMilliseconds();
+ };
+
+ self.getTimezoneOffset = function() {
+ return offset * 60;
+ };
+
+ self.getUTCFullYear = function() {
+ return self.origDate.getUTCFullYear();
+ };
+
+ self.getUTCMonth = function() {
+ return self.origDate.getUTCMonth();
+ };
+
+ self.getUTCDate = function() {
+ return self.origDate.getUTCDate();
+ };
+
+ self.getUTCHours = function() {
+ return self.origDate.getUTCHours();
+ };
+
+ self.getUTCMinutes = function() {
+ return self.origDate.getUTCMinutes();
+ };
+
+ self.getUTCSeconds = function() {
+ return self.origDate.getUTCSeconds();
+ };
+
+ self.getUTCMilliseconds = function() {
+ return self.origDate.getUTCMilliseconds();
+ };
+
+ self.getDay = function() {
+ return self.date.getDay();
+ };
+
+ // provide this method only on browsers that already have it
+ if (self.toISOString) {
+ self.toISOString = function() {
+ return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
+ padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
+ padNumber(self.origDate.getUTCDate(), 2) + 'T' +
+ padNumber(self.origDate.getUTCHours(), 2) + ':' +
+ padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
+ padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
+ padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z';
+ };
+ }
+
+ //hide all methods not implemented in this mock that the Date prototype exposes
+ var unimplementedMethods = ['getUTCDay',
+ 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
+ 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
+ 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
+ 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
+ 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
+
+ angular.forEach(unimplementedMethods, function(methodName) {
+ self[methodName] = function() {
+ throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock");
+ };
+ });
+
+ return self;
+};
+
+//make "tzDateInstance instanceof Date" return true
+angular.mock.TzDate.prototype = Date.prototype;
+/* jshint +W101 */
+
+angular.mock.animate = angular.module('ngAnimateMock', ['ng'])
+
+ .config(['$provide', function($provide) {
+
+ $provide.factory('$$forceReflow', function() {
+ function reflowFn() {
+ reflowFn.totalReflows++;
+ }
+ reflowFn.totalReflows = 0;
+ return reflowFn;
+ });
+
+ $provide.factory('$$animateAsyncRun', function() {
+ var queue = [];
+ var queueFn = function() {
+ return function(fn) {
+ queue.push(fn);
+ };
+ };
+ queueFn.flush = function() {
+ if (queue.length === 0) return false;
+
+ for (var i = 0; i < queue.length; i++) {
+ queue[i]();
+ }
+ queue = [];
+
+ return true;
+ };
+ return queueFn;
+ });
+
+ $provide.decorator('$animate', ['$delegate', '$timeout', '$browser', '$$rAF',
+ '$$forceReflow', '$$animateAsyncRun', '$rootScope',
+ function($delegate, $timeout, $browser, $$rAF,
+ $$forceReflow, $$animateAsyncRun, $rootScope) {
+ var animate = {
+ queue: [],
+ cancel: $delegate.cancel,
+ on: $delegate.on,
+ off: $delegate.off,
+ pin: $delegate.pin,
+ get reflows() {
+ return $$forceReflow.totalReflows;
+ },
+ enabled: $delegate.enabled,
+ flush: function() {
+ $rootScope.$digest();
+
+ var doNextRun, somethingFlushed = false;
+ do {
+ doNextRun = false;
+
+ if ($$rAF.queue.length) {
+ $$rAF.flush();
+ doNextRun = somethingFlushed = true;
+ }
+
+ if ($$animateAsyncRun.flush()) {
+ doNextRun = somethingFlushed = true;
+ }
+ } while (doNextRun);
+
+ if (!somethingFlushed) {
+ throw new Error('No pending animations ready to be closed or flushed');
+ }
+
+ $rootScope.$digest();
+ }
+ };
+
+ angular.forEach(
+ ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) {
+ animate[method] = function() {
+ animate.queue.push({
+ event: method,
+ element: arguments[0],
+ options: arguments[arguments.length - 1],
+ args: arguments
+ });
+ return $delegate[method].apply($delegate, arguments);
+ };
+ });
+
+ return animate;
+ }]);
+
+ }]);
+
+
+/**
+ * @ngdoc function
+ * @name angular.mock.dump
+ * @description
+ *
+ * *NOTE*: this is not an injectable instance, just a globally available function.
+ *
+ * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for
+ * debugging.
+ *
+ * This method is also available on window, where it can be used to display objects on debug
+ * console.
+ *
+ * @param {*} object - any object to turn into string.
+ * @return {string} a serialized string of the argument
+ */
+angular.mock.dump = function(object) {
+ return serialize(object);
+
+ function serialize(object) {
+ var out;
+
+ if (angular.isElement(object)) {
+ object = angular.element(object);
+ out = angular.element('<div></div>');
+ angular.forEach(object, function(element) {
+ out.append(angular.element(element).clone());
+ });
+ out = out.html();
+ } else if (angular.isArray(object)) {
+ out = [];
+ angular.forEach(object, function(o) {
+ out.push(serialize(o));
+ });
+ out = '[ ' + out.join(', ') + ' ]';
+ } else if (angular.isObject(object)) {
+ if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
+ out = serializeScope(object);
+ } else if (object instanceof Error) {
+ out = object.stack || ('' + object.name + ': ' + object.message);
+ } else {
+ // TODO(i): this prevents methods being logged,
+ // we should have a better way to serialize objects
+ out = angular.toJson(object, true);
+ }
+ } else {
+ out = String(object);
+ }
+
+ return out;
+ }
+
+ function serializeScope(scope, offset) {
+ offset = offset || ' ';
+ var log = [offset + 'Scope(' + scope.$id + '): {'];
+ for (var key in scope) {
+ if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) {
+ log.push(' ' + key + ': ' + angular.toJson(scope[key]));
+ }
+ }
+ var child = scope.$$childHead;
+ while (child) {
+ log.push(serializeScope(child, offset + ' '));
+ child = child.$$nextSibling;
+ }
+ log.push('}');
+ return log.join('\n' + offset);
+ }
+};
+
+/**
+ * @ngdoc service
+ * @name $httpBackend
+ * @description
+ * Fake HTTP backend implementation suitable for unit testing applications that use the
+ * {@link ng.$http $http service}.
+ *
+ * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less
+ * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
+ *
+ * During unit testing, we want our unit tests to run quickly and have no external dependencies so
+ * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or
+ * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is
+ * to verify whether a certain request has been sent or not, or alternatively just let the
+ * application make requests, respond with pre-trained responses and assert that the end result is
+ * what we expect it to be.
+ *
+ * This mock implementation can be used to respond with static or dynamic responses via the
+ * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
+ *
+ * When an Angular application needs some data from a server, it calls the $http service, which
+ * sends the request to a real server using $httpBackend service. With dependency injection, it is
+ * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
+ * the requests and respond with some testing data without sending a request to a real server.
+ *
+ * There are two ways to specify what test data should be returned as http responses by the mock
+ * backend when the code under test makes http requests:
+ *
+ * - `$httpBackend.expect` - specifies a request expectation
+ * - `$httpBackend.when` - specifies a backend definition
+ *
+ *
+ * # Request Expectations vs Backend Definitions
+ *
+ * Request expectations provide a way to make assertions about requests made by the application and
+ * to define responses for those requests. The test will fail if the expected requests are not made
+ * or they are made in the wrong order.
+ *
+ * Backend definitions allow you to define a fake backend for your application which doesn't assert
+ * if a particular request was made or not, it just returns a trained response if a request is made.
+ * The test will pass whether or not the request gets made during testing.
+ *
+ *
+ * <table class="table">
+ * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr>
+ * <tr>
+ * <th>Syntax</th>
+ * <td>.expect(...).respond(...)</td>
+ * <td>.when(...).respond(...)</td>
+ * </tr>
+ * <tr>
+ * <th>Typical usage</th>
+ * <td>strict unit tests</td>
+ * <td>loose (black-box) unit testing</td>
+ * </tr>
+ * <tr>
+ * <th>Fulfills multiple requests</th>
+ * <td>NO</td>
+ * <td>YES</td>
+ * </tr>
+ * <tr>
+ * <th>Order of requests matters</th>
+ * <td>YES</td>
+ * <td>NO</td>
+ * </tr>
+ * <tr>
+ * <th>Request required</th>
+ * <td>YES</td>
+ * <td>NO</td>
+ * </tr>
+ * <tr>
+ * <th>Response required</th>
+ * <td>optional (see below)</td>
+ * <td>YES</td>
+ * </tr>
+ * </table>
+ *
+ * In cases where both backend definitions and request expectations are specified during unit
+ * testing, the request expectations are evaluated first.
+ *
+ * If a request expectation has no response specified, the algorithm will search your backend
+ * definitions for an appropriate response.
+ *
+ * If a request didn't match any expectation or if the expectation doesn't have the response
+ * defined, the backend definitions are evaluated in sequential order to see if any of them match
+ * the request. The response from the first matched definition is returned.
+ *
+ *
+ * # Flushing HTTP requests
+ *
+ * The $httpBackend used in production always responds to requests asynchronously. If we preserved
+ * this behavior in unit testing, we'd have to create async unit tests, which are hard to write,
+ * to follow and to maintain. But neither can the testing mock respond synchronously; that would
+ * change the execution of the code under test. For this reason, the mock $httpBackend has a
+ * `flush()` method, which allows the test to explicitly flush pending requests. This preserves
+ * the async api of the backend, while allowing the test to execute synchronously.
+ *
+ *
+ * # Unit testing with mock $httpBackend
+ * The following code shows how to setup and use the mock backend when unit testing a controller.
+ * First we create the controller under test:
+ *
+ ```js
+ // The module code
+ angular
+ .module('MyApp', [])
+ .controller('MyController', MyController);
+
+ // The controller code
+ function MyController($scope, $http) {
+ var authToken;
+
+ $http.get('/auth.py').success(function(data, status, headers) {
+ authToken = headers('A-Token');
+ $scope.user = data;
+ });
+
+ $scope.saveMessage = function(message) {
+ var headers = { 'Authorization': authToken };
+ $scope.status = 'Saving...';
+
+ $http.post('/add-msg.py', message, { headers: headers } ).success(function(response) {
+ $scope.status = '';
+ }).error(function() {
+ $scope.status = 'Failed...';
+ });
+ };
+ }
+ ```
+ *
+ * Now we setup the mock backend and create the test specs:
+ *
+ ```js
+ // testing controller
+ describe('MyController', function() {
+ var $httpBackend, $rootScope, createController, authRequestHandler;
+
+ // Set up the module
+ beforeEach(module('MyApp'));
+
+ beforeEach(inject(function($injector) {
+ // Set up the mock http service responses
+ $httpBackend = $injector.get('$httpBackend');
+ // backend definition common for all tests
+ authRequestHandler = $httpBackend.when('GET', '/auth.py')
+ .respond({userId: 'userX'}, {'A-Token': 'xxx'});
+
+ // Get hold of a scope (i.e. the root scope)
+ $rootScope = $injector.get('$rootScope');
+ // The $controller service is used to create instances of controllers
+ var $controller = $injector.get('$controller');
+
+ createController = function() {
+ return $controller('MyController', {'$scope' : $rootScope });
+ };
+ }));
+
+
+ afterEach(function() {
+ $httpBackend.verifyNoOutstandingExpectation();
+ $httpBackend.verifyNoOutstandingRequest();
+ });
+
+
+ it('should fetch authentication token', function() {
+ $httpBackend.expectGET('/auth.py');
+ var controller = createController();
+ $httpBackend.flush();
+ });
+
+
+ it('should fail authentication', function() {
+
+ // Notice how you can change the response even after it was set
+ authRequestHandler.respond(401, '');
+
+ $httpBackend.expectGET('/auth.py');
+ var controller = createController();
+ $httpBackend.flush();
+ expect($rootScope.status).toBe('Failed...');
+ });
+
+
+ it('should send msg to server', function() {
+ var controller = createController();
+ $httpBackend.flush();
+
+ // now you don’t care about the authentication, but
+ // the controller will still send the request and
+ // $httpBackend will respond without you having to
+ // specify the expectation and response for this request
+
+ $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
+ $rootScope.saveMessage('message content');
+ expect($rootScope.status).toBe('Saving...');
+ $httpBackend.flush();
+ expect($rootScope.status).toBe('');
+ });
+
+
+ it('should send auth header', function() {
+ var controller = createController();
+ $httpBackend.flush();
+
+ $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
+ // check if the header was sent, if it wasn't the expectation won't
+ // match the request and the test will fail
+ return headers['Authorization'] == 'xxx';
+ }).respond(201, '');
+
+ $rootScope.saveMessage('whatever');
+ $httpBackend.flush();
+ });
+ });
+ ```
+ */
+angular.mock.$HttpBackendProvider = function() {
+ this.$get = ['$rootScope', '$timeout', createHttpBackendMock];
+};
+
+/**
+ * General factory function for $httpBackend mock.
+ * Returns instance for unit testing (when no arguments specified):
+ * - passing through is disabled
+ * - auto flushing is disabled
+ *
+ * Returns instance for e2e testing (when `$delegate` and `$browser` specified):
+ * - passing through (delegating request to real backend) is enabled
+ * - auto flushing is enabled
+ *
+ * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
+ * @param {Object=} $browser Auto-flushing enabled if specified
+ * @return {Object} Instance of $httpBackend mock
+ */
+function createHttpBackendMock($rootScope, $timeout, $delegate, $browser) {
+ var definitions = [],
+ expectations = [],
+ responses = [],
+ responsesPush = angular.bind(responses, responses.push),
+ copy = angular.copy;
+
+ function createResponse(status, data, headers, statusText) {
+ if (angular.isFunction(status)) return status;
+
+ return function() {
+ return angular.isNumber(status)
+ ? [status, data, headers, statusText]
+ : [200, status, data, headers];
+ };
+ }
+
+ // TODO(vojta): change params to: method, url, data, headers, callback
+ function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) {
+ var xhr = new MockXhr(),
+ expectation = expectations[0],
+ wasExpected = false;
+
+ function prettyPrint(data) {
+ return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
+ ? data
+ : angular.toJson(data);
+ }
+
+ function wrapResponse(wrapped) {
+ if (!$browser && timeout) {
+ timeout.then ? timeout.then(handleTimeout) : $timeout(handleTimeout, timeout);
+ }
+
+ return handleResponse;
+
+ function handleResponse() {
+ var response = wrapped.response(method, url, data, headers);
+ xhr.$$respHeaders = response[2];
+ callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(),
+ copy(response[3] || ''));
+ }
+
+ function handleTimeout() {
+ for (var i = 0, ii = responses.length; i < ii; i++) {
+ if (responses[i] === handleResponse) {
+ responses.splice(i, 1);
+ callback(-1, undefined, '');
+ break;
+ }
+ }
+ }
+ }
+
+ if (expectation && expectation.match(method, url)) {
+ if (!expectation.matchData(data)) {
+ throw new Error('Expected ' + expectation + ' with different data\n' +
+ 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
+ }
+
+ if (!expectation.matchHeaders(headers)) {
+ throw new Error('Expected ' + expectation + ' with different headers\n' +
+ 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
+ prettyPrint(headers));
+ }
+
+ expectations.shift();
+
+ if (expectation.response) {
+ responses.push(wrapResponse(expectation));
+ return;
+ }
+ wasExpected = true;
+ }
+
+ var i = -1, definition;
+ while ((definition = definitions[++i])) {
+ if (definition.match(method, url, data, headers || {})) {
+ if (definition.response) {
+ // if $browser specified, we do auto flush all requests
+ ($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
+ } else if (definition.passThrough) {
+ $delegate(method, url, data, callback, headers, timeout, withCredentials);
+ } else throw new Error('No response defined !');
+ return;
+ }
+ }
+ throw wasExpected ?
+ new Error('No response defined !') :
+ new Error('Unexpected request: ' + method + ' ' + url + '\n' +
+ (expectation ? 'Expected ' + expectation : 'No more request expected'));
+ }
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#when
+ * @description
+ * Creates a new backend definition.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
+ * data string and returns true if the data is as expected.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current definition.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ *
+ * - respond –
+ * `{function([status,] data[, headers, statusText])
+ * | function(function(method, url, data, headers)}`
+ * – The respond method takes a set of static data to be returned or a function that can
+ * return an array containing response status (number), response data (string), response
+ * headers (Object), and the text for the status (string). The respond method returns the
+ * `requestHandler` object for possible overrides.
+ */
+ $httpBackend.when = function(method, url, data, headers) {
+ var definition = new MockHttpExpectation(method, url, data, headers),
+ chain = {
+ respond: function(status, data, headers, statusText) {
+ definition.passThrough = undefined;
+ definition.response = createResponse(status, data, headers, statusText);
+ return chain;
+ }
+ };
+
+ if ($browser) {
+ chain.passThrough = function() {
+ definition.response = undefined;
+ definition.passThrough = true;
+ return chain;
+ };
+ }
+
+ definitions.push(definition);
+ return chain;
+ };
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#whenGET
+ * @description
+ * Creates a new backend definition for GET requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#whenHEAD
+ * @description
+ * Creates a new backend definition for HEAD requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#whenDELETE
+ * @description
+ * Creates a new backend definition for DELETE requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#whenPOST
+ * @description
+ * Creates a new backend definition for POST requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
+ * data string and returns true if the data is as expected.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#whenPUT
+ * @description
+ * Creates a new backend definition for PUT requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives
+ * data string and returns true if the data is as expected.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#whenJSONP
+ * @description
+ * Creates a new backend definition for JSONP requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+ createShortMethods('when');
+
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expect
+ * @description
+ * Creates a new request expectation.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
+ * receives data string and returns true if the data is as expected, or Object if request body
+ * is in JSON format.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current expectation.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ *
+ * - respond –
+ * `{function([status,] data[, headers, statusText])
+ * | function(function(method, url, data, headers)}`
+ * – The respond method takes a set of static data to be returned or a function that can
+ * return an array containing response status (number), response data (string), response
+ * headers (Object), and the text for the status (string). The respond method returns the
+ * `requestHandler` object for possible overrides.
+ */
+ $httpBackend.expect = function(method, url, data, headers) {
+ var expectation = new MockHttpExpectation(method, url, data, headers),
+ chain = {
+ respond: function(status, data, headers, statusText) {
+ expectation.response = createResponse(status, data, headers, statusText);
+ return chain;
+ }
+ };
+
+ expectations.push(expectation);
+ return chain;
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectGET
+ * @description
+ * Creates a new request expectation for GET requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled. See #expect for more info.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectHEAD
+ * @description
+ * Creates a new request expectation for HEAD requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectDELETE
+ * @description
+ * Creates a new request expectation for DELETE requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectPOST
+ * @description
+ * Creates a new request expectation for POST requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
+ * receives data string and returns true if the data is as expected, or Object if request body
+ * is in JSON format.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectPUT
+ * @description
+ * Creates a new request expectation for PUT requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
+ * receives data string and returns true if the data is as expected, or Object if request body
+ * is in JSON format.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectPATCH
+ * @description
+ * Creates a new request expectation for PATCH requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that
+ * receives data string and returns true if the data is as expected, or Object if request body
+ * is in JSON format.
+ * @param {Object=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#expectJSONP
+ * @description
+ * Creates a new request expectation for JSONP requests. For more info see `expect()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives an url
+ * and returns true if the url matches the current definition.
+ * @returns {requestHandler} Returns an object with `respond` method that controls how a matched
+ * request is handled. You can save this object for later use and invoke `respond` again in
+ * order to change how a matched request is handled.
+ */
+ createShortMethods('expect');
+
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#flush
+ * @description
+ * Flushes all pending requests using the trained responses.
+ *
+ * @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
+ * all pending requests will be flushed. If there are no pending requests when the flush method
+ * is called an exception is thrown (as this typically a sign of programming error).
+ */
+ $httpBackend.flush = function(count, digest) {
+ if (digest !== false) $rootScope.$digest();
+ if (!responses.length) throw new Error('No pending request to flush !');
+
+ if (angular.isDefined(count) && count !== null) {
+ while (count--) {
+ if (!responses.length) throw new Error('No more pending request to flush !');
+ responses.shift()();
+ }
+ } else {
+ while (responses.length) {
+ responses.shift()();
+ }
+ }
+ $httpBackend.verifyNoOutstandingExpectation(digest);
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#verifyNoOutstandingExpectation
+ * @description
+ * Verifies that all of the requests defined via the `expect` api were made. If any of the
+ * requests were not made, verifyNoOutstandingExpectation throws an exception.
+ *
+ * Typically, you would call this method following each test case that asserts requests using an
+ * "afterEach" clause.
+ *
+ * ```js
+ * afterEach($httpBackend.verifyNoOutstandingExpectation);
+ * ```
+ */
+ $httpBackend.verifyNoOutstandingExpectation = function(digest) {
+ if (digest !== false) $rootScope.$digest();
+ if (expectations.length) {
+ throw new Error('Unsatisfied requests: ' + expectations.join(', '));
+ }
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#verifyNoOutstandingRequest
+ * @description
+ * Verifies that there are no outstanding requests that need to be flushed.
+ *
+ * Typically, you would call this method following each test case that asserts requests using an
+ * "afterEach" clause.
+ *
+ * ```js
+ * afterEach($httpBackend.verifyNoOutstandingRequest);
+ * ```
+ */
+ $httpBackend.verifyNoOutstandingRequest = function() {
+ if (responses.length) {
+ throw new Error('Unflushed requests: ' + responses.length);
+ }
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $httpBackend#resetExpectations
+ * @description
+ * Resets all request expectations, but preserves all backend definitions. Typically, you would
+ * call resetExpectations during a multiple-phase test when you want to reuse the same instance of
+ * $httpBackend mock.
+ */
+ $httpBackend.resetExpectations = function() {
+ expectations.length = 0;
+ responses.length = 0;
+ };
+
+ return $httpBackend;
+
+
+ function createShortMethods(prefix) {
+ angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) {
+ $httpBackend[prefix + method] = function(url, headers) {
+ return $httpBackend[prefix](method, url, undefined, headers);
+ };
+ });
+
+ angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
+ $httpBackend[prefix + method] = function(url, data, headers) {
+ return $httpBackend[prefix](method, url, data, headers);
+ };
+ });
+ }
+}
+
+function MockHttpExpectation(method, url, data, headers) {
+
+ this.data = data;
+ this.headers = headers;
+
+ this.match = function(m, u, d, h) {
+ if (method != m) return false;
+ if (!this.matchUrl(u)) return false;
+ if (angular.isDefined(d) && !this.matchData(d)) return false;
+ if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
+ return true;
+ };
+
+ this.matchUrl = function(u) {
+ if (!url) return true;
+ if (angular.isFunction(url.test)) return url.test(u);
+ if (angular.isFunction(url)) return url(u);
+ return url == u;
+ };
+
+ this.matchHeaders = function(h) {
+ if (angular.isUndefined(headers)) return true;
+ if (angular.isFunction(headers)) return headers(h);
+ return angular.equals(headers, h);
+ };
+
+ this.matchData = function(d) {
+ if (angular.isUndefined(data)) return true;
+ if (data && angular.isFunction(data.test)) return data.test(d);
+ if (data && angular.isFunction(data)) return data(d);
+ if (data && !angular.isString(data)) {
+ return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d));
+ }
+ return data == d;
+ };
+
+ this.toString = function() {
+ return method + ' ' + url;
+ };
+}
+
+function createMockXhr() {
+ return new MockXhr();
+}
+
+function MockXhr() {
+
+ // hack for testing $http, $httpBackend
+ MockXhr.$$lastInstance = this;
+
+ this.open = function(method, url, async) {
+ this.$$method = method;
+ this.$$url = url;
+ this.$$async = async;
+ this.$$reqHeaders = {};
+ this.$$respHeaders = {};
+ };
+
+ this.send = function(data) {
+ this.$$data = data;
+ };
+
+ this.setRequestHeader = function(key, value) {
+ this.$$reqHeaders[key] = value;
+ };
+
+ this.getResponseHeader = function(name) {
+ // the lookup must be case insensitive,
+ // that's why we try two quick lookups first and full scan last
+ var header = this.$$respHeaders[name];
+ if (header) return header;
+
+ name = angular.lowercase(name);
+ header = this.$$respHeaders[name];
+ if (header) return header;
+
+ header = undefined;
+ angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
+ if (!header && angular.lowercase(headerName) == name) header = headerVal;
+ });
+ return header;
+ };
+
+ this.getAllResponseHeaders = function() {
+ var lines = [];
+
+ angular.forEach(this.$$respHeaders, function(value, key) {
+ lines.push(key + ': ' + value);
+ });
+ return lines.join('\n');
+ };
+
+ this.abort = angular.noop;
+}
+
+
+/**
+ * @ngdoc service
+ * @name $timeout
+ * @description
+ *
+ * This service is just a simple decorator for {@link ng.$timeout $timeout} service
+ * that adds a "flush" and "verifyNoPendingTasks" methods.
+ */
+
+angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) {
+
+ /**
+ * @ngdoc method
+ * @name $timeout#flush
+ * @description
+ *
+ * Flushes the queue of pending tasks.
+ *
+ * @param {number=} delay maximum timeout amount to flush up until
+ */
+ $delegate.flush = function(delay) {
+ $browser.defer.flush(delay);
+ };
+
+ /**
+ * @ngdoc method
+ * @name $timeout#verifyNoPendingTasks
+ * @description
+ *
+ * Verifies that there are no pending tasks that need to be flushed.
+ */
+ $delegate.verifyNoPendingTasks = function() {
+ if ($browser.deferredFns.length) {
+ throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +
+ formatPendingTasksAsString($browser.deferredFns));
+ }
+ };
+
+ function formatPendingTasksAsString(tasks) {
+ var result = [];
+ angular.forEach(tasks, function(task) {
+ result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');
+ });
+
+ return result.join(', ');
+ }
+
+ return $delegate;
+}];
+
+angular.mock.$RAFDecorator = ['$delegate', function($delegate) {
+ var rafFn = function(fn) {
+ var index = rafFn.queue.length;
+ rafFn.queue.push(fn);
+ return function() {
+ rafFn.queue.splice(index, 1);
+ };
+ };
+
+ rafFn.queue = [];
+ rafFn.supported = $delegate.supported;
+
+ rafFn.flush = function() {
+ if (rafFn.queue.length === 0) {
+ throw new Error('No rAF callbacks present');
+ }
+
+ var length = rafFn.queue.length;
+ for (var i = 0; i < length; i++) {
+ rafFn.queue[i]();
+ }
+
+ rafFn.queue = rafFn.queue.slice(i);
+ };
+
+ return rafFn;
+}];
+
+/**
+ *
+ */
+angular.mock.$RootElementProvider = function() {
+ this.$get = function() {
+ return angular.element('<div ng-app></div>');
+ };
+};
+
+/**
+ * @ngdoc service
+ * @name $controller
+ * @description
+ * A decorator for {@link ng.$controller} with additional `bindings` parameter, useful when testing
+ * controllers of directives that use {@link $compile#-bindtocontroller- `bindToController`}.
+ *
+ *
+ * ## Example
+ *
+ * ```js
+ *
+ * // Directive definition ...
+ *
+ * myMod.directive('myDirective', {
+ * controller: 'MyDirectiveController',
+ * bindToController: {
+ * name: '@'
+ * }
+ * });
+ *
+ *
+ * // Controller definition ...
+ *
+ * myMod.controller('MyDirectiveController', ['log', function($log) {
+ * $log.info(this.name);
+ * })];
+ *
+ *
+ * // In a test ...
+ *
+ * describe('myDirectiveController', function() {
+ * it('should write the bound name to the log', inject(function($controller, $log) {
+ * var ctrl = $controller('MyDirectiveController', { /* no locals */ }, { name: 'Clark Kent' });
+ * expect(ctrl.name).toEqual('Clark Kent');
+ * expect($log.info.logs).toEqual(['Clark Kent']);
+ * });
+ * });
+ *
+ * ```
+ *
+ * @param {Function|string} constructor If called with a function then it's considered to be the
+ * controller constructor function. Otherwise it's considered to be a string which is used
+ * to retrieve the controller constructor using the following steps:
+ *
+ * * check if a controller with given name is registered via `$controllerProvider`
+ * * check if evaluating the string on the current scope returns a constructor
+ * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
+ * `window` object (not recommended)
+ *
+ * The string can use the `controller as property` syntax, where the controller instance is published
+ * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
+ * to work correctly.
+ *
+ * @param {Object} locals Injection locals for Controller.
+ * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used
+ * to simulate the `bindToController` feature and simplify certain kinds of tests.
+ * @return {Object} Instance of given controller.
+ */
+angular.mock.$ControllerDecorator = ['$delegate', function($delegate) {
+ return function(expression, locals, later, ident) {
+ if (later && typeof later === 'object') {
+ var create = $delegate(expression, locals, true, ident);
+ angular.extend(create.instance, later);
+ return create();
+ }
+ return $delegate(expression, locals, later, ident);
+ };
+}];
+
+
+/**
+ * @ngdoc module
+ * @name ngMock
+ * @packageName angular-mocks
+ * @description
+ *
+ * # ngMock
+ *
+ * The `ngMock` module provides support to inject and mock Angular services into unit tests.
+ * In addition, ngMock also extends various core ng services such that they can be
+ * inspected and controlled in a synchronous manner within test code.
+ *
+ *
+ * <div doc-module-components="ngMock"></div>
+ *
+ */
+angular.module('ngMock', ['ng']).provider({
+ $browser: angular.mock.$BrowserProvider,
+ $exceptionHandler: angular.mock.$ExceptionHandlerProvider,
+ $log: angular.mock.$LogProvider,
+ $interval: angular.mock.$IntervalProvider,
+ $httpBackend: angular.mock.$HttpBackendProvider,
+ $rootElement: angular.mock.$RootElementProvider
+}).config(['$provide', function($provide) {
+ $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);
+ $provide.decorator('$$rAF', angular.mock.$RAFDecorator);
+ $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator);
+ $provide.decorator('$controller', angular.mock.$ControllerDecorator);
+}]);
+
+/**
+ * @ngdoc module
+ * @name ngMockE2E
+ * @module ngMockE2E
+ * @packageName angular-mocks
+ * @description
+ *
+ * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
+ * Currently there is only one mock present in this module -
+ * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
+ */
+angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) {
+ $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
+}]);
+
+/**
+ * @ngdoc service
+ * @name $httpBackend
+ * @module ngMockE2E
+ * @description
+ * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
+ * applications that use the {@link ng.$http $http service}.
+ *
+ * *Note*: For fake http backend implementation suitable for unit testing please see
+ * {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
+ *
+ * This implementation can be used to respond with static or dynamic responses via the `when` api
+ * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
+ * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
+ * templates from a webserver).
+ *
+ * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
+ * is being developed with the real backend api replaced with a mock, it is often desirable for
+ * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
+ * templates or static files from the webserver). To configure the backend with this behavior
+ * use the `passThrough` request handler of `when` instead of `respond`.
+ *
+ * Additionally, we don't want to manually have to flush mocked out requests like we do during unit
+ * testing. For this reason the e2e $httpBackend flushes mocked out requests
+ * automatically, closely simulating the behavior of the XMLHttpRequest object.
+ *
+ * To setup the application to run with this http backend, you have to create a module that depends
+ * on the `ngMockE2E` and your application modules and defines the fake backend:
+ *
+ * ```js
+ * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
+ * myAppDev.run(function($httpBackend) {
+ * phones = [{name: 'phone1'}, {name: 'phone2'}];
+ *
+ * // returns the current list of phones
+ * $httpBackend.whenGET('/phones').respond(phones);
+ *
+ * // adds a new phone to the phones array
+ * $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
+ * var phone = angular.fromJson(data);
+ * phones.push(phone);
+ * return [200, phone, {}];
+ * });
+ * $httpBackend.whenGET(/^\/templates\//).passThrough();
+ * //...
+ * });
+ * ```
+ *
+ * Afterwards, bootstrap your app with this new module.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#when
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition.
+ *
+ * @param {string} method HTTP method.
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
+ * object and returns true if the headers match the current definition.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ *
+ * - respond –
+ * `{function([status,] data[, headers, statusText])
+ * | function(function(method, url, data, headers)}`
+ * – The respond method takes a set of static data to be returned or a function that can return
+ * an array containing response status (number), response data (string), response headers
+ * (Object), and the text for the status (string).
+ * - passThrough – `{function()}` – Any request matching a backend definition with
+ * `passThrough` handler will be passed through to the real backend (an XHR request will be made
+ * to the server.)
+ * - Both methods return the `requestHandler` object for possible overrides.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenGET
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for GET requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenHEAD
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for HEAD requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenDELETE
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for DELETE requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenPOST
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for POST requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenPUT
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for PUT requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenPATCH
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for PATCH requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @param {(string|RegExp)=} data HTTP request body.
+ * @param {(Object|function(Object))=} headers HTTP headers.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+
+/**
+ * @ngdoc method
+ * @name $httpBackend#whenJSONP
+ * @module ngMockE2E
+ * @description
+ * Creates a new backend definition for JSONP requests. For more info see `when()`.
+ *
+ * @param {string|RegExp|function(string)} url HTTP url or function that receives a url
+ * and returns true if the url matches the current definition.
+ * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
+ * control how a matched request is handled. You can save this object for later use and invoke
+ * `respond` or `passThrough` again in order to change how a matched request is handled.
+ */
+angular.mock.e2e = {};
+angular.mock.e2e.$httpBackendDecorator =
+ ['$rootScope', '$timeout', '$delegate', '$browser', createHttpBackendMock];
+
+
+/**
+ * @ngdoc type
+ * @name $rootScope.Scope
+ * @module ngMock
+ * @description
+ * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These
+ * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when
+ * `ngMock` module is loaded.
+ *
+ * In addition to all the regular `Scope` methods, the following helper methods are available:
+ */
+angular.mock.$RootScopeDecorator = ['$delegate', function($delegate) {
+
+ var $rootScopePrototype = Object.getPrototypeOf($delegate);
+
+ $rootScopePrototype.$countChildScopes = countChildScopes;
+ $rootScopePrototype.$countWatchers = countWatchers;
+
+ return $delegate;
+
+ // ------------------------------------------------------------------------------------------ //
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$countChildScopes
+ * @module ngMock
+ * @description
+ * Counts all the direct and indirect child scopes of the current scope.
+ *
+ * The current scope is excluded from the count. The count includes all isolate child scopes.
+ *
+ * @returns {number} Total number of child scopes.
+ */
+ function countChildScopes() {
+ // jshint validthis: true
+ var count = 0; // exclude the current scope
+ var pendingChildHeads = [this.$$childHead];
+ var currentScope;
+
+ while (pendingChildHeads.length) {
+ currentScope = pendingChildHeads.shift();
+
+ while (currentScope) {
+ count += 1;
+ pendingChildHeads.push(currentScope.$$childHead);
+ currentScope = currentScope.$$nextSibling;
+ }
+ }
+
+ return count;
+ }
+
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$countWatchers
+ * @module ngMock
+ * @description
+ * Counts all the watchers of direct and indirect child scopes of the current scope.
+ *
+ * The watchers of the current scope are included in the count and so are all the watchers of
+ * isolate child scopes.
+ *
+ * @returns {number} Total number of watchers.
+ */
+ function countWatchers() {
+ // jshint validthis: true
+ var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope
+ var pendingChildHeads = [this.$$childHead];
+ var currentScope;
+
+ while (pendingChildHeads.length) {
+ currentScope = pendingChildHeads.shift();
+
+ while (currentScope) {
+ count += currentScope.$$watchers ? currentScope.$$watchers.length : 0;
+ pendingChildHeads.push(currentScope.$$childHead);
+ currentScope = currentScope.$$nextSibling;
+ }
+ }
+
+ return count;
+ }
+}];
+
+
+if (window.jasmine || window.mocha) {
+
+ var currentSpec = null,
+ annotatedFunctions = [],
+ isSpecRunning = function() {
+ return !!currentSpec;
+ };
+
+ angular.mock.$$annotate = angular.injector.$$annotate;
+ angular.injector.$$annotate = function(fn) {
+ if (typeof fn === 'function' && !fn.$inject) {
+ annotatedFunctions.push(fn);
+ }
+ return angular.mock.$$annotate.apply(this, arguments);
+ };
+
+
+ (window.beforeEach || window.setup)(function() {
+ annotatedFunctions = [];
+ currentSpec = this;
+ });
+
+ (window.afterEach || window.teardown)(function() {
+ var injector = currentSpec.$injector;
+
+ annotatedFunctions.forEach(function(fn) {
+ delete fn.$inject;
+ });
+
+ angular.forEach(currentSpec.$modules, function(module) {
+ if (module && module.$$hashKey) {
+ module.$$hashKey = undefined;
+ }
+ });
+
+ currentSpec.$injector = null;
+ currentSpec.$modules = null;
+ currentSpec = null;
+
+ if (injector) {
+ injector.get('$rootElement').off();
+ }
+
+ // clean up jquery's fragment cache
+ angular.forEach(angular.element.fragments, function(val, key) {
+ delete angular.element.fragments[key];
+ });
+
+ MockXhr.$$lastInstance = null;
+
+ angular.forEach(angular.callbacks, function(val, key) {
+ delete angular.callbacks[key];
+ });
+ angular.callbacks.counter = 0;
+ });
+
+ /**
+ * @ngdoc function
+ * @name angular.mock.module
+ * @description
+ *
+ * *NOTE*: This function is also published on window for easy access.<br>
+ * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
+ *
+ * This function registers a module configuration code. It collects the configuration information
+ * which will be used when the injector is created by {@link angular.mock.inject inject}.
+ *
+ * See {@link angular.mock.inject inject} for usage example
+ *
+ * @param {...(string|Function|Object)} fns any number of modules which are represented as string
+ * aliases or as anonymous module initialization functions. The modules are used to
+ * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an
+ * object literal is passed each key-value pair will be registered on the module via
+ * {@link auto.$provide $provide}.value, the key being the string name (or token) to associate
+ * with the value on the injector.
+ */
+ window.module = angular.mock.module = function() {
+ var moduleFns = Array.prototype.slice.call(arguments, 0);
+ return isSpecRunning() ? workFn() : workFn;
+ /////////////////////
+ function workFn() {
+ if (currentSpec.$injector) {
+ throw new Error('Injector already created, can not register a module!');
+ } else {
+ var modules = currentSpec.$modules || (currentSpec.$modules = []);
+ angular.forEach(moduleFns, function(module) {
+ if (angular.isObject(module) && !angular.isArray(module)) {
+ modules.push(function($provide) {
+ angular.forEach(module, function(value, key) {
+ $provide.value(key, value);
+ });
+ });
+ } else {
+ modules.push(module);
+ }
+ });
+ }
+ }
+ };
+
+ /**
+ * @ngdoc function
+ * @name angular.mock.inject
+ * @description
+ *
+ * *NOTE*: This function is also published on window for easy access.<br>
+ * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha
+ *
+ * The inject function wraps a function into an injectable function. The inject() creates new
+ * instance of {@link auto.$injector $injector} per test, which is then used for
+ * resolving references.
+ *
+ *
+ * ## Resolving References (Underscore Wrapping)
+ * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this
+ * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable
+ * that is declared in the scope of the `describe()` block. Since we would, most likely, want
+ * the variable to have the same name of the reference we have a problem, since the parameter
+ * to the `inject()` function would hide the outer variable.
+ *
+ * To help with this, the injected parameters can, optionally, be enclosed with underscores.
+ * These are ignored by the injector when the reference name is resolved.
+ *
+ * For example, the parameter `_myService_` would be resolved as the reference `myService`.
+ * Since it is available in the function body as _myService_, we can then assign it to a variable
+ * defined in an outer scope.
+ *
+ * ```
+ * // Defined out reference variable outside
+ * var myService;
+ *
+ * // Wrap the parameter in underscores
+ * beforeEach( inject( function(_myService_){
+ * myService = _myService_;
+ * }));
+ *
+ * // Use myService in a series of tests.
+ * it('makes use of myService', function() {
+ * myService.doStuff();
+ * });
+ *
+ * ```
+ *
+ * See also {@link angular.mock.module angular.mock.module}
+ *
+ * ## Example
+ * Example of what a typical jasmine tests looks like with the inject method.
+ * ```js
+ *
+ * angular.module('myApplicationModule', [])
+ * .value('mode', 'app')
+ * .value('version', 'v1.0.1');
+ *
+ *
+ * describe('MyApp', function() {
+ *
+ * // You need to load modules that you want to test,
+ * // it loads only the "ng" module by default.
+ * beforeEach(module('myApplicationModule'));
+ *
+ *
+ * // inject() is used to inject arguments of all given functions
+ * it('should provide a version', inject(function(mode, version) {
+ * expect(version).toEqual('v1.0.1');
+ * expect(mode).toEqual('app');
+ * }));
+ *
+ *
+ * // The inject and module method can also be used inside of the it or beforeEach
+ * it('should override a version and test the new version is injected', function() {
+ * // module() takes functions or strings (module aliases)
+ * module(function($provide) {
+ * $provide.value('version', 'overridden'); // override version here
+ * });
+ *
+ * inject(function(version) {
+ * expect(version).toEqual('overridden');
+ * });
+ * });
+ * });
+ *
+ * ```
+ *
+ * @param {...Function} fns any number of functions which will be injected using the injector.
+ */
+
+
+
+ var ErrorAddingDeclarationLocationStack = function(e, errorForStack) {
+ this.message = e.message;
+ this.name = e.name;
+ if (e.line) this.line = e.line;
+ if (e.sourceId) this.sourceId = e.sourceId;
+ if (e.stack && errorForStack)
+ this.stack = e.stack + '\n' + errorForStack.stack;
+ if (e.stackArray) this.stackArray = e.stackArray;
+ };
+ ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString;
+
+ window.inject = angular.mock.inject = function() {
+ var blockFns = Array.prototype.slice.call(arguments, 0);
+ var errorForStack = new Error('Declaration Location');
+ return isSpecRunning() ? workFn.call(currentSpec) : workFn;
+ /////////////////////
+ function workFn() {
+ var modules = currentSpec.$modules || [];
+ var strictDi = !!currentSpec.$injectorStrict;
+ modules.unshift('ngMock');
+ modules.unshift('ng');
+ var injector = currentSpec.$injector;
+ if (!injector) {
+ if (strictDi) {
+ // If strictDi is enabled, annotate the providerInjector blocks
+ angular.forEach(modules, function(moduleFn) {
+ if (typeof moduleFn === "function") {
+ angular.injector.$$annotate(moduleFn);
+ }
+ });
+ }
+ injector = currentSpec.$injector = angular.injector(modules, strictDi);
+ currentSpec.$injectorStrict = strictDi;
+ }
+ for (var i = 0, ii = blockFns.length; i < ii; i++) {
+ if (currentSpec.$injectorStrict) {
+ // If the injector is strict / strictDi, and the spec wants to inject using automatic
+ // annotation, then annotate the function here.
+ injector.annotate(blockFns[i]);
+ }
+ try {
+ /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */
+ injector.invoke(blockFns[i] || angular.noop, this);
+ /* jshint +W040 */
+ } catch (e) {
+ if (e.stack && errorForStack) {
+ throw new ErrorAddingDeclarationLocationStack(e, errorForStack);
+ }
+ throw e;
+ } finally {
+ errorForStack = null;
+ }
+ }
+ }
+ };
+
+
+ angular.mock.inject.strictDi = function(value) {
+ value = arguments.length ? !!value : true;
+ return isSpecRunning() ? workFn() : workFn;
+
+ function workFn() {
+ if (value !== currentSpec.$injectorStrict) {
+ if (currentSpec.$injector) {
+ throw new Error('Injector already created, can not modify strict annotations');
+ } else {
+ currentSpec.$injectorStrict = value;
+ }
+ }
+ }
+ };
+}
+
+
+})(window, window.angular);
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-mocks/bower.json b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/bower.json
new file mode 100644
index 0000000..423cf38
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/bower.json
@@ -0,0 +1,9 @@
+{
+ "name": "angular-mocks",
+ "version": "1.4.8",
+ "main": "./angular-mocks.js",
+ "ignore": [],
+ "dependencies": {
+ "angular": "1.4.8"
+ }
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-mocks/ngAnimateMock.js b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/ngAnimateMock.js
new file mode 100644
index 0000000..6f99e62
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/ngAnimateMock.js
@@ -0,0 +1,2 @@
+require('./angular-mocks');
+module.exports = 'ngAnimateMock';
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-mocks/ngMock.js b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/ngMock.js
new file mode 100644
index 0000000..7944de7
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/ngMock.js
@@ -0,0 +1,2 @@
+require('./angular-mocks');
+module.exports = 'ngMock';
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-mocks/ngMockE2E.js b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/ngMockE2E.js
new file mode 100644
index 0000000..fc2e539
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/ngMockE2E.js
@@ -0,0 +1,2 @@
+require('./angular-mocks');
+module.exports = 'ngMockE2E';
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-mocks/package.json b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/package.json
new file mode 100644
index 0000000..49f7779
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-mocks/package.json
@@ -0,0 +1,27 @@
+{
+ "name": "angular-mocks",
+ "version": "1.4.8",
+ "description": "AngularJS mocks for testing",
+ "main": "angular-mocks.js",
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/angular/angular.js.git"
+ },
+ "keywords": [
+ "angular",
+ "framework",
+ "browser",
+ "mocks",
+ "testing",
+ "client-side"
+ ],
+ "author": "Angular Core Team <angular-core+npm@google.com>",
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/angular/angular.js/issues"
+ },
+ "homepage": "http://angularjs.org"
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/.bower.json b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/.bower.json
new file mode 100644
index 0000000..3ede443
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/.bower.json
@@ -0,0 +1,33 @@
+{
+ "name": "angular-ui-router",
+ "version": "0.2.15",
+ "main": "./release/angular-ui-router.js",
+ "dependencies": {
+ "angular": ">= 1.0.8"
+ },
+ "ignore": [
+ "**/.*",
+ "node_modules",
+ "bower_components",
+ "component.json",
+ "package.json",
+ "lib",
+ "config",
+ "sample",
+ "test",
+ "tests",
+ "ngdoc_assets",
+ "Gruntfile.js",
+ "files.js"
+ ],
+ "homepage": "https://github.com/angular-ui/ui-router",
+ "_release": "0.2.15",
+ "_resolution": {
+ "type": "version",
+ "tag": "0.2.15",
+ "commit": "805e69bae319e922e4d3265b7ef565058aaff850"
+ },
+ "_source": "git://github.com/angular-ui/ui-router.git",
+ "_target": "~0.2.15",
+ "_originalSource": "angular-ui-router"
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/CHANGELOG.md b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/CHANGELOG.md
new file mode 100644
index 0000000..23b59d3
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/CHANGELOG.md
@@ -0,0 +1,228 @@
+<a name="0.2.14"></a>
+### 0.2.14 (2015-04-23)
+
+
+#### Bug Fixes
+
+* **$StateRefDirective:** resolve missing support for svg anchor elements #1667 ([0149a7bb](https://github.com/angular-ui/ui-router/commit/0149a7bb38b7af99388a1ad7cc9909a7b7c4439d))
+* **$urlMatcherFactory:**
+ * regex params should respect case-sensitivity ([1e10519f](https://github.com/angular-ui/ui-router/commit/1e10519f3be6bbf0cefdcce623cd2ade06e649e5), closes [#1671](https://github.com/angular-ui/ui-router/issues/1671))
+ * unquote all dashes from array params ([06664d33](https://github.com/angular-ui/ui-router/commit/06664d330f882390655dcfa83e10276110d0d0fa))
+ * add Type.$normalize function ([b0c6aa23](https://github.com/angular-ui/ui-router/commit/b0c6aa2350fdd3ce8483144774adc12f5a72b7e9))
+ * make optional params regex grouping optional ([06f73794](https://github.com/angular-ui/ui-router/commit/06f737945e83e668d09cfc3bcffd04a500ff1963), closes [#1576](https://github.com/angular-ui/ui-router/issues/1576))
+* **$state:** allow about.*.** glob patterns ([e39b27a2](https://github.com/angular-ui/ui-router/commit/e39b27a2cb7d88525c446a041f9fbf1553202010))
+* **uiSref:**
+ * use Object's toString instead of Window's toString ([2aa7f4d1](https://github.com/angular-ui/ui-router/commit/2aa7f4d139dbd5b9fcc4afdcf2ab6642c87f5671))
+ * add absolute to allowed transition options ([ae1b3c4e](https://github.com/angular-ui/ui-router/commit/ae1b3c4eedc37983400d830895afb50457c63af4))
+* **uiSrefActive:** Apply active classes on lazy loaded states ([f0ddbe7b](https://github.com/angular-ui/ui-router/commit/f0ddbe7b4a91daf279c3b7d0cee732bb1f3be5b4))
+* **uiView:** add `$element` to locals for view controller ([db68914c](https://github.com/angular-ui/ui-router/commit/db68914cd6c821e7dec8155bd33142a3a97f5453))
+
+
+#### Features
+
+* **$state:**
+ * support URLs with #fragments ([3da0a170](https://github.com/angular-ui/ui-router/commit/3da0a17069e27598c0f9d9164e104dd5ce05cdc6))
+ * inject resolve params into controllerProvider ([b380c223](https://github.com/angular-ui/ui-router/commit/b380c223fe12e2fde7582c0d6b1ed7b15a23579b), closes [#1131](https://github.com/angular-ui/ui-router/issues/1131))
+ * added 'state' to state reload method (feat no.1612) - modiefied options.reload ([b8f04575](https://github.com/angular-ui/ui-router/commit/b8f04575a8557035c1858c4d5c8dbde3e1855aaa))
+ * broadcast $stateChangeCancel event when event.preventDefault() is called in $sta ([ecefb758](https://github.com/angular-ui/ui-router/commit/ecefb758cb445e41620b62a272aafa3638613d7a))
+* **$uiViewScroll:** change function to return promise ([c2a9a311](https://github.com/angular-ui/ui-router/commit/c2a9a311388bb212e5a2e820536d1d739f829ccd), closes [#1702](https://github.com/angular-ui/ui-router/issues/1702))
+* **uiSrefActive:** Added support for multiple nested uiSref directives ([b1844948](https://github.com/angular-ui/ui-router/commit/b18449481d152b50705abfce2493a444eb059fa5))
+
+
+<a name="0.2.13"></a>
+### 0.2.13 (2014-11-20)
+
+This release primarily fixes issues reported against 0.2.12
+
+#### Bug Fixes
+
+* **$state:** fix $state.includes/.is to apply param types before comparisions fix(uiSref): ma ([19715d15](https://github.com/angular-ui/ui-router/commit/19715d15e3cbfff724519e9febedd05b49c75baa), closes [#1513](https://github.com/angular-ui/ui-router/issues/1513))
+ * Avoid re-synchronizing from url after .transitionTo ([b267ecd3](https://github.com/angular-ui/ui-router/commit/b267ecd348e5c415233573ef95ebdbd051875f52), closes [#1573](https://github.com/angular-ui/ui-router/issues/1573))
+* **$urlMatcherFactory:**
+ * Built-in date type uses local time zone ([d726bedc](https://github.com/angular-ui/ui-router/commit/d726bedcbb5f70a5660addf43fd52ec730790293))
+ * make date type fn check .is before running ([aa94ce3b](https://github.com/angular-ui/ui-router/commit/aa94ce3b86632ad05301530a2213099da73a3dc0), closes [#1564](https://github.com/angular-ui/ui-router/issues/1564))
+ * early binding of array handler bypasses type resolution ([ada4bc27](https://github.com/angular-ui/ui-router/commit/ada4bc27df5eff3ba3ab0de94a09bd91b0f7a28c))
+ * add 'any' Type for non-encoding non-url params ([3bfd75ab](https://github.com/angular-ui/ui-router/commit/3bfd75ab445ee2f1dd55275465059ed116b10b27), closes [#1562](https://github.com/angular-ui/ui-router/issues/1562))
+ * fix encoding slashes in params ([0c983a08](https://github.com/angular-ui/ui-router/commit/0c983a08e2947f999683571477debd73038e95cf), closes [#1119](https://github.com/angular-ui/ui-router/issues/1119))
+ * fix mixed path/query params ordering problem ([a479fbd0](https://github.com/angular-ui/ui-router/commit/a479fbd0b8eb393a94320973e5b9a62d83912ee2), closes [#1543](https://github.com/angular-ui/ui-router/issues/1543))
+* **ArrayType:**
+ * specify empty array mapping corner case ([74aa6091](https://github.com/angular-ui/ui-router/commit/74aa60917e996b0b4e27bbb4eb88c3c03832021d), closes [#1511](https://github.com/angular-ui/ui-router/issues/1511))
+ * fix .equals for array types ([5e6783b7](https://github.com/angular-ui/ui-router/commit/5e6783b77af9a90ddff154f990b43dbb17eeda6e), closes [#1538](https://github.com/angular-ui/ui-router/issues/1538))
+* **Param:** fix default value shorthand declaration ([831d812a](https://github.com/angular-ui/ui-router/commit/831d812a524524c71f0ee1c9afaf0487a5a66230), closes [#1554](https://github.com/angular-ui/ui-router/issues/1554))
+* **common:** fixed the _.filter clone to not create sparse arrays ([750f5cf5](https://github.com/angular-ui/ui-router/commit/750f5cf5fd91f9ada96f39e50d39aceb2caf22b6), closes [#1563](https://github.com/angular-ui/ui-router/issues/1563))
+* **ie8:** fix calls to indexOf and filter ([dcb31b84](https://github.com/angular-ui/ui-router/commit/dcb31b843391b3e61dee4de13f368c109541813e), closes [#1556](https://github.com/angular-ui/ui-router/issues/1556))
+
+
+#### Features
+
+* add json parameter Type ([027f1fcf](https://github.com/angular-ui/ui-router/commit/027f1fcf9c0916cea651e88981345da6f9ff214a))
+
+
+<a name="0.2.12"></a>
+### 0.2.12 (2014-11-13)
+
+#### Bug Fixes
+
+* **$resolve:** use resolve fn result, not parent resolved value of same name ([67f5e00c](https://github.com/angular-ui/ui-router/commit/67f5e00cc9aa006ce3fe6cde9dff261c28eab70a), closes [#1317], [#1353])
+* **$state:**
+ * populate default params in .transitionTo. ([3f60fbe6](https://github.com/angular-ui/ui-router/commit/3f60fbe6d65ebeca8d97952c05aa1d269f1b7ba1), closes [#1396])
+ * reload() now reinvokes controllers ([73443420](https://github.com/angular-ui/ui-router/commit/7344342018847902594dc1fc62d30a5c30f01763), closes [#582])
+ * do not emit $viewContentLoading if notify: false ([74255feb](https://github.com/angular-ui/ui-router/commit/74255febdf48ae082a02ca1e735165f2c369a463), closes [#1387](https://github.com/angular-ui/ui-router/issues/1387))
+ * register states at config-time ([4533fe36](https://github.com/angular-ui/ui-router/commit/4533fe36e0ab2f0143edd854a4145deaa013915a))
+ * handle parent.name when parent is obj ([4533fe36](https://github.com/angular-ui/ui-router/commit/4533fe36e0ab2f0143edd854a4145deaa013915a))
+* **$urlMatcherFactory:**
+ * register types at config ([4533fe36](https://github.com/angular-ui/ui-router/commit/4533fe36e0ab2f0143edd854a4145deaa013915a), closes [#1476])
+ * made path params default value "" for backwards compat ([8f998e71](https://github.com/angular-ui/ui-router/commit/8f998e71e43a0b31293331c981f5db0f0097b8ba))
+ * Pre-replace certain param values for better mapping ([6374a3e2](https://github.com/angular-ui/ui-router/commit/6374a3e29ab932014a7c77d2e1ab884cc841a2e3))
+ * fixed ParamSet.$$keys() ordering ([9136fecb](https://github.com/angular-ui/ui-router/commit/9136fecbc2bfd4fda748a9914f0225a46c933860))
+ * empty string policy now respected in Param.value() ([db12c85c](https://github.com/angular-ui/ui-router/commit/db12c85c16f2d105415f9bbbdeb11863f64728e0))
+ * "string" type now encodes/decodes slashes ([3045e415](https://github.com/angular-ui/ui-router/commit/3045e41577a8b8b8afc6039f42adddf5f3c061ec), closes [#1119])
+ * allow arrays in both path and query params ([fdd2f2c1](https://github.com/angular-ui/ui-router/commit/fdd2f2c191c4a67c874fdb9ec9a34f8dde9ad180), closes [#1073], [#1045], [#1486], [#1394])
+ * typed params in search ([8d4cab69](https://github.com/angular-ui/ui-router/commit/8d4cab69dd67058e1a716892cc37b7d80a57037f), closes [#1488](https://github.com/angular-ui/ui-router/issues/1488))
+ * no longer generate unroutable urls ([cb9fd9d8](https://github.com/angular-ui/ui-router/commit/cb9fd9d8943cb26c7223f6990db29c82ae8740f8), closes [#1487](https://github.com/angular-ui/ui-router/issues/1487))
+ * handle optional parameter followed by required parameter in url format. ([efc72106](https://github.com/angular-ui/ui-router/commit/efc72106ddcc4774b48ea176a505ef9e95193b41))
+ * default to parameter string coersion. ([13a468a7](https://github.com/angular-ui/ui-router/commit/13a468a7d54c2fb0751b94c0c1841d580b71e6dc), closes [#1414](https://github.com/angular-ui/ui-router/issues/1414))
+ * concat respects strictMode/caseInsensitive ([dd72e103](https://github.com/angular-ui/ui-router/commit/dd72e103edb342d9cf802816fe127e1bbd68fd5f), closes [#1395])
+* **ui-sref:**
+ * Allow sref state options to take a scope object ([b5f7b596](https://github.com/angular-ui/ui-router/commit/b5f7b59692ce4933e2d63eb5df3f50a4ba68ccc0))
+ * replace raw href modification with attrs. ([08c96782](https://github.com/angular-ui/ui-router/commit/08c96782faf881b0c7ab00afc233ee6729548fa0))
+ * nagivate to state when url is "" fix($state.href): generate href for state with ([656b5aab](https://github.com/angular-ui/ui-router/commit/656b5aab906e5749db9b5a080c6a83b95f50fd91), closes [#1363](https://github.com/angular-ui/ui-router/issues/1363))
+ * Check that state is defined in isMatch() ([92aebc75](https://github.com/angular-ui/ui-router/commit/92aebc7520f88babdc6e266536086e07263514c3), closes [#1314](https://github.com/angular-ui/ui-router/issues/1314), [#1332](https://github.com/angular-ui/ui-router/issues/1332))
+* **uiView:**
+ * allow inteprolated ui-view names ([81f6a19a](https://github.com/angular-ui/ui-router/commit/81f6a19a432dac9198fd33243855bfd3b4fea8c0), closes [#1324](https://github.com/angular-ui/ui-router/issues/1324))
+ * Made anim work with angular 1.3 ([c3bb7ad9](https://github.com/angular-ui/ui-router/commit/c3bb7ad903da1e1f3c91019cfd255be8489ff4ef), closes [#1367](https://github.com/angular-ui/ui-router/issues/1367), [#1345](https://github.com/angular-ui/ui-router/issues/1345))
+* **urlRouter:** html5Mode accepts an object from angular v1.3.0-rc.3 ([7fea1e9d](https://github.com/angular-ui/ui-router/commit/7fea1e9d0d8c6e09cc6c895ecb93d4221e9adf48))
+* **stateFilters:** mark state filters as stateful. ([a00b353e](https://github.com/angular-ui/ui-router/commit/a00b353e3036f64a81245c4e7898646ba218f833), closes [#1479])
+* **ui-router:** re-add IE8 compatibility for map/filter/keys ([8ce69d9f](https://github.com/angular-ui/ui-router/commit/8ce69d9f7c886888ab53eca7e53536f36b428aae), closes [#1518], [#1383])
+* **package:** point 'main' to a valid filename ([ac903350](https://github.com/angular-ui/ui-router/commit/ac9033501debb63364539d91fbf3a0cba4579f8e))
+* **travis:** make CI build faster ([0531de05](https://github.com/angular-ui/ui-router/commit/0531de052e414a8d839fbb4e7635e923e94865b3))
+
+
+#### Features
+
+##### Default and Typed params
+
+This release includes a lot of bug fixes around default/optional and typed parameters. As such, 0.2.12 is the first release where we recommend those features be used.
+
+* **$state:**
+ * add state params validation ([b1379e6a](https://github.com/angular-ui/ui-router/commit/b1379e6a4d38f7ed7436e05873932d7c279af578), closes [#1433](https://github.com/angular-ui/ui-router/issues/1433))
+ * is/includes/get work on relative stateOrName ([232e94b3](https://github.com/angular-ui/ui-router/commit/232e94b3c2ca2c764bb9510046e4b61690c87852))
+ * .reload() returns state transition promise ([639e0565](https://github.com/angular-ui/ui-router/commit/639e0565dece9d5544cc93b3eee6e11c99bd7373))
+* **$templateFactory:** request templateURL as text/html ([ccd60769](https://github.com/angular-ui/ui-router/commit/ccd6076904a4b801d77b47f6e2de4c06ce9962f8), closes [#1287])
+* **$urlMatcherFactory:** Made a Params and ParamSet class ([0cc1e6cc](https://github.com/angular-ui/ui-router/commit/0cc1e6cc461a4640618e2bb594566551c54834e2))
+
+
+
+<a name="0.2.11"></a>
+### 0.2.11 (2014-08-26)
+
+
+#### Bug Fixes
+
+* **$resolve:** Resolves only inherit from immediate parent fixes #702 ([df34e20c](https://github.com/angular-ui/ui-router/commit/df34e20c576299e7a3c8bd4ebc68d42341c0ace9))
+* **$state:**
+ * change $state.href default options.inherit to true ([deea695f](https://github.com/angular-ui/ui-router/commit/deea695f5cacc55de351ab985144fd233c02a769))
+ * sanity-check state lookups ([456fd5ae](https://github.com/angular-ui/ui-router/commit/456fd5aec9ea507518927bfabd62b4afad4cf714), closes [#980](https://github.com/angular-ui/ui-router/issues/980))
+ * didn't comply to inherit parameter ([09836781](https://github.com/angular-ui/ui-router/commit/09836781f126c1c485b06551eb9cfd4fa0f45c35))
+ * allow view content loading broadcast ([7b78edee](https://github.com/angular-ui/ui-router/commit/7b78edeeb52a74abf4d3f00f79534033d5a08d1a))
+* **$urlMatcherFactory:**
+ * detect injected functions ([91f75ae6](https://github.com/angular-ui/ui-router/commit/91f75ae66c4d129f6f69e53bd547594e9661f5d5))
+ * syntax ([1ebed370](https://github.com/angular-ui/ui-router/commit/1ebed37069bae8614d41541d56521f5c45f703f3))
+* **UrlMatcher:**
+ * query param function defaults ([f9c20530](https://github.com/angular-ui/ui-router/commit/f9c205304f10d8a4ebe7efe9025e642016479a51))
+ * don't decode default values ([63607bdb](https://github.com/angular-ui/ui-router/commit/63607bdbbcb432d3fb37856a1cb3da0cd496804e))
+* **travis:** update Node version to fix build ([d6b95ef2](https://github.com/angular-ui/ui-router/commit/d6b95ef23d9dacb4eba08897f5190a0bcddb3a48))
+* **uiSref:**
+ * Generate an href for states with a blank url. closes #1293 ([691745b1](https://github.com/angular-ui/ui-router/commit/691745b12fa05d3700dd28f0c8d25f8a105074ad))
+ * should inherit params by default ([b973dad1](https://github.com/angular-ui/ui-router/commit/b973dad155ad09a7975e1476bd096f7b2c758eeb))
+ * cancel transition if preventDefault() has been called ([2e6d9167](https://github.com/angular-ui/ui-router/commit/2e6d9167d3afbfbca6427e53e012f94fb5fb8022))
+* **uiView:** Fixed infinite loop when is called .go() from a controller. ([e13988b8](https://github.com/angular-ui/ui-router/commit/e13988b8cd6231d75c78876ee9d012cc87f4a8d9), closes [#1194](https://github.com/angular-ui/ui-router/issues/1194))
+* **docs:**
+ * Fixed link to milestones ([6c0ae500](https://github.com/angular-ui/ui-router/commit/6c0ae500cc238ea9fc95adcc15415c55fc9e1f33))
+ * fix bug in decorator example ([4bd00af5](https://github.com/angular-ui/ui-router/commit/4bd00af50b8b88a49d1545a76290731cb8e0feb1))
+ * Removed an incorrect semi-colon ([af97cef8](https://github.com/angular-ui/ui-router/commit/af97cef8b967f2e32177e539ef41450dca131a7d))
+ * Explain return value of rule as function ([5e887890](https://github.com/angular-ui/ui-router/commit/5e8878900a6ffe59a81aed531a3925e34a297377))
+
+
+#### Features
+
+* **$state:**
+ * allow parameters to pass unharmed ([8939d057](https://github.com/angular-ui/ui-router/commit/8939d0572ab1316e458ef016317ecff53131a822))
+ * **BREAKING CHANGE**: state parameters are no longer automatically coerced to strings, and unspecified parameter values are now set to undefined rather than null.
+ * allow prevent syncUrl on failure ([753060b9](https://github.com/angular-ui/ui-router/commit/753060b910d5d2da600a6fa0757976e401c33172))
+* **typescript:** Add typescript definitions for component builds ([521ceb3f](https://github.com/angular-ui/ui-router/commit/521ceb3fd7850646422f411921e21ce5e7d82e0f))
+* **uiSref:** extend syntax for ui-sref ([71cad3d6](https://github.com/angular-ui/ui-router/commit/71cad3d636508b5a9fe004775ad1f1adc0c80c3e))
+* **uiSrefActive:**
+ * Also activate for child states. ([bf163ad6](https://github.com/angular-ui/ui-router/commit/bf163ad6ce176ce28792696c8302d7cdf5c05a01), closes [#818](https://github.com/angular-ui/ui-router/issues/818))
+ * **BREAKING CHANGE** Since ui-sref-active now activates even when child states are active you may need to swap out your ui-sref-active with ui-sref-active-eq, thought typically we think devs want the auto inheritance.
+
+ * uiSrefActiveEq: new directive with old ui-sref-active behavior
+* **$urlRouter:**
+ * defer URL change interception ([c72d8ce1](https://github.com/angular-ui/ui-router/commit/c72d8ce11916d0ac22c81b409c9e61d7048554d7))
+ * force URLs to have valid params ([d48505cd](https://github.com/angular-ui/ui-router/commit/d48505cd328d83e39d5706e085ba319715f999a6))
+ * abstract $location handling ([08b4636b](https://github.com/angular-ui/ui-router/commit/08b4636b294611f08db35f00641eb5211686fb50))
+* **$urlMatcherFactory:**
+ * fail on bad parameters ([d8f124c1](https://github.com/angular-ui/ui-router/commit/d8f124c10d00c7e5dde88c602d966db261aea221))
+ * date type support ([b7f074ff](https://github.com/angular-ui/ui-router/commit/b7f074ff65ca150a3cdbda4d5ad6cb17107300eb))
+ * implement type support ([450b1f0e](https://github.com/angular-ui/ui-router/commit/450b1f0e8e03c738174ff967f688b9a6373290f4))
+* **UrlMatcher:**
+ * handle query string arrays ([9cf764ef](https://github.com/angular-ui/ui-router/commit/9cf764efab45fa9309368688d535ddf6e96d6449), closes [#373](https://github.com/angular-ui/ui-router/issues/373))
+ * injectable functions as defaults ([00966ecd](https://github.com/angular-ui/ui-router/commit/00966ecd91fb745846039160cab707bfca8b3bec))
+ * default values & type decoding for query params ([a472b301](https://github.com/angular-ui/ui-router/commit/a472b301389fbe84d1c1fa9f24852b492a569d11))
+ * allow shorthand definitions ([5b724304](https://github.com/angular-ui/ui-router/commit/5b7243049793505e44b6608ea09878c37c95b1f5))
+ * validates whole interface ([32b27db1](https://github.com/angular-ui/ui-router/commit/32b27db173722e9194ef1d5c0ea7d93f25a98d11))
+ * implement non-strict matching ([a3e21366](https://github.com/angular-ui/ui-router/commit/a3e21366bee0475c9795a1ec76f70eec41c5b4e3))
+ * add per-param config support ([07b3029f](https://github.com/angular-ui/ui-router/commit/07b3029f4d409cf955780113df92e36401b47580))
+ * **BREAKING CHANGE**: the `params` option in state configurations must now be an object keyed by parameter name.
+
+### 0.2.10 (2014-03-12)
+
+
+#### Bug Fixes
+
+* **$state:** use $browser.baseHref() when generating urls with .href() ([cbcc8488](https://github.com/angular-ui/ui-router/commit/cbcc84887d6b6d35258adabb97c714cd9c1e272d))
+* **bower.json:** JS files should not be ignored ([ccdab193](https://github.com/angular-ui/ui-router/commit/ccdab193315f304eb3be5f5b97c47a926c79263e))
+* **dev:** karma:background task is missing, can't run grunt:dev. ([d9f7b898](https://github.com/angular-ui/ui-router/commit/d9f7b898e8e3abb8c846b0faa16a382913d7b22b))
+* **sample:** Contacts menu button not staying active when navigating to detail states. Need t ([2fcb8443](https://github.com/angular-ui/ui-router/commit/2fcb84437cb43ade12682a92b764f13cac77dfe7))
+* **uiSref:** support mock-clicks/events with no data ([717d3ff7](https://github.com/angular-ui/ui-router/commit/717d3ff7d0ba72d239892dee562b401cdf90e418))
+* **uiView:**
+ * Do NOT autoscroll when autoscroll attr is missing ([affe5bd7](https://github.com/angular-ui/ui-router/commit/affe5bd785cdc3f02b7a9f64a52e3900386ec3a0), closes [#807](https://github.com/angular-ui/ui-router/issues/807))
+ * Refactoring uiView directive to copy ngView logic ([548fab6a](https://github.com/angular-ui/ui-router/commit/548fab6ab9debc9904c5865c8bc68b4fc3271dd0), closes [#857](https://github.com/angular-ui/ui-router/issues/857), [#552](https://github.com/angular-ui/ui-router/issues/552))
+
+
+#### Features
+
+* **$state:** includes() allows glob patterns for state matching. ([2d5f6b37](https://github.com/angular-ui/ui-router/commit/2d5f6b37191a3135f4a6d9e8f344c54edcdc065b))
+* **UrlMatcher:** Add support for case insensitive url matching ([642d5247](https://github.com/angular-ui/ui-router/commit/642d524799f604811e680331002feec7199a1fb5))
+* **uiSref:** add support for transition options ([2ed7a728](https://github.com/angular-ui/ui-router/commit/2ed7a728cee6854b38501fbc1df6139d3de5b28a))
+* **uiView:** add controllerAs config with function ([1ee7334a](https://github.com/angular-ui/ui-router/commit/1ee7334a73efeccc9b95340e315cdfd59944762d))
+
+
+### 0.2.9 (2014-01-17)
+
+
+This release is identical to 0.2.8. 0.2.8 was re-tagged in git to fix a problem with bower.
+
+
+### 0.2.8 (2014-01-16)
+
+
+#### Bug Fixes
+
+* **$state:** allow null to be passed as 'params' param ([094dc30e](https://github.com/angular-ui/ui-router/commit/094dc30e883e1bd14e50a475553bafeaade3b178))
+* **$state.go:** param inheritance shouldn't inherit from siblings ([aea872e0](https://github.com/angular-ui/ui-router/commit/aea872e0b983cb433436ce5875df10c838fccedb))
+* **bower.json:** fixes bower.json ([eed3cc4d](https://github.com/angular-ui/ui-router/commit/eed3cc4d4dfef1d3ef84b9fd063127538ebf59d3))
+* **uiSrefActive:** annotate controller injection ([85921422](https://github.com/angular-ui/ui-router/commit/85921422ff7fb0effed358136426d616cce3d583), closes [#671](https://github.com/angular-ui/ui-router/issues/671))
+* **uiView:**
+ * autoscroll tests pass on 1.2.4 & 1.1.5 ([86eacac0](https://github.com/angular-ui/ui-router/commit/86eacac09ca5e9000bd3b9c7ba6e2cc95d883a3a))
+ * don't animate initial load ([83b6634d](https://github.com/angular-ui/ui-router/commit/83b6634d27942ca74766b2b1244a7fc52c5643d9))
+ * test pass against 1.0.8 and 1.2.4 ([a402415a](https://github.com/angular-ui/ui-router/commit/a402415a2a28b360c43b9fe8f4f54c540f6c33de))
+ * it should autoscroll when expr is missing. ([8bb9e27a](https://github.com/angular-ui/ui-router/commit/8bb9e27a2986725f45daf44c4c9f846385095aff))
+
+
+#### Features
+
+* **uiSref:** add target attribute behaviour ([c12bf9a5](https://github.com/angular-ui/ui-router/commit/c12bf9a520d30d70294e3d82de7661900f8e394e))
+* **uiView:**
+ * merge autoscroll expression test. ([b89e0f87](https://github.com/angular-ui/ui-router/commit/b89e0f871d5cc35c10925ede986c10684d5c9252))
+ * cache and test autoscroll expression ([ee262282](https://github.com/angular-ui/ui-router/commit/ee2622828c2ce83807f006a459ac4e11406d9258))
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/CONTRIBUTING.md b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/CONTRIBUTING.md
new file mode 100644
index 0000000..63829a5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/CONTRIBUTING.md
@@ -0,0 +1,65 @@
+
+# Report an Issue
+
+Help us make UI-Router better! If you think you might have found a bug, or some other weirdness, start by making sure
+it hasn't already been reported. You can [search through existing issues](https://github.com/angular-ui/ui-router/search?q=wat%3F&type=Issues)
+to see if someone's reported one similar to yours.
+
+If not, then [create a plunkr](http://bit.ly/UIR-Plunk) that demonstrates the problem (try to use as little code
+as possible: the more minimalist, the faster we can debug it).
+
+Next, [create a new issue](https://github.com/angular-ui/ui-router/issues/new) that briefly explains the problem,
+and provides a bit of background as to the circumstances that triggered it. Don't forget to include the link to
+that plunkr you created!
+
+**Note**: If you're unsure how a feature is used, or are encountering some unexpected behavior that you aren't sure
+is a bug, it's best to talk it out on
+[StackOverflow](http://stackoverflow.com/questions/ask?tags=angularjs,angular-ui-router) before reporting it. This
+keeps development streamlined, and helps us focus on building great software.
+
+
+Issues only! |
+-------------|
+Please keep in mind that the issue tracker is for *issues*. Please do *not* post an issue if you need help or support. Instead, see one of the above-mentioned forums or [IRC](irc://irc.freenode.net/#angularjs). |
+
+####Purple Labels
+A purple label means that **you** need to take some further action.
+ - ![Not Actionable - Need Info](http://angular-ui.github.io/ui-router/images/notactionable.png): Your issue is not specific enough, or there is no clear action that we can take. Please clarify and refine your issue.
+ - ![Plunkr Please](http://angular-ui.github.io/ui-router/images/plunkrplease.png): Please [create a plunkr](http://bit.ly/UIR-Plunk)
+ - ![StackOverflow](http://angular-ui.github.io/ui-router/images/stackoverflow.png): We suspect your issue is really a help request, or could be answered by the community. Please ask your question on [StackOverflow](http://stackoverflow.com/questions/ask?tags=angularjs,angular-ui-router). If you determine that is an actual issue, please explain why.
+
+If your issue gets labeled with purple label, no further action will be taken until you respond to the label appropriately.
+
+# Contribute
+
+**(1)** See the **[Developing](#developing)** section below, to get the development version of UI-Router up and running on your local machine.
+
+**(2)** Check out the [roadmap](https://github.com/angular-ui/ui-router/milestones) to see where the project is headed, and if your feature idea fits with where we're headed.
+
+**(3)** If you're not sure, [open an RFC](https://github.com/angular-ui/ui-router/issues/new?title=RFC:%20My%20idea) to get some feedback on your idea.
+
+**(4)** Finally, commit some code and open a pull request. Code & commits should abide by the following rules:
+
+- *Always* have test coverage for new features (or regression tests for bug fixes), and *never* break existing tests
+- Commits should represent one logical change each; if a feature goes through multiple iterations, squash your commits down to one
+- Make sure to follow the [Angular commit message format](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md#commit-message-format) so your change will appear in the changelog of the next release.
+- Changes should always respect the coding style of the project
+
+
+
+# Developing
+
+UI-Router uses <code>grunt >= 0.4.x</code>. Make sure to upgrade your environment and read the
+[Migration Guide](http://gruntjs.com/upgrading-from-0.3-to-0.4).
+
+Dependencies for building from source and running tests:
+
+* [grunt-cli](https://github.com/gruntjs/grunt-cli) - run: `$ npm install -g grunt-cli`
+* Then, install the development dependencies by running `$ npm install` from the project directory
+
+There are a number of targets in the gruntfile that are used to generating different builds:
+
+* `grunt`: Perform a normal build, runs jshint and karma tests
+* `grunt build`: Perform a normal build
+* `grunt dist`: Perform a clean build and generate documentation
+* `grunt dev`: Run dev server (sample app) and watch for changes, builds and runs karma tests on changes.
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/LICENSE b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/LICENSE
new file mode 100644
index 0000000..6413b09
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/LICENSE
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2013-2015 The AngularUI Team, Karsten Sperling
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/README.md b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/README.md
new file mode 100644
index 0000000..1d8bcd6
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/README.md
@@ -0,0 +1,245 @@
+# AngularUI Router [![Build Status](https://travis-ci.org/angular-ui/ui-router.svg?branch=master)](https://travis-ci.org/angular-ui/ui-router)
+
+#### The de-facto solution to flexible routing with nested views
+---
+**[Download 0.2.15](http://angular-ui.github.io/ui-router/release/angular-ui-router.js)** (or **[Minified](http://angular-ui.github.io/ui-router/release/angular-ui-router.min.js)**) **|**
+**[Guide](https://github.com/angular-ui/ui-router/wiki) |**
+**[API](http://angular-ui.github.io/ui-router/site) |**
+**[Sample](http://angular-ui.github.com/ui-router/sample/) ([Src](https://github.com/angular-ui/ui-router/tree/gh-pages/sample)) |**
+**[FAQ](https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions) |**
+**[Resources](#resources) |**
+**[Report an Issue](https://github.com/angular-ui/ui-router/blob/master/CONTRIBUTING.md#report-an-issue) |**
+**[Contribute](https://github.com/angular-ui/ui-router/blob/master/CONTRIBUTING.md#contribute) |**
+**[Help!](http://stackoverflow.com/questions/ask?tags=angularjs,angular-ui-router) |**
+**[Discuss](https://groups.google.com/forum/#!categories/angular-ui/router)**
+
+---
+
+AngularUI Router is a routing framework for [AngularJS](http://angularjs.org), which allows you to organize the
+parts of your interface into a [*state machine*](https://en.wikipedia.org/wiki/Finite-state_machine). Unlike the
+[`$route` service](http://docs.angularjs.org/api/ngRoute.$route) in the Angular ngRoute module, which is organized around URL
+routes, UI-Router is organized around [*states*](https://github.com/angular-ui/ui-router/wiki),
+which may optionally have routes, as well as other behavior, attached.
+
+States are bound to *named*, *nested* and *parallel views*, allowing you to powerfully manage your application's interface.
+
+Check out the sample app: http://angular-ui.github.io/ui-router/sample/
+
+-
+**Note:** *UI-Router is under active development. As such, while this library is well-tested, the API may change. Consider using it in production applications only if you're comfortable following a changelog and updating your usage accordingly.*
+
+
+## Get Started
+
+**(1)** Get UI-Router in one of the following ways:
+ - clone & [build](CONTRIBUTING.md#developing) this repository
+ - [download the release](http://angular-ui.github.io/ui-router/release/angular-ui-router.js) (or [minified](http://angular-ui.github.io/ui-router/release/angular-ui-router.min.js))
+ - [link to cdn](http://cdnjs.com/libraries/angular-ui-router)
+ - via **[jspm](http://jspm.io/)**: by running `$ jspm install angular-ui-router` from your console
+ - or via **[npm](https://www.npmjs.org/)**: by running `$ npm install angular-ui-router` from your console
+ - or via **[Bower](http://bower.io/)**: by running `$ bower install angular-ui-router` from your console
+ - or via **[Component](https://github.com/component/component)**: by running `$ component install angular-ui/ui-router` from your console
+
+**(2)** Include `angular-ui-router.js` (or `angular-ui-router.min.js`) in your `index.html`, after including Angular itself (For Component users: ignore this step)
+
+**(3)** Add `'ui.router'` to your main module's list of dependencies (For Component users: replace `'ui.router'` with `require('angular-ui-router')`)
+
+When you're done, your setup should look similar to the following:
+
+>
+```html
+<!doctype html>
+<html ng-app="myApp">
+<head>
+ <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
+ <script src="js/angular-ui-router.min.js"></script>
+ <script>
+ var myApp = angular.module('myApp', ['ui.router']);
+ // For Component users, it should look like this:
+ // var myApp = angular.module('myApp', [require('angular-ui-router')]);
+ </script>
+ ...
+</head>
+<body>
+ ...
+</body>
+</html>
+```
+
+### [Nested States & Views](http://plnkr.co/edit/u18KQc?p=preview)
+
+The majority of UI-Router's power is in its ability to nest states & views.
+
+**(1)** First, follow the [setup](#get-started) instructions detailed above.
+
+**(2)** Then, add a [`ui-view` directive](https://github.com/angular-ui/ui-router/wiki/Quick-Reference#ui-view) to the `<body />` of your app.
+
+>
+```html
+<!-- index.html -->
+<body>
+ <div ui-view></div>
+ <!-- We'll also add some navigation: -->
+ <a ui-sref="state1">State 1</a>
+ <a ui-sref="state2">State 2</a>
+</body>
+```
+
+**(3)** You'll notice we also added some links with [`ui-sref` directives](https://github.com/angular-ui/ui-router/wiki/Quick-Reference#ui-sref). In addition to managing state transitions, this directive auto-generates the `href` attribute of the `<a />` element it's attached to, if the corresponding state has a URL. Next we'll add some templates. These will plug into the `ui-view` within `index.html`. Notice that they have their own `ui-view` as well! That is the key to nesting states and views.
+
+>
+```html
+<!-- partials/state1.html -->
+<h1>State 1</h1>
+<hr/>
+<a ui-sref="state1.list">Show List</a>
+<div ui-view></div>
+```
+```html
+<!-- partials/state2.html -->
+<h1>State 2</h1>
+<hr/>
+<a ui-sref="state2.list">Show List</a>
+<div ui-view></div>
+```
+
+**(4)** Next, we'll add some child templates. *These* will get plugged into the `ui-view` of their parent state templates.
+
+>
+```html
+<!-- partials/state1.list.html -->
+<h3>List of State 1 Items</h3>
+<ul>
+ <li ng-repeat="item in items">{{ item }}</li>
+</ul>
+```
+
+>
+```html
+<!-- partials/state2.list.html -->
+<h3>List of State 2 Things</h3>
+<ul>
+ <li ng-repeat="thing in things">{{ thing }}</li>
+</ul>
+```
+
+**(5)** Finally, we'll wire it all up with `$stateProvider`. Set up your states in the module config, as in the following:
+
+
+>
+```javascript
+myApp.config(function($stateProvider, $urlRouterProvider) {
+ //
+ // For any unmatched url, redirect to /state1
+ $urlRouterProvider.otherwise("/state1");
+ //
+ // Now set up the states
+ $stateProvider
+ .state('state1', {
+ url: "/state1",
+ templateUrl: "partials/state1.html"
+ })
+ .state('state1.list', {
+ url: "/list",
+ templateUrl: "partials/state1.list.html",
+ controller: function($scope) {
+ $scope.items = ["A", "List", "Of", "Items"];
+ }
+ })
+ .state('state2', {
+ url: "/state2",
+ templateUrl: "partials/state2.html"
+ })
+ .state('state2.list', {
+ url: "/list",
+ templateUrl: "partials/state2.list.html",
+ controller: function($scope) {
+ $scope.things = ["A", "Set", "Of", "Things"];
+ }
+ });
+});
+```
+
+**(6)** See this quick start example in action.
+>**[Go to Quick Start Plunker for Nested States & Views](http://plnkr.co/edit/u18KQc?p=preview)**
+
+**(7)** This only scratches the surface
+>**[Dive Deeper!](https://github.com/angular-ui/ui-router/wiki)**
+
+
+### [Multiple & Named Views](http://plnkr.co/edit/SDOcGS?p=preview)
+
+Another great feature is the ability to have multiple `ui-view`s view per template.
+
+**Pro Tip:** *While multiple parallel views are a powerful feature, you'll often be able to manage your
+interfaces more effectively by nesting your views, and pairing those views with nested states.*
+
+**(1)** Follow the [setup](#get-started) instructions detailed above.
+
+**(2)** Add one or more `ui-view` to your app, give them names.
+>
+```html
+<!-- index.html -->
+<body>
+ <div ui-view="viewA"></div>
+ <div ui-view="viewB"></div>
+ <!-- Also a way to navigate -->
+ <a ui-sref="route1">Route 1</a>
+ <a ui-sref="route2">Route 2</a>
+</body>
+```
+
+**(3)** Set up your states in the module config:
+>
+```javascript
+myApp.config(function($stateProvider) {
+ $stateProvider
+ .state('index', {
+ url: "",
+ views: {
+ "viewA": { template: "index.viewA" },
+ "viewB": { template: "index.viewB" }
+ }
+ })
+ .state('route1', {
+ url: "/route1",
+ views: {
+ "viewA": { template: "route1.viewA" },
+ "viewB": { template: "route1.viewB" }
+ }
+ })
+ .state('route2', {
+ url: "/route2",
+ views: {
+ "viewA": { template: "route2.viewA" },
+ "viewB": { template: "route2.viewB" }
+ }
+ })
+});
+```
+
+**(4)** See this quick start example in action.
+>**[Go to Quick Start Plunker for Multiple & Named Views](http://plnkr.co/edit/SDOcGS?p=preview)**
+
+
+## Resources
+
+* [In-Depth Guide](https://github.com/angular-ui/ui-router/wiki)
+* [API Reference](http://angular-ui.github.io/ui-router/site)
+* [Sample App](http://angular-ui.github.com/ui-router/sample/) ([Source](https://github.com/angular-ui/ui-router/tree/gh-pages/sample))
+* [FAQ](https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions)
+* [Slides comparing ngRoute to ui-router](http://slid.es/timkindberg/ui-router#/)
+* [UI-Router Extras / Addons](http://christopherthielen.github.io/ui-router-extras/#/home) (@christopherthielen)
+
+### Videos
+
+* [Introduction Video](https://egghead.io/lessons/angularjs-introduction-ui-router) (egghead.io)
+* [Tim Kindberg on Angular UI-Router](https://www.youtube.com/watch?v=lBqiZSemrqg)
+* [Activating States](https://egghead.io/lessons/angularjs-ui-router-activating-states) (egghead.io)
+* [Learn Angular.js using UI-Router](http://youtu.be/QETUuZ27N0w) (LearnCode.academy)
+
+
+
+## Reporting issues and Contributing
+
+Please read our [Contributor guidelines](CONTRIBUTING.md) before reporting an issue or creating a pull request.
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/api/angular-ui-router.d.ts b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/api/angular-ui-router.d.ts
new file mode 100644
index 0000000..55c5d5e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/api/angular-ui-router.d.ts
@@ -0,0 +1,126 @@
+// Type definitions for Angular JS 1.1.5+ (ui.router module)
+// Project: https://github.com/angular-ui/ui-router
+// Definitions by: Michel Salib <https://github.com/michelsalib>
+// Definitions: https://github.com/borisyankov/DefinitelyTyped
+
+declare module ng.ui {
+
+ interface IState {
+ name?: string;
+ template?: string;
+ templateUrl?: any; // string || () => string
+ templateProvider?: any; // () => string || IPromise<string>
+ controller?: any;
+ controllerAs?: string;
+ controllerProvider?: any;
+ resolve?: {};
+ url?: string;
+ params?: any;
+ views?: {};
+ abstract?: boolean;
+ onEnter?: (...args: any[]) => void;
+ onExit?: (...args: any[]) => void;
+ data?: any;
+ reloadOnSearch?: boolean;
+ }
+
+ interface ITypedState<T> extends IState {
+ data?: T;
+ }
+
+ interface IStateProvider extends IServiceProvider {
+ state(name: string, config: IState): IStateProvider;
+ state(config: IState): IStateProvider;
+ decorator(name?: string, decorator?: (state: IState, parent: Function) => any): any;
+ }
+
+ interface IUrlMatcher {
+ concat(pattern: string): IUrlMatcher;
+ exec(path: string, searchParams: {}): {};
+ parameters(): string[];
+ format(values: {}): string;
+ }
+
+ interface IUrlMatcherFactory {
+ compile(pattern: string): IUrlMatcher;
+ isMatcher(o: any): boolean;
+ }
+
+ interface IUrlRouterProvider extends IServiceProvider {
+ when(whenPath: RegExp, handler: Function): IUrlRouterProvider;
+ when(whenPath: RegExp, handler: any[]): IUrlRouterProvider;
+ when(whenPath: RegExp, toPath: string): IUrlRouterProvider;
+ when(whenPath: IUrlMatcher, hanlder: Function): IUrlRouterProvider;
+ when(whenPath: IUrlMatcher, handler: any[]): IUrlRouterProvider;
+ when(whenPath: IUrlMatcher, toPath: string): IUrlRouterProvider;
+ when(whenPath: string, handler: Function): IUrlRouterProvider;
+ when(whenPath: string, handler: any[]): IUrlRouterProvider;
+ when(whenPath: string, toPath: string): IUrlRouterProvider;
+ otherwise(handler: Function): IUrlRouterProvider;
+ otherwise(handler: any[]): IUrlRouterProvider;
+ otherwise(path: string): IUrlRouterProvider;
+ rule(handler: Function): IUrlRouterProvider;
+ rule(handler: any[]): IUrlRouterProvider;
+ }
+
+ interface IStateOptions {
+ location?: any;
+ inherit?: boolean;
+ relative?: IState;
+ notify?: boolean;
+ reload?: boolean;
+ }
+
+ interface IHrefOptions {
+ lossy?: boolean;
+ inherit?: boolean;
+ relative?: IState;
+ absolute?: boolean;
+ }
+
+ interface IStateService {
+ go(to: string, params?: {}, options?: IStateOptions): IPromise<any>;
+ transitionTo(state: string, params?: {}, updateLocation?: boolean): void;
+ transitionTo(state: string, params?: {}, options?: IStateOptions): void;
+ includes(state: string, params?: {}): boolean;
+ is(state:string, params?: {}): boolean;
+ is(state: IState, params?: {}): boolean;
+ href(state: IState, params?: {}, options?: IHrefOptions): string;
+ href(state: string, params?: {}, options?: IHrefOptions): string;
+ get(state: string): IState;
+ get(): IState[];
+ current: IState;
+ params: any;
+ reload(): void;
+ }
+
+ interface IStateParamsService {
+ [key: string]: any;
+ }
+
+ interface IStateParams {
+ [key: string]: any;
+ }
+
+ interface IUrlRouterService {
+ /*
+ * Triggers an update; the same update that happens when the address bar
+ * url changes, aka $locationChangeSuccess.
+ *
+ * This method is useful when you need to use preventDefault() on the
+ * $locationChangeSuccess event, perform some custom logic (route protection,
+ * auth, config, redirection, etc) and then finally proceed with the transition
+ * by calling $urlRouter.sync().
+ *
+ */
+ sync(): void;
+ }
+
+ interface IUiViewScrollProvider {
+ /*
+ * Reverts back to using the core $anchorScroll service for scrolling
+ * based on the url anchor.
+ */
+ useAnchorScroll(): void;
+ }
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/bower.json b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/bower.json
new file mode 100644
index 0000000..f4f08fa
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/bower.json
@@ -0,0 +1,23 @@
+{
+ "name": "angular-ui-router",
+ "version": "0.2.15",
+ "main": "./release/angular-ui-router.js",
+ "dependencies": {
+ "angular": ">= 1.0.8"
+ },
+ "ignore": [
+ "**/.*",
+ "node_modules",
+ "bower_components",
+ "component.json",
+ "package.json",
+ "lib",
+ "config",
+ "sample",
+ "test",
+ "tests",
+ "ngdoc_assets",
+ "Gruntfile.js",
+ "files.js"
+ ]
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/release/angular-ui-router.js b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/release/angular-ui-router.js
new file mode 100644
index 0000000..57c62cc
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/release/angular-ui-router.js
@@ -0,0 +1,4370 @@
+/**
+ * State-based routing for AngularJS
+ * @version v0.2.15
+ * @link http://angular-ui.github.com/
+ * @license MIT License, http://www.opensource.org/licenses/MIT
+ */
+
+/* commonjs package manager support (eg componentjs) */
+if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
+ module.exports = 'ui.router';
+}
+
+(function (window, angular, undefined) {
+/*jshint globalstrict:true*/
+/*global angular:false*/
+'use strict';
+
+var isDefined = angular.isDefined,
+ isFunction = angular.isFunction,
+ isString = angular.isString,
+ isObject = angular.isObject,
+ isArray = angular.isArray,
+ forEach = angular.forEach,
+ extend = angular.extend,
+ copy = angular.copy;
+
+function inherit(parent, extra) {
+ return extend(new (extend(function() {}, { prototype: parent }))(), extra);
+}
+
+function merge(dst) {
+ forEach(arguments, function(obj) {
+ if (obj !== dst) {
+ forEach(obj, function(value, key) {
+ if (!dst.hasOwnProperty(key)) dst[key] = value;
+ });
+ }
+ });
+ return dst;
+}
+
+/**
+ * Finds the common ancestor path between two states.
+ *
+ * @param {Object} first The first state.
+ * @param {Object} second The second state.
+ * @return {Array} Returns an array of state names in descending order, not including the root.
+ */
+function ancestors(first, second) {
+ var path = [];
+
+ for (var n in first.path) {
+ if (first.path[n] !== second.path[n]) break;
+ path.push(first.path[n]);
+ }
+ return path;
+}
+
+/**
+ * IE8-safe wrapper for `Object.keys()`.
+ *
+ * @param {Object} object A JavaScript object.
+ * @return {Array} Returns the keys of the object as an array.
+ */
+function objectKeys(object) {
+ if (Object.keys) {
+ return Object.keys(object);
+ }
+ var result = [];
+
+ forEach(object, function(val, key) {
+ result.push(key);
+ });
+ return result;
+}
+
+/**
+ * IE8-safe wrapper for `Array.prototype.indexOf()`.
+ *
+ * @param {Array} array A JavaScript array.
+ * @param {*} value A value to search the array for.
+ * @return {Number} Returns the array index value of `value`, or `-1` if not present.
+ */
+function indexOf(array, value) {
+ if (Array.prototype.indexOf) {
+ return array.indexOf(value, Number(arguments[2]) || 0);
+ }
+ var len = array.length >>> 0, from = Number(arguments[2]) || 0;
+ from = (from < 0) ? Math.ceil(from) : Math.floor(from);
+
+ if (from < 0) from += len;
+
+ for (; from < len; from++) {
+ if (from in array && array[from] === value) return from;
+ }
+ return -1;
+}
+
+/**
+ * Merges a set of parameters with all parameters inherited between the common parents of the
+ * current state and a given destination state.
+ *
+ * @param {Object} currentParams The value of the current state parameters ($stateParams).
+ * @param {Object} newParams The set of parameters which will be composited with inherited params.
+ * @param {Object} $current Internal definition of object representing the current state.
+ * @param {Object} $to Internal definition of object representing state to transition to.
+ */
+function inheritParams(currentParams, newParams, $current, $to) {
+ var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];
+
+ for (var i in parents) {
+ if (!parents[i].params) continue;
+ parentParams = objectKeys(parents[i].params);
+ if (!parentParams.length) continue;
+
+ for (var j in parentParams) {
+ if (indexOf(inheritList, parentParams[j]) >= 0) continue;
+ inheritList.push(parentParams[j]);
+ inherited[parentParams[j]] = currentParams[parentParams[j]];
+ }
+ }
+ return extend({}, inherited, newParams);
+}
+
+/**
+ * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.
+ *
+ * @param {Object} a The first object.
+ * @param {Object} b The second object.
+ * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,
+ * it defaults to the list of keys in `a`.
+ * @return {Boolean} Returns `true` if the keys match, otherwise `false`.
+ */
+function equalForKeys(a, b, keys) {
+ if (!keys) {
+ keys = [];
+ for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
+ }
+
+ for (var i=0; i<keys.length; i++) {
+ var k = keys[i];
+ if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
+ }
+ return true;
+}
+
+/**
+ * Returns the subset of an object, based on a list of keys.
+ *
+ * @param {Array} keys
+ * @param {Object} values
+ * @return {Boolean} Returns a subset of `values`.
+ */
+function filterByKeys(keys, values) {
+ var filtered = {};
+
+ forEach(keys, function (name) {
+ filtered[name] = values[name];
+ });
+ return filtered;
+}
+
+// like _.indexBy
+// when you know that your index values will be unique, or you want last-one-in to win
+function indexBy(array, propName) {
+ var result = {};
+ forEach(array, function(item) {
+ result[item[propName]] = item;
+ });
+ return result;
+}
+
+// extracted from underscore.js
+// Return a copy of the object only containing the whitelisted properties.
+function pick(obj) {
+ var copy = {};
+ var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
+ forEach(keys, function(key) {
+ if (key in obj) copy[key] = obj[key];
+ });
+ return copy;
+}
+
+// extracted from underscore.js
+// Return a copy of the object omitting the blacklisted properties.
+function omit(obj) {
+ var copy = {};
+ var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
+ for (var key in obj) {
+ if (indexOf(keys, key) == -1) copy[key] = obj[key];
+ }
+ return copy;
+}
+
+function pluck(collection, key) {
+ var result = isArray(collection) ? [] : {};
+
+ forEach(collection, function(val, i) {
+ result[i] = isFunction(key) ? key(val) : val[key];
+ });
+ return result;
+}
+
+function filter(collection, callback) {
+ var array = isArray(collection);
+ var result = array ? [] : {};
+ forEach(collection, function(val, i) {
+ if (callback(val, i)) {
+ result[array ? result.length : i] = val;
+ }
+ });
+ return result;
+}
+
+function map(collection, callback) {
+ var result = isArray(collection) ? [] : {};
+
+ forEach(collection, function(val, i) {
+ result[i] = callback(val, i);
+ });
+ return result;
+}
+
+/**
+ * @ngdoc overview
+ * @name ui.router.util
+ *
+ * @description
+ * # ui.router.util sub-module
+ *
+ * This module is a dependency of other sub-modules. Do not include this module as a dependency
+ * in your angular app (use {@link ui.router} module instead).
+ *
+ */
+angular.module('ui.router.util', ['ng']);
+
+/**
+ * @ngdoc overview
+ * @name ui.router.router
+ *
+ * @requires ui.router.util
+ *
+ * @description
+ * # ui.router.router sub-module
+ *
+ * This module is a dependency of other sub-modules. Do not include this module as a dependency
+ * in your angular app (use {@link ui.router} module instead).
+ */
+angular.module('ui.router.router', ['ui.router.util']);
+
+/**
+ * @ngdoc overview
+ * @name ui.router.state
+ *
+ * @requires ui.router.router
+ * @requires ui.router.util
+ *
+ * @description
+ * # ui.router.state sub-module
+ *
+ * This module is a dependency of the main ui.router module. Do not include this module as a dependency
+ * in your angular app (use {@link ui.router} module instead).
+ *
+ */
+angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);
+
+/**
+ * @ngdoc overview
+ * @name ui.router
+ *
+ * @requires ui.router.state
+ *
+ * @description
+ * # ui.router
+ *
+ * ## The main module for ui.router
+ * There are several sub-modules included with the ui.router module, however only this module is needed
+ * as a dependency within your angular app. The other modules are for organization purposes.
+ *
+ * The modules are:
+ * * ui.router - the main "umbrella" module
+ * * ui.router.router -
+ *
+ * *You'll need to include **only** this module as the dependency within your angular app.*
+ *
+ * <pre>
+ * <!doctype html>
+ * <html ng-app="myApp">
+ * <head>
+ * <script src="js/angular.js"></script>
+ * <!-- Include the ui-router script -->
+ * <script src="js/angular-ui-router.min.js"></script>
+ * <script>
+ * // ...and add 'ui.router' as a dependency
+ * var myApp = angular.module('myApp', ['ui.router']);
+ * </script>
+ * </head>
+ * <body>
+ * </body>
+ * </html>
+ * </pre>
+ */
+angular.module('ui.router', ['ui.router.state']);
+
+angular.module('ui.router.compat', ['ui.router']);
+
+/**
+ * @ngdoc object
+ * @name ui.router.util.$resolve
+ *
+ * @requires $q
+ * @requires $injector
+ *
+ * @description
+ * Manages resolution of (acyclic) graphs of promises.
+ */
+$Resolve.$inject = ['$q', '$injector'];
+function $Resolve( $q, $injector) {
+
+ var VISIT_IN_PROGRESS = 1,
+ VISIT_DONE = 2,
+ NOTHING = {},
+ NO_DEPENDENCIES = [],
+ NO_LOCALS = NOTHING,
+ NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING });
+
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$resolve#study
+ * @methodOf ui.router.util.$resolve
+ *
+ * @description
+ * Studies a set of invocables that are likely to be used multiple times.
+ * <pre>
+ * $resolve.study(invocables)(locals, parent, self)
+ * </pre>
+ * is equivalent to
+ * <pre>
+ * $resolve.resolve(invocables, locals, parent, self)
+ * </pre>
+ * but the former is more efficient (in fact `resolve` just calls `study`
+ * internally).
+ *
+ * @param {object} invocables Invocable objects
+ * @return {function} a function to pass in locals, parent and self
+ */
+ this.study = function (invocables) {
+ if (!isObject(invocables)) throw new Error("'invocables' must be an object");
+ var invocableKeys = objectKeys(invocables || {});
+
+ // Perform a topological sort of invocables to build an ordered plan
+ var plan = [], cycle = [], visited = {};
+ function visit(value, key) {
+ if (visited[key] === VISIT_DONE) return;
+
+ cycle.push(key);
+ if (visited[key] === VISIT_IN_PROGRESS) {
+ cycle.splice(0, indexOf(cycle, key));
+ throw new Error("Cyclic dependency: " + cycle.join(" -> "));
+ }
+ visited[key] = VISIT_IN_PROGRESS;
+
+ if (isString(value)) {
+ plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES);
+ } else {
+ var params = $injector.annotate(value);
+ forEach(params, function (param) {
+ if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);
+ });
+ plan.push(key, value, params);
+ }
+
+ cycle.pop();
+ visited[key] = VISIT_DONE;
+ }
+ forEach(invocables, visit);
+ invocables = cycle = visited = null; // plan is all that's required
+
+ function isResolve(value) {
+ return isObject(value) && value.then && value.$$promises;
+ }
+
+ return function (locals, parent, self) {
+ if (isResolve(locals) && self === undefined) {
+ self = parent; parent = locals; locals = null;
+ }
+ if (!locals) locals = NO_LOCALS;
+ else if (!isObject(locals)) {
+ throw new Error("'locals' must be an object");
+ }
+ if (!parent) parent = NO_PARENT;
+ else if (!isResolve(parent)) {
+ throw new Error("'parent' must be a promise returned by $resolve.resolve()");
+ }
+
+ // To complete the overall resolution, we have to wait for the parent
+ // promise and for the promise for each invokable in our plan.
+ var resolution = $q.defer(),
+ result = resolution.promise,
+ promises = result.$$promises = {},
+ values = extend({}, locals),
+ wait = 1 + plan.length/3,
+ merged = false;
+
+ function done() {
+ // Merge parent values we haven't got yet and publish our own $$values
+ if (!--wait) {
+ if (!merged) merge(values, parent.$$values);
+ result.$$values = values;
+ result.$$promises = result.$$promises || true; // keep for isResolve()
+ delete result.$$inheritedValues;
+ resolution.resolve(values);
+ }
+ }
+
+ function fail(reason) {
+ result.$$failure = reason;
+ resolution.reject(reason);
+ }
+
+ // Short-circuit if parent has already failed
+ if (isDefined(parent.$$failure)) {
+ fail(parent.$$failure);
+ return result;
+ }
+
+ if (parent.$$inheritedValues) {
+ merge(values, omit(parent.$$inheritedValues, invocableKeys));
+ }
+
+ // Merge parent values if the parent has already resolved, or merge
+ // parent promises and wait if the parent resolve is still in progress.
+ extend(promises, parent.$$promises);
+ if (parent.$$values) {
+ merged = merge(values, omit(parent.$$values, invocableKeys));
+ result.$$inheritedValues = omit(parent.$$values, invocableKeys);
+ done();
+ } else {
+ if (parent.$$inheritedValues) {
+ result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);
+ }
+ parent.then(done, fail);
+ }
+
+ // Process each invocable in the plan, but ignore any where a local of the same name exists.
+ for (var i=0, ii=plan.length; i<ii; i+=3) {
+ if (locals.hasOwnProperty(plan[i])) done();
+ else invoke(plan[i], plan[i+1], plan[i+2]);
+ }
+
+ function invoke(key, invocable, params) {
+ // Create a deferred for this invocation. Failures will propagate to the resolution as well.
+ var invocation = $q.defer(), waitParams = 0;
+ function onfailure(reason) {
+ invocation.reject(reason);
+ fail(reason);
+ }
+ // Wait for any parameter that we have a promise for (either from parent or from this
+ // resolve; in that case study() will have made sure it's ordered before us in the plan).
+ forEach(params, function (dep) {
+ if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) {
+ waitParams++;
+ promises[dep].then(function (result) {
+ values[dep] = result;
+ if (!(--waitParams)) proceed();
+ }, onfailure);
+ }
+ });
+ if (!waitParams) proceed();
+ function proceed() {
+ if (isDefined(result.$$failure)) return;
+ try {
+ invocation.resolve($injector.invoke(invocable, self, values));
+ invocation.promise.then(function (result) {
+ values[key] = result;
+ done();
+ }, onfailure);
+ } catch (e) {
+ onfailure(e);
+ }
+ }
+ // Publish promise synchronously; invocations further down in the plan may depend on it.
+ promises[key] = invocation.promise;
+ }
+
+ return result;
+ };
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$resolve#resolve
+ * @methodOf ui.router.util.$resolve
+ *
+ * @description
+ * Resolves a set of invocables. An invocable is a function to be invoked via
+ * `$injector.invoke()`, and can have an arbitrary number of dependencies.
+ * An invocable can either return a value directly,
+ * or a `$q` promise. If a promise is returned it will be resolved and the
+ * resulting value will be used instead. Dependencies of invocables are resolved
+ * (in this order of precedence)
+ *
+ * - from the specified `locals`
+ * - from another invocable that is part of this `$resolve` call
+ * - from an invocable that is inherited from a `parent` call to `$resolve`
+ * (or recursively
+ * - from any ancestor `$resolve` of that parent).
+ *
+ * The return value of `$resolve` is a promise for an object that contains
+ * (in this order of precedence)
+ *
+ * - any `locals` (if specified)
+ * - the resolved return values of all injectables
+ * - any values inherited from a `parent` call to `$resolve` (if specified)
+ *
+ * The promise will resolve after the `parent` promise (if any) and all promises
+ * returned by injectables have been resolved. If any invocable
+ * (or `$injector.invoke`) throws an exception, or if a promise returned by an
+ * invocable is rejected, the `$resolve` promise is immediately rejected with the
+ * same error. A rejection of a `parent` promise (if specified) will likewise be
+ * propagated immediately. Once the `$resolve` promise has been rejected, no
+ * further invocables will be called.
+ *
+ * Cyclic dependencies between invocables are not permitted and will caues `$resolve`
+ * to throw an error. As a special case, an injectable can depend on a parameter
+ * with the same name as the injectable, which will be fulfilled from the `parent`
+ * injectable of the same name. This allows inherited values to be decorated.
+ * Note that in this case any other injectable in the same `$resolve` with the same
+ * dependency would see the decorated value, not the inherited value.
+ *
+ * Note that missing dependencies -- unlike cyclic dependencies -- will cause an
+ * (asynchronous) rejection of the `$resolve` promise rather than a (synchronous)
+ * exception.
+ *
+ * Invocables are invoked eagerly as soon as all dependencies are available.
+ * This is true even for dependencies inherited from a `parent` call to `$resolve`.
+ *
+ * As a special case, an invocable can be a string, in which case it is taken to
+ * be a service name to be passed to `$injector.get()`. This is supported primarily
+ * for backwards-compatibility with the `resolve` property of `$routeProvider`
+ * routes.
+ *
+ * @param {object} invocables functions to invoke or
+ * `$injector` services to fetch.
+ * @param {object} locals values to make available to the injectables
+ * @param {object} parent a promise returned by another call to `$resolve`.
+ * @param {object} self the `this` for the invoked methods
+ * @return {object} Promise for an object that contains the resolved return value
+ * of all invocables, as well as any inherited and local values.
+ */
+ this.resolve = function (invocables, locals, parent, self) {
+ return this.study(invocables)(locals, parent, self);
+ };
+}
+
+angular.module('ui.router.util').service('$resolve', $Resolve);
+
+
+/**
+ * @ngdoc object
+ * @name ui.router.util.$templateFactory
+ *
+ * @requires $http
+ * @requires $templateCache
+ * @requires $injector
+ *
+ * @description
+ * Service. Manages loading of templates.
+ */
+$TemplateFactory.$inject = ['$http', '$templateCache', '$injector'];
+function $TemplateFactory( $http, $templateCache, $injector) {
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$templateFactory#fromConfig
+ * @methodOf ui.router.util.$templateFactory
+ *
+ * @description
+ * Creates a template from a configuration object.
+ *
+ * @param {object} config Configuration object for which to load a template.
+ * The following properties are search in the specified order, and the first one
+ * that is defined is used to create the template:
+ *
+ * @param {string|object} config.template html string template or function to
+ * load via {@link ui.router.util.$templateFactory#fromString fromString}.
+ * @param {string|object} config.templateUrl url to load or a function returning
+ * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.
+ * @param {Function} config.templateProvider function to invoke via
+ * {@link ui.router.util.$templateFactory#fromProvider fromProvider}.
+ * @param {object} params Parameters to pass to the template function.
+ * @param {object} locals Locals to pass to `invoke` if the template is loaded
+ * via a `templateProvider`. Defaults to `{ params: params }`.
+ *
+ * @return {string|object} The template html as a string, or a promise for
+ * that string,or `null` if no template is configured.
+ */
+ this.fromConfig = function (config, params, locals) {
+ return (
+ isDefined(config.template) ? this.fromString(config.template, params) :
+ isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :
+ isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :
+ null
+ );
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$templateFactory#fromString
+ * @methodOf ui.router.util.$templateFactory
+ *
+ * @description
+ * Creates a template from a string or a function returning a string.
+ *
+ * @param {string|object} template html template as a string or function that
+ * returns an html template as a string.
+ * @param {object} params Parameters to pass to the template function.
+ *
+ * @return {string|object} The template html as a string, or a promise for that
+ * string.
+ */
+ this.fromString = function (template, params) {
+ return isFunction(template) ? template(params) : template;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$templateFactory#fromUrl
+ * @methodOf ui.router.util.$templateFactory
+ *
+ * @description
+ * Loads a template from the a URL via `$http` and `$templateCache`.
+ *
+ * @param {string|Function} url url of the template to load, or a function
+ * that returns a url.
+ * @param {Object} params Parameters to pass to the url function.
+ * @return {string|Promise.<string>} The template html as a string, or a promise
+ * for that string.
+ */
+ this.fromUrl = function (url, params) {
+ if (isFunction(url)) url = url(params);
+ if (url == null) return null;
+ else return $http
+ .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})
+ .then(function(response) { return response.data; });
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$templateFactory#fromProvider
+ * @methodOf ui.router.util.$templateFactory
+ *
+ * @description
+ * Creates a template by invoking an injectable provider function.
+ *
+ * @param {Function} provider Function to invoke via `$injector.invoke`
+ * @param {Object} params Parameters for the template.
+ * @param {Object} locals Locals to pass to `invoke`. Defaults to
+ * `{ params: params }`.
+ * @return {string|Promise.<string>} The template html as a string, or a promise
+ * for that string.
+ */
+ this.fromProvider = function (provider, params, locals) {
+ return $injector.invoke(provider, null, locals || { params: params });
+ };
+}
+
+angular.module('ui.router.util').service('$templateFactory', $TemplateFactory);
+
+var $$UMFP; // reference to $UrlMatcherFactoryProvider
+
+/**
+ * @ngdoc object
+ * @name ui.router.util.type:UrlMatcher
+ *
+ * @description
+ * Matches URLs against patterns and extracts named parameters from the path or the search
+ * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list
+ * of search parameters. Multiple search parameter names are separated by '&'. Search parameters
+ * do not influence whether or not a URL is matched, but their values are passed through into
+ * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.
+ *
+ * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace
+ * syntax, which optionally allows a regular expression for the parameter to be specified:
+ *
+ * * `':'` name - colon placeholder
+ * * `'*'` name - catch-all placeholder
+ * * `'{' name '}'` - curly placeholder
+ * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the
+ * regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.
+ *
+ * Parameter names may contain only word characters (latin letters, digits, and underscore) and
+ * must be unique within the pattern (across both path and search parameters). For colon
+ * placeholders or curly placeholders without an explicit regexp, a path parameter matches any
+ * number of characters other than '/'. For catch-all placeholders the path parameter matches
+ * any number of characters.
+ *
+ * Examples:
+ *
+ * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for
+ * trailing slashes, and patterns have to match the entire path, not just a prefix.
+ * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or
+ * '/user/bob/details'. The second path segment will be captured as the parameter 'id'.
+ * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.
+ * * `'/user/{id:[^/]*}'` - Same as the previous example.
+ * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id
+ * parameter consists of 1 to 8 hex digits.
+ * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the
+ * path into the parameter 'path'.
+ * * `'/files/*path'` - ditto.
+ * * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined
+ * in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start
+ *
+ * @param {string} pattern The pattern to compile into a matcher.
+ * @param {Object} config A configuration object hash:
+ * @param {Object=} parentMatcher Used to concatenate the pattern/config onto
+ * an existing UrlMatcher
+ *
+ * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.
+ * * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.
+ *
+ * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any
+ * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns
+ * non-null) will start with this prefix.
+ *
+ * @property {string} source The pattern that was passed into the constructor
+ *
+ * @property {string} sourcePath The path portion of the source property
+ *
+ * @property {string} sourceSearch The search portion of the source property
+ *
+ * @property {string} regex The constructed regex that will be used to match against the url when
+ * it is time to determine which url will match.
+ *
+ * @returns {Object} New `UrlMatcher` object
+ */
+function UrlMatcher(pattern, config, parentMatcher) {
+ config = extend({ params: {} }, isObject(config) ? config : {});
+
+ // Find all placeholders and create a compiled pattern, using either classic or curly syntax:
+ // '*' name
+ // ':' name
+ // '{' name '}'
+ // '{' name ':' regexp '}'
+ // The regular expression is somewhat complicated due to the need to allow curly braces
+ // inside the regular expression. The placeholder regexp breaks down as follows:
+ // ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)
+ // \{([\w\[\]]+)(?:\:( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case
+ // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either
+ // [^{}\\]+ - anything other than curly braces or backslash
+ // \\. - a backslash escape
+ // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms
+ var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
+ searchPlaceholder = /([:]?)([\w\[\]-]+)|\{([\w\[\]-]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
+ compiled = '^', last = 0, m,
+ segments = this.segments = [],
+ parentParams = parentMatcher ? parentMatcher.params : {},
+ params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),
+ paramNames = [];
+
+ function addParameter(id, type, config, location) {
+ paramNames.push(id);
+ if (parentParams[id]) return parentParams[id];
+ if (!/^\w+(-+\w+)*(?:\[\])?$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'");
+ if (params[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'");
+ params[id] = new $$UMFP.Param(id, type, config, location);
+ return params[id];
+ }
+
+ function quoteRegExp(string, pattern, squash, optional) {
+ var surroundPattern = ['',''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&");
+ if (!pattern) return result;
+ switch(squash) {
+ case false: surroundPattern = ['(', ')' + (optional ? "?" : "")]; break;
+ case true: surroundPattern = ['?(', ')?']; break;
+ default: surroundPattern = ['(' + squash + "|", ')?']; break;
+ }
+ return result + surroundPattern[0] + pattern + surroundPattern[1];
+ }
+
+ this.source = pattern;
+
+ // Split into static segments separated by path parameter placeholders.
+ // The number of segments is always 1 more than the number of parameters.
+ function matchDetails(m, isSearch) {
+ var id, regexp, segment, type, cfg, arrayMode;
+ id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null
+ cfg = config.params[id];
+ segment = pattern.substring(last, m.index);
+ regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);
+ type = $$UMFP.type(regexp || "string") || inherit($$UMFP.type("string"), { pattern: new RegExp(regexp, config.caseInsensitive ? 'i' : undefined) });
+ return {
+ id: id, regexp: regexp, segment: segment, type: type, cfg: cfg
+ };
+ }
+
+ var p, param, segment;
+ while ((m = placeholder.exec(pattern))) {
+ p = matchDetails(m, false);
+ if (p.segment.indexOf('?') >= 0) break; // we're into the search part
+
+ param = addParameter(p.id, p.type, p.cfg, "path");
+ compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash, param.isOptional);
+ segments.push(p.segment);
+ last = placeholder.lastIndex;
+ }
+ segment = pattern.substring(last);
+
+ // Find any search parameter names and remove them from the last segment
+ var i = segment.indexOf('?');
+
+ if (i >= 0) {
+ var search = this.sourceSearch = segment.substring(i);
+ segment = segment.substring(0, i);
+ this.sourcePath = pattern.substring(0, last + i);
+
+ if (search.length > 0) {
+ last = 0;
+ while ((m = searchPlaceholder.exec(search))) {
+ p = matchDetails(m, true);
+ param = addParameter(p.id, p.type, p.cfg, "search");
+ last = placeholder.lastIndex;
+ // check if ?&
+ }
+ }
+ } else {
+ this.sourcePath = pattern;
+ this.sourceSearch = '';
+ }
+
+ compiled += quoteRegExp(segment) + (config.strict === false ? '\/?' : '') + '$';
+ segments.push(segment);
+
+ this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);
+ this.prefix = segments[0];
+ this.$$paramNames = paramNames;
+}
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:UrlMatcher#concat
+ * @methodOf ui.router.util.type:UrlMatcher
+ *
+ * @description
+ * Returns a new matcher for a pattern constructed by appending the path part and adding the
+ * search parameters of the specified pattern to this pattern. The current pattern is not
+ * modified. This can be understood as creating a pattern for URLs that are relative to (or
+ * suffixes of) the current pattern.
+ *
+ * @example
+ * The following two matchers are equivalent:
+ * <pre>
+ * new UrlMatcher('/user/{id}?q').concat('/details?date');
+ * new UrlMatcher('/user/{id}/details?q&date');
+ * </pre>
+ *
+ * @param {string} pattern The pattern to append.
+ * @param {Object} config An object hash of the configuration for the matcher.
+ * @returns {UrlMatcher} A matcher for the concatenated pattern.
+ */
+UrlMatcher.prototype.concat = function (pattern, config) {
+ // Because order of search parameters is irrelevant, we can add our own search
+ // parameters to the end of the new pattern. Parse the new pattern by itself
+ // and then join the bits together, but it's much easier to do this on a string level.
+ var defaultConfig = {
+ caseInsensitive: $$UMFP.caseInsensitive(),
+ strict: $$UMFP.strictMode(),
+ squash: $$UMFP.defaultSquashPolicy()
+ };
+ return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);
+};
+
+UrlMatcher.prototype.toString = function () {
+ return this.source;
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:UrlMatcher#exec
+ * @methodOf ui.router.util.type:UrlMatcher
+ *
+ * @description
+ * Tests the specified path against this matcher, and returns an object containing the captured
+ * parameter values, or null if the path does not match. The returned object contains the values
+ * of any search parameters that are mentioned in the pattern, but their value may be null if
+ * they are not present in `searchParams`. This means that search parameters are always treated
+ * as optional.
+ *
+ * @example
+ * <pre>
+ * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {
+ * x: '1', q: 'hello'
+ * });
+ * // returns { id: 'bob', q: 'hello', r: null }
+ * </pre>
+ *
+ * @param {string} path The URL path to match, e.g. `$location.path()`.
+ * @param {Object} searchParams URL search parameters, e.g. `$location.search()`.
+ * @returns {Object} The captured parameter values.
+ */
+UrlMatcher.prototype.exec = function (path, searchParams) {
+ var m = this.regexp.exec(path);
+ if (!m) return null;
+ searchParams = searchParams || {};
+
+ var paramNames = this.parameters(), nTotal = paramNames.length,
+ nPath = this.segments.length - 1,
+ values = {}, i, j, cfg, paramName;
+
+ if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'");
+
+ function decodePathArray(string) {
+ function reverseString(str) { return str.split("").reverse().join(""); }
+ function unquoteDashes(str) { return str.replace(/\\-/g, "-"); }
+
+ var split = reverseString(string).split(/-(?!\\)/);
+ var allReversed = map(split, reverseString);
+ return map(allReversed, unquoteDashes).reverse();
+ }
+
+ for (i = 0; i < nPath; i++) {
+ paramName = paramNames[i];
+ var param = this.params[paramName];
+ var paramVal = m[i+1];
+ // if the param value matches a pre-replace pair, replace the value before decoding.
+ for (j = 0; j < param.replace; j++) {
+ if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;
+ }
+ if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);
+ values[paramName] = param.value(paramVal);
+ }
+ for (/**/; i < nTotal; i++) {
+ paramName = paramNames[i];
+ values[paramName] = this.params[paramName].value(searchParams[paramName]);
+ }
+
+ return values;
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:UrlMatcher#parameters
+ * @methodOf ui.router.util.type:UrlMatcher
+ *
+ * @description
+ * Returns the names of all path and search parameters of this pattern in an unspecified order.
+ *
+ * @returns {Array.<string>} An array of parameter names. Must be treated as read-only. If the
+ * pattern has no parameters, an empty array is returned.
+ */
+UrlMatcher.prototype.parameters = function (param) {
+ if (!isDefined(param)) return this.$$paramNames;
+ return this.params[param] || null;
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:UrlMatcher#validate
+ * @methodOf ui.router.util.type:UrlMatcher
+ *
+ * @description
+ * Checks an object hash of parameters to validate their correctness according to the parameter
+ * types of this `UrlMatcher`.
+ *
+ * @param {Object} params The object hash of parameters to validate.
+ * @returns {boolean} Returns `true` if `params` validates, otherwise `false`.
+ */
+UrlMatcher.prototype.validates = function (params) {
+ return this.params.$$validates(params);
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:UrlMatcher#format
+ * @methodOf ui.router.util.type:UrlMatcher
+ *
+ * @description
+ * Creates a URL that matches this pattern by substituting the specified values
+ * for the path and search parameters. Null values for path parameters are
+ * treated as empty strings.
+ *
+ * @example
+ * <pre>
+ * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });
+ * // returns '/user/bob?q=yes'
+ * </pre>
+ *
+ * @param {Object} values the values to substitute for the parameters in this pattern.
+ * @returns {string} the formatted URL (path and optionally search part).
+ */
+UrlMatcher.prototype.format = function (values) {
+ values = values || {};
+ var segments = this.segments, params = this.parameters(), paramset = this.params;
+ if (!this.validates(values)) return null;
+
+ var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];
+
+ function encodeDashes(str) { // Replace dashes with encoded "\-"
+ return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); });
+ }
+
+ for (i = 0; i < nTotal; i++) {
+ var isPathParam = i < nPath;
+ var name = params[i], param = paramset[name], value = param.value(values[name]);
+ var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);
+ var squash = isDefaultValue ? param.squash : false;
+ var encoded = param.type.encode(value);
+
+ if (isPathParam) {
+ var nextSegment = segments[i + 1];
+ if (squash === false) {
+ if (encoded != null) {
+ if (isArray(encoded)) {
+ result += map(encoded, encodeDashes).join("-");
+ } else {
+ result += encodeURIComponent(encoded);
+ }
+ }
+ result += nextSegment;
+ } else if (squash === true) {
+ var capture = result.match(/\/$/) ? /\/?(.*)/ : /(.*)/;
+ result += nextSegment.match(capture)[1];
+ } else if (isString(squash)) {
+ result += squash + nextSegment;
+ }
+ } else {
+ if (encoded == null || (isDefaultValue && squash !== false)) continue;
+ if (!isArray(encoded)) encoded = [ encoded ];
+ encoded = map(encoded, encodeURIComponent).join('&' + name + '=');
+ result += (search ? '&' : '?') + (name + '=' + encoded);
+ search = true;
+ }
+ }
+
+ return result;
+};
+
+/**
+ * @ngdoc object
+ * @name ui.router.util.type:Type
+ *
+ * @description
+ * Implements an interface to define custom parameter types that can be decoded from and encoded to
+ * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}
+ * objects when matching or formatting URLs, or comparing or validating parameter values.
+ *
+ * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more
+ * information on registering custom types.
+ *
+ * @param {Object} config A configuration object which contains the custom type definition. The object's
+ * properties will override the default methods and/or pattern in `Type`'s public interface.
+ * @example
+ * <pre>
+ * {
+ * decode: function(val) { return parseInt(val, 10); },
+ * encode: function(val) { return val && val.toString(); },
+ * equals: function(a, b) { return this.is(a) && a === b; },
+ * is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },
+ * pattern: /\d+/
+ * }
+ * </pre>
+ *
+ * @property {RegExp} pattern The regular expression pattern used to match values of this type when
+ * coming from a substring of a URL.
+ *
+ * @returns {Object} Returns a new `Type` object.
+ */
+function Type(config) {
+ extend(this, config);
+}
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:Type#is
+ * @methodOf ui.router.util.type:Type
+ *
+ * @description
+ * Detects whether a value is of a particular type. Accepts a native (decoded) value
+ * and determines whether it matches the current `Type` object.
+ *
+ * @param {*} val The value to check.
+ * @param {string} key Optional. If the type check is happening in the context of a specific
+ * {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the
+ * parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.
+ * @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`.
+ */
+Type.prototype.is = function(val, key) {
+ return true;
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:Type#encode
+ * @methodOf ui.router.util.type:Type
+ *
+ * @description
+ * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the
+ * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it
+ * only needs to be a representation of `val` that has been coerced to a string.
+ *
+ * @param {*} val The value to encode.
+ * @param {string} key The name of the parameter in which `val` is stored. Can be used for
+ * meta-programming of `Type` objects.
+ * @returns {string} Returns a string representation of `val` that can be encoded in a URL.
+ */
+Type.prototype.encode = function(val, key) {
+ return val;
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:Type#decode
+ * @methodOf ui.router.util.type:Type
+ *
+ * @description
+ * Converts a parameter value (from URL string or transition param) to a custom/native value.
+ *
+ * @param {string} val The URL parameter value to decode.
+ * @param {string} key The name of the parameter in which `val` is stored. Can be used for
+ * meta-programming of `Type` objects.
+ * @returns {*} Returns a custom representation of the URL parameter value.
+ */
+Type.prototype.decode = function(val, key) {
+ return val;
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:Type#equals
+ * @methodOf ui.router.util.type:Type
+ *
+ * @description
+ * Determines whether two decoded values are equivalent.
+ *
+ * @param {*} a A value to compare against.
+ * @param {*} b A value to compare against.
+ * @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`.
+ */
+Type.prototype.equals = function(a, b) {
+ return a == b;
+};
+
+Type.prototype.$subPattern = function() {
+ var sub = this.pattern.toString();
+ return sub.substr(1, sub.length - 2);
+};
+
+Type.prototype.pattern = /.*/;
+
+Type.prototype.toString = function() { return "{Type:" + this.name + "}"; };
+
+/** Given an encoded string, or a decoded object, returns a decoded object */
+Type.prototype.$normalize = function(val) {
+ return this.is(val) ? val : this.decode(val);
+};
+
+/*
+ * Wraps an existing custom Type as an array of Type, depending on 'mode'.
+ * e.g.:
+ * - urlmatcher pattern "/path?{queryParam[]:int}"
+ * - url: "/path?queryParam=1&queryParam=2
+ * - $stateParams.queryParam will be [1, 2]
+ * if `mode` is "auto", then
+ * - url: "/path?queryParam=1 will create $stateParams.queryParam: 1
+ * - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]
+ */
+Type.prototype.$asArray = function(mode, isSearch) {
+ if (!mode) return this;
+ if (mode === "auto" && !isSearch) throw new Error("'auto' array mode is for query parameters only");
+
+ function ArrayType(type, mode) {
+ function bindTo(type, callbackName) {
+ return function() {
+ return type[callbackName].apply(type, arguments);
+ };
+ }
+
+ // Wrap non-array value as array
+ function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); }
+ // Unwrap array value for "auto" mode. Return undefined for empty array.
+ function arrayUnwrap(val) {
+ switch(val.length) {
+ case 0: return undefined;
+ case 1: return mode === "auto" ? val[0] : val;
+ default: return val;
+ }
+ }
+ function falsey(val) { return !val; }
+
+ // Wraps type (.is/.encode/.decode) functions to operate on each value of an array
+ function arrayHandler(callback, allTruthyMode) {
+ return function handleArray(val) {
+ val = arrayWrap(val);
+ var result = map(val, callback);
+ if (allTruthyMode === true)
+ return filter(result, falsey).length === 0;
+ return arrayUnwrap(result);
+ };
+ }
+
+ // Wraps type (.equals) functions to operate on each value of an array
+ function arrayEqualsHandler(callback) {
+ return function handleArray(val1, val2) {
+ var left = arrayWrap(val1), right = arrayWrap(val2);
+ if (left.length !== right.length) return false;
+ for (var i = 0; i < left.length; i++) {
+ if (!callback(left[i], right[i])) return false;
+ }
+ return true;
+ };
+ }
+
+ this.encode = arrayHandler(bindTo(type, 'encode'));
+ this.decode = arrayHandler(bindTo(type, 'decode'));
+ this.is = arrayHandler(bindTo(type, 'is'), true);
+ this.equals = arrayEqualsHandler(bindTo(type, 'equals'));
+ this.pattern = type.pattern;
+ this.$normalize = arrayHandler(bindTo(type, '$normalize'));
+ this.name = type.name;
+ this.$arrayMode = mode;
+ }
+
+ return new ArrayType(this, mode);
+};
+
+
+
+/**
+ * @ngdoc object
+ * @name ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory
+ * is also available to providers under the name `$urlMatcherFactoryProvider`.
+ */
+function $UrlMatcherFactory() {
+ $$UMFP = this;
+
+ var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;
+
+ function valToString(val) { return val != null ? val.toString().replace(/\//g, "%2F") : val; }
+ function valFromString(val) { return val != null ? val.toString().replace(/%2F/g, "/") : val; }
+
+ var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {
+ string: {
+ encode: valToString,
+ decode: valFromString,
+ // TODO: in 1.0, make string .is() return false if value is undefined/null by default.
+ // In 0.2.x, string params are optional by default for backwards compat
+ is: function(val) { return val == null || !isDefined(val) || typeof val === "string"; },
+ pattern: /[^/]*/
+ },
+ int: {
+ encode: valToString,
+ decode: function(val) { return parseInt(val, 10); },
+ is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; },
+ pattern: /\d+/
+ },
+ bool: {
+ encode: function(val) { return val ? 1 : 0; },
+ decode: function(val) { return parseInt(val, 10) !== 0; },
+ is: function(val) { return val === true || val === false; },
+ pattern: /0|1/
+ },
+ date: {
+ encode: function (val) {
+ if (!this.is(val))
+ return undefined;
+ return [ val.getFullYear(),
+ ('0' + (val.getMonth() + 1)).slice(-2),
+ ('0' + val.getDate()).slice(-2)
+ ].join("-");
+ },
+ decode: function (val) {
+ if (this.is(val)) return val;
+ var match = this.capture.exec(val);
+ return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;
+ },
+ is: function(val) { return val instanceof Date && !isNaN(val.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: angular.toJson,
+ decode: angular.fromJson,
+ is: angular.isObject,
+ equals: angular.equals,
+ pattern: /[^/]*/
+ },
+ any: { // does not encode/decode
+ encode: angular.identity,
+ decode: angular.identity,
+ equals: angular.equals,
+ pattern: /.*/
+ }
+ };
+
+ function getDefaultConfig() {
+ return {
+ strict: isStrictMode,
+ caseInsensitive: isCaseInsensitive
+ };
+ }
+
+ function isInjectable(value) {
+ return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));
+ }
+
+ /**
+ * [Internal] Get the default value of a parameter, which may be an injectable function.
+ */
+ $UrlMatcherFactory.$$getDefaultValue = function(config) {
+ if (!isInjectable(config.value)) return config.value;
+ if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
+ return injector.invoke(config.value);
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$urlMatcherFactory#caseInsensitive
+ * @methodOf ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Defines whether URL matching should be case sensitive (the default behavior), or not.
+ *
+ * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;
+ * @returns {boolean} the current value of caseInsensitive
+ */
+ this.caseInsensitive = function(value) {
+ if (isDefined(value))
+ isCaseInsensitive = value;
+ return isCaseInsensitive;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$urlMatcherFactory#strictMode
+ * @methodOf ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Defines whether URLs should match trailing slashes, or not (the default behavior).
+ *
+ * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.
+ * @returns {boolean} the current value of strictMode
+ */
+ this.strictMode = function(value) {
+ if (isDefined(value))
+ isStrictMode = value;
+ return isStrictMode;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy
+ * @methodOf ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Sets the default behavior when generating or matching URLs with default parameter values.
+ *
+ * @param {string} value A string that defines the default parameter URL squashing behavior.
+ * `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL
+ * `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the
+ * parameter is surrounded by slashes, squash (remove) one slash from the URL
+ * any other string, e.g. "~": When generating an href with a default parameter value, squash (remove)
+ * the parameter value from the URL and replace it with this string.
+ */
+ this.defaultSquashPolicy = function(value) {
+ if (!isDefined(value)) return defaultSquashPolicy;
+ if (value !== true && value !== false && !isString(value))
+ throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string");
+ defaultSquashPolicy = value;
+ return value;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$urlMatcherFactory#compile
+ * @methodOf ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.
+ *
+ * @param {string} pattern The URL pattern.
+ * @param {Object} config The config object hash.
+ * @returns {UrlMatcher} The UrlMatcher.
+ */
+ this.compile = function (pattern, config) {
+ return new UrlMatcher(pattern, extend(getDefaultConfig(), config));
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$urlMatcherFactory#isMatcher
+ * @methodOf ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Returns true if the specified object is a `UrlMatcher`, or false otherwise.
+ *
+ * @param {Object} object The object to perform the type check against.
+ * @returns {Boolean} Returns `true` if the object matches the `UrlMatcher` interface, by
+ * implementing all the same methods.
+ */
+ this.isMatcher = function (o) {
+ if (!isObject(o)) return false;
+ var result = true;
+
+ forEach(UrlMatcher.prototype, function(val, name) {
+ if (isFunction(val)) {
+ result = result && (isDefined(o[name]) && isFunction(o[name]));
+ }
+ });
+ return result;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$urlMatcherFactory#type
+ * @methodOf ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to
+ * generate URLs with typed parameters.
+ *
+ * @param {string} name The type name.
+ * @param {Object|Function} definition The type definition. See
+ * {@link ui.router.util.type:Type `Type`} for information on the values accepted.
+ * @param {Object|Function} definitionFn (optional) A function that is injected before the app
+ * runtime starts. The result of this function is merged into the existing `definition`.
+ * See {@link ui.router.util.type:Type `Type`} for information on the values accepted.
+ *
+ * @returns {Object} Returns `$urlMatcherFactoryProvider`.
+ *
+ * @example
+ * This is a simple example of a custom type that encodes and decodes items from an
+ * array, using the array index as the URL-encoded value:
+ *
+ * <pre>
+ * var list = ['John', 'Paul', 'George', 'Ringo'];
+ *
+ * $urlMatcherFactoryProvider.type('listItem', {
+ * encode: function(item) {
+ * // Represent the list item in the URL using its corresponding index
+ * return list.indexOf(item);
+ * },
+ * decode: function(item) {
+ * // Look up the list item by index
+ * return list[parseInt(item, 10)];
+ * },
+ * is: function(item) {
+ * // Ensure the item is valid by checking to see that it appears
+ * // in the list
+ * return list.indexOf(item) > -1;
+ * }
+ * });
+ *
+ * $stateProvider.state('list', {
+ * url: "/list/{item:listItem}",
+ * controller: function($scope, $stateParams) {
+ * console.log($stateParams.item);
+ * }
+ * });
+ *
+ * // ...
+ *
+ * // Changes URL to '/list/3', logs "Ringo" to the console
+ * $state.go('list', { item: "Ringo" });
+ * </pre>
+ *
+ * This is a more complex example of a type that relies on dependency injection to
+ * interact with services, and uses the parameter name from the URL to infer how to
+ * handle encoding and decoding parameter values:
+ *
+ * <pre>
+ * // Defines a custom type that gets a value from a service,
+ * // where each service gets different types of values from
+ * // a backend API:
+ * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {
+ *
+ * // Matches up services to URL parameter names
+ * var services = {
+ * user: Users,
+ * post: Posts
+ * };
+ *
+ * return {
+ * encode: function(object) {
+ * // Represent the object in the URL using its unique ID
+ * return object.id;
+ * },
+ * decode: function(value, key) {
+ * // Look up the object by ID, using the parameter
+ * // name (key) to call the correct service
+ * return services[key].findById(value);
+ * },
+ * is: function(object, key) {
+ * // Check that object is a valid dbObject
+ * return angular.isObject(object) && object.id && services[key];
+ * }
+ * equals: function(a, b) {
+ * // Check the equality of decoded objects by comparing
+ * // their unique IDs
+ * return a.id === b.id;
+ * }
+ * };
+ * });
+ *
+ * // In a config() block, you can then attach URLs with
+ * // type-annotated parameters:
+ * $stateProvider.state('users', {
+ * url: "/users",
+ * // ...
+ * }).state('users.item', {
+ * url: "/{user:dbObject}",
+ * controller: function($scope, $stateParams) {
+ * // $stateParams.user will now be an object returned from
+ * // the Users service
+ * },
+ * // ...
+ * });
+ * </pre>
+ */
+ this.type = function (name, definition, definitionFn) {
+ if (!isDefined(definition)) return $types[name];
+ if ($types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined.");
+
+ $types[name] = new Type(extend({ name: name }, definition));
+ if (definitionFn) {
+ typeQueue.push({ name: name, def: definitionFn });
+ if (!enqueue) flushTypeQueue();
+ }
+ return this;
+ };
+
+ // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s
+ function flushTypeQueue() {
+ while(typeQueue.length) {
+ var type = typeQueue.shift();
+ if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime.");
+ angular.extend($types[type.name], injector.invoke(type.def));
+ }
+ }
+
+ // Register default types. Store them in the prototype of $types.
+ forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); });
+ $types = inherit($types, {});
+
+ /* No need to document $get, since it returns this */
+ this.$get = ['$injector', function ($injector) {
+ injector = $injector;
+ enqueue = false;
+ flushTypeQueue();
+
+ forEach(defaultTypes, function(type, name) {
+ if (!$types[name]) $types[name] = new Type(type);
+ });
+ return this;
+ }];
+
+ this.Param = function Param(id, type, config, location) {
+ var self = this;
+ config = unwrapShorthand(config);
+ type = getType(config, type, location);
+ var arrayMode = getArrayMode();
+ type = arrayMode ? type.$asArray(arrayMode, location === "search") : type;
+ if (type.name === "string" && !arrayMode && location === "path" && config.value === undefined)
+ config.value = ""; // for 0.2.x; in 0.3.0+ do not automatically default to ""
+ var isOptional = config.value !== undefined;
+ var squash = getSquashPolicy(config, isOptional);
+ var replace = getReplace(config, arrayMode, isOptional, squash);
+
+ function unwrapShorthand(config) {
+ var keys = isObject(config) ? objectKeys(config) : [];
+ var isShorthand = indexOf(keys, "value") === -1 && indexOf(keys, "type") === -1 &&
+ indexOf(keys, "squash") === -1 && indexOf(keys, "array") === -1;
+ if (isShorthand) config = { value: config };
+ config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; };
+ return config;
+ }
+
+ function getType(config, urlType, location) {
+ if (config.type && urlType) throw new Error("Param '"+id+"' has two type configurations.");
+ if (urlType) return urlType;
+ if (!config.type) return (location === "config" ? $types.any : $types.string);
+ return config.type instanceof Type ? config.type : new Type(config.type);
+ }
+
+ // array config: param name (param[]) overrides default settings. explicit config overrides param name.
+ function getArrayMode() {
+ var arrayDefaults = { array: (location === "search" ? "auto" : false) };
+ var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {};
+ return extend(arrayDefaults, arrayParamNomenclature, config).array;
+ }
+
+ /**
+ * returns false, true, or the squash value to indicate the "default parameter url squash policy".
+ */
+ function getSquashPolicy(config, isOptional) {
+ var squash = config.squash;
+ if (!isOptional || squash === false) return false;
+ if (!isDefined(squash) || squash == null) return defaultSquashPolicy;
+ if (squash === true || isString(squash)) return squash;
+ throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string");
+ }
+
+ function getReplace(config, arrayMode, isOptional, squash) {
+ var replace, configuredKeys, defaultPolicy = [
+ { from: "", to: (isOptional || arrayMode ? undefined : "") },
+ { from: null, to: (isOptional || arrayMode ? undefined : "") }
+ ];
+ replace = isArray(config.replace) ? config.replace : [];
+ if (isString(squash))
+ replace.push({ from: squash, to: undefined });
+ configuredKeys = map(replace, function(item) { return item.from; } );
+ return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace);
+ }
+
+ /**
+ * [Internal] Get the default value of a parameter, which may be an injectable function.
+ */
+ function $$getDefaultValue() {
+ if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
+ var defaultValue = injector.invoke(config.$$fn);
+ if (defaultValue !== null && defaultValue !== undefined && !self.type.is(defaultValue))
+ throw new Error("Default value (" + defaultValue + ") for parameter '" + self.id + "' is not an instance of Type (" + self.type.name + ")");
+ return defaultValue;
+ }
+
+ /**
+ * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the
+ * default value, which may be the result of an injectable function.
+ */
+ function $value(value) {
+ function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; }
+ function $replace(value) {
+ var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; });
+ return replacement.length ? replacement[0] : value;
+ }
+ value = $replace(value);
+ return !isDefined(value) ? $$getDefaultValue() : self.type.$normalize(value);
+ }
+
+ function toString() { return "{Param:" + id + " " + type + " squash: '" + squash + "' optional: " + isOptional + "}"; }
+
+ extend(this, {
+ id: id,
+ type: type,
+ location: location,
+ array: arrayMode,
+ squash: squash,
+ replace: replace,
+ isOptional: isOptional,
+ value: $value,
+ dynamic: undefined,
+ config: config,
+ toString: toString
+ });
+ };
+
+ function ParamSet(params) {
+ extend(this, params || {});
+ }
+
+ ParamSet.prototype = {
+ $$new: function() {
+ return inherit(this, extend(new ParamSet(), { $$parent: this}));
+ },
+ $$keys: function () {
+ var keys = [], chain = [], parent = this,
+ ignore = objectKeys(ParamSet.prototype);
+ while (parent) { chain.push(parent); parent = parent.$$parent; }
+ chain.reverse();
+ forEach(chain, function(paramset) {
+ forEach(objectKeys(paramset), function(key) {
+ if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);
+ });
+ });
+ return keys;
+ },
+ $$values: function(paramValues) {
+ var values = {}, self = this;
+ forEach(self.$$keys(), function(key) {
+ values[key] = self[key].value(paramValues && paramValues[key]);
+ });
+ return values;
+ },
+ $$equals: function(paramValues1, paramValues2) {
+ var equal = true, self = this;
+ forEach(self.$$keys(), function(key) {
+ var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];
+ if (!self[key].type.equals(left, right)) equal = false;
+ });
+ return equal;
+ },
+ $$validates: function $$validate(paramValues) {
+ var keys = this.$$keys(), i, param, rawVal, normalized, encoded;
+ for (i = 0; i < keys.length; i++) {
+ param = this[keys[i]];
+ rawVal = paramValues[keys[i]];
+ if ((rawVal === undefined || rawVal === null) && param.isOptional)
+ break; // There was no parameter value, but the param is optional
+ normalized = param.type.$normalize(rawVal);
+ if (!param.type.is(normalized))
+ return false; // The value was not of the correct Type, and could not be decoded to the correct Type
+ encoded = param.type.encode(normalized);
+ if (angular.isString(encoded) && !param.type.pattern.exec(encoded))
+ return false; // The value was of the correct type, but when encoded, did not match the Type's regexp
+ }
+ return true;
+ },
+ $$parent: undefined
+ };
+
+ this.ParamSet = ParamSet;
+}
+
+// Register as a provider so it's available to other providers
+angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);
+angular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]);
+
+/**
+ * @ngdoc object
+ * @name ui.router.router.$urlRouterProvider
+ *
+ * @requires ui.router.util.$urlMatcherFactoryProvider
+ * @requires $locationProvider
+ *
+ * @description
+ * `$urlRouterProvider` has the responsibility of watching `$location`.
+ * When `$location` changes it runs through a list of rules one by one until a
+ * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify
+ * a url in a state configuration. All urls are compiled into a UrlMatcher object.
+ *
+ * There are several methods on `$urlRouterProvider` that make it useful to use directly
+ * in your module config.
+ */
+$UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];
+function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {
+ var rules = [], otherwise = null, interceptDeferred = false, listener;
+
+ // Returns a string that is a prefix of all strings matching the RegExp
+ function regExpPrefix(re) {
+ var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
+ return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
+ }
+
+ // Interpolates matched values into a String.replace()-style pattern
+ function interpolate(pattern, match) {
+ return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) {
+ return match[what === '$' ? 0 : Number(what)];
+ });
+ }
+
+ /**
+ * @ngdoc function
+ * @name ui.router.router.$urlRouterProvider#rule
+ * @methodOf ui.router.router.$urlRouterProvider
+ *
+ * @description
+ * Defines rules that are used by `$urlRouterProvider` to find matches for
+ * specific URLs.
+ *
+ * @example
+ * <pre>
+ * var app = angular.module('app', ['ui.router.router']);
+ *
+ * app.config(function ($urlRouterProvider) {
+ * // Here's an example of how you might allow case insensitive urls
+ * $urlRouterProvider.rule(function ($injector, $location) {
+ * var path = $location.path(),
+ * normalized = path.toLowerCase();
+ *
+ * if (path !== normalized) {
+ * return normalized;
+ * }
+ * });
+ * });
+ * </pre>
+ *
+ * @param {object} rule Handler function that takes `$injector` and `$location`
+ * services as arguments. You can use them to return a valid path as a string.
+ *
+ * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
+ */
+ this.rule = function (rule) {
+ if (!isFunction(rule)) throw new Error("'rule' must be a function");
+ rules.push(rule);
+ return this;
+ };
+
+ /**
+ * @ngdoc object
+ * @name ui.router.router.$urlRouterProvider#otherwise
+ * @methodOf ui.router.router.$urlRouterProvider
+ *
+ * @description
+ * Defines a path that is used when an invalid route is requested.
+ *
+ * @example
+ * <pre>
+ * var app = angular.module('app', ['ui.router.router']);
+ *
+ * app.config(function ($urlRouterProvider) {
+ * // if the path doesn't match any of the urls you configured
+ * // otherwise will take care of routing the user to the
+ * // specified url
+ * $urlRouterProvider.otherwise('/index');
+ *
+ * // Example of using function rule as param
+ * $urlRouterProvider.otherwise(function ($injector, $location) {
+ * return '/a/valid/url';
+ * });
+ * });
+ * </pre>
+ *
+ * @param {string|object} rule The url path you want to redirect to or a function
+ * rule that returns the url path. The function version is passed two params:
+ * `$injector` and `$location` services, and must return a url string.
+ *
+ * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
+ */
+ this.otherwise = function (rule) {
+ if (isString(rule)) {
+ var redirect = rule;
+ rule = function () { return redirect; };
+ }
+ else if (!isFunction(rule)) throw new Error("'rule' must be a function");
+ otherwise = rule;
+ return this;
+ };
+
+
+ function handleIfMatch($injector, handler, match) {
+ if (!match) return false;
+ var result = $injector.invoke(handler, handler, { $match: match });
+ return isDefined(result) ? result : true;
+ }
+
+ /**
+ * @ngdoc function
+ * @name ui.router.router.$urlRouterProvider#when
+ * @methodOf ui.router.router.$urlRouterProvider
+ *
+ * @description
+ * Registers a handler for a given url matching. if handle is a string, it is
+ * treated as a redirect, and is interpolated according to the syntax of match
+ * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).
+ *
+ * If the handler is a function, it is injectable. It gets invoked if `$location`
+ * matches. You have the option of inject the match object as `$match`.
+ *
+ * The handler can return
+ *
+ * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`
+ * will continue trying to find another one that matches.
+ * - **string** which is treated as a redirect and passed to `$location.url()`
+ * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.
+ *
+ * @example
+ * <pre>
+ * var app = angular.module('app', ['ui.router.router']);
+ *
+ * app.config(function ($urlRouterProvider) {
+ * $urlRouterProvider.when($state.url, function ($match, $stateParams) {
+ * if ($state.$current.navigable !== state ||
+ * !equalForKeys($match, $stateParams) {
+ * $state.transitionTo(state, $match, false);
+ * }
+ * });
+ * });
+ * </pre>
+ *
+ * @param {string|object} what The incoming path that you want to redirect.
+ * @param {string|object} handler The path you want to redirect your user to.
+ */
+ this.when = function (what, handler) {
+ var redirect, handlerIsString = isString(handler);
+ if (isString(what)) what = $urlMatcherFactory.compile(what);
+
+ if (!handlerIsString && !isFunction(handler) && !isArray(handler))
+ throw new Error("invalid 'handler' in when()");
+
+ var strategies = {
+ matcher: function (what, handler) {
+ if (handlerIsString) {
+ redirect = $urlMatcherFactory.compile(handler);
+ handler = ['$match', function ($match) { return redirect.format($match); }];
+ }
+ return extend(function ($injector, $location) {
+ return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));
+ }, {
+ prefix: isString(what.prefix) ? what.prefix : ''
+ });
+ },
+ regex: function (what, handler) {
+ if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky");
+
+ if (handlerIsString) {
+ redirect = handler;
+ handler = ['$match', function ($match) { return interpolate(redirect, $match); }];
+ }
+ return extend(function ($injector, $location) {
+ return handleIfMatch($injector, handler, what.exec($location.path()));
+ }, {
+ prefix: regExpPrefix(what)
+ });
+ }
+ };
+
+ var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };
+
+ for (var n in check) {
+ if (check[n]) return this.rule(strategies[n](what, handler));
+ }
+
+ throw new Error("invalid 'what' in when()");
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.router.$urlRouterProvider#deferIntercept
+ * @methodOf ui.router.router.$urlRouterProvider
+ *
+ * @description
+ * Disables (or enables) deferring location change interception.
+ *
+ * If you wish to customize the behavior of syncing the URL (for example, if you wish to
+ * defer a transition but maintain the current URL), call this method at configuration time.
+ * Then, at run time, call `$urlRouter.listen()` after you have configured your own
+ * `$locationChangeSuccess` event handler.
+ *
+ * @example
+ * <pre>
+ * var app = angular.module('app', ['ui.router.router']);
+ *
+ * app.config(function ($urlRouterProvider) {
+ *
+ * // Prevent $urlRouter from automatically intercepting URL changes;
+ * // this allows you to configure custom behavior in between
+ * // location changes and route synchronization:
+ * $urlRouterProvider.deferIntercept();
+ *
+ * }).run(function ($rootScope, $urlRouter, UserService) {
+ *
+ * $rootScope.$on('$locationChangeSuccess', function(e) {
+ * // UserService is an example service for managing user state
+ * if (UserService.isLoggedIn()) return;
+ *
+ * // Prevent $urlRouter's default handler from firing
+ * e.preventDefault();
+ *
+ * UserService.handleLogin().then(function() {
+ * // Once the user has logged in, sync the current URL
+ * // to the router:
+ * $urlRouter.sync();
+ * });
+ * });
+ *
+ * // Configures $urlRouter's listener *after* your custom listener
+ * $urlRouter.listen();
+ * });
+ * </pre>
+ *
+ * @param {boolean} defer Indicates whether to defer location change interception. Passing
+ no parameter is equivalent to `true`.
+ */
+ this.deferIntercept = function (defer) {
+ if (defer === undefined) defer = true;
+ interceptDeferred = defer;
+ };
+
+ /**
+ * @ngdoc object
+ * @name ui.router.router.$urlRouter
+ *
+ * @requires $location
+ * @requires $rootScope
+ * @requires $injector
+ * @requires $browser
+ *
+ * @description
+ *
+ */
+ this.$get = $get;
+ $get.$inject = ['$location', '$rootScope', '$injector', '$browser'];
+ function $get( $location, $rootScope, $injector, $browser) {
+
+ var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;
+
+ function appendBasePath(url, isHtml5, absolute) {
+ if (baseHref === '/') return url;
+ if (isHtml5) return baseHref.slice(0, -1) + url;
+ if (absolute) return baseHref.slice(1) + url;
+ return url;
+ }
+
+ // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
+ function update(evt) {
+ if (evt && evt.defaultPrevented) return;
+ var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;
+ lastPushedUrl = undefined;
+ // TODO: Re-implement this in 1.0 for https://github.com/angular-ui/ui-router/issues/1573
+ //if (ignoreUpdate) return true;
+
+ function check(rule) {
+ var handled = rule($injector, $location);
+
+ if (!handled) return false;
+ if (isString(handled)) $location.replace().url(handled);
+ return true;
+ }
+ var n = rules.length, i;
+
+ for (i = 0; i < n; i++) {
+ if (check(rules[i])) return;
+ }
+ // always check otherwise last to allow dynamic updates to the set of rules
+ if (otherwise) check(otherwise);
+ }
+
+ function listen() {
+ listener = listener || $rootScope.$on('$locationChangeSuccess', update);
+ return listener;
+ }
+
+ if (!interceptDeferred) listen();
+
+ return {
+ /**
+ * @ngdoc function
+ * @name ui.router.router.$urlRouter#sync
+ * @methodOf ui.router.router.$urlRouter
+ *
+ * @description
+ * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.
+ * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,
+ * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed
+ * with the transition by calling `$urlRouter.sync()`.
+ *
+ * @example
+ * <pre>
+ * angular.module('app', ['ui.router'])
+ * .run(function($rootScope, $urlRouter) {
+ * $rootScope.$on('$locationChangeSuccess', function(evt) {
+ * // Halt state change from even starting
+ * evt.preventDefault();
+ * // Perform custom logic
+ * var meetsRequirement = ...
+ * // Continue with the update and state transition if logic allows
+ * if (meetsRequirement) $urlRouter.sync();
+ * });
+ * });
+ * </pre>
+ */
+ sync: function() {
+ update();
+ },
+
+ listen: function() {
+ return listen();
+ },
+
+ update: function(read) {
+ if (read) {
+ location = $location.url();
+ return;
+ }
+ if ($location.url() === location) return;
+
+ $location.url(location);
+ $location.replace();
+ },
+
+ push: function(urlMatcher, params, options) {
+ var url = urlMatcher.format(params || {});
+
+ // Handle the special hash param, if needed
+ if (url !== null && params && params['#']) {
+ url += '#' + params['#'];
+ }
+
+ $location.url(url);
+ lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;
+ if (options && options.replace) $location.replace();
+ },
+
+ /**
+ * @ngdoc function
+ * @name ui.router.router.$urlRouter#href
+ * @methodOf ui.router.router.$urlRouter
+ *
+ * @description
+ * A URL generation method that returns the compiled URL for a given
+ * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.
+ *
+ * @example
+ * <pre>
+ * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
+ * person: "bob"
+ * });
+ * // $bob == "/about/bob";
+ * </pre>
+ *
+ * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.
+ * @param {object=} params An object of parameter values to fill the matcher's required parameters.
+ * @param {object=} options Options object. The options are:
+ *
+ * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
+ *
+ * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`
+ */
+ href: function(urlMatcher, params, options) {
+ if (!urlMatcher.validates(params)) return null;
+
+ var isHtml5 = $locationProvider.html5Mode();
+ if (angular.isObject(isHtml5)) {
+ isHtml5 = isHtml5.enabled;
+ }
+
+ var url = urlMatcher.format(params);
+ options = options || {};
+
+ if (!isHtml5 && url !== null) {
+ url = "#" + $locationProvider.hashPrefix() + url;
+ }
+
+ // Handle special hash param, if needed
+ if (url !== null && params && params['#']) {
+ url += '#' + params['#'];
+ }
+
+ url = appendBasePath(url, isHtml5, options.absolute);
+
+ if (!options.absolute || !url) {
+ return url;
+ }
+
+ var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();
+ port = (port === 80 || port === 443 ? '' : ':' + port);
+
+ return [$location.protocol(), '://', $location.host(), port, slash, url].join('');
+ }
+ };
+ }
+}
+
+angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);
+
+/**
+ * @ngdoc object
+ * @name ui.router.state.$stateProvider
+ *
+ * @requires ui.router.router.$urlRouterProvider
+ * @requires ui.router.util.$urlMatcherFactoryProvider
+ *
+ * @description
+ * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely
+ * on state.
+ *
+ * A state corresponds to a "place" in the application in terms of the overall UI and
+ * navigation. A state describes (via the controller / template / view properties) what
+ * the UI looks like and does at that place.
+ *
+ * States often have things in common, and the primary way of factoring out these
+ * commonalities in this model is via the state hierarchy, i.e. parent/child states aka
+ * nested states.
+ *
+ * The `$stateProvider` provides interfaces to declare these states for your app.
+ */
+$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];
+function $StateProvider( $urlRouterProvider, $urlMatcherFactory) {
+
+ var root, states = {}, $state, queue = {}, abstractKey = 'abstract';
+
+ // Builds state properties from definition passed to registerState()
+ var stateBuilder = {
+
+ // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.
+ // state.children = [];
+ // if (parent) parent.children.push(state);
+ parent: function(state) {
+ if (isDefined(state.parent) && state.parent) return findState(state.parent);
+ // regex matches any valid composite state name
+ // would match "contact.list" but not "contacts"
+ var compositeName = /^(.+)\.[^.]+$/.exec(state.name);
+ return compositeName ? findState(compositeName[1]) : root;
+ },
+
+ // inherit 'data' from parent and override by own values (if any)
+ data: function(state) {
+ if (state.parent && state.parent.data) {
+ state.data = state.self.data = extend({}, state.parent.data, state.data);
+ }
+ return state.data;
+ },
+
+ // Build a URLMatcher if necessary, either via a relative or absolute URL
+ url: function(state) {
+ var url = state.url, config = { params: state.params || {} };
+
+ if (isString(url)) {
+ if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);
+ return (state.parent.navigable || root).url.concat(url, config);
+ }
+
+ if (!url || $urlMatcherFactory.isMatcher(url)) return url;
+ throw new Error("Invalid url '" + url + "' in state '" + state + "'");
+ },
+
+ // Keep track of the closest ancestor state that has a URL (i.e. is navigable)
+ navigable: function(state) {
+ return state.url ? state : (state.parent ? state.parent.navigable : null);
+ },
+
+ // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params
+ ownParams: function(state) {
+ var params = state.url && state.url.params || new $$UMFP.ParamSet();
+ forEach(state.params || {}, function(config, id) {
+ if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config");
+ });
+ return params;
+ },
+
+ // Derive parameters for this state and ensure they're a super-set of parent's parameters
+ params: function(state) {
+ return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet();
+ },
+
+ // If there is no explicit multi-view configuration, make one up so we don't have
+ // to handle both cases in the view directive later. Note that having an explicit
+ // 'views' property will mean the default unnamed view properties are ignored. This
+ // is also a good time to resolve view names to absolute names, so everything is a
+ // straight lookup at link time.
+ views: function(state) {
+ var views = {};
+
+ forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {
+ if (name.indexOf('@') < 0) name += '@' + state.parent.name;
+ views[name] = view;
+ });
+ return views;
+ },
+
+ // Keep a full path from the root down to this state as this is needed for state activation.
+ path: function(state) {
+ return state.parent ? state.parent.path.concat(state) : []; // exclude root from path
+ },
+
+ // Speed up $state.contains() as it's used a lot
+ includes: function(state) {
+ var includes = state.parent ? extend({}, state.parent.includes) : {};
+ includes[state.name] = true;
+ return includes;
+ },
+
+ $delegates: {}
+ };
+
+ function isRelative(stateName) {
+ return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
+ }
+
+ function findState(stateOrName, base) {
+ if (!stateOrName) return undefined;
+
+ var isStr = isString(stateOrName),
+ name = isStr ? stateOrName : stateOrName.name,
+ path = isRelative(name);
+
+ if (path) {
+ if (!base) throw new Error("No reference point given for path '" + name + "'");
+ base = findState(base);
+
+ var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
+
+ for (; i < pathLength; i++) {
+ if (rel[i] === "" && i === 0) {
+ current = base;
+ continue;
+ }
+ if (rel[i] === "^") {
+ if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
+ current = current.parent;
+ continue;
+ }
+ break;
+ }
+ rel = rel.slice(i).join(".");
+ name = current.name + (current.name && rel ? "." : "") + rel;
+ }
+ var state = states[name];
+
+ if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
+ return state;
+ }
+ return undefined;
+ }
+
+ function queueState(parentName, state) {
+ if (!queue[parentName]) {
+ queue[parentName] = [];
+ }
+ queue[parentName].push(state);
+ }
+
+ function flushQueuedChildren(parentName) {
+ var queued = queue[parentName] || [];
+ while(queued.length) {
+ registerState(queued.shift());
+ }
+ }
+
+ function registerState(state) {
+ // Wrap a new object around the state so we can store our private details easily.
+ state = inherit(state, {
+ self: state,
+ resolve: state.resolve || {},
+ toString: function() { return this.name; }
+ });
+
+ var name = state.name;
+ if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
+ if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined");
+
+ // Get parent name
+ var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))
+ : (isString(state.parent)) ? state.parent
+ : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name
+ : '';
+
+ // If parent is not registered yet, add state to queue and register later
+ if (parentName && !states[parentName]) {
+ return queueState(parentName, state.self);
+ }
+
+ for (var key in stateBuilder) {
+ if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
+ }
+ states[name] = state;
+
+ // Register the state in the global state list and with $urlRouter if necessary.
+ if (!state[abstractKey] && state.url) {
+ $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
+ if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
+ $state.transitionTo(state, $match, { inherit: true, location: false });
+ }
+ }]);
+ }
+
+ // Register any queued children
+ flushQueuedChildren(name);
+
+ return state;
+ }
+
+ // Checks text to see if it looks like a glob.
+ function isGlob (text) {
+ return text.indexOf('*') > -1;
+ }
+
+ // Returns true if glob matches current $state name.
+ function doesStateMatchGlob (glob) {
+ var globSegments = glob.split('.'),
+ segments = $state.$current.name.split('.');
+
+ //match single stars
+ for (var i = 0, l = globSegments.length; i < l; i++) {
+ if (globSegments[i] === '*') {
+ segments[i] = '*';
+ }
+ }
+
+ //match greedy starts
+ if (globSegments[0] === '**') {
+ segments = segments.slice(indexOf(segments, globSegments[1]));
+ segments.unshift('**');
+ }
+ //match greedy ends
+ if (globSegments[globSegments.length - 1] === '**') {
+ segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);
+ segments.push('**');
+ }
+
+ if (globSegments.length != segments.length) {
+ return false;
+ }
+
+ return segments.join('') === globSegments.join('');
+ }
+
+
+ // Implicit root state that is always active
+ root = registerState({
+ name: '',
+ url: '^',
+ views: null,
+ 'abstract': true
+ });
+ root.navigable = null;
+
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$stateProvider#decorator
+ * @methodOf ui.router.state.$stateProvider
+ *
+ * @description
+ * Allows you to extend (carefully) or override (at your own peril) the
+ * `stateBuilder` object used internally by `$stateProvider`. This can be used
+ * to add custom functionality to ui-router, for example inferring templateUrl
+ * based on the state name.
+ *
+ * When passing only a name, it returns the current (original or decorated) builder
+ * function that matches `name`.
+ *
+ * The builder functions that can be decorated are listed below. Though not all
+ * necessarily have a good use case for decoration, that is up to you to decide.
+ *
+ * In addition, users can attach custom decorators, which will generate new
+ * properties within the state's internal definition. There is currently no clear
+ * use-case for this beyond accessing internal states (i.e. $state.$current),
+ * however, expect this to become increasingly relevant as we introduce additional
+ * meta-programming features.
+ *
+ * **Warning**: Decorators should not be interdependent because the order of
+ * execution of the builder functions in non-deterministic. Builder functions
+ * should only be dependent on the state definition object and super function.
+ *
+ *
+ * Existing builder functions and current return values:
+ *
+ * - **parent** `{object}` - returns the parent state object.
+ * - **data** `{object}` - returns state data, including any inherited data that is not
+ * overridden by own values (if any).
+ * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
+ * or `null`.
+ * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
+ * navigable).
+ * - **params** `{object}` - returns an array of state params that are ensured to
+ * be a super-set of parent's params.
+ * - **views** `{object}` - returns a views object where each key is an absolute view
+ * name (i.e. "viewName@stateName") and each value is the config object
+ * (template, controller) for the view. Even when you don't use the views object
+ * explicitly on a state config, one is still created for you internally.
+ * So by decorating this builder function you have access to decorating template
+ * and controller properties.
+ * - **ownParams** `{object}` - returns an array of params that belong to the state,
+ * not including any params defined by ancestor states.
+ * - **path** `{string}` - returns the full path from the root down to this state.
+ * Needed for state activation.
+ * - **includes** `{object}` - returns an object that includes every state that
+ * would pass a `$state.includes()` test.
+ *
+ * @example
+ * <pre>
+ * // Override the internal 'views' builder with a function that takes the state
+ * // definition, and a reference to the internal function being overridden:
+ * $stateProvider.decorator('views', function (state, parent) {
+ * var result = {},
+ * views = parent(state);
+ *
+ * angular.forEach(views, function (config, name) {
+ * var autoName = (state.name + '.' + name).replace('.', '/');
+ * config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
+ * result[name] = config;
+ * });
+ * return result;
+ * });
+ *
+ * $stateProvider.state('home', {
+ * views: {
+ * 'contact.list': { controller: 'ListController' },
+ * 'contact.item': { controller: 'ItemController' }
+ * }
+ * });
+ *
+ * // ...
+ *
+ * $state.go('home');
+ * // Auto-populates list and item views with /partials/home/contact/list.html,
+ * // and /partials/home/contact/item.html, respectively.
+ * </pre>
+ *
+ * @param {string} name The name of the builder function to decorate.
+ * @param {object} func A function that is responsible for decorating the original
+ * builder function. The function receives two parameters:
+ *
+ * - `{object}` - state - The state config object.
+ * - `{object}` - super - The original builder function.
+ *
+ * @return {object} $stateProvider - $stateProvider instance
+ */
+ this.decorator = decorator;
+ function decorator(name, func) {
+ /*jshint validthis: true */
+ if (isString(name) && !isDefined(func)) {
+ return stateBuilder[name];
+ }
+ if (!isFunction(func) || !isString(name)) {
+ return this;
+ }
+ if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
+ stateBuilder.$delegates[name] = stateBuilder[name];
+ }
+ stateBuilder[name] = func;
+ return this;
+ }
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$stateProvider#state
+ * @methodOf ui.router.state.$stateProvider
+ *
+ * @description
+ * Registers a state configuration under a given state name. The stateConfig object
+ * has the following acceptable properties.
+ *
+ * @param {string} name A unique state name, e.g. "home", "about", "contacts".
+ * To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
+ * @param {object} stateConfig State configuration object.
+ * @param {string|function=} stateConfig.template
+ * <a id='template'></a>
+ * html template as a string or a function that returns
+ * an html template as a string which should be used by the uiView directives. This property
+ * takes precedence over templateUrl.
+ *
+ * If `template` is a function, it will be called with the following parameters:
+ *
+ * - {array.<object>} - state parameters extracted from the current $location.path() by
+ * applying the current state
+ *
+ * <pre>template:
+ * "<h1>inline template definition</h1>" +
+ * "<div ui-view></div>"</pre>
+ * <pre>template: function(params) {
+ * return "<h1>generated template</h1>"; }</pre>
+ * </div>
+ *
+ * @param {string|function=} stateConfig.templateUrl
+ * <a id='templateUrl'></a>
+ *
+ * path or function that returns a path to an html
+ * template that should be used by uiView.
+ *
+ * If `templateUrl` is a function, it will be called with the following parameters:
+ *
+ * - {array.<object>} - state parameters extracted from the current $location.path() by
+ * applying the current state
+ *
+ * <pre>templateUrl: "home.html"</pre>
+ * <pre>templateUrl: function(params) {
+ * return myTemplates[params.pageId]; }</pre>
+ *
+ * @param {function=} stateConfig.templateProvider
+ * <a id='templateProvider'></a>
+ * Provider function that returns HTML content string.
+ * <pre> templateProvider:
+ * function(MyTemplateService, params) {
+ * return MyTemplateService.getTemplate(params.pageId);
+ * }</pre>
+ *
+ * @param {string|function=} stateConfig.controller
+ * <a id='controller'></a>
+ *
+ * Controller fn that should be associated with newly
+ * related scope or the name of a registered controller if passed as a string.
+ * Optionally, the ControllerAs may be declared here.
+ * <pre>controller: "MyRegisteredController"</pre>
+ * <pre>controller:
+ * "MyRegisteredController as fooCtrl"}</pre>
+ * <pre>controller: function($scope, MyService) {
+ * $scope.data = MyService.getData(); }</pre>
+ *
+ * @param {function=} stateConfig.controllerProvider
+ * <a id='controllerProvider'></a>
+ *
+ * Injectable provider function that returns the actual controller or string.
+ * <pre>controllerProvider:
+ * function(MyResolveData) {
+ * if (MyResolveData.foo)
+ * return "FooCtrl"
+ * else if (MyResolveData.bar)
+ * return "BarCtrl";
+ * else return function($scope) {
+ * $scope.baz = "Qux";
+ * }
+ * }</pre>
+ *
+ * @param {string=} stateConfig.controllerAs
+ * <a id='controllerAs'></a>
+ *
+ * A controller alias name. If present the controller will be
+ * published to scope under the controllerAs name.
+ * <pre>controllerAs: "myCtrl"</pre>
+ *
+ * @param {string|object=} stateConfig.parent
+ * <a id='parent'></a>
+ * Optionally specifies the parent state of this state.
+ *
+ * <pre>parent: 'parentState'</pre>
+ * <pre>parent: parentState // JS variable</pre>
+ *
+ * @param {object=} stateConfig.resolve
+ * <a id='resolve'></a>
+ *
+ * An optional map<string, function> of dependencies which
+ * should be injected into the controller. If any of these dependencies are promises,
+ * the router will wait for them all to be resolved before the controller is instantiated.
+ * If all the promises are resolved successfully, the $stateChangeSuccess event is fired
+ * and the values of the resolved promises are injected into any controllers that reference them.
+ * If any of the promises are rejected the $stateChangeError event is fired.
+ *
+ * The map object is:
+ *
+ * - key - {string}: name of dependency to be injected into controller
+ * - factory - {string|function}: If string then it is alias for service. Otherwise if function,
+ * it is injected and return value it treated as dependency. If result is a promise, it is
+ * resolved before its value is injected into controller.
+ *
+ * <pre>resolve: {
+ * myResolve1:
+ * function($http, $stateParams) {
+ * return $http.get("/api/foos/"+stateParams.fooID);
+ * }
+ * }</pre>
+ *
+ * @param {string=} stateConfig.url
+ * <a id='url'></a>
+ *
+ * A url fragment with optional parameters. When a state is navigated or
+ * transitioned to, the `$stateParams` service will be populated with any
+ * parameters that were passed.
+ *
+ * (See {@link ui.router.util.type:UrlMatcher UrlMatcher} `UrlMatcher`} for
+ * more details on acceptable patterns )
+ *
+ * examples:
+ * <pre>url: "/home"
+ * url: "/users/:userid"
+ * url: "/books/{bookid:[a-zA-Z_-]}"
+ * url: "/books/{categoryid:int}"
+ * url: "/books/{publishername:string}/{categoryid:int}"
+ * url: "/messages?before&after"
+ * url: "/messages?{before:date}&{after:date}"
+ * url: "/messages/:mailboxid?{before:date}&{after:date}"
+ * </pre>
+ *
+ * @param {object=} stateConfig.views
+ * <a id='views'></a>
+ * an optional map<string, object> which defined multiple views, or targets views
+ * manually/explicitly.
+ *
+ * Examples:
+ *
+ * Targets three named `ui-view`s in the parent state's template
+ * <pre>views: {
+ * header: {
+ * controller: "headerCtrl",
+ * templateUrl: "header.html"
+ * }, body: {
+ * controller: "bodyCtrl",
+ * templateUrl: "body.html"
+ * }, footer: {
+ * controller: "footCtrl",
+ * templateUrl: "footer.html"
+ * }
+ * }</pre>
+ *
+ * Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template.
+ * <pre>views: {
+ * 'header@top': {
+ * controller: "msgHeaderCtrl",
+ * templateUrl: "msgHeader.html"
+ * }, 'body': {
+ * controller: "messagesCtrl",
+ * templateUrl: "messages.html"
+ * }
+ * }</pre>
+ *
+ * @param {boolean=} [stateConfig.abstract=false]
+ * <a id='abstract'></a>
+ * An abstract state will never be directly activated,
+ * but can provide inherited properties to its common children states.
+ * <pre>abstract: true</pre>
+ *
+ * @param {function=} stateConfig.onEnter
+ * <a id='onEnter'></a>
+ *
+ * Callback function for when a state is entered. Good way
+ * to trigger an action or dispatch an event, such as opening a dialog.
+ * If minifying your scripts, make sure to explictly annotate this function,
+ * because it won't be automatically annotated by your build tools.
+ *
+ * <pre>onEnter: function(MyService, $stateParams) {
+ * MyService.foo($stateParams.myParam);
+ * }</pre>
+ *
+ * @param {function=} stateConfig.onExit
+ * <a id='onExit'></a>
+ *
+ * Callback function for when a state is exited. Good way to
+ * trigger an action or dispatch an event, such as opening a dialog.
+ * If minifying your scripts, make sure to explictly annotate this function,
+ * because it won't be automatically annotated by your build tools.
+ *
+ * <pre>onExit: function(MyService, $stateParams) {
+ * MyService.cleanup($stateParams.myParam);
+ * }</pre>
+ *
+ * @param {boolean=} [stateConfig.reloadOnSearch=true]
+ * <a id='reloadOnSearch'></a>
+ *
+ * If `false`, will not retrigger the same state
+ * just because a search/query parameter has changed (via $location.search() or $location.hash()).
+ * Useful for when you'd like to modify $location.search() without triggering a reload.
+ * <pre>reloadOnSearch: false</pre>
+ *
+ * @param {object=} stateConfig.data
+ * <a id='data'></a>
+ *
+ * Arbitrary data object, useful for custom configuration. The parent state's `data` is
+ * prototypally inherited. In other words, adding a data property to a state adds it to
+ * the entire subtree via prototypal inheritance.
+ *
+ * <pre>data: {
+ * requiredRole: 'foo'
+ * } </pre>
+ *
+ * @param {object=} stateConfig.params
+ * <a id='params'></a>
+ *
+ * A map which optionally configures parameters declared in the `url`, or
+ * defines additional non-url parameters. For each parameter being
+ * configured, add a configuration object keyed to the name of the parameter.
+ *
+ * Each parameter configuration object may contain the following properties:
+ *
+ * - ** value ** - {object|function=}: specifies the default value for this
+ * parameter. This implicitly sets this parameter as optional.
+ *
+ * When UI-Router routes to a state and no value is
+ * specified for this parameter in the URL or transition, the
+ * default value will be used instead. If `value` is a function,
+ * it will be injected and invoked, and the return value used.
+ *
+ * *Note*: `undefined` is treated as "no default value" while `null`
+ * is treated as "the default value is `null`".
+ *
+ * *Shorthand*: If you only need to configure the default value of the
+ * parameter, you may use a shorthand syntax. In the **`params`**
+ * map, instead mapping the param name to a full parameter configuration
+ * object, simply set map it to the default parameter value, e.g.:
+ *
+ * <pre>// define a parameter's default value
+ * params: {
+ * param1: { value: "defaultValue" }
+ * }
+ * // shorthand default values
+ * params: {
+ * param1: "defaultValue",
+ * param2: "param2Default"
+ * }</pre>
+ *
+ * - ** array ** - {boolean=}: *(default: false)* If true, the param value will be
+ * treated as an array of values. If you specified a Type, the value will be
+ * treated as an array of the specified Type. Note: query parameter values
+ * default to a special `"auto"` mode.
+ *
+ * For query parameters in `"auto"` mode, if multiple values for a single parameter
+ * are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values
+ * are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`). However, if
+ * only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single
+ * value (e.g.: `{ foo: '1' }`).
+ *
+ * <pre>params: {
+ * param1: { array: true }
+ * }</pre>
+ *
+ * - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when
+ * the current parameter value is the same as the default value. If `squash` is not set, it uses the
+ * configured default squash policy.
+ * (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})
+ *
+ * There are three squash settings:
+ *
+ * - false: The parameter's default value is not squashed. It is encoded and included in the URL
+ * - true: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed
+ * by slashes in the state's `url` declaration, then one of those slashes are omitted.
+ * This can allow for cleaner looking URLs.
+ * - `"<arbitrary string>"`: The parameter's default value is replaced with an arbitrary placeholder of your choice.
+ *
+ * <pre>params: {
+ * param1: {
+ * value: "defaultId",
+ * squash: true
+ * } }
+ * // squash "defaultValue" to "~"
+ * params: {
+ * param1: {
+ * value: "defaultValue",
+ * squash: "~"
+ * } }
+ * </pre>
+ *
+ *
+ * @example
+ * <pre>
+ * // Some state name examples
+ *
+ * // stateName can be a single top-level name (must be unique).
+ * $stateProvider.state("home", {});
+ *
+ * // Or it can be a nested state name. This state is a child of the
+ * // above "home" state.
+ * $stateProvider.state("home.newest", {});
+ *
+ * // Nest states as deeply as needed.
+ * $stateProvider.state("home.newest.abc.xyz.inception", {});
+ *
+ * // state() returns $stateProvider, so you can chain state declarations.
+ * $stateProvider
+ * .state("home", {})
+ * .state("about", {})
+ * .state("contacts", {});
+ * </pre>
+ *
+ */
+ this.state = state;
+ function state(name, definition) {
+ /*jshint validthis: true */
+ if (isObject(name)) definition = name;
+ else definition.name = name;
+ registerState(definition);
+ return this;
+ }
+
+ /**
+ * @ngdoc object
+ * @name ui.router.state.$state
+ *
+ * @requires $rootScope
+ * @requires $q
+ * @requires ui.router.state.$view
+ * @requires $injector
+ * @requires ui.router.util.$resolve
+ * @requires ui.router.state.$stateParams
+ * @requires ui.router.router.$urlRouter
+ *
+ * @property {object} params A param object, e.g. {sectionId: section.id)}, that
+ * you'd like to test against the current active state.
+ * @property {object} current A reference to the state's config object. However
+ * you passed it in. Useful for accessing custom data.
+ * @property {object} transition Currently pending transition. A promise that'll
+ * resolve or reject.
+ *
+ * @description
+ * `$state` service is responsible for representing states as well as transitioning
+ * between them. It also provides interfaces to ask for current state or even states
+ * you're coming from.
+ */
+ this.$get = $get;
+ $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];
+ function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) {
+
+ var TransitionSuperseded = $q.reject(new Error('transition superseded'));
+ var TransitionPrevented = $q.reject(new Error('transition prevented'));
+ var TransitionAborted = $q.reject(new Error('transition aborted'));
+ var TransitionFailed = $q.reject(new Error('transition failed'));
+
+ // Handles the case where a state which is the target of a transition is not found, and the user
+ // can optionally retry or defer the transition
+ function handleRedirect(redirect, state, params, options) {
+ /**
+ * @ngdoc event
+ * @name ui.router.state.$state#$stateNotFound
+ * @eventOf ui.router.state.$state
+ * @eventType broadcast on root scope
+ * @description
+ * Fired when a requested state **cannot be found** using the provided state name during transition.
+ * The event is broadcast allowing any handlers a single chance to deal with the error (usually by
+ * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,
+ * you can see its three properties in the example. You can use `event.preventDefault()` to abort the
+ * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.
+ *
+ * @param {Object} event Event object.
+ * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.
+ * @param {State} fromState Current state object.
+ * @param {Object} fromParams Current state params.
+ *
+ * @example
+ *
+ * <pre>
+ * // somewhere, assume lazy.state has not been defined
+ * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
+ *
+ * // somewhere else
+ * $scope.$on('$stateNotFound',
+ * function(event, unfoundState, fromState, fromParams){
+ * console.log(unfoundState.to); // "lazy.state"
+ * console.log(unfoundState.toParams); // {a:1, b:2}
+ * console.log(unfoundState.options); // {inherit:false} + default options
+ * })
+ * </pre>
+ */
+ var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);
+
+ if (evt.defaultPrevented) {
+ $urlRouter.update();
+ return TransitionAborted;
+ }
+
+ if (!evt.retry) {
+ return null;
+ }
+
+ // Allow the handler to return a promise to defer state lookup retry
+ if (options.$retry) {
+ $urlRouter.update();
+ return TransitionFailed;
+ }
+ var retryTransition = $state.transition = $q.when(evt.retry);
+
+ retryTransition.then(function() {
+ if (retryTransition !== $state.transition) return TransitionSuperseded;
+ redirect.options.$retry = true;
+ return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);
+ }, function() {
+ return TransitionAborted;
+ });
+ $urlRouter.update();
+
+ return retryTransition;
+ }
+
+ root.locals = { resolve: null, globals: { $stateParams: {} } };
+
+ $state = {
+ params: {},
+ current: root.self,
+ $current: root,
+ transition: null
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#reload
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * A method that force reloads the current state. All resolves are re-resolved,
+ * controllers reinstantiated, and events re-fired.
+ *
+ * @example
+ * <pre>
+ * var app angular.module('app', ['ui.router']);
+ *
+ * app.controller('ctrl', function ($scope, $state) {
+ * $scope.reload = function(){
+ * $state.reload();
+ * }
+ * });
+ * </pre>
+ *
+ * `reload()` is just an alias for:
+ * <pre>
+ * $state.transitionTo($state.current, $stateParams, {
+ * reload: true, inherit: false, notify: true
+ * });
+ * </pre>
+ *
+ * @param {string=|object=} state - A state name or a state object, which is the root of the resolves to be re-resolved.
+ * @example
+ * <pre>
+ * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'
+ * //and current state is 'contacts.detail.item'
+ * var app angular.module('app', ['ui.router']);
+ *
+ * app.controller('ctrl', function ($scope, $state) {
+ * $scope.reload = function(){
+ * //will reload 'contact.detail' and 'contact.detail.item' states
+ * $state.reload('contact.detail');
+ * }
+ * });
+ * </pre>
+ *
+ * `reload()` is just an alias for:
+ * <pre>
+ * $state.transitionTo($state.current, $stateParams, {
+ * reload: true, inherit: false, notify: true
+ * });
+ * </pre>
+
+ * @returns {promise} A promise representing the state of the new transition. See
+ * {@link ui.router.state.$state#methods_go $state.go}.
+ */
+ $state.reload = function reload(state) {
+ return $state.transitionTo($state.current, $stateParams, { reload: state || true, inherit: false, notify: true});
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#go
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * Convenience method for transitioning to a new state. `$state.go` calls
+ * `$state.transitionTo` internally but automatically sets options to
+ * `{ location: true, inherit: true, relative: $state.$current, notify: true }`.
+ * This allows you to easily use an absolute or relative to path and specify
+ * only the parameters you'd like to update (while letting unspecified parameters
+ * inherit from the currently active ancestor states).
+ *
+ * @example
+ * <pre>
+ * var app = angular.module('app', ['ui.router']);
+ *
+ * app.controller('ctrl', function ($scope, $state) {
+ * $scope.changeState = function () {
+ * $state.go('contact.detail');
+ * };
+ * });
+ * </pre>
+ * <img src='../ngdoc_assets/StateGoExamples.png'/>
+ *
+ * @param {string} to Absolute state name or relative state path. Some examples:
+ *
+ * - `$state.go('contact.detail')` - will go to the `contact.detail` state
+ * - `$state.go('^')` - will go to a parent state
+ * - `$state.go('^.sibling')` - will go to a sibling state
+ * - `$state.go('.child.grandchild')` - will go to grandchild state
+ *
+ * @param {object=} params A map of the parameters that will be sent to the state,
+ * will populate $stateParams. Any parameters that are not specified will be inherited from currently
+ * defined parameters. This allows, for example, going to a sibling state that shares parameters
+ * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.
+ * transitioning to a sibling will get you the parameters for all parents, transitioning to a child
+ * will get you all current parameters, etc.
+ * @param {object=} options Options object. The options are:
+ *
+ * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
+ * will not. If string, must be `"replace"`, which will update url and also replace last history record.
+ * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
+ * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
+ * defines which state to be relative from.
+ * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
+ * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
+ * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
+ * use this when you want to force a reload when *everything* is the same, including search params.
+ *
+ * @returns {promise} A promise representing the state of the new transition.
+ *
+ * Possible success values:
+ *
+ * - $state.current
+ *
+ * <br/>Possible rejection values:
+ *
+ * - 'transition superseded' - when a newer transition has been started after this one
+ * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener
+ * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or
+ * when a `$stateNotFound` `event.retry` promise errors.
+ * - 'transition failed' - when a state has been unsuccessfully found after 2 tries.
+ * - *resolve error* - when an error has occurred with a `resolve`
+ *
+ */
+ $state.go = function go(to, params, options) {
+ return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#transitionTo
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
+ * uses `transitionTo` internally. `$state.go` is recommended in most situations.
+ *
+ * @example
+ * <pre>
+ * var app = angular.module('app', ['ui.router']);
+ *
+ * app.controller('ctrl', function ($scope, $state) {
+ * $scope.changeState = function () {
+ * $state.transitionTo('contact.detail');
+ * };
+ * });
+ * </pre>
+ *
+ * @param {string} to State name.
+ * @param {object=} toParams A map of the parameters that will be sent to the state,
+ * will populate $stateParams.
+ * @param {object=} options Options object. The options are:
+ *
+ * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
+ * will not. If string, must be `"replace"`, which will update url and also replace last history record.
+ * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
+ * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'),
+ * defines which state to be relative from.
+ * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
+ * - **`reload`** (v0.2.5) - {boolean=false|string=|object=}, If `true` will force transition even if the state or params
+ * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
+ * use this when you want to force a reload when *everything* is the same, including search params.
+ * if String, then will reload the state with the name given in reload, and any children.
+ * if Object, then a stateObj is expected, will reload the state found in stateObj, and any children.
+ *
+ * @returns {promise} A promise representing the state of the new transition. See
+ * {@link ui.router.state.$state#methods_go $state.go}.
+ */
+ $state.transitionTo = function transitionTo(to, toParams, options) {
+ toParams = toParams || {};
+ options = extend({
+ location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
+ }, options || {});
+
+ var from = $state.$current, fromParams = $state.params, fromPath = from.path;
+ var evt, toState = findState(to, options.relative);
+
+ // Store the hash param for later (since it will be stripped out by various methods)
+ var hash = toParams['#'];
+
+ if (!isDefined(toState)) {
+ var redirect = { to: to, toParams: toParams, options: options };
+ var redirectResult = handleRedirect(redirect, from.self, fromParams, options);
+
+ if (redirectResult) {
+ return redirectResult;
+ }
+
+ // Always retry once if the $stateNotFound was not prevented
+ // (handles either redirect changed or state lazy-definition)
+ to = redirect.to;
+ toParams = redirect.toParams;
+ options = redirect.options;
+ toState = findState(to, options.relative);
+
+ if (!isDefined(toState)) {
+ if (!options.relative) throw new Error("No such state '" + to + "'");
+ throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
+ }
+ }
+ if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'");
+ if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);
+ if (!toState.params.$$validates(toParams)) return TransitionFailed;
+
+ toParams = toState.params.$$values(toParams);
+ to = toState;
+
+ var toPath = to.path;
+
+ // Starting from the root of the path, keep all levels that haven't changed
+ var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];
+
+ if (!options.reload) {
+ while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {
+ locals = toLocals[keep] = state.locals;
+ keep++;
+ state = toPath[keep];
+ }
+ } else if (isString(options.reload) || isObject(options.reload)) {
+ if (isObject(options.reload) && !options.reload.name) {
+ throw new Error('Invalid reload state object');
+ }
+
+ var reloadState = options.reload === true ? fromPath[0] : findState(options.reload);
+ if (options.reload && !reloadState) {
+ throw new Error("No such reload state '" + (isString(options.reload) ? options.reload : options.reload.name) + "'");
+ }
+
+ while (state && state === fromPath[keep] && state !== reloadState) {
+ locals = toLocals[keep] = state.locals;
+ keep++;
+ state = toPath[keep];
+ }
+ }
+
+ // If we're going to the same state and all locals are kept, we've got nothing to do.
+ // But clear 'transition', as we still want to cancel any other pending transitions.
+ // TODO: We may not want to bump 'transition' if we're called from a location change
+ // that we've initiated ourselves, because we might accidentally abort a legitimate
+ // transition initiated from code?
+ if (shouldSkipReload(to, toParams, from, fromParams, locals, options)) {
+ if (hash) toParams['#'] = hash;
+ $state.params = toParams;
+ copy($state.params, $stateParams);
+ if (options.location && to.navigable && to.navigable.url) {
+ $urlRouter.push(to.navigable.url, toParams, {
+ $$avoidResync: true, replace: options.location === 'replace'
+ });
+ $urlRouter.update(true);
+ }
+ $state.transition = null;
+ return $q.when($state.current);
+ }
+
+ // Filter parameters before we pass them to event handlers etc.
+ toParams = filterByKeys(to.params.$$keys(), toParams || {});
+
+ // Broadcast start event and cancel the transition if requested
+ if (options.notify) {
+ /**
+ * @ngdoc event
+ * @name ui.router.state.$state#$stateChangeStart
+ * @eventOf ui.router.state.$state
+ * @eventType broadcast on root scope
+ * @description
+ * Fired when the state transition **begins**. You can use `event.preventDefault()`
+ * to prevent the transition from happening and then the transition promise will be
+ * rejected with a `'transition prevented'` value.
+ *
+ * @param {Object} event Event object.
+ * @param {State} toState The state being transitioned to.
+ * @param {Object} toParams The params supplied to the `toState`.
+ * @param {State} fromState The current state, pre-transition.
+ * @param {Object} fromParams The params supplied to the `fromState`.
+ *
+ * @example
+ *
+ * <pre>
+ * $rootScope.$on('$stateChangeStart',
+ * function(event, toState, toParams, fromState, fromParams){
+ * event.preventDefault();
+ * // transitionTo() promise will be rejected with
+ * // a 'transition prevented' error
+ * })
+ * </pre>
+ */
+ if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {
+ $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams);
+ $urlRouter.update();
+ return TransitionPrevented;
+ }
+ }
+
+ // Resolve locals for the remaining states, but don't update any global state just
+ // yet -- if anything fails to resolve the current state needs to remain untouched.
+ // We also set up an inheritance chain for the locals here. This allows the view directive
+ // to quickly look up the correct definition for each view in the current state. Even
+ // though we create the locals object itself outside resolveState(), it is initially
+ // empty and gets filled asynchronously. We need to keep track of the promise for the
+ // (fully resolved) current locals, and pass this down the chain.
+ var resolved = $q.when(locals);
+
+ for (var l = keep; l < toPath.length; l++, state = toPath[l]) {
+ locals = toLocals[l] = inherit(locals);
+ resolved = resolveState(state, toParams, state === to, resolved, locals, options);
+ }
+
+ // Once everything is resolved, we are ready to perform the actual transition
+ // and return a promise for the new state. We also keep track of what the
+ // current promise is, so that we can detect overlapping transitions and
+ // keep only the outcome of the last transition.
+ var transition = $state.transition = resolved.then(function () {
+ var l, entering, exiting;
+
+ if ($state.transition !== transition) return TransitionSuperseded;
+
+ // Exit 'from' states not kept
+ for (l = fromPath.length - 1; l >= keep; l--) {
+ exiting = fromPath[l];
+ if (exiting.self.onExit) {
+ $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);
+ }
+ exiting.locals = null;
+ }
+
+ // Enter 'to' states not kept
+ for (l = keep; l < toPath.length; l++) {
+ entering = toPath[l];
+ entering.locals = toLocals[l];
+ if (entering.self.onEnter) {
+ $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);
+ }
+ }
+
+ // Re-add the saved hash before we start returning things
+ if (hash) toParams['#'] = hash;
+
+ // Run it again, to catch any transitions in callbacks
+ if ($state.transition !== transition) return TransitionSuperseded;
+
+ // Update globals in $state
+ $state.$current = to;
+ $state.current = to.self;
+ $state.params = toParams;
+ copy($state.params, $stateParams);
+ $state.transition = null;
+
+ if (options.location && to.navigable) {
+ $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {
+ $$avoidResync: true, replace: options.location === 'replace'
+ });
+ }
+
+ if (options.notify) {
+ /**
+ * @ngdoc event
+ * @name ui.router.state.$state#$stateChangeSuccess
+ * @eventOf ui.router.state.$state
+ * @eventType broadcast on root scope
+ * @description
+ * Fired once the state transition is **complete**.
+ *
+ * @param {Object} event Event object.
+ * @param {State} toState The state being transitioned to.
+ * @param {Object} toParams The params supplied to the `toState`.
+ * @param {State} fromState The current state, pre-transition.
+ * @param {Object} fromParams The params supplied to the `fromState`.
+ */
+ $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
+ }
+ $urlRouter.update(true);
+
+ return $state.current;
+ }, function (error) {
+ if ($state.transition !== transition) return TransitionSuperseded;
+
+ $state.transition = null;
+ /**
+ * @ngdoc event
+ * @name ui.router.state.$state#$stateChangeError
+ * @eventOf ui.router.state.$state
+ * @eventType broadcast on root scope
+ * @description
+ * Fired when an **error occurs** during transition. It's important to note that if you
+ * have any errors in your resolve functions (javascript errors, non-existent services, etc)
+ * they will not throw traditionally. You must listen for this $stateChangeError event to
+ * catch **ALL** errors.
+ *
+ * @param {Object} event Event object.
+ * @param {State} toState The state being transitioned to.
+ * @param {Object} toParams The params supplied to the `toState`.
+ * @param {State} fromState The current state, pre-transition.
+ * @param {Object} fromParams The params supplied to the `fromState`.
+ * @param {Error} error The resolve error object.
+ */
+ evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
+
+ if (!evt.defaultPrevented) {
+ $urlRouter.update();
+ }
+
+ return $q.reject(error);
+ });
+
+ return transition;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#is
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * Similar to {@link ui.router.state.$state#methods_includes $state.includes},
+ * but only checks for the full state name. If params is supplied then it will be
+ * tested for strict equality against the current active params object, so all params
+ * must match with none missing and no extras.
+ *
+ * @example
+ * <pre>
+ * $state.$current.name = 'contacts.details.item';
+ *
+ * // absolute name
+ * $state.is('contact.details.item'); // returns true
+ * $state.is(contactDetailItemStateObject); // returns true
+ *
+ * // relative name (. and ^), typically from a template
+ * // E.g. from the 'contacts.details' template
+ * <div ng-class="{highlighted: $state.is('.item')}">Item</div>
+ * </pre>
+ *
+ * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.
+ * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like
+ * to test against the current active state.
+ * @param {object=} options An options object. The options are:
+ *
+ * - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will
+ * test relative to `options.relative` state (or name).
+ *
+ * @returns {boolean} Returns true if it is the state.
+ */
+ $state.is = function is(stateOrName, params, options) {
+ options = extend({ relative: $state.$current }, options || {});
+ var state = findState(stateOrName, options.relative);
+
+ if (!isDefined(state)) { return undefined; }
+ if ($state.$current !== state) { return false; }
+ return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#includes
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * A method to determine if the current active state is equal to or is the child of the
+ * state stateName. If any params are passed then they will be tested for a match as well.
+ * Not all the parameters need to be passed, just the ones you'd like to test for equality.
+ *
+ * @example
+ * Partial and relative names
+ * <pre>
+ * $state.$current.name = 'contacts.details.item';
+ *
+ * // Using partial names
+ * $state.includes("contacts"); // returns true
+ * $state.includes("contacts.details"); // returns true
+ * $state.includes("contacts.details.item"); // returns true
+ * $state.includes("contacts.list"); // returns false
+ * $state.includes("about"); // returns false
+ *
+ * // Using relative names (. and ^), typically from a template
+ * // E.g. from the 'contacts.details' template
+ * <div ng-class="{highlighted: $state.includes('.item')}">Item</div>
+ * </pre>
+ *
+ * Basic globbing patterns
+ * <pre>
+ * $state.$current.name = 'contacts.details.item.url';
+ *
+ * $state.includes("*.details.*.*"); // returns true
+ * $state.includes("*.details.**"); // returns true
+ * $state.includes("**.item.**"); // returns true
+ * $state.includes("*.details.item.url"); // returns true
+ * $state.includes("*.details.*.url"); // returns true
+ * $state.includes("*.details.*"); // returns false
+ * $state.includes("item.**"); // returns false
+ * </pre>
+ *
+ * @param {string} stateOrName A partial name, relative name, or glob pattern
+ * to be searched for within the current state name.
+ * @param {object=} params A param object, e.g. `{sectionId: section.id}`,
+ * that you'd like to test against the current active state.
+ * @param {object=} options An options object. The options are:
+ *
+ * - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set,
+ * .includes will test relative to `options.relative` state (or name).
+ *
+ * @returns {boolean} Returns true if it does include the state
+ */
+ $state.includes = function includes(stateOrName, params, options) {
+ options = extend({ relative: $state.$current }, options || {});
+ if (isString(stateOrName) && isGlob(stateOrName)) {
+ if (!doesStateMatchGlob(stateOrName)) {
+ return false;
+ }
+ stateOrName = $state.$current.name;
+ }
+
+ var state = findState(stateOrName, options.relative);
+ if (!isDefined(state)) { return undefined; }
+ if (!isDefined($state.$current.includes[state.name])) { return false; }
+ return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;
+ };
+
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#href
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * A url generation method that returns the compiled url for the given state populated with the given params.
+ *
+ * @example
+ * <pre>
+ * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
+ * </pre>
+ *
+ * @param {string|object} stateOrName The state name or state object you'd like to generate a url from.
+ * @param {object=} params An object of parameter values to fill the state's required parameters.
+ * @param {object=} options Options object. The options are:
+ *
+ * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the
+ * first parameter, then the constructed href url will be built from the first navigable ancestor (aka
+ * ancestor with a valid url).
+ * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
+ * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
+ * defines which state to be relative from.
+ * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
+ *
+ * @returns {string} compiled state url
+ */
+ $state.href = function href(stateOrName, params, options) {
+ options = extend({
+ lossy: true,
+ inherit: true,
+ absolute: false,
+ relative: $state.$current
+ }, options || {});
+
+ var state = findState(stateOrName, options.relative);
+
+ if (!isDefined(state)) return null;
+ if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);
+
+ var nav = (state && options.lossy) ? state.navigable : state;
+
+ if (!nav || nav.url === undefined || nav.url === null) {
+ return null;
+ }
+ return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys().concat('#'), params || {}), {
+ absolute: options.absolute
+ });
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#get
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * Returns the state configuration object for any specific state or all states.
+ *
+ * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for
+ * the requested state. If not provided, returns an array of ALL state configs.
+ * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.
+ * @returns {Object|Array} State configuration object or array of all objects.
+ */
+ $state.get = function (stateOrName, context) {
+ if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });
+ var state = findState(stateOrName, context || $state.$current);
+ return (state && state.self) ? state.self : null;
+ };
+
+ function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {
+ // Make a restricted $stateParams with only the parameters that apply to this state if
+ // necessary. In addition to being available to the controller and onEnter/onExit callbacks,
+ // we also need $stateParams to be available for any $injector calls we make during the
+ // dependency resolution process.
+ var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);
+ var locals = { $stateParams: $stateParams };
+
+ // Resolve 'global' dependencies for the state, i.e. those not specific to a view.
+ // We're also including $stateParams in this; that way the parameters are restricted
+ // to the set that should be visible to the state, and are independent of when we update
+ // the global $state and $stateParams values.
+ dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
+ var promises = [dst.resolve.then(function (globals) {
+ dst.globals = globals;
+ })];
+ if (inherited) promises.push(inherited);
+
+ function resolveViews() {
+ var viewsPromises = [];
+
+ // Resolve template and dependencies for all views.
+ forEach(state.views, function (view, name) {
+ var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});
+ injectables.$template = [ function () {
+ return $view.load(name, { view: view, locals: dst.globals, params: $stateParams, notify: options.notify }) || '';
+ }];
+
+ viewsPromises.push($resolve.resolve(injectables, dst.globals, dst.resolve, state).then(function (result) {
+ // References to the controller (only instantiated at link time)
+ if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {
+ var injectLocals = angular.extend({}, injectables, dst.globals);
+ result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);
+ } else {
+ result.$$controller = view.controller;
+ }
+ // Provide access to the state itself for internal use
+ result.$$state = state;
+ result.$$controllerAs = view.controllerAs;
+ dst[name] = result;
+ }));
+ });
+
+ return $q.all(viewsPromises).then(function(){
+ return dst.globals;
+ });
+ }
+
+ // Wait for all the promises and then return the activation object
+ return $q.all(promises).then(resolveViews).then(function (values) {
+ return dst;
+ });
+ }
+
+ return $state;
+ }
+
+ function shouldSkipReload(to, toParams, from, fromParams, locals, options) {
+ // Return true if there are no differences in non-search (path/object) params, false if there are differences
+ function nonSearchParamsEqual(fromAndToState, fromParams, toParams) {
+ // Identify whether all the parameters that differ between `fromParams` and `toParams` were search params.
+ function notSearchParam(key) {
+ return fromAndToState.params[key].location != "search";
+ }
+ var nonQueryParamKeys = fromAndToState.params.$$keys().filter(notSearchParam);
+ var nonQueryParams = pick.apply({}, [fromAndToState.params].concat(nonQueryParamKeys));
+ var nonQueryParamSet = new $$UMFP.ParamSet(nonQueryParams);
+ return nonQueryParamSet.$$equals(fromParams, toParams);
+ }
+
+ // If reload was not explicitly requested
+ // and we're transitioning to the same state we're already in
+ // and the locals didn't change
+ // or they changed in a way that doesn't merit reloading
+ // (reloadOnParams:false, or reloadOnSearch.false and only search params changed)
+ // Then return true.
+ if (!options.reload && to === from &&
+ (locals === from.locals || (to.self.reloadOnSearch === false && nonSearchParamsEqual(from, fromParams, toParams)))) {
+ return true;
+ }
+ }
+}
+
+angular.module('ui.router.state')
+ .value('$stateParams', {})
+ .provider('$state', $StateProvider);
+
+
+$ViewProvider.$inject = [];
+function $ViewProvider() {
+
+ this.$get = $get;
+ /**
+ * @ngdoc object
+ * @name ui.router.state.$view
+ *
+ * @requires ui.router.util.$templateFactory
+ * @requires $rootScope
+ *
+ * @description
+ *
+ */
+ $get.$inject = ['$rootScope', '$templateFactory'];
+ function $get( $rootScope, $templateFactory) {
+ return {
+ // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$view#load
+ * @methodOf ui.router.state.$view
+ *
+ * @description
+ *
+ * @param {string} name name
+ * @param {object} options option object.
+ */
+ load: function load(name, options) {
+ var result, defaults = {
+ template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}
+ };
+ options = extend(defaults, options);
+
+ if (options.view) {
+ result = $templateFactory.fromConfig(options.view, options.params, options.locals);
+ }
+ if (result && options.notify) {
+ /**
+ * @ngdoc event
+ * @name ui.router.state.$state#$viewContentLoading
+ * @eventOf ui.router.state.$view
+ * @eventType broadcast on root scope
+ * @description
+ *
+ * Fired once the view **begins loading**, *before* the DOM is rendered.
+ *
+ * @param {Object} event Event object.
+ * @param {Object} viewConfig The view config properties (template, controller, etc).
+ *
+ * @example
+ *
+ * <pre>
+ * $scope.$on('$viewContentLoading',
+ * function(event, viewConfig){
+ * // Access to all the view config properties.
+ * // and one special property 'targetView'
+ * // viewConfig.targetView
+ * });
+ * </pre>
+ */
+ $rootScope.$broadcast('$viewContentLoading', options);
+ }
+ return result;
+ }
+ };
+ }
+}
+
+angular.module('ui.router.state').provider('$view', $ViewProvider);
+
+/**
+ * @ngdoc object
+ * @name ui.router.state.$uiViewScrollProvider
+ *
+ * @description
+ * Provider that returns the {@link ui.router.state.$uiViewScroll} service function.
+ */
+function $ViewScrollProvider() {
+
+ var useAnchorScroll = false;
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll
+ * @methodOf ui.router.state.$uiViewScrollProvider
+ *
+ * @description
+ * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for
+ * scrolling based on the url anchor.
+ */
+ this.useAnchorScroll = function () {
+ useAnchorScroll = true;
+ };
+
+ /**
+ * @ngdoc object
+ * @name ui.router.state.$uiViewScroll
+ *
+ * @requires $anchorScroll
+ * @requires $timeout
+ *
+ * @description
+ * When called with a jqLite element, it scrolls the element into view (after a
+ * `$timeout` so the DOM has time to refresh).
+ *
+ * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,
+ * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.
+ */
+ this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {
+ if (useAnchorScroll) {
+ return $anchorScroll;
+ }
+
+ return function ($element) {
+ return $timeout(function () {
+ $element[0].scrollIntoView();
+ }, 0, false);
+ };
+ }];
+}
+
+angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);
+
+/**
+ * @ngdoc directive
+ * @name ui.router.state.directive:ui-view
+ *
+ * @requires ui.router.state.$state
+ * @requires $compile
+ * @requires $controller
+ * @requires $injector
+ * @requires ui.router.state.$uiViewScroll
+ * @requires $document
+ *
+ * @restrict ECA
+ *
+ * @description
+ * The ui-view directive tells $state where to place your templates.
+ *
+ * @param {string=} name A view name. The name should be unique amongst the other views in the
+ * same state. You can have views of the same name that live in different states.
+ *
+ * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window
+ * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll
+ * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you
+ * scroll ui-view elements into view when they are populated during a state activation.
+ *
+ * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)
+ * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*
+ *
+ * @param {string=} onload Expression to evaluate whenever the view updates.
+ *
+ * @example
+ * A view can be unnamed or named.
+ * <pre>
+ * <!-- Unnamed -->
+ * <div ui-view></div>
+ *
+ * <!-- Named -->
+ * <div ui-view="viewName"></div>
+ * </pre>
+ *
+ * You can only have one unnamed view within any template (or root html). If you are only using a
+ * single view and it is unnamed then you can populate it like so:
+ * <pre>
+ * <div ui-view></div>
+ * $stateProvider.state("home", {
+ * template: "<h1>HELLO!</h1>"
+ * })
+ * </pre>
+ *
+ * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`}
+ * config property, by name, in this case an empty name:
+ * <pre>
+ * $stateProvider.state("home", {
+ * views: {
+ * "": {
+ * template: "<h1>HELLO!</h1>"
+ * }
+ * }
+ * })
+ * </pre>
+ *
+ * But typically you'll only use the views property if you name your view or have more than one view
+ * in the same template. There's not really a compelling reason to name a view if its the only one,
+ * but you could if you wanted, like so:
+ * <pre>
+ * <div ui-view="main"></div>
+ * </pre>
+ * <pre>
+ * $stateProvider.state("home", {
+ * views: {
+ * "main": {
+ * template: "<h1>HELLO!</h1>"
+ * }
+ * }
+ * })
+ * </pre>
+ *
+ * Really though, you'll use views to set up multiple views:
+ * <pre>
+ * <div ui-view></div>
+ * <div ui-view="chart"></div>
+ * <div ui-view="data"></div>
+ * </pre>
+ *
+ * <pre>
+ * $stateProvider.state("home", {
+ * views: {
+ * "": {
+ * template: "<h1>HELLO!</h1>"
+ * },
+ * "chart": {
+ * template: "<chart_thing/>"
+ * },
+ * "data": {
+ * template: "<data_thing/>"
+ * }
+ * }
+ * })
+ * </pre>
+ *
+ * Examples for `autoscroll`:
+ *
+ * <pre>
+ * <!-- If autoscroll present with no expression,
+ * then scroll ui-view into view -->
+ * <ui-view autoscroll/>
+ *
+ * <!-- If autoscroll present with valid expression,
+ * then scroll ui-view into view if expression evaluates to true -->
+ * <ui-view autoscroll='true'/>
+ * <ui-view autoscroll='false'/>
+ * <ui-view autoscroll='scopeVariable'/>
+ * </pre>
+ */
+$ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate'];
+function $ViewDirective( $state, $injector, $uiViewScroll, $interpolate) {
+
+ function getService() {
+ return ($injector.has) ? function(service) {
+ return $injector.has(service) ? $injector.get(service) : null;
+ } : function(service) {
+ try {
+ return $injector.get(service);
+ } catch (e) {
+ return null;
+ }
+ };
+ }
+
+ var service = getService(),
+ $animator = service('$animator'),
+ $animate = service('$animate');
+
+ // Returns a set of DOM manipulation functions based on which Angular version
+ // it should use
+ function getRenderer(attrs, scope) {
+ var statics = function() {
+ return {
+ enter: function (element, target, cb) { target.after(element); cb(); },
+ leave: function (element, cb) { element.remove(); cb(); }
+ };
+ };
+
+ if ($animate) {
+ return {
+ enter: function(element, target, cb) {
+ var promise = $animate.enter(element, null, target, cb);
+ if (promise && promise.then) promise.then(cb);
+ },
+ leave: function(element, cb) {
+ var promise = $animate.leave(element, cb);
+ if (promise && promise.then) promise.then(cb);
+ }
+ };
+ }
+
+ if ($animator) {
+ var animate = $animator && $animator(scope, attrs);
+
+ return {
+ enter: function(element, target, cb) {animate.enter(element, null, target); cb(); },
+ leave: function(element, cb) { animate.leave(element); cb(); }
+ };
+ }
+
+ return statics();
+ }
+
+ var directive = {
+ restrict: 'ECA',
+ terminal: true,
+ priority: 400,
+ transclude: 'element',
+ compile: function (tElement, tAttrs, $transclude) {
+ return function (scope, $element, attrs) {
+ var previousEl, currentEl, currentScope, latestLocals,
+ onloadExp = attrs.onload || '',
+ autoScrollExp = attrs.autoscroll,
+ renderer = getRenderer(attrs, scope);
+
+ scope.$on('$stateChangeSuccess', function() {
+ updateView(false);
+ });
+ scope.$on('$viewContentLoading', function() {
+ updateView(false);
+ });
+
+ updateView(true);
+
+ function cleanupLastView() {
+ if (previousEl) {
+ previousEl.remove();
+ previousEl = null;
+ }
+
+ if (currentScope) {
+ currentScope.$destroy();
+ currentScope = null;
+ }
+
+ if (currentEl) {
+ renderer.leave(currentEl, function() {
+ previousEl = null;
+ });
+
+ previousEl = currentEl;
+ currentEl = null;
+ }
+ }
+
+ function updateView(firstTime) {
+ var newScope,
+ name = getUiViewName(scope, attrs, $element, $interpolate),
+ previousLocals = name && $state.$current && $state.$current.locals[name];
+
+ if (!firstTime && previousLocals === latestLocals) return; // nothing to do
+ newScope = scope.$new();
+ latestLocals = $state.$current.locals[name];
+
+ var clone = $transclude(newScope, function(clone) {
+ renderer.enter(clone, $element, function onUiViewEnter() {
+ if(currentScope) {
+ currentScope.$emit('$viewContentAnimationEnded');
+ }
+
+ if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {
+ $uiViewScroll(clone);
+ }
+ });
+ cleanupLastView();
+ });
+
+ currentEl = clone;
+ currentScope = newScope;
+ /**
+ * @ngdoc event
+ * @name ui.router.state.directive:ui-view#$viewContentLoaded
+ * @eventOf ui.router.state.directive:ui-view
+ * @eventType emits on ui-view directive scope
+ * @description *
+ * Fired once the view is **loaded**, *after* the DOM is rendered.
+ *
+ * @param {Object} event Event object.
+ */
+ currentScope.$emit('$viewContentLoaded');
+ currentScope.$eval(onloadExp);
+ }
+ };
+ }
+ };
+
+ return directive;
+}
+
+$ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];
+function $ViewDirectiveFill ( $compile, $controller, $state, $interpolate) {
+ return {
+ restrict: 'ECA',
+ priority: -400,
+ compile: function (tElement) {
+ var initial = tElement.html();
+ return function (scope, $element, attrs) {
+ var current = $state.$current,
+ name = getUiViewName(scope, attrs, $element, $interpolate),
+ locals = current && current.locals[name];
+
+ if (! locals) {
+ return;
+ }
+
+ $element.data('$uiView', { name: name, state: locals.$$state });
+ $element.html(locals.$template ? locals.$template : initial);
+
+ var link = $compile($element.contents());
+
+ if (locals.$$controller) {
+ locals.$scope = scope;
+ locals.$element = $element;
+ var controller = $controller(locals.$$controller, locals);
+ if (locals.$$controllerAs) {
+ scope[locals.$$controllerAs] = controller;
+ }
+ $element.data('$ngControllerController', controller);
+ $element.children().data('$ngControllerController', controller);
+ }
+
+ link(scope);
+ };
+ }
+ };
+}
+
+/**
+ * Shared ui-view code for both directives:
+ * Given scope, element, and its attributes, return the view's name
+ */
+function getUiViewName(scope, attrs, element, $interpolate) {
+ var name = $interpolate(attrs.uiView || attrs.name || '')(scope);
+ var inherited = element.inheritedData('$uiView');
+ return name.indexOf('@') >= 0 ? name : (name + '@' + (inherited ? inherited.state.name : ''));
+}
+
+angular.module('ui.router.state').directive('uiView', $ViewDirective);
+angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);
+
+function parseStateRef(ref, current) {
+ var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
+ if (preparsed) ref = current + '(' + preparsed[1] + ')';
+ parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
+ if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
+ return { state: parsed[1], paramExpr: parsed[3] || null };
+}
+
+function stateContext(el) {
+ var stateData = el.parent().inheritedData('$uiView');
+
+ if (stateData && stateData.state && stateData.state.name) {
+ return stateData.state;
+ }
+}
+
+/**
+ * @ngdoc directive
+ * @name ui.router.state.directive:ui-sref
+ *
+ * @requires ui.router.state.$state
+ * @requires $timeout
+ *
+ * @restrict A
+ *
+ * @description
+ * A directive that binds a link (`<a>` tag) to a state. If the state has an associated
+ * URL, the directive will automatically generate & update the `href` attribute via
+ * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking
+ * the link will trigger a state transition with optional parameters.
+ *
+ * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be
+ * handled natively by the browser.
+ *
+ * You can also use relative state paths within ui-sref, just like the relative
+ * paths passed to `$state.go()`. You just need to be aware that the path is relative
+ * to the state that the link lives in, in other words the state that loaded the
+ * template containing the link.
+ *
+ * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}
+ * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,
+ * and `reload`.
+ *
+ * @example
+ * Here's an example of how you'd use ui-sref and how it would compile. If you have the
+ * following template:
+ * <pre>
+ * <a ui-sref="home">Home</a> | <a ui-sref="about">About</a> | <a ui-sref="{page: 2}">Next page</a>
+ *
+ * <ul>
+ * <li ng-repeat="contact in contacts">
+ * <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
+ * </li>
+ * </ul>
+ * </pre>
+ *
+ * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):
+ * <pre>
+ * <a href="#/home" ui-sref="home">Home</a> | <a href="#/about" ui-sref="about">About</a> | <a href="#/contacts?page=2" ui-sref="{page: 2}">Next page</a>
+ *
+ * <ul>
+ * <li ng-repeat="contact in contacts">
+ * <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
+ * </li>
+ * <li ng-repeat="contact in contacts">
+ * <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
+ * </li>
+ * <li ng-repeat="contact in contacts">
+ * <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
+ * </li>
+ * </ul>
+ *
+ * <a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
+ * </pre>
+ *
+ * @param {string} ui-sref 'stateName' can be any valid absolute or relative state
+ * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}
+ */
+$StateRefDirective.$inject = ['$state', '$timeout'];
+function $StateRefDirective($state, $timeout) {
+ var allowedOptions = ['location', 'inherit', 'reload', 'absolute'];
+
+ return {
+ restrict: 'A',
+ require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
+ link: function(scope, element, attrs, uiSrefActive) {
+ var ref = parseStateRef(attrs.uiSref, $state.current.name);
+ var params = null, url = null, base = stateContext(element) || $state.$current;
+ // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
+ var hrefKind = Object.prototype.toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
+ 'xlink:href' : 'href';
+ var newHref = null, isAnchor = element.prop("tagName").toUpperCase() === "A";
+ var isForm = element[0].nodeName === "FORM";
+ var attr = isForm ? "action" : hrefKind, nav = true;
+
+ var options = { relative: base, inherit: true };
+ var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {};
+
+ angular.forEach(allowedOptions, function(option) {
+ if (option in optionsOverride) {
+ options[option] = optionsOverride[option];
+ }
+ });
+
+ var update = function(newVal) {
+ if (newVal) params = angular.copy(newVal);
+ if (!nav) return;
+
+ newHref = $state.href(ref.state, params, options);
+
+ var activeDirective = uiSrefActive[1] || uiSrefActive[0];
+ if (activeDirective) {
+ activeDirective.$$addStateInfo(ref.state, params);
+ }
+ if (newHref === null) {
+ nav = false;
+ return false;
+ }
+ attrs.$set(attr, newHref);
+ };
+
+ if (ref.paramExpr) {
+ scope.$watch(ref.paramExpr, function(newVal, oldVal) {
+ if (newVal !== params) update(newVal);
+ }, true);
+ params = angular.copy(scope.$eval(ref.paramExpr));
+ }
+ update();
+
+ if (isForm) return;
+
+ element.bind("click", function(e) {
+ var button = e.which || e.button;
+ if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {
+ // HACK: This is to allow ng-clicks to be processed before the transition is initiated:
+ var transition = $timeout(function() {
+ $state.go(ref.state, params, options);
+ });
+ e.preventDefault();
+
+ // if the state has no URL, ignore one preventDefault from the <a> directive.
+ var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0;
+ e.preventDefault = function() {
+ if (ignorePreventDefaultCount-- <= 0)
+ $timeout.cancel(transition);
+ };
+ }
+ });
+ }
+ };
+}
+
+/**
+ * @ngdoc directive
+ * @name ui.router.state.directive:ui-sref-active
+ *
+ * @requires ui.router.state.$state
+ * @requires ui.router.state.$stateParams
+ * @requires $interpolate
+ *
+ * @restrict A
+ *
+ * @description
+ * A directive working alongside ui-sref to add classes to an element when the
+ * related ui-sref directive's state is active, and removing them when it is inactive.
+ * The primary use-case is to simplify the special appearance of navigation menus
+ * relying on `ui-sref`, by having the "active" state's menu button appear different,
+ * distinguishing it from the inactive menu items.
+ *
+ * ui-sref-active can live on the same element as ui-sref or on a parent element. The first
+ * ui-sref-active found at the same level or above the ui-sref will be used.
+ *
+ * Will activate when the ui-sref's target state or any child state is active. If you
+ * need to activate only when the ui-sref target state is active and *not* any of
+ * it's children, then you will use
+ * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}
+ *
+ * @example
+ * Given the following template:
+ * <pre>
+ * <ul>
+ * <li ui-sref-active="active" class="item">
+ * <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
+ * </li>
+ * </ul>
+ * </pre>
+ *
+ *
+ * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins",
+ * the resulting HTML will appear as (note the 'active' class):
+ * <pre>
+ * <ul>
+ * <li ui-sref-active="active" class="item active">
+ * <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
+ * </li>
+ * </ul>
+ * </pre>
+ *
+ * The class name is interpolated **once** during the directives link time (any further changes to the
+ * interpolated value are ignored).
+ *
+ * Multiple classes may be specified in a space-separated format:
+ * <pre>
+ * <ul>
+ * <li ui-sref-active='class1 class2 class3'>
+ * <a ui-sref="app.user">link</a>
+ * </li>
+ * </ul>
+ * </pre>
+ */
+
+/**
+ * @ngdoc directive
+ * @name ui.router.state.directive:ui-sref-active-eq
+ *
+ * @requires ui.router.state.$state
+ * @requires ui.router.state.$stateParams
+ * @requires $interpolate
+ *
+ * @restrict A
+ *
+ * @description
+ * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate
+ * when the exact target state used in the `ui-sref` is active; no child states.
+ *
+ */
+$StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];
+function $StateRefActiveDirective($state, $stateParams, $interpolate) {
+ return {
+ restrict: "A",
+ controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
+ var states = [], activeClass;
+
+ // There probably isn't much point in $observing this
+ // uiSrefActive and uiSrefActiveEq share the same directive object with some
+ // slight difference in logic routing
+ activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope);
+
+ // Allow uiSref to communicate with uiSrefActive[Equals]
+ this.$$addStateInfo = function (newState, newParams) {
+ var state = $state.get(newState, stateContext($element));
+
+ states.push({
+ state: state || { name: newState },
+ params: newParams
+ });
+
+ update();
+ };
+
+ $scope.$on('$stateChangeSuccess', update);
+
+ // Update route state
+ function update() {
+ if (anyMatch()) {
+ $element.addClass(activeClass);
+ } else {
+ $element.removeClass(activeClass);
+ }
+ }
+
+ function anyMatch() {
+ for (var i = 0; i < states.length; i++) {
+ if (isMatch(states[i].state, states[i].params)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function isMatch(state, params) {
+ if (typeof $attrs.uiSrefActiveEq !== 'undefined') {
+ return $state.is(state.name, params);
+ } else {
+ return $state.includes(state.name, params);
+ }
+ }
+ }]
+ };
+}
+
+angular.module('ui.router.state')
+ .directive('uiSref', $StateRefDirective)
+ .directive('uiSrefActive', $StateRefActiveDirective)
+ .directive('uiSrefActiveEq', $StateRefActiveDirective);
+
+/**
+ * @ngdoc filter
+ * @name ui.router.state.filter:isState
+ *
+ * @requires ui.router.state.$state
+ *
+ * @description
+ * Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}.
+ */
+$IsStateFilter.$inject = ['$state'];
+function $IsStateFilter($state) {
+ var isFilter = function (state) {
+ return $state.is(state);
+ };
+ isFilter.$stateful = true;
+ return isFilter;
+}
+
+/**
+ * @ngdoc filter
+ * @name ui.router.state.filter:includedByState
+ *
+ * @requires ui.router.state.$state
+ *
+ * @description
+ * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.
+ */
+$IncludedByStateFilter.$inject = ['$state'];
+function $IncludedByStateFilter($state) {
+ var includesFilter = function (state) {
+ return $state.includes(state);
+ };
+ includesFilter.$stateful = true;
+ return includesFilter;
+}
+
+angular.module('ui.router.state')
+ .filter('isState', $IsStateFilter)
+ .filter('includedByState', $IncludedByStateFilter);
+})(window, window.angular);
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/release/angular-ui-router.min.js b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/release/angular-ui-router.min.js
new file mode 100644
index 0000000..18d8307
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/release/angular-ui-router.min.js
@@ -0,0 +1,7 @@
+/**
+ * State-based routing for AngularJS
+ * @version v0.2.15
+ * @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 N(new(N(function(){},{prototype:a})),b)}function e(a){return M(arguments,function(b){b!==a&&M(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 b=[];return M(a,function(a,c){b.push(c)}),b}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 N({},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 M(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));return M(c,function(c){c in a&&(b[c]=a[c])}),b}function m(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 n(a,b){var c=L(a),d=c?[]:{};return M(a,function(a,e){b(a,e)&&(d[c?d.length:e]=a)}),d}function o(a,b){var c=L(a)?[]:{};return M(a,function(a,d){c[d]=b(a,d)}),c}function p(a,b){var d=1,f=2,i={},j=[],k=i,l=N(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,J(a))q.push(c,[function(){return b.get(a)}],j);else{var e=b.annotate(a);M(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 K(a)&&a.then&&a.$$promises}if(!K(i))throw new Error("'invocables' must be an object");var p=g(i||{}),q=[],r=[],s={};return M(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(!H(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;M(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(!K(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=l;var n=a.defer(),r=n.promise,s=r.$$promises={},t=N({},d),u=1+q.length/3,v=!1;if(H(f.$$failure))return i(f.$$failure),r;f.$$inheritedValues&&e(t,m(f.$$inheritedValues,p)),N(s,f.$$promises),f.$$values?(v=e(t,m(f.$$values,p)),r.$$inheritedValues=m(f.$$values,p),h()):(f.$$inheritedValues&&(r.$$inheritedValues=m(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 q(a,b,c){this.fromConfig=function(a,b,c){return H(a.template)?this.fromString(a.template,b):H(a.templateUrl)?this.fromUrl(a.templateUrl,b):H(a.templateProvider)?this.fromProvider(a.templateProvider,b,c):null},this.fromString=function(a,b){return I(a)?a(b):a},this.fromUrl=function(c,d){return I(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 r(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 P.Param(b,c,d,e),p[b]}function g(a,b,c,d){var e=["",""],f=a.replace(/[\\\[\]\^$*+?.()|{}]/g,"\\$&");if(!b)return f;switch(c){case!1:e=["(",")"+(d?"?":"")];break;case!0:e=["?(",")?"];break;default:e=["("+c+"|",")?"]}return f+e[0]+b+e[1]}function h(e,f){var g,h,i,j,k;return g=e[2]||e[3],k=b.params[g],i=a.substring(m,e.index),h=f?e[4]:e[4]||("*"==e[1]?".*":null),j=P.type(h||"string")||d(P.type("string"),{pattern:new RegExp(h,b.caseInsensitive?"i":c)}),{id:g,regexp:h,segment:i,type:j,cfg:k}}b=N({params:{}},K(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 P.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,s.isOptional),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 s(a){N(this,a)}function t(){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(){return{strict:p,caseInsensitive:m}}function i(a){return I(a)||L(a)&&I(a[a.length-1])}function j(){for(;w.length;){var a=w.shift();if(a.pattern)throw new Error("You cannot override a type's .pattern at runtime.");b.extend(u[a.name],l.invoke(a.def))}}function k(a){N(this,a||{})}P=this;var l,m=!1,p=!0,q=!1,u={},v=!0,w=[],x={string:{encode:a,decode:e,is:function(a){return null==a||!H(a)||"string"==typeof a},pattern:/[^/]*/},"int":{encode:a,decode:function(a){return parseInt(a,10)},is:function(a){return H(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,equals:b.equals,pattern:/.*/}};t.$$getDefaultValue=function(a){if(!i(a.value))return a.value;if(!l)throw new Error("Injectable functions cannot be called at configuration time");return l.invoke(a.value)},this.caseInsensitive=function(a){return H(a)&&(m=a),m},this.strictMode=function(a){return H(a)&&(p=a),p},this.defaultSquashPolicy=function(a){if(!H(a))return q;if(a!==!0&&a!==!1&&!J(a))throw new Error("Invalid squash policy: "+a+". Valid policies: false, true, arbitrary-string");return q=a,a},this.compile=function(a,b){return new r(a,N(f(),b))},this.isMatcher=function(a){if(!K(a))return!1;var b=!0;return M(r.prototype,function(c,d){I(c)&&(b=b&&H(a[d])&&I(a[d]))}),b},this.type=function(a,b,c){if(!H(b))return u[a];if(u.hasOwnProperty(a))throw new Error("A type named '"+a+"' has already been defined.");return u[a]=new s(N({name:a},b)),c&&(w.push({name:a,def:c}),v||j()),this},M(x,function(a,b){u[b]=new s(N({name:b},a))}),u=d(u,{}),this.$get=["$injector",function(a){return l=a,v=!1,j(),M(x,function(a,b){u[b]||(u[b]=new s(a))}),this}],this.Param=function(a,b,d,e){function f(a){var b=K(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=i(a.value)?a.value:function(){return a.value},a}function j(b,c,d){if(b.type&&c)throw new Error("Param '"+a+"' has two type configurations.");return c?c:b.type?b.type instanceof s?b.type:new s(b.type):"config"===d?u.any:u.string}function k(){var b={array:"search"===e?"auto":!1},c=a.match(/\[\]$/)?{array:!0}:{};return N(b,c,d).array}function m(a,b){var c=a.squash;if(!b||c===!1)return!1;if(!H(c)||null==c)return q;if(c===!0||J(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=L(a.replace)?a.replace:[],J(e)&&f.push({from:e,to:c}),g=o(f,function(a){return a.from}),n(i,function(a){return-1===h(g,a.from)}).concat(f)}function r(){if(!l)throw new Error("Injectable functions cannot be called at configuration time");var a=l.invoke(d.$$fn);if(null!==a&&a!==c&&!w.type.is(a))throw new Error("Default value ("+a+") for parameter '"+w.id+"' is not an instance of Type ("+w.type.name+")");return a}function t(a){function b(a){return function(b){return b.from===a}}function c(a){var c=o(n(w.replace,b(a)),function(a){return a.to});return c.length?c[0]:a}return a=c(a),H(a)?w.type.$normalize(a):r()}function v(){return"{Param:"+a+" "+b+" squash: '"+z+"' optional: "+y+"}"}var w=this;d=f(d),b=j(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=m(d,y),A=p(d,x,y,z);N(this,{id:a,type:b,location:e,array:x,squash:z,replace:A,isOptional:y,value:t,dynamic:c,config:d,toString:v})},k.prototype={$$new:function(){return d(this,N(new k,{$$parent:this}))},$$keys:function(){for(var a=[],b=[],c=this,d=g(k.prototype);c;)b.push(c),c=c.$$parent;return b.reverse(),M(b,function(b){M(g(b),function(b){-1===h(a,b)&&-1===h(d,b)&&a.push(b)})}),a},$$values:function(a){var b={},c=this;return M(c.$$keys(),function(d){b[d]=c[d].value(a&&a[d])}),b},$$equals:function(a,b){var c=!0,d=this;return M(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 d,e,f,g,h,i=this.$$keys();for(d=0;d<i.length&&(e=this[i[d]],f=a[i[d]],f!==c&&null!==f||!e.isOptional);d++){if(g=e.type.$normalize(f),!e.type.is(g))return!1;if(h=e.type.encode(g),b.isString(h)&&!e.type.pattern.exec(h))return!1}return!0},$$parent:c},this.ParamSet=k}function u(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 H(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?(J(b)&&d.replace().url(b),!0):!1}if(!a||!a.defaultPrevented){o&&d.url()===o;o=c;var e,g=j.length;for(e=0;g>e;e++)if(b(j[e]))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){var f=a.format(b||{});null!==f&&b&&b["#"]&&(f+="#"+b["#"]),d.url(f),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),null!==i&&e&&e["#"]&&(i+="#"+e["#"]),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(!I(a))throw new Error("'rule' must be a function");return j.push(a),this},this.otherwise=function(a){if(J(a)){var b=a;a=function(){return b}}else if(!I(a))throw new Error("'rule' must be a function");return k=a,this},this.when=function(a,b){var c,h=J(b);if(J(a)&&(a=d.compile(a)),!h&&!I(b)&&!L(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)}]),N(function(c,d){return g(c,b,a.exec(d.path(),d.search()))},{prefix:J(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)}]),N(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 v(a,e){function f(a){return 0===a.indexOf(".")||0===a.indexOf("^")}function m(a,b){if(!a)return c;var d=J(a),e=d?a:a.name,g=f(e);if(g){if(!b)throw new Error("No reference point given for path '"+e+"'");b=m(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 l=z[e];return!l||!d&&(d||l!==a&&l.self!==a)?c:l}function n(a,b){A[a]||(A[a]=[]),A[a].push(b)}function p(a){for(var b=A[a]||[];b.length;)q(b.shift())}function q(b){b=d(b,{self:b,resolve:b.resolve||{},toString:function(){return this.name}});var c=b.name;if(!J(c)||c.indexOf("@")>=0)throw new Error("State must have a valid name");if(z.hasOwnProperty(c))throw new Error("State '"+c+"'' is already defined");var e=-1!==c.indexOf(".")?c.substring(0,c.lastIndexOf(".")):J(b.parent)?b.parent:K(b.parent)&&J(b.parent.name)?b.parent.name:"";if(e&&!z[e])return n(e,b.self);for(var f in C)I(C[f])&&(b[f]=C[f](b,C.$delegates[f]));return z[c]=b,!b[B]&&b.url&&a.when(b.url,["$match","$stateParams",function(a,c){y.$current.navigable==b&&j(a,c)||y.transitionTo(b,a,{inherit:!0,location:!1})}]),p(c),b}function r(a){return a.indexOf("*")>-1}function s(a){for(var b=a.split("."),c=y.$current.name.split("."),d=0,e=b.length;e>d;d++)"*"===b[d]&&(c[d]="*");return"**"===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?!1:c.join("")===b.join("")}function t(a,b){return J(a)&&!H(b)?C[a]:I(b)&&J(a)?(C[a]&&!C.$delegates[a]&&(C.$delegates[a]=C[a]),C[a]=b,this):this}function u(a,b){return K(a)?b=a:b.name=a,q(b),this}function v(a,e,f,h,l,n,p,q,t){function u(b,c,d,f){var g=a.$broadcast("$stateNotFound",b,c,d);if(g.defaultPrevented)return p.update(),D;if(!g.retry)return null;if(f.$retry)return p.update(),E;var h=y.transition=e.when(g.retry);return h.then(function(){return h!==y.transition?A:(b.options.$retry=!0,y.transitionTo(b.to,b.toParams,b.options))},function(){return D}),p.update(),h}function v(a,c,d,g,i,j){function m(){var c=[];return M(a.views,function(d,e){var g=d.resolve&&d.resolve!==a.resolve?d.resolve:{};g.$template=[function(){return f.load(e,{view:d,locals:i.globals,params:n,notify:j.notify})||""}],c.push(l.resolve(g,i.globals,i.resolve,a).then(function(c){if(I(d.controllerProvider)||L(d.controllerProvider)){var f=b.extend({},g,i.globals);c.$$controller=h.invoke(d.controllerProvider,null,f)}else c.$$controller=d.controller;c.$$state=a,c.$$controllerAs=d.controllerAs,i[e]=c}))}),e.all(c).then(function(){return i.globals})}var n=d?c:k(a.params.$$keys(),c),o={$stateParams:n};i.resolve=l.resolve(a.resolve,o,i.resolve,a);var p=[i.resolve.then(function(a){i.globals=a})];return g&&p.push(g),e.all(p).then(m).then(function(a){return i})}var A=e.reject(new Error("transition superseded")),C=e.reject(new Error("transition prevented")),D=e.reject(new Error("transition aborted")),E=e.reject(new Error("transition failed"));return x.locals={resolve:null,globals:{$stateParams:{}}},y={params:{},current:x.self,$current:x,transition:null},y.reload=function(a){return y.transitionTo(y.current,n,{reload:a||!0,inherit:!1,notify:!0})},y.go=function(a,b,c){return y.transitionTo(a,b,N({inherit:!0,relative:y.$current},c))},y.transitionTo=function(b,c,f){c=c||{},f=N({location:!0,inherit:!1,relative:null,notify:!0,reload:!1,$retry:!1},f||{});var g,j=y.$current,l=y.params,o=j.path,q=m(b,f.relative),r=c["#"];if(!H(q)){var s={to:b,toParams:c,options:f},t=u(s,j.self,l,f);if(t)return t;if(b=s.to,c=s.toParams,f=s.options,q=m(b,f.relative),!H(q)){if(!f.relative)throw new Error("No such state '"+b+"'");throw new Error("Could not resolve '"+b+"' from state '"+f.relative+"'")}}if(q[B])throw new Error("Cannot transition to abstract state '"+b+"'");if(f.inherit&&(c=i(n,c||{},y.$current,q)),!q.params.$$validates(c))return E;c=q.params.$$values(c),b=q;var z=b.path,D=0,F=z[D],G=x.locals,I=[];if(f.reload){if(J(f.reload)||K(f.reload)){if(K(f.reload)&&!f.reload.name)throw new Error("Invalid reload state object");var L=f.reload===!0?o[0]:m(f.reload);if(f.reload&&!L)throw new Error("No such reload state '"+(J(f.reload)?f.reload:f.reload.name)+"'");for(;F&&F===o[D]&&F!==L;)G=I[D]=F.locals,D++,F=z[D]}}else for(;F&&F===o[D]&&F.ownParams.$$equals(c,l);)G=I[D]=F.locals,D++,F=z[D];if(w(b,c,j,l,G,f))return r&&(c["#"]=r),y.params=c,O(y.params,n),f.location&&b.navigable&&b.navigable.url&&(p.push(b.navigable.url,c,{$$avoidResync:!0,replace:"replace"===f.location}),p.update(!0)),y.transition=null,e.when(y.current);if(c=k(b.params.$$keys(),c||{}),f.notify&&a.$broadcast("$stateChangeStart",b.self,c,j.self,l).defaultPrevented)return a.$broadcast("$stateChangeCancel",b.self,c,j.self,l),p.update(),C;for(var M=e.when(G),P=D;P<z.length;P++,F=z[P])G=I[P]=d(G),M=v(F,c,F===b,M,G,f);var Q=y.transition=M.then(function(){var d,e,g;if(y.transition!==Q)return A;for(d=o.length-1;d>=D;d--)g=o[d],g.self.onExit&&h.invoke(g.self.onExit,g.self,g.locals.globals),g.locals=null;for(d=D;d<z.length;d++)e=z[d],e.locals=I[d],e.self.onEnter&&h.invoke(e.self.onEnter,e.self,e.locals.globals);return r&&(c["#"]=r),y.transition!==Q?A:(y.$current=b,y.current=b.self,y.params=c,O(y.params,n),y.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,l),p.update(!0),y.current)},function(d){return y.transition!==Q?A:(y.transition=null,g=a.$broadcast("$stateChangeError",b.self,c,j.self,l,d),g.defaultPrevented||p.update(),e.reject(d))});return Q},y.is=function(a,b,d){d=N({relative:y.$current},d||{});var e=m(a,d.relative);return H(e)?y.$current!==e?!1:b?j(e.params.$$values(b),n):!0:c},y.includes=function(a,b,d){if(d=N({relative:y.$current},d||{}),J(a)&&r(a)){if(!s(a))return!1;a=y.$current.name}var e=m(a,d.relative);return H(e)?H(y.$current.includes[e.name])?b?j(e.params.$$values(b),n,g(b)):!0:!1:c},y.href=function(a,b,d){d=N({lossy:!0,inherit:!0,absolute:!1,relative:y.$current},d||{});var e=m(a,d.relative);if(!H(e))return null;d.inherit&&(b=i(n,b||{},y.$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().concat("#"),b||{}),{absolute:d.absolute}):null},y.get=function(a,b){if(0===arguments.length)return o(g(z),function(a){return z[a].self});var c=m(a,b||y.$current);return c&&c.self?c.self:null},y}function w(a,b,c,d,e,f){function g(a,b,c){function d(b){return"search"!=a.params[b].location}var e=a.params.$$keys().filter(d),f=l.apply({},[a.params].concat(e)),g=new P.ParamSet(f);return g.$$equals(b,c)}return!f.reload&&a===c&&(e===c.locals||a.self.reloadOnSearch===!1&&g(c,d,b))?!0:void 0}var x,y,z={},A={},B="abstract",C={parent:function(a){if(H(a.parent)&&a.parent)return m(a.parent);var b=/^(.+)\.[^.]+$/.exec(a.name);return b?m(b[1]):x},data:function(a){return a.parent&&a.parent.data&&(a.data=a.self.data=N({},a.parent.data,a.data)),a.data},url:function(a){var b=a.url,c={params:a.params||{}};if(J(b))return"^"==b.charAt(0)?e.compile(b.substring(1),c):(a.parent.navigable||x).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 P.ParamSet;return M(a.params||{},function(a,c){b[c]||(b[c]=new P.Param(c,null,a,"config"))}),b},params:function(a){return a.parent&&a.parent.params?N(a.parent.params.$$new(),a.ownParams):new P.ParamSet},views:function(a){var b={};return M(H(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?N({},a.parent.includes):{};return b[a.name]=!0,b},$delegates:{}};x=q({name:"",url:"^",views:null,"abstract":!0}),x.navigable=null,this.decorator=t,this.state=u,this.$get=v,v.$inject=["$rootScope","$q","$view","$injector","$resolve","$stateParams","$urlRouter","$location","$urlMatcherFactory"]}function w(){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=N(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 x(){var a=!1;this.useAnchorScroll=function(){a=!0},this.$get=["$anchorScroll","$timeout",function(b,c){return a?b:function(a){return c(function(){a[0].scrollIntoView()},0,!1)}}]}function y(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=A(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 z(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=A(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,k.$element=g;var m=b(k.$$controller,k);k.$$controllerAs&&(e[k.$$controllerAs]=m),g.data("$ngControllerController",m),g.children().data("$ngControllerController",m)}l(e)}}}}}function A(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 B(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 C(a){var b=a.parent().inheritedData("$uiView");return b&&b.state&&b.state.name?b.state:void 0}function D(a,c){var d=["location","inherit","reload","absolute"];return{restrict:"A",require:["?^uiSrefActive","?^uiSrefActiveEq"],link:function(e,f,g,h){var i=B(g.uiSref,a.current.name),j=null,k=C(f)||a.$current,l="[object SVGAnimatedString]"===Object.prototype.toString.call(f.prop("href"))?"xlink:href":"href",m=null,n="A"===f.prop("tagName").toUpperCase(),o="FORM"===f[0].nodeName,p=o?"action":l,q=!0,r={relative:k,inherit:!0},s=e.$eval(g.uiSrefOpts)||{};b.forEach(d,function(a){a in s&&(r[a]=s[a])});var t=function(c){if(c&&(j=b.copy(c)),q){m=a.href(i.state,j,r);var d=h[1]||h[0];return d&&d.$$addStateInfo(i.state,j),null===m?(q=!1,!1):void g.$set(p,m)}};i.paramExpr&&(e.$watch(i.paramExpr,function(a,b){a!==j&&t(a)},!0),j=b.copy(e.$eval(i.paramExpr))),t(),o||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,r)});b.preventDefault();var g=n&&!m?1:0;b.preventDefault=function(){g--<=0&&c.cancel(e)}}})}}}function E(a,b,c){return{restrict:"A",controller:["$scope","$element","$attrs",function(b,d,e){function f(){g()?d.addClass(i):d.removeClass(i)}function g(){for(var a=0;a<j.length;a++)if(h(j[a].state,j[a].params))return!0;return!1}function h(b,c){return"undefined"!=typeof e.uiSrefActiveEq?a.is(b.name,c):a.includes(b.name,c)}var i,j=[];i=c(e.uiSrefActiveEq||e.uiSrefActive||"",!1)(b),this.$$addStateInfo=function(b,c){var e=a.get(b,C(d));j.push({state:e||{name:b},params:c}),f()},b.$on("$stateChangeSuccess",f)}]}}function F(a){var b=function(b){return a.is(b)};return b.$stateful=!0,b}function G(a){var b=function(b){return a.includes(b)};return b.$stateful=!0,b}var H=b.isDefined,I=b.isFunction,J=b.isString,K=b.isObject,L=b.isArray,M=b.forEach,N=b.extend,O=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"]),p.$inject=["$q","$injector"],b.module("ui.router.util").service("$resolve",p),q.$inject=["$http","$templateCache","$injector"],b.module("ui.router.util").service("$templateFactory",q);var P;r.prototype.concat=function(a,b){var c={caseInsensitive:P.caseInsensitive(),strict:P.strictMode(),squash:P.defaultSquashPolicy()};return new r(this.sourcePath+a+this.sourceSearch,N(c,b),this)},r.prototype.toString=function(){return this.source},r.prototype.exec=function(a,b){function c(a){function b(a){return a.split("").reverse().join("")}function c(a){return a.replace(/\\-/g,"-")}var d=b(a).split(/-(?!\\)/),e=o(d,b);return o(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},r.prototype.parameters=function(a){return H(a)?this.params[a]||null:this.$$paramNames},r.prototype.validates=function(a){return this.params.$$validates(a)},r.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],n=m.value(a[l]),p=m.isOptional&&m.type.equals(m.value(),n),q=p?m.squash:!1,r=m.type.encode(n);if(k){var s=c[f+1];if(q===!1)null!=r&&(j+=L(r)?o(r,b).join("-"):encodeURIComponent(r)),j+=s;else if(q===!0){var t=j.match(/\/$/)?/\/?(.*)/:/(.*)/;j+=s.match(t)[1]}else J(q)&&(j+=q+s)}else{if(null==r||p&&q!==!1)continue;L(r)||(r=[r]),r=o(r,encodeURIComponent).join("&"+l+"="),j+=(g?"&":"?")+(l+"="+r),g=!0}}return j},s.prototype.is=function(a,b){return!0},s.prototype.encode=function(a,b){return a},s.prototype.decode=function(a,b){return a},s.prototype.equals=function(a,b){return a==b},s.prototype.$subPattern=function(){var a=this.pattern.toString();return a.substr(1,a.length-2)},s.prototype.pattern=/.*/,s.prototype.toString=function(){return"{Type:"+this.name+"}"},s.prototype.$normalize=function(a){return this.is(a)?a:this.decode(a)},s.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 L(a)?a:H(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=o(c,a);return b===!0?0===n(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.$normalize=h(d(a,"$normalize")),this.name=a.name,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",t),b.module("ui.router.util").run(["$urlMatcherFactory",function(a){}]),u.$inject=["$locationProvider","$urlMatcherFactoryProvider"],b.module("ui.router.router").provider("$urlRouter",u),v.$inject=["$urlRouterProvider","$urlMatcherFactoryProvider"],b.module("ui.router.state").value("$stateParams",{}).provider("$state",v),w.$inject=[],b.module("ui.router.state").provider("$view",w),b.module("ui.router.state").provider("$uiViewScroll",x),y.$inject=["$state","$injector","$uiViewScroll","$interpolate"],z.$inject=["$compile","$controller","$state","$interpolate"],b.module("ui.router.state").directive("uiView",y),b.module("ui.router.state").directive("uiView",z),D.$inject=["$state","$timeout"],E.$inject=["$state","$stateParams","$interpolate"],b.module("ui.router.state").directive("uiSref",D).directive("uiSrefActive",E).directive("uiSrefActiveEq",E),F.$inject=["$state"],G.$inject=["$state"],b.module("ui.router.state").filter("isState",F).filter("includedByState",G)}(window,window.angular);
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/common.js b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/common.js
new file mode 100644
index 0000000..a85ff9e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/common.js
@@ -0,0 +1,292 @@
+/*jshint globalstrict:true*/
+/*global angular:false*/
+'use strict';
+
+var isDefined = angular.isDefined,
+ isFunction = angular.isFunction,
+ isString = angular.isString,
+ isObject = angular.isObject,
+ isArray = angular.isArray,
+ forEach = angular.forEach,
+ extend = angular.extend,
+ copy = angular.copy;
+
+function inherit(parent, extra) {
+ return extend(new (extend(function() {}, { prototype: parent }))(), extra);
+}
+
+function merge(dst) {
+ forEach(arguments, function(obj) {
+ if (obj !== dst) {
+ forEach(obj, function(value, key) {
+ if (!dst.hasOwnProperty(key)) dst[key] = value;
+ });
+ }
+ });
+ return dst;
+}
+
+/**
+ * Finds the common ancestor path between two states.
+ *
+ * @param {Object} first The first state.
+ * @param {Object} second The second state.
+ * @return {Array} Returns an array of state names in descending order, not including the root.
+ */
+function ancestors(first, second) {
+ var path = [];
+
+ for (var n in first.path) {
+ if (first.path[n] !== second.path[n]) break;
+ path.push(first.path[n]);
+ }
+ return path;
+}
+
+/**
+ * IE8-safe wrapper for `Object.keys()`.
+ *
+ * @param {Object} object A JavaScript object.
+ * @return {Array} Returns the keys of the object as an array.
+ */
+function objectKeys(object) {
+ if (Object.keys) {
+ return Object.keys(object);
+ }
+ var result = [];
+
+ forEach(object, function(val, key) {
+ result.push(key);
+ });
+ return result;
+}
+
+/**
+ * IE8-safe wrapper for `Array.prototype.indexOf()`.
+ *
+ * @param {Array} array A JavaScript array.
+ * @param {*} value A value to search the array for.
+ * @return {Number} Returns the array index value of `value`, or `-1` if not present.
+ */
+function indexOf(array, value) {
+ if (Array.prototype.indexOf) {
+ return array.indexOf(value, Number(arguments[2]) || 0);
+ }
+ var len = array.length >>> 0, from = Number(arguments[2]) || 0;
+ from = (from < 0) ? Math.ceil(from) : Math.floor(from);
+
+ if (from < 0) from += len;
+
+ for (; from < len; from++) {
+ if (from in array && array[from] === value) return from;
+ }
+ return -1;
+}
+
+/**
+ * Merges a set of parameters with all parameters inherited between the common parents of the
+ * current state and a given destination state.
+ *
+ * @param {Object} currentParams The value of the current state parameters ($stateParams).
+ * @param {Object} newParams The set of parameters which will be composited with inherited params.
+ * @param {Object} $current Internal definition of object representing the current state.
+ * @param {Object} $to Internal definition of object representing state to transition to.
+ */
+function inheritParams(currentParams, newParams, $current, $to) {
+ var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];
+
+ for (var i in parents) {
+ if (!parents[i].params) continue;
+ parentParams = objectKeys(parents[i].params);
+ if (!parentParams.length) continue;
+
+ for (var j in parentParams) {
+ if (indexOf(inheritList, parentParams[j]) >= 0) continue;
+ inheritList.push(parentParams[j]);
+ inherited[parentParams[j]] = currentParams[parentParams[j]];
+ }
+ }
+ return extend({}, inherited, newParams);
+}
+
+/**
+ * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.
+ *
+ * @param {Object} a The first object.
+ * @param {Object} b The second object.
+ * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,
+ * it defaults to the list of keys in `a`.
+ * @return {Boolean} Returns `true` if the keys match, otherwise `false`.
+ */
+function equalForKeys(a, b, keys) {
+ if (!keys) {
+ keys = [];
+ for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
+ }
+
+ for (var i=0; i<keys.length; i++) {
+ var k = keys[i];
+ if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
+ }
+ return true;
+}
+
+/**
+ * Returns the subset of an object, based on a list of keys.
+ *
+ * @param {Array} keys
+ * @param {Object} values
+ * @return {Boolean} Returns a subset of `values`.
+ */
+function filterByKeys(keys, values) {
+ var filtered = {};
+
+ forEach(keys, function (name) {
+ filtered[name] = values[name];
+ });
+ return filtered;
+}
+
+// like _.indexBy
+// when you know that your index values will be unique, or you want last-one-in to win
+function indexBy(array, propName) {
+ var result = {};
+ forEach(array, function(item) {
+ result[item[propName]] = item;
+ });
+ return result;
+}
+
+// extracted from underscore.js
+// Return a copy of the object only containing the whitelisted properties.
+function pick(obj) {
+ var copy = {};
+ var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
+ forEach(keys, function(key) {
+ if (key in obj) copy[key] = obj[key];
+ });
+ return copy;
+}
+
+// extracted from underscore.js
+// Return a copy of the object omitting the blacklisted properties.
+function omit(obj) {
+ var copy = {};
+ var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
+ for (var key in obj) {
+ if (indexOf(keys, key) == -1) copy[key] = obj[key];
+ }
+ return copy;
+}
+
+function pluck(collection, key) {
+ var result = isArray(collection) ? [] : {};
+
+ forEach(collection, function(val, i) {
+ result[i] = isFunction(key) ? key(val) : val[key];
+ });
+ return result;
+}
+
+function filter(collection, callback) {
+ var array = isArray(collection);
+ var result = array ? [] : {};
+ forEach(collection, function(val, i) {
+ if (callback(val, i)) {
+ result[array ? result.length : i] = val;
+ }
+ });
+ return result;
+}
+
+function map(collection, callback) {
+ var result = isArray(collection) ? [] : {};
+
+ forEach(collection, function(val, i) {
+ result[i] = callback(val, i);
+ });
+ return result;
+}
+
+/**
+ * @ngdoc overview
+ * @name ui.router.util
+ *
+ * @description
+ * # ui.router.util sub-module
+ *
+ * This module is a dependency of other sub-modules. Do not include this module as a dependency
+ * in your angular app (use {@link ui.router} module instead).
+ *
+ */
+angular.module('ui.router.util', ['ng']);
+
+/**
+ * @ngdoc overview
+ * @name ui.router.router
+ *
+ * @requires ui.router.util
+ *
+ * @description
+ * # ui.router.router sub-module
+ *
+ * This module is a dependency of other sub-modules. Do not include this module as a dependency
+ * in your angular app (use {@link ui.router} module instead).
+ */
+angular.module('ui.router.router', ['ui.router.util']);
+
+/**
+ * @ngdoc overview
+ * @name ui.router.state
+ *
+ * @requires ui.router.router
+ * @requires ui.router.util
+ *
+ * @description
+ * # ui.router.state sub-module
+ *
+ * This module is a dependency of the main ui.router module. Do not include this module as a dependency
+ * in your angular app (use {@link ui.router} module instead).
+ *
+ */
+angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);
+
+/**
+ * @ngdoc overview
+ * @name ui.router
+ *
+ * @requires ui.router.state
+ *
+ * @description
+ * # ui.router
+ *
+ * ## The main module for ui.router
+ * There are several sub-modules included with the ui.router module, however only this module is needed
+ * as a dependency within your angular app. The other modules are for organization purposes.
+ *
+ * The modules are:
+ * * ui.router - the main "umbrella" module
+ * * ui.router.router -
+ *
+ * *You'll need to include **only** this module as the dependency within your angular app.*
+ *
+ * <pre>
+ * <!doctype html>
+ * <html ng-app="myApp">
+ * <head>
+ * <script src="js/angular.js"></script>
+ * <!-- Include the ui-router script -->
+ * <script src="js/angular-ui-router.min.js"></script>
+ * <script>
+ * // ...and add 'ui.router' as a dependency
+ * var myApp = angular.module('myApp', ['ui.router']);
+ * </script>
+ * </head>
+ * <body>
+ * </body>
+ * </html>
+ * </pre>
+ */
+angular.module('ui.router', ['ui.router.state']);
+
+angular.module('ui.router.compat', ['ui.router']);
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/resolve.js b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/resolve.js
new file mode 100644
index 0000000..f1c1790
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/resolve.js
@@ -0,0 +1,252 @@
+/**
+ * @ngdoc object
+ * @name ui.router.util.$resolve
+ *
+ * @requires $q
+ * @requires $injector
+ *
+ * @description
+ * Manages resolution of (acyclic) graphs of promises.
+ */
+$Resolve.$inject = ['$q', '$injector'];
+function $Resolve( $q, $injector) {
+
+ var VISIT_IN_PROGRESS = 1,
+ VISIT_DONE = 2,
+ NOTHING = {},
+ NO_DEPENDENCIES = [],
+ NO_LOCALS = NOTHING,
+ NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING });
+
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$resolve#study
+ * @methodOf ui.router.util.$resolve
+ *
+ * @description
+ * Studies a set of invocables that are likely to be used multiple times.
+ * <pre>
+ * $resolve.study(invocables)(locals, parent, self)
+ * </pre>
+ * is equivalent to
+ * <pre>
+ * $resolve.resolve(invocables, locals, parent, self)
+ * </pre>
+ * but the former is more efficient (in fact `resolve` just calls `study`
+ * internally).
+ *
+ * @param {object} invocables Invocable objects
+ * @return {function} a function to pass in locals, parent and self
+ */
+ this.study = function (invocables) {
+ if (!isObject(invocables)) throw new Error("'invocables' must be an object");
+ var invocableKeys = objectKeys(invocables || {});
+
+ // Perform a topological sort of invocables to build an ordered plan
+ var plan = [], cycle = [], visited = {};
+ function visit(value, key) {
+ if (visited[key] === VISIT_DONE) return;
+
+ cycle.push(key);
+ if (visited[key] === VISIT_IN_PROGRESS) {
+ cycle.splice(0, indexOf(cycle, key));
+ throw new Error("Cyclic dependency: " + cycle.join(" -> "));
+ }
+ visited[key] = VISIT_IN_PROGRESS;
+
+ if (isString(value)) {
+ plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES);
+ } else {
+ var params = $injector.annotate(value);
+ forEach(params, function (param) {
+ if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);
+ });
+ plan.push(key, value, params);
+ }
+
+ cycle.pop();
+ visited[key] = VISIT_DONE;
+ }
+ forEach(invocables, visit);
+ invocables = cycle = visited = null; // plan is all that's required
+
+ function isResolve(value) {
+ return isObject(value) && value.then && value.$$promises;
+ }
+
+ return function (locals, parent, self) {
+ if (isResolve(locals) && self === undefined) {
+ self = parent; parent = locals; locals = null;
+ }
+ if (!locals) locals = NO_LOCALS;
+ else if (!isObject(locals)) {
+ throw new Error("'locals' must be an object");
+ }
+ if (!parent) parent = NO_PARENT;
+ else if (!isResolve(parent)) {
+ throw new Error("'parent' must be a promise returned by $resolve.resolve()");
+ }
+
+ // To complete the overall resolution, we have to wait for the parent
+ // promise and for the promise for each invokable in our plan.
+ var resolution = $q.defer(),
+ result = resolution.promise,
+ promises = result.$$promises = {},
+ values = extend({}, locals),
+ wait = 1 + plan.length/3,
+ merged = false;
+
+ function done() {
+ // Merge parent values we haven't got yet and publish our own $$values
+ if (!--wait) {
+ if (!merged) merge(values, parent.$$values);
+ result.$$values = values;
+ result.$$promises = result.$$promises || true; // keep for isResolve()
+ delete result.$$inheritedValues;
+ resolution.resolve(values);
+ }
+ }
+
+ function fail(reason) {
+ result.$$failure = reason;
+ resolution.reject(reason);
+ }
+
+ // Short-circuit if parent has already failed
+ if (isDefined(parent.$$failure)) {
+ fail(parent.$$failure);
+ return result;
+ }
+
+ if (parent.$$inheritedValues) {
+ merge(values, omit(parent.$$inheritedValues, invocableKeys));
+ }
+
+ // Merge parent values if the parent has already resolved, or merge
+ // parent promises and wait if the parent resolve is still in progress.
+ extend(promises, parent.$$promises);
+ if (parent.$$values) {
+ merged = merge(values, omit(parent.$$values, invocableKeys));
+ result.$$inheritedValues = omit(parent.$$values, invocableKeys);
+ done();
+ } else {
+ if (parent.$$inheritedValues) {
+ result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);
+ }
+ parent.then(done, fail);
+ }
+
+ // Process each invocable in the plan, but ignore any where a local of the same name exists.
+ for (var i=0, ii=plan.length; i<ii; i+=3) {
+ if (locals.hasOwnProperty(plan[i])) done();
+ else invoke(plan[i], plan[i+1], plan[i+2]);
+ }
+
+ function invoke(key, invocable, params) {
+ // Create a deferred for this invocation. Failures will propagate to the resolution as well.
+ var invocation = $q.defer(), waitParams = 0;
+ function onfailure(reason) {
+ invocation.reject(reason);
+ fail(reason);
+ }
+ // Wait for any parameter that we have a promise for (either from parent or from this
+ // resolve; in that case study() will have made sure it's ordered before us in the plan).
+ forEach(params, function (dep) {
+ if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) {
+ waitParams++;
+ promises[dep].then(function (result) {
+ values[dep] = result;
+ if (!(--waitParams)) proceed();
+ }, onfailure);
+ }
+ });
+ if (!waitParams) proceed();
+ function proceed() {
+ if (isDefined(result.$$failure)) return;
+ try {
+ invocation.resolve($injector.invoke(invocable, self, values));
+ invocation.promise.then(function (result) {
+ values[key] = result;
+ done();
+ }, onfailure);
+ } catch (e) {
+ onfailure(e);
+ }
+ }
+ // Publish promise synchronously; invocations further down in the plan may depend on it.
+ promises[key] = invocation.promise;
+ }
+
+ return result;
+ };
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$resolve#resolve
+ * @methodOf ui.router.util.$resolve
+ *
+ * @description
+ * Resolves a set of invocables. An invocable is a function to be invoked via
+ * `$injector.invoke()`, and can have an arbitrary number of dependencies.
+ * An invocable can either return a value directly,
+ * or a `$q` promise. If a promise is returned it will be resolved and the
+ * resulting value will be used instead. Dependencies of invocables are resolved
+ * (in this order of precedence)
+ *
+ * - from the specified `locals`
+ * - from another invocable that is part of this `$resolve` call
+ * - from an invocable that is inherited from a `parent` call to `$resolve`
+ * (or recursively
+ * - from any ancestor `$resolve` of that parent).
+ *
+ * The return value of `$resolve` is a promise for an object that contains
+ * (in this order of precedence)
+ *
+ * - any `locals` (if specified)
+ * - the resolved return values of all injectables
+ * - any values inherited from a `parent` call to `$resolve` (if specified)
+ *
+ * The promise will resolve after the `parent` promise (if any) and all promises
+ * returned by injectables have been resolved. If any invocable
+ * (or `$injector.invoke`) throws an exception, or if a promise returned by an
+ * invocable is rejected, the `$resolve` promise is immediately rejected with the
+ * same error. A rejection of a `parent` promise (if specified) will likewise be
+ * propagated immediately. Once the `$resolve` promise has been rejected, no
+ * further invocables will be called.
+ *
+ * Cyclic dependencies between invocables are not permitted and will caues `$resolve`
+ * to throw an error. As a special case, an injectable can depend on a parameter
+ * with the same name as the injectable, which will be fulfilled from the `parent`
+ * injectable of the same name. This allows inherited values to be decorated.
+ * Note that in this case any other injectable in the same `$resolve` with the same
+ * dependency would see the decorated value, not the inherited value.
+ *
+ * Note that missing dependencies -- unlike cyclic dependencies -- will cause an
+ * (asynchronous) rejection of the `$resolve` promise rather than a (synchronous)
+ * exception.
+ *
+ * Invocables are invoked eagerly as soon as all dependencies are available.
+ * This is true even for dependencies inherited from a `parent` call to `$resolve`.
+ *
+ * As a special case, an invocable can be a string, in which case it is taken to
+ * be a service name to be passed to `$injector.get()`. This is supported primarily
+ * for backwards-compatibility with the `resolve` property of `$routeProvider`
+ * routes.
+ *
+ * @param {object} invocables functions to invoke or
+ * `$injector` services to fetch.
+ * @param {object} locals values to make available to the injectables
+ * @param {object} parent a promise returned by another call to `$resolve`.
+ * @param {object} self the `this` for the invoked methods
+ * @return {object} Promise for an object that contains the resolved return value
+ * of all invocables, as well as any inherited and local values.
+ */
+ this.resolve = function (invocables, locals, parent, self) {
+ return this.study(invocables)(locals, parent, self);
+ };
+}
+
+angular.module('ui.router.util').service('$resolve', $Resolve);
+
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/state.js b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/state.js
new file mode 100644
index 0000000..56ee5a0
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/state.js
@@ -0,0 +1,1465 @@
+/**
+ * @ngdoc object
+ * @name ui.router.state.$stateProvider
+ *
+ * @requires ui.router.router.$urlRouterProvider
+ * @requires ui.router.util.$urlMatcherFactoryProvider
+ *
+ * @description
+ * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely
+ * on state.
+ *
+ * A state corresponds to a "place" in the application in terms of the overall UI and
+ * navigation. A state describes (via the controller / template / view properties) what
+ * the UI looks like and does at that place.
+ *
+ * States often have things in common, and the primary way of factoring out these
+ * commonalities in this model is via the state hierarchy, i.e. parent/child states aka
+ * nested states.
+ *
+ * The `$stateProvider` provides interfaces to declare these states for your app.
+ */
+$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];
+function $StateProvider( $urlRouterProvider, $urlMatcherFactory) {
+
+ var root, states = {}, $state, queue = {}, abstractKey = 'abstract';
+
+ // Builds state properties from definition passed to registerState()
+ var stateBuilder = {
+
+ // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.
+ // state.children = [];
+ // if (parent) parent.children.push(state);
+ parent: function(state) {
+ if (isDefined(state.parent) && state.parent) return findState(state.parent);
+ // regex matches any valid composite state name
+ // would match "contact.list" but not "contacts"
+ var compositeName = /^(.+)\.[^.]+$/.exec(state.name);
+ return compositeName ? findState(compositeName[1]) : root;
+ },
+
+ // inherit 'data' from parent and override by own values (if any)
+ data: function(state) {
+ if (state.parent && state.parent.data) {
+ state.data = state.self.data = extend({}, state.parent.data, state.data);
+ }
+ return state.data;
+ },
+
+ // Build a URLMatcher if necessary, either via a relative or absolute URL
+ url: function(state) {
+ var url = state.url, config = { params: state.params || {} };
+
+ if (isString(url)) {
+ if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);
+ return (state.parent.navigable || root).url.concat(url, config);
+ }
+
+ if (!url || $urlMatcherFactory.isMatcher(url)) return url;
+ throw new Error("Invalid url '" + url + "' in state '" + state + "'");
+ },
+
+ // Keep track of the closest ancestor state that has a URL (i.e. is navigable)
+ navigable: function(state) {
+ return state.url ? state : (state.parent ? state.parent.navigable : null);
+ },
+
+ // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params
+ ownParams: function(state) {
+ var params = state.url && state.url.params || new $$UMFP.ParamSet();
+ forEach(state.params || {}, function(config, id) {
+ if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config");
+ });
+ return params;
+ },
+
+ // Derive parameters for this state and ensure they're a super-set of parent's parameters
+ params: function(state) {
+ return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet();
+ },
+
+ // If there is no explicit multi-view configuration, make one up so we don't have
+ // to handle both cases in the view directive later. Note that having an explicit
+ // 'views' property will mean the default unnamed view properties are ignored. This
+ // is also a good time to resolve view names to absolute names, so everything is a
+ // straight lookup at link time.
+ views: function(state) {
+ var views = {};
+
+ forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {
+ if (name.indexOf('@') < 0) name += '@' + state.parent.name;
+ views[name] = view;
+ });
+ return views;
+ },
+
+ // Keep a full path from the root down to this state as this is needed for state activation.
+ path: function(state) {
+ return state.parent ? state.parent.path.concat(state) : []; // exclude root from path
+ },
+
+ // Speed up $state.contains() as it's used a lot
+ includes: function(state) {
+ var includes = state.parent ? extend({}, state.parent.includes) : {};
+ includes[state.name] = true;
+ return includes;
+ },
+
+ $delegates: {}
+ };
+
+ function isRelative(stateName) {
+ return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
+ }
+
+ function findState(stateOrName, base) {
+ if (!stateOrName) return undefined;
+
+ var isStr = isString(stateOrName),
+ name = isStr ? stateOrName : stateOrName.name,
+ path = isRelative(name);
+
+ if (path) {
+ if (!base) throw new Error("No reference point given for path '" + name + "'");
+ base = findState(base);
+
+ var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
+
+ for (; i < pathLength; i++) {
+ if (rel[i] === "" && i === 0) {
+ current = base;
+ continue;
+ }
+ if (rel[i] === "^") {
+ if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
+ current = current.parent;
+ continue;
+ }
+ break;
+ }
+ rel = rel.slice(i).join(".");
+ name = current.name + (current.name && rel ? "." : "") + rel;
+ }
+ var state = states[name];
+
+ if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
+ return state;
+ }
+ return undefined;
+ }
+
+ function queueState(parentName, state) {
+ if (!queue[parentName]) {
+ queue[parentName] = [];
+ }
+ queue[parentName].push(state);
+ }
+
+ function flushQueuedChildren(parentName) {
+ var queued = queue[parentName] || [];
+ while(queued.length) {
+ registerState(queued.shift());
+ }
+ }
+
+ function registerState(state) {
+ // Wrap a new object around the state so we can store our private details easily.
+ state = inherit(state, {
+ self: state,
+ resolve: state.resolve || {},
+ toString: function() { return this.name; }
+ });
+
+ var name = state.name;
+ if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
+ if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined");
+
+ // Get parent name
+ var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))
+ : (isString(state.parent)) ? state.parent
+ : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name
+ : '';
+
+ // If parent is not registered yet, add state to queue and register later
+ if (parentName && !states[parentName]) {
+ return queueState(parentName, state.self);
+ }
+
+ for (var key in stateBuilder) {
+ if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
+ }
+ states[name] = state;
+
+ // Register the state in the global state list and with $urlRouter if necessary.
+ if (!state[abstractKey] && state.url) {
+ $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
+ if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
+ $state.transitionTo(state, $match, { inherit: true, location: false });
+ }
+ }]);
+ }
+
+ // Register any queued children
+ flushQueuedChildren(name);
+
+ return state;
+ }
+
+ // Checks text to see if it looks like a glob.
+ function isGlob (text) {
+ return text.indexOf('*') > -1;
+ }
+
+ // Returns true if glob matches current $state name.
+ function doesStateMatchGlob (glob) {
+ var globSegments = glob.split('.'),
+ segments = $state.$current.name.split('.');
+
+ //match single stars
+ for (var i = 0, l = globSegments.length; i < l; i++) {
+ if (globSegments[i] === '*') {
+ segments[i] = '*';
+ }
+ }
+
+ //match greedy starts
+ if (globSegments[0] === '**') {
+ segments = segments.slice(indexOf(segments, globSegments[1]));
+ segments.unshift('**');
+ }
+ //match greedy ends
+ if (globSegments[globSegments.length - 1] === '**') {
+ segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);
+ segments.push('**');
+ }
+
+ if (globSegments.length != segments.length) {
+ return false;
+ }
+
+ return segments.join('') === globSegments.join('');
+ }
+
+
+ // Implicit root state that is always active
+ root = registerState({
+ name: '',
+ url: '^',
+ views: null,
+ 'abstract': true
+ });
+ root.navigable = null;
+
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$stateProvider#decorator
+ * @methodOf ui.router.state.$stateProvider
+ *
+ * @description
+ * Allows you to extend (carefully) or override (at your own peril) the
+ * `stateBuilder` object used internally by `$stateProvider`. This can be used
+ * to add custom functionality to ui-router, for example inferring templateUrl
+ * based on the state name.
+ *
+ * When passing only a name, it returns the current (original or decorated) builder
+ * function that matches `name`.
+ *
+ * The builder functions that can be decorated are listed below. Though not all
+ * necessarily have a good use case for decoration, that is up to you to decide.
+ *
+ * In addition, users can attach custom decorators, which will generate new
+ * properties within the state's internal definition. There is currently no clear
+ * use-case for this beyond accessing internal states (i.e. $state.$current),
+ * however, expect this to become increasingly relevant as we introduce additional
+ * meta-programming features.
+ *
+ * **Warning**: Decorators should not be interdependent because the order of
+ * execution of the builder functions in non-deterministic. Builder functions
+ * should only be dependent on the state definition object and super function.
+ *
+ *
+ * Existing builder functions and current return values:
+ *
+ * - **parent** `{object}` - returns the parent state object.
+ * - **data** `{object}` - returns state data, including any inherited data that is not
+ * overridden by own values (if any).
+ * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
+ * or `null`.
+ * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
+ * navigable).
+ * - **params** `{object}` - returns an array of state params that are ensured to
+ * be a super-set of parent's params.
+ * - **views** `{object}` - returns a views object where each key is an absolute view
+ * name (i.e. "viewName@stateName") and each value is the config object
+ * (template, controller) for the view. Even when you don't use the views object
+ * explicitly on a state config, one is still created for you internally.
+ * So by decorating this builder function you have access to decorating template
+ * and controller properties.
+ * - **ownParams** `{object}` - returns an array of params that belong to the state,
+ * not including any params defined by ancestor states.
+ * - **path** `{string}` - returns the full path from the root down to this state.
+ * Needed for state activation.
+ * - **includes** `{object}` - returns an object that includes every state that
+ * would pass a `$state.includes()` test.
+ *
+ * @example
+ * <pre>
+ * // Override the internal 'views' builder with a function that takes the state
+ * // definition, and a reference to the internal function being overridden:
+ * $stateProvider.decorator('views', function (state, parent) {
+ * var result = {},
+ * views = parent(state);
+ *
+ * angular.forEach(views, function (config, name) {
+ * var autoName = (state.name + '.' + name).replace('.', '/');
+ * config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
+ * result[name] = config;
+ * });
+ * return result;
+ * });
+ *
+ * $stateProvider.state('home', {
+ * views: {
+ * 'contact.list': { controller: 'ListController' },
+ * 'contact.item': { controller: 'ItemController' }
+ * }
+ * });
+ *
+ * // ...
+ *
+ * $state.go('home');
+ * // Auto-populates list and item views with /partials/home/contact/list.html,
+ * // and /partials/home/contact/item.html, respectively.
+ * </pre>
+ *
+ * @param {string} name The name of the builder function to decorate.
+ * @param {object} func A function that is responsible for decorating the original
+ * builder function. The function receives two parameters:
+ *
+ * - `{object}` - state - The state config object.
+ * - `{object}` - super - The original builder function.
+ *
+ * @return {object} $stateProvider - $stateProvider instance
+ */
+ this.decorator = decorator;
+ function decorator(name, func) {
+ /*jshint validthis: true */
+ if (isString(name) && !isDefined(func)) {
+ return stateBuilder[name];
+ }
+ if (!isFunction(func) || !isString(name)) {
+ return this;
+ }
+ if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
+ stateBuilder.$delegates[name] = stateBuilder[name];
+ }
+ stateBuilder[name] = func;
+ return this;
+ }
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$stateProvider#state
+ * @methodOf ui.router.state.$stateProvider
+ *
+ * @description
+ * Registers a state configuration under a given state name. The stateConfig object
+ * has the following acceptable properties.
+ *
+ * @param {string} name A unique state name, e.g. "home", "about", "contacts".
+ * To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
+ * @param {object} stateConfig State configuration object.
+ * @param {string|function=} stateConfig.template
+ * <a id='template'></a>
+ * html template as a string or a function that returns
+ * an html template as a string which should be used by the uiView directives. This property
+ * takes precedence over templateUrl.
+ *
+ * If `template` is a function, it will be called with the following parameters:
+ *
+ * - {array.<object>} - state parameters extracted from the current $location.path() by
+ * applying the current state
+ *
+ * <pre>template:
+ * "<h1>inline template definition</h1>" +
+ * "<div ui-view></div>"</pre>
+ * <pre>template: function(params) {
+ * return "<h1>generated template</h1>"; }</pre>
+ * </div>
+ *
+ * @param {string|function=} stateConfig.templateUrl
+ * <a id='templateUrl'></a>
+ *
+ * path or function that returns a path to an html
+ * template that should be used by uiView.
+ *
+ * If `templateUrl` is a function, it will be called with the following parameters:
+ *
+ * - {array.<object>} - state parameters extracted from the current $location.path() by
+ * applying the current state
+ *
+ * <pre>templateUrl: "home.html"</pre>
+ * <pre>templateUrl: function(params) {
+ * return myTemplates[params.pageId]; }</pre>
+ *
+ * @param {function=} stateConfig.templateProvider
+ * <a id='templateProvider'></a>
+ * Provider function that returns HTML content string.
+ * <pre> templateProvider:
+ * function(MyTemplateService, params) {
+ * return MyTemplateService.getTemplate(params.pageId);
+ * }</pre>
+ *
+ * @param {string|function=} stateConfig.controller
+ * <a id='controller'></a>
+ *
+ * Controller fn that should be associated with newly
+ * related scope or the name of a registered controller if passed as a string.
+ * Optionally, the ControllerAs may be declared here.
+ * <pre>controller: "MyRegisteredController"</pre>
+ * <pre>controller:
+ * "MyRegisteredController as fooCtrl"}</pre>
+ * <pre>controller: function($scope, MyService) {
+ * $scope.data = MyService.getData(); }</pre>
+ *
+ * @param {function=} stateConfig.controllerProvider
+ * <a id='controllerProvider'></a>
+ *
+ * Injectable provider function that returns the actual controller or string.
+ * <pre>controllerProvider:
+ * function(MyResolveData) {
+ * if (MyResolveData.foo)
+ * return "FooCtrl"
+ * else if (MyResolveData.bar)
+ * return "BarCtrl";
+ * else return function($scope) {
+ * $scope.baz = "Qux";
+ * }
+ * }</pre>
+ *
+ * @param {string=} stateConfig.controllerAs
+ * <a id='controllerAs'></a>
+ *
+ * A controller alias name. If present the controller will be
+ * published to scope under the controllerAs name.
+ * <pre>controllerAs: "myCtrl"</pre>
+ *
+ * @param {string|object=} stateConfig.parent
+ * <a id='parent'></a>
+ * Optionally specifies the parent state of this state.
+ *
+ * <pre>parent: 'parentState'</pre>
+ * <pre>parent: parentState // JS variable</pre>
+ *
+ * @param {object=} stateConfig.resolve
+ * <a id='resolve'></a>
+ *
+ * An optional map<string, function> of dependencies which
+ * should be injected into the controller. If any of these dependencies are promises,
+ * the router will wait for them all to be resolved before the controller is instantiated.
+ * If all the promises are resolved successfully, the $stateChangeSuccess event is fired
+ * and the values of the resolved promises are injected into any controllers that reference them.
+ * If any of the promises are rejected the $stateChangeError event is fired.
+ *
+ * The map object is:
+ *
+ * - key - {string}: name of dependency to be injected into controller
+ * - factory - {string|function}: If string then it is alias for service. Otherwise if function,
+ * it is injected and return value it treated as dependency. If result is a promise, it is
+ * resolved before its value is injected into controller.
+ *
+ * <pre>resolve: {
+ * myResolve1:
+ * function($http, $stateParams) {
+ * return $http.get("/api/foos/"+stateParams.fooID);
+ * }
+ * }</pre>
+ *
+ * @param {string=} stateConfig.url
+ * <a id='url'></a>
+ *
+ * A url fragment with optional parameters. When a state is navigated or
+ * transitioned to, the `$stateParams` service will be populated with any
+ * parameters that were passed.
+ *
+ * (See {@link ui.router.util.type:UrlMatcher UrlMatcher} `UrlMatcher`} for
+ * more details on acceptable patterns )
+ *
+ * examples:
+ * <pre>url: "/home"
+ * url: "/users/:userid"
+ * url: "/books/{bookid:[a-zA-Z_-]}"
+ * url: "/books/{categoryid:int}"
+ * url: "/books/{publishername:string}/{categoryid:int}"
+ * url: "/messages?before&after"
+ * url: "/messages?{before:date}&{after:date}"
+ * url: "/messages/:mailboxid?{before:date}&{after:date}"
+ * </pre>
+ *
+ * @param {object=} stateConfig.views
+ * <a id='views'></a>
+ * an optional map<string, object> which defined multiple views, or targets views
+ * manually/explicitly.
+ *
+ * Examples:
+ *
+ * Targets three named `ui-view`s in the parent state's template
+ * <pre>views: {
+ * header: {
+ * controller: "headerCtrl",
+ * templateUrl: "header.html"
+ * }, body: {
+ * controller: "bodyCtrl",
+ * templateUrl: "body.html"
+ * }, footer: {
+ * controller: "footCtrl",
+ * templateUrl: "footer.html"
+ * }
+ * }</pre>
+ *
+ * Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template.
+ * <pre>views: {
+ * 'header@top': {
+ * controller: "msgHeaderCtrl",
+ * templateUrl: "msgHeader.html"
+ * }, 'body': {
+ * controller: "messagesCtrl",
+ * templateUrl: "messages.html"
+ * }
+ * }</pre>
+ *
+ * @param {boolean=} [stateConfig.abstract=false]
+ * <a id='abstract'></a>
+ * An abstract state will never be directly activated,
+ * but can provide inherited properties to its common children states.
+ * <pre>abstract: true</pre>
+ *
+ * @param {function=} stateConfig.onEnter
+ * <a id='onEnter'></a>
+ *
+ * Callback function for when a state is entered. Good way
+ * to trigger an action or dispatch an event, such as opening a dialog.
+ * If minifying your scripts, make sure to explictly annotate this function,
+ * because it won't be automatically annotated by your build tools.
+ *
+ * <pre>onEnter: function(MyService, $stateParams) {
+ * MyService.foo($stateParams.myParam);
+ * }</pre>
+ *
+ * @param {function=} stateConfig.onExit
+ * <a id='onExit'></a>
+ *
+ * Callback function for when a state is exited. Good way to
+ * trigger an action or dispatch an event, such as opening a dialog.
+ * If minifying your scripts, make sure to explictly annotate this function,
+ * because it won't be automatically annotated by your build tools.
+ *
+ * <pre>onExit: function(MyService, $stateParams) {
+ * MyService.cleanup($stateParams.myParam);
+ * }</pre>
+ *
+ * @param {boolean=} [stateConfig.reloadOnSearch=true]
+ * <a id='reloadOnSearch'></a>
+ *
+ * If `false`, will not retrigger the same state
+ * just because a search/query parameter has changed (via $location.search() or $location.hash()).
+ * Useful for when you'd like to modify $location.search() without triggering a reload.
+ * <pre>reloadOnSearch: false</pre>
+ *
+ * @param {object=} stateConfig.data
+ * <a id='data'></a>
+ *
+ * Arbitrary data object, useful for custom configuration. The parent state's `data` is
+ * prototypally inherited. In other words, adding a data property to a state adds it to
+ * the entire subtree via prototypal inheritance.
+ *
+ * <pre>data: {
+ * requiredRole: 'foo'
+ * } </pre>
+ *
+ * @param {object=} stateConfig.params
+ * <a id='params'></a>
+ *
+ * A map which optionally configures parameters declared in the `url`, or
+ * defines additional non-url parameters. For each parameter being
+ * configured, add a configuration object keyed to the name of the parameter.
+ *
+ * Each parameter configuration object may contain the following properties:
+ *
+ * - ** value ** - {object|function=}: specifies the default value for this
+ * parameter. This implicitly sets this parameter as optional.
+ *
+ * When UI-Router routes to a state and no value is
+ * specified for this parameter in the URL or transition, the
+ * default value will be used instead. If `value` is a function,
+ * it will be injected and invoked, and the return value used.
+ *
+ * *Note*: `undefined` is treated as "no default value" while `null`
+ * is treated as "the default value is `null`".
+ *
+ * *Shorthand*: If you only need to configure the default value of the
+ * parameter, you may use a shorthand syntax. In the **`params`**
+ * map, instead mapping the param name to a full parameter configuration
+ * object, simply set map it to the default parameter value, e.g.:
+ *
+ * <pre>// define a parameter's default value
+ * params: {
+ * param1: { value: "defaultValue" }
+ * }
+ * // shorthand default values
+ * params: {
+ * param1: "defaultValue",
+ * param2: "param2Default"
+ * }</pre>
+ *
+ * - ** array ** - {boolean=}: *(default: false)* If true, the param value will be
+ * treated as an array of values. If you specified a Type, the value will be
+ * treated as an array of the specified Type. Note: query parameter values
+ * default to a special `"auto"` mode.
+ *
+ * For query parameters in `"auto"` mode, if multiple values for a single parameter
+ * are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values
+ * are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`). However, if
+ * only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single
+ * value (e.g.: `{ foo: '1' }`).
+ *
+ * <pre>params: {
+ * param1: { array: true }
+ * }</pre>
+ *
+ * - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when
+ * the current parameter value is the same as the default value. If `squash` is not set, it uses the
+ * configured default squash policy.
+ * (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})
+ *
+ * There are three squash settings:
+ *
+ * - false: The parameter's default value is not squashed. It is encoded and included in the URL
+ * - true: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed
+ * by slashes in the state's `url` declaration, then one of those slashes are omitted.
+ * This can allow for cleaner looking URLs.
+ * - `"<arbitrary string>"`: The parameter's default value is replaced with an arbitrary placeholder of your choice.
+ *
+ * <pre>params: {
+ * param1: {
+ * value: "defaultId",
+ * squash: true
+ * } }
+ * // squash "defaultValue" to "~"
+ * params: {
+ * param1: {
+ * value: "defaultValue",
+ * squash: "~"
+ * } }
+ * </pre>
+ *
+ *
+ * @example
+ * <pre>
+ * // Some state name examples
+ *
+ * // stateName can be a single top-level name (must be unique).
+ * $stateProvider.state("home", {});
+ *
+ * // Or it can be a nested state name. This state is a child of the
+ * // above "home" state.
+ * $stateProvider.state("home.newest", {});
+ *
+ * // Nest states as deeply as needed.
+ * $stateProvider.state("home.newest.abc.xyz.inception", {});
+ *
+ * // state() returns $stateProvider, so you can chain state declarations.
+ * $stateProvider
+ * .state("home", {})
+ * .state("about", {})
+ * .state("contacts", {});
+ * </pre>
+ *
+ */
+ this.state = state;
+ function state(name, definition) {
+ /*jshint validthis: true */
+ if (isObject(name)) definition = name;
+ else definition.name = name;
+ registerState(definition);
+ return this;
+ }
+
+ /**
+ * @ngdoc object
+ * @name ui.router.state.$state
+ *
+ * @requires $rootScope
+ * @requires $q
+ * @requires ui.router.state.$view
+ * @requires $injector
+ * @requires ui.router.util.$resolve
+ * @requires ui.router.state.$stateParams
+ * @requires ui.router.router.$urlRouter
+ *
+ * @property {object} params A param object, e.g. {sectionId: section.id)}, that
+ * you'd like to test against the current active state.
+ * @property {object} current A reference to the state's config object. However
+ * you passed it in. Useful for accessing custom data.
+ * @property {object} transition Currently pending transition. A promise that'll
+ * resolve or reject.
+ *
+ * @description
+ * `$state` service is responsible for representing states as well as transitioning
+ * between them. It also provides interfaces to ask for current state or even states
+ * you're coming from.
+ */
+ this.$get = $get;
+ $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];
+ function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) {
+
+ var TransitionSuperseded = $q.reject(new Error('transition superseded'));
+ var TransitionPrevented = $q.reject(new Error('transition prevented'));
+ var TransitionAborted = $q.reject(new Error('transition aborted'));
+ var TransitionFailed = $q.reject(new Error('transition failed'));
+
+ // Handles the case where a state which is the target of a transition is not found, and the user
+ // can optionally retry or defer the transition
+ function handleRedirect(redirect, state, params, options) {
+ /**
+ * @ngdoc event
+ * @name ui.router.state.$state#$stateNotFound
+ * @eventOf ui.router.state.$state
+ * @eventType broadcast on root scope
+ * @description
+ * Fired when a requested state **cannot be found** using the provided state name during transition.
+ * The event is broadcast allowing any handlers a single chance to deal with the error (usually by
+ * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,
+ * you can see its three properties in the example. You can use `event.preventDefault()` to abort the
+ * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.
+ *
+ * @param {Object} event Event object.
+ * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.
+ * @param {State} fromState Current state object.
+ * @param {Object} fromParams Current state params.
+ *
+ * @example
+ *
+ * <pre>
+ * // somewhere, assume lazy.state has not been defined
+ * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
+ *
+ * // somewhere else
+ * $scope.$on('$stateNotFound',
+ * function(event, unfoundState, fromState, fromParams){
+ * console.log(unfoundState.to); // "lazy.state"
+ * console.log(unfoundState.toParams); // {a:1, b:2}
+ * console.log(unfoundState.options); // {inherit:false} + default options
+ * })
+ * </pre>
+ */
+ var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);
+
+ if (evt.defaultPrevented) {
+ $urlRouter.update();
+ return TransitionAborted;
+ }
+
+ if (!evt.retry) {
+ return null;
+ }
+
+ // Allow the handler to return a promise to defer state lookup retry
+ if (options.$retry) {
+ $urlRouter.update();
+ return TransitionFailed;
+ }
+ var retryTransition = $state.transition = $q.when(evt.retry);
+
+ retryTransition.then(function() {
+ if (retryTransition !== $state.transition) return TransitionSuperseded;
+ redirect.options.$retry = true;
+ return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);
+ }, function() {
+ return TransitionAborted;
+ });
+ $urlRouter.update();
+
+ return retryTransition;
+ }
+
+ root.locals = { resolve: null, globals: { $stateParams: {} } };
+
+ $state = {
+ params: {},
+ current: root.self,
+ $current: root,
+ transition: null
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#reload
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * A method that force reloads the current state. All resolves are re-resolved,
+ * controllers reinstantiated, and events re-fired.
+ *
+ * @example
+ * <pre>
+ * var app angular.module('app', ['ui.router']);
+ *
+ * app.controller('ctrl', function ($scope, $state) {
+ * $scope.reload = function(){
+ * $state.reload();
+ * }
+ * });
+ * </pre>
+ *
+ * `reload()` is just an alias for:
+ * <pre>
+ * $state.transitionTo($state.current, $stateParams, {
+ * reload: true, inherit: false, notify: true
+ * });
+ * </pre>
+ *
+ * @param {string=|object=} state - A state name or a state object, which is the root of the resolves to be re-resolved.
+ * @example
+ * <pre>
+ * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'
+ * //and current state is 'contacts.detail.item'
+ * var app angular.module('app', ['ui.router']);
+ *
+ * app.controller('ctrl', function ($scope, $state) {
+ * $scope.reload = function(){
+ * //will reload 'contact.detail' and 'contact.detail.item' states
+ * $state.reload('contact.detail');
+ * }
+ * });
+ * </pre>
+ *
+ * `reload()` is just an alias for:
+ * <pre>
+ * $state.transitionTo($state.current, $stateParams, {
+ * reload: true, inherit: false, notify: true
+ * });
+ * </pre>
+
+ * @returns {promise} A promise representing the state of the new transition. See
+ * {@link ui.router.state.$state#methods_go $state.go}.
+ */
+ $state.reload = function reload(state) {
+ return $state.transitionTo($state.current, $stateParams, { reload: state || true, inherit: false, notify: true});
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#go
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * Convenience method for transitioning to a new state. `$state.go` calls
+ * `$state.transitionTo` internally but automatically sets options to
+ * `{ location: true, inherit: true, relative: $state.$current, notify: true }`.
+ * This allows you to easily use an absolute or relative to path and specify
+ * only the parameters you'd like to update (while letting unspecified parameters
+ * inherit from the currently active ancestor states).
+ *
+ * @example
+ * <pre>
+ * var app = angular.module('app', ['ui.router']);
+ *
+ * app.controller('ctrl', function ($scope, $state) {
+ * $scope.changeState = function () {
+ * $state.go('contact.detail');
+ * };
+ * });
+ * </pre>
+ * <img src='../ngdoc_assets/StateGoExamples.png'/>
+ *
+ * @param {string} to Absolute state name or relative state path. Some examples:
+ *
+ * - `$state.go('contact.detail')` - will go to the `contact.detail` state
+ * - `$state.go('^')` - will go to a parent state
+ * - `$state.go('^.sibling')` - will go to a sibling state
+ * - `$state.go('.child.grandchild')` - will go to grandchild state
+ *
+ * @param {object=} params A map of the parameters that will be sent to the state,
+ * will populate $stateParams. Any parameters that are not specified will be inherited from currently
+ * defined parameters. This allows, for example, going to a sibling state that shares parameters
+ * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.
+ * transitioning to a sibling will get you the parameters for all parents, transitioning to a child
+ * will get you all current parameters, etc.
+ * @param {object=} options Options object. The options are:
+ *
+ * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
+ * will not. If string, must be `"replace"`, which will update url and also replace last history record.
+ * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
+ * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
+ * defines which state to be relative from.
+ * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
+ * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
+ * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
+ * use this when you want to force a reload when *everything* is the same, including search params.
+ *
+ * @returns {promise} A promise representing the state of the new transition.
+ *
+ * Possible success values:
+ *
+ * - $state.current
+ *
+ * <br/>Possible rejection values:
+ *
+ * - 'transition superseded' - when a newer transition has been started after this one
+ * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener
+ * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or
+ * when a `$stateNotFound` `event.retry` promise errors.
+ * - 'transition failed' - when a state has been unsuccessfully found after 2 tries.
+ * - *resolve error* - when an error has occurred with a `resolve`
+ *
+ */
+ $state.go = function go(to, params, options) {
+ return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#transitionTo
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
+ * uses `transitionTo` internally. `$state.go` is recommended in most situations.
+ *
+ * @example
+ * <pre>
+ * var app = angular.module('app', ['ui.router']);
+ *
+ * app.controller('ctrl', function ($scope, $state) {
+ * $scope.changeState = function () {
+ * $state.transitionTo('contact.detail');
+ * };
+ * });
+ * </pre>
+ *
+ * @param {string} to State name.
+ * @param {object=} toParams A map of the parameters that will be sent to the state,
+ * will populate $stateParams.
+ * @param {object=} options Options object. The options are:
+ *
+ * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
+ * will not. If string, must be `"replace"`, which will update url and also replace last history record.
+ * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
+ * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'),
+ * defines which state to be relative from.
+ * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
+ * - **`reload`** (v0.2.5) - {boolean=false|string=|object=}, If `true` will force transition even if the state or params
+ * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
+ * use this when you want to force a reload when *everything* is the same, including search params.
+ * if String, then will reload the state with the name given in reload, and any children.
+ * if Object, then a stateObj is expected, will reload the state found in stateObj, and any children.
+ *
+ * @returns {promise} A promise representing the state of the new transition. See
+ * {@link ui.router.state.$state#methods_go $state.go}.
+ */
+ $state.transitionTo = function transitionTo(to, toParams, options) {
+ toParams = toParams || {};
+ options = extend({
+ location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
+ }, options || {});
+
+ var from = $state.$current, fromParams = $state.params, fromPath = from.path;
+ var evt, toState = findState(to, options.relative);
+
+ // Store the hash param for later (since it will be stripped out by various methods)
+ var hash = toParams['#'];
+
+ if (!isDefined(toState)) {
+ var redirect = { to: to, toParams: toParams, options: options };
+ var redirectResult = handleRedirect(redirect, from.self, fromParams, options);
+
+ if (redirectResult) {
+ return redirectResult;
+ }
+
+ // Always retry once if the $stateNotFound was not prevented
+ // (handles either redirect changed or state lazy-definition)
+ to = redirect.to;
+ toParams = redirect.toParams;
+ options = redirect.options;
+ toState = findState(to, options.relative);
+
+ if (!isDefined(toState)) {
+ if (!options.relative) throw new Error("No such state '" + to + "'");
+ throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
+ }
+ }
+ if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'");
+ if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);
+ if (!toState.params.$$validates(toParams)) return TransitionFailed;
+
+ toParams = toState.params.$$values(toParams);
+ to = toState;
+
+ var toPath = to.path;
+
+ // Starting from the root of the path, keep all levels that haven't changed
+ var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];
+
+ if (!options.reload) {
+ while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {
+ locals = toLocals[keep] = state.locals;
+ keep++;
+ state = toPath[keep];
+ }
+ } else if (isString(options.reload) || isObject(options.reload)) {
+ if (isObject(options.reload) && !options.reload.name) {
+ throw new Error('Invalid reload state object');
+ }
+
+ var reloadState = options.reload === true ? fromPath[0] : findState(options.reload);
+ if (options.reload && !reloadState) {
+ throw new Error("No such reload state '" + (isString(options.reload) ? options.reload : options.reload.name) + "'");
+ }
+
+ while (state && state === fromPath[keep] && state !== reloadState) {
+ locals = toLocals[keep] = state.locals;
+ keep++;
+ state = toPath[keep];
+ }
+ }
+
+ // If we're going to the same state and all locals are kept, we've got nothing to do.
+ // But clear 'transition', as we still want to cancel any other pending transitions.
+ // TODO: We may not want to bump 'transition' if we're called from a location change
+ // that we've initiated ourselves, because we might accidentally abort a legitimate
+ // transition initiated from code?
+ if (shouldSkipReload(to, toParams, from, fromParams, locals, options)) {
+ if (hash) toParams['#'] = hash;
+ $state.params = toParams;
+ copy($state.params, $stateParams);
+ if (options.location && to.navigable && to.navigable.url) {
+ $urlRouter.push(to.navigable.url, toParams, {
+ $$avoidResync: true, replace: options.location === 'replace'
+ });
+ $urlRouter.update(true);
+ }
+ $state.transition = null;
+ return $q.when($state.current);
+ }
+
+ // Filter parameters before we pass them to event handlers etc.
+ toParams = filterByKeys(to.params.$$keys(), toParams || {});
+
+ // Broadcast start event and cancel the transition if requested
+ if (options.notify) {
+ /**
+ * @ngdoc event
+ * @name ui.router.state.$state#$stateChangeStart
+ * @eventOf ui.router.state.$state
+ * @eventType broadcast on root scope
+ * @description
+ * Fired when the state transition **begins**. You can use `event.preventDefault()`
+ * to prevent the transition from happening and then the transition promise will be
+ * rejected with a `'transition prevented'` value.
+ *
+ * @param {Object} event Event object.
+ * @param {State} toState The state being transitioned to.
+ * @param {Object} toParams The params supplied to the `toState`.
+ * @param {State} fromState The current state, pre-transition.
+ * @param {Object} fromParams The params supplied to the `fromState`.
+ *
+ * @example
+ *
+ * <pre>
+ * $rootScope.$on('$stateChangeStart',
+ * function(event, toState, toParams, fromState, fromParams){
+ * event.preventDefault();
+ * // transitionTo() promise will be rejected with
+ * // a 'transition prevented' error
+ * })
+ * </pre>
+ */
+ if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {
+ $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams);
+ $urlRouter.update();
+ return TransitionPrevented;
+ }
+ }
+
+ // Resolve locals for the remaining states, but don't update any global state just
+ // yet -- if anything fails to resolve the current state needs to remain untouched.
+ // We also set up an inheritance chain for the locals here. This allows the view directive
+ // to quickly look up the correct definition for each view in the current state. Even
+ // though we create the locals object itself outside resolveState(), it is initially
+ // empty and gets filled asynchronously. We need to keep track of the promise for the
+ // (fully resolved) current locals, and pass this down the chain.
+ var resolved = $q.when(locals);
+
+ for (var l = keep; l < toPath.length; l++, state = toPath[l]) {
+ locals = toLocals[l] = inherit(locals);
+ resolved = resolveState(state, toParams, state === to, resolved, locals, options);
+ }
+
+ // Once everything is resolved, we are ready to perform the actual transition
+ // and return a promise for the new state. We also keep track of what the
+ // current promise is, so that we can detect overlapping transitions and
+ // keep only the outcome of the last transition.
+ var transition = $state.transition = resolved.then(function () {
+ var l, entering, exiting;
+
+ if ($state.transition !== transition) return TransitionSuperseded;
+
+ // Exit 'from' states not kept
+ for (l = fromPath.length - 1; l >= keep; l--) {
+ exiting = fromPath[l];
+ if (exiting.self.onExit) {
+ $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);
+ }
+ exiting.locals = null;
+ }
+
+ // Enter 'to' states not kept
+ for (l = keep; l < toPath.length; l++) {
+ entering = toPath[l];
+ entering.locals = toLocals[l];
+ if (entering.self.onEnter) {
+ $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);
+ }
+ }
+
+ // Re-add the saved hash before we start returning things
+ if (hash) toParams['#'] = hash;
+
+ // Run it again, to catch any transitions in callbacks
+ if ($state.transition !== transition) return TransitionSuperseded;
+
+ // Update globals in $state
+ $state.$current = to;
+ $state.current = to.self;
+ $state.params = toParams;
+ copy($state.params, $stateParams);
+ $state.transition = null;
+
+ if (options.location && to.navigable) {
+ $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {
+ $$avoidResync: true, replace: options.location === 'replace'
+ });
+ }
+
+ if (options.notify) {
+ /**
+ * @ngdoc event
+ * @name ui.router.state.$state#$stateChangeSuccess
+ * @eventOf ui.router.state.$state
+ * @eventType broadcast on root scope
+ * @description
+ * Fired once the state transition is **complete**.
+ *
+ * @param {Object} event Event object.
+ * @param {State} toState The state being transitioned to.
+ * @param {Object} toParams The params supplied to the `toState`.
+ * @param {State} fromState The current state, pre-transition.
+ * @param {Object} fromParams The params supplied to the `fromState`.
+ */
+ $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
+ }
+ $urlRouter.update(true);
+
+ return $state.current;
+ }, function (error) {
+ if ($state.transition !== transition) return TransitionSuperseded;
+
+ $state.transition = null;
+ /**
+ * @ngdoc event
+ * @name ui.router.state.$state#$stateChangeError
+ * @eventOf ui.router.state.$state
+ * @eventType broadcast on root scope
+ * @description
+ * Fired when an **error occurs** during transition. It's important to note that if you
+ * have any errors in your resolve functions (javascript errors, non-existent services, etc)
+ * they will not throw traditionally. You must listen for this $stateChangeError event to
+ * catch **ALL** errors.
+ *
+ * @param {Object} event Event object.
+ * @param {State} toState The state being transitioned to.
+ * @param {Object} toParams The params supplied to the `toState`.
+ * @param {State} fromState The current state, pre-transition.
+ * @param {Object} fromParams The params supplied to the `fromState`.
+ * @param {Error} error The resolve error object.
+ */
+ evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
+
+ if (!evt.defaultPrevented) {
+ $urlRouter.update();
+ }
+
+ return $q.reject(error);
+ });
+
+ return transition;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#is
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * Similar to {@link ui.router.state.$state#methods_includes $state.includes},
+ * but only checks for the full state name. If params is supplied then it will be
+ * tested for strict equality against the current active params object, so all params
+ * must match with none missing and no extras.
+ *
+ * @example
+ * <pre>
+ * $state.$current.name = 'contacts.details.item';
+ *
+ * // absolute name
+ * $state.is('contact.details.item'); // returns true
+ * $state.is(contactDetailItemStateObject); // returns true
+ *
+ * // relative name (. and ^), typically from a template
+ * // E.g. from the 'contacts.details' template
+ * <div ng-class="{highlighted: $state.is('.item')}">Item</div>
+ * </pre>
+ *
+ * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.
+ * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like
+ * to test against the current active state.
+ * @param {object=} options An options object. The options are:
+ *
+ * - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will
+ * test relative to `options.relative` state (or name).
+ *
+ * @returns {boolean} Returns true if it is the state.
+ */
+ $state.is = function is(stateOrName, params, options) {
+ options = extend({ relative: $state.$current }, options || {});
+ var state = findState(stateOrName, options.relative);
+
+ if (!isDefined(state)) { return undefined; }
+ if ($state.$current !== state) { return false; }
+ return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#includes
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * A method to determine if the current active state is equal to or is the child of the
+ * state stateName. If any params are passed then they will be tested for a match as well.
+ * Not all the parameters need to be passed, just the ones you'd like to test for equality.
+ *
+ * @example
+ * Partial and relative names
+ * <pre>
+ * $state.$current.name = 'contacts.details.item';
+ *
+ * // Using partial names
+ * $state.includes("contacts"); // returns true
+ * $state.includes("contacts.details"); // returns true
+ * $state.includes("contacts.details.item"); // returns true
+ * $state.includes("contacts.list"); // returns false
+ * $state.includes("about"); // returns false
+ *
+ * // Using relative names (. and ^), typically from a template
+ * // E.g. from the 'contacts.details' template
+ * <div ng-class="{highlighted: $state.includes('.item')}">Item</div>
+ * </pre>
+ *
+ * Basic globbing patterns
+ * <pre>
+ * $state.$current.name = 'contacts.details.item.url';
+ *
+ * $state.includes("*.details.*.*"); // returns true
+ * $state.includes("*.details.**"); // returns true
+ * $state.includes("**.item.**"); // returns true
+ * $state.includes("*.details.item.url"); // returns true
+ * $state.includes("*.details.*.url"); // returns true
+ * $state.includes("*.details.*"); // returns false
+ * $state.includes("item.**"); // returns false
+ * </pre>
+ *
+ * @param {string} stateOrName A partial name, relative name, or glob pattern
+ * to be searched for within the current state name.
+ * @param {object=} params A param object, e.g. `{sectionId: section.id}`,
+ * that you'd like to test against the current active state.
+ * @param {object=} options An options object. The options are:
+ *
+ * - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set,
+ * .includes will test relative to `options.relative` state (or name).
+ *
+ * @returns {boolean} Returns true if it does include the state
+ */
+ $state.includes = function includes(stateOrName, params, options) {
+ options = extend({ relative: $state.$current }, options || {});
+ if (isString(stateOrName) && isGlob(stateOrName)) {
+ if (!doesStateMatchGlob(stateOrName)) {
+ return false;
+ }
+ stateOrName = $state.$current.name;
+ }
+
+ var state = findState(stateOrName, options.relative);
+ if (!isDefined(state)) { return undefined; }
+ if (!isDefined($state.$current.includes[state.name])) { return false; }
+ return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;
+ };
+
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#href
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * A url generation method that returns the compiled url for the given state populated with the given params.
+ *
+ * @example
+ * <pre>
+ * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
+ * </pre>
+ *
+ * @param {string|object} stateOrName The state name or state object you'd like to generate a url from.
+ * @param {object=} params An object of parameter values to fill the state's required parameters.
+ * @param {object=} options Options object. The options are:
+ *
+ * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the
+ * first parameter, then the constructed href url will be built from the first navigable ancestor (aka
+ * ancestor with a valid url).
+ * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
+ * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
+ * defines which state to be relative from.
+ * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
+ *
+ * @returns {string} compiled state url
+ */
+ $state.href = function href(stateOrName, params, options) {
+ options = extend({
+ lossy: true,
+ inherit: true,
+ absolute: false,
+ relative: $state.$current
+ }, options || {});
+
+ var state = findState(stateOrName, options.relative);
+
+ if (!isDefined(state)) return null;
+ if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);
+
+ var nav = (state && options.lossy) ? state.navigable : state;
+
+ if (!nav || nav.url === undefined || nav.url === null) {
+ return null;
+ }
+ return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys().concat('#'), params || {}), {
+ absolute: options.absolute
+ });
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$state#get
+ * @methodOf ui.router.state.$state
+ *
+ * @description
+ * Returns the state configuration object for any specific state or all states.
+ *
+ * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for
+ * the requested state. If not provided, returns an array of ALL state configs.
+ * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.
+ * @returns {Object|Array} State configuration object or array of all objects.
+ */
+ $state.get = function (stateOrName, context) {
+ if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });
+ var state = findState(stateOrName, context || $state.$current);
+ return (state && state.self) ? state.self : null;
+ };
+
+ function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {
+ // Make a restricted $stateParams with only the parameters that apply to this state if
+ // necessary. In addition to being available to the controller and onEnter/onExit callbacks,
+ // we also need $stateParams to be available for any $injector calls we make during the
+ // dependency resolution process.
+ var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);
+ var locals = { $stateParams: $stateParams };
+
+ // Resolve 'global' dependencies for the state, i.e. those not specific to a view.
+ // We're also including $stateParams in this; that way the parameters are restricted
+ // to the set that should be visible to the state, and are independent of when we update
+ // the global $state and $stateParams values.
+ dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
+ var promises = [dst.resolve.then(function (globals) {
+ dst.globals = globals;
+ })];
+ if (inherited) promises.push(inherited);
+
+ function resolveViews() {
+ var viewsPromises = [];
+
+ // Resolve template and dependencies for all views.
+ forEach(state.views, function (view, name) {
+ var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});
+ injectables.$template = [ function () {
+ return $view.load(name, { view: view, locals: dst.globals, params: $stateParams, notify: options.notify }) || '';
+ }];
+
+ viewsPromises.push($resolve.resolve(injectables, dst.globals, dst.resolve, state).then(function (result) {
+ // References to the controller (only instantiated at link time)
+ if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {
+ var injectLocals = angular.extend({}, injectables, dst.globals);
+ result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);
+ } else {
+ result.$$controller = view.controller;
+ }
+ // Provide access to the state itself for internal use
+ result.$$state = state;
+ result.$$controllerAs = view.controllerAs;
+ dst[name] = result;
+ }));
+ });
+
+ return $q.all(viewsPromises).then(function(){
+ return dst.globals;
+ });
+ }
+
+ // Wait for all the promises and then return the activation object
+ return $q.all(promises).then(resolveViews).then(function (values) {
+ return dst;
+ });
+ }
+
+ return $state;
+ }
+
+ function shouldSkipReload(to, toParams, from, fromParams, locals, options) {
+ // Return true if there are no differences in non-search (path/object) params, false if there are differences
+ function nonSearchParamsEqual(fromAndToState, fromParams, toParams) {
+ // Identify whether all the parameters that differ between `fromParams` and `toParams` were search params.
+ function notSearchParam(key) {
+ return fromAndToState.params[key].location != "search";
+ }
+ var nonQueryParamKeys = fromAndToState.params.$$keys().filter(notSearchParam);
+ var nonQueryParams = pick.apply({}, [fromAndToState.params].concat(nonQueryParamKeys));
+ var nonQueryParamSet = new $$UMFP.ParamSet(nonQueryParams);
+ return nonQueryParamSet.$$equals(fromParams, toParams);
+ }
+
+ // If reload was not explicitly requested
+ // and we're transitioning to the same state we're already in
+ // and the locals didn't change
+ // or they changed in a way that doesn't merit reloading
+ // (reloadOnParams:false, or reloadOnSearch.false and only search params changed)
+ // Then return true.
+ if (!options.reload && to === from &&
+ (locals === from.locals || (to.self.reloadOnSearch === false && nonSearchParamsEqual(from, fromParams, toParams)))) {
+ return true;
+ }
+ }
+}
+
+angular.module('ui.router.state')
+ .value('$stateParams', {})
+ .provider('$state', $StateProvider);
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/stateDirectives.js b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/stateDirectives.js
new file mode 100644
index 0000000..0999103
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/stateDirectives.js
@@ -0,0 +1,285 @@
+function parseStateRef(ref, current) {
+ var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
+ if (preparsed) ref = current + '(' + preparsed[1] + ')';
+ parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
+ if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
+ return { state: parsed[1], paramExpr: parsed[3] || null };
+}
+
+function stateContext(el) {
+ var stateData = el.parent().inheritedData('$uiView');
+
+ if (stateData && stateData.state && stateData.state.name) {
+ return stateData.state;
+ }
+}
+
+/**
+ * @ngdoc directive
+ * @name ui.router.state.directive:ui-sref
+ *
+ * @requires ui.router.state.$state
+ * @requires $timeout
+ *
+ * @restrict A
+ *
+ * @description
+ * A directive that binds a link (`<a>` tag) to a state. If the state has an associated
+ * URL, the directive will automatically generate & update the `href` attribute via
+ * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking
+ * the link will trigger a state transition with optional parameters.
+ *
+ * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be
+ * handled natively by the browser.
+ *
+ * You can also use relative state paths within ui-sref, just like the relative
+ * paths passed to `$state.go()`. You just need to be aware that the path is relative
+ * to the state that the link lives in, in other words the state that loaded the
+ * template containing the link.
+ *
+ * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}
+ * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,
+ * and `reload`.
+ *
+ * @example
+ * Here's an example of how you'd use ui-sref and how it would compile. If you have the
+ * following template:
+ * <pre>
+ * <a ui-sref="home">Home</a> | <a ui-sref="about">About</a> | <a ui-sref="{page: 2}">Next page</a>
+ *
+ * <ul>
+ * <li ng-repeat="contact in contacts">
+ * <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
+ * </li>
+ * </ul>
+ * </pre>
+ *
+ * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):
+ * <pre>
+ * <a href="#/home" ui-sref="home">Home</a> | <a href="#/about" ui-sref="about">About</a> | <a href="#/contacts?page=2" ui-sref="{page: 2}">Next page</a>
+ *
+ * <ul>
+ * <li ng-repeat="contact in contacts">
+ * <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
+ * </li>
+ * <li ng-repeat="contact in contacts">
+ * <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
+ * </li>
+ * <li ng-repeat="contact in contacts">
+ * <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
+ * </li>
+ * </ul>
+ *
+ * <a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
+ * </pre>
+ *
+ * @param {string} ui-sref 'stateName' can be any valid absolute or relative state
+ * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}
+ */
+$StateRefDirective.$inject = ['$state', '$timeout'];
+function $StateRefDirective($state, $timeout) {
+ var allowedOptions = ['location', 'inherit', 'reload', 'absolute'];
+
+ return {
+ restrict: 'A',
+ require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
+ link: function(scope, element, attrs, uiSrefActive) {
+ var ref = parseStateRef(attrs.uiSref, $state.current.name);
+ var params = null, url = null, base = stateContext(element) || $state.$current;
+ // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
+ var hrefKind = Object.prototype.toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
+ 'xlink:href' : 'href';
+ var newHref = null, isAnchor = element.prop("tagName").toUpperCase() === "A";
+ var isForm = element[0].nodeName === "FORM";
+ var attr = isForm ? "action" : hrefKind, nav = true;
+
+ var options = { relative: base, inherit: true };
+ var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {};
+
+ angular.forEach(allowedOptions, function(option) {
+ if (option in optionsOverride) {
+ options[option] = optionsOverride[option];
+ }
+ });
+
+ var update = function(newVal) {
+ if (newVal) params = angular.copy(newVal);
+ if (!nav) return;
+
+ newHref = $state.href(ref.state, params, options);
+
+ var activeDirective = uiSrefActive[1] || uiSrefActive[0];
+ if (activeDirective) {
+ activeDirective.$$addStateInfo(ref.state, params);
+ }
+ if (newHref === null) {
+ nav = false;
+ return false;
+ }
+ attrs.$set(attr, newHref);
+ };
+
+ if (ref.paramExpr) {
+ scope.$watch(ref.paramExpr, function(newVal, oldVal) {
+ if (newVal !== params) update(newVal);
+ }, true);
+ params = angular.copy(scope.$eval(ref.paramExpr));
+ }
+ update();
+
+ if (isForm) return;
+
+ element.bind("click", function(e) {
+ var button = e.which || e.button;
+ if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {
+ // HACK: This is to allow ng-clicks to be processed before the transition is initiated:
+ var transition = $timeout(function() {
+ $state.go(ref.state, params, options);
+ });
+ e.preventDefault();
+
+ // if the state has no URL, ignore one preventDefault from the <a> directive.
+ var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0;
+ e.preventDefault = function() {
+ if (ignorePreventDefaultCount-- <= 0)
+ $timeout.cancel(transition);
+ };
+ }
+ });
+ }
+ };
+}
+
+/**
+ * @ngdoc directive
+ * @name ui.router.state.directive:ui-sref-active
+ *
+ * @requires ui.router.state.$state
+ * @requires ui.router.state.$stateParams
+ * @requires $interpolate
+ *
+ * @restrict A
+ *
+ * @description
+ * A directive working alongside ui-sref to add classes to an element when the
+ * related ui-sref directive's state is active, and removing them when it is inactive.
+ * The primary use-case is to simplify the special appearance of navigation menus
+ * relying on `ui-sref`, by having the "active" state's menu button appear different,
+ * distinguishing it from the inactive menu items.
+ *
+ * ui-sref-active can live on the same element as ui-sref or on a parent element. The first
+ * ui-sref-active found at the same level or above the ui-sref will be used.
+ *
+ * Will activate when the ui-sref's target state or any child state is active. If you
+ * need to activate only when the ui-sref target state is active and *not* any of
+ * it's children, then you will use
+ * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}
+ *
+ * @example
+ * Given the following template:
+ * <pre>
+ * <ul>
+ * <li ui-sref-active="active" class="item">
+ * <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
+ * </li>
+ * </ul>
+ * </pre>
+ *
+ *
+ * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins",
+ * the resulting HTML will appear as (note the 'active' class):
+ * <pre>
+ * <ul>
+ * <li ui-sref-active="active" class="item active">
+ * <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
+ * </li>
+ * </ul>
+ * </pre>
+ *
+ * The class name is interpolated **once** during the directives link time (any further changes to the
+ * interpolated value are ignored).
+ *
+ * Multiple classes may be specified in a space-separated format:
+ * <pre>
+ * <ul>
+ * <li ui-sref-active='class1 class2 class3'>
+ * <a ui-sref="app.user">link</a>
+ * </li>
+ * </ul>
+ * </pre>
+ */
+
+/**
+ * @ngdoc directive
+ * @name ui.router.state.directive:ui-sref-active-eq
+ *
+ * @requires ui.router.state.$state
+ * @requires ui.router.state.$stateParams
+ * @requires $interpolate
+ *
+ * @restrict A
+ *
+ * @description
+ * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate
+ * when the exact target state used in the `ui-sref` is active; no child states.
+ *
+ */
+$StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];
+function $StateRefActiveDirective($state, $stateParams, $interpolate) {
+ return {
+ restrict: "A",
+ controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
+ var states = [], activeClass;
+
+ // There probably isn't much point in $observing this
+ // uiSrefActive and uiSrefActiveEq share the same directive object with some
+ // slight difference in logic routing
+ activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope);
+
+ // Allow uiSref to communicate with uiSrefActive[Equals]
+ this.$$addStateInfo = function (newState, newParams) {
+ var state = $state.get(newState, stateContext($element));
+
+ states.push({
+ state: state || { name: newState },
+ params: newParams
+ });
+
+ update();
+ };
+
+ $scope.$on('$stateChangeSuccess', update);
+
+ // Update route state
+ function update() {
+ if (anyMatch()) {
+ $element.addClass(activeClass);
+ } else {
+ $element.removeClass(activeClass);
+ }
+ }
+
+ function anyMatch() {
+ for (var i = 0; i < states.length; i++) {
+ if (isMatch(states[i].state, states[i].params)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function isMatch(state, params) {
+ if (typeof $attrs.uiSrefActiveEq !== 'undefined') {
+ return $state.is(state.name, params);
+ } else {
+ return $state.includes(state.name, params);
+ }
+ }
+ }]
+ };
+}
+
+angular.module('ui.router.state')
+ .directive('uiSref', $StateRefDirective)
+ .directive('uiSrefActive', $StateRefActiveDirective)
+ .directive('uiSrefActiveEq', $StateRefActiveDirective);
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/stateFilters.js b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/stateFilters.js
new file mode 100644
index 0000000..e0a1175
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/stateFilters.js
@@ -0,0 +1,39 @@
+/**
+ * @ngdoc filter
+ * @name ui.router.state.filter:isState
+ *
+ * @requires ui.router.state.$state
+ *
+ * @description
+ * Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}.
+ */
+$IsStateFilter.$inject = ['$state'];
+function $IsStateFilter($state) {
+ var isFilter = function (state) {
+ return $state.is(state);
+ };
+ isFilter.$stateful = true;
+ return isFilter;
+}
+
+/**
+ * @ngdoc filter
+ * @name ui.router.state.filter:includedByState
+ *
+ * @requires ui.router.state.$state
+ *
+ * @description
+ * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.
+ */
+$IncludedByStateFilter.$inject = ['$state'];
+function $IncludedByStateFilter($state) {
+ var includesFilter = function (state) {
+ return $state.includes(state);
+ };
+ includesFilter.$stateful = true;
+ return includesFilter;
+}
+
+angular.module('ui.router.state')
+ .filter('isState', $IsStateFilter)
+ .filter('includedByState', $IncludedByStateFilter);
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/templateFactory.js b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/templateFactory.js
new file mode 100644
index 0000000..ca491a9
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/templateFactory.js
@@ -0,0 +1,110 @@
+/**
+ * @ngdoc object
+ * @name ui.router.util.$templateFactory
+ *
+ * @requires $http
+ * @requires $templateCache
+ * @requires $injector
+ *
+ * @description
+ * Service. Manages loading of templates.
+ */
+$TemplateFactory.$inject = ['$http', '$templateCache', '$injector'];
+function $TemplateFactory( $http, $templateCache, $injector) {
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$templateFactory#fromConfig
+ * @methodOf ui.router.util.$templateFactory
+ *
+ * @description
+ * Creates a template from a configuration object.
+ *
+ * @param {object} config Configuration object for which to load a template.
+ * The following properties are search in the specified order, and the first one
+ * that is defined is used to create the template:
+ *
+ * @param {string|object} config.template html string template or function to
+ * load via {@link ui.router.util.$templateFactory#fromString fromString}.
+ * @param {string|object} config.templateUrl url to load or a function returning
+ * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.
+ * @param {Function} config.templateProvider function to invoke via
+ * {@link ui.router.util.$templateFactory#fromProvider fromProvider}.
+ * @param {object} params Parameters to pass to the template function.
+ * @param {object} locals Locals to pass to `invoke` if the template is loaded
+ * via a `templateProvider`. Defaults to `{ params: params }`.
+ *
+ * @return {string|object} The template html as a string, or a promise for
+ * that string,or `null` if no template is configured.
+ */
+ this.fromConfig = function (config, params, locals) {
+ return (
+ isDefined(config.template) ? this.fromString(config.template, params) :
+ isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :
+ isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :
+ null
+ );
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$templateFactory#fromString
+ * @methodOf ui.router.util.$templateFactory
+ *
+ * @description
+ * Creates a template from a string or a function returning a string.
+ *
+ * @param {string|object} template html template as a string or function that
+ * returns an html template as a string.
+ * @param {object} params Parameters to pass to the template function.
+ *
+ * @return {string|object} The template html as a string, or a promise for that
+ * string.
+ */
+ this.fromString = function (template, params) {
+ return isFunction(template) ? template(params) : template;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$templateFactory#fromUrl
+ * @methodOf ui.router.util.$templateFactory
+ *
+ * @description
+ * Loads a template from the a URL via `$http` and `$templateCache`.
+ *
+ * @param {string|Function} url url of the template to load, or a function
+ * that returns a url.
+ * @param {Object} params Parameters to pass to the url function.
+ * @return {string|Promise.<string>} The template html as a string, or a promise
+ * for that string.
+ */
+ this.fromUrl = function (url, params) {
+ if (isFunction(url)) url = url(params);
+ if (url == null) return null;
+ else return $http
+ .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})
+ .then(function(response) { return response.data; });
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$templateFactory#fromProvider
+ * @methodOf ui.router.util.$templateFactory
+ *
+ * @description
+ * Creates a template by invoking an injectable provider function.
+ *
+ * @param {Function} provider Function to invoke via `$injector.invoke`
+ * @param {Object} params Parameters for the template.
+ * @param {Object} locals Locals to pass to `invoke`. Defaults to
+ * `{ params: params }`.
+ * @return {string|Promise.<string>} The template html as a string, or a promise
+ * for that string.
+ */
+ this.fromProvider = function (provider, params, locals) {
+ return $injector.invoke(provider, null, locals || { params: params });
+ };
+}
+
+angular.module('ui.router.util').service('$templateFactory', $TemplateFactory);
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/urlMatcherFactory.js b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/urlMatcherFactory.js
new file mode 100644
index 0000000..bf116f0
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/urlMatcherFactory.js
@@ -0,0 +1,1050 @@
+var $$UMFP; // reference to $UrlMatcherFactoryProvider
+
+/**
+ * @ngdoc object
+ * @name ui.router.util.type:UrlMatcher
+ *
+ * @description
+ * Matches URLs against patterns and extracts named parameters from the path or the search
+ * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list
+ * of search parameters. Multiple search parameter names are separated by '&'. Search parameters
+ * do not influence whether or not a URL is matched, but their values are passed through into
+ * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.
+ *
+ * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace
+ * syntax, which optionally allows a regular expression for the parameter to be specified:
+ *
+ * * `':'` name - colon placeholder
+ * * `'*'` name - catch-all placeholder
+ * * `'{' name '}'` - curly placeholder
+ * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the
+ * regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.
+ *
+ * Parameter names may contain only word characters (latin letters, digits, and underscore) and
+ * must be unique within the pattern (across both path and search parameters). For colon
+ * placeholders or curly placeholders without an explicit regexp, a path parameter matches any
+ * number of characters other than '/'. For catch-all placeholders the path parameter matches
+ * any number of characters.
+ *
+ * Examples:
+ *
+ * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for
+ * trailing slashes, and patterns have to match the entire path, not just a prefix.
+ * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or
+ * '/user/bob/details'. The second path segment will be captured as the parameter 'id'.
+ * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.
+ * * `'/user/{id:[^/]*}'` - Same as the previous example.
+ * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id
+ * parameter consists of 1 to 8 hex digits.
+ * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the
+ * path into the parameter 'path'.
+ * * `'/files/*path'` - ditto.
+ * * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined
+ * in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start
+ *
+ * @param {string} pattern The pattern to compile into a matcher.
+ * @param {Object} config A configuration object hash:
+ * @param {Object=} parentMatcher Used to concatenate the pattern/config onto
+ * an existing UrlMatcher
+ *
+ * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.
+ * * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.
+ *
+ * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any
+ * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns
+ * non-null) will start with this prefix.
+ *
+ * @property {string} source The pattern that was passed into the constructor
+ *
+ * @property {string} sourcePath The path portion of the source property
+ *
+ * @property {string} sourceSearch The search portion of the source property
+ *
+ * @property {string} regex The constructed regex that will be used to match against the url when
+ * it is time to determine which url will match.
+ *
+ * @returns {Object} New `UrlMatcher` object
+ */
+function UrlMatcher(pattern, config, parentMatcher) {
+ config = extend({ params: {} }, isObject(config) ? config : {});
+
+ // Find all placeholders and create a compiled pattern, using either classic or curly syntax:
+ // '*' name
+ // ':' name
+ // '{' name '}'
+ // '{' name ':' regexp '}'
+ // The regular expression is somewhat complicated due to the need to allow curly braces
+ // inside the regular expression. The placeholder regexp breaks down as follows:
+ // ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)
+ // \{([\w\[\]]+)(?:\:( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case
+ // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either
+ // [^{}\\]+ - anything other than curly braces or backslash
+ // \\. - a backslash escape
+ // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms
+ var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
+ searchPlaceholder = /([:]?)([\w\[\]-]+)|\{([\w\[\]-]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
+ compiled = '^', last = 0, m,
+ segments = this.segments = [],
+ parentParams = parentMatcher ? parentMatcher.params : {},
+ params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),
+ paramNames = [];
+
+ function addParameter(id, type, config, location) {
+ paramNames.push(id);
+ if (parentParams[id]) return parentParams[id];
+ if (!/^\w+(-+\w+)*(?:\[\])?$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'");
+ if (params[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'");
+ params[id] = new $$UMFP.Param(id, type, config, location);
+ return params[id];
+ }
+
+ function quoteRegExp(string, pattern, squash, optional) {
+ var surroundPattern = ['',''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&");
+ if (!pattern) return result;
+ switch(squash) {
+ case false: surroundPattern = ['(', ')' + (optional ? "?" : "")]; break;
+ case true: surroundPattern = ['?(', ')?']; break;
+ default: surroundPattern = ['(' + squash + "|", ')?']; break;
+ }
+ return result + surroundPattern[0] + pattern + surroundPattern[1];
+ }
+
+ this.source = pattern;
+
+ // Split into static segments separated by path parameter placeholders.
+ // The number of segments is always 1 more than the number of parameters.
+ function matchDetails(m, isSearch) {
+ var id, regexp, segment, type, cfg, arrayMode;
+ id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null
+ cfg = config.params[id];
+ segment = pattern.substring(last, m.index);
+ regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);
+ type = $$UMFP.type(regexp || "string") || inherit($$UMFP.type("string"), { pattern: new RegExp(regexp, config.caseInsensitive ? 'i' : undefined) });
+ return {
+ id: id, regexp: regexp, segment: segment, type: type, cfg: cfg
+ };
+ }
+
+ var p, param, segment;
+ while ((m = placeholder.exec(pattern))) {
+ p = matchDetails(m, false);
+ if (p.segment.indexOf('?') >= 0) break; // we're into the search part
+
+ param = addParameter(p.id, p.type, p.cfg, "path");
+ compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash, param.isOptional);
+ segments.push(p.segment);
+ last = placeholder.lastIndex;
+ }
+ segment = pattern.substring(last);
+
+ // Find any search parameter names and remove them from the last segment
+ var i = segment.indexOf('?');
+
+ if (i >= 0) {
+ var search = this.sourceSearch = segment.substring(i);
+ segment = segment.substring(0, i);
+ this.sourcePath = pattern.substring(0, last + i);
+
+ if (search.length > 0) {
+ last = 0;
+ while ((m = searchPlaceholder.exec(search))) {
+ p = matchDetails(m, true);
+ param = addParameter(p.id, p.type, p.cfg, "search");
+ last = placeholder.lastIndex;
+ // check if ?&
+ }
+ }
+ } else {
+ this.sourcePath = pattern;
+ this.sourceSearch = '';
+ }
+
+ compiled += quoteRegExp(segment) + (config.strict === false ? '\/?' : '') + '$';
+ segments.push(segment);
+
+ this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);
+ this.prefix = segments[0];
+ this.$$paramNames = paramNames;
+}
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:UrlMatcher#concat
+ * @methodOf ui.router.util.type:UrlMatcher
+ *
+ * @description
+ * Returns a new matcher for a pattern constructed by appending the path part and adding the
+ * search parameters of the specified pattern to this pattern. The current pattern is not
+ * modified. This can be understood as creating a pattern for URLs that are relative to (or
+ * suffixes of) the current pattern.
+ *
+ * @example
+ * The following two matchers are equivalent:
+ * <pre>
+ * new UrlMatcher('/user/{id}?q').concat('/details?date');
+ * new UrlMatcher('/user/{id}/details?q&date');
+ * </pre>
+ *
+ * @param {string} pattern The pattern to append.
+ * @param {Object} config An object hash of the configuration for the matcher.
+ * @returns {UrlMatcher} A matcher for the concatenated pattern.
+ */
+UrlMatcher.prototype.concat = function (pattern, config) {
+ // Because order of search parameters is irrelevant, we can add our own search
+ // parameters to the end of the new pattern. Parse the new pattern by itself
+ // and then join the bits together, but it's much easier to do this on a string level.
+ var defaultConfig = {
+ caseInsensitive: $$UMFP.caseInsensitive(),
+ strict: $$UMFP.strictMode(),
+ squash: $$UMFP.defaultSquashPolicy()
+ };
+ return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);
+};
+
+UrlMatcher.prototype.toString = function () {
+ return this.source;
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:UrlMatcher#exec
+ * @methodOf ui.router.util.type:UrlMatcher
+ *
+ * @description
+ * Tests the specified path against this matcher, and returns an object containing the captured
+ * parameter values, or null if the path does not match. The returned object contains the values
+ * of any search parameters that are mentioned in the pattern, but their value may be null if
+ * they are not present in `searchParams`. This means that search parameters are always treated
+ * as optional.
+ *
+ * @example
+ * <pre>
+ * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {
+ * x: '1', q: 'hello'
+ * });
+ * // returns { id: 'bob', q: 'hello', r: null }
+ * </pre>
+ *
+ * @param {string} path The URL path to match, e.g. `$location.path()`.
+ * @param {Object} searchParams URL search parameters, e.g. `$location.search()`.
+ * @returns {Object} The captured parameter values.
+ */
+UrlMatcher.prototype.exec = function (path, searchParams) {
+ var m = this.regexp.exec(path);
+ if (!m) return null;
+ searchParams = searchParams || {};
+
+ var paramNames = this.parameters(), nTotal = paramNames.length,
+ nPath = this.segments.length - 1,
+ values = {}, i, j, cfg, paramName;
+
+ if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'");
+
+ function decodePathArray(string) {
+ function reverseString(str) { return str.split("").reverse().join(""); }
+ function unquoteDashes(str) { return str.replace(/\\-/g, "-"); }
+
+ var split = reverseString(string).split(/-(?!\\)/);
+ var allReversed = map(split, reverseString);
+ return map(allReversed, unquoteDashes).reverse();
+ }
+
+ for (i = 0; i < nPath; i++) {
+ paramName = paramNames[i];
+ var param = this.params[paramName];
+ var paramVal = m[i+1];
+ // if the param value matches a pre-replace pair, replace the value before decoding.
+ for (j = 0; j < param.replace; j++) {
+ if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;
+ }
+ if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);
+ values[paramName] = param.value(paramVal);
+ }
+ for (/**/; i < nTotal; i++) {
+ paramName = paramNames[i];
+ values[paramName] = this.params[paramName].value(searchParams[paramName]);
+ }
+
+ return values;
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:UrlMatcher#parameters
+ * @methodOf ui.router.util.type:UrlMatcher
+ *
+ * @description
+ * Returns the names of all path and search parameters of this pattern in an unspecified order.
+ *
+ * @returns {Array.<string>} An array of parameter names. Must be treated as read-only. If the
+ * pattern has no parameters, an empty array is returned.
+ */
+UrlMatcher.prototype.parameters = function (param) {
+ if (!isDefined(param)) return this.$$paramNames;
+ return this.params[param] || null;
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:UrlMatcher#validate
+ * @methodOf ui.router.util.type:UrlMatcher
+ *
+ * @description
+ * Checks an object hash of parameters to validate their correctness according to the parameter
+ * types of this `UrlMatcher`.
+ *
+ * @param {Object} params The object hash of parameters to validate.
+ * @returns {boolean} Returns `true` if `params` validates, otherwise `false`.
+ */
+UrlMatcher.prototype.validates = function (params) {
+ return this.params.$$validates(params);
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:UrlMatcher#format
+ * @methodOf ui.router.util.type:UrlMatcher
+ *
+ * @description
+ * Creates a URL that matches this pattern by substituting the specified values
+ * for the path and search parameters. Null values for path parameters are
+ * treated as empty strings.
+ *
+ * @example
+ * <pre>
+ * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });
+ * // returns '/user/bob?q=yes'
+ * </pre>
+ *
+ * @param {Object} values the values to substitute for the parameters in this pattern.
+ * @returns {string} the formatted URL (path and optionally search part).
+ */
+UrlMatcher.prototype.format = function (values) {
+ values = values || {};
+ var segments = this.segments, params = this.parameters(), paramset = this.params;
+ if (!this.validates(values)) return null;
+
+ var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];
+
+ function encodeDashes(str) { // Replace dashes with encoded "\-"
+ return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); });
+ }
+
+ for (i = 0; i < nTotal; i++) {
+ var isPathParam = i < nPath;
+ var name = params[i], param = paramset[name], value = param.value(values[name]);
+ var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);
+ var squash = isDefaultValue ? param.squash : false;
+ var encoded = param.type.encode(value);
+
+ if (isPathParam) {
+ var nextSegment = segments[i + 1];
+ if (squash === false) {
+ if (encoded != null) {
+ if (isArray(encoded)) {
+ result += map(encoded, encodeDashes).join("-");
+ } else {
+ result += encodeURIComponent(encoded);
+ }
+ }
+ result += nextSegment;
+ } else if (squash === true) {
+ var capture = result.match(/\/$/) ? /\/?(.*)/ : /(.*)/;
+ result += nextSegment.match(capture)[1];
+ } else if (isString(squash)) {
+ result += squash + nextSegment;
+ }
+ } else {
+ if (encoded == null || (isDefaultValue && squash !== false)) continue;
+ if (!isArray(encoded)) encoded = [ encoded ];
+ encoded = map(encoded, encodeURIComponent).join('&' + name + '=');
+ result += (search ? '&' : '?') + (name + '=' + encoded);
+ search = true;
+ }
+ }
+
+ return result;
+};
+
+/**
+ * @ngdoc object
+ * @name ui.router.util.type:Type
+ *
+ * @description
+ * Implements an interface to define custom parameter types that can be decoded from and encoded to
+ * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}
+ * objects when matching or formatting URLs, or comparing or validating parameter values.
+ *
+ * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more
+ * information on registering custom types.
+ *
+ * @param {Object} config A configuration object which contains the custom type definition. The object's
+ * properties will override the default methods and/or pattern in `Type`'s public interface.
+ * @example
+ * <pre>
+ * {
+ * decode: function(val) { return parseInt(val, 10); },
+ * encode: function(val) { return val && val.toString(); },
+ * equals: function(a, b) { return this.is(a) && a === b; },
+ * is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },
+ * pattern: /\d+/
+ * }
+ * </pre>
+ *
+ * @property {RegExp} pattern The regular expression pattern used to match values of this type when
+ * coming from a substring of a URL.
+ *
+ * @returns {Object} Returns a new `Type` object.
+ */
+function Type(config) {
+ extend(this, config);
+}
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:Type#is
+ * @methodOf ui.router.util.type:Type
+ *
+ * @description
+ * Detects whether a value is of a particular type. Accepts a native (decoded) value
+ * and determines whether it matches the current `Type` object.
+ *
+ * @param {*} val The value to check.
+ * @param {string} key Optional. If the type check is happening in the context of a specific
+ * {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the
+ * parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.
+ * @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`.
+ */
+Type.prototype.is = function(val, key) {
+ return true;
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:Type#encode
+ * @methodOf ui.router.util.type:Type
+ *
+ * @description
+ * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the
+ * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it
+ * only needs to be a representation of `val` that has been coerced to a string.
+ *
+ * @param {*} val The value to encode.
+ * @param {string} key The name of the parameter in which `val` is stored. Can be used for
+ * meta-programming of `Type` objects.
+ * @returns {string} Returns a string representation of `val` that can be encoded in a URL.
+ */
+Type.prototype.encode = function(val, key) {
+ return val;
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:Type#decode
+ * @methodOf ui.router.util.type:Type
+ *
+ * @description
+ * Converts a parameter value (from URL string or transition param) to a custom/native value.
+ *
+ * @param {string} val The URL parameter value to decode.
+ * @param {string} key The name of the parameter in which `val` is stored. Can be used for
+ * meta-programming of `Type` objects.
+ * @returns {*} Returns a custom representation of the URL parameter value.
+ */
+Type.prototype.decode = function(val, key) {
+ return val;
+};
+
+/**
+ * @ngdoc function
+ * @name ui.router.util.type:Type#equals
+ * @methodOf ui.router.util.type:Type
+ *
+ * @description
+ * Determines whether two decoded values are equivalent.
+ *
+ * @param {*} a A value to compare against.
+ * @param {*} b A value to compare against.
+ * @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`.
+ */
+Type.prototype.equals = function(a, b) {
+ return a == b;
+};
+
+Type.prototype.$subPattern = function() {
+ var sub = this.pattern.toString();
+ return sub.substr(1, sub.length - 2);
+};
+
+Type.prototype.pattern = /.*/;
+
+Type.prototype.toString = function() { return "{Type:" + this.name + "}"; };
+
+/** Given an encoded string, or a decoded object, returns a decoded object */
+Type.prototype.$normalize = function(val) {
+ return this.is(val) ? val : this.decode(val);
+};
+
+/*
+ * Wraps an existing custom Type as an array of Type, depending on 'mode'.
+ * e.g.:
+ * - urlmatcher pattern "/path?{queryParam[]:int}"
+ * - url: "/path?queryParam=1&queryParam=2
+ * - $stateParams.queryParam will be [1, 2]
+ * if `mode` is "auto", then
+ * - url: "/path?queryParam=1 will create $stateParams.queryParam: 1
+ * - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]
+ */
+Type.prototype.$asArray = function(mode, isSearch) {
+ if (!mode) return this;
+ if (mode === "auto" && !isSearch) throw new Error("'auto' array mode is for query parameters only");
+
+ function ArrayType(type, mode) {
+ function bindTo(type, callbackName) {
+ return function() {
+ return type[callbackName].apply(type, arguments);
+ };
+ }
+
+ // Wrap non-array value as array
+ function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); }
+ // Unwrap array value for "auto" mode. Return undefined for empty array.
+ function arrayUnwrap(val) {
+ switch(val.length) {
+ case 0: return undefined;
+ case 1: return mode === "auto" ? val[0] : val;
+ default: return val;
+ }
+ }
+ function falsey(val) { return !val; }
+
+ // Wraps type (.is/.encode/.decode) functions to operate on each value of an array
+ function arrayHandler(callback, allTruthyMode) {
+ return function handleArray(val) {
+ val = arrayWrap(val);
+ var result = map(val, callback);
+ if (allTruthyMode === true)
+ return filter(result, falsey).length === 0;
+ return arrayUnwrap(result);
+ };
+ }
+
+ // Wraps type (.equals) functions to operate on each value of an array
+ function arrayEqualsHandler(callback) {
+ return function handleArray(val1, val2) {
+ var left = arrayWrap(val1), right = arrayWrap(val2);
+ if (left.length !== right.length) return false;
+ for (var i = 0; i < left.length; i++) {
+ if (!callback(left[i], right[i])) return false;
+ }
+ return true;
+ };
+ }
+
+ this.encode = arrayHandler(bindTo(type, 'encode'));
+ this.decode = arrayHandler(bindTo(type, 'decode'));
+ this.is = arrayHandler(bindTo(type, 'is'), true);
+ this.equals = arrayEqualsHandler(bindTo(type, 'equals'));
+ this.pattern = type.pattern;
+ this.$normalize = arrayHandler(bindTo(type, '$normalize'));
+ this.name = type.name;
+ this.$arrayMode = mode;
+ }
+
+ return new ArrayType(this, mode);
+};
+
+
+
+/**
+ * @ngdoc object
+ * @name ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory
+ * is also available to providers under the name `$urlMatcherFactoryProvider`.
+ */
+function $UrlMatcherFactory() {
+ $$UMFP = this;
+
+ var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;
+
+ function valToString(val) { return val != null ? val.toString().replace(/\//g, "%2F") : val; }
+ function valFromString(val) { return val != null ? val.toString().replace(/%2F/g, "/") : val; }
+
+ var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {
+ string: {
+ encode: valToString,
+ decode: valFromString,
+ // TODO: in 1.0, make string .is() return false if value is undefined/null by default.
+ // In 0.2.x, string params are optional by default for backwards compat
+ is: function(val) { return val == null || !isDefined(val) || typeof val === "string"; },
+ pattern: /[^/]*/
+ },
+ int: {
+ encode: valToString,
+ decode: function(val) { return parseInt(val, 10); },
+ is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; },
+ pattern: /\d+/
+ },
+ bool: {
+ encode: function(val) { return val ? 1 : 0; },
+ decode: function(val) { return parseInt(val, 10) !== 0; },
+ is: function(val) { return val === true || val === false; },
+ pattern: /0|1/
+ },
+ date: {
+ encode: function (val) {
+ if (!this.is(val))
+ return undefined;
+ return [ val.getFullYear(),
+ ('0' + (val.getMonth() + 1)).slice(-2),
+ ('0' + val.getDate()).slice(-2)
+ ].join("-");
+ },
+ decode: function (val) {
+ if (this.is(val)) return val;
+ var match = this.capture.exec(val);
+ return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;
+ },
+ is: function(val) { return val instanceof Date && !isNaN(val.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: angular.toJson,
+ decode: angular.fromJson,
+ is: angular.isObject,
+ equals: angular.equals,
+ pattern: /[^/]*/
+ },
+ any: { // does not encode/decode
+ encode: angular.identity,
+ decode: angular.identity,
+ equals: angular.equals,
+ pattern: /.*/
+ }
+ };
+
+ function getDefaultConfig() {
+ return {
+ strict: isStrictMode,
+ caseInsensitive: isCaseInsensitive
+ };
+ }
+
+ function isInjectable(value) {
+ return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));
+ }
+
+ /**
+ * [Internal] Get the default value of a parameter, which may be an injectable function.
+ */
+ $UrlMatcherFactory.$$getDefaultValue = function(config) {
+ if (!isInjectable(config.value)) return config.value;
+ if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
+ return injector.invoke(config.value);
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$urlMatcherFactory#caseInsensitive
+ * @methodOf ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Defines whether URL matching should be case sensitive (the default behavior), or not.
+ *
+ * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;
+ * @returns {boolean} the current value of caseInsensitive
+ */
+ this.caseInsensitive = function(value) {
+ if (isDefined(value))
+ isCaseInsensitive = value;
+ return isCaseInsensitive;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$urlMatcherFactory#strictMode
+ * @methodOf ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Defines whether URLs should match trailing slashes, or not (the default behavior).
+ *
+ * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.
+ * @returns {boolean} the current value of strictMode
+ */
+ this.strictMode = function(value) {
+ if (isDefined(value))
+ isStrictMode = value;
+ return isStrictMode;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy
+ * @methodOf ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Sets the default behavior when generating or matching URLs with default parameter values.
+ *
+ * @param {string} value A string that defines the default parameter URL squashing behavior.
+ * `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL
+ * `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the
+ * parameter is surrounded by slashes, squash (remove) one slash from the URL
+ * any other string, e.g. "~": When generating an href with a default parameter value, squash (remove)
+ * the parameter value from the URL and replace it with this string.
+ */
+ this.defaultSquashPolicy = function(value) {
+ if (!isDefined(value)) return defaultSquashPolicy;
+ if (value !== true && value !== false && !isString(value))
+ throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string");
+ defaultSquashPolicy = value;
+ return value;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$urlMatcherFactory#compile
+ * @methodOf ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.
+ *
+ * @param {string} pattern The URL pattern.
+ * @param {Object} config The config object hash.
+ * @returns {UrlMatcher} The UrlMatcher.
+ */
+ this.compile = function (pattern, config) {
+ return new UrlMatcher(pattern, extend(getDefaultConfig(), config));
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$urlMatcherFactory#isMatcher
+ * @methodOf ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Returns true if the specified object is a `UrlMatcher`, or false otherwise.
+ *
+ * @param {Object} object The object to perform the type check against.
+ * @returns {Boolean} Returns `true` if the object matches the `UrlMatcher` interface, by
+ * implementing all the same methods.
+ */
+ this.isMatcher = function (o) {
+ if (!isObject(o)) return false;
+ var result = true;
+
+ forEach(UrlMatcher.prototype, function(val, name) {
+ if (isFunction(val)) {
+ result = result && (isDefined(o[name]) && isFunction(o[name]));
+ }
+ });
+ return result;
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.util.$urlMatcherFactory#type
+ * @methodOf ui.router.util.$urlMatcherFactory
+ *
+ * @description
+ * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to
+ * generate URLs with typed parameters.
+ *
+ * @param {string} name The type name.
+ * @param {Object|Function} definition The type definition. See
+ * {@link ui.router.util.type:Type `Type`} for information on the values accepted.
+ * @param {Object|Function} definitionFn (optional) A function that is injected before the app
+ * runtime starts. The result of this function is merged into the existing `definition`.
+ * See {@link ui.router.util.type:Type `Type`} for information on the values accepted.
+ *
+ * @returns {Object} Returns `$urlMatcherFactoryProvider`.
+ *
+ * @example
+ * This is a simple example of a custom type that encodes and decodes items from an
+ * array, using the array index as the URL-encoded value:
+ *
+ * <pre>
+ * var list = ['John', 'Paul', 'George', 'Ringo'];
+ *
+ * $urlMatcherFactoryProvider.type('listItem', {
+ * encode: function(item) {
+ * // Represent the list item in the URL using its corresponding index
+ * return list.indexOf(item);
+ * },
+ * decode: function(item) {
+ * // Look up the list item by index
+ * return list[parseInt(item, 10)];
+ * },
+ * is: function(item) {
+ * // Ensure the item is valid by checking to see that it appears
+ * // in the list
+ * return list.indexOf(item) > -1;
+ * }
+ * });
+ *
+ * $stateProvider.state('list', {
+ * url: "/list/{item:listItem}",
+ * controller: function($scope, $stateParams) {
+ * console.log($stateParams.item);
+ * }
+ * });
+ *
+ * // ...
+ *
+ * // Changes URL to '/list/3', logs "Ringo" to the console
+ * $state.go('list', { item: "Ringo" });
+ * </pre>
+ *
+ * This is a more complex example of a type that relies on dependency injection to
+ * interact with services, and uses the parameter name from the URL to infer how to
+ * handle encoding and decoding parameter values:
+ *
+ * <pre>
+ * // Defines a custom type that gets a value from a service,
+ * // where each service gets different types of values from
+ * // a backend API:
+ * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {
+ *
+ * // Matches up services to URL parameter names
+ * var services = {
+ * user: Users,
+ * post: Posts
+ * };
+ *
+ * return {
+ * encode: function(object) {
+ * // Represent the object in the URL using its unique ID
+ * return object.id;
+ * },
+ * decode: function(value, key) {
+ * // Look up the object by ID, using the parameter
+ * // name (key) to call the correct service
+ * return services[key].findById(value);
+ * },
+ * is: function(object, key) {
+ * // Check that object is a valid dbObject
+ * return angular.isObject(object) && object.id && services[key];
+ * }
+ * equals: function(a, b) {
+ * // Check the equality of decoded objects by comparing
+ * // their unique IDs
+ * return a.id === b.id;
+ * }
+ * };
+ * });
+ *
+ * // In a config() block, you can then attach URLs with
+ * // type-annotated parameters:
+ * $stateProvider.state('users', {
+ * url: "/users",
+ * // ...
+ * }).state('users.item', {
+ * url: "/{user:dbObject}",
+ * controller: function($scope, $stateParams) {
+ * // $stateParams.user will now be an object returned from
+ * // the Users service
+ * },
+ * // ...
+ * });
+ * </pre>
+ */
+ this.type = function (name, definition, definitionFn) {
+ if (!isDefined(definition)) return $types[name];
+ if ($types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined.");
+
+ $types[name] = new Type(extend({ name: name }, definition));
+ if (definitionFn) {
+ typeQueue.push({ name: name, def: definitionFn });
+ if (!enqueue) flushTypeQueue();
+ }
+ return this;
+ };
+
+ // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s
+ function flushTypeQueue() {
+ while(typeQueue.length) {
+ var type = typeQueue.shift();
+ if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime.");
+ angular.extend($types[type.name], injector.invoke(type.def));
+ }
+ }
+
+ // Register default types. Store them in the prototype of $types.
+ forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); });
+ $types = inherit($types, {});
+
+ /* No need to document $get, since it returns this */
+ this.$get = ['$injector', function ($injector) {
+ injector = $injector;
+ enqueue = false;
+ flushTypeQueue();
+
+ forEach(defaultTypes, function(type, name) {
+ if (!$types[name]) $types[name] = new Type(type);
+ });
+ return this;
+ }];
+
+ this.Param = function Param(id, type, config, location) {
+ var self = this;
+ config = unwrapShorthand(config);
+ type = getType(config, type, location);
+ var arrayMode = getArrayMode();
+ type = arrayMode ? type.$asArray(arrayMode, location === "search") : type;
+ if (type.name === "string" && !arrayMode && location === "path" && config.value === undefined)
+ config.value = ""; // for 0.2.x; in 0.3.0+ do not automatically default to ""
+ var isOptional = config.value !== undefined;
+ var squash = getSquashPolicy(config, isOptional);
+ var replace = getReplace(config, arrayMode, isOptional, squash);
+
+ function unwrapShorthand(config) {
+ var keys = isObject(config) ? objectKeys(config) : [];
+ var isShorthand = indexOf(keys, "value") === -1 && indexOf(keys, "type") === -1 &&
+ indexOf(keys, "squash") === -1 && indexOf(keys, "array") === -1;
+ if (isShorthand) config = { value: config };
+ config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; };
+ return config;
+ }
+
+ function getType(config, urlType, location) {
+ if (config.type && urlType) throw new Error("Param '"+id+"' has two type configurations.");
+ if (urlType) return urlType;
+ if (!config.type) return (location === "config" ? $types.any : $types.string);
+ return config.type instanceof Type ? config.type : new Type(config.type);
+ }
+
+ // array config: param name (param[]) overrides default settings. explicit config overrides param name.
+ function getArrayMode() {
+ var arrayDefaults = { array: (location === "search" ? "auto" : false) };
+ var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {};
+ return extend(arrayDefaults, arrayParamNomenclature, config).array;
+ }
+
+ /**
+ * returns false, true, or the squash value to indicate the "default parameter url squash policy".
+ */
+ function getSquashPolicy(config, isOptional) {
+ var squash = config.squash;
+ if (!isOptional || squash === false) return false;
+ if (!isDefined(squash) || squash == null) return defaultSquashPolicy;
+ if (squash === true || isString(squash)) return squash;
+ throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string");
+ }
+
+ function getReplace(config, arrayMode, isOptional, squash) {
+ var replace, configuredKeys, defaultPolicy = [
+ { from: "", to: (isOptional || arrayMode ? undefined : "") },
+ { from: null, to: (isOptional || arrayMode ? undefined : "") }
+ ];
+ replace = isArray(config.replace) ? config.replace : [];
+ if (isString(squash))
+ replace.push({ from: squash, to: undefined });
+ configuredKeys = map(replace, function(item) { return item.from; } );
+ return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace);
+ }
+
+ /**
+ * [Internal] Get the default value of a parameter, which may be an injectable function.
+ */
+ function $$getDefaultValue() {
+ if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
+ var defaultValue = injector.invoke(config.$$fn);
+ if (defaultValue !== null && defaultValue !== undefined && !self.type.is(defaultValue))
+ throw new Error("Default value (" + defaultValue + ") for parameter '" + self.id + "' is not an instance of Type (" + self.type.name + ")");
+ return defaultValue;
+ }
+
+ /**
+ * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the
+ * default value, which may be the result of an injectable function.
+ */
+ function $value(value) {
+ function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; }
+ function $replace(value) {
+ var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; });
+ return replacement.length ? replacement[0] : value;
+ }
+ value = $replace(value);
+ return !isDefined(value) ? $$getDefaultValue() : self.type.$normalize(value);
+ }
+
+ function toString() { return "{Param:" + id + " " + type + " squash: '" + squash + "' optional: " + isOptional + "}"; }
+
+ extend(this, {
+ id: id,
+ type: type,
+ location: location,
+ array: arrayMode,
+ squash: squash,
+ replace: replace,
+ isOptional: isOptional,
+ value: $value,
+ dynamic: undefined,
+ config: config,
+ toString: toString
+ });
+ };
+
+ function ParamSet(params) {
+ extend(this, params || {});
+ }
+
+ ParamSet.prototype = {
+ $$new: function() {
+ return inherit(this, extend(new ParamSet(), { $$parent: this}));
+ },
+ $$keys: function () {
+ var keys = [], chain = [], parent = this,
+ ignore = objectKeys(ParamSet.prototype);
+ while (parent) { chain.push(parent); parent = parent.$$parent; }
+ chain.reverse();
+ forEach(chain, function(paramset) {
+ forEach(objectKeys(paramset), function(key) {
+ if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);
+ });
+ });
+ return keys;
+ },
+ $$values: function(paramValues) {
+ var values = {}, self = this;
+ forEach(self.$$keys(), function(key) {
+ values[key] = self[key].value(paramValues && paramValues[key]);
+ });
+ return values;
+ },
+ $$equals: function(paramValues1, paramValues2) {
+ var equal = true, self = this;
+ forEach(self.$$keys(), function(key) {
+ var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];
+ if (!self[key].type.equals(left, right)) equal = false;
+ });
+ return equal;
+ },
+ $$validates: function $$validate(paramValues) {
+ var keys = this.$$keys(), i, param, rawVal, normalized, encoded;
+ for (i = 0; i < keys.length; i++) {
+ param = this[keys[i]];
+ rawVal = paramValues[keys[i]];
+ if ((rawVal === undefined || rawVal === null) && param.isOptional)
+ break; // There was no parameter value, but the param is optional
+ normalized = param.type.$normalize(rawVal);
+ if (!param.type.is(normalized))
+ return false; // The value was not of the correct Type, and could not be decoded to the correct Type
+ encoded = param.type.encode(normalized);
+ if (angular.isString(encoded) && !param.type.pattern.exec(encoded))
+ return false; // The value was of the correct type, but when encoded, did not match the Type's regexp
+ }
+ return true;
+ },
+ $$parent: undefined
+ };
+
+ this.ParamSet = ParamSet;
+}
+
+// Register as a provider so it's available to other providers
+angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);
+angular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/urlRouter.js b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/urlRouter.js
new file mode 100644
index 0000000..33c1709
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/urlRouter.js
@@ -0,0 +1,427 @@
+/**
+ * @ngdoc object
+ * @name ui.router.router.$urlRouterProvider
+ *
+ * @requires ui.router.util.$urlMatcherFactoryProvider
+ * @requires $locationProvider
+ *
+ * @description
+ * `$urlRouterProvider` has the responsibility of watching `$location`.
+ * When `$location` changes it runs through a list of rules one by one until a
+ * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify
+ * a url in a state configuration. All urls are compiled into a UrlMatcher object.
+ *
+ * There are several methods on `$urlRouterProvider` that make it useful to use directly
+ * in your module config.
+ */
+$UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];
+function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {
+ var rules = [], otherwise = null, interceptDeferred = false, listener;
+
+ // Returns a string that is a prefix of all strings matching the RegExp
+ function regExpPrefix(re) {
+ var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
+ return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
+ }
+
+ // Interpolates matched values into a String.replace()-style pattern
+ function interpolate(pattern, match) {
+ return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) {
+ return match[what === '$' ? 0 : Number(what)];
+ });
+ }
+
+ /**
+ * @ngdoc function
+ * @name ui.router.router.$urlRouterProvider#rule
+ * @methodOf ui.router.router.$urlRouterProvider
+ *
+ * @description
+ * Defines rules that are used by `$urlRouterProvider` to find matches for
+ * specific URLs.
+ *
+ * @example
+ * <pre>
+ * var app = angular.module('app', ['ui.router.router']);
+ *
+ * app.config(function ($urlRouterProvider) {
+ * // Here's an example of how you might allow case insensitive urls
+ * $urlRouterProvider.rule(function ($injector, $location) {
+ * var path = $location.path(),
+ * normalized = path.toLowerCase();
+ *
+ * if (path !== normalized) {
+ * return normalized;
+ * }
+ * });
+ * });
+ * </pre>
+ *
+ * @param {object} rule Handler function that takes `$injector` and `$location`
+ * services as arguments. You can use them to return a valid path as a string.
+ *
+ * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
+ */
+ this.rule = function (rule) {
+ if (!isFunction(rule)) throw new Error("'rule' must be a function");
+ rules.push(rule);
+ return this;
+ };
+
+ /**
+ * @ngdoc object
+ * @name ui.router.router.$urlRouterProvider#otherwise
+ * @methodOf ui.router.router.$urlRouterProvider
+ *
+ * @description
+ * Defines a path that is used when an invalid route is requested.
+ *
+ * @example
+ * <pre>
+ * var app = angular.module('app', ['ui.router.router']);
+ *
+ * app.config(function ($urlRouterProvider) {
+ * // if the path doesn't match any of the urls you configured
+ * // otherwise will take care of routing the user to the
+ * // specified url
+ * $urlRouterProvider.otherwise('/index');
+ *
+ * // Example of using function rule as param
+ * $urlRouterProvider.otherwise(function ($injector, $location) {
+ * return '/a/valid/url';
+ * });
+ * });
+ * </pre>
+ *
+ * @param {string|object} rule The url path you want to redirect to or a function
+ * rule that returns the url path. The function version is passed two params:
+ * `$injector` and `$location` services, and must return a url string.
+ *
+ * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
+ */
+ this.otherwise = function (rule) {
+ if (isString(rule)) {
+ var redirect = rule;
+ rule = function () { return redirect; };
+ }
+ else if (!isFunction(rule)) throw new Error("'rule' must be a function");
+ otherwise = rule;
+ return this;
+ };
+
+
+ function handleIfMatch($injector, handler, match) {
+ if (!match) return false;
+ var result = $injector.invoke(handler, handler, { $match: match });
+ return isDefined(result) ? result : true;
+ }
+
+ /**
+ * @ngdoc function
+ * @name ui.router.router.$urlRouterProvider#when
+ * @methodOf ui.router.router.$urlRouterProvider
+ *
+ * @description
+ * Registers a handler for a given url matching. if handle is a string, it is
+ * treated as a redirect, and is interpolated according to the syntax of match
+ * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).
+ *
+ * If the handler is a function, it is injectable. It gets invoked if `$location`
+ * matches. You have the option of inject the match object as `$match`.
+ *
+ * The handler can return
+ *
+ * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`
+ * will continue trying to find another one that matches.
+ * - **string** which is treated as a redirect and passed to `$location.url()`
+ * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.
+ *
+ * @example
+ * <pre>
+ * var app = angular.module('app', ['ui.router.router']);
+ *
+ * app.config(function ($urlRouterProvider) {
+ * $urlRouterProvider.when($state.url, function ($match, $stateParams) {
+ * if ($state.$current.navigable !== state ||
+ * !equalForKeys($match, $stateParams) {
+ * $state.transitionTo(state, $match, false);
+ * }
+ * });
+ * });
+ * </pre>
+ *
+ * @param {string|object} what The incoming path that you want to redirect.
+ * @param {string|object} handler The path you want to redirect your user to.
+ */
+ this.when = function (what, handler) {
+ var redirect, handlerIsString = isString(handler);
+ if (isString(what)) what = $urlMatcherFactory.compile(what);
+
+ if (!handlerIsString && !isFunction(handler) && !isArray(handler))
+ throw new Error("invalid 'handler' in when()");
+
+ var strategies = {
+ matcher: function (what, handler) {
+ if (handlerIsString) {
+ redirect = $urlMatcherFactory.compile(handler);
+ handler = ['$match', function ($match) { return redirect.format($match); }];
+ }
+ return extend(function ($injector, $location) {
+ return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));
+ }, {
+ prefix: isString(what.prefix) ? what.prefix : ''
+ });
+ },
+ regex: function (what, handler) {
+ if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky");
+
+ if (handlerIsString) {
+ redirect = handler;
+ handler = ['$match', function ($match) { return interpolate(redirect, $match); }];
+ }
+ return extend(function ($injector, $location) {
+ return handleIfMatch($injector, handler, what.exec($location.path()));
+ }, {
+ prefix: regExpPrefix(what)
+ });
+ }
+ };
+
+ var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };
+
+ for (var n in check) {
+ if (check[n]) return this.rule(strategies[n](what, handler));
+ }
+
+ throw new Error("invalid 'what' in when()");
+ };
+
+ /**
+ * @ngdoc function
+ * @name ui.router.router.$urlRouterProvider#deferIntercept
+ * @methodOf ui.router.router.$urlRouterProvider
+ *
+ * @description
+ * Disables (or enables) deferring location change interception.
+ *
+ * If you wish to customize the behavior of syncing the URL (for example, if you wish to
+ * defer a transition but maintain the current URL), call this method at configuration time.
+ * Then, at run time, call `$urlRouter.listen()` after you have configured your own
+ * `$locationChangeSuccess` event handler.
+ *
+ * @example
+ * <pre>
+ * var app = angular.module('app', ['ui.router.router']);
+ *
+ * app.config(function ($urlRouterProvider) {
+ *
+ * // Prevent $urlRouter from automatically intercepting URL changes;
+ * // this allows you to configure custom behavior in between
+ * // location changes and route synchronization:
+ * $urlRouterProvider.deferIntercept();
+ *
+ * }).run(function ($rootScope, $urlRouter, UserService) {
+ *
+ * $rootScope.$on('$locationChangeSuccess', function(e) {
+ * // UserService is an example service for managing user state
+ * if (UserService.isLoggedIn()) return;
+ *
+ * // Prevent $urlRouter's default handler from firing
+ * e.preventDefault();
+ *
+ * UserService.handleLogin().then(function() {
+ * // Once the user has logged in, sync the current URL
+ * // to the router:
+ * $urlRouter.sync();
+ * });
+ * });
+ *
+ * // Configures $urlRouter's listener *after* your custom listener
+ * $urlRouter.listen();
+ * });
+ * </pre>
+ *
+ * @param {boolean} defer Indicates whether to defer location change interception. Passing
+ no parameter is equivalent to `true`.
+ */
+ this.deferIntercept = function (defer) {
+ if (defer === undefined) defer = true;
+ interceptDeferred = defer;
+ };
+
+ /**
+ * @ngdoc object
+ * @name ui.router.router.$urlRouter
+ *
+ * @requires $location
+ * @requires $rootScope
+ * @requires $injector
+ * @requires $browser
+ *
+ * @description
+ *
+ */
+ this.$get = $get;
+ $get.$inject = ['$location', '$rootScope', '$injector', '$browser'];
+ function $get( $location, $rootScope, $injector, $browser) {
+
+ var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;
+
+ function appendBasePath(url, isHtml5, absolute) {
+ if (baseHref === '/') return url;
+ if (isHtml5) return baseHref.slice(0, -1) + url;
+ if (absolute) return baseHref.slice(1) + url;
+ return url;
+ }
+
+ // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
+ function update(evt) {
+ if (evt && evt.defaultPrevented) return;
+ var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;
+ lastPushedUrl = undefined;
+ // TODO: Re-implement this in 1.0 for https://github.com/angular-ui/ui-router/issues/1573
+ //if (ignoreUpdate) return true;
+
+ function check(rule) {
+ var handled = rule($injector, $location);
+
+ if (!handled) return false;
+ if (isString(handled)) $location.replace().url(handled);
+ return true;
+ }
+ var n = rules.length, i;
+
+ for (i = 0; i < n; i++) {
+ if (check(rules[i])) return;
+ }
+ // always check otherwise last to allow dynamic updates to the set of rules
+ if (otherwise) check(otherwise);
+ }
+
+ function listen() {
+ listener = listener || $rootScope.$on('$locationChangeSuccess', update);
+ return listener;
+ }
+
+ if (!interceptDeferred) listen();
+
+ return {
+ /**
+ * @ngdoc function
+ * @name ui.router.router.$urlRouter#sync
+ * @methodOf ui.router.router.$urlRouter
+ *
+ * @description
+ * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.
+ * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,
+ * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed
+ * with the transition by calling `$urlRouter.sync()`.
+ *
+ * @example
+ * <pre>
+ * angular.module('app', ['ui.router'])
+ * .run(function($rootScope, $urlRouter) {
+ * $rootScope.$on('$locationChangeSuccess', function(evt) {
+ * // Halt state change from even starting
+ * evt.preventDefault();
+ * // Perform custom logic
+ * var meetsRequirement = ...
+ * // Continue with the update and state transition if logic allows
+ * if (meetsRequirement) $urlRouter.sync();
+ * });
+ * });
+ * </pre>
+ */
+ sync: function() {
+ update();
+ },
+
+ listen: function() {
+ return listen();
+ },
+
+ update: function(read) {
+ if (read) {
+ location = $location.url();
+ return;
+ }
+ if ($location.url() === location) return;
+
+ $location.url(location);
+ $location.replace();
+ },
+
+ push: function(urlMatcher, params, options) {
+ var url = urlMatcher.format(params || {});
+
+ // Handle the special hash param, if needed
+ if (url !== null && params && params['#']) {
+ url += '#' + params['#'];
+ }
+
+ $location.url(url);
+ lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;
+ if (options && options.replace) $location.replace();
+ },
+
+ /**
+ * @ngdoc function
+ * @name ui.router.router.$urlRouter#href
+ * @methodOf ui.router.router.$urlRouter
+ *
+ * @description
+ * A URL generation method that returns the compiled URL for a given
+ * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.
+ *
+ * @example
+ * <pre>
+ * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
+ * person: "bob"
+ * });
+ * // $bob == "/about/bob";
+ * </pre>
+ *
+ * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.
+ * @param {object=} params An object of parameter values to fill the matcher's required parameters.
+ * @param {object=} options Options object. The options are:
+ *
+ * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
+ *
+ * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`
+ */
+ href: function(urlMatcher, params, options) {
+ if (!urlMatcher.validates(params)) return null;
+
+ var isHtml5 = $locationProvider.html5Mode();
+ if (angular.isObject(isHtml5)) {
+ isHtml5 = isHtml5.enabled;
+ }
+
+ var url = urlMatcher.format(params);
+ options = options || {};
+
+ if (!isHtml5 && url !== null) {
+ url = "#" + $locationProvider.hashPrefix() + url;
+ }
+
+ // Handle special hash param, if needed
+ if (url !== null && params && params['#']) {
+ url += '#' + params['#'];
+ }
+
+ url = appendBasePath(url, isHtml5, options.absolute);
+
+ if (!options.absolute || !url) {
+ return url;
+ }
+
+ var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();
+ port = (port === 80 || port === 443 ? '' : ':' + port);
+
+ return [$location.protocol(), '://', $location.host(), port, slash, url].join('');
+ }
+ };
+ }
+}
+
+angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/view.js b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/view.js
new file mode 100644
index 0000000..f19a3c5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/view.js
@@ -0,0 +1,71 @@
+
+$ViewProvider.$inject = [];
+function $ViewProvider() {
+
+ this.$get = $get;
+ /**
+ * @ngdoc object
+ * @name ui.router.state.$view
+ *
+ * @requires ui.router.util.$templateFactory
+ * @requires $rootScope
+ *
+ * @description
+ *
+ */
+ $get.$inject = ['$rootScope', '$templateFactory'];
+ function $get( $rootScope, $templateFactory) {
+ return {
+ // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$view#load
+ * @methodOf ui.router.state.$view
+ *
+ * @description
+ *
+ * @param {string} name name
+ * @param {object} options option object.
+ */
+ load: function load(name, options) {
+ var result, defaults = {
+ template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}
+ };
+ options = extend(defaults, options);
+
+ if (options.view) {
+ result = $templateFactory.fromConfig(options.view, options.params, options.locals);
+ }
+ if (result && options.notify) {
+ /**
+ * @ngdoc event
+ * @name ui.router.state.$state#$viewContentLoading
+ * @eventOf ui.router.state.$view
+ * @eventType broadcast on root scope
+ * @description
+ *
+ * Fired once the view **begins loading**, *before* the DOM is rendered.
+ *
+ * @param {Object} event Event object.
+ * @param {Object} viewConfig The view config properties (template, controller, etc).
+ *
+ * @example
+ *
+ * <pre>
+ * $scope.$on('$viewContentLoading',
+ * function(event, viewConfig){
+ * // Access to all the view config properties.
+ * // and one special property 'targetView'
+ * // viewConfig.targetView
+ * });
+ * </pre>
+ */
+ $rootScope.$broadcast('$viewContentLoading', options);
+ }
+ return result;
+ }
+ };
+ }
+}
+
+angular.module('ui.router.state').provider('$view', $ViewProvider);
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/viewDirective.js b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/viewDirective.js
new file mode 100644
index 0000000..b702207
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/viewDirective.js
@@ -0,0 +1,303 @@
+/**
+ * @ngdoc directive
+ * @name ui.router.state.directive:ui-view
+ *
+ * @requires ui.router.state.$state
+ * @requires $compile
+ * @requires $controller
+ * @requires $injector
+ * @requires ui.router.state.$uiViewScroll
+ * @requires $document
+ *
+ * @restrict ECA
+ *
+ * @description
+ * The ui-view directive tells $state where to place your templates.
+ *
+ * @param {string=} name A view name. The name should be unique amongst the other views in the
+ * same state. You can have views of the same name that live in different states.
+ *
+ * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window
+ * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll
+ * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you
+ * scroll ui-view elements into view when they are populated during a state activation.
+ *
+ * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)
+ * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*
+ *
+ * @param {string=} onload Expression to evaluate whenever the view updates.
+ *
+ * @example
+ * A view can be unnamed or named.
+ * <pre>
+ * <!-- Unnamed -->
+ * <div ui-view></div>
+ *
+ * <!-- Named -->
+ * <div ui-view="viewName"></div>
+ * </pre>
+ *
+ * You can only have one unnamed view within any template (or root html). If you are only using a
+ * single view and it is unnamed then you can populate it like so:
+ * <pre>
+ * <div ui-view></div>
+ * $stateProvider.state("home", {
+ * template: "<h1>HELLO!</h1>"
+ * })
+ * </pre>
+ *
+ * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`}
+ * config property, by name, in this case an empty name:
+ * <pre>
+ * $stateProvider.state("home", {
+ * views: {
+ * "": {
+ * template: "<h1>HELLO!</h1>"
+ * }
+ * }
+ * })
+ * </pre>
+ *
+ * But typically you'll only use the views property if you name your view or have more than one view
+ * in the same template. There's not really a compelling reason to name a view if its the only one,
+ * but you could if you wanted, like so:
+ * <pre>
+ * <div ui-view="main"></div>
+ * </pre>
+ * <pre>
+ * $stateProvider.state("home", {
+ * views: {
+ * "main": {
+ * template: "<h1>HELLO!</h1>"
+ * }
+ * }
+ * })
+ * </pre>
+ *
+ * Really though, you'll use views to set up multiple views:
+ * <pre>
+ * <div ui-view></div>
+ * <div ui-view="chart"></div>
+ * <div ui-view="data"></div>
+ * </pre>
+ *
+ * <pre>
+ * $stateProvider.state("home", {
+ * views: {
+ * "": {
+ * template: "<h1>HELLO!</h1>"
+ * },
+ * "chart": {
+ * template: "<chart_thing/>"
+ * },
+ * "data": {
+ * template: "<data_thing/>"
+ * }
+ * }
+ * })
+ * </pre>
+ *
+ * Examples for `autoscroll`:
+ *
+ * <pre>
+ * <!-- If autoscroll present with no expression,
+ * then scroll ui-view into view -->
+ * <ui-view autoscroll/>
+ *
+ * <!-- If autoscroll present with valid expression,
+ * then scroll ui-view into view if expression evaluates to true -->
+ * <ui-view autoscroll='true'/>
+ * <ui-view autoscroll='false'/>
+ * <ui-view autoscroll='scopeVariable'/>
+ * </pre>
+ */
+$ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate'];
+function $ViewDirective( $state, $injector, $uiViewScroll, $interpolate) {
+
+ function getService() {
+ return ($injector.has) ? function(service) {
+ return $injector.has(service) ? $injector.get(service) : null;
+ } : function(service) {
+ try {
+ return $injector.get(service);
+ } catch (e) {
+ return null;
+ }
+ };
+ }
+
+ var service = getService(),
+ $animator = service('$animator'),
+ $animate = service('$animate');
+
+ // Returns a set of DOM manipulation functions based on which Angular version
+ // it should use
+ function getRenderer(attrs, scope) {
+ var statics = function() {
+ return {
+ enter: function (element, target, cb) { target.after(element); cb(); },
+ leave: function (element, cb) { element.remove(); cb(); }
+ };
+ };
+
+ if ($animate) {
+ return {
+ enter: function(element, target, cb) {
+ var promise = $animate.enter(element, null, target, cb);
+ if (promise && promise.then) promise.then(cb);
+ },
+ leave: function(element, cb) {
+ var promise = $animate.leave(element, cb);
+ if (promise && promise.then) promise.then(cb);
+ }
+ };
+ }
+
+ if ($animator) {
+ var animate = $animator && $animator(scope, attrs);
+
+ return {
+ enter: function(element, target, cb) {animate.enter(element, null, target); cb(); },
+ leave: function(element, cb) { animate.leave(element); cb(); }
+ };
+ }
+
+ return statics();
+ }
+
+ var directive = {
+ restrict: 'ECA',
+ terminal: true,
+ priority: 400,
+ transclude: 'element',
+ compile: function (tElement, tAttrs, $transclude) {
+ return function (scope, $element, attrs) {
+ var previousEl, currentEl, currentScope, latestLocals,
+ onloadExp = attrs.onload || '',
+ autoScrollExp = attrs.autoscroll,
+ renderer = getRenderer(attrs, scope);
+
+ scope.$on('$stateChangeSuccess', function() {
+ updateView(false);
+ });
+ scope.$on('$viewContentLoading', function() {
+ updateView(false);
+ });
+
+ updateView(true);
+
+ function cleanupLastView() {
+ if (previousEl) {
+ previousEl.remove();
+ previousEl = null;
+ }
+
+ if (currentScope) {
+ currentScope.$destroy();
+ currentScope = null;
+ }
+
+ if (currentEl) {
+ renderer.leave(currentEl, function() {
+ previousEl = null;
+ });
+
+ previousEl = currentEl;
+ currentEl = null;
+ }
+ }
+
+ function updateView(firstTime) {
+ var newScope,
+ name = getUiViewName(scope, attrs, $element, $interpolate),
+ previousLocals = name && $state.$current && $state.$current.locals[name];
+
+ if (!firstTime && previousLocals === latestLocals) return; // nothing to do
+ newScope = scope.$new();
+ latestLocals = $state.$current.locals[name];
+
+ var clone = $transclude(newScope, function(clone) {
+ renderer.enter(clone, $element, function onUiViewEnter() {
+ if(currentScope) {
+ currentScope.$emit('$viewContentAnimationEnded');
+ }
+
+ if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {
+ $uiViewScroll(clone);
+ }
+ });
+ cleanupLastView();
+ });
+
+ currentEl = clone;
+ currentScope = newScope;
+ /**
+ * @ngdoc event
+ * @name ui.router.state.directive:ui-view#$viewContentLoaded
+ * @eventOf ui.router.state.directive:ui-view
+ * @eventType emits on ui-view directive scope
+ * @description *
+ * Fired once the view is **loaded**, *after* the DOM is rendered.
+ *
+ * @param {Object} event Event object.
+ */
+ currentScope.$emit('$viewContentLoaded');
+ currentScope.$eval(onloadExp);
+ }
+ };
+ }
+ };
+
+ return directive;
+}
+
+$ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];
+function $ViewDirectiveFill ( $compile, $controller, $state, $interpolate) {
+ return {
+ restrict: 'ECA',
+ priority: -400,
+ compile: function (tElement) {
+ var initial = tElement.html();
+ return function (scope, $element, attrs) {
+ var current = $state.$current,
+ name = getUiViewName(scope, attrs, $element, $interpolate),
+ locals = current && current.locals[name];
+
+ if (! locals) {
+ return;
+ }
+
+ $element.data('$uiView', { name: name, state: locals.$$state });
+ $element.html(locals.$template ? locals.$template : initial);
+
+ var link = $compile($element.contents());
+
+ if (locals.$$controller) {
+ locals.$scope = scope;
+ locals.$element = $element;
+ var controller = $controller(locals.$$controller, locals);
+ if (locals.$$controllerAs) {
+ scope[locals.$$controllerAs] = controller;
+ }
+ $element.data('$ngControllerController', controller);
+ $element.children().data('$ngControllerController', controller);
+ }
+
+ link(scope);
+ };
+ }
+ };
+}
+
+/**
+ * Shared ui-view code for both directives:
+ * Given scope, element, and its attributes, return the view's name
+ */
+function getUiViewName(scope, attrs, element, $interpolate) {
+ var name = $interpolate(attrs.uiView || attrs.name || '')(scope);
+ var inherited = element.inheritedData('$uiView');
+ return name.indexOf('@') >= 0 ? name : (name + '@' + (inherited ? inherited.state.name : ''));
+}
+
+angular.module('ui.router.state').directive('uiView', $ViewDirective);
+angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/viewScroll.js b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/viewScroll.js
new file mode 100644
index 0000000..81114e2
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular-ui-router/src/viewScroll.js
@@ -0,0 +1,52 @@
+/**
+ * @ngdoc object
+ * @name ui.router.state.$uiViewScrollProvider
+ *
+ * @description
+ * Provider that returns the {@link ui.router.state.$uiViewScroll} service function.
+ */
+function $ViewScrollProvider() {
+
+ var useAnchorScroll = false;
+
+ /**
+ * @ngdoc function
+ * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll
+ * @methodOf ui.router.state.$uiViewScrollProvider
+ *
+ * @description
+ * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for
+ * scrolling based on the url anchor.
+ */
+ this.useAnchorScroll = function () {
+ useAnchorScroll = true;
+ };
+
+ /**
+ * @ngdoc object
+ * @name ui.router.state.$uiViewScroll
+ *
+ * @requires $anchorScroll
+ * @requires $timeout
+ *
+ * @description
+ * When called with a jqLite element, it scrolls the element into view (after a
+ * `$timeout` so the DOM has time to refresh).
+ *
+ * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,
+ * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.
+ */
+ this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {
+ if (useAnchorScroll) {
+ return $anchorScroll;
+ }
+
+ return function ($element) {
+ return $timeout(function () {
+ $element[0].scrollIntoView();
+ }, 0, false);
+ };
+ }];
+}
+
+angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular/.bower.json b/xos-apps/auto-scale/gui/src/vendor/angular/.bower.json
new file mode 100644
index 0000000..e60c1b4
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular/.bower.json
@@ -0,0 +1,17 @@
+{
+ "name": "angular",
+ "version": "1.4.8",
+ "main": "./angular.js",
+ "ignore": [],
+ "dependencies": {},
+ "homepage": "https://github.com/angular/bower-angular",
+ "_release": "1.4.8",
+ "_resolution": {
+ "type": "version",
+ "tag": "v1.4.8",
+ "commit": "572a4fcc552c27c0f4bb1b9aab395249218c1255"
+ },
+ "_source": "git://github.com/angular/bower-angular.git",
+ "_target": "1.x",
+ "_originalSource": "angular"
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular/README.md b/xos-apps/auto-scale/gui/src/vendor/angular/README.md
new file mode 100644
index 0000000..d1bc0ed
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular/README.md
@@ -0,0 +1,64 @@
+# packaged angular
+
+This repo is for distribution on `npm` and `bower`. The source for this module is in the
+[main AngularJS repo](https://github.com/angular/angular.js).
+Please file issues and pull requests against that repo.
+
+## Install
+
+You can install this package either with `npm` or with `bower`.
+
+### npm
+
+```shell
+npm install angular
+```
+
+Then add a `<script>` to your `index.html`:
+
+```html
+<script src="/node_modules/angular/angular.js"></script>
+```
+
+Or `require('angular')` from your code.
+
+### bower
+
+```shell
+bower install angular
+```
+
+Then add a `<script>` to your `index.html`:
+
+```html
+<script src="/bower_components/angular/angular.js"></script>
+```
+
+## Documentation
+
+Documentation is available on the
+[AngularJS docs site](http://docs.angularjs.org/).
+
+## License
+
+The MIT License
+
+Copyright (c) 2010-2015 Google, Inc. http://angularjs.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular/angular-csp.css b/xos-apps/auto-scale/gui/src/vendor/angular/angular-csp.css
new file mode 100644
index 0000000..f3cd926
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular/angular-csp.css
@@ -0,0 +1,21 @@
+/* Include this file in your html if you are using the CSP mode. */
+
+@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;
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular/angular.js b/xos-apps/auto-scale/gui/src/vendor/angular/angular.js
new file mode 100644
index 0000000..a3aee7d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular/angular.js
@@ -0,0 +1,29018 @@
+/**
+ * @license AngularJS v1.4.8
+ * (c) 2010-2015 Google, Inc. http://angularjs.org
+ * License: MIT
+ */
+(function(window, document, undefined) {'use strict';
+
+/**
+ * @description
+ *
+ * This object provides a utility for producing rich Error messages within
+ * Angular. It can be called as follows:
+ *
+ * var exampleMinErr = minErr('example');
+ * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
+ *
+ * The above creates an instance of minErr in the example namespace. The
+ * resulting error will have a namespaced error code of example.one. The
+ * resulting error will replace {0} with the value of foo, and {1} with the
+ * value of bar. The object is not restricted in the number of arguments it can
+ * take.
+ *
+ * If fewer arguments are specified than necessary for interpolation, the extra
+ * interpolation markers will be preserved in the final string.
+ *
+ * Since data will be parsed statically during a build step, some restrictions
+ * are applied with respect to how minErr instances are created and called.
+ * Instances should have names of the form namespaceMinErr for a minErr created
+ * using minErr('namespace') . Error codes, namespaces and template strings
+ * should all be static strings, not variables or general expressions.
+ *
+ * @param {string} module The namespace to use for the new minErr instance.
+ * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
+ * error from returned function, for cases when a particular type of error is useful.
+ * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
+ */
+
+function minErr(module, ErrorConstructor) {
+ ErrorConstructor = ErrorConstructor || Error;
+ return function() {
+ var SKIP_INDEXES = 2;
+
+ var templateArgs = arguments,
+ code = templateArgs[0],
+ message = '[' + (module ? module + ':' : '') + code + '] ',
+ template = templateArgs[1],
+ paramPrefix, i;
+
+ message += template.replace(/\{\d+\}/g, function(match) {
+ var index = +match.slice(1, -1),
+ shiftedIndex = index + SKIP_INDEXES;
+
+ if (shiftedIndex < templateArgs.length) {
+ return toDebugString(templateArgs[shiftedIndex]);
+ }
+
+ return match;
+ });
+
+ message += '\nhttp://errors.angularjs.org/1.4.8/' +
+ (module ? module + '/' : '') + code;
+
+ for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
+ message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
+ encodeURIComponent(toDebugString(templateArgs[i]));
+ }
+
+ return new ErrorConstructor(message);
+ };
+}
+
+/* We need to tell jshint what variables are being exported */
+/* global angular: true,
+ msie: true,
+ jqLite: true,
+ jQuery: true,
+ slice: true,
+ splice: true,
+ push: true,
+ toString: true,
+ ngMinErr: true,
+ angularModule: true,
+ uid: true,
+ REGEX_STRING_REGEXP: true,
+ VALIDITY_STATE_PROPERTY: true,
+
+ lowercase: true,
+ uppercase: true,
+ manualLowercase: true,
+ manualUppercase: true,
+ nodeName_: true,
+ isArrayLike: true,
+ forEach: true,
+ forEachSorted: true,
+ reverseParams: true,
+ nextUid: true,
+ setHashKey: true,
+ extend: true,
+ toInt: true,
+ inherit: true,
+ merge: true,
+ noop: true,
+ identity: true,
+ valueFn: true,
+ isUndefined: true,
+ isDefined: true,
+ isObject: true,
+ isBlankObject: true,
+ isString: true,
+ isNumber: true,
+ isDate: true,
+ isArray: true,
+ isFunction: true,
+ isRegExp: true,
+ isWindow: true,
+ isScope: true,
+ isFile: true,
+ isFormData: true,
+ isBlob: true,
+ isBoolean: true,
+ isPromiseLike: true,
+ trim: true,
+ escapeForRegexp: true,
+ isElement: true,
+ makeMap: true,
+ includes: true,
+ arrayRemove: true,
+ copy: true,
+ shallowCopy: true,
+ equals: true,
+ csp: true,
+ jq: true,
+ concat: true,
+ sliceArgs: true,
+ bind: true,
+ toJsonReplacer: true,
+ toJson: true,
+ fromJson: true,
+ convertTimezoneToLocal: true,
+ timezoneToOffset: true,
+ startingTag: true,
+ tryDecodeURIComponent: true,
+ parseKeyValue: true,
+ toKeyValue: true,
+ encodeUriSegment: true,
+ encodeUriQuery: true,
+ angularInit: true,
+ bootstrap: true,
+ getTestability: true,
+ snake_case: true,
+ bindJQuery: true,
+ assertArg: true,
+ assertArgFn: true,
+ assertNotHasOwnProperty: true,
+ getter: true,
+ getBlockNodes: true,
+ hasOwnProperty: true,
+ createMap: true,
+
+ NODE_TYPE_ELEMENT: true,
+ NODE_TYPE_ATTRIBUTE: true,
+ NODE_TYPE_TEXT: true,
+ NODE_TYPE_COMMENT: true,
+ NODE_TYPE_DOCUMENT: true,
+ NODE_TYPE_DOCUMENT_FRAGMENT: true,
+*/
+
+////////////////////////////////////
+
+/**
+ * @ngdoc module
+ * @name ng
+ * @module ng
+ * @description
+ *
+ * # ng (core module)
+ * The ng module is loaded by default when an AngularJS application is started. The module itself
+ * contains the essential components for an AngularJS application to function. The table below
+ * lists a high level breakdown of each of the services/factories, filters, directives and testing
+ * components available within this core module.
+ *
+ * <div doc-module-components="ng"></div>
+ */
+
+var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
+
+// The name of a form control's ValidityState property.
+// This is used so that it's possible for internal tests to create mock ValidityStates.
+var VALIDITY_STATE_PROPERTY = 'validity';
+
+/**
+ * @ngdoc function
+ * @name angular.lowercase
+ * @module ng
+ * @kind function
+ *
+ * @description Converts the specified string to lowercase.
+ * @param {string} string String to be converted to lowercase.
+ * @returns {string} Lowercased string.
+ */
+var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
+var hasOwnProperty = Object.prototype.hasOwnProperty;
+
+/**
+ * @ngdoc function
+ * @name angular.uppercase
+ * @module ng
+ * @kind function
+ *
+ * @description Converts the specified string to uppercase.
+ * @param {string} string String to be converted to uppercase.
+ * @returns {string} Uppercased string.
+ */
+var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
+
+
+var manualLowercase = function(s) {
+ /* jshint bitwise: false */
+ return isString(s)
+ ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
+ : s;
+};
+var manualUppercase = function(s) {
+ /* jshint bitwise: false */
+ return isString(s)
+ ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
+ : s;
+};
+
+
+// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
+// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
+// with correct but slower alternatives.
+if ('i' !== 'I'.toLowerCase()) {
+ lowercase = manualLowercase;
+ uppercase = manualUppercase;
+}
+
+
+var
+ msie, // holds major version number for IE, or NaN if UA is not IE.
+ jqLite, // delay binding since jQuery could be loaded after us.
+ jQuery, // delay binding
+ slice = [].slice,
+ splice = [].splice,
+ push = [].push,
+ toString = Object.prototype.toString,
+ getPrototypeOf = Object.getPrototypeOf,
+ ngMinErr = minErr('ng'),
+
+ /** @name angular */
+ angular = window.angular || (window.angular = {}),
+ angularModule,
+ uid = 0;
+
+/**
+ * documentMode is an IE-only property
+ * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
+ */
+msie = document.documentMode;
+
+
+/**
+ * @private
+ * @param {*} obj
+ * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
+ * String ...)
+ */
+function isArrayLike(obj) {
+
+ // `null`, `undefined` and `window` are not array-like
+ if (obj == null || isWindow(obj)) return false;
+
+ // arrays, strings and jQuery/jqLite objects are array like
+ // * jqLite is either the jQuery or jqLite constructor function
+ // * we have to check the existance of jqLite first as this method is called
+ // via the forEach method when constructing the jqLite object in the first place
+ if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
+
+ // Support: iOS 8.2 (not reproducible in simulator)
+ // "length" in obj used to prevent JIT error (gh-11508)
+ var length = "length" in Object(obj) && obj.length;
+
+ // NodeList objects (with `item` method) and
+ // other objects with suitable length characteristics are array-like
+ return isNumber(length) &&
+ (length >= 0 && (length - 1) in obj || typeof obj.item == 'function');
+}
+
+/**
+ * @ngdoc function
+ * @name angular.forEach
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
+ * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
+ * is the value of an object property or an array element, `key` is the object property key or
+ * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
+ *
+ * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
+ * using the `hasOwnProperty` method.
+ *
+ * Unlike ES262's
+ * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
+ * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
+ * return the value provided.
+ *
+ ```js
+ var values = {name: 'misko', gender: 'male'};
+ var log = [];
+ angular.forEach(values, function(value, key) {
+ this.push(key + ': ' + value);
+ }, log);
+ expect(log).toEqual(['name: misko', 'gender: male']);
+ ```
+ *
+ * @param {Object|Array} obj Object to iterate over.
+ * @param {Function} iterator Iterator function.
+ * @param {Object=} context Object to become context (`this`) for the iterator function.
+ * @returns {Object|Array} Reference to `obj`.
+ */
+
+function forEach(obj, iterator, context) {
+ var key, length;
+ if (obj) {
+ if (isFunction(obj)) {
+ for (key in obj) {
+ // Need to check if hasOwnProperty exists,
+ // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
+ if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
+ iterator.call(context, obj[key], key, obj);
+ }
+ }
+ } else if (isArray(obj) || isArrayLike(obj)) {
+ var isPrimitive = typeof obj !== 'object';
+ for (key = 0, length = obj.length; key < length; key++) {
+ if (isPrimitive || key in obj) {
+ iterator.call(context, obj[key], key, obj);
+ }
+ }
+ } else if (obj.forEach && obj.forEach !== forEach) {
+ obj.forEach(iterator, context, obj);
+ } else if (isBlankObject(obj)) {
+ // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
+ for (key in obj) {
+ iterator.call(context, obj[key], key, obj);
+ }
+ } else if (typeof obj.hasOwnProperty === 'function') {
+ // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
+ for (key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ iterator.call(context, obj[key], key, obj);
+ }
+ }
+ } else {
+ // Slow path for objects which do not have a method `hasOwnProperty`
+ for (key in obj) {
+ if (hasOwnProperty.call(obj, key)) {
+ iterator.call(context, obj[key], key, obj);
+ }
+ }
+ }
+ }
+ return obj;
+}
+
+function forEachSorted(obj, iterator, context) {
+ var keys = Object.keys(obj).sort();
+ for (var i = 0; i < keys.length; i++) {
+ iterator.call(context, obj[keys[i]], keys[i]);
+ }
+ return keys;
+}
+
+
+/**
+ * when using forEach the params are value, key, but it is often useful to have key, value.
+ * @param {function(string, *)} iteratorFn
+ * @returns {function(*, string)}
+ */
+function reverseParams(iteratorFn) {
+ return function(value, key) { iteratorFn(key, value); };
+}
+
+/**
+ * A consistent way of creating unique IDs in angular.
+ *
+ * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
+ * we hit number precision issues in JavaScript.
+ *
+ * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
+ *
+ * @returns {number} an unique alpha-numeric string
+ */
+function nextUid() {
+ return ++uid;
+}
+
+
+/**
+ * Set or clear the hashkey for an object.
+ * @param obj object
+ * @param h the hashkey (!truthy to delete the hashkey)
+ */
+function setHashKey(obj, h) {
+ if (h) {
+ obj.$$hashKey = h;
+ } else {
+ delete obj.$$hashKey;
+ }
+}
+
+
+function baseExtend(dst, objs, deep) {
+ var h = dst.$$hashKey;
+
+ for (var i = 0, ii = objs.length; i < ii; ++i) {
+ var obj = objs[i];
+ if (!isObject(obj) && !isFunction(obj)) continue;
+ var keys = Object.keys(obj);
+ for (var j = 0, jj = keys.length; j < jj; j++) {
+ var key = keys[j];
+ var src = obj[key];
+
+ if (deep && isObject(src)) {
+ if (isDate(src)) {
+ dst[key] = new Date(src.valueOf());
+ } else if (isRegExp(src)) {
+ dst[key] = new RegExp(src);
+ } else if (src.nodeName) {
+ dst[key] = src.cloneNode(true);
+ } else if (isElement(src)) {
+ dst[key] = src.clone();
+ } else {
+ if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
+ baseExtend(dst[key], [src], true);
+ }
+ } else {
+ dst[key] = src;
+ }
+ }
+ }
+
+ setHashKey(dst, h);
+ return dst;
+}
+
+/**
+ * @ngdoc function
+ * @name angular.extend
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
+ * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
+ * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
+ *
+ * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
+ * {@link angular.merge} for this.
+ *
+ * @param {Object} dst Destination object.
+ * @param {...Object} src Source object(s).
+ * @returns {Object} Reference to `dst`.
+ */
+function extend(dst) {
+ return baseExtend(dst, slice.call(arguments, 1), false);
+}
+
+
+/**
+* @ngdoc function
+* @name angular.merge
+* @module ng
+* @kind function
+*
+* @description
+* Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
+* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
+* by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
+*
+* Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
+* objects, performing a deep copy.
+*
+* @param {Object} dst Destination object.
+* @param {...Object} src Source object(s).
+* @returns {Object} Reference to `dst`.
+*/
+function merge(dst) {
+ return baseExtend(dst, slice.call(arguments, 1), true);
+}
+
+
+
+function toInt(str) {
+ return parseInt(str, 10);
+}
+
+
+function inherit(parent, extra) {
+ return extend(Object.create(parent), extra);
+}
+
+/**
+ * @ngdoc function
+ * @name angular.noop
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * A function that performs no operations. This function can be useful when writing code in the
+ * functional style.
+ ```js
+ function foo(callback) {
+ var result = calculateResult();
+ (callback || angular.noop)(result);
+ }
+ ```
+ */
+function noop() {}
+noop.$inject = [];
+
+
+/**
+ * @ngdoc function
+ * @name angular.identity
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * A function that returns its first argument. This function is useful when writing code in the
+ * functional style.
+ *
+ ```js
+ function transformer(transformationFn, value) {
+ return (transformationFn || angular.identity)(value);
+ };
+ ```
+ * @param {*} value to be returned.
+ * @returns {*} the value passed in.
+ */
+function identity($) {return $;}
+identity.$inject = [];
+
+
+function valueFn(value) {return function() {return value;};}
+
+function hasCustomToString(obj) {
+ return isFunction(obj.toString) && obj.toString !== toString;
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isUndefined
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is undefined.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is undefined.
+ */
+function isUndefined(value) {return typeof value === 'undefined';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isDefined
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is defined.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is defined.
+ */
+function isDefined(value) {return typeof value !== 'undefined';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isObject
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
+ * considered to be objects. Note that JavaScript arrays are objects.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is an `Object` but not `null`.
+ */
+function isObject(value) {
+ // http://jsperf.com/isobject4
+ return value !== null && typeof value === 'object';
+}
+
+
+/**
+ * Determine if a value is an object with a null prototype
+ *
+ * @returns {boolean} True if `value` is an `Object` with a null prototype
+ */
+function isBlankObject(value) {
+ return value !== null && typeof value === 'object' && !getPrototypeOf(value);
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isString
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is a `String`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `String`.
+ */
+function isString(value) {return typeof value === 'string';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isNumber
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is a `Number`.
+ *
+ * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
+ *
+ * If you wish to exclude these then you can use the native
+ * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
+ * method.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `Number`.
+ */
+function isNumber(value) {return typeof value === 'number';}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isDate
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a value is a date.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `Date`.
+ */
+function isDate(value) {
+ return toString.call(value) === '[object Date]';
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.isArray
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is an `Array`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is an `Array`.
+ */
+var isArray = Array.isArray;
+
+/**
+ * @ngdoc function
+ * @name angular.isFunction
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is a `Function`.
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `Function`.
+ */
+function isFunction(value) {return typeof value === 'function';}
+
+
+/**
+ * Determines if a value is a regular expression object.
+ *
+ * @private
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a `RegExp`.
+ */
+function isRegExp(value) {
+ return toString.call(value) === '[object RegExp]';
+}
+
+
+/**
+ * Checks if `obj` is a window object.
+ *
+ * @private
+ * @param {*} obj Object to check
+ * @returns {boolean} True if `obj` is a window obj.
+ */
+function isWindow(obj) {
+ return obj && obj.window === obj;
+}
+
+
+function isScope(obj) {
+ return obj && obj.$evalAsync && obj.$watch;
+}
+
+
+function isFile(obj) {
+ return toString.call(obj) === '[object File]';
+}
+
+
+function isFormData(obj) {
+ return toString.call(obj) === '[object FormData]';
+}
+
+
+function isBlob(obj) {
+ return toString.call(obj) === '[object Blob]';
+}
+
+
+function isBoolean(value) {
+ return typeof value === 'boolean';
+}
+
+
+function isPromiseLike(obj) {
+ return obj && isFunction(obj.then);
+}
+
+
+var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
+function isTypedArray(value) {
+ return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
+}
+
+
+var trim = function(value) {
+ return isString(value) ? value.trim() : value;
+};
+
+// Copied from:
+// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
+// Prereq: s is a string.
+var escapeForRegexp = function(s) {
+ return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
+ replace(/\x08/g, '\\x08');
+};
+
+
+/**
+ * @ngdoc function
+ * @name angular.isElement
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if a reference is a DOM element (or wrapped jQuery element).
+ *
+ * @param {*} value Reference to check.
+ * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
+ */
+function isElement(node) {
+ return !!(node &&
+ (node.nodeName // we are a direct element
+ || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
+}
+
+/**
+ * @param str 'key1,key2,...'
+ * @returns {object} in the form of {key1:true, key2:true, ...}
+ */
+function makeMap(str) {
+ var obj = {}, items = str.split(","), i;
+ for (i = 0; i < items.length; i++) {
+ obj[items[i]] = true;
+ }
+ return obj;
+}
+
+
+function nodeName_(element) {
+ return lowercase(element.nodeName || (element[0] && element[0].nodeName));
+}
+
+function includes(array, obj) {
+ return Array.prototype.indexOf.call(array, obj) != -1;
+}
+
+function arrayRemove(array, value) {
+ var index = array.indexOf(value);
+ if (index >= 0) {
+ array.splice(index, 1);
+ }
+ return index;
+}
+
+/**
+ * @ngdoc function
+ * @name angular.copy
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Creates a deep copy of `source`, which should be an object or an array.
+ *
+ * * If no destination is supplied, a copy of the object or array is created.
+ * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
+ * are deleted and then all elements/properties from the source are copied to it.
+ * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
+ * * If `source` is identical to 'destination' an exception will be thrown.
+ *
+ * @param {*} source The source that will be used to make a copy.
+ * Can be any type, including primitives, `null`, and `undefined`.
+ * @param {(Object|Array)=} destination Destination into which the source is copied. If
+ * provided, must be of the same type as `source`.
+ * @returns {*} The copy or updated `destination`, if `destination` was specified.
+ *
+ * @example
+ <example module="copyExample">
+ <file name="index.html">
+ <div ng-controller="ExampleController">
+ <form novalidate class="simple-form">
+ Name: <input type="text" ng-model="user.name" /><br />
+ E-mail: <input type="email" ng-model="user.email" /><br />
+ Gender: <input type="radio" ng-model="user.gender" value="male" />male
+ <input type="radio" ng-model="user.gender" value="female" />female<br />
+ <button ng-click="reset()">RESET</button>
+ <button ng-click="update(user)">SAVE</button>
+ </form>
+ <pre>form = {{user | json}}</pre>
+ <pre>master = {{master | json}}</pre>
+ </div>
+
+ <script>
+ angular.module('copyExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.master= {};
+
+ $scope.update = function(user) {
+ // Example with 1 argument
+ $scope.master= angular.copy(user);
+ };
+
+ $scope.reset = function() {
+ // Example with 2 arguments
+ angular.copy($scope.master, $scope.user);
+ };
+
+ $scope.reset();
+ }]);
+ </script>
+ </file>
+ </example>
+ */
+function copy(source, destination) {
+ var stackSource = [];
+ var stackDest = [];
+
+ if (destination) {
+ if (isTypedArray(destination)) {
+ throw ngMinErr('cpta', "Can't copy! TypedArray destination cannot be mutated.");
+ }
+ if (source === destination) {
+ throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
+ }
+
+ // Empty the destination object
+ if (isArray(destination)) {
+ destination.length = 0;
+ } else {
+ forEach(destination, function(value, key) {
+ if (key !== '$$hashKey') {
+ delete destination[key];
+ }
+ });
+ }
+
+ stackSource.push(source);
+ stackDest.push(destination);
+ return copyRecurse(source, destination);
+ }
+
+ return copyElement(source);
+
+ function copyRecurse(source, destination) {
+ var h = destination.$$hashKey;
+ var result, key;
+ if (isArray(source)) {
+ for (var i = 0, ii = source.length; i < ii; i++) {
+ destination.push(copyElement(source[i]));
+ }
+ } else if (isBlankObject(source)) {
+ // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
+ for (key in source) {
+ destination[key] = copyElement(source[key]);
+ }
+ } else if (source && typeof source.hasOwnProperty === 'function') {
+ // Slow path, which must rely on hasOwnProperty
+ for (key in source) {
+ if (source.hasOwnProperty(key)) {
+ destination[key] = copyElement(source[key]);
+ }
+ }
+ } else {
+ // Slowest path --- hasOwnProperty can't be called as a method
+ for (key in source) {
+ if (hasOwnProperty.call(source, key)) {
+ destination[key] = copyElement(source[key]);
+ }
+ }
+ }
+ setHashKey(destination, h);
+ return destination;
+ }
+
+ function copyElement(source) {
+ // Simple values
+ if (!isObject(source)) {
+ return source;
+ }
+
+ // Already copied values
+ var index = stackSource.indexOf(source);
+ if (index !== -1) {
+ return stackDest[index];
+ }
+
+ if (isWindow(source) || isScope(source)) {
+ throw ngMinErr('cpws',
+ "Can't copy! Making copies of Window or Scope instances is not supported.");
+ }
+
+ var needsRecurse = false;
+ var destination;
+
+ if (isArray(source)) {
+ destination = [];
+ needsRecurse = true;
+ } else if (isTypedArray(source)) {
+ destination = new source.constructor(source);
+ } else if (isDate(source)) {
+ destination = new Date(source.getTime());
+ } else if (isRegExp(source)) {
+ destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
+ destination.lastIndex = source.lastIndex;
+ } else if (isFunction(source.cloneNode)) {
+ destination = source.cloneNode(true);
+ } else {
+ destination = Object.create(getPrototypeOf(source));
+ needsRecurse = true;
+ }
+
+ stackSource.push(source);
+ stackDest.push(destination);
+
+ return needsRecurse
+ ? copyRecurse(source, destination)
+ : destination;
+ }
+}
+
+/**
+ * Creates a shallow copy of an object, an array or a primitive.
+ *
+ * Assumes that there are no proto properties for objects.
+ */
+function shallowCopy(src, dst) {
+ if (isArray(src)) {
+ dst = dst || [];
+
+ for (var i = 0, ii = src.length; i < ii; i++) {
+ dst[i] = src[i];
+ }
+ } else if (isObject(src)) {
+ dst = dst || {};
+
+ for (var key in src) {
+ if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
+ dst[key] = src[key];
+ }
+ }
+ }
+
+ return dst || src;
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.equals
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Determines if two objects or two values are equivalent. Supports value types, regular
+ * expressions, arrays and objects.
+ *
+ * Two objects or values are considered equivalent if at least one of the following is true:
+ *
+ * * Both objects or values pass `===` comparison.
+ * * Both objects or values are of the same type and all of their properties are equal by
+ * comparing them with `angular.equals`.
+ * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
+ * * Both values represent the same regular expression (In JavaScript,
+ * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
+ * representation matches).
+ *
+ * During a property comparison, properties of `function` type and properties with names
+ * that begin with `$` are ignored.
+ *
+ * Scope and DOMWindow objects are being compared only by identify (`===`).
+ *
+ * @param {*} o1 Object or value to compare.
+ * @param {*} o2 Object or value to compare.
+ * @returns {boolean} True if arguments are equal.
+ */
+function equals(o1, o2) {
+ if (o1 === o2) return true;
+ if (o1 === null || o2 === null) return false;
+ if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
+ var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
+ if (t1 == t2) {
+ if (t1 == 'object') {
+ if (isArray(o1)) {
+ if (!isArray(o2)) return false;
+ if ((length = o1.length) == o2.length) {
+ for (key = 0; key < length; key++) {
+ if (!equals(o1[key], o2[key])) return false;
+ }
+ return true;
+ }
+ } else if (isDate(o1)) {
+ if (!isDate(o2)) return false;
+ return equals(o1.getTime(), o2.getTime());
+ } else if (isRegExp(o1)) {
+ return isRegExp(o2) ? o1.toString() == o2.toString() : false;
+ } else {
+ if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
+ isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
+ keySet = createMap();
+ for (key in o1) {
+ if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
+ if (!equals(o1[key], o2[key])) return false;
+ keySet[key] = true;
+ }
+ for (key in o2) {
+ if (!(key in keySet) &&
+ key.charAt(0) !== '$' &&
+ isDefined(o2[key]) &&
+ !isFunction(o2[key])) return false;
+ }
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+var csp = function() {
+ if (!isDefined(csp.rules)) {
+
+
+ var ngCspElement = (document.querySelector('[ng-csp]') ||
+ document.querySelector('[data-ng-csp]'));
+
+ if (ngCspElement) {
+ var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
+ ngCspElement.getAttribute('data-ng-csp');
+ csp.rules = {
+ noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
+ noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
+ };
+ } else {
+ csp.rules = {
+ noUnsafeEval: noUnsafeEval(),
+ noInlineStyle: false
+ };
+ }
+ }
+
+ return csp.rules;
+
+ function noUnsafeEval() {
+ try {
+ /* jshint -W031, -W054 */
+ new Function('');
+ /* jshint +W031, +W054 */
+ return false;
+ } catch (e) {
+ return true;
+ }
+ }
+};
+
+/**
+ * @ngdoc directive
+ * @module ng
+ * @name ngJq
+ *
+ * @element ANY
+ * @param {string=} ngJq the name of the library available under `window`
+ * to be used for angular.element
+ * @description
+ * Use this directive to force the angular.element library. This should be
+ * used to force either jqLite by leaving ng-jq blank or setting the name of
+ * the jquery variable under window (eg. jQuery).
+ *
+ * Since angular looks for this directive when it is loaded (doesn't wait for the
+ * DOMContentLoaded event), it must be placed on an element that comes before the script
+ * which loads angular. Also, only the first instance of `ng-jq` will be used and all
+ * others ignored.
+ *
+ * @example
+ * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
+ ```html
+ <!doctype html>
+ <html ng-app ng-jq>
+ ...
+ ...
+ </html>
+ ```
+ * @example
+ * This example shows how to use a jQuery based library of a different name.
+ * The library name must be available at the top most 'window'.
+ ```html
+ <!doctype html>
+ <html ng-app ng-jq="jQueryLib">
+ ...
+ ...
+ </html>
+ ```
+ */
+var jq = function() {
+ if (isDefined(jq.name_)) return jq.name_;
+ var el;
+ var i, ii = ngAttrPrefixes.length, prefix, name;
+ for (i = 0; i < ii; ++i) {
+ prefix = ngAttrPrefixes[i];
+ if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
+ name = el.getAttribute(prefix + 'jq');
+ break;
+ }
+ }
+
+ return (jq.name_ = name);
+};
+
+function concat(array1, array2, index) {
+ return array1.concat(slice.call(array2, index));
+}
+
+function sliceArgs(args, startIndex) {
+ return slice.call(args, startIndex || 0);
+}
+
+
+/* jshint -W101 */
+/**
+ * @ngdoc function
+ * @name angular.bind
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
+ * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
+ * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
+ * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
+ *
+ * @param {Object} self Context which `fn` should be evaluated in.
+ * @param {function()} fn Function to be bound.
+ * @param {...*} args Optional arguments to be prebound to the `fn` function call.
+ * @returns {function()} Function that wraps the `fn` with all the specified bindings.
+ */
+/* jshint +W101 */
+function bind(self, fn) {
+ var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
+ if (isFunction(fn) && !(fn instanceof RegExp)) {
+ return curryArgs.length
+ ? function() {
+ return arguments.length
+ ? fn.apply(self, concat(curryArgs, arguments, 0))
+ : fn.apply(self, curryArgs);
+ }
+ : function() {
+ return arguments.length
+ ? fn.apply(self, arguments)
+ : fn.call(self);
+ };
+ } else {
+ // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
+ return fn;
+ }
+}
+
+
+function toJsonReplacer(key, value) {
+ var val = value;
+
+ if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
+ val = undefined;
+ } else if (isWindow(value)) {
+ val = '$WINDOW';
+ } else if (value && document === value) {
+ val = '$DOCUMENT';
+ } else if (isScope(value)) {
+ val = '$SCOPE';
+ }
+
+ return val;
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.toJson
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
+ * stripped since angular uses this notation internally.
+ *
+ * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
+ * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
+ * If set to an integer, the JSON output will contain that many spaces per indentation.
+ * @returns {string|undefined} JSON-ified string representing `obj`.
+ */
+function toJson(obj, pretty) {
+ if (typeof obj === 'undefined') return undefined;
+ if (!isNumber(pretty)) {
+ pretty = pretty ? 2 : null;
+ }
+ return JSON.stringify(obj, toJsonReplacer, pretty);
+}
+
+
+/**
+ * @ngdoc function
+ * @name angular.fromJson
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Deserializes a JSON string.
+ *
+ * @param {string} json JSON string to deserialize.
+ * @returns {Object|Array|string|number} Deserialized JSON string.
+ */
+function fromJson(json) {
+ return isString(json)
+ ? JSON.parse(json)
+ : json;
+}
+
+
+function timezoneToOffset(timezone, fallback) {
+ var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
+ return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
+}
+
+
+function addDateMinutes(date, minutes) {
+ date = new Date(date.getTime());
+ date.setMinutes(date.getMinutes() + minutes);
+ return date;
+}
+
+
+function convertTimezoneToLocal(date, timezone, reverse) {
+ reverse = reverse ? -1 : 1;
+ var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
+ return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
+}
+
+
+/**
+ * @returns {string} Returns the string representation of the element.
+ */
+function startingTag(element) {
+ element = jqLite(element).clone();
+ try {
+ // turns out IE does not let you set .html() on elements which
+ // are not allowed to have children. So we just ignore it.
+ element.empty();
+ } catch (e) {}
+ var elemHtml = jqLite('<div>').append(element).html();
+ try {
+ return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
+ elemHtml.
+ match(/^(<[^>]+>)/)[1].
+ replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
+ } catch (e) {
+ return lowercase(elemHtml);
+ }
+
+}
+
+
+/////////////////////////////////////////////////
+
+/**
+ * Tries to decode the URI component without throwing an exception.
+ *
+ * @private
+ * @param str value potential URI component to check.
+ * @returns {boolean} True if `value` can be decoded
+ * with the decodeURIComponent function.
+ */
+function tryDecodeURIComponent(value) {
+ try {
+ return decodeURIComponent(value);
+ } catch (e) {
+ // Ignore any invalid uri component
+ }
+}
+
+
+/**
+ * Parses an escaped url query string into key-value pairs.
+ * @returns {Object.<string,boolean|Array>}
+ */
+function parseKeyValue(/**string*/keyValue) {
+ var obj = {};
+ forEach((keyValue || "").split('&'), function(keyValue) {
+ var splitPoint, key, val;
+ if (keyValue) {
+ key = keyValue = keyValue.replace(/\+/g,'%20');
+ splitPoint = keyValue.indexOf('=');
+ if (splitPoint !== -1) {
+ key = keyValue.substring(0, splitPoint);
+ val = keyValue.substring(splitPoint + 1);
+ }
+ key = tryDecodeURIComponent(key);
+ if (isDefined(key)) {
+ val = isDefined(val) ? tryDecodeURIComponent(val) : true;
+ if (!hasOwnProperty.call(obj, key)) {
+ obj[key] = val;
+ } else if (isArray(obj[key])) {
+ obj[key].push(val);
+ } else {
+ obj[key] = [obj[key],val];
+ }
+ }
+ }
+ });
+ return obj;
+}
+
+function toKeyValue(obj) {
+ var parts = [];
+ forEach(obj, function(value, key) {
+ if (isArray(value)) {
+ forEach(value, function(arrayValue) {
+ parts.push(encodeUriQuery(key, true) +
+ (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
+ });
+ } else {
+ parts.push(encodeUriQuery(key, true) +
+ (value === true ? '' : '=' + encodeUriQuery(value, true)));
+ }
+ });
+ return parts.length ? parts.join('&') : '';
+}
+
+
+/**
+ * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
+ * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
+ * segments:
+ * segment = *pchar
+ * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
+ * pct-encoded = "%" HEXDIG HEXDIG
+ * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
+ * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
+ * / "*" / "+" / "," / ";" / "="
+ */
+function encodeUriSegment(val) {
+ return encodeUriQuery(val, true).
+ replace(/%26/gi, '&').
+ replace(/%3D/gi, '=').
+ replace(/%2B/gi, '+');
+}
+
+
+/**
+ * This method is intended for encoding *key* or *value* parts of query component. We need a custom
+ * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
+ * encoded per http://tools.ietf.org/html/rfc3986:
+ * query = *( pchar / "/" / "?" )
+ * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
+ * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
+ * pct-encoded = "%" HEXDIG HEXDIG
+ * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
+ * / "*" / "+" / "," / ";" / "="
+ */
+function encodeUriQuery(val, pctEncodeSpaces) {
+ return encodeURIComponent(val).
+ replace(/%40/gi, '@').
+ replace(/%3A/gi, ':').
+ replace(/%24/g, '$').
+ replace(/%2C/gi, ',').
+ replace(/%3B/gi, ';').
+ replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
+}
+
+var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
+
+function getNgAttribute(element, ngAttr) {
+ var attr, i, ii = ngAttrPrefixes.length;
+ for (i = 0; i < ii; ++i) {
+ attr = ngAttrPrefixes[i] + ngAttr;
+ if (isString(attr = element.getAttribute(attr))) {
+ return attr;
+ }
+ }
+ return null;
+}
+
+/**
+ * @ngdoc directive
+ * @name ngApp
+ * @module ng
+ *
+ * @element ANY
+ * @param {angular.Module} ngApp an optional application
+ * {@link angular.module module} name to load.
+ * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
+ * created in "strict-di" mode. This means that the application will fail to invoke functions which
+ * do not use explicit function annotation (and are thus unsuitable for minification), as described
+ * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
+ * tracking down the root of these bugs.
+ *
+ * @description
+ *
+ * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
+ * designates the **root element** of the application and is typically placed near the root element
+ * of the page - e.g. on the `<body>` or `<html>` tags.
+ *
+ * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
+ * found in the document will be used to define the root element to auto-bootstrap as an
+ * application. To run multiple applications in an HTML document you must manually bootstrap them using
+ * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
+ *
+ * You can specify an **AngularJS module** to be used as the root module for the application. This
+ * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
+ * should contain the application code needed or have dependencies on other modules that will
+ * contain the code. See {@link angular.module} for more information.
+ *
+ * In the example below if the `ngApp` directive were not placed on the `html` element then the
+ * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
+ * would not be resolved to `3`.
+ *
+ * `ngApp` is the easiest, and most common way to bootstrap an application.
+ *
+ <example module="ngAppDemo">
+ <file name="index.html">
+ <div ng-controller="ngAppDemoController">
+ I can add: {{a}} + {{b}} = {{ a+b }}
+ </div>
+ </file>
+ <file name="script.js">
+ angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
+ $scope.a = 1;
+ $scope.b = 2;
+ });
+ </file>
+ </example>
+ *
+ * Using `ngStrictDi`, you would see something like this:
+ *
+ <example ng-app-included="true">
+ <file name="index.html">
+ <div ng-app="ngAppStrictDemo" ng-strict-di>
+ <div ng-controller="GoodController1">
+ I can add: {{a}} + {{b}} = {{ a+b }}
+
+ <p>This renders because the controller does not fail to
+ instantiate, by using explicit annotation style (see
+ script.js for details)
+ </p>
+ </div>
+
+ <div ng-controller="GoodController2">
+ Name: <input ng-model="name"><br />
+ Hello, {{name}}!
+
+ <p>This renders because the controller does not fail to
+ instantiate, by using explicit annotation style
+ (see script.js for details)
+ </p>
+ </div>
+
+ <div ng-controller="BadController">
+ I can add: {{a}} + {{b}} = {{ a+b }}
+
+ <p>The controller could not be instantiated, due to relying
+ on automatic function annotations (which are disabled in
+ strict mode). As such, the content of this section is not
+ interpolated, and there should be an error in your web console.
+ </p>
+ </div>
+ </div>
+ </file>
+ <file name="script.js">
+ angular.module('ngAppStrictDemo', [])
+ // BadController will fail to instantiate, due to relying on automatic function annotation,
+ // rather than an explicit annotation
+ .controller('BadController', function($scope) {
+ $scope.a = 1;
+ $scope.b = 2;
+ })
+ // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
+ // due to using explicit annotations using the array style and $inject property, respectively.
+ .controller('GoodController1', ['$scope', function($scope) {
+ $scope.a = 1;
+ $scope.b = 2;
+ }])
+ .controller('GoodController2', GoodController2);
+ function GoodController2($scope) {
+ $scope.name = "World";
+ }
+ GoodController2.$inject = ['$scope'];
+ </file>
+ <file name="style.css">
+ div[ng-controller] {
+ margin-bottom: 1em;
+ -webkit-border-radius: 4px;
+ border-radius: 4px;
+ border: 1px solid;
+ padding: .5em;
+ }
+ div[ng-controller^=Good] {
+ border-color: #d6e9c6;
+ background-color: #dff0d8;
+ color: #3c763d;
+ }
+ div[ng-controller^=Bad] {
+ border-color: #ebccd1;
+ background-color: #f2dede;
+ color: #a94442;
+ margin-bottom: 0;
+ }
+ </file>
+ </example>
+ */
+function angularInit(element, bootstrap) {
+ var appElement,
+ module,
+ config = {};
+
+ // The element `element` has priority over any other element
+ forEach(ngAttrPrefixes, function(prefix) {
+ var name = prefix + 'app';
+
+ if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
+ appElement = element;
+ module = element.getAttribute(name);
+ }
+ });
+ forEach(ngAttrPrefixes, function(prefix) {
+ var name = prefix + 'app';
+ var candidate;
+
+ if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
+ appElement = candidate;
+ module = candidate.getAttribute(name);
+ }
+ });
+ if (appElement) {
+ config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
+ bootstrap(appElement, module ? [module] : [], config);
+ }
+}
+
+/**
+ * @ngdoc function
+ * @name angular.bootstrap
+ * @module ng
+ * @description
+ * Use this function to manually start up angular application.
+ *
+ * See: {@link guide/bootstrap Bootstrap}
+ *
+ * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
+ * They must use {@link ng.directive:ngApp ngApp}.
+ *
+ * Angular will detect if it has been loaded into the browser more than once and only allow the
+ * first loaded script to be bootstrapped and will report a warning to the browser console for
+ * each of the subsequent scripts. This prevents strange results in applications, where otherwise
+ * multiple instances of Angular try to work on the DOM.
+ *
+ * ```html
+ * <!doctype html>
+ * <html>
+ * <body>
+ * <div ng-controller="WelcomeController">
+ * {{greeting}}
+ * </div>
+ *
+ * <script src="angular.js"></script>
+ * <script>
+ * var app = angular.module('demo', [])
+ * .controller('WelcomeController', function($scope) {
+ * $scope.greeting = 'Welcome!';
+ * });
+ * angular.bootstrap(document, ['demo']);
+ * </script>
+ * </body>
+ * </html>
+ * ```
+ *
+ * @param {DOMElement} element DOM element which is the root of angular application.
+ * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
+ * Each item in the array should be the name of a predefined module or a (DI annotated)
+ * function that will be invoked by the injector as a `config` block.
+ * See: {@link angular.module modules}
+ * @param {Object=} config an object for defining configuration options for the application. The
+ * following keys are supported:
+ *
+ * * `strictDi` - disable automatic function annotation for the application. This is meant to
+ * assist in finding bugs which break minified code. Defaults to `false`.
+ *
+ * @returns {auto.$injector} Returns the newly created injector for this app.
+ */
+function bootstrap(element, modules, config) {
+ if (!isObject(config)) config = {};
+ var defaultConfig = {
+ strictDi: false
+ };
+ config = extend(defaultConfig, config);
+ var doBootstrap = function() {
+ element = jqLite(element);
+
+ if (element.injector()) {
+ var tag = (element[0] === document) ? 'document' : startingTag(element);
+ //Encode angle brackets to prevent input from being sanitized to empty string #8683
+ throw ngMinErr(
+ 'btstrpd',
+ "App Already Bootstrapped with this Element '{0}'",
+ tag.replace(/</,'<').replace(/>/,'>'));
+ }
+
+ modules = modules || [];
+ modules.unshift(['$provide', function($provide) {
+ $provide.value('$rootElement', element);
+ }]);
+
+ if (config.debugInfoEnabled) {
+ // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
+ modules.push(['$compileProvider', function($compileProvider) {
+ $compileProvider.debugInfoEnabled(true);
+ }]);
+ }
+
+ modules.unshift('ng');
+ var injector = createInjector(modules, config.strictDi);
+ injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
+ function bootstrapApply(scope, element, compile, injector) {
+ scope.$apply(function() {
+ element.data('$injector', injector);
+ compile(element)(scope);
+ });
+ }]
+ );
+ return injector;
+ };
+
+ var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
+ var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
+
+ if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
+ config.debugInfoEnabled = true;
+ window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
+ }
+
+ if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
+ return doBootstrap();
+ }
+
+ window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
+ angular.resumeBootstrap = function(extraModules) {
+ forEach(extraModules, function(module) {
+ modules.push(module);
+ });
+ return doBootstrap();
+ };
+
+ if (isFunction(angular.resumeDeferredBootstrap)) {
+ angular.resumeDeferredBootstrap();
+ }
+}
+
+/**
+ * @ngdoc function
+ * @name angular.reloadWithDebugInfo
+ * @module ng
+ * @description
+ * Use this function to reload the current application with debug information turned on.
+ * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
+ *
+ * See {@link ng.$compileProvider#debugInfoEnabled} for more.
+ */
+function reloadWithDebugInfo() {
+ window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
+ window.location.reload();
+}
+
+/**
+ * @name angular.getTestability
+ * @module ng
+ * @description
+ * Get the testability service for the instance of Angular on the given
+ * element.
+ * @param {DOMElement} element DOM element which is the root of angular application.
+ */
+function getTestability(rootElement) {
+ var injector = angular.element(rootElement).injector();
+ if (!injector) {
+ throw ngMinErr('test',
+ 'no injector found for element argument to getTestability');
+ }
+ return injector.get('$$testability');
+}
+
+var SNAKE_CASE_REGEXP = /[A-Z]/g;
+function snake_case(name, separator) {
+ separator = separator || '_';
+ return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
+ return (pos ? separator : '') + letter.toLowerCase();
+ });
+}
+
+var bindJQueryFired = false;
+var skipDestroyOnNextJQueryCleanData;
+function bindJQuery() {
+ var originalCleanData;
+
+ if (bindJQueryFired) {
+ return;
+ }
+
+ // bind to jQuery if present;
+ var jqName = jq();
+ jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
+ !jqName ? undefined : // use jqLite
+ window[jqName]; // use jQuery specified by `ngJq`
+
+ // Use jQuery if it exists with proper functionality, otherwise default to us.
+ // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
+ // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
+ // versions. It will not work for sure with jQuery <1.7, though.
+ if (jQuery && jQuery.fn.on) {
+ jqLite = jQuery;
+ extend(jQuery.fn, {
+ scope: JQLitePrototype.scope,
+ isolateScope: JQLitePrototype.isolateScope,
+ controller: JQLitePrototype.controller,
+ injector: JQLitePrototype.injector,
+ inheritedData: JQLitePrototype.inheritedData
+ });
+
+ // All nodes removed from the DOM via various jQuery APIs like .remove()
+ // are passed through jQuery.cleanData. Monkey-patch this method to fire
+ // the $destroy event on all removed nodes.
+ originalCleanData = jQuery.cleanData;
+ jQuery.cleanData = function(elems) {
+ var events;
+ if (!skipDestroyOnNextJQueryCleanData) {
+ for (var i = 0, elem; (elem = elems[i]) != null; i++) {
+ events = jQuery._data(elem, "events");
+ if (events && events.$destroy) {
+ jQuery(elem).triggerHandler('$destroy');
+ }
+ }
+ } else {
+ skipDestroyOnNextJQueryCleanData = false;
+ }
+ originalCleanData(elems);
+ };
+ } else {
+ jqLite = JQLite;
+ }
+
+ angular.element = jqLite;
+
+ // Prevent double-proxying.
+ bindJQueryFired = true;
+}
+
+/**
+ * throw error if the argument is falsy.
+ */
+function assertArg(arg, name, reason) {
+ if (!arg) {
+ throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
+ }
+ return arg;
+}
+
+function assertArgFn(arg, name, acceptArrayAnnotation) {
+ if (acceptArrayAnnotation && isArray(arg)) {
+ arg = arg[arg.length - 1];
+ }
+
+ assertArg(isFunction(arg), name, 'not a function, got ' +
+ (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
+ return arg;
+}
+
+/**
+ * throw error if the name given is hasOwnProperty
+ * @param {String} name the name to test
+ * @param {String} context the context in which the name is used, such as module or directive
+ */
+function assertNotHasOwnProperty(name, context) {
+ if (name === 'hasOwnProperty') {
+ throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
+ }
+}
+
+/**
+ * Return the value accessible from the object by path. Any undefined traversals are ignored
+ * @param {Object} obj starting object
+ * @param {String} path path to traverse
+ * @param {boolean} [bindFnToScope=true]
+ * @returns {Object} value as accessible by path
+ */
+//TODO(misko): this function needs to be removed
+function getter(obj, path, bindFnToScope) {
+ if (!path) return obj;
+ var keys = path.split('.');
+ var key;
+ var lastInstance = obj;
+ var len = keys.length;
+
+ for (var i = 0; i < len; i++) {
+ key = keys[i];
+ if (obj) {
+ obj = (lastInstance = obj)[key];
+ }
+ }
+ if (!bindFnToScope && isFunction(obj)) {
+ return bind(lastInstance, obj);
+ }
+ return obj;
+}
+
+/**
+ * Return the DOM siblings between the first and last node in the given array.
+ * @param {Array} array like object
+ * @returns {Array} the inputted object or a jqLite collection containing the nodes
+ */
+function getBlockNodes(nodes) {
+ // TODO(perf): update `nodes` instead of creating a new object?
+ var node = nodes[0];
+ var endNode = nodes[nodes.length - 1];
+ var blockNodes;
+
+ for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
+ if (blockNodes || nodes[i] !== node) {
+ if (!blockNodes) {
+ blockNodes = jqLite(slice.call(nodes, 0, i));
+ }
+ blockNodes.push(node);
+ }
+ }
+
+ return blockNodes || nodes;
+}
+
+
+/**
+ * Creates a new object without a prototype. This object is useful for lookup without having to
+ * guard against prototypically inherited properties via hasOwnProperty.
+ *
+ * Related micro-benchmarks:
+ * - http://jsperf.com/object-create2
+ * - http://jsperf.com/proto-map-lookup/2
+ * - http://jsperf.com/for-in-vs-object-keys2
+ *
+ * @returns {Object}
+ */
+function createMap() {
+ return Object.create(null);
+}
+
+var NODE_TYPE_ELEMENT = 1;
+var NODE_TYPE_ATTRIBUTE = 2;
+var NODE_TYPE_TEXT = 3;
+var NODE_TYPE_COMMENT = 8;
+var NODE_TYPE_DOCUMENT = 9;
+var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
+
+/**
+ * @ngdoc type
+ * @name angular.Module
+ * @module ng
+ * @description
+ *
+ * Interface for configuring angular {@link angular.module modules}.
+ */
+
+function setupModuleLoader(window) {
+
+ var $injectorMinErr = minErr('$injector');
+ var ngMinErr = minErr('ng');
+
+ function ensure(obj, name, factory) {
+ return obj[name] || (obj[name] = factory());
+ }
+
+ var angular = ensure(window, 'angular', Object);
+
+ // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
+ angular.$$minErr = angular.$$minErr || minErr;
+
+ return ensure(angular, 'module', function() {
+ /** @type {Object.<string, angular.Module>} */
+ var modules = {};
+
+ /**
+ * @ngdoc function
+ * @name angular.module
+ * @module ng
+ * @description
+ *
+ * The `angular.module` is a global place for creating, registering and retrieving Angular
+ * modules.
+ * All modules (angular core or 3rd party) that should be available to an application must be
+ * registered using this mechanism.
+ *
+ * Passing one argument retrieves an existing {@link angular.Module},
+ * whereas passing more than one argument creates a new {@link angular.Module}
+ *
+ *
+ * # Module
+ *
+ * A module is a collection of services, directives, controllers, filters, and configuration information.
+ * `angular.module` is used to configure the {@link auto.$injector $injector}.
+ *
+ * ```js
+ * // Create a new module
+ * var myModule = angular.module('myModule', []);
+ *
+ * // register a new service
+ * myModule.value('appName', 'MyCoolApp');
+ *
+ * // configure existing services inside initialization blocks.
+ * myModule.config(['$locationProvider', function($locationProvider) {
+ * // Configure existing providers
+ * $locationProvider.hashPrefix('!');
+ * }]);
+ * ```
+ *
+ * Then you can create an injector and load your modules like this:
+ *
+ * ```js
+ * var injector = angular.injector(['ng', 'myModule'])
+ * ```
+ *
+ * However it's more likely that you'll just use
+ * {@link ng.directive:ngApp ngApp} or
+ * {@link angular.bootstrap} to simplify this process for you.
+ *
+ * @param {!string} name The name of the module to create or retrieve.
+ * @param {!Array.<string>=} requires If specified then new module is being created. If
+ * unspecified then the module is being retrieved for further configuration.
+ * @param {Function=} configFn Optional configuration function for the module. Same as
+ * {@link angular.Module#config Module#config()}.
+ * @returns {module} new module with the {@link angular.Module} api.
+ */
+ return function module(name, requires, configFn) {
+ var assertNotHasOwnProperty = function(name, context) {
+ if (name === 'hasOwnProperty') {
+ throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
+ }
+ };
+
+ assertNotHasOwnProperty(name, 'module');
+ if (requires && modules.hasOwnProperty(name)) {
+ modules[name] = null;
+ }
+ return ensure(modules, name, function() {
+ if (!requires) {
+ throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
+ "the module name or forgot to load it. If registering a module ensure that you " +
+ "specify the dependencies as the second argument.", name);
+ }
+
+ /** @type {!Array.<Array.<*>>} */
+ var invokeQueue = [];
+
+ /** @type {!Array.<Function>} */
+ var configBlocks = [];
+
+ /** @type {!Array.<Function>} */
+ var runBlocks = [];
+
+ var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
+
+ /** @type {angular.Module} */
+ var moduleInstance = {
+ // Private state
+ _invokeQueue: invokeQueue,
+ _configBlocks: configBlocks,
+ _runBlocks: runBlocks,
+
+ /**
+ * @ngdoc property
+ * @name angular.Module#requires
+ * @module ng
+ *
+ * @description
+ * Holds the list of modules which the injector will load before the current module is
+ * loaded.
+ */
+ requires: requires,
+
+ /**
+ * @ngdoc property
+ * @name angular.Module#name
+ * @module ng
+ *
+ * @description
+ * Name of the module.
+ */
+ name: name,
+
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#provider
+ * @module ng
+ * @param {string} name service name
+ * @param {Function} providerType Construction function for creating new instance of the
+ * service.
+ * @description
+ * See {@link auto.$provide#provider $provide.provider()}.
+ */
+ provider: invokeLaterAndSetModuleName('$provide', 'provider'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#factory
+ * @module ng
+ * @param {string} name service name
+ * @param {Function} providerFunction Function for creating new instance of the service.
+ * @description
+ * See {@link auto.$provide#factory $provide.factory()}.
+ */
+ factory: invokeLaterAndSetModuleName('$provide', 'factory'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#service
+ * @module ng
+ * @param {string} name service name
+ * @param {Function} constructor A constructor function that will be instantiated.
+ * @description
+ * See {@link auto.$provide#service $provide.service()}.
+ */
+ service: invokeLaterAndSetModuleName('$provide', 'service'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#value
+ * @module ng
+ * @param {string} name service name
+ * @param {*} object Service instance object.
+ * @description
+ * See {@link auto.$provide#value $provide.value()}.
+ */
+ value: invokeLater('$provide', 'value'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#constant
+ * @module ng
+ * @param {string} name constant name
+ * @param {*} object Constant value.
+ * @description
+ * Because the constants are fixed, they get applied before other provide methods.
+ * See {@link auto.$provide#constant $provide.constant()}.
+ */
+ constant: invokeLater('$provide', 'constant', 'unshift'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#decorator
+ * @module ng
+ * @param {string} The name of the service to decorate.
+ * @param {Function} This function will be invoked when the service needs to be
+ * instantiated and should return the decorated service instance.
+ * @description
+ * See {@link auto.$provide#decorator $provide.decorator()}.
+ */
+ decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#animation
+ * @module ng
+ * @param {string} name animation name
+ * @param {Function} animationFactory Factory function for creating new instance of an
+ * animation.
+ * @description
+ *
+ * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
+ *
+ *
+ * Defines an animation hook that can be later used with
+ * {@link $animate $animate} service and directives that use this service.
+ *
+ * ```js
+ * module.animation('.animation-name', function($inject1, $inject2) {
+ * return {
+ * eventName : function(element, done) {
+ * //code to run the animation
+ * //once complete, then run done()
+ * return function cancellationFunction(element) {
+ * //code to cancel the animation
+ * }
+ * }
+ * }
+ * })
+ * ```
+ *
+ * See {@link ng.$animateProvider#register $animateProvider.register()} and
+ * {@link ngAnimate ngAnimate module} for more information.
+ */
+ animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#filter
+ * @module ng
+ * @param {string} name Filter name - this must be a valid angular expression identifier
+ * @param {Function} filterFactory Factory function for creating new instance of filter.
+ * @description
+ * See {@link ng.$filterProvider#register $filterProvider.register()}.
+ *
+ * <div class="alert alert-warning">
+ * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
+ * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
+ * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
+ * (`myapp_subsection_filterx`).
+ * </div>
+ */
+ filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#controller
+ * @module ng
+ * @param {string|Object} name Controller name, or an object map of controllers where the
+ * keys are the names and the values are the constructors.
+ * @param {Function} constructor Controller constructor function.
+ * @description
+ * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
+ */
+ controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#directive
+ * @module ng
+ * @param {string|Object} name Directive name, or an object map of directives where the
+ * keys are the names and the values are the factories.
+ * @param {Function} directiveFactory Factory function for creating new instance of
+ * directives.
+ * @description
+ * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
+ */
+ directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#config
+ * @module ng
+ * @param {Function} configFn Execute this function on module load. Useful for service
+ * configuration.
+ * @description
+ * Use this method to register work which needs to be performed on module loading.
+ * For more about how to configure services, see
+ * {@link providers#provider-recipe Provider Recipe}.
+ */
+ config: config,
+
+ /**
+ * @ngdoc method
+ * @name angular.Module#run
+ * @module ng
+ * @param {Function} initializationFn Execute this function after injector creation.
+ * Useful for application initialization.
+ * @description
+ * Use this method to register work which should be performed when the injector is done
+ * loading all modules.
+ */
+ run: function(block) {
+ runBlocks.push(block);
+ return this;
+ }
+ };
+
+ if (configFn) {
+ config(configFn);
+ }
+
+ return moduleInstance;
+
+ /**
+ * @param {string} provider
+ * @param {string} method
+ * @param {String=} insertMethod
+ * @returns {angular.Module}
+ */
+ function invokeLater(provider, method, insertMethod, queue) {
+ if (!queue) queue = invokeQueue;
+ return function() {
+ queue[insertMethod || 'push']([provider, method, arguments]);
+ return moduleInstance;
+ };
+ }
+
+ /**
+ * @param {string} provider
+ * @param {string} method
+ * @returns {angular.Module}
+ */
+ function invokeLaterAndSetModuleName(provider, method) {
+ return function(recipeName, factoryFunction) {
+ if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
+ invokeQueue.push([provider, method, arguments]);
+ return moduleInstance;
+ };
+ }
+ });
+ };
+ });
+
+}
+
+/* global: toDebugString: true */
+
+function serializeObject(obj) {
+ var seen = [];
+
+ return JSON.stringify(obj, function(key, val) {
+ val = toJsonReplacer(key, val);
+ if (isObject(val)) {
+
+ if (seen.indexOf(val) >= 0) return '...';
+
+ seen.push(val);
+ }
+ return val;
+ });
+}
+
+function toDebugString(obj) {
+ if (typeof obj === 'function') {
+ return obj.toString().replace(/ \{[\s\S]*$/, '');
+ } else if (isUndefined(obj)) {
+ return 'undefined';
+ } else if (typeof obj !== 'string') {
+ return serializeObject(obj);
+ }
+ return obj;
+}
+
+/* global angularModule: true,
+ version: true,
+
+ $CompileProvider,
+
+ htmlAnchorDirective,
+ inputDirective,
+ inputDirective,
+ formDirective,
+ scriptDirective,
+ selectDirective,
+ styleDirective,
+ optionDirective,
+ ngBindDirective,
+ ngBindHtmlDirective,
+ ngBindTemplateDirective,
+ ngClassDirective,
+ ngClassEvenDirective,
+ ngClassOddDirective,
+ ngCloakDirective,
+ ngControllerDirective,
+ ngFormDirective,
+ ngHideDirective,
+ ngIfDirective,
+ ngIncludeDirective,
+ ngIncludeFillContentDirective,
+ ngInitDirective,
+ ngNonBindableDirective,
+ ngPluralizeDirective,
+ ngRepeatDirective,
+ ngShowDirective,
+ ngStyleDirective,
+ ngSwitchDirective,
+ ngSwitchWhenDirective,
+ ngSwitchDefaultDirective,
+ ngOptionsDirective,
+ ngTranscludeDirective,
+ ngModelDirective,
+ ngListDirective,
+ ngChangeDirective,
+ patternDirective,
+ patternDirective,
+ requiredDirective,
+ requiredDirective,
+ minlengthDirective,
+ minlengthDirective,
+ maxlengthDirective,
+ maxlengthDirective,
+ ngValueDirective,
+ ngModelOptionsDirective,
+ ngAttributeAliasDirectives,
+ ngEventDirectives,
+
+ $AnchorScrollProvider,
+ $AnimateProvider,
+ $CoreAnimateCssProvider,
+ $$CoreAnimateQueueProvider,
+ $$CoreAnimateRunnerProvider,
+ $BrowserProvider,
+ $CacheFactoryProvider,
+ $ControllerProvider,
+ $DocumentProvider,
+ $ExceptionHandlerProvider,
+ $FilterProvider,
+ $$ForceReflowProvider,
+ $InterpolateProvider,
+ $IntervalProvider,
+ $$HashMapProvider,
+ $HttpProvider,
+ $HttpParamSerializerProvider,
+ $HttpParamSerializerJQLikeProvider,
+ $HttpBackendProvider,
+ $xhrFactoryProvider,
+ $LocationProvider,
+ $LogProvider,
+ $ParseProvider,
+ $RootScopeProvider,
+ $QProvider,
+ $$QProvider,
+ $$SanitizeUriProvider,
+ $SceProvider,
+ $SceDelegateProvider,
+ $SnifferProvider,
+ $TemplateCacheProvider,
+ $TemplateRequestProvider,
+ $$TestabilityProvider,
+ $TimeoutProvider,
+ $$RAFProvider,
+ $WindowProvider,
+ $$jqLiteProvider,
+ $$CookieReaderProvider
+*/
+
+
+/**
+ * @ngdoc object
+ * @name angular.version
+ * @module ng
+ * @description
+ * An object that contains information about the current AngularJS version.
+ *
+ * This object has the following properties:
+ *
+ * - `full` – `{string}` – Full version string, such as "0.9.18".
+ * - `major` – `{number}` – Major version number, such as "0".
+ * - `minor` – `{number}` – Minor version number, such as "9".
+ * - `dot` – `{number}` – Dot version number, such as "18".
+ * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
+ */
+var version = {
+ full: '1.4.8', // all of these placeholder strings will be replaced by grunt's
+ major: 1, // package task
+ minor: 4,
+ dot: 8,
+ codeName: 'ice-manipulation'
+};
+
+
+function publishExternalAPI(angular) {
+ extend(angular, {
+ 'bootstrap': bootstrap,
+ 'copy': copy,
+ 'extend': extend,
+ 'merge': merge,
+ 'equals': equals,
+ 'element': jqLite,
+ 'forEach': forEach,
+ 'injector': createInjector,
+ 'noop': noop,
+ 'bind': bind,
+ 'toJson': toJson,
+ 'fromJson': fromJson,
+ 'identity': identity,
+ 'isUndefined': isUndefined,
+ 'isDefined': isDefined,
+ 'isString': isString,
+ 'isFunction': isFunction,
+ 'isObject': isObject,
+ 'isNumber': isNumber,
+ 'isElement': isElement,
+ 'isArray': isArray,
+ 'version': version,
+ 'isDate': isDate,
+ 'lowercase': lowercase,
+ 'uppercase': uppercase,
+ 'callbacks': {counter: 0},
+ 'getTestability': getTestability,
+ '$$minErr': minErr,
+ '$$csp': csp,
+ 'reloadWithDebugInfo': reloadWithDebugInfo
+ });
+
+ angularModule = setupModuleLoader(window);
+
+ angularModule('ng', ['ngLocale'], ['$provide',
+ function ngModule($provide) {
+ // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
+ $provide.provider({
+ $$sanitizeUri: $$SanitizeUriProvider
+ });
+ $provide.provider('$compile', $CompileProvider).
+ directive({
+ a: htmlAnchorDirective,
+ input: inputDirective,
+ textarea: inputDirective,
+ form: formDirective,
+ script: scriptDirective,
+ select: selectDirective,
+ style: styleDirective,
+ option: optionDirective,
+ ngBind: ngBindDirective,
+ ngBindHtml: ngBindHtmlDirective,
+ ngBindTemplate: ngBindTemplateDirective,
+ ngClass: ngClassDirective,
+ ngClassEven: ngClassEvenDirective,
+ ngClassOdd: ngClassOddDirective,
+ ngCloak: ngCloakDirective,
+ ngController: ngControllerDirective,
+ ngForm: ngFormDirective,
+ ngHide: ngHideDirective,
+ ngIf: ngIfDirective,
+ ngInclude: ngIncludeDirective,
+ ngInit: ngInitDirective,
+ ngNonBindable: ngNonBindableDirective,
+ ngPluralize: ngPluralizeDirective,
+ ngRepeat: ngRepeatDirective,
+ ngShow: ngShowDirective,
+ ngStyle: ngStyleDirective,
+ ngSwitch: ngSwitchDirective,
+ ngSwitchWhen: ngSwitchWhenDirective,
+ ngSwitchDefault: ngSwitchDefaultDirective,
+ ngOptions: ngOptionsDirective,
+ ngTransclude: ngTranscludeDirective,
+ ngModel: ngModelDirective,
+ ngList: ngListDirective,
+ ngChange: ngChangeDirective,
+ pattern: patternDirective,
+ ngPattern: patternDirective,
+ required: requiredDirective,
+ ngRequired: requiredDirective,
+ minlength: minlengthDirective,
+ ngMinlength: minlengthDirective,
+ maxlength: maxlengthDirective,
+ ngMaxlength: maxlengthDirective,
+ ngValue: ngValueDirective,
+ ngModelOptions: ngModelOptionsDirective
+ }).
+ directive({
+ ngInclude: ngIncludeFillContentDirective
+ }).
+ directive(ngAttributeAliasDirectives).
+ directive(ngEventDirectives);
+ $provide.provider({
+ $anchorScroll: $AnchorScrollProvider,
+ $animate: $AnimateProvider,
+ $animateCss: $CoreAnimateCssProvider,
+ $$animateQueue: $$CoreAnimateQueueProvider,
+ $$AnimateRunner: $$CoreAnimateRunnerProvider,
+ $browser: $BrowserProvider,
+ $cacheFactory: $CacheFactoryProvider,
+ $controller: $ControllerProvider,
+ $document: $DocumentProvider,
+ $exceptionHandler: $ExceptionHandlerProvider,
+ $filter: $FilterProvider,
+ $$forceReflow: $$ForceReflowProvider,
+ $interpolate: $InterpolateProvider,
+ $interval: $IntervalProvider,
+ $http: $HttpProvider,
+ $httpParamSerializer: $HttpParamSerializerProvider,
+ $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
+ $httpBackend: $HttpBackendProvider,
+ $xhrFactory: $xhrFactoryProvider,
+ $location: $LocationProvider,
+ $log: $LogProvider,
+ $parse: $ParseProvider,
+ $rootScope: $RootScopeProvider,
+ $q: $QProvider,
+ $$q: $$QProvider,
+ $sce: $SceProvider,
+ $sceDelegate: $SceDelegateProvider,
+ $sniffer: $SnifferProvider,
+ $templateCache: $TemplateCacheProvider,
+ $templateRequest: $TemplateRequestProvider,
+ $$testability: $$TestabilityProvider,
+ $timeout: $TimeoutProvider,
+ $window: $WindowProvider,
+ $$rAF: $$RAFProvider,
+ $$jqLite: $$jqLiteProvider,
+ $$HashMap: $$HashMapProvider,
+ $$cookieReader: $$CookieReaderProvider
+ });
+ }
+ ]);
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Any commits to this file should be reviewed with security in mind. *
+ * Changes to this file can potentially create security vulnerabilities. *
+ * An approval from 2 Core members with history of modifying *
+ * this file is required. *
+ * *
+ * Does the change somehow allow for arbitrary javascript to be executed? *
+ * Or allows for someone to change the prototype of built-in objects? *
+ * Or gives undesired access to variables likes document or window? *
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+/* global JQLitePrototype: true,
+ addEventListenerFn: true,
+ removeEventListenerFn: true,
+ BOOLEAN_ATTR: true,
+ ALIASED_ATTR: true,
+*/
+
+//////////////////////////////////
+//JQLite
+//////////////////////////////////
+
+/**
+ * @ngdoc function
+ * @name angular.element
+ * @module ng
+ * @kind function
+ *
+ * @description
+ * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
+ *
+ * If jQuery is available, `angular.element` is an alias for the
+ * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
+ * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
+ *
+ * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
+ * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
+ * commonly needed functionality with the goal of having a very small footprint.</div>
+ *
+ * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
+ *
+ * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
+ * jqLite; they are never raw DOM references.</div>
+ *
+ * ## Angular's jqLite
+ * jqLite provides only the following jQuery methods:
+ *
+ * - [`addClass()`](http://api.jquery.com/addClass/)
+ * - [`after()`](http://api.jquery.com/after/)
+ * - [`append()`](http://api.jquery.com/append/)
+ * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
+ * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
+ * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
+ * - [`clone()`](http://api.jquery.com/clone/)
+ * - [`contents()`](http://api.jquery.com/contents/)
+ * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
+ * - [`data()`](http://api.jquery.com/data/)
+ * - [`detach()`](http://api.jquery.com/detach/)
+ * - [`empty()`](http://api.jquery.com/empty/)
+ * - [`eq()`](http://api.jquery.com/eq/)
+ * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
+ * - [`hasClass()`](http://api.jquery.com/hasClass/)
+ * - [`html()`](http://api.jquery.com/html/)
+ * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
+ * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
+ * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
+ * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
+ * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
+ * - [`prepend()`](http://api.jquery.com/prepend/)
+ * - [`prop()`](http://api.jquery.com/prop/)
+ * - [`ready()`](http://api.jquery.com/ready/)
+ * - [`remove()`](http://api.jquery.com/remove/)
+ * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
+ * - [`removeClass()`](http://api.jquery.com/removeClass/)
+ * - [`removeData()`](http://api.jquery.com/removeData/)
+ * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
+ * - [`text()`](http://api.jquery.com/text/)
+ * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
+ * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
+ * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
+ * - [`val()`](http://api.jquery.com/val/)
+ * - [`wrap()`](http://api.jquery.com/wrap/)
+ *
+ * ## jQuery/jqLite Extras
+ * Angular also provides the following additional methods and events to both jQuery and jqLite:
+ *
+ * ### Events
+ * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
+ * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
+ * element before it is removed.
+ *
+ * ### Methods
+ * - `controller(name)` - retrieves the controller of the current element or its parent. By default
+ * retrieves controller associated with the `ngController` directive. If `name` is provided as
+ * camelCase directive name, then the controller for this directive will be retrieved (e.g.
+ * `'ngModel'`).
+ * - `injector()` - retrieves the injector of the current element or its parent.
+ * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
+ * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
+ * be enabled.
+ * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
+ * current element. This getter should be used only on elements that contain a directive which starts a new isolate
+ * scope. Calling `scope()` on this element always returns the original non-isolate scope.
+ * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
+ * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
+ * parent element is reached.
+ *
+ * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
+ * @returns {Object} jQuery object.
+ */
+
+JQLite.expando = 'ng339';
+
+var jqCache = JQLite.cache = {},
+ jqId = 1,
+ addEventListenerFn = function(element, type, fn) {
+ element.addEventListener(type, fn, false);
+ },
+ removeEventListenerFn = function(element, type, fn) {
+ element.removeEventListener(type, fn, false);
+ };
+
+/*
+ * !!! This is an undocumented "private" function !!!
+ */
+JQLite._data = function(node) {
+ //jQuery always returns an object on cache miss
+ return this.cache[node[this.expando]] || {};
+};
+
+function jqNextId() { return ++jqId; }
+
+
+var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
+var MOZ_HACK_REGEXP = /^moz([A-Z])/;
+var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
+var jqLiteMinErr = minErr('jqLite');
+
+/**
+ * Converts snake_case to camelCase.
+ * Also there is special case for Moz prefix starting with upper case letter.
+ * @param name Name to normalize
+ */
+function camelCase(name) {
+ return name.
+ replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
+ return offset ? letter.toUpperCase() : letter;
+ }).
+ replace(MOZ_HACK_REGEXP, 'Moz$1');
+}
+
+var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
+var HTML_REGEXP = /<|&#?\w+;/;
+var TAG_NAME_REGEXP = /<([\w:-]+)/;
+var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
+
+var wrapMap = {
+ '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, "", ""]
+};
+
+wrapMap.optgroup = wrapMap.option;
+wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+wrapMap.th = wrapMap.td;
+
+
+function jqLiteIsTextNode(html) {
+ return !HTML_REGEXP.test(html);
+}
+
+function jqLiteAcceptsData(node) {
+ // The window object can accept data but has no nodeType
+ // Otherwise we are only interested in elements (1) and documents (9)
+ var nodeType = node.nodeType;
+ return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
+}
+
+function jqLiteHasData(node) {
+ for (var key in jqCache[node.ng339]) {
+ return true;
+ }
+ return false;
+}
+
+function jqLiteBuildFragment(html, context) {
+ var tmp, tag, wrap,
+ fragment = context.createDocumentFragment(),
+ nodes = [], i;
+
+ if (jqLiteIsTextNode(html)) {
+ // Convert non-html into a text node
+ nodes.push(context.createTextNode(html));
+ } else {
+ // Convert html into DOM nodes
+ tmp = tmp || fragment.appendChild(context.createElement("div"));
+ tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
+ wrap = wrapMap[tag] || wrapMap._default;
+ tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
+
+ // Descend through wrappers to the right content
+ i = wrap[0];
+ while (i--) {
+ tmp = tmp.lastChild;
+ }
+
+ nodes = concat(nodes, tmp.childNodes);
+
+ tmp = fragment.firstChild;
+ tmp.textContent = "";
+ }
+
+ // Remove wrapper from fragment
+ fragment.textContent = "";
+ fragment.innerHTML = ""; // Clear inner HTML
+ forEach(nodes, function(node) {
+ fragment.appendChild(node);
+ });
+
+ return fragment;
+}
+
+function jqLiteParseHTML(html, context) {
+ context = context || document;
+ var parsed;
+
+ if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
+ return [context.createElement(parsed[1])];
+ }
+
+ if ((parsed = jqLiteBuildFragment(html, context))) {
+ return parsed.childNodes;
+ }
+
+ return [];
+}
+
+
+// IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
+var jqLiteContains = Node.prototype.contains || function(arg) {
+ // jshint bitwise: false
+ return !!(this.compareDocumentPosition(arg) & 16);
+ // jshint bitwise: true
+};
+
+/////////////////////////////////////////////
+function JQLite(element) {
+ if (element instanceof JQLite) {
+ return element;
+ }
+
+ var argIsString;
+
+ if (isString(element)) {
+ element = trim(element);
+ argIsString = true;
+ }
+ if (!(this instanceof JQLite)) {
+ if (argIsString && element.charAt(0) != '<') {
+ throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
+ }
+ return new JQLite(element);
+ }
+
+ if (argIsString) {
+ jqLiteAddNodes(this, jqLiteParseHTML(element));
+ } else {
+ jqLiteAddNodes(this, element);
+ }
+}
+
+function jqLiteClone(element) {
+ return element.cloneNode(true);
+}
+
+function jqLiteDealoc(element, onlyDescendants) {
+ if (!onlyDescendants) jqLiteRemoveData(element);
+
+ if (element.querySelectorAll) {
+ var descendants = element.querySelectorAll('*');
+ for (var i = 0, l = descendants.length; i < l; i++) {
+ jqLiteRemoveData(descendants[i]);
+ }
+ }
+}
+
+function jqLiteOff(element, type, fn, unsupported) {
+ if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
+
+ var expandoStore = jqLiteExpandoStore(element);
+ var events = expandoStore && expandoStore.events;
+ var handle = expandoStore && expandoStore.handle;
+
+ if (!handle) return; //no listeners registered
+
+ if (!type) {
+ for (type in events) {
+ if (type !== '$destroy') {
+ removeEventListenerFn(element, type, handle);
+ }
+ delete events[type];
+ }
+ } else {
+
+ var removeHandler = function(type) {
+ var listenerFns = events[type];
+ if (isDefined(fn)) {
+ arrayRemove(listenerFns || [], fn);
+ }
+ if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
+ removeEventListenerFn(element, type, handle);
+ delete events[type];
+ }
+ };
+
+ forEach(type.split(' '), function(type) {
+ removeHandler(type);
+ if (MOUSE_EVENT_MAP[type]) {
+ removeHandler(MOUSE_EVENT_MAP[type]);
+ }
+ });
+ }
+}
+
+function jqLiteRemoveData(element, name) {
+ var expandoId = element.ng339;
+ var expandoStore = expandoId && jqCache[expandoId];
+
+ if (expandoStore) {
+ if (name) {
+ delete expandoStore.data[name];
+ return;
+ }
+
+ if (expandoStore.handle) {
+ if (expandoStore.events.$destroy) {
+ expandoStore.handle({}, '$destroy');
+ }
+ jqLiteOff(element);
+ }
+ delete jqCache[expandoId];
+ element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
+ }
+}
+
+
+function jqLiteExpandoStore(element, createIfNecessary) {
+ var expandoId = element.ng339,
+ expandoStore = expandoId && jqCache[expandoId];
+
+ if (createIfNecessary && !expandoStore) {
+ element.ng339 = expandoId = jqNextId();
+ expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
+ }
+
+ return expandoStore;
+}
+
+
+function jqLiteData(element, key, value) {
+ if (jqLiteAcceptsData(element)) {
+
+ var isSimpleSetter = isDefined(value);
+ var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
+ var massGetter = !key;
+ var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
+ var data = expandoStore && expandoStore.data;
+
+ if (isSimpleSetter) { // data('key', value)
+ data[key] = value;
+ } else {
+ if (massGetter) { // data()
+ return data;
+ } else {
+ if (isSimpleGetter) { // data('key')
+ // don't force creation of expandoStore if it doesn't exist yet
+ return data && data[key];
+ } else { // mass-setter: data({key1: val1, key2: val2})
+ extend(data, key);
+ }
+ }
+ }
+ }
+}
+
+function jqLiteHasClass(element, selector) {
+ if (!element.getAttribute) return false;
+ return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
+ indexOf(" " + selector + " ") > -1);
+}
+
+function jqLiteRemoveClass(element, cssClasses) {
+ if (cssClasses && element.setAttribute) {
+ forEach(cssClasses.split(' '), function(cssClass) {
+ element.setAttribute('class', trim(
+ (" " + (element.getAttribute('class') || '') + " ")
+ .replace(/[\n\t]/g, " ")
+ .replace(" " + trim(cssClass) + " ", " "))
+ );
+ });
+ }
+}
+
+function jqLiteAddClass(element, cssClasses) {
+ if (cssClasses && element.setAttribute) {
+ var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
+ .replace(/[\n\t]/g, " ");
+
+ forEach(cssClasses.split(' '), function(cssClass) {
+ cssClass = trim(cssClass);
+ if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
+ existingClasses += cssClass + ' ';
+ }
+ });
+
+ element.setAttribute('class', trim(existingClasses));
+ }
+}
+
+
+function jqLiteAddNodes(root, elements) {
+ // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
+
+ if (elements) {
+
+ // if a Node (the most common case)
+ if (elements.nodeType) {
+ root[root.length++] = elements;
+ } else {
+ var length = elements.length;
+
+ // if an Array or NodeList and not a Window
+ if (typeof length === 'number' && elements.window !== elements) {
+ if (length) {
+ for (var i = 0; i < length; i++) {
+ root[root.length++] = elements[i];
+ }
+ }
+ } else {
+ root[root.length++] = elements;
+ }
+ }
+ }
+}
+
+
+function jqLiteController(element, name) {
+ return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
+}
+
+function jqLiteInheritedData(element, name, value) {
+ // if element is the document object work with the html element instead
+ // this makes $(document).scope() possible
+ if (element.nodeType == NODE_TYPE_DOCUMENT) {
+ element = element.documentElement;
+ }
+ var names = isArray(name) ? name : [name];
+
+ while (element) {
+ for (var i = 0, ii = names.length; i < ii; i++) {
+ if (isDefined(value = jqLite.data(element, names[i]))) return value;
+ }
+
+ // If dealing with a document fragment node with a host element, and no parent, use the host
+ // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
+ // to lookup parent controllers.
+ element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
+ }
+}
+
+function jqLiteEmpty(element) {
+ jqLiteDealoc(element, true);
+ while (element.firstChild) {
+ element.removeChild(element.firstChild);
+ }
+}
+
+function jqLiteRemove(element, keepData) {
+ if (!keepData) jqLiteDealoc(element);
+ var parent = element.parentNode;
+ if (parent) parent.removeChild(element);
+}
+
+
+function jqLiteDocumentLoaded(action, win) {
+ win = win || window;
+ if (win.document.readyState === 'complete') {
+ // Force the action to be run async for consistent behaviour
+ // from the action's point of view
+ // i.e. it will definitely not be in a $apply
+ win.setTimeout(action);
+ } else {
+ // No need to unbind this handler as load is only ever called once
+ jqLite(win).on('load', action);
+ }
+}
+
+//////////////////////////////////////////
+// Functions which are declared directly.
+//////////////////////////////////////////
+var JQLitePrototype = JQLite.prototype = {
+ ready: function(fn) {
+ var fired = false;
+
+ function trigger() {
+ if (fired) return;
+ fired = true;
+ fn();
+ }
+
+ // check if document is already loaded
+ if (document.readyState === 'complete') {
+ setTimeout(trigger);
+ } else {
+ this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
+ // we can not use jqLite since we are not done loading and jQuery could be loaded later.
+ // jshint -W064
+ JQLite(window).on('load', trigger); // fallback to window.onload for others
+ // jshint +W064
+ }
+ },
+ toString: function() {
+ var value = [];
+ forEach(this, function(e) { value.push('' + e);});
+ return '[' + value.join(', ') + ']';
+ },
+
+ eq: function(index) {
+ return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
+ },
+
+ length: 0,
+ push: push,
+ sort: [].sort,
+ splice: [].splice
+};
+
+//////////////////////////////////////////
+// Functions iterating getter/setters.
+// these functions return self on setter and
+// value on get.
+//////////////////////////////////////////
+var BOOLEAN_ATTR = {};
+forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
+ BOOLEAN_ATTR[lowercase(value)] = value;
+});
+var BOOLEAN_ELEMENTS = {};
+forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
+ BOOLEAN_ELEMENTS[value] = true;
+});
+var ALIASED_ATTR = {
+ 'ngMinlength': 'minlength',
+ 'ngMaxlength': 'maxlength',
+ 'ngMin': 'min',
+ 'ngMax': 'max',
+ 'ngPattern': 'pattern'
+};
+
+function getBooleanAttrName(element, name) {
+ // check dom last since we will most likely fail on name
+ var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
+
+ // booleanAttr is here twice to minimize DOM access
+ return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
+}
+
+function getAliasedAttrName(name) {
+ return ALIASED_ATTR[name];
+}
+
+forEach({
+ data: jqLiteData,
+ removeData: jqLiteRemoveData,
+ hasData: jqLiteHasData
+}, function(fn, name) {
+ JQLite[name] = fn;
+});
+
+forEach({
+ data: jqLiteData,
+ inheritedData: jqLiteInheritedData,
+
+ scope: function(element) {
+ // Can't use jqLiteData here directly so we stay compatible with jQuery!
+ return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
+ },
+
+ isolateScope: function(element) {
+ // Can't use jqLiteData here directly so we stay compatible with jQuery!
+ return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
+ },
+
+ controller: jqLiteController,
+
+ injector: function(element) {
+ return jqLiteInheritedData(element, '$injector');
+ },
+
+ removeAttr: function(element, name) {
+ element.removeAttribute(name);
+ },
+
+ hasClass: jqLiteHasClass,
+
+ css: function(element, name, value) {
+ name = camelCase(name);
+
+ if (isDefined(value)) {
+ element.style[name] = value;
+ } else {
+ return element.style[name];
+ }
+ },
+
+ attr: function(element, name, value) {
+ var nodeType = element.nodeType;
+ if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
+ return;
+ }
+ var lowercasedName = lowercase(name);
+ if (BOOLEAN_ATTR[lowercasedName]) {
+ if (isDefined(value)) {
+ if (!!value) {
+ element[name] = true;
+ element.setAttribute(name, lowercasedName);
+ } else {
+ element[name] = false;
+ element.removeAttribute(lowercasedName);
+ }
+ } else {
+ return (element[name] ||
+ (element.attributes.getNamedItem(name) || noop).specified)
+ ? lowercasedName
+ : undefined;
+ }
+ } else if (isDefined(value)) {
+ element.setAttribute(name, value);
+ } else if (element.getAttribute) {
+ // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
+ // some elements (e.g. Document) don't have get attribute, so return undefined
+ var ret = element.getAttribute(name, 2);
+ // normalize non-existing attributes to undefined (as jQuery)
+ return ret === null ? undefined : ret;
+ }
+ },
+
+ prop: function(element, name, value) {
+ if (isDefined(value)) {
+ element[name] = value;
+ } else {
+ return element[name];
+ }
+ },
+
+ text: (function() {
+ getText.$dv = '';
+ return getText;
+
+ function getText(element, value) {
+ if (isUndefined(value)) {
+ var nodeType = element.nodeType;
+ return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
+ }
+ element.textContent = value;
+ }
+ })(),
+
+ val: function(element, value) {
+ if (isUndefined(value)) {
+ if (element.multiple && nodeName_(element) === 'select') {
+ var result = [];
+ forEach(element.options, function(option) {
+ if (option.selected) {
+ result.push(option.value || option.text);
+ }
+ });
+ return result.length === 0 ? null : result;
+ }
+ return element.value;
+ }
+ element.value = value;
+ },
+
+ html: function(element, value) {
+ if (isUndefined(value)) {
+ return element.innerHTML;
+ }
+ jqLiteDealoc(element, true);
+ element.innerHTML = value;
+ },
+
+ empty: jqLiteEmpty
+}, function(fn, name) {
+ /**
+ * Properties: writes return selection, reads return first value
+ */
+ JQLite.prototype[name] = function(arg1, arg2) {
+ var i, key;
+ var nodeCount = this.length;
+
+ // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
+ // in a way that survives minification.
+ // jqLiteEmpty takes no arguments but is a setter.
+ if (fn !== jqLiteEmpty &&
+ (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
+ if (isObject(arg1)) {
+
+ // we are a write, but the object properties are the key/values
+ for (i = 0; i < nodeCount; i++) {
+ if (fn === jqLiteData) {
+ // data() takes the whole object in jQuery
+ fn(this[i], arg1);
+ } else {
+ for (key in arg1) {
+ fn(this[i], key, arg1[key]);
+ }
+ }
+ }
+ // return self for chaining
+ return this;
+ } else {
+ // we are a read, so read the first child.
+ // TODO: do we still need this?
+ var value = fn.$dv;
+ // Only if we have $dv do we iterate over all, otherwise it is just the first element.
+ var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
+ for (var j = 0; j < jj; j++) {
+ var nodeValue = fn(this[j], arg1, arg2);
+ value = value ? value + nodeValue : nodeValue;
+ }
+ return value;
+ }
+ } else {
+ // we are a write, so apply to all children
+ for (i = 0; i < nodeCount; i++) {
+ fn(this[i], arg1, arg2);
+ }
+ // return self for chaining
+ return this;
+ }
+ };
+});
+
+function createEventHandler(element, events) {
+ var eventHandler = function(event, type) {
+ // jQuery specific api
+ event.isDefaultPrevented = function() {
+ return event.defaultPrevented;
+ };
+
+ var eventFns = events[type || event.type];
+ var eventFnsLength = eventFns ? eventFns.length : 0;
+
+ if (!eventFnsLength) return;
+
+ if (isUndefined(event.immediatePropagationStopped)) {
+ var originalStopImmediatePropagation = event.stopImmediatePropagation;
+ event.stopImmediatePropagation = function() {
+ event.immediatePropagationStopped = true;
+
+ if (event.stopPropagation) {
+ event.stopPropagation();
+ }
+
+ if (originalStopImmediatePropagation) {
+ originalStopImmediatePropagation.call(event);
+ }
+ };
+ }
+
+ event.isImmediatePropagationStopped = function() {
+ return event.immediatePropagationStopped === true;
+ };
+
+ // Some events have special handlers that wrap the real handler
+ var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
+
+ // Copy event handlers in case event handlers array is modified during execution.
+ if ((eventFnsLength > 1)) {
+ eventFns = shallowCopy(eventFns);
+ }
+
+ for (var i = 0; i < eventFnsLength; i++) {
+ if (!event.isImmediatePropagationStopped()) {
+ handlerWrapper(element, event, eventFns[i]);
+ }
+ }
+ };
+
+ // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
+ // events on `element`
+ eventHandler.elem = element;
+ return eventHandler;
+}
+
+function defaultHandlerWrapper(element, event, handler) {
+ handler.call(element, event);
+}
+
+function specialMouseHandlerWrapper(target, event, handler) {
+ // Refer to jQuery's implementation of mouseenter & mouseleave
+ // Read about mouseenter and mouseleave:
+ // http://www.quirksmode.org/js/events_mouse.html#link8
+ var related = event.relatedTarget;
+ // For mousenter/leave call the handler if related is outside the target.
+ // NB: No relatedTarget if the mouse left/entered the browser window
+ if (!related || (related !== target && !jqLiteContains.call(target, related))) {
+ handler.call(target, event);
+ }
+}
+
+//////////////////////////////////////////
+// Functions iterating traversal.
+// These functions chain results into a single
+// selector.
+//////////////////////////////////////////
+forEach({
+ removeData: jqLiteRemoveData,
+
+ on: function jqLiteOn(element, type, fn, unsupported) {
+ if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
+
+ // Do not add event handlers to non-elements because they will not be cleaned up.
+ if (!jqLiteAcceptsData(element)) {
+ return;
+ }
+
+ var expandoStore = jqLiteExpandoStore(element, true);
+ var events = expandoStore.events;
+ var handle = expandoStore.handle;
+
+ if (!handle) {
+ handle = expandoStore.handle = createEventHandler(element, events);
+ }
+
+ // http://jsperf.com/string-indexof-vs-split
+ var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
+ var i = types.length;
+
+ var addHandler = function(type, specialHandlerWrapper, noEventListener) {
+ var eventFns = events[type];
+
+ if (!eventFns) {
+ eventFns = events[type] = [];
+ eventFns.specialHandlerWrapper = specialHandlerWrapper;
+ if (type !== '$destroy' && !noEventListener) {
+ addEventListenerFn(element, type, handle);
+ }
+ }
+
+ eventFns.push(fn);
+ };
+
+ while (i--) {
+ type = types[i];
+ if (MOUSE_EVENT_MAP[type]) {
+ addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
+ addHandler(type, undefined, true);
+ } else {
+ addHandler(type);
+ }
+ }
+ },
+
+ off: jqLiteOff,
+
+ one: function(element, type, fn) {
+ element = jqLite(element);
+
+ //add the listener twice so that when it is called
+ //you can remove the original function and still be
+ //able to call element.off(ev, fn) normally
+ element.on(type, function onFn() {
+ element.off(type, fn);
+ element.off(type, onFn);
+ });
+ element.on(type, fn);
+ },
+
+ replaceWith: function(element, replaceNode) {
+ var index, parent = element.parentNode;
+ jqLiteDealoc(element);
+ forEach(new JQLite(replaceNode), function(node) {
+ if (index) {
+ parent.insertBefore(node, index.nextSibling);
+ } else {
+ parent.replaceChild(node, element);
+ }
+ index = node;
+ });
+ },
+
+ children: function(element) {
+ var children = [];
+ forEach(element.childNodes, function(element) {
+ if (element.nodeType === NODE_TYPE_ELEMENT) {
+ children.push(element);
+ }
+ });
+ return children;
+ },
+
+ contents: function(element) {
+ return element.contentDocument || element.childNodes || [];
+ },
+
+ append: function(element, node) {
+ var nodeType = element.nodeType;
+ if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
+
+ node = new JQLite(node);
+
+ for (var i = 0, ii = node.length; i < ii; i++) {
+ var child = node[i];
+ element.appendChild(child);
+ }
+ },
+
+ prepend: function(element, node) {
+ if (element.nodeType === NODE_TYPE_ELEMENT) {
+ var index = element.firstChild;
+ forEach(new JQLite(node), function(child) {
+ element.insertBefore(child, index);
+ });
+ }
+ },
+
+ wrap: function(element, wrapNode) {
+ wrapNode = jqLite(wrapNode).eq(0).clone()[0];
+ var parent = element.parentNode;
+ if (parent) {
+ parent.replaceChild(wrapNode, element);
+ }
+ wrapNode.appendChild(element);
+ },
+
+ remove: jqLiteRemove,
+
+ detach: function(element) {
+ jqLiteRemove(element, true);
+ },
+
+ after: function(element, newElement) {
+ var index = element, parent = element.parentNode;
+ newElement = new JQLite(newElement);
+
+ for (var i = 0, ii = newElement.length; i < ii; i++) {
+ var node = newElement[i];
+ parent.insertBefore(node, index.nextSibling);
+ index = node;
+ }
+ },
+
+ addClass: jqLiteAddClass,
+ removeClass: jqLiteRemoveClass,
+
+ toggleClass: function(element, selector, condition) {
+ if (selector) {
+ forEach(selector.split(' '), function(className) {
+ var classCondition = condition;
+ if (isUndefined(classCondition)) {
+ classCondition = !jqLiteHasClass(element, className);
+ }
+ (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
+ });
+ }
+ },
+
+ parent: function(element) {
+ var parent = element.parentNode;
+ return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
+ },
+
+ next: function(element) {
+ return element.nextElementSibling;
+ },
+
+ find: function(element, selector) {
+ if (element.getElementsByTagName) {
+ return element.getElementsByTagName(selector);
+ } else {
+ return [];
+ }
+ },
+
+ clone: jqLiteClone,
+
+ triggerHandler: function(element, event, extraParameters) {
+
+ var dummyEvent, eventFnsCopy, handlerArgs;
+ var eventName = event.type || event;
+ var expandoStore = jqLiteExpandoStore(element);
+ var events = expandoStore && expandoStore.events;
+ var eventFns = events && events[eventName];
+
+ if (eventFns) {
+ // Create a dummy event to pass to the handlers
+ dummyEvent = {
+ preventDefault: function() { this.defaultPrevented = true; },
+ isDefaultPrevented: function() { return this.defaultPrevented === true; },
+ stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
+ isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
+ stopPropagation: noop,
+ type: eventName,
+ target: element
+ };
+
+ // If a custom event was provided then extend our dummy event with it
+ if (event.type) {
+ dummyEvent = extend(dummyEvent, event);
+ }
+
+ // Copy event handlers in case event handlers array is modified during execution.
+ eventFnsCopy = shallowCopy(eventFns);
+ handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
+
+ forEach(eventFnsCopy, function(fn) {
+ if (!dummyEvent.isImmediatePropagationStopped()) {
+ fn.apply(element, handlerArgs);
+ }
+ });
+ }
+ }
+}, function(fn, name) {
+ /**
+ * chaining functions
+ */
+ JQLite.prototype[name] = function(arg1, arg2, arg3) {
+ var value;
+
+ for (var i = 0, ii = this.length; i < ii; i++) {
+ if (isUndefined(value)) {
+ value = fn(this[i], arg1, arg2, arg3);
+ if (isDefined(value)) {
+ // any function which returns a value needs to be wrapped
+ value = jqLite(value);
+ }
+ } else {
+ jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
+ }
+ }
+ return isDefined(value) ? value : this;
+ };
+
+ // bind legacy bind/unbind to on/off
+ JQLite.prototype.bind = JQLite.prototype.on;
+ JQLite.prototype.unbind = JQLite.prototype.off;
+});
+
+
+// Provider for private $$jqLite service
+function $$jqLiteProvider() {
+ this.$get = function $$jqLite() {
+ return extend(JQLite, {
+ hasClass: function(node, classes) {
+ if (node.attr) node = node[0];
+ return jqLiteHasClass(node, classes);
+ },
+ addClass: function(node, classes) {
+ if (node.attr) node = node[0];
+ return jqLiteAddClass(node, classes);
+ },
+ removeClass: function(node, classes) {
+ if (node.attr) node = node[0];
+ return jqLiteRemoveClass(node, classes);
+ }
+ });
+ };
+}
+
+/**
+ * Computes a hash of an 'obj'.
+ * Hash of a:
+ * string is string
+ * number is number as string
+ * object is either result of calling $$hashKey function on the object or uniquely generated id,
+ * that is also assigned to the $$hashKey property of the object.
+ *
+ * @param obj
+ * @returns {string} hash string such that the same input will have the same hash string.
+ * The resulting string key is in 'type:hashKey' format.
+ */
+function hashKey(obj, nextUidFn) {
+ var key = obj && obj.$$hashKey;
+
+ if (key) {
+ if (typeof key === 'function') {
+ key = obj.$$hashKey();
+ }
+ return key;
+ }
+
+ var objType = typeof obj;
+ if (objType == 'function' || (objType == 'object' && obj !== null)) {
+ key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
+ } else {
+ key = objType + ':' + obj;
+ }
+
+ return key;
+}
+
+/**
+ * HashMap which can use objects as keys
+ */
+function HashMap(array, isolatedUid) {
+ if (isolatedUid) {
+ var uid = 0;
+ this.nextUid = function() {
+ return ++uid;
+ };
+ }
+ forEach(array, this.put, this);
+}
+HashMap.prototype = {
+ /**
+ * Store key value pair
+ * @param key key to store can be any type
+ * @param value value to store can be any type
+ */
+ put: function(key, value) {
+ this[hashKey(key, this.nextUid)] = value;
+ },
+
+ /**
+ * @param key
+ * @returns {Object} the value for the key
+ */
+ get: function(key) {
+ return this[hashKey(key, this.nextUid)];
+ },
+
+ /**
+ * Remove the key/value pair
+ * @param key
+ */
+ remove: function(key) {
+ var value = this[key = hashKey(key, this.nextUid)];
+ delete this[key];
+ return value;
+ }
+};
+
+var $$HashMapProvider = [function() {
+ this.$get = [function() {
+ return HashMap;
+ }];
+}];
+
+/**
+ * @ngdoc function
+ * @module ng
+ * @name angular.injector
+ * @kind function
+ *
+ * @description
+ * Creates an injector object that can be used for retrieving services as well as for
+ * dependency injection (see {@link guide/di dependency injection}).
+ *
+ * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
+ * {@link angular.module}. The `ng` module must be explicitly added.
+ * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
+ * disallows argument name annotation inference.
+ * @returns {injector} Injector object. See {@link auto.$injector $injector}.
+ *
+ * @example
+ * Typical usage
+ * ```js
+ * // create an injector
+ * var $injector = angular.injector(['ng']);
+ *
+ * // use the injector to kick off your application
+ * // use the type inference to auto inject arguments, or use implicit injection
+ * $injector.invoke(function($rootScope, $compile, $document) {
+ * $compile($document)($rootScope);
+ * $rootScope.$digest();
+ * });
+ * ```
+ *
+ * Sometimes you want to get access to the injector of a currently running Angular app
+ * from outside Angular. Perhaps, you want to inject and compile some markup after the
+ * application has been bootstrapped. You can do this using the extra `injector()` added
+ * to JQuery/jqLite elements. See {@link angular.element}.
+ *
+ * *This is fairly rare but could be the case if a third party library is injecting the
+ * markup.*
+ *
+ * In the following example a new block of HTML containing a `ng-controller`
+ * directive is added to the end of the document body by JQuery. We then compile and link
+ * it into the current AngularJS scope.
+ *
+ * ```js
+ * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
+ * $(document.body).append($div);
+ *
+ * angular.element(document).injector().invoke(function($compile) {
+ * var scope = angular.element($div).scope();
+ * $compile($div)(scope);
+ * });
+ * ```
+ */
+
+
+/**
+ * @ngdoc module
+ * @name auto
+ * @description
+ *
+ * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
+ */
+
+var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
+var FN_ARG_SPLIT = /,/;
+var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
+var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
+var $injectorMinErr = minErr('$injector');
+
+function anonFn(fn) {
+ // For anonymous functions, showing at the very least the function signature can help in
+ // debugging.
+ var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
+ args = fnText.match(FN_ARGS);
+ if (args) {
+ return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
+ }
+ return 'fn';
+}
+
+function annotate(fn, strictDi, name) {
+ var $inject,
+ fnText,
+ argDecl,
+ last;
+
+ if (typeof fn === 'function') {
+ if (!($inject = fn.$inject)) {
+ $inject = [];
+ if (fn.length) {
+ if (strictDi) {
+ if (!isString(name) || !name) {
+ name = fn.name || anonFn(fn);
+ }
+ throw $injectorMinErr('strictdi',
+ '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
+ }
+ fnText = fn.toString().replace(STRIP_COMMENTS, '');
+ argDecl = fnText.match(FN_ARGS);
+ forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
+ arg.replace(FN_ARG, function(all, underscore, name) {
+ $inject.push(name);
+ });
+ });
+ }
+ fn.$inject = $inject;
+ }
+ } else if (isArray(fn)) {
+ last = fn.length - 1;
+ assertArgFn(fn[last], 'fn');
+ $inject = fn.slice(0, last);
+ } else {
+ assertArgFn(fn, 'fn', true);
+ }
+ return $inject;
+}
+
+///////////////////////////////////////
+
+/**
+ * @ngdoc service
+ * @name $injector
+ *
+ * @description
+ *
+ * `$injector` is used to retrieve object instances as defined by
+ * {@link auto.$provide provider}, instantiate types, invoke methods,
+ * and load modules.
+ *
+ * The following always holds true:
+ *
+ * ```js
+ * var $injector = angular.injector();
+ * expect($injector.get('$injector')).toBe($injector);
+ * expect($injector.invoke(function($injector) {
+ * return $injector;
+ * })).toBe($injector);
+ * ```
+ *
+ * # Injection Function Annotation
+ *
+ * JavaScript does not have annotations, and annotations are needed for dependency injection. The
+ * following are all valid ways of annotating function with injection arguments and are equivalent.
+ *
+ * ```js
+ * // inferred (only works if code not minified/obfuscated)
+ * $injector.invoke(function(serviceA){});
+ *
+ * // annotated
+ * function explicit(serviceA) {};
+ * explicit.$inject = ['serviceA'];
+ * $injector.invoke(explicit);
+ *
+ * // inline
+ * $injector.invoke(['serviceA', function(serviceA){}]);
+ * ```
+ *
+ * ## Inference
+ *
+ * In JavaScript calling `toString()` on a function returns the function definition. The definition
+ * can then be parsed and the function arguments can be extracted. This method of discovering
+ * annotations is disallowed when the injector is in strict mode.
+ * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
+ * argument names.
+ *
+ * ## `$inject` Annotation
+ * By adding an `$inject` property onto a function the injection parameters can be specified.
+ *
+ * ## Inline
+ * As an array of injection names, where the last item in the array is the function to call.
+ */
+
+/**
+ * @ngdoc method
+ * @name $injector#get
+ *
+ * @description
+ * Return an instance of the service.
+ *
+ * @param {string} name The name of the instance to retrieve.
+ * @param {string=} caller An optional string to provide the origin of the function call for error messages.
+ * @return {*} The instance.
+ */
+
+/**
+ * @ngdoc method
+ * @name $injector#invoke
+ *
+ * @description
+ * Invoke the method and supply the method arguments from the `$injector`.
+ *
+ * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
+ * injected according to the {@link guide/di $inject Annotation} rules.
+ * @param {Object=} self The `this` for the invoked method.
+ * @param {Object=} locals Optional object. If preset then any argument names are read from this
+ * object first, before the `$injector` is consulted.
+ * @returns {*} the value returned by the invoked `fn` function.
+ */
+
+/**
+ * @ngdoc method
+ * @name $injector#has
+ *
+ * @description
+ * Allows the user to query if the particular service exists.
+ *
+ * @param {string} name Name of the service to query.
+ * @returns {boolean} `true` if injector has given service.
+ */
+
+/**
+ * @ngdoc method
+ * @name $injector#instantiate
+ * @description
+ * Create a new instance of JS type. The method takes a constructor function, invokes the new
+ * operator, and supplies all of the arguments to the constructor function as specified by the
+ * constructor annotation.
+ *
+ * @param {Function} Type Annotated constructor function.
+ * @param {Object=} locals Optional object. If preset then any argument names are read from this
+ * object first, before the `$injector` is consulted.
+ * @returns {Object} new instance of `Type`.
+ */
+
+/**
+ * @ngdoc method
+ * @name $injector#annotate
+ *
+ * @description
+ * Returns an array of service names which the function is requesting for injection. This API is
+ * used by the injector to determine which services need to be injected into the function when the
+ * function is invoked. There are three ways in which the function can be annotated with the needed
+ * dependencies.
+ *
+ * # Argument names
+ *
+ * The simplest form is to extract the dependencies from the arguments of the function. This is done
+ * by converting the function into a string using `toString()` method and extracting the argument
+ * names.
+ * ```js
+ * // Given
+ * function MyController($scope, $route) {
+ * // ...
+ * }
+ *
+ * // Then
+ * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
+ * ```
+ *
+ * You can disallow this method by using strict injection mode.
+ *
+ * This method does not work with code minification / obfuscation. For this reason the following
+ * annotation strategies are supported.
+ *
+ * # The `$inject` property
+ *
+ * If a function has an `$inject` property and its value is an array of strings, then the strings
+ * represent names of services to be injected into the function.
+ * ```js
+ * // Given
+ * var MyController = function(obfuscatedScope, obfuscatedRoute) {
+ * // ...
+ * }
+ * // Define function dependencies
+ * MyController['$inject'] = ['$scope', '$route'];
+ *
+ * // Then
+ * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
+ * ```
+ *
+ * # The array notation
+ *
+ * It is often desirable to inline Injected functions and that's when setting the `$inject` property
+ * is very inconvenient. In these situations using the array notation to specify the dependencies in
+ * a way that survives minification is a better choice:
+ *
+ * ```js
+ * // We wish to write this (not minification / obfuscation safe)
+ * injector.invoke(function($compile, $rootScope) {
+ * // ...
+ * });
+ *
+ * // We are forced to write break inlining
+ * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
+ * // ...
+ * };
+ * tmpFn.$inject = ['$compile', '$rootScope'];
+ * injector.invoke(tmpFn);
+ *
+ * // To better support inline function the inline annotation is supported
+ * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
+ * // ...
+ * }]);
+ *
+ * // Therefore
+ * expect(injector.annotate(
+ * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
+ * ).toEqual(['$compile', '$rootScope']);
+ * ```
+ *
+ * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
+ * be retrieved as described above.
+ *
+ * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
+ *
+ * @returns {Array.<string>} The names of the services which the function requires.
+ */
+
+
+
+
+/**
+ * @ngdoc service
+ * @name $provide
+ *
+ * @description
+ *
+ * The {@link auto.$provide $provide} service has a number of methods for registering components
+ * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
+ * {@link angular.Module}.
+ *
+ * An Angular **service** is a singleton object created by a **service factory**. These **service
+ * factories** are functions which, in turn, are created by a **service provider**.
+ * The **service providers** are constructor functions. When instantiated they must contain a
+ * property called `$get`, which holds the **service factory** function.
+ *
+ * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
+ * correct **service provider**, instantiating it and then calling its `$get` **service factory**
+ * function to get the instance of the **service**.
+ *
+ * Often services have no configuration options and there is no need to add methods to the service
+ * provider. The provider will be no more than a constructor function with a `$get` property. For
+ * these cases the {@link auto.$provide $provide} service has additional helper methods to register
+ * services without specifying a provider.
+ *
+ * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
+ * {@link auto.$injector $injector}
+ * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
+ * providers and services.
+ * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
+ * services, not providers.
+ * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
+ * that will be wrapped in a **service provider** object, whose `$get` property will contain the
+ * given factory function.
+ * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
+ * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
+ * a new object using the given constructor function.
+ *
+ * See the individual methods for more information and examples.
+ */
+
+/**
+ * @ngdoc method
+ * @name $provide#provider
+ * @description
+ *
+ * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
+ * are constructor functions, whose instances are responsible for "providing" a factory for a
+ * service.
+ *
+ * Service provider names start with the name of the service they provide followed by `Provider`.
+ * For example, the {@link ng.$log $log} service has a provider called
+ * {@link ng.$logProvider $logProvider}.
+ *
+ * Service provider objects can have additional methods which allow configuration of the provider
+ * and its service. Importantly, you can configure what kind of service is created by the `$get`
+ * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
+ * method {@link ng.$logProvider#debugEnabled debugEnabled}
+ * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
+ * console or not.
+ *
+ * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
+ 'Provider'` key.
+ * @param {(Object|function())} provider If the provider is:
+ *
+ * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
+ * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
+ * - `Constructor`: a new instance of the provider will be created using
+ * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
+ *
+ * @returns {Object} registered provider instance
+
+ * @example
+ *
+ * The following example shows how to create a simple event tracking service and register it using
+ * {@link auto.$provide#provider $provide.provider()}.
+ *
+ * ```js
+ * // Define the eventTracker provider
+ * function EventTrackerProvider() {
+ * var trackingUrl = '/track';
+ *
+ * // A provider method for configuring where the tracked events should been saved
+ * this.setTrackingUrl = function(url) {
+ * trackingUrl = url;
+ * };
+ *
+ * // The service factory function
+ * this.$get = ['$http', function($http) {
+ * var trackedEvents = {};
+ * return {
+ * // Call this to track an event
+ * event: function(event) {
+ * var count = trackedEvents[event] || 0;
+ * count += 1;
+ * trackedEvents[event] = count;
+ * return count;
+ * },
+ * // Call this to save the tracked events to the trackingUrl
+ * save: function() {
+ * $http.post(trackingUrl, trackedEvents);
+ * }
+ * };
+ * }];
+ * }
+ *
+ * describe('eventTracker', function() {
+ * var postSpy;
+ *
+ * beforeEach(module(function($provide) {
+ * // Register the eventTracker provider
+ * $provide.provider('eventTracker', EventTrackerProvider);
+ * }));
+ *
+ * beforeEach(module(function(eventTrackerProvider) {
+ * // Configure eventTracker provider
+ * eventTrackerProvider.setTrackingUrl('/custom-track');
+ * }));
+ *
+ * it('tracks events', inject(function(eventTracker) {
+ * expect(eventTracker.event('login')).toEqual(1);
+ * expect(eventTracker.event('login')).toEqual(2);
+ * }));
+ *
+ * it('saves to the tracking url', inject(function(eventTracker, $http) {
+ * postSpy = spyOn($http, 'post');
+ * eventTracker.event('login');
+ * eventTracker.save();
+ * expect(postSpy).toHaveBeenCalled();
+ * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
+ * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
+ * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
+ * }));
+ * });
+ * ```
+ */
+
+/**
+ * @ngdoc method
+ * @name $provide#factory
+ * @description
+ *
+ * Register a **service factory**, which will be called to return the service instance.
+ * This is short for registering a service where its provider consists of only a `$get` property,
+ * which is the given service factory function.
+ * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
+ * configure your service in a provider.
+ *
+ * @param {string} name The name of the instance.
+ * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
+ * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
+ * @returns {Object} registered provider instance
+ *
+ * @example
+ * Here is an example of registering a service
+ * ```js
+ * $provide.factory('ping', ['$http', function($http) {
+ * return function ping() {
+ * return $http.send('/ping');
+ * };
+ * }]);
+ * ```
+ * You would then inject and use this service like this:
+ * ```js
+ * someModule.controller('Ctrl', ['ping', function(ping) {
+ * ping();
+ * }]);
+ * ```
+ */
+
+
+/**
+ * @ngdoc method
+ * @name $provide#service
+ * @description
+ *
+ * Register a **service constructor**, which will be invoked with `new` to create the service
+ * instance.
+ * This is short for registering a service where its provider's `$get` property is the service
+ * constructor function that will be used to instantiate the service instance.
+ *
+ * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
+ * as a type/class.
+ *
+ * @param {string} name The name of the instance.
+ * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
+ * that will be instantiated.
+ * @returns {Object} registered provider instance
+ *
+ * @example
+ * Here is an example of registering a service using
+ * {@link auto.$provide#service $provide.service(class)}.
+ * ```js
+ * var Ping = function($http) {
+ * this.$http = $http;
+ * };
+ *
+ * Ping.$inject = ['$http'];
+ *
+ * Ping.prototype.send = function() {
+ * return this.$http.get('/ping');
+ * };
+ * $provide.service('ping', Ping);
+ * ```
+ * You would then inject and use this service like this:
+ * ```js
+ * someModule.controller('Ctrl', ['ping', function(ping) {
+ * ping.send();
+ * }]);
+ * ```
+ */
+
+
+/**
+ * @ngdoc method
+ * @name $provide#value
+ * @description
+ *
+ * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
+ * number, an array, an object or a function. This is short for registering a service where its
+ * provider's `$get` property is a factory function that takes no arguments and returns the **value
+ * service**.
+ *
+ * Value services are similar to constant services, except that they cannot be injected into a
+ * module configuration function (see {@link angular.Module#config}) but they can be overridden by
+ * an Angular
+ * {@link auto.$provide#decorator decorator}.
+ *
+ * @param {string} name The name of the instance.
+ * @param {*} value The value.
+ * @returns {Object} registered provider instance
+ *
+ * @example
+ * Here are some examples of creating value services.
+ * ```js
+ * $provide.value('ADMIN_USER', 'admin');
+ *
+ * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
+ *
+ * $provide.value('halfOf', function(value) {
+ * return value / 2;
+ * });
+ * ```
+ */
+
+
+/**
+ * @ngdoc method
+ * @name $provide#constant
+ * @description
+ *
+ * Register a **constant service**, such as a string, a number, an array, an object or a function,
+ * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
+ * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
+ * be overridden by an Angular {@link auto.$provide#decorator decorator}.
+ *
+ * @param {string} name The name of the constant.
+ * @param {*} value The constant value.
+ * @returns {Object} registered instance
+ *
+ * @example
+ * Here a some examples of creating constants:
+ * ```js
+ * $provide.constant('SHARD_HEIGHT', 306);
+ *
+ * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
+ *
+ * $provide.constant('double', function(value) {
+ * return value * 2;
+ * });
+ * ```
+ */
+
+
+/**
+ * @ngdoc method
+ * @name $provide#decorator
+ * @description
+ *
+ * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
+ * intercepts the creation of a service, allowing it to override or modify the behaviour of the
+ * service. The object returned by the decorator may be the original service, or a new service
+ * object which replaces or wraps and delegates to the original service.
+ *
+ * @param {string} name The name of the service to decorate.
+ * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
+ * instantiated and should return the decorated service instance. The function is called using
+ * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
+ * Local injection arguments:
+ *
+ * * `$delegate` - The original service instance, which can be monkey patched, configured,
+ * decorated or delegated to.
+ *
+ * @example
+ * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
+ * calls to {@link ng.$log#error $log.warn()}.
+ * ```js
+ * $provide.decorator('$log', ['$delegate', function($delegate) {
+ * $delegate.warn = $delegate.error;
+ * return $delegate;
+ * }]);
+ * ```
+ */
+
+
+function createInjector(modulesToLoad, strictDi) {
+ strictDi = (strictDi === true);
+ var INSTANTIATING = {},
+ providerSuffix = 'Provider',
+ path = [],
+ loadedModules = new HashMap([], true),
+ providerCache = {
+ $provide: {
+ provider: supportObject(provider),
+ factory: supportObject(factory),
+ service: supportObject(service),
+ value: supportObject(value),
+ constant: supportObject(constant),
+ decorator: decorator
+ }
+ },
+ providerInjector = (providerCache.$injector =
+ createInternalInjector(providerCache, function(serviceName, caller) {
+ if (angular.isString(caller)) {
+ path.push(caller);
+ }
+ throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
+ })),
+ instanceCache = {},
+ instanceInjector = (instanceCache.$injector =
+ createInternalInjector(instanceCache, function(serviceName, caller) {
+ var provider = providerInjector.get(serviceName + providerSuffix, caller);
+ return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
+ }));
+
+
+ forEach(loadModules(modulesToLoad), function(fn) { if (fn) instanceInjector.invoke(fn); });
+
+ return instanceInjector;
+
+ ////////////////////////////////////
+ // $provider
+ ////////////////////////////////////
+
+ function supportObject(delegate) {
+ return function(key, value) {
+ if (isObject(key)) {
+ forEach(key, reverseParams(delegate));
+ } else {
+ return delegate(key, value);
+ }
+ };
+ }
+
+ function provider(name, provider_) {
+ assertNotHasOwnProperty(name, 'service');
+ if (isFunction(provider_) || isArray(provider_)) {
+ provider_ = providerInjector.instantiate(provider_);
+ }
+ if (!provider_.$get) {
+ throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
+ }
+ return providerCache[name + providerSuffix] = provider_;
+ }
+
+ function enforceReturnValue(name, factory) {
+ return function enforcedReturnValue() {
+ var result = instanceInjector.invoke(factory, this);
+ if (isUndefined(result)) {
+ throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
+ }
+ return result;
+ };
+ }
+
+ function factory(name, factoryFn, enforce) {
+ return provider(name, {
+ $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
+ });
+ }
+
+ function service(name, constructor) {
+ return factory(name, ['$injector', function($injector) {
+ return $injector.instantiate(constructor);
+ }]);
+ }
+
+ function value(name, val) { return factory(name, valueFn(val), false); }
+
+ function constant(name, value) {
+ assertNotHasOwnProperty(name, 'constant');
+ providerCache[name] = value;
+ instanceCache[name] = value;
+ }
+
+ function decorator(serviceName, decorFn) {
+ var origProvider = providerInjector.get(serviceName + providerSuffix),
+ orig$get = origProvider.$get;
+
+ origProvider.$get = function() {
+ var origInstance = instanceInjector.invoke(orig$get, origProvider);
+ return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
+ };
+ }
+
+ ////////////////////////////////////
+ // Module Loading
+ ////////////////////////////////////
+ function loadModules(modulesToLoad) {
+ assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
+ var runBlocks = [], moduleFn;
+ forEach(modulesToLoad, function(module) {
+ if (loadedModules.get(module)) return;
+ loadedModules.put(module, true);
+
+ function runInvokeQueue(queue) {
+ var i, ii;
+ for (i = 0, ii = queue.length; i < ii; i++) {
+ var invokeArgs = queue[i],
+ provider = providerInjector.get(invokeArgs[0]);
+
+ provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
+ }
+ }
+
+ try {
+ if (isString(module)) {
+ moduleFn = angularModule(module);
+ runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
+ runInvokeQueue(moduleFn._invokeQueue);
+ runInvokeQueue(moduleFn._configBlocks);
+ } else if (isFunction(module)) {
+ runBlocks.push(providerInjector.invoke(module));
+ } else if (isArray(module)) {
+ runBlocks.push(providerInjector.invoke(module));
+ } else {
+ assertArgFn(module, 'module');
+ }
+ } catch (e) {
+ if (isArray(module)) {
+ module = module[module.length - 1];
+ }
+ if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
+ // Safari & FF's stack traces don't contain error.message content
+ // unlike those of Chrome and IE
+ // So if stack doesn't contain message, we create a new string that contains both.
+ // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
+ /* jshint -W022 */
+ e = e.message + '\n' + e.stack;
+ }
+ throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
+ module, e.stack || e.message || e);
+ }
+ });
+ return runBlocks;
+ }
+
+ ////////////////////////////////////
+ // internal Injector
+ ////////////////////////////////////
+
+ function createInternalInjector(cache, factory) {
+
+ function getService(serviceName, caller) {
+ if (cache.hasOwnProperty(serviceName)) {
+ if (cache[serviceName] === INSTANTIATING) {
+ throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
+ serviceName + ' <- ' + path.join(' <- '));
+ }
+ return cache[serviceName];
+ } else {
+ try {
+ path.unshift(serviceName);
+ cache[serviceName] = INSTANTIATING;
+ return cache[serviceName] = factory(serviceName, caller);
+ } catch (err) {
+ if (cache[serviceName] === INSTANTIATING) {
+ delete cache[serviceName];
+ }
+ throw err;
+ } finally {
+ path.shift();
+ }
+ }
+ }
+
+ function invoke(fn, self, locals, serviceName) {
+ if (typeof locals === 'string') {
+ serviceName = locals;
+ locals = null;
+ }
+
+ var args = [],
+ $inject = createInjector.$$annotate(fn, strictDi, serviceName),
+ length, i,
+ key;
+
+ for (i = 0, length = $inject.length; i < length; i++) {
+ key = $inject[i];
+ if (typeof key !== 'string') {
+ throw $injectorMinErr('itkn',
+ 'Incorrect injection token! Expected service name as string, got {0}', key);
+ }
+ args.push(
+ locals && locals.hasOwnProperty(key)
+ ? locals[key]
+ : getService(key, serviceName)
+ );
+ }
+ if (isArray(fn)) {
+ fn = fn[length];
+ }
+
+ // http://jsperf.com/angularjs-invoke-apply-vs-switch
+ // #5388
+ return fn.apply(self, args);
+ }
+
+ function instantiate(Type, locals, serviceName) {
+ // Check if Type is annotated and use just the given function at n-1 as parameter
+ // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
+ // Object creation: http://jsperf.com/create-constructor/2
+ var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
+ var returnedValue = invoke(Type, instance, locals, serviceName);
+
+ return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
+ }
+
+ return {
+ invoke: invoke,
+ instantiate: instantiate,
+ get: getService,
+ annotate: createInjector.$$annotate,
+ has: function(name) {
+ return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
+ }
+ };
+ }
+}
+
+createInjector.$$annotate = annotate;
+
+/**
+ * @ngdoc provider
+ * @name $anchorScrollProvider
+ *
+ * @description
+ * Use `$anchorScrollProvider` to disable automatic scrolling whenever
+ * {@link ng.$location#hash $location.hash()} changes.
+ */
+function $AnchorScrollProvider() {
+
+ var autoScrollingEnabled = true;
+
+ /**
+ * @ngdoc method
+ * @name $anchorScrollProvider#disableAutoScrolling
+ *
+ * @description
+ * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
+ * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
+ * Use this method to disable automatic scrolling.
+ *
+ * If automatic scrolling is disabled, one must explicitly call
+ * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
+ * current hash.
+ */
+ this.disableAutoScrolling = function() {
+ autoScrollingEnabled = false;
+ };
+
+ /**
+ * @ngdoc service
+ * @name $anchorScroll
+ * @kind function
+ * @requires $window
+ * @requires $location
+ * @requires $rootScope
+ *
+ * @description
+ * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
+ * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
+ * in the
+ * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#the-indicated-part-of-the-document).
+ *
+ * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
+ * match any anchor whenever it changes. This can be disabled by calling
+ * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
+ *
+ * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
+ * vertical scroll-offset (either fixed or dynamic).
+ *
+ * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
+ * {@link ng.$location#hash $location.hash()} will be used.
+ *
+ * @property {(number|function|jqLite)} yOffset
+ * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
+ * positioned elements at the top of the page, such as navbars, headers etc.
+ *
+ * `yOffset` can be specified in various ways:
+ * - **number**: A fixed number of pixels to be used as offset.<br /><br />
+ * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
+ * a number representing the offset (in pixels).<br /><br />
+ * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
+ * the top of the page to the element's bottom will be used as offset.<br />
+ * **Note**: The element will be taken into account only as long as its `position` is set to
+ * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
+ * their height and/or positioning according to the viewport's size.
+ *
+ * <br />
+ * <div class="alert alert-warning">
+ * In order for `yOffset` to work properly, scrolling should take place on the document's root and
+ * not some child element.
+ * </div>
+ *
+ * @example
+ <example module="anchorScrollExample">
+ <file name="index.html">
+ <div id="scrollArea" ng-controller="ScrollController">
+ <a ng-click="gotoBottom()">Go to bottom</a>
+ <a id="bottom"></a> You're at the bottom!
+ </div>
+ </file>
+ <file name="script.js">
+ angular.module('anchorScrollExample', [])
+ .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
+ function ($scope, $location, $anchorScroll) {
+ $scope.gotoBottom = function() {
+ // set the location.hash to the id of
+ // the element you wish to scroll to.
+ $location.hash('bottom');
+
+ // call $anchorScroll()
+ $anchorScroll();
+ };
+ }]);
+ </file>
+ <file name="style.css">
+ #scrollArea {
+ height: 280px;
+ overflow: auto;
+ }
+
+ #bottom {
+ display: block;
+ margin-top: 2000px;
+ }
+ </file>
+ </example>
+ *
+ * <hr />
+ * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
+ * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
+ *
+ * @example
+ <example module="anchorScrollOffsetExample">
+ <file name="index.html">
+ <div class="fixed-header" ng-controller="headerCtrl">
+ <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
+ Go to anchor {{x}}
+ </a>
+ </div>
+ <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
+ Anchor {{x}} of 5
+ </div>
+ </file>
+ <file name="script.js">
+ angular.module('anchorScrollOffsetExample', [])
+ .run(['$anchorScroll', function($anchorScroll) {
+ $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
+ }])
+ .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
+ function ($anchorScroll, $location, $scope) {
+ $scope.gotoAnchor = function(x) {
+ var newHash = 'anchor' + x;
+ if ($location.hash() !== newHash) {
+ // set the $location.hash to `newHash` and
+ // $anchorScroll will automatically scroll to it
+ $location.hash('anchor' + x);
+ } else {
+ // call $anchorScroll() explicitly,
+ // since $location.hash hasn't changed
+ $anchorScroll();
+ }
+ };
+ }
+ ]);
+ </file>
+ <file name="style.css">
+ body {
+ padding-top: 50px;
+ }
+
+ .anchor {
+ border: 2px dashed DarkOrchid;
+ padding: 10px 10px 200px 10px;
+ }
+
+ .fixed-header {
+ background-color: rgba(0, 0, 0, 0.2);
+ height: 50px;
+ position: fixed;
+ top: 0; left: 0; right: 0;
+ }
+
+ .fixed-header > a {
+ display: inline-block;
+ margin: 5px 15px;
+ }
+ </file>
+ </example>
+ */
+ this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
+ var document = $window.document;
+
+ // Helper function to get first anchor from a NodeList
+ // (using `Array#some()` instead of `angular#forEach()` since it's more performant
+ // and working in all supported browsers.)
+ function getFirstAnchor(list) {
+ var result = null;
+ Array.prototype.some.call(list, function(element) {
+ if (nodeName_(element) === 'a') {
+ result = element;
+ return true;
+ }
+ });
+ return result;
+ }
+
+ function getYOffset() {
+
+ var offset = scroll.yOffset;
+
+ if (isFunction(offset)) {
+ offset = offset();
+ } else if (isElement(offset)) {
+ var elem = offset[0];
+ var style = $window.getComputedStyle(elem);
+ if (style.position !== 'fixed') {
+ offset = 0;
+ } else {
+ offset = elem.getBoundingClientRect().bottom;
+ }
+ } else if (!isNumber(offset)) {
+ offset = 0;
+ }
+
+ return offset;
+ }
+
+ function scrollTo(elem) {
+ if (elem) {
+ elem.scrollIntoView();
+
+ var offset = getYOffset();
+
+ if (offset) {
+ // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
+ // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
+ // top of the viewport.
+ //
+ // IF the number of pixels from the top of `elem` to the end of the page's content is less
+ // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
+ // way down the page.
+ //
+ // This is often the case for elements near the bottom of the page.
+ //
+ // In such cases we do not need to scroll the whole `offset` up, just the difference between
+ // the top of the element and the offset, which is enough to align the top of `elem` at the
+ // desired position.
+ var elemTop = elem.getBoundingClientRect().top;
+ $window.scrollBy(0, elemTop - offset);
+ }
+ } else {
+ $window.scrollTo(0, 0);
+ }
+ }
+
+ function scroll(hash) {
+ hash = isString(hash) ? hash : $location.hash();
+ var elm;
+
+ // empty hash, scroll to the top of the page
+ if (!hash) scrollTo(null);
+
+ // element with given id
+ else if ((elm = document.getElementById(hash))) scrollTo(elm);
+
+ // first anchor with given name :-D
+ else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
+
+ // no element and hash == 'top', scroll to the top of the page
+ else if (hash === 'top') scrollTo(null);
+ }
+
+ // does not scroll when user clicks on anchor link that is currently on
+ // (no url change, no $location.hash() change), browser native does scroll
+ if (autoScrollingEnabled) {
+ $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
+ function autoScrollWatchAction(newVal, oldVal) {
+ // skip the initial scroll if $location.hash is empty
+ if (newVal === oldVal && newVal === '') return;
+
+ jqLiteDocumentLoaded(function() {
+ $rootScope.$evalAsync(scroll);
+ });
+ });
+ }
+
+ return scroll;
+ }];
+}
+
+var $animateMinErr = minErr('$animate');
+var ELEMENT_NODE = 1;
+var NG_ANIMATE_CLASSNAME = 'ng-animate';
+
+function mergeClasses(a,b) {
+ if (!a && !b) return '';
+ if (!a) return b;
+ if (!b) return a;
+ if (isArray(a)) a = a.join(' ');
+ if (isArray(b)) b = b.join(' ');
+ return a + ' ' + b;
+}
+
+function extractElementNode(element) {
+ for (var i = 0; i < element.length; i++) {
+ var elm = element[i];
+ if (elm.nodeType === ELEMENT_NODE) {
+ return elm;
+ }
+ }
+}
+
+function splitClasses(classes) {
+ if (isString(classes)) {
+ classes = classes.split(' ');
+ }
+
+ // Use createMap() to prevent class assumptions involving property names in
+ // Object.prototype
+ var obj = createMap();
+ forEach(classes, function(klass) {
+ // sometimes the split leaves empty string values
+ // incase extra spaces were applied to the options
+ if (klass.length) {
+ obj[klass] = true;
+ }
+ });
+ return obj;
+}
+
+// if any other type of options value besides an Object value is
+// passed into the $animate.method() animation then this helper code
+// will be run which will ignore it. While this patch is not the
+// greatest solution to this, a lot of existing plugins depend on
+// $animate to either call the callback (< 1.2) or return a promise
+// that can be changed. This helper function ensures that the options
+// are wiped clean incase a callback function is provided.
+function prepareAnimateOptions(options) {
+ return isObject(options)
+ ? options
+ : {};
+}
+
+var $$CoreAnimateRunnerProvider = function() {
+ this.$get = ['$q', '$$rAF', function($q, $$rAF) {
+ function AnimateRunner() {}
+ AnimateRunner.all = noop;
+ AnimateRunner.chain = noop;
+ AnimateRunner.prototype = {
+ end: noop,
+ cancel: noop,
+ resume: noop,
+ pause: noop,
+ complete: noop,
+ then: function(pass, fail) {
+ return $q(function(resolve) {
+ $$rAF(function() {
+ resolve();
+ });
+ }).then(pass, fail);
+ }
+ };
+ return AnimateRunner;
+ }];
+};
+
+// this is prefixed with Core since it conflicts with
+// the animateQueueProvider defined in ngAnimate/animateQueue.js
+var $$CoreAnimateQueueProvider = function() {
+ var postDigestQueue = new HashMap();
+ var postDigestElements = [];
+
+ this.$get = ['$$AnimateRunner', '$rootScope',
+ function($$AnimateRunner, $rootScope) {
+ return {
+ enabled: noop,
+ on: noop,
+ off: noop,
+ pin: noop,
+
+ push: function(element, event, options, domOperation) {
+ domOperation && domOperation();
+
+ options = options || {};
+ options.from && element.css(options.from);
+ options.to && element.css(options.to);
+
+ if (options.addClass || options.removeClass) {
+ addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
+ }
+
+ return new $$AnimateRunner(); // jshint ignore:line
+ }
+ };
+
+
+ function updateData(data, classes, value) {
+ var changed = false;
+ if (classes) {
+ classes = isString(classes) ? classes.split(' ') :
+ isArray(classes) ? classes : [];
+ forEach(classes, function(className) {
+ if (className) {
+ changed = true;
+ data[className] = value;
+ }
+ });
+ }
+ return changed;
+ }
+
+ function handleCSSClassChanges() {
+ forEach(postDigestElements, function(element) {
+ var data = postDigestQueue.get(element);
+ if (data) {
+ var existing = splitClasses(element.attr('class'));
+ var toAdd = '';
+ var toRemove = '';
+ forEach(data, function(status, className) {
+ var hasClass = !!existing[className];
+ if (status !== hasClass) {
+ if (status) {
+ toAdd += (toAdd.length ? ' ' : '') + className;
+ } else {
+ toRemove += (toRemove.length ? ' ' : '') + className;
+ }
+ }
+ });
+
+ forEach(element, function(elm) {
+ toAdd && jqLiteAddClass(elm, toAdd);
+ toRemove && jqLiteRemoveClass(elm, toRemove);
+ });
+ postDigestQueue.remove(element);
+ }
+ });
+ postDigestElements.length = 0;
+ }
+
+
+ function addRemoveClassesPostDigest(element, add, remove) {
+ var data = postDigestQueue.get(element) || {};
+
+ var classesAdded = updateData(data, add, true);
+ var classesRemoved = updateData(data, remove, false);
+
+ if (classesAdded || classesRemoved) {
+
+ postDigestQueue.put(element, data);
+ postDigestElements.push(element);
+
+ if (postDigestElements.length === 1) {
+ $rootScope.$$postDigest(handleCSSClassChanges);
+ }
+ }
+ }
+ }];
+};
+
+/**
+ * @ngdoc provider
+ * @name $animateProvider
+ *
+ * @description
+ * Default implementation of $animate that doesn't perform any animations, instead just
+ * synchronously performs DOM updates and resolves the returned runner promise.
+ *
+ * In order to enable animations the `ngAnimate` module has to be loaded.
+ *
+ * To see the functional implementation check out `src/ngAnimate/animate.js`.
+ */
+var $AnimateProvider = ['$provide', function($provide) {
+ var provider = this;
+
+ this.$$registeredAnimations = Object.create(null);
+
+ /**
+ * @ngdoc method
+ * @name $animateProvider#register
+ *
+ * @description
+ * Registers a new injectable animation factory function. The factory function produces the
+ * animation object which contains callback functions for each event that is expected to be
+ * animated.
+ *
+ * * `eventFn`: `function(element, ... , doneFunction, options)`
+ * The element to animate, the `doneFunction` and the options fed into the animation. Depending
+ * on the type of animation additional arguments will be injected into the animation function. The
+ * list below explains the function signatures for the different animation methods:
+ *
+ * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
+ * - addClass: function(element, addedClasses, doneFunction, options)
+ * - removeClass: function(element, removedClasses, doneFunction, options)
+ * - enter, leave, move: function(element, doneFunction, options)
+ * - animate: function(element, fromStyles, toStyles, doneFunction, options)
+ *
+ * Make sure to trigger the `doneFunction` once the animation is fully complete.
+ *
+ * ```js
+ * return {
+ * //enter, leave, move signature
+ * eventFn : function(element, done, options) {
+ * //code to run the animation
+ * //once complete, then run done()
+ * return function endFunction(wasCancelled) {
+ * //code to cancel the animation
+ * }
+ * }
+ * }
+ * ```
+ *
+ * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
+ * @param {Function} factory The factory function that will be executed to return the animation
+ * object.
+ */
+ this.register = function(name, factory) {
+ if (name && name.charAt(0) !== '.') {
+ throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
+ }
+
+ var key = name + '-animation';
+ provider.$$registeredAnimations[name.substr(1)] = key;
+ $provide.factory(key, factory);
+ };
+
+ /**
+ * @ngdoc method
+ * @name $animateProvider#classNameFilter
+ *
+ * @description
+ * Sets and/or returns the CSS class regular expression that is checked when performing
+ * an animation. Upon bootstrap the classNameFilter value is not set at all and will
+ * therefore enable $animate to attempt to perform an animation on any element that is triggered.
+ * When setting the `classNameFilter` value, animations will only be performed on elements
+ * that successfully match the filter expression. This in turn can boost performance
+ * for low-powered devices as well as applications containing a lot of structural operations.
+ * @param {RegExp=} expression The className expression which will be checked against all animations
+ * @return {RegExp} The current CSS className expression value. If null then there is no expression value
+ */
+ this.classNameFilter = function(expression) {
+ if (arguments.length === 1) {
+ this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
+ if (this.$$classNameFilter) {
+ var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
+ if (reservedRegex.test(this.$$classNameFilter.toString())) {
+ throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
+
+ }
+ }
+ }
+ return this.$$classNameFilter;
+ };
+
+ this.$get = ['$$animateQueue', function($$animateQueue) {
+ function domInsert(element, parentElement, afterElement) {
+ // if for some reason the previous element was removed
+ // from the dom sometime before this code runs then let's
+ // just stick to using the parent element as the anchor
+ if (afterElement) {
+ var afterNode = extractElementNode(afterElement);
+ if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
+ afterElement = null;
+ }
+ }
+ afterElement ? afterElement.after(element) : parentElement.prepend(element);
+ }
+
+ /**
+ * @ngdoc service
+ * @name $animate
+ * @description The $animate service exposes a series of DOM utility methods that provide support
+ * for animation hooks. The default behavior is the application of DOM operations, however,
+ * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
+ * to ensure that animation runs with the triggered DOM operation.
+ *
+ * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
+ * included and only when it is active then the animation hooks that `$animate` triggers will be
+ * functional. Once active then all structural `ng-` directives will trigger animations as they perform
+ * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
+ * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
+ *
+ * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
+ *
+ * To learn more about enabling animation support, click here to visit the
+ * {@link ngAnimate ngAnimate module page}.
+ */
+ return {
+ // we don't call it directly since non-existant arguments may
+ // be interpreted as null within the sub enabled function
+
+ /**
+ *
+ * @ngdoc method
+ * @name $animate#on
+ * @kind function
+ * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
+ * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
+ * is fired with the following params:
+ *
+ * ```js
+ * $animate.on('enter', container,
+ * function callback(element, phase) {
+ * // cool we detected an enter animation within the container
+ * }
+ * );
+ * ```
+ *
+ * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
+ * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
+ * as well as among its children
+ * @param {Function} callback the callback function that will be fired when the listener is triggered
+ *
+ * The arguments present in the callback function are:
+ * * `element` - The captured DOM element that the animation was fired on.
+ * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
+ */
+ on: $$animateQueue.on,
+
+ /**
+ *
+ * @ngdoc method
+ * @name $animate#off
+ * @kind function
+ * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
+ * can be used in three different ways depending on the arguments:
+ *
+ * ```js
+ * // remove all the animation event listeners listening for `enter`
+ * $animate.off('enter');
+ *
+ * // remove all the animation event listeners listening for `enter` on the given element and its children
+ * $animate.off('enter', container);
+ *
+ * // remove the event listener function provided by `listenerFn` that is set
+ * // to listen for `enter` on the given `element` as well as its children
+ * $animate.off('enter', container, callback);
+ * ```
+ *
+ * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
+ * @param {DOMElement=} container the container element the event listener was placed on
+ * @param {Function=} callback the callback function that was registered as the listener
+ */
+ off: $$animateQueue.off,
+
+ /**
+ * @ngdoc method
+ * @name $animate#pin
+ * @kind function
+ * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
+ * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
+ * element despite being outside the realm of the application or within another application. Say for example if the application
+ * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
+ * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
+ * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
+ *
+ * Note that this feature is only active when the `ngAnimate` module is used.
+ *
+ * @param {DOMElement} element the external element that will be pinned
+ * @param {DOMElement} parentElement the host parent element that will be associated with the external element
+ */
+ pin: $$animateQueue.pin,
+
+ /**
+ *
+ * @ngdoc method
+ * @name $animate#enabled
+ * @kind function
+ * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
+ * function can be called in four ways:
+ *
+ * ```js
+ * // returns true or false
+ * $animate.enabled();
+ *
+ * // changes the enabled state for all animations
+ * $animate.enabled(false);
+ * $animate.enabled(true);
+ *
+ * // returns true or false if animations are enabled for an element
+ * $animate.enabled(element);
+ *
+ * // changes the enabled state for an element and its children
+ * $animate.enabled(element, true);
+ * $animate.enabled(element, false);
+ * ```
+ *
+ * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
+ * @param {boolean=} enabled whether or not the animations will be enabled for the element
+ *
+ * @return {boolean} whether or not animations are enabled
+ */
+ enabled: $$animateQueue.enabled,
+
+ /**
+ * @ngdoc method
+ * @name $animate#cancel
+ * @kind function
+ * @description Cancels the provided animation.
+ *
+ * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
+ */
+ cancel: function(runner) {
+ runner.end && runner.end();
+ },
+
+ /**
+ *
+ * @ngdoc method
+ * @name $animate#enter
+ * @kind function
+ * @description Inserts the element into the DOM either after the `after` element (if provided) or
+ * as the first child within the `parent` element and then triggers an animation.
+ * A promise is returned that will be resolved during the next digest once the animation
+ * has completed.
+ *
+ * @param {DOMElement} element the element which will be inserted into the DOM
+ * @param {DOMElement} parent the parent element which will append the element as
+ * a child (so long as the after element is not present)
+ * @param {DOMElement=} after the sibling element after which the element will be appended
+ * @param {object=} options an optional collection of options/styles that will be applied to the element
+ *
+ * @return {Promise} the animation callback promise
+ */
+ enter: function(element, parent, after, options) {
+ parent = parent && jqLite(parent);
+ after = after && jqLite(after);
+ parent = parent || after.parent();
+ domInsert(element, parent, after);
+ return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
+ },
+
+ /**
+ *
+ * @ngdoc method
+ * @name $animate#move
+ * @kind function
+ * @description Inserts (moves) the element into its new position in the DOM either after
+ * the `after` element (if provided) or as the first child within the `parent` element
+ * and then triggers an animation. A promise is returned that will be resolved
+ * during the next digest once the animation has completed.
+ *
+ * @param {DOMElement} element the element which will be moved into the new DOM position
+ * @param {DOMElement} parent the parent element which will append the element as
+ * a child (so long as the after element is not present)
+ * @param {DOMElement=} after the sibling element after which the element will be appended
+ * @param {object=} options an optional collection of options/styles that will be applied to the element
+ *
+ * @return {Promise} the animation callback promise
+ */
+ move: function(element, parent, after, options) {
+ parent = parent && jqLite(parent);
+ after = after && jqLite(after);
+ parent = parent || after.parent();
+ domInsert(element, parent, after);
+ return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
+ },
+
+ /**
+ * @ngdoc method
+ * @name $animate#leave
+ * @kind function
+ * @description Triggers an animation and then removes the element from the DOM.
+ * When the function is called a promise is returned that will be resolved during the next
+ * digest once the animation has completed.
+ *
+ * @param {DOMElement} element the element which will be removed from the DOM
+ * @param {object=} options an optional collection of options/styles that will be applied to the element
+ *
+ * @return {Promise} the animation callback promise
+ */
+ leave: function(element, options) {
+ return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
+ element.remove();
+ });
+ },
+
+ /**
+ * @ngdoc method
+ * @name $animate#addClass
+ * @kind function
+ *
+ * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
+ * execution, the addClass operation will only be handled after the next digest and it will not trigger an
+ * animation if element already contains the CSS class or if the class is removed at a later step.
+ * Note that class-based animations are treated differently compared to structural animations
+ * (like enter, move and leave) since the CSS classes may be added/removed at different points
+ * depending if CSS or JavaScript animations are used.
+ *
+ * @param {DOMElement} element the element which the CSS classes will be applied to
+ * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
+ * @param {object=} options an optional collection of options/styles that will be applied to the element
+ *
+ * @return {Promise} the animation callback promise
+ */
+ addClass: function(element, className, options) {
+ options = prepareAnimateOptions(options);
+ options.addClass = mergeClasses(options.addclass, className);
+ return $$animateQueue.push(element, 'addClass', options);
+ },
+
+ /**
+ * @ngdoc method
+ * @name $animate#removeClass
+ * @kind function
+ *
+ * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
+ * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
+ * animation if element does not contain the CSS class or if the class is added at a later step.
+ * Note that class-based animations are treated differently compared to structural animations
+ * (like enter, move and leave) since the CSS classes may be added/removed at different points
+ * depending if CSS or JavaScript animations are used.
+ *
+ * @param {DOMElement} element the element which the CSS classes will be applied to
+ * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
+ * @param {object=} options an optional collection of options/styles that will be applied to the element
+ *
+ * @return {Promise} the animation callback promise
+ */
+ removeClass: function(element, className, options) {
+ options = prepareAnimateOptions(options);
+ options.removeClass = mergeClasses(options.removeClass, className);
+ return $$animateQueue.push(element, 'removeClass', options);
+ },
+
+ /**
+ * @ngdoc method
+ * @name $animate#setClass
+ * @kind function
+ *
+ * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
+ * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
+ * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
+ * passed. Note that class-based animations are treated differently compared to structural animations
+ * (like enter, move and leave) since the CSS classes may be added/removed at different points
+ * depending if CSS or JavaScript animations are used.
+ *
+ * @param {DOMElement} element the element which the CSS classes will be applied to
+ * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
+ * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
+ * @param {object=} options an optional collection of options/styles that will be applied to the element
+ *
+ * @return {Promise} the animation callback promise
+ */
+ setClass: function(element, add, remove, options) {
+ options = prepareAnimateOptions(options);
+ options.addClass = mergeClasses(options.addClass, add);
+ options.removeClass = mergeClasses(options.removeClass, remove);
+ return $$animateQueue.push(element, 'setClass', options);
+ },
+
+ /**
+ * @ngdoc method
+ * @name $animate#animate
+ * @kind function
+ *
+ * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
+ * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
+ * on the provided styles. For example, if a transition animation is set for the given className then the provided from and
+ * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
+ * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
+ *
+ * @param {DOMElement} element the element which the CSS styles will be applied to
+ * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
+ * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
+ * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
+ * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
+ * (Note that if no animation is detected then this value will not be appplied to the element.)
+ * @param {object=} options an optional collection of options/styles that will be applied to the element
+ *
+ * @return {Promise} the animation callback promise
+ */
+ animate: function(element, from, to, className, options) {
+ options = prepareAnimateOptions(options);
+ options.from = options.from ? extend(options.from, from) : from;
+ options.to = options.to ? extend(options.to, to) : to;
+
+ className = className || 'ng-inline-animate';
+ options.tempClasses = mergeClasses(options.tempClasses, className);
+ return $$animateQueue.push(element, 'animate', options);
+ }
+ };
+ }];
+}];
+
+/**
+ * @ngdoc service
+ * @name $animateCss
+ * @kind object
+ *
+ * @description
+ * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
+ * then the `$animateCss` service will actually perform animations.
+ *
+ * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
+ */
+var $CoreAnimateCssProvider = function() {
+ this.$get = ['$$rAF', '$q', function($$rAF, $q) {
+
+ var RAFPromise = function() {};
+ RAFPromise.prototype = {
+ done: function(cancel) {
+ this.defer && this.defer[cancel === true ? 'reject' : 'resolve']();
+ },
+ end: function() {
+ this.done();
+ },
+ cancel: function() {
+ this.done(true);
+ },
+ getPromise: function() {
+ if (!this.defer) {
+ this.defer = $q.defer();
+ }
+ return this.defer.promise;
+ },
+ then: function(f1,f2) {
+ return this.getPromise().then(f1,f2);
+ },
+ 'catch': function(f1) {
+ return this.getPromise()['catch'](f1);
+ },
+ 'finally': function(f1) {
+ return this.getPromise()['finally'](f1);
+ }
+ };
+
+ return function(element, options) {
+ // there is no point in applying the styles since
+ // there is no animation that goes on at all in
+ // this version of $animateCss.
+ if (options.cleanupStyles) {
+ options.from = options.to = null;
+ }
+
+ if (options.from) {
+ element.css(options.from);
+ options.from = null;
+ }
+
+ var closed, runner = new RAFPromise();
+ return {
+ start: run,
+ end: run
+ };
+
+ function run() {
+ $$rAF(function() {
+ close();
+ if (!closed) {
+ runner.done();
+ }
+ closed = true;
+ });
+ return runner;
+ }
+
+ function close() {
+ if (options.addClass) {
+ element.addClass(options.addClass);
+ options.addClass = null;
+ }
+ if (options.removeClass) {
+ element.removeClass(options.removeClass);
+ options.removeClass = null;
+ }
+ if (options.to) {
+ element.css(options.to);
+ options.to = null;
+ }
+ }
+ };
+ }];
+};
+
+/* global stripHash: true */
+
+/**
+ * ! This is a private undocumented service !
+ *
+ * @name $browser
+ * @requires $log
+ * @description
+ * This object has two goals:
+ *
+ * - hide all the global state in the browser caused by the window object
+ * - abstract away all the browser specific features and inconsistencies
+ *
+ * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
+ * service, which can be used for convenient testing of the application without the interaction with
+ * the real browser apis.
+ */
+/**
+ * @param {object} window The global window object.
+ * @param {object} document jQuery wrapped document.
+ * @param {object} $log window.console or an object with the same interface.
+ * @param {object} $sniffer $sniffer service
+ */
+function Browser(window, document, $log, $sniffer) {
+ var self = this,
+ rawDocument = document[0],
+ location = window.location,
+ history = window.history,
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ pendingDeferIds = {};
+
+ self.isMock = false;
+
+ var outstandingRequestCount = 0;
+ var outstandingRequestCallbacks = [];
+
+ // TODO(vojta): remove this temporary api
+ self.$$completeOutstandingRequest = completeOutstandingRequest;
+ self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
+
+ /**
+ * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
+ * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
+ */
+ function completeOutstandingRequest(fn) {
+ try {
+ fn.apply(null, sliceArgs(arguments, 1));
+ } finally {
+ outstandingRequestCount--;
+ if (outstandingRequestCount === 0) {
+ while (outstandingRequestCallbacks.length) {
+ try {
+ outstandingRequestCallbacks.pop()();
+ } catch (e) {
+ $log.error(e);
+ }
+ }
+ }
+ }
+ }
+
+ function getHash(url) {
+ var index = url.indexOf('#');
+ return index === -1 ? '' : url.substr(index);
+ }
+
+ /**
+ * @private
+ * Note: this method is used only by scenario runner
+ * TODO(vojta): prefix this method with $$ ?
+ * @param {function()} callback Function that will be called when no outstanding request
+ */
+ self.notifyWhenNoOutstandingRequests = function(callback) {
+ if (outstandingRequestCount === 0) {
+ callback();
+ } else {
+ outstandingRequestCallbacks.push(callback);
+ }
+ };
+
+ //////////////////////////////////////////////////////////////
+ // URL API
+ //////////////////////////////////////////////////////////////
+
+ var cachedState, lastHistoryState,
+ lastBrowserUrl = location.href,
+ baseElement = document.find('base'),
+ pendingLocation = null;
+
+ cacheState();
+ lastHistoryState = cachedState;
+
+ /**
+ * @name $browser#url
+ *
+ * @description
+ * GETTER:
+ * Without any argument, this method just returns current value of location.href.
+ *
+ * SETTER:
+ * With at least one argument, this method sets url to new value.
+ * If html5 history api supported, pushState/replaceState is used, otherwise
+ * location.href/location.replace is used.
+ * Returns its own instance to allow chaining
+ *
+ * NOTE: this api is intended for use only by the $location service. Please use the
+ * {@link ng.$location $location service} to change url.
+ *
+ * @param {string} url New url (when used as setter)
+ * @param {boolean=} replace Should new url replace current history record?
+ * @param {object=} state object to use with pushState/replaceState
+ */
+ self.url = function(url, replace, state) {
+ // In modern browsers `history.state` is `null` by default; treating it separately
+ // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
+ // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
+ if (isUndefined(state)) {
+ state = null;
+ }
+
+ // Android Browser BFCache causes location, history reference to become stale.
+ if (location !== window.location) location = window.location;
+ if (history !== window.history) history = window.history;
+
+ // setter
+ if (url) {
+ var sameState = lastHistoryState === state;
+
+ // Don't change anything if previous and current URLs and states match. This also prevents
+ // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
+ // See https://github.com/angular/angular.js/commit/ffb2701
+ if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
+ return self;
+ }
+ var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
+ lastBrowserUrl = url;
+ lastHistoryState = state;
+ // Don't use history API if only the hash changed
+ // due to a bug in IE10/IE11 which leads
+ // to not firing a `hashchange` nor `popstate` event
+ // in some cases (see #9143).
+ if ($sniffer.history && (!sameBase || !sameState)) {
+ history[replace ? 'replaceState' : 'pushState'](state, '', url);
+ cacheState();
+ // Do the assignment again so that those two variables are referentially identical.
+ lastHistoryState = cachedState;
+ } else {
+ if (!sameBase || pendingLocation) {
+ pendingLocation = url;
+ }
+ if (replace) {
+ location.replace(url);
+ } else if (!sameBase) {
+ location.href = url;
+ } else {
+ location.hash = getHash(url);
+ }
+ if (location.href !== url) {
+ pendingLocation = url;
+ }
+ }
+ return self;
+ // getter
+ } else {
+ // - pendingLocation is needed as browsers don't allow to read out
+ // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
+ // https://openradar.appspot.com/22186109).
+ // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
+ return pendingLocation || location.href.replace(/%27/g,"'");
+ }
+ };
+
+ /**
+ * @name $browser#state
+ *
+ * @description
+ * This method is a getter.
+ *
+ * Return history.state or null if history.state is undefined.
+ *
+ * @returns {object} state
+ */
+ self.state = function() {
+ return cachedState;
+ };
+
+ var urlChangeListeners = [],
+ urlChangeInit = false;
+
+ function cacheStateAndFireUrlChange() {
+ pendingLocation = null;
+ cacheState();
+ fireUrlChange();
+ }
+
+ function getCurrentState() {
+ try {
+ return history.state;
+ } catch (e) {
+ // MSIE can reportedly throw when there is no state (UNCONFIRMED).
+ }
+ }
+
+ // This variable should be used *only* inside the cacheState function.
+ var lastCachedState = null;
+ function cacheState() {
+ // This should be the only place in $browser where `history.state` is read.
+ cachedState = getCurrentState();
+ cachedState = isUndefined(cachedState) ? null : cachedState;
+
+ // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
+ if (equals(cachedState, lastCachedState)) {
+ cachedState = lastCachedState;
+ }
+ lastCachedState = cachedState;
+ }
+
+ function fireUrlChange() {
+ if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
+ return;
+ }
+
+ lastBrowserUrl = self.url();
+ lastHistoryState = cachedState;
+ forEach(urlChangeListeners, function(listener) {
+ listener(self.url(), cachedState);
+ });
+ }
+
+ /**
+ * @name $browser#onUrlChange
+ *
+ * @description
+ * Register callback function that will be called, when url changes.
+ *
+ * It's only called when the url is changed from outside of angular:
+ * - user types different url into address bar
+ * - user clicks on history (forward/back) button
+ * - user clicks on a link
+ *
+ * It's not called when url is changed by $browser.url() method
+ *
+ * The listener gets called with new url as parameter.
+ *
+ * NOTE: this api is intended for use only by the $location service. Please use the
+ * {@link ng.$location $location service} to monitor url changes in angular apps.
+ *
+ * @param {function(string)} listener Listener function to be called when url changes.
+ * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
+ */
+ self.onUrlChange = function(callback) {
+ // TODO(vojta): refactor to use node's syntax for events
+ if (!urlChangeInit) {
+ // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
+ // don't fire popstate when user change the address bar and don't fire hashchange when url
+ // changed by push/replaceState
+
+ // html5 history api - popstate event
+ if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
+ // hashchange event
+ jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
+
+ urlChangeInit = true;
+ }
+
+ urlChangeListeners.push(callback);
+ return callback;
+ };
+
+ /**
+ * @private
+ * Remove popstate and hashchange handler from window.
+ *
+ * NOTE: this api is intended for use only by $rootScope.
+ */
+ self.$$applicationDestroyed = function() {
+ jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
+ };
+
+ /**
+ * Checks whether the url has changed outside of Angular.
+ * Needs to be exported to be able to check for changes that have been done in sync,
+ * as hashchange/popstate events fire in async.
+ */
+ self.$$checkUrlChange = fireUrlChange;
+
+ //////////////////////////////////////////////////////////////
+ // Misc API
+ //////////////////////////////////////////////////////////////
+
+ /**
+ * @name $browser#baseHref
+ *
+ * @description
+ * Returns current <base href>
+ * (always relative - without domain)
+ *
+ * @returns {string} The current base href
+ */
+ self.baseHref = function() {
+ var href = baseElement.attr('href');
+ return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
+ };
+
+ /**
+ * @name $browser#defer
+ * @param {function()} fn A function, who's execution should be deferred.
+ * @param {number=} [delay=0] of milliseconds to defer the function execution.
+ * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
+ *
+ * @description
+ * Executes a fn asynchronously via `setTimeout(fn, delay)`.
+ *
+ * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
+ * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
+ * via `$browser.defer.flush()`.
+ *
+ */
+ self.defer = function(fn, delay) {
+ var timeoutId;
+ outstandingRequestCount++;
+ timeoutId = setTimeout(function() {
+ delete pendingDeferIds[timeoutId];
+ completeOutstandingRequest(fn);
+ }, delay || 0);
+ pendingDeferIds[timeoutId] = true;
+ return timeoutId;
+ };
+
+
+ /**
+ * @name $browser#defer.cancel
+ *
+ * @description
+ * Cancels a deferred task identified with `deferId`.
+ *
+ * @param {*} deferId Token returned by the `$browser.defer` function.
+ * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
+ * canceled.
+ */
+ self.defer.cancel = function(deferId) {
+ if (pendingDeferIds[deferId]) {
+ delete pendingDeferIds[deferId];
+ clearTimeout(deferId);
+ completeOutstandingRequest(noop);
+ return true;
+ }
+ return false;
+ };
+
+}
+
+function $BrowserProvider() {
+ this.$get = ['$window', '$log', '$sniffer', '$document',
+ function($window, $log, $sniffer, $document) {
+ return new Browser($window, $document, $log, $sniffer);
+ }];
+}
+
+/**
+ * @ngdoc service
+ * @name $cacheFactory
+ *
+ * @description
+ * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
+ * them.
+ *
+ * ```js
+ *
+ * var cache = $cacheFactory('cacheId');
+ * expect($cacheFactory.get('cacheId')).toBe(cache);
+ * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
+ *
+ * cache.put("key", "value");
+ * cache.put("another key", "another value");
+ *
+ * // We've specified no options on creation
+ * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
+ *
+ * ```
+ *
+ *
+ * @param {string} cacheId Name or id of the newly created cache.
+ * @param {object=} options Options object that specifies the cache behavior. Properties:
+ *
+ * - `{number=}` `capacity` — turns the cache into LRU cache.
+ *
+ * @returns {object} Newly created cache object with the following set of methods:
+ *
+ * - `{object}` `info()` — Returns id, size, and options of cache.
+ * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
+ * it.
+ * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
+ * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
+ * - `{void}` `removeAll()` — Removes all cached values.
+ * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
+ *
+ * @example
+ <example module="cacheExampleApp">
+ <file name="index.html">
+ <div ng-controller="CacheController">
+ <input ng-model="newCacheKey" placeholder="Key">
+ <input ng-model="newCacheValue" placeholder="Value">
+ <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
+
+ <p ng-if="keys.length">Cached Values</p>
+ <div ng-repeat="key in keys">
+ <span ng-bind="key"></span>
+ <span>: </span>
+ <b ng-bind="cache.get(key)"></b>
+ </div>
+
+ <p>Cache Info</p>
+ <div ng-repeat="(key, value) in cache.info()">
+ <span ng-bind="key"></span>
+ <span>: </span>
+ <b ng-bind="value"></b>
+ </div>
+ </div>
+ </file>
+ <file name="script.js">
+ angular.module('cacheExampleApp', []).
+ controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
+ $scope.keys = [];
+ $scope.cache = $cacheFactory('cacheId');
+ $scope.put = function(key, value) {
+ if (angular.isUndefined($scope.cache.get(key))) {
+ $scope.keys.push(key);
+ }
+ $scope.cache.put(key, angular.isUndefined(value) ? null : value);
+ };
+ }]);
+ </file>
+ <file name="style.css">
+ p {
+ margin: 10px 0 3px;
+ }
+ </file>
+ </example>
+ */
+function $CacheFactoryProvider() {
+
+ this.$get = function() {
+ var caches = {};
+
+ function cacheFactory(cacheId, options) {
+ if (cacheId in caches) {
+ throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
+ }
+
+ var size = 0,
+ stats = extend({}, options, {id: cacheId}),
+ data = createMap(),
+ capacity = (options && options.capacity) || Number.MAX_VALUE,
+ lruHash = createMap(),
+ freshEnd = null,
+ staleEnd = null;
+
+ /**
+ * @ngdoc type
+ * @name $cacheFactory.Cache
+ *
+ * @description
+ * A cache object used to store and retrieve data, primarily used by
+ * {@link $http $http} and the {@link ng.directive:script script} directive to cache
+ * templates and other data.
+ *
+ * ```js
+ * angular.module('superCache')
+ * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
+ * return $cacheFactory('super-cache');
+ * }]);
+ * ```
+ *
+ * Example test:
+ *
+ * ```js
+ * it('should behave like a cache', inject(function(superCache) {
+ * superCache.put('key', 'value');
+ * superCache.put('another key', 'another value');
+ *
+ * expect(superCache.info()).toEqual({
+ * id: 'super-cache',
+ * size: 2
+ * });
+ *
+ * superCache.remove('another key');
+ * expect(superCache.get('another key')).toBeUndefined();
+ *
+ * superCache.removeAll();
+ * expect(superCache.info()).toEqual({
+ * id: 'super-cache',
+ * size: 0
+ * });
+ * }));
+ * ```
+ */
+ return caches[cacheId] = {
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory.Cache#put
+ * @kind function
+ *
+ * @description
+ * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
+ * retrieved later, and incrementing the size of the cache if the key was not already
+ * present in the cache. If behaving like an LRU cache, it will also remove stale
+ * entries from the set.
+ *
+ * It will not insert undefined values into the cache.
+ *
+ * @param {string} key the key under which the cached data is stored.
+ * @param {*} value the value to store alongside the key. If it is undefined, the key
+ * will not be stored.
+ * @returns {*} the value stored.
+ */
+ put: function(key, value) {
+ if (isUndefined(value)) return;
+ if (capacity < Number.MAX_VALUE) {
+ var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
+
+ refresh(lruEntry);
+ }
+
+ if (!(key in data)) size++;
+ data[key] = value;
+
+ if (size > capacity) {
+ this.remove(staleEnd.key);
+ }
+
+ return value;
+ },
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory.Cache#get
+ * @kind function
+ *
+ * @description
+ * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
+ *
+ * @param {string} key the key of the data to be retrieved
+ * @returns {*} the value stored.
+ */
+ get: function(key) {
+ if (capacity < Number.MAX_VALUE) {
+ var lruEntry = lruHash[key];
+
+ if (!lruEntry) return;
+
+ refresh(lruEntry);
+ }
+
+ return data[key];
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory.Cache#remove
+ * @kind function
+ *
+ * @description
+ * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
+ *
+ * @param {string} key the key of the entry to be removed
+ */
+ remove: function(key) {
+ if (capacity < Number.MAX_VALUE) {
+ var lruEntry = lruHash[key];
+
+ if (!lruEntry) return;
+
+ if (lruEntry == freshEnd) freshEnd = lruEntry.p;
+ if (lruEntry == staleEnd) staleEnd = lruEntry.n;
+ link(lruEntry.n,lruEntry.p);
+
+ delete lruHash[key];
+ }
+
+ if (!(key in data)) return;
+
+ delete data[key];
+ size--;
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory.Cache#removeAll
+ * @kind function
+ *
+ * @description
+ * Clears the cache object of any entries.
+ */
+ removeAll: function() {
+ data = createMap();
+ size = 0;
+ lruHash = createMap();
+ freshEnd = staleEnd = null;
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory.Cache#destroy
+ * @kind function
+ *
+ * @description
+ * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
+ * removing it from the {@link $cacheFactory $cacheFactory} set.
+ */
+ destroy: function() {
+ data = null;
+ stats = null;
+ lruHash = null;
+ delete caches[cacheId];
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory.Cache#info
+ * @kind function
+ *
+ * @description
+ * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
+ *
+ * @returns {object} an object with the following properties:
+ * <ul>
+ * <li>**id**: the id of the cache instance</li>
+ * <li>**size**: the number of entries kept in the cache instance</li>
+ * <li>**...**: any additional properties from the options object when creating the
+ * cache.</li>
+ * </ul>
+ */
+ info: function() {
+ return extend({}, stats, {size: size});
+ }
+ };
+
+
+ /**
+ * makes the `entry` the freshEnd of the LRU linked list
+ */
+ function refresh(entry) {
+ if (entry != freshEnd) {
+ if (!staleEnd) {
+ staleEnd = entry;
+ } else if (staleEnd == entry) {
+ staleEnd = entry.n;
+ }
+
+ link(entry.n, entry.p);
+ link(entry, freshEnd);
+ freshEnd = entry;
+ freshEnd.n = null;
+ }
+ }
+
+
+ /**
+ * bidirectionally links two entries of the LRU linked list
+ */
+ function link(nextEntry, prevEntry) {
+ if (nextEntry != prevEntry) {
+ if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
+ if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
+ }
+ }
+ }
+
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory#info
+ *
+ * @description
+ * Get information about all the caches that have been created
+ *
+ * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
+ */
+ cacheFactory.info = function() {
+ var info = {};
+ forEach(caches, function(cache, cacheId) {
+ info[cacheId] = cache.info();
+ });
+ return info;
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $cacheFactory#get
+ *
+ * @description
+ * Get access to a cache object by the `cacheId` used when it was created.
+ *
+ * @param {string} cacheId Name or id of a cache to access.
+ * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
+ */
+ cacheFactory.get = function(cacheId) {
+ return caches[cacheId];
+ };
+
+
+ return cacheFactory;
+ };
+}
+
+/**
+ * @ngdoc service
+ * @name $templateCache
+ *
+ * @description
+ * The first time a template is used, it is loaded in the template cache for quick retrieval. You
+ * can load templates directly into the cache in a `script` tag, or by consuming the
+ * `$templateCache` service directly.
+ *
+ * Adding via the `script` tag:
+ *
+ * ```html
+ * <script type="text/ng-template" id="templateId.html">
+ * <p>This is the content of the template</p>
+ * </script>
+ * ```
+ *
+ * **Note:** the `script` tag containing the template does not need to be included in the `head` of
+ * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
+ * element with ng-app attribute), otherwise the template will be ignored.
+ *
+ * Adding via the `$templateCache` service:
+ *
+ * ```js
+ * var myApp = angular.module('myApp', []);
+ * myApp.run(function($templateCache) {
+ * $templateCache.put('templateId.html', 'This is the content of the template');
+ * });
+ * ```
+ *
+ * To retrieve the template later, simply use it in your HTML:
+ * ```html
+ * <div ng-include=" 'templateId.html' "></div>
+ * ```
+ *
+ * or get it via Javascript:
+ * ```js
+ * $templateCache.get('templateId.html')
+ * ```
+ *
+ * See {@link ng.$cacheFactory $cacheFactory}.
+ *
+ */
+function $TemplateCacheProvider() {
+ this.$get = ['$cacheFactory', function($cacheFactory) {
+ return $cacheFactory('templates');
+ }];
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Any commits to this file should be reviewed with security in mind. *
+ * Changes to this file can potentially create security vulnerabilities. *
+ * An approval from 2 Core members with history of modifying *
+ * this file is required. *
+ * *
+ * Does the change somehow allow for arbitrary javascript to be executed? *
+ * Or allows for someone to change the prototype of built-in objects? *
+ * Or gives undesired access to variables likes document or window? *
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
+ *
+ * DOM-related variables:
+ *
+ * - "node" - DOM Node
+ * - "element" - DOM Element or Node
+ * - "$node" or "$element" - jqLite-wrapped node or element
+ *
+ *
+ * Compiler related stuff:
+ *
+ * - "linkFn" - linking fn of a single directive
+ * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
+ * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
+ * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
+ */
+
+
+/**
+ * @ngdoc service
+ * @name $compile
+ * @kind function
+ *
+ * @description
+ * Compiles an HTML string or DOM into a template and produces a template function, which
+ * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
+ *
+ * The compilation is a process of walking the DOM tree and matching DOM elements to
+ * {@link ng.$compileProvider#directive directives}.
+ *
+ * <div class="alert alert-warning">
+ * **Note:** This document is an in-depth reference of all directive options.
+ * For a gentle introduction to directives with examples of common use cases,
+ * see the {@link guide/directive directive guide}.
+ * </div>
+ *
+ * ## Comprehensive Directive API
+ *
+ * There are many different options for a directive.
+ *
+ * The difference resides in the return value of the factory function.
+ * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
+ * or just the `postLink` function (all other properties will have the default values).
+ *
+ * <div class="alert alert-success">
+ * **Best Practice:** It's recommended to use the "directive definition object" form.
+ * </div>
+ *
+ * Here's an example directive declared with a Directive Definition Object:
+ *
+ * ```js
+ * var myModule = angular.module(...);
+ *
+ * myModule.directive('directiveName', function factory(injectables) {
+ * var directiveDefinitionObject = {
+ * priority: 0,
+ * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
+ * // or
+ * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
+ * transclude: false,
+ * restrict: 'A',
+ * templateNamespace: 'html',
+ * scope: false,
+ * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
+ * controllerAs: 'stringIdentifier',
+ * bindToController: false,
+ * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
+ * compile: function compile(tElement, tAttrs, transclude) {
+ * return {
+ * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
+ * post: function postLink(scope, iElement, iAttrs, controller) { ... }
+ * }
+ * // or
+ * // return function postLink( ... ) { ... }
+ * },
+ * // or
+ * // link: {
+ * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
+ * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
+ * // }
+ * // or
+ * // link: function postLink( ... ) { ... }
+ * };
+ * return directiveDefinitionObject;
+ * });
+ * ```
+ *
+ * <div class="alert alert-warning">
+ * **Note:** Any unspecified options will use the default value. You can see the default values below.
+ * </div>
+ *
+ * Therefore the above can be simplified as:
+ *
+ * ```js
+ * var myModule = angular.module(...);
+ *
+ * myModule.directive('directiveName', function factory(injectables) {
+ * var directiveDefinitionObject = {
+ * link: function postLink(scope, iElement, iAttrs) { ... }
+ * };
+ * return directiveDefinitionObject;
+ * // or
+ * // return function postLink(scope, iElement, iAttrs) { ... }
+ * });
+ * ```
+ *
+ *
+ *
+ * ### Directive Definition Object
+ *
+ * The directive definition object provides instructions to the {@link ng.$compile
+ * compiler}. The attributes are:
+ *
+ * #### `multiElement`
+ * When this property is set to true, the HTML compiler will collect DOM nodes between
+ * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
+ * together as the directive elements. It is recommended that this feature be used on directives
+ * which are not strictly behavioural (such as {@link ngClick}), and which
+ * do not manipulate or replace child nodes (such as {@link ngInclude}).
+ *
+ * #### `priority`
+ * When there are multiple directives defined on a single DOM element, sometimes it
+ * is necessary to specify the order in which the directives are applied. The `priority` is used
+ * to sort the directives before their `compile` functions get called. Priority is defined as a
+ * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
+ * are also run in priority order, but post-link functions are run in reverse order. The order
+ * of directives with the same priority is undefined. The default priority is `0`.
+ *
+ * #### `terminal`
+ * If set to true then the current `priority` will be the last set of directives
+ * which will execute (any directives at the current priority will still execute
+ * as the order of execution on same `priority` is undefined). Note that expressions
+ * and other directives used in the directive's template will also be excluded from execution.
+ *
+ * #### `scope`
+ * The scope property can be `true`, an object or a falsy value:
+ *
+ * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
+ *
+ * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
+ * the directive's element. If multiple directives on the same element request a new scope,
+ * only one new scope is created. The new scope rule does not apply for the root of the template
+ * since the root of the template always gets a new scope.
+ *
+ * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
+ * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
+ * scope. This is useful when creating reusable components, which should not accidentally read or modify
+ * data in the parent scope.
+ *
+ * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
+ * directive's element. These local properties are useful for aliasing values for templates. The keys in
+ * the object hash map to the name of the property on the isolate scope; the values define how the property
+ * is bound to the parent scope, via matching attributes on the directive's element:
+ *
+ * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
+ * always a string since DOM attributes are strings. If no `attr` name is specified then the
+ * attribute name is assumed to be the same as the local name.
+ * Given `<widget my-attr="hello {{name}}">` and widget definition
+ * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
+ * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
+ * `localName` property on the widget scope. The `name` is read from the parent scope (not
+ * component scope).
+ *
+ * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
+ * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
+ * name is specified then the attribute name is assumed to be the same as the local name.
+ * Given `<widget my-attr="parentModel">` and widget definition of
+ * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
+ * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
+ * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
+ * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
+ * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
+ * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
+ * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
+ *
+ * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
+ * If no `attr` name is specified then the attribute name is assumed to be the same as the
+ * local name. Given `<widget my-attr="count = count + value">` and widget definition of
+ * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
+ * a function wrapper for the `count = count + value` expression. Often it's desirable to
+ * pass data from the isolated scope via an expression to the parent scope, this can be
+ * done by passing a map of local variable names and values into the expression wrapper fn.
+ * For example, if the expression is `increment(amount)` then we can specify the amount value
+ * by calling the `localFn` as `localFn({amount: 22})`.
+ *
+ * In general it's possible to apply more than one directive to one element, but there might be limitations
+ * depending on the type of scope required by the directives. The following points will help explain these limitations.
+ * For simplicity only two directives are taken into account, but it is also applicable for several directives:
+ *
+ * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
+ * * **child scope** + **no scope** => Both directives will share one single child scope
+ * * **child scope** + **child scope** => Both directives will share one single child scope
+ * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
+ * its parent's scope
+ * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
+ * be applied to the same element.
+ * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
+ * cannot be applied to the same element.
+ *
+ *
+ * #### `bindToController`
+ * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
+ * allow a component to have its properties bound to the controller, rather than to scope. When the controller
+ * is instantiated, the initial values of the isolate scope bindings are already available.
+ *
+ * #### `controller`
+ * Controller constructor function. The controller is instantiated before the
+ * pre-linking phase and can be accessed by other directives (see
+ * `require` attribute). This allows the directives to communicate with each other and augment
+ * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
+ *
+ * * `$scope` - Current scope associated with the element
+ * * `$element` - Current element
+ * * `$attrs` - Current attributes object for the element
+ * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
+ * `function([scope], cloneLinkingFn, futureParentElement)`.
+ * * `scope`: optional argument to override the scope.
+ * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
+ * * `futureParentElement`:
+ * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
+ * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
+ * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
+ * and when the `cloneLinkinFn` is passed,
+ * as those elements need to created and cloned in a special way when they are defined outside their
+ * usual containers (e.g. like `<svg>`).
+ * * See also the `directive.templateNamespace` property.
+ *
+ *
+ * #### `require`
+ * Require another directive and inject its controller as the fourth argument to the linking function. The
+ * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
+ * injected argument will be an array in corresponding order. If no such directive can be
+ * found, or if the directive does not have a controller, then an error is raised (unless no link function
+ * is specified, in which case error checking is skipped). The name can be prefixed with:
+ *
+ * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
+ * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
+ * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
+ * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
+ * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
+ * `null` to the `link` fn if not found.
+ * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
+ * `null` to the `link` fn if not found.
+ *
+ *
+ * #### `controllerAs`
+ * Identifier name for a reference to the controller in the directive's scope.
+ * This allows the controller to be referenced from the directive template. This is especially
+ * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
+ * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
+ * `controllerAs` reference might overwrite a property that already exists on the parent scope.
+ *
+ *
+ * #### `restrict`
+ * String of subset of `EACM` which restricts the directive to a specific directive
+ * declaration style. If omitted, the defaults (elements and attributes) are used.
+ *
+ * * `E` - Element name (default): `<my-directive></my-directive>`
+ * * `A` - Attribute (default): `<div my-directive="exp"></div>`
+ * * `C` - Class: `<div class="my-directive: exp;"></div>`
+ * * `M` - Comment: `<!-- directive: my-directive exp -->`
+ *
+ *
+ * #### `templateNamespace`
+ * String representing the document type used by the markup in the template.
+ * AngularJS needs this information as those elements need to be created and cloned
+ * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
+ *
+ * * `html` - All root nodes in the template are HTML. Root nodes may also be
+ * top-level elements such as `<svg>` or `<math>`.
+ * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
+ * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
+ *
+ * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
+ *
+ * #### `template`
+ * HTML markup that may:
+ * * Replace the contents of the directive's element (default).
+ * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
+ * * Wrap the contents of the directive's element (if `transclude` is true).
+ *
+ * Value may be:
+ *
+ * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
+ * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
+ * function api below) and returns a string value.
+ *
+ *
+ * #### `templateUrl`
+ * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
+ *
+ * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
+ * for later when the template has been resolved. In the meantime it will continue to compile and link
+ * sibling and parent elements as though this element had not contained any directives.
+ *
+ * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
+ * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
+ * case when only one deeply nested directive has `templateUrl`.
+ *
+ * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
+ *
+ * You can specify `templateUrl` as a string representing the URL or as a function which takes two
+ * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
+ * a string value representing the url. In either case, the template URL is passed through {@link
+ * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
+ *
+ *
+ * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
+ * specify what the template should replace. Defaults to `false`.
+ *
+ * * `true` - the template will replace the directive's element.
+ * * `false` - the template will replace the contents of the directive's element.
+ *
+ * The replacement process migrates all of the attributes / classes from the old element to the new
+ * one. See the {@link guide/directive#template-expanding-directive
+ * Directives Guide} for an example.
+ *
+ * There are very few scenarios where element replacement is required for the application function,
+ * the main one being reusable custom components that are used within SVG contexts
+ * (because SVG doesn't work with custom elements in the DOM tree).
+ *
+ * #### `transclude`
+ * Extract the contents of the element where the directive appears and make it available to the directive.
+ * The contents are compiled and provided to the directive as a **transclusion function**. See the
+ * {@link $compile#transclusion Transclusion} section below.
+ *
+ * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
+ * directive's element or the entire element:
+ *
+ * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
+ * * `'element'` - transclude the whole of the directive's element including any directives on this
+ * element that defined at a lower priority than this directive. When used, the `template`
+ * property is ignored.
+ *
+ *
+ * #### `compile`
+ *
+ * ```js
+ * function compile(tElement, tAttrs, transclude) { ... }
+ * ```
+ *
+ * The compile function deals with transforming the template DOM. Since most directives do not do
+ * template transformation, it is not used often. The compile function takes the following arguments:
+ *
+ * * `tElement` - template element - The element where the directive has been declared. It is
+ * safe to do template transformation on the element and child elements only.
+ *
+ * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
+ * between all directive compile functions.
+ *
+ * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
+ *
+ * <div class="alert alert-warning">
+ * **Note:** The template instance and the link instance may be different objects if the template has
+ * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
+ * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
+ * should be done in a linking function rather than in a compile function.
+ * </div>
+
+ * <div class="alert alert-warning">
+ * **Note:** The compile function cannot handle directives that recursively use themselves in their
+ * own templates or compile functions. Compiling these directives results in an infinite loop and a
+ * stack overflow errors.
+ *
+ * This can be avoided by manually using $compile in the postLink function to imperatively compile
+ * a directive's template instead of relying on automatic template compilation via `template` or
+ * `templateUrl` declaration or manual compilation inside the compile function.
+ * </div>
+ *
+ * <div class="alert alert-danger">
+ * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
+ * e.g. does not know about the right outer scope. Please use the transclude function that is passed
+ * to the link function instead.
+ * </div>
+
+ * A compile function can have a return value which can be either a function or an object.
+ *
+ * * returning a (post-link) function - is equivalent to registering the linking function via the
+ * `link` property of the config object when the compile function is empty.
+ *
+ * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
+ * control when a linking function should be called during the linking phase. See info about
+ * pre-linking and post-linking functions below.
+ *
+ *
+ * #### `link`
+ * This property is used only if the `compile` property is not defined.
+ *
+ * ```js
+ * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
+ * ```
+ *
+ * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
+ * executed after the template has been cloned. This is where most of the directive logic will be
+ * put.
+ *
+ * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
+ * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
+ *
+ * * `iElement` - instance element - The element where the directive is to be used. It is safe to
+ * manipulate the children of the element only in `postLink` function since the children have
+ * already been linked.
+ *
+ * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
+ * between all directive linking functions.
+ *
+ * * `controller` - the directive's required controller instance(s) - Instances are shared
+ * among all directives, which allows the directives to use the controllers as a communication
+ * channel. The exact value depends on the directive's `require` property:
+ * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
+ * * `string`: the controller instance
+ * * `array`: array of controller instances
+ *
+ * If a required controller cannot be found, and it is optional, the instance is `null`,
+ * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
+ *
+ * Note that you can also require the directive's own controller - it will be made available like
+ * any other controller.
+ *
+ * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
+ * This is the same as the `$transclude`
+ * parameter of directive controllers, see there for details.
+ * `function([scope], cloneLinkingFn, futureParentElement)`.
+ *
+ * #### Pre-linking function
+ *
+ * Executed before the child elements are linked. Not safe to do DOM transformation since the
+ * compiler linking function will fail to locate the correct elements for linking.
+ *
+ * #### Post-linking function
+ *
+ * Executed after the child elements are linked.
+ *
+ * Note that child elements that contain `templateUrl` directives will not have been compiled
+ * and linked since they are waiting for their template to load asynchronously and their own
+ * compilation and linking has been suspended until that occurs.
+ *
+ * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
+ * for their async templates to be resolved.
+ *
+ *
+ * ### Transclusion
+ *
+ * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
+ * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
+ * scope from where they were taken.
+ *
+ * Transclusion is used (often with {@link ngTransclude}) to insert the
+ * original contents of a directive's element into a specified place in the template of the directive.
+ * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
+ * content has access to the properties on the scope from which it was taken, even if the directive
+ * has isolated scope.
+ * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
+ *
+ * This makes it possible for the widget to have private state for its template, while the transcluded
+ * content has access to its originating scope.
+ *
+ * <div class="alert alert-warning">
+ * **Note:** When testing an element transclude directive you must not place the directive at the root of the
+ * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
+ * Testing Transclusion Directives}.
+ * </div>
+ *
+ * #### Transclusion Functions
+ *
+ * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
+ * function** to the directive's `link` function and `controller`. This transclusion function is a special
+ * **linking function** that will return the compiled contents linked to a new transclusion scope.
+ *
+ * <div class="alert alert-info">
+ * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
+ * ngTransclude will deal with it for us.
+ * </div>
+ *
+ * If you want to manually control the insertion and removal of the transcluded content in your directive
+ * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
+ * object that contains the compiled DOM, which is linked to the correct transclusion scope.
+ *
+ * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
+ * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
+ * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
+ *
+ * <div class="alert alert-info">
+ * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
+ * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
+ * </div>
+ *
+ * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
+ * attach function**:
+ *
+ * ```js
+ * var transcludedContent, transclusionScope;
+ *
+ * $transclude(function(clone, scope) {
+ * element.append(clone);
+ * transcludedContent = clone;
+ * transclusionScope = scope;
+ * });
+ * ```
+ *
+ * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
+ * associated transclusion scope:
+ *
+ * ```js
+ * transcludedContent.remove();
+ * transclusionScope.$destroy();
+ * ```
+ *
+ * <div class="alert alert-info">
+ * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
+ * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
+ * then you are also responsible for calling `$destroy` on the transclusion scope.
+ * </div>
+ *
+ * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
+ * automatically destroy their transluded clones as necessary so you do not need to worry about this if
+ * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
+ *
+ *
+ * #### Transclusion Scopes
+ *
+ * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
+ * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
+ * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
+ * was taken.
+ *
+ * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
+ * like this:
+ *
+ * ```html
+ * <div ng-app>
+ * <div isolate>
+ * <div transclusion>
+ * </div>
+ * </div>
+ * </div>
+ * ```
+ *
+ * The `$parent` scope hierarchy will look like this:
+ *
+ * ```
+ * - $rootScope
+ * - isolate
+ * - transclusion
+ * ```
+ *
+ * but the scopes will inherit prototypically from different scopes to their `$parent`.
+ *
+ * ```
+ * - $rootScope
+ * - transclusion
+ * - isolate
+ * ```
+ *
+ *
+ * ### Attributes
+ *
+ * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
+ * `link()` or `compile()` functions. It has a variety of uses.
+ *
+ * accessing *Normalized attribute names:*
+ * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
+ * the attributes object allows for normalized access to
+ * the attributes.
+ *
+ * * *Directive inter-communication:* All directives share the same instance of the attributes
+ * object which allows the directives to use the attributes object as inter directive
+ * communication.
+ *
+ * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
+ * allowing other directives to read the interpolated value.
+ *
+ * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
+ * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
+ * the only way to easily get the actual value because during the linking phase the interpolation
+ * hasn't been evaluated yet and so the value is at this time set to `undefined`.
+ *
+ * ```js
+ * function linkingFn(scope, elm, attrs, ctrl) {
+ * // get the attribute value
+ * console.log(attrs.ngModel);
+ *
+ * // change the attribute
+ * attrs.$set('ngModel', 'new value');
+ *
+ * // observe changes to interpolated attribute
+ * attrs.$observe('ngModel', function(value) {
+ * console.log('ngModel has changed value to ' + value);
+ * });
+ * }
+ * ```
+ *
+ * ## Example
+ *
+ * <div class="alert alert-warning">
+ * **Note**: Typically directives are registered with `module.directive`. The example below is
+ * to illustrate how `$compile` works.
+ * </div>
+ *
+ <example module="compileExample">
+ <file name="index.html">
+ <script>
+ angular.module('compileExample', [], function($compileProvider) {
+ // configure new 'compile' directive by passing a directive
+ // factory function. The factory function injects the '$compile'
+ $compileProvider.directive('compile', function($compile) {
+ // directive factory creates a link function
+ return function(scope, element, attrs) {
+ scope.$watch(
+ function(scope) {
+ // watch the 'compile' expression for changes
+ return scope.$eval(attrs.compile);
+ },
+ function(value) {
+ // when the 'compile' expression changes
+ // assign it into the current DOM
+ element.html(value);
+
+ // compile the new DOM and link it to the current
+ // scope.
+ // NOTE: we only compile .childNodes so that
+ // we don't get into infinite loop compiling ourselves
+ $compile(element.contents())(scope);
+ }
+ );
+ };
+ });
+ })
+ .controller('GreeterController', ['$scope', function($scope) {
+ $scope.name = 'Angular';
+ $scope.html = 'Hello {{name}}';
+ }]);
+ </script>
+ <div ng-controller="GreeterController">
+ <input ng-model="name"> <br/>
+ <textarea ng-model="html"></textarea> <br/>
+ <div compile="html"></div>
+ </div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should auto compile', function() {
+ var textarea = $('textarea');
+ var output = $('div[compile]');
+ // The initial state reads 'Hello Angular'.
+ expect(output.getText()).toBe('Hello Angular');
+ textarea.clear();
+ textarea.sendKeys('{{name}}!');
+ expect(output.getText()).toBe('Angular!');
+ });
+ </file>
+ </example>
+
+ *
+ *
+ * @param {string|DOMElement} element Element or HTML string to compile into a template function.
+ * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
+ *
+ * <div class="alert alert-danger">
+ * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
+ * e.g. will not use the right outer scope. Please pass the transclude function as a
+ * `parentBoundTranscludeFn` to the link function instead.
+ * </div>
+ *
+ * @param {number} maxPriority only apply directives lower than given priority (Only effects the
+ * root element(s), not their children)
+ * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
+ * (a DOM element/tree) to a scope. Where:
+ *
+ * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
+ * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
+ * `template` and call the `cloneAttachFn` function allowing the caller to attach the
+ * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
+ * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
+ *
+ * * `clonedElement` - is a clone of the original `element` passed into the compiler.
+ * * `scope` - is the current scope with which the linking function is working with.
+ *
+ * * `options` - An optional object hash with linking options. If `options` is provided, then the following
+ * keys may be used to control linking behavior:
+ *
+ * * `parentBoundTranscludeFn` - the transclude function made available to
+ * directives; if given, it will be passed through to the link functions of
+ * directives found in `element` during compilation.
+ * * `transcludeControllers` - an object hash with keys that map controller names
+ * to controller instances; if given, it will make the controllers
+ * available to directives.
+ * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
+ * the cloned elements; only needed for transcludes that are allowed to contain non html
+ * elements (e.g. SVG elements). See also the directive.controller property.
+ *
+ * Calling the linking function returns the element of the template. It is either the original
+ * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
+ *
+ * After linking the view is not updated until after a call to $digest which typically is done by
+ * Angular automatically.
+ *
+ * If you need access to the bound view, there are two ways to do it:
+ *
+ * - If you are not asking the linking function to clone the template, create the DOM element(s)
+ * before you send them to the compiler and keep this reference around.
+ * ```js
+ * var element = $compile('<p>{{total}}</p>')(scope);
+ * ```
+ *
+ * - if on the other hand, you need the element to be cloned, the view reference from the original
+ * example would not point to the clone, but rather to the original template that was cloned. In
+ * this case, you can access the clone via the cloneAttachFn:
+ * ```js
+ * var templateElement = angular.element('<p>{{total}}</p>'),
+ * scope = ....;
+ *
+ * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
+ * //attach the clone to DOM document at the right place
+ * });
+ *
+ * //now we have reference to the cloned DOM via `clonedElement`
+ * ```
+ *
+ *
+ * For information on how the compiler works, see the
+ * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
+ */
+
+var $compileMinErr = minErr('$compile');
+
+/**
+ * @ngdoc provider
+ * @name $compileProvider
+ *
+ * @description
+ */
+$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
+function $CompileProvider($provide, $$sanitizeUriProvider) {
+ var hasDirectives = {},
+ Suffix = 'Directive',
+ COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
+ CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
+ ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
+ REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
+
+ // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
+ // The assumption is that future DOM event attribute names will begin with
+ // 'on' and be composed of only English letters.
+ var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
+
+ function parseIsolateBindings(scope, directiveName, isController) {
+ var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
+
+ var bindings = {};
+
+ forEach(scope, function(definition, scopeName) {
+ var match = definition.match(LOCAL_REGEXP);
+
+ if (!match) {
+ throw $compileMinErr('iscp',
+ "Invalid {3} for directive '{0}'." +
+ " Definition: {... {1}: '{2}' ...}",
+ directiveName, scopeName, definition,
+ (isController ? "controller bindings definition" :
+ "isolate scope definition"));
+ }
+
+ bindings[scopeName] = {
+ mode: match[1][0],
+ collection: match[2] === '*',
+ optional: match[3] === '?',
+ attrName: match[4] || scopeName
+ };
+ });
+
+ return bindings;
+ }
+
+ function parseDirectiveBindings(directive, directiveName) {
+ var bindings = {
+ isolateScope: null,
+ bindToController: null
+ };
+ if (isObject(directive.scope)) {
+ if (directive.bindToController === true) {
+ bindings.bindToController = parseIsolateBindings(directive.scope,
+ directiveName, true);
+ bindings.isolateScope = {};
+ } else {
+ bindings.isolateScope = parseIsolateBindings(directive.scope,
+ directiveName, false);
+ }
+ }
+ if (isObject(directive.bindToController)) {
+ bindings.bindToController =
+ parseIsolateBindings(directive.bindToController, directiveName, true);
+ }
+ if (isObject(bindings.bindToController)) {
+ var controller = directive.controller;
+ var controllerAs = directive.controllerAs;
+ if (!controller) {
+ // There is no controller, there may or may not be a controllerAs property
+ throw $compileMinErr('noctrl',
+ "Cannot bind to controller without directive '{0}'s controller.",
+ directiveName);
+ } else if (!identifierForController(controller, controllerAs)) {
+ // There is a controller, but no identifier or controllerAs property
+ throw $compileMinErr('noident',
+ "Cannot bind to controller without identifier for directive '{0}'.",
+ directiveName);
+ }
+ }
+ return bindings;
+ }
+
+ function assertValidDirectiveName(name) {
+ var letter = name.charAt(0);
+ if (!letter || letter !== lowercase(letter)) {
+ throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
+ }
+ if (name !== name.trim()) {
+ throw $compileMinErr('baddir',
+ "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
+ name);
+ }
+ }
+
+ /**
+ * @ngdoc method
+ * @name $compileProvider#directive
+ * @kind function
+ *
+ * @description
+ * Register a new directive with the compiler.
+ *
+ * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
+ * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
+ * names and the values are the factories.
+ * @param {Function|Array} directiveFactory An injectable directive factory function. See
+ * {@link guide/directive} for more info.
+ * @returns {ng.$compileProvider} Self for chaining.
+ */
+ this.directive = function registerDirective(name, directiveFactory) {
+ assertNotHasOwnProperty(name, 'directive');
+ if (isString(name)) {
+ assertValidDirectiveName(name);
+ assertArg(directiveFactory, 'directiveFactory');
+ if (!hasDirectives.hasOwnProperty(name)) {
+ hasDirectives[name] = [];
+ $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
+ function($injector, $exceptionHandler) {
+ var directives = [];
+ forEach(hasDirectives[name], function(directiveFactory, index) {
+ try {
+ var directive = $injector.invoke(directiveFactory);
+ if (isFunction(directive)) {
+ directive = { compile: valueFn(directive) };
+ } else if (!directive.compile && directive.link) {
+ directive.compile = valueFn(directive.link);
+ }
+ directive.priority = directive.priority || 0;
+ directive.index = index;
+ directive.name = directive.name || name;
+ directive.require = directive.require || (directive.controller && directive.name);
+ directive.restrict = directive.restrict || 'EA';
+ var bindings = directive.$$bindings =
+ parseDirectiveBindings(directive, directive.name);
+ if (isObject(bindings.isolateScope)) {
+ directive.$$isolateBindings = bindings.isolateScope;
+ }
+ directive.$$moduleName = directiveFactory.$$moduleName;
+ directives.push(directive);
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ });
+ return directives;
+ }]);
+ }
+ hasDirectives[name].push(directiveFactory);
+ } else {
+ forEach(name, reverseParams(registerDirective));
+ }
+ return this;
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $compileProvider#aHrefSanitizationWhitelist
+ * @kind function
+ *
+ * @description
+ * Retrieves or overrides the default regular expression that is used for whitelisting of safe
+ * urls during a[href] sanitization.
+ *
+ * The sanitization is a security measure aimed at preventing XSS attacks via html links.
+ *
+ * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
+ * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
+ * regular expression. If a match is found, the original url is written into the dom. Otherwise,
+ * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
+ *
+ * @param {RegExp=} regexp New regexp to whitelist urls with.
+ * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
+ * chaining otherwise.
+ */
+ this.aHrefSanitizationWhitelist = function(regexp) {
+ if (isDefined(regexp)) {
+ $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
+ return this;
+ } else {
+ return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
+ }
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $compileProvider#imgSrcSanitizationWhitelist
+ * @kind function
+ *
+ * @description
+ * Retrieves or overrides the default regular expression that is used for whitelisting of safe
+ * urls during img[src] sanitization.
+ *
+ * The sanitization is a security measure aimed at prevent XSS attacks via html links.
+ *
+ * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
+ * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
+ * regular expression. If a match is found, the original url is written into the dom. Otherwise,
+ * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
+ *
+ * @param {RegExp=} regexp New regexp to whitelist urls with.
+ * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
+ * chaining otherwise.
+ */
+ this.imgSrcSanitizationWhitelist = function(regexp) {
+ if (isDefined(regexp)) {
+ $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
+ return this;
+ } else {
+ return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name $compileProvider#debugInfoEnabled
+ *
+ * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
+ * current debugInfoEnabled state
+ * @returns {*} current value if used as getter or itself (chaining) if used as setter
+ *
+ * @kind function
+ *
+ * @description
+ * Call this method to enable/disable various debug runtime information in the compiler such as adding
+ * binding information and a reference to the current scope on to DOM elements.
+ * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
+ * * `ng-binding` CSS class
+ * * `$binding` data property containing an array of the binding expressions
+ *
+ * You may want to disable this in production for a significant performance boost. See
+ * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
+ *
+ * The default value is true.
+ */
+ var debugInfoEnabled = true;
+ this.debugInfoEnabled = function(enabled) {
+ if (isDefined(enabled)) {
+ debugInfoEnabled = enabled;
+ return this;
+ }
+ return debugInfoEnabled;
+ };
+
+ this.$get = [
+ '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
+ '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
+ function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
+ $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
+
+ var Attributes = function(element, attributesToCopy) {
+ if (attributesToCopy) {
+ var keys = Object.keys(attributesToCopy);
+ var i, l, key;
+
+ for (i = 0, l = keys.length; i < l; i++) {
+ key = keys[i];
+ this[key] = attributesToCopy[key];
+ }
+ } else {
+ this.$attr = {};
+ }
+
+ this.$$element = element;
+ };
+
+ Attributes.prototype = {
+ /**
+ * @ngdoc method
+ * @name $compile.directive.Attributes#$normalize
+ * @kind function
+ *
+ * @description
+ * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
+ * `data-`) to its normalized, camelCase form.
+ *
+ * Also there is special case for Moz prefix starting with upper case letter.
+ *
+ * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
+ *
+ * @param {string} name Name to normalize
+ */
+ $normalize: directiveNormalize,
+
+
+ /**
+ * @ngdoc method
+ * @name $compile.directive.Attributes#$addClass
+ * @kind function
+ *
+ * @description
+ * Adds the CSS class value specified by the classVal parameter to the element. If animations
+ * are enabled then an animation will be triggered for the class addition.
+ *
+ * @param {string} classVal The className value that will be added to the element
+ */
+ $addClass: function(classVal) {
+ if (classVal && classVal.length > 0) {
+ $animate.addClass(this.$$element, classVal);
+ }
+ },
+
+ /**
+ * @ngdoc method
+ * @name $compile.directive.Attributes#$removeClass
+ * @kind function
+ *
+ * @description
+ * Removes the CSS class value specified by the classVal parameter from the element. If
+ * animations are enabled then an animation will be triggered for the class removal.
+ *
+ * @param {string} classVal The className value that will be removed from the element
+ */
+ $removeClass: function(classVal) {
+ if (classVal && classVal.length > 0) {
+ $animate.removeClass(this.$$element, classVal);
+ }
+ },
+
+ /**
+ * @ngdoc method
+ * @name $compile.directive.Attributes#$updateClass
+ * @kind function
+ *
+ * @description
+ * Adds and removes the appropriate CSS class values to the element based on the difference
+ * between the new and old CSS class values (specified as newClasses and oldClasses).
+ *
+ * @param {string} newClasses The current CSS className value
+ * @param {string} oldClasses The former CSS className value
+ */
+ $updateClass: function(newClasses, oldClasses) {
+ var toAdd = tokenDifference(newClasses, oldClasses);
+ if (toAdd && toAdd.length) {
+ $animate.addClass(this.$$element, toAdd);
+ }
+
+ var toRemove = tokenDifference(oldClasses, newClasses);
+ if (toRemove && toRemove.length) {
+ $animate.removeClass(this.$$element, toRemove);
+ }
+ },
+
+ /**
+ * Set a normalized attribute on the element in a way such that all directives
+ * can share the attribute. This function properly handles boolean attributes.
+ * @param {string} key Normalized key. (ie ngAttribute)
+ * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
+ * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
+ * Defaults to true.
+ * @param {string=} attrName Optional none normalized name. Defaults to key.
+ */
+ $set: function(key, value, writeAttr, attrName) {
+ // TODO: decide whether or not to throw an error if "class"
+ //is set through this function since it may cause $updateClass to
+ //become unstable.
+
+ var node = this.$$element[0],
+ booleanKey = getBooleanAttrName(node, key),
+ aliasedKey = getAliasedAttrName(key),
+ observer = key,
+ nodeName;
+
+ if (booleanKey) {
+ this.$$element.prop(key, value);
+ attrName = booleanKey;
+ } else if (aliasedKey) {
+ this[aliasedKey] = value;
+ observer = aliasedKey;
+ }
+
+ this[key] = value;
+
+ // translate normalized key to actual key
+ if (attrName) {
+ this.$attr[key] = attrName;
+ } else {
+ attrName = this.$attr[key];
+ if (!attrName) {
+ this.$attr[key] = attrName = snake_case(key, '-');
+ }
+ }
+
+ nodeName = nodeName_(this.$$element);
+
+ if ((nodeName === 'a' && key === 'href') ||
+ (nodeName === 'img' && key === 'src')) {
+ // sanitize a[href] and img[src] values
+ this[key] = value = $$sanitizeUri(value, key === 'src');
+ } else if (nodeName === 'img' && key === 'srcset') {
+ // sanitize img[srcset] values
+ var result = "";
+
+ // first check if there are spaces because it's not the same pattern
+ var trimmedSrcset = trim(value);
+ // ( 999x ,| 999w ,| ,|, )
+ var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
+ var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
+
+ // split srcset into tuple of uri and descriptor except for the last item
+ var rawUris = trimmedSrcset.split(pattern);
+
+ // for each tuples
+ var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
+ for (var i = 0; i < nbrUrisWith2parts; i++) {
+ var innerIdx = i * 2;
+ // sanitize the uri
+ result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
+ // add the descriptor
+ result += (" " + trim(rawUris[innerIdx + 1]));
+ }
+
+ // split the last item into uri and descriptor
+ var lastTuple = trim(rawUris[i * 2]).split(/\s/);
+
+ // sanitize the last uri
+ result += $$sanitizeUri(trim(lastTuple[0]), true);
+
+ // and add the last descriptor if any
+ if (lastTuple.length === 2) {
+ result += (" " + trim(lastTuple[1]));
+ }
+ this[key] = value = result;
+ }
+
+ if (writeAttr !== false) {
+ if (value === null || isUndefined(value)) {
+ this.$$element.removeAttr(attrName);
+ } else {
+ this.$$element.attr(attrName, value);
+ }
+ }
+
+ // fire observers
+ var $$observers = this.$$observers;
+ $$observers && forEach($$observers[observer], function(fn) {
+ try {
+ fn(value);
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ });
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $compile.directive.Attributes#$observe
+ * @kind function
+ *
+ * @description
+ * Observes an interpolated attribute.
+ *
+ * The observer function will be invoked once during the next `$digest` following
+ * compilation. The observer is then invoked whenever the interpolated value
+ * changes.
+ *
+ * @param {string} key Normalized key. (ie ngAttribute) .
+ * @param {function(interpolatedValue)} fn Function that will be called whenever
+ the interpolated value of the attribute changes.
+ * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
+ * @returns {function()} Returns a deregistration function for this observer.
+ */
+ $observe: function(key, fn) {
+ var attrs = this,
+ $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
+ listeners = ($$observers[key] || ($$observers[key] = []));
+
+ listeners.push(fn);
+ $rootScope.$evalAsync(function() {
+ if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
+ // no one registered attribute interpolation function, so lets call it manually
+ fn(attrs[key]);
+ }
+ });
+
+ return function() {
+ arrayRemove(listeners, fn);
+ };
+ }
+ };
+
+
+ function safeAddClass($element, className) {
+ try {
+ $element.addClass(className);
+ } catch (e) {
+ // ignore, since it means that we are trying to set class on
+ // SVG element, where class name is read-only.
+ }
+ }
+
+
+ var startSymbol = $interpolate.startSymbol(),
+ endSymbol = $interpolate.endSymbol(),
+ denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
+ ? identity
+ : function denormalizeTemplate(template) {
+ return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
+ },
+ NG_ATTR_BINDING = /^ngAttr[A-Z]/;
+ var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
+
+ compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
+ var bindings = $element.data('$binding') || [];
+
+ if (isArray(binding)) {
+ bindings = bindings.concat(binding);
+ } else {
+ bindings.push(binding);
+ }
+
+ $element.data('$binding', bindings);
+ } : noop;
+
+ compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
+ safeAddClass($element, 'ng-binding');
+ } : noop;
+
+ compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
+ var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
+ $element.data(dataName, scope);
+ } : noop;
+
+ compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
+ safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
+ } : noop;
+
+ return compile;
+
+ //================================
+
+ function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
+ previousCompileContext) {
+ if (!($compileNodes instanceof jqLite)) {
+ // jquery always rewraps, whereas we need to preserve the original selector so that we can
+ // modify it.
+ $compileNodes = jqLite($compileNodes);
+ }
+ // We can not compile top level text elements since text nodes can be merged and we will
+ // not be able to attach scope data to them, so we will wrap them in <span>
+ forEach($compileNodes, function(node, index) {
+ if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
+ $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
+ }
+ });
+ var compositeLinkFn =
+ compileNodes($compileNodes, transcludeFn, $compileNodes,
+ maxPriority, ignoreDirective, previousCompileContext);
+ compile.$$addScopeClass($compileNodes);
+ var namespace = null;
+ return function publicLinkFn(scope, cloneConnectFn, options) {
+ assertArg(scope, 'scope');
+
+ if (previousCompileContext && previousCompileContext.needsNewScope) {
+ // A parent directive did a replace and a directive on this element asked
+ // for transclusion, which caused us to lose a layer of element on which
+ // we could hold the new transclusion scope, so we will create it manually
+ // here.
+ scope = scope.$parent.$new();
+ }
+
+ options = options || {};
+ var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
+ transcludeControllers = options.transcludeControllers,
+ futureParentElement = options.futureParentElement;
+
+ // When `parentBoundTranscludeFn` is passed, it is a
+ // `controllersBoundTransclude` function (it was previously passed
+ // as `transclude` to directive.link) so we must unwrap it to get
+ // its `boundTranscludeFn`
+ if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
+ parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
+ }
+
+ if (!namespace) {
+ namespace = detectNamespaceForChildElements(futureParentElement);
+ }
+ var $linkNode;
+ if (namespace !== 'html') {
+ // When using a directive with replace:true and templateUrl the $compileNodes
+ // (or a child element inside of them)
+ // might change, so we need to recreate the namespace adapted compileNodes
+ // for call to the link function.
+ // Note: This will already clone the nodes...
+ $linkNode = jqLite(
+ wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
+ );
+ } else if (cloneConnectFn) {
+ // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
+ // and sometimes changes the structure of the DOM.
+ $linkNode = JQLitePrototype.clone.call($compileNodes);
+ } else {
+ $linkNode = $compileNodes;
+ }
+
+ if (transcludeControllers) {
+ for (var controllerName in transcludeControllers) {
+ $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
+ }
+ }
+
+ compile.$$addScopeInfo($linkNode, scope);
+
+ if (cloneConnectFn) cloneConnectFn($linkNode, scope);
+ if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
+ return $linkNode;
+ };
+ }
+
+ function detectNamespaceForChildElements(parentElement) {
+ // TODO: Make this detect MathML as well...
+ var node = parentElement && parentElement[0];
+ if (!node) {
+ return 'html';
+ } else {
+ return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
+ }
+ }
+
+ /**
+ * Compile function matches each node in nodeList against the directives. Once all directives
+ * for a particular node are collected their compile functions are executed. The compile
+ * functions return values - the linking functions - are combined into a composite linking
+ * function, which is the a linking function for the node.
+ *
+ * @param {NodeList} nodeList an array of nodes or NodeList to compile
+ * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
+ * scope argument is auto-generated to the new child of the transcluded parent scope.
+ * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
+ * the rootElement must be set the jqLite collection of the compile root. This is
+ * needed so that the jqLite collection items can be replaced with widgets.
+ * @param {number=} maxPriority Max directive priority.
+ * @returns {Function} A composite linking function of all of the matched directives or null.
+ */
+ function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
+ previousCompileContext) {
+ var linkFns = [],
+ attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
+
+ for (var i = 0; i < nodeList.length; i++) {
+ attrs = new Attributes();
+
+ // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
+ directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
+ ignoreDirective);
+
+ nodeLinkFn = (directives.length)
+ ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
+ null, [], [], previousCompileContext)
+ : null;
+
+ if (nodeLinkFn && nodeLinkFn.scope) {
+ compile.$$addScopeClass(attrs.$$element);
+ }
+
+ childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
+ !(childNodes = nodeList[i].childNodes) ||
+ !childNodes.length)
+ ? null
+ : compileNodes(childNodes,
+ nodeLinkFn ? (
+ (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
+ && nodeLinkFn.transclude) : transcludeFn);
+
+ if (nodeLinkFn || childLinkFn) {
+ linkFns.push(i, nodeLinkFn, childLinkFn);
+ linkFnFound = true;
+ nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
+ }
+
+ //use the previous context only for the first element in the virtual group
+ previousCompileContext = null;
+ }
+
+ // return a linking function if we have found anything, null otherwise
+ return linkFnFound ? compositeLinkFn : null;
+
+ function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
+ var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
+ var stableNodeList;
+
+
+ if (nodeLinkFnFound) {
+ // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
+ // offsets don't get screwed up
+ var nodeListLength = nodeList.length;
+ stableNodeList = new Array(nodeListLength);
+
+ // create a sparse array by only copying the elements which have a linkFn
+ for (i = 0; i < linkFns.length; i+=3) {
+ idx = linkFns[i];
+ stableNodeList[idx] = nodeList[idx];
+ }
+ } else {
+ stableNodeList = nodeList;
+ }
+
+ for (i = 0, ii = linkFns.length; i < ii;) {
+ node = stableNodeList[linkFns[i++]];
+ nodeLinkFn = linkFns[i++];
+ childLinkFn = linkFns[i++];
+
+ if (nodeLinkFn) {
+ if (nodeLinkFn.scope) {
+ childScope = scope.$new();
+ compile.$$addScopeInfo(jqLite(node), childScope);
+ } else {
+ childScope = scope;
+ }
+
+ if (nodeLinkFn.transcludeOnThisElement) {
+ childBoundTranscludeFn = createBoundTranscludeFn(
+ scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
+
+ } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
+ childBoundTranscludeFn = parentBoundTranscludeFn;
+
+ } else if (!parentBoundTranscludeFn && transcludeFn) {
+ childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
+
+ } else {
+ childBoundTranscludeFn = null;
+ }
+
+ nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
+
+ } else if (childLinkFn) {
+ childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
+ }
+ }
+ }
+ }
+
+ function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
+
+ var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
+
+ if (!transcludedScope) {
+ transcludedScope = scope.$new(false, containingScope);
+ transcludedScope.$$transcluded = true;
+ }
+
+ return transcludeFn(transcludedScope, cloneFn, {
+ parentBoundTranscludeFn: previousBoundTranscludeFn,
+ transcludeControllers: controllers,
+ futureParentElement: futureParentElement
+ });
+ };
+
+ return boundTranscludeFn;
+ }
+
+ /**
+ * Looks for directives on the given node and adds them to the directive collection which is
+ * sorted.
+ *
+ * @param node Node to search.
+ * @param directives An array to which the directives are added to. This array is sorted before
+ * the function returns.
+ * @param attrs The shared attrs object which is used to populate the normalized attributes.
+ * @param {number=} maxPriority Max directive priority.
+ */
+ function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
+ var nodeType = node.nodeType,
+ attrsMap = attrs.$attr,
+ match,
+ className;
+
+ switch (nodeType) {
+ case NODE_TYPE_ELEMENT: /* Element */
+ // use the node name: <directive>
+ addDirective(directives,
+ directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
+
+ // iterate over the attributes
+ for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
+ j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
+ var attrStartName = false;
+ var attrEndName = false;
+
+ attr = nAttrs[j];
+ name = attr.name;
+ value = trim(attr.value);
+
+ // support ngAttr attribute binding
+ ngAttrName = directiveNormalize(name);
+ if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
+ name = name.replace(PREFIX_REGEXP, '')
+ .substr(8).replace(/_(.)/g, function(match, letter) {
+ return letter.toUpperCase();
+ });
+ }
+
+ var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
+ if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
+ attrStartName = name;
+ attrEndName = name.substr(0, name.length - 5) + 'end';
+ name = name.substr(0, name.length - 6);
+ }
+
+ nName = directiveNormalize(name.toLowerCase());
+ attrsMap[nName] = name;
+ if (isNgAttr || !attrs.hasOwnProperty(nName)) {
+ attrs[nName] = value;
+ if (getBooleanAttrName(node, nName)) {
+ attrs[nName] = true; // presence means true
+ }
+ }
+ addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
+ addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
+ attrEndName);
+ }
+
+ // use class as directive
+ className = node.className;
+ if (isObject(className)) {
+ // Maybe SVGAnimatedString
+ className = className.animVal;
+ }
+ if (isString(className) && className !== '') {
+ while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
+ nName = directiveNormalize(match[2]);
+ if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
+ attrs[nName] = trim(match[3]);
+ }
+ className = className.substr(match.index + match[0].length);
+ }
+ }
+ break;
+ case NODE_TYPE_TEXT: /* Text Node */
+ if (msie === 11) {
+ // Workaround for #11781
+ while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
+ node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
+ node.parentNode.removeChild(node.nextSibling);
+ }
+ }
+ addTextInterpolateDirective(directives, node.nodeValue);
+ break;
+ case NODE_TYPE_COMMENT: /* Comment */
+ try {
+ match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
+ if (match) {
+ nName = directiveNormalize(match[1]);
+ if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
+ attrs[nName] = trim(match[2]);
+ }
+ }
+ } catch (e) {
+ // turns out that under some circumstances IE9 throws errors when one attempts to read
+ // comment's node value.
+ // Just ignore it and continue. (Can't seem to reproduce in test case.)
+ }
+ break;
+ }
+
+ directives.sort(byPriority);
+ return directives;
+ }
+
+ /**
+ * Given a node with an directive-start it collects all of the siblings until it finds
+ * directive-end.
+ * @param node
+ * @param attrStart
+ * @param attrEnd
+ * @returns {*}
+ */
+ function groupScan(node, attrStart, attrEnd) {
+ var nodes = [];
+ var depth = 0;
+ if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
+ do {
+ if (!node) {
+ throw $compileMinErr('uterdir',
+ "Unterminated attribute, found '{0}' but no matching '{1}' found.",
+ attrStart, attrEnd);
+ }
+ if (node.nodeType == NODE_TYPE_ELEMENT) {
+ if (node.hasAttribute(attrStart)) depth++;
+ if (node.hasAttribute(attrEnd)) depth--;
+ }
+ nodes.push(node);
+ node = node.nextSibling;
+ } while (depth > 0);
+ } else {
+ nodes.push(node);
+ }
+
+ return jqLite(nodes);
+ }
+
+ /**
+ * Wrapper for linking function which converts normal linking function into a grouped
+ * linking function.
+ * @param linkFn
+ * @param attrStart
+ * @param attrEnd
+ * @returns {Function}
+ */
+ function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
+ return function(scope, element, attrs, controllers, transcludeFn) {
+ element = groupScan(element[0], attrStart, attrEnd);
+ return linkFn(scope, element, attrs, controllers, transcludeFn);
+ };
+ }
+
+ /**
+ * Once the directives have been collected, their compile functions are executed. This method
+ * is responsible for inlining directive templates as well as terminating the application
+ * of the directives if the terminal directive has been reached.
+ *
+ * @param {Array} directives Array of collected directives to execute their compile function.
+ * this needs to be pre-sorted by priority order.
+ * @param {Node} compileNode The raw DOM node to apply the compile functions to
+ * @param {Object} templateAttrs The shared attribute function
+ * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
+ * scope argument is auto-generated to the new
+ * child of the transcluded parent scope.
+ * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
+ * argument has the root jqLite array so that we can replace nodes
+ * on it.
+ * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
+ * compiling the transclusion.
+ * @param {Array.<Function>} preLinkFns
+ * @param {Array.<Function>} postLinkFns
+ * @param {Object} previousCompileContext Context used for previous compilation of the current
+ * node
+ * @returns {Function} linkFn
+ */
+ function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
+ jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
+ previousCompileContext) {
+ previousCompileContext = previousCompileContext || {};
+
+ var terminalPriority = -Number.MAX_VALUE,
+ newScopeDirective = previousCompileContext.newScopeDirective,
+ controllerDirectives = previousCompileContext.controllerDirectives,
+ newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
+ templateDirective = previousCompileContext.templateDirective,
+ nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
+ hasTranscludeDirective = false,
+ hasTemplate = false,
+ hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
+ $compileNode = templateAttrs.$$element = jqLite(compileNode),
+ directive,
+ directiveName,
+ $template,
+ replaceDirective = originalReplaceDirective,
+ childTranscludeFn = transcludeFn,
+ linkFn,
+ directiveValue;
+
+ // executes all directives on the current element
+ for (var i = 0, ii = directives.length; i < ii; i++) {
+ directive = directives[i];
+ var attrStart = directive.$$start;
+ var attrEnd = directive.$$end;
+
+ // collect multiblock sections
+ if (attrStart) {
+ $compileNode = groupScan(compileNode, attrStart, attrEnd);
+ }
+ $template = undefined;
+
+ if (terminalPriority > directive.priority) {
+ break; // prevent further processing of directives
+ }
+
+ if (directiveValue = directive.scope) {
+
+ // skip the check for directives with async templates, we'll check the derived sync
+ // directive when the template arrives
+ if (!directive.templateUrl) {
+ if (isObject(directiveValue)) {
+ // This directive is trying to add an isolated scope.
+ // Check that there is no scope of any kind already
+ assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
+ directive, $compileNode);
+ newIsolateScopeDirective = directive;
+ } else {
+ // This directive is trying to add a child scope.
+ // Check that there is no isolated scope already
+ assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
+ $compileNode);
+ }
+ }
+
+ newScopeDirective = newScopeDirective || directive;
+ }
+
+ directiveName = directive.name;
+
+ if (!directive.templateUrl && directive.controller) {
+ directiveValue = directive.controller;
+ controllerDirectives = controllerDirectives || createMap();
+ assertNoDuplicate("'" + directiveName + "' controller",
+ controllerDirectives[directiveName], directive, $compileNode);
+ controllerDirectives[directiveName] = directive;
+ }
+
+ if (directiveValue = directive.transclude) {
+ hasTranscludeDirective = true;
+
+ // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
+ // This option should only be used by directives that know how to safely handle element transclusion,
+ // where the transcluded nodes are added or replaced after linking.
+ if (!directive.$$tlb) {
+ assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
+ nonTlbTranscludeDirective = directive;
+ }
+
+ if (directiveValue == 'element') {
+ hasElementTranscludeDirective = true;
+ terminalPriority = directive.priority;
+ $template = $compileNode;
+ $compileNode = templateAttrs.$$element =
+ jqLite(document.createComment(' ' + directiveName + ': ' +
+ templateAttrs[directiveName] + ' '));
+ compileNode = $compileNode[0];
+ replaceWith(jqCollection, sliceArgs($template), compileNode);
+
+ childTranscludeFn = compile($template, transcludeFn, terminalPriority,
+ replaceDirective && replaceDirective.name, {
+ // Don't pass in:
+ // - controllerDirectives - otherwise we'll create duplicates controllers
+ // - newIsolateScopeDirective or templateDirective - combining templates with
+ // element transclusion doesn't make sense.
+ //
+ // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
+ // on the same element more than once.
+ nonTlbTranscludeDirective: nonTlbTranscludeDirective
+ });
+ } else {
+ $template = jqLite(jqLiteClone(compileNode)).contents();
+ $compileNode.empty(); // clear contents
+ childTranscludeFn = compile($template, transcludeFn, undefined,
+ undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
+ }
+ }
+
+ if (directive.template) {
+ hasTemplate = true;
+ assertNoDuplicate('template', templateDirective, directive, $compileNode);
+ templateDirective = directive;
+
+ directiveValue = (isFunction(directive.template))
+ ? directive.template($compileNode, templateAttrs)
+ : directive.template;
+
+ directiveValue = denormalizeTemplate(directiveValue);
+
+ if (directive.replace) {
+ replaceDirective = directive;
+ if (jqLiteIsTextNode(directiveValue)) {
+ $template = [];
+ } else {
+ $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
+ }
+ compileNode = $template[0];
+
+ if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
+ throw $compileMinErr('tplrt',
+ "Template for directive '{0}' must have exactly one root element. {1}",
+ directiveName, '');
+ }
+
+ replaceWith(jqCollection, $compileNode, compileNode);
+
+ var newTemplateAttrs = {$attr: {}};
+
+ // combine directives from the original node and from the template:
+ // - take the array of directives for this element
+ // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
+ // - collect directives from the template and sort them by priority
+ // - combine directives as: processed + template + unprocessed
+ var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
+ var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
+
+ if (newIsolateScopeDirective || newScopeDirective) {
+ // The original directive caused the current element to be replaced but this element
+ // also needs to have a new scope, so we need to tell the template directives
+ // that they would need to get their scope from further up, if they require transclusion
+ markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
+ }
+ directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
+ mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
+
+ ii = directives.length;
+ } else {
+ $compileNode.html(directiveValue);
+ }
+ }
+
+ if (directive.templateUrl) {
+ hasTemplate = true;
+ assertNoDuplicate('template', templateDirective, directive, $compileNode);
+ templateDirective = directive;
+
+ if (directive.replace) {
+ replaceDirective = directive;
+ }
+
+ nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
+ templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
+ controllerDirectives: controllerDirectives,
+ newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
+ newIsolateScopeDirective: newIsolateScopeDirective,
+ templateDirective: templateDirective,
+ nonTlbTranscludeDirective: nonTlbTranscludeDirective
+ });
+ ii = directives.length;
+ } else if (directive.compile) {
+ try {
+ linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
+ if (isFunction(linkFn)) {
+ addLinkFns(null, linkFn, attrStart, attrEnd);
+ } else if (linkFn) {
+ addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
+ }
+ } catch (e) {
+ $exceptionHandler(e, startingTag($compileNode));
+ }
+ }
+
+ if (directive.terminal) {
+ nodeLinkFn.terminal = true;
+ terminalPriority = Math.max(terminalPriority, directive.priority);
+ }
+
+ }
+
+ nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
+ nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
+ nodeLinkFn.templateOnThisElement = hasTemplate;
+ nodeLinkFn.transclude = childTranscludeFn;
+
+ previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
+
+ // might be normal or delayed nodeLinkFn depending on if templateUrl is present
+ return nodeLinkFn;
+
+ ////////////////////
+
+ function addLinkFns(pre, post, attrStart, attrEnd) {
+ if (pre) {
+ if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
+ pre.require = directive.require;
+ pre.directiveName = directiveName;
+ if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
+ pre = cloneAndAnnotateFn(pre, {isolateScope: true});
+ }
+ preLinkFns.push(pre);
+ }
+ if (post) {
+ if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
+ post.require = directive.require;
+ post.directiveName = directiveName;
+ if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
+ post = cloneAndAnnotateFn(post, {isolateScope: true});
+ }
+ postLinkFns.push(post);
+ }
+ }
+
+
+ function getControllers(directiveName, require, $element, elementControllers) {
+ var value;
+
+ if (isString(require)) {
+ var match = require.match(REQUIRE_PREFIX_REGEXP);
+ var name = require.substring(match[0].length);
+ var inheritType = match[1] || match[3];
+ var optional = match[2] === '?';
+
+ //If only parents then start at the parent element
+ if (inheritType === '^^') {
+ $element = $element.parent();
+ //Otherwise attempt getting the controller from elementControllers in case
+ //the element is transcluded (and has no data) and to avoid .data if possible
+ } else {
+ value = elementControllers && elementControllers[name];
+ value = value && value.instance;
+ }
+
+ if (!value) {
+ var dataName = '$' + name + 'Controller';
+ value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
+ }
+
+ if (!value && !optional) {
+ throw $compileMinErr('ctreq',
+ "Controller '{0}', required by directive '{1}', can't be found!",
+ name, directiveName);
+ }
+ } else if (isArray(require)) {
+ value = [];
+ for (var i = 0, ii = require.length; i < ii; i++) {
+ value[i] = getControllers(directiveName, require[i], $element, elementControllers);
+ }
+ }
+
+ return value || null;
+ }
+
+ function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
+ var elementControllers = createMap();
+ for (var controllerKey in controllerDirectives) {
+ var directive = controllerDirectives[controllerKey];
+ var locals = {
+ $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
+ $element: $element,
+ $attrs: attrs,
+ $transclude: transcludeFn
+ };
+
+ var controller = directive.controller;
+ if (controller == '@') {
+ controller = attrs[directive.name];
+ }
+
+ var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
+
+ // For directives with element transclusion the element is a comment,
+ // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
+ // clean up (http://bugs.jquery.com/ticket/8335).
+ // Instead, we save the controllers for the element in a local hash and attach to .data
+ // later, once we have the actual element.
+ elementControllers[directive.name] = controllerInstance;
+ if (!hasElementTranscludeDirective) {
+ $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
+ }
+ }
+ return elementControllers;
+ }
+
+ function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
+ var linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
+ attrs, removeScopeBindingWatches, removeControllerBindingWatches;
+
+ if (compileNode === linkNode) {
+ attrs = templateAttrs;
+ $element = templateAttrs.$$element;
+ } else {
+ $element = jqLite(linkNode);
+ attrs = new Attributes($element, templateAttrs);
+ }
+
+ controllerScope = scope;
+ if (newIsolateScopeDirective) {
+ isolateScope = scope.$new(true);
+ } else if (newScopeDirective) {
+ controllerScope = scope.$parent;
+ }
+
+ if (boundTranscludeFn) {
+ // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
+ // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
+ transcludeFn = controllersBoundTransclude;
+ transcludeFn.$$boundTransclude = boundTranscludeFn;
+ }
+
+ if (controllerDirectives) {
+ elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
+ }
+
+ if (newIsolateScopeDirective) {
+ // Initialize isolate scope bindings for new isolate scope directive.
+ compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
+ templateDirective === newIsolateScopeDirective.$$originalDirective)));
+ compile.$$addScopeClass($element, true);
+ isolateScope.$$isolateBindings =
+ newIsolateScopeDirective.$$isolateBindings;
+ removeScopeBindingWatches = initializeDirectiveBindings(scope, attrs, isolateScope,
+ isolateScope.$$isolateBindings,
+ newIsolateScopeDirective);
+ if (removeScopeBindingWatches) {
+ isolateScope.$on('$destroy', removeScopeBindingWatches);
+ }
+ }
+
+ // Initialize bindToController bindings
+ for (var name in elementControllers) {
+ var controllerDirective = controllerDirectives[name];
+ var controller = elementControllers[name];
+ var bindings = controllerDirective.$$bindings.bindToController;
+
+ if (controller.identifier && bindings) {
+ removeControllerBindingWatches =
+ initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
+ }
+
+ var controllerResult = controller();
+ if (controllerResult !== controller.instance) {
+ // If the controller constructor has a return value, overwrite the instance
+ // from setupControllers
+ controller.instance = controllerResult;
+ $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
+ removeControllerBindingWatches && removeControllerBindingWatches();
+ removeControllerBindingWatches =
+ initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
+ }
+ }
+
+ // PRELINKING
+ for (i = 0, ii = preLinkFns.length; i < ii; i++) {
+ linkFn = preLinkFns[i];
+ invokeLinkFn(linkFn,
+ linkFn.isolateScope ? isolateScope : scope,
+ $element,
+ attrs,
+ linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
+ transcludeFn
+ );
+ }
+
+ // RECURSION
+ // We only pass the isolate scope, if the isolate directive has a template,
+ // otherwise the child elements do not belong to the isolate directive.
+ var scopeToChild = scope;
+ if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
+ scopeToChild = isolateScope;
+ }
+ childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
+
+ // POSTLINKING
+ for (i = postLinkFns.length - 1; i >= 0; i--) {
+ linkFn = postLinkFns[i];
+ invokeLinkFn(linkFn,
+ linkFn.isolateScope ? isolateScope : scope,
+ $element,
+ attrs,
+ linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
+ transcludeFn
+ );
+ }
+
+ // This is the function that is injected as `$transclude`.
+ // Note: all arguments are optional!
+ function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
+ var transcludeControllers;
+
+ // No scope passed in:
+ if (!isScope(scope)) {
+ futureParentElement = cloneAttachFn;
+ cloneAttachFn = scope;
+ scope = undefined;
+ }
+
+ if (hasElementTranscludeDirective) {
+ transcludeControllers = elementControllers;
+ }
+ if (!futureParentElement) {
+ futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
+ }
+ return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
+ }
+ }
+ }
+
+ // Depending upon the context in which a directive finds itself it might need to have a new isolated
+ // or child scope created. For instance:
+ // * if the directive has been pulled into a template because another directive with a higher priority
+ // asked for element transclusion
+ // * if the directive itself asks for transclusion but it is at the root of a template and the original
+ // element was replaced. See https://github.com/angular/angular.js/issues/12936
+ function markDirectiveScope(directives, isolateScope, newScope) {
+ for (var j = 0, jj = directives.length; j < jj; j++) {
+ directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
+ }
+ }
+
+ /**
+ * looks up the directive and decorates it with exception handling and proper parameters. We
+ * call this the boundDirective.
+ *
+ * @param {string} name name of the directive to look up.
+ * @param {string} location The directive must be found in specific format.
+ * String containing any of theses characters:
+ *
+ * * `E`: element name
+ * * `A': attribute
+ * * `C`: class
+ * * `M`: comment
+ * @returns {boolean} true if directive was added.
+ */
+ function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
+ endAttrName) {
+ if (name === ignoreDirective) return null;
+ var match = null;
+ if (hasDirectives.hasOwnProperty(name)) {
+ for (var directive, directives = $injector.get(name + Suffix),
+ i = 0, ii = directives.length; i < ii; i++) {
+ try {
+ directive = directives[i];
+ if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
+ directive.restrict.indexOf(location) != -1) {
+ if (startAttrName) {
+ directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
+ }
+ tDirectives.push(directive);
+ match = directive;
+ }
+ } catch (e) { $exceptionHandler(e); }
+ }
+ }
+ return match;
+ }
+
+
+ /**
+ * looks up the directive and returns true if it is a multi-element directive,
+ * and therefore requires DOM nodes between -start and -end markers to be grouped
+ * together.
+ *
+ * @param {string} name name of the directive to look up.
+ * @returns true if directive was registered as multi-element.
+ */
+ function directiveIsMultiElement(name) {
+ if (hasDirectives.hasOwnProperty(name)) {
+ for (var directive, directives = $injector.get(name + Suffix),
+ i = 0, ii = directives.length; i < ii; i++) {
+ directive = directives[i];
+ if (directive.multiElement) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * When the element is replaced with HTML template then the new attributes
+ * on the template need to be merged with the existing attributes in the DOM.
+ * The desired effect is to have both of the attributes present.
+ *
+ * @param {object} dst destination attributes (original DOM)
+ * @param {object} src source attributes (from the directive template)
+ */
+ function mergeTemplateAttributes(dst, src) {
+ var srcAttr = src.$attr,
+ dstAttr = dst.$attr,
+ $element = dst.$$element;
+
+ // reapply the old attributes to the new element
+ forEach(dst, function(value, key) {
+ if (key.charAt(0) != '$') {
+ if (src[key] && src[key] !== value) {
+ value += (key === 'style' ? ';' : ' ') + src[key];
+ }
+ dst.$set(key, value, true, srcAttr[key]);
+ }
+ });
+
+ // copy the new attributes on the old attrs object
+ forEach(src, function(value, key) {
+ if (key == 'class') {
+ safeAddClass($element, value);
+ dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
+ } else if (key == 'style') {
+ $element.attr('style', $element.attr('style') + ';' + value);
+ dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
+ // `dst` will never contain hasOwnProperty as DOM parser won't let it.
+ // You will get an "InvalidCharacterError: DOM Exception 5" error if you
+ // have an attribute like "has-own-property" or "data-has-own-property", etc.
+ } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
+ dst[key] = value;
+ dstAttr[key] = srcAttr[key];
+ }
+ });
+ }
+
+
+ function compileTemplateUrl(directives, $compileNode, tAttrs,
+ $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
+ var linkQueue = [],
+ afterTemplateNodeLinkFn,
+ afterTemplateChildLinkFn,
+ beforeTemplateCompileNode = $compileNode[0],
+ origAsyncDirective = directives.shift(),
+ derivedSyncDirective = inherit(origAsyncDirective, {
+ templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
+ }),
+ templateUrl = (isFunction(origAsyncDirective.templateUrl))
+ ? origAsyncDirective.templateUrl($compileNode, tAttrs)
+ : origAsyncDirective.templateUrl,
+ templateNamespace = origAsyncDirective.templateNamespace;
+
+ $compileNode.empty();
+
+ $templateRequest(templateUrl)
+ .then(function(content) {
+ var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
+
+ content = denormalizeTemplate(content);
+
+ if (origAsyncDirective.replace) {
+ if (jqLiteIsTextNode(content)) {
+ $template = [];
+ } else {
+ $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
+ }
+ compileNode = $template[0];
+
+ if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
+ throw $compileMinErr('tplrt',
+ "Template for directive '{0}' must have exactly one root element. {1}",
+ origAsyncDirective.name, templateUrl);
+ }
+
+ tempTemplateAttrs = {$attr: {}};
+ replaceWith($rootElement, $compileNode, compileNode);
+ var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
+
+ if (isObject(origAsyncDirective.scope)) {
+ // the original directive that caused the template to be loaded async required
+ // an isolate scope
+ markDirectiveScope(templateDirectives, true);
+ }
+ directives = templateDirectives.concat(directives);
+ mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
+ } else {
+ compileNode = beforeTemplateCompileNode;
+ $compileNode.html(content);
+ }
+
+ directives.unshift(derivedSyncDirective);
+
+ afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
+ childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
+ previousCompileContext);
+ forEach($rootElement, function(node, i) {
+ if (node == compileNode) {
+ $rootElement[i] = $compileNode[0];
+ }
+ });
+ afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
+
+ while (linkQueue.length) {
+ var scope = linkQueue.shift(),
+ beforeTemplateLinkNode = linkQueue.shift(),
+ linkRootElement = linkQueue.shift(),
+ boundTranscludeFn = linkQueue.shift(),
+ linkNode = $compileNode[0];
+
+ if (scope.$$destroyed) continue;
+
+ if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
+ var oldClasses = beforeTemplateLinkNode.className;
+
+ if (!(previousCompileContext.hasElementTranscludeDirective &&
+ origAsyncDirective.replace)) {
+ // it was cloned therefore we have to clone as well.
+ linkNode = jqLiteClone(compileNode);
+ }
+ replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
+
+ // Copy in CSS classes from original node
+ safeAddClass(jqLite(linkNode), oldClasses);
+ }
+ if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
+ childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
+ } else {
+ childBoundTranscludeFn = boundTranscludeFn;
+ }
+ afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
+ childBoundTranscludeFn);
+ }
+ linkQueue = null;
+ });
+
+ return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
+ var childBoundTranscludeFn = boundTranscludeFn;
+ if (scope.$$destroyed) return;
+ if (linkQueue) {
+ linkQueue.push(scope,
+ node,
+ rootElement,
+ childBoundTranscludeFn);
+ } else {
+ if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
+ childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
+ }
+ afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
+ }
+ };
+ }
+
+
+ /**
+ * Sorting function for bound directives.
+ */
+ function byPriority(a, b) {
+ var diff = b.priority - a.priority;
+ if (diff !== 0) return diff;
+ if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
+ return a.index - b.index;
+ }
+
+ function assertNoDuplicate(what, previousDirective, directive, element) {
+
+ function wrapModuleNameIfDefined(moduleName) {
+ return moduleName ?
+ (' (module: ' + moduleName + ')') :
+ '';
+ }
+
+ if (previousDirective) {
+ throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
+ previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
+ directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
+ }
+ }
+
+
+ function addTextInterpolateDirective(directives, text) {
+ var interpolateFn = $interpolate(text, true);
+ if (interpolateFn) {
+ directives.push({
+ priority: 0,
+ compile: function textInterpolateCompileFn(templateNode) {
+ var templateNodeParent = templateNode.parent(),
+ hasCompileParent = !!templateNodeParent.length;
+
+ // When transcluding a template that has bindings in the root
+ // we don't have a parent and thus need to add the class during linking fn.
+ if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
+
+ return function textInterpolateLinkFn(scope, node) {
+ var parent = node.parent();
+ if (!hasCompileParent) compile.$$addBindingClass(parent);
+ compile.$$addBindingInfo(parent, interpolateFn.expressions);
+ scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
+ node[0].nodeValue = value;
+ });
+ };
+ }
+ });
+ }
+ }
+
+
+ function wrapTemplate(type, template) {
+ type = lowercase(type || 'html');
+ switch (type) {
+ case 'svg':
+ case 'math':
+ var wrapper = document.createElement('div');
+ wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
+ return wrapper.childNodes[0].childNodes;
+ default:
+ return template;
+ }
+ }
+
+
+ function getTrustedContext(node, attrNormalizedName) {
+ if (attrNormalizedName == "srcdoc") {
+ return $sce.HTML;
+ }
+ var tag = nodeName_(node);
+ // maction[xlink:href] can source SVG. It's not limited to <maction>.
+ if (attrNormalizedName == "xlinkHref" ||
+ (tag == "form" && attrNormalizedName == "action") ||
+ (tag != "img" && (attrNormalizedName == "src" ||
+ attrNormalizedName == "ngSrc"))) {
+ return $sce.RESOURCE_URL;
+ }
+ }
+
+
+ function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
+ var trustedContext = getTrustedContext(node, name);
+ allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
+
+ var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
+
+ // no interpolation found -> ignore
+ if (!interpolateFn) return;
+
+
+ if (name === "multiple" && nodeName_(node) === "select") {
+ throw $compileMinErr("selmulti",
+ "Binding to the 'multiple' attribute is not supported. Element: {0}",
+ startingTag(node));
+ }
+
+ directives.push({
+ priority: 100,
+ compile: function() {
+ return {
+ pre: function attrInterpolatePreLinkFn(scope, element, attr) {
+ var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
+
+ if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
+ throw $compileMinErr('nodomevents',
+ "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
+ "ng- versions (such as ng-click instead of onclick) instead.");
+ }
+
+ // If the attribute has changed since last $interpolate()ed
+ var newValue = attr[name];
+ if (newValue !== value) {
+ // we need to interpolate again since the attribute value has been updated
+ // (e.g. by another directive's compile function)
+ // ensure unset/empty values make interpolateFn falsy
+ interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
+ value = newValue;
+ }
+
+ // if attribute was updated so that there is no interpolation going on we don't want to
+ // register any observers
+ if (!interpolateFn) return;
+
+ // initialize attr object so that it's ready in case we need the value for isolate
+ // scope initialization, otherwise the value would not be available from isolate
+ // directive's linking fn during linking phase
+ attr[name] = interpolateFn(scope);
+
+ ($$observers[name] || ($$observers[name] = [])).$$inter = true;
+ (attr.$$observers && attr.$$observers[name].$$scope || scope).
+ $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
+ //special case for class attribute addition + removal
+ //so that class changes can tap into the animation
+ //hooks provided by the $animate service. Be sure to
+ //skip animations when the first digest occurs (when
+ //both the new and the old values are the same) since
+ //the CSS classes are the non-interpolated values
+ if (name === 'class' && newValue != oldValue) {
+ attr.$updateClass(newValue, oldValue);
+ } else {
+ attr.$set(name, newValue);
+ }
+ });
+ }
+ };
+ }
+ });
+ }
+
+
+ /**
+ * This is a special jqLite.replaceWith, which can replace items which
+ * have no parents, provided that the containing jqLite collection is provided.
+ *
+ * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
+ * in the root of the tree.
+ * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
+ * the shell, but replace its DOM node reference.
+ * @param {Node} newNode The new DOM node.
+ */
+ function replaceWith($rootElement, elementsToRemove, newNode) {
+ var firstElementToRemove = elementsToRemove[0],
+ removeCount = elementsToRemove.length,
+ parent = firstElementToRemove.parentNode,
+ i, ii;
+
+ if ($rootElement) {
+ for (i = 0, ii = $rootElement.length; i < ii; i++) {
+ if ($rootElement[i] == firstElementToRemove) {
+ $rootElement[i++] = newNode;
+ for (var j = i, j2 = j + removeCount - 1,
+ jj = $rootElement.length;
+ j < jj; j++, j2++) {
+ if (j2 < jj) {
+ $rootElement[j] = $rootElement[j2];
+ } else {
+ delete $rootElement[j];
+ }
+ }
+ $rootElement.length -= removeCount - 1;
+
+ // If the replaced element is also the jQuery .context then replace it
+ // .context is a deprecated jQuery api, so we should set it only when jQuery set it
+ // http://api.jquery.com/context/
+ if ($rootElement.context === firstElementToRemove) {
+ $rootElement.context = newNode;
+ }
+ break;
+ }
+ }
+ }
+
+ if (parent) {
+ parent.replaceChild(newNode, firstElementToRemove);
+ }
+
+ // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
+ var fragment = document.createDocumentFragment();
+ fragment.appendChild(firstElementToRemove);
+
+ if (jqLite.hasData(firstElementToRemove)) {
+ // Copy over user data (that includes Angular's $scope etc.). Don't copy private
+ // data here because there's no public interface in jQuery to do that and copying over
+ // event listeners (which is the main use of private data) wouldn't work anyway.
+ jqLite.data(newNode, jqLite.data(firstElementToRemove));
+
+ // Remove data of the replaced element. We cannot just call .remove()
+ // on the element it since that would deallocate scope that is needed
+ // for the new node. Instead, remove the data "manually".
+ if (!jQuery) {
+ delete jqLite.cache[firstElementToRemove[jqLite.expando]];
+ } else {
+ // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
+ // the replaced element. The cleanData version monkey-patched by Angular would cause
+ // the scope to be trashed and we do need the very same scope to work with the new
+ // element. However, we cannot just cache the non-patched version and use it here as
+ // that would break if another library patches the method after Angular does (one
+ // example is jQuery UI). Instead, set a flag indicating scope destroying should be
+ // skipped this one time.
+ skipDestroyOnNextJQueryCleanData = true;
+ jQuery.cleanData([firstElementToRemove]);
+ }
+ }
+
+ for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
+ var element = elementsToRemove[k];
+ jqLite(element).remove(); // must do this way to clean up expando
+ fragment.appendChild(element);
+ delete elementsToRemove[k];
+ }
+
+ elementsToRemove[0] = newNode;
+ elementsToRemove.length = 1;
+ }
+
+
+ function cloneAndAnnotateFn(fn, annotation) {
+ return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
+ }
+
+
+ function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
+ try {
+ linkFn(scope, $element, attrs, controllers, transcludeFn);
+ } catch (e) {
+ $exceptionHandler(e, startingTag($element));
+ }
+ }
+
+
+ // Set up $watches for isolate scope and controller bindings. This process
+ // only occurs for isolate scopes and new scopes with controllerAs.
+ function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
+ var removeWatchCollection = [];
+ forEach(bindings, function(definition, scopeName) {
+ var attrName = definition.attrName,
+ optional = definition.optional,
+ mode = definition.mode, // @, =, or &
+ lastValue,
+ parentGet, parentSet, compare;
+
+ switch (mode) {
+
+ case '@':
+ if (!optional && !hasOwnProperty.call(attrs, attrName)) {
+ destination[scopeName] = attrs[attrName] = void 0;
+ }
+ attrs.$observe(attrName, function(value) {
+ if (isString(value)) {
+ destination[scopeName] = value;
+ }
+ });
+ attrs.$$observers[attrName].$$scope = scope;
+ if (isString(attrs[attrName])) {
+ // If the attribute has been provided then we trigger an interpolation to ensure
+ // the value is there for use in the link fn
+ destination[scopeName] = $interpolate(attrs[attrName])(scope);
+ }
+ break;
+
+ case '=':
+ if (!hasOwnProperty.call(attrs, attrName)) {
+ if (optional) break;
+ attrs[attrName] = void 0;
+ }
+ if (optional && !attrs[attrName]) break;
+
+ parentGet = $parse(attrs[attrName]);
+ if (parentGet.literal) {
+ compare = equals;
+ } else {
+ compare = function(a, b) { return a === b || (a !== a && b !== b); };
+ }
+ parentSet = parentGet.assign || function() {
+ // reset the change, or we will throw this exception on every $digest
+ lastValue = destination[scopeName] = parentGet(scope);
+ throw $compileMinErr('nonassign',
+ "Expression '{0}' used with directive '{1}' is non-assignable!",
+ attrs[attrName], directive.name);
+ };
+ lastValue = destination[scopeName] = parentGet(scope);
+ var parentValueWatch = function parentValueWatch(parentValue) {
+ if (!compare(parentValue, destination[scopeName])) {
+ // we are out of sync and need to copy
+ if (!compare(parentValue, lastValue)) {
+ // parent changed and it has precedence
+ destination[scopeName] = parentValue;
+ } else {
+ // if the parent can be assigned then do so
+ parentSet(scope, parentValue = destination[scopeName]);
+ }
+ }
+ return lastValue = parentValue;
+ };
+ parentValueWatch.$stateful = true;
+ var removeWatch;
+ if (definition.collection) {
+ removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
+ } else {
+ removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
+ }
+ removeWatchCollection.push(removeWatch);
+ break;
+
+ case '&':
+ // Don't assign Object.prototype method to scope
+ parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
+
+ // Don't assign noop to destination if expression is not valid
+ if (parentGet === noop && optional) break;
+
+ destination[scopeName] = function(locals) {
+ return parentGet(scope, locals);
+ };
+ break;
+ }
+ });
+
+ return removeWatchCollection.length && function removeWatches() {
+ for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
+ removeWatchCollection[i]();
+ }
+ };
+ }
+ }];
+}
+
+var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
+/**
+ * Converts all accepted directives format into proper directive name.
+ * @param name Name to normalize
+ */
+function directiveNormalize(name) {
+ return camelCase(name.replace(PREFIX_REGEXP, ''));
+}
+
+/**
+ * @ngdoc type
+ * @name $compile.directive.Attributes
+ *
+ * @description
+ * A shared object between directive compile / linking functions which contains normalized DOM
+ * element attributes. The values reflect current binding state `{{ }}`. The normalization is
+ * needed since all of these are treated as equivalent in Angular:
+ *
+ * ```
+ * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
+ * ```
+ */
+
+/**
+ * @ngdoc property
+ * @name $compile.directive.Attributes#$attr
+ *
+ * @description
+ * A map of DOM element attribute names to the normalized name. This is
+ * needed to do reverse lookup from normalized name back to actual name.
+ */
+
+
+/**
+ * @ngdoc method
+ * @name $compile.directive.Attributes#$set
+ * @kind function
+ *
+ * @description
+ * Set DOM element attribute value.
+ *
+ *
+ * @param {string} name Normalized element attribute name of the property to modify. The name is
+ * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
+ * property to the original name.
+ * @param {string} value Value to set the attribute to. The value can be an interpolated string.
+ */
+
+
+
+/**
+ * Closure compiler type information
+ */
+
+function nodesetLinkingFn(
+ /* angular.Scope */ scope,
+ /* NodeList */ nodeList,
+ /* Element */ rootElement,
+ /* function(Function) */ boundTranscludeFn
+) {}
+
+function directiveLinkingFn(
+ /* nodesetLinkingFn */ nodesetLinkingFn,
+ /* angular.Scope */ scope,
+ /* Node */ node,
+ /* Element */ rootElement,
+ /* function(Function) */ boundTranscludeFn
+) {}
+
+function tokenDifference(str1, str2) {
+ var values = '',
+ tokens1 = str1.split(/\s+/),
+ tokens2 = str2.split(/\s+/);
+
+ outer:
+ for (var i = 0; i < tokens1.length; i++) {
+ var token = tokens1[i];
+ for (var j = 0; j < tokens2.length; j++) {
+ if (token == tokens2[j]) continue outer;
+ }
+ values += (values.length > 0 ? ' ' : '') + token;
+ }
+ return values;
+}
+
+function removeComments(jqNodes) {
+ jqNodes = jqLite(jqNodes);
+ var i = jqNodes.length;
+
+ if (i <= 1) {
+ return jqNodes;
+ }
+
+ while (i--) {
+ var node = jqNodes[i];
+ if (node.nodeType === NODE_TYPE_COMMENT) {
+ splice.call(jqNodes, i, 1);
+ }
+ }
+ return jqNodes;
+}
+
+var $controllerMinErr = minErr('$controller');
+
+
+var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
+function identifierForController(controller, ident) {
+ if (ident && isString(ident)) return ident;
+ if (isString(controller)) {
+ var match = CNTRL_REG.exec(controller);
+ if (match) return match[3];
+ }
+}
+
+
+/**
+ * @ngdoc provider
+ * @name $controllerProvider
+ * @description
+ * The {@link ng.$controller $controller service} is used by Angular to create new
+ * controllers.
+ *
+ * This provider allows controller registration via the
+ * {@link ng.$controllerProvider#register register} method.
+ */
+function $ControllerProvider() {
+ var controllers = {},
+ globals = false;
+
+ /**
+ * @ngdoc method
+ * @name $controllerProvider#register
+ * @param {string|Object} name Controller name, or an object map of controllers where the keys are
+ * the names and the values are the constructors.
+ * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
+ * annotations in the array notation).
+ */
+ this.register = function(name, constructor) {
+ assertNotHasOwnProperty(name, 'controller');
+ if (isObject(name)) {
+ extend(controllers, name);
+ } else {
+ controllers[name] = constructor;
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name $controllerProvider#allowGlobals
+ * @description If called, allows `$controller` to find controller constructors on `window`
+ */
+ this.allowGlobals = function() {
+ globals = true;
+ };
+
+
+ this.$get = ['$injector', '$window', function($injector, $window) {
+
+ /**
+ * @ngdoc service
+ * @name $controller
+ * @requires $injector
+ *
+ * @param {Function|string} constructor If called with a function then it's considered to be the
+ * controller constructor function. Otherwise it's considered to be a string which is used
+ * to retrieve the controller constructor using the following steps:
+ *
+ * * check if a controller with given name is registered via `$controllerProvider`
+ * * check if evaluating the string on the current scope returns a constructor
+ * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
+ * `window` object (not recommended)
+ *
+ * The string can use the `controller as property` syntax, where the controller instance is published
+ * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
+ * to work correctly.
+ *
+ * @param {Object} locals Injection locals for Controller.
+ * @return {Object} Instance of given controller.
+ *
+ * @description
+ * `$controller` service is responsible for instantiating controllers.
+ *
+ * It's just a simple call to {@link auto.$injector $injector}, but extracted into
+ * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
+ */
+ return function(expression, locals, later, ident) {
+ // PRIVATE API:
+ // param `later` --- indicates that the controller's constructor is invoked at a later time.
+ // If true, $controller will allocate the object with the correct
+ // prototype chain, but will not invoke the controller until a returned
+ // callback is invoked.
+ // param `ident` --- An optional label which overrides the label parsed from the controller
+ // expression, if any.
+ var instance, match, constructor, identifier;
+ later = later === true;
+ if (ident && isString(ident)) {
+ identifier = ident;
+ }
+
+ if (isString(expression)) {
+ match = expression.match(CNTRL_REG);
+ if (!match) {
+ throw $controllerMinErr('ctrlfmt',
+ "Badly formed controller string '{0}'. " +
+ "Must match `__name__ as __id__` or `__name__`.", expression);
+ }
+ constructor = match[1],
+ identifier = identifier || match[3];
+ expression = controllers.hasOwnProperty(constructor)
+ ? controllers[constructor]
+ : getter(locals.$scope, constructor, true) ||
+ (globals ? getter($window, constructor, true) : undefined);
+
+ assertArgFn(expression, constructor, true);
+ }
+
+ if (later) {
+ // Instantiate controller later:
+ // This machinery is used to create an instance of the object before calling the
+ // controller's constructor itself.
+ //
+ // This allows properties to be added to the controller before the constructor is
+ // invoked. Primarily, this is used for isolate scope bindings in $compile.
+ //
+ // This feature is not intended for use by applications, and is thus not documented
+ // publicly.
+ // Object creation: http://jsperf.com/create-constructor/2
+ var controllerPrototype = (isArray(expression) ?
+ expression[expression.length - 1] : expression).prototype;
+ instance = Object.create(controllerPrototype || null);
+
+ if (identifier) {
+ addIdentifier(locals, identifier, instance, constructor || expression.name);
+ }
+
+ var instantiate;
+ return instantiate = extend(function() {
+ var result = $injector.invoke(expression, instance, locals, constructor);
+ if (result !== instance && (isObject(result) || isFunction(result))) {
+ instance = result;
+ if (identifier) {
+ // If result changed, re-assign controllerAs value to scope.
+ addIdentifier(locals, identifier, instance, constructor || expression.name);
+ }
+ }
+ return instance;
+ }, {
+ instance: instance,
+ identifier: identifier
+ });
+ }
+
+ instance = $injector.instantiate(expression, locals, constructor);
+
+ if (identifier) {
+ addIdentifier(locals, identifier, instance, constructor || expression.name);
+ }
+
+ return instance;
+ };
+
+ function addIdentifier(locals, identifier, instance, name) {
+ if (!(locals && isObject(locals.$scope))) {
+ throw minErr('$controller')('noscp',
+ "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
+ name, identifier);
+ }
+
+ locals.$scope[identifier] = instance;
+ }
+ }];
+}
+
+/**
+ * @ngdoc service
+ * @name $document
+ * @requires $window
+ *
+ * @description
+ * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
+ *
+ * @example
+ <example module="documentExample">
+ <file name="index.html">
+ <div ng-controller="ExampleController">
+ <p>$document title: <b ng-bind="title"></b></p>
+ <p>window.document title: <b ng-bind="windowTitle"></b></p>
+ </div>
+ </file>
+ <file name="script.js">
+ angular.module('documentExample', [])
+ .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
+ $scope.title = $document[0].title;
+ $scope.windowTitle = angular.element(window.document)[0].title;
+ }]);
+ </file>
+ </example>
+ */
+function $DocumentProvider() {
+ this.$get = ['$window', function(window) {
+ return jqLite(window.document);
+ }];
+}
+
+/**
+ * @ngdoc service
+ * @name $exceptionHandler
+ * @requires ng.$log
+ *
+ * @description
+ * Any uncaught exception in angular expressions is delegated to this service.
+ * The default implementation simply delegates to `$log.error` which logs it into
+ * the browser console.
+ *
+ * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
+ * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
+ *
+ * ## Example:
+ *
+ * ```js
+ * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
+ * return function(exception, cause) {
+ * exception.message += ' (caused by "' + cause + '")';
+ * throw exception;
+ * };
+ * });
+ * ```
+ *
+ * This example will override the normal action of `$exceptionHandler`, to make angular
+ * exceptions fail hard when they happen, instead of just logging to the console.
+ *
+ * <hr />
+ * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
+ * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
+ * (unless executed during a digest).
+ *
+ * If you wish, you can manually delegate exceptions, e.g.
+ * `try { ... } catch(e) { $exceptionHandler(e); }`
+ *
+ * @param {Error} exception Exception associated with the error.
+ * @param {string=} cause optional information about the context in which
+ * the error was thrown.
+ *
+ */
+function $ExceptionHandlerProvider() {
+ this.$get = ['$log', function($log) {
+ return function(exception, cause) {
+ $log.error.apply($log, arguments);
+ };
+ }];
+}
+
+var $$ForceReflowProvider = function() {
+ this.$get = ['$document', function($document) {
+ return function(domNode) {
+ //the line below will force the browser to perform a repaint so
+ //that all the animated elements within the animation frame will
+ //be properly updated and drawn on screen. This is required to
+ //ensure that the preparation animation is properly flushed so that
+ //the active state picks up from there. DO NOT REMOVE THIS LINE.
+ //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
+ //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
+ //WILL TAKE YEARS AWAY FROM YOUR LIFE.
+ if (domNode) {
+ if (!domNode.nodeType && domNode instanceof jqLite) {
+ domNode = domNode[0];
+ }
+ } else {
+ domNode = $document[0].body;
+ }
+ return domNode.offsetWidth + 1;
+ };
+ }];
+};
+
+var APPLICATION_JSON = 'application/json';
+var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
+var JSON_START = /^\[|^\{(?!\{)/;
+var JSON_ENDS = {
+ '[': /]$/,
+ '{': /}$/
+};
+var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
+var $httpMinErr = minErr('$http');
+var $httpMinErrLegacyFn = function(method) {
+ return function() {
+ throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
+ };
+};
+
+function serializeValue(v) {
+ if (isObject(v)) {
+ return isDate(v) ? v.toISOString() : toJson(v);
+ }
+ return v;
+}
+
+
+function $HttpParamSerializerProvider() {
+ /**
+ * @ngdoc service
+ * @name $httpParamSerializer
+ * @description
+ *
+ * Default {@link $http `$http`} params serializer that converts objects to strings
+ * according to the following rules:
+ *
+ * * `{'foo': 'bar'}` results in `foo=bar`
+ * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
+ * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
+ * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
+ *
+ * Note that serializer will sort the request parameters alphabetically.
+ * */
+
+ this.$get = function() {
+ return function ngParamSerializer(params) {
+ if (!params) return '';
+ var parts = [];
+ forEachSorted(params, function(value, key) {
+ if (value === null || isUndefined(value)) return;
+ if (isArray(value)) {
+ forEach(value, function(v, k) {
+ parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
+ });
+ } else {
+ parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
+ }
+ });
+
+ return parts.join('&');
+ };
+ };
+}
+
+function $HttpParamSerializerJQLikeProvider() {
+ /**
+ * @ngdoc service
+ * @name $httpParamSerializerJQLike
+ * @description
+ *
+ * Alternative {@link $http `$http`} params serializer that follows
+ * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
+ * The serializer will also sort the params alphabetically.
+ *
+ * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
+ *
+ * ```js
+ * $http({
+ * url: myUrl,
+ * method: 'GET',
+ * params: myParams,
+ * paramSerializer: '$httpParamSerializerJQLike'
+ * });
+ * ```
+ *
+ * It is also possible to set it as the default `paramSerializer` in the
+ * {@link $httpProvider#defaults `$httpProvider`}.
+ *
+ * Additionally, you can inject the serializer and use it explicitly, for example to serialize
+ * form data for submission:
+ *
+ * ```js
+ * .controller(function($http, $httpParamSerializerJQLike) {
+ * //...
+ *
+ * $http({
+ * url: myUrl,
+ * method: 'POST',
+ * data: $httpParamSerializerJQLike(myData),
+ * headers: {
+ * 'Content-Type': 'application/x-www-form-urlencoded'
+ * }
+ * });
+ *
+ * });
+ * ```
+ *
+ * */
+ this.$get = function() {
+ return function jQueryLikeParamSerializer(params) {
+ if (!params) return '';
+ var parts = [];
+ serialize(params, '', true);
+ return parts.join('&');
+
+ function serialize(toSerialize, prefix, topLevel) {
+ if (toSerialize === null || isUndefined(toSerialize)) return;
+ if (isArray(toSerialize)) {
+ forEach(toSerialize, function(value, index) {
+ serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
+ });
+ } else if (isObject(toSerialize) && !isDate(toSerialize)) {
+ forEachSorted(toSerialize, function(value, key) {
+ serialize(value, prefix +
+ (topLevel ? '' : '[') +
+ key +
+ (topLevel ? '' : ']'));
+ });
+ } else {
+ parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
+ }
+ }
+ };
+ };
+}
+
+function defaultHttpResponseTransform(data, headers) {
+ if (isString(data)) {
+ // Strip json vulnerability protection prefix and trim whitespace
+ var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
+
+ if (tempData) {
+ var contentType = headers('Content-Type');
+ if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
+ data = fromJson(tempData);
+ }
+ }
+ }
+
+ return data;
+}
+
+function isJsonLike(str) {
+ var jsonStart = str.match(JSON_START);
+ return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
+}
+
+/**
+ * Parse headers into key value object
+ *
+ * @param {string} headers Raw headers as a string
+ * @returns {Object} Parsed headers as key value object
+ */
+function parseHeaders(headers) {
+ var parsed = createMap(), i;
+
+ function fillInParsed(key, val) {
+ if (key) {
+ parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
+ }
+ }
+
+ if (isString(headers)) {
+ forEach(headers.split('\n'), function(line) {
+ i = line.indexOf(':');
+ fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
+ });
+ } else if (isObject(headers)) {
+ forEach(headers, function(headerVal, headerKey) {
+ fillInParsed(lowercase(headerKey), trim(headerVal));
+ });
+ }
+
+ return parsed;
+}
+
+
+/**
+ * Returns a function that provides access to parsed headers.
+ *
+ * Headers are lazy parsed when first requested.
+ * @see parseHeaders
+ *
+ * @param {(string|Object)} headers Headers to provide access to.
+ * @returns {function(string=)} Returns a getter function which if called with:
+ *
+ * - if called with single an argument returns a single header value or null
+ * - if called with no arguments returns an object containing all headers.
+ */
+function headersGetter(headers) {
+ var headersObj;
+
+ return function(name) {
+ if (!headersObj) headersObj = parseHeaders(headers);
+
+ if (name) {
+ var value = headersObj[lowercase(name)];
+ if (value === void 0) {
+ value = null;
+ }
+ return value;
+ }
+
+ return headersObj;
+ };
+}
+
+
+/**
+ * Chain all given functions
+ *
+ * This function is used for both request and response transforming
+ *
+ * @param {*} data Data to transform.
+ * @param {function(string=)} headers HTTP headers getter fn.
+ * @param {number} status HTTP status code of the response.
+ * @param {(Function|Array.<Function>)} fns Function or an array of functions.
+ * @returns {*} Transformed data.
+ */
+function transformData(data, headers, status, fns) {
+ if (isFunction(fns)) {
+ return fns(data, headers, status);
+ }
+
+ forEach(fns, function(fn) {
+ data = fn(data, headers, status);
+ });
+
+ return data;
+}
+
+
+function isSuccess(status) {
+ return 200 <= status && status < 300;
+}
+
+
+/**
+ * @ngdoc provider
+ * @name $httpProvider
+ * @description
+ * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
+ * */
+function $HttpProvider() {
+ /**
+ * @ngdoc property
+ * @name $httpProvider#defaults
+ * @description
+ *
+ * Object containing default values for all {@link ng.$http $http} requests.
+ *
+ * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
+ * that will provide the cache for all requests who set their `cache` property to `true`.
+ * If you set the `defaults.cache = false` then only requests that specify their own custom
+ * cache object will be cached. See {@link $http#caching $http Caching} for more information.
+ *
+ * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
+ * Defaults value is `'XSRF-TOKEN'`.
+ *
+ * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
+ * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
+ *
+ * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
+ * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
+ * setting default headers.
+ * - **`defaults.headers.common`**
+ * - **`defaults.headers.post`**
+ * - **`defaults.headers.put`**
+ * - **`defaults.headers.patch`**
+ *
+ *
+ * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
+ * used to the prepare string representation of request parameters (specified as an object).
+ * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
+ * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
+ *
+ **/
+ var defaults = this.defaults = {
+ // transform incoming response data
+ transformResponse: [defaultHttpResponseTransform],
+
+ // transform outgoing request data
+ transformRequest: [function(d) {
+ return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
+ }],
+
+ // default headers
+ headers: {
+ common: {
+ 'Accept': 'application/json, text/plain, */*'
+ },
+ post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
+ put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
+ patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
+ },
+
+ xsrfCookieName: 'XSRF-TOKEN',
+ xsrfHeaderName: 'X-XSRF-TOKEN',
+
+ paramSerializer: '$httpParamSerializer'
+ };
+
+ var useApplyAsync = false;
+ /**
+ * @ngdoc method
+ * @name $httpProvider#useApplyAsync
+ * @description
+ *
+ * Configure $http service to combine processing of multiple http responses received at around
+ * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
+ * significant performance improvement for bigger applications that make many HTTP requests
+ * concurrently (common during application bootstrap).
+ *
+ * Defaults to false. If no value is specified, returns the current configured value.
+ *
+ * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
+ * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
+ * to load and share the same digest cycle.
+ *
+ * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
+ * otherwise, returns the current configured value.
+ **/
+ this.useApplyAsync = function(value) {
+ if (isDefined(value)) {
+ useApplyAsync = !!value;
+ return this;
+ }
+ return useApplyAsync;
+ };
+
+ var useLegacyPromise = true;
+ /**
+ * @ngdoc method
+ * @name $httpProvider#useLegacyPromiseExtensions
+ * @description
+ *
+ * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
+ * This should be used to make sure that applications work without these methods.
+ *
+ * Defaults to true. If no value is specified, returns the current configured value.
+ *
+ * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
+ *
+ * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
+ * otherwise, returns the current configured value.
+ **/
+ this.useLegacyPromiseExtensions = function(value) {
+ if (isDefined(value)) {
+ useLegacyPromise = !!value;
+ return this;
+ }
+ return useLegacyPromise;
+ };
+
+ /**
+ * @ngdoc property
+ * @name $httpProvider#interceptors
+ * @description
+ *
+ * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
+ * pre-processing of request or postprocessing of responses.
+ *
+ * These service factories are ordered by request, i.e. they are applied in the same order as the
+ * array, on request, but reverse order, on response.
+ *
+ * {@link ng.$http#interceptors Interceptors detailed info}
+ **/
+ var interceptorFactories = this.interceptors = [];
+
+ this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
+ function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
+
+ var defaultCache = $cacheFactory('$http');
+
+ /**
+ * Make sure that default param serializer is exposed as a function
+ */
+ defaults.paramSerializer = isString(defaults.paramSerializer) ?
+ $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
+
+ /**
+ * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
+ * The reversal is needed so that we can build up the interception chain around the
+ * server request.
+ */
+ var reversedInterceptors = [];
+
+ forEach(interceptorFactories, function(interceptorFactory) {
+ reversedInterceptors.unshift(isString(interceptorFactory)
+ ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
+ });
+
+ /**
+ * @ngdoc service
+ * @kind function
+ * @name $http
+ * @requires ng.$httpBackend
+ * @requires $cacheFactory
+ * @requires $rootScope
+ * @requires $q
+ * @requires $injector
+ *
+ * @description
+ * The `$http` service is a core Angular service that facilitates communication with the remote
+ * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
+ * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
+ *
+ * For unit testing applications that use `$http` service, see
+ * {@link ngMock.$httpBackend $httpBackend mock}.
+ *
+ * For a higher level of abstraction, please check out the {@link ngResource.$resource
+ * $resource} service.
+ *
+ * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
+ * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
+ * it is important to familiarize yourself with these APIs and the guarantees they provide.
+ *
+ *
+ * ## General usage
+ * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
+ * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
+ *
+ * ```js
+ * // Simple GET request example:
+ * $http({
+ * method: 'GET',
+ * url: '/someUrl'
+ * }).then(function successCallback(response) {
+ * // this callback will be called asynchronously
+ * // when the response is available
+ * }, function errorCallback(response) {
+ * // called asynchronously if an error occurs
+ * // or server returns response with an error status.
+ * });
+ * ```
+ *
+ * The response object has these properties:
+ *
+ * - **data** – `{string|Object}` – The response body transformed with the transform
+ * functions.
+ * - **status** – `{number}` – HTTP status code of the response.
+ * - **headers** – `{function([headerName])}` – Header getter function.
+ * - **config** – `{Object}` – The configuration object that was used to generate the request.
+ * - **statusText** – `{string}` – HTTP status text of the response.
+ *
+ * A response status code between 200 and 299 is considered a success status and
+ * will result in the success callback being called. Note that if the response is a redirect,
+ * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
+ * called for such responses.
+ *
+ *
+ * ## Shortcut methods
+ *
+ * Shortcut methods are also available. All shortcut methods require passing in the URL, and
+ * request data must be passed in for POST/PUT requests. An optional config can be passed as the
+ * last argument.
+ *
+ * ```js
+ * $http.get('/someUrl', config).then(successCallback, errorCallback);
+ * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
+ * ```
+ *
+ * Complete list of shortcut methods:
+ *
+ * - {@link ng.$http#get $http.get}
+ * - {@link ng.$http#head $http.head}
+ * - {@link ng.$http#post $http.post}
+ * - {@link ng.$http#put $http.put}
+ * - {@link ng.$http#delete $http.delete}
+ * - {@link ng.$http#jsonp $http.jsonp}
+ * - {@link ng.$http#patch $http.patch}
+ *
+ *
+ * ## Writing Unit Tests that use $http
+ * When unit testing (using {@link ngMock ngMock}), it is necessary to call
+ * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
+ * request using trained responses.
+ *
+ * ```
+ * $httpBackend.expectGET(...);
+ * $http.get(...);
+ * $httpBackend.flush();
+ * ```
+ *
+ * ## Deprecation Notice
+ * <div class="alert alert-danger">
+ * The `$http` legacy promise methods `success` and `error` have been deprecated.
+ * Use the standard `then` method instead.
+ * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
+ * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
+ * </div>
+ *
+ * ## Setting HTTP Headers
+ *
+ * The $http service will automatically add certain HTTP headers to all requests. These defaults
+ * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
+ * object, which currently contains this default configuration:
+ *
+ * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
+ * - `Accept: application/json, text/plain, * / *`
+ * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
+ * - `Content-Type: application/json`
+ * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
+ * - `Content-Type: application/json`
+ *
+ * To add or overwrite these defaults, simply add or remove a property from these configuration
+ * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
+ * with the lowercased HTTP method name as the key, e.g.
+ * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
+ *
+ * The defaults can also be set at runtime via the `$http.defaults` object in the same
+ * fashion. For example:
+ *
+ * ```
+ * module.run(function($http) {
+ * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
+ * });
+ * ```
+ *
+ * In addition, you can supply a `headers` property in the config object passed when
+ * calling `$http(config)`, which overrides the defaults without changing them globally.
+ *
+ * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
+ * Use the `headers` property, setting the desired header to `undefined`. For example:
+ *
+ * ```js
+ * var req = {
+ * method: 'POST',
+ * url: 'http://example.com',
+ * headers: {
+ * 'Content-Type': undefined
+ * },
+ * data: { test: 'test' }
+ * }
+ *
+ * $http(req).then(function(){...}, function(){...});
+ * ```
+ *
+ * ## Transforming Requests and Responses
+ *
+ * Both requests and responses can be transformed using transformation functions: `transformRequest`
+ * and `transformResponse`. These properties can be a single function that returns
+ * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
+ * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
+ *
+ * ### Default Transformations
+ *
+ * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
+ * `defaults.transformResponse` properties. If a request does not provide its own transformations
+ * then these will be applied.
+ *
+ * You can augment or replace the default transformations by modifying these properties by adding to or
+ * replacing the array.
+ *
+ * Angular provides the following default transformations:
+ *
+ * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
+ *
+ * - If the `data` property of the request configuration object contains an object, serialize it
+ * into JSON format.
+ *
+ * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
+ *
+ * - If XSRF prefix is detected, strip it (see Security Considerations section below).
+ * - If JSON response is detected, deserialize it using a JSON parser.
+ *
+ *
+ * ### Overriding the Default Transformations Per Request
+ *
+ * If you wish override the request/response transformations only for a single request then provide
+ * `transformRequest` and/or `transformResponse` properties on the configuration object passed
+ * into `$http`.
+ *
+ * Note that if you provide these properties on the config object the default transformations will be
+ * overwritten. If you wish to augment the default transformations then you must include them in your
+ * local transformation array.
+ *
+ * The following code demonstrates adding a new response transformation to be run after the default response
+ * transformations have been run.
+ *
+ * ```js
+ * function appendTransform(defaults, transform) {
+ *
+ * // We can't guarantee that the default transformation is an array
+ * defaults = angular.isArray(defaults) ? defaults : [defaults];
+ *
+ * // Append the new transformation to the defaults
+ * return defaults.concat(transform);
+ * }
+ *
+ * $http({
+ * url: '...',
+ * method: 'GET',
+ * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
+ * return doTransform(value);
+ * })
+ * });
+ * ```
+ *
+ *
+ * ## Caching
+ *
+ * To enable caching, set the request configuration `cache` property to `true` (to use default
+ * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
+ * When the cache is enabled, `$http` stores the response from the server in the specified
+ * cache. The next time the same request is made, the response is served from the cache without
+ * sending a request to the server.
+ *
+ * Note that even if the response is served from cache, delivery of the data is asynchronous in
+ * the same way that real requests are.
+ *
+ * If there are multiple GET requests for the same URL that should be cached using the same
+ * cache, but the cache is not populated yet, only one request to the server will be made and
+ * the remaining requests will be fulfilled using the response from the first request.
+ *
+ * You can change the default cache to a new object (built with
+ * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
+ * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
+ * their `cache` property to `true` will now use this cache object.
+ *
+ * If you set the default cache to `false` then only requests that specify their own custom
+ * cache object will be cached.
+ *
+ * ## Interceptors
+ *
+ * Before you start creating interceptors, be sure to understand the
+ * {@link ng.$q $q and deferred/promise APIs}.
+ *
+ * For purposes of global error handling, authentication, or any kind of synchronous or
+ * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
+ * able to intercept requests before they are handed to the server and
+ * responses before they are handed over to the application code that
+ * initiated these requests. The interceptors leverage the {@link ng.$q
+ * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
+ *
+ * The interceptors are service factories that are registered with the `$httpProvider` by
+ * adding them to the `$httpProvider.interceptors` array. The factory is called and
+ * injected with dependencies (if specified) and returns the interceptor.
+ *
+ * There are two kinds of interceptors (and two kinds of rejection interceptors):
+ *
+ * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
+ * modify the `config` object or create a new one. The function needs to return the `config`
+ * object directly, or a promise containing the `config` or a new `config` object.
+ * * `requestError`: interceptor gets called when a previous interceptor threw an error or
+ * resolved with a rejection.
+ * * `response`: interceptors get called with http `response` object. The function is free to
+ * modify the `response` object or create a new one. The function needs to return the `response`
+ * object directly, or as a promise containing the `response` or a new `response` object.
+ * * `responseError`: interceptor gets called when a previous interceptor threw an error or
+ * resolved with a rejection.
+ *
+ *
+ * ```js
+ * // register the interceptor as a service
+ * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
+ * return {
+ * // optional method
+ * 'request': function(config) {
+ * // do something on success
+ * return config;
+ * },
+ *
+ * // optional method
+ * 'requestError': function(rejection) {
+ * // do something on error
+ * if (canRecover(rejection)) {
+ * return responseOrNewPromise
+ * }
+ * return $q.reject(rejection);
+ * },
+ *
+ *
+ *
+ * // optional method
+ * 'response': function(response) {
+ * // do something on success
+ * return response;
+ * },
+ *
+ * // optional method
+ * 'responseError': function(rejection) {
+ * // do something on error
+ * if (canRecover(rejection)) {
+ * return responseOrNewPromise
+ * }
+ * return $q.reject(rejection);
+ * }
+ * };
+ * });
+ *
+ * $httpProvider.interceptors.push('myHttpInterceptor');
+ *
+ *
+ * // alternatively, register the interceptor via an anonymous factory
+ * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
+ * return {
+ * 'request': function(config) {
+ * // same as above
+ * },
+ *
+ * 'response': function(response) {
+ * // same as above
+ * }
+ * };
+ * });
+ * ```
+ *
+ * ## Security Considerations
+ *
+ * When designing web applications, consider security threats from:
+ *
+ * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
+ * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
+ *
+ * Both server and the client must cooperate in order to eliminate these threats. Angular comes
+ * pre-configured with strategies that address these issues, but for this to work backend server
+ * cooperation is required.
+ *
+ * ### JSON Vulnerability Protection
+ *
+ * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
+ * allows third party website to turn your JSON resource URL into
+ * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
+ * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
+ * Angular will automatically strip the prefix before processing it as JSON.
+ *
+ * For example if your server needs to return:
+ * ```js
+ * ['one','two']
+ * ```
+ *
+ * which is vulnerable to attack, your server can return:
+ * ```js
+ * )]}',
+ * ['one','two']
+ * ```
+ *
+ * Angular will strip the prefix, before processing the JSON.
+ *
+ *
+ * ### Cross Site Request Forgery (XSRF) Protection
+ *
+ * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
+ * an unauthorized site can gain your user's private data. Angular provides a mechanism
+ * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
+ * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
+ * JavaScript that runs on your domain could read the cookie, your server can be assured that
+ * the XHR came from JavaScript running on your domain. The header will not be set for
+ * cross-domain requests.
+ *
+ * To take advantage of this, your server needs to set a token in a JavaScript readable session
+ * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
+ * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
+ * that only JavaScript running on your domain could have sent the request. The token must be
+ * unique for each user and must be verifiable by the server (to prevent the JavaScript from
+ * making up its own tokens). We recommend that the token is a digest of your site's
+ * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
+ * for added security.
+ *
+ * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
+ * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
+ * or the per-request config object.
+ *
+ * In order to prevent collisions in environments where multiple Angular apps share the
+ * same domain or subdomain, we recommend that each application uses unique cookie name.
+ *
+ * @param {object} config Object describing the request to be made and how it should be
+ * processed. The object has following properties:
+ *
+ * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
+ * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
+ * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
+ * with the `paramSerializer` and appended as GET parameters.
+ * - **data** – `{string|Object}` – Data to be sent as the request message data.
+ * - **headers** – `{Object}` – Map of strings or functions which return strings representing
+ * HTTP headers to send to the server. If the return value of a function is null, the
+ * header will not be sent. Functions accept a config object as an argument.
+ * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
+ * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
+ * - **transformRequest** –
+ * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
+ * transform function or an array of such functions. The transform function takes the http
+ * request body and headers and returns its transformed (typically serialized) version.
+ * See {@link ng.$http#overriding-the-default-transformations-per-request
+ * Overriding the Default Transformations}
+ * - **transformResponse** –
+ * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
+ * transform function or an array of such functions. The transform function takes the http
+ * response body, headers and status and returns its transformed (typically deserialized) version.
+ * See {@link ng.$http#overriding-the-default-transformations-per-request
+ * Overriding the Default TransformationjqLiks}
+ * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
+ * prepare the string representation of request parameters (specified as an object).
+ * If specified as string, it is interpreted as function registered with the
+ * {@link $injector $injector}, which means you can create your own serializer
+ * by registering it as a {@link auto.$provide#service service}.
+ * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
+ * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
+ * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
+ * GET request, otherwise if a cache instance built with
+ * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
+ * caching.
+ * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
+ * that should abort the request when resolved.
+ * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
+ * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
+ * for more information.
+ * - **responseType** - `{string}` - see
+ * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
+ *
+ * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
+ * when the request succeeds or fails.
+ *
+ *
+ * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
+ * requests. This is primarily meant to be used for debugging purposes.
+ *
+ *
+ * @example
+<example module="httpExample">
+<file name="index.html">
+ <div ng-controller="FetchController">
+ <select ng-model="method" aria-label="Request method">
+ <option>GET</option>
+ <option>JSONP</option>
+ </select>
+ <input type="text" ng-model="url" size="80" aria-label="URL" />
+ <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
+ <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
+ <button id="samplejsonpbtn"
+ ng-click="updateModel('JSONP',
+ 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
+ Sample JSONP
+ </button>
+ <button id="invalidjsonpbtn"
+ ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
+ Invalid JSONP
+ </button>
+ <pre>http status code: {{status}}</pre>
+ <pre>http response data: {{data}}</pre>
+ </div>
+</file>
+<file name="script.js">
+ angular.module('httpExample', [])
+ .controller('FetchController', ['$scope', '$http', '$templateCache',
+ function($scope, $http, $templateCache) {
+ $scope.method = 'GET';
+ $scope.url = 'http-hello.html';
+
+ $scope.fetch = function() {
+ $scope.code = null;
+ $scope.response = null;
+
+ $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
+ then(function(response) {
+ $scope.status = response.status;
+ $scope.data = response.data;
+ }, function(response) {
+ $scope.data = response.data || "Request failed";
+ $scope.status = response.status;
+ });
+ };
+
+ $scope.updateModel = function(method, url) {
+ $scope.method = method;
+ $scope.url = url;
+ };
+ }]);
+</file>
+<file name="http-hello.html">
+ Hello, $http!
+</file>
+<file name="protractor.js" type="protractor">
+ var status = element(by.binding('status'));
+ var data = element(by.binding('data'));
+ var fetchBtn = element(by.id('fetchbtn'));
+ var sampleGetBtn = element(by.id('samplegetbtn'));
+ var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
+ var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
+
+ it('should make an xhr GET request', function() {
+ sampleGetBtn.click();
+ fetchBtn.click();
+ expect(status.getText()).toMatch('200');
+ expect(data.getText()).toMatch(/Hello, \$http!/);
+ });
+
+// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
+// it('should make a JSONP request to angularjs.org', function() {
+// sampleJsonpBtn.click();
+// fetchBtn.click();
+// expect(status.getText()).toMatch('200');
+// expect(data.getText()).toMatch(/Super Hero!/);
+// });
+
+ it('should make JSONP request to invalid URL and invoke the error handler',
+ function() {
+ invalidJsonpBtn.click();
+ fetchBtn.click();
+ expect(status.getText()).toMatch('0');
+ expect(data.getText()).toMatch('Request failed');
+ });
+</file>
+</example>
+ */
+ function $http(requestConfig) {
+
+ if (!angular.isObject(requestConfig)) {
+ throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
+ }
+
+ var config = extend({
+ method: 'get',
+ transformRequest: defaults.transformRequest,
+ transformResponse: defaults.transformResponse,
+ paramSerializer: defaults.paramSerializer
+ }, requestConfig);
+
+ config.headers = mergeHeaders(requestConfig);
+ config.method = uppercase(config.method);
+ config.paramSerializer = isString(config.paramSerializer) ?
+ $injector.get(config.paramSerializer) : config.paramSerializer;
+
+ var serverRequest = function(config) {
+ var headers = config.headers;
+ var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
+
+ // strip content-type if data is undefined
+ if (isUndefined(reqData)) {
+ forEach(headers, function(value, header) {
+ if (lowercase(header) === 'content-type') {
+ delete headers[header];
+ }
+ });
+ }
+
+ if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
+ config.withCredentials = defaults.withCredentials;
+ }
+
+ // send request
+ return sendReq(config, reqData).then(transformResponse, transformResponse);
+ };
+
+ var chain = [serverRequest, undefined];
+ var promise = $q.when(config);
+
+ // apply interceptors
+ forEach(reversedInterceptors, function(interceptor) {
+ if (interceptor.request || interceptor.requestError) {
+ chain.unshift(interceptor.request, interceptor.requestError);
+ }
+ if (interceptor.response || interceptor.responseError) {
+ chain.push(interceptor.response, interceptor.responseError);
+ }
+ });
+
+ while (chain.length) {
+ var thenFn = chain.shift();
+ var rejectFn = chain.shift();
+
+ promise = promise.then(thenFn, rejectFn);
+ }
+
+ if (useLegacyPromise) {
+ promise.success = function(fn) {
+ assertArgFn(fn, 'fn');
+
+ promise.then(function(response) {
+ fn(response.data, response.status, response.headers, config);
+ });
+ return promise;
+ };
+
+ promise.error = function(fn) {
+ assertArgFn(fn, 'fn');
+
+ promise.then(null, function(response) {
+ fn(response.data, response.status, response.headers, config);
+ });
+ return promise;
+ };
+ } else {
+ promise.success = $httpMinErrLegacyFn('success');
+ promise.error = $httpMinErrLegacyFn('error');
+ }
+
+ return promise;
+
+ function transformResponse(response) {
+ // make a copy since the response must be cacheable
+ var resp = extend({}, response);
+ resp.data = transformData(response.data, response.headers, response.status,
+ config.transformResponse);
+ return (isSuccess(response.status))
+ ? resp
+ : $q.reject(resp);
+ }
+
+ function executeHeaderFns(headers, config) {
+ var headerContent, processedHeaders = {};
+
+ forEach(headers, function(headerFn, header) {
+ if (isFunction(headerFn)) {
+ headerContent = headerFn(config);
+ if (headerContent != null) {
+ processedHeaders[header] = headerContent;
+ }
+ } else {
+ processedHeaders[header] = headerFn;
+ }
+ });
+
+ return processedHeaders;
+ }
+
+ function mergeHeaders(config) {
+ var defHeaders = defaults.headers,
+ reqHeaders = extend({}, config.headers),
+ defHeaderName, lowercaseDefHeaderName, reqHeaderName;
+
+ defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
+
+ // using for-in instead of forEach to avoid unecessary iteration after header has been found
+ defaultHeadersIteration:
+ for (defHeaderName in defHeaders) {
+ lowercaseDefHeaderName = lowercase(defHeaderName);
+
+ for (reqHeaderName in reqHeaders) {
+ if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
+ continue defaultHeadersIteration;
+ }
+ }
+
+ reqHeaders[defHeaderName] = defHeaders[defHeaderName];
+ }
+
+ // execute if header value is a function for merged headers
+ return executeHeaderFns(reqHeaders, shallowCopy(config));
+ }
+ }
+
+ $http.pendingRequests = [];
+
+ /**
+ * @ngdoc method
+ * @name $http#get
+ *
+ * @description
+ * Shortcut method to perform `GET` request.
+ *
+ * @param {string} url Relative or absolute URL specifying the destination of the request
+ * @param {Object=} config Optional configuration object
+ * @returns {HttpPromise} Future object
+ */
+
+ /**
+ * @ngdoc method
+ * @name $http#delete
+ *
+ * @description
+ * Shortcut method to perform `DELETE` request.
+ *
+ * @param {string} url Relative or absolute URL specifying the destination of the request
+ * @param {Object=} config Optional configuration object
+ * @returns {HttpPromise} Future object
+ */
+
+ /**
+ * @ngdoc method
+ * @name $http#head
+ *
+ * @description
+ * Shortcut method to perform `HEAD` request.
+ *
+ * @param {string} url Relative or absolute URL specifying the destination of the request
+ * @param {Object=} config Optional configuration object
+ * @returns {HttpPromise} Future object
+ */
+
+ /**
+ * @ngdoc method
+ * @name $http#jsonp
+ *
+ * @description
+ * Shortcut method to perform `JSONP` request.
+ *
+ * @param {string} url Relative or absolute URL specifying the destination of the request.
+ * The name of the callback should be the string `JSON_CALLBACK`.
+ * @param {Object=} config Optional configuration object
+ * @returns {HttpPromise} Future object
+ */
+ createShortMethods('get', 'delete', 'head', 'jsonp');
+
+ /**
+ * @ngdoc method
+ * @name $http#post
+ *
+ * @description
+ * Shortcut method to perform `POST` request.
+ *
+ * @param {string} url Relative or absolute URL specifying the destination of the request
+ * @param {*} data Request content
+ * @param {Object=} config Optional configuration object
+ * @returns {HttpPromise} Future object
+ */
+
+ /**
+ * @ngdoc method
+ * @name $http#put
+ *
+ * @description
+ * Shortcut method to perform `PUT` request.
+ *
+ * @param {string} url Relative or absolute URL specifying the destination of the request
+ * @param {*} data Request content
+ * @param {Object=} config Optional configuration object
+ * @returns {HttpPromise} Future object
+ */
+
+ /**
+ * @ngdoc method
+ * @name $http#patch
+ *
+ * @description
+ * Shortcut method to perform `PATCH` request.
+ *
+ * @param {string} url Relative or absolute URL specifying the destination of the request
+ * @param {*} data Request content
+ * @param {Object=} config Optional configuration object
+ * @returns {HttpPromise} Future object
+ */
+ createShortMethodsWithData('post', 'put', 'patch');
+
+ /**
+ * @ngdoc property
+ * @name $http#defaults
+ *
+ * @description
+ * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
+ * default headers, withCredentials as well as request and response transformations.
+ *
+ * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
+ */
+ $http.defaults = defaults;
+
+
+ return $http;
+
+
+ function createShortMethods(names) {
+ forEach(arguments, function(name) {
+ $http[name] = function(url, config) {
+ return $http(extend({}, config || {}, {
+ method: name,
+ url: url
+ }));
+ };
+ });
+ }
+
+
+ function createShortMethodsWithData(name) {
+ forEach(arguments, function(name) {
+ $http[name] = function(url, data, config) {
+ return $http(extend({}, config || {}, {
+ method: name,
+ url: url,
+ data: data
+ }));
+ };
+ });
+ }
+
+
+ /**
+ * Makes the request.
+ *
+ * !!! ACCESSES CLOSURE VARS:
+ * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
+ */
+ function sendReq(config, reqData) {
+ var deferred = $q.defer(),
+ promise = deferred.promise,
+ cache,
+ cachedResp,
+ reqHeaders = config.headers,
+ url = buildUrl(config.url, config.paramSerializer(config.params));
+
+ $http.pendingRequests.push(config);
+ promise.then(removePendingReq, removePendingReq);
+
+
+ if ((config.cache || defaults.cache) && config.cache !== false &&
+ (config.method === 'GET' || config.method === 'JSONP')) {
+ cache = isObject(config.cache) ? config.cache
+ : isObject(defaults.cache) ? defaults.cache
+ : defaultCache;
+ }
+
+ if (cache) {
+ cachedResp = cache.get(url);
+ if (isDefined(cachedResp)) {
+ if (isPromiseLike(cachedResp)) {
+ // cached request has already been sent, but there is no response yet
+ cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
+ } else {
+ // serving from cache
+ if (isArray(cachedResp)) {
+ resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
+ } else {
+ resolvePromise(cachedResp, 200, {}, 'OK');
+ }
+ }
+ } else {
+ // put the promise for the non-transformed response into cache as a placeholder
+ cache.put(url, promise);
+ }
+ }
+
+
+ // if we won't have the response in cache, set the xsrf headers and
+ // send the request to the backend
+ if (isUndefined(cachedResp)) {
+ var xsrfValue = urlIsSameOrigin(config.url)
+ ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
+ : undefined;
+ if (xsrfValue) {
+ reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
+ }
+
+ $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
+ config.withCredentials, config.responseType);
+ }
+
+ return promise;
+
+
+ /**
+ * Callback registered to $httpBackend():
+ * - caches the response if desired
+ * - resolves the raw $http promise
+ * - calls $apply
+ */
+ function done(status, response, headersString, statusText) {
+ if (cache) {
+ if (isSuccess(status)) {
+ cache.put(url, [status, response, parseHeaders(headersString), statusText]);
+ } else {
+ // remove promise from the cache
+ cache.remove(url);
+ }
+ }
+
+ function resolveHttpPromise() {
+ resolvePromise(response, status, headersString, statusText);
+ }
+
+ if (useApplyAsync) {
+ $rootScope.$applyAsync(resolveHttpPromise);
+ } else {
+ resolveHttpPromise();
+ if (!$rootScope.$$phase) $rootScope.$apply();
+ }
+ }
+
+
+ /**
+ * Resolves the raw $http promise.
+ */
+ function resolvePromise(response, status, headers, statusText) {
+ //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
+ status = status >= -1 ? status : 0;
+
+ (isSuccess(status) ? deferred.resolve : deferred.reject)({
+ data: response,
+ status: status,
+ headers: headersGetter(headers),
+ config: config,
+ statusText: statusText
+ });
+ }
+
+ function resolvePromiseWithResult(result) {
+ resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
+ }
+
+ function removePendingReq() {
+ var idx = $http.pendingRequests.indexOf(config);
+ if (idx !== -1) $http.pendingRequests.splice(idx, 1);
+ }
+ }
+
+
+ function buildUrl(url, serializedParams) {
+ if (serializedParams.length > 0) {
+ url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
+ }
+ return url;
+ }
+ }];
+}
+
+/**
+ * @ngdoc service
+ * @name $xhrFactory
+ *
+ * @description
+ * Factory function used to create XMLHttpRequest objects.
+ *
+ * Replace or decorate this service to create your own custom XMLHttpRequest objects.
+ *
+ * ```
+ * angular.module('myApp', [])
+ * .factory('$xhrFactory', function() {
+ * return function createXhr(method, url) {
+ * return new window.XMLHttpRequest({mozSystem: true});
+ * };
+ * });
+ * ```
+ *
+ * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
+ * @param {string} url URL of the request.
+ */
+function $xhrFactoryProvider() {
+ this.$get = function() {
+ return function createXhr() {
+ return new window.XMLHttpRequest();
+ };
+ };
+}
+
+/**
+ * @ngdoc service
+ * @name $httpBackend
+ * @requires $window
+ * @requires $document
+ * @requires $xhrFactory
+ *
+ * @description
+ * HTTP backend used by the {@link ng.$http service} that delegates to
+ * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
+ *
+ * You should never need to use this service directly, instead use the higher-level abstractions:
+ * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
+ *
+ * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
+ * $httpBackend} which can be trained with responses.
+ */
+function $HttpBackendProvider() {
+ this.$get = ['$browser', '$window', '$document', '$xhrFactory', function($browser, $window, $document, $xhrFactory) {
+ return createHttpBackend($browser, $xhrFactory, $browser.defer, $window.angular.callbacks, $document[0]);
+ }];
+}
+
+function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
+ // TODO(vojta): fix the signature
+ return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
+ $browser.$$incOutstandingRequestCount();
+ url = url || $browser.url();
+
+ if (lowercase(method) == 'jsonp') {
+ var callbackId = '_' + (callbacks.counter++).toString(36);
+ callbacks[callbackId] = function(data) {
+ callbacks[callbackId].data = data;
+ callbacks[callbackId].called = true;
+ };
+
+ var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
+ callbackId, function(status, text) {
+ completeRequest(callback, status, callbacks[callbackId].data, "", text);
+ callbacks[callbackId] = noop;
+ });
+ } else {
+
+ var xhr = createXhr(method, url);
+
+ xhr.open(method, url, true);
+ forEach(headers, function(value, key) {
+ if (isDefined(value)) {
+ xhr.setRequestHeader(key, value);
+ }
+ });
+
+ xhr.onload = function requestLoaded() {
+ var statusText = xhr.statusText || '';
+
+ // responseText is the old-school way of retrieving response (supported by IE9)
+ // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
+ var response = ('response' in xhr) ? xhr.response : xhr.responseText;
+
+ // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
+ var status = xhr.status === 1223 ? 204 : xhr.status;
+
+ // fix status code when it is 0 (0 status is undocumented).
+ // Occurs when accessing file resources or on Android 4.1 stock browser
+ // while retrieving files from application cache.
+ if (status === 0) {
+ status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
+ }
+
+ completeRequest(callback,
+ status,
+ response,
+ xhr.getAllResponseHeaders(),
+ statusText);
+ };
+
+ var requestError = function() {
+ // The response is always empty
+ // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
+ completeRequest(callback, -1, null, null, '');
+ };
+
+ xhr.onerror = requestError;
+ xhr.onabort = requestError;
+
+ if (withCredentials) {
+ xhr.withCredentials = true;
+ }
+
+ if (responseType) {
+ try {
+ xhr.responseType = responseType;
+ } catch (e) {
+ // WebKit added support for the json responseType value on 09/03/2013
+ // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
+ // known to throw when setting the value "json" as the response type. Other older
+ // browsers implementing the responseType
+ //
+ // The json response type can be ignored if not supported, because JSON payloads are
+ // parsed on the client-side regardless.
+ if (responseType !== 'json') {
+ throw e;
+ }
+ }
+ }
+
+ xhr.send(isUndefined(post) ? null : post);
+ }
+
+ if (timeout > 0) {
+ var timeoutId = $browserDefer(timeoutRequest, timeout);
+ } else if (isPromiseLike(timeout)) {
+ timeout.then(timeoutRequest);
+ }
+
+
+ function timeoutRequest() {
+ jsonpDone && jsonpDone();
+ xhr && xhr.abort();
+ }
+
+ function completeRequest(callback, status, response, headersString, statusText) {
+ // cancel timeout and subsequent timeout promise resolution
+ if (isDefined(timeoutId)) {
+ $browserDefer.cancel(timeoutId);
+ }
+ jsonpDone = xhr = null;
+
+ callback(status, response, headersString, statusText);
+ $browser.$$completeOutstandingRequest(noop);
+ }
+ };
+
+ function jsonpReq(url, callbackId, done) {
+ // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
+ // - fetches local scripts via XHR and evals them
+ // - adds and immediately removes script elements from the document
+ var script = rawDocument.createElement('script'), callback = null;
+ script.type = "text/javascript";
+ script.src = url;
+ script.async = true;
+
+ callback = function(event) {
+ removeEventListenerFn(script, "load", callback);
+ removeEventListenerFn(script, "error", callback);
+ rawDocument.body.removeChild(script);
+ script = null;
+ var status = -1;
+ var text = "unknown";
+
+ if (event) {
+ if (event.type === "load" && !callbacks[callbackId].called) {
+ event = { type: "error" };
+ }
+ text = event.type;
+ status = event.type === "error" ? 404 : 200;
+ }
+
+ if (done) {
+ done(status, text);
+ }
+ };
+
+ addEventListenerFn(script, "load", callback);
+ addEventListenerFn(script, "error", callback);
+ rawDocument.body.appendChild(script);
+ return callback;
+ }
+}
+
+var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
+$interpolateMinErr.throwNoconcat = function(text) {
+ throw $interpolateMinErr('noconcat',
+ "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
+ "interpolations that concatenate multiple expressions when a trusted value is " +
+ "required. See http://docs.angularjs.org/api/ng.$sce", text);
+};
+
+$interpolateMinErr.interr = function(text, err) {
+ return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
+};
+
+/**
+ * @ngdoc provider
+ * @name $interpolateProvider
+ *
+ * @description
+ *
+ * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
+ *
+ * @example
+<example module="customInterpolationApp">
+<file name="index.html">
+<script>
+ var customInterpolationApp = angular.module('customInterpolationApp', []);
+
+ customInterpolationApp.config(function($interpolateProvider) {
+ $interpolateProvider.startSymbol('//');
+ $interpolateProvider.endSymbol('//');
+ });
+
+
+ customInterpolationApp.controller('DemoController', function() {
+ this.label = "This binding is brought you by // interpolation symbols.";
+ });
+</script>
+<div ng-app="App" ng-controller="DemoController as demo">
+ //demo.label//
+</div>
+</file>
+<file name="protractor.js" type="protractor">
+ it('should interpolate binding with custom symbols', function() {
+ expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
+ });
+</file>
+</example>
+ */
+function $InterpolateProvider() {
+ var startSymbol = '{{';
+ var endSymbol = '}}';
+
+ /**
+ * @ngdoc method
+ * @name $interpolateProvider#startSymbol
+ * @description
+ * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
+ *
+ * @param {string=} value new value to set the starting symbol to.
+ * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
+ */
+ this.startSymbol = function(value) {
+ if (value) {
+ startSymbol = value;
+ return this;
+ } else {
+ return startSymbol;
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name $interpolateProvider#endSymbol
+ * @description
+ * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
+ *
+ * @param {string=} value new value to set the ending symbol to.
+ * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
+ */
+ this.endSymbol = function(value) {
+ if (value) {
+ endSymbol = value;
+ return this;
+ } else {
+ return endSymbol;
+ }
+ };
+
+
+ this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
+ var startSymbolLength = startSymbol.length,
+ endSymbolLength = endSymbol.length,
+ escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
+ escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
+
+ function escape(ch) {
+ return '\\\\\\' + ch;
+ }
+
+ function unescapeText(text) {
+ return text.replace(escapedStartRegexp, startSymbol).
+ replace(escapedEndRegexp, endSymbol);
+ }
+
+ function stringify(value) {
+ if (value == null) { // null || undefined
+ return '';
+ }
+ switch (typeof value) {
+ case 'string':
+ break;
+ case 'number':
+ value = '' + value;
+ break;
+ default:
+ value = toJson(value);
+ }
+
+ return value;
+ }
+
+ /**
+ * @ngdoc service
+ * @name $interpolate
+ * @kind function
+ *
+ * @requires $parse
+ * @requires $sce
+ *
+ * @description
+ *
+ * Compiles a string with markup into an interpolation function. This service is used by the
+ * HTML {@link ng.$compile $compile} service for data binding. See
+ * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
+ * interpolation markup.
+ *
+ *
+ * ```js
+ * var $interpolate = ...; // injected
+ * var exp = $interpolate('Hello {{name | uppercase}}!');
+ * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
+ * ```
+ *
+ * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
+ * `true`, the interpolation function will return `undefined` unless all embedded expressions
+ * evaluate to a value other than `undefined`.
+ *
+ * ```js
+ * var $interpolate = ...; // injected
+ * var context = {greeting: 'Hello', name: undefined };
+ *
+ * // default "forgiving" mode
+ * var exp = $interpolate('{{greeting}} {{name}}!');
+ * expect(exp(context)).toEqual('Hello !');
+ *
+ * // "allOrNothing" mode
+ * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
+ * expect(exp(context)).toBeUndefined();
+ * context.name = 'Angular';
+ * expect(exp(context)).toEqual('Hello Angular!');
+ * ```
+ *
+ * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
+ *
+ * ####Escaped Interpolation
+ * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
+ * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
+ * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
+ * or binding.
+ *
+ * This enables web-servers to prevent script injection attacks and defacing attacks, to some
+ * degree, while also enabling code examples to work without relying on the
+ * {@link ng.directive:ngNonBindable ngNonBindable} directive.
+ *
+ * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
+ * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all
+ * interpolation start/end markers with their escaped counterparts.**
+ *
+ * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
+ * output when the $interpolate service processes the text. So, for HTML elements interpolated
+ * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
+ * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
+ * this is typically useful only when user-data is used in rendering a template from the server, or
+ * when otherwise untrusted data is used by a directive.
+ *
+ * <example>
+ * <file name="index.html">
+ * <div ng-init="username='A user'">
+ * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
+ * </p>
+ * <p><strong>{{username}}</strong> attempts to inject code which will deface the
+ * application, but fails to accomplish their task, because the server has correctly
+ * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
+ * characters.</p>
+ * <p>Instead, the result of the attempted script injection is visible, and can be removed
+ * from the database by an administrator.</p>
+ * </div>
+ * </file>
+ * </example>
+ *
+ * @param {string} text The text with markup to interpolate.
+ * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
+ * embedded expression in order to return an interpolation function. Strings with no
+ * embedded expression will return null for the interpolation function.
+ * @param {string=} trustedContext when provided, the returned function passes the interpolated
+ * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
+ * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
+ * provides Strict Contextual Escaping for details.
+ * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
+ * unless all embedded expressions evaluate to a value other than `undefined`.
+ * @returns {function(context)} an interpolation function which is used to compute the
+ * interpolated string. The function has these parameters:
+ *
+ * - `context`: evaluation context for all expressions embedded in the interpolated text
+ */
+ function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
+ allOrNothing = !!allOrNothing;
+ var startIndex,
+ endIndex,
+ index = 0,
+ expressions = [],
+ parseFns = [],
+ textLength = text.length,
+ exp,
+ concat = [],
+ expressionPositions = [];
+
+ while (index < textLength) {
+ if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
+ ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
+ if (index !== startIndex) {
+ concat.push(unescapeText(text.substring(index, startIndex)));
+ }
+ exp = text.substring(startIndex + startSymbolLength, endIndex);
+ expressions.push(exp);
+ parseFns.push($parse(exp, parseStringifyInterceptor));
+ index = endIndex + endSymbolLength;
+ expressionPositions.push(concat.length);
+ concat.push('');
+ } else {
+ // we did not find an interpolation, so we have to add the remainder to the separators array
+ if (index !== textLength) {
+ concat.push(unescapeText(text.substring(index)));
+ }
+ break;
+ }
+ }
+
+ // Concatenating expressions makes it hard to reason about whether some combination of
+ // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
+ // single expression be used for iframe[src], object[src], etc., we ensure that the value
+ // that's used is assigned or constructed by some JS code somewhere that is more testable or
+ // make it obvious that you bound the value to some user controlled value. This helps reduce
+ // the load when auditing for XSS issues.
+ if (trustedContext && concat.length > 1) {
+ $interpolateMinErr.throwNoconcat(text);
+ }
+
+ if (!mustHaveExpression || expressions.length) {
+ var compute = function(values) {
+ for (var i = 0, ii = expressions.length; i < ii; i++) {
+ if (allOrNothing && isUndefined(values[i])) return;
+ concat[expressionPositions[i]] = values[i];
+ }
+ return concat.join('');
+ };
+
+ var getValue = function(value) {
+ return trustedContext ?
+ $sce.getTrusted(trustedContext, value) :
+ $sce.valueOf(value);
+ };
+
+ return extend(function interpolationFn(context) {
+ var i = 0;
+ var ii = expressions.length;
+ var values = new Array(ii);
+
+ try {
+ for (; i < ii; i++) {
+ values[i] = parseFns[i](context);
+ }
+
+ return compute(values);
+ } catch (err) {
+ $exceptionHandler($interpolateMinErr.interr(text, err));
+ }
+
+ }, {
+ // all of these properties are undocumented for now
+ exp: text, //just for compatibility with regular watchers created via $watch
+ expressions: expressions,
+ $$watchDelegate: function(scope, listener) {
+ var lastValue;
+ return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
+ var currValue = compute(values);
+ if (isFunction(listener)) {
+ listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
+ }
+ lastValue = currValue;
+ });
+ }
+ });
+ }
+
+ function parseStringifyInterceptor(value) {
+ try {
+ value = getValue(value);
+ return allOrNothing && !isDefined(value) ? value : stringify(value);
+ } catch (err) {
+ $exceptionHandler($interpolateMinErr.interr(text, err));
+ }
+ }
+ }
+
+
+ /**
+ * @ngdoc method
+ * @name $interpolate#startSymbol
+ * @description
+ * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
+ *
+ * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
+ * the symbol.
+ *
+ * @returns {string} start symbol.
+ */
+ $interpolate.startSymbol = function() {
+ return startSymbol;
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name $interpolate#endSymbol
+ * @description
+ * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
+ *
+ * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
+ * the symbol.
+ *
+ * @returns {string} end symbol.
+ */
+ $interpolate.endSymbol = function() {
+ return endSymbol;
+ };
+
+ return $interpolate;
+ }];
+}
+
+function $IntervalProvider() {
+ this.$get = ['$rootScope', '$window', '$q', '$$q',
+ function($rootScope, $window, $q, $$q) {
+ var intervals = {};
+
+
+ /**
+ * @ngdoc service
+ * @name $interval
+ *
+ * @description
+ * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
+ * milliseconds.
+ *
+ * The return value of registering an interval function is a promise. This promise will be
+ * notified upon each tick of the interval, and will be resolved after `count` iterations, or
+ * run indefinitely if `count` is not defined. The value of the notification will be the
+ * number of iterations that have run.
+ * To cancel an interval, call `$interval.cancel(promise)`.
+ *
+ * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
+ * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
+ * time.
+ *
+ * <div class="alert alert-warning">
+ * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
+ * with them. In particular they are not automatically destroyed when a controller's scope or a
+ * directive's element are destroyed.
+ * You should take this into consideration and make sure to always cancel the interval at the
+ * appropriate moment. See the example below for more details on how and when to do this.
+ * </div>
+ *
+ * @param {function()} fn A function that should be called repeatedly.
+ * @param {number} delay Number of milliseconds between each function call.
+ * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
+ * indefinitely.
+ * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
+ * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
+ * @param {...*=} Pass additional parameters to the executed function.
+ * @returns {promise} A promise which will be notified on each iteration.
+ *
+ * @example
+ * <example module="intervalExample">
+ * <file name="index.html">
+ * <script>
+ * angular.module('intervalExample', [])
+ * .controller('ExampleController', ['$scope', '$interval',
+ * function($scope, $interval) {
+ * $scope.format = 'M/d/yy h:mm:ss a';
+ * $scope.blood_1 = 100;
+ * $scope.blood_2 = 120;
+ *
+ * var stop;
+ * $scope.fight = function() {
+ * // Don't start a new fight if we are already fighting
+ * if ( angular.isDefined(stop) ) return;
+ *
+ * stop = $interval(function() {
+ * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
+ * $scope.blood_1 = $scope.blood_1 - 3;
+ * $scope.blood_2 = $scope.blood_2 - 4;
+ * } else {
+ * $scope.stopFight();
+ * }
+ * }, 100);
+ * };
+ *
+ * $scope.stopFight = function() {
+ * if (angular.isDefined(stop)) {
+ * $interval.cancel(stop);
+ * stop = undefined;
+ * }
+ * };
+ *
+ * $scope.resetFight = function() {
+ * $scope.blood_1 = 100;
+ * $scope.blood_2 = 120;
+ * };
+ *
+ * $scope.$on('$destroy', function() {
+ * // Make sure that the interval is destroyed too
+ * $scope.stopFight();
+ * });
+ * }])
+ * // Register the 'myCurrentTime' directive factory method.
+ * // We inject $interval and dateFilter service since the factory method is DI.
+ * .directive('myCurrentTime', ['$interval', 'dateFilter',
+ * function($interval, dateFilter) {
+ * // return the directive link function. (compile function not needed)
+ * return function(scope, element, attrs) {
+ * var format, // date format
+ * stopTime; // so that we can cancel the time updates
+ *
+ * // used to update the UI
+ * function updateTime() {
+ * element.text(dateFilter(new Date(), format));
+ * }
+ *
+ * // watch the expression, and update the UI on change.
+ * scope.$watch(attrs.myCurrentTime, function(value) {
+ * format = value;
+ * updateTime();
+ * });
+ *
+ * stopTime = $interval(updateTime, 1000);
+ *
+ * // listen on DOM destroy (removal) event, and cancel the next UI update
+ * // to prevent updating time after the DOM element was removed.
+ * element.on('$destroy', function() {
+ * $interval.cancel(stopTime);
+ * });
+ * }
+ * }]);
+ * </script>
+ *
+ * <div>
+ * <div ng-controller="ExampleController">
+ * <label>Date format: <input ng-model="format"></label> <hr/>
+ * Current time is: <span my-current-time="format"></span>
+ * <hr/>
+ * Blood 1 : <font color='red'>{{blood_1}}</font>
+ * Blood 2 : <font color='red'>{{blood_2}}</font>
+ * <button type="button" data-ng-click="fight()">Fight</button>
+ * <button type="button" data-ng-click="stopFight()">StopFight</button>
+ * <button type="button" data-ng-click="resetFight()">resetFight</button>
+ * </div>
+ * </div>
+ *
+ * </file>
+ * </example>
+ */
+ function interval(fn, delay, count, invokeApply) {
+ var hasParams = arguments.length > 4,
+ args = hasParams ? sliceArgs(arguments, 4) : [],
+ setInterval = $window.setInterval,
+ clearInterval = $window.clearInterval,
+ iteration = 0,
+ skipApply = (isDefined(invokeApply) && !invokeApply),
+ deferred = (skipApply ? $$q : $q).defer(),
+ promise = deferred.promise;
+
+ count = isDefined(count) ? count : 0;
+
+ promise.then(null, null, (!hasParams) ? fn : function() {
+ fn.apply(null, args);
+ });
+
+ promise.$$intervalId = setInterval(function tick() {
+ deferred.notify(iteration++);
+
+ if (count > 0 && iteration >= count) {
+ deferred.resolve(iteration);
+ clearInterval(promise.$$intervalId);
+ delete intervals[promise.$$intervalId];
+ }
+
+ if (!skipApply) $rootScope.$apply();
+
+ }, delay);
+
+ intervals[promise.$$intervalId] = deferred;
+
+ return promise;
+ }
+
+
+ /**
+ * @ngdoc method
+ * @name $interval#cancel
+ *
+ * @description
+ * Cancels a task associated with the `promise`.
+ *
+ * @param {Promise=} promise returned by the `$interval` function.
+ * @returns {boolean} Returns `true` if the task was successfully canceled.
+ */
+ interval.cancel = function(promise) {
+ if (promise && promise.$$intervalId in intervals) {
+ intervals[promise.$$intervalId].reject('canceled');
+ $window.clearInterval(promise.$$intervalId);
+ delete intervals[promise.$$intervalId];
+ return true;
+ }
+ return false;
+ };
+
+ return interval;
+ }];
+}
+
+/**
+ * @ngdoc service
+ * @name $locale
+ *
+ * @description
+ * $locale service provides localization rules for various Angular components. As of right now the
+ * only public api is:
+ *
+ * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
+ */
+
+var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
+ DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
+var $locationMinErr = minErr('$location');
+
+
+/**
+ * Encode path using encodeUriSegment, ignoring forward slashes
+ *
+ * @param {string} path Path to encode
+ * @returns {string}
+ */
+function encodePath(path) {
+ var segments = path.split('/'),
+ i = segments.length;
+
+ while (i--) {
+ segments[i] = encodeUriSegment(segments[i]);
+ }
+
+ return segments.join('/');
+}
+
+function parseAbsoluteUrl(absoluteUrl, locationObj) {
+ var parsedUrl = urlResolve(absoluteUrl);
+
+ locationObj.$$protocol = parsedUrl.protocol;
+ locationObj.$$host = parsedUrl.hostname;
+ locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
+}
+
+
+function parseAppUrl(relativeUrl, locationObj) {
+ var prefixed = (relativeUrl.charAt(0) !== '/');
+ if (prefixed) {
+ relativeUrl = '/' + relativeUrl;
+ }
+ var match = urlResolve(relativeUrl);
+ locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
+ match.pathname.substring(1) : match.pathname);
+ locationObj.$$search = parseKeyValue(match.search);
+ locationObj.$$hash = decodeURIComponent(match.hash);
+
+ // make sure path starts with '/';
+ if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
+ locationObj.$$path = '/' + locationObj.$$path;
+ }
+}
+
+
+/**
+ *
+ * @param {string} begin
+ * @param {string} whole
+ * @returns {string} returns text from whole after begin or undefined if it does not begin with
+ * expected string.
+ */
+function beginsWith(begin, whole) {
+ if (whole.indexOf(begin) === 0) {
+ return whole.substr(begin.length);
+ }
+}
+
+
+function stripHash(url) {
+ var index = url.indexOf('#');
+ return index == -1 ? url : url.substr(0, index);
+}
+
+function trimEmptyHash(url) {
+ return url.replace(/(#.+)|#$/, '$1');
+}
+
+
+function stripFile(url) {
+ return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
+}
+
+/* return the server only (scheme://host:port) */
+function serverBase(url) {
+ return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
+}
+
+
+/**
+ * LocationHtml5Url represents an url
+ * This object is exposed as $location service when HTML5 mode is enabled and supported
+ *
+ * @constructor
+ * @param {string} appBase application base URL
+ * @param {string} appBaseNoFile application base URL stripped of any filename
+ * @param {string} basePrefix url path prefix
+ */
+function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
+ this.$$html5 = true;
+ basePrefix = basePrefix || '';
+ parseAbsoluteUrl(appBase, this);
+
+
+ /**
+ * Parse given html5 (regular) url string into properties
+ * @param {string} url HTML5 url
+ * @private
+ */
+ this.$$parse = function(url) {
+ var pathUrl = beginsWith(appBaseNoFile, url);
+ if (!isString(pathUrl)) {
+ throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
+ appBaseNoFile);
+ }
+
+ parseAppUrl(pathUrl, this);
+
+ if (!this.$$path) {
+ this.$$path = '/';
+ }
+
+ this.$$compose();
+ };
+
+ /**
+ * Compose url and update `absUrl` property
+ * @private
+ */
+ this.$$compose = function() {
+ var search = toKeyValue(this.$$search),
+ hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
+
+ this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
+ this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
+ };
+
+ this.$$parseLinkUrl = function(url, relHref) {
+ if (relHref && relHref[0] === '#') {
+ // special case for links to hash fragments:
+ // keep the old url and only replace the hash fragment
+ this.hash(relHref.slice(1));
+ return true;
+ }
+ var appUrl, prevAppUrl;
+ var rewrittenUrl;
+
+ if (isDefined(appUrl = beginsWith(appBase, url))) {
+ prevAppUrl = appUrl;
+ if (isDefined(appUrl = beginsWith(basePrefix, appUrl))) {
+ rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
+ } else {
+ rewrittenUrl = appBase + prevAppUrl;
+ }
+ } else if (isDefined(appUrl = beginsWith(appBaseNoFile, url))) {
+ rewrittenUrl = appBaseNoFile + appUrl;
+ } else if (appBaseNoFile == url + '/') {
+ rewrittenUrl = appBaseNoFile;
+ }
+ if (rewrittenUrl) {
+ this.$$parse(rewrittenUrl);
+ }
+ return !!rewrittenUrl;
+ };
+}
+
+
+/**
+ * LocationHashbangUrl represents url
+ * This object is exposed as $location service when developer doesn't opt into html5 mode.
+ * It also serves as the base class for html5 mode fallback on legacy browsers.
+ *
+ * @constructor
+ * @param {string} appBase application base URL
+ * @param {string} appBaseNoFile application base URL stripped of any filename
+ * @param {string} hashPrefix hashbang prefix
+ */
+function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
+
+ parseAbsoluteUrl(appBase, this);
+
+
+ /**
+ * Parse given hashbang url into properties
+ * @param {string} url Hashbang url
+ * @private
+ */
+ this.$$parse = function(url) {
+ var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
+ var withoutHashUrl;
+
+ if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
+
+ // The rest of the url starts with a hash so we have
+ // got either a hashbang path or a plain hash fragment
+ withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
+ if (isUndefined(withoutHashUrl)) {
+ // There was no hashbang prefix so we just have a hash fragment
+ withoutHashUrl = withoutBaseUrl;
+ }
+
+ } else {
+ // There was no hashbang path nor hash fragment:
+ // If we are in HTML5 mode we use what is left as the path;
+ // Otherwise we ignore what is left
+ if (this.$$html5) {
+ withoutHashUrl = withoutBaseUrl;
+ } else {
+ withoutHashUrl = '';
+ if (isUndefined(withoutBaseUrl)) {
+ appBase = url;
+ this.replace();
+ }
+ }
+ }
+
+ parseAppUrl(withoutHashUrl, this);
+
+ this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
+
+ this.$$compose();
+
+ /*
+ * In Windows, on an anchor node on documents loaded from
+ * the filesystem, the browser will return a pathname
+ * prefixed with the drive name ('/C:/path') when a
+ * pathname without a drive is set:
+ * * a.setAttribute('href', '/foo')
+ * * a.pathname === '/C:/foo' //true
+ *
+ * Inside of Angular, we're always using pathnames that
+ * do not include drive names for routing.
+ */
+ function removeWindowsDriveName(path, url, base) {
+ /*
+ Matches paths for file protocol on windows,
+ such as /C:/foo/bar, and captures only /foo/bar.
+ */
+ var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
+
+ var firstPathSegmentMatch;
+
+ //Get the relative path from the input URL.
+ if (url.indexOf(base) === 0) {
+ url = url.replace(base, '');
+ }
+
+ // The input URL intentionally contains a first path segment that ends with a colon.
+ if (windowsFilePathExp.exec(url)) {
+ return path;
+ }
+
+ firstPathSegmentMatch = windowsFilePathExp.exec(path);
+ return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
+ }
+ };
+
+ /**
+ * Compose hashbang url and update `absUrl` property
+ * @private
+ */
+ this.$$compose = function() {
+ var search = toKeyValue(this.$$search),
+ hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
+
+ this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
+ this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
+ };
+
+ this.$$parseLinkUrl = function(url, relHref) {
+ if (stripHash(appBase) == stripHash(url)) {
+ this.$$parse(url);
+ return true;
+ }
+ return false;
+ };
+}
+
+
+/**
+ * LocationHashbangUrl represents url
+ * This object is exposed as $location service when html5 history api is enabled but the browser
+ * does not support it.
+ *
+ * @constructor
+ * @param {string} appBase application base URL
+ * @param {string} appBaseNoFile application base URL stripped of any filename
+ * @param {string} hashPrefix hashbang prefix
+ */
+function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
+ this.$$html5 = true;
+ LocationHashbangUrl.apply(this, arguments);
+
+ this.$$parseLinkUrl = function(url, relHref) {
+ if (relHref && relHref[0] === '#') {
+ // special case for links to hash fragments:
+ // keep the old url and only replace the hash fragment
+ this.hash(relHref.slice(1));
+ return true;
+ }
+
+ var rewrittenUrl;
+ var appUrl;
+
+ if (appBase == stripHash(url)) {
+ rewrittenUrl = url;
+ } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
+ rewrittenUrl = appBase + hashPrefix + appUrl;
+ } else if (appBaseNoFile === url + '/') {
+ rewrittenUrl = appBaseNoFile;
+ }
+ if (rewrittenUrl) {
+ this.$$parse(rewrittenUrl);
+ }
+ return !!rewrittenUrl;
+ };
+
+ this.$$compose = function() {
+ var search = toKeyValue(this.$$search),
+ hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
+
+ this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
+ // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
+ this.$$absUrl = appBase + hashPrefix + this.$$url;
+ };
+
+}
+
+
+var locationPrototype = {
+
+ /**
+ * Are we in html5 mode?
+ * @private
+ */
+ $$html5: false,
+
+ /**
+ * Has any change been replacing?
+ * @private
+ */
+ $$replace: false,
+
+ /**
+ * @ngdoc method
+ * @name $location#absUrl
+ *
+ * @description
+ * This method is getter only.
+ *
+ * Return full url representation with all segments encoded according to rules specified in
+ * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
+ *
+ *
+ * ```js
+ * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
+ * var absUrl = $location.absUrl();
+ * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
+ * ```
+ *
+ * @return {string} full url
+ */
+ absUrl: locationGetter('$$absUrl'),
+
+ /**
+ * @ngdoc method
+ * @name $location#url
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
+ *
+ * Change path, search and hash, when called with parameter and return `$location`.
+ *
+ *
+ * ```js
+ * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
+ * var url = $location.url();
+ * // => "/some/path?foo=bar&baz=xoxo"
+ * ```
+ *
+ * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
+ * @return {string} url
+ */
+ url: function(url) {
+ if (isUndefined(url)) {
+ return this.$$url;
+ }
+
+ var match = PATH_MATCH.exec(url);
+ if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
+ if (match[2] || match[1] || url === '') this.search(match[3] || '');
+ this.hash(match[5] || '');
+
+ return this;
+ },
+
+ /**
+ * @ngdoc method
+ * @name $location#protocol
+ *
+ * @description
+ * This method is getter only.
+ *
+ * Return protocol of current url.
+ *
+ *
+ * ```js
+ * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
+ * var protocol = $location.protocol();
+ * // => "http"
+ * ```
+ *
+ * @return {string} protocol of current url
+ */
+ protocol: locationGetter('$$protocol'),
+
+ /**
+ * @ngdoc method
+ * @name $location#host
+ *
+ * @description
+ * This method is getter only.
+ *
+ * Return host of current url.
+ *
+ * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
+ *
+ *
+ * ```js
+ * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
+ * var host = $location.host();
+ * // => "example.com"
+ *
+ * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
+ * host = $location.host();
+ * // => "example.com"
+ * host = location.host;
+ * // => "example.com:8080"
+ * ```
+ *
+ * @return {string} host of current url.
+ */
+ host: locationGetter('$$host'),
+
+ /**
+ * @ngdoc method
+ * @name $location#port
+ *
+ * @description
+ * This method is getter only.
+ *
+ * Return port of current url.
+ *
+ *
+ * ```js
+ * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
+ * var port = $location.port();
+ * // => 80
+ * ```
+ *
+ * @return {Number} port
+ */
+ port: locationGetter('$$port'),
+
+ /**
+ * @ngdoc method
+ * @name $location#path
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Return path of current url when called without any parameter.
+ *
+ * Change path when called with parameter and return `$location`.
+ *
+ * Note: Path should always begin with forward slash (/), this method will add the forward slash
+ * if it is missing.
+ *
+ *
+ * ```js
+ * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
+ * var path = $location.path();
+ * // => "/some/path"
+ * ```
+ *
+ * @param {(string|number)=} path New path
+ * @return {string} path
+ */
+ path: locationGetterSetter('$$path', function(path) {
+ path = path !== null ? path.toString() : '';
+ return path.charAt(0) == '/' ? path : '/' + path;
+ }),
+
+ /**
+ * @ngdoc method
+ * @name $location#search
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Return search part (as object) of current url when called without any parameter.
+ *
+ * Change search part when called with parameter and return `$location`.
+ *
+ *
+ * ```js
+ * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
+ * var searchObject = $location.search();
+ * // => {foo: 'bar', baz: 'xoxo'}
+ *
+ * // set foo to 'yipee'
+ * $location.search('foo', 'yipee');
+ * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
+ * ```
+ *
+ * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
+ * hash object.
+ *
+ * When called with a single argument the method acts as a setter, setting the `search` component
+ * of `$location` to the specified value.
+ *
+ * If the argument is a hash object containing an array of values, these values will be encoded
+ * as duplicate search parameters in the url.
+ *
+ * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
+ * will override only a single search property.
+ *
+ * If `paramValue` is an array, it will override the property of the `search` component of
+ * `$location` specified via the first argument.
+ *
+ * If `paramValue` is `null`, the property specified via the first argument will be deleted.
+ *
+ * If `paramValue` is `true`, the property specified via the first argument will be added with no
+ * value nor trailing equal sign.
+ *
+ * @return {Object} If called with no arguments returns the parsed `search` object. If called with
+ * one or more arguments returns `$location` object itself.
+ */
+ search: function(search, paramValue) {
+ switch (arguments.length) {
+ case 0:
+ return this.$$search;
+ case 1:
+ if (isString(search) || isNumber(search)) {
+ search = search.toString();
+ this.$$search = parseKeyValue(search);
+ } else if (isObject(search)) {
+ search = copy(search, {});
+ // remove object undefined or null properties
+ forEach(search, function(value, key) {
+ if (value == null) delete search[key];
+ });
+
+ this.$$search = search;
+ } else {
+ throw $locationMinErr('isrcharg',
+ 'The first argument of the `$location#search()` call must be a string or an object.');
+ }
+ break;
+ default:
+ if (isUndefined(paramValue) || paramValue === null) {
+ delete this.$$search[search];
+ } else {
+ this.$$search[search] = paramValue;
+ }
+ }
+
+ this.$$compose();
+ return this;
+ },
+
+ /**
+ * @ngdoc method
+ * @name $location#hash
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Returns the hash fragment when called without any parameters.
+ *
+ * Changes the hash fragment when called with a parameter and returns `$location`.
+ *
+ *
+ * ```js
+ * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
+ * var hash = $location.hash();
+ * // => "hashValue"
+ * ```
+ *
+ * @param {(string|number)=} hash New hash fragment
+ * @return {string} hash
+ */
+ hash: locationGetterSetter('$$hash', function(hash) {
+ return hash !== null ? hash.toString() : '';
+ }),
+
+ /**
+ * @ngdoc method
+ * @name $location#replace
+ *
+ * @description
+ * If called, all changes to $location during the current `$digest` will replace the current history
+ * record, instead of adding a new one.
+ */
+ replace: function() {
+ this.$$replace = true;
+ return this;
+ }
+};
+
+forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
+ Location.prototype = Object.create(locationPrototype);
+
+ /**
+ * @ngdoc method
+ * @name $location#state
+ *
+ * @description
+ * This method is getter / setter.
+ *
+ * Return the history state object when called without any parameter.
+ *
+ * Change the history state object when called with one parameter and return `$location`.
+ * The state object is later passed to `pushState` or `replaceState`.
+ *
+ * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
+ * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
+ * older browsers (like IE9 or Android < 4.0), don't use this method.
+ *
+ * @param {object=} state State object for pushState or replaceState
+ * @return {object} state
+ */
+ Location.prototype.state = function(state) {
+ if (!arguments.length) {
+ return this.$$state;
+ }
+
+ if (Location !== LocationHtml5Url || !this.$$html5) {
+ throw $locationMinErr('nostate', 'History API state support is available only ' +
+ 'in HTML5 mode and only in browsers supporting HTML5 History API');
+ }
+ // The user might modify `stateObject` after invoking `$location.state(stateObject)`
+ // but we're changing the $$state reference to $browser.state() during the $digest
+ // so the modification window is narrow.
+ this.$$state = isUndefined(state) ? null : state;
+
+ return this;
+ };
+});
+
+
+function locationGetter(property) {
+ return function() {
+ return this[property];
+ };
+}
+
+
+function locationGetterSetter(property, preprocess) {
+ return function(value) {
+ if (isUndefined(value)) {
+ return this[property];
+ }
+
+ this[property] = preprocess(value);
+ this.$$compose();
+
+ return this;
+ };
+}
+
+
+/**
+ * @ngdoc service
+ * @name $location
+ *
+ * @requires $rootElement
+ *
+ * @description
+ * The $location service parses the URL in the browser address bar (based on the
+ * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
+ * available to your application. Changes to the URL in the address bar are reflected into
+ * $location service and changes to $location are reflected into the browser address bar.
+ *
+ * **The $location service:**
+ *
+ * - Exposes the current URL in the browser address bar, so you can
+ * - Watch and observe the URL.
+ * - Change the URL.
+ * - Synchronizes the URL with the browser when the user
+ * - Changes the address bar.
+ * - Clicks the back or forward button (or clicks a History link).
+ * - Clicks on a link.
+ * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
+ *
+ * For more information see {@link guide/$location Developer Guide: Using $location}
+ */
+
+/**
+ * @ngdoc provider
+ * @name $locationProvider
+ * @description
+ * Use the `$locationProvider` to configure how the application deep linking paths are stored.
+ */
+function $LocationProvider() {
+ var hashPrefix = '',
+ html5Mode = {
+ enabled: false,
+ requireBase: true,
+ rewriteLinks: true
+ };
+
+ /**
+ * @ngdoc method
+ * @name $locationProvider#hashPrefix
+ * @description
+ * @param {string=} prefix Prefix for hash part (containing path and search)
+ * @returns {*} current value if used as getter or itself (chaining) if used as setter
+ */
+ this.hashPrefix = function(prefix) {
+ if (isDefined(prefix)) {
+ hashPrefix = prefix;
+ return this;
+ } else {
+ return hashPrefix;
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name $locationProvider#html5Mode
+ * @description
+ * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
+ * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
+ * properties:
+ * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
+ * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
+ * support `pushState`.
+ * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
+ * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
+ * true, and a base tag is not present, an error will be thrown when `$location` is injected.
+ * See the {@link guide/$location $location guide for more information}
+ * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
+ * enables/disables url rewriting for relative links.
+ *
+ * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
+ */
+ this.html5Mode = function(mode) {
+ if (isBoolean(mode)) {
+ html5Mode.enabled = mode;
+ return this;
+ } else if (isObject(mode)) {
+
+ if (isBoolean(mode.enabled)) {
+ html5Mode.enabled = mode.enabled;
+ }
+
+ if (isBoolean(mode.requireBase)) {
+ html5Mode.requireBase = mode.requireBase;
+ }
+
+ if (isBoolean(mode.rewriteLinks)) {
+ html5Mode.rewriteLinks = mode.rewriteLinks;
+ }
+
+ return this;
+ } else {
+ return html5Mode;
+ }
+ };
+
+ /**
+ * @ngdoc event
+ * @name $location#$locationChangeStart
+ * @eventType broadcast on root scope
+ * @description
+ * Broadcasted before a URL will change.
+ *
+ * This change can be prevented by calling
+ * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
+ * details about event object. Upon successful change
+ * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
+ *
+ * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
+ * the browser supports the HTML5 History API.
+ *
+ * @param {Object} angularEvent Synthetic event object.
+ * @param {string} newUrl New URL
+ * @param {string=} oldUrl URL that was before it was changed.
+ * @param {string=} newState New history state object
+ * @param {string=} oldState History state object that was before it was changed.
+ */
+
+ /**
+ * @ngdoc event
+ * @name $location#$locationChangeSuccess
+ * @eventType broadcast on root scope
+ * @description
+ * Broadcasted after a URL was changed.
+ *
+ * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
+ * the browser supports the HTML5 History API.
+ *
+ * @param {Object} angularEvent Synthetic event object.
+ * @param {string} newUrl New URL
+ * @param {string=} oldUrl URL that was before it was changed.
+ * @param {string=} newState New history state object
+ * @param {string=} oldState History state object that was before it was changed.
+ */
+
+ this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
+ function($rootScope, $browser, $sniffer, $rootElement, $window) {
+ var $location,
+ LocationMode,
+ baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
+ initialUrl = $browser.url(),
+ appBase;
+
+ if (html5Mode.enabled) {
+ if (!baseHref && html5Mode.requireBase) {
+ throw $locationMinErr('nobase',
+ "$location in HTML5 mode requires a <base> tag to be present!");
+ }
+ appBase = serverBase(initialUrl) + (baseHref || '/');
+ LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
+ } else {
+ appBase = stripHash(initialUrl);
+ LocationMode = LocationHashbangUrl;
+ }
+ var appBaseNoFile = stripFile(appBase);
+
+ $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
+ $location.$$parseLinkUrl(initialUrl, initialUrl);
+
+ $location.$$state = $browser.state();
+
+ var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
+
+ function setBrowserUrlWithFallback(url, replace, state) {
+ var oldUrl = $location.url();
+ var oldState = $location.$$state;
+ try {
+ $browser.url(url, replace, state);
+
+ // Make sure $location.state() returns referentially identical (not just deeply equal)
+ // state object; this makes possible quick checking if the state changed in the digest
+ // loop. Checking deep equality would be too expensive.
+ $location.$$state = $browser.state();
+ } catch (e) {
+ // Restore old values if pushState fails
+ $location.url(oldUrl);
+ $location.$$state = oldState;
+
+ throw e;
+ }
+ }
+
+ $rootElement.on('click', function(event) {
+ // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
+ // currently we open nice url link and redirect then
+
+ if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
+
+ var elm = jqLite(event.target);
+
+ // traverse the DOM up to find first A tag
+ while (nodeName_(elm[0]) !== 'a') {
+ // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
+ if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
+ }
+
+ var absHref = elm.prop('href');
+ // get the actual href attribute - see
+ // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
+ var relHref = elm.attr('href') || elm.attr('xlink:href');
+
+ if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
+ // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
+ // an animation.
+ absHref = urlResolve(absHref.animVal).href;
+ }
+
+ // Ignore when url is started with javascript: or mailto:
+ if (IGNORE_URI_REGEXP.test(absHref)) return;
+
+ if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
+ if ($location.$$parseLinkUrl(absHref, relHref)) {
+ // We do a preventDefault for all urls that are part of the angular application,
+ // in html5mode and also without, so that we are able to abort navigation without
+ // getting double entries in the location history.
+ event.preventDefault();
+ // update location manually
+ if ($location.absUrl() != $browser.url()) {
+ $rootScope.$apply();
+ // hack to work around FF6 bug 684208 when scenario runner clicks on links
+ $window.angular['ff-684208-preventDefault'] = true;
+ }
+ }
+ }
+ });
+
+
+ // rewrite hashbang url <> html5 url
+ if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
+ $browser.url($location.absUrl(), true);
+ }
+
+ var initializing = true;
+
+ // update $location when $browser url changes
+ $browser.onUrlChange(function(newUrl, newState) {
+
+ if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
+ // If we are navigating outside of the app then force a reload
+ $window.location.href = newUrl;
+ return;
+ }
+
+ $rootScope.$evalAsync(function() {
+ var oldUrl = $location.absUrl();
+ var oldState = $location.$$state;
+ var defaultPrevented;
+ newUrl = trimEmptyHash(newUrl);
+ $location.$$parse(newUrl);
+ $location.$$state = newState;
+
+ defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
+ newState, oldState).defaultPrevented;
+
+ // if the location was changed by a `$locationChangeStart` handler then stop
+ // processing this location change
+ if ($location.absUrl() !== newUrl) return;
+
+ if (defaultPrevented) {
+ $location.$$parse(oldUrl);
+ $location.$$state = oldState;
+ setBrowserUrlWithFallback(oldUrl, false, oldState);
+ } else {
+ initializing = false;
+ afterLocationChange(oldUrl, oldState);
+ }
+ });
+ if (!$rootScope.$$phase) $rootScope.$digest();
+ });
+
+ // update browser
+ $rootScope.$watch(function $locationWatch() {
+ var oldUrl = trimEmptyHash($browser.url());
+ var newUrl = trimEmptyHash($location.absUrl());
+ var oldState = $browser.state();
+ var currentReplace = $location.$$replace;
+ var urlOrStateChanged = oldUrl !== newUrl ||
+ ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
+
+ if (initializing || urlOrStateChanged) {
+ initializing = false;
+
+ $rootScope.$evalAsync(function() {
+ var newUrl = $location.absUrl();
+ var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
+ $location.$$state, oldState).defaultPrevented;
+
+ // if the location was changed by a `$locationChangeStart` handler then stop
+ // processing this location change
+ if ($location.absUrl() !== newUrl) return;
+
+ if (defaultPrevented) {
+ $location.$$parse(oldUrl);
+ $location.$$state = oldState;
+ } else {
+ if (urlOrStateChanged) {
+ setBrowserUrlWithFallback(newUrl, currentReplace,
+ oldState === $location.$$state ? null : $location.$$state);
+ }
+ afterLocationChange(oldUrl, oldState);
+ }
+ });
+ }
+
+ $location.$$replace = false;
+
+ // we don't need to return anything because $evalAsync will make the digest loop dirty when
+ // there is a change
+ });
+
+ return $location;
+
+ function afterLocationChange(oldUrl, oldState) {
+ $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
+ $location.$$state, oldState);
+ }
+}];
+}
+
+/**
+ * @ngdoc service
+ * @name $log
+ * @requires $window
+ *
+ * @description
+ * Simple service for logging. Default implementation safely writes the message
+ * into the browser's console (if present).
+ *
+ * The main purpose of this service is to simplify debugging and troubleshooting.
+ *
+ * The default is to log `debug` messages. You can use
+ * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
+ *
+ * @example
+ <example module="logExample">
+ <file name="script.js">
+ angular.module('logExample', [])
+ .controller('LogController', ['$scope', '$log', function($scope, $log) {
+ $scope.$log = $log;
+ $scope.message = 'Hello World!';
+ }]);
+ </file>
+ <file name="index.html">
+ <div ng-controller="LogController">
+ <p>Reload this page with open console, enter text and hit the log button...</p>
+ <label>Message:
+ <input type="text" ng-model="message" /></label>
+ <button ng-click="$log.log(message)">log</button>
+ <button ng-click="$log.warn(message)">warn</button>
+ <button ng-click="$log.info(message)">info</button>
+ <button ng-click="$log.error(message)">error</button>
+ <button ng-click="$log.debug(message)">debug</button>
+ </div>
+ </file>
+ </example>
+ */
+
+/**
+ * @ngdoc provider
+ * @name $logProvider
+ * @description
+ * Use the `$logProvider` to configure how the application logs messages
+ */
+function $LogProvider() {
+ var debug = true,
+ self = this;
+
+ /**
+ * @ngdoc method
+ * @name $logProvider#debugEnabled
+ * @description
+ * @param {boolean=} flag enable or disable debug level messages
+ * @returns {*} current value if used as getter or itself (chaining) if used as setter
+ */
+ this.debugEnabled = function(flag) {
+ if (isDefined(flag)) {
+ debug = flag;
+ return this;
+ } else {
+ return debug;
+ }
+ };
+
+ this.$get = ['$window', function($window) {
+ return {
+ /**
+ * @ngdoc method
+ * @name $log#log
+ *
+ * @description
+ * Write a log message
+ */
+ log: consoleLog('log'),
+
+ /**
+ * @ngdoc method
+ * @name $log#info
+ *
+ * @description
+ * Write an information message
+ */
+ info: consoleLog('info'),
+
+ /**
+ * @ngdoc method
+ * @name $log#warn
+ *
+ * @description
+ * Write a warning message
+ */
+ warn: consoleLog('warn'),
+
+ /**
+ * @ngdoc method
+ * @name $log#error
+ *
+ * @description
+ * Write an error message
+ */
+ error: consoleLog('error'),
+
+ /**
+ * @ngdoc method
+ * @name $log#debug
+ *
+ * @description
+ * Write a debug message
+ */
+ debug: (function() {
+ var fn = consoleLog('debug');
+
+ return function() {
+ if (debug) {
+ fn.apply(self, arguments);
+ }
+ };
+ }())
+ };
+
+ function formatError(arg) {
+ if (arg instanceof Error) {
+ if (arg.stack) {
+ arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
+ ? 'Error: ' + arg.message + '\n' + arg.stack
+ : arg.stack;
+ } else if (arg.sourceURL) {
+ arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
+ }
+ }
+ return arg;
+ }
+
+ function consoleLog(type) {
+ var console = $window.console || {},
+ logFn = console[type] || console.log || noop,
+ hasApply = false;
+
+ // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
+ // The reason behind this is that console.log has type "object" in IE8...
+ try {
+ hasApply = !!logFn.apply;
+ } catch (e) {}
+
+ if (hasApply) {
+ return function() {
+ var args = [];
+ forEach(arguments, function(arg) {
+ args.push(formatError(arg));
+ });
+ return logFn.apply(console, args);
+ };
+ }
+
+ // we are IE which either doesn't have window.console => this is noop and we do nothing,
+ // or we are IE where console.log doesn't have apply so we log at least first 2 args
+ return function(arg1, arg2) {
+ logFn(arg1, arg2 == null ? '' : arg2);
+ };
+ }
+ }];
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Any commits to this file should be reviewed with security in mind. *
+ * Changes to this file can potentially create security vulnerabilities. *
+ * An approval from 2 Core members with history of modifying *
+ * this file is required. *
+ * *
+ * Does the change somehow allow for arbitrary javascript to be executed? *
+ * Or allows for someone to change the prototype of built-in objects? *
+ * Or gives undesired access to variables likes document or window? *
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+var $parseMinErr = minErr('$parse');
+
+// Sandboxing Angular Expressions
+// ------------------------------
+// Angular expressions are generally considered safe because these expressions only have direct
+// access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
+// obtaining a reference to native JS functions such as the Function constructor.
+//
+// As an example, consider the following Angular expression:
+//
+// {}.toString.constructor('alert("evil JS code")')
+//
+// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
+// against the expression language, but not to prevent exploits that were enabled by exposing
+// sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
+// practice and therefore we are not even trying to protect against interaction with an object
+// explicitly exposed in this way.
+//
+// In general, it is not possible to access a Window object from an angular expression unless a
+// window or some DOM object that has a reference to window is published onto a Scope.
+// Similarly we prevent invocations of function known to be dangerous, as well as assignments to
+// native objects.
+//
+// See https://docs.angularjs.org/guide/security
+
+
+function ensureSafeMemberName(name, fullExpression) {
+ if (name === "__defineGetter__" || name === "__defineSetter__"
+ || name === "__lookupGetter__" || name === "__lookupSetter__"
+ || name === "__proto__") {
+ throw $parseMinErr('isecfld',
+ 'Attempting to access a disallowed field in Angular expressions! '
+ + 'Expression: {0}', fullExpression);
+ }
+ return name;
+}
+
+function getStringValue(name, fullExpression) {
+ // From the JavaScript docs:
+ // Property names must be strings. This means that non-string objects cannot be used
+ // as keys in an object. Any non-string object, including a number, is typecasted
+ // into a string via the toString method.
+ //
+ // So, to ensure that we are checking the same `name` that JavaScript would use,
+ // we cast it to a string, if possible.
+ // Doing `name + ''` can cause a repl error if the result to `toString` is not a string,
+ // this is, this will handle objects that misbehave.
+ name = name + '';
+ if (!isString(name)) {
+ throw $parseMinErr('iseccst',
+ 'Cannot convert object to primitive value! '
+ + 'Expression: {0}', fullExpression);
+ }
+ return name;
+}
+
+function ensureSafeObject(obj, fullExpression) {
+ // nifty check if obj is Function that is fast and works across iframes and other contexts
+ if (obj) {
+ if (obj.constructor === obj) {
+ throw $parseMinErr('isecfn',
+ 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ } else if (// isWindow(obj)
+ obj.window === obj) {
+ throw $parseMinErr('isecwindow',
+ 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ } else if (// isElement(obj)
+ obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
+ throw $parseMinErr('isecdom',
+ 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ } else if (// block Object so that we can't get hold of dangerous Object.* methods
+ obj === Object) {
+ throw $parseMinErr('isecobj',
+ 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ }
+ }
+ return obj;
+}
+
+var CALL = Function.prototype.call;
+var APPLY = Function.prototype.apply;
+var BIND = Function.prototype.bind;
+
+function ensureSafeFunction(obj, fullExpression) {
+ if (obj) {
+ if (obj.constructor === obj) {
+ throw $parseMinErr('isecfn',
+ 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ } else if (obj === CALL || obj === APPLY || obj === BIND) {
+ throw $parseMinErr('isecff',
+ 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ }
+ }
+}
+
+function ensureSafeAssignContext(obj, fullExpression) {
+ if (obj) {
+ if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
+ obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
+ throw $parseMinErr('isecaf',
+ 'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
+ }
+ }
+}
+
+var OPERATORS = createMap();
+forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
+var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
+
+
+/////////////////////////////////////////
+
+
+/**
+ * @constructor
+ */
+var Lexer = function(options) {
+ this.options = options;
+};
+
+Lexer.prototype = {
+ constructor: Lexer,
+
+ lex: function(text) {
+ this.text = text;
+ this.index = 0;
+ this.tokens = [];
+
+ while (this.index < this.text.length) {
+ var ch = this.text.charAt(this.index);
+ if (ch === '"' || ch === "'") {
+ this.readString(ch);
+ } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
+ this.readNumber();
+ } else if (this.isIdent(ch)) {
+ this.readIdent();
+ } else if (this.is(ch, '(){}[].,;:?')) {
+ this.tokens.push({index: this.index, text: ch});
+ this.index++;
+ } else if (this.isWhitespace(ch)) {
+ this.index++;
+ } else {
+ var ch2 = ch + this.peek();
+ var ch3 = ch2 + this.peek(2);
+ var op1 = OPERATORS[ch];
+ var op2 = OPERATORS[ch2];
+ var op3 = OPERATORS[ch3];
+ if (op1 || op2 || op3) {
+ var token = op3 ? ch3 : (op2 ? ch2 : ch);
+ this.tokens.push({index: this.index, text: token, operator: true});
+ this.index += token.length;
+ } else {
+ this.throwError('Unexpected next character ', this.index, this.index + 1);
+ }
+ }
+ }
+ return this.tokens;
+ },
+
+ is: function(ch, chars) {
+ return chars.indexOf(ch) !== -1;
+ },
+
+ peek: function(i) {
+ var num = i || 1;
+ return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
+ },
+
+ isNumber: function(ch) {
+ return ('0' <= ch && ch <= '9') && typeof ch === "string";
+ },
+
+ isWhitespace: function(ch) {
+ // IE treats non-breaking space as \u00A0
+ return (ch === ' ' || ch === '\r' || ch === '\t' ||
+ ch === '\n' || ch === '\v' || ch === '\u00A0');
+ },
+
+ isIdent: function(ch) {
+ return ('a' <= ch && ch <= 'z' ||
+ 'A' <= ch && ch <= 'Z' ||
+ '_' === ch || ch === '$');
+ },
+
+ isExpOperator: function(ch) {
+ return (ch === '-' || ch === '+' || this.isNumber(ch));
+ },
+
+ throwError: function(error, start, end) {
+ end = end || this.index;
+ var colStr = (isDefined(start)
+ ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
+ : ' ' + end);
+ throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
+ error, colStr, this.text);
+ },
+
+ readNumber: function() {
+ var number = '';
+ var start = this.index;
+ while (this.index < this.text.length) {
+ var ch = lowercase(this.text.charAt(this.index));
+ if (ch == '.' || this.isNumber(ch)) {
+ number += ch;
+ } else {
+ var peekCh = this.peek();
+ if (ch == 'e' && this.isExpOperator(peekCh)) {
+ number += ch;
+ } else if (this.isExpOperator(ch) &&
+ peekCh && this.isNumber(peekCh) &&
+ number.charAt(number.length - 1) == 'e') {
+ number += ch;
+ } else if (this.isExpOperator(ch) &&
+ (!peekCh || !this.isNumber(peekCh)) &&
+ number.charAt(number.length - 1) == 'e') {
+ this.throwError('Invalid exponent');
+ } else {
+ break;
+ }
+ }
+ this.index++;
+ }
+ this.tokens.push({
+ index: start,
+ text: number,
+ constant: true,
+ value: Number(number)
+ });
+ },
+
+ readIdent: function() {
+ var start = this.index;
+ while (this.index < this.text.length) {
+ var ch = this.text.charAt(this.index);
+ if (!(this.isIdent(ch) || this.isNumber(ch))) {
+ break;
+ }
+ this.index++;
+ }
+ this.tokens.push({
+ index: start,
+ text: this.text.slice(start, this.index),
+ identifier: true
+ });
+ },
+
+ readString: function(quote) {
+ var start = this.index;
+ this.index++;
+ var string = '';
+ var rawString = quote;
+ var escape = false;
+ while (this.index < this.text.length) {
+ var ch = this.text.charAt(this.index);
+ rawString += ch;
+ if (escape) {
+ if (ch === 'u') {
+ var hex = this.text.substring(this.index + 1, this.index + 5);
+ if (!hex.match(/[\da-f]{4}/i)) {
+ this.throwError('Invalid unicode escape [\\u' + hex + ']');
+ }
+ this.index += 4;
+ string += String.fromCharCode(parseInt(hex, 16));
+ } else {
+ var rep = ESCAPE[ch];
+ string = string + (rep || ch);
+ }
+ escape = false;
+ } else if (ch === '\\') {
+ escape = true;
+ } else if (ch === quote) {
+ this.index++;
+ this.tokens.push({
+ index: start,
+ text: rawString,
+ constant: true,
+ value: string
+ });
+ return;
+ } else {
+ string += ch;
+ }
+ this.index++;
+ }
+ this.throwError('Unterminated quote', start);
+ }
+};
+
+var AST = function(lexer, options) {
+ this.lexer = lexer;
+ this.options = options;
+};
+
+AST.Program = 'Program';
+AST.ExpressionStatement = 'ExpressionStatement';
+AST.AssignmentExpression = 'AssignmentExpression';
+AST.ConditionalExpression = 'ConditionalExpression';
+AST.LogicalExpression = 'LogicalExpression';
+AST.BinaryExpression = 'BinaryExpression';
+AST.UnaryExpression = 'UnaryExpression';
+AST.CallExpression = 'CallExpression';
+AST.MemberExpression = 'MemberExpression';
+AST.Identifier = 'Identifier';
+AST.Literal = 'Literal';
+AST.ArrayExpression = 'ArrayExpression';
+AST.Property = 'Property';
+AST.ObjectExpression = 'ObjectExpression';
+AST.ThisExpression = 'ThisExpression';
+
+// Internal use only
+AST.NGValueParameter = 'NGValueParameter';
+
+AST.prototype = {
+ ast: function(text) {
+ this.text = text;
+ this.tokens = this.lexer.lex(text);
+
+ var value = this.program();
+
+ if (this.tokens.length !== 0) {
+ this.throwError('is an unexpected token', this.tokens[0]);
+ }
+
+ return value;
+ },
+
+ program: function() {
+ var body = [];
+ while (true) {
+ if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
+ body.push(this.expressionStatement());
+ if (!this.expect(';')) {
+ return { type: AST.Program, body: body};
+ }
+ }
+ },
+
+ expressionStatement: function() {
+ return { type: AST.ExpressionStatement, expression: this.filterChain() };
+ },
+
+ filterChain: function() {
+ var left = this.expression();
+ var token;
+ while ((token = this.expect('|'))) {
+ left = this.filter(left);
+ }
+ return left;
+ },
+
+ expression: function() {
+ return this.assignment();
+ },
+
+ assignment: function() {
+ var result = this.ternary();
+ if (this.expect('=')) {
+ result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
+ }
+ return result;
+ },
+
+ ternary: function() {
+ var test = this.logicalOR();
+ var alternate;
+ var consequent;
+ if (this.expect('?')) {
+ alternate = this.expression();
+ if (this.consume(':')) {
+ consequent = this.expression();
+ return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
+ }
+ }
+ return test;
+ },
+
+ logicalOR: function() {
+ var left = this.logicalAND();
+ while (this.expect('||')) {
+ left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
+ }
+ return left;
+ },
+
+ logicalAND: function() {
+ var left = this.equality();
+ while (this.expect('&&')) {
+ left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
+ }
+ return left;
+ },
+
+ equality: function() {
+ var left = this.relational();
+ var token;
+ while ((token = this.expect('==','!=','===','!=='))) {
+ left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
+ }
+ return left;
+ },
+
+ relational: function() {
+ var left = this.additive();
+ var token;
+ while ((token = this.expect('<', '>', '<=', '>='))) {
+ left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
+ }
+ return left;
+ },
+
+ additive: function() {
+ var left = this.multiplicative();
+ var token;
+ while ((token = this.expect('+','-'))) {
+ left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
+ }
+ return left;
+ },
+
+ multiplicative: function() {
+ var left = this.unary();
+ var token;
+ while ((token = this.expect('*','/','%'))) {
+ left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
+ }
+ return left;
+ },
+
+ unary: function() {
+ var token;
+ if ((token = this.expect('+', '-', '!'))) {
+ return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
+ } else {
+ return this.primary();
+ }
+ },
+
+ primary: function() {
+ var primary;
+ if (this.expect('(')) {
+ primary = this.filterChain();
+ this.consume(')');
+ } else if (this.expect('[')) {
+ primary = this.arrayDeclaration();
+ } else if (this.expect('{')) {
+ primary = this.object();
+ } else if (this.constants.hasOwnProperty(this.peek().text)) {
+ primary = copy(this.constants[this.consume().text]);
+ } else if (this.peek().identifier) {
+ primary = this.identifier();
+ } else if (this.peek().constant) {
+ primary = this.constant();
+ } else {
+ this.throwError('not a primary expression', this.peek());
+ }
+
+ var next;
+ while ((next = this.expect('(', '[', '.'))) {
+ if (next.text === '(') {
+ primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
+ this.consume(')');
+ } else if (next.text === '[') {
+ primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
+ this.consume(']');
+ } else if (next.text === '.') {
+ primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
+ } else {
+ this.throwError('IMPOSSIBLE');
+ }
+ }
+ return primary;
+ },
+
+ filter: function(baseExpression) {
+ var args = [baseExpression];
+ var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
+
+ while (this.expect(':')) {
+ args.push(this.expression());
+ }
+
+ return result;
+ },
+
+ parseArguments: function() {
+ var args = [];
+ if (this.peekToken().text !== ')') {
+ do {
+ args.push(this.expression());
+ } while (this.expect(','));
+ }
+ return args;
+ },
+
+ identifier: function() {
+ var token = this.consume();
+ if (!token.identifier) {
+ this.throwError('is not a valid identifier', token);
+ }
+ return { type: AST.Identifier, name: token.text };
+ },
+
+ constant: function() {
+ // TODO check that it is a constant
+ return { type: AST.Literal, value: this.consume().value };
+ },
+
+ arrayDeclaration: function() {
+ var elements = [];
+ if (this.peekToken().text !== ']') {
+ do {
+ if (this.peek(']')) {
+ // Support trailing commas per ES5.1.
+ break;
+ }
+ elements.push(this.expression());
+ } while (this.expect(','));
+ }
+ this.consume(']');
+
+ return { type: AST.ArrayExpression, elements: elements };
+ },
+
+ object: function() {
+ var properties = [], property;
+ if (this.peekToken().text !== '}') {
+ do {
+ if (this.peek('}')) {
+ // Support trailing commas per ES5.1.
+ break;
+ }
+ property = {type: AST.Property, kind: 'init'};
+ if (this.peek().constant) {
+ property.key = this.constant();
+ } else if (this.peek().identifier) {
+ property.key = this.identifier();
+ } else {
+ this.throwError("invalid key", this.peek());
+ }
+ this.consume(':');
+ property.value = this.expression();
+ properties.push(property);
+ } while (this.expect(','));
+ }
+ this.consume('}');
+
+ return {type: AST.ObjectExpression, properties: properties };
+ },
+
+ throwError: function(msg, token) {
+ throw $parseMinErr('syntax',
+ 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
+ token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
+ },
+
+ consume: function(e1) {
+ if (this.tokens.length === 0) {
+ throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
+ }
+
+ var token = this.expect(e1);
+ if (!token) {
+ this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
+ }
+ return token;
+ },
+
+ peekToken: function() {
+ if (this.tokens.length === 0) {
+ throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
+ }
+ return this.tokens[0];
+ },
+
+ peek: function(e1, e2, e3, e4) {
+ return this.peekAhead(0, e1, e2, e3, e4);
+ },
+
+ peekAhead: function(i, e1, e2, e3, e4) {
+ if (this.tokens.length > i) {
+ var token = this.tokens[i];
+ var t = token.text;
+ if (t === e1 || t === e2 || t === e3 || t === e4 ||
+ (!e1 && !e2 && !e3 && !e4)) {
+ return token;
+ }
+ }
+ return false;
+ },
+
+ expect: function(e1, e2, e3, e4) {
+ var token = this.peek(e1, e2, e3, e4);
+ if (token) {
+ this.tokens.shift();
+ return token;
+ }
+ return false;
+ },
+
+
+ /* `undefined` is not a constant, it is an identifier,
+ * but using it as an identifier is not supported
+ */
+ constants: {
+ 'true': { type: AST.Literal, value: true },
+ 'false': { type: AST.Literal, value: false },
+ 'null': { type: AST.Literal, value: null },
+ 'undefined': {type: AST.Literal, value: undefined },
+ 'this': {type: AST.ThisExpression }
+ }
+};
+
+function ifDefined(v, d) {
+ return typeof v !== 'undefined' ? v : d;
+}
+
+function plusFn(l, r) {
+ if (typeof l === 'undefined') return r;
+ if (typeof r === 'undefined') return l;
+ return l + r;
+}
+
+function isStateless($filter, filterName) {
+ var fn = $filter(filterName);
+ return !fn.$stateful;
+}
+
+function findConstantAndWatchExpressions(ast, $filter) {
+ var allConstants;
+ var argsToWatch;
+ switch (ast.type) {
+ case AST.Program:
+ allConstants = true;
+ forEach(ast.body, function(expr) {
+ findConstantAndWatchExpressions(expr.expression, $filter);
+ allConstants = allConstants && expr.expression.constant;
+ });
+ ast.constant = allConstants;
+ break;
+ case AST.Literal:
+ ast.constant = true;
+ ast.toWatch = [];
+ break;
+ case AST.UnaryExpression:
+ findConstantAndWatchExpressions(ast.argument, $filter);
+ ast.constant = ast.argument.constant;
+ ast.toWatch = ast.argument.toWatch;
+ break;
+ case AST.BinaryExpression:
+ findConstantAndWatchExpressions(ast.left, $filter);
+ findConstantAndWatchExpressions(ast.right, $filter);
+ ast.constant = ast.left.constant && ast.right.constant;
+ ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
+ break;
+ case AST.LogicalExpression:
+ findConstantAndWatchExpressions(ast.left, $filter);
+ findConstantAndWatchExpressions(ast.right, $filter);
+ ast.constant = ast.left.constant && ast.right.constant;
+ ast.toWatch = ast.constant ? [] : [ast];
+ break;
+ case AST.ConditionalExpression:
+ findConstantAndWatchExpressions(ast.test, $filter);
+ findConstantAndWatchExpressions(ast.alternate, $filter);
+ findConstantAndWatchExpressions(ast.consequent, $filter);
+ ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
+ ast.toWatch = ast.constant ? [] : [ast];
+ break;
+ case AST.Identifier:
+ ast.constant = false;
+ ast.toWatch = [ast];
+ break;
+ case AST.MemberExpression:
+ findConstantAndWatchExpressions(ast.object, $filter);
+ if (ast.computed) {
+ findConstantAndWatchExpressions(ast.property, $filter);
+ }
+ ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
+ ast.toWatch = [ast];
+ break;
+ case AST.CallExpression:
+ allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
+ argsToWatch = [];
+ forEach(ast.arguments, function(expr) {
+ findConstantAndWatchExpressions(expr, $filter);
+ allConstants = allConstants && expr.constant;
+ if (!expr.constant) {
+ argsToWatch.push.apply(argsToWatch, expr.toWatch);
+ }
+ });
+ ast.constant = allConstants;
+ ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
+ break;
+ case AST.AssignmentExpression:
+ findConstantAndWatchExpressions(ast.left, $filter);
+ findConstantAndWatchExpressions(ast.right, $filter);
+ ast.constant = ast.left.constant && ast.right.constant;
+ ast.toWatch = [ast];
+ break;
+ case AST.ArrayExpression:
+ allConstants = true;
+ argsToWatch = [];
+ forEach(ast.elements, function(expr) {
+ findConstantAndWatchExpressions(expr, $filter);
+ allConstants = allConstants && expr.constant;
+ if (!expr.constant) {
+ argsToWatch.push.apply(argsToWatch, expr.toWatch);
+ }
+ });
+ ast.constant = allConstants;
+ ast.toWatch = argsToWatch;
+ break;
+ case AST.ObjectExpression:
+ allConstants = true;
+ argsToWatch = [];
+ forEach(ast.properties, function(property) {
+ findConstantAndWatchExpressions(property.value, $filter);
+ allConstants = allConstants && property.value.constant;
+ if (!property.value.constant) {
+ argsToWatch.push.apply(argsToWatch, property.value.toWatch);
+ }
+ });
+ ast.constant = allConstants;
+ ast.toWatch = argsToWatch;
+ break;
+ case AST.ThisExpression:
+ ast.constant = false;
+ ast.toWatch = [];
+ break;
+ }
+}
+
+function getInputs(body) {
+ if (body.length != 1) return;
+ var lastExpression = body[0].expression;
+ var candidate = lastExpression.toWatch;
+ if (candidate.length !== 1) return candidate;
+ return candidate[0] !== lastExpression ? candidate : undefined;
+}
+
+function isAssignable(ast) {
+ return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
+}
+
+function assignableAST(ast) {
+ if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
+ return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
+ }
+}
+
+function isLiteral(ast) {
+ return ast.body.length === 0 ||
+ ast.body.length === 1 && (
+ ast.body[0].expression.type === AST.Literal ||
+ ast.body[0].expression.type === AST.ArrayExpression ||
+ ast.body[0].expression.type === AST.ObjectExpression);
+}
+
+function isConstant(ast) {
+ return ast.constant;
+}
+
+function ASTCompiler(astBuilder, $filter) {
+ this.astBuilder = astBuilder;
+ this.$filter = $filter;
+}
+
+ASTCompiler.prototype = {
+ compile: function(expression, expensiveChecks) {
+ var self = this;
+ var ast = this.astBuilder.ast(expression);
+ this.state = {
+ nextId: 0,
+ filters: {},
+ expensiveChecks: expensiveChecks,
+ fn: {vars: [], body: [], own: {}},
+ assign: {vars: [], body: [], own: {}},
+ inputs: []
+ };
+ findConstantAndWatchExpressions(ast, self.$filter);
+ var extra = '';
+ var assignable;
+ this.stage = 'assign';
+ if ((assignable = assignableAST(ast))) {
+ this.state.computing = 'assign';
+ var result = this.nextId();
+ this.recurse(assignable, result);
+ this.return_(result);
+ extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
+ }
+ var toWatch = getInputs(ast.body);
+ self.stage = 'inputs';
+ forEach(toWatch, function(watch, key) {
+ var fnKey = 'fn' + key;
+ self.state[fnKey] = {vars: [], body: [], own: {}};
+ self.state.computing = fnKey;
+ var intoId = self.nextId();
+ self.recurse(watch, intoId);
+ self.return_(intoId);
+ self.state.inputs.push(fnKey);
+ watch.watchId = key;
+ });
+ this.state.computing = 'fn';
+ this.stage = 'main';
+ this.recurse(ast);
+ var fnString =
+ // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
+ // This is a workaround for this until we do a better job at only removing the prefix only when we should.
+ '"' + this.USE + ' ' + this.STRICT + '";\n' +
+ this.filterPrefix() +
+ 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
+ extra +
+ this.watchFns() +
+ 'return fn;';
+
+ /* jshint -W054 */
+ var fn = (new Function('$filter',
+ 'ensureSafeMemberName',
+ 'ensureSafeObject',
+ 'ensureSafeFunction',
+ 'getStringValue',
+ 'ensureSafeAssignContext',
+ 'ifDefined',
+ 'plus',
+ 'text',
+ fnString))(
+ this.$filter,
+ ensureSafeMemberName,
+ ensureSafeObject,
+ ensureSafeFunction,
+ getStringValue,
+ ensureSafeAssignContext,
+ ifDefined,
+ plusFn,
+ expression);
+ /* jshint +W054 */
+ this.state = this.stage = undefined;
+ fn.literal = isLiteral(ast);
+ fn.constant = isConstant(ast);
+ return fn;
+ },
+
+ USE: 'use',
+
+ STRICT: 'strict',
+
+ watchFns: function() {
+ var result = [];
+ var fns = this.state.inputs;
+ var self = this;
+ forEach(fns, function(name) {
+ result.push('var ' + name + '=' + self.generateFunction(name, 's'));
+ });
+ if (fns.length) {
+ result.push('fn.inputs=[' + fns.join(',') + '];');
+ }
+ return result.join('');
+ },
+
+ generateFunction: function(name, params) {
+ return 'function(' + params + '){' +
+ this.varsPrefix(name) +
+ this.body(name) +
+ '};';
+ },
+
+ filterPrefix: function() {
+ var parts = [];
+ var self = this;
+ forEach(this.state.filters, function(id, filter) {
+ parts.push(id + '=$filter(' + self.escape(filter) + ')');
+ });
+ if (parts.length) return 'var ' + parts.join(',') + ';';
+ return '';
+ },
+
+ varsPrefix: function(section) {
+ return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
+ },
+
+ body: function(section) {
+ return this.state[section].body.join('');
+ },
+
+ recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
+ var left, right, self = this, args, expression;
+ recursionFn = recursionFn || noop;
+ if (!skipWatchIdCheck && isDefined(ast.watchId)) {
+ intoId = intoId || this.nextId();
+ this.if_('i',
+ this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
+ this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
+ );
+ return;
+ }
+ switch (ast.type) {
+ case AST.Program:
+ forEach(ast.body, function(expression, pos) {
+ self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
+ if (pos !== ast.body.length - 1) {
+ self.current().body.push(right, ';');
+ } else {
+ self.return_(right);
+ }
+ });
+ break;
+ case AST.Literal:
+ expression = this.escape(ast.value);
+ this.assign(intoId, expression);
+ recursionFn(expression);
+ break;
+ case AST.UnaryExpression:
+ this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
+ expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
+ this.assign(intoId, expression);
+ recursionFn(expression);
+ break;
+ case AST.BinaryExpression:
+ this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
+ this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
+ if (ast.operator === '+') {
+ expression = this.plus(left, right);
+ } else if (ast.operator === '-') {
+ expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
+ } else {
+ expression = '(' + left + ')' + ast.operator + '(' + right + ')';
+ }
+ this.assign(intoId, expression);
+ recursionFn(expression);
+ break;
+ case AST.LogicalExpression:
+ intoId = intoId || this.nextId();
+ self.recurse(ast.left, intoId);
+ self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
+ recursionFn(intoId);
+ break;
+ case AST.ConditionalExpression:
+ intoId = intoId || this.nextId();
+ self.recurse(ast.test, intoId);
+ self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
+ recursionFn(intoId);
+ break;
+ case AST.Identifier:
+ intoId = intoId || this.nextId();
+ if (nameId) {
+ nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
+ nameId.computed = false;
+ nameId.name = ast.name;
+ }
+ ensureSafeMemberName(ast.name);
+ self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
+ function() {
+ self.if_(self.stage === 'inputs' || 's', function() {
+ if (create && create !== 1) {
+ self.if_(
+ self.not(self.nonComputedMember('s', ast.name)),
+ self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
+ }
+ self.assign(intoId, self.nonComputedMember('s', ast.name));
+ });
+ }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
+ );
+ if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
+ self.addEnsureSafeObject(intoId);
+ }
+ recursionFn(intoId);
+ break;
+ case AST.MemberExpression:
+ left = nameId && (nameId.context = this.nextId()) || this.nextId();
+ intoId = intoId || this.nextId();
+ self.recurse(ast.object, left, undefined, function() {
+ self.if_(self.notNull(left), function() {
+ if (ast.computed) {
+ right = self.nextId();
+ self.recurse(ast.property, right);
+ self.getStringValue(right);
+ self.addEnsureSafeMemberName(right);
+ if (create && create !== 1) {
+ self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
+ }
+ expression = self.ensureSafeObject(self.computedMember(left, right));
+ self.assign(intoId, expression);
+ if (nameId) {
+ nameId.computed = true;
+ nameId.name = right;
+ }
+ } else {
+ ensureSafeMemberName(ast.property.name);
+ if (create && create !== 1) {
+ self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
+ }
+ expression = self.nonComputedMember(left, ast.property.name);
+ if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
+ expression = self.ensureSafeObject(expression);
+ }
+ self.assign(intoId, expression);
+ if (nameId) {
+ nameId.computed = false;
+ nameId.name = ast.property.name;
+ }
+ }
+ }, function() {
+ self.assign(intoId, 'undefined');
+ });
+ recursionFn(intoId);
+ }, !!create);
+ break;
+ case AST.CallExpression:
+ intoId = intoId || this.nextId();
+ if (ast.filter) {
+ right = self.filter(ast.callee.name);
+ args = [];
+ forEach(ast.arguments, function(expr) {
+ var argument = self.nextId();
+ self.recurse(expr, argument);
+ args.push(argument);
+ });
+ expression = right + '(' + args.join(',') + ')';
+ self.assign(intoId, expression);
+ recursionFn(intoId);
+ } else {
+ right = self.nextId();
+ left = {};
+ args = [];
+ self.recurse(ast.callee, right, left, function() {
+ self.if_(self.notNull(right), function() {
+ self.addEnsureSafeFunction(right);
+ forEach(ast.arguments, function(expr) {
+ self.recurse(expr, self.nextId(), undefined, function(argument) {
+ args.push(self.ensureSafeObject(argument));
+ });
+ });
+ if (left.name) {
+ if (!self.state.expensiveChecks) {
+ self.addEnsureSafeObject(left.context);
+ }
+ expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
+ } else {
+ expression = right + '(' + args.join(',') + ')';
+ }
+ expression = self.ensureSafeObject(expression);
+ self.assign(intoId, expression);
+ }, function() {
+ self.assign(intoId, 'undefined');
+ });
+ recursionFn(intoId);
+ });
+ }
+ break;
+ case AST.AssignmentExpression:
+ right = this.nextId();
+ left = {};
+ if (!isAssignable(ast.left)) {
+ throw $parseMinErr('lval', 'Trying to assing a value to a non l-value');
+ }
+ this.recurse(ast.left, undefined, left, function() {
+ self.if_(self.notNull(left.context), function() {
+ self.recurse(ast.right, right);
+ self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
+ self.addEnsureSafeAssignContext(left.context);
+ expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
+ self.assign(intoId, expression);
+ recursionFn(intoId || expression);
+ });
+ }, 1);
+ break;
+ case AST.ArrayExpression:
+ args = [];
+ forEach(ast.elements, function(expr) {
+ self.recurse(expr, self.nextId(), undefined, function(argument) {
+ args.push(argument);
+ });
+ });
+ expression = '[' + args.join(',') + ']';
+ this.assign(intoId, expression);
+ recursionFn(expression);
+ break;
+ case AST.ObjectExpression:
+ args = [];
+ forEach(ast.properties, function(property) {
+ self.recurse(property.value, self.nextId(), undefined, function(expr) {
+ args.push(self.escape(
+ property.key.type === AST.Identifier ? property.key.name :
+ ('' + property.key.value)) +
+ ':' + expr);
+ });
+ });
+ expression = '{' + args.join(',') + '}';
+ this.assign(intoId, expression);
+ recursionFn(expression);
+ break;
+ case AST.ThisExpression:
+ this.assign(intoId, 's');
+ recursionFn('s');
+ break;
+ case AST.NGValueParameter:
+ this.assign(intoId, 'v');
+ recursionFn('v');
+ break;
+ }
+ },
+
+ getHasOwnProperty: function(element, property) {
+ var key = element + '.' + property;
+ var own = this.current().own;
+ if (!own.hasOwnProperty(key)) {
+ own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
+ }
+ return own[key];
+ },
+
+ assign: function(id, value) {
+ if (!id) return;
+ this.current().body.push(id, '=', value, ';');
+ return id;
+ },
+
+ filter: function(filterName) {
+ if (!this.state.filters.hasOwnProperty(filterName)) {
+ this.state.filters[filterName] = this.nextId(true);
+ }
+ return this.state.filters[filterName];
+ },
+
+ ifDefined: function(id, defaultValue) {
+ return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
+ },
+
+ plus: function(left, right) {
+ return 'plus(' + left + ',' + right + ')';
+ },
+
+ return_: function(id) {
+ this.current().body.push('return ', id, ';');
+ },
+
+ if_: function(test, alternate, consequent) {
+ if (test === true) {
+ alternate();
+ } else {
+ var body = this.current().body;
+ body.push('if(', test, '){');
+ alternate();
+ body.push('}');
+ if (consequent) {
+ body.push('else{');
+ consequent();
+ body.push('}');
+ }
+ }
+ },
+
+ not: function(expression) {
+ return '!(' + expression + ')';
+ },
+
+ notNull: function(expression) {
+ return expression + '!=null';
+ },
+
+ nonComputedMember: function(left, right) {
+ return left + '.' + right;
+ },
+
+ computedMember: function(left, right) {
+ return left + '[' + right + ']';
+ },
+
+ member: function(left, right, computed) {
+ if (computed) return this.computedMember(left, right);
+ return this.nonComputedMember(left, right);
+ },
+
+ addEnsureSafeObject: function(item) {
+ this.current().body.push(this.ensureSafeObject(item), ';');
+ },
+
+ addEnsureSafeMemberName: function(item) {
+ this.current().body.push(this.ensureSafeMemberName(item), ';');
+ },
+
+ addEnsureSafeFunction: function(item) {
+ this.current().body.push(this.ensureSafeFunction(item), ';');
+ },
+
+ addEnsureSafeAssignContext: function(item) {
+ this.current().body.push(this.ensureSafeAssignContext(item), ';');
+ },
+
+ ensureSafeObject: function(item) {
+ return 'ensureSafeObject(' + item + ',text)';
+ },
+
+ ensureSafeMemberName: function(item) {
+ return 'ensureSafeMemberName(' + item + ',text)';
+ },
+
+ ensureSafeFunction: function(item) {
+ return 'ensureSafeFunction(' + item + ',text)';
+ },
+
+ getStringValue: function(item) {
+ this.assign(item, 'getStringValue(' + item + ',text)');
+ },
+
+ ensureSafeAssignContext: function(item) {
+ return 'ensureSafeAssignContext(' + item + ',text)';
+ },
+
+ lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
+ var self = this;
+ return function() {
+ self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
+ };
+ },
+
+ lazyAssign: function(id, value) {
+ var self = this;
+ return function() {
+ self.assign(id, value);
+ };
+ },
+
+ stringEscapeRegex: /[^ a-zA-Z0-9]/g,
+
+ stringEscapeFn: function(c) {
+ return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
+ },
+
+ escape: function(value) {
+ if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
+ if (isNumber(value)) return value.toString();
+ if (value === true) return 'true';
+ if (value === false) return 'false';
+ if (value === null) return 'null';
+ if (typeof value === 'undefined') return 'undefined';
+
+ throw $parseMinErr('esc', 'IMPOSSIBLE');
+ },
+
+ nextId: function(skip, init) {
+ var id = 'v' + (this.state.nextId++);
+ if (!skip) {
+ this.current().vars.push(id + (init ? '=' + init : ''));
+ }
+ return id;
+ },
+
+ current: function() {
+ return this.state[this.state.computing];
+ }
+};
+
+
+function ASTInterpreter(astBuilder, $filter) {
+ this.astBuilder = astBuilder;
+ this.$filter = $filter;
+}
+
+ASTInterpreter.prototype = {
+ compile: function(expression, expensiveChecks) {
+ var self = this;
+ var ast = this.astBuilder.ast(expression);
+ this.expression = expression;
+ this.expensiveChecks = expensiveChecks;
+ findConstantAndWatchExpressions(ast, self.$filter);
+ var assignable;
+ var assign;
+ if ((assignable = assignableAST(ast))) {
+ assign = this.recurse(assignable);
+ }
+ var toWatch = getInputs(ast.body);
+ var inputs;
+ if (toWatch) {
+ inputs = [];
+ forEach(toWatch, function(watch, key) {
+ var input = self.recurse(watch);
+ watch.input = input;
+ inputs.push(input);
+ watch.watchId = key;
+ });
+ }
+ var expressions = [];
+ forEach(ast.body, function(expression) {
+ expressions.push(self.recurse(expression.expression));
+ });
+ var fn = ast.body.length === 0 ? function() {} :
+ ast.body.length === 1 ? expressions[0] :
+ function(scope, locals) {
+ var lastValue;
+ forEach(expressions, function(exp) {
+ lastValue = exp(scope, locals);
+ });
+ return lastValue;
+ };
+ if (assign) {
+ fn.assign = function(scope, value, locals) {
+ return assign(scope, locals, value);
+ };
+ }
+ if (inputs) {
+ fn.inputs = inputs;
+ }
+ fn.literal = isLiteral(ast);
+ fn.constant = isConstant(ast);
+ return fn;
+ },
+
+ recurse: function(ast, context, create) {
+ var left, right, self = this, args, expression;
+ if (ast.input) {
+ return this.inputs(ast.input, ast.watchId);
+ }
+ switch (ast.type) {
+ case AST.Literal:
+ return this.value(ast.value, context);
+ case AST.UnaryExpression:
+ right = this.recurse(ast.argument);
+ return this['unary' + ast.operator](right, context);
+ case AST.BinaryExpression:
+ left = this.recurse(ast.left);
+ right = this.recurse(ast.right);
+ return this['binary' + ast.operator](left, right, context);
+ case AST.LogicalExpression:
+ left = this.recurse(ast.left);
+ right = this.recurse(ast.right);
+ return this['binary' + ast.operator](left, right, context);
+ case AST.ConditionalExpression:
+ return this['ternary?:'](
+ this.recurse(ast.test),
+ this.recurse(ast.alternate),
+ this.recurse(ast.consequent),
+ context
+ );
+ case AST.Identifier:
+ ensureSafeMemberName(ast.name, self.expression);
+ return self.identifier(ast.name,
+ self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
+ context, create, self.expression);
+ case AST.MemberExpression:
+ left = this.recurse(ast.object, false, !!create);
+ if (!ast.computed) {
+ ensureSafeMemberName(ast.property.name, self.expression);
+ right = ast.property.name;
+ }
+ if (ast.computed) right = this.recurse(ast.property);
+ return ast.computed ?
+ this.computedMember(left, right, context, create, self.expression) :
+ this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
+ case AST.CallExpression:
+ args = [];
+ forEach(ast.arguments, function(expr) {
+ args.push(self.recurse(expr));
+ });
+ if (ast.filter) right = this.$filter(ast.callee.name);
+ if (!ast.filter) right = this.recurse(ast.callee, true);
+ return ast.filter ?
+ function(scope, locals, assign, inputs) {
+ var values = [];
+ for (var i = 0; i < args.length; ++i) {
+ values.push(args[i](scope, locals, assign, inputs));
+ }
+ var value = right.apply(undefined, values, inputs);
+ return context ? {context: undefined, name: undefined, value: value} : value;
+ } :
+ function(scope, locals, assign, inputs) {
+ var rhs = right(scope, locals, assign, inputs);
+ var value;
+ if (rhs.value != null) {
+ ensureSafeObject(rhs.context, self.expression);
+ ensureSafeFunction(rhs.value, self.expression);
+ var values = [];
+ for (var i = 0; i < args.length; ++i) {
+ values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
+ }
+ value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
+ }
+ return context ? {value: value} : value;
+ };
+ case AST.AssignmentExpression:
+ left = this.recurse(ast.left, true, 1);
+ right = this.recurse(ast.right);
+ return function(scope, locals, assign, inputs) {
+ var lhs = left(scope, locals, assign, inputs);
+ var rhs = right(scope, locals, assign, inputs);
+ ensureSafeObject(lhs.value, self.expression);
+ ensureSafeAssignContext(lhs.context);
+ lhs.context[lhs.name] = rhs;
+ return context ? {value: rhs} : rhs;
+ };
+ case AST.ArrayExpression:
+ args = [];
+ forEach(ast.elements, function(expr) {
+ args.push(self.recurse(expr));
+ });
+ return function(scope, locals, assign, inputs) {
+ var value = [];
+ for (var i = 0; i < args.length; ++i) {
+ value.push(args[i](scope, locals, assign, inputs));
+ }
+ return context ? {value: value} : value;
+ };
+ case AST.ObjectExpression:
+ args = [];
+ forEach(ast.properties, function(property) {
+ args.push({key: property.key.type === AST.Identifier ?
+ property.key.name :
+ ('' + property.key.value),
+ value: self.recurse(property.value)
+ });
+ });
+ return function(scope, locals, assign, inputs) {
+ var value = {};
+ for (var i = 0; i < args.length; ++i) {
+ value[args[i].key] = args[i].value(scope, locals, assign, inputs);
+ }
+ return context ? {value: value} : value;
+ };
+ case AST.ThisExpression:
+ return function(scope) {
+ return context ? {value: scope} : scope;
+ };
+ case AST.NGValueParameter:
+ return function(scope, locals, assign, inputs) {
+ return context ? {value: assign} : assign;
+ };
+ }
+ },
+
+ 'unary+': function(argument, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = argument(scope, locals, assign, inputs);
+ if (isDefined(arg)) {
+ arg = +arg;
+ } else {
+ arg = 0;
+ }
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'unary-': function(argument, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = argument(scope, locals, assign, inputs);
+ if (isDefined(arg)) {
+ arg = -arg;
+ } else {
+ arg = 0;
+ }
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'unary!': function(argument, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = !argument(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary+': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var lhs = left(scope, locals, assign, inputs);
+ var rhs = right(scope, locals, assign, inputs);
+ var arg = plusFn(lhs, rhs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary-': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var lhs = left(scope, locals, assign, inputs);
+ var rhs = right(scope, locals, assign, inputs);
+ var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary*': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary/': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary%': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary===': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary!==': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary==': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary!=': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary<': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary>': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary<=': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary>=': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary&&': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'binary||': function(left, right, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ 'ternary?:': function(test, alternate, consequent, context) {
+ return function(scope, locals, assign, inputs) {
+ var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
+ return context ? {value: arg} : arg;
+ };
+ },
+ value: function(value, context) {
+ return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
+ },
+ identifier: function(name, expensiveChecks, context, create, expression) {
+ return function(scope, locals, assign, inputs) {
+ var base = locals && (name in locals) ? locals : scope;
+ if (create && create !== 1 && base && !(base[name])) {
+ base[name] = {};
+ }
+ var value = base ? base[name] : undefined;
+ if (expensiveChecks) {
+ ensureSafeObject(value, expression);
+ }
+ if (context) {
+ return {context: base, name: name, value: value};
+ } else {
+ return value;
+ }
+ };
+ },
+ computedMember: function(left, right, context, create, expression) {
+ return function(scope, locals, assign, inputs) {
+ var lhs = left(scope, locals, assign, inputs);
+ var rhs;
+ var value;
+ if (lhs != null) {
+ rhs = right(scope, locals, assign, inputs);
+ rhs = getStringValue(rhs);
+ ensureSafeMemberName(rhs, expression);
+ if (create && create !== 1 && lhs && !(lhs[rhs])) {
+ lhs[rhs] = {};
+ }
+ value = lhs[rhs];
+ ensureSafeObject(value, expression);
+ }
+ if (context) {
+ return {context: lhs, name: rhs, value: value};
+ } else {
+ return value;
+ }
+ };
+ },
+ nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
+ return function(scope, locals, assign, inputs) {
+ var lhs = left(scope, locals, assign, inputs);
+ if (create && create !== 1 && lhs && !(lhs[right])) {
+ lhs[right] = {};
+ }
+ var value = lhs != null ? lhs[right] : undefined;
+ if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
+ ensureSafeObject(value, expression);
+ }
+ if (context) {
+ return {context: lhs, name: right, value: value};
+ } else {
+ return value;
+ }
+ };
+ },
+ inputs: function(input, watchId) {
+ return function(scope, value, locals, inputs) {
+ if (inputs) return inputs[watchId];
+ return input(scope, value, locals);
+ };
+ }
+};
+
+/**
+ * @constructor
+ */
+var Parser = function(lexer, $filter, options) {
+ this.lexer = lexer;
+ this.$filter = $filter;
+ this.options = options;
+ this.ast = new AST(this.lexer);
+ this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
+ new ASTCompiler(this.ast, $filter);
+};
+
+Parser.prototype = {
+ constructor: Parser,
+
+ parse: function(text) {
+ return this.astCompiler.compile(text, this.options.expensiveChecks);
+ }
+};
+
+var getterFnCacheDefault = createMap();
+var getterFnCacheExpensive = createMap();
+
+function isPossiblyDangerousMemberName(name) {
+ return name == 'constructor';
+}
+
+var objectValueOf = Object.prototype.valueOf;
+
+function getValueOf(value) {
+ return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
+}
+
+///////////////////////////////////
+
+/**
+ * @ngdoc service
+ * @name $parse
+ * @kind function
+ *
+ * @description
+ *
+ * Converts Angular {@link guide/expression expression} into a function.
+ *
+ * ```js
+ * var getter = $parse('user.name');
+ * var setter = getter.assign;
+ * var context = {user:{name:'angular'}};
+ * var locals = {user:{name:'local'}};
+ *
+ * expect(getter(context)).toEqual('angular');
+ * setter(context, 'newValue');
+ * expect(context.user.name).toEqual('newValue');
+ * expect(getter(context, locals)).toEqual('local');
+ * ```
+ *
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ *
+ * The returned function also has the following properties:
+ * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
+ * literal.
+ * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
+ * constant literals.
+ * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
+ * set to a function to change its value on the given context.
+ *
+ */
+
+
+/**
+ * @ngdoc provider
+ * @name $parseProvider
+ *
+ * @description
+ * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
+ * service.
+ */
+function $ParseProvider() {
+ var cacheDefault = createMap();
+ var cacheExpensive = createMap();
+
+ this.$get = ['$filter', function($filter) {
+ var noUnsafeEval = csp().noUnsafeEval;
+ var $parseOptions = {
+ csp: noUnsafeEval,
+ expensiveChecks: false
+ },
+ $parseOptionsExpensive = {
+ csp: noUnsafeEval,
+ expensiveChecks: true
+ };
+
+ return function $parse(exp, interceptorFn, expensiveChecks) {
+ var parsedExpression, oneTime, cacheKey;
+
+ switch (typeof exp) {
+ case 'string':
+ exp = exp.trim();
+ cacheKey = exp;
+
+ var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
+ parsedExpression = cache[cacheKey];
+
+ if (!parsedExpression) {
+ if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
+ oneTime = true;
+ exp = exp.substring(2);
+ }
+ var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
+ var lexer = new Lexer(parseOptions);
+ var parser = new Parser(lexer, $filter, parseOptions);
+ parsedExpression = parser.parse(exp);
+ if (parsedExpression.constant) {
+ parsedExpression.$$watchDelegate = constantWatchDelegate;
+ } else if (oneTime) {
+ parsedExpression.$$watchDelegate = parsedExpression.literal ?
+ oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
+ } else if (parsedExpression.inputs) {
+ parsedExpression.$$watchDelegate = inputsWatchDelegate;
+ }
+ cache[cacheKey] = parsedExpression;
+ }
+ return addInterceptor(parsedExpression, interceptorFn);
+
+ case 'function':
+ return addInterceptor(exp, interceptorFn);
+
+ default:
+ return noop;
+ }
+ };
+
+ function expressionInputDirtyCheck(newValue, oldValueOfValue) {
+
+ if (newValue == null || oldValueOfValue == null) { // null/undefined
+ return newValue === oldValueOfValue;
+ }
+
+ if (typeof newValue === 'object') {
+
+ // attempt to convert the value to a primitive type
+ // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
+ // be cheaply dirty-checked
+ newValue = getValueOf(newValue);
+
+ if (typeof newValue === 'object') {
+ // objects/arrays are not supported - deep-watching them would be too expensive
+ return false;
+ }
+
+ // fall-through to the primitive equality check
+ }
+
+ //Primitive or NaN
+ return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
+ }
+
+ function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
+ var inputExpressions = parsedExpression.inputs;
+ var lastResult;
+
+ if (inputExpressions.length === 1) {
+ var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
+ inputExpressions = inputExpressions[0];
+ return scope.$watch(function expressionInputWatch(scope) {
+ var newInputValue = inputExpressions(scope);
+ if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
+ lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
+ oldInputValueOf = newInputValue && getValueOf(newInputValue);
+ }
+ return lastResult;
+ }, listener, objectEquality, prettyPrintExpression);
+ }
+
+ var oldInputValueOfValues = [];
+ var oldInputValues = [];
+ for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
+ oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
+ oldInputValues[i] = null;
+ }
+
+ return scope.$watch(function expressionInputsWatch(scope) {
+ var changed = false;
+
+ for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
+ var newInputValue = inputExpressions[i](scope);
+ if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
+ oldInputValues[i] = newInputValue;
+ oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
+ }
+ }
+
+ if (changed) {
+ lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
+ }
+
+ return lastResult;
+ }, listener, objectEquality, prettyPrintExpression);
+ }
+
+ function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
+ var unwatch, lastValue;
+ return unwatch = scope.$watch(function oneTimeWatch(scope) {
+ return parsedExpression(scope);
+ }, function oneTimeListener(value, old, scope) {
+ lastValue = value;
+ if (isFunction(listener)) {
+ listener.apply(this, arguments);
+ }
+ if (isDefined(value)) {
+ scope.$$postDigest(function() {
+ if (isDefined(lastValue)) {
+ unwatch();
+ }
+ });
+ }
+ }, objectEquality);
+ }
+
+ function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
+ var unwatch, lastValue;
+ return unwatch = scope.$watch(function oneTimeWatch(scope) {
+ return parsedExpression(scope);
+ }, function oneTimeListener(value, old, scope) {
+ lastValue = value;
+ if (isFunction(listener)) {
+ listener.call(this, value, old, scope);
+ }
+ if (isAllDefined(value)) {
+ scope.$$postDigest(function() {
+ if (isAllDefined(lastValue)) unwatch();
+ });
+ }
+ }, objectEquality);
+
+ function isAllDefined(value) {
+ var allDefined = true;
+ forEach(value, function(val) {
+ if (!isDefined(val)) allDefined = false;
+ });
+ return allDefined;
+ }
+ }
+
+ function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
+ var unwatch;
+ return unwatch = scope.$watch(function constantWatch(scope) {
+ return parsedExpression(scope);
+ }, function constantListener(value, old, scope) {
+ if (isFunction(listener)) {
+ listener.apply(this, arguments);
+ }
+ unwatch();
+ }, objectEquality);
+ }
+
+ function addInterceptor(parsedExpression, interceptorFn) {
+ if (!interceptorFn) return parsedExpression;
+ var watchDelegate = parsedExpression.$$watchDelegate;
+ var useInputs = false;
+
+ var regularWatch =
+ watchDelegate !== oneTimeLiteralWatchDelegate &&
+ watchDelegate !== oneTimeWatchDelegate;
+
+ var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
+ var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
+ return interceptorFn(value, scope, locals);
+ } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
+ var value = parsedExpression(scope, locals, assign, inputs);
+ var result = interceptorFn(value, scope, locals);
+ // we only return the interceptor's result if the
+ // initial value is defined (for bind-once)
+ return isDefined(value) ? result : value;
+ };
+
+ // Propagate $$watchDelegates other then inputsWatchDelegate
+ if (parsedExpression.$$watchDelegate &&
+ parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
+ fn.$$watchDelegate = parsedExpression.$$watchDelegate;
+ } else if (!interceptorFn.$stateful) {
+ // If there is an interceptor, but no watchDelegate then treat the interceptor like
+ // we treat filters - it is assumed to be a pure function unless flagged with $stateful
+ fn.$$watchDelegate = inputsWatchDelegate;
+ useInputs = !parsedExpression.inputs;
+ fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
+ }
+
+ return fn;
+ }
+ }];
+}
+
+/**
+ * @ngdoc service
+ * @name $q
+ * @requires $rootScope
+ *
+ * @description
+ * A service that helps you run functions asynchronously, and use their return values (or exceptions)
+ * when they are done processing.
+ *
+ * This is an implementation of promises/deferred objects inspired by
+ * [Kris Kowal's Q](https://github.com/kriskowal/q).
+ *
+ * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
+ * implementations, and the other which resembles ES6 promises to some degree.
+ *
+ * # $q constructor
+ *
+ * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
+ * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
+ * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
+ *
+ * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
+ * available yet.
+ *
+ * It can be used like so:
+ *
+ * ```js
+ * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
+ * // are available in the current lexical scope (they could have been injected or passed in).
+ *
+ * function asyncGreet(name) {
+ * // perform some asynchronous operation, resolve or reject the promise when appropriate.
+ * return $q(function(resolve, reject) {
+ * setTimeout(function() {
+ * if (okToGreet(name)) {
+ * resolve('Hello, ' + name + '!');
+ * } else {
+ * reject('Greeting ' + name + ' is not allowed.');
+ * }
+ * }, 1000);
+ * });
+ * }
+ *
+ * var promise = asyncGreet('Robin Hood');
+ * promise.then(function(greeting) {
+ * alert('Success: ' + greeting);
+ * }, function(reason) {
+ * alert('Failed: ' + reason);
+ * });
+ * ```
+ *
+ * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
+ *
+ * Note: unlike ES6 behaviour, an exception thrown in the constructor function will NOT implicitly reject the promise.
+ *
+ * However, the more traditional CommonJS-style usage is still available, and documented below.
+ *
+ * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
+ * interface for interacting with an object that represents the result of an action that is
+ * performed asynchronously, and may or may not be finished at any given point in time.
+ *
+ * From the perspective of dealing with error handling, deferred and promise APIs are to
+ * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
+ *
+ * ```js
+ * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
+ * // are available in the current lexical scope (they could have been injected or passed in).
+ *
+ * function asyncGreet(name) {
+ * var deferred = $q.defer();
+ *
+ * setTimeout(function() {
+ * deferred.notify('About to greet ' + name + '.');
+ *
+ * if (okToGreet(name)) {
+ * deferred.resolve('Hello, ' + name + '!');
+ * } else {
+ * deferred.reject('Greeting ' + name + ' is not allowed.');
+ * }
+ * }, 1000);
+ *
+ * return deferred.promise;
+ * }
+ *
+ * var promise = asyncGreet('Robin Hood');
+ * promise.then(function(greeting) {
+ * alert('Success: ' + greeting);
+ * }, function(reason) {
+ * alert('Failed: ' + reason);
+ * }, function(update) {
+ * alert('Got notification: ' + update);
+ * });
+ * ```
+ *
+ * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
+ * comes in the way of guarantees that promise and deferred APIs make, see
+ * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
+ *
+ * Additionally the promise api allows for composition that is very hard to do with the
+ * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
+ * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
+ * section on serial or parallel joining of promises.
+ *
+ * # The Deferred API
+ *
+ * A new instance of deferred is constructed by calling `$q.defer()`.
+ *
+ * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
+ * that can be used for signaling the successful or unsuccessful completion, as well as the status
+ * of the task.
+ *
+ * **Methods**
+ *
+ * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
+ * constructed via `$q.reject`, the promise will be rejected instead.
+ * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
+ * resolving it with a rejection constructed via `$q.reject`.
+ * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
+ * multiple times before the promise is either resolved or rejected.
+ *
+ * **Properties**
+ *
+ * - promise – `{Promise}` – promise object associated with this deferred.
+ *
+ *
+ * # The Promise API
+ *
+ * A new promise instance is created when a deferred instance is created and can be retrieved by
+ * calling `deferred.promise`.
+ *
+ * The purpose of the promise object is to allow for interested parties to get access to the result
+ * of the deferred task when it completes.
+ *
+ * **Methods**
+ *
+ * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
+ * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
+ * as soon as the result is available. The callbacks are called with a single argument: the result
+ * or rejection reason. Additionally, the notify callback may be called zero or more times to
+ * provide a progress indication, before the promise is resolved or rejected.
+ *
+ * This method *returns a new promise* which is resolved or rejected via the return value of the
+ * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
+ * with the value which is resolved in that promise using
+ * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
+ * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
+ * resolved or rejected from the notifyCallback method.
+ *
+ * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
+ *
+ * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
+ * but to do so without modifying the final value. This is useful to release resources or do some
+ * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
+ * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
+ * more information.
+ *
+ * # Chaining promises
+ *
+ * Because calling the `then` method of a promise returns a new derived promise, it is easily
+ * possible to create a chain of promises:
+ *
+ * ```js
+ * promiseB = promiseA.then(function(result) {
+ * return result + 1;
+ * });
+ *
+ * // promiseB will be resolved immediately after promiseA is resolved and its value
+ * // will be the result of promiseA incremented by 1
+ * ```
+ *
+ * It is possible to create chains of any length and since a promise can be resolved with another
+ * promise (which will defer its resolution further), it is possible to pause/defer resolution of
+ * the promises at any point in the chain. This makes it possible to implement powerful APIs like
+ * $http's response interceptors.
+ *
+ *
+ * # Differences between Kris Kowal's Q and $q
+ *
+ * There are two main differences:
+ *
+ * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
+ * mechanism in angular, which means faster propagation of resolution or rejection into your
+ * models and avoiding unnecessary browser repaints, which would result in flickering UI.
+ * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
+ * all the important functionality needed for common async tasks.
+ *
+ * # Testing
+ *
+ * ```js
+ * it('should simulate promise', inject(function($q, $rootScope) {
+ * var deferred = $q.defer();
+ * var promise = deferred.promise;
+ * var resolvedValue;
+ *
+ * promise.then(function(value) { resolvedValue = value; });
+ * expect(resolvedValue).toBeUndefined();
+ *
+ * // Simulate resolving of promise
+ * deferred.resolve(123);
+ * // Note that the 'then' function does not get called synchronously.
+ * // This is because we want the promise API to always be async, whether or not
+ * // it got called synchronously or asynchronously.
+ * expect(resolvedValue).toBeUndefined();
+ *
+ * // Propagate promise resolution to 'then' functions using $apply().
+ * $rootScope.$apply();
+ * expect(resolvedValue).toEqual(123);
+ * }));
+ * ```
+ *
+ * @param {function(function, function)} resolver Function which is responsible for resolving or
+ * rejecting the newly created promise. The first parameter is a function which resolves the
+ * promise, the second parameter is a function which rejects the promise.
+ *
+ * @returns {Promise} The newly created promise.
+ */
+function $QProvider() {
+
+ this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
+ return qFactory(function(callback) {
+ $rootScope.$evalAsync(callback);
+ }, $exceptionHandler);
+ }];
+}
+
+function $$QProvider() {
+ this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
+ return qFactory(function(callback) {
+ $browser.defer(callback);
+ }, $exceptionHandler);
+ }];
+}
+
+/**
+ * Constructs a promise manager.
+ *
+ * @param {function(function)} nextTick Function for executing functions in the next turn.
+ * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
+ * debugging purposes.
+ * @returns {object} Promise manager.
+ */
+function qFactory(nextTick, exceptionHandler) {
+ var $qMinErr = minErr('$q', TypeError);
+ function callOnce(self, resolveFn, rejectFn) {
+ var called = false;
+ function wrap(fn) {
+ return function(value) {
+ if (called) return;
+ called = true;
+ fn.call(self, value);
+ };
+ }
+
+ return [wrap(resolveFn), wrap(rejectFn)];
+ }
+
+ /**
+ * @ngdoc method
+ * @name ng.$q#defer
+ * @kind function
+ *
+ * @description
+ * Creates a `Deferred` object which represents a task which will finish in the future.
+ *
+ * @returns {Deferred} Returns a new instance of deferred.
+ */
+ var defer = function() {
+ return new Deferred();
+ };
+
+ function Promise() {
+ this.$$state = { status: 0 };
+ }
+
+ extend(Promise.prototype, {
+ then: function(onFulfilled, onRejected, progressBack) {
+ if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
+ return this;
+ }
+ var result = new Deferred();
+
+ this.$$state.pending = this.$$state.pending || [];
+ this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
+ if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
+
+ return result.promise;
+ },
+
+ "catch": function(callback) {
+ return this.then(null, callback);
+ },
+
+ "finally": function(callback, progressBack) {
+ return this.then(function(value) {
+ return handleCallback(value, true, callback);
+ }, function(error) {
+ return handleCallback(error, false, callback);
+ }, progressBack);
+ }
+ });
+
+ //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
+ function simpleBind(context, fn) {
+ return function(value) {
+ fn.call(context, value);
+ };
+ }
+
+ function processQueue(state) {
+ var fn, deferred, pending;
+
+ pending = state.pending;
+ state.processScheduled = false;
+ state.pending = undefined;
+ for (var i = 0, ii = pending.length; i < ii; ++i) {
+ deferred = pending[i][0];
+ fn = pending[i][state.status];
+ try {
+ if (isFunction(fn)) {
+ deferred.resolve(fn(state.value));
+ } else if (state.status === 1) {
+ deferred.resolve(state.value);
+ } else {
+ deferred.reject(state.value);
+ }
+ } catch (e) {
+ deferred.reject(e);
+ exceptionHandler(e);
+ }
+ }
+ }
+
+ function scheduleProcessQueue(state) {
+ if (state.processScheduled || !state.pending) return;
+ state.processScheduled = true;
+ nextTick(function() { processQueue(state); });
+ }
+
+ function Deferred() {
+ this.promise = new Promise();
+ //Necessary to support unbound execution :/
+ this.resolve = simpleBind(this, this.resolve);
+ this.reject = simpleBind(this, this.reject);
+ this.notify = simpleBind(this, this.notify);
+ }
+
+ extend(Deferred.prototype, {
+ resolve: function(val) {
+ if (this.promise.$$state.status) return;
+ if (val === this.promise) {
+ this.$$reject($qMinErr(
+ 'qcycle',
+ "Expected promise to be resolved with value other than itself '{0}'",
+ val));
+ } else {
+ this.$$resolve(val);
+ }
+
+ },
+
+ $$resolve: function(val) {
+ var then, fns;
+
+ fns = callOnce(this, this.$$resolve, this.$$reject);
+ try {
+ if ((isObject(val) || isFunction(val))) then = val && val.then;
+ if (isFunction(then)) {
+ this.promise.$$state.status = -1;
+ then.call(val, fns[0], fns[1], this.notify);
+ } else {
+ this.promise.$$state.value = val;
+ this.promise.$$state.status = 1;
+ scheduleProcessQueue(this.promise.$$state);
+ }
+ } catch (e) {
+ fns[1](e);
+ exceptionHandler(e);
+ }
+ },
+
+ reject: function(reason) {
+ if (this.promise.$$state.status) return;
+ this.$$reject(reason);
+ },
+
+ $$reject: function(reason) {
+ this.promise.$$state.value = reason;
+ this.promise.$$state.status = 2;
+ scheduleProcessQueue(this.promise.$$state);
+ },
+
+ notify: function(progress) {
+ var callbacks = this.promise.$$state.pending;
+
+ if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
+ nextTick(function() {
+ var callback, result;
+ for (var i = 0, ii = callbacks.length; i < ii; i++) {
+ result = callbacks[i][0];
+ callback = callbacks[i][3];
+ try {
+ result.notify(isFunction(callback) ? callback(progress) : progress);
+ } catch (e) {
+ exceptionHandler(e);
+ }
+ }
+ });
+ }
+ }
+ });
+
+ /**
+ * @ngdoc method
+ * @name $q#reject
+ * @kind function
+ *
+ * @description
+ * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
+ * used to forward rejection in a chain of promises. If you are dealing with the last promise in
+ * a promise chain, you don't need to worry about it.
+ *
+ * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
+ * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
+ * a promise error callback and you want to forward the error to the promise derived from the
+ * current promise, you have to "rethrow" the error by returning a rejection constructed via
+ * `reject`.
+ *
+ * ```js
+ * promiseB = promiseA.then(function(result) {
+ * // success: do something and resolve promiseB
+ * // with the old or a new result
+ * return result;
+ * }, function(reason) {
+ * // error: handle the error if possible and
+ * // resolve promiseB with newPromiseOrValue,
+ * // otherwise forward the rejection to promiseB
+ * if (canHandle(reason)) {
+ * // handle the error and recover
+ * return newPromiseOrValue;
+ * }
+ * return $q.reject(reason);
+ * });
+ * ```
+ *
+ * @param {*} reason Constant, message, exception or an object representing the rejection reason.
+ * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
+ */
+ var reject = function(reason) {
+ var result = new Deferred();
+ result.reject(reason);
+ return result.promise;
+ };
+
+ var makePromise = function makePromise(value, resolved) {
+ var result = new Deferred();
+ if (resolved) {
+ result.resolve(value);
+ } else {
+ result.reject(value);
+ }
+ return result.promise;
+ };
+
+ var handleCallback = function handleCallback(value, isResolved, callback) {
+ var callbackOutput = null;
+ try {
+ if (isFunction(callback)) callbackOutput = callback();
+ } catch (e) {
+ return makePromise(e, false);
+ }
+ if (isPromiseLike(callbackOutput)) {
+ return callbackOutput.then(function() {
+ return makePromise(value, isResolved);
+ }, function(error) {
+ return makePromise(error, false);
+ });
+ } else {
+ return makePromise(value, isResolved);
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name $q#when
+ * @kind function
+ *
+ * @description
+ * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
+ * This is useful when you are dealing with an object that might or might not be a promise, or if
+ * the promise comes from a source that can't be trusted.
+ *
+ * @param {*} value Value or a promise
+ * @param {Function=} successCallback
+ * @param {Function=} errorCallback
+ * @param {Function=} progressCallback
+ * @returns {Promise} Returns a promise of the passed value or promise
+ */
+
+
+ var when = function(value, callback, errback, progressBack) {
+ var result = new Deferred();
+ result.resolve(value);
+ return result.promise.then(callback, errback, progressBack);
+ };
+
+ /**
+ * @ngdoc method
+ * @name $q#resolve
+ * @kind function
+ *
+ * @description
+ * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
+ *
+ * @param {*} value Value or a promise
+ * @param {Function=} successCallback
+ * @param {Function=} errorCallback
+ * @param {Function=} progressCallback
+ * @returns {Promise} Returns a promise of the passed value or promise
+ */
+ var resolve = when;
+
+ /**
+ * @ngdoc method
+ * @name $q#all
+ * @kind function
+ *
+ * @description
+ * Combines multiple promises into a single promise that is resolved when all of the input
+ * promises are resolved.
+ *
+ * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
+ * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
+ * each value corresponding to the promise at the same index/key in the `promises` array/hash.
+ * If any of the promises is resolved with a rejection, this resulting promise will be rejected
+ * with the same rejection value.
+ */
+
+ function all(promises) {
+ var deferred = new Deferred(),
+ counter = 0,
+ results = isArray(promises) ? [] : {};
+
+ forEach(promises, function(promise, key) {
+ counter++;
+ when(promise).then(function(value) {
+ if (results.hasOwnProperty(key)) return;
+ results[key] = value;
+ if (!(--counter)) deferred.resolve(results);
+ }, function(reason) {
+ if (results.hasOwnProperty(key)) return;
+ deferred.reject(reason);
+ });
+ });
+
+ if (counter === 0) {
+ deferred.resolve(results);
+ }
+
+ return deferred.promise;
+ }
+
+ var $Q = function Q(resolver) {
+ if (!isFunction(resolver)) {
+ throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
+ }
+
+ if (!(this instanceof Q)) {
+ // More useful when $Q is the Promise itself.
+ return new Q(resolver);
+ }
+
+ var deferred = new Deferred();
+
+ function resolveFn(value) {
+ deferred.resolve(value);
+ }
+
+ function rejectFn(reason) {
+ deferred.reject(reason);
+ }
+
+ resolver(resolveFn, rejectFn);
+
+ return deferred.promise;
+ };
+
+ $Q.defer = defer;
+ $Q.reject = reject;
+ $Q.when = when;
+ $Q.resolve = resolve;
+ $Q.all = all;
+
+ return $Q;
+}
+
+function $$RAFProvider() { //rAF
+ this.$get = ['$window', '$timeout', function($window, $timeout) {
+ var requestAnimationFrame = $window.requestAnimationFrame ||
+ $window.webkitRequestAnimationFrame;
+
+ var cancelAnimationFrame = $window.cancelAnimationFrame ||
+ $window.webkitCancelAnimationFrame ||
+ $window.webkitCancelRequestAnimationFrame;
+
+ var rafSupported = !!requestAnimationFrame;
+ var raf = rafSupported
+ ? function(fn) {
+ var id = requestAnimationFrame(fn);
+ return function() {
+ cancelAnimationFrame(id);
+ };
+ }
+ : function(fn) {
+ var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
+ return function() {
+ $timeout.cancel(timer);
+ };
+ };
+
+ raf.supported = rafSupported;
+
+ return raf;
+ }];
+}
+
+/**
+ * DESIGN NOTES
+ *
+ * The design decisions behind the scope are heavily favored for speed and memory consumption.
+ *
+ * The typical use of scope is to watch the expressions, which most of the time return the same
+ * value as last time so we optimize the operation.
+ *
+ * Closures construction is expensive in terms of speed as well as memory:
+ * - No closures, instead use prototypical inheritance for API
+ * - Internal state needs to be stored on scope directly, which means that private state is
+ * exposed as $$____ properties
+ *
+ * Loop operations are optimized by using while(count--) { ... }
+ * - This means that in order to keep the same order of execution as addition we have to add
+ * items to the array at the beginning (unshift) instead of at the end (push)
+ *
+ * Child scopes are created and removed often
+ * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
+ *
+ * There are fewer watches than observers. This is why you don't want the observer to be implemented
+ * in the same way as watch. Watch requires return of the initialization function which is expensive
+ * to construct.
+ */
+
+
+/**
+ * @ngdoc provider
+ * @name $rootScopeProvider
+ * @description
+ *
+ * Provider for the $rootScope service.
+ */
+
+/**
+ * @ngdoc method
+ * @name $rootScopeProvider#digestTtl
+ * @description
+ *
+ * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
+ * assuming that the model is unstable.
+ *
+ * The current default is 10 iterations.
+ *
+ * In complex applications it's possible that the dependencies between `$watch`s will result in
+ * several digest iterations. However if an application needs more than the default 10 digest
+ * iterations for its model to stabilize then you should investigate what is causing the model to
+ * continuously change during the digest.
+ *
+ * Increasing the TTL could have performance implications, so you should not change it without
+ * proper justification.
+ *
+ * @param {number} limit The number of digest iterations.
+ */
+
+
+/**
+ * @ngdoc service
+ * @name $rootScope
+ * @description
+ *
+ * Every application has a single root {@link ng.$rootScope.Scope scope}.
+ * All other scopes are descendant scopes of the root scope. Scopes provide separation
+ * between the model and the view, via a mechanism for watching the model for changes.
+ * They also provide event emission/broadcast and subscription facility. See the
+ * {@link guide/scope developer guide on scopes}.
+ */
+function $RootScopeProvider() {
+ var TTL = 10;
+ var $rootScopeMinErr = minErr('$rootScope');
+ var lastDirtyWatch = null;
+ var applyAsyncId = null;
+
+ this.digestTtl = function(value) {
+ if (arguments.length) {
+ TTL = value;
+ }
+ return TTL;
+ };
+
+ function createChildScopeClass(parent) {
+ function ChildScope() {
+ this.$$watchers = this.$$nextSibling =
+ this.$$childHead = this.$$childTail = null;
+ this.$$listeners = {};
+ this.$$listenerCount = {};
+ this.$$watchersCount = 0;
+ this.$id = nextUid();
+ this.$$ChildScope = null;
+ }
+ ChildScope.prototype = parent;
+ return ChildScope;
+ }
+
+ this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
+ function($injector, $exceptionHandler, $parse, $browser) {
+
+ function destroyChildScope($event) {
+ $event.currentScope.$$destroyed = true;
+ }
+
+ function cleanUpScope($scope) {
+
+ if (msie === 9) {
+ // There is a memory leak in IE9 if all child scopes are not disconnected
+ // completely when a scope is destroyed. So this code will recurse up through
+ // all this scopes children
+ //
+ // See issue https://github.com/angular/angular.js/issues/10706
+ $scope.$$childHead && cleanUpScope($scope.$$childHead);
+ $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
+ }
+
+ // The code below works around IE9 and V8's memory leaks
+ //
+ // See:
+ // - https://code.google.com/p/v8/issues/detail?id=2073#c26
+ // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
+ // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
+
+ $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
+ $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
+ }
+
+ /**
+ * @ngdoc type
+ * @name $rootScope.Scope
+ *
+ * @description
+ * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
+ * {@link auto.$injector $injector}. Child scopes are created using the
+ * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
+ * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
+ * an in-depth introduction and usage examples.
+ *
+ *
+ * # Inheritance
+ * A scope can inherit from a parent scope, as in this example:
+ * ```js
+ var parent = $rootScope;
+ var child = parent.$new();
+
+ parent.salutation = "Hello";
+ expect(child.salutation).toEqual('Hello');
+
+ child.salutation = "Welcome";
+ expect(child.salutation).toEqual('Welcome');
+ expect(parent.salutation).toEqual('Hello');
+ * ```
+ *
+ * When interacting with `Scope` in tests, additional helper methods are available on the
+ * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
+ * details.
+ *
+ *
+ * @param {Object.<string, function()>=} providers Map of service factory which need to be
+ * provided for the current scope. Defaults to {@link ng}.
+ * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
+ * append/override services provided by `providers`. This is handy
+ * when unit-testing and having the need to override a default
+ * service.
+ * @returns {Object} Newly created scope.
+ *
+ */
+ function Scope() {
+ this.$id = nextUid();
+ this.$$phase = this.$parent = this.$$watchers =
+ this.$$nextSibling = this.$$prevSibling =
+ this.$$childHead = this.$$childTail = null;
+ this.$root = this;
+ this.$$destroyed = false;
+ this.$$listeners = {};
+ this.$$listenerCount = {};
+ this.$$watchersCount = 0;
+ this.$$isolateBindings = null;
+ }
+
+ /**
+ * @ngdoc property
+ * @name $rootScope.Scope#$id
+ *
+ * @description
+ * Unique scope ID (monotonically increasing) useful for debugging.
+ */
+
+ /**
+ * @ngdoc property
+ * @name $rootScope.Scope#$parent
+ *
+ * @description
+ * Reference to the parent scope.
+ */
+
+ /**
+ * @ngdoc property
+ * @name $rootScope.Scope#$root
+ *
+ * @description
+ * Reference to the root scope.
+ */
+
+ Scope.prototype = {
+ constructor: Scope,
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$new
+ * @kind function
+ *
+ * @description
+ * Creates a new child {@link ng.$rootScope.Scope scope}.
+ *
+ * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
+ * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
+ *
+ * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
+ * desired for the scope and its child scopes to be permanently detached from the parent and
+ * thus stop participating in model change detection and listener notification by invoking.
+ *
+ * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
+ * parent scope. The scope is isolated, as it can not see parent scope properties.
+ * When creating widgets, it is useful for the widget to not accidentally read parent
+ * state.
+ *
+ * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
+ * of the newly created scope. Defaults to `this` scope if not provided.
+ * This is used when creating a transclude scope to correctly place it
+ * in the scope hierarchy while maintaining the correct prototypical
+ * inheritance.
+ *
+ * @returns {Object} The newly created child scope.
+ *
+ */
+ $new: function(isolate, parent) {
+ var child;
+
+ parent = parent || this;
+
+ if (isolate) {
+ child = new Scope();
+ child.$root = this.$root;
+ } else {
+ // Only create a child scope class if somebody asks for one,
+ // but cache it to allow the VM to optimize lookups.
+ if (!this.$$ChildScope) {
+ this.$$ChildScope = createChildScopeClass(this);
+ }
+ child = new this.$$ChildScope();
+ }
+ child.$parent = parent;
+ child.$$prevSibling = parent.$$childTail;
+ if (parent.$$childHead) {
+ parent.$$childTail.$$nextSibling = child;
+ parent.$$childTail = child;
+ } else {
+ parent.$$childHead = parent.$$childTail = child;
+ }
+
+ // When the new scope is not isolated or we inherit from `this`, and
+ // the parent scope is destroyed, the property `$$destroyed` is inherited
+ // prototypically. In all other cases, this property needs to be set
+ // when the parent scope is destroyed.
+ // The listener needs to be added after the parent is set
+ if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
+
+ return child;
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$watch
+ * @kind function
+ *
+ * @description
+ * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
+ *
+ * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
+ * $digest()} and should return the value that will be watched. (`watchExpression` should not change
+ * its value when executed multiple times with the same input because it may be executed multiple
+ * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
+ * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
+ * - The `listener` is called only when the value from the current `watchExpression` and the
+ * previous call to `watchExpression` are not equal (with the exception of the initial run,
+ * see below). Inequality is determined according to reference inequality,
+ * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
+ * via the `!==` Javascript operator, unless `objectEquality == true`
+ * (see next point)
+ * - When `objectEquality == true`, inequality of the `watchExpression` is determined
+ * according to the {@link angular.equals} function. To save the value of the object for
+ * later comparison, the {@link angular.copy} function is used. This therefore means that
+ * watching complex objects will have adverse memory and performance implications.
+ * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
+ * This is achieved by rerunning the watchers until no changes are detected. The rerun
+ * iteration limit is 10 to prevent an infinite loop deadlock.
+ *
+ *
+ * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
+ * you can register a `watchExpression` function with no `listener`. (Be prepared for
+ * multiple calls to your `watchExpression` because it will execute multiple times in a
+ * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
+ *
+ * After a watcher is registered with the scope, the `listener` fn is called asynchronously
+ * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
+ * watcher. In rare cases, this is undesirable because the listener is called when the result
+ * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
+ * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
+ * listener was called due to initialization.
+ *
+ *
+ *
+ * # Example
+ * ```js
+ // let's assume that scope was dependency injected as the $rootScope
+ var scope = $rootScope;
+ scope.name = 'misko';
+ scope.counter = 0;
+
+ expect(scope.counter).toEqual(0);
+ scope.$watch('name', function(newValue, oldValue) {
+ scope.counter = scope.counter + 1;
+ });
+ expect(scope.counter).toEqual(0);
+
+ scope.$digest();
+ // the listener is always called during the first $digest loop after it was registered
+ expect(scope.counter).toEqual(1);
+
+ scope.$digest();
+ // but now it will not be called unless the value changes
+ expect(scope.counter).toEqual(1);
+
+ scope.name = 'adam';
+ scope.$digest();
+ expect(scope.counter).toEqual(2);
+
+
+
+ // Using a function as a watchExpression
+ var food;
+ scope.foodCounter = 0;
+ expect(scope.foodCounter).toEqual(0);
+ scope.$watch(
+ // This function returns the value being watched. It is called for each turn of the $digest loop
+ function() { return food; },
+ // This is the change listener, called when the value returned from the above function changes
+ function(newValue, oldValue) {
+ if ( newValue !== oldValue ) {
+ // Only increment the counter if the value changed
+ scope.foodCounter = scope.foodCounter + 1;
+ }
+ }
+ );
+ // No digest has been run so the counter will be zero
+ expect(scope.foodCounter).toEqual(0);
+
+ // Run the digest but since food has not changed count will still be zero
+ scope.$digest();
+ expect(scope.foodCounter).toEqual(0);
+
+ // Update food and run digest. Now the counter will increment
+ food = 'cheeseburger';
+ scope.$digest();
+ expect(scope.foodCounter).toEqual(1);
+
+ * ```
+ *
+ *
+ *
+ * @param {(function()|string)} watchExpression Expression that is evaluated on each
+ * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
+ * a call to the `listener`.
+ *
+ * - `string`: Evaluated as {@link guide/expression expression}
+ * - `function(scope)`: called with current `scope` as a parameter.
+ * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
+ * of `watchExpression` changes.
+ *
+ * - `newVal` contains the current value of the `watchExpression`
+ * - `oldVal` contains the previous value of the `watchExpression`
+ * - `scope` refers to the current scope
+ * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
+ * comparing for reference equality.
+ * @returns {function()} Returns a deregistration function for this listener.
+ */
+ $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
+ var get = $parse(watchExp);
+
+ if (get.$$watchDelegate) {
+ return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
+ }
+ var scope = this,
+ array = scope.$$watchers,
+ watcher = {
+ fn: listener,
+ last: initWatchVal,
+ get: get,
+ exp: prettyPrintExpression || watchExp,
+ eq: !!objectEquality
+ };
+
+ lastDirtyWatch = null;
+
+ if (!isFunction(listener)) {
+ watcher.fn = noop;
+ }
+
+ if (!array) {
+ array = scope.$$watchers = [];
+ }
+ // we use unshift since we use a while loop in $digest for speed.
+ // the while loop reads in reverse order.
+ array.unshift(watcher);
+ incrementWatchersCount(this, 1);
+
+ return function deregisterWatch() {
+ if (arrayRemove(array, watcher) >= 0) {
+ incrementWatchersCount(scope, -1);
+ }
+ lastDirtyWatch = null;
+ };
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$watchGroup
+ * @kind function
+ *
+ * @description
+ * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
+ * If any one expression in the collection changes the `listener` is executed.
+ *
+ * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
+ * call to $digest() to see if any items changes.
+ * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
+ *
+ * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
+ * watched using {@link ng.$rootScope.Scope#$watch $watch()}
+ *
+ * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
+ * expression in `watchExpressions` changes
+ * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
+ * those of `watchExpression`
+ * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
+ * those of `watchExpression`
+ * The `scope` refers to the current scope.
+ * @returns {function()} Returns a de-registration function for all listeners.
+ */
+ $watchGroup: function(watchExpressions, listener) {
+ var oldValues = new Array(watchExpressions.length);
+ var newValues = new Array(watchExpressions.length);
+ var deregisterFns = [];
+ var self = this;
+ var changeReactionScheduled = false;
+ var firstRun = true;
+
+ if (!watchExpressions.length) {
+ // No expressions means we call the listener ASAP
+ var shouldCall = true;
+ self.$evalAsync(function() {
+ if (shouldCall) listener(newValues, newValues, self);
+ });
+ return function deregisterWatchGroup() {
+ shouldCall = false;
+ };
+ }
+
+ if (watchExpressions.length === 1) {
+ // Special case size of one
+ return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
+ newValues[0] = value;
+ oldValues[0] = oldValue;
+ listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
+ });
+ }
+
+ forEach(watchExpressions, function(expr, i) {
+ var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
+ newValues[i] = value;
+ oldValues[i] = oldValue;
+ if (!changeReactionScheduled) {
+ changeReactionScheduled = true;
+ self.$evalAsync(watchGroupAction);
+ }
+ });
+ deregisterFns.push(unwatchFn);
+ });
+
+ function watchGroupAction() {
+ changeReactionScheduled = false;
+
+ if (firstRun) {
+ firstRun = false;
+ listener(newValues, newValues, self);
+ } else {
+ listener(newValues, oldValues, self);
+ }
+ }
+
+ return function deregisterWatchGroup() {
+ while (deregisterFns.length) {
+ deregisterFns.shift()();
+ }
+ };
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$watchCollection
+ * @kind function
+ *
+ * @description
+ * Shallow watches the properties of an object and fires whenever any of the properties change
+ * (for arrays, this implies watching the array items; for object maps, this implies watching
+ * the properties). If a change is detected, the `listener` callback is fired.
+ *
+ * - The `obj` collection is observed via standard $watch operation and is examined on every
+ * call to $digest() to see if any items have been added, removed, or moved.
+ * - The `listener` is called whenever anything within the `obj` has changed. Examples include
+ * adding, removing, and moving items belonging to an object or array.
+ *
+ *
+ * # Example
+ * ```js
+ $scope.names = ['igor', 'matias', 'misko', 'james'];
+ $scope.dataCount = 4;
+
+ $scope.$watchCollection('names', function(newNames, oldNames) {
+ $scope.dataCount = newNames.length;
+ });
+
+ expect($scope.dataCount).toEqual(4);
+ $scope.$digest();
+
+ //still at 4 ... no changes
+ expect($scope.dataCount).toEqual(4);
+
+ $scope.names.pop();
+ $scope.$digest();
+
+ //now there's been a change
+ expect($scope.dataCount).toEqual(3);
+ * ```
+ *
+ *
+ * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
+ * expression value should evaluate to an object or an array which is observed on each
+ * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
+ * collection will trigger a call to the `listener`.
+ *
+ * @param {function(newCollection, oldCollection, scope)} listener a callback function called
+ * when a change is detected.
+ * - The `newCollection` object is the newly modified data obtained from the `obj` expression
+ * - The `oldCollection` object is a copy of the former collection data.
+ * Due to performance considerations, the`oldCollection` value is computed only if the
+ * `listener` function declares two or more arguments.
+ * - The `scope` argument refers to the current scope.
+ *
+ * @returns {function()} Returns a de-registration function for this listener. When the
+ * de-registration function is executed, the internal watch operation is terminated.
+ */
+ $watchCollection: function(obj, listener) {
+ $watchCollectionInterceptor.$stateful = true;
+
+ var self = this;
+ // the current value, updated on each dirty-check run
+ var newValue;
+ // a shallow copy of the newValue from the last dirty-check run,
+ // updated to match newValue during dirty-check run
+ var oldValue;
+ // a shallow copy of the newValue from when the last change happened
+ var veryOldValue;
+ // only track veryOldValue if the listener is asking for it
+ var trackVeryOldValue = (listener.length > 1);
+ var changeDetected = 0;
+ var changeDetector = $parse(obj, $watchCollectionInterceptor);
+ var internalArray = [];
+ var internalObject = {};
+ var initRun = true;
+ var oldLength = 0;
+
+ function $watchCollectionInterceptor(_value) {
+ newValue = _value;
+ var newLength, key, bothNaN, newItem, oldItem;
+
+ // If the new value is undefined, then return undefined as the watch may be a one-time watch
+ if (isUndefined(newValue)) return;
+
+ if (!isObject(newValue)) { // if primitive
+ if (oldValue !== newValue) {
+ oldValue = newValue;
+ changeDetected++;
+ }
+ } else if (isArrayLike(newValue)) {
+ if (oldValue !== internalArray) {
+ // we are transitioning from something which was not an array into array.
+ oldValue = internalArray;
+ oldLength = oldValue.length = 0;
+ changeDetected++;
+ }
+
+ newLength = newValue.length;
+
+ if (oldLength !== newLength) {
+ // if lengths do not match we need to trigger change notification
+ changeDetected++;
+ oldValue.length = oldLength = newLength;
+ }
+ // copy the items to oldValue and look for changes.
+ for (var i = 0; i < newLength; i++) {
+ oldItem = oldValue[i];
+ newItem = newValue[i];
+
+ bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
+ if (!bothNaN && (oldItem !== newItem)) {
+ changeDetected++;
+ oldValue[i] = newItem;
+ }
+ }
+ } else {
+ if (oldValue !== internalObject) {
+ // we are transitioning from something which was not an object into object.
+ oldValue = internalObject = {};
+ oldLength = 0;
+ changeDetected++;
+ }
+ // copy the items to oldValue and look for changes.
+ newLength = 0;
+ for (key in newValue) {
+ if (hasOwnProperty.call(newValue, key)) {
+ newLength++;
+ newItem = newValue[key];
+ oldItem = oldValue[key];
+
+ if (key in oldValue) {
+ bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
+ if (!bothNaN && (oldItem !== newItem)) {
+ changeDetected++;
+ oldValue[key] = newItem;
+ }
+ } else {
+ oldLength++;
+ oldValue[key] = newItem;
+ changeDetected++;
+ }
+ }
+ }
+ if (oldLength > newLength) {
+ // we used to have more keys, need to find them and destroy them.
+ changeDetected++;
+ for (key in oldValue) {
+ if (!hasOwnProperty.call(newValue, key)) {
+ oldLength--;
+ delete oldValue[key];
+ }
+ }
+ }
+ }
+ return changeDetected;
+ }
+
+ function $watchCollectionAction() {
+ if (initRun) {
+ initRun = false;
+ listener(newValue, newValue, self);
+ } else {
+ listener(newValue, veryOldValue, self);
+ }
+
+ // make a copy for the next time a collection is changed
+ if (trackVeryOldValue) {
+ if (!isObject(newValue)) {
+ //primitive
+ veryOldValue = newValue;
+ } else if (isArrayLike(newValue)) {
+ veryOldValue = new Array(newValue.length);
+ for (var i = 0; i < newValue.length; i++) {
+ veryOldValue[i] = newValue[i];
+ }
+ } else { // if object
+ veryOldValue = {};
+ for (var key in newValue) {
+ if (hasOwnProperty.call(newValue, key)) {
+ veryOldValue[key] = newValue[key];
+ }
+ }
+ }
+ }
+ }
+
+ return this.$watch(changeDetector, $watchCollectionAction);
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$digest
+ * @kind function
+ *
+ * @description
+ * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
+ * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
+ * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
+ * until no more listeners are firing. This means that it is possible to get into an infinite
+ * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
+ * iterations exceeds 10.
+ *
+ * Usually, you don't call `$digest()` directly in
+ * {@link ng.directive:ngController controllers} or in
+ * {@link ng.$compileProvider#directive directives}.
+ * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
+ * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
+ *
+ * If you want to be notified whenever `$digest()` is called,
+ * you can register a `watchExpression` function with
+ * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
+ *
+ * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
+ *
+ * # Example
+ * ```js
+ var scope = ...;
+ scope.name = 'misko';
+ scope.counter = 0;
+
+ expect(scope.counter).toEqual(0);
+ scope.$watch('name', function(newValue, oldValue) {
+ scope.counter = scope.counter + 1;
+ });
+ expect(scope.counter).toEqual(0);
+
+ scope.$digest();
+ // the listener is always called during the first $digest loop after it was registered
+ expect(scope.counter).toEqual(1);
+
+ scope.$digest();
+ // but now it will not be called unless the value changes
+ expect(scope.counter).toEqual(1);
+
+ scope.name = 'adam';
+ scope.$digest();
+ expect(scope.counter).toEqual(2);
+ * ```
+ *
+ */
+ $digest: function() {
+ var watch, value, last,
+ watchers,
+ length,
+ dirty, ttl = TTL,
+ next, current, target = this,
+ watchLog = [],
+ logIdx, logMsg, asyncTask;
+
+ beginPhase('$digest');
+ // Check for changes to browser url that happened in sync before the call to $digest
+ $browser.$$checkUrlChange();
+
+ if (this === $rootScope && applyAsyncId !== null) {
+ // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
+ // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
+ $browser.defer.cancel(applyAsyncId);
+ flushApplyAsync();
+ }
+
+ lastDirtyWatch = null;
+
+ do { // "while dirty" loop
+ dirty = false;
+ current = target;
+
+ while (asyncQueue.length) {
+ try {
+ asyncTask = asyncQueue.shift();
+ asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ lastDirtyWatch = null;
+ }
+
+ traverseScopesLoop:
+ do { // "traverse the scopes" loop
+ if ((watchers = current.$$watchers)) {
+ // process our watches
+ length = watchers.length;
+ while (length--) {
+ try {
+ watch = watchers[length];
+ // Most common watches are on primitives, in which case we can short
+ // circuit it with === operator, only when === fails do we use .equals
+ if (watch) {
+ if ((value = watch.get(current)) !== (last = watch.last) &&
+ !(watch.eq
+ ? equals(value, last)
+ : (typeof value === 'number' && typeof last === 'number'
+ && isNaN(value) && isNaN(last)))) {
+ dirty = true;
+ lastDirtyWatch = watch;
+ watch.last = watch.eq ? copy(value, null) : value;
+ watch.fn(value, ((last === initWatchVal) ? value : last), current);
+ if (ttl < 5) {
+ logIdx = 4 - ttl;
+ if (!watchLog[logIdx]) watchLog[logIdx] = [];
+ watchLog[logIdx].push({
+ msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
+ newVal: value,
+ oldVal: last
+ });
+ }
+ } else if (watch === lastDirtyWatch) {
+ // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
+ // have already been tested.
+ dirty = false;
+ break traverseScopesLoop;
+ }
+ }
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ }
+ }
+
+ // Insanity Warning: scope depth-first traversal
+ // yes, this code is a bit crazy, but it works and we have tests to prove it!
+ // this piece should be kept in sync with the traversal in $broadcast
+ if (!(next = ((current.$$watchersCount && current.$$childHead) ||
+ (current !== target && current.$$nextSibling)))) {
+ while (current !== target && !(next = current.$$nextSibling)) {
+ current = current.$parent;
+ }
+ }
+ } while ((current = next));
+
+ // `break traverseScopesLoop;` takes us to here
+
+ if ((dirty || asyncQueue.length) && !(ttl--)) {
+ clearPhase();
+ throw $rootScopeMinErr('infdig',
+ '{0} $digest() iterations reached. Aborting!\n' +
+ 'Watchers fired in the last 5 iterations: {1}',
+ TTL, watchLog);
+ }
+
+ } while (dirty || asyncQueue.length);
+
+ clearPhase();
+
+ while (postDigestQueue.length) {
+ try {
+ postDigestQueue.shift()();
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ }
+ },
+
+
+ /**
+ * @ngdoc event
+ * @name $rootScope.Scope#$destroy
+ * @eventType broadcast on scope being destroyed
+ *
+ * @description
+ * Broadcasted when a scope and its children are being destroyed.
+ *
+ * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
+ * clean up DOM bindings before an element is removed from the DOM.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$destroy
+ * @kind function
+ *
+ * @description
+ * Removes the current scope (and all of its children) from the parent scope. Removal implies
+ * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
+ * propagate to the current scope and its children. Removal also implies that the current
+ * scope is eligible for garbage collection.
+ *
+ * The `$destroy()` is usually used by directives such as
+ * {@link ng.directive:ngRepeat ngRepeat} for managing the
+ * unrolling of the loop.
+ *
+ * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
+ * Application code can register a `$destroy` event handler that will give it a chance to
+ * perform any necessary cleanup.
+ *
+ * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
+ * clean up DOM bindings before an element is removed from the DOM.
+ */
+ $destroy: function() {
+ // We can't destroy a scope that has been already destroyed.
+ if (this.$$destroyed) return;
+ var parent = this.$parent;
+
+ this.$broadcast('$destroy');
+ this.$$destroyed = true;
+
+ if (this === $rootScope) {
+ //Remove handlers attached to window when $rootScope is removed
+ $browser.$$applicationDestroyed();
+ }
+
+ incrementWatchersCount(this, -this.$$watchersCount);
+ for (var eventName in this.$$listenerCount) {
+ decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
+ }
+
+ // sever all the references to parent scopes (after this cleanup, the current scope should
+ // not be retained by any of our references and should be eligible for garbage collection)
+ if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
+ if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
+ if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
+ if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
+
+ // Disable listeners, watchers and apply/digest methods
+ this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
+ this.$on = this.$watch = this.$watchGroup = function() { return noop; };
+ this.$$listeners = {};
+
+ // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
+ this.$$nextSibling = null;
+ cleanUpScope(this);
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$eval
+ * @kind function
+ *
+ * @description
+ * Executes the `expression` on the current scope and returns the result. Any exceptions in
+ * the expression are propagated (uncaught). This is useful when evaluating Angular
+ * expressions.
+ *
+ * # Example
+ * ```js
+ var scope = ng.$rootScope.Scope();
+ scope.a = 1;
+ scope.b = 2;
+
+ expect(scope.$eval('a+b')).toEqual(3);
+ expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
+ * ```
+ *
+ * @param {(string|function())=} expression An angular expression to be executed.
+ *
+ * - `string`: execute using the rules as defined in {@link guide/expression expression}.
+ * - `function(scope)`: execute the function with the current `scope` parameter.
+ *
+ * @param {(object)=} locals Local variables object, useful for overriding values in scope.
+ * @returns {*} The result of evaluating the expression.
+ */
+ $eval: function(expr, locals) {
+ return $parse(expr)(this, locals);
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$evalAsync
+ * @kind function
+ *
+ * @description
+ * Executes the expression on the current scope at a later point in time.
+ *
+ * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
+ * that:
+ *
+ * - it will execute after the function that scheduled the evaluation (preferably before DOM
+ * rendering).
+ * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
+ * `expression` execution.
+ *
+ * Any exceptions from the execution of the expression are forwarded to the
+ * {@link ng.$exceptionHandler $exceptionHandler} service.
+ *
+ * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
+ * will be scheduled. However, it is encouraged to always call code that changes the model
+ * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
+ *
+ * @param {(string|function())=} expression An angular expression to be executed.
+ *
+ * - `string`: execute using the rules as defined in {@link guide/expression expression}.
+ * - `function(scope)`: execute the function with the current `scope` parameter.
+ *
+ * @param {(object)=} locals Local variables object, useful for overriding values in scope.
+ */
+ $evalAsync: function(expr, locals) {
+ // if we are outside of an $digest loop and this is the first time we are scheduling async
+ // task also schedule async auto-flush
+ if (!$rootScope.$$phase && !asyncQueue.length) {
+ $browser.defer(function() {
+ if (asyncQueue.length) {
+ $rootScope.$digest();
+ }
+ });
+ }
+
+ asyncQueue.push({scope: this, expression: expr, locals: locals});
+ },
+
+ $$postDigest: function(fn) {
+ postDigestQueue.push(fn);
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$apply
+ * @kind function
+ *
+ * @description
+ * `$apply()` is used to execute an expression in angular from outside of the angular
+ * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
+ * Because we are calling into the angular framework we need to perform proper scope life
+ * cycle of {@link ng.$exceptionHandler exception handling},
+ * {@link ng.$rootScope.Scope#$digest executing watches}.
+ *
+ * ## Life cycle
+ *
+ * # Pseudo-Code of `$apply()`
+ * ```js
+ function $apply(expr) {
+ try {
+ return $eval(expr);
+ } catch (e) {
+ $exceptionHandler(e);
+ } finally {
+ $root.$digest();
+ }
+ }
+ * ```
+ *
+ *
+ * Scope's `$apply()` method transitions through the following stages:
+ *
+ * 1. The {@link guide/expression expression} is executed using the
+ * {@link ng.$rootScope.Scope#$eval $eval()} method.
+ * 2. Any exceptions from the execution of the expression are forwarded to the
+ * {@link ng.$exceptionHandler $exceptionHandler} service.
+ * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
+ * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
+ *
+ *
+ * @param {(string|function())=} exp An angular expression to be executed.
+ *
+ * - `string`: execute using the rules as defined in {@link guide/expression expression}.
+ * - `function(scope)`: execute the function with current `scope` parameter.
+ *
+ * @returns {*} The result of evaluating the expression.
+ */
+ $apply: function(expr) {
+ try {
+ beginPhase('$apply');
+ try {
+ return this.$eval(expr);
+ } finally {
+ clearPhase();
+ }
+ } catch (e) {
+ $exceptionHandler(e);
+ } finally {
+ try {
+ $rootScope.$digest();
+ } catch (e) {
+ $exceptionHandler(e);
+ throw e;
+ }
+ }
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$applyAsync
+ * @kind function
+ *
+ * @description
+ * Schedule the invocation of $apply to occur at a later time. The actual time difference
+ * varies across browsers, but is typically around ~10 milliseconds.
+ *
+ * This can be used to queue up multiple expressions which need to be evaluated in the same
+ * digest.
+ *
+ * @param {(string|function())=} exp An angular expression to be executed.
+ *
+ * - `string`: execute using the rules as defined in {@link guide/expression expression}.
+ * - `function(scope)`: execute the function with current `scope` parameter.
+ */
+ $applyAsync: function(expr) {
+ var scope = this;
+ expr && applyAsyncQueue.push($applyAsyncExpression);
+ scheduleApplyAsync();
+
+ function $applyAsyncExpression() {
+ scope.$eval(expr);
+ }
+ },
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$on
+ * @kind function
+ *
+ * @description
+ * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
+ * discussion of event life cycle.
+ *
+ * The event listener function format is: `function(event, args...)`. The `event` object
+ * passed into the listener has the following attributes:
+ *
+ * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
+ * `$broadcast`-ed.
+ * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
+ * event propagates through the scope hierarchy, this property is set to null.
+ * - `name` - `{string}`: name of the event.
+ * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
+ * further event propagation (available only for events that were `$emit`-ed).
+ * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
+ * to true.
+ * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
+ *
+ * @param {string} name Event name to listen on.
+ * @param {function(event, ...args)} listener Function to call when the event is emitted.
+ * @returns {function()} Returns a deregistration function for this listener.
+ */
+ $on: function(name, listener) {
+ var namedListeners = this.$$listeners[name];
+ if (!namedListeners) {
+ this.$$listeners[name] = namedListeners = [];
+ }
+ namedListeners.push(listener);
+
+ var current = this;
+ do {
+ if (!current.$$listenerCount[name]) {
+ current.$$listenerCount[name] = 0;
+ }
+ current.$$listenerCount[name]++;
+ } while ((current = current.$parent));
+
+ var self = this;
+ return function() {
+ var indexOfListener = namedListeners.indexOf(listener);
+ if (indexOfListener !== -1) {
+ namedListeners[indexOfListener] = null;
+ decrementListenerCount(self, 1, name);
+ }
+ };
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$emit
+ * @kind function
+ *
+ * @description
+ * Dispatches an event `name` upwards through the scope hierarchy notifying the
+ * registered {@link ng.$rootScope.Scope#$on} listeners.
+ *
+ * The event life cycle starts at the scope on which `$emit` was called. All
+ * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
+ * notified. Afterwards, the event traverses upwards toward the root scope and calls all
+ * registered listeners along the way. The event will stop propagating if one of the listeners
+ * cancels it.
+ *
+ * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
+ * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
+ *
+ * @param {string} name Event name to emit.
+ * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
+ * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
+ */
+ $emit: function(name, args) {
+ var empty = [],
+ namedListeners,
+ scope = this,
+ stopPropagation = false,
+ event = {
+ name: name,
+ targetScope: scope,
+ stopPropagation: function() {stopPropagation = true;},
+ preventDefault: function() {
+ event.defaultPrevented = true;
+ },
+ defaultPrevented: false
+ },
+ listenerArgs = concat([event], arguments, 1),
+ i, length;
+
+ do {
+ namedListeners = scope.$$listeners[name] || empty;
+ event.currentScope = scope;
+ for (i = 0, length = namedListeners.length; i < length; i++) {
+
+ // if listeners were deregistered, defragment the array
+ if (!namedListeners[i]) {
+ namedListeners.splice(i, 1);
+ i--;
+ length--;
+ continue;
+ }
+ try {
+ //allow all listeners attached to the current scope to run
+ namedListeners[i].apply(null, listenerArgs);
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ }
+ //if any listener on the current scope stops propagation, prevent bubbling
+ if (stopPropagation) {
+ event.currentScope = null;
+ return event;
+ }
+ //traverse upwards
+ scope = scope.$parent;
+ } while (scope);
+
+ event.currentScope = null;
+
+ return event;
+ },
+
+
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$broadcast
+ * @kind function
+ *
+ * @description
+ * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
+ * registered {@link ng.$rootScope.Scope#$on} listeners.
+ *
+ * The event life cycle starts at the scope on which `$broadcast` was called. All
+ * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
+ * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
+ * scope and calls all registered listeners along the way. The event cannot be canceled.
+ *
+ * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
+ * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
+ *
+ * @param {string} name Event name to broadcast.
+ * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
+ * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
+ */
+ $broadcast: function(name, args) {
+ var target = this,
+ current = target,
+ next = target,
+ event = {
+ name: name,
+ targetScope: target,
+ preventDefault: function() {
+ event.defaultPrevented = true;
+ },
+ defaultPrevented: false
+ };
+
+ if (!target.$$listenerCount[name]) return event;
+
+ var listenerArgs = concat([event], arguments, 1),
+ listeners, i, length;
+
+ //down while you can, then up and next sibling or up and next sibling until back at root
+ while ((current = next)) {
+ event.currentScope = current;
+ listeners = current.$$listeners[name] || [];
+ for (i = 0, length = listeners.length; i < length; i++) {
+ // if listeners were deregistered, defragment the array
+ if (!listeners[i]) {
+ listeners.splice(i, 1);
+ i--;
+ length--;
+ continue;
+ }
+
+ try {
+ listeners[i].apply(null, listenerArgs);
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ }
+
+ // Insanity Warning: scope depth-first traversal
+ // yes, this code is a bit crazy, but it works and we have tests to prove it!
+ // this piece should be kept in sync with the traversal in $digest
+ // (though it differs due to having the extra check for $$listenerCount)
+ if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
+ (current !== target && current.$$nextSibling)))) {
+ while (current !== target && !(next = current.$$nextSibling)) {
+ current = current.$parent;
+ }
+ }
+ }
+
+ event.currentScope = null;
+ return event;
+ }
+ };
+
+ var $rootScope = new Scope();
+
+ //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
+ var asyncQueue = $rootScope.$$asyncQueue = [];
+ var postDigestQueue = $rootScope.$$postDigestQueue = [];
+ var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
+
+ return $rootScope;
+
+
+ function beginPhase(phase) {
+ if ($rootScope.$$phase) {
+ throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
+ }
+
+ $rootScope.$$phase = phase;
+ }
+
+ function clearPhase() {
+ $rootScope.$$phase = null;
+ }
+
+ function incrementWatchersCount(current, count) {
+ do {
+ current.$$watchersCount += count;
+ } while ((current = current.$parent));
+ }
+
+ function decrementListenerCount(current, count, name) {
+ do {
+ current.$$listenerCount[name] -= count;
+
+ if (current.$$listenerCount[name] === 0) {
+ delete current.$$listenerCount[name];
+ }
+ } while ((current = current.$parent));
+ }
+
+ /**
+ * function used as an initial value for watchers.
+ * because it's unique we can easily tell it apart from other values
+ */
+ function initWatchVal() {}
+
+ function flushApplyAsync() {
+ while (applyAsyncQueue.length) {
+ try {
+ applyAsyncQueue.shift()();
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ }
+ applyAsyncId = null;
+ }
+
+ function scheduleApplyAsync() {
+ if (applyAsyncId === null) {
+ applyAsyncId = $browser.defer(function() {
+ $rootScope.$apply(flushApplyAsync);
+ });
+ }
+ }
+ }];
+}
+
+/**
+ * @description
+ * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
+ */
+function $$SanitizeUriProvider() {
+ var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
+ imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
+
+ /**
+ * @description
+ * Retrieves or overrides the default regular expression that is used for whitelisting of safe
+ * urls during a[href] sanitization.
+ *
+ * The sanitization is a security measure aimed at prevent XSS attacks via html links.
+ *
+ * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
+ * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
+ * regular expression. If a match is found, the original url is written into the dom. Otherwise,
+ * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
+ *
+ * @param {RegExp=} regexp New regexp to whitelist urls with.
+ * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
+ * chaining otherwise.
+ */
+ this.aHrefSanitizationWhitelist = function(regexp) {
+ if (isDefined(regexp)) {
+ aHrefSanitizationWhitelist = regexp;
+ return this;
+ }
+ return aHrefSanitizationWhitelist;
+ };
+
+
+ /**
+ * @description
+ * Retrieves or overrides the default regular expression that is used for whitelisting of safe
+ * urls during img[src] sanitization.
+ *
+ * The sanitization is a security measure aimed at prevent XSS attacks via html links.
+ *
+ * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
+ * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
+ * regular expression. If a match is found, the original url is written into the dom. Otherwise,
+ * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
+ *
+ * @param {RegExp=} regexp New regexp to whitelist urls with.
+ * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
+ * chaining otherwise.
+ */
+ this.imgSrcSanitizationWhitelist = function(regexp) {
+ if (isDefined(regexp)) {
+ imgSrcSanitizationWhitelist = regexp;
+ return this;
+ }
+ return imgSrcSanitizationWhitelist;
+ };
+
+ this.$get = function() {
+ return function sanitizeUri(uri, isImage) {
+ var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
+ var normalizedVal;
+ normalizedVal = urlResolve(uri).href;
+ if (normalizedVal !== '' && !normalizedVal.match(regex)) {
+ return 'unsafe:' + normalizedVal;
+ }
+ return uri;
+ };
+ };
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Any commits to this file should be reviewed with security in mind. *
+ * Changes to this file can potentially create security vulnerabilities. *
+ * An approval from 2 Core members with history of modifying *
+ * this file is required. *
+ * *
+ * Does the change somehow allow for arbitrary javascript to be executed? *
+ * Or allows for someone to change the prototype of built-in objects? *
+ * Or gives undesired access to variables likes document or window? *
+ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+var $sceMinErr = minErr('$sce');
+
+var SCE_CONTEXTS = {
+ HTML: 'html',
+ CSS: 'css',
+ URL: 'url',
+ // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
+ // url. (e.g. ng-include, script src, templateUrl)
+ RESOURCE_URL: 'resourceUrl',
+ JS: 'js'
+};
+
+// Helper functions follow.
+
+function adjustMatcher(matcher) {
+ if (matcher === 'self') {
+ return matcher;
+ } else if (isString(matcher)) {
+ // Strings match exactly except for 2 wildcards - '*' and '**'.
+ // '*' matches any character except those from the set ':/.?&'.
+ // '**' matches any character (like .* in a RegExp).
+ // More than 2 *'s raises an error as it's ill defined.
+ if (matcher.indexOf('***') > -1) {
+ throw $sceMinErr('iwcard',
+ 'Illegal sequence *** in string matcher. String: {0}', matcher);
+ }
+ matcher = escapeForRegexp(matcher).
+ replace('\\*\\*', '.*').
+ replace('\\*', '[^:/.?&;]*');
+ return new RegExp('^' + matcher + '$');
+ } else if (isRegExp(matcher)) {
+ // The only other type of matcher allowed is a Regexp.
+ // Match entire URL / disallow partial matches.
+ // Flags are reset (i.e. no global, ignoreCase or multiline)
+ return new RegExp('^' + matcher.source + '$');
+ } else {
+ throw $sceMinErr('imatcher',
+ 'Matchers may only be "self", string patterns or RegExp objects');
+ }
+}
+
+
+function adjustMatchers(matchers) {
+ var adjustedMatchers = [];
+ if (isDefined(matchers)) {
+ forEach(matchers, function(matcher) {
+ adjustedMatchers.push(adjustMatcher(matcher));
+ });
+ }
+ return adjustedMatchers;
+}
+
+
+/**
+ * @ngdoc service
+ * @name $sceDelegate
+ * @kind function
+ *
+ * @description
+ *
+ * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
+ * Contextual Escaping (SCE)} services to AngularJS.
+ *
+ * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
+ * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
+ * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
+ * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
+ * work because `$sce` delegates to `$sceDelegate` for these operations.
+ *
+ * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
+ *
+ * The default instance of `$sceDelegate` should work out of the box with little pain. While you
+ * can override it completely to change the behavior of `$sce`, the common case would
+ * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
+ * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
+ * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
+ * $sceDelegateProvider.resourceUrlWhitelist} and {@link
+ * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
+ */
+
+/**
+ * @ngdoc provider
+ * @name $sceDelegateProvider
+ * @description
+ *
+ * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
+ * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
+ * that the URLs used for sourcing Angular templates are safe. Refer {@link
+ * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
+ * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
+ *
+ * For the general details about this service in Angular, read the main page for {@link ng.$sce
+ * Strict Contextual Escaping (SCE)}.
+ *
+ * **Example**: Consider the following case. <a name="example"></a>
+ *
+ * - your app is hosted at url `http://myapp.example.com/`
+ * - but some of your templates are hosted on other domains you control such as
+ * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
+ * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
+ *
+ * Here is what a secure configuration for this scenario might look like:
+ *
+ * ```
+ * angular.module('myApp', []).config(function($sceDelegateProvider) {
+ * $sceDelegateProvider.resourceUrlWhitelist([
+ * // Allow same origin resource loads.
+ * 'self',
+ * // Allow loading from our assets domain. Notice the difference between * and **.
+ * 'http://srv*.assets.example.com/**'
+ * ]);
+ *
+ * // The blacklist overrides the whitelist so the open redirect here is blocked.
+ * $sceDelegateProvider.resourceUrlBlacklist([
+ * 'http://myapp.example.com/clickThru**'
+ * ]);
+ * });
+ * ```
+ */
+
+function $SceDelegateProvider() {
+ this.SCE_CONTEXTS = SCE_CONTEXTS;
+
+ // Resource URLs can also be trusted by policy.
+ var resourceUrlWhitelist = ['self'],
+ resourceUrlBlacklist = [];
+
+ /**
+ * @ngdoc method
+ * @name $sceDelegateProvider#resourceUrlWhitelist
+ * @kind function
+ *
+ * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
+ * provided. This must be an array or null. A snapshot of this array is used so further
+ * changes to the array are ignored.
+ *
+ * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
+ * allowed in this array.
+ *
+ * Note: **an empty whitelist array will block all URLs**!
+ *
+ * @return {Array} the currently set whitelist array.
+ *
+ * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
+ * same origin resource requests.
+ *
+ * @description
+ * Sets/Gets the whitelist of trusted resource URLs.
+ */
+ this.resourceUrlWhitelist = function(value) {
+ if (arguments.length) {
+ resourceUrlWhitelist = adjustMatchers(value);
+ }
+ return resourceUrlWhitelist;
+ };
+
+ /**
+ * @ngdoc method
+ * @name $sceDelegateProvider#resourceUrlBlacklist
+ * @kind function
+ *
+ * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
+ * provided. This must be an array or null. A snapshot of this array is used so further
+ * changes to the array are ignored.
+ *
+ * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
+ * allowed in this array.
+ *
+ * The typical usage for the blacklist is to **block
+ * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
+ * these would otherwise be trusted but actually return content from the redirected domain.
+ *
+ * Finally, **the blacklist overrides the whitelist** and has the final say.
+ *
+ * @return {Array} the currently set blacklist array.
+ *
+ * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
+ * is no blacklist.)
+ *
+ * @description
+ * Sets/Gets the blacklist of trusted resource URLs.
+ */
+
+ this.resourceUrlBlacklist = function(value) {
+ if (arguments.length) {
+ resourceUrlBlacklist = adjustMatchers(value);
+ }
+ return resourceUrlBlacklist;
+ };
+
+ this.$get = ['$injector', function($injector) {
+
+ var htmlSanitizer = function htmlSanitizer(html) {
+ throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
+ };
+
+ if ($injector.has('$sanitize')) {
+ htmlSanitizer = $injector.get('$sanitize');
+ }
+
+
+ function matchUrl(matcher, parsedUrl) {
+ if (matcher === 'self') {
+ return urlIsSameOrigin(parsedUrl);
+ } else {
+ // definitely a regex. See adjustMatchers()
+ return !!matcher.exec(parsedUrl.href);
+ }
+ }
+
+ function isResourceUrlAllowedByPolicy(url) {
+ var parsedUrl = urlResolve(url.toString());
+ var i, n, allowed = false;
+ // Ensure that at least one item from the whitelist allows this url.
+ for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
+ if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
+ allowed = true;
+ break;
+ }
+ }
+ if (allowed) {
+ // Ensure that no item from the blacklist blocked this url.
+ for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
+ if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
+ allowed = false;
+ break;
+ }
+ }
+ }
+ return allowed;
+ }
+
+ function generateHolderType(Base) {
+ var holderType = function TrustedValueHolderType(trustedValue) {
+ this.$$unwrapTrustedValue = function() {
+ return trustedValue;
+ };
+ };
+ if (Base) {
+ holderType.prototype = new Base();
+ }
+ holderType.prototype.valueOf = function sceValueOf() {
+ return this.$$unwrapTrustedValue();
+ };
+ holderType.prototype.toString = function sceToString() {
+ return this.$$unwrapTrustedValue().toString();
+ };
+ return holderType;
+ }
+
+ var trustedValueHolderBase = generateHolderType(),
+ byType = {};
+
+ byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
+ byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
+ byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
+ byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
+ byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
+
+ /**
+ * @ngdoc method
+ * @name $sceDelegate#trustAs
+ *
+ * @description
+ * Returns an object that is trusted by angular for use in specified strict
+ * contextual escaping contexts (such as ng-bind-html, ng-include, any src
+ * attribute interpolation, any dom event binding attribute interpolation
+ * such as for onclick, etc.) that uses the provided value.
+ * See {@link ng.$sce $sce} for enabling strict contextual escaping.
+ *
+ * @param {string} type The kind of context in which this value is safe for use. e.g. url,
+ * resourceUrl, html, js and css.
+ * @param {*} value The value that that should be considered trusted/safe.
+ * @returns {*} A value that can be used to stand in for the provided `value` in places
+ * where Angular expects a $sce.trustAs() return value.
+ */
+ function trustAs(type, trustedValue) {
+ var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
+ if (!Constructor) {
+ throw $sceMinErr('icontext',
+ 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
+ type, trustedValue);
+ }
+ if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
+ return trustedValue;
+ }
+ // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
+ // mutable objects, we ensure here that the value passed in is actually a string.
+ if (typeof trustedValue !== 'string') {
+ throw $sceMinErr('itype',
+ 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
+ type);
+ }
+ return new Constructor(trustedValue);
+ }
+
+ /**
+ * @ngdoc method
+ * @name $sceDelegate#valueOf
+ *
+ * @description
+ * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
+ * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
+ * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
+ *
+ * If the passed parameter is not a value that had been returned by {@link
+ * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
+ *
+ * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
+ * call or anything else.
+ * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
+ * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
+ * `value` unchanged.
+ */
+ function valueOf(maybeTrusted) {
+ if (maybeTrusted instanceof trustedValueHolderBase) {
+ return maybeTrusted.$$unwrapTrustedValue();
+ } else {
+ return maybeTrusted;
+ }
+ }
+
+ /**
+ * @ngdoc method
+ * @name $sceDelegate#getTrusted
+ *
+ * @description
+ * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
+ * returns the originally supplied value if the queried context type is a supertype of the
+ * created type. If this condition isn't satisfied, throws an exception.
+ *
+ * @param {string} type The kind of context in which this value is to be used.
+ * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
+ * `$sceDelegate.trustAs`} call.
+ * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
+ * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
+ */
+ function getTrusted(type, maybeTrusted) {
+ if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
+ return maybeTrusted;
+ }
+ var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
+ if (constructor && maybeTrusted instanceof constructor) {
+ return maybeTrusted.$$unwrapTrustedValue();
+ }
+ // If we get here, then we may only take one of two actions.
+ // 1. sanitize the value for the requested type, or
+ // 2. throw an exception.
+ if (type === SCE_CONTEXTS.RESOURCE_URL) {
+ if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
+ return maybeTrusted;
+ } else {
+ throw $sceMinErr('insecurl',
+ 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
+ maybeTrusted.toString());
+ }
+ } else if (type === SCE_CONTEXTS.HTML) {
+ return htmlSanitizer(maybeTrusted);
+ }
+ throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
+ }
+
+ return { trustAs: trustAs,
+ getTrusted: getTrusted,
+ valueOf: valueOf };
+ }];
+}
+
+
+/**
+ * @ngdoc provider
+ * @name $sceProvider
+ * @description
+ *
+ * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
+ * - enable/disable Strict Contextual Escaping (SCE) in a module
+ * - override the default implementation with a custom delegate
+ *
+ * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
+ */
+
+/* jshint maxlen: false*/
+
+/**
+ * @ngdoc service
+ * @name $sce
+ * @kind function
+ *
+ * @description
+ *
+ * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
+ *
+ * # Strict Contextual Escaping
+ *
+ * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
+ * contexts to result in a value that is marked as safe to use for that context. One example of
+ * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
+ * to these contexts as privileged or SCE contexts.
+ *
+ * As of version 1.2, Angular ships with SCE enabled by default.
+ *
+ * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
+ * one to execute arbitrary javascript by the use of the expression() syntax. Refer
+ * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
+ * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
+ * to the top of your HTML document.
+ *
+ * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
+ * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
+ *
+ * Here's an example of a binding in a privileged context:
+ *
+ * ```
+ * <input ng-model="userHtml" aria-label="User input">
+ * <div ng-bind-html="userHtml"></div>
+ * ```
+ *
+ * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
+ * disabled, this application allows the user to render arbitrary HTML into the DIV.
+ * In a more realistic example, one may be rendering user comments, blog articles, etc. via
+ * bindings. (HTML is just one example of a context where rendering user controlled input creates
+ * security vulnerabilities.)
+ *
+ * For the case of HTML, you might use a library, either on the client side, or on the server side,
+ * to sanitize unsafe HTML before binding to the value and rendering it in the document.
+ *
+ * How would you ensure that every place that used these types of bindings was bound to a value that
+ * was sanitized by your library (or returned as safe for rendering by your server?) How can you
+ * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
+ * properties/fields and forgot to update the binding to the sanitized value?
+ *
+ * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
+ * determine that something explicitly says it's safe to use a value for binding in that
+ * context. You can then audit your code (a simple grep would do) to ensure that this is only done
+ * for those values that you can easily tell are safe - because they were received from your server,
+ * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
+ * allowing only the files in a specific directory to do this. Ensuring that the internal API
+ * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
+ *
+ * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
+ * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
+ * obtain values that will be accepted by SCE / privileged contexts.
+ *
+ *
+ * ## How does it work?
+ *
+ * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
+ * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
+ * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
+ * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
+ *
+ * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
+ * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
+ * simplified):
+ *
+ * ```
+ * var ngBindHtmlDirective = ['$sce', function($sce) {
+ * return function(scope, element, attr) {
+ * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
+ * element.html(value || '');
+ * });
+ * };
+ * }];
+ * ```
+ *
+ * ## Impact on loading templates
+ *
+ * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
+ * `templateUrl`'s specified by {@link guide/directive directives}.
+ *
+ * By default, Angular only loads templates from the same domain and protocol as the application
+ * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
+ * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
+ * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
+ * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
+ *
+ * *Please note*:
+ * The browser's
+ * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
+ * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
+ * policy apply in addition to this and may further restrict whether the template is successfully
+ * loaded. This means that without the right CORS policy, loading templates from a different domain
+ * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
+ * browsers.
+ *
+ * ## This feels like too much overhead
+ *
+ * It's important to remember that SCE only applies to interpolation expressions.
+ *
+ * If your expressions are constant literals, they're automatically trusted and you don't need to
+ * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
+ * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
+ *
+ * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
+ * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
+ *
+ * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
+ * templates in `ng-include` from your application's domain without having to even know about SCE.
+ * It blocks loading templates from other domains or loading templates over http from an https
+ * served document. You can change these by setting your own custom {@link
+ * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
+ * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
+ *
+ * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
+ * application that's secure and can be audited to verify that with much more ease than bolting
+ * security onto an application later.
+ *
+ * <a name="contexts"></a>
+ * ## What trusted context types are supported?
+ *
+ * | Context | Notes |
+ * |---------------------|----------------|
+ * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
+ * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
+ * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
+ * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
+ * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
+ *
+ * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
+ *
+ * Each element in these arrays must be one of the following:
+ *
+ * - **'self'**
+ * - The special **string**, `'self'`, can be used to match against all URLs of the **same
+ * domain** as the application document using the **same protocol**.
+ * - **String** (except the special value `'self'`)
+ * - The string is matched against the full *normalized / absolute URL* of the resource
+ * being tested (substring matches are not good enough.)
+ * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
+ * match themselves.
+ * - `*`: matches zero or more occurrences of any character other than one of the following 6
+ * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
+ * in a whitelist.
+ * - `**`: matches zero or more occurrences of *any* character. As such, it's not
+ * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
+ * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
+ * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
+ * http://foo.example.com/templates/**).
+ * - **RegExp** (*see caveat below*)
+ * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
+ * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
+ * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
+ * have good test coverage). For instance, the use of `.` in the regex is correct only in a
+ * small number of cases. A `.` character in the regex used when matching the scheme or a
+ * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
+ * is highly recommended to use the string patterns and only fall back to regular expressions
+ * as a last resort.
+ * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
+ * matched against the **entire** *normalized / absolute URL* of the resource being tested
+ * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
+ * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
+ * - If you are generating your JavaScript from some other templating engine (not
+ * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
+ * remember to escape your regular expression (and be aware that you might need more than
+ * one level of escaping depending on your templating engine and the way you interpolated
+ * the value.) Do make use of your platform's escaping mechanism as it might be good
+ * enough before coding your own. E.g. Ruby has
+ * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
+ * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
+ * Javascript lacks a similar built in function for escaping. Take a look at Google
+ * Closure library's [goog.string.regExpEscape(s)](
+ * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
+ *
+ * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
+ *
+ * ## Show me an example using SCE.
+ *
+ * <example module="mySceApp" deps="angular-sanitize.js">
+ * <file name="index.html">
+ * <div ng-controller="AppController as myCtrl">
+ * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
+ * <b>User comments</b><br>
+ * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
+ * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
+ * exploit.
+ * <div class="well">
+ * <div ng-repeat="userComment in myCtrl.userComments">
+ * <b>{{userComment.name}}</b>:
+ * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
+ * <br>
+ * </div>
+ * </div>
+ * </div>
+ * </file>
+ *
+ * <file name="script.js">
+ * angular.module('mySceApp', ['ngSanitize'])
+ * .controller('AppController', ['$http', '$templateCache', '$sce',
+ * function($http, $templateCache, $sce) {
+ * var self = this;
+ * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
+ * self.userComments = userComments;
+ * });
+ * self.explicitlyTrustedHtml = $sce.trustAsHtml(
+ * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
+ * 'sanitization."">Hover over this text.</span>');
+ * }]);
+ * </file>
+ *
+ * <file name="test_data.json">
+ * [
+ * { "name": "Alice",
+ * "htmlComment":
+ * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
+ * },
+ * { "name": "Bob",
+ * "htmlComment": "<i>Yes!</i> Am I the only other one?"
+ * }
+ * ]
+ * </file>
+ *
+ * <file name="protractor.js" type="protractor">
+ * describe('SCE doc demo', function() {
+ * it('should sanitize untrusted values', function() {
+ * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
+ * .toBe('<span>Is <i>anyone</i> reading this?</span>');
+ * });
+ *
+ * it('should NOT sanitize explicitly trusted values', function() {
+ * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
+ * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
+ * 'sanitization."">Hover over this text.</span>');
+ * });
+ * });
+ * </file>
+ * </example>
+ *
+ *
+ *
+ * ## Can I disable SCE completely?
+ *
+ * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
+ * for little coding overhead. It will be much harder to take an SCE disabled application and
+ * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
+ * for cases where you have a lot of existing code that was written before SCE was introduced and
+ * you're migrating them a module at a time.
+ *
+ * That said, here's how you can completely disable SCE:
+ *
+ * ```
+ * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
+ * // Completely disable SCE. For demonstration purposes only!
+ * // Do not use in new projects.
+ * $sceProvider.enabled(false);
+ * });
+ * ```
+ *
+ */
+/* jshint maxlen: 100 */
+
+function $SceProvider() {
+ var enabled = true;
+
+ /**
+ * @ngdoc method
+ * @name $sceProvider#enabled
+ * @kind function
+ *
+ * @param {boolean=} value If provided, then enables/disables SCE.
+ * @return {boolean} true if SCE is enabled, false otherwise.
+ *
+ * @description
+ * Enables/disables SCE and returns the current value.
+ */
+ this.enabled = function(value) {
+ if (arguments.length) {
+ enabled = !!value;
+ }
+ return enabled;
+ };
+
+
+ /* Design notes on the default implementation for SCE.
+ *
+ * The API contract for the SCE delegate
+ * -------------------------------------
+ * The SCE delegate object must provide the following 3 methods:
+ *
+ * - trustAs(contextEnum, value)
+ * This method is used to tell the SCE service that the provided value is OK to use in the
+ * contexts specified by contextEnum. It must return an object that will be accepted by
+ * getTrusted() for a compatible contextEnum and return this value.
+ *
+ * - valueOf(value)
+ * For values that were not produced by trustAs(), return them as is. For values that were
+ * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
+ * trustAs is wrapping the given values into some type, this operation unwraps it when given
+ * such a value.
+ *
+ * - getTrusted(contextEnum, value)
+ * This function should return the a value that is safe to use in the context specified by
+ * contextEnum or throw and exception otherwise.
+ *
+ * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
+ * opaque or wrapped in some holder object. That happens to be an implementation detail. For
+ * instance, an implementation could maintain a registry of all trusted objects by context. In
+ * such a case, trustAs() would return the same object that was passed in. getTrusted() would
+ * return the same object passed in if it was found in the registry under a compatible context or
+ * throw an exception otherwise. An implementation might only wrap values some of the time based
+ * on some criteria. getTrusted() might return a value and not throw an exception for special
+ * constants or objects even if not wrapped. All such implementations fulfill this contract.
+ *
+ *
+ * A note on the inheritance model for SCE contexts
+ * ------------------------------------------------
+ * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
+ * is purely an implementation details.
+ *
+ * The contract is simply this:
+ *
+ * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
+ * will also succeed.
+ *
+ * Inheritance happens to capture this in a natural way. In some future, we
+ * may not use inheritance anymore. That is OK because no code outside of
+ * sce.js and sceSpecs.js would need to be aware of this detail.
+ */
+
+ this.$get = ['$parse', '$sceDelegate', function(
+ $parse, $sceDelegate) {
+ // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
+ // the "expression(javascript expression)" syntax which is insecure.
+ if (enabled && msie < 8) {
+ throw $sceMinErr('iequirks',
+ 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
+ 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
+ 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
+ }
+
+ var sce = shallowCopy(SCE_CONTEXTS);
+
+ /**
+ * @ngdoc method
+ * @name $sce#isEnabled
+ * @kind function
+ *
+ * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
+ * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
+ *
+ * @description
+ * Returns a boolean indicating if SCE is enabled.
+ */
+ sce.isEnabled = function() {
+ return enabled;
+ };
+ sce.trustAs = $sceDelegate.trustAs;
+ sce.getTrusted = $sceDelegate.getTrusted;
+ sce.valueOf = $sceDelegate.valueOf;
+
+ if (!enabled) {
+ sce.trustAs = sce.getTrusted = function(type, value) { return value; };
+ sce.valueOf = identity;
+ }
+
+ /**
+ * @ngdoc method
+ * @name $sce#parseAs
+ *
+ * @description
+ * Converts Angular {@link guide/expression expression} into a function. This is like {@link
+ * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
+ * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
+ * *result*)}
+ *
+ * @param {string} type The kind of SCE context in which this result will be used.
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ */
+ sce.parseAs = function sceParseAs(type, expr) {
+ var parsed = $parse(expr);
+ if (parsed.literal && parsed.constant) {
+ return parsed;
+ } else {
+ return $parse(expr, function(value) {
+ return sce.getTrusted(type, value);
+ });
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name $sce#trustAs
+ *
+ * @description
+ * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
+ * returns an object that is trusted by angular for use in specified strict contextual
+ * escaping contexts (such as ng-bind-html, ng-include, any src attribute
+ * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
+ * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
+ * escaping.
+ *
+ * @param {string} type The kind of context in which this value is safe for use. e.g. url,
+ * resourceUrl, html, js and css.
+ * @param {*} value The value that that should be considered trusted/safe.
+ * @returns {*} A value that can be used to stand in for the provided `value` in places
+ * where Angular expects a $sce.trustAs() return value.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#trustAsHtml
+ *
+ * @description
+ * Shorthand method. `$sce.trustAsHtml(value)` →
+ * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
+ *
+ * @param {*} value The value to trustAs.
+ * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
+ * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
+ * only accept expressions that are either literal constants or are the
+ * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#trustAsUrl
+ *
+ * @description
+ * Shorthand method. `$sce.trustAsUrl(value)` →
+ * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
+ *
+ * @param {*} value The value to trustAs.
+ * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
+ * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
+ * only accept expressions that are either literal constants or are the
+ * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#trustAsResourceUrl
+ *
+ * @description
+ * Shorthand method. `$sce.trustAsResourceUrl(value)` →
+ * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
+ *
+ * @param {*} value The value to trustAs.
+ * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
+ * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
+ * only accept expressions that are either literal constants or are the return
+ * value of {@link ng.$sce#trustAs $sce.trustAs}.)
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#trustAsJs
+ *
+ * @description
+ * Shorthand method. `$sce.trustAsJs(value)` →
+ * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
+ *
+ * @param {*} value The value to trustAs.
+ * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
+ * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
+ * only accept expressions that are either literal constants or are the
+ * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#getTrusted
+ *
+ * @description
+ * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
+ * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
+ * originally supplied value if the queried context type is a supertype of the created type.
+ * If this condition isn't satisfied, throws an exception.
+ *
+ * @param {string} type The kind of context in which this value is to be used.
+ * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
+ * call.
+ * @returns {*} The value the was originally provided to
+ * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
+ * Otherwise, throws an exception.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#getTrustedHtml
+ *
+ * @description
+ * Shorthand method. `$sce.getTrustedHtml(value)` →
+ * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
+ *
+ * @param {*} value The value to pass to `$sce.getTrusted`.
+ * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#getTrustedCss
+ *
+ * @description
+ * Shorthand method. `$sce.getTrustedCss(value)` →
+ * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
+ *
+ * @param {*} value The value to pass to `$sce.getTrusted`.
+ * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#getTrustedUrl
+ *
+ * @description
+ * Shorthand method. `$sce.getTrustedUrl(value)` →
+ * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
+ *
+ * @param {*} value The value to pass to `$sce.getTrusted`.
+ * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#getTrustedResourceUrl
+ *
+ * @description
+ * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
+ * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
+ *
+ * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
+ * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#getTrustedJs
+ *
+ * @description
+ * Shorthand method. `$sce.getTrustedJs(value)` →
+ * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
+ *
+ * @param {*} value The value to pass to `$sce.getTrusted`.
+ * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#parseAsHtml
+ *
+ * @description
+ * Shorthand method. `$sce.parseAsHtml(expression string)` →
+ * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#parseAsCss
+ *
+ * @description
+ * Shorthand method. `$sce.parseAsCss(value)` →
+ * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#parseAsUrl
+ *
+ * @description
+ * Shorthand method. `$sce.parseAsUrl(value)` →
+ * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#parseAsResourceUrl
+ *
+ * @description
+ * Shorthand method. `$sce.parseAsResourceUrl(value)` →
+ * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ */
+
+ /**
+ * @ngdoc method
+ * @name $sce#parseAsJs
+ *
+ * @description
+ * Shorthand method. `$sce.parseAsJs(value)` →
+ * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
+ *
+ * @param {string} expression String expression to compile.
+ * @returns {function(context, locals)} a function which represents the compiled expression:
+ *
+ * * `context` – `{object}` – an object against which any expressions embedded in the strings
+ * are evaluated against (typically a scope object).
+ * * `locals` – `{object=}` – local variables context object, useful for overriding values in
+ * `context`.
+ */
+
+ // Shorthand delegations.
+ var parse = sce.parseAs,
+ getTrusted = sce.getTrusted,
+ trustAs = sce.trustAs;
+
+ forEach(SCE_CONTEXTS, function(enumValue, name) {
+ var lName = lowercase(name);
+ sce[camelCase("parse_as_" + lName)] = function(expr) {
+ return parse(enumValue, expr);
+ };
+ sce[camelCase("get_trusted_" + lName)] = function(value) {
+ return getTrusted(enumValue, value);
+ };
+ sce[camelCase("trust_as_" + lName)] = function(value) {
+ return trustAs(enumValue, value);
+ };
+ });
+
+ return sce;
+ }];
+}
+
+/**
+ * !!! This is an undocumented "private" service !!!
+ *
+ * @name $sniffer
+ * @requires $window
+ * @requires $document
+ *
+ * @property {boolean} history Does the browser support html5 history api ?
+ * @property {boolean} transitions Does the browser support CSS transition events ?
+ * @property {boolean} animations Does the browser support CSS animation events ?
+ *
+ * @description
+ * This is very simple implementation of testing browser's features.
+ */
+function $SnifferProvider() {
+ this.$get = ['$window', '$document', function($window, $document) {
+ var eventSupport = {},
+ android =
+ toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
+ boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
+ document = $document[0] || {},
+ vendorPrefix,
+ vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
+ bodyStyle = document.body && document.body.style,
+ transitions = false,
+ animations = false,
+ match;
+
+ if (bodyStyle) {
+ for (var prop in bodyStyle) {
+ if (match = vendorRegex.exec(prop)) {
+ vendorPrefix = match[0];
+ vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
+ break;
+ }
+ }
+
+ if (!vendorPrefix) {
+ vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
+ }
+
+ transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
+ animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
+
+ if (android && (!transitions || !animations)) {
+ transitions = isString(bodyStyle.webkitTransition);
+ animations = isString(bodyStyle.webkitAnimation);
+ }
+ }
+
+
+ return {
+ // Android has history.pushState, but it does not update location correctly
+ // so let's not use the history API at all.
+ // http://code.google.com/p/android/issues/detail?id=17471
+ // https://github.com/angular/angular.js/issues/904
+
+ // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
+ // so let's not use the history API also
+ // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
+ // jshint -W018
+ history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
+ // jshint +W018
+ hasEvent: function(event) {
+ // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
+ // it. In particular the event is not fired when backspace or delete key are pressed or
+ // when cut operation is performed.
+ // IE10+ implements 'input' event but it erroneously fires under various situations,
+ // e.g. when placeholder changes, or a form is focused.
+ if (event === 'input' && msie <= 11) return false;
+
+ if (isUndefined(eventSupport[event])) {
+ var divElm = document.createElement('div');
+ eventSupport[event] = 'on' + event in divElm;
+ }
+
+ return eventSupport[event];
+ },
+ csp: csp(),
+ vendorPrefix: vendorPrefix,
+ transitions: transitions,
+ animations: animations,
+ android: android
+ };
+ }];
+}
+
+var $compileMinErr = minErr('$compile');
+
+/**
+ * @ngdoc service
+ * @name $templateRequest
+ *
+ * @description
+ * The `$templateRequest` service runs security checks then downloads the provided template using
+ * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
+ * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
+ * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
+ * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
+ * when `tpl` is of type string and `$templateCache` has the matching entry.
+ *
+ * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
+ * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
+ *
+ * @return {Promise} a promise for the HTTP response data of the given URL.
+ *
+ * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
+ */
+function $TemplateRequestProvider() {
+ this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
+ function handleRequestFn(tpl, ignoreRequestError) {
+ handleRequestFn.totalPendingRequests++;
+
+ // We consider the template cache holds only trusted templates, so
+ // there's no need to go through whitelisting again for keys that already
+ // are included in there. This also makes Angular accept any script
+ // directive, no matter its name. However, we still need to unwrap trusted
+ // types.
+ if (!isString(tpl) || !$templateCache.get(tpl)) {
+ tpl = $sce.getTrustedResourceUrl(tpl);
+ }
+
+ var transformResponse = $http.defaults && $http.defaults.transformResponse;
+
+ if (isArray(transformResponse)) {
+ transformResponse = transformResponse.filter(function(transformer) {
+ return transformer !== defaultHttpResponseTransform;
+ });
+ } else if (transformResponse === defaultHttpResponseTransform) {
+ transformResponse = null;
+ }
+
+ var httpOptions = {
+ cache: $templateCache,
+ transformResponse: transformResponse
+ };
+
+ return $http.get(tpl, httpOptions)
+ ['finally'](function() {
+ handleRequestFn.totalPendingRequests--;
+ })
+ .then(function(response) {
+ $templateCache.put(tpl, response.data);
+ return response.data;
+ }, handleError);
+
+ function handleError(resp) {
+ if (!ignoreRequestError) {
+ throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
+ tpl, resp.status, resp.statusText);
+ }
+ return $q.reject(resp);
+ }
+ }
+
+ handleRequestFn.totalPendingRequests = 0;
+
+ return handleRequestFn;
+ }];
+}
+
+function $$TestabilityProvider() {
+ this.$get = ['$rootScope', '$browser', '$location',
+ function($rootScope, $browser, $location) {
+
+ /**
+ * @name $testability
+ *
+ * @description
+ * The private $$testability service provides a collection of methods for use when debugging
+ * or by automated test and debugging tools.
+ */
+ var testability = {};
+
+ /**
+ * @name $$testability#findBindings
+ *
+ * @description
+ * Returns an array of elements that are bound (via ng-bind or {{}})
+ * to expressions matching the input.
+ *
+ * @param {Element} element The element root to search from.
+ * @param {string} expression The binding expression to match.
+ * @param {boolean} opt_exactMatch If true, only returns exact matches
+ * for the expression. Filters and whitespace are ignored.
+ */
+ testability.findBindings = function(element, expression, opt_exactMatch) {
+ var bindings = element.getElementsByClassName('ng-binding');
+ var matches = [];
+ forEach(bindings, function(binding) {
+ var dataBinding = angular.element(binding).data('$binding');
+ if (dataBinding) {
+ forEach(dataBinding, function(bindingName) {
+ if (opt_exactMatch) {
+ var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
+ if (matcher.test(bindingName)) {
+ matches.push(binding);
+ }
+ } else {
+ if (bindingName.indexOf(expression) != -1) {
+ matches.push(binding);
+ }
+ }
+ });
+ }
+ });
+ return matches;
+ };
+
+ /**
+ * @name $$testability#findModels
+ *
+ * @description
+ * Returns an array of elements that are two-way found via ng-model to
+ * expressions matching the input.
+ *
+ * @param {Element} element The element root to search from.
+ * @param {string} expression The model expression to match.
+ * @param {boolean} opt_exactMatch If true, only returns exact matches
+ * for the expression.
+ */
+ testability.findModels = function(element, expression, opt_exactMatch) {
+ var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
+ for (var p = 0; p < prefixes.length; ++p) {
+ var attributeEquals = opt_exactMatch ? '=' : '*=';
+ var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
+ var elements = element.querySelectorAll(selector);
+ if (elements.length) {
+ return elements;
+ }
+ }
+ };
+
+ /**
+ * @name $$testability#getLocation
+ *
+ * @description
+ * Shortcut for getting the location in a browser agnostic way. Returns
+ * the path, search, and hash. (e.g. /path?a=b#hash)
+ */
+ testability.getLocation = function() {
+ return $location.url();
+ };
+
+ /**
+ * @name $$testability#setLocation
+ *
+ * @description
+ * Shortcut for navigating to a location without doing a full page reload.
+ *
+ * @param {string} url The location url (path, search and hash,
+ * e.g. /path?a=b#hash) to go to.
+ */
+ testability.setLocation = function(url) {
+ if (url !== $location.url()) {
+ $location.url(url);
+ $rootScope.$digest();
+ }
+ };
+
+ /**
+ * @name $$testability#whenStable
+ *
+ * @description
+ * Calls the callback when $timeout and $http requests are completed.
+ *
+ * @param {function} callback
+ */
+ testability.whenStable = function(callback) {
+ $browser.notifyWhenNoOutstandingRequests(callback);
+ };
+
+ return testability;
+ }];
+}
+
+function $TimeoutProvider() {
+ this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
+ function($rootScope, $browser, $q, $$q, $exceptionHandler) {
+
+ var deferreds = {};
+
+
+ /**
+ * @ngdoc service
+ * @name $timeout
+ *
+ * @description
+ * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
+ * block and delegates any exceptions to
+ * {@link ng.$exceptionHandler $exceptionHandler} service.
+ *
+ * The return value of calling `$timeout` is a promise, which will be resolved when
+ * the delay has passed and the timeout function, if provided, is executed.
+ *
+ * To cancel a timeout request, call `$timeout.cancel(promise)`.
+ *
+ * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
+ * synchronously flush the queue of deferred functions.
+ *
+ * If you only want a promise that will be resolved after some specified delay
+ * then you can call `$timeout` without the `fn` function.
+ *
+ * @param {function()=} fn A function, whose execution should be delayed.
+ * @param {number=} [delay=0] Delay in milliseconds.
+ * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
+ * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
+ * @param {...*=} Pass additional parameters to the executed function.
+ * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
+ * promise will be resolved with is the return value of the `fn` function.
+ *
+ */
+ function timeout(fn, delay, invokeApply) {
+ if (!isFunction(fn)) {
+ invokeApply = delay;
+ delay = fn;
+ fn = noop;
+ }
+
+ var args = sliceArgs(arguments, 3),
+ skipApply = (isDefined(invokeApply) && !invokeApply),
+ deferred = (skipApply ? $$q : $q).defer(),
+ promise = deferred.promise,
+ timeoutId;
+
+ timeoutId = $browser.defer(function() {
+ try {
+ deferred.resolve(fn.apply(null, args));
+ } catch (e) {
+ deferred.reject(e);
+ $exceptionHandler(e);
+ }
+ finally {
+ delete deferreds[promise.$$timeoutId];
+ }
+
+ if (!skipApply) $rootScope.$apply();
+ }, delay);
+
+ promise.$$timeoutId = timeoutId;
+ deferreds[timeoutId] = deferred;
+
+ return promise;
+ }
+
+
+ /**
+ * @ngdoc method
+ * @name $timeout#cancel
+ *
+ * @description
+ * Cancels a task associated with the `promise`. As a result of this, the promise will be
+ * resolved with a rejection.
+ *
+ * @param {Promise=} promise Promise returned by the `$timeout` function.
+ * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
+ * canceled.
+ */
+ timeout.cancel = function(promise) {
+ if (promise && promise.$$timeoutId in deferreds) {
+ deferreds[promise.$$timeoutId].reject('canceled');
+ delete deferreds[promise.$$timeoutId];
+ return $browser.defer.cancel(promise.$$timeoutId);
+ }
+ return false;
+ };
+
+ return timeout;
+ }];
+}
+
+// NOTE: The usage of window and document instead of $window and $document here is
+// deliberate. This service depends on the specific behavior of anchor nodes created by the
+// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
+// cause us to break tests. In addition, when the browser resolves a URL for XHR, it
+// doesn't know about mocked locations and resolves URLs to the real document - which is
+// exactly the behavior needed here. There is little value is mocking these out for this
+// service.
+var urlParsingNode = document.createElement("a");
+var originUrl = urlResolve(window.location.href);
+
+
+/**
+ *
+ * Implementation Notes for non-IE browsers
+ * ----------------------------------------
+ * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
+ * results both in the normalizing and parsing of the URL. Normalizing means that a relative
+ * URL will be resolved into an absolute URL in the context of the application document.
+ * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
+ * properties are all populated to reflect the normalized URL. This approach has wide
+ * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
+ * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
+ *
+ * Implementation Notes for IE
+ * ---------------------------
+ * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
+ * browsers. However, the parsed components will not be set if the URL assigned did not specify
+ * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
+ * work around that by performing the parsing in a 2nd step by taking a previously normalized
+ * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
+ * properties such as protocol, hostname, port, etc.
+ *
+ * References:
+ * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
+ * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
+ * http://url.spec.whatwg.org/#urlutils
+ * https://github.com/angular/angular.js/pull/2902
+ * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
+ *
+ * @kind function
+ * @param {string} url The URL to be parsed.
+ * @description Normalizes and parses a URL.
+ * @returns {object} Returns the normalized URL as a dictionary.
+ *
+ * | member name | Description |
+ * |---------------|----------------|
+ * | href | A normalized version of the provided URL if it was not an absolute URL |
+ * | protocol | The protocol including the trailing colon |
+ * | host | The host and port (if the port is non-default) of the normalizedUrl |
+ * | search | The search params, minus the question mark |
+ * | hash | The hash string, minus the hash symbol
+ * | hostname | The hostname
+ * | port | The port, without ":"
+ * | pathname | The pathname, beginning with "/"
+ *
+ */
+function urlResolve(url) {
+ var href = url;
+
+ if (msie) {
+ // Normalize before parse. Refer Implementation Notes on why this is
+ // done in two steps on IE.
+ urlParsingNode.setAttribute("href", href);
+ href = urlParsingNode.href;
+ }
+
+ urlParsingNode.setAttribute('href', href);
+
+ // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
+ return {
+ href: urlParsingNode.href,
+ protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
+ host: urlParsingNode.host,
+ search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
+ hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
+ hostname: urlParsingNode.hostname,
+ port: urlParsingNode.port,
+ pathname: (urlParsingNode.pathname.charAt(0) === '/')
+ ? urlParsingNode.pathname
+ : '/' + urlParsingNode.pathname
+ };
+}
+
+/**
+ * Parse a request URL and determine whether this is a same-origin request as the application document.
+ *
+ * @param {string|object} requestUrl The url of the request as a string that will be resolved
+ * or a parsed URL object.
+ * @returns {boolean} Whether the request is for the same origin as the application document.
+ */
+function urlIsSameOrigin(requestUrl) {
+ var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
+ return (parsed.protocol === originUrl.protocol &&
+ parsed.host === originUrl.host);
+}
+
+/**
+ * @ngdoc service
+ * @name $window
+ *
+ * @description
+ * A reference to the browser's `window` object. While `window`
+ * is globally available in JavaScript, it causes testability problems, because
+ * it is a global variable. In angular we always refer to it through the
+ * `$window` service, so it may be overridden, removed or mocked for testing.
+ *
+ * Expressions, like the one defined for the `ngClick` directive in the example
+ * below, are evaluated with respect to the current scope. Therefore, there is
+ * no risk of inadvertently coding in a dependency on a global value in such an
+ * expression.
+ *
+ * @example
+ <example module="windowExample">
+ <file name="index.html">
+ <script>
+ angular.module('windowExample', [])
+ .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
+ $scope.greeting = 'Hello, World!';
+ $scope.doGreeting = function(greeting) {
+ $window.alert(greeting);
+ };
+ }]);
+ </script>
+ <div ng-controller="ExampleController">
+ <input type="text" ng-model="greeting" aria-label="greeting" />
+ <button ng-click="doGreeting(greeting)">ALERT</button>
+ </div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should display the greeting in the input box', function() {
+ element(by.model('greeting')).sendKeys('Hello, E2E Tests');
+ // If we click the button it will block the test runner
+ // element(':button').click();
+ });
+ </file>
+ </example>
+ */
+function $WindowProvider() {
+ this.$get = valueFn(window);
+}
+
+/**
+ * @name $$cookieReader
+ * @requires $document
+ *
+ * @description
+ * This is a private service for reading cookies used by $http and ngCookies
+ *
+ * @return {Object} a key/value map of the current cookies
+ */
+function $$CookieReader($document) {
+ var rawDocument = $document[0] || {};
+ var lastCookies = {};
+ var lastCookieString = '';
+
+ function safeDecodeURIComponent(str) {
+ try {
+ return decodeURIComponent(str);
+ } catch (e) {
+ return str;
+ }
+ }
+
+ return function() {
+ var cookieArray, cookie, i, index, name;
+ var currentCookieString = rawDocument.cookie || '';
+
+ if (currentCookieString !== lastCookieString) {
+ lastCookieString = currentCookieString;
+ cookieArray = lastCookieString.split('; ');
+ lastCookies = {};
+
+ for (i = 0; i < cookieArray.length; i++) {
+ cookie = cookieArray[i];
+ index = cookie.indexOf('=');
+ if (index > 0) { //ignore nameless cookies
+ name = safeDecodeURIComponent(cookie.substring(0, index));
+ // the first value that is seen for a cookie is the most
+ // specific one. values for the same cookie name that
+ // follow are for less specific paths.
+ if (isUndefined(lastCookies[name])) {
+ lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
+ }
+ }
+ }
+ }
+ return lastCookies;
+ };
+}
+
+$$CookieReader.$inject = ['$document'];
+
+function $$CookieReaderProvider() {
+ this.$get = $$CookieReader;
+}
+
+/* global currencyFilter: true,
+ dateFilter: true,
+ filterFilter: true,
+ jsonFilter: true,
+ limitToFilter: true,
+ lowercaseFilter: true,
+ numberFilter: true,
+ orderByFilter: true,
+ uppercaseFilter: true,
+ */
+
+/**
+ * @ngdoc provider
+ * @name $filterProvider
+ * @description
+ *
+ * Filters are just functions which transform input to an output. However filters need to be
+ * Dependency Injected. To achieve this a filter definition consists of a factory function which is
+ * annotated with dependencies and is responsible for creating a filter function.
+ *
+ * <div class="alert alert-warning">
+ * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
+ * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
+ * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
+ * (`myapp_subsection_filterx`).
+ * </div>
+ *
+ * ```js
+ * // Filter registration
+ * function MyModule($provide, $filterProvider) {
+ * // create a service to demonstrate injection (not always needed)
+ * $provide.value('greet', function(name){
+ * return 'Hello ' + name + '!';
+ * });
+ *
+ * // register a filter factory which uses the
+ * // greet service to demonstrate DI.
+ * $filterProvider.register('greet', function(greet){
+ * // return the filter function which uses the greet service
+ * // to generate salutation
+ * return function(text) {
+ * // filters need to be forgiving so check input validity
+ * return text && greet(text) || text;
+ * };
+ * });
+ * }
+ * ```
+ *
+ * The filter function is registered with the `$injector` under the filter name suffix with
+ * `Filter`.
+ *
+ * ```js
+ * it('should be the same instance', inject(
+ * function($filterProvider) {
+ * $filterProvider.register('reverse', function(){
+ * return ...;
+ * });
+ * },
+ * function($filter, reverseFilter) {
+ * expect($filter('reverse')).toBe(reverseFilter);
+ * });
+ * ```
+ *
+ *
+ * For more information about how angular filters work, and how to create your own filters, see
+ * {@link guide/filter Filters} in the Angular Developer Guide.
+ */
+
+/**
+ * @ngdoc service
+ * @name $filter
+ * @kind function
+ * @description
+ * Filters are used for formatting data displayed to the user.
+ *
+ * The general syntax in templates is as follows:
+ *
+ * {{ expression [| filter_name[:parameter_value] ... ] }}
+ *
+ * @param {String} name Name of the filter function to retrieve
+ * @return {Function} the filter function
+ * @example
+ <example name="$filter" module="filterExample">
+ <file name="index.html">
+ <div ng-controller="MainCtrl">
+ <h3>{{ originalText }}</h3>
+ <h3>{{ filteredText }}</h3>
+ </div>
+ </file>
+
+ <file name="script.js">
+ angular.module('filterExample', [])
+ .controller('MainCtrl', function($scope, $filter) {
+ $scope.originalText = 'hello';
+ $scope.filteredText = $filter('uppercase')($scope.originalText);
+ });
+ </file>
+ </example>
+ */
+$FilterProvider.$inject = ['$provide'];
+function $FilterProvider($provide) {
+ var suffix = 'Filter';
+
+ /**
+ * @ngdoc method
+ * @name $filterProvider#register
+ * @param {string|Object} name Name of the filter function, or an object map of filters where
+ * the keys are the filter names and the values are the filter factories.
+ *
+ * <div class="alert alert-warning">
+ * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
+ * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
+ * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
+ * (`myapp_subsection_filterx`).
+ * </div>
+ * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
+ * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
+ * of the registered filter instances.
+ */
+ function register(name, factory) {
+ if (isObject(name)) {
+ var filters = {};
+ forEach(name, function(filter, key) {
+ filters[key] = register(key, filter);
+ });
+ return filters;
+ } else {
+ return $provide.factory(name + suffix, factory);
+ }
+ }
+ this.register = register;
+
+ this.$get = ['$injector', function($injector) {
+ return function(name) {
+ return $injector.get(name + suffix);
+ };
+ }];
+
+ ////////////////////////////////////////
+
+ /* global
+ currencyFilter: false,
+ dateFilter: false,
+ filterFilter: false,
+ jsonFilter: false,
+ limitToFilter: false,
+ lowercaseFilter: false,
+ numberFilter: false,
+ orderByFilter: false,
+ uppercaseFilter: false,
+ */
+
+ register('currency', currencyFilter);
+ register('date', dateFilter);
+ register('filter', filterFilter);
+ register('json', jsonFilter);
+ register('limitTo', limitToFilter);
+ register('lowercase', lowercaseFilter);
+ register('number', numberFilter);
+ register('orderBy', orderByFilter);
+ register('uppercase', uppercaseFilter);
+}
+
+/**
+ * @ngdoc filter
+ * @name filter
+ * @kind function
+ *
+ * @description
+ * Selects a subset of items from `array` and returns it as a new array.
+ *
+ * @param {Array} array The source array.
+ * @param {string|Object|function()} expression The predicate to be used for selecting items from
+ * `array`.
+ *
+ * Can be one of:
+ *
+ * - `string`: The string is used for matching against the contents of the `array`. All strings or
+ * objects with string properties in `array` that match this string will be returned. This also
+ * applies to nested object properties.
+ * The predicate can be negated by prefixing the string with `!`.
+ *
+ * - `Object`: A pattern object can be used to filter specific properties on objects contained
+ * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
+ * which have property `name` containing "M" and property `phone` containing "1". A special
+ * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
+ * property of the object or its nested object properties. That's equivalent to the simple
+ * substring match with a `string` as described above. The predicate can be negated by prefixing
+ * the string with `!`.
+ * For example `{name: "!M"}` predicate will return an array of items which have property `name`
+ * not containing "M".
+ *
+ * Note that a named property will match properties on the same level only, while the special
+ * `$` property will match properties on the same level or deeper. E.g. an array item like
+ * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
+ * **will** be matched by `{$: 'John'}`.
+ *
+ * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
+ * The function is called for each element of the array, with the element, its index, and
+ * the entire array itself as arguments.
+ *
+ * The final result is an array of those elements that the predicate returned true for.
+ *
+ * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
+ * determining if the expected value (from the filter expression) and actual value (from
+ * the object in the array) should be considered a match.
+ *
+ * Can be one of:
+ *
+ * - `function(actual, expected)`:
+ * The function will be given the object value and the predicate value to compare and
+ * should return true if both values should be considered equal.
+ *
+ * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
+ * This is essentially strict comparison of expected and actual.
+ *
+ * - `false|undefined`: A short hand for a function which will look for a substring match in case
+ * insensitive way.
+ *
+ * Primitive values are converted to strings. Objects are not compared against primitives,
+ * unless they have a custom `toString` method (e.g. `Date` objects).
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <div ng-init="friends = [{name:'John', phone:'555-1276'},
+ {name:'Mary', phone:'800-BIG-MARY'},
+ {name:'Mike', phone:'555-4321'},
+ {name:'Adam', phone:'555-5678'},
+ {name:'Julie', phone:'555-8765'},
+ {name:'Juliette', phone:'555-5678'}]"></div>
+
+ <label>Search: <input ng-model="searchText"></label>
+ <table id="searchTextResults">
+ <tr><th>Name</th><th>Phone</th></tr>
+ <tr ng-repeat="friend in friends | filter:searchText">
+ <td>{{friend.name}}</td>
+ <td>{{friend.phone}}</td>
+ </tr>
+ </table>
+ <hr>
+ <label>Any: <input ng-model="search.$"></label> <br>
+ <label>Name only <input ng-model="search.name"></label><br>
+ <label>Phone only <input ng-model="search.phone"></label><br>
+ <label>Equality <input type="checkbox" ng-model="strict"></label><br>
+ <table id="searchObjResults">
+ <tr><th>Name</th><th>Phone</th></tr>
+ <tr ng-repeat="friendObj in friends | filter:search:strict">
+ <td>{{friendObj.name}}</td>
+ <td>{{friendObj.phone}}</td>
+ </tr>
+ </table>
+ </file>
+ <file name="protractor.js" type="protractor">
+ var expectFriendNames = function(expectedNames, key) {
+ element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
+ arr.forEach(function(wd, i) {
+ expect(wd.getText()).toMatch(expectedNames[i]);
+ });
+ });
+ };
+
+ it('should search across all fields when filtering with a string', function() {
+ var searchText = element(by.model('searchText'));
+ searchText.clear();
+ searchText.sendKeys('m');
+ expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
+
+ searchText.clear();
+ searchText.sendKeys('76');
+ expectFriendNames(['John', 'Julie'], 'friend');
+ });
+
+ it('should search in specific fields when filtering with a predicate object', function() {
+ var searchAny = element(by.model('search.$'));
+ searchAny.clear();
+ searchAny.sendKeys('i');
+ expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
+ });
+ it('should use a equal comparison when comparator is true', function() {
+ var searchName = element(by.model('search.name'));
+ var strict = element(by.model('strict'));
+ searchName.clear();
+ searchName.sendKeys('Julie');
+ strict.click();
+ expectFriendNames(['Julie'], 'friendObj');
+ });
+ </file>
+ </example>
+ */
+function filterFilter() {
+ return function(array, expression, comparator) {
+ if (!isArrayLike(array)) {
+ if (array == null) {
+ return array;
+ } else {
+ throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
+ }
+ }
+
+ var expressionType = getTypeForFilter(expression);
+ var predicateFn;
+ var matchAgainstAnyProp;
+
+ switch (expressionType) {
+ case 'function':
+ predicateFn = expression;
+ break;
+ case 'boolean':
+ case 'null':
+ case 'number':
+ case 'string':
+ matchAgainstAnyProp = true;
+ //jshint -W086
+ case 'object':
+ //jshint +W086
+ predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
+ break;
+ default:
+ return array;
+ }
+
+ return Array.prototype.filter.call(array, predicateFn);
+ };
+}
+
+// Helper functions for `filterFilter`
+function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
+ var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
+ var predicateFn;
+
+ if (comparator === true) {
+ comparator = equals;
+ } else if (!isFunction(comparator)) {
+ comparator = function(actual, expected) {
+ if (isUndefined(actual)) {
+ // No substring matching against `undefined`
+ return false;
+ }
+ if ((actual === null) || (expected === null)) {
+ // No substring matching against `null`; only match against `null`
+ return actual === expected;
+ }
+ if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
+ // Should not compare primitives against objects, unless they have custom `toString` method
+ return false;
+ }
+
+ actual = lowercase('' + actual);
+ expected = lowercase('' + expected);
+ return actual.indexOf(expected) !== -1;
+ };
+ }
+
+ predicateFn = function(item) {
+ if (shouldMatchPrimitives && !isObject(item)) {
+ return deepCompare(item, expression.$, comparator, false);
+ }
+ return deepCompare(item, expression, comparator, matchAgainstAnyProp);
+ };
+
+ return predicateFn;
+}
+
+function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
+ var actualType = getTypeForFilter(actual);
+ var expectedType = getTypeForFilter(expected);
+
+ if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
+ return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
+ } else if (isArray(actual)) {
+ // In case `actual` is an array, consider it a match
+ // if ANY of it's items matches `expected`
+ return actual.some(function(item) {
+ return deepCompare(item, expected, comparator, matchAgainstAnyProp);
+ });
+ }
+
+ switch (actualType) {
+ case 'object':
+ var key;
+ if (matchAgainstAnyProp) {
+ for (key in actual) {
+ if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
+ return true;
+ }
+ }
+ return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
+ } else if (expectedType === 'object') {
+ for (key in expected) {
+ var expectedVal = expected[key];
+ if (isFunction(expectedVal) || isUndefined(expectedVal)) {
+ continue;
+ }
+
+ var matchAnyProperty = key === '$';
+ var actualVal = matchAnyProperty ? actual : actual[key];
+ if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
+ return false;
+ }
+ }
+ return true;
+ } else {
+ return comparator(actual, expected);
+ }
+ break;
+ case 'function':
+ return false;
+ default:
+ return comparator(actual, expected);
+ }
+}
+
+// Used for easily differentiating between `null` and actual `object`
+function getTypeForFilter(val) {
+ return (val === null) ? 'null' : typeof val;
+}
+
+/**
+ * @ngdoc filter
+ * @name currency
+ * @kind function
+ *
+ * @description
+ * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
+ * symbol for current locale is used.
+ *
+ * @param {number} amount Input to filter.
+ * @param {string=} symbol Currency symbol or identifier to be displayed.
+ * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
+ * @returns {string} Formatted number.
+ *
+ *
+ * @example
+ <example module="currencyExample">
+ <file name="index.html">
+ <script>
+ angular.module('currencyExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.amount = 1234.56;
+ }]);
+ </script>
+ <div ng-controller="ExampleController">
+ <input type="number" ng-model="amount" aria-label="amount"> <br>
+ default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
+ custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
+ no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
+ </div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should init with 1234.56', function() {
+ expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
+ expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
+ expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
+ });
+ it('should update', function() {
+ if (browser.params.browser == 'safari') {
+ // Safari does not understand the minus key. See
+ // https://github.com/angular/protractor/issues/481
+ return;
+ }
+ element(by.model('amount')).clear();
+ element(by.model('amount')).sendKeys('-1234');
+ expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
+ expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
+ expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
+ });
+ </file>
+ </example>
+ */
+currencyFilter.$inject = ['$locale'];
+function currencyFilter($locale) {
+ var formats = $locale.NUMBER_FORMATS;
+ return function(amount, currencySymbol, fractionSize) {
+ if (isUndefined(currencySymbol)) {
+ currencySymbol = formats.CURRENCY_SYM;
+ }
+
+ if (isUndefined(fractionSize)) {
+ fractionSize = formats.PATTERNS[1].maxFrac;
+ }
+
+ // if null or undefined pass it through
+ return (amount == null)
+ ? amount
+ : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
+ replace(/\u00A4/g, currencySymbol);
+ };
+}
+
+/**
+ * @ngdoc filter
+ * @name number
+ * @kind function
+ *
+ * @description
+ * Formats a number as text.
+ *
+ * If the input is null or undefined, it will just be returned.
+ * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
+ * If the input is not a number an empty string is returned.
+ *
+ *
+ * @param {number|string} number Number to format.
+ * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
+ * If this is not provided then the fraction size is computed from the current locale's number
+ * formatting pattern. In the case of the default locale, it will be 3.
+ * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
+ *
+ * @example
+ <example module="numberFilterExample">
+ <file name="index.html">
+ <script>
+ angular.module('numberFilterExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.val = 1234.56789;
+ }]);
+ </script>
+ <div ng-controller="ExampleController">
+ <label>Enter number: <input ng-model='val'></label><br>
+ Default formatting: <span id='number-default'>{{val | number}}</span><br>
+ No fractions: <span>{{val | number:0}}</span><br>
+ Negative number: <span>{{-val | number:4}}</span>
+ </div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should format numbers', function() {
+ expect(element(by.id('number-default')).getText()).toBe('1,234.568');
+ expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
+ expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
+ });
+
+ it('should update', function() {
+ element(by.model('val')).clear();
+ element(by.model('val')).sendKeys('3374.333');
+ expect(element(by.id('number-default')).getText()).toBe('3,374.333');
+ expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
+ expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
+ });
+ </file>
+ </example>
+ */
+
+
+numberFilter.$inject = ['$locale'];
+function numberFilter($locale) {
+ var formats = $locale.NUMBER_FORMATS;
+ return function(number, fractionSize) {
+
+ // if null or undefined pass it through
+ return (number == null)
+ ? number
+ : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
+ fractionSize);
+ };
+}
+
+var DECIMAL_SEP = '.';
+function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
+ if (isObject(number)) return '';
+
+ var isNegative = number < 0;
+ number = Math.abs(number);
+
+ var isInfinity = number === Infinity;
+ if (!isInfinity && !isFinite(number)) return '';
+
+ var numStr = number + '',
+ formatedText = '',
+ hasExponent = false,
+ parts = [];
+
+ if (isInfinity) formatedText = '\u221e';
+
+ if (!isInfinity && numStr.indexOf('e') !== -1) {
+ var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
+ if (match && match[2] == '-' && match[3] > fractionSize + 1) {
+ number = 0;
+ } else {
+ formatedText = numStr;
+ hasExponent = true;
+ }
+ }
+
+ if (!isInfinity && !hasExponent) {
+ var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
+
+ // determine fractionSize if it is not specified
+ if (isUndefined(fractionSize)) {
+ fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
+ }
+
+ // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
+ // inspired by:
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
+ number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
+
+ var fraction = ('' + number).split(DECIMAL_SEP);
+ var whole = fraction[0];
+ fraction = fraction[1] || '';
+
+ var i, pos = 0,
+ lgroup = pattern.lgSize,
+ group = pattern.gSize;
+
+ if (whole.length >= (lgroup + group)) {
+ pos = whole.length - lgroup;
+ for (i = 0; i < pos; i++) {
+ if ((pos - i) % group === 0 && i !== 0) {
+ formatedText += groupSep;
+ }
+ formatedText += whole.charAt(i);
+ }
+ }
+
+ for (i = pos; i < whole.length; i++) {
+ if ((whole.length - i) % lgroup === 0 && i !== 0) {
+ formatedText += groupSep;
+ }
+ formatedText += whole.charAt(i);
+ }
+
+ // format fraction part.
+ while (fraction.length < fractionSize) {
+ fraction += '0';
+ }
+
+ if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
+ } else {
+ if (fractionSize > 0 && number < 1) {
+ formatedText = number.toFixed(fractionSize);
+ number = parseFloat(formatedText);
+ formatedText = formatedText.replace(DECIMAL_SEP, decimalSep);
+ }
+ }
+
+ if (number === 0) {
+ isNegative = false;
+ }
+
+ parts.push(isNegative ? pattern.negPre : pattern.posPre,
+ formatedText,
+ isNegative ? pattern.negSuf : pattern.posSuf);
+ return parts.join('');
+}
+
+function padNumber(num, digits, trim) {
+ var neg = '';
+ if (num < 0) {
+ neg = '-';
+ num = -num;
+ }
+ num = '' + num;
+ while (num.length < digits) num = '0' + num;
+ if (trim) {
+ num = num.substr(num.length - digits);
+ }
+ return neg + num;
+}
+
+
+function dateGetter(name, size, offset, trim) {
+ offset = offset || 0;
+ return function(date) {
+ var value = date['get' + name]();
+ if (offset > 0 || value > -offset) {
+ value += offset;
+ }
+ if (value === 0 && offset == -12) value = 12;
+ return padNumber(value, size, trim);
+ };
+}
+
+function dateStrGetter(name, shortForm) {
+ return function(date, formats) {
+ var value = date['get' + name]();
+ var get = uppercase(shortForm ? ('SHORT' + name) : name);
+
+ return formats[get][value];
+ };
+}
+
+function timeZoneGetter(date, formats, offset) {
+ var zone = -1 * offset;
+ var paddedZone = (zone >= 0) ? "+" : "";
+
+ paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
+ padNumber(Math.abs(zone % 60), 2);
+
+ return paddedZone;
+}
+
+function getFirstThursdayOfYear(year) {
+ // 0 = index of January
+ var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
+ // 4 = index of Thursday (+1 to account for 1st = 5)
+ // 11 = index of *next* Thursday (+1 account for 1st = 12)
+ return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
+}
+
+function getThursdayThisWeek(datetime) {
+ return new Date(datetime.getFullYear(), datetime.getMonth(),
+ // 4 = index of Thursday
+ datetime.getDate() + (4 - datetime.getDay()));
+}
+
+function weekGetter(size) {
+ return function(date) {
+ var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
+ thisThurs = getThursdayThisWeek(date);
+
+ var diff = +thisThurs - +firstThurs,
+ result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
+
+ return padNumber(result, size);
+ };
+}
+
+function ampmGetter(date, formats) {
+ return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
+}
+
+function eraGetter(date, formats) {
+ return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
+}
+
+function longEraGetter(date, formats) {
+ return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
+}
+
+var DATE_FORMATS = {
+ yyyy: dateGetter('FullYear', 4),
+ yy: dateGetter('FullYear', 2, 0, true),
+ y: dateGetter('FullYear', 1),
+ MMMM: dateStrGetter('Month'),
+ MMM: dateStrGetter('Month', true),
+ MM: dateGetter('Month', 2, 1),
+ M: dateGetter('Month', 1, 1),
+ dd: dateGetter('Date', 2),
+ d: dateGetter('Date', 1),
+ HH: dateGetter('Hours', 2),
+ H: dateGetter('Hours', 1),
+ hh: dateGetter('Hours', 2, -12),
+ h: dateGetter('Hours', 1, -12),
+ mm: dateGetter('Minutes', 2),
+ m: dateGetter('Minutes', 1),
+ ss: dateGetter('Seconds', 2),
+ s: dateGetter('Seconds', 1),
+ // while ISO 8601 requires fractions to be prefixed with `.` or `,`
+ // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
+ sss: dateGetter('Milliseconds', 3),
+ EEEE: dateStrGetter('Day'),
+ EEE: dateStrGetter('Day', true),
+ a: ampmGetter,
+ Z: timeZoneGetter,
+ ww: weekGetter(2),
+ w: weekGetter(1),
+ G: eraGetter,
+ GG: eraGetter,
+ GGG: eraGetter,
+ GGGG: longEraGetter
+};
+
+var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
+ NUMBER_STRING = /^\-?\d+$/;
+
+/**
+ * @ngdoc filter
+ * @name date
+ * @kind function
+ *
+ * @description
+ * Formats `date` to a string based on the requested `format`.
+ *
+ * `format` string can be composed of the following elements:
+ *
+ * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
+ * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
+ * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
+ * * `'MMMM'`: Month in year (January-December)
+ * * `'MMM'`: Month in year (Jan-Dec)
+ * * `'MM'`: Month in year, padded (01-12)
+ * * `'M'`: Month in year (1-12)
+ * * `'dd'`: Day in month, padded (01-31)
+ * * `'d'`: Day in month (1-31)
+ * * `'EEEE'`: Day in Week,(Sunday-Saturday)
+ * * `'EEE'`: Day in Week, (Sun-Sat)
+ * * `'HH'`: Hour in day, padded (00-23)
+ * * `'H'`: Hour in day (0-23)
+ * * `'hh'`: Hour in AM/PM, padded (01-12)
+ * * `'h'`: Hour in AM/PM, (1-12)
+ * * `'mm'`: Minute in hour, padded (00-59)
+ * * `'m'`: Minute in hour (0-59)
+ * * `'ss'`: Second in minute, padded (00-59)
+ * * `'s'`: Second in minute (0-59)
+ * * `'sss'`: Millisecond in second, padded (000-999)
+ * * `'a'`: AM/PM marker
+ * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
+ * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
+ * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
+ * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
+ * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
+ *
+ * `format` string can also be one of the following predefined
+ * {@link guide/i18n localizable formats}:
+ *
+ * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
+ * (e.g. Sep 3, 2010 12:05:08 PM)
+ * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
+ * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
+ * (e.g. Friday, September 3, 2010)
+ * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
+ * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
+ * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
+ * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
+ * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
+ *
+ * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
+ * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
+ * (e.g. `"h 'o''clock'"`).
+ *
+ * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
+ * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
+ * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
+ * specified in the string input, the time is considered to be in the local timezone.
+ * @param {string=} format Formatting rules (see Description). If not specified,
+ * `mediumDate` is used.
+ * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
+ * continental US time zone abbreviations, but for general use, use a time zone offset, for
+ * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
+ * If not specified, the timezone of the browser will be used.
+ * @returns {string} Formatted string or the input if input is not recognized as date/millis.
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
+ <span>{{1288323623006 | date:'medium'}}</span><br>
+ <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
+ <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
+ <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
+ <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
+ <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
+ <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should format date', function() {
+ expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
+ toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
+ expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
+ toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
+ expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
+ toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
+ expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
+ toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
+ });
+ </file>
+ </example>
+ */
+dateFilter.$inject = ['$locale'];
+function dateFilter($locale) {
+
+
+ var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
+ // 1 2 3 4 5 6 7 8 9 10 11
+ function jsonStringToDate(string) {
+ var match;
+ if (match = string.match(R_ISO8601_STR)) {
+ var date = new Date(0),
+ tzHour = 0,
+ tzMin = 0,
+ dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
+ timeSetter = match[8] ? date.setUTCHours : date.setHours;
+
+ if (match[9]) {
+ tzHour = toInt(match[9] + match[10]);
+ tzMin = toInt(match[9] + match[11]);
+ }
+ dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
+ var h = toInt(match[4] || 0) - tzHour;
+ var m = toInt(match[5] || 0) - tzMin;
+ var s = toInt(match[6] || 0);
+ var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
+ timeSetter.call(date, h, m, s, ms);
+ return date;
+ }
+ return string;
+ }
+
+
+ return function(date, format, timezone) {
+ var text = '',
+ parts = [],
+ fn, match;
+
+ format = format || 'mediumDate';
+ format = $locale.DATETIME_FORMATS[format] || format;
+ if (isString(date)) {
+ date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
+ }
+
+ if (isNumber(date)) {
+ date = new Date(date);
+ }
+
+ if (!isDate(date) || !isFinite(date.getTime())) {
+ return date;
+ }
+
+ while (format) {
+ match = DATE_FORMATS_SPLIT.exec(format);
+ if (match) {
+ parts = concat(parts, match, 1);
+ format = parts.pop();
+ } else {
+ parts.push(format);
+ format = null;
+ }
+ }
+
+ var dateTimezoneOffset = date.getTimezoneOffset();
+ if (timezone) {
+ dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
+ date = convertTimezoneToLocal(date, timezone, true);
+ }
+ forEach(parts, function(value) {
+ fn = DATE_FORMATS[value];
+ text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
+ : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
+ });
+
+ return text;
+ };
+}
+
+
+/**
+ * @ngdoc filter
+ * @name json
+ * @kind function
+ *
+ * @description
+ * Allows you to convert a JavaScript object into JSON string.
+ *
+ * This filter is mostly useful for debugging. When using the double curly {{value}} notation
+ * the binding is automatically converted to JSON.
+ *
+ * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
+ * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
+ * @returns {string} JSON string.
+ *
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
+ <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should jsonify filtered objects', function() {
+ expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
+ expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
+ });
+ </file>
+ </example>
+ *
+ */
+function jsonFilter() {
+ return function(object, spacing) {
+ if (isUndefined(spacing)) {
+ spacing = 2;
+ }
+ return toJson(object, spacing);
+ };
+}
+
+
+/**
+ * @ngdoc filter
+ * @name lowercase
+ * @kind function
+ * @description
+ * Converts string to lowercase.
+ * @see angular.lowercase
+ */
+var lowercaseFilter = valueFn(lowercase);
+
+
+/**
+ * @ngdoc filter
+ * @name uppercase
+ * @kind function
+ * @description
+ * Converts string to uppercase.
+ * @see angular.uppercase
+ */
+var uppercaseFilter = valueFn(uppercase);
+
+/**
+ * @ngdoc filter
+ * @name limitTo
+ * @kind function
+ *
+ * @description
+ * Creates a new array or string containing only a specified number of elements. The elements
+ * are taken from either the beginning or the end of the source array, string or number, as specified by
+ * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
+ * converted to a string.
+ *
+ * @param {Array|string|number} input Source array, string or number to be limited.
+ * @param {string|number} limit The length of the returned array or string. If the `limit` number
+ * is positive, `limit` number of items from the beginning of the source array/string are copied.
+ * If the number is negative, `limit` number of items from the end of the source array/string
+ * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
+ * the input will be returned unchanged.
+ * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
+ * indicates an offset from the end of `input`. Defaults to `0`.
+ * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
+ * had less than `limit` elements.
+ *
+ * @example
+ <example module="limitToExample">
+ <file name="index.html">
+ <script>
+ angular.module('limitToExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.numbers = [1,2,3,4,5,6,7,8,9];
+ $scope.letters = "abcdefghi";
+ $scope.longNumber = 2345432342;
+ $scope.numLimit = 3;
+ $scope.letterLimit = 3;
+ $scope.longNumberLimit = 3;
+ }]);
+ </script>
+ <div ng-controller="ExampleController">
+ <label>
+ Limit {{numbers}} to:
+ <input type="number" step="1" ng-model="numLimit">
+ </label>
+ <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
+ <label>
+ Limit {{letters}} to:
+ <input type="number" step="1" ng-model="letterLimit">
+ </label>
+ <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
+ <label>
+ Limit {{longNumber}} to:
+ <input type="number" step="1" ng-model="longNumberLimit">
+ </label>
+ <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
+ </div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ var numLimitInput = element(by.model('numLimit'));
+ var letterLimitInput = element(by.model('letterLimit'));
+ var longNumberLimitInput = element(by.model('longNumberLimit'));
+ var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
+ var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
+ var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
+
+ it('should limit the number array to first three items', function() {
+ expect(numLimitInput.getAttribute('value')).toBe('3');
+ expect(letterLimitInput.getAttribute('value')).toBe('3');
+ expect(longNumberLimitInput.getAttribute('value')).toBe('3');
+ expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
+ expect(limitedLetters.getText()).toEqual('Output letters: abc');
+ expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
+ });
+
+ // There is a bug in safari and protractor that doesn't like the minus key
+ // it('should update the output when -3 is entered', function() {
+ // numLimitInput.clear();
+ // numLimitInput.sendKeys('-3');
+ // letterLimitInput.clear();
+ // letterLimitInput.sendKeys('-3');
+ // longNumberLimitInput.clear();
+ // longNumberLimitInput.sendKeys('-3');
+ // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
+ // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
+ // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
+ // });
+
+ it('should not exceed the maximum size of input array', function() {
+ numLimitInput.clear();
+ numLimitInput.sendKeys('100');
+ letterLimitInput.clear();
+ letterLimitInput.sendKeys('100');
+ longNumberLimitInput.clear();
+ longNumberLimitInput.sendKeys('100');
+ expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
+ expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
+ expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
+ });
+ </file>
+ </example>
+*/
+function limitToFilter() {
+ return function(input, limit, begin) {
+ if (Math.abs(Number(limit)) === Infinity) {
+ limit = Number(limit);
+ } else {
+ limit = toInt(limit);
+ }
+ if (isNaN(limit)) return input;
+
+ if (isNumber(input)) input = input.toString();
+ if (!isArray(input) && !isString(input)) return input;
+
+ begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
+ begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
+
+ if (limit >= 0) {
+ return input.slice(begin, begin + limit);
+ } else {
+ if (begin === 0) {
+ return input.slice(limit, input.length);
+ } else {
+ return input.slice(Math.max(0, begin + limit), begin);
+ }
+ }
+ };
+}
+
+/**
+ * @ngdoc filter
+ * @name orderBy
+ * @kind function
+ *
+ * @description
+ * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
+ * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
+ * as expected, make sure they are actually being saved as numbers and not strings.
+ *
+ * @param {Array} array The array to sort.
+ * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
+ * used by the comparator to determine the order of elements.
+ *
+ * Can be one of:
+ *
+ * - `function`: Getter function. The result of this function will be sorted using the
+ * `<`, `===`, `>` operator.
+ * - `string`: An Angular expression. The result of this expression is used to compare elements
+ * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
+ * 3 first characters of a property called `name`). The result of a constant expression
+ * is interpreted as a property name to be used in comparisons (for example `"special name"`
+ * to sort object by the value of their `special name` property). An expression can be
+ * optionally prefixed with `+` or `-` to control ascending or descending sort order
+ * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
+ * element itself is used to compare where sorting.
+ * - `Array`: An array of function or string predicates. The first predicate in the array
+ * is used for sorting, but when two items are equivalent, the next predicate is used.
+ *
+ * If the predicate is missing or empty then it defaults to `'+'`.
+ *
+ * @param {boolean=} reverse Reverse the order of the array.
+ * @returns {Array} Sorted copy of the source array.
+ *
+ *
+ * @example
+ * The example below demonstrates a simple ngRepeat, where the data is sorted
+ * by age in descending order (predicate is set to `'-age'`).
+ * `reverse` is not set, which means it defaults to `false`.
+ <example module="orderByExample">
+ <file name="index.html">
+ <script>
+ angular.module('orderByExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.friends =
+ [{name:'John', phone:'555-1212', age:10},
+ {name:'Mary', phone:'555-9876', age:19},
+ {name:'Mike', phone:'555-4321', age:21},
+ {name:'Adam', phone:'555-5678', age:35},
+ {name:'Julie', phone:'555-8765', age:29}];
+ }]);
+ </script>
+ <div ng-controller="ExampleController">
+ <table class="friend">
+ <tr>
+ <th>Name</th>
+ <th>Phone Number</th>
+ <th>Age</th>
+ </tr>
+ <tr ng-repeat="friend in friends | orderBy:'-age'">
+ <td>{{friend.name}}</td>
+ <td>{{friend.phone}}</td>
+ <td>{{friend.age}}</td>
+ </tr>
+ </table>
+ </div>
+ </file>
+ </example>
+ *
+ * The predicate and reverse parameters can be controlled dynamically through scope properties,
+ * as shown in the next example.
+ * @example
+ <example module="orderByExample">
+ <file name="index.html">
+ <script>
+ angular.module('orderByExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.friends =
+ [{name:'John', phone:'555-1212', age:10},
+ {name:'Mary', phone:'555-9876', age:19},
+ {name:'Mike', phone:'555-4321', age:21},
+ {name:'Adam', phone:'555-5678', age:35},
+ {name:'Julie', phone:'555-8765', age:29}];
+ $scope.predicate = 'age';
+ $scope.reverse = true;
+ $scope.order = function(predicate) {
+ $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
+ $scope.predicate = predicate;
+ };
+ }]);
+ </script>
+ <style type="text/css">
+ .sortorder:after {
+ content: '\25b2';
+ }
+ .sortorder.reverse:after {
+ content: '\25bc';
+ }
+ </style>
+ <div ng-controller="ExampleController">
+ <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
+ <hr/>
+ [ <a href="" ng-click="predicate=''">unsorted</a> ]
+ <table class="friend">
+ <tr>
+ <th>
+ <a href="" ng-click="order('name')">Name</a>
+ <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
+ </th>
+ <th>
+ <a href="" ng-click="order('phone')">Phone Number</a>
+ <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
+ </th>
+ <th>
+ <a href="" ng-click="order('age')">Age</a>
+ <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
+ </th>
+ </tr>
+ <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
+ <td>{{friend.name}}</td>
+ <td>{{friend.phone}}</td>
+ <td>{{friend.age}}</td>
+ </tr>
+ </table>
+ </div>
+ </file>
+ </example>
+ *
+ * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
+ * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
+ * desired parameters.
+ *
+ * Example:
+ *
+ * @example
+ <example module="orderByExample">
+ <file name="index.html">
+ <div ng-controller="ExampleController">
+ <table class="friend">
+ <tr>
+ <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
+ (<a href="" ng-click="order('-name',false)">^</a>)</th>
+ <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
+ <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
+ </tr>
+ <tr ng-repeat="friend in friends">
+ <td>{{friend.name}}</td>
+ <td>{{friend.phone}}</td>
+ <td>{{friend.age}}</td>
+ </tr>
+ </table>
+ </div>
+ </file>
+
+ <file name="script.js">
+ angular.module('orderByExample', [])
+ .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
+ var orderBy = $filter('orderBy');
+ $scope.friends = [
+ { name: 'John', phone: '555-1212', age: 10 },
+ { name: 'Mary', phone: '555-9876', age: 19 },
+ { name: 'Mike', phone: '555-4321', age: 21 },
+ { name: 'Adam', phone: '555-5678', age: 35 },
+ { name: 'Julie', phone: '555-8765', age: 29 }
+ ];
+ $scope.order = function(predicate, reverse) {
+ $scope.friends = orderBy($scope.friends, predicate, reverse);
+ };
+ $scope.order('-age',false);
+ }]);
+ </file>
+</example>
+ */
+orderByFilter.$inject = ['$parse'];
+function orderByFilter($parse) {
+ return function(array, sortPredicate, reverseOrder) {
+
+ if (!(isArrayLike(array))) return array;
+
+ if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
+ if (sortPredicate.length === 0) { sortPredicate = ['+']; }
+
+ var predicates = processPredicates(sortPredicate, reverseOrder);
+ // Add a predicate at the end that evaluates to the element index. This makes the
+ // sort stable as it works as a tie-breaker when all the input predicates cannot
+ // distinguish between two elements.
+ predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
+
+ // The next three lines are a version of a Swartzian Transform idiom from Perl
+ // (sometimes called the Decorate-Sort-Undecorate idiom)
+ // See https://en.wikipedia.org/wiki/Schwartzian_transform
+ var compareValues = Array.prototype.map.call(array, getComparisonObject);
+ compareValues.sort(doComparison);
+ array = compareValues.map(function(item) { return item.value; });
+
+ return array;
+
+ function getComparisonObject(value, index) {
+ return {
+ value: value,
+ predicateValues: predicates.map(function(predicate) {
+ return getPredicateValue(predicate.get(value), index);
+ })
+ };
+ }
+
+ function doComparison(v1, v2) {
+ var result = 0;
+ for (var index=0, length = predicates.length; index < length; ++index) {
+ result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
+ if (result) break;
+ }
+ return result;
+ }
+ };
+
+ function processPredicates(sortPredicate, reverseOrder) {
+ reverseOrder = reverseOrder ? -1 : 1;
+ return sortPredicate.map(function(predicate) {
+ var descending = 1, get = identity;
+
+ if (isFunction(predicate)) {
+ get = predicate;
+ } else if (isString(predicate)) {
+ if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
+ descending = predicate.charAt(0) == '-' ? -1 : 1;
+ predicate = predicate.substring(1);
+ }
+ if (predicate !== '') {
+ get = $parse(predicate);
+ if (get.constant) {
+ var key = get();
+ get = function(value) { return value[key]; };
+ }
+ }
+ }
+ return { get: get, descending: descending * reverseOrder };
+ });
+ }
+
+ function isPrimitive(value) {
+ switch (typeof value) {
+ case 'number': /* falls through */
+ case 'boolean': /* falls through */
+ case 'string':
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ function objectValue(value, index) {
+ // If `valueOf` is a valid function use that
+ if (typeof value.valueOf === 'function') {
+ value = value.valueOf();
+ if (isPrimitive(value)) return value;
+ }
+ // If `toString` is a valid function and not the one from `Object.prototype` use that
+ if (hasCustomToString(value)) {
+ value = value.toString();
+ if (isPrimitive(value)) return value;
+ }
+ // We have a basic object so we use the position of the object in the collection
+ return index;
+ }
+
+ function getPredicateValue(value, index) {
+ var type = typeof value;
+ if (value === null) {
+ type = 'string';
+ value = 'null';
+ } else if (type === 'string') {
+ value = value.toLowerCase();
+ } else if (type === 'object') {
+ value = objectValue(value, index);
+ }
+ return { value: value, type: type };
+ }
+
+ function compare(v1, v2) {
+ var result = 0;
+ if (v1.type === v2.type) {
+ if (v1.value !== v2.value) {
+ result = v1.value < v2.value ? -1 : 1;
+ }
+ } else {
+ result = v1.type < v2.type ? -1 : 1;
+ }
+ return result;
+ }
+}
+
+function ngDirective(directive) {
+ if (isFunction(directive)) {
+ directive = {
+ link: directive
+ };
+ }
+ directive.restrict = directive.restrict || 'AC';
+ return valueFn(directive);
+}
+
+/**
+ * @ngdoc directive
+ * @name a
+ * @restrict E
+ *
+ * @description
+ * Modifies the default behavior of the html A tag so that the default action is prevented when
+ * the href attribute is empty.
+ *
+ * This change permits the easy creation of action links with the `ngClick` directive
+ * without changing the location or causing page reloads, e.g.:
+ * `<a href="" ng-click="list.addItem()">Add Item</a>`
+ */
+var htmlAnchorDirective = valueFn({
+ restrict: 'E',
+ compile: function(element, attr) {
+ if (!attr.href && !attr.xlinkHref) {
+ return function(scope, element) {
+ // If the linked element is not an anchor tag anymore, do nothing
+ if (element[0].nodeName.toLowerCase() !== 'a') return;
+
+ // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
+ var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
+ 'xlink:href' : 'href';
+ element.on('click', function(event) {
+ // if we have no href url, then don't navigate anywhere.
+ if (!element.attr(href)) {
+ event.preventDefault();
+ }
+ });
+ };
+ }
+ }
+});
+
+/**
+ * @ngdoc directive
+ * @name ngHref
+ * @restrict A
+ * @priority 99
+ *
+ * @description
+ * Using Angular markup like `{{hash}}` in an href attribute will
+ * make the link go to the wrong URL if the user clicks it before
+ * Angular has a chance to replace the `{{hash}}` markup with its
+ * value. Until Angular replaces the markup the link will be broken
+ * and will most likely return a 404 error. The `ngHref` directive
+ * solves this problem.
+ *
+ * The wrong way to write it:
+ * ```html
+ * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
+ * ```
+ *
+ * The correct way to write it:
+ * ```html
+ * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
+ * ```
+ *
+ * @element A
+ * @param {template} ngHref any string which can contain `{{}}` markup.
+ *
+ * @example
+ * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
+ * in links and their different behaviors:
+ <example>
+ <file name="index.html">
+ <input ng-model="value" /><br />
+ <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
+ <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
+ <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
+ <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
+ <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
+ <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should execute ng-click but not reload when href without value', function() {
+ element(by.id('link-1')).click();
+ expect(element(by.model('value')).getAttribute('value')).toEqual('1');
+ expect(element(by.id('link-1')).getAttribute('href')).toBe('');
+ });
+
+ it('should execute ng-click but not reload when href empty string', function() {
+ element(by.id('link-2')).click();
+ expect(element(by.model('value')).getAttribute('value')).toEqual('2');
+ expect(element(by.id('link-2')).getAttribute('href')).toBe('');
+ });
+
+ it('should execute ng-click and change url when ng-href specified', function() {
+ expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
+
+ element(by.id('link-3')).click();
+
+ // At this point, we navigate away from an Angular page, so we need
+ // to use browser.driver to get the base webdriver.
+
+ browser.wait(function() {
+ return browser.driver.getCurrentUrl().then(function(url) {
+ return url.match(/\/123$/);
+ });
+ }, 5000, 'page should navigate to /123');
+ });
+
+ it('should execute ng-click but not reload when href empty string and name specified', function() {
+ element(by.id('link-4')).click();
+ expect(element(by.model('value')).getAttribute('value')).toEqual('4');
+ expect(element(by.id('link-4')).getAttribute('href')).toBe('');
+ });
+
+ it('should execute ng-click but not reload when no href but name specified', function() {
+ element(by.id('link-5')).click();
+ expect(element(by.model('value')).getAttribute('value')).toEqual('5');
+ expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
+ });
+
+ it('should only change url when only ng-href', function() {
+ element(by.model('value')).clear();
+ element(by.model('value')).sendKeys('6');
+ expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
+
+ element(by.id('link-6')).click();
+
+ // At this point, we navigate away from an Angular page, so we need
+ // to use browser.driver to get the base webdriver.
+ browser.wait(function() {
+ return browser.driver.getCurrentUrl().then(function(url) {
+ return url.match(/\/6$/);
+ });
+ }, 5000, 'page should navigate to /6');
+ });
+ </file>
+ </example>
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngSrc
+ * @restrict A
+ * @priority 99
+ *
+ * @description
+ * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
+ * work right: The browser will fetch from the URL with the literal
+ * text `{{hash}}` until Angular replaces the expression inside
+ * `{{hash}}`. The `ngSrc` directive solves this problem.
+ *
+ * The buggy way to write it:
+ * ```html
+ * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
+ * ```
+ *
+ * The correct way to write it:
+ * ```html
+ * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
+ * ```
+ *
+ * @element IMG
+ * @param {template} ngSrc any string which can contain `{{}}` markup.
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngSrcset
+ * @restrict A
+ * @priority 99
+ *
+ * @description
+ * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
+ * work right: The browser will fetch from the URL with the literal
+ * text `{{hash}}` until Angular replaces the expression inside
+ * `{{hash}}`. The `ngSrcset` directive solves this problem.
+ *
+ * The buggy way to write it:
+ * ```html
+ * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
+ * ```
+ *
+ * The correct way to write it:
+ * ```html
+ * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
+ * ```
+ *
+ * @element IMG
+ * @param {template} ngSrcset any string which can contain `{{}}` markup.
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngDisabled
+ * @restrict A
+ * @priority 100
+ *
+ * @description
+ *
+ * This directive sets the `disabled` attribute on the element if the
+ * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
+ *
+ * A special directive is necessary because we cannot use interpolation inside the `disabled`
+ * attribute. The following example would make the button enabled on Chrome/Firefox
+ * but not on older IEs:
+ *
+ * ```html
+ * <!-- See below for an example of ng-disabled being used correctly -->
+ * <div ng-init="isDisabled = false">
+ * <button disabled="{{isDisabled}}">Disabled</button>
+ * </div>
+ * ```
+ *
+ * This is because the HTML specification does not require browsers to preserve the values of
+ * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
+ * If we put an Angular interpolation expression into such an attribute then the
+ * binding information would be lost when the browser removes the attribute.
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
+ <button ng-model="button" ng-disabled="checked">Button</button>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should toggle button', function() {
+ expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
+ element(by.model('checked')).click();
+ expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
+ });
+ </file>
+ </example>
+ *
+ * @element INPUT
+ * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
+ * then the `disabled` attribute will be set on the element
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngChecked
+ * @restrict A
+ * @priority 100
+ *
+ * @description
+ * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
+ *
+ * Note that this directive should not be used together with {@link ngModel `ngModel`},
+ * as this can lead to unexpected behavior.
+ *
+ * ### Why do we need `ngChecked`?
+ *
+ * The HTML specification does not require browsers to preserve the values of boolean attributes
+ * such as checked. (Their presence means true and their absence means false.)
+ * If we put an Angular interpolation expression into such an attribute then the
+ * binding information would be lost when the browser removes the attribute.
+ * The `ngChecked` directive solves this problem for the `checked` attribute.
+ * This complementary directive is not removed by the browser and so provides
+ * a permanent reliable place to store the binding information.
+ * @example
+ <example>
+ <file name="index.html">
+ <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
+ <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should check both checkBoxes', function() {
+ expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
+ element(by.model('master')).click();
+ expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
+ });
+ </file>
+ </example>
+ *
+ * @element INPUT
+ * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
+ * then the `checked` attribute will be set on the element
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngReadonly
+ * @restrict A
+ * @priority 100
+ *
+ * @description
+ * The HTML specification does not require browsers to preserve the values of boolean attributes
+ * such as readonly. (Their presence means true and their absence means false.)
+ * If we put an Angular interpolation expression into such an attribute then the
+ * binding information would be lost when the browser removes the attribute.
+ * The `ngReadonly` directive solves this problem for the `readonly` attribute.
+ * This complementary directive is not removed by the browser and so provides
+ * a permanent reliable place to store the binding information.
+ * @example
+ <example>
+ <file name="index.html">
+ <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
+ <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should toggle readonly attr', function() {
+ expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
+ element(by.model('checked')).click();
+ expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
+ });
+ </file>
+ </example>
+ *
+ * @element INPUT
+ * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
+ * then special attribute "readonly" will be set on the element
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngSelected
+ * @restrict A
+ * @priority 100
+ *
+ * @description
+ * The HTML specification does not require browsers to preserve the values of boolean attributes
+ * such as selected. (Their presence means true and their absence means false.)
+ * If we put an Angular interpolation expression into such an attribute then the
+ * binding information would be lost when the browser removes the attribute.
+ * The `ngSelected` directive solves this problem for the `selected` attribute.
+ * This complementary directive is not removed by the browser and so provides
+ * a permanent reliable place to store the binding information.
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
+ <select aria-label="ngSelected demo">
+ <option>Hello!</option>
+ <option id="greet" ng-selected="selected">Greetings!</option>
+ </select>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should select Greetings!', function() {
+ expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
+ element(by.model('selected')).click();
+ expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
+ });
+ </file>
+ </example>
+ *
+ * @element OPTION
+ * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
+ * then special attribute "selected" will be set on the element
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngOpen
+ * @restrict A
+ * @priority 100
+ *
+ * @description
+ * The HTML specification does not require browsers to preserve the values of boolean attributes
+ * such as open. (Their presence means true and their absence means false.)
+ * If we put an Angular interpolation expression into such an attribute then the
+ * binding information would be lost when the browser removes the attribute.
+ * The `ngOpen` directive solves this problem for the `open` attribute.
+ * This complementary directive is not removed by the browser and so provides
+ * a permanent reliable place to store the binding information.
+ * @example
+ <example>
+ <file name="index.html">
+ <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
+ <details id="details" ng-open="open">
+ <summary>Show/Hide me</summary>
+ </details>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should toggle open', function() {
+ expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
+ element(by.model('open')).click();
+ expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
+ });
+ </file>
+ </example>
+ *
+ * @element DETAILS
+ * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
+ * then special attribute "open" will be set on the element
+ */
+
+var ngAttributeAliasDirectives = {};
+
+// boolean attrs are evaluated
+forEach(BOOLEAN_ATTR, function(propName, attrName) {
+ // binding to multiple is not supported
+ if (propName == "multiple") return;
+
+ function defaultLinkFn(scope, element, attr) {
+ scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
+ attr.$set(attrName, !!value);
+ });
+ }
+
+ var normalized = directiveNormalize('ng-' + attrName);
+ var linkFn = defaultLinkFn;
+
+ if (propName === 'checked') {
+ linkFn = function(scope, element, attr) {
+ // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
+ if (attr.ngModel !== attr[normalized]) {
+ defaultLinkFn(scope, element, attr);
+ }
+ };
+ }
+
+ ngAttributeAliasDirectives[normalized] = function() {
+ return {
+ restrict: 'A',
+ priority: 100,
+ link: linkFn
+ };
+ };
+});
+
+// aliased input attrs are evaluated
+forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
+ ngAttributeAliasDirectives[ngAttr] = function() {
+ return {
+ priority: 100,
+ link: function(scope, element, attr) {
+ //special case ngPattern when a literal regular expression value
+ //is used as the expression (this way we don't have to watch anything).
+ if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
+ var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
+ if (match) {
+ attr.$set("ngPattern", new RegExp(match[1], match[2]));
+ return;
+ }
+ }
+
+ scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
+ attr.$set(ngAttr, value);
+ });
+ }
+ };
+ };
+});
+
+// ng-src, ng-srcset, ng-href are interpolated
+forEach(['src', 'srcset', 'href'], function(attrName) {
+ var normalized = directiveNormalize('ng-' + attrName);
+ ngAttributeAliasDirectives[normalized] = function() {
+ return {
+ priority: 99, // it needs to run after the attributes are interpolated
+ link: function(scope, element, attr) {
+ var propName = attrName,
+ name = attrName;
+
+ if (attrName === 'href' &&
+ toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
+ name = 'xlinkHref';
+ attr.$attr[name] = 'xlink:href';
+ propName = null;
+ }
+
+ attr.$observe(normalized, function(value) {
+ if (!value) {
+ if (attrName === 'href') {
+ attr.$set(name, null);
+ }
+ return;
+ }
+
+ attr.$set(name, value);
+
+ // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
+ // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
+ // to set the property as well to achieve the desired effect.
+ // we use attr[attrName] value since $set can sanitize the url.
+ if (msie && propName) element.prop(propName, attr[name]);
+ });
+ }
+ };
+ };
+});
+
+/* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
+ */
+var nullFormCtrl = {
+ $addControl: noop,
+ $$renameControl: nullFormRenameControl,
+ $removeControl: noop,
+ $setValidity: noop,
+ $setDirty: noop,
+ $setPristine: noop,
+ $setSubmitted: noop
+},
+SUBMITTED_CLASS = 'ng-submitted';
+
+function nullFormRenameControl(control, name) {
+ control.$name = name;
+}
+
+/**
+ * @ngdoc type
+ * @name form.FormController
+ *
+ * @property {boolean} $pristine True if user has not interacted with the form yet.
+ * @property {boolean} $dirty True if user has already interacted with the form.
+ * @property {boolean} $valid True if all of the containing forms and controls are valid.
+ * @property {boolean} $invalid True if at least one containing control or form is invalid.
+ * @property {boolean} $pending True if at least one containing control or form is pending.
+ * @property {boolean} $submitted True if user has submitted the form even if its invalid.
+ *
+ * @property {Object} $error Is an object hash, containing references to controls or
+ * forms with failing validators, where:
+ *
+ * - keys are validation tokens (error names),
+ * - values are arrays of controls or forms that have a failing validator for given error name.
+ *
+ * Built-in validation tokens:
+ *
+ * - `email`
+ * - `max`
+ * - `maxlength`
+ * - `min`
+ * - `minlength`
+ * - `number`
+ * - `pattern`
+ * - `required`
+ * - `url`
+ * - `date`
+ * - `datetimelocal`
+ * - `time`
+ * - `week`
+ * - `month`
+ *
+ * @description
+ * `FormController` keeps track of all its controls and nested forms as well as the state of them,
+ * such as being valid/invalid or dirty/pristine.
+ *
+ * Each {@link ng.directive:form form} directive creates an instance
+ * of `FormController`.
+ *
+ */
+//asks for $scope to fool the BC controller module
+FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
+function FormController(element, attrs, $scope, $animate, $interpolate) {
+ var form = this,
+ controls = [];
+
+ // init state
+ form.$error = {};
+ form.$$success = {};
+ form.$pending = undefined;
+ form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
+ form.$dirty = false;
+ form.$pristine = true;
+ form.$valid = true;
+ form.$invalid = false;
+ form.$submitted = false;
+ form.$$parentForm = nullFormCtrl;
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$rollbackViewValue
+ *
+ * @description
+ * Rollback all form controls pending updates to the `$modelValue`.
+ *
+ * Updates may be pending by a debounced event or because the input is waiting for a some future
+ * event defined in `ng-model-options`. This method is typically needed by the reset button of
+ * a form that uses `ng-model-options` to pend updates.
+ */
+ form.$rollbackViewValue = function() {
+ forEach(controls, function(control) {
+ control.$rollbackViewValue();
+ });
+ };
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$commitViewValue
+ *
+ * @description
+ * Commit all form controls pending updates to the `$modelValue`.
+ *
+ * Updates may be pending by a debounced event or because the input is waiting for a some future
+ * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
+ * usually handles calling this in response to input events.
+ */
+ form.$commitViewValue = function() {
+ forEach(controls, function(control) {
+ control.$commitViewValue();
+ });
+ };
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$addControl
+ * @param {object} control control object, either a {@link form.FormController} or an
+ * {@link ngModel.NgModelController}
+ *
+ * @description
+ * Register a control with the form. Input elements using ngModelController do this automatically
+ * when they are linked.
+ *
+ * Note that the current state of the control will not be reflected on the new parent form. This
+ * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
+ * state.
+ *
+ * However, if the method is used programmatically, for example by adding dynamically created controls,
+ * or controls that have been previously removed without destroying their corresponding DOM element,
+ * it's the developers responsiblity to make sure the current state propagates to the parent form.
+ *
+ * For example, if an input control is added that is already `$dirty` and has `$error` properties,
+ * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
+ */
+ form.$addControl = function(control) {
+ // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
+ // and not added to the scope. Now we throw an error.
+ assertNotHasOwnProperty(control.$name, 'input');
+ controls.push(control);
+
+ if (control.$name) {
+ form[control.$name] = control;
+ }
+
+ control.$$parentForm = form;
+ };
+
+ // Private API: rename a form control
+ form.$$renameControl = function(control, newName) {
+ var oldName = control.$name;
+
+ if (form[oldName] === control) {
+ delete form[oldName];
+ }
+ form[newName] = control;
+ control.$name = newName;
+ };
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$removeControl
+ * @param {object} control control object, either a {@link form.FormController} or an
+ * {@link ngModel.NgModelController}
+ *
+ * @description
+ * Deregister a control from the form.
+ *
+ * Input elements using ngModelController do this automatically when they are destroyed.
+ *
+ * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
+ * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
+ * different from case to case. For example, removing the only `$dirty` control from a form may or
+ * may not mean that the form is still `$dirty`.
+ */
+ form.$removeControl = function(control) {
+ if (control.$name && form[control.$name] === control) {
+ delete form[control.$name];
+ }
+ forEach(form.$pending, function(value, name) {
+ form.$setValidity(name, null, control);
+ });
+ forEach(form.$error, function(value, name) {
+ form.$setValidity(name, null, control);
+ });
+ forEach(form.$$success, function(value, name) {
+ form.$setValidity(name, null, control);
+ });
+
+ arrayRemove(controls, control);
+ control.$$parentForm = nullFormCtrl;
+ };
+
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$setValidity
+ *
+ * @description
+ * Sets the validity of a form control.
+ *
+ * This method will also propagate to parent forms.
+ */
+ addSetValidityMethod({
+ ctrl: this,
+ $element: element,
+ set: function(object, property, controller) {
+ var list = object[property];
+ if (!list) {
+ object[property] = [controller];
+ } else {
+ var index = list.indexOf(controller);
+ if (index === -1) {
+ list.push(controller);
+ }
+ }
+ },
+ unset: function(object, property, controller) {
+ var list = object[property];
+ if (!list) {
+ return;
+ }
+ arrayRemove(list, controller);
+ if (list.length === 0) {
+ delete object[property];
+ }
+ },
+ $animate: $animate
+ });
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$setDirty
+ *
+ * @description
+ * Sets the form to a dirty state.
+ *
+ * This method can be called to add the 'ng-dirty' class and set the form to a dirty
+ * state (ng-dirty class). This method will also propagate to parent forms.
+ */
+ form.$setDirty = function() {
+ $animate.removeClass(element, PRISTINE_CLASS);
+ $animate.addClass(element, DIRTY_CLASS);
+ form.$dirty = true;
+ form.$pristine = false;
+ form.$$parentForm.$setDirty();
+ };
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$setPristine
+ *
+ * @description
+ * Sets the form to its pristine state.
+ *
+ * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
+ * state (ng-pristine class). This method will also propagate to all the controls contained
+ * in this form.
+ *
+ * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
+ * saving or resetting it.
+ */
+ form.$setPristine = function() {
+ $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
+ form.$dirty = false;
+ form.$pristine = true;
+ form.$submitted = false;
+ forEach(controls, function(control) {
+ control.$setPristine();
+ });
+ };
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$setUntouched
+ *
+ * @description
+ * Sets the form to its untouched state.
+ *
+ * This method can be called to remove the 'ng-touched' class and set the form controls to their
+ * untouched state (ng-untouched class).
+ *
+ * Setting a form controls back to their untouched state is often useful when setting the form
+ * back to its pristine state.
+ */
+ form.$setUntouched = function() {
+ forEach(controls, function(control) {
+ control.$setUntouched();
+ });
+ };
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$setSubmitted
+ *
+ * @description
+ * Sets the form to its submitted state.
+ */
+ form.$setSubmitted = function() {
+ $animate.addClass(element, SUBMITTED_CLASS);
+ form.$submitted = true;
+ form.$$parentForm.$setSubmitted();
+ };
+}
+
+/**
+ * @ngdoc directive
+ * @name ngForm
+ * @restrict EAC
+ *
+ * @description
+ * Nestable alias of {@link ng.directive:form `form`} directive. HTML
+ * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
+ * sub-group of controls needs to be determined.
+ *
+ * Note: the purpose of `ngForm` is to group controls,
+ * but not to be a replacement for the `<form>` tag with all of its capabilities
+ * (e.g. posting to the server, ...).
+ *
+ * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
+ * related scope, under this name.
+ *
+ */
+
+ /**
+ * @ngdoc directive
+ * @name form
+ * @restrict E
+ *
+ * @description
+ * Directive that instantiates
+ * {@link form.FormController FormController}.
+ *
+ * If the `name` attribute is specified, the form controller is published onto the current scope under
+ * this name.
+ *
+ * # Alias: {@link ng.directive:ngForm `ngForm`}
+ *
+ * In Angular, forms can be nested. This means that the outer form is valid when all of the child
+ * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
+ * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
+ * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
+ * using Angular validation directives in forms that are dynamically generated using the
+ * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
+ * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
+ * `ngForm` directive and nest these in an outer `form` element.
+ *
+ *
+ * # CSS classes
+ * - `ng-valid` is set if the form is valid.
+ * - `ng-invalid` is set if the form is invalid.
+ * - `ng-pending` is set if the form is pending.
+ * - `ng-pristine` is set if the form is pristine.
+ * - `ng-dirty` is set if the form is dirty.
+ * - `ng-submitted` is set if the form was submitted.
+ *
+ * Keep in mind that ngAnimate can detect each of these classes when added and removed.
+ *
+ *
+ * # Submitting a form and preventing the default action
+ *
+ * Since the role of forms in client-side Angular applications is different than in classical
+ * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
+ * page reload that sends the data to the server. Instead some javascript logic should be triggered
+ * to handle the form submission in an application-specific way.
+ *
+ * For this reason, Angular prevents the default action (form submission to the server) unless the
+ * `<form>` element has an `action` attribute specified.
+ *
+ * You can use one of the following two ways to specify what javascript method should be called when
+ * a form is submitted:
+ *
+ * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
+ * - {@link ng.directive:ngClick ngClick} directive on the first
+ * button or input field of type submit (input[type=submit])
+ *
+ * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
+ * or {@link ng.directive:ngClick ngClick} directives.
+ * This is because of the following form submission rules in the HTML specification:
+ *
+ * - If a form has only one input field then hitting enter in this field triggers form submit
+ * (`ngSubmit`)
+ * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
+ * doesn't trigger submit
+ * - if a form has one or more input fields and one or more buttons or input[type=submit] then
+ * hitting enter in any of the input fields will trigger the click handler on the *first* button or
+ * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
+ *
+ * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
+ * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
+ * to have access to the updated model.
+ *
+ * ## Animation Hooks
+ *
+ * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
+ * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
+ * other validations that are performed within the form. Animations in ngForm are similar to how
+ * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
+ * as JS animations.
+ *
+ * The following example shows a simple way to utilize CSS transitions to style a form element
+ * that has been rendered as invalid after it has been validated:
+ *
+ * <pre>
+ * //be sure to include ngAnimate as a module to hook into more
+ * //advanced animations
+ * .my-form {
+ * transition:0.5s linear all;
+ * background: white;
+ * }
+ * .my-form.ng-invalid {
+ * background: red;
+ * color:white;
+ * }
+ * </pre>
+ *
+ * @example
+ <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
+ <file name="index.html">
+ <script>
+ angular.module('formExample', [])
+ .controller('FormController', ['$scope', function($scope) {
+ $scope.userType = 'guest';
+ }]);
+ </script>
+ <style>
+ .my-form {
+ transition:all linear 0.5s;
+ background: transparent;
+ }
+ .my-form.ng-invalid {
+ background: red;
+ }
+ </style>
+ <form name="myForm" ng-controller="FormController" class="my-form">
+ userType: <input name="input" ng-model="userType" required>
+ <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
+ <code>userType = {{userType}}</code><br>
+ <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
+ <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
+ <code>myForm.$valid = {{myForm.$valid}}</code><br>
+ <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should initialize to model', function() {
+ var userType = element(by.binding('userType'));
+ var valid = element(by.binding('myForm.input.$valid'));
+
+ expect(userType.getText()).toContain('guest');
+ expect(valid.getText()).toContain('true');
+ });
+
+ it('should be invalid if empty', function() {
+ var userType = element(by.binding('userType'));
+ var valid = element(by.binding('myForm.input.$valid'));
+ var userInput = element(by.model('userType'));
+
+ userInput.clear();
+ userInput.sendKeys('');
+
+ expect(userType.getText()).toEqual('userType =');
+ expect(valid.getText()).toContain('false');
+ });
+ </file>
+ </example>
+ *
+ * @param {string=} name Name of the form. If specified, the form controller will be published into
+ * related scope, under this name.
+ */
+var formDirectiveFactory = function(isNgForm) {
+ return ['$timeout', '$parse', function($timeout, $parse) {
+ var formDirective = {
+ name: 'form',
+ restrict: isNgForm ? 'EAC' : 'E',
+ require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
+ controller: FormController,
+ compile: function ngFormCompile(formElement, attr) {
+ // Setup initial state of the control
+ formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
+
+ var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
+
+ return {
+ pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
+ var controller = ctrls[0];
+
+ // if `action` attr is not present on the form, prevent the default action (submission)
+ if (!('action' in attr)) {
+ // we can't use jq events because if a form is destroyed during submission the default
+ // action is not prevented. see #1238
+ //
+ // IE 9 is not affected because it doesn't fire a submit event and try to do a full
+ // page reload if the form was destroyed by submission of the form via a click handler
+ // on a button in the form. Looks like an IE9 specific bug.
+ var handleFormSubmission = function(event) {
+ scope.$apply(function() {
+ controller.$commitViewValue();
+ controller.$setSubmitted();
+ });
+
+ event.preventDefault();
+ };
+
+ addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
+
+ // unregister the preventDefault listener so that we don't not leak memory but in a
+ // way that will achieve the prevention of the default action.
+ formElement.on('$destroy', function() {
+ $timeout(function() {
+ removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
+ }, 0, false);
+ });
+ }
+
+ var parentFormCtrl = ctrls[1] || controller.$$parentForm;
+ parentFormCtrl.$addControl(controller);
+
+ var setter = nameAttr ? getSetter(controller.$name) : noop;
+
+ if (nameAttr) {
+ setter(scope, controller);
+ attr.$observe(nameAttr, function(newValue) {
+ if (controller.$name === newValue) return;
+ setter(scope, undefined);
+ controller.$$parentForm.$$renameControl(controller, newValue);
+ setter = getSetter(controller.$name);
+ setter(scope, controller);
+ });
+ }
+ formElement.on('$destroy', function() {
+ controller.$$parentForm.$removeControl(controller);
+ setter(scope, undefined);
+ extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
+ });
+ }
+ };
+ }
+ };
+
+ return formDirective;
+
+ function getSetter(expression) {
+ if (expression === '') {
+ //create an assignable expression, so forms with an empty name can be renamed later
+ return $parse('this[""]').assign;
+ }
+ return $parse(expression).assign || noop;
+ }
+ }];
+};
+
+var formDirective = formDirectiveFactory();
+var ngFormDirective = formDirectiveFactory(true);
+
+/* global VALID_CLASS: false,
+ INVALID_CLASS: false,
+ PRISTINE_CLASS: false,
+ DIRTY_CLASS: false,
+ UNTOUCHED_CLASS: false,
+ TOUCHED_CLASS: false,
+ ngModelMinErr: false,
+*/
+
+// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
+var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
+// See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
+var URL_REGEXP = /^[A-Za-z][A-Za-z\d.+-]*:\/*(?:\w+(?::\w+)?@)?[^\s/]+(?::\d+)?(?:\/[\w#!:.?+=&%@\-/]*)?$/;
+var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
+var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
+var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
+var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
+var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
+var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
+var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
+
+var inputType = {
+
+ /**
+ * @ngdoc input
+ * @name input[text]
+ *
+ * @description
+ * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
+ *
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} required Adds `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
+ * minlength.
+ * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
+ * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
+ * any length.
+ * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
+ * that contains the regular expression body that will be converted to a regular expression
+ * as in the ngPattern directive.
+ * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
+ * a RegExp found by evaluating the Angular expression given in the attribute value.
+ * If the expression evaluates to a RegExp object, then this is used directly.
+ * If the expression evaluates to a string, then it will be converted to a RegExp
+ * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
+ * `new RegExp('^abc$')`.<br />
+ * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
+ * start at the index of the last search's match, thus not taking the whole input value into
+ * account.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
+ * This parameter is ignored for input[type=password] controls, which will never trim the
+ * input.
+ *
+ * @example
+ <example name="text-input-directive" module="textInputExample">
+ <file name="index.html">
+ <script>
+ angular.module('textInputExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.example = {
+ text: 'guest',
+ word: /^\s*\w*\s*$/
+ };
+ }]);
+ </script>
+ <form name="myForm" ng-controller="ExampleController">
+ <label>Single word:
+ <input type="text" name="input" ng-model="example.text"
+ ng-pattern="example.word" required ng-trim="false">
+ </label>
+ <div role="alert">
+ <span class="error" ng-show="myForm.input.$error.required">
+ Required!</span>
+ <span class="error" ng-show="myForm.input.$error.pattern">
+ Single word only!</span>
+ </div>
+ <tt>text = {{example.text}}</tt><br/>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ var text = element(by.binding('example.text'));
+ var valid = element(by.binding('myForm.input.$valid'));
+ var input = element(by.model('example.text'));
+
+ it('should initialize to model', function() {
+ expect(text.getText()).toContain('guest');
+ expect(valid.getText()).toContain('true');
+ });
+
+ it('should be invalid if empty', function() {
+ input.clear();
+ input.sendKeys('');
+
+ expect(text.getText()).toEqual('text =');
+ expect(valid.getText()).toContain('false');
+ });
+
+ it('should be invalid if multi word', function() {
+ input.clear();
+ input.sendKeys('hello world');
+
+ expect(valid.getText()).toContain('false');
+ });
+ </file>
+ </example>
+ */
+ 'text': textInputType,
+
+ /**
+ * @ngdoc input
+ * @name input[date]
+ *
+ * @description
+ * Input with date validation and transformation. In browsers that do not yet support
+ * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
+ * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
+ * modern browsers do not yet support this input type, it is important to provide cues to users on the
+ * expected input format via a placeholder or label.
+ *
+ * The model must always be a Date object, otherwise Angular will throw an error.
+ * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
+ *
+ * The timezone to be used to read/write the `Date` instance in the model can be defined using
+ * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
+ * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
+ * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
+ * constraint validation.
+ * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
+ * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
+ * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
+ * constraint validation.
+ * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
+ * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
+ * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
+ * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <example name="date-input-directive" module="dateInputExample">
+ <file name="index.html">
+ <script>
+ angular.module('dateInputExample', [])
+ .controller('DateController', ['$scope', function($scope) {
+ $scope.example = {
+ value: new Date(2013, 9, 22)
+ };
+ }]);
+ </script>
+ <form name="myForm" ng-controller="DateController as dateCtrl">
+ <label for="exampleInput">Pick a date in 2013:</label>
+ <input type="date" id="exampleInput" name="input" ng-model="example.value"
+ placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
+ <div role="alert">
+ <span class="error" ng-show="myForm.input.$error.required">
+ Required!</span>
+ <span class="error" ng-show="myForm.input.$error.date">
+ Not a valid date!</span>
+ </div>
+ <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
+ var valid = element(by.binding('myForm.input.$valid'));
+ var input = element(by.model('example.value'));
+
+ // currently protractor/webdriver does not support
+ // sending keys to all known HTML5 input controls
+ // for various browsers (see https://github.com/angular/protractor/issues/562).
+ function setInput(val) {
+ // set the value of the element and force validation.
+ var scr = "var ipt = document.getElementById('exampleInput'); " +
+ "ipt.value = '" + val + "';" +
+ "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
+ browser.executeScript(scr);
+ }
+
+ it('should initialize to model', function() {
+ expect(value.getText()).toContain('2013-10-22');
+ expect(valid.getText()).toContain('myForm.input.$valid = true');
+ });
+
+ it('should be invalid if empty', function() {
+ setInput('');
+ expect(value.getText()).toEqual('value =');
+ expect(valid.getText()).toContain('myForm.input.$valid = false');
+ });
+
+ it('should be invalid if over max', function() {
+ setInput('2015-01-01');
+ expect(value.getText()).toContain('');
+ expect(valid.getText()).toContain('myForm.input.$valid = false');
+ });
+ </file>
+ </example>
+ */
+ 'date': createDateInputType('date', DATE_REGEXP,
+ createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
+ 'yyyy-MM-dd'),
+
+ /**
+ * @ngdoc input
+ * @name input[datetime-local]
+ *
+ * @description
+ * Input with datetime validation and transformation. In browsers that do not yet support
+ * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
+ * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
+ *
+ * The model must always be a Date object, otherwise Angular will throw an error.
+ * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
+ *
+ * The timezone to be used to read/write the `Date` instance in the model can be defined using
+ * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
+ * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
+ * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
+ * Note that `min` will also add native HTML5 constraint validation.
+ * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
+ * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
+ * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
+ * Note that `max` will also add native HTML5 constraint validation.
+ * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
+ * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
+ * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
+ * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <example name="datetimelocal-input-directive" module="dateExample">
+ <file name="index.html">
+ <script>
+ angular.module('dateExample', [])
+ .controller('DateController', ['$scope', function($scope) {
+ $scope.example = {
+ value: new Date(2010, 11, 28, 14, 57)
+ };
+ }]);
+ </script>
+ <form name="myForm" ng-controller="DateController as dateCtrl">
+ <label for="exampleInput">Pick a date between in 2013:</label>
+ <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
+ placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
+ <div role="alert">
+ <span class="error" ng-show="myForm.input.$error.required">
+ Required!</span>
+ <span class="error" ng-show="myForm.input.$error.datetimelocal">
+ Not a valid date!</span>
+ </div>
+ <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
+ var valid = element(by.binding('myForm.input.$valid'));
+ var input = element(by.model('example.value'));
+
+ // currently protractor/webdriver does not support
+ // sending keys to all known HTML5 input controls
+ // for various browsers (https://github.com/angular/protractor/issues/562).
+ function setInput(val) {
+ // set the value of the element and force validation.
+ var scr = "var ipt = document.getElementById('exampleInput'); " +
+ "ipt.value = '" + val + "';" +
+ "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
+ browser.executeScript(scr);
+ }
+
+ it('should initialize to model', function() {
+ expect(value.getText()).toContain('2010-12-28T14:57:00');
+ expect(valid.getText()).toContain('myForm.input.$valid = true');
+ });
+
+ it('should be invalid if empty', function() {
+ setInput('');
+ expect(value.getText()).toEqual('value =');
+ expect(valid.getText()).toContain('myForm.input.$valid = false');
+ });
+
+ it('should be invalid if over max', function() {
+ setInput('2015-01-01T23:59:00');
+ expect(value.getText()).toContain('');
+ expect(valid.getText()).toContain('myForm.input.$valid = false');
+ });
+ </file>
+ </example>
+ */
+ 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
+ createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
+ 'yyyy-MM-ddTHH:mm:ss.sss'),
+
+ /**
+ * @ngdoc input
+ * @name input[time]
+ *
+ * @description
+ * Input with time validation and transformation. In browsers that do not yet support
+ * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
+ * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
+ * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
+ *
+ * The model must always be a Date object, otherwise Angular will throw an error.
+ * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
+ *
+ * The timezone to be used to read/write the `Date` instance in the model can be defined using
+ * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
+ * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
+ * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
+ * native HTML5 constraint validation.
+ * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
+ * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
+ * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
+ * native HTML5 constraint validation.
+ * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
+ * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
+ * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
+ * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <example name="time-input-directive" module="timeExample">
+ <file name="index.html">
+ <script>
+ angular.module('timeExample', [])
+ .controller('DateController', ['$scope', function($scope) {
+ $scope.example = {
+ value: new Date(1970, 0, 1, 14, 57, 0)
+ };
+ }]);
+ </script>
+ <form name="myForm" ng-controller="DateController as dateCtrl">
+ <label for="exampleInput">Pick a between 8am and 5pm:</label>
+ <input type="time" id="exampleInput" name="input" ng-model="example.value"
+ placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
+ <div role="alert">
+ <span class="error" ng-show="myForm.input.$error.required">
+ Required!</span>
+ <span class="error" ng-show="myForm.input.$error.time">
+ Not a valid date!</span>
+ </div>
+ <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ var value = element(by.binding('example.value | date: "HH:mm:ss"'));
+ var valid = element(by.binding('myForm.input.$valid'));
+ var input = element(by.model('example.value'));
+
+ // currently protractor/webdriver does not support
+ // sending keys to all known HTML5 input controls
+ // for various browsers (https://github.com/angular/protractor/issues/562).
+ function setInput(val) {
+ // set the value of the element and force validation.
+ var scr = "var ipt = document.getElementById('exampleInput'); " +
+ "ipt.value = '" + val + "';" +
+ "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
+ browser.executeScript(scr);
+ }
+
+ it('should initialize to model', function() {
+ expect(value.getText()).toContain('14:57:00');
+ expect(valid.getText()).toContain('myForm.input.$valid = true');
+ });
+
+ it('should be invalid if empty', function() {
+ setInput('');
+ expect(value.getText()).toEqual('value =');
+ expect(valid.getText()).toContain('myForm.input.$valid = false');
+ });
+
+ it('should be invalid if over max', function() {
+ setInput('23:59:00');
+ expect(value.getText()).toContain('');
+ expect(valid.getText()).toContain('myForm.input.$valid = false');
+ });
+ </file>
+ </example>
+ */
+ 'time': createDateInputType('time', TIME_REGEXP,
+ createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
+ 'HH:mm:ss.sss'),
+
+ /**
+ * @ngdoc input
+ * @name input[week]
+ *
+ * @description
+ * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
+ * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
+ * week format (yyyy-W##), for example: `2013-W02`.
+ *
+ * The model must always be a Date object, otherwise Angular will throw an error.
+ * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
+ *
+ * The timezone to be used to read/write the `Date` instance in the model can be defined using
+ * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
+ * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
+ * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
+ * native HTML5 constraint validation.
+ * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
+ * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
+ * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
+ * native HTML5 constraint validation.
+ * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
+ * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
+ * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
+ * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <example name="week-input-directive" module="weekExample">
+ <file name="index.html">
+ <script>
+ angular.module('weekExample', [])
+ .controller('DateController', ['$scope', function($scope) {
+ $scope.example = {
+ value: new Date(2013, 0, 3)
+ };
+ }]);
+ </script>
+ <form name="myForm" ng-controller="DateController as dateCtrl">
+ <label>Pick a date between in 2013:
+ <input id="exampleInput" type="week" name="input" ng-model="example.value"
+ placeholder="YYYY-W##" min="2012-W32"
+ max="2013-W52" required />
+ </label>
+ <div role="alert">
+ <span class="error" ng-show="myForm.input.$error.required">
+ Required!</span>
+ <span class="error" ng-show="myForm.input.$error.week">
+ Not a valid date!</span>
+ </div>
+ <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ var value = element(by.binding('example.value | date: "yyyy-Www"'));
+ var valid = element(by.binding('myForm.input.$valid'));
+ var input = element(by.model('example.value'));
+
+ // currently protractor/webdriver does not support
+ // sending keys to all known HTML5 input controls
+ // for various browsers (https://github.com/angular/protractor/issues/562).
+ function setInput(val) {
+ // set the value of the element and force validation.
+ var scr = "var ipt = document.getElementById('exampleInput'); " +
+ "ipt.value = '" + val + "';" +
+ "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
+ browser.executeScript(scr);
+ }
+
+ it('should initialize to model', function() {
+ expect(value.getText()).toContain('2013-W01');
+ expect(valid.getText()).toContain('myForm.input.$valid = true');
+ });
+
+ it('should be invalid if empty', function() {
+ setInput('');
+ expect(value.getText()).toEqual('value =');
+ expect(valid.getText()).toContain('myForm.input.$valid = false');
+ });
+
+ it('should be invalid if over max', function() {
+ setInput('2015-W01');
+ expect(value.getText()).toContain('');
+ expect(valid.getText()).toContain('myForm.input.$valid = false');
+ });
+ </file>
+ </example>
+ */
+ 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
+
+ /**
+ * @ngdoc input
+ * @name input[month]
+ *
+ * @description
+ * Input with month validation and transformation. In browsers that do not yet support
+ * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
+ * month format (yyyy-MM), for example: `2009-01`.
+ *
+ * The model must always be a Date object, otherwise Angular will throw an error.
+ * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
+ * If the model is not set to the first of the month, the next view to model update will set it
+ * to the first of the month.
+ *
+ * The timezone to be used to read/write the `Date` instance in the model can be defined using
+ * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
+ * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
+ * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
+ * native HTML5 constraint validation.
+ * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
+ * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
+ * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
+ * native HTML5 constraint validation.
+ * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
+ * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
+ * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
+ * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
+
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <example name="month-input-directive" module="monthExample">
+ <file name="index.html">
+ <script>
+ angular.module('monthExample', [])
+ .controller('DateController', ['$scope', function($scope) {
+ $scope.example = {
+ value: new Date(2013, 9, 1)
+ };
+ }]);
+ </script>
+ <form name="myForm" ng-controller="DateController as dateCtrl">
+ <label for="exampleInput">Pick a month in 2013:</label>
+ <input id="exampleInput" type="month" name="input" ng-model="example.value"
+ placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
+ <div role="alert">
+ <span class="error" ng-show="myForm.input.$error.required">
+ Required!</span>
+ <span class="error" ng-show="myForm.input.$error.month">
+ Not a valid month!</span>
+ </div>
+ <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ var value = element(by.binding('example.value | date: "yyyy-MM"'));
+ var valid = element(by.binding('myForm.input.$valid'));
+ var input = element(by.model('example.value'));
+
+ // currently protractor/webdriver does not support
+ // sending keys to all known HTML5 input controls
+ // for various browsers (https://github.com/angular/protractor/issues/562).
+ function setInput(val) {
+ // set the value of the element and force validation.
+ var scr = "var ipt = document.getElementById('exampleInput'); " +
+ "ipt.value = '" + val + "';" +
+ "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
+ browser.executeScript(scr);
+ }
+
+ it('should initialize to model', function() {
+ expect(value.getText()).toContain('2013-10');
+ expect(valid.getText()).toContain('myForm.input.$valid = true');
+ });
+
+ it('should be invalid if empty', function() {
+ setInput('');
+ expect(value.getText()).toEqual('value =');
+ expect(valid.getText()).toContain('myForm.input.$valid = false');
+ });
+
+ it('should be invalid if over max', function() {
+ setInput('2015-01');
+ expect(value.getText()).toContain('');
+ expect(valid.getText()).toContain('myForm.input.$valid = false');
+ });
+ </file>
+ </example>
+ */
+ 'month': createDateInputType('month', MONTH_REGEXP,
+ createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
+ 'yyyy-MM'),
+
+ /**
+ * @ngdoc input
+ * @name input[number]
+ *
+ * @description
+ * Text input with number validation and transformation. Sets the `number` validation
+ * error if not a valid number.
+ *
+ * <div class="alert alert-warning">
+ * The model must always be of type `number` otherwise Angular will throw an error.
+ * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
+ * error docs for more information and an example of how to convert your model if necessary.
+ * </div>
+ *
+ * ## Issues with HTML5 constraint validation
+ *
+ * In browsers that follow the
+ * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
+ * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
+ * If a non-number is entered in the input, the browser will report the value as an empty string,
+ * which means the view / model values in `ngModel` and subsequently the scope value
+ * will also be an empty string.
+ *
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
+ * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
+ * minlength.
+ * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
+ * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
+ * any length.
+ * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
+ * that contains the regular expression body that will be converted to a regular expression
+ * as in the ngPattern directive.
+ * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
+ * a RegExp found by evaluating the Angular expression given in the attribute value.
+ * If the expression evaluates to a RegExp object, then this is used directly.
+ * If the expression evaluates to a string, then it will be converted to a RegExp
+ * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
+ * `new RegExp('^abc$')`.<br />
+ * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
+ * start at the index of the last search's match, thus not taking the whole input value into
+ * account.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <example name="number-input-directive" module="numberExample">
+ <file name="index.html">
+ <script>
+ angular.module('numberExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.example = {
+ value: 12
+ };
+ }]);
+ </script>
+ <form name="myForm" ng-controller="ExampleController">
+ <label>Number:
+ <input type="number" name="input" ng-model="example.value"
+ min="0" max="99" required>
+ </label>
+ <div role="alert">
+ <span class="error" ng-show="myForm.input.$error.required">
+ Required!</span>
+ <span class="error" ng-show="myForm.input.$error.number">
+ Not valid number!</span>
+ </div>
+ <tt>value = {{example.value}}</tt><br/>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ var value = element(by.binding('example.value'));
+ var valid = element(by.binding('myForm.input.$valid'));
+ var input = element(by.model('example.value'));
+
+ it('should initialize to model', function() {
+ expect(value.getText()).toContain('12');
+ expect(valid.getText()).toContain('true');
+ });
+
+ it('should be invalid if empty', function() {
+ input.clear();
+ input.sendKeys('');
+ expect(value.getText()).toEqual('value =');
+ expect(valid.getText()).toContain('false');
+ });
+
+ it('should be invalid if over max', function() {
+ input.clear();
+ input.sendKeys('123');
+ expect(value.getText()).toEqual('value =');
+ expect(valid.getText()).toContain('false');
+ });
+ </file>
+ </example>
+ */
+ 'number': numberInputType,
+
+
+ /**
+ * @ngdoc input
+ * @name input[url]
+ *
+ * @description
+ * Text input with URL validation. Sets the `url` validation error key if the content is not a
+ * valid URL.
+ *
+ * <div class="alert alert-warning">
+ * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
+ * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
+ * the built-in validators (see the {@link guide/forms Forms guide})
+ * </div>
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
+ * minlength.
+ * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
+ * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
+ * any length.
+ * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
+ * that contains the regular expression body that will be converted to a regular expression
+ * as in the ngPattern directive.
+ * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
+ * a RegExp found by evaluating the Angular expression given in the attribute value.
+ * If the expression evaluates to a RegExp object, then this is used directly.
+ * If the expression evaluates to a string, then it will be converted to a RegExp
+ * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
+ * `new RegExp('^abc$')`.<br />
+ * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
+ * start at the index of the last search's match, thus not taking the whole input value into
+ * account.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <example name="url-input-directive" module="urlExample">
+ <file name="index.html">
+ <script>
+ angular.module('urlExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.url = {
+ text: 'http://google.com'
+ };
+ }]);
+ </script>
+ <form name="myForm" ng-controller="ExampleController">
+ <label>URL:
+ <input type="url" name="input" ng-model="url.text" required>
+ <label>
+ <div role="alert">
+ <span class="error" ng-show="myForm.input.$error.required">
+ Required!</span>
+ <span class="error" ng-show="myForm.input.$error.url">
+ Not valid url!</span>
+ </div>
+ <tt>text = {{url.text}}</tt><br/>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ var text = element(by.binding('url.text'));
+ var valid = element(by.binding('myForm.input.$valid'));
+ var input = element(by.model('url.text'));
+
+ it('should initialize to model', function() {
+ expect(text.getText()).toContain('http://google.com');
+ expect(valid.getText()).toContain('true');
+ });
+
+ it('should be invalid if empty', function() {
+ input.clear();
+ input.sendKeys('');
+
+ expect(text.getText()).toEqual('text =');
+ expect(valid.getText()).toContain('false');
+ });
+
+ it('should be invalid if not url', function() {
+ input.clear();
+ input.sendKeys('box');
+
+ expect(valid.getText()).toContain('false');
+ });
+ </file>
+ </example>
+ */
+ 'url': urlInputType,
+
+
+ /**
+ * @ngdoc input
+ * @name input[email]
+ *
+ * @description
+ * Text input with email validation. Sets the `email` validation error key if not a valid email
+ * address.
+ *
+ * <div class="alert alert-warning">
+ * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
+ * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
+ * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
+ * </div>
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
+ * minlength.
+ * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
+ * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
+ * any length.
+ * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
+ * that contains the regular expression body that will be converted to a regular expression
+ * as in the ngPattern directive.
+ * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
+ * a RegExp found by evaluating the Angular expression given in the attribute value.
+ * If the expression evaluates to a RegExp object, then this is used directly.
+ * If the expression evaluates to a string, then it will be converted to a RegExp
+ * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
+ * `new RegExp('^abc$')`.<br />
+ * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
+ * start at the index of the last search's match, thus not taking the whole input value into
+ * account.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <example name="email-input-directive" module="emailExample">
+ <file name="index.html">
+ <script>
+ angular.module('emailExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.email = {
+ text: 'me@example.com'
+ };
+ }]);
+ </script>
+ <form name="myForm" ng-controller="ExampleController">
+ <label>Email:
+ <input type="email" name="input" ng-model="email.text" required>
+ </label>
+ <div role="alert">
+ <span class="error" ng-show="myForm.input.$error.required">
+ Required!</span>
+ <span class="error" ng-show="myForm.input.$error.email">
+ Not valid email!</span>
+ </div>
+ <tt>text = {{email.text}}</tt><br/>
+ <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
+ <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ var text = element(by.binding('email.text'));
+ var valid = element(by.binding('myForm.input.$valid'));
+ var input = element(by.model('email.text'));
+
+ it('should initialize to model', function() {
+ expect(text.getText()).toContain('me@example.com');
+ expect(valid.getText()).toContain('true');
+ });
+
+ it('should be invalid if empty', function() {
+ input.clear();
+ input.sendKeys('');
+ expect(text.getText()).toEqual('text =');
+ expect(valid.getText()).toContain('false');
+ });
+
+ it('should be invalid if not email', function() {
+ input.clear();
+ input.sendKeys('xxx');
+
+ expect(valid.getText()).toContain('false');
+ });
+ </file>
+ </example>
+ */
+ 'email': emailInputType,
+
+
+ /**
+ * @ngdoc input
+ * @name input[radio]
+ *
+ * @description
+ * HTML radio button.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string} value The value to which the `ngModel` expression should be set when selected.
+ * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
+ * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
+ * is selected. Should be used instead of the `value` attribute if you need
+ * a non-string `ngModel` (`boolean`, `array`, ...).
+ *
+ * @example
+ <example name="radio-input-directive" module="radioExample">
+ <file name="index.html">
+ <script>
+ angular.module('radioExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.color = {
+ name: 'blue'
+ };
+ $scope.specialValue = {
+ "id": "12345",
+ "value": "green"
+ };
+ }]);
+ </script>
+ <form name="myForm" ng-controller="ExampleController">
+ <label>
+ <input type="radio" ng-model="color.name" value="red">
+ Red
+ </label><br/>
+ <label>
+ <input type="radio" ng-model="color.name" ng-value="specialValue">
+ Green
+ </label><br/>
+ <label>
+ <input type="radio" ng-model="color.name" value="blue">
+ Blue
+ </label><br/>
+ <tt>color = {{color.name | json}}</tt><br/>
+ </form>
+ Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should change state', function() {
+ var color = element(by.binding('color.name'));
+
+ expect(color.getText()).toContain('blue');
+
+ element.all(by.model('color.name')).get(0).click();
+
+ expect(color.getText()).toContain('red');
+ });
+ </file>
+ </example>
+ */
+ 'radio': radioInputType,
+
+
+ /**
+ * @ngdoc input
+ * @name input[checkbox]
+ *
+ * @description
+ * HTML checkbox.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
+ * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ *
+ * @example
+ <example name="checkbox-input-directive" module="checkboxExample">
+ <file name="index.html">
+ <script>
+ angular.module('checkboxExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.checkboxModel = {
+ value1 : true,
+ value2 : 'YES'
+ };
+ }]);
+ </script>
+ <form name="myForm" ng-controller="ExampleController">
+ <label>Value1:
+ <input type="checkbox" ng-model="checkboxModel.value1">
+ </label><br/>
+ <label>Value2:
+ <input type="checkbox" ng-model="checkboxModel.value2"
+ ng-true-value="'YES'" ng-false-value="'NO'">
+ </label><br/>
+ <tt>value1 = {{checkboxModel.value1}}</tt><br/>
+ <tt>value2 = {{checkboxModel.value2}}</tt><br/>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should change state', function() {
+ var value1 = element(by.binding('checkboxModel.value1'));
+ var value2 = element(by.binding('checkboxModel.value2'));
+
+ expect(value1.getText()).toContain('true');
+ expect(value2.getText()).toContain('YES');
+
+ element(by.model('checkboxModel.value1')).click();
+ element(by.model('checkboxModel.value2')).click();
+
+ expect(value1.getText()).toContain('false');
+ expect(value2.getText()).toContain('NO');
+ });
+ </file>
+ </example>
+ */
+ 'checkbox': checkboxInputType,
+
+ 'hidden': noop,
+ 'button': noop,
+ 'submit': noop,
+ 'reset': noop,
+ 'file': noop
+};
+
+function stringBasedInputType(ctrl) {
+ ctrl.$formatters.push(function(value) {
+ return ctrl.$isEmpty(value) ? value : value.toString();
+ });
+}
+
+function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
+ baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
+ stringBasedInputType(ctrl);
+}
+
+function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
+ var type = lowercase(element[0].type);
+
+ // In composition mode, users are still inputing intermediate text buffer,
+ // hold the listener until composition is done.
+ // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
+ if (!$sniffer.android) {
+ var composing = false;
+
+ element.on('compositionstart', function(data) {
+ composing = true;
+ });
+
+ element.on('compositionend', function() {
+ composing = false;
+ listener();
+ });
+ }
+
+ var listener = function(ev) {
+ if (timeout) {
+ $browser.defer.cancel(timeout);
+ timeout = null;
+ }
+ if (composing) return;
+ var value = element.val(),
+ event = ev && ev.type;
+
+ // By default we will trim the value
+ // If the attribute ng-trim exists we will avoid trimming
+ // If input type is 'password', the value is never trimmed
+ if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
+ value = trim(value);
+ }
+
+ // If a control is suffering from bad input (due to native validators), browsers discard its
+ // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
+ // control's value is the same empty value twice in a row.
+ if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
+ ctrl.$setViewValue(value, event);
+ }
+ };
+
+ // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
+ // input event on backspace, delete or cut
+ if ($sniffer.hasEvent('input')) {
+ element.on('input', listener);
+ } else {
+ var timeout;
+
+ var deferListener = function(ev, input, origValue) {
+ if (!timeout) {
+ timeout = $browser.defer(function() {
+ timeout = null;
+ if (!input || input.value !== origValue) {
+ listener(ev);
+ }
+ });
+ }
+ };
+
+ element.on('keydown', function(event) {
+ var key = event.keyCode;
+
+ // ignore
+ // command modifiers arrows
+ if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
+
+ deferListener(event, this, this.value);
+ });
+
+ // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
+ if ($sniffer.hasEvent('paste')) {
+ element.on('paste cut', deferListener);
+ }
+ }
+
+ // if user paste into input using mouse on older browser
+ // or form autocomplete on newer browser, we need "change" event to catch it
+ element.on('change', listener);
+
+ ctrl.$render = function() {
+ // Workaround for Firefox validation #12102.
+ var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
+ if (element.val() !== value) {
+ element.val(value);
+ }
+ };
+}
+
+function weekParser(isoWeek, existingDate) {
+ if (isDate(isoWeek)) {
+ return isoWeek;
+ }
+
+ if (isString(isoWeek)) {
+ WEEK_REGEXP.lastIndex = 0;
+ var parts = WEEK_REGEXP.exec(isoWeek);
+ if (parts) {
+ var year = +parts[1],
+ week = +parts[2],
+ hours = 0,
+ minutes = 0,
+ seconds = 0,
+ milliseconds = 0,
+ firstThurs = getFirstThursdayOfYear(year),
+ addDays = (week - 1) * 7;
+
+ if (existingDate) {
+ hours = existingDate.getHours();
+ minutes = existingDate.getMinutes();
+ seconds = existingDate.getSeconds();
+ milliseconds = existingDate.getMilliseconds();
+ }
+
+ return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
+ }
+ }
+
+ return NaN;
+}
+
+function createDateParser(regexp, mapping) {
+ return function(iso, date) {
+ var parts, map;
+
+ if (isDate(iso)) {
+ return iso;
+ }
+
+ if (isString(iso)) {
+ // When a date is JSON'ified to wraps itself inside of an extra
+ // set of double quotes. This makes the date parsing code unable
+ // to match the date string and parse it as a date.
+ if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
+ iso = iso.substring(1, iso.length - 1);
+ }
+ if (ISO_DATE_REGEXP.test(iso)) {
+ return new Date(iso);
+ }
+ regexp.lastIndex = 0;
+ parts = regexp.exec(iso);
+
+ if (parts) {
+ parts.shift();
+ if (date) {
+ map = {
+ yyyy: date.getFullYear(),
+ MM: date.getMonth() + 1,
+ dd: date.getDate(),
+ HH: date.getHours(),
+ mm: date.getMinutes(),
+ ss: date.getSeconds(),
+ sss: date.getMilliseconds() / 1000
+ };
+ } else {
+ map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
+ }
+
+ forEach(parts, function(part, index) {
+ if (index < mapping.length) {
+ map[mapping[index]] = +part;
+ }
+ });
+ return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
+ }
+ }
+
+ return NaN;
+ };
+}
+
+function createDateInputType(type, regexp, parseDate, format) {
+ return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
+ badInputChecker(scope, element, attr, ctrl);
+ baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
+ var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
+ var previousDate;
+
+ ctrl.$$parserName = type;
+ ctrl.$parsers.push(function(value) {
+ if (ctrl.$isEmpty(value)) return null;
+ if (regexp.test(value)) {
+ // Note: We cannot read ctrl.$modelValue, as there might be a different
+ // parser/formatter in the processing chain so that the model
+ // contains some different data format!
+ var parsedDate = parseDate(value, previousDate);
+ if (timezone) {
+ parsedDate = convertTimezoneToLocal(parsedDate, timezone);
+ }
+ return parsedDate;
+ }
+ return undefined;
+ });
+
+ ctrl.$formatters.push(function(value) {
+ if (value && !isDate(value)) {
+ throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
+ }
+ if (isValidDate(value)) {
+ previousDate = value;
+ if (previousDate && timezone) {
+ previousDate = convertTimezoneToLocal(previousDate, timezone, true);
+ }
+ return $filter('date')(value, format, timezone);
+ } else {
+ previousDate = null;
+ return '';
+ }
+ });
+
+ if (isDefined(attr.min) || attr.ngMin) {
+ var minVal;
+ ctrl.$validators.min = function(value) {
+ return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
+ };
+ attr.$observe('min', function(val) {
+ minVal = parseObservedDateValue(val);
+ ctrl.$validate();
+ });
+ }
+
+ if (isDefined(attr.max) || attr.ngMax) {
+ var maxVal;
+ ctrl.$validators.max = function(value) {
+ return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
+ };
+ attr.$observe('max', function(val) {
+ maxVal = parseObservedDateValue(val);
+ ctrl.$validate();
+ });
+ }
+
+ function isValidDate(value) {
+ // Invalid Date: getTime() returns NaN
+ return value && !(value.getTime && value.getTime() !== value.getTime());
+ }
+
+ function parseObservedDateValue(val) {
+ return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
+ }
+ };
+}
+
+function badInputChecker(scope, element, attr, ctrl) {
+ var node = element[0];
+ var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
+ if (nativeValidation) {
+ ctrl.$parsers.push(function(value) {
+ var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
+ // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
+ // - also sets validity.badInput (should only be validity.typeMismatch).
+ // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
+ // - can ignore this case as we can still read out the erroneous email...
+ return validity.badInput && !validity.typeMismatch ? undefined : value;
+ });
+ }
+}
+
+function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
+ badInputChecker(scope, element, attr, ctrl);
+ baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
+
+ ctrl.$$parserName = 'number';
+ ctrl.$parsers.push(function(value) {
+ if (ctrl.$isEmpty(value)) return null;
+ if (NUMBER_REGEXP.test(value)) return parseFloat(value);
+ return undefined;
+ });
+
+ ctrl.$formatters.push(function(value) {
+ if (!ctrl.$isEmpty(value)) {
+ if (!isNumber(value)) {
+ throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
+ }
+ value = value.toString();
+ }
+ return value;
+ });
+
+ if (isDefined(attr.min) || attr.ngMin) {
+ var minVal;
+ ctrl.$validators.min = function(value) {
+ return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
+ };
+
+ attr.$observe('min', function(val) {
+ if (isDefined(val) && !isNumber(val)) {
+ val = parseFloat(val, 10);
+ }
+ minVal = isNumber(val) && !isNaN(val) ? val : undefined;
+ // TODO(matsko): implement validateLater to reduce number of validations
+ ctrl.$validate();
+ });
+ }
+
+ if (isDefined(attr.max) || attr.ngMax) {
+ var maxVal;
+ ctrl.$validators.max = function(value) {
+ return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
+ };
+
+ attr.$observe('max', function(val) {
+ if (isDefined(val) && !isNumber(val)) {
+ val = parseFloat(val, 10);
+ }
+ maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
+ // TODO(matsko): implement validateLater to reduce number of validations
+ ctrl.$validate();
+ });
+ }
+}
+
+function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
+ // Note: no badInputChecker here by purpose as `url` is only a validation
+ // in browsers, i.e. we can always read out input.value even if it is not valid!
+ baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
+ stringBasedInputType(ctrl);
+
+ ctrl.$$parserName = 'url';
+ ctrl.$validators.url = function(modelValue, viewValue) {
+ var value = modelValue || viewValue;
+ return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
+ };
+}
+
+function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
+ // Note: no badInputChecker here by purpose as `url` is only a validation
+ // in browsers, i.e. we can always read out input.value even if it is not valid!
+ baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
+ stringBasedInputType(ctrl);
+
+ ctrl.$$parserName = 'email';
+ ctrl.$validators.email = function(modelValue, viewValue) {
+ var value = modelValue || viewValue;
+ return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
+ };
+}
+
+function radioInputType(scope, element, attr, ctrl) {
+ // make the name unique, if not defined
+ if (isUndefined(attr.name)) {
+ element.attr('name', nextUid());
+ }
+
+ var listener = function(ev) {
+ if (element[0].checked) {
+ ctrl.$setViewValue(attr.value, ev && ev.type);
+ }
+ };
+
+ element.on('click', listener);
+
+ ctrl.$render = function() {
+ var value = attr.value;
+ element[0].checked = (value == ctrl.$viewValue);
+ };
+
+ attr.$observe('value', ctrl.$render);
+}
+
+function parseConstantExpr($parse, context, name, expression, fallback) {
+ var parseFn;
+ if (isDefined(expression)) {
+ parseFn = $parse(expression);
+ if (!parseFn.constant) {
+ throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
+ '`{1}`.', name, expression);
+ }
+ return parseFn(context);
+ }
+ return fallback;
+}
+
+function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
+ var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
+ var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
+
+ var listener = function(ev) {
+ ctrl.$setViewValue(element[0].checked, ev && ev.type);
+ };
+
+ element.on('click', listener);
+
+ ctrl.$render = function() {
+ element[0].checked = ctrl.$viewValue;
+ };
+
+ // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
+ // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
+ // it to a boolean.
+ ctrl.$isEmpty = function(value) {
+ return value === false;
+ };
+
+ ctrl.$formatters.push(function(value) {
+ return equals(value, trueValue);
+ });
+
+ ctrl.$parsers.push(function(value) {
+ return value ? trueValue : falseValue;
+ });
+}
+
+
+/**
+ * @ngdoc directive
+ * @name textarea
+ * @restrict E
+ *
+ * @description
+ * HTML textarea element control with angular data-binding. The data-binding and validation
+ * properties of this element are exactly the same as those of the
+ * {@link ng.directive:input input element}.
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
+ * minlength.
+ * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
+ * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
+ * length.
+ * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
+ * a RegExp found by evaluating the Angular expression given in the attribute value.
+ * If the expression evaluates to a RegExp object, then this is used directly.
+ * If the expression evaluates to a string, then it will be converted to a RegExp
+ * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
+ * `new RegExp('^abc$')`.<br />
+ * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
+ * start at the index of the last search's match, thus not taking the whole input value into
+ * account.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name input
+ * @restrict E
+ *
+ * @description
+ * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
+ * input state control, and validation.
+ * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
+ *
+ * <div class="alert alert-warning">
+ * **Note:** Not every feature offered is available for all input types.
+ * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
+ * </div>
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {boolean=} ngRequired Sets `required` attribute if set to true
+ * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
+ * minlength.
+ * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
+ * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
+ * length.
+ * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
+ * a RegExp found by evaluating the Angular expression given in the attribute value.
+ * If the expression evaluates to a RegExp object, then this is used directly.
+ * If the expression evaluates to a string, then it will be converted to a RegExp
+ * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
+ * `new RegExp('^abc$')`.<br />
+ * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
+ * start at the index of the last search's match, thus not taking the whole input value into
+ * account.
+ * @param {string=} ngChange Angular expression to be executed when input changes due to user
+ * interaction with the input element.
+ * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
+ * This parameter is ignored for input[type=password] controls, which will never trim the
+ * input.
+ *
+ * @example
+ <example name="input-directive" module="inputExample">
+ <file name="index.html">
+ <script>
+ angular.module('inputExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.user = {name: 'guest', last: 'visitor'};
+ }]);
+ </script>
+ <div ng-controller="ExampleController">
+ <form name="myForm">
+ <label>
+ User name:
+ <input type="text" name="userName" ng-model="user.name" required>
+ </label>
+ <div role="alert">
+ <span class="error" ng-show="myForm.userName.$error.required">
+ Required!</span>
+ </div>
+ <label>
+ Last name:
+ <input type="text" name="lastName" ng-model="user.last"
+ ng-minlength="3" ng-maxlength="10">
+ </label>
+ <div role="alert">
+ <span class="error" ng-show="myForm.lastName.$error.minlength">
+ Too short!</span>
+ <span class="error" ng-show="myForm.lastName.$error.maxlength">
+ Too long!</span>
+ </div>
+ </form>
+ <hr>
+ <tt>user = {{user}}</tt><br/>
+ <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
+ <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
+ <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
+ <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
+ <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
+ <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
+ </div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ var user = element(by.exactBinding('user'));
+ var userNameValid = element(by.binding('myForm.userName.$valid'));
+ var lastNameValid = element(by.binding('myForm.lastName.$valid'));
+ var lastNameError = element(by.binding('myForm.lastName.$error'));
+ var formValid = element(by.binding('myForm.$valid'));
+ var userNameInput = element(by.model('user.name'));
+ var userLastInput = element(by.model('user.last'));
+
+ it('should initialize to model', function() {
+ expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
+ expect(userNameValid.getText()).toContain('true');
+ expect(formValid.getText()).toContain('true');
+ });
+
+ it('should be invalid if empty when required', function() {
+ userNameInput.clear();
+ userNameInput.sendKeys('');
+
+ expect(user.getText()).toContain('{"last":"visitor"}');
+ expect(userNameValid.getText()).toContain('false');
+ expect(formValid.getText()).toContain('false');
+ });
+
+ it('should be valid if empty when min length is set', function() {
+ userLastInput.clear();
+ userLastInput.sendKeys('');
+
+ expect(user.getText()).toContain('{"name":"guest","last":""}');
+ expect(lastNameValid.getText()).toContain('true');
+ expect(formValid.getText()).toContain('true');
+ });
+
+ it('should be invalid if less than required min length', function() {
+ userLastInput.clear();
+ userLastInput.sendKeys('xx');
+
+ expect(user.getText()).toContain('{"name":"guest"}');
+ expect(lastNameValid.getText()).toContain('false');
+ expect(lastNameError.getText()).toContain('minlength');
+ expect(formValid.getText()).toContain('false');
+ });
+
+ it('should be invalid if longer than max length', function() {
+ userLastInput.clear();
+ userLastInput.sendKeys('some ridiculously long name');
+
+ expect(user.getText()).toContain('{"name":"guest"}');
+ expect(lastNameValid.getText()).toContain('false');
+ expect(lastNameError.getText()).toContain('maxlength');
+ expect(formValid.getText()).toContain('false');
+ });
+ </file>
+ </example>
+ */
+var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
+ function($browser, $sniffer, $filter, $parse) {
+ return {
+ restrict: 'E',
+ require: ['?ngModel'],
+ link: {
+ pre: function(scope, element, attr, ctrls) {
+ if (ctrls[0]) {
+ (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
+ $browser, $filter, $parse);
+ }
+ }
+ }
+ };
+}];
+
+
+
+var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
+/**
+ * @ngdoc directive
+ * @name ngValue
+ *
+ * @description
+ * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
+ * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
+ * the bound value.
+ *
+ * `ngValue` is useful when dynamically generating lists of radio buttons using
+ * {@link ngRepeat `ngRepeat`}, as shown below.
+ *
+ * Likewise, `ngValue` can be used to generate `<option>` elements for
+ * the {@link select `select`} element. In that case however, only strings are supported
+ * for the `value `attribute, so the resulting `ngModel` will always be a string.
+ * Support for `select` models with non-string values is available via `ngOptions`.
+ *
+ * @element input
+ * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
+ * of the `input` element
+ *
+ * @example
+ <example name="ngValue-directive" module="valueExample">
+ <file name="index.html">
+ <script>
+ angular.module('valueExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.names = ['pizza', 'unicorns', 'robots'];
+ $scope.my = { favorite: 'unicorns' };
+ }]);
+ </script>
+ <form ng-controller="ExampleController">
+ <h2>Which is your favorite?</h2>
+ <label ng-repeat="name in names" for="{{name}}">
+ {{name}}
+ <input type="radio"
+ ng-model="my.favorite"
+ ng-value="name"
+ id="{{name}}"
+ name="favorite">
+ </label>
+ <div>You chose {{my.favorite}}</div>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ var favorite = element(by.binding('my.favorite'));
+
+ it('should initialize to model', function() {
+ expect(favorite.getText()).toContain('unicorns');
+ });
+ it('should bind the values to the inputs', function() {
+ element.all(by.model('my.favorite')).get(0).click();
+ expect(favorite.getText()).toContain('pizza');
+ });
+ </file>
+ </example>
+ */
+var ngValueDirective = function() {
+ return {
+ restrict: 'A',
+ priority: 100,
+ compile: function(tpl, tplAttr) {
+ if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
+ return function ngValueConstantLink(scope, elm, attr) {
+ attr.$set('value', scope.$eval(attr.ngValue));
+ };
+ } else {
+ return function ngValueLink(scope, elm, attr) {
+ scope.$watch(attr.ngValue, function valueWatchAction(value) {
+ attr.$set('value', value);
+ });
+ };
+ }
+ }
+ };
+};
+
+/**
+ * @ngdoc directive
+ * @name ngBind
+ * @restrict AC
+ *
+ * @description
+ * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
+ * with the value of a given expression, and to update the text content when the value of that
+ * expression changes.
+ *
+ * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
+ * `{{ expression }}` which is similar but less verbose.
+ *
+ * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
+ * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
+ * element attribute, it makes the bindings invisible to the user while the page is loading.
+ *
+ * An alternative solution to this problem would be using the
+ * {@link ng.directive:ngCloak ngCloak} directive.
+ *
+ *
+ * @element ANY
+ * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
+ *
+ * @example
+ * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
+ <example module="bindExample">
+ <file name="index.html">
+ <script>
+ angular.module('bindExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.name = 'Whirled';
+ }]);
+ </script>
+ <div ng-controller="ExampleController">
+ <label>Enter name: <input type="text" ng-model="name"></label><br>
+ Hello <span ng-bind="name"></span>!
+ </div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should check ng-bind', function() {
+ var nameInput = element(by.model('name'));
+
+ expect(element(by.binding('name')).getText()).toBe('Whirled');
+ nameInput.clear();
+ nameInput.sendKeys('world');
+ expect(element(by.binding('name')).getText()).toBe('world');
+ });
+ </file>
+ </example>
+ */
+var ngBindDirective = ['$compile', function($compile) {
+ return {
+ restrict: 'AC',
+ compile: function ngBindCompile(templateElement) {
+ $compile.$$addBindingClass(templateElement);
+ return function ngBindLink(scope, element, attr) {
+ $compile.$$addBindingInfo(element, attr.ngBind);
+ element = element[0];
+ scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
+ element.textContent = isUndefined(value) ? '' : value;
+ });
+ };
+ }
+ };
+}];
+
+
+/**
+ * @ngdoc directive
+ * @name ngBindTemplate
+ *
+ * @description
+ * The `ngBindTemplate` directive specifies that the element
+ * text content should be replaced with the interpolation of the template
+ * in the `ngBindTemplate` attribute.
+ * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
+ * expressions. This directive is needed since some HTML elements
+ * (such as TITLE and OPTION) cannot contain SPAN elements.
+ *
+ * @element ANY
+ * @param {string} ngBindTemplate template of form
+ * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
+ *
+ * @example
+ * Try it here: enter text in text box and watch the greeting change.
+ <example module="bindExample">
+ <file name="index.html">
+ <script>
+ angular.module('bindExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.salutation = 'Hello';
+ $scope.name = 'World';
+ }]);
+ </script>
+ <div ng-controller="ExampleController">
+ <label>Salutation: <input type="text" ng-model="salutation"></label><br>
+ <label>Name: <input type="text" ng-model="name"></label><br>
+ <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
+ </div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should check ng-bind', function() {
+ var salutationElem = element(by.binding('salutation'));
+ var salutationInput = element(by.model('salutation'));
+ var nameInput = element(by.model('name'));
+
+ expect(salutationElem.getText()).toBe('Hello World!');
+
+ salutationInput.clear();
+ salutationInput.sendKeys('Greetings');
+ nameInput.clear();
+ nameInput.sendKeys('user');
+
+ expect(salutationElem.getText()).toBe('Greetings user!');
+ });
+ </file>
+ </example>
+ */
+var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
+ return {
+ compile: function ngBindTemplateCompile(templateElement) {
+ $compile.$$addBindingClass(templateElement);
+ return function ngBindTemplateLink(scope, element, attr) {
+ var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
+ $compile.$$addBindingInfo(element, interpolateFn.expressions);
+ element = element[0];
+ attr.$observe('ngBindTemplate', function(value) {
+ element.textContent = isUndefined(value) ? '' : value;
+ });
+ };
+ }
+ };
+}];
+
+
+/**
+ * @ngdoc directive
+ * @name ngBindHtml
+ *
+ * @description
+ * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
+ * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
+ * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
+ * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
+ * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
+ *
+ * You may also bypass sanitization for values you know are safe. To do so, bind to
+ * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
+ * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
+ *
+ * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
+ * will have an exception (instead of an exploit.)
+ *
+ * @element ANY
+ * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
+ *
+ * @example
+
+ <example module="bindHtmlExample" deps="angular-sanitize.js">
+ <file name="index.html">
+ <div ng-controller="ExampleController">
+ <p ng-bind-html="myHTML"></p>
+ </div>
+ </file>
+
+ <file name="script.js">
+ angular.module('bindHtmlExample', ['ngSanitize'])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.myHTML =
+ 'I am an <code>HTML</code>string with ' +
+ '<a href="#">links!</a> and other <em>stuff</em>';
+ }]);
+ </file>
+
+ <file name="protractor.js" type="protractor">
+ it('should check ng-bind-html', function() {
+ expect(element(by.binding('myHTML')).getText()).toBe(
+ 'I am an HTMLstring with links! and other stuff');
+ });
+ </file>
+ </example>
+ */
+var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
+ return {
+ restrict: 'A',
+ compile: function ngBindHtmlCompile(tElement, tAttrs) {
+ var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
+ var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
+ return (value || '').toString();
+ });
+ $compile.$$addBindingClass(tElement);
+
+ return function ngBindHtmlLink(scope, element, attr) {
+ $compile.$$addBindingInfo(element, attr.ngBindHtml);
+
+ scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
+ // we re-evaluate the expr because we want a TrustedValueHolderType
+ // for $sce, not a string
+ element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
+ });
+ };
+ }
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ngChange
+ *
+ * @description
+ * Evaluate the given expression when the user changes the input.
+ * The expression is evaluated immediately, unlike the JavaScript onchange event
+ * which only triggers at the end of a change (usually, when the user leaves the
+ * form element or presses the return key).
+ *
+ * The `ngChange` expression is only evaluated when a change in the input value causes
+ * a new value to be committed to the model.
+ *
+ * It will not be evaluated:
+ * * if the value returned from the `$parsers` transformation pipeline has not changed
+ * * if the input has continued to be invalid since the model will stay `null`
+ * * if the model is changed programmatically and not by a change to the input value
+ *
+ *
+ * Note, this directive requires `ngModel` to be present.
+ *
+ * @element input
+ * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
+ * in input value.
+ *
+ * @example
+ * <example name="ngChange-directive" module="changeExample">
+ * <file name="index.html">
+ * <script>
+ * angular.module('changeExample', [])
+ * .controller('ExampleController', ['$scope', function($scope) {
+ * $scope.counter = 0;
+ * $scope.change = function() {
+ * $scope.counter++;
+ * };
+ * }]);
+ * </script>
+ * <div ng-controller="ExampleController">
+ * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
+ * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
+ * <label for="ng-change-example2">Confirmed</label><br />
+ * <tt>debug = {{confirmed}}</tt><br/>
+ * <tt>counter = {{counter}}</tt><br/>
+ * </div>
+ * </file>
+ * <file name="protractor.js" type="protractor">
+ * var counter = element(by.binding('counter'));
+ * var debug = element(by.binding('confirmed'));
+ *
+ * it('should evaluate the expression if changing from view', function() {
+ * expect(counter.getText()).toContain('0');
+ *
+ * element(by.id('ng-change-example1')).click();
+ *
+ * expect(counter.getText()).toContain('1');
+ * expect(debug.getText()).toContain('true');
+ * });
+ *
+ * it('should not evaluate the expression if changing from model', function() {
+ * element(by.id('ng-change-example2')).click();
+
+ * expect(counter.getText()).toContain('0');
+ * expect(debug.getText()).toContain('true');
+ * });
+ * </file>
+ * </example>
+ */
+var ngChangeDirective = valueFn({
+ restrict: 'A',
+ require: 'ngModel',
+ link: function(scope, element, attr, ctrl) {
+ ctrl.$viewChangeListeners.push(function() {
+ scope.$eval(attr.ngChange);
+ });
+ }
+});
+
+function classDirective(name, selector) {
+ name = 'ngClass' + name;
+ return ['$animate', function($animate) {
+ return {
+ restrict: 'AC',
+ link: function(scope, element, attr) {
+ var oldVal;
+
+ scope.$watch(attr[name], ngClassWatchAction, true);
+
+ attr.$observe('class', function(value) {
+ ngClassWatchAction(scope.$eval(attr[name]));
+ });
+
+
+ if (name !== 'ngClass') {
+ scope.$watch('$index', function($index, old$index) {
+ // jshint bitwise: false
+ var mod = $index & 1;
+ if (mod !== (old$index & 1)) {
+ var classes = arrayClasses(scope.$eval(attr[name]));
+ mod === selector ?
+ addClasses(classes) :
+ removeClasses(classes);
+ }
+ });
+ }
+
+ function addClasses(classes) {
+ var newClasses = digestClassCounts(classes, 1);
+ attr.$addClass(newClasses);
+ }
+
+ function removeClasses(classes) {
+ var newClasses = digestClassCounts(classes, -1);
+ attr.$removeClass(newClasses);
+ }
+
+ function digestClassCounts(classes, count) {
+ // Use createMap() to prevent class assumptions involving property
+ // names in Object.prototype
+ var classCounts = element.data('$classCounts') || createMap();
+ var classesToUpdate = [];
+ forEach(classes, function(className) {
+ if (count > 0 || classCounts[className]) {
+ classCounts[className] = (classCounts[className] || 0) + count;
+ if (classCounts[className] === +(count > 0)) {
+ classesToUpdate.push(className);
+ }
+ }
+ });
+ element.data('$classCounts', classCounts);
+ return classesToUpdate.join(' ');
+ }
+
+ function updateClasses(oldClasses, newClasses) {
+ var toAdd = arrayDifference(newClasses, oldClasses);
+ var toRemove = arrayDifference(oldClasses, newClasses);
+ toAdd = digestClassCounts(toAdd, 1);
+ toRemove = digestClassCounts(toRemove, -1);
+ if (toAdd && toAdd.length) {
+ $animate.addClass(element, toAdd);
+ }
+ if (toRemove && toRemove.length) {
+ $animate.removeClass(element, toRemove);
+ }
+ }
+
+ function ngClassWatchAction(newVal) {
+ if (selector === true || scope.$index % 2 === selector) {
+ var newClasses = arrayClasses(newVal || []);
+ if (!oldVal) {
+ addClasses(newClasses);
+ } else if (!equals(newVal,oldVal)) {
+ var oldClasses = arrayClasses(oldVal);
+ updateClasses(oldClasses, newClasses);
+ }
+ }
+ oldVal = shallowCopy(newVal);
+ }
+ }
+ };
+
+ function arrayDifference(tokens1, tokens2) {
+ var values = [];
+
+ outer:
+ for (var i = 0; i < tokens1.length; i++) {
+ var token = tokens1[i];
+ for (var j = 0; j < tokens2.length; j++) {
+ if (token == tokens2[j]) continue outer;
+ }
+ values.push(token);
+ }
+ return values;
+ }
+
+ function arrayClasses(classVal) {
+ var classes = [];
+ if (isArray(classVal)) {
+ forEach(classVal, function(v) {
+ classes = classes.concat(arrayClasses(v));
+ });
+ return classes;
+ } else if (isString(classVal)) {
+ return classVal.split(' ');
+ } else if (isObject(classVal)) {
+ forEach(classVal, function(v, k) {
+ if (v) {
+ classes = classes.concat(k.split(' '));
+ }
+ });
+ return classes;
+ }
+ return classVal;
+ }
+ }];
+}
+
+/**
+ * @ngdoc directive
+ * @name ngClass
+ * @restrict AC
+ *
+ * @description
+ * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
+ * an expression that represents all classes to be added.
+ *
+ * The directive operates in three different ways, depending on which of three types the expression
+ * evaluates to:
+ *
+ * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
+ * names.
+ *
+ * 2. If the expression evaluates to an object, then for each key-value pair of the
+ * object with a truthy value the corresponding key is used as a class name.
+ *
+ * 3. If the expression evaluates to an array, each element of the array should either be a string as in
+ * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
+ * to give you more control over what CSS classes appear. See the code below for an example of this.
+ *
+ *
+ * The directive won't add duplicate classes if a particular class was already set.
+ *
+ * When the expression changes, the previously added classes are removed and only then are the
+ * new classes added.
+ *
+ * @animations
+ * **add** - happens just before the class is applied to the elements
+ *
+ * **remove** - happens just before the class is removed from the element
+ *
+ * @element ANY
+ * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
+ * of the evaluation can be a string representing space delimited class
+ * names, an array, or a map of class names to boolean values. In the case of a map, the
+ * names of the properties whose values are truthy will be added as css classes to the
+ * element.
+ *
+ * @example Example that demonstrates basic bindings via ngClass directive.
+ <example>
+ <file name="index.html">
+ <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
+ <label>
+ <input type="checkbox" ng-model="deleted">
+ deleted (apply "strike" class)
+ </label><br>
+ <label>
+ <input type="checkbox" ng-model="important">
+ important (apply "bold" class)
+ </label><br>
+ <label>
+ <input type="checkbox" ng-model="error">
+ error (apply "has-error" class)
+ </label>
+ <hr>
+ <p ng-class="style">Using String Syntax</p>
+ <input type="text" ng-model="style"
+ placeholder="Type: bold strike red" aria-label="Type: bold strike red">
+ <hr>
+ <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
+ <input ng-model="style1"
+ placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
+ <input ng-model="style2"
+ placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
+ <input ng-model="style3"
+ placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
+ <hr>
+ <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
+ <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
+ <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
+ </file>
+ <file name="style.css">
+ .strike {
+ text-decoration: line-through;
+ }
+ .bold {
+ font-weight: bold;
+ }
+ .red {
+ color: red;
+ }
+ .has-error {
+ color: red;
+ background-color: yellow;
+ }
+ .orange {
+ color: orange;
+ }
+ </file>
+ <file name="protractor.js" type="protractor">
+ var ps = element.all(by.css('p'));
+
+ it('should let you toggle the class', function() {
+
+ expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
+ expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
+
+ element(by.model('important')).click();
+ expect(ps.first().getAttribute('class')).toMatch(/bold/);
+
+ element(by.model('error')).click();
+ expect(ps.first().getAttribute('class')).toMatch(/has-error/);
+ });
+
+ it('should let you toggle string example', function() {
+ expect(ps.get(1).getAttribute('class')).toBe('');
+ element(by.model('style')).clear();
+ element(by.model('style')).sendKeys('red');
+ expect(ps.get(1).getAttribute('class')).toBe('red');
+ });
+
+ it('array example should have 3 classes', function() {
+ expect(ps.get(2).getAttribute('class')).toBe('');
+ element(by.model('style1')).sendKeys('bold');
+ element(by.model('style2')).sendKeys('strike');
+ element(by.model('style3')).sendKeys('red');
+ expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
+ });
+
+ it('array with map example should have 2 classes', function() {
+ expect(ps.last().getAttribute('class')).toBe('');
+ element(by.model('style4')).sendKeys('bold');
+ element(by.model('warning')).click();
+ expect(ps.last().getAttribute('class')).toBe('bold orange');
+ });
+ </file>
+ </example>
+
+ ## Animations
+
+ The example below demonstrates how to perform animations using ngClass.
+
+ <example module="ngAnimate" deps="angular-animate.js" animations="true">
+ <file name="index.html">
+ <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
+ <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
+ <br>
+ <span class="base-class" ng-class="myVar">Sample Text</span>
+ </file>
+ <file name="style.css">
+ .base-class {
+ transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ }
+
+ .base-class.my-class {
+ color: red;
+ font-size:3em;
+ }
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should check ng-class', function() {
+ expect(element(by.css('.base-class')).getAttribute('class')).not.
+ toMatch(/my-class/);
+
+ element(by.id('setbtn')).click();
+
+ expect(element(by.css('.base-class')).getAttribute('class')).
+ toMatch(/my-class/);
+
+ element(by.id('clearbtn')).click();
+
+ expect(element(by.css('.base-class')).getAttribute('class')).not.
+ toMatch(/my-class/);
+ });
+ </file>
+ </example>
+
+
+ ## ngClass and pre-existing CSS3 Transitions/Animations
+ The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
+ Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
+ any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
+ to view the step by step details of {@link $animate#addClass $animate.addClass} and
+ {@link $animate#removeClass $animate.removeClass}.
+ */
+var ngClassDirective = classDirective('', true);
+
+/**
+ * @ngdoc directive
+ * @name ngClassOdd
+ * @restrict AC
+ *
+ * @description
+ * The `ngClassOdd` and `ngClassEven` directives work exactly as
+ * {@link ng.directive:ngClass ngClass}, except they work in
+ * conjunction with `ngRepeat` and take effect only on odd (even) rows.
+ *
+ * This directive can be applied only within the scope of an
+ * {@link ng.directive:ngRepeat ngRepeat}.
+ *
+ * @element ANY
+ * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
+ * of the evaluation can be a string representing space delimited class names or an array.
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
+ <li ng-repeat="name in names">
+ <span ng-class-odd="'odd'" ng-class-even="'even'">
+ {{name}}
+ </span>
+ </li>
+ </ol>
+ </file>
+ <file name="style.css">
+ .odd {
+ color: red;
+ }
+ .even {
+ color: blue;
+ }
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should check ng-class-odd and ng-class-even', function() {
+ expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
+ toMatch(/odd/);
+ expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
+ toMatch(/even/);
+ });
+ </file>
+ </example>
+ */
+var ngClassOddDirective = classDirective('Odd', 0);
+
+/**
+ * @ngdoc directive
+ * @name ngClassEven
+ * @restrict AC
+ *
+ * @description
+ * The `ngClassOdd` and `ngClassEven` directives work exactly as
+ * {@link ng.directive:ngClass ngClass}, except they work in
+ * conjunction with `ngRepeat` and take effect only on odd (even) rows.
+ *
+ * This directive can be applied only within the scope of an
+ * {@link ng.directive:ngRepeat ngRepeat}.
+ *
+ * @element ANY
+ * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
+ * result of the evaluation can be a string representing space delimited class names or an array.
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
+ <li ng-repeat="name in names">
+ <span ng-class-odd="'odd'" ng-class-even="'even'">
+ {{name}}
+ </span>
+ </li>
+ </ol>
+ </file>
+ <file name="style.css">
+ .odd {
+ color: red;
+ }
+ .even {
+ color: blue;
+ }
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should check ng-class-odd and ng-class-even', function() {
+ expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
+ toMatch(/odd/);
+ expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
+ toMatch(/even/);
+ });
+ </file>
+ </example>
+ */
+var ngClassEvenDirective = classDirective('Even', 1);
+
+/**
+ * @ngdoc directive
+ * @name ngCloak
+ * @restrict AC
+ *
+ * @description
+ * The `ngCloak` directive is used to prevent the Angular html template from being briefly
+ * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
+ * directive to avoid the undesirable flicker effect caused by the html template display.
+ *
+ * The directive can be applied to the `<body>` element, but the preferred usage is to apply
+ * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
+ * of the browser view.
+ *
+ * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
+ * `angular.min.js`.
+ * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
+ *
+ * ```css
+ * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
+ * display: none !important;
+ * }
+ * ```
+ *
+ * When this css rule is loaded by the browser, all html elements (including their children) that
+ * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
+ * during the compilation of the template it deletes the `ngCloak` element attribute, making
+ * the compiled element visible.
+ *
+ * For the best result, the `angular.js` script must be loaded in the head section of the html
+ * document; alternatively, the css rule above must be included in the external stylesheet of the
+ * application.
+ *
+ * @element ANY
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <div id="template1" ng-cloak>{{ 'hello' }}</div>
+ <div id="template2" class="ng-cloak">{{ 'world' }}</div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should remove the template directive and css class', function() {
+ expect($('#template1').getAttribute('ng-cloak')).
+ toBeNull();
+ expect($('#template2').getAttribute('ng-cloak')).
+ toBeNull();
+ });
+ </file>
+ </example>
+ *
+ */
+var ngCloakDirective = ngDirective({
+ compile: function(element, attr) {
+ attr.$set('ngCloak', undefined);
+ element.removeClass('ng-cloak');
+ }
+});
+
+/**
+ * @ngdoc directive
+ * @name ngController
+ *
+ * @description
+ * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
+ * supports the principles behind the Model-View-Controller design pattern.
+ *
+ * MVC components in angular:
+ *
+ * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
+ * are accessed through bindings.
+ * * View — The template (HTML with data bindings) that is rendered into the View.
+ * * Controller — The `ngController` directive specifies a Controller class; the class contains business
+ * logic behind the application to decorate the scope with functions and values
+ *
+ * Note that you can also attach controllers to the DOM by declaring it in a route definition
+ * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
+ * again using `ng-controller` in the template itself. This will cause the controller to be attached
+ * and executed twice.
+ *
+ * @element ANY
+ * @scope
+ * @priority 500
+ * @param {expression} ngController Name of a constructor function registered with the current
+ * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
+ * that on the current scope evaluates to a constructor function.
+ *
+ * The controller instance can be published into a scope property by specifying
+ * `ng-controller="as propertyName"`.
+ *
+ * If the current `$controllerProvider` is configured to use globals (via
+ * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
+ * also be the name of a globally accessible constructor function (not recommended).
+ *
+ * @example
+ * Here is a simple form for editing user contact information. Adding, removing, clearing, and
+ * greeting are methods declared on the controller (see source tab). These methods can
+ * easily be called from the angular markup. Any changes to the data are automatically reflected
+ * in the View without the need for a manual update.
+ *
+ * Two different declaration styles are included below:
+ *
+ * * one binds methods and properties directly onto the controller using `this`:
+ * `ng-controller="SettingsController1 as settings"`
+ * * one injects `$scope` into the controller:
+ * `ng-controller="SettingsController2"`
+ *
+ * The second option is more common in the Angular community, and is generally used in boilerplates
+ * and in this guide. However, there are advantages to binding properties directly to the controller
+ * and avoiding scope.
+ *
+ * * Using `controller as` makes it obvious which controller you are accessing in the template when
+ * multiple controllers apply to an element.
+ * * If you are writing your controllers as classes you have easier access to the properties and
+ * methods, which will appear on the scope, from inside the controller code.
+ * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
+ * inheritance masking primitives.
+ *
+ * This example demonstrates the `controller as` syntax.
+ *
+ * <example name="ngControllerAs" module="controllerAsExample">
+ * <file name="index.html">
+ * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
+ * <label>Name: <input type="text" ng-model="settings.name"/></label>
+ * <button ng-click="settings.greet()">greet</button><br/>
+ * Contact:
+ * <ul>
+ * <li ng-repeat="contact in settings.contacts">
+ * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
+ * <option>phone</option>
+ * <option>email</option>
+ * </select>
+ * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
+ * <button ng-click="settings.clearContact(contact)">clear</button>
+ * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
+ * </li>
+ * <li><button ng-click="settings.addContact()">add</button></li>
+ * </ul>
+ * </div>
+ * </file>
+ * <file name="app.js">
+ * angular.module('controllerAsExample', [])
+ * .controller('SettingsController1', SettingsController1);
+ *
+ * function SettingsController1() {
+ * this.name = "John Smith";
+ * this.contacts = [
+ * {type: 'phone', value: '408 555 1212'},
+ * {type: 'email', value: 'john.smith@example.org'} ];
+ * }
+ *
+ * SettingsController1.prototype.greet = function() {
+ * alert(this.name);
+ * };
+ *
+ * SettingsController1.prototype.addContact = function() {
+ * this.contacts.push({type: 'email', value: 'yourname@example.org'});
+ * };
+ *
+ * SettingsController1.prototype.removeContact = function(contactToRemove) {
+ * var index = this.contacts.indexOf(contactToRemove);
+ * this.contacts.splice(index, 1);
+ * };
+ *
+ * SettingsController1.prototype.clearContact = function(contact) {
+ * contact.type = 'phone';
+ * contact.value = '';
+ * };
+ * </file>
+ * <file name="protractor.js" type="protractor">
+ * it('should check controller as', function() {
+ * var container = element(by.id('ctrl-as-exmpl'));
+ * expect(container.element(by.model('settings.name'))
+ * .getAttribute('value')).toBe('John Smith');
+ *
+ * var firstRepeat =
+ * container.element(by.repeater('contact in settings.contacts').row(0));
+ * var secondRepeat =
+ * container.element(by.repeater('contact in settings.contacts').row(1));
+ *
+ * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
+ * .toBe('408 555 1212');
+ *
+ * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
+ * .toBe('john.smith@example.org');
+ *
+ * firstRepeat.element(by.buttonText('clear')).click();
+ *
+ * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
+ * .toBe('');
+ *
+ * container.element(by.buttonText('add')).click();
+ *
+ * expect(container.element(by.repeater('contact in settings.contacts').row(2))
+ * .element(by.model('contact.value'))
+ * .getAttribute('value'))
+ * .toBe('yourname@example.org');
+ * });
+ * </file>
+ * </example>
+ *
+ * This example demonstrates the "attach to `$scope`" style of controller.
+ *
+ * <example name="ngController" module="controllerExample">
+ * <file name="index.html">
+ * <div id="ctrl-exmpl" ng-controller="SettingsController2">
+ * <label>Name: <input type="text" ng-model="name"/></label>
+ * <button ng-click="greet()">greet</button><br/>
+ * Contact:
+ * <ul>
+ * <li ng-repeat="contact in contacts">
+ * <select ng-model="contact.type" id="select_{{$index}}">
+ * <option>phone</option>
+ * <option>email</option>
+ * </select>
+ * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
+ * <button ng-click="clearContact(contact)">clear</button>
+ * <button ng-click="removeContact(contact)">X</button>
+ * </li>
+ * <li>[ <button ng-click="addContact()">add</button> ]</li>
+ * </ul>
+ * </div>
+ * </file>
+ * <file name="app.js">
+ * angular.module('controllerExample', [])
+ * .controller('SettingsController2', ['$scope', SettingsController2]);
+ *
+ * function SettingsController2($scope) {
+ * $scope.name = "John Smith";
+ * $scope.contacts = [
+ * {type:'phone', value:'408 555 1212'},
+ * {type:'email', value:'john.smith@example.org'} ];
+ *
+ * $scope.greet = function() {
+ * alert($scope.name);
+ * };
+ *
+ * $scope.addContact = function() {
+ * $scope.contacts.push({type:'email', value:'yourname@example.org'});
+ * };
+ *
+ * $scope.removeContact = function(contactToRemove) {
+ * var index = $scope.contacts.indexOf(contactToRemove);
+ * $scope.contacts.splice(index, 1);
+ * };
+ *
+ * $scope.clearContact = function(contact) {
+ * contact.type = 'phone';
+ * contact.value = '';
+ * };
+ * }
+ * </file>
+ * <file name="protractor.js" type="protractor">
+ * it('should check controller', function() {
+ * var container = element(by.id('ctrl-exmpl'));
+ *
+ * expect(container.element(by.model('name'))
+ * .getAttribute('value')).toBe('John Smith');
+ *
+ * var firstRepeat =
+ * container.element(by.repeater('contact in contacts').row(0));
+ * var secondRepeat =
+ * container.element(by.repeater('contact in contacts').row(1));
+ *
+ * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
+ * .toBe('408 555 1212');
+ * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
+ * .toBe('john.smith@example.org');
+ *
+ * firstRepeat.element(by.buttonText('clear')).click();
+ *
+ * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
+ * .toBe('');
+ *
+ * container.element(by.buttonText('add')).click();
+ *
+ * expect(container.element(by.repeater('contact in contacts').row(2))
+ * .element(by.model('contact.value'))
+ * .getAttribute('value'))
+ * .toBe('yourname@example.org');
+ * });
+ * </file>
+ *</example>
+
+ */
+var ngControllerDirective = [function() {
+ return {
+ restrict: 'A',
+ scope: true,
+ controller: '@',
+ priority: 500
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ngCsp
+ *
+ * @element html
+ * @description
+ *
+ * Angular has some features that can break certain
+ * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
+ *
+ * If you intend to implement these rules then you must tell Angular not to use these features.
+ *
+ * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
+ *
+ *
+ * The following rules affect Angular:
+ *
+ * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
+ * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
+ * increase in the speed of evaluating Angular expressions.
+ *
+ * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
+ * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
+ * To make these directives work when a CSP rule is blocking inline styles, you must link to the
+ * `angular-csp.css` in your HTML manually.
+ *
+ * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
+ * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
+ * however, triggers a CSP error to be logged in the console:
+ *
+ * ```
+ * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
+ * script in the following Content Security Policy directive: "default-src 'self'". Note that
+ * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
+ * ```
+ *
+ * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
+ * directive on an element of the HTML document that appears before the `<script>` tag that loads
+ * the `angular.js` file.
+ *
+ * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
+ *
+ * You can specify which of the CSP related Angular features should be deactivated by providing
+ * a value for the `ng-csp` attribute. The options are as follows:
+ *
+ * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
+ *
+ * * no-unsafe-eval: this stops Angular from optimising $parse with unsafe eval of strings
+ *
+ * You can use these values in the following combinations:
+ *
+ *
+ * * No declaration means that Angular will assume that you can do inline styles, but it will do
+ * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
+ * of Angular.
+ *
+ * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
+ * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
+ * of Angular.
+ *
+ * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
+ * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
+ *
+ * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
+ * run eval - no automcatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
+ *
+ * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
+ * styles nor use eval, which is the same as an empty: ng-csp.
+ * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
+ *
+ * @example
+ * This example shows how to apply the `ngCsp` directive to the `html` tag.
+ ```html
+ <!doctype html>
+ <html ng-app ng-csp>
+ ...
+ ...
+ </html>
+ ```
+ * @example
+ // Note: the suffix `.csp` in the example name triggers
+ // csp mode in our http server!
+ <example name="example.csp" module="cspExample" ng-csp="true">
+ <file name="index.html">
+ <div ng-controller="MainController as ctrl">
+ <div>
+ <button ng-click="ctrl.inc()" id="inc">Increment</button>
+ <span id="counter">
+ {{ctrl.counter}}
+ </span>
+ </div>
+
+ <div>
+ <button ng-click="ctrl.evil()" id="evil">Evil</button>
+ <span id="evilError">
+ {{ctrl.evilError}}
+ </span>
+ </div>
+ </div>
+ </file>
+ <file name="script.js">
+ angular.module('cspExample', [])
+ .controller('MainController', function() {
+ this.counter = 0;
+ this.inc = function() {
+ this.counter++;
+ };
+ this.evil = function() {
+ // jshint evil:true
+ try {
+ eval('1+2');
+ } catch (e) {
+ this.evilError = e.message;
+ }
+ };
+ });
+ </file>
+ <file name="protractor.js" type="protractor">
+ var util, webdriver;
+
+ var incBtn = element(by.id('inc'));
+ var counter = element(by.id('counter'));
+ var evilBtn = element(by.id('evil'));
+ var evilError = element(by.id('evilError'));
+
+ function getAndClearSevereErrors() {
+ return browser.manage().logs().get('browser').then(function(browserLog) {
+ return browserLog.filter(function(logEntry) {
+ return logEntry.level.value > webdriver.logging.Level.WARNING.value;
+ });
+ });
+ }
+
+ function clearErrors() {
+ getAndClearSevereErrors();
+ }
+
+ function expectNoErrors() {
+ getAndClearSevereErrors().then(function(filteredLog) {
+ expect(filteredLog.length).toEqual(0);
+ if (filteredLog.length) {
+ console.log('browser console errors: ' + util.inspect(filteredLog));
+ }
+ });
+ }
+
+ function expectError(regex) {
+ getAndClearSevereErrors().then(function(filteredLog) {
+ var found = false;
+ filteredLog.forEach(function(log) {
+ if (log.message.match(regex)) {
+ found = true;
+ }
+ });
+ if (!found) {
+ throw new Error('expected an error that matches ' + regex);
+ }
+ });
+ }
+
+ beforeEach(function() {
+ util = require('util');
+ webdriver = require('protractor/node_modules/selenium-webdriver');
+ });
+
+ // For now, we only test on Chrome,
+ // as Safari does not load the page with Protractor's injected scripts,
+ // and Firefox webdriver always disables content security policy (#6358)
+ if (browser.params.browser !== 'chrome') {
+ return;
+ }
+
+ it('should not report errors when the page is loaded', function() {
+ // clear errors so we are not dependent on previous tests
+ clearErrors();
+ // Need to reload the page as the page is already loaded when
+ // we come here
+ browser.driver.getCurrentUrl().then(function(url) {
+ browser.get(url);
+ });
+ expectNoErrors();
+ });
+
+ it('should evaluate expressions', function() {
+ expect(counter.getText()).toEqual('0');
+ incBtn.click();
+ expect(counter.getText()).toEqual('1');
+ expectNoErrors();
+ });
+
+ it('should throw and report an error when using "eval"', function() {
+ evilBtn.click();
+ expect(evilError.getText()).toMatch(/Content Security Policy/);
+ expectError(/Content Security Policy/);
+ });
+ </file>
+ </example>
+ */
+
+// ngCsp is not implemented as a proper directive any more, because we need it be processed while we
+// bootstrap the system (before $parse is instantiated), for this reason we just have
+// the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
+
+/**
+ * @ngdoc directive
+ * @name ngClick
+ *
+ * @description
+ * The ngClick directive allows you to specify custom behavior when
+ * an element is clicked.
+ *
+ * @element ANY
+ * @priority 0
+ * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
+ * click. ({@link guide/expression#-event- Event object is available as `$event`})
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <button ng-click="count = count + 1" ng-init="count=0">
+ Increment
+ </button>
+ <span>
+ count: {{count}}
+ </span>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should check ng-click', function() {
+ expect(element(by.binding('count')).getText()).toMatch('0');
+ element(by.css('button')).click();
+ expect(element(by.binding('count')).getText()).toMatch('1');
+ });
+ </file>
+ </example>
+ */
+/*
+ * A collection of directives that allows creation of custom event handlers that are defined as
+ * angular expressions and are compiled and executed within the current scope.
+ */
+var ngEventDirectives = {};
+
+// For events that might fire synchronously during DOM manipulation
+// we need to execute their event handlers asynchronously using $evalAsync,
+// so that they are not executed in an inconsistent state.
+var forceAsyncEvents = {
+ 'blur': true,
+ 'focus': true
+};
+forEach(
+ 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
+ function(eventName) {
+ var directiveName = directiveNormalize('ng-' + eventName);
+ ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
+ return {
+ restrict: 'A',
+ compile: function($element, attr) {
+ // We expose the powerful $event object on the scope that provides access to the Window,
+ // etc. that isn't protected by the fast paths in $parse. We explicitly request better
+ // checks at the cost of speed since event handler expressions are not executed as
+ // frequently as regular change detection.
+ var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
+ return function ngEventHandler(scope, element) {
+ element.on(eventName, function(event) {
+ var callback = function() {
+ fn(scope, {$event:event});
+ };
+ if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
+ scope.$evalAsync(callback);
+ } else {
+ scope.$apply(callback);
+ }
+ });
+ };
+ }
+ };
+ }];
+ }
+);
+
+/**
+ * @ngdoc directive
+ * @name ngDblclick
+ *
+ * @description
+ * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
+ *
+ * @element ANY
+ * @priority 0
+ * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
+ * a dblclick. (The Event object is available as `$event`)
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <button ng-dblclick="count = count + 1" ng-init="count=0">
+ Increment (on double click)
+ </button>
+ count: {{count}}
+ </file>
+ </example>
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngMousedown
+ *
+ * @description
+ * The ngMousedown directive allows you to specify custom behavior on mousedown event.
+ *
+ * @element ANY
+ * @priority 0
+ * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
+ * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <button ng-mousedown="count = count + 1" ng-init="count=0">
+ Increment (on mouse down)
+ </button>
+ count: {{count}}
+ </file>
+ </example>
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngMouseup
+ *
+ * @description
+ * Specify custom behavior on mouseup event.
+ *
+ * @element ANY
+ * @priority 0
+ * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
+ * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <button ng-mouseup="count = count + 1" ng-init="count=0">
+ Increment (on mouse up)
+ </button>
+ count: {{count}}
+ </file>
+ </example>
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngMouseover
+ *
+ * @description
+ * Specify custom behavior on mouseover event.
+ *
+ * @element ANY
+ * @priority 0
+ * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
+ * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <button ng-mouseover="count = count + 1" ng-init="count=0">
+ Increment (when mouse is over)
+ </button>
+ count: {{count}}
+ </file>
+ </example>
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngMouseenter
+ *
+ * @description
+ * Specify custom behavior on mouseenter event.
+ *
+ * @element ANY
+ * @priority 0
+ * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
+ * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <button ng-mouseenter="count = count + 1" ng-init="count=0">
+ Increment (when mouse enters)
+ </button>
+ count: {{count}}
+ </file>
+ </example>
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngMouseleave
+ *
+ * @description
+ * Specify custom behavior on mouseleave event.
+ *
+ * @element ANY
+ * @priority 0
+ * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
+ * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <button ng-mouseleave="count = count + 1" ng-init="count=0">
+ Increment (when mouse leaves)
+ </button>
+ count: {{count}}
+ </file>
+ </example>
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngMousemove
+ *
+ * @description
+ * Specify custom behavior on mousemove event.
+ *
+ * @element ANY
+ * @priority 0
+ * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
+ * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <button ng-mousemove="count = count + 1" ng-init="count=0">
+ Increment (when mouse moves)
+ </button>
+ count: {{count}}
+ </file>
+ </example>
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngKeydown
+ *
+ * @description
+ * Specify custom behavior on keydown event.
+ *
+ * @element ANY
+ * @priority 0
+ * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
+ * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <input ng-keydown="count = count + 1" ng-init="count=0">
+ key down count: {{count}}
+ </file>
+ </example>
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngKeyup
+ *
+ * @description
+ * Specify custom behavior on keyup event.
+ *
+ * @element ANY
+ * @priority 0
+ * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
+ * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <p>Typing in the input box below updates the key count</p>
+ <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
+
+ <p>Typing in the input box below updates the keycode</p>
+ <input ng-keyup="event=$event">
+ <p>event keyCode: {{ event.keyCode }}</p>
+ <p>event altKey: {{ event.altKey }}</p>
+ </file>
+ </example>
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngKeypress
+ *
+ * @description
+ * Specify custom behavior on keypress event.
+ *
+ * @element ANY
+ * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
+ * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
+ * and can be interrogated for keyCode, altKey, etc.)
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <input ng-keypress="count = count + 1" ng-init="count=0">
+ key press count: {{count}}
+ </file>
+ </example>
+ */
+
+
+/**
+ * @ngdoc directive
+ * @name ngSubmit
+ *
+ * @description
+ * Enables binding angular expressions to onsubmit events.
+ *
+ * Additionally it prevents the default action (which for form means sending the request to the
+ * server and reloading the current page), but only if the form does not contain `action`,
+ * `data-action`, or `x-action` attributes.
+ *
+ * <div class="alert alert-warning">
+ * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
+ * `ngSubmit` handlers together. See the
+ * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
+ * for a detailed discussion of when `ngSubmit` may be triggered.
+ * </div>
+ *
+ * @element form
+ * @priority 0
+ * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
+ * ({@link guide/expression#-event- Event object is available as `$event`})
+ *
+ * @example
+ <example module="submitExample">
+ <file name="index.html">
+ <script>
+ angular.module('submitExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.list = [];
+ $scope.text = 'hello';
+ $scope.submit = function() {
+ if ($scope.text) {
+ $scope.list.push(this.text);
+ $scope.text = '';
+ }
+ };
+ }]);
+ </script>
+ <form ng-submit="submit()" ng-controller="ExampleController">
+ Enter text and hit enter:
+ <input type="text" ng-model="text" name="text" />
+ <input type="submit" id="submit" value="Submit" />
+ <pre>list={{list}}</pre>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should check ng-submit', function() {
+ expect(element(by.binding('list')).getText()).toBe('list=[]');
+ element(by.css('#submit')).click();
+ expect(element(by.binding('list')).getText()).toContain('hello');
+ expect(element(by.model('text')).getAttribute('value')).toBe('');
+ });
+ it('should ignore empty strings', function() {
+ expect(element(by.binding('list')).getText()).toBe('list=[]');
+ element(by.css('#submit')).click();
+ element(by.css('#submit')).click();
+ expect(element(by.binding('list')).getText()).toContain('hello');
+ });
+ </file>
+ </example>
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngFocus
+ *
+ * @description
+ * Specify custom behavior on focus event.
+ *
+ * Note: As the `focus` event is executed synchronously when calling `input.focus()`
+ * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
+ * during an `$apply` to ensure a consistent state.
+ *
+ * @element window, input, select, textarea, a
+ * @priority 0
+ * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
+ * focus. ({@link guide/expression#-event- Event object is available as `$event`})
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngBlur
+ *
+ * @description
+ * Specify custom behavior on blur event.
+ *
+ * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
+ * an element has lost focus.
+ *
+ * Note: As the `blur` event is executed synchronously also during DOM manipulations
+ * (e.g. removing a focussed input),
+ * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
+ * during an `$apply` to ensure a consistent state.
+ *
+ * @element window, input, select, textarea, a
+ * @priority 0
+ * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
+ * blur. ({@link guide/expression#-event- Event object is available as `$event`})
+ *
+ * @example
+ * See {@link ng.directive:ngClick ngClick}
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngCopy
+ *
+ * @description
+ * Specify custom behavior on copy event.
+ *
+ * @element window, input, select, textarea, a
+ * @priority 0
+ * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
+ * copy. ({@link guide/expression#-event- Event object is available as `$event`})
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
+ copied: {{copied}}
+ </file>
+ </example>
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngCut
+ *
+ * @description
+ * Specify custom behavior on cut event.
+ *
+ * @element window, input, select, textarea, a
+ * @priority 0
+ * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
+ * cut. ({@link guide/expression#-event- Event object is available as `$event`})
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
+ cut: {{cut}}
+ </file>
+ </example>
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngPaste
+ *
+ * @description
+ * Specify custom behavior on paste event.
+ *
+ * @element window, input, select, textarea, a
+ * @priority 0
+ * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
+ * paste. ({@link guide/expression#-event- Event object is available as `$event`})
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
+ pasted: {{paste}}
+ </file>
+ </example>
+ */
+
+/**
+ * @ngdoc directive
+ * @name ngIf
+ * @restrict A
+ * @multiElement
+ *
+ * @description
+ * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
+ * {expression}. If the expression assigned to `ngIf` evaluates to a false
+ * value then the element is removed from the DOM, otherwise a clone of the
+ * element is reinserted into the DOM.
+ *
+ * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
+ * element in the DOM rather than changing its visibility via the `display` css property. A common
+ * case when this difference is significant is when using css selectors that rely on an element's
+ * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
+ *
+ * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
+ * is created when the element is restored. The scope created within `ngIf` inherits from
+ * its parent scope using
+ * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
+ * An important implication of this is if `ngModel` is used within `ngIf` to bind to
+ * a javascript primitive defined in the parent scope. In this case any modifications made to the
+ * variable within the child scope will override (hide) the value in the parent scope.
+ *
+ * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
+ * is if an element's class attribute is directly modified after it's compiled, using something like
+ * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
+ * the added class will be lost because the original compiled state is used to regenerate the element.
+ *
+ * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
+ * and `leave` effects.
+ *
+ * @animations
+ * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
+ * leave - happens just before the `ngIf` contents are removed from the DOM
+ *
+ * @element ANY
+ * @scope
+ * @priority 600
+ * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
+ * the element is removed from the DOM tree. If it is truthy a copy of the compiled
+ * element is added to the DOM tree.
+ *
+ * @example
+ <example module="ngAnimate" deps="angular-animate.js" animations="true">
+ <file name="index.html">
+ <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
+ Show when checked:
+ <span ng-if="checked" class="animate-if">
+ This is removed when the checkbox is unchecked.
+ </span>
+ </file>
+ <file name="animations.css">
+ .animate-if {
+ background:white;
+ border:1px solid black;
+ padding:10px;
+ }
+
+ .animate-if.ng-enter, .animate-if.ng-leave {
+ transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+ }
+
+ .animate-if.ng-enter,
+ .animate-if.ng-leave.ng-leave-active {
+ opacity:0;
+ }
+
+ .animate-if.ng-leave,
+ .animate-if.ng-enter.ng-enter-active {
+ opacity:1;
+ }
+ </file>
+ </example>
+ */
+var ngIfDirective = ['$animate', function($animate) {
+ return {
+ multiElement: true,
+ transclude: 'element',
+ priority: 600,
+ terminal: true,
+ restrict: 'A',
+ $$tlb: true,
+ link: function($scope, $element, $attr, ctrl, $transclude) {
+ var block, childScope, previousElements;
+ $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
+
+ if (value) {
+ if (!childScope) {
+ $transclude(function(clone, newScope) {
+ childScope = newScope;
+ clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
+ // Note: We only need the first/last node of the cloned nodes.
+ // However, we need to keep the reference to the jqlite wrapper as it might be changed later
+ // by a directive with templateUrl when its template arrives.
+ block = {
+ clone: clone
+ };
+ $animate.enter(clone, $element.parent(), $element);
+ });
+ }
+ } else {
+ if (previousElements) {
+ previousElements.remove();
+ previousElements = null;
+ }
+ if (childScope) {
+ childScope.$destroy();
+ childScope = null;
+ }
+ if (block) {
+ previousElements = getBlockNodes(block.clone);
+ $animate.leave(previousElements).then(function() {
+ previousElements = null;
+ });
+ block = null;
+ }
+ }
+ });
+ }
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ngInclude
+ * @restrict ECA
+ *
+ * @description
+ * Fetches, compiles and includes an external HTML fragment.
+ *
+ * By default, the template URL is restricted to the same domain and protocol as the
+ * application document. This is done by calling {@link $sce#getTrustedResourceUrl
+ * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
+ * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
+ * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
+ * ng.$sce Strict Contextual Escaping}.
+ *
+ * In addition, the browser's
+ * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
+ * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
+ * policy may further restrict whether the template is successfully loaded.
+ * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
+ * access on some browsers.
+ *
+ * @animations
+ * enter - animation is used to bring new content into the browser.
+ * leave - animation is used to animate existing content away.
+ *
+ * The enter and leave animation occur concurrently.
+ *
+ * @scope
+ * @priority 400
+ *
+ * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
+ * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
+ * @param {string=} onload Expression to evaluate when a new partial is loaded.
+ * <div class="alert alert-warning">
+ * **Note:** When using onload on SVG elements in IE11, the browser will try to call
+ * a function with the name on the window element, which will usually throw a
+ * "function is undefined" error. To fix this, you can instead use `data-onload` or a
+ * different form that {@link guide/directive#normalization matches} `onload`.
+ * </div>
+ *
+ * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
+ * $anchorScroll} to scroll the viewport after the content is loaded.
+ *
+ * - If the attribute is not set, disable scrolling.
+ * - If the attribute is set without value, enable scrolling.
+ * - Otherwise enable scrolling only if the expression evaluates to truthy value.
+ *
+ * @example
+ <example module="includeExample" deps="angular-animate.js" animations="true">
+ <file name="index.html">
+ <div ng-controller="ExampleController">
+ <select ng-model="template" ng-options="t.name for t in templates">
+ <option value="">(blank)</option>
+ </select>
+ url of the template: <code>{{template.url}}</code>
+ <hr/>
+ <div class="slide-animate-container">
+ <div class="slide-animate" ng-include="template.url"></div>
+ </div>
+ </div>
+ </file>
+ <file name="script.js">
+ angular.module('includeExample', ['ngAnimate'])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.templates =
+ [ { name: 'template1.html', url: 'template1.html'},
+ { name: 'template2.html', url: 'template2.html'} ];
+ $scope.template = $scope.templates[0];
+ }]);
+ </file>
+ <file name="template1.html">
+ Content of template1.html
+ </file>
+ <file name="template2.html">
+ Content of template2.html
+ </file>
+ <file name="animations.css">
+ .slide-animate-container {
+ position:relative;
+ background:white;
+ border:1px solid black;
+ height:40px;
+ overflow:hidden;
+ }
+
+ .slide-animate {
+ padding:10px;
+ }
+
+ .slide-animate.ng-enter, .slide-animate.ng-leave {
+ transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+
+ position:absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+ display:block;
+ padding:10px;
+ }
+
+ .slide-animate.ng-enter {
+ top:-50px;
+ }
+ .slide-animate.ng-enter.ng-enter-active {
+ top:0;
+ }
+
+ .slide-animate.ng-leave {
+ top:0;
+ }
+ .slide-animate.ng-leave.ng-leave-active {
+ top:50px;
+ }
+ </file>
+ <file name="protractor.js" type="protractor">
+ var templateSelect = element(by.model('template'));
+ var includeElem = element(by.css('[ng-include]'));
+
+ it('should load template1.html', function() {
+ expect(includeElem.getText()).toMatch(/Content of template1.html/);
+ });
+
+ it('should load template2.html', function() {
+ if (browser.params.browser == 'firefox') {
+ // Firefox can't handle using selects
+ // See https://github.com/angular/protractor/issues/480
+ return;
+ }
+ templateSelect.click();
+ templateSelect.all(by.css('option')).get(2).click();
+ expect(includeElem.getText()).toMatch(/Content of template2.html/);
+ });
+
+ it('should change to blank', function() {
+ if (browser.params.browser == 'firefox') {
+ // Firefox can't handle using selects
+ return;
+ }
+ templateSelect.click();
+ templateSelect.all(by.css('option')).get(0).click();
+ expect(includeElem.isPresent()).toBe(false);
+ });
+ </file>
+ </example>
+ */
+
+
+/**
+ * @ngdoc event
+ * @name ngInclude#$includeContentRequested
+ * @eventType emit on the scope ngInclude was declared in
+ * @description
+ * Emitted every time the ngInclude content is requested.
+ *
+ * @param {Object} angularEvent Synthetic event object.
+ * @param {String} src URL of content to load.
+ */
+
+
+/**
+ * @ngdoc event
+ * @name ngInclude#$includeContentLoaded
+ * @eventType emit on the current ngInclude scope
+ * @description
+ * Emitted every time the ngInclude content is reloaded.
+ *
+ * @param {Object} angularEvent Synthetic event object.
+ * @param {String} src URL of content to load.
+ */
+
+
+/**
+ * @ngdoc event
+ * @name ngInclude#$includeContentError
+ * @eventType emit on the scope ngInclude was declared in
+ * @description
+ * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
+ *
+ * @param {Object} angularEvent Synthetic event object.
+ * @param {String} src URL of content to load.
+ */
+var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
+ function($templateRequest, $anchorScroll, $animate) {
+ return {
+ restrict: 'ECA',
+ priority: 400,
+ terminal: true,
+ transclude: 'element',
+ controller: angular.noop,
+ compile: function(element, attr) {
+ var srcExp = attr.ngInclude || attr.src,
+ onloadExp = attr.onload || '',
+ autoScrollExp = attr.autoscroll;
+
+ return function(scope, $element, $attr, ctrl, $transclude) {
+ var changeCounter = 0,
+ currentScope,
+ previousElement,
+ currentElement;
+
+ var cleanupLastIncludeContent = function() {
+ if (previousElement) {
+ previousElement.remove();
+ previousElement = null;
+ }
+ if (currentScope) {
+ currentScope.$destroy();
+ currentScope = null;
+ }
+ if (currentElement) {
+ $animate.leave(currentElement).then(function() {
+ previousElement = null;
+ });
+ previousElement = currentElement;
+ currentElement = null;
+ }
+ };
+
+ scope.$watch(srcExp, function ngIncludeWatchAction(src) {
+ var afterAnimation = function() {
+ if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
+ $anchorScroll();
+ }
+ };
+ var thisChangeId = ++changeCounter;
+
+ if (src) {
+ //set the 2nd param to true to ignore the template request error so that the inner
+ //contents and scope can be cleaned up.
+ $templateRequest(src, true).then(function(response) {
+ if (thisChangeId !== changeCounter) return;
+ var newScope = scope.$new();
+ ctrl.template = response;
+
+ // Note: This will also link all children of ng-include that were contained in the original
+ // html. If that content contains controllers, ... they could pollute/change the scope.
+ // However, using ng-include on an element with additional content does not make sense...
+ // Note: We can't remove them in the cloneAttchFn of $transclude as that
+ // function is called before linking the content, which would apply child
+ // directives to non existing elements.
+ var clone = $transclude(newScope, function(clone) {
+ cleanupLastIncludeContent();
+ $animate.enter(clone, null, $element).then(afterAnimation);
+ });
+
+ currentScope = newScope;
+ currentElement = clone;
+
+ currentScope.$emit('$includeContentLoaded', src);
+ scope.$eval(onloadExp);
+ }, function() {
+ if (thisChangeId === changeCounter) {
+ cleanupLastIncludeContent();
+ scope.$emit('$includeContentError', src);
+ }
+ });
+ scope.$emit('$includeContentRequested', src);
+ } else {
+ cleanupLastIncludeContent();
+ ctrl.template = null;
+ }
+ });
+ };
+ }
+ };
+}];
+
+// This directive is called during the $transclude call of the first `ngInclude` directive.
+// It will replace and compile the content of the element with the loaded template.
+// We need this directive so that the element content is already filled when
+// the link function of another directive on the same element as ngInclude
+// is called.
+var ngIncludeFillContentDirective = ['$compile',
+ function($compile) {
+ return {
+ restrict: 'ECA',
+ priority: -400,
+ require: 'ngInclude',
+ link: function(scope, $element, $attr, ctrl) {
+ if (/SVG/.test($element[0].toString())) {
+ // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
+ // support innerHTML, so detect this here and try to generate the contents
+ // specially.
+ $element.empty();
+ $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
+ function namespaceAdaptedClone(clone) {
+ $element.append(clone);
+ }, {futureParentElement: $element});
+ return;
+ }
+
+ $element.html(ctrl.template);
+ $compile($element.contents())(scope);
+ }
+ };
+ }];
+
+/**
+ * @ngdoc directive
+ * @name ngInit
+ * @restrict AC
+ *
+ * @description
+ * The `ngInit` directive allows you to evaluate an expression in the
+ * current scope.
+ *
+ * <div class="alert alert-danger">
+ * This directive can be abused to add unnecessary amounts of logic into your templates.
+ * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
+ * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
+ * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
+ * rather than `ngInit` to initialize values on a scope.
+ * </div>
+ *
+ * <div class="alert alert-warning">
+ * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
+ * sure you have parentheses to ensure correct operator precedence:
+ * <pre class="prettyprint">
+ * `<div ng-init="test1 = ($index | toString)"></div>`
+ * </pre>
+ * </div>
+ *
+ * @priority 450
+ *
+ * @element ANY
+ * @param {expression} ngInit {@link guide/expression Expression} to eval.
+ *
+ * @example
+ <example module="initExample">
+ <file name="index.html">
+ <script>
+ angular.module('initExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.list = [['a', 'b'], ['c', 'd']];
+ }]);
+ </script>
+ <div ng-controller="ExampleController">
+ <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
+ <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
+ <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
+ </div>
+ </div>
+ </div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should alias index positions', function() {
+ var elements = element.all(by.css('.example-init'));
+ expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
+ expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
+ expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
+ expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
+ });
+ </file>
+ </example>
+ */
+var ngInitDirective = ngDirective({
+ priority: 450,
+ compile: function() {
+ return {
+ pre: function(scope, element, attrs) {
+ scope.$eval(attrs.ngInit);
+ }
+ };
+ }
+});
+
+/**
+ * @ngdoc directive
+ * @name ngList
+ *
+ * @description
+ * Text input that converts between a delimited string and an array of strings. The default
+ * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
+ * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
+ *
+ * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
+ * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
+ * list item is respected. This implies that the user of the directive is responsible for
+ * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
+ * tab or newline character.
+ * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
+ * when joining the list items back together) and whitespace around each list item is stripped
+ * before it is added to the model.
+ *
+ * ### Example with Validation
+ *
+ * <example name="ngList-directive" module="listExample">
+ * <file name="app.js">
+ * angular.module('listExample', [])
+ * .controller('ExampleController', ['$scope', function($scope) {
+ * $scope.names = ['morpheus', 'neo', 'trinity'];
+ * }]);
+ * </file>
+ * <file name="index.html">
+ * <form name="myForm" ng-controller="ExampleController">
+ * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
+ * <span role="alert">
+ * <span class="error" ng-show="myForm.namesInput.$error.required">
+ * Required!</span>
+ * </span>
+ * <br>
+ * <tt>names = {{names}}</tt><br/>
+ * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
+ * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
+ * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
+ * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
+ * </form>
+ * </file>
+ * <file name="protractor.js" type="protractor">
+ * var listInput = element(by.model('names'));
+ * var names = element(by.exactBinding('names'));
+ * var valid = element(by.binding('myForm.namesInput.$valid'));
+ * var error = element(by.css('span.error'));
+ *
+ * it('should initialize to model', function() {
+ * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
+ * expect(valid.getText()).toContain('true');
+ * expect(error.getCssValue('display')).toBe('none');
+ * });
+ *
+ * it('should be invalid if empty', function() {
+ * listInput.clear();
+ * listInput.sendKeys('');
+ *
+ * expect(names.getText()).toContain('');
+ * expect(valid.getText()).toContain('false');
+ * expect(error.getCssValue('display')).not.toBe('none');
+ * });
+ * </file>
+ * </example>
+ *
+ * ### Example - splitting on newline
+ * <example name="ngList-directive-newlines">
+ * <file name="index.html">
+ * <textarea ng-model="list" ng-list=" " ng-trim="false"></textarea>
+ * <pre>{{ list | json }}</pre>
+ * </file>
+ * <file name="protractor.js" type="protractor">
+ * it("should split the text by newlines", function() {
+ * var listInput = element(by.model('list'));
+ * var output = element(by.binding('list | json'));
+ * listInput.sendKeys('abc\ndef\nghi');
+ * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
+ * });
+ * </file>
+ * </example>
+ *
+ * @element input
+ * @param {string=} ngList optional delimiter that should be used to split the value.
+ */
+var ngListDirective = function() {
+ return {
+ restrict: 'A',
+ priority: 100,
+ require: 'ngModel',
+ link: function(scope, element, attr, ctrl) {
+ // We want to control whitespace trimming so we use this convoluted approach
+ // to access the ngList attribute, which doesn't pre-trim the attribute
+ var ngList = element.attr(attr.$attr.ngList) || ', ';
+ var trimValues = attr.ngTrim !== 'false';
+ var separator = trimValues ? trim(ngList) : ngList;
+
+ var parse = function(viewValue) {
+ // If the viewValue is invalid (say required but empty) it will be `undefined`
+ if (isUndefined(viewValue)) return;
+
+ var list = [];
+
+ if (viewValue) {
+ forEach(viewValue.split(separator), function(value) {
+ if (value) list.push(trimValues ? trim(value) : value);
+ });
+ }
+
+ return list;
+ };
+
+ ctrl.$parsers.push(parse);
+ ctrl.$formatters.push(function(value) {
+ if (isArray(value)) {
+ return value.join(ngList);
+ }
+
+ return undefined;
+ });
+
+ // Override the standard $isEmpty because an empty array means the input is empty.
+ ctrl.$isEmpty = function(value) {
+ return !value || !value.length;
+ };
+ }
+ };
+};
+
+/* global VALID_CLASS: true,
+ INVALID_CLASS: true,
+ PRISTINE_CLASS: true,
+ DIRTY_CLASS: true,
+ UNTOUCHED_CLASS: true,
+ TOUCHED_CLASS: true,
+*/
+
+var VALID_CLASS = 'ng-valid',
+ INVALID_CLASS = 'ng-invalid',
+ PRISTINE_CLASS = 'ng-pristine',
+ DIRTY_CLASS = 'ng-dirty',
+ UNTOUCHED_CLASS = 'ng-untouched',
+ TOUCHED_CLASS = 'ng-touched',
+ PENDING_CLASS = 'ng-pending';
+
+var ngModelMinErr = minErr('ngModel');
+
+/**
+ * @ngdoc type
+ * @name ngModel.NgModelController
+ *
+ * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
+ * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
+ * is set.
+ * @property {*} $modelValue The value in the model that the control is bound to.
+ * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
+ the control reads value from the DOM. The functions are called in array order, each passing
+ its return value through to the next. The last return value is forwarded to the
+ {@link ngModel.NgModelController#$validators `$validators`} collection.
+
+Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
+`$viewValue`}.
+
+Returning `undefined` from a parser means a parse error occurred. In that case,
+no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
+will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
+is set to `true`. The parse error is stored in `ngModel.$error.parse`.
+
+ *
+ * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
+ the model value changes. The functions are called in reverse array order, each passing the value through to the
+ next. The last return value is used as the actual DOM value.
+ Used to format / convert values for display in the control.
+ * ```js
+ * function formatter(value) {
+ * if (value) {
+ * return value.toUpperCase();
+ * }
+ * }
+ * ngModel.$formatters.push(formatter);
+ * ```
+ *
+ * @property {Object.<string, function>} $validators A collection of validators that are applied
+ * whenever the model value changes. The key value within the object refers to the name of the
+ * validator while the function refers to the validation operation. The validation operation is
+ * provided with the model value as an argument and must return a true or false value depending
+ * on the response of that validation.
+ *
+ * ```js
+ * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
+ * var value = modelValue || viewValue;
+ * return /[0-9]+/.test(value) &&
+ * /[a-z]+/.test(value) &&
+ * /[A-Z]+/.test(value) &&
+ * /\W+/.test(value);
+ * };
+ * ```
+ *
+ * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
+ * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
+ * is expected to return a promise when it is run during the model validation process. Once the promise
+ * is delivered then the validation status will be set to true when fulfilled and false when rejected.
+ * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
+ * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
+ * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
+ * will only run once all synchronous validators have passed.
+ *
+ * Please note that if $http is used then it is important that the server returns a success HTTP response code
+ * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
+ *
+ * ```js
+ * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
+ * var value = modelValue || viewValue;
+ *
+ * // Lookup user by username
+ * return $http.get('/api/users/' + value).
+ * then(function resolved() {
+ * //username exists, this means validation fails
+ * return $q.reject('exists');
+ * }, function rejected() {
+ * //username does not exist, therefore this validation passes
+ * return true;
+ * });
+ * };
+ * ```
+ *
+ * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
+ * view value has changed. It is called with no arguments, and its return value is ignored.
+ * This can be used in place of additional $watches against the model value.
+ *
+ * @property {Object} $error An object hash with all failing validator ids as keys.
+ * @property {Object} $pending An object hash with all pending validator ids as keys.
+ *
+ * @property {boolean} $untouched True if control has not lost focus yet.
+ * @property {boolean} $touched True if control has lost focus.
+ * @property {boolean} $pristine True if user has not interacted with the control yet.
+ * @property {boolean} $dirty True if user has already interacted with the control.
+ * @property {boolean} $valid True if there is no error.
+ * @property {boolean} $invalid True if at least one error on the control.
+ * @property {string} $name The name attribute of the control.
+ *
+ * @description
+ *
+ * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
+ * The controller contains services for data-binding, validation, CSS updates, and value formatting
+ * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
+ * listening to DOM events.
+ * Such DOM related logic should be provided by other directives which make use of
+ * `NgModelController` for data-binding to control elements.
+ * Angular provides this DOM logic for most {@link input `input`} elements.
+ * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
+ * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
+ *
+ * @example
+ * ### Custom Control Example
+ * This example shows how to use `NgModelController` with a custom control to achieve
+ * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
+ * collaborate together to achieve the desired result.
+ *
+ * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
+ * contents be edited in place by the user.
+ *
+ * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
+ * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
+ * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
+ * that content using the `$sce` service.
+ *
+ * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
+ <file name="style.css">
+ [contenteditable] {
+ border: 1px solid black;
+ background-color: white;
+ min-height: 20px;
+ }
+
+ .ng-invalid {
+ border: 1px solid red;
+ }
+
+ </file>
+ <file name="script.js">
+ angular.module('customControl', ['ngSanitize']).
+ directive('contenteditable', ['$sce', function($sce) {
+ return {
+ restrict: 'A', // only activate on element attribute
+ require: '?ngModel', // get a hold of NgModelController
+ link: function(scope, element, attrs, ngModel) {
+ if (!ngModel) return; // do nothing if no ng-model
+
+ // Specify how UI should be updated
+ ngModel.$render = function() {
+ element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
+ };
+
+ // Listen for change events to enable binding
+ element.on('blur keyup change', function() {
+ scope.$evalAsync(read);
+ });
+ read(); // initialize
+
+ // Write data to the model
+ function read() {
+ var html = element.html();
+ // When we clear the content editable the browser leaves a <br> behind
+ // If strip-br attribute is provided then we strip this out
+ if ( attrs.stripBr && html == '<br>' ) {
+ html = '';
+ }
+ ngModel.$setViewValue(html);
+ }
+ }
+ };
+ }]);
+ </file>
+ <file name="index.html">
+ <form name="myForm">
+ <div contenteditable
+ name="myWidget" ng-model="userContent"
+ strip-br="true"
+ required>Change me!</div>
+ <span ng-show="myForm.myWidget.$error.required">Required!</span>
+ <hr>
+ <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
+ </form>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should data-bind and become invalid', function() {
+ if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
+ // SafariDriver can't handle contenteditable
+ // and Firefox driver can't clear contenteditables very well
+ return;
+ }
+ var contentEditable = element(by.css('[contenteditable]'));
+ var content = 'Change me!';
+
+ expect(contentEditable.getText()).toEqual(content);
+
+ contentEditable.clear();
+ contentEditable.sendKeys(protractor.Key.BACK_SPACE);
+ expect(contentEditable.getText()).toEqual('');
+ expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
+ });
+ </file>
+ * </example>
+ *
+ *
+ */
+var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
+ function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
+ this.$viewValue = Number.NaN;
+ this.$modelValue = Number.NaN;
+ this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
+ this.$validators = {};
+ this.$asyncValidators = {};
+ this.$parsers = [];
+ this.$formatters = [];
+ this.$viewChangeListeners = [];
+ this.$untouched = true;
+ this.$touched = false;
+ this.$pristine = true;
+ this.$dirty = false;
+ this.$valid = true;
+ this.$invalid = false;
+ this.$error = {}; // keep invalid keys here
+ this.$$success = {}; // keep valid keys here
+ this.$pending = undefined; // keep pending keys here
+ this.$name = $interpolate($attr.name || '', false)($scope);
+ this.$$parentForm = nullFormCtrl;
+
+ var parsedNgModel = $parse($attr.ngModel),
+ parsedNgModelAssign = parsedNgModel.assign,
+ ngModelGet = parsedNgModel,
+ ngModelSet = parsedNgModelAssign,
+ pendingDebounce = null,
+ parserValid,
+ ctrl = this;
+
+ this.$$setOptions = function(options) {
+ ctrl.$options = options;
+ if (options && options.getterSetter) {
+ var invokeModelGetter = $parse($attr.ngModel + '()'),
+ invokeModelSetter = $parse($attr.ngModel + '($$$p)');
+
+ ngModelGet = function($scope) {
+ var modelValue = parsedNgModel($scope);
+ if (isFunction(modelValue)) {
+ modelValue = invokeModelGetter($scope);
+ }
+ return modelValue;
+ };
+ ngModelSet = function($scope, newValue) {
+ if (isFunction(parsedNgModel($scope))) {
+ invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
+ } else {
+ parsedNgModelAssign($scope, ctrl.$modelValue);
+ }
+ };
+ } else if (!parsedNgModel.assign) {
+ throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
+ $attr.ngModel, startingTag($element));
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngModel.NgModelController#$render
+ *
+ * @description
+ * Called when the view needs to be updated. It is expected that the user of the ng-model
+ * directive will implement this method.
+ *
+ * The `$render()` method is invoked in the following situations:
+ *
+ * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
+ * committed value then `$render()` is called to update the input control.
+ * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
+ * the `$viewValue` are different from last time.
+ *
+ * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
+ * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
+ * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
+ * invoked if you only change a property on the objects.
+ */
+ this.$render = noop;
+
+ /**
+ * @ngdoc method
+ * @name ngModel.NgModelController#$isEmpty
+ *
+ * @description
+ * This is called when we need to determine if the value of an input is empty.
+ *
+ * For instance, the required directive does this to work out if the input has data or not.
+ *
+ * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
+ *
+ * You can override this for input directives whose concept of being empty is different from the
+ * default. The `checkboxInputType` directive does this because in its case a value of `false`
+ * implies empty.
+ *
+ * @param {*} value The value of the input to check for emptiness.
+ * @returns {boolean} True if `value` is "empty".
+ */
+ this.$isEmpty = function(value) {
+ return isUndefined(value) || value === '' || value === null || value !== value;
+ };
+
+ var currentValidationRunId = 0;
+
+ /**
+ * @ngdoc method
+ * @name ngModel.NgModelController#$setValidity
+ *
+ * @description
+ * Change the validity state, and notify the form.
+ *
+ * This method can be called within $parsers/$formatters or a custom validation implementation.
+ * However, in most cases it should be sufficient to use the `ngModel.$validators` and
+ * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
+ *
+ * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
+ * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
+ * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
+ * The `validationErrorKey` should be in camelCase and will get converted into dash-case
+ * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
+ * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
+ * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
+ * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
+ * Skipped is used by Angular when validators do not run because of parse errors and
+ * when `$asyncValidators` do not run because any of the `$validators` failed.
+ */
+ addSetValidityMethod({
+ ctrl: this,
+ $element: $element,
+ set: function(object, property) {
+ object[property] = true;
+ },
+ unset: function(object, property) {
+ delete object[property];
+ },
+ $animate: $animate
+ });
+
+ /**
+ * @ngdoc method
+ * @name ngModel.NgModelController#$setPristine
+ *
+ * @description
+ * Sets the control to its pristine state.
+ *
+ * This method can be called to remove the `ng-dirty` class and set the control to its pristine
+ * state (`ng-pristine` class). A model is considered to be pristine when the control
+ * has not been changed from when first compiled.
+ */
+ this.$setPristine = function() {
+ ctrl.$dirty = false;
+ ctrl.$pristine = true;
+ $animate.removeClass($element, DIRTY_CLASS);
+ $animate.addClass($element, PRISTINE_CLASS);
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngModel.NgModelController#$setDirty
+ *
+ * @description
+ * Sets the control to its dirty state.
+ *
+ * This method can be called to remove the `ng-pristine` class and set the control to its dirty
+ * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
+ * from when first compiled.
+ */
+ this.$setDirty = function() {
+ ctrl.$dirty = true;
+ ctrl.$pristine = false;
+ $animate.removeClass($element, PRISTINE_CLASS);
+ $animate.addClass($element, DIRTY_CLASS);
+ ctrl.$$parentForm.$setDirty();
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngModel.NgModelController#$setUntouched
+ *
+ * @description
+ * Sets the control to its untouched state.
+ *
+ * This method can be called to remove the `ng-touched` class and set the control to its
+ * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
+ * by default, however this function can be used to restore that state if the model has
+ * already been touched by the user.
+ */
+ this.$setUntouched = function() {
+ ctrl.$touched = false;
+ ctrl.$untouched = true;
+ $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngModel.NgModelController#$setTouched
+ *
+ * @description
+ * Sets the control to its touched state.
+ *
+ * This method can be called to remove the `ng-untouched` class and set the control to its
+ * touched state (`ng-touched` class). A model is considered to be touched when the user has
+ * first focused the control element and then shifted focus away from the control (blur event).
+ */
+ this.$setTouched = function() {
+ ctrl.$touched = true;
+ ctrl.$untouched = false;
+ $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngModel.NgModelController#$rollbackViewValue
+ *
+ * @description
+ * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
+ * which may be caused by a pending debounced event or because the input is waiting for a some
+ * future event.
+ *
+ * If you have an input that uses `ng-model-options` to set up debounced events or events such
+ * as blur you can have a situation where there is a period when the `$viewValue`
+ * is out of synch with the ngModel's `$modelValue`.
+ *
+ * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
+ * programmatically before these debounced/future events have resolved/occurred, because Angular's
+ * dirty checking mechanism is not able to tell whether the model has actually changed or not.
+ *
+ * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
+ * input which may have such events pending. This is important in order to make sure that the
+ * input field will be updated with the new model value and any pending operations are cancelled.
+ *
+ * <example name="ng-model-cancel-update" module="cancel-update-example">
+ * <file name="app.js">
+ * angular.module('cancel-update-example', [])
+ *
+ * .controller('CancelUpdateController', ['$scope', function($scope) {
+ * $scope.resetWithCancel = function(e) {
+ * if (e.keyCode == 27) {
+ * $scope.myForm.myInput1.$rollbackViewValue();
+ * $scope.myValue = '';
+ * }
+ * };
+ * $scope.resetWithoutCancel = function(e) {
+ * if (e.keyCode == 27) {
+ * $scope.myValue = '';
+ * }
+ * };
+ * }]);
+ * </file>
+ * <file name="index.html">
+ * <div ng-controller="CancelUpdateController">
+ * <p>Try typing something in each input. See that the model only updates when you
+ * blur off the input.
+ * </p>
+ * <p>Now see what happens if you start typing then press the Escape key</p>
+ *
+ * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
+ * <p id="inputDescription1">With $rollbackViewValue()</p>
+ * <input name="myInput1" aria-describedby="inputDescription1" ng-model="myValue"
+ * ng-keydown="resetWithCancel($event)"><br/>
+ * myValue: "{{ myValue }}"
+ *
+ * <p id="inputDescription2">Without $rollbackViewValue()</p>
+ * <input name="myInput2" aria-describedby="inputDescription2" ng-model="myValue"
+ * ng-keydown="resetWithoutCancel($event)"><br/>
+ * myValue: "{{ myValue }}"
+ * </form>
+ * </div>
+ * </file>
+ * </example>
+ */
+ this.$rollbackViewValue = function() {
+ $timeout.cancel(pendingDebounce);
+ ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
+ ctrl.$render();
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngModel.NgModelController#$validate
+ *
+ * @description
+ * Runs each of the registered validators (first synchronous validators and then
+ * asynchronous validators).
+ * If the validity changes to invalid, the model will be set to `undefined`,
+ * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
+ * If the validity changes to valid, it will set the model to the last available valid
+ * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
+ */
+ this.$validate = function() {
+ // ignore $validate before model is initialized
+ if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
+ return;
+ }
+
+ var viewValue = ctrl.$$lastCommittedViewValue;
+ // Note: we use the $$rawModelValue as $modelValue might have been
+ // set to undefined during a view -> model update that found validation
+ // errors. We can't parse the view here, since that could change
+ // the model although neither viewValue nor the model on the scope changed
+ var modelValue = ctrl.$$rawModelValue;
+
+ var prevValid = ctrl.$valid;
+ var prevModelValue = ctrl.$modelValue;
+
+ var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
+
+ ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
+ // If there was no change in validity, don't update the model
+ // This prevents changing an invalid modelValue to undefined
+ if (!allowInvalid && prevValid !== allValid) {
+ // Note: Don't check ctrl.$valid here, as we could have
+ // external validators (e.g. calculated on the server),
+ // that just call $setValidity and need the model value
+ // to calculate their validity.
+ ctrl.$modelValue = allValid ? modelValue : undefined;
+
+ if (ctrl.$modelValue !== prevModelValue) {
+ ctrl.$$writeModelToScope();
+ }
+ }
+ });
+
+ };
+
+ this.$$runValidators = function(modelValue, viewValue, doneCallback) {
+ currentValidationRunId++;
+ var localValidationRunId = currentValidationRunId;
+
+ // check parser error
+ if (!processParseErrors()) {
+ validationDone(false);
+ return;
+ }
+ if (!processSyncValidators()) {
+ validationDone(false);
+ return;
+ }
+ processAsyncValidators();
+
+ function processParseErrors() {
+ var errorKey = ctrl.$$parserName || 'parse';
+ if (isUndefined(parserValid)) {
+ setValidity(errorKey, null);
+ } else {
+ if (!parserValid) {
+ forEach(ctrl.$validators, function(v, name) {
+ setValidity(name, null);
+ });
+ forEach(ctrl.$asyncValidators, function(v, name) {
+ setValidity(name, null);
+ });
+ }
+ // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
+ setValidity(errorKey, parserValid);
+ return parserValid;
+ }
+ return true;
+ }
+
+ function processSyncValidators() {
+ var syncValidatorsValid = true;
+ forEach(ctrl.$validators, function(validator, name) {
+ var result = validator(modelValue, viewValue);
+ syncValidatorsValid = syncValidatorsValid && result;
+ setValidity(name, result);
+ });
+ if (!syncValidatorsValid) {
+ forEach(ctrl.$asyncValidators, function(v, name) {
+ setValidity(name, null);
+ });
+ return false;
+ }
+ return true;
+ }
+
+ function processAsyncValidators() {
+ var validatorPromises = [];
+ var allValid = true;
+ forEach(ctrl.$asyncValidators, function(validator, name) {
+ var promise = validator(modelValue, viewValue);
+ if (!isPromiseLike(promise)) {
+ throw ngModelMinErr("$asyncValidators",
+ "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
+ }
+ setValidity(name, undefined);
+ validatorPromises.push(promise.then(function() {
+ setValidity(name, true);
+ }, function(error) {
+ allValid = false;
+ setValidity(name, false);
+ }));
+ });
+ if (!validatorPromises.length) {
+ validationDone(true);
+ } else {
+ $q.all(validatorPromises).then(function() {
+ validationDone(allValid);
+ }, noop);
+ }
+ }
+
+ function setValidity(name, isValid) {
+ if (localValidationRunId === currentValidationRunId) {
+ ctrl.$setValidity(name, isValid);
+ }
+ }
+
+ function validationDone(allValid) {
+ if (localValidationRunId === currentValidationRunId) {
+
+ doneCallback(allValid);
+ }
+ }
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngModel.NgModelController#$commitViewValue
+ *
+ * @description
+ * Commit a pending update to the `$modelValue`.
+ *
+ * Updates may be pending by a debounced event or because the input is waiting for a some future
+ * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
+ * usually handles calling this in response to input events.
+ */
+ this.$commitViewValue = function() {
+ var viewValue = ctrl.$viewValue;
+
+ $timeout.cancel(pendingDebounce);
+
+ // If the view value has not changed then we should just exit, except in the case where there is
+ // a native validator on the element. In this case the validation state may have changed even though
+ // the viewValue has stayed empty.
+ if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
+ return;
+ }
+ ctrl.$$lastCommittedViewValue = viewValue;
+
+ // change to dirty
+ if (ctrl.$pristine) {
+ this.$setDirty();
+ }
+ this.$$parseAndValidate();
+ };
+
+ this.$$parseAndValidate = function() {
+ var viewValue = ctrl.$$lastCommittedViewValue;
+ var modelValue = viewValue;
+ parserValid = isUndefined(modelValue) ? undefined : true;
+
+ if (parserValid) {
+ for (var i = 0; i < ctrl.$parsers.length; i++) {
+ modelValue = ctrl.$parsers[i](modelValue);
+ if (isUndefined(modelValue)) {
+ parserValid = false;
+ break;
+ }
+ }
+ }
+ if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
+ // ctrl.$modelValue has not been touched yet...
+ ctrl.$modelValue = ngModelGet($scope);
+ }
+ var prevModelValue = ctrl.$modelValue;
+ var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
+ ctrl.$$rawModelValue = modelValue;
+
+ if (allowInvalid) {
+ ctrl.$modelValue = modelValue;
+ writeToModelIfNeeded();
+ }
+
+ // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
+ // This can happen if e.g. $setViewValue is called from inside a parser
+ ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
+ if (!allowInvalid) {
+ // Note: Don't check ctrl.$valid here, as we could have
+ // external validators (e.g. calculated on the server),
+ // that just call $setValidity and need the model value
+ // to calculate their validity.
+ ctrl.$modelValue = allValid ? modelValue : undefined;
+ writeToModelIfNeeded();
+ }
+ });
+
+ function writeToModelIfNeeded() {
+ if (ctrl.$modelValue !== prevModelValue) {
+ ctrl.$$writeModelToScope();
+ }
+ }
+ };
+
+ this.$$writeModelToScope = function() {
+ ngModelSet($scope, ctrl.$modelValue);
+ forEach(ctrl.$viewChangeListeners, function(listener) {
+ try {
+ listener();
+ } catch (e) {
+ $exceptionHandler(e);
+ }
+ });
+ };
+
+ /**
+ * @ngdoc method
+ * @name ngModel.NgModelController#$setViewValue
+ *
+ * @description
+ * Update the view value.
+ *
+ * This method should be called when a control wants to change the view value; typically,
+ * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
+ * directive calls it when the value of the input changes and {@link ng.directive:select select}
+ * calls it when an option is selected.
+ *
+ * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
+ * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
+ * value sent directly for processing, finally to be applied to `$modelValue` and then the
+ * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
+ * in the `$viewChangeListeners` list, are called.
+ *
+ * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
+ * and the `default` trigger is not listed, all those actions will remain pending until one of the
+ * `updateOn` events is triggered on the DOM element.
+ * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
+ * directive is used with a custom debounce for this particular event.
+ * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
+ * is specified, once the timer runs out.
+ *
+ * When used with standard inputs, the view value will always be a string (which is in some cases
+ * parsed into another type, such as a `Date` object for `input[date]`.)
+ * However, custom controls might also pass objects to this method. In this case, we should make
+ * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
+ * perform a deep watch of objects, it only looks for a change of identity. If you only change
+ * the property of the object then ngModel will not realise that the object has changed and
+ * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
+ * not change properties of the copy once it has been passed to `$setViewValue`.
+ * Otherwise you may cause the model value on the scope to change incorrectly.
+ *
+ * <div class="alert alert-info">
+ * In any case, the value passed to the method should always reflect the current value
+ * of the control. For example, if you are calling `$setViewValue` for an input element,
+ * you should pass the input DOM value. Otherwise, the control and the scope model become
+ * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
+ * the control's DOM value in any way. If we want to change the control's DOM value
+ * programmatically, we should update the `ngModel` scope expression. Its new value will be
+ * picked up by the model controller, which will run it through the `$formatters`, `$render` it
+ * to update the DOM, and finally call `$validate` on it.
+ * </div>
+ *
+ * @param {*} value value from the view.
+ * @param {string} trigger Event that triggered the update.
+ */
+ this.$setViewValue = function(value, trigger) {
+ ctrl.$viewValue = value;
+ if (!ctrl.$options || ctrl.$options.updateOnDefault) {
+ ctrl.$$debounceViewValueCommit(trigger);
+ }
+ };
+
+ this.$$debounceViewValueCommit = function(trigger) {
+ var debounceDelay = 0,
+ options = ctrl.$options,
+ debounce;
+
+ if (options && isDefined(options.debounce)) {
+ debounce = options.debounce;
+ if (isNumber(debounce)) {
+ debounceDelay = debounce;
+ } else if (isNumber(debounce[trigger])) {
+ debounceDelay = debounce[trigger];
+ } else if (isNumber(debounce['default'])) {
+ debounceDelay = debounce['default'];
+ }
+ }
+
+ $timeout.cancel(pendingDebounce);
+ if (debounceDelay) {
+ pendingDebounce = $timeout(function() {
+ ctrl.$commitViewValue();
+ }, debounceDelay);
+ } else if ($rootScope.$$phase) {
+ ctrl.$commitViewValue();
+ } else {
+ $scope.$apply(function() {
+ ctrl.$commitViewValue();
+ });
+ }
+ };
+
+ // model -> value
+ // Note: we cannot use a normal scope.$watch as we want to detect the following:
+ // 1. scope value is 'a'
+ // 2. user enters 'b'
+ // 3. ng-change kicks in and reverts scope value to 'a'
+ // -> scope value did not change since the last digest as
+ // ng-change executes in apply phase
+ // 4. view should be changed back to 'a'
+ $scope.$watch(function ngModelWatch() {
+ var modelValue = ngModelGet($scope);
+
+ // if scope model value and ngModel value are out of sync
+ // TODO(perf): why not move this to the action fn?
+ if (modelValue !== ctrl.$modelValue &&
+ // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
+ (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
+ ) {
+ ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
+ parserValid = undefined;
+
+ var formatters = ctrl.$formatters,
+ idx = formatters.length;
+
+ var viewValue = modelValue;
+ while (idx--) {
+ viewValue = formatters[idx](viewValue);
+ }
+ if (ctrl.$viewValue !== viewValue) {
+ ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
+ ctrl.$render();
+
+ ctrl.$$runValidators(modelValue, viewValue, noop);
+ }
+ }
+
+ return modelValue;
+ });
+}];
+
+
+/**
+ * @ngdoc directive
+ * @name ngModel
+ *
+ * @element input
+ * @priority 1
+ *
+ * @description
+ * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
+ * property on the scope using {@link ngModel.NgModelController NgModelController},
+ * which is created and exposed by this directive.
+ *
+ * `ngModel` is responsible for:
+ *
+ * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
+ * require.
+ * - Providing validation behavior (i.e. required, number, email, url).
+ * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
+ * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
+ * - Registering the control with its parent {@link ng.directive:form form}.
+ *
+ * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
+ * current scope. If the property doesn't already exist on this scope, it will be created
+ * implicitly and added to the scope.
+ *
+ * For best practices on using `ngModel`, see:
+ *
+ * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
+ *
+ * For basic examples, how to use `ngModel`, see:
+ *
+ * - {@link ng.directive:input input}
+ * - {@link input[text] text}
+ * - {@link input[checkbox] checkbox}
+ * - {@link input[radio] radio}
+ * - {@link input[number] number}
+ * - {@link input[email] email}
+ * - {@link input[url] url}
+ * - {@link input[date] date}
+ * - {@link input[datetime-local] datetime-local}
+ * - {@link input[time] time}
+ * - {@link input[month] month}
+ * - {@link input[week] week}
+ * - {@link ng.directive:select select}
+ * - {@link ng.directive:textarea textarea}
+ *
+ * # CSS classes
+ * The following CSS classes are added and removed on the associated input/select/textarea element
+ * depending on the validity of the model.
+ *
+ * - `ng-valid`: the model is valid
+ * - `ng-invalid`: the model is invalid
+ * - `ng-valid-[key]`: for each valid key added by `$setValidity`
+ * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
+ * - `ng-pristine`: the control hasn't been interacted with yet
+ * - `ng-dirty`: the control has been interacted with
+ * - `ng-touched`: the control has been blurred
+ * - `ng-untouched`: the control hasn't been blurred
+ * - `ng-pending`: any `$asyncValidators` are unfulfilled
+ *
+ * Keep in mind that ngAnimate can detect each of these classes when added and removed.
+ *
+ * ## Animation Hooks
+ *
+ * Animations within models are triggered when any of the associated CSS classes are added and removed
+ * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
+ * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
+ * The animations that are triggered within ngModel are similar to how they work in ngClass and
+ * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
+ *
+ * The following example shows a simple way to utilize CSS transitions to style an input element
+ * that has been rendered as invalid after it has been validated:
+ *
+ * <pre>
+ * //be sure to include ngAnimate as a module to hook into more
+ * //advanced animations
+ * .my-input {
+ * transition:0.5s linear all;
+ * background: white;
+ * }
+ * .my-input.ng-invalid {
+ * background: red;
+ * color:white;
+ * }
+ * </pre>
+ *
+ * @example
+ * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
+ <file name="index.html">
+ <script>
+ angular.module('inputExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.val = '1';
+ }]);
+ </script>
+ <style>
+ .my-input {
+ transition:all linear 0.5s;
+ background: transparent;
+ }
+ .my-input.ng-invalid {
+ color:white;
+ background: red;
+ }
+ </style>
+ <p id="inputDescription">
+ Update input to see transitions when valid/invalid.
+ Integer is a valid value.
+ </p>
+ <form name="testForm" ng-controller="ExampleController">
+ <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
+ aria-describedby="inputDescription" />
+ </form>
+ </file>
+ * </example>
+ *
+ * ## Binding to a getter/setter
+ *
+ * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
+ * function that returns a representation of the model when called with zero arguments, and sets
+ * the internal state of a model when called with an argument. It's sometimes useful to use this
+ * for models that have an internal representation that's different from what the model exposes
+ * to the view.
+ *
+ * <div class="alert alert-success">
+ * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
+ * frequently than other parts of your code.
+ * </div>
+ *
+ * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
+ * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
+ * a `<form>`, which will enable this behavior for all `<input>`s within it. See
+ * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
+ *
+ * The following example shows how to use `ngModel` with a getter/setter:
+ *
+ * @example
+ * <example name="ngModel-getter-setter" module="getterSetterExample">
+ <file name="index.html">
+ <div ng-controller="ExampleController">
+ <form name="userForm">
+ <label>Name:
+ <input type="text" name="userName"
+ ng-model="user.name"
+ ng-model-options="{ getterSetter: true }" />
+ </label>
+ </form>
+ <pre>user.name = <span ng-bind="user.name()"></span></pre>
+ </div>
+ </file>
+ <file name="app.js">
+ angular.module('getterSetterExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ var _name = 'Brian';
+ $scope.user = {
+ name: function(newName) {
+ // Note that newName can be undefined for two reasons:
+ // 1. Because it is called as a getter and thus called with no arguments
+ // 2. Because the property should actually be set to undefined. This happens e.g. if the
+ // input is invalid
+ return arguments.length ? (_name = newName) : _name;
+ }
+ };
+ }]);
+ </file>
+ * </example>
+ */
+var ngModelDirective = ['$rootScope', function($rootScope) {
+ return {
+ restrict: 'A',
+ require: ['ngModel', '^?form', '^?ngModelOptions'],
+ controller: NgModelController,
+ // Prelink needs to run before any input directive
+ // so that we can set the NgModelOptions in NgModelController
+ // before anyone else uses it.
+ priority: 1,
+ compile: function ngModelCompile(element) {
+ // Setup initial state of the control
+ element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
+
+ return {
+ pre: function ngModelPreLink(scope, element, attr, ctrls) {
+ var modelCtrl = ctrls[0],
+ formCtrl = ctrls[1] || modelCtrl.$$parentForm;
+
+ modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
+
+ // notify others, especially parent forms
+ formCtrl.$addControl(modelCtrl);
+
+ attr.$observe('name', function(newValue) {
+ if (modelCtrl.$name !== newValue) {
+ modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
+ }
+ });
+
+ scope.$on('$destroy', function() {
+ modelCtrl.$$parentForm.$removeControl(modelCtrl);
+ });
+ },
+ post: function ngModelPostLink(scope, element, attr, ctrls) {
+ var modelCtrl = ctrls[0];
+ if (modelCtrl.$options && modelCtrl.$options.updateOn) {
+ element.on(modelCtrl.$options.updateOn, function(ev) {
+ modelCtrl.$$debounceViewValueCommit(ev && ev.type);
+ });
+ }
+
+ element.on('blur', function(ev) {
+ if (modelCtrl.$touched) return;
+
+ if ($rootScope.$$phase) {
+ scope.$evalAsync(modelCtrl.$setTouched);
+ } else {
+ scope.$apply(modelCtrl.$setTouched);
+ }
+ });
+ }
+ };
+ }
+ };
+}];
+
+var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
+
+/**
+ * @ngdoc directive
+ * @name ngModelOptions
+ *
+ * @description
+ * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
+ * events that will trigger a model update and/or a debouncing delay so that the actual update only
+ * takes place when a timer expires; this timer will be reset after another change takes place.
+ *
+ * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
+ * be different from the value in the actual model. This means that if you update the model you
+ * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
+ * order to make sure it is synchronized with the model and that any debounced action is canceled.
+ *
+ * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
+ * method is by making sure the input is placed inside a form that has a `name` attribute. This is
+ * important because `form` controllers are published to the related scope under the name in their
+ * `name` attribute.
+ *
+ * Any pending changes will take place immediately when an enclosing form is submitted via the
+ * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
+ * to have access to the updated model.
+ *
+ * `ngModelOptions` has an effect on the element it's declared on and its descendants.
+ *
+ * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
+ * - `updateOn`: string specifying which event should the input be bound to. You can set several
+ * events using an space delimited list. There is a special event called `default` that
+ * matches the default events belonging of the control.
+ * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
+ * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
+ * custom value for each event. For example:
+ * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
+ * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
+ * not validate correctly instead of the default behavior of setting the model to undefined.
+ * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
+ `ngModel` as getters/setters.
+ * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
+ * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
+ * continental US time zone abbreviations, but for general use, use a time zone offset, for
+ * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
+ * If not specified, the timezone of the browser will be used.
+ *
+ * @example
+
+ The following example shows how to override immediate updates. Changes on the inputs within the
+ form will update the model only when the control loses focus (blur event). If `escape` key is
+ pressed while the input field is focused, the value is reset to the value in the current model.
+
+ <example name="ngModelOptions-directive-blur" module="optionsExample">
+ <file name="index.html">
+ <div ng-controller="ExampleController">
+ <form name="userForm">
+ <label>Name:
+ <input type="text" name="userName"
+ ng-model="user.name"
+ ng-model-options="{ updateOn: 'blur' }"
+ ng-keyup="cancel($event)" />
+ </label><br />
+ <label>Other data:
+ <input type="text" ng-model="user.data" />
+ </label><br />
+ </form>
+ <pre>user.name = <span ng-bind="user.name"></span></pre>
+ <pre>user.data = <span ng-bind="user.data"></span></pre>
+ </div>
+ </file>
+ <file name="app.js">
+ angular.module('optionsExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.user = { name: 'John', data: '' };
+
+ $scope.cancel = function(e) {
+ if (e.keyCode == 27) {
+ $scope.userForm.userName.$rollbackViewValue();
+ }
+ };
+ }]);
+ </file>
+ <file name="protractor.js" type="protractor">
+ var model = element(by.binding('user.name'));
+ var input = element(by.model('user.name'));
+ var other = element(by.model('user.data'));
+
+ it('should allow custom events', function() {
+ input.sendKeys(' Doe');
+ input.click();
+ expect(model.getText()).toEqual('John');
+ other.click();
+ expect(model.getText()).toEqual('John Doe');
+ });
+
+ it('should $rollbackViewValue when model changes', function() {
+ input.sendKeys(' Doe');
+ expect(input.getAttribute('value')).toEqual('John Doe');
+ input.sendKeys(protractor.Key.ESCAPE);
+ expect(input.getAttribute('value')).toEqual('John');
+ other.click();
+ expect(model.getText()).toEqual('John');
+ });
+ </file>
+ </example>
+
+ This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
+ If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
+
+ <example name="ngModelOptions-directive-debounce" module="optionsExample">
+ <file name="index.html">
+ <div ng-controller="ExampleController">
+ <form name="userForm">
+ <label>Name:
+ <input type="text" name="userName"
+ ng-model="user.name"
+ ng-model-options="{ debounce: 1000 }" />
+ </label>
+ <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
+ <br />
+ </form>
+ <pre>user.name = <span ng-bind="user.name"></span></pre>
+ </div>
+ </file>
+ <file name="app.js">
+ angular.module('optionsExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.user = { name: 'Igor' };
+ }]);
+ </file>
+ </example>
+
+ This one shows how to bind to getter/setters:
+
+ <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
+ <file name="index.html">
+ <div ng-controller="ExampleController">
+ <form name="userForm">
+ <label>Name:
+ <input type="text" name="userName"
+ ng-model="user.name"
+ ng-model-options="{ getterSetter: true }" />
+ </label>
+ </form>
+ <pre>user.name = <span ng-bind="user.name()"></span></pre>
+ </div>
+ </file>
+ <file name="app.js">
+ angular.module('getterSetterExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ var _name = 'Brian';
+ $scope.user = {
+ name: function(newName) {
+ // Note that newName can be undefined for two reasons:
+ // 1. Because it is called as a getter and thus called with no arguments
+ // 2. Because the property should actually be set to undefined. This happens e.g. if the
+ // input is invalid
+ return arguments.length ? (_name = newName) : _name;
+ }
+ };
+ }]);
+ </file>
+ </example>
+ */
+var ngModelOptionsDirective = function() {
+ return {
+ restrict: 'A',
+ controller: ['$scope', '$attrs', function($scope, $attrs) {
+ var that = this;
+ this.$options = copy($scope.$eval($attrs.ngModelOptions));
+ // Allow adding/overriding bound events
+ if (isDefined(this.$options.updateOn)) {
+ this.$options.updateOnDefault = false;
+ // extract "default" pseudo-event from list of events that can trigger a model update
+ this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
+ that.$options.updateOnDefault = true;
+ return ' ';
+ }));
+ } else {
+ this.$options.updateOnDefault = true;
+ }
+ }]
+ };
+};
+
+
+
+// helper methods
+function addSetValidityMethod(context) {
+ var ctrl = context.ctrl,
+ $element = context.$element,
+ classCache = {},
+ set = context.set,
+ unset = context.unset,
+ $animate = context.$animate;
+
+ classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
+
+ ctrl.$setValidity = setValidity;
+
+ function setValidity(validationErrorKey, state, controller) {
+ if (isUndefined(state)) {
+ createAndSet('$pending', validationErrorKey, controller);
+ } else {
+ unsetAndCleanup('$pending', validationErrorKey, controller);
+ }
+ if (!isBoolean(state)) {
+ unset(ctrl.$error, validationErrorKey, controller);
+ unset(ctrl.$$success, validationErrorKey, controller);
+ } else {
+ if (state) {
+ unset(ctrl.$error, validationErrorKey, controller);
+ set(ctrl.$$success, validationErrorKey, controller);
+ } else {
+ set(ctrl.$error, validationErrorKey, controller);
+ unset(ctrl.$$success, validationErrorKey, controller);
+ }
+ }
+ if (ctrl.$pending) {
+ cachedToggleClass(PENDING_CLASS, true);
+ ctrl.$valid = ctrl.$invalid = undefined;
+ toggleValidationCss('', null);
+ } else {
+ cachedToggleClass(PENDING_CLASS, false);
+ ctrl.$valid = isObjectEmpty(ctrl.$error);
+ ctrl.$invalid = !ctrl.$valid;
+ toggleValidationCss('', ctrl.$valid);
+ }
+
+ // re-read the state as the set/unset methods could have
+ // combined state in ctrl.$error[validationError] (used for forms),
+ // where setting/unsetting only increments/decrements the value,
+ // and does not replace it.
+ var combinedState;
+ if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
+ combinedState = undefined;
+ } else if (ctrl.$error[validationErrorKey]) {
+ combinedState = false;
+ } else if (ctrl.$$success[validationErrorKey]) {
+ combinedState = true;
+ } else {
+ combinedState = null;
+ }
+
+ toggleValidationCss(validationErrorKey, combinedState);
+ ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
+ }
+
+ function createAndSet(name, value, controller) {
+ if (!ctrl[name]) {
+ ctrl[name] = {};
+ }
+ set(ctrl[name], value, controller);
+ }
+
+ function unsetAndCleanup(name, value, controller) {
+ if (ctrl[name]) {
+ unset(ctrl[name], value, controller);
+ }
+ if (isObjectEmpty(ctrl[name])) {
+ ctrl[name] = undefined;
+ }
+ }
+
+ function cachedToggleClass(className, switchValue) {
+ if (switchValue && !classCache[className]) {
+ $animate.addClass($element, className);
+ classCache[className] = true;
+ } else if (!switchValue && classCache[className]) {
+ $animate.removeClass($element, className);
+ classCache[className] = false;
+ }
+ }
+
+ function toggleValidationCss(validationErrorKey, isValid) {
+ validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
+
+ cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
+ cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
+ }
+}
+
+function isObjectEmpty(obj) {
+ if (obj) {
+ for (var prop in obj) {
+ if (obj.hasOwnProperty(prop)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+/**
+ * @ngdoc directive
+ * @name ngNonBindable
+ * @restrict AC
+ * @priority 1000
+ *
+ * @description
+ * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
+ * DOM element. This is useful if the element contains what appears to be Angular directives and
+ * bindings but which should be ignored by Angular. This could be the case if you have a site that
+ * displays snippets of code, for instance.
+ *
+ * @element ANY
+ *
+ * @example
+ * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
+ * but the one wrapped in `ngNonBindable` is left alone.
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <div>Normal: {{1 + 2}}</div>
+ <div ng-non-bindable>Ignored: {{1 + 2}}</div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should check ng-non-bindable', function() {
+ expect(element(by.binding('1 + 2')).getText()).toContain('3');
+ expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
+ });
+ </file>
+ </example>
+ */
+var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
+
+/* global jqLiteRemove */
+
+var ngOptionsMinErr = minErr('ngOptions');
+
+/**
+ * @ngdoc directive
+ * @name ngOptions
+ * @restrict A
+ *
+ * @description
+ *
+ * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
+ * elements for the `<select>` element using the array or object obtained by evaluating the
+ * `ngOptions` comprehension expression.
+ *
+ * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
+ * similar result. However, `ngOptions` provides some benefits such as reducing memory and
+ * increasing speed by not creating a new scope for each repeated instance, as well as providing
+ * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
+ * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
+ * to a non-string value. This is because an option element can only be bound to string values at
+ * present.
+ *
+ * When an item in the `<select>` menu is selected, the array element or object property
+ * represented by the selected option will be bound to the model identified by the `ngModel`
+ * directive.
+ *
+ * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
+ * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
+ * option. See example below for demonstration.
+ *
+ * ## Complex Models (objects or collections)
+ *
+ * By default, `ngModel` watches the model by reference, not value. This is important to know when
+ * binding the select to a model that is an object or a collection.
+ *
+ * One issue occurs if you want to preselect an option. For example, if you set
+ * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
+ * because the objects are not identical. So by default, you should always reference the item in your collection
+ * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
+ *
+ * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
+ * of the item not by reference, but by the result of the `track by` expression. For example, if your
+ * collection items have an id property, you would `track by item.id`.
+ *
+ * A different issue with objects or collections is that ngModel won't detect if an object property or
+ * a collection item changes. For that reason, `ngOptions` additionally watches the model using
+ * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
+ * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
+ * has not changed identity, but only a property on the object or an item in the collection changes.
+ *
+ * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
+ * if the model is an array). This means that changing a property deeper than the first level inside the
+ * object/collection will not trigger a re-rendering.
+ *
+ * ## `select` **`as`**
+ *
+ * Using `select` **`as`** will bind the result of the `select` expression to the model, but
+ * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
+ * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
+ * is used, the result of that expression will be set as the value of the `option` and `select` elements.
+ *
+ *
+ * ### `select` **`as`** and **`track by`**
+ *
+ * <div class="alert alert-warning">
+ * Be careful when using `select` **`as`** and **`track by`** in the same expression.
+ * </div>
+ *
+ * Given this array of items on the $scope:
+ *
+ * ```js
+ * $scope.items = [{
+ * id: 1,
+ * label: 'aLabel',
+ * subItem: { name: 'aSubItem' }
+ * }, {
+ * id: 2,
+ * label: 'bLabel',
+ * subItem: { name: 'bSubItem' }
+ * }];
+ * ```
+ *
+ * This will work:
+ *
+ * ```html
+ * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
+ * ```
+ * ```js
+ * $scope.selected = $scope.items[0];
+ * ```
+ *
+ * but this will not work:
+ *
+ * ```html
+ * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
+ * ```
+ * ```js
+ * $scope.selected = $scope.items[0].subItem;
+ * ```
+ *
+ * In both examples, the **`track by`** expression is applied successfully to each `item` in the
+ * `items` array. Because the selected option has been set programmatically in the controller, the
+ * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
+ * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
+ * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
+ * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
+ * is not matched against any `<option>` and the `<select>` appears as having no selected value.
+ *
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} required The control is considered valid only if value is entered.
+ * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
+ * `required` when you want to data-bind to the `required` attribute.
+ * @param {comprehension_expression=} ngOptions in one of the following forms:
+ *
+ * * for array data sources:
+ * * `label` **`for`** `value` **`in`** `array`
+ * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
+ * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
+ * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
+ * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
+ * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
+ * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
+ * (for including a filter with `track by`)
+ * * for object data sources:
+ * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
+ * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
+ * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
+ * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
+ * * `select` **`as`** `label` **`group by`** `group`
+ * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
+ * * `select` **`as`** `label` **`disable when`** `disable`
+ * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
+ *
+ * Where:
+ *
+ * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
+ * * `value`: local variable which will refer to each item in the `array` or each property value
+ * of `object` during iteration.
+ * * `key`: local variable which will refer to a property name in `object` during iteration.
+ * * `label`: The result of this expression will be the label for `<option>` element. The
+ * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
+ * * `select`: The result of this expression will be bound to the model of the parent `<select>`
+ * element. If not specified, `select` expression will default to `value`.
+ * * `group`: The result of this expression will be used to group options using the `<optgroup>`
+ * DOM element.
+ * * `disable`: The result of this expression will be used to disable the rendered `<option>`
+ * element. Return `true` to disable.
+ * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
+ * used to identify the objects in the array. The `trackexpr` will most likely refer to the
+ * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
+ * even when the options are recreated (e.g. reloaded from the server).
+ *
+ * @example
+ <example module="selectExample">
+ <file name="index.html">
+ <script>
+ angular.module('selectExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.colors = [
+ {name:'black', shade:'dark'},
+ {name:'white', shade:'light', notAnOption: true},
+ {name:'red', shade:'dark'},
+ {name:'blue', shade:'dark', notAnOption: true},
+ {name:'yellow', shade:'light', notAnOption: false}
+ ];
+ $scope.myColor = $scope.colors[2]; // red
+ }]);
+ </script>
+ <div ng-controller="ExampleController">
+ <ul>
+ <li ng-repeat="color in colors">
+ <label>Name: <input ng-model="color.name"></label>
+ <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
+ <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
+ </li>
+ <li>
+ <button ng-click="colors.push({})">add</button>
+ </li>
+ </ul>
+ <hr/>
+ <label>Color (null not allowed):
+ <select ng-model="myColor" ng-options="color.name for color in colors"></select>
+ </label><br/>
+ <label>Color (null allowed):
+ <span class="nullable">
+ <select ng-model="myColor" ng-options="color.name for color in colors">
+ <option value="">-- choose color --</option>
+ </select>
+ </span></label><br/>
+
+ <label>Color grouped by shade:
+ <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
+ </select>
+ </label><br/>
+
+ <label>Color grouped by shade, with some disabled:
+ <select ng-model="myColor"
+ ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
+ </select>
+ </label><br/>
+
+
+
+ Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
+ <br/>
+ <hr/>
+ Currently selected: {{ {selected_color:myColor} }}
+ <div style="border:solid 1px black; height:20px"
+ ng-style="{'background-color':myColor.name}">
+ </div>
+ </div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should check ng-options', function() {
+ expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
+ element.all(by.model('myColor')).first().click();
+ element.all(by.css('select[ng-model="myColor"] option')).first().click();
+ expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
+ element(by.css('.nullable select[ng-model="myColor"]')).click();
+ element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
+ expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
+ });
+ </file>
+ </example>
+ */
+
+// jshint maxlen: false
+// //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
+var NG_OPTIONS_REGEXP = /^\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]+?))?$/;
+ // 1: value expression (valueFn)
+ // 2: label expression (displayFn)
+ // 3: group by expression (groupByFn)
+ // 4: disable when expression (disableWhenFn)
+ // 5: array item variable name
+ // 6: object item key variable name
+ // 7: object item value variable name
+ // 8: collection expression
+ // 9: track by expression
+// jshint maxlen: 100
+
+
+var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
+
+ function parseOptionsExpression(optionsExp, selectElement, scope) {
+
+ var match = optionsExp.match(NG_OPTIONS_REGEXP);
+ if (!(match)) {
+ throw ngOptionsMinErr('iexp',
+ "Expected expression in form of " +
+ "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
+ " but got '{0}'. Element: {1}",
+ optionsExp, startingTag(selectElement));
+ }
+
+ // Extract the parts from the ngOptions expression
+
+ // The variable name for the value of the item in the collection
+ var valueName = match[5] || match[7];
+ // The variable name for the key of the item in the collection
+ var keyName = match[6];
+
+ // An expression that generates the viewValue for an option if there is a label expression
+ var selectAs = / as /.test(match[0]) && match[1];
+ // An expression that is used to track the id of each object in the options collection
+ var trackBy = match[9];
+ // An expression that generates the viewValue for an option if there is no label expression
+ var valueFn = $parse(match[2] ? match[1] : valueName);
+ var selectAsFn = selectAs && $parse(selectAs);
+ var viewValueFn = selectAsFn || valueFn;
+ var trackByFn = trackBy && $parse(trackBy);
+
+ // Get the value by which we are going to track the option
+ // if we have a trackFn then use that (passing scope and locals)
+ // otherwise just hash the given viewValue
+ var getTrackByValueFn = trackBy ?
+ function(value, locals) { return trackByFn(scope, locals); } :
+ function getHashOfValue(value) { return hashKey(value); };
+ var getTrackByValue = function(value, key) {
+ return getTrackByValueFn(value, getLocals(value, key));
+ };
+
+ var displayFn = $parse(match[2] || match[1]);
+ var groupByFn = $parse(match[3] || '');
+ var disableWhenFn = $parse(match[4] || '');
+ var valuesFn = $parse(match[8]);
+
+ var locals = {};
+ var getLocals = keyName ? function(value, key) {
+ locals[keyName] = key;
+ locals[valueName] = value;
+ return locals;
+ } : function(value) {
+ locals[valueName] = value;
+ return locals;
+ };
+
+
+ function Option(selectValue, viewValue, label, group, disabled) {
+ this.selectValue = selectValue;
+ this.viewValue = viewValue;
+ this.label = label;
+ this.group = group;
+ this.disabled = disabled;
+ }
+
+ function getOptionValuesKeys(optionValues) {
+ var optionValuesKeys;
+
+ if (!keyName && isArrayLike(optionValues)) {
+ optionValuesKeys = optionValues;
+ } else {
+ // if object, extract keys, in enumeration order, unsorted
+ optionValuesKeys = [];
+ for (var itemKey in optionValues) {
+ if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
+ optionValuesKeys.push(itemKey);
+ }
+ }
+ }
+ return optionValuesKeys;
+ }
+
+ return {
+ trackBy: trackBy,
+ getTrackByValue: getTrackByValue,
+ getWatchables: $parse(valuesFn, function(optionValues) {
+ // Create a collection of things that we would like to watch (watchedArray)
+ // so that they can all be watched using a single $watchCollection
+ // that only runs the handler once if anything changes
+ var watchedArray = [];
+ optionValues = optionValues || [];
+
+ var optionValuesKeys = getOptionValuesKeys(optionValues);
+ var optionValuesLength = optionValuesKeys.length;
+ for (var index = 0; index < optionValuesLength; index++) {
+ var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
+ var value = optionValues[key];
+
+ var locals = getLocals(optionValues[key], key);
+ var selectValue = getTrackByValueFn(optionValues[key], locals);
+ watchedArray.push(selectValue);
+
+ // Only need to watch the displayFn if there is a specific label expression
+ if (match[2] || match[1]) {
+ var label = displayFn(scope, locals);
+ watchedArray.push(label);
+ }
+
+ // Only need to watch the disableWhenFn if there is a specific disable expression
+ if (match[4]) {
+ var disableWhen = disableWhenFn(scope, locals);
+ watchedArray.push(disableWhen);
+ }
+ }
+ return watchedArray;
+ }),
+
+ getOptions: function() {
+
+ var optionItems = [];
+ var selectValueMap = {};
+
+ // The option values were already computed in the `getWatchables` fn,
+ // which must have been called to trigger `getOptions`
+ var optionValues = valuesFn(scope) || [];
+ var optionValuesKeys = getOptionValuesKeys(optionValues);
+ var optionValuesLength = optionValuesKeys.length;
+
+ for (var index = 0; index < optionValuesLength; index++) {
+ var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
+ var value = optionValues[key];
+ var locals = getLocals(value, key);
+ var viewValue = viewValueFn(scope, locals);
+ var selectValue = getTrackByValueFn(viewValue, locals);
+ var label = displayFn(scope, locals);
+ var group = groupByFn(scope, locals);
+ var disabled = disableWhenFn(scope, locals);
+ var optionItem = new Option(selectValue, viewValue, label, group, disabled);
+
+ optionItems.push(optionItem);
+ selectValueMap[selectValue] = optionItem;
+ }
+
+ return {
+ items: optionItems,
+ selectValueMap: selectValueMap,
+ getOptionFromViewValue: function(value) {
+ return selectValueMap[getTrackByValue(value)];
+ },
+ getViewValueFromOption: function(option) {
+ // If the viewValue could be an object that may be mutated by the application,
+ // we need to make a copy and not return the reference to the value on the option.
+ return trackBy ? angular.copy(option.viewValue) : option.viewValue;
+ }
+ };
+ }
+ };
+ }
+
+
+ // we can't just jqLite('<option>') since jqLite is not smart enough
+ // to create it in <select> and IE barfs otherwise.
+ var optionTemplate = document.createElement('option'),
+ optGroupTemplate = document.createElement('optgroup');
+
+
+ function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
+
+ // if ngModel is not defined, we don't need to do anything
+ var ngModelCtrl = ctrls[1];
+ if (!ngModelCtrl) return;
+
+ var selectCtrl = ctrls[0];
+ var multiple = attr.multiple;
+
+ // The emptyOption allows the application developer to provide their own custom "empty"
+ // option when the viewValue does not match any of the option values.
+ var emptyOption;
+ for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
+ if (children[i].value === '') {
+ emptyOption = children.eq(i);
+ break;
+ }
+ }
+
+ var providedEmptyOption = !!emptyOption;
+
+ var unknownOption = jqLite(optionTemplate.cloneNode(false));
+ unknownOption.val('?');
+
+ var options;
+ var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
+
+
+ var renderEmptyOption = function() {
+ if (!providedEmptyOption) {
+ selectElement.prepend(emptyOption);
+ }
+ selectElement.val('');
+ emptyOption.prop('selected', true); // needed for IE
+ emptyOption.attr('selected', true);
+ };
+
+ var removeEmptyOption = function() {
+ if (!providedEmptyOption) {
+ emptyOption.remove();
+ }
+ };
+
+
+ var renderUnknownOption = function() {
+ selectElement.prepend(unknownOption);
+ selectElement.val('?');
+ unknownOption.prop('selected', true); // needed for IE
+ unknownOption.attr('selected', true);
+ };
+
+ var removeUnknownOption = function() {
+ unknownOption.remove();
+ };
+
+ // Update the controller methods for multiple selectable options
+ if (!multiple) {
+
+ selectCtrl.writeValue = function writeNgOptionsValue(value) {
+ var option = options.getOptionFromViewValue(value);
+
+ if (option && !option.disabled) {
+ if (selectElement[0].value !== option.selectValue) {
+ removeUnknownOption();
+ removeEmptyOption();
+
+ selectElement[0].value = option.selectValue;
+ option.element.selected = true;
+ option.element.setAttribute('selected', 'selected');
+ }
+ } else {
+ if (value === null || providedEmptyOption) {
+ removeUnknownOption();
+ renderEmptyOption();
+ } else {
+ removeEmptyOption();
+ renderUnknownOption();
+ }
+ }
+ };
+
+ selectCtrl.readValue = function readNgOptionsValue() {
+
+ var selectedOption = options.selectValueMap[selectElement.val()];
+
+ if (selectedOption && !selectedOption.disabled) {
+ removeEmptyOption();
+ removeUnknownOption();
+ return options.getViewValueFromOption(selectedOption);
+ }
+ return null;
+ };
+
+ // If we are using `track by` then we must watch the tracked value on the model
+ // since ngModel only watches for object identity change
+ if (ngOptions.trackBy) {
+ scope.$watch(
+ function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
+ function() { ngModelCtrl.$render(); }
+ );
+ }
+
+ } else {
+
+ ngModelCtrl.$isEmpty = function(value) {
+ return !value || value.length === 0;
+ };
+
+
+ selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
+ options.items.forEach(function(option) {
+ option.element.selected = false;
+ });
+
+ if (value) {
+ value.forEach(function(item) {
+ var option = options.getOptionFromViewValue(item);
+ if (option && !option.disabled) option.element.selected = true;
+ });
+ }
+ };
+
+
+ selectCtrl.readValue = function readNgOptionsMultiple() {
+ var selectedValues = selectElement.val() || [],
+ selections = [];
+
+ forEach(selectedValues, function(value) {
+ var option = options.selectValueMap[value];
+ if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
+ });
+
+ return selections;
+ };
+
+ // If we are using `track by` then we must watch these tracked values on the model
+ // since ngModel only watches for object identity change
+ if (ngOptions.trackBy) {
+
+ scope.$watchCollection(function() {
+ if (isArray(ngModelCtrl.$viewValue)) {
+ return ngModelCtrl.$viewValue.map(function(value) {
+ return ngOptions.getTrackByValue(value);
+ });
+ }
+ }, function() {
+ ngModelCtrl.$render();
+ });
+
+ }
+ }
+
+
+ if (providedEmptyOption) {
+
+ // we need to remove it before calling selectElement.empty() because otherwise IE will
+ // remove the label from the element. wtf?
+ emptyOption.remove();
+
+ // compile the element since there might be bindings in it
+ $compile(emptyOption)(scope);
+
+ // remove the class, which is added automatically because we recompile the element and it
+ // becomes the compilation root
+ emptyOption.removeClass('ng-scope');
+ } else {
+ emptyOption = jqLite(optionTemplate.cloneNode(false));
+ }
+
+ // We need to do this here to ensure that the options object is defined
+ // when we first hit it in writeNgOptionsValue
+ updateOptions();
+
+ // We will re-render the option elements if the option values or labels change
+ scope.$watchCollection(ngOptions.getWatchables, updateOptions);
+
+ // ------------------------------------------------------------------ //
+
+
+ function updateOptionElement(option, element) {
+ option.element = element;
+ element.disabled = option.disabled;
+ // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
+ // selects in certain circumstances when multiple selects are next to each other and display
+ // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
+ // See https://github.com/angular/angular.js/issues/11314 for more info.
+ // This is unfortunately untestable with unit / e2e tests
+ if (option.label !== element.label) {
+ element.label = option.label;
+ element.textContent = option.label;
+ }
+ if (option.value !== element.value) element.value = option.selectValue;
+ }
+
+ function addOrReuseElement(parent, current, type, templateElement) {
+ var element;
+ // Check whether we can reuse the next element
+ if (current && lowercase(current.nodeName) === type) {
+ // The next element is the right type so reuse it
+ element = current;
+ } else {
+ // The next element is not the right type so create a new one
+ element = templateElement.cloneNode(false);
+ if (!current) {
+ // There are no more elements so just append it to the select
+ parent.appendChild(element);
+ } else {
+ // The next element is not a group so insert the new one
+ parent.insertBefore(element, current);
+ }
+ }
+ return element;
+ }
+
+
+ function removeExcessElements(current) {
+ var next;
+ while (current) {
+ next = current.nextSibling;
+ jqLiteRemove(current);
+ current = next;
+ }
+ }
+
+
+ function skipEmptyAndUnknownOptions(current) {
+ var emptyOption_ = emptyOption && emptyOption[0];
+ var unknownOption_ = unknownOption && unknownOption[0];
+
+ // We cannot rely on the extracted empty option being the same as the compiled empty option,
+ // because the compiled empty option might have been replaced by a comment because
+ // it had an "element" transclusion directive on it (such as ngIf)
+ if (emptyOption_ || unknownOption_) {
+ while (current &&
+ (current === emptyOption_ ||
+ current === unknownOption_ ||
+ current.nodeType === NODE_TYPE_COMMENT ||
+ current.value === '')) {
+ current = current.nextSibling;
+ }
+ }
+ return current;
+ }
+
+
+ function updateOptions() {
+
+ var previousValue = options && selectCtrl.readValue();
+
+ options = ngOptions.getOptions();
+
+ var groupMap = {};
+ var currentElement = selectElement[0].firstChild;
+
+ // Ensure that the empty option is always there if it was explicitly provided
+ if (providedEmptyOption) {
+ selectElement.prepend(emptyOption);
+ }
+
+ currentElement = skipEmptyAndUnknownOptions(currentElement);
+
+ options.items.forEach(function updateOption(option) {
+ var group;
+ var groupElement;
+ var optionElement;
+
+ if (option.group) {
+
+ // This option is to live in a group
+ // See if we have already created this group
+ group = groupMap[option.group];
+
+ if (!group) {
+
+ // We have not already created this group
+ groupElement = addOrReuseElement(selectElement[0],
+ currentElement,
+ 'optgroup',
+ optGroupTemplate);
+ // Move to the next element
+ currentElement = groupElement.nextSibling;
+
+ // Update the label on the group element
+ groupElement.label = option.group;
+
+ // Store it for use later
+ group = groupMap[option.group] = {
+ groupElement: groupElement,
+ currentOptionElement: groupElement.firstChild
+ };
+
+ }
+
+ // So now we have a group for this option we add the option to the group
+ optionElement = addOrReuseElement(group.groupElement,
+ group.currentOptionElement,
+ 'option',
+ optionTemplate);
+ updateOptionElement(option, optionElement);
+ // Move to the next element
+ group.currentOptionElement = optionElement.nextSibling;
+
+ } else {
+
+ // This option is not in a group
+ optionElement = addOrReuseElement(selectElement[0],
+ currentElement,
+ 'option',
+ optionTemplate);
+ updateOptionElement(option, optionElement);
+ // Move to the next element
+ currentElement = optionElement.nextSibling;
+ }
+ });
+
+
+ // Now remove all excess options and group
+ Object.keys(groupMap).forEach(function(key) {
+ removeExcessElements(groupMap[key].currentOptionElement);
+ });
+ removeExcessElements(currentElement);
+
+ ngModelCtrl.$render();
+
+ // Check to see if the value has changed due to the update to the options
+ if (!ngModelCtrl.$isEmpty(previousValue)) {
+ var nextValue = selectCtrl.readValue();
+ if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
+ ngModelCtrl.$setViewValue(nextValue);
+ ngModelCtrl.$render();
+ }
+ }
+
+ }
+ }
+
+ return {
+ restrict: 'A',
+ terminal: true,
+ require: ['select', '?ngModel'],
+ link: {
+ pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
+ // Deactivate the SelectController.register method to prevent
+ // option directives from accidentally registering themselves
+ // (and unwanted $destroy handlers etc.)
+ ctrls[0].registerOption = noop;
+ },
+ post: ngOptionsPostLink
+ }
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ngPluralize
+ * @restrict EA
+ *
+ * @description
+ * `ngPluralize` is a directive that displays messages according to en-US localization rules.
+ * These rules are bundled with angular.js, but can be overridden
+ * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
+ * by specifying the mappings between
+ * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
+ * and the strings to be displayed.
+ *
+ * # Plural categories and explicit number rules
+ * There are two
+ * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
+ * in Angular's default en-US locale: "one" and "other".
+ *
+ * While a plural category may match many numbers (for example, in en-US locale, "other" can match
+ * any number that is not 1), an explicit number rule can only match one number. For example, the
+ * explicit number rule for "3" matches the number 3. There are examples of plural categories
+ * and explicit number rules throughout the rest of this documentation.
+ *
+ * # Configuring ngPluralize
+ * You configure ngPluralize by providing 2 attributes: `count` and `when`.
+ * You can also provide an optional attribute, `offset`.
+ *
+ * The value of the `count` attribute can be either a string or an {@link guide/expression
+ * Angular expression}; these are evaluated on the current scope for its bound value.
+ *
+ * The `when` attribute specifies the mappings between plural categories and the actual
+ * string to be displayed. The value of the attribute should be a JSON object.
+ *
+ * The following example shows how to configure ngPluralize:
+ *
+ * ```html
+ * <ng-pluralize count="personCount"
+ when="{'0': 'Nobody is viewing.',
+ * 'one': '1 person is viewing.',
+ * 'other': '{} people are viewing.'}">
+ * </ng-pluralize>
+ *```
+ *
+ * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
+ * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
+ * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
+ * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
+ * show "a dozen people are viewing".
+ *
+ * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
+ * into pluralized strings. In the previous example, Angular will replace `{}` with
+ * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
+ * for <span ng-non-bindable>{{numberExpression}}</span>.
+ *
+ * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
+ * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
+ *
+ * # Configuring ngPluralize with offset
+ * The `offset` attribute allows further customization of pluralized text, which can result in
+ * a better user experience. For example, instead of the message "4 people are viewing this document",
+ * you might display "John, Kate and 2 others are viewing this document".
+ * The offset attribute allows you to offset a number by any desired value.
+ * Let's take a look at an example:
+ *
+ * ```html
+ * <ng-pluralize count="personCount" offset=2
+ * when="{'0': 'Nobody is viewing.',
+ * '1': '{{person1}} is viewing.',
+ * '2': '{{person1}} and {{person2}} are viewing.',
+ * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
+ * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
+ * </ng-pluralize>
+ * ```
+ *
+ * Notice that we are still using two plural categories(one, other), but we added
+ * three explicit number rules 0, 1 and 2.
+ * When one person, perhaps John, views the document, "John is viewing" will be shown.
+ * When three people view the document, no explicit number rule is found, so
+ * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
+ * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
+ * is shown.
+ *
+ * Note that when you specify offsets, you must provide explicit number rules for
+ * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
+ * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
+ * plural categories "one" and "other".
+ *
+ * @param {string|expression} count The variable to be bound to.
+ * @param {string} when The mapping between plural category to its corresponding strings.
+ * @param {number=} offset Offset to deduct from the total number.
+ *
+ * @example
+ <example module="pluralizeExample">
+ <file name="index.html">
+ <script>
+ angular.module('pluralizeExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.person1 = 'Igor';
+ $scope.person2 = 'Misko';
+ $scope.personCount = 1;
+ }]);
+ </script>
+ <div ng-controller="ExampleController">
+ <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
+ <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
+ <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
+
+ <!--- Example with simple pluralization rules for en locale --->
+ Without Offset:
+ <ng-pluralize count="personCount"
+ when="{'0': 'Nobody is viewing.',
+ 'one': '1 person is viewing.',
+ 'other': '{} people are viewing.'}">
+ </ng-pluralize><br>
+
+ <!--- Example with offset --->
+ With Offset(2):
+ <ng-pluralize count="personCount" offset=2
+ when="{'0': 'Nobody is viewing.',
+ '1': '{{person1}} is viewing.',
+ '2': '{{person1}} and {{person2}} are viewing.',
+ 'one': '{{person1}}, {{person2}} and one other person are viewing.',
+ 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
+ </ng-pluralize>
+ </div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should show correct pluralized string', function() {
+ var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
+ var withOffset = element.all(by.css('ng-pluralize')).get(1);
+ var countInput = element(by.model('personCount'));
+
+ expect(withoutOffset.getText()).toEqual('1 person is viewing.');
+ expect(withOffset.getText()).toEqual('Igor is viewing.');
+
+ countInput.clear();
+ countInput.sendKeys('0');
+
+ expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
+ expect(withOffset.getText()).toEqual('Nobody is viewing.');
+
+ countInput.clear();
+ countInput.sendKeys('2');
+
+ expect(withoutOffset.getText()).toEqual('2 people are viewing.');
+ expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
+
+ countInput.clear();
+ countInput.sendKeys('3');
+
+ expect(withoutOffset.getText()).toEqual('3 people are viewing.');
+ expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
+
+ countInput.clear();
+ countInput.sendKeys('4');
+
+ expect(withoutOffset.getText()).toEqual('4 people are viewing.');
+ expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
+ });
+ it('should show data-bound names', function() {
+ var withOffset = element.all(by.css('ng-pluralize')).get(1);
+ var personCount = element(by.model('personCount'));
+ var person1 = element(by.model('person1'));
+ var person2 = element(by.model('person2'));
+ personCount.clear();
+ personCount.sendKeys('4');
+ person1.clear();
+ person1.sendKeys('Di');
+ person2.clear();
+ person2.sendKeys('Vojta');
+ expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
+ });
+ </file>
+ </example>
+ */
+var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
+ var BRACE = /{}/g,
+ IS_WHEN = /^when(Minus)?(.+)$/;
+
+ return {
+ link: function(scope, element, attr) {
+ var numberExp = attr.count,
+ whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
+ offset = attr.offset || 0,
+ whens = scope.$eval(whenExp) || {},
+ whensExpFns = {},
+ startSymbol = $interpolate.startSymbol(),
+ endSymbol = $interpolate.endSymbol(),
+ braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
+ watchRemover = angular.noop,
+ lastCount;
+
+ forEach(attr, function(expression, attributeName) {
+ var tmpMatch = IS_WHEN.exec(attributeName);
+ if (tmpMatch) {
+ var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
+ whens[whenKey] = element.attr(attr.$attr[attributeName]);
+ }
+ });
+ forEach(whens, function(expression, key) {
+ whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
+
+ });
+
+ scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
+ var count = parseFloat(newVal);
+ var countIsNaN = isNaN(count);
+
+ if (!countIsNaN && !(count in whens)) {
+ // If an explicit number rule such as 1, 2, 3... is defined, just use it.
+ // Otherwise, check it against pluralization rules in $locale service.
+ count = $locale.pluralCat(count - offset);
+ }
+
+ // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
+ // In JS `NaN !== NaN`, so we have to exlicitly check.
+ if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
+ watchRemover();
+ var whenExpFn = whensExpFns[count];
+ if (isUndefined(whenExpFn)) {
+ if (newVal != null) {
+ $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
+ }
+ watchRemover = noop;
+ updateElementText();
+ } else {
+ watchRemover = scope.$watch(whenExpFn, updateElementText);
+ }
+ lastCount = count;
+ }
+ });
+
+ function updateElementText(newText) {
+ element.text(newText || '');
+ }
+ }
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ngRepeat
+ * @multiElement
+ *
+ * @description
+ * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
+ * instance gets its own scope, where the given loop variable is set to the current collection item,
+ * and `$index` is set to the item index or key.
+ *
+ * Special properties are exposed on the local scope of each template instance, including:
+ *
+ * | Variable | Type | Details |
+ * |-----------|-----------------|-----------------------------------------------------------------------------|
+ * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
+ * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
+ * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
+ * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
+ * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
+ * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
+ *
+ * <div class="alert alert-info">
+ * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
+ * This may be useful when, for instance, nesting ngRepeats.
+ * </div>
+ *
+ *
+ * # Iterating over object properties
+ *
+ * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
+ * syntax:
+ *
+ * ```js
+ * <div ng-repeat="(key, value) in myObj"> ... </div>
+ * ```
+ *
+ * You need to be aware that the JavaScript specification does not define the order of keys
+ * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
+ * used to sort the keys alphabetically.)
+ *
+ * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
+ * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
+ * keys in the order in which they were defined, although there are exceptions when keys are deleted
+ * and reinstated. See the [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
+ *
+ * If this is not desired, the recommended workaround is to convert your object into an array
+ * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
+ * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
+ * or implement a `$watch` on the object yourself.
+ *
+ *
+ * # Tracking and Duplicates
+ *
+ * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
+ * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
+ *
+ * * When an item is added, a new instance of the template is added to the DOM.
+ * * When an item is removed, its template instance is removed from the DOM.
+ * * When items are reordered, their respective templates are reordered in the DOM.
+ *
+ * To minimize creation of DOM elements, `ngRepeat` uses a function
+ * to "keep track" of all items in the collection and their corresponding DOM elements.
+ * For example, if an item is added to the collection, ngRepeat will know that all other items
+ * already have DOM elements, and will not re-render them.
+ *
+ * The default tracking function (which tracks items by their identity) does not allow
+ * duplicate items in arrays. This is because when there are duplicates, it is not possible
+ * to maintain a one-to-one mapping between collection items and DOM elements.
+ *
+ * If you do need to repeat duplicate items, you can substitute the default tracking behavior
+ * with your own using the `track by` expression.
+ *
+ * For example, you may track items by the index of each item in the collection, using the
+ * special scope property `$index`:
+ * ```html
+ * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
+ * {{n}}
+ * </div>
+ * ```
+ *
+ * You may also use arbitrary expressions in `track by`, including references to custom functions
+ * on the scope:
+ * ```html
+ * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
+ * {{n}}
+ * </div>
+ * ```
+ *
+ * <div class="alert alert-success">
+ * If you are working with objects that have an identifier property, you should track
+ * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
+ * will not have to rebuild the DOM elements for items it has already rendered, even if the
+ * JavaScript objects in the collection have been substituted for new ones. For large collections,
+ * this signifincantly improves rendering performance. If you don't have a unique identifier,
+ * `track by $index` can also provide a performance boost.
+ * </div>
+ * ```html
+ * <div ng-repeat="model in collection track by model.id">
+ * {{model.name}}
+ * </div>
+ * ```
+ *
+ * When no `track by` expression is provided, it is equivalent to tracking by the built-in
+ * `$id` function, which tracks items by their identity:
+ * ```html
+ * <div ng-repeat="obj in collection track by $id(obj)">
+ * {{obj.prop}}
+ * </div>
+ * ```
+ *
+ * <div class="alert alert-warning">
+ * **Note:** `track by` must always be the last expression:
+ * </div>
+ * ```
+ * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
+ * {{model.name}}
+ * </div>
+ * ```
+ *
+ * # Special repeat start and end points
+ * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
+ * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
+ * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
+ * up to and including the ending HTML tag where **ng-repeat-end** is placed.
+ *
+ * The example below makes use of this feature:
+ * ```html
+ * <header ng-repeat-start="item in items">
+ * Header {{ item }}
+ * </header>
+ * <div class="body">
+ * Body {{ item }}
+ * </div>
+ * <footer ng-repeat-end>
+ * Footer {{ item }}
+ * </footer>
+ * ```
+ *
+ * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
+ * ```html
+ * <header>
+ * Header A
+ * </header>
+ * <div class="body">
+ * Body A
+ * </div>
+ * <footer>
+ * Footer A
+ * </footer>
+ * <header>
+ * Header B
+ * </header>
+ * <div class="body">
+ * Body B
+ * </div>
+ * <footer>
+ * Footer B
+ * </footer>
+ * ```
+ *
+ * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
+ * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
+ *
+ * @animations
+ * **.enter** - when a new item is added to the list or when an item is revealed after a filter
+ *
+ * **.leave** - when an item is removed from the list or when an item is filtered out
+ *
+ * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
+ *
+ * @element ANY
+ * @scope
+ * @priority 1000
+ * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
+ * formats are currently supported:
+ *
+ * * `variable in expression` – where variable is the user defined loop variable and `expression`
+ * is a scope expression giving the collection to enumerate.
+ *
+ * For example: `album in artist.albums`.
+ *
+ * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
+ * and `expression` is the scope expression giving the collection to enumerate.
+ *
+ * For example: `(name, age) in {'adam':10, 'amalie':12}`.
+ *
+ * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
+ * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
+ * is specified, ng-repeat associates elements by identity. It is an error to have
+ * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
+ * mapped to the same DOM element, which is not possible.)
+ *
+ * Note that the tracking expression must come last, after any filters, and the alias expression.
+ *
+ * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
+ * will be associated by item identity in the array.
+ *
+ * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
+ * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
+ * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
+ * element in the same way in the DOM.
+ *
+ * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
+ * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
+ * property is same.
+ *
+ * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
+ * to items in conjunction with a tracking expression.
+ *
+ * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
+ * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
+ * when a filter is active on the repeater, but the filtered result set is empty.
+ *
+ * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
+ * the items have been processed through the filter.
+ *
+ * Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end
+ * (and not as operator, inside an expression).
+ *
+ * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
+ *
+ * @example
+ * This example initializes the scope to a list of names and
+ * then uses `ngRepeat` to display every person:
+ <example module="ngAnimate" deps="angular-animate.js" animations="true">
+ <file name="index.html">
+ <div ng-init="friends = [
+ {name:'John', age:25, gender:'boy'},
+ {name:'Jessie', age:30, gender:'girl'},
+ {name:'Johanna', age:28, gender:'girl'},
+ {name:'Joy', age:15, gender:'girl'},
+ {name:'Mary', age:28, gender:'girl'},
+ {name:'Peter', age:95, gender:'boy'},
+ {name:'Sebastian', age:50, gender:'boy'},
+ {name:'Erika', age:27, gender:'girl'},
+ {name:'Patrick', age:40, gender:'boy'},
+ {name:'Samantha', age:60, gender:'girl'}
+ ]">
+ I have {{friends.length}} friends. They are:
+ <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
+ <ul class="example-animate-container">
+ <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
+ [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
+ </li>
+ <li class="animate-repeat" ng-if="results.length == 0">
+ <strong>No results found...</strong>
+ </li>
+ </ul>
+ </div>
+ </file>
+ <file name="animations.css">
+ .example-animate-container {
+ background:white;
+ border:1px solid black;
+ list-style:none;
+ margin:0;
+ padding:0 10px;
+ }
+
+ .animate-repeat {
+ line-height:40px;
+ list-style:none;
+ box-sizing:border-box;
+ }
+
+ .animate-repeat.ng-move,
+ .animate-repeat.ng-enter,
+ .animate-repeat.ng-leave {
+ transition:all linear 0.5s;
+ }
+
+ .animate-repeat.ng-leave.ng-leave-active,
+ .animate-repeat.ng-move,
+ .animate-repeat.ng-enter {
+ opacity:0;
+ max-height:0;
+ }
+
+ .animate-repeat.ng-leave,
+ .animate-repeat.ng-move.ng-move-active,
+ .animate-repeat.ng-enter.ng-enter-active {
+ opacity:1;
+ max-height:40px;
+ }
+ </file>
+ <file name="protractor.js" type="protractor">
+ var friends = element.all(by.repeater('friend in friends'));
+
+ it('should render initial data set', function() {
+ expect(friends.count()).toBe(10);
+ expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
+ expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
+ expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
+ expect(element(by.binding('friends.length')).getText())
+ .toMatch("I have 10 friends. They are:");
+ });
+
+ it('should update repeater when filter predicate changes', function() {
+ expect(friends.count()).toBe(10);
+
+ element(by.model('q')).sendKeys('ma');
+
+ expect(friends.count()).toBe(2);
+ expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
+ expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
+ });
+ </file>
+ </example>
+ */
+var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
+ var NG_REMOVED = '$$NG_REMOVED';
+ var ngRepeatMinErr = minErr('ngRepeat');
+
+ var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
+ // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
+ scope[valueIdentifier] = value;
+ if (keyIdentifier) scope[keyIdentifier] = key;
+ scope.$index = index;
+ scope.$first = (index === 0);
+ scope.$last = (index === (arrayLength - 1));
+ scope.$middle = !(scope.$first || scope.$last);
+ // jshint bitwise: false
+ scope.$odd = !(scope.$even = (index&1) === 0);
+ // jshint bitwise: true
+ };
+
+ var getBlockStart = function(block) {
+ return block.clone[0];
+ };
+
+ var getBlockEnd = function(block) {
+ return block.clone[block.clone.length - 1];
+ };
+
+
+ return {
+ restrict: 'A',
+ multiElement: true,
+ transclude: 'element',
+ priority: 1000,
+ terminal: true,
+ $$tlb: true,
+ compile: function ngRepeatCompile($element, $attr) {
+ var expression = $attr.ngRepeat;
+ var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
+
+ var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
+
+ if (!match) {
+ throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
+ expression);
+ }
+
+ var lhs = match[1];
+ var rhs = match[2];
+ var aliasAs = match[3];
+ var trackByExp = match[4];
+
+ match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
+
+ if (!match) {
+ throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
+ lhs);
+ }
+ var valueIdentifier = match[3] || match[1];
+ var keyIdentifier = match[2];
+
+ if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
+ /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
+ throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
+ aliasAs);
+ }
+
+ var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
+ var hashFnLocals = {$id: hashKey};
+
+ if (trackByExp) {
+ trackByExpGetter = $parse(trackByExp);
+ } else {
+ trackByIdArrayFn = function(key, value) {
+ return hashKey(value);
+ };
+ trackByIdObjFn = function(key) {
+ return key;
+ };
+ }
+
+ return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
+
+ if (trackByExpGetter) {
+ trackByIdExpFn = function(key, value, index) {
+ // assign key, value, and $index to the locals so that they can be used in hash functions
+ if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
+ hashFnLocals[valueIdentifier] = value;
+ hashFnLocals.$index = index;
+ return trackByExpGetter($scope, hashFnLocals);
+ };
+ }
+
+ // Store a list of elements from previous run. This is a hash where key is the item from the
+ // iterator, and the value is objects with following properties.
+ // - scope: bound scope
+ // - element: previous element.
+ // - index: position
+ //
+ // We are using no-proto object so that we don't need to guard against inherited props via
+ // hasOwnProperty.
+ var lastBlockMap = createMap();
+
+ //watch props
+ $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
+ var index, length,
+ previousNode = $element[0], // node that cloned nodes should be inserted after
+ // initialized to the comment node anchor
+ nextNode,
+ // Same as lastBlockMap but it has the current state. It will become the
+ // lastBlockMap on the next iteration.
+ nextBlockMap = createMap(),
+ collectionLength,
+ key, value, // key/value of iteration
+ trackById,
+ trackByIdFn,
+ collectionKeys,
+ block, // last object information {scope, element, id}
+ nextBlockOrder,
+ elementsToRemove;
+
+ if (aliasAs) {
+ $scope[aliasAs] = collection;
+ }
+
+ if (isArrayLike(collection)) {
+ collectionKeys = collection;
+ trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
+ } else {
+ trackByIdFn = trackByIdExpFn || trackByIdObjFn;
+ // if object, extract keys, in enumeration order, unsorted
+ collectionKeys = [];
+ for (var itemKey in collection) {
+ if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
+ collectionKeys.push(itemKey);
+ }
+ }
+ }
+
+ collectionLength = collectionKeys.length;
+ nextBlockOrder = new Array(collectionLength);
+
+ // locate existing items
+ for (index = 0; index < collectionLength; index++) {
+ key = (collection === collectionKeys) ? index : collectionKeys[index];
+ value = collection[key];
+ trackById = trackByIdFn(key, value, index);
+ if (lastBlockMap[trackById]) {
+ // found previously seen block
+ block = lastBlockMap[trackById];
+ delete lastBlockMap[trackById];
+ nextBlockMap[trackById] = block;
+ nextBlockOrder[index] = block;
+ } else if (nextBlockMap[trackById]) {
+ // if collision detected. restore lastBlockMap and throw an error
+ forEach(nextBlockOrder, function(block) {
+ if (block && block.scope) lastBlockMap[block.id] = block;
+ });
+ throw ngRepeatMinErr('dupes',
+ "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
+ expression, trackById, value);
+ } else {
+ // new never before seen block
+ nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
+ nextBlockMap[trackById] = true;
+ }
+ }
+
+ // remove leftover items
+ for (var blockKey in lastBlockMap) {
+ block = lastBlockMap[blockKey];
+ elementsToRemove = getBlockNodes(block.clone);
+ $animate.leave(elementsToRemove);
+ if (elementsToRemove[0].parentNode) {
+ // if the element was not removed yet because of pending animation, mark it as deleted
+ // so that we can ignore it later
+ for (index = 0, length = elementsToRemove.length; index < length; index++) {
+ elementsToRemove[index][NG_REMOVED] = true;
+ }
+ }
+ block.scope.$destroy();
+ }
+
+ // we are not using forEach for perf reasons (trying to avoid #call)
+ for (index = 0; index < collectionLength; index++) {
+ key = (collection === collectionKeys) ? index : collectionKeys[index];
+ value = collection[key];
+ block = nextBlockOrder[index];
+
+ if (block.scope) {
+ // if we have already seen this object, then we need to reuse the
+ // associated scope/element
+
+ nextNode = previousNode;
+
+ // skip nodes that are already pending removal via leave animation
+ do {
+ nextNode = nextNode.nextSibling;
+ } while (nextNode && nextNode[NG_REMOVED]);
+
+ if (getBlockStart(block) != nextNode) {
+ // existing item which got moved
+ $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
+ }
+ previousNode = getBlockEnd(block);
+ updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
+ } else {
+ // new item which we don't know about
+ $transclude(function ngRepeatTransclude(clone, scope) {
+ block.scope = scope;
+ // http://jsperf.com/clone-vs-createcomment
+ var endNode = ngRepeatEndComment.cloneNode(false);
+ clone[clone.length++] = endNode;
+
+ // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
+ $animate.enter(clone, null, jqLite(previousNode));
+ previousNode = endNode;
+ // Note: We only need the first/last node of the cloned nodes.
+ // However, we need to keep the reference to the jqlite wrapper as it might be changed later
+ // by a directive with templateUrl when its template arrives.
+ block.clone = clone;
+ nextBlockMap[block.id] = block;
+ updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
+ });
+ }
+ }
+ lastBlockMap = nextBlockMap;
+ });
+ };
+ }
+ };
+}];
+
+var NG_HIDE_CLASS = 'ng-hide';
+var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
+/**
+ * @ngdoc directive
+ * @name ngShow
+ * @multiElement
+ *
+ * @description
+ * The `ngShow` directive shows or hides the given HTML element based on the expression
+ * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
+ * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
+ * in AngularJS and sets the display style to none (using an !important flag).
+ * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
+ *
+ * ```html
+ * <!-- when $scope.myValue is truthy (element is visible) -->
+ * <div ng-show="myValue"></div>
+ *
+ * <!-- when $scope.myValue is falsy (element is hidden) -->
+ * <div ng-show="myValue" class="ng-hide"></div>
+ * ```
+ *
+ * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
+ * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
+ * from the element causing the element not to appear hidden.
+ *
+ * ## Why is !important used?
+ *
+ * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
+ * can be easily overridden by heavier selectors. For example, something as simple
+ * as changing the display style on a HTML list item would make hidden elements appear visible.
+ * This also becomes a bigger issue when dealing with CSS frameworks.
+ *
+ * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
+ * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
+ * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
+ *
+ * ### Overriding `.ng-hide`
+ *
+ * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
+ * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
+ * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
+ * with extra animation classes that can be added.
+ *
+ * ```css
+ * .ng-hide:not(.ng-hide-animate) {
+ * /* this is just another form of hiding an element */
+ * display: block!important;
+ * position: absolute;
+ * top: -9999px;
+ * left: -9999px;
+ * }
+ * ```
+ *
+ * By default you don't need to override in CSS anything and the animations will work around the display style.
+ *
+ * ## A note about animations with `ngShow`
+ *
+ * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
+ * is true and false. This system works like the animation system present with ngClass except that
+ * you must also include the !important flag to override the display property
+ * so that you can perform an animation when the element is hidden during the time of the animation.
+ *
+ * ```css
+ * //
+ * //a working example can be found at the bottom of this page
+ * //
+ * .my-element.ng-hide-add, .my-element.ng-hide-remove {
+ * /* this is required as of 1.3x to properly
+ * apply all styling in a show/hide animation */
+ * transition: 0s linear all;
+ * }
+ *
+ * .my-element.ng-hide-add-active,
+ * .my-element.ng-hide-remove-active {
+ * /* the transition is defined in the active class */
+ * transition: 1s linear all;
+ * }
+ *
+ * .my-element.ng-hide-add { ... }
+ * .my-element.ng-hide-add.ng-hide-add-active { ... }
+ * .my-element.ng-hide-remove { ... }
+ * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
+ * ```
+ *
+ * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
+ * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
+ *
+ * @animations
+ * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
+ * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
+ *
+ * @element ANY
+ * @param {expression} ngShow If the {@link guide/expression expression} is truthy
+ * then the element is shown or hidden respectively.
+ *
+ * @example
+ <example module="ngAnimate" deps="angular-animate.js" animations="true">
+ <file name="index.html">
+ Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
+ <div>
+ Show:
+ <div class="check-element animate-show" ng-show="checked">
+ <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
+ </div>
+ </div>
+ <div>
+ Hide:
+ <div class="check-element animate-show" ng-hide="checked">
+ <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
+ </div>
+ </div>
+ </file>
+ <file name="glyphicons.css">
+ @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
+ </file>
+ <file name="animations.css">
+ .animate-show {
+ line-height: 20px;
+ opacity: 1;
+ padding: 10px;
+ border: 1px solid black;
+ background: white;
+ }
+
+ .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
+ transition: all linear 0.5s;
+ }
+
+ .animate-show.ng-hide {
+ line-height: 0;
+ opacity: 0;
+ padding: 0 10px;
+ }
+
+ .check-element {
+ padding: 10px;
+ border: 1px solid black;
+ background: white;
+ }
+ </file>
+ <file name="protractor.js" type="protractor">
+ var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
+ var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
+
+ it('should check ng-show / ng-hide', function() {
+ expect(thumbsUp.isDisplayed()).toBeFalsy();
+ expect(thumbsDown.isDisplayed()).toBeTruthy();
+
+ element(by.model('checked')).click();
+
+ expect(thumbsUp.isDisplayed()).toBeTruthy();
+ expect(thumbsDown.isDisplayed()).toBeFalsy();
+ });
+ </file>
+ </example>
+ */
+var ngShowDirective = ['$animate', function($animate) {
+ return {
+ restrict: 'A',
+ multiElement: true,
+ link: function(scope, element, attr) {
+ scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
+ // we're adding a temporary, animation-specific class for ng-hide since this way
+ // we can control when the element is actually displayed on screen without having
+ // to have a global/greedy CSS selector that breaks when other animations are run.
+ // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
+ $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
+ tempClasses: NG_HIDE_IN_PROGRESS_CLASS
+ });
+ });
+ }
+ };
+}];
+
+
+/**
+ * @ngdoc directive
+ * @name ngHide
+ * @multiElement
+ *
+ * @description
+ * The `ngHide` directive shows or hides the given HTML element based on the expression
+ * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
+ * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
+ * in AngularJS and sets the display style to none (using an !important flag).
+ * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
+ *
+ * ```html
+ * <!-- when $scope.myValue is truthy (element is hidden) -->
+ * <div ng-hide="myValue" class="ng-hide"></div>
+ *
+ * <!-- when $scope.myValue is falsy (element is visible) -->
+ * <div ng-hide="myValue"></div>
+ * ```
+ *
+ * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
+ * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
+ * from the element causing the element not to appear hidden.
+ *
+ * ## Why is !important used?
+ *
+ * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
+ * can be easily overridden by heavier selectors. For example, something as simple
+ * as changing the display style on a HTML list item would make hidden elements appear visible.
+ * This also becomes a bigger issue when dealing with CSS frameworks.
+ *
+ * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
+ * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
+ * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
+ *
+ * ### Overriding `.ng-hide`
+ *
+ * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
+ * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
+ * class in CSS:
+ *
+ * ```css
+ * .ng-hide {
+ * /* this is just another form of hiding an element */
+ * display: block!important;
+ * position: absolute;
+ * top: -9999px;
+ * left: -9999px;
+ * }
+ * ```
+ *
+ * By default you don't need to override in CSS anything and the animations will work around the display style.
+ *
+ * ## A note about animations with `ngHide`
+ *
+ * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
+ * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
+ * CSS class is added and removed for you instead of your own CSS class.
+ *
+ * ```css
+ * //
+ * //a working example can be found at the bottom of this page
+ * //
+ * .my-element.ng-hide-add, .my-element.ng-hide-remove {
+ * transition: 0.5s linear all;
+ * }
+ *
+ * .my-element.ng-hide-add { ... }
+ * .my-element.ng-hide-add.ng-hide-add-active { ... }
+ * .my-element.ng-hide-remove { ... }
+ * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
+ * ```
+ *
+ * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
+ * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
+ *
+ * @animations
+ * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
+ * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
+ *
+ * @element ANY
+ * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
+ * the element is shown or hidden respectively.
+ *
+ * @example
+ <example module="ngAnimate" deps="angular-animate.js" animations="true">
+ <file name="index.html">
+ Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
+ <div>
+ Show:
+ <div class="check-element animate-hide" ng-show="checked">
+ <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
+ </div>
+ </div>
+ <div>
+ Hide:
+ <div class="check-element animate-hide" ng-hide="checked">
+ <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
+ </div>
+ </div>
+ </file>
+ <file name="glyphicons.css">
+ @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
+ </file>
+ <file name="animations.css">
+ .animate-hide {
+ transition: all linear 0.5s;
+ line-height: 20px;
+ opacity: 1;
+ padding: 10px;
+ border: 1px solid black;
+ background: white;
+ }
+
+ .animate-hide.ng-hide {
+ line-height: 0;
+ opacity: 0;
+ padding: 0 10px;
+ }
+
+ .check-element {
+ padding: 10px;
+ border: 1px solid black;
+ background: white;
+ }
+ </file>
+ <file name="protractor.js" type="protractor">
+ var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
+ var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
+
+ it('should check ng-show / ng-hide', function() {
+ expect(thumbsUp.isDisplayed()).toBeFalsy();
+ expect(thumbsDown.isDisplayed()).toBeTruthy();
+
+ element(by.model('checked')).click();
+
+ expect(thumbsUp.isDisplayed()).toBeTruthy();
+ expect(thumbsDown.isDisplayed()).toBeFalsy();
+ });
+ </file>
+ </example>
+ */
+var ngHideDirective = ['$animate', function($animate) {
+ return {
+ restrict: 'A',
+ multiElement: true,
+ link: function(scope, element, attr) {
+ scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
+ // The comment inside of the ngShowDirective explains why we add and
+ // remove a temporary class for the show/hide animation
+ $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
+ tempClasses: NG_HIDE_IN_PROGRESS_CLASS
+ });
+ });
+ }
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name ngStyle
+ * @restrict AC
+ *
+ * @description
+ * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
+ *
+ * @element ANY
+ * @param {expression} ngStyle
+ *
+ * {@link guide/expression Expression} which evals to an
+ * object whose keys are CSS style names and values are corresponding values for those CSS
+ * keys.
+ *
+ * Since some CSS style names are not valid keys for an object, they must be quoted.
+ * See the 'background-color' style in the example below.
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <input type="button" value="set color" ng-click="myStyle={color:'red'}">
+ <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
+ <input type="button" value="clear" ng-click="myStyle={}">
+ <br/>
+ <span ng-style="myStyle">Sample Text</span>
+ <pre>myStyle={{myStyle}}</pre>
+ </file>
+ <file name="style.css">
+ span {
+ color: black;
+ }
+ </file>
+ <file name="protractor.js" type="protractor">
+ var colorSpan = element(by.css('span'));
+
+ it('should check ng-style', function() {
+ expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
+ element(by.css('input[value=\'set color\']')).click();
+ expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
+ element(by.css('input[value=clear]')).click();
+ expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
+ });
+ </file>
+ </example>
+ */
+var ngStyleDirective = ngDirective(function(scope, element, attr) {
+ scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
+ if (oldStyles && (newStyles !== oldStyles)) {
+ forEach(oldStyles, function(val, style) { element.css(style, '');});
+ }
+ if (newStyles) element.css(newStyles);
+ }, true);
+});
+
+/**
+ * @ngdoc directive
+ * @name ngSwitch
+ * @restrict EA
+ *
+ * @description
+ * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
+ * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
+ * as specified in the template.
+ *
+ * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
+ * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
+ * matches the value obtained from the evaluated expression. In other words, you define a container element
+ * (where you place the directive), place an expression on the **`on="..."` attribute**
+ * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
+ * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
+ * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
+ * attribute is displayed.
+ *
+ * <div class="alert alert-info">
+ * Be aware that the attribute values to match against cannot be expressions. They are interpreted
+ * as literal string values to match against.
+ * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
+ * value of the expression `$scope.someVal`.
+ * </div>
+
+ * @animations
+ * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
+ * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
+ *
+ * @usage
+ *
+ * ```
+ * <ANY ng-switch="expression">
+ * <ANY ng-switch-when="matchValue1">...</ANY>
+ * <ANY ng-switch-when="matchValue2">...</ANY>
+ * <ANY ng-switch-default>...</ANY>
+ * </ANY>
+ * ```
+ *
+ *
+ * @scope
+ * @priority 1200
+ * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
+ * On child elements add:
+ *
+ * * `ngSwitchWhen`: the case statement to match against. If match then this
+ * case will be displayed. If the same match appears multiple times, all the
+ * elements will be displayed.
+ * * `ngSwitchDefault`: the default case when no other case match. If there
+ * are multiple default cases, all of them will be displayed when no other
+ * case match.
+ *
+ *
+ * @example
+ <example module="switchExample" deps="angular-animate.js" animations="true">
+ <file name="index.html">
+ <div ng-controller="ExampleController">
+ <select ng-model="selection" ng-options="item for item in items">
+ </select>
+ <code>selection={{selection}}</code>
+ <hr/>
+ <div class="animate-switch-container"
+ ng-switch on="selection">
+ <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
+ <div class="animate-switch" ng-switch-when="home">Home Span</div>
+ <div class="animate-switch" ng-switch-default>default</div>
+ </div>
+ </div>
+ </file>
+ <file name="script.js">
+ angular.module('switchExample', ['ngAnimate'])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.items = ['settings', 'home', 'other'];
+ $scope.selection = $scope.items[0];
+ }]);
+ </file>
+ <file name="animations.css">
+ .animate-switch-container {
+ position:relative;
+ background:white;
+ border:1px solid black;
+ height:40px;
+ overflow:hidden;
+ }
+
+ .animate-switch {
+ padding:10px;
+ }
+
+ .animate-switch.ng-animate {
+ transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
+
+ position:absolute;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+ }
+
+ .animate-switch.ng-leave.ng-leave-active,
+ .animate-switch.ng-enter {
+ top:-50px;
+ }
+ .animate-switch.ng-leave,
+ .animate-switch.ng-enter.ng-enter-active {
+ top:0;
+ }
+ </file>
+ <file name="protractor.js" type="protractor">
+ var switchElem = element(by.css('[ng-switch]'));
+ var select = element(by.model('selection'));
+
+ it('should start in settings', function() {
+ expect(switchElem.getText()).toMatch(/Settings Div/);
+ });
+ it('should change to home', function() {
+ select.all(by.css('option')).get(1).click();
+ expect(switchElem.getText()).toMatch(/Home Span/);
+ });
+ it('should select default', function() {
+ select.all(by.css('option')).get(2).click();
+ expect(switchElem.getText()).toMatch(/default/);
+ });
+ </file>
+ </example>
+ */
+var ngSwitchDirective = ['$animate', function($animate) {
+ return {
+ require: 'ngSwitch',
+
+ // asks for $scope to fool the BC controller module
+ controller: ['$scope', function ngSwitchController() {
+ this.cases = {};
+ }],
+ link: function(scope, element, attr, ngSwitchController) {
+ var watchExpr = attr.ngSwitch || attr.on,
+ selectedTranscludes = [],
+ selectedElements = [],
+ previousLeaveAnimations = [],
+ selectedScopes = [];
+
+ var spliceFactory = function(array, index) {
+ return function() { array.splice(index, 1); };
+ };
+
+ scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
+ var i, ii;
+ for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
+ $animate.cancel(previousLeaveAnimations[i]);
+ }
+ previousLeaveAnimations.length = 0;
+
+ for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
+ var selected = getBlockNodes(selectedElements[i].clone);
+ selectedScopes[i].$destroy();
+ var promise = previousLeaveAnimations[i] = $animate.leave(selected);
+ promise.then(spliceFactory(previousLeaveAnimations, i));
+ }
+
+ selectedElements.length = 0;
+ selectedScopes.length = 0;
+
+ if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
+ forEach(selectedTranscludes, function(selectedTransclude) {
+ selectedTransclude.transclude(function(caseElement, selectedScope) {
+ selectedScopes.push(selectedScope);
+ var anchor = selectedTransclude.element;
+ caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
+ var block = { clone: caseElement };
+
+ selectedElements.push(block);
+ $animate.enter(caseElement, anchor.parent(), anchor);
+ });
+ });
+ }
+ });
+ }
+ };
+}];
+
+var ngSwitchWhenDirective = ngDirective({
+ transclude: 'element',
+ priority: 1200,
+ require: '^ngSwitch',
+ multiElement: true,
+ link: function(scope, element, attrs, ctrl, $transclude) {
+ ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
+ ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
+ }
+});
+
+var ngSwitchDefaultDirective = ngDirective({
+ transclude: 'element',
+ priority: 1200,
+ require: '^ngSwitch',
+ multiElement: true,
+ link: function(scope, element, attr, ctrl, $transclude) {
+ ctrl.cases['?'] = (ctrl.cases['?'] || []);
+ ctrl.cases['?'].push({ transclude: $transclude, element: element });
+ }
+});
+
+/**
+ * @ngdoc directive
+ * @name ngTransclude
+ * @restrict EAC
+ *
+ * @description
+ * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
+ *
+ * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
+ *
+ * @element ANY
+ *
+ * @example
+ <example module="transcludeExample">
+ <file name="index.html">
+ <script>
+ angular.module('transcludeExample', [])
+ .directive('pane', function(){
+ return {
+ restrict: 'E',
+ transclude: true,
+ scope: { title:'@' },
+ template: '<div style="border: 1px solid black;">' +
+ '<div style="background-color: gray">{{title}}</div>' +
+ '<ng-transclude></ng-transclude>' +
+ '</div>'
+ };
+ })
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.title = 'Lorem Ipsum';
+ $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
+ }]);
+ </script>
+ <div ng-controller="ExampleController">
+ <input ng-model="title" aria-label="title"> <br/>
+ <textarea ng-model="text" aria-label="text"></textarea> <br/>
+ <pane title="{{title}}">{{text}}</pane>
+ </div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should have transcluded', function() {
+ var titleElement = element(by.model('title'));
+ titleElement.clear();
+ titleElement.sendKeys('TITLE');
+ var textElement = element(by.model('text'));
+ textElement.clear();
+ textElement.sendKeys('TEXT');
+ expect(element(by.binding('title')).getText()).toEqual('TITLE');
+ expect(element(by.binding('text')).getText()).toEqual('TEXT');
+ });
+ </file>
+ </example>
+ *
+ */
+var ngTranscludeDirective = ngDirective({
+ restrict: 'EAC',
+ link: function($scope, $element, $attrs, controller, $transclude) {
+ if (!$transclude) {
+ throw minErr('ngTransclude')('orphan',
+ 'Illegal use of ngTransclude directive in the template! ' +
+ 'No parent directive that requires a transclusion found. ' +
+ 'Element: {0}',
+ startingTag($element));
+ }
+
+ $transclude(function(clone) {
+ $element.empty();
+ $element.append(clone);
+ });
+ }
+});
+
+/**
+ * @ngdoc directive
+ * @name script
+ * @restrict E
+ *
+ * @description
+ * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
+ * template can be used by {@link ng.directive:ngInclude `ngInclude`},
+ * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
+ * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
+ * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
+ *
+ * @param {string} type Must be set to `'text/ng-template'`.
+ * @param {string} id Cache name of the template.
+ *
+ * @example
+ <example>
+ <file name="index.html">
+ <script type="text/ng-template" id="/tpl.html">
+ Content of the template.
+ </script>
+
+ <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
+ <div id="tpl-content" ng-include src="currentTpl"></div>
+ </file>
+ <file name="protractor.js" type="protractor">
+ it('should load template defined inside script tag', function() {
+ element(by.css('#tpl-link')).click();
+ expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
+ });
+ </file>
+ </example>
+ */
+var scriptDirective = ['$templateCache', function($templateCache) {
+ return {
+ restrict: 'E',
+ terminal: true,
+ compile: function(element, attr) {
+ if (attr.type == 'text/ng-template') {
+ var templateUrl = attr.id,
+ text = element[0].text;
+
+ $templateCache.put(templateUrl, text);
+ }
+ }
+ };
+}];
+
+var noopNgModelController = { $setViewValue: noop, $render: noop };
+
+function chromeHack(optionElement) {
+ // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
+ // Adding an <option selected="selected"> element to a <select required="required"> should
+ // automatically select the new element
+ if (optionElement[0].hasAttribute('selected')) {
+ optionElement[0].selected = true;
+ }
+}
+
+/**
+ * @ngdoc type
+ * @name select.SelectController
+ * @description
+ * The controller for the `<select>` directive. This provides support for reading
+ * and writing the selected value(s) of the control and also coordinates dynamically
+ * added `<option>` elements, perhaps by an `ngRepeat` directive.
+ */
+var SelectController =
+ ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
+
+ var self = this,
+ optionsMap = new HashMap();
+
+ // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
+ self.ngModelCtrl = noopNgModelController;
+
+ // The "unknown" option is one that is prepended to the list if the viewValue
+ // does not match any of the options. When it is rendered the value of the unknown
+ // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
+ //
+ // We can't just jqLite('<option>') since jqLite is not smart enough
+ // to create it in <select> and IE barfs otherwise.
+ self.unknownOption = jqLite(document.createElement('option'));
+ self.renderUnknownOption = function(val) {
+ var unknownVal = '? ' + hashKey(val) + ' ?';
+ self.unknownOption.val(unknownVal);
+ $element.prepend(self.unknownOption);
+ $element.val(unknownVal);
+ };
+
+ $scope.$on('$destroy', function() {
+ // disable unknown option so that we don't do work when the whole select is being destroyed
+ self.renderUnknownOption = noop;
+ });
+
+ self.removeUnknownOption = function() {
+ if (self.unknownOption.parent()) self.unknownOption.remove();
+ };
+
+
+ // Read the value of the select control, the implementation of this changes depending
+ // upon whether the select can have multiple values and whether ngOptions is at work.
+ self.readValue = function readSingleValue() {
+ self.removeUnknownOption();
+ return $element.val();
+ };
+
+
+ // Write the value to the select control, the implementation of this changes depending
+ // upon whether the select can have multiple values and whether ngOptions is at work.
+ self.writeValue = function writeSingleValue(value) {
+ if (self.hasOption(value)) {
+ self.removeUnknownOption();
+ $element.val(value);
+ if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
+ } else {
+ if (value == null && self.emptyOption) {
+ self.removeUnknownOption();
+ $element.val('');
+ } else {
+ self.renderUnknownOption(value);
+ }
+ }
+ };
+
+
+ // Tell the select control that an option, with the given value, has been added
+ self.addOption = function(value, element) {
+ assertNotHasOwnProperty(value, '"option value"');
+ if (value === '') {
+ self.emptyOption = element;
+ }
+ var count = optionsMap.get(value) || 0;
+ optionsMap.put(value, count + 1);
+ self.ngModelCtrl.$render();
+ chromeHack(element);
+ };
+
+ // Tell the select control that an option, with the given value, has been removed
+ self.removeOption = function(value) {
+ var count = optionsMap.get(value);
+ if (count) {
+ if (count === 1) {
+ optionsMap.remove(value);
+ if (value === '') {
+ self.emptyOption = undefined;
+ }
+ } else {
+ optionsMap.put(value, count - 1);
+ }
+ }
+ };
+
+ // Check whether the select control has an option matching the given value
+ self.hasOption = function(value) {
+ return !!optionsMap.get(value);
+ };
+
+
+ self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
+
+ if (interpolateValueFn) {
+ // The value attribute is interpolated
+ var oldVal;
+ optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
+ if (isDefined(oldVal)) {
+ self.removeOption(oldVal);
+ }
+ oldVal = newVal;
+ self.addOption(newVal, optionElement);
+ });
+ } else if (interpolateTextFn) {
+ // The text content is interpolated
+ optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
+ optionAttrs.$set('value', newVal);
+ if (oldVal !== newVal) {
+ self.removeOption(oldVal);
+ }
+ self.addOption(newVal, optionElement);
+ });
+ } else {
+ // The value attribute is static
+ self.addOption(optionAttrs.value, optionElement);
+ }
+
+ optionElement.on('$destroy', function() {
+ self.removeOption(optionAttrs.value);
+ self.ngModelCtrl.$render();
+ });
+ };
+}];
+
+/**
+ * @ngdoc directive
+ * @name select
+ * @restrict E
+ *
+ * @description
+ * HTML `SELECT` element with angular data-binding.
+ *
+ * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
+ * between the scope and the `<select>` control (including setting default values).
+ * Ìt also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
+ * {@link ngOptions `ngOptions`} directives.
+ *
+ * When an item in the `<select>` menu is selected, the value of the selected option will be bound
+ * to the model identified by the `ngModel` directive. With static or repeated options, this is
+ * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
+ * If you want dynamic value attributes, you can use interpolation inside the value attribute.
+ *
+ * <div class="alert alert-warning">
+ * Note that the value of a `select` directive used without `ngOptions` is always a string.
+ * When the model needs to be bound to a non-string value, you must either explictly convert it
+ * using a directive (see example below) or use `ngOptions` to specify the set of options.
+ * This is because an option element can only be bound to string values at present.
+ * </div>
+ *
+ * If the viewValue of `ngModel` does not match any of the options, then the control
+ * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
+ *
+ * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
+ * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
+ * option. See example below for demonstration.
+ *
+ * <div class="alert alert-info">
+ * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
+ * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
+ * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
+ * comprehension expression, and additionally in reducing memory and increasing speed by not creating
+ * a new scope for each repeated instance.
+ * </div>
+ *
+ *
+ * @param {string} ngModel Assignable angular expression to data-bind to.
+ * @param {string=} name Property name of the form under which the control is published.
+ * @param {string=} multiple Allows multiple options to be selected. The selected values will be
+ * bound to the model as an array.
+ * @param {string=} required Sets `required` validation error key if the value is not entered.
+ * @param {string=} ngRequired Adds required attribute and required validation constraint to
+ * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
+ * when you want to data-bind to the required attribute.
+ * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
+ * interaction with the select element.
+ * @param {string=} ngOptions sets the options that the select is populated with and defines what is
+ * set on the model on selection. See {@link ngOptions `ngOptions`}.
+ *
+ * @example
+ * ### Simple `select` elements with static options
+ *
+ * <example name="static-select" module="staticSelect">
+ * <file name="index.html">
+ * <div ng-controller="ExampleController">
+ * <form name="myForm">
+ * <label for="singleSelect"> Single select: </label><br>
+ * <select name="singleSelect" ng-model="data.singleSelect">
+ * <option value="option-1">Option 1</option>
+ * <option value="option-2">Option 2</option>
+ * </select><br>
+ *
+ * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
+ * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
+ * <option value="">---Please select---</option> <!-- not selected / blank option -->
+ * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
+ * <option value="option-2">Option 2</option>
+ * </select><br>
+ * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
+ * <tt>singleSelect = {{data.singleSelect}}</tt>
+ *
+ * <hr>
+ * <label for="multipleSelect"> Multiple select: </label><br>
+ * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
+ * <option value="option-1">Option 1</option>
+ * <option value="option-2">Option 2</option>
+ * <option value="option-3">Option 3</option>
+ * </select><br>
+ * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
+ * </form>
+ * </div>
+ * </file>
+ * <file name="app.js">
+ * angular.module('staticSelect', [])
+ * .controller('ExampleController', ['$scope', function($scope) {
+ * $scope.data = {
+ * singleSelect: null,
+ * multipleSelect: [],
+ * option1: 'option-1',
+ * };
+ *
+ * $scope.forceUnknownOption = function() {
+ * $scope.data.singleSelect = 'nonsense';
+ * };
+ * }]);
+ * </file>
+ *</example>
+ *
+ * ### Using `ngRepeat` to generate `select` options
+ * <example name="ngrepeat-select" module="ngrepeatSelect">
+ * <file name="index.html">
+ * <div ng-controller="ExampleController">
+ * <form name="myForm">
+ * <label for="repeatSelect"> Repeat select: </label>
+ * <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
+ * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
+ * </select>
+ * </form>
+ * <hr>
+ * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
+ * </div>
+ * </file>
+ * <file name="app.js">
+ * angular.module('ngrepeatSelect', [])
+ * .controller('ExampleController', ['$scope', function($scope) {
+ * $scope.data = {
+ * repeatSelect: null,
+ * availableOptions: [
+ * {id: '1', name: 'Option A'},
+ * {id: '2', name: 'Option B'},
+ * {id: '3', name: 'Option C'}
+ * ],
+ * };
+ * }]);
+ * </file>
+ *</example>
+ *
+ *
+ * ### Using `select` with `ngOptions` and setting a default value
+ * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
+ *
+ * <example name="select-with-default-values" module="defaultValueSelect">
+ * <file name="index.html">
+ * <div ng-controller="ExampleController">
+ * <form name="myForm">
+ * <label for="mySelect">Make a choice:</label>
+ * <select name="mySelect" id="mySelect"
+ * ng-options="option.name for option in data.availableOptions track by option.id"
+ * ng-model="data.selectedOption"></select>
+ * </form>
+ * <hr>
+ * <tt>option = {{data.selectedOption}}</tt><br/>
+ * </div>
+ * </file>
+ * <file name="app.js">
+ * angular.module('defaultValueSelect', [])
+ * .controller('ExampleController', ['$scope', function($scope) {
+ * $scope.data = {
+ * availableOptions: [
+ * {id: '1', name: 'Option A'},
+ * {id: '2', name: 'Option B'},
+ * {id: '3', name: 'Option C'}
+ * ],
+ * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
+ * };
+ * }]);
+ * </file>
+ *</example>
+ *
+ *
+ * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
+ *
+ * <example name="select-with-non-string-options" module="nonStringSelect">
+ * <file name="index.html">
+ * <select ng-model="model.id" convert-to-number>
+ * <option value="0">Zero</option>
+ * <option value="1">One</option>
+ * <option value="2">Two</option>
+ * </select>
+ * {{ model }}
+ * </file>
+ * <file name="app.js">
+ * angular.module('nonStringSelect', [])
+ * .run(function($rootScope) {
+ * $rootScope.model = { id: 2 };
+ * })
+ * .directive('convertToNumber', function() {
+ * return {
+ * require: 'ngModel',
+ * link: function(scope, element, attrs, ngModel) {
+ * ngModel.$parsers.push(function(val) {
+ * return parseInt(val, 10);
+ * });
+ * ngModel.$formatters.push(function(val) {
+ * return '' + val;
+ * });
+ * }
+ * };
+ * });
+ * </file>
+ * <file name="protractor.js" type="protractor">
+ * it('should initialize to model', function() {
+ * var select = element(by.css('select'));
+ * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
+ * });
+ * </file>
+ * </example>
+ *
+ */
+var selectDirective = function() {
+
+ return {
+ restrict: 'E',
+ require: ['select', '?ngModel'],
+ controller: SelectController,
+ priority: 1,
+ link: {
+ pre: selectPreLink
+ }
+ };
+
+ function selectPreLink(scope, element, attr, ctrls) {
+
+ // if ngModel is not defined, we don't need to do anything
+ var ngModelCtrl = ctrls[1];
+ if (!ngModelCtrl) return;
+
+ var selectCtrl = ctrls[0];
+
+ selectCtrl.ngModelCtrl = ngModelCtrl;
+
+ // We delegate rendering to the `writeValue` method, which can be changed
+ // if the select can have multiple selected values or if the options are being
+ // generated by `ngOptions`
+ ngModelCtrl.$render = function() {
+ selectCtrl.writeValue(ngModelCtrl.$viewValue);
+ };
+
+ // When the selected item(s) changes we delegate getting the value of the select control
+ // to the `readValue` method, which can be changed if the select can have multiple
+ // selected values or if the options are being generated by `ngOptions`
+ element.on('change', function() {
+ scope.$apply(function() {
+ ngModelCtrl.$setViewValue(selectCtrl.readValue());
+ });
+ });
+
+ // If the select allows multiple values then we need to modify how we read and write
+ // values from and to the control; also what it means for the value to be empty and
+ // we have to add an extra watch since ngModel doesn't work well with arrays - it
+ // doesn't trigger rendering if only an item in the array changes.
+ if (attr.multiple) {
+
+ // Read value now needs to check each option to see if it is selected
+ selectCtrl.readValue = function readMultipleValue() {
+ var array = [];
+ forEach(element.find('option'), function(option) {
+ if (option.selected) {
+ array.push(option.value);
+ }
+ });
+ return array;
+ };
+
+ // Write value now needs to set the selected property of each matching option
+ selectCtrl.writeValue = function writeMultipleValue(value) {
+ var items = new HashMap(value);
+ forEach(element.find('option'), function(option) {
+ option.selected = isDefined(items.get(option.value));
+ });
+ };
+
+ // we have to do it on each watch since ngModel watches reference, but
+ // we need to work of an array, so we need to see if anything was inserted/removed
+ var lastView, lastViewRef = NaN;
+ scope.$watch(function selectMultipleWatch() {
+ if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
+ lastView = shallowCopy(ngModelCtrl.$viewValue);
+ ngModelCtrl.$render();
+ }
+ lastViewRef = ngModelCtrl.$viewValue;
+ });
+
+ // If we are a multiple select then value is now a collection
+ // so the meaning of $isEmpty changes
+ ngModelCtrl.$isEmpty = function(value) {
+ return !value || value.length === 0;
+ };
+
+ }
+ }
+};
+
+
+// The option directive is purely designed to communicate the existence (or lack of)
+// of dynamically created (and destroyed) option elements to their containing select
+// directive via its controller.
+var optionDirective = ['$interpolate', function($interpolate) {
+ return {
+ restrict: 'E',
+ priority: 100,
+ compile: function(element, attr) {
+
+ if (isDefined(attr.value)) {
+ // If the value attribute is defined, check if it contains an interpolation
+ var interpolateValueFn = $interpolate(attr.value, true);
+ } else {
+ // If the value attribute is not defined then we fall back to the
+ // text content of the option element, which may be interpolated
+ var interpolateTextFn = $interpolate(element.text(), true);
+ if (!interpolateTextFn) {
+ attr.$set('value', element.text());
+ }
+ }
+
+ return function(scope, element, attr) {
+
+ // This is an optimization over using ^^ since we don't want to have to search
+ // all the way to the root of the DOM for every single option element
+ var selectCtrlName = '$selectController',
+ parent = element.parent(),
+ selectCtrl = parent.data(selectCtrlName) ||
+ parent.parent().data(selectCtrlName); // in case we are in optgroup
+
+ if (selectCtrl) {
+ selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
+ }
+ };
+ }
+ };
+}];
+
+var styleDirective = valueFn({
+ restrict: 'E',
+ terminal: false
+});
+
+var requiredDirective = function() {
+ return {
+ restrict: 'A',
+ require: '?ngModel',
+ link: function(scope, elm, attr, ctrl) {
+ if (!ctrl) return;
+ attr.required = true; // force truthy in case we are on non input element
+
+ ctrl.$validators.required = function(modelValue, viewValue) {
+ return !attr.required || !ctrl.$isEmpty(viewValue);
+ };
+
+ attr.$observe('required', function() {
+ ctrl.$validate();
+ });
+ }
+ };
+};
+
+
+var patternDirective = function() {
+ return {
+ restrict: 'A',
+ require: '?ngModel',
+ link: function(scope, elm, attr, ctrl) {
+ if (!ctrl) return;
+
+ var regexp, patternExp = attr.ngPattern || attr.pattern;
+ attr.$observe('pattern', function(regex) {
+ if (isString(regex) && regex.length > 0) {
+ regex = new RegExp('^' + regex + '$');
+ }
+
+ if (regex && !regex.test) {
+ throw minErr('ngPattern')('noregexp',
+ 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
+ regex, startingTag(elm));
+ }
+
+ regexp = regex || undefined;
+ ctrl.$validate();
+ });
+
+ ctrl.$validators.pattern = function(modelValue, viewValue) {
+ // HTML5 pattern constraint validates the input value, so we validate the viewValue
+ return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
+ };
+ }
+ };
+};
+
+
+var maxlengthDirective = function() {
+ return {
+ restrict: 'A',
+ require: '?ngModel',
+ link: function(scope, elm, attr, ctrl) {
+ if (!ctrl) return;
+
+ var maxlength = -1;
+ attr.$observe('maxlength', function(value) {
+ var intVal = toInt(value);
+ maxlength = isNaN(intVal) ? -1 : intVal;
+ ctrl.$validate();
+ });
+ ctrl.$validators.maxlength = function(modelValue, viewValue) {
+ return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
+ };
+ }
+ };
+};
+
+var minlengthDirective = function() {
+ return {
+ restrict: 'A',
+ require: '?ngModel',
+ link: function(scope, elm, attr, ctrl) {
+ if (!ctrl) return;
+
+ var minlength = 0;
+ attr.$observe('minlength', function(value) {
+ minlength = toInt(value) || 0;
+ ctrl.$validate();
+ });
+ ctrl.$validators.minlength = function(modelValue, viewValue) {
+ return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
+ };
+ }
+ };
+};
+
+if (window.angular.bootstrap) {
+ //AngularJS is already loaded, so we can return here...
+ console.log('WARNING: Tried to load angular more than once.');
+ return;
+}
+
+//try to bind to jquery now so that one can write jqLite(document).ready()
+//but we will rebind on bootstrap again.
+bindJQuery();
+
+publishExternalAPI(angular);
+
+angular.module("ngLocale", [], ["$provide", function($provide) {
+var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
+function getDecimals(n) {
+ n = n + '';
+ var i = n.indexOf('.');
+ return (i == -1) ? 0 : n.length - i - 1;
+}
+
+function getVF(n, opt_precision) {
+ var v = opt_precision;
+
+ if (undefined === v) {
+ v = Math.min(getDecimals(n), 3);
+ }
+
+ var base = Math.pow(10, v);
+ var f = ((n * base) | 0) % base;
+ return {v: v, f: f};
+}
+
+$provide.value("$locale", {
+ "DATETIME_FORMATS": {
+ "AMPMS": [
+ "AM",
+ "PM"
+ ],
+ "DAY": [
+ "Sunday",
+ "Monday",
+ "Tuesday",
+ "Wednesday",
+ "Thursday",
+ "Friday",
+ "Saturday"
+ ],
+ "ERANAMES": [
+ "Before Christ",
+ "Anno Domini"
+ ],
+ "ERAS": [
+ "BC",
+ "AD"
+ ],
+ "FIRSTDAYOFWEEK": 6,
+ "MONTH": [
+ "January",
+ "February",
+ "March",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December"
+ ],
+ "SHORTDAY": [
+ "Sun",
+ "Mon",
+ "Tue",
+ "Wed",
+ "Thu",
+ "Fri",
+ "Sat"
+ ],
+ "SHORTMONTH": [
+ "Jan",
+ "Feb",
+ "Mar",
+ "Apr",
+ "May",
+ "Jun",
+ "Jul",
+ "Aug",
+ "Sep",
+ "Oct",
+ "Nov",
+ "Dec"
+ ],
+ "WEEKENDRANGE": [
+ 5,
+ 6
+ ],
+ "fullDate": "EEEE, MMMM d, y",
+ "longDate": "MMMM d, y",
+ "medium": "MMM d, y h:mm:ss a",
+ "mediumDate": "MMM d, y",
+ "mediumTime": "h:mm:ss a",
+ "short": "M/d/yy h:mm a",
+ "shortDate": "M/d/yy",
+ "shortTime": "h:mm a"
+ },
+ "NUMBER_FORMATS": {
+ "CURRENCY_SYM": "$",
+ "DECIMAL_SEP": ".",
+ "GROUP_SEP": ",",
+ "PATTERNS": [
+ {
+ "gSize": 3,
+ "lgSize": 3,
+ "maxFrac": 3,
+ "minFrac": 0,
+ "minInt": 1,
+ "negPre": "-",
+ "negSuf": "",
+ "posPre": "",
+ "posSuf": ""
+ },
+ {
+ "gSize": 3,
+ "lgSize": 3,
+ "maxFrac": 2,
+ "minFrac": 2,
+ "minInt": 1,
+ "negPre": "-\u00a4",
+ "negSuf": "",
+ "posPre": "\u00a4",
+ "posSuf": ""
+ }
+ ]
+ },
+ "id": "en-us",
+ "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
+});
+}]);
+
+ jqLite(document).ready(function() {
+ angularInit(document, bootstrap);
+ });
+
+})(window, document);
+
+!window.angular.$$csp().noInlineStyle && 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>');
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular/angular.min.js b/xos-apps/auto-scale/gui/src/vendor/angular/angular.min.js
new file mode 100644
index 0000000..b4f9b07
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular/angular.min.js
@@ -0,0 +1,295 @@
+/*
+ AngularJS v1.4.8
+ (c) 2010-2015 Google, Inc. http://angularjs.org
+ License: MIT
+*/
+(function(S,X,u){'use strict';function G(a){return function(){var b=arguments[0],d;d="["+(a?a+":":"")+b+"] http://errors.angularjs.org/1.4.8/"+(a?a+"/":"")+b;for(b=1;b<arguments.length;b++){d=d+(1==b?"?":"&")+"p"+(b-1)+"=";var c=encodeURIComponent,e;e=arguments[b];e="function"==typeof e?e.toString().replace(/ \{[\s\S]*$/,""):"undefined"==typeof e?"undefined":"string"!=typeof e?JSON.stringify(e):e;d+=c(e)}return Error(d)}}function za(a){if(null==a||Xa(a))return!1;if(I(a)||E(a)||B&&a instanceof B)return!0;
+var b="length"in Object(a)&&a.length;return Q(b)&&(0<=b&&b-1 in a||"function"==typeof a.item)}function n(a,b,d){var c,e;if(a)if(z(a))for(c in a)"prototype"==c||"length"==c||"name"==c||a.hasOwnProperty&&!a.hasOwnProperty(c)||b.call(d,a[c],c,a);else if(I(a)||za(a)){var f="object"!==typeof a;c=0;for(e=a.length;c<e;c++)(f||c in a)&&b.call(d,a[c],c,a)}else if(a.forEach&&a.forEach!==n)a.forEach(b,d,a);else if(nc(a))for(c in a)b.call(d,a[c],c,a);else if("function"===typeof a.hasOwnProperty)for(c in a)a.hasOwnProperty(c)&&
+b.call(d,a[c],c,a);else for(c in a)qa.call(a,c)&&b.call(d,a[c],c,a);return a}function oc(a,b,d){for(var c=Object.keys(a).sort(),e=0;e<c.length;e++)b.call(d,a[c[e]],c[e]);return c}function pc(a){return function(b,d){a(d,b)}}function Td(){return++nb}function Mb(a,b,d){for(var c=a.$$hashKey,e=0,f=b.length;e<f;++e){var g=b[e];if(H(g)||z(g))for(var h=Object.keys(g),k=0,l=h.length;k<l;k++){var m=h[k],r=g[m];d&&H(r)?da(r)?a[m]=new Date(r.valueOf()):Ma(r)?a[m]=new RegExp(r):r.nodeName?a[m]=r.cloneNode(!0):
+Nb(r)?a[m]=r.clone():(H(a[m])||(a[m]=I(r)?[]:{}),Mb(a[m],[r],!0)):a[m]=r}}c?a.$$hashKey=c:delete a.$$hashKey;return a}function M(a){return Mb(a,ra.call(arguments,1),!1)}function Ud(a){return Mb(a,ra.call(arguments,1),!0)}function ea(a){return parseInt(a,10)}function Ob(a,b){return M(Object.create(a),b)}function x(){}function Ya(a){return a}function na(a){return function(){return a}}function qc(a){return z(a.toString)&&a.toString!==sa}function q(a){return"undefined"===typeof a}function y(a){return"undefined"!==
+typeof a}function H(a){return null!==a&&"object"===typeof a}function nc(a){return null!==a&&"object"===typeof a&&!rc(a)}function E(a){return"string"===typeof a}function Q(a){return"number"===typeof a}function da(a){return"[object Date]"===sa.call(a)}function z(a){return"function"===typeof a}function Ma(a){return"[object RegExp]"===sa.call(a)}function Xa(a){return a&&a.window===a}function Za(a){return a&&a.$evalAsync&&a.$watch}function $a(a){return"boolean"===typeof a}function sc(a){return a&&Q(a.length)&&
+Vd.test(sa.call(a))}function Nb(a){return!(!a||!(a.nodeName||a.prop&&a.attr&&a.find))}function Wd(a){var b={};a=a.split(",");var d;for(d=0;d<a.length;d++)b[a[d]]=!0;return b}function ta(a){return F(a.nodeName||a[0]&&a[0].nodeName)}function ab(a,b){var d=a.indexOf(b);0<=d&&a.splice(d,1);return d}function bb(a,b){function d(a,b){var d=b.$$hashKey,e;if(I(a)){e=0;for(var f=a.length;e<f;e++)b.push(c(a[e]))}else if(nc(a))for(e in a)b[e]=c(a[e]);else if(a&&"function"===typeof a.hasOwnProperty)for(e in a)a.hasOwnProperty(e)&&
+(b[e]=c(a[e]));else for(e in a)qa.call(a,e)&&(b[e]=c(a[e]));d?b.$$hashKey=d:delete b.$$hashKey;return b}function c(a){if(!H(a))return a;var b=e.indexOf(a);if(-1!==b)return f[b];if(Xa(a)||Za(a))throw Aa("cpws");var b=!1,c;I(a)?(c=[],b=!0):sc(a)?c=new a.constructor(a):da(a)?c=new Date(a.getTime()):Ma(a)?(c=new RegExp(a.source,a.toString().match(/[^\/]*$/)[0]),c.lastIndex=a.lastIndex):z(a.cloneNode)?c=a.cloneNode(!0):(c=Object.create(rc(a)),b=!0);e.push(a);f.push(c);return b?d(a,c):c}var e=[],f=[];if(b){if(sc(b))throw Aa("cpta");
+if(a===b)throw Aa("cpi");I(b)?b.length=0:n(b,function(a,c){"$$hashKey"!==c&&delete b[c]});e.push(a);f.push(b);return d(a,b)}return c(a)}function ia(a,b){if(I(a)){b=b||[];for(var d=0,c=a.length;d<c;d++)b[d]=a[d]}else if(H(a))for(d in b=b||{},a)if("$"!==d.charAt(0)||"$"!==d.charAt(1))b[d]=a[d];return b||a}function ma(a,b){if(a===b)return!0;if(null===a||null===b)return!1;if(a!==a&&b!==b)return!0;var d=typeof a,c;if(d==typeof b&&"object"==d)if(I(a)){if(!I(b))return!1;if((d=a.length)==b.length){for(c=
+0;c<d;c++)if(!ma(a[c],b[c]))return!1;return!0}}else{if(da(a))return da(b)?ma(a.getTime(),b.getTime()):!1;if(Ma(a))return Ma(b)?a.toString()==b.toString():!1;if(Za(a)||Za(b)||Xa(a)||Xa(b)||I(b)||da(b)||Ma(b))return!1;d=$();for(c in a)if("$"!==c.charAt(0)&&!z(a[c])){if(!ma(a[c],b[c]))return!1;d[c]=!0}for(c in b)if(!(c in d)&&"$"!==c.charAt(0)&&y(b[c])&&!z(b[c]))return!1;return!0}return!1}function cb(a,b,d){return a.concat(ra.call(b,d))}function tc(a,b){var d=2<arguments.length?ra.call(arguments,2):
+[];return!z(b)||b instanceof RegExp?b:d.length?function(){return arguments.length?b.apply(a,cb(d,arguments,0)):b.apply(a,d)}:function(){return arguments.length?b.apply(a,arguments):b.call(a)}}function Xd(a,b){var d=b;"string"===typeof a&&"$"===a.charAt(0)&&"$"===a.charAt(1)?d=u:Xa(b)?d="$WINDOW":b&&X===b?d="$DOCUMENT":Za(b)&&(d="$SCOPE");return d}function db(a,b){if("undefined"===typeof a)return u;Q(b)||(b=b?2:null);return JSON.stringify(a,Xd,b)}function uc(a){return E(a)?JSON.parse(a):a}function vc(a,
+b){var d=Date.parse("Jan 01, 1970 00:00:00 "+a)/6E4;return isNaN(d)?b:d}function Pb(a,b,d){d=d?-1:1;var c=vc(b,a.getTimezoneOffset());b=a;a=d*(c-a.getTimezoneOffset());b=new Date(b.getTime());b.setMinutes(b.getMinutes()+a);return b}function ua(a){a=B(a).clone();try{a.empty()}catch(b){}var d=B("<div>").append(a).html();try{return a[0].nodeType===Na?F(d):d.match(/^(<[^>]+>)/)[1].replace(/^<([\w\-]+)/,function(a,b){return"<"+F(b)})}catch(c){return F(d)}}function wc(a){try{return decodeURIComponent(a)}catch(b){}}
+function xc(a){var b={};n((a||"").split("&"),function(a){var c,e,f;a&&(e=a=a.replace(/\+/g,"%20"),c=a.indexOf("="),-1!==c&&(e=a.substring(0,c),f=a.substring(c+1)),e=wc(e),y(e)&&(f=y(f)?wc(f):!0,qa.call(b,e)?I(b[e])?b[e].push(f):b[e]=[b[e],f]:b[e]=f))});return b}function Qb(a){var b=[];n(a,function(a,c){I(a)?n(a,function(a){b.push(ja(c,!0)+(!0===a?"":"="+ja(a,!0)))}):b.push(ja(c,!0)+(!0===a?"":"="+ja(a,!0)))});return b.length?b.join("&"):""}function ob(a){return ja(a,!0).replace(/%26/gi,"&").replace(/%3D/gi,
+"=").replace(/%2B/gi,"+")}function ja(a,b){return encodeURIComponent(a).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%3B/gi,";").replace(/%20/g,b?"%20":"+")}function Yd(a,b){var d,c,e=Oa.length;for(c=0;c<e;++c)if(d=Oa[c]+b,E(d=a.getAttribute(d)))return d;return null}function Zd(a,b){var d,c,e={};n(Oa,function(b){b+="app";!d&&a.hasAttribute&&a.hasAttribute(b)&&(d=a,c=a.getAttribute(b))});n(Oa,function(b){b+="app";var e;!d&&(e=a.querySelector("["+b.replace(":",
+"\\:")+"]"))&&(d=e,c=e.getAttribute(b))});d&&(e.strictDi=null!==Yd(d,"strict-di"),b(d,c?[c]:[],e))}function yc(a,b,d){H(d)||(d={});d=M({strictDi:!1},d);var c=function(){a=B(a);if(a.injector()){var c=a[0]===X?"document":ua(a);throw Aa("btstrpd",c.replace(/</,"<").replace(/>/,">"));}b=b||[];b.unshift(["$provide",function(b){b.value("$rootElement",a)}]);d.debugInfoEnabled&&b.push(["$compileProvider",function(a){a.debugInfoEnabled(!0)}]);b.unshift("ng");c=eb(b,d.strictDi);c.invoke(["$rootScope",
+"$rootElement","$compile","$injector",function(a,b,c,d){a.$apply(function(){b.data("$injector",d);c(b)(a)})}]);return c},e=/^NG_ENABLE_DEBUG_INFO!/,f=/^NG_DEFER_BOOTSTRAP!/;S&&e.test(S.name)&&(d.debugInfoEnabled=!0,S.name=S.name.replace(e,""));if(S&&!f.test(S.name))return c();S.name=S.name.replace(f,"");fa.resumeBootstrap=function(a){n(a,function(a){b.push(a)});return c()};z(fa.resumeDeferredBootstrap)&&fa.resumeDeferredBootstrap()}function $d(){S.name="NG_ENABLE_DEBUG_INFO!"+S.name;S.location.reload()}
+function ae(a){a=fa.element(a).injector();if(!a)throw Aa("test");return a.get("$$testability")}function zc(a,b){b=b||"_";return a.replace(be,function(a,c){return(c?b:"")+a.toLowerCase()})}function ce(){var a;if(!Ac){var b=pb();(oa=q(b)?S.jQuery:b?S[b]:u)&&oa.fn.on?(B=oa,M(oa.fn,{scope:Pa.scope,isolateScope:Pa.isolateScope,controller:Pa.controller,injector:Pa.injector,inheritedData:Pa.inheritedData}),a=oa.cleanData,oa.cleanData=function(b){var c;if(Rb)Rb=!1;else for(var e=0,f;null!=(f=b[e]);e++)(c=
+oa._data(f,"events"))&&c.$destroy&&oa(f).triggerHandler("$destroy");a(b)}):B=N;fa.element=B;Ac=!0}}function qb(a,b,d){if(!a)throw Aa("areq",b||"?",d||"required");return a}function Qa(a,b,d){d&&I(a)&&(a=a[a.length-1]);qb(z(a),b,"not a function, got "+(a&&"object"===typeof a?a.constructor.name||"Object":typeof a));return a}function Ra(a,b){if("hasOwnProperty"===a)throw Aa("badname",b);}function Bc(a,b,d){if(!b)return a;b=b.split(".");for(var c,e=a,f=b.length,g=0;g<f;g++)c=b[g],a&&(a=(e=a)[c]);return!d&&
+z(a)?tc(e,a):a}function rb(a){for(var b=a[0],d=a[a.length-1],c,e=1;b!==d&&(b=b.nextSibling);e++)if(c||a[e]!==b)c||(c=B(ra.call(a,0,e))),c.push(b);return c||a}function $(){return Object.create(null)}function de(a){function b(a,b,c){return a[b]||(a[b]=c())}var d=G("$injector"),c=G("ng");a=b(a,"angular",Object);a.$$minErr=a.$$minErr||G;return b(a,"module",function(){var a={};return function(f,g,h){if("hasOwnProperty"===f)throw c("badname","module");g&&a.hasOwnProperty(f)&&(a[f]=null);return b(a,f,function(){function a(b,
+d,e,f){f||(f=c);return function(){f[e||"push"]([b,d,arguments]);return v}}function b(a,d){return function(b,e){e&&z(e)&&(e.$$moduleName=f);c.push([a,d,arguments]);return v}}if(!g)throw d("nomod",f);var c=[],e=[],t=[],A=a("$injector","invoke","push",e),v={_invokeQueue:c,_configBlocks:e,_runBlocks:t,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:A,run:function(a){t.push(a);return this}};h&&A(h);return v})}})}function ee(a){M(a,{bootstrap:yc,copy:bb,extend:M,merge:Ud,equals:ma,element:B,forEach:n,injector:eb,noop:x,bind:tc,toJson:db,fromJson:uc,identity:Ya,isUndefined:q,isDefined:y,isString:E,isFunction:z,isObject:H,isNumber:Q,isElement:Nb,isArray:I,
+version:fe,isDate:da,lowercase:F,uppercase:sb,callbacks:{counter:0},getTestability:ae,$$minErr:G,$$csp:Ba,reloadWithDebugInfo:$d});Sb=de(S);Sb("ng",["ngLocale"],["$provide",function(a){a.provider({$$sanitizeUri:ge});a.provider("$compile",Cc).directive({a:he,input:Dc,textarea:Dc,form:ie,script:je,select:ke,style:le,option:me,ngBind:ne,ngBindHtml:oe,ngBindTemplate:pe,ngClass:qe,ngClassEven:re,ngClassOdd:se,ngCloak:te,ngController:ue,ngForm:ve,ngHide:we,ngIf:xe,ngInclude:ye,ngInit:ze,ngNonBindable:Ae,
+ngPluralize:Be,ngRepeat:Ce,ngShow:De,ngStyle:Ee,ngSwitch:Fe,ngSwitchWhen:Ge,ngSwitchDefault:He,ngOptions:Ie,ngTransclude:Je,ngModel:Ke,ngList:Le,ngChange:Me,pattern:Ec,ngPattern:Ec,required:Fc,ngRequired:Fc,minlength:Gc,ngMinlength:Gc,maxlength:Hc,ngMaxlength:Hc,ngValue:Ne,ngModelOptions:Oe}).directive({ngInclude:Pe}).directive(tb).directive(Ic);a.provider({$anchorScroll:Qe,$animate:Re,$animateCss:Se,$$animateQueue:Te,$$AnimateRunner:Ue,$browser:Ve,$cacheFactory:We,$controller:Xe,$document:Ye,$exceptionHandler:Ze,
+$filter:Jc,$$forceReflow:$e,$interpolate:af,$interval:bf,$http:cf,$httpParamSerializer:df,$httpParamSerializerJQLike:ef,$httpBackend:ff,$xhrFactory:gf,$location:hf,$log:jf,$parse:kf,$rootScope:lf,$q:mf,$$q:nf,$sce:of,$sceDelegate:pf,$sniffer:qf,$templateCache:rf,$templateRequest:sf,$$testability:tf,$timeout:uf,$window:vf,$$rAF:wf,$$jqLite:xf,$$HashMap:yf,$$cookieReader:zf})}])}function fb(a){return a.replace(Af,function(a,d,c,e){return e?c.toUpperCase():c}).replace(Bf,"Moz$1")}function Kc(a){a=a.nodeType;
+return 1===a||!a||9===a}function Lc(a,b){var d,c,e=b.createDocumentFragment(),f=[];if(Tb.test(a)){d=d||e.appendChild(b.createElement("div"));c=(Cf.exec(a)||["",""])[1].toLowerCase();c=ka[c]||ka._default;d.innerHTML=c[1]+a.replace(Df,"<$1></$2>")+c[2];for(c=c[0];c--;)d=d.lastChild;f=cb(f,d.childNodes);d=e.firstChild;d.textContent=""}else f.push(b.createTextNode(a));e.textContent="";e.innerHTML="";n(f,function(a){e.appendChild(a)});return e}function N(a){if(a instanceof N)return a;var b;E(a)&&(a=U(a),
+b=!0);if(!(this instanceof N)){if(b&&"<"!=a.charAt(0))throw Ub("nosel");return new N(a)}if(b){b=X;var d;a=(d=Ef.exec(a))?[b.createElement(d[1])]:(d=Lc(a,b))?d.childNodes:[]}Mc(this,a)}function Vb(a){return a.cloneNode(!0)}function ub(a,b){b||vb(a);if(a.querySelectorAll)for(var d=a.querySelectorAll("*"),c=0,e=d.length;c<e;c++)vb(d[c])}function Nc(a,b,d,c){if(y(c))throw Ub("offargs");var e=(c=wb(a))&&c.events,f=c&&c.handle;if(f)if(b){var g=function(b){var c=e[b];y(d)&&ab(c||[],d);y(d)&&c&&0<c.length||
+(a.removeEventListener(b,f,!1),delete e[b])};n(b.split(" "),function(a){g(a);xb[a]&&g(xb[a])})}else for(b in e)"$destroy"!==b&&a.removeEventListener(b,f,!1),delete e[b]}function vb(a,b){var d=a.ng339,c=d&&gb[d];c&&(b?delete c.data[b]:(c.handle&&(c.events.$destroy&&c.handle({},"$destroy"),Nc(a)),delete gb[d],a.ng339=u))}function wb(a,b){var d=a.ng339,d=d&&gb[d];b&&!d&&(a.ng339=d=++Ff,d=gb[d]={events:{},data:{},handle:u});return d}function Wb(a,b,d){if(Kc(a)){var c=y(d),e=!c&&b&&!H(b),f=!b;a=(a=wb(a,
+!e))&&a.data;if(c)a[b]=d;else{if(f)return a;if(e)return a&&a[b];M(a,b)}}}function yb(a,b){return a.getAttribute?-1<(" "+(a.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").indexOf(" "+b+" "):!1}function zb(a,b){b&&a.setAttribute&&n(b.split(" "),function(b){a.setAttribute("class",U((" "+(a.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").replace(" "+U(b)+" "," ")))})}function Ab(a,b){if(b&&a.setAttribute){var d=(" "+(a.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ");n(b.split(" "),
+function(a){a=U(a);-1===d.indexOf(" "+a+" ")&&(d+=a+" ")});a.setAttribute("class",U(d))}}function Mc(a,b){if(b)if(b.nodeType)a[a.length++]=b;else{var d=b.length;if("number"===typeof d&&b.window!==b){if(d)for(var c=0;c<d;c++)a[a.length++]=b[c]}else a[a.length++]=b}}function Oc(a,b){return Bb(a,"$"+(b||"ngController")+"Controller")}function Bb(a,b,d){9==a.nodeType&&(a=a.documentElement);for(b=I(b)?b:[b];a;){for(var c=0,e=b.length;c<e;c++)if(y(d=B.data(a,b[c])))return d;a=a.parentNode||11===a.nodeType&&
+a.host}}function Pc(a){for(ub(a,!0);a.firstChild;)a.removeChild(a.firstChild)}function Xb(a,b){b||ub(a);var d=a.parentNode;d&&d.removeChild(a)}function Gf(a,b){b=b||S;if("complete"===b.document.readyState)b.setTimeout(a);else B(b).on("load",a)}function Qc(a,b){var d=Cb[b.toLowerCase()];return d&&Rc[ta(a)]&&d}function Hf(a,b){var d=function(c,d){c.isDefaultPrevented=function(){return c.defaultPrevented};var f=b[d||c.type],g=f?f.length:0;if(g){if(q(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};var k=f.specialHandlerWrapper||If;1<g&&(f=ia(f));for(var l=0;l<g;l++)c.isImmediatePropagationStopped()||k(a,c,f[l])}};d.elem=a;return d}function If(a,b,d){d.call(a,b)}function Jf(a,b,d){var c=b.relatedTarget;c&&(c===a||Kf.call(a,c))||d.call(a,b)}function xf(){this.$get=function(){return M(N,
+{hasClass:function(a,b){a.attr&&(a=a[0]);return yb(a,b)},addClass:function(a,b){a.attr&&(a=a[0]);return Ab(a,b)},removeClass:function(a,b){a.attr&&(a=a[0]);return zb(a,b)}})}}function Ca(a,b){var d=a&&a.$$hashKey;if(d)return"function"===typeof d&&(d=a.$$hashKey()),d;d=typeof a;return d="function"==d||"object"==d&&null!==a?a.$$hashKey=d+":"+(b||Td)():d+":"+a}function Sa(a,b){if(b){var d=0;this.nextUid=function(){return++d}}n(a,this.put,this)}function Lf(a){return(a=a.toString().replace(Sc,"").match(Tc))?
+"function("+(a[1]||"").replace(/[\s\r\n]+/," ")+")":"fn"}function eb(a,b){function d(a){return function(b,c){if(H(b))n(b,pc(a));else return a(b,c)}}function c(a,b){Ra(a,"service");if(z(b)||I(b))b=t.instantiate(b);if(!b.$get)throw Da("pget",a);return r[a+"Provider"]=b}function e(a,b){return function(){var c=v.invoke(b,this);if(q(c))throw Da("undef",a);return c}}function f(a,b,d){return c(a,{$get:!1!==d?e(a,b):b})}function g(a){qb(q(a)||I(a),"modulesToLoad","not an array");var b=[],c;n(a,function(a){function d(a){var b,
+c;b=0;for(c=a.length;b<c;b++){var e=a[b],f=t.get(e[0]);f[e[1]].apply(f,e[2])}}if(!m.get(a)){m.put(a,!0);try{E(a)?(c=Sb(a),b=b.concat(g(c.requires)).concat(c._runBlocks),d(c._invokeQueue),d(c._configBlocks)):z(a)?b.push(t.invoke(a)):I(a)?b.push(t.invoke(a)):Qa(a,"module")}catch(e){throw I(a)&&(a=a[a.length-1]),e.message&&e.stack&&-1==e.stack.indexOf(e.message)&&(e=e.message+"\n"+e.stack),Da("modulerr",a,e.stack||e.message||e);}}});return b}function h(a,c){function d(b,e){if(a.hasOwnProperty(b)){if(a[b]===
+k)throw Da("cdep",b+" <- "+l.join(" <- "));return a[b]}try{return l.unshift(b),a[b]=k,a[b]=c(b,e)}catch(f){throw a[b]===k&&delete a[b],f;}finally{l.shift()}}function e(a,c,f,g){"string"===typeof f&&(g=f,f=null);var h=[],k=eb.$$annotate(a,b,g),l,m,t;m=0;for(l=k.length;m<l;m++){t=k[m];if("string"!==typeof t)throw Da("itkn",t);h.push(f&&f.hasOwnProperty(t)?f[t]:d(t,g))}I(a)&&(a=a[l]);return a.apply(c,h)}return{invoke:e,instantiate:function(a,b,c){var d=Object.create((I(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(b){return r.hasOwnProperty(b+"Provider")||a.hasOwnProperty(b)}}}b=!0===b;var k={},l=[],m=new Sa([],!0),r={$provide:{provider:d(c),factory:d(f),service:d(function(a,b){return f(a,["$injector",function(a){return a.instantiate(b)}])}),value:d(function(a,b){return f(a,na(b),!1)}),constant:d(function(a,b){Ra(a,"constant");r[a]=b;A[a]=b}),decorator:function(a,b){var c=t.get(a+"Provider"),d=c.$get;c.$get=function(){var a=
+v.invoke(d,c);return v.invoke(b,null,{$delegate:a})}}}},t=r.$injector=h(r,function(a,b){fa.isString(b)&&l.push(b);throw Da("unpr",l.join(" <- "));}),A={},v=A.$injector=h(A,function(a,b){var c=t.get(a+"Provider",b);return v.invoke(c.$get,c,u,a)});n(g(a),function(a){a&&v.invoke(a)});return v}function Qe(){var a=!0;this.disableAutoScrolling=function(){a=!1};this.$get=["$window","$location","$rootScope",function(b,d,c){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(a){if(a){a.scrollIntoView();var c;c=g.yOffset;z(c)?c=c():Nb(c)?(c=c[0],c="fixed"!==b.getComputedStyle(c).position?0:c.getBoundingClientRect().bottom):Q(c)||(c=0);c&&(a=a.getBoundingClientRect().top,b.scrollBy(0,a-c))}else b.scrollTo(0,0)}function g(a){a=E(a)?a:d.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=b.document;a&&c.$watch(function(){return d.hash()},function(a,b){a===b&&""===a||Gf(function(){c.$evalAsync(g)})});
+return g}]}function hb(a,b){if(!a&&!b)return"";if(!a)return b;if(!b)return a;I(a)&&(a=a.join(" "));I(b)&&(b=b.join(" "));return a+" "+b}function Mf(a){E(a)&&(a=a.split(" "));var b=$();n(a,function(a){a.length&&(b[a]=!0)});return b}function Ea(a){return H(a)?a:{}}function Nf(a,b,d,c){function e(a){try{a.apply(null,ra.call(arguments,1))}finally{if(v--,0===v)for(;T.length;)try{T.pop()()}catch(b){d.error(b)}}}function f(){L=null;g();h()}function g(){a:{try{p=m.state;break a}catch(a){}p=void 0}p=q(p)?
+null:p;ma(p,J)&&(p=J);J=p}function h(){if(w!==k.url()||C!==p)w=k.url(),C=p,n(aa,function(a){a(k.url(),p)})}var k=this,l=a.location,m=a.history,r=a.setTimeout,t=a.clearTimeout,A={};k.isMock=!1;var v=0,T=[];k.$$completeOutstandingRequest=e;k.$$incOutstandingRequestCount=function(){v++};k.notifyWhenNoOutstandingRequests=function(a){0===v?a():T.push(a)};var p,C,w=l.href,ga=b.find("base"),L=null;g();C=p;k.url=function(b,d,e){q(e)&&(e=null);l!==a.location&&(l=a.location);m!==a.history&&(m=a.history);if(b){var f=
+C===e;if(w===b&&(!c.history||f))return k;var h=w&&Fa(w)===Fa(b);w=b;C=e;if(!c.history||h&&f){if(!h||L)L=b;d?l.replace(b):h?(d=l,e=b.indexOf("#"),e=-1===e?"":b.substr(e),d.hash=e):l.href=b;l.href!==b&&(L=b)}else m[d?"replaceState":"pushState"](e,"",b),g(),C=p;return k}return L||l.href.replace(/%27/g,"'")};k.state=function(){return p};var aa=[],D=!1,J=null;k.onUrlChange=function(b){if(!D){if(c.history)B(a).on("popstate",f);B(a).on("hashchange",f);D=!0}aa.push(b);return b};k.$$applicationDestroyed=function(){B(a).off("hashchange popstate",
+f)};k.$$checkUrlChange=h;k.baseHref=function(){var a=ga.attr("href");return a?a.replace(/^(https?\:)?\/\/[^\/]*/,""):""};k.defer=function(a,b){var c;v++;c=r(function(){delete A[c];e(a)},b||0);A[c]=!0;return c};k.defer.cancel=function(a){return A[a]?(delete A[a],t(a),e(x),!0):!1}}function Ve(){this.$get=["$window","$log","$sniffer","$document",function(a,b,d,c){return new Nf(a,c,b,d)}]}function We(){this.$get=function(){function a(a,c){function e(a){a!=r&&(t?t==a&&(t=a.n):t=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(a in b)throw G("$cacheFactory")("iid",a);var g=0,h=M({},c,{id:a}),k=$(),l=c&&c.capacity||Number.MAX_VALUE,m=$(),r=null,t=null;return b[a]={put:function(a,b){if(!q(b)){if(l<Number.MAX_VALUE){var c=m[a]||(m[a]={key:a});e(c)}a in k||g++;k[a]=b;g>l&&this.remove(t.key);return b}},get:function(a){if(l<Number.MAX_VALUE){var b=m[a];if(!b)return;e(b)}return k[a]},remove:function(a){if(l<Number.MAX_VALUE){var b=m[a];if(!b)return;b==r&&(r=b.p);b==t&&
+(t=b.n);f(b.n,b.p);delete m[a]}a in k&&(delete k[a],g--)},removeAll:function(){k=$();g=0;m=$();r=t=null},destroy:function(){m=h=k=null;delete b[a]},info:function(){return M({},h,{size:g})}}}var b={};a.info=function(){var a={};n(b,function(b,e){a[e]=b.info()});return a};a.get=function(a){return b[a]};return a}}function rf(){this.$get=["$cacheFactory",function(a){return a("templates")}]}function Cc(a,b){function d(a,b,c){var d=/^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/,e={};n(a,function(a,f){var g=a.match(d);
+if(!g)throw ha("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 c(a){var b=a.charAt(0);if(!b||b!==F(b))throw ha("baddir",a);if(a!==a.trim())throw ha("baddir",a);}var e={},f=/^\s*directive\:\s*([\w\-]+)\s+(.*)$/,g=/(([\w\-]+)(?:\:([^;]+))?;?)/,h=Wd("ngSrc,ngSrcset,src,srcset"),k=/^(?:(\^\^?)?(\?)?(\^\^?)?)?/,l=/^(on[a-z]+|formaction)$/;this.directive=function t(b,f){Ra(b,"directive");
+E(b)?(c(b),qb(f,"directiveFactory"),e.hasOwnProperty(b)||(e[b]=[],a.factory(b+"Directive",["$injector","$exceptionHandler",function(a,c){var f=[];n(e[b],function(e,g){try{var h=a.invoke(e);z(h)?h={compile:na(h)}:!h.compile&&h.link&&(h.compile=na(h.link));h.priority=h.priority||0;h.index=g;h.name=h.name||b;h.require=h.require||h.controller&&h.name;h.restrict=h.restrict||"EA";var k=h,l=h,m=h.name,t={isolateScope:null,bindToController:null};H(l.scope)&&(!0===l.bindToController?(t.bindToController=d(l.scope,
+m,!0),t.isolateScope={}):t.isolateScope=d(l.scope,m,!1));H(l.bindToController)&&(t.bindToController=d(l.bindToController,m,!0));if(H(t.bindToController)){var v=l.controller,R=l.controllerAs;if(!v)throw ha("noctrl",m);var V;a:if(R&&E(R))V=R;else{if(E(v)){var n=Uc.exec(v);if(n){V=n[3];break a}}V=void 0}if(!V)throw ha("noident",m);}var s=k.$$bindings=t;H(s.isolateScope)&&(h.$$isolateBindings=s.isolateScope);h.$$moduleName=e.$$moduleName;f.push(h)}catch(u){c(u)}});return f}])),e[b].push(f)):n(b,pc(t));
+return this};this.aHrefSanitizationWhitelist=function(a){return y(a)?(b.aHrefSanitizationWhitelist(a),this):b.aHrefSanitizationWhitelist()};this.imgSrcSanitizationWhitelist=function(a){return y(a)?(b.imgSrcSanitizationWhitelist(a),this):b.imgSrcSanitizationWhitelist()};var m=!0;this.debugInfoEnabled=function(a){return y(a)?(m=a,this):m};this.$get=["$injector","$interpolate","$exceptionHandler","$templateRequest","$parse","$controller","$rootScope","$document","$sce","$animate","$$sanitizeUri",function(a,
+b,c,d,p,C,w,ga,L,aa,D){function J(a,b){try{a.addClass(b)}catch(c){}}function K(a,b,c,d,e){a instanceof B||(a=B(a));n(a,function(b,c){b.nodeType==Na&&b.nodeValue.match(/\S+/)&&(a[c]=B(b).wrap("<span></span>").parent()[0])});var f=O(a,b,a,c,d,e);K.$$addScopeClass(a);var g=null;return function(b,c,d){qb(b,"scope");e&&e.needsNewScope&&(b=b.$parent.$new());d=d||{};var h=d.parentBoundTranscludeFn,k=d.transcludeControllers;d=d.futureParentElement;h&&h.$$boundTransclude&&(h=h.$$boundTransclude);g||(g=(d=
+d&&d[0])?"foreignobject"!==ta(d)&&d.toString().match(/SVG/)?"svg":"html":"html");d="html"!==g?B(Yb(g,B("<div>").append(a).html())):c?Pa.clone.call(a):a;if(k)for(var l in k)d.data("$"+l+"Controller",k[l].instance);K.$$addScopeInfo(d,b);c&&c(d,b);f&&f(b,d,d,h);return d}}function O(a,b,c,d,e,f){function g(a,c,d,e){var f,k,l,m,t,w,D;if(p)for(D=Array(c.length),m=0;m<h.length;m+=3)f=h[m],D[f]=c[f];else D=c;m=0;for(t=h.length;m<t;)k=D[h[m++]],c=h[m++],f=h[m++],c?(c.scope?(l=a.$new(),K.$$addScopeInfo(B(k),
+l)):l=a,w=c.transcludeOnThisElement?R(a,c.transclude,e):!c.templateOnThisElement&&e?e:!e&&b?R(a,b):null,c(f,l,k,d,w)):f&&f(a,k.childNodes,u,e)}for(var h=[],k,l,m,t,p,w=0;w<a.length;w++){k=new fa;l=V(a[w],[],k,0===w?d:u,e);(f=l.length?Z(l,a[w],k,b,c,null,[],[],f):null)&&f.scope&&K.$$addScopeClass(k.$$element);k=f&&f.terminal||!(m=a[w].childNodes)||!m.length?null:O(m,f?(f.transcludeOnThisElement||!f.templateOnThisElement)&&f.transclude:b);if(f||k)h.push(w,f,k),t=!0,p=p||f;f=null}return t?g:null}function R(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 V(a,b,c,d,e){var h=c.$attr,k;switch(a.nodeType){case 1:P(b,va(ta(a)),"E",d,e);for(var l,m,t,p=a.attributes,w=0,D=p&&p.length;w<D;w++){var K=!1,A=!1;l=p[w];k=l.name;m=U(l.value);l=va(k);if(t=ka.test(l))k=k.replace(Vc,"").substr(8).replace(/_(.)/g,function(a,b){return b.toUpperCase()});(l=l.match(la))&&G(l[1])&&(K=k,A=k.substr(0,k.length-
+5)+"end",k=k.substr(0,k.length-6));l=va(k.toLowerCase());h[l]=k;if(t||!c.hasOwnProperty(l))c[l]=m,Qc(a,l)&&(c[l]=!0);W(a,b,m,l,t);P(b,l,"A",d,e,K,A)}a=a.className;H(a)&&(a=a.animVal);if(E(a)&&""!==a)for(;k=g.exec(a);)l=va(k[2]),P(b,l,"C",d,e)&&(c[l]=U(k[3])),a=a.substr(k.index+k[0].length);break;case Na:if(11===Ha)for(;a.parentNode&&a.nextSibling&&a.nextSibling.nodeType===Na;)a.nodeValue+=a.nextSibling.nodeValue,a.parentNode.removeChild(a.nextSibling);N(b,a.nodeValue);break;case 8:try{if(k=f.exec(a.nodeValue))l=
+va(k[1]),P(b,l,"M",d,e)&&(c[l]=U(k[2]))}catch(R){}}b.sort(Ia);return b}function Ta(a,b,c){var d=[],e=0;if(b&&a.hasAttribute&&a.hasAttribute(b)){do{if(!a)throw ha("uterdir",b,c);1==a.nodeType&&(a.hasAttribute(b)&&e++,a.hasAttribute(c)&&e--);d.push(a);a=a.nextSibling}while(0<e)}else d.push(a);return B(d)}function s(a,b,c){return function(d,e,f,g,h){e=Ta(e[0],b,c);return a(d,e,f,g,h)}}function Z(a,b,d,e,f,g,h,l,m){function t(a,b,c,d){if(a){c&&(a=s(a,c,d));a.require=q.require;a.directiveName=x;if(O===
+q||q.$$isolateScope)a=ca(a,{isolateScope:!0});h.push(a)}if(b){c&&(b=s(b,c,d));b.require=q.require;b.directiveName=x;if(O===q||q.$$isolateScope)b=ca(b,{isolateScope:!0});l.push(b)}}function p(a,b,c,d){var e;if(E(b)){var f=b.match(k);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 ha("ctreq",b,a);}else if(I(b))for(e=[],g=0,f=b.length;g<f;g++)e[g]=p(a,b[g],c,d);return e||
+null}function w(a,b,c,d,e,f){var g=$(),h;for(h in d){var k=d[h],l={$scope:k===O||k.$$isolateScope?e:f,$element:a,$attrs:b,$transclude:c},m=k.controller;"@"==m&&(m=b[k.name]);l=C(m,l,!0,k.controllerAs);g[k.name]=l;aa||a.data("$"+k.name+"Controller",l.instance)}return g}function D(a,c,e,f,g){function k(a,b,c){var d;Za(a)||(c=b,b=a,a=u);aa&&(d=v);c||(c=aa?V.parent():V);return g(a,b,d,c,Ta)}var m,t,A,v,C,V,Ga;b===e?(f=d,V=d.$$element):(V=B(e),f=new fa(V,d));A=c;O?t=c.$new(!0):R&&(A=c.$parent);g&&(C=k,
+C.$$boundTransclude=g);T&&(v=w(V,f,C,T,t,c));O&&(K.$$addScopeInfo(V,t,!0,!(J&&(J===O||J===O.$$originalDirective))),K.$$addScopeClass(V,!0),t.$$isolateBindings=O.$$isolateBindings,(Ga=ba(c,f,t,t.$$isolateBindings,O))&&t.$on("$destroy",Ga));for(var n in v){Ga=T[n];var ga=v[n],L=Ga.$$bindings.bindToController;ga.identifier&&L&&(m=ba(A,f,ga.instance,L,Ga));var q=ga();q!==ga.instance&&(ga.instance=q,V.data("$"+Ga.name+"Controller",q),m&&m(),m=ba(A,f,ga.instance,L,Ga))}F=0;for(M=h.length;F<M;F++)m=h[F],
+ea(m,m.isolateScope?t:c,V,f,m.require&&p(m.directiveName,m.require,V,v),C);var Ta=c;O&&(O.template||null===O.templateUrl)&&(Ta=t);a&&a(Ta,e.childNodes,u,g);for(F=l.length-1;0<=F;F--)m=l[F],ea(m,m.isolateScope?t:c,V,f,m.require&&p(m.directiveName,m.require,V,v),C)}m=m||{};for(var A=-Number.MAX_VALUE,R=m.newScopeDirective,T=m.controllerDirectives,O=m.newIsolateScopeDirective,J=m.templateDirective,n=m.nonTlbTranscludeDirective,ga=!1,L=!1,aa=m.hasElementTranscludeDirective,Z=d.$$element=B(b),q,x,P,Ia=
+e,G,F=0,M=a.length;F<M;F++){q=a[F];var N=q.$$start,Q=q.$$end;N&&(Z=Ta(b,N,Q));P=u;if(A>q.priority)break;if(P=q.scope)q.templateUrl||(H(P)?(Ua("new/isolated scope",O||R,q,Z),O=q):Ua("new/isolated scope",O,q,Z)),R=R||q;x=q.name;!q.templateUrl&&q.controller&&(P=q.controller,T=T||$(),Ua("'"+x+"' controller",T[x],q,Z),T[x]=q);if(P=q.transclude)ga=!0,q.$$tlb||(Ua("transclusion",n,q,Z),n=q),"element"==P?(aa=!0,A=q.priority,P=Z,Z=d.$$element=B(X.createComment(" "+x+": "+d[x]+" ")),b=Z[0],Y(f,ra.call(P,0),
+b),Ia=K(P,e,A,g&&g.name,{nonTlbTranscludeDirective:n})):(P=B(Vb(b)).contents(),Z.empty(),Ia=K(P,e,u,u,{needsNewScope:q.$$isolateScope||q.$$newScope}));if(q.template)if(L=!0,Ua("template",J,q,Z),J=q,P=z(q.template)?q.template(Z,d):q.template,P=ja(P),q.replace){g=q;P=Tb.test(P)?Xc(Yb(q.templateNamespace,U(P))):[];b=P[0];if(1!=P.length||1!==b.nodeType)throw ha("tplrt",x,"");Y(f,Z,b);P={$attr:{}};var Wc=V(b,[],P),W=a.splice(F+1,a.length-(F+1));(O||R)&&y(Wc,O,R);a=a.concat(Wc).concat(W);S(d,P);M=a.length}else Z.html(P);
+if(q.templateUrl)L=!0,Ua("template",J,q,Z),J=q,q.replace&&(g=q),D=Of(a.splice(F,a.length-F),Z,d,f,ga&&Ia,h,l,{controllerDirectives:T,newScopeDirective:R!==q&&R,newIsolateScopeDirective:O,templateDirective:J,nonTlbTranscludeDirective:n}),M=a.length;else if(q.compile)try{G=q.compile(Z,d,Ia),z(G)?t(null,G,N,Q):G&&t(G.pre,G.post,N,Q)}catch(da){c(da,ua(Z))}q.terminal&&(D.terminal=!0,A=Math.max(A,q.priority))}D.scope=R&&!0===R.scope;D.transcludeOnThisElement=ga;D.templateOnThisElement=L;D.transclude=Ia;
+m.hasElementTranscludeDirective=aa;return D}function y(a,b,c){for(var d=0,e=a.length;d<e;d++)a[d]=Ob(a[d],{$$isolateScope:b,$$newScope:c})}function P(b,d,f,g,h,k,l){if(d===h)return null;h=null;if(e.hasOwnProperty(d)){var m;d=a.get(d+"Directive");for(var p=0,w=d.length;p<w;p++)try{m=d[p],(q(g)||g>m.priority)&&-1!=m.restrict.indexOf(f)&&(k&&(m=Ob(m,{$$start:k,$$end:l})),b.push(m),h=m)}catch(D){c(D)}}return h}function G(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 S(a,b){var c=b.$attr,d=a.$attr,e=a.$$element;n(a,function(d,e){"$"!=e.charAt(0)&&(b[e]&&b[e]!==d&&(d+=("style"===e?";":" ")+b[e]),a.$set(e,d,!0,c[e]))});n(b,function(b,f){"class"==f?(J(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 Of(a,b,c,e,f,g,h,k){var l=[],m,t,p=b[0],w=a.shift(),D=Ob(w,{templateUrl:null,
+transclude:null,replace:null,$$originalDirective:w}),A=z(w.templateUrl)?w.templateUrl(b,c):w.templateUrl,K=w.templateNamespace;b.empty();d(A).then(function(d){var T,v;d=ja(d);if(w.replace){d=Tb.test(d)?Xc(Yb(K,U(d))):[];T=d[0];if(1!=d.length||1!==T.nodeType)throw ha("tplrt",w.name,A);d={$attr:{}};Y(e,b,T);var C=V(T,[],d);H(w.scope)&&y(C,!0);a=C.concat(a);S(c,d)}else T=p,b.html(d);a.unshift(D);m=Z(a,T,c,f,b,w,g,h,k);n(e,function(a,c){a==T&&(e[c]=b[0])});for(t=O(b[0].childNodes,f);l.length;){d=l.shift();
+v=l.shift();var ga=l.shift(),L=l.shift(),C=b[0];if(!d.$$destroyed){if(v!==p){var q=v.className;k.hasElementTranscludeDirective&&w.replace||(C=Vb(T));Y(ga,B(v),C);J(B(C),q)}v=m.transcludeOnThisElement?R(d,m.transclude,L):L;m(t,d,C,e,v)}}l=null});return function(a,b,c,d,e){a=e;b.$$destroyed||(l?l.push(b,c,d,a):(m.transcludeOnThisElement&&(a=R(b,m.transclude,e)),m(t,b,c,d,a)))}}function Ia(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 Ua(a,
+b,c,d){function e(a){return a?" (module: "+a+")":""}if(b)throw ha("multidir",b.name,e(b.$$moduleName),c.name,e(c.$$moduleName),a,ua(d));}function N(a,c){var d=b(c,!0);d&&a.push({priority:0,compile:function(a){a=a.parent();var b=!!a.length;b&&K.$$addBindingClass(a);return function(a,c){var e=c.parent();b||K.$$addBindingClass(e);K.$$addBindingInfo(e,d.expressions);a.$watch(d,function(a){c[0].nodeValue=a})}}})}function Yb(a,b){a=F(a||"html");switch(a){case "svg":case "math":var c=X.createElement("div");
+c.innerHTML="<"+a+">"+b+"</"+a+">";return c.childNodes[0].childNodes;default:return b}}function Q(a,b){if("srcdoc"==b)return L.HTML;var c=ta(a);if("xlinkHref"==b||"form"==c&&"action"==b||"img"!=c&&("src"==b||"ngSrc"==b))return L.RESOURCE_URL}function W(a,c,d,e,f){var g=Q(a,e);f=h[e]||f;var k=b(d,!0,g,f);if(k){if("multiple"===e&&"select"===ta(a))throw ha("selmulti",ua(a));c.push({priority:100,compile:function(){return{pre:function(a,c,h){c=h.$$observers||(h.$$observers=$());if(l.test(e))throw ha("nodomevents");
+var m=h[e];m!==d&&(k=m&&b(m,!0,g,f),d=m);k&&(h[e]=k(a),(c[e]||(c[e]=[])).$$inter=!0,(h.$$observers&&h.$$observers[e].$$scope||a).$watch(k,function(a,b){"class"===e&&a!=b?h.$updateClass(a,b):h.$set(e,a)}))}}}})}}function Y(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=X.createDocumentFragment();a.appendChild(d);
+B.hasData(d)&&(B.data(c,B.data(d)),oa?(Rb=!0,oa.cleanData([d])):delete B.cache[d[B.expando]]);d=1;for(e=b.length;d<e;d++)f=b[d],B(f).remove(),a.appendChild(f),delete b[d];b[0]=c;b.length=1}function ca(a,b){return M(function(){return a.apply(null,arguments)},a,b)}function ea(a,b,d,e,f,g){try{a(b,d,e,f,g)}catch(h){c(h,ua(d))}}function ba(a,c,d,e,f){var g=[];n(e,function(e,h){var k=e.attrName,l=e.optional,m,t,w,D;switch(e.mode){case "@":l||qa.call(c,k)||(d[h]=c[k]=void 0);c.$observe(k,function(a){E(a)&&
+(d[h]=a)});c.$$observers[k].$$scope=a;E(c[k])&&(d[h]=b(c[k])(a));break;case "=":if(!qa.call(c,k)){if(l)break;c[k]=void 0}if(l&&!c[k])break;t=p(c[k]);D=t.literal?ma:function(a,b){return a===b||a!==a&&b!==b};w=t.assign||function(){m=d[h]=t(a);throw ha("nonassign",c[k],f.name);};m=d[h]=t(a);l=function(b){D(b,d[h])||(D(b,m)?w(a,b=d[h]):d[h]=b);return m=b};l.$stateful=!0;l=e.collection?a.$watchCollection(c[k],l):a.$watch(p(c[k],l),null,t.literal);g.push(l);break;case "&":t=c.hasOwnProperty(k)?p(c[k]):
+x;if(t===x&&l)break;d[h]=function(b){return t(a,b)}}});return g.length&&function(){for(var a=0,b=g.length;a<b;++a)g[a]()}}var fa=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};fa.prototype={$normalize:va,$addClass:function(a){a&&0<a.length&&aa.addClass(this.$$element,a)},$removeClass:function(a){a&&0<a.length&&aa.removeClass(this.$$element,a)},$updateClass:function(a,b){var c=Yc(a,b);c&&c.length&&aa.addClass(this.$$element,
+c);(c=Yc(b,a))&&c.length&&aa.removeClass(this.$$element,c)},$set:function(a,b,d,e){var f=Qc(this.$$element[0],a),g=Zc[a],h=a;f?(this.$$element.prop(a,b),e=f):g&&(this[g]=b,h=g);this[a]=b;e?this.$attr[a]=e:(e=this.$attr[a])||(this.$attr[a]=e=zc(a,"-"));f=ta(this.$$element);if("a"===f&&"href"===a||"img"===f&&"src"===a)this[a]=b=D(b,"src"===a);else if("img"===f&&"srcset"===a){for(var f="",g=U(b),k=/(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/,k=/\s/.test(g)?k:/(,)/,g=g.split(k),k=Math.floor(g.length/2),l=0;l<
+k;l++)var m=2*l,f=f+D(U(g[m]),!0),f=f+(" "+U(g[m+1]));g=U(g[2*l]).split(/\s/);f+=D(U(g[0]),!0);2===g.length&&(f+=" "+U(g[1]));this[a]=b=f}!1!==d&&(null===b||q(b)?this.$$element.removeAttr(e):this.$$element.attr(e,b));(a=this.$$observers)&&n(a[h],function(a){try{a(b)}catch(d){c(d)}})},$observe:function(a,b){var c=this,d=c.$$observers||(c.$$observers=$()),e=d[a]||(d[a]=[]);e.push(b);w.$evalAsync(function(){e.$$inter||!c.hasOwnProperty(a)||q(c[a])||b(c[a])});return function(){ab(e,b)}}};var da=b.startSymbol(),
+ia=b.endSymbol(),ja="{{"==da||"}}"==ia?Ya:function(a){return a.replace(/\{\{/g,da).replace(/}}/g,ia)},ka=/^ngAttr[A-Z]/,la=/^(.+)Start$/;K.$$addBindingInfo=m?function(a,b){var c=a.data("$binding")||[];I(b)?c=c.concat(b):c.push(b);a.data("$binding",c)}:x;K.$$addBindingClass=m?function(a){J(a,"ng-binding")}:x;K.$$addScopeInfo=m?function(a,b,c,d){a.data(c?d?"$isolateScopeNoTemplate":"$isolateScope":"$scope",b)}:x;K.$$addScopeClass=m?function(a,b){J(a,b?"ng-isolate-scope":"ng-scope")}:x;return K}]}function va(a){return fb(a.replace(Vc,
+""))}function Yc(a,b){var d="",c=a.split(/\s+/),e=b.split(/\s+/),f=0;a:for(;f<c.length;f++){for(var g=c[f],h=0;h<e.length;h++)if(g==e[h])continue a;d+=(0<d.length?" ":"")+g}return d}function Xc(a){a=B(a);var b=a.length;if(1>=b)return a;for(;b--;)8===a[b].nodeType&&Pf.call(a,b,1);return a}function Xe(){var a={},b=!1;this.register=function(b,c){Ra(b,"controller");H(b)?M(a,b):a[b]=c};this.allowGlobals=function(){b=!0};this.$get=["$injector","$window",function(d,c){function e(a,b,c,d){if(!a||!H(a.$scope))throw G("$controller")("noscp",
+d,b);a.$scope[b]=c}return function(f,g,h,k){var l,m,r;h=!0===h;k&&E(k)&&(r=k);if(E(f)){k=f.match(Uc);if(!k)throw Qf("ctrlfmt",f);m=k[1];r=r||k[3];f=a.hasOwnProperty(m)?a[m]:Bc(g.$scope,m,!0)||(b?Bc(c,m,!0):u);Qa(f,m,!0)}if(h)return h=(I(f)?f[f.length-1]:f).prototype,l=Object.create(h||null),r&&e(g,r,l,m||f.name),M(function(){var a=d.invoke(f,l,g,m);a!==l&&(H(a)||z(a))&&(l=a,r&&e(g,r,l,m||f.name));return l},{instance:l,identifier:r});l=d.instantiate(f,g,m);r&&e(g,r,l,m||f.name);return l}}]}function Ye(){this.$get=
+["$window",function(a){return B(a.document)}]}function Ze(){this.$get=["$log",function(a){return function(b,d){a.error.apply(a,arguments)}}]}function Zb(a){return H(a)?da(a)?a.toISOString():db(a):a}function df(){this.$get=function(){return function(a){if(!a)return"";var b=[];oc(a,function(a,c){null===a||q(a)||(I(a)?n(a,function(a,d){b.push(ja(c)+"="+ja(Zb(a)))}):b.push(ja(c)+"="+ja(Zb(a))))});return b.join("&")}}}function ef(){this.$get=function(){return function(a){function b(a,e,f){null===a||q(a)||
+(I(a)?n(a,function(a,c){b(a,e+"["+(H(a)?c:"")+"]")}):H(a)&&!da(a)?oc(a,function(a,c){b(a,e+(f?"":"[")+c+(f?"":"]"))}):d.push(ja(e)+"="+ja(Zb(a))))}if(!a)return"";var d=[];b(a,"",!0);return d.join("&")}}}function $b(a,b){if(E(a)){var d=a.replace(Rf,"").trim();if(d){var c=b("Content-Type");(c=c&&0===c.indexOf($c))||(c=(c=d.match(Sf))&&Tf[c[0]].test(d));c&&(a=uc(d))}}return a}function ad(a){var b=$(),d;E(a)?n(a.split("\n"),function(a){d=a.indexOf(":");var e=F(U(a.substr(0,d)));a=U(a.substr(d+1));e&&
+(b[e]=b[e]?b[e]+", "+a:a)}):H(a)&&n(a,function(a,d){var f=F(d),g=U(a);f&&(b[f]=b[f]?b[f]+", "+g:g)});return b}function bd(a){var b;return function(d){b||(b=ad(a));return d?(d=b[F(d)],void 0===d&&(d=null),d):b}}function cd(a,b,d,c){if(z(c))return c(a,b,d);n(c,function(c){a=c(a,b,d)});return a}function cf(){var a=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"},b=!1;this.useApplyAsync=function(a){return y(a)?(b=!!a,this):b};var d=!0;this.useLegacyPromiseExtensions=function(a){return y(a)?(d=!!a,this):d};var c=this.interceptors=[];this.$get=["$httpBackend","$$cookieReader","$cacheFactory","$rootScope","$q","$injector",function(e,f,g,h,k,l){function m(b){function c(a){var b=M({},a);b.data=cd(a.data,a.headers,a.status,f.transformResponse);
+a=a.status;return 200<=a&&300>a?b:k.reject(b)}function e(a,b){var c,d={};n(a,function(a,e){z(a)?(c=a(b),null!=c&&(d[e]=c)):d[e]=a});return d}if(!fa.isObject(b))throw G("$http")("badreq",b);var f=M({method:"get",transformRequest:a.transformRequest,transformResponse:a.transformResponse,paramSerializer:a.paramSerializer},b);f.headers=function(b){var c=a.headers,d=M({},b.headers),f,g,h,c=M({},c.common,c[F(b.method)]);a:for(f in c){g=F(f);for(h in d)if(F(h)===g)continue a;d[f]=c[f]}return e(d,ia(b))}(b);
+f.method=sb(f.method);f.paramSerializer=E(f.paramSerializer)?l.get(f.paramSerializer):f.paramSerializer;var g=[function(b){var d=b.headers,e=cd(b.data,bd(d),u,b.transformRequest);q(e)&&n(d,function(a,b){"content-type"===F(b)&&delete d[b]});q(b.withCredentials)&&!q(a.withCredentials)&&(b.withCredentials=a.withCredentials);return r(b,e).then(c,c)},u],h=k.when(f);for(n(v,function(a){(a.request||a.requestError)&&g.unshift(a.request,a.requestError);(a.response||a.responseError)&&g.push(a.response,a.responseError)});g.length;){b=
+g.shift();var m=g.shift(),h=h.then(b,m)}d?(h.success=function(a){Qa(a,"fn");h.then(function(b){a(b.data,b.status,b.headers,f)});return h},h.error=function(a){Qa(a,"fn");h.then(null,function(b){a(b.data,b.status,b.headers,f)});return h}):(h.success=dd("success"),h.error=dd("error"));return h}function r(c,d){function g(a,c,d,e){function f(){l(c,a,d,e)}J&&(200<=a&&300>a?J.put(R,[a,c,ad(d),e]):J.remove(R));b?h.$applyAsync(f):(f(),h.$$phase||h.$apply())}function l(a,b,d,e){b=-1<=b?b:0;(200<=b&&300>b?n.resolve:
+n.reject)({data:a,status:b,headers:bd(d),config:c,statusText:e})}function r(a){l(a.data,a.status,ia(a.headers()),a.statusText)}function v(){var a=m.pendingRequests.indexOf(c);-1!==a&&m.pendingRequests.splice(a,1)}var n=k.defer(),D=n.promise,J,K,O=c.headers,R=t(c.url,c.paramSerializer(c.params));m.pendingRequests.push(c);D.then(v,v);!c.cache&&!a.cache||!1===c.cache||"GET"!==c.method&&"JSONP"!==c.method||(J=H(c.cache)?c.cache:H(a.cache)?a.cache:A);J&&(K=J.get(R),y(K)?K&&z(K.then)?K.then(r,r):I(K)?l(K[1],
+K[0],ia(K[2]),K[3]):l(K,200,{},"OK"):J.put(R,D));q(K)&&((K=ed(c.url)?f()[c.xsrfCookieName||a.xsrfCookieName]:u)&&(O[c.xsrfHeaderName||a.xsrfHeaderName]=K),e(c.method,R,d,g,O,c.timeout,c.withCredentials,c.responseType));return D}function t(a,b){0<b.length&&(a+=(-1==a.indexOf("?")?"?":"&")+b);return a}var A=g("$http");a.paramSerializer=E(a.paramSerializer)?l.get(a.paramSerializer):a.paramSerializer;var v=[];n(c,function(a){v.unshift(E(a)?l.get(a):l.invoke(a))});m.pendingRequests=[];(function(a){n(arguments,
+function(a){m[a]=function(b,c){return m(M({},c||{},{method:a,url:b}))}})})("get","delete","head","jsonp");(function(a){n(arguments,function(a){m[a]=function(b,c,d){return m(M({},d||{},{method:a,url:b,data:c}))}})})("post","put","patch");m.defaults=a;return m}]}function gf(){this.$get=function(){return function(){return new S.XMLHttpRequest}}}function ff(){this.$get=["$browser","$window","$document","$xhrFactory",function(a,b,d,c){return Uf(a,c,a.defer,b.angular.callbacks,d[0])}]}function Uf(a,b,d,
+c,e){function f(a,b,d){var f=e.createElement("script"),m=null;f.type="text/javascript";f.src=a;f.async=!0;m=function(a){f.removeEventListener("load",m,!1);f.removeEventListener("error",m,!1);e.body.removeChild(f);f=null;var g=-1,A="unknown";a&&("load"!==a.type||c[b].called||(a={type:"error"}),A=a.type,g="error"===a.type?404:200);d&&d(g,A)};f.addEventListener("load",m,!1);f.addEventListener("error",m,!1);e.body.appendChild(f);return m}return function(e,h,k,l,m,r,t,A){function v(){C&&C();w&&w.abort()}
+function T(b,c,e,f,g){y(L)&&d.cancel(L);C=w=null;b(c,e,f,g);a.$$completeOutstandingRequest(x)}a.$$incOutstandingRequestCount();h=h||a.url();if("jsonp"==F(e)){var p="_"+(c.counter++).toString(36);c[p]=function(a){c[p].data=a;c[p].called=!0};var C=f(h.replace("JSON_CALLBACK","angular.callbacks."+p),p,function(a,b){T(l,a,c[p].data,"",b);c[p]=x})}else{var w=b(e,h);w.open(e,h,!0);n(m,function(a,b){y(a)&&w.setRequestHeader(b,a)});w.onload=function(){var a=w.statusText||"",b="response"in w?w.response:w.responseText,
+c=1223===w.status?204:w.status;0===c&&(c=b?200:"file"==wa(h).protocol?404:0);T(l,c,b,w.getAllResponseHeaders(),a)};e=function(){T(l,-1,null,null,"")};w.onerror=e;w.onabort=e;t&&(w.withCredentials=!0);if(A)try{w.responseType=A}catch(ga){if("json"!==A)throw ga;}w.send(q(k)?null:k)}if(0<r)var L=d(v,r);else r&&z(r.then)&&r.then(v)}}function af(){var a="{{",b="}}";this.startSymbol=function(b){return b?(a=b,this):a};this.endSymbol=function(a){return a?(b=a,this):b};this.$get=["$parse","$exceptionHandler",
+"$sce",function(d,c,e){function f(a){return"\\\\\\"+a}function g(c){return c.replace(m,a).replace(r,b)}function h(f,h,m,r){function p(a){try{var b=a;a=m?e.getTrusted(m,b):e.valueOf(b);var d;if(r&&!y(a))d=a;else if(null==a)d="";else{switch(typeof a){case "string":break;case "number":a=""+a;break;default:a=db(a)}d=a}return d}catch(g){c(Ja.interr(f,g))}}r=!!r;for(var C,w,n=0,L=[],s=[],D=f.length,J=[],K=[];n<D;)if(-1!=(C=f.indexOf(a,n))&&-1!=(w=f.indexOf(b,C+k)))n!==C&&J.push(g(f.substring(n,C))),n=f.substring(C+
+k,w),L.push(n),s.push(d(n,p)),n=w+l,K.push(J.length),J.push("");else{n!==D&&J.push(g(f.substring(n)));break}m&&1<J.length&&Ja.throwNoconcat(f);if(!h||L.length){var O=function(a){for(var b=0,c=L.length;b<c;b++){if(r&&q(a[b]))return;J[K[b]]=a[b]}return J.join("")};return M(function(a){var b=0,d=L.length,e=Array(d);try{for(;b<d;b++)e[b]=s[b](a);return O(e)}catch(g){c(Ja.interr(f,g))}},{exp:f,expressions:L,$$watchDelegate:function(a,b){var c;return a.$watchGroup(s,function(d,e){var f=O(d);z(b)&&b.call(this,
+f,d!==e?c:f,a);c=f})}})}}var k=a.length,l=b.length,m=new RegExp(a.replace(/./g,f),"g"),r=new RegExp(b.replace(/./g,f),"g");h.startSymbol=function(){return a};h.endSymbol=function(){return b};return h}]}function bf(){this.$get=["$rootScope","$window","$q","$$q",function(a,b,d,c){function e(e,h,k,l){var m=4<arguments.length,r=m?ra.call(arguments,4):[],t=b.setInterval,A=b.clearInterval,v=0,n=y(l)&&!l,p=(n?c:d).defer(),C=p.promise;k=y(k)?k:0;C.then(null,null,m?function(){e.apply(null,r)}:e);C.$$intervalId=
+t(function(){p.notify(v++);0<k&&v>=k&&(p.resolve(v),A(C.$$intervalId),delete f[C.$$intervalId]);n||a.$apply()},h);f[C.$$intervalId]=p;return C}var f={};e.cancel=function(a){return a&&a.$$intervalId in f?(f[a.$$intervalId].reject("canceled"),b.clearInterval(a.$$intervalId),delete f[a.$$intervalId],!0):!1};return e}]}function bc(a){a=a.split("/");for(var b=a.length;b--;)a[b]=ob(a[b]);return a.join("/")}function fd(a,b){var d=wa(a);b.$$protocol=d.protocol;b.$$host=d.hostname;b.$$port=ea(d.port)||Vf[d.protocol]||
+null}function gd(a,b){var d="/"!==a.charAt(0);d&&(a="/"+a);var c=wa(a);b.$$path=decodeURIComponent(d&&"/"===c.pathname.charAt(0)?c.pathname.substring(1):c.pathname);b.$$search=xc(c.search);b.$$hash=decodeURIComponent(c.hash);b.$$path&&"/"!=b.$$path.charAt(0)&&(b.$$path="/"+b.$$path)}function pa(a,b){if(0===b.indexOf(a))return b.substr(a.length)}function Fa(a){var b=a.indexOf("#");return-1==b?a:a.substr(0,b)}function ib(a){return a.replace(/(#.+)|#$/,"$1")}function cc(a,b,d){this.$$html5=!0;d=d||"";
+fd(a,this);this.$$parse=function(a){var d=pa(b,a);if(!E(d))throw Db("ipthprfx",a,b);gd(d,this);this.$$path||(this.$$path="/");this.$$compose()};this.$$compose=function(){var a=Qb(this.$$search),d=this.$$hash?"#"+ob(this.$$hash):"";this.$$url=bc(this.$$path)+(a?"?"+a:"")+d;this.$$absUrl=b+this.$$url.substr(1)};this.$$parseLinkUrl=function(c,e){if(e&&"#"===e[0])return this.hash(e.slice(1)),!0;var f,g;y(f=pa(a,c))?(g=f,g=y(f=pa(d,f))?b+(pa("/",f)||f):a+g):y(f=pa(b,c))?g=b+f:b==c+"/"&&(g=b);g&&this.$$parse(g);
+return!!g}}function dc(a,b,d){fd(a,this);this.$$parse=function(c){var e=pa(a,c)||pa(b,c),f;q(e)||"#"!==e.charAt(0)?this.$$html5?f=e:(f="",q(e)&&(a=c,this.replace())):(f=pa(d,e),q(f)&&(f=e));gd(f,this);c=this.$$path;var e=a,g=/^\/[A-Z]:(\/.*)/;0===f.indexOf(e)&&(f=f.replace(e,""));g.exec(f)||(c=(f=g.exec(c))?f[1]:c);this.$$path=c;this.$$compose()};this.$$compose=function(){var b=Qb(this.$$search),e=this.$$hash?"#"+ob(this.$$hash):"";this.$$url=bc(this.$$path)+(b?"?"+b:"")+e;this.$$absUrl=a+(this.$$url?
+d+this.$$url:"")};this.$$parseLinkUrl=function(b,d){return Fa(a)==Fa(b)?(this.$$parse(b),!0):!1}}function hd(a,b,d){this.$$html5=!0;dc.apply(this,arguments);this.$$parseLinkUrl=function(c,e){if(e&&"#"===e[0])return this.hash(e.slice(1)),!0;var f,g;a==Fa(c)?f=c:(g=pa(b,c))?f=a+d+g:b===c+"/"&&(f=b);f&&this.$$parse(f);return!!f};this.$$compose=function(){var b=Qb(this.$$search),e=this.$$hash?"#"+ob(this.$$hash):"";this.$$url=bc(this.$$path)+(b?"?"+b:"")+e;this.$$absUrl=a+d+this.$$url}}function Eb(a){return function(){return this[a]}}
+function id(a,b){return function(d){if(q(d))return this[a];this[a]=b(d);this.$$compose();return this}}function hf(){var a="",b={enabled:!1,requireBase:!0,rewriteLinks:!0};this.hashPrefix=function(b){return y(b)?(a=b,this):a};this.html5Mode=function(a){return $a(a)?(b.enabled=a,this):H(a)?($a(a.enabled)&&(b.enabled=a.enabled),$a(a.requireBase)&&(b.requireBase=a.requireBase),$a(a.rewriteLinks)&&(b.rewriteLinks=a.rewriteLinks),this):b};this.$get=["$rootScope","$browser","$sniffer","$rootElement","$window",
+function(d,c,e,f,g){function h(a,b,d){var e=l.url(),f=l.$$state;try{c.url(a,b,d),l.$$state=c.state()}catch(g){throw l.url(e),l.$$state=f,g;}}function k(a,b){d.$broadcast("$locationChangeSuccess",l.absUrl(),a,l.$$state,b)}var l,m;m=c.baseHref();var r=c.url(),t;if(b.enabled){if(!m&&b.requireBase)throw Db("nobase");t=r.substring(0,r.indexOf("/",r.indexOf("//")+2))+(m||"/");m=e.history?cc:hd}else t=Fa(r),m=dc;var A=t.substr(0,Fa(t).lastIndexOf("/")+1);l=new m(t,A,"#"+a);l.$$parseLinkUrl(r,r);l.$$state=
+c.state();var v=/^\s*(javascript|mailto):/i;f.on("click",function(a){if(b.rewriteLinks&&!a.ctrlKey&&!a.metaKey&&!a.shiftKey&&2!=a.which&&2!=a.button){for(var e=B(a.target);"a"!==ta(e[0]);)if(e[0]===f[0]||!(e=e.parent())[0])return;var h=e.prop("href"),k=e.attr("href")||e.attr("xlink:href");H(h)&&"[object SVGAnimatedString]"===h.toString()&&(h=wa(h.animVal).href);v.test(h)||!h||e.attr("target")||a.isDefaultPrevented()||!l.$$parseLinkUrl(h,k)||(a.preventDefault(),l.absUrl()!=c.url()&&(d.$apply(),g.angular["ff-684208-preventDefault"]=
+!0))}});ib(l.absUrl())!=ib(r)&&c.url(l.absUrl(),!0);var n=!0;c.onUrlChange(function(a,b){q(pa(A,a))?g.location.href=a:(d.$evalAsync(function(){var c=l.absUrl(),e=l.$$state,f;a=ib(a);l.$$parse(a);l.$$state=b;f=d.$broadcast("$locationChangeStart",a,c,b,e).defaultPrevented;l.absUrl()===a&&(f?(l.$$parse(c),l.$$state=e,h(c,!1,e)):(n=!1,k(c,e)))}),d.$$phase||d.$digest())});d.$watch(function(){var a=ib(c.url()),b=ib(l.absUrl()),f=c.state(),g=l.$$replace,m=a!==b||l.$$html5&&e.history&&f!==l.$$state;if(n||
+m)n=!1,d.$evalAsync(function(){var b=l.absUrl(),c=d.$broadcast("$locationChangeStart",b,a,l.$$state,f).defaultPrevented;l.absUrl()===b&&(c?(l.$$parse(a),l.$$state=f):(m&&h(b,g,f===l.$$state?null:l.$$state),k(a,f)))});l.$$replace=!1});return l}]}function jf(){var a=!0,b=this;this.debugEnabled=function(b){return y(b)?(a=b,this):a};this.$get=["$window",function(d){function c(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=d.console||{},e=b[a]||b.log||x;a=!1;try{a=!!e.apply}catch(k){}return a?function(){var a=[];n(arguments,function(b){a.push(c(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(){a&&c.apply(b,arguments)}}()}}]}function Va(a,b){if("__defineGetter__"===a||"__defineSetter__"===a||"__lookupGetter__"===a||"__lookupSetter__"===
+a||"__proto__"===a)throw ba("isecfld",b);return a}function jd(a,b){a+="";if(!E(a))throw ba("iseccst",b);return a}function xa(a,b){if(a){if(a.constructor===a)throw ba("isecfn",b);if(a.window===a)throw ba("isecwindow",b);if(a.children&&(a.nodeName||a.prop&&a.attr&&a.find))throw ba("isecdom",b);if(a===Object)throw ba("isecobj",b);}return a}function kd(a,b){if(a){if(a.constructor===a)throw ba("isecfn",b);if(a===Wf||a===Xf||a===Yf)throw ba("isecff",b);}}function ld(a,b){if(a&&(a===(0).constructor||a===
+(!1).constructor||a==="".constructor||a==={}.constructor||a===[].constructor||a===Function.constructor))throw ba("isecaf",b);}function Zf(a,b){return"undefined"!==typeof a?a:b}function md(a,b){return"undefined"===typeof a?b:"undefined"===typeof b?a:a+b}function W(a,b){var d,c;switch(a.type){case s.Program:d=!0;n(a.body,function(a){W(a.expression,b);d=d&&a.expression.constant});a.constant=d;break;case s.Literal:a.constant=!0;a.toWatch=[];break;case s.UnaryExpression:W(a.argument,b);a.constant=a.argument.constant;
+a.toWatch=a.argument.toWatch;break;case s.BinaryExpression:W(a.left,b);W(a.right,b);a.constant=a.left.constant&&a.right.constant;a.toWatch=a.left.toWatch.concat(a.right.toWatch);break;case s.LogicalExpression:W(a.left,b);W(a.right,b);a.constant=a.left.constant&&a.right.constant;a.toWatch=a.constant?[]:[a];break;case s.ConditionalExpression:W(a.test,b);W(a.alternate,b);W(a.consequent,b);a.constant=a.test.constant&&a.alternate.constant&&a.consequent.constant;a.toWatch=a.constant?[]:[a];break;case s.Identifier:a.constant=
+!1;a.toWatch=[a];break;case s.MemberExpression:W(a.object,b);a.computed&&W(a.property,b);a.constant=a.object.constant&&(!a.computed||a.property.constant);a.toWatch=[a];break;case s.CallExpression:d=a.filter?!b(a.callee.name).$stateful:!1;c=[];n(a.arguments,function(a){W(a,b);d=d&&a.constant;a.constant||c.push.apply(c,a.toWatch)});a.constant=d;a.toWatch=a.filter&&!b(a.callee.name).$stateful?c:[a];break;case s.AssignmentExpression:W(a.left,b);W(a.right,b);a.constant=a.left.constant&&a.right.constant;
+a.toWatch=[a];break;case s.ArrayExpression:d=!0;c=[];n(a.elements,function(a){W(a,b);d=d&&a.constant;a.constant||c.push.apply(c,a.toWatch)});a.constant=d;a.toWatch=c;break;case s.ObjectExpression:d=!0;c=[];n(a.properties,function(a){W(a.value,b);d=d&&a.value.constant;a.value.constant||c.push.apply(c,a.value.toWatch)});a.constant=d;a.toWatch=c;break;case s.ThisExpression:a.constant=!1,a.toWatch=[]}}function nd(a){if(1==a.length){a=a[0].expression;var b=a.toWatch;return 1!==b.length?b:b[0]!==a?b:u}}
+function od(a){return a.type===s.Identifier||a.type===s.MemberExpression}function pd(a){if(1===a.body.length&&od(a.body[0].expression))return{type:s.AssignmentExpression,left:a.body[0].expression,right:{type:s.NGValueParameter},operator:"="}}function qd(a){return 0===a.body.length||1===a.body.length&&(a.body[0].expression.type===s.Literal||a.body[0].expression.type===s.ArrayExpression||a.body[0].expression.type===s.ObjectExpression)}function rd(a,b){this.astBuilder=a;this.$filter=b}function sd(a,
+b){this.astBuilder=a;this.$filter=b}function Fb(a){return"constructor"==a}function ec(a){return z(a.valueOf)?a.valueOf():$f.call(a)}function kf(){var a=$(),b=$();this.$get=["$filter",function(d){function c(a,b){return null==a||null==b?a===b:"object"===typeof a&&(a=ec(a),"object"===typeof a)?!1:a===b||a!==a&&b!==b}function e(a,b,d,e,f){var g=e.inputs,h;if(1===g.length){var k=c,g=g[0];return a.$watch(function(a){var b=g(a);c(b,k)||(h=e(a,u,u,[b]),k=b&&ec(b));return h},b,d,f)}for(var l=[],m=[],r=0,n=
+g.length;r<n;r++)l[r]=c,m[r]=null;return a.$watch(function(a){for(var b=!1,d=0,f=g.length;d<f;d++){var k=g[d](a);if(b||(b=!c(k,l[d])))m[d]=k,l[d]=k&&ec(k)}b&&(h=e(a,u,u,m));return h},b,d,f)}function f(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);y(a)&&d.$$postDigest(function(){y(f)&&e()})},c)}function g(a,b,c,d){function e(a){var b=!0;n(a,function(a){y(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 h(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,d=!1,c=c!==g&&c!==f?function(c,e,f,g){f=d&&g?g[0]:a(c,e,f,g);return b(f,c,e)}:function(c,d,e,f){e=a(c,d,e,f);c=b(e,c,d);return y(e)?c:e};a.$$watchDelegate&&a.$$watchDelegate!==e?c.$$watchDelegate=a.$$watchDelegate:b.$stateful||(c.$$watchDelegate=
+e,d=!a.inputs,c.inputs=a.inputs?a.inputs:[a]);return c}var l=Ba().noUnsafeEval,m={csp:l,expensiveChecks:!1},r={csp:l,expensiveChecks:!0};return function(c,l,v){var n,p,q;switch(typeof c){case "string":q=c=c.trim();var w=v?b:a;n=w[q];n||(":"===c.charAt(0)&&":"===c.charAt(1)&&(p=!0,c=c.substring(2)),v=v?r:m,n=new fc(v),n=(new gc(n,d,v)).parse(c),n.constant?n.$$watchDelegate=h:p?n.$$watchDelegate=n.literal?g:f:n.inputs&&(n.$$watchDelegate=e),w[q]=n);return k(n,l);case "function":return k(c,l);default:return x}}}]}
+function mf(){this.$get=["$rootScope","$exceptionHandler",function(a,b){return td(function(b){a.$evalAsync(b)},b)}]}function nf(){this.$get=["$browser","$exceptionHandler",function(a,b){return td(function(b){a.defer(b)},b)}]}function td(a,b){function d(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 c(){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,a(function(){var a,
+d,e;e=c.pending;c.processScheduled=!1;c.pending=u;for(var f=0,g=e.length;f<g;++f){d=e[f][0];a=e[f][c.status];try{z(a)?d.resolve(a(c.value)):1===c.status?d.resolve(c.value):d.reject(c.value)}catch(h){d.reject(h),b(h)}}}))}function g(){this.promise=new c;this.resolve=e(this,this.resolve);this.reject=e(this,this.reject);this.notify=e(this,this.notify)}var h=G("$q",TypeError);M(c.prototype,{then:function(a,b,c){if(q(a)&&q(b)&&q(c))return this;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 l(b,!0,a)},function(b){return l(b,!1,a)},b)}});M(g.prototype,{resolve:function(a){this.promise.$$state.status||(a===this.promise?this.$$reject(h("qcycle",a)):this.$$resolve(a))},$$resolve:function(a){var c,e;e=d(this,this.$$resolve,this.$$reject);try{if(H(a)||z(a))c=a&&a.then;z(c)?(this.promise.$$state.status=
+-1,c.call(a,e[0],e[1],this.notify)):(this.promise.$$state.value=a,this.promise.$$state.status=1,f(this.promise.$$state))}catch(g){e[1](g),b(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&&a(function(){for(var a,e,f=0,g=d.length;f<g;f++){e=d[f][0];a=d[f][3];try{e.notify(z(a)?
+a(c):c)}catch(h){b(h)}}})}});var k=function(a,b){var c=new g;b?c.resolve(a):c.reject(a);return c.promise},l=function(a,b,c){var d=null;try{z(c)&&(d=c())}catch(e){return k(e,!1)}return d&&z(d.then)?d.then(function(){return k(a,b)},function(a){return k(a,!1)}):k(a,b)},m=function(a,b,c,d){var e=new g;e.resolve(a);return e.promise.then(b,c,d)},r=function A(a){if(!z(a))throw h("norslvr",a);if(!(this instanceof A))return new A(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=m;r.resolve=m;r.all=function(a){var b=new g,c=0,d=I(a)?[]:{};n(a,function(a,e){c++;m(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 wf(){this.$get=["$window","$timeout",function(a,b){var d=a.requestAnimationFrame||a.webkitRequestAnimationFrame,c=a.cancelAnimationFrame||a.webkitCancelAnimationFrame||
+a.webkitCancelRequestAnimationFrame,e=!!d,f=e?function(a){var b=d(a);return function(){c(b)}}:function(a){var c=b(a,16.66,!1);return function(){b.cancel(c)}};f.supported=e;return f}]}function lf(){function a(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 b=10,d=G("$rootScope"),c=null,e=null;this.digestTtl=function(a){arguments.length&&
+(b=a);return b};this.$get=["$injector","$exceptionHandler","$parse","$browser",function(f,g,h,k){function l(a){a.currentScope.$$destroyed=!0}function m(a){9===Ha&&(a.$$childHead&&m(a.$$childHead),a.$$nextSibling&&m(a.$$nextSibling));a.$parent=a.$$nextSibling=a.$$prevSibling=a.$$childHead=a.$$childTail=a.$root=a.$$watchers=null}function r(){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 t(a){if(w.$$phase)throw d("inprog",w.$$phase);w.$$phase=a}function A(a,b){do a.$$watchersCount+=b;while(a=a.$parent)}function v(a,b,c){do a.$$listenerCount[c]-=b,0===a.$$listenerCount[c]&&delete a.$$listenerCount[c];while(a=a.$parent)}function s(){}function p(){for(;aa.length;)try{aa.shift()()}catch(a){g(a)}e=null}function C(){null===e&&(e=k.defer(function(){w.$apply(p)}))}r.prototype={constructor:r,
+$new:function(b,c){var d;c=c||this;b?(d=new r,d.$root=this.$root):(this.$$ChildScope||(this.$$ChildScope=a(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;(b||c!=this)&&d.$on("$destroy",l);return d},$watch:function(a,b,d,e){var f=h(a);if(f.$$watchDelegate)return f.$$watchDelegate(this,b,d,f,a);var g=this,k=g.$$watchers,l={fn:b,last:s,get:f,exp:e||a,eq:!!d};c=null;z(b)||(l.fn=x);k||
+(k=g.$$watchers=[]);k.unshift(l);A(this,1);return function(){0<=ab(k,l)&&A(g,-1);c=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)});n(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(!q(e)){if(H(e))if(za(e))for(f!==r&&(f=r,n=f.length=0,l++),a=e.length,n!==a&&(l++,f.length=n=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!==t&&(f=t={},n=0,l++);a=0;for(b in e)qa.call(e,b)&&(a++,g=e[b],h=f[b],b in f?(d=h!==h&&g!==g,d||h===g||(l++,f[b]=g)):(n++,f[b]=g,l++));if(n>a)for(b in l++,f)qa.call(e,b)||(n--,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,m=
+h(a,c),r=[],t={},p=!0,n=0;return this.$watch(m,function(){p?(p=!1,b(e,e,d)):b(e,g,d);if(k)if(H(e))if(za(e)){g=Array(e.length);for(var a=0;a<e.length;a++)g[a]=e[a]}else for(a in g={},e)qa.call(e,a)&&(g[a]=e[a]);else g=e})},$digest:function(){var a,f,h,l,m,r,n=b,A,q=[],v,C;t("$digest");k.$$checkUrlChange();this===w&&null!==e&&(k.defer.cancel(e),p());c=null;do{r=!1;for(A=this;u.length;){try{C=u.shift(),C.scope.$eval(C.expression,C.locals)}catch(aa){g(aa)}c=null}a:do{if(l=A.$$watchers)for(m=l.length;m--;)try{if(a=
+l[m])if((f=a.get(A))!==(h=a.last)&&!(a.eq?ma(f,h):"number"===typeof f&&"number"===typeof h&&isNaN(f)&&isNaN(h)))r=!0,c=a,a.last=a.eq?bb(f,null):f,a.fn(f,h===s?f:h,A),5>n&&(v=4-n,q[v]||(q[v]=[]),q[v].push({msg:z(a.exp)?"fn: "+(a.exp.name||a.exp.toString()):a.exp,newVal:f,oldVal:h}));else if(a===c){r=!1;break a}}catch(y){g(y)}if(!(l=A.$$watchersCount&&A.$$childHead||A!==this&&A.$$nextSibling))for(;A!==this&&!(l=A.$$nextSibling);)A=A.$parent}while(A=l);if((r||u.length)&&!n--)throw w.$$phase=null,d("infdig",
+b,q);}while(r||u.length);for(w.$$phase=null;L.length;)try{L.shift()()}catch(x){g(x)}},$destroy:function(){if(!this.$$destroyed){var a=this.$parent;this.$broadcast("$destroy");this.$$destroyed=!0;this===w&&k.$$applicationDestroyed();A(this,-this.$$watchersCount);for(var b in this.$$listenerCount)v(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=x;this.$on=this.$watch=this.$watchGroup=function(){return x};this.$$listeners={};this.$$nextSibling=null;m(this)}},$eval:function(a,b){return h(a)(this,b)},$evalAsync:function(a,b){w.$$phase||u.length||k.defer(function(){u.length&&w.$digest()});u.push({scope:this,expression:a,locals:b})},$$postDigest:function(a){L.push(a)},$apply:function(a){try{t("$apply");
+try{return this.$eval(a)}finally{w.$$phase=null}}catch(b){g(b)}finally{try{w.$digest()}catch(c){throw g(c),c;}}},$applyAsync:function(a){function b(){c.$eval(a)}var c=this;a&&aa.push(b);C()},$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,v(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,m;do{d=e.$$listeners[a]||c;h.currentScope=e;l=0;for(m=d.length;l<m;l++)if(d[l])try{d[l].apply(null,k)}catch(r){g(r)}else d.splice(l,1),l--,m--;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 w=new r,u=w.$$asyncQueue=[],L=w.$$postDigestQueue=[],aa=w.$$applyAsyncQueue=[];return w}]}function ge(){var a=/^\s*(https?|ftp|mailto|tel|file):/,
+b=/^\s*((https?|ftp|file|blob):|data:image\/)/;this.aHrefSanitizationWhitelist=function(b){return y(b)?(a=b,this):a};this.imgSrcSanitizationWhitelist=function(a){return y(a)?(b=a,this):b};this.$get=function(){return function(d,c){var e=c?b:a,f;f=wa(d).href;return""===f||f.match(e)?d:"unsafe:"+f}}}function ag(a){if("self"===a)return a;if(E(a)){if(-1<a.indexOf("***"))throw ya("iwcard",a);a=ud(a).replace("\\*\\*",".*").replace("\\*","[^:/.?&;]*");return new RegExp("^"+a+"$")}if(Ma(a))return new RegExp("^"+
+a.source+"$");throw ya("imatcher");}function vd(a){var b=[];y(a)&&n(a,function(a){b.push(ag(a))});return b}function pf(){this.SCE_CONTEXTS=la;var a=["self"],b=[];this.resourceUrlWhitelist=function(b){arguments.length&&(a=vd(b));return a};this.resourceUrlBlacklist=function(a){arguments.length&&(b=vd(a));return b};this.$get=["$injector",function(d){function c(a,b){return"self"===a?ed(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 ya("unsafe");};d.has("$sanitize")&&(f=d.get("$sanitize"));var g=e(),h={};h[la.HTML]=e(g);h[la.CSS]=e(g);h[la.URL]=e(g);h[la.JS]=e(g);h[la.RESOURCE_URL]=e(h[la.URL]);return{trustAs:function(a,b){var c=h.hasOwnProperty(a)?h[a]:null;if(!c)throw ya("icontext",a,b);if(null===b||q(b)||""===b)return b;if("string"!==typeof b)throw ya("itype",
+a);return new c(b)},getTrusted:function(d,e){if(null===e||q(e)||""===e)return e;var g=h.hasOwnProperty(d)?h[d]:null;if(g&&e instanceof g)return e.$$unwrapTrustedValue();if(d===la.RESOURCE_URL){var g=wa(e.toString()),r,t,n=!1;r=0;for(t=a.length;r<t;r++)if(c(a[r],g)){n=!0;break}if(n)for(r=0,t=b.length;r<t;r++)if(c(b[r],g)){n=!1;break}if(n)return e;throw ya("insecurl",e.toString());}if(d===la.HTML)return f(e);throw ya("unsafe");},valueOf:function(a){return a instanceof g?a.$$unwrapTrustedValue():a}}}]}
+function of(){var a=!0;this.enabled=function(b){arguments.length&&(a=!!b);return a};this.$get=["$parse","$sceDelegate",function(b,d){if(a&&8>Ha)throw ya("iequirks");var c=ia(la);c.isEnabled=function(){return a};c.trustAs=d.trustAs;c.getTrusted=d.getTrusted;c.valueOf=d.valueOf;a||(c.trustAs=c.getTrusted=function(a,b){return b},c.valueOf=Ya);c.parseAs=function(a,d){var e=b(d);return e.literal&&e.constant?e:b(d,function(b){return c.getTrusted(a,b)})};var e=c.parseAs,f=c.getTrusted,g=c.trustAs;n(la,function(a,
+b){var d=F(b);c[fb("parse_as_"+d)]=function(b){return e(a,b)};c[fb("get_trusted_"+d)]=function(b){return f(a,b)};c[fb("trust_as_"+d)]=function(b){return g(a,b)}});return c}]}function qf(){this.$get=["$window","$document",function(a,b){var d={},c=ea((/android (\d+)/.exec(F((a.navigator||{}).userAgent))||[])[1]),e=/Boxee/i.test((a.navigator||{}).userAgent),f=b[0]||{},g,h=/^(Moz|webkit|ms)(?=[A-Z])/,k=f.body&&f.body.style,l=!1,m=!1;if(k){for(var r in k)if(l=h.exec(r)){g=l[0];g=g.substr(0,1).toUpperCase()+
+g.substr(1);break}g||(g="WebkitOpacity"in k&&"webkit");l=!!("transition"in k||g+"Transition"in k);m=!!("animation"in k||g+"Animation"in k);!c||l&&m||(l=E(k.webkitTransition),m=E(k.webkitAnimation))}return{history:!(!a.history||!a.history.pushState||4>c||e),hasEvent:function(a){if("input"===a&&11>=Ha)return!1;if(q(d[a])){var b=f.createElement("div");d[a]="on"+a in b}return d[a]},csp:Ba(),vendorPrefix:g,transitions:l,animations:m,android:c}}]}function sf(){this.$get=["$templateCache","$http","$q","$sce",
+function(a,b,d,c){function e(f,g){e.totalPendingRequests++;E(f)&&a.get(f)||(f=c.getTrustedResourceUrl(f));var h=b.defaults&&b.defaults.transformResponse;I(h)?h=h.filter(function(a){return a!==$b}):h===$b&&(h=null);return b.get(f,{cache:a,transformResponse:h})["finally"](function(){e.totalPendingRequests--}).then(function(b){a.put(f,b.data);return b.data},function(a){if(!g)throw ha("tpload",f,a.status,a.statusText);return d.reject(a)})}e.totalPendingRequests=0;return e}]}function tf(){this.$get=["$rootScope",
+"$browser","$location",function(a,b,d){return{findBindings:function(a,b,d){a=a.getElementsByClassName("ng-binding");var g=[];n(a,function(a){var c=fa.element(a).data("$binding");c&&n(c,function(c){d?(new RegExp("(^|\\s)"+ud(b)+"(\\s|\\||$)")).test(c)&&g.push(a):-1!=c.indexOf(b)&&g.push(a)})});return g},findModels:function(a,b,d){for(var g=["ng-","data-ng-","ng\\:"],h=0;h<g.length;++h){var k=a.querySelectorAll("["+g[h]+"model"+(d?"=":"*=")+'"'+b+'"]');if(k.length)return k}},getLocation:function(){return d.url()},
+setLocation:function(b){b!==d.url()&&(d.url(b),a.$digest())},whenStable:function(a){b.notifyWhenNoOutstandingRequests(a)}}}]}function uf(){this.$get=["$rootScope","$browser","$q","$$q","$exceptionHandler",function(a,b,d,c,e){function f(f,k,l){z(f)||(l=k,k=f,f=x);var m=ra.call(arguments,3),r=y(l)&&!l,t=(r?c:d).defer(),n=t.promise,q;q=b.defer(function(){try{t.resolve(f.apply(null,m))}catch(b){t.reject(b),e(b)}finally{delete g[n.$$timeoutId]}r||a.$apply()},k);n.$$timeoutId=q;g[q]=t;return n}var g={};
+f.cancel=function(a){return a&&a.$$timeoutId in g?(g[a.$$timeoutId].reject("canceled"),delete g[a.$$timeoutId],b.defer.cancel(a.$$timeoutId)):!1};return f}]}function wa(a){Ha&&(Y.setAttribute("href",a),a=Y.href);Y.setAttribute("href",a);return{href:Y.href,protocol:Y.protocol?Y.protocol.replace(/:$/,""):"",host:Y.host,search:Y.search?Y.search.replace(/^\?/,""):"",hash:Y.hash?Y.hash.replace(/^#/,""):"",hostname:Y.hostname,port:Y.port,pathname:"/"===Y.pathname.charAt(0)?Y.pathname:"/"+Y.pathname}}function ed(a){a=
+E(a)?wa(a):a;return a.protocol===wd.protocol&&a.host===wd.host}function vf(){this.$get=na(S)}function xd(a){function b(a){try{return decodeURIComponent(a)}catch(b){return a}}var d=a[0]||{},c={},e="";return function(){var a,g,h,k,l;a=d.cookie||"";if(a!==e)for(e=a,a=e.split("; "),c={},h=0;h<a.length;h++)g=a[h],k=g.indexOf("="),0<k&&(l=b(g.substring(0,k)),q(c[l])&&(c[l]=b(g.substring(k+1))));return c}}function zf(){this.$get=xd}function Jc(a){function b(d,c){if(H(d)){var e={};n(d,function(a,c){e[c]=
+b(c,a)});return e}return a.factory(d+"Filter",c)}this.register=b;this.$get=["$injector",function(a){return function(b){return a.get(b+"Filter")}}];b("currency",yd);b("date",zd);b("filter",bg);b("json",cg);b("limitTo",dg);b("lowercase",eg);b("number",Ad);b("orderBy",Bd);b("uppercase",fg)}function bg(){return function(a,b,d){if(!za(a)){if(null==a)return a;throw G("filter")("notarray",a);}var c;switch(hc(b)){case "function":break;case "boolean":case "null":case "number":case "string":c=!0;case "object":b=
+gg(b,d,c);break;default:return a}return Array.prototype.filter.call(a,b)}}function gg(a,b,d){var c=H(a)&&"$"in a;!0===b?b=ma:z(b)||(b=function(a,b){if(q(a))return!1;if(null===a||null===b)return a===b;if(H(b)||H(a)&&!qc(a))return!1;a=F(""+a);b=F(""+b);return-1!==a.indexOf(b)});return function(e){return c&&!H(e)?Ka(e,a.$,b,!1):Ka(e,a,b,d)}}function Ka(a,b,d,c,e){var f=hc(a),g=hc(b);if("string"===g&&"!"===b.charAt(0))return!Ka(a,b.substring(1),d,c);if(I(a))return a.some(function(a){return Ka(a,b,d,c)});
+switch(f){case "object":var h;if(c){for(h in a)if("$"!==h.charAt(0)&&Ka(a[h],b,d,!0))return!0;return e?!1:Ka(a,b,d,!1)}if("object"===g){for(h in b)if(e=b[h],!z(e)&&!q(e)&&(f="$"===h,!Ka(f?a:a[h],e,d,f,f)))return!1;return!0}return d(a,b);case "function":return!1;default:return d(a,b)}}function hc(a){return null===a?"null":typeof a}function yd(a){var b=a.NUMBER_FORMATS;return function(a,c,e){q(c)&&(c=b.CURRENCY_SYM);q(e)&&(e=b.PATTERNS[1].maxFrac);return null==a?a:Cd(a,b.PATTERNS[1],b.GROUP_SEP,b.DECIMAL_SEP,
+e).replace(/\u00A4/g,c)}}function Ad(a){var b=a.NUMBER_FORMATS;return function(a,c){return null==a?a:Cd(a,b.PATTERNS[0],b.GROUP_SEP,b.DECIMAL_SEP,c)}}function Cd(a,b,d,c,e){if(H(a))return"";var f=0>a;a=Math.abs(a);var g=Infinity===a;if(!g&&!isFinite(a))return"";var h=a+"",k="",l=!1,m=[];g&&(k="\u221e");if(!g&&-1!==h.indexOf("e")){var r=h.match(/([\d\.]+)e(-?)(\d+)/);r&&"-"==r[2]&&r[3]>e+1?a=0:(k=h,l=!0)}if(g||l)0<e&&1>a&&(k=a.toFixed(e),a=parseFloat(k),k=k.replace(ic,c));else{g=(h.split(ic)[1]||"").length;
+q(e)&&(e=Math.min(Math.max(b.minFrac,g),b.maxFrac));a=+(Math.round(+(a.toString()+"e"+e)).toString()+"e"+-e);var g=(""+a).split(ic),h=g[0],g=g[1]||"",r=0,t=b.lgSize,n=b.gSize;if(h.length>=t+n)for(r=h.length-t,l=0;l<r;l++)0===(r-l)%n&&0!==l&&(k+=d),k+=h.charAt(l);for(l=r;l<h.length;l++)0===(h.length-l)%t&&0!==l&&(k+=d),k+=h.charAt(l);for(;g.length<e;)g+="0";e&&"0"!==e&&(k+=c+g.substr(0,e))}0===a&&(f=!1);m.push(f?b.negPre:b.posPre,k,f?b.negSuf:b.posSuf);return m.join("")}function Gb(a,b,d){var c="";
+0>a&&(c="-",a=-a);for(a=""+a;a.length<b;)a="0"+a;d&&(a=a.substr(a.length-b));return c+a}function ca(a,b,d,c){d=d||0;return function(e){e=e["get"+a]();if(0<d||e>-d)e+=d;0===e&&-12==d&&(e=12);return Gb(e,b,c)}}function Hb(a,b){return function(d,c){var e=d["get"+a](),f=sb(b?"SHORT"+a:a);return c[f][e]}}function Dd(a){var b=(new Date(a,0,1)).getDay();return new Date(a,0,(4>=b?5:12)-b)}function Ed(a){return function(b){var d=Dd(b.getFullYear());b=+new Date(b.getFullYear(),b.getMonth(),b.getDate()+(4-b.getDay()))-
++d;b=1+Math.round(b/6048E5);return Gb(b,a)}}function jc(a,b){return 0>=a.getFullYear()?b.ERAS[0]:b.ERAS[1]}function zd(a){function b(a){var b;if(b=a.match(d)){a=new Date(0);var f=0,g=0,h=b[8]?a.setUTCFullYear:a.setFullYear,k=b[8]?a.setUTCHours:a.setHours;b[9]&&(f=ea(b[9]+b[10]),g=ea(b[9]+b[11]));h.call(a,ea(b[1]),ea(b[2])-1,ea(b[3]));f=ea(b[4]||0)-f;g=ea(b[5]||0)-g;h=ea(b[6]||0);b=Math.round(1E3*parseFloat("0."+(b[7]||0)));k.call(a,f,g,h,b)}return a}var d=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
+return function(c,d,f){var g="",h=[],k,l;d=d||"mediumDate";d=a.DATETIME_FORMATS[d]||d;E(c)&&(c=hg.test(c)?ea(c):b(c));Q(c)&&(c=new Date(c));if(!da(c)||!isFinite(c.getTime()))return c;for(;d;)(l=ig.exec(d))?(h=cb(h,l,1),d=h.pop()):(h.push(d),d=null);var m=c.getTimezoneOffset();f&&(m=vc(f,c.getTimezoneOffset()),c=Pb(c,f,!0));n(h,function(b){k=jg[b];g+=k?k(c,a.DATETIME_FORMATS,m):b.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return g}}function cg(){return function(a,b){q(b)&&(b=2);return db(a,b)}}function dg(){return function(a,
+b,d){b=Infinity===Math.abs(Number(b))?Number(b):ea(b);if(isNaN(b))return a;Q(a)&&(a=a.toString());if(!I(a)&&!E(a))return a;d=!d||isNaN(d)?0:ea(d);d=0>d?Math.max(0,a.length+d):d;return 0<=b?a.slice(d,d+b):0===d?a.slice(b,a.length):a.slice(Math.max(0,d+b),d)}}function Bd(a){function b(b,d){d=d?-1:1;return b.map(function(b){var c=1,h=Ya;if(z(b))h=b;else if(E(b)){if("+"==b.charAt(0)||"-"==b.charAt(0))c="-"==b.charAt(0)?-1:1,b=b.substring(1);if(""!==b&&(h=a(b),h.constant))var k=h(),h=function(a){return a[k]}}return{get:h,
+descending:c*d}})}function d(a){switch(typeof a){case "number":case "boolean":case "string":return!0;default:return!1}}return function(a,e,f){if(!za(a))return a;I(e)||(e=[e]);0===e.length&&(e=["+"]);var g=b(e,f);g.push({get:function(){return{}},descending:f?-1:1});a=Array.prototype.map.call(a,function(a,b){return{value:a,predicateValues:g.map(function(c){var e=c.get(a);c=typeof e;if(null===e)c="string",e="null";else if("string"===c)e=e.toLowerCase();else if("object"===c)a:{if("function"===typeof e.valueOf&&
+(e=e.valueOf(),d(e)))break a;if(qc(e)&&(e=e.toString(),d(e)))break a;e=b}return{value:e,type:c}})}});a.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],n=0;c.type===f.type?c.value!==f.value&&(n=c.value<f.value?-1:1):n=c.type<f.type?-1:1;if(c=n*g[d].descending)break}return c});return a=a.map(function(a){return a.value})}}function La(a){z(a)&&(a={link:a});a.restrict=a.restrict||"AC";return na(a)}function Fd(a,b,d,c,e){var f=this,g=[];f.$error=
+{};f.$$success={};f.$pending=u;f.$name=e(b.name||b.ngForm||"")(d);f.$dirty=!1;f.$pristine=!0;f.$valid=!0;f.$invalid=!1;f.$submitted=!1;f.$$parentForm=Ib;f.$rollbackViewValue=function(){n(g,function(a){a.$rollbackViewValue()})};f.$commitViewValue=function(){n(g,function(a){a.$commitViewValue()})};f.$addControl=function(a){Ra(a.$name,"input");g.push(a);a.$name&&(f[a.$name]=a);a.$$parentForm=f};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];n(f.$pending,function(b,c){f.$setValidity(c,null,a)});n(f.$error,function(b,c){f.$setValidity(c,null,a)});n(f.$$success,function(b,c){f.$setValidity(c,null,a)});ab(g,a);a.$$parentForm=Ib};Gd({ctrl:this,$element:a,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&&(ab(d,c),0===d.length&&delete a[b])},$animate:c});f.$setDirty=function(){c.removeClass(a,Wa);c.addClass(a,Jb);f.$dirty=!0;f.$pristine=!1;f.$$parentForm.$setDirty()};
+f.$setPristine=function(){c.setClass(a,Wa,Jb+" ng-submitted");f.$dirty=!1;f.$pristine=!0;f.$submitted=!1;n(g,function(a){a.$setPristine()})};f.$setUntouched=function(){n(g,function(a){a.$setUntouched()})};f.$setSubmitted=function(){c.addClass(a,"ng-submitted");f.$submitted=!0;f.$$parentForm.$setSubmitted()}}function kc(a){a.$formatters.push(function(b){return a.$isEmpty(b)?b:b.toString()})}function jb(a,b,d,c,e,f){var g=F(b[0].type);if(!e.android){var h=!1;b.on("compositionstart",function(a){h=!0});
+b.on("compositionend",function(){h=!1;k()})}var k=function(a){l&&(f.defer.cancel(l),l=null);if(!h){var e=b.val();a=a&&a.type;"password"===g||d.ngTrim&&"false"===d.ngTrim||(e=U(e));(c.$viewValue!==e||""===e&&c.$$hasNativeValidators)&&c.$setViewValue(e,a)}};if(e.hasEvent("input"))b.on("input",k);else{var l,m=function(a,b,c){l||(l=f.defer(function(){l=null;b&&b.value===c||k(a)}))};b.on("keydown",function(a){var b=a.keyCode;91===b||15<b&&19>b||37<=b&&40>=b||m(a,this,this.value)});if(e.hasEvent("paste"))b.on("paste cut",
+m)}b.on("change",k);c.$render=function(){var a=c.$isEmpty(c.$viewValue)?"":c.$viewValue;b.val()!==a&&b.val(a)}}function Kb(a,b){return function(d,c){var e,f;if(da(d))return d;if(E(d)){'"'==d.charAt(0)&&'"'==d.charAt(d.length-1)&&(d=d.substring(1,d.length-1));if(kg.test(d))return new Date(d);a.lastIndex=0;if(e=a.exec(d))return e.shift(),f=c?{yyyy:c.getFullYear(),MM:c.getMonth()+1,dd:c.getDate(),HH:c.getHours(),mm:c.getMinutes(),ss:c.getSeconds(),sss:c.getMilliseconds()/1E3}:{yyyy:1970,MM:1,dd:1,HH:0,
+mm:0,ss:0,sss:0},n(e,function(a,c){c<b.length&&(f[b[c]]=+a)}),new Date(f.yyyy,f.MM-1,f.dd,f.HH,f.mm,f.ss||0,1E3*f.sss||0)}return NaN}}function kb(a,b,d,c){return function(e,f,g,h,k,l,m){function r(a){return a&&!(a.getTime&&a.getTime()!==a.getTime())}function n(a){return y(a)&&!da(a)?d(a)||u:a}Hd(e,f,g,h);jb(e,f,g,h,k,l);var A=h&&h.$options&&h.$options.timezone,v;h.$$parserName=a;h.$parsers.push(function(a){return h.$isEmpty(a)?null:b.test(a)?(a=d(a,v),A&&(a=Pb(a,A)),a):u});h.$formatters.push(function(a){if(a&&
+!da(a))throw lb("datefmt",a);if(r(a))return(v=a)&&A&&(v=Pb(v,A,!0)),m("date")(a,c,A);v=null;return""});if(y(g.min)||g.ngMin){var s;h.$validators.min=function(a){return!r(a)||q(s)||d(a)>=s};g.$observe("min",function(a){s=n(a);h.$validate()})}if(y(g.max)||g.ngMax){var p;h.$validators.max=function(a){return!r(a)||q(p)||d(a)<=p};g.$observe("max",function(a){p=n(a);h.$validate()})}}}function Hd(a,b,d,c){(c.$$hasNativeValidators=H(b[0].validity))&&c.$parsers.push(function(a){var c=b.prop("validity")||{};
+return c.badInput&&!c.typeMismatch?u:a})}function Id(a,b,d,c,e){if(y(c)){a=a(c);if(!a.constant)throw lb("constexpr",d,c);return a(b)}return e}function lc(a,b){a="ngClass"+a;return["$animate",function(d){function c(a,b){var c=[],d=0;a:for(;d<a.length;d++){for(var e=a[d],m=0;m<b.length;m++)if(e==b[m])continue a;c.push(e)}return c}function e(a){var b=[];return I(a)?(n(a,function(a){b=b.concat(e(a))}),b):E(a)?a.split(" "):H(a)?(n(a,function(a,c){a&&(b=b.concat(c.split(" ")))}),b):a}return{restrict:"AC",
+link:function(f,g,h){function k(a,b){var c=g.data("$classCounts")||$(),d=[];n(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 l(a){if(!0===b||f.$index%2===b){var l=e(a||[]);if(!m){var n=k(l,1);h.$addClass(n)}else if(!ma(a,m)){var q=e(m),n=c(l,q),l=c(q,l),n=k(n,1),l=k(l,-1);n&&n.length&&d.addClass(g,n);l&&l.length&&d.removeClass(g,l)}}m=ia(a)}var m;f.$watch(h[a],l,!0);h.$observe("class",function(b){l(f.$eval(h[a]))});"ngClass"!==
+a&&f.$watch("$index",function(c,d){var g=c&1;if(g!==(d&1)){var l=e(f.$eval(h[a]));g===b?(g=k(l,1),h.$addClass(g)):(g=k(l,-1),h.$removeClass(g))}})}}}]}function Gd(a){function b(a,b){b&&!f[a]?(k.addClass(e,a),f[a]=!0):!b&&f[a]&&(k.removeClass(e,a),f[a]=!1)}function d(a,c){a=a?"-"+zc(a,"-"):"";b(mb+a,!0===c);b(Jd+a,!1===c)}var c=a.ctrl,e=a.$element,f={},g=a.set,h=a.unset,k=a.$animate;f[Jd]=!(f[mb]=e.hasClass(mb));c.$setValidity=function(a,e,f){q(e)?(c.$pending||(c.$pending={}),g(c.$pending,a,f)):(c.$pending&&
+h(c.$pending,a,f),Kd(c.$pending)&&(c.$pending=u));$a(e)?e?(h(c.$error,a,f),g(c.$$success,a,f)):(g(c.$error,a,f),h(c.$$success,a,f)):(h(c.$error,a,f),h(c.$$success,a,f));c.$pending?(b(Ld,!0),c.$valid=c.$invalid=u,d("",null)):(b(Ld,!1),c.$valid=Kd(c.$error),c.$invalid=!c.$valid,d("",c.$valid));e=c.$pending&&c.$pending[a]?u:c.$error[a]?!1:c.$$success[a]?!0:null;d(a,e);c.$$parentForm.$setValidity(a,e,c)}}function Kd(a){if(a)for(var b in a)if(a.hasOwnProperty(b))return!1;return!0}var lg=/^\/(.+)\/([a-z]*)$/,
+F=function(a){return E(a)?a.toLowerCase():a},qa=Object.prototype.hasOwnProperty,sb=function(a){return E(a)?a.toUpperCase():a},Ha,B,oa,ra=[].slice,Pf=[].splice,mg=[].push,sa=Object.prototype.toString,rc=Object.getPrototypeOf,Aa=G("ng"),fa=S.angular||(S.angular={}),Sb,nb=0;Ha=X.documentMode;x.$inject=[];Ya.$inject=[];var I=Array.isArray,Vd=/^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/,U=function(a){return E(a)?a.trim():a},ud=function(a){return a.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,
+"\\$1").replace(/\x08/g,"\\x08")},Ba=function(){if(!y(Ba.rules)){var a=X.querySelector("[ng-csp]")||X.querySelector("[data-ng-csp]");if(a){var b=a.getAttribute("ng-csp")||a.getAttribute("data-ng-csp");Ba.rules={noUnsafeEval:!b||-1!==b.indexOf("no-unsafe-eval"),noInlineStyle:!b||-1!==b.indexOf("no-inline-style")}}else{a=Ba;try{new Function(""),b=!1}catch(d){b=!0}a.rules={noUnsafeEval:b,noInlineStyle:!1}}}return Ba.rules},pb=function(){if(y(pb.name_))return pb.name_;var a,b,d=Oa.length,c,e;for(b=0;b<
+d;++b)if(c=Oa[b],a=X.querySelector("["+c.replace(":","\\:")+"jq]")){e=a.getAttribute(c+"jq");break}return pb.name_=e},Oa=["ng-","data-ng-","ng:","x-ng-"],be=/[A-Z]/g,Ac=!1,Rb,Na=3,fe={full:"1.4.8",major:1,minor:4,dot:8,codeName:"ice-manipulation"};N.expando="ng339";var gb=N.cache={},Ff=1;N._data=function(a){return this.cache[a[this.expando]]||{}};var Af=/([\:\-\_]+(.))/g,Bf=/^moz([A-Z])/,xb={mouseleave:"mouseout",mouseenter:"mouseover"},Ub=G("jqLite"),Ef=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,Tb=/<|&#?\w+;/,
+Cf=/<([\w:-]+)/,Df=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,ka={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,"",""]};ka.optgroup=ka.option;ka.tbody=ka.tfoot=ka.colgroup=ka.caption=ka.thead;ka.th=ka.td;var Kf=Node.prototype.contains||function(a){return!!(this.compareDocumentPosition(a)&
+16)},Pa=N.prototype={ready:function(a){function b(){d||(d=!0,a())}var d=!1;"complete"===X.readyState?setTimeout(b):(this.on("DOMContentLoaded",b),N(S).on("load",b))},toString:function(){var a=[];n(this,function(b){a.push(""+b)});return"["+a.join(", ")+"]"},eq:function(a){return 0<=a?B(this[a]):B(this[this.length+a])},length:0,push:mg,sort:[].sort,splice:[].splice},Cb={};n("multiple selected checked disabled readOnly required open".split(" "),function(a){Cb[F(a)]=a});var Rc={};n("input select option textarea button form details".split(" "),
+function(a){Rc[a]=!0});var Zc={ngMinlength:"minlength",ngMaxlength:"maxlength",ngMin:"min",ngMax:"max",ngPattern:"pattern"};n({data:Wb,removeData:vb,hasData:function(a){for(var b in gb[a.ng339])return!0;return!1}},function(a,b){N[b]=a});n({data:Wb,inheritedData:Bb,scope:function(a){return B.data(a,"$scope")||Bb(a.parentNode||a,["$isolateScope","$scope"])},isolateScope:function(a){return B.data(a,"$isolateScope")||B.data(a,"$isolateScopeNoTemplate")},controller:Oc,injector:function(a){return Bb(a,
+"$injector")},removeAttr:function(a,b){a.removeAttribute(b)},hasClass:yb,css:function(a,b,d){b=fb(b);if(y(d))a.style[b]=d;else return a.style[b]},attr:function(a,b,d){var c=a.nodeType;if(c!==Na&&2!==c&&8!==c)if(c=F(b),Cb[c])if(y(d))d?(a[b]=!0,a.setAttribute(b,c)):(a[b]=!1,a.removeAttribute(c));else return a[b]||(a.attributes.getNamedItem(b)||x).specified?c:u;else if(y(d))a.setAttribute(b,d);else if(a.getAttribute)return a=a.getAttribute(b,2),null===a?u:a},prop:function(a,b,d){if(y(d))a[b]=d;else return a[b]},
+text:function(){function a(a,d){if(q(d)){var c=a.nodeType;return 1===c||c===Na?a.textContent:""}a.textContent=d}a.$dv="";return a}(),val:function(a,b){if(q(b)){if(a.multiple&&"select"===ta(a)){var d=[];n(a.options,function(a){a.selected&&d.push(a.value||a.text)});return 0===d.length?null:d}return a.value}a.value=b},html:function(a,b){if(q(b))return a.innerHTML;ub(a,!0);a.innerHTML=b},empty:Pc},function(a,b){N.prototype[b]=function(b,c){var e,f,g=this.length;if(a!==Pc&&q(2==a.length&&a!==yb&&a!==Oc?
+b:c)){if(H(b)){for(e=0;e<g;e++)if(a===Wb)a(this[e],b);else for(f in b)a(this[e],f,b[f]);return this}e=a.$dv;g=q(e)?Math.min(g,1):g;for(f=0;f<g;f++){var h=a(this[f],b,c);e=e?e+h:h}return e}for(e=0;e<g;e++)a(this[e],b,c);return this}});n({removeData:vb,on:function(a,b,d,c){if(y(c))throw Ub("onargs");if(Kc(a)){c=wb(a,!0);var e=c.events,f=c.handle;f||(f=c.handle=Hf(a,e));c=0<=b.indexOf(" ")?b.split(" "):[b];for(var g=c.length,h=function(b,c,g){var h=e[b];h||(h=e[b]=[],h.specialHandlerWrapper=c,"$destroy"===
+b||g||a.addEventListener(b,f,!1));h.push(d)};g--;)b=c[g],xb[b]?(h(xb[b],Jf),h(b,u,!0)):h(b)}},off:Nc,one:function(a,b,d){a=B(a);a.on(b,function e(){a.off(b,d);a.off(b,e)});a.on(b,d)},replaceWith:function(a,b){var d,c=a.parentNode;ub(a);n(new N(b),function(b){d?c.insertBefore(b,d.nextSibling):c.replaceChild(b,a);d=b})},children:function(a){var b=[];n(a.childNodes,function(a){1===a.nodeType&&b.push(a)});return b},contents:function(a){return a.contentDocument||a.childNodes||[]},append:function(a,b){var d=
+a.nodeType;if(1===d||11===d){b=new N(b);for(var d=0,c=b.length;d<c;d++)a.appendChild(b[d])}},prepend:function(a,b){if(1===a.nodeType){var d=a.firstChild;n(new N(b),function(b){a.insertBefore(b,d)})}},wrap:function(a,b){b=B(b).eq(0).clone()[0];var d=a.parentNode;d&&d.replaceChild(b,a);b.appendChild(a)},remove:Xb,detach:function(a){Xb(a,!0)},after:function(a,b){var d=a,c=a.parentNode;b=new N(b);for(var e=0,f=b.length;e<f;e++){var g=b[e];c.insertBefore(g,d.nextSibling);d=g}},addClass:Ab,removeClass:zb,
+toggleClass:function(a,b,d){b&&n(b.split(" "),function(b){var e=d;q(e)&&(e=!yb(a,b));(e?Ab:zb)(a,b)})},parent:function(a){return(a=a.parentNode)&&11!==a.nodeType?a:null},next:function(a){return a.nextElementSibling},find:function(a,b){return a.getElementsByTagName?a.getElementsByTagName(b):[]},clone:Vb,triggerHandler:function(a,b,d){var c,e,f=b.type||b,g=wb(a);if(g=(g=g&&g.events)&&g[f])c={preventDefault:function(){this.defaultPrevented=!0},isDefaultPrevented:function(){return!0===this.defaultPrevented},
+stopImmediatePropagation:function(){this.immediatePropagationStopped=!0},isImmediatePropagationStopped:function(){return!0===this.immediatePropagationStopped},stopPropagation:x,type:f,target:a},b.type&&(c=M(c,b)),b=ia(g),e=d?[c].concat(d):[c],n(b,function(b){c.isImmediatePropagationStopped()||b.apply(a,e)})}},function(a,b){N.prototype[b]=function(b,c,e){for(var f,g=0,h=this.length;g<h;g++)q(f)?(f=a(this[g],b,c,e),y(f)&&(f=B(f))):Mc(f,a(this[g],b,c,e));return y(f)?f:this};N.prototype.bind=N.prototype.on;
+N.prototype.unbind=N.prototype.off});Sa.prototype={put:function(a,b){this[Ca(a,this.nextUid)]=b},get:function(a){return this[Ca(a,this.nextUid)]},remove:function(a){var b=this[a=Ca(a,this.nextUid)];delete this[a];return b}};var yf=[function(){this.$get=[function(){return Sa}]}],Tc=/^[^\(]*\(\s*([^\)]*)\)/m,ng=/,/,og=/^\s*(_?)(\S+?)\1\s*$/,Sc=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,Da=G("$injector");eb.$$annotate=function(a,b,d){var c;if("function"===typeof a){if(!(c=a.$inject)){c=[];if(a.length){if(b)throw E(d)&&
+d||(d=a.name||Lf(a)),Da("strictdi",d);b=a.toString().replace(Sc,"");b=b.match(Tc);n(b[1].split(ng),function(a){a.replace(og,function(a,b,d){c.push(d)})})}a.$inject=c}}else I(a)?(b=a.length-1,Qa(a[b],"fn"),c=a.slice(0,b)):Qa(a,"fn",!0);return c};var Md=G("$animate"),Ue=function(){this.$get=["$q","$$rAF",function(a,b){function d(){}d.all=x;d.chain=x;d.prototype={end:x,cancel:x,resume:x,pause:x,complete:x,then:function(c,d){return a(function(a){b(function(){a()})}).then(c,d)}};return d}]},Te=function(){var a=
+new Sa,b=[];this.$get=["$$AnimateRunner","$rootScope",function(d,c){function e(a,b,c){var d=!1;b&&(b=E(b)?b.split(" "):I(b)?b:[],n(b,function(b){b&&(d=!0,a[b]=c)}));return d}function f(){n(b,function(b){var c=a.get(b);if(c){var d=Mf(b.attr("class")),e="",f="";n(c,function(a,b){a!==!!d[b]&&(a?e+=(e.length?" ":"")+b:f+=(f.length?" ":"")+b)});n(b,function(a){e&&Ab(a,e);f&&zb(a,f)});a.remove(b)}});b.length=0}return{enabled:x,on:x,off:x,pin:x,push:function(g,h,k,l){l&&l();k=k||{};k.from&&g.css(k.from);
+k.to&&g.css(k.to);if(k.addClass||k.removeClass)if(h=k.addClass,l=k.removeClass,k=a.get(g)||{},h=e(k,h,!0),l=e(k,l,!1),h||l)a.put(g,k),b.push(g),1===b.length&&c.$$postDigest(f);return new d}}}]},Re=["$provide",function(a){var b=this;this.$$registeredAnimations=Object.create(null);this.register=function(d,c){if(d&&"."!==d.charAt(0))throw Md("notcsel",d);var e=d+"-animation";b.$$registeredAnimations[d.substr(1)]=e;a.factory(e,c)};this.classNameFilter=function(a){if(1===arguments.length&&(this.$$classNameFilter=
+a instanceof RegExp?a:null)&&/(\s+|\/)ng-animate(\s+|\/)/.test(this.$$classNameFilter.toString()))throw Md("nongcls","ng-animate");return this.$$classNameFilter};this.$get=["$$animateQueue",function(a){function b(a,c,d){if(d){var h;a:{for(h=0;h<d.length;h++){var k=d[h];if(1===k.nodeType){h=k;break a}}h=void 0}!h||h.parentNode||h.previousElementSibling||(d=null)}d?d.after(a):c.prepend(a)}return{on:a.on,off:a.off,pin:a.pin,enabled:a.enabled,cancel:function(a){a.end&&a.end()},enter:function(e,f,g,h){f=
+f&&B(f);g=g&&B(g);f=f||g.parent();b(e,f,g);return a.push(e,"enter",Ea(h))},move:function(e,f,g,h){f=f&&B(f);g=g&&B(g);f=f||g.parent();b(e,f,g);return a.push(e,"move",Ea(h))},leave:function(b,c){return a.push(b,"leave",Ea(c),function(){b.remove()})},addClass:function(b,c,g){g=Ea(g);g.addClass=hb(g.addclass,c);return a.push(b,"addClass",g)},removeClass:function(b,c,g){g=Ea(g);g.removeClass=hb(g.removeClass,c);return a.push(b,"removeClass",g)},setClass:function(b,c,g,h){h=Ea(h);h.addClass=hb(h.addClass,
+c);h.removeClass=hb(h.removeClass,g);return a.push(b,"setClass",h)},animate:function(b,c,g,h,k){k=Ea(k);k.from=k.from?M(k.from,c):c;k.to=k.to?M(k.to,g):g;k.tempClasses=hb(k.tempClasses,h||"ng-inline-animate");return a.push(b,"animate",k)}}}]}],Se=function(){this.$get=["$$rAF","$q",function(a,b){var d=function(){};d.prototype={done:function(a){this.defer&&this.defer[!0===a?"reject":"resolve"]()},end:function(){this.done()},cancel:function(){this.done(!0)},getPromise:function(){this.defer||(this.defer=
+b.defer());return this.defer.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)}};return function(b,e){function f(){a(function(){e.addClass&&(b.addClass(e.addClass),e.addClass=null);e.removeClass&&(b.removeClass(e.removeClass),e.removeClass=null);e.to&&(b.css(e.to),e.to=null);g||h.done();g=!0});return h}e.cleanupStyles&&(e.from=e.to=null);e.from&&(b.css(e.from),e.from=
+null);var g,h=new d;return{start:f,end:f}}}]},ha=G("$compile");Cc.$inject=["$provide","$$sanitizeUriProvider"];var Vc=/^((?:x|data)[\:\-_])/i,Qf=G("$controller"),Uc=/^(\S+)(\s+as\s+(\w+))?$/,$e=function(){this.$get=["$document",function(a){return function(b){b?!b.nodeType&&b instanceof B&&(b=b[0]):b=a[0].body;return b.offsetWidth+1}}]},$c="application/json",ac={"Content-Type":$c+";charset=utf-8"},Sf=/^\[|^\{(?!\{)/,Tf={"[":/]$/,"{":/}$/},Rf=/^\)\]\}',?\n/,pg=G("$http"),dd=function(a){return function(){throw pg("legacy",
+a);}},Ja=fa.$interpolateMinErr=G("$interpolate");Ja.throwNoconcat=function(a){throw Ja("noconcat",a);};Ja.interr=function(a,b){return Ja("interr",a,b.toString())};var qg=/^([^\?#]*)(\?([^#]*))?(#(.*))?$/,Vf={http:80,https:443,ftp:21},Db=G("$location"),rg={$$html5:!1,$$replace:!1,absUrl:Eb("$$absUrl"),url:function(a){if(q(a))return this.$$url;var b=qg.exec(a);(b[1]||""===a)&&this.path(decodeURIComponent(b[1]));(b[2]||b[1]||""===a)&&this.search(b[3]||"");this.hash(b[5]||"");return this},protocol:Eb("$$protocol"),
+host:Eb("$$host"),port:Eb("$$port"),path:id("$$path",function(a){a=null!==a?a.toString():"";return"/"==a.charAt(0)?a:"/"+a}),search:function(a,b){switch(arguments.length){case 0:return this.$$search;case 1:if(E(a)||Q(a))a=a.toString(),this.$$search=xc(a);else if(H(a))a=bb(a,{}),n(a,function(b,c){null==b&&delete a[c]}),this.$$search=a;else throw Db("isrcharg");break;default:q(b)||null===b?delete this.$$search[a]:this.$$search[a]=b}this.$$compose();return this},hash:id("$$hash",function(a){return null!==
+a?a.toString():""}),replace:function(){this.$$replace=!0;return this}};n([hd,dc,cc],function(a){a.prototype=Object.create(rg);a.prototype.state=function(b){if(!arguments.length)return this.$$state;if(a!==cc||!this.$$html5)throw Db("nostate");this.$$state=q(b)?null:b;return this}});var ba=G("$parse"),Wf=Function.prototype.call,Xf=Function.prototype.apply,Yf=Function.prototype.bind,Lb=$();n("+ - * / % === !== == != < > <= >= && || ! = |".split(" "),function(a){Lb[a]=!0});var sg={n:"\n",f:"\f",r:"\r",
+t:"\t",v:"\v","'":"'",'"':'"'},fc=function(a){this.options=a};fc.prototype={constructor:fc,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 b=a+this.peek(),d=b+this.peek(2),c=Lb[b],e=Lb[d];Lb[a]||c||e?(a=e?d:c?b: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,b){return-1!==b.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,b,d){d=d||this.index;b=y(b)?"s "+b+"-"+this.index+" ["+this.text.substring(b,d)+"]":" "+d;throw ba("lexerr",a,b,this.text);},readNumber:function(){for(var a="",b=this.index;this.index<this.text.length;){var d=F(this.text.charAt(this.index));if("."==d||this.isNumber(d))a+=d;else{var c=this.peek();
+if("e"==d&&this.isExpOperator(c))a+=d;else if(this.isExpOperator(d)&&c&&this.isNumber(c)&&"e"==a.charAt(a.length-1))a+=d;else if(!this.isExpOperator(d)||c&&this.isNumber(c)||"e"!=a.charAt(a.length-1))break;else this.throwError("Invalid exponent")}this.index++}this.tokens.push({index:b,text:a,constant:!0,value:Number(a)})},readIdent:function(){for(var a=this.index;this.index<this.text.length;){var b=this.text.charAt(this.index);if(!this.isIdent(b)&&!this.isNumber(b))break;this.index++}this.tokens.push({index:a,
+text:this.text.slice(a,this.index),identifier:!0})},readString:function(a){var b=this.index;this.index++;for(var d="",c=a,e=!1;this.index<this.text.length;){var f=this.text.charAt(this.index),c=c+f;if(e)"u"===f?(e=this.text.substring(this.index+1,this.index+5),e.match(/[\da-f]{4}/i)||this.throwError("Invalid unicode escape [\\u"+e+"]"),this.index+=4,d+=String.fromCharCode(parseInt(e,16))):d+=sg[f]||f,e=!1;else if("\\"===f)e=!0;else{if(f===a){this.index++;this.tokens.push({index:b,text:c,constant:!0,
+value:d});return}d+=f}this.index++}this.throwError("Unterminated quote",b)}};var s=function(a,b){this.lexer=a;this.options=b};s.Program="Program";s.ExpressionStatement="ExpressionStatement";s.AssignmentExpression="AssignmentExpression";s.ConditionalExpression="ConditionalExpression";s.LogicalExpression="LogicalExpression";s.BinaryExpression="BinaryExpression";s.UnaryExpression="UnaryExpression";s.CallExpression="CallExpression";s.MemberExpression="MemberExpression";s.Identifier="Identifier";s.Literal=
+"Literal";s.ArrayExpression="ArrayExpression";s.Property="Property";s.ObjectExpression="ObjectExpression";s.ThisExpression="ThisExpression";s.NGValueParameter="NGValueParameter";s.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:s.Program,
+body:a}},expressionStatement:function(){return{type:s.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:s.AssignmentExpression,left:a,right:this.assignment(),operator:"="});return a},ternary:function(){var a=this.logicalOR(),b,d;return this.expect("?")&&(b=this.expression(),this.consume(":"))?
+(d=this.expression(),{type:s.ConditionalExpression,test:a,alternate:b,consequent:d}):a},logicalOR:function(){for(var a=this.logicalAND();this.expect("||");)a={type:s.LogicalExpression,operator:"||",left:a,right:this.logicalAND()};return a},logicalAND:function(){for(var a=this.equality();this.expect("&&");)a={type:s.LogicalExpression,operator:"&&",left:a,right:this.equality()};return a},equality:function(){for(var a=this.relational(),b;b=this.expect("==","!=","===","!==");)a={type:s.BinaryExpression,
+operator:b.text,left:a,right:this.relational()};return a},relational:function(){for(var a=this.additive(),b;b=this.expect("<",">","<=",">=");)a={type:s.BinaryExpression,operator:b.text,left:a,right:this.additive()};return a},additive:function(){for(var a=this.multiplicative(),b;b=this.expect("+","-");)a={type:s.BinaryExpression,operator:b.text,left:a,right:this.multiplicative()};return a},multiplicative:function(){for(var a=this.unary(),b;b=this.expect("*","/","%");)a={type:s.BinaryExpression,operator:b.text,
+left:a,right:this.unary()};return a},unary:function(){var a;return(a=this.expect("+","-","!"))?{type:s.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=bb(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 b;b=this.expect("(","[",".");)"("===b.text?(a={type:s.CallExpression,callee:a,arguments:this.parseArguments()},this.consume(")")):"["===b.text?(a={type:s.MemberExpression,object:a,property:this.expression(),computed:!0},this.consume("]")):"."===b.text?a={type:s.MemberExpression,object:a,property:this.identifier(),computed:!1}:this.throwError("IMPOSSIBLE");return a},filter:function(a){a=[a];for(var b={type:s.CallExpression,callee:this.identifier(),
+arguments:a,filter:!0};this.expect(":");)a.push(this.expression());return b},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:s.Identifier,name:a.text}},constant:function(){return{type:s.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:s.ArrayExpression,elements:a}},object:function(){var a=[],b;if("}"!==this.peekToken().text){do{if(this.peek("}"))break;b={type:s.Property,kind:"init"};this.peek().constant?b.key=this.constant():this.peek().identifier?b.key=this.identifier():this.throwError("invalid key",this.peek());this.consume(":");b.value=this.expression();a.push(b)}while(this.expect(","))}this.consume("}");return{type:s.ObjectExpression,properties:a}},
+throwError:function(a,b){throw ba("syntax",b.text,a,b.index+1,this.text,this.text.substring(b.index));},consume:function(a){if(0===this.tokens.length)throw ba("ueoe",this.text);var b=this.expect(a);b||this.throwError("is unexpected, expecting ["+a+"]",this.peek());return b},peekToken:function(){if(0===this.tokens.length)throw ba("ueoe",this.text);return this.tokens[0]},peek:function(a,b,d,c){return this.peekAhead(0,a,b,d,c)},peekAhead:function(a,b,d,c,e){if(this.tokens.length>a){a=this.tokens[a];
+var f=a.text;if(f===b||f===d||f===c||f===e||!(b||d||c||e))return a}return!1},expect:function(a,b,d,c){return(a=this.peek(a,b,d,c))?(this.tokens.shift(),a):!1},constants:{"true":{type:s.Literal,value:!0},"false":{type:s.Literal,value:!1},"null":{type:s.Literal,value:null},undefined:{type:s.Literal,value:u},"this":{type:s.ThisExpression}}};rd.prototype={compile:function(a,b){var d=this,c=this.astBuilder.ast(a);this.state={nextId:0,filters:{},expensiveChecks:b,fn:{vars:[],body:[],own:{}},assign:{vars:[],
+body:[],own:{}},inputs:[]};W(c,d.$filter);var e="",f;this.stage="assign";if(f=pd(c))this.state.computing="assign",e=this.nextId(),this.recurse(f,e),this.return_(e),e="fn.assign="+this.generateFunction("assign","s,v,l");f=nd(c.body);d.stage="inputs";n(f,function(a,b){var c="fn"+b;d.state[c]={vars:[],body:[],own:{}};d.state.computing=c;var e=d.nextId();d.recurse(a,e);d.return_(e);d.state.inputs.push(c);a.watchId=b});this.state.computing="fn";this.stage="main";this.recurse(c);e='"'+this.USE+" "+this.STRICT+
+'";\n'+this.filterPrefix()+"var fn="+this.generateFunction("fn","s,l,a,i")+e+this.watchFns()+"return fn;";e=(new Function("$filter","ensureSafeMemberName","ensureSafeObject","ensureSafeFunction","getStringValue","ensureSafeAssignContext","ifDefined","plus","text",e))(this.$filter,Va,xa,kd,jd,ld,Zf,md,a);this.state=this.stage=u;e.literal=qd(c);e.constant=c.constant;return e},USE:"use",STRICT:"strict",watchFns:function(){var a=[],b=this.state.inputs,d=this;n(b,function(b){a.push("var "+b+"="+d.generateFunction(b,
+"s"))});b.length&&a.push("fn.inputs=["+b.join(",")+"];");return a.join("")},generateFunction:function(a,b){return"function("+b+"){"+this.varsPrefix(a)+this.body(a)+"};"},filterPrefix:function(){var a=[],b=this;n(this.state.filters,function(d,c){a.push(d+"=$filter("+b.escape(c)+")")});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,b,
+d,c,e,f){var g,h,k=this,l,m;c=c||x;if(!f&&y(a.watchId))b=b||this.nextId(),this.if_("i",this.lazyAssign(b,this.computedMember("i",a.watchId)),this.lazyRecurse(a,b,d,c,e,!0));else switch(a.type){case s.Program:n(a.body,function(b,c){k.recurse(b.expression,u,u,function(a){h=a});c!==a.body.length-1?k.current().body.push(h,";"):k.return_(h)});break;case s.Literal:m=this.escape(a.value);this.assign(b,m);c(m);break;case s.UnaryExpression:this.recurse(a.argument,u,u,function(a){h=a});m=a.operator+"("+this.ifDefined(h,
+0)+")";this.assign(b,m);c(m);break;case s.BinaryExpression:this.recurse(a.left,u,u,function(a){g=a});this.recurse(a.right,u,u,function(a){h=a});m="+"===a.operator?this.plus(g,h):"-"===a.operator?this.ifDefined(g,0)+a.operator+this.ifDefined(h,0):"("+g+")"+a.operator+"("+h+")";this.assign(b,m);c(m);break;case s.LogicalExpression:b=b||this.nextId();k.recurse(a.left,b);k.if_("&&"===a.operator?b:k.not(b),k.lazyRecurse(a.right,b));c(b);break;case s.ConditionalExpression:b=b||this.nextId();k.recurse(a.test,
+b);k.if_(b,k.lazyRecurse(a.alternate,b),k.lazyRecurse(a.consequent,b));c(b);break;case s.Identifier:b=b||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);Va(a.name);k.if_("inputs"===k.stage||k.not(k.getHasOwnProperty("l",a.name)),function(){k.if_("inputs"===k.stage||"s",function(){e&&1!==e&&k.if_(k.not(k.nonComputedMember("s",a.name)),k.lazyAssign(k.nonComputedMember("s",a.name),"{}"));k.assign(b,k.nonComputedMember("s",
+a.name))})},b&&k.lazyAssign(b,k.nonComputedMember("l",a.name)));(k.state.expensiveChecks||Fb(a.name))&&k.addEnsureSafeObject(b);c(b);break;case s.MemberExpression:g=d&&(d.context=this.nextId())||this.nextId();b=b||this.nextId();k.recurse(a.object,g,u,function(){k.if_(k.notNull(g),function(){if(a.computed)h=k.nextId(),k.recurse(a.property,h),k.getStringValue(h),k.addEnsureSafeMemberName(h),e&&1!==e&&k.if_(k.not(k.computedMember(g,h)),k.lazyAssign(k.computedMember(g,h),"{}")),m=k.ensureSafeObject(k.computedMember(g,
+h)),k.assign(b,m),d&&(d.computed=!0,d.name=h);else{Va(a.property.name);e&&1!==e&&k.if_(k.not(k.nonComputedMember(g,a.property.name)),k.lazyAssign(k.nonComputedMember(g,a.property.name),"{}"));m=k.nonComputedMember(g,a.property.name);if(k.state.expensiveChecks||Fb(a.property.name))m=k.ensureSafeObject(m);k.assign(b,m);d&&(d.computed=!1,d.name=a.property.name)}},function(){k.assign(b,"undefined")});c(b)},!!e);break;case s.CallExpression:b=b||this.nextId();a.filter?(h=k.filter(a.callee.name),l=[],n(a.arguments,
+function(a){var b=k.nextId();k.recurse(a,b);l.push(b)}),m=h+"("+l.join(",")+")",k.assign(b,m),c(b)):(h=k.nextId(),g={},l=[],k.recurse(a.callee,h,g,function(){k.if_(k.notNull(h),function(){k.addEnsureSafeFunction(h);n(a.arguments,function(a){k.recurse(a,k.nextId(),u,function(a){l.push(k.ensureSafeObject(a))})});g.name?(k.state.expensiveChecks||k.addEnsureSafeObject(g.context),m=k.member(g.context,g.name,g.computed)+"("+l.join(",")+")"):m=h+"("+l.join(",")+")";m=k.ensureSafeObject(m);k.assign(b,m)},
+function(){k.assign(b,"undefined")});c(b)}));break;case s.AssignmentExpression:h=this.nextId();g={};if(!od(a.left))throw ba("lval");this.recurse(a.left,u,g,function(){k.if_(k.notNull(g.context),function(){k.recurse(a.right,h);k.addEnsureSafeObject(k.member(g.context,g.name,g.computed));k.addEnsureSafeAssignContext(g.context);m=k.member(g.context,g.name,g.computed)+a.operator+h;k.assign(b,m);c(b||m)})},1);break;case s.ArrayExpression:l=[];n(a.elements,function(a){k.recurse(a,k.nextId(),u,function(a){l.push(a)})});
+m="["+l.join(",")+"]";this.assign(b,m);c(m);break;case s.ObjectExpression:l=[];n(a.properties,function(a){k.recurse(a.value,k.nextId(),u,function(b){l.push(k.escape(a.key.type===s.Identifier?a.key.name:""+a.key.value)+":"+b)})});m="{"+l.join(",")+"}";this.assign(b,m);c(m);break;case s.ThisExpression:this.assign(b,"s");c("s");break;case s.NGValueParameter:this.assign(b,"v"),c("v")}},getHasOwnProperty:function(a,b){var d=a+"."+b,c=this.current().own;c.hasOwnProperty(d)||(c[d]=this.nextId(!1,a+"&&("+
+this.escape(b)+" in "+a+")"));return c[d]},assign:function(a,b){if(a)return this.current().body.push(a,"=",b,";"),a},filter:function(a){this.state.filters.hasOwnProperty(a)||(this.state.filters[a]=this.nextId(!0));return this.state.filters[a]},ifDefined:function(a,b){return"ifDefined("+a+","+this.escape(b)+")"},plus:function(a,b){return"plus("+a+","+b+")"},return_:function(a){this.current().body.push("return ",a,";")},if_:function(a,b,d){if(!0===a)b();else{var c=this.current().body;c.push("if(",a,
+"){");b();c.push("}");d&&(c.push("else{"),d(),c.push("}"))}},not:function(a){return"!("+a+")"},notNull:function(a){return a+"!=null"},nonComputedMember:function(a,b){return a+"."+b},computedMember:function(a,b){return a+"["+b+"]"},member:function(a,b,d){return d?this.computedMember(a,b):this.nonComputedMember(a,b)},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),";")},addEnsureSafeAssignContext:function(a){this.current().body.push(this.ensureSafeAssignContext(a),";")},ensureSafeObject:function(a){return"ensureSafeObject("+a+",text)"},ensureSafeMemberName:function(a){return"ensureSafeMemberName("+a+",text)"},ensureSafeFunction:function(a){return"ensureSafeFunction("+a+",text)"},getStringValue:function(a){this.assign(a,"getStringValue("+a+",text)")},ensureSafeAssignContext:function(a){return"ensureSafeAssignContext("+
+a+",text)"},lazyRecurse:function(a,b,d,c,e,f){var g=this;return function(){g.recurse(a,b,d,c,e,f)}},lazyAssign:function(a,b){var d=this;return function(){d.assign(a,b)}},stringEscapeRegex:/[^ a-zA-Z0-9]/g,stringEscapeFn:function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)},escape:function(a){if(E(a))return"'"+a.replace(this.stringEscapeRegex,this.stringEscapeFn)+"'";if(Q(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 ba("esc");},nextId:function(a,b){var d="v"+this.state.nextId++;a||this.current().vars.push(d+(b?"="+b:""));return d},current:function(){return this.state[this.state.computing]}};sd.prototype={compile:function(a,b){var d=this,c=this.astBuilder.ast(a);this.expression=a;this.expensiveChecks=b;W(c,d.$filter);var e,f;if(e=pd(c))f=this.recurse(e);e=nd(c.body);var g;e&&(g=[],n(e,function(a,b){var c=d.recurse(a);a.input=c;g.push(c);a.watchId=b}));var h=[];n(c.body,function(a){h.push(d.recurse(a.expression))});
+e=0===c.body.length?function(){}:1===c.body.length?h[0]:function(a,b){var c;n(h,function(d){c=d(a,b)});return c};f&&(e.assign=function(a,b,c){return f(a,c,b)});g&&(e.inputs=g);e.literal=qd(c);e.constant=c.constant;return e},recurse:function(a,b,d){var c,e,f=this,g;if(a.input)return this.inputs(a.input,a.watchId);switch(a.type){case s.Literal:return this.value(a.value,b);case s.UnaryExpression:return e=this.recurse(a.argument),this["unary"+a.operator](e,b);case s.BinaryExpression:return c=this.recurse(a.left),
+e=this.recurse(a.right),this["binary"+a.operator](c,e,b);case s.LogicalExpression:return c=this.recurse(a.left),e=this.recurse(a.right),this["binary"+a.operator](c,e,b);case s.ConditionalExpression:return this["ternary?:"](this.recurse(a.test),this.recurse(a.alternate),this.recurse(a.consequent),b);case s.Identifier:return Va(a.name,f.expression),f.identifier(a.name,f.expensiveChecks||Fb(a.name),b,d,f.expression);case s.MemberExpression:return c=this.recurse(a.object,!1,!!d),a.computed||(Va(a.property.name,
+f.expression),e=a.property.name),a.computed&&(e=this.recurse(a.property)),a.computed?this.computedMember(c,e,b,d,f.expression):this.nonComputedMember(c,e,f.expensiveChecks,b,d,f.expression);case s.CallExpression:return g=[],n(a.arguments,function(a){g.push(f.recurse(a))}),a.filter&&(e=this.$filter(a.callee.name)),a.filter||(e=this.recurse(a.callee,!0)),a.filter?function(a,c,d,f){for(var r=[],n=0;n<g.length;++n)r.push(g[n](a,c,d,f));a=e.apply(u,r,f);return b?{context:u,name:u,value:a}:a}:function(a,
+c,d,m){var r=e(a,c,d,m),n;if(null!=r.value){xa(r.context,f.expression);kd(r.value,f.expression);n=[];for(var q=0;q<g.length;++q)n.push(xa(g[q](a,c,d,m),f.expression));n=xa(r.value.apply(r.context,n),f.expression)}return b?{value:n}:n};case s.AssignmentExpression:return c=this.recurse(a.left,!0,1),e=this.recurse(a.right),function(a,d,g,m){var n=c(a,d,g,m);a=e(a,d,g,m);xa(n.value,f.expression);ld(n.context);n.context[n.name]=a;return b?{value:a}:a};case s.ArrayExpression:return g=[],n(a.elements,function(a){g.push(f.recurse(a))}),
+function(a,c,d,e){for(var f=[],n=0;n<g.length;++n)f.push(g[n](a,c,d,e));return b?{value:f}:f};case s.ObjectExpression:return g=[],n(a.properties,function(a){g.push({key:a.key.type===s.Identifier?a.key.name:""+a.key.value,value:f.recurse(a.value)})}),function(a,c,d,e){for(var f={},n=0;n<g.length;++n)f[g[n].key]=g[n].value(a,c,d,e);return b?{value:f}:f};case s.ThisExpression:return function(a){return b?{value:a}:a};case s.NGValueParameter:return function(a,c,d,e){return b?{value:d}:d}}},"unary+":function(a,
+b){return function(d,c,e,f){d=a(d,c,e,f);d=y(d)?+d:0;return b?{value:d}:d}},"unary-":function(a,b){return function(d,c,e,f){d=a(d,c,e,f);d=y(d)?-d:0;return b?{value:d}:d}},"unary!":function(a,b){return function(d,c,e,f){d=!a(d,c,e,f);return b?{value:d}:d}},"binary+":function(a,b,d){return function(c,e,f,g){var h=a(c,e,f,g);c=b(c,e,f,g);h=md(h,c);return d?{value:h}:h}},"binary-":function(a,b,d){return function(c,e,f,g){var h=a(c,e,f,g);c=b(c,e,f,g);h=(y(h)?h:0)-(y(c)?c:0);return d?{value:h}:h}},"binary*":function(a,
+b,d){return function(c,e,f,g){c=a(c,e,f,g)*b(c,e,f,g);return d?{value:c}:c}},"binary/":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)/b(c,e,f,g);return d?{value:c}:c}},"binary%":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)%b(c,e,f,g);return d?{value:c}:c}},"binary===":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)===b(c,e,f,g);return d?{value:c}:c}},"binary!==":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)!==b(c,e,f,g);return d?{value:c}:c}},"binary==":function(a,b,
+d){return function(c,e,f,g){c=a(c,e,f,g)==b(c,e,f,g);return d?{value:c}:c}},"binary!=":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)!=b(c,e,f,g);return d?{value:c}:c}},"binary<":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)<b(c,e,f,g);return d?{value:c}:c}},"binary>":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)>b(c,e,f,g);return d?{value:c}:c}},"binary<=":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)<=b(c,e,f,g);return d?{value:c}:c}},"binary>=":function(a,b,d){return function(c,
+e,f,g){c=a(c,e,f,g)>=b(c,e,f,g);return d?{value:c}:c}},"binary&&":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)&&b(c,e,f,g);return d?{value:c}:c}},"binary||":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)||b(c,e,f,g);return d?{value:c}:c}},"ternary?:":function(a,b,d,c){return function(e,f,g,h){e=a(e,f,g,h)?b(e,f,g,h):d(e,f,g,h);return c?{value:e}:e}},value:function(a,b){return function(){return b?{context:u,name:u,value:a}:a}},identifier:function(a,b,d,c,e){return function(f,g,h,k){f=
+g&&a in g?g:f;c&&1!==c&&f&&!f[a]&&(f[a]={});g=f?f[a]:u;b&&xa(g,e);return d?{context:f,name:a,value:g}:g}},computedMember:function(a,b,d,c,e){return function(f,g,h,k){var l=a(f,g,h,k),m,n;null!=l&&(m=b(f,g,h,k),m=jd(m),Va(m,e),c&&1!==c&&l&&!l[m]&&(l[m]={}),n=l[m],xa(n,e));return d?{context:l,name:m,value:n}:n}},nonComputedMember:function(a,b,d,c,e,f){return function(g,h,k,l){g=a(g,h,k,l);e&&1!==e&&g&&!g[b]&&(g[b]={});h=null!=g?g[b]:u;(d||Fb(b))&&xa(h,f);return c?{context:g,name:b,value:h}:h}},inputs:function(a,
+b){return function(d,c,e,f){return f?f[b]:a(d,c,e)}}};var gc=function(a,b,d){this.lexer=a;this.$filter=b;this.options=d;this.ast=new s(this.lexer);this.astCompiler=d.csp?new sd(this.ast,b):new rd(this.ast,b)};gc.prototype={constructor:gc,parse:function(a){return this.astCompiler.compile(a,this.options.expensiveChecks)}};$();$();var $f=Object.prototype.valueOf,ya=G("$sce"),la={HTML:"html",CSS:"css",URL:"url",RESOURCE_URL:"resourceUrl",JS:"js"},ha=G("$compile"),Y=X.createElement("a"),wd=wa(S.location.href);
+xd.$inject=["$document"];Jc.$inject=["$provide"];yd.$inject=["$locale"];Ad.$inject=["$locale"];var ic=".",jg={yyyy:ca("FullYear",4),yy:ca("FullYear",2,0,!0),y:ca("FullYear",1),MMMM:Hb("Month"),MMM:Hb("Month",!0),MM:ca("Month",2,1),M:ca("Month",1,1),dd:ca("Date",2),d:ca("Date",1),HH:ca("Hours",2),H:ca("Hours",1),hh:ca("Hours",2,-12),h:ca("Hours",1,-12),mm:ca("Minutes",2),m:ca("Minutes",1),ss:ca("Seconds",2),s:ca("Seconds",1),sss:ca("Milliseconds",3),EEEE:Hb("Day"),EEE:Hb("Day",!0),a:function(a,b){return 12>
+a.getHours()?b.AMPMS[0]:b.AMPMS[1]},Z:function(a,b,d){a=-1*d;return a=(0<=a?"+":"")+(Gb(Math[0<a?"floor":"ceil"](a/60),2)+Gb(Math.abs(a%60),2))},ww:Ed(2),w:Ed(1),G:jc,GG:jc,GGG:jc,GGGG:function(a,b){return 0>=a.getFullYear()?b.ERANAMES[0]:b.ERANAMES[1]}},ig=/((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,hg=/^\-?\d+$/;zd.$inject=["$locale"];var eg=na(F),fg=na(sb);Bd.$inject=["$parse"];var he=na({restrict:"E",compile:function(a,b){if(!b.href&&!b.xlinkHref)return function(a,
+b){if("a"===b[0].nodeName.toLowerCase()){var e="[object SVGAnimatedString]"===sa.call(b.prop("href"))?"xlink:href":"href";b.on("click",function(a){b.attr(e)||a.preventDefault()})}}}}),tb={};n(Cb,function(a,b){function d(a,d,e){a.$watch(e[c],function(a){e.$set(b,!!a)})}if("multiple"!=a){var c=va("ng-"+b),e=d;"checked"===a&&(e=function(a,b,e){e.ngModel!==e[c]&&d(a,b,e)});tb[c]=function(){return{restrict:"A",priority:100,link:e}}}});n(Zc,function(a,b){tb[b]=function(){return{priority:100,link:function(a,
+c,e){if("ngPattern"===b&&"/"==e.ngPattern.charAt(0)&&(c=e.ngPattern.match(lg))){e.$set("ngPattern",new RegExp(c[1],c[2]));return}a.$watch(e[b],function(a){e.$set(b,a)})}}}});n(["src","srcset","href"],function(a){var b=va("ng-"+a);tb[b]=function(){return{priority:99,link:function(d,c,e){var f=a,g=a;"href"===a&&"[object SVGAnimatedString]"===sa.call(c.prop("href"))&&(g="xlinkHref",e.$attr[g]="xlink:href",f=null);e.$observe(b,function(b){b?(e.$set(g,b),Ha&&f&&c.prop(f,e[g])):"href"===a&&e.$set(g,null)})}}}});
+var Ib={$addControl:x,$$renameControl:function(a,b){a.$name=b},$removeControl:x,$setValidity:x,$setDirty:x,$setPristine:x,$setSubmitted:x};Fd.$inject=["$element","$attrs","$scope","$animate","$interpolate"];var Nd=function(a){return["$timeout","$parse",function(b,d){function c(a){return""===a?d('this[""]').assign:d(a).assign||x}return{name:"form",restrict:a?"EAC":"E",require:["form","^^?form"],controller:Fd,compile:function(d,f){d.addClass(Wa).addClass(mb);var g=f.name?"name":a&&f.ngForm?"ngForm":
+!1;return{pre:function(a,d,e,f){var n=f[0];if(!("action"in e)){var q=function(b){a.$apply(function(){n.$commitViewValue();n.$setSubmitted()});b.preventDefault()};d[0].addEventListener("submit",q,!1);d.on("$destroy",function(){b(function(){d[0].removeEventListener("submit",q,!1)},0,!1)})}(f[1]||n.$$parentForm).$addControl(n);var s=g?c(n.$name):x;g&&(s(a,n),e.$observe(g,function(b){n.$name!==b&&(s(a,u),n.$$parentForm.$$renameControl(n,b),s=c(n.$name),s(a,n))}));d.on("$destroy",function(){n.$$parentForm.$removeControl(n);
+s(a,u);M(n,Ib)})}}}}}]},ie=Nd(),ve=Nd(!0),kg=/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/,tg=/^[A-Za-z][A-Za-z\d.+-]*:\/*(?:\w+(?::\w+)?@)?[^\s/]+(?::\d+)?(?:\/[\w#!:.?+=&%@\-/]*)?$/,ug=/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i,vg=/^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/,Od=/^(\d{4})-(\d{2})-(\d{2})$/,Pd=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,mc=/^(\d{4})-W(\d\d)$/,Qd=/^(\d{4})-(\d\d)$/,
+Rd=/^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,Sd={text:function(a,b,d,c,e,f){jb(a,b,d,c,e,f);kc(c)},date:kb("date",Od,Kb(Od,["yyyy","MM","dd"]),"yyyy-MM-dd"),"datetime-local":kb("datetimelocal",Pd,Kb(Pd,"yyyy MM dd HH mm ss sss".split(" ")),"yyyy-MM-ddTHH:mm:ss.sss"),time:kb("time",Rd,Kb(Rd,["HH","mm","ss","sss"]),"HH:mm:ss.sss"),week:kb("week",mc,function(a,b){if(da(a))return a;if(E(a)){mc.lastIndex=0;var d=mc.exec(a);if(d){var c=+d[1],e=+d[2],f=d=0,g=0,h=0,k=Dd(c),e=7*(e-1);b&&(d=b.getHours(),f=
+b.getMinutes(),g=b.getSeconds(),h=b.getMilliseconds());return new Date(c,0,k.getDate()+e,d,f,g,h)}}return NaN},"yyyy-Www"),month:kb("month",Qd,Kb(Qd,["yyyy","MM"]),"yyyy-MM"),number:function(a,b,d,c,e,f){Hd(a,b,d,c);jb(a,b,d,c,e,f);c.$$parserName="number";c.$parsers.push(function(a){return c.$isEmpty(a)?null:vg.test(a)?parseFloat(a):u});c.$formatters.push(function(a){if(!c.$isEmpty(a)){if(!Q(a))throw lb("numfmt",a);a=a.toString()}return a});if(y(d.min)||d.ngMin){var g;c.$validators.min=function(a){return c.$isEmpty(a)||
+q(g)||a>=g};d.$observe("min",function(a){y(a)&&!Q(a)&&(a=parseFloat(a,10));g=Q(a)&&!isNaN(a)?a:u;c.$validate()})}if(y(d.max)||d.ngMax){var h;c.$validators.max=function(a){return c.$isEmpty(a)||q(h)||a<=h};d.$observe("max",function(a){y(a)&&!Q(a)&&(a=parseFloat(a,10));h=Q(a)&&!isNaN(a)?a:u;c.$validate()})}},url:function(a,b,d,c,e,f){jb(a,b,d,c,e,f);kc(c);c.$$parserName="url";c.$validators.url=function(a,b){var d=a||b;return c.$isEmpty(d)||tg.test(d)}},email:function(a,b,d,c,e,f){jb(a,b,d,c,e,f);kc(c);
+c.$$parserName="email";c.$validators.email=function(a,b){var d=a||b;return c.$isEmpty(d)||ug.test(d)}},radio:function(a,b,d,c){q(d.name)&&b.attr("name",++nb);b.on("click",function(a){b[0].checked&&c.$setViewValue(d.value,a&&a.type)});c.$render=function(){b[0].checked=d.value==c.$viewValue};d.$observe("value",c.$render)},checkbox:function(a,b,d,c,e,f,g,h){var k=Id(h,a,"ngTrueValue",d.ngTrueValue,!0),l=Id(h,a,"ngFalseValue",d.ngFalseValue,!1);b.on("click",function(a){c.$setViewValue(b[0].checked,a&&
+a.type)});c.$render=function(){b[0].checked=c.$viewValue};c.$isEmpty=function(a){return!1===a};c.$formatters.push(function(a){return ma(a,k)});c.$parsers.push(function(a){return a?k:l})},hidden:x,button:x,submit:x,reset:x,file:x},Dc=["$browser","$sniffer","$filter","$parse",function(a,b,d,c){return{restrict:"E",require:["?ngModel"],link:{pre:function(e,f,g,h){h[0]&&(Sd[F(g.type)]||Sd.text)(e,f,g,h[0],b,a,d,c)}}}}],wg=/^(true|false|\d+)$/,Ne=function(){return{restrict:"A",priority:100,compile:function(a,
+b){return wg.test(b.ngValue)?function(a,b,e){e.$set("value",a.$eval(e.ngValue))}:function(a,b,e){a.$watch(e.ngValue,function(a){e.$set("value",a)})}}}},ne=["$compile",function(a){return{restrict:"AC",compile:function(b){a.$$addBindingClass(b);return function(b,c,e){a.$$addBindingInfo(c,e.ngBind);c=c[0];b.$watch(e.ngBind,function(a){c.textContent=q(a)?"":a})}}}}],pe=["$interpolate","$compile",function(a,b){return{compile:function(d){b.$$addBindingClass(d);return function(c,d,f){c=a(d.attr(f.$attr.ngBindTemplate));
+b.$$addBindingInfo(d,c.expressions);d=d[0];f.$observe("ngBindTemplate",function(a){d.textContent=q(a)?"":a})}}}}],oe=["$sce","$parse","$compile",function(a,b,d){return{restrict:"A",compile:function(c,e){var f=b(e.ngBindHtml),g=b(e.ngBindHtml,function(a){return(a||"").toString()});d.$$addBindingClass(c);return function(b,c,e){d.$$addBindingInfo(c,e.ngBindHtml);b.$watch(g,function(){c.html(a.getTrustedHtml(f(b))||"")})}}}}],Me=na({restrict:"A",require:"ngModel",link:function(a,b,d,c){c.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}),
+qe=lc("",!0),se=lc("Odd",0),re=lc("Even",1),te=La({compile:function(a,b){b.$set("ngCloak",u);a.removeClass("ng-cloak")}}),ue=[function(){return{restrict:"A",scope:!0,controller:"@",priority:500}}],Ic={},xg={blur:!0,focus:!0};n("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" "),function(a){var b=va("ng-"+a);Ic[b]=["$parse","$rootScope",function(d,c){return{restrict:"A",compile:function(e,f){var g=
+d(f[b],null,!0);return function(b,d){d.on(a,function(d){var e=function(){g(b,{$event:d})};xg[a]&&c.$$phase?b.$evalAsync(e):b.$apply(e)})}}}}]});var xe=["$animate",function(a){return{multiElement:!0,transclude:"element",priority:600,terminal:!0,restrict:"A",$$tlb:!0,link:function(b,d,c,e,f){var g,h,k;b.$watch(c.ngIf,function(b){b?h||f(function(b,e){h=e;b[b.length++]=X.createComment(" end ngIf: "+c.ngIf+" ");g={clone:b};a.enter(b,d.parent(),d)}):(k&&(k.remove(),k=null),h&&(h.$destroy(),h=null),g&&(k=
+rb(g.clone),a.leave(k).then(function(){k=null}),g=null))})}}}],ye=["$templateRequest","$anchorScroll","$animate",function(a,b,d){return{restrict:"ECA",priority:400,terminal:!0,transclude:"element",controller:fa.noop,compile:function(c,e){var f=e.ngInclude||e.src,g=e.onload||"",h=e.autoscroll;return function(c,e,m,n,q){var s=0,v,u,p,C=function(){u&&(u.remove(),u=null);v&&(v.$destroy(),v=null);p&&(d.leave(p).then(function(){u=null}),u=p,p=null)};c.$watch(f,function(f){var m=function(){!y(h)||h&&!c.$eval(h)||
+b()},u=++s;f?(a(f,!0).then(function(a){if(u===s){var b=c.$new();n.template=a;a=q(b,function(a){C();d.enter(a,null,e).then(m)});v=b;p=a;v.$emit("$includeContentLoaded",f);c.$eval(g)}},function(){u===s&&(C(),c.$emit("$includeContentError",f))}),c.$emit("$includeContentRequested",f)):(C(),n.template=null)})}}}}],Pe=["$compile",function(a){return{restrict:"ECA",priority:-400,require:"ngInclude",link:function(b,d,c,e){/SVG/.test(d[0].toString())?(d.empty(),a(Lc(e.template,X).childNodes)(b,function(a){d.append(a)},
+{futureParentElement:d})):(d.html(e.template),a(d.contents())(b))}}}],ze=La({priority:450,compile:function(){return{pre:function(a,b,d){a.$eval(d.ngInit)}}}}),Le=function(){return{restrict:"A",priority:100,require:"ngModel",link:function(a,b,d,c){var e=b.attr(d.$attr.ngList)||", ",f="false"!==d.ngTrim,g=f?U(e):e;c.$parsers.push(function(a){if(!q(a)){var b=[];a&&n(a.split(g),function(a){a&&b.push(f?U(a):a)});return b}});c.$formatters.push(function(a){return I(a)?a.join(e):u});c.$isEmpty=function(a){return!a||
+!a.length}}}},mb="ng-valid",Jd="ng-invalid",Wa="ng-pristine",Jb="ng-dirty",Ld="ng-pending",lb=G("ngModel"),yg=["$scope","$exceptionHandler","$attrs","$element","$parse","$animate","$timeout","$rootScope","$q","$interpolate",function(a,b,d,c,e,f,g,h,k,l){this.$modelValue=this.$viewValue=Number.NaN;this.$$rawModelValue=u;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=u;this.$name=l(d.name||"",!1)(a);this.$$parentForm=Ib;var m=e(d.ngModel),r=m.assign,t=m,s=r,v=null,B,p=this;this.$$setOptions=function(a){if((p.$options=a)&&a.getterSetter){var b=e(d.ngModel+"()"),f=e(d.ngModel+"($$$p)");t=function(a){var c=m(a);z(c)&&(c=b(a));return c};s=function(a,b){z(m(a))?f(a,{$$$p:p.$modelValue}):r(a,p.$modelValue)}}else if(!m.assign)throw lb("nonassign",d.ngModel,ua(c));};this.$render=x;this.$isEmpty=
+function(a){return q(a)||""===a||null===a||a!==a};var C=0;Gd({ctrl:this,$element:c,set:function(a,b){a[b]=!0},unset:function(a,b){delete a[b]},$animate:f});this.$setPristine=function(){p.$dirty=!1;p.$pristine=!0;f.removeClass(c,Jb);f.addClass(c,Wa)};this.$setDirty=function(){p.$dirty=!0;p.$pristine=!1;f.removeClass(c,Wa);f.addClass(c,Jb);p.$$parentForm.$setDirty()};this.$setUntouched=function(){p.$touched=!1;p.$untouched=!0;f.setClass(c,"ng-untouched","ng-touched")};this.$setTouched=function(){p.$touched=
+!0;p.$untouched=!1;f.setClass(c,"ng-touched","ng-untouched")};this.$rollbackViewValue=function(){g.cancel(v);p.$viewValue=p.$$lastCommittedViewValue;p.$render()};this.$validate=function(){if(!Q(p.$modelValue)||!isNaN(p.$modelValue)){var a=p.$$rawModelValue,b=p.$valid,c=p.$modelValue,d=p.$options&&p.$options.allowInvalid;p.$$runValidators(a,p.$$lastCommittedViewValue,function(e){d||b===e||(p.$modelValue=e?a:u,p.$modelValue!==c&&p.$$writeModelToScope())})}};this.$$runValidators=function(a,b,c){function d(){var c=
+!0;n(p.$validators,function(d,e){var g=d(a,b);c=c&&g;f(e,g)});return c?!0:(n(p.$asyncValidators,function(a,b){f(b,null)}),!1)}function e(){var c=[],d=!0;n(p.$asyncValidators,function(e,g){var h=e(a,b);if(!h||!z(h.then))throw lb("$asyncValidators",h);f(g,u);c.push(h.then(function(){f(g,!0)},function(a){d=!1;f(g,!1)}))});c.length?k.all(c).then(function(){g(d)},x):g(!0)}function f(a,b){h===C&&p.$setValidity(a,b)}function g(a){h===C&&c(a)}C++;var h=C;(function(){var a=p.$$parserName||"parse";if(q(B))f(a,
+null);else return B||(n(p.$validators,function(a,b){f(b,null)}),n(p.$asyncValidators,function(a,b){f(b,null)})),f(a,B),B;return!0})()?d()?e():g(!1):g(!1)};this.$commitViewValue=function(){var a=p.$viewValue;g.cancel(v);if(p.$$lastCommittedViewValue!==a||""===a&&p.$$hasNativeValidators)p.$$lastCommittedViewValue=a,p.$pristine&&this.$setDirty(),this.$$parseAndValidate()};this.$$parseAndValidate=function(){var b=p.$$lastCommittedViewValue;if(B=q(b)?u:!0)for(var c=0;c<p.$parsers.length;c++)if(b=p.$parsers[c](b),
+q(b)){B=!1;break}Q(p.$modelValue)&&isNaN(p.$modelValue)&&(p.$modelValue=t(a));var d=p.$modelValue,e=p.$options&&p.$options.allowInvalid;p.$$rawModelValue=b;e&&(p.$modelValue=b,p.$modelValue!==d&&p.$$writeModelToScope());p.$$runValidators(b,p.$$lastCommittedViewValue,function(a){e||(p.$modelValue=a?b:u,p.$modelValue!==d&&p.$$writeModelToScope())})};this.$$writeModelToScope=function(){s(a,p.$modelValue);n(p.$viewChangeListeners,function(a){try{a()}catch(c){b(c)}})};this.$setViewValue=function(a,b){p.$viewValue=
+a;p.$options&&!p.$options.updateOnDefault||p.$$debounceViewValueCommit(b)};this.$$debounceViewValueCommit=function(b){var c=0,d=p.$options;d&&y(d.debounce)&&(d=d.debounce,Q(d)?c=d:Q(d[b])?c=d[b]:Q(d["default"])&&(c=d["default"]));g.cancel(v);c?v=g(function(){p.$commitViewValue()},c):h.$$phase?p.$commitViewValue():a.$apply(function(){p.$commitViewValue()})};a.$watch(function(){var b=t(a);if(b!==p.$modelValue&&(p.$modelValue===p.$modelValue||b===b)){p.$modelValue=p.$$rawModelValue=b;B=u;for(var c=p.$formatters,
+d=c.length,e=b;d--;)e=c[d](e);p.$viewValue!==e&&(p.$viewValue=p.$$lastCommittedViewValue=e,p.$render(),p.$$runValidators(b,e,x))}return b})}],Ke=["$rootScope",function(a){return{restrict:"A",require:["ngModel","^?form","^?ngModelOptions"],controller:yg,priority:1,compile:function(b){b.addClass(Wa).addClass("ng-untouched").addClass(mb);return{pre:function(a,b,e,f){var g=f[0];b=f[1]||g.$$parentForm;g.$$setOptions(f[2]&&f[2].$options);b.$addControl(g);e.$observe("name",function(a){g.$name!==a&&g.$$parentForm.$$renameControl(g,
+a)});a.$on("$destroy",function(){g.$$parentForm.$removeControl(g)})},post:function(b,c,e,f){var g=f[0];if(g.$options&&g.$options.updateOn)c.on(g.$options.updateOn,function(a){g.$$debounceViewValueCommit(a&&a.type)});c.on("blur",function(c){g.$touched||(a.$$phase?b.$evalAsync(g.$setTouched):b.$apply(g.$setTouched))})}}}}}],zg=/(\s+|^)default(\s+|$)/,Oe=function(){return{restrict:"A",controller:["$scope","$attrs",function(a,b){var d=this;this.$options=bb(a.$eval(b.ngModelOptions));y(this.$options.updateOn)?
+(this.$options.updateOnDefault=!1,this.$options.updateOn=U(this.$options.updateOn.replace(zg,function(){d.$options.updateOnDefault=!0;return" "}))):this.$options.updateOnDefault=!0}]}},Ae=La({terminal:!0,priority:1E3}),Ag=G("ngOptions"),Bg=/^\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]+?))?$/,Ie=["$compile","$parse",function(a,
+b){function d(a,c,d){function e(a,b,c,d,f){this.selectValue=a;this.viewValue=b;this.label=c;this.group=d;this.disabled=f}function l(a){var b;if(!q&&za(a))b=a;else{b=[];for(var c in a)a.hasOwnProperty(c)&&"$"!==c.charAt(0)&&b.push(c)}return b}var m=a.match(Bg);if(!m)throw Ag("iexp",a,ua(c));var n=m[5]||m[7],q=m[6];a=/ as /.test(m[0])&&m[1];var s=m[9];c=b(m[2]?m[1]:n);var v=a&&b(a)||c,u=s&&b(s),p=s?function(a,b){return u(d,b)}:function(a){return Ca(a)},C=function(a,b){return p(a,z(a,b))},w=b(m[2]||
+m[1]),y=b(m[3]||""),B=b(m[4]||""),x=b(m[8]),D={},z=q?function(a,b){D[q]=b;D[n]=a;return D}:function(a){D[n]=a;return D};return{trackBy:s,getTrackByValue:C,getWatchables:b(x,function(a){var b=[];a=a||[];for(var c=l(a),e=c.length,f=0;f<e;f++){var g=a===c?f:c[f],k=z(a[g],g),g=p(a[g],k);b.push(g);if(m[2]||m[1])g=w(d,k),b.push(g);m[4]&&(k=B(d,k),b.push(k))}return b}),getOptions:function(){for(var a=[],b={},c=x(d)||[],f=l(c),g=f.length,m=0;m<g;m++){var n=c===f?m:f[m],r=z(c[n],n),q=v(d,r),n=p(q,r),t=w(d,
+r),u=y(d,r),r=B(d,r),q=new e(n,q,t,u,r);a.push(q);b[n]=q}return{items:a,selectValueMap:b,getOptionFromViewValue:function(a){return b[C(a)]},getViewValueFromOption:function(a){return s?fa.copy(a.viewValue):a.viewValue}}}}}var c=X.createElement("option"),e=X.createElement("optgroup");return{restrict:"A",terminal:!0,require:["select","?ngModel"],link:{pre:function(a,b,c,d){d[0].registerOption=x},post:function(b,g,h,k){function l(a,b){a.element=b;b.disabled=a.disabled;a.label!==b.label&&(b.label=a.label,
+b.textContent=a.label);a.value!==b.value&&(b.value=a.selectValue)}function m(a,b,c,d){b&&F(b.nodeName)===c?c=b:(c=d.cloneNode(!1),b?a.insertBefore(c,b):a.appendChild(c));return c}function r(a){for(var b;a;)b=a.nextSibling,Xb(a),a=b}function q(a){var b=p&&p[0],c=z&&z[0];if(b||c)for(;a&&(a===b||a===c||8===a.nodeType||""===a.value);)a=a.nextSibling;return a}function s(){var a=D&&u.readValue();D=E.getOptions();var b={},d=g[0].firstChild;x&&g.prepend(p);d=q(d);D.items.forEach(function(a){var f,h;a.group?
+(f=b[a.group],f||(f=m(g[0],d,"optgroup",e),d=f.nextSibling,f.label=a.group,f=b[a.group]={groupElement:f,currentOptionElement:f.firstChild}),h=m(f.groupElement,f.currentOptionElement,"option",c),l(a,h),f.currentOptionElement=h.nextSibling):(h=m(g[0],d,"option",c),l(a,h),d=h.nextSibling)});Object.keys(b).forEach(function(a){r(b[a].currentOptionElement)});r(d);v.$render();if(!v.$isEmpty(a)){var f=u.readValue();(E.trackBy?ma(a,f):a===f)||(v.$setViewValue(f),v.$render())}}var v=k[1];if(v){var u=k[0];k=
+h.multiple;for(var p,C=0,w=g.children(),y=w.length;C<y;C++)if(""===w[C].value){p=w.eq(C);break}var x=!!p,z=B(c.cloneNode(!1));z.val("?");var D,E=d(h.ngOptions,g,b);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=g.val()||[],b=[];n(a,function(a){(a=D.selectValueMap[a])&&!a.disabled&&b.push(D.getViewValueFromOption(a))});
+return b},E.trackBy&&b.$watchCollection(function(){if(I(v.$viewValue))return v.$viewValue.map(function(a){return E.getTrackByValue(a)})},function(){v.$render()})):(u.writeValue=function(a){var b=D.getOptionFromViewValue(a);b&&!b.disabled?g[0].value!==b.selectValue&&(z.remove(),x||p.remove(),g[0].value=b.selectValue,b.element.selected=!0,b.element.setAttribute("selected","selected")):null===a||x?(z.remove(),x||g.prepend(p),g.val(""),p.prop("selected",!0),p.attr("selected",!0)):(x||p.remove(),g.prepend(z),
+g.val("?"),z.prop("selected",!0),z.attr("selected",!0))},u.readValue=function(){var a=D.selectValueMap[g.val()];return a&&!a.disabled?(x||p.remove(),z.remove(),D.getViewValueFromOption(a)):null},E.trackBy&&b.$watch(function(){return E.getTrackByValue(v.$viewValue)},function(){v.$render()}));x?(p.remove(),a(p)(b),p.removeClass("ng-scope")):p=B(c.cloneNode(!1));s();b.$watchCollection(E.getWatchables,s)}}}}}],Be=["$locale","$interpolate","$log",function(a,b,d){var c=/{}/g,e=/^when(Minus)?(.+)$/;return{link:function(f,
+g,h){function k(a){g.text(a||"")}var l=h.count,m=h.$attr.when&&g.attr(h.$attr.when),r=h.offset||0,s=f.$eval(m)||{},u={},v=b.startSymbol(),y=b.endSymbol(),p=v+l+"-"+r+y,C=fa.noop,w;n(h,function(a,b){var c=e.exec(b);c&&(c=(c[1]?"-":"")+F(c[2]),s[c]=g.attr(h.$attr[b]))});n(s,function(a,d){u[d]=b(a.replace(c,p))});f.$watch(l,function(b){var c=parseFloat(b),e=isNaN(c);e||c in s||(c=a.pluralCat(c-r));c===w||e&&Q(w)&&isNaN(w)||(C(),e=u[c],q(e)?(null!=b&&d.debug("ngPluralize: no rule defined for '"+c+"' in "+
+m),C=x,k()):C=f.$watch(e,k),w=c)})}}}],Ce=["$parse","$animate",function(a,b){var d=G("ngRepeat"),c=function(a,b,c,d,k,l,m){a[c]=d;k&&(a[k]=l);a.$index=b;a.$first=0===b;a.$last=b===m-1;a.$middle=!(a.$first||a.$last);a.$odd=!(a.$even=0===(b&1))};return{restrict:"A",multiElement:!0,transclude:"element",priority:1E3,terminal:!0,$$tlb:!0,compile:function(e,f){var g=f.ngRepeat,h=X.createComment(" end ngRepeat: "+g+" "),k=g.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",g);var l=k[1],m=k[2],r=k[3],q=k[4],k=l.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);if(!k)throw d("iidexp",l);var s=k[3]||k[1],v=k[2];if(r&&(!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(r)||/^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(r)))throw d("badident",r);var x,p,y,w,z={$id:Ca};q?x=a(q):(y=function(a,b){return Ca(b)},w=function(a){return a});return function(a,e,f,k,l){x&&(p=function(b,c,d){v&&(z[v]=b);z[s]=c;z.$index=
+d;return x(a,z)});var q=$();a.$watchCollection(m,function(f){var k,m,t=e[0],x,z=$(),D,E,H,F,I,G,J;r&&(a[r]=f);if(za(f))I=f,m=p||y;else for(J in m=p||w,I=[],f)qa.call(f,J)&&"$"!==J.charAt(0)&&I.push(J);D=I.length;J=Array(D);for(k=0;k<D;k++)if(E=f===I?k:I[k],H=f[E],F=m(E,H,k),q[F])G=q[F],delete q[F],z[F]=G,J[k]=G;else{if(z[F])throw n(J,function(a){a&&a.scope&&(q[a.id]=a)}),d("dupes",g,F,H);J[k]={id:F,scope:u,clone:u};z[F]=!0}for(x in q){G=q[x];F=rb(G.clone);b.leave(F);if(F[0].parentNode)for(k=0,m=F.length;k<
+m;k++)F[k].$$NG_REMOVED=!0;G.scope.$destroy()}for(k=0;k<D;k++)if(E=f===I?k:I[k],H=f[E],G=J[k],G.scope){x=t;do x=x.nextSibling;while(x&&x.$$NG_REMOVED);G.clone[0]!=x&&b.move(rb(G.clone),null,B(t));t=G.clone[G.clone.length-1];c(G.scope,k,s,H,v,E,D)}else l(function(a,d){G.scope=d;var e=h.cloneNode(!1);a[a.length++]=e;b.enter(a,null,B(t));t=e;G.clone=a;z[G.id]=G;c(G.scope,k,s,H,v,E,D)});q=z})}}}}],De=["$animate",function(a){return{restrict:"A",multiElement:!0,link:function(b,d,c){b.$watch(c.ngShow,function(b){a[b?
+"removeClass":"addClass"](d,"ng-hide",{tempClasses:"ng-hide-animate"})})}}}],we=["$animate",function(a){return{restrict:"A",multiElement:!0,link:function(b,d,c){b.$watch(c.ngHide,function(b){a[b?"addClass":"removeClass"](d,"ng-hide",{tempClasses:"ng-hide-animate"})})}}}],Ee=La(function(a,b,d){a.$watch(d.ngStyle,function(a,d){d&&a!==d&&n(d,function(a,c){b.css(c,"")});a&&b.css(a)},!0)}),Fe=["$animate",function(a){return{require:"ngSwitch",controller:["$scope",function(){this.cases={}}],link:function(b,
+d,c,e){var f=[],g=[],h=[],k=[],l=function(a,b){return function(){a.splice(b,1)}};b.$watch(c.ngSwitch||c.on,function(b){var c,d;c=0;for(d=h.length;c<d;++c)a.cancel(h[c]);c=h.length=0;for(d=k.length;c<d;++c){var q=rb(g[c].clone);k[c].$destroy();(h[c]=a.leave(q)).then(l(h,c))}g.length=0;k.length=0;(f=e.cases["!"+b]||e.cases["?"])&&n(f,function(b){b.transclude(function(c,d){k.push(d);var e=b.element;c[c.length++]=X.createComment(" end ngSwitchWhen: ");g.push({clone:c});a.enter(c,e.parent(),e)})})})}}}],
+Ge=La({transclude:"element",priority:1200,require:"^ngSwitch",multiElement:!0,link:function(a,b,d,c,e){c.cases["!"+d.ngSwitchWhen]=c.cases["!"+d.ngSwitchWhen]||[];c.cases["!"+d.ngSwitchWhen].push({transclude:e,element:b})}}),He=La({transclude:"element",priority:1200,require:"^ngSwitch",multiElement:!0,link:function(a,b,d,c,e){c.cases["?"]=c.cases["?"]||[];c.cases["?"].push({transclude:e,element:b})}}),Je=La({restrict:"EAC",link:function(a,b,d,c,e){if(!e)throw G("ngTransclude")("orphan",ua(b));e(function(a){b.empty();
+b.append(a)})}}),je=["$templateCache",function(a){return{restrict:"E",terminal:!0,compile:function(b,d){"text/ng-template"==d.type&&a.put(d.id,b[0].text)}}}],Cg={$setViewValue:x,$render:x},Dg=["$element","$scope","$attrs",function(a,b,d){var c=this,e=new Sa;c.ngModelCtrl=Cg;c.unknownOption=B(X.createElement("option"));c.renderUnknownOption=function(b){b="? "+Ca(b)+" ?";c.unknownOption.val(b);a.prepend(c.unknownOption);a.val(b)};b.$on("$destroy",function(){c.renderUnknownOption=x});c.removeUnknownOption=
+function(){c.unknownOption.parent()&&c.unknownOption.remove()};c.readValue=function(){c.removeUnknownOption();return a.val()};c.writeValue=function(b){c.hasOption(b)?(c.removeUnknownOption(),a.val(b),""===b&&c.emptyOption.prop("selected",!0)):null==b&&c.emptyOption?(c.removeUnknownOption(),a.val("")):c.renderUnknownOption(b)};c.addOption=function(a,b){Ra(a,'"option value"');""===a&&(c.emptyOption=b);var d=e.get(a)||0;e.put(a,d+1);c.ngModelCtrl.$render();b[0].hasAttribute("selected")&&(b[0].selected=
+!0)};c.removeOption=function(a){var b=e.get(a);b&&(1===b?(e.remove(a),""===a&&(c.emptyOption=u)):e.put(a,b-1))};c.hasOption=function(a){return!!e.get(a)};c.registerOption=function(a,b,d,e,l){if(e){var m;d.$observe("value",function(a){y(m)&&c.removeOption(m);m=a;c.addOption(a,b)})}else l?a.$watch(l,function(a,e){d.$set("value",a);e!==a&&c.removeOption(e);c.addOption(a,b)}):c.addOption(d.value,b);b.on("$destroy",function(){c.removeOption(d.value);c.ngModelCtrl.$render()})}}],ke=function(){return{restrict:"E",
+require:["select","?ngModel"],controller:Dg,priority:1,link:{pre:function(a,b,d,c){var e=c[1];if(e){var f=c[0];f.ngModelCtrl=e;e.$render=function(){f.writeValue(e.$viewValue)};b.on("change",function(){a.$apply(function(){e.$setViewValue(f.readValue())})});if(d.multiple){f.readValue=function(){var a=[];n(b.find("option"),function(b){b.selected&&a.push(b.value)});return a};f.writeValue=function(a){var c=new Sa(a);n(b.find("option"),function(a){a.selected=y(c.get(a.value))})};var g,h=NaN;a.$watch(function(){h!==
+e.$viewValue||ma(g,e.$viewValue)||(g=ia(e.$viewValue),e.$render());h=e.$viewValue});e.$isEmpty=function(a){return!a||0===a.length}}}}}}},me=["$interpolate",function(a){return{restrict:"E",priority:100,compile:function(b,d){if(y(d.value))var c=a(d.value,!0);else{var e=a(b.text(),!0);e||d.$set("value",b.text())}return function(a,b,d){var k=b.parent();(k=k.data("$selectController")||k.parent().data("$selectController"))&&k.registerOption(a,b,d,c,e)}}}}],le=na({restrict:"E",terminal:!1}),Fc=function(){return{restrict:"A",
+require:"?ngModel",link:function(a,b,d,c){c&&(d.required=!0,c.$validators.required=function(a,b){return!d.required||!c.$isEmpty(b)},d.$observe("required",function(){c.$validate()}))}}},Ec=function(){return{restrict:"A",require:"?ngModel",link:function(a,b,d,c){if(c){var e,f=d.ngPattern||d.pattern;d.$observe("pattern",function(a){E(a)&&0<a.length&&(a=new RegExp("^"+a+"$"));if(a&&!a.test)throw G("ngPattern")("noregexp",f,a,ua(b));e=a||u;c.$validate()});c.$validators.pattern=function(a,b){return c.$isEmpty(b)||
+q(e)||e.test(b)}}}}},Hc=function(){return{restrict:"A",require:"?ngModel",link:function(a,b,d,c){if(c){var e=-1;d.$observe("maxlength",function(a){a=ea(a);e=isNaN(a)?-1:a;c.$validate()});c.$validators.maxlength=function(a,b){return 0>e||c.$isEmpty(b)||b.length<=e}}}}},Gc=function(){return{restrict:"A",require:"?ngModel",link:function(a,b,d,c){if(c){var e=0;d.$observe("minlength",function(a){e=ea(a)||0;c.$validate()});c.$validators.minlength=function(a,b){return c.$isEmpty(b)||b.length>=e}}}}};S.angular.bootstrap?
+console.log("WARNING: Tried to load angular more than once."):(ce(),ee(fa),fa.module("ngLocale",[],["$provide",function(a){function b(a){a+="";var b=a.indexOf(".");return-1==b?0:a.length-b-1}a.value("$locale",{DATETIME_FORMATS:{AMPMS:["AM","PM"],DAY:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),ERANAMES:["Before Christ","Anno Domini"],ERAS:["BC","AD"],FIRSTDAYOFWEEK:6,MONTH:"January February March April May June July August September October November December".split(" "),SHORTDAY:"Sun Mon Tue Wed Thu Fri Sat".split(" "),
+SHORTMONTH:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),WEEKENDRANGE:[5,6],fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",medium:"MMM d, y h:mm:ss a",mediumDate:"MMM d, y",mediumTime:"h:mm:ss a","short":"M/d/yy h:mm a",shortDate:"M/d/yy",shortTime:"h:mm a"},NUMBER_FORMATS:{CURRENCY_SYM:"$",DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"-\u00a4",
+negSuf:"",posPre:"\u00a4",posSuf:""}]},id:"en-us",pluralCat:function(a,c){var e=a|0,f=c;u===f&&(f=Math.min(b(a),3));Math.pow(10,f);return 1==e&&0==f?"one":"other"}})}]),B(X).ready(function(){Zd(X,yc)}))})(window,document);!window.angular.$$csp().noInlineStyle&&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
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular/angular.min.js.gzip b/xos-apps/auto-scale/gui/src/vendor/angular/angular.min.js.gzip
new file mode 100644
index 0000000..db839d6
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular/angular.min.js.gzip
Binary files differ
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular/angular.min.js.map b/xos-apps/auto-scale/gui/src/vendor/angular/angular.min.js.map
new file mode 100644
index 0000000..fbb9d46
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular/angular.min.js.map
@@ -0,0 +1,8 @@
+{
+"version":3,
+"file":"angular.min.js",
+"lineCount":294,
+"mappings":"A;;;;;aAKC,SAAQ,CAACA,CAAD,CAASC,CAAT,CAAmBC,CAAnB,CAA8B,CAgCvCC,QAAAA,EAAAA,CAAAA,CAAAA,CAAAA,CAAAA,MAAAA,SAAAA,EAAAA,CAAAA,IAAAA,EAAAA,SAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,GAAAA,EAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,EAAAA,EAAAA,CAAAA,CAAAA,sCAAAA,EAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,EAAAA,EAAAA,CAAAA,KAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,SAAAA,OAAAA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AAOE,OAAU,EAPZ,CAQE,OAAU,QARZ,CASE,OAAU,EATZ,CAZU,CAJI,CA1EM,CAuGxB,GAAM,OAvGkB,CAwGxB,UAAay1E,QAAQ,CAAC/pD,CAAD,CAAIwvD,CAAJ,CAAmB,CAAG,IAAIr7E,EAAI6rB,CAAJ7rB,CAAQ,CAAZ,CAnHvCihC,EAmHyEo6C,CAjHzE78E,EAAJ,GAAkByiC,CAAlB,GACEA,CADF,CACMlI,IAAA4wB,IAAA,CAASyxB,CAAA,CAgH2DvvD,CAhH3D,CAAT,CAAyB,CAAzB,CADN,CAIWkN,KAAAuiD,IAAA,CAAS,EAAT,CAAar6C,CAAb,CA6GmF,OAAS,EAAT,EAAIjhC,CAAJ,EAAsB,CAAtB,EA3GnFihC,CA2GmF,CA3HtDs6C,KA2HsD,CA3HFC,OA2HpD,CAxGhB,CAA1B,CApB+D,CAAhC,CAA/B,CAgIE,CAAAz8E,CAAA,CAAOR,CAAP,CAAA44D,MAAA,CAAuB,QAAQ,EAAG,CAChC9tD,EAAA,CAAY9K,CAAZ,CAAsB+K,EAAtB,CADgC,CAAlC,CA5IF,CAls4BuC,CAAtC,CAAD,CAk14BGhL,MAl14BH,CAk14BWC,QAl14BX,CAo14BCs3D,EAAAv3D,MAAA4M,QAAAuwE,MAAA,EAAA5lB,cAAD,EAAyCv3D,MAAA4M,QAAArH,QAAA,CAAuBtF,QAAAm9E,KAAvB,CAAA7iB,QAAA,CAA8C,gRAA9C;",
+"sources":["angular.js"],
+"names":["window","document","undefined","minErr","isArrayLike","obj","isWindow","isArray","isString","jqLite","length","Object","isNumber","item","forEach","iterator","context","key","isFunction","hasOwnProperty","call","isPrimitive","isBlankObject","forEachSorted","keys","sort","i","reverseParams","iteratorFn","value","nextUid","uid","baseExtend","dst","objs","deep","h","$$hashKey","ii","isObject","j","jj","src","isDate","Date","valueOf","isRegExp","RegExp","nodeName","cloneNode","isElement","clone","extend","slice","arguments","merge","toInt","str","parseInt","inherit","parent","extra","create","noop","identity","$","valueFn","hasCustomToString","toString","isUndefined","isDefined","getPrototypeOf","isScope","$evalAsync","$watch","isBoolean","isTypedArray","TYPED_ARRAY_REGEXP","test","node","prop","attr","find","makeMap","items","split","nodeName_","element","lowercase","arrayRemove","array","index","indexOf","splice","copy","source","destination","copyRecurse","push","copyElement","stackSource","stackDest","ngMinErr","needsRecurse","constructor","getTime","match","lastIndex","shallowCopy","charAt","equals","o1","o2","t1","t2","keySet","createMap","concat","array1","array2","bind","self","fn","curryArgs","startIndex","apply","toJsonReplacer","val","toJson","pretty","JSON","stringify","fromJson","json","parse","timezoneToOffset","timezone","fallback","requestedTimezoneOffset","isNaN","convertTimezoneToLocal","date","reverse","timezoneOffset","getTimezoneOffset","setMinutes","getMinutes","minutes","startingTag","empty","e","elemHtml","append","html","nodeType","NODE_TYPE_TEXT","replace","tryDecodeURIComponent","decodeURIComponent","parseKeyValue","keyValue","splitPoint","substring","toKeyValue","parts","arrayValue","encodeUriQuery","join","encodeUriSegment","pctEncodeSpaces","encodeURIComponent","getNgAttribute","ngAttr","ngAttrPrefixes","getAttribute","angularInit","bootstrap","appElement","module","config","prefix","name","hasAttribute","candidate","querySelector","strictDi","modules","defaultConfig","doBootstrap","injector","tag","unshift","$provide","debugInfoEnabled","$compileProvider","createInjector","invoke","bootstrapApply","scope","compile","$apply","data","NG_ENABLE_DEBUG_INFO","NG_DEFER_BOOTSTRAP","angular","resumeBootstrap","angular.resumeBootstrap","extraModules","resumeDeferredBootstrap","reloadWithDebugInfo","location","reload","getTestability","rootElement","get","snake_case","separator","SNAKE_CASE_REGEXP","letter","pos","toLowerCase","bindJQuery","originalCleanData","bindJQueryFired","jqName","jq","jQuery","on","JQLitePrototype","isolateScope","controller","inheritedData","cleanData","jQuery.cleanData","elems","events","skipDestroyOnNextJQueryCleanData","elem","_data","$destroy","triggerHandler","JQLite","assertArg","arg","reason","assertArgFn","acceptArrayAnnotation","assertNotHasOwnProperty","getter","path","bindFnToScope","lastInstance","len","getBlockNodes","nodes","endNode","blockNodes","nextSibling","setupModuleLoader","ensure","factory","$injectorMinErr","$$minErr","requires","configFn","invokeLater","provider","method","insertMethod","queue","invokeQueue","moduleInstance","invokeLaterAndSetModuleName","recipeName","factoryFunction","$$moduleName","configBlocks","runBlocks","_invokeQueue","_configBlocks","_runBlocks","service","constant","decorator","animation","filter","directive","run","block","publishExternalAPI","version","uppercase","counter","csp","angularModule","ngModule","$$sanitizeUri","$$SanitizeUriProvider","$CompileProvider","a","htmlAnchorDirective","input","inputDirective","textarea","form","formDirective","script","scriptDirective","select","selectDirective","style","styleDirective","option","optionDirective","ngBind","ngBindDirective","ngBindHtml","ngBindHtmlDirective","ngBindTemplate","ngBindTemplateDirective","ngClass","ngClassDirective","ngClassEven","ngClassEvenDirective","ngClassOdd","ngClassOddDirective","ngCloak","ngCloakDirective","ngController","ngControllerDirective","ngForm","ngFormDirective","ngHide","ngHideDirective","ngIf","ngIfDirective","ngInclude","ngIncludeDirective","ngInit","ngInitDirective","ngNonBindable","ngNonBindableDirective","ngPluralize","ngPluralizeDirective","ngRepeat","ngRepeatDirective","ngShow","ngShowDirective","ngStyle","ngStyleDirective","ngSwitch","ngSwitchDirective","ngSwitchWhen","ngSwitchWhenDirective","ngSwitchDefault","ngSwitchDefaultDirective","ngOptions","ngOptionsDirective","ngTransclude","ngTranscludeDirective","ngModel","ngModelDirective","ngList","ngListDirective","ngChange","ngChangeDirective","pattern","patternDirective","ngPattern","required","requiredDirective","ngRequired","minlength","minlengthDirective","ngMinlength","maxlength","maxlengthDirective","ngMaxlength","ngValue","ngValueDirective","ngModelOptions","ngModelOptionsDirective","ngIncludeFillContentDirective","ngAttributeAliasDirectives","ngEventDirectives","$anchorScroll","$AnchorScrollProvider","$animate","$AnimateProvider","$animateCss","$CoreAnimateCssProvider","$$animateQueue","$$CoreAnimateQueueProvider","$$AnimateRunner","$$CoreAnimateRunnerProvider","$browser","$BrowserProvider","$cacheFactory","$CacheFactoryProvider","$controller","$ControllerProvider","$document","$DocumentProvider","$exceptionHandler","$ExceptionHandlerProvider","$filter","$FilterProvider","$$forceReflow","$$ForceReflowProvider","$interpolate","$InterpolateProvider","$interval","$IntervalProvider","$http","$HttpProvider","$httpParamSerializer","$HttpParamSerializerProvider","$httpParamSerializerJQLike","$HttpParamSerializerJQLikeProvider","$httpBackend","$HttpBackendProvider","$xhrFactory","$xhrFactoryProvider","$location","$LocationProvider","$log","$LogProvider","$parse","$ParseProvider","$rootScope","$RootScopeProvider","$q","$QProvider","$$q","$$QProvider","$sce","$SceProvider","$sceDelegate","$SceDelegateProvider","$sniffer","$SnifferProvider","$templateCache","$TemplateCacheProvider","$templateRequest","$TemplateRequestProvider","$$testability","$$TestabilityProvider","$timeout","$TimeoutProvider","$window","$WindowProvider","$$rAF","$$RAFProvider","$$jqLite","$$jqLiteProvider","$$HashMap","$$HashMapProvider","$$cookieReader","$$CookieReaderProvider","camelCase","SPECIAL_CHARS_REGEXP","_","offset","toUpperCase","MOZ_HACK_REGEXP","jqLiteAcceptsData","NODE_TYPE_ELEMENT","NODE_TYPE_DOCUMENT","jqLiteBuildFragment","tmp","fragment","createDocumentFragment","HTML_REGEXP","appendChild","createElement","TAG_NAME_REGEXP","exec","wrap","wrapMap","_default","innerHTML","XHTML_TAG_REGEXP","lastChild","childNodes","firstChild","textContent","createTextNode","argIsString","trim","jqLiteMinErr","parsed","SINGLE_TAG_REGEXP","jqLiteAddNodes","jqLiteClone","jqLiteDealoc","onlyDescendants","jqLiteRemoveData","querySelectorAll","descendants","l","jqLiteOff","type","unsupported","expandoStore","jqLiteExpandoStore","handle","removeHandler","listenerFns","removeEventListener","MOUSE_EVENT_MAP","expandoId","ng339","jqCache","createIfNecessary","jqId","jqLiteData","isSimpleSetter","isSimpleGetter","massGetter","jqLiteHasClass","selector","jqLiteRemoveClass","cssClasses","setAttribute","cssClass","jqLiteAddClass","existingClasses","root","elements","jqLiteController","jqLiteInheritedData","documentElement","names","parentNode","NODE_TYPE_DOCUMENT_FRAGMENT","host","jqLiteEmpty","removeChild","jqLiteRemove","keepData","jqLiteDocumentLoaded","action","win","readyState","setTimeout","getBooleanAttrName","booleanAttr","BOOLEAN_ATTR","BOOLEAN_ELEMENTS","createEventHandler","eventHandler","event","isDefaultPrevented","event.isDefaultPrevented","defaultPrevented","eventFns","eventFnsLength","immediatePropagationStopped","originalStopImmediatePropagation","stopImmediatePropagation","event.stopImmediatePropagation","stopPropagation","isImmediatePropagationStopped","event.isImmediatePropagationStopped","handlerWrapper","specialHandlerWrapper","defaultHandlerWrapper","handler","specialMouseHandlerWrapper","target","related","relatedTarget","jqLiteContains","$get","this.$get","hasClass","classes","addClass","removeClass","hashKey","nextUidFn","objType","HashMap","isolatedUid","this.nextUid","put","anonFn","args","fnText","STRIP_COMMENTS","FN_ARGS","modulesToLoad","supportObject","delegate","provider_","providerInjector","instantiate","providerCache","providerSuffix","enforceReturnValue","enforcedReturnValue","result","instanceInjector","factoryFn","enforce","loadModules","moduleFn","runInvokeQueue","invokeArgs","loadedModules","message","stack","createInternalInjector","cache","getService","serviceName","caller","INSTANTIATING","err","shift","locals","$inject","$$annotate","Type","instance","prototype","returnedValue","annotate","has","$injector","instanceCache","decorFn","origProvider","orig$get","origProvider.$get","origInstance","$delegate","autoScrollingEnabled","disableAutoScrolling","this.disableAutoScrolling","getFirstAnchor","list","Array","some","scrollTo","scrollIntoView","scroll","yOffset","getComputedStyle","position","getBoundingClientRect","bottom","elemTop","top","scrollBy","hash","elm","getElementById","getElementsByName","autoScrollWatch","autoScrollWatchAction","newVal","oldVal","mergeClasses","b","splitClasses","klass","prepareAnimateOptions","options","Browser","completeOutstandingRequest","outstandingRequestCount","outstandingRequestCallbacks","pop","error","cacheStateAndFireUrlChange","pendingLocation","cacheState","fireUrlChange","history","state","cachedState","lastCachedState","lastBrowserUrl","url","lastHistoryState","urlChangeListeners","listener","clearTimeout","pendingDeferIds","isMock","$$completeOutstandingRequest","$$incOutstandingRequestCount","self.$$incOutstandingRequestCount","notifyWhenNoOutstandingRequests","self.notifyWhenNoOutstandingRequests","callback","href","baseElement","self.url","sameState","sameBase","stripHash","substr","self.state","urlChangeInit","onUrlChange","self.onUrlChange","$$applicationDestroyed","self.$$applicationDestroyed","off","$$checkUrlChange","baseHref","self.baseHref","defer","self.defer","delay","timeoutId","cancel","self.defer.cancel","deferId","cacheFactory","cacheId","refresh","entry","freshEnd","staleEnd","n","link","p","nextEntry","prevEntry","caches","size","stats","id","capacity","Number","MAX_VALUE","lruHash","lruEntry","remove","removeAll","destroy","info","cacheFactory.info","cacheFactory.get","$$sanitizeUriProvider","parseIsolateBindings","directiveName","isController","LOCAL_REGEXP","bindings","definition","scopeName","$compileMinErr","mode","collection","optional","attrName","assertValidDirectiveName","hasDirectives","COMMENT_DIRECTIVE_REGEXP","CLASS_DIRECTIVE_REGEXP","ALL_OR_NOTHING_ATTRS","REQUIRE_PREFIX_REGEXP","EVENT_HANDLER_ATTR_REGEXP","this.directive","registerDirective","directiveFactory","Suffix","directives","priority","require","restrict","bindToController","controllerAs","CNTRL_REG","$$bindings","$$isolateBindings","aHrefSanitizationWhitelist","this.aHrefSanitizationWhitelist","regexp","imgSrcSanitizationWhitelist","this.imgSrcSanitizationWhitelist","this.debugInfoEnabled","enabled","safeAddClass","$element","className","$compileNodes","transcludeFn","maxPriority","ignoreDirective","previousCompileContext","nodeValue","compositeLinkFn","compileNodes","$$addScopeClass","namespace","publicLinkFn","cloneConnectFn","needsNewScope","$parent","$new","parentBoundTranscludeFn","transcludeControllers","futureParentElement","$$boundTransclude","$linkNode","wrapTemplate","controllerName","$$addScopeInfo","nodeList","$rootElement","childLinkFn","childScope","childBoundTranscludeFn","stableNodeList","nodeLinkFnFound","linkFns","idx","nodeLinkFn","transcludeOnThisElement","createBoundTranscludeFn","transclude","templateOnThisElement","attrs","linkFnFound","Attributes","collectDirectives","applyDirectivesToNode","$$element","terminal","previousBoundTranscludeFn","boundTranscludeFn","transcludedScope","cloneFn","controllers","containingScope","$$transcluded","attrsMap","$attr","addDirective","directiveNormalize","isNgAttr","nAttrs","attributes","attrStartName","attrEndName","ngAttrName","NG_ATTR_BINDING","PREFIX_REGEXP","multiElementMatch","MULTI_ELEMENT_DIR_RE","directiveIsMultiElement","nName","addAttrInterpolateDirective","animVal","msie","addTextInterpolateDirective","NODE_TYPE_COMMENT","byPriority","groupScan","attrStart","attrEnd","depth","groupElementsLinkFnWrapper","linkFn","compileNode","templateAttrs","jqCollection","originalReplaceDirective","preLinkFns","postLinkFns","addLinkFns","pre","post","newIsolateScopeDirective","$$isolateScope","cloneAndAnnotateFn","getControllers","elementControllers","inheritType","dataName","setupControllers","controllerDirectives","controllerKey","$scope","$attrs","$transclude","controllerInstance","hasElementTranscludeDirective","linkNode","controllersBoundTransclude","cloneAttachFn","scopeToChild","controllerScope","removeScopeBindingWatches","newScopeDirective","templateDirective","$$originalDirective","initializeDirectiveBindings","$on","controllerDirective","identifier","removeControllerBindingWatches","controllerResult","invokeLinkFn","template","templateUrl","terminalPriority","nonTlbTranscludeDirective","hasTranscludeDirective","hasTemplate","$compileNode","$template","childTranscludeFn","$$start","$$end","directiveValue","assertNoDuplicate","$$tlb","createComment","replaceWith","replaceDirective","contents","$$newScope","denormalizeTemplate","removeComments","templateNamespace","newTemplateAttrs","templateDirectives","unprocessedDirectives","markDirectiveScope","mergeTemplateAttributes","compileTemplateUrl","Math","max","newScope","tDirectives","startAttrName","endAttrName","multiElement","srcAttr","dstAttr","$set","tAttrs","linkQueue","afterTemplateNodeLinkFn","afterTemplateChildLinkFn","beforeTemplateCompileNode","origAsyncDirective","derivedSyncDirective","then","content","tempTemplateAttrs","beforeTemplateLinkNode","linkRootElement","$$destroyed","oldClasses","delayedNodeLinkFn","ignoreChildLinkFn","diff","what","previousDirective","wrapModuleNameIfDefined","moduleName","text","interpolateFn","textInterpolateCompileFn","templateNode","templateNodeParent","hasCompileParent","$$addBindingClass","textInterpolateLinkFn","$$addBindingInfo","expressions","interpolateFnWatchAction","wrapper","getTrustedContext","attrNormalizedName","HTML","RESOURCE_URL","allOrNothing","trustedContext","attrInterpolatePreLinkFn","$$observers","newValue","$$inter","$$scope","oldValue","$updateClass","elementsToRemove","newNode","firstElementToRemove","removeCount","j2","replaceChild","hasData","expando","k","kk","annotation","removeWatchCollection","lastValue","parentGet","parentSet","compare","$observe","literal","assign","parentValueWatch","parentValue","$stateful","removeWatch","$watchCollection","removeWatches","attributesToCopy","$normalize","$addClass","classVal","$removeClass","newClasses","toAdd","tokenDifference","toRemove","writeAttr","booleanKey","aliasedKey","ALIASED_ATTR","observer","trimmedSrcset","srcPattern","rawUris","nbrUrisWith2parts","floor","innerIdx","lastTuple","removeAttr","listeners","startSymbol","endSymbol","binding","isolated","noTemplate","str1","str2","values","tokens1","tokens2","token","jqNodes","globals","register","this.register","allowGlobals","this.allowGlobals","addIdentifier","expression","later","ident","$controllerMinErr","controllerPrototype","exception","cause","serializeValue","v","toISOString","ngParamSerializer","params","jQueryLikeParamSerializer","serialize","toSerialize","topLevel","defaultHttpResponseTransform","headers","tempData","JSON_PROTECTION_PREFIX","contentType","jsonStart","JSON_START","JSON_ENDS","parseHeaders","line","headerVal","headerKey","headersGetter","headersObj","transformData","status","fns","defaults","transformResponse","transformRequest","d","common","CONTENT_TYPE_APPLICATION_JSON","patch","xsrfCookieName","xsrfHeaderName","paramSerializer","useApplyAsync","this.useApplyAsync","useLegacyPromise","useLegacyPromiseExtensions","this.useLegacyPromiseExtensions","interceptorFactories","interceptors","requestConfig","response","resp","reject","executeHeaderFns","headerContent","processedHeaders","headerFn","header","mergeHeaders","defHeaders","reqHeaders","defHeaderName","lowercaseDefHeaderName","reqHeaderName","chain","serverRequest","reqData","withCredentials","sendReq","promise","when","reversedInterceptors","interceptor","request","requestError","responseError","thenFn","rejectFn","success","promise.success","promise.error","$httpMinErrLegacyFn","done","headersString","statusText","resolveHttpPromise","resolvePromise","$applyAsync","$$phase","deferred","resolve","resolvePromiseWithResult","removePendingReq","pendingRequests","cachedResp","buildUrl","defaultCache","xsrfValue","urlIsSameOrigin","timeout","responseType","serializedParams","interceptorFactory","createShortMethods","createShortMethodsWithData","createXhr","XMLHttpRequest","createHttpBackend","callbacks","$browserDefer","rawDocument","jsonpReq","callbackId","async","body","called","addEventListener","timeoutRequest","jsonpDone","xhr","abort","completeRequest","open","setRequestHeader","onload","xhr.onload","responseText","urlResolve","protocol","getAllResponseHeaders","onerror","onabort","send","this.startSymbol","this.endSymbol","escape","ch","unescapeText","escapedStartRegexp","escapedEndRegexp","mustHaveExpression","parseStringifyInterceptor","getTrusted","$interpolateMinErr","interr","endIndex","parseFns","textLength","expressionPositions","startSymbolLength","exp","endSymbolLength","throwNoconcat","compute","interpolationFn","$$watchDelegate","$watchGroup","interpolateFnWatcher","oldValues","currValue","$interpolate.startSymbol","$interpolate.endSymbol","interval","count","invokeApply","hasParams","setInterval","clearInterval","iteration","skipApply","$$intervalId","tick","notify","intervals","interval.cancel","encodePath","segments","parseAbsoluteUrl","absoluteUrl","locationObj","parsedUrl","$$protocol","$$host","hostname","$$port","port","DEFAULT_PORTS","parseAppUrl","relativeUrl","prefixed","$$path","pathname","$$search","search","$$hash","beginsWith","begin","whole","trimEmptyHash","LocationHtml5Url","appBase","appBaseNoFile","basePrefix","$$html5","$$parse","this.$$parse","pathUrl","$locationMinErr","$$compose","this.$$compose","$$url","$$absUrl","$$parseLinkUrl","this.$$parseLinkUrl","relHref","appUrl","prevAppUrl","rewrittenUrl","LocationHashbangUrl","hashPrefix","withoutBaseUrl","withoutHashUrl","windowsFilePathExp","base","firstPathSegmentMatch","LocationHashbangInHtml5Url","locationGetter","property","locationGetterSetter","preprocess","html5Mode","requireBase","rewriteLinks","this.hashPrefix","this.html5Mode","setBrowserUrlWithFallback","oldUrl","oldState","$$state","afterLocationChange","$broadcast","absUrl","LocationMode","initialUrl","lastIndexOf","IGNORE_URI_REGEXP","ctrlKey","metaKey","shiftKey","which","button","absHref","preventDefault","initializing","newUrl","newState","$digest","$locationWatch","currentReplace","$$replace","urlOrStateChanged","debug","debugEnabled","this.debugEnabled","flag","formatError","Error","sourceURL","consoleLog","console","logFn","log","hasApply","arg1","arg2","warn","ensureSafeMemberName","fullExpression","$parseMinErr","getStringValue","ensureSafeObject","children","ensureSafeFunction","CALL","APPLY","BIND","ensureSafeAssignContext","Function","ifDefined","plusFn","r","findConstantAndWatchExpressions","ast","allConstants","argsToWatch","AST","Program","expr","Literal","toWatch","UnaryExpression","argument","BinaryExpression","left","right","LogicalExpression","ConditionalExpression","alternate","consequent","Identifier","MemberExpression","object","computed","CallExpression","callee","AssignmentExpression","ArrayExpression","ObjectExpression","properties","ThisExpression","getInputs","lastExpression","isAssignable","assignableAST","NGValueParameter","operator","isLiteral","ASTCompiler","astBuilder","ASTInterpreter","isPossiblyDangerousMemberName","getValueOf","objectValueOf","cacheDefault","cacheExpensive","expressionInputDirtyCheck","oldValueOfValue","inputsWatchDelegate","objectEquality","parsedExpression","prettyPrintExpression","inputExpressions","inputs","lastResult","oldInputValueOf","expressionInputWatch","newInputValue","oldInputValueOfValues","oldInputValues","expressionInputsWatch","changed","oneTimeWatchDelegate","unwatch","oneTimeWatch","oneTimeListener","old","$$postDigest","oneTimeLiteralWatchDelegate","isAllDefined","allDefined","constantWatchDelegate","constantWatch","constantListener","addInterceptor","interceptorFn","watchDelegate","useInputs","regularInterceptedExpression","oneTimeInterceptedExpression","noUnsafeEval","$parseOptions","expensiveChecks","$parseOptionsExpensive","oneTime","cacheKey","parseOptions","lexer","Lexer","parser","Parser","qFactory","nextTick","exceptionHandler","callOnce","resolveFn","Promise","simpleBind","scheduleProcessQueue","processScheduled","pending","Deferred","$qMinErr","TypeError","onFulfilled","onRejected","progressBack","catch","finally","handleCallback","$$reject","$$resolve","progress","makePromise","resolved","isResolved","callbackOutput","errback","$Q","Q","resolver","all","promises","results","requestAnimationFrame","webkitRequestAnimationFrame","cancelAnimationFrame","webkitCancelAnimationFrame","webkitCancelRequestAnimationFrame","rafSupported","raf","timer","supported","createChildScopeClass","ChildScope","$$watchers","$$nextSibling","$$childHead","$$childTail","$$listeners","$$listenerCount","$$watchersCount","$id","$$ChildScope","TTL","$rootScopeMinErr","lastDirtyWatch","applyAsyncId","digestTtl","this.digestTtl","destroyChildScope","$event","currentScope","cleanUpScope","$$prevSibling","$root","Scope","beginPhase","phase","incrementWatchersCount","current","decrementListenerCount","initWatchVal","flushApplyAsync","applyAsyncQueue","scheduleApplyAsync","isolate","child","watchExp","watcher","last","eq","deregisterWatch","watchExpressions","watchGroupAction","changeReactionScheduled","firstRun","newValues","deregisterFns","shouldCall","deregisterWatchGroup","unwatchFn","watchGroupSubAction","$watchCollectionInterceptor","_value","bothNaN","newItem","oldItem","internalArray","oldLength","changeDetected","newLength","internalObject","veryOldValue","trackVeryOldValue","changeDetector","initRun","$watchCollectionAction","watch","watchers","dirty","ttl","watchLog","logIdx","asyncTask","asyncQueue","$eval","msg","next","postDigestQueue","eventName","this.$watchGroup","$applyAsyncExpression","namedListeners","indexOfListener","$emit","targetScope","listenerArgs","$$asyncQueue","$$postDigestQueue","$$applyAsyncQueue","sanitizeUri","uri","isImage","regex","normalizedVal","adjustMatcher","matcher","$sceMinErr","escapeForRegexp","adjustMatchers","matchers","adjustedMatchers","SCE_CONTEXTS","resourceUrlWhitelist","resourceUrlBlacklist","this.resourceUrlWhitelist","this.resourceUrlBlacklist","matchUrl","generateHolderType","Base","holderType","trustedValue","$$unwrapTrustedValue","this.$$unwrapTrustedValue","holderType.prototype.valueOf","holderType.prototype.toString","htmlSanitizer","trustedValueHolderBase","byType","CSS","URL","JS","trustAs","Constructor","maybeTrusted","allowed","this.enabled","sce","isEnabled","sce.isEnabled","sce.getTrusted","parseAs","sce.parseAs","enumValue","lName","eventSupport","android","userAgent","navigator","boxee","vendorPrefix","vendorRegex","bodyStyle","transitions","animations","webkitTransition","webkitAnimation","pushState","hasEvent","divElm","handleRequestFn","tpl","ignoreRequestError","totalPendingRequests","getTrustedResourceUrl","transformer","httpOptions","handleError","testability","testability.findBindings","opt_exactMatch","getElementsByClassName","matches","dataBinding","bindingName","testability.findModels","prefixes","attributeEquals","testability.getLocation","testability.setLocation","testability.whenStable","deferreds","$$timeoutId","timeout.cancel","urlParsingNode","requestUrl","originUrl","$$CookieReader","safeDecodeURIComponent","lastCookies","lastCookieString","cookieArray","cookie","currentCookieString","filters","suffix","currencyFilter","dateFilter","filterFilter","jsonFilter","limitToFilter","lowercaseFilter","numberFilter","orderByFilter","uppercaseFilter","comparator","matchAgainstAnyProp","getTypeForFilter","expressionType","predicateFn","createPredicateFn","shouldMatchPrimitives","actual","expected","deepCompare","dontMatchWholeObject","actualType","expectedType","expectedVal","matchAnyProperty","actualVal","$locale","formats","NUMBER_FORMATS","amount","currencySymbol","fractionSize","CURRENCY_SYM","PATTERNS","maxFrac","formatNumber","GROUP_SEP","DECIMAL_SEP","number","groupSep","decimalSep","isNegative","abs","isInfinity","Infinity","isFinite","numStr","formatedText","hasExponent","toFixed","parseFloat","fractionLen","min","minFrac","round","fraction","lgroup","lgSize","group","gSize","negPre","posPre","negSuf","posSuf","padNumber","num","digits","neg","dateGetter","dateStrGetter","shortForm","getFirstThursdayOfYear","year","dayOfWeekOnFirst","getDay","weekGetter","firstThurs","getFullYear","thisThurs","getMonth","getDate","eraGetter","ERAS","jsonStringToDate","string","R_ISO8601_STR","tzHour","tzMin","dateSetter","setUTCFullYear","setFullYear","timeSetter","setUTCHours","setHours","m","s","ms","format","DATETIME_FORMATS","NUMBER_STRING","DATE_FORMATS_SPLIT","dateTimezoneOffset","DATE_FORMATS","spacing","limit","processPredicates","sortPredicate","reverseOrder","map","predicate","descending","predicates","compareValues","getComparisonObject","predicateValues","doComparison","v1","v2","ngDirective","FormController","controls","$error","$$success","$pending","$name","$dirty","$pristine","$valid","$invalid","$submitted","$$parentForm","nullFormCtrl","$rollbackViewValue","form.$rollbackViewValue","control","$commitViewValue","form.$commitViewValue","$addControl","form.$addControl","$$renameControl","form.$$renameControl","newName","oldName","$removeControl","form.$removeControl","$setValidity","addSetValidityMethod","ctrl","set","unset","$setDirty","form.$setDirty","PRISTINE_CLASS","DIRTY_CLASS","$setPristine","form.$setPristine","setClass","SUBMITTED_CLASS","$setUntouched","form.$setUntouched","$setSubmitted","form.$setSubmitted","stringBasedInputType","$formatters","$isEmpty","baseInputType","composing","ev","ngTrim","$viewValue","$$hasNativeValidators","$setViewValue","deferListener","origValue","keyCode","$render","ctrl.$render","createDateParser","mapping","iso","ISO_DATE_REGEXP","yyyy","MM","dd","HH","getHours","mm","ss","getSeconds","sss","getMilliseconds","part","NaN","createDateInputType","parseDate","dynamicDateInputType","isValidDate","parseObservedDateValue","badInputChecker","$options","previousDate","$$parserName","$parsers","parsedDate","ngModelMinErr","ngMin","minVal","$validators","ctrl.$validators.min","$validate","ngMax","maxVal","ctrl.$validators.max","validity","VALIDITY_STATE_PROPERTY","badInput","typeMismatch","parseConstantExpr","parseFn","classDirective","arrayDifference","arrayClasses","digestClassCounts","classCounts","classesToUpdate","ngClassWatchAction","$index","old$index","mod","cachedToggleClass","switchValue","classCache","toggleValidationCss","validationErrorKey","isValid","VALID_CLASS","INVALID_CLASS","setValidity","isObjectEmpty","PENDING_CLASS","combinedState","REGEX_STRING_REGEXP","documentMode","rules","ngCspElement","ngCspAttribute","noInlineStyle","name_","el","full","major","minor","dot","codeName","JQLite._data","mouseleave","mouseenter","optgroup","tbody","tfoot","colgroup","caption","thead","th","td","Node","contains","compareDocumentPosition","ready","trigger","fired","removeData","jqLiteHasData","removeAttribute","css","NODE_TYPE_ATTRIBUTE","lowercasedName","specified","getNamedItem","ret","getText","$dv","multiple","selected","nodeCount","jqLiteOn","types","addHandler","noEventListener","one","onFn","replaceNode","insertBefore","contentDocument","prepend","wrapNode","detach","after","newElement","toggleClass","condition","classCondition","nextElementSibling","getElementsByTagName","extraParameters","dummyEvent","handlerArgs","eventFnsCopy","arg3","unbind","FN_ARG_SPLIT","FN_ARG","argDecl","underscore","$animateMinErr","AnimateRunner","end","resume","pause","complete","pass","fail","postDigestElements","updateData","handleCSSClassChanges","existing","pin","domOperation","from","to","classesAdded","add","classesRemoved","$$registeredAnimations","classNameFilter","this.classNameFilter","$$classNameFilter","reservedRegex","NG_ANIMATE_CLASSNAME","domInsert","parentElement","afterElement","afterNode","ELEMENT_NODE","previousElementSibling","runner","enter","move","leave","addclass","animate","tempClasses","RAFPromise","getPromise","f1","f2","closed","cleanupStyles","start","domNode","offsetWidth","APPLICATION_JSON","$httpMinErr","$interpolateMinErr.throwNoconcat","$interpolateMinErr.interr","PATH_MATCH","locationPrototype","paramValue","Location","Location.prototype.state","OPERATORS","ESCAPE","lex","tokens","readString","peek","readNumber","isIdent","readIdent","is","isWhitespace","ch2","ch3","op2","op3","op1","throwError","chars","isExpOperator","colStr","peekCh","quote","rawString","hex","String","fromCharCode","rep","ExpressionStatement","Property","program","expressionStatement","expect","filterChain","assignment","ternary","logicalOR","consume","logicalAND","equality","relational","additive","multiplicative","unary","primary","arrayDeclaration","constants","parseArguments","baseExpression","peekToken","kind","e1","e2","e3","e4","peekAhead","t","nextId","vars","own","assignable","stage","computing","recurse","return_","generateFunction","fnKey","intoId","watchId","fnString","USE","STRICT","filterPrefix","watchFns","varsPrefix","section","nameId","recursionFn","skipWatchIdCheck","if_","lazyAssign","computedMember","lazyRecurse","plus","not","getHasOwnProperty","nonComputedMember","addEnsureSafeObject","notNull","addEnsureSafeMemberName","addEnsureSafeFunction","member","addEnsureSafeAssignContext","filterName","defaultValue","stringEscapeRegex","stringEscapeFn","c","charCodeAt","skip","init","fn.assign","rhs","lhs","unary+","unary-","unary!","binary+","binary-","binary*","binary/","binary%","binary===","binary!==","binary==","binary!=","binary<","binary>","binary<=","binary>=","binary&&","binary||","ternary?:","astCompiler","yy","y","MMMM","MMM","M","H","hh","EEEE","EEE","ampmGetter","AMPMS","Z","timeZoneGetter","zone","paddedZone","ww","w","G","GG","GGG","GGGG","longEraGetter","ERANAMES","xlinkHref","propName","defaultLinkFn","normalized","ngBooleanAttrWatchAction","htmlAttr","ngAttrAliasWatchAction","nullFormRenameControl","formDirectiveFactory","isNgForm","getSetter","ngFormCompile","formElement","nameAttr","ngFormPreLink","ctrls","handleFormSubmission","setter","URL_REGEXP","EMAIL_REGEXP","NUMBER_REGEXP","DATE_REGEXP","DATETIMELOCAL_REGEXP","WEEK_REGEXP","MONTH_REGEXP","TIME_REGEXP","inputType","textInputType","weekParser","isoWeek","existingDate","week","hours","seconds","milliseconds","addDays","numberInputType","urlInputType","ctrl.$validators.url","modelValue","viewValue","emailInputType","email","ctrl.$validators.email","radioInputType","checked","checkboxInputType","trueValue","ngTrueValue","falseValue","ngFalseValue","ctrl.$isEmpty","CONSTANT_VALUE_REGEXP","tplAttr","ngValueConstantLink","ngValueLink","valueWatchAction","$compile","ngBindCompile","templateElement","ngBindLink","ngBindWatchAction","ngBindTemplateCompile","ngBindTemplateLink","ngBindHtmlCompile","tElement","ngBindHtmlGetter","ngBindHtmlWatch","ngBindHtmlLink","ngBindHtmlWatchAction","getTrustedHtml","$viewChangeListeners","forceAsyncEvents","ngEventHandler","previousElements","ngIfWatchAction","srcExp","onloadExp","autoScrollExp","autoscroll","changeCounter","previousElement","currentElement","cleanupLastIncludeContent","ngIncludeWatchAction","afterAnimation","thisChangeId","namespaceAdaptedClone","trimValues","NgModelController","$modelValue","$$rawModelValue","$asyncValidators","$untouched","$touched","parsedNgModel","parsedNgModelAssign","ngModelGet","ngModelSet","pendingDebounce","parserValid","$$setOptions","this.$$setOptions","getterSetter","invokeModelGetter","invokeModelSetter","$$$p","this.$isEmpty","currentValidationRunId","this.$setPristine","this.$setDirty","this.$setUntouched","UNTOUCHED_CLASS","TOUCHED_CLASS","$setTouched","this.$setTouched","this.$rollbackViewValue","$$lastCommittedViewValue","this.$validate","prevValid","prevModelValue","allowInvalid","$$runValidators","allValid","$$writeModelToScope","this.$$runValidators","doneCallback","processSyncValidators","syncValidatorsValid","validator","processAsyncValidators","validatorPromises","validationDone","localValidationRunId","processParseErrors","errorKey","this.$commitViewValue","$$parseAndValidate","this.$$parseAndValidate","this.$$writeModelToScope","this.$setViewValue","updateOnDefault","$$debounceViewValueCommit","this.$$debounceViewValueCommit","debounceDelay","debounce","ngModelWatch","formatters","ngModelCompile","ngModelPreLink","modelCtrl","formCtrl","ngModelPostLink","updateOn","DEFAULT_REGEXP","that","ngOptionsMinErr","NG_OPTIONS_REGEXP","parseOptionsExpression","optionsExp","selectElement","Option","selectValue","label","disabled","getOptionValuesKeys","optionValues","optionValuesKeys","keyName","itemKey","valueName","selectAs","trackBy","viewValueFn","trackByFn","getTrackByValueFn","getHashOfValue","getTrackByValue","getLocals","displayFn","groupByFn","disableWhenFn","valuesFn","getWatchables","watchedArray","optionValuesLength","disableWhen","getOptions","optionItems","selectValueMap","optionItem","getOptionFromViewValue","getViewValueFromOption","optionTemplate","optGroupTemplate","ngOptionsPreLink","registerOption","ngOptionsPostLink","updateOptionElement","addOrReuseElement","removeExcessElements","skipEmptyAndUnknownOptions","emptyOption_","emptyOption","unknownOption_","unknownOption","updateOptions","previousValue","selectCtrl","readValue","groupMap","providedEmptyOption","updateOption","optionElement","groupElement","currentOptionElement","ngModelCtrl","nextValue","ngModelCtrl.$isEmpty","writeValue","selectCtrl.writeValue","selectCtrl.readValue","selectedValues","selections","selectedOption","BRACE","IS_WHEN","updateElementText","newText","numberExp","whenExp","whens","whensExpFns","braceReplacement","watchRemover","lastCount","attributeName","tmpMatch","whenKey","ngPluralizeWatchAction","countIsNaN","pluralCat","whenExpFn","ngRepeatMinErr","updateScope","valueIdentifier","keyIdentifier","arrayLength","$first","$last","$middle","$odd","$even","ngRepeatCompile","ngRepeatEndComment","aliasAs","trackByExp","trackByExpGetter","trackByIdExpFn","trackByIdArrayFn","trackByIdObjFn","hashFnLocals","ngRepeatLink","lastBlockMap","ngRepeatAction","previousNode","nextNode","nextBlockMap","collectionLength","trackById","collectionKeys","nextBlockOrder","trackByIdFn","blockKey","ngRepeatTransclude","ngShowWatchAction","NG_HIDE_CLASS","NG_HIDE_IN_PROGRESS_CLASS","ngHideWatchAction","ngStyleWatchAction","newStyles","oldStyles","ngSwitchController","cases","selectedTranscludes","selectedElements","previousLeaveAnimations","selectedScopes","spliceFactory","ngSwitchWatchAction","selectedTransclude","caseElement","selectedScope","anchor","noopNgModelController","SelectController","optionsMap","renderUnknownOption","self.renderUnknownOption","unknownVal","removeUnknownOption","self.removeUnknownOption","self.readValue","self.writeValue","hasOption","addOption","self.addOption","removeOption","self.removeOption","self.hasOption","self.registerOption","optionScope","optionAttrs","interpolateValueFn","interpolateTextFn","valueAttributeObserveAction","interpolateWatchAction","selectPreLink","ngModelCtrl.$render","lastView","lastViewRef","selectMultipleWatch","selectCtrlName","ctrl.$validators.required","patternExp","ctrl.$validators.pattern","intVal","ctrl.$validators.maxlength","ctrl.$validators.minlength","getDecimals","opt_precision","pow","ONE","OTHER","$$csp","head"]
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular/bower.json b/xos-apps/auto-scale/gui/src/vendor/angular/bower.json
new file mode 100644
index 0000000..766d984
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular/bower.json
@@ -0,0 +1,8 @@
+{
+ "name": "angular",
+ "version": "1.4.8",
+ "main": "./angular.js",
+ "ignore": [],
+ "dependencies": {
+ }
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular/index.js b/xos-apps/auto-scale/gui/src/vendor/angular/index.js
new file mode 100644
index 0000000..5c1aafc
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular/index.js
@@ -0,0 +1,2 @@
+require('./angular');
+module.exports = angular;
diff --git a/xos-apps/auto-scale/gui/src/vendor/angular/package.json b/xos-apps/auto-scale/gui/src/vendor/angular/package.json
new file mode 100644
index 0000000..09f440e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/angular/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "angular",
+ "version": "1.4.8",
+ "description": "HTML enhanced for web apps",
+ "main": "index.js",
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/angular/angular.js.git"
+ },
+ "keywords": [
+ "angular",
+ "framework",
+ "browser",
+ "client-side"
+ ],
+ "author": "Angular Core Team <angular-core+npm@google.com>",
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/angular/angular.js/issues"
+ },
+ "homepage": "http://angularjs.org"
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/.bower.json b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/.bower.json
new file mode 100644
index 0000000..2f8653c
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/.bower.json
@@ -0,0 +1,39 @@
+{
+ "name": "bootstrap-css",
+ "version": "3.3.4",
+ "keywords": [
+ "css",
+ "js",
+ "less",
+ "mobile-first",
+ "responsive",
+ "front-end",
+ "framework",
+ "web",
+ "bootstrap",
+ "twitter-bootstrap",
+ "bootstrap.js"
+ ],
+ "main": [
+ "css/bootstrap.min.css",
+ "js/bootstrap.min.js"
+ ],
+ "homepage": "http://getbootstrap.com/",
+ "author": {
+ "name": "Twitter Inc."
+ },
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/jozefizso/bower-bootstrap-css.git"
+ },
+ "license": "MIT",
+ "_release": "3.3.4",
+ "_resolution": {
+ "type": "version",
+ "tag": "3.3.4",
+ "commit": "01808188487a0806a8d68d2b5eaa346dca6f2ad7"
+ },
+ "_source": "git://github.com/jozefizso/bower-bootstrap-css.git",
+ "_target": "3.3.4",
+ "_originalSource": "bootstrap-css"
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/LICENSE b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/LICENSE
new file mode 100644
index 0000000..9858866
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2011-2015 Twitter, Inc
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/README.md b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/README.md
new file mode 100644
index 0000000..9da1527
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/README.md
@@ -0,0 +1,28 @@
+# Bootstrap
+
+
+This is a Bower component for [Bootstrap 3](http://getbootstrap.com/) CSS library (v3.3.4).
+
+## Installation:
+
+`bower install bootstrap-css`
+
+## Bootstrap 3.0 versions
+
+```
+bower install bootstrap-css#3.3.4
+bower install bootstrap-css#3.3.2
+bower install bootstrap-css#3.2.0
+bower install bootstrap-css#3.1.1
+bower install bootstrap-css#3.1.0
+bower install bootstrap-css#3.0.0
+```
+
+
+## Bootstrap 2.3 versions
+
+```
+bower install bootstrap-css#2.3.2
+bower install bootstrap-css#2.3.1
+bower install bootstrap-css#2.3.0
+```
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/bower.json b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/bower.json
new file mode 100644
index 0000000..c931530
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/bower.json
@@ -0,0 +1,30 @@
+{
+ "name": "bootstrap-css",
+ "version": "3.3.4",
+ "keywords": [
+ "css",
+ "js",
+ "less",
+ "mobile-first",
+ "responsive",
+ "front-end",
+ "framework",
+ "web",
+ "bootstrap",
+ "twitter-bootstrap",
+ "bootstrap.js"
+ ],
+ "main": [
+ "css/bootstrap.min.css",
+ "js/bootstrap.min.js"
+ ],
+ "homepage": "http://getbootstrap.com/",
+ "author": {
+ "name": "Twitter Inc."
+ },
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/jozefizso/bower-bootstrap-css.git"
+ },
+ "license": "MIT"
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap-theme.css b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap-theme.css
new file mode 100644
index 0000000..b0fdfcb
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap-theme.css
@@ -0,0 +1,476 @@
+/*!
+ * Bootstrap v3.3.4 (http://getbootstrap.com)
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ */
+
+.btn-default,
+.btn-primary,
+.btn-success,
+.btn-info,
+.btn-warning,
+.btn-danger {
+ text-shadow: 0 -1px 0 rgba(0, 0, 0, .2);
+ -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 1px rgba(0, 0, 0, .075);
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 1px rgba(0, 0, 0, .075);
+}
+.btn-default:active,
+.btn-primary:active,
+.btn-success:active,
+.btn-info:active,
+.btn-warning:active,
+.btn-danger:active,
+.btn-default.active,
+.btn-primary.active,
+.btn-success.active,
+.btn-info.active,
+.btn-warning.active,
+.btn-danger.active {
+ -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+ box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+}
+.btn-default .badge,
+.btn-primary .badge,
+.btn-success .badge,
+.btn-info .badge,
+.btn-warning .badge,
+.btn-danger .badge {
+ text-shadow: none;
+}
+.btn:active,
+.btn.active {
+ background-image: none;
+}
+.btn-default {
+ text-shadow: 0 1px 0 #fff;
+ background-image: -webkit-linear-gradient(top, #fff 0%, #e0e0e0 100%);
+ background-image: -o-linear-gradient(top, #fff 0%, #e0e0e0 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#e0e0e0));
+ background-image: linear-gradient(to bottom, #fff 0%, #e0e0e0 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe0e0e0', GradientType=0);
+ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
+ background-repeat: repeat-x;
+ border-color: #dbdbdb;
+ border-color: #ccc;
+}
+.btn-default:hover,
+.btn-default:focus {
+ background-color: #e0e0e0;
+ background-position: 0 -15px;
+}
+.btn-default:active,
+.btn-default.active {
+ background-color: #e0e0e0;
+ border-color: #dbdbdb;
+}
+.btn-default.disabled,
+.btn-default:disabled,
+.btn-default[disabled] {
+ background-color: #e0e0e0;
+ background-image: none;
+}
+.btn-primary {
+ background-image: -webkit-linear-gradient(top, #337ab7 0%, #265a88 100%);
+ background-image: -o-linear-gradient(top, #337ab7 0%, #265a88 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#265a88));
+ background-image: linear-gradient(to bottom, #337ab7 0%, #265a88 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff265a88', GradientType=0);
+ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
+ background-repeat: repeat-x;
+ border-color: #245580;
+}
+.btn-primary:hover,
+.btn-primary:focus {
+ background-color: #265a88;
+ background-position: 0 -15px;
+}
+.btn-primary:active,
+.btn-primary.active {
+ background-color: #265a88;
+ border-color: #245580;
+}
+.btn-primary.disabled,
+.btn-primary:disabled,
+.btn-primary[disabled] {
+ background-color: #265a88;
+ background-image: none;
+}
+.btn-success {
+ background-image: -webkit-linear-gradient(top, #5cb85c 0%, #419641 100%);
+ background-image: -o-linear-gradient(top, #5cb85c 0%, #419641 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#5cb85c), to(#419641));
+ background-image: linear-gradient(to bottom, #5cb85c 0%, #419641 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff419641', GradientType=0);
+ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
+ background-repeat: repeat-x;
+ border-color: #3e8f3e;
+}
+.btn-success:hover,
+.btn-success:focus {
+ background-color: #419641;
+ background-position: 0 -15px;
+}
+.btn-success:active,
+.btn-success.active {
+ background-color: #419641;
+ border-color: #3e8f3e;
+}
+.btn-success.disabled,
+.btn-success:disabled,
+.btn-success[disabled] {
+ background-color: #419641;
+ background-image: none;
+}
+.btn-info {
+ background-image: -webkit-linear-gradient(top, #5bc0de 0%, #2aabd2 100%);
+ background-image: -o-linear-gradient(top, #5bc0de 0%, #2aabd2 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#5bc0de), to(#2aabd2));
+ background-image: linear-gradient(to bottom, #5bc0de 0%, #2aabd2 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2aabd2', GradientType=0);
+ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
+ background-repeat: repeat-x;
+ border-color: #28a4c9;
+}
+.btn-info:hover,
+.btn-info:focus {
+ background-color: #2aabd2;
+ background-position: 0 -15px;
+}
+.btn-info:active,
+.btn-info.active {
+ background-color: #2aabd2;
+ border-color: #28a4c9;
+}
+.btn-info.disabled,
+.btn-info:disabled,
+.btn-info[disabled] {
+ background-color: #2aabd2;
+ background-image: none;
+}
+.btn-warning {
+ background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #eb9316 100%);
+ background-image: -o-linear-gradient(top, #f0ad4e 0%, #eb9316 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#f0ad4e), to(#eb9316));
+ background-image: linear-gradient(to bottom, #f0ad4e 0%, #eb9316 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffeb9316', GradientType=0);
+ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
+ background-repeat: repeat-x;
+ border-color: #e38d13;
+}
+.btn-warning:hover,
+.btn-warning:focus {
+ background-color: #eb9316;
+ background-position: 0 -15px;
+}
+.btn-warning:active,
+.btn-warning.active {
+ background-color: #eb9316;
+ border-color: #e38d13;
+}
+.btn-warning.disabled,
+.btn-warning:disabled,
+.btn-warning[disabled] {
+ background-color: #eb9316;
+ background-image: none;
+}
+.btn-danger {
+ background-image: -webkit-linear-gradient(top, #d9534f 0%, #c12e2a 100%);
+ background-image: -o-linear-gradient(top, #d9534f 0%, #c12e2a 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#d9534f), to(#c12e2a));
+ background-image: linear-gradient(to bottom, #d9534f 0%, #c12e2a 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc12e2a', GradientType=0);
+ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
+ background-repeat: repeat-x;
+ border-color: #b92c28;
+}
+.btn-danger:hover,
+.btn-danger:focus {
+ background-color: #c12e2a;
+ background-position: 0 -15px;
+}
+.btn-danger:active,
+.btn-danger.active {
+ background-color: #c12e2a;
+ border-color: #b92c28;
+}
+.btn-danger.disabled,
+.btn-danger:disabled,
+.btn-danger[disabled] {
+ background-color: #c12e2a;
+ background-image: none;
+}
+.thumbnail,
+.img-thumbnail {
+ -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .075);
+ box-shadow: 0 1px 2px rgba(0, 0, 0, .075);
+}
+.dropdown-menu > li > a:hover,
+.dropdown-menu > li > a:focus {
+ background-color: #e8e8e8;
+ background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
+ background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#e8e8e8));
+ background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);
+ background-repeat: repeat-x;
+}
+.dropdown-menu > .active > a,
+.dropdown-menu > .active > a:hover,
+.dropdown-menu > .active > a:focus {
+ background-color: #2e6da4;
+ background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%);
+ background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4));
+ background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);
+ background-repeat: repeat-x;
+}
+.navbar-default {
+ background-image: -webkit-linear-gradient(top, #fff 0%, #f8f8f8 100%);
+ background-image: -o-linear-gradient(top, #fff 0%, #f8f8f8 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#f8f8f8));
+ background-image: linear-gradient(to bottom, #fff 0%, #f8f8f8 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff8f8f8', GradientType=0);
+ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
+ background-repeat: repeat-x;
+ border-radius: 4px;
+ -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 5px rgba(0, 0, 0, .075);
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 5px rgba(0, 0, 0, .075);
+}
+.navbar-default .navbar-nav > .open > a,
+.navbar-default .navbar-nav > .active > a {
+ background-image: -webkit-linear-gradient(top, #dbdbdb 0%, #e2e2e2 100%);
+ background-image: -o-linear-gradient(top, #dbdbdb 0%, #e2e2e2 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#dbdbdb), to(#e2e2e2));
+ background-image: linear-gradient(to bottom, #dbdbdb 0%, #e2e2e2 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdbdbdb', endColorstr='#ffe2e2e2', GradientType=0);
+ background-repeat: repeat-x;
+ -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, .075);
+ box-shadow: inset 0 3px 9px rgba(0, 0, 0, .075);
+}
+.navbar-brand,
+.navbar-nav > li > a {
+ text-shadow: 0 1px 0 rgba(255, 255, 255, .25);
+}
+.navbar-inverse {
+ background-image: -webkit-linear-gradient(top, #3c3c3c 0%, #222 100%);
+ background-image: -o-linear-gradient(top, #3c3c3c 0%, #222 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#3c3c3c), to(#222));
+ background-image: linear-gradient(to bottom, #3c3c3c 0%, #222 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c', endColorstr='#ff222222', GradientType=0);
+ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
+ background-repeat: repeat-x;
+}
+.navbar-inverse .navbar-nav > .open > a,
+.navbar-inverse .navbar-nav > .active > a {
+ background-image: -webkit-linear-gradient(top, #080808 0%, #0f0f0f 100%);
+ background-image: -o-linear-gradient(top, #080808 0%, #0f0f0f 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#080808), to(#0f0f0f));
+ background-image: linear-gradient(to bottom, #080808 0%, #0f0f0f 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff080808', endColorstr='#ff0f0f0f', GradientType=0);
+ background-repeat: repeat-x;
+ -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, .25);
+ box-shadow: inset 0 3px 9px rgba(0, 0, 0, .25);
+}
+.navbar-inverse .navbar-brand,
+.navbar-inverse .navbar-nav > li > a {
+ text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
+}
+.navbar-static-top,
+.navbar-fixed-top,
+.navbar-fixed-bottom {
+ border-radius: 0;
+}
+@media (max-width: 767px) {
+ .navbar .navbar-nav .open .dropdown-menu > .active > a,
+ .navbar .navbar-nav .open .dropdown-menu > .active > a:hover,
+ .navbar .navbar-nav .open .dropdown-menu > .active > a:focus {
+ color: #fff;
+ background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%);
+ background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4));
+ background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);
+ background-repeat: repeat-x;
+ }
+}
+.alert {
+ text-shadow: 0 1px 0 rgba(255, 255, 255, .2);
+ -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), 0 1px 2px rgba(0, 0, 0, .05);
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), 0 1px 2px rgba(0, 0, 0, .05);
+}
+.alert-success {
+ background-image: -webkit-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%);
+ background-image: -o-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#dff0d8), to(#c8e5bc));
+ background-image: linear-gradient(to bottom, #dff0d8 0%, #c8e5bc 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0);
+ background-repeat: repeat-x;
+ border-color: #b2dba1;
+}
+.alert-info {
+ background-image: -webkit-linear-gradient(top, #d9edf7 0%, #b9def0 100%);
+ background-image: -o-linear-gradient(top, #d9edf7 0%, #b9def0 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#d9edf7), to(#b9def0));
+ background-image: linear-gradient(to bottom, #d9edf7 0%, #b9def0 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffb9def0', GradientType=0);
+ background-repeat: repeat-x;
+ border-color: #9acfea;
+}
+.alert-warning {
+ background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%);
+ background-image: -o-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#fcf8e3), to(#f8efc0));
+ background-image: linear-gradient(to bottom, #fcf8e3 0%, #f8efc0 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fff8efc0', GradientType=0);
+ background-repeat: repeat-x;
+ border-color: #f5e79e;
+}
+.alert-danger {
+ background-image: -webkit-linear-gradient(top, #f2dede 0%, #e7c3c3 100%);
+ background-image: -o-linear-gradient(top, #f2dede 0%, #e7c3c3 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#f2dede), to(#e7c3c3));
+ background-image: linear-gradient(to bottom, #f2dede 0%, #e7c3c3 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffe7c3c3', GradientType=0);
+ background-repeat: repeat-x;
+ border-color: #dca7a7;
+}
+.progress {
+ background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%);
+ background-image: -o-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#ebebeb), to(#f5f5f5));
+ background-image: linear-gradient(to bottom, #ebebeb 0%, #f5f5f5 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0);
+ background-repeat: repeat-x;
+}
+.progress-bar {
+ background-image: -webkit-linear-gradient(top, #337ab7 0%, #286090 100%);
+ background-image: -o-linear-gradient(top, #337ab7 0%, #286090 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#286090));
+ background-image: linear-gradient(to bottom, #337ab7 0%, #286090 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff286090', GradientType=0);
+ background-repeat: repeat-x;
+}
+.progress-bar-success {
+ background-image: -webkit-linear-gradient(top, #5cb85c 0%, #449d44 100%);
+ background-image: -o-linear-gradient(top, #5cb85c 0%, #449d44 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#5cb85c), to(#449d44));
+ background-image: linear-gradient(to bottom, #5cb85c 0%, #449d44 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0);
+ background-repeat: repeat-x;
+}
+.progress-bar-info {
+ background-image: -webkit-linear-gradient(top, #5bc0de 0%, #31b0d5 100%);
+ background-image: -o-linear-gradient(top, #5bc0de 0%, #31b0d5 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#5bc0de), to(#31b0d5));
+ background-image: linear-gradient(to bottom, #5bc0de 0%, #31b0d5 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0);
+ background-repeat: repeat-x;
+}
+.progress-bar-warning {
+ background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #ec971f 100%);
+ background-image: -o-linear-gradient(top, #f0ad4e 0%, #ec971f 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#f0ad4e), to(#ec971f));
+ background-image: linear-gradient(to bottom, #f0ad4e 0%, #ec971f 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0);
+ background-repeat: repeat-x;
+}
+.progress-bar-danger {
+ background-image: -webkit-linear-gradient(top, #d9534f 0%, #c9302c 100%);
+ background-image: -o-linear-gradient(top, #d9534f 0%, #c9302c 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#d9534f), to(#c9302c));
+ background-image: linear-gradient(to bottom, #d9534f 0%, #c9302c 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0);
+ background-repeat: repeat-x;
+}
+.progress-bar-striped {
+ background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+}
+.list-group {
+ border-radius: 4px;
+ -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .075);
+ box-shadow: 0 1px 2px rgba(0, 0, 0, .075);
+}
+.list-group-item.active,
+.list-group-item.active:hover,
+.list-group-item.active:focus {
+ text-shadow: 0 -1px 0 #286090;
+ background-image: -webkit-linear-gradient(top, #337ab7 0%, #2b669a 100%);
+ background-image: -o-linear-gradient(top, #337ab7 0%, #2b669a 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2b669a));
+ background-image: linear-gradient(to bottom, #337ab7 0%, #2b669a 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2b669a', GradientType=0);
+ background-repeat: repeat-x;
+ border-color: #2b669a;
+}
+.list-group-item.active .badge,
+.list-group-item.active:hover .badge,
+.list-group-item.active:focus .badge {
+ text-shadow: none;
+}
+.panel {
+ -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .05);
+ box-shadow: 0 1px 2px rgba(0, 0, 0, .05);
+}
+.panel-default > .panel-heading {
+ background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
+ background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#e8e8e8));
+ background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);
+ background-repeat: repeat-x;
+}
+.panel-primary > .panel-heading {
+ background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%);
+ background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4));
+ background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);
+ background-repeat: repeat-x;
+}
+.panel-success > .panel-heading {
+ background-image: -webkit-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%);
+ background-image: -o-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#dff0d8), to(#d0e9c6));
+ background-image: linear-gradient(to bottom, #dff0d8 0%, #d0e9c6 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffd0e9c6', GradientType=0);
+ background-repeat: repeat-x;
+}
+.panel-info > .panel-heading {
+ background-image: -webkit-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%);
+ background-image: -o-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#d9edf7), to(#c4e3f3));
+ background-image: linear-gradient(to bottom, #d9edf7 0%, #c4e3f3 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffc4e3f3', GradientType=0);
+ background-repeat: repeat-x;
+}
+.panel-warning > .panel-heading {
+ background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%);
+ background-image: -o-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#fcf8e3), to(#faf2cc));
+ background-image: linear-gradient(to bottom, #fcf8e3 0%, #faf2cc 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fffaf2cc', GradientType=0);
+ background-repeat: repeat-x;
+}
+.panel-danger > .panel-heading {
+ background-image: -webkit-linear-gradient(top, #f2dede 0%, #ebcccc 100%);
+ background-image: -o-linear-gradient(top, #f2dede 0%, #ebcccc 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#f2dede), to(#ebcccc));
+ background-image: linear-gradient(to bottom, #f2dede 0%, #ebcccc 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffebcccc', GradientType=0);
+ background-repeat: repeat-x;
+}
+.well {
+ background-image: -webkit-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%);
+ background-image: -o-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%);
+ background-image: -webkit-gradient(linear, left top, left bottom, from(#e8e8e8), to(#f5f5f5));
+ background-image: linear-gradient(to bottom, #e8e8e8 0%, #f5f5f5 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8', endColorstr='#fff5f5f5', GradientType=0);
+ background-repeat: repeat-x;
+ border-color: #dcdcdc;
+ -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, .05), 0 1px 0 rgba(255, 255, 255, .1);
+ box-shadow: inset 0 1px 3px rgba(0, 0, 0, .05), 0 1px 0 rgba(255, 255, 255, .1);
+}
+/*# sourceMappingURL=bootstrap-theme.css.map */
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap-theme.css.map b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap-theme.css.map
new file mode 100644
index 0000000..5a12d63
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap-theme.css.map
@@ -0,0 +1 @@
+{"version":3,"sources":["less/theme.less","less/mixins/vendor-prefixes.less","bootstrap-theme.css","less/mixins/gradients.less","less/mixins/reset-filter.less"],"names":[],"mappings":"AAcA;;;;;;EAME,0CAAA;ECgDA,6FAAA;EACQ,qFAAA;EC5DT;AFgBC;;;;;;;;;;;;EC2CA,0DAAA;EACQ,kDAAA;EC7CT;AFVD;;;;;;EAiBI,mBAAA;EECH;AFiCC;;EAEE,wBAAA;EE/BH;AFoCD;EGnDI,0EAAA;EACA,qEAAA;EACA,+FAAA;EAAA,wEAAA;EAEA,wHAAA;ECnBF,qEAAA;EJiCA,6BAAA;EACA,uBAAA;EAgC2C,2BAAA;EAA2B,oBAAA;EEzBvE;AFLC;;EAEE,2BAAA;EACA,8BAAA;EEOH;AFJC;;EAEE,2BAAA;EACA,uBAAA;EEMH;AFHC;;;EAGE,2BAAA;EACA,wBAAA;EEKH;AFUD;EGpDI,0EAAA;EACA,qEAAA;EACA,+FAAA;EAAA,wEAAA;EAEA,wHAAA;ECnBF,qEAAA;EJiCA,6BAAA;EACA,uBAAA;EEgCD;AF9BC;;EAEE,2BAAA;EACA,8BAAA;EEgCH;AF7BC;;EAEE,2BAAA;EACA,uBAAA;EE+BH;AF5BC;;;EAGE,2BAAA;EACA,wBAAA;EE8BH;AFdD;EGrDI,0EAAA;EACA,qEAAA;EACA,+FAAA;EAAA,wEAAA;EAEA,wHAAA;ECnBF,qEAAA;EJiCA,6BAAA;EACA,uBAAA;EEyDD;AFvDC;;EAEE,2BAAA;EACA,8BAAA;EEyDH;AFtDC;;EAEE,2BAAA;EACA,uBAAA;EEwDH;AFrDC;;;EAGE,2BAAA;EACA,wBAAA;EEuDH;AFtCD;EGtDI,0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A;EACA,6BAAA;EACA,wHAAA;ED4TH;AFpID;EG5LI,0EAAA;EACA,qEAAA;EACA,+FAAA;EAAA,wEAAA;EACA,6BAAA;EACA,wHAAA;EDmUH;AF1ID;EG7LI,0EAAA;EACA,qEAAA;EACA,+FAAA;EAAA,wEAAA;EACA,6BAAA;EACA,wHAAA;ED0UH;AF7ID;EGhKI,+MAAA;EACA,0MAAA;EACA,uMAAA;EDgTH;AFzID;EACE,oBAAA;EC5JA,oDAAA;EACQ,4CAAA;ECwST;AF1ID;;;EAGE,+BAAA;EGjNE,0EAAA;EACA,qEAAA;EACA,+FAAA;EAAA,wEAAA;EACA,6BAAA;EACA,wHAAA;EH+MF,uBAAA;EEgJD;AFrJD;;;EAQI,mBAAA;EEkJH;AFxID;ECjLE,mDAAA;EACQ,2CAAA;EC4TT;AFlID;EG1OI,0EAAA;EACA,qEAAA;EACA,+FAAA;EAAA,wEAAA;EACA,6BAAA;EACA,wHAAA;ED+WH;AFxID;EG3OI,0EAAA;EACA,qEAAA;EACA,+FAAA;EAAA,wEAAA;EACA,6BAAA;EACA,wHAAA;EDsXH;AF9ID;EG5OI,0EAAA;EACA,qEAAA;EACA,+FAAA;EAAA,wEAAA;EACA,6BAAA;EACA,wHAAA;ED6XH;AFpJD;EG7OI,0EAAA;EACA,qEAAA;EACA,+FAAA;EAAA,wEAAA;EACA,6BAAA;EACA,wHAAA;EDoYH;AF1JD;EG9OI,0EAAA;EACA,qEAAA;EACA,+FAAA;EAAA,wEAAA;EACA,6BAAA;EACA,wHAAA;ED2YH;AFhKD;EG/OI,0EAAA;EACA,qEAAA;EACA,+FAAA;EAAA,wEAAA;EACA,6BAAA;EACA,wHAAA;EDkZH;AFhKD;EGtPI,0EAAA;EACA,qEAAA;EACA,+FAAA;EAAA,wEAAA;EACA,6BAAA;EACA,wHAAA;EHoPF,uBAAA;ECzMA,2FAAA;EACQ,mFAAA;ECgXT","file":"bootstrap-theme.css","sourcesContent":["\n//\n// Load core variables and mixins\n// --------------------------------------------------\n\n@import \"variables.less\";\n@import \"mixins.less\";\n\n\n//\n// Buttons\n// --------------------------------------------------\n\n// Common styles\n.btn-default,\n.btn-primary,\n.btn-success,\n.btn-info,\n.btn-warning,\n.btn-danger {\n text-shadow: 0 -1px 0 rgba(0,0,0,.2);\n @shadow: inset 0 1px 0 rgba(255,255,255,.15), 0 1px 1px rgba(0,0,0,.075);\n .box-shadow(@shadow);\n\n // Reset the shadow\n &:active,\n &.active {\n .box-shadow(inset 0 3px 5px rgba(0,0,0,.125));\n }\n\n .badge {\n text-shadow: none;\n }\n}\n\n// Mixin for generating new styles\n.btn-styles(@btn-color: #555) {\n #gradient > .vertical(@start-color: @btn-color; @end-color: darken(@btn-color, 12%));\n .reset-filter(); // Disable gradients for IE9 because filter bleeds through rounded corners; see https://github.com/twbs/bootstrap/issues/10620\n background-repeat: repeat-x;\n border-color: darken(@btn-color, 14%);\n\n &:hover,\n &:focus {\n background-color: darken(@btn-color, 12%);\n background-position: 0 -15px;\n }\n\n &:active,\n &.active {\n background-color: darken(@btn-color, 12%);\n border-color: darken(@btn-color, 14%);\n }\n\n &.disabled,\n &:disabled,\n &[disabled] {\n background-color: darken(@btn-color, 12%);\n background-image: none;\n }\n}\n\n// Common styles\n.btn {\n // Remove the gradient for the pressed/active state\n &:active,\n &.active {\n background-image: none;\n }\n}\n\n// Apply the mixin to the buttons\n.btn-default { .btn-styles(@btn-default-bg); text-shadow: 0 1px 0 #fff; border-color: #ccc; }\n.btn-primary { .btn-styles(@btn-primary-bg); }\n.btn-success { .btn-styles(@btn-success-bg); }\n.btn-info { .btn-styles(@btn-info-bg); }\n.btn-warning { .btn-styles(@btn-warning-bg); }\n.btn-danger { .btn-styles(@btn-danger-bg); }\n\n\n//\n// Images\n// --------------------------------------------------\n\n.thumbnail,\n.img-thumbnail {\n .box-shadow(0 1px 2px rgba(0,0,0,.075));\n}\n\n\n//\n// Dropdowns\n// --------------------------------------------------\n\n.dropdown-menu > li > a:hover,\n.dropdown-menu > li > a:focus {\n #gradient > .vertical(@start-color: @dropdown-link-hover-bg; @end-color: darken(@dropdown-link-hover-bg, 5%));\n background-color: darken(@dropdown-link-hover-bg, 5%);\n}\n.dropdown-menu > .active > a,\n.dropdown-menu > .active > a:hover,\n.dropdown-menu > .active > a:focus {\n #gradient > .vertical(@start-color: @dropdown-link-active-bg; @end-color: darken(@dropdown-link-active-bg, 5%));\n background-color: darken(@dropdown-link-active-bg, 5%);\n}\n\n\n//\n// Navbar\n// --------------------------------------------------\n\n// Default navbar\n.navbar-default {\n #gradient > .vertical(@start-color: lighten(@navbar-default-bg, 10%); @end-color: @navbar-default-bg);\n .reset-filter(); // Remove gradient in IE<10 to fix bug where dropdowns don't get triggered\n border-radius: @navbar-border-radius;\n @shadow: inset 0 1px 0 rgba(255,255,255,.15), 0 1px 5px rgba(0,0,0,.075);\n .box-shadow(@shadow);\n\n .navbar-nav > .open > a,\n .navbar-nav > .active > a {\n #gradient > .vertical(@start-color: darken(@navbar-default-link-active-bg, 5%); @end-color: darken(@navbar-default-link-active-bg, 2%));\n .box-shadow(inset 0 3px 9px rgba(0,0,0,.075));\n }\n}\n.navbar-brand,\n.navbar-nav > li > a {\n text-shadow: 0 1px 0 rgba(255,255,255,.25);\n}\n\n// Inverted navbar\n.navbar-inverse {\n #gradient > .vertical(@start-color: lighten(@navbar-inverse-bg, 10%); @end-color: @navbar-inverse-bg);\n .reset-filter(); // Remove gradient in IE<10 to fix bug where dropdowns don't get triggered; see https://github.com/twbs/bootstrap/issues/10257\n\n .navbar-nav > .open > a,\n .navbar-nav > .active > a {\n #gradient > .vertical(@start-color: @navbar-inverse-link-active-bg; @end-color: lighten(@navbar-inverse-link-active-bg, 2.5%));\n .box-shadow(inset 0 3px 9px rgba(0,0,0,.25));\n }\n\n .navbar-brand,\n .navbar-nav > li > a {\n text-shadow: 0 -1px 0 rgba(0,0,0,.25);\n }\n}\n\n// Undo rounded corners in static and fixed navbars\n.navbar-static-top,\n.navbar-fixed-top,\n.navbar-fixed-bottom {\n border-radius: 0;\n}\n\n// Fix active state of dropdown items in collapsed mode\n@media (max-width: @grid-float-breakpoint-max) {\n .navbar .navbar-nav .open .dropdown-menu > .active > a {\n &,\n &:hover,\n &:focus {\n color: #fff;\n #gradient > .vertical(@start-color: @dropdown-link-active-bg; @end-color: darken(@dropdown-link-active-bg, 5%));\n }\n }\n}\n\n\n//\n// Alerts\n// --------------------------------------------------\n\n// Common styles\n.alert {\n text-shadow: 0 1px 0 rgba(255,255,255,.2);\n @shadow: inset 0 1px 0 rgba(255,255,255,.25), 0 1px 2px rgba(0,0,0,.05);\n .box-shadow(@shadow);\n}\n\n// Mixin for generating new styles\n.alert-styles(@color) {\n #gradient > .vertical(@start-color: @color; @end-color: darken(@color, 7.5%));\n border-color: darken(@color, 15%);\n}\n\n// Apply the mixin to the alerts\n.alert-success { .alert-styles(@alert-success-bg); }\n.alert-info { .alert-styles(@alert-info-bg); }\n.alert-warning { .alert-styles(@alert-warning-bg); }\n.alert-danger { .alert-styles(@alert-danger-bg); }\n\n\n//\n// Progress bars\n// --------------------------------------------------\n\n// Give the progress background some depth\n.progress {\n #gradient > .vertical(@start-color: darken(@progress-bg, 4%); @end-color: @progress-bg)\n}\n\n// Mixin for generating new styles\n.progress-bar-styles(@color) {\n #gradient > .vertical(@start-color: @color; @end-color: darken(@color, 10%));\n}\n\n// Apply the mixin to the progress bars\n.progress-bar { .progress-bar-styles(@progress-bar-bg); }\n.progress-bar-success { .progress-bar-styles(@progress-bar-success-bg); }\n.progress-bar-info { .progress-bar-styles(@progress-bar-info-bg); }\n.progress-bar-warning { .progress-bar-styles(@progress-bar-warning-bg); }\n.progress-bar-danger { .progress-bar-styles(@progress-bar-danger-bg); }\n\n// Reset the striped class because our mixins don't do multiple gradients and\n// the above custom styles override the new `.progress-bar-striped` in v3.2.0.\n.progress-bar-striped {\n #gradient > .striped();\n}\n\n\n//\n// List groups\n// --------------------------------------------------\n\n.list-group {\n border-radius: @border-radius-base;\n .box-shadow(0 1px 2px rgba(0,0,0,.075));\n}\n.list-group-item.active,\n.list-group-item.active:hover,\n.list-group-item.active:focus {\n text-shadow: 0 -1px 0 darken(@list-group-active-bg, 10%);\n #gradient > .vertical(@start-color: @list-group-active-bg; @end-color: darken(@list-group-active-bg, 7.5%));\n border-color: darken(@list-group-active-border, 7.5%);\n\n .badge {\n text-shadow: none;\n }\n}\n\n\n//\n// Panels\n// --------------------------------------------------\n\n// Common styles\n.panel {\n .box-shadow(0 1px 2px rgba(0,0,0,.05));\n}\n\n// Mixin for generating new styles\n.panel-heading-styles(@color) {\n #gradient > .vertical(@start-color: @color; @end-color: darken(@color, 5%));\n}\n\n// Apply the mixin to the panel headings only\n.panel-default > .panel-heading { .panel-heading-styles(@panel-default-heading-bg); }\n.panel-primary > .panel-heading { .panel-heading-styles(@panel-primary-heading-bg); }\n.panel-success > .panel-heading { .panel-heading-styles(@panel-success-heading-bg); }\n.panel-info > .panel-heading { .panel-heading-styles(@panel-info-heading-bg); }\n.panel-warning > .panel-heading { .panel-heading-styles(@panel-warning-heading-bg); }\n.panel-danger > .panel-heading { .panel-heading-styles(@panel-danger-heading-bg); }\n\n\n//\n// Wells\n// --------------------------------------------------\n\n.well {\n #gradient > .vertical(@start-color: darken(@well-bg, 5%); @end-color: @well-bg);\n border-color: darken(@well-bg, 10%);\n @shadow: inset 0 1px 3px rgba(0,0,0,.05), 0 1px 0 rgba(255,255,255,.1);\n .box-shadow(@shadow);\n}\n","// Vendor Prefixes\n//\n// All vendor mixins are deprecated as of v3.2.0 due to the introduction of\n// Autoprefixer in our Gruntfile. They will be removed in v4.\n\n// - Animations\n// - Backface visibility\n// - Box shadow\n// - Box sizing\n// - Content columns\n// - Hyphens\n// - Placeholder text\n// - Transformations\n// - Transitions\n// - User Select\n\n\n// Animations\n.animation(@animation) {\n -webkit-animation: @animation;\n -o-animation: @animation;\n animation: @animation;\n}\n.animation-name(@name) {\n -webkit-animation-name: @name;\n animation-name: @name;\n}\n.animation-duration(@duration) {\n -webkit-animation-duration: @duration;\n animation-duration: @duration;\n}\n.animation-timing-function(@timing-function) {\n -webkit-animation-timing-function: @timing-function;\n animation-timing-function: @timing-function;\n}\n.animation-delay(@delay) {\n -webkit-animation-delay: @delay;\n animation-delay: @delay;\n}\n.animation-iteration-count(@iteration-count) {\n -webkit-animation-iteration-count: @iteration-count;\n animation-iteration-count: @iteration-count;\n}\n.animation-direction(@direction) {\n -webkit-animation-direction: @direction;\n animation-direction: @direction;\n}\n.animation-fill-mode(@fill-mode) {\n -webkit-animation-fill-mode: @fill-mode;\n animation-fill-mode: @fill-mode;\n}\n\n// Backface visibility\n// Prevent browsers from flickering when using CSS 3D transforms.\n// Default value is `visible`, but can be changed to `hidden`\n\n.backface-visibility(@visibility){\n -webkit-backface-visibility: @visibility;\n -moz-backface-visibility: @visibility;\n backface-visibility: @visibility;\n}\n\n// Drop shadows\n//\n// Note: Deprecated `.box-shadow()` as of v3.1.0 since all of Bootstrap's\n// supported browsers that have box shadow capabilities now support it.\n\n.box-shadow(@shadow) {\n -webkit-box-shadow: @shadow; // iOS <4.3 & Android <4.1\n box-shadow: @shadow;\n}\n\n// Box sizing\n.box-sizing(@boxmodel) {\n -webkit-box-sizing: @boxmodel;\n -moz-box-sizing: @boxmodel;\n box-sizing: @boxmodel;\n}\n\n// CSS3 Content Columns\n.content-columns(@column-count; @column-gap: @grid-gutter-width) {\n -webkit-column-count: @column-count;\n -moz-column-count: @column-count;\n column-count: @column-count;\n -webkit-column-gap: @column-gap;\n -moz-column-gap: @column-gap;\n column-gap: @column-gap;\n}\n\n// Optional hyphenation\n.hyphens(@mode: auto) {\n word-wrap: break-word;\n -webkit-hyphens: @mode;\n -moz-hyphens: @mode;\n -ms-hyphens: @mode; // IE10+\n -o-hyphens: @mode;\n hyphens: @mode;\n}\n\n// Placeholder text\n.placeholder(@color: @input-color-placeholder) {\n // Firefox\n &::-moz-placeholder {\n color: @color;\n opacity: 1; // Override Firefox's unusual default opacity; see https://github.com/twbs/bootstrap/pull/11526\n }\n &:-ms-input-placeholder { color: @color; } // Internet Explorer 10+\n &::-webkit-input-placeholder { color: @color; } // Safari and Chrome\n}\n\n// Transformations\n.scale(@ratio) {\n -webkit-transform: scale(@ratio);\n -ms-transform: scale(@ratio); // IE9 only\n -o-transform: scale(@ratio);\n transform: scale(@ratio);\n}\n.scale(@ratioX; @ratioY) {\n -webkit-transform: scale(@ratioX, @ratioY);\n -ms-transform: scale(@ratioX, @ratioY); // IE9 only\n -o-transform: scale(@ratioX, @ratioY);\n transform: scale(@ratioX, @ratioY);\n}\n.scaleX(@ratio) {\n -webkit-transform: scaleX(@ratio);\n -ms-transform: scaleX(@ratio); // IE9 only\n -o-transform: scaleX(@ratio);\n transform: scaleX(@ratio);\n}\n.scaleY(@ratio) {\n -webkit-transform: scaleY(@ratio);\n -ms-transform: scaleY(@ratio); // IE9 only\n -o-transform: scaleY(@ratio);\n transform: scaleY(@ratio);\n}\n.skew(@x; @y) {\n -webkit-transform: skewX(@x) skewY(@y);\n -ms-transform: skewX(@x) skewY(@y); // See https://github.com/twbs/bootstrap/issues/4885; IE9+\n -o-transform: skewX(@x) skewY(@y);\n transform: skewX(@x) skewY(@y);\n}\n.translate(@x; @y) {\n -webkit-transform: translate(@x, @y);\n -ms-transform: translate(@x, @y); // IE9 only\n -o-transform: translate(@x, @y);\n transform: translate(@x, @y);\n}\n.translate3d(@x; @y; @z) {\n -webkit-transform: translate3d(@x, @y, @z);\n transform: translate3d(@x, @y, @z);\n}\n.rotate(@degrees) {\n -webkit-transform: rotate(@degrees);\n -ms-transform: rotate(@degrees); // IE9 only\n -o-transform: rotate(@degrees);\n transform: rotate(@degrees);\n}\n.rotateX(@degrees) {\n -webkit-transform: rotateX(@degrees);\n -ms-transform: rotateX(@degrees); // IE9 only\n -o-transform: rotateX(@degrees);\n transform: rotateX(@degrees);\n}\n.rotateY(@degrees) {\n -webkit-transform: rotateY(@degrees);\n -ms-transform: rotateY(@degrees); // IE9 only\n -o-transform: rotateY(@degrees);\n transform: rotateY(@degrees);\n}\n.perspective(@perspective) {\n -webkit-perspective: @perspective;\n -moz-perspective: @perspective;\n perspective: @perspective;\n}\n.perspective-origin(@perspective) {\n -webkit-perspective-origin: @perspective;\n -moz-perspective-origin: @perspective;\n perspective-origin: @perspective;\n}\n.transform-origin(@origin) {\n -webkit-transform-origin: @origin;\n -moz-transform-origin: @origin;\n -ms-transform-origin: @origin; // IE9 only\n transform-origin: @origin;\n}\n\n\n// Transitions\n\n.transition(@transition) {\n -webkit-transition: @transition;\n -o-transition: @transition;\n transition: @transition;\n}\n.transition-property(@transition-property) {\n -webkit-transition-property: @transition-property;\n transition-property: @transition-property;\n}\n.transition-delay(@transition-delay) {\n -webkit-transition-delay: @transition-delay;\n transition-delay: @transition-delay;\n}\n.transition-duration(@transition-duration) {\n -webkit-transition-duration: @transition-duration;\n transition-duration: @transition-duration;\n}\n.transition-timing-function(@timing-function) {\n -webkit-transition-timing-function: @timing-function;\n transition-timing-function: @timing-function;\n}\n.transition-transform(@transition) {\n -webkit-transition: -webkit-transform @transition;\n -moz-transition: -moz-transform @transition;\n -o-transition: -o-transform @transition;\n transition: transform @transition;\n}\n\n\n// User select\n// For selecting text on the page\n\n.user-select(@select) {\n -webkit-user-select: @select;\n -moz-user-select: @select;\n -ms-user-select: @select; // IE10+\n user-select: @select;\n}\n",".btn-default,\n.btn-primary,\n.btn-success,\n.btn-info,\n.btn-warning,\n.btn-danger {\n text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2);\n -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075);\n box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075);\n}\n.btn-default:active,\n.btn-primary:active,\n.btn-success:active,\n.btn-info:active,\n.btn-warning:active,\n.btn-danger:active,\n.btn-default.active,\n.btn-primary.active,\n.btn-success.active,\n.btn-info.active,\n.btn-warning.active,\n.btn-danger.active {\n -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n}\n.btn-default .badge,\n.btn-primary .badge,\n.btn-success .badge,\n.btn-info .badge,\n.btn-warning .badge,\n.btn-danger .badge {\n text-shadow: none;\n}\n.btn:active,\n.btn.active {\n background-image: none;\n}\n.btn-default {\n background-image: -webkit-linear-gradient(top, #ffffff 0%, #e0e0e0 100%);\n background-image: -o-linear-gradient(top, #ffffff 0%, #e0e0e0 100%);\n background-image: linear-gradient(to bottom, #ffffff 0%, #e0e0e0 100%);\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe0e0e0', GradientType=0);\n filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);\n background-repeat: repeat-x;\n border-color: #dbdbdb;\n text-shadow: 0 1px 0 #fff;\n border-color: #ccc;\n}\n.btn-default:hover,\n.btn-default:focus {\n background-color: #e0e0e0;\n background-position: 0 -15px;\n}\n.btn-default:active,\n.btn-default.active {\n background-color: #e0e0e0;\n border-color: #dbdbdb;\n}\n.btn-default.disabled,\n.btn-default:disabled,\n.btn-default[disabled] {\n background-color: #e0e0e0;\n background-image: none;\n}\n.btn-primary {\n background-image: -webkit-linear-gradient(top, #337ab7 0%, #265a88 100%);\n background-image: -o-linear-gradient(top, #337ab7 0%, #265a88 100%);\n background-image: linear-gradient(to bottom, #337ab7 0%, #265a88 100%);\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff265a88', GradientType=0);\n filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);\n background-repeat: repeat-x;\n border-color: #245580;\n}\n.btn-primary:hover,\n.btn-primary:focus {\n background-color: #265a88;\n background-position: 0 -15px;\n}\n.btn-primary:active,\n.btn-primary.active {\n background-color: #265a88;\n border-color: #245580;\n}\n.btn-primary.disabled,\n.btn-primary:disabled,\n.btn-primary[disabled] {\n background-color: #265a88;\n background-image: none;\n}\n.btn-success {\n background-image: -webkit-linear-gradient(top, #5cb85c 0%, #419641 100%);\n background-image: -o-linear-gradient(top, #5cb85c 0%, #419641 100%);\n background-image: linear-gradient(to bottom, #5cb85c 0%, #419641 100%);\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff419641', GradientType=0);\n filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);\n background-repeat: repeat-x;\n border-color: #3e8f3e;\n}\n.btn-success:hover,\n.btn-success:focus {\n background-color: #419641;\n background-position: 0 -15px;\n}\n.btn-success:active,\n.btn-success.active {\n background-color: #419641;\n border-color: #3e8f3e;\n}\n.btn-success.disabled,\n.btn-success:disabled,\n.btn-success[disabled] {\n background-color: #419641;\n background-image: none;\n}\n.btn-info {\n background-image: -webkit-linear-gradient(top, #5bc0de 0%, #2aabd2 100%);\n background-image: -o-linear-gradient(top, #5bc0de 0%, #2aabd2 100%);\n background-image: linear-gradient(to bottom, #5bc0de 0%, #2aabd2 100%);\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2aabd2', GradientType=0);\n filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);\n background-repeat: repeat-x;\n border-color: #28a4c9;\n}\n.btn-info:hover,\n.btn-info:focus {\n background-color: #2aabd2;\n background-position: 0 -15px;\n}\n.btn-info:active,\n.btn-info.active {\n background-color: #2aabd2;\n border-color: #28a4c9;\n}\n.btn-info.disabled,\n.btn-info:disabled,\n.btn-info[disabled] {\n background-color: #2aabd2;\n background-image: none;\n}\n.btn-warning {\n background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #eb9316 100%);\n background-image: -o-linear-gradient(top, #f0ad4e 0%, #eb9316 100%);\n background-image: linear-gradient(to bottom, #f0ad4e 0%, #eb9316 100%);\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffeb9316', GradientType=0);\n filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);\n background-repeat: repeat-x;\n border-color: #e38d13;\n}\n.btn-warning:hover,\n.btn-warning:focus {\n background-color: #eb9316;\n background-position: 0 -15px;\n}\n.btn-warning:active,\n.btn-warning.active {\n background-color: #eb9316;\n border-color: #e38d13;\n}\n.btn-warning.disabled,\n.btn-warning:disabled,\n.btn-warning[disabled] {\n background-color: #eb9316;\n background-image: none;\n}\n.btn-danger {\n background-image: -webkit-linear-gradient(top, #d9534f 0%, #c12e2a 100%);\n background-image: -o-linear-gradient(top, #d9534f 0%, #c12e2a 100%);\n background-image: linear-gradient(to bottom, #d9534f 0%, #c12e2a 100%);\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc12e2a', GradientType=0);\n filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);\n background-repeat: repeat-x;\n border-color: #b92c28;\n}\n.btn-danger:hover,\n.btn-danger:focus {\n background-color: #c12e2a;\n background-position: 0 -15px;\n}\n.btn-danger:active,\n.btn-danger.active {\n background-color: #c12e2a;\n border-color: #b92c28;\n}\n.btn-danger.disabled,\n.btn-danger:disabled,\n.btn-danger[disabled] {\n background-color: #c12e2a;\n background-image: none;\n}\n.thumbnail,\n.img-thumbnail {\n -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);\n}\n.dropdown-menu > li > a:hover,\n.dropdown-menu > li > a:focus {\n background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);\n background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);\n background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);\n background-color: #e8e8e8;\n}\n.dropdown-menu > .active > a,\n.dropdown-menu > .active > a:hover,\n.dropdown-menu > .active > a:focus {\n background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%);\n background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%);\n background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);\n background-color: #2e6da4;\n}\n.navbar-default {\n background-image: -webkit-linear-gradient(top, #ffffff 0%, #f8f8f8 100%);\n background-image: -o-linear-gradient(top, #ffffff 0%, #f8f8f8 100%);\n background-image: linear-gradient(to bottom, #ffffff 0%, #f8f8f8 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff8f8f8', GradientType=0);\n filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);\n border-radius: 4px;\n -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.075);\n box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.075);\n}\n.navbar-default .navbar-nav > .open > a,\n.navbar-default .navbar-nav > .active > a {\n background-image: -webkit-linear-gradient(top, #dbdbdb 0%, #e2e2e2 100%);\n background-image: -o-linear-gradient(top, #dbdbdb 0%, #e2e2e2 100%);\n background-image: linear-gradient(to bottom, #dbdbdb 0%, #e2e2e2 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdbdbdb', endColorstr='#ffe2e2e2', GradientType=0);\n -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.075);\n box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.075);\n}\n.navbar-brand,\n.navbar-nav > li > a {\n text-shadow: 0 1px 0 rgba(255, 255, 255, 0.25);\n}\n.navbar-inverse {\n background-image: -webkit-linear-gradient(top, #3c3c3c 0%, #222222 100%);\n background-image: -o-linear-gradient(top, #3c3c3c 0%, #222222 100%);\n background-image: linear-gradient(to bottom, #3c3c3c 0%, #222222 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c', endColorstr='#ff222222', GradientType=0);\n filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);\n}\n.navbar-inverse .navbar-nav > .open > a,\n.navbar-inverse .navbar-nav > .active > a {\n background-image: -webkit-linear-gradient(top, #080808 0%, #0f0f0f 100%);\n background-image: -o-linear-gradient(top, #080808 0%, #0f0f0f 100%);\n background-image: linear-gradient(to bottom, #080808 0%, #0f0f0f 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff080808', endColorstr='#ff0f0f0f', GradientType=0);\n -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.25);\n box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.25);\n}\n.navbar-inverse .navbar-brand,\n.navbar-inverse .navbar-nav > li > a {\n text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);\n}\n.navbar-static-top,\n.navbar-fixed-top,\n.navbar-fixed-bottom {\n border-radius: 0;\n}\n@media (max-width: 767px) {\n .navbar .navbar-nav .open .dropdown-menu > .active > a,\n .navbar .navbar-nav .open .dropdown-menu > .active > a:hover,\n .navbar .navbar-nav .open .dropdown-menu > .active > a:focus {\n color: #fff;\n background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%);\n background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%);\n background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);\n }\n}\n.alert {\n text-shadow: 0 1px 0 rgba(255, 255, 255, 0.2);\n -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05);\n box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05);\n}\n.alert-success {\n background-image: -webkit-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%);\n background-image: -o-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%);\n background-image: linear-gradient(to bottom, #dff0d8 0%, #c8e5bc 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0);\n border-color: #b2dba1;\n}\n.alert-info {\n background-image: -webkit-linear-gradient(top, #d9edf7 0%, #b9def0 100%);\n background-image: -o-linear-gradient(top, #d9edf7 0%, #b9def0 100%);\n background-image: linear-gradient(to bottom, #d9edf7 0%, #b9def0 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffb9def0', GradientType=0);\n border-color: #9acfea;\n}\n.alert-warning {\n background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%);\n background-image: -o-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%);\n background-image: linear-gradient(to bottom, #fcf8e3 0%, #f8efc0 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fff8efc0', GradientType=0);\n border-color: #f5e79e;\n}\n.alert-danger {\n background-image: -webkit-linear-gradient(top, #f2dede 0%, #e7c3c3 100%);\n background-image: -o-linear-gradient(top, #f2dede 0%, #e7c3c3 100%);\n background-image: linear-gradient(to bottom, #f2dede 0%, #e7c3c3 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffe7c3c3', GradientType=0);\n border-color: #dca7a7;\n}\n.progress {\n background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%);\n background-image: -o-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%);\n background-image: linear-gradient(to bottom, #ebebeb 0%, #f5f5f5 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0);\n}\n.progress-bar {\n background-image: -webkit-linear-gradient(top, #337ab7 0%, #286090 100%);\n background-image: -o-linear-gradient(top, #337ab7 0%, #286090 100%);\n background-image: linear-gradient(to bottom, #337ab7 0%, #286090 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff286090', GradientType=0);\n}\n.progress-bar-success {\n background-image: -webkit-linear-gradient(top, #5cb85c 0%, #449d44 100%);\n background-image: -o-linear-gradient(top, #5cb85c 0%, #449d44 100%);\n background-image: linear-gradient(to bottom, #5cb85c 0%, #449d44 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0);\n}\n.progress-bar-info {\n background-image: -webkit-linear-gradient(top, #5bc0de 0%, #31b0d5 100%);\n background-image: -o-linear-gradient(top, #5bc0de 0%, #31b0d5 100%);\n background-image: linear-gradient(to bottom, #5bc0de 0%, #31b0d5 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0);\n}\n.progress-bar-warning {\n background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #ec971f 100%);\n background-image: -o-linear-gradient(top, #f0ad4e 0%, #ec971f 100%);\n background-image: linear-gradient(to bottom, #f0ad4e 0%, #ec971f 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0);\n}\n.progress-bar-danger {\n background-image: -webkit-linear-gradient(top, #d9534f 0%, #c9302c 100%);\n background-image: -o-linear-gradient(top, #d9534f 0%, #c9302c 100%);\n background-image: linear-gradient(to bottom, #d9534f 0%, #c9302c 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0);\n}\n.progress-bar-striped {\n background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n}\n.list-group {\n border-radius: 4px;\n -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);\n}\n.list-group-item.active,\n.list-group-item.active:hover,\n.list-group-item.active:focus {\n text-shadow: 0 -1px 0 #286090;\n background-image: -webkit-linear-gradient(top, #337ab7 0%, #2b669a 100%);\n background-image: -o-linear-gradient(top, #337ab7 0%, #2b669a 100%);\n background-image: linear-gradient(to bottom, #337ab7 0%, #2b669a 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2b669a', GradientType=0);\n border-color: #2b669a;\n}\n.list-group-item.active .badge,\n.list-group-item.active:hover .badge,\n.list-group-item.active:focus .badge {\n text-shadow: none;\n}\n.panel {\n -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);\n}\n.panel-default > .panel-heading {\n background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);\n background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);\n background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);\n}\n.panel-primary > .panel-heading {\n background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%);\n background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%);\n background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);\n}\n.panel-success > .panel-heading {\n background-image: -webkit-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%);\n background-image: -o-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%);\n background-image: linear-gradient(to bottom, #dff0d8 0%, #d0e9c6 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffd0e9c6', GradientType=0);\n}\n.panel-info > .panel-heading {\n background-image: -webkit-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%);\n background-image: -o-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%);\n background-image: linear-gradient(to bottom, #d9edf7 0%, #c4e3f3 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffc4e3f3', GradientType=0);\n}\n.panel-warning > .panel-heading {\n background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%);\n background-image: -o-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%);\n background-image: linear-gradient(to bottom, #fcf8e3 0%, #faf2cc 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fffaf2cc', GradientType=0);\n}\n.panel-danger > .panel-heading {\n background-image: -webkit-linear-gradient(top, #f2dede 0%, #ebcccc 100%);\n background-image: -o-linear-gradient(top, #f2dede 0%, #ebcccc 100%);\n background-image: linear-gradient(to bottom, #f2dede 0%, #ebcccc 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffebcccc', GradientType=0);\n}\n.well {\n background-image: -webkit-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%);\n background-image: -o-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%);\n background-image: linear-gradient(to bottom, #e8e8e8 0%, #f5f5f5 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8', endColorstr='#fff5f5f5', GradientType=0);\n border-color: #dcdcdc;\n -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 0 rgba(255, 255, 255, 0.1);\n box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 0 rgba(255, 255, 255, 0.1);\n}\n/*# sourceMappingURL=bootstrap-theme.css.map */","// Gradients\n\n#gradient {\n\n // Horizontal gradient, from left to right\n //\n // Creates two color stops, start and end, by specifying a color and position for each color stop.\n // Color stops are not available in IE9 and below.\n .horizontal(@start-color: #555; @end-color: #333; @start-percent: 0%; @end-percent: 100%) {\n background-image: -webkit-linear-gradient(left, @start-color @start-percent, @end-color @end-percent); // Safari 5.1-6, Chrome 10+\n background-image: -o-linear-gradient(left, @start-color @start-percent, @end-color @end-percent); // Opera 12\n background-image: linear-gradient(to right, @start-color @start-percent, @end-color @end-percent); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+\n background-repeat: repeat-x;\n filter: e(%(\"progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)\",argb(@start-color),argb(@end-color))); // IE9 and down\n }\n\n // Vertical gradient, from top to bottom\n //\n // Creates two color stops, start and end, by specifying a color and position for each color stop.\n // Color stops are not available in IE9 and below.\n .vertical(@start-color: #555; @end-color: #333; @start-percent: 0%; @end-percent: 100%) {\n background-image: -webkit-linear-gradient(top, @start-color @start-percent, @end-color @end-percent); // Safari 5.1-6, Chrome 10+\n background-image: -o-linear-gradient(top, @start-color @start-percent, @end-color @end-percent); // Opera 12\n background-image: linear-gradient(to bottom, @start-color @start-percent, @end-color @end-percent); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+\n background-repeat: repeat-x;\n filter: e(%(\"progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)\",argb(@start-color),argb(@end-color))); // IE9 and down\n }\n\n .directional(@start-color: #555; @end-color: #333; @deg: 45deg) {\n background-repeat: repeat-x;\n background-image: -webkit-linear-gradient(@deg, @start-color, @end-color); // Safari 5.1-6, Chrome 10+\n background-image: -o-linear-gradient(@deg, @start-color, @end-color); // Opera 12\n background-image: linear-gradient(@deg, @start-color, @end-color); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+\n }\n .horizontal-three-colors(@start-color: #00b3ee; @mid-color: #7a43b6; @color-stop: 50%; @end-color: #c3325f) {\n background-image: -webkit-linear-gradient(left, @start-color, @mid-color @color-stop, @end-color);\n background-image: -o-linear-gradient(left, @start-color, @mid-color @color-stop, @end-color);\n background-image: linear-gradient(to right, @start-color, @mid-color @color-stop, @end-color);\n background-repeat: no-repeat;\n filter: e(%(\"progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)\",argb(@start-color),argb(@end-color))); // IE9 and down, gets no color-stop at all for proper fallback\n }\n .vertical-three-colors(@start-color: #00b3ee; @mid-color: #7a43b6; @color-stop: 50%; @end-color: #c3325f) {\n background-image: -webkit-linear-gradient(@start-color, @mid-color @color-stop, @end-color);\n background-image: -o-linear-gradient(@start-color, @mid-color @color-stop, @end-color);\n background-image: linear-gradient(@start-color, @mid-color @color-stop, @end-color);\n background-repeat: no-repeat;\n filter: e(%(\"progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)\",argb(@start-color),argb(@end-color))); // IE9 and down, gets no color-stop at all for proper fallback\n }\n .radial(@inner-color: #555; @outer-color: #333) {\n background-image: -webkit-radial-gradient(circle, @inner-color, @outer-color);\n background-image: radial-gradient(circle, @inner-color, @outer-color);\n background-repeat: no-repeat;\n }\n .striped(@color: rgba(255,255,255,.15); @angle: 45deg) {\n background-image: -webkit-linear-gradient(@angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent);\n background-image: -o-linear-gradient(@angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent);\n background-image: linear-gradient(@angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent);\n }\n}\n","// Reset filters for IE\n//\n// When you need to remove a gradient background, do not forget to use this to reset\n// the IE filter for IE9 and below.\n\n.reset-filter() {\n filter: e(%(\"progid:DXImageTransform.Microsoft.gradient(enabled = false)\"));\n}\n"]}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap-theme.min.css b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap-theme.min.css
new file mode 100644
index 0000000..cefa3d1
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap-theme.min.css
@@ -0,0 +1,5 @@
+/*!
+ * Bootstrap v3.3.4 (http://getbootstrap.com)
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ */.btn-danger,.btn-default,.btn-info,.btn-primary,.btn-success,.btn-warning{text-shadow:0 -1px 0 rgba(0,0,0,.2);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.15),0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 0 rgba(255,255,255,.15),0 1px 1px rgba(0,0,0,.075)}.btn-danger.active,.btn-danger:active,.btn-default.active,.btn-default:active,.btn-info.active,.btn-info:active,.btn-primary.active,.btn-primary:active,.btn-success.active,.btn-success:active,.btn-warning.active,.btn-warning:active{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-danger .badge,.btn-default .badge,.btn-info .badge,.btn-primary .badge,.btn-success .badge,.btn-warning .badge{text-shadow:none}.btn.active,.btn:active{background-image:none}.btn-default{text-shadow:0 1px 0 #fff;background-image:-webkit-linear-gradient(top,#fff 0,#e0e0e0 100%);background-image:-o-linear-gradient(top,#fff 0,#e0e0e0 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#fff),to(#e0e0e0));background-image:linear-gradient(to bottom,#fff 0,#e0e0e0 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe0e0e0', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-color:#dbdbdb;border-color:#ccc}.btn-default:focus,.btn-default:hover{background-color:#e0e0e0;background-position:0 -15px}.btn-default.active,.btn-default:active{background-color:#e0e0e0;border-color:#dbdbdb}.btn-default.disabled,.btn-default:disabled,.btn-default[disabled]{background-color:#e0e0e0;background-image:none}.btn-primary{background-image:-webkit-linear-gradient(top,#337ab7 0,#265a88 100%);background-image:-o-linear-gradient(top,#337ab7 0,#265a88 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#337ab7),to(#265a88));background-image:linear-gradient(to bottom,#337ab7 0,#265a88 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff265a88', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-color:#245580}.btn-primary:focus,.btn-primary:hover{background-color:#265a88;background-position:0 -15px}.btn-primary.active,.btn-primary:active{background-color:#265a88;border-color:#245580}.btn-primary.disabled,.btn-primary:disabled,.btn-primary[disabled]{background-color:#265a88;background-image:none}.btn-success{background-image:-webkit-linear-gradient(top,#5cb85c 0,#419641 100%);background-image:-o-linear-gradient(top,#5cb85c 0,#419641 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#5cb85c),to(#419641));background-image:linear-gradient(to bottom,#5cb85c 0,#419641 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff419641', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-color:#3e8f3e}.btn-success:focus,.btn-success:hover{background-color:#419641;background-position:0 -15px}.btn-success.active,.btn-success:active{background-color:#419641;border-color:#3e8f3e}.btn-success.disabled,.btn-success:disabled,.btn-success[disabled]{background-color:#419641;background-image:none}.btn-info{background-image:-webkit-linear-gradient(top,#5bc0de 0,#2aabd2 100%);background-image:-o-linear-gradient(top,#5bc0de 0,#2aabd2 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#5bc0de),to(#2aabd2));background-image:linear-gradient(to bottom,#5bc0de 0,#2aabd2 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2aabd2', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-color:#28a4c9}.btn-info:focus,.btn-info:hover{background-color:#2aabd2;background-position:0 -15px}.btn-info.active,.btn-info:active{background-color:#2aabd2;border-color:#28a4c9}.btn-info.disabled,.btn-info:disabled,.btn-info[disabled]{background-color:#2aabd2;background-image:none}.btn-warning{background-image:-webkit-linear-gradient(top,#f0ad4e 0,#eb9316 100%);background-image:-o-linear-gradient(top,#f0ad4e 0,#eb9316 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#f0ad4e),to(#eb9316));background-image:linear-gradient(to bottom,#f0ad4e 0,#eb9316 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffeb9316', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-color:#e38d13}.btn-warning:focus,.btn-warning:hover{background-color:#eb9316;background-position:0 -15px}.btn-warning.active,.btn-warning:active{background-color:#eb9316;border-color:#e38d13}.btn-warning.disabled,.btn-warning:disabled,.btn-warning[disabled]{background-color:#eb9316;background-image:none}.btn-danger{background-image:-webkit-linear-gradient(top,#d9534f 0,#c12e2a 100%);background-image:-o-linear-gradient(top,#d9534f 0,#c12e2a 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#d9534f),to(#c12e2a));background-image:linear-gradient(to bottom,#d9534f 0,#c12e2a 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc12e2a', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-color:#b92c28}.btn-danger:focus,.btn-danger:hover{background-color:#c12e2a;background-position:0 -15px}.btn-danger.active,.btn-danger:active{background-color:#c12e2a;border-color:#b92c28}.btn-danger.disabled,.btn-danger:disabled,.btn-danger[disabled]{background-color:#c12e2a;background-image:none}.img-thumbnail,.thumbnail{-webkit-box-shadow:0 1px 2px rgba(0,0,0,.075);box-shadow:0 1px 2px rgba(0,0,0,.075)}.dropdown-menu>li>a:focus,.dropdown-menu>li>a:hover{background-color:#e8e8e8;background-image:-webkit-linear-gradient(top,#f5f5f5 0,#e8e8e8 100%);background-image:-o-linear-gradient(top,#f5f5f5 0,#e8e8e8 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#f5f5f5),to(#e8e8e8));background-image:linear-gradient(to bottom,#f5f5f5 0,#e8e8e8 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);background-repeat:repeat-x}.dropdown-menu>.active>a,.dropdown-menu>.active>a:focus,.dropdown-menu>.active>a:hover{background-color:#2e6da4;background-image:-webkit-linear-gradient(top,#337ab7 0,#2e6da4 100%);background-image:-o-linear-gradient(top,#337ab7 0,#2e6da4 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#337ab7),to(#2e6da4));background-image:linear-gradient(to bottom,#337ab7 0,#2e6da4 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);background-repeat:repeat-x}.navbar-default{background-image:-webkit-linear-gradient(top,#fff 0,#f8f8f8 100%);background-image:-o-linear-gradient(top,#fff 0,#f8f8f8 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#fff),to(#f8f8f8));background-image:linear-gradient(to bottom,#fff 0,#f8f8f8 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff8f8f8', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x;border-radius:4px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.15),0 1px 5px rgba(0,0,0,.075);box-shadow:inset 0 1px 0 rgba(255,255,255,.15),0 1px 5px rgba(0,0,0,.075)}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.open>a{background-image:-webkit-linear-gradient(top,#dbdbdb 0,#e2e2e2 100%);background-image:-o-linear-gradient(top,#dbdbdb 0,#e2e2e2 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#dbdbdb),to(#e2e2e2));background-image:linear-gradient(to bottom,#dbdbdb 0,#e2e2e2 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdbdbdb', endColorstr='#ffe2e2e2', GradientType=0);background-repeat:repeat-x;-webkit-box-shadow:inset 0 3px 9px rgba(0,0,0,.075);box-shadow:inset 0 3px 9px rgba(0,0,0,.075)}.navbar-brand,.navbar-nav>li>a{text-shadow:0 1px 0 rgba(255,255,255,.25)}.navbar-inverse{background-image:-webkit-linear-gradient(top,#3c3c3c 0,#222 100%);background-image:-o-linear-gradient(top,#3c3c3c 0,#222 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#3c3c3c),to(#222));background-image:linear-gradient(to bottom,#3c3c3c 0,#222 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c', endColorstr='#ff222222', GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);background-repeat:repeat-x}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.open>a{background-image:-webkit-linear-gradient(top,#080808 0,#0f0f0f 100%);background-image:-o-linear-gradient(top,#080808 0,#0f0f0f 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#080808),to(#0f0f0f));background-image:linear-gradient(to bottom,#080808 0,#0f0f0f 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff080808', endColorstr='#ff0f0f0f', GradientType=0);background-repeat:repeat-x;-webkit-box-shadow:inset 0 3px 9px rgba(0,0,0,.25);box-shadow:inset 0 3px 9px rgba(0,0,0,.25)}.navbar-inverse .navbar-brand,.navbar-inverse .navbar-nav>li>a{text-shadow:0 -1px 0 rgba(0,0,0,.25)}.navbar-fixed-bottom,.navbar-fixed-top,.navbar-static-top{border-radius:0}@media (max-width:767px){.navbar .navbar-nav .open .dropdown-menu>.active>a,.navbar .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar .navbar-nav .open .dropdown-menu>.active>a:hover{color:#fff;background-image:-webkit-linear-gradient(top,#337ab7 0,#2e6da4 100%);background-image:-o-linear-gradient(top,#337ab7 0,#2e6da4 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#337ab7),to(#2e6da4));background-image:linear-gradient(to bottom,#337ab7 0,#2e6da4 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);background-repeat:repeat-x}}.alert{text-shadow:0 1px 0 rgba(255,255,255,.2);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.25),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.25),0 1px 2px rgba(0,0,0,.05)}.alert-success{background-image:-webkit-linear-gradient(top,#dff0d8 0,#c8e5bc 100%);background-image:-o-linear-gradient(top,#dff0d8 0,#c8e5bc 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#dff0d8),to(#c8e5bc));background-image:linear-gradient(to bottom,#dff0d8 0,#c8e5bc 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0);background-repeat:repeat-x;border-color:#b2dba1}.alert-info{background-image:-webkit-linear-gradient(top,#d9edf7 0,#b9def0 100%);background-image:-o-linear-gradient(top,#d9edf7 0,#b9def0 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#d9edf7),to(#b9def0));background-image:linear-gradient(to bottom,#d9edf7 0,#b9def0 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffb9def0', GradientType=0);background-repeat:repeat-x;border-color:#9acfea}.alert-warning{background-image:-webkit-linear-gradient(top,#fcf8e3 0,#f8efc0 100%);background-image:-o-linear-gradient(top,#fcf8e3 0,#f8efc0 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#fcf8e3),to(#f8efc0));background-image:linear-gradient(to bottom,#fcf8e3 0,#f8efc0 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fff8efc0', GradientType=0);background-repeat:repeat-x;border-color:#f5e79e}.alert-danger{background-image:-webkit-linear-gradient(top,#f2dede 0,#e7c3c3 100%);background-image:-o-linear-gradient(top,#f2dede 0,#e7c3c3 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#f2dede),to(#e7c3c3));background-image:linear-gradient(to bottom,#f2dede 0,#e7c3c3 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffe7c3c3', GradientType=0);background-repeat:repeat-x;border-color:#dca7a7}.progress{background-image:-webkit-linear-gradient(top,#ebebeb 0,#f5f5f5 100%);background-image:-o-linear-gradient(top,#ebebeb 0,#f5f5f5 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#ebebeb),to(#f5f5f5));background-image:linear-gradient(to bottom,#ebebeb 0,#f5f5f5 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0);background-repeat:repeat-x}.progress-bar{background-image:-webkit-linear-gradient(top,#337ab7 0,#286090 100%);background-image:-o-linear-gradient(top,#337ab7 0,#286090 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#337ab7),to(#286090));background-image:linear-gradient(to bottom,#337ab7 0,#286090 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff286090', GradientType=0);background-repeat:repeat-x}.progress-bar-success{background-image:-webkit-linear-gradient(top,#5cb85c 0,#449d44 100%);background-image:-o-linear-gradient(top,#5cb85c 0,#449d44 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#5cb85c),to(#449d44));background-image:linear-gradient(to bottom,#5cb85c 0,#449d44 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0);background-repeat:repeat-x}.progress-bar-info{background-image:-webkit-linear-gradient(top,#5bc0de 0,#31b0d5 100%);background-image:-o-linear-gradient(top,#5bc0de 0,#31b0d5 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#5bc0de),to(#31b0d5));background-image:linear-gradient(to bottom,#5bc0de 0,#31b0d5 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0);background-repeat:repeat-x}.progress-bar-warning{background-image:-webkit-linear-gradient(top,#f0ad4e 0,#ec971f 100%);background-image:-o-linear-gradient(top,#f0ad4e 0,#ec971f 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#f0ad4e),to(#ec971f));background-image:linear-gradient(to bottom,#f0ad4e 0,#ec971f 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0);background-repeat:repeat-x}.progress-bar-danger{background-image:-webkit-linear-gradient(top,#d9534f 0,#c9302c 100%);background-image:-o-linear-gradient(top,#d9534f 0,#c9302c 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#d9534f),to(#c9302c));background-image:linear-gradient(to bottom,#d9534f 0,#c9302c 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0);background-repeat:repeat-x}.progress-bar-striped{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.list-group{border-radius:4px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.075);box-shadow:0 1px 2px rgba(0,0,0,.075)}.list-group-item.active,.list-group-item.active:focus,.list-group-item.active:hover{text-shadow:0 -1px 0 #286090;background-image:-webkit-linear-gradient(top,#337ab7 0,#2b669a 100%);background-image:-o-linear-gradient(top,#337ab7 0,#2b669a 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#337ab7),to(#2b669a));background-image:linear-gradient(to bottom,#337ab7 0,#2b669a 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2b669a', GradientType=0);background-repeat:repeat-x;border-color:#2b669a}.list-group-item.active .badge,.list-group-item.active:focus .badge,.list-group-item.active:hover .badge{text-shadow:none}.panel{-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.panel-default>.panel-heading{background-image:-webkit-linear-gradient(top,#f5f5f5 0,#e8e8e8 100%);background-image:-o-linear-gradient(top,#f5f5f5 0,#e8e8e8 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#f5f5f5),to(#e8e8e8));background-image:linear-gradient(to bottom,#f5f5f5 0,#e8e8e8 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);background-repeat:repeat-x}.panel-primary>.panel-heading{background-image:-webkit-linear-gradient(top,#337ab7 0,#2e6da4 100%);background-image:-o-linear-gradient(top,#337ab7 0,#2e6da4 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#337ab7),to(#2e6da4));background-image:linear-gradient(to bottom,#337ab7 0,#2e6da4 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);background-repeat:repeat-x}.panel-success>.panel-heading{background-image:-webkit-linear-gradient(top,#dff0d8 0,#d0e9c6 100%);background-image:-o-linear-gradient(top,#dff0d8 0,#d0e9c6 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#dff0d8),to(#d0e9c6));background-image:linear-gradient(to bottom,#dff0d8 0,#d0e9c6 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffd0e9c6', GradientType=0);background-repeat:repeat-x}.panel-info>.panel-heading{background-image:-webkit-linear-gradient(top,#d9edf7 0,#c4e3f3 100%);background-image:-o-linear-gradient(top,#d9edf7 0,#c4e3f3 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#d9edf7),to(#c4e3f3));background-image:linear-gradient(to bottom,#d9edf7 0,#c4e3f3 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffc4e3f3', GradientType=0);background-repeat:repeat-x}.panel-warning>.panel-heading{background-image:-webkit-linear-gradient(top,#fcf8e3 0,#faf2cc 100%);background-image:-o-linear-gradient(top,#fcf8e3 0,#faf2cc 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#fcf8e3),to(#faf2cc));background-image:linear-gradient(to bottom,#fcf8e3 0,#faf2cc 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fffaf2cc', GradientType=0);background-repeat:repeat-x}.panel-danger>.panel-heading{background-image:-webkit-linear-gradient(top,#f2dede 0,#ebcccc 100%);background-image:-o-linear-gradient(top,#f2dede 0,#ebcccc 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#f2dede),to(#ebcccc));background-image:linear-gradient(to bottom,#f2dede 0,#ebcccc 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffebcccc', GradientType=0);background-repeat:repeat-x}.well{background-image:-webkit-linear-gradient(top,#e8e8e8 0,#f5f5f5 100%);background-image:-o-linear-gradient(top,#e8e8e8 0,#f5f5f5 100%);background-image:-webkit-gradient(linear,left top,left bottom,from(#e8e8e8),to(#f5f5f5));background-image:linear-gradient(to bottom,#e8e8e8 0,#f5f5f5 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8', endColorstr='#fff5f5f5', GradientType=0);background-repeat:repeat-x;border-color:#dcdcdc;-webkit-box-shadow:inset 0 1px 3px rgba(0,0,0,.05),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 3px rgba(0,0,0,.05),0 1px 0 rgba(255,255,255,.1)}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap.css b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap.css
new file mode 100644
index 0000000..fb15e3d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap.css
@@ -0,0 +1,6584 @@
+/*!
+ * Bootstrap v3.3.4 (http://getbootstrap.com)
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ */
+
+/*! normalize.css v3.0.2 | MIT License | git.io/normalize */
+html {
+ font-family: sans-serif;
+ -webkit-text-size-adjust: 100%;
+ -ms-text-size-adjust: 100%;
+}
+body {
+ margin: 0;
+}
+article,
+aside,
+details,
+figcaption,
+figure,
+footer,
+header,
+hgroup,
+main,
+menu,
+nav,
+section,
+summary {
+ display: block;
+}
+audio,
+canvas,
+progress,
+video {
+ display: inline-block;
+ vertical-align: baseline;
+}
+audio:not([controls]) {
+ display: none;
+ height: 0;
+}
+[hidden],
+template {
+ display: none;
+}
+a {
+ background-color: transparent;
+}
+a:active,
+a:hover {
+ outline: 0;
+}
+abbr[title] {
+ border-bottom: 1px dotted;
+}
+b,
+strong {
+ font-weight: bold;
+}
+dfn {
+ font-style: italic;
+}
+h1 {
+ margin: .67em 0;
+ font-size: 2em;
+}
+mark {
+ color: #000;
+ background: #ff0;
+}
+small {
+ font-size: 80%;
+}
+sub,
+sup {
+ position: relative;
+ font-size: 75%;
+ line-height: 0;
+ vertical-align: baseline;
+}
+sup {
+ top: -.5em;
+}
+sub {
+ bottom: -.25em;
+}
+img {
+ border: 0;
+}
+svg:not(:root) {
+ overflow: hidden;
+}
+figure {
+ margin: 1em 40px;
+}
+hr {
+ height: 0;
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+}
+pre {
+ overflow: auto;
+}
+code,
+kbd,
+pre,
+samp {
+ font-family: monospace, monospace;
+ font-size: 1em;
+}
+button,
+input,
+optgroup,
+select,
+textarea {
+ margin: 0;
+ font: inherit;
+ color: inherit;
+}
+button {
+ overflow: visible;
+}
+button,
+select {
+ text-transform: none;
+}
+button,
+html input[type="button"],
+input[type="reset"],
+input[type="submit"] {
+ -webkit-appearance: button;
+ cursor: pointer;
+}
+button[disabled],
+html input[disabled] {
+ cursor: default;
+}
+button::-moz-focus-inner,
+input::-moz-focus-inner {
+ padding: 0;
+ border: 0;
+}
+input {
+ line-height: normal;
+}
+input[type="checkbox"],
+input[type="radio"] {
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+ padding: 0;
+}
+input[type="number"]::-webkit-inner-spin-button,
+input[type="number"]::-webkit-outer-spin-button {
+ height: auto;
+}
+input[type="search"] {
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+ -webkit-appearance: textfield;
+}
+input[type="search"]::-webkit-search-cancel-button,
+input[type="search"]::-webkit-search-decoration {
+ -webkit-appearance: none;
+}
+fieldset {
+ padding: .35em .625em .75em;
+ margin: 0 2px;
+ border: 1px solid #c0c0c0;
+}
+legend {
+ padding: 0;
+ border: 0;
+}
+textarea {
+ overflow: auto;
+}
+optgroup {
+ font-weight: bold;
+}
+table {
+ border-spacing: 0;
+ border-collapse: collapse;
+}
+td,
+th {
+ padding: 0;
+}
+/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */
+@media print {
+ *,
+ *:before,
+ *:after {
+ color: #000 !important;
+ text-shadow: none !important;
+ background: transparent !important;
+ -webkit-box-shadow: none !important;
+ box-shadow: none !important;
+ }
+ a,
+ a:visited {
+ text-decoration: underline;
+ }
+ a[href]:after {
+ content: " (" attr(href) ")";
+ }
+ abbr[title]:after {
+ content: " (" attr(title) ")";
+ }
+ a[href^="#"]:after,
+ a[href^="javascript:"]:after {
+ content: "";
+ }
+ pre,
+ blockquote {
+ border: 1px solid #999;
+
+ page-break-inside: avoid;
+ }
+ thead {
+ display: table-header-group;
+ }
+ tr,
+ img {
+ page-break-inside: avoid;
+ }
+ img {
+ max-width: 100% !important;
+ }
+ p,
+ h2,
+ h3 {
+ orphans: 3;
+ widows: 3;
+ }
+ h2,
+ h3 {
+ page-break-after: avoid;
+ }
+ select {
+ background: #fff !important;
+ }
+ .navbar {
+ display: none;
+ }
+ .btn > .caret,
+ .dropup > .btn > .caret {
+ border-top-color: #000 !important;
+ }
+ .label {
+ border: 1px solid #000;
+ }
+ .table {
+ border-collapse: collapse !important;
+ }
+ .table td,
+ .table th {
+ background-color: #fff !important;
+ }
+ .table-bordered th,
+ .table-bordered td {
+ border: 1px solid #ddd !important;
+ }
+}
+@font-face {
+ font-family: 'Glyphicons Halflings';
+
+ src: url('../fonts/glyphicons-halflings-regular.eot');
+ src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
+}
+.glyphicon {
+ position: relative;
+ top: 1px;
+ display: inline-block;
+ font-family: 'Glyphicons Halflings';
+ font-style: normal;
+ font-weight: normal;
+ line-height: 1;
+
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+}
+.glyphicon-asterisk:before {
+ content: "\2a";
+}
+.glyphicon-plus:before {
+ content: "\2b";
+}
+.glyphicon-euro:before,
+.glyphicon-eur:before {
+ content: "\20ac";
+}
+.glyphicon-minus:before {
+ content: "\2212";
+}
+.glyphicon-cloud:before {
+ content: "\2601";
+}
+.glyphicon-envelope:before {
+ content: "\2709";
+}
+.glyphicon-pencil:before {
+ content: "\270f";
+}
+.glyphicon-glass:before {
+ content: "\e001";
+}
+.glyphicon-music:before {
+ content: "\e002";
+}
+.glyphicon-search:before {
+ content: "\e003";
+}
+.glyphicon-heart:before {
+ content: "\e005";
+}
+.glyphicon-star:before {
+ content: "\e006";
+}
+.glyphicon-star-empty:before {
+ content: "\e007";
+}
+.glyphicon-user:before {
+ content: "\e008";
+}
+.glyphicon-film:before {
+ content: "\e009";
+}
+.glyphicon-th-large:before {
+ content: "\e010";
+}
+.glyphicon-th:before {
+ content: "\e011";
+}
+.glyphicon-th-list:before {
+ content: "\e012";
+}
+.glyphicon-ok:before {
+ content: "\e013";
+}
+.glyphicon-remove:before {
+ content: "\e014";
+}
+.glyphicon-zoom-in:before {
+ content: "\e015";
+}
+.glyphicon-zoom-out:before {
+ content: "\e016";
+}
+.glyphicon-off:before {
+ content: "\e017";
+}
+.glyphicon-signal:before {
+ content: "\e018";
+}
+.glyphicon-cog:before {
+ content: "\e019";
+}
+.glyphicon-trash:before {
+ content: "\e020";
+}
+.glyphicon-home:before {
+ content: "\e021";
+}
+.glyphicon-file:before {
+ content: "\e022";
+}
+.glyphicon-time:before {
+ content: "\e023";
+}
+.glyphicon-road:before {
+ content: "\e024";
+}
+.glyphicon-download-alt:before {
+ content: "\e025";
+}
+.glyphicon-download:before {
+ content: "\e026";
+}
+.glyphicon-upload:before {
+ content: "\e027";
+}
+.glyphicon-inbox:before {
+ content: "\e028";
+}
+.glyphicon-play-circle:before {
+ content: "\e029";
+}
+.glyphicon-repeat:before {
+ content: "\e030";
+}
+.glyphicon-refresh:before {
+ content: "\e031";
+}
+.glyphicon-list-alt:before {
+ content: "\e032";
+}
+.glyphicon-lock:before {
+ content: "\e033";
+}
+.glyphicon-flag:before {
+ content: "\e034";
+}
+.glyphicon-headphones:before {
+ content: "\e035";
+}
+.glyphicon-volume-off:before {
+ content: "\e036";
+}
+.glyphicon-volume-down:before {
+ content: "\e037";
+}
+.glyphicon-volume-up:before {
+ content: "\e038";
+}
+.glyphicon-qrcode:before {
+ content: "\e039";
+}
+.glyphicon-barcode:before {
+ content: "\e040";
+}
+.glyphicon-tag:before {
+ content: "\e041";
+}
+.glyphicon-tags:before {
+ content: "\e042";
+}
+.glyphicon-book:before {
+ content: "\e043";
+}
+.glyphicon-bookmark:before {
+ content: "\e044";
+}
+.glyphicon-print:before {
+ content: "\e045";
+}
+.glyphicon-camera:before {
+ content: "\e046";
+}
+.glyphicon-font:before {
+ content: "\e047";
+}
+.glyphicon-bold:before {
+ content: "\e048";
+}
+.glyphicon-italic:before {
+ content: "\e049";
+}
+.glyphicon-text-height:before {
+ content: "\e050";
+}
+.glyphicon-text-width:before {
+ content: "\e051";
+}
+.glyphicon-align-left:before {
+ content: "\e052";
+}
+.glyphicon-align-center:before {
+ content: "\e053";
+}
+.glyphicon-align-right:before {
+ content: "\e054";
+}
+.glyphicon-align-justify:before {
+ content: "\e055";
+}
+.glyphicon-list:before {
+ content: "\e056";
+}
+.glyphicon-indent-left:before {
+ content: "\e057";
+}
+.glyphicon-indent-right:before {
+ content: "\e058";
+}
+.glyphicon-facetime-video:before {
+ content: "\e059";
+}
+.glyphicon-picture:before {
+ content: "\e060";
+}
+.glyphicon-map-marker:before {
+ content: "\e062";
+}
+.glyphicon-adjust:before {
+ content: "\e063";
+}
+.glyphicon-tint:before {
+ content: "\e064";
+}
+.glyphicon-edit:before {
+ content: "\e065";
+}
+.glyphicon-share:before {
+ content: "\e066";
+}
+.glyphicon-check:before {
+ content: "\e067";
+}
+.glyphicon-move:before {
+ content: "\e068";
+}
+.glyphicon-step-backward:before {
+ content: "\e069";
+}
+.glyphicon-fast-backward:before {
+ content: "\e070";
+}
+.glyphicon-backward:before {
+ content: "\e071";
+}
+.glyphicon-play:before {
+ content: "\e072";
+}
+.glyphicon-pause:before {
+ content: "\e073";
+}
+.glyphicon-stop:before {
+ content: "\e074";
+}
+.glyphicon-forward:before {
+ content: "\e075";
+}
+.glyphicon-fast-forward:before {
+ content: "\e076";
+}
+.glyphicon-step-forward:before {
+ content: "\e077";
+}
+.glyphicon-eject:before {
+ content: "\e078";
+}
+.glyphicon-chevron-left:before {
+ content: "\e079";
+}
+.glyphicon-chevron-right:before {
+ content: "\e080";
+}
+.glyphicon-plus-sign:before {
+ content: "\e081";
+}
+.glyphicon-minus-sign:before {
+ content: "\e082";
+}
+.glyphicon-remove-sign:before {
+ content: "\e083";
+}
+.glyphicon-ok-sign:before {
+ content: "\e084";
+}
+.glyphicon-question-sign:before {
+ content: "\e085";
+}
+.glyphicon-info-sign:before {
+ content: "\e086";
+}
+.glyphicon-screenshot:before {
+ content: "\e087";
+}
+.glyphicon-remove-circle:before {
+ content: "\e088";
+}
+.glyphicon-ok-circle:before {
+ content: "\e089";
+}
+.glyphicon-ban-circle:before {
+ content: "\e090";
+}
+.glyphicon-arrow-left:before {
+ content: "\e091";
+}
+.glyphicon-arrow-right:before {
+ content: "\e092";
+}
+.glyphicon-arrow-up:before {
+ content: "\e093";
+}
+.glyphicon-arrow-down:before {
+ content: "\e094";
+}
+.glyphicon-share-alt:before {
+ content: "\e095";
+}
+.glyphicon-resize-full:before {
+ content: "\e096";
+}
+.glyphicon-resize-small:before {
+ content: "\e097";
+}
+.glyphicon-exclamation-sign:before {
+ content: "\e101";
+}
+.glyphicon-gift:before {
+ content: "\e102";
+}
+.glyphicon-leaf:before {
+ content: "\e103";
+}
+.glyphicon-fire:before {
+ content: "\e104";
+}
+.glyphicon-eye-open:before {
+ content: "\e105";
+}
+.glyphicon-eye-close:before {
+ content: "\e106";
+}
+.glyphicon-warning-sign:before {
+ content: "\e107";
+}
+.glyphicon-plane:before {
+ content: "\e108";
+}
+.glyphicon-calendar:before {
+ content: "\e109";
+}
+.glyphicon-random:before {
+ content: "\e110";
+}
+.glyphicon-comment:before {
+ content: "\e111";
+}
+.glyphicon-magnet:before {
+ content: "\e112";
+}
+.glyphicon-chevron-up:before {
+ content: "\e113";
+}
+.glyphicon-chevron-down:before {
+ content: "\e114";
+}
+.glyphicon-retweet:before {
+ content: "\e115";
+}
+.glyphicon-shopping-cart:before {
+ content: "\e116";
+}
+.glyphicon-folder-close:before {
+ content: "\e117";
+}
+.glyphicon-folder-open:before {
+ content: "\e118";
+}
+.glyphicon-resize-vertical:before {
+ content: "\e119";
+}
+.glyphicon-resize-horizontal:before {
+ content: "\e120";
+}
+.glyphicon-hdd:before {
+ content: "\e121";
+}
+.glyphicon-bullhorn:before {
+ content: "\e122";
+}
+.glyphicon-bell:before {
+ content: "\e123";
+}
+.glyphicon-certificate:before {
+ content: "\e124";
+}
+.glyphicon-thumbs-up:before {
+ content: "\e125";
+}
+.glyphicon-thumbs-down:before {
+ content: "\e126";
+}
+.glyphicon-hand-right:before {
+ content: "\e127";
+}
+.glyphicon-hand-left:before {
+ content: "\e128";
+}
+.glyphicon-hand-up:before {
+ content: "\e129";
+}
+.glyphicon-hand-down:before {
+ content: "\e130";
+}
+.glyphicon-circle-arrow-right:before {
+ content: "\e131";
+}
+.glyphicon-circle-arrow-left:before {
+ content: "\e132";
+}
+.glyphicon-circle-arrow-up:before {
+ content: "\e133";
+}
+.glyphicon-circle-arrow-down:before {
+ content: "\e134";
+}
+.glyphicon-globe:before {
+ content: "\e135";
+}
+.glyphicon-wrench:before {
+ content: "\e136";
+}
+.glyphicon-tasks:before {
+ content: "\e137";
+}
+.glyphicon-filter:before {
+ content: "\e138";
+}
+.glyphicon-briefcase:before {
+ content: "\e139";
+}
+.glyphicon-fullscreen:before {
+ content: "\e140";
+}
+.glyphicon-dashboard:before {
+ content: "\e141";
+}
+.glyphicon-paperclip:before {
+ content: "\e142";
+}
+.glyphicon-heart-empty:before {
+ content: "\e143";
+}
+.glyphicon-link:before {
+ content: "\e144";
+}
+.glyphicon-phone:before {
+ content: "\e145";
+}
+.glyphicon-pushpin:before {
+ content: "\e146";
+}
+.glyphicon-usd:before {
+ content: "\e148";
+}
+.glyphicon-gbp:before {
+ content: "\e149";
+}
+.glyphicon-sort:before {
+ content: "\e150";
+}
+.glyphicon-sort-by-alphabet:before {
+ content: "\e151";
+}
+.glyphicon-sort-by-alphabet-alt:before {
+ content: "\e152";
+}
+.glyphicon-sort-by-order:before {
+ content: "\e153";
+}
+.glyphicon-sort-by-order-alt:before {
+ content: "\e154";
+}
+.glyphicon-sort-by-attributes:before {
+ content: "\e155";
+}
+.glyphicon-sort-by-attributes-alt:before {
+ content: "\e156";
+}
+.glyphicon-unchecked:before {
+ content: "\e157";
+}
+.glyphicon-expand:before {
+ content: "\e158";
+}
+.glyphicon-collapse-down:before {
+ content: "\e159";
+}
+.glyphicon-collapse-up:before {
+ content: "\e160";
+}
+.glyphicon-log-in:before {
+ content: "\e161";
+}
+.glyphicon-flash:before {
+ content: "\e162";
+}
+.glyphicon-log-out:before {
+ content: "\e163";
+}
+.glyphicon-new-window:before {
+ content: "\e164";
+}
+.glyphicon-record:before {
+ content: "\e165";
+}
+.glyphicon-save:before {
+ content: "\e166";
+}
+.glyphicon-open:before {
+ content: "\e167";
+}
+.glyphicon-saved:before {
+ content: "\e168";
+}
+.glyphicon-import:before {
+ content: "\e169";
+}
+.glyphicon-export:before {
+ content: "\e170";
+}
+.glyphicon-send:before {
+ content: "\e171";
+}
+.glyphicon-floppy-disk:before {
+ content: "\e172";
+}
+.glyphicon-floppy-saved:before {
+ content: "\e173";
+}
+.glyphicon-floppy-remove:before {
+ content: "\e174";
+}
+.glyphicon-floppy-save:before {
+ content: "\e175";
+}
+.glyphicon-floppy-open:before {
+ content: "\e176";
+}
+.glyphicon-credit-card:before {
+ content: "\e177";
+}
+.glyphicon-transfer:before {
+ content: "\e178";
+}
+.glyphicon-cutlery:before {
+ content: "\e179";
+}
+.glyphicon-header:before {
+ content: "\e180";
+}
+.glyphicon-compressed:before {
+ content: "\e181";
+}
+.glyphicon-earphone:before {
+ content: "\e182";
+}
+.glyphicon-phone-alt:before {
+ content: "\e183";
+}
+.glyphicon-tower:before {
+ content: "\e184";
+}
+.glyphicon-stats:before {
+ content: "\e185";
+}
+.glyphicon-sd-video:before {
+ content: "\e186";
+}
+.glyphicon-hd-video:before {
+ content: "\e187";
+}
+.glyphicon-subtitles:before {
+ content: "\e188";
+}
+.glyphicon-sound-stereo:before {
+ content: "\e189";
+}
+.glyphicon-sound-dolby:before {
+ content: "\e190";
+}
+.glyphicon-sound-5-1:before {
+ content: "\e191";
+}
+.glyphicon-sound-6-1:before {
+ content: "\e192";
+}
+.glyphicon-sound-7-1:before {
+ content: "\e193";
+}
+.glyphicon-copyright-mark:before {
+ content: "\e194";
+}
+.glyphicon-registration-mark:before {
+ content: "\e195";
+}
+.glyphicon-cloud-download:before {
+ content: "\e197";
+}
+.glyphicon-cloud-upload:before {
+ content: "\e198";
+}
+.glyphicon-tree-conifer:before {
+ content: "\e199";
+}
+.glyphicon-tree-deciduous:before {
+ content: "\e200";
+}
+.glyphicon-cd:before {
+ content: "\e201";
+}
+.glyphicon-save-file:before {
+ content: "\e202";
+}
+.glyphicon-open-file:before {
+ content: "\e203";
+}
+.glyphicon-level-up:before {
+ content: "\e204";
+}
+.glyphicon-copy:before {
+ content: "\e205";
+}
+.glyphicon-paste:before {
+ content: "\e206";
+}
+.glyphicon-alert:before {
+ content: "\e209";
+}
+.glyphicon-equalizer:before {
+ content: "\e210";
+}
+.glyphicon-king:before {
+ content: "\e211";
+}
+.glyphicon-queen:before {
+ content: "\e212";
+}
+.glyphicon-pawn:before {
+ content: "\e213";
+}
+.glyphicon-bishop:before {
+ content: "\e214";
+}
+.glyphicon-knight:before {
+ content: "\e215";
+}
+.glyphicon-baby-formula:before {
+ content: "\e216";
+}
+.glyphicon-tent:before {
+ content: "\26fa";
+}
+.glyphicon-blackboard:before {
+ content: "\e218";
+}
+.glyphicon-bed:before {
+ content: "\e219";
+}
+.glyphicon-apple:before {
+ content: "\f8ff";
+}
+.glyphicon-erase:before {
+ content: "\e221";
+}
+.glyphicon-hourglass:before {
+ content: "\231b";
+}
+.glyphicon-lamp:before {
+ content: "\e223";
+}
+.glyphicon-duplicate:before {
+ content: "\e224";
+}
+.glyphicon-piggy-bank:before {
+ content: "\e225";
+}
+.glyphicon-scissors:before {
+ content: "\e226";
+}
+.glyphicon-bitcoin:before {
+ content: "\e227";
+}
+.glyphicon-btc:before {
+ content: "\e227";
+}
+.glyphicon-xbt:before {
+ content: "\e227";
+}
+.glyphicon-yen:before {
+ content: "\00a5";
+}
+.glyphicon-jpy:before {
+ content: "\00a5";
+}
+.glyphicon-ruble:before {
+ content: "\20bd";
+}
+.glyphicon-rub:before {
+ content: "\20bd";
+}
+.glyphicon-scale:before {
+ content: "\e230";
+}
+.glyphicon-ice-lolly:before {
+ content: "\e231";
+}
+.glyphicon-ice-lolly-tasted:before {
+ content: "\e232";
+}
+.glyphicon-education:before {
+ content: "\e233";
+}
+.glyphicon-option-horizontal:before {
+ content: "\e234";
+}
+.glyphicon-option-vertical:before {
+ content: "\e235";
+}
+.glyphicon-menu-hamburger:before {
+ content: "\e236";
+}
+.glyphicon-modal-window:before {
+ content: "\e237";
+}
+.glyphicon-oil:before {
+ content: "\e238";
+}
+.glyphicon-grain:before {
+ content: "\e239";
+}
+.glyphicon-sunglasses:before {
+ content: "\e240";
+}
+.glyphicon-text-size:before {
+ content: "\e241";
+}
+.glyphicon-text-color:before {
+ content: "\e242";
+}
+.glyphicon-text-background:before {
+ content: "\e243";
+}
+.glyphicon-object-align-top:before {
+ content: "\e244";
+}
+.glyphicon-object-align-bottom:before {
+ content: "\e245";
+}
+.glyphicon-object-align-horizontal:before {
+ content: "\e246";
+}
+.glyphicon-object-align-left:before {
+ content: "\e247";
+}
+.glyphicon-object-align-vertical:before {
+ content: "\e248";
+}
+.glyphicon-object-align-right:before {
+ content: "\e249";
+}
+.glyphicon-triangle-right:before {
+ content: "\e250";
+}
+.glyphicon-triangle-left:before {
+ content: "\e251";
+}
+.glyphicon-triangle-bottom:before {
+ content: "\e252";
+}
+.glyphicon-triangle-top:before {
+ content: "\e253";
+}
+.glyphicon-console:before {
+ content: "\e254";
+}
+.glyphicon-superscript:before {
+ content: "\e255";
+}
+.glyphicon-subscript:before {
+ content: "\e256";
+}
+.glyphicon-menu-left:before {
+ content: "\e257";
+}
+.glyphicon-menu-right:before {
+ content: "\e258";
+}
+.glyphicon-menu-down:before {
+ content: "\e259";
+}
+.glyphicon-menu-up:before {
+ content: "\e260";
+}
+* {
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+}
+*:before,
+*:after {
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+}
+html {
+ font-size: 10px;
+
+ -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
+}
+body {
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ font-size: 14px;
+ line-height: 1.42857143;
+ color: #333;
+ background-color: #fff;
+}
+input,
+button,
+select,
+textarea {
+ font-family: inherit;
+ font-size: inherit;
+ line-height: inherit;
+}
+a {
+ color: #337ab7;
+ text-decoration: none;
+}
+a:hover,
+a:focus {
+ color: #23527c;
+ text-decoration: underline;
+}
+a:focus {
+ outline: thin dotted;
+ outline: 5px auto -webkit-focus-ring-color;
+ outline-offset: -2px;
+}
+figure {
+ margin: 0;
+}
+img {
+ vertical-align: middle;
+}
+.img-responsive,
+.thumbnail > img,
+.thumbnail a > img,
+.carousel-inner > .item > img,
+.carousel-inner > .item > a > img {
+ display: block;
+ max-width: 100%;
+ height: auto;
+}
+.img-rounded {
+ border-radius: 6px;
+}
+.img-thumbnail {
+ display: inline-block;
+ max-width: 100%;
+ height: auto;
+ padding: 4px;
+ line-height: 1.42857143;
+ background-color: #fff;
+ border: 1px solid #ddd;
+ border-radius: 4px;
+ -webkit-transition: all .2s ease-in-out;
+ -o-transition: all .2s ease-in-out;
+ transition: all .2s ease-in-out;
+}
+.img-circle {
+ border-radius: 50%;
+}
+hr {
+ margin-top: 20px;
+ margin-bottom: 20px;
+ border: 0;
+ border-top: 1px solid #eee;
+}
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ border: 0;
+}
+.sr-only-focusable:active,
+.sr-only-focusable:focus {
+ position: static;
+ width: auto;
+ height: auto;
+ margin: 0;
+ overflow: visible;
+ clip: auto;
+}
+[role="button"] {
+ cursor: pointer;
+}
+h1,
+h2,
+h3,
+h4,
+h5,
+h6,
+.h1,
+.h2,
+.h3,
+.h4,
+.h5,
+.h6 {
+ font-family: inherit;
+ font-weight: 500;
+ line-height: 1.1;
+ color: inherit;
+}
+h1 small,
+h2 small,
+h3 small,
+h4 small,
+h5 small,
+h6 small,
+.h1 small,
+.h2 small,
+.h3 small,
+.h4 small,
+.h5 small,
+.h6 small,
+h1 .small,
+h2 .small,
+h3 .small,
+h4 .small,
+h5 .small,
+h6 .small,
+.h1 .small,
+.h2 .small,
+.h3 .small,
+.h4 .small,
+.h5 .small,
+.h6 .small {
+ font-weight: normal;
+ line-height: 1;
+ color: #777;
+}
+h1,
+.h1,
+h2,
+.h2,
+h3,
+.h3 {
+ margin-top: 20px;
+ margin-bottom: 10px;
+}
+h1 small,
+.h1 small,
+h2 small,
+.h2 small,
+h3 small,
+.h3 small,
+h1 .small,
+.h1 .small,
+h2 .small,
+.h2 .small,
+h3 .small,
+.h3 .small {
+ font-size: 65%;
+}
+h4,
+.h4,
+h5,
+.h5,
+h6,
+.h6 {
+ margin-top: 10px;
+ margin-bottom: 10px;
+}
+h4 small,
+.h4 small,
+h5 small,
+.h5 small,
+h6 small,
+.h6 small,
+h4 .small,
+.h4 .small,
+h5 .small,
+.h5 .small,
+h6 .small,
+.h6 .small {
+ font-size: 75%;
+}
+h1,
+.h1 {
+ font-size: 36px;
+}
+h2,
+.h2 {
+ font-size: 30px;
+}
+h3,
+.h3 {
+ font-size: 24px;
+}
+h4,
+.h4 {
+ font-size: 18px;
+}
+h5,
+.h5 {
+ font-size: 14px;
+}
+h6,
+.h6 {
+ font-size: 12px;
+}
+p {
+ margin: 0 0 10px;
+}
+.lead {
+ margin-bottom: 20px;
+ font-size: 16px;
+ font-weight: 300;
+ line-height: 1.4;
+}
+@media (min-width: 768px) {
+ .lead {
+ font-size: 21px;
+ }
+}
+small,
+.small {
+ font-size: 85%;
+}
+mark,
+.mark {
+ padding: .2em;
+ background-color: #fcf8e3;
+}
+.text-left {
+ text-align: left;
+}
+.text-right {
+ text-align: right;
+}
+.text-center {
+ text-align: center;
+}
+.text-justify {
+ text-align: justify;
+}
+.text-nowrap {
+ white-space: nowrap;
+}
+.text-lowercase {
+ text-transform: lowercase;
+}
+.text-uppercase {
+ text-transform: uppercase;
+}
+.text-capitalize {
+ text-transform: capitalize;
+}
+.text-muted {
+ color: #777;
+}
+.text-primary {
+ color: #337ab7;
+}
+a.text-primary:hover {
+ color: #286090;
+}
+.text-success {
+ color: #3c763d;
+}
+a.text-success:hover {
+ color: #2b542c;
+}
+.text-info {
+ color: #31708f;
+}
+a.text-info:hover {
+ color: #245269;
+}
+.text-warning {
+ color: #8a6d3b;
+}
+a.text-warning:hover {
+ color: #66512c;
+}
+.text-danger {
+ color: #a94442;
+}
+a.text-danger:hover {
+ color: #843534;
+}
+.bg-primary {
+ color: #fff;
+ background-color: #337ab7;
+}
+a.bg-primary:hover {
+ background-color: #286090;
+}
+.bg-success {
+ background-color: #dff0d8;
+}
+a.bg-success:hover {
+ background-color: #c1e2b3;
+}
+.bg-info {
+ background-color: #d9edf7;
+}
+a.bg-info:hover {
+ background-color: #afd9ee;
+}
+.bg-warning {
+ background-color: #fcf8e3;
+}
+a.bg-warning:hover {
+ background-color: #f7ecb5;
+}
+.bg-danger {
+ background-color: #f2dede;
+}
+a.bg-danger:hover {
+ background-color: #e4b9b9;
+}
+.page-header {
+ padding-bottom: 9px;
+ margin: 40px 0 20px;
+ border-bottom: 1px solid #eee;
+}
+ul,
+ol {
+ margin-top: 0;
+ margin-bottom: 10px;
+}
+ul ul,
+ol ul,
+ul ol,
+ol ol {
+ margin-bottom: 0;
+}
+.list-unstyled {
+ padding-left: 0;
+ list-style: none;
+}
+.list-inline {
+ padding-left: 0;
+ margin-left: -5px;
+ list-style: none;
+}
+.list-inline > li {
+ display: inline-block;
+ padding-right: 5px;
+ padding-left: 5px;
+}
+dl {
+ margin-top: 0;
+ margin-bottom: 20px;
+}
+dt,
+dd {
+ line-height: 1.42857143;
+}
+dt {
+ font-weight: bold;
+}
+dd {
+ margin-left: 0;
+}
+@media (min-width: 768px) {
+ .dl-horizontal dt {
+ float: left;
+ width: 160px;
+ overflow: hidden;
+ clear: left;
+ text-align: right;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .dl-horizontal dd {
+ margin-left: 180px;
+ }
+}
+abbr[title],
+abbr[data-original-title] {
+ cursor: help;
+ border-bottom: 1px dotted #777;
+}
+.initialism {
+ font-size: 90%;
+ text-transform: uppercase;
+}
+blockquote {
+ padding: 10px 20px;
+ margin: 0 0 20px;
+ font-size: 17.5px;
+ border-left: 5px solid #eee;
+}
+blockquote p:last-child,
+blockquote ul:last-child,
+blockquote ol:last-child {
+ margin-bottom: 0;
+}
+blockquote footer,
+blockquote small,
+blockquote .small {
+ display: block;
+ font-size: 80%;
+ line-height: 1.42857143;
+ color: #777;
+}
+blockquote footer:before,
+blockquote small:before,
+blockquote .small:before {
+ content: '\2014 \00A0';
+}
+.blockquote-reverse,
+blockquote.pull-right {
+ padding-right: 15px;
+ padding-left: 0;
+ text-align: right;
+ border-right: 5px solid #eee;
+ border-left: 0;
+}
+.blockquote-reverse footer:before,
+blockquote.pull-right footer:before,
+.blockquote-reverse small:before,
+blockquote.pull-right small:before,
+.blockquote-reverse .small:before,
+blockquote.pull-right .small:before {
+ content: '';
+}
+.blockquote-reverse footer:after,
+blockquote.pull-right footer:after,
+.blockquote-reverse small:after,
+blockquote.pull-right small:after,
+.blockquote-reverse .small:after,
+blockquote.pull-right .small:after {
+ content: '\00A0 \2014';
+}
+address {
+ margin-bottom: 20px;
+ font-style: normal;
+ line-height: 1.42857143;
+}
+code,
+kbd,
+pre,
+samp {
+ font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
+}
+code {
+ padding: 2px 4px;
+ font-size: 90%;
+ color: #c7254e;
+ background-color: #f9f2f4;
+ border-radius: 4px;
+}
+kbd {
+ padding: 2px 4px;
+ font-size: 90%;
+ color: #fff;
+ background-color: #333;
+ border-radius: 3px;
+ -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
+ box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
+}
+kbd kbd {
+ padding: 0;
+ font-size: 100%;
+ font-weight: bold;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+}
+pre {
+ display: block;
+ padding: 9.5px;
+ margin: 0 0 10px;
+ font-size: 13px;
+ line-height: 1.42857143;
+ color: #333;
+ word-break: break-all;
+ word-wrap: break-word;
+ background-color: #f5f5f5;
+ border: 1px solid #ccc;
+ border-radius: 4px;
+}
+pre code {
+ padding: 0;
+ font-size: inherit;
+ color: inherit;
+ white-space: pre-wrap;
+ background-color: transparent;
+ border-radius: 0;
+}
+.pre-scrollable {
+ max-height: 340px;
+ overflow-y: scroll;
+}
+.container {
+ padding-right: 15px;
+ padding-left: 15px;
+ margin-right: auto;
+ margin-left: auto;
+}
+@media (min-width: 768px) {
+ .container {
+ width: 750px;
+ }
+}
+@media (min-width: 992px) {
+ .container {
+ width: 970px;
+ }
+}
+@media (min-width: 1200px) {
+ .container {
+ width: 1170px;
+ }
+}
+.container-fluid {
+ padding-right: 15px;
+ padding-left: 15px;
+ margin-right: auto;
+ margin-left: auto;
+}
+.row {
+ margin-right: -15px;
+ margin-left: -15px;
+}
+.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
+ position: relative;
+ min-height: 1px;
+ padding-right: 15px;
+ padding-left: 15px;
+}
+.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 {
+ float: left;
+}
+.col-xs-12 {
+ width: 100%;
+}
+.col-xs-11 {
+ width: 91.66666667%;
+}
+.col-xs-10 {
+ width: 83.33333333%;
+}
+.col-xs-9 {
+ width: 75%;
+}
+.col-xs-8 {
+ width: 66.66666667%;
+}
+.col-xs-7 {
+ width: 58.33333333%;
+}
+.col-xs-6 {
+ width: 50%;
+}
+.col-xs-5 {
+ width: 41.66666667%;
+}
+.col-xs-4 {
+ width: 33.33333333%;
+}
+.col-xs-3 {
+ width: 25%;
+}
+.col-xs-2 {
+ width: 16.66666667%;
+}
+.col-xs-1 {
+ width: 8.33333333%;
+}
+.col-xs-pull-12 {
+ right: 100%;
+}
+.col-xs-pull-11 {
+ right: 91.66666667%;
+}
+.col-xs-pull-10 {
+ right: 83.33333333%;
+}
+.col-xs-pull-9 {
+ right: 75%;
+}
+.col-xs-pull-8 {
+ right: 66.66666667%;
+}
+.col-xs-pull-7 {
+ right: 58.33333333%;
+}
+.col-xs-pull-6 {
+ right: 50%;
+}
+.col-xs-pull-5 {
+ right: 41.66666667%;
+}
+.col-xs-pull-4 {
+ right: 33.33333333%;
+}
+.col-xs-pull-3 {
+ right: 25%;
+}
+.col-xs-pull-2 {
+ right: 16.66666667%;
+}
+.col-xs-pull-1 {
+ right: 8.33333333%;
+}
+.col-xs-pull-0 {
+ right: auto;
+}
+.col-xs-push-12 {
+ left: 100%;
+}
+.col-xs-push-11 {
+ left: 91.66666667%;
+}
+.col-xs-push-10 {
+ left: 83.33333333%;
+}
+.col-xs-push-9 {
+ left: 75%;
+}
+.col-xs-push-8 {
+ left: 66.66666667%;
+}
+.col-xs-push-7 {
+ left: 58.33333333%;
+}
+.col-xs-push-6 {
+ left: 50%;
+}
+.col-xs-push-5 {
+ left: 41.66666667%;
+}
+.col-xs-push-4 {
+ left: 33.33333333%;
+}
+.col-xs-push-3 {
+ left: 25%;
+}
+.col-xs-push-2 {
+ left: 16.66666667%;
+}
+.col-xs-push-1 {
+ left: 8.33333333%;
+}
+.col-xs-push-0 {
+ left: auto;
+}
+.col-xs-offset-12 {
+ margin-left: 100%;
+}
+.col-xs-offset-11 {
+ margin-left: 91.66666667%;
+}
+.col-xs-offset-10 {
+ margin-left: 83.33333333%;
+}
+.col-xs-offset-9 {
+ margin-left: 75%;
+}
+.col-xs-offset-8 {
+ margin-left: 66.66666667%;
+}
+.col-xs-offset-7 {
+ margin-left: 58.33333333%;
+}
+.col-xs-offset-6 {
+ margin-left: 50%;
+}
+.col-xs-offset-5 {
+ margin-left: 41.66666667%;
+}
+.col-xs-offset-4 {
+ margin-left: 33.33333333%;
+}
+.col-xs-offset-3 {
+ margin-left: 25%;
+}
+.col-xs-offset-2 {
+ margin-left: 16.66666667%;
+}
+.col-xs-offset-1 {
+ margin-left: 8.33333333%;
+}
+.col-xs-offset-0 {
+ margin-left: 0;
+}
+@media (min-width: 768px) {
+ .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
+ float: left;
+ }
+ .col-sm-12 {
+ width: 100%;
+ }
+ .col-sm-11 {
+ width: 91.66666667%;
+ }
+ .col-sm-10 {
+ width: 83.33333333%;
+ }
+ .col-sm-9 {
+ width: 75%;
+ }
+ .col-sm-8 {
+ width: 66.66666667%;
+ }
+ .col-sm-7 {
+ width: 58.33333333%;
+ }
+ .col-sm-6 {
+ width: 50%;
+ }
+ .col-sm-5 {
+ width: 41.66666667%;
+ }
+ .col-sm-4 {
+ width: 33.33333333%;
+ }
+ .col-sm-3 {
+ width: 25%;
+ }
+ .col-sm-2 {
+ width: 16.66666667%;
+ }
+ .col-sm-1 {
+ width: 8.33333333%;
+ }
+ .col-sm-pull-12 {
+ right: 100%;
+ }
+ .col-sm-pull-11 {
+ right: 91.66666667%;
+ }
+ .col-sm-pull-10 {
+ right: 83.33333333%;
+ }
+ .col-sm-pull-9 {
+ right: 75%;
+ }
+ .col-sm-pull-8 {
+ right: 66.66666667%;
+ }
+ .col-sm-pull-7 {
+ right: 58.33333333%;
+ }
+ .col-sm-pull-6 {
+ right: 50%;
+ }
+ .col-sm-pull-5 {
+ right: 41.66666667%;
+ }
+ .col-sm-pull-4 {
+ right: 33.33333333%;
+ }
+ .col-sm-pull-3 {
+ right: 25%;
+ }
+ .col-sm-pull-2 {
+ right: 16.66666667%;
+ }
+ .col-sm-pull-1 {
+ right: 8.33333333%;
+ }
+ .col-sm-pull-0 {
+ right: auto;
+ }
+ .col-sm-push-12 {
+ left: 100%;
+ }
+ .col-sm-push-11 {
+ left: 91.66666667%;
+ }
+ .col-sm-push-10 {
+ left: 83.33333333%;
+ }
+ .col-sm-push-9 {
+ left: 75%;
+ }
+ .col-sm-push-8 {
+ left: 66.66666667%;
+ }
+ .col-sm-push-7 {
+ left: 58.33333333%;
+ }
+ .col-sm-push-6 {
+ left: 50%;
+ }
+ .col-sm-push-5 {
+ left: 41.66666667%;
+ }
+ .col-sm-push-4 {
+ left: 33.33333333%;
+ }
+ .col-sm-push-3 {
+ left: 25%;
+ }
+ .col-sm-push-2 {
+ left: 16.66666667%;
+ }
+ .col-sm-push-1 {
+ left: 8.33333333%;
+ }
+ .col-sm-push-0 {
+ left: auto;
+ }
+ .col-sm-offset-12 {
+ margin-left: 100%;
+ }
+ .col-sm-offset-11 {
+ margin-left: 91.66666667%;
+ }
+ .col-sm-offset-10 {
+ margin-left: 83.33333333%;
+ }
+ .col-sm-offset-9 {
+ margin-left: 75%;
+ }
+ .col-sm-offset-8 {
+ margin-left: 66.66666667%;
+ }
+ .col-sm-offset-7 {
+ margin-left: 58.33333333%;
+ }
+ .col-sm-offset-6 {
+ margin-left: 50%;
+ }
+ .col-sm-offset-5 {
+ margin-left: 41.66666667%;
+ }
+ .col-sm-offset-4 {
+ margin-left: 33.33333333%;
+ }
+ .col-sm-offset-3 {
+ margin-left: 25%;
+ }
+ .col-sm-offset-2 {
+ margin-left: 16.66666667%;
+ }
+ .col-sm-offset-1 {
+ margin-left: 8.33333333%;
+ }
+ .col-sm-offset-0 {
+ margin-left: 0;
+ }
+}
+@media (min-width: 992px) {
+ .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
+ float: left;
+ }
+ .col-md-12 {
+ width: 100%;
+ }
+ .col-md-11 {
+ width: 91.66666667%;
+ }
+ .col-md-10 {
+ width: 83.33333333%;
+ }
+ .col-md-9 {
+ width: 75%;
+ }
+ .col-md-8 {
+ width: 66.66666667%;
+ }
+ .col-md-7 {
+ width: 58.33333333%;
+ }
+ .col-md-6 {
+ width: 50%;
+ }
+ .col-md-5 {
+ width: 41.66666667%;
+ }
+ .col-md-4 {
+ width: 33.33333333%;
+ }
+ .col-md-3 {
+ width: 25%;
+ }
+ .col-md-2 {
+ width: 16.66666667%;
+ }
+ .col-md-1 {
+ width: 8.33333333%;
+ }
+ .col-md-pull-12 {
+ right: 100%;
+ }
+ .col-md-pull-11 {
+ right: 91.66666667%;
+ }
+ .col-md-pull-10 {
+ right: 83.33333333%;
+ }
+ .col-md-pull-9 {
+ right: 75%;
+ }
+ .col-md-pull-8 {
+ right: 66.66666667%;
+ }
+ .col-md-pull-7 {
+ right: 58.33333333%;
+ }
+ .col-md-pull-6 {
+ right: 50%;
+ }
+ .col-md-pull-5 {
+ right: 41.66666667%;
+ }
+ .col-md-pull-4 {
+ right: 33.33333333%;
+ }
+ .col-md-pull-3 {
+ right: 25%;
+ }
+ .col-md-pull-2 {
+ right: 16.66666667%;
+ }
+ .col-md-pull-1 {
+ right: 8.33333333%;
+ }
+ .col-md-pull-0 {
+ right: auto;
+ }
+ .col-md-push-12 {
+ left: 100%;
+ }
+ .col-md-push-11 {
+ left: 91.66666667%;
+ }
+ .col-md-push-10 {
+ left: 83.33333333%;
+ }
+ .col-md-push-9 {
+ left: 75%;
+ }
+ .col-md-push-8 {
+ left: 66.66666667%;
+ }
+ .col-md-push-7 {
+ left: 58.33333333%;
+ }
+ .col-md-push-6 {
+ left: 50%;
+ }
+ .col-md-push-5 {
+ left: 41.66666667%;
+ }
+ .col-md-push-4 {
+ left: 33.33333333%;
+ }
+ .col-md-push-3 {
+ left: 25%;
+ }
+ .col-md-push-2 {
+ left: 16.66666667%;
+ }
+ .col-md-push-1 {
+ left: 8.33333333%;
+ }
+ .col-md-push-0 {
+ left: auto;
+ }
+ .col-md-offset-12 {
+ margin-left: 100%;
+ }
+ .col-md-offset-11 {
+ margin-left: 91.66666667%;
+ }
+ .col-md-offset-10 {
+ margin-left: 83.33333333%;
+ }
+ .col-md-offset-9 {
+ margin-left: 75%;
+ }
+ .col-md-offset-8 {
+ margin-left: 66.66666667%;
+ }
+ .col-md-offset-7 {
+ margin-left: 58.33333333%;
+ }
+ .col-md-offset-6 {
+ margin-left: 50%;
+ }
+ .col-md-offset-5 {
+ margin-left: 41.66666667%;
+ }
+ .col-md-offset-4 {
+ margin-left: 33.33333333%;
+ }
+ .col-md-offset-3 {
+ margin-left: 25%;
+ }
+ .col-md-offset-2 {
+ margin-left: 16.66666667%;
+ }
+ .col-md-offset-1 {
+ margin-left: 8.33333333%;
+ }
+ .col-md-offset-0 {
+ margin-left: 0;
+ }
+}
+@media (min-width: 1200px) {
+ .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {
+ float: left;
+ }
+ .col-lg-12 {
+ width: 100%;
+ }
+ .col-lg-11 {
+ width: 91.66666667%;
+ }
+ .col-lg-10 {
+ width: 83.33333333%;
+ }
+ .col-lg-9 {
+ width: 75%;
+ }
+ .col-lg-8 {
+ width: 66.66666667%;
+ }
+ .col-lg-7 {
+ width: 58.33333333%;
+ }
+ .col-lg-6 {
+ width: 50%;
+ }
+ .col-lg-5 {
+ width: 41.66666667%;
+ }
+ .col-lg-4 {
+ width: 33.33333333%;
+ }
+ .col-lg-3 {
+ width: 25%;
+ }
+ .col-lg-2 {
+ width: 16.66666667%;
+ }
+ .col-lg-1 {
+ width: 8.33333333%;
+ }
+ .col-lg-pull-12 {
+ right: 100%;
+ }
+ .col-lg-pull-11 {
+ right: 91.66666667%;
+ }
+ .col-lg-pull-10 {
+ right: 83.33333333%;
+ }
+ .col-lg-pull-9 {
+ right: 75%;
+ }
+ .col-lg-pull-8 {
+ right: 66.66666667%;
+ }
+ .col-lg-pull-7 {
+ right: 58.33333333%;
+ }
+ .col-lg-pull-6 {
+ right: 50%;
+ }
+ .col-lg-pull-5 {
+ right: 41.66666667%;
+ }
+ .col-lg-pull-4 {
+ right: 33.33333333%;
+ }
+ .col-lg-pull-3 {
+ right: 25%;
+ }
+ .col-lg-pull-2 {
+ right: 16.66666667%;
+ }
+ .col-lg-pull-1 {
+ right: 8.33333333%;
+ }
+ .col-lg-pull-0 {
+ right: auto;
+ }
+ .col-lg-push-12 {
+ left: 100%;
+ }
+ .col-lg-push-11 {
+ left: 91.66666667%;
+ }
+ .col-lg-push-10 {
+ left: 83.33333333%;
+ }
+ .col-lg-push-9 {
+ left: 75%;
+ }
+ .col-lg-push-8 {
+ left: 66.66666667%;
+ }
+ .col-lg-push-7 {
+ left: 58.33333333%;
+ }
+ .col-lg-push-6 {
+ left: 50%;
+ }
+ .col-lg-push-5 {
+ left: 41.66666667%;
+ }
+ .col-lg-push-4 {
+ left: 33.33333333%;
+ }
+ .col-lg-push-3 {
+ left: 25%;
+ }
+ .col-lg-push-2 {
+ left: 16.66666667%;
+ }
+ .col-lg-push-1 {
+ left: 8.33333333%;
+ }
+ .col-lg-push-0 {
+ left: auto;
+ }
+ .col-lg-offset-12 {
+ margin-left: 100%;
+ }
+ .col-lg-offset-11 {
+ margin-left: 91.66666667%;
+ }
+ .col-lg-offset-10 {
+ margin-left: 83.33333333%;
+ }
+ .col-lg-offset-9 {
+ margin-left: 75%;
+ }
+ .col-lg-offset-8 {
+ margin-left: 66.66666667%;
+ }
+ .col-lg-offset-7 {
+ margin-left: 58.33333333%;
+ }
+ .col-lg-offset-6 {
+ margin-left: 50%;
+ }
+ .col-lg-offset-5 {
+ margin-left: 41.66666667%;
+ }
+ .col-lg-offset-4 {
+ margin-left: 33.33333333%;
+ }
+ .col-lg-offset-3 {
+ margin-left: 25%;
+ }
+ .col-lg-offset-2 {
+ margin-left: 16.66666667%;
+ }
+ .col-lg-offset-1 {
+ margin-left: 8.33333333%;
+ }
+ .col-lg-offset-0 {
+ margin-left: 0;
+ }
+}
+table {
+ background-color: transparent;
+}
+caption {
+ padding-top: 8px;
+ padding-bottom: 8px;
+ color: #777;
+ text-align: left;
+}
+th {
+ text-align: left;
+}
+.table {
+ width: 100%;
+ max-width: 100%;
+ margin-bottom: 20px;
+}
+.table > thead > tr > th,
+.table > tbody > tr > th,
+.table > tfoot > tr > th,
+.table > thead > tr > td,
+.table > tbody > tr > td,
+.table > tfoot > tr > td {
+ padding: 8px;
+ line-height: 1.42857143;
+ vertical-align: top;
+ border-top: 1px solid #ddd;
+}
+.table > thead > tr > th {
+ vertical-align: bottom;
+ border-bottom: 2px solid #ddd;
+}
+.table > caption + thead > tr:first-child > th,
+.table > colgroup + thead > tr:first-child > th,
+.table > thead:first-child > tr:first-child > th,
+.table > caption + thead > tr:first-child > td,
+.table > colgroup + thead > tr:first-child > td,
+.table > thead:first-child > tr:first-child > td {
+ border-top: 0;
+}
+.table > tbody + tbody {
+ border-top: 2px solid #ddd;
+}
+.table .table {
+ background-color: #fff;
+}
+.table-condensed > thead > tr > th,
+.table-condensed > tbody > tr > th,
+.table-condensed > tfoot > tr > th,
+.table-condensed > thead > tr > td,
+.table-condensed > tbody > tr > td,
+.table-condensed > tfoot > tr > td {
+ padding: 5px;
+}
+.table-bordered {
+ border: 1px solid #ddd;
+}
+.table-bordered > thead > tr > th,
+.table-bordered > tbody > tr > th,
+.table-bordered > tfoot > tr > th,
+.table-bordered > thead > tr > td,
+.table-bordered > tbody > tr > td,
+.table-bordered > tfoot > tr > td {
+ border: 1px solid #ddd;
+}
+.table-bordered > thead > tr > th,
+.table-bordered > thead > tr > td {
+ border-bottom-width: 2px;
+}
+.table-striped > tbody > tr:nth-of-type(odd) {
+ background-color: #f9f9f9;
+}
+.table-hover > tbody > tr:hover {
+ background-color: #f5f5f5;
+}
+table col[class*="col-"] {
+ position: static;
+ display: table-column;
+ float: none;
+}
+table td[class*="col-"],
+table th[class*="col-"] {
+ position: static;
+ display: table-cell;
+ float: none;
+}
+.table > thead > tr > td.active,
+.table > tbody > tr > td.active,
+.table > tfoot > tr > td.active,
+.table > thead > tr > th.active,
+.table > tbody > tr > th.active,
+.table > tfoot > tr > th.active,
+.table > thead > tr.active > td,
+.table > tbody > tr.active > td,
+.table > tfoot > tr.active > td,
+.table > thead > tr.active > th,
+.table > tbody > tr.active > th,
+.table > tfoot > tr.active > th {
+ background-color: #f5f5f5;
+}
+.table-hover > tbody > tr > td.active:hover,
+.table-hover > tbody > tr > th.active:hover,
+.table-hover > tbody > tr.active:hover > td,
+.table-hover > tbody > tr:hover > .active,
+.table-hover > tbody > tr.active:hover > th {
+ background-color: #e8e8e8;
+}
+.table > thead > tr > td.success,
+.table > tbody > tr > td.success,
+.table > tfoot > tr > td.success,
+.table > thead > tr > th.success,
+.table > tbody > tr > th.success,
+.table > tfoot > tr > th.success,
+.table > thead > tr.success > td,
+.table > tbody > tr.success > td,
+.table > tfoot > tr.success > td,
+.table > thead > tr.success > th,
+.table > tbody > tr.success > th,
+.table > tfoot > tr.success > th {
+ background-color: #dff0d8;
+}
+.table-hover > tbody > tr > td.success:hover,
+.table-hover > tbody > tr > th.success:hover,
+.table-hover > tbody > tr.success:hover > td,
+.table-hover > tbody > tr:hover > .success,
+.table-hover > tbody > tr.success:hover > th {
+ background-color: #d0e9c6;
+}
+.table > thead > tr > td.info,
+.table > tbody > tr > td.info,
+.table > tfoot > tr > td.info,
+.table > thead > tr > th.info,
+.table > tbody > tr > th.info,
+.table > tfoot > tr > th.info,
+.table > thead > tr.info > td,
+.table > tbody > tr.info > td,
+.table > tfoot > tr.info > td,
+.table > thead > tr.info > th,
+.table > tbody > tr.info > th,
+.table > tfoot > tr.info > th {
+ background-color: #d9edf7;
+}
+.table-hover > tbody > tr > td.info:hover,
+.table-hover > tbody > tr > th.info:hover,
+.table-hover > tbody > tr.info:hover > td,
+.table-hover > tbody > tr:hover > .info,
+.table-hover > tbody > tr.info:hover > th {
+ background-color: #c4e3f3;
+}
+.table > thead > tr > td.warning,
+.table > tbody > tr > td.warning,
+.table > tfoot > tr > td.warning,
+.table > thead > tr > th.warning,
+.table > tbody > tr > th.warning,
+.table > tfoot > tr > th.warning,
+.table > thead > tr.warning > td,
+.table > tbody > tr.warning > td,
+.table > tfoot > tr.warning > td,
+.table > thead > tr.warning > th,
+.table > tbody > tr.warning > th,
+.table > tfoot > tr.warning > th {
+ background-color: #fcf8e3;
+}
+.table-hover > tbody > tr > td.warning:hover,
+.table-hover > tbody > tr > th.warning:hover,
+.table-hover > tbody > tr.warning:hover > td,
+.table-hover > tbody > tr:hover > .warning,
+.table-hover > tbody > tr.warning:hover > th {
+ background-color: #faf2cc;
+}
+.table > thead > tr > td.danger,
+.table > tbody > tr > td.danger,
+.table > tfoot > tr > td.danger,
+.table > thead > tr > th.danger,
+.table > tbody > tr > th.danger,
+.table > tfoot > tr > th.danger,
+.table > thead > tr.danger > td,
+.table > tbody > tr.danger > td,
+.table > tfoot > tr.danger > td,
+.table > thead > tr.danger > th,
+.table > tbody > tr.danger > th,
+.table > tfoot > tr.danger > th {
+ background-color: #f2dede;
+}
+.table-hover > tbody > tr > td.danger:hover,
+.table-hover > tbody > tr > th.danger:hover,
+.table-hover > tbody > tr.danger:hover > td,
+.table-hover > tbody > tr:hover > .danger,
+.table-hover > tbody > tr.danger:hover > th {
+ background-color: #ebcccc;
+}
+.table-responsive {
+ min-height: .01%;
+ overflow-x: auto;
+}
+@media screen and (max-width: 767px) {
+ .table-responsive {
+ width: 100%;
+ margin-bottom: 15px;
+ overflow-y: hidden;
+ -ms-overflow-style: -ms-autohiding-scrollbar;
+ border: 1px solid #ddd;
+ }
+ .table-responsive > .table {
+ margin-bottom: 0;
+ }
+ .table-responsive > .table > thead > tr > th,
+ .table-responsive > .table > tbody > tr > th,
+ .table-responsive > .table > tfoot > tr > th,
+ .table-responsive > .table > thead > tr > td,
+ .table-responsive > .table > tbody > tr > td,
+ .table-responsive > .table > tfoot > tr > td {
+ white-space: nowrap;
+ }
+ .table-responsive > .table-bordered {
+ border: 0;
+ }
+ .table-responsive > .table-bordered > thead > tr > th:first-child,
+ .table-responsive > .table-bordered > tbody > tr > th:first-child,
+ .table-responsive > .table-bordered > tfoot > tr > th:first-child,
+ .table-responsive > .table-bordered > thead > tr > td:first-child,
+ .table-responsive > .table-bordered > tbody > tr > td:first-child,
+ .table-responsive > .table-bordered > tfoot > tr > td:first-child {
+ border-left: 0;
+ }
+ .table-responsive > .table-bordered > thead > tr > th:last-child,
+ .table-responsive > .table-bordered > tbody > tr > th:last-child,
+ .table-responsive > .table-bordered > tfoot > tr > th:last-child,
+ .table-responsive > .table-bordered > thead > tr > td:last-child,
+ .table-responsive > .table-bordered > tbody > tr > td:last-child,
+ .table-responsive > .table-bordered > tfoot > tr > td:last-child {
+ border-right: 0;
+ }
+ .table-responsive > .table-bordered > tbody > tr:last-child > th,
+ .table-responsive > .table-bordered > tfoot > tr:last-child > th,
+ .table-responsive > .table-bordered > tbody > tr:last-child > td,
+ .table-responsive > .table-bordered > tfoot > tr:last-child > td {
+ border-bottom: 0;
+ }
+}
+fieldset {
+ min-width: 0;
+ padding: 0;
+ margin: 0;
+ border: 0;
+}
+legend {
+ display: block;
+ width: 100%;
+ padding: 0;
+ margin-bottom: 20px;
+ font-size: 21px;
+ line-height: inherit;
+ color: #333;
+ border: 0;
+ border-bottom: 1px solid #e5e5e5;
+}
+label {
+ display: inline-block;
+ max-width: 100%;
+ margin-bottom: 5px;
+ font-weight: bold;
+}
+input[type="search"] {
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+}
+input[type="radio"],
+input[type="checkbox"] {
+ margin: 4px 0 0;
+ margin-top: 1px \9;
+ line-height: normal;
+}
+input[type="file"] {
+ display: block;
+}
+input[type="range"] {
+ display: block;
+ width: 100%;
+}
+select[multiple],
+select[size] {
+ height: auto;
+}
+input[type="file"]:focus,
+input[type="radio"]:focus,
+input[type="checkbox"]:focus {
+ outline: thin dotted;
+ outline: 5px auto -webkit-focus-ring-color;
+ outline-offset: -2px;
+}
+output {
+ display: block;
+ padding-top: 7px;
+ font-size: 14px;
+ line-height: 1.42857143;
+ color: #555;
+}
+.form-control {
+ display: block;
+ width: 100%;
+ height: 34px;
+ padding: 6px 12px;
+ font-size: 14px;
+ line-height: 1.42857143;
+ color: #555;
+ background-color: #fff;
+ background-image: none;
+ border: 1px solid #ccc;
+ border-radius: 4px;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+ -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
+ -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
+ transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
+}
+.form-control:focus {
+ border-color: #66afe9;
+ outline: 0;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
+ box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
+}
+.form-control::-moz-placeholder {
+ color: #999;
+ opacity: 1;
+}
+.form-control:-ms-input-placeholder {
+ color: #999;
+}
+.form-control::-webkit-input-placeholder {
+ color: #999;
+}
+.form-control[disabled],
+.form-control[readonly],
+fieldset[disabled] .form-control {
+ background-color: #eee;
+ opacity: 1;
+}
+.form-control[disabled],
+fieldset[disabled] .form-control {
+ cursor: not-allowed;
+}
+textarea.form-control {
+ height: auto;
+}
+input[type="search"] {
+ -webkit-appearance: none;
+}
+@media screen and (-webkit-min-device-pixel-ratio: 0) {
+ input[type="date"],
+ input[type="time"],
+ input[type="datetime-local"],
+ input[type="month"] {
+ line-height: 34px;
+ }
+ input[type="date"].input-sm,
+ input[type="time"].input-sm,
+ input[type="datetime-local"].input-sm,
+ input[type="month"].input-sm,
+ .input-group-sm input[type="date"],
+ .input-group-sm input[type="time"],
+ .input-group-sm input[type="datetime-local"],
+ .input-group-sm input[type="month"] {
+ line-height: 30px;
+ }
+ input[type="date"].input-lg,
+ input[type="time"].input-lg,
+ input[type="datetime-local"].input-lg,
+ input[type="month"].input-lg,
+ .input-group-lg input[type="date"],
+ .input-group-lg input[type="time"],
+ .input-group-lg input[type="datetime-local"],
+ .input-group-lg input[type="month"] {
+ line-height: 46px;
+ }
+}
+.form-group {
+ margin-bottom: 15px;
+}
+.radio,
+.checkbox {
+ position: relative;
+ display: block;
+ margin-top: 10px;
+ margin-bottom: 10px;
+}
+.radio label,
+.checkbox label {
+ min-height: 20px;
+ padding-left: 20px;
+ margin-bottom: 0;
+ font-weight: normal;
+ cursor: pointer;
+}
+.radio input[type="radio"],
+.radio-inline input[type="radio"],
+.checkbox input[type="checkbox"],
+.checkbox-inline input[type="checkbox"] {
+ position: absolute;
+ margin-top: 4px \9;
+ margin-left: -20px;
+}
+.radio + .radio,
+.checkbox + .checkbox {
+ margin-top: -5px;
+}
+.radio-inline,
+.checkbox-inline {
+ position: relative;
+ display: inline-block;
+ padding-left: 20px;
+ margin-bottom: 0;
+ font-weight: normal;
+ vertical-align: middle;
+ cursor: pointer;
+}
+.radio-inline + .radio-inline,
+.checkbox-inline + .checkbox-inline {
+ margin-top: 0;
+ margin-left: 10px;
+}
+input[type="radio"][disabled],
+input[type="checkbox"][disabled],
+input[type="radio"].disabled,
+input[type="checkbox"].disabled,
+fieldset[disabled] input[type="radio"],
+fieldset[disabled] input[type="checkbox"] {
+ cursor: not-allowed;
+}
+.radio-inline.disabled,
+.checkbox-inline.disabled,
+fieldset[disabled] .radio-inline,
+fieldset[disabled] .checkbox-inline {
+ cursor: not-allowed;
+}
+.radio.disabled label,
+.checkbox.disabled label,
+fieldset[disabled] .radio label,
+fieldset[disabled] .checkbox label {
+ cursor: not-allowed;
+}
+.form-control-static {
+ min-height: 34px;
+ padding-top: 7px;
+ padding-bottom: 7px;
+ margin-bottom: 0;
+}
+.form-control-static.input-lg,
+.form-control-static.input-sm {
+ padding-right: 0;
+ padding-left: 0;
+}
+.input-sm {
+ height: 30px;
+ padding: 5px 10px;
+ font-size: 12px;
+ line-height: 1.5;
+ border-radius: 3px;
+}
+select.input-sm {
+ height: 30px;
+ line-height: 30px;
+}
+textarea.input-sm,
+select[multiple].input-sm {
+ height: auto;
+}
+.form-group-sm .form-control {
+ height: 30px;
+ padding: 5px 10px;
+ font-size: 12px;
+ line-height: 1.5;
+ border-radius: 3px;
+}
+select.form-group-sm .form-control {
+ height: 30px;
+ line-height: 30px;
+}
+textarea.form-group-sm .form-control,
+select[multiple].form-group-sm .form-control {
+ height: auto;
+}
+.form-group-sm .form-control-static {
+ height: 30px;
+ min-height: 32px;
+ padding: 5px 10px;
+ font-size: 12px;
+ line-height: 1.5;
+}
+.input-lg {
+ height: 46px;
+ padding: 10px 16px;
+ font-size: 18px;
+ line-height: 1.3333333;
+ border-radius: 6px;
+}
+select.input-lg {
+ height: 46px;
+ line-height: 46px;
+}
+textarea.input-lg,
+select[multiple].input-lg {
+ height: auto;
+}
+.form-group-lg .form-control {
+ height: 46px;
+ padding: 10px 16px;
+ font-size: 18px;
+ line-height: 1.3333333;
+ border-radius: 6px;
+}
+select.form-group-lg .form-control {
+ height: 46px;
+ line-height: 46px;
+}
+textarea.form-group-lg .form-control,
+select[multiple].form-group-lg .form-control {
+ height: auto;
+}
+.form-group-lg .form-control-static {
+ height: 46px;
+ min-height: 38px;
+ padding: 10px 16px;
+ font-size: 18px;
+ line-height: 1.3333333;
+}
+.has-feedback {
+ position: relative;
+}
+.has-feedback .form-control {
+ padding-right: 42.5px;
+}
+.form-control-feedback {
+ position: absolute;
+ top: 0;
+ right: 0;
+ z-index: 2;
+ display: block;
+ width: 34px;
+ height: 34px;
+ line-height: 34px;
+ text-align: center;
+ pointer-events: none;
+}
+.input-lg + .form-control-feedback {
+ width: 46px;
+ height: 46px;
+ line-height: 46px;
+}
+.input-sm + .form-control-feedback {
+ width: 30px;
+ height: 30px;
+ line-height: 30px;
+}
+.has-success .help-block,
+.has-success .control-label,
+.has-success .radio,
+.has-success .checkbox,
+.has-success .radio-inline,
+.has-success .checkbox-inline,
+.has-success.radio label,
+.has-success.checkbox label,
+.has-success.radio-inline label,
+.has-success.checkbox-inline label {
+ color: #3c763d;
+}
+.has-success .form-control {
+ border-color: #3c763d;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+}
+.has-success .form-control:focus {
+ border-color: #2b542c;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
+}
+.has-success .input-group-addon {
+ color: #3c763d;
+ background-color: #dff0d8;
+ border-color: #3c763d;
+}
+.has-success .form-control-feedback {
+ color: #3c763d;
+}
+.has-warning .help-block,
+.has-warning .control-label,
+.has-warning .radio,
+.has-warning .checkbox,
+.has-warning .radio-inline,
+.has-warning .checkbox-inline,
+.has-warning.radio label,
+.has-warning.checkbox label,
+.has-warning.radio-inline label,
+.has-warning.checkbox-inline label {
+ color: #8a6d3b;
+}
+.has-warning .form-control {
+ border-color: #8a6d3b;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+}
+.has-warning .form-control:focus {
+ border-color: #66512c;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
+}
+.has-warning .input-group-addon {
+ color: #8a6d3b;
+ background-color: #fcf8e3;
+ border-color: #8a6d3b;
+}
+.has-warning .form-control-feedback {
+ color: #8a6d3b;
+}
+.has-error .help-block,
+.has-error .control-label,
+.has-error .radio,
+.has-error .checkbox,
+.has-error .radio-inline,
+.has-error .checkbox-inline,
+.has-error.radio label,
+.has-error.checkbox label,
+.has-error.radio-inline label,
+.has-error.checkbox-inline label {
+ color: #a94442;
+}
+.has-error .form-control {
+ border-color: #a94442;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
+}
+.has-error .form-control:focus {
+ border-color: #843534;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
+}
+.has-error .input-group-addon {
+ color: #a94442;
+ background-color: #f2dede;
+ border-color: #a94442;
+}
+.has-error .form-control-feedback {
+ color: #a94442;
+}
+.has-feedback label ~ .form-control-feedback {
+ top: 25px;
+}
+.has-feedback label.sr-only ~ .form-control-feedback {
+ top: 0;
+}
+.help-block {
+ display: block;
+ margin-top: 5px;
+ margin-bottom: 10px;
+ color: #737373;
+}
+@media (min-width: 768px) {
+ .form-inline .form-group {
+ display: inline-block;
+ margin-bottom: 0;
+ vertical-align: middle;
+ }
+ .form-inline .form-control {
+ display: inline-block;
+ width: auto;
+ vertical-align: middle;
+ }
+ .form-inline .form-control-static {
+ display: inline-block;
+ }
+ .form-inline .input-group {
+ display: inline-table;
+ vertical-align: middle;
+ }
+ .form-inline .input-group .input-group-addon,
+ .form-inline .input-group .input-group-btn,
+ .form-inline .input-group .form-control {
+ width: auto;
+ }
+ .form-inline .input-group > .form-control {
+ width: 100%;
+ }
+ .form-inline .control-label {
+ margin-bottom: 0;
+ vertical-align: middle;
+ }
+ .form-inline .radio,
+ .form-inline .checkbox {
+ display: inline-block;
+ margin-top: 0;
+ margin-bottom: 0;
+ vertical-align: middle;
+ }
+ .form-inline .radio label,
+ .form-inline .checkbox label {
+ padding-left: 0;
+ }
+ .form-inline .radio input[type="radio"],
+ .form-inline .checkbox input[type="checkbox"] {
+ position: relative;
+ margin-left: 0;
+ }
+ .form-inline .has-feedback .form-control-feedback {
+ top: 0;
+ }
+}
+.form-horizontal .radio,
+.form-horizontal .checkbox,
+.form-horizontal .radio-inline,
+.form-horizontal .checkbox-inline {
+ padding-top: 7px;
+ margin-top: 0;
+ margin-bottom: 0;
+}
+.form-horizontal .radio,
+.form-horizontal .checkbox {
+ min-height: 27px;
+}
+.form-horizontal .form-group {
+ margin-right: -15px;
+ margin-left: -15px;
+}
+@media (min-width: 768px) {
+ .form-horizontal .control-label {
+ padding-top: 7px;
+ margin-bottom: 0;
+ text-align: right;
+ }
+}
+.form-horizontal .has-feedback .form-control-feedback {
+ right: 15px;
+}
+@media (min-width: 768px) {
+ .form-horizontal .form-group-lg .control-label {
+ padding-top: 14.333333px;
+ }
+}
+@media (min-width: 768px) {
+ .form-horizontal .form-group-sm .control-label {
+ padding-top: 6px;
+ }
+}
+.btn {
+ display: inline-block;
+ padding: 6px 12px;
+ margin-bottom: 0;
+ font-size: 14px;
+ font-weight: normal;
+ line-height: 1.42857143;
+ text-align: center;
+ white-space: nowrap;
+ vertical-align: middle;
+ -ms-touch-action: manipulation;
+ touch-action: manipulation;
+ cursor: pointer;
+ -webkit-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+ user-select: none;
+ background-image: none;
+ border: 1px solid transparent;
+ border-radius: 4px;
+}
+.btn:focus,
+.btn:active:focus,
+.btn.active:focus,
+.btn.focus,
+.btn:active.focus,
+.btn.active.focus {
+ outline: thin dotted;
+ outline: 5px auto -webkit-focus-ring-color;
+ outline-offset: -2px;
+}
+.btn:hover,
+.btn:focus,
+.btn.focus {
+ color: #333;
+ text-decoration: none;
+}
+.btn:active,
+.btn.active {
+ background-image: none;
+ outline: 0;
+ -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+ box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+}
+.btn.disabled,
+.btn[disabled],
+fieldset[disabled] .btn {
+ pointer-events: none;
+ cursor: not-allowed;
+ filter: alpha(opacity=65);
+ -webkit-box-shadow: none;
+ box-shadow: none;
+ opacity: .65;
+}
+.btn-default {
+ color: #333;
+ background-color: #fff;
+ border-color: #ccc;
+}
+.btn-default:hover,
+.btn-default:focus,
+.btn-default.focus,
+.btn-default:active,
+.btn-default.active,
+.open > .dropdown-toggle.btn-default {
+ color: #333;
+ background-color: #e6e6e6;
+ border-color: #adadad;
+}
+.btn-default:active,
+.btn-default.active,
+.open > .dropdown-toggle.btn-default {
+ background-image: none;
+}
+.btn-default.disabled,
+.btn-default[disabled],
+fieldset[disabled] .btn-default,
+.btn-default.disabled:hover,
+.btn-default[disabled]:hover,
+fieldset[disabled] .btn-default:hover,
+.btn-default.disabled:focus,
+.btn-default[disabled]:focus,
+fieldset[disabled] .btn-default:focus,
+.btn-default.disabled.focus,
+.btn-default[disabled].focus,
+fieldset[disabled] .btn-default.focus,
+.btn-default.disabled:active,
+.btn-default[disabled]:active,
+fieldset[disabled] .btn-default:active,
+.btn-default.disabled.active,
+.btn-default[disabled].active,
+fieldset[disabled] .btn-default.active {
+ background-color: #fff;
+ border-color: #ccc;
+}
+.btn-default .badge {
+ color: #fff;
+ background-color: #333;
+}
+.btn-primary {
+ color: #fff;
+ background-color: #337ab7;
+ border-color: #2e6da4;
+}
+.btn-primary:hover,
+.btn-primary:focus,
+.btn-primary.focus,
+.btn-primary:active,
+.btn-primary.active,
+.open > .dropdown-toggle.btn-primary {
+ color: #fff;
+ background-color: #286090;
+ border-color: #204d74;
+}
+.btn-primary:active,
+.btn-primary.active,
+.open > .dropdown-toggle.btn-primary {
+ background-image: none;
+}
+.btn-primary.disabled,
+.btn-primary[disabled],
+fieldset[disabled] .btn-primary,
+.btn-primary.disabled:hover,
+.btn-primary[disabled]:hover,
+fieldset[disabled] .btn-primary:hover,
+.btn-primary.disabled:focus,
+.btn-primary[disabled]:focus,
+fieldset[disabled] .btn-primary:focus,
+.btn-primary.disabled.focus,
+.btn-primary[disabled].focus,
+fieldset[disabled] .btn-primary.focus,
+.btn-primary.disabled:active,
+.btn-primary[disabled]:active,
+fieldset[disabled] .btn-primary:active,
+.btn-primary.disabled.active,
+.btn-primary[disabled].active,
+fieldset[disabled] .btn-primary.active {
+ background-color: #337ab7;
+ border-color: #2e6da4;
+}
+.btn-primary .badge {
+ color: #337ab7;
+ background-color: #fff;
+}
+.btn-success {
+ color: #fff;
+ background-color: #5cb85c;
+ border-color: #4cae4c;
+}
+.btn-success:hover,
+.btn-success:focus,
+.btn-success.focus,
+.btn-success:active,
+.btn-success.active,
+.open > .dropdown-toggle.btn-success {
+ color: #fff;
+ background-color: #449d44;
+ border-color: #398439;
+}
+.btn-success:active,
+.btn-success.active,
+.open > .dropdown-toggle.btn-success {
+ background-image: none;
+}
+.btn-success.disabled,
+.btn-success[disabled],
+fieldset[disabled] .btn-success,
+.btn-success.disabled:hover,
+.btn-success[disabled]:hover,
+fieldset[disabled] .btn-success:hover,
+.btn-success.disabled:focus,
+.btn-success[disabled]:focus,
+fieldset[disabled] .btn-success:focus,
+.btn-success.disabled.focus,
+.btn-success[disabled].focus,
+fieldset[disabled] .btn-success.focus,
+.btn-success.disabled:active,
+.btn-success[disabled]:active,
+fieldset[disabled] .btn-success:active,
+.btn-success.disabled.active,
+.btn-success[disabled].active,
+fieldset[disabled] .btn-success.active {
+ background-color: #5cb85c;
+ border-color: #4cae4c;
+}
+.btn-success .badge {
+ color: #5cb85c;
+ background-color: #fff;
+}
+.btn-info {
+ color: #fff;
+ background-color: #5bc0de;
+ border-color: #46b8da;
+}
+.btn-info:hover,
+.btn-info:focus,
+.btn-info.focus,
+.btn-info:active,
+.btn-info.active,
+.open > .dropdown-toggle.btn-info {
+ color: #fff;
+ background-color: #31b0d5;
+ border-color: #269abc;
+}
+.btn-info:active,
+.btn-info.active,
+.open > .dropdown-toggle.btn-info {
+ background-image: none;
+}
+.btn-info.disabled,
+.btn-info[disabled],
+fieldset[disabled] .btn-info,
+.btn-info.disabled:hover,
+.btn-info[disabled]:hover,
+fieldset[disabled] .btn-info:hover,
+.btn-info.disabled:focus,
+.btn-info[disabled]:focus,
+fieldset[disabled] .btn-info:focus,
+.btn-info.disabled.focus,
+.btn-info[disabled].focus,
+fieldset[disabled] .btn-info.focus,
+.btn-info.disabled:active,
+.btn-info[disabled]:active,
+fieldset[disabled] .btn-info:active,
+.btn-info.disabled.active,
+.btn-info[disabled].active,
+fieldset[disabled] .btn-info.active {
+ background-color: #5bc0de;
+ border-color: #46b8da;
+}
+.btn-info .badge {
+ color: #5bc0de;
+ background-color: #fff;
+}
+.btn-warning {
+ color: #fff;
+ background-color: #f0ad4e;
+ border-color: #eea236;
+}
+.btn-warning:hover,
+.btn-warning:focus,
+.btn-warning.focus,
+.btn-warning:active,
+.btn-warning.active,
+.open > .dropdown-toggle.btn-warning {
+ color: #fff;
+ background-color: #ec971f;
+ border-color: #d58512;
+}
+.btn-warning:active,
+.btn-warning.active,
+.open > .dropdown-toggle.btn-warning {
+ background-image: none;
+}
+.btn-warning.disabled,
+.btn-warning[disabled],
+fieldset[disabled] .btn-warning,
+.btn-warning.disabled:hover,
+.btn-warning[disabled]:hover,
+fieldset[disabled] .btn-warning:hover,
+.btn-warning.disabled:focus,
+.btn-warning[disabled]:focus,
+fieldset[disabled] .btn-warning:focus,
+.btn-warning.disabled.focus,
+.btn-warning[disabled].focus,
+fieldset[disabled] .btn-warning.focus,
+.btn-warning.disabled:active,
+.btn-warning[disabled]:active,
+fieldset[disabled] .btn-warning:active,
+.btn-warning.disabled.active,
+.btn-warning[disabled].active,
+fieldset[disabled] .btn-warning.active {
+ background-color: #f0ad4e;
+ border-color: #eea236;
+}
+.btn-warning .badge {
+ color: #f0ad4e;
+ background-color: #fff;
+}
+.btn-danger {
+ color: #fff;
+ background-color: #d9534f;
+ border-color: #d43f3a;
+}
+.btn-danger:hover,
+.btn-danger:focus,
+.btn-danger.focus,
+.btn-danger:active,
+.btn-danger.active,
+.open > .dropdown-toggle.btn-danger {
+ color: #fff;
+ background-color: #c9302c;
+ border-color: #ac2925;
+}
+.btn-danger:active,
+.btn-danger.active,
+.open > .dropdown-toggle.btn-danger {
+ background-image: none;
+}
+.btn-danger.disabled,
+.btn-danger[disabled],
+fieldset[disabled] .btn-danger,
+.btn-danger.disabled:hover,
+.btn-danger[disabled]:hover,
+fieldset[disabled] .btn-danger:hover,
+.btn-danger.disabled:focus,
+.btn-danger[disabled]:focus,
+fieldset[disabled] .btn-danger:focus,
+.btn-danger.disabled.focus,
+.btn-danger[disabled].focus,
+fieldset[disabled] .btn-danger.focus,
+.btn-danger.disabled:active,
+.btn-danger[disabled]:active,
+fieldset[disabled] .btn-danger:active,
+.btn-danger.disabled.active,
+.btn-danger[disabled].active,
+fieldset[disabled] .btn-danger.active {
+ background-color: #d9534f;
+ border-color: #d43f3a;
+}
+.btn-danger .badge {
+ color: #d9534f;
+ background-color: #fff;
+}
+.btn-link {
+ font-weight: normal;
+ color: #337ab7;
+ border-radius: 0;
+}
+.btn-link,
+.btn-link:active,
+.btn-link.active,
+.btn-link[disabled],
+fieldset[disabled] .btn-link {
+ background-color: transparent;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+}
+.btn-link,
+.btn-link:hover,
+.btn-link:focus,
+.btn-link:active {
+ border-color: transparent;
+}
+.btn-link:hover,
+.btn-link:focus {
+ color: #23527c;
+ text-decoration: underline;
+ background-color: transparent;
+}
+.btn-link[disabled]:hover,
+fieldset[disabled] .btn-link:hover,
+.btn-link[disabled]:focus,
+fieldset[disabled] .btn-link:focus {
+ color: #777;
+ text-decoration: none;
+}
+.btn-lg,
+.btn-group-lg > .btn {
+ padding: 10px 16px;
+ font-size: 18px;
+ line-height: 1.3333333;
+ border-radius: 6px;
+}
+.btn-sm,
+.btn-group-sm > .btn {
+ padding: 5px 10px;
+ font-size: 12px;
+ line-height: 1.5;
+ border-radius: 3px;
+}
+.btn-xs,
+.btn-group-xs > .btn {
+ padding: 1px 5px;
+ font-size: 12px;
+ line-height: 1.5;
+ border-radius: 3px;
+}
+.btn-block {
+ display: block;
+ width: 100%;
+}
+.btn-block + .btn-block {
+ margin-top: 5px;
+}
+input[type="submit"].btn-block,
+input[type="reset"].btn-block,
+input[type="button"].btn-block {
+ width: 100%;
+}
+.fade {
+ opacity: 0;
+ -webkit-transition: opacity .15s linear;
+ -o-transition: opacity .15s linear;
+ transition: opacity .15s linear;
+}
+.fade.in {
+ opacity: 1;
+}
+.collapse {
+ display: none;
+}
+.collapse.in {
+ display: block;
+}
+tr.collapse.in {
+ display: table-row;
+}
+tbody.collapse.in {
+ display: table-row-group;
+}
+.collapsing {
+ position: relative;
+ height: 0;
+ overflow: hidden;
+ -webkit-transition-timing-function: ease;
+ -o-transition-timing-function: ease;
+ transition-timing-function: ease;
+ -webkit-transition-duration: .35s;
+ -o-transition-duration: .35s;
+ transition-duration: .35s;
+ -webkit-transition-property: height, visibility;
+ -o-transition-property: height, visibility;
+ transition-property: height, visibility;
+}
+.caret {
+ display: inline-block;
+ width: 0;
+ height: 0;
+ margin-left: 2px;
+ vertical-align: middle;
+ border-top: 4px dashed;
+ border-right: 4px solid transparent;
+ border-left: 4px solid transparent;
+}
+.dropup,
+.dropdown {
+ position: relative;
+}
+.dropdown-toggle:focus {
+ outline: 0;
+}
+.dropdown-menu {
+ position: absolute;
+ top: 100%;
+ left: 0;
+ z-index: 1000;
+ display: none;
+ float: left;
+ min-width: 160px;
+ padding: 5px 0;
+ margin: 2px 0 0;
+ font-size: 14px;
+ text-align: left;
+ list-style: none;
+ background-color: #fff;
+ -webkit-background-clip: padding-box;
+ background-clip: padding-box;
+ border: 1px solid #ccc;
+ border: 1px solid rgba(0, 0, 0, .15);
+ border-radius: 4px;
+ -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
+ box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
+}
+.dropdown-menu.pull-right {
+ right: 0;
+ left: auto;
+}
+.dropdown-menu .divider {
+ height: 1px;
+ margin: 9px 0;
+ overflow: hidden;
+ background-color: #e5e5e5;
+}
+.dropdown-menu > li > a {
+ display: block;
+ padding: 3px 20px;
+ clear: both;
+ font-weight: normal;
+ line-height: 1.42857143;
+ color: #333;
+ white-space: nowrap;
+}
+.dropdown-menu > li > a:hover,
+.dropdown-menu > li > a:focus {
+ color: #262626;
+ text-decoration: none;
+ background-color: #f5f5f5;
+}
+.dropdown-menu > .active > a,
+.dropdown-menu > .active > a:hover,
+.dropdown-menu > .active > a:focus {
+ color: #fff;
+ text-decoration: none;
+ background-color: #337ab7;
+ outline: 0;
+}
+.dropdown-menu > .disabled > a,
+.dropdown-menu > .disabled > a:hover,
+.dropdown-menu > .disabled > a:focus {
+ color: #777;
+}
+.dropdown-menu > .disabled > a:hover,
+.dropdown-menu > .disabled > a:focus {
+ text-decoration: none;
+ cursor: not-allowed;
+ background-color: transparent;
+ background-image: none;
+ filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
+}
+.open > .dropdown-menu {
+ display: block;
+}
+.open > a {
+ outline: 0;
+}
+.dropdown-menu-right {
+ right: 0;
+ left: auto;
+}
+.dropdown-menu-left {
+ right: auto;
+ left: 0;
+}
+.dropdown-header {
+ display: block;
+ padding: 3px 20px;
+ font-size: 12px;
+ line-height: 1.42857143;
+ color: #777;
+ white-space: nowrap;
+}
+.dropdown-backdrop {
+ position: fixed;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ z-index: 990;
+}
+.pull-right > .dropdown-menu {
+ right: 0;
+ left: auto;
+}
+.dropup .caret,
+.navbar-fixed-bottom .dropdown .caret {
+ content: "";
+ border-top: 0;
+ border-bottom: 4px solid;
+}
+.dropup .dropdown-menu,
+.navbar-fixed-bottom .dropdown .dropdown-menu {
+ top: auto;
+ bottom: 100%;
+ margin-bottom: 2px;
+}
+@media (min-width: 768px) {
+ .navbar-right .dropdown-menu {
+ right: 0;
+ left: auto;
+ }
+ .navbar-right .dropdown-menu-left {
+ right: auto;
+ left: 0;
+ }
+}
+.btn-group,
+.btn-group-vertical {
+ position: relative;
+ display: inline-block;
+ vertical-align: middle;
+}
+.btn-group > .btn,
+.btn-group-vertical > .btn {
+ position: relative;
+ float: left;
+}
+.btn-group > .btn:hover,
+.btn-group-vertical > .btn:hover,
+.btn-group > .btn:focus,
+.btn-group-vertical > .btn:focus,
+.btn-group > .btn:active,
+.btn-group-vertical > .btn:active,
+.btn-group > .btn.active,
+.btn-group-vertical > .btn.active {
+ z-index: 2;
+}
+.btn-group .btn + .btn,
+.btn-group .btn + .btn-group,
+.btn-group .btn-group + .btn,
+.btn-group .btn-group + .btn-group {
+ margin-left: -1px;
+}
+.btn-toolbar {
+ margin-left: -5px;
+}
+.btn-toolbar .btn-group,
+.btn-toolbar .input-group {
+ float: left;
+}
+.btn-toolbar > .btn,
+.btn-toolbar > .btn-group,
+.btn-toolbar > .input-group {
+ margin-left: 5px;
+}
+.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
+ border-radius: 0;
+}
+.btn-group > .btn:first-child {
+ margin-left: 0;
+}
+.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+}
+.btn-group > .btn:last-child:not(:first-child),
+.btn-group > .dropdown-toggle:not(:first-child) {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+}
+.btn-group > .btn-group {
+ float: left;
+}
+.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
+ border-radius: 0;
+}
+.btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child,
+.btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+}
+.btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+}
+.btn-group .dropdown-toggle:active,
+.btn-group.open .dropdown-toggle {
+ outline: 0;
+}
+.btn-group > .btn + .dropdown-toggle {
+ padding-right: 8px;
+ padding-left: 8px;
+}
+.btn-group > .btn-lg + .dropdown-toggle {
+ padding-right: 12px;
+ padding-left: 12px;
+}
+.btn-group.open .dropdown-toggle {
+ -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+ box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
+}
+.btn-group.open .dropdown-toggle.btn-link {
+ -webkit-box-shadow: none;
+ box-shadow: none;
+}
+.btn .caret {
+ margin-left: 0;
+}
+.btn-lg .caret {
+ border-width: 5px 5px 0;
+ border-bottom-width: 0;
+}
+.dropup .btn-lg .caret {
+ border-width: 0 5px 5px;
+}
+.btn-group-vertical > .btn,
+.btn-group-vertical > .btn-group,
+.btn-group-vertical > .btn-group > .btn {
+ display: block;
+ float: none;
+ width: 100%;
+ max-width: 100%;
+}
+.btn-group-vertical > .btn-group > .btn {
+ float: none;
+}
+.btn-group-vertical > .btn + .btn,
+.btn-group-vertical > .btn + .btn-group,
+.btn-group-vertical > .btn-group + .btn,
+.btn-group-vertical > .btn-group + .btn-group {
+ margin-top: -1px;
+ margin-left: 0;
+}
+.btn-group-vertical > .btn:not(:first-child):not(:last-child) {
+ border-radius: 0;
+}
+.btn-group-vertical > .btn:first-child:not(:last-child) {
+ border-top-right-radius: 4px;
+ border-bottom-right-radius: 0;
+ border-bottom-left-radius: 0;
+}
+.btn-group-vertical > .btn:last-child:not(:first-child) {
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+ border-bottom-left-radius: 4px;
+}
+.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {
+ border-radius: 0;
+}
+.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child,
+.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
+ border-bottom-right-radius: 0;
+ border-bottom-left-radius: 0;
+}
+.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+}
+.btn-group-justified {
+ display: table;
+ width: 100%;
+ table-layout: fixed;
+ border-collapse: separate;
+}
+.btn-group-justified > .btn,
+.btn-group-justified > .btn-group {
+ display: table-cell;
+ float: none;
+ width: 1%;
+}
+.btn-group-justified > .btn-group .btn {
+ width: 100%;
+}
+.btn-group-justified > .btn-group .dropdown-menu {
+ left: auto;
+}
+[data-toggle="buttons"] > .btn input[type="radio"],
+[data-toggle="buttons"] > .btn-group > .btn input[type="radio"],
+[data-toggle="buttons"] > .btn input[type="checkbox"],
+[data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] {
+ position: absolute;
+ clip: rect(0, 0, 0, 0);
+ pointer-events: none;
+}
+.input-group {
+ position: relative;
+ display: table;
+ border-collapse: separate;
+}
+.input-group[class*="col-"] {
+ float: none;
+ padding-right: 0;
+ padding-left: 0;
+}
+.input-group .form-control {
+ position: relative;
+ z-index: 2;
+ float: left;
+ width: 100%;
+ margin-bottom: 0;
+}
+.input-group-lg > .form-control,
+.input-group-lg > .input-group-addon,
+.input-group-lg > .input-group-btn > .btn {
+ height: 46px;
+ padding: 10px 16px;
+ font-size: 18px;
+ line-height: 1.3333333;
+ border-radius: 6px;
+}
+select.input-group-lg > .form-control,
+select.input-group-lg > .input-group-addon,
+select.input-group-lg > .input-group-btn > .btn {
+ height: 46px;
+ line-height: 46px;
+}
+textarea.input-group-lg > .form-control,
+textarea.input-group-lg > .input-group-addon,
+textarea.input-group-lg > .input-group-btn > .btn,
+select[multiple].input-group-lg > .form-control,
+select[multiple].input-group-lg > .input-group-addon,
+select[multiple].input-group-lg > .input-group-btn > .btn {
+ height: auto;
+}
+.input-group-sm > .form-control,
+.input-group-sm > .input-group-addon,
+.input-group-sm > .input-group-btn > .btn {
+ height: 30px;
+ padding: 5px 10px;
+ font-size: 12px;
+ line-height: 1.5;
+ border-radius: 3px;
+}
+select.input-group-sm > .form-control,
+select.input-group-sm > .input-group-addon,
+select.input-group-sm > .input-group-btn > .btn {
+ height: 30px;
+ line-height: 30px;
+}
+textarea.input-group-sm > .form-control,
+textarea.input-group-sm > .input-group-addon,
+textarea.input-group-sm > .input-group-btn > .btn,
+select[multiple].input-group-sm > .form-control,
+select[multiple].input-group-sm > .input-group-addon,
+select[multiple].input-group-sm > .input-group-btn > .btn {
+ height: auto;
+}
+.input-group-addon,
+.input-group-btn,
+.input-group .form-control {
+ display: table-cell;
+}
+.input-group-addon:not(:first-child):not(:last-child),
+.input-group-btn:not(:first-child):not(:last-child),
+.input-group .form-control:not(:first-child):not(:last-child) {
+ border-radius: 0;
+}
+.input-group-addon,
+.input-group-btn {
+ width: 1%;
+ white-space: nowrap;
+ vertical-align: middle;
+}
+.input-group-addon {
+ padding: 6px 12px;
+ font-size: 14px;
+ font-weight: normal;
+ line-height: 1;
+ color: #555;
+ text-align: center;
+ background-color: #eee;
+ border: 1px solid #ccc;
+ border-radius: 4px;
+}
+.input-group-addon.input-sm {
+ padding: 5px 10px;
+ font-size: 12px;
+ border-radius: 3px;
+}
+.input-group-addon.input-lg {
+ padding: 10px 16px;
+ font-size: 18px;
+ border-radius: 6px;
+}
+.input-group-addon input[type="radio"],
+.input-group-addon input[type="checkbox"] {
+ margin-top: 0;
+}
+.input-group .form-control:first-child,
+.input-group-addon:first-child,
+.input-group-btn:first-child > .btn,
+.input-group-btn:first-child > .btn-group > .btn,
+.input-group-btn:first-child > .dropdown-toggle,
+.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),
+.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+}
+.input-group-addon:first-child {
+ border-right: 0;
+}
+.input-group .form-control:last-child,
+.input-group-addon:last-child,
+.input-group-btn:last-child > .btn,
+.input-group-btn:last-child > .btn-group > .btn,
+.input-group-btn:last-child > .dropdown-toggle,
+.input-group-btn:first-child > .btn:not(:first-child),
+.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+}
+.input-group-addon:last-child {
+ border-left: 0;
+}
+.input-group-btn {
+ position: relative;
+ font-size: 0;
+ white-space: nowrap;
+}
+.input-group-btn > .btn {
+ position: relative;
+}
+.input-group-btn > .btn + .btn {
+ margin-left: -1px;
+}
+.input-group-btn > .btn:hover,
+.input-group-btn > .btn:focus,
+.input-group-btn > .btn:active {
+ z-index: 2;
+}
+.input-group-btn:first-child > .btn,
+.input-group-btn:first-child > .btn-group {
+ margin-right: -1px;
+}
+.input-group-btn:last-child > .btn,
+.input-group-btn:last-child > .btn-group {
+ margin-left: -1px;
+}
+.nav {
+ padding-left: 0;
+ margin-bottom: 0;
+ list-style: none;
+}
+.nav > li {
+ position: relative;
+ display: block;
+}
+.nav > li > a {
+ position: relative;
+ display: block;
+ padding: 10px 15px;
+}
+.nav > li > a:hover,
+.nav > li > a:focus {
+ text-decoration: none;
+ background-color: #eee;
+}
+.nav > li.disabled > a {
+ color: #777;
+}
+.nav > li.disabled > a:hover,
+.nav > li.disabled > a:focus {
+ color: #777;
+ text-decoration: none;
+ cursor: not-allowed;
+ background-color: transparent;
+}
+.nav .open > a,
+.nav .open > a:hover,
+.nav .open > a:focus {
+ background-color: #eee;
+ border-color: #337ab7;
+}
+.nav .nav-divider {
+ height: 1px;
+ margin: 9px 0;
+ overflow: hidden;
+ background-color: #e5e5e5;
+}
+.nav > li > a > img {
+ max-width: none;
+}
+.nav-tabs {
+ border-bottom: 1px solid #ddd;
+}
+.nav-tabs > li {
+ float: left;
+ margin-bottom: -1px;
+}
+.nav-tabs > li > a {
+ margin-right: 2px;
+ line-height: 1.42857143;
+ border: 1px solid transparent;
+ border-radius: 4px 4px 0 0;
+}
+.nav-tabs > li > a:hover {
+ border-color: #eee #eee #ddd;
+}
+.nav-tabs > li.active > a,
+.nav-tabs > li.active > a:hover,
+.nav-tabs > li.active > a:focus {
+ color: #555;
+ cursor: default;
+ background-color: #fff;
+ border: 1px solid #ddd;
+ border-bottom-color: transparent;
+}
+.nav-tabs.nav-justified {
+ width: 100%;
+ border-bottom: 0;
+}
+.nav-tabs.nav-justified > li {
+ float: none;
+}
+.nav-tabs.nav-justified > li > a {
+ margin-bottom: 5px;
+ text-align: center;
+}
+.nav-tabs.nav-justified > .dropdown .dropdown-menu {
+ top: auto;
+ left: auto;
+}
+@media (min-width: 768px) {
+ .nav-tabs.nav-justified > li {
+ display: table-cell;
+ width: 1%;
+ }
+ .nav-tabs.nav-justified > li > a {
+ margin-bottom: 0;
+ }
+}
+.nav-tabs.nav-justified > li > a {
+ margin-right: 0;
+ border-radius: 4px;
+}
+.nav-tabs.nav-justified > .active > a,
+.nav-tabs.nav-justified > .active > a:hover,
+.nav-tabs.nav-justified > .active > a:focus {
+ border: 1px solid #ddd;
+}
+@media (min-width: 768px) {
+ .nav-tabs.nav-justified > li > a {
+ border-bottom: 1px solid #ddd;
+ border-radius: 4px 4px 0 0;
+ }
+ .nav-tabs.nav-justified > .active > a,
+ .nav-tabs.nav-justified > .active > a:hover,
+ .nav-tabs.nav-justified > .active > a:focus {
+ border-bottom-color: #fff;
+ }
+}
+.nav-pills > li {
+ float: left;
+}
+.nav-pills > li > a {
+ border-radius: 4px;
+}
+.nav-pills > li + li {
+ margin-left: 2px;
+}
+.nav-pills > li.active > a,
+.nav-pills > li.active > a:hover,
+.nav-pills > li.active > a:focus {
+ color: #fff;
+ background-color: #337ab7;
+}
+.nav-stacked > li {
+ float: none;
+}
+.nav-stacked > li + li {
+ margin-top: 2px;
+ margin-left: 0;
+}
+.nav-justified {
+ width: 100%;
+}
+.nav-justified > li {
+ float: none;
+}
+.nav-justified > li > a {
+ margin-bottom: 5px;
+ text-align: center;
+}
+.nav-justified > .dropdown .dropdown-menu {
+ top: auto;
+ left: auto;
+}
+@media (min-width: 768px) {
+ .nav-justified > li {
+ display: table-cell;
+ width: 1%;
+ }
+ .nav-justified > li > a {
+ margin-bottom: 0;
+ }
+}
+.nav-tabs-justified {
+ border-bottom: 0;
+}
+.nav-tabs-justified > li > a {
+ margin-right: 0;
+ border-radius: 4px;
+}
+.nav-tabs-justified > .active > a,
+.nav-tabs-justified > .active > a:hover,
+.nav-tabs-justified > .active > a:focus {
+ border: 1px solid #ddd;
+}
+@media (min-width: 768px) {
+ .nav-tabs-justified > li > a {
+ border-bottom: 1px solid #ddd;
+ border-radius: 4px 4px 0 0;
+ }
+ .nav-tabs-justified > .active > a,
+ .nav-tabs-justified > .active > a:hover,
+ .nav-tabs-justified > .active > a:focus {
+ border-bottom-color: #fff;
+ }
+}
+.tab-content > .tab-pane {
+ display: none;
+}
+.tab-content > .active {
+ display: block;
+}
+.nav-tabs .dropdown-menu {
+ margin-top: -1px;
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+}
+.navbar {
+ position: relative;
+ min-height: 50px;
+ margin-bottom: 20px;
+ border: 1px solid transparent;
+}
+@media (min-width: 768px) {
+ .navbar {
+ border-radius: 4px;
+ }
+}
+@media (min-width: 768px) {
+ .navbar-header {
+ float: left;
+ }
+}
+.navbar-collapse {
+ padding-right: 15px;
+ padding-left: 15px;
+ overflow-x: visible;
+ -webkit-overflow-scrolling: touch;
+ border-top: 1px solid transparent;
+ -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
+}
+.navbar-collapse.in {
+ overflow-y: auto;
+}
+@media (min-width: 768px) {
+ .navbar-collapse {
+ width: auto;
+ border-top: 0;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+ }
+ .navbar-collapse.collapse {
+ display: block !important;
+ height: auto !important;
+ padding-bottom: 0;
+ overflow: visible !important;
+ }
+ .navbar-collapse.in {
+ overflow-y: visible;
+ }
+ .navbar-fixed-top .navbar-collapse,
+ .navbar-static-top .navbar-collapse,
+ .navbar-fixed-bottom .navbar-collapse {
+ padding-right: 0;
+ padding-left: 0;
+ }
+}
+.navbar-fixed-top .navbar-collapse,
+.navbar-fixed-bottom .navbar-collapse {
+ max-height: 340px;
+}
+@media (max-device-width: 480px) and (orientation: landscape) {
+ .navbar-fixed-top .navbar-collapse,
+ .navbar-fixed-bottom .navbar-collapse {
+ max-height: 200px;
+ }
+}
+.container > .navbar-header,
+.container-fluid > .navbar-header,
+.container > .navbar-collapse,
+.container-fluid > .navbar-collapse {
+ margin-right: -15px;
+ margin-left: -15px;
+}
+@media (min-width: 768px) {
+ .container > .navbar-header,
+ .container-fluid > .navbar-header,
+ .container > .navbar-collapse,
+ .container-fluid > .navbar-collapse {
+ margin-right: 0;
+ margin-left: 0;
+ }
+}
+.navbar-static-top {
+ z-index: 1000;
+ border-width: 0 0 1px;
+}
+@media (min-width: 768px) {
+ .navbar-static-top {
+ border-radius: 0;
+ }
+}
+.navbar-fixed-top,
+.navbar-fixed-bottom {
+ position: fixed;
+ right: 0;
+ left: 0;
+ z-index: 1030;
+}
+@media (min-width: 768px) {
+ .navbar-fixed-top,
+ .navbar-fixed-bottom {
+ border-radius: 0;
+ }
+}
+.navbar-fixed-top {
+ top: 0;
+ border-width: 0 0 1px;
+}
+.navbar-fixed-bottom {
+ bottom: 0;
+ margin-bottom: 0;
+ border-width: 1px 0 0;
+}
+.navbar-brand {
+ float: left;
+ height: 50px;
+ padding: 15px 15px;
+ font-size: 18px;
+ line-height: 20px;
+}
+.navbar-brand:hover,
+.navbar-brand:focus {
+ text-decoration: none;
+}
+.navbar-brand > img {
+ display: block;
+}
+@media (min-width: 768px) {
+ .navbar > .container .navbar-brand,
+ .navbar > .container-fluid .navbar-brand {
+ margin-left: -15px;
+ }
+}
+.navbar-toggle {
+ position: relative;
+ float: right;
+ padding: 9px 10px;
+ margin-top: 8px;
+ margin-right: 15px;
+ margin-bottom: 8px;
+ background-color: transparent;
+ background-image: none;
+ border: 1px solid transparent;
+ border-radius: 4px;
+}
+.navbar-toggle:focus {
+ outline: 0;
+}
+.navbar-toggle .icon-bar {
+ display: block;
+ width: 22px;
+ height: 2px;
+ border-radius: 1px;
+}
+.navbar-toggle .icon-bar + .icon-bar {
+ margin-top: 4px;
+}
+@media (min-width: 768px) {
+ .navbar-toggle {
+ display: none;
+ }
+}
+.navbar-nav {
+ margin: 7.5px -15px;
+}
+.navbar-nav > li > a {
+ padding-top: 10px;
+ padding-bottom: 10px;
+ line-height: 20px;
+}
+@media (max-width: 767px) {
+ .navbar-nav .open .dropdown-menu {
+ position: static;
+ float: none;
+ width: auto;
+ margin-top: 0;
+ background-color: transparent;
+ border: 0;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+ }
+ .navbar-nav .open .dropdown-menu > li > a,
+ .navbar-nav .open .dropdown-menu .dropdown-header {
+ padding: 5px 15px 5px 25px;
+ }
+ .navbar-nav .open .dropdown-menu > li > a {
+ line-height: 20px;
+ }
+ .navbar-nav .open .dropdown-menu > li > a:hover,
+ .navbar-nav .open .dropdown-menu > li > a:focus {
+ background-image: none;
+ }
+}
+@media (min-width: 768px) {
+ .navbar-nav {
+ float: left;
+ margin: 0;
+ }
+ .navbar-nav > li {
+ float: left;
+ }
+ .navbar-nav > li > a {
+ padding-top: 15px;
+ padding-bottom: 15px;
+ }
+}
+.navbar-form {
+ padding: 10px 15px;
+ margin-top: 8px;
+ margin-right: -15px;
+ margin-bottom: 8px;
+ margin-left: -15px;
+ border-top: 1px solid transparent;
+ border-bottom: 1px solid transparent;
+ -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
+}
+@media (min-width: 768px) {
+ .navbar-form .form-group {
+ display: inline-block;
+ margin-bottom: 0;
+ vertical-align: middle;
+ }
+ .navbar-form .form-control {
+ display: inline-block;
+ width: auto;
+ vertical-align: middle;
+ }
+ .navbar-form .form-control-static {
+ display: inline-block;
+ }
+ .navbar-form .input-group {
+ display: inline-table;
+ vertical-align: middle;
+ }
+ .navbar-form .input-group .input-group-addon,
+ .navbar-form .input-group .input-group-btn,
+ .navbar-form .input-group .form-control {
+ width: auto;
+ }
+ .navbar-form .input-group > .form-control {
+ width: 100%;
+ }
+ .navbar-form .control-label {
+ margin-bottom: 0;
+ vertical-align: middle;
+ }
+ .navbar-form .radio,
+ .navbar-form .checkbox {
+ display: inline-block;
+ margin-top: 0;
+ margin-bottom: 0;
+ vertical-align: middle;
+ }
+ .navbar-form .radio label,
+ .navbar-form .checkbox label {
+ padding-left: 0;
+ }
+ .navbar-form .radio input[type="radio"],
+ .navbar-form .checkbox input[type="checkbox"] {
+ position: relative;
+ margin-left: 0;
+ }
+ .navbar-form .has-feedback .form-control-feedback {
+ top: 0;
+ }
+}
+@media (max-width: 767px) {
+ .navbar-form .form-group {
+ margin-bottom: 5px;
+ }
+ .navbar-form .form-group:last-child {
+ margin-bottom: 0;
+ }
+}
+@media (min-width: 768px) {
+ .navbar-form {
+ width: auto;
+ padding-top: 0;
+ padding-bottom: 0;
+ margin-right: 0;
+ margin-left: 0;
+ border: 0;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+ }
+}
+.navbar-nav > li > .dropdown-menu {
+ margin-top: 0;
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+}
+.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
+ margin-bottom: 0;
+ border-top-left-radius: 4px;
+ border-top-right-radius: 4px;
+ border-bottom-right-radius: 0;
+ border-bottom-left-radius: 0;
+}
+.navbar-btn {
+ margin-top: 8px;
+ margin-bottom: 8px;
+}
+.navbar-btn.btn-sm {
+ margin-top: 10px;
+ margin-bottom: 10px;
+}
+.navbar-btn.btn-xs {
+ margin-top: 14px;
+ margin-bottom: 14px;
+}
+.navbar-text {
+ margin-top: 15px;
+ margin-bottom: 15px;
+}
+@media (min-width: 768px) {
+ .navbar-text {
+ float: left;
+ margin-right: 15px;
+ margin-left: 15px;
+ }
+}
+@media (min-width: 768px) {
+ .navbar-left {
+ float: left !important;
+ }
+ .navbar-right {
+ float: right !important;
+ margin-right: -15px;
+ }
+ .navbar-right ~ .navbar-right {
+ margin-right: 0;
+ }
+}
+.navbar-default {
+ background-color: #f8f8f8;
+ border-color: #e7e7e7;
+}
+.navbar-default .navbar-brand {
+ color: #777;
+}
+.navbar-default .navbar-brand:hover,
+.navbar-default .navbar-brand:focus {
+ color: #5e5e5e;
+ background-color: transparent;
+}
+.navbar-default .navbar-text {
+ color: #777;
+}
+.navbar-default .navbar-nav > li > a {
+ color: #777;
+}
+.navbar-default .navbar-nav > li > a:hover,
+.navbar-default .navbar-nav > li > a:focus {
+ color: #333;
+ background-color: transparent;
+}
+.navbar-default .navbar-nav > .active > a,
+.navbar-default .navbar-nav > .active > a:hover,
+.navbar-default .navbar-nav > .active > a:focus {
+ color: #555;
+ background-color: #e7e7e7;
+}
+.navbar-default .navbar-nav > .disabled > a,
+.navbar-default .navbar-nav > .disabled > a:hover,
+.navbar-default .navbar-nav > .disabled > a:focus {
+ color: #ccc;
+ background-color: transparent;
+}
+.navbar-default .navbar-toggle {
+ border-color: #ddd;
+}
+.navbar-default .navbar-toggle:hover,
+.navbar-default .navbar-toggle:focus {
+ background-color: #ddd;
+}
+.navbar-default .navbar-toggle .icon-bar {
+ background-color: #888;
+}
+.navbar-default .navbar-collapse,
+.navbar-default .navbar-form {
+ border-color: #e7e7e7;
+}
+.navbar-default .navbar-nav > .open > a,
+.navbar-default .navbar-nav > .open > a:hover,
+.navbar-default .navbar-nav > .open > a:focus {
+ color: #555;
+ background-color: #e7e7e7;
+}
+@media (max-width: 767px) {
+ .navbar-default .navbar-nav .open .dropdown-menu > li > a {
+ color: #777;
+ }
+ .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
+ .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
+ color: #333;
+ background-color: transparent;
+ }
+ .navbar-default .navbar-nav .open .dropdown-menu > .active > a,
+ .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
+ .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
+ color: #555;
+ background-color: #e7e7e7;
+ }
+ .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
+ .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
+ .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
+ color: #ccc;
+ background-color: transparent;
+ }
+}
+.navbar-default .navbar-link {
+ color: #777;
+}
+.navbar-default .navbar-link:hover {
+ color: #333;
+}
+.navbar-default .btn-link {
+ color: #777;
+}
+.navbar-default .btn-link:hover,
+.navbar-default .btn-link:focus {
+ color: #333;
+}
+.navbar-default .btn-link[disabled]:hover,
+fieldset[disabled] .navbar-default .btn-link:hover,
+.navbar-default .btn-link[disabled]:focus,
+fieldset[disabled] .navbar-default .btn-link:focus {
+ color: #ccc;
+}
+.navbar-inverse {
+ background-color: #222;
+ border-color: #080808;
+}
+.navbar-inverse .navbar-brand {
+ color: #9d9d9d;
+}
+.navbar-inverse .navbar-brand:hover,
+.navbar-inverse .navbar-brand:focus {
+ color: #fff;
+ background-color: transparent;
+}
+.navbar-inverse .navbar-text {
+ color: #9d9d9d;
+}
+.navbar-inverse .navbar-nav > li > a {
+ color: #9d9d9d;
+}
+.navbar-inverse .navbar-nav > li > a:hover,
+.navbar-inverse .navbar-nav > li > a:focus {
+ color: #fff;
+ background-color: transparent;
+}
+.navbar-inverse .navbar-nav > .active > a,
+.navbar-inverse .navbar-nav > .active > a:hover,
+.navbar-inverse .navbar-nav > .active > a:focus {
+ color: #fff;
+ background-color: #080808;
+}
+.navbar-inverse .navbar-nav > .disabled > a,
+.navbar-inverse .navbar-nav > .disabled > a:hover,
+.navbar-inverse .navbar-nav > .disabled > a:focus {
+ color: #444;
+ background-color: transparent;
+}
+.navbar-inverse .navbar-toggle {
+ border-color: #333;
+}
+.navbar-inverse .navbar-toggle:hover,
+.navbar-inverse .navbar-toggle:focus {
+ background-color: #333;
+}
+.navbar-inverse .navbar-toggle .icon-bar {
+ background-color: #fff;
+}
+.navbar-inverse .navbar-collapse,
+.navbar-inverse .navbar-form {
+ border-color: #101010;
+}
+.navbar-inverse .navbar-nav > .open > a,
+.navbar-inverse .navbar-nav > .open > a:hover,
+.navbar-inverse .navbar-nav > .open > a:focus {
+ color: #fff;
+ background-color: #080808;
+}
+@media (max-width: 767px) {
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {
+ border-color: #080808;
+ }
+ .navbar-inverse .navbar-nav .open .dropdown-menu .divider {
+ background-color: #080808;
+ }
+ .navbar-inverse .navbar-nav .open .dropdown-menu > li > a {
+ color: #9d9d9d;
+ }
+ .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,
+ .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {
+ color: #fff;
+ background-color: transparent;
+ }
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {
+ color: #fff;
+ background-color: #080808;
+ }
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,
+ .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {
+ color: #444;
+ background-color: transparent;
+ }
+}
+.navbar-inverse .navbar-link {
+ color: #9d9d9d;
+}
+.navbar-inverse .navbar-link:hover {
+ color: #fff;
+}
+.navbar-inverse .btn-link {
+ color: #9d9d9d;
+}
+.navbar-inverse .btn-link:hover,
+.navbar-inverse .btn-link:focus {
+ color: #fff;
+}
+.navbar-inverse .btn-link[disabled]:hover,
+fieldset[disabled] .navbar-inverse .btn-link:hover,
+.navbar-inverse .btn-link[disabled]:focus,
+fieldset[disabled] .navbar-inverse .btn-link:focus {
+ color: #444;
+}
+.breadcrumb {
+ padding: 8px 15px;
+ margin-bottom: 20px;
+ list-style: none;
+ background-color: #f5f5f5;
+ border-radius: 4px;
+}
+.breadcrumb > li {
+ display: inline-block;
+}
+.breadcrumb > li + li:before {
+ padding: 0 5px;
+ color: #ccc;
+ content: "/\00a0";
+}
+.breadcrumb > .active {
+ color: #777;
+}
+.pagination {
+ display: inline-block;
+ padding-left: 0;
+ margin: 20px 0;
+ border-radius: 4px;
+}
+.pagination > li {
+ display: inline;
+}
+.pagination > li > a,
+.pagination > li > span {
+ position: relative;
+ float: left;
+ padding: 6px 12px;
+ margin-left: -1px;
+ line-height: 1.42857143;
+ color: #337ab7;
+ text-decoration: none;
+ background-color: #fff;
+ border: 1px solid #ddd;
+}
+.pagination > li:first-child > a,
+.pagination > li:first-child > span {
+ margin-left: 0;
+ border-top-left-radius: 4px;
+ border-bottom-left-radius: 4px;
+}
+.pagination > li:last-child > a,
+.pagination > li:last-child > span {
+ border-top-right-radius: 4px;
+ border-bottom-right-radius: 4px;
+}
+.pagination > li > a:hover,
+.pagination > li > span:hover,
+.pagination > li > a:focus,
+.pagination > li > span:focus {
+ color: #23527c;
+ background-color: #eee;
+ border-color: #ddd;
+}
+.pagination > .active > a,
+.pagination > .active > span,
+.pagination > .active > a:hover,
+.pagination > .active > span:hover,
+.pagination > .active > a:focus,
+.pagination > .active > span:focus {
+ z-index: 2;
+ color: #fff;
+ cursor: default;
+ background-color: #337ab7;
+ border-color: #337ab7;
+}
+.pagination > .disabled > span,
+.pagination > .disabled > span:hover,
+.pagination > .disabled > span:focus,
+.pagination > .disabled > a,
+.pagination > .disabled > a:hover,
+.pagination > .disabled > a:focus {
+ color: #777;
+ cursor: not-allowed;
+ background-color: #fff;
+ border-color: #ddd;
+}
+.pagination-lg > li > a,
+.pagination-lg > li > span {
+ padding: 10px 16px;
+ font-size: 18px;
+}
+.pagination-lg > li:first-child > a,
+.pagination-lg > li:first-child > span {
+ border-top-left-radius: 6px;
+ border-bottom-left-radius: 6px;
+}
+.pagination-lg > li:last-child > a,
+.pagination-lg > li:last-child > span {
+ border-top-right-radius: 6px;
+ border-bottom-right-radius: 6px;
+}
+.pagination-sm > li > a,
+.pagination-sm > li > span {
+ padding: 5px 10px;
+ font-size: 12px;
+}
+.pagination-sm > li:first-child > a,
+.pagination-sm > li:first-child > span {
+ border-top-left-radius: 3px;
+ border-bottom-left-radius: 3px;
+}
+.pagination-sm > li:last-child > a,
+.pagination-sm > li:last-child > span {
+ border-top-right-radius: 3px;
+ border-bottom-right-radius: 3px;
+}
+.pager {
+ padding-left: 0;
+ margin: 20px 0;
+ text-align: center;
+ list-style: none;
+}
+.pager li {
+ display: inline;
+}
+.pager li > a,
+.pager li > span {
+ display: inline-block;
+ padding: 5px 14px;
+ background-color: #fff;
+ border: 1px solid #ddd;
+ border-radius: 15px;
+}
+.pager li > a:hover,
+.pager li > a:focus {
+ text-decoration: none;
+ background-color: #eee;
+}
+.pager .next > a,
+.pager .next > span {
+ float: right;
+}
+.pager .previous > a,
+.pager .previous > span {
+ float: left;
+}
+.pager .disabled > a,
+.pager .disabled > a:hover,
+.pager .disabled > a:focus,
+.pager .disabled > span {
+ color: #777;
+ cursor: not-allowed;
+ background-color: #fff;
+}
+.label {
+ display: inline;
+ padding: .2em .6em .3em;
+ font-size: 75%;
+ font-weight: bold;
+ line-height: 1;
+ color: #fff;
+ text-align: center;
+ white-space: nowrap;
+ vertical-align: baseline;
+ border-radius: .25em;
+}
+a.label:hover,
+a.label:focus {
+ color: #fff;
+ text-decoration: none;
+ cursor: pointer;
+}
+.label:empty {
+ display: none;
+}
+.btn .label {
+ position: relative;
+ top: -1px;
+}
+.label-default {
+ background-color: #777;
+}
+.label-default[href]:hover,
+.label-default[href]:focus {
+ background-color: #5e5e5e;
+}
+.label-primary {
+ background-color: #337ab7;
+}
+.label-primary[href]:hover,
+.label-primary[href]:focus {
+ background-color: #286090;
+}
+.label-success {
+ background-color: #5cb85c;
+}
+.label-success[href]:hover,
+.label-success[href]:focus {
+ background-color: #449d44;
+}
+.label-info {
+ background-color: #5bc0de;
+}
+.label-info[href]:hover,
+.label-info[href]:focus {
+ background-color: #31b0d5;
+}
+.label-warning {
+ background-color: #f0ad4e;
+}
+.label-warning[href]:hover,
+.label-warning[href]:focus {
+ background-color: #ec971f;
+}
+.label-danger {
+ background-color: #d9534f;
+}
+.label-danger[href]:hover,
+.label-danger[href]:focus {
+ background-color: #c9302c;
+}
+.badge {
+ display: inline-block;
+ min-width: 10px;
+ padding: 3px 7px;
+ font-size: 12px;
+ font-weight: bold;
+ line-height: 1;
+ color: #fff;
+ text-align: center;
+ white-space: nowrap;
+ vertical-align: baseline;
+ background-color: #777;
+ border-radius: 10px;
+}
+.badge:empty {
+ display: none;
+}
+.btn .badge {
+ position: relative;
+ top: -1px;
+}
+.btn-xs .badge,
+.btn-group-xs > .btn .badge {
+ top: 0;
+ padding: 1px 5px;
+}
+a.badge:hover,
+a.badge:focus {
+ color: #fff;
+ text-decoration: none;
+ cursor: pointer;
+}
+.list-group-item.active > .badge,
+.nav-pills > .active > a > .badge {
+ color: #337ab7;
+ background-color: #fff;
+}
+.list-group-item > .badge {
+ float: right;
+}
+.list-group-item > .badge + .badge {
+ margin-right: 5px;
+}
+.nav-pills > li > a > .badge {
+ margin-left: 3px;
+}
+.jumbotron {
+ padding: 30px 15px;
+ margin-bottom: 30px;
+ color: inherit;
+ background-color: #eee;
+}
+.jumbotron h1,
+.jumbotron .h1 {
+ color: inherit;
+}
+.jumbotron p {
+ margin-bottom: 15px;
+ font-size: 21px;
+ font-weight: 200;
+}
+.jumbotron > hr {
+ border-top-color: #d5d5d5;
+}
+.container .jumbotron,
+.container-fluid .jumbotron {
+ border-radius: 6px;
+}
+.jumbotron .container {
+ max-width: 100%;
+}
+@media screen and (min-width: 768px) {
+ .jumbotron {
+ padding: 48px 0;
+ }
+ .container .jumbotron,
+ .container-fluid .jumbotron {
+ padding-right: 60px;
+ padding-left: 60px;
+ }
+ .jumbotron h1,
+ .jumbotron .h1 {
+ font-size: 63px;
+ }
+}
+.thumbnail {
+ display: block;
+ padding: 4px;
+ margin-bottom: 20px;
+ line-height: 1.42857143;
+ background-color: #fff;
+ border: 1px solid #ddd;
+ border-radius: 4px;
+ -webkit-transition: border .2s ease-in-out;
+ -o-transition: border .2s ease-in-out;
+ transition: border .2s ease-in-out;
+}
+.thumbnail > img,
+.thumbnail a > img {
+ margin-right: auto;
+ margin-left: auto;
+}
+a.thumbnail:hover,
+a.thumbnail:focus,
+a.thumbnail.active {
+ border-color: #337ab7;
+}
+.thumbnail .caption {
+ padding: 9px;
+ color: #333;
+}
+.alert {
+ padding: 15px;
+ margin-bottom: 20px;
+ border: 1px solid transparent;
+ border-radius: 4px;
+}
+.alert h4 {
+ margin-top: 0;
+ color: inherit;
+}
+.alert .alert-link {
+ font-weight: bold;
+}
+.alert > p,
+.alert > ul {
+ margin-bottom: 0;
+}
+.alert > p + p {
+ margin-top: 5px;
+}
+.alert-dismissable,
+.alert-dismissible {
+ padding-right: 35px;
+}
+.alert-dismissable .close,
+.alert-dismissible .close {
+ position: relative;
+ top: -2px;
+ right: -21px;
+ color: inherit;
+}
+.alert-success {
+ color: #3c763d;
+ background-color: #dff0d8;
+ border-color: #d6e9c6;
+}
+.alert-success hr {
+ border-top-color: #c9e2b3;
+}
+.alert-success .alert-link {
+ color: #2b542c;
+}
+.alert-info {
+ color: #31708f;
+ background-color: #d9edf7;
+ border-color: #bce8f1;
+}
+.alert-info hr {
+ border-top-color: #a6e1ec;
+}
+.alert-info .alert-link {
+ color: #245269;
+}
+.alert-warning {
+ color: #8a6d3b;
+ background-color: #fcf8e3;
+ border-color: #faebcc;
+}
+.alert-warning hr {
+ border-top-color: #f7e1b5;
+}
+.alert-warning .alert-link {
+ color: #66512c;
+}
+.alert-danger {
+ color: #a94442;
+ background-color: #f2dede;
+ border-color: #ebccd1;
+}
+.alert-danger hr {
+ border-top-color: #e4b9c0;
+}
+.alert-danger .alert-link {
+ color: #843534;
+}
+@-webkit-keyframes progress-bar-stripes {
+ from {
+ background-position: 40px 0;
+ }
+ to {
+ background-position: 0 0;
+ }
+}
+@-o-keyframes progress-bar-stripes {
+ from {
+ background-position: 40px 0;
+ }
+ to {
+ background-position: 0 0;
+ }
+}
+@keyframes progress-bar-stripes {
+ from {
+ background-position: 40px 0;
+ }
+ to {
+ background-position: 0 0;
+ }
+}
+.progress {
+ height: 20px;
+ margin-bottom: 20px;
+ overflow: hidden;
+ background-color: #f5f5f5;
+ border-radius: 4px;
+ -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
+ box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
+}
+.progress-bar {
+ float: left;
+ width: 0;
+ height: 100%;
+ font-size: 12px;
+ line-height: 20px;
+ color: #fff;
+ text-align: center;
+ background-color: #337ab7;
+ -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
+ box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
+ -webkit-transition: width .6s ease;
+ -o-transition: width .6s ease;
+ transition: width .6s ease;
+}
+.progress-striped .progress-bar,
+.progress-bar-striped {
+ background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ -webkit-background-size: 40px 40px;
+ background-size: 40px 40px;
+}
+.progress.active .progress-bar,
+.progress-bar.active {
+ -webkit-animation: progress-bar-stripes 2s linear infinite;
+ -o-animation: progress-bar-stripes 2s linear infinite;
+ animation: progress-bar-stripes 2s linear infinite;
+}
+.progress-bar-success {
+ background-color: #5cb85c;
+}
+.progress-striped .progress-bar-success {
+ background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+}
+.progress-bar-info {
+ background-color: #5bc0de;
+}
+.progress-striped .progress-bar-info {
+ background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+}
+.progress-bar-warning {
+ background-color: #f0ad4e;
+}
+.progress-striped .progress-bar-warning {
+ background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+}
+.progress-bar-danger {
+ background-color: #d9534f;
+}
+.progress-striped .progress-bar-danger {
+ background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+ background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
+}
+.media {
+ margin-top: 15px;
+}
+.media:first-child {
+ margin-top: 0;
+}
+.media,
+.media-body {
+ overflow: hidden;
+ zoom: 1;
+}
+.media-body {
+ width: 10000px;
+}
+.media-object {
+ display: block;
+}
+.media-right,
+.media > .pull-right {
+ padding-left: 10px;
+}
+.media-left,
+.media > .pull-left {
+ padding-right: 10px;
+}
+.media-left,
+.media-right,
+.media-body {
+ display: table-cell;
+ vertical-align: top;
+}
+.media-middle {
+ vertical-align: middle;
+}
+.media-bottom {
+ vertical-align: bottom;
+}
+.media-heading {
+ margin-top: 0;
+ margin-bottom: 5px;
+}
+.media-list {
+ padding-left: 0;
+ list-style: none;
+}
+.list-group {
+ padding-left: 0;
+ margin-bottom: 20px;
+}
+.list-group-item {
+ position: relative;
+ display: block;
+ padding: 10px 15px;
+ margin-bottom: -1px;
+ background-color: #fff;
+ border: 1px solid #ddd;
+}
+.list-group-item:first-child {
+ border-top-left-radius: 4px;
+ border-top-right-radius: 4px;
+}
+.list-group-item:last-child {
+ margin-bottom: 0;
+ border-bottom-right-radius: 4px;
+ border-bottom-left-radius: 4px;
+}
+a.list-group-item {
+ color: #555;
+}
+a.list-group-item .list-group-item-heading {
+ color: #333;
+}
+a.list-group-item:hover,
+a.list-group-item:focus {
+ color: #555;
+ text-decoration: none;
+ background-color: #f5f5f5;
+}
+.list-group-item.disabled,
+.list-group-item.disabled:hover,
+.list-group-item.disabled:focus {
+ color: #777;
+ cursor: not-allowed;
+ background-color: #eee;
+}
+.list-group-item.disabled .list-group-item-heading,
+.list-group-item.disabled:hover .list-group-item-heading,
+.list-group-item.disabled:focus .list-group-item-heading {
+ color: inherit;
+}
+.list-group-item.disabled .list-group-item-text,
+.list-group-item.disabled:hover .list-group-item-text,
+.list-group-item.disabled:focus .list-group-item-text {
+ color: #777;
+}
+.list-group-item.active,
+.list-group-item.active:hover,
+.list-group-item.active:focus {
+ z-index: 2;
+ color: #fff;
+ background-color: #337ab7;
+ border-color: #337ab7;
+}
+.list-group-item.active .list-group-item-heading,
+.list-group-item.active:hover .list-group-item-heading,
+.list-group-item.active:focus .list-group-item-heading,
+.list-group-item.active .list-group-item-heading > small,
+.list-group-item.active:hover .list-group-item-heading > small,
+.list-group-item.active:focus .list-group-item-heading > small,
+.list-group-item.active .list-group-item-heading > .small,
+.list-group-item.active:hover .list-group-item-heading > .small,
+.list-group-item.active:focus .list-group-item-heading > .small {
+ color: inherit;
+}
+.list-group-item.active .list-group-item-text,
+.list-group-item.active:hover .list-group-item-text,
+.list-group-item.active:focus .list-group-item-text {
+ color: #c7ddef;
+}
+.list-group-item-success {
+ color: #3c763d;
+ background-color: #dff0d8;
+}
+a.list-group-item-success {
+ color: #3c763d;
+}
+a.list-group-item-success .list-group-item-heading {
+ color: inherit;
+}
+a.list-group-item-success:hover,
+a.list-group-item-success:focus {
+ color: #3c763d;
+ background-color: #d0e9c6;
+}
+a.list-group-item-success.active,
+a.list-group-item-success.active:hover,
+a.list-group-item-success.active:focus {
+ color: #fff;
+ background-color: #3c763d;
+ border-color: #3c763d;
+}
+.list-group-item-info {
+ color: #31708f;
+ background-color: #d9edf7;
+}
+a.list-group-item-info {
+ color: #31708f;
+}
+a.list-group-item-info .list-group-item-heading {
+ color: inherit;
+}
+a.list-group-item-info:hover,
+a.list-group-item-info:focus {
+ color: #31708f;
+ background-color: #c4e3f3;
+}
+a.list-group-item-info.active,
+a.list-group-item-info.active:hover,
+a.list-group-item-info.active:focus {
+ color: #fff;
+ background-color: #31708f;
+ border-color: #31708f;
+}
+.list-group-item-warning {
+ color: #8a6d3b;
+ background-color: #fcf8e3;
+}
+a.list-group-item-warning {
+ color: #8a6d3b;
+}
+a.list-group-item-warning .list-group-item-heading {
+ color: inherit;
+}
+a.list-group-item-warning:hover,
+a.list-group-item-warning:focus {
+ color: #8a6d3b;
+ background-color: #faf2cc;
+}
+a.list-group-item-warning.active,
+a.list-group-item-warning.active:hover,
+a.list-group-item-warning.active:focus {
+ color: #fff;
+ background-color: #8a6d3b;
+ border-color: #8a6d3b;
+}
+.list-group-item-danger {
+ color: #a94442;
+ background-color: #f2dede;
+}
+a.list-group-item-danger {
+ color: #a94442;
+}
+a.list-group-item-danger .list-group-item-heading {
+ color: inherit;
+}
+a.list-group-item-danger:hover,
+a.list-group-item-danger:focus {
+ color: #a94442;
+ background-color: #ebcccc;
+}
+a.list-group-item-danger.active,
+a.list-group-item-danger.active:hover,
+a.list-group-item-danger.active:focus {
+ color: #fff;
+ background-color: #a94442;
+ border-color: #a94442;
+}
+.list-group-item-heading {
+ margin-top: 0;
+ margin-bottom: 5px;
+}
+.list-group-item-text {
+ margin-bottom: 0;
+ line-height: 1.3;
+}
+.panel {
+ margin-bottom: 20px;
+ background-color: #fff;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
+ box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
+}
+.panel-body {
+ padding: 15px;
+}
+.panel-heading {
+ padding: 10px 15px;
+ border-bottom: 1px solid transparent;
+ border-top-left-radius: 3px;
+ border-top-right-radius: 3px;
+}
+.panel-heading > .dropdown .dropdown-toggle {
+ color: inherit;
+}
+.panel-title {
+ margin-top: 0;
+ margin-bottom: 0;
+ font-size: 16px;
+ color: inherit;
+}
+.panel-title > a,
+.panel-title > small,
+.panel-title > .small,
+.panel-title > small > a,
+.panel-title > .small > a {
+ color: inherit;
+}
+.panel-footer {
+ padding: 10px 15px;
+ background-color: #f5f5f5;
+ border-top: 1px solid #ddd;
+ border-bottom-right-radius: 3px;
+ border-bottom-left-radius: 3px;
+}
+.panel > .list-group,
+.panel > .panel-collapse > .list-group {
+ margin-bottom: 0;
+}
+.panel > .list-group .list-group-item,
+.panel > .panel-collapse > .list-group .list-group-item {
+ border-width: 1px 0;
+ border-radius: 0;
+}
+.panel > .list-group:first-child .list-group-item:first-child,
+.panel > .panel-collapse > .list-group:first-child .list-group-item:first-child {
+ border-top: 0;
+ border-top-left-radius: 3px;
+ border-top-right-radius: 3px;
+}
+.panel > .list-group:last-child .list-group-item:last-child,
+.panel > .panel-collapse > .list-group:last-child .list-group-item:last-child {
+ border-bottom: 0;
+ border-bottom-right-radius: 3px;
+ border-bottom-left-radius: 3px;
+}
+.panel-heading + .list-group .list-group-item:first-child {
+ border-top-width: 0;
+}
+.list-group + .panel-footer {
+ border-top-width: 0;
+}
+.panel > .table,
+.panel > .table-responsive > .table,
+.panel > .panel-collapse > .table {
+ margin-bottom: 0;
+}
+.panel > .table caption,
+.panel > .table-responsive > .table caption,
+.panel > .panel-collapse > .table caption {
+ padding-right: 15px;
+ padding-left: 15px;
+}
+.panel > .table:first-child,
+.panel > .table-responsive:first-child > .table:first-child {
+ border-top-left-radius: 3px;
+ border-top-right-radius: 3px;
+}
+.panel > .table:first-child > thead:first-child > tr:first-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child {
+ border-top-left-radius: 3px;
+ border-top-right-radius: 3px;
+}
+.panel > .table:first-child > thead:first-child > tr:first-child td:first-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,
+.panel > .table:first-child > thead:first-child > tr:first-child th:first-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {
+ border-top-left-radius: 3px;
+}
+.panel > .table:first-child > thead:first-child > tr:first-child td:last-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,
+.panel > .table:first-child > thead:first-child > tr:first-child th:last-child,
+.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,
+.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child,
+.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {
+ border-top-right-radius: 3px;
+}
+.panel > .table:last-child,
+.panel > .table-responsive:last-child > .table:last-child {
+ border-bottom-right-radius: 3px;
+ border-bottom-left-radius: 3px;
+}
+.panel > .table:last-child > tbody:last-child > tr:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child {
+ border-bottom-right-radius: 3px;
+ border-bottom-left-radius: 3px;
+}
+.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
+.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {
+ border-bottom-left-radius: 3px;
+}
+.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
+.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,
+.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child,
+.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {
+ border-bottom-right-radius: 3px;
+}
+.panel > .panel-body + .table,
+.panel > .panel-body + .table-responsive,
+.panel > .table + .panel-body,
+.panel > .table-responsive + .panel-body {
+ border-top: 1px solid #ddd;
+}
+.panel > .table > tbody:first-child > tr:first-child th,
+.panel > .table > tbody:first-child > tr:first-child td {
+ border-top: 0;
+}
+.panel > .table-bordered,
+.panel > .table-responsive > .table-bordered {
+ border: 0;
+}
+.panel > .table-bordered > thead > tr > th:first-child,
+.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,
+.panel > .table-bordered > tbody > tr > th:first-child,
+.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,
+.panel > .table-bordered > tfoot > tr > th:first-child,
+.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,
+.panel > .table-bordered > thead > tr > td:first-child,
+.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,
+.panel > .table-bordered > tbody > tr > td:first-child,
+.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,
+.panel > .table-bordered > tfoot > tr > td:first-child,
+.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {
+ border-left: 0;
+}
+.panel > .table-bordered > thead > tr > th:last-child,
+.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,
+.panel > .table-bordered > tbody > tr > th:last-child,
+.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,
+.panel > .table-bordered > tfoot > tr > th:last-child,
+.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,
+.panel > .table-bordered > thead > tr > td:last-child,
+.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,
+.panel > .table-bordered > tbody > tr > td:last-child,
+.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,
+.panel > .table-bordered > tfoot > tr > td:last-child,
+.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {
+ border-right: 0;
+}
+.panel > .table-bordered > thead > tr:first-child > td,
+.panel > .table-responsive > .table-bordered > thead > tr:first-child > td,
+.panel > .table-bordered > tbody > tr:first-child > td,
+.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td,
+.panel > .table-bordered > thead > tr:first-child > th,
+.panel > .table-responsive > .table-bordered > thead > tr:first-child > th,
+.panel > .table-bordered > tbody > tr:first-child > th,
+.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th {
+ border-bottom: 0;
+}
+.panel > .table-bordered > tbody > tr:last-child > td,
+.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,
+.panel > .table-bordered > tfoot > tr:last-child > td,
+.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td,
+.panel > .table-bordered > tbody > tr:last-child > th,
+.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,
+.panel > .table-bordered > tfoot > tr:last-child > th,
+.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th {
+ border-bottom: 0;
+}
+.panel > .table-responsive {
+ margin-bottom: 0;
+ border: 0;
+}
+.panel-group {
+ margin-bottom: 20px;
+}
+.panel-group .panel {
+ margin-bottom: 0;
+ border-radius: 4px;
+}
+.panel-group .panel + .panel {
+ margin-top: 5px;
+}
+.panel-group .panel-heading {
+ border-bottom: 0;
+}
+.panel-group .panel-heading + .panel-collapse > .panel-body,
+.panel-group .panel-heading + .panel-collapse > .list-group {
+ border-top: 1px solid #ddd;
+}
+.panel-group .panel-footer {
+ border-top: 0;
+}
+.panel-group .panel-footer + .panel-collapse .panel-body {
+ border-bottom: 1px solid #ddd;
+}
+.panel-default {
+ border-color: #ddd;
+}
+.panel-default > .panel-heading {
+ color: #333;
+ background-color: #f5f5f5;
+ border-color: #ddd;
+}
+.panel-default > .panel-heading + .panel-collapse > .panel-body {
+ border-top-color: #ddd;
+}
+.panel-default > .panel-heading .badge {
+ color: #f5f5f5;
+ background-color: #333;
+}
+.panel-default > .panel-footer + .panel-collapse > .panel-body {
+ border-bottom-color: #ddd;
+}
+.panel-primary {
+ border-color: #337ab7;
+}
+.panel-primary > .panel-heading {
+ color: #fff;
+ background-color: #337ab7;
+ border-color: #337ab7;
+}
+.panel-primary > .panel-heading + .panel-collapse > .panel-body {
+ border-top-color: #337ab7;
+}
+.panel-primary > .panel-heading .badge {
+ color: #337ab7;
+ background-color: #fff;
+}
+.panel-primary > .panel-footer + .panel-collapse > .panel-body {
+ border-bottom-color: #337ab7;
+}
+.panel-success {
+ border-color: #d6e9c6;
+}
+.panel-success > .panel-heading {
+ color: #3c763d;
+ background-color: #dff0d8;
+ border-color: #d6e9c6;
+}
+.panel-success > .panel-heading + .panel-collapse > .panel-body {
+ border-top-color: #d6e9c6;
+}
+.panel-success > .panel-heading .badge {
+ color: #dff0d8;
+ background-color: #3c763d;
+}
+.panel-success > .panel-footer + .panel-collapse > .panel-body {
+ border-bottom-color: #d6e9c6;
+}
+.panel-info {
+ border-color: #bce8f1;
+}
+.panel-info > .panel-heading {
+ color: #31708f;
+ background-color: #d9edf7;
+ border-color: #bce8f1;
+}
+.panel-info > .panel-heading + .panel-collapse > .panel-body {
+ border-top-color: #bce8f1;
+}
+.panel-info > .panel-heading .badge {
+ color: #d9edf7;
+ background-color: #31708f;
+}
+.panel-info > .panel-footer + .panel-collapse > .panel-body {
+ border-bottom-color: #bce8f1;
+}
+.panel-warning {
+ border-color: #faebcc;
+}
+.panel-warning > .panel-heading {
+ color: #8a6d3b;
+ background-color: #fcf8e3;
+ border-color: #faebcc;
+}
+.panel-warning > .panel-heading + .panel-collapse > .panel-body {
+ border-top-color: #faebcc;
+}
+.panel-warning > .panel-heading .badge {
+ color: #fcf8e3;
+ background-color: #8a6d3b;
+}
+.panel-warning > .panel-footer + .panel-collapse > .panel-body {
+ border-bottom-color: #faebcc;
+}
+.panel-danger {
+ border-color: #ebccd1;
+}
+.panel-danger > .panel-heading {
+ color: #a94442;
+ background-color: #f2dede;
+ border-color: #ebccd1;
+}
+.panel-danger > .panel-heading + .panel-collapse > .panel-body {
+ border-top-color: #ebccd1;
+}
+.panel-danger > .panel-heading .badge {
+ color: #f2dede;
+ background-color: #a94442;
+}
+.panel-danger > .panel-footer + .panel-collapse > .panel-body {
+ border-bottom-color: #ebccd1;
+}
+.embed-responsive {
+ position: relative;
+ display: block;
+ height: 0;
+ padding: 0;
+ overflow: hidden;
+}
+.embed-responsive .embed-responsive-item,
+.embed-responsive iframe,
+.embed-responsive embed,
+.embed-responsive object,
+.embed-responsive video {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ border: 0;
+}
+.embed-responsive-16by9 {
+ padding-bottom: 56.25%;
+}
+.embed-responsive-4by3 {
+ padding-bottom: 75%;
+}
+.well {
+ min-height: 20px;
+ padding: 19px;
+ margin-bottom: 20px;
+ background-color: #f5f5f5;
+ border: 1px solid #e3e3e3;
+ border-radius: 4px;
+ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
+ box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
+}
+.well blockquote {
+ border-color: #ddd;
+ border-color: rgba(0, 0, 0, .15);
+}
+.well-lg {
+ padding: 24px;
+ border-radius: 6px;
+}
+.well-sm {
+ padding: 9px;
+ border-radius: 3px;
+}
+.close {
+ float: right;
+ font-size: 21px;
+ font-weight: bold;
+ line-height: 1;
+ color: #000;
+ text-shadow: 0 1px 0 #fff;
+ filter: alpha(opacity=20);
+ opacity: .2;
+}
+.close:hover,
+.close:focus {
+ color: #000;
+ text-decoration: none;
+ cursor: pointer;
+ filter: alpha(opacity=50);
+ opacity: .5;
+}
+button.close {
+ -webkit-appearance: none;
+ padding: 0;
+ cursor: pointer;
+ background: transparent;
+ border: 0;
+}
+.modal-open {
+ overflow: hidden;
+}
+.modal {
+ position: fixed;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ z-index: 1050;
+ display: none;
+ overflow: hidden;
+ -webkit-overflow-scrolling: touch;
+ outline: 0;
+}
+.modal.fade .modal-dialog {
+ -webkit-transition: -webkit-transform .3s ease-out;
+ -o-transition: -o-transform .3s ease-out;
+ transition: transform .3s ease-out;
+ -webkit-transform: translate(0, -25%);
+ -ms-transform: translate(0, -25%);
+ -o-transform: translate(0, -25%);
+ transform: translate(0, -25%);
+}
+.modal.in .modal-dialog {
+ -webkit-transform: translate(0, 0);
+ -ms-transform: translate(0, 0);
+ -o-transform: translate(0, 0);
+ transform: translate(0, 0);
+}
+.modal-open .modal {
+ overflow-x: hidden;
+ overflow-y: auto;
+}
+.modal-dialog {
+ position: relative;
+ width: auto;
+ margin: 10px;
+}
+.modal-content {
+ position: relative;
+ background-color: #fff;
+ -webkit-background-clip: padding-box;
+ background-clip: padding-box;
+ border: 1px solid #999;
+ border: 1px solid rgba(0, 0, 0, .2);
+ border-radius: 6px;
+ outline: 0;
+ -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
+ box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
+}
+.modal-backdrop {
+ position: fixed;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ z-index: 1040;
+ background-color: #000;
+}
+.modal-backdrop.fade {
+ filter: alpha(opacity=0);
+ opacity: 0;
+}
+.modal-backdrop.in {
+ filter: alpha(opacity=50);
+ opacity: .5;
+}
+.modal-header {
+ min-height: 16.42857143px;
+ padding: 15px;
+ border-bottom: 1px solid #e5e5e5;
+}
+.modal-header .close {
+ margin-top: -2px;
+}
+.modal-title {
+ margin: 0;
+ line-height: 1.42857143;
+}
+.modal-body {
+ position: relative;
+ padding: 15px;
+}
+.modal-footer {
+ padding: 15px;
+ text-align: right;
+ border-top: 1px solid #e5e5e5;
+}
+.modal-footer .btn + .btn {
+ margin-bottom: 0;
+ margin-left: 5px;
+}
+.modal-footer .btn-group .btn + .btn {
+ margin-left: -1px;
+}
+.modal-footer .btn-block + .btn-block {
+ margin-left: 0;
+}
+.modal-scrollbar-measure {
+ position: absolute;
+ top: -9999px;
+ width: 50px;
+ height: 50px;
+ overflow: scroll;
+}
+@media (min-width: 768px) {
+ .modal-dialog {
+ width: 600px;
+ margin: 30px auto;
+ }
+ .modal-content {
+ -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
+ box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
+ }
+ .modal-sm {
+ width: 300px;
+ }
+}
+@media (min-width: 992px) {
+ .modal-lg {
+ width: 900px;
+ }
+}
+.tooltip {
+ position: absolute;
+ z-index: 1070;
+ display: block;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ font-size: 12px;
+ font-weight: normal;
+ line-height: 1.4;
+ filter: alpha(opacity=0);
+ opacity: 0;
+}
+.tooltip.in {
+ filter: alpha(opacity=90);
+ opacity: .9;
+}
+.tooltip.top {
+ padding: 5px 0;
+ margin-top: -3px;
+}
+.tooltip.right {
+ padding: 0 5px;
+ margin-left: 3px;
+}
+.tooltip.bottom {
+ padding: 5px 0;
+ margin-top: 3px;
+}
+.tooltip.left {
+ padding: 0 5px;
+ margin-left: -3px;
+}
+.tooltip-inner {
+ max-width: 200px;
+ padding: 3px 8px;
+ color: #fff;
+ text-align: center;
+ text-decoration: none;
+ background-color: #000;
+ border-radius: 4px;
+}
+.tooltip-arrow {
+ position: absolute;
+ width: 0;
+ height: 0;
+ border-color: transparent;
+ border-style: solid;
+}
+.tooltip.top .tooltip-arrow {
+ bottom: 0;
+ left: 50%;
+ margin-left: -5px;
+ border-width: 5px 5px 0;
+ border-top-color: #000;
+}
+.tooltip.top-left .tooltip-arrow {
+ right: 5px;
+ bottom: 0;
+ margin-bottom: -5px;
+ border-width: 5px 5px 0;
+ border-top-color: #000;
+}
+.tooltip.top-right .tooltip-arrow {
+ bottom: 0;
+ left: 5px;
+ margin-bottom: -5px;
+ border-width: 5px 5px 0;
+ border-top-color: #000;
+}
+.tooltip.right .tooltip-arrow {
+ top: 50%;
+ left: 0;
+ margin-top: -5px;
+ border-width: 5px 5px 5px 0;
+ border-right-color: #000;
+}
+.tooltip.left .tooltip-arrow {
+ top: 50%;
+ right: 0;
+ margin-top: -5px;
+ border-width: 5px 0 5px 5px;
+ border-left-color: #000;
+}
+.tooltip.bottom .tooltip-arrow {
+ top: 0;
+ left: 50%;
+ margin-left: -5px;
+ border-width: 0 5px 5px;
+ border-bottom-color: #000;
+}
+.tooltip.bottom-left .tooltip-arrow {
+ top: 0;
+ right: 5px;
+ margin-top: -5px;
+ border-width: 0 5px 5px;
+ border-bottom-color: #000;
+}
+.tooltip.bottom-right .tooltip-arrow {
+ top: 0;
+ left: 5px;
+ margin-top: -5px;
+ border-width: 0 5px 5px;
+ border-bottom-color: #000;
+}
+.popover {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 1060;
+ display: none;
+ max-width: 276px;
+ padding: 1px;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ font-size: 14px;
+ font-weight: normal;
+ line-height: 1.42857143;
+ text-align: left;
+ white-space: normal;
+ background-color: #fff;
+ -webkit-background-clip: padding-box;
+ background-clip: padding-box;
+ border: 1px solid #ccc;
+ border: 1px solid rgba(0, 0, 0, .2);
+ border-radius: 6px;
+ -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
+ box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
+}
+.popover.top {
+ margin-top: -10px;
+}
+.popover.right {
+ margin-left: 10px;
+}
+.popover.bottom {
+ margin-top: 10px;
+}
+.popover.left {
+ margin-left: -10px;
+}
+.popover-title {
+ padding: 8px 14px;
+ margin: 0;
+ font-size: 14px;
+ background-color: #f7f7f7;
+ border-bottom: 1px solid #ebebeb;
+ border-radius: 5px 5px 0 0;
+}
+.popover-content {
+ padding: 9px 14px;
+}
+.popover > .arrow,
+.popover > .arrow:after {
+ position: absolute;
+ display: block;
+ width: 0;
+ height: 0;
+ border-color: transparent;
+ border-style: solid;
+}
+.popover > .arrow {
+ border-width: 11px;
+}
+.popover > .arrow:after {
+ content: "";
+ border-width: 10px;
+}
+.popover.top > .arrow {
+ bottom: -11px;
+ left: 50%;
+ margin-left: -11px;
+ border-top-color: #999;
+ border-top-color: rgba(0, 0, 0, .25);
+ border-bottom-width: 0;
+}
+.popover.top > .arrow:after {
+ bottom: 1px;
+ margin-left: -10px;
+ content: " ";
+ border-top-color: #fff;
+ border-bottom-width: 0;
+}
+.popover.right > .arrow {
+ top: 50%;
+ left: -11px;
+ margin-top: -11px;
+ border-right-color: #999;
+ border-right-color: rgba(0, 0, 0, .25);
+ border-left-width: 0;
+}
+.popover.right > .arrow:after {
+ bottom: -10px;
+ left: 1px;
+ content: " ";
+ border-right-color: #fff;
+ border-left-width: 0;
+}
+.popover.bottom > .arrow {
+ top: -11px;
+ left: 50%;
+ margin-left: -11px;
+ border-top-width: 0;
+ border-bottom-color: #999;
+ border-bottom-color: rgba(0, 0, 0, .25);
+}
+.popover.bottom > .arrow:after {
+ top: 1px;
+ margin-left: -10px;
+ content: " ";
+ border-top-width: 0;
+ border-bottom-color: #fff;
+}
+.popover.left > .arrow {
+ top: 50%;
+ right: -11px;
+ margin-top: -11px;
+ border-right-width: 0;
+ border-left-color: #999;
+ border-left-color: rgba(0, 0, 0, .25);
+}
+.popover.left > .arrow:after {
+ right: 1px;
+ bottom: -10px;
+ content: " ";
+ border-right-width: 0;
+ border-left-color: #fff;
+}
+.carousel {
+ position: relative;
+}
+.carousel-inner {
+ position: relative;
+ width: 100%;
+ overflow: hidden;
+}
+.carousel-inner > .item {
+ position: relative;
+ display: none;
+ -webkit-transition: .6s ease-in-out left;
+ -o-transition: .6s ease-in-out left;
+ transition: .6s ease-in-out left;
+}
+.carousel-inner > .item > img,
+.carousel-inner > .item > a > img {
+ line-height: 1;
+}
+@media all and (transform-3d), (-webkit-transform-3d) {
+ .carousel-inner > .item {
+ -webkit-transition: -webkit-transform .6s ease-in-out;
+ -o-transition: -o-transform .6s ease-in-out;
+ transition: transform .6s ease-in-out;
+
+ -webkit-backface-visibility: hidden;
+ backface-visibility: hidden;
+ -webkit-perspective: 1000;
+ perspective: 1000;
+ }
+ .carousel-inner > .item.next,
+ .carousel-inner > .item.active.right {
+ left: 0;
+ -webkit-transform: translate3d(100%, 0, 0);
+ transform: translate3d(100%, 0, 0);
+ }
+ .carousel-inner > .item.prev,
+ .carousel-inner > .item.active.left {
+ left: 0;
+ -webkit-transform: translate3d(-100%, 0, 0);
+ transform: translate3d(-100%, 0, 0);
+ }
+ .carousel-inner > .item.next.left,
+ .carousel-inner > .item.prev.right,
+ .carousel-inner > .item.active {
+ left: 0;
+ -webkit-transform: translate3d(0, 0, 0);
+ transform: translate3d(0, 0, 0);
+ }
+}
+.carousel-inner > .active,
+.carousel-inner > .next,
+.carousel-inner > .prev {
+ display: block;
+}
+.carousel-inner > .active {
+ left: 0;
+}
+.carousel-inner > .next,
+.carousel-inner > .prev {
+ position: absolute;
+ top: 0;
+ width: 100%;
+}
+.carousel-inner > .next {
+ left: 100%;
+}
+.carousel-inner > .prev {
+ left: -100%;
+}
+.carousel-inner > .next.left,
+.carousel-inner > .prev.right {
+ left: 0;
+}
+.carousel-inner > .active.left {
+ left: -100%;
+}
+.carousel-inner > .active.right {
+ left: 100%;
+}
+.carousel-control {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ width: 15%;
+ font-size: 20px;
+ color: #fff;
+ text-align: center;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
+ filter: alpha(opacity=50);
+ opacity: .5;
+}
+.carousel-control.left {
+ background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
+ background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
+ background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001)));
+ background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
+ background-repeat: repeat-x;
+}
+.carousel-control.right {
+ right: 0;
+ left: auto;
+ background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
+ background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
+ background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5)));
+ background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
+ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
+ background-repeat: repeat-x;
+}
+.carousel-control:hover,
+.carousel-control:focus {
+ color: #fff;
+ text-decoration: none;
+ filter: alpha(opacity=90);
+ outline: 0;
+ opacity: .9;
+}
+.carousel-control .icon-prev,
+.carousel-control .icon-next,
+.carousel-control .glyphicon-chevron-left,
+.carousel-control .glyphicon-chevron-right {
+ position: absolute;
+ top: 50%;
+ z-index: 5;
+ display: inline-block;
+}
+.carousel-control .icon-prev,
+.carousel-control .glyphicon-chevron-left {
+ left: 50%;
+ margin-left: -10px;
+}
+.carousel-control .icon-next,
+.carousel-control .glyphicon-chevron-right {
+ right: 50%;
+ margin-right: -10px;
+}
+.carousel-control .icon-prev,
+.carousel-control .icon-next {
+ width: 20px;
+ height: 20px;
+ margin-top: -10px;
+ font-family: serif;
+ line-height: 1;
+}
+.carousel-control .icon-prev:before {
+ content: '\2039';
+}
+.carousel-control .icon-next:before {
+ content: '\203a';
+}
+.carousel-indicators {
+ position: absolute;
+ bottom: 10px;
+ left: 50%;
+ z-index: 15;
+ width: 60%;
+ padding-left: 0;
+ margin-left: -30%;
+ text-align: center;
+ list-style: none;
+}
+.carousel-indicators li {
+ display: inline-block;
+ width: 10px;
+ height: 10px;
+ margin: 1px;
+ text-indent: -999px;
+ cursor: pointer;
+ background-color: #000 \9;
+ background-color: rgba(0, 0, 0, 0);
+ border: 1px solid #fff;
+ border-radius: 10px;
+}
+.carousel-indicators .active {
+ width: 12px;
+ height: 12px;
+ margin: 0;
+ background-color: #fff;
+}
+.carousel-caption {
+ position: absolute;
+ right: 15%;
+ bottom: 20px;
+ left: 15%;
+ z-index: 10;
+ padding-top: 20px;
+ padding-bottom: 20px;
+ color: #fff;
+ text-align: center;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
+}
+.carousel-caption .btn {
+ text-shadow: none;
+}
+@media screen and (min-width: 768px) {
+ .carousel-control .glyphicon-chevron-left,
+ .carousel-control .glyphicon-chevron-right,
+ .carousel-control .icon-prev,
+ .carousel-control .icon-next {
+ width: 30px;
+ height: 30px;
+ margin-top: -15px;
+ font-size: 30px;
+ }
+ .carousel-control .glyphicon-chevron-left,
+ .carousel-control .icon-prev {
+ margin-left: -15px;
+ }
+ .carousel-control .glyphicon-chevron-right,
+ .carousel-control .icon-next {
+ margin-right: -15px;
+ }
+ .carousel-caption {
+ right: 20%;
+ left: 20%;
+ padding-bottom: 30px;
+ }
+ .carousel-indicators {
+ bottom: 20px;
+ }
+}
+.clearfix:before,
+.clearfix:after,
+.dl-horizontal dd:before,
+.dl-horizontal dd:after,
+.container:before,
+.container:after,
+.container-fluid:before,
+.container-fluid:after,
+.row:before,
+.row:after,
+.form-horizontal .form-group:before,
+.form-horizontal .form-group:after,
+.btn-toolbar:before,
+.btn-toolbar:after,
+.btn-group-vertical > .btn-group:before,
+.btn-group-vertical > .btn-group:after,
+.nav:before,
+.nav:after,
+.navbar:before,
+.navbar:after,
+.navbar-header:before,
+.navbar-header:after,
+.navbar-collapse:before,
+.navbar-collapse:after,
+.pager:before,
+.pager:after,
+.panel-body:before,
+.panel-body:after,
+.modal-footer:before,
+.modal-footer:after {
+ display: table;
+ content: " ";
+}
+.clearfix:after,
+.dl-horizontal dd:after,
+.container:after,
+.container-fluid:after,
+.row:after,
+.form-horizontal .form-group:after,
+.btn-toolbar:after,
+.btn-group-vertical > .btn-group:after,
+.nav:after,
+.navbar:after,
+.navbar-header:after,
+.navbar-collapse:after,
+.pager:after,
+.panel-body:after,
+.modal-footer:after {
+ clear: both;
+}
+.center-block {
+ display: block;
+ margin-right: auto;
+ margin-left: auto;
+}
+.pull-right {
+ float: right !important;
+}
+.pull-left {
+ float: left !important;
+}
+.hide {
+ display: none !important;
+}
+.show {
+ display: block !important;
+}
+.invisible {
+ visibility: hidden;
+}
+.text-hide {
+ font: 0/0 a;
+ color: transparent;
+ text-shadow: none;
+ background-color: transparent;
+ border: 0;
+}
+.hidden {
+ display: none !important;
+}
+.affix {
+ position: fixed;
+}
+@-ms-viewport {
+ width: device-width;
+}
+.visible-xs,
+.visible-sm,
+.visible-md,
+.visible-lg {
+ display: none !important;
+}
+.visible-xs-block,
+.visible-xs-inline,
+.visible-xs-inline-block,
+.visible-sm-block,
+.visible-sm-inline,
+.visible-sm-inline-block,
+.visible-md-block,
+.visible-md-inline,
+.visible-md-inline-block,
+.visible-lg-block,
+.visible-lg-inline,
+.visible-lg-inline-block {
+ display: none !important;
+}
+@media (max-width: 767px) {
+ .visible-xs {
+ display: block !important;
+ }
+ table.visible-xs {
+ display: table;
+ }
+ tr.visible-xs {
+ display: table-row !important;
+ }
+ th.visible-xs,
+ td.visible-xs {
+ display: table-cell !important;
+ }
+}
+@media (max-width: 767px) {
+ .visible-xs-block {
+ display: block !important;
+ }
+}
+@media (max-width: 767px) {
+ .visible-xs-inline {
+ display: inline !important;
+ }
+}
+@media (max-width: 767px) {
+ .visible-xs-inline-block {
+ display: inline-block !important;
+ }
+}
+@media (min-width: 768px) and (max-width: 991px) {
+ .visible-sm {
+ display: block !important;
+ }
+ table.visible-sm {
+ display: table;
+ }
+ tr.visible-sm {
+ display: table-row !important;
+ }
+ th.visible-sm,
+ td.visible-sm {
+ display: table-cell !important;
+ }
+}
+@media (min-width: 768px) and (max-width: 991px) {
+ .visible-sm-block {
+ display: block !important;
+ }
+}
+@media (min-width: 768px) and (max-width: 991px) {
+ .visible-sm-inline {
+ display: inline !important;
+ }
+}
+@media (min-width: 768px) and (max-width: 991px) {
+ .visible-sm-inline-block {
+ display: inline-block !important;
+ }
+}
+@media (min-width: 992px) and (max-width: 1199px) {
+ .visible-md {
+ display: block !important;
+ }
+ table.visible-md {
+ display: table;
+ }
+ tr.visible-md {
+ display: table-row !important;
+ }
+ th.visible-md,
+ td.visible-md {
+ display: table-cell !important;
+ }
+}
+@media (min-width: 992px) and (max-width: 1199px) {
+ .visible-md-block {
+ display: block !important;
+ }
+}
+@media (min-width: 992px) and (max-width: 1199px) {
+ .visible-md-inline {
+ display: inline !important;
+ }
+}
+@media (min-width: 992px) and (max-width: 1199px) {
+ .visible-md-inline-block {
+ display: inline-block !important;
+ }
+}
+@media (min-width: 1200px) {
+ .visible-lg {
+ display: block !important;
+ }
+ table.visible-lg {
+ display: table;
+ }
+ tr.visible-lg {
+ display: table-row !important;
+ }
+ th.visible-lg,
+ td.visible-lg {
+ display: table-cell !important;
+ }
+}
+@media (min-width: 1200px) {
+ .visible-lg-block {
+ display: block !important;
+ }
+}
+@media (min-width: 1200px) {
+ .visible-lg-inline {
+ display: inline !important;
+ }
+}
+@media (min-width: 1200px) {
+ .visible-lg-inline-block {
+ display: inline-block !important;
+ }
+}
+@media (max-width: 767px) {
+ .hidden-xs {
+ display: none !important;
+ }
+}
+@media (min-width: 768px) and (max-width: 991px) {
+ .hidden-sm {
+ display: none !important;
+ }
+}
+@media (min-width: 992px) and (max-width: 1199px) {
+ .hidden-md {
+ display: none !important;
+ }
+}
+@media (min-width: 1200px) {
+ .hidden-lg {
+ display: none !important;
+ }
+}
+.visible-print {
+ display: none !important;
+}
+@media print {
+ .visible-print {
+ display: block !important;
+ }
+ table.visible-print {
+ display: table;
+ }
+ tr.visible-print {
+ display: table-row !important;
+ }
+ th.visible-print,
+ td.visible-print {
+ display: table-cell !important;
+ }
+}
+.visible-print-block {
+ display: none !important;
+}
+@media print {
+ .visible-print-block {
+ display: block !important;
+ }
+}
+.visible-print-inline {
+ display: none !important;
+}
+@media print {
+ .visible-print-inline {
+ display: inline !important;
+ }
+}
+.visible-print-inline-block {
+ display: none !important;
+}
+@media print {
+ .visible-print-inline-block {
+ display: inline-block !important;
+ }
+}
+@media print {
+ .hidden-print {
+ display: none !important;
+ }
+}
+/*# sourceMappingURL=bootstrap.css.map */
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap.css.map b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap.css.map
new file mode 100644
index 0000000..2fd84f3
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap.css.map
@@ -0,0 +1 @@
+{"version":3,"sources":["bootstrap.css","less/normalize.less","less/print.less","less/glyphicons.less","less/scaffolding.less","less/mixins/vendor-prefixes.less","less/mixins/tab-focus.less","less/mixins/image.less","less/type.less","less/mixins/text-emphasis.less","less/mixins/background-variant.less","less/mixins/text-overflow.less","less/code.less","less/grid.less","less/mixins/grid.less","less/mixins/grid-framework.less","less/tables.less","less/mixins/table-row.less","less/forms.less","less/mixins/forms.less","less/buttons.less","less/mixins/buttons.less","less/mixins/opacity.less","less/component-animations.less","less/dropdowns.less","less/mixins/nav-divider.less","less/mixins/reset-filter.less","less/button-groups.less","less/mixins/border-radius.less","less/input-groups.less","less/navs.less","less/navbar.less","less/mixins/nav-vertical-align.less","less/utilities.less","less/breadcrumbs.less","less/pagination.less","less/mixins/pagination.less","less/pager.less","less/labels.less","less/mixins/labels.less","less/badges.less","less/jumbotron.less","less/thumbnails.less","less/alerts.less","less/mixins/alerts.less","less/progress-bars.less","less/mixins/gradients.less","less/mixins/progress-bar.less","less/media.less","less/list-group.less","less/mixins/list-group.less","less/panels.less","less/mixins/panels.less","less/responsive-embed.less","less/wells.less","less/close.less","less/modals.less","less/tooltip.less","less/popovers.less","less/carousel.less","less/mixins/clearfix.less","less/mixins/center-block.less","less/mixins/hide-text.less","less/responsive-utilities.less","less/mixins/responsive-visibility.less"],"names":[],"mappings":"AAAA,6DAA4D;ACQ5D;EACE,yBAAA;EACA,4BAAA;EACA,gCAAA;EDND;ACaD;EACE,WAAA;EDXD;ACwBD;;;;;;;;;;;;;EAaE,gBAAA;EDtBD;AC8BD;;;;EAIE,uBAAA;EACA,0BAAA;ED5BD;ACoCD;EACE,eAAA;EACA,WAAA;EDlCD;AC0CD;;EAEE,eAAA;EDxCD;ACkDD;EACE,+BAAA;EDhDD;ACuDD;;EAEE,YAAA;EDrDD;AC+DD;EACE,2BAAA;ED7DD;ACoED;;EAEE,mBAAA;EDlED;ACyED;EACE,oBAAA;EDvED;AC+ED;EACE,gBAAA;EACA,kBAAA;ED7ED;ACoFD;EACE,kBAAA;EACA,aAAA;EDlFD;ACyFD;EACE,gBAAA;EDvFD;AC8FD;;EAEE,gBAAA;EACA,gBAAA;EACA,oBAAA;EACA,0BAAA;ED5FD;AC+FD;EACE,aAAA;ED7FD;ACgGD;EACE,iBAAA;ED9FD;ACwGD;EACE,WAAA;EDtGD;AC6GD;EACE,kBAAA;ED3GD;ACqHD;EACE,kBAAA;EDnHD;AC0HD;EACE,8BAAA;EACA,iCAAA;UAAA,yBAAA;EACA,WAAA;EDxHD;AC+HD;EACE,gBAAA;ED7HD;ACoID;;;;EAIE,mCAAA;EACA,gBAAA;EDlID;ACoJD;;;;;EAKE,gBAAA;EACA,eAAA;EACA,WAAA;EDlJD;ACyJD;EACE,mBAAA;EDvJD;ACiKD;;EAEE,sBAAA;ED/JD;AC0KD;;;;EAIE,4BAAA;EACA,iBAAA;EDxKD;AC+KD;;EAEE,iBAAA;ED7KD;ACoLD;;EAEE,WAAA;EACA,YAAA;EDlLD;AC0LD;EACE,qBAAA;EDxLD;ACmMD;;EAE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IACE,qBAAA;If6/DD;Ee9/DD;IACE,YAAA;IfggED;EejgED;IACE,qBAAA;IfmgED;EepgED;IACE,qBAAA;IfsgED;EevgED;IACE,YAAA;IfygED;Ee1gED;IACE,qBAAA;If4gED;Ee7gED;IACE,oBAAA;If+gED;EejgED;IACE,aAAA;IfmgED;EepgED;IACE,qBAAA;IfsgED;EevgED;IACE,qBAAA;IfygED;Ee1gED;IACE,YAAA;If4gED;Ee7gED;IACE,qBAAA;If+gED;EehhED;IACE,qBAAA;IfkhED;EenhED;IACE,YAAA;IfqhED;EethED;IACE,qBAAA;IfwhED;EezhED;IACE,qBAAA;If2hED;Ee5hED;IACE,YAAA;If8hED;Ee/hED;IACE,qBAAA;IfiiED;EeliED;IACE,oBAAA;IfoiED;EehiED;IACE,aAAA;IfkiED;EeljED;IACE,YAAA;IfojED;EerjED;IACE,oBAAA;IfujED;EexjED;IACE,oBAAA;If0jED;Ee3jED;IACE,WAAA;If6jED;Ee9jED;IACE,oBAAA;IfgkED;EejkED;IACE,oBAAA;IfmkED;EepkED;IACE,WAAA;IfskED;EevkED;IACE,oBAAA;IfykED;Ee1kED;IACE,oBAAA;If4kED;Ee7kED;IACE,WAAA;If+kED;EehlED;IACE,oBAAA;IfklED;EenlED;IACE,mBAAA;IfqlED;EejlED;IACE,YAAA;IfmlED;EerkED;IACE,mBAAA;IfukED;EexkED;IACE,2BAAA;If0kED;Ee3kED;IACE,2BAAA;If6kED;Ee9kED;IACE,kBAAA;IfglED;EejlED;IACE,2BAAA;IfmlED;EeplED;IACE,2BAAA;IfslED;EevlED;IACE,kBAAA;IfylED;Ee1lED;IACE,2BAAA;If4lED;Ee7lED;IACE,2BAAA;If+lED;EehmED;IACE,kBAAA;IfkmED;EenmED;IACE,2BAAA;IfqmED;EetmED;IACE,0BAAA;IfwmED;EezmED;IACE,iBAAA;If2mED;EACF;AgB/qED;EACE,+BAAA;EhBirED;AgB/qED;EACE,kBAAA;EACA,qBAAA;EACA,gBAAA;EACA,kBAA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;EAAA;IAFI,kCAAA;I/DqtMD;EACF;A+D9sMD;EAAA;ICpLE,0BAAA;IhEs4MC;EACF","file":"bootstrap.css","sourcesContent":["/*! normalize.css v3.0.2 | MIT License | git.io/normalize */\nhtml {\n font-family: sans-serif;\n -ms-text-size-adjust: 100%;\n -webkit-text-size-adjust: 100%;\n}\nbody {\n margin: 0;\n}\narticle,\naside,\ndetails,\nfigcaption,\nfigure,\nfooter,\nheader,\nhgroup,\nmain,\nmenu,\nnav,\nsection,\nsummary {\n display: block;\n}\naudio,\ncanvas,\nprogress,\nvideo {\n display: inline-block;\n vertical-align: baseline;\n}\naudio:not([controls]) {\n display: none;\n height: 0;\n}\n[hidden],\ntemplate {\n display: none;\n}\na {\n background-color: transparent;\n}\na:active,\na:hover {\n outline: 0;\n}\nabbr[title] {\n border-bottom: 1px dotted;\n}\nb,\nstrong {\n font-weight: bold;\n}\ndfn {\n font-style: italic;\n}\nh1 {\n font-size: 2em;\n margin: 0.67em 0;\n}\nmark {\n background: #ff0;\n color: #000;\n}\nsmall {\n font-size: 80%;\n}\nsub,\nsup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsup {\n top: -0.5em;\n}\nsub {\n bottom: -0.25em;\n}\nimg {\n border: 0;\n}\nsvg:not(:root) {\n overflow: hidden;\n}\nfigure {\n margin: 1em 40px;\n}\nhr {\n -moz-box-sizing: content-box;\n box-sizing: content-box;\n height: 0;\n}\npre {\n overflow: auto;\n}\ncode,\nkbd,\npre,\nsamp {\n font-family: monospace, monospace;\n font-size: 1em;\n}\nbutton,\ninput,\noptgroup,\nselect,\ntextarea {\n color: inherit;\n font: inherit;\n margin: 0;\n}\nbutton {\n overflow: visible;\n}\nbutton,\nselect {\n text-transform: none;\n}\nbutton,\nhtml input[type=\"button\"],\ninput[type=\"reset\"],\ninput[type=\"submit\"] {\n -webkit-appearance: button;\n cursor: pointer;\n}\nbutton[disabled],\nhtml input[disabled] {\n cursor: default;\n}\nbutton::-moz-focus-inner,\ninput::-moz-focus-inner {\n border: 0;\n padding: 0;\n}\ninput {\n line-height: normal;\n}\ninput[type=\"checkbox\"],\ninput[type=\"radio\"] {\n box-sizing: border-box;\n padding: 0;\n}\ninput[type=\"number\"]::-webkit-inner-spin-button,\ninput[type=\"number\"]::-webkit-outer-spin-button {\n height: auto;\n}\ninput[type=\"search\"] {\n -webkit-appearance: textfield;\n -moz-box-sizing: content-box;\n -webkit-box-sizing: content-box;\n box-sizing: content-box;\n}\ninput[type=\"search\"]::-webkit-search-cancel-button,\ninput[type=\"search\"]::-webkit-search-decoration {\n -webkit-appearance: none;\n}\nfieldset {\n border: 1px solid #c0c0c0;\n margin: 0 2px;\n padding: 0.35em 0.625em 0.75em;\n}\nlegend {\n border: 0;\n padding: 0;\n}\ntextarea {\n overflow: auto;\n}\noptgroup {\n font-weight: bold;\n}\ntable {\n border-collapse: collapse;\n border-spacing: 0;\n}\ntd,\nth {\n padding: 0;\n}\n/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */\n@media print {\n *,\n *:before,\n *:after {\n background: transparent !important;\n color: #000 !important;\n box-shadow: none !important;\n text-shadow: none !important;\n }\n a,\n a:visited {\n text-decoration: underline;\n }\n a[href]:after {\n content: \" (\" attr(href) \")\";\n }\n abbr[title]:after {\n content: \" (\" attr(title) \")\";\n }\n a[href^=\"#\"]:after,\n a[href^=\"javascript:\"]:after {\n content: \"\";\n }\n pre,\n blockquote {\n border: 1px solid #999;\n page-break-inside: avoid;\n }\n thead {\n display: table-header-group;\n }\n tr,\n img {\n page-break-inside: avoid;\n }\n img {\n max-width: 100% !important;\n }\n p,\n h2,\n h3 {\n orphans: 3;\n widows: 3;\n }\n h2,\n h3 {\n page-break-after: avoid;\n }\n select {\n background: #fff !important;\n }\n .navbar {\n display: none;\n }\n .btn > .caret,\n .dropup > .btn > .caret {\n border-top-color: #000 !important;\n }\n .label {\n border: 1px solid #000;\n }\n .table {\n border-collapse: collapse !important;\n }\n .table td,\n .table th {\n background-color: #fff !important;\n }\n .table-bordered th,\n .table-bordered td {\n border: 1px solid #ddd !important;\n }\n}\n@font-face {\n font-family: 'Glyphicons Halflings';\n src: url('../fonts/glyphicons-halflings-regular.eot');\n src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');\n}\n.glyphicon {\n position: relative;\n top: 1px;\n display: inline-block;\n font-family: 'Glyphicons Halflings';\n font-style: normal;\n font-weight: normal;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n.glyphicon-asterisk:before {\n content: \"\\2a\";\n}\n.glyphicon-plus:before {\n content: \"\\2b\";\n}\n.glyphicon-euro:before,\n.glyphicon-eur:before {\n content: \"\\20ac\";\n}\n.glyphicon-minus:before {\n content: \"\\2212\";\n}\n.glyphicon-cloud:before {\n content: \"\\2601\";\n}\n.glyphicon-envelope:before {\n content: \"\\2709\";\n}\n.glyphicon-pencil:before {\n content: \"\\270f\";\n}\n.glyphicon-glass:before {\n content: \"\\e001\";\n}\n.glyphicon-music:before {\n content: \"\\e002\";\n}\n.glyphicon-search:before {\n content: \"\\e003\";\n}\n.glyphicon-heart:before {\n content: \"\\e005\";\n}\n.glyphicon-star:before {\n content: \"\\e006\";\n}\n.glyphicon-star-empty:before {\n content: \"\\e007\";\n}\n.glyphicon-user:before {\n content: \"\\e008\";\n}\n.glyphicon-film:before {\n content: \"\\e009\";\n}\n.glyphicon-th-large:before {\n content: \"\\e010\";\n}\n.glyphicon-th:before {\n content: \"\\e011\";\n}\n.glyphicon-th-list:before {\n content: \"\\e012\";\n}\n.glyphicon-ok:before {\n content: \"\\e013\";\n}\n.glyphicon-remove:before {\n content: \"\\e014\";\n}\n.glyphicon-zoom-in:before {\n content: \"\\e015\";\n}\n.glyphicon-zoom-out:before {\n content: \"\\e016\";\n}\n.glyphicon-off:before {\n content: \"\\e017\";\n}\n.glyphicon-signal:before {\n content: \"\\e018\";\n}\n.glyphicon-cog:before {\n content: \"\\e019\";\n}\n.glyphicon-trash:before {\n content: \"\\e020\";\n}\n.glyphicon-home:before {\n content: \"\\e021\";\n}\n.glyphicon-file:before {\n content: \"\\e022\";\n}\n.glyphicon-time:before {\n content: \"\\e023\";\n}\n.glyphicon-road:before {\n content: \"\\e024\";\n}\n.glyphicon-download-alt:before {\n content: \"\\e025\";\n}\n.glyphicon-download:before {\n content: \"\\e026\";\n}\n.glyphicon-upload:before {\n content: \"\\e027\";\n}\n.glyphicon-inbox:before {\n content: \"\\e028\";\n}\n.glyphicon-play-circle:before {\n content: \"\\e029\";\n}\n.glyphicon-repeat:before {\n content: \"\\e030\";\n}\n.glyphicon-refresh:before {\n content: \"\\e031\";\n}\n.glyphicon-list-alt:before {\n content: \"\\e032\";\n}\n.glyphicon-lock:before {\n content: \"\\e033\";\n}\n.glyphicon-flag:before {\n content: \"\\e034\";\n}\n.glyphicon-headphones:before {\n content: \"\\e035\";\n}\n.glyphicon-volume-off:before {\n content: \"\\e036\";\n}\n.glyphicon-volume-down:before {\n content: \"\\e037\";\n}\n.glyphicon-volume-up:before {\n content: \"\\e038\";\n}\n.glyphicon-qrcode:before {\n content: \"\\e039\";\n}\n.glyphicon-barcode:before {\n content: \"\\e040\";\n}\n.glyphicon-tag:before {\n content: \"\\e041\";\n}\n.glyphicon-tags:before {\n content: \"\\e042\";\n}\n.glyphicon-book:before {\n content: \"\\e043\";\n}\n.glyphicon-bookmark:before {\n content: \"\\e044\";\n}\n.glyphicon-print:before {\n content: \"\\e045\";\n}\n.glyphicon-camera:before {\n content: \"\\e046\";\n}\n.glyphicon-font:before {\n content: \"\\e047\";\n}\n.glyphicon-bold:before {\n content: \"\\e048\";\n}\n.glyphicon-italic:before {\n content: \"\\e049\";\n}\n.glyphicon-text-height:before {\n content: \"\\e050\";\n}\n.glyphicon-text-width:before {\n content: \"\\e051\";\n}\n.glyphicon-align-left:before {\n content: \"\\e052\";\n}\n.glyphicon-align-center:before {\n content: \"\\e053\";\n}\n.glyphicon-align-right:before {\n content: \"\\e054\";\n}\n.glyphicon-align-justify:before {\n content: \"\\e055\";\n}\n.glyphicon-list:before {\n content: \"\\e056\";\n}\n.glyphicon-indent-left:before {\n content: \"\\e057\";\n}\n.glyphicon-indent-right:before {\n content: \"\\e058\";\n}\n.glyphicon-facetime-video:before {\n content: \"\\e059\";\n}\n.glyphicon-picture:before {\n content: \"\\e060\";\n}\n.glyphicon-map-marker:before {\n content: \"\\e062\";\n}\n.glyphicon-adjust:before {\n content: \"\\e063\";\n}\n.glyphicon-tint:before {\n content: \"\\e064\";\n}\n.glyphicon-edit:before {\n content: \"\\e065\";\n}\n.glyphicon-share:before {\n content: \"\\e066\";\n}\n.glyphicon-check:before {\n content: \"\\e067\";\n}\n.glyphicon-move:before {\n content: \"\\e068\";\n}\n.glyphicon-step-backward:before {\n content: \"\\e069\";\n}\n.glyphicon-fast-backward:before {\n content: \"\\e070\";\n}\n.glyphicon-backward:before {\n content: \"\\e071\";\n}\n.glyphicon-play:before {\n content: \"\\e072\";\n}\n.glyphicon-pause:before {\n content: \"\\e073\";\n}\n.glyphicon-stop:before {\n content: \"\\e074\";\n}\n.glyphicon-forward:before {\n content: \"\\e075\";\n}\n.glyphicon-fast-forward:before {\n content: \"\\e076\";\n}\n.glyphicon-step-forward:before {\n content: \"\\e077\";\n}\n.glyphicon-eject:before {\n content: \"\\e078\";\n}\n.glyphicon-chevron-left:before {\n content: \"\\e079\";\n}\n.glyphicon-chevron-right:before {\n content: \"\\e080\";\n}\n.glyphicon-plus-sign:before {\n content: \"\\e081\";\n}\n.glyphicon-minus-sign:before {\n content: \"\\e082\";\n}\n.glyphicon-remove-sign:before {\n content: \"\\e083\";\n}\n.glyphicon-ok-sign:before {\n content: \"\\e084\";\n}\n.glyphicon-question-sign:before {\n content: \"\\e085\";\n}\n.glyphicon-info-sign:before {\n content: \"\\e086\";\n}\n.glyphicon-screenshot:before {\n content: \"\\e087\";\n}\n.glyphicon-remove-circle:before {\n content: \"\\e088\";\n}\n.glyphicon-ok-circle:before {\n content: \"\\e089\";\n}\n.glyphicon-ban-circle:before {\n content: \"\\e090\";\n}\n.glyphicon-arrow-left:before {\n content: \"\\e091\";\n}\n.glyphicon-arrow-right:before {\n content: \"\\e092\";\n}\n.glyphicon-arrow-up:before {\n content: \"\\e093\";\n}\n.glyphicon-arrow-down:before {\n content: \"\\e094\";\n}\n.glyphicon-share-alt:before {\n content: \"\\e095\";\n}\n.glyphicon-resize-full:before {\n content: \"\\e096\";\n}\n.glyphicon-resize-small:before {\n content: \"\\e097\";\n}\n.glyphicon-exclamation-sign:before {\n content: \"\\e101\";\n}\n.glyphicon-gift:before {\n content: \"\\e102\";\n}\n.glyphicon-leaf:before {\n content: \"\\e103\";\n}\n.glyphicon-fire:before {\n content: \"\\e104\";\n}\n.glyphicon-eye-open:before {\n content: \"\\e105\";\n}\n.glyphicon-eye-close:before {\n content: \"\\e106\";\n}\n.glyphicon-warning-sign:before {\n content: \"\\e107\";\n}\n.glyphicon-plane:before {\n content: \"\\e108\";\n}\n.glyphicon-calendar:before {\n content: \"\\e109\";\n}\n.glyphicon-random:before {\n content: \"\\e110\";\n}\n.glyphicon-comment:before {\n content: \"\\e111\";\n}\n.glyphicon-magnet:before {\n content: \"\\e112\";\n}\n.glyphicon-chevron-up:before {\n content: \"\\e113\";\n}\n.glyphicon-chevron-down:before {\n content: \"\\e114\";\n}\n.glyphicon-retweet:before {\n content: \"\\e115\";\n}\n.glyphicon-shopping-cart:before {\n content: \"\\e116\";\n}\n.glyphicon-folder-close:before {\n content: \"\\e117\";\n}\n.glyphicon-folder-open:before {\n content: \"\\e118\";\n}\n.glyphicon-resize-vertical:before {\n content: \"\\e119\";\n}\n.glyphicon-resize-horizontal:before {\n content: \"\\e120\";\n}\n.glyphicon-hdd:before {\n content: \"\\e121\";\n}\n.glyphicon-bullhorn:before {\n content: \"\\e122\";\n}\n.glyphicon-bell:before {\n content: \"\\e123\";\n}\n.glyphicon-certificate:before {\n content: \"\\e124\";\n}\n.glyphicon-thumbs-up:before {\n content: \"\\e125\";\n}\n.glyphicon-thumbs-down:before {\n content: \"\\e126\";\n}\n.glyphicon-hand-right:before {\n content: \"\\e127\";\n}\n.glyphicon-hand-left:before {\n content: \"\\e128\";\n}\n.glyphicon-hand-up:before {\n content: \"\\e129\";\n}\n.glyphicon-hand-down:before {\n content: \"\\e130\";\n}\n.glyphicon-circle-arrow-right:before {\n content: \"\\e131\";\n}\n.glyphicon-circle-arrow-left:before {\n content: \"\\e132\";\n}\n.glyphicon-circle-arrow-up:before {\n content: \"\\e133\";\n}\n.glyphicon-circle-arrow-down:before {\n content: \"\\e134\";\n}\n.glyphicon-globe:before {\n content: \"\\e135\";\n}\n.glyphicon-wrench:before {\n content: \"\\e136\";\n}\n.glyphicon-tasks:before {\n content: \"\\e137\";\n}\n.glyphicon-filter:before {\n content: \"\\e138\";\n}\n.glyphicon-briefcase:before {\n content: \"\\e139\";\n}\n.glyphicon-fullscreen:before {\n content: \"\\e140\";\n}\n.glyphicon-dashboard:before {\n content: \"\\e141\";\n}\n.glyphicon-paperclip:before {\n content: \"\\e142\";\n}\n.glyphicon-heart-empty:before {\n content: \"\\e143\";\n}\n.glyphicon-link:before {\n content: \"\\e144\";\n}\n.glyphicon-phone:before {\n content: \"\\e145\";\n}\n.glyphicon-pushpin:before {\n content: \"\\e146\";\n}\n.glyphicon-usd:before {\n content: \"\\e148\";\n}\n.glyphicon-gbp:before {\n content: \"\\e149\";\n}\n.glyphicon-sort:before {\n content: \"\\e150\";\n}\n.glyphicon-sort-by-alphabet:before {\n content: \"\\e151\";\n}\n.glyphicon-sort-by-alphabet-alt:before {\n content: \"\\e152\";\n}\n.glyphicon-sort-by-order:before {\n content: \"\\e153\";\n}\n.glyphicon-sort-by-order-alt:before {\n content: \"\\e154\";\n}\n.glyphicon-sort-by-attributes:before {\n content: \"\\e155\";\n}\n.glyphicon-sort-by-attributes-alt:before {\n content: \"\\e156\";\n}\n.glyphicon-unchecked:before {\n content: \"\\e157\";\n}\n.glyphicon-expand:before {\n content: \"\\e158\";\n}\n.glyphicon-collapse-down:before {\n content: \"\\e159\";\n}\n.glyphicon-collapse-up:before {\n content: \"\\e160\";\n}\n.glyphicon-log-in:before {\n content: \"\\e161\";\n}\n.glyphicon-flash:before {\n content: \"\\e162\";\n}\n.glyphicon-log-out:before {\n content: \"\\e163\";\n}\n.glyphicon-new-window:before {\n content: \"\\e164\";\n}\n.glyphicon-record:before {\n content: \"\\e165\";\n}\n.glyphicon-save:before {\n content: \"\\e166\";\n}\n.glyphicon-open:before {\n content: \"\\e167\";\n}\n.glyphicon-saved:before {\n content: \"\\e168\";\n}\n.glyphicon-import:before {\n content: \"\\e169\";\n}\n.glyphicon-export:before {\n content: \"\\e170\";\n}\n.glyphicon-send:before {\n content: \"\\e171\";\n}\n.glyphicon-floppy-disk:before {\n content: \"\\e172\";\n}\n.glyphicon-floppy-saved:before {\n content: \"\\e173\";\n}\n.glyphicon-floppy-remove:before {\n content: \"\\e174\";\n}\n.glyphicon-floppy-save:before {\n content: \"\\e175\";\n}\n.glyphicon-floppy-open:before {\n content: \"\\e176\";\n}\n.glyphicon-credit-card:before {\n content: \"\\e177\";\n}\n.glyphicon-transfer:before {\n content: \"\\e178\";\n}\n.glyphicon-cutlery:before {\n content: \"\\e179\";\n}\n.glyphicon-header:before {\n content: \"\\e180\";\n}\n.glyphicon-compressed:before {\n content: \"\\e181\";\n}\n.glyphicon-earphone:before {\n content: \"\\e182\";\n}\n.glyphicon-phone-alt:before {\n content: \"\\e183\";\n}\n.glyphicon-tower:before {\n content: \"\\e184\";\n}\n.glyphicon-stats:before {\n content: \"\\e185\";\n}\n.glyphicon-sd-video:before {\n content: \"\\e186\";\n}\n.glyphicon-hd-video:before {\n content: \"\\e187\";\n}\n.glyphicon-subtitles:before {\n content: \"\\e188\";\n}\n.glyphicon-sound-stereo:before {\n content: \"\\e189\";\n}\n.glyphicon-sound-dolby:before {\n content: \"\\e190\";\n}\n.glyphicon-sound-5-1:before {\n content: \"\\e191\";\n}\n.glyphicon-sound-6-1:before {\n content: \"\\e192\";\n}\n.glyphicon-sound-7-1:before {\n content: \"\\e193\";\n}\n.glyphicon-copyright-mark:before {\n content: \"\\e194\";\n}\n.glyphicon-registration-mark:before {\n content: \"\\e195\";\n}\n.glyphicon-cloud-download:before {\n content: \"\\e197\";\n}\n.glyphicon-cloud-upload:before {\n content: \"\\e198\";\n}\n.glyphicon-tree-conifer:before {\n content: \"\\e199\";\n}\n.glyphicon-tree-deciduous:before {\n content: \"\\e200\";\n}\n.glyphicon-cd:before {\n content: \"\\e201\";\n}\n.glyphicon-save-file:before {\n content: \"\\e202\";\n}\n.glyphicon-open-file:before {\n content: \"\\e203\";\n}\n.glyphicon-level-up:before {\n content: \"\\e204\";\n}\n.glyphicon-copy:before {\n content: \"\\e205\";\n}\n.glyphicon-paste:before {\n content: \"\\e206\";\n}\n.glyphicon-alert:before {\n content: \"\\e209\";\n}\n.glyphicon-equalizer:before {\n content: \"\\e210\";\n}\n.glyphicon-king:before {\n content: \"\\e211\";\n}\n.glyphicon-queen:before {\n content: \"\\e212\";\n}\n.glyphicon-pawn:before {\n content: \"\\e213\";\n}\n.glyphicon-bishop:before {\n content: \"\\e214\";\n}\n.glyphicon-knight:before {\n content: \"\\e215\";\n}\n.glyphicon-baby-formula:before {\n content: \"\\e216\";\n}\n.glyphicon-tent:before {\n content: \"\\26fa\";\n}\n.glyphicon-blackboard:before {\n content: \"\\e218\";\n}\n.glyphicon-bed:before {\n content: \"\\e219\";\n}\n.glyphicon-apple:before {\n content: \"\\f8ff\";\n}\n.glyphicon-erase:before {\n content: \"\\e221\";\n}\n.glyphicon-hourglass:before {\n content: \"\\231b\";\n}\n.glyphicon-lamp:before {\n content: \"\\e223\";\n}\n.glyphicon-duplicate:before {\n content: \"\\e224\";\n}\n.glyphicon-piggy-bank:before {\n content: \"\\e225\";\n}\n.glyphicon-scissors:before {\n content: \"\\e226\";\n}\n.glyphicon-bitcoin:before {\n content: \"\\e227\";\n}\n.glyphicon-btc:before {\n content: \"\\e227\";\n}\n.glyphicon-xbt:before {\n content: \"\\e227\";\n}\n.glyphicon-yen:before {\n content: \"\\00a5\";\n}\n.glyphicon-jpy:before {\n content: \"\\00a5\";\n}\n.glyphicon-ruble:before {\n content: \"\\20bd\";\n}\n.glyphicon-rub:before {\n content: \"\\20bd\";\n}\n.glyphicon-scale:before {\n content: \"\\e230\";\n}\n.glyphicon-ice-lolly:before {\n content: \"\\e231\";\n}\n.glyphicon-ice-lolly-tasted:before {\n content: \"\\e232\";\n}\n.glyphicon-education:before {\n content: \"\\e233\";\n}\n.glyphicon-option-horizontal:before {\n content: \"\\e234\";\n}\n.glyphicon-option-vertical:before {\n content: \"\\e235\";\n}\n.glyphicon-menu-hamburger:before {\n content: \"\\e236\";\n}\n.glyphicon-modal-window:before {\n content: \"\\e237\";\n}\n.glyphicon-oil:before {\n content: \"\\e238\";\n}\n.glyphicon-grain:before {\n content: \"\\e239\";\n}\n.glyphicon-sunglasses:before {\n content: \"\\e240\";\n}\n.glyphicon-text-size:before {\n content: \"\\e241\";\n}\n.glyphicon-text-color:before {\n content: \"\\e242\";\n}\n.glyphicon-text-background:before {\n content: \"\\e243\";\n}\n.glyphicon-object-align-top:before {\n content: \"\\e244\";\n}\n.glyphicon-object-align-bottom:before {\n content: \"\\e245\";\n}\n.glyphicon-object-align-horizontal:before {\n content: \"\\e246\";\n}\n.glyphicon-object-align-left:before {\n content: \"\\e247\";\n}\n.glyphicon-object-align-vertical:before {\n content: \"\\e248\";\n}\n.glyphicon-object-align-right:before {\n content: \"\\e249\";\n}\n.glyphicon-triangle-right:before {\n content: \"\\e250\";\n}\n.glyphicon-triangle-left:before {\n content: \"\\e251\";\n}\n.glyphicon-triangle-bottom:before {\n content: \"\\e252\";\n}\n.glyphicon-triangle-top:before {\n content: \"\\e253\";\n}\n.glyphicon-console:before {\n content: \"\\e254\";\n}\n.glyphicon-superscript:before {\n content: \"\\e255\";\n}\n.glyphicon-subscript:before {\n content: \"\\e256\";\n}\n.glyphicon-menu-left:before {\n content: \"\\e257\";\n}\n.glyphicon-menu-right:before {\n content: \"\\e258\";\n}\n.glyphicon-menu-down:before {\n content: \"\\e259\";\n}\n.glyphicon-menu-up:before {\n content: \"\\e260\";\n}\n* {\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n}\n*:before,\n*:after {\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n}\nhtml {\n font-size: 10px;\n -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n}\nbody {\n font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n font-size: 14px;\n line-height: 1.42857143;\n color: #333333;\n background-color: #ffffff;\n}\ninput,\nbutton,\nselect,\ntextarea {\n font-family: inherit;\n font-size: inherit;\n line-height: inherit;\n}\na {\n color: #337ab7;\n text-decoration: none;\n}\na:hover,\na:focus {\n color: #23527c;\n text-decoration: underline;\n}\na:focus {\n outline: thin dotted;\n outline: 5px auto -webkit-focus-ring-color;\n outline-offset: -2px;\n}\nfigure {\n margin: 0;\n}\nimg {\n vertical-align: middle;\n}\n.img-responsive,\n.thumbnail > img,\n.thumbnail a > img,\n.carousel-inner > .item > img,\n.carousel-inner > .item > a > img {\n display: block;\n max-width: 100%;\n height: auto;\n}\n.img-rounded {\n border-radius: 6px;\n}\n.img-thumbnail {\n padding: 4px;\n line-height: 1.42857143;\n background-color: #ffffff;\n border: 1px solid #dddddd;\n border-radius: 4px;\n -webkit-transition: all 0.2s ease-in-out;\n -o-transition: all 0.2s ease-in-out;\n transition: all 0.2s ease-in-out;\n display: inline-block;\n max-width: 100%;\n height: auto;\n}\n.img-circle {\n border-radius: 50%;\n}\nhr {\n margin-top: 20px;\n margin-bottom: 20px;\n border: 0;\n border-top: 1px solid #eeeeee;\n}\n.sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n margin: -1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n border: 0;\n}\n.sr-only-focusable:active,\n.sr-only-focusable:focus {\n position: static;\n width: auto;\n height: auto;\n margin: 0;\n overflow: visible;\n clip: auto;\n}\n[role=\"button\"] {\n cursor: pointer;\n}\nh1,\nh2,\nh3,\nh4,\nh5,\nh6,\n.h1,\n.h2,\n.h3,\n.h4,\n.h5,\n.h6 {\n font-family: inherit;\n font-weight: 500;\n line-height: 1.1;\n color: inherit;\n}\nh1 small,\nh2 small,\nh3 small,\nh4 small,\nh5 small,\nh6 small,\n.h1 small,\n.h2 small,\n.h3 small,\n.h4 small,\n.h5 small,\n.h6 small,\nh1 .small,\nh2 .small,\nh3 .small,\nh4 .small,\nh5 .small,\nh6 .small,\n.h1 .small,\n.h2 .small,\n.h3 .small,\n.h4 .small,\n.h5 .small,\n.h6 .small {\n font-weight: normal;\n line-height: 1;\n color: #777777;\n}\nh1,\n.h1,\nh2,\n.h2,\nh3,\n.h3 {\n margin-top: 20px;\n margin-bottom: 10px;\n}\nh1 small,\n.h1 small,\nh2 small,\n.h2 small,\nh3 small,\n.h3 small,\nh1 .small,\n.h1 .small,\nh2 .small,\n.h2 .small,\nh3 .small,\n.h3 .small {\n font-size: 65%;\n}\nh4,\n.h4,\nh5,\n.h5,\nh6,\n.h6 {\n margin-top: 10px;\n margin-bottom: 10px;\n}\nh4 small,\n.h4 small,\nh5 small,\n.h5 small,\nh6 small,\n.h6 small,\nh4 .small,\n.h4 .small,\nh5 .small,\n.h5 .small,\nh6 .small,\n.h6 .small {\n font-size: 75%;\n}\nh1,\n.h1 {\n font-size: 36px;\n}\nh2,\n.h2 {\n font-size: 30px;\n}\nh3,\n.h3 {\n font-size: 24px;\n}\nh4,\n.h4 {\n font-size: 18px;\n}\nh5,\n.h5 {\n font-size: 14px;\n}\nh6,\n.h6 {\n font-size: 12px;\n}\np {\n margin: 0 0 10px;\n}\n.lead {\n margin-bottom: 20px;\n font-size: 16px;\n font-weight: 300;\n line-height: 1.4;\n}\n@media (min-width: 768px) {\n .lead {\n font-size: 21px;\n }\n}\nsmall,\n.small {\n font-size: 85%;\n}\nmark,\n.mark {\n background-color: #fcf8e3;\n padding: .2em;\n}\n.text-left {\n text-align: left;\n}\n.text-right {\n text-align: right;\n}\n.text-center {\n text-align: center;\n}\n.text-justify {\n text-align: justify;\n}\n.text-nowrap {\n white-space: nowrap;\n}\n.text-lowercase {\n text-transform: lowercase;\n}\n.text-uppercase {\n text-transform: uppercase;\n}\n.text-capitalize {\n text-transform: capitalize;\n}\n.text-muted {\n color: #777777;\n}\n.text-primary {\n color: #337ab7;\n}\na.text-primary:hover {\n color: #286090;\n}\n.text-success {\n color: #3c763d;\n}\na.text-success:hover {\n color: #2b542c;\n}\n.text-info {\n color: #31708f;\n}\na.text-info:hover {\n color: #245269;\n}\n.text-warning {\n color: #8a6d3b;\n}\na.text-warning:hover {\n color: #66512c;\n}\n.text-danger {\n color: #a94442;\n}\na.text-danger:hover {\n color: #843534;\n}\n.bg-primary {\n color: #fff;\n background-color: #337ab7;\n}\na.bg-primary:hover {\n background-color: #286090;\n}\n.bg-success {\n background-color: #dff0d8;\n}\na.bg-success:hover {\n background-color: #c1e2b3;\n}\n.bg-info {\n background-color: #d9edf7;\n}\na.bg-info:hover {\n background-color: #afd9ee;\n}\n.bg-warning {\n background-color: #fcf8e3;\n}\na.bg-warning:hover {\n background-color: #f7ecb5;\n}\n.bg-danger {\n background-color: #f2dede;\n}\na.bg-danger:hover {\n background-color: #e4b9b9;\n}\n.page-header {\n padding-bottom: 9px;\n margin: 40px 0 20px;\n border-bottom: 1px solid #eeeeee;\n}\nul,\nol {\n margin-top: 0;\n margin-bottom: 10px;\n}\nul ul,\nol ul,\nul ol,\nol ol {\n margin-bottom: 0;\n}\n.list-unstyled {\n padding-left: 0;\n list-style: none;\n}\n.list-inline {\n padding-left: 0;\n list-style: none;\n margin-left: -5px;\n}\n.list-inline > li {\n display: inline-block;\n padding-left: 5px;\n padding-right: 5px;\n}\ndl {\n margin-top: 0;\n margin-bottom: 20px;\n}\ndt,\ndd {\n line-height: 1.42857143;\n}\ndt {\n font-weight: bold;\n}\ndd {\n margin-left: 0;\n}\n@media (min-width: 768px) {\n .dl-horizontal dt {\n float: left;\n width: 160px;\n clear: left;\n text-align: right;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .dl-horizontal dd {\n margin-left: 180px;\n }\n}\nabbr[title],\nabbr[data-original-title] {\n cursor: help;\n border-bottom: 1px dotted #777777;\n}\n.initialism {\n font-size: 90%;\n text-transform: uppercase;\n}\nblockquote {\n padding: 10px 20px;\n margin: 0 0 20px;\n font-size: 17.5px;\n border-left: 5px solid #eeeeee;\n}\nblockquote p:last-child,\nblockquote ul:last-child,\nblockquote ol:last-child {\n margin-bottom: 0;\n}\nblockquote footer,\nblockquote small,\nblockquote .small {\n display: block;\n font-size: 80%;\n line-height: 1.42857143;\n color: #777777;\n}\nblockquote footer:before,\nblockquote small:before,\nblockquote .small:before {\n content: '\\2014 \\00A0';\n}\n.blockquote-reverse,\nblockquote.pull-right {\n padding-right: 15px;\n padding-left: 0;\n border-right: 5px solid #eeeeee;\n border-left: 0;\n text-align: right;\n}\n.blockquote-reverse footer:before,\nblockquote.pull-right footer:before,\n.blockquote-reverse small:before,\nblockquote.pull-right small:before,\n.blockquote-reverse .small:before,\nblockquote.pull-right .small:before {\n content: '';\n}\n.blockquote-reverse footer:after,\nblockquote.pull-right footer:after,\n.blockquote-reverse small:after,\nblockquote.pull-right small:after,\n.blockquote-reverse .small:after,\nblockquote.pull-right .small:after {\n content: '\\00A0 \\2014';\n}\naddress {\n margin-bottom: 20px;\n font-style: normal;\n line-height: 1.42857143;\n}\ncode,\nkbd,\npre,\nsamp {\n font-family: Menlo, Monaco, Consolas, \"Courier New\", monospace;\n}\ncode {\n padding: 2px 4px;\n font-size: 90%;\n color: #c7254e;\n background-color: #f9f2f4;\n border-radius: 4px;\n}\nkbd {\n padding: 2px 4px;\n font-size: 90%;\n color: #ffffff;\n background-color: #333333;\n border-radius: 3px;\n box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.25);\n}\nkbd kbd {\n padding: 0;\n font-size: 100%;\n font-weight: bold;\n box-shadow: none;\n}\npre {\n display: block;\n padding: 9.5px;\n margin: 0 0 10px;\n font-size: 13px;\n line-height: 1.42857143;\n word-break: break-all;\n word-wrap: break-word;\n color: #333333;\n background-color: #f5f5f5;\n border: 1px solid #cccccc;\n border-radius: 4px;\n}\npre code {\n padding: 0;\n font-size: inherit;\n color: inherit;\n white-space: pre-wrap;\n background-color: transparent;\n border-radius: 0;\n}\n.pre-scrollable {\n max-height: 340px;\n overflow-y: scroll;\n}\n.container {\n margin-right: auto;\n margin-left: auto;\n padding-left: 15px;\n padding-right: 15px;\n}\n@media (min-width: 768px) {\n .container {\n width: 750px;\n }\n}\n@media (min-width: 992px) {\n .container {\n width: 970px;\n }\n}\n@media (min-width: 1200px) {\n .container {\n width: 1170px;\n }\n}\n.container-fluid {\n margin-right: auto;\n margin-left: auto;\n padding-left: 15px;\n padding-right: 15px;\n}\n.row {\n margin-left: -15px;\n margin-right: -15px;\n}\n.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {\n position: relative;\n min-height: 1px;\n padding-left: 15px;\n padding-right: 15px;\n}\n.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 {\n float: left;\n}\n.col-xs-12 {\n width: 100%;\n}\n.col-xs-11 {\n width: 91.66666667%;\n}\n.col-xs-10 {\n width: 83.33333333%;\n}\n.col-xs-9 {\n width: 75%;\n}\n.col-xs-8 {\n width: 66.66666667%;\n}\n.col-xs-7 {\n width: 58.33333333%;\n}\n.col-xs-6 {\n width: 50%;\n}\n.col-xs-5 {\n width: 41.66666667%;\n}\n.col-xs-4 {\n width: 33.33333333%;\n}\n.col-xs-3 {\n width: 25%;\n}\n.col-xs-2 {\n width: 16.66666667%;\n}\n.col-xs-1 {\n width: 8.33333333%;\n}\n.col-xs-pull-12 {\n right: 100%;\n}\n.col-xs-pull-11 {\n right: 91.66666667%;\n}\n.col-xs-pull-10 {\n right: 83.33333333%;\n}\n.col-xs-pull-9 {\n right: 75%;\n}\n.col-xs-pull-8 {\n right: 66.66666667%;\n}\n.col-xs-pull-7 {\n right: 58.33333333%;\n}\n.col-xs-pull-6 {\n right: 50%;\n}\n.col-xs-pull-5 {\n right: 41.66666667%;\n}\n.col-xs-pull-4 {\n right: 33.33333333%;\n}\n.col-xs-pull-3 {\n right: 25%;\n}\n.col-xs-pull-2 {\n right: 16.66666667%;\n}\n.col-xs-pull-1 {\n right: 8.33333333%;\n}\n.col-xs-pull-0 {\n right: auto;\n}\n.col-xs-push-12 {\n left: 100%;\n}\n.col-xs-push-11 {\n left: 91.66666667%;\n}\n.col-xs-push-10 {\n left: 83.33333333%;\n}\n.col-xs-push-9 {\n left: 75%;\n}\n.col-xs-push-8 {\n left: 66.66666667%;\n}\n.col-xs-push-7 {\n left: 58.33333333%;\n}\n.col-xs-push-6 {\n left: 50%;\n}\n.col-xs-push-5 {\n left: 41.66666667%;\n}\n.col-xs-push-4 {\n left: 33.33333333%;\n}\n.col-xs-push-3 {\n left: 25%;\n}\n.col-xs-push-2 {\n left: 16.66666667%;\n}\n.col-xs-push-1 {\n left: 8.33333333%;\n}\n.col-xs-push-0 {\n left: auto;\n}\n.col-xs-offset-12 {\n margin-left: 100%;\n}\n.col-xs-offset-11 {\n margin-left: 91.66666667%;\n}\n.col-xs-offset-10 {\n margin-left: 83.33333333%;\n}\n.col-xs-offset-9 {\n margin-left: 75%;\n}\n.col-xs-offset-8 {\n margin-left: 66.66666667%;\n}\n.col-xs-offset-7 {\n margin-left: 58.33333333%;\n}\n.col-xs-offset-6 {\n margin-left: 50%;\n}\n.col-xs-offset-5 {\n margin-left: 41.66666667%;\n}\n.col-xs-offset-4 {\n margin-left: 33.33333333%;\n}\n.col-xs-offset-3 {\n margin-left: 25%;\n}\n.col-xs-offset-2 {\n margin-left: 16.66666667%;\n}\n.col-xs-offset-1 {\n margin-left: 8.33333333%;\n}\n.col-xs-offset-0 {\n margin-left: 0%;\n}\n@media (min-width: 768px) {\n .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {\n float: left;\n }\n .col-sm-12 {\n width: 100%;\n }\n .col-sm-11 {\n width: 91.66666667%;\n }\n .col-sm-10 {\n width: 83.33333333%;\n }\n .col-sm-9 {\n width: 75%;\n }\n .col-sm-8 {\n width: 66.66666667%;\n }\n .col-sm-7 {\n width: 58.33333333%;\n }\n .col-sm-6 {\n width: 50%;\n }\n .col-sm-5 {\n width: 41.66666667%;\n }\n .col-sm-4 {\n width: 33.33333333%;\n }\n .col-sm-3 {\n width: 25%;\n }\n .col-sm-2 {\n width: 16.66666667%;\n }\n .col-sm-1 {\n width: 8.33333333%;\n }\n .col-sm-pull-12 {\n right: 100%;\n }\n .col-sm-pull-11 {\n right: 91.66666667%;\n }\n .col-sm-pull-10 {\n right: 83.33333333%;\n }\n .col-sm-pull-9 {\n right: 75%;\n }\n .col-sm-pull-8 {\n right: 66.66666667%;\n }\n .col-sm-pull-7 {\n right: 58.33333333%;\n }\n .col-sm-pull-6 {\n right: 50%;\n }\n .col-sm-pull-5 {\n right: 41.66666667%;\n }\n .col-sm-pull-4 {\n right: 33.33333333%;\n }\n .col-sm-pull-3 {\n right: 25%;\n }\n .col-sm-pull-2 {\n right: 16.66666667%;\n }\n .col-sm-pull-1 {\n right: 8.33333333%;\n }\n .col-sm-pull-0 {\n right: auto;\n }\n .col-sm-push-12 {\n left: 100%;\n }\n .col-sm-push-11 {\n left: 91.66666667%;\n }\n .col-sm-push-10 {\n left: 83.33333333%;\n }\n .col-sm-push-9 {\n left: 75%;\n }\n .col-sm-push-8 {\n left: 66.66666667%;\n }\n .col-sm-push-7 {\n left: 58.33333333%;\n }\n .col-sm-push-6 {\n left: 50%;\n }\n .col-sm-push-5 {\n left: 41.66666667%;\n }\n .col-sm-push-4 {\n left: 33.33333333%;\n }\n .col-sm-push-3 {\n left: 25%;\n }\n .col-sm-push-2 {\n left: 16.66666667%;\n }\n .col-sm-push-1 {\n left: 8.33333333%;\n }\n .col-sm-push-0 {\n left: auto;\n }\n .col-sm-offset-12 {\n margin-left: 100%;\n }\n .col-sm-offset-11 {\n margin-left: 91.66666667%;\n }\n .col-sm-offset-10 {\n margin-left: 83.33333333%;\n }\n .col-sm-offset-9 {\n margin-left: 75%;\n }\n .col-sm-offset-8 {\n margin-left: 66.66666667%;\n }\n .col-sm-offset-7 {\n margin-left: 58.33333333%;\n }\n .col-sm-offset-6 {\n margin-left: 50%;\n }\n .col-sm-offset-5 {\n margin-left: 41.66666667%;\n }\n .col-sm-offset-4 {\n margin-left: 33.33333333%;\n }\n .col-sm-offset-3 {\n margin-left: 25%;\n }\n .col-sm-offset-2 {\n margin-left: 16.66666667%;\n }\n .col-sm-offset-1 {\n margin-left: 8.33333333%;\n }\n .col-sm-offset-0 {\n margin-left: 0%;\n }\n}\n@media (min-width: 992px) {\n .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {\n float: left;\n }\n .col-md-12 {\n width: 100%;\n }\n .col-md-11 {\n width: 91.66666667%;\n }\n .col-md-10 {\n width: 83.33333333%;\n }\n .col-md-9 {\n width: 75%;\n }\n .col-md-8 {\n width: 66.66666667%;\n }\n .col-md-7 {\n width: 58.33333333%;\n }\n .col-md-6 {\n width: 50%;\n }\n .col-md-5 {\n width: 41.66666667%;\n }\n .col-md-4 {\n width: 33.33333333%;\n }\n .col-md-3 {\n width: 25%;\n }\n .col-md-2 {\n width: 16.66666667%;\n }\n .col-md-1 {\n width: 8.33333333%;\n }\n .col-md-pull-12 {\n right: 100%;\n }\n .col-md-pull-11 {\n right: 91.66666667%;\n }\n .col-md-pull-10 {\n right: 83.33333333%;\n }\n .col-md-pull-9 {\n right: 75%;\n }\n .col-md-pull-8 {\n right: 66.66666667%;\n }\n .col-md-pull-7 {\n right: 58.33333333%;\n }\n .col-md-pull-6 {\n right: 50%;\n }\n .col-md-pull-5 {\n right: 41.66666667%;\n }\n .col-md-pull-4 {\n right: 33.33333333%;\n }\n .col-md-pull-3 {\n right: 25%;\n }\n .col-md-pull-2 {\n right: 16.66666667%;\n }\n .col-md-pull-1 {\n right: 8.33333333%;\n }\n .col-md-pull-0 {\n right: auto;\n }\n .col-md-push-12 {\n left: 100%;\n }\n .col-md-push-11 {\n left: 91.66666667%;\n }\n .col-md-push-10 {\n left: 83.33333333%;\n }\n .col-md-push-9 {\n left: 75%;\n }\n .col-md-push-8 {\n left: 66.66666667%;\n }\n .col-md-push-7 {\n left: 58.33333333%;\n }\n .col-md-push-6 {\n left: 50%;\n }\n .col-md-push-5 {\n left: 41.66666667%;\n }\n .col-md-push-4 {\n left: 33.33333333%;\n }\n .col-md-push-3 {\n left: 25%;\n }\n .col-md-push-2 {\n left: 16.66666667%;\n }\n .col-md-push-1 {\n left: 8.33333333%;\n }\n .col-md-push-0 {\n left: auto;\n }\n .col-md-offset-12 {\n margin-left: 100%;\n }\n .col-md-offset-11 {\n margin-left: 91.66666667%;\n }\n .col-md-offset-10 {\n margin-left: 83.33333333%;\n }\n .col-md-offset-9 {\n margin-left: 75%;\n }\n .col-md-offset-8 {\n margin-left: 66.66666667%;\n }\n .col-md-offset-7 {\n margin-left: 58.33333333%;\n }\n .col-md-offset-6 {\n margin-left: 50%;\n }\n .col-md-offset-5 {\n margin-left: 41.66666667%;\n }\n .col-md-offset-4 {\n margin-left: 33.33333333%;\n }\n .col-md-offset-3 {\n margin-left: 25%;\n }\n .col-md-offset-2 {\n margin-left: 16.66666667%;\n }\n .col-md-offset-1 {\n margin-left: 8.33333333%;\n }\n .col-md-offset-0 {\n margin-left: 0%;\n }\n}\n@media (min-width: 1200px) {\n .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {\n float: left;\n }\n .col-lg-12 {\n width: 100%;\n }\n .col-lg-11 {\n width: 91.66666667%;\n }\n .col-lg-10 {\n width: 83.33333333%;\n }\n .col-lg-9 {\n width: 75%;\n }\n .col-lg-8 {\n width: 66.66666667%;\n }\n .col-lg-7 {\n width: 58.33333333%;\n }\n .col-lg-6 {\n width: 50%;\n }\n .col-lg-5 {\n width: 41.66666667%;\n }\n .col-lg-4 {\n width: 33.33333333%;\n }\n .col-lg-3 {\n width: 25%;\n }\n .col-lg-2 {\n width: 16.66666667%;\n }\n .col-lg-1 {\n width: 8.33333333%;\n }\n .col-lg-pull-12 {\n right: 100%;\n }\n .col-lg-pull-11 {\n right: 91.66666667%;\n }\n .col-lg-pull-10 {\n right: 83.33333333%;\n }\n .col-lg-pull-9 {\n right: 75%;\n }\n .col-lg-pull-8 {\n right: 66.66666667%;\n }\n .col-lg-pull-7 {\n right: 58.33333333%;\n }\n .col-lg-pull-6 {\n right: 50%;\n }\n .col-lg-pull-5 {\n right: 41.66666667%;\n }\n .col-lg-pull-4 {\n right: 33.33333333%;\n }\n .col-lg-pull-3 {\n right: 25%;\n }\n .col-lg-pull-2 {\n right: 16.66666667%;\n }\n .col-lg-pull-1 {\n right: 8.33333333%;\n }\n .col-lg-pull-0 {\n right: auto;\n }\n .col-lg-push-12 {\n left: 100%;\n }\n .col-lg-push-11 {\n left: 91.66666667%;\n }\n .col-lg-push-10 {\n left: 83.33333333%;\n }\n .col-lg-push-9 {\n left: 75%;\n }\n .col-lg-push-8 {\n left: 66.66666667%;\n }\n .col-lg-push-7 {\n left: 58.33333333%;\n }\n .col-lg-push-6 {\n left: 50%;\n }\n .col-lg-push-5 {\n left: 41.66666667%;\n }\n .col-lg-push-4 {\n left: 33.33333333%;\n }\n .col-lg-push-3 {\n left: 25%;\n }\n .col-lg-push-2 {\n left: 16.66666667%;\n }\n .col-lg-push-1 {\n left: 8.33333333%;\n }\n .col-lg-push-0 {\n left: auto;\n }\n .col-lg-offset-12 {\n margin-left: 100%;\n }\n .col-lg-offset-11 {\n margin-left: 91.66666667%;\n }\n .col-lg-offset-10 {\n margin-left: 83.33333333%;\n }\n .col-lg-offset-9 {\n margin-left: 75%;\n }\n .col-lg-offset-8 {\n margin-left: 66.66666667%;\n }\n .col-lg-offset-7 {\n margin-left: 58.33333333%;\n }\n .col-lg-offset-6 {\n margin-left: 50%;\n }\n .col-lg-offset-5 {\n margin-left: 41.66666667%;\n }\n .col-lg-offset-4 {\n margin-left: 33.33333333%;\n }\n .col-lg-offset-3 {\n margin-left: 25%;\n }\n .col-lg-offset-2 {\n margin-left: 16.66666667%;\n }\n .col-lg-offset-1 {\n margin-left: 8.33333333%;\n }\n .col-lg-offset-0 {\n margin-left: 0%;\n }\n}\ntable {\n background-color: transparent;\n}\ncaption {\n padding-top: 8px;\n padding-bottom: 8px;\n color: #777777;\n text-align: left;\n}\nth {\n text-align: left;\n}\n.table {\n width: 100%;\n max-width: 100%;\n margin-bottom: 20px;\n}\n.table > thead > tr > th,\n.table > tbody > tr > th,\n.table > tfoot > tr > th,\n.table > thead > tr > td,\n.table > tbody > tr > td,\n.table > tfoot > tr > td {\n padding: 8px;\n line-height: 1.42857143;\n vertical-align: top;\n border-top: 1px solid #dddddd;\n}\n.table > thead > tr > th {\n vertical-align: bottom;\n border-bottom: 2px solid #dddddd;\n}\n.table > caption + thead > tr:first-child > th,\n.table > colgroup + thead > tr:first-child > th,\n.table > thead:first-child > tr:first-child > th,\n.table > caption + thead > tr:first-child > td,\n.table > colgroup + thead > tr:first-child > td,\n.table > thead:first-child > tr:first-child > td {\n border-top: 0;\n}\n.table > tbody + tbody {\n border-top: 2px solid #dddddd;\n}\n.table .table {\n background-color: #ffffff;\n}\n.table-condensed > thead > tr > th,\n.table-condensed > tbody > tr > th,\n.table-condensed > tfoot > tr > th,\n.table-condensed > thead > tr > td,\n.table-condensed > tbody > tr > td,\n.table-condensed > tfoot > tr > td {\n padding: 5px;\n}\n.table-bordered {\n border: 1px solid #dddddd;\n}\n.table-bordered > thead > tr > th,\n.table-bordered > tbody > tr > th,\n.table-bordered > tfoot > tr > th,\n.table-bordered > thead > tr > td,\n.table-bordered > tbody > tr > td,\n.table-bordered > tfoot > tr > td {\n border: 1px solid #dddddd;\n}\n.table-bordered > thead > tr > th,\n.table-bordered > thead > tr > td {\n border-bottom-width: 2px;\n}\n.table-striped > tbody > tr:nth-of-type(odd) {\n background-color: #f9f9f9;\n}\n.table-hover > tbody > tr:hover {\n background-color: #f5f5f5;\n}\ntable col[class*=\"col-\"] {\n position: static;\n float: none;\n display: table-column;\n}\ntable td[class*=\"col-\"],\ntable th[class*=\"col-\"] {\n position: static;\n float: none;\n display: table-cell;\n}\n.table > thead > tr > td.active,\n.table > tbody > tr > td.active,\n.table > tfoot > tr > td.active,\n.table > thead > tr > th.active,\n.table > tbody > tr > th.active,\n.table > tfoot > tr > th.active,\n.table > thead > tr.active > td,\n.table > tbody > tr.active > td,\n.table > tfoot > tr.active > td,\n.table > thead > tr.active > th,\n.table > tbody > tr.active > th,\n.table > tfoot > tr.active > th {\n background-color: #f5f5f5;\n}\n.table-hover > tbody > tr > td.active:hover,\n.table-hover > tbody > tr > th.active:hover,\n.table-hover > tbody > tr.active:hover > td,\n.table-hover > tbody > tr:hover > .active,\n.table-hover > tbody > tr.active:hover > th {\n background-color: #e8e8e8;\n}\n.table > thead > tr > td.success,\n.table > tbody > tr > td.success,\n.table > tfoot > tr > td.success,\n.table > thead > tr > th.success,\n.table > tbody > tr > th.success,\n.table > tfoot > tr > th.success,\n.table > thead > tr.success > td,\n.table > tbody > tr.success > td,\n.table > tfoot > tr.success > td,\n.table > thead > tr.success > th,\n.table > tbody > tr.success > th,\n.table > tfoot > tr.success > th {\n background-color: #dff0d8;\n}\n.table-hover > tbody > tr > td.success:hover,\n.table-hover > tbody > tr > th.success:hover,\n.table-hover > tbody > tr.success:hover > td,\n.table-hover > tbody > tr:hover > .success,\n.table-hover > tbody > tr.success:hover > th {\n background-color: #d0e9c6;\n}\n.table > thead > tr > td.info,\n.table > tbody > tr > td.info,\n.table > tfoot > tr > td.info,\n.table > thead > tr > th.info,\n.table > tbody > tr > th.info,\n.table > tfoot > tr > th.info,\n.table > thead > tr.info > td,\n.table > tbody > tr.info > td,\n.table > tfoot > tr.info > td,\n.table > thead > tr.info > th,\n.table > tbody > tr.info > th,\n.table > tfoot > tr.info > th {\n background-color: #d9edf7;\n}\n.table-hover > tbody > tr > td.info:hover,\n.table-hover > tbody > tr > th.info:hover,\n.table-hover > tbody > tr.info:hover > td,\n.table-hover > tbody > tr:hover > .info,\n.table-hover > tbody > tr.info:hover > th {\n background-color: #c4e3f3;\n}\n.table > thead > tr > td.warning,\n.table > tbody > tr > td.warning,\n.table > tfoot > tr > td.warning,\n.table > thead > tr > th.warning,\n.table > tbody > tr > th.warning,\n.table > tfoot > tr > th.warning,\n.table > thead > tr.warning > td,\n.table > tbody > tr.warning > td,\n.table > tfoot > tr.warning > td,\n.table > thead > tr.warning > th,\n.table > tbody > tr.warning > th,\n.table > tfoot > tr.warning > th {\n background-color: #fcf8e3;\n}\n.table-hover > tbody > tr > td.warning:hover,\n.table-hover > tbody > tr > th.warning:hover,\n.table-hover > tbody > tr.warning:hover > td,\n.table-hover > tbody > tr:hover > .warning,\n.table-hover > tbody > tr.warning:hover > th {\n background-color: #faf2cc;\n}\n.table > thead > tr > td.danger,\n.table > tbody > tr > td.danger,\n.table > tfoot > tr > td.danger,\n.table > thead > tr > th.danger,\n.table > tbody > tr > th.danger,\n.table > tfoot > tr > th.danger,\n.table > thead > tr.danger > td,\n.table > tbody > tr.danger > td,\n.table > tfoot > tr.danger > td,\n.table > thead > tr.danger > th,\n.table > tbody > tr.danger > th,\n.table > tfoot > tr.danger > th {\n background-color: #f2dede;\n}\n.table-hover > tbody > tr > td.danger:hover,\n.table-hover > tbody > tr > th.danger:hover,\n.table-hover > tbody > tr.danger:hover > td,\n.table-hover > tbody > tr:hover > .danger,\n.table-hover > tbody > tr.danger:hover > th {\n background-color: #ebcccc;\n}\n.table-responsive {\n overflow-x: auto;\n min-height: 0.01%;\n}\n@media screen and (max-width: 767px) {\n .table-responsive {\n width: 100%;\n margin-bottom: 15px;\n overflow-y: hidden;\n -ms-overflow-style: -ms-autohiding-scrollbar;\n border: 1px solid #dddddd;\n }\n .table-responsive > .table {\n margin-bottom: 0;\n }\n .table-responsive > .table > thead > tr > th,\n .table-responsive > .table > tbody > tr > th,\n .table-responsive > .table > tfoot > tr > th,\n .table-responsive > .table > thead > tr > td,\n .table-responsive > .table > tbody > tr > td,\n .table-responsive > .table > tfoot > tr > td {\n white-space: nowrap;\n }\n .table-responsive > .table-bordered {\n border: 0;\n }\n .table-responsive > .table-bordered > thead > tr > th:first-child,\n .table-responsive > .table-bordered > tbody > tr > th:first-child,\n .table-responsive > .table-bordered > tfoot > tr > th:first-child,\n .table-responsive > .table-bordered > thead > tr > td:first-child,\n .table-responsive > .table-bordered > tbody > tr > td:first-child,\n .table-responsive > .table-bordered > tfoot > tr > td:first-child {\n border-left: 0;\n }\n .table-responsive > .table-bordered > thead > tr > th:last-child,\n .table-responsive > .table-bordered > tbody > tr > th:last-child,\n .table-responsive > .table-bordered > tfoot > tr > th:last-child,\n .table-responsive > .table-bordered > thead > tr > td:last-child,\n .table-responsive > .table-bordered > tbody > tr > td:last-child,\n .table-responsive > .table-bordered > tfoot > tr > td:last-child {\n border-right: 0;\n }\n .table-responsive > .table-bordered > tbody > tr:last-child > th,\n .table-responsive > .table-bordered > tfoot > tr:last-child > th,\n .table-responsive > .table-bordered > tbody > tr:last-child > td,\n .table-responsive > .table-bordered > tfoot > tr:last-child > td {\n border-bottom: 0;\n }\n}\nfieldset {\n padding: 0;\n margin: 0;\n border: 0;\n min-width: 0;\n}\nlegend {\n display: block;\n width: 100%;\n padding: 0;\n margin-bottom: 20px;\n font-size: 21px;\n line-height: inherit;\n color: #333333;\n border: 0;\n border-bottom: 1px solid #e5e5e5;\n}\nlabel {\n display: inline-block;\n max-width: 100%;\n margin-bottom: 5px;\n font-weight: bold;\n}\ninput[type=\"search\"] {\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n}\ninput[type=\"radio\"],\ninput[type=\"checkbox\"] {\n margin: 4px 0 0;\n margin-top: 1px \\9;\n line-height: normal;\n}\ninput[type=\"file\"] {\n display: block;\n}\ninput[type=\"range\"] {\n display: block;\n width: 100%;\n}\nselect[multiple],\nselect[size] {\n height: auto;\n}\ninput[type=\"file\"]:focus,\ninput[type=\"radio\"]:focus,\ninput[type=\"checkbox\"]:focus {\n outline: thin dotted;\n outline: 5px auto -webkit-focus-ring-color;\n outline-offset: -2px;\n}\noutput {\n display: block;\n padding-top: 7px;\n font-size: 14px;\n line-height: 1.42857143;\n color: #555555;\n}\n.form-control {\n display: block;\n width: 100%;\n height: 34px;\n padding: 6px 12px;\n font-size: 14px;\n line-height: 1.42857143;\n color: #555555;\n background-color: #ffffff;\n background-image: none;\n border: 1px solid #cccccc;\n border-radius: 4px;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n -webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;\n -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;\n transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;\n}\n.form-control:focus {\n border-color: #66afe9;\n outline: 0;\n -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);\n box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);\n}\n.form-control::-moz-placeholder {\n color: #999999;\n opacity: 1;\n}\n.form-control:-ms-input-placeholder {\n color: #999999;\n}\n.form-control::-webkit-input-placeholder {\n color: #999999;\n}\n.form-control[disabled],\n.form-control[readonly],\nfieldset[disabled] .form-control {\n background-color: #eeeeee;\n opacity: 1;\n}\n.form-control[disabled],\nfieldset[disabled] .form-control {\n cursor: not-allowed;\n}\ntextarea.form-control {\n height: auto;\n}\ninput[type=\"search\"] {\n -webkit-appearance: none;\n}\n@media screen and (-webkit-min-device-pixel-ratio: 0) {\n input[type=\"date\"],\n input[type=\"time\"],\n input[type=\"datetime-local\"],\n input[type=\"month\"] {\n line-height: 34px;\n }\n input[type=\"date\"].input-sm,\n input[type=\"time\"].input-sm,\n input[type=\"datetime-local\"].input-sm,\n input[type=\"month\"].input-sm,\n .input-group-sm input[type=\"date\"],\n .input-group-sm input[type=\"time\"],\n .input-group-sm input[type=\"datetime-local\"],\n .input-group-sm input[type=\"month\"] {\n line-height: 30px;\n }\n input[type=\"date\"].input-lg,\n input[type=\"time\"].input-lg,\n input[type=\"datetime-local\"].input-lg,\n input[type=\"month\"].input-lg,\n .input-group-lg input[type=\"date\"],\n .input-group-lg input[type=\"time\"],\n .input-group-lg input[type=\"datetime-local\"],\n .input-group-lg input[type=\"month\"] {\n line-height: 46px;\n }\n}\n.form-group {\n margin-bottom: 15px;\n}\n.radio,\n.checkbox {\n position: relative;\n display: block;\n margin-top: 10px;\n margin-bottom: 10px;\n}\n.radio label,\n.checkbox label {\n min-height: 20px;\n padding-left: 20px;\n margin-bottom: 0;\n font-weight: normal;\n cursor: pointer;\n}\n.radio input[type=\"radio\"],\n.radio-inline input[type=\"radio\"],\n.checkbox input[type=\"checkbox\"],\n.checkbox-inline input[type=\"checkbox\"] {\n position: absolute;\n margin-left: -20px;\n margin-top: 4px \\9;\n}\n.radio + .radio,\n.checkbox + .checkbox {\n margin-top: -5px;\n}\n.radio-inline,\n.checkbox-inline {\n position: relative;\n display: inline-block;\n padding-left: 20px;\n margin-bottom: 0;\n vertical-align: middle;\n font-weight: normal;\n cursor: pointer;\n}\n.radio-inline + .radio-inline,\n.checkbox-inline + .checkbox-inline {\n margin-top: 0;\n margin-left: 10px;\n}\ninput[type=\"radio\"][disabled],\ninput[type=\"checkbox\"][disabled],\ninput[type=\"radio\"].disabled,\ninput[type=\"checkbox\"].disabled,\nfieldset[disabled] input[type=\"radio\"],\nfieldset[disabled] input[type=\"checkbox\"] {\n cursor: not-allowed;\n}\n.radio-inline.disabled,\n.checkbox-inline.disabled,\nfieldset[disabled] .radio-inline,\nfieldset[disabled] .checkbox-inline {\n cursor: not-allowed;\n}\n.radio.disabled label,\n.checkbox.disabled label,\nfieldset[disabled] .radio label,\nfieldset[disabled] .checkbox label {\n cursor: not-allowed;\n}\n.form-control-static {\n padding-top: 7px;\n padding-bottom: 7px;\n margin-bottom: 0;\n min-height: 34px;\n}\n.form-control-static.input-lg,\n.form-control-static.input-sm {\n padding-left: 0;\n padding-right: 0;\n}\n.input-sm {\n height: 30px;\n padding: 5px 10px;\n font-size: 12px;\n line-height: 1.5;\n border-radius: 3px;\n}\nselect.input-sm {\n height: 30px;\n line-height: 30px;\n}\ntextarea.input-sm,\nselect[multiple].input-sm {\n height: auto;\n}\n.form-group-sm .form-control {\n height: 30px;\n padding: 5px 10px;\n font-size: 12px;\n line-height: 1.5;\n border-radius: 3px;\n}\nselect.form-group-sm .form-control {\n height: 30px;\n line-height: 30px;\n}\ntextarea.form-group-sm .form-control,\nselect[multiple].form-group-sm .form-control {\n height: auto;\n}\n.form-group-sm .form-control-static {\n height: 30px;\n padding: 5px 10px;\n font-size: 12px;\n line-height: 1.5;\n min-height: 32px;\n}\n.input-lg {\n height: 46px;\n padding: 10px 16px;\n font-size: 18px;\n line-height: 1.3333333;\n border-radius: 6px;\n}\nselect.input-lg {\n height: 46px;\n line-height: 46px;\n}\ntextarea.input-lg,\nselect[multiple].input-lg {\n height: auto;\n}\n.form-group-lg .form-control {\n height: 46px;\n padding: 10px 16px;\n font-size: 18px;\n line-height: 1.3333333;\n border-radius: 6px;\n}\nselect.form-group-lg .form-control {\n height: 46px;\n line-height: 46px;\n}\ntextarea.form-group-lg .form-control,\nselect[multiple].form-group-lg .form-control {\n height: auto;\n}\n.form-group-lg .form-control-static {\n height: 46px;\n padding: 10px 16px;\n font-size: 18px;\n line-height: 1.3333333;\n min-height: 38px;\n}\n.has-feedback {\n position: relative;\n}\n.has-feedback .form-control {\n padding-right: 42.5px;\n}\n.form-control-feedback {\n position: absolute;\n top: 0;\n right: 0;\n z-index: 2;\n display: block;\n width: 34px;\n height: 34px;\n line-height: 34px;\n text-align: center;\n pointer-events: none;\n}\n.input-lg + .form-control-feedback {\n width: 46px;\n height: 46px;\n line-height: 46px;\n}\n.input-sm + .form-control-feedback {\n width: 30px;\n height: 30px;\n line-height: 30px;\n}\n.has-success .help-block,\n.has-success .control-label,\n.has-success .radio,\n.has-success .checkbox,\n.has-success .radio-inline,\n.has-success .checkbox-inline,\n.has-success.radio label,\n.has-success.checkbox label,\n.has-success.radio-inline label,\n.has-success.checkbox-inline label {\n color: #3c763d;\n}\n.has-success .form-control {\n border-color: #3c763d;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n}\n.has-success .form-control:focus {\n border-color: #2b542c;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #67b168;\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #67b168;\n}\n.has-success .input-group-addon {\n color: #3c763d;\n border-color: #3c763d;\n background-color: #dff0d8;\n}\n.has-success .form-control-feedback {\n color: #3c763d;\n}\n.has-warning .help-block,\n.has-warning .control-label,\n.has-warning .radio,\n.has-warning .checkbox,\n.has-warning .radio-inline,\n.has-warning .checkbox-inline,\n.has-warning.radio label,\n.has-warning.checkbox label,\n.has-warning.radio-inline label,\n.has-warning.checkbox-inline label {\n color: #8a6d3b;\n}\n.has-warning .form-control {\n border-color: #8a6d3b;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n}\n.has-warning .form-control:focus {\n border-color: #66512c;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #c0a16b;\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #c0a16b;\n}\n.has-warning .input-group-addon {\n color: #8a6d3b;\n border-color: #8a6d3b;\n background-color: #fcf8e3;\n}\n.has-warning .form-control-feedback {\n color: #8a6d3b;\n}\n.has-error .help-block,\n.has-error .control-label,\n.has-error .radio,\n.has-error .checkbox,\n.has-error .radio-inline,\n.has-error .checkbox-inline,\n.has-error.radio label,\n.has-error.checkbox label,\n.has-error.radio-inline label,\n.has-error.checkbox-inline label {\n color: #a94442;\n}\n.has-error .form-control {\n border-color: #a94442;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);\n}\n.has-error .form-control:focus {\n border-color: #843534;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #ce8483;\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #ce8483;\n}\n.has-error .input-group-addon {\n color: #a94442;\n border-color: #a94442;\n background-color: #f2dede;\n}\n.has-error .form-control-feedback {\n color: #a94442;\n}\n.has-feedback label ~ .form-control-feedback {\n top: 25px;\n}\n.has-feedback label.sr-only ~ .form-control-feedback {\n top: 0;\n}\n.help-block {\n display: block;\n margin-top: 5px;\n margin-bottom: 10px;\n color: #737373;\n}\n@media (min-width: 768px) {\n .form-inline .form-group {\n display: inline-block;\n margin-bottom: 0;\n vertical-align: middle;\n }\n .form-inline .form-control {\n display: inline-block;\n width: auto;\n vertical-align: middle;\n }\n .form-inline .form-control-static {\n display: inline-block;\n }\n .form-inline .input-group {\n display: inline-table;\n vertical-align: middle;\n }\n .form-inline .input-group .input-group-addon,\n .form-inline .input-group .input-group-btn,\n .form-inline .input-group .form-control {\n width: auto;\n }\n .form-inline .input-group > .form-control {\n width: 100%;\n }\n .form-inline .control-label {\n margin-bottom: 0;\n vertical-align: middle;\n }\n .form-inline .radio,\n .form-inline .checkbox {\n display: inline-block;\n margin-top: 0;\n margin-bottom: 0;\n vertical-align: middle;\n }\n .form-inline .radio label,\n .form-inline .checkbox label {\n padding-left: 0;\n }\n .form-inline .radio input[type=\"radio\"],\n .form-inline .checkbox input[type=\"checkbox\"] {\n position: relative;\n margin-left: 0;\n }\n .form-inline .has-feedback .form-control-feedback {\n top: 0;\n }\n}\n.form-horizontal .radio,\n.form-horizontal .checkbox,\n.form-horizontal .radio-inline,\n.form-horizontal .checkbox-inline {\n margin-top: 0;\n margin-bottom: 0;\n padding-top: 7px;\n}\n.form-horizontal .radio,\n.form-horizontal .checkbox {\n min-height: 27px;\n}\n.form-horizontal .form-group {\n margin-left: -15px;\n margin-right: -15px;\n}\n@media (min-width: 768px) {\n .form-horizontal .control-label {\n text-align: right;\n margin-bottom: 0;\n padding-top: 7px;\n }\n}\n.form-horizontal .has-feedback .form-control-feedback {\n right: 15px;\n}\n@media (min-width: 768px) {\n .form-horizontal .form-group-lg .control-label {\n padding-top: 14.333333px;\n }\n}\n@media (min-width: 768px) {\n .form-horizontal .form-group-sm .control-label {\n padding-top: 6px;\n }\n}\n.btn {\n display: inline-block;\n margin-bottom: 0;\n font-weight: normal;\n text-align: center;\n vertical-align: middle;\n touch-action: manipulation;\n cursor: pointer;\n background-image: none;\n border: 1px solid transparent;\n white-space: nowrap;\n padding: 6px 12px;\n font-size: 14px;\n line-height: 1.42857143;\n border-radius: 4px;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n.btn:focus,\n.btn:active:focus,\n.btn.active:focus,\n.btn.focus,\n.btn:active.focus,\n.btn.active.focus {\n outline: thin dotted;\n outline: 5px auto -webkit-focus-ring-color;\n outline-offset: -2px;\n}\n.btn:hover,\n.btn:focus,\n.btn.focus {\n color: #333333;\n text-decoration: none;\n}\n.btn:active,\n.btn.active {\n outline: 0;\n background-image: none;\n -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n}\n.btn.disabled,\n.btn[disabled],\nfieldset[disabled] .btn {\n cursor: not-allowed;\n pointer-events: none;\n opacity: 0.65;\n filter: alpha(opacity=65);\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n.btn-default {\n color: #333333;\n background-color: #ffffff;\n border-color: #cccccc;\n}\n.btn-default:hover,\n.btn-default:focus,\n.btn-default.focus,\n.btn-default:active,\n.btn-default.active,\n.open > .dropdown-toggle.btn-default {\n color: #333333;\n background-color: #e6e6e6;\n border-color: #adadad;\n}\n.btn-default:active,\n.btn-default.active,\n.open > .dropdown-toggle.btn-default {\n background-image: none;\n}\n.btn-default.disabled,\n.btn-default[disabled],\nfieldset[disabled] .btn-default,\n.btn-default.disabled:hover,\n.btn-default[disabled]:hover,\nfieldset[disabled] .btn-default:hover,\n.btn-default.disabled:focus,\n.btn-default[disabled]:focus,\nfieldset[disabled] .btn-default:focus,\n.btn-default.disabled.focus,\n.btn-default[disabled].focus,\nfieldset[disabled] .btn-default.focus,\n.btn-default.disabled:active,\n.btn-default[disabled]:active,\nfieldset[disabled] .btn-default:active,\n.btn-default.disabled.active,\n.btn-default[disabled].active,\nfieldset[disabled] .btn-default.active {\n background-color: #ffffff;\n border-color: #cccccc;\n}\n.btn-default .badge {\n color: #ffffff;\n background-color: #333333;\n}\n.btn-primary {\n color: #ffffff;\n background-color: #337ab7;\n border-color: #2e6da4;\n}\n.btn-primary:hover,\n.btn-primary:focus,\n.btn-primary.focus,\n.btn-primary:active,\n.btn-primary.active,\n.open > .dropdown-toggle.btn-primary {\n color: #ffffff;\n background-color: #286090;\n border-color: #204d74;\n}\n.btn-primary:active,\n.btn-primary.active,\n.open > .dropdown-toggle.btn-primary {\n background-image: none;\n}\n.btn-primary.disabled,\n.btn-primary[disabled],\nfieldset[disabled] .btn-primary,\n.btn-primary.disabled:hover,\n.btn-primary[disabled]:hover,\nfieldset[disabled] .btn-primary:hover,\n.btn-primary.disabled:focus,\n.btn-primary[disabled]:focus,\nfieldset[disabled] .btn-primary:focus,\n.btn-primary.disabled.focus,\n.btn-primary[disabled].focus,\nfieldset[disabled] .btn-primary.focus,\n.btn-primary.disabled:active,\n.btn-primary[disabled]:active,\nfieldset[disabled] .btn-primary:active,\n.btn-primary.disabled.active,\n.btn-primary[disabled].active,\nfieldset[disabled] .btn-primary.active {\n background-color: #337ab7;\n border-color: #2e6da4;\n}\n.btn-primary .badge {\n color: #337ab7;\n background-color: #ffffff;\n}\n.btn-success {\n color: #ffffff;\n background-color: #5cb85c;\n border-color: #4cae4c;\n}\n.btn-success:hover,\n.btn-success:focus,\n.btn-success.focus,\n.btn-success:active,\n.btn-success.active,\n.open > .dropdown-toggle.btn-success {\n color: #ffffff;\n background-color: #449d44;\n border-color: #398439;\n}\n.btn-success:active,\n.btn-success.active,\n.open > .dropdown-toggle.btn-success {\n background-image: none;\n}\n.btn-success.disabled,\n.btn-success[disabled],\nfieldset[disabled] .btn-success,\n.btn-success.disabled:hover,\n.btn-success[disabled]:hover,\nfieldset[disabled] .btn-success:hover,\n.btn-success.disabled:focus,\n.btn-success[disabled]:focus,\nfieldset[disabled] .btn-success:focus,\n.btn-success.disabled.focus,\n.btn-success[disabled].focus,\nfieldset[disabled] .btn-success.focus,\n.btn-success.disabled:active,\n.btn-success[disabled]:active,\nfieldset[disabled] .btn-success:active,\n.btn-success.disabled.active,\n.btn-success[disabled].active,\nfieldset[disabled] .btn-success.active {\n background-color: #5cb85c;\n border-color: #4cae4c;\n}\n.btn-success .badge {\n color: #5cb85c;\n background-color: #ffffff;\n}\n.btn-info {\n color: #ffffff;\n background-color: #5bc0de;\n border-color: #46b8da;\n}\n.btn-info:hover,\n.btn-info:focus,\n.btn-info.focus,\n.btn-info:active,\n.btn-info.active,\n.open > .dropdown-toggle.btn-info {\n color: #ffffff;\n background-color: #31b0d5;\n border-color: #269abc;\n}\n.btn-info:active,\n.btn-info.active,\n.open > .dropdown-toggle.btn-info {\n background-image: none;\n}\n.btn-info.disabled,\n.btn-info[disabled],\nfieldset[disabled] .btn-info,\n.btn-info.disabled:hover,\n.btn-info[disabled]:hover,\nfieldset[disabled] .btn-info:hover,\n.btn-info.disabled:focus,\n.btn-info[disabled]:focus,\nfieldset[disabled] .btn-info:focus,\n.btn-info.disabled.focus,\n.btn-info[disabled].focus,\nfieldset[disabled] .btn-info.focus,\n.btn-info.disabled:active,\n.btn-info[disabled]:active,\nfieldset[disabled] .btn-info:active,\n.btn-info.disabled.active,\n.btn-info[disabled].active,\nfieldset[disabled] .btn-info.active {\n background-color: #5bc0de;\n border-color: #46b8da;\n}\n.btn-info .badge {\n color: #5bc0de;\n background-color: #ffffff;\n}\n.btn-warning {\n color: #ffffff;\n background-color: #f0ad4e;\n border-color: #eea236;\n}\n.btn-warning:hover,\n.btn-warning:focus,\n.btn-warning.focus,\n.btn-warning:active,\n.btn-warning.active,\n.open > .dropdown-toggle.btn-warning {\n color: #ffffff;\n background-color: #ec971f;\n border-color: #d58512;\n}\n.btn-warning:active,\n.btn-warning.active,\n.open > .dropdown-toggle.btn-warning {\n background-image: none;\n}\n.btn-warning.disabled,\n.btn-warning[disabled],\nfieldset[disabled] .btn-warning,\n.btn-warning.disabled:hover,\n.btn-warning[disabled]:hover,\nfieldset[disabled] .btn-warning:hover,\n.btn-warning.disabled:focus,\n.btn-warning[disabled]:focus,\nfieldset[disabled] .btn-warning:focus,\n.btn-warning.disabled.focus,\n.btn-warning[disabled].focus,\nfieldset[disabled] .btn-warning.focus,\n.btn-warning.disabled:active,\n.btn-warning[disabled]:active,\nfieldset[disabled] .btn-warning:active,\n.btn-warning.disabled.active,\n.btn-warning[disabled].active,\nfieldset[disabled] .btn-warning.active {\n background-color: #f0ad4e;\n border-color: #eea236;\n}\n.btn-warning .badge {\n color: #f0ad4e;\n background-color: #ffffff;\n}\n.btn-danger {\n color: #ffffff;\n background-color: #d9534f;\n border-color: #d43f3a;\n}\n.btn-danger:hover,\n.btn-danger:focus,\n.btn-danger.focus,\n.btn-danger:active,\n.btn-danger.active,\n.open > .dropdown-toggle.btn-danger {\n color: #ffffff;\n background-color: #c9302c;\n border-color: #ac2925;\n}\n.btn-danger:active,\n.btn-danger.active,\n.open > .dropdown-toggle.btn-danger {\n background-image: none;\n}\n.btn-danger.disabled,\n.btn-danger[disabled],\nfieldset[disabled] .btn-danger,\n.btn-danger.disabled:hover,\n.btn-danger[disabled]:hover,\nfieldset[disabled] .btn-danger:hover,\n.btn-danger.disabled:focus,\n.btn-danger[disabled]:focus,\nfieldset[disabled] .btn-danger:focus,\n.btn-danger.disabled.focus,\n.btn-danger[disabled].focus,\nfieldset[disabled] .btn-danger.focus,\n.btn-danger.disabled:active,\n.btn-danger[disabled]:active,\nfieldset[disabled] .btn-danger:active,\n.btn-danger.disabled.active,\n.btn-danger[disabled].active,\nfieldset[disabled] .btn-danger.active {\n background-color: #d9534f;\n border-color: #d43f3a;\n}\n.btn-danger .badge {\n color: #d9534f;\n background-color: #ffffff;\n}\n.btn-link {\n color: #337ab7;\n font-weight: normal;\n border-radius: 0;\n}\n.btn-link,\n.btn-link:active,\n.btn-link.active,\n.btn-link[disabled],\nfieldset[disabled] .btn-link {\n background-color: transparent;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n.btn-link,\n.btn-link:hover,\n.btn-link:focus,\n.btn-link:active {\n border-color: transparent;\n}\n.btn-link:hover,\n.btn-link:focus {\n color: #23527c;\n text-decoration: underline;\n background-color: transparent;\n}\n.btn-link[disabled]:hover,\nfieldset[disabled] .btn-link:hover,\n.btn-link[disabled]:focus,\nfieldset[disabled] .btn-link:focus {\n color: #777777;\n text-decoration: none;\n}\n.btn-lg,\n.btn-group-lg > .btn {\n padding: 10px 16px;\n font-size: 18px;\n line-height: 1.3333333;\n border-radius: 6px;\n}\n.btn-sm,\n.btn-group-sm > .btn {\n padding: 5px 10px;\n font-size: 12px;\n line-height: 1.5;\n border-radius: 3px;\n}\n.btn-xs,\n.btn-group-xs > .btn {\n padding: 1px 5px;\n font-size: 12px;\n line-height: 1.5;\n border-radius: 3px;\n}\n.btn-block {\n display: block;\n width: 100%;\n}\n.btn-block + .btn-block {\n margin-top: 5px;\n}\ninput[type=\"submit\"].btn-block,\ninput[type=\"reset\"].btn-block,\ninput[type=\"button\"].btn-block {\n width: 100%;\n}\n.fade {\n opacity: 0;\n -webkit-transition: opacity 0.15s linear;\n -o-transition: opacity 0.15s linear;\n transition: opacity 0.15s linear;\n}\n.fade.in {\n opacity: 1;\n}\n.collapse {\n display: none;\n}\n.collapse.in {\n display: block;\n}\ntr.collapse.in {\n display: table-row;\n}\ntbody.collapse.in {\n display: table-row-group;\n}\n.collapsing {\n position: relative;\n height: 0;\n overflow: hidden;\n -webkit-transition-property: height, visibility;\n transition-property: height, visibility;\n -webkit-transition-duration: 0.35s;\n transition-duration: 0.35s;\n -webkit-transition-timing-function: ease;\n transition-timing-function: ease;\n}\n.caret {\n display: inline-block;\n width: 0;\n height: 0;\n margin-left: 2px;\n vertical-align: middle;\n border-top: 4px dashed;\n border-right: 4px solid transparent;\n border-left: 4px solid transparent;\n}\n.dropup,\n.dropdown {\n position: relative;\n}\n.dropdown-toggle:focus {\n outline: 0;\n}\n.dropdown-menu {\n position: absolute;\n top: 100%;\n left: 0;\n z-index: 1000;\n display: none;\n float: left;\n min-width: 160px;\n padding: 5px 0;\n margin: 2px 0 0;\n list-style: none;\n font-size: 14px;\n text-align: left;\n background-color: #ffffff;\n border: 1px solid #cccccc;\n border: 1px solid rgba(0, 0, 0, 0.15);\n border-radius: 4px;\n -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);\n box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);\n background-clip: padding-box;\n}\n.dropdown-menu.pull-right {\n right: 0;\n left: auto;\n}\n.dropdown-menu .divider {\n height: 1px;\n margin: 9px 0;\n overflow: hidden;\n background-color: #e5e5e5;\n}\n.dropdown-menu > li > a {\n display: block;\n padding: 3px 20px;\n clear: both;\n font-weight: normal;\n line-height: 1.42857143;\n color: #333333;\n white-space: nowrap;\n}\n.dropdown-menu > li > a:hover,\n.dropdown-menu > li > a:focus {\n text-decoration: none;\n color: #262626;\n background-color: #f5f5f5;\n}\n.dropdown-menu > .active > a,\n.dropdown-menu > .active > a:hover,\n.dropdown-menu > .active > a:focus {\n color: #ffffff;\n text-decoration: none;\n outline: 0;\n background-color: #337ab7;\n}\n.dropdown-menu > .disabled > a,\n.dropdown-menu > .disabled > a:hover,\n.dropdown-menu > .disabled > a:focus {\n color: #777777;\n}\n.dropdown-menu > .disabled > a:hover,\n.dropdown-menu > .disabled > a:focus {\n text-decoration: none;\n background-color: transparent;\n background-image: none;\n filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);\n cursor: not-allowed;\n}\n.open > .dropdown-menu {\n display: block;\n}\n.open > a {\n outline: 0;\n}\n.dropdown-menu-right {\n left: auto;\n right: 0;\n}\n.dropdown-menu-left {\n left: 0;\n right: auto;\n}\n.dropdown-header {\n display: block;\n padding: 3px 20px;\n font-size: 12px;\n line-height: 1.42857143;\n color: #777777;\n white-space: nowrap;\n}\n.dropdown-backdrop {\n position: fixed;\n left: 0;\n right: 0;\n bottom: 0;\n top: 0;\n z-index: 990;\n}\n.pull-right > .dropdown-menu {\n right: 0;\n left: auto;\n}\n.dropup .caret,\n.navbar-fixed-bottom .dropdown .caret {\n border-top: 0;\n border-bottom: 4px solid;\n content: \"\";\n}\n.dropup .dropdown-menu,\n.navbar-fixed-bottom .dropdown .dropdown-menu {\n top: auto;\n bottom: 100%;\n margin-bottom: 2px;\n}\n@media (min-width: 768px) {\n .navbar-right .dropdown-menu {\n left: auto;\n right: 0;\n }\n .navbar-right .dropdown-menu-left {\n left: 0;\n right: auto;\n }\n}\n.btn-group,\n.btn-group-vertical {\n position: relative;\n display: inline-block;\n vertical-align: middle;\n}\n.btn-group > .btn,\n.btn-group-vertical > .btn {\n position: relative;\n float: left;\n}\n.btn-group > .btn:hover,\n.btn-group-vertical > .btn:hover,\n.btn-group > .btn:focus,\n.btn-group-vertical > .btn:focus,\n.btn-group > .btn:active,\n.btn-group-vertical > .btn:active,\n.btn-group > .btn.active,\n.btn-group-vertical > .btn.active {\n z-index: 2;\n}\n.btn-group .btn + .btn,\n.btn-group .btn + .btn-group,\n.btn-group .btn-group + .btn,\n.btn-group .btn-group + .btn-group {\n margin-left: -1px;\n}\n.btn-toolbar {\n margin-left: -5px;\n}\n.btn-toolbar .btn-group,\n.btn-toolbar .input-group {\n float: left;\n}\n.btn-toolbar > .btn,\n.btn-toolbar > .btn-group,\n.btn-toolbar > .input-group {\n margin-left: 5px;\n}\n.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {\n border-radius: 0;\n}\n.btn-group > .btn:first-child {\n margin-left: 0;\n}\n.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {\n border-bottom-right-radius: 0;\n border-top-right-radius: 0;\n}\n.btn-group > .btn:last-child:not(:first-child),\n.btn-group > .dropdown-toggle:not(:first-child) {\n border-bottom-left-radius: 0;\n border-top-left-radius: 0;\n}\n.btn-group > .btn-group {\n float: left;\n}\n.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {\n border-radius: 0;\n}\n.btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child,\n.btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle {\n border-bottom-right-radius: 0;\n border-top-right-radius: 0;\n}\n.btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child {\n border-bottom-left-radius: 0;\n border-top-left-radius: 0;\n}\n.btn-group .dropdown-toggle:active,\n.btn-group.open .dropdown-toggle {\n outline: 0;\n}\n.btn-group > .btn + .dropdown-toggle {\n padding-left: 8px;\n padding-right: 8px;\n}\n.btn-group > .btn-lg + .dropdown-toggle {\n padding-left: 12px;\n padding-right: 12px;\n}\n.btn-group.open .dropdown-toggle {\n -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);\n}\n.btn-group.open .dropdown-toggle.btn-link {\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n.btn .caret {\n margin-left: 0;\n}\n.btn-lg .caret {\n border-width: 5px 5px 0;\n border-bottom-width: 0;\n}\n.dropup .btn-lg .caret {\n border-width: 0 5px 5px;\n}\n.btn-group-vertical > .btn,\n.btn-group-vertical > .btn-group,\n.btn-group-vertical > .btn-group > .btn {\n display: block;\n float: none;\n width: 100%;\n max-width: 100%;\n}\n.btn-group-vertical > .btn-group > .btn {\n float: none;\n}\n.btn-group-vertical > .btn + .btn,\n.btn-group-vertical > .btn + .btn-group,\n.btn-group-vertical > .btn-group + .btn,\n.btn-group-vertical > .btn-group + .btn-group {\n margin-top: -1px;\n margin-left: 0;\n}\n.btn-group-vertical > .btn:not(:first-child):not(:last-child) {\n border-radius: 0;\n}\n.btn-group-vertical > .btn:first-child:not(:last-child) {\n border-top-right-radius: 4px;\n border-bottom-right-radius: 0;\n border-bottom-left-radius: 0;\n}\n.btn-group-vertical > .btn:last-child:not(:first-child) {\n border-bottom-left-radius: 4px;\n border-top-right-radius: 0;\n border-top-left-radius: 0;\n}\n.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {\n border-radius: 0;\n}\n.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child,\n.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle {\n border-bottom-right-radius: 0;\n border-bottom-left-radius: 0;\n}\n.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {\n border-top-right-radius: 0;\n border-top-left-radius: 0;\n}\n.btn-group-justified {\n display: table;\n width: 100%;\n table-layout: fixed;\n border-collapse: separate;\n}\n.btn-group-justified > .btn,\n.btn-group-justified > .btn-group {\n float: none;\n display: table-cell;\n width: 1%;\n}\n.btn-group-justified > .btn-group .btn {\n width: 100%;\n}\n.btn-group-justified > .btn-group .dropdown-menu {\n left: auto;\n}\n[data-toggle=\"buttons\"] > .btn input[type=\"radio\"],\n[data-toggle=\"buttons\"] > .btn-group > .btn input[type=\"radio\"],\n[data-toggle=\"buttons\"] > .btn input[type=\"checkbox\"],\n[data-toggle=\"buttons\"] > .btn-group > .btn input[type=\"checkbox\"] {\n position: absolute;\n clip: rect(0, 0, 0, 0);\n pointer-events: none;\n}\n.input-group {\n position: relative;\n display: table;\n border-collapse: separate;\n}\n.input-group[class*=\"col-\"] {\n float: none;\n padding-left: 0;\n padding-right: 0;\n}\n.input-group .form-control {\n position: relative;\n z-index: 2;\n float: left;\n width: 100%;\n margin-bottom: 0;\n}\n.input-group-lg > .form-control,\n.input-group-lg > .input-group-addon,\n.input-group-lg > .input-group-btn > .btn {\n height: 46px;\n padding: 10px 16px;\n font-size: 18px;\n line-height: 1.3333333;\n border-radius: 6px;\n}\nselect.input-group-lg > .form-control,\nselect.input-group-lg > .input-group-addon,\nselect.input-group-lg > .input-group-btn > .btn {\n height: 46px;\n line-height: 46px;\n}\ntextarea.input-group-lg > .form-control,\ntextarea.input-group-lg > .input-group-addon,\ntextarea.input-group-lg > .input-group-btn > .btn,\nselect[multiple].input-group-lg > .form-control,\nselect[multiple].input-group-lg > .input-group-addon,\nselect[multiple].input-group-lg > .input-group-btn > .btn {\n height: auto;\n}\n.input-group-sm > .form-control,\n.input-group-sm > .input-group-addon,\n.input-group-sm > .input-group-btn > .btn {\n height: 30px;\n padding: 5px 10px;\n font-size: 12px;\n line-height: 1.5;\n border-radius: 3px;\n}\nselect.input-group-sm > .form-control,\nselect.input-group-sm > .input-group-addon,\nselect.input-group-sm > .input-group-btn > .btn {\n height: 30px;\n line-height: 30px;\n}\ntextarea.input-group-sm > .form-control,\ntextarea.input-group-sm > .input-group-addon,\ntextarea.input-group-sm > .input-group-btn > .btn,\nselect[multiple].input-group-sm > .form-control,\nselect[multiple].input-group-sm > .input-group-addon,\nselect[multiple].input-group-sm > .input-group-btn > .btn {\n height: auto;\n}\n.input-group-addon,\n.input-group-btn,\n.input-group .form-control {\n display: table-cell;\n}\n.input-group-addon:not(:first-child):not(:last-child),\n.input-group-btn:not(:first-child):not(:last-child),\n.input-group .form-control:not(:first-child):not(:last-child) {\n border-radius: 0;\n}\n.input-group-addon,\n.input-group-btn {\n width: 1%;\n white-space: nowrap;\n vertical-align: middle;\n}\n.input-group-addon {\n padding: 6px 12px;\n font-size: 14px;\n font-weight: normal;\n line-height: 1;\n color: #555555;\n text-align: center;\n background-color: #eeeeee;\n border: 1px solid #cccccc;\n border-radius: 4px;\n}\n.input-group-addon.input-sm {\n padding: 5px 10px;\n font-size: 12px;\n border-radius: 3px;\n}\n.input-group-addon.input-lg {\n padding: 10px 16px;\n font-size: 18px;\n border-radius: 6px;\n}\n.input-group-addon input[type=\"radio\"],\n.input-group-addon input[type=\"checkbox\"] {\n margin-top: 0;\n}\n.input-group .form-control:first-child,\n.input-group-addon:first-child,\n.input-group-btn:first-child > .btn,\n.input-group-btn:first-child > .btn-group > .btn,\n.input-group-btn:first-child > .dropdown-toggle,\n.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),\n.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {\n border-bottom-right-radius: 0;\n border-top-right-radius: 0;\n}\n.input-group-addon:first-child {\n border-right: 0;\n}\n.input-group .form-control:last-child,\n.input-group-addon:last-child,\n.input-group-btn:last-child > .btn,\n.input-group-btn:last-child > .btn-group > .btn,\n.input-group-btn:last-child > .dropdown-toggle,\n.input-group-btn:first-child > .btn:not(:first-child),\n.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {\n border-bottom-left-radius: 0;\n border-top-left-radius: 0;\n}\n.input-group-addon:last-child {\n border-left: 0;\n}\n.input-group-btn {\n position: relative;\n font-size: 0;\n white-space: nowrap;\n}\n.input-group-btn > .btn {\n position: relative;\n}\n.input-group-btn > .btn + .btn {\n margin-left: -1px;\n}\n.input-group-btn > .btn:hover,\n.input-group-btn > .btn:focus,\n.input-group-btn > .btn:active {\n z-index: 2;\n}\n.input-group-btn:first-child > .btn,\n.input-group-btn:first-child > .btn-group {\n margin-right: -1px;\n}\n.input-group-btn:last-child > .btn,\n.input-group-btn:last-child > .btn-group {\n margin-left: -1px;\n}\n.nav {\n margin-bottom: 0;\n padding-left: 0;\n list-style: none;\n}\n.nav > li {\n position: relative;\n display: block;\n}\n.nav > li > a {\n position: relative;\n display: block;\n padding: 10px 15px;\n}\n.nav > li > a:hover,\n.nav > li > a:focus {\n text-decoration: none;\n background-color: #eeeeee;\n}\n.nav > li.disabled > a {\n color: #777777;\n}\n.nav > li.disabled > a:hover,\n.nav > li.disabled > a:focus {\n color: #777777;\n text-decoration: none;\n background-color: transparent;\n cursor: not-allowed;\n}\n.nav .open > a,\n.nav .open > a:hover,\n.nav .open > a:focus {\n background-color: #eeeeee;\n border-color: #337ab7;\n}\n.nav .nav-divider {\n height: 1px;\n margin: 9px 0;\n overflow: hidden;\n background-color: #e5e5e5;\n}\n.nav > li > a > img {\n max-width: none;\n}\n.nav-tabs {\n border-bottom: 1px solid #dddddd;\n}\n.nav-tabs > li {\n float: left;\n margin-bottom: -1px;\n}\n.nav-tabs > li > a {\n margin-right: 2px;\n line-height: 1.42857143;\n border: 1px solid transparent;\n border-radius: 4px 4px 0 0;\n}\n.nav-tabs > li > a:hover {\n border-color: #eeeeee #eeeeee #dddddd;\n}\n.nav-tabs > li.active > a,\n.nav-tabs > li.active > a:hover,\n.nav-tabs > li.active > a:focus {\n color: #555555;\n background-color: #ffffff;\n border: 1px solid #dddddd;\n border-bottom-color: transparent;\n cursor: default;\n}\n.nav-tabs.nav-justified {\n width: 100%;\n border-bottom: 0;\n}\n.nav-tabs.nav-justified > li {\n float: none;\n}\n.nav-tabs.nav-justified > li > a {\n text-align: center;\n margin-bottom: 5px;\n}\n.nav-tabs.nav-justified > .dropdown .dropdown-menu {\n top: auto;\n left: auto;\n}\n@media (min-width: 768px) {\n .nav-tabs.nav-justified > li {\n display: table-cell;\n width: 1%;\n }\n .nav-tabs.nav-justified > li > a {\n margin-bottom: 0;\n }\n}\n.nav-tabs.nav-justified > li > a {\n margin-right: 0;\n border-radius: 4px;\n}\n.nav-tabs.nav-justified > .active > a,\n.nav-tabs.nav-justified > .active > a:hover,\n.nav-tabs.nav-justified > .active > a:focus {\n border: 1px solid #dddddd;\n}\n@media (min-width: 768px) {\n .nav-tabs.nav-justified > li > a {\n border-bottom: 1px solid #dddddd;\n border-radius: 4px 4px 0 0;\n }\n .nav-tabs.nav-justified > .active > a,\n .nav-tabs.nav-justified > .active > a:hover,\n .nav-tabs.nav-justified > .active > a:focus {\n border-bottom-color: #ffffff;\n }\n}\n.nav-pills > li {\n float: left;\n}\n.nav-pills > li > a {\n border-radius: 4px;\n}\n.nav-pills > li + li {\n margin-left: 2px;\n}\n.nav-pills > li.active > a,\n.nav-pills > li.active > a:hover,\n.nav-pills > li.active > a:focus {\n color: #ffffff;\n background-color: #337ab7;\n}\n.nav-stacked > li {\n float: none;\n}\n.nav-stacked > li + li {\n margin-top: 2px;\n margin-left: 0;\n}\n.nav-justified {\n width: 100%;\n}\n.nav-justified > li {\n float: none;\n}\n.nav-justified > li > a {\n text-align: center;\n margin-bottom: 5px;\n}\n.nav-justified > .dropdown .dropdown-menu {\n top: auto;\n left: auto;\n}\n@media (min-width: 768px) {\n .nav-justified > li {\n display: table-cell;\n width: 1%;\n }\n .nav-justified > li > a {\n margin-bottom: 0;\n }\n}\n.nav-tabs-justified {\n border-bottom: 0;\n}\n.nav-tabs-justified > li > a {\n margin-right: 0;\n border-radius: 4px;\n}\n.nav-tabs-justified > .active > a,\n.nav-tabs-justified > .active > a:hover,\n.nav-tabs-justified > .active > a:focus {\n border: 1px solid #dddddd;\n}\n@media (min-width: 768px) {\n .nav-tabs-justified > li > a {\n border-bottom: 1px solid #dddddd;\n border-radius: 4px 4px 0 0;\n }\n .nav-tabs-justified > .active > a,\n .nav-tabs-justified > .active > a:hover,\n .nav-tabs-justified > .active > a:focus {\n border-bottom-color: #ffffff;\n }\n}\n.tab-content > .tab-pane {\n display: none;\n}\n.tab-content > .active {\n display: block;\n}\n.nav-tabs .dropdown-menu {\n margin-top: -1px;\n border-top-right-radius: 0;\n border-top-left-radius: 0;\n}\n.navbar {\n position: relative;\n min-height: 50px;\n margin-bottom: 20px;\n border: 1px solid transparent;\n}\n@media (min-width: 768px) {\n .navbar {\n border-radius: 4px;\n }\n}\n@media (min-width: 768px) {\n .navbar-header {\n float: left;\n }\n}\n.navbar-collapse {\n overflow-x: visible;\n padding-right: 15px;\n padding-left: 15px;\n border-top: 1px solid transparent;\n box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);\n -webkit-overflow-scrolling: touch;\n}\n.navbar-collapse.in {\n overflow-y: auto;\n}\n@media (min-width: 768px) {\n .navbar-collapse {\n width: auto;\n border-top: 0;\n box-shadow: none;\n }\n .navbar-collapse.collapse {\n display: block !important;\n height: auto !important;\n padding-bottom: 0;\n overflow: visible !important;\n }\n .navbar-collapse.in {\n overflow-y: visible;\n }\n .navbar-fixed-top .navbar-collapse,\n .navbar-static-top .navbar-collapse,\n .navbar-fixed-bottom .navbar-collapse {\n padding-left: 0;\n padding-right: 0;\n }\n}\n.navbar-fixed-top .navbar-collapse,\n.navbar-fixed-bottom .navbar-collapse {\n max-height: 340px;\n}\n@media (max-device-width: 480px) and (orientation: landscape) {\n .navbar-fixed-top .navbar-collapse,\n .navbar-fixed-bottom .navbar-collapse {\n max-height: 200px;\n }\n}\n.container > .navbar-header,\n.container-fluid > .navbar-header,\n.container > .navbar-collapse,\n.container-fluid > .navbar-collapse {\n margin-right: -15px;\n margin-left: -15px;\n}\n@media (min-width: 768px) {\n .container > .navbar-header,\n .container-fluid > .navbar-header,\n .container > .navbar-collapse,\n .container-fluid > .navbar-collapse {\n margin-right: 0;\n margin-left: 0;\n }\n}\n.navbar-static-top {\n z-index: 1000;\n border-width: 0 0 1px;\n}\n@media (min-width: 768px) {\n .navbar-static-top {\n border-radius: 0;\n }\n}\n.navbar-fixed-top,\n.navbar-fixed-bottom {\n position: fixed;\n right: 0;\n left: 0;\n z-index: 1030;\n}\n@media (min-width: 768px) {\n .navbar-fixed-top,\n .navbar-fixed-bottom {\n border-radius: 0;\n }\n}\n.navbar-fixed-top {\n top: 0;\n border-width: 0 0 1px;\n}\n.navbar-fixed-bottom {\n bottom: 0;\n margin-bottom: 0;\n border-width: 1px 0 0;\n}\n.navbar-brand {\n float: left;\n padding: 15px 15px;\n font-size: 18px;\n line-height: 20px;\n height: 50px;\n}\n.navbar-brand:hover,\n.navbar-brand:focus {\n text-decoration: none;\n}\n.navbar-brand > img {\n display: block;\n}\n@media (min-width: 768px) {\n .navbar > .container .navbar-brand,\n .navbar > .container-fluid .navbar-brand {\n margin-left: -15px;\n }\n}\n.navbar-toggle {\n position: relative;\n float: right;\n margin-right: 15px;\n padding: 9px 10px;\n margin-top: 8px;\n margin-bottom: 8px;\n background-color: transparent;\n background-image: none;\n border: 1px solid transparent;\n border-radius: 4px;\n}\n.navbar-toggle:focus {\n outline: 0;\n}\n.navbar-toggle .icon-bar {\n display: block;\n width: 22px;\n height: 2px;\n border-radius: 1px;\n}\n.navbar-toggle .icon-bar + .icon-bar {\n margin-top: 4px;\n}\n@media (min-width: 768px) {\n .navbar-toggle {\n display: none;\n }\n}\n.navbar-nav {\n margin: 7.5px -15px;\n}\n.navbar-nav > li > a {\n padding-top: 10px;\n padding-bottom: 10px;\n line-height: 20px;\n}\n@media (max-width: 767px) {\n .navbar-nav .open .dropdown-menu {\n position: static;\n float: none;\n width: auto;\n margin-top: 0;\n background-color: transparent;\n border: 0;\n box-shadow: none;\n }\n .navbar-nav .open .dropdown-menu > li > a,\n .navbar-nav .open .dropdown-menu .dropdown-header {\n padding: 5px 15px 5px 25px;\n }\n .navbar-nav .open .dropdown-menu > li > a {\n line-height: 20px;\n }\n .navbar-nav .open .dropdown-menu > li > a:hover,\n .navbar-nav .open .dropdown-menu > li > a:focus {\n background-image: none;\n }\n}\n@media (min-width: 768px) {\n .navbar-nav {\n float: left;\n margin: 0;\n }\n .navbar-nav > li {\n float: left;\n }\n .navbar-nav > li > a {\n padding-top: 15px;\n padding-bottom: 15px;\n }\n}\n.navbar-form {\n margin-left: -15px;\n margin-right: -15px;\n padding: 10px 15px;\n border-top: 1px solid transparent;\n border-bottom: 1px solid transparent;\n -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);\n box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);\n margin-top: 8px;\n margin-bottom: 8px;\n}\n@media (min-width: 768px) {\n .navbar-form .form-group {\n display: inline-block;\n margin-bottom: 0;\n vertical-align: middle;\n }\n .navbar-form .form-control {\n display: inline-block;\n width: auto;\n vertical-align: middle;\n }\n .navbar-form .form-control-static {\n display: inline-block;\n }\n .navbar-form .input-group {\n display: inline-table;\n vertical-align: middle;\n }\n .navbar-form .input-group .input-group-addon,\n .navbar-form .input-group .input-group-btn,\n .navbar-form .input-group .form-control {\n width: auto;\n }\n .navbar-form .input-group > .form-control {\n width: 100%;\n }\n .navbar-form .control-label {\n margin-bottom: 0;\n vertical-align: middle;\n }\n .navbar-form .radio,\n .navbar-form .checkbox {\n display: inline-block;\n margin-top: 0;\n margin-bottom: 0;\n vertical-align: middle;\n }\n .navbar-form .radio label,\n .navbar-form .checkbox label {\n padding-left: 0;\n }\n .navbar-form .radio input[type=\"radio\"],\n .navbar-form .checkbox input[type=\"checkbox\"] {\n position: relative;\n margin-left: 0;\n }\n .navbar-form .has-feedback .form-control-feedback {\n top: 0;\n }\n}\n@media (max-width: 767px) {\n .navbar-form .form-group {\n margin-bottom: 5px;\n }\n .navbar-form .form-group:last-child {\n margin-bottom: 0;\n }\n}\n@media (min-width: 768px) {\n .navbar-form {\n width: auto;\n border: 0;\n margin-left: 0;\n margin-right: 0;\n padding-top: 0;\n padding-bottom: 0;\n -webkit-box-shadow: none;\n box-shadow: none;\n }\n}\n.navbar-nav > li > .dropdown-menu {\n margin-top: 0;\n border-top-right-radius: 0;\n border-top-left-radius: 0;\n}\n.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {\n margin-bottom: 0;\n border-top-right-radius: 4px;\n border-top-left-radius: 4px;\n border-bottom-right-radius: 0;\n border-bottom-left-radius: 0;\n}\n.navbar-btn {\n margin-top: 8px;\n margin-bottom: 8px;\n}\n.navbar-btn.btn-sm {\n margin-top: 10px;\n margin-bottom: 10px;\n}\n.navbar-btn.btn-xs {\n margin-top: 14px;\n margin-bottom: 14px;\n}\n.navbar-text {\n margin-top: 15px;\n margin-bottom: 15px;\n}\n@media (min-width: 768px) {\n .navbar-text {\n float: left;\n margin-left: 15px;\n margin-right: 15px;\n }\n}\n@media (min-width: 768px) {\n .navbar-left {\n float: left !important;\n }\n .navbar-right {\n float: right !important;\n margin-right: -15px;\n }\n .navbar-right ~ .navbar-right {\n margin-right: 0;\n }\n}\n.navbar-default {\n background-color: #f8f8f8;\n border-color: #e7e7e7;\n}\n.navbar-default .navbar-brand {\n color: #777777;\n}\n.navbar-default .navbar-brand:hover,\n.navbar-default .navbar-brand:focus {\n color: #5e5e5e;\n background-color: transparent;\n}\n.navbar-default .navbar-text {\n color: #777777;\n}\n.navbar-default .navbar-nav > li > a {\n color: #777777;\n}\n.navbar-default .navbar-nav > li > a:hover,\n.navbar-default .navbar-nav > li > a:focus {\n color: #333333;\n background-color: transparent;\n}\n.navbar-default .navbar-nav > .active > a,\n.navbar-default .navbar-nav > .active > a:hover,\n.navbar-default .navbar-nav > .active > a:focus {\n color: #555555;\n background-color: #e7e7e7;\n}\n.navbar-default .navbar-nav > .disabled > a,\n.navbar-default .navbar-nav > .disabled > a:hover,\n.navbar-default .navbar-nav > .disabled > a:focus {\n color: #cccccc;\n background-color: transparent;\n}\n.navbar-default .navbar-toggle {\n border-color: #dddddd;\n}\n.navbar-default .navbar-toggle:hover,\n.navbar-default .navbar-toggle:focus {\n background-color: #dddddd;\n}\n.navbar-default .navbar-toggle .icon-bar {\n background-color: #888888;\n}\n.navbar-default .navbar-collapse,\n.navbar-default .navbar-form {\n border-color: #e7e7e7;\n}\n.navbar-default .navbar-nav > .open > a,\n.navbar-default .navbar-nav > .open > a:hover,\n.navbar-default .navbar-nav > .open > a:focus {\n background-color: #e7e7e7;\n color: #555555;\n}\n@media (max-width: 767px) {\n .navbar-default .navbar-nav .open .dropdown-menu > li > a {\n color: #777777;\n }\n .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,\n .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {\n color: #333333;\n background-color: transparent;\n }\n .navbar-default .navbar-nav .open .dropdown-menu > .active > a,\n .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,\n .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {\n color: #555555;\n background-color: #e7e7e7;\n }\n .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,\n .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,\n .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {\n color: #cccccc;\n background-color: transparent;\n }\n}\n.navbar-default .navbar-link {\n color: #777777;\n}\n.navbar-default .navbar-link:hover {\n color: #333333;\n}\n.navbar-default .btn-link {\n color: #777777;\n}\n.navbar-default .btn-link:hover,\n.navbar-default .btn-link:focus {\n color: #333333;\n}\n.navbar-default .btn-link[disabled]:hover,\nfieldset[disabled] .navbar-default .btn-link:hover,\n.navbar-default .btn-link[disabled]:focus,\nfieldset[disabled] .navbar-default .btn-link:focus {\n color: #cccccc;\n}\n.navbar-inverse {\n background-color: #222222;\n border-color: #080808;\n}\n.navbar-inverse .navbar-brand {\n color: #9d9d9d;\n}\n.navbar-inverse .navbar-brand:hover,\n.navbar-inverse .navbar-brand:focus {\n color: #ffffff;\n background-color: transparent;\n}\n.navbar-inverse .navbar-text {\n color: #9d9d9d;\n}\n.navbar-inverse .navbar-nav > li > a {\n color: #9d9d9d;\n}\n.navbar-inverse .navbar-nav > li > a:hover,\n.navbar-inverse .navbar-nav > li > a:focus {\n color: #ffffff;\n background-color: transparent;\n}\n.navbar-inverse .navbar-nav > .active > a,\n.navbar-inverse .navbar-nav > .active > a:hover,\n.navbar-inverse .navbar-nav > .active > a:focus {\n color: #ffffff;\n background-color: #080808;\n}\n.navbar-inverse .navbar-nav > .disabled > a,\n.navbar-inverse .navbar-nav > .disabled > a:hover,\n.navbar-inverse .navbar-nav > .disabled > a:focus {\n color: #444444;\n background-color: transparent;\n}\n.navbar-inverse .navbar-toggle {\n border-color: #333333;\n}\n.navbar-inverse .navbar-toggle:hover,\n.navbar-inverse .navbar-toggle:focus {\n background-color: #333333;\n}\n.navbar-inverse .navbar-toggle .icon-bar {\n background-color: #ffffff;\n}\n.navbar-inverse .navbar-collapse,\n.navbar-inverse .navbar-form {\n border-color: #101010;\n}\n.navbar-inverse .navbar-nav > .open > a,\n.navbar-inverse .navbar-nav > .open > a:hover,\n.navbar-inverse .navbar-nav > .open > a:focus {\n background-color: #080808;\n color: #ffffff;\n}\n@media (max-width: 767px) {\n .navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {\n border-color: #080808;\n }\n .navbar-inverse .navbar-nav .open .dropdown-menu .divider {\n background-color: #080808;\n }\n .navbar-inverse .navbar-nav .open .dropdown-menu > li > a {\n color: #9d9d9d;\n }\n .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,\n .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {\n color: #ffffff;\n background-color: transparent;\n }\n .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,\n .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,\n .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {\n color: #ffffff;\n background-color: #080808;\n }\n .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,\n .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,\n .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {\n color: #444444;\n background-color: transparent;\n }\n}\n.navbar-inverse .navbar-link {\n color: #9d9d9d;\n}\n.navbar-inverse .navbar-link:hover {\n color: #ffffff;\n}\n.navbar-inverse .btn-link {\n color: #9d9d9d;\n}\n.navbar-inverse .btn-link:hover,\n.navbar-inverse .btn-link:focus {\n color: #ffffff;\n}\n.navbar-inverse .btn-link[disabled]:hover,\nfieldset[disabled] .navbar-inverse .btn-link:hover,\n.navbar-inverse .btn-link[disabled]:focus,\nfieldset[disabled] .navbar-inverse .btn-link:focus {\n color: #444444;\n}\n.breadcrumb {\n padding: 8px 15px;\n margin-bottom: 20px;\n list-style: none;\n background-color: #f5f5f5;\n border-radius: 4px;\n}\n.breadcrumb > li {\n display: inline-block;\n}\n.breadcrumb > li + li:before {\n content: \"/\\00a0\";\n padding: 0 5px;\n color: #cccccc;\n}\n.breadcrumb > .active {\n color: #777777;\n}\n.pagination {\n display: inline-block;\n padding-left: 0;\n margin: 20px 0;\n border-radius: 4px;\n}\n.pagination > li {\n display: inline;\n}\n.pagination > li > a,\n.pagination > li > span {\n position: relative;\n float: left;\n padding: 6px 12px;\n line-height: 1.42857143;\n text-decoration: none;\n color: #337ab7;\n background-color: #ffffff;\n border: 1px solid #dddddd;\n margin-left: -1px;\n}\n.pagination > li:first-child > a,\n.pagination > li:first-child > span {\n margin-left: 0;\n border-bottom-left-radius: 4px;\n border-top-left-radius: 4px;\n}\n.pagination > li:last-child > a,\n.pagination > li:last-child > span {\n border-bottom-right-radius: 4px;\n border-top-right-radius: 4px;\n}\n.pagination > li > a:hover,\n.pagination > li > span:hover,\n.pagination > li > a:focus,\n.pagination > li > span:focus {\n color: #23527c;\n background-color: #eeeeee;\n border-color: #dddddd;\n}\n.pagination > .active > a,\n.pagination > .active > span,\n.pagination > .active > a:hover,\n.pagination > .active > span:hover,\n.pagination > .active > a:focus,\n.pagination > .active > span:focus {\n z-index: 2;\n color: #ffffff;\n background-color: #337ab7;\n border-color: #337ab7;\n cursor: default;\n}\n.pagination > .disabled > span,\n.pagination > .disabled > span:hover,\n.pagination > .disabled > span:focus,\n.pagination > .disabled > a,\n.pagination > .disabled > a:hover,\n.pagination > .disabled > a:focus {\n color: #777777;\n background-color: #ffffff;\n border-color: #dddddd;\n cursor: not-allowed;\n}\n.pagination-lg > li > a,\n.pagination-lg > li > span {\n padding: 10px 16px;\n font-size: 18px;\n}\n.pagination-lg > li:first-child > a,\n.pagination-lg > li:first-child > span {\n border-bottom-left-radius: 6px;\n border-top-left-radius: 6px;\n}\n.pagination-lg > li:last-child > a,\n.pagination-lg > li:last-child > span {\n border-bottom-right-radius: 6px;\n border-top-right-radius: 6px;\n}\n.pagination-sm > li > a,\n.pagination-sm > li > span {\n padding: 5px 10px;\n font-size: 12px;\n}\n.pagination-sm > li:first-child > a,\n.pagination-sm > li:first-child > span {\n border-bottom-left-radius: 3px;\n border-top-left-radius: 3px;\n}\n.pagination-sm > li:last-child > a,\n.pagination-sm > li:last-child > span {\n border-bottom-right-radius: 3px;\n border-top-right-radius: 3px;\n}\n.pager {\n padding-left: 0;\n margin: 20px 0;\n list-style: none;\n text-align: center;\n}\n.pager li {\n display: inline;\n}\n.pager li > a,\n.pager li > span {\n display: inline-block;\n padding: 5px 14px;\n background-color: #ffffff;\n border: 1px solid #dddddd;\n border-radius: 15px;\n}\n.pager li > a:hover,\n.pager li > a:focus {\n text-decoration: none;\n background-color: #eeeeee;\n}\n.pager .next > a,\n.pager .next > span {\n float: right;\n}\n.pager .previous > a,\n.pager .previous > span {\n float: left;\n}\n.pager .disabled > a,\n.pager .disabled > a:hover,\n.pager .disabled > a:focus,\n.pager .disabled > span {\n color: #777777;\n background-color: #ffffff;\n cursor: not-allowed;\n}\n.label {\n display: inline;\n padding: .2em .6em .3em;\n font-size: 75%;\n font-weight: bold;\n line-height: 1;\n color: #ffffff;\n text-align: center;\n white-space: nowrap;\n vertical-align: baseline;\n border-radius: .25em;\n}\na.label:hover,\na.label:focus {\n color: #ffffff;\n text-decoration: none;\n cursor: pointer;\n}\n.label:empty {\n display: none;\n}\n.btn .label {\n position: relative;\n top: -1px;\n}\n.label-default {\n background-color: #777777;\n}\n.label-default[href]:hover,\n.label-default[href]:focus {\n background-color: #5e5e5e;\n}\n.label-primary {\n background-color: #337ab7;\n}\n.label-primary[href]:hover,\n.label-primary[href]:focus {\n background-color: #286090;\n}\n.label-success {\n background-color: #5cb85c;\n}\n.label-success[href]:hover,\n.label-success[href]:focus {\n background-color: #449d44;\n}\n.label-info {\n background-color: #5bc0de;\n}\n.label-info[href]:hover,\n.label-info[href]:focus {\n background-color: #31b0d5;\n}\n.label-warning {\n background-color: #f0ad4e;\n}\n.label-warning[href]:hover,\n.label-warning[href]:focus {\n background-color: #ec971f;\n}\n.label-danger {\n background-color: #d9534f;\n}\n.label-danger[href]:hover,\n.label-danger[href]:focus {\n background-color: #c9302c;\n}\n.badge {\n display: inline-block;\n min-width: 10px;\n padding: 3px 7px;\n font-size: 12px;\n font-weight: bold;\n color: #ffffff;\n line-height: 1;\n vertical-align: baseline;\n white-space: nowrap;\n text-align: center;\n background-color: #777777;\n border-radius: 10px;\n}\n.badge:empty {\n display: none;\n}\n.btn .badge {\n position: relative;\n top: -1px;\n}\n.btn-xs .badge,\n.btn-group-xs > .btn .badge {\n top: 0;\n padding: 1px 5px;\n}\na.badge:hover,\na.badge:focus {\n color: #ffffff;\n text-decoration: none;\n cursor: pointer;\n}\n.list-group-item.active > .badge,\n.nav-pills > .active > a > .badge {\n color: #337ab7;\n background-color: #ffffff;\n}\n.list-group-item > .badge {\n float: right;\n}\n.list-group-item > .badge + .badge {\n margin-right: 5px;\n}\n.nav-pills > li > a > .badge {\n margin-left: 3px;\n}\n.jumbotron {\n padding: 30px 15px;\n margin-bottom: 30px;\n color: inherit;\n background-color: #eeeeee;\n}\n.jumbotron h1,\n.jumbotron .h1 {\n color: inherit;\n}\n.jumbotron p {\n margin-bottom: 15px;\n font-size: 21px;\n font-weight: 200;\n}\n.jumbotron > hr {\n border-top-color: #d5d5d5;\n}\n.container .jumbotron,\n.container-fluid .jumbotron {\n border-radius: 6px;\n}\n.jumbotron .container {\n max-width: 100%;\n}\n@media screen and (min-width: 768px) {\n .jumbotron {\n padding: 48px 0;\n }\n .container .jumbotron,\n .container-fluid .jumbotron {\n padding-left: 60px;\n padding-right: 60px;\n }\n .jumbotron h1,\n .jumbotron .h1 {\n font-size: 63px;\n }\n}\n.thumbnail {\n display: block;\n padding: 4px;\n margin-bottom: 20px;\n line-height: 1.42857143;\n background-color: #ffffff;\n border: 1px solid #dddddd;\n border-radius: 4px;\n -webkit-transition: border 0.2s ease-in-out;\n -o-transition: border 0.2s ease-in-out;\n transition: border 0.2s ease-in-out;\n}\n.thumbnail > img,\n.thumbnail a > img {\n margin-left: auto;\n margin-right: auto;\n}\na.thumbnail:hover,\na.thumbnail:focus,\na.thumbnail.active {\n border-color: #337ab7;\n}\n.thumbnail .caption {\n padding: 9px;\n color: #333333;\n}\n.alert {\n padding: 15px;\n margin-bottom: 20px;\n border: 1px solid transparent;\n border-radius: 4px;\n}\n.alert h4 {\n margin-top: 0;\n color: inherit;\n}\n.alert .alert-link {\n font-weight: bold;\n}\n.alert > p,\n.alert > ul {\n margin-bottom: 0;\n}\n.alert > p + p {\n margin-top: 5px;\n}\n.alert-dismissable,\n.alert-dismissible {\n padding-right: 35px;\n}\n.alert-dismissable .close,\n.alert-dismissible .close {\n position: relative;\n top: -2px;\n right: -21px;\n color: inherit;\n}\n.alert-success {\n background-color: #dff0d8;\n border-color: #d6e9c6;\n color: #3c763d;\n}\n.alert-success hr {\n border-top-color: #c9e2b3;\n}\n.alert-success .alert-link {\n color: #2b542c;\n}\n.alert-info {\n background-color: #d9edf7;\n border-color: #bce8f1;\n color: #31708f;\n}\n.alert-info hr {\n border-top-color: #a6e1ec;\n}\n.alert-info .alert-link {\n color: #245269;\n}\n.alert-warning {\n background-color: #fcf8e3;\n border-color: #faebcc;\n color: #8a6d3b;\n}\n.alert-warning hr {\n border-top-color: #f7e1b5;\n}\n.alert-warning .alert-link {\n color: #66512c;\n}\n.alert-danger {\n background-color: #f2dede;\n border-color: #ebccd1;\n color: #a94442;\n}\n.alert-danger hr {\n border-top-color: #e4b9c0;\n}\n.alert-danger .alert-link {\n color: #843534;\n}\n@-webkit-keyframes progress-bar-stripes {\n from {\n background-position: 40px 0;\n }\n to {\n background-position: 0 0;\n }\n}\n@keyframes progress-bar-stripes {\n from {\n background-position: 40px 0;\n }\n to {\n background-position: 0 0;\n }\n}\n.progress {\n overflow: hidden;\n height: 20px;\n margin-bottom: 20px;\n background-color: #f5f5f5;\n border-radius: 4px;\n -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);\n box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);\n}\n.progress-bar {\n float: left;\n width: 0%;\n height: 100%;\n font-size: 12px;\n line-height: 20px;\n color: #ffffff;\n text-align: center;\n background-color: #337ab7;\n -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);\n box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);\n -webkit-transition: width 0.6s ease;\n -o-transition: width 0.6s ease;\n transition: width 0.6s ease;\n}\n.progress-striped .progress-bar,\n.progress-bar-striped {\n background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-size: 40px 40px;\n}\n.progress.active .progress-bar,\n.progress-bar.active {\n -webkit-animation: progress-bar-stripes 2s linear infinite;\n -o-animation: progress-bar-stripes 2s linear infinite;\n animation: progress-bar-stripes 2s linear infinite;\n}\n.progress-bar-success {\n background-color: #5cb85c;\n}\n.progress-striped .progress-bar-success {\n background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n}\n.progress-bar-info {\n background-color: #5bc0de;\n}\n.progress-striped .progress-bar-info {\n background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n}\n.progress-bar-warning {\n background-color: #f0ad4e;\n}\n.progress-striped .progress-bar-warning {\n background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n}\n.progress-bar-danger {\n background-color: #d9534f;\n}\n.progress-striped .progress-bar-danger {\n background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);\n}\n.media {\n margin-top: 15px;\n}\n.media:first-child {\n margin-top: 0;\n}\n.media,\n.media-body {\n zoom: 1;\n overflow: hidden;\n}\n.media-body {\n width: 10000px;\n}\n.media-object {\n display: block;\n}\n.media-right,\n.media > .pull-right {\n padding-left: 10px;\n}\n.media-left,\n.media > .pull-left {\n padding-right: 10px;\n}\n.media-left,\n.media-right,\n.media-body {\n display: table-cell;\n vertical-align: top;\n}\n.media-middle {\n vertical-align: middle;\n}\n.media-bottom {\n vertical-align: bottom;\n}\n.media-heading {\n margin-top: 0;\n margin-bottom: 5px;\n}\n.media-list {\n padding-left: 0;\n list-style: none;\n}\n.list-group {\n margin-bottom: 20px;\n padding-left: 0;\n}\n.list-group-item {\n position: relative;\n display: block;\n padding: 10px 15px;\n margin-bottom: -1px;\n background-color: #ffffff;\n border: 1px solid #dddddd;\n}\n.list-group-item:first-child {\n border-top-right-radius: 4px;\n border-top-left-radius: 4px;\n}\n.list-group-item:last-child {\n margin-bottom: 0;\n border-bottom-right-radius: 4px;\n border-bottom-left-radius: 4px;\n}\na.list-group-item {\n color: #555555;\n}\na.list-group-item .list-group-item-heading {\n color: #333333;\n}\na.list-group-item:hover,\na.list-group-item:focus {\n text-decoration: none;\n color: #555555;\n background-color: #f5f5f5;\n}\n.list-group-item.disabled,\n.list-group-item.disabled:hover,\n.list-group-item.disabled:focus {\n background-color: #eeeeee;\n color: #777777;\n cursor: not-allowed;\n}\n.list-group-item.disabled .list-group-item-heading,\n.list-group-item.disabled:hover .list-group-item-heading,\n.list-group-item.disabled:focus .list-group-item-heading {\n color: inherit;\n}\n.list-group-item.disabled .list-group-item-text,\n.list-group-item.disabled:hover .list-group-item-text,\n.list-group-item.disabled:focus .list-group-item-text {\n color: #777777;\n}\n.list-group-item.active,\n.list-group-item.active:hover,\n.list-group-item.active:focus {\n z-index: 2;\n color: #ffffff;\n background-color: #337ab7;\n border-color: #337ab7;\n}\n.list-group-item.active .list-group-item-heading,\n.list-group-item.active:hover .list-group-item-heading,\n.list-group-item.active:focus .list-group-item-heading,\n.list-group-item.active .list-group-item-heading > small,\n.list-group-item.active:hover .list-group-item-heading > small,\n.list-group-item.active:focus .list-group-item-heading > small,\n.list-group-item.active .list-group-item-heading > .small,\n.list-group-item.active:hover .list-group-item-heading > .small,\n.list-group-item.active:focus .list-group-item-heading > .small {\n color: inherit;\n}\n.list-group-item.active .list-group-item-text,\n.list-group-item.active:hover .list-group-item-text,\n.list-group-item.active:focus .list-group-item-text {\n color: #c7ddef;\n}\n.list-group-item-success {\n color: #3c763d;\n background-color: #dff0d8;\n}\na.list-group-item-success {\n color: #3c763d;\n}\na.list-group-item-success .list-group-item-heading {\n color: inherit;\n}\na.list-group-item-success:hover,\na.list-group-item-success:focus {\n color: #3c763d;\n background-color: #d0e9c6;\n}\na.list-group-item-success.active,\na.list-group-item-success.active:hover,\na.list-group-item-success.active:focus {\n color: #fff;\n background-color: #3c763d;\n border-color: #3c763d;\n}\n.list-group-item-info {\n color: #31708f;\n background-color: #d9edf7;\n}\na.list-group-item-info {\n color: #31708f;\n}\na.list-group-item-info .list-group-item-heading {\n color: inherit;\n}\na.list-group-item-info:hover,\na.list-group-item-info:focus {\n color: #31708f;\n background-color: #c4e3f3;\n}\na.list-group-item-info.active,\na.list-group-item-info.active:hover,\na.list-group-item-info.active:focus {\n color: #fff;\n background-color: #31708f;\n border-color: #31708f;\n}\n.list-group-item-warning {\n color: #8a6d3b;\n background-color: #fcf8e3;\n}\na.list-group-item-warning {\n color: #8a6d3b;\n}\na.list-group-item-warning .list-group-item-heading {\n color: inherit;\n}\na.list-group-item-warning:hover,\na.list-group-item-warning:focus {\n color: #8a6d3b;\n background-color: #faf2cc;\n}\na.list-group-item-warning.active,\na.list-group-item-warning.active:hover,\na.list-group-item-warning.active:focus {\n color: #fff;\n background-color: #8a6d3b;\n border-color: #8a6d3b;\n}\n.list-group-item-danger {\n color: #a94442;\n background-color: #f2dede;\n}\na.list-group-item-danger {\n color: #a94442;\n}\na.list-group-item-danger .list-group-item-heading {\n color: inherit;\n}\na.list-group-item-danger:hover,\na.list-group-item-danger:focus {\n color: #a94442;\n background-color: #ebcccc;\n}\na.list-group-item-danger.active,\na.list-group-item-danger.active:hover,\na.list-group-item-danger.active:focus {\n color: #fff;\n background-color: #a94442;\n border-color: #a94442;\n}\n.list-group-item-heading {\n margin-top: 0;\n margin-bottom: 5px;\n}\n.list-group-item-text {\n margin-bottom: 0;\n line-height: 1.3;\n}\n.panel {\n margin-bottom: 20px;\n background-color: #ffffff;\n border: 1px solid transparent;\n border-radius: 4px;\n -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);\n box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);\n}\n.panel-body {\n padding: 15px;\n}\n.panel-heading {\n padding: 10px 15px;\n border-bottom: 1px solid transparent;\n border-top-right-radius: 3px;\n border-top-left-radius: 3px;\n}\n.panel-heading > .dropdown .dropdown-toggle {\n color: inherit;\n}\n.panel-title {\n margin-top: 0;\n margin-bottom: 0;\n font-size: 16px;\n color: inherit;\n}\n.panel-title > a,\n.panel-title > small,\n.panel-title > .small,\n.panel-title > small > a,\n.panel-title > .small > a {\n color: inherit;\n}\n.panel-footer {\n padding: 10px 15px;\n background-color: #f5f5f5;\n border-top: 1px solid #dddddd;\n border-bottom-right-radius: 3px;\n border-bottom-left-radius: 3px;\n}\n.panel > .list-group,\n.panel > .panel-collapse > .list-group {\n margin-bottom: 0;\n}\n.panel > .list-group .list-group-item,\n.panel > .panel-collapse > .list-group .list-group-item {\n border-width: 1px 0;\n border-radius: 0;\n}\n.panel > .list-group:first-child .list-group-item:first-child,\n.panel > .panel-collapse > .list-group:first-child .list-group-item:first-child {\n border-top: 0;\n border-top-right-radius: 3px;\n border-top-left-radius: 3px;\n}\n.panel > .list-group:last-child .list-group-item:last-child,\n.panel > .panel-collapse > .list-group:last-child .list-group-item:last-child {\n border-bottom: 0;\n border-bottom-right-radius: 3px;\n border-bottom-left-radius: 3px;\n}\n.panel-heading + .list-group .list-group-item:first-child {\n border-top-width: 0;\n}\n.list-group + .panel-footer {\n border-top-width: 0;\n}\n.panel > .table,\n.panel > .table-responsive > .table,\n.panel > .panel-collapse > .table {\n margin-bottom: 0;\n}\n.panel > .table caption,\n.panel > .table-responsive > .table caption,\n.panel > .panel-collapse > .table caption {\n padding-left: 15px;\n padding-right: 15px;\n}\n.panel > .table:first-child,\n.panel > .table-responsive:first-child > .table:first-child {\n border-top-right-radius: 3px;\n border-top-left-radius: 3px;\n}\n.panel > .table:first-child > thead:first-child > tr:first-child,\n.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child,\n.panel > .table:first-child > tbody:first-child > tr:first-child,\n.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child {\n border-top-left-radius: 3px;\n border-top-right-radius: 3px;\n}\n.panel > .table:first-child > thead:first-child > tr:first-child td:first-child,\n.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,\n.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child,\n.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,\n.panel > .table:first-child > thead:first-child > tr:first-child th:first-child,\n.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,\n.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child,\n.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {\n border-top-left-radius: 3px;\n}\n.panel > .table:first-child > thead:first-child > tr:first-child td:last-child,\n.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,\n.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child,\n.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,\n.panel > .table:first-child > thead:first-child > tr:first-child th:last-child,\n.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,\n.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child,\n.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {\n border-top-right-radius: 3px;\n}\n.panel > .table:last-child,\n.panel > .table-responsive:last-child > .table:last-child {\n border-bottom-right-radius: 3px;\n border-bottom-left-radius: 3px;\n}\n.panel > .table:last-child > tbody:last-child > tr:last-child,\n.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child,\n.panel > .table:last-child > tfoot:last-child > tr:last-child,\n.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child {\n border-bottom-left-radius: 3px;\n border-bottom-right-radius: 3px;\n}\n.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child,\n.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,\n.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child,\n.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,\n.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child,\n.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,\n.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child,\n.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {\n border-bottom-left-radius: 3px;\n}\n.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child,\n.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,\n.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child,\n.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,\n.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child,\n.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,\n.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child,\n.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {\n border-bottom-right-radius: 3px;\n}\n.panel > .panel-body + .table,\n.panel > .panel-body + .table-responsive,\n.panel > .table + .panel-body,\n.panel > .table-responsive + .panel-body {\n border-top: 1px solid #dddddd;\n}\n.panel > .table > tbody:first-child > tr:first-child th,\n.panel > .table > tbody:first-child > tr:first-child td {\n border-top: 0;\n}\n.panel > .table-bordered,\n.panel > .table-responsive > .table-bordered {\n border: 0;\n}\n.panel > .table-bordered > thead > tr > th:first-child,\n.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,\n.panel > .table-bordered > tbody > tr > th:first-child,\n.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,\n.panel > .table-bordered > tfoot > tr > th:first-child,\n.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,\n.panel > .table-bordered > thead > tr > td:first-child,\n.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,\n.panel > .table-bordered > tbody > tr > td:first-child,\n.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,\n.panel > .table-bordered > tfoot > tr > td:first-child,\n.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {\n border-left: 0;\n}\n.panel > .table-bordered > thead > tr > th:last-child,\n.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,\n.panel > .table-bordered > tbody > tr > th:last-child,\n.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,\n.panel > .table-bordered > tfoot > tr > th:last-child,\n.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,\n.panel > .table-bordered > thead > tr > td:last-child,\n.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,\n.panel > .table-bordered > tbody > tr > td:last-child,\n.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,\n.panel > .table-bordered > tfoot > tr > td:last-child,\n.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {\n border-right: 0;\n}\n.panel > .table-bordered > thead > tr:first-child > td,\n.panel > .table-responsive > .table-bordered > thead > tr:first-child > td,\n.panel > .table-bordered > tbody > tr:first-child > td,\n.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td,\n.panel > .table-bordered > thead > tr:first-child > th,\n.panel > .table-responsive > .table-bordered > thead > tr:first-child > th,\n.panel > .table-bordered > tbody > tr:first-child > th,\n.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th {\n border-bottom: 0;\n}\n.panel > .table-bordered > tbody > tr:last-child > td,\n.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,\n.panel > .table-bordered > tfoot > tr:last-child > td,\n.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td,\n.panel > .table-bordered > tbody > tr:last-child > th,\n.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,\n.panel > .table-bordered > tfoot > tr:last-child > th,\n.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th {\n border-bottom: 0;\n}\n.panel > .table-responsive {\n border: 0;\n margin-bottom: 0;\n}\n.panel-group {\n margin-bottom: 20px;\n}\n.panel-group .panel {\n margin-bottom: 0;\n border-radius: 4px;\n}\n.panel-group .panel + .panel {\n margin-top: 5px;\n}\n.panel-group .panel-heading {\n border-bottom: 0;\n}\n.panel-group .panel-heading + .panel-collapse > .panel-body,\n.panel-group .panel-heading + .panel-collapse > .list-group {\n border-top: 1px solid #dddddd;\n}\n.panel-group .panel-footer {\n border-top: 0;\n}\n.panel-group .panel-footer + .panel-collapse .panel-body {\n border-bottom: 1px solid #dddddd;\n}\n.panel-default {\n border-color: #dddddd;\n}\n.panel-default > .panel-heading {\n color: #333333;\n background-color: #f5f5f5;\n border-color: #dddddd;\n}\n.panel-default > .panel-heading + .panel-collapse > .panel-body {\n border-top-color: #dddddd;\n}\n.panel-default > .panel-heading .badge {\n color: #f5f5f5;\n background-color: #333333;\n}\n.panel-default > .panel-footer + .panel-collapse > .panel-body {\n border-bottom-color: #dddddd;\n}\n.panel-primary {\n border-color: #337ab7;\n}\n.panel-primary > .panel-heading {\n color: #ffffff;\n background-color: #337ab7;\n border-color: #337ab7;\n}\n.panel-primary > .panel-heading + .panel-collapse > .panel-body {\n border-top-color: #337ab7;\n}\n.panel-primary > .panel-heading .badge {\n color: #337ab7;\n background-color: #ffffff;\n}\n.panel-primary > .panel-footer + .panel-collapse > .panel-body {\n border-bottom-color: #337ab7;\n}\n.panel-success {\n border-color: #d6e9c6;\n}\n.panel-success > .panel-heading {\n color: #3c763d;\n background-color: #dff0d8;\n border-color: #d6e9c6;\n}\n.panel-success > .panel-heading + .panel-collapse > .panel-body {\n border-top-color: #d6e9c6;\n}\n.panel-success > .panel-heading .badge {\n color: #dff0d8;\n background-color: #3c763d;\n}\n.panel-success > .panel-footer + .panel-collapse > .panel-body {\n border-bottom-color: #d6e9c6;\n}\n.panel-info {\n border-color: #bce8f1;\n}\n.panel-info > .panel-heading {\n color: #31708f;\n background-color: #d9edf7;\n border-color: #bce8f1;\n}\n.panel-info > .panel-heading + .panel-collapse > .panel-body {\n border-top-color: #bce8f1;\n}\n.panel-info > .panel-heading .badge {\n color: #d9edf7;\n background-color: #31708f;\n}\n.panel-info > .panel-footer + .panel-collapse > .panel-body {\n border-bottom-color: #bce8f1;\n}\n.panel-warning {\n border-color: #faebcc;\n}\n.panel-warning > .panel-heading {\n color: #8a6d3b;\n background-color: #fcf8e3;\n border-color: #faebcc;\n}\n.panel-warning > .panel-heading + .panel-collapse > .panel-body {\n border-top-color: #faebcc;\n}\n.panel-warning > .panel-heading .badge {\n color: #fcf8e3;\n background-color: #8a6d3b;\n}\n.panel-warning > .panel-footer + .panel-collapse > .panel-body {\n border-bottom-color: #faebcc;\n}\n.panel-danger {\n border-color: #ebccd1;\n}\n.panel-danger > .panel-heading {\n color: #a94442;\n background-color: #f2dede;\n border-color: #ebccd1;\n}\n.panel-danger > .panel-heading + .panel-collapse > .panel-body {\n border-top-color: #ebccd1;\n}\n.panel-danger > .panel-heading .badge {\n color: #f2dede;\n background-color: #a94442;\n}\n.panel-danger > .panel-footer + .panel-collapse > .panel-body {\n border-bottom-color: #ebccd1;\n}\n.embed-responsive {\n position: relative;\n display: block;\n height: 0;\n padding: 0;\n overflow: hidden;\n}\n.embed-responsive .embed-responsive-item,\n.embed-responsive iframe,\n.embed-responsive embed,\n.embed-responsive object,\n.embed-responsive video {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n height: 100%;\n width: 100%;\n border: 0;\n}\n.embed-responsive-16by9 {\n padding-bottom: 56.25%;\n}\n.embed-responsive-4by3 {\n padding-bottom: 75%;\n}\n.well {\n min-height: 20px;\n padding: 19px;\n margin-bottom: 20px;\n background-color: #f5f5f5;\n border: 1px solid #e3e3e3;\n border-radius: 4px;\n -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);\n box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);\n}\n.well blockquote {\n border-color: #ddd;\n border-color: rgba(0, 0, 0, 0.15);\n}\n.well-lg {\n padding: 24px;\n border-radius: 6px;\n}\n.well-sm {\n padding: 9px;\n border-radius: 3px;\n}\n.close {\n float: right;\n font-size: 21px;\n font-weight: bold;\n line-height: 1;\n color: #000000;\n text-shadow: 0 1px 0 #ffffff;\n opacity: 0.2;\n filter: alpha(opacity=20);\n}\n.close:hover,\n.close:focus {\n color: #000000;\n text-decoration: none;\n cursor: pointer;\n opacity: 0.5;\n filter: alpha(opacity=50);\n}\nbutton.close {\n padding: 0;\n cursor: pointer;\n background: transparent;\n border: 0;\n -webkit-appearance: none;\n}\n.modal-open {\n overflow: hidden;\n}\n.modal {\n display: none;\n overflow: hidden;\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1050;\n -webkit-overflow-scrolling: touch;\n outline: 0;\n}\n.modal.fade .modal-dialog {\n -webkit-transform: translate(0, -25%);\n -ms-transform: translate(0, -25%);\n -o-transform: translate(0, -25%);\n transform: translate(0, -25%);\n -webkit-transition: -webkit-transform 0.3s ease-out;\n -moz-transition: -moz-transform 0.3s ease-out;\n -o-transition: -o-transform 0.3s ease-out;\n transition: transform 0.3s ease-out;\n}\n.modal.in .modal-dialog {\n -webkit-transform: translate(0, 0);\n -ms-transform: translate(0, 0);\n -o-transform: translate(0, 0);\n transform: translate(0, 0);\n}\n.modal-open .modal {\n overflow-x: hidden;\n overflow-y: auto;\n}\n.modal-dialog {\n position: relative;\n width: auto;\n margin: 10px;\n}\n.modal-content {\n position: relative;\n background-color: #ffffff;\n border: 1px solid #999999;\n border: 1px solid rgba(0, 0, 0, 0.2);\n border-radius: 6px;\n -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);\n box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);\n background-clip: padding-box;\n outline: 0;\n}\n.modal-backdrop {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: 1040;\n background-color: #000000;\n}\n.modal-backdrop.fade {\n opacity: 0;\n filter: alpha(opacity=0);\n}\n.modal-backdrop.in {\n opacity: 0.5;\n filter: alpha(opacity=50);\n}\n.modal-header {\n padding: 15px;\n border-bottom: 1px solid #e5e5e5;\n min-height: 16.42857143px;\n}\n.modal-header .close {\n margin-top: -2px;\n}\n.modal-title {\n margin: 0;\n line-height: 1.42857143;\n}\n.modal-body {\n position: relative;\n padding: 15px;\n}\n.modal-footer {\n padding: 15px;\n text-align: right;\n border-top: 1px solid #e5e5e5;\n}\n.modal-footer .btn + .btn {\n margin-left: 5px;\n margin-bottom: 0;\n}\n.modal-footer .btn-group .btn + .btn {\n margin-left: -1px;\n}\n.modal-footer .btn-block + .btn-block {\n margin-left: 0;\n}\n.modal-scrollbar-measure {\n position: absolute;\n top: -9999px;\n width: 50px;\n height: 50px;\n overflow: scroll;\n}\n@media (min-width: 768px) {\n .modal-dialog {\n width: 600px;\n margin: 30px auto;\n }\n .modal-content {\n -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);\n box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);\n }\n .modal-sm {\n width: 300px;\n }\n}\n@media (min-width: 992px) {\n .modal-lg {\n width: 900px;\n }\n}\n.tooltip {\n position: absolute;\n z-index: 1070;\n display: block;\n font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n font-size: 12px;\n font-weight: normal;\n line-height: 1.4;\n opacity: 0;\n filter: alpha(opacity=0);\n}\n.tooltip.in {\n opacity: 0.9;\n filter: alpha(opacity=90);\n}\n.tooltip.top {\n margin-top: -3px;\n padding: 5px 0;\n}\n.tooltip.right {\n margin-left: 3px;\n padding: 0 5px;\n}\n.tooltip.bottom {\n margin-top: 3px;\n padding: 5px 0;\n}\n.tooltip.left {\n margin-left: -3px;\n padding: 0 5px;\n}\n.tooltip-inner {\n max-width: 200px;\n padding: 3px 8px;\n color: #ffffff;\n text-align: center;\n text-decoration: none;\n background-color: #000000;\n border-radius: 4px;\n}\n.tooltip-arrow {\n position: absolute;\n width: 0;\n height: 0;\n border-color: transparent;\n border-style: solid;\n}\n.tooltip.top .tooltip-arrow {\n bottom: 0;\n left: 50%;\n margin-left: -5px;\n border-width: 5px 5px 0;\n border-top-color: #000000;\n}\n.tooltip.top-left .tooltip-arrow {\n bottom: 0;\n right: 5px;\n margin-bottom: -5px;\n border-width: 5px 5px 0;\n border-top-color: #000000;\n}\n.tooltip.top-right .tooltip-arrow {\n bottom: 0;\n left: 5px;\n margin-bottom: -5px;\n border-width: 5px 5px 0;\n border-top-color: #000000;\n}\n.tooltip.right .tooltip-arrow {\n top: 50%;\n left: 0;\n margin-top: -5px;\n border-width: 5px 5px 5px 0;\n border-right-color: #000000;\n}\n.tooltip.left .tooltip-arrow {\n top: 50%;\n right: 0;\n margin-top: -5px;\n border-width: 5px 0 5px 5px;\n border-left-color: #000000;\n}\n.tooltip.bottom .tooltip-arrow {\n top: 0;\n left: 50%;\n margin-left: -5px;\n border-width: 0 5px 5px;\n border-bottom-color: #000000;\n}\n.tooltip.bottom-left .tooltip-arrow {\n top: 0;\n right: 5px;\n margin-top: -5px;\n border-width: 0 5px 5px;\n border-bottom-color: #000000;\n}\n.tooltip.bottom-right .tooltip-arrow {\n top: 0;\n left: 5px;\n margin-top: -5px;\n border-width: 0 5px 5px;\n border-bottom-color: #000000;\n}\n.popover {\n position: absolute;\n top: 0;\n left: 0;\n z-index: 1060;\n display: none;\n max-width: 276px;\n padding: 1px;\n font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n font-size: 14px;\n font-weight: normal;\n line-height: 1.42857143;\n text-align: left;\n background-color: #ffffff;\n background-clip: padding-box;\n border: 1px solid #cccccc;\n border: 1px solid rgba(0, 0, 0, 0.2);\n border-radius: 6px;\n -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);\n box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);\n white-space: normal;\n}\n.popover.top {\n margin-top: -10px;\n}\n.popover.right {\n margin-left: 10px;\n}\n.popover.bottom {\n margin-top: 10px;\n}\n.popover.left {\n margin-left: -10px;\n}\n.popover-title {\n margin: 0;\n padding: 8px 14px;\n font-size: 14px;\n background-color: #f7f7f7;\n border-bottom: 1px solid #ebebeb;\n border-radius: 5px 5px 0 0;\n}\n.popover-content {\n padding: 9px 14px;\n}\n.popover > .arrow,\n.popover > .arrow:after {\n position: absolute;\n display: block;\n width: 0;\n height: 0;\n border-color: transparent;\n border-style: solid;\n}\n.popover > .arrow {\n border-width: 11px;\n}\n.popover > .arrow:after {\n border-width: 10px;\n content: \"\";\n}\n.popover.top > .arrow {\n left: 50%;\n margin-left: -11px;\n border-bottom-width: 0;\n border-top-color: #999999;\n border-top-color: rgba(0, 0, 0, 0.25);\n bottom: -11px;\n}\n.popover.top > .arrow:after {\n content: \" \";\n bottom: 1px;\n margin-left: -10px;\n border-bottom-width: 0;\n border-top-color: #ffffff;\n}\n.popover.right > .arrow {\n top: 50%;\n left: -11px;\n margin-top: -11px;\n border-left-width: 0;\n border-right-color: #999999;\n border-right-color: rgba(0, 0, 0, 0.25);\n}\n.popover.right > .arrow:after {\n content: \" \";\n left: 1px;\n bottom: -10px;\n border-left-width: 0;\n border-right-color: #ffffff;\n}\n.popover.bottom > .arrow {\n left: 50%;\n margin-left: -11px;\n border-top-width: 0;\n border-bottom-color: #999999;\n border-bottom-color: rgba(0, 0, 0, 0.25);\n top: -11px;\n}\n.popover.bottom > .arrow:after {\n content: \" \";\n top: 1px;\n margin-left: -10px;\n border-top-width: 0;\n border-bottom-color: #ffffff;\n}\n.popover.left > .arrow {\n top: 50%;\n right: -11px;\n margin-top: -11px;\n border-right-width: 0;\n border-left-color: #999999;\n border-left-color: rgba(0, 0, 0, 0.25);\n}\n.popover.left > .arrow:after {\n content: \" \";\n right: 1px;\n border-right-width: 0;\n border-left-color: #ffffff;\n bottom: -10px;\n}\n.carousel {\n position: relative;\n}\n.carousel-inner {\n position: relative;\n overflow: hidden;\n width: 100%;\n}\n.carousel-inner > .item {\n display: none;\n position: relative;\n -webkit-transition: 0.6s ease-in-out left;\n -o-transition: 0.6s ease-in-out left;\n transition: 0.6s ease-in-out left;\n}\n.carousel-inner > .item > img,\n.carousel-inner > .item > a > img {\n line-height: 1;\n}\n@media all and (transform-3d), (-webkit-transform-3d) {\n .carousel-inner > .item {\n -webkit-transition: -webkit-transform 0.6s ease-in-out;\n -moz-transition: -moz-transform 0.6s ease-in-out;\n -o-transition: -o-transform 0.6s ease-in-out;\n transition: transform 0.6s ease-in-out;\n -webkit-backface-visibility: hidden;\n -moz-backface-visibility: hidden;\n backface-visibility: hidden;\n -webkit-perspective: 1000;\n -moz-perspective: 1000;\n perspective: 1000;\n }\n .carousel-inner > .item.next,\n .carousel-inner > .item.active.right {\n -webkit-transform: translate3d(100%, 0, 0);\n transform: translate3d(100%, 0, 0);\n left: 0;\n }\n .carousel-inner > .item.prev,\n .carousel-inner > .item.active.left {\n -webkit-transform: translate3d(-100%, 0, 0);\n transform: translate3d(-100%, 0, 0);\n left: 0;\n }\n .carousel-inner > .item.next.left,\n .carousel-inner > .item.prev.right,\n .carousel-inner > .item.active {\n -webkit-transform: translate3d(0, 0, 0);\n transform: translate3d(0, 0, 0);\n left: 0;\n }\n}\n.carousel-inner > .active,\n.carousel-inner > .next,\n.carousel-inner > .prev {\n display: block;\n}\n.carousel-inner > .active {\n left: 0;\n}\n.carousel-inner > .next,\n.carousel-inner > .prev {\n position: absolute;\n top: 0;\n width: 100%;\n}\n.carousel-inner > .next {\n left: 100%;\n}\n.carousel-inner > .prev {\n left: -100%;\n}\n.carousel-inner > .next.left,\n.carousel-inner > .prev.right {\n left: 0;\n}\n.carousel-inner > .active.left {\n left: -100%;\n}\n.carousel-inner > .active.right {\n left: 100%;\n}\n.carousel-control {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n width: 15%;\n opacity: 0.5;\n filter: alpha(opacity=50);\n font-size: 20px;\n color: #ffffff;\n text-align: center;\n text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);\n}\n.carousel-control.left {\n background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.0001) 100%);\n background-image: -o-linear-gradient(left, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.0001) 100%);\n background-image: linear-gradient(to right, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.0001) 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);\n}\n.carousel-control.right {\n left: auto;\n right: 0;\n background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 0.0001) 0%, rgba(0, 0, 0, 0.5) 100%);\n background-image: -o-linear-gradient(left, rgba(0, 0, 0, 0.0001) 0%, rgba(0, 0, 0, 0.5) 100%);\n background-image: linear-gradient(to right, rgba(0, 0, 0, 0.0001) 0%, rgba(0, 0, 0, 0.5) 100%);\n background-repeat: repeat-x;\n filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);\n}\n.carousel-control:hover,\n.carousel-control:focus {\n outline: 0;\n color: #ffffff;\n text-decoration: none;\n opacity: 0.9;\n filter: alpha(opacity=90);\n}\n.carousel-control .icon-prev,\n.carousel-control .icon-next,\n.carousel-control .glyphicon-chevron-left,\n.carousel-control .glyphicon-chevron-right {\n position: absolute;\n top: 50%;\n z-index: 5;\n display: inline-block;\n}\n.carousel-control .icon-prev,\n.carousel-control .glyphicon-chevron-left {\n left: 50%;\n margin-left: -10px;\n}\n.carousel-control .icon-next,\n.carousel-control .glyphicon-chevron-right {\n right: 50%;\n margin-right: -10px;\n}\n.carousel-control .icon-prev,\n.carousel-control .icon-next {\n width: 20px;\n height: 20px;\n margin-top: -10px;\n line-height: 1;\n font-family: serif;\n}\n.carousel-control .icon-prev:before {\n content: '\\2039';\n}\n.carousel-control .icon-next:before {\n content: '\\203a';\n}\n.carousel-indicators {\n position: absolute;\n bottom: 10px;\n left: 50%;\n z-index: 15;\n width: 60%;\n margin-left: -30%;\n padding-left: 0;\n list-style: none;\n text-align: center;\n}\n.carousel-indicators li {\n display: inline-block;\n width: 10px;\n height: 10px;\n margin: 1px;\n text-indent: -999px;\n border: 1px solid #ffffff;\n border-radius: 10px;\n cursor: pointer;\n background-color: #000 \\9;\n background-color: rgba(0, 0, 0, 0);\n}\n.carousel-indicators .active {\n margin: 0;\n width: 12px;\n height: 12px;\n background-color: #ffffff;\n}\n.carousel-caption {\n position: absolute;\n left: 15%;\n right: 15%;\n bottom: 20px;\n z-index: 10;\n padding-top: 20px;\n padding-bottom: 20px;\n color: #ffffff;\n text-align: center;\n text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);\n}\n.carousel-caption .btn {\n text-shadow: none;\n}\n@media screen and (min-width: 768px) {\n .carousel-control .glyphicon-chevron-left,\n .carousel-control .glyphicon-chevron-right,\n .carousel-control .icon-prev,\n .carousel-control .icon-next {\n width: 30px;\n height: 30px;\n margin-top: -15px;\n font-size: 30px;\n }\n .carousel-control .glyphicon-chevron-left,\n .carousel-control .icon-prev {\n margin-left: -15px;\n }\n .carousel-control .glyphicon-chevron-right,\n .carousel-control .icon-next {\n margin-right: -15px;\n }\n .carousel-caption {\n left: 20%;\n right: 20%;\n padding-bottom: 30px;\n }\n .carousel-indicators {\n bottom: 20px;\n }\n}\n.clearfix:before,\n.clearfix:after,\n.dl-horizontal dd:before,\n.dl-horizontal dd:after,\n.container:before,\n.container:after,\n.container-fluid:before,\n.container-fluid:after,\n.row:before,\n.row:after,\n.form-horizontal .form-group:before,\n.form-horizontal .form-group:after,\n.btn-toolbar:before,\n.btn-toolbar:after,\n.btn-group-vertical > .btn-group:before,\n.btn-group-vertical > .btn-group:after,\n.nav:before,\n.nav:after,\n.navbar:before,\n.navbar:after,\n.navbar-header:before,\n.navbar-header:after,\n.navbar-collapse:before,\n.navbar-collapse:after,\n.pager:before,\n.pager:after,\n.panel-body:before,\n.panel-body:after,\n.modal-footer:before,\n.modal-footer:after {\n content: \" \";\n display: table;\n}\n.clearfix:after,\n.dl-horizontal dd:after,\n.container:after,\n.container-fluid:after,\n.row:after,\n.form-horizontal .form-group:after,\n.btn-toolbar:after,\n.btn-group-vertical > .btn-group:after,\n.nav:after,\n.navbar:after,\n.navbar-header:after,\n.navbar-collapse:after,\n.pager:after,\n.panel-body:after,\n.modal-footer:after {\n clear: both;\n}\n.center-block {\n display: block;\n margin-left: auto;\n margin-right: auto;\n}\n.pull-right {\n float: right !important;\n}\n.pull-left {\n float: left !important;\n}\n.hide {\n display: none !important;\n}\n.show {\n display: block !important;\n}\n.invisible {\n visibility: hidden;\n}\n.text-hide {\n font: 0/0 a;\n color: transparent;\n text-shadow: none;\n background-color: transparent;\n border: 0;\n}\n.hidden {\n display: none !important;\n}\n.affix {\n position: fixed;\n}\n@-ms-viewport {\n width: device-width;\n}\n.visible-xs,\n.visible-sm,\n.visible-md,\n.visible-lg {\n display: none !important;\n}\n.visible-xs-block,\n.visible-xs-inline,\n.visible-xs-inline-block,\n.visible-sm-block,\n.visible-sm-inline,\n.visible-sm-inline-block,\n.visible-md-block,\n.visible-md-inline,\n.visible-md-inline-block,\n.visible-lg-block,\n.visible-lg-inline,\n.visible-lg-inline-block {\n display: none !important;\n}\n@media (max-width: 767px) {\n .visible-xs {\n display: block !important;\n }\n table.visible-xs {\n display: table;\n }\n tr.visible-xs {\n display: table-row !important;\n }\n th.visible-xs,\n td.visible-xs {\n display: table-cell !important;\n }\n}\n@media (max-width: 767px) {\n .visible-xs-block {\n display: block !important;\n }\n}\n@media (max-width: 767px) {\n .visible-xs-inline {\n display: inline !important;\n }\n}\n@media (max-width: 767px) {\n .visible-xs-inline-block {\n display: inline-block !important;\n }\n}\n@media (min-width: 768px) and (max-width: 991px) {\n .visible-sm {\n display: block !important;\n }\n table.visible-sm {\n display: table;\n }\n tr.visible-sm {\n display: table-row !important;\n }\n th.visible-sm,\n td.visible-sm {\n display: table-cell !important;\n }\n}\n@media (min-width: 768px) and (max-width: 991px) {\n .visible-sm-block {\n display: block !important;\n }\n}\n@media (min-width: 768px) and (max-width: 991px) {\n .visible-sm-inline {\n display: inline !important;\n }\n}\n@media (min-width: 768px) and (max-width: 991px) {\n .visible-sm-inline-block {\n display: inline-block !important;\n }\n}\n@media (min-width: 992px) and (max-width: 1199px) {\n .visible-md {\n display: block !important;\n }\n table.visible-md {\n display: table;\n }\n tr.visible-md {\n display: table-row !important;\n }\n th.visible-md,\n td.visible-md {\n display: table-cell !important;\n }\n}\n@media (min-width: 992px) and (max-width: 1199px) {\n .visible-md-block {\n display: block !important;\n }\n}\n@media (min-width: 992px) and (max-width: 1199px) {\n .visible-md-inline {\n display: inline !important;\n }\n}\n@media (min-width: 992px) and (max-width: 1199px) {\n .visible-md-inline-block {\n display: inline-block !important;\n }\n}\n@media (min-width: 1200px) {\n .visible-lg {\n display: block !important;\n }\n table.visible-lg {\n display: table;\n }\n tr.visible-lg {\n display: table-row !important;\n }\n th.visible-lg,\n td.visible-lg {\n display: table-cell !important;\n }\n}\n@media (min-width: 1200px) {\n .visible-lg-block {\n display: block !important;\n }\n}\n@media (min-width: 1200px) {\n .visible-lg-inline {\n display: inline !important;\n }\n}\n@media (min-width: 1200px) {\n .visible-lg-inline-block {\n display: inline-block !important;\n }\n}\n@media (max-width: 767px) {\n .hidden-xs {\n display: none !important;\n }\n}\n@media (min-width: 768px) and (max-width: 991px) {\n .hidden-sm {\n display: none !important;\n }\n}\n@media (min-width: 992px) and (max-width: 1199px) {\n .hidden-md {\n display: none !important;\n }\n}\n@media (min-width: 1200px) {\n .hidden-lg {\n display: none !important;\n }\n}\n.visible-print {\n display: none !important;\n}\n@media print {\n .visible-print {\n display: block !important;\n }\n table.visible-print {\n display: table;\n }\n tr.visible-print {\n display: table-row !important;\n }\n th.visible-print,\n td.visible-print {\n display: table-cell !important;\n }\n}\n.visible-print-block {\n display: none !important;\n}\n@media print {\n .visible-print-block {\n display: block !important;\n }\n}\n.visible-print-inline {\n display: none !important;\n}\n@media print {\n .visible-print-inline {\n display: inline !important;\n }\n}\n.visible-print-inline-block {\n display: none !important;\n}\n@media print {\n .visible-print-inline-block {\n display: inline-block !important;\n }\n}\n@media print {\n .hidden-print {\n display: none !important;\n }\n}\n/*# sourceMappingURL=bootstrap.css.map */","/*! normalize.css v3.0.2 | MIT License | git.io/normalize */\n\n//\n// 1. Set default font family to sans-serif.\n// 2. Prevent iOS text size adjust after orientation change, without disabling\n// user zoom.\n//\n\nhtml {\n font-family: sans-serif; // 1\n -ms-text-size-adjust: 100%; // 2\n -webkit-text-size-adjust: 100%; // 2\n}\n\n//\n// Remove default margin.\n//\n\nbody {\n margin: 0;\n}\n\n// HTML5 display definitions\n// ==========================================================================\n\n//\n// Correct `block` display not defined for any HTML5 element in IE 8/9.\n// Correct `block` display not defined for `details` or `summary` in IE 10/11\n// and Firefox.\n// Correct `block` display not defined for `main` in IE 11.\n//\n\narticle,\naside,\ndetails,\nfigcaption,\nfigure,\nfooter,\nheader,\nhgroup,\nmain,\nmenu,\nnav,\nsection,\nsummary {\n display: block;\n}\n\n//\n// 1. Correct `inline-block` display not defined in IE 8/9.\n// 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.\n//\n\naudio,\ncanvas,\nprogress,\nvideo {\n display: inline-block; // 1\n vertical-align: baseline; // 2\n}\n\n//\n// Prevent modern browsers from displaying `audio` without controls.\n// Remove excess height in iOS 5 devices.\n//\n\naudio:not([controls]) {\n display: none;\n height: 0;\n}\n\n//\n// Address `[hidden]` styling not present in IE 8/9/10.\n// Hide the `template` element in IE 8/9/11, Safari, and Firefox < 22.\n//\n\n[hidden],\ntemplate {\n display: none;\n}\n\n// Links\n// ==========================================================================\n\n//\n// Remove the gray background color from active links in IE 10.\n//\n\na {\n background-color: transparent;\n}\n\n//\n// Improve readability when focused and also mouse hovered in all browsers.\n//\n\na:active,\na:hover {\n outline: 0;\n}\n\n// Text-level semantics\n// ==========================================================================\n\n//\n// Address styling not present in IE 8/9/10/11, Safari, and Chrome.\n//\n\nabbr[title] {\n border-bottom: 1px dotted;\n}\n\n//\n// Address style set to `bolder` in Firefox 4+, Safari, and Chrome.\n//\n\nb,\nstrong {\n font-weight: bold;\n}\n\n//\n// Address styling not present in Safari and Chrome.\n//\n\ndfn {\n font-style: italic;\n}\n\n//\n// Address variable `h1` font-size and margin within `section` and `article`\n// contexts in Firefox 4+, Safari, and Chrome.\n//\n\nh1 {\n font-size: 2em;\n margin: 0.67em 0;\n}\n\n//\n// Address styling not present in IE 8/9.\n//\n\nmark {\n background: #ff0;\n color: #000;\n}\n\n//\n// Address inconsistent and variable font size in all browsers.\n//\n\nsmall {\n font-size: 80%;\n}\n\n//\n// Prevent `sub` and `sup` affecting `line-height` in all browsers.\n//\n\nsub,\nsup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\n\nsup {\n top: -0.5em;\n}\n\nsub {\n bottom: -0.25em;\n}\n\n// Embedded content\n// ==========================================================================\n\n//\n// Remove border when inside `a` element in IE 8/9/10.\n//\n\nimg {\n border: 0;\n}\n\n//\n// Correct overflow not hidden in IE 9/10/11.\n//\n\nsvg:not(:root) {\n overflow: hidden;\n}\n\n// Grouping content\n// ==========================================================================\n\n//\n// Address margin not present in IE 8/9 and Safari.\n//\n\nfigure {\n margin: 1em 40px;\n}\n\n//\n// Address differences between Firefox and other browsers.\n//\n\nhr {\n -moz-box-sizing: content-box;\n box-sizing: content-box;\n height: 0;\n}\n\n//\n// Contain overflow in all browsers.\n//\n\npre {\n overflow: auto;\n}\n\n//\n// Address odd `em`-unit font size rendering in all browsers.\n//\n\ncode,\nkbd,\npre,\nsamp {\n font-family: monospace, monospace;\n font-size: 1em;\n}\n\n// Forms\n// ==========================================================================\n\n//\n// Known limitation: by default, Chrome and Safari on OS X allow very limited\n// styling of `select`, unless a `border` property is set.\n//\n\n//\n// 1. Correct color not being inherited.\n// Known issue: affects color of disabled elements.\n// 2. Correct font properties not being inherited.\n// 3. Address margins set differently in Firefox 4+, Safari, and Chrome.\n//\n\nbutton,\ninput,\noptgroup,\nselect,\ntextarea {\n color: inherit; // 1\n font: inherit; // 2\n margin: 0; // 3\n}\n\n//\n// Address `overflow` set to `hidden` in IE 8/9/10/11.\n//\n\nbutton {\n overflow: visible;\n}\n\n//\n// Address inconsistent `text-transform` inheritance for `button` and `select`.\n// All other form control elements do not inherit `text-transform` values.\n// Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera.\n// Correct `select` style inheritance in Firefox.\n//\n\nbutton,\nselect {\n text-transform: none;\n}\n\n//\n// 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`\n// and `video` controls.\n// 2. Correct inability to style clickable `input` types in iOS.\n// 3. Improve usability and consistency of cursor style between image-type\n// `input` and others.\n//\n\nbutton,\nhtml input[type=\"button\"], // 1\ninput[type=\"reset\"],\ninput[type=\"submit\"] {\n -webkit-appearance: button; // 2\n cursor: pointer; // 3\n}\n\n//\n// Re-set default cursor for disabled elements.\n//\n\nbutton[disabled],\nhtml input[disabled] {\n cursor: default;\n}\n\n//\n// Remove inner padding and border in Firefox 4+.\n//\n\nbutton::-moz-focus-inner,\ninput::-moz-focus-inner {\n border: 0;\n padding: 0;\n}\n\n//\n// Address Firefox 4+ setting `line-height` on `input` using `!important` in\n// the UA stylesheet.\n//\n\ninput {\n line-height: normal;\n}\n\n//\n// It's recommended that you don't attempt to style these elements.\n// Firefox's implementation doesn't respect box-sizing, padding, or width.\n//\n// 1. Address box sizing set to `content-box` in IE 8/9/10.\n// 2. Remove excess padding in IE 8/9/10.\n//\n\ninput[type=\"checkbox\"],\ninput[type=\"radio\"] {\n box-sizing: border-box; // 1\n padding: 0; // 2\n}\n\n//\n// Fix the cursor style for Chrome's increment/decrement buttons. For certain\n// `font-size` values of the `input`, it causes the cursor style of the\n// decrement button to change from `default` to `text`.\n//\n\ninput[type=\"number\"]::-webkit-inner-spin-button,\ninput[type=\"number\"]::-webkit-outer-spin-button {\n height: auto;\n}\n\n//\n// 1. Address `appearance` set to `searchfield` in Safari and Chrome.\n// 2. Address `box-sizing` set to `border-box` in Safari and Chrome\n// (include `-moz` to future-proof).\n//\n\ninput[type=\"search\"] {\n -webkit-appearance: textfield; // 1\n -moz-box-sizing: content-box;\n -webkit-box-sizing: content-box; // 2\n box-sizing: content-box;\n}\n\n//\n// Remove inner padding and search cancel button in Safari and Chrome on OS X.\n// Safari (but not Chrome) clips the cancel button when the search input has\n// padding (and `textfield` appearance).\n//\n\ninput[type=\"search\"]::-webkit-search-cancel-button,\ninput[type=\"search\"]::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n\n//\n// Define consistent border, margin, and padding.\n//\n\nfieldset {\n border: 1px solid #c0c0c0;\n margin: 0 2px;\n padding: 0.35em 0.625em 0.75em;\n}\n\n//\n// 1. Correct `color` not being inherited in IE 8/9/10/11.\n// 2. Remove padding so people aren't caught out if they zero out fieldsets.\n//\n\nlegend {\n border: 0; // 1\n padding: 0; // 2\n}\n\n//\n// Remove default vertical scrollbar in IE 8/9/10/11.\n//\n\ntextarea {\n overflow: auto;\n}\n\n//\n// Don't inherit the `font-weight` (applied by a rule above).\n// NOTE: the default cannot safely be changed in Chrome and Safari on OS X.\n//\n\noptgroup {\n font-weight: bold;\n}\n\n// Tables\n// ==========================================================================\n\n//\n// Remove most spacing between table cells.\n//\n\ntable {\n border-collapse: collapse;\n border-spacing: 0;\n}\n\ntd,\nth {\n padding: 0;\n}\n","/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */\n\n// ==========================================================================\n// Print styles.\n// Inlined to avoid the additional HTTP request: h5bp.com/r\n// ==========================================================================\n\n@media print {\n *,\n *:before,\n *:after {\n background: transparent !important;\n color: #000 !important; // Black prints faster: h5bp.com/s\n box-shadow: none !important;\n text-shadow: none !important;\n }\n\n a,\n a:visited {\n text-decoration: underline;\n }\n\n a[href]:after {\n content: \" (\" attr(href) \")\";\n }\n\n abbr[title]:after {\n content: \" (\" attr(title) \")\";\n }\n\n // Don't show links that are fragment identifiers,\n // or use the `javascript:` pseudo protocol\n a[href^=\"#\"]:after,\n a[href^=\"javascript:\"]:after {\n content: \"\";\n }\n\n pre,\n blockquote {\n border: 1px solid #999;\n page-break-inside: avoid;\n }\n\n thead {\n display: table-header-group; // h5bp.com/t\n }\n\n tr,\n img {\n page-break-inside: avoid;\n }\n\n img {\n max-width: 100% !important;\n }\n\n p,\n h2,\n h3 {\n orphans: 3;\n widows: 3;\n }\n\n h2,\n h3 {\n page-break-after: avoid;\n }\n\n // Bootstrap specific changes start\n //\n // Chrome (OSX) fix for https://github.com/twbs/bootstrap/issues/11245\n // Once fixed, we can just straight up remove this.\n select {\n background: #fff !important;\n }\n\n // Bootstrap components\n .navbar {\n display: none;\n }\n .btn,\n .dropup > .btn {\n > .caret {\n border-top-color: #000 !important;\n }\n }\n .label {\n border: 1px solid #000;\n }\n\n .table {\n border-collapse: collapse !important;\n\n td,\n th {\n background-color: #fff !important;\n }\n }\n .table-bordered {\n th,\n td {\n border: 1px solid #ddd !important;\n }\n }\n\n // Bootstrap specific changes end\n}\n","//\n// Glyphicons for Bootstrap\n//\n// Since icons are fonts, they can be placed anywhere text is placed and are\n// thus automatically sized to match the surrounding child. To use, create an\n// inline element with the appropriate classes, like so:\n//\n// <a href=\"#\"><span class=\"glyphicon glyphicon-star\"></span> Star</a>\n\n// Import the fonts\n@font-face {\n font-family: 'Glyphicons Halflings';\n src: url('@{icon-font-path}@{icon-font-name}.eot');\n src: url('@{icon-font-path}@{icon-font-name}.eot?#iefix') format('embedded-opentype'),\n url('@{icon-font-path}@{icon-font-name}.woff2') format('woff2'),\n url('@{icon-font-path}@{icon-font-name}.woff') format('woff'),\n url('@{icon-font-path}@{icon-font-name}.ttf') format('truetype'),\n url('@{icon-font-path}@{icon-font-name}.svg#@{icon-font-svg-id}') format('svg');\n}\n\n// Catchall baseclass\n.glyphicon {\n position: relative;\n top: 1px;\n display: inline-block;\n font-family: 'Glyphicons Halflings';\n font-style: normal;\n font-weight: normal;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n// Individual icons\n.glyphicon-asterisk { &:before { content: \"\\2a\"; } }\n.glyphicon-plus { &:before { content: \"\\2b\"; } }\n.glyphicon-euro,\n.glyphicon-eur { &:before { content: \"\\20ac\"; } }\n.glyphicon-minus { &:before { content: \"\\2212\"; } }\n.glyphicon-cloud { &:before { content: \"\\2601\"; } }\n.glyphicon-envelope { &:before { content: \"\\2709\"; } }\n.glyphicon-pencil { &:before { content: \"\\270f\"; } }\n.glyphicon-glass { &:before { content: \"\\e001\"; } }\n.glyphicon-music { &:before { content: \"\\e002\"; } }\n.glyphicon-search { &:before { content: \"\\e003\"; } }\n.glyphicon-heart { &:before { content: \"\\e005\"; } }\n.glyphicon-star { &:before { content: \"\\e006\"; } }\n.glyphicon-star-empty { &:before { content: \"\\e007\"; } }\n.glyphicon-user { &:before { content: \"\\e008\"; } }\n.glyphicon-film { &:before { content: \"\\e009\"; } }\n.glyphicon-th-large { &:before { content: \"\\e010\"; } }\n.glyphicon-th { &:before { content: \"\\e011\"; } }\n.glyphicon-th-list { &:before { content: \"\\e012\"; } }\n.glyphicon-ok { &:before { content: \"\\e013\"; } }\n.glyphicon-remove { &:before { content: \"\\e014\"; } }\n.glyphicon-zoom-in { &:before { content: \"\\e015\"; } }\n.glyphicon-zoom-out { &:before { content: \"\\e016\"; } }\n.glyphicon-off { &:before { content: \"\\e017\"; } }\n.glyphicon-signal { &:before { content: \"\\e018\"; } }\n.glyphicon-cog { &:before { content: \"\\e019\"; } }\n.glyphicon-trash { &:before { content: \"\\e020\"; } }\n.glyphicon-home { &:before { content: \"\\e021\"; } }\n.glyphicon-file { &:before { content: \"\\e022\"; } }\n.glyphicon-time { &:before { content: \"\\e023\"; } }\n.glyphicon-road { &:before { content: \"\\e024\"; } }\n.glyphicon-download-alt { &:before { content: \"\\e025\"; } }\n.glyphicon-download { &:before { content: \"\\e026\"; } }\n.glyphicon-upload { &:before { content: \"\\e027\"; } }\n.glyphicon-inbox { &:before { content: \"\\e028\"; } }\n.glyphicon-play-circle { &:before { content: \"\\e029\"; } }\n.glyphicon-repeat { &:before { content: \"\\e030\"; } }\n.glyphicon-refresh { &:before { content: \"\\e031\"; } }\n.glyphicon-list-alt { &:before { content: \"\\e032\"; } }\n.glyphicon-lock { &:before { content: \"\\e033\"; } }\n.glyphicon-flag { &:before { content: \"\\e034\"; } }\n.glyphicon-headphones { &:before { content: \"\\e035\"; } }\n.glyphicon-volume-off { &:before { content: \"\\e036\"; } }\n.glyphicon-volume-down { &:before { content: \"\\e037\"; } }\n.glyphicon-volume-up { &:before { content: \"\\e038\"; } }\n.glyphicon-qrcode { &:before { content: \"\\e039\"; } }\n.glyphicon-barcode { &:before { content: \"\\e040\"; } }\n.glyphicon-tag { &:before { content: \"\\e041\"; } }\n.glyphicon-tags { &:before { content: \"\\e042\"; } }\n.glyphicon-book { &:before { content: \"\\e043\"; } }\n.glyphicon-bookmark { &:before { content: \"\\e044\"; } }\n.glyphicon-print { &:before { content: \"\\e045\"; } }\n.glyphicon-camera { &:before { content: \"\\e046\"; } }\n.glyphicon-font { &:before { content: \"\\e047\"; } }\n.glyphicon-bold { &:before { content: \"\\e048\"; } }\n.glyphicon-italic { &:before { content: \"\\e049\"; } }\n.glyphicon-text-height { &:before { content: \"\\e050\"; } }\n.glyphicon-text-width { &:before { content: \"\\e051\"; } }\n.glyphicon-align-left { &:before { content: \"\\e052\"; } }\n.glyphicon-align-center { &:before { content: \"\\e053\"; } }\n.glyphicon-align-right { &:before { content: \"\\e054\"; } }\n.glyphicon-align-justify { &:before { content: \"\\e055\"; } }\n.glyphicon-list { &:before { content: \"\\e056\"; } }\n.glyphicon-indent-left { &:before { content: \"\\e057\"; } }\n.glyphicon-indent-right { &:before { content: \"\\e058\"; } }\n.glyphicon-facetime-video { &:before { content: \"\\e059\"; } }\n.glyphicon-picture { &:before { content: \"\\e060\"; } }\n.glyphicon-map-marker { &:before { content: \"\\e062\"; } }\n.glyphicon-adjust { &:before { content: \"\\e063\"; } }\n.glyphicon-tint { &:before { content: \"\\e064\"; } }\n.glyphicon-edit { &:before { content: \"\\e065\"; } }\n.glyphicon-share { &:before { content: \"\\e066\"; } }\n.glyphicon-check { &:before { content: \"\\e067\"; } }\n.glyphicon-move { &:before { content: \"\\e068\"; } }\n.glyphicon-step-backward { &:before { content: \"\\e069\"; } }\n.glyphicon-fast-backward { &:before { content: \"\\e070\"; } }\n.glyphicon-backward { &:before { content: \"\\e071\"; } }\n.glyphicon-play { &:before { content: \"\\e072\"; } }\n.glyphicon-pause { &:before { content: \"\\e073\"; } }\n.glyphicon-stop { &:before { content: \"\\e074\"; } }\n.glyphicon-forward { &:before { content: \"\\e075\"; } }\n.glyphicon-fast-forward { &:before { content: \"\\e076\"; } }\n.glyphicon-step-forward { &:before { content: \"\\e077\"; } }\n.glyphicon-eject { &:before { content: \"\\e078\"; } }\n.glyphicon-chevron-left { &:before { content: \"\\e079\"; } }\n.glyphicon-chevron-right { &:before { content: \"\\e080\"; } }\n.glyphicon-plus-sign { &:before { content: \"\\e081\"; } }\n.glyphicon-minus-sign { &:before { content: \"\\e082\"; } }\n.glyphicon-remove-sign { &:before { content: \"\\e083\"; } }\n.glyphicon-ok-sign { &:before { content: \"\\e084\"; } }\n.glyphicon-question-sign { &:before { content: \"\\e085\"; } }\n.glyphicon-info-sign { &:before { content: \"\\e086\"; } }\n.glyphicon-screenshot { &:before { content: \"\\e087\"; } }\n.glyphicon-remove-circle { &:before { content: \"\\e088\"; } }\n.glyphicon-ok-circle { &:before { content: \"\\e089\"; } }\n.glyphicon-ban-circle { &:before { content: \"\\e090\"; } }\n.glyphicon-arrow-left { &:before { content: \"\\e091\"; } }\n.glyphicon-arrow-right { &:before { content: \"\\e092\"; } }\n.glyphicon-arrow-up { &:before { content: \"\\e093\"; } }\n.glyphicon-arrow-down { &:before { content: \"\\e094\"; } }\n.glyphicon-share-alt { &:before { content: \"\\e095\"; } }\n.glyphicon-resize-full { &:before { content: \"\\e096\"; } }\n.glyphicon-resize-small { &:before { content: \"\\e097\"; } }\n.glyphicon-exclamation-sign { &:before { content: \"\\e101\"; } }\n.glyphicon-gift { &:before { content: \"\\e102\"; } }\n.glyphicon-leaf { &:before { content: \"\\e103\"; } }\n.glyphicon-fire { &:before { content: \"\\e104\"; } }\n.glyphicon-eye-open { &:before { content: \"\\e105\"; } }\n.glyphicon-eye-close { &:before { content: \"\\e106\"; } }\n.glyphicon-warning-sign { &:before { content: \"\\e107\"; } }\n.glyphicon-plane { &:before { content: \"\\e108\"; } }\n.glyphicon-calendar { &:before { content: \"\\e109\"; } }\n.glyphicon-random { &:before { content: \"\\e110\"; } }\n.glyphicon-comment { &:before { content: \"\\e111\"; } }\n.glyphicon-magnet { &:before { content: \"\\e112\"; } }\n.glyphicon-chevron-up { &:before { content: \"\\e113\"; } }\n.glyphicon-chevron-down { &:before { content: \"\\e114\"; } }\n.glyphicon-retweet { &:before { content: \"\\e115\"; } }\n.glyphicon-shopping-cart { &:before { content: \"\\e116\"; } }\n.glyphicon-folder-close { &:before { content: \"\\e117\"; } }\n.glyphicon-folder-open { &:before { content: \"\\e118\"; } }\n.glyphicon-resize-vertical { &:before { content: \"\\e119\"; } }\n.glyphicon-resize-horizontal { &:before { content: \"\\e120\"; } }\n.glyphicon-hdd { &:before { content: \"\\e121\"; } }\n.glyphicon-bullhorn { &:before { content: \"\\e122\"; } }\n.glyphicon-bell { &:before { content: \"\\e123\"; } }\n.glyphicon-certificate { &:before { content: \"\\e124\"; } }\n.glyphicon-thumbs-up { &:before { content: \"\\e125\"; } }\n.glyphicon-thumbs-down { &:before { content: \"\\e126\"; } }\n.glyphicon-hand-right { &:before { content: \"\\e127\"; } }\n.glyphicon-hand-left { &:before { content: \"\\e128\"; } }\n.glyphicon-hand-up { &:before { content: \"\\e129\"; } }\n.glyphicon-hand-down { &:before { content: \"\\e130\"; } }\n.glyphicon-circle-arrow-right { &:before { content: \"\\e131\"; } }\n.glyphicon-circle-arrow-left { &:before { content: \"\\e132\"; } }\n.glyphicon-circle-arrow-up { &:before { content: \"\\e133\"; } }\n.glyphicon-circle-arrow-down { &:before { content: \"\\e134\"; } }\n.glyphicon-globe { &:before { content: \"\\e135\"; } }\n.glyphicon-wrench { &:before { content: \"\\e136\"; } }\n.glyphicon-tasks { &:before { content: \"\\e137\"; } }\n.glyphicon-filter { &:before { content: \"\\e138\"; } }\n.glyphicon-briefcase { &:before { content: \"\\e139\"; } }\n.glyphicon-fullscreen { &:before { content: \"\\e140\"; } }\n.glyphicon-dashboard { &:before { content: \"\\e141\"; } }\n.glyphicon-paperclip { &:before { content: \"\\e142\"; } }\n.glyphicon-heart-empty { &:before { content: \"\\e143\"; } }\n.glyphicon-link { &:before { content: \"\\e144\"; } }\n.glyphicon-phone { &:before { content: \"\\e145\"; } }\n.glyphicon-pushpin { &:before { content: \"\\e146\"; } }\n.glyphicon-usd { &:before { content: \"\\e148\"; } }\n.glyphicon-gbp { &:before { content: \"\\e149\"; } }\n.glyphicon-sort { &:before { content: \"\\e150\"; } }\n.glyphicon-sort-by-alphabet { &:before { content: \"\\e151\"; } }\n.glyphicon-sort-by-alphabet-alt { &:before { content: \"\\e152\"; } }\n.glyphicon-sort-by-order { &:before { content: \"\\e153\"; } }\n.glyphicon-sort-by-order-alt { &:before { content: \"\\e154\"; } }\n.glyphicon-sort-by-attributes { &:before { content: \"\\e155\"; } }\n.glyphicon-sort-by-attributes-alt { &:before { content: \"\\e156\"; } }\n.glyphicon-unchecked { &:before { content: \"\\e157\"; } }\n.glyphicon-expand { &:before { content: \"\\e158\"; } }\n.glyphicon-collapse-down { &:before { content: \"\\e159\"; } }\n.glyphicon-collapse-up { &:before { content: \"\\e160\"; } }\n.glyphicon-log-in { &:before { content: \"\\e161\"; } }\n.glyphicon-flash { &:before { content: \"\\e162\"; } }\n.glyphicon-log-out { &:before { content: \"\\e163\"; } }\n.glyphicon-new-window { &:before { content: \"\\e164\"; } }\n.glyphicon-record { &:before { content: \"\\e165\"; } }\n.glyphicon-save { &:before { content: \"\\e166\"; } }\n.glyphicon-open { &:before { content: \"\\e167\"; } }\n.glyphicon-saved { &:before { content: \"\\e168\"; } }\n.glyphicon-import { &:before { content: \"\\e169\"; } }\n.glyphicon-export { &:before { content: \"\\e170\"; } }\n.glyphicon-send { &:before { content: \"\\e171\"; } }\n.glyphicon-floppy-disk { &:before { content: \"\\e172\"; } }\n.glyphicon-floppy-saved { &:before { content: \"\\e173\"; } }\n.glyphicon-floppy-remove { &:before { content: \"\\e174\"; } }\n.glyphicon-floppy-save { &:before { content: \"\\e175\"; } }\n.glyphicon-floppy-open { &:before { content: \"\\e176\"; } }\n.glyphicon-credit-card { &:before { content: \"\\e177\"; } }\n.glyphicon-transfer { &:before { content: \"\\e178\"; } }\n.glyphicon-cutlery { &:before { content: \"\\e179\"; } }\n.glyphicon-header { &:before { content: \"\\e180\"; } }\n.glyphicon-compressed { &:before { content: \"\\e181\"; } }\n.glyphicon-earphone { &:before { content: \"\\e182\"; } }\n.glyphicon-phone-alt { &:before { content: \"\\e183\"; } }\n.glyphicon-tower { &:before { content: \"\\e184\"; } }\n.glyphicon-stats { &:before { content: \"\\e185\"; } }\n.glyphicon-sd-video { &:before { content: \"\\e186\"; } }\n.glyphicon-hd-video { &:before { content: \"\\e187\"; } }\n.glyphicon-subtitles { &:before { content: \"\\e188\"; } }\n.glyphicon-sound-stereo { &:before { content: \"\\e189\"; } }\n.glyphicon-sound-dolby { &:before { content: \"\\e190\"; } }\n.glyphicon-sound-5-1 { &:before { content: \"\\e191\"; } }\n.glyphicon-sound-6-1 { &:before { content: \"\\e192\"; } }\n.glyphicon-sound-7-1 { &:before { content: \"\\e193\"; } }\n.glyphicon-copyright-mark { &:before { content: \"\\e194\"; } }\n.glyphicon-registration-mark { &:before { content: \"\\e195\"; } }\n.glyphicon-cloud-download { &:before { content: \"\\e197\"; } }\n.glyphicon-cloud-upload { &:before { content: \"\\e198\"; } }\n.glyphicon-tree-conifer { &:before { content: \"\\e199\"; } }\n.glyphicon-tree-deciduous { &:before { content: \"\\e200\"; } }\n.glyphicon-cd { &:before { content: \"\\e201\"; } }\n.glyphicon-save-file { &:before { content: \"\\e202\"; } }\n.glyphicon-open-file { &:before { content: \"\\e203\"; } }\n.glyphicon-level-up { &:before { content: \"\\e204\"; } }\n.glyphicon-copy { &:before { content: \"\\e205\"; } }\n.glyphicon-paste { &:before { content: \"\\e206\"; } }\n// The following 2 Glyphicons are omitted for the time being because\n// they currently use Unicode codepoints that are outside the\n// Basic Multilingual Plane (BMP). Older buggy versions of WebKit can't handle\n// non-BMP codepoints in CSS string escapes, and thus can't display these two icons.\n// Notably, the bug affects some older versions of the Android Browser.\n// More info: https://github.com/twbs/bootstrap/issues/10106\n// .glyphicon-door { &:before { content: \"\\1f6aa\"; } }\n// .glyphicon-key { &:before { content: \"\\1f511\"; } }\n.glyphicon-alert { &:before { content: \"\\e209\"; } }\n.glyphicon-equalizer { &:before { content: \"\\e210\"; } }\n.glyphicon-king { &:before { content: \"\\e211\"; } }\n.glyphicon-queen { &:before { content: \"\\e212\"; } }\n.glyphicon-pawn { &:before { content: \"\\e213\"; } }\n.glyphicon-bishop { &:before { content: \"\\e214\"; } }\n.glyphicon-knight { &:before { content: \"\\e215\"; } }\n.glyphicon-baby-formula { &:before { content: \"\\e216\"; } }\n.glyphicon-tent { &:before { content: \"\\26fa\"; } }\n.glyphicon-blackboard { &:before { content: \"\\e218\"; } }\n.glyphicon-bed { &:before { content: \"\\e219\"; } }\n.glyphicon-apple { &:before { content: \"\\f8ff\"; } }\n.glyphicon-erase { &:before { content: \"\\e221\"; } }\n.glyphicon-hourglass { &:before { content: \"\\231b\"; } }\n.glyphicon-lamp { &:before { content: \"\\e223\"; } }\n.glyphicon-duplicate { &:before { content: \"\\e224\"; } }\n.glyphicon-piggy-bank { &:before { content: \"\\e225\"; } }\n.glyphicon-scissors { &:before { content: \"\\e226\"; } }\n.glyphicon-bitcoin { &:before { content: \"\\e227\"; } }\n.glyphicon-btc { &:before { content: \"\\e227\"; } }\n.glyphicon-xbt { &:before { content: \"\\e227\"; } }\n.glyphicon-yen { &:before { content: \"\\00a5\"; } }\n.glyphicon-jpy { &:before { content: \"\\00a5\"; } }\n.glyphicon-ruble { &:before { content: \"\\20bd\"; } }\n.glyphicon-rub { &:before { content: \"\\20bd\"; } }\n.glyphicon-scale { &:before { content: \"\\e230\"; } }\n.glyphicon-ice-lolly { &:before { content: \"\\e231\"; } }\n.glyphicon-ice-lolly-tasted { &:before { content: \"\\e232\"; } }\n.glyphicon-education { &:before { content: \"\\e233\"; } }\n.glyphicon-option-horizontal { &:before { content: \"\\e234\"; } }\n.glyphicon-option-vertical { &:before { content: \"\\e235\"; } }\n.glyphicon-menu-hamburger { &:before { content: \"\\e236\"; } }\n.glyphicon-modal-window { &:before { content: \"\\e237\"; } }\n.glyphicon-oil { &:before { content: \"\\e238\"; } }\n.glyphicon-grain { &:before { content: \"\\e239\"; } }\n.glyphicon-sunglasses { &:before { content: \"\\e240\"; } }\n.glyphicon-text-size { &:before { content: \"\\e241\"; } }\n.glyphicon-text-color { &:before { content: \"\\e242\"; } }\n.glyphicon-text-background { &:before { content: \"\\e243\"; } }\n.glyphicon-object-align-top { &:before { content: \"\\e244\"; } }\n.glyphicon-object-align-bottom { &:before { content: \"\\e245\"; } }\n.glyphicon-object-align-horizontal{ &:before { content: \"\\e246\"; } }\n.glyphicon-object-align-left { &:before { content: \"\\e247\"; } }\n.glyphicon-object-align-vertical { &:before { content: \"\\e248\"; } }\n.glyphicon-object-align-right { &:before { content: \"\\e249\"; } }\n.glyphicon-triangle-right { &:before { content: \"\\e250\"; } }\n.glyphicon-triangle-left { &:before { content: \"\\e251\"; } }\n.glyphicon-triangle-bottom { &:before { content: \"\\e252\"; } }\n.glyphicon-triangle-top { &:before { content: \"\\e253\"; } }\n.glyphicon-console { &:before { content: \"\\e254\"; } }\n.glyphicon-superscript { &:before { content: \"\\e255\"; } }\n.glyphicon-subscript { &:before { content: \"\\e256\"; } }\n.glyphicon-menu-left { &:before { content: \"\\e257\"; } }\n.glyphicon-menu-right { &:before { content: \"\\e258\"; } }\n.glyphicon-menu-down { &:before { content: \"\\e259\"; } }\n.glyphicon-menu-up { &:before { content: \"\\e260\"; } }\n","//\n// Scaffolding\n// --------------------------------------------------\n\n\n// Reset the box-sizing\n//\n// Heads up! This reset may cause conflicts with some third-party widgets.\n// For recommendations on resolving such conflicts, see\n// http://getbootstrap.com/getting-started/#third-box-sizing\n* {\n .box-sizing(border-box);\n}\n*:before,\n*:after {\n .box-sizing(border-box);\n}\n\n\n// Body reset\n\nhtml {\n font-size: 10px;\n -webkit-tap-highlight-color: rgba(0,0,0,0);\n}\n\nbody {\n font-family: @font-family-base;\n font-size: @font-size-base;\n line-height: @line-height-base;\n color: @text-color;\n background-color: @body-bg;\n}\n\n// Reset fonts for relevant elements\ninput,\nbutton,\nselect,\ntextarea {\n font-family: inherit;\n font-size: inherit;\n line-height: inherit;\n}\n\n\n// Links\n\na {\n color: @link-color;\n text-decoration: none;\n\n &:hover,\n &:focus {\n color: @link-hover-color;\n text-decoration: @link-hover-decoration;\n }\n\n &:focus {\n .tab-focus();\n }\n}\n\n\n// Figures\n//\n// We reset this here because previously Normalize had no `figure` margins. This\n// ensures we don't break anyone's use of the element.\n\nfigure {\n margin: 0;\n}\n\n\n// Images\n\nimg {\n vertical-align: middle;\n}\n\n// Responsive images (ensure images don't scale beyond their parents)\n.img-responsive {\n .img-responsive();\n}\n\n// Rounded corners\n.img-rounded {\n border-radius: @border-radius-large;\n}\n\n// Image thumbnails\n//\n// Heads up! This is mixin-ed into thumbnails.less for `.thumbnail`.\n.img-thumbnail {\n padding: @thumbnail-padding;\n line-height: @line-height-base;\n background-color: @thumbnail-bg;\n border: 1px solid @thumbnail-border;\n border-radius: @thumbnail-border-radius;\n .transition(all .2s ease-in-out);\n\n // Keep them at most 100% wide\n .img-responsive(inline-block);\n}\n\n// Perfect circle\n.img-circle {\n border-radius: 50%; // set radius in percents\n}\n\n\n// Horizontal rules\n\nhr {\n margin-top: @line-height-computed;\n margin-bottom: @line-height-computed;\n border: 0;\n border-top: 1px solid @hr-border;\n}\n\n\n// Only display content to screen readers\n//\n// See: http://a11yproject.com/posts/how-to-hide-content/\n\n.sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n margin: -1px;\n padding: 0;\n overflow: hidden;\n clip: rect(0,0,0,0);\n border: 0;\n}\n\n// Use in conjunction with .sr-only to only display content when it's focused.\n// Useful for \"Skip to main content\" links; see http://www.w3.org/TR/2013/NOTE-WCAG20-TECHS-20130905/G1\n// Credit: HTML5 Boilerplate\n\n.sr-only-focusable {\n &:active,\n &:focus {\n position: static;\n width: auto;\n height: auto;\n margin: 0;\n overflow: visible;\n clip: auto;\n }\n}\n\n\n// iOS \"clickable elements\" fix for role=\"button\"\n//\n// Fixes \"clickability\" issue (and more generally, the firing of events such as focus as well)\n// for traditionally non-focusable elements with role=\"button\"\n// see https://developer.mozilla.org/en-US/docs/Web/Events/click#Safari_Mobile\n// Upstream patch for normalize.css submitted: https://github.com/necolas/normalize.css/pull/379 - remove this fix once that is merged\n\n[role=\"button\"] {\n cursor: pointer;\n}","// Vendor Prefixes\n//\n// All vendor mixins are deprecated as of v3.2.0 due to the introduction of\n// Autoprefixer in our Gruntfile. They will be removed in v4.\n\n// - Animations\n// - Backface visibility\n// - Box shadow\n// - Box sizing\n// - Content columns\n// - Hyphens\n// - Placeholder text\n// - Transformations\n// - Transitions\n// - User Select\n\n\n// Animations\n.animation(@animation) {\n -webkit-animation: @animation;\n -o-animation: @animation;\n animation: @animation;\n}\n.animation-name(@name) {\n -webkit-animation-name: @name;\n animation-name: @name;\n}\n.animation-duration(@duration) {\n -webkit-animation-duration: @duration;\n animation-duration: @duration;\n}\n.animation-timing-function(@timing-function) {\n -webkit-animation-timing-function: @timing-function;\n animation-timing-function: @timing-function;\n}\n.animation-delay(@delay) {\n -webkit-animation-delay: @delay;\n animation-delay: @delay;\n}\n.animation-iteration-count(@iteration-count) {\n -webkit-animation-iteration-count: @iteration-count;\n animation-iteration-count: @iteration-count;\n}\n.animation-direction(@direction) {\n -webkit-animation-direction: @direction;\n animation-direction: @direction;\n}\n.animation-fill-mode(@fill-mode) {\n -webkit-animation-fill-mode: @fill-mode;\n animation-fill-mode: @fill-mode;\n}\n\n// Backface visibility\n// Prevent browsers from flickering when using CSS 3D transforms.\n// Default value is `visible`, but can be changed to `hidden`\n\n.backface-visibility(@visibility){\n -webkit-backface-visibility: @visibility;\n -moz-backface-visibility: @visibility;\n backface-visibility: @visibility;\n}\n\n// Drop shadows\n//\n// Note: Deprecated `.box-shadow()` as of v3.1.0 since all of Bootstrap's\n// supported browsers that have box shadow capabilities now support it.\n\n.box-shadow(@shadow) {\n -webkit-box-shadow: @shadow; // iOS <4.3 & Android <4.1\n box-shadow: @shadow;\n}\n\n// Box sizing\n.box-sizing(@boxmodel) {\n -webkit-box-sizing: @boxmodel;\n -moz-box-sizing: @boxmodel;\n box-sizing: @boxmodel;\n}\n\n// CSS3 Content Columns\n.content-columns(@column-count; @column-gap: @grid-gutter-width) {\n -webkit-column-count: @column-count;\n -moz-column-count: @column-count;\n column-count: @column-count;\n -webkit-column-gap: @column-gap;\n -moz-column-gap: @column-gap;\n column-gap: @column-gap;\n}\n\n// Optional hyphenation\n.hyphens(@mode: auto) {\n word-wrap: break-word;\n -webkit-hyphens: @mode;\n -moz-hyphens: @mode;\n -ms-hyphens: @mode; // IE10+\n -o-hyphens: @mode;\n hyphens: @mode;\n}\n\n// Placeholder text\n.placeholder(@color: @input-color-placeholder) {\n // Firefox\n &::-moz-placeholder {\n color: @color;\n opacity: 1; // Override Firefox's unusual default opacity; see https://github.com/twbs/bootstrap/pull/11526\n }\n &:-ms-input-placeholder { color: @color; } // Internet Explorer 10+\n &::-webkit-input-placeholder { color: @color; } // Safari and Chrome\n}\n\n// Transformations\n.scale(@ratio) {\n -webkit-transform: scale(@ratio);\n -ms-transform: scale(@ratio); // IE9 only\n -o-transform: scale(@ratio);\n transform: scale(@ratio);\n}\n.scale(@ratioX; @ratioY) {\n -webkit-transform: scale(@ratioX, @ratioY);\n -ms-transform: scale(@ratioX, @ratioY); // IE9 only\n -o-transform: scale(@ratioX, @ratioY);\n transform: scale(@ratioX, @ratioY);\n}\n.scaleX(@ratio) {\n -webkit-transform: scaleX(@ratio);\n -ms-transform: scaleX(@ratio); // IE9 only\n -o-transform: scaleX(@ratio);\n transform: scaleX(@ratio);\n}\n.scaleY(@ratio) {\n -webkit-transform: scaleY(@ratio);\n -ms-transform: scaleY(@ratio); // IE9 only\n -o-transform: scaleY(@ratio);\n transform: scaleY(@ratio);\n}\n.skew(@x; @y) {\n -webkit-transform: skewX(@x) skewY(@y);\n -ms-transform: skewX(@x) skewY(@y); // See https://github.com/twbs/bootstrap/issues/4885; IE9+\n -o-transform: skewX(@x) skewY(@y);\n transform: skewX(@x) skewY(@y);\n}\n.translate(@x; @y) {\n -webkit-transform: translate(@x, @y);\n -ms-transform: translate(@x, @y); // IE9 only\n -o-transform: translate(@x, @y);\n transform: translate(@x, @y);\n}\n.translate3d(@x; @y; @z) {\n -webkit-transform: translate3d(@x, @y, @z);\n transform: translate3d(@x, @y, @z);\n}\n.rotate(@degrees) {\n -webkit-transform: rotate(@degrees);\n -ms-transform: rotate(@degrees); // IE9 only\n -o-transform: rotate(@degrees);\n transform: rotate(@degrees);\n}\n.rotateX(@degrees) {\n -webkit-transform: rotateX(@degrees);\n -ms-transform: rotateX(@degrees); // IE9 only\n -o-transform: rotateX(@degrees);\n transform: rotateX(@degrees);\n}\n.rotateY(@degrees) {\n -webkit-transform: rotateY(@degrees);\n -ms-transform: rotateY(@degrees); // IE9 only\n -o-transform: rotateY(@degrees);\n transform: rotateY(@degrees);\n}\n.perspective(@perspective) {\n -webkit-perspective: @perspective;\n -moz-perspective: @perspective;\n perspective: @perspective;\n}\n.perspective-origin(@perspective) {\n -webkit-perspective-origin: @perspective;\n -moz-perspective-origin: @perspective;\n perspective-origin: @perspective;\n}\n.transform-origin(@origin) {\n -webkit-transform-origin: @origin;\n -moz-transform-origin: @origin;\n -ms-transform-origin: @origin; // IE9 only\n transform-origin: @origin;\n}\n\n\n// Transitions\n\n.transition(@transition) {\n -webkit-transition: @transition;\n -o-transition: @transition;\n transition: @transition;\n}\n.transition-property(@transition-property) {\n -webkit-transition-property: @transition-property;\n transition-property: @transition-property;\n}\n.transition-delay(@transition-delay) {\n -webkit-transition-delay: @transition-delay;\n transition-delay: @transition-delay;\n}\n.transition-duration(@transition-duration) {\n -webkit-transition-duration: @transition-duration;\n transition-duration: @transition-duration;\n}\n.transition-timing-function(@timing-function) {\n -webkit-transition-timing-function: @timing-function;\n transition-timing-function: @timing-function;\n}\n.transition-transform(@transition) {\n -webkit-transition: -webkit-transform @transition;\n -moz-transition: -moz-transform @transition;\n -o-transition: -o-transform @transition;\n transition: transform @transition;\n}\n\n\n// User select\n// For selecting text on the page\n\n.user-select(@select) {\n -webkit-user-select: @select;\n -moz-user-select: @select;\n -ms-user-select: @select; // IE10+\n user-select: @select;\n}\n","// WebKit-style focus\n\n.tab-focus() {\n // Default\n outline: thin dotted;\n // WebKit\n outline: 5px auto -webkit-focus-ring-color;\n outline-offset: -2px;\n}\n","// Image Mixins\n// - Responsive image\n// - Retina image\n\n\n// Responsive image\n//\n// Keep images from scaling beyond the width of their parents.\n.img-responsive(@display: block) {\n display: @display;\n max-width: 100%; // Part 1: Set a maximum relative to the parent\n height: auto; // Part 2: Scale the height according to the width, otherwise you get stretching\n}\n\n\n// Retina image\n//\n// Short retina mixin for setting background-image and -size. Note that the\n// spelling of `min--moz-device-pixel-ratio` is intentional.\n.img-retina(@file-1x; @file-2x; @width-1x; @height-1x) {\n background-image: url(\"@{file-1x}\");\n\n @media\n only screen and (-webkit-min-device-pixel-ratio: 2),\n only screen and ( min--moz-device-pixel-ratio: 2),\n only screen and ( -o-min-device-pixel-ratio: 2/1),\n only screen and ( min-device-pixel-ratio: 2),\n only screen and ( min-resolution: 192dpi),\n only screen and ( min-resolution: 2dppx) {\n background-image: url(\"@{file-2x}\");\n background-size: @width-1x @height-1x;\n }\n}\n","//\n// Typography\n// --------------------------------------------------\n\n\n// Headings\n// -------------------------\n\nh1, h2, h3, h4, h5, h6,\n.h1, .h2, .h3, .h4, .h5, .h6 {\n font-family: @headings-font-family;\n font-weight: @headings-font-weight;\n line-height: @headings-line-height;\n color: @headings-color;\n\n small,\n .small {\n font-weight: normal;\n line-height: 1;\n color: @headings-small-color;\n }\n}\n\nh1, .h1,\nh2, .h2,\nh3, .h3 {\n margin-top: @line-height-computed;\n margin-bottom: (@line-height-computed / 2);\n\n small,\n .small {\n font-size: 65%;\n }\n}\nh4, .h4,\nh5, .h5,\nh6, .h6 {\n margin-top: (@line-height-computed / 2);\n margin-bottom: (@line-height-computed / 2);\n\n small,\n .small {\n font-size: 75%;\n }\n}\n\nh1, .h1 { font-size: @font-size-h1; }\nh2, .h2 { font-size: @font-size-h2; }\nh3, .h3 { font-size: @font-size-h3; }\nh4, .h4 { font-size: @font-size-h4; }\nh5, .h5 { font-size: @font-size-h5; }\nh6, .h6 { font-size: @font-size-h6; }\n\n\n// Body text\n// -------------------------\n\np {\n margin: 0 0 (@line-height-computed / 2);\n}\n\n.lead {\n margin-bottom: @line-height-computed;\n font-size: floor((@font-size-base * 1.15));\n font-weight: 300;\n line-height: 1.4;\n\n @media (min-width: @screen-sm-min) {\n font-size: (@font-size-base * 1.5);\n }\n}\n\n\n// Emphasis & misc\n// -------------------------\n\n// Ex: (12px small font / 14px base font) * 100% = about 85%\nsmall,\n.small {\n font-size: floor((100% * @font-size-small / @font-size-base));\n}\n\nmark,\n.mark {\n background-color: @state-warning-bg;\n padding: .2em;\n}\n\n// Alignment\n.text-left { text-align: left; }\n.text-right { text-align: right; }\n.text-center { text-align: center; }\n.text-justify { text-align: justify; }\n.text-nowrap { white-space: nowrap; }\n\n// Transformation\n.text-lowercase { text-transform: lowercase; }\n.text-uppercase { text-transform: uppercase; }\n.text-capitalize { text-transform: capitalize; }\n\n// Contextual colors\n.text-muted {\n color: @text-muted;\n}\n.text-primary {\n .text-emphasis-variant(@brand-primary);\n}\n.text-success {\n .text-emphasis-variant(@state-success-text);\n}\n.text-info {\n .text-emphasis-variant(@state-info-text);\n}\n.text-warning {\n .text-emphasis-variant(@state-warning-text);\n}\n.text-danger {\n .text-emphasis-variant(@state-danger-text);\n}\n\n// Contextual backgrounds\n// For now we'll leave these alongside the text classes until v4 when we can\n// safely shift things around (per SemVer rules).\n.bg-primary {\n // Given the contrast here, this is the only class to have its color inverted\n // automatically.\n color: #fff;\n .bg-variant(@brand-primary);\n}\n.bg-success {\n .bg-variant(@state-success-bg);\n}\n.bg-info {\n .bg-variant(@state-info-bg);\n}\n.bg-warning {\n .bg-variant(@state-warning-bg);\n}\n.bg-danger {\n .bg-variant(@state-danger-bg);\n}\n\n\n// Page header\n// -------------------------\n\n.page-header {\n padding-bottom: ((@line-height-computed / 2) - 1);\n margin: (@line-height-computed * 2) 0 @line-height-computed;\n border-bottom: 1px solid @page-header-border-color;\n}\n\n\n// Lists\n// -------------------------\n\n// Unordered and Ordered lists\nul,\nol {\n margin-top: 0;\n margin-bottom: (@line-height-computed / 2);\n ul,\n ol {\n margin-bottom: 0;\n }\n}\n\n// List options\n\n// Unstyled keeps list items block level, just removes default browser padding and list-style\n.list-unstyled {\n padding-left: 0;\n list-style: none;\n}\n\n// Inline turns list items into inline-block\n.list-inline {\n .list-unstyled();\n margin-left: -5px;\n\n > li {\n display: inline-block;\n padding-left: 5px;\n padding-right: 5px;\n }\n}\n\n// Description Lists\ndl {\n margin-top: 0; // Remove browser default\n margin-bottom: @line-height-computed;\n}\ndt,\ndd {\n line-height: @line-height-base;\n}\ndt {\n font-weight: bold;\n}\ndd {\n margin-left: 0; // Undo browser default\n}\n\n// Horizontal description lists\n//\n// Defaults to being stacked without any of the below styles applied, until the\n// grid breakpoint is reached (default of ~768px).\n\n.dl-horizontal {\n dd {\n &:extend(.clearfix all); // Clear the floated `dt` if an empty `dd` is present\n }\n\n @media (min-width: @grid-float-breakpoint) {\n dt {\n float: left;\n width: (@dl-horizontal-offset - 20);\n clear: left;\n text-align: right;\n .text-overflow();\n }\n dd {\n margin-left: @dl-horizontal-offset;\n }\n }\n}\n\n\n// Misc\n// -------------------------\n\n// Abbreviations and acronyms\nabbr[title],\n// Add data-* attribute to help out our tooltip plugin, per https://github.com/twbs/bootstrap/issues/5257\nabbr[data-original-title] {\n cursor: help;\n border-bottom: 1px dotted @abbr-border-color;\n}\n.initialism {\n font-size: 90%;\n .text-uppercase();\n}\n\n// Blockquotes\nblockquote {\n padding: (@line-height-computed / 2) @line-height-computed;\n margin: 0 0 @line-height-computed;\n font-size: @blockquote-font-size;\n border-left: 5px solid @blockquote-border-color;\n\n p,\n ul,\n ol {\n &:last-child {\n margin-bottom: 0;\n }\n }\n\n // Note: Deprecated small and .small as of v3.1.0\n // Context: https://github.com/twbs/bootstrap/issues/11660\n footer,\n small,\n .small {\n display: block;\n font-size: 80%; // back to default font-size\n line-height: @line-height-base;\n color: @blockquote-small-color;\n\n &:before {\n content: '\\2014 \\00A0'; // em dash, nbsp\n }\n }\n}\n\n// Opposite alignment of blockquote\n//\n// Heads up: `blockquote.pull-right` has been deprecated as of v3.1.0.\n.blockquote-reverse,\nblockquote.pull-right {\n padding-right: 15px;\n padding-left: 0;\n border-right: 5px solid @blockquote-border-color;\n border-left: 0;\n text-align: right;\n\n // Account for citation\n footer,\n small,\n .small {\n &:before { content: ''; }\n &:after {\n content: '\\00A0 \\2014'; // nbsp, em dash\n }\n }\n}\n\n// Addresses\naddress {\n margin-bottom: @line-height-computed;\n font-style: normal;\n line-height: @line-height-base;\n}\n","// Typography\n\n.text-emphasis-variant(@color) {\n color: @color;\n a&:hover {\n color: darken(@color, 10%);\n }\n}\n","// Contextual backgrounds\n\n.bg-variant(@color) {\n background-color: @color;\n a&:hover {\n background-color: darken(@color, 10%);\n }\n}\n","// Text overflow\n// Requires inline-block or block for proper styling\n\n.text-overflow() {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n","//\n// Code (inline and block)\n// --------------------------------------------------\n\n\n// Inline and block code styles\ncode,\nkbd,\npre,\nsamp {\n font-family: @font-family-monospace;\n}\n\n// Inline code\ncode {\n padding: 2px 4px;\n font-size: 90%;\n color: @code-color;\n background-color: @code-bg;\n border-radius: @border-radius-base;\n}\n\n// User input typically entered via keyboard\nkbd {\n padding: 2px 4px;\n font-size: 90%;\n color: @kbd-color;\n background-color: @kbd-bg;\n border-radius: @border-radius-small;\n box-shadow: inset 0 -1px 0 rgba(0,0,0,.25);\n\n kbd {\n padding: 0;\n font-size: 100%;\n font-weight: bold;\n box-shadow: none;\n }\n}\n\n// Blocks of code\npre {\n display: block;\n padding: ((@line-height-computed - 1) / 2);\n margin: 0 0 (@line-height-computed / 2);\n font-size: (@font-size-base - 1); // 14px to 13px\n line-height: @line-height-base;\n word-break: break-all;\n word-wrap: break-word;\n color: @pre-color;\n background-color: @pre-bg;\n border: 1px solid @pre-border-color;\n border-radius: @border-radius-base;\n\n // Account for some code outputs that place code tags in pre tags\n code {\n padding: 0;\n font-size: inherit;\n color: inherit;\n white-space: pre-wrap;\n background-color: transparent;\n border-radius: 0;\n }\n}\n\n// Enable scrollable blocks of code\n.pre-scrollable {\n max-height: @pre-scrollable-max-height;\n overflow-y: scroll;\n}\n","//\n// Grid system\n// --------------------------------------------------\n\n\n// Container widths\n//\n// Set the container width, and override it for fixed navbars in media queries.\n\n.container {\n .container-fixed();\n\n @media (min-width: @screen-sm-min) {\n width: @container-sm;\n }\n @media (min-width: @screen-md-min) {\n width: @container-md;\n }\n @media (min-width: @screen-lg-min) {\n width: @container-lg;\n }\n}\n\n\n// Fluid container\n//\n// Utilizes the mixin meant for fixed width containers, but without any defined\n// width for fluid, full width layouts.\n\n.container-fluid {\n .container-fixed();\n}\n\n\n// Row\n//\n// Rows contain and clear the floats of your columns.\n\n.row {\n .make-row();\n}\n\n\n// Columns\n//\n// Common styles for small and large grid columns\n\n.make-grid-columns();\n\n\n// Extra small grid\n//\n// Columns, offsets, pushes, and pulls for extra small devices like\n// smartphones.\n\n.make-grid(xs);\n\n\n// Small grid\n//\n// Columns, offsets, pushes, and pulls for the small device range, from phones\n// to tablets.\n\n@media (min-width: @screen-sm-min) {\n .make-grid(sm);\n}\n\n\n// Medium grid\n//\n// Columns, offsets, pushes, and pulls for the desktop device range.\n\n@media (min-width: @screen-md-min) {\n .make-grid(md);\n}\n\n\n// Large grid\n//\n// Columns, offsets, pushes, and pulls for the large desktop device range.\n\n@media (min-width: @screen-lg-min) {\n .make-grid(lg);\n}\n","// Grid system\n//\n// Generate semantic grid columns with these mixins.\n\n// Centered container element\n.container-fixed(@gutter: @grid-gutter-width) {\n margin-right: auto;\n margin-left: auto;\n padding-left: (@gutter / 2);\n padding-right: (@gutter / 2);\n &:extend(.clearfix all);\n}\n\n// Creates a wrapper for a series of columns\n.make-row(@gutter: @grid-gutter-width) {\n margin-left: (@gutter / -2);\n margin-right: (@gutter / -2);\n &:extend(.clearfix all);\n}\n\n// Generate the extra small columns\n.make-xs-column(@columns; @gutter: @grid-gutter-width) {\n position: relative;\n float: left;\n width: percentage((@columns / @grid-columns));\n min-height: 1px;\n padding-left: (@gutter / 2);\n padding-right: (@gutter / 2);\n}\n.make-xs-column-offset(@columns) {\n margin-left: percentage((@columns / @grid-columns));\n}\n.make-xs-column-push(@columns) {\n left: percentage((@columns / @grid-columns));\n}\n.make-xs-column-pull(@columns) {\n right: percentage((@columns / @grid-columns));\n}\n\n// Generate the small columns\n.make-sm-column(@columns; @gutter: @grid-gutter-width) {\n position: relative;\n min-height: 1px;\n padding-left: (@gutter / 2);\n padding-right: (@gutter / 2);\n\n @media (min-width: @screen-sm-min) {\n float: left;\n width: percentage((@columns / @grid-columns));\n }\n}\n.make-sm-column-offset(@columns) {\n @media (min-width: @screen-sm-min) {\n margin-left: percentage((@columns / @grid-columns));\n }\n}\n.make-sm-column-push(@columns) {\n @media (min-width: @screen-sm-min) {\n left: percentage((@columns / @grid-columns));\n }\n}\n.make-sm-column-pull(@columns) {\n @media (min-width: @screen-sm-min) {\n right: percentage((@columns / @grid-columns));\n }\n}\n\n// Generate the medium columns\n.make-md-column(@columns; @gutter: @grid-gutter-width) {\n position: relative;\n min-height: 1px;\n padding-left: (@gutter / 2);\n padding-right: (@gutter / 2);\n\n @media (min-width: @screen-md-min) {\n float: left;\n width: percentage((@columns / @grid-columns));\n }\n}\n.make-md-column-offset(@columns) {\n @media (min-width: @screen-md-min) {\n margin-left: percentage((@columns / @grid-columns));\n }\n}\n.make-md-column-push(@columns) {\n @media (min-width: @screen-md-min) {\n left: percentage((@columns / @grid-columns));\n }\n}\n.make-md-column-pull(@columns) {\n @media (min-width: @screen-md-min) {\n right: percentage((@columns / @grid-columns));\n }\n}\n\n// Generate the large columns\n.make-lg-column(@columns; @gutter: @grid-gutter-width) {\n position: relative;\n min-height: 1px;\n padding-left: (@gutter / 2);\n padding-right: (@gutter / 2);\n\n @media (min-width: @screen-lg-min) {\n float: left;\n width: percentage((@columns / @grid-columns));\n }\n}\n.make-lg-column-offset(@columns) {\n @media (min-width: @screen-lg-min) {\n margin-left: percentage((@columns / @grid-columns));\n }\n}\n.make-lg-column-push(@columns) {\n @media (min-width: @screen-lg-min) {\n left: percentage((@columns / @grid-columns));\n }\n}\n.make-lg-column-pull(@columns) {\n @media (min-width: @screen-lg-min) {\n right: percentage((@columns / @grid-columns));\n }\n}\n","// Framework grid generation\n//\n// Used only by Bootstrap to generate the correct number of grid classes given\n// any value of `@grid-columns`.\n\n.make-grid-columns() {\n // Common styles for all sizes of grid columns, widths 1-12\n .col(@index) { // initial\n @item: ~\".col-xs-@{index}, .col-sm-@{index}, .col-md-@{index}, .col-lg-@{index}\";\n .col((@index + 1), @item);\n }\n .col(@index, @list) when (@index =< @grid-columns) { // general; \"=<\" isn't a typo\n @item: ~\".col-xs-@{index}, .col-sm-@{index}, .col-md-@{index}, .col-lg-@{index}\";\n .col((@index + 1), ~\"@{list}, @{item}\");\n }\n .col(@index, @list) when (@index > @grid-columns) { // terminal\n @{list} {\n position: relative;\n // Prevent columns from collapsing when empty\n min-height: 1px;\n // Inner gutter via padding\n padding-left: (@grid-gutter-width / 2);\n padding-right: (@grid-gutter-width / 2);\n }\n }\n .col(1); // kickstart it\n}\n\n.float-grid-columns(@class) {\n .col(@index) { // initial\n @item: ~\".col-@{class}-@{index}\";\n .col((@index + 1), @item);\n }\n .col(@index, @list) when (@index =< @grid-columns) { // general\n @item: ~\".col-@{class}-@{index}\";\n .col((@index + 1), ~\"@{list}, @{item}\");\n }\n .col(@index, @list) when (@index > @grid-columns) { // terminal\n @{list} {\n float: left;\n }\n }\n .col(1); // kickstart it\n}\n\n.calc-grid-column(@index, @class, @type) when (@type = width) and (@index > 0) {\n .col-@{class}-@{index} {\n width: percentage((@index / @grid-columns));\n }\n}\n.calc-grid-column(@index, @class, @type) when (@type = push) and (@index > 0) {\n .col-@{class}-push-@{index} {\n left: percentage((@index / @grid-columns));\n }\n}\n.calc-grid-column(@index, @class, @type) when (@type = push) and (@index = 0) {\n .col-@{class}-push-0 {\n left: auto;\n }\n}\n.calc-grid-column(@index, @class, @type) when (@type = pull) and (@index > 0) {\n .col-@{class}-pull-@{index} {\n right: percentage((@index / @grid-columns));\n }\n}\n.calc-grid-column(@index, @class, @type) when (@type = pull) and (@index = 0) {\n .col-@{class}-pull-0 {\n right: auto;\n }\n}\n.calc-grid-column(@index, @class, @type) when (@type = offset) {\n .col-@{class}-offset-@{index} {\n margin-left: percentage((@index / @grid-columns));\n }\n}\n\n// Basic looping in LESS\n.loop-grid-columns(@index, @class, @type) when (@index >= 0) {\n .calc-grid-column(@index, @class, @type);\n // next iteration\n .loop-grid-columns((@index - 1), @class, @type);\n}\n\n// Create grid for specific class\n.make-grid(@class) {\n .float-grid-columns(@class);\n .loop-grid-columns(@grid-columns, @class, width);\n .loop-grid-columns(@grid-columns, @class, pull);\n .loop-grid-columns(@grid-columns, @class, push);\n .loop-grid-columns(@grid-columns, @class, offset);\n}\n","//\n// Tables\n// --------------------------------------------------\n\n\ntable {\n background-color: @table-bg;\n}\ncaption {\n padding-top: @table-cell-padding;\n padding-bottom: @table-cell-padding;\n color: @text-muted;\n text-align: left;\n}\nth {\n text-align: left;\n}\n\n\n// Baseline styles\n\n.table {\n width: 100%;\n max-width: 100%;\n margin-bottom: @line-height-computed;\n // Cells\n > thead,\n > tbody,\n > tfoot {\n > tr {\n > th,\n > td {\n padding: @table-cell-padding;\n line-height: @line-height-base;\n vertical-align: top;\n border-top: 1px solid @table-border-color;\n }\n }\n }\n // Bottom align for column headings\n > thead > tr > th {\n vertical-align: bottom;\n border-bottom: 2px solid @table-border-color;\n }\n // Remove top border from thead by default\n > caption + thead,\n > colgroup + thead,\n > thead:first-child {\n > tr:first-child {\n > th,\n > td {\n border-top: 0;\n }\n }\n }\n // Account for multiple tbody instances\n > tbody + tbody {\n border-top: 2px solid @table-border-color;\n }\n\n // Nesting\n .table {\n background-color: @body-bg;\n }\n}\n\n\n// Condensed table w/ half padding\n\n.table-condensed {\n > thead,\n > tbody,\n > tfoot {\n > tr {\n > th,\n > td {\n padding: @table-condensed-cell-padding;\n }\n }\n }\n}\n\n\n// Bordered version\n//\n// Add borders all around the table and between all the columns.\n\n.table-bordered {\n border: 1px solid @table-border-color;\n > thead,\n > tbody,\n > tfoot {\n > tr {\n > th,\n > td {\n border: 1px solid @table-border-color;\n }\n }\n }\n > thead > tr {\n > th,\n > td {\n border-bottom-width: 2px;\n }\n }\n}\n\n\n// Zebra-striping\n//\n// Default zebra-stripe styles (alternating gray and transparent backgrounds)\n\n.table-striped {\n > tbody > tr:nth-of-type(odd) {\n background-color: @table-bg-accent;\n }\n}\n\n\n// Hover effect\n//\n// Placed here since it has to come after the potential zebra striping\n\n.table-hover {\n > tbody > tr:hover {\n background-color: @table-bg-hover;\n }\n}\n\n\n// Table cell sizing\n//\n// Reset default table behavior\n\ntable col[class*=\"col-\"] {\n position: static; // Prevent border hiding in Firefox and IE9-11 (see https://github.com/twbs/bootstrap/issues/11623)\n float: none;\n display: table-column;\n}\ntable {\n td,\n th {\n &[class*=\"col-\"] {\n position: static; // Prevent border hiding in Firefox and IE9-11 (see https://github.com/twbs/bootstrap/issues/11623)\n float: none;\n display: table-cell;\n }\n }\n}\n\n\n// Table backgrounds\n//\n// Exact selectors below required to override `.table-striped` and prevent\n// inheritance to nested tables.\n\n// Generate the contextual variants\n.table-row-variant(active; @table-bg-active);\n.table-row-variant(success; @state-success-bg);\n.table-row-variant(info; @state-info-bg);\n.table-row-variant(warning; @state-warning-bg);\n.table-row-variant(danger; @state-danger-bg);\n\n\n// Responsive tables\n//\n// Wrap your tables in `.table-responsive` and we'll make them mobile friendly\n// by enabling horizontal scrolling. Only applies <768px. Everything above that\n// will display normally.\n\n.table-responsive {\n overflow-x: auto;\n min-height: 0.01%; // Workaround for IE9 bug (see https://github.com/twbs/bootstrap/issues/14837)\n\n @media screen and (max-width: @screen-xs-max) {\n width: 100%;\n margin-bottom: (@line-height-computed * 0.75);\n overflow-y: hidden;\n -ms-overflow-style: -ms-autohiding-scrollbar;\n border: 1px solid @table-border-color;\n\n // Tighten up spacing\n > .table {\n margin-bottom: 0;\n\n // Ensure the content doesn't wrap\n > thead,\n > tbody,\n > tfoot {\n > tr {\n > th,\n > td {\n white-space: nowrap;\n }\n }\n }\n }\n\n // Special overrides for the bordered tables\n > .table-bordered {\n border: 0;\n\n // Nuke the appropriate borders so that the parent can handle them\n > thead,\n > tbody,\n > tfoot {\n > tr {\n > th:first-child,\n > td:first-child {\n border-left: 0;\n }\n > th:last-child,\n > td:last-child {\n border-right: 0;\n }\n }\n }\n\n // Only nuke the last row's bottom-border in `tbody` and `tfoot` since\n // chances are there will be only one `tr` in a `thead` and that would\n // remove the border altogether.\n > tbody,\n > tfoot {\n > tr:last-child {\n > th,\n > td {\n border-bottom: 0;\n }\n }\n }\n\n }\n }\n}\n","// Tables\n\n.table-row-variant(@state; @background) {\n // Exact selectors below required to override `.table-striped` and prevent\n // inheritance to nested tables.\n .table > thead > tr,\n .table > tbody > tr,\n .table > tfoot > tr {\n > td.@{state},\n > th.@{state},\n &.@{state} > td,\n &.@{state} > th {\n background-color: @background;\n }\n }\n\n // Hover states for `.table-hover`\n // Note: this is not available for cells or rows within `thead` or `tfoot`.\n .table-hover > tbody > tr {\n > td.@{state}:hover,\n > th.@{state}:hover,\n &.@{state}:hover > td,\n &:hover > .@{state},\n &.@{state}:hover > th {\n background-color: darken(@background, 5%);\n }\n }\n}\n","//\n// Forms\n// --------------------------------------------------\n\n\n// Normalize non-controls\n//\n// Restyle and baseline non-control form elements.\n\nfieldset {\n padding: 0;\n margin: 0;\n border: 0;\n // Chrome and Firefox set a `min-width: min-content;` on fieldsets,\n // so we reset that to ensure it behaves more like a standard block element.\n // See https://github.com/twbs/bootstrap/issues/12359.\n min-width: 0;\n}\n\nlegend {\n display: block;\n width: 100%;\n padding: 0;\n margin-bottom: @line-height-computed;\n font-size: (@font-size-base * 1.5);\n line-height: inherit;\n color: @legend-color;\n border: 0;\n border-bottom: 1px solid @legend-border-color;\n}\n\nlabel {\n display: inline-block;\n max-width: 100%; // Force IE8 to wrap long content (see https://github.com/twbs/bootstrap/issues/13141)\n margin-bottom: 5px;\n font-weight: bold;\n}\n\n\n// Normalize form controls\n//\n// While most of our form styles require extra classes, some basic normalization\n// is required to ensure optimum display with or without those classes to better\n// address browser inconsistencies.\n\n// Override content-box in Normalize (* isn't specific enough)\ninput[type=\"search\"] {\n .box-sizing(border-box);\n}\n\n// Position radios and checkboxes better\ninput[type=\"radio\"],\ninput[type=\"checkbox\"] {\n margin: 4px 0 0;\n margin-top: 1px \\9; // IE8-9\n line-height: normal;\n}\n\n// Set the height of file controls to match text inputs\ninput[type=\"file\"] {\n display: block;\n}\n\n// Make range inputs behave like textual form controls\ninput[type=\"range\"] {\n display: block;\n width: 100%;\n}\n\n// Make multiple select elements height not fixed\nselect[multiple],\nselect[size] {\n height: auto;\n}\n\n// Focus for file, radio, and checkbox\ninput[type=\"file\"]:focus,\ninput[type=\"radio\"]:focus,\ninput[type=\"checkbox\"]:focus {\n .tab-focus();\n}\n\n// Adjust output element\noutput {\n display: block;\n padding-top: (@padding-base-vertical + 1);\n font-size: @font-size-base;\n line-height: @line-height-base;\n color: @input-color;\n}\n\n\n// Common form controls\n//\n// Shared size and type resets for form controls. Apply `.form-control` to any\n// of the following form controls:\n//\n// select\n// textarea\n// input[type=\"text\"]\n// input[type=\"password\"]\n// input[type=\"datetime\"]\n// input[type=\"datetime-local\"]\n// input[type=\"date\"]\n// input[type=\"month\"]\n// input[type=\"time\"]\n// input[type=\"week\"]\n// input[type=\"number\"]\n// input[type=\"email\"]\n// input[type=\"url\"]\n// input[type=\"search\"]\n// input[type=\"tel\"]\n// input[type=\"color\"]\n\n.form-control {\n display: block;\n width: 100%;\n height: @input-height-base; // Make inputs at least the height of their button counterpart (base line-height + padding + border)\n padding: @padding-base-vertical @padding-base-horizontal;\n font-size: @font-size-base;\n line-height: @line-height-base;\n color: @input-color;\n background-color: @input-bg;\n background-image: none; // Reset unusual Firefox-on-Android default style; see https://github.com/necolas/normalize.css/issues/214\n border: 1px solid @input-border;\n border-radius: @input-border-radius; // Note: This has no effect on <select>s in some browsers, due to the limited stylability of <select>s in CSS.\n .box-shadow(inset 0 1px 1px rgba(0,0,0,.075));\n .transition(~\"border-color ease-in-out .15s, box-shadow ease-in-out .15s\");\n\n // Customize the `:focus` state to imitate native WebKit styles.\n .form-control-focus();\n\n // Placeholder\n .placeholder();\n\n // Disabled and read-only inputs\n //\n // HTML5 says that controls under a fieldset > legend:first-child won't be\n // disabled if the fieldset is disabled. Due to implementation difficulty, we\n // don't honor that edge case; we style them as disabled anyway.\n &[disabled],\n &[readonly],\n fieldset[disabled] & {\n background-color: @input-bg-disabled;\n opacity: 1; // iOS fix for unreadable disabled content; see https://github.com/twbs/bootstrap/issues/11655\n }\n\n &[disabled],\n fieldset[disabled] & {\n cursor: @cursor-disabled;\n }\n\n // Reset height for `textarea`s\n textarea& {\n height: auto;\n }\n}\n\n\n// Search inputs in iOS\n//\n// This overrides the extra rounded corners on search inputs in iOS so that our\n// `.form-control` class can properly style them. Note that this cannot simply\n// be added to `.form-control` as it's not specific enough. For details, see\n// https://github.com/twbs/bootstrap/issues/11586.\n\ninput[type=\"search\"] {\n -webkit-appearance: none;\n}\n\n\n// Special styles for iOS temporal inputs\n//\n// In Mobile Safari, setting `display: block` on temporal inputs causes the\n// text within the input to become vertically misaligned. As a workaround, we\n// set a pixel line-height that matches the given height of the input, but only\n// for Safari. See https://bugs.webkit.org/show_bug.cgi?id=139848\n\n@media screen and (-webkit-min-device-pixel-ratio: 0) {\n input[type=\"date\"],\n input[type=\"time\"],\n input[type=\"datetime-local\"],\n input[type=\"month\"] {\n line-height: @input-height-base;\n\n &.input-sm,\n .input-group-sm & {\n line-height: @input-height-small;\n }\n\n &.input-lg,\n .input-group-lg & {\n line-height: @input-height-large;\n }\n }\n}\n\n\n// Form groups\n//\n// Designed to help with the organization and spacing of vertical forms. For\n// horizontal forms, use the predefined grid classes.\n\n.form-group {\n margin-bottom: @form-group-margin-bottom;\n}\n\n\n// Checkboxes and radios\n//\n// Indent the labels to position radios/checkboxes as hanging controls.\n\n.radio,\n.checkbox {\n position: relative;\n display: block;\n margin-top: 10px;\n margin-bottom: 10px;\n\n label {\n min-height: @line-height-computed; // Ensure the input doesn't jump when there is no text\n padding-left: 20px;\n margin-bottom: 0;\n font-weight: normal;\n cursor: pointer;\n }\n}\n.radio input[type=\"radio\"],\n.radio-inline input[type=\"radio\"],\n.checkbox input[type=\"checkbox\"],\n.checkbox-inline input[type=\"checkbox\"] {\n position: absolute;\n margin-left: -20px;\n margin-top: 4px \\9;\n}\n\n.radio + .radio,\n.checkbox + .checkbox {\n margin-top: -5px; // Move up sibling radios or checkboxes for tighter spacing\n}\n\n// Radios and checkboxes on same line\n.radio-inline,\n.checkbox-inline {\n position: relative;\n display: inline-block;\n padding-left: 20px;\n margin-bottom: 0;\n vertical-align: middle;\n font-weight: normal;\n cursor: pointer;\n}\n.radio-inline + .radio-inline,\n.checkbox-inline + .checkbox-inline {\n margin-top: 0;\n margin-left: 10px; // space out consecutive inline controls\n}\n\n// Apply same disabled cursor tweak as for inputs\n// Some special care is needed because <label>s don't inherit their parent's `cursor`.\n//\n// Note: Neither radios nor checkboxes can be readonly.\ninput[type=\"radio\"],\ninput[type=\"checkbox\"] {\n &[disabled],\n &.disabled,\n fieldset[disabled] & {\n cursor: @cursor-disabled;\n }\n}\n// These classes are used directly on <label>s\n.radio-inline,\n.checkbox-inline {\n &.disabled,\n fieldset[disabled] & {\n cursor: @cursor-disabled;\n }\n}\n// These classes are used on elements with <label> descendants\n.radio,\n.checkbox {\n &.disabled,\n fieldset[disabled] & {\n label {\n cursor: @cursor-disabled;\n }\n }\n}\n\n\n// Static form control text\n//\n// Apply class to a `p` element to make any string of text align with labels in\n// a horizontal form layout.\n\n.form-control-static {\n // Size it appropriately next to real form controls\n padding-top: (@padding-base-vertical + 1);\n padding-bottom: (@padding-base-vertical + 1);\n // Remove default margin from `p`\n margin-bottom: 0;\n min-height: (@line-height-computed + @font-size-base);\n\n &.input-lg,\n &.input-sm {\n padding-left: 0;\n padding-right: 0;\n }\n}\n\n\n// Form control sizing\n//\n// Build on `.form-control` with modifier classes to decrease or increase the\n// height and font-size of form controls.\n//\n// The `.form-group-* form-control` variations are sadly duplicated to avoid the\n// issue documented in https://github.com/twbs/bootstrap/issues/15074.\n\n.input-sm {\n .input-size(@input-height-small; @padding-small-vertical; @padding-small-horizontal; @font-size-small; @line-height-small; @input-border-radius-small);\n}\n.form-group-sm {\n .form-control {\n .input-size(@input-height-small; @padding-small-vertical; @padding-small-horizontal; @font-size-small; @line-height-small; @input-border-radius-small);\n }\n .form-control-static {\n height: @input-height-small;\n padding: @padding-small-vertical @padding-small-horizontal;\n font-size: @font-size-small;\n line-height: @line-height-small;\n min-height: (@line-height-computed + @font-size-small);\n }\n}\n\n.input-lg {\n .input-size(@input-height-large; @padding-large-vertical; @padding-large-horizontal; @font-size-large; @line-height-large; @input-border-radius-large);\n}\n.form-group-lg {\n .form-control {\n .input-size(@input-height-large; @padding-large-vertical; @padding-large-horizontal; @font-size-large; @line-height-large; @input-border-radius-large);\n }\n .form-control-static {\n height: @input-height-large;\n padding: @padding-large-vertical @padding-large-horizontal;\n font-size: @font-size-large;\n line-height: @line-height-large;\n min-height: (@line-height-computed + @font-size-large);\n }\n}\n\n\n// Form control feedback states\n//\n// Apply contextual and semantic states to individual form controls.\n\n.has-feedback {\n // Enable absolute positioning\n position: relative;\n\n // Ensure icons don't overlap text\n .form-control {\n padding-right: (@input-height-base * 1.25);\n }\n}\n// Feedback icon (requires .glyphicon classes)\n.form-control-feedback {\n position: absolute;\n top: 0;\n right: 0;\n z-index: 2; // Ensure icon is above input groups\n display: block;\n width: @input-height-base;\n height: @input-height-base;\n line-height: @input-height-base;\n text-align: center;\n pointer-events: none;\n}\n.input-lg + .form-control-feedback {\n width: @input-height-large;\n height: @input-height-large;\n line-height: @input-height-large;\n}\n.input-sm + .form-control-feedback {\n width: @input-height-small;\n height: @input-height-small;\n line-height: @input-height-small;\n}\n\n// Feedback states\n.has-success {\n .form-control-validation(@state-success-text; @state-success-text; @state-success-bg);\n}\n.has-warning {\n .form-control-validation(@state-warning-text; @state-warning-text; @state-warning-bg);\n}\n.has-error {\n .form-control-validation(@state-danger-text; @state-danger-text; @state-danger-bg);\n}\n\n// Reposition feedback icon if input has visible label above\n.has-feedback label {\n\n & ~ .form-control-feedback {\n top: (@line-height-computed + 5); // Height of the `label` and its margin\n }\n &.sr-only ~ .form-control-feedback {\n top: 0;\n }\n}\n\n\n// Help text\n//\n// Apply to any element you wish to create light text for placement immediately\n// below a form control. Use for general help, formatting, or instructional text.\n\n.help-block {\n display: block; // account for any element using help-block\n margin-top: 5px;\n margin-bottom: 10px;\n color: lighten(@text-color, 25%); // lighten the text some for contrast\n}\n\n\n// Inline forms\n//\n// Make forms appear inline(-block) by adding the `.form-inline` class. Inline\n// forms begin stacked on extra small (mobile) devices and then go inline when\n// viewports reach <768px.\n//\n// Requires wrapping inputs and labels with `.form-group` for proper display of\n// default HTML form controls and our custom form controls (e.g., input groups).\n//\n// Heads up! This is mixin-ed into `.navbar-form` in navbars.less.\n\n.form-inline {\n\n // Kick in the inline\n @media (min-width: @screen-sm-min) {\n // Inline-block all the things for \"inline\"\n .form-group {\n display: inline-block;\n margin-bottom: 0;\n vertical-align: middle;\n }\n\n // In navbar-form, allow folks to *not* use `.form-group`\n .form-control {\n display: inline-block;\n width: auto; // Prevent labels from stacking above inputs in `.form-group`\n vertical-align: middle;\n }\n\n // Make static controls behave like regular ones\n .form-control-static {\n display: inline-block;\n }\n\n .input-group {\n display: inline-table;\n vertical-align: middle;\n\n .input-group-addon,\n .input-group-btn,\n .form-control {\n width: auto;\n }\n }\n\n // Input groups need that 100% width though\n .input-group > .form-control {\n width: 100%;\n }\n\n .control-label {\n margin-bottom: 0;\n vertical-align: middle;\n }\n\n // Remove default margin on radios/checkboxes that were used for stacking, and\n // then undo the floating of radios and checkboxes to match.\n .radio,\n .checkbox {\n display: inline-block;\n margin-top: 0;\n margin-bottom: 0;\n vertical-align: middle;\n\n label {\n padding-left: 0;\n }\n }\n .radio input[type=\"radio\"],\n .checkbox input[type=\"checkbox\"] {\n position: relative;\n margin-left: 0;\n }\n\n // Re-override the feedback icon.\n .has-feedback .form-control-feedback {\n top: 0;\n }\n }\n}\n\n\n// Horizontal forms\n//\n// Horizontal forms are built on grid classes and allow you to create forms with\n// labels on the left and inputs on the right.\n\n.form-horizontal {\n\n // Consistent vertical alignment of radios and checkboxes\n //\n // Labels also get some reset styles, but that is scoped to a media query below.\n .radio,\n .checkbox,\n .radio-inline,\n .checkbox-inline {\n margin-top: 0;\n margin-bottom: 0;\n padding-top: (@padding-base-vertical + 1); // Default padding plus a border\n }\n // Account for padding we're adding to ensure the alignment and of help text\n // and other content below items\n .radio,\n .checkbox {\n min-height: (@line-height-computed + (@padding-base-vertical + 1));\n }\n\n // Make form groups behave like rows\n .form-group {\n .make-row();\n }\n\n // Reset spacing and right align labels, but scope to media queries so that\n // labels on narrow viewports stack the same as a default form example.\n @media (min-width: @screen-sm-min) {\n .control-label {\n text-align: right;\n margin-bottom: 0;\n padding-top: (@padding-base-vertical + 1); // Default padding plus a border\n }\n }\n\n // Validation states\n //\n // Reposition the icon because it's now within a grid column and columns have\n // `position: relative;` on them. Also accounts for the grid gutter padding.\n .has-feedback .form-control-feedback {\n right: (@grid-gutter-width / 2);\n }\n\n // Form group sizes\n //\n // Quick utility class for applying `.input-lg` and `.input-sm` styles to the\n // inputs and labels within a `.form-group`.\n .form-group-lg {\n @media (min-width: @screen-sm-min) {\n .control-label {\n padding-top: ((@padding-large-vertical * @line-height-large) + 1);\n }\n }\n }\n .form-group-sm {\n @media (min-width: @screen-sm-min) {\n .control-label {\n padding-top: (@padding-small-vertical + 1);\n }\n }\n }\n}\n","// Form validation states\n//\n// Used in forms.less to generate the form validation CSS for warnings, errors,\n// and successes.\n\n.form-control-validation(@text-color: #555; @border-color: #ccc; @background-color: #f5f5f5) {\n // Color the label and help text\n .help-block,\n .control-label,\n .radio,\n .checkbox,\n .radio-inline,\n .checkbox-inline,\n &.radio label,\n &.checkbox label,\n &.radio-inline label,\n &.checkbox-inline label {\n color: @text-color;\n }\n // Set the border and box shadow on specific inputs to match\n .form-control {\n border-color: @border-color;\n .box-shadow(inset 0 1px 1px rgba(0,0,0,.075)); // Redeclare so transitions work\n &:focus {\n border-color: darken(@border-color, 10%);\n @shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 6px lighten(@border-color, 20%);\n .box-shadow(@shadow);\n }\n }\n // Set validation states also for addons\n .input-group-addon {\n color: @text-color;\n border-color: @border-color;\n background-color: @background-color;\n }\n // Optional feedback icon\n .form-control-feedback {\n color: @text-color;\n }\n}\n\n\n// Form control focus state\n//\n// Generate a customized focus state and for any input with the specified color,\n// which defaults to the `@input-border-focus` variable.\n//\n// We highly encourage you to not customize the default value, but instead use\n// this to tweak colors on an as-needed basis. This aesthetic change is based on\n// WebKit's default styles, but applicable to a wider range of browsers. Its\n// usability and accessibility should be taken into account with any change.\n//\n// Example usage: change the default blue border and shadow to white for better\n// contrast against a dark gray background.\n.form-control-focus(@color: @input-border-focus) {\n @color-rgba: rgba(red(@color), green(@color), blue(@color), .6);\n &:focus {\n border-color: @color;\n outline: 0;\n .box-shadow(~\"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px @{color-rgba}\");\n }\n}\n\n// Form control sizing\n//\n// Relative text size, padding, and border-radii changes for form controls. For\n// horizontal sizing, wrap controls in the predefined grid classes. `<select>`\n// element gets special love because it's special, and that's a fact!\n.input-size(@input-height; @padding-vertical; @padding-horizontal; @font-size; @line-height; @border-radius) {\n height: @input-height;\n padding: @padding-vertical @padding-horizontal;\n font-size: @font-size;\n line-height: @line-height;\n border-radius: @border-radius;\n\n select& {\n height: @input-height;\n line-height: @input-height;\n }\n\n textarea&,\n select[multiple]& {\n height: auto;\n }\n}\n","//\n// Buttons\n// --------------------------------------------------\n\n\n// Base styles\n// --------------------------------------------------\n\n.btn {\n display: inline-block;\n margin-bottom: 0; // For input.btn\n font-weight: @btn-font-weight;\n text-align: center;\n vertical-align: middle;\n touch-action: manipulation;\n cursor: pointer;\n background-image: none; // Reset unusual Firefox-on-Android default style; see https://github.com/necolas/normalize.css/issues/214\n border: 1px solid transparent;\n white-space: nowrap;\n .button-size(@padding-base-vertical; @padding-base-horizontal; @font-size-base; @line-height-base; @border-radius-base);\n .user-select(none);\n\n &,\n &:active,\n &.active {\n &:focus,\n &.focus {\n .tab-focus();\n }\n }\n\n &:hover,\n &:focus,\n &.focus {\n color: @btn-default-color;\n text-decoration: none;\n }\n\n &:active,\n &.active {\n outline: 0;\n background-image: none;\n .box-shadow(inset 0 3px 5px rgba(0,0,0,.125));\n }\n\n &.disabled,\n &[disabled],\n fieldset[disabled] & {\n cursor: @cursor-disabled;\n pointer-events: none; // Future-proof disabling of clicks\n .opacity(.65);\n .box-shadow(none);\n }\n}\n\n\n// Alternate buttons\n// --------------------------------------------------\n\n.btn-default {\n .button-variant(@btn-default-color; @btn-default-bg; @btn-default-border);\n}\n.btn-primary {\n .button-variant(@btn-primary-color; @btn-primary-bg; @btn-primary-border);\n}\n// Success appears as green\n.btn-success {\n .button-variant(@btn-success-color; @btn-success-bg; @btn-success-border);\n}\n// Info appears as blue-green\n.btn-info {\n .button-variant(@btn-info-color; @btn-info-bg; @btn-info-border);\n}\n// Warning appears as orange\n.btn-warning {\n .button-variant(@btn-warning-color; @btn-warning-bg; @btn-warning-border);\n}\n// Danger and error appear as red\n.btn-danger {\n .button-variant(@btn-danger-color; @btn-danger-bg; @btn-danger-border);\n}\n\n\n// Link buttons\n// -------------------------\n\n// Make a button look and behave like a link\n.btn-link {\n color: @link-color;\n font-weight: normal;\n border-radius: 0;\n\n &,\n &:active,\n &.active,\n &[disabled],\n fieldset[disabled] & {\n background-color: transparent;\n .box-shadow(none);\n }\n &,\n &:hover,\n &:focus,\n &:active {\n border-color: transparent;\n }\n &:hover,\n &:focus {\n color: @link-hover-color;\n text-decoration: @link-hover-decoration;\n background-color: transparent;\n }\n &[disabled],\n fieldset[disabled] & {\n &:hover,\n &:focus {\n color: @btn-link-disabled-color;\n text-decoration: none;\n }\n }\n}\n\n\n// Button Sizes\n// --------------------------------------------------\n\n.btn-lg {\n // line-height: ensure even-numbered height of button next to large input\n .button-size(@padding-large-vertical; @padding-large-horizontal; @font-size-large; @line-height-large; @border-radius-large);\n}\n.btn-sm {\n // line-height: ensure proper height of button next to small input\n .button-size(@padding-small-vertical; @padding-small-horizontal; @font-size-small; @line-height-small; @border-radius-small);\n}\n.btn-xs {\n .button-size(@padding-xs-vertical; @padding-xs-horizontal; @font-size-small; @line-height-small; @border-radius-small);\n}\n\n\n// Block button\n// --------------------------------------------------\n\n.btn-block {\n display: block;\n width: 100%;\n}\n\n// Vertically space out multiple block buttons\n.btn-block + .btn-block {\n margin-top: 5px;\n}\n\n// Specificity overrides\ninput[type=\"submit\"],\ninput[type=\"reset\"],\ninput[type=\"button\"] {\n &.btn-block {\n width: 100%;\n }\n}\n","// Button variants\n//\n// Easily pump out default styles, as well as :hover, :focus, :active,\n// and disabled options for all buttons\n\n.button-variant(@color; @background; @border) {\n color: @color;\n background-color: @background;\n border-color: @border;\n\n &:hover,\n &:focus,\n &.focus,\n &:active,\n &.active,\n .open > .dropdown-toggle& {\n color: @color;\n background-color: darken(@background, 10%);\n border-color: darken(@border, 12%);\n }\n &:active,\n &.active,\n .open > .dropdown-toggle& {\n background-image: none;\n }\n &.disabled,\n &[disabled],\n fieldset[disabled] & {\n &,\n &:hover,\n &:focus,\n &.focus,\n &:active,\n &.active {\n background-color: @background;\n border-color: @border;\n }\n }\n\n .badge {\n color: @background;\n background-color: @color;\n }\n}\n\n// Button sizes\n.button-size(@padding-vertical; @padding-horizontal; @font-size; @line-height; @border-radius) {\n padding: @padding-vertical @padding-horizontal;\n font-size: @font-size;\n line-height: @line-height;\n border-radius: @border-radius;\n}\n","// Opacity\n\n.opacity(@opacity) {\n opacity: @opacity;\n // IE8 filter\n @opacity-ie: (@opacity * 100);\n filter: ~\"alpha(opacity=@{opacity-ie})\";\n}\n","//\n// Component animations\n// --------------------------------------------------\n\n// Heads up!\n//\n// We don't use the `.opacity()` mixin here since it causes a bug with text\n// fields in IE7-8. Source: https://github.com/twbs/bootstrap/pull/3552.\n\n.fade {\n opacity: 0;\n .transition(opacity .15s linear);\n &.in {\n opacity: 1;\n }\n}\n\n.collapse {\n display: none;\n\n &.in { display: block; }\n tr&.in { display: table-row; }\n tbody&.in { display: table-row-group; }\n}\n\n.collapsing {\n position: relative;\n height: 0;\n overflow: hidden;\n .transition-property(~\"height, visibility\");\n .transition-duration(.35s);\n .transition-timing-function(ease);\n}\n","//\n// Dropdown menus\n// --------------------------------------------------\n\n\n// Dropdown arrow/caret\n.caret {\n display: inline-block;\n width: 0;\n height: 0;\n margin-left: 2px;\n vertical-align: middle;\n border-top: @caret-width-base dashed;\n border-right: @caret-width-base solid transparent;\n border-left: @caret-width-base solid transparent;\n}\n\n// The dropdown wrapper (div)\n.dropup,\n.dropdown {\n position: relative;\n}\n\n// Prevent the focus on the dropdown toggle when closing dropdowns\n.dropdown-toggle:focus {\n outline: 0;\n}\n\n// The dropdown menu (ul)\n.dropdown-menu {\n position: absolute;\n top: 100%;\n left: 0;\n z-index: @zindex-dropdown;\n display: none; // none by default, but block on \"open\" of the menu\n float: left;\n min-width: 160px;\n padding: 5px 0;\n margin: 2px 0 0; // override default ul\n list-style: none;\n font-size: @font-size-base;\n text-align: left; // Ensures proper alignment if parent has it changed (e.g., modal footer)\n background-color: @dropdown-bg;\n border: 1px solid @dropdown-fallback-border; // IE8 fallback\n border: 1px solid @dropdown-border;\n border-radius: @border-radius-base;\n .box-shadow(0 6px 12px rgba(0,0,0,.175));\n background-clip: padding-box;\n\n // Aligns the dropdown menu to right\n //\n // Deprecated as of 3.1.0 in favor of `.dropdown-menu-[dir]`\n &.pull-right {\n right: 0;\n left: auto;\n }\n\n // Dividers (basically an hr) within the dropdown\n .divider {\n .nav-divider(@dropdown-divider-bg);\n }\n\n // Links within the dropdown menu\n > li > a {\n display: block;\n padding: 3px 20px;\n clear: both;\n font-weight: normal;\n line-height: @line-height-base;\n color: @dropdown-link-color;\n white-space: nowrap; // prevent links from randomly breaking onto new lines\n }\n}\n\n// Hover/Focus state\n.dropdown-menu > li > a {\n &:hover,\n &:focus {\n text-decoration: none;\n color: @dropdown-link-hover-color;\n background-color: @dropdown-link-hover-bg;\n }\n}\n\n// Active state\n.dropdown-menu > .active > a {\n &,\n &:hover,\n &:focus {\n color: @dropdown-link-active-color;\n text-decoration: none;\n outline: 0;\n background-color: @dropdown-link-active-bg;\n }\n}\n\n// Disabled state\n//\n// Gray out text and ensure the hover/focus state remains gray\n\n.dropdown-menu > .disabled > a {\n &,\n &:hover,\n &:focus {\n color: @dropdown-link-disabled-color;\n }\n\n // Nuke hover/focus effects\n &:hover,\n &:focus {\n text-decoration: none;\n background-color: transparent;\n background-image: none; // Remove CSS gradient\n .reset-filter();\n cursor: @cursor-disabled;\n }\n}\n\n// Open state for the dropdown\n.open {\n // Show the menu\n > .dropdown-menu {\n display: block;\n }\n\n // Remove the outline when :focus is triggered\n > a {\n outline: 0;\n }\n}\n\n// Menu positioning\n//\n// Add extra class to `.dropdown-menu` to flip the alignment of the dropdown\n// menu with the parent.\n.dropdown-menu-right {\n left: auto; // Reset the default from `.dropdown-menu`\n right: 0;\n}\n// With v3, we enabled auto-flipping if you have a dropdown within a right\n// aligned nav component. To enable the undoing of that, we provide an override\n// to restore the default dropdown menu alignment.\n//\n// This is only for left-aligning a dropdown menu within a `.navbar-right` or\n// `.pull-right` nav component.\n.dropdown-menu-left {\n left: 0;\n right: auto;\n}\n\n// Dropdown section headers\n.dropdown-header {\n display: block;\n padding: 3px 20px;\n font-size: @font-size-small;\n line-height: @line-height-base;\n color: @dropdown-header-color;\n white-space: nowrap; // as with > li > a\n}\n\n// Backdrop to catch body clicks on mobile, etc.\n.dropdown-backdrop {\n position: fixed;\n left: 0;\n right: 0;\n bottom: 0;\n top: 0;\n z-index: (@zindex-dropdown - 10);\n}\n\n// Right aligned dropdowns\n.pull-right > .dropdown-menu {\n right: 0;\n left: auto;\n}\n\n// Allow for dropdowns to go bottom up (aka, dropup-menu)\n//\n// Just add .dropup after the standard .dropdown class and you're set, bro.\n// TODO: abstract this so that the navbar fixed styles are not placed here?\n\n.dropup,\n.navbar-fixed-bottom .dropdown {\n // Reverse the caret\n .caret {\n border-top: 0;\n border-bottom: @caret-width-base solid;\n content: \"\";\n }\n // Different positioning for bottom up menu\n .dropdown-menu {\n top: auto;\n bottom: 100%;\n margin-bottom: 2px;\n }\n}\n\n\n// Component alignment\n//\n// Reiterate per navbar.less and the modified component alignment there.\n\n@media (min-width: @grid-float-breakpoint) {\n .navbar-right {\n .dropdown-menu {\n .dropdown-menu-right();\n }\n // Necessary for overrides of the default right aligned menu.\n // Will remove come v4 in all likelihood.\n .dropdown-menu-left {\n .dropdown-menu-left();\n }\n }\n}\n","// Horizontal dividers\n//\n// Dividers (basically an hr) within dropdowns and nav lists\n\n.nav-divider(@color: #e5e5e5) {\n height: 1px;\n margin: ((@line-height-computed / 2) - 1) 0;\n overflow: hidden;\n background-color: @color;\n}\n","// Reset filters for IE\n//\n// When you need to remove a gradient background, do not forget to use this to reset\n// the IE filter for IE9 and below.\n\n.reset-filter() {\n filter: e(%(\"progid:DXImageTransform.Microsoft.gradient(enabled = false)\"));\n}\n","//\n// Button groups\n// --------------------------------------------------\n\n// Make the div behave like a button\n.btn-group,\n.btn-group-vertical {\n position: relative;\n display: inline-block;\n vertical-align: middle; // match .btn alignment given font-size hack above\n > .btn {\n position: relative;\n float: left;\n // Bring the \"active\" button to the front\n &:hover,\n &:focus,\n &:active,\n &.active {\n z-index: 2;\n }\n }\n}\n\n// Prevent double borders when buttons are next to each other\n.btn-group {\n .btn + .btn,\n .btn + .btn-group,\n .btn-group + .btn,\n .btn-group + .btn-group {\n margin-left: -1px;\n }\n}\n\n// Optional: Group multiple button groups together for a toolbar\n.btn-toolbar {\n margin-left: -5px; // Offset the first child's margin\n &:extend(.clearfix all);\n\n .btn-group,\n .input-group {\n float: left;\n }\n > .btn,\n > .btn-group,\n > .input-group {\n margin-left: 5px;\n }\n}\n\n.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {\n border-radius: 0;\n}\n\n// Set corners individual because sometimes a single button can be in a .btn-group and we need :first-child and :last-child to both match\n.btn-group > .btn:first-child {\n margin-left: 0;\n &:not(:last-child):not(.dropdown-toggle) {\n .border-right-radius(0);\n }\n}\n// Need .dropdown-toggle since :last-child doesn't apply given a .dropdown-menu immediately after it\n.btn-group > .btn:last-child:not(:first-child),\n.btn-group > .dropdown-toggle:not(:first-child) {\n .border-left-radius(0);\n}\n\n// Custom edits for including btn-groups within btn-groups (useful for including dropdown buttons within a btn-group)\n.btn-group > .btn-group {\n float: left;\n}\n.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {\n border-radius: 0;\n}\n.btn-group > .btn-group:first-child:not(:last-child) {\n > .btn:last-child,\n > .dropdown-toggle {\n .border-right-radius(0);\n }\n}\n.btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child {\n .border-left-radius(0);\n}\n\n// On active and open, don't show outline\n.btn-group .dropdown-toggle:active,\n.btn-group.open .dropdown-toggle {\n outline: 0;\n}\n\n\n// Sizing\n//\n// Remix the default button sizing classes into new ones for easier manipulation.\n\n.btn-group-xs > .btn { &:extend(.btn-xs); }\n.btn-group-sm > .btn { &:extend(.btn-sm); }\n.btn-group-lg > .btn { &:extend(.btn-lg); }\n\n\n// Split button dropdowns\n// ----------------------\n\n// Give the line between buttons some depth\n.btn-group > .btn + .dropdown-toggle {\n padding-left: 8px;\n padding-right: 8px;\n}\n.btn-group > .btn-lg + .dropdown-toggle {\n padding-left: 12px;\n padding-right: 12px;\n}\n\n// The clickable button for toggling the menu\n// Remove the gradient and set the same inset shadow as the :active state\n.btn-group.open .dropdown-toggle {\n .box-shadow(inset 0 3px 5px rgba(0,0,0,.125));\n\n // Show no shadow for `.btn-link` since it has no other button styles.\n &.btn-link {\n .box-shadow(none);\n }\n}\n\n\n// Reposition the caret\n.btn .caret {\n margin-left: 0;\n}\n// Carets in other button sizes\n.btn-lg .caret {\n border-width: @caret-width-large @caret-width-large 0;\n border-bottom-width: 0;\n}\n// Upside down carets for .dropup\n.dropup .btn-lg .caret {\n border-width: 0 @caret-width-large @caret-width-large;\n}\n\n\n// Vertical button groups\n// ----------------------\n\n.btn-group-vertical {\n > .btn,\n > .btn-group,\n > .btn-group > .btn {\n display: block;\n float: none;\n width: 100%;\n max-width: 100%;\n }\n\n // Clear floats so dropdown menus can be properly placed\n > .btn-group {\n &:extend(.clearfix all);\n > .btn {\n float: none;\n }\n }\n\n > .btn + .btn,\n > .btn + .btn-group,\n > .btn-group + .btn,\n > .btn-group + .btn-group {\n margin-top: -1px;\n margin-left: 0;\n }\n}\n\n.btn-group-vertical > .btn {\n &:not(:first-child):not(:last-child) {\n border-radius: 0;\n }\n &:first-child:not(:last-child) {\n border-top-right-radius: @border-radius-base;\n .border-bottom-radius(0);\n }\n &:last-child:not(:first-child) {\n border-bottom-left-radius: @border-radius-base;\n .border-top-radius(0);\n }\n}\n.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {\n border-radius: 0;\n}\n.btn-group-vertical > .btn-group:first-child:not(:last-child) {\n > .btn:last-child,\n > .dropdown-toggle {\n .border-bottom-radius(0);\n }\n}\n.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {\n .border-top-radius(0);\n}\n\n\n// Justified button groups\n// ----------------------\n\n.btn-group-justified {\n display: table;\n width: 100%;\n table-layout: fixed;\n border-collapse: separate;\n > .btn,\n > .btn-group {\n float: none;\n display: table-cell;\n width: 1%;\n }\n > .btn-group .btn {\n width: 100%;\n }\n\n > .btn-group .dropdown-menu {\n left: auto;\n }\n}\n\n\n// Checkbox and radio options\n//\n// In order to support the browser's form validation feedback, powered by the\n// `required` attribute, we have to \"hide\" the inputs via `clip`. We cannot use\n// `display: none;` or `visibility: hidden;` as that also hides the popover.\n// Simply visually hiding the inputs via `opacity` would leave them clickable in\n// certain cases which is prevented by using `clip` and `pointer-events`.\n// This way, we ensure a DOM element is visible to position the popover from.\n//\n// See https://github.com/twbs/bootstrap/pull/12794 and\n// https://github.com/twbs/bootstrap/pull/14559 for more information.\n\n[data-toggle=\"buttons\"] {\n > .btn,\n > .btn-group > .btn {\n input[type=\"radio\"],\n input[type=\"checkbox\"] {\n position: absolute;\n clip: rect(0,0,0,0);\n pointer-events: none;\n }\n }\n}\n","// Single side border-radius\n\n.border-top-radius(@radius) {\n border-top-right-radius: @radius;\n border-top-left-radius: @radius;\n}\n.border-right-radius(@radius) {\n border-bottom-right-radius: @radius;\n border-top-right-radius: @radius;\n}\n.border-bottom-radius(@radius) {\n border-bottom-right-radius: @radius;\n border-bottom-left-radius: @radius;\n}\n.border-left-radius(@radius) {\n border-bottom-left-radius: @radius;\n border-top-left-radius: @radius;\n}\n","//\n// Input groups\n// --------------------------------------------------\n\n// Base styles\n// -------------------------\n.input-group {\n position: relative; // For dropdowns\n display: table;\n border-collapse: separate; // prevent input groups from inheriting border styles from table cells when placed within a table\n\n // Undo padding and float of grid classes\n &[class*=\"col-\"] {\n float: none;\n padding-left: 0;\n padding-right: 0;\n }\n\n .form-control {\n // Ensure that the input is always above the *appended* addon button for\n // proper border colors.\n position: relative;\n z-index: 2;\n\n // IE9 fubars the placeholder attribute in text inputs and the arrows on\n // select elements in input groups. To fix it, we float the input. Details:\n // https://github.com/twbs/bootstrap/issues/11561#issuecomment-28936855\n float: left;\n\n width: 100%;\n margin-bottom: 0;\n }\n}\n\n// Sizing options\n//\n// Remix the default form control sizing classes into new ones for easier\n// manipulation.\n\n.input-group-lg > .form-control,\n.input-group-lg > .input-group-addon,\n.input-group-lg > .input-group-btn > .btn {\n .input-lg();\n}\n.input-group-sm > .form-control,\n.input-group-sm > .input-group-addon,\n.input-group-sm > .input-group-btn > .btn {\n .input-sm();\n}\n\n\n// Display as table-cell\n// -------------------------\n.input-group-addon,\n.input-group-btn,\n.input-group .form-control {\n display: table-cell;\n\n &:not(:first-child):not(:last-child) {\n border-radius: 0;\n }\n}\n// Addon and addon wrapper for buttons\n.input-group-addon,\n.input-group-btn {\n width: 1%;\n white-space: nowrap;\n vertical-align: middle; // Match the inputs\n}\n\n// Text input groups\n// -------------------------\n.input-group-addon {\n padding: @padding-base-vertical @padding-base-horizontal;\n font-size: @font-size-base;\n font-weight: normal;\n line-height: 1;\n color: @input-color;\n text-align: center;\n background-color: @input-group-addon-bg;\n border: 1px solid @input-group-addon-border-color;\n border-radius: @border-radius-base;\n\n // Sizing\n &.input-sm {\n padding: @padding-small-vertical @padding-small-horizontal;\n font-size: @font-size-small;\n border-radius: @border-radius-small;\n }\n &.input-lg {\n padding: @padding-large-vertical @padding-large-horizontal;\n font-size: @font-size-large;\n border-radius: @border-radius-large;\n }\n\n // Nuke default margins from checkboxes and radios to vertically center within.\n input[type=\"radio\"],\n input[type=\"checkbox\"] {\n margin-top: 0;\n }\n}\n\n// Reset rounded corners\n.input-group .form-control:first-child,\n.input-group-addon:first-child,\n.input-group-btn:first-child > .btn,\n.input-group-btn:first-child > .btn-group > .btn,\n.input-group-btn:first-child > .dropdown-toggle,\n.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),\n.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {\n .border-right-radius(0);\n}\n.input-group-addon:first-child {\n border-right: 0;\n}\n.input-group .form-control:last-child,\n.input-group-addon:last-child,\n.input-group-btn:last-child > .btn,\n.input-group-btn:last-child > .btn-group > .btn,\n.input-group-btn:last-child > .dropdown-toggle,\n.input-group-btn:first-child > .btn:not(:first-child),\n.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {\n .border-left-radius(0);\n}\n.input-group-addon:last-child {\n border-left: 0;\n}\n\n// Button input groups\n// -------------------------\n.input-group-btn {\n position: relative;\n // Jankily prevent input button groups from wrapping with `white-space` and\n // `font-size` in combination with `inline-block` on buttons.\n font-size: 0;\n white-space: nowrap;\n\n // Negative margin for spacing, position for bringing hovered/focused/actived\n // element above the siblings.\n > .btn {\n position: relative;\n + .btn {\n margin-left: -1px;\n }\n // Bring the \"active\" button to the front\n &:hover,\n &:focus,\n &:active {\n z-index: 2;\n }\n }\n\n // Negative margin to only have a 1px border between the two\n &:first-child {\n > .btn,\n > .btn-group {\n margin-right: -1px;\n }\n }\n &:last-child {\n > .btn,\n > .btn-group {\n margin-left: -1px;\n }\n }\n}\n","//\n// Navs\n// --------------------------------------------------\n\n\n// Base class\n// --------------------------------------------------\n\n.nav {\n margin-bottom: 0;\n padding-left: 0; // Override default ul/ol\n list-style: none;\n &:extend(.clearfix all);\n\n > li {\n position: relative;\n display: block;\n\n > a {\n position: relative;\n display: block;\n padding: @nav-link-padding;\n &:hover,\n &:focus {\n text-decoration: none;\n background-color: @nav-link-hover-bg;\n }\n }\n\n // Disabled state sets text to gray and nukes hover/tab effects\n &.disabled > a {\n color: @nav-disabled-link-color;\n\n &:hover,\n &:focus {\n color: @nav-disabled-link-hover-color;\n text-decoration: none;\n background-color: transparent;\n cursor: @cursor-disabled;\n }\n }\n }\n\n // Open dropdowns\n .open > a {\n &,\n &:hover,\n &:focus {\n background-color: @nav-link-hover-bg;\n border-color: @link-color;\n }\n }\n\n // Nav dividers (deprecated with v3.0.1)\n //\n // This should have been removed in v3 with the dropping of `.nav-list`, but\n // we missed it. We don't currently support this anywhere, but in the interest\n // of maintaining backward compatibility in case you use it, it's deprecated.\n .nav-divider {\n .nav-divider();\n }\n\n // Prevent IE8 from misplacing imgs\n //\n // See https://github.com/h5bp/html5-boilerplate/issues/984#issuecomment-3985989\n > li > a > img {\n max-width: none;\n }\n}\n\n\n// Tabs\n// -------------------------\n\n// Give the tabs something to sit on\n.nav-tabs {\n border-bottom: 1px solid @nav-tabs-border-color;\n > li {\n float: left;\n // Make the list-items overlay the bottom border\n margin-bottom: -1px;\n\n // Actual tabs (as links)\n > a {\n margin-right: 2px;\n line-height: @line-height-base;\n border: 1px solid transparent;\n border-radius: @border-radius-base @border-radius-base 0 0;\n &:hover {\n border-color: @nav-tabs-link-hover-border-color @nav-tabs-link-hover-border-color @nav-tabs-border-color;\n }\n }\n\n // Active state, and its :hover to override normal :hover\n &.active > a {\n &,\n &:hover,\n &:focus {\n color: @nav-tabs-active-link-hover-color;\n background-color: @nav-tabs-active-link-hover-bg;\n border: 1px solid @nav-tabs-active-link-hover-border-color;\n border-bottom-color: transparent;\n cursor: default;\n }\n }\n }\n // pulling this in mainly for less shorthand\n &.nav-justified {\n .nav-justified();\n .nav-tabs-justified();\n }\n}\n\n\n// Pills\n// -------------------------\n.nav-pills {\n > li {\n float: left;\n\n // Links rendered as pills\n > a {\n border-radius: @nav-pills-border-radius;\n }\n + li {\n margin-left: 2px;\n }\n\n // Active state\n &.active > a {\n &,\n &:hover,\n &:focus {\n color: @nav-pills-active-link-hover-color;\n background-color: @nav-pills-active-link-hover-bg;\n }\n }\n }\n}\n\n\n// Stacked pills\n.nav-stacked {\n > li {\n float: none;\n + li {\n margin-top: 2px;\n margin-left: 0; // no need for this gap between nav items\n }\n }\n}\n\n\n// Nav variations\n// --------------------------------------------------\n\n// Justified nav links\n// -------------------------\n\n.nav-justified {\n width: 100%;\n\n > li {\n float: none;\n > a {\n text-align: center;\n margin-bottom: 5px;\n }\n }\n\n > .dropdown .dropdown-menu {\n top: auto;\n left: auto;\n }\n\n @media (min-width: @screen-sm-min) {\n > li {\n display: table-cell;\n width: 1%;\n > a {\n margin-bottom: 0;\n }\n }\n }\n}\n\n// Move borders to anchors instead of bottom of list\n//\n// Mixin for adding on top the shared `.nav-justified` styles for our tabs\n.nav-tabs-justified {\n border-bottom: 0;\n\n > li > a {\n // Override margin from .nav-tabs\n margin-right: 0;\n border-radius: @border-radius-base;\n }\n\n > .active > a,\n > .active > a:hover,\n > .active > a:focus {\n border: 1px solid @nav-tabs-justified-link-border-color;\n }\n\n @media (min-width: @screen-sm-min) {\n > li > a {\n border-bottom: 1px solid @nav-tabs-justified-link-border-color;\n border-radius: @border-radius-base @border-radius-base 0 0;\n }\n > .active > a,\n > .active > a:hover,\n > .active > a:focus {\n border-bottom-color: @nav-tabs-justified-active-link-border-color;\n }\n }\n}\n\n\n// Tabbable tabs\n// -------------------------\n\n// Hide tabbable panes to start, show them when `.active`\n.tab-content {\n > .tab-pane {\n display: none;\n }\n > .active {\n display: block;\n }\n}\n\n\n// Dropdowns\n// -------------------------\n\n// Specific dropdowns\n.nav-tabs .dropdown-menu {\n // make dropdown border overlap tab border\n margin-top: -1px;\n // Remove the top rounded corners here since there is a hard edge above the menu\n .border-top-radius(0);\n}\n","//\n// Navbars\n// --------------------------------------------------\n\n\n// Wrapper and base class\n//\n// Provide a static navbar from which we expand to create full-width, fixed, and\n// other navbar variations.\n\n.navbar {\n position: relative;\n min-height: @navbar-height; // Ensure a navbar always shows (e.g., without a .navbar-brand in collapsed mode)\n margin-bottom: @navbar-margin-bottom;\n border: 1px solid transparent;\n\n // Prevent floats from breaking the navbar\n &:extend(.clearfix all);\n\n @media (min-width: @grid-float-breakpoint) {\n border-radius: @navbar-border-radius;\n }\n}\n\n\n// Navbar heading\n//\n// Groups `.navbar-brand` and `.navbar-toggle` into a single component for easy\n// styling of responsive aspects.\n\n.navbar-header {\n &:extend(.clearfix all);\n\n @media (min-width: @grid-float-breakpoint) {\n float: left;\n }\n}\n\n\n// Navbar collapse (body)\n//\n// Group your navbar content into this for easy collapsing and expanding across\n// various device sizes. By default, this content is collapsed when <768px, but\n// will expand past that for a horizontal display.\n//\n// To start (on mobile devices) the navbar links, forms, and buttons are stacked\n// vertically and include a `max-height` to overflow in case you have too much\n// content for the user's viewport.\n\n.navbar-collapse {\n overflow-x: visible;\n padding-right: @navbar-padding-horizontal;\n padding-left: @navbar-padding-horizontal;\n border-top: 1px solid transparent;\n box-shadow: inset 0 1px 0 rgba(255,255,255,.1);\n &:extend(.clearfix all);\n -webkit-overflow-scrolling: touch;\n\n &.in {\n overflow-y: auto;\n }\n\n @media (min-width: @grid-float-breakpoint) {\n width: auto;\n border-top: 0;\n box-shadow: none;\n\n &.collapse {\n display: block !important;\n height: auto !important;\n padding-bottom: 0; // Override default setting\n overflow: visible !important;\n }\n\n &.in {\n overflow-y: visible;\n }\n\n // Undo the collapse side padding for navbars with containers to ensure\n // alignment of right-aligned contents.\n .navbar-fixed-top &,\n .navbar-static-top &,\n .navbar-fixed-bottom & {\n padding-left: 0;\n padding-right: 0;\n }\n }\n}\n\n.navbar-fixed-top,\n.navbar-fixed-bottom {\n .navbar-collapse {\n max-height: @navbar-collapse-max-height;\n\n @media (max-device-width: @screen-xs-min) and (orientation: landscape) {\n max-height: 200px;\n }\n }\n}\n\n\n// Both navbar header and collapse\n//\n// When a container is present, change the behavior of the header and collapse.\n\n.container,\n.container-fluid {\n > .navbar-header,\n > .navbar-collapse {\n margin-right: -@navbar-padding-horizontal;\n margin-left: -@navbar-padding-horizontal;\n\n @media (min-width: @grid-float-breakpoint) {\n margin-right: 0;\n margin-left: 0;\n }\n }\n}\n\n\n//\n// Navbar alignment options\n//\n// Display the navbar across the entirety of the page or fixed it to the top or\n// bottom of the page.\n\n// Static top (unfixed, but 100% wide) navbar\n.navbar-static-top {\n z-index: @zindex-navbar;\n border-width: 0 0 1px;\n\n @media (min-width: @grid-float-breakpoint) {\n border-radius: 0;\n }\n}\n\n// Fix the top/bottom navbars when screen real estate supports it\n.navbar-fixed-top,\n.navbar-fixed-bottom {\n position: fixed;\n right: 0;\n left: 0;\n z-index: @zindex-navbar-fixed;\n\n // Undo the rounded corners\n @media (min-width: @grid-float-breakpoint) {\n border-radius: 0;\n }\n}\n.navbar-fixed-top {\n top: 0;\n border-width: 0 0 1px;\n}\n.navbar-fixed-bottom {\n bottom: 0;\n margin-bottom: 0; // override .navbar defaults\n border-width: 1px 0 0;\n}\n\n\n// Brand/project name\n\n.navbar-brand {\n float: left;\n padding: @navbar-padding-vertical @navbar-padding-horizontal;\n font-size: @font-size-large;\n line-height: @line-height-computed;\n height: @navbar-height;\n\n &:hover,\n &:focus {\n text-decoration: none;\n }\n\n > img {\n display: block;\n }\n\n @media (min-width: @grid-float-breakpoint) {\n .navbar > .container &,\n .navbar > .container-fluid & {\n margin-left: -@navbar-padding-horizontal;\n }\n }\n}\n\n\n// Navbar toggle\n//\n// Custom button for toggling the `.navbar-collapse`, powered by the collapse\n// JavaScript plugin.\n\n.navbar-toggle {\n position: relative;\n float: right;\n margin-right: @navbar-padding-horizontal;\n padding: 9px 10px;\n .navbar-vertical-align(34px);\n background-color: transparent;\n background-image: none; // Reset unusual Firefox-on-Android default style; see https://github.com/necolas/normalize.css/issues/214\n border: 1px solid transparent;\n border-radius: @border-radius-base;\n\n // We remove the `outline` here, but later compensate by attaching `:hover`\n // styles to `:focus`.\n &:focus {\n outline: 0;\n }\n\n // Bars\n .icon-bar {\n display: block;\n width: 22px;\n height: 2px;\n border-radius: 1px;\n }\n .icon-bar + .icon-bar {\n margin-top: 4px;\n }\n\n @media (min-width: @grid-float-breakpoint) {\n display: none;\n }\n}\n\n\n// Navbar nav links\n//\n// Builds on top of the `.nav` components with its own modifier class to make\n// the nav the full height of the horizontal nav (above 768px).\n\n.navbar-nav {\n margin: (@navbar-padding-vertical / 2) -@navbar-padding-horizontal;\n\n > li > a {\n padding-top: 10px;\n padding-bottom: 10px;\n line-height: @line-height-computed;\n }\n\n @media (max-width: @grid-float-breakpoint-max) {\n // Dropdowns get custom display when collapsed\n .open .dropdown-menu {\n position: static;\n float: none;\n width: auto;\n margin-top: 0;\n background-color: transparent;\n border: 0;\n box-shadow: none;\n > li > a,\n .dropdown-header {\n padding: 5px 15px 5px 25px;\n }\n > li > a {\n line-height: @line-height-computed;\n &:hover,\n &:focus {\n background-image: none;\n }\n }\n }\n }\n\n // Uncollapse the nav\n @media (min-width: @grid-float-breakpoint) {\n float: left;\n margin: 0;\n\n > li {\n float: left;\n > a {\n padding-top: @navbar-padding-vertical;\n padding-bottom: @navbar-padding-vertical;\n }\n }\n }\n}\n\n\n// Navbar form\n//\n// Extension of the `.form-inline` with some extra flavor for optimum display in\n// our navbars.\n\n.navbar-form {\n margin-left: -@navbar-padding-horizontal;\n margin-right: -@navbar-padding-horizontal;\n padding: 10px @navbar-padding-horizontal;\n border-top: 1px solid transparent;\n border-bottom: 1px solid transparent;\n @shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1);\n .box-shadow(@shadow);\n\n // Mixin behavior for optimum display\n .form-inline();\n\n .form-group {\n @media (max-width: @grid-float-breakpoint-max) {\n margin-bottom: 5px;\n\n &:last-child {\n margin-bottom: 0;\n }\n }\n }\n\n // Vertically center in expanded, horizontal navbar\n .navbar-vertical-align(@input-height-base);\n\n // Undo 100% width for pull classes\n @media (min-width: @grid-float-breakpoint) {\n width: auto;\n border: 0;\n margin-left: 0;\n margin-right: 0;\n padding-top: 0;\n padding-bottom: 0;\n .box-shadow(none);\n }\n}\n\n\n// Dropdown menus\n\n// Menu position and menu carets\n.navbar-nav > li > .dropdown-menu {\n margin-top: 0;\n .border-top-radius(0);\n}\n// Menu position and menu caret support for dropups via extra dropup class\n.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {\n margin-bottom: 0;\n .border-top-radius(@navbar-border-radius);\n .border-bottom-radius(0);\n}\n\n\n// Buttons in navbars\n//\n// Vertically center a button within a navbar (when *not* in a form).\n\n.navbar-btn {\n .navbar-vertical-align(@input-height-base);\n\n &.btn-sm {\n .navbar-vertical-align(@input-height-small);\n }\n &.btn-xs {\n .navbar-vertical-align(22);\n }\n}\n\n\n// Text in navbars\n//\n// Add a class to make any element properly align itself vertically within the navbars.\n\n.navbar-text {\n .navbar-vertical-align(@line-height-computed);\n\n @media (min-width: @grid-float-breakpoint) {\n float: left;\n margin-left: @navbar-padding-horizontal;\n margin-right: @navbar-padding-horizontal;\n }\n}\n\n\n// Component alignment\n//\n// Repurpose the pull utilities as their own navbar utilities to avoid specificity\n// issues with parents and chaining. Only do this when the navbar is uncollapsed\n// though so that navbar contents properly stack and align in mobile.\n//\n// Declared after the navbar components to ensure more specificity on the margins.\n\n@media (min-width: @grid-float-breakpoint) {\n .navbar-left { .pull-left(); }\n .navbar-right {\n .pull-right();\n margin-right: -@navbar-padding-horizontal;\n\n ~ .navbar-right {\n margin-right: 0;\n }\n }\n}\n\n\n// Alternate navbars\n// --------------------------------------------------\n\n// Default navbar\n.navbar-default {\n background-color: @navbar-default-bg;\n border-color: @navbar-default-border;\n\n .navbar-brand {\n color: @navbar-default-brand-color;\n &:hover,\n &:focus {\n color: @navbar-default-brand-hover-color;\n background-color: @navbar-default-brand-hover-bg;\n }\n }\n\n .navbar-text {\n color: @navbar-default-color;\n }\n\n .navbar-nav {\n > li > a {\n color: @navbar-default-link-color;\n\n &:hover,\n &:focus {\n color: @navbar-default-link-hover-color;\n background-color: @navbar-default-link-hover-bg;\n }\n }\n > .active > a {\n &,\n &:hover,\n &:focus {\n color: @navbar-default-link-active-color;\n background-color: @navbar-default-link-active-bg;\n }\n }\n > .disabled > a {\n &,\n &:hover,\n &:focus {\n color: @navbar-default-link-disabled-color;\n background-color: @navbar-default-link-disabled-bg;\n }\n }\n }\n\n .navbar-toggle {\n border-color: @navbar-default-toggle-border-color;\n &:hover,\n &:focus {\n background-color: @navbar-default-toggle-hover-bg;\n }\n .icon-bar {\n background-color: @navbar-default-toggle-icon-bar-bg;\n }\n }\n\n .navbar-collapse,\n .navbar-form {\n border-color: @navbar-default-border;\n }\n\n // Dropdown menu items\n .navbar-nav {\n // Remove background color from open dropdown\n > .open > a {\n &,\n &:hover,\n &:focus {\n background-color: @navbar-default-link-active-bg;\n color: @navbar-default-link-active-color;\n }\n }\n\n @media (max-width: @grid-float-breakpoint-max) {\n // Dropdowns get custom display when collapsed\n .open .dropdown-menu {\n > li > a {\n color: @navbar-default-link-color;\n &:hover,\n &:focus {\n color: @navbar-default-link-hover-color;\n background-color: @navbar-default-link-hover-bg;\n }\n }\n > .active > a {\n &,\n &:hover,\n &:focus {\n color: @navbar-default-link-active-color;\n background-color: @navbar-default-link-active-bg;\n }\n }\n > .disabled > a {\n &,\n &:hover,\n &:focus {\n color: @navbar-default-link-disabled-color;\n background-color: @navbar-default-link-disabled-bg;\n }\n }\n }\n }\n }\n\n\n // Links in navbars\n //\n // Add a class to ensure links outside the navbar nav are colored correctly.\n\n .navbar-link {\n color: @navbar-default-link-color;\n &:hover {\n color: @navbar-default-link-hover-color;\n }\n }\n\n .btn-link {\n color: @navbar-default-link-color;\n &:hover,\n &:focus {\n color: @navbar-default-link-hover-color;\n }\n &[disabled],\n fieldset[disabled] & {\n &:hover,\n &:focus {\n color: @navbar-default-link-disabled-color;\n }\n }\n }\n}\n\n// Inverse navbar\n\n.navbar-inverse {\n background-color: @navbar-inverse-bg;\n border-color: @navbar-inverse-border;\n\n .navbar-brand {\n color: @navbar-inverse-brand-color;\n &:hover,\n &:focus {\n color: @navbar-inverse-brand-hover-color;\n background-color: @navbar-inverse-brand-hover-bg;\n }\n }\n\n .navbar-text {\n color: @navbar-inverse-color;\n }\n\n .navbar-nav {\n > li > a {\n color: @navbar-inverse-link-color;\n\n &:hover,\n &:focus {\n color: @navbar-inverse-link-hover-color;\n background-color: @navbar-inverse-link-hover-bg;\n }\n }\n > .active > a {\n &,\n &:hover,\n &:focus {\n color: @navbar-inverse-link-active-color;\n background-color: @navbar-inverse-link-active-bg;\n }\n }\n > .disabled > a {\n &,\n &:hover,\n &:focus {\n color: @navbar-inverse-link-disabled-color;\n background-color: @navbar-inverse-link-disabled-bg;\n }\n }\n }\n\n // Darken the responsive nav toggle\n .navbar-toggle {\n border-color: @navbar-inverse-toggle-border-color;\n &:hover,\n &:focus {\n background-color: @navbar-inverse-toggle-hover-bg;\n }\n .icon-bar {\n background-color: @navbar-inverse-toggle-icon-bar-bg;\n }\n }\n\n .navbar-collapse,\n .navbar-form {\n border-color: darken(@navbar-inverse-bg, 7%);\n }\n\n // Dropdowns\n .navbar-nav {\n > .open > a {\n &,\n &:hover,\n &:focus {\n background-color: @navbar-inverse-link-active-bg;\n color: @navbar-inverse-link-active-color;\n }\n }\n\n @media (max-width: @grid-float-breakpoint-max) {\n // Dropdowns get custom display\n .open .dropdown-menu {\n > .dropdown-header {\n border-color: @navbar-inverse-border;\n }\n .divider {\n background-color: @navbar-inverse-border;\n }\n > li > a {\n color: @navbar-inverse-link-color;\n &:hover,\n &:focus {\n color: @navbar-inverse-link-hover-color;\n background-color: @navbar-inverse-link-hover-bg;\n }\n }\n > .active > a {\n &,\n &:hover,\n &:focus {\n color: @navbar-inverse-link-active-color;\n background-color: @navbar-inverse-link-active-bg;\n }\n }\n > .disabled > a {\n &,\n &:hover,\n &:focus {\n color: @navbar-inverse-link-disabled-color;\n background-color: @navbar-inverse-link-disabled-bg;\n }\n }\n }\n }\n }\n\n .navbar-link {\n color: @navbar-inverse-link-color;\n &:hover {\n color: @navbar-inverse-link-hover-color;\n }\n }\n\n .btn-link {\n color: @navbar-inverse-link-color;\n &:hover,\n &:focus {\n color: @navbar-inverse-link-hover-color;\n }\n &[disabled],\n fieldset[disabled] & {\n &:hover,\n &:focus {\n color: @navbar-inverse-link-disabled-color;\n }\n }\n }\n}\n","// Navbar vertical align\n//\n// Vertically center elements in the navbar.\n// Example: an element has a height of 30px, so write out `.navbar-vertical-align(30px);` to calculate the appropriate top margin.\n\n.navbar-vertical-align(@element-height) {\n margin-top: ((@navbar-height - @element-height) / 2);\n margin-bottom: ((@navbar-height - @element-height) / 2);\n}\n","//\n// Utility classes\n// --------------------------------------------------\n\n\n// Floats\n// -------------------------\n\n.clearfix {\n .clearfix();\n}\n.center-block {\n .center-block();\n}\n.pull-right {\n float: right !important;\n}\n.pull-left {\n float: left !important;\n}\n\n\n// Toggling content\n// -------------------------\n\n// Note: Deprecated .hide in favor of .hidden or .sr-only (as appropriate) in v3.0.1\n.hide {\n display: none !important;\n}\n.show {\n display: block !important;\n}\n.invisible {\n visibility: hidden;\n}\n.text-hide {\n .text-hide();\n}\n\n\n// Hide from screenreaders and browsers\n//\n// Credit: HTML5 Boilerplate\n\n.hidden {\n display: none !important;\n}\n\n\n// For Affix plugin\n// -------------------------\n\n.affix {\n position: fixed;\n}\n","//\n// Breadcrumbs\n// --------------------------------------------------\n\n\n.breadcrumb {\n padding: @breadcrumb-padding-vertical @breadcrumb-padding-horizontal;\n margin-bottom: @line-height-computed;\n list-style: none;\n background-color: @breadcrumb-bg;\n border-radius: @border-radius-base;\n\n > li {\n display: inline-block;\n\n + li:before {\n content: \"@{breadcrumb-separator}\\00a0\"; // Unicode space added since inline-block means non-collapsing white-space\n padding: 0 5px;\n color: @breadcrumb-color;\n }\n }\n\n > .active {\n color: @breadcrumb-active-color;\n }\n}\n","//\n// Pagination (multiple pages)\n// --------------------------------------------------\n.pagination {\n display: inline-block;\n padding-left: 0;\n margin: @line-height-computed 0;\n border-radius: @border-radius-base;\n\n > li {\n display: inline; // Remove list-style and block-level defaults\n > a,\n > span {\n position: relative;\n float: left; // Collapse white-space\n padding: @padding-base-vertical @padding-base-horizontal;\n line-height: @line-height-base;\n text-decoration: none;\n color: @pagination-color;\n background-color: @pagination-bg;\n border: 1px solid @pagination-border;\n margin-left: -1px;\n }\n &:first-child {\n > a,\n > span {\n margin-left: 0;\n .border-left-radius(@border-radius-base);\n }\n }\n &:last-child {\n > a,\n > span {\n .border-right-radius(@border-radius-base);\n }\n }\n }\n\n > li > a,\n > li > span {\n &:hover,\n &:focus {\n color: @pagination-hover-color;\n background-color: @pagination-hover-bg;\n border-color: @pagination-hover-border;\n }\n }\n\n > .active > a,\n > .active > span {\n &,\n &:hover,\n &:focus {\n z-index: 2;\n color: @pagination-active-color;\n background-color: @pagination-active-bg;\n border-color: @pagination-active-border;\n cursor: default;\n }\n }\n\n > .disabled {\n > span,\n > span:hover,\n > span:focus,\n > a,\n > a:hover,\n > a:focus {\n color: @pagination-disabled-color;\n background-color: @pagination-disabled-bg;\n border-color: @pagination-disabled-border;\n cursor: @cursor-disabled;\n }\n }\n}\n\n// Sizing\n// --------------------------------------------------\n\n// Large\n.pagination-lg {\n .pagination-size(@padding-large-vertical; @padding-large-horizontal; @font-size-large; @border-radius-large);\n}\n\n// Small\n.pagination-sm {\n .pagination-size(@padding-small-vertical; @padding-small-horizontal; @font-size-small; @border-radius-small);\n}\n","// Pagination\n\n.pagination-size(@padding-vertical; @padding-horizontal; @font-size; @border-radius) {\n > li {\n > a,\n > span {\n padding: @padding-vertical @padding-horizontal;\n font-size: @font-size;\n }\n &:first-child {\n > a,\n > span {\n .border-left-radius(@border-radius);\n }\n }\n &:last-child {\n > a,\n > span {\n .border-right-radius(@border-radius);\n }\n }\n }\n}\n","//\n// Pager pagination\n// --------------------------------------------------\n\n\n.pager {\n padding-left: 0;\n margin: @line-height-computed 0;\n list-style: none;\n text-align: center;\n &:extend(.clearfix all);\n li {\n display: inline;\n > a,\n > span {\n display: inline-block;\n padding: 5px 14px;\n background-color: @pager-bg;\n border: 1px solid @pager-border;\n border-radius: @pager-border-radius;\n }\n\n > a:hover,\n > a:focus {\n text-decoration: none;\n background-color: @pager-hover-bg;\n }\n }\n\n .next {\n > a,\n > span {\n float: right;\n }\n }\n\n .previous {\n > a,\n > span {\n float: left;\n }\n }\n\n .disabled {\n > a,\n > a:hover,\n > a:focus,\n > span {\n color: @pager-disabled-color;\n background-color: @pager-bg;\n cursor: @cursor-disabled;\n }\n }\n}\n","//\n// Labels\n// --------------------------------------------------\n\n.label {\n display: inline;\n padding: .2em .6em .3em;\n font-size: 75%;\n font-weight: bold;\n line-height: 1;\n color: @label-color;\n text-align: center;\n white-space: nowrap;\n vertical-align: baseline;\n border-radius: .25em;\n\n // Add hover effects, but only for links\n a& {\n &:hover,\n &:focus {\n color: @label-link-hover-color;\n text-decoration: none;\n cursor: pointer;\n }\n }\n\n // Empty labels collapse automatically (not available in IE8)\n &:empty {\n display: none;\n }\n\n // Quick fix for labels in buttons\n .btn & {\n position: relative;\n top: -1px;\n }\n}\n\n// Colors\n// Contextual variations (linked labels get darker on :hover)\n\n.label-default {\n .label-variant(@label-default-bg);\n}\n\n.label-primary {\n .label-variant(@label-primary-bg);\n}\n\n.label-success {\n .label-variant(@label-success-bg);\n}\n\n.label-info {\n .label-variant(@label-info-bg);\n}\n\n.label-warning {\n .label-variant(@label-warning-bg);\n}\n\n.label-danger {\n .label-variant(@label-danger-bg);\n}\n","// Labels\n\n.label-variant(@color) {\n background-color: @color;\n\n &[href] {\n &:hover,\n &:focus {\n background-color: darken(@color, 10%);\n }\n }\n}\n","//\n// Badges\n// --------------------------------------------------\n\n\n// Base class\n.badge {\n display: inline-block;\n min-width: 10px;\n padding: 3px 7px;\n font-size: @font-size-small;\n font-weight: @badge-font-weight;\n color: @badge-color;\n line-height: @badge-line-height;\n vertical-align: baseline;\n white-space: nowrap;\n text-align: center;\n background-color: @badge-bg;\n border-radius: @badge-border-radius;\n\n // Empty badges collapse automatically (not available in IE8)\n &:empty {\n display: none;\n }\n\n // Quick fix for badges in buttons\n .btn & {\n position: relative;\n top: -1px;\n }\n\n .btn-xs &,\n .btn-group-xs > .btn & {\n top: 0;\n padding: 1px 5px;\n }\n\n // Hover state, but only for links\n a& {\n &:hover,\n &:focus {\n color: @badge-link-hover-color;\n text-decoration: none;\n cursor: pointer;\n }\n }\n\n // Account for badges in navs\n .list-group-item.active > &,\n .nav-pills > .active > a > & {\n color: @badge-active-color;\n background-color: @badge-active-bg;\n }\n\n .list-group-item > & {\n float: right;\n }\n\n .list-group-item > & + & {\n margin-right: 5px;\n }\n\n .nav-pills > li > a > & {\n margin-left: 3px;\n }\n}\n","//\n// Jumbotron\n// --------------------------------------------------\n\n\n.jumbotron {\n padding: @jumbotron-padding (@jumbotron-padding / 2);\n margin-bottom: @jumbotron-padding;\n color: @jumbotron-color;\n background-color: @jumbotron-bg;\n\n h1,\n .h1 {\n color: @jumbotron-heading-color;\n }\n\n p {\n margin-bottom: (@jumbotron-padding / 2);\n font-size: @jumbotron-font-size;\n font-weight: 200;\n }\n\n > hr {\n border-top-color: darken(@jumbotron-bg, 10%);\n }\n\n .container &,\n .container-fluid & {\n border-radius: @border-radius-large; // Only round corners at higher resolutions if contained in a container\n }\n\n .container {\n max-width: 100%;\n }\n\n @media screen and (min-width: @screen-sm-min) {\n padding: (@jumbotron-padding * 1.6) 0;\n\n .container &,\n .container-fluid & {\n padding-left: (@jumbotron-padding * 2);\n padding-right: (@jumbotron-padding * 2);\n }\n\n h1,\n .h1 {\n font-size: (@font-size-base * 4.5);\n }\n }\n}\n","//\n// Thumbnails\n// --------------------------------------------------\n\n\n// Mixin and adjust the regular image class\n.thumbnail {\n display: block;\n padding: @thumbnail-padding;\n margin-bottom: @line-height-computed;\n line-height: @line-height-base;\n background-color: @thumbnail-bg;\n border: 1px solid @thumbnail-border;\n border-radius: @thumbnail-border-radius;\n .transition(border .2s ease-in-out);\n\n > img,\n a > img {\n &:extend(.img-responsive);\n margin-left: auto;\n margin-right: auto;\n }\n\n // Add a hover state for linked versions only\n a&:hover,\n a&:focus,\n a&.active {\n border-color: @link-color;\n }\n\n // Image captions\n .caption {\n padding: @thumbnail-caption-padding;\n color: @thumbnail-caption-color;\n }\n}\n","//\n// Alerts\n// --------------------------------------------------\n\n\n// Base styles\n// -------------------------\n\n.alert {\n padding: @alert-padding;\n margin-bottom: @line-height-computed;\n border: 1px solid transparent;\n border-radius: @alert-border-radius;\n\n // Headings for larger alerts\n h4 {\n margin-top: 0;\n // Specified for the h4 to prevent conflicts of changing @headings-color\n color: inherit;\n }\n\n // Provide class for links that match alerts\n .alert-link {\n font-weight: @alert-link-font-weight;\n }\n\n // Improve alignment and spacing of inner content\n > p,\n > ul {\n margin-bottom: 0;\n }\n\n > p + p {\n margin-top: 5px;\n }\n}\n\n// Dismissible alerts\n//\n// Expand the right padding and account for the close button's positioning.\n\n.alert-dismissable, // The misspelled .alert-dismissable was deprecated in 3.2.0.\n.alert-dismissible {\n padding-right: (@alert-padding + 20);\n\n // Adjust close link position\n .close {\n position: relative;\n top: -2px;\n right: -21px;\n color: inherit;\n }\n}\n\n// Alternate styles\n//\n// Generate contextual modifier classes for colorizing the alert.\n\n.alert-success {\n .alert-variant(@alert-success-bg; @alert-success-border; @alert-success-text);\n}\n\n.alert-info {\n .alert-variant(@alert-info-bg; @alert-info-border; @alert-info-text);\n}\n\n.alert-warning {\n .alert-variant(@alert-warning-bg; @alert-warning-border; @alert-warning-text);\n}\n\n.alert-danger {\n .alert-variant(@alert-danger-bg; @alert-danger-border; @alert-danger-text);\n}\n","// Alerts\n\n.alert-variant(@background; @border; @text-color) {\n background-color: @background;\n border-color: @border;\n color: @text-color;\n\n hr {\n border-top-color: darken(@border, 5%);\n }\n .alert-link {\n color: darken(@text-color, 10%);\n }\n}\n","//\n// Progress bars\n// --------------------------------------------------\n\n\n// Bar animations\n// -------------------------\n\n// WebKit\n@-webkit-keyframes progress-bar-stripes {\n from { background-position: 40px 0; }\n to { background-position: 0 0; }\n}\n\n// Spec and IE10+\n@keyframes progress-bar-stripes {\n from { background-position: 40px 0; }\n to { background-position: 0 0; }\n}\n\n\n// Bar itself\n// -------------------------\n\n// Outer container\n.progress {\n overflow: hidden;\n height: @line-height-computed;\n margin-bottom: @line-height-computed;\n background-color: @progress-bg;\n border-radius: @progress-border-radius;\n .box-shadow(inset 0 1px 2px rgba(0,0,0,.1));\n}\n\n// Bar of progress\n.progress-bar {\n float: left;\n width: 0%;\n height: 100%;\n font-size: @font-size-small;\n line-height: @line-height-computed;\n color: @progress-bar-color;\n text-align: center;\n background-color: @progress-bar-bg;\n .box-shadow(inset 0 -1px 0 rgba(0,0,0,.15));\n .transition(width .6s ease);\n}\n\n// Striped bars\n//\n// `.progress-striped .progress-bar` is deprecated as of v3.2.0 in favor of the\n// `.progress-bar-striped` class, which you just add to an existing\n// `.progress-bar`.\n.progress-striped .progress-bar,\n.progress-bar-striped {\n #gradient > .striped();\n background-size: 40px 40px;\n}\n\n// Call animation for the active one\n//\n// `.progress.active .progress-bar` is deprecated as of v3.2.0 in favor of the\n// `.progress-bar.active` approach.\n.progress.active .progress-bar,\n.progress-bar.active {\n .animation(progress-bar-stripes 2s linear infinite);\n}\n\n\n// Variations\n// -------------------------\n\n.progress-bar-success {\n .progress-bar-variant(@progress-bar-success-bg);\n}\n\n.progress-bar-info {\n .progress-bar-variant(@progress-bar-info-bg);\n}\n\n.progress-bar-warning {\n .progress-bar-variant(@progress-bar-warning-bg);\n}\n\n.progress-bar-danger {\n .progress-bar-variant(@progress-bar-danger-bg);\n}\n","// Gradients\n\n#gradient {\n\n // Horizontal gradient, from left to right\n //\n // Creates two color stops, start and end, by specifying a color and position for each color stop.\n // Color stops are not available in IE9 and below.\n .horizontal(@start-color: #555; @end-color: #333; @start-percent: 0%; @end-percent: 100%) {\n background-image: -webkit-linear-gradient(left, @start-color @start-percent, @end-color @end-percent); // Safari 5.1-6, Chrome 10+\n background-image: -o-linear-gradient(left, @start-color @start-percent, @end-color @end-percent); // Opera 12\n background-image: linear-gradient(to right, @start-color @start-percent, @end-color @end-percent); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+\n background-repeat: repeat-x;\n filter: e(%(\"progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)\",argb(@start-color),argb(@end-color))); // IE9 and down\n }\n\n // Vertical gradient, from top to bottom\n //\n // Creates two color stops, start and end, by specifying a color and position for each color stop.\n // Color stops are not available in IE9 and below.\n .vertical(@start-color: #555; @end-color: #333; @start-percent: 0%; @end-percent: 100%) {\n background-image: -webkit-linear-gradient(top, @start-color @start-percent, @end-color @end-percent); // Safari 5.1-6, Chrome 10+\n background-image: -o-linear-gradient(top, @start-color @start-percent, @end-color @end-percent); // Opera 12\n background-image: linear-gradient(to bottom, @start-color @start-percent, @end-color @end-percent); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+\n background-repeat: repeat-x;\n filter: e(%(\"progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)\",argb(@start-color),argb(@end-color))); // IE9 and down\n }\n\n .directional(@start-color: #555; @end-color: #333; @deg: 45deg) {\n background-repeat: repeat-x;\n background-image: -webkit-linear-gradient(@deg, @start-color, @end-color); // Safari 5.1-6, Chrome 10+\n background-image: -o-linear-gradient(@deg, @start-color, @end-color); // Opera 12\n background-image: linear-gradient(@deg, @start-color, @end-color); // Standard, IE10, Firefox 16+, Opera 12.10+, Safari 7+, Chrome 26+\n }\n .horizontal-three-colors(@start-color: #00b3ee; @mid-color: #7a43b6; @color-stop: 50%; @end-color: #c3325f) {\n background-image: -webkit-linear-gradient(left, @start-color, @mid-color @color-stop, @end-color);\n background-image: -o-linear-gradient(left, @start-color, @mid-color @color-stop, @end-color);\n background-image: linear-gradient(to right, @start-color, @mid-color @color-stop, @end-color);\n background-repeat: no-repeat;\n filter: e(%(\"progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)\",argb(@start-color),argb(@end-color))); // IE9 and down, gets no color-stop at all for proper fallback\n }\n .vertical-three-colors(@start-color: #00b3ee; @mid-color: #7a43b6; @color-stop: 50%; @end-color: #c3325f) {\n background-image: -webkit-linear-gradient(@start-color, @mid-color @color-stop, @end-color);\n background-image: -o-linear-gradient(@start-color, @mid-color @color-stop, @end-color);\n background-image: linear-gradient(@start-color, @mid-color @color-stop, @end-color);\n background-repeat: no-repeat;\n filter: e(%(\"progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)\",argb(@start-color),argb(@end-color))); // IE9 and down, gets no color-stop at all for proper fallback\n }\n .radial(@inner-color: #555; @outer-color: #333) {\n background-image: -webkit-radial-gradient(circle, @inner-color, @outer-color);\n background-image: radial-gradient(circle, @inner-color, @outer-color);\n background-repeat: no-repeat;\n }\n .striped(@color: rgba(255,255,255,.15); @angle: 45deg) {\n background-image: -webkit-linear-gradient(@angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent);\n background-image: -o-linear-gradient(@angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent);\n background-image: linear-gradient(@angle, @color 25%, transparent 25%, transparent 50%, @color 50%, @color 75%, transparent 75%, transparent);\n }\n}\n","// Progress bars\n\n.progress-bar-variant(@color) {\n background-color: @color;\n\n // Deprecated parent class requirement as of v3.2.0\n .progress-striped & {\n #gradient > .striped();\n }\n}\n",".media {\n // Proper spacing between instances of .media\n margin-top: 15px;\n\n &:first-child {\n margin-top: 0;\n }\n}\n\n.media,\n.media-body {\n zoom: 1;\n overflow: hidden;\n}\n\n.media-body {\n width: 10000px;\n}\n\n.media-object {\n display: block;\n}\n\n.media-right,\n.media > .pull-right {\n padding-left: 10px;\n}\n\n.media-left,\n.media > .pull-left {\n padding-right: 10px;\n}\n\n.media-left,\n.media-right,\n.media-body {\n display: table-cell;\n vertical-align: top;\n}\n\n.media-middle {\n vertical-align: middle;\n}\n\n.media-bottom {\n vertical-align: bottom;\n}\n\n// Reset margins on headings for tighter default spacing\n.media-heading {\n margin-top: 0;\n margin-bottom: 5px;\n}\n\n// Media list variation\n//\n// Undo default ul/ol styles\n.media-list {\n padding-left: 0;\n list-style: none;\n}\n","//\n// List groups\n// --------------------------------------------------\n\n\n// Base class\n//\n// Easily usable on <ul>, <ol>, or <div>.\n\n.list-group {\n // No need to set list-style: none; since .list-group-item is block level\n margin-bottom: 20px;\n padding-left: 0; // reset padding because ul and ol\n}\n\n\n// Individual list items\n//\n// Use on `li`s or `div`s within the `.list-group` parent.\n\n.list-group-item {\n position: relative;\n display: block;\n padding: 10px 15px;\n // Place the border on the list items and negative margin up for better styling\n margin-bottom: -1px;\n background-color: @list-group-bg;\n border: 1px solid @list-group-border;\n\n // Round the first and last items\n &:first-child {\n .border-top-radius(@list-group-border-radius);\n }\n &:last-child {\n margin-bottom: 0;\n .border-bottom-radius(@list-group-border-radius);\n }\n}\n\n\n// Linked list items\n//\n// Use anchor elements instead of `li`s or `div`s to create linked list items.\n// Includes an extra `.active` modifier class for showing selected items.\n\na.list-group-item {\n color: @list-group-link-color;\n\n .list-group-item-heading {\n color: @list-group-link-heading-color;\n }\n\n // Hover state\n &:hover,\n &:focus {\n text-decoration: none;\n color: @list-group-link-hover-color;\n background-color: @list-group-hover-bg;\n }\n}\n\n.list-group-item {\n // Disabled state\n &.disabled,\n &.disabled:hover,\n &.disabled:focus {\n background-color: @list-group-disabled-bg;\n color: @list-group-disabled-color;\n cursor: @cursor-disabled;\n\n // Force color to inherit for custom content\n .list-group-item-heading {\n color: inherit;\n }\n .list-group-item-text {\n color: @list-group-disabled-text-color;\n }\n }\n\n // Active class on item itself, not parent\n &.active,\n &.active:hover,\n &.active:focus {\n z-index: 2; // Place active items above their siblings for proper border styling\n color: @list-group-active-color;\n background-color: @list-group-active-bg;\n border-color: @list-group-active-border;\n\n // Force color to inherit for custom content\n .list-group-item-heading,\n .list-group-item-heading > small,\n .list-group-item-heading > .small {\n color: inherit;\n }\n .list-group-item-text {\n color: @list-group-active-text-color;\n }\n }\n}\n\n\n// Contextual variants\n//\n// Add modifier classes to change text and background color on individual items.\n// Organizationally, this must come after the `:hover` states.\n\n.list-group-item-variant(success; @state-success-bg; @state-success-text);\n.list-group-item-variant(info; @state-info-bg; @state-info-text);\n.list-group-item-variant(warning; @state-warning-bg; @state-warning-text);\n.list-group-item-variant(danger; @state-danger-bg; @state-danger-text);\n\n\n// Custom content options\n//\n// Extra classes for creating well-formatted content within `.list-group-item`s.\n\n.list-group-item-heading {\n margin-top: 0;\n margin-bottom: 5px;\n}\n.list-group-item-text {\n margin-bottom: 0;\n line-height: 1.3;\n}\n","// List Groups\n\n.list-group-item-variant(@state; @background; @color) {\n .list-group-item-@{state} {\n color: @color;\n background-color: @background;\n\n a& {\n color: @color;\n\n .list-group-item-heading {\n color: inherit;\n }\n\n &:hover,\n &:focus {\n color: @color;\n background-color: darken(@background, 5%);\n }\n &.active,\n &.active:hover,\n &.active:focus {\n color: #fff;\n background-color: @color;\n border-color: @color;\n }\n }\n }\n}\n","//\n// Panels\n// --------------------------------------------------\n\n\n// Base class\n.panel {\n margin-bottom: @line-height-computed;\n background-color: @panel-bg;\n border: 1px solid transparent;\n border-radius: @panel-border-radius;\n .box-shadow(0 1px 1px rgba(0,0,0,.05));\n}\n\n// Panel contents\n.panel-body {\n padding: @panel-body-padding;\n &:extend(.clearfix all);\n}\n\n// Optional heading\n.panel-heading {\n padding: @panel-heading-padding;\n border-bottom: 1px solid transparent;\n .border-top-radius((@panel-border-radius - 1));\n\n > .dropdown .dropdown-toggle {\n color: inherit;\n }\n}\n\n// Within heading, strip any `h*` tag of its default margins for spacing.\n.panel-title {\n margin-top: 0;\n margin-bottom: 0;\n font-size: ceil((@font-size-base * 1.125));\n color: inherit;\n\n > a,\n > small,\n > .small,\n > small > a,\n > .small > a {\n color: inherit;\n }\n}\n\n// Optional footer (stays gray in every modifier class)\n.panel-footer {\n padding: @panel-footer-padding;\n background-color: @panel-footer-bg;\n border-top: 1px solid @panel-inner-border;\n .border-bottom-radius((@panel-border-radius - 1));\n}\n\n\n// List groups in panels\n//\n// By default, space out list group content from panel headings to account for\n// any kind of custom content between the two.\n\n.panel {\n > .list-group,\n > .panel-collapse > .list-group {\n margin-bottom: 0;\n\n .list-group-item {\n border-width: 1px 0;\n border-radius: 0;\n }\n\n // Add border top radius for first one\n &:first-child {\n .list-group-item:first-child {\n border-top: 0;\n .border-top-radius((@panel-border-radius - 1));\n }\n }\n // Add border bottom radius for last one\n &:last-child {\n .list-group-item:last-child {\n border-bottom: 0;\n .border-bottom-radius((@panel-border-radius - 1));\n }\n }\n }\n}\n// Collapse space between when there's no additional content.\n.panel-heading + .list-group {\n .list-group-item:first-child {\n border-top-width: 0;\n }\n}\n.list-group + .panel-footer {\n border-top-width: 0;\n}\n\n// Tables in panels\n//\n// Place a non-bordered `.table` within a panel (not within a `.panel-body`) and\n// watch it go full width.\n\n.panel {\n > .table,\n > .table-responsive > .table,\n > .panel-collapse > .table {\n margin-bottom: 0;\n\n caption {\n padding-left: @panel-body-padding;\n padding-right: @panel-body-padding;\n }\n }\n // Add border top radius for first one\n > .table:first-child,\n > .table-responsive:first-child > .table:first-child {\n .border-top-radius((@panel-border-radius - 1));\n\n > thead:first-child,\n > tbody:first-child {\n > tr:first-child {\n border-top-left-radius: (@panel-border-radius - 1);\n border-top-right-radius: (@panel-border-radius - 1);\n\n td:first-child,\n th:first-child {\n border-top-left-radius: (@panel-border-radius - 1);\n }\n td:last-child,\n th:last-child {\n border-top-right-radius: (@panel-border-radius - 1);\n }\n }\n }\n }\n // Add border bottom radius for last one\n > .table:last-child,\n > .table-responsive:last-child > .table:last-child {\n .border-bottom-radius((@panel-border-radius - 1));\n\n > tbody:last-child,\n > tfoot:last-child {\n > tr:last-child {\n border-bottom-left-radius: (@panel-border-radius - 1);\n border-bottom-right-radius: (@panel-border-radius - 1);\n\n td:first-child,\n th:first-child {\n border-bottom-left-radius: (@panel-border-radius - 1);\n }\n td:last-child,\n th:last-child {\n border-bottom-right-radius: (@panel-border-radius - 1);\n }\n }\n }\n }\n > .panel-body + .table,\n > .panel-body + .table-responsive,\n > .table + .panel-body,\n > .table-responsive + .panel-body {\n border-top: 1px solid @table-border-color;\n }\n > .table > tbody:first-child > tr:first-child th,\n > .table > tbody:first-child > tr:first-child td {\n border-top: 0;\n }\n > .table-bordered,\n > .table-responsive > .table-bordered {\n border: 0;\n > thead,\n > tbody,\n > tfoot {\n > tr {\n > th:first-child,\n > td:first-child {\n border-left: 0;\n }\n > th:last-child,\n > td:last-child {\n border-right: 0;\n }\n }\n }\n > thead,\n > tbody {\n > tr:first-child {\n > td,\n > th {\n border-bottom: 0;\n }\n }\n }\n > tbody,\n > tfoot {\n > tr:last-child {\n > td,\n > th {\n border-bottom: 0;\n }\n }\n }\n }\n > .table-responsive {\n border: 0;\n margin-bottom: 0;\n }\n}\n\n\n// Collapsable panels (aka, accordion)\n//\n// Wrap a series of panels in `.panel-group` to turn them into an accordion with\n// the help of our collapse JavaScript plugin.\n\n.panel-group {\n margin-bottom: @line-height-computed;\n\n // Tighten up margin so it's only between panels\n .panel {\n margin-bottom: 0;\n border-radius: @panel-border-radius;\n\n + .panel {\n margin-top: 5px;\n }\n }\n\n .panel-heading {\n border-bottom: 0;\n\n + .panel-collapse > .panel-body,\n + .panel-collapse > .list-group {\n border-top: 1px solid @panel-inner-border;\n }\n }\n\n .panel-footer {\n border-top: 0;\n + .panel-collapse .panel-body {\n border-bottom: 1px solid @panel-inner-border;\n }\n }\n}\n\n\n// Contextual variations\n.panel-default {\n .panel-variant(@panel-default-border; @panel-default-text; @panel-default-heading-bg; @panel-default-border);\n}\n.panel-primary {\n .panel-variant(@panel-primary-border; @panel-primary-text; @panel-primary-heading-bg; @panel-primary-border);\n}\n.panel-success {\n .panel-variant(@panel-success-border; @panel-success-text; @panel-success-heading-bg; @panel-success-border);\n}\n.panel-info {\n .panel-variant(@panel-info-border; @panel-info-text; @panel-info-heading-bg; @panel-info-border);\n}\n.panel-warning {\n .panel-variant(@panel-warning-border; @panel-warning-text; @panel-warning-heading-bg; @panel-warning-border);\n}\n.panel-danger {\n .panel-variant(@panel-danger-border; @panel-danger-text; @panel-danger-heading-bg; @panel-danger-border);\n}\n","// Panels\n\n.panel-variant(@border; @heading-text-color; @heading-bg-color; @heading-border) {\n border-color: @border;\n\n & > .panel-heading {\n color: @heading-text-color;\n background-color: @heading-bg-color;\n border-color: @heading-border;\n\n + .panel-collapse > .panel-body {\n border-top-color: @border;\n }\n .badge {\n color: @heading-bg-color;\n background-color: @heading-text-color;\n }\n }\n & > .panel-footer {\n + .panel-collapse > .panel-body {\n border-bottom-color: @border;\n }\n }\n}\n","// Embeds responsive\n//\n// Credit: Nicolas Gallagher and SUIT CSS.\n\n.embed-responsive {\n position: relative;\n display: block;\n height: 0;\n padding: 0;\n overflow: hidden;\n\n .embed-responsive-item,\n iframe,\n embed,\n object,\n video {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n height: 100%;\n width: 100%;\n border: 0;\n }\n}\n\n// Modifier class for 16:9 aspect ratio\n.embed-responsive-16by9 {\n padding-bottom: 56.25%;\n}\n\n// Modifier class for 4:3 aspect ratio\n.embed-responsive-4by3 {\n padding-bottom: 75%;\n}\n","//\n// Wells\n// --------------------------------------------------\n\n\n// Base class\n.well {\n min-height: 20px;\n padding: 19px;\n margin-bottom: 20px;\n background-color: @well-bg;\n border: 1px solid @well-border;\n border-radius: @border-radius-base;\n .box-shadow(inset 0 1px 1px rgba(0,0,0,.05));\n blockquote {\n border-color: #ddd;\n border-color: rgba(0,0,0,.15);\n }\n}\n\n// Sizes\n.well-lg {\n padding: 24px;\n border-radius: @border-radius-large;\n}\n.well-sm {\n padding: 9px;\n border-radius: @border-radius-small;\n}\n","//\n// Close icons\n// --------------------------------------------------\n\n\n.close {\n float: right;\n font-size: (@font-size-base * 1.5);\n font-weight: @close-font-weight;\n line-height: 1;\n color: @close-color;\n text-shadow: @close-text-shadow;\n .opacity(.2);\n\n &:hover,\n &:focus {\n color: @close-color;\n text-decoration: none;\n cursor: pointer;\n .opacity(.5);\n }\n\n // Additional properties for button version\n // iOS requires the button element instead of an anchor tag.\n // If you want the anchor version, it requires `href=\"#\"`.\n // See https://developer.mozilla.org/en-US/docs/Web/Events/click#Safari_Mobile\n button& {\n padding: 0;\n cursor: pointer;\n background: transparent;\n border: 0;\n -webkit-appearance: none;\n }\n}\n","//\n// Modals\n// --------------------------------------------------\n\n// .modal-open - body class for killing the scroll\n// .modal - container to scroll within\n// .modal-dialog - positioning shell for the actual modal\n// .modal-content - actual modal w/ bg and corners and shit\n\n// Kill the scroll on the body\n.modal-open {\n overflow: hidden;\n}\n\n// Container that the modal scrolls within\n.modal {\n display: none;\n overflow: hidden;\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: @zindex-modal;\n -webkit-overflow-scrolling: touch;\n\n // Prevent Chrome on Windows from adding a focus outline. For details, see\n // https://github.com/twbs/bootstrap/pull/10951.\n outline: 0;\n\n // When fading in the modal, animate it to slide down\n &.fade .modal-dialog {\n .translate(0, -25%);\n .transition-transform(~\"0.3s ease-out\");\n }\n &.in .modal-dialog { .translate(0, 0) }\n}\n.modal-open .modal {\n overflow-x: hidden;\n overflow-y: auto;\n}\n\n// Shell div to position the modal with bottom padding\n.modal-dialog {\n position: relative;\n width: auto;\n margin: 10px;\n}\n\n// Actual modal\n.modal-content {\n position: relative;\n background-color: @modal-content-bg;\n border: 1px solid @modal-content-fallback-border-color; //old browsers fallback (ie8 etc)\n border: 1px solid @modal-content-border-color;\n border-radius: @border-radius-large;\n .box-shadow(0 3px 9px rgba(0,0,0,.5));\n background-clip: padding-box;\n // Remove focus outline from opened modal\n outline: 0;\n}\n\n// Modal background\n.modal-backdrop {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: @zindex-modal-background;\n background-color: @modal-backdrop-bg;\n // Fade for backdrop\n &.fade { .opacity(0); }\n &.in { .opacity(@modal-backdrop-opacity); }\n}\n\n// Modal header\n// Top section of the modal w/ title and dismiss\n.modal-header {\n padding: @modal-title-padding;\n border-bottom: 1px solid @modal-header-border-color;\n min-height: (@modal-title-padding + @modal-title-line-height);\n}\n// Close icon\n.modal-header .close {\n margin-top: -2px;\n}\n\n// Title text within header\n.modal-title {\n margin: 0;\n line-height: @modal-title-line-height;\n}\n\n// Modal body\n// Where all modal content resides (sibling of .modal-header and .modal-footer)\n.modal-body {\n position: relative;\n padding: @modal-inner-padding;\n}\n\n// Footer (for actions)\n.modal-footer {\n padding: @modal-inner-padding;\n text-align: right; // right align buttons\n border-top: 1px solid @modal-footer-border-color;\n &:extend(.clearfix all); // clear it in case folks use .pull-* classes on buttons\n\n // Properly space out buttons\n .btn + .btn {\n margin-left: 5px;\n margin-bottom: 0; // account for input[type=\"submit\"] which gets the bottom margin like all other inputs\n }\n // but override that for button groups\n .btn-group .btn + .btn {\n margin-left: -1px;\n }\n // and override it for block buttons as well\n .btn-block + .btn-block {\n margin-left: 0;\n }\n}\n\n// Measure scrollbar width for padding body during modal show/hide\n.modal-scrollbar-measure {\n position: absolute;\n top: -9999px;\n width: 50px;\n height: 50px;\n overflow: scroll;\n}\n\n// Scale up the modal\n@media (min-width: @screen-sm-min) {\n // Automatically set modal's width for larger viewports\n .modal-dialog {\n width: @modal-md;\n margin: 30px auto;\n }\n .modal-content {\n .box-shadow(0 5px 15px rgba(0,0,0,.5));\n }\n\n // Modal sizes\n .modal-sm { width: @modal-sm; }\n}\n\n@media (min-width: @screen-md-min) {\n .modal-lg { width: @modal-lg; }\n}\n","//\n// Tooltips\n// --------------------------------------------------\n\n\n// Base class\n.tooltip {\n position: absolute;\n z-index: @zindex-tooltip;\n display: block;\n // Reset font and text properties given new insertion method\n font-family: @font-family-base;\n font-size: @font-size-small;\n font-weight: normal;\n line-height: 1.4;\n .opacity(0);\n\n &.in { .opacity(@tooltip-opacity); }\n &.top { margin-top: -3px; padding: @tooltip-arrow-width 0; }\n &.right { margin-left: 3px; padding: 0 @tooltip-arrow-width; }\n &.bottom { margin-top: 3px; padding: @tooltip-arrow-width 0; }\n &.left { margin-left: -3px; padding: 0 @tooltip-arrow-width; }\n}\n\n// Wrapper for the tooltip content\n.tooltip-inner {\n max-width: @tooltip-max-width;\n padding: 3px 8px;\n color: @tooltip-color;\n text-align: center;\n text-decoration: none;\n background-color: @tooltip-bg;\n border-radius: @border-radius-base;\n}\n\n// Arrows\n.tooltip-arrow {\n position: absolute;\n width: 0;\n height: 0;\n border-color: transparent;\n border-style: solid;\n}\n// Note: Deprecated .top-left, .top-right, .bottom-left, and .bottom-right as of v3.3.1\n.tooltip {\n &.top .tooltip-arrow {\n bottom: 0;\n left: 50%;\n margin-left: -@tooltip-arrow-width;\n border-width: @tooltip-arrow-width @tooltip-arrow-width 0;\n border-top-color: @tooltip-arrow-color;\n }\n &.top-left .tooltip-arrow {\n bottom: 0;\n right: @tooltip-arrow-width;\n margin-bottom: -@tooltip-arrow-width;\n border-width: @tooltip-arrow-width @tooltip-arrow-width 0;\n border-top-color: @tooltip-arrow-color;\n }\n &.top-right .tooltip-arrow {\n bottom: 0;\n left: @tooltip-arrow-width;\n margin-bottom: -@tooltip-arrow-width;\n border-width: @tooltip-arrow-width @tooltip-arrow-width 0;\n border-top-color: @tooltip-arrow-color;\n }\n &.right .tooltip-arrow {\n top: 50%;\n left: 0;\n margin-top: -@tooltip-arrow-width;\n border-width: @tooltip-arrow-width @tooltip-arrow-width @tooltip-arrow-width 0;\n border-right-color: @tooltip-arrow-color;\n }\n &.left .tooltip-arrow {\n top: 50%;\n right: 0;\n margin-top: -@tooltip-arrow-width;\n border-width: @tooltip-arrow-width 0 @tooltip-arrow-width @tooltip-arrow-width;\n border-left-color: @tooltip-arrow-color;\n }\n &.bottom .tooltip-arrow {\n top: 0;\n left: 50%;\n margin-left: -@tooltip-arrow-width;\n border-width: 0 @tooltip-arrow-width @tooltip-arrow-width;\n border-bottom-color: @tooltip-arrow-color;\n }\n &.bottom-left .tooltip-arrow {\n top: 0;\n right: @tooltip-arrow-width;\n margin-top: -@tooltip-arrow-width;\n border-width: 0 @tooltip-arrow-width @tooltip-arrow-width;\n border-bottom-color: @tooltip-arrow-color;\n }\n &.bottom-right .tooltip-arrow {\n top: 0;\n left: @tooltip-arrow-width;\n margin-top: -@tooltip-arrow-width;\n border-width: 0 @tooltip-arrow-width @tooltip-arrow-width;\n border-bottom-color: @tooltip-arrow-color;\n }\n}\n","//\n// Popovers\n// --------------------------------------------------\n\n\n.popover {\n position: absolute;\n top: 0;\n left: 0;\n z-index: @zindex-popover;\n display: none;\n max-width: @popover-max-width;\n padding: 1px;\n // Reset font and text properties given new insertion method\n font-family: @font-family-base;\n font-size: @font-size-base;\n font-weight: normal;\n line-height: @line-height-base;\n text-align: left;\n background-color: @popover-bg;\n background-clip: padding-box;\n border: 1px solid @popover-fallback-border-color;\n border: 1px solid @popover-border-color;\n border-radius: @border-radius-large;\n .box-shadow(0 5px 10px rgba(0,0,0,.2));\n\n // Overrides for proper insertion\n white-space: normal;\n\n // Offset the popover to account for the popover arrow\n &.top { margin-top: -@popover-arrow-width; }\n &.right { margin-left: @popover-arrow-width; }\n &.bottom { margin-top: @popover-arrow-width; }\n &.left { margin-left: -@popover-arrow-width; }\n}\n\n.popover-title {\n margin: 0; // reset heading margin\n padding: 8px 14px;\n font-size: @font-size-base;\n background-color: @popover-title-bg;\n border-bottom: 1px solid darken(@popover-title-bg, 5%);\n border-radius: (@border-radius-large - 1) (@border-radius-large - 1) 0 0;\n}\n\n.popover-content {\n padding: 9px 14px;\n}\n\n// Arrows\n//\n// .arrow is outer, .arrow:after is inner\n\n.popover > .arrow {\n &,\n &:after {\n position: absolute;\n display: block;\n width: 0;\n height: 0;\n border-color: transparent;\n border-style: solid;\n }\n}\n.popover > .arrow {\n border-width: @popover-arrow-outer-width;\n}\n.popover > .arrow:after {\n border-width: @popover-arrow-width;\n content: \"\";\n}\n\n.popover {\n &.top > .arrow {\n left: 50%;\n margin-left: -@popover-arrow-outer-width;\n border-bottom-width: 0;\n border-top-color: @popover-arrow-outer-fallback-color; // IE8 fallback\n border-top-color: @popover-arrow-outer-color;\n bottom: -@popover-arrow-outer-width;\n &:after {\n content: \" \";\n bottom: 1px;\n margin-left: -@popover-arrow-width;\n border-bottom-width: 0;\n border-top-color: @popover-arrow-color;\n }\n }\n &.right > .arrow {\n top: 50%;\n left: -@popover-arrow-outer-width;\n margin-top: -@popover-arrow-outer-width;\n border-left-width: 0;\n border-right-color: @popover-arrow-outer-fallback-color; // IE8 fallback\n border-right-color: @popover-arrow-outer-color;\n &:after {\n content: \" \";\n left: 1px;\n bottom: -@popover-arrow-width;\n border-left-width: 0;\n border-right-color: @popover-arrow-color;\n }\n }\n &.bottom > .arrow {\n left: 50%;\n margin-left: -@popover-arrow-outer-width;\n border-top-width: 0;\n border-bottom-color: @popover-arrow-outer-fallback-color; // IE8 fallback\n border-bottom-color: @popover-arrow-outer-color;\n top: -@popover-arrow-outer-width;\n &:after {\n content: \" \";\n top: 1px;\n margin-left: -@popover-arrow-width;\n border-top-width: 0;\n border-bottom-color: @popover-arrow-color;\n }\n }\n\n &.left > .arrow {\n top: 50%;\n right: -@popover-arrow-outer-width;\n margin-top: -@popover-arrow-outer-width;\n border-right-width: 0;\n border-left-color: @popover-arrow-outer-fallback-color; // IE8 fallback\n border-left-color: @popover-arrow-outer-color;\n &:after {\n content: \" \";\n right: 1px;\n border-right-width: 0;\n border-left-color: @popover-arrow-color;\n bottom: -@popover-arrow-width;\n }\n }\n}\n","//\n// Carousel\n// --------------------------------------------------\n\n\n// Wrapper for the slide container and indicators\n.carousel {\n position: relative;\n}\n\n.carousel-inner {\n position: relative;\n overflow: hidden;\n width: 100%;\n\n > .item {\n display: none;\n position: relative;\n .transition(.6s ease-in-out left);\n\n // Account for jankitude on images\n > img,\n > a > img {\n &:extend(.img-responsive);\n line-height: 1;\n }\n\n // WebKit CSS3 transforms for supported devices\n @media all and (transform-3d), (-webkit-transform-3d) {\n .transition-transform(~'0.6s ease-in-out');\n .backface-visibility(~'hidden');\n .perspective(1000);\n\n &.next,\n &.active.right {\n .translate3d(100%, 0, 0);\n left: 0;\n }\n &.prev,\n &.active.left {\n .translate3d(-100%, 0, 0);\n left: 0;\n }\n &.next.left,\n &.prev.right,\n &.active {\n .translate3d(0, 0, 0);\n left: 0;\n }\n }\n }\n\n > .active,\n > .next,\n > .prev {\n display: block;\n }\n\n > .active {\n left: 0;\n }\n\n > .next,\n > .prev {\n position: absolute;\n top: 0;\n width: 100%;\n }\n\n > .next {\n left: 100%;\n }\n > .prev {\n left: -100%;\n }\n > .next.left,\n > .prev.right {\n left: 0;\n }\n\n > .active.left {\n left: -100%;\n }\n > .active.right {\n left: 100%;\n }\n\n}\n\n// Left/right controls for nav\n// ---------------------------\n\n.carousel-control {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n width: @carousel-control-width;\n .opacity(@carousel-control-opacity);\n font-size: @carousel-control-font-size;\n color: @carousel-control-color;\n text-align: center;\n text-shadow: @carousel-text-shadow;\n // We can't have this transition here because WebKit cancels the carousel\n // animation if you trip this while in the middle of another animation.\n\n // Set gradients for backgrounds\n &.left {\n #gradient > .horizontal(@start-color: rgba(0,0,0,.5); @end-color: rgba(0,0,0,.0001));\n }\n &.right {\n left: auto;\n right: 0;\n #gradient > .horizontal(@start-color: rgba(0,0,0,.0001); @end-color: rgba(0,0,0,.5));\n }\n\n // Hover/focus state\n &:hover,\n &:focus {\n outline: 0;\n color: @carousel-control-color;\n text-decoration: none;\n .opacity(.9);\n }\n\n // Toggles\n .icon-prev,\n .icon-next,\n .glyphicon-chevron-left,\n .glyphicon-chevron-right {\n position: absolute;\n top: 50%;\n z-index: 5;\n display: inline-block;\n }\n .icon-prev,\n .glyphicon-chevron-left {\n left: 50%;\n margin-left: -10px;\n }\n .icon-next,\n .glyphicon-chevron-right {\n right: 50%;\n margin-right: -10px;\n }\n .icon-prev,\n .icon-next {\n width: 20px;\n height: 20px;\n margin-top: -10px;\n line-height: 1;\n font-family: serif;\n }\n\n\n .icon-prev {\n &:before {\n content: '\\2039';// SINGLE LEFT-POINTING ANGLE QUOTATION MARK (U+2039)\n }\n }\n .icon-next {\n &:before {\n content: '\\203a';// SINGLE RIGHT-POINTING ANGLE QUOTATION MARK (U+203A)\n }\n }\n}\n\n// Optional indicator pips\n//\n// Add an unordered list with the following class and add a list item for each\n// slide your carousel holds.\n\n.carousel-indicators {\n position: absolute;\n bottom: 10px;\n left: 50%;\n z-index: 15;\n width: 60%;\n margin-left: -30%;\n padding-left: 0;\n list-style: none;\n text-align: center;\n\n li {\n display: inline-block;\n width: 10px;\n height: 10px;\n margin: 1px;\n text-indent: -999px;\n border: 1px solid @carousel-indicator-border-color;\n border-radius: 10px;\n cursor: pointer;\n\n // IE8-9 hack for event handling\n //\n // Internet Explorer 8-9 does not support clicks on elements without a set\n // `background-color`. We cannot use `filter` since that's not viewed as a\n // background color by the browser. Thus, a hack is needed.\n // See https://developer.mozilla.org/en-US/docs/Web/Events/click#Internet_Explorer\n //\n // For IE8, we set solid black as it doesn't support `rgba()`. For IE9, we\n // set alpha transparency for the best results possible.\n background-color: #000 \\9; // IE8\n background-color: rgba(0,0,0,0); // IE9\n }\n .active {\n margin: 0;\n width: 12px;\n height: 12px;\n background-color: @carousel-indicator-active-bg;\n }\n}\n\n// Optional captions\n// -----------------------------\n// Hidden by default for smaller viewports\n.carousel-caption {\n position: absolute;\n left: 15%;\n right: 15%;\n bottom: 20px;\n z-index: 10;\n padding-top: 20px;\n padding-bottom: 20px;\n color: @carousel-caption-color;\n text-align: center;\n text-shadow: @carousel-text-shadow;\n & .btn {\n text-shadow: none; // No shadow for button elements in carousel-caption\n }\n}\n\n\n// Scale up controls for tablets and up\n@media screen and (min-width: @screen-sm-min) {\n\n // Scale up the controls a smidge\n .carousel-control {\n .glyphicon-chevron-left,\n .glyphicon-chevron-right,\n .icon-prev,\n .icon-next {\n width: 30px;\n height: 30px;\n margin-top: -15px;\n font-size: 30px;\n }\n .glyphicon-chevron-left,\n .icon-prev {\n margin-left: -15px;\n }\n .glyphicon-chevron-right,\n .icon-next {\n margin-right: -15px;\n }\n }\n\n // Show and left align the captions\n .carousel-caption {\n left: 20%;\n right: 20%;\n padding-bottom: 30px;\n }\n\n // Move up the indicators\n .carousel-indicators {\n bottom: 20px;\n }\n}\n","// Clearfix\n//\n// For modern browsers\n// 1. The space content is one way to avoid an Opera bug when the\n// contenteditable attribute is included anywhere else in the document.\n// Otherwise it causes space to appear at the top and bottom of elements\n// that are clearfixed.\n// 2. The use of `table` rather than `block` is only necessary if using\n// `:before` to contain the top-margins of child elements.\n//\n// Source: http://nicolasgallagher.com/micro-clearfix-hack/\n\n.clearfix() {\n &:before,\n &:after {\n content: \" \"; // 1\n display: table; // 2\n }\n &:after {\n clear: both;\n }\n}\n","// Center-align a block level element\n\n.center-block() {\n display: block;\n margin-left: auto;\n margin-right: auto;\n}\n","// CSS image replacement\n//\n// Heads up! v3 launched with with only `.hide-text()`, but per our pattern for\n// mixins being reused as classes with the same name, this doesn't hold up. As\n// of v3.0.1 we have added `.text-hide()` and deprecated `.hide-text()`.\n//\n// Source: https://github.com/h5bp/html5-boilerplate/commit/aa0396eae757\n\n// Deprecated as of v3.0.1 (will be removed in v4)\n.hide-text() {\n font: ~\"0/0\" a;\n color: transparent;\n text-shadow: none;\n background-color: transparent;\n border: 0;\n}\n\n// New mixin to use as of v3.0.1\n.text-hide() {\n .hide-text();\n}\n","//\n// Responsive: Utility classes\n// --------------------------------------------------\n\n\n// IE10 in Windows (Phone) 8\n//\n// Support for responsive views via media queries is kind of borked in IE10, for\n// Surface/desktop in split view and for Windows Phone 8. This particular fix\n// must be accompanied by a snippet of JavaScript to sniff the user agent and\n// apply some conditional CSS to *only* the Surface/desktop Windows 8. Look at\n// our Getting Started page for more information on this bug.\n//\n// For more information, see the following:\n//\n// Issue: https://github.com/twbs/bootstrap/issues/10497\n// Docs: http://getbootstrap.com/getting-started/#support-ie10-width\n// Source: http://timkadlec.com/2013/01/windows-phone-8-and-device-width/\n// Source: http://timkadlec.com/2012/10/ie10-snap-mode-and-responsive-design/\n\n@-ms-viewport {\n width: device-width;\n}\n\n\n// Visibility utilities\n// Note: Deprecated .visible-xs, .visible-sm, .visible-md, and .visible-lg as of v3.2.0\n.visible-xs,\n.visible-sm,\n.visible-md,\n.visible-lg {\n .responsive-invisibility();\n}\n\n.visible-xs-block,\n.visible-xs-inline,\n.visible-xs-inline-block,\n.visible-sm-block,\n.visible-sm-inline,\n.visible-sm-inline-block,\n.visible-md-block,\n.visible-md-inline,\n.visible-md-inline-block,\n.visible-lg-block,\n.visible-lg-inline,\n.visible-lg-inline-block {\n display: none !important;\n}\n\n.visible-xs {\n @media (max-width: @screen-xs-max) {\n .responsive-visibility();\n }\n}\n.visible-xs-block {\n @media (max-width: @screen-xs-max) {\n display: block !important;\n }\n}\n.visible-xs-inline {\n @media (max-width: @screen-xs-max) {\n display: inline !important;\n }\n}\n.visible-xs-inline-block {\n @media (max-width: @screen-xs-max) {\n display: inline-block !important;\n }\n}\n\n.visible-sm {\n @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {\n .responsive-visibility();\n }\n}\n.visible-sm-block {\n @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {\n display: block !important;\n }\n}\n.visible-sm-inline {\n @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {\n display: inline !important;\n }\n}\n.visible-sm-inline-block {\n @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {\n display: inline-block !important;\n }\n}\n\n.visible-md {\n @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {\n .responsive-visibility();\n }\n}\n.visible-md-block {\n @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {\n display: block !important;\n }\n}\n.visible-md-inline {\n @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {\n display: inline !important;\n }\n}\n.visible-md-inline-block {\n @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {\n display: inline-block !important;\n }\n}\n\n.visible-lg {\n @media (min-width: @screen-lg-min) {\n .responsive-visibility();\n }\n}\n.visible-lg-block {\n @media (min-width: @screen-lg-min) {\n display: block !important;\n }\n}\n.visible-lg-inline {\n @media (min-width: @screen-lg-min) {\n display: inline !important;\n }\n}\n.visible-lg-inline-block {\n @media (min-width: @screen-lg-min) {\n display: inline-block !important;\n }\n}\n\n.hidden-xs {\n @media (max-width: @screen-xs-max) {\n .responsive-invisibility();\n }\n}\n.hidden-sm {\n @media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) {\n .responsive-invisibility();\n }\n}\n.hidden-md {\n @media (min-width: @screen-md-min) and (max-width: @screen-md-max) {\n .responsive-invisibility();\n }\n}\n.hidden-lg {\n @media (min-width: @screen-lg-min) {\n .responsive-invisibility();\n }\n}\n\n\n// Print utilities\n//\n// Media queries are placed on the inside to be mixin-friendly.\n\n// Note: Deprecated .visible-print as of v3.2.0\n.visible-print {\n .responsive-invisibility();\n\n @media print {\n .responsive-visibility();\n }\n}\n.visible-print-block {\n display: none !important;\n\n @media print {\n display: block !important;\n }\n}\n.visible-print-inline {\n display: none !important;\n\n @media print {\n display: inline !important;\n }\n}\n.visible-print-inline-block {\n display: none !important;\n\n @media print {\n display: inline-block !important;\n }\n}\n\n.hidden-print {\n @media print {\n .responsive-invisibility();\n }\n}\n","// Responsive utilities\n\n//\n// More easily include all the states for responsive-utilities.less.\n.responsive-visibility() {\n display: block !important;\n table& { display: table; }\n tr& { display: table-row !important; }\n th&,\n td& { display: table-cell !important; }\n}\n\n.responsive-invisibility() {\n display: none !important;\n}\n"]}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap.min.css b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap.min.css
new file mode 100644
index 0000000..cd1c616
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/css/bootstrap.min.css
@@ -0,0 +1,5 @@
+/*!
+ * Bootstrap v3.3.4 (http://getbootstrap.com)
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ *//*! normalize.css v3.0.2 | MIT License | git.io/normalize */html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background-color:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0;font-size:2em}mark{color:#000;background:#ff0}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{height:0;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{margin:0;font:inherit;color:inherit}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}input{line-height:normal}input[type=checkbox],input[type=radio]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid silver}legend{padding:0;border:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-spacing:0;border-collapse:collapse}td,th{padding:0}/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */@media print{*,:after,:before{color:#000!important;text-shadow:none!important;background:0 0!important;-webkit-box-shadow:none!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="javascript:"]:after,a[href^="#"]:after{content:""}blockquote,pre{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}img{max-width:100%!important}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}select{background:#fff!important}.navbar{display:none}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #ddd!important}}@font-face{font-family:'Glyphicons Halflings';src:url(../fonts/glyphicons-halflings-regular.eot);src:url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(../fonts/glyphicons-halflings-regular.woff2) format('woff2'),url(../fonts/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/glyphicons-halflings-regular.ttf) format('truetype'),url(../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"\2a"}.glyphicon-plus:before{content:"\2b"}.glyphicon-eur:before,.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-lock:before{content:"\e033"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-bookmark:before{content:"\e044"}.glyphicon-print:before{content:"\e045"}.glyphicon-camera:before{content:"\e046"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-fire:before{content:"\e104"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-calendar:before{content:"\e109"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-bell:before{content:"\e123"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-wrench:before{content:"\e136"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-briefcase:before{content:"\e139"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-paperclip:before{content:"\e142"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-pushpin:before{content:"\e146"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}.glyphicon-cd:before{content:"\e201"}.glyphicon-save-file:before{content:"\e202"}.glyphicon-open-file:before{content:"\e203"}.glyphicon-level-up:before{content:"\e204"}.glyphicon-copy:before{content:"\e205"}.glyphicon-paste:before{content:"\e206"}.glyphicon-alert:before{content:"\e209"}.glyphicon-equalizer:before{content:"\e210"}.glyphicon-king:before{content:"\e211"}.glyphicon-queen:before{content:"\e212"}.glyphicon-pawn:before{content:"\e213"}.glyphicon-bishop:before{content:"\e214"}.glyphicon-knight:before{content:"\e215"}.glyphicon-baby-formula:before{content:"\e216"}.glyphicon-tent:before{content:"\26fa"}.glyphicon-blackboard:before{content:"\e218"}.glyphicon-bed:before{content:"\e219"}.glyphicon-apple:before{content:"\f8ff"}.glyphicon-erase:before{content:"\e221"}.glyphicon-hourglass:before{content:"\231b"}.glyphicon-lamp:before{content:"\e223"}.glyphicon-duplicate:before{content:"\e224"}.glyphicon-piggy-bank:before{content:"\e225"}.glyphicon-scissors:before{content:"\e226"}.glyphicon-bitcoin:before{content:"\e227"}.glyphicon-btc:before{content:"\e227"}.glyphicon-xbt:before{content:"\e227"}.glyphicon-yen:before{content:"\00a5"}.glyphicon-jpy:before{content:"\00a5"}.glyphicon-ruble:before{content:"\20bd"}.glyphicon-rub:before{content:"\20bd"}.glyphicon-scale:before{content:"\e230"}.glyphicon-ice-lolly:before{content:"\e231"}.glyphicon-ice-lolly-tasted:before{content:"\e232"}.glyphicon-education:before{content:"\e233"}.glyphicon-option-horizontal:before{content:"\e234"}.glyphicon-option-vertical:before{content:"\e235"}.glyphicon-menu-hamburger:before{content:"\e236"}.glyphicon-modal-window:before{content:"\e237"}.glyphicon-oil:before{content:"\e238"}.glyphicon-grain:before{content:"\e239"}.glyphicon-sunglasses:before{content:"\e240"}.glyphicon-text-size:before{content:"\e241"}.glyphicon-text-color:before{content:"\e242"}.glyphicon-text-background:before{content:"\e243"}.glyphicon-object-align-top:before{content:"\e244"}.glyphicon-object-align-bottom:before{content:"\e245"}.glyphicon-object-align-horizontal:before{content:"\e246"}.glyphicon-object-align-left:before{content:"\e247"}.glyphicon-object-align-vertical:before{content:"\e248"}.glyphicon-object-align-right:before{content:"\e249"}.glyphicon-triangle-right:before{content:"\e250"}.glyphicon-triangle-left:before{content:"\e251"}.glyphicon-triangle-bottom:before{content:"\e252"}.glyphicon-triangle-top:before{content:"\e253"}.glyphicon-console:before{content:"\e254"}.glyphicon-superscript:before{content:"\e255"}.glyphicon-subscript:before{content:"\e256"}.glyphicon-menu-left:before{content:"\e257"}.glyphicon-menu-right:before{content:"\e258"}.glyphicon-menu-down:before{content:"\e259"}.glyphicon-menu-up:before{content:"\e260"}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}:after,:before{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}button,input,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#337ab7;text-decoration:none}a:focus,a:hover{color:#23527c;text-decoration:underline}a:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.carousel-inner>.item>a>img,.carousel-inner>.item>img,.img-responsive,.thumbnail a>img,.thumbnail>img{display:block;max-width:100%;height:auto}.img-rounded{border-radius:6px}.img-thumbnail{display:inline-block;max-width:100%;height:auto;padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}[role=button]{cursor:pointer}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-weight:400;line-height:1;color:#777}.h1,.h2,.h3,h1,h2,h3{margin-top:20px;margin-bottom:10px}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small{font-size:65%}.h4,.h5,.h6,h4,h5,h6{margin-top:10px;margin-bottom:10px}.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-size:75%}.h1,h1{font-size:36px}.h2,h2{font-size:30px}.h3,h3{font-size:24px}.h4,h4{font-size:18px}.h5,h5{font-size:14px}.h6,h6{font-size:12px}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16px;font-weight:300;line-height:1.4}@media (min-width:768px){.lead{font-size:21px}}.small,small{font-size:85%}.mark,mark{padding:.2em;background-color:#fcf8e3}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-nowrap{white-space:nowrap}.text-lowercase{text-transform:lowercase}.text-uppercase{text-transform:uppercase}.text-capitalize{text-transform:capitalize}.text-muted{color:#777}.text-primary{color:#337ab7}a.text-primary:hover{color:#286090}.text-success{color:#3c763d}a.text-success:hover{color:#2b542c}.text-info{color:#31708f}a.text-info:hover{color:#245269}.text-warning{color:#8a6d3b}a.text-warning:hover{color:#66512c}.text-danger{color:#a94442}a.text-danger:hover{color:#843534}.bg-primary{color:#fff;background-color:#337ab7}a.bg-primary:hover{background-color:#286090}.bg-success{background-color:#dff0d8}a.bg-success:hover{background-color:#c1e2b3}.bg-info{background-color:#d9edf7}a.bg-info:hover{background-color:#afd9ee}.bg-warning{background-color:#fcf8e3}a.bg-warning:hover{background-color:#f7ecb5}.bg-danger{background-color:#f2dede}a.bg-danger:hover{background-color:#e4b9b9}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ol,ul{margin-top:0;margin-bottom:10px}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;margin-left:-5px;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-top:0;margin-bottom:20px}dd,dt{line-height:1.42857143}dt{font-weight:700}dd{margin-left:0}@media (min-width:768px){.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[data-original-title],abbr[title]{cursor:help;border-bottom:1px dotted #777}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}blockquote ol:last-child,blockquote p:last-child,blockquote ul:last-child{margin-bottom:0}blockquote .small,blockquote footer,blockquote small{display:block;font-size:80%;line-height:1.42857143;color:#777}blockquote .small:before,blockquote footer:before,blockquote small:before{content:'\2014 \00A0'}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;text-align:right;border-right:5px solid #eee;border-left:0}.blockquote-reverse .small:before,.blockquote-reverse footer:before,.blockquote-reverse small:before,blockquote.pull-right .small:before,blockquote.pull-right footer:before,blockquote.pull-right small:before{content:''}.blockquote-reverse .small:after,.blockquote-reverse footer:after,.blockquote-reverse small:after,blockquote.pull-right .small:after,blockquote.pull-right footer:after,blockquote.pull-right small:after{content:'\00A0 \2014'}address{margin-bottom:20px;font-style:normal;line-height:1.42857143}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;border-radius:4px}kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.25);box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;font-weight:700;-webkit-box-shadow:none;box-shadow:none}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{margin-right:-15px;margin-left:-15px}.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:auto}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-0{left:auto}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}.col-sm-pull-0{right:auto}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666667%}.col-sm-push-10{left:83.33333333%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666667%}.col-sm-push-7{left:58.33333333%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666667%}.col-sm-push-4{left:33.33333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.66666667%}.col-sm-push-1{left:8.33333333%}.col-sm-push-0{left:auto}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666667%}.col-sm-offset-10{margin-left:83.33333333%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666667%}.col-sm-offset-7{margin-left:58.33333333%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666667%}.col-sm-offset-4{margin-left:33.33333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.66666667%}.col-sm-offset-1{margin-left:8.33333333%}.col-sm-offset-0{margin-left:0}}@media (min-width:992px){.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666667%}.col-md-pull-10{right:83.33333333%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666667%}.col-md-pull-7{right:58.33333333%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666667%}.col-md-pull-4{right:33.33333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.66666667%}.col-md-pull-1{right:8.33333333%}.col-md-pull-0{right:auto}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666667%}.col-md-push-10{left:83.33333333%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666667%}.col-md-push-7{left:58.33333333%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666667%}.col-md-push-4{left:33.33333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.66666667%}.col-md-push-1{left:8.33333333%}.col-md-push-0{left:auto}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666667%}.col-md-offset-10{margin-left:83.33333333%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666667%}.col-md-offset-7{margin-left:58.33333333%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666667%}.col-md-offset-4{margin-left:33.33333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.66666667%}.col-md-offset-1{margin-left:8.33333333%}.col-md-offset-0{margin-left:0}}@media (min-width:1200px){.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666667%}.col-lg-pull-10{right:83.33333333%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666667%}.col-lg-pull-7{right:58.33333333%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666667%}.col-lg-pull-4{right:33.33333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.66666667%}.col-lg-pull-1{right:8.33333333%}.col-lg-pull-0{right:auto}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666667%}.col-lg-push-10{left:83.33333333%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666667%}.col-lg-push-7{left:58.33333333%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666667%}.col-lg-push-4{left:33.33333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.66666667%}.col-lg-push-1{left:8.33333333%}.col-lg-push-0{left:auto}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666667%}.col-lg-offset-10{margin-left:83.33333333%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666667%}.col-lg-offset-7{margin-left:58.33333333%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666667%}.col-lg-offset-4{margin-left:33.33333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.66666667%}.col-lg-offset-1{margin-left:8.33333333%}.col-lg-offset-0{margin-left:0}}table{background-color:transparent}caption{padding-top:8px;padding-bottom:8px;color:#777;text-align:left}th{text-align:left}.table{width:100%;max-width:100%;margin-bottom:20px}.table>tbody>tr>td,.table>tbody>tr>th,.table>tfoot>tr>td,.table>tfoot>tr>th,.table>thead>tr>td,.table>thead>tr>th{padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>td,.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>td,.table>thead:first-child>tr:first-child>th{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>tbody>tr>td,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>td,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>thead>tr>th{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>tbody>tr>td,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>td,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border:1px solid #ddd}.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border-bottom-width:2px}.table-striped>tbody>tr:nth-of-type(odd){background-color:#f9f9f9}.table-hover>tbody>tr:hover{background-color:#f5f5f5}table col[class*=col-]{position:static;display:table-column;float:none}table td[class*=col-],table th[class*=col-]{position:static;display:table-cell;float:none}.table>tbody>tr.active>td,.table>tbody>tr.active>th,.table>tbody>tr>td.active,.table>tbody>tr>th.active,.table>tfoot>tr.active>td,.table>tfoot>tr.active>th,.table>tfoot>tr>td.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>thead>tr.active>th,.table>thead>tr>td.active,.table>thead>tr>th.active{background-color:#f5f5f5}.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr.active:hover>th,.table-hover>tbody>tr:hover>.active,.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover{background-color:#e8e8e8}.table>tbody>tr.success>td,.table>tbody>tr.success>th,.table>tbody>tr>td.success,.table>tbody>tr>th.success,.table>tfoot>tr.success>td,.table>tfoot>tr.success>th,.table>tfoot>tr>td.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>thead>tr.success>th,.table>thead>tr>td.success,.table>thead>tr>th.success{background-color:#dff0d8}.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr.success:hover>th,.table-hover>tbody>tr:hover>.success,.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover{background-color:#d0e9c6}.table>tbody>tr.info>td,.table>tbody>tr.info>th,.table>tbody>tr>td.info,.table>tbody>tr>th.info,.table>tfoot>tr.info>td,.table>tfoot>tr.info>th,.table>tfoot>tr>td.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>thead>tr.info>th,.table>thead>tr>td.info,.table>thead>tr>th.info{background-color:#d9edf7}.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr.info:hover>th,.table-hover>tbody>tr:hover>.info,.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover{background-color:#c4e3f3}.table>tbody>tr.warning>td,.table>tbody>tr.warning>th,.table>tbody>tr>td.warning,.table>tbody>tr>th.warning,.table>tfoot>tr.warning>td,.table>tfoot>tr.warning>th,.table>tfoot>tr>td.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>thead>tr.warning>th,.table>thead>tr>td.warning,.table>thead>tr>th.warning{background-color:#fcf8e3}.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr.warning:hover>th,.table-hover>tbody>tr:hover>.warning,.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover{background-color:#faf2cc}.table>tbody>tr.danger>td,.table>tbody>tr.danger>th,.table>tbody>tr>td.danger,.table>tbody>tr>th.danger,.table>tfoot>tr.danger>td,.table>tfoot>tr.danger>th,.table>tfoot>tr>td.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>thead>tr.danger>th,.table>thead>tr>td.danger,.table>thead>tr>th.danger{background-color:#f2dede}.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr.danger:hover>th,.table-hover>tbody>tr:hover>.danger,.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover{background-color:#ebcccc}.table-responsive{min-height:.01%;overflow-x:auto}@media screen and (max-width:767px){.table-responsive{width:100%;margin-bottom:15px;overflow-y:hidden;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>td,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>thead>tr>th{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=checkbox],input[type=radio]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=file]:focus,input[type=checkbox]:focus,input[type=radio]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{display:block;padding-top:7px;font-size:14px;line-height:1.42857143;color:#555}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#999;opacity:1}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{background-color:#eee;opacity:1}.form-control[disabled],fieldset[disabled] .form-control{cursor:not-allowed}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}@media screen and (-webkit-min-device-pixel-ratio:0){input[type=date],input[type=time],input[type=datetime-local],input[type=month]{line-height:34px}.input-group-sm input[type=date],.input-group-sm input[type=time],.input-group-sm input[type=datetime-local],.input-group-sm input[type=month],input[type=date].input-sm,input[type=time].input-sm,input[type=datetime-local].input-sm,input[type=month].input-sm{line-height:30px}.input-group-lg input[type=date],.input-group-lg input[type=time],.input-group-lg input[type=datetime-local],.input-group-lg input[type=month],input[type=date].input-lg,input[type=time].input-lg,input[type=datetime-local].input-lg,input[type=month].input-lg{line-height:46px}}.form-group{margin-bottom:15px}.checkbox,.radio{position:relative;display:block;margin-top:10px;margin-bottom:10px}.checkbox label,.radio label{min-height:20px;padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.checkbox input[type=checkbox],.checkbox-inline input[type=checkbox],.radio input[type=radio],.radio-inline input[type=radio]{position:absolute;margin-top:4px \9;margin-left:-20px}.checkbox+.checkbox,.radio+.radio{margin-top:-5px}.checkbox-inline,.radio-inline{position:relative;display:inline-block;padding-left:20px;margin-bottom:0;font-weight:400;vertical-align:middle;cursor:pointer}.checkbox-inline+.checkbox-inline,.radio-inline+.radio-inline{margin-top:0;margin-left:10px}fieldset[disabled] input[type=checkbox],fieldset[disabled] input[type=radio],input[type=checkbox].disabled,input[type=checkbox][disabled],input[type=radio].disabled,input[type=radio][disabled]{cursor:not-allowed}.checkbox-inline.disabled,.radio-inline.disabled,fieldset[disabled] .checkbox-inline,fieldset[disabled] .radio-inline{cursor:not-allowed}.checkbox.disabled label,.radio.disabled label,fieldset[disabled] .checkbox label,fieldset[disabled] .radio label{cursor:not-allowed}.form-control-static{min-height:34px;padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-control-static.input-sm{padding-right:0;padding-left:0}.input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}select[multiple].input-sm,textarea.input-sm{height:auto}.form-group-sm .form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.form-group-sm .form-control{height:30px;line-height:30px}select[multiple].form-group-sm .form-control,textarea.form-group-sm .form-control{height:auto}.form-group-sm .form-control-static{height:30px;min-height:32px;padding:5px 10px;font-size:12px;line-height:1.5}.input-lg{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-lg{height:46px;line-height:46px}select[multiple].input-lg,textarea.input-lg{height:auto}.form-group-lg .form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}select.form-group-lg .form-control{height:46px;line-height:46px}select[multiple].form-group-lg .form-control,textarea.form-group-lg .form-control{height:auto}.form-group-lg .form-control-static{height:46px;min-height:38px;padding:10px 16px;font-size:18px;line-height:1.3333333}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:0;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center;pointer-events:none}.input-lg+.form-control-feedback{width:46px;height:46px;line-height:46px}.input-sm+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .checkbox,.has-success .checkbox-inline,.has-success .control-label,.has-success .help-block,.has-success .radio,.has-success .radio-inline,.has-success.checkbox label,.has-success.checkbox-inline label,.has-success.radio label,.has-success.radio-inline label{color:#3c763d}.has-success .form-control{border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;background-color:#dff0d8;border-color:#3c763d}.has-success .form-control-feedback{color:#3c763d}.has-warning .checkbox,.has-warning .checkbox-inline,.has-warning .control-label,.has-warning .help-block,.has-warning .radio,.has-warning .radio-inline,.has-warning.checkbox label,.has-warning.checkbox-inline label,.has-warning.radio label,.has-warning.radio-inline label{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;background-color:#fcf8e3;border-color:#8a6d3b}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .checkbox,.has-error .checkbox-inline,.has-error .control-label,.has-error .help-block,.has-error .radio,.has-error .radio-inline,.has-error.checkbox label,.has-error.checkbox-inline label,.has-error.radio label,.has-error.radio-inline label{color:#a94442}.has-error .form-control{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;background-color:#f2dede;border-color:#a94442}.has-error .form-control-feedback{color:#a94442}.has-feedback label~.form-control-feedback{top:25px}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-static{display:inline-block}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .form-control,.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .checkbox,.form-inline .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .checkbox label,.form-inline .radio label{padding-left:0}.form-inline .checkbox input[type=checkbox],.form-inline .radio input[type=radio]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .checkbox,.form-horizontal .checkbox-inline,.form-horizontal .radio,.form-horizontal .radio-inline{padding-top:7px;margin-top:0;margin-bottom:0}.form-horizontal .checkbox,.form-horizontal .radio{min-height:27px}.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.form-horizontal .control-label{padding-top:7px;margin-bottom:0;text-align:right}}.form-horizontal .has-feedback .form-control-feedback{right:15px}@media (min-width:768px){.form-horizontal .form-group-lg .control-label{padding-top:14.33px}}@media (min-width:768px){.form-horizontal .form-group-sm .control-label{padding-top:6px}}.btn{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;-ms-touch-action:manipulation;touch-action:manipulation;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-image:none;border:1px solid transparent;border-radius:4px}.btn.active.focus,.btn.active:focus,.btn.focus,.btn:active.focus,.btn:active:focus,.btn:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.focus,.btn:focus,.btn:hover{color:#333;text-decoration:none}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:not-allowed;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none;opacity:.65}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default.active,.btn-default.focus,.btn-default:active,.btn-default:focus,.btn-default:hover,.open>.dropdown-toggle.btn-default{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default.active,.btn-default:active,.open>.dropdown-toggle.btn-default{background-image:none}.btn-default.disabled,.btn-default.disabled.active,.btn-default.disabled.focus,.btn-default.disabled:active,.btn-default.disabled:focus,.btn-default.disabled:hover,.btn-default[disabled],.btn-default[disabled].active,.btn-default[disabled].focus,.btn-default[disabled]:active,.btn-default[disabled]:focus,.btn-default[disabled]:hover,fieldset[disabled] .btn-default,fieldset[disabled] .btn-default.active,fieldset[disabled] .btn-default.focus,fieldset[disabled] .btn-default:active,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:hover{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#337ab7;border-color:#2e6da4}.btn-primary.active,.btn-primary.focus,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.open>.dropdown-toggle.btn-primary{color:#fff;background-color:#286090;border-color:#204d74}.btn-primary.active,.btn-primary:active,.open>.dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled,.btn-primary.disabled.active,.btn-primary.disabled.focus,.btn-primary.disabled:active,.btn-primary.disabled:focus,.btn-primary.disabled:hover,.btn-primary[disabled],.btn-primary[disabled].active,.btn-primary[disabled].focus,.btn-primary[disabled]:active,.btn-primary[disabled]:focus,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary,fieldset[disabled] .btn-primary.active,fieldset[disabled] .btn-primary.focus,fieldset[disabled] .btn-primary:active,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:hover{background-color:#337ab7;border-color:#2e6da4}.btn-primary .badge{color:#337ab7;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success.active,.btn-success.focus,.btn-success:active,.btn-success:focus,.btn-success:hover,.open>.dropdown-toggle.btn-success{color:#fff;background-color:#449d44;border-color:#398439}.btn-success.active,.btn-success:active,.open>.dropdown-toggle.btn-success{background-image:none}.btn-success.disabled,.btn-success.disabled.active,.btn-success.disabled.focus,.btn-success.disabled:active,.btn-success.disabled:focus,.btn-success.disabled:hover,.btn-success[disabled],.btn-success[disabled].active,.btn-success[disabled].focus,.btn-success[disabled]:active,.btn-success[disabled]:focus,.btn-success[disabled]:hover,fieldset[disabled] .btn-success,fieldset[disabled] .btn-success.active,fieldset[disabled] .btn-success.focus,fieldset[disabled] .btn-success:active,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:hover{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info.active,.btn-info.focus,.btn-info:active,.btn-info:focus,.btn-info:hover,.open>.dropdown-toggle.btn-info{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info.active,.btn-info:active,.open>.dropdown-toggle.btn-info{background-image:none}.btn-info.disabled,.btn-info.disabled.active,.btn-info.disabled.focus,.btn-info.disabled:active,.btn-info.disabled:focus,.btn-info.disabled:hover,.btn-info[disabled],.btn-info[disabled].active,.btn-info[disabled].focus,.btn-info[disabled]:active,.btn-info[disabled]:focus,.btn-info[disabled]:hover,fieldset[disabled] .btn-info,fieldset[disabled] .btn-info.active,fieldset[disabled] .btn-info.focus,fieldset[disabled] .btn-info:active,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:hover{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning.active,.btn-warning.focus,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.open>.dropdown-toggle.btn-warning{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning.active,.btn-warning:active,.open>.dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled,.btn-warning.disabled.active,.btn-warning.disabled.focus,.btn-warning.disabled:active,.btn-warning.disabled:focus,.btn-warning.disabled:hover,.btn-warning[disabled],.btn-warning[disabled].active,.btn-warning[disabled].focus,.btn-warning[disabled]:active,.btn-warning[disabled]:focus,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning,fieldset[disabled] .btn-warning.active,fieldset[disabled] .btn-warning.focus,fieldset[disabled] .btn-warning:active,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:hover{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger.active,.btn-danger.focus,.btn-danger:active,.btn-danger:focus,.btn-danger:hover,.open>.dropdown-toggle.btn-danger{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger.active,.btn-danger:active,.open>.dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled,.btn-danger.disabled.active,.btn-danger.disabled.focus,.btn-danger.disabled:active,.btn-danger.disabled:focus,.btn-danger.disabled:hover,.btn-danger[disabled],.btn-danger[disabled].active,.btn-danger[disabled].focus,.btn-danger[disabled]:active,.btn-danger[disabled]:focus,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger,fieldset[disabled] .btn-danger.active,fieldset[disabled] .btn-danger.focus,fieldset[disabled] .btn-danger:active,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:hover{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{font-weight:400;color:#337ab7;border-radius:0}.btn-link,.btn-link.active,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:active,.btn-link:focus,.btn-link:hover{border-color:transparent}.btn-link:focus,.btn-link:hover{color:#23527c;text-decoration:underline;background-color:transparent}.btn-link[disabled]:focus,.btn-link[disabled]:hover,fieldset[disabled] .btn-link:focus,fieldset[disabled] .btn-link:hover{color:#777;text-decoration:none}.btn-group-lg>.btn,.btn-lg{padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}.btn-group-sm>.btn,.btn-sm{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-xs>.btn,.btn-xs{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition-timing-function:ease;-o-transition-timing-function:ease;transition-timing-function:ease;-webkit-transition-duration:.35s;-o-transition-duration:.35s;transition-duration:.35s;-webkit-transition-property:height,visibility;-o-transition-property:height,visibility;transition-property:height,visibility}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px dashed;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown,.dropup{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;text-align:left;list-style:none;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175)}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:focus,.dropdown-menu>li>a:hover{color:#262626;text-decoration:none;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:focus,.dropdown-menu>.active>a:hover{color:#fff;text-decoration:none;background-color:#337ab7;outline:0}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{color:#777}.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{right:0;left:auto}.dropdown-menu-left{right:auto;left:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.42857143;color:#777;white-space:nowrap}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{content:"";border-top:0;border-bottom:4px solid}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:2px}@media (min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}.navbar-right .dropdown-menu-left{right:auto;left:0}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;float:left}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group-vertical>.btn:hover,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus,.btn-group>.btn:hover{z-index:2}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-bottom-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-left-radius:0;border-top-right-radius:0;border-bottom-left-radius:4px}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-top-right-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{display:table-cell;float:none;width:1%}.btn-group-justified>.btn-group .btn{width:100%}.btn-group-justified>.btn-group .dropdown-menu{left:auto}[data-toggle=buttons]>.btn input[type=checkbox],[data-toggle=buttons]>.btn input[type=radio],[data-toggle=buttons]>.btn-group>.btn input[type=checkbox],[data-toggle=buttons]>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-right:0;padding-left:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:46px;line-height:46px}select[multiple].input-group-lg>.form-control,select[multiple].input-group-lg>.input-group-addon,select[multiple].input-group-lg>.input-group-btn>.btn,textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}select[multiple].input-group-sm>.form-control,select[multiple].input-group-sm>.input-group-addon,select[multiple].input-group-sm>.input-group-btn>.btn,textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn{height:auto}.input-group .form-control,.input-group-addon,.input-group-btn{display:table-cell}.input-group .form-control:not(:first-child):not(:last-child),.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type=checkbox],.input-group-addon input[type=radio]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn-group:not(:last-child)>.btn,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:first-child>.btn-group:not(:first-child)>.btn,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;font-size:0;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:active,.input-group-btn>.btn:focus,.input-group-btn>.btn:hover{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{margin-left:-1px}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:focus,.nav>li>a:hover{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#777}.nav>li.disabled>a:focus,.nav>li.disabled>a:hover{color:#777;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav .open>a,.nav .open>a:focus,.nav .open>a:hover{background-color:#eee;border-color:#337ab7}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.42857143;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:focus,.nav-tabs>li.active>a:hover{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:focus,.nav-pills>li.active>a:hover{color:#fff;background-color:#337ab7}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}@media (min-width:768px){.navbar{border-radius:4px}}@media (min-width:768px){.navbar-header{float:left}}.navbar-collapse{padding-right:15px;padding-left:15px;overflow-x:visible;-webkit-overflow-scrolling:touch;border-top:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1)}.navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.navbar-collapse{width:auto;border-top:0;-webkit-box-shadow:none;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse{padding-right:0;padding-left:0}}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:340px}@media (max-device-width:480px)and (orientation:landscape){.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:200px}}.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-bottom,.navbar-fixed-top{position:fixed;right:0;left:0;z-index:1030}@media (min-width:768px){.navbar-fixed-bottom,.navbar-fixed-top{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;height:50px;padding:15px 15px;font-size:18px;line-height:20px}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-brand>img{display:block}@media (min-width:768px){.navbar>.container .navbar-brand,.navbar>.container-fluid .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;-webkit-box-shadow:none;box-shadow:none}.navbar-nav .open .dropdown-menu .dropdown-header,.navbar-nav .open .dropdown-menu>li>a{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:focus,.navbar-nav .open .dropdown-menu>li>a:hover{background-image:none}}@media (min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}}.navbar-form{padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .form-control-static{display:inline-block}.navbar-form .input-group{display:inline-table;vertical-align:middle}.navbar-form .input-group .form-control,.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn{width:auto}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .checkbox,.navbar-form .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.navbar-form .checkbox label,.navbar-form .radio label{padding-left:0}.navbar-form .checkbox input[type=checkbox],.navbar-form .radio input[type=radio]{position:relative;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.navbar-form .form-group{margin-bottom:5px}.navbar-form .form-group:last-child{margin-bottom:0}}@media (min-width:768px){.navbar-form{width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-left-radius:0;border-top-right-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{margin-bottom:0;border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.navbar-text{float:left;margin-right:15px;margin-left:15px}}@media (min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important;margin-right:-15px}.navbar-right~.navbar-right{margin-right:0}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:focus,.navbar-default .navbar-brand:hover{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:focus,.navbar-default .navbar-nav>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:focus,.navbar-default .navbar-nav>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:focus,.navbar-default .navbar-nav>.disabled>a:hover{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:focus,.navbar-default .navbar-toggle:hover{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e7e7e7}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:focus,.navbar-default .navbar-nav>.open>a:hover{color:#555;background-color:#e7e7e7}@media (max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-default .btn-link{color:#777}.navbar-default .btn-link:focus,.navbar-default .btn-link:hover{color:#333}.navbar-default .btn-link[disabled]:focus,.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:focus,fieldset[disabled] .navbar-default .btn-link:hover{color:#ccc}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#9d9d9d}.navbar-inverse .navbar-brand:focus,.navbar-inverse .navbar-brand:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a:focus,.navbar-inverse .navbar-nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:focus,.navbar-inverse .navbar-nav>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:focus,.navbar-inverse .navbar-nav>.disabled>a:hover{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:focus,.navbar-inverse .navbar-toggle:hover{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:focus,.navbar-inverse .navbar-nav>.open>a:hover{color:#fff;background-color:#080808}@media (max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#9d9d9d}.navbar-inverse .navbar-link:hover{color:#fff}.navbar-inverse .btn-link{color:#9d9d9d}.navbar-inverse .btn-link:focus,.navbar-inverse .btn-link:hover{color:#fff}.navbar-inverse .btn-link[disabled]:focus,.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:focus,fieldset[disabled] .navbar-inverse .btn-link:hover{color:#444}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#777}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;margin-left:-1px;line-height:1.42857143;color:#337ab7;text-decoration:none;background-color:#fff;border:1px solid #ddd}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-top-left-radius:4px;border-bottom-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:focus,.pagination>li>a:hover,.pagination>li>span:focus,.pagination>li>span:hover{color:#23527c;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>a:focus,.pagination>.active>a:hover,.pagination>.active>span,.pagination>.active>span:focus,.pagination>.active>span:hover{z-index:2;color:#fff;cursor:default;background-color:#337ab7;border-color:#337ab7}.pagination>.disabled>a,.pagination>.disabled>a:focus,.pagination>.disabled>a:hover,.pagination>.disabled>span,.pagination>.disabled>span:focus,.pagination>.disabled>span:hover{color:#777;cursor:not-allowed;background-color:#fff;border-color:#ddd}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-top-left-radius:6px;border-bottom-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-top-left-radius:3px;border-bottom-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:focus,.pager li>a:hover{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:focus,.pager .disabled>a:hover,.pager .disabled>span{color:#777;cursor:not-allowed;background-color:#fff}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}a.label:focus,a.label:hover{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#777}.label-default[href]:focus,.label-default[href]:hover{background-color:#5e5e5e}.label-primary{background-color:#337ab7}.label-primary[href]:focus,.label-primary[href]:hover{background-color:#286090}.label-success{background-color:#5cb85c}.label-success[href]:focus,.label-success[href]:hover{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:focus,.label-info[href]:hover{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:focus,.label-warning[href]:hover{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:focus,.label-danger[href]:hover{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;background-color:#777;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-group-xs>.btn .badge,.btn-xs .badge{top:0;padding:1px 5px}a.badge:focus,a.badge:hover{color:#fff;text-decoration:none;cursor:pointer}.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#337ab7;background-color:#fff}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding:30px 15px;margin-bottom:30px;color:inherit;background-color:#eee}.jumbotron .h1,.jumbotron h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.jumbotron>hr{border-top-color:#d5d5d5}.container .jumbotron,.container-fluid .jumbotron{border-radius:6px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding:48px 0}.container .jumbotron,.container-fluid .jumbotron{padding-right:60px;padding-left:60px}.jumbotron .h1,.jumbotron h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:border .2s ease-in-out;-o-transition:border .2s ease-in-out;transition:border .2s ease-in-out}.thumbnail a>img,.thumbnail>img{margin-right:auto;margin-left:auto}a.thumbnail.active,a.thumbnail:focus,a.thumbnail:hover{border-color:#337ab7}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable,.alert-dismissible{padding-right:35px}.alert-dismissable .close,.alert-dismissible .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#2b542c}.alert-info{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#245269}.alert-warning{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.alert-warning hr{border-top-color:#f7e1b5}.alert-warning .alert-link{color:#66512c}.alert-danger{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.alert-danger hr{border-top-color:#e4b9c0}.alert-danger .alert-link{color:#843534}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#337ab7;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress-bar-striped,.progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;background-size:40px 40px}.progress-bar.active,.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.media{margin-top:15px}.media:first-child{margin-top:0}.media,.media-body{overflow:hidden;zoom:1}.media-body{width:10000px}.media-object{display:block}.media-right,.media>.pull-right{padding-left:10px}.media-left,.media>.pull-left{padding-right:10px}.media-body,.media-left,.media-right{display:table-cell;vertical-align:top}.media-middle{vertical-align:middle}.media-bottom{vertical-align:bottom}.media-heading{margin-top:0;margin-bottom:5px}.media-list{padding-left:0;list-style:none}.list-group{padding-left:0;margin-bottom:20px}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-left-radius:4px;border-top-right-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}a.list-group-item{color:#555}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item:focus,a.list-group-item:hover{color:#555;text-decoration:none;background-color:#f5f5f5}.list-group-item.disabled,.list-group-item.disabled:focus,.list-group-item.disabled:hover{color:#777;cursor:not-allowed;background-color:#eee}.list-group-item.disabled .list-group-item-heading,.list-group-item.disabled:focus .list-group-item-heading,.list-group-item.disabled:hover .list-group-item-heading{color:inherit}.list-group-item.disabled .list-group-item-text,.list-group-item.disabled:focus .list-group-item-text,.list-group-item.disabled:hover .list-group-item-text{color:#777}.list-group-item.active,.list-group-item.active:focus,.list-group-item.active:hover{z-index:2;color:#fff;background-color:#337ab7;border-color:#337ab7}.list-group-item.active .list-group-item-heading,.list-group-item.active .list-group-item-heading>.small,.list-group-item.active .list-group-item-heading>small,.list-group-item.active:focus .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading>.small,.list-group-item.active:focus .list-group-item-heading>small,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading>.small,.list-group-item.active:hover .list-group-item-heading>small{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:focus .list-group-item-text,.list-group-item.active:hover .list-group-item-text{color:#c7ddef}.list-group-item-success{color:#3c763d;background-color:#dff0d8}a.list-group-item-success{color:#3c763d}a.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:focus,a.list-group-item-success:hover{color:#3c763d;background-color:#d0e9c6}a.list-group-item-success.active,a.list-group-item-success.active:focus,a.list-group-item-success.active:hover{color:#fff;background-color:#3c763d;border-color:#3c763d}.list-group-item-info{color:#31708f;background-color:#d9edf7}a.list-group-item-info{color:#31708f}a.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:focus,a.list-group-item-info:hover{color:#31708f;background-color:#c4e3f3}a.list-group-item-info.active,a.list-group-item-info.active:focus,a.list-group-item-info.active:hover{color:#fff;background-color:#31708f;border-color:#31708f}.list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}a.list-group-item-warning{color:#8a6d3b}a.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:focus,a.list-group-item-warning:hover{color:#8a6d3b;background-color:#faf2cc}a.list-group-item-warning.active,a.list-group-item-warning.active:focus,a.list-group-item-warning.active:hover{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.list-group-item-danger{color:#a94442;background-color:#f2dede}a.list-group-item-danger{color:#a94442}a.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:focus,a.list-group-item-danger:hover{color:#a94442;background-color:#ebcccc}a.list-group-item-danger.active,a.list-group-item-danger.active:focus,a.list-group-item-danger.active:hover{color:#fff;background-color:#a94442;border-color:#a94442}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-left-radius:3px;border-top-right-radius:3px}.panel-heading>.dropdown .dropdown-toggle{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.panel-title>.small,.panel-title>.small>a,.panel-title>a,.panel-title>small,.panel-title>small>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.list-group,.panel>.panel-collapse>.list-group{margin-bottom:0}.panel>.list-group .list-group-item,.panel>.panel-collapse>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child,.panel>.panel-collapse>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-left-radius:3px;border-top-right-radius:3px}.panel>.list-group:last-child .list-group-item:last-child,.panel>.panel-collapse>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.list-group+.panel-footer{border-top-width:0}.panel>.panel-collapse>.table,.panel>.table,.panel>.table-responsive>.table{margin-bottom:0}.panel>.panel-collapse>.table caption,.panel>.table caption,.panel>.table-responsive>.table caption{padding-right:15px;padding-left:15px}.panel>.table-responsive:first-child>.table:first-child,.panel>.table:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child,.panel>.table:first-child>thead:first-child>tr:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.panel>.table-responsive:last-child>.table:last-child,.panel>.table:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive,.panel>.table+.panel-body,.panel>.table-responsive+.panel-body{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child td,.panel>.table>tbody:first-child>tr:first-child th{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th{border-bottom:0}.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}.panel>.table-responsive{margin-bottom:0;border:0}.panel-group{margin-bottom:20px}.panel-group .panel{margin-bottom:0;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse>.list-group,.panel-group .panel-heading+.panel-collapse>.panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ddd}.panel-default>.panel-heading .badge{color:#f5f5f5;background-color:#333}.panel-default>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#337ab7}.panel-primary>.panel-heading{color:#fff;background-color:#337ab7;border-color:#337ab7}.panel-primary>.panel-heading+.panel-collapse>.panel-body{border-top-color:#337ab7}.panel-primary>.panel-heading .badge{color:#337ab7;background-color:#fff}.panel-primary>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#337ab7}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d6e9c6}.panel-success>.panel-heading .badge{color:#dff0d8;background-color:#3c763d}.panel-success>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d6e9c6}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse>.panel-body{border-top-color:#bce8f1}.panel-info>.panel-heading .badge{color:#d9edf7;background-color:#31708f}.panel-info>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#bce8f1}.panel-warning{border-color:#faebcc}.panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.panel-warning>.panel-heading+.panel-collapse>.panel-body{border-top-color:#faebcc}.panel-warning>.panel-heading .badge{color:#fcf8e3;background-color:#8a6d3b}.panel-warning>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#faebcc}.panel-danger{border-color:#ebccd1}.panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.panel-danger>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ebccd1}.panel-danger>.panel-heading .badge{color:#f2dede;background-color:#a94442}.panel-danger>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ebccd1}.embed-responsive{position:relative;display:block;height:0;padding:0;overflow:hidden}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive-16by9{padding-bottom:56.25%}.embed-responsive-4by3{padding-bottom:75%}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;filter:alpha(opacity=20);opacity:.2}.close:focus,.close:hover{color:#000;text-decoration:none;cursor:pointer;filter:alpha(opacity=50);opacity:.5}button.close{-webkit-appearance:none;padding:0;cursor:pointer;background:0 0;border:0}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;display:none;overflow:hidden;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transition:-webkit-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out;-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);-o-transform:translate(0,-25%);transform:translate(0,-25%)}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);-o-transform:translate(0,0);transform:translate(0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5)}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{filter:alpha(opacity=0);opacity:0}.modal-backdrop.in{filter:alpha(opacity=50);opacity:.5}.modal-header{min-height:16.43px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.42857143}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1070;display:block;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:12px;font-weight:400;line-height:1.4;filter:alpha(opacity=0);opacity:0}.tooltip.in{filter:alpha(opacity=90);opacity:.9}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{right:5px;bottom:0;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{bottom:0;left:5px;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;right:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;left:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1060;display:none;max-width:276px;padding:1px;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;font-weight:400;line-height:1.42857143;text-align:left;white-space:normal;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2)}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{content:"";border-width:10px}.popover.top>.arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,.25);border-bottom-width:0}.popover.top>.arrow:after{bottom:1px;margin-left:-10px;content:" ";border-top-color:#fff;border-bottom-width:0}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,.25);border-left-width:0}.popover.right>.arrow:after{bottom:-10px;left:1px;content:" ";border-right-color:#fff;border-left-width:0}.popover.bottom>.arrow{top:-11px;left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25)}.popover.bottom>.arrow:after{top:1px;margin-left:-10px;content:" ";border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{right:1px;bottom:-10px;content:" ";border-right-width:0;border-left-color:#fff}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>a>img,.carousel-inner>.item>img{line-height:1}@media all and (transform-3d),(-webkit-transform-3d){.carousel-inner>.item{-webkit-transition:-webkit-transform .6s ease-in-out;-o-transition:-o-transform .6s ease-in-out;transition:transform .6s ease-in-out;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-perspective:1000;perspective:1000}.carousel-inner>.item.active.right,.carousel-inner>.item.next{left:0;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.carousel-inner>.item.active.left,.carousel-inner>.item.prev{left:0;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.carousel-inner>.item.active,.carousel-inner>.item.next.left,.carousel-inner>.item.prev.right{left:0;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6);filter:alpha(opacity=50);opacity:.5}.carousel-control.left{background-image:-webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.5)),to(rgba(0,0,0,.0001)));background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);background-repeat:repeat-x}.carousel-control.right{right:0;left:auto;background-image:-webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.0001)),to(rgba(0,0,0,.5)));background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);background-repeat:repeat-x}.carousel-control:focus,.carousel-control:hover{color:#fff;text-decoration:none;filter:alpha(opacity=90);outline:0;opacity:.9}.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{position:absolute;top:50%;z-index:5;display:inline-block}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{left:50%;margin-left:-10px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{right:50%;margin-right:-10px}.carousel-control .icon-next,.carousel-control .icon-prev{width:20px;height:20px;margin-top:-10px;font-family:serif;line-height:1}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;padding-left:0;margin-left:-30%;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;background-color:#000 \9;background-color:rgba(0,0,0,0);border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{width:30px;height:30px;margin-top:-15px;font-size:30px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{margin-left:-15px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{margin-right:-15px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.btn-group-vertical>.btn-group:after,.btn-group-vertical>.btn-group:before,.btn-toolbar:after,.btn-toolbar:before,.clearfix:after,.clearfix:before,.container-fluid:after,.container-fluid:before,.container:after,.container:before,.dl-horizontal dd:after,.dl-horizontal dd:before,.form-horizontal .form-group:after,.form-horizontal .form-group:before,.modal-footer:after,.modal-footer:before,.nav:after,.nav:before,.navbar-collapse:after,.navbar-collapse:before,.navbar-header:after,.navbar-header:before,.navbar:after,.navbar:before,.pager:after,.pager:before,.panel-body:after,.panel-body:before,.row:after,.row:before{display:table;content:" "}.btn-group-vertical>.btn-group:after,.btn-toolbar:after,.clearfix:after,.container-fluid:after,.container:after,.dl-horizontal dd:after,.form-horizontal .form-group:after,.modal-footer:after,.nav:after,.navbar-collapse:after,.navbar-header:after,.navbar:after,.pager:after,.panel-body:after,.row:after{clear:both}.center-block{display:block;margin-right:auto;margin-left:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important}.affix{position:fixed}@-ms-viewport{width:device-width}.visible-lg,.visible-md,.visible-sm,.visible-xs{display:none!important}.visible-lg-block,.visible-lg-inline,.visible-lg-inline-block,.visible-md-block,.visible-md-inline,.visible-md-inline-block,.visible-sm-block,.visible-sm-inline,.visible-sm-inline-block,.visible-xs-block,.visible-xs-inline,.visible-xs-inline-block{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table}tr.visible-xs{display:table-row!important}td.visible-xs,th.visible-xs{display:table-cell!important}}@media (max-width:767px){.visible-xs-block{display:block!important}}@media (max-width:767px){.visible-xs-inline{display:inline!important}}@media (max-width:767px){.visible-xs-inline-block{display:inline-block!important}}@media (min-width:768px)and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table}tr.visible-sm{display:table-row!important}td.visible-sm,th.visible-sm{display:table-cell!important}}@media (min-width:768px)and (max-width:991px){.visible-sm-block{display:block!important}}@media (min-width:768px)and (max-width:991px){.visible-sm-inline{display:inline!important}}@media (min-width:768px)and (max-width:991px){.visible-sm-inline-block{display:inline-block!important}}@media (min-width:992px)and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table}tr.visible-md{display:table-row!important}td.visible-md,th.visible-md{display:table-cell!important}}@media (min-width:992px)and (max-width:1199px){.visible-md-block{display:block!important}}@media (min-width:992px)and (max-width:1199px){.visible-md-inline{display:inline!important}}@media (min-width:992px)and (max-width:1199px){.visible-md-inline-block{display:inline-block!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table}tr.visible-lg{display:table-row!important}td.visible-lg,th.visible-lg{display:table-cell!important}}@media (min-width:1200px){.visible-lg-block{display:block!important}}@media (min-width:1200px){.visible-lg-inline{display:inline!important}}@media (min-width:1200px){.visible-lg-inline-block{display:inline-block!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px)and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px)and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table}tr.visible-print{display:table-row!important}td.visible-print,th.visible-print{display:table-cell!important}}.visible-print-block{display:none!important}@media print{.visible-print-block{display:block!important}}.visible-print-inline{display:none!important}@media print{.visible-print-inline{display:inline!important}}.visible-print-inline-block{display:none!important}@media print{.visible-print-inline-block{display:inline-block!important}}@media print{.hidden-print{display:none!important}}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.eot b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.eot
new file mode 100644
index 0000000..b93a495
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.eot
Binary files differ
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.svg b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.svg
new file mode 100644
index 0000000..94fb549
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.svg
@@ -0,0 +1,288 @@
+<?xml version="1.0" standalone="no"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
+<svg xmlns="http://www.w3.org/2000/svg">
+<metadata></metadata>
+<defs>
+<font id="glyphicons_halflingsregular" horiz-adv-x="1200" >
+<font-face units-per-em="1200" ascent="960" descent="-240" />
+<missing-glyph horiz-adv-x="500" />
+<glyph horiz-adv-x="0" />
+<glyph horiz-adv-x="400" />
+<glyph unicode=" " />
+<glyph unicode="*" d="M600 1100q15 0 34 -1.5t30 -3.5l11 -1q10 -2 17.5 -10.5t7.5 -18.5v-224l158 158q7 7 18 8t19 -6l106 -106q7 -8 6 -19t-8 -18l-158 -158h224q10 0 18.5 -7.5t10.5 -17.5q6 -41 6 -75q0 -15 -1.5 -34t-3.5 -30l-1 -11q-2 -10 -10.5 -17.5t-18.5 -7.5h-224l158 -158 q7 -7 8 -18t-6 -19l-106 -106q-8 -7 -19 -6t-18 8l-158 158v-224q0 -10 -7.5 -18.5t-17.5 -10.5q-41 -6 -75 -6q-15 0 -34 1.5t-30 3.5l-11 1q-10 2 -17.5 10.5t-7.5 18.5v224l-158 -158q-7 -7 -18 -8t-19 6l-106 106q-7 8 -6 19t8 18l158 158h-224q-10 0 -18.5 7.5 t-10.5 17.5q-6 41 -6 75q0 15 1.5 34t3.5 30l1 11q2 10 10.5 17.5t18.5 7.5h224l-158 158q-7 7 -8 18t6 19l106 106q8 7 19 6t18 -8l158 -158v224q0 10 7.5 18.5t17.5 10.5q41 6 75 6z" />
+<glyph unicode="+" d="M450 1100h200q21 0 35.5 -14.5t14.5 -35.5v-350h350q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-350v-350q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v350h-350q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5 h350v350q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode=" " />
+<glyph unicode="¥" d="M825 1100h250q10 0 12.5 -5t-5.5 -13l-364 -364q-6 -6 -11 -18h268q10 0 13 -6t-3 -14l-120 -160q-6 -8 -18 -14t-22 -6h-125v-100h275q10 0 13 -6t-3 -14l-120 -160q-6 -8 -18 -14t-22 -6h-125v-174q0 -11 -7.5 -18.5t-18.5 -7.5h-148q-11 0 -18.5 7.5t-7.5 18.5v174 h-275q-10 0 -13 6t3 14l120 160q6 8 18 14t22 6h125v100h-275q-10 0 -13 6t3 14l120 160q6 8 18 14t22 6h118q-5 12 -11 18l-364 364q-8 8 -5.5 13t12.5 5h250q25 0 43 -18l164 -164q8 -8 18 -8t18 8l164 164q18 18 43 18z" />
+<glyph unicode=" " horiz-adv-x="650" />
+<glyph unicode=" " horiz-adv-x="1300" />
+<glyph unicode=" " horiz-adv-x="650" />
+<glyph unicode=" " horiz-adv-x="1300" />
+<glyph unicode=" " horiz-adv-x="433" />
+<glyph unicode=" " horiz-adv-x="325" />
+<glyph unicode=" " horiz-adv-x="216" />
+<glyph unicode=" " horiz-adv-x="216" />
+<glyph unicode=" " horiz-adv-x="162" />
+<glyph unicode=" " horiz-adv-x="260" />
+<glyph unicode=" " horiz-adv-x="72" />
+<glyph unicode=" " horiz-adv-x="260" />
+<glyph unicode=" " horiz-adv-x="325" />
+<glyph unicode="€" d="M744 1198q242 0 354 -189q60 -104 66 -209h-181q0 45 -17.5 82.5t-43.5 61.5t-58 40.5t-60.5 24t-51.5 7.5q-19 0 -40.5 -5.5t-49.5 -20.5t-53 -38t-49 -62.5t-39 -89.5h379l-100 -100h-300q-6 -50 -6 -100h406l-100 -100h-300q9 -74 33 -132t52.5 -91t61.5 -54.5t59 -29 t47 -7.5q22 0 50.5 7.5t60.5 24.5t58 41t43.5 61t17.5 80h174q-30 -171 -128 -278q-107 -117 -274 -117q-206 0 -324 158q-36 48 -69 133t-45 204h-217l100 100h112q1 47 6 100h-218l100 100h134q20 87 51 153.5t62 103.5q117 141 297 141z" />
+<glyph unicode="₽" d="M428 1200h350q67 0 120 -13t86 -31t57 -49.5t35 -56.5t17 -64.5t6.5 -60.5t0.5 -57v-16.5v-16.5q0 -36 -0.5 -57t-6.5 -61t-17 -65t-35 -57t-57 -50.5t-86 -31.5t-120 -13h-178l-2 -100h288q10 0 13 -6t-3 -14l-120 -160q-6 -8 -18 -14t-22 -6h-138v-175q0 -11 -5.5 -18 t-15.5 -7h-149q-10 0 -17.5 7.5t-7.5 17.5v175h-267q-10 0 -13 6t3 14l120 160q6 8 18 14t22 6h117v100h-267q-10 0 -13 6t3 14l120 160q6 8 18 14t22 6h117v475q0 10 7.5 17.5t17.5 7.5zM600 1000v-300h203q64 0 86.5 33t22.5 119q0 84 -22.5 116t-86.5 32h-203z" />
+<glyph unicode="−" d="M250 700h800q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-800q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="⌛" d="M1000 1200v-150q0 -21 -14.5 -35.5t-35.5 -14.5h-50v-100q0 -91 -49.5 -165.5t-130.5 -109.5q81 -35 130.5 -109.5t49.5 -165.5v-150h50q21 0 35.5 -14.5t14.5 -35.5v-150h-800v150q0 21 14.5 35.5t35.5 14.5h50v150q0 91 49.5 165.5t130.5 109.5q-81 35 -130.5 109.5 t-49.5 165.5v100h-50q-21 0 -35.5 14.5t-14.5 35.5v150h800zM400 1000v-100q0 -60 32.5 -109.5t87.5 -73.5q28 -12 44 -37t16 -55t-16 -55t-44 -37q-55 -24 -87.5 -73.5t-32.5 -109.5v-150h400v150q0 60 -32.5 109.5t-87.5 73.5q-28 12 -44 37t-16 55t16 55t44 37 q55 24 87.5 73.5t32.5 109.5v100h-400z" />
+<glyph unicode="◼" horiz-adv-x="500" d="M0 0z" />
+<glyph unicode="☁" d="M503 1089q110 0 200.5 -59.5t134.5 -156.5q44 14 90 14q120 0 205 -86.5t85 -206.5q0 -121 -85 -207.5t-205 -86.5h-750q-79 0 -135.5 57t-56.5 137q0 69 42.5 122.5t108.5 67.5q-2 12 -2 37q0 153 108 260.5t260 107.5z" />
+<glyph unicode="⛺" d="M774 1193.5q16 -9.5 20.5 -27t-5.5 -33.5l-136 -187l467 -746h30q20 0 35 -18.5t15 -39.5v-42h-1200v42q0 21 15 39.5t35 18.5h30l468 746l-135 183q-10 16 -5.5 34t20.5 28t34 5.5t28 -20.5l111 -148l112 150q9 16 27 20.5t34 -5zM600 200h377l-182 112l-195 534v-646z " />
+<glyph unicode="✉" d="M25 1100h1150q10 0 12.5 -5t-5.5 -13l-564 -567q-8 -8 -18 -8t-18 8l-564 567q-8 8 -5.5 13t12.5 5zM18 882l264 -264q8 -8 8 -18t-8 -18l-264 -264q-8 -8 -13 -5.5t-5 12.5v550q0 10 5 12.5t13 -5.5zM918 618l264 264q8 8 13 5.5t5 -12.5v-550q0 -10 -5 -12.5t-13 5.5 l-264 264q-8 8 -8 18t8 18zM818 482l364 -364q8 -8 5.5 -13t-12.5 -5h-1150q-10 0 -12.5 5t5.5 13l364 364q8 8 18 8t18 -8l164 -164q8 -8 18 -8t18 8l164 164q8 8 18 8t18 -8z" />
+<glyph unicode="✏" d="M1011 1210q19 0 33 -13l153 -153q13 -14 13 -33t-13 -33l-99 -92l-214 214l95 96q13 14 32 14zM1013 800l-615 -614l-214 214l614 614zM317 96l-333 -112l110 335z" />
+<glyph unicode="" d="M700 650v-550h250q21 0 35.5 -14.5t14.5 -35.5v-50h-800v50q0 21 14.5 35.5t35.5 14.5h250v550l-500 550h1200z" />
+<glyph unicode="" d="M368 1017l645 163q39 15 63 0t24 -49v-831q0 -55 -41.5 -95.5t-111.5 -63.5q-79 -25 -147 -4.5t-86 75t25.5 111.5t122.5 82q72 24 138 8v521l-600 -155v-606q0 -42 -44 -90t-109 -69q-79 -26 -147 -5.5t-86 75.5t25.5 111.5t122.5 82.5q72 24 138 7v639q0 38 14.5 59 t53.5 34z" />
+<glyph unicode="" d="M500 1191q100 0 191 -39t156.5 -104.5t104.5 -156.5t39 -191l-1 -2l1 -5q0 -141 -78 -262l275 -274q23 -26 22.5 -44.5t-22.5 -42.5l-59 -58q-26 -20 -46.5 -20t-39.5 20l-275 274q-119 -77 -261 -77l-5 1l-2 -1q-100 0 -191 39t-156.5 104.5t-104.5 156.5t-39 191 t39 191t104.5 156.5t156.5 104.5t191 39zM500 1022q-88 0 -162 -43t-117 -117t-43 -162t43 -162t117 -117t162 -43t162 43t117 117t43 162t-43 162t-117 117t-162 43z" />
+<glyph unicode="" d="M649 949q48 68 109.5 104t121.5 38.5t118.5 -20t102.5 -64t71 -100.5t27 -123q0 -57 -33.5 -117.5t-94 -124.5t-126.5 -127.5t-150 -152.5t-146 -174q-62 85 -145.5 174t-150 152.5t-126.5 127.5t-93.5 124.5t-33.5 117.5q0 64 28 123t73 100.5t104 64t119 20 t120.5 -38.5t104.5 -104z" />
+<glyph unicode="" d="M407 800l131 353q7 19 17.5 19t17.5 -19l129 -353h421q21 0 24 -8.5t-14 -20.5l-342 -249l130 -401q7 -20 -0.5 -25.5t-24.5 6.5l-343 246l-342 -247q-17 -12 -24.5 -6.5t-0.5 25.5l130 400l-347 251q-17 12 -14 20.5t23 8.5h429z" />
+<glyph unicode="" d="M407 800l131 353q7 19 17.5 19t17.5 -19l129 -353h421q21 0 24 -8.5t-14 -20.5l-342 -249l130 -401q7 -20 -0.5 -25.5t-24.5 6.5l-343 246l-342 -247q-17 -12 -24.5 -6.5t-0.5 25.5l130 400l-347 251q-17 12 -14 20.5t23 8.5h429zM477 700h-240l197 -142l-74 -226 l193 139l195 -140l-74 229l192 140h-234l-78 211z" />
+<glyph unicode="" d="M600 1200q124 0 212 -88t88 -212v-250q0 -46 -31 -98t-69 -52v-75q0 -10 6 -21.5t15 -17.5l358 -230q9 -5 15 -16.5t6 -21.5v-93q0 -10 -7.5 -17.5t-17.5 -7.5h-1150q-10 0 -17.5 7.5t-7.5 17.5v93q0 10 6 21.5t15 16.5l358 230q9 6 15 17.5t6 21.5v75q-38 0 -69 52 t-31 98v250q0 124 88 212t212 88z" />
+<glyph unicode="" d="M25 1100h1150q10 0 17.5 -7.5t7.5 -17.5v-1050q0 -10 -7.5 -17.5t-17.5 -7.5h-1150q-10 0 -17.5 7.5t-7.5 17.5v1050q0 10 7.5 17.5t17.5 7.5zM100 1000v-100h100v100h-100zM875 1000h-550q-10 0 -17.5 -7.5t-7.5 -17.5v-350q0 -10 7.5 -17.5t17.5 -7.5h550 q10 0 17.5 7.5t7.5 17.5v350q0 10 -7.5 17.5t-17.5 7.5zM1000 1000v-100h100v100h-100zM100 800v-100h100v100h-100zM1000 800v-100h100v100h-100zM100 600v-100h100v100h-100zM1000 600v-100h100v100h-100zM875 500h-550q-10 0 -17.5 -7.5t-7.5 -17.5v-350q0 -10 7.5 -17.5 t17.5 -7.5h550q10 0 17.5 7.5t7.5 17.5v350q0 10 -7.5 17.5t-17.5 7.5zM100 400v-100h100v100h-100zM1000 400v-100h100v100h-100zM100 200v-100h100v100h-100zM1000 200v-100h100v100h-100z" />
+<glyph unicode="" d="M50 1100h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5zM650 1100h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5v400 q0 21 14.5 35.5t35.5 14.5zM50 500h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5zM650 500h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400 q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M50 1100h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5zM450 1100h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200 q0 21 14.5 35.5t35.5 14.5zM850 1100h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5zM50 700h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200 q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5zM450 700h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5zM850 700h200q21 0 35.5 -14.5t14.5 -35.5v-200 q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5zM50 300h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5zM450 300h200 q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5zM850 300h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5 t35.5 14.5z" />
+<glyph unicode="" d="M50 1100h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5zM450 1100h700q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5v200 q0 21 14.5 35.5t35.5 14.5zM50 700h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5zM450 700h700q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-700 q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5zM50 300h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5zM450 300h700q21 0 35.5 -14.5t14.5 -35.5v-200 q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M465 477l571 571q8 8 18 8t17 -8l177 -177q8 -7 8 -17t-8 -18l-783 -784q-7 -8 -17.5 -8t-17.5 8l-384 384q-8 8 -8 18t8 17l177 177q7 8 17 8t18 -8l171 -171q7 -7 18 -7t18 7z" />
+<glyph unicode="" d="M904 1083l178 -179q8 -8 8 -18.5t-8 -17.5l-267 -268l267 -268q8 -7 8 -17.5t-8 -18.5l-178 -178q-8 -8 -18.5 -8t-17.5 8l-268 267l-268 -267q-7 -8 -17.5 -8t-18.5 8l-178 178q-8 8 -8 18.5t8 17.5l267 268l-267 268q-8 7 -8 17.5t8 18.5l178 178q8 8 18.5 8t17.5 -8 l268 -267l268 268q7 7 17.5 7t18.5 -7z" />
+<glyph unicode="" d="M507 1177q98 0 187.5 -38.5t154.5 -103.5t103.5 -154.5t38.5 -187.5q0 -141 -78 -262l300 -299q8 -8 8 -18.5t-8 -18.5l-109 -108q-7 -8 -17.5 -8t-18.5 8l-300 299q-119 -77 -261 -77q-98 0 -188 38.5t-154.5 103t-103 154.5t-38.5 188t38.5 187.5t103 154.5 t154.5 103.5t188 38.5zM506.5 1023q-89.5 0 -165.5 -44t-120 -120.5t-44 -166t44 -165.5t120 -120t165.5 -44t166 44t120.5 120t44 165.5t-44 166t-120.5 120.5t-166 44zM425 900h150q10 0 17.5 -7.5t7.5 -17.5v-75h75q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5 t-17.5 -7.5h-75v-75q0 -10 -7.5 -17.5t-17.5 -7.5h-150q-10 0 -17.5 7.5t-7.5 17.5v75h-75q-10 0 -17.5 7.5t-7.5 17.5v150q0 10 7.5 17.5t17.5 7.5h75v75q0 10 7.5 17.5t17.5 7.5z" />
+<glyph unicode="" d="M507 1177q98 0 187.5 -38.5t154.5 -103.5t103.5 -154.5t38.5 -187.5q0 -141 -78 -262l300 -299q8 -8 8 -18.5t-8 -18.5l-109 -108q-7 -8 -17.5 -8t-18.5 8l-300 299q-119 -77 -261 -77q-98 0 -188 38.5t-154.5 103t-103 154.5t-38.5 188t38.5 187.5t103 154.5 t154.5 103.5t188 38.5zM506.5 1023q-89.5 0 -165.5 -44t-120 -120.5t-44 -166t44 -165.5t120 -120t165.5 -44t166 44t120.5 120t44 165.5t-44 166t-120.5 120.5t-166 44zM325 800h350q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-350q-10 0 -17.5 7.5 t-7.5 17.5v150q0 10 7.5 17.5t17.5 7.5z" />
+<glyph unicode="" d="M550 1200h100q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5zM800 975v166q167 -62 272 -209.5t105 -331.5q0 -117 -45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5 t-184.5 123t-123 184.5t-45.5 224q0 184 105 331.5t272 209.5v-166q-103 -55 -165 -155t-62 -220q0 -116 57 -214.5t155.5 -155.5t214.5 -57t214.5 57t155.5 155.5t57 214.5q0 120 -62 220t-165 155z" />
+<glyph unicode="" d="M1025 1200h150q10 0 17.5 -7.5t7.5 -17.5v-1150q0 -10 -7.5 -17.5t-17.5 -7.5h-150q-10 0 -17.5 7.5t-7.5 17.5v1150q0 10 7.5 17.5t17.5 7.5zM725 800h150q10 0 17.5 -7.5t7.5 -17.5v-750q0 -10 -7.5 -17.5t-17.5 -7.5h-150q-10 0 -17.5 7.5t-7.5 17.5v750 q0 10 7.5 17.5t17.5 7.5zM425 500h150q10 0 17.5 -7.5t7.5 -17.5v-450q0 -10 -7.5 -17.5t-17.5 -7.5h-150q-10 0 -17.5 7.5t-7.5 17.5v450q0 10 7.5 17.5t17.5 7.5zM125 300h150q10 0 17.5 -7.5t7.5 -17.5v-250q0 -10 -7.5 -17.5t-17.5 -7.5h-150q-10 0 -17.5 7.5t-7.5 17.5 v250q0 10 7.5 17.5t17.5 7.5z" />
+<glyph unicode="" d="M600 1174q33 0 74 -5l38 -152l5 -1q49 -14 94 -39l5 -2l134 80q61 -48 104 -105l-80 -134l3 -5q25 -44 39 -93l1 -6l152 -38q5 -43 5 -73q0 -34 -5 -74l-152 -38l-1 -6q-15 -49 -39 -93l-3 -5l80 -134q-48 -61 -104 -105l-134 81l-5 -3q-44 -25 -94 -39l-5 -2l-38 -151 q-43 -5 -74 -5q-33 0 -74 5l-38 151l-5 2q-49 14 -94 39l-5 3l-134 -81q-60 48 -104 105l80 134l-3 5q-25 45 -38 93l-2 6l-151 38q-6 42 -6 74q0 33 6 73l151 38l2 6q13 48 38 93l3 5l-80 134q47 61 105 105l133 -80l5 2q45 25 94 39l5 1l38 152q43 5 74 5zM600 815 q-89 0 -152 -63t-63 -151.5t63 -151.5t152 -63t152 63t63 151.5t-63 151.5t-152 63z" />
+<glyph unicode="" d="M500 1300h300q41 0 70.5 -29.5t29.5 -70.5v-100h275q10 0 17.5 -7.5t7.5 -17.5v-75h-1100v75q0 10 7.5 17.5t17.5 7.5h275v100q0 41 29.5 70.5t70.5 29.5zM500 1200v-100h300v100h-300zM1100 900v-800q0 -41 -29.5 -70.5t-70.5 -29.5h-700q-41 0 -70.5 29.5t-29.5 70.5 v800h900zM300 800v-700h100v700h-100zM500 800v-700h100v700h-100zM700 800v-700h100v700h-100zM900 800v-700h100v700h-100z" />
+<glyph unicode="" d="M18 618l620 608q8 7 18.5 7t17.5 -7l608 -608q8 -8 5.5 -13t-12.5 -5h-175v-575q0 -10 -7.5 -17.5t-17.5 -7.5h-250q-10 0 -17.5 7.5t-7.5 17.5v375h-300v-375q0 -10 -7.5 -17.5t-17.5 -7.5h-250q-10 0 -17.5 7.5t-7.5 17.5v575h-175q-10 0 -12.5 5t5.5 13z" />
+<glyph unicode="" d="M600 1200v-400q0 -41 29.5 -70.5t70.5 -29.5h300v-650q0 -21 -14.5 -35.5t-35.5 -14.5h-800q-21 0 -35.5 14.5t-14.5 35.5v1100q0 21 14.5 35.5t35.5 14.5h450zM1000 800h-250q-21 0 -35.5 14.5t-14.5 35.5v250z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM600 1027q-116 0 -214.5 -57t-155.5 -155.5t-57 -214.5t57 -214.5 t155.5 -155.5t214.5 -57t214.5 57t155.5 155.5t57 214.5t-57 214.5t-155.5 155.5t-214.5 57zM525 900h50q10 0 17.5 -7.5t7.5 -17.5v-275h175q10 0 17.5 -7.5t7.5 -17.5v-50q0 -10 -7.5 -17.5t-17.5 -7.5h-250q-10 0 -17.5 7.5t-7.5 17.5v350q0 10 7.5 17.5t17.5 7.5z" />
+<glyph unicode="" d="M1300 0h-538l-41 400h-242l-41 -400h-538l431 1200h209l-21 -300h162l-20 300h208zM515 800l-27 -300h224l-27 300h-170z" />
+<glyph unicode="" d="M550 1200h200q21 0 35.5 -14.5t14.5 -35.5v-450h191q20 0 25.5 -11.5t-7.5 -27.5l-327 -400q-13 -16 -32 -16t-32 16l-327 400q-13 16 -7.5 27.5t25.5 11.5h191v450q0 21 14.5 35.5t35.5 14.5zM1125 400h50q10 0 17.5 -7.5t7.5 -17.5v-350q0 -10 -7.5 -17.5t-17.5 -7.5 h-1050q-10 0 -17.5 7.5t-7.5 17.5v350q0 10 7.5 17.5t17.5 7.5h50q10 0 17.5 -7.5t7.5 -17.5v-175h900v175q0 10 7.5 17.5t17.5 7.5z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM600 1027q-116 0 -214.5 -57t-155.5 -155.5t-57 -214.5t57 -214.5 t155.5 -155.5t214.5 -57t214.5 57t155.5 155.5t57 214.5t-57 214.5t-155.5 155.5t-214.5 57zM525 900h150q10 0 17.5 -7.5t7.5 -17.5v-275h137q21 0 26 -11.5t-8 -27.5l-223 -275q-13 -16 -32 -16t-32 16l-223 275q-13 16 -8 27.5t26 11.5h137v275q0 10 7.5 17.5t17.5 7.5z " />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM600 1027q-116 0 -214.5 -57t-155.5 -155.5t-57 -214.5t57 -214.5 t155.5 -155.5t214.5 -57t214.5 57t155.5 155.5t57 214.5t-57 214.5t-155.5 155.5t-214.5 57zM632 914l223 -275q13 -16 8 -27.5t-26 -11.5h-137v-275q0 -10 -7.5 -17.5t-17.5 -7.5h-150q-10 0 -17.5 7.5t-7.5 17.5v275h-137q-21 0 -26 11.5t8 27.5l223 275q13 16 32 16 t32 -16z" />
+<glyph unicode="" d="M225 1200h750q10 0 19.5 -7t12.5 -17l186 -652q7 -24 7 -49v-425q0 -12 -4 -27t-9 -17q-12 -6 -37 -6h-1100q-12 0 -27 4t-17 8q-6 13 -6 38l1 425q0 25 7 49l185 652q3 10 12.5 17t19.5 7zM878 1000h-556q-10 0 -19 -7t-11 -18l-87 -450q-2 -11 4 -18t16 -7h150 q10 0 19.5 -7t11.5 -17l38 -152q2 -10 11.5 -17t19.5 -7h250q10 0 19.5 7t11.5 17l38 152q2 10 11.5 17t19.5 7h150q10 0 16 7t4 18l-87 450q-2 11 -11 18t-19 7z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM600 1027q-116 0 -214.5 -57t-155.5 -155.5t-57 -214.5t57 -214.5 t155.5 -155.5t214.5 -57t214.5 57t155.5 155.5t57 214.5t-57 214.5t-155.5 155.5t-214.5 57zM540 820l253 -190q17 -12 17 -30t-17 -30l-253 -190q-16 -12 -28 -6.5t-12 26.5v400q0 21 12 26.5t28 -6.5z" />
+<glyph unicode="" d="M947 1060l135 135q7 7 12.5 5t5.5 -13v-362q0 -10 -7.5 -17.5t-17.5 -7.5h-362q-11 0 -13 5.5t5 12.5l133 133q-109 76 -238 76q-116 0 -214.5 -57t-155.5 -155.5t-57 -214.5t57 -214.5t155.5 -155.5t214.5 -57t214.5 57t155.5 155.5t57 214.5h150q0 -117 -45.5 -224 t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5q192 0 347 -117z" />
+<glyph unicode="" d="M947 1060l135 135q7 7 12.5 5t5.5 -13v-361q0 -11 -7.5 -18.5t-18.5 -7.5h-361q-11 0 -13 5.5t5 12.5l134 134q-110 75 -239 75q-116 0 -214.5 -57t-155.5 -155.5t-57 -214.5h-150q0 117 45.5 224t123 184.5t184.5 123t224 45.5q192 0 347 -117zM1027 600h150 q0 -117 -45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5q-192 0 -348 118l-134 -134q-7 -8 -12.5 -5.5t-5.5 12.5v360q0 11 7.5 18.5t18.5 7.5h360q10 0 12.5 -5.5t-5.5 -12.5l-133 -133q110 -76 240 -76q116 0 214.5 57t155.5 155.5t57 214.5z" />
+<glyph unicode="" d="M125 1200h1050q10 0 17.5 -7.5t7.5 -17.5v-1150q0 -10 -7.5 -17.5t-17.5 -7.5h-1050q-10 0 -17.5 7.5t-7.5 17.5v1150q0 10 7.5 17.5t17.5 7.5zM1075 1000h-850q-10 0 -17.5 -7.5t-7.5 -17.5v-850q0 -10 7.5 -17.5t17.5 -7.5h850q10 0 17.5 7.5t7.5 17.5v850 q0 10 -7.5 17.5t-17.5 7.5zM325 900h50q10 0 17.5 -7.5t7.5 -17.5v-50q0 -10 -7.5 -17.5t-17.5 -7.5h-50q-10 0 -17.5 7.5t-7.5 17.5v50q0 10 7.5 17.5t17.5 7.5zM525 900h450q10 0 17.5 -7.5t7.5 -17.5v-50q0 -10 -7.5 -17.5t-17.5 -7.5h-450q-10 0 -17.5 7.5t-7.5 17.5v50 q0 10 7.5 17.5t17.5 7.5zM325 700h50q10 0 17.5 -7.5t7.5 -17.5v-50q0 -10 -7.5 -17.5t-17.5 -7.5h-50q-10 0 -17.5 7.5t-7.5 17.5v50q0 10 7.5 17.5t17.5 7.5zM525 700h450q10 0 17.5 -7.5t7.5 -17.5v-50q0 -10 -7.5 -17.5t-17.5 -7.5h-450q-10 0 -17.5 7.5t-7.5 17.5v50 q0 10 7.5 17.5t17.5 7.5zM325 500h50q10 0 17.5 -7.5t7.5 -17.5v-50q0 -10 -7.5 -17.5t-17.5 -7.5h-50q-10 0 -17.5 7.5t-7.5 17.5v50q0 10 7.5 17.5t17.5 7.5zM525 500h450q10 0 17.5 -7.5t7.5 -17.5v-50q0 -10 -7.5 -17.5t-17.5 -7.5h-450q-10 0 -17.5 7.5t-7.5 17.5v50 q0 10 7.5 17.5t17.5 7.5zM325 300h50q10 0 17.5 -7.5t7.5 -17.5v-50q0 -10 -7.5 -17.5t-17.5 -7.5h-50q-10 0 -17.5 7.5t-7.5 17.5v50q0 10 7.5 17.5t17.5 7.5zM525 300h450q10 0 17.5 -7.5t7.5 -17.5v-50q0 -10 -7.5 -17.5t-17.5 -7.5h-450q-10 0 -17.5 7.5t-7.5 17.5v50 q0 10 7.5 17.5t17.5 7.5z" />
+<glyph unicode="" d="M900 800v200q0 83 -58.5 141.5t-141.5 58.5h-300q-82 0 -141 -59t-59 -141v-200h-100q-41 0 -70.5 -29.5t-29.5 -70.5v-600q0 -41 29.5 -70.5t70.5 -29.5h900q41 0 70.5 29.5t29.5 70.5v600q0 41 -29.5 70.5t-70.5 29.5h-100zM400 800v150q0 21 15 35.5t35 14.5h200 q20 0 35 -14.5t15 -35.5v-150h-300z" />
+<glyph unicode="" d="M125 1100h50q10 0 17.5 -7.5t7.5 -17.5v-1075h-100v1075q0 10 7.5 17.5t17.5 7.5zM1075 1052q4 0 9 -2q16 -6 16 -23v-421q0 -6 -3 -12q-33 -59 -66.5 -99t-65.5 -58t-56.5 -24.5t-52.5 -6.5q-26 0 -57.5 6.5t-52.5 13.5t-60 21q-41 15 -63 22.5t-57.5 15t-65.5 7.5 q-85 0 -160 -57q-7 -5 -15 -5q-6 0 -11 3q-14 7 -14 22v438q22 55 82 98.5t119 46.5q23 2 43 0.5t43 -7t32.5 -8.5t38 -13t32.5 -11q41 -14 63.5 -21t57 -14t63.5 -7q103 0 183 87q7 8 18 8z" />
+<glyph unicode="" d="M600 1175q116 0 227 -49.5t192.5 -131t131 -192.5t49.5 -227v-300q0 -10 -7.5 -17.5t-17.5 -7.5h-50q-10 0 -17.5 7.5t-7.5 17.5v300q0 127 -70.5 231.5t-184.5 161.5t-245 57t-245 -57t-184.5 -161.5t-70.5 -231.5v-300q0 -10 -7.5 -17.5t-17.5 -7.5h-50 q-10 0 -17.5 7.5t-7.5 17.5v300q0 116 49.5 227t131 192.5t192.5 131t227 49.5zM220 500h160q8 0 14 -6t6 -14v-460q0 -8 -6 -14t-14 -6h-160q-8 0 -14 6t-6 14v460q0 8 6 14t14 6zM820 500h160q8 0 14 -6t6 -14v-460q0 -8 -6 -14t-14 -6h-160q-8 0 -14 6t-6 14v460 q0 8 6 14t14 6z" />
+<glyph unicode="" d="M321 814l258 172q9 6 15 2.5t6 -13.5v-750q0 -10 -6 -13.5t-15 2.5l-258 172q-21 14 -46 14h-250q-10 0 -17.5 7.5t-7.5 17.5v350q0 10 7.5 17.5t17.5 7.5h250q25 0 46 14zM900 668l120 120q7 7 17 7t17 -7l34 -34q7 -7 7 -17t-7 -17l-120 -120l120 -120q7 -7 7 -17 t-7 -17l-34 -34q-7 -7 -17 -7t-17 7l-120 119l-120 -119q-7 -7 -17 -7t-17 7l-34 34q-7 7 -7 17t7 17l119 120l-119 120q-7 7 -7 17t7 17l34 34q7 8 17 8t17 -8z" />
+<glyph unicode="" d="M321 814l258 172q9 6 15 2.5t6 -13.5v-750q0 -10 -6 -13.5t-15 2.5l-258 172q-21 14 -46 14h-250q-10 0 -17.5 7.5t-7.5 17.5v350q0 10 7.5 17.5t17.5 7.5h250q25 0 46 14zM766 900h4q10 -1 16 -10q96 -129 96 -290q0 -154 -90 -281q-6 -9 -17 -10l-3 -1q-9 0 -16 6 l-29 23q-7 7 -8.5 16.5t4.5 17.5q72 103 72 229q0 132 -78 238q-6 8 -4.5 18t9.5 17l29 22q7 5 15 5z" />
+<glyph unicode="" d="M967 1004h3q11 -1 17 -10q135 -179 135 -396q0 -105 -34 -206.5t-98 -185.5q-7 -9 -17 -10h-3q-9 0 -16 6l-42 34q-8 6 -9 16t5 18q111 150 111 328q0 90 -29.5 176t-84.5 157q-6 9 -5 19t10 16l42 33q7 5 15 5zM321 814l258 172q9 6 15 2.5t6 -13.5v-750q0 -10 -6 -13.5 t-15 2.5l-258 172q-21 14 -46 14h-250q-10 0 -17.5 7.5t-7.5 17.5v350q0 10 7.5 17.5t17.5 7.5h250q25 0 46 14zM766 900h4q10 -1 16 -10q96 -129 96 -290q0 -154 -90 -281q-6 -9 -17 -10l-3 -1q-9 0 -16 6l-29 23q-7 7 -8.5 16.5t4.5 17.5q72 103 72 229q0 132 -78 238 q-6 8 -4.5 18.5t9.5 16.5l29 22q7 5 15 5z" />
+<glyph unicode="" d="M500 900h100v-100h-100v-100h-400v-100h-100v600h500v-300zM1200 700h-200v-100h200v-200h-300v300h-200v300h-100v200h600v-500zM100 1100v-300h300v300h-300zM800 1100v-300h300v300h-300zM300 900h-100v100h100v-100zM1000 900h-100v100h100v-100zM300 500h200v-500 h-500v500h200v100h100v-100zM800 300h200v-100h-100v-100h-200v100h-100v100h100v200h-200v100h300v-300zM100 400v-300h300v300h-300zM300 200h-100v100h100v-100zM1200 200h-100v100h100v-100zM700 0h-100v100h100v-100zM1200 0h-300v100h300v-100z" />
+<glyph unicode="" d="M100 200h-100v1000h100v-1000zM300 200h-100v1000h100v-1000zM700 200h-200v1000h200v-1000zM900 200h-100v1000h100v-1000zM1200 200h-200v1000h200v-1000zM400 0h-300v100h300v-100zM600 0h-100v91h100v-91zM800 0h-100v91h100v-91zM1100 0h-200v91h200v-91z" />
+<glyph unicode="" d="M500 1200l682 -682q8 -8 8 -18t-8 -18l-464 -464q-8 -8 -18 -8t-18 8l-682 682l1 475q0 10 7.5 17.5t17.5 7.5h474zM319.5 1024.5q-29.5 29.5 -71 29.5t-71 -29.5t-29.5 -71.5t29.5 -71.5t71 -29.5t71 29.5t29.5 71.5t-29.5 71.5z" />
+<glyph unicode="" d="M500 1200l682 -682q8 -8 8 -18t-8 -18l-464 -464q-8 -8 -18 -8t-18 8l-682 682l1 475q0 10 7.5 17.5t17.5 7.5h474zM800 1200l682 -682q8 -8 8 -18t-8 -18l-464 -464q-8 -8 -18 -8t-18 8l-56 56l424 426l-700 700h150zM319.5 1024.5q-29.5 29.5 -71 29.5t-71 -29.5 t-29.5 -71.5t29.5 -71.5t71 -29.5t71 29.5t29.5 71.5t-29.5 71.5z" />
+<glyph unicode="" d="M300 1200h825q75 0 75 -75v-900q0 -25 -18 -43l-64 -64q-8 -8 -13 -5.5t-5 12.5v950q0 10 -7.5 17.5t-17.5 7.5h-700q-25 0 -43 -18l-64 -64q-8 -8 -5.5 -13t12.5 -5h700q10 0 17.5 -7.5t7.5 -17.5v-950q0 -10 -7.5 -17.5t-17.5 -7.5h-850q-10 0 -17.5 7.5t-7.5 17.5v975 q0 25 18 43l139 139q18 18 43 18z" />
+<glyph unicode="" d="M250 1200h800q21 0 35.5 -14.5t14.5 -35.5v-1150l-450 444l-450 -445v1151q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M822 1200h-444q-11 0 -19 -7.5t-9 -17.5l-78 -301q-7 -24 7 -45l57 -108q6 -9 17.5 -15t21.5 -6h450q10 0 21.5 6t17.5 15l62 108q14 21 7 45l-83 301q-1 10 -9 17.5t-19 7.5zM1175 800h-150q-10 0 -21 -6.5t-15 -15.5l-78 -156q-4 -9 -15 -15.5t-21 -6.5h-550 q-10 0 -21 6.5t-15 15.5l-78 156q-4 9 -15 15.5t-21 6.5h-150q-10 0 -17.5 -7.5t-7.5 -17.5v-650q0 -10 7.5 -17.5t17.5 -7.5h150q10 0 17.5 7.5t7.5 17.5v150q0 10 7.5 17.5t17.5 7.5h750q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 7.5 -17.5t17.5 -7.5h150q10 0 17.5 7.5 t7.5 17.5v650q0 10 -7.5 17.5t-17.5 7.5zM850 200h-500q-10 0 -19.5 -7t-11.5 -17l-38 -152q-2 -10 3.5 -17t15.5 -7h600q10 0 15.5 7t3.5 17l-38 152q-2 10 -11.5 17t-19.5 7z" />
+<glyph unicode="" d="M500 1100h200q56 0 102.5 -20.5t72.5 -50t44 -59t25 -50.5l6 -20h150q41 0 70.5 -29.5t29.5 -70.5v-600q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5v600q0 41 29.5 70.5t70.5 29.5h150q2 8 6.5 21.5t24 48t45 61t72 48t102.5 21.5zM900 800v-100 h100v100h-100zM600 730q-95 0 -162.5 -67.5t-67.5 -162.5t67.5 -162.5t162.5 -67.5t162.5 67.5t67.5 162.5t-67.5 162.5t-162.5 67.5zM600 603q43 0 73 -30t30 -73t-30 -73t-73 -30t-73 30t-30 73t30 73t73 30z" />
+<glyph unicode="" d="M681 1199l385 -998q20 -50 60 -92q18 -19 36.5 -29.5t27.5 -11.5l10 -2v-66h-417v66q53 0 75 43.5t5 88.5l-82 222h-391q-58 -145 -92 -234q-11 -34 -6.5 -57t25.5 -37t46 -20t55 -6v-66h-365v66q56 24 84 52q12 12 25 30.5t20 31.5l7 13l399 1006h93zM416 521h340 l-162 457z" />
+<glyph unicode="" d="M753 641q5 -1 14.5 -4.5t36 -15.5t50.5 -26.5t53.5 -40t50.5 -54.5t35.5 -70t14.5 -87q0 -67 -27.5 -125.5t-71.5 -97.5t-98.5 -66.5t-108.5 -40.5t-102 -13h-500v89q41 7 70.5 32.5t29.5 65.5v827q0 24 -0.5 34t-3.5 24t-8.5 19.5t-17 13.5t-28 12.5t-42.5 11.5v71 l471 -1q57 0 115.5 -20.5t108 -57t80.5 -94t31 -124.5q0 -51 -15.5 -96.5t-38 -74.5t-45 -50.5t-38.5 -30.5zM400 700h139q78 0 130.5 48.5t52.5 122.5q0 41 -8.5 70.5t-29.5 55.5t-62.5 39.5t-103.5 13.5h-118v-350zM400 200h216q80 0 121 50.5t41 130.5q0 90 -62.5 154.5 t-156.5 64.5h-159v-400z" />
+<glyph unicode="" d="M877 1200l2 -57q-83 -19 -116 -45.5t-40 -66.5l-132 -839q-9 -49 13 -69t96 -26v-97h-500v97q186 16 200 98l173 832q3 17 3 30t-1.5 22.5t-9 17.5t-13.5 12.5t-21.5 10t-26 8.5t-33.5 10q-13 3 -19 5v57h425z" />
+<glyph unicode="" d="M1300 900h-50q0 21 -4 37t-9.5 26.5t-18 17.5t-22 11t-28.5 5.5t-31 2t-37 0.5h-200v-850q0 -22 25 -34.5t50 -13.5l25 -2v-100h-400v100q4 0 11 0.5t24 3t30 7t24 15t11 24.5v850h-200q-25 0 -37 -0.5t-31 -2t-28.5 -5.5t-22 -11t-18 -17.5t-9.5 -26.5t-4 -37h-50v300 h1000v-300zM175 1000h-75v-800h75l-125 -167l-125 167h75v800h-75l125 167z" />
+<glyph unicode="" d="M1100 900h-50q0 21 -4 37t-9.5 26.5t-18 17.5t-22 11t-28.5 5.5t-31 2t-37 0.5h-200v-650q0 -22 25 -34.5t50 -13.5l25 -2v-100h-400v100q4 0 11 0.5t24 3t30 7t24 15t11 24.5v650h-200q-25 0 -37 -0.5t-31 -2t-28.5 -5.5t-22 -11t-18 -17.5t-9.5 -26.5t-4 -37h-50v300 h1000v-300zM1167 50l-167 -125v75h-800v-75l-167 125l167 125v-75h800v75z" />
+<glyph unicode="" d="M50 1100h600q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-600q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM50 800h1000q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1000q-21 0 -35.5 14.5t-14.5 35.5v100 q0 21 14.5 35.5t35.5 14.5zM50 500h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-800q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM50 200h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1100 q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M250 1100h700q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM50 800h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1100q-21 0 -35.5 14.5t-14.5 35.5v100 q0 21 14.5 35.5t35.5 14.5zM250 500h700q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM50 200h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1100 q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M500 950v100q0 21 14.5 35.5t35.5 14.5h600q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-600q-21 0 -35.5 14.5t-14.5 35.5zM100 650v100q0 21 14.5 35.5t35.5 14.5h1000q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1000 q-21 0 -35.5 14.5t-14.5 35.5zM300 350v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-800q-21 0 -35.5 14.5t-14.5 35.5zM0 50v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100 q0 -21 -14.5 -35.5t-35.5 -14.5h-1100q-21 0 -35.5 14.5t-14.5 35.5z" />
+<glyph unicode="" d="M50 1100h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1100q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM50 800h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1100q-21 0 -35.5 14.5t-14.5 35.5v100 q0 21 14.5 35.5t35.5 14.5zM50 500h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1100q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM50 200h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1100 q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M50 1100h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM350 1100h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-800q-21 0 -35.5 14.5t-14.5 35.5v100 q0 21 14.5 35.5t35.5 14.5zM50 800h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM350 800h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-800 q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM50 500h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM350 500h800q21 0 35.5 -14.5t14.5 -35.5v-100 q0 -21 -14.5 -35.5t-35.5 -14.5h-800q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM50 200h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM350 200h800 q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-800q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M400 0h-100v1100h100v-1100zM550 1100h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM550 800h500q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-500 q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM267 550l-167 -125v75h-200v100h200v75zM550 500h300q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-300q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM550 200h600 q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-600q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M50 1100h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM900 0h-100v1100h100v-1100zM50 800h500q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-500 q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM1100 600h200v-100h-200v-75l-167 125l167 125v-75zM50 500h300q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-300q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5zM50 200h600 q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-600q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M75 1000h750q31 0 53 -22t22 -53v-650q0 -31 -22 -53t-53 -22h-750q-31 0 -53 22t-22 53v650q0 31 22 53t53 22zM1200 300l-300 300l300 300v-600z" />
+<glyph unicode="" d="M44 1100h1112q18 0 31 -13t13 -31v-1012q0 -18 -13 -31t-31 -13h-1112q-18 0 -31 13t-13 31v1012q0 18 13 31t31 13zM100 1000v-737l247 182l298 -131l-74 156l293 318l236 -288v500h-1000zM342 884q56 0 95 -39t39 -94.5t-39 -95t-95 -39.5t-95 39.5t-39 95t39 94.5 t95 39z" />
+<glyph unicode="" d="M648 1169q117 0 216 -60t156.5 -161t57.5 -218q0 -115 -70 -258q-69 -109 -158 -225.5t-143 -179.5l-54 -62q-9 8 -25.5 24.5t-63.5 67.5t-91 103t-98.5 128t-95.5 148q-60 132 -60 249q0 88 34 169.5t91.5 142t137 96.5t166.5 36zM652.5 974q-91.5 0 -156.5 -65 t-65 -157t65 -156.5t156.5 -64.5t156.5 64.5t65 156.5t-65 157t-156.5 65z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM600 173v854q-116 0 -214.5 -57t-155.5 -155.5t-57 -214.5t57 -214.5 t155.5 -155.5t214.5 -57z" />
+<glyph unicode="" d="M554 1295q21 -72 57.5 -143.5t76 -130t83 -118t82.5 -117t70 -116t49.5 -126t18.5 -136.5q0 -71 -25.5 -135t-68.5 -111t-99 -82t-118.5 -54t-125.5 -23q-84 5 -161.5 34t-139.5 78.5t-99 125t-37 164.5q0 69 18 136.5t49.5 126.5t69.5 116.5t81.5 117.5t83.5 119 t76.5 131t58.5 143zM344 710q-23 -33 -43.5 -70.5t-40.5 -102.5t-17 -123q1 -37 14.5 -69.5t30 -52t41 -37t38.5 -24.5t33 -15q21 -7 32 -1t13 22l6 34q2 10 -2.5 22t-13.5 19q-5 4 -14 12t-29.5 40.5t-32.5 73.5q-26 89 6 271q2 11 -6 11q-8 1 -15 -10z" />
+<glyph unicode="" d="M1000 1013l108 115q2 1 5 2t13 2t20.5 -1t25 -9.5t28.5 -21.5q22 -22 27 -43t0 -32l-6 -10l-108 -115zM350 1100h400q50 0 105 -13l-187 -187h-368q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v182l200 200v-332 q0 -165 -93.5 -257.5t-256.5 -92.5h-400q-165 0 -257.5 92.5t-92.5 257.5v400q0 165 92.5 257.5t257.5 92.5zM1009 803l-362 -362l-161 -50l55 170l355 355z" />
+<glyph unicode="" d="M350 1100h361q-164 -146 -216 -200h-195q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5l200 153v-103q0 -165 -92.5 -257.5t-257.5 -92.5h-400q-165 0 -257.5 92.5t-92.5 257.5v400q0 165 92.5 257.5t257.5 92.5z M824 1073l339 -301q8 -7 8 -17.5t-8 -17.5l-340 -306q-7 -6 -12.5 -4t-6.5 11v203q-26 1 -54.5 0t-78.5 -7.5t-92 -17.5t-86 -35t-70 -57q10 59 33 108t51.5 81.5t65 58.5t68.5 40.5t67 24.5t56 13.5t40 4.5v210q1 10 6.5 12.5t13.5 -4.5z" />
+<glyph unicode="" d="M350 1100h350q60 0 127 -23l-178 -177h-349q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v69l200 200v-219q0 -165 -92.5 -257.5t-257.5 -92.5h-400q-165 0 -257.5 92.5t-92.5 257.5v400q0 165 92.5 257.5t257.5 92.5z M643 639l395 395q7 7 17.5 7t17.5 -7l101 -101q7 -7 7 -17.5t-7 -17.5l-531 -532q-7 -7 -17.5 -7t-17.5 7l-248 248q-7 7 -7 17.5t7 17.5l101 101q7 7 17.5 7t17.5 -7l111 -111q8 -7 18 -7t18 7z" />
+<glyph unicode="" d="M318 918l264 264q8 8 18 8t18 -8l260 -264q7 -8 4.5 -13t-12.5 -5h-170v-200h200v173q0 10 5 12t13 -5l264 -260q8 -7 8 -17.5t-8 -17.5l-264 -265q-8 -7 -13 -5t-5 12v173h-200v-200h170q10 0 12.5 -5t-4.5 -13l-260 -264q-8 -8 -18 -8t-18 8l-264 264q-8 8 -5.5 13 t12.5 5h175v200h-200v-173q0 -10 -5 -12t-13 5l-264 265q-8 7 -8 17.5t8 17.5l264 260q8 7 13 5t5 -12v-173h200v200h-175q-10 0 -12.5 5t5.5 13z" />
+<glyph unicode="" d="M250 1100h100q21 0 35.5 -14.5t14.5 -35.5v-438l464 453q15 14 25.5 10t10.5 -25v-1000q0 -21 -10.5 -25t-25.5 10l-464 453v-438q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v1000q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M50 1100h100q21 0 35.5 -14.5t14.5 -35.5v-438l464 453q15 14 25.5 10t10.5 -25v-438l464 453q15 14 25.5 10t10.5 -25v-1000q0 -21 -10.5 -25t-25.5 10l-464 453v-438q0 -21 -10.5 -25t-25.5 10l-464 453v-438q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5 t-14.5 35.5v1000q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M1200 1050v-1000q0 -21 -10.5 -25t-25.5 10l-464 453v-438q0 -21 -10.5 -25t-25.5 10l-492 480q-15 14 -15 35t15 35l492 480q15 14 25.5 10t10.5 -25v-438l464 453q15 14 25.5 10t10.5 -25z" />
+<glyph unicode="" d="M243 1074l814 -498q18 -11 18 -26t-18 -26l-814 -498q-18 -11 -30.5 -4t-12.5 28v1000q0 21 12.5 28t30.5 -4z" />
+<glyph unicode="" d="M250 1000h200q21 0 35.5 -14.5t14.5 -35.5v-800q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v800q0 21 14.5 35.5t35.5 14.5zM650 1000h200q21 0 35.5 -14.5t14.5 -35.5v-800q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v800 q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M1100 950v-800q0 -21 -14.5 -35.5t-35.5 -14.5h-800q-21 0 -35.5 14.5t-14.5 35.5v800q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5z" />
+<glyph unicode="" d="M500 612v438q0 21 10.5 25t25.5 -10l492 -480q15 -14 15 -35t-15 -35l-492 -480q-15 -14 -25.5 -10t-10.5 25v438l-464 -453q-15 -14 -25.5 -10t-10.5 25v1000q0 21 10.5 25t25.5 -10z" />
+<glyph unicode="" d="M1048 1102l100 1q20 0 35 -14.5t15 -35.5l5 -1000q0 -21 -14.5 -35.5t-35.5 -14.5l-100 -1q-21 0 -35.5 14.5t-14.5 35.5l-2 437l-463 -454q-14 -15 -24.5 -10.5t-10.5 25.5l-2 437l-462 -455q-15 -14 -25.5 -9.5t-10.5 24.5l-5 1000q0 21 10.5 25.5t25.5 -10.5l466 -450 l-2 438q0 20 10.5 24.5t25.5 -9.5l466 -451l-2 438q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M850 1100h100q21 0 35.5 -14.5t14.5 -35.5v-1000q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v438l-464 -453q-15 -14 -25.5 -10t-10.5 25v1000q0 21 10.5 25t25.5 -10l464 -453v438q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M686 1081l501 -540q15 -15 10.5 -26t-26.5 -11h-1042q-22 0 -26.5 11t10.5 26l501 540q15 15 36 15t36 -15zM150 400h1000q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1000q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M885 900l-352 -353l352 -353l-197 -198l-552 552l552 550z" />
+<glyph unicode="" d="M1064 547l-551 -551l-198 198l353 353l-353 353l198 198z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM650 900h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-150h-150 q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -21 14.5 -35.5t35.5 -14.5h150v-150q0 -21 14.5 -35.5t35.5 -14.5h100q21 0 35.5 14.5t14.5 35.5v150h150q21 0 35.5 14.5t14.5 35.5v100q0 21 -14.5 35.5t-35.5 14.5h-150v150q0 21 -14.5 35.5t-35.5 14.5z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM850 700h-500q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -21 14.5 -35.5 t35.5 -14.5h500q21 0 35.5 14.5t14.5 35.5v100q0 21 -14.5 35.5t-35.5 14.5z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM741.5 913q-12.5 0 -21.5 -9l-120 -120l-120 120q-9 9 -21.5 9 t-21.5 -9l-141 -141q-9 -9 -9 -21.5t9 -21.5l120 -120l-120 -120q-9 -9 -9 -21.5t9 -21.5l141 -141q9 -9 21.5 -9t21.5 9l120 120l120 -120q9 -9 21.5 -9t21.5 9l141 141q9 9 9 21.5t-9 21.5l-120 120l120 120q9 9 9 21.5t-9 21.5l-141 141q-9 9 -21.5 9z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM546 623l-84 85q-7 7 -17.5 7t-18.5 -7l-139 -139q-7 -8 -7 -18t7 -18 l242 -241q7 -8 17.5 -8t17.5 8l375 375q7 7 7 17.5t-7 18.5l-139 139q-7 7 -17.5 7t-17.5 -7z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM588 941q-29 0 -59 -5.5t-63 -20.5t-58 -38.5t-41.5 -63t-16.5 -89.5 q0 -25 20 -25h131q30 -5 35 11q6 20 20.5 28t45.5 8q20 0 31.5 -10.5t11.5 -28.5q0 -23 -7 -34t-26 -18q-1 0 -13.5 -4t-19.5 -7.5t-20 -10.5t-22 -17t-18.5 -24t-15.5 -35t-8 -46q-1 -8 5.5 -16.5t20.5 -8.5h173q7 0 22 8t35 28t37.5 48t29.5 74t12 100q0 47 -17 83 t-42.5 57t-59.5 34.5t-64 18t-59 4.5zM675 400h-150q-10 0 -17.5 -7.5t-7.5 -17.5v-150q0 -10 7.5 -17.5t17.5 -7.5h150q10 0 17.5 7.5t7.5 17.5v150q0 10 -7.5 17.5t-17.5 7.5z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM675 1000h-150q-10 0 -17.5 -7.5t-7.5 -17.5v-150q0 -10 7.5 -17.5 t17.5 -7.5h150q10 0 17.5 7.5t7.5 17.5v150q0 10 -7.5 17.5t-17.5 7.5zM675 700h-250q-10 0 -17.5 -7.5t-7.5 -17.5v-50q0 -10 7.5 -17.5t17.5 -7.5h75v-200h-75q-10 0 -17.5 -7.5t-7.5 -17.5v-50q0 -10 7.5 -17.5t17.5 -7.5h350q10 0 17.5 7.5t7.5 17.5v50q0 10 -7.5 17.5 t-17.5 7.5h-75v275q0 10 -7.5 17.5t-17.5 7.5z" />
+<glyph unicode="" d="M525 1200h150q10 0 17.5 -7.5t7.5 -17.5v-194q103 -27 178.5 -102.5t102.5 -178.5h194q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-194q-27 -103 -102.5 -178.5t-178.5 -102.5v-194q0 -10 -7.5 -17.5t-17.5 -7.5h-150q-10 0 -17.5 7.5t-7.5 17.5v194 q-103 27 -178.5 102.5t-102.5 178.5h-194q-10 0 -17.5 7.5t-7.5 17.5v150q0 10 7.5 17.5t17.5 7.5h194q27 103 102.5 178.5t178.5 102.5v194q0 10 7.5 17.5t17.5 7.5zM700 893v-168q0 -10 -7.5 -17.5t-17.5 -7.5h-150q-10 0 -17.5 7.5t-7.5 17.5v168q-68 -23 -119 -74 t-74 -119h168q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-168q23 -68 74 -119t119 -74v168q0 10 7.5 17.5t17.5 7.5h150q10 0 17.5 -7.5t7.5 -17.5v-168q68 23 119 74t74 119h-168q-10 0 -17.5 7.5t-7.5 17.5v150q0 10 7.5 17.5t17.5 7.5h168 q-23 68 -74 119t-119 74z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM600 1027q-116 0 -214.5 -57t-155.5 -155.5t-57 -214.5t57 -214.5 t155.5 -155.5t214.5 -57t214.5 57t155.5 155.5t57 214.5t-57 214.5t-155.5 155.5t-214.5 57zM759 823l64 -64q7 -7 7 -17.5t-7 -17.5l-124 -124l124 -124q7 -7 7 -17.5t-7 -17.5l-64 -64q-7 -7 -17.5 -7t-17.5 7l-124 124l-124 -124q-7 -7 -17.5 -7t-17.5 7l-64 64 q-7 7 -7 17.5t7 17.5l124 124l-124 124q-7 7 -7 17.5t7 17.5l64 64q7 7 17.5 7t17.5 -7l124 -124l124 124q7 7 17.5 7t17.5 -7z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM600 1027q-116 0 -214.5 -57t-155.5 -155.5t-57 -214.5t57 -214.5 t155.5 -155.5t214.5 -57t214.5 57t155.5 155.5t57 214.5t-57 214.5t-155.5 155.5t-214.5 57zM782 788l106 -106q7 -7 7 -17.5t-7 -17.5l-320 -321q-8 -7 -18 -7t-18 7l-202 203q-8 7 -8 17.5t8 17.5l106 106q7 8 17.5 8t17.5 -8l79 -79l197 197q7 7 17.5 7t17.5 -7z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM600 1027q-116 0 -214.5 -57t-155.5 -155.5t-57 -214.5q0 -120 65 -225 l587 587q-105 65 -225 65zM965 819l-584 -584q104 -62 219 -62q116 0 214.5 57t155.5 155.5t57 214.5q0 115 -62 219z" />
+<glyph unicode="" d="M39 582l522 427q16 13 27.5 8t11.5 -26v-291h550q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-550v-291q0 -21 -11.5 -26t-27.5 8l-522 427q-16 13 -16 32t16 32z" />
+<glyph unicode="" d="M639 1009l522 -427q16 -13 16 -32t-16 -32l-522 -427q-16 -13 -27.5 -8t-11.5 26v291h-550q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h550v291q0 21 11.5 26t27.5 -8z" />
+<glyph unicode="" d="M682 1161l427 -522q13 -16 8 -27.5t-26 -11.5h-291v-550q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v550h-291q-21 0 -26 11.5t8 27.5l427 522q13 16 32 16t32 -16z" />
+<glyph unicode="" d="M550 1200h200q21 0 35.5 -14.5t14.5 -35.5v-550h291q21 0 26 -11.5t-8 -27.5l-427 -522q-13 -16 -32 -16t-32 16l-427 522q-13 16 -8 27.5t26 11.5h291v550q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M639 1109l522 -427q16 -13 16 -32t-16 -32l-522 -427q-16 -13 -27.5 -8t-11.5 26v291q-94 -2 -182 -20t-170.5 -52t-147 -92.5t-100.5 -135.5q5 105 27 193.5t67.5 167t113 135t167 91.5t225.5 42v262q0 21 11.5 26t27.5 -8z" />
+<glyph unicode="" d="M850 1200h300q21 0 35.5 -14.5t14.5 -35.5v-300q0 -21 -10.5 -25t-24.5 10l-94 94l-249 -249q-8 -7 -18 -7t-18 7l-106 106q-7 8 -7 18t7 18l249 249l-94 94q-14 14 -10 24.5t25 10.5zM350 0h-300q-21 0 -35.5 14.5t-14.5 35.5v300q0 21 10.5 25t24.5 -10l94 -94l249 249 q8 7 18 7t18 -7l106 -106q7 -8 7 -18t-7 -18l-249 -249l94 -94q14 -14 10 -24.5t-25 -10.5z" />
+<glyph unicode="" d="M1014 1120l106 -106q7 -8 7 -18t-7 -18l-249 -249l94 -94q14 -14 10 -24.5t-25 -10.5h-300q-21 0 -35.5 14.5t-14.5 35.5v300q0 21 10.5 25t24.5 -10l94 -94l249 249q8 7 18 7t18 -7zM250 600h300q21 0 35.5 -14.5t14.5 -35.5v-300q0 -21 -10.5 -25t-24.5 10l-94 94 l-249 -249q-8 -7 -18 -7t-18 7l-106 106q-7 8 -7 18t7 18l249 249l-94 94q-14 14 -10 24.5t25 10.5z" />
+<glyph unicode="" d="M600 1177q117 0 224 -45.5t184.5 -123t123 -184.5t45.5 -224t-45.5 -224t-123 -184.5t-184.5 -123t-224 -45.5t-224 45.5t-184.5 123t-123 184.5t-45.5 224t45.5 224t123 184.5t184.5 123t224 45.5zM704 900h-208q-20 0 -32 -14.5t-8 -34.5l58 -302q4 -20 21.5 -34.5 t37.5 -14.5h54q20 0 37.5 14.5t21.5 34.5l58 302q4 20 -8 34.5t-32 14.5zM675 400h-150q-10 0 -17.5 -7.5t-7.5 -17.5v-150q0 -10 7.5 -17.5t17.5 -7.5h150q10 0 17.5 7.5t7.5 17.5v150q0 10 -7.5 17.5t-17.5 7.5z" />
+<glyph unicode="" d="M260 1200q9 0 19 -2t15 -4l5 -2q22 -10 44 -23l196 -118q21 -13 36 -24q29 -21 37 -12q11 13 49 35l196 118q22 13 45 23q17 7 38 7q23 0 47 -16.5t37 -33.5l13 -16q14 -21 18 -45l25 -123l8 -44q1 -9 8.5 -14.5t17.5 -5.5h61q10 0 17.5 -7.5t7.5 -17.5v-50 q0 -10 -7.5 -17.5t-17.5 -7.5h-50q-10 0 -17.5 -7.5t-7.5 -17.5v-175h-400v300h-200v-300h-400v175q0 10 -7.5 17.5t-17.5 7.5h-50q-10 0 -17.5 7.5t-7.5 17.5v50q0 10 7.5 17.5t17.5 7.5h61q11 0 18 3t7 8q0 4 9 52l25 128q5 25 19 45q2 3 5 7t13.5 15t21.5 19.5t26.5 15.5 t29.5 7zM915 1079l-166 -162q-7 -7 -5 -12t12 -5h219q10 0 15 7t2 17l-51 149q-3 10 -11 12t-15 -6zM463 917l-177 157q-8 7 -16 5t-11 -12l-51 -143q-3 -10 2 -17t15 -7h231q11 0 12.5 5t-5.5 12zM500 0h-375q-10 0 -17.5 7.5t-7.5 17.5v375h400v-400zM1100 400v-375 q0 -10 -7.5 -17.5t-17.5 -7.5h-375v400h400z" />
+<glyph unicode="" d="M1165 1190q8 3 21 -6.5t13 -17.5q-2 -178 -24.5 -323.5t-55.5 -245.5t-87 -174.5t-102.5 -118.5t-118 -68.5t-118.5 -33t-120 -4.5t-105 9.5t-90 16.5q-61 12 -78 11q-4 1 -12.5 0t-34 -14.5t-52.5 -40.5l-153 -153q-26 -24 -37 -14.5t-11 43.5q0 64 42 102q8 8 50.5 45 t66.5 58q19 17 35 47t13 61q-9 55 -10 102.5t7 111t37 130t78 129.5q39 51 80 88t89.5 63.5t94.5 45t113.5 36t129 31t157.5 37t182 47.5zM1116 1098q-8 9 -22.5 -3t-45.5 -50q-38 -47 -119 -103.5t-142 -89.5l-62 -33q-56 -30 -102 -57t-104 -68t-102.5 -80.5t-85.5 -91 t-64 -104.5q-24 -56 -31 -86t2 -32t31.5 17.5t55.5 59.5q25 30 94 75.5t125.5 77.5t147.5 81q70 37 118.5 69t102 79.5t99 111t86.5 148.5q22 50 24 60t-6 19z" />
+<glyph unicode="" d="M653 1231q-39 -67 -54.5 -131t-10.5 -114.5t24.5 -96.5t47.5 -80t63.5 -62.5t68.5 -46.5t65 -30q-4 7 -17.5 35t-18.5 39.5t-17 39.5t-17 43t-13 42t-9.5 44.5t-2 42t4 43t13.5 39t23 38.5q96 -42 165 -107.5t105 -138t52 -156t13 -159t-19 -149.5q-13 -55 -44 -106.5 t-68 -87t-78.5 -64.5t-72.5 -45t-53 -22q-72 -22 -127 -11q-31 6 -13 19q6 3 17 7q13 5 32.5 21t41 44t38.5 63.5t21.5 81.5t-6.5 94.5t-50 107t-104 115.5q10 -104 -0.5 -189t-37 -140.5t-65 -93t-84 -52t-93.5 -11t-95 24.5q-80 36 -131.5 114t-53.5 171q-2 23 0 49.5 t4.5 52.5t13.5 56t27.5 60t46 64.5t69.5 68.5q-8 -53 -5 -102.5t17.5 -90t34 -68.5t44.5 -39t49 -2q31 13 38.5 36t-4.5 55t-29 64.5t-36 75t-26 75.5q-15 85 2 161.5t53.5 128.5t85.5 92.5t93.5 61t81.5 25.5z" />
+<glyph unicode="" d="M600 1094q82 0 160.5 -22.5t140 -59t116.5 -82.5t94.5 -95t68 -95t42.5 -82.5t14 -57.5t-14 -57.5t-43 -82.5t-68.5 -95t-94.5 -95t-116.5 -82.5t-140 -59t-159.5 -22.5t-159.5 22.5t-140 59t-116.5 82.5t-94.5 95t-68.5 95t-43 82.5t-14 57.5t14 57.5t42.5 82.5t68 95 t94.5 95t116.5 82.5t140 59t160.5 22.5zM888 829q-15 15 -18 12t5 -22q25 -57 25 -119q0 -124 -88 -212t-212 -88t-212 88t-88 212q0 59 23 114q8 19 4.5 22t-17.5 -12q-70 -69 -160 -184q-13 -16 -15 -40.5t9 -42.5q22 -36 47 -71t70 -82t92.5 -81t113 -58.5t133.5 -24.5 t133.5 24t113 58.5t92.5 81.5t70 81.5t47 70.5q11 18 9 42.5t-14 41.5q-90 117 -163 189zM448 727l-35 -36q-15 -15 -19.5 -38.5t4.5 -41.5q37 -68 93 -116q16 -13 38.5 -11t36.5 17l35 34q14 15 12.5 33.5t-16.5 33.5q-44 44 -89 117q-11 18 -28 20t-32 -12z" />
+<glyph unicode="" d="M592 0h-148l31 120q-91 20 -175.5 68.5t-143.5 106.5t-103.5 119t-66.5 110t-22 76q0 21 14 57.5t42.5 82.5t68 95t94.5 95t116.5 82.5t140 59t160.5 22.5q61 0 126 -15l32 121h148zM944 770l47 181q108 -85 176.5 -192t68.5 -159q0 -26 -19.5 -71t-59.5 -102t-93 -112 t-129 -104.5t-158 -75.5l46 173q77 49 136 117t97 131q11 18 9 42.5t-14 41.5q-54 70 -107 130zM310 824q-70 -69 -160 -184q-13 -16 -15 -40.5t9 -42.5q18 -30 39 -60t57 -70.5t74 -73t90 -61t105 -41.5l41 154q-107 18 -178.5 101.5t-71.5 193.5q0 59 23 114q8 19 4.5 22 t-17.5 -12zM448 727l-35 -36q-15 -15 -19.5 -38.5t4.5 -41.5q37 -68 93 -116q16 -13 38.5 -11t36.5 17l12 11l22 86l-3 4q-44 44 -89 117q-11 18 -28 20t-32 -12z" />
+<glyph unicode="" d="M-90 100l642 1066q20 31 48 28.5t48 -35.5l642 -1056q21 -32 7.5 -67.5t-50.5 -35.5h-1294q-37 0 -50.5 34t7.5 66zM155 200h345v75q0 10 7.5 17.5t17.5 7.5h150q10 0 17.5 -7.5t7.5 -17.5v-75h345l-445 723zM496 700h208q20 0 32 -14.5t8 -34.5l-58 -252 q-4 -20 -21.5 -34.5t-37.5 -14.5h-54q-20 0 -37.5 14.5t-21.5 34.5l-58 252q-4 20 8 34.5t32 14.5z" />
+<glyph unicode="" d="M650 1200q62 0 106 -44t44 -106v-339l363 -325q15 -14 26 -38.5t11 -44.5v-41q0 -20 -12 -26.5t-29 5.5l-359 249v-263q100 -93 100 -113v-64q0 -21 -13 -29t-32 1l-205 128l-205 -128q-19 -9 -32 -1t-13 29v64q0 20 100 113v263l-359 -249q-17 -12 -29 -5.5t-12 26.5v41 q0 20 11 44.5t26 38.5l363 325v339q0 62 44 106t106 44z" />
+<glyph unicode="" d="M850 1200h100q21 0 35.5 -14.5t14.5 -35.5v-50h50q21 0 35.5 -14.5t14.5 -35.5v-150h-1100v150q0 21 14.5 35.5t35.5 14.5h50v50q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-50h500v50q0 21 14.5 35.5t35.5 14.5zM1100 800v-750q0 -21 -14.5 -35.5 t-35.5 -14.5h-1000q-21 0 -35.5 14.5t-14.5 35.5v750h1100zM100 600v-100h100v100h-100zM300 600v-100h100v100h-100zM500 600v-100h100v100h-100zM700 600v-100h100v100h-100zM900 600v-100h100v100h-100zM100 400v-100h100v100h-100zM300 400v-100h100v100h-100zM500 400 v-100h100v100h-100zM700 400v-100h100v100h-100zM900 400v-100h100v100h-100zM100 200v-100h100v100h-100zM300 200v-100h100v100h-100zM500 200v-100h100v100h-100zM700 200v-100h100v100h-100zM900 200v-100h100v100h-100z" />
+<glyph unicode="" d="M1135 1165l249 -230q15 -14 15 -35t-15 -35l-249 -230q-14 -14 -24.5 -10t-10.5 25v150h-159l-600 -600h-291q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5h209l600 600h241v150q0 21 10.5 25t24.5 -10zM522 819l-141 -141l-122 122h-209q-21 0 -35.5 14.5 t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5h291zM1135 565l249 -230q15 -14 15 -35t-15 -35l-249 -230q-14 -14 -24.5 -10t-10.5 25v150h-241l-181 181l141 141l122 -122h159v150q0 21 10.5 25t24.5 -10z" />
+<glyph unicode="" d="M100 1100h1000q41 0 70.5 -29.5t29.5 -70.5v-600q0 -41 -29.5 -70.5t-70.5 -29.5h-596l-304 -300v300h-100q-41 0 -70.5 29.5t-29.5 70.5v600q0 41 29.5 70.5t70.5 29.5z" />
+<glyph unicode="" d="M150 1200h200q21 0 35.5 -14.5t14.5 -35.5v-250h-300v250q0 21 14.5 35.5t35.5 14.5zM850 1200h200q21 0 35.5 -14.5t14.5 -35.5v-250h-300v250q0 21 14.5 35.5t35.5 14.5zM1100 800v-300q0 -41 -3 -77.5t-15 -89.5t-32 -96t-58 -89t-89 -77t-129 -51t-174 -20t-174 20 t-129 51t-89 77t-58 89t-32 96t-15 89.5t-3 77.5v300h300v-250v-27v-42.5t1.5 -41t5 -38t10 -35t16.5 -30t25.5 -24.5t35 -19t46.5 -12t60 -4t60 4.5t46.5 12.5t35 19.5t25 25.5t17 30.5t10 35t5 38t2 40.5t-0.5 42v25v250h300z" />
+<glyph unicode="" d="M1100 411l-198 -199l-353 353l-353 -353l-197 199l551 551z" />
+<glyph unicode="" d="M1101 789l-550 -551l-551 551l198 199l353 -353l353 353z" />
+<glyph unicode="" d="M404 1000h746q21 0 35.5 -14.5t14.5 -35.5v-551h150q21 0 25 -10.5t-10 -24.5l-230 -249q-14 -15 -35 -15t-35 15l-230 249q-14 14 -10 24.5t25 10.5h150v401h-381zM135 984l230 -249q14 -14 10 -24.5t-25 -10.5h-150v-400h385l215 -200h-750q-21 0 -35.5 14.5 t-14.5 35.5v550h-150q-21 0 -25 10.5t10 24.5l230 249q14 15 35 15t35 -15z" />
+<glyph unicode="" d="M56 1200h94q17 0 31 -11t18 -27l38 -162h896q24 0 39 -18.5t10 -42.5l-100 -475q-5 -21 -27 -42.5t-55 -21.5h-633l48 -200h535q21 0 35.5 -14.5t14.5 -35.5t-14.5 -35.5t-35.5 -14.5h-50v-50q0 -21 -14.5 -35.5t-35.5 -14.5t-35.5 14.5t-14.5 35.5v50h-300v-50 q0 -21 -14.5 -35.5t-35.5 -14.5t-35.5 14.5t-14.5 35.5v50h-31q-18 0 -32.5 10t-20.5 19l-5 10l-201 961h-54q-20 0 -35 14.5t-15 35.5t15 35.5t35 14.5z" />
+<glyph unicode="" d="M1200 1000v-100h-1200v100h200q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5h500zM0 800h1200v-800h-1200v800z" />
+<glyph unicode="" d="M200 800l-200 -400v600h200q0 41 29.5 70.5t70.5 29.5h300q42 0 71 -29.5t29 -70.5h500v-200h-1000zM1500 700l-300 -700h-1200l300 700h1200z" />
+<glyph unicode="" d="M635 1184l230 -249q14 -14 10 -24.5t-25 -10.5h-150v-601h150q21 0 25 -10.5t-10 -24.5l-230 -249q-14 -15 -35 -15t-35 15l-230 249q-14 14 -10 24.5t25 10.5h150v601h-150q-21 0 -25 10.5t10 24.5l230 249q14 15 35 15t35 -15z" />
+<glyph unicode="" d="M936 864l249 -229q14 -15 14 -35.5t-14 -35.5l-249 -229q-15 -15 -25.5 -10.5t-10.5 24.5v151h-600v-151q0 -20 -10.5 -24.5t-25.5 10.5l-249 229q-14 15 -14 35.5t14 35.5l249 229q15 15 25.5 10.5t10.5 -25.5v-149h600v149q0 21 10.5 25.5t25.5 -10.5z" />
+<glyph unicode="" d="M1169 400l-172 732q-5 23 -23 45.5t-38 22.5h-672q-20 0 -38 -20t-23 -41l-172 -739h1138zM1100 300h-1000q-41 0 -70.5 -29.5t-29.5 -70.5v-100q0 -41 29.5 -70.5t70.5 -29.5h1000q41 0 70.5 29.5t29.5 70.5v100q0 41 -29.5 70.5t-70.5 29.5zM800 100v100h100v-100h-100 zM1000 100v100h100v-100h-100z" />
+<glyph unicode="" d="M1150 1100q21 0 35.5 -14.5t14.5 -35.5v-850q0 -21 -14.5 -35.5t-35.5 -14.5t-35.5 14.5t-14.5 35.5v850q0 21 14.5 35.5t35.5 14.5zM1000 200l-675 200h-38l47 -276q3 -16 -5.5 -20t-29.5 -4h-7h-84q-20 0 -34.5 14t-18.5 35q-55 337 -55 351v250v6q0 16 1 23.5t6.5 14 t17.5 6.5h200l675 250v-850zM0 750v-250q-4 0 -11 0.5t-24 6t-30 15t-24 30t-11 48.5v50q0 26 10.5 46t25 30t29 16t25.5 7z" />
+<glyph unicode="" d="M553 1200h94q20 0 29 -10.5t3 -29.5l-18 -37q83 -19 144 -82.5t76 -140.5l63 -327l118 -173h17q19 0 33 -14.5t14 -35t-13 -40.5t-31 -27q-8 -4 -23 -9.5t-65 -19.5t-103 -25t-132.5 -20t-158.5 -9q-57 0 -115 5t-104 12t-88.5 15.5t-73.5 17.5t-54.5 16t-35.5 12l-11 4 q-18 8 -31 28t-13 40.5t14 35t33 14.5h17l118 173l63 327q15 77 76 140t144 83l-18 32q-6 19 3.5 32t28.5 13zM498 110q50 -6 102 -6q53 0 102 6q-12 -49 -39.5 -79.5t-62.5 -30.5t-63 30.5t-39 79.5z" />
+<glyph unicode="" d="M800 946l224 78l-78 -224l234 -45l-180 -155l180 -155l-234 -45l78 -224l-224 78l-45 -234l-155 180l-155 -180l-45 234l-224 -78l78 224l-234 45l180 155l-180 155l234 45l-78 224l224 -78l45 234l155 -180l155 180z" />
+<glyph unicode="" d="M650 1200h50q40 0 70 -40.5t30 -84.5v-150l-28 -125h328q40 0 70 -40.5t30 -84.5v-100q0 -45 -29 -74l-238 -344q-16 -24 -38 -40.5t-45 -16.5h-250q-7 0 -42 25t-66 50l-31 25h-61q-45 0 -72.5 18t-27.5 57v400q0 36 20 63l145 196l96 198q13 28 37.5 48t51.5 20z M650 1100l-100 -212l-150 -213v-375h100l136 -100h214l250 375v125h-450l50 225v175h-50zM50 800h100q21 0 35.5 -14.5t14.5 -35.5v-500q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v500q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M600 1100h250q23 0 45 -16.5t38 -40.5l238 -344q29 -29 29 -74v-100q0 -44 -30 -84.5t-70 -40.5h-328q28 -118 28 -125v-150q0 -44 -30 -84.5t-70 -40.5h-50q-27 0 -51.5 20t-37.5 48l-96 198l-145 196q-20 27 -20 63v400q0 39 27.5 57t72.5 18h61q124 100 139 100z M50 1000h100q21 0 35.5 -14.5t14.5 -35.5v-500q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v500q0 21 14.5 35.5t35.5 14.5zM636 1000l-136 -100h-100v-375l150 -213l100 -212h50v175l-50 225h450v125l-250 375h-214z" />
+<glyph unicode="" d="M356 873l363 230q31 16 53 -6l110 -112q13 -13 13.5 -32t-11.5 -34l-84 -121h302q84 0 138 -38t54 -110t-55 -111t-139 -39h-106l-131 -339q-6 -21 -19.5 -41t-28.5 -20h-342q-7 0 -90 81t-83 94v525q0 17 14 35.5t28 28.5zM400 792v-503l100 -89h293l131 339 q6 21 19.5 41t28.5 20h203q21 0 30.5 25t0.5 50t-31 25h-456h-7h-6h-5.5t-6 0.5t-5 1.5t-5 2t-4 2.5t-4 4t-2.5 4.5q-12 25 5 47l146 183l-86 83zM50 800h100q21 0 35.5 -14.5t14.5 -35.5v-500q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v500 q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M475 1103l366 -230q2 -1 6 -3.5t14 -10.5t18 -16.5t14.5 -20t6.5 -22.5v-525q0 -13 -86 -94t-93 -81h-342q-15 0 -28.5 20t-19.5 41l-131 339h-106q-85 0 -139.5 39t-54.5 111t54 110t138 38h302l-85 121q-11 15 -10.5 34t13.5 32l110 112q22 22 53 6zM370 945l146 -183 q17 -22 5 -47q-2 -2 -3.5 -4.5t-4 -4t-4 -2.5t-5 -2t-5 -1.5t-6 -0.5h-6h-6.5h-6h-475v-100h221q15 0 29 -20t20 -41l130 -339h294l106 89v503l-342 236zM1050 800h100q21 0 35.5 -14.5t14.5 -35.5v-500q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5 v500q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M550 1294q72 0 111 -55t39 -139v-106l339 -131q21 -6 41 -19.5t20 -28.5v-342q0 -7 -81 -90t-94 -83h-525q-17 0 -35.5 14t-28.5 28l-9 14l-230 363q-16 31 6 53l112 110q13 13 32 13.5t34 -11.5l121 -84v302q0 84 38 138t110 54zM600 972v203q0 21 -25 30.5t-50 0.5 t-25 -31v-456v-7v-6v-5.5t-0.5 -6t-1.5 -5t-2 -5t-2.5 -4t-4 -4t-4.5 -2.5q-25 -12 -47 5l-183 146l-83 -86l236 -339h503l89 100v293l-339 131q-21 6 -41 19.5t-20 28.5zM450 200h500q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-500 q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M350 1100h500q21 0 35.5 14.5t14.5 35.5v100q0 21 -14.5 35.5t-35.5 14.5h-500q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -21 14.5 -35.5t35.5 -14.5zM600 306v-106q0 -84 -39 -139t-111 -55t-110 54t-38 138v302l-121 -84q-15 -12 -34 -11.5t-32 13.5l-112 110 q-22 22 -6 53l230 363q1 2 3.5 6t10.5 13.5t16.5 17t20 13.5t22.5 6h525q13 0 94 -83t81 -90v-342q0 -15 -20 -28.5t-41 -19.5zM308 900l-236 -339l83 -86l183 146q22 17 47 5q2 -1 4.5 -2.5t4 -4t2.5 -4t2 -5t1.5 -5t0.5 -6v-5.5v-6v-7v-456q0 -22 25 -31t50 0.5t25 30.5 v203q0 15 20 28.5t41 19.5l339 131v293l-89 100h-503z" />
+<glyph unicode="" d="M600 1178q118 0 225 -45.5t184.5 -123t123 -184.5t45.5 -225t-45.5 -225t-123 -184.5t-184.5 -123t-225 -45.5t-225 45.5t-184.5 123t-123 184.5t-45.5 225t45.5 225t123 184.5t184.5 123t225 45.5zM914 632l-275 223q-16 13 -27.5 8t-11.5 -26v-137h-275 q-10 0 -17.5 -7.5t-7.5 -17.5v-150q0 -10 7.5 -17.5t17.5 -7.5h275v-137q0 -21 11.5 -26t27.5 8l275 223q16 13 16 32t-16 32z" />
+<glyph unicode="" d="M600 1178q118 0 225 -45.5t184.5 -123t123 -184.5t45.5 -225t-45.5 -225t-123 -184.5t-184.5 -123t-225 -45.5t-225 45.5t-184.5 123t-123 184.5t-45.5 225t45.5 225t123 184.5t184.5 123t225 45.5zM561 855l-275 -223q-16 -13 -16 -32t16 -32l275 -223q16 -13 27.5 -8 t11.5 26v137h275q10 0 17.5 7.5t7.5 17.5v150q0 10 -7.5 17.5t-17.5 7.5h-275v137q0 21 -11.5 26t-27.5 -8z" />
+<glyph unicode="" d="M600 1178q118 0 225 -45.5t184.5 -123t123 -184.5t45.5 -225t-45.5 -225t-123 -184.5t-184.5 -123t-225 -45.5t-225 45.5t-184.5 123t-123 184.5t-45.5 225t45.5 225t123 184.5t184.5 123t225 45.5zM855 639l-223 275q-13 16 -32 16t-32 -16l-223 -275q-13 -16 -8 -27.5 t26 -11.5h137v-275q0 -10 7.5 -17.5t17.5 -7.5h150q10 0 17.5 7.5t7.5 17.5v275h137q21 0 26 11.5t-8 27.5z" />
+<glyph unicode="" d="M600 1178q118 0 225 -45.5t184.5 -123t123 -184.5t45.5 -225t-45.5 -225t-123 -184.5t-184.5 -123t-225 -45.5t-225 45.5t-184.5 123t-123 184.5t-45.5 225t45.5 225t123 184.5t184.5 123t225 45.5zM675 900h-150q-10 0 -17.5 -7.5t-7.5 -17.5v-275h-137q-21 0 -26 -11.5 t8 -27.5l223 -275q13 -16 32 -16t32 16l223 275q13 16 8 27.5t-26 11.5h-137v275q0 10 -7.5 17.5t-17.5 7.5z" />
+<glyph unicode="" d="M600 1176q116 0 222.5 -46t184 -123.5t123.5 -184t46 -222.5t-46 -222.5t-123.5 -184t-184 -123.5t-222.5 -46t-222.5 46t-184 123.5t-123.5 184t-46 222.5t46 222.5t123.5 184t184 123.5t222.5 46zM627 1101q-15 -12 -36.5 -20.5t-35.5 -12t-43 -8t-39 -6.5 q-15 -3 -45.5 0t-45.5 -2q-20 -7 -51.5 -26.5t-34.5 -34.5q-3 -11 6.5 -22.5t8.5 -18.5q-3 -34 -27.5 -91t-29.5 -79q-9 -34 5 -93t8 -87q0 -9 17 -44.5t16 -59.5q12 0 23 -5t23.5 -15t19.5 -14q16 -8 33 -15t40.5 -15t34.5 -12q21 -9 52.5 -32t60 -38t57.5 -11 q7 -15 -3 -34t-22.5 -40t-9.5 -38q13 -21 23 -34.5t27.5 -27.5t36.5 -18q0 -7 -3.5 -16t-3.5 -14t5 -17q104 -2 221 112q30 29 46.5 47t34.5 49t21 63q-13 8 -37 8.5t-36 7.5q-15 7 -49.5 15t-51.5 19q-18 0 -41 -0.5t-43 -1.5t-42 -6.5t-38 -16.5q-51 -35 -66 -12 q-4 1 -3.5 25.5t0.5 25.5q-6 13 -26.5 17.5t-24.5 6.5q1 15 -0.5 30.5t-7 28t-18.5 11.5t-31 -21q-23 -25 -42 4q-19 28 -8 58q6 16 22 22q6 -1 26 -1.5t33.5 -4t19.5 -13.5q7 -12 18 -24t21.5 -20.5t20 -15t15.5 -10.5l5 -3q2 12 7.5 30.5t8 34.5t-0.5 32q-3 18 3.5 29 t18 22.5t15.5 24.5q6 14 10.5 35t8 31t15.5 22.5t34 22.5q-6 18 10 36q8 0 24 -1.5t24.5 -1.5t20 4.5t20.5 15.5q-10 23 -31 42.5t-37.5 29.5t-49 27t-43.5 23q0 1 2 8t3 11.5t1.5 10.5t-1 9.5t-4.5 4.5q31 -13 58.5 -14.5t38.5 2.5l12 5q5 28 -9.5 46t-36.5 24t-50 15 t-41 20q-18 -4 -37 0zM613 994q0 -17 8 -42t17 -45t9 -23q-8 1 -39.5 5.5t-52.5 10t-37 16.5q3 11 16 29.5t16 25.5q10 -10 19 -10t14 6t13.5 14.5t16.5 12.5z" />
+<glyph unicode="" d="M756 1157q164 92 306 -9l-259 -138l145 -232l251 126q6 -89 -34 -156.5t-117 -110.5q-60 -34 -127 -39.5t-126 16.5l-596 -596q-15 -16 -36.5 -16t-36.5 16l-111 110q-15 15 -15 36.5t15 37.5l600 599q-34 101 5.5 201.5t135.5 154.5z" />
+<glyph unicode="" horiz-adv-x="1220" d="M100 1196h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5v100q0 41 29.5 70.5t70.5 29.5zM1100 1096h-200v-100h200v100zM100 796h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000 q-41 0 -70.5 29.5t-29.5 70.5v100q0 41 29.5 70.5t70.5 29.5zM1100 696h-500v-100h500v100zM100 396h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5v100q0 41 29.5 70.5t70.5 29.5zM1100 296h-300v-100h300v100z " />
+<glyph unicode="" d="M150 1200h900q21 0 35.5 -14.5t14.5 -35.5t-14.5 -35.5t-35.5 -14.5h-900q-21 0 -35.5 14.5t-14.5 35.5t14.5 35.5t35.5 14.5zM700 500v-300l-200 -200v500l-350 500h900z" />
+<glyph unicode="" d="M500 1200h200q41 0 70.5 -29.5t29.5 -70.5v-100h300q41 0 70.5 -29.5t29.5 -70.5v-400h-500v100h-200v-100h-500v400q0 41 29.5 70.5t70.5 29.5h300v100q0 41 29.5 70.5t70.5 29.5zM500 1100v-100h200v100h-200zM1200 400v-200q0 -41 -29.5 -70.5t-70.5 -29.5h-1000 q-41 0 -70.5 29.5t-29.5 70.5v200h1200z" />
+<glyph unicode="" d="M50 1200h300q21 0 25 -10.5t-10 -24.5l-94 -94l199 -199q7 -8 7 -18t-7 -18l-106 -106q-8 -7 -18 -7t-18 7l-199 199l-94 -94q-14 -14 -24.5 -10t-10.5 25v300q0 21 14.5 35.5t35.5 14.5zM850 1200h300q21 0 35.5 -14.5t14.5 -35.5v-300q0 -21 -10.5 -25t-24.5 10l-94 94 l-199 -199q-8 -7 -18 -7t-18 7l-106 106q-7 8 -7 18t7 18l199 199l-94 94q-14 14 -10 24.5t25 10.5zM364 470l106 -106q7 -8 7 -18t-7 -18l-199 -199l94 -94q14 -14 10 -24.5t-25 -10.5h-300q-21 0 -35.5 14.5t-14.5 35.5v300q0 21 10.5 25t24.5 -10l94 -94l199 199 q8 7 18 7t18 -7zM1071 271l94 94q14 14 24.5 10t10.5 -25v-300q0 -21 -14.5 -35.5t-35.5 -14.5h-300q-21 0 -25 10.5t10 24.5l94 94l-199 199q-7 8 -7 18t7 18l106 106q8 7 18 7t18 -7z" />
+<glyph unicode="" d="M596 1192q121 0 231.5 -47.5t190 -127t127 -190t47.5 -231.5t-47.5 -231.5t-127 -190.5t-190 -127t-231.5 -47t-231.5 47t-190.5 127t-127 190.5t-47 231.5t47 231.5t127 190t190.5 127t231.5 47.5zM596 1010q-112 0 -207.5 -55.5t-151 -151t-55.5 -207.5t55.5 -207.5 t151 -151t207.5 -55.5t207.5 55.5t151 151t55.5 207.5t-55.5 207.5t-151 151t-207.5 55.5zM454.5 905q22.5 0 38.5 -16t16 -38.5t-16 -39t-38.5 -16.5t-38.5 16.5t-16 39t16 38.5t38.5 16zM754.5 905q22.5 0 38.5 -16t16 -38.5t-16 -39t-38 -16.5q-14 0 -29 10l-55 -145 q17 -23 17 -51q0 -36 -25.5 -61.5t-61.5 -25.5t-61.5 25.5t-25.5 61.5q0 32 20.5 56.5t51.5 29.5l122 126l1 1q-9 14 -9 28q0 23 16 39t38.5 16zM345.5 709q22.5 0 38.5 -16t16 -38.5t-16 -38.5t-38.5 -16t-38.5 16t-16 38.5t16 38.5t38.5 16zM854.5 709q22.5 0 38.5 -16 t16 -38.5t-16 -38.5t-38.5 -16t-38.5 16t-16 38.5t16 38.5t38.5 16z" />
+<glyph unicode="" d="M546 173l469 470q91 91 99 192q7 98 -52 175.5t-154 94.5q-22 4 -47 4q-34 0 -66.5 -10t-56.5 -23t-55.5 -38t-48 -41.5t-48.5 -47.5q-376 -375 -391 -390q-30 -27 -45 -41.5t-37.5 -41t-32 -46.5t-16 -47.5t-1.5 -56.5q9 -62 53.5 -95t99.5 -33q74 0 125 51l548 548 q36 36 20 75q-7 16 -21.5 26t-32.5 10q-26 0 -50 -23q-13 -12 -39 -38l-341 -338q-15 -15 -35.5 -15.5t-34.5 13.5t-14 34.5t14 34.5q327 333 361 367q35 35 67.5 51.5t78.5 16.5q14 0 29 -1q44 -8 74.5 -35.5t43.5 -68.5q14 -47 2 -96.5t-47 -84.5q-12 -11 -32 -32 t-79.5 -81t-114.5 -115t-124.5 -123.5t-123 -119.5t-96.5 -89t-57 -45q-56 -27 -120 -27q-70 0 -129 32t-93 89q-48 78 -35 173t81 163l511 511q71 72 111 96q91 55 198 55q80 0 152 -33q78 -36 129.5 -103t66.5 -154q17 -93 -11 -183.5t-94 -156.5l-482 -476 q-15 -15 -36 -16t-37 14t-17.5 34t14.5 35z" />
+<glyph unicode="" d="M649 949q48 68 109.5 104t121.5 38.5t118.5 -20t102.5 -64t71 -100.5t27 -123q0 -57 -33.5 -117.5t-94 -124.5t-126.5 -127.5t-150 -152.5t-146 -174q-62 85 -145.5 174t-150 152.5t-126.5 127.5t-93.5 124.5t-33.5 117.5q0 64 28 123t73 100.5t104 64t119 20 t120.5 -38.5t104.5 -104zM896 972q-33 0 -64.5 -19t-56.5 -46t-47.5 -53.5t-43.5 -45.5t-37.5 -19t-36 19t-40 45.5t-43 53.5t-54 46t-65.5 19q-67 0 -122.5 -55.5t-55.5 -132.5q0 -23 13.5 -51t46 -65t57.5 -63t76 -75l22 -22q15 -14 44 -44t50.5 -51t46 -44t41 -35t23 -12 t23.5 12t42.5 36t46 44t52.5 52t44 43q4 4 12 13q43 41 63.5 62t52 55t46 55t26 46t11.5 44q0 79 -53 133.5t-120 54.5z" />
+<glyph unicode="" d="M776.5 1214q93.5 0 159.5 -66l141 -141q66 -66 66 -160q0 -42 -28 -95.5t-62 -87.5l-29 -29q-31 53 -77 99l-18 18l95 95l-247 248l-389 -389l212 -212l-105 -106l-19 18l-141 141q-66 66 -66 159t66 159l283 283q65 66 158.5 66zM600 706l105 105q10 -8 19 -17l141 -141 q66 -66 66 -159t-66 -159l-283 -283q-66 -66 -159 -66t-159 66l-141 141q-66 66 -66 159.5t66 159.5l55 55q29 -55 75 -102l18 -17l-95 -95l247 -248l389 389z" />
+<glyph unicode="" d="M603 1200q85 0 162 -15t127 -38t79 -48t29 -46v-953q0 -41 -29.5 -70.5t-70.5 -29.5h-600q-41 0 -70.5 29.5t-29.5 70.5v953q0 21 30 46.5t81 48t129 37.5t163 15zM300 1000v-700h600v700h-600zM600 254q-43 0 -73.5 -30.5t-30.5 -73.5t30.5 -73.5t73.5 -30.5t73.5 30.5 t30.5 73.5t-30.5 73.5t-73.5 30.5z" />
+<glyph unicode="" d="M902 1185l283 -282q15 -15 15 -36t-14.5 -35.5t-35.5 -14.5t-35 15l-36 35l-279 -267v-300l-212 210l-308 -307l-280 -203l203 280l307 308l-210 212h300l267 279l-35 36q-15 14 -15 35t14.5 35.5t35.5 14.5t35 -15z" />
+<glyph unicode="" d="M700 1248v-78q38 -5 72.5 -14.5t75.5 -31.5t71 -53.5t52 -84t24 -118.5h-159q-4 36 -10.5 59t-21 45t-40 35.5t-64.5 20.5v-307l64 -13q34 -7 64 -16.5t70 -32t67.5 -52.5t47.5 -80t20 -112q0 -139 -89 -224t-244 -97v-77h-100v79q-150 16 -237 103q-40 40 -52.5 93.5 t-15.5 139.5h139q5 -77 48.5 -126t117.5 -65v335l-27 8q-46 14 -79 26.5t-72 36t-63 52t-40 72.5t-16 98q0 70 25 126t67.5 92t94.5 57t110 27v77h100zM600 754v274q-29 -4 -50 -11t-42 -21.5t-31.5 -41.5t-10.5 -65q0 -29 7 -50.5t16.5 -34t28.5 -22.5t31.5 -14t37.5 -10 q9 -3 13 -4zM700 547v-310q22 2 42.5 6.5t45 15.5t41.5 27t29 42t12 59.5t-12.5 59.5t-38 44.5t-53 31t-66.5 24.5z" />
+<glyph unicode="" d="M561 1197q84 0 160.5 -40t123.5 -109.5t47 -147.5h-153q0 40 -19.5 71.5t-49.5 48.5t-59.5 26t-55.5 9q-37 0 -79 -14.5t-62 -35.5q-41 -44 -41 -101q0 -26 13.5 -63t26.5 -61t37 -66q6 -9 9 -14h241v-100h-197q8 -50 -2.5 -115t-31.5 -95q-45 -62 -99 -112 q34 10 83 17.5t71 7.5q32 1 102 -16t104 -17q83 0 136 30l50 -147q-31 -19 -58 -30.5t-55 -15.5t-42 -4.5t-46 -0.5q-23 0 -76 17t-111 32.5t-96 11.5q-39 -3 -82 -16t-67 -25l-23 -11l-55 145q4 3 16 11t15.5 10.5t13 9t15.5 12t14.5 14t17.5 18.5q48 55 54 126.5 t-30 142.5h-221v100h166q-23 47 -44 104q-7 20 -12 41.5t-6 55.5t6 66.5t29.5 70.5t58.5 71q97 88 263 88z" />
+<glyph unicode="" d="M400 300h150q21 0 25 -11t-10 -25l-230 -250q-14 -15 -35 -15t-35 15l-230 250q-14 14 -10 25t25 11h150v900h200v-900zM935 1184l230 -249q14 -14 10 -24.5t-25 -10.5h-150v-900h-200v900h-150q-21 0 -25 10.5t10 24.5l230 249q14 15 35 15t35 -15z" />
+<glyph unicode="" d="M1000 700h-100v100h-100v-100h-100v500h300v-500zM400 300h150q21 0 25 -11t-10 -25l-230 -250q-14 -15 -35 -15t-35 15l-230 250q-14 14 -10 25t25 11h150v900h200v-900zM801 1100v-200h100v200h-100zM1000 350l-200 -250h200v-100h-300v150l200 250h-200v100h300v-150z " />
+<glyph unicode="" d="M400 300h150q21 0 25 -11t-10 -25l-230 -250q-14 -15 -35 -15t-35 15l-230 250q-14 14 -10 25t25 11h150v900h200v-900zM1000 1050l-200 -250h200v-100h-300v150l200 250h-200v100h300v-150zM1000 0h-100v100h-100v-100h-100v500h300v-500zM801 400v-200h100v200h-100z " />
+<glyph unicode="" d="M400 300h150q21 0 25 -11t-10 -25l-230 -250q-14 -15 -35 -15t-35 15l-230 250q-14 14 -10 25t25 11h150v900h200v-900zM1000 700h-100v400h-100v100h200v-500zM1100 0h-100v100h-200v400h300v-500zM901 400v-200h100v200h-100z" />
+<glyph unicode="" d="M400 300h150q21 0 25 -11t-10 -25l-230 -250q-14 -15 -35 -15t-35 15l-230 250q-14 14 -10 25t25 11h150v900h200v-900zM1100 700h-100v100h-200v400h300v-500zM901 1100v-200h100v200h-100zM1000 0h-100v400h-100v100h200v-500z" />
+<glyph unicode="" d="M400 300h150q21 0 25 -11t-10 -25l-230 -250q-14 -15 -35 -15t-35 15l-230 250q-14 14 -10 25t25 11h150v900h200v-900zM900 1000h-200v200h200v-200zM1000 700h-300v200h300v-200zM1100 400h-400v200h400v-200zM1200 100h-500v200h500v-200z" />
+<glyph unicode="" d="M400 300h150q21 0 25 -11t-10 -25l-230 -250q-14 -15 -35 -15t-35 15l-230 250q-14 14 -10 25t25 11h150v900h200v-900zM1200 1000h-500v200h500v-200zM1100 700h-400v200h400v-200zM1000 400h-300v200h300v-200zM900 100h-200v200h200v-200z" />
+<glyph unicode="" d="M350 1100h400q162 0 256 -93.5t94 -256.5v-400q0 -165 -93.5 -257.5t-256.5 -92.5h-400q-165 0 -257.5 92.5t-92.5 257.5v400q0 165 92.5 257.5t257.5 92.5zM800 900h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5 v500q0 41 -29.5 70.5t-70.5 29.5z" />
+<glyph unicode="" d="M350 1100h400q165 0 257.5 -92.5t92.5 -257.5v-400q0 -165 -92.5 -257.5t-257.5 -92.5h-400q-163 0 -256.5 92.5t-93.5 257.5v400q0 163 94 256.5t256 93.5zM800 900h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5 v500q0 41 -29.5 70.5t-70.5 29.5zM440 770l253 -190q17 -12 17 -30t-17 -30l-253 -190q-16 -12 -28 -6.5t-12 26.5v400q0 21 12 26.5t28 -6.5z" />
+<glyph unicode="" d="M350 1100h400q163 0 256.5 -94t93.5 -256v-400q0 -165 -92.5 -257.5t-257.5 -92.5h-400q-165 0 -257.5 92.5t-92.5 257.5v400q0 163 92.5 256.5t257.5 93.5zM800 900h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5 v500q0 41 -29.5 70.5t-70.5 29.5zM350 700h400q21 0 26.5 -12t-6.5 -28l-190 -253q-12 -17 -30 -17t-30 17l-190 253q-12 16 -6.5 28t26.5 12z" />
+<glyph unicode="" d="M350 1100h400q165 0 257.5 -92.5t92.5 -257.5v-400q0 -163 -92.5 -256.5t-257.5 -93.5h-400q-163 0 -256.5 94t-93.5 256v400q0 165 92.5 257.5t257.5 92.5zM800 900h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5 v500q0 41 -29.5 70.5t-70.5 29.5zM580 693l190 -253q12 -16 6.5 -28t-26.5 -12h-400q-21 0 -26.5 12t6.5 28l190 253q12 17 30 17t30 -17z" />
+<glyph unicode="" d="M550 1100h400q165 0 257.5 -92.5t92.5 -257.5v-400q0 -165 -92.5 -257.5t-257.5 -92.5h-400q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5h450q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5h-450q-21 0 -35.5 14.5t-14.5 35.5v100 q0 21 14.5 35.5t35.5 14.5zM338 867l324 -284q16 -14 16 -33t-16 -33l-324 -284q-16 -14 -27 -9t-11 26v150h-250q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h250v150q0 21 11 26t27 -9z" />
+<glyph unicode="" d="M793 1182l9 -9q8 -10 5 -27q-3 -11 -79 -225.5t-78 -221.5l300 1q24 0 32.5 -17.5t-5.5 -35.5q-1 0 -133.5 -155t-267 -312.5t-138.5 -162.5q-12 -15 -26 -15h-9l-9 8q-9 11 -4 32q2 9 42 123.5t79 224.5l39 110h-302q-23 0 -31 19q-10 21 6 41q75 86 209.5 237.5 t228 257t98.5 111.5q9 16 25 16h9z" />
+<glyph unicode="" d="M350 1100h400q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-450q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h450q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-165 0 -257.5 92.5t-92.5 257.5v400 q0 165 92.5 257.5t257.5 92.5zM938 867l324 -284q16 -14 16 -33t-16 -33l-324 -284q-16 -14 -27 -9t-11 26v150h-250q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h250v150q0 21 11 26t27 -9z" />
+<glyph unicode="" d="M750 1200h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -10.5 -25t-24.5 10l-109 109l-312 -312q-15 -15 -35.5 -15t-35.5 15l-141 141q-15 15 -15 35.5t15 35.5l312 312l-109 109q-14 14 -10 24.5t25 10.5zM456 900h-156q-41 0 -70.5 -29.5t-29.5 -70.5v-500 q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v148l200 200v-298q0 -165 -93.5 -257.5t-256.5 -92.5h-400q-165 0 -257.5 92.5t-92.5 257.5v400q0 165 92.5 257.5t257.5 92.5h300z" />
+<glyph unicode="" d="M600 1186q119 0 227.5 -46.5t187 -125t125 -187t46.5 -227.5t-46.5 -227.5t-125 -187t-187 -125t-227.5 -46.5t-227.5 46.5t-187 125t-125 187t-46.5 227.5t46.5 227.5t125 187t187 125t227.5 46.5zM600 1022q-115 0 -212 -56.5t-153.5 -153.5t-56.5 -212t56.5 -212 t153.5 -153.5t212 -56.5t212 56.5t153.5 153.5t56.5 212t-56.5 212t-153.5 153.5t-212 56.5zM600 794q80 0 137 -57t57 -137t-57 -137t-137 -57t-137 57t-57 137t57 137t137 57z" />
+<glyph unicode="" d="M450 1200h200q21 0 35.5 -14.5t14.5 -35.5v-350h245q20 0 25 -11t-9 -26l-383 -426q-14 -15 -33.5 -15t-32.5 15l-379 426q-13 15 -8.5 26t25.5 11h250v350q0 21 14.5 35.5t35.5 14.5zM50 300h1000q21 0 35.5 -14.5t14.5 -35.5v-250h-1100v250q0 21 14.5 35.5t35.5 14.5z M900 200v-50h100v50h-100z" />
+<glyph unicode="" d="M583 1182l378 -435q14 -15 9 -31t-26 -16h-244v-250q0 -20 -17 -35t-39 -15h-200q-20 0 -32 14.5t-12 35.5v250h-250q-20 0 -25.5 16.5t8.5 31.5l383 431q14 16 33.5 17t33.5 -14zM50 300h1000q21 0 35.5 -14.5t14.5 -35.5v-250h-1100v250q0 21 14.5 35.5t35.5 14.5z M900 200v-50h100v50h-100z" />
+<glyph unicode="" d="M396 723l369 369q7 7 17.5 7t17.5 -7l139 -139q7 -8 7 -18.5t-7 -17.5l-525 -525q-7 -8 -17.5 -8t-17.5 8l-292 291q-7 8 -7 18t7 18l139 139q8 7 18.5 7t17.5 -7zM50 300h1000q21 0 35.5 -14.5t14.5 -35.5v-250h-1100v250q0 21 14.5 35.5t35.5 14.5zM900 200v-50h100v50 h-100z" />
+<glyph unicode="" d="M135 1023l142 142q14 14 35 14t35 -14l77 -77l-212 -212l-77 76q-14 15 -14 36t14 35zM655 855l210 210q14 14 24.5 10t10.5 -25l-2 -599q-1 -20 -15.5 -35t-35.5 -15l-597 -1q-21 0 -25 10.5t10 24.5l208 208l-154 155l212 212zM50 300h1000q21 0 35.5 -14.5t14.5 -35.5 v-250h-1100v250q0 21 14.5 35.5t35.5 14.5zM900 200v-50h100v50h-100z" />
+<glyph unicode="" d="M350 1200l599 -2q20 -1 35 -15.5t15 -35.5l1 -597q0 -21 -10.5 -25t-24.5 10l-208 208l-155 -154l-212 212l155 154l-210 210q-14 14 -10 24.5t25 10.5zM524 512l-76 -77q-15 -14 -36 -14t-35 14l-142 142q-14 14 -14 35t14 35l77 77zM50 300h1000q21 0 35.5 -14.5 t14.5 -35.5v-250h-1100v250q0 21 14.5 35.5t35.5 14.5zM900 200v-50h100v50h-100z" />
+<glyph unicode="" d="M1200 103l-483 276l-314 -399v423h-399l1196 796v-1096zM483 424v-230l683 953z" />
+<glyph unicode="" d="M1100 1000v-850q0 -21 -14.5 -35.5t-35.5 -14.5h-150v400h-700v-400h-150q-21 0 -35.5 14.5t-14.5 35.5v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100zM700 1000h-100v200h100v-200z" />
+<glyph unicode="" d="M1100 1000l-2 -149l-299 -299l-95 95q-9 9 -21.5 9t-21.5 -9l-149 -147h-312v-400h-150q-21 0 -35.5 14.5t-14.5 35.5v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100zM700 1000h-100v200h100v-200zM1132 638l106 -106q7 -7 7 -17.5t-7 -17.5l-420 -421q-8 -7 -18 -7 t-18 7l-202 203q-8 7 -8 17.5t8 17.5l106 106q7 8 17.5 8t17.5 -8l79 -79l297 297q7 7 17.5 7t17.5 -7z" />
+<glyph unicode="" d="M1100 1000v-269l-103 -103l-134 134q-15 15 -33.5 16.5t-34.5 -12.5l-266 -266h-329v-400h-150q-21 0 -35.5 14.5t-14.5 35.5v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100zM700 1000h-100v200h100v-200zM1202 572l70 -70q15 -15 15 -35.5t-15 -35.5l-131 -131 l131 -131q15 -15 15 -35.5t-15 -35.5l-70 -70q-15 -15 -35.5 -15t-35.5 15l-131 131l-131 -131q-15 -15 -35.5 -15t-35.5 15l-70 70q-15 15 -15 35.5t15 35.5l131 131l-131 131q-15 15 -15 35.5t15 35.5l70 70q15 15 35.5 15t35.5 -15l131 -131l131 131q15 15 35.5 15 t35.5 -15z" />
+<glyph unicode="" d="M1100 1000v-300h-350q-21 0 -35.5 -14.5t-14.5 -35.5v-150h-500v-400h-150q-21 0 -35.5 14.5t-14.5 35.5v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100zM700 1000h-100v200h100v-200zM850 600h100q21 0 35.5 -14.5t14.5 -35.5v-250h150q21 0 25 -10.5t-10 -24.5 l-230 -230q-14 -14 -35 -14t-35 14l-230 230q-14 14 -10 24.5t25 10.5h150v250q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M1100 1000v-400l-165 165q-14 15 -35 15t-35 -15l-263 -265h-402v-400h-150q-21 0 -35.5 14.5t-14.5 35.5v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100zM700 1000h-100v200h100v-200zM935 565l230 -229q14 -15 10 -25.5t-25 -10.5h-150v-250q0 -20 -14.5 -35 t-35.5 -15h-100q-21 0 -35.5 15t-14.5 35v250h-150q-21 0 -25 10.5t10 25.5l230 229q14 15 35 15t35 -15z" />
+<glyph unicode="" d="M50 1100h1100q21 0 35.5 -14.5t14.5 -35.5v-150h-1200v150q0 21 14.5 35.5t35.5 14.5zM1200 800v-550q0 -21 -14.5 -35.5t-35.5 -14.5h-1100q-21 0 -35.5 14.5t-14.5 35.5v550h1200zM100 500v-200h400v200h-400z" />
+<glyph unicode="" d="M935 1165l248 -230q14 -14 14 -35t-14 -35l-248 -230q-14 -14 -24.5 -10t-10.5 25v150h-400v200h400v150q0 21 10.5 25t24.5 -10zM200 800h-50q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5h50v-200zM400 800h-100v200h100v-200zM18 435l247 230 q14 14 24.5 10t10.5 -25v-150h400v-200h-400v-150q0 -21 -10.5 -25t-24.5 10l-247 230q-15 14 -15 35t15 35zM900 300h-100v200h100v-200zM1000 500h51q20 0 34.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-34.5 -14.5h-51v200z" />
+<glyph unicode="" d="M862 1073l276 116q25 18 43.5 8t18.5 -41v-1106q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v397q-4 1 -11 5t-24 17.5t-30 29t-24 42t-11 56.5v359q0 31 18.5 65t43.5 52zM550 1200q22 0 34.5 -12.5t14.5 -24.5l1 -13v-450q0 -28 -10.5 -59.5 t-25 -56t-29 -45t-25.5 -31.5l-10 -11v-447q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v447q-4 4 -11 11.5t-24 30.5t-30 46t-24 55t-11 60v450q0 2 0.5 5.5t4 12t8.5 15t14.5 12t22.5 5.5q20 0 32.5 -12.5t14.5 -24.5l3 -13v-350h100v350v5.5t2.5 12 t7 15t15 12t25.5 5.5q23 0 35.5 -12.5t13.5 -24.5l1 -13v-350h100v350q0 2 0.5 5.5t3 12t7 15t15 12t24.5 5.5z" />
+<glyph unicode="" d="M1200 1100v-56q-4 0 -11 -0.5t-24 -3t-30 -7.5t-24 -15t-11 -24v-888q0 -22 25 -34.5t50 -13.5l25 -2v-56h-400v56q75 0 87.5 6.5t12.5 43.5v394h-500v-394q0 -37 12.5 -43.5t87.5 -6.5v-56h-400v56q4 0 11 0.5t24 3t30 7.5t24 15t11 24v888q0 22 -25 34.5t-50 13.5 l-25 2v56h400v-56q-75 0 -87.5 -6.5t-12.5 -43.5v-394h500v394q0 37 -12.5 43.5t-87.5 6.5v56h400z" />
+<glyph unicode="" d="M675 1000h375q21 0 35.5 -14.5t14.5 -35.5v-150h-105l-295 -98v98l-200 200h-400l100 100h375zM100 900h300q41 0 70.5 -29.5t29.5 -70.5v-500q0 -41 -29.5 -70.5t-70.5 -29.5h-300q-41 0 -70.5 29.5t-29.5 70.5v500q0 41 29.5 70.5t70.5 29.5zM100 800v-200h300v200 h-300zM1100 535l-400 -133v163l400 133v-163zM100 500v-200h300v200h-300zM1100 398v-248q0 -21 -14.5 -35.5t-35.5 -14.5h-375l-100 -100h-375l-100 100h400l200 200h105z" />
+<glyph unicode="" d="M17 1007l162 162q17 17 40 14t37 -22l139 -194q14 -20 11 -44.5t-20 -41.5l-119 -118q102 -142 228 -268t267 -227l119 118q17 17 42.5 19t44.5 -12l192 -136q19 -14 22.5 -37.5t-13.5 -40.5l-163 -162q-3 -1 -9.5 -1t-29.5 2t-47.5 6t-62.5 14.5t-77.5 26.5t-90 42.5 t-101.5 60t-111 83t-119 108.5q-74 74 -133.5 150.5t-94.5 138.5t-60 119.5t-34.5 100t-15 74.5t-4.5 48z" />
+<glyph unicode="" d="M600 1100q92 0 175 -10.5t141.5 -27t108.5 -36.5t81.5 -40t53.5 -37t31 -27l9 -10v-200q0 -21 -14.5 -33t-34.5 -9l-202 34q-20 3 -34.5 20t-14.5 38v146q-141 24 -300 24t-300 -24v-146q0 -21 -14.5 -38t-34.5 -20l-202 -34q-20 -3 -34.5 9t-14.5 33v200q3 4 9.5 10.5 t31 26t54 37.5t80.5 39.5t109 37.5t141 26.5t175 10.5zM600 795q56 0 97 -9.5t60 -23.5t30 -28t12 -24l1 -10v-50l365 -303q14 -15 24.5 -40t10.5 -45v-212q0 -21 -14.5 -35.5t-35.5 -14.5h-1100q-21 0 -35.5 14.5t-14.5 35.5v212q0 20 10.5 45t24.5 40l365 303v50 q0 4 1 10.5t12 23t30 29t60 22.5t97 10z" />
+<glyph unicode="" d="M1100 700l-200 -200h-600l-200 200v500h200v-200h200v200h200v-200h200v200h200v-500zM250 400h700q21 0 35.5 -14.5t14.5 -35.5t-14.5 -35.5t-35.5 -14.5h-12l137 -100h-950l137 100h-12q-21 0 -35.5 14.5t-14.5 35.5t14.5 35.5t35.5 14.5zM50 100h1100q21 0 35.5 -14.5 t14.5 -35.5v-50h-1200v50q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M700 1100h-100q-41 0 -70.5 -29.5t-29.5 -70.5v-1000h300v1000q0 41 -29.5 70.5t-70.5 29.5zM1100 800h-100q-41 0 -70.5 -29.5t-29.5 -70.5v-700h300v700q0 41 -29.5 70.5t-70.5 29.5zM400 0h-300v400q0 41 29.5 70.5t70.5 29.5h100q41 0 70.5 -29.5t29.5 -70.5v-400z " />
+<glyph unicode="" d="M200 1100h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88zM100 900v-700h900v700h-900zM500 700h-200v-100h200v-300h-300v100h200v100h-200v300h300v-100zM900 700v-300l-100 -100h-200v500h200z M700 700v-300h100v300h-100z" />
+<glyph unicode="" d="M200 1100h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88zM100 900v-700h900v700h-900zM500 300h-100v200h-100v-200h-100v500h100v-200h100v200h100v-500zM900 700v-300l-100 -100h-200v500h200z M700 700v-300h100v300h-100z" />
+<glyph unicode="" d="M200 1100h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88zM100 900v-700h900v700h-900zM500 700h-200v-300h200v-100h-300v500h300v-100zM900 700h-200v-300h200v-100h-300v500h300v-100z" />
+<glyph unicode="" d="M200 1100h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88zM100 900v-700h900v700h-900zM500 400l-300 150l300 150v-300zM900 550l-300 -150v300z" />
+<glyph unicode="" d="M200 1100h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88zM100 900v-700h900v700h-900zM900 300h-700v500h700v-500zM800 700h-130q-38 0 -66.5 -43t-28.5 -108t27 -107t68 -42h130v300zM300 700v-300 h130q41 0 68 42t27 107t-28.5 108t-66.5 43h-130z" />
+<glyph unicode="" d="M200 1100h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88zM100 900v-700h900v700h-900zM500 700h-200v-100h200v-300h-300v100h200v100h-200v300h300v-100zM900 300h-100v400h-100v100h200v-500z M700 300h-100v100h100v-100z" />
+<glyph unicode="" d="M200 1100h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88zM100 900v-700h900v700h-900zM300 700h200v-400h-300v500h100v-100zM900 300h-100v400h-100v100h200v-500zM300 600v-200h100v200h-100z M700 300h-100v100h100v-100z" />
+<glyph unicode="" d="M200 1100h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88zM100 900v-700h900v700h-900zM500 500l-199 -200h-100v50l199 200v150h-200v100h300v-300zM900 300h-100v400h-100v100h200v-500zM701 300h-100 v100h100v-100z" />
+<glyph unicode="" d="M600 1191q120 0 229.5 -47t188.5 -126t126 -188.5t47 -229.5t-47 -229.5t-126 -188.5t-188.5 -126t-229.5 -47t-229.5 47t-188.5 126t-126 188.5t-47 229.5t47 229.5t126 188.5t188.5 126t229.5 47zM600 1021q-114 0 -211 -56.5t-153.5 -153.5t-56.5 -211t56.5 -211 t153.5 -153.5t211 -56.5t211 56.5t153.5 153.5t56.5 211t-56.5 211t-153.5 153.5t-211 56.5zM800 700h-300v-200h300v-100h-300l-100 100v200l100 100h300v-100z" />
+<glyph unicode="" d="M600 1191q120 0 229.5 -47t188.5 -126t126 -188.5t47 -229.5t-47 -229.5t-126 -188.5t-188.5 -126t-229.5 -47t-229.5 47t-188.5 126t-126 188.5t-47 229.5t47 229.5t126 188.5t188.5 126t229.5 47zM600 1021q-114 0 -211 -56.5t-153.5 -153.5t-56.5 -211t56.5 -211 t153.5 -153.5t211 -56.5t211 56.5t153.5 153.5t56.5 211t-56.5 211t-153.5 153.5t-211 56.5zM800 700v-100l-50 -50l100 -100v-50h-100l-100 100h-150v-100h-100v400h300zM500 700v-100h200v100h-200z" />
+<glyph unicode="" d="M503 1089q110 0 200.5 -59.5t134.5 -156.5q44 14 90 14q120 0 205 -86.5t85 -207t-85 -207t-205 -86.5h-128v250q0 21 -14.5 35.5t-35.5 14.5h-300q-21 0 -35.5 -14.5t-14.5 -35.5v-250h-222q-80 0 -136 57.5t-56 136.5q0 69 43 122.5t108 67.5q-2 19 -2 37q0 100 49 185 t134 134t185 49zM525 500h150q10 0 17.5 -7.5t7.5 -17.5v-275h137q21 0 26 -11.5t-8 -27.5l-223 -244q-13 -16 -32 -16t-32 16l-223 244q-13 16 -8 27.5t26 11.5h137v275q0 10 7.5 17.5t17.5 7.5z" />
+<glyph unicode="" d="M502 1089q110 0 201 -59.5t135 -156.5q43 15 89 15q121 0 206 -86.5t86 -206.5q0 -99 -60 -181t-150 -110l-378 360q-13 16 -31.5 16t-31.5 -16l-381 -365h-9q-79 0 -135.5 57.5t-56.5 136.5q0 69 43 122.5t108 67.5q-2 19 -2 38q0 100 49 184.5t133.5 134t184.5 49.5z M632 467l223 -228q13 -16 8 -27.5t-26 -11.5h-137v-275q0 -10 -7.5 -17.5t-17.5 -7.5h-150q-10 0 -17.5 7.5t-7.5 17.5v275h-137q-21 0 -26 11.5t8 27.5q199 204 223 228q19 19 31.5 19t32.5 -19z" />
+<glyph unicode="" d="M700 100v100h400l-270 300h170l-270 300h170l-300 333l-300 -333h170l-270 -300h170l-270 -300h400v-100h-50q-21 0 -35.5 -14.5t-14.5 -35.5v-50h400v50q0 21 -14.5 35.5t-35.5 14.5h-50z" />
+<glyph unicode="" d="M600 1179q94 0 167.5 -56.5t99.5 -145.5q89 -6 150.5 -71.5t61.5 -155.5q0 -61 -29.5 -112.5t-79.5 -82.5q9 -29 9 -55q0 -74 -52.5 -126.5t-126.5 -52.5q-55 0 -100 30v-251q21 0 35.5 -14.5t14.5 -35.5v-50h-300v50q0 21 14.5 35.5t35.5 14.5v251q-45 -30 -100 -30 q-74 0 -126.5 52.5t-52.5 126.5q0 18 4 38q-47 21 -75.5 65t-28.5 97q0 74 52.5 126.5t126.5 52.5q5 0 23 -2q0 2 -1 10t-1 13q0 116 81.5 197.5t197.5 81.5z" />
+<glyph unicode="" d="M1010 1010q111 -111 150.5 -260.5t0 -299t-150.5 -260.5q-83 -83 -191.5 -126.5t-218.5 -43.5t-218.5 43.5t-191.5 126.5q-111 111 -150.5 260.5t0 299t150.5 260.5q83 83 191.5 126.5t218.5 43.5t218.5 -43.5t191.5 -126.5zM476 1065q-4 0 -8 -1q-121 -34 -209.5 -122.5 t-122.5 -209.5q-4 -12 2.5 -23t18.5 -14l36 -9q3 -1 7 -1q23 0 29 22q27 96 98 166q70 71 166 98q11 3 17.5 13.5t3.5 22.5l-9 35q-3 13 -14 19q-7 4 -15 4zM512 920q-4 0 -9 -2q-80 -24 -138.5 -82.5t-82.5 -138.5q-4 -13 2 -24t19 -14l34 -9q4 -1 8 -1q22 0 28 21 q18 58 58.5 98.5t97.5 58.5q12 3 18 13.5t3 21.5l-9 35q-3 12 -14 19q-7 4 -15 4zM719.5 719.5q-49.5 49.5 -119.5 49.5t-119.5 -49.5t-49.5 -119.5t49.5 -119.5t119.5 -49.5t119.5 49.5t49.5 119.5t-49.5 119.5zM855 551q-22 0 -28 -21q-18 -58 -58.5 -98.5t-98.5 -57.5 q-11 -4 -17 -14.5t-3 -21.5l9 -35q3 -12 14 -19q7 -4 15 -4q4 0 9 2q80 24 138.5 82.5t82.5 138.5q4 13 -2.5 24t-18.5 14l-34 9q-4 1 -8 1zM1000 515q-23 0 -29 -22q-27 -96 -98 -166q-70 -71 -166 -98q-11 -3 -17.5 -13.5t-3.5 -22.5l9 -35q3 -13 14 -19q7 -4 15 -4 q4 0 8 1q121 34 209.5 122.5t122.5 209.5q4 12 -2.5 23t-18.5 14l-36 9q-3 1 -7 1z" />
+<glyph unicode="" d="M700 800h300v-380h-180v200h-340v-200h-380v755q0 10 7.5 17.5t17.5 7.5h575v-400zM1000 900h-200v200zM700 300h162l-212 -212l-212 212h162v200h100v-200zM520 0h-395q-10 0 -17.5 7.5t-7.5 17.5v395zM1000 220v-195q0 -10 -7.5 -17.5t-17.5 -7.5h-195z" />
+<glyph unicode="" d="M700 800h300v-520l-350 350l-550 -550v1095q0 10 7.5 17.5t17.5 7.5h575v-400zM1000 900h-200v200zM862 200h-162v-200h-100v200h-162l212 212zM480 0h-355q-10 0 -17.5 7.5t-7.5 17.5v55h380v-80zM1000 80v-55q0 -10 -7.5 -17.5t-17.5 -7.5h-155v80h180z" />
+<glyph unicode="" d="M1162 800h-162v-200h100l100 -100h-300v300h-162l212 212zM200 800h200q27 0 40 -2t29.5 -10.5t23.5 -30t7 -57.5h300v-100h-600l-200 -350v450h100q0 36 7 57.5t23.5 30t29.5 10.5t40 2zM800 400h240l-240 -400h-800l300 500h500v-100z" />
+<glyph unicode="" d="M650 1100h100q21 0 35.5 -14.5t14.5 -35.5v-50h50q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-300q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5h50v50q0 21 14.5 35.5t35.5 14.5zM1000 850v150q41 0 70.5 -29.5t29.5 -70.5v-800 q0 -41 -29.5 -70.5t-70.5 -29.5h-600q-1 0 -20 4l246 246l-326 326v324q0 41 29.5 70.5t70.5 29.5v-150q0 -62 44 -106t106 -44h300q62 0 106 44t44 106zM412 250l-212 -212v162h-200v100h200v162z" />
+<glyph unicode="" d="M450 1100h100q21 0 35.5 -14.5t14.5 -35.5v-50h50q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-300q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5h50v50q0 21 14.5 35.5t35.5 14.5zM800 850v150q41 0 70.5 -29.5t29.5 -70.5v-500 h-200v-300h200q0 -36 -7 -57.5t-23.5 -30t-29.5 -10.5t-40 -2h-600q-41 0 -70.5 29.5t-29.5 70.5v800q0 41 29.5 70.5t70.5 29.5v-150q0 -62 44 -106t106 -44h300q62 0 106 44t44 106zM1212 250l-212 -212v162h-200v100h200v162z" />
+<glyph unicode="" d="M658 1197l637 -1104q23 -38 7 -65.5t-60 -27.5h-1276q-44 0 -60 27.5t7 65.5l637 1104q22 39 54 39t54 -39zM704 800h-208q-20 0 -32 -14.5t-8 -34.5l58 -302q4 -20 21.5 -34.5t37.5 -14.5h54q20 0 37.5 14.5t21.5 34.5l58 302q4 20 -8 34.5t-32 14.5zM500 300v-100h200 v100h-200z" />
+<glyph unicode="" d="M425 1100h250q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-250q-10 0 -17.5 7.5t-7.5 17.5v150q0 10 7.5 17.5t17.5 7.5zM425 800h250q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-250q-10 0 -17.5 7.5t-7.5 17.5v150q0 10 7.5 17.5 t17.5 7.5zM825 800h250q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-250q-10 0 -17.5 7.5t-7.5 17.5v150q0 10 7.5 17.5t17.5 7.5zM25 500h250q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-250q-10 0 -17.5 7.5t-7.5 17.5v150 q0 10 7.5 17.5t17.5 7.5zM425 500h250q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-250q-10 0 -17.5 7.5t-7.5 17.5v150q0 10 7.5 17.5t17.5 7.5zM825 500h250q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-250q-10 0 -17.5 7.5t-7.5 17.5 v150q0 10 7.5 17.5t17.5 7.5zM25 200h250q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-250q-10 0 -17.5 7.5t-7.5 17.5v150q0 10 7.5 17.5t17.5 7.5zM425 200h250q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-250q-10 0 -17.5 7.5 t-7.5 17.5v150q0 10 7.5 17.5t17.5 7.5zM825 200h250q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-250q-10 0 -17.5 7.5t-7.5 17.5v150q0 10 7.5 17.5t17.5 7.5z" />
+<glyph unicode="" d="M700 1200h100v-200h-100v-100h350q62 0 86.5 -39.5t-3.5 -94.5l-66 -132q-41 -83 -81 -134h-772q-40 51 -81 134l-66 132q-28 55 -3.5 94.5t86.5 39.5h350v100h-100v200h100v100h200v-100zM250 400h700q21 0 35.5 -14.5t14.5 -35.5t-14.5 -35.5t-35.5 -14.5h-12l137 -100 h-950l138 100h-13q-21 0 -35.5 14.5t-14.5 35.5t14.5 35.5t35.5 14.5zM50 100h1100q21 0 35.5 -14.5t14.5 -35.5v-50h-1200v50q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M600 1300q40 0 68.5 -29.5t28.5 -70.5h-194q0 41 28.5 70.5t68.5 29.5zM443 1100h314q18 -37 18 -75q0 -8 -3 -25h328q41 0 44.5 -16.5t-30.5 -38.5l-175 -145h-678l-178 145q-34 22 -29 38.5t46 16.5h328q-3 17 -3 25q0 38 18 75zM250 700h700q21 0 35.5 -14.5 t14.5 -35.5t-14.5 -35.5t-35.5 -14.5h-150v-200l275 -200h-950l275 200v200h-150q-21 0 -35.5 14.5t-14.5 35.5t14.5 35.5t35.5 14.5zM50 100h1100q21 0 35.5 -14.5t14.5 -35.5v-50h-1200v50q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M600 1181q75 0 128 -53t53 -128t-53 -128t-128 -53t-128 53t-53 128t53 128t128 53zM602 798h46q34 0 55.5 -28.5t21.5 -86.5q0 -76 39 -183h-324q39 107 39 183q0 58 21.5 86.5t56.5 28.5h45zM250 400h700q21 0 35.5 -14.5t14.5 -35.5t-14.5 -35.5t-35.5 -14.5h-13 l138 -100h-950l137 100h-12q-21 0 -35.5 14.5t-14.5 35.5t14.5 35.5t35.5 14.5zM50 100h1100q21 0 35.5 -14.5t14.5 -35.5v-50h-1200v50q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M600 1300q47 0 92.5 -53.5t71 -123t25.5 -123.5q0 -78 -55.5 -133.5t-133.5 -55.5t-133.5 55.5t-55.5 133.5q0 62 34 143l144 -143l111 111l-163 163q34 26 63 26zM602 798h46q34 0 55.5 -28.5t21.5 -86.5q0 -76 39 -183h-324q39 107 39 183q0 58 21.5 86.5t56.5 28.5h45 zM250 400h700q21 0 35.5 -14.5t14.5 -35.5t-14.5 -35.5t-35.5 -14.5h-13l138 -100h-950l137 100h-12q-21 0 -35.5 14.5t-14.5 35.5t14.5 35.5t35.5 14.5zM50 100h1100q21 0 35.5 -14.5t14.5 -35.5v-50h-1200v50q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M600 1200l300 -161v-139h-300q0 -57 18.5 -108t50 -91.5t63 -72t70 -67.5t57.5 -61h-530q-60 83 -90.5 177.5t-30.5 178.5t33 164.5t87.5 139.5t126 96.5t145.5 41.5v-98zM250 400h700q21 0 35.5 -14.5t14.5 -35.5t-14.5 -35.5t-35.5 -14.5h-13l138 -100h-950l137 100 h-12q-21 0 -35.5 14.5t-14.5 35.5t14.5 35.5t35.5 14.5zM50 100h1100q21 0 35.5 -14.5t14.5 -35.5v-50h-1200v50q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M600 1300q41 0 70.5 -29.5t29.5 -70.5v-78q46 -26 73 -72t27 -100v-50h-400v50q0 54 27 100t73 72v78q0 41 29.5 70.5t70.5 29.5zM400 800h400q54 0 100 -27t72 -73h-172v-100h200v-100h-200v-100h200v-100h-200v-100h200q0 -83 -58.5 -141.5t-141.5 -58.5h-400 q-83 0 -141.5 58.5t-58.5 141.5v400q0 83 58.5 141.5t141.5 58.5z" />
+<glyph unicode="" d="M150 1100h900q21 0 35.5 -14.5t14.5 -35.5v-500q0 -21 -14.5 -35.5t-35.5 -14.5h-900q-21 0 -35.5 14.5t-14.5 35.5v500q0 21 14.5 35.5t35.5 14.5zM125 400h950q10 0 17.5 -7.5t7.5 -17.5v-50q0 -10 -7.5 -17.5t-17.5 -7.5h-283l224 -224q13 -13 13 -31.5t-13 -32 t-31.5 -13.5t-31.5 13l-88 88h-524l-87 -88q-13 -13 -32 -13t-32 13.5t-13 32t13 31.5l224 224h-289q-10 0 -17.5 7.5t-7.5 17.5v50q0 10 7.5 17.5t17.5 7.5zM541 300l-100 -100h324l-100 100h-124z" />
+<glyph unicode="" d="M200 1100h800q83 0 141.5 -58.5t58.5 -141.5v-200h-100q0 41 -29.5 70.5t-70.5 29.5h-250q-41 0 -70.5 -29.5t-29.5 -70.5h-100q0 41 -29.5 70.5t-70.5 29.5h-250q-41 0 -70.5 -29.5t-29.5 -70.5h-100v200q0 83 58.5 141.5t141.5 58.5zM100 600h1000q41 0 70.5 -29.5 t29.5 -70.5v-300h-1200v300q0 41 29.5 70.5t70.5 29.5zM300 100v-50q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v50h200zM1100 100v-50q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v50h200z" />
+<glyph unicode="" d="M480 1165l682 -683q31 -31 31 -75.5t-31 -75.5l-131 -131h-481l-517 518q-32 31 -32 75.5t32 75.5l295 296q31 31 75.5 31t76.5 -31zM108 794l342 -342l303 304l-341 341zM250 100h800q21 0 35.5 -14.5t14.5 -35.5v-50h-900v50q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M1057 647l-189 506q-8 19 -27.5 33t-40.5 14h-400q-21 0 -40.5 -14t-27.5 -33l-189 -506q-8 -19 1.5 -33t30.5 -14h625v-150q0 -21 14.5 -35.5t35.5 -14.5t35.5 14.5t14.5 35.5v150h125q21 0 30.5 14t1.5 33zM897 0h-595v50q0 21 14.5 35.5t35.5 14.5h50v50 q0 21 14.5 35.5t35.5 14.5h48v300h200v-300h47q21 0 35.5 -14.5t14.5 -35.5v-50h50q21 0 35.5 -14.5t14.5 -35.5v-50z" />
+<glyph unicode="" d="M900 800h300v-575q0 -10 -7.5 -17.5t-17.5 -7.5h-375v591l-300 300v84q0 10 7.5 17.5t17.5 7.5h375v-400zM1200 900h-200v200zM400 600h300v-575q0 -10 -7.5 -17.5t-17.5 -7.5h-650q-10 0 -17.5 7.5t-7.5 17.5v950q0 10 7.5 17.5t17.5 7.5h375v-400zM700 700h-200v200z " />
+<glyph unicode="" d="M484 1095h195q75 0 146 -32.5t124 -86t89.5 -122.5t48.5 -142q18 -14 35 -20q31 -10 64.5 6.5t43.5 48.5q10 34 -15 71q-19 27 -9 43q5 8 12.5 11t19 -1t23.5 -16q41 -44 39 -105q-3 -63 -46 -106.5t-104 -43.5h-62q-7 -55 -35 -117t-56 -100l-39 -234q-3 -20 -20 -34.5 t-38 -14.5h-100q-21 0 -33 14.5t-9 34.5l12 70q-49 -14 -91 -14h-195q-24 0 -65 8l-11 -64q-3 -20 -20 -34.5t-38 -14.5h-100q-21 0 -33 14.5t-9 34.5l26 157q-84 74 -128 175l-159 53q-19 7 -33 26t-14 40v50q0 21 14.5 35.5t35.5 14.5h124q11 87 56 166l-111 95 q-16 14 -12.5 23.5t24.5 9.5h203q116 101 250 101zM675 1000h-250q-10 0 -17.5 -7.5t-7.5 -17.5v-50q0 -10 7.5 -17.5t17.5 -7.5h250q10 0 17.5 7.5t7.5 17.5v50q0 10 -7.5 17.5t-17.5 7.5z" />
+<glyph unicode="" d="M641 900l423 247q19 8 42 2.5t37 -21.5l32 -38q14 -15 12.5 -36t-17.5 -34l-139 -120h-390zM50 1100h106q67 0 103 -17t66 -71l102 -212h823q21 0 35.5 -14.5t14.5 -35.5v-50q0 -21 -14 -40t-33 -26l-737 -132q-23 -4 -40 6t-26 25q-42 67 -100 67h-300q-62 0 -106 44 t-44 106v200q0 62 44 106t106 44zM173 928h-80q-19 0 -28 -14t-9 -35v-56q0 -51 42 -51h134q16 0 21.5 8t5.5 24q0 11 -16 45t-27 51q-18 28 -43 28zM550 727q-32 0 -54.5 -22.5t-22.5 -54.5t22.5 -54.5t54.5 -22.5t54.5 22.5t22.5 54.5t-22.5 54.5t-54.5 22.5zM130 389 l152 130q18 19 34 24t31 -3.5t24.5 -17.5t25.5 -28q28 -35 50.5 -51t48.5 -13l63 5l48 -179q13 -61 -3.5 -97.5t-67.5 -79.5l-80 -69q-47 -40 -109 -35.5t-103 51.5l-130 151q-40 47 -35.5 109.5t51.5 102.5zM380 377l-102 -88q-31 -27 2 -65l37 -43q13 -15 27.5 -19.5 t31.5 6.5l61 53q19 16 14 49q-2 20 -12 56t-17 45q-11 12 -19 14t-23 -8z" />
+<glyph unicode="" d="M625 1200h150q10 0 17.5 -7.5t7.5 -17.5v-109q79 -33 131 -87.5t53 -128.5q1 -46 -15 -84.5t-39 -61t-46 -38t-39 -21.5l-17 -6q6 0 15 -1.5t35 -9t50 -17.5t53 -30t50 -45t35.5 -64t14.5 -84q0 -59 -11.5 -105.5t-28.5 -76.5t-44 -51t-49.5 -31.5t-54.5 -16t-49.5 -6.5 t-43.5 -1v-75q0 -10 -7.5 -17.5t-17.5 -7.5h-150q-10 0 -17.5 7.5t-7.5 17.5v75h-100v-75q0 -10 -7.5 -17.5t-17.5 -7.5h-150q-10 0 -17.5 7.5t-7.5 17.5v75h-175q-10 0 -17.5 7.5t-7.5 17.5v150q0 10 7.5 17.5t17.5 7.5h75v600h-75q-10 0 -17.5 7.5t-7.5 17.5v150 q0 10 7.5 17.5t17.5 7.5h175v75q0 10 7.5 17.5t17.5 7.5h150q10 0 17.5 -7.5t7.5 -17.5v-75h100v75q0 10 7.5 17.5t17.5 7.5zM400 900v-200h263q28 0 48.5 10.5t30 25t15 29t5.5 25.5l1 10q0 4 -0.5 11t-6 24t-15 30t-30 24t-48.5 11h-263zM400 500v-200h363q28 0 48.5 10.5 t30 25t15 29t5.5 25.5l1 10q0 4 -0.5 11t-6 24t-15 30t-30 24t-48.5 11h-363z" />
+<glyph unicode="" d="M212 1198h780q86 0 147 -61t61 -147v-416q0 -51 -18 -142.5t-36 -157.5l-18 -66q-29 -87 -93.5 -146.5t-146.5 -59.5h-572q-82 0 -147 59t-93 147q-8 28 -20 73t-32 143.5t-20 149.5v416q0 86 61 147t147 61zM600 1045q-70 0 -132.5 -11.5t-105.5 -30.5t-78.5 -41.5 t-57 -45t-36 -41t-20.5 -30.5l-6 -12l156 -243h560l156 243q-2 5 -6 12.5t-20 29.5t-36.5 42t-57 44.5t-79 42t-105 29.5t-132.5 12zM762 703h-157l195 261z" />
+<glyph unicode="" d="M475 1300h150q103 0 189 -86t86 -189v-500q0 -41 -42 -83t-83 -42h-450q-41 0 -83 42t-42 83v500q0 103 86 189t189 86zM700 300v-225q0 -21 -27 -48t-48 -27h-150q-21 0 -48 27t-27 48v225h300z" />
+<glyph unicode="" d="M475 1300h96q0 -150 89.5 -239.5t239.5 -89.5v-446q0 -41 -42 -83t-83 -42h-450q-41 0 -83 42t-42 83v500q0 103 86 189t189 86zM700 300v-225q0 -21 -27 -48t-48 -27h-150q-21 0 -48 27t-27 48v225h300z" />
+<glyph unicode="" d="M1294 767l-638 -283l-378 170l-78 -60v-224l100 -150v-199l-150 148l-150 -149v200l100 150v250q0 4 -0.5 10.5t0 9.5t1 8t3 8t6.5 6l47 40l-147 65l642 283zM1000 380l-350 -166l-350 166v147l350 -165l350 165v-147z" />
+<glyph unicode="" d="M250 800q62 0 106 -44t44 -106t-44 -106t-106 -44t-106 44t-44 106t44 106t106 44zM650 800q62 0 106 -44t44 -106t-44 -106t-106 -44t-106 44t-44 106t44 106t106 44zM1050 800q62 0 106 -44t44 -106t-44 -106t-106 -44t-106 44t-44 106t44 106t106 44z" />
+<glyph unicode="" d="M550 1100q62 0 106 -44t44 -106t-44 -106t-106 -44t-106 44t-44 106t44 106t106 44zM550 700q62 0 106 -44t44 -106t-44 -106t-106 -44t-106 44t-44 106t44 106t106 44zM550 300q62 0 106 -44t44 -106t-44 -106t-106 -44t-106 44t-44 106t44 106t106 44z" />
+<glyph unicode="" d="M125 1100h950q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-950q-10 0 -17.5 7.5t-7.5 17.5v150q0 10 7.5 17.5t17.5 7.5zM125 700h950q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-950q-10 0 -17.5 7.5t-7.5 17.5v150q0 10 7.5 17.5 t17.5 7.5zM125 300h950q10 0 17.5 -7.5t7.5 -17.5v-150q0 -10 -7.5 -17.5t-17.5 -7.5h-950q-10 0 -17.5 7.5t-7.5 17.5v150q0 10 7.5 17.5t17.5 7.5z" />
+<glyph unicode="" d="M350 1200h500q162 0 256 -93.5t94 -256.5v-500q0 -165 -93.5 -257.5t-256.5 -92.5h-500q-165 0 -257.5 92.5t-92.5 257.5v500q0 165 92.5 257.5t257.5 92.5zM900 1000h-600q-41 0 -70.5 -29.5t-29.5 -70.5v-600q0 -41 29.5 -70.5t70.5 -29.5h600q41 0 70.5 29.5 t29.5 70.5v600q0 41 -29.5 70.5t-70.5 29.5zM350 900h500q21 0 35.5 -14.5t14.5 -35.5v-300q0 -21 -14.5 -35.5t-35.5 -14.5h-500q-21 0 -35.5 14.5t-14.5 35.5v300q0 21 14.5 35.5t35.5 14.5zM400 800v-200h400v200h-400z" />
+<glyph unicode="" d="M150 1100h1000q21 0 35.5 -14.5t14.5 -35.5t-14.5 -35.5t-35.5 -14.5h-50v-200h50q21 0 35.5 -14.5t14.5 -35.5t-14.5 -35.5t-35.5 -14.5h-50v-200h50q21 0 35.5 -14.5t14.5 -35.5t-14.5 -35.5t-35.5 -14.5h-50v-200h50q21 0 35.5 -14.5t14.5 -35.5t-14.5 -35.5 t-35.5 -14.5h-1000q-21 0 -35.5 14.5t-14.5 35.5t14.5 35.5t35.5 14.5h50v200h-50q-21 0 -35.5 14.5t-14.5 35.5t14.5 35.5t35.5 14.5h50v200h-50q-21 0 -35.5 14.5t-14.5 35.5t14.5 35.5t35.5 14.5h50v200h-50q-21 0 -35.5 14.5t-14.5 35.5t14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M650 1187q87 -67 118.5 -156t0 -178t-118.5 -155q-87 66 -118.5 155t0 178t118.5 156zM300 800q124 0 212 -88t88 -212q-124 0 -212 88t-88 212zM1000 800q0 -124 -88 -212t-212 -88q0 124 88 212t212 88zM300 500q124 0 212 -88t88 -212q-124 0 -212 88t-88 212z M1000 500q0 -124 -88 -212t-212 -88q0 124 88 212t212 88zM700 199v-144q0 -21 -14.5 -35.5t-35.5 -14.5t-35.5 14.5t-14.5 35.5v142q40 -4 43 -4q17 0 57 6z" />
+<glyph unicode="" d="M745 878l69 19q25 6 45 -12l298 -295q11 -11 15 -26.5t-2 -30.5q-5 -14 -18 -23.5t-28 -9.5h-8q1 0 1 -13q0 -29 -2 -56t-8.5 -62t-20 -63t-33 -53t-51 -39t-72.5 -14h-146q-184 0 -184 288q0 24 10 47q-20 4 -62 4t-63 -4q11 -24 11 -47q0 -288 -184 -288h-142 q-48 0 -84.5 21t-56 51t-32 71.5t-16 75t-3.5 68.5q0 13 2 13h-7q-15 0 -27.5 9.5t-18.5 23.5q-6 15 -2 30.5t15 25.5l298 296q20 18 46 11l76 -19q20 -5 30.5 -22.5t5.5 -37.5t-22.5 -31t-37.5 -5l-51 12l-182 -193h891l-182 193l-44 -12q-20 -5 -37.5 6t-22.5 31t6 37.5 t31 22.5z" />
+<glyph unicode="" d="M1200 900h-50q0 21 -4 37t-9.5 26.5t-18 17.5t-22 11t-28.5 5.5t-31 2t-37 0.5h-200v-850q0 -22 25 -34.5t50 -13.5l25 -2v-100h-400v100q4 0 11 0.5t24 3t30 7t24 15t11 24.5v850h-200q-25 0 -37 -0.5t-31 -2t-28.5 -5.5t-22 -11t-18 -17.5t-9.5 -26.5t-4 -37h-50v300 h1000v-300zM500 450h-25q0 15 -4 24.5t-9 14.5t-17 7.5t-20 3t-25 0.5h-100v-425q0 -11 12.5 -17.5t25.5 -7.5h12v-50h-200v50q50 0 50 25v425h-100q-17 0 -25 -0.5t-20 -3t-17 -7.5t-9 -14.5t-4 -24.5h-25v150h500v-150z" />
+<glyph unicode="" d="M1000 300v50q-25 0 -55 32q-14 14 -25 31t-16 27l-4 11l-289 747h-69l-300 -754q-18 -35 -39 -56q-9 -9 -24.5 -18.5t-26.5 -14.5l-11 -5v-50h273v50q-49 0 -78.5 21.5t-11.5 67.5l69 176h293l61 -166q13 -34 -3.5 -66.5t-55.5 -32.5v-50h312zM412 691l134 342l121 -342 h-255zM1100 150v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1000q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5h1000q21 0 35.5 -14.5t14.5 -35.5z" />
+<glyph unicode="" d="M50 1200h1100q21 0 35.5 -14.5t14.5 -35.5v-1100q0 -21 -14.5 -35.5t-35.5 -14.5h-1100q-21 0 -35.5 14.5t-14.5 35.5v1100q0 21 14.5 35.5t35.5 14.5zM611 1118h-70q-13 0 -18 -12l-299 -753q-17 -32 -35 -51q-18 -18 -56 -34q-12 -5 -12 -18v-50q0 -8 5.5 -14t14.5 -6 h273q8 0 14 6t6 14v50q0 8 -6 14t-14 6q-55 0 -71 23q-10 14 0 39l63 163h266l57 -153q11 -31 -6 -55q-12 -17 -36 -17q-8 0 -14 -6t-6 -14v-50q0 -8 6 -14t14 -6h313q8 0 14 6t6 14v50q0 7 -5.5 13t-13.5 7q-17 0 -42 25q-25 27 -40 63h-1l-288 748q-5 12 -19 12zM639 611 h-197l103 264z" />
+<glyph unicode="" d="M1200 1100h-1200v100h1200v-100zM50 1000h400q21 0 35.5 -14.5t14.5 -35.5v-900q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5v900q0 21 14.5 35.5t35.5 14.5zM650 1000h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400 q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5zM700 900v-300h300v300h-300z" />
+<glyph unicode="" d="M50 1200h400q21 0 35.5 -14.5t14.5 -35.5v-900q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5v900q0 21 14.5 35.5t35.5 14.5zM650 700h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5v400 q0 21 14.5 35.5t35.5 14.5zM700 600v-300h300v300h-300zM1200 0h-1200v100h1200v-100z" />
+<glyph unicode="" d="M50 1000h400q21 0 35.5 -14.5t14.5 -35.5v-350h100v150q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-150h100v-100h-100v-150q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5v150h-100v-350q0 -21 -14.5 -35.5t-35.5 -14.5h-400 q-21 0 -35.5 14.5t-14.5 35.5v800q0 21 14.5 35.5t35.5 14.5zM700 700v-300h300v300h-300z" />
+<glyph unicode="" d="M100 0h-100v1200h100v-1200zM250 1100h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5zM300 1000v-300h300v300h-300zM250 500h900q21 0 35.5 -14.5t14.5 -35.5v-400 q0 -21 -14.5 -35.5t-35.5 -14.5h-900q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M600 1100h150q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-150v-100h450q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-900q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5h350v100h-150q-21 0 -35.5 14.5 t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5h150v100h100v-100zM400 1000v-300h300v300h-300z" />
+<glyph unicode="" d="M1200 0h-100v1200h100v-1200zM550 1100h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5zM600 1000v-300h300v300h-300zM50 500h900q21 0 35.5 -14.5t14.5 -35.5v-400 q0 -21 -14.5 -35.5t-35.5 -14.5h-900q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="" d="M865 565l-494 -494q-23 -23 -41 -23q-14 0 -22 13.5t-8 38.5v1000q0 25 8 38.5t22 13.5q18 0 41 -23l494 -494q14 -14 14 -35t-14 -35z" />
+<glyph unicode="" d="M335 635l494 494q29 29 50 20.5t21 -49.5v-1000q0 -41 -21 -49.5t-50 20.5l-494 494q-14 14 -14 35t14 35z" />
+<glyph unicode="" d="M100 900h1000q41 0 49.5 -21t-20.5 -50l-494 -494q-14 -14 -35 -14t-35 14l-494 494q-29 29 -20.5 50t49.5 21z" />
+<glyph unicode="" d="M635 865l494 -494q29 -29 20.5 -50t-49.5 -21h-1000q-41 0 -49.5 21t20.5 50l494 494q14 14 35 14t35 -14z" />
+<glyph unicode="" d="M700 741v-182l-692 -323v221l413 193l-413 193v221zM1200 0h-800v200h800v-200z" />
+<glyph unicode="" d="M1200 900h-200v-100h200v-100h-300v300h200v100h-200v100h300v-300zM0 700h50q0 21 4 37t9.5 26.5t18 17.5t22 11t28.5 5.5t31 2t37 0.5h100v-550q0 -22 -25 -34.5t-50 -13.5l-25 -2v-100h400v100q-4 0 -11 0.5t-24 3t-30 7t-24 15t-11 24.5v550h100q25 0 37 -0.5t31 -2 t28.5 -5.5t22 -11t18 -17.5t9.5 -26.5t4 -37h50v300h-800v-300z" />
+<glyph unicode="" d="M800 700h-50q0 21 -4 37t-9.5 26.5t-18 17.5t-22 11t-28.5 5.5t-31 2t-37 0.5h-100v-550q0 -22 25 -34.5t50 -14.5l25 -1v-100h-400v100q4 0 11 0.5t24 3t30 7t24 15t11 24.5v550h-100q-25 0 -37 -0.5t-31 -2t-28.5 -5.5t-22 -11t-18 -17.5t-9.5 -26.5t-4 -37h-50v300 h800v-300zM1100 200h-200v-100h200v-100h-300v300h200v100h-200v100h300v-300z" />
+<glyph unicode="" d="M701 1098h160q16 0 21 -11t-7 -23l-464 -464l464 -464q12 -12 7 -23t-21 -11h-160q-13 0 -23 9l-471 471q-7 8 -7 18t7 18l471 471q10 9 23 9z" />
+<glyph unicode="" d="M339 1098h160q13 0 23 -9l471 -471q7 -8 7 -18t-7 -18l-471 -471q-10 -9 -23 -9h-160q-16 0 -21 11t7 23l464 464l-464 464q-12 12 -7 23t21 11z" />
+<glyph unicode="" d="M1087 882q11 -5 11 -21v-160q0 -13 -9 -23l-471 -471q-8 -7 -18 -7t-18 7l-471 471q-9 10 -9 23v160q0 16 11 21t23 -7l464 -464l464 464q12 12 23 7z" />
+<glyph unicode="" d="M618 993l471 -471q9 -10 9 -23v-160q0 -16 -11 -21t-23 7l-464 464l-464 -464q-12 -12 -23 -7t-11 21v160q0 13 9 23l471 471q8 7 18 7t18 -7z" />
+<glyph unicode="" d="M1000 1200q0 -124 -88 -212t-212 -88q0 124 88 212t212 88zM450 1000h100q21 0 40 -14t26 -33l79 -194q5 1 16 3q34 6 54 9.5t60 7t65.5 1t61 -10t56.5 -23t42.5 -42t29 -64t5 -92t-19.5 -121.5q-1 -7 -3 -19.5t-11 -50t-20.5 -73t-32.5 -81.5t-46.5 -83t-64 -70 t-82.5 -50q-13 -5 -42 -5t-65.5 2.5t-47.5 2.5q-14 0 -49.5 -3.5t-63 -3.5t-43.5 7q-57 25 -104.5 78.5t-75 111.5t-46.5 112t-26 90l-7 35q-15 63 -18 115t4.5 88.5t26 64t39.5 43.5t52 25.5t58.5 13t62.5 2t59.5 -4.5t55.5 -8l-147 192q-12 18 -5.5 30t27.5 12z" />
+<glyph unicode="🔑" d="M250 1200h600q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-150v-500l-255 -178q-19 -9 -32 -1t-13 29v650h-150q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5zM400 1100v-100h300v100h-300z" />
+<glyph unicode="🚪" d="M250 1200h750q39 0 69.5 -40.5t30.5 -84.5v-933l-700 -117v950l600 125h-700v-1000h-100v1025q0 23 15.5 49t34.5 26zM500 525v-100l100 20v100z" />
+</font>
+</defs></svg>
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.ttf b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.ttf
new file mode 100644
index 0000000..1413fc6
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.ttf
Binary files differ
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.woff b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.woff
new file mode 100644
index 0000000..9e61285
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.woff
Binary files differ
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.woff2 b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.woff2
new file mode 100644
index 0000000..64539b5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/fonts/glyphicons-halflings-regular.woff2
Binary files differ
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/js/bootstrap.js b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/js/bootstrap.js
new file mode 100644
index 0000000..1c88b71
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/js/bootstrap.js
@@ -0,0 +1,2317 @@
+/*!
+ * Bootstrap v3.3.4 (http://getbootstrap.com)
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ */
+
+if (typeof jQuery === 'undefined') {
+ throw new Error('Bootstrap\'s JavaScript requires jQuery')
+}
+
++function ($) {
+ 'use strict';
+ var version = $.fn.jquery.split(' ')[0].split('.')
+ if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1)) {
+ throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher')
+ }
+}(jQuery);
+
+/* ========================================================================
+ * Bootstrap: transition.js v3.3.4
+ * http://getbootstrap.com/javascript/#transitions
+ * ========================================================================
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ * ======================================================================== */
+
+
++function ($) {
+ 'use strict';
+
+ // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
+ // ============================================================
+
+ function transitionEnd() {
+ var el = document.createElement('bootstrap')
+
+ var transEndEventNames = {
+ WebkitTransition : 'webkitTransitionEnd',
+ MozTransition : 'transitionend',
+ OTransition : 'oTransitionEnd otransitionend',
+ transition : 'transitionend'
+ }
+
+ for (var name in transEndEventNames) {
+ if (el.style[name] !== undefined) {
+ return { end: transEndEventNames[name] }
+ }
+ }
+
+ return false // explicit for ie8 ( ._.)
+ }
+
+ // http://blog.alexmaccaw.com/css-transitions
+ $.fn.emulateTransitionEnd = function (duration) {
+ var called = false
+ var $el = this
+ $(this).one('bsTransitionEnd', function () { called = true })
+ var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
+ setTimeout(callback, duration)
+ return this
+ }
+
+ $(function () {
+ $.support.transition = transitionEnd()
+
+ if (!$.support.transition) return
+
+ $.event.special.bsTransitionEnd = {
+ bindType: $.support.transition.end,
+ delegateType: $.support.transition.end,
+ handle: function (e) {
+ if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
+ }
+ }
+ })
+
+}(jQuery);
+
+/* ========================================================================
+ * Bootstrap: alert.js v3.3.4
+ * http://getbootstrap.com/javascript/#alerts
+ * ========================================================================
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ * ======================================================================== */
+
+
++function ($) {
+ 'use strict';
+
+ // ALERT CLASS DEFINITION
+ // ======================
+
+ var dismiss = '[data-dismiss="alert"]'
+ var Alert = function (el) {
+ $(el).on('click', dismiss, this.close)
+ }
+
+ Alert.VERSION = '3.3.4'
+
+ Alert.TRANSITION_DURATION = 150
+
+ Alert.prototype.close = function (e) {
+ var $this = $(this)
+ var selector = $this.attr('data-target')
+
+ if (!selector) {
+ selector = $this.attr('href')
+ selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
+ }
+
+ var $parent = $(selector)
+
+ if (e) e.preventDefault()
+
+ if (!$parent.length) {
+ $parent = $this.closest('.alert')
+ }
+
+ $parent.trigger(e = $.Event('close.bs.alert'))
+
+ if (e.isDefaultPrevented()) return
+
+ $parent.removeClass('in')
+
+ function removeElement() {
+ // detach from parent, fire event then clean up data
+ $parent.detach().trigger('closed.bs.alert').remove()
+ }
+
+ $.support.transition && $parent.hasClass('fade') ?
+ $parent
+ .one('bsTransitionEnd', removeElement)
+ .emulateTransitionEnd(Alert.TRANSITION_DURATION) :
+ removeElement()
+ }
+
+
+ // ALERT PLUGIN DEFINITION
+ // =======================
+
+ function Plugin(option) {
+ return this.each(function () {
+ var $this = $(this)
+ var data = $this.data('bs.alert')
+
+ if (!data) $this.data('bs.alert', (data = new Alert(this)))
+ if (typeof option == 'string') data[option].call($this)
+ })
+ }
+
+ var old = $.fn.alert
+
+ $.fn.alert = Plugin
+ $.fn.alert.Constructor = Alert
+
+
+ // ALERT NO CONFLICT
+ // =================
+
+ $.fn.alert.noConflict = function () {
+ $.fn.alert = old
+ return this
+ }
+
+
+ // ALERT DATA-API
+ // ==============
+
+ $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
+
+}(jQuery);
+
+/* ========================================================================
+ * Bootstrap: button.js v3.3.4
+ * http://getbootstrap.com/javascript/#buttons
+ * ========================================================================
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ * ======================================================================== */
+
+
++function ($) {
+ 'use strict';
+
+ // BUTTON PUBLIC CLASS DEFINITION
+ // ==============================
+
+ var Button = function (element, options) {
+ this.$element = $(element)
+ this.options = $.extend({}, Button.DEFAULTS, options)
+ this.isLoading = false
+ }
+
+ Button.VERSION = '3.3.4'
+
+ Button.DEFAULTS = {
+ loadingText: 'loading...'
+ }
+
+ Button.prototype.setState = function (state) {
+ var d = 'disabled'
+ var $el = this.$element
+ var val = $el.is('input') ? 'val' : 'html'
+ var data = $el.data()
+
+ state = state + 'Text'
+
+ if (data.resetText == null) $el.data('resetText', $el[val]())
+
+ // push to event loop to allow forms to submit
+ setTimeout($.proxy(function () {
+ $el[val](data[state] == null ? this.options[state] : data[state])
+
+ if (state == 'loadingText') {
+ this.isLoading = true
+ $el.addClass(d).attr(d, d)
+ } else if (this.isLoading) {
+ this.isLoading = false
+ $el.removeClass(d).removeAttr(d)
+ }
+ }, this), 0)
+ }
+
+ Button.prototype.toggle = function () {
+ var changed = true
+ var $parent = this.$element.closest('[data-toggle="buttons"]')
+
+ if ($parent.length) {
+ var $input = this.$element.find('input')
+ if ($input.prop('type') == 'radio') {
+ if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
+ else $parent.find('.active').removeClass('active')
+ }
+ if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
+ } else {
+ this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
+ }
+
+ if (changed) this.$element.toggleClass('active')
+ }
+
+
+ // BUTTON PLUGIN DEFINITION
+ // ========================
+
+ function Plugin(option) {
+ return this.each(function () {
+ var $this = $(this)
+ var data = $this.data('bs.button')
+ var options = typeof option == 'object' && option
+
+ if (!data) $this.data('bs.button', (data = new Button(this, options)))
+
+ if (option == 'toggle') data.toggle()
+ else if (option) data.setState(option)
+ })
+ }
+
+ var old = $.fn.button
+
+ $.fn.button = Plugin
+ $.fn.button.Constructor = Button
+
+
+ // BUTTON NO CONFLICT
+ // ==================
+
+ $.fn.button.noConflict = function () {
+ $.fn.button = old
+ return this
+ }
+
+
+ // BUTTON DATA-API
+ // ===============
+
+ $(document)
+ .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
+ var $btn = $(e.target)
+ if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
+ Plugin.call($btn, 'toggle')
+ e.preventDefault()
+ })
+ .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
+ $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
+ })
+
+}(jQuery);
+
+/* ========================================================================
+ * Bootstrap: carousel.js v3.3.4
+ * http://getbootstrap.com/javascript/#carousel
+ * ========================================================================
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ * ======================================================================== */
+
+
++function ($) {
+ 'use strict';
+
+ // CAROUSEL CLASS DEFINITION
+ // =========================
+
+ var Carousel = function (element, options) {
+ this.$element = $(element)
+ this.$indicators = this.$element.find('.carousel-indicators')
+ this.options = options
+ this.paused = null
+ this.sliding = null
+ this.interval = null
+ this.$active = null
+ this.$items = null
+
+ this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
+
+ this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
+ .on('mouseenter.bs.carousel', $.proxy(this.pause, this))
+ .on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
+ }
+
+ Carousel.VERSION = '3.3.4'
+
+ Carousel.TRANSITION_DURATION = 600
+
+ Carousel.DEFAULTS = {
+ interval: 5000,
+ pause: 'hover',
+ wrap: true,
+ keyboard: true
+ }
+
+ Carousel.prototype.keydown = function (e) {
+ if (/input|textarea/i.test(e.target.tagName)) return
+ switch (e.which) {
+ case 37: this.prev(); break
+ case 39: this.next(); break
+ default: return
+ }
+
+ e.preventDefault()
+ }
+
+ Carousel.prototype.cycle = function (e) {
+ e || (this.paused = false)
+
+ this.interval && clearInterval(this.interval)
+
+ this.options.interval
+ && !this.paused
+ && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
+
+ return this
+ }
+
+ Carousel.prototype.getItemIndex = function (item) {
+ this.$items = item.parent().children('.item')
+ return this.$items.index(item || this.$active)
+ }
+
+ Carousel.prototype.getItemForDirection = function (direction, active) {
+ var activeIndex = this.getItemIndex(active)
+ var willWrap = (direction == 'prev' && activeIndex === 0)
+ || (direction == 'next' && activeIndex == (this.$items.length - 1))
+ if (willWrap && !this.options.wrap) return active
+ var delta = direction == 'prev' ? -1 : 1
+ var itemIndex = (activeIndex + delta) % this.$items.length
+ return this.$items.eq(itemIndex)
+ }
+
+ Carousel.prototype.to = function (pos) {
+ var that = this
+ var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
+
+ if (pos > (this.$items.length - 1) || pos < 0) return
+
+ if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
+ if (activeIndex == pos) return this.pause().cycle()
+
+ return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
+ }
+
+ Carousel.prototype.pause = function (e) {
+ e || (this.paused = true)
+
+ if (this.$element.find('.next, .prev').length && $.support.transition) {
+ this.$element.trigger($.support.transition.end)
+ this.cycle(true)
+ }
+
+ this.interval = clearInterval(this.interval)
+
+ return this
+ }
+
+ Carousel.prototype.next = function () {
+ if (this.sliding) return
+ return this.slide('next')
+ }
+
+ Carousel.prototype.prev = function () {
+ if (this.sliding) return
+ return this.slide('prev')
+ }
+
+ Carousel.prototype.slide = function (type, next) {
+ var $active = this.$element.find('.item.active')
+ var $next = next || this.getItemForDirection(type, $active)
+ var isCycling = this.interval
+ var direction = type == 'next' ? 'left' : 'right'
+ var that = this
+
+ if ($next.hasClass('active')) return (this.sliding = false)
+
+ var relatedTarget = $next[0]
+ var slideEvent = $.Event('slide.bs.carousel', {
+ relatedTarget: relatedTarget,
+ direction: direction
+ })
+ this.$element.trigger(slideEvent)
+ if (slideEvent.isDefaultPrevented()) return
+
+ this.sliding = true
+
+ isCycling && this.pause()
+
+ if (this.$indicators.length) {
+ this.$indicators.find('.active').removeClass('active')
+ var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
+ $nextIndicator && $nextIndicator.addClass('active')
+ }
+
+ var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
+ if ($.support.transition && this.$element.hasClass('slide')) {
+ $next.addClass(type)
+ $next[0].offsetWidth // force reflow
+ $active.addClass(direction)
+ $next.addClass(direction)
+ $active
+ .one('bsTransitionEnd', function () {
+ $next.removeClass([type, direction].join(' ')).addClass('active')
+ $active.removeClass(['active', direction].join(' '))
+ that.sliding = false
+ setTimeout(function () {
+ that.$element.trigger(slidEvent)
+ }, 0)
+ })
+ .emulateTransitionEnd(Carousel.TRANSITION_DURATION)
+ } else {
+ $active.removeClass('active')
+ $next.addClass('active')
+ this.sliding = false
+ this.$element.trigger(slidEvent)
+ }
+
+ isCycling && this.cycle()
+
+ return this
+ }
+
+
+ // CAROUSEL PLUGIN DEFINITION
+ // ==========================
+
+ function Plugin(option) {
+ return this.each(function () {
+ var $this = $(this)
+ var data = $this.data('bs.carousel')
+ var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
+ var action = typeof option == 'string' ? option : options.slide
+
+ if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
+ if (typeof option == 'number') data.to(option)
+ else if (action) data[action]()
+ else if (options.interval) data.pause().cycle()
+ })
+ }
+
+ var old = $.fn.carousel
+
+ $.fn.carousel = Plugin
+ $.fn.carousel.Constructor = Carousel
+
+
+ // CAROUSEL NO CONFLICT
+ // ====================
+
+ $.fn.carousel.noConflict = function () {
+ $.fn.carousel = old
+ return this
+ }
+
+
+ // CAROUSEL DATA-API
+ // =================
+
+ var clickHandler = function (e) {
+ var href
+ var $this = $(this)
+ var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
+ if (!$target.hasClass('carousel')) return
+ var options = $.extend({}, $target.data(), $this.data())
+ var slideIndex = $this.attr('data-slide-to')
+ if (slideIndex) options.interval = false
+
+ Plugin.call($target, options)
+
+ if (slideIndex) {
+ $target.data('bs.carousel').to(slideIndex)
+ }
+
+ e.preventDefault()
+ }
+
+ $(document)
+ .on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
+ .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
+
+ $(window).on('load', function () {
+ $('[data-ride="carousel"]').each(function () {
+ var $carousel = $(this)
+ Plugin.call($carousel, $carousel.data())
+ })
+ })
+
+}(jQuery);
+
+/* ========================================================================
+ * Bootstrap: collapse.js v3.3.4
+ * http://getbootstrap.com/javascript/#collapse
+ * ========================================================================
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ * ======================================================================== */
+
+
++function ($) {
+ 'use strict';
+
+ // COLLAPSE PUBLIC CLASS DEFINITION
+ // ================================
+
+ var Collapse = function (element, options) {
+ this.$element = $(element)
+ this.options = $.extend({}, Collapse.DEFAULTS, options)
+ this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
+ '[data-toggle="collapse"][data-target="#' + element.id + '"]')
+ this.transitioning = null
+
+ if (this.options.parent) {
+ this.$parent = this.getParent()
+ } else {
+ this.addAriaAndCollapsedClass(this.$element, this.$trigger)
+ }
+
+ if (this.options.toggle) this.toggle()
+ }
+
+ Collapse.VERSION = '3.3.4'
+
+ Collapse.TRANSITION_DURATION = 350
+
+ Collapse.DEFAULTS = {
+ toggle: true
+ }
+
+ Collapse.prototype.dimension = function () {
+ var hasWidth = this.$element.hasClass('width')
+ return hasWidth ? 'width' : 'height'
+ }
+
+ Collapse.prototype.show = function () {
+ if (this.transitioning || this.$element.hasClass('in')) return
+
+ var activesData
+ var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
+
+ if (actives && actives.length) {
+ activesData = actives.data('bs.collapse')
+ if (activesData && activesData.transitioning) return
+ }
+
+ var startEvent = $.Event('show.bs.collapse')
+ this.$element.trigger(startEvent)
+ if (startEvent.isDefaultPrevented()) return
+
+ if (actives && actives.length) {
+ Plugin.call(actives, 'hide')
+ activesData || actives.data('bs.collapse', null)
+ }
+
+ var dimension = this.dimension()
+
+ this.$element
+ .removeClass('collapse')
+ .addClass('collapsing')[dimension](0)
+ .attr('aria-expanded', true)
+
+ this.$trigger
+ .removeClass('collapsed')
+ .attr('aria-expanded', true)
+
+ this.transitioning = 1
+
+ var complete = function () {
+ this.$element
+ .removeClass('collapsing')
+ .addClass('collapse in')[dimension]('')
+ this.transitioning = 0
+ this.$element
+ .trigger('shown.bs.collapse')
+ }
+
+ if (!$.support.transition) return complete.call(this)
+
+ var scrollSize = $.camelCase(['scroll', dimension].join('-'))
+
+ this.$element
+ .one('bsTransitionEnd', $.proxy(complete, this))
+ .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
+ }
+
+ Collapse.prototype.hide = function () {
+ if (this.transitioning || !this.$element.hasClass('in')) return
+
+ var startEvent = $.Event('hide.bs.collapse')
+ this.$element.trigger(startEvent)
+ if (startEvent.isDefaultPrevented()) return
+
+ var dimension = this.dimension()
+
+ this.$element[dimension](this.$element[dimension]())[0].offsetHeight
+
+ this.$element
+ .addClass('collapsing')
+ .removeClass('collapse in')
+ .attr('aria-expanded', false)
+
+ this.$trigger
+ .addClass('collapsed')
+ .attr('aria-expanded', false)
+
+ this.transitioning = 1
+
+ var complete = function () {
+ this.transitioning = 0
+ this.$element
+ .removeClass('collapsing')
+ .addClass('collapse')
+ .trigger('hidden.bs.collapse')
+ }
+
+ if (!$.support.transition) return complete.call(this)
+
+ this.$element
+ [dimension](0)
+ .one('bsTransitionEnd', $.proxy(complete, this))
+ .emulateTransitionEnd(Collapse.TRANSITION_DURATION)
+ }
+
+ Collapse.prototype.toggle = function () {
+ this[this.$element.hasClass('in') ? 'hide' : 'show']()
+ }
+
+ Collapse.prototype.getParent = function () {
+ return $(this.options.parent)
+ .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
+ .each($.proxy(function (i, element) {
+ var $element = $(element)
+ this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
+ }, this))
+ .end()
+ }
+
+ Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
+ var isOpen = $element.hasClass('in')
+
+ $element.attr('aria-expanded', isOpen)
+ $trigger
+ .toggleClass('collapsed', !isOpen)
+ .attr('aria-expanded', isOpen)
+ }
+
+ function getTargetFromTrigger($trigger) {
+ var href
+ var target = $trigger.attr('data-target')
+ || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
+
+ return $(target)
+ }
+
+
+ // COLLAPSE PLUGIN DEFINITION
+ // ==========================
+
+ function Plugin(option) {
+ return this.each(function () {
+ var $this = $(this)
+ var data = $this.data('bs.collapse')
+ var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
+
+ if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
+ if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
+ if (typeof option == 'string') data[option]()
+ })
+ }
+
+ var old = $.fn.collapse
+
+ $.fn.collapse = Plugin
+ $.fn.collapse.Constructor = Collapse
+
+
+ // COLLAPSE NO CONFLICT
+ // ====================
+
+ $.fn.collapse.noConflict = function () {
+ $.fn.collapse = old
+ return this
+ }
+
+
+ // COLLAPSE DATA-API
+ // =================
+
+ $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
+ var $this = $(this)
+
+ if (!$this.attr('data-target')) e.preventDefault()
+
+ var $target = getTargetFromTrigger($this)
+ var data = $target.data('bs.collapse')
+ var option = data ? 'toggle' : $this.data()
+
+ Plugin.call($target, option)
+ })
+
+}(jQuery);
+
+/* ========================================================================
+ * Bootstrap: dropdown.js v3.3.4
+ * http://getbootstrap.com/javascript/#dropdowns
+ * ========================================================================
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ * ======================================================================== */
+
+
++function ($) {
+ 'use strict';
+
+ // DROPDOWN CLASS DEFINITION
+ // =========================
+
+ var backdrop = '.dropdown-backdrop'
+ var toggle = '[data-toggle="dropdown"]'
+ var Dropdown = function (element) {
+ $(element).on('click.bs.dropdown', this.toggle)
+ }
+
+ Dropdown.VERSION = '3.3.4'
+
+ Dropdown.prototype.toggle = function (e) {
+ var $this = $(this)
+
+ if ($this.is('.disabled, :disabled')) return
+
+ var $parent = getParent($this)
+ var isActive = $parent.hasClass('open')
+
+ clearMenus()
+
+ if (!isActive) {
+ if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
+ // if mobile we use a backdrop because click events don't delegate
+ $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
+ }
+
+ var relatedTarget = { relatedTarget: this }
+ $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
+
+ if (e.isDefaultPrevented()) return
+
+ $this
+ .trigger('focus')
+ .attr('aria-expanded', 'true')
+
+ $parent
+ .toggleClass('open')
+ .trigger('shown.bs.dropdown', relatedTarget)
+ }
+
+ return false
+ }
+
+ Dropdown.prototype.keydown = function (e) {
+ if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
+
+ var $this = $(this)
+
+ e.preventDefault()
+ e.stopPropagation()
+
+ if ($this.is('.disabled, :disabled')) return
+
+ var $parent = getParent($this)
+ var isActive = $parent.hasClass('open')
+
+ if ((!isActive && e.which != 27) || (isActive && e.which == 27)) {
+ if (e.which == 27) $parent.find(toggle).trigger('focus')
+ return $this.trigger('click')
+ }
+
+ var desc = ' li:not(.disabled):visible a'
+ var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)
+
+ if (!$items.length) return
+
+ var index = $items.index(e.target)
+
+ if (e.which == 38 && index > 0) index-- // up
+ if (e.which == 40 && index < $items.length - 1) index++ // down
+ if (!~index) index = 0
+
+ $items.eq(index).trigger('focus')
+ }
+
+ function clearMenus(e) {
+ if (e && e.which === 3) return
+ $(backdrop).remove()
+ $(toggle).each(function () {
+ var $this = $(this)
+ var $parent = getParent($this)
+ var relatedTarget = { relatedTarget: this }
+
+ if (!$parent.hasClass('open')) return
+
+ $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
+
+ if (e.isDefaultPrevented()) return
+
+ $this.attr('aria-expanded', 'false')
+ $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
+ })
+ }
+
+ function getParent($this) {
+ var selector = $this.attr('data-target')
+
+ if (!selector) {
+ selector = $this.attr('href')
+ selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
+ }
+
+ var $parent = selector && $(selector)
+
+ return $parent && $parent.length ? $parent : $this.parent()
+ }
+
+
+ // DROPDOWN PLUGIN DEFINITION
+ // ==========================
+
+ function Plugin(option) {
+ return this.each(function () {
+ var $this = $(this)
+ var data = $this.data('bs.dropdown')
+
+ if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
+ if (typeof option == 'string') data[option].call($this)
+ })
+ }
+
+ var old = $.fn.dropdown
+
+ $.fn.dropdown = Plugin
+ $.fn.dropdown.Constructor = Dropdown
+
+
+ // DROPDOWN NO CONFLICT
+ // ====================
+
+ $.fn.dropdown.noConflict = function () {
+ $.fn.dropdown = old
+ return this
+ }
+
+
+ // APPLY TO STANDARD DROPDOWN ELEMENTS
+ // ===================================
+
+ $(document)
+ .on('click.bs.dropdown.data-api', clearMenus)
+ .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
+ .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
+ .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
+ .on('keydown.bs.dropdown.data-api', '[role="menu"]', Dropdown.prototype.keydown)
+ .on('keydown.bs.dropdown.data-api', '[role="listbox"]', Dropdown.prototype.keydown)
+
+}(jQuery);
+
+/* ========================================================================
+ * Bootstrap: modal.js v3.3.4
+ * http://getbootstrap.com/javascript/#modals
+ * ========================================================================
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ * ======================================================================== */
+
+
++function ($) {
+ 'use strict';
+
+ // MODAL CLASS DEFINITION
+ // ======================
+
+ var Modal = function (element, options) {
+ this.options = options
+ this.$body = $(document.body)
+ this.$element = $(element)
+ this.$dialog = this.$element.find('.modal-dialog')
+ this.$backdrop = null
+ this.isShown = null
+ this.originalBodyPad = null
+ this.scrollbarWidth = 0
+ this.ignoreBackdropClick = false
+
+ if (this.options.remote) {
+ this.$element
+ .find('.modal-content')
+ .load(this.options.remote, $.proxy(function () {
+ this.$element.trigger('loaded.bs.modal')
+ }, this))
+ }
+ }
+
+ Modal.VERSION = '3.3.4'
+
+ Modal.TRANSITION_DURATION = 300
+ Modal.BACKDROP_TRANSITION_DURATION = 150
+
+ Modal.DEFAULTS = {
+ backdrop: true,
+ keyboard: true,
+ show: true
+ }
+
+ Modal.prototype.toggle = function (_relatedTarget) {
+ return this.isShown ? this.hide() : this.show(_relatedTarget)
+ }
+
+ Modal.prototype.show = function (_relatedTarget) {
+ var that = this
+ var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
+
+ this.$element.trigger(e)
+
+ if (this.isShown || e.isDefaultPrevented()) return
+
+ this.isShown = true
+
+ this.checkScrollbar()
+ this.setScrollbar()
+ this.$body.addClass('modal-open')
+
+ this.escape()
+ this.resize()
+
+ this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
+
+ this.$dialog.on('mousedown.dismiss.bs.modal', function () {
+ that.$element.one('mouseup.dismiss.bs.modal', function (e) {
+ if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
+ })
+ })
+
+ this.backdrop(function () {
+ var transition = $.support.transition && that.$element.hasClass('fade')
+
+ if (!that.$element.parent().length) {
+ that.$element.appendTo(that.$body) // don't move modals dom position
+ }
+
+ that.$element
+ .show()
+ .scrollTop(0)
+
+ that.adjustDialog()
+
+ if (transition) {
+ that.$element[0].offsetWidth // force reflow
+ }
+
+ that.$element
+ .addClass('in')
+ .attr('aria-hidden', false)
+
+ that.enforceFocus()
+
+ var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
+
+ transition ?
+ that.$dialog // wait for modal to slide in
+ .one('bsTransitionEnd', function () {
+ that.$element.trigger('focus').trigger(e)
+ })
+ .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
+ that.$element.trigger('focus').trigger(e)
+ })
+ }
+
+ Modal.prototype.hide = function (e) {
+ if (e) e.preventDefault()
+
+ e = $.Event('hide.bs.modal')
+
+ this.$element.trigger(e)
+
+ if (!this.isShown || e.isDefaultPrevented()) return
+
+ this.isShown = false
+
+ this.escape()
+ this.resize()
+
+ $(document).off('focusin.bs.modal')
+
+ this.$element
+ .removeClass('in')
+ .attr('aria-hidden', true)
+ .off('click.dismiss.bs.modal')
+ .off('mouseup.dismiss.bs.modal')
+
+ this.$dialog.off('mousedown.dismiss.bs.modal')
+
+ $.support.transition && this.$element.hasClass('fade') ?
+ this.$element
+ .one('bsTransitionEnd', $.proxy(this.hideModal, this))
+ .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
+ this.hideModal()
+ }
+
+ Modal.prototype.enforceFocus = function () {
+ $(document)
+ .off('focusin.bs.modal') // guard against infinite focus loop
+ .on('focusin.bs.modal', $.proxy(function (e) {
+ if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
+ this.$element.trigger('focus')
+ }
+ }, this))
+ }
+
+ Modal.prototype.escape = function () {
+ if (this.isShown && this.options.keyboard) {
+ this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
+ e.which == 27 && this.hide()
+ }, this))
+ } else if (!this.isShown) {
+ this.$element.off('keydown.dismiss.bs.modal')
+ }
+ }
+
+ Modal.prototype.resize = function () {
+ if (this.isShown) {
+ $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
+ } else {
+ $(window).off('resize.bs.modal')
+ }
+ }
+
+ Modal.prototype.hideModal = function () {
+ var that = this
+ this.$element.hide()
+ this.backdrop(function () {
+ that.$body.removeClass('modal-open')
+ that.resetAdjustments()
+ that.resetScrollbar()
+ that.$element.trigger('hidden.bs.modal')
+ })
+ }
+
+ Modal.prototype.removeBackdrop = function () {
+ this.$backdrop && this.$backdrop.remove()
+ this.$backdrop = null
+ }
+
+ Modal.prototype.backdrop = function (callback) {
+ var that = this
+ var animate = this.$element.hasClass('fade') ? 'fade' : ''
+
+ if (this.isShown && this.options.backdrop) {
+ var doAnimate = $.support.transition && animate
+
+ this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
+ .appendTo(this.$body)
+
+ this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
+ if (this.ignoreBackdropClick) {
+ this.ignoreBackdropClick = false
+ return
+ }
+ if (e.target !== e.currentTarget) return
+ this.options.backdrop == 'static'
+ ? this.$element[0].focus()
+ : this.hide()
+ }, this))
+
+ if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
+
+ this.$backdrop.addClass('in')
+
+ if (!callback) return
+
+ doAnimate ?
+ this.$backdrop
+ .one('bsTransitionEnd', callback)
+ .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
+ callback()
+
+ } else if (!this.isShown && this.$backdrop) {
+ this.$backdrop.removeClass('in')
+
+ var callbackRemove = function () {
+ that.removeBackdrop()
+ callback && callback()
+ }
+ $.support.transition && this.$element.hasClass('fade') ?
+ this.$backdrop
+ .one('bsTransitionEnd', callbackRemove)
+ .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
+ callbackRemove()
+
+ } else if (callback) {
+ callback()
+ }
+ }
+
+ // these following methods are used to handle overflowing modals
+
+ Modal.prototype.handleUpdate = function () {
+ this.adjustDialog()
+ }
+
+ Modal.prototype.adjustDialog = function () {
+ var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
+
+ this.$element.css({
+ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
+ paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
+ })
+ }
+
+ Modal.prototype.resetAdjustments = function () {
+ this.$element.css({
+ paddingLeft: '',
+ paddingRight: ''
+ })
+ }
+
+ Modal.prototype.checkScrollbar = function () {
+ var fullWindowWidth = window.innerWidth
+ if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
+ var documentElementRect = document.documentElement.getBoundingClientRect()
+ fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
+ }
+ this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
+ this.scrollbarWidth = this.measureScrollbar()
+ }
+
+ Modal.prototype.setScrollbar = function () {
+ var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
+ this.originalBodyPad = document.body.style.paddingRight || ''
+ if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
+ }
+
+ Modal.prototype.resetScrollbar = function () {
+ this.$body.css('padding-right', this.originalBodyPad)
+ }
+
+ Modal.prototype.measureScrollbar = function () { // thx walsh
+ var scrollDiv = document.createElement('div')
+ scrollDiv.className = 'modal-scrollbar-measure'
+ this.$body.append(scrollDiv)
+ var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
+ this.$body[0].removeChild(scrollDiv)
+ return scrollbarWidth
+ }
+
+
+ // MODAL PLUGIN DEFINITION
+ // =======================
+
+ function Plugin(option, _relatedTarget) {
+ return this.each(function () {
+ var $this = $(this)
+ var data = $this.data('bs.modal')
+ var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
+
+ if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
+ if (typeof option == 'string') data[option](_relatedTarget)
+ else if (options.show) data.show(_relatedTarget)
+ })
+ }
+
+ var old = $.fn.modal
+
+ $.fn.modal = Plugin
+ $.fn.modal.Constructor = Modal
+
+
+ // MODAL NO CONFLICT
+ // =================
+
+ $.fn.modal.noConflict = function () {
+ $.fn.modal = old
+ return this
+ }
+
+
+ // MODAL DATA-API
+ // ==============
+
+ $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
+ var $this = $(this)
+ var href = $this.attr('href')
+ var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
+ var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
+
+ if ($this.is('a')) e.preventDefault()
+
+ $target.one('show.bs.modal', function (showEvent) {
+ if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
+ $target.one('hidden.bs.modal', function () {
+ $this.is(':visible') && $this.trigger('focus')
+ })
+ })
+ Plugin.call($target, option, this)
+ })
+
+}(jQuery);
+
+/* ========================================================================
+ * Bootstrap: tooltip.js v3.3.4
+ * http://getbootstrap.com/javascript/#tooltip
+ * Inspired by the original jQuery.tipsy by Jason Frame
+ * ========================================================================
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ * ======================================================================== */
+
+
++function ($) {
+ 'use strict';
+
+ // TOOLTIP PUBLIC CLASS DEFINITION
+ // ===============================
+
+ var Tooltip = function (element, options) {
+ this.type = null
+ this.options = null
+ this.enabled = null
+ this.timeout = null
+ this.hoverState = null
+ this.$element = null
+
+ this.init('tooltip', element, options)
+ }
+
+ Tooltip.VERSION = '3.3.4'
+
+ Tooltip.TRANSITION_DURATION = 150
+
+ Tooltip.DEFAULTS = {
+ animation: true,
+ placement: 'top',
+ selector: false,
+ template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
+ trigger: 'hover focus',
+ title: '',
+ delay: 0,
+ html: false,
+ container: false,
+ viewport: {
+ selector: 'body',
+ padding: 0
+ }
+ }
+
+ Tooltip.prototype.init = function (type, element, options) {
+ this.enabled = true
+ this.type = type
+ this.$element = $(element)
+ this.options = this.getOptions(options)
+ this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport)
+
+ if (this.$element[0] instanceof document.constructor && !this.options.selector) {
+ throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
+ }
+
+ var triggers = this.options.trigger.split(' ')
+
+ for (var i = triggers.length; i--;) {
+ var trigger = triggers[i]
+
+ if (trigger == 'click') {
+ this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
+ } else if (trigger != 'manual') {
+ var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
+ var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
+
+ this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
+ this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
+ }
+ }
+
+ this.options.selector ?
+ (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
+ this.fixTitle()
+ }
+
+ Tooltip.prototype.getDefaults = function () {
+ return Tooltip.DEFAULTS
+ }
+
+ Tooltip.prototype.getOptions = function (options) {
+ options = $.extend({}, this.getDefaults(), this.$element.data(), options)
+
+ if (options.delay && typeof options.delay == 'number') {
+ options.delay = {
+ show: options.delay,
+ hide: options.delay
+ }
+ }
+
+ return options
+ }
+
+ Tooltip.prototype.getDelegateOptions = function () {
+ var options = {}
+ var defaults = this.getDefaults()
+
+ this._options && $.each(this._options, function (key, value) {
+ if (defaults[key] != value) options[key] = value
+ })
+
+ return options
+ }
+
+ Tooltip.prototype.enter = function (obj) {
+ var self = obj instanceof this.constructor ?
+ obj : $(obj.currentTarget).data('bs.' + this.type)
+
+ if (self && self.$tip && self.$tip.is(':visible')) {
+ self.hoverState = 'in'
+ return
+ }
+
+ if (!self) {
+ self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
+ $(obj.currentTarget).data('bs.' + this.type, self)
+ }
+
+ clearTimeout(self.timeout)
+
+ self.hoverState = 'in'
+
+ if (!self.options.delay || !self.options.delay.show) return self.show()
+
+ self.timeout = setTimeout(function () {
+ if (self.hoverState == 'in') self.show()
+ }, self.options.delay.show)
+ }
+
+ Tooltip.prototype.leave = function (obj) {
+ var self = obj instanceof this.constructor ?
+ obj : $(obj.currentTarget).data('bs.' + this.type)
+
+ if (!self) {
+ self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
+ $(obj.currentTarget).data('bs.' + this.type, self)
+ }
+
+ clearTimeout(self.timeout)
+
+ self.hoverState = 'out'
+
+ if (!self.options.delay || !self.options.delay.hide) return self.hide()
+
+ self.timeout = setTimeout(function () {
+ if (self.hoverState == 'out') self.hide()
+ }, self.options.delay.hide)
+ }
+
+ Tooltip.prototype.show = function () {
+ var e = $.Event('show.bs.' + this.type)
+
+ if (this.hasContent() && this.enabled) {
+ this.$element.trigger(e)
+
+ var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
+ if (e.isDefaultPrevented() || !inDom) return
+ var that = this
+
+ var $tip = this.tip()
+
+ var tipId = this.getUID(this.type)
+
+ this.setContent()
+ $tip.attr('id', tipId)
+ this.$element.attr('aria-describedby', tipId)
+
+ if (this.options.animation) $tip.addClass('fade')
+
+ var placement = typeof this.options.placement == 'function' ?
+ this.options.placement.call(this, $tip[0], this.$element[0]) :
+ this.options.placement
+
+ var autoToken = /\s?auto?\s?/i
+ var autoPlace = autoToken.test(placement)
+ if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
+
+ $tip
+ .detach()
+ .css({ top: 0, left: 0, display: 'block' })
+ .addClass(placement)
+ .data('bs.' + this.type, this)
+
+ this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
+
+ var pos = this.getPosition()
+ var actualWidth = $tip[0].offsetWidth
+ var actualHeight = $tip[0].offsetHeight
+
+ if (autoPlace) {
+ var orgPlacement = placement
+ var $container = this.options.container ? $(this.options.container) : this.$element.parent()
+ var containerDim = this.getPosition($container)
+
+ placement = placement == 'bottom' && pos.bottom + actualHeight > containerDim.bottom ? 'top' :
+ placement == 'top' && pos.top - actualHeight < containerDim.top ? 'bottom' :
+ placement == 'right' && pos.right + actualWidth > containerDim.width ? 'left' :
+ placement == 'left' && pos.left - actualWidth < containerDim.left ? 'right' :
+ placement
+
+ $tip
+ .removeClass(orgPlacement)
+ .addClass(placement)
+ }
+
+ var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
+
+ this.applyPlacement(calculatedOffset, placement)
+
+ var complete = function () {
+ var prevHoverState = that.hoverState
+ that.$element.trigger('shown.bs.' + that.type)
+ that.hoverState = null
+
+ if (prevHoverState == 'out') that.leave(that)
+ }
+
+ $.support.transition && this.$tip.hasClass('fade') ?
+ $tip
+ .one('bsTransitionEnd', complete)
+ .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
+ complete()
+ }
+ }
+
+ Tooltip.prototype.applyPlacement = function (offset, placement) {
+ var $tip = this.tip()
+ var width = $tip[0].offsetWidth
+ var height = $tip[0].offsetHeight
+
+ // manually read margins because getBoundingClientRect includes difference
+ var marginTop = parseInt($tip.css('margin-top'), 10)
+ var marginLeft = parseInt($tip.css('margin-left'), 10)
+
+ // we must check for NaN for ie 8/9
+ if (isNaN(marginTop)) marginTop = 0
+ if (isNaN(marginLeft)) marginLeft = 0
+
+ offset.top = offset.top + marginTop
+ offset.left = offset.left + marginLeft
+
+ // $.fn.offset doesn't round pixel values
+ // so we use setOffset directly with our own function B-0
+ $.offset.setOffset($tip[0], $.extend({
+ using: function (props) {
+ $tip.css({
+ top: Math.round(props.top),
+ left: Math.round(props.left)
+ })
+ }
+ }, offset), 0)
+
+ $tip.addClass('in')
+
+ // check to see if placing tip in new offset caused the tip to resize itself
+ var actualWidth = $tip[0].offsetWidth
+ var actualHeight = $tip[0].offsetHeight
+
+ if (placement == 'top' && actualHeight != height) {
+ offset.top = offset.top + height - actualHeight
+ }
+
+ var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
+
+ if (delta.left) offset.left += delta.left
+ else offset.top += delta.top
+
+ var isVertical = /top|bottom/.test(placement)
+ var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
+ var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
+
+ $tip.offset(offset)
+ this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
+ }
+
+ Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
+ this.arrow()
+ .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
+ .css(isVertical ? 'top' : 'left', '')
+ }
+
+ Tooltip.prototype.setContent = function () {
+ var $tip = this.tip()
+ var title = this.getTitle()
+
+ $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
+ $tip.removeClass('fade in top bottom left right')
+ }
+
+ Tooltip.prototype.hide = function (callback) {
+ var that = this
+ var $tip = $(this.$tip)
+ var e = $.Event('hide.bs.' + this.type)
+
+ function complete() {
+ if (that.hoverState != 'in') $tip.detach()
+ that.$element
+ .removeAttr('aria-describedby')
+ .trigger('hidden.bs.' + that.type)
+ callback && callback()
+ }
+
+ this.$element.trigger(e)
+
+ if (e.isDefaultPrevented()) return
+
+ $tip.removeClass('in')
+
+ $.support.transition && $tip.hasClass('fade') ?
+ $tip
+ .one('bsTransitionEnd', complete)
+ .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
+ complete()
+
+ this.hoverState = null
+
+ return this
+ }
+
+ Tooltip.prototype.fixTitle = function () {
+ var $e = this.$element
+ if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
+ $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
+ }
+ }
+
+ Tooltip.prototype.hasContent = function () {
+ return this.getTitle()
+ }
+
+ Tooltip.prototype.getPosition = function ($element) {
+ $element = $element || this.$element
+
+ var el = $element[0]
+ var isBody = el.tagName == 'BODY'
+
+ var elRect = el.getBoundingClientRect()
+ if (elRect.width == null) {
+ // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
+ elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
+ }
+ var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()
+ var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
+ var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
+
+ return $.extend({}, elRect, scroll, outerDims, elOffset)
+ }
+
+ Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
+ return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
+ placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
+ placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
+ /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
+
+ }
+
+ Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
+ var delta = { top: 0, left: 0 }
+ if (!this.$viewport) return delta
+
+ var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
+ var viewportDimensions = this.getPosition(this.$viewport)
+
+ if (/right|left/.test(placement)) {
+ var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
+ var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
+ if (topEdgeOffset < viewportDimensions.top) { // top overflow
+ delta.top = viewportDimensions.top - topEdgeOffset
+ } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
+ delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
+ }
+ } else {
+ var leftEdgeOffset = pos.left - viewportPadding
+ var rightEdgeOffset = pos.left + viewportPadding + actualWidth
+ if (leftEdgeOffset < viewportDimensions.left) { // left overflow
+ delta.left = viewportDimensions.left - leftEdgeOffset
+ } else if (rightEdgeOffset > viewportDimensions.width) { // right overflow
+ delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
+ }
+ }
+
+ return delta
+ }
+
+ Tooltip.prototype.getTitle = function () {
+ var title
+ var $e = this.$element
+ var o = this.options
+
+ title = $e.attr('data-original-title')
+ || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
+
+ return title
+ }
+
+ Tooltip.prototype.getUID = function (prefix) {
+ do prefix += ~~(Math.random() * 1000000)
+ while (document.getElementById(prefix))
+ return prefix
+ }
+
+ Tooltip.prototype.tip = function () {
+ return (this.$tip = this.$tip || $(this.options.template))
+ }
+
+ Tooltip.prototype.arrow = function () {
+ return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
+ }
+
+ Tooltip.prototype.enable = function () {
+ this.enabled = true
+ }
+
+ Tooltip.prototype.disable = function () {
+ this.enabled = false
+ }
+
+ Tooltip.prototype.toggleEnabled = function () {
+ this.enabled = !this.enabled
+ }
+
+ Tooltip.prototype.toggle = function (e) {
+ var self = this
+ if (e) {
+ self = $(e.currentTarget).data('bs.' + this.type)
+ if (!self) {
+ self = new this.constructor(e.currentTarget, this.getDelegateOptions())
+ $(e.currentTarget).data('bs.' + this.type, self)
+ }
+ }
+
+ self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
+ }
+
+ Tooltip.prototype.destroy = function () {
+ var that = this
+ clearTimeout(this.timeout)
+ this.hide(function () {
+ that.$element.off('.' + that.type).removeData('bs.' + that.type)
+ })
+ }
+
+
+ // TOOLTIP PLUGIN DEFINITION
+ // =========================
+
+ function Plugin(option) {
+ return this.each(function () {
+ var $this = $(this)
+ var data = $this.data('bs.tooltip')
+ var options = typeof option == 'object' && option
+
+ if (!data && /destroy|hide/.test(option)) return
+ if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
+ if (typeof option == 'string') data[option]()
+ })
+ }
+
+ var old = $.fn.tooltip
+
+ $.fn.tooltip = Plugin
+ $.fn.tooltip.Constructor = Tooltip
+
+
+ // TOOLTIP NO CONFLICT
+ // ===================
+
+ $.fn.tooltip.noConflict = function () {
+ $.fn.tooltip = old
+ return this
+ }
+
+}(jQuery);
+
+/* ========================================================================
+ * Bootstrap: popover.js v3.3.4
+ * http://getbootstrap.com/javascript/#popovers
+ * ========================================================================
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ * ======================================================================== */
+
+
++function ($) {
+ 'use strict';
+
+ // POPOVER PUBLIC CLASS DEFINITION
+ // ===============================
+
+ var Popover = function (element, options) {
+ this.init('popover', element, options)
+ }
+
+ if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
+
+ Popover.VERSION = '3.3.4'
+
+ Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
+ placement: 'right',
+ trigger: 'click',
+ content: '',
+ template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
+ })
+
+
+ // NOTE: POPOVER EXTENDS tooltip.js
+ // ================================
+
+ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
+
+ Popover.prototype.constructor = Popover
+
+ Popover.prototype.getDefaults = function () {
+ return Popover.DEFAULTS
+ }
+
+ Popover.prototype.setContent = function () {
+ var $tip = this.tip()
+ var title = this.getTitle()
+ var content = this.getContent()
+
+ $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
+ $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
+ this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
+ ](content)
+
+ $tip.removeClass('fade top bottom left right in')
+
+ // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
+ // this manually by checking the contents.
+ if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
+ }
+
+ Popover.prototype.hasContent = function () {
+ return this.getTitle() || this.getContent()
+ }
+
+ Popover.prototype.getContent = function () {
+ var $e = this.$element
+ var o = this.options
+
+ return $e.attr('data-content')
+ || (typeof o.content == 'function' ?
+ o.content.call($e[0]) :
+ o.content)
+ }
+
+ Popover.prototype.arrow = function () {
+ return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
+ }
+
+
+ // POPOVER PLUGIN DEFINITION
+ // =========================
+
+ function Plugin(option) {
+ return this.each(function () {
+ var $this = $(this)
+ var data = $this.data('bs.popover')
+ var options = typeof option == 'object' && option
+
+ if (!data && /destroy|hide/.test(option)) return
+ if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
+ if (typeof option == 'string') data[option]()
+ })
+ }
+
+ var old = $.fn.popover
+
+ $.fn.popover = Plugin
+ $.fn.popover.Constructor = Popover
+
+
+ // POPOVER NO CONFLICT
+ // ===================
+
+ $.fn.popover.noConflict = function () {
+ $.fn.popover = old
+ return this
+ }
+
+}(jQuery);
+
+/* ========================================================================
+ * Bootstrap: scrollspy.js v3.3.4
+ * http://getbootstrap.com/javascript/#scrollspy
+ * ========================================================================
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ * ======================================================================== */
+
+
++function ($) {
+ 'use strict';
+
+ // SCROLLSPY CLASS DEFINITION
+ // ==========================
+
+ function ScrollSpy(element, options) {
+ this.$body = $(document.body)
+ this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
+ this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
+ this.selector = (this.options.target || '') + ' .nav li > a'
+ this.offsets = []
+ this.targets = []
+ this.activeTarget = null
+ this.scrollHeight = 0
+
+ this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
+ this.refresh()
+ this.process()
+ }
+
+ ScrollSpy.VERSION = '3.3.4'
+
+ ScrollSpy.DEFAULTS = {
+ offset: 10
+ }
+
+ ScrollSpy.prototype.getScrollHeight = function () {
+ return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
+ }
+
+ ScrollSpy.prototype.refresh = function () {
+ var that = this
+ var offsetMethod = 'offset'
+ var offsetBase = 0
+
+ this.offsets = []
+ this.targets = []
+ this.scrollHeight = this.getScrollHeight()
+
+ if (!$.isWindow(this.$scrollElement[0])) {
+ offsetMethod = 'position'
+ offsetBase = this.$scrollElement.scrollTop()
+ }
+
+ this.$body
+ .find(this.selector)
+ .map(function () {
+ var $el = $(this)
+ var href = $el.data('target') || $el.attr('href')
+ var $href = /^#./.test(href) && $(href)
+
+ return ($href
+ && $href.length
+ && $href.is(':visible')
+ && [[$href[offsetMethod]().top + offsetBase, href]]) || null
+ })
+ .sort(function (a, b) { return a[0] - b[0] })
+ .each(function () {
+ that.offsets.push(this[0])
+ that.targets.push(this[1])
+ })
+ }
+
+ ScrollSpy.prototype.process = function () {
+ var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
+ var scrollHeight = this.getScrollHeight()
+ var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
+ var offsets = this.offsets
+ var targets = this.targets
+ var activeTarget = this.activeTarget
+ var i
+
+ if (this.scrollHeight != scrollHeight) {
+ this.refresh()
+ }
+
+ if (scrollTop >= maxScroll) {
+ return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
+ }
+
+ if (activeTarget && scrollTop < offsets[0]) {
+ this.activeTarget = null
+ return this.clear()
+ }
+
+ for (i = offsets.length; i--;) {
+ activeTarget != targets[i]
+ && scrollTop >= offsets[i]
+ && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1])
+ && this.activate(targets[i])
+ }
+ }
+
+ ScrollSpy.prototype.activate = function (target) {
+ this.activeTarget = target
+
+ this.clear()
+
+ var selector = this.selector +
+ '[data-target="' + target + '"],' +
+ this.selector + '[href="' + target + '"]'
+
+ var active = $(selector)
+ .parents('li')
+ .addClass('active')
+
+ if (active.parent('.dropdown-menu').length) {
+ active = active
+ .closest('li.dropdown')
+ .addClass('active')
+ }
+
+ active.trigger('activate.bs.scrollspy')
+ }
+
+ ScrollSpy.prototype.clear = function () {
+ $(this.selector)
+ .parentsUntil(this.options.target, '.active')
+ .removeClass('active')
+ }
+
+
+ // SCROLLSPY PLUGIN DEFINITION
+ // ===========================
+
+ function Plugin(option) {
+ return this.each(function () {
+ var $this = $(this)
+ var data = $this.data('bs.scrollspy')
+ var options = typeof option == 'object' && option
+
+ if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
+ if (typeof option == 'string') data[option]()
+ })
+ }
+
+ var old = $.fn.scrollspy
+
+ $.fn.scrollspy = Plugin
+ $.fn.scrollspy.Constructor = ScrollSpy
+
+
+ // SCROLLSPY NO CONFLICT
+ // =====================
+
+ $.fn.scrollspy.noConflict = function () {
+ $.fn.scrollspy = old
+ return this
+ }
+
+
+ // SCROLLSPY DATA-API
+ // ==================
+
+ $(window).on('load.bs.scrollspy.data-api', function () {
+ $('[data-spy="scroll"]').each(function () {
+ var $spy = $(this)
+ Plugin.call($spy, $spy.data())
+ })
+ })
+
+}(jQuery);
+
+/* ========================================================================
+ * Bootstrap: tab.js v3.3.4
+ * http://getbootstrap.com/javascript/#tabs
+ * ========================================================================
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ * ======================================================================== */
+
+
++function ($) {
+ 'use strict';
+
+ // TAB CLASS DEFINITION
+ // ====================
+
+ var Tab = function (element) {
+ this.element = $(element)
+ }
+
+ Tab.VERSION = '3.3.4'
+
+ Tab.TRANSITION_DURATION = 150
+
+ Tab.prototype.show = function () {
+ var $this = this.element
+ var $ul = $this.closest('ul:not(.dropdown-menu)')
+ var selector = $this.data('target')
+
+ if (!selector) {
+ selector = $this.attr('href')
+ selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
+ }
+
+ if ($this.parent('li').hasClass('active')) return
+
+ var $previous = $ul.find('.active:last a')
+ var hideEvent = $.Event('hide.bs.tab', {
+ relatedTarget: $this[0]
+ })
+ var showEvent = $.Event('show.bs.tab', {
+ relatedTarget: $previous[0]
+ })
+
+ $previous.trigger(hideEvent)
+ $this.trigger(showEvent)
+
+ if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
+
+ var $target = $(selector)
+
+ this.activate($this.closest('li'), $ul)
+ this.activate($target, $target.parent(), function () {
+ $previous.trigger({
+ type: 'hidden.bs.tab',
+ relatedTarget: $this[0]
+ })
+ $this.trigger({
+ type: 'shown.bs.tab',
+ relatedTarget: $previous[0]
+ })
+ })
+ }
+
+ Tab.prototype.activate = function (element, container, callback) {
+ var $active = container.find('> .active')
+ var transition = callback
+ && $.support.transition
+ && (($active.length && $active.hasClass('fade')) || !!container.find('> .fade').length)
+
+ function next() {
+ $active
+ .removeClass('active')
+ .find('> .dropdown-menu > .active')
+ .removeClass('active')
+ .end()
+ .find('[data-toggle="tab"]')
+ .attr('aria-expanded', false)
+
+ element
+ .addClass('active')
+ .find('[data-toggle="tab"]')
+ .attr('aria-expanded', true)
+
+ if (transition) {
+ element[0].offsetWidth // reflow for transition
+ element.addClass('in')
+ } else {
+ element.removeClass('fade')
+ }
+
+ if (element.parent('.dropdown-menu').length) {
+ element
+ .closest('li.dropdown')
+ .addClass('active')
+ .end()
+ .find('[data-toggle="tab"]')
+ .attr('aria-expanded', true)
+ }
+
+ callback && callback()
+ }
+
+ $active.length && transition ?
+ $active
+ .one('bsTransitionEnd', next)
+ .emulateTransitionEnd(Tab.TRANSITION_DURATION) :
+ next()
+
+ $active.removeClass('in')
+ }
+
+
+ // TAB PLUGIN DEFINITION
+ // =====================
+
+ function Plugin(option) {
+ return this.each(function () {
+ var $this = $(this)
+ var data = $this.data('bs.tab')
+
+ if (!data) $this.data('bs.tab', (data = new Tab(this)))
+ if (typeof option == 'string') data[option]()
+ })
+ }
+
+ var old = $.fn.tab
+
+ $.fn.tab = Plugin
+ $.fn.tab.Constructor = Tab
+
+
+ // TAB NO CONFLICT
+ // ===============
+
+ $.fn.tab.noConflict = function () {
+ $.fn.tab = old
+ return this
+ }
+
+
+ // TAB DATA-API
+ // ============
+
+ var clickHandler = function (e) {
+ e.preventDefault()
+ Plugin.call($(this), 'show')
+ }
+
+ $(document)
+ .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
+ .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
+
+}(jQuery);
+
+/* ========================================================================
+ * Bootstrap: affix.js v3.3.4
+ * http://getbootstrap.com/javascript/#affix
+ * ========================================================================
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ * ======================================================================== */
+
+
++function ($) {
+ 'use strict';
+
+ // AFFIX CLASS DEFINITION
+ // ======================
+
+ var Affix = function (element, options) {
+ this.options = $.extend({}, Affix.DEFAULTS, options)
+
+ this.$target = $(this.options.target)
+ .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
+ .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
+
+ this.$element = $(element)
+ this.affixed = null
+ this.unpin = null
+ this.pinnedOffset = null
+
+ this.checkPosition()
+ }
+
+ Affix.VERSION = '3.3.4'
+
+ Affix.RESET = 'affix affix-top affix-bottom'
+
+ Affix.DEFAULTS = {
+ offset: 0,
+ target: window
+ }
+
+ Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
+ var scrollTop = this.$target.scrollTop()
+ var position = this.$element.offset()
+ var targetHeight = this.$target.height()
+
+ if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
+
+ if (this.affixed == 'bottom') {
+ if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
+ return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
+ }
+
+ var initializing = this.affixed == null
+ var colliderTop = initializing ? scrollTop : position.top
+ var colliderHeight = initializing ? targetHeight : height
+
+ if (offsetTop != null && scrollTop <= offsetTop) return 'top'
+ if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
+
+ return false
+ }
+
+ Affix.prototype.getPinnedOffset = function () {
+ if (this.pinnedOffset) return this.pinnedOffset
+ this.$element.removeClass(Affix.RESET).addClass('affix')
+ var scrollTop = this.$target.scrollTop()
+ var position = this.$element.offset()
+ return (this.pinnedOffset = position.top - scrollTop)
+ }
+
+ Affix.prototype.checkPositionWithEventLoop = function () {
+ setTimeout($.proxy(this.checkPosition, this), 1)
+ }
+
+ Affix.prototype.checkPosition = function () {
+ if (!this.$element.is(':visible')) return
+
+ var height = this.$element.height()
+ var offset = this.options.offset
+ var offsetTop = offset.top
+ var offsetBottom = offset.bottom
+ var scrollHeight = $(document.body).height()
+
+ if (typeof offset != 'object') offsetBottom = offsetTop = offset
+ if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
+ if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
+
+ var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
+
+ if (this.affixed != affix) {
+ if (this.unpin != null) this.$element.css('top', '')
+
+ var affixType = 'affix' + (affix ? '-' + affix : '')
+ var e = $.Event(affixType + '.bs.affix')
+
+ this.$element.trigger(e)
+
+ if (e.isDefaultPrevented()) return
+
+ this.affixed = affix
+ this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
+
+ this.$element
+ .removeClass(Affix.RESET)
+ .addClass(affixType)
+ .trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
+ }
+
+ if (affix == 'bottom') {
+ this.$element.offset({
+ top: scrollHeight - height - offsetBottom
+ })
+ }
+ }
+
+
+ // AFFIX PLUGIN DEFINITION
+ // =======================
+
+ function Plugin(option) {
+ return this.each(function () {
+ var $this = $(this)
+ var data = $this.data('bs.affix')
+ var options = typeof option == 'object' && option
+
+ if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
+ if (typeof option == 'string') data[option]()
+ })
+ }
+
+ var old = $.fn.affix
+
+ $.fn.affix = Plugin
+ $.fn.affix.Constructor = Affix
+
+
+ // AFFIX NO CONFLICT
+ // =================
+
+ $.fn.affix.noConflict = function () {
+ $.fn.affix = old
+ return this
+ }
+
+
+ // AFFIX DATA-API
+ // ==============
+
+ $(window).on('load', function () {
+ $('[data-spy="affix"]').each(function () {
+ var $spy = $(this)
+ var data = $spy.data()
+
+ data.offset = data.offset || {}
+
+ if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
+ if (data.offsetTop != null) data.offset.top = data.offsetTop
+
+ Plugin.call($spy, data)
+ })
+ })
+
+}(jQuery);
diff --git a/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/js/bootstrap.min.js b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/js/bootstrap.min.js
new file mode 100644
index 0000000..c8f82e5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/bootstrap-css/js/bootstrap.min.js
@@ -0,0 +1,7 @@
+/*!
+ * Bootstrap v3.3.4 (http://getbootstrap.com)
+ * Copyright 2011-2015 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ */
+if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.4",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.4",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active"));a&&this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.4",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.4",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){b&&3===b.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=c(d),f={relatedTarget:this};e.hasClass("open")&&(e.trigger(b=a.Event("hide.bs.dropdown",f)),b.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f)))}))}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.4",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(b){if(/(38|40|27|32)/.test(b.which)&&!/input|textarea/i.test(b.target.tagName)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var e=c(d),g=e.hasClass("open");if(!g&&27!=b.which||g&&27==b.which)return 27==b.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find('[role="menu"]'+h+', [role="listbox"]'+h);if(i.length){var j=i.index(b.target);38==b.which&&j>0&&j--,40==b.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="menu"]',g.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="listbox"]',g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.4",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){d.$element.one("mouseup.dismiss.bs.modal",function(b){a(b.target).is(d.$element)&&(d.ignoreBackdropClick=!0)})}),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),d.adjustDialog(),e&&d.$element[0].offsetWidth,d.$element.addClass("in").attr("aria-hidden",!1),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$dialog.one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a('<div class="modal-backdrop '+e+'" />').appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.adjustDialog()},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth<a,this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"",this.bodyIsOverflowing&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad)},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.init("tooltip",a,b)};c.VERSION="3.3.4",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport),this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c&&c.$tip&&c.$tip.is(":visible")?void(c.hoverState="in"):(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.options.container?a(this.options.container):this.$element.parent(),p=this.getPosition(o);h="bottom"==h&&k.bottom+m>p.bottom?"top":"top"==h&&k.top-m<p.top?"bottom":"right"==h&&k.right+l>p.width?"left":"left"==h&&k.left-l<p.left?"right":h,f.removeClass(n).addClass(h)}var q=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(q,h);var r=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",r).emulateTransitionEnd(c.TRANSITION_DURATION):r()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top=b.top+g,b.left=b.left+h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=a(this.$tip),g=a.Event("hide.bs."+this.type);return this.$element.trigger(g),g.isDefaultPrevented()?void 0:(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=d?{top:0,left:0}:b.offset(),g={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},h=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,g,h,f)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type)})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.4",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.4",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(void 0===e[a+1]||b<e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.4",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){
+var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.4",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=a(document.body).height();"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/.bower.json b/xos-apps/auto-scale/gui/src/vendor/jquery/.bower.json
new file mode 100644
index 0000000..a5f3c21
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/.bower.json
@@ -0,0 +1,38 @@
+{
+ "name": "jquery",
+ "version": "2.1.4",
+ "main": "dist/jquery.js",
+ "license": "MIT",
+ "ignore": [
+ "**/.*",
+ "build",
+ "dist/cdn",
+ "speed",
+ "test",
+ "*.md",
+ "AUTHORS.txt",
+ "Gruntfile.js",
+ "package.json"
+ ],
+ "devDependencies": {
+ "sizzle": "2.1.1-jquery.2.1.2",
+ "requirejs": "2.1.10",
+ "qunit": "1.14.0",
+ "sinon": "1.8.1"
+ },
+ "keywords": [
+ "jquery",
+ "javascript",
+ "library"
+ ],
+ "homepage": "https://github.com/jquery/jquery",
+ "_release": "2.1.4",
+ "_resolution": {
+ "type": "version",
+ "tag": "2.1.4",
+ "commit": "7751e69b615c6eca6f783a81e292a55725af6b85"
+ },
+ "_source": "git://github.com/jquery/jquery.git",
+ "_target": "~2.1.4",
+ "_originalSource": "jquery"
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/MIT-LICENSE.txt b/xos-apps/auto-scale/gui/src/vendor/jquery/MIT-LICENSE.txt
new file mode 100644
index 0000000..cdd31b5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/MIT-LICENSE.txt
@@ -0,0 +1,21 @@
+Copyright 2014 jQuery Foundation and other contributors
+http://jquery.com/
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/bower.json b/xos-apps/auto-scale/gui/src/vendor/jquery/bower.json
new file mode 100644
index 0000000..0c80cd5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/bower.json
@@ -0,0 +1,28 @@
+{
+ "name": "jquery",
+ "version": "2.1.4",
+ "main": "dist/jquery.js",
+ "license": "MIT",
+ "ignore": [
+ "**/.*",
+ "build",
+ "dist/cdn",
+ "speed",
+ "test",
+ "*.md",
+ "AUTHORS.txt",
+ "Gruntfile.js",
+ "package.json"
+ ],
+ "devDependencies": {
+ "sizzle": "2.1.1-jquery.2.1.2",
+ "requirejs": "2.1.10",
+ "qunit": "1.14.0",
+ "sinon": "1.8.1"
+ },
+ "keywords": [
+ "jquery",
+ "javascript",
+ "library"
+ ]
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax.js
new file mode 100644
index 0000000..5c7b4ad
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax.js
@@ -0,0 +1,786 @@
+define([
+ "./core",
+ "./var/rnotwhite",
+ "./ajax/var/nonce",
+ "./ajax/var/rquery",
+ "./core/init",
+ "./ajax/parseJSON",
+ "./ajax/parseXML",
+ "./deferred"
+], function( jQuery, rnotwhite, nonce, rquery ) {
+
+var
+ rhash = /#.*$/,
+ rts = /([?&])_=[^&]*/,
+ rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
+ // #7653, #8125, #8152: local protocol detection
+ rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
+ rnoContent = /^(?:GET|HEAD)$/,
+ rprotocol = /^\/\//,
+ rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
+
+ /* Prefilters
+ * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
+ * 2) These are called:
+ * - BEFORE asking for a transport
+ * - AFTER param serialization (s.data is a string if s.processData is true)
+ * 3) key is the dataType
+ * 4) the catchall symbol "*" can be used
+ * 5) execution will start with transport dataType and THEN continue down to "*" if needed
+ */
+ prefilters = {},
+
+ /* Transports bindings
+ * 1) key is the dataType
+ * 2) the catchall symbol "*" can be used
+ * 3) selection will start with transport dataType and THEN go to "*" if needed
+ */
+ transports = {},
+
+ // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
+ allTypes = "*/".concat( "*" ),
+
+ // Document location
+ ajaxLocation = window.location.href,
+
+ // Segment location into parts
+ ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
+
+// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
+function addToPrefiltersOrTransports( structure ) {
+
+ // dataTypeExpression is optional and defaults to "*"
+ return function( dataTypeExpression, func ) {
+
+ if ( typeof dataTypeExpression !== "string" ) {
+ func = dataTypeExpression;
+ dataTypeExpression = "*";
+ }
+
+ var dataType,
+ i = 0,
+ dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
+
+ if ( jQuery.isFunction( func ) ) {
+ // For each dataType in the dataTypeExpression
+ while ( (dataType = dataTypes[i++]) ) {
+ // Prepend if requested
+ if ( dataType[0] === "+" ) {
+ dataType = dataType.slice( 1 ) || "*";
+ (structure[ dataType ] = structure[ dataType ] || []).unshift( func );
+
+ // Otherwise append
+ } else {
+ (structure[ dataType ] = structure[ dataType ] || []).push( func );
+ }
+ }
+ }
+ };
+}
+
+// Base inspection function for prefilters and transports
+function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
+
+ var inspected = {},
+ seekingTransport = ( structure === transports );
+
+ function inspect( dataType ) {
+ var selected;
+ inspected[ dataType ] = true;
+ jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
+ var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
+ if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
+ options.dataTypes.unshift( dataTypeOrTransport );
+ inspect( dataTypeOrTransport );
+ return false;
+ } else if ( seekingTransport ) {
+ return !( selected = dataTypeOrTransport );
+ }
+ });
+ return selected;
+ }
+
+ return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
+}
+
+// A special extend for ajax options
+// that takes "flat" options (not to be deep extended)
+// Fixes #9887
+function ajaxExtend( target, src ) {
+ var key, deep,
+ flatOptions = jQuery.ajaxSettings.flatOptions || {};
+
+ for ( key in src ) {
+ if ( src[ key ] !== undefined ) {
+ ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
+ }
+ }
+ if ( deep ) {
+ jQuery.extend( true, target, deep );
+ }
+
+ return target;
+}
+
+/* Handles responses to an ajax request:
+ * - finds the right dataType (mediates between content-type and expected dataType)
+ * - returns the corresponding response
+ */
+function ajaxHandleResponses( s, jqXHR, responses ) {
+
+ var ct, type, finalDataType, firstDataType,
+ contents = s.contents,
+ dataTypes = s.dataTypes;
+
+ // Remove auto dataType and get content-type in the process
+ while ( dataTypes[ 0 ] === "*" ) {
+ dataTypes.shift();
+ if ( ct === undefined ) {
+ ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
+ }
+ }
+
+ // Check if we're dealing with a known content-type
+ if ( ct ) {
+ for ( type in contents ) {
+ if ( contents[ type ] && contents[ type ].test( ct ) ) {
+ dataTypes.unshift( type );
+ break;
+ }
+ }
+ }
+
+ // Check to see if we have a response for the expected dataType
+ if ( dataTypes[ 0 ] in responses ) {
+ finalDataType = dataTypes[ 0 ];
+ } else {
+ // Try convertible dataTypes
+ for ( type in responses ) {
+ if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
+ finalDataType = type;
+ break;
+ }
+ if ( !firstDataType ) {
+ firstDataType = type;
+ }
+ }
+ // Or just use first one
+ finalDataType = finalDataType || firstDataType;
+ }
+
+ // If we found a dataType
+ // We add the dataType to the list if needed
+ // and return the corresponding response
+ if ( finalDataType ) {
+ if ( finalDataType !== dataTypes[ 0 ] ) {
+ dataTypes.unshift( finalDataType );
+ }
+ return responses[ finalDataType ];
+ }
+}
+
+/* Chain conversions given the request and the original response
+ * Also sets the responseXXX fields on the jqXHR instance
+ */
+function ajaxConvert( s, response, jqXHR, isSuccess ) {
+ var conv2, current, conv, tmp, prev,
+ converters = {},
+ // Work with a copy of dataTypes in case we need to modify it for conversion
+ dataTypes = s.dataTypes.slice();
+
+ // Create converters map with lowercased keys
+ if ( dataTypes[ 1 ] ) {
+ for ( conv in s.converters ) {
+ converters[ conv.toLowerCase() ] = s.converters[ conv ];
+ }
+ }
+
+ current = dataTypes.shift();
+
+ // Convert to each sequential dataType
+ while ( current ) {
+
+ if ( s.responseFields[ current ] ) {
+ jqXHR[ s.responseFields[ current ] ] = response;
+ }
+
+ // Apply the dataFilter if provided
+ if ( !prev && isSuccess && s.dataFilter ) {
+ response = s.dataFilter( response, s.dataType );
+ }
+
+ prev = current;
+ current = dataTypes.shift();
+
+ if ( current ) {
+
+ // There's only work to do if current dataType is non-auto
+ if ( current === "*" ) {
+
+ current = prev;
+
+ // Convert response if prev dataType is non-auto and differs from current
+ } else if ( prev !== "*" && prev !== current ) {
+
+ // Seek a direct converter
+ conv = converters[ prev + " " + current ] || converters[ "* " + current ];
+
+ // If none found, seek a pair
+ if ( !conv ) {
+ for ( conv2 in converters ) {
+
+ // If conv2 outputs current
+ tmp = conv2.split( " " );
+ if ( tmp[ 1 ] === current ) {
+
+ // If prev can be converted to accepted input
+ conv = converters[ prev + " " + tmp[ 0 ] ] ||
+ converters[ "* " + tmp[ 0 ] ];
+ if ( conv ) {
+ // Condense equivalence converters
+ if ( conv === true ) {
+ conv = converters[ conv2 ];
+
+ // Otherwise, insert the intermediate dataType
+ } else if ( converters[ conv2 ] !== true ) {
+ current = tmp[ 0 ];
+ dataTypes.unshift( tmp[ 1 ] );
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ // Apply converter (if not an equivalence)
+ if ( conv !== true ) {
+
+ // Unless errors are allowed to bubble, catch and return them
+ if ( conv && s[ "throws" ] ) {
+ response = conv( response );
+ } else {
+ try {
+ response = conv( response );
+ } catch ( e ) {
+ return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return { state: "success", data: response };
+}
+
+jQuery.extend({
+
+ // Counter for holding the number of active queries
+ active: 0,
+
+ // Last-Modified header cache for next request
+ lastModified: {},
+ etag: {},
+
+ ajaxSettings: {
+ url: ajaxLocation,
+ type: "GET",
+ isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
+ global: true,
+ processData: true,
+ async: true,
+ contentType: "application/x-www-form-urlencoded; charset=UTF-8",
+ /*
+ timeout: 0,
+ data: null,
+ dataType: null,
+ username: null,
+ password: null,
+ cache: null,
+ throws: false,
+ traditional: false,
+ headers: {},
+ */
+
+ accepts: {
+ "*": allTypes,
+ text: "text/plain",
+ html: "text/html",
+ xml: "application/xml, text/xml",
+ json: "application/json, text/javascript"
+ },
+
+ contents: {
+ xml: /xml/,
+ html: /html/,
+ json: /json/
+ },
+
+ responseFields: {
+ xml: "responseXML",
+ text: "responseText",
+ json: "responseJSON"
+ },
+
+ // Data converters
+ // Keys separate source (or catchall "*") and destination types with a single space
+ converters: {
+
+ // Convert anything to text
+ "* text": String,
+
+ // Text to html (true = no transformation)
+ "text html": true,
+
+ // Evaluate text as a json expression
+ "text json": jQuery.parseJSON,
+
+ // Parse text as xml
+ "text xml": jQuery.parseXML
+ },
+
+ // For options that shouldn't be deep extended:
+ // you can add your own custom options here if
+ // and when you create one that shouldn't be
+ // deep extended (see ajaxExtend)
+ flatOptions: {
+ url: true,
+ context: true
+ }
+ },
+
+ // Creates a full fledged settings object into target
+ // with both ajaxSettings and settings fields.
+ // If target is omitted, writes into ajaxSettings.
+ ajaxSetup: function( target, settings ) {
+ return settings ?
+
+ // Building a settings object
+ ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
+
+ // Extending ajaxSettings
+ ajaxExtend( jQuery.ajaxSettings, target );
+ },
+
+ ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
+ ajaxTransport: addToPrefiltersOrTransports( transports ),
+
+ // Main method
+ ajax: function( url, options ) {
+
+ // If url is an object, simulate pre-1.5 signature
+ if ( typeof url === "object" ) {
+ options = url;
+ url = undefined;
+ }
+
+ // Force options to be an object
+ options = options || {};
+
+ var transport,
+ // URL without anti-cache param
+ cacheURL,
+ // Response headers
+ responseHeadersString,
+ responseHeaders,
+ // timeout handle
+ timeoutTimer,
+ // Cross-domain detection vars
+ parts,
+ // To know if global events are to be dispatched
+ fireGlobals,
+ // Loop variable
+ i,
+ // Create the final options object
+ s = jQuery.ajaxSetup( {}, options ),
+ // Callbacks context
+ callbackContext = s.context || s,
+ // Context for global events is callbackContext if it is a DOM node or jQuery collection
+ globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
+ jQuery( callbackContext ) :
+ jQuery.event,
+ // Deferreds
+ deferred = jQuery.Deferred(),
+ completeDeferred = jQuery.Callbacks("once memory"),
+ // Status-dependent callbacks
+ statusCode = s.statusCode || {},
+ // Headers (they are sent all at once)
+ requestHeaders = {},
+ requestHeadersNames = {},
+ // The jqXHR state
+ state = 0,
+ // Default abort message
+ strAbort = "canceled",
+ // Fake xhr
+ jqXHR = {
+ readyState: 0,
+
+ // Builds headers hashtable if needed
+ getResponseHeader: function( key ) {
+ var match;
+ if ( state === 2 ) {
+ if ( !responseHeaders ) {
+ responseHeaders = {};
+ while ( (match = rheaders.exec( responseHeadersString )) ) {
+ responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
+ }
+ }
+ match = responseHeaders[ key.toLowerCase() ];
+ }
+ return match == null ? null : match;
+ },
+
+ // Raw string
+ getAllResponseHeaders: function() {
+ return state === 2 ? responseHeadersString : null;
+ },
+
+ // Caches the header
+ setRequestHeader: function( name, value ) {
+ var lname = name.toLowerCase();
+ if ( !state ) {
+ name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
+ requestHeaders[ name ] = value;
+ }
+ return this;
+ },
+
+ // Overrides response content-type header
+ overrideMimeType: function( type ) {
+ if ( !state ) {
+ s.mimeType = type;
+ }
+ return this;
+ },
+
+ // Status-dependent callbacks
+ statusCode: function( map ) {
+ var code;
+ if ( map ) {
+ if ( state < 2 ) {
+ for ( code in map ) {
+ // Lazy-add the new callback in a way that preserves old ones
+ statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
+ }
+ } else {
+ // Execute the appropriate callbacks
+ jqXHR.always( map[ jqXHR.status ] );
+ }
+ }
+ return this;
+ },
+
+ // Cancel the request
+ abort: function( statusText ) {
+ var finalText = statusText || strAbort;
+ if ( transport ) {
+ transport.abort( finalText );
+ }
+ done( 0, finalText );
+ return this;
+ }
+ };
+
+ // Attach deferreds
+ deferred.promise( jqXHR ).complete = completeDeferred.add;
+ jqXHR.success = jqXHR.done;
+ jqXHR.error = jqXHR.fail;
+
+ // Remove hash character (#7531: and string promotion)
+ // Add protocol if not provided (prefilters might expect it)
+ // Handle falsy url in the settings object (#10093: consistency with old signature)
+ // We also use the url parameter if available
+ s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" )
+ .replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
+
+ // Alias method option to type as per ticket #12004
+ s.type = options.method || options.type || s.method || s.type;
+
+ // Extract dataTypes list
+ s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
+
+ // A cross-domain request is in order when we have a protocol:host:port mismatch
+ if ( s.crossDomain == null ) {
+ parts = rurl.exec( s.url.toLowerCase() );
+ s.crossDomain = !!( parts &&
+ ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
+ ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
+ ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
+ );
+ }
+
+ // Convert data if not already a string
+ if ( s.data && s.processData && typeof s.data !== "string" ) {
+ s.data = jQuery.param( s.data, s.traditional );
+ }
+
+ // Apply prefilters
+ inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
+
+ // If request was aborted inside a prefilter, stop there
+ if ( state === 2 ) {
+ return jqXHR;
+ }
+
+ // We can fire global events as of now if asked to
+ // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
+ fireGlobals = jQuery.event && s.global;
+
+ // Watch for a new set of requests
+ if ( fireGlobals && jQuery.active++ === 0 ) {
+ jQuery.event.trigger("ajaxStart");
+ }
+
+ // Uppercase the type
+ s.type = s.type.toUpperCase();
+
+ // Determine if request has content
+ s.hasContent = !rnoContent.test( s.type );
+
+ // Save the URL in case we're toying with the If-Modified-Since
+ // and/or If-None-Match header later on
+ cacheURL = s.url;
+
+ // More options handling for requests with no content
+ if ( !s.hasContent ) {
+
+ // If data is available, append data to url
+ if ( s.data ) {
+ cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
+ // #9682: remove data so that it's not used in an eventual retry
+ delete s.data;
+ }
+
+ // Add anti-cache in url if needed
+ if ( s.cache === false ) {
+ s.url = rts.test( cacheURL ) ?
+
+ // If there is already a '_' parameter, set its value
+ cacheURL.replace( rts, "$1_=" + nonce++ ) :
+
+ // Otherwise add one to the end
+ cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
+ }
+ }
+
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
+ if ( jQuery.lastModified[ cacheURL ] ) {
+ jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
+ }
+ if ( jQuery.etag[ cacheURL ] ) {
+ jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
+ }
+ }
+
+ // Set the correct header, if data is being sent
+ if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
+ jqXHR.setRequestHeader( "Content-Type", s.contentType );
+ }
+
+ // Set the Accepts header for the server, depending on the dataType
+ jqXHR.setRequestHeader(
+ "Accept",
+ s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
+ s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
+ s.accepts[ "*" ]
+ );
+
+ // Check for headers option
+ for ( i in s.headers ) {
+ jqXHR.setRequestHeader( i, s.headers[ i ] );
+ }
+
+ // Allow custom headers/mimetypes and early abort
+ if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
+ // Abort if not done already and return
+ return jqXHR.abort();
+ }
+
+ // Aborting is no longer a cancellation
+ strAbort = "abort";
+
+ // Install callbacks on deferreds
+ for ( i in { success: 1, error: 1, complete: 1 } ) {
+ jqXHR[ i ]( s[ i ] );
+ }
+
+ // Get transport
+ transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
+
+ // If no transport, we auto-abort
+ if ( !transport ) {
+ done( -1, "No Transport" );
+ } else {
+ jqXHR.readyState = 1;
+
+ // Send global event
+ if ( fireGlobals ) {
+ globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
+ }
+ // Timeout
+ if ( s.async && s.timeout > 0 ) {
+ timeoutTimer = setTimeout(function() {
+ jqXHR.abort("timeout");
+ }, s.timeout );
+ }
+
+ try {
+ state = 1;
+ transport.send( requestHeaders, done );
+ } catch ( e ) {
+ // Propagate exception as error if not done
+ if ( state < 2 ) {
+ done( -1, e );
+ // Simply rethrow otherwise
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ // Callback for when everything is done
+ function done( status, nativeStatusText, responses, headers ) {
+ var isSuccess, success, error, response, modified,
+ statusText = nativeStatusText;
+
+ // Called once
+ if ( state === 2 ) {
+ return;
+ }
+
+ // State is "done" now
+ state = 2;
+
+ // Clear timeout if it exists
+ if ( timeoutTimer ) {
+ clearTimeout( timeoutTimer );
+ }
+
+ // Dereference transport for early garbage collection
+ // (no matter how long the jqXHR object will be used)
+ transport = undefined;
+
+ // Cache response headers
+ responseHeadersString = headers || "";
+
+ // Set readyState
+ jqXHR.readyState = status > 0 ? 4 : 0;
+
+ // Determine if successful
+ isSuccess = status >= 200 && status < 300 || status === 304;
+
+ // Get response data
+ if ( responses ) {
+ response = ajaxHandleResponses( s, jqXHR, responses );
+ }
+
+ // Convert no matter what (that way responseXXX fields are always set)
+ response = ajaxConvert( s, response, jqXHR, isSuccess );
+
+ // If successful, handle type chaining
+ if ( isSuccess ) {
+
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
+ modified = jqXHR.getResponseHeader("Last-Modified");
+ if ( modified ) {
+ jQuery.lastModified[ cacheURL ] = modified;
+ }
+ modified = jqXHR.getResponseHeader("etag");
+ if ( modified ) {
+ jQuery.etag[ cacheURL ] = modified;
+ }
+ }
+
+ // if no content
+ if ( status === 204 || s.type === "HEAD" ) {
+ statusText = "nocontent";
+
+ // if not modified
+ } else if ( status === 304 ) {
+ statusText = "notmodified";
+
+ // If we have data, let's convert it
+ } else {
+ statusText = response.state;
+ success = response.data;
+ error = response.error;
+ isSuccess = !error;
+ }
+ } else {
+ // Extract error from statusText and normalize for non-aborts
+ error = statusText;
+ if ( status || !statusText ) {
+ statusText = "error";
+ if ( status < 0 ) {
+ status = 0;
+ }
+ }
+ }
+
+ // Set data for the fake xhr object
+ jqXHR.status = status;
+ jqXHR.statusText = ( nativeStatusText || statusText ) + "";
+
+ // Success/Error
+ if ( isSuccess ) {
+ deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
+ } else {
+ deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
+ }
+
+ // Status-dependent callbacks
+ jqXHR.statusCode( statusCode );
+ statusCode = undefined;
+
+ if ( fireGlobals ) {
+ globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
+ [ jqXHR, s, isSuccess ? success : error ] );
+ }
+
+ // Complete
+ completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
+
+ if ( fireGlobals ) {
+ globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
+ // Handle the global AJAX counter
+ if ( !( --jQuery.active ) ) {
+ jQuery.event.trigger("ajaxStop");
+ }
+ }
+ }
+
+ return jqXHR;
+ },
+
+ getJSON: function( url, data, callback ) {
+ return jQuery.get( url, data, callback, "json" );
+ },
+
+ getScript: function( url, callback ) {
+ return jQuery.get( url, undefined, callback, "script" );
+ }
+});
+
+jQuery.each( [ "get", "post" ], function( i, method ) {
+ jQuery[ method ] = function( url, data, callback, type ) {
+ // Shift arguments if data argument was omitted
+ if ( jQuery.isFunction( data ) ) {
+ type = type || callback;
+ callback = data;
+ data = undefined;
+ }
+
+ return jQuery.ajax({
+ url: url,
+ type: method,
+ dataType: type,
+ data: data,
+ success: callback
+ });
+ };
+});
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/jsonp.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/jsonp.js
new file mode 100644
index 0000000..ff0d538
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/jsonp.js
@@ -0,0 +1,89 @@
+define([
+ "../core",
+ "./var/nonce",
+ "./var/rquery",
+ "../ajax"
+], function( jQuery, nonce, rquery ) {
+
+var oldCallbacks = [],
+ rjsonp = /(=)\?(?=&|$)|\?\?/;
+
+// Default jsonp settings
+jQuery.ajaxSetup({
+ jsonp: "callback",
+ jsonpCallback: function() {
+ var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
+ this[ callback ] = true;
+ return callback;
+ }
+});
+
+// Detect, normalize options and install callbacks for jsonp requests
+jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
+
+ var callbackName, overwritten, responseContainer,
+ jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
+ "url" :
+ typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
+ );
+
+ // Handle iff the expected data type is "jsonp" or we have a parameter to set
+ if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
+
+ // Get callback name, remembering preexisting value associated with it
+ callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
+ s.jsonpCallback() :
+ s.jsonpCallback;
+
+ // Insert callback into url or form data
+ if ( jsonProp ) {
+ s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
+ } else if ( s.jsonp !== false ) {
+ s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
+ }
+
+ // Use data converter to retrieve json after script execution
+ s.converters["script json"] = function() {
+ if ( !responseContainer ) {
+ jQuery.error( callbackName + " was not called" );
+ }
+ return responseContainer[ 0 ];
+ };
+
+ // force json dataType
+ s.dataTypes[ 0 ] = "json";
+
+ // Install callback
+ overwritten = window[ callbackName ];
+ window[ callbackName ] = function() {
+ responseContainer = arguments;
+ };
+
+ // Clean-up function (fires after converters)
+ jqXHR.always(function() {
+ // Restore preexisting value
+ window[ callbackName ] = overwritten;
+
+ // Save back as free
+ if ( s[ callbackName ] ) {
+ // make sure that re-using the options doesn't screw things around
+ s.jsonpCallback = originalSettings.jsonpCallback;
+
+ // save the callback name for future use
+ oldCallbacks.push( callbackName );
+ }
+
+ // Call if it was a function and we have a response
+ if ( responseContainer && jQuery.isFunction( overwritten ) ) {
+ overwritten( responseContainer[ 0 ] );
+ }
+
+ responseContainer = overwritten = undefined;
+ });
+
+ // Delegate to script
+ return "script";
+ }
+});
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/load.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/load.js
new file mode 100644
index 0000000..bff25b1
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/load.js
@@ -0,0 +1,75 @@
+define([
+ "../core",
+ "../core/parseHTML",
+ "../ajax",
+ "../traversing",
+ "../manipulation",
+ "../selector",
+ // Optional event/alias dependency
+ "../event/alias"
+], function( jQuery ) {
+
+// Keep a copy of the old load method
+var _load = jQuery.fn.load;
+
+/**
+ * Load a url into a page
+ */
+jQuery.fn.load = function( url, params, callback ) {
+ if ( typeof url !== "string" && _load ) {
+ return _load.apply( this, arguments );
+ }
+
+ var selector, type, response,
+ self = this,
+ off = url.indexOf(" ");
+
+ if ( off >= 0 ) {
+ selector = jQuery.trim( url.slice( off ) );
+ url = url.slice( 0, off );
+ }
+
+ // If it's a function
+ if ( jQuery.isFunction( params ) ) {
+
+ // We assume that it's the callback
+ callback = params;
+ params = undefined;
+
+ // Otherwise, build a param string
+ } else if ( params && typeof params === "object" ) {
+ type = "POST";
+ }
+
+ // If we have elements to modify, make the request
+ if ( self.length > 0 ) {
+ jQuery.ajax({
+ url: url,
+
+ // if "type" variable is undefined, then "GET" method will be used
+ type: type,
+ dataType: "html",
+ data: params
+ }).done(function( responseText ) {
+
+ // Save response for use in complete callback
+ response = arguments;
+
+ self.html( selector ?
+
+ // If a selector was specified, locate the right elements in a dummy div
+ // Exclude scripts to avoid IE 'Permission Denied' errors
+ jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
+
+ // Otherwise use the full result
+ responseText );
+
+ }).complete( callback && function( jqXHR, status ) {
+ self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
+ });
+ }
+
+ return this;
+};
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/parseJSON.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/parseJSON.js
new file mode 100644
index 0000000..3a96d15
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/parseJSON.js
@@ -0,0 +1,13 @@
+define([
+ "../core"
+], function( jQuery ) {
+
+// Support: Android 2.3
+// Workaround failure to string-cast null input
+jQuery.parseJSON = function( data ) {
+ return JSON.parse( data + "" );
+};
+
+return jQuery.parseJSON;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/parseXML.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/parseXML.js
new file mode 100644
index 0000000..9eeb625
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/parseXML.js
@@ -0,0 +1,28 @@
+define([
+ "../core"
+], function( jQuery ) {
+
+// Cross-browser xml parsing
+jQuery.parseXML = function( data ) {
+ var xml, tmp;
+ if ( !data || typeof data !== "string" ) {
+ return null;
+ }
+
+ // Support: IE9
+ try {
+ tmp = new DOMParser();
+ xml = tmp.parseFromString( data, "text/xml" );
+ } catch ( e ) {
+ xml = undefined;
+ }
+
+ if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
+ jQuery.error( "Invalid XML: " + data );
+ }
+ return xml;
+};
+
+return jQuery.parseXML;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/script.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/script.js
new file mode 100644
index 0000000..f44329d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/script.js
@@ -0,0 +1,64 @@
+define([
+ "../core",
+ "../ajax"
+], function( jQuery ) {
+
+// Install script dataType
+jQuery.ajaxSetup({
+ accepts: {
+ script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
+ },
+ contents: {
+ script: /(?:java|ecma)script/
+ },
+ converters: {
+ "text script": function( text ) {
+ jQuery.globalEval( text );
+ return text;
+ }
+ }
+});
+
+// Handle cache's special case and crossDomain
+jQuery.ajaxPrefilter( "script", function( s ) {
+ if ( s.cache === undefined ) {
+ s.cache = false;
+ }
+ if ( s.crossDomain ) {
+ s.type = "GET";
+ }
+});
+
+// Bind script tag hack transport
+jQuery.ajaxTransport( "script", function( s ) {
+ // This transport only deals with cross domain requests
+ if ( s.crossDomain ) {
+ var script, callback;
+ return {
+ send: function( _, complete ) {
+ script = jQuery("<script>").prop({
+ async: true,
+ charset: s.scriptCharset,
+ src: s.url
+ }).on(
+ "load error",
+ callback = function( evt ) {
+ script.remove();
+ callback = null;
+ if ( evt ) {
+ complete( evt.type === "error" ? 404 : 200, evt.type );
+ }
+ }
+ );
+ document.head.appendChild( script[ 0 ] );
+ },
+ abort: function() {
+ if ( callback ) {
+ callback();
+ }
+ }
+ };
+ }
+});
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/var/nonce.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/var/nonce.js
new file mode 100644
index 0000000..0871aae
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/var/nonce.js
@@ -0,0 +1,5 @@
+define([
+ "../../core"
+], function( jQuery ) {
+ return jQuery.now();
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/var/rquery.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/var/rquery.js
new file mode 100644
index 0000000..500a77a
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/var/rquery.js
@@ -0,0 +1,3 @@
+define(function() {
+ return (/\?/);
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/xhr.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/xhr.js
new file mode 100644
index 0000000..c2b43c9
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/ajax/xhr.js
@@ -0,0 +1,136 @@
+define([
+ "../core",
+ "../var/support",
+ "../ajax"
+], function( jQuery, support ) {
+
+jQuery.ajaxSettings.xhr = function() {
+ try {
+ return new XMLHttpRequest();
+ } catch( e ) {}
+};
+
+var xhrId = 0,
+ xhrCallbacks = {},
+ xhrSuccessStatus = {
+ // file protocol always yields status code 0, assume 200
+ 0: 200,
+ // Support: IE9
+ // #1450: sometimes IE returns 1223 when it should be 204
+ 1223: 204
+ },
+ xhrSupported = jQuery.ajaxSettings.xhr();
+
+// Support: IE9
+// Open requests must be manually aborted on unload (#5280)
+// See https://support.microsoft.com/kb/2856746 for more info
+if ( window.attachEvent ) {
+ window.attachEvent( "onunload", function() {
+ for ( var key in xhrCallbacks ) {
+ xhrCallbacks[ key ]();
+ }
+ });
+}
+
+support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
+support.ajax = xhrSupported = !!xhrSupported;
+
+jQuery.ajaxTransport(function( options ) {
+ var callback;
+
+ // Cross domain only allowed if supported through XMLHttpRequest
+ if ( support.cors || xhrSupported && !options.crossDomain ) {
+ return {
+ send: function( headers, complete ) {
+ var i,
+ xhr = options.xhr(),
+ id = ++xhrId;
+
+ xhr.open( options.type, options.url, options.async, options.username, options.password );
+
+ // Apply custom fields if provided
+ if ( options.xhrFields ) {
+ for ( i in options.xhrFields ) {
+ xhr[ i ] = options.xhrFields[ i ];
+ }
+ }
+
+ // Override mime type if needed
+ if ( options.mimeType && xhr.overrideMimeType ) {
+ xhr.overrideMimeType( options.mimeType );
+ }
+
+ // X-Requested-With header
+ // For cross-domain requests, seeing as conditions for a preflight are
+ // akin to a jigsaw puzzle, we simply never set it to be sure.
+ // (it can always be set on a per-request basis or even using ajaxSetup)
+ // For same-domain requests, won't change header if already provided.
+ if ( !options.crossDomain && !headers["X-Requested-With"] ) {
+ headers["X-Requested-With"] = "XMLHttpRequest";
+ }
+
+ // Set headers
+ for ( i in headers ) {
+ xhr.setRequestHeader( i, headers[ i ] );
+ }
+
+ // Callback
+ callback = function( type ) {
+ return function() {
+ if ( callback ) {
+ delete xhrCallbacks[ id ];
+ callback = xhr.onload = xhr.onerror = null;
+
+ if ( type === "abort" ) {
+ xhr.abort();
+ } else if ( type === "error" ) {
+ complete(
+ // file: protocol always yields status 0; see #8605, #14207
+ xhr.status,
+ xhr.statusText
+ );
+ } else {
+ complete(
+ xhrSuccessStatus[ xhr.status ] || xhr.status,
+ xhr.statusText,
+ // Support: IE9
+ // Accessing binary-data responseText throws an exception
+ // (#11426)
+ typeof xhr.responseText === "string" ? {
+ text: xhr.responseText
+ } : undefined,
+ xhr.getAllResponseHeaders()
+ );
+ }
+ }
+ };
+ };
+
+ // Listen to events
+ xhr.onload = callback();
+ xhr.onerror = callback("error");
+
+ // Create the abort callback
+ callback = xhrCallbacks[ id ] = callback("abort");
+
+ try {
+ // Do send the request (this may raise an exception)
+ xhr.send( options.hasContent && options.data || null );
+ } catch ( e ) {
+ // #14683: Only rethrow if this hasn't been notified as an error yet
+ if ( callback ) {
+ throw e;
+ }
+ }
+ },
+
+ abort: function() {
+ if ( callback ) {
+ callback();
+ }
+ }
+ };
+ }
+});
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes.js
new file mode 100644
index 0000000..fa2ef1e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes.js
@@ -0,0 +1,11 @@
+define([
+ "./core",
+ "./attributes/attr",
+ "./attributes/prop",
+ "./attributes/classes",
+ "./attributes/val"
+], function( jQuery ) {
+
+// Return jQuery for attributes-only inclusion
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/attr.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/attr.js
new file mode 100644
index 0000000..a4414d1
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/attr.js
@@ -0,0 +1,141 @@
+define([
+ "../core",
+ "../var/rnotwhite",
+ "../var/strundefined",
+ "../core/access",
+ "./support",
+ "../selector"
+], function( jQuery, rnotwhite, strundefined, access, support ) {
+
+var nodeHook, boolHook,
+ attrHandle = jQuery.expr.attrHandle;
+
+jQuery.fn.extend({
+ attr: function( name, value ) {
+ return access( this, jQuery.attr, name, value, arguments.length > 1 );
+ },
+
+ removeAttr: function( name ) {
+ return this.each(function() {
+ jQuery.removeAttr( this, name );
+ });
+ }
+});
+
+jQuery.extend({
+ attr: function( elem, name, value ) {
+ var hooks, ret,
+ nType = elem.nodeType;
+
+ // don't get/set attributes on text, comment and attribute nodes
+ if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+ return;
+ }
+
+ // Fallback to prop when attributes are not supported
+ if ( typeof elem.getAttribute === strundefined ) {
+ return jQuery.prop( elem, name, value );
+ }
+
+ // All attributes are lowercase
+ // Grab necessary hook if one is defined
+ if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
+ name = name.toLowerCase();
+ hooks = jQuery.attrHooks[ name ] ||
+ ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
+ }
+
+ if ( value !== undefined ) {
+
+ if ( value === null ) {
+ jQuery.removeAttr( elem, name );
+
+ } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
+ return ret;
+
+ } else {
+ elem.setAttribute( name, value + "" );
+ return value;
+ }
+
+ } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
+ return ret;
+
+ } else {
+ ret = jQuery.find.attr( elem, name );
+
+ // Non-existent attributes return null, we normalize to undefined
+ return ret == null ?
+ undefined :
+ ret;
+ }
+ },
+
+ removeAttr: function( elem, value ) {
+ var name, propName,
+ i = 0,
+ attrNames = value && value.match( rnotwhite );
+
+ if ( attrNames && elem.nodeType === 1 ) {
+ while ( (name = attrNames[i++]) ) {
+ propName = jQuery.propFix[ name ] || name;
+
+ // Boolean attributes get special treatment (#10870)
+ if ( jQuery.expr.match.bool.test( name ) ) {
+ // Set corresponding property to false
+ elem[ propName ] = false;
+ }
+
+ elem.removeAttribute( name );
+ }
+ }
+ },
+
+ attrHooks: {
+ type: {
+ set: function( elem, value ) {
+ if ( !support.radioValue && value === "radio" &&
+ jQuery.nodeName( elem, "input" ) ) {
+ var val = elem.value;
+ elem.setAttribute( "type", value );
+ if ( val ) {
+ elem.value = val;
+ }
+ return value;
+ }
+ }
+ }
+ }
+});
+
+// Hooks for boolean attributes
+boolHook = {
+ set: function( elem, value, name ) {
+ if ( value === false ) {
+ // Remove boolean attributes when set to false
+ jQuery.removeAttr( elem, name );
+ } else {
+ elem.setAttribute( name, name );
+ }
+ return name;
+ }
+};
+jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
+ var getter = attrHandle[ name ] || jQuery.find.attr;
+
+ attrHandle[ name ] = function( elem, name, isXML ) {
+ var ret, handle;
+ if ( !isXML ) {
+ // Avoid an infinite loop by temporarily removing this function from the getter
+ handle = attrHandle[ name ];
+ attrHandle[ name ] = ret;
+ ret = getter( elem, name, isXML ) != null ?
+ name.toLowerCase() :
+ null;
+ attrHandle[ name ] = handle;
+ }
+ return ret;
+ };
+});
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/classes.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/classes.js
new file mode 100644
index 0000000..1011384
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/classes.js
@@ -0,0 +1,158 @@
+define([
+ "../core",
+ "../var/rnotwhite",
+ "../var/strundefined",
+ "../data/var/data_priv",
+ "../core/init"
+], function( jQuery, rnotwhite, strundefined, data_priv ) {
+
+var rclass = /[\t\r\n\f]/g;
+
+jQuery.fn.extend({
+ addClass: function( value ) {
+ var classes, elem, cur, clazz, j, finalValue,
+ proceed = typeof value === "string" && value,
+ i = 0,
+ len = this.length;
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( j ) {
+ jQuery( this ).addClass( value.call( this, j, this.className ) );
+ });
+ }
+
+ if ( proceed ) {
+ // The disjunction here is for better compressibility (see removeClass)
+ classes = ( value || "" ).match( rnotwhite ) || [];
+
+ for ( ; i < len; i++ ) {
+ elem = this[ i ];
+ cur = elem.nodeType === 1 && ( elem.className ?
+ ( " " + elem.className + " " ).replace( rclass, " " ) :
+ " "
+ );
+
+ if ( cur ) {
+ j = 0;
+ while ( (clazz = classes[j++]) ) {
+ if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
+ cur += clazz + " ";
+ }
+ }
+
+ // only assign if different to avoid unneeded rendering.
+ finalValue = jQuery.trim( cur );
+ if ( elem.className !== finalValue ) {
+ elem.className = finalValue;
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ removeClass: function( value ) {
+ var classes, elem, cur, clazz, j, finalValue,
+ proceed = arguments.length === 0 || typeof value === "string" && value,
+ i = 0,
+ len = this.length;
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( j ) {
+ jQuery( this ).removeClass( value.call( this, j, this.className ) );
+ });
+ }
+ if ( proceed ) {
+ classes = ( value || "" ).match( rnotwhite ) || [];
+
+ for ( ; i < len; i++ ) {
+ elem = this[ i ];
+ // This expression is here for better compressibility (see addClass)
+ cur = elem.nodeType === 1 && ( elem.className ?
+ ( " " + elem.className + " " ).replace( rclass, " " ) :
+ ""
+ );
+
+ if ( cur ) {
+ j = 0;
+ while ( (clazz = classes[j++]) ) {
+ // Remove *all* instances
+ while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
+ cur = cur.replace( " " + clazz + " ", " " );
+ }
+ }
+
+ // Only assign if different to avoid unneeded rendering.
+ finalValue = value ? jQuery.trim( cur ) : "";
+ if ( elem.className !== finalValue ) {
+ elem.className = finalValue;
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ toggleClass: function( value, stateVal ) {
+ var type = typeof value;
+
+ if ( typeof stateVal === "boolean" && type === "string" ) {
+ return stateVal ? this.addClass( value ) : this.removeClass( value );
+ }
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( i ) {
+ jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
+ });
+ }
+
+ return this.each(function() {
+ if ( type === "string" ) {
+ // Toggle individual class names
+ var className,
+ i = 0,
+ self = jQuery( this ),
+ classNames = value.match( rnotwhite ) || [];
+
+ while ( (className = classNames[ i++ ]) ) {
+ // Check each className given, space separated list
+ if ( self.hasClass( className ) ) {
+ self.removeClass( className );
+ } else {
+ self.addClass( className );
+ }
+ }
+
+ // Toggle whole class name
+ } else if ( type === strundefined || type === "boolean" ) {
+ if ( this.className ) {
+ // store className if set
+ data_priv.set( this, "__className__", this.className );
+ }
+
+ // If the element has a class name or if we're passed `false`,
+ // then remove the whole classname (if there was one, the above saved it).
+ // Otherwise bring back whatever was previously saved (if anything),
+ // falling back to the empty string if nothing was stored.
+ this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
+ }
+ });
+ },
+
+ hasClass: function( selector ) {
+ var className = " " + selector + " ",
+ i = 0,
+ l = this.length;
+ for ( ; i < l; i++ ) {
+ if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+});
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/prop.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/prop.js
new file mode 100644
index 0000000..d4ee8b6
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/prop.js
@@ -0,0 +1,94 @@
+define([
+ "../core",
+ "../core/access",
+ "./support"
+], function( jQuery, access, support ) {
+
+var rfocusable = /^(?:input|select|textarea|button)$/i;
+
+jQuery.fn.extend({
+ prop: function( name, value ) {
+ return access( this, jQuery.prop, name, value, arguments.length > 1 );
+ },
+
+ removeProp: function( name ) {
+ return this.each(function() {
+ delete this[ jQuery.propFix[ name ] || name ];
+ });
+ }
+});
+
+jQuery.extend({
+ propFix: {
+ "for": "htmlFor",
+ "class": "className"
+ },
+
+ prop: function( elem, name, value ) {
+ var ret, hooks, notxml,
+ nType = elem.nodeType;
+
+ // Don't get/set properties on text, comment and attribute nodes
+ if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+ return;
+ }
+
+ notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
+
+ if ( notxml ) {
+ // Fix name and attach hooks
+ name = jQuery.propFix[ name ] || name;
+ hooks = jQuery.propHooks[ name ];
+ }
+
+ if ( value !== undefined ) {
+ return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
+ ret :
+ ( elem[ name ] = value );
+
+ } else {
+ return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
+ ret :
+ elem[ name ];
+ }
+ },
+
+ propHooks: {
+ tabIndex: {
+ get: function( elem ) {
+ return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
+ elem.tabIndex :
+ -1;
+ }
+ }
+ }
+});
+
+if ( !support.optSelected ) {
+ jQuery.propHooks.selected = {
+ get: function( elem ) {
+ var parent = elem.parentNode;
+ if ( parent && parent.parentNode ) {
+ parent.parentNode.selectedIndex;
+ }
+ return null;
+ }
+ };
+}
+
+jQuery.each([
+ "tabIndex",
+ "readOnly",
+ "maxLength",
+ "cellSpacing",
+ "cellPadding",
+ "rowSpan",
+ "colSpan",
+ "useMap",
+ "frameBorder",
+ "contentEditable"
+], function() {
+ jQuery.propFix[ this.toLowerCase() ] = this;
+});
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/support.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/support.js
new file mode 100644
index 0000000..5db5c52
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/support.js
@@ -0,0 +1,35 @@
+define([
+ "../var/support"
+], function( support ) {
+
+(function() {
+ var input = document.createElement( "input" ),
+ select = document.createElement( "select" ),
+ opt = select.appendChild( document.createElement( "option" ) );
+
+ input.type = "checkbox";
+
+ // Support: iOS<=5.1, Android<=4.2+
+ // Default value for a checkbox should be "on"
+ support.checkOn = input.value !== "";
+
+ // Support: IE<=11+
+ // Must access selectedIndex to make default options select
+ support.optSelected = opt.selected;
+
+ // Support: Android<=2.3
+ // Options inside disabled selects are incorrectly marked as disabled
+ select.disabled = true;
+ support.optDisabled = !opt.disabled;
+
+ // Support: IE<=11+
+ // An input loses its value after becoming a radio
+ input = document.createElement( "input" );
+ input.value = "t";
+ input.type = "radio";
+ support.radioValue = input.value === "t";
+})();
+
+return support;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/val.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/val.js
new file mode 100644
index 0000000..4a1358a
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/attributes/val.js
@@ -0,0 +1,161 @@
+define([
+ "../core",
+ "./support",
+ "../core/init"
+], function( jQuery, support ) {
+
+var rreturn = /\r/g;
+
+jQuery.fn.extend({
+ val: function( value ) {
+ var hooks, ret, isFunction,
+ elem = this[0];
+
+ if ( !arguments.length ) {
+ if ( elem ) {
+ hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
+
+ if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
+ return ret;
+ }
+
+ ret = elem.value;
+
+ return typeof ret === "string" ?
+ // Handle most common string cases
+ ret.replace(rreturn, "") :
+ // Handle cases where value is null/undef or number
+ ret == null ? "" : ret;
+ }
+
+ return;
+ }
+
+ isFunction = jQuery.isFunction( value );
+
+ return this.each(function( i ) {
+ var val;
+
+ if ( this.nodeType !== 1 ) {
+ return;
+ }
+
+ if ( isFunction ) {
+ val = value.call( this, i, jQuery( this ).val() );
+ } else {
+ val = value;
+ }
+
+ // Treat null/undefined as ""; convert numbers to string
+ if ( val == null ) {
+ val = "";
+
+ } else if ( typeof val === "number" ) {
+ val += "";
+
+ } else if ( jQuery.isArray( val ) ) {
+ val = jQuery.map( val, function( value ) {
+ return value == null ? "" : value + "";
+ });
+ }
+
+ hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
+
+ // If set returns undefined, fall back to normal setting
+ if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
+ this.value = val;
+ }
+ });
+ }
+});
+
+jQuery.extend({
+ valHooks: {
+ option: {
+ get: function( elem ) {
+ var val = jQuery.find.attr( elem, "value" );
+ return val != null ?
+ val :
+ // Support: IE10-11+
+ // option.text throws exceptions (#14686, #14858)
+ jQuery.trim( jQuery.text( elem ) );
+ }
+ },
+ select: {
+ get: function( elem ) {
+ var value, option,
+ options = elem.options,
+ index = elem.selectedIndex,
+ one = elem.type === "select-one" || index < 0,
+ values = one ? null : [],
+ max = one ? index + 1 : options.length,
+ i = index < 0 ?
+ max :
+ one ? index : 0;
+
+ // Loop through all the selected options
+ for ( ; i < max; i++ ) {
+ option = options[ i ];
+
+ // IE6-9 doesn't update selected after form reset (#2551)
+ if ( ( option.selected || i === index ) &&
+ // Don't return options that are disabled or in a disabled optgroup
+ ( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) &&
+ ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
+
+ // Get the specific value for the option
+ value = jQuery( option ).val();
+
+ // We don't need an array for one selects
+ if ( one ) {
+ return value;
+ }
+
+ // Multi-Selects return an array
+ values.push( value );
+ }
+ }
+
+ return values;
+ },
+
+ set: function( elem, value ) {
+ var optionSet, option,
+ options = elem.options,
+ values = jQuery.makeArray( value ),
+ i = options.length;
+
+ while ( i-- ) {
+ option = options[ i ];
+ if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) {
+ optionSet = true;
+ }
+ }
+
+ // Force browsers to behave consistently when non-matching value is set
+ if ( !optionSet ) {
+ elem.selectedIndex = -1;
+ }
+ return values;
+ }
+ }
+ }
+});
+
+// Radios and checkboxes getter/setter
+jQuery.each([ "radio", "checkbox" ], function() {
+ jQuery.valHooks[ this ] = {
+ set: function( elem, value ) {
+ if ( jQuery.isArray( value ) ) {
+ return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
+ }
+ }
+ };
+ if ( !support.checkOn ) {
+ jQuery.valHooks[ this ].get = function( elem ) {
+ return elem.getAttribute("value") === null ? "on" : elem.value;
+ };
+ }
+});
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/callbacks.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/callbacks.js
new file mode 100644
index 0000000..17572bb
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/callbacks.js
@@ -0,0 +1,205 @@
+define([
+ "./core",
+ "./var/rnotwhite"
+], function( jQuery, rnotwhite ) {
+
+// String to Object options format cache
+var optionsCache = {};
+
+// Convert String-formatted options into Object-formatted ones and store in cache
+function createOptions( options ) {
+ var object = optionsCache[ options ] = {};
+ jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
+ object[ flag ] = true;
+ });
+ return object;
+}
+
+/*
+ * Create a callback list using the following parameters:
+ *
+ * options: an optional list of space-separated options that will change how
+ * the callback list behaves or a more traditional option object
+ *
+ * By default a callback list will act like an event callback list and can be
+ * "fired" multiple times.
+ *
+ * Possible options:
+ *
+ * once: will ensure the callback list can only be fired once (like a Deferred)
+ *
+ * memory: will keep track of previous values and will call any callback added
+ * after the list has been fired right away with the latest "memorized"
+ * values (like a Deferred)
+ *
+ * unique: will ensure a callback can only be added once (no duplicate in the list)
+ *
+ * stopOnFalse: interrupt callings when a callback returns false
+ *
+ */
+jQuery.Callbacks = function( options ) {
+
+ // Convert options from String-formatted to Object-formatted if needed
+ // (we check in cache first)
+ options = typeof options === "string" ?
+ ( optionsCache[ options ] || createOptions( options ) ) :
+ jQuery.extend( {}, options );
+
+ var // Last fire value (for non-forgettable lists)
+ memory,
+ // Flag to know if list was already fired
+ fired,
+ // Flag to know if list is currently firing
+ firing,
+ // First callback to fire (used internally by add and fireWith)
+ firingStart,
+ // End of the loop when firing
+ firingLength,
+ // Index of currently firing callback (modified by remove if needed)
+ firingIndex,
+ // Actual callback list
+ list = [],
+ // Stack of fire calls for repeatable lists
+ stack = !options.once && [],
+ // Fire callbacks
+ fire = function( data ) {
+ memory = options.memory && data;
+ fired = true;
+ firingIndex = firingStart || 0;
+ firingStart = 0;
+ firingLength = list.length;
+ firing = true;
+ for ( ; list && firingIndex < firingLength; firingIndex++ ) {
+ if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
+ memory = false; // To prevent further calls using add
+ break;
+ }
+ }
+ firing = false;
+ if ( list ) {
+ if ( stack ) {
+ if ( stack.length ) {
+ fire( stack.shift() );
+ }
+ } else if ( memory ) {
+ list = [];
+ } else {
+ self.disable();
+ }
+ }
+ },
+ // Actual Callbacks object
+ self = {
+ // Add a callback or a collection of callbacks to the list
+ add: function() {
+ if ( list ) {
+ // First, we save the current length
+ var start = list.length;
+ (function add( args ) {
+ jQuery.each( args, function( _, arg ) {
+ var type = jQuery.type( arg );
+ if ( type === "function" ) {
+ if ( !options.unique || !self.has( arg ) ) {
+ list.push( arg );
+ }
+ } else if ( arg && arg.length && type !== "string" ) {
+ // Inspect recursively
+ add( arg );
+ }
+ });
+ })( arguments );
+ // Do we need to add the callbacks to the
+ // current firing batch?
+ if ( firing ) {
+ firingLength = list.length;
+ // With memory, if we're not firing then
+ // we should call right away
+ } else if ( memory ) {
+ firingStart = start;
+ fire( memory );
+ }
+ }
+ return this;
+ },
+ // Remove a callback from the list
+ remove: function() {
+ if ( list ) {
+ jQuery.each( arguments, function( _, arg ) {
+ var index;
+ while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
+ list.splice( index, 1 );
+ // Handle firing indexes
+ if ( firing ) {
+ if ( index <= firingLength ) {
+ firingLength--;
+ }
+ if ( index <= firingIndex ) {
+ firingIndex--;
+ }
+ }
+ }
+ });
+ }
+ return this;
+ },
+ // Check if a given callback is in the list.
+ // If no argument is given, return whether or not list has callbacks attached.
+ has: function( fn ) {
+ return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
+ },
+ // Remove all callbacks from the list
+ empty: function() {
+ list = [];
+ firingLength = 0;
+ return this;
+ },
+ // Have the list do nothing anymore
+ disable: function() {
+ list = stack = memory = undefined;
+ return this;
+ },
+ // Is it disabled?
+ disabled: function() {
+ return !list;
+ },
+ // Lock the list in its current state
+ lock: function() {
+ stack = undefined;
+ if ( !memory ) {
+ self.disable();
+ }
+ return this;
+ },
+ // Is it locked?
+ locked: function() {
+ return !stack;
+ },
+ // Call all callbacks with the given context and arguments
+ fireWith: function( context, args ) {
+ if ( list && ( !fired || stack ) ) {
+ args = args || [];
+ args = [ context, args.slice ? args.slice() : args ];
+ if ( firing ) {
+ stack.push( args );
+ } else {
+ fire( args );
+ }
+ }
+ return this;
+ },
+ // Call all the callbacks with the given arguments
+ fire: function() {
+ self.fireWith( this, arguments );
+ return this;
+ },
+ // To know if the callbacks have already been called at least once
+ fired: function() {
+ return !!fired;
+ }
+ };
+
+ return self;
+};
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/core.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/core.js
new file mode 100644
index 0000000..6f471ee
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/core.js
@@ -0,0 +1,502 @@
+define([
+ "./var/arr",
+ "./var/slice",
+ "./var/concat",
+ "./var/push",
+ "./var/indexOf",
+ "./var/class2type",
+ "./var/toString",
+ "./var/hasOwn",
+ "./var/support"
+], function( arr, slice, concat, push, indexOf, class2type, toString, hasOwn, support ) {
+
+var
+ // Use the correct document accordingly with window argument (sandbox)
+ document = window.document,
+
+ version = "@VERSION",
+
+ // Define a local copy of jQuery
+ jQuery = function( selector, context ) {
+ // The jQuery object is actually just the init constructor 'enhanced'
+ // Need init if jQuery is called (just allow error to be thrown if not included)
+ return new jQuery.fn.init( selector, context );
+ },
+
+ // Support: Android<4.1
+ // Make sure we trim BOM and NBSP
+ rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
+
+ // Matches dashed string for camelizing
+ rmsPrefix = /^-ms-/,
+ rdashAlpha = /-([\da-z])/gi,
+
+ // Used by jQuery.camelCase as callback to replace()
+ fcamelCase = function( all, letter ) {
+ return letter.toUpperCase();
+ };
+
+jQuery.fn = jQuery.prototype = {
+ // The current version of jQuery being used
+ jquery: version,
+
+ constructor: jQuery,
+
+ // Start with an empty selector
+ selector: "",
+
+ // The default length of a jQuery object is 0
+ length: 0,
+
+ toArray: function() {
+ return slice.call( this );
+ },
+
+ // Get the Nth element in the matched element set OR
+ // Get the whole matched element set as a clean array
+ get: function( num ) {
+ return num != null ?
+
+ // Return just the one element from the set
+ ( num < 0 ? this[ num + this.length ] : this[ num ] ) :
+
+ // Return all the elements in a clean array
+ slice.call( this );
+ },
+
+ // Take an array of elements and push it onto the stack
+ // (returning the new matched element set)
+ pushStack: function( elems ) {
+
+ // Build a new jQuery matched element set
+ var ret = jQuery.merge( this.constructor(), elems );
+
+ // Add the old object onto the stack (as a reference)
+ ret.prevObject = this;
+ ret.context = this.context;
+
+ // Return the newly-formed element set
+ return ret;
+ },
+
+ // Execute a callback for every element in the matched set.
+ // (You can seed the arguments with an array of args, but this is
+ // only used internally.)
+ each: function( callback, args ) {
+ return jQuery.each( this, callback, args );
+ },
+
+ map: function( callback ) {
+ return this.pushStack( jQuery.map(this, function( elem, i ) {
+ return callback.call( elem, i, elem );
+ }));
+ },
+
+ slice: function() {
+ return this.pushStack( slice.apply( this, arguments ) );
+ },
+
+ first: function() {
+ return this.eq( 0 );
+ },
+
+ last: function() {
+ return this.eq( -1 );
+ },
+
+ eq: function( i ) {
+ var len = this.length,
+ j = +i + ( i < 0 ? len : 0 );
+ return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
+ },
+
+ end: function() {
+ return this.prevObject || this.constructor(null);
+ },
+
+ // For internal use only.
+ // Behaves like an Array's method, not like a jQuery method.
+ push: push,
+ sort: arr.sort,
+ splice: arr.splice
+};
+
+jQuery.extend = jQuery.fn.extend = function() {
+ var options, name, src, copy, copyIsArray, clone,
+ target = arguments[0] || {},
+ i = 1,
+ length = arguments.length,
+ deep = false;
+
+ // Handle a deep copy situation
+ if ( typeof target === "boolean" ) {
+ deep = target;
+
+ // Skip the boolean and the target
+ target = arguments[ i ] || {};
+ i++;
+ }
+
+ // Handle case when target is a string or something (possible in deep copy)
+ if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
+ target = {};
+ }
+
+ // Extend jQuery itself if only one argument is passed
+ if ( i === length ) {
+ target = this;
+ i--;
+ }
+
+ for ( ; i < length; i++ ) {
+ // Only deal with non-null/undefined values
+ if ( (options = arguments[ i ]) != null ) {
+ // Extend the base object
+ for ( name in options ) {
+ src = target[ name ];
+ copy = options[ name ];
+
+ // Prevent never-ending loop
+ if ( target === copy ) {
+ continue;
+ }
+
+ // Recurse if we're merging plain objects or arrays
+ if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
+ if ( copyIsArray ) {
+ copyIsArray = false;
+ clone = src && jQuery.isArray(src) ? src : [];
+
+ } else {
+ clone = src && jQuery.isPlainObject(src) ? src : {};
+ }
+
+ // Never move original objects, clone them
+ target[ name ] = jQuery.extend( deep, clone, copy );
+
+ // Don't bring in undefined values
+ } else if ( copy !== undefined ) {
+ target[ name ] = copy;
+ }
+ }
+ }
+ }
+
+ // Return the modified object
+ return target;
+};
+
+jQuery.extend({
+ // Unique for each copy of jQuery on the page
+ expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
+
+ // Assume jQuery is ready without the ready module
+ isReady: true,
+
+ error: function( msg ) {
+ throw new Error( msg );
+ },
+
+ noop: function() {},
+
+ isFunction: function( obj ) {
+ return jQuery.type(obj) === "function";
+ },
+
+ isArray: Array.isArray,
+
+ isWindow: function( obj ) {
+ return obj != null && obj === obj.window;
+ },
+
+ isNumeric: function( obj ) {
+ // parseFloat NaNs numeric-cast false positives (null|true|false|"")
+ // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
+ // subtraction forces infinities to NaN
+ // adding 1 corrects loss of precision from parseFloat (#15100)
+ return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
+ },
+
+ isPlainObject: function( obj ) {
+ // Not plain objects:
+ // - Any object or value whose internal [[Class]] property is not "[object Object]"
+ // - DOM nodes
+ // - window
+ if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
+ return false;
+ }
+
+ if ( obj.constructor &&
+ !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
+ return false;
+ }
+
+ // If the function hasn't returned already, we're confident that
+ // |obj| is a plain object, created by {} or constructed with new Object
+ return true;
+ },
+
+ isEmptyObject: function( obj ) {
+ var name;
+ for ( name in obj ) {
+ return false;
+ }
+ return true;
+ },
+
+ type: function( obj ) {
+ if ( obj == null ) {
+ return obj + "";
+ }
+ // Support: Android<4.0, iOS<6 (functionish RegExp)
+ return typeof obj === "object" || typeof obj === "function" ?
+ class2type[ toString.call(obj) ] || "object" :
+ typeof obj;
+ },
+
+ // Evaluates a script in a global context
+ globalEval: function( code ) {
+ var script,
+ indirect = eval;
+
+ code = jQuery.trim( code );
+
+ if ( code ) {
+ // If the code includes a valid, prologue position
+ // strict mode pragma, execute code by injecting a
+ // script tag into the document.
+ if ( code.indexOf("use strict") === 1 ) {
+ script = document.createElement("script");
+ script.text = code;
+ document.head.appendChild( script ).parentNode.removeChild( script );
+ } else {
+ // Otherwise, avoid the DOM node creation, insertion
+ // and removal by using an indirect global eval
+ indirect( code );
+ }
+ }
+ },
+
+ // Convert dashed to camelCase; used by the css and data modules
+ // Support: IE9-11+
+ // Microsoft forgot to hump their vendor prefix (#9572)
+ camelCase: function( string ) {
+ return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
+ },
+
+ nodeName: function( elem, name ) {
+ return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
+ },
+
+ // args is for internal usage only
+ each: function( obj, callback, args ) {
+ var value,
+ i = 0,
+ length = obj.length,
+ isArray = isArraylike( obj );
+
+ if ( args ) {
+ if ( isArray ) {
+ for ( ; i < length; i++ ) {
+ value = callback.apply( obj[ i ], args );
+
+ if ( value === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( i in obj ) {
+ value = callback.apply( obj[ i ], args );
+
+ if ( value === false ) {
+ break;
+ }
+ }
+ }
+
+ // A special, fast, case for the most common use of each
+ } else {
+ if ( isArray ) {
+ for ( ; i < length; i++ ) {
+ value = callback.call( obj[ i ], i, obj[ i ] );
+
+ if ( value === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( i in obj ) {
+ value = callback.call( obj[ i ], i, obj[ i ] );
+
+ if ( value === false ) {
+ break;
+ }
+ }
+ }
+ }
+
+ return obj;
+ },
+
+ // Support: Android<4.1
+ trim: function( text ) {
+ return text == null ?
+ "" :
+ ( text + "" ).replace( rtrim, "" );
+ },
+
+ // results is for internal usage only
+ makeArray: function( arr, results ) {
+ var ret = results || [];
+
+ if ( arr != null ) {
+ if ( isArraylike( Object(arr) ) ) {
+ jQuery.merge( ret,
+ typeof arr === "string" ?
+ [ arr ] : arr
+ );
+ } else {
+ push.call( ret, arr );
+ }
+ }
+
+ return ret;
+ },
+
+ inArray: function( elem, arr, i ) {
+ return arr == null ? -1 : indexOf.call( arr, elem, i );
+ },
+
+ merge: function( first, second ) {
+ var len = +second.length,
+ j = 0,
+ i = first.length;
+
+ for ( ; j < len; j++ ) {
+ first[ i++ ] = second[ j ];
+ }
+
+ first.length = i;
+
+ return first;
+ },
+
+ grep: function( elems, callback, invert ) {
+ var callbackInverse,
+ matches = [],
+ i = 0,
+ length = elems.length,
+ callbackExpect = !invert;
+
+ // Go through the array, only saving the items
+ // that pass the validator function
+ for ( ; i < length; i++ ) {
+ callbackInverse = !callback( elems[ i ], i );
+ if ( callbackInverse !== callbackExpect ) {
+ matches.push( elems[ i ] );
+ }
+ }
+
+ return matches;
+ },
+
+ // arg is for internal usage only
+ map: function( elems, callback, arg ) {
+ var value,
+ i = 0,
+ length = elems.length,
+ isArray = isArraylike( elems ),
+ ret = [];
+
+ // Go through the array, translating each of the items to their new values
+ if ( isArray ) {
+ for ( ; i < length; i++ ) {
+ value = callback( elems[ i ], i, arg );
+
+ if ( value != null ) {
+ ret.push( value );
+ }
+ }
+
+ // Go through every key on the object,
+ } else {
+ for ( i in elems ) {
+ value = callback( elems[ i ], i, arg );
+
+ if ( value != null ) {
+ ret.push( value );
+ }
+ }
+ }
+
+ // Flatten any nested arrays
+ return concat.apply( [], ret );
+ },
+
+ // A global GUID counter for objects
+ guid: 1,
+
+ // Bind a function to a context, optionally partially applying any
+ // arguments.
+ proxy: function( fn, context ) {
+ var tmp, args, proxy;
+
+ if ( typeof context === "string" ) {
+ tmp = fn[ context ];
+ context = fn;
+ fn = tmp;
+ }
+
+ // Quick check to determine if target is callable, in the spec
+ // this throws a TypeError, but we will just return undefined.
+ if ( !jQuery.isFunction( fn ) ) {
+ return undefined;
+ }
+
+ // Simulated bind
+ args = slice.call( arguments, 2 );
+ proxy = function() {
+ return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
+ };
+
+ // Set the guid of unique handler to the same of original handler, so it can be removed
+ proxy.guid = fn.guid = fn.guid || jQuery.guid++;
+
+ return proxy;
+ },
+
+ now: Date.now,
+
+ // jQuery.support is not used in Core but other projects attach their
+ // properties to it so it needs to exist.
+ support: support
+});
+
+// Populate the class2type map
+jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
+ class2type[ "[object " + name + "]" ] = name.toLowerCase();
+});
+
+function isArraylike( obj ) {
+
+ // Support: iOS 8.2 (not reproducible in simulator)
+ // `in` check used to prevent JIT error (gh-2145)
+ // hasOwn isn't used here due to false negatives
+ // regarding Nodelist length in IE
+ var length = "length" in obj && obj.length,
+ type = jQuery.type( obj );
+
+ if ( type === "function" || jQuery.isWindow( obj ) ) {
+ return false;
+ }
+
+ if ( obj.nodeType === 1 && length ) {
+ return true;
+ }
+
+ return type === "array" || length === 0 ||
+ typeof length === "number" && length > 0 && ( length - 1 ) in obj;
+}
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/access.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/access.js
new file mode 100644
index 0000000..b6110c8
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/access.js
@@ -0,0 +1,60 @@
+define([
+ "../core"
+], function( jQuery ) {
+
+// Multifunctional method to get and set values of a collection
+// The value/s can optionally be executed if it's a function
+var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
+ var i = 0,
+ len = elems.length,
+ bulk = key == null;
+
+ // Sets many values
+ if ( jQuery.type( key ) === "object" ) {
+ chainable = true;
+ for ( i in key ) {
+ jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
+ }
+
+ // Sets one value
+ } else if ( value !== undefined ) {
+ chainable = true;
+
+ if ( !jQuery.isFunction( value ) ) {
+ raw = true;
+ }
+
+ if ( bulk ) {
+ // Bulk operations run against the entire set
+ if ( raw ) {
+ fn.call( elems, value );
+ fn = null;
+
+ // ...except when executing function values
+ } else {
+ bulk = fn;
+ fn = function( elem, key, value ) {
+ return bulk.call( jQuery( elem ), value );
+ };
+ }
+ }
+
+ if ( fn ) {
+ for ( ; i < len; i++ ) {
+ fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
+ }
+ }
+ }
+
+ return chainable ?
+ elems :
+
+ // Gets
+ bulk ?
+ fn.call( elems ) :
+ len ? fn( elems[0], key ) : emptyGet;
+};
+
+return access;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/init.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/init.js
new file mode 100644
index 0000000..7e83a04
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/init.js
@@ -0,0 +1,123 @@
+// Initialize a jQuery object
+define([
+ "../core",
+ "./var/rsingleTag",
+ "../traversing/findFilter"
+], function( jQuery, rsingleTag ) {
+
+// A central reference to the root jQuery(document)
+var rootjQuery,
+
+ // A simple way to check for HTML strings
+ // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
+ // Strict HTML recognition (#11290: must start with <)
+ rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
+
+ init = jQuery.fn.init = function( selector, context ) {
+ var match, elem;
+
+ // HANDLE: $(""), $(null), $(undefined), $(false)
+ if ( !selector ) {
+ return this;
+ }
+
+ // Handle HTML strings
+ if ( typeof selector === "string" ) {
+ if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) {
+ // Assume that strings that start and end with <> are HTML and skip the regex check
+ match = [ null, selector, null ];
+
+ } else {
+ match = rquickExpr.exec( selector );
+ }
+
+ // Match html or make sure no context is specified for #id
+ if ( match && (match[1] || !context) ) {
+
+ // HANDLE: $(html) -> $(array)
+ if ( match[1] ) {
+ context = context instanceof jQuery ? context[0] : context;
+
+ // Option to run scripts is true for back-compat
+ // Intentionally let the error be thrown if parseHTML is not present
+ jQuery.merge( this, jQuery.parseHTML(
+ match[1],
+ context && context.nodeType ? context.ownerDocument || context : document,
+ true
+ ) );
+
+ // HANDLE: $(html, props)
+ if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
+ for ( match in context ) {
+ // Properties of context are called as methods if possible
+ if ( jQuery.isFunction( this[ match ] ) ) {
+ this[ match ]( context[ match ] );
+
+ // ...and otherwise set as attributes
+ } else {
+ this.attr( match, context[ match ] );
+ }
+ }
+ }
+
+ return this;
+
+ // HANDLE: $(#id)
+ } else {
+ elem = document.getElementById( match[2] );
+
+ // Support: Blackberry 4.6
+ // gEBID returns nodes no longer in the document (#6963)
+ if ( elem && elem.parentNode ) {
+ // Inject the element directly into the jQuery object
+ this.length = 1;
+ this[0] = elem;
+ }
+
+ this.context = document;
+ this.selector = selector;
+ return this;
+ }
+
+ // HANDLE: $(expr, $(...))
+ } else if ( !context || context.jquery ) {
+ return ( context || rootjQuery ).find( selector );
+
+ // HANDLE: $(expr, context)
+ // (which is just equivalent to: $(context).find(expr)
+ } else {
+ return this.constructor( context ).find( selector );
+ }
+
+ // HANDLE: $(DOMElement)
+ } else if ( selector.nodeType ) {
+ this.context = this[0] = selector;
+ this.length = 1;
+ return this;
+
+ // HANDLE: $(function)
+ // Shortcut for document ready
+ } else if ( jQuery.isFunction( selector ) ) {
+ return typeof rootjQuery.ready !== "undefined" ?
+ rootjQuery.ready( selector ) :
+ // Execute immediately if ready is not present
+ selector( jQuery );
+ }
+
+ if ( selector.selector !== undefined ) {
+ this.selector = selector.selector;
+ this.context = selector.context;
+ }
+
+ return jQuery.makeArray( selector, this );
+ };
+
+// Give the init function the jQuery prototype for later instantiation
+init.prototype = jQuery.fn;
+
+// Initialize central reference
+rootjQuery = jQuery( document );
+
+return init;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/parseHTML.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/parseHTML.js
new file mode 100644
index 0000000..64cf2a1
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/parseHTML.js
@@ -0,0 +1,39 @@
+define([
+ "../core",
+ "./var/rsingleTag",
+ "../manipulation" // buildFragment
+], function( jQuery, rsingleTag ) {
+
+// data: string of html
+// context (optional): If specified, the fragment will be created in this context, defaults to document
+// keepScripts (optional): If true, will include scripts passed in the html string
+jQuery.parseHTML = function( data, context, keepScripts ) {
+ if ( !data || typeof data !== "string" ) {
+ return null;
+ }
+ if ( typeof context === "boolean" ) {
+ keepScripts = context;
+ context = false;
+ }
+ context = context || document;
+
+ var parsed = rsingleTag.exec( data ),
+ scripts = !keepScripts && [];
+
+ // Single tag
+ if ( parsed ) {
+ return [ context.createElement( parsed[1] ) ];
+ }
+
+ parsed = jQuery.buildFragment( [ data ], context, scripts );
+
+ if ( scripts && scripts.length ) {
+ jQuery( scripts ).remove();
+ }
+
+ return jQuery.merge( [], parsed.childNodes );
+};
+
+return jQuery.parseHTML;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/ready.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/ready.js
new file mode 100644
index 0000000..db1a6e6
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/ready.js
@@ -0,0 +1,97 @@
+define([
+ "../core",
+ "../core/init",
+ "../deferred"
+], function( jQuery ) {
+
+// The deferred used on DOM ready
+var readyList;
+
+jQuery.fn.ready = function( fn ) {
+ // Add the callback
+ jQuery.ready.promise().done( fn );
+
+ return this;
+};
+
+jQuery.extend({
+ // Is the DOM ready to be used? Set to true once it occurs.
+ isReady: false,
+
+ // A counter to track how many items to wait for before
+ // the ready event fires. See #6781
+ readyWait: 1,
+
+ // Hold (or release) the ready event
+ holdReady: function( hold ) {
+ if ( hold ) {
+ jQuery.readyWait++;
+ } else {
+ jQuery.ready( true );
+ }
+ },
+
+ // Handle when the DOM is ready
+ ready: function( wait ) {
+
+ // Abort if there are pending holds or we're already ready
+ if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
+ return;
+ }
+
+ // Remember that the DOM is ready
+ jQuery.isReady = true;
+
+ // If a normal DOM Ready event fired, decrement, and wait if need be
+ if ( wait !== true && --jQuery.readyWait > 0 ) {
+ return;
+ }
+
+ // If there are functions bound, to execute
+ readyList.resolveWith( document, [ jQuery ] );
+
+ // Trigger any bound ready events
+ if ( jQuery.fn.triggerHandler ) {
+ jQuery( document ).triggerHandler( "ready" );
+ jQuery( document ).off( "ready" );
+ }
+ }
+});
+
+/**
+ * The ready event handler and self cleanup method
+ */
+function completed() {
+ document.removeEventListener( "DOMContentLoaded", completed, false );
+ window.removeEventListener( "load", completed, false );
+ jQuery.ready();
+}
+
+jQuery.ready.promise = function( obj ) {
+ if ( !readyList ) {
+
+ readyList = jQuery.Deferred();
+
+ // Catch cases where $(document).ready() is called after the browser event has already occurred.
+ // We once tried to use readyState "interactive" here, but it caused issues like the one
+ // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
+ if ( document.readyState === "complete" ) {
+ // Handle it asynchronously to allow scripts the opportunity to delay ready
+ setTimeout( jQuery.ready );
+
+ } else {
+
+ // Use the handy event callback
+ document.addEventListener( "DOMContentLoaded", completed, false );
+
+ // A fallback to window.onload, that will always work
+ window.addEventListener( "load", completed, false );
+ }
+ }
+ return readyList.promise( obj );
+};
+
+// Kick off the DOM ready check even if the user does not
+jQuery.ready.promise();
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/var/rsingleTag.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/var/rsingleTag.js
new file mode 100644
index 0000000..7e7090b
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/core/var/rsingleTag.js
@@ -0,0 +1,4 @@
+define(function() {
+ // Match a standalone tag
+ return (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/css.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css.js
new file mode 100644
index 0000000..d481617
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css.js
@@ -0,0 +1,450 @@
+define([
+ "./core",
+ "./var/pnum",
+ "./core/access",
+ "./css/var/rmargin",
+ "./css/var/rnumnonpx",
+ "./css/var/cssExpand",
+ "./css/var/isHidden",
+ "./css/var/getStyles",
+ "./css/curCSS",
+ "./css/defaultDisplay",
+ "./css/addGetHookIf",
+ "./css/support",
+ "./data/var/data_priv",
+
+ "./core/init",
+ "./css/swap",
+ "./core/ready",
+ "./selector" // contains
+], function( jQuery, pnum, access, rmargin, rnumnonpx, cssExpand, isHidden,
+ getStyles, curCSS, defaultDisplay, addGetHookIf, support, data_priv ) {
+
+var
+ // Swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
+ // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
+ rdisplayswap = /^(none|table(?!-c[ea]).+)/,
+ rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
+ rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
+
+ cssShow = { position: "absolute", visibility: "hidden", display: "block" },
+ cssNormalTransform = {
+ letterSpacing: "0",
+ fontWeight: "400"
+ },
+
+ cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
+
+// Return a css property mapped to a potentially vendor prefixed property
+function vendorPropName( style, name ) {
+
+ // Shortcut for names that are not vendor prefixed
+ if ( name in style ) {
+ return name;
+ }
+
+ // Check for vendor prefixed names
+ var capName = name[0].toUpperCase() + name.slice(1),
+ origName = name,
+ i = cssPrefixes.length;
+
+ while ( i-- ) {
+ name = cssPrefixes[ i ] + capName;
+ if ( name in style ) {
+ return name;
+ }
+ }
+
+ return origName;
+}
+
+function setPositiveNumber( elem, value, subtract ) {
+ var matches = rnumsplit.exec( value );
+ return matches ?
+ // Guard against undefined "subtract", e.g., when used as in cssHooks
+ Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
+ value;
+}
+
+function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
+ var i = extra === ( isBorderBox ? "border" : "content" ) ?
+ // If we already have the right measurement, avoid augmentation
+ 4 :
+ // Otherwise initialize for horizontal or vertical properties
+ name === "width" ? 1 : 0,
+
+ val = 0;
+
+ for ( ; i < 4; i += 2 ) {
+ // Both box models exclude margin, so add it if we want it
+ if ( extra === "margin" ) {
+ val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
+ }
+
+ if ( isBorderBox ) {
+ // border-box includes padding, so remove it if we want content
+ if ( extra === "content" ) {
+ val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
+ }
+
+ // At this point, extra isn't border nor margin, so remove border
+ if ( extra !== "margin" ) {
+ val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
+ }
+ } else {
+ // At this point, extra isn't content, so add padding
+ val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
+
+ // At this point, extra isn't content nor padding, so add border
+ if ( extra !== "padding" ) {
+ val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
+ }
+ }
+ }
+
+ return val;
+}
+
+function getWidthOrHeight( elem, name, extra ) {
+
+ // Start with offset property, which is equivalent to the border-box value
+ var valueIsBorderBox = true,
+ val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
+ styles = getStyles( elem ),
+ isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
+
+ // Some non-html elements return undefined for offsetWidth, so check for null/undefined
+ // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
+ // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
+ if ( val <= 0 || val == null ) {
+ // Fall back to computed then uncomputed css if necessary
+ val = curCSS( elem, name, styles );
+ if ( val < 0 || val == null ) {
+ val = elem.style[ name ];
+ }
+
+ // Computed unit is not pixels. Stop here and return.
+ if ( rnumnonpx.test(val) ) {
+ return val;
+ }
+
+ // Check for style in case a browser which returns unreliable values
+ // for getComputedStyle silently falls back to the reliable elem.style
+ valueIsBorderBox = isBorderBox &&
+ ( support.boxSizingReliable() || val === elem.style[ name ] );
+
+ // Normalize "", auto, and prepare for extra
+ val = parseFloat( val ) || 0;
+ }
+
+ // Use the active box-sizing model to add/subtract irrelevant styles
+ return ( val +
+ augmentWidthOrHeight(
+ elem,
+ name,
+ extra || ( isBorderBox ? "border" : "content" ),
+ valueIsBorderBox,
+ styles
+ )
+ ) + "px";
+}
+
+function showHide( elements, show ) {
+ var display, elem, hidden,
+ values = [],
+ index = 0,
+ length = elements.length;
+
+ for ( ; index < length; index++ ) {
+ elem = elements[ index ];
+ if ( !elem.style ) {
+ continue;
+ }
+
+ values[ index ] = data_priv.get( elem, "olddisplay" );
+ display = elem.style.display;
+ if ( show ) {
+ // Reset the inline display of this element to learn if it is
+ // being hidden by cascaded rules or not
+ if ( !values[ index ] && display === "none" ) {
+ elem.style.display = "";
+ }
+
+ // Set elements which have been overridden with display: none
+ // in a stylesheet to whatever the default browser style is
+ // for such an element
+ if ( elem.style.display === "" && isHidden( elem ) ) {
+ values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) );
+ }
+ } else {
+ hidden = isHidden( elem );
+
+ if ( display !== "none" || !hidden ) {
+ data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
+ }
+ }
+ }
+
+ // Set the display of most of the elements in a second loop
+ // to avoid the constant reflow
+ for ( index = 0; index < length; index++ ) {
+ elem = elements[ index ];
+ if ( !elem.style ) {
+ continue;
+ }
+ if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
+ elem.style.display = show ? values[ index ] || "" : "none";
+ }
+ }
+
+ return elements;
+}
+
+jQuery.extend({
+
+ // Add in style property hooks for overriding the default
+ // behavior of getting and setting a style property
+ cssHooks: {
+ opacity: {
+ get: function( elem, computed ) {
+ if ( computed ) {
+
+ // We should always get a number back from opacity
+ var ret = curCSS( elem, "opacity" );
+ return ret === "" ? "1" : ret;
+ }
+ }
+ }
+ },
+
+ // Don't automatically add "px" to these possibly-unitless properties
+ cssNumber: {
+ "columnCount": true,
+ "fillOpacity": true,
+ "flexGrow": true,
+ "flexShrink": true,
+ "fontWeight": true,
+ "lineHeight": true,
+ "opacity": true,
+ "order": true,
+ "orphans": true,
+ "widows": true,
+ "zIndex": true,
+ "zoom": true
+ },
+
+ // Add in properties whose names you wish to fix before
+ // setting or getting the value
+ cssProps: {
+ "float": "cssFloat"
+ },
+
+ // Get and set the style property on a DOM Node
+ style: function( elem, name, value, extra ) {
+
+ // Don't set styles on text and comment nodes
+ if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
+ return;
+ }
+
+ // Make sure that we're working with the right name
+ var ret, type, hooks,
+ origName = jQuery.camelCase( name ),
+ style = elem.style;
+
+ name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
+
+ // Gets hook for the prefixed version, then unprefixed version
+ hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
+
+ // Check if we're setting a value
+ if ( value !== undefined ) {
+ type = typeof value;
+
+ // Convert "+=" or "-=" to relative numbers (#7345)
+ if ( type === "string" && (ret = rrelNum.exec( value )) ) {
+ value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
+ // Fixes bug #9237
+ type = "number";
+ }
+
+ // Make sure that null and NaN values aren't set (#7116)
+ if ( value == null || value !== value ) {
+ return;
+ }
+
+ // If a number, add 'px' to the (except for certain CSS properties)
+ if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
+ value += "px";
+ }
+
+ // Support: IE9-11+
+ // background-* props affect original clone's values
+ if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
+ style[ name ] = "inherit";
+ }
+
+ // If a hook was provided, use that value, otherwise just set the specified value
+ if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
+ style[ name ] = value;
+ }
+
+ } else {
+ // If a hook was provided get the non-computed value from there
+ if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
+ return ret;
+ }
+
+ // Otherwise just get the value from the style object
+ return style[ name ];
+ }
+ },
+
+ css: function( elem, name, extra, styles ) {
+ var val, num, hooks,
+ origName = jQuery.camelCase( name );
+
+ // Make sure that we're working with the right name
+ name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
+
+ // Try prefixed name followed by the unprefixed name
+ hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
+
+ // If a hook was provided get the computed value from there
+ if ( hooks && "get" in hooks ) {
+ val = hooks.get( elem, true, extra );
+ }
+
+ // Otherwise, if a way to get the computed value exists, use that
+ if ( val === undefined ) {
+ val = curCSS( elem, name, styles );
+ }
+
+ // Convert "normal" to computed value
+ if ( val === "normal" && name in cssNormalTransform ) {
+ val = cssNormalTransform[ name ];
+ }
+
+ // Make numeric if forced or a qualifier was provided and val looks numeric
+ if ( extra === "" || extra ) {
+ num = parseFloat( val );
+ return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
+ }
+ return val;
+ }
+});
+
+jQuery.each([ "height", "width" ], function( i, name ) {
+ jQuery.cssHooks[ name ] = {
+ get: function( elem, computed, extra ) {
+ if ( computed ) {
+
+ // Certain elements can have dimension info if we invisibly show them
+ // but it must have a current display style that would benefit
+ return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
+ jQuery.swap( elem, cssShow, function() {
+ return getWidthOrHeight( elem, name, extra );
+ }) :
+ getWidthOrHeight( elem, name, extra );
+ }
+ },
+
+ set: function( elem, value, extra ) {
+ var styles = extra && getStyles( elem );
+ return setPositiveNumber( elem, value, extra ?
+ augmentWidthOrHeight(
+ elem,
+ name,
+ extra,
+ jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
+ styles
+ ) : 0
+ );
+ }
+ };
+});
+
+// Support: Android 2.3
+jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
+ function( elem, computed ) {
+ if ( computed ) {
+ return jQuery.swap( elem, { "display": "inline-block" },
+ curCSS, [ elem, "marginRight" ] );
+ }
+ }
+);
+
+// These hooks are used by animate to expand properties
+jQuery.each({
+ margin: "",
+ padding: "",
+ border: "Width"
+}, function( prefix, suffix ) {
+ jQuery.cssHooks[ prefix + suffix ] = {
+ expand: function( value ) {
+ var i = 0,
+ expanded = {},
+
+ // Assumes a single number if not a string
+ parts = typeof value === "string" ? value.split(" ") : [ value ];
+
+ for ( ; i < 4; i++ ) {
+ expanded[ prefix + cssExpand[ i ] + suffix ] =
+ parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
+ }
+
+ return expanded;
+ }
+ };
+
+ if ( !rmargin.test( prefix ) ) {
+ jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
+ }
+});
+
+jQuery.fn.extend({
+ css: function( name, value ) {
+ return access( this, function( elem, name, value ) {
+ var styles, len,
+ map = {},
+ i = 0;
+
+ if ( jQuery.isArray( name ) ) {
+ styles = getStyles( elem );
+ len = name.length;
+
+ for ( ; i < len; i++ ) {
+ map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
+ }
+
+ return map;
+ }
+
+ return value !== undefined ?
+ jQuery.style( elem, name, value ) :
+ jQuery.css( elem, name );
+ }, name, value, arguments.length > 1 );
+ },
+ show: function() {
+ return showHide( this, true );
+ },
+ hide: function() {
+ return showHide( this );
+ },
+ toggle: function( state ) {
+ if ( typeof state === "boolean" ) {
+ return state ? this.show() : this.hide();
+ }
+
+ return this.each(function() {
+ if ( isHidden( this ) ) {
+ jQuery( this ).show();
+ } else {
+ jQuery( this ).hide();
+ }
+ });
+ }
+});
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/addGetHookIf.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/addGetHookIf.js
new file mode 100644
index 0000000..e12f359
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/addGetHookIf.js
@@ -0,0 +1,22 @@
+define(function() {
+
+function addGetHookIf( conditionFn, hookFn ) {
+ // Define the hook, we'll check on the first run if it's really needed.
+ return {
+ get: function() {
+ if ( conditionFn() ) {
+ // Hook not needed (or it's not possible to use it due
+ // to missing dependency), remove it.
+ delete this.get;
+ return;
+ }
+
+ // Hook needed; redefine it so that the support test is not executed again.
+ return (this.get = hookFn).apply( this, arguments );
+ }
+ };
+}
+
+return addGetHookIf;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/curCSS.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/curCSS.js
new file mode 100644
index 0000000..90e508c
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/curCSS.js
@@ -0,0 +1,57 @@
+define([
+ "../core",
+ "./var/rnumnonpx",
+ "./var/rmargin",
+ "./var/getStyles",
+ "../selector" // contains
+], function( jQuery, rnumnonpx, rmargin, getStyles ) {
+
+function curCSS( elem, name, computed ) {
+ var width, minWidth, maxWidth, ret,
+ style = elem.style;
+
+ computed = computed || getStyles( elem );
+
+ // Support: IE9
+ // getPropertyValue is only needed for .css('filter') (#12537)
+ if ( computed ) {
+ ret = computed.getPropertyValue( name ) || computed[ name ];
+ }
+
+ if ( computed ) {
+
+ if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
+ ret = jQuery.style( elem, name );
+ }
+
+ // Support: iOS < 6
+ // A tribute to the "awesome hack by Dean Edwards"
+ // iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
+ // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
+ if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
+
+ // Remember the original values
+ width = style.width;
+ minWidth = style.minWidth;
+ maxWidth = style.maxWidth;
+
+ // Put in the new values to get a computed value out
+ style.minWidth = style.maxWidth = style.width = ret;
+ ret = computed.width;
+
+ // Revert the changed values
+ style.width = width;
+ style.minWidth = minWidth;
+ style.maxWidth = maxWidth;
+ }
+ }
+
+ return ret !== undefined ?
+ // Support: IE
+ // IE returns zIndex value as an integer.
+ ret + "" :
+ ret;
+}
+
+return curCSS;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/defaultDisplay.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/defaultDisplay.js
new file mode 100644
index 0000000..046ae91
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/defaultDisplay.js
@@ -0,0 +1,70 @@
+define([
+ "../core",
+ "../manipulation" // appendTo
+], function( jQuery ) {
+
+var iframe,
+ elemdisplay = {};
+
+/**
+ * Retrieve the actual display of a element
+ * @param {String} name nodeName of the element
+ * @param {Object} doc Document object
+ */
+// Called only from within defaultDisplay
+function actualDisplay( name, doc ) {
+ var style,
+ elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
+
+ // getDefaultComputedStyle might be reliably used only on attached element
+ display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
+
+ // Use of this method is a temporary fix (more like optimization) until something better comes along,
+ // since it was removed from specification and supported only in FF
+ style.display : jQuery.css( elem[ 0 ], "display" );
+
+ // We don't have any data stored on the element,
+ // so use "detach" method as fast way to get rid of the element
+ elem.detach();
+
+ return display;
+}
+
+/**
+ * Try to determine the default display value of an element
+ * @param {String} nodeName
+ */
+function defaultDisplay( nodeName ) {
+ var doc = document,
+ display = elemdisplay[ nodeName ];
+
+ if ( !display ) {
+ display = actualDisplay( nodeName, doc );
+
+ // If the simple way fails, read from inside an iframe
+ if ( display === "none" || !display ) {
+
+ // Use the already-created iframe if possible
+ iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
+
+ // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
+ doc = iframe[ 0 ].contentDocument;
+
+ // Support: IE
+ doc.write();
+ doc.close();
+
+ display = actualDisplay( nodeName, doc );
+ iframe.detach();
+ }
+
+ // Store the correct default display
+ elemdisplay[ nodeName ] = display;
+ }
+
+ return display;
+}
+
+return defaultDisplay;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/hiddenVisibleSelectors.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/hiddenVisibleSelectors.js
new file mode 100644
index 0000000..c7f1c7e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/hiddenVisibleSelectors.js
@@ -0,0 +1,15 @@
+define([
+ "../core",
+ "../selector"
+], function( jQuery ) {
+
+jQuery.expr.filters.hidden = function( elem ) {
+ // Support: Opera <= 12.12
+ // Opera reports offsetWidths and offsetHeights less than zero on some elements
+ return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
+};
+jQuery.expr.filters.visible = function( elem ) {
+ return !jQuery.expr.filters.hidden( elem );
+};
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/support.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/support.js
new file mode 100644
index 0000000..b9eaf14
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/support.js
@@ -0,0 +1,96 @@
+define([
+ "../core",
+ "../var/support"
+], function( jQuery, support ) {
+
+(function() {
+ var pixelPositionVal, boxSizingReliableVal,
+ docElem = document.documentElement,
+ container = document.createElement( "div" ),
+ div = document.createElement( "div" );
+
+ if ( !div.style ) {
+ return;
+ }
+
+ // Support: IE9-11+
+ // Style of cloned element affects source element cloned (#8908)
+ div.style.backgroundClip = "content-box";
+ div.cloneNode( true ).style.backgroundClip = "";
+ support.clearCloneStyle = div.style.backgroundClip === "content-box";
+
+ container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" +
+ "position:absolute";
+ container.appendChild( div );
+
+ // Executing both pixelPosition & boxSizingReliable tests require only one layout
+ // so they're executed at the same time to save the second computation.
+ function computePixelPositionAndBoxSizingReliable() {
+ div.style.cssText =
+ // Support: Firefox<29, Android 2.3
+ // Vendor-prefix box-sizing
+ "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
+ "box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
+ "border:1px;padding:1px;width:4px;position:absolute";
+ div.innerHTML = "";
+ docElem.appendChild( container );
+
+ var divStyle = window.getComputedStyle( div, null );
+ pixelPositionVal = divStyle.top !== "1%";
+ boxSizingReliableVal = divStyle.width === "4px";
+
+ docElem.removeChild( container );
+ }
+
+ // Support: node.js jsdom
+ // Don't assume that getComputedStyle is a property of the global object
+ if ( window.getComputedStyle ) {
+ jQuery.extend( support, {
+ pixelPosition: function() {
+
+ // This test is executed only once but we still do memoizing
+ // since we can use the boxSizingReliable pre-computing.
+ // No need to check if the test was already performed, though.
+ computePixelPositionAndBoxSizingReliable();
+ return pixelPositionVal;
+ },
+ boxSizingReliable: function() {
+ if ( boxSizingReliableVal == null ) {
+ computePixelPositionAndBoxSizingReliable();
+ }
+ return boxSizingReliableVal;
+ },
+ reliableMarginRight: function() {
+
+ // Support: Android 2.3
+ // Check if div with explicit width and no margin-right incorrectly
+ // gets computed margin-right based on width of container. (#3333)
+ // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+ // This support function is only executed once so no memoizing is needed.
+ var ret,
+ marginDiv = div.appendChild( document.createElement( "div" ) );
+
+ // Reset CSS: box-sizing; display; margin; border; padding
+ marginDiv.style.cssText = div.style.cssText =
+ // Support: Firefox<29, Android 2.3
+ // Vendor-prefix box-sizing
+ "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
+ "box-sizing:content-box;display:block;margin:0;border:0;padding:0";
+ marginDiv.style.marginRight = marginDiv.style.width = "0";
+ div.style.width = "1px";
+ docElem.appendChild( container );
+
+ ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );
+
+ docElem.removeChild( container );
+ div.removeChild( marginDiv );
+
+ return ret;
+ }
+ });
+ }
+})();
+
+return support;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/swap.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/swap.js
new file mode 100644
index 0000000..ce16435
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/swap.js
@@ -0,0 +1,28 @@
+define([
+ "../core"
+], function( jQuery ) {
+
+// A method for quickly swapping in/out CSS properties to get correct calculations.
+jQuery.swap = function( elem, options, callback, args ) {
+ var ret, name,
+ old = {};
+
+ // Remember the old values, and insert the new ones
+ for ( name in options ) {
+ old[ name ] = elem.style[ name ];
+ elem.style[ name ] = options[ name ];
+ }
+
+ ret = callback.apply( elem, args || [] );
+
+ // Revert the old values
+ for ( name in options ) {
+ elem.style[ name ] = old[ name ];
+ }
+
+ return ret;
+};
+
+return jQuery.swap;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/cssExpand.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/cssExpand.js
new file mode 100644
index 0000000..91e90a8
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/cssExpand.js
@@ -0,0 +1,3 @@
+define(function() {
+ return [ "Top", "Right", "Bottom", "Left" ];
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/getStyles.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/getStyles.js
new file mode 100644
index 0000000..413acd0
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/getStyles.js
@@ -0,0 +1,12 @@
+define(function() {
+ return function( elem ) {
+ // Support: IE<=11+, Firefox<=30+ (#15098, #14150)
+ // IE throws on elements created in popups
+ // FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
+ if ( elem.ownerDocument.defaultView.opener ) {
+ return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
+ }
+
+ return window.getComputedStyle( elem, null );
+ };
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/isHidden.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/isHidden.js
new file mode 100644
index 0000000..15ab81a
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/isHidden.js
@@ -0,0 +1,13 @@
+define([
+ "../../core",
+ "../../selector"
+ // css is assumed
+], function( jQuery ) {
+
+ return function( elem, el ) {
+ // isHidden might be called from jQuery#filter function;
+ // in that case, element will be second argument
+ elem = el || elem;
+ return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
+ };
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/rmargin.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/rmargin.js
new file mode 100644
index 0000000..da0438d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/rmargin.js
@@ -0,0 +1,3 @@
+define(function() {
+ return (/^margin/);
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/rnumnonpx.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/rnumnonpx.js
new file mode 100644
index 0000000..c93be28
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/css/var/rnumnonpx.js
@@ -0,0 +1,5 @@
+define([
+ "../../var/pnum"
+], function( pnum ) {
+ return new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/data.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/data.js
new file mode 100644
index 0000000..f9af9ae
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/data.js
@@ -0,0 +1,178 @@
+define([
+ "./core",
+ "./var/rnotwhite",
+ "./core/access",
+ "./data/var/data_priv",
+ "./data/var/data_user"
+], function( jQuery, rnotwhite, access, data_priv, data_user ) {
+
+// Implementation Summary
+//
+// 1. Enforce API surface and semantic compatibility with 1.9.x branch
+// 2. Improve the module's maintainability by reducing the storage
+// paths to a single mechanism.
+// 3. Use the same single mechanism to support "private" and "user" data.
+// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
+// 5. Avoid exposing implementation details on user objects (eg. expando properties)
+// 6. Provide a clear path for implementation upgrade to WeakMap in 2014
+
+var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
+ rmultiDash = /([A-Z])/g;
+
+function dataAttr( elem, key, data ) {
+ var name;
+
+ // If nothing was found internally, try to fetch any
+ // data from the HTML5 data-* attribute
+ if ( data === undefined && elem.nodeType === 1 ) {
+ name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
+ data = elem.getAttribute( name );
+
+ if ( typeof data === "string" ) {
+ try {
+ data = data === "true" ? true :
+ data === "false" ? false :
+ data === "null" ? null :
+ // Only convert to a number if it doesn't change the string
+ +data + "" === data ? +data :
+ rbrace.test( data ) ? jQuery.parseJSON( data ) :
+ data;
+ } catch( e ) {}
+
+ // Make sure we set the data so it isn't changed later
+ data_user.set( elem, key, data );
+ } else {
+ data = undefined;
+ }
+ }
+ return data;
+}
+
+jQuery.extend({
+ hasData: function( elem ) {
+ return data_user.hasData( elem ) || data_priv.hasData( elem );
+ },
+
+ data: function( elem, name, data ) {
+ return data_user.access( elem, name, data );
+ },
+
+ removeData: function( elem, name ) {
+ data_user.remove( elem, name );
+ },
+
+ // TODO: Now that all calls to _data and _removeData have been replaced
+ // with direct calls to data_priv methods, these can be deprecated.
+ _data: function( elem, name, data ) {
+ return data_priv.access( elem, name, data );
+ },
+
+ _removeData: function( elem, name ) {
+ data_priv.remove( elem, name );
+ }
+});
+
+jQuery.fn.extend({
+ data: function( key, value ) {
+ var i, name, data,
+ elem = this[ 0 ],
+ attrs = elem && elem.attributes;
+
+ // Gets all values
+ if ( key === undefined ) {
+ if ( this.length ) {
+ data = data_user.get( elem );
+
+ if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
+ i = attrs.length;
+ while ( i-- ) {
+
+ // Support: IE11+
+ // The attrs elements can be null (#14894)
+ if ( attrs[ i ] ) {
+ name = attrs[ i ].name;
+ if ( name.indexOf( "data-" ) === 0 ) {
+ name = jQuery.camelCase( name.slice(5) );
+ dataAttr( elem, name, data[ name ] );
+ }
+ }
+ }
+ data_priv.set( elem, "hasDataAttrs", true );
+ }
+ }
+
+ return data;
+ }
+
+ // Sets multiple values
+ if ( typeof key === "object" ) {
+ return this.each(function() {
+ data_user.set( this, key );
+ });
+ }
+
+ return access( this, function( value ) {
+ var data,
+ camelKey = jQuery.camelCase( key );
+
+ // The calling jQuery object (element matches) is not empty
+ // (and therefore has an element appears at this[ 0 ]) and the
+ // `value` parameter was not undefined. An empty jQuery object
+ // will result in `undefined` for elem = this[ 0 ] which will
+ // throw an exception if an attempt to read a data cache is made.
+ if ( elem && value === undefined ) {
+ // Attempt to get data from the cache
+ // with the key as-is
+ data = data_user.get( elem, key );
+ if ( data !== undefined ) {
+ return data;
+ }
+
+ // Attempt to get data from the cache
+ // with the key camelized
+ data = data_user.get( elem, camelKey );
+ if ( data !== undefined ) {
+ return data;
+ }
+
+ // Attempt to "discover" the data in
+ // HTML5 custom data-* attrs
+ data = dataAttr( elem, camelKey, undefined );
+ if ( data !== undefined ) {
+ return data;
+ }
+
+ // We tried really hard, but the data doesn't exist.
+ return;
+ }
+
+ // Set the data...
+ this.each(function() {
+ // First, attempt to store a copy or reference of any
+ // data that might've been store with a camelCased key.
+ var data = data_user.get( this, camelKey );
+
+ // For HTML5 data-* attribute interop, we have to
+ // store property names with dashes in a camelCase form.
+ // This might not apply to all properties...*
+ data_user.set( this, camelKey, value );
+
+ // *... In the case of properties that might _actually_
+ // have dashes, we need to also store a copy of that
+ // unchanged property.
+ if ( key.indexOf("-") !== -1 && data !== undefined ) {
+ data_user.set( this, key, value );
+ }
+ });
+ }, null, value, arguments.length > 1, null, true );
+ },
+
+ removeData: function( key ) {
+ return this.each(function() {
+ data_user.remove( this, key );
+ });
+ }
+});
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/data/Data.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/data/Data.js
new file mode 100644
index 0000000..85afd64
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/data/Data.js
@@ -0,0 +1,181 @@
+define([
+ "../core",
+ "../var/rnotwhite",
+ "./accepts"
+], function( jQuery, rnotwhite ) {
+
+function Data() {
+ // Support: Android<4,
+ // Old WebKit does not have Object.preventExtensions/freeze method,
+ // return new empty object instead with no [[set]] accessor
+ Object.defineProperty( this.cache = {}, 0, {
+ get: function() {
+ return {};
+ }
+ });
+
+ this.expando = jQuery.expando + Data.uid++;
+}
+
+Data.uid = 1;
+Data.accepts = jQuery.acceptData;
+
+Data.prototype = {
+ key: function( owner ) {
+ // We can accept data for non-element nodes in modern browsers,
+ // but we should not, see #8335.
+ // Always return the key for a frozen object.
+ if ( !Data.accepts( owner ) ) {
+ return 0;
+ }
+
+ var descriptor = {},
+ // Check if the owner object already has a cache key
+ unlock = owner[ this.expando ];
+
+ // If not, create one
+ if ( !unlock ) {
+ unlock = Data.uid++;
+
+ // Secure it in a non-enumerable, non-writable property
+ try {
+ descriptor[ this.expando ] = { value: unlock };
+ Object.defineProperties( owner, descriptor );
+
+ // Support: Android<4
+ // Fallback to a less secure definition
+ } catch ( e ) {
+ descriptor[ this.expando ] = unlock;
+ jQuery.extend( owner, descriptor );
+ }
+ }
+
+ // Ensure the cache object
+ if ( !this.cache[ unlock ] ) {
+ this.cache[ unlock ] = {};
+ }
+
+ return unlock;
+ },
+ set: function( owner, data, value ) {
+ var prop,
+ // There may be an unlock assigned to this node,
+ // if there is no entry for this "owner", create one inline
+ // and set the unlock as though an owner entry had always existed
+ unlock = this.key( owner ),
+ cache = this.cache[ unlock ];
+
+ // Handle: [ owner, key, value ] args
+ if ( typeof data === "string" ) {
+ cache[ data ] = value;
+
+ // Handle: [ owner, { properties } ] args
+ } else {
+ // Fresh assignments by object are shallow copied
+ if ( jQuery.isEmptyObject( cache ) ) {
+ jQuery.extend( this.cache[ unlock ], data );
+ // Otherwise, copy the properties one-by-one to the cache object
+ } else {
+ for ( prop in data ) {
+ cache[ prop ] = data[ prop ];
+ }
+ }
+ }
+ return cache;
+ },
+ get: function( owner, key ) {
+ // Either a valid cache is found, or will be created.
+ // New caches will be created and the unlock returned,
+ // allowing direct access to the newly created
+ // empty data object. A valid owner object must be provided.
+ var cache = this.cache[ this.key( owner ) ];
+
+ return key === undefined ?
+ cache : cache[ key ];
+ },
+ access: function( owner, key, value ) {
+ var stored;
+ // In cases where either:
+ //
+ // 1. No key was specified
+ // 2. A string key was specified, but no value provided
+ //
+ // Take the "read" path and allow the get method to determine
+ // which value to return, respectively either:
+ //
+ // 1. The entire cache object
+ // 2. The data stored at the key
+ //
+ if ( key === undefined ||
+ ((key && typeof key === "string") && value === undefined) ) {
+
+ stored = this.get( owner, key );
+
+ return stored !== undefined ?
+ stored : this.get( owner, jQuery.camelCase(key) );
+ }
+
+ // [*]When the key is not a string, or both a key and value
+ // are specified, set or extend (existing objects) with either:
+ //
+ // 1. An object of properties
+ // 2. A key and value
+ //
+ this.set( owner, key, value );
+
+ // Since the "set" path can have two possible entry points
+ // return the expected data based on which path was taken[*]
+ return value !== undefined ? value : key;
+ },
+ remove: function( owner, key ) {
+ var i, name, camel,
+ unlock = this.key( owner ),
+ cache = this.cache[ unlock ];
+
+ if ( key === undefined ) {
+ this.cache[ unlock ] = {};
+
+ } else {
+ // Support array or space separated string of keys
+ if ( jQuery.isArray( key ) ) {
+ // If "name" is an array of keys...
+ // When data is initially created, via ("key", "val") signature,
+ // keys will be converted to camelCase.
+ // Since there is no way to tell _how_ a key was added, remove
+ // both plain key and camelCase key. #12786
+ // This will only penalize the array argument path.
+ name = key.concat( key.map( jQuery.camelCase ) );
+ } else {
+ camel = jQuery.camelCase( key );
+ // Try the string as a key before any manipulation
+ if ( key in cache ) {
+ name = [ key, camel ];
+ } else {
+ // If a key with the spaces exists, use it.
+ // Otherwise, create an array by matching non-whitespace
+ name = camel;
+ name = name in cache ?
+ [ name ] : ( name.match( rnotwhite ) || [] );
+ }
+ }
+
+ i = name.length;
+ while ( i-- ) {
+ delete cache[ name[ i ] ];
+ }
+ }
+ },
+ hasData: function( owner ) {
+ return !jQuery.isEmptyObject(
+ this.cache[ owner[ this.expando ] ] || {}
+ );
+ },
+ discard: function( owner ) {
+ if ( owner[ this.expando ] ) {
+ delete this.cache[ owner[ this.expando ] ];
+ }
+ }
+};
+
+return Data;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/data/accepts.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/data/accepts.js
new file mode 100644
index 0000000..291c7b4
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/data/accepts.js
@@ -0,0 +1,20 @@
+define([
+ "../core"
+], function( jQuery ) {
+
+/**
+ * Determines whether an object can have data
+ */
+jQuery.acceptData = function( owner ) {
+ // Accepts only:
+ // - Node
+ // - Node.ELEMENT_NODE
+ // - Node.DOCUMENT_NODE
+ // - Object
+ // - Any
+ /* jshint -W018 */
+ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
+};
+
+return jQuery.acceptData;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/data/var/data_priv.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/data/var/data_priv.js
new file mode 100644
index 0000000..24399e4
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/data/var/data_priv.js
@@ -0,0 +1,5 @@
+define([
+ "../Data"
+], function( Data ) {
+ return new Data();
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/data/var/data_user.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/data/var/data_user.js
new file mode 100644
index 0000000..24399e4
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/data/var/data_user.js
@@ -0,0 +1,5 @@
+define([
+ "../Data"
+], function( Data ) {
+ return new Data();
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/deferred.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/deferred.js
new file mode 100644
index 0000000..98f9c31
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/deferred.js
@@ -0,0 +1,149 @@
+define([
+ "./core",
+ "./var/slice",
+ "./callbacks"
+], function( jQuery, slice ) {
+
+jQuery.extend({
+
+ Deferred: function( func ) {
+ var tuples = [
+ // action, add listener, listener list, final state
+ [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
+ [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
+ [ "notify", "progress", jQuery.Callbacks("memory") ]
+ ],
+ state = "pending",
+ promise = {
+ state: function() {
+ return state;
+ },
+ always: function() {
+ deferred.done( arguments ).fail( arguments );
+ return this;
+ },
+ then: function( /* fnDone, fnFail, fnProgress */ ) {
+ var fns = arguments;
+ return jQuery.Deferred(function( newDefer ) {
+ jQuery.each( tuples, function( i, tuple ) {
+ var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
+ // deferred[ done | fail | progress ] for forwarding actions to newDefer
+ deferred[ tuple[1] ](function() {
+ var returned = fn && fn.apply( this, arguments );
+ if ( returned && jQuery.isFunction( returned.promise ) ) {
+ returned.promise()
+ .done( newDefer.resolve )
+ .fail( newDefer.reject )
+ .progress( newDefer.notify );
+ } else {
+ newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
+ }
+ });
+ });
+ fns = null;
+ }).promise();
+ },
+ // Get a promise for this deferred
+ // If obj is provided, the promise aspect is added to the object
+ promise: function( obj ) {
+ return obj != null ? jQuery.extend( obj, promise ) : promise;
+ }
+ },
+ deferred = {};
+
+ // Keep pipe for back-compat
+ promise.pipe = promise.then;
+
+ // Add list-specific methods
+ jQuery.each( tuples, function( i, tuple ) {
+ var list = tuple[ 2 ],
+ stateString = tuple[ 3 ];
+
+ // promise[ done | fail | progress ] = list.add
+ promise[ tuple[1] ] = list.add;
+
+ // Handle state
+ if ( stateString ) {
+ list.add(function() {
+ // state = [ resolved | rejected ]
+ state = stateString;
+
+ // [ reject_list | resolve_list ].disable; progress_list.lock
+ }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
+ }
+
+ // deferred[ resolve | reject | notify ]
+ deferred[ tuple[0] ] = function() {
+ deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
+ return this;
+ };
+ deferred[ tuple[0] + "With" ] = list.fireWith;
+ });
+
+ // Make the deferred a promise
+ promise.promise( deferred );
+
+ // Call given func if any
+ if ( func ) {
+ func.call( deferred, deferred );
+ }
+
+ // All done!
+ return deferred;
+ },
+
+ // Deferred helper
+ when: function( subordinate /* , ..., subordinateN */ ) {
+ var i = 0,
+ resolveValues = slice.call( arguments ),
+ length = resolveValues.length,
+
+ // the count of uncompleted subordinates
+ remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
+
+ // the master Deferred. If resolveValues consist of only a single Deferred, just use that.
+ deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
+
+ // Update function for both resolve and progress values
+ updateFunc = function( i, contexts, values ) {
+ return function( value ) {
+ contexts[ i ] = this;
+ values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
+ if ( values === progressValues ) {
+ deferred.notifyWith( contexts, values );
+ } else if ( !( --remaining ) ) {
+ deferred.resolveWith( contexts, values );
+ }
+ };
+ },
+
+ progressValues, progressContexts, resolveContexts;
+
+ // Add listeners to Deferred subordinates; treat others as resolved
+ if ( length > 1 ) {
+ progressValues = new Array( length );
+ progressContexts = new Array( length );
+ resolveContexts = new Array( length );
+ for ( ; i < length; i++ ) {
+ if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
+ resolveValues[ i ].promise()
+ .done( updateFunc( i, resolveContexts, resolveValues ) )
+ .fail( deferred.reject )
+ .progress( updateFunc( i, progressContexts, progressValues ) );
+ } else {
+ --remaining;
+ }
+ }
+ }
+
+ // If we're not waiting on anything, resolve the master
+ if ( !remaining ) {
+ deferred.resolveWith( resolveContexts, resolveValues );
+ }
+
+ return deferred.promise();
+ }
+});
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/deprecated.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/deprecated.js
new file mode 100644
index 0000000..1b068bc
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/deprecated.js
@@ -0,0 +1,13 @@
+define([
+ "./core",
+ "./traversing"
+], function( jQuery ) {
+
+// The number of elements contained in the matched element set
+jQuery.fn.size = function() {
+ return this.length;
+};
+
+jQuery.fn.andSelf = jQuery.fn.addBack;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/dimensions.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/dimensions.js
new file mode 100644
index 0000000..e6cb04c
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/dimensions.js
@@ -0,0 +1,50 @@
+define([
+ "./core",
+ "./core/access",
+ "./css"
+], function( jQuery, access ) {
+
+// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
+jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
+ jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
+ // Margin is only for outerHeight, outerWidth
+ jQuery.fn[ funcName ] = function( margin, value ) {
+ var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
+ extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
+
+ return access( this, function( elem, type, value ) {
+ var doc;
+
+ if ( jQuery.isWindow( elem ) ) {
+ // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
+ // isn't a whole lot we can do. See pull request at this URL for discussion:
+ // https://github.com/jquery/jquery/pull/764
+ return elem.document.documentElement[ "client" + name ];
+ }
+
+ // Get document width or height
+ if ( elem.nodeType === 9 ) {
+ doc = elem.documentElement;
+
+ // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
+ // whichever is greatest
+ return Math.max(
+ elem.body[ "scroll" + name ], doc[ "scroll" + name ],
+ elem.body[ "offset" + name ], doc[ "offset" + name ],
+ doc[ "client" + name ]
+ );
+ }
+
+ return value === undefined ?
+ // Get width or height on the element, requesting but not forcing parseFloat
+ jQuery.css( elem, type, extra ) :
+
+ // Set width or height on the element
+ jQuery.style( elem, type, value, extra );
+ }, type, chainable ? margin : undefined, chainable, null );
+ };
+ });
+});
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/effects.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/effects.js
new file mode 100644
index 0000000..90226bd
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/effects.js
@@ -0,0 +1,648 @@
+define([
+ "./core",
+ "./var/pnum",
+ "./css/var/cssExpand",
+ "./css/var/isHidden",
+ "./css/defaultDisplay",
+ "./data/var/data_priv",
+
+ "./core/init",
+ "./effects/Tween",
+ "./queue",
+ "./css",
+ "./deferred",
+ "./traversing"
+], function( jQuery, pnum, cssExpand, isHidden, defaultDisplay, data_priv ) {
+
+var
+ fxNow, timerId,
+ rfxtypes = /^(?:toggle|show|hide)$/,
+ rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
+ rrun = /queueHooks$/,
+ animationPrefilters = [ defaultPrefilter ],
+ tweeners = {
+ "*": [ function( prop, value ) {
+ var tween = this.createTween( prop, value ),
+ target = tween.cur(),
+ parts = rfxnum.exec( value ),
+ unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
+
+ // Starting value computation is required for potential unit mismatches
+ start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
+ rfxnum.exec( jQuery.css( tween.elem, prop ) ),
+ scale = 1,
+ maxIterations = 20;
+
+ if ( start && start[ 3 ] !== unit ) {
+ // Trust units reported by jQuery.css
+ unit = unit || start[ 3 ];
+
+ // Make sure we update the tween properties later on
+ parts = parts || [];
+
+ // Iteratively approximate from a nonzero starting point
+ start = +target || 1;
+
+ do {
+ // If previous iteration zeroed out, double until we get *something*.
+ // Use string for doubling so we don't accidentally see scale as unchanged below
+ scale = scale || ".5";
+
+ // Adjust and apply
+ start = start / scale;
+ jQuery.style( tween.elem, prop, start + unit );
+
+ // Update scale, tolerating zero or NaN from tween.cur(),
+ // break the loop if scale is unchanged or perfect, or if we've just had enough
+ } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
+ }
+
+ // Update tween properties
+ if ( parts ) {
+ start = tween.start = +start || +target || 0;
+ tween.unit = unit;
+ // If a +=/-= token was provided, we're doing a relative animation
+ tween.end = parts[ 1 ] ?
+ start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+ +parts[ 2 ];
+ }
+
+ return tween;
+ } ]
+ };
+
+// Animations created synchronously will run synchronously
+function createFxNow() {
+ setTimeout(function() {
+ fxNow = undefined;
+ });
+ return ( fxNow = jQuery.now() );
+}
+
+// Generate parameters to create a standard animation
+function genFx( type, includeWidth ) {
+ var which,
+ i = 0,
+ attrs = { height: type };
+
+ // If we include width, step value is 1 to do all cssExpand values,
+ // otherwise step value is 2 to skip over Left and Right
+ includeWidth = includeWidth ? 1 : 0;
+ for ( ; i < 4 ; i += 2 - includeWidth ) {
+ which = cssExpand[ i ];
+ attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
+ }
+
+ if ( includeWidth ) {
+ attrs.opacity = attrs.width = type;
+ }
+
+ return attrs;
+}
+
+function createTween( value, prop, animation ) {
+ var tween,
+ collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
+ index = 0,
+ length = collection.length;
+ for ( ; index < length; index++ ) {
+ if ( (tween = collection[ index ].call( animation, prop, value )) ) {
+
+ // We're done with this property
+ return tween;
+ }
+ }
+}
+
+function defaultPrefilter( elem, props, opts ) {
+ /* jshint validthis: true */
+ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
+ anim = this,
+ orig = {},
+ style = elem.style,
+ hidden = elem.nodeType && isHidden( elem ),
+ dataShow = data_priv.get( elem, "fxshow" );
+
+ // Handle queue: false promises
+ if ( !opts.queue ) {
+ hooks = jQuery._queueHooks( elem, "fx" );
+ if ( hooks.unqueued == null ) {
+ hooks.unqueued = 0;
+ oldfire = hooks.empty.fire;
+ hooks.empty.fire = function() {
+ if ( !hooks.unqueued ) {
+ oldfire();
+ }
+ };
+ }
+ hooks.unqueued++;
+
+ anim.always(function() {
+ // Ensure the complete handler is called before this completes
+ anim.always(function() {
+ hooks.unqueued--;
+ if ( !jQuery.queue( elem, "fx" ).length ) {
+ hooks.empty.fire();
+ }
+ });
+ });
+ }
+
+ // Height/width overflow pass
+ if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
+ // Make sure that nothing sneaks out
+ // Record all 3 overflow attributes because IE9-10 do not
+ // change the overflow attribute when overflowX and
+ // overflowY are set to the same value
+ opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
+
+ // Set display property to inline-block for height/width
+ // animations on inline elements that are having width/height animated
+ display = jQuery.css( elem, "display" );
+
+ // Test default display if display is currently "none"
+ checkDisplay = display === "none" ?
+ data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
+
+ if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
+ style.display = "inline-block";
+ }
+ }
+
+ if ( opts.overflow ) {
+ style.overflow = "hidden";
+ anim.always(function() {
+ style.overflow = opts.overflow[ 0 ];
+ style.overflowX = opts.overflow[ 1 ];
+ style.overflowY = opts.overflow[ 2 ];
+ });
+ }
+
+ // show/hide pass
+ for ( prop in props ) {
+ value = props[ prop ];
+ if ( rfxtypes.exec( value ) ) {
+ delete props[ prop ];
+ toggle = toggle || value === "toggle";
+ if ( value === ( hidden ? "hide" : "show" ) ) {
+
+ // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
+ if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
+ hidden = true;
+ } else {
+ continue;
+ }
+ }
+ orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
+
+ // Any non-fx value stops us from restoring the original display value
+ } else {
+ display = undefined;
+ }
+ }
+
+ if ( !jQuery.isEmptyObject( orig ) ) {
+ if ( dataShow ) {
+ if ( "hidden" in dataShow ) {
+ hidden = dataShow.hidden;
+ }
+ } else {
+ dataShow = data_priv.access( elem, "fxshow", {} );
+ }
+
+ // Store state if its toggle - enables .stop().toggle() to "reverse"
+ if ( toggle ) {
+ dataShow.hidden = !hidden;
+ }
+ if ( hidden ) {
+ jQuery( elem ).show();
+ } else {
+ anim.done(function() {
+ jQuery( elem ).hide();
+ });
+ }
+ anim.done(function() {
+ var prop;
+
+ data_priv.remove( elem, "fxshow" );
+ for ( prop in orig ) {
+ jQuery.style( elem, prop, orig[ prop ] );
+ }
+ });
+ for ( prop in orig ) {
+ tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
+
+ if ( !( prop in dataShow ) ) {
+ dataShow[ prop ] = tween.start;
+ if ( hidden ) {
+ tween.end = tween.start;
+ tween.start = prop === "width" || prop === "height" ? 1 : 0;
+ }
+ }
+ }
+
+ // If this is a noop like .hide().hide(), restore an overwritten display value
+ } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
+ style.display = display;
+ }
+}
+
+function propFilter( props, specialEasing ) {
+ var index, name, easing, value, hooks;
+
+ // camelCase, specialEasing and expand cssHook pass
+ for ( index in props ) {
+ name = jQuery.camelCase( index );
+ easing = specialEasing[ name ];
+ value = props[ index ];
+ if ( jQuery.isArray( value ) ) {
+ easing = value[ 1 ];
+ value = props[ index ] = value[ 0 ];
+ }
+
+ if ( index !== name ) {
+ props[ name ] = value;
+ delete props[ index ];
+ }
+
+ hooks = jQuery.cssHooks[ name ];
+ if ( hooks && "expand" in hooks ) {
+ value = hooks.expand( value );
+ delete props[ name ];
+
+ // Not quite $.extend, this won't overwrite existing keys.
+ // Reusing 'index' because we have the correct "name"
+ for ( index in value ) {
+ if ( !( index in props ) ) {
+ props[ index ] = value[ index ];
+ specialEasing[ index ] = easing;
+ }
+ }
+ } else {
+ specialEasing[ name ] = easing;
+ }
+ }
+}
+
+function Animation( elem, properties, options ) {
+ var result,
+ stopped,
+ index = 0,
+ length = animationPrefilters.length,
+ deferred = jQuery.Deferred().always( function() {
+ // Don't match elem in the :animated selector
+ delete tick.elem;
+ }),
+ tick = function() {
+ if ( stopped ) {
+ return false;
+ }
+ var currentTime = fxNow || createFxNow(),
+ remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
+ // Support: Android 2.3
+ // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
+ temp = remaining / animation.duration || 0,
+ percent = 1 - temp,
+ index = 0,
+ length = animation.tweens.length;
+
+ for ( ; index < length ; index++ ) {
+ animation.tweens[ index ].run( percent );
+ }
+
+ deferred.notifyWith( elem, [ animation, percent, remaining ]);
+
+ if ( percent < 1 && length ) {
+ return remaining;
+ } else {
+ deferred.resolveWith( elem, [ animation ] );
+ return false;
+ }
+ },
+ animation = deferred.promise({
+ elem: elem,
+ props: jQuery.extend( {}, properties ),
+ opts: jQuery.extend( true, { specialEasing: {} }, options ),
+ originalProperties: properties,
+ originalOptions: options,
+ startTime: fxNow || createFxNow(),
+ duration: options.duration,
+ tweens: [],
+ createTween: function( prop, end ) {
+ var tween = jQuery.Tween( elem, animation.opts, prop, end,
+ animation.opts.specialEasing[ prop ] || animation.opts.easing );
+ animation.tweens.push( tween );
+ return tween;
+ },
+ stop: function( gotoEnd ) {
+ var index = 0,
+ // If we are going to the end, we want to run all the tweens
+ // otherwise we skip this part
+ length = gotoEnd ? animation.tweens.length : 0;
+ if ( stopped ) {
+ return this;
+ }
+ stopped = true;
+ for ( ; index < length ; index++ ) {
+ animation.tweens[ index ].run( 1 );
+ }
+
+ // Resolve when we played the last frame; otherwise, reject
+ if ( gotoEnd ) {
+ deferred.resolveWith( elem, [ animation, gotoEnd ] );
+ } else {
+ deferred.rejectWith( elem, [ animation, gotoEnd ] );
+ }
+ return this;
+ }
+ }),
+ props = animation.props;
+
+ propFilter( props, animation.opts.specialEasing );
+
+ for ( ; index < length ; index++ ) {
+ result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
+ if ( result ) {
+ return result;
+ }
+ }
+
+ jQuery.map( props, createTween, animation );
+
+ if ( jQuery.isFunction( animation.opts.start ) ) {
+ animation.opts.start.call( elem, animation );
+ }
+
+ jQuery.fx.timer(
+ jQuery.extend( tick, {
+ elem: elem,
+ anim: animation,
+ queue: animation.opts.queue
+ })
+ );
+
+ // attach callbacks from options
+ return animation.progress( animation.opts.progress )
+ .done( animation.opts.done, animation.opts.complete )
+ .fail( animation.opts.fail )
+ .always( animation.opts.always );
+}
+
+jQuery.Animation = jQuery.extend( Animation, {
+
+ tweener: function( props, callback ) {
+ if ( jQuery.isFunction( props ) ) {
+ callback = props;
+ props = [ "*" ];
+ } else {
+ props = props.split(" ");
+ }
+
+ var prop,
+ index = 0,
+ length = props.length;
+
+ for ( ; index < length ; index++ ) {
+ prop = props[ index ];
+ tweeners[ prop ] = tweeners[ prop ] || [];
+ tweeners[ prop ].unshift( callback );
+ }
+ },
+
+ prefilter: function( callback, prepend ) {
+ if ( prepend ) {
+ animationPrefilters.unshift( callback );
+ } else {
+ animationPrefilters.push( callback );
+ }
+ }
+});
+
+jQuery.speed = function( speed, easing, fn ) {
+ var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
+ complete: fn || !fn && easing ||
+ jQuery.isFunction( speed ) && speed,
+ duration: speed,
+ easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
+ };
+
+ opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
+ opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
+
+ // Normalize opt.queue - true/undefined/null -> "fx"
+ if ( opt.queue == null || opt.queue === true ) {
+ opt.queue = "fx";
+ }
+
+ // Queueing
+ opt.old = opt.complete;
+
+ opt.complete = function() {
+ if ( jQuery.isFunction( opt.old ) ) {
+ opt.old.call( this );
+ }
+
+ if ( opt.queue ) {
+ jQuery.dequeue( this, opt.queue );
+ }
+ };
+
+ return opt;
+};
+
+jQuery.fn.extend({
+ fadeTo: function( speed, to, easing, callback ) {
+
+ // Show any hidden elements after setting opacity to 0
+ return this.filter( isHidden ).css( "opacity", 0 ).show()
+
+ // Animate to the value specified
+ .end().animate({ opacity: to }, speed, easing, callback );
+ },
+ animate: function( prop, speed, easing, callback ) {
+ var empty = jQuery.isEmptyObject( prop ),
+ optall = jQuery.speed( speed, easing, callback ),
+ doAnimation = function() {
+ // Operate on a copy of prop so per-property easing won't be lost
+ var anim = Animation( this, jQuery.extend( {}, prop ), optall );
+
+ // Empty animations, or finishing resolves immediately
+ if ( empty || data_priv.get( this, "finish" ) ) {
+ anim.stop( true );
+ }
+ };
+ doAnimation.finish = doAnimation;
+
+ return empty || optall.queue === false ?
+ this.each( doAnimation ) :
+ this.queue( optall.queue, doAnimation );
+ },
+ stop: function( type, clearQueue, gotoEnd ) {
+ var stopQueue = function( hooks ) {
+ var stop = hooks.stop;
+ delete hooks.stop;
+ stop( gotoEnd );
+ };
+
+ if ( typeof type !== "string" ) {
+ gotoEnd = clearQueue;
+ clearQueue = type;
+ type = undefined;
+ }
+ if ( clearQueue && type !== false ) {
+ this.queue( type || "fx", [] );
+ }
+
+ return this.each(function() {
+ var dequeue = true,
+ index = type != null && type + "queueHooks",
+ timers = jQuery.timers,
+ data = data_priv.get( this );
+
+ if ( index ) {
+ if ( data[ index ] && data[ index ].stop ) {
+ stopQueue( data[ index ] );
+ }
+ } else {
+ for ( index in data ) {
+ if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
+ stopQueue( data[ index ] );
+ }
+ }
+ }
+
+ for ( index = timers.length; index--; ) {
+ if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
+ timers[ index ].anim.stop( gotoEnd );
+ dequeue = false;
+ timers.splice( index, 1 );
+ }
+ }
+
+ // Start the next in the queue if the last step wasn't forced.
+ // Timers currently will call their complete callbacks, which
+ // will dequeue but only if they were gotoEnd.
+ if ( dequeue || !gotoEnd ) {
+ jQuery.dequeue( this, type );
+ }
+ });
+ },
+ finish: function( type ) {
+ if ( type !== false ) {
+ type = type || "fx";
+ }
+ return this.each(function() {
+ var index,
+ data = data_priv.get( this ),
+ queue = data[ type + "queue" ],
+ hooks = data[ type + "queueHooks" ],
+ timers = jQuery.timers,
+ length = queue ? queue.length : 0;
+
+ // Enable finishing flag on private data
+ data.finish = true;
+
+ // Empty the queue first
+ jQuery.queue( this, type, [] );
+
+ if ( hooks && hooks.stop ) {
+ hooks.stop.call( this, true );
+ }
+
+ // Look for any active animations, and finish them
+ for ( index = timers.length; index--; ) {
+ if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
+ timers[ index ].anim.stop( true );
+ timers.splice( index, 1 );
+ }
+ }
+
+ // Look for any animations in the old queue and finish them
+ for ( index = 0; index < length; index++ ) {
+ if ( queue[ index ] && queue[ index ].finish ) {
+ queue[ index ].finish.call( this );
+ }
+ }
+
+ // Turn off finishing flag
+ delete data.finish;
+ });
+ }
+});
+
+jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
+ var cssFn = jQuery.fn[ name ];
+ jQuery.fn[ name ] = function( speed, easing, callback ) {
+ return speed == null || typeof speed === "boolean" ?
+ cssFn.apply( this, arguments ) :
+ this.animate( genFx( name, true ), speed, easing, callback );
+ };
+});
+
+// Generate shortcuts for custom animations
+jQuery.each({
+ slideDown: genFx("show"),
+ slideUp: genFx("hide"),
+ slideToggle: genFx("toggle"),
+ fadeIn: { opacity: "show" },
+ fadeOut: { opacity: "hide" },
+ fadeToggle: { opacity: "toggle" }
+}, function( name, props ) {
+ jQuery.fn[ name ] = function( speed, easing, callback ) {
+ return this.animate( props, speed, easing, callback );
+ };
+});
+
+jQuery.timers = [];
+jQuery.fx.tick = function() {
+ var timer,
+ i = 0,
+ timers = jQuery.timers;
+
+ fxNow = jQuery.now();
+
+ for ( ; i < timers.length; i++ ) {
+ timer = timers[ i ];
+ // Checks the timer has not already been removed
+ if ( !timer() && timers[ i ] === timer ) {
+ timers.splice( i--, 1 );
+ }
+ }
+
+ if ( !timers.length ) {
+ jQuery.fx.stop();
+ }
+ fxNow = undefined;
+};
+
+jQuery.fx.timer = function( timer ) {
+ jQuery.timers.push( timer );
+ if ( timer() ) {
+ jQuery.fx.start();
+ } else {
+ jQuery.timers.pop();
+ }
+};
+
+jQuery.fx.interval = 13;
+
+jQuery.fx.start = function() {
+ if ( !timerId ) {
+ timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
+ }
+};
+
+jQuery.fx.stop = function() {
+ clearInterval( timerId );
+ timerId = null;
+};
+
+jQuery.fx.speeds = {
+ slow: 600,
+ fast: 200,
+ // Default speed
+ _default: 400
+};
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/effects/Tween.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/effects/Tween.js
new file mode 100644
index 0000000..9acd8d0
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/effects/Tween.js
@@ -0,0 +1,114 @@
+define([
+ "../core",
+ "../css"
+], function( jQuery ) {
+
+function Tween( elem, options, prop, end, easing ) {
+ return new Tween.prototype.init( elem, options, prop, end, easing );
+}
+jQuery.Tween = Tween;
+
+Tween.prototype = {
+ constructor: Tween,
+ init: function( elem, options, prop, end, easing, unit ) {
+ this.elem = elem;
+ this.prop = prop;
+ this.easing = easing || "swing";
+ this.options = options;
+ this.start = this.now = this.cur();
+ this.end = end;
+ this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
+ },
+ cur: function() {
+ var hooks = Tween.propHooks[ this.prop ];
+
+ return hooks && hooks.get ?
+ hooks.get( this ) :
+ Tween.propHooks._default.get( this );
+ },
+ run: function( percent ) {
+ var eased,
+ hooks = Tween.propHooks[ this.prop ];
+
+ if ( this.options.duration ) {
+ this.pos = eased = jQuery.easing[ this.easing ](
+ percent, this.options.duration * percent, 0, 1, this.options.duration
+ );
+ } else {
+ this.pos = eased = percent;
+ }
+ this.now = ( this.end - this.start ) * eased + this.start;
+
+ if ( this.options.step ) {
+ this.options.step.call( this.elem, this.now, this );
+ }
+
+ if ( hooks && hooks.set ) {
+ hooks.set( this );
+ } else {
+ Tween.propHooks._default.set( this );
+ }
+ return this;
+ }
+};
+
+Tween.prototype.init.prototype = Tween.prototype;
+
+Tween.propHooks = {
+ _default: {
+ get: function( tween ) {
+ var result;
+
+ if ( tween.elem[ tween.prop ] != null &&
+ (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
+ return tween.elem[ tween.prop ];
+ }
+
+ // Passing an empty string as a 3rd parameter to .css will automatically
+ // attempt a parseFloat and fallback to a string if the parse fails.
+ // Simple values such as "10px" are parsed to Float;
+ // complex values such as "rotate(1rad)" are returned as-is.
+ result = jQuery.css( tween.elem, tween.prop, "" );
+ // Empty strings, null, undefined and "auto" are converted to 0.
+ return !result || result === "auto" ? 0 : result;
+ },
+ set: function( tween ) {
+ // Use step hook for back compat.
+ // Use cssHook if its there.
+ // Use .style if available and use plain properties where available.
+ if ( jQuery.fx.step[ tween.prop ] ) {
+ jQuery.fx.step[ tween.prop ]( tween );
+ } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
+ jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
+ } else {
+ tween.elem[ tween.prop ] = tween.now;
+ }
+ }
+ }
+};
+
+// Support: IE9
+// Panic based approach to setting things on disconnected nodes
+Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
+ set: function( tween ) {
+ if ( tween.elem.nodeType && tween.elem.parentNode ) {
+ tween.elem[ tween.prop ] = tween.now;
+ }
+ }
+};
+
+jQuery.easing = {
+ linear: function( p ) {
+ return p;
+ },
+ swing: function( p ) {
+ return 0.5 - Math.cos( p * Math.PI ) / 2;
+ }
+};
+
+jQuery.fx = Tween.prototype.init;
+
+// Back Compat <1.8 extension point
+jQuery.fx.step = {};
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/effects/animatedSelector.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/effects/animatedSelector.js
new file mode 100644
index 0000000..bc5a3d6
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/effects/animatedSelector.js
@@ -0,0 +1,13 @@
+define([
+ "../core",
+ "../selector",
+ "../effects"
+], function( jQuery ) {
+
+jQuery.expr.filters.animated = function( elem ) {
+ return jQuery.grep(jQuery.timers, function( fn ) {
+ return elem === fn.elem;
+ }).length;
+};
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/event.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/event.js
new file mode 100644
index 0000000..8f04b89
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/event.js
@@ -0,0 +1,868 @@
+define([
+ "./core",
+ "./var/strundefined",
+ "./var/rnotwhite",
+ "./var/hasOwn",
+ "./var/slice",
+ "./event/support",
+ "./data/var/data_priv",
+
+ "./core/init",
+ "./data/accepts",
+ "./selector"
+], function( jQuery, strundefined, rnotwhite, hasOwn, slice, support, data_priv ) {
+
+var
+ rkeyEvent = /^key/,
+ rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
+ rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
+ rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
+
+function returnTrue() {
+ return true;
+}
+
+function returnFalse() {
+ return false;
+}
+
+function safeActiveElement() {
+ try {
+ return document.activeElement;
+ } catch ( err ) { }
+}
+
+/*
+ * Helper functions for managing events -- not part of the public interface.
+ * Props to Dean Edwards' addEvent library for many of the ideas.
+ */
+jQuery.event = {
+
+ global: {},
+
+ add: function( elem, types, handler, data, selector ) {
+
+ var handleObjIn, eventHandle, tmp,
+ events, t, handleObj,
+ special, handlers, type, namespaces, origType,
+ elemData = data_priv.get( elem );
+
+ // Don't attach events to noData or text/comment nodes (but allow plain objects)
+ if ( !elemData ) {
+ return;
+ }
+
+ // Caller can pass in an object of custom data in lieu of the handler
+ if ( handler.handler ) {
+ handleObjIn = handler;
+ handler = handleObjIn.handler;
+ selector = handleObjIn.selector;
+ }
+
+ // Make sure that the handler has a unique ID, used to find/remove it later
+ if ( !handler.guid ) {
+ handler.guid = jQuery.guid++;
+ }
+
+ // Init the element's event structure and main handler, if this is the first
+ if ( !(events = elemData.events) ) {
+ events = elemData.events = {};
+ }
+ if ( !(eventHandle = elemData.handle) ) {
+ eventHandle = elemData.handle = function( e ) {
+ // Discard the second event of a jQuery.event.trigger() and
+ // when an event is called after a page has unloaded
+ return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
+ jQuery.event.dispatch.apply( elem, arguments ) : undefined;
+ };
+ }
+
+ // Handle multiple events separated by a space
+ types = ( types || "" ).match( rnotwhite ) || [ "" ];
+ t = types.length;
+ while ( t-- ) {
+ tmp = rtypenamespace.exec( types[t] ) || [];
+ type = origType = tmp[1];
+ namespaces = ( tmp[2] || "" ).split( "." ).sort();
+
+ // There *must* be a type, no attaching namespace-only handlers
+ if ( !type ) {
+ continue;
+ }
+
+ // If event changes its type, use the special event handlers for the changed type
+ special = jQuery.event.special[ type ] || {};
+
+ // If selector defined, determine special event api type, otherwise given type
+ type = ( selector ? special.delegateType : special.bindType ) || type;
+
+ // Update special based on newly reset type
+ special = jQuery.event.special[ type ] || {};
+
+ // handleObj is passed to all event handlers
+ handleObj = jQuery.extend({
+ type: type,
+ origType: origType,
+ data: data,
+ handler: handler,
+ guid: handler.guid,
+ selector: selector,
+ needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
+ namespace: namespaces.join(".")
+ }, handleObjIn );
+
+ // Init the event handler queue if we're the first
+ if ( !(handlers = events[ type ]) ) {
+ handlers = events[ type ] = [];
+ handlers.delegateCount = 0;
+
+ // Only use addEventListener if the special events handler returns false
+ if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
+ if ( elem.addEventListener ) {
+ elem.addEventListener( type, eventHandle, false );
+ }
+ }
+ }
+
+ if ( special.add ) {
+ special.add.call( elem, handleObj );
+
+ if ( !handleObj.handler.guid ) {
+ handleObj.handler.guid = handler.guid;
+ }
+ }
+
+ // Add to the element's handler list, delegates in front
+ if ( selector ) {
+ handlers.splice( handlers.delegateCount++, 0, handleObj );
+ } else {
+ handlers.push( handleObj );
+ }
+
+ // Keep track of which events have ever been used, for event optimization
+ jQuery.event.global[ type ] = true;
+ }
+
+ },
+
+ // Detach an event or set of events from an element
+ remove: function( elem, types, handler, selector, mappedTypes ) {
+
+ var j, origCount, tmp,
+ events, t, handleObj,
+ special, handlers, type, namespaces, origType,
+ elemData = data_priv.hasData( elem ) && data_priv.get( elem );
+
+ if ( !elemData || !(events = elemData.events) ) {
+ return;
+ }
+
+ // Once for each type.namespace in types; type may be omitted
+ types = ( types || "" ).match( rnotwhite ) || [ "" ];
+ t = types.length;
+ while ( t-- ) {
+ tmp = rtypenamespace.exec( types[t] ) || [];
+ type = origType = tmp[1];
+ namespaces = ( tmp[2] || "" ).split( "." ).sort();
+
+ // Unbind all events (on this namespace, if provided) for the element
+ if ( !type ) {
+ for ( type in events ) {
+ jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
+ }
+ continue;
+ }
+
+ special = jQuery.event.special[ type ] || {};
+ type = ( selector ? special.delegateType : special.bindType ) || type;
+ handlers = events[ type ] || [];
+ tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
+
+ // Remove matching events
+ origCount = j = handlers.length;
+ while ( j-- ) {
+ handleObj = handlers[ j ];
+
+ if ( ( mappedTypes || origType === handleObj.origType ) &&
+ ( !handler || handler.guid === handleObj.guid ) &&
+ ( !tmp || tmp.test( handleObj.namespace ) ) &&
+ ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
+ handlers.splice( j, 1 );
+
+ if ( handleObj.selector ) {
+ handlers.delegateCount--;
+ }
+ if ( special.remove ) {
+ special.remove.call( elem, handleObj );
+ }
+ }
+ }
+
+ // Remove generic event handler if we removed something and no more handlers exist
+ // (avoids potential for endless recursion during removal of special event handlers)
+ if ( origCount && !handlers.length ) {
+ if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
+ jQuery.removeEvent( elem, type, elemData.handle );
+ }
+
+ delete events[ type ];
+ }
+ }
+
+ // Remove the expando if it's no longer used
+ if ( jQuery.isEmptyObject( events ) ) {
+ delete elemData.handle;
+ data_priv.remove( elem, "events" );
+ }
+ },
+
+ trigger: function( event, data, elem, onlyHandlers ) {
+
+ var i, cur, tmp, bubbleType, ontype, handle, special,
+ eventPath = [ elem || document ],
+ type = hasOwn.call( event, "type" ) ? event.type : event,
+ namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
+
+ cur = tmp = elem = elem || document;
+
+ // Don't do events on text and comment nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ // focus/blur morphs to focusin/out; ensure we're not firing them right now
+ if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
+ return;
+ }
+
+ if ( type.indexOf(".") >= 0 ) {
+ // Namespaced trigger; create a regexp to match event type in handle()
+ namespaces = type.split(".");
+ type = namespaces.shift();
+ namespaces.sort();
+ }
+ ontype = type.indexOf(":") < 0 && "on" + type;
+
+ // Caller can pass in a jQuery.Event object, Object, or just an event type string
+ event = event[ jQuery.expando ] ?
+ event :
+ new jQuery.Event( type, typeof event === "object" && event );
+
+ // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
+ event.isTrigger = onlyHandlers ? 2 : 3;
+ event.namespace = namespaces.join(".");
+ event.namespace_re = event.namespace ?
+ new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
+ null;
+
+ // Clean up the event in case it is being reused
+ event.result = undefined;
+ if ( !event.target ) {
+ event.target = elem;
+ }
+
+ // Clone any incoming data and prepend the event, creating the handler arg list
+ data = data == null ?
+ [ event ] :
+ jQuery.makeArray( data, [ event ] );
+
+ // Allow special events to draw outside the lines
+ special = jQuery.event.special[ type ] || {};
+ if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
+ return;
+ }
+
+ // Determine event propagation path in advance, per W3C events spec (#9951)
+ // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
+ if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
+
+ bubbleType = special.delegateType || type;
+ if ( !rfocusMorph.test( bubbleType + type ) ) {
+ cur = cur.parentNode;
+ }
+ for ( ; cur; cur = cur.parentNode ) {
+ eventPath.push( cur );
+ tmp = cur;
+ }
+
+ // Only add window if we got to document (e.g., not plain obj or detached DOM)
+ if ( tmp === (elem.ownerDocument || document) ) {
+ eventPath.push( tmp.defaultView || tmp.parentWindow || window );
+ }
+ }
+
+ // Fire handlers on the event path
+ i = 0;
+ while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
+
+ event.type = i > 1 ?
+ bubbleType :
+ special.bindType || type;
+
+ // jQuery handler
+ handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
+ if ( handle ) {
+ handle.apply( cur, data );
+ }
+
+ // Native handler
+ handle = ontype && cur[ ontype ];
+ if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
+ event.result = handle.apply( cur, data );
+ if ( event.result === false ) {
+ event.preventDefault();
+ }
+ }
+ }
+ event.type = type;
+
+ // If nobody prevented the default action, do it now
+ if ( !onlyHandlers && !event.isDefaultPrevented() ) {
+
+ if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
+ jQuery.acceptData( elem ) ) {
+
+ // Call a native DOM method on the target with the same name name as the event.
+ // Don't do default actions on window, that's where global variables be (#6170)
+ if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
+
+ // Don't re-trigger an onFOO event when we call its FOO() method
+ tmp = elem[ ontype ];
+
+ if ( tmp ) {
+ elem[ ontype ] = null;
+ }
+
+ // Prevent re-triggering of the same event, since we already bubbled it above
+ jQuery.event.triggered = type;
+ elem[ type ]();
+ jQuery.event.triggered = undefined;
+
+ if ( tmp ) {
+ elem[ ontype ] = tmp;
+ }
+ }
+ }
+ }
+
+ return event.result;
+ },
+
+ dispatch: function( event ) {
+
+ // Make a writable jQuery.Event from the native event object
+ event = jQuery.event.fix( event );
+
+ var i, j, ret, matched, handleObj,
+ handlerQueue = [],
+ args = slice.call( arguments ),
+ handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [],
+ special = jQuery.event.special[ event.type ] || {};
+
+ // Use the fix-ed jQuery.Event rather than the (read-only) native event
+ args[0] = event;
+ event.delegateTarget = this;
+
+ // Call the preDispatch hook for the mapped type, and let it bail if desired
+ if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
+ return;
+ }
+
+ // Determine handlers
+ handlerQueue = jQuery.event.handlers.call( this, event, handlers );
+
+ // Run delegates first; they may want to stop propagation beneath us
+ i = 0;
+ while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
+ event.currentTarget = matched.elem;
+
+ j = 0;
+ while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
+
+ // Triggered event must either 1) have no namespace, or 2) have namespace(s)
+ // a subset or equal to those in the bound event (both can have no namespace).
+ if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
+
+ event.handleObj = handleObj;
+ event.data = handleObj.data;
+
+ ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
+ .apply( matched.elem, args );
+
+ if ( ret !== undefined ) {
+ if ( (event.result = ret) === false ) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }
+ }
+ }
+ }
+
+ // Call the postDispatch hook for the mapped type
+ if ( special.postDispatch ) {
+ special.postDispatch.call( this, event );
+ }
+
+ return event.result;
+ },
+
+ handlers: function( event, handlers ) {
+ var i, matches, sel, handleObj,
+ handlerQueue = [],
+ delegateCount = handlers.delegateCount,
+ cur = event.target;
+
+ // Find delegate handlers
+ // Black-hole SVG <use> instance trees (#13180)
+ // Avoid non-left-click bubbling in Firefox (#3861)
+ if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
+
+ for ( ; cur !== this; cur = cur.parentNode || this ) {
+
+ // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
+ if ( cur.disabled !== true || event.type !== "click" ) {
+ matches = [];
+ for ( i = 0; i < delegateCount; i++ ) {
+ handleObj = handlers[ i ];
+
+ // Don't conflict with Object.prototype properties (#13203)
+ sel = handleObj.selector + " ";
+
+ if ( matches[ sel ] === undefined ) {
+ matches[ sel ] = handleObj.needsContext ?
+ jQuery( sel, this ).index( cur ) >= 0 :
+ jQuery.find( sel, this, null, [ cur ] ).length;
+ }
+ if ( matches[ sel ] ) {
+ matches.push( handleObj );
+ }
+ }
+ if ( matches.length ) {
+ handlerQueue.push({ elem: cur, handlers: matches });
+ }
+ }
+ }
+ }
+
+ // Add the remaining (directly-bound) handlers
+ if ( delegateCount < handlers.length ) {
+ handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
+ }
+
+ return handlerQueue;
+ },
+
+ // Includes some event props shared by KeyEvent and MouseEvent
+ props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
+
+ fixHooks: {},
+
+ keyHooks: {
+ props: "char charCode key keyCode".split(" "),
+ filter: function( event, original ) {
+
+ // Add which for key events
+ if ( event.which == null ) {
+ event.which = original.charCode != null ? original.charCode : original.keyCode;
+ }
+
+ return event;
+ }
+ },
+
+ mouseHooks: {
+ props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
+ filter: function( event, original ) {
+ var eventDoc, doc, body,
+ button = original.button;
+
+ // Calculate pageX/Y if missing and clientX/Y available
+ if ( event.pageX == null && original.clientX != null ) {
+ eventDoc = event.target.ownerDocument || document;
+ doc = eventDoc.documentElement;
+ body = eventDoc.body;
+
+ event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
+ event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
+ }
+
+ // Add which for click: 1 === left; 2 === middle; 3 === right
+ // Note: button is not normalized, so don't use it
+ if ( !event.which && button !== undefined ) {
+ event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
+ }
+
+ return event;
+ }
+ },
+
+ fix: function( event ) {
+ if ( event[ jQuery.expando ] ) {
+ return event;
+ }
+
+ // Create a writable copy of the event object and normalize some properties
+ var i, prop, copy,
+ type = event.type,
+ originalEvent = event,
+ fixHook = this.fixHooks[ type ];
+
+ if ( !fixHook ) {
+ this.fixHooks[ type ] = fixHook =
+ rmouseEvent.test( type ) ? this.mouseHooks :
+ rkeyEvent.test( type ) ? this.keyHooks :
+ {};
+ }
+ copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
+
+ event = new jQuery.Event( originalEvent );
+
+ i = copy.length;
+ while ( i-- ) {
+ prop = copy[ i ];
+ event[ prop ] = originalEvent[ prop ];
+ }
+
+ // Support: Cordova 2.5 (WebKit) (#13255)
+ // All events should have a target; Cordova deviceready doesn't
+ if ( !event.target ) {
+ event.target = document;
+ }
+
+ // Support: Safari 6.0+, Chrome<28
+ // Target should not be a text node (#504, #13143)
+ if ( event.target.nodeType === 3 ) {
+ event.target = event.target.parentNode;
+ }
+
+ return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
+ },
+
+ special: {
+ load: {
+ // Prevent triggered image.load events from bubbling to window.load
+ noBubble: true
+ },
+ focus: {
+ // Fire native event if possible so blur/focus sequence is correct
+ trigger: function() {
+ if ( this !== safeActiveElement() && this.focus ) {
+ this.focus();
+ return false;
+ }
+ },
+ delegateType: "focusin"
+ },
+ blur: {
+ trigger: function() {
+ if ( this === safeActiveElement() && this.blur ) {
+ this.blur();
+ return false;
+ }
+ },
+ delegateType: "focusout"
+ },
+ click: {
+ // For checkbox, fire native event so checked state will be right
+ trigger: function() {
+ if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
+ this.click();
+ return false;
+ }
+ },
+
+ // For cross-browser consistency, don't fire native .click() on links
+ _default: function( event ) {
+ return jQuery.nodeName( event.target, "a" );
+ }
+ },
+
+ beforeunload: {
+ postDispatch: function( event ) {
+
+ // Support: Firefox 20+
+ // Firefox doesn't alert if the returnValue field is not set.
+ if ( event.result !== undefined && event.originalEvent ) {
+ event.originalEvent.returnValue = event.result;
+ }
+ }
+ }
+ },
+
+ simulate: function( type, elem, event, bubble ) {
+ // Piggyback on a donor event to simulate a different one.
+ // Fake originalEvent to avoid donor's stopPropagation, but if the
+ // simulated event prevents default then we do the same on the donor.
+ var e = jQuery.extend(
+ new jQuery.Event(),
+ event,
+ {
+ type: type,
+ isSimulated: true,
+ originalEvent: {}
+ }
+ );
+ if ( bubble ) {
+ jQuery.event.trigger( e, null, elem );
+ } else {
+ jQuery.event.dispatch.call( elem, e );
+ }
+ if ( e.isDefaultPrevented() ) {
+ event.preventDefault();
+ }
+ }
+};
+
+jQuery.removeEvent = function( elem, type, handle ) {
+ if ( elem.removeEventListener ) {
+ elem.removeEventListener( type, handle, false );
+ }
+};
+
+jQuery.Event = function( src, props ) {
+ // Allow instantiation without the 'new' keyword
+ if ( !(this instanceof jQuery.Event) ) {
+ return new jQuery.Event( src, props );
+ }
+
+ // Event object
+ if ( src && src.type ) {
+ this.originalEvent = src;
+ this.type = src.type;
+
+ // Events bubbling up the document may have been marked as prevented
+ // by a handler lower down the tree; reflect the correct value.
+ this.isDefaultPrevented = src.defaultPrevented ||
+ src.defaultPrevented === undefined &&
+ // Support: Android<4.0
+ src.returnValue === false ?
+ returnTrue :
+ returnFalse;
+
+ // Event type
+ } else {
+ this.type = src;
+ }
+
+ // Put explicitly provided properties onto the event object
+ if ( props ) {
+ jQuery.extend( this, props );
+ }
+
+ // Create a timestamp if incoming event doesn't have one
+ this.timeStamp = src && src.timeStamp || jQuery.now();
+
+ // Mark it as fixed
+ this[ jQuery.expando ] = true;
+};
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+jQuery.Event.prototype = {
+ isDefaultPrevented: returnFalse,
+ isPropagationStopped: returnFalse,
+ isImmediatePropagationStopped: returnFalse,
+
+ preventDefault: function() {
+ var e = this.originalEvent;
+
+ this.isDefaultPrevented = returnTrue;
+
+ if ( e && e.preventDefault ) {
+ e.preventDefault();
+ }
+ },
+ stopPropagation: function() {
+ var e = this.originalEvent;
+
+ this.isPropagationStopped = returnTrue;
+
+ if ( e && e.stopPropagation ) {
+ e.stopPropagation();
+ }
+ },
+ stopImmediatePropagation: function() {
+ var e = this.originalEvent;
+
+ this.isImmediatePropagationStopped = returnTrue;
+
+ if ( e && e.stopImmediatePropagation ) {
+ e.stopImmediatePropagation();
+ }
+
+ this.stopPropagation();
+ }
+};
+
+// Create mouseenter/leave events using mouseover/out and event-time checks
+// Support: Chrome 15+
+jQuery.each({
+ mouseenter: "mouseover",
+ mouseleave: "mouseout",
+ pointerenter: "pointerover",
+ pointerleave: "pointerout"
+}, function( orig, fix ) {
+ jQuery.event.special[ orig ] = {
+ delegateType: fix,
+ bindType: fix,
+
+ handle: function( event ) {
+ var ret,
+ target = this,
+ related = event.relatedTarget,
+ handleObj = event.handleObj;
+
+ // For mousenter/leave call the handler if related is outside the target.
+ // NB: No relatedTarget if the mouse left/entered the browser window
+ if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
+ event.type = handleObj.origType;
+ ret = handleObj.handler.apply( this, arguments );
+ event.type = fix;
+ }
+ return ret;
+ }
+ };
+});
+
+// Support: Firefox, Chrome, Safari
+// Create "bubbling" focus and blur events
+if ( !support.focusinBubbles ) {
+ jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
+
+ // Attach a single capturing handler on the document while someone wants focusin/focusout
+ var handler = function( event ) {
+ jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
+ };
+
+ jQuery.event.special[ fix ] = {
+ setup: function() {
+ var doc = this.ownerDocument || this,
+ attaches = data_priv.access( doc, fix );
+
+ if ( !attaches ) {
+ doc.addEventListener( orig, handler, true );
+ }
+ data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
+ },
+ teardown: function() {
+ var doc = this.ownerDocument || this,
+ attaches = data_priv.access( doc, fix ) - 1;
+
+ if ( !attaches ) {
+ doc.removeEventListener( orig, handler, true );
+ data_priv.remove( doc, fix );
+
+ } else {
+ data_priv.access( doc, fix, attaches );
+ }
+ }
+ };
+ });
+}
+
+jQuery.fn.extend({
+
+ on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
+ var origFn, type;
+
+ // Types can be a map of types/handlers
+ if ( typeof types === "object" ) {
+ // ( types-Object, selector, data )
+ if ( typeof selector !== "string" ) {
+ // ( types-Object, data )
+ data = data || selector;
+ selector = undefined;
+ }
+ for ( type in types ) {
+ this.on( type, selector, data, types[ type ], one );
+ }
+ return this;
+ }
+
+ if ( data == null && fn == null ) {
+ // ( types, fn )
+ fn = selector;
+ data = selector = undefined;
+ } else if ( fn == null ) {
+ if ( typeof selector === "string" ) {
+ // ( types, selector, fn )
+ fn = data;
+ data = undefined;
+ } else {
+ // ( types, data, fn )
+ fn = data;
+ data = selector;
+ selector = undefined;
+ }
+ }
+ if ( fn === false ) {
+ fn = returnFalse;
+ } else if ( !fn ) {
+ return this;
+ }
+
+ if ( one === 1 ) {
+ origFn = fn;
+ fn = function( event ) {
+ // Can use an empty set, since event contains the info
+ jQuery().off( event );
+ return origFn.apply( this, arguments );
+ };
+ // Use same guid so caller can remove using origFn
+ fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
+ }
+ return this.each( function() {
+ jQuery.event.add( this, types, fn, data, selector );
+ });
+ },
+ one: function( types, selector, data, fn ) {
+ return this.on( types, selector, data, fn, 1 );
+ },
+ off: function( types, selector, fn ) {
+ var handleObj, type;
+ if ( types && types.preventDefault && types.handleObj ) {
+ // ( event ) dispatched jQuery.Event
+ handleObj = types.handleObj;
+ jQuery( types.delegateTarget ).off(
+ handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
+ handleObj.selector,
+ handleObj.handler
+ );
+ return this;
+ }
+ if ( typeof types === "object" ) {
+ // ( types-object [, selector] )
+ for ( type in types ) {
+ this.off( type, selector, types[ type ] );
+ }
+ return this;
+ }
+ if ( selector === false || typeof selector === "function" ) {
+ // ( types [, fn] )
+ fn = selector;
+ selector = undefined;
+ }
+ if ( fn === false ) {
+ fn = returnFalse;
+ }
+ return this.each(function() {
+ jQuery.event.remove( this, types, fn, selector );
+ });
+ },
+
+ trigger: function( type, data ) {
+ return this.each(function() {
+ jQuery.event.trigger( type, data, this );
+ });
+ },
+ triggerHandler: function( type, data ) {
+ var elem = this[0];
+ if ( elem ) {
+ return jQuery.event.trigger( type, data, elem, true );
+ }
+ }
+});
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/event/ajax.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/event/ajax.js
new file mode 100644
index 0000000..278c403
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/event/ajax.js
@@ -0,0 +1,13 @@
+define([
+ "../core",
+ "../event"
+], function( jQuery ) {
+
+// Attach a bunch of functions for handling common AJAX events
+jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
+ jQuery.fn[ type ] = function( fn ) {
+ return this.on( type, fn );
+ };
+});
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/event/alias.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/event/alias.js
new file mode 100644
index 0000000..7e79175
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/event/alias.js
@@ -0,0 +1,39 @@
+define([
+ "../core",
+ "../event"
+], function( jQuery ) {
+
+jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
+ "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
+ "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
+
+ // Handle event binding
+ jQuery.fn[ name ] = function( data, fn ) {
+ return arguments.length > 0 ?
+ this.on( name, null, data, fn ) :
+ this.trigger( name );
+ };
+});
+
+jQuery.fn.extend({
+ hover: function( fnOver, fnOut ) {
+ return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
+ },
+
+ bind: function( types, data, fn ) {
+ return this.on( types, null, data, fn );
+ },
+ unbind: function( types, fn ) {
+ return this.off( types, null, fn );
+ },
+
+ delegate: function( selector, types, data, fn ) {
+ return this.on( types, selector, data, fn );
+ },
+ undelegate: function( selector, types, fn ) {
+ // ( namespace ) or ( selector, types [, fn] )
+ return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
+ }
+});
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/event/support.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/event/support.js
new file mode 100644
index 0000000..85060db
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/event/support.js
@@ -0,0 +1,9 @@
+define([
+ "../var/support"
+], function( support ) {
+
+support.focusinBubbles = "onfocusin" in window;
+
+return support;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/exports/amd.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/exports/amd.js
new file mode 100644
index 0000000..9a9846f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/exports/amd.js
@@ -0,0 +1,24 @@
+define([
+ "../core"
+], function( jQuery ) {
+
+// Register as a named AMD module, since jQuery can be concatenated with other
+// files that may use define, but not via a proper concatenation script that
+// understands anonymous AMD modules. A named AMD is safest and most robust
+// way to register. Lowercase jquery is used because AMD module names are
+// derived from file names, and jQuery is normally delivered in a lowercase
+// file name. Do this after creating the global so that if an AMD module wants
+// to call noConflict to hide this version of jQuery, it will work.
+
+// Note that for maximum portability, libraries that are not jQuery should
+// declare themselves as anonymous modules, and avoid setting a global if an
+// AMD loader is present. jQuery is a special case. For more information, see
+// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
+
+if ( typeof define === "function" && define.amd ) {
+ define( "jquery", [], function() {
+ return jQuery;
+ });
+}
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/exports/global.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/exports/global.js
new file mode 100644
index 0000000..6513287
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/exports/global.js
@@ -0,0 +1,32 @@
+define([
+ "../core",
+ "../var/strundefined"
+], function( jQuery, strundefined ) {
+
+var
+ // Map over jQuery in case of overwrite
+ _jQuery = window.jQuery,
+
+ // Map over the $ in case of overwrite
+ _$ = window.$;
+
+jQuery.noConflict = function( deep ) {
+ if ( window.$ === jQuery ) {
+ window.$ = _$;
+ }
+
+ if ( deep && window.jQuery === jQuery ) {
+ window.jQuery = _jQuery;
+ }
+
+ return jQuery;
+};
+
+// Expose jQuery and $ identifiers, even in AMD
+// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
+// and CommonJS for browser emulators (#13566)
+if ( typeof noGlobal === strundefined ) {
+ window.jQuery = window.$ = jQuery;
+}
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/intro.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/intro.js
new file mode 100644
index 0000000..d7d4368
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/intro.js
@@ -0,0 +1,44 @@
+/*!
+ * jQuery JavaScript Library v@VERSION
+ * http://jquery.com/
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ *
+ * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: @DATE
+ */
+
+(function( global, factory ) {
+
+ if ( typeof module === "object" && typeof module.exports === "object" ) {
+ // For CommonJS and CommonJS-like environments where a proper `window`
+ // is present, execute the factory and get jQuery.
+ // For environments that do not have a `window` with a `document`
+ // (such as Node.js), expose a factory as module.exports.
+ // This accentuates the need for the creation of a real `window`.
+ // e.g. var jQuery = require("jquery")(window);
+ // See ticket #14549 for more info.
+ module.exports = global.document ?
+ factory( global, true ) :
+ function( w ) {
+ if ( !w.document ) {
+ throw new Error( "jQuery requires a window with a document" );
+ }
+ return factory( w );
+ };
+ } else {
+ factory( global );
+ }
+
+// Pass this if window is not defined yet
+}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
+
+// Support: Firefox 18+
+// Can't be in strict mode, several libs including ASP.NET trace
+// the stack via arguments.caller.callee and Firefox dies if
+// you try to trace through "use strict" call chains. (#13335)
+//"use strict";
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/jquery.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/jquery.js
new file mode 100644
index 0000000..d3857e9
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/jquery.js
@@ -0,0 +1,37 @@
+define([
+ "./core",
+ "./selector",
+ "./traversing",
+ "./callbacks",
+ "./deferred",
+ "./core/ready",
+ "./data",
+ "./queue",
+ "./queue/delay",
+ "./attributes",
+ "./event",
+ "./event/alias",
+ "./manipulation",
+ "./manipulation/_evalUrl",
+ "./wrap",
+ "./css",
+ "./css/hiddenVisibleSelectors",
+ "./serialize",
+ "./ajax",
+ "./ajax/xhr",
+ "./ajax/script",
+ "./ajax/jsonp",
+ "./ajax/load",
+ "./event/ajax",
+ "./effects",
+ "./effects/animatedSelector",
+ "./offset",
+ "./dimensions",
+ "./deprecated",
+ "./exports/amd",
+ "./exports/global"
+], function( jQuery ) {
+
+return jQuery;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/manipulation.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/manipulation.js
new file mode 100644
index 0000000..c627962
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/manipulation.js
@@ -0,0 +1,580 @@
+define([
+ "./core",
+ "./var/concat",
+ "./var/push",
+ "./core/access",
+ "./manipulation/var/rcheckableType",
+ "./manipulation/support",
+ "./data/var/data_priv",
+ "./data/var/data_user",
+
+ "./core/init",
+ "./data/accepts",
+ "./traversing",
+ "./selector",
+ "./event"
+], function( jQuery, concat, push, access, rcheckableType, support, data_priv, data_user ) {
+
+var
+ rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
+ rtagName = /<([\w:]+)/,
+ rhtml = /<|&#?\w+;/,
+ rnoInnerhtml = /<(?:script|style|link)/i,
+ // checked="checked" or checked
+ rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
+ rscriptType = /^$|\/(?:java|ecma)script/i,
+ rscriptTypeMasked = /^true\/(.*)/,
+ rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
+
+ // We have to close these tags to support XHTML (#13200)
+ wrapMap = {
+
+ // Support: IE9
+ 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, "", "" ]
+ };
+
+// Support: IE9
+wrapMap.optgroup = wrapMap.option;
+
+wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+wrapMap.th = wrapMap.td;
+
+// Support: 1.x compatibility
+// Manipulating tables requires a tbody
+function manipulationTarget( elem, content ) {
+ return jQuery.nodeName( elem, "table" ) &&
+ jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
+
+ elem.getElementsByTagName("tbody")[0] ||
+ elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
+ elem;
+}
+
+// Replace/restore the type attribute of script elements for safe DOM manipulation
+function disableScript( elem ) {
+ elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
+ return elem;
+}
+function restoreScript( elem ) {
+ var match = rscriptTypeMasked.exec( elem.type );
+
+ if ( match ) {
+ elem.type = match[ 1 ];
+ } else {
+ elem.removeAttribute("type");
+ }
+
+ return elem;
+}
+
+// Mark scripts as having already been evaluated
+function setGlobalEval( elems, refElements ) {
+ var i = 0,
+ l = elems.length;
+
+ for ( ; i < l; i++ ) {
+ data_priv.set(
+ elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
+ );
+ }
+}
+
+function cloneCopyEvent( src, dest ) {
+ var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
+
+ if ( dest.nodeType !== 1 ) {
+ return;
+ }
+
+ // 1. Copy private data: events, handlers, etc.
+ if ( data_priv.hasData( src ) ) {
+ pdataOld = data_priv.access( src );
+ pdataCur = data_priv.set( dest, pdataOld );
+ events = pdataOld.events;
+
+ if ( events ) {
+ delete pdataCur.handle;
+ pdataCur.events = {};
+
+ for ( type in events ) {
+ for ( i = 0, l = events[ type ].length; i < l; i++ ) {
+ jQuery.event.add( dest, type, events[ type ][ i ] );
+ }
+ }
+ }
+ }
+
+ // 2. Copy user data
+ if ( data_user.hasData( src ) ) {
+ udataOld = data_user.access( src );
+ udataCur = jQuery.extend( {}, udataOld );
+
+ data_user.set( dest, udataCur );
+ }
+}
+
+function getAll( context, tag ) {
+ var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
+ context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
+ [];
+
+ return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
+ jQuery.merge( [ context ], ret ) :
+ ret;
+}
+
+// Fix IE bugs, see support tests
+function fixInput( src, dest ) {
+ var nodeName = dest.nodeName.toLowerCase();
+
+ // Fails to persist the checked state of a cloned checkbox or radio button.
+ if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
+ dest.checked = src.checked;
+
+ // Fails to return the selected option to the default selected state when cloning options
+ } else if ( nodeName === "input" || nodeName === "textarea" ) {
+ dest.defaultValue = src.defaultValue;
+ }
+}
+
+jQuery.extend({
+ clone: function( elem, dataAndEvents, deepDataAndEvents ) {
+ var i, l, srcElements, destElements,
+ clone = elem.cloneNode( true ),
+ inPage = jQuery.contains( elem.ownerDocument, elem );
+
+ // Fix IE cloning issues
+ if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
+ !jQuery.isXMLDoc( elem ) ) {
+
+ // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
+ destElements = getAll( clone );
+ srcElements = getAll( elem );
+
+ for ( i = 0, l = srcElements.length; i < l; i++ ) {
+ fixInput( srcElements[ i ], destElements[ i ] );
+ }
+ }
+
+ // Copy the events from the original to the clone
+ if ( dataAndEvents ) {
+ if ( deepDataAndEvents ) {
+ srcElements = srcElements || getAll( elem );
+ destElements = destElements || getAll( clone );
+
+ for ( i = 0, l = srcElements.length; i < l; i++ ) {
+ cloneCopyEvent( srcElements[ i ], destElements[ i ] );
+ }
+ } else {
+ cloneCopyEvent( elem, clone );
+ }
+ }
+
+ // Preserve script evaluation history
+ destElements = getAll( clone, "script" );
+ if ( destElements.length > 0 ) {
+ setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
+ }
+
+ // Return the cloned set
+ return clone;
+ },
+
+ buildFragment: function( elems, context, scripts, selection ) {
+ var elem, tmp, tag, wrap, contains, j,
+ fragment = context.createDocumentFragment(),
+ nodes = [],
+ i = 0,
+ l = elems.length;
+
+ for ( ; i < l; i++ ) {
+ elem = elems[ i ];
+
+ if ( elem || elem === 0 ) {
+
+ // Add nodes directly
+ if ( jQuery.type( elem ) === "object" ) {
+ // Support: QtWebKit, PhantomJS
+ // push.apply(_, arraylike) throws on ancient WebKit
+ jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
+
+ // Convert non-html into a text node
+ } else if ( !rhtml.test( elem ) ) {
+ nodes.push( context.createTextNode( elem ) );
+
+ // Convert html into DOM nodes
+ } else {
+ tmp = tmp || fragment.appendChild( context.createElement("div") );
+
+ // Deserialize a standard representation
+ tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
+ wrap = wrapMap[ tag ] || wrapMap._default;
+ tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
+
+ // Descend through wrappers to the right content
+ j = wrap[ 0 ];
+ while ( j-- ) {
+ tmp = tmp.lastChild;
+ }
+
+ // Support: QtWebKit, PhantomJS
+ // push.apply(_, arraylike) throws on ancient WebKit
+ jQuery.merge( nodes, tmp.childNodes );
+
+ // Remember the top-level container
+ tmp = fragment.firstChild;
+
+ // Ensure the created nodes are orphaned (#12392)
+ tmp.textContent = "";
+ }
+ }
+ }
+
+ // Remove wrapper from fragment
+ fragment.textContent = "";
+
+ i = 0;
+ while ( (elem = nodes[ i++ ]) ) {
+
+ // #4087 - If origin and destination elements are the same, and this is
+ // that element, do not do anything
+ if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
+ continue;
+ }
+
+ contains = jQuery.contains( elem.ownerDocument, elem );
+
+ // Append to fragment
+ tmp = getAll( fragment.appendChild( elem ), "script" );
+
+ // Preserve script evaluation history
+ if ( contains ) {
+ setGlobalEval( tmp );
+ }
+
+ // Capture executables
+ if ( scripts ) {
+ j = 0;
+ while ( (elem = tmp[ j++ ]) ) {
+ if ( rscriptType.test( elem.type || "" ) ) {
+ scripts.push( elem );
+ }
+ }
+ }
+ }
+
+ return fragment;
+ },
+
+ cleanData: function( elems ) {
+ var data, elem, type, key,
+ special = jQuery.event.special,
+ i = 0;
+
+ for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
+ if ( jQuery.acceptData( elem ) ) {
+ key = elem[ data_priv.expando ];
+
+ if ( key && (data = data_priv.cache[ key ]) ) {
+ if ( data.events ) {
+ for ( type in data.events ) {
+ if ( special[ type ] ) {
+ jQuery.event.remove( elem, type );
+
+ // This is a shortcut to avoid jQuery.event.remove's overhead
+ } else {
+ jQuery.removeEvent( elem, type, data.handle );
+ }
+ }
+ }
+ if ( data_priv.cache[ key ] ) {
+ // Discard any remaining `private` data
+ delete data_priv.cache[ key ];
+ }
+ }
+ }
+ // Discard any remaining `user` data
+ delete data_user.cache[ elem[ data_user.expando ] ];
+ }
+ }
+});
+
+jQuery.fn.extend({
+ text: function( value ) {
+ return access( this, function( value ) {
+ return value === undefined ?
+ jQuery.text( this ) :
+ this.empty().each(function() {
+ if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+ this.textContent = value;
+ }
+ });
+ }, null, value, arguments.length );
+ },
+
+ append: function() {
+ return this.domManip( arguments, function( elem ) {
+ if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+ var target = manipulationTarget( this, elem );
+ target.appendChild( elem );
+ }
+ });
+ },
+
+ prepend: function() {
+ return this.domManip( arguments, function( elem ) {
+ if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+ var target = manipulationTarget( this, elem );
+ target.insertBefore( elem, target.firstChild );
+ }
+ });
+ },
+
+ before: function() {
+ return this.domManip( arguments, function( elem ) {
+ if ( this.parentNode ) {
+ this.parentNode.insertBefore( elem, this );
+ }
+ });
+ },
+
+ after: function() {
+ return this.domManip( arguments, function( elem ) {
+ if ( this.parentNode ) {
+ this.parentNode.insertBefore( elem, this.nextSibling );
+ }
+ });
+ },
+
+ remove: function( selector, keepData /* Internal Use Only */ ) {
+ var elem,
+ elems = selector ? jQuery.filter( selector, this ) : this,
+ i = 0;
+
+ for ( ; (elem = elems[i]) != null; i++ ) {
+ if ( !keepData && elem.nodeType === 1 ) {
+ jQuery.cleanData( getAll( elem ) );
+ }
+
+ if ( elem.parentNode ) {
+ if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
+ setGlobalEval( getAll( elem, "script" ) );
+ }
+ elem.parentNode.removeChild( elem );
+ }
+ }
+
+ return this;
+ },
+
+ empty: function() {
+ var elem,
+ i = 0;
+
+ for ( ; (elem = this[i]) != null; i++ ) {
+ if ( elem.nodeType === 1 ) {
+
+ // Prevent memory leaks
+ jQuery.cleanData( getAll( elem, false ) );
+
+ // Remove any remaining nodes
+ elem.textContent = "";
+ }
+ }
+
+ return this;
+ },
+
+ clone: function( dataAndEvents, deepDataAndEvents ) {
+ dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
+ deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
+
+ return this.map(function() {
+ return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
+ });
+ },
+
+ html: function( value ) {
+ return access( this, function( value ) {
+ var elem = this[ 0 ] || {},
+ i = 0,
+ l = this.length;
+
+ if ( value === undefined && elem.nodeType === 1 ) {
+ return elem.innerHTML;
+ }
+
+ // See if we can take a shortcut and just use innerHTML
+ if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
+ !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
+
+ value = value.replace( rxhtmlTag, "<$1></$2>" );
+
+ try {
+ for ( ; i < l; i++ ) {
+ elem = this[ i ] || {};
+
+ // Remove element nodes and prevent memory leaks
+ if ( elem.nodeType === 1 ) {
+ jQuery.cleanData( getAll( elem, false ) );
+ elem.innerHTML = value;
+ }
+ }
+
+ elem = 0;
+
+ // If using innerHTML throws an exception, use the fallback method
+ } catch( e ) {}
+ }
+
+ if ( elem ) {
+ this.empty().append( value );
+ }
+ }, null, value, arguments.length );
+ },
+
+ replaceWith: function() {
+ var arg = arguments[ 0 ];
+
+ // Make the changes, replacing each context element with the new content
+ this.domManip( arguments, function( elem ) {
+ arg = this.parentNode;
+
+ jQuery.cleanData( getAll( this ) );
+
+ if ( arg ) {
+ arg.replaceChild( elem, this );
+ }
+ });
+
+ // Force removal if there was no new content (e.g., from empty arguments)
+ return arg && (arg.length || arg.nodeType) ? this : this.remove();
+ },
+
+ detach: function( selector ) {
+ return this.remove( selector, true );
+ },
+
+ domManip: function( args, callback ) {
+
+ // Flatten any nested arrays
+ args = concat.apply( [], args );
+
+ var fragment, first, scripts, hasScripts, node, doc,
+ i = 0,
+ l = this.length,
+ set = this,
+ iNoClone = l - 1,
+ value = args[ 0 ],
+ isFunction = jQuery.isFunction( value );
+
+ // We can't cloneNode fragments that contain checked, in WebKit
+ if ( isFunction ||
+ ( l > 1 && typeof value === "string" &&
+ !support.checkClone && rchecked.test( value ) ) ) {
+ return this.each(function( index ) {
+ var self = set.eq( index );
+ if ( isFunction ) {
+ args[ 0 ] = value.call( this, index, self.html() );
+ }
+ self.domManip( args, callback );
+ });
+ }
+
+ if ( l ) {
+ fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
+ first = fragment.firstChild;
+
+ if ( fragment.childNodes.length === 1 ) {
+ fragment = first;
+ }
+
+ if ( first ) {
+ scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
+ hasScripts = scripts.length;
+
+ // Use the original fragment for the last item instead of the first because it can end up
+ // being emptied incorrectly in certain situations (#8070).
+ for ( ; i < l; i++ ) {
+ node = fragment;
+
+ if ( i !== iNoClone ) {
+ node = jQuery.clone( node, true, true );
+
+ // Keep references to cloned scripts for later restoration
+ if ( hasScripts ) {
+ // Support: QtWebKit
+ // jQuery.merge because push.apply(_, arraylike) throws
+ jQuery.merge( scripts, getAll( node, "script" ) );
+ }
+ }
+
+ callback.call( this[ i ], node, i );
+ }
+
+ if ( hasScripts ) {
+ doc = scripts[ scripts.length - 1 ].ownerDocument;
+
+ // Reenable scripts
+ jQuery.map( scripts, restoreScript );
+
+ // Evaluate executable scripts on first document insertion
+ for ( i = 0; i < hasScripts; i++ ) {
+ node = scripts[ i ];
+ if ( rscriptType.test( node.type || "" ) &&
+ !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
+
+ if ( node.src ) {
+ // Optional AJAX dependency, but won't run scripts if not present
+ if ( jQuery._evalUrl ) {
+ jQuery._evalUrl( node.src );
+ }
+ } else {
+ jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return this;
+ }
+});
+
+jQuery.each({
+ appendTo: "append",
+ prependTo: "prepend",
+ insertBefore: "before",
+ insertAfter: "after",
+ replaceAll: "replaceWith"
+}, function( name, original ) {
+ jQuery.fn[ name ] = function( selector ) {
+ var elems,
+ ret = [],
+ insert = jQuery( selector ),
+ last = insert.length - 1,
+ i = 0;
+
+ for ( ; i <= last; i++ ) {
+ elems = i === last ? this : this.clone( true );
+ jQuery( insert[ i ] )[ original ]( elems );
+
+ // Support: QtWebKit
+ // .get() because push.apply(_, arraylike) throws
+ push.apply( ret, elems.get() );
+ }
+
+ return this.pushStack( ret );
+ };
+});
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/manipulation/_evalUrl.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/manipulation/_evalUrl.js
new file mode 100644
index 0000000..6704749
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/manipulation/_evalUrl.js
@@ -0,0 +1,18 @@
+define([
+ "../ajax"
+], function( jQuery ) {
+
+jQuery._evalUrl = function( url ) {
+ return jQuery.ajax({
+ url: url,
+ type: "GET",
+ dataType: "script",
+ async: false,
+ global: false,
+ "throws": true
+ });
+};
+
+return jQuery._evalUrl;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/manipulation/support.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/manipulation/support.js
new file mode 100644
index 0000000..822a014
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/manipulation/support.js
@@ -0,0 +1,32 @@
+define([
+ "../var/support"
+], function( support ) {
+
+(function() {
+ var fragment = document.createDocumentFragment(),
+ div = fragment.appendChild( document.createElement( "div" ) ),
+ input = document.createElement( "input" );
+
+ // Support: Safari<=5.1
+ // Check state lost if the name is set (#11217)
+ // Support: Windows Web Apps (WWA)
+ // `name` and `type` must use .setAttribute for WWA (#14901)
+ input.setAttribute( "type", "radio" );
+ input.setAttribute( "checked", "checked" );
+ input.setAttribute( "name", "t" );
+
+ div.appendChild( input );
+
+ // Support: Safari<=5.1, Android<4.2
+ // Older WebKit doesn't clone checked state correctly in fragments
+ support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
+
+ // Support: IE<=11+
+ // Make sure textarea (and checkbox) defaultValue is properly cloned
+ div.innerHTML = "<textarea>x</textarea>";
+ support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
+})();
+
+return support;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/manipulation/var/rcheckableType.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/manipulation/var/rcheckableType.js
new file mode 100644
index 0000000..c27a15d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/manipulation/var/rcheckableType.js
@@ -0,0 +1,3 @@
+define(function() {
+ return (/^(?:checkbox|radio)$/i);
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/offset.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/offset.js
new file mode 100644
index 0000000..4c34fd0
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/offset.js
@@ -0,0 +1,207 @@
+define([
+ "./core",
+ "./var/strundefined",
+ "./core/access",
+ "./css/var/rnumnonpx",
+ "./css/curCSS",
+ "./css/addGetHookIf",
+ "./css/support",
+
+ "./core/init",
+ "./css",
+ "./selector" // contains
+], function( jQuery, strundefined, access, rnumnonpx, curCSS, addGetHookIf, support ) {
+
+var docElem = window.document.documentElement;
+
+/**
+ * Gets a window from an element
+ */
+function getWindow( elem ) {
+ return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
+}
+
+jQuery.offset = {
+ setOffset: function( elem, options, i ) {
+ var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
+ position = jQuery.css( elem, "position" ),
+ curElem = jQuery( elem ),
+ props = {};
+
+ // Set position first, in-case top/left are set even on static elem
+ if ( position === "static" ) {
+ elem.style.position = "relative";
+ }
+
+ curOffset = curElem.offset();
+ curCSSTop = jQuery.css( elem, "top" );
+ curCSSLeft = jQuery.css( elem, "left" );
+ calculatePosition = ( position === "absolute" || position === "fixed" ) &&
+ ( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
+
+ // Need to be able to calculate position if either
+ // top or left is auto and position is either absolute or fixed
+ if ( calculatePosition ) {
+ curPosition = curElem.position();
+ curTop = curPosition.top;
+ curLeft = curPosition.left;
+
+ } else {
+ curTop = parseFloat( curCSSTop ) || 0;
+ curLeft = parseFloat( curCSSLeft ) || 0;
+ }
+
+ if ( jQuery.isFunction( options ) ) {
+ options = options.call( elem, i, curOffset );
+ }
+
+ if ( options.top != null ) {
+ props.top = ( options.top - curOffset.top ) + curTop;
+ }
+ if ( options.left != null ) {
+ props.left = ( options.left - curOffset.left ) + curLeft;
+ }
+
+ if ( "using" in options ) {
+ options.using.call( elem, props );
+
+ } else {
+ curElem.css( props );
+ }
+ }
+};
+
+jQuery.fn.extend({
+ offset: function( options ) {
+ if ( arguments.length ) {
+ return options === undefined ?
+ this :
+ this.each(function( i ) {
+ jQuery.offset.setOffset( this, options, i );
+ });
+ }
+
+ var docElem, win,
+ elem = this[ 0 ],
+ box = { top: 0, left: 0 },
+ doc = elem && elem.ownerDocument;
+
+ if ( !doc ) {
+ return;
+ }
+
+ docElem = doc.documentElement;
+
+ // Make sure it's not a disconnected DOM node
+ if ( !jQuery.contains( docElem, elem ) ) {
+ return box;
+ }
+
+ // Support: BlackBerry 5, iOS 3 (original iPhone)
+ // If we don't have gBCR, just use 0,0 rather than error
+ if ( typeof elem.getBoundingClientRect !== strundefined ) {
+ box = elem.getBoundingClientRect();
+ }
+ win = getWindow( doc );
+ return {
+ top: box.top + win.pageYOffset - docElem.clientTop,
+ left: box.left + win.pageXOffset - docElem.clientLeft
+ };
+ },
+
+ position: function() {
+ if ( !this[ 0 ] ) {
+ return;
+ }
+
+ var offsetParent, offset,
+ elem = this[ 0 ],
+ parentOffset = { top: 0, left: 0 };
+
+ // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
+ if ( jQuery.css( elem, "position" ) === "fixed" ) {
+ // Assume getBoundingClientRect is there when computed position is fixed
+ offset = elem.getBoundingClientRect();
+
+ } else {
+ // Get *real* offsetParent
+ offsetParent = this.offsetParent();
+
+ // Get correct offsets
+ offset = this.offset();
+ if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
+ parentOffset = offsetParent.offset();
+ }
+
+ // Add offsetParent borders
+ parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
+ parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
+ }
+
+ // Subtract parent offsets and element margins
+ return {
+ top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
+ left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
+ };
+ },
+
+ offsetParent: function() {
+ return this.map(function() {
+ var offsetParent = this.offsetParent || docElem;
+
+ while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
+ offsetParent = offsetParent.offsetParent;
+ }
+
+ return offsetParent || docElem;
+ });
+ }
+});
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
+ var top = "pageYOffset" === prop;
+
+ jQuery.fn[ method ] = function( val ) {
+ return access( this, function( elem, method, val ) {
+ var win = getWindow( elem );
+
+ if ( val === undefined ) {
+ return win ? win[ prop ] : elem[ method ];
+ }
+
+ if ( win ) {
+ win.scrollTo(
+ !top ? val : window.pageXOffset,
+ top ? val : window.pageYOffset
+ );
+
+ } else {
+ elem[ method ] = val;
+ }
+ }, method, val, arguments.length, null );
+ };
+});
+
+// Support: Safari<7+, Chrome<37+
+// Add the top/left cssHooks using jQuery.fn.position
+// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
+// Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280
+// getComputedStyle returns percent when specified for top/left/bottom/right;
+// rather than make the css module depend on the offset module, just check for it here
+jQuery.each( [ "top", "left" ], function( i, prop ) {
+ jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
+ function( elem, computed ) {
+ if ( computed ) {
+ computed = curCSS( elem, prop );
+ // If curCSS returns percentage, fallback to offset
+ return rnumnonpx.test( computed ) ?
+ jQuery( elem ).position()[ prop ] + "px" :
+ computed;
+ }
+ }
+ );
+});
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/outro.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/outro.js
new file mode 100644
index 0000000..be4600a
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/outro.js
@@ -0,0 +1 @@
+}));
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/queue.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/queue.js
new file mode 100644
index 0000000..199c56d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/queue.js
@@ -0,0 +1,142 @@
+define([
+ "./core",
+ "./data/var/data_priv",
+ "./deferred",
+ "./callbacks"
+], function( jQuery, data_priv ) {
+
+jQuery.extend({
+ queue: function( elem, type, data ) {
+ var queue;
+
+ if ( elem ) {
+ type = ( type || "fx" ) + "queue";
+ queue = data_priv.get( elem, type );
+
+ // Speed up dequeue by getting out quickly if this is just a lookup
+ if ( data ) {
+ if ( !queue || jQuery.isArray( data ) ) {
+ queue = data_priv.access( elem, type, jQuery.makeArray(data) );
+ } else {
+ queue.push( data );
+ }
+ }
+ return queue || [];
+ }
+ },
+
+ dequeue: function( elem, type ) {
+ type = type || "fx";
+
+ var queue = jQuery.queue( elem, type ),
+ startLength = queue.length,
+ fn = queue.shift(),
+ hooks = jQuery._queueHooks( elem, type ),
+ next = function() {
+ jQuery.dequeue( elem, type );
+ };
+
+ // If the fx queue is dequeued, always remove the progress sentinel
+ if ( fn === "inprogress" ) {
+ fn = queue.shift();
+ startLength--;
+ }
+
+ if ( fn ) {
+
+ // Add a progress sentinel to prevent the fx queue from being
+ // automatically dequeued
+ if ( type === "fx" ) {
+ queue.unshift( "inprogress" );
+ }
+
+ // Clear up the last queue stop function
+ delete hooks.stop;
+ fn.call( elem, next, hooks );
+ }
+
+ if ( !startLength && hooks ) {
+ hooks.empty.fire();
+ }
+ },
+
+ // Not public - generate a queueHooks object, or return the current one
+ _queueHooks: function( elem, type ) {
+ var key = type + "queueHooks";
+ return data_priv.get( elem, key ) || data_priv.access( elem, key, {
+ empty: jQuery.Callbacks("once memory").add(function() {
+ data_priv.remove( elem, [ type + "queue", key ] );
+ })
+ });
+ }
+});
+
+jQuery.fn.extend({
+ queue: function( type, data ) {
+ var setter = 2;
+
+ if ( typeof type !== "string" ) {
+ data = type;
+ type = "fx";
+ setter--;
+ }
+
+ if ( arguments.length < setter ) {
+ return jQuery.queue( this[0], type );
+ }
+
+ return data === undefined ?
+ this :
+ this.each(function() {
+ var queue = jQuery.queue( this, type, data );
+
+ // Ensure a hooks for this queue
+ jQuery._queueHooks( this, type );
+
+ if ( type === "fx" && queue[0] !== "inprogress" ) {
+ jQuery.dequeue( this, type );
+ }
+ });
+ },
+ dequeue: function( type ) {
+ return this.each(function() {
+ jQuery.dequeue( this, type );
+ });
+ },
+ clearQueue: function( type ) {
+ return this.queue( type || "fx", [] );
+ },
+ // Get a promise resolved when queues of a certain type
+ // are emptied (fx is the type by default)
+ promise: function( type, obj ) {
+ var tmp,
+ count = 1,
+ defer = jQuery.Deferred(),
+ elements = this,
+ i = this.length,
+ resolve = function() {
+ if ( !( --count ) ) {
+ defer.resolveWith( elements, [ elements ] );
+ }
+ };
+
+ if ( typeof type !== "string" ) {
+ obj = type;
+ type = undefined;
+ }
+ type = type || "fx";
+
+ while ( i-- ) {
+ tmp = data_priv.get( elements[ i ], type + "queueHooks" );
+ if ( tmp && tmp.empty ) {
+ count++;
+ tmp.empty.add( resolve );
+ }
+ }
+ resolve();
+ return defer.promise( obj );
+ }
+});
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/queue/delay.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/queue/delay.js
new file mode 100644
index 0000000..4b4498c
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/queue/delay.js
@@ -0,0 +1,22 @@
+define([
+ "../core",
+ "../queue",
+ "../effects" // Delay is optional because of this dependency
+], function( jQuery ) {
+
+// Based off of the plugin by Clint Helfers, with permission.
+// http://blindsignals.com/index.php/2009/07/jquery-delay/
+jQuery.fn.delay = function( time, type ) {
+ time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
+ type = type || "fx";
+
+ return this.queue( type, function( next, hooks ) {
+ var timeout = setTimeout( next, time );
+ hooks.stop = function() {
+ clearTimeout( timeout );
+ };
+ });
+};
+
+return jQuery.fn.delay;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/selector-native.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/selector-native.js
new file mode 100644
index 0000000..d8163c2
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/selector-native.js
@@ -0,0 +1,172 @@
+define([
+ "./core"
+], function( jQuery ) {
+
+/*
+ * Optional (non-Sizzle) selector module for custom builds.
+ *
+ * Note that this DOES NOT SUPPORT many documented jQuery
+ * features in exchange for its smaller size:
+ *
+ * Attribute not equal selector
+ * Positional selectors (:first; :eq(n); :odd; etc.)
+ * Type selectors (:input; :checkbox; :button; etc.)
+ * State-based selectors (:animated; :visible; :hidden; etc.)
+ * :has(selector)
+ * :not(complex selector)
+ * custom selectors via Sizzle extensions
+ * Leading combinators (e.g., $collection.find("> *"))
+ * Reliable functionality on XML fragments
+ * Requiring all parts of a selector to match elements under context
+ * (e.g., $div.find("div > *") now matches children of $div)
+ * Matching against non-elements
+ * Reliable sorting of disconnected nodes
+ * querySelectorAll bug fixes (e.g., unreliable :focus on WebKit)
+ *
+ * If any of these are unacceptable tradeoffs, either use Sizzle or
+ * customize this stub for the project's specific needs.
+ */
+
+var docElem = window.document.documentElement,
+ selector_hasDuplicate,
+ matches = docElem.matches ||
+ docElem.webkitMatchesSelector ||
+ docElem.mozMatchesSelector ||
+ docElem.oMatchesSelector ||
+ docElem.msMatchesSelector,
+ selector_sortOrder = function( a, b ) {
+ // Flag for duplicate removal
+ if ( a === b ) {
+ selector_hasDuplicate = true;
+ return 0;
+ }
+
+ var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
+
+ if ( compare ) {
+ // Disconnected nodes
+ if ( compare & 1 ) {
+
+ // Choose the first element that is related to our document
+ if ( a === document || jQuery.contains(document, a) ) {
+ return -1;
+ }
+ if ( b === document || jQuery.contains(document, b) ) {
+ return 1;
+ }
+
+ // Maintain original order
+ return 0;
+ }
+
+ return compare & 4 ? -1 : 1;
+ }
+
+ // Not directly comparable, sort on existence of method
+ return a.compareDocumentPosition ? -1 : 1;
+ };
+
+jQuery.extend({
+ find: function( selector, context, results, seed ) {
+ var elem, nodeType,
+ i = 0;
+
+ results = results || [];
+ context = context || document;
+
+ // Same basic safeguard as Sizzle
+ if ( !selector || typeof selector !== "string" ) {
+ return results;
+ }
+
+ // Early return if context is not an element or document
+ if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
+ return [];
+ }
+
+ if ( seed ) {
+ while ( (elem = seed[i++]) ) {
+ if ( jQuery.find.matchesSelector(elem, selector) ) {
+ results.push( elem );
+ }
+ }
+ } else {
+ jQuery.merge( results, context.querySelectorAll(selector) );
+ }
+
+ return results;
+ },
+ unique: function( results ) {
+ var elem,
+ duplicates = [],
+ i = 0,
+ j = 0;
+
+ selector_hasDuplicate = false;
+ results.sort( selector_sortOrder );
+
+ if ( selector_hasDuplicate ) {
+ while ( (elem = results[i++]) ) {
+ if ( elem === results[ i ] ) {
+ j = duplicates.push( i );
+ }
+ }
+ while ( j-- ) {
+ results.splice( duplicates[ j ], 1 );
+ }
+ }
+
+ return results;
+ },
+ text: function( elem ) {
+ var node,
+ ret = "",
+ i = 0,
+ nodeType = elem.nodeType;
+
+ if ( !nodeType ) {
+ // If no nodeType, this is expected to be an array
+ while ( (node = elem[i++]) ) {
+ // Do not traverse comment nodes
+ ret += jQuery.text( node );
+ }
+ } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
+ // Use textContent for elements
+ return elem.textContent;
+ } else if ( nodeType === 3 || nodeType === 4 ) {
+ return elem.nodeValue;
+ }
+ // Do not include comment or processing instruction nodes
+
+ return ret;
+ },
+ contains: function( a, b ) {
+ var adown = a.nodeType === 9 ? a.documentElement : a,
+ bup = b && b.parentNode;
+ return a === bup || !!( bup && bup.nodeType === 1 && adown.contains(bup) );
+ },
+ isXMLDoc: function( elem ) {
+ return (elem.ownerDocument || elem).documentElement.nodeName !== "HTML";
+ },
+ expr: {
+ attrHandle: {},
+ match: {
+ bool: /^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i,
+ needsContext: /^[\x20\t\r\n\f]*[>+~]/
+ }
+ }
+});
+
+jQuery.extend( jQuery.find, {
+ matches: function( expr, elements ) {
+ return jQuery.find( expr, null, null, elements );
+ },
+ matchesSelector: function( elem, expr ) {
+ return matches.call( elem, expr );
+ },
+ attr: function( elem, name ) {
+ return elem.getAttribute( name );
+ }
+});
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/selector-sizzle.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/selector-sizzle.js
new file mode 100644
index 0000000..7d3926b
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/selector-sizzle.js
@@ -0,0 +1,14 @@
+define([
+ "./core",
+ "sizzle"
+], function( jQuery, Sizzle ) {
+
+jQuery.find = Sizzle;
+jQuery.expr = Sizzle.selectors;
+jQuery.expr[":"] = jQuery.expr.pseudos;
+jQuery.unique = Sizzle.uniqueSort;
+jQuery.text = Sizzle.getText;
+jQuery.isXMLDoc = Sizzle.isXML;
+jQuery.contains = Sizzle.contains;
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/selector.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/selector.js
new file mode 100644
index 0000000..01e9733
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/selector.js
@@ -0,0 +1 @@
+define([ "./selector-sizzle" ]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/serialize.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/serialize.js
new file mode 100644
index 0000000..0d6dfec
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/serialize.js
@@ -0,0 +1,111 @@
+define([
+ "./core",
+ "./manipulation/var/rcheckableType",
+ "./core/init",
+ "./traversing", // filter
+ "./attributes/prop"
+], function( jQuery, rcheckableType ) {
+
+var r20 = /%20/g,
+ rbracket = /\[\]$/,
+ rCRLF = /\r?\n/g,
+ rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
+ rsubmittable = /^(?:input|select|textarea|keygen)/i;
+
+function buildParams( prefix, obj, traditional, add ) {
+ var name;
+
+ if ( jQuery.isArray( obj ) ) {
+ // Serialize array item.
+ jQuery.each( obj, function( i, v ) {
+ if ( traditional || rbracket.test( prefix ) ) {
+ // Treat each array item as a scalar.
+ add( prefix, v );
+
+ } else {
+ // Item is non-scalar (array or object), encode its numeric index.
+ buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
+ }
+ });
+
+ } else if ( !traditional && jQuery.type( obj ) === "object" ) {
+ // Serialize object item.
+ for ( name in obj ) {
+ buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
+ }
+
+ } else {
+ // Serialize scalar item.
+ add( prefix, obj );
+ }
+}
+
+// Serialize an array of form elements or a set of
+// key/values into a query string
+jQuery.param = function( a, traditional ) {
+ var prefix,
+ s = [],
+ add = function( key, value ) {
+ // If value is a function, invoke it and return its value
+ value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
+ s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
+ };
+
+ // Set traditional to true for jQuery <= 1.3.2 behavior.
+ if ( traditional === undefined ) {
+ traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
+ }
+
+ // If an array was passed in, assume that it is an array of form elements.
+ if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
+ // Serialize the form elements
+ jQuery.each( a, function() {
+ add( this.name, this.value );
+ });
+
+ } else {
+ // If traditional, encode the "old" way (the way 1.3.2 or older
+ // did it), otherwise encode params recursively.
+ for ( prefix in a ) {
+ buildParams( prefix, a[ prefix ], traditional, add );
+ }
+ }
+
+ // Return the resulting serialization
+ return s.join( "&" ).replace( r20, "+" );
+};
+
+jQuery.fn.extend({
+ serialize: function() {
+ return jQuery.param( this.serializeArray() );
+ },
+ serializeArray: function() {
+ return this.map(function() {
+ // Can add propHook for "elements" to filter or add form elements
+ var elements = jQuery.prop( this, "elements" );
+ return elements ? jQuery.makeArray( elements ) : this;
+ })
+ .filter(function() {
+ var type = this.type;
+
+ // Use .is( ":disabled" ) so that fieldset[disabled] works
+ return this.name && !jQuery( this ).is( ":disabled" ) &&
+ rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
+ ( this.checked || !rcheckableType.test( type ) );
+ })
+ .map(function( i, elem ) {
+ var val = jQuery( this ).val();
+
+ return val == null ?
+ null :
+ jQuery.isArray( val ) ?
+ jQuery.map( val, function( val ) {
+ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+ }) :
+ { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+ }).get();
+ }
+});
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/traversing.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/traversing.js
new file mode 100644
index 0000000..d9ff0ae
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/traversing.js
@@ -0,0 +1,199 @@
+define([
+ "./core",
+ "./var/indexOf",
+ "./traversing/var/rneedsContext",
+ "./core/init",
+ "./traversing/findFilter",
+ "./selector"
+], function( jQuery, indexOf, rneedsContext ) {
+
+var rparentsprev = /^(?:parents|prev(?:Until|All))/,
+ // Methods guaranteed to produce a unique set when starting from a unique set
+ guaranteedUnique = {
+ children: true,
+ contents: true,
+ next: true,
+ prev: true
+ };
+
+jQuery.extend({
+ dir: function( elem, dir, until ) {
+ var matched = [],
+ truncate = until !== undefined;
+
+ while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
+ if ( elem.nodeType === 1 ) {
+ if ( truncate && jQuery( elem ).is( until ) ) {
+ break;
+ }
+ matched.push( elem );
+ }
+ }
+ return matched;
+ },
+
+ sibling: function( n, elem ) {
+ var matched = [];
+
+ for ( ; n; n = n.nextSibling ) {
+ if ( n.nodeType === 1 && n !== elem ) {
+ matched.push( n );
+ }
+ }
+
+ return matched;
+ }
+});
+
+jQuery.fn.extend({
+ has: function( target ) {
+ var targets = jQuery( target, this ),
+ l = targets.length;
+
+ return this.filter(function() {
+ var i = 0;
+ for ( ; i < l; i++ ) {
+ if ( jQuery.contains( this, targets[i] ) ) {
+ return true;
+ }
+ }
+ });
+ },
+
+ closest: function( selectors, context ) {
+ var cur,
+ i = 0,
+ l = this.length,
+ matched = [],
+ pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
+ jQuery( selectors, context || this.context ) :
+ 0;
+
+ for ( ; i < l; i++ ) {
+ for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
+ // Always skip document fragments
+ if ( cur.nodeType < 11 && (pos ?
+ pos.index(cur) > -1 :
+
+ // Don't pass non-elements to Sizzle
+ cur.nodeType === 1 &&
+ jQuery.find.matchesSelector(cur, selectors)) ) {
+
+ matched.push( cur );
+ break;
+ }
+ }
+ }
+
+ return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
+ },
+
+ // Determine the position of an element within the set
+ index: function( elem ) {
+
+ // No argument, return index in parent
+ if ( !elem ) {
+ return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
+ }
+
+ // Index in selector
+ if ( typeof elem === "string" ) {
+ return indexOf.call( jQuery( elem ), this[ 0 ] );
+ }
+
+ // Locate the position of the desired element
+ return indexOf.call( this,
+
+ // If it receives a jQuery object, the first element is used
+ elem.jquery ? elem[ 0 ] : elem
+ );
+ },
+
+ add: function( selector, context ) {
+ return this.pushStack(
+ jQuery.unique(
+ jQuery.merge( this.get(), jQuery( selector, context ) )
+ )
+ );
+ },
+
+ addBack: function( selector ) {
+ return this.add( selector == null ?
+ this.prevObject : this.prevObject.filter(selector)
+ );
+ }
+});
+
+function sibling( cur, dir ) {
+ while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}
+ return cur;
+}
+
+jQuery.each({
+ parent: function( elem ) {
+ var parent = elem.parentNode;
+ return parent && parent.nodeType !== 11 ? parent : null;
+ },
+ parents: function( elem ) {
+ return jQuery.dir( elem, "parentNode" );
+ },
+ parentsUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "parentNode", until );
+ },
+ next: function( elem ) {
+ return sibling( elem, "nextSibling" );
+ },
+ prev: function( elem ) {
+ return sibling( elem, "previousSibling" );
+ },
+ nextAll: function( elem ) {
+ return jQuery.dir( elem, "nextSibling" );
+ },
+ prevAll: function( elem ) {
+ return jQuery.dir( elem, "previousSibling" );
+ },
+ nextUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "nextSibling", until );
+ },
+ prevUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "previousSibling", until );
+ },
+ siblings: function( elem ) {
+ return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
+ },
+ children: function( elem ) {
+ return jQuery.sibling( elem.firstChild );
+ },
+ contents: function( elem ) {
+ return elem.contentDocument || jQuery.merge( [], elem.childNodes );
+ }
+}, function( name, fn ) {
+ jQuery.fn[ name ] = function( until, selector ) {
+ var matched = jQuery.map( this, fn, until );
+
+ if ( name.slice( -5 ) !== "Until" ) {
+ selector = until;
+ }
+
+ if ( selector && typeof selector === "string" ) {
+ matched = jQuery.filter( selector, matched );
+ }
+
+ if ( this.length > 1 ) {
+ // Remove duplicates
+ if ( !guaranteedUnique[ name ] ) {
+ jQuery.unique( matched );
+ }
+
+ // Reverse order for parents* and prev-derivatives
+ if ( rparentsprev.test( name ) ) {
+ matched.reverse();
+ }
+ }
+
+ return this.pushStack( matched );
+ };
+});
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/traversing/findFilter.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/traversing/findFilter.js
new file mode 100644
index 0000000..dd70a73
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/traversing/findFilter.js
@@ -0,0 +1,100 @@
+define([
+ "../core",
+ "../var/indexOf",
+ "./var/rneedsContext",
+ "../selector"
+], function( jQuery, indexOf, rneedsContext ) {
+
+var risSimple = /^.[^:#\[\.,]*$/;
+
+// Implement the identical functionality for filter and not
+function winnow( elements, qualifier, not ) {
+ if ( jQuery.isFunction( qualifier ) ) {
+ return jQuery.grep( elements, function( elem, i ) {
+ /* jshint -W018 */
+ return !!qualifier.call( elem, i, elem ) !== not;
+ });
+
+ }
+
+ if ( qualifier.nodeType ) {
+ return jQuery.grep( elements, function( elem ) {
+ return ( elem === qualifier ) !== not;
+ });
+
+ }
+
+ if ( typeof qualifier === "string" ) {
+ if ( risSimple.test( qualifier ) ) {
+ return jQuery.filter( qualifier, elements, not );
+ }
+
+ qualifier = jQuery.filter( qualifier, elements );
+ }
+
+ return jQuery.grep( elements, function( elem ) {
+ return ( indexOf.call( qualifier, elem ) >= 0 ) !== not;
+ });
+}
+
+jQuery.filter = function( expr, elems, not ) {
+ var elem = elems[ 0 ];
+
+ if ( not ) {
+ expr = ":not(" + expr + ")";
+ }
+
+ return elems.length === 1 && elem.nodeType === 1 ?
+ jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
+ jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
+ return elem.nodeType === 1;
+ }));
+};
+
+jQuery.fn.extend({
+ find: function( selector ) {
+ var i,
+ len = this.length,
+ ret = [],
+ self = this;
+
+ if ( typeof selector !== "string" ) {
+ return this.pushStack( jQuery( selector ).filter(function() {
+ for ( i = 0; i < len; i++ ) {
+ if ( jQuery.contains( self[ i ], this ) ) {
+ return true;
+ }
+ }
+ }) );
+ }
+
+ for ( i = 0; i < len; i++ ) {
+ jQuery.find( selector, self[ i ], ret );
+ }
+
+ // Needed because $( selector, context ) becomes $( context ).find( selector )
+ ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
+ ret.selector = this.selector ? this.selector + " " + selector : selector;
+ return ret;
+ },
+ filter: function( selector ) {
+ return this.pushStack( winnow(this, selector || [], false) );
+ },
+ not: function( selector ) {
+ return this.pushStack( winnow(this, selector || [], true) );
+ },
+ is: function( selector ) {
+ return !!winnow(
+ this,
+
+ // If this is a positional/relative selector, check membership in the returned set
+ // so $("p:first").is("p:last") won't return true for a doc with two "p".
+ typeof selector === "string" && rneedsContext.test( selector ) ?
+ jQuery( selector ) :
+ selector || [],
+ false
+ ).length;
+ }
+});
+
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/traversing/var/rneedsContext.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/traversing/var/rneedsContext.js
new file mode 100644
index 0000000..3d6ae40
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/traversing/var/rneedsContext.js
@@ -0,0 +1,6 @@
+define([
+ "../../core",
+ "../../selector"
+], function( jQuery ) {
+ return jQuery.expr.match.needsContext;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/arr.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/arr.js
new file mode 100644
index 0000000..b18fc9c
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/arr.js
@@ -0,0 +1,3 @@
+define(function() {
+ return [];
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/class2type.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/class2type.js
new file mode 100644
index 0000000..e674c3b
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/class2type.js
@@ -0,0 +1,4 @@
+define(function() {
+ // [[Class]] -> type pairs
+ return {};
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/concat.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/concat.js
new file mode 100644
index 0000000..7dcf77e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/concat.js
@@ -0,0 +1,5 @@
+define([
+ "./arr"
+], function( arr ) {
+ return arr.concat;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/hasOwn.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/hasOwn.js
new file mode 100644
index 0000000..32c002a
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/hasOwn.js
@@ -0,0 +1,5 @@
+define([
+ "./class2type"
+], function( class2type ) {
+ return class2type.hasOwnProperty;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/indexOf.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/indexOf.js
new file mode 100644
index 0000000..cdbe3c7
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/indexOf.js
@@ -0,0 +1,5 @@
+define([
+ "./arr"
+], function( arr ) {
+ return arr.indexOf;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/pnum.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/pnum.js
new file mode 100644
index 0000000..4070447
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/pnum.js
@@ -0,0 +1,3 @@
+define(function() {
+ return (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/push.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/push.js
new file mode 100644
index 0000000..ad6f0a1
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/push.js
@@ -0,0 +1,5 @@
+define([
+ "./arr"
+], function( arr ) {
+ return arr.push;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/rnotwhite.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/rnotwhite.js
new file mode 100644
index 0000000..7c69bec
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/rnotwhite.js
@@ -0,0 +1,3 @@
+define(function() {
+ return (/\S+/g);
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/slice.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/slice.js
new file mode 100644
index 0000000..614d46c
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/slice.js
@@ -0,0 +1,5 @@
+define([
+ "./arr"
+], function( arr ) {
+ return arr.slice;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/strundefined.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/strundefined.js
new file mode 100644
index 0000000..04e16b0
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/strundefined.js
@@ -0,0 +1,3 @@
+define(function() {
+ return typeof undefined;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/support.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/support.js
new file mode 100644
index 0000000..b25dbc7
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/support.js
@@ -0,0 +1,4 @@
+define(function() {
+ // All support tests are defined in their respective modules.
+ return {};
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/toString.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/toString.js
new file mode 100644
index 0000000..ca92d22
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/var/toString.js
@@ -0,0 +1,5 @@
+define([
+ "./class2type"
+], function( class2type ) {
+ return class2type.toString;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/jquery/src/wrap.js b/xos-apps/auto-scale/gui/src/vendor/jquery/src/wrap.js
new file mode 100644
index 0000000..4958251
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/jquery/src/wrap.js
@@ -0,0 +1,79 @@
+define([
+ "./core",
+ "./core/init",
+ "./manipulation", // clone
+ "./traversing" // parent, contents
+], function( jQuery ) {
+
+jQuery.fn.extend({
+ wrapAll: function( html ) {
+ var wrap;
+
+ if ( jQuery.isFunction( html ) ) {
+ return this.each(function( i ) {
+ jQuery( this ).wrapAll( html.call(this, i) );
+ });
+ }
+
+ if ( this[ 0 ] ) {
+
+ // The elements to wrap the target around
+ wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
+
+ if ( this[ 0 ].parentNode ) {
+ wrap.insertBefore( this[ 0 ] );
+ }
+
+ wrap.map(function() {
+ var elem = this;
+
+ while ( elem.firstElementChild ) {
+ elem = elem.firstElementChild;
+ }
+
+ return elem;
+ }).append( this );
+ }
+
+ return this;
+ },
+
+ wrapInner: function( html ) {
+ if ( jQuery.isFunction( html ) ) {
+ return this.each(function( i ) {
+ jQuery( this ).wrapInner( html.call(this, i) );
+ });
+ }
+
+ return this.each(function() {
+ var self = jQuery( this ),
+ contents = self.contents();
+
+ if ( contents.length ) {
+ contents.wrapAll( html );
+
+ } else {
+ self.append( html );
+ }
+ });
+ },
+
+ wrap: function( html ) {
+ var isFunction = jQuery.isFunction( html );
+
+ return this.each(function( i ) {
+ jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
+ });
+ },
+
+ unwrap: function() {
+ return this.parent().each(function() {
+ if ( !jQuery.nodeName( this, "body" ) ) {
+ jQuery( this ).replaceWith( this.childNodes );
+ }
+ }).end();
+ }
+});
+
+return jQuery;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.bower.json b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.bower.json
new file mode 100644
index 0000000..a913870
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.bower.json
@@ -0,0 +1,43 @@
+{
+ "name": "ng-lodash",
+ "version": "0.3.0",
+ "description": "An Angular module wrapper for lodash",
+ "author": [
+ "Rockabox <tech@rockabox.com> (http://www.rockabox.com)"
+ ],
+ "license": "MIT",
+ "keywords": [
+ "nglodash",
+ "angular",
+ "lodash"
+ ],
+ "ignore": [
+ "test",
+ "*.",
+ "karma.conf.js",
+ "Gruntfile.js"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/rockabox/ng-lodash.git"
+ },
+ "main": [
+ "build/ng-lodash.js"
+ ],
+ "dependencies": {
+ "angular": ">=1.2"
+ },
+ "devDependencies": {
+ "angular-mocks": ">=1.2"
+ },
+ "homepage": "https://github.com/rockabox/ng-lodash",
+ "_release": "0.3.0",
+ "_resolution": {
+ "type": "version",
+ "tag": "0.3.0",
+ "commit": "16eedfec93b22cea2bbf1732b96d08fc11bce5f6"
+ },
+ "_source": "git://github.com/rockabox/ng-lodash.git",
+ "_target": "~0.3.0",
+ "_originalSource": "ng-lodash"
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.bowerrc b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.bowerrc
new file mode 100644
index 0000000..daf4083
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.bowerrc
@@ -0,0 +1,3 @@
+{
+ "directory": "lib"
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.editorconfig b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.editorconfig
new file mode 100644
index 0000000..03b2556
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.editorconfig
@@ -0,0 +1,12 @@
+# editorconfig.org
+
+root = true
+
+[*]
+indent_style = space
+indent_size = 4
+end_of_line = lf
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+max_line_length = 120
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.gitignore b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.gitignore
new file mode 100644
index 0000000..904971f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.gitignore
@@ -0,0 +1,3 @@
+.grunt
+node_modules
+lib
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.jscsrc b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.jscsrc
new file mode 100644
index 0000000..84bb7cf
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.jscsrc
@@ -0,0 +1,153 @@
+{
+ "requireCurlyBraces": [
+ "if",
+ "else",
+ "for",
+ "while",
+ "do",
+ "try",
+ "catch"
+ ],
+ "requireSpaceAfterKeywords": [
+ "if",
+ "else",
+ "for",
+ "while",
+ "do",
+ "switch",
+ "return",
+ "try",
+ "catch"
+ ],
+ "requireSpaceBeforeBlockStatements": true,
+ "requireSpacesInConditionalExpression": {
+ "afterTest": true,
+ "beforeConsequent": true,
+ "afterConsequent": true,
+ "beforeAlternate": true
+ },
+ "requireSpacesInFunctionExpression": {
+ "beforeOpeningRoundBrace": true,
+ "beforeOpeningCurlyBrace": true
+ },
+ "requireSpacesInAnonymousFunctionExpression": {
+ "beforeOpeningRoundBrace": true,
+ "beforeOpeningCurlyBrace": true
+ },
+ "requireSpacesInNamedFunctionExpression": {
+ "beforeOpeningRoundBrace": true,
+ "beforeOpeningCurlyBrace": true
+ },
+ "requireSpacesInFunctionDeclaration": {
+ "beforeOpeningRoundBrace": true,
+ "beforeOpeningCurlyBrace": true
+ },
+ "requireMultipleVarDecl": true,
+ "requireBlocksOnNewline": 1,
+ "disallowEmptyBlocks": true,
+ "disallowSpacesInsideObjectBrackets": true,
+ "disallowSpacesInsideArrayBrackets": true,
+ "disallowSpacesInsideParentheses": true,
+ "disallowSpaceAfterObjectKeys": true,
+ "requireCommaBeforeLineBreak": true,
+ "requireOperatorBeforeLineBreak": [
+ "?",
+ "=",
+ "+",
+ "-",
+ "/",
+ "*",
+ "==",
+ "===",
+ "!=",
+ "!==",
+ ">",
+ ">=",
+ "<",
+ "<="
+ ],
+ "requireSpaceBeforeBinaryOperators": [
+ "?",
+ "=",
+ "+",
+ "-",
+ "/",
+ "*",
+ "==",
+ "===",
+ "!=",
+ "!==",
+ ">",
+ ">=",
+ "<",
+ "<="
+ ],
+ "requireSpaceAfterBinaryOperators": [
+ "?",
+ "=",
+ "+",
+ "/",
+ "*",
+ ":",
+ "==",
+ "===",
+ "!=",
+ "!==",
+ ">",
+ ">=",
+ "<",
+ "<=",
+ ","
+ ],
+ "disallowSpaceBeforeBinaryOperators": [","],
+ "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"],
+ "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"],
+ "requireSpaceBeforeBinaryOperators": [
+ "=",
+ "+",
+ "-",
+ "/",
+ "*",
+ "==",
+ "===",
+ "!=",
+ "!=="
+ ],
+ "requireSpaceAfterBinaryOperators": [
+ "=",
+ ",",
+ "+",
+ "-",
+ "/",
+ "*",
+ "==",
+ "===",
+ "!=",
+ "!=="
+ ],
+ "disallowImplicitTypeConversion": [
+ "numeric",
+ "boolean",
+ "binary",
+ "string"
+ ],
+ "requireCamelCaseOrUpperCaseIdentifiers": true,
+ "disallowKeywords": ["with"],
+ "disallowMultipleLineBreaks": true,
+ "validateLineBreaks": "LF",
+ "validateQuoteMarks": "'",
+ "validateIndentation": 4,
+ "disallowMixedSpacesAndTabs": true,
+ "disallowTrailingWhitespace": true,
+ "disallowTrailingComma": true,
+ "disallowKeywordsOnNewLine": ["else"],
+ "maximumLineLength": 120,
+ "safeContextKeyword": ["$this"],
+ "disallowYodaConditions": true,
+ "validateJSDoc": {
+ "checkParamNames": true,
+ "checkRedundantParams": true,
+ "requireParamTypes": true
+ },
+ "requireLineFeedAtFileEnd": true
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.jshintrc b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.jshintrc
new file mode 100644
index 0000000..75c081f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.jshintrc
@@ -0,0 +1,19 @@
+{
+ // Predefined globals
+ "browser" : true, // Standard browser globals
+
+ // Development
+ "debug" : false, // Allow debugger statements e.g. browser breakpoints.
+ "devel" : true, // Allow development statements e.g. `console.log();`.
+
+ // The Good Parts
+ "evil" : false, // Tolerate use of `eval`.
+ "regexdash" : true, // Tolerate unescaped last dash i.e. `[-...]`.
+ "trailing" : true, // Prohibit trailing whitespaces.
+ "sub" : true, // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`.
+ "eqeqeq" : false, // Require triple equals i.e. `===`.
+
+ // Styling preferences.
+ "indent" : 4, // Indent level
+ "camelcase" : true // Use CAMEL Casing for variables
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.travis.yml b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.travis.yml
new file mode 100644
index 0000000..6e5919d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/.travis.yml
@@ -0,0 +1,3 @@
+language: node_js
+node_js:
+ - "0.10"
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/CONTRIBUTING.md b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/CONTRIBUTING.md
new file mode 100644
index 0000000..930d581
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/CONTRIBUTING.md
@@ -0,0 +1,657 @@
+# Contributing
+
+This document outlines general guidelines, best practices and coding style rules
+for developers contributing to the project.
+
+## Contents
+
+- [Pull requests](#pull-requests)
+- [Bugs](#bugs)
+- [Features](#features)
+- [Node dependencies](#node-dependencies)
+- [Frontend dependencies](#frontend-dependencies)
+- [Using grunt](#grunt)
+- [JS Guidelines](#js)
+
+## Pull requests
+
+If you fixed or added something useful to the project, you can send a
+pull request. It will be reviewed by maintainer and accepted, or commented for
+rework, or declined.
+
+## Bugs
+
+If you found an error, typo or any other flaw in the project, please report
+about it using GitHub Issues. The more details you provide, the easier it could
+be reproduced and the faster it could be fixed. Unfortunately, sometimes the
+bug can only be reproduced in your project or in your environment, so
+maintainers cannot reproduce it. In this case we believe you can fix the bug
+and send us the fix.
+
+## Features
+
+If you've got an idea about a new feature, it's most likely that you'll have to
+implement it on your own. If you cannot implement the feature, but it is very
+important, you can create an issue at GitHub, but expect it to be declined by
+the maintainer.
+
+## Node dependencies
+
+This project's build process uses Node npm modules defined via the
+`package.json` file.
+
+To add the latest version of new npm package to the project and automatically
+append it to `package.json` run:
+
+```
+npm install <pkg> --save-dev
+```
+
+If new packages have been added by other contributors then run:
+
+```
+npm update
+```
+
+To update all your local packages to the latest possible versions as constrained
+by `package.json` then run:
+
+```
+npm install
+```
+
+### JS
+
+#### General top level guidelines
+
+- Don't skip semicolons
+- 4 spaces for indentation
+- Single quotes for strings
+- Use `{}` instead of `new Object();`
+- Use `[]` instead of `new Array();`
+- Don't use single line `if` statements.
+- 80 chars maximum line length.
+- Use inline comments only where needed to document dense code, code should
+otherwise be clearly comprehensible without redundant commenting
+- Add a whitespace char when writing inline comments, i.e `// Good` vs `//Bad`.
+
+#### Variable naming
+
+- Always use `var` to declare variables.
+- Use only one `var` for multiple variables.
+- Define variables before use.
+- Define constants in CAPS.
+
+```js
+// Good
+var aVariable = 0,
+ aSecondVariable = null,
+ A_CONSTANT = 'constant';
+
+// Bad
+var a_variable = 0;
+var a_second_variable = null;
+```
+
+#### Whitespace
+
+Our JavaScript code is compressed so don't try and save on space when writing
+code, focus on readability by trying to (however do not add unnecessary spaces).
+
+ - Use one (and only one) blank line to separate logical sets of code.
+ - Add a whitespace character after keywords like `if` and after right
+parenthesis.
+ - Add a whitespace character after commas.
+ - Leave a line before a function or `if` statement.
+
+```js
+if (foo === 'foo') {
+ var array = ['one', 'two', 'three'];
+ bar(array);
+
+ foo = 'bar';
+}
+
+function (arg1, arg2) {
+ var foo = arg1;
+ bar(foo);
+}
+```
+
+- Don't add superfluos newlines when writing short/simple indented blocks:
+
+```js
+// Bad
+
+if ( foo ) {
+
+ bar();
+}
+
+function ( baz ) {
+
+ bar();
+}
+```
+
+- Do add newlines in blocks when the opening part of the block has wrapped onto
+a newline due to the 80 char line length limit:
+
+```js
+// Good
+
+angular.module('foo')
+ .controller('FooCtrl', function ($scope, $someReallyLongServiceName,
+ $anotherService, $somethingElse) {
+
+ $scope.bar = 'baz';
+ $scope.qux = 'quux';
+ });
+```
+
+#### JSHint
+
+This repo uses [JSHint](http://www.jshint.com/about/), defined in
+[.jshintrc](../../.jshintrc). Files are checked on save, and errors are visible
+in the console. Optionally this config file can also be used by your code
+editor.
+
+The following guidelines are checked by JSHint.
+
+- Four spaces for indentation, never tabs.
+- Lines no longer than 80 Characters (including comments).
+- Use single `'` quotes for strings.
+- Use `===` and `!==` over `==` and `!=`
+- Use `camelCase` for variables.
+- Don't leave trailing whitespace.
+
+#### JS Code Style (JSCS)
+
+This repo also uses [JSCS](https://github.com/mdevils/node-jscs), defined in
+[.jscsrc](../../.jscsrc). Files are checked on save, and errors are visible in
+the console. Optionally this config file can also be used by your code editor.
+
+The following rules have been defined.
+
+##### `requireCurlyBraces`
+
+Use curly braces after statements.
+
+```js
+// Good
+if (x) {
+ x++;
+}
+
+// Bad
+if (x) x++;
+```
+
+##### `requireSpaceAfterKeywords`
+
+Use spaces after keywords:
+
+```js
+// Good
+if (x) {
+ x++;
+}
+
+// Bad
+if(x) {
+ x++;
+}
+```
+
+##### `requireSpaceBeforeBlockStatements`
+
+Use spaces after parenthesis, before curly brace:
+
+```js
+// Good
+if (x) {
+ x++;
+}
+
+// Bad
+if (x){
+ x++;
+}
+```
+
+##### `requireSpacesInConditionalExpression`
+
+Use spaces around conditional expressions:
+
+```js
+// Good
+var a = b ? c : d;
+
+// Bad
+var a=b?c:d;
+```
+
+##### `requireSpacesInFunctionExpression`
+
+
+##### `requireSpacesInAnonymousFunctionExpression`
+
+
+##### `requireSpacesInNamedFunctionExpression`
+
+
+##### `requireSpacesInFunctionDeclaration`
+
+Use spaces before and after parenthesis:
+
+```js
+// Good
+function a () {}
+
+// Bad
+function a() {}
+function a (){}
+```
+
+##### `requireMultipleVarDecl`
+
+Use one `var` statement for multiple variables:
+
+```js
+// Good
+var x = 1,
+ y = 2;
+
+// Bad
+var x = 1;
+var y = 2;
+```
+
+##### `requireBlocksOnNewline`
+
+Use new lines for multiple statements
+
+```js
+// Good
+if (true) {
+ doSomething();
+ doSomethingElse();
+}
+
+// Bad
+if (true) { doSomething(); doSomethingElse(); }
+```
+
+##### `disallowEmptyBlocks`
+
+Don't use empty blocks
+
+```js
+// Good
+if ( a === b ) {
+ c = d;
+}
+
+// Bad
+if ( a !== b ) {
+
+} else {
+ c = d;
+}
+```
+
+##### `disallowSpacesInsideObjectBrackets`
+
+Don't use a space after an opening or before a closing curly bracket
+
+```js
+// Good
+var x = {a: 1};
+
+// Bad
+var x = { a: 1 };
+```
+
+##### `disallowSpacesInsideArrayBrackets`
+
+Don't use a space after an opening or before a closing square bracket
+
+```js
+// Good
+var x = [1];
+
+// Bad
+var x = [ 1 ];
+```
+
+##### `disallowSpacesInsideParentheses`
+
+Don't use a space after an opening or before a closing parenthesis
+
+```js
+// Good
+var x = (1 + 2) * 3;
+
+// Bad
+var x = ( 1 + 2 ) * 3;
+```
+
+##### `disallowSpaceAfterObjectKeys`
+
+Don't use a space after a key in an object
+
+```js
+// Good
+var x = {a: 1};
+
+// Bad
+var x = {a : 1};
+```
+
+##### `requireCommaBeforeLineBreak`
+
+Don't put commas on the following line
+
+```js
+// Good
+var x = {
+ one: 1,
+ two: 2
+};
+
+// Bad
+var x = {
+ one: 1
+ , two: 2
+};
+```
+
+##### `requireOperatorBeforeLineBreak`
+
+Break lines after (not before) an operator
+
+```js
+// Good
+x = y ?
+ 1 : 2;
+
+// Bad
+x = y
+ ? 1 : 2;
+```
+
+##### `disallowLeftStickedOperators`
+
+Put a space before an operator
+
+```js
+// Good
+x = y ? 1 : 2;
+
+// Bad
+x = y? 1 : 2;
+```
+
+##### `disallowRightStickedOperators`
+
+Put a space after an operator
+
+```js
+// Good
+x = y + 1;
+
+// Bad
+x = y +1;
+```
+
+##### `requireLeftStickedOperators`
+
+Don't put a space before a comma
+
+```js
+// Good
+x = [1, 2];
+
+// Bad
+x = [1 , 2];
+```
+
+##### `disallowSpaceAfterPrefixUnaryOperators`
+
+Don't put a space after a prefix unary operator
+
+```js
+// Good
+x = !y;
+y = ++z;
+// Bad
+x = ! y;
+y = ++ z;
+```
+
+##### `disallowSpaceBeforePostfixUnaryOperators`
+
+Don't put a space after a postfix unary operator
+
+```js
+// Good
+x = y++;
+
+// Bad
+x = y ++;
+```
+
+##### `requireSpaceBeforeBinaryOperators`
+
+Put a space before binary operators
+
+```js
+// Good
+x !== y;
+
+// Bad
+x!== y;
+```
+
+##### `requireSpaceAfterBinaryOperators`
+
+Put a space after binary operators
+
+```js
+// Good
+x + y;
+
+// Bad
+x +y;
+```
+
+##### `disallowImplicitTypeConversion`
+
+Don't use implicit type conversion
+
+```js
+// Good
+x = Boolean(y);
+x = Number(y);
+x = String(y);
+x = s.indexOf('.') !== -1;
+
+// Bad
+x = !!y;
+x = +y;
+x = '' + y;
+x = ~s.indexOf('.');
+```
+
+##### `requireCamelCaseOrUpperCaseIdentifiers`
+
+Use camelCase or
+UPPERCASE_WITH_UNDERSCORES for variable names
+
+```js
+// Good
+var camelCase = 0;
+var UPPER_CASE = 4;
+
+// Bad
+var lower_case = 1;
+var Mixed_case = 2;
+var mixed_Case = 3;
+```
+
+##### `disallowKeywords`
+
+Disallow certain keywords from anywhere in the code base.
+
+```js
+// Bad
+with (foo) {
+}
+```
+
+##### `disallowMultipleLineBreaks`
+
+Don't use multiple blank lines in a row
+
+```js
+// Bad
+var x = 1;
+x++;
+```
+
+##### `validateLineBreaks`
+
+Checks line break character consistency:
+
+```js
+// Good
+foo();<LF>
+
+// Bad
+foo();<CRLF>
+foo();<CR>
+```
+##### `validateQuoteMarks`
+
+Check quote mark usage is single quotes.
+
+```js
+// Good
+var foo = 'bar';
+
+// Bad
+var foo = "bar";
+```
+
+##### `validateIndentation`
+
+Check indentation is at 4 spaces, no tabs.
+
+```js
+// Good
+function foo (bar) {
+ console.log(bar);
+}
+
+// Bad
+function foo (bar) {
+ console.log(bar);
+}
+
+```
+
+##### `disallowMixedSpacesAndTabs`
+
+Check that spaces and tabs are not mixed.
+
+##### `disallowTrailingWhitespace`
+
+Check that no line ends in a whitespace char.
+
+```js
+// Good
+var foo = "blah blah";<LF>
+
+// Bad
+var foo = "blah blah"; <LF>
+```
+
+##### `disallowTrailingComma`
+
+Don't use a comma at the end of an array or object
+
+```js
+// Good
+var foo = [1, 2, 3];
+var bar = {a: "a", b: "b"}
+
+// Bad
+var foo = [1, 2, 3,];
+var bar = {a: "a", b: "b",}
+```
+
+##### `disallowKeywordsOnNewLine`
+
+Don't place `else` statements on their own line
+
+```js
+// Good
+if (x < 0) {
+ x++;
+} else {
+ x--;
+}
+
+// Bad
+if (x < 0) {
+ x++;
+}
+else {
+ x--;
+}
+```
+
+##### `maximumLineLength`
+
+Checks that no single line extends beyond 80 chars.
+
+##### `requireCapitalizedConstructors`
+
+Constructor variable names should be Capitalised.
+
+```js
+// Good
+var foo = new Bar();
+
+// Bad
+var foo = new bar();
+```
+
+##### `safeContextKeyword`
+
+When saving `this` context call the variable `$this`.
+
+```js
+// Good
+var $this = this;
+
+// Bad
+var that = this;
+var self = this;
+```
+
+##### `disallowYodaConditions`
+
+The variable should be on the left in boolean comparisons.
+
+```js
+// Good
+if (a === 1) {
+ // ...
+}
+
+// Bad
+if (1 === a) {
+ // ...
+}
+```
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/License.txt b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/License.txt
new file mode 100644
index 0000000..be8afc1
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/License.txt
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Rockabox Ltd.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/README.md b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/README.md
new file mode 100644
index 0000000..0b2443c
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/README.md
@@ -0,0 +1,61 @@
+[![Built with Grunt](https://cdn.gruntjs.com/builtwith.png)](http://gruntjs.com/)
+[![Build Status](https://travis-ci.org/rockabox/ng-lodash.svg?branch=master)](https://travis-ci.org/rockabox/ng-lodash)
+[![devDependency Status](https://david-dm.org/rockabox/ng-lodash/dev-status.svg)](https://david-dm.org/rockabox/ng-lodash#info=devDependencies)
+
+ng-lodash
+=========
+
+This is a wrapper for the utility library [Lo-Dash](http://lodash.com/) for
+Angular JS. One aim for this project is to ensure Lo-Dash doesn't have to be
+left on the window, and we use Lo-Dash with Angular, in the normal depenedency
+ injection manner.
+
+## Installing
+Install via bower
+
+```bower install ng-lodash```
+
+Require it into your application (after Angular)
+
+```<script src="ng-lodash.min.js"></script>```
+
+Add the module as a dependency to your app
+
+```js
+var app = angular.module('yourAwesomeApp', ['ngLodash']);
+```
+
+And inject it into your controller like so!
+
+```js
+var YourCtrl = app.controller('yourController', function($scope, lodash) {
+ lodash.assign({ 'a': 1 }, { 'b': 2 }, { 'c': 3 });
+});
+```
+
+## Developing
+
+To help us develop this module, we are using Grunt some tasks that may be
+helpful for you to know about are:
+
+### Testing
+
+This command will run JSHint and JSCS testing JS Files (note files within build)
+are not tested, it will also run your local build of the module with all of the
+Karma tests:
+
+```grunt test``` it can also be run by using ```npm test```
+
+### Build
+
+This command will build the module, run it through ngMin and then create a
+minified version of the module, ready for distribution:
+
+```grunt build```
+
+### Dist
+
+This command will build the module initially and then run the test suite.
+Testing with JSHint, JSCS and Karma:
+
+```grunt dist```
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/bower.json b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/bower.json
new file mode 100644
index 0000000..eb17cb3
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/bower.json
@@ -0,0 +1,31 @@
+{
+ "name": "ng-lodash",
+ "version": "0.3.0",
+ "description": "An Angular module wrapper for lodash",
+ "author": ["Rockabox <tech@rockabox.com> (http://www.rockabox.com)"],
+ "license": "MIT",
+ "keywords": [
+ "nglodash",
+ "angular",
+ "lodash"
+ ],
+ "ignore": [
+ "test",
+ "*.",
+ "karma.conf.js",
+ "Gruntfile.js"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/rockabox/ng-lodash.git"
+ },
+ "main": [
+ "build/ng-lodash.js"
+ ],
+ "dependencies": {
+ "angular": ">=1.2"
+ },
+ "devDependencies": {
+ "angular-mocks": ">=1.2"
+ }
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/build/ng-lodash.js b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/build/ng-lodash.js
new file mode 100644
index 0000000..6e4a6b5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/build/ng-lodash.js
@@ -0,0 +1,11267 @@
+/**
+ * @license
+ * lodash 3.10.1 (Custom Build) <https://lodash.com/>
+ * Build: `lodash modern exports="amd,commonjs,node" iife="angular.module('ngLodash', []).constant('lodash', null).config(function ($provide) { %output% $provide.constant('lodash', _);});" --output build/ng-lodash.js`
+ * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
+ * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
+ * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license <https://lodash.com/license>
+ */
+angular.module('ngLodash', []).constant('lodash', null).config([
+ '$provide',
+ function ($provide) {
+ /** Used as a safe reference for `undefined` in pre-ES5 environments. */
+ var undefined;
+ /** Used as the semantic version number. */
+ var VERSION = '3.10.1';
+ /** Used to compose bitmasks for wrapper metadata. */
+ var BIND_FLAG = 1, BIND_KEY_FLAG = 2, CURRY_BOUND_FLAG = 4, CURRY_FLAG = 8, CURRY_RIGHT_FLAG = 16, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FLAG = 64, ARY_FLAG = 128, REARG_FLAG = 256;
+ /** Used as default options for `_.trunc`. */
+ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...';
+ /** Used to detect when a function becomes hot. */
+ var HOT_COUNT = 150, HOT_SPAN = 16;
+ /** Used as the size to enable large array optimizations. */
+ var LARGE_ARRAY_SIZE = 200;
+ /** Used to indicate the type of lazy iteratees. */
+ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2;
+ /** Used as the `TypeError` message for "Functions" methods. */
+ var FUNC_ERROR_TEXT = 'Expected a function';
+ /** Used as the internal argument placeholder. */
+ var PLACEHOLDER = '__lodash_placeholder__';
+ /** `Object#toString` result references. */
+ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]';
+ var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]';
+ /** Used to match empty string literals in compiled template source. */
+ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
+ /** Used to match HTML entities and HTML characters. */
+ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g, reUnescapedHtml = /[&<>"'`]/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
+ /** Used to match template delimiters. */
+ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g;
+ /** Used to match property names within property paths. */
+ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g;
+ /**
+ * Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns)
+ * and those outlined by [`EscapeRegExpPattern`](http://ecma-international.org/ecma-262/6.0/#sec-escaperegexppattern).
+ */
+ var reRegExpChars = /^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g, reHasRegExpChars = RegExp(reRegExpChars.source);
+ /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */
+ var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g;
+ /** Used to match backslashes in property paths. */
+ var reEscapeChar = /\\(\\)?/g;
+ /** Used to match [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components). */
+ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
+ /** Used to match `RegExp` flags from their coerced string values. */
+ var reFlags = /\w*$/;
+ /** Used to detect hexadecimal string values. */
+ var reHasHexPrefix = /^0[xX]/;
+ /** Used to detect host constructors (Safari > 5). */
+ var reIsHostCtor = /^\[object .+?Constructor\]$/;
+ /** Used to detect unsigned integer values. */
+ var reIsUint = /^\d+$/;
+ /** Used to match latin-1 supplementary letters (excluding mathematical operators). */
+ var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;
+ /** Used to ensure capturing order of template delimiters. */
+ var reNoMatch = /($^)/;
+ /** Used to match unescaped characters in compiled string literals. */
+ var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
+ /** Used to match words to create compound words. */
+ var reWords = function () {
+ var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]', lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+';
+ return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');
+ }();
+ /** Used to assign default `context` object properties. */
+ var contextProps = [
+ 'Array',
+ 'ArrayBuffer',
+ 'Date',
+ 'Error',
+ 'Float32Array',
+ 'Float64Array',
+ 'Function',
+ 'Int8Array',
+ 'Int16Array',
+ 'Int32Array',
+ 'Math',
+ 'Number',
+ 'Object',
+ 'RegExp',
+ 'Set',
+ 'String',
+ '_',
+ 'clearTimeout',
+ 'isFinite',
+ 'parseFloat',
+ 'parseInt',
+ 'setTimeout',
+ 'TypeError',
+ 'Uint8Array',
+ 'Uint8ClampedArray',
+ 'Uint16Array',
+ 'Uint32Array',
+ 'WeakMap'
+ ];
+ /** Used to make template sourceURLs easier to identify. */
+ var templateCounter = -1;
+ /** Used to identify `toStringTag` values of typed arrays. */
+ var typedArrayTags = {};
+ typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
+ typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
+ /** Used to identify `toStringTag` values supported by `_.clone`. */
+ var cloneableTags = {};
+ cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[stringTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
+ cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[mapTag] = cloneableTags[setTag] = cloneableTags[weakMapTag] = false;
+ /** Used to map latin-1 supplementary letters to basic latin letters. */
+ var deburredLetters = {
+ '\xc0': 'A',
+ '\xc1': 'A',
+ '\xc2': 'A',
+ '\xc3': 'A',
+ '\xc4': 'A',
+ '\xc5': 'A',
+ '\xe0': 'a',
+ '\xe1': 'a',
+ '\xe2': 'a',
+ '\xe3': 'a',
+ '\xe4': 'a',
+ '\xe5': 'a',
+ '\xc7': 'C',
+ '\xe7': 'c',
+ '\xd0': 'D',
+ '\xf0': 'd',
+ '\xc8': 'E',
+ '\xc9': 'E',
+ '\xca': 'E',
+ '\xcb': 'E',
+ '\xe8': 'e',
+ '\xe9': 'e',
+ '\xea': 'e',
+ '\xeb': 'e',
+ '\xcc': 'I',
+ '\xcd': 'I',
+ '\xce': 'I',
+ '\xcf': 'I',
+ '\xec': 'i',
+ '\xed': 'i',
+ '\xee': 'i',
+ '\xef': 'i',
+ '\xd1': 'N',
+ '\xf1': 'n',
+ '\xd2': 'O',
+ '\xd3': 'O',
+ '\xd4': 'O',
+ '\xd5': 'O',
+ '\xd6': 'O',
+ '\xd8': 'O',
+ '\xf2': 'o',
+ '\xf3': 'o',
+ '\xf4': 'o',
+ '\xf5': 'o',
+ '\xf6': 'o',
+ '\xf8': 'o',
+ '\xd9': 'U',
+ '\xda': 'U',
+ '\xdb': 'U',
+ '\xdc': 'U',
+ '\xf9': 'u',
+ '\xfa': 'u',
+ '\xfb': 'u',
+ '\xfc': 'u',
+ '\xdd': 'Y',
+ '\xfd': 'y',
+ '\xff': 'y',
+ '\xc6': 'Ae',
+ '\xe6': 'ae',
+ '\xde': 'Th',
+ '\xfe': 'th',
+ '\xdf': 'ss'
+ };
+ /** Used to map characters to HTML entities. */
+ var htmlEscapes = {
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ '\'': ''',
+ '`': '`'
+ };
+ /** Used to map HTML entities to characters. */
+ var htmlUnescapes = {
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ ''': '\'',
+ '`': '`'
+ };
+ /** Used to determine if values are of the language type `Object`. */
+ var objectTypes = {
+ 'function': true,
+ 'object': true
+ };
+ /** Used to escape characters for inclusion in compiled regexes. */
+ var regexpEscapes = {
+ '0': 'x30',
+ '1': 'x31',
+ '2': 'x32',
+ '3': 'x33',
+ '4': 'x34',
+ '5': 'x35',
+ '6': 'x36',
+ '7': 'x37',
+ '8': 'x38',
+ '9': 'x39',
+ 'A': 'x41',
+ 'B': 'x42',
+ 'C': 'x43',
+ 'D': 'x44',
+ 'E': 'x45',
+ 'F': 'x46',
+ 'a': 'x61',
+ 'b': 'x62',
+ 'c': 'x63',
+ 'd': 'x64',
+ 'e': 'x65',
+ 'f': 'x66',
+ 'n': 'x6e',
+ 'r': 'x72',
+ 't': 'x74',
+ 'u': 'x75',
+ 'v': 'x76',
+ 'x': 'x78'
+ };
+ /** Used to escape characters for inclusion in compiled string literals. */
+ var stringEscapes = {
+ '\\': '\\',
+ '\'': '\'',
+ '\n': 'n',
+ '\r': 'r',
+ '\u2028': 'u2028',
+ '\u2029': 'u2029'
+ };
+ /** Detect free variable `exports`. */
+ var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
+ /** Detect free variable `module`. */
+ var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
+ /** Detect free variable `global` from Node.js. */
+ var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global;
+ /** Detect free variable `self`. */
+ var freeSelf = objectTypes[typeof self] && self && self.Object && self;
+ /** Detect free variable `window`. */
+ var freeWindow = objectTypes[typeof window] && window && window.Object && window;
+ /** Detect the popular CommonJS extension `module.exports`. */
+ var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
+ /**
+ * Used as a reference to the global object.
+ *
+ * The `this` value is used if it's the global object to avoid Greasemonkey's
+ * restricted `window` object, otherwise the `window` object is used.
+ */
+ var root = freeGlobal || freeWindow !== (this && this.window) && freeWindow || freeSelf || this;
+ /*--------------------------------------------------------------------------*/
+ /**
+ * The base implementation of `compareAscending` which compares values and
+ * sorts them in ascending order without guaranteeing a stable sort.
+ *
+ * @private
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {number} Returns the sort order indicator for `value`.
+ */
+ function baseCompareAscending(value, other) {
+ if (value !== other) {
+ var valIsNull = value === null, valIsUndef = value === undefined, valIsReflexive = value === value;
+ var othIsNull = other === null, othIsUndef = other === undefined, othIsReflexive = other === other;
+ if (value > other && !othIsNull || !valIsReflexive || valIsNull && !othIsUndef && othIsReflexive || valIsUndef && othIsReflexive) {
+ return 1;
+ }
+ if (value < other && !valIsNull || !othIsReflexive || othIsNull && !valIsUndef && valIsReflexive || othIsUndef && valIsReflexive) {
+ return -1;
+ }
+ }
+ return 0;
+ }
+ /**
+ * The base implementation of `_.findIndex` and `_.findLastIndex` without
+ * support for callback shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array} array The array to search.
+ * @param {Function} predicate The function invoked per iteration.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ */
+ function baseFindIndex(array, predicate, fromRight) {
+ var length = array.length, index = fromRight ? length : -1;
+ while (fromRight ? index-- : ++index < length) {
+ if (predicate(array[index], index, array)) {
+ return index;
+ }
+ }
+ return -1;
+ }
+ /**
+ * The base implementation of `_.indexOf` without support for binary searches.
+ *
+ * @private
+ * @param {Array} array The array to search.
+ * @param {*} value The value to search for.
+ * @param {number} fromIndex The index to search from.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ */
+ function baseIndexOf(array, value, fromIndex) {
+ if (value !== value) {
+ return indexOfNaN(array, fromIndex);
+ }
+ var index = fromIndex - 1, length = array.length;
+ while (++index < length) {
+ if (array[index] === value) {
+ return index;
+ }
+ }
+ return -1;
+ }
+ /**
+ * The base implementation of `_.isFunction` without support for environments
+ * with incorrect `typeof` results.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ */
+ function baseIsFunction(value) {
+ // Avoid a Chakra JIT bug in compatibility modes of IE 11.
+ // See https://github.com/jashkenas/underscore/issues/1621 for more details.
+ return typeof value == 'function' || false;
+ }
+ /**
+ * Converts `value` to a string if it's not one. An empty string is returned
+ * for `null` or `undefined` values.
+ *
+ * @private
+ * @param {*} value The value to process.
+ * @returns {string} Returns the string.
+ */
+ function baseToString(value) {
+ return value == null ? '' : value + '';
+ }
+ /**
+ * Used by `_.trim` and `_.trimLeft` to get the index of the first character
+ * of `string` that is not found in `chars`.
+ *
+ * @private
+ * @param {string} string The string to inspect.
+ * @param {string} chars The characters to find.
+ * @returns {number} Returns the index of the first character not found in `chars`.
+ */
+ function charsLeftIndex(string, chars) {
+ var index = -1, length = string.length;
+ while (++index < length && chars.indexOf(string.charAt(index)) > -1) {
+ }
+ return index;
+ }
+ /**
+ * Used by `_.trim` and `_.trimRight` to get the index of the last character
+ * of `string` that is not found in `chars`.
+ *
+ * @private
+ * @param {string} string The string to inspect.
+ * @param {string} chars The characters to find.
+ * @returns {number} Returns the index of the last character not found in `chars`.
+ */
+ function charsRightIndex(string, chars) {
+ var index = string.length;
+ while (index-- && chars.indexOf(string.charAt(index)) > -1) {
+ }
+ return index;
+ }
+ /**
+ * Used by `_.sortBy` to compare transformed elements of a collection and stable
+ * sort them in ascending order.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @returns {number} Returns the sort order indicator for `object`.
+ */
+ function compareAscending(object, other) {
+ return baseCompareAscending(object.criteria, other.criteria) || object.index - other.index;
+ }
+ /**
+ * Used by `_.sortByOrder` to compare multiple properties of a value to another
+ * and stable sort them.
+ *
+ * If `orders` is unspecified, all valuess are sorted in ascending order. Otherwise,
+ * a value is sorted in ascending order if its corresponding order is "asc", and
+ * descending if "desc".
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {boolean[]} orders The order to sort by for each property.
+ * @returns {number} Returns the sort order indicator for `object`.
+ */
+ function compareMultiple(object, other, orders) {
+ var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length;
+ while (++index < length) {
+ var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
+ if (result) {
+ if (index >= ordersLength) {
+ return result;
+ }
+ var order = orders[index];
+ return result * (order === 'asc' || order === true ? 1 : -1);
+ }
+ }
+ // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
+ // that causes it, under certain circumstances, to provide the same value for
+ // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
+ // for more details.
+ //
+ // This also ensures a stable sort in V8 and other engines.
+ // See https://code.google.com/p/v8/issues/detail?id=90 for more details.
+ return object.index - other.index;
+ }
+ /**
+ * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
+ *
+ * @private
+ * @param {string} letter The matched letter to deburr.
+ * @returns {string} Returns the deburred letter.
+ */
+ function deburrLetter(letter) {
+ return deburredLetters[letter];
+ }
+ /**
+ * Used by `_.escape` to convert characters to HTML entities.
+ *
+ * @private
+ * @param {string} chr The matched character to escape.
+ * @returns {string} Returns the escaped character.
+ */
+ function escapeHtmlChar(chr) {
+ return htmlEscapes[chr];
+ }
+ /**
+ * Used by `_.escapeRegExp` to escape characters for inclusion in compiled regexes.
+ *
+ * @private
+ * @param {string} chr The matched character to escape.
+ * @param {string} leadingChar The capture group for a leading character.
+ * @param {string} whitespaceChar The capture group for a whitespace character.
+ * @returns {string} Returns the escaped character.
+ */
+ function escapeRegExpChar(chr, leadingChar, whitespaceChar) {
+ if (leadingChar) {
+ chr = regexpEscapes[chr];
+ } else if (whitespaceChar) {
+ chr = stringEscapes[chr];
+ }
+ return '\\' + chr;
+ }
+ /**
+ * Used by `_.template` to escape characters for inclusion in compiled string literals.
+ *
+ * @private
+ * @param {string} chr The matched character to escape.
+ * @returns {string} Returns the escaped character.
+ */
+ function escapeStringChar(chr) {
+ return '\\' + stringEscapes[chr];
+ }
+ /**
+ * Gets the index at which the first occurrence of `NaN` is found in `array`.
+ *
+ * @private
+ * @param {Array} array The array to search.
+ * @param {number} fromIndex The index to search from.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {number} Returns the index of the matched `NaN`, else `-1`.
+ */
+ function indexOfNaN(array, fromIndex, fromRight) {
+ var length = array.length, index = fromIndex + (fromRight ? 0 : -1);
+ while (fromRight ? index-- : ++index < length) {
+ var other = array[index];
+ if (other !== other) {
+ return index;
+ }
+ }
+ return -1;
+ }
+ /**
+ * Checks if `value` is object-like.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
+ */
+ function isObjectLike(value) {
+ return !!value && typeof value == 'object';
+ }
+ /**
+ * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a
+ * character code is whitespace.
+ *
+ * @private
+ * @param {number} charCode The character code to inspect.
+ * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`.
+ */
+ function isSpace(charCode) {
+ return charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160 || charCode == 5760 || charCode == 6158 || charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279);
+ }
+ /**
+ * Replaces all `placeholder` elements in `array` with an internal placeholder
+ * and returns an array of their indexes.
+ *
+ * @private
+ * @param {Array} array The array to modify.
+ * @param {*} placeholder The placeholder to replace.
+ * @returns {Array} Returns the new array of placeholder indexes.
+ */
+ function replaceHolders(array, placeholder) {
+ var index = -1, length = array.length, resIndex = -1, result = [];
+ while (++index < length) {
+ if (array[index] === placeholder) {
+ array[index] = PLACEHOLDER;
+ result[++resIndex] = index;
+ }
+ }
+ return result;
+ }
+ /**
+ * An implementation of `_.uniq` optimized for sorted arrays without support
+ * for callback shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {Function} [iteratee] The function invoked per iteration.
+ * @returns {Array} Returns the new duplicate free array.
+ */
+ function sortedUniq(array, iteratee) {
+ var seen, index = -1, length = array.length, resIndex = -1, result = [];
+ while (++index < length) {
+ var value = array[index], computed = iteratee ? iteratee(value, index, array) : value;
+ if (!index || seen !== computed) {
+ seen = computed;
+ result[++resIndex] = value;
+ }
+ }
+ return result;
+ }
+ /**
+ * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace
+ * character of `string`.
+ *
+ * @private
+ * @param {string} string The string to inspect.
+ * @returns {number} Returns the index of the first non-whitespace character.
+ */
+ function trimmedLeftIndex(string) {
+ var index = -1, length = string.length;
+ while (++index < length && isSpace(string.charCodeAt(index))) {
+ }
+ return index;
+ }
+ /**
+ * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace
+ * character of `string`.
+ *
+ * @private
+ * @param {string} string The string to inspect.
+ * @returns {number} Returns the index of the last non-whitespace character.
+ */
+ function trimmedRightIndex(string) {
+ var index = string.length;
+ while (index-- && isSpace(string.charCodeAt(index))) {
+ }
+ return index;
+ }
+ /**
+ * Used by `_.unescape` to convert HTML entities to characters.
+ *
+ * @private
+ * @param {string} chr The matched character to unescape.
+ * @returns {string} Returns the unescaped character.
+ */
+ function unescapeHtmlChar(chr) {
+ return htmlUnescapes[chr];
+ }
+ /*--------------------------------------------------------------------------*/
+ /**
+ * Create a new pristine `lodash` function using the given `context` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {Object} [context=root] The context object.
+ * @returns {Function} Returns a new `lodash` function.
+ * @example
+ *
+ * _.mixin({ 'foo': _.constant('foo') });
+ *
+ * var lodash = _.runInContext();
+ * lodash.mixin({ 'bar': lodash.constant('bar') });
+ *
+ * _.isFunction(_.foo);
+ * // => true
+ * _.isFunction(_.bar);
+ * // => false
+ *
+ * lodash.isFunction(lodash.foo);
+ * // => false
+ * lodash.isFunction(lodash.bar);
+ * // => true
+ *
+ * // using `context` to mock `Date#getTime` use in `_.now`
+ * var mock = _.runInContext({
+ * 'Date': function() {
+ * return { 'getTime': getTimeMock };
+ * }
+ * });
+ *
+ * // or creating a suped-up `defer` in Node.js
+ * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
+ */
+ function runInContext(context) {
+ // Avoid issues with some ES3 environments that attempt to use values, named
+ // after built-in constructors like `Object`, for the creation of literals.
+ // ES5 clears this up by stating that literals must use built-in constructors.
+ // See https://es5.github.io/#x11.1.5 for more details.
+ context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
+ /** Native constructor references. */
+ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Number = context.Number, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError;
+ /** Used for native method references. */
+ var arrayProto = Array.prototype, objectProto = Object.prototype, stringProto = String.prototype;
+ /** Used to resolve the decompiled source of functions. */
+ var fnToString = Function.prototype.toString;
+ /** Used to check objects for own properties. */
+ var hasOwnProperty = objectProto.hasOwnProperty;
+ /** Used to generate unique IDs. */
+ var idCounter = 0;
+ /**
+ * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
+ * of values.
+ */
+ var objToString = objectProto.toString;
+ /** Used to restore the original `_` reference in `_.noConflict`. */
+ var oldDash = root._;
+ /** Used to detect if a method is native. */
+ var reIsNative = RegExp('^' + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
+ /** Native method references. */
+ var ArrayBuffer = context.ArrayBuffer, clearTimeout = context.clearTimeout, parseFloat = context.parseFloat, pow = Math.pow, propertyIsEnumerable = objectProto.propertyIsEnumerable, Set = getNative(context, 'Set'), setTimeout = context.setTimeout, splice = arrayProto.splice, Uint8Array = context.Uint8Array, WeakMap = getNative(context, 'WeakMap');
+ /* Native method references for those with the same name as other `lodash` methods. */
+ var nativeCeil = Math.ceil, nativeCreate = getNative(Object, 'create'), nativeFloor = Math.floor, nativeIsArray = getNative(Array, 'isArray'), nativeIsFinite = context.isFinite, nativeKeys = getNative(Object, 'keys'), nativeMax = Math.max, nativeMin = Math.min, nativeNow = getNative(Date, 'now'), nativeParseInt = context.parseInt, nativeRandom = Math.random;
+ /** Used as references for `-Infinity` and `Infinity`. */
+ var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY, POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
+ /** Used as references for the maximum length and index of an array. */
+ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
+ /**
+ * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
+ * of an array-like value.
+ */
+ var MAX_SAFE_INTEGER = 9007199254740991;
+ /** Used to store function metadata. */
+ var metaMap = WeakMap && new WeakMap();
+ /** Used to lookup unminified function names. */
+ var realNames = {};
+ /*------------------------------------------------------------------------*/
+ /**
+ * Creates a `lodash` object which wraps `value` to enable implicit chaining.
+ * Methods that operate on and return arrays, collections, and functions can
+ * be chained together. Methods that retrieve a single value or may return a
+ * primitive value will automatically end the chain returning the unwrapped
+ * value. Explicit chaining may be enabled using `_.chain`. The execution of
+ * chained methods is lazy, that is, execution is deferred until `_#value`
+ * is implicitly or explicitly called.
+ *
+ * Lazy evaluation allows several methods to support shortcut fusion. Shortcut
+ * fusion is an optimization strategy which merge iteratee calls; this can help
+ * to avoid the creation of intermediate data structures and greatly reduce the
+ * number of iteratee executions.
+ *
+ * Chaining is supported in custom builds as long as the `_#value` method is
+ * directly or indirectly included in the build.
+ *
+ * In addition to lodash methods, wrappers have `Array` and `String` methods.
+ *
+ * The wrapper `Array` methods are:
+ * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`,
+ * `splice`, and `unshift`
+ *
+ * The wrapper `String` methods are:
+ * `replace` and `split`
+ *
+ * The wrapper methods that support shortcut fusion are:
+ * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`,
+ * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`,
+ * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`,
+ * and `where`
+ *
+ * The chainable wrapper methods are:
+ * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`,
+ * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`,
+ * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`,
+ * `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`,
+ * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`,
+ * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
+ * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
+ * `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`,
+ * `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`,
+ * `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`,
+ * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`,
+ * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`,
+ * `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`,
+ * `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`,
+ * `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`,
+ * `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`,
+ * `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith`
+ *
+ * The wrapper methods that are **not** chainable by default are:
+ * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`,
+ * `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`,
+ * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`,
+ * `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`,
+ * `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
+ * `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`,
+ * `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`,
+ * `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`,
+ * `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`,
+ * `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`,
+ * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`,
+ * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`,
+ * `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`,
+ * `unescape`, `uniqueId`, `value`, and `words`
+ *
+ * The wrapper method `sample` will return a wrapped value when `n` is provided,
+ * otherwise an unwrapped value is returned.
+ *
+ * @name _
+ * @constructor
+ * @category Chain
+ * @param {*} value The value to wrap in a `lodash` instance.
+ * @returns {Object} Returns the new `lodash` wrapper instance.
+ * @example
+ *
+ * var wrapped = _([1, 2, 3]);
+ *
+ * // returns an unwrapped value
+ * wrapped.reduce(function(total, n) {
+ * return total + n;
+ * });
+ * // => 6
+ *
+ * // returns a wrapped value
+ * var squares = wrapped.map(function(n) {
+ * return n * n;
+ * });
+ *
+ * _.isArray(squares);
+ * // => false
+ *
+ * _.isArray(squares.value());
+ * // => true
+ */
+ function lodash(value) {
+ if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
+ if (value instanceof LodashWrapper) {
+ return value;
+ }
+ if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) {
+ return wrapperClone(value);
+ }
+ }
+ return new LodashWrapper(value);
+ }
+ /**
+ * The function whose prototype all chaining wrappers inherit from.
+ *
+ * @private
+ */
+ function baseLodash() {
+ }
+ /**
+ * The base constructor for creating `lodash` wrapper objects.
+ *
+ * @private
+ * @param {*} value The value to wrap.
+ * @param {boolean} [chainAll] Enable chaining for all wrapper methods.
+ * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value.
+ */
+ function LodashWrapper(value, chainAll, actions) {
+ this.__wrapped__ = value;
+ this.__actions__ = actions || [];
+ this.__chain__ = !!chainAll;
+ }
+ /**
+ * An object environment feature flags.
+ *
+ * @static
+ * @memberOf _
+ * @type Object
+ */
+ var support = lodash.support = {};
+ /**
+ * By default, the template delimiters used by lodash are like those in
+ * embedded Ruby (ERB). Change the following template settings to use
+ * alternative delimiters.
+ *
+ * @static
+ * @memberOf _
+ * @type Object
+ */
+ lodash.templateSettings = {
+ 'escape': reEscape,
+ 'evaluate': reEvaluate,
+ 'interpolate': reInterpolate,
+ 'variable': '',
+ 'imports': { '_': lodash }
+ };
+ /*------------------------------------------------------------------------*/
+ /**
+ * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
+ *
+ * @private
+ * @param {*} value The value to wrap.
+ */
+ function LazyWrapper(value) {
+ this.__wrapped__ = value;
+ this.__actions__ = [];
+ this.__dir__ = 1;
+ this.__filtered__ = false;
+ this.__iteratees__ = [];
+ this.__takeCount__ = POSITIVE_INFINITY;
+ this.__views__ = [];
+ }
+ /**
+ * Creates a clone of the lazy wrapper object.
+ *
+ * @private
+ * @name clone
+ * @memberOf LazyWrapper
+ * @returns {Object} Returns the cloned `LazyWrapper` object.
+ */
+ function lazyClone() {
+ var result = new LazyWrapper(this.__wrapped__);
+ result.__actions__ = arrayCopy(this.__actions__);
+ result.__dir__ = this.__dir__;
+ result.__filtered__ = this.__filtered__;
+ result.__iteratees__ = arrayCopy(this.__iteratees__);
+ result.__takeCount__ = this.__takeCount__;
+ result.__views__ = arrayCopy(this.__views__);
+ return result;
+ }
+ /**
+ * Reverses the direction of lazy iteration.
+ *
+ * @private
+ * @name reverse
+ * @memberOf LazyWrapper
+ * @returns {Object} Returns the new reversed `LazyWrapper` object.
+ */
+ function lazyReverse() {
+ if (this.__filtered__) {
+ var result = new LazyWrapper(this);
+ result.__dir__ = -1;
+ result.__filtered__ = true;
+ } else {
+ result = this.clone();
+ result.__dir__ *= -1;
+ }
+ return result;
+ }
+ /**
+ * Extracts the unwrapped value from its lazy wrapper.
+ *
+ * @private
+ * @name value
+ * @memberOf LazyWrapper
+ * @returns {*} Returns the unwrapped value.
+ */
+ function lazyValue() {
+ var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : start - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__);
+ if (!isArr || arrLength < LARGE_ARRAY_SIZE || arrLength == length && takeCount == length) {
+ return baseWrapperValue(array, this.__actions__);
+ }
+ var result = [];
+ outer:
+ while (length-- && resIndex < takeCount) {
+ index += dir;
+ var iterIndex = -1, value = array[index];
+ while (++iterIndex < iterLength) {
+ var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value);
+ if (type == LAZY_MAP_FLAG) {
+ value = computed;
+ } else if (!computed) {
+ if (type == LAZY_FILTER_FLAG) {
+ continue outer;
+ } else {
+ break outer;
+ }
+ }
+ }
+ result[resIndex++] = value;
+ }
+ return result;
+ }
+ /*------------------------------------------------------------------------*/
+ /**
+ * Creates a cache object to store key/value pairs.
+ *
+ * @private
+ * @static
+ * @name Cache
+ * @memberOf _.memoize
+ */
+ function MapCache() {
+ this.__data__ = {};
+ }
+ /**
+ * Removes `key` and its value from the cache.
+ *
+ * @private
+ * @name delete
+ * @memberOf _.memoize.Cache
+ * @param {string} key The key of the value to remove.
+ * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`.
+ */
+ function mapDelete(key) {
+ return this.has(key) && delete this.__data__[key];
+ }
+ /**
+ * Gets the cached value for `key`.
+ *
+ * @private
+ * @name get
+ * @memberOf _.memoize.Cache
+ * @param {string} key The key of the value to get.
+ * @returns {*} Returns the cached value.
+ */
+ function mapGet(key) {
+ return key == '__proto__' ? undefined : this.__data__[key];
+ }
+ /**
+ * Checks if a cached value for `key` exists.
+ *
+ * @private
+ * @name has
+ * @memberOf _.memoize.Cache
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
+ */
+ function mapHas(key) {
+ return key != '__proto__' && hasOwnProperty.call(this.__data__, key);
+ }
+ /**
+ * Sets `value` to `key` of the cache.
+ *
+ * @private
+ * @name set
+ * @memberOf _.memoize.Cache
+ * @param {string} key The key of the value to cache.
+ * @param {*} value The value to cache.
+ * @returns {Object} Returns the cache object.
+ */
+ function mapSet(key, value) {
+ if (key != '__proto__') {
+ this.__data__[key] = value;
+ }
+ return this;
+ }
+ /*------------------------------------------------------------------------*/
+ /**
+ *
+ * Creates a cache object to store unique values.
+ *
+ * @private
+ * @param {Array} [values] The values to cache.
+ */
+ function SetCache(values) {
+ var length = values ? values.length : 0;
+ this.data = {
+ 'hash': nativeCreate(null),
+ 'set': new Set()
+ };
+ while (length--) {
+ this.push(values[length]);
+ }
+ }
+ /**
+ * Checks if `value` is in `cache` mimicking the return signature of
+ * `_.indexOf` by returning `0` if the value is found, else `-1`.
+ *
+ * @private
+ * @param {Object} cache The cache to search.
+ * @param {*} value The value to search for.
+ * @returns {number} Returns `0` if `value` is found, else `-1`.
+ */
+ function cacheIndexOf(cache, value) {
+ var data = cache.data, result = typeof value == 'string' || isObject(value) ? data.set.has(value) : data.hash[value];
+ return result ? 0 : -1;
+ }
+ /**
+ * Adds `value` to the cache.
+ *
+ * @private
+ * @name push
+ * @memberOf SetCache
+ * @param {*} value The value to cache.
+ */
+ function cachePush(value) {
+ var data = this.data;
+ if (typeof value == 'string' || isObject(value)) {
+ data.set.add(value);
+ } else {
+ data.hash[value] = true;
+ }
+ }
+ /*------------------------------------------------------------------------*/
+ /**
+ * Creates a new array joining `array` with `other`.
+ *
+ * @private
+ * @param {Array} array The array to join.
+ * @param {Array} other The other array to join.
+ * @returns {Array} Returns the new concatenated array.
+ */
+ function arrayConcat(array, other) {
+ var index = -1, length = array.length, othIndex = -1, othLength = other.length, result = Array(length + othLength);
+ while (++index < length) {
+ result[index] = array[index];
+ }
+ while (++othIndex < othLength) {
+ result[index++] = other[othIndex];
+ }
+ return result;
+ }
+ /**
+ * Copies the values of `source` to `array`.
+ *
+ * @private
+ * @param {Array} source The array to copy values from.
+ * @param {Array} [array=[]] The array to copy values to.
+ * @returns {Array} Returns `array`.
+ */
+ function arrayCopy(source, array) {
+ var index = -1, length = source.length;
+ array || (array = Array(length));
+ while (++index < length) {
+ array[index] = source[index];
+ }
+ return array;
+ }
+ /**
+ * A specialized version of `_.forEach` for arrays without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns `array`.
+ */
+ function arrayEach(array, iteratee) {
+ var index = -1, length = array.length;
+ while (++index < length) {
+ if (iteratee(array[index], index, array) === false) {
+ break;
+ }
+ }
+ return array;
+ }
+ /**
+ * A specialized version of `_.forEachRight` for arrays without support for
+ * callback shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns `array`.
+ */
+ function arrayEachRight(array, iteratee) {
+ var length = array.length;
+ while (length--) {
+ if (iteratee(array[length], length, array) === false) {
+ break;
+ }
+ }
+ return array;
+ }
+ /**
+ * A specialized version of `_.every` for arrays without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if all elements pass the predicate check,
+ * else `false`.
+ */
+ function arrayEvery(array, predicate) {
+ var index = -1, length = array.length;
+ while (++index < length) {
+ if (!predicate(array[index], index, array)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ /**
+ * A specialized version of `baseExtremum` for arrays which invokes `iteratee`
+ * with one argument: (value).
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {Function} comparator The function used to compare values.
+ * @param {*} exValue The initial extremum value.
+ * @returns {*} Returns the extremum value.
+ */
+ function arrayExtremum(array, iteratee, comparator, exValue) {
+ var index = -1, length = array.length, computed = exValue, result = computed;
+ while (++index < length) {
+ var value = array[index], current = +iteratee(value);
+ if (comparator(current, computed)) {
+ computed = current;
+ result = value;
+ }
+ }
+ return result;
+ }
+ /**
+ * A specialized version of `_.filter` for arrays without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {Array} Returns the new filtered array.
+ */
+ function arrayFilter(array, predicate) {
+ var index = -1, length = array.length, resIndex = -1, result = [];
+ while (++index < length) {
+ var value = array[index];
+ if (predicate(value, index, array)) {
+ result[++resIndex] = value;
+ }
+ }
+ return result;
+ }
+ /**
+ * A specialized version of `_.map` for arrays without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns the new mapped array.
+ */
+ function arrayMap(array, iteratee) {
+ var index = -1, length = array.length, result = Array(length);
+ while (++index < length) {
+ result[index] = iteratee(array[index], index, array);
+ }
+ return result;
+ }
+ /**
+ * Appends the elements of `values` to `array`.
+ *
+ * @private
+ * @param {Array} array The array to modify.
+ * @param {Array} values The values to append.
+ * @returns {Array} Returns `array`.
+ */
+ function arrayPush(array, values) {
+ var index = -1, length = values.length, offset = array.length;
+ while (++index < length) {
+ array[offset + index] = values[index];
+ }
+ return array;
+ }
+ /**
+ * A specialized version of `_.reduce` for arrays without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {*} [accumulator] The initial value.
+ * @param {boolean} [initFromArray] Specify using the first element of `array`
+ * as the initial value.
+ * @returns {*} Returns the accumulated value.
+ */
+ function arrayReduce(array, iteratee, accumulator, initFromArray) {
+ var index = -1, length = array.length;
+ if (initFromArray && length) {
+ accumulator = array[++index];
+ }
+ while (++index < length) {
+ accumulator = iteratee(accumulator, array[index], index, array);
+ }
+ return accumulator;
+ }
+ /**
+ * A specialized version of `_.reduceRight` for arrays without support for
+ * callback shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {*} [accumulator] The initial value.
+ * @param {boolean} [initFromArray] Specify using the last element of `array`
+ * as the initial value.
+ * @returns {*} Returns the accumulated value.
+ */
+ function arrayReduceRight(array, iteratee, accumulator, initFromArray) {
+ var length = array.length;
+ if (initFromArray && length) {
+ accumulator = array[--length];
+ }
+ while (length--) {
+ accumulator = iteratee(accumulator, array[length], length, array);
+ }
+ return accumulator;
+ }
+ /**
+ * A specialized version of `_.some` for arrays without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if any element passes the predicate check,
+ * else `false`.
+ */
+ function arraySome(array, predicate) {
+ var index = -1, length = array.length;
+ while (++index < length) {
+ if (predicate(array[index], index, array)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ /**
+ * A specialized version of `_.sum` for arrays without support for callback
+ * shorthands and `this` binding..
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {number} Returns the sum.
+ */
+ function arraySum(array, iteratee) {
+ var length = array.length, result = 0;
+ while (length--) {
+ result += +iteratee(array[length]) || 0;
+ }
+ return result;
+ }
+ /**
+ * Used by `_.defaults` to customize its `_.assign` use.
+ *
+ * @private
+ * @param {*} objectValue The destination object property value.
+ * @param {*} sourceValue The source object property value.
+ * @returns {*} Returns the value to assign to the destination object.
+ */
+ function assignDefaults(objectValue, sourceValue) {
+ return objectValue === undefined ? sourceValue : objectValue;
+ }
+ /**
+ * Used by `_.template` to customize its `_.assign` use.
+ *
+ * **Note:** This function is like `assignDefaults` except that it ignores
+ * inherited property values when checking if a property is `undefined`.
+ *
+ * @private
+ * @param {*} objectValue The destination object property value.
+ * @param {*} sourceValue The source object property value.
+ * @param {string} key The key associated with the object and source values.
+ * @param {Object} object The destination object.
+ * @returns {*} Returns the value to assign to the destination object.
+ */
+ function assignOwnDefaults(objectValue, sourceValue, key, object) {
+ return objectValue === undefined || !hasOwnProperty.call(object, key) ? sourceValue : objectValue;
+ }
+ /**
+ * A specialized version of `_.assign` for customizing assigned values without
+ * support for argument juggling, multiple sources, and `this` binding `customizer`
+ * functions.
+ *
+ * @private
+ * @param {Object} object The destination object.
+ * @param {Object} source The source object.
+ * @param {Function} customizer The function to customize assigned values.
+ * @returns {Object} Returns `object`.
+ */
+ function assignWith(object, source, customizer) {
+ var index = -1, props = keys(source), length = props.length;
+ while (++index < length) {
+ var key = props[index], value = object[key], result = customizer(value, source[key], key, object, source);
+ if ((result === result ? result !== value : value === value) || value === undefined && !(key in object)) {
+ object[key] = result;
+ }
+ }
+ return object;
+ }
+ /**
+ * The base implementation of `_.assign` without support for argument juggling,
+ * multiple sources, and `customizer` functions.
+ *
+ * @private
+ * @param {Object} object The destination object.
+ * @param {Object} source The source object.
+ * @returns {Object} Returns `object`.
+ */
+ function baseAssign(object, source) {
+ return source == null ? object : baseCopy(source, keys(source), object);
+ }
+ /**
+ * The base implementation of `_.at` without support for string collections
+ * and individual key arguments.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {number[]|string[]} props The property names or indexes of elements to pick.
+ * @returns {Array} Returns the new array of picked elements.
+ */
+ function baseAt(collection, props) {
+ var index = -1, isNil = collection == null, isArr = !isNil && isArrayLike(collection), length = isArr ? collection.length : 0, propsLength = props.length, result = Array(propsLength);
+ while (++index < propsLength) {
+ var key = props[index];
+ if (isArr) {
+ result[index] = isIndex(key, length) ? collection[key] : undefined;
+ } else {
+ result[index] = isNil ? undefined : collection[key];
+ }
+ }
+ return result;
+ }
+ /**
+ * Copies properties of `source` to `object`.
+ *
+ * @private
+ * @param {Object} source The object to copy properties from.
+ * @param {Array} props The property names to copy.
+ * @param {Object} [object={}] The object to copy properties to.
+ * @returns {Object} Returns `object`.
+ */
+ function baseCopy(source, props, object) {
+ object || (object = {});
+ var index = -1, length = props.length;
+ while (++index < length) {
+ var key = props[index];
+ object[key] = source[key];
+ }
+ return object;
+ }
+ /**
+ * The base implementation of `_.callback` which supports specifying the
+ * number of arguments to provide to `func`.
+ *
+ * @private
+ * @param {*} [func=_.identity] The value to convert to a callback.
+ * @param {*} [thisArg] The `this` binding of `func`.
+ * @param {number} [argCount] The number of arguments to provide to `func`.
+ * @returns {Function} Returns the callback.
+ */
+ function baseCallback(func, thisArg, argCount) {
+ var type = typeof func;
+ if (type == 'function') {
+ return thisArg === undefined ? func : bindCallback(func, thisArg, argCount);
+ }
+ if (func == null) {
+ return identity;
+ }
+ if (type == 'object') {
+ return baseMatches(func);
+ }
+ return thisArg === undefined ? property(func) : baseMatchesProperty(func, thisArg);
+ }
+ /**
+ * The base implementation of `_.clone` without support for argument juggling
+ * and `this` binding `customizer` functions.
+ *
+ * @private
+ * @param {*} value The value to clone.
+ * @param {boolean} [isDeep] Specify a deep clone.
+ * @param {Function} [customizer] The function to customize cloning values.
+ * @param {string} [key] The key of `value`.
+ * @param {Object} [object] The object `value` belongs to.
+ * @param {Array} [stackA=[]] Tracks traversed source objects.
+ * @param {Array} [stackB=[]] Associates clones with source counterparts.
+ * @returns {*} Returns the cloned value.
+ */
+ function baseClone(value, isDeep, customizer, key, object, stackA, stackB) {
+ var result;
+ if (customizer) {
+ result = object ? customizer(value, key, object) : customizer(value);
+ }
+ if (result !== undefined) {
+ return result;
+ }
+ if (!isObject(value)) {
+ return value;
+ }
+ var isArr = isArray(value);
+ if (isArr) {
+ result = initCloneArray(value);
+ if (!isDeep) {
+ return arrayCopy(value, result);
+ }
+ } else {
+ var tag = objToString.call(value), isFunc = tag == funcTag;
+ if (tag == objectTag || tag == argsTag || isFunc && !object) {
+ result = initCloneObject(isFunc ? {} : value);
+ if (!isDeep) {
+ return baseAssign(result, value);
+ }
+ } else {
+ return cloneableTags[tag] ? initCloneByTag(value, tag, isDeep) : object ? value : {};
+ }
+ }
+ // Check for circular references and return its corresponding clone.
+ stackA || (stackA = []);
+ stackB || (stackB = []);
+ var length = stackA.length;
+ while (length--) {
+ if (stackA[length] == value) {
+ return stackB[length];
+ }
+ }
+ // Add the source value to the stack of traversed objects and associate it with its clone.
+ stackA.push(value);
+ stackB.push(result);
+ // Recursively populate clone (susceptible to call stack limits).
+ (isArr ? arrayEach : baseForOwn)(value, function (subValue, key) {
+ result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB);
+ });
+ return result;
+ }
+ /**
+ * The base implementation of `_.create` without support for assigning
+ * properties to the created object.
+ *
+ * @private
+ * @param {Object} prototype The object to inherit from.
+ * @returns {Object} Returns the new object.
+ */
+ var baseCreate = function () {
+ function object() {
+ }
+ return function (prototype) {
+ if (isObject(prototype)) {
+ object.prototype = prototype;
+ var result = new object();
+ object.prototype = undefined;
+ }
+ return result || {};
+ };
+ }();
+ /**
+ * The base implementation of `_.delay` and `_.defer` which accepts an index
+ * of where to slice the arguments to provide to `func`.
+ *
+ * @private
+ * @param {Function} func The function to delay.
+ * @param {number} wait The number of milliseconds to delay invocation.
+ * @param {Object} args The arguments provide to `func`.
+ * @returns {number} Returns the timer id.
+ */
+ function baseDelay(func, wait, args) {
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ return setTimeout(function () {
+ func.apply(undefined, args);
+ }, wait);
+ }
+ /**
+ * The base implementation of `_.difference` which accepts a single array
+ * of values to exclude.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {Array} values The values to exclude.
+ * @returns {Array} Returns the new array of filtered values.
+ */
+ function baseDifference(array, values) {
+ var length = array ? array.length : 0, result = [];
+ if (!length) {
+ return result;
+ }
+ var index = -1, indexOf = getIndexOf(), isCommon = indexOf === baseIndexOf, cache = isCommon && values.length >= LARGE_ARRAY_SIZE ? createCache(values) : null, valuesLength = values.length;
+ if (cache) {
+ indexOf = cacheIndexOf;
+ isCommon = false;
+ values = cache;
+ }
+ outer:
+ while (++index < length) {
+ var value = array[index];
+ if (isCommon && value === value) {
+ var valuesIndex = valuesLength;
+ while (valuesIndex--) {
+ if (values[valuesIndex] === value) {
+ continue outer;
+ }
+ }
+ result.push(value);
+ } else if (indexOf(values, value, 0) < 0) {
+ result.push(value);
+ }
+ }
+ return result;
+ }
+ /**
+ * The base implementation of `_.forEach` without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array|Object|string} Returns `collection`.
+ */
+ var baseEach = createBaseEach(baseForOwn);
+ /**
+ * The base implementation of `_.forEachRight` without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array|Object|string} Returns `collection`.
+ */
+ var baseEachRight = createBaseEach(baseForOwnRight, true);
+ /**
+ * The base implementation of `_.every` without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if all elements pass the predicate check,
+ * else `false`
+ */
+ function baseEvery(collection, predicate) {
+ var result = true;
+ baseEach(collection, function (value, index, collection) {
+ result = !!predicate(value, index, collection);
+ return result;
+ });
+ return result;
+ }
+ /**
+ * Gets the extremum value of `collection` invoking `iteratee` for each value
+ * in `collection` to generate the criterion by which the value is ranked.
+ * The `iteratee` is invoked with three arguments: (value, index|key, collection).
+ *
+ * @private
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {Function} comparator The function used to compare values.
+ * @param {*} exValue The initial extremum value.
+ * @returns {*} Returns the extremum value.
+ */
+ function baseExtremum(collection, iteratee, comparator, exValue) {
+ var computed = exValue, result = computed;
+ baseEach(collection, function (value, index, collection) {
+ var current = +iteratee(value, index, collection);
+ if (comparator(current, computed) || current === exValue && current === result) {
+ computed = current;
+ result = value;
+ }
+ });
+ return result;
+ }
+ /**
+ * The base implementation of `_.fill` without an iteratee call guard.
+ *
+ * @private
+ * @param {Array} array The array to fill.
+ * @param {*} value The value to fill `array` with.
+ * @param {number} [start=0] The start position.
+ * @param {number} [end=array.length] The end position.
+ * @returns {Array} Returns `array`.
+ */
+ function baseFill(array, value, start, end) {
+ var length = array.length;
+ start = start == null ? 0 : +start || 0;
+ if (start < 0) {
+ start = -start > length ? 0 : length + start;
+ }
+ end = end === undefined || end > length ? length : +end || 0;
+ if (end < 0) {
+ end += length;
+ }
+ length = start > end ? 0 : end >>> 0;
+ start >>>= 0;
+ while (start < length) {
+ array[start++] = value;
+ }
+ return array;
+ }
+ /**
+ * The base implementation of `_.filter` without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {Array} Returns the new filtered array.
+ */
+ function baseFilter(collection, predicate) {
+ var result = [];
+ baseEach(collection, function (value, index, collection) {
+ if (predicate(value, index, collection)) {
+ result.push(value);
+ }
+ });
+ return result;
+ }
+ /**
+ * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
+ * without support for callback shorthands and `this` binding, which iterates
+ * over `collection` using the provided `eachFunc`.
+ *
+ * @private
+ * @param {Array|Object|string} collection The collection to search.
+ * @param {Function} predicate The function invoked per iteration.
+ * @param {Function} eachFunc The function to iterate over `collection`.
+ * @param {boolean} [retKey] Specify returning the key of the found element
+ * instead of the element itself.
+ * @returns {*} Returns the found element or its key, else `undefined`.
+ */
+ function baseFind(collection, predicate, eachFunc, retKey) {
+ var result;
+ eachFunc(collection, function (value, key, collection) {
+ if (predicate(value, key, collection)) {
+ result = retKey ? key : value;
+ return false;
+ }
+ });
+ return result;
+ }
+ /**
+ * The base implementation of `_.flatten` with added support for restricting
+ * flattening and specifying the start index.
+ *
+ * @private
+ * @param {Array} array The array to flatten.
+ * @param {boolean} [isDeep] Specify a deep flatten.
+ * @param {boolean} [isStrict] Restrict flattening to arrays-like objects.
+ * @param {Array} [result=[]] The initial result value.
+ * @returns {Array} Returns the new flattened array.
+ */
+ function baseFlatten(array, isDeep, isStrict, result) {
+ result || (result = []);
+ var index = -1, length = array.length;
+ while (++index < length) {
+ var value = array[index];
+ if (isObjectLike(value) && isArrayLike(value) && (isStrict || isArray(value) || isArguments(value))) {
+ if (isDeep) {
+ // Recursively flatten arrays (susceptible to call stack limits).
+ baseFlatten(value, isDeep, isStrict, result);
+ } else {
+ arrayPush(result, value);
+ }
+ } else if (!isStrict) {
+ result[result.length] = value;
+ }
+ }
+ return result;
+ }
+ /**
+ * The base implementation of `baseForIn` and `baseForOwn` which iterates
+ * over `object` properties returned by `keysFunc` invoking `iteratee` for
+ * each property. Iteratee functions may exit iteration early by explicitly
+ * returning `false`.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {Function} keysFunc The function to get the keys of `object`.
+ * @returns {Object} Returns `object`.
+ */
+ var baseFor = createBaseFor();
+ /**
+ * This function is like `baseFor` except that it iterates over properties
+ * in the opposite order.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {Function} keysFunc The function to get the keys of `object`.
+ * @returns {Object} Returns `object`.
+ */
+ var baseForRight = createBaseFor(true);
+ /**
+ * The base implementation of `_.forIn` without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Object} Returns `object`.
+ */
+ function baseForIn(object, iteratee) {
+ return baseFor(object, iteratee, keysIn);
+ }
+ /**
+ * The base implementation of `_.forOwn` without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Object} Returns `object`.
+ */
+ function baseForOwn(object, iteratee) {
+ return baseFor(object, iteratee, keys);
+ }
+ /**
+ * The base implementation of `_.forOwnRight` without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Object} Returns `object`.
+ */
+ function baseForOwnRight(object, iteratee) {
+ return baseForRight(object, iteratee, keys);
+ }
+ /**
+ * The base implementation of `_.functions` which creates an array of
+ * `object` function property names filtered from those provided.
+ *
+ * @private
+ * @param {Object} object The object to inspect.
+ * @param {Array} props The property names to filter.
+ * @returns {Array} Returns the new array of filtered property names.
+ */
+ function baseFunctions(object, props) {
+ var index = -1, length = props.length, resIndex = -1, result = [];
+ while (++index < length) {
+ var key = props[index];
+ if (isFunction(object[key])) {
+ result[++resIndex] = key;
+ }
+ }
+ return result;
+ }
+ /**
+ * The base implementation of `get` without support for string paths
+ * and default values.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array} path The path of the property to get.
+ * @param {string} [pathKey] The key representation of path.
+ * @returns {*} Returns the resolved value.
+ */
+ function baseGet(object, path, pathKey) {
+ if (object == null) {
+ return;
+ }
+ if (pathKey !== undefined && pathKey in toObject(object)) {
+ path = [pathKey];
+ }
+ var index = 0, length = path.length;
+ while (object != null && index < length) {
+ object = object[path[index++]];
+ }
+ return index && index == length ? object : undefined;
+ }
+ /**
+ * The base implementation of `_.isEqual` without support for `this` binding
+ * `customizer` functions.
+ *
+ * @private
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @param {Function} [customizer] The function to customize comparing values.
+ * @param {boolean} [isLoose] Specify performing partial comparisons.
+ * @param {Array} [stackA] Tracks traversed `value` objects.
+ * @param {Array} [stackB] Tracks traversed `other` objects.
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+ */
+ function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
+ if (value === other) {
+ return true;
+ }
+ if (value == null || other == null || !isObject(value) && !isObjectLike(other)) {
+ return value !== value && other !== other;
+ }
+ return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
+ }
+ /**
+ * A specialized version of `baseIsEqual` for arrays and objects which performs
+ * deep comparisons and tracks traversed objects enabling objects with circular
+ * references to be compared.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Function} [customizer] The function to customize comparing objects.
+ * @param {boolean} [isLoose] Specify performing partial comparisons.
+ * @param {Array} [stackA=[]] Tracks traversed `value` objects.
+ * @param {Array} [stackB=[]] Tracks traversed `other` objects.
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ */
+ function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
+ var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag;
+ if (!objIsArr) {
+ objTag = objToString.call(object);
+ if (objTag == argsTag) {
+ objTag = objectTag;
+ } else if (objTag != objectTag) {
+ objIsArr = isTypedArray(object);
+ }
+ }
+ if (!othIsArr) {
+ othTag = objToString.call(other);
+ if (othTag == argsTag) {
+ othTag = objectTag;
+ } else if (othTag != objectTag) {
+ othIsArr = isTypedArray(other);
+ }
+ }
+ var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag;
+ if (isSameTag && !(objIsArr || objIsObj)) {
+ return equalByTag(object, other, objTag);
+ }
+ if (!isLoose) {
+ var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
+ if (objIsWrapped || othIsWrapped) {
+ return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB);
+ }
+ }
+ if (!isSameTag) {
+ return false;
+ }
+ // Assume cyclic values are equal.
+ // For more information on detecting circular references see https://es5.github.io/#JO.
+ stackA || (stackA = []);
+ stackB || (stackB = []);
+ var length = stackA.length;
+ while (length--) {
+ if (stackA[length] == object) {
+ return stackB[length] == other;
+ }
+ }
+ // Add `object` and `other` to the stack of traversed objects.
+ stackA.push(object);
+ stackB.push(other);
+ var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB);
+ stackA.pop();
+ stackB.pop();
+ return result;
+ }
+ /**
+ * The base implementation of `_.isMatch` without support for callback
+ * shorthands and `this` binding.
+ *
+ * @private
+ * @param {Object} object The object to inspect.
+ * @param {Array} matchData The propery names, values, and compare flags to match.
+ * @param {Function} [customizer] The function to customize comparing objects.
+ * @returns {boolean} Returns `true` if `object` is a match, else `false`.
+ */
+ function baseIsMatch(object, matchData, customizer) {
+ var index = matchData.length, length = index, noCustomizer = !customizer;
+ if (object == null) {
+ return !length;
+ }
+ object = toObject(object);
+ while (index--) {
+ var data = matchData[index];
+ if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
+ return false;
+ }
+ }
+ while (++index < length) {
+ data = matchData[index];
+ var key = data[0], objValue = object[key], srcValue = data[1];
+ if (noCustomizer && data[2]) {
+ if (objValue === undefined && !(key in object)) {
+ return false;
+ }
+ } else {
+ var result = customizer ? customizer(objValue, srcValue, key) : undefined;
+ if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+ /**
+ * The base implementation of `_.map` without support for callback shorthands
+ * and `this` binding.
+ *
+ * @private
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns the new mapped array.
+ */
+ function baseMap(collection, iteratee) {
+ var index = -1, result = isArrayLike(collection) ? Array(collection.length) : [];
+ baseEach(collection, function (value, key, collection) {
+ result[++index] = iteratee(value, key, collection);
+ });
+ return result;
+ }
+ /**
+ * The base implementation of `_.matches` which does not clone `source`.
+ *
+ * @private
+ * @param {Object} source The object of property values to match.
+ * @returns {Function} Returns the new function.
+ */
+ function baseMatches(source) {
+ var matchData = getMatchData(source);
+ if (matchData.length == 1 && matchData[0][2]) {
+ var key = matchData[0][0], value = matchData[0][1];
+ return function (object) {
+ if (object == null) {
+ return false;
+ }
+ return object[key] === value && (value !== undefined || key in toObject(object));
+ };
+ }
+ return function (object) {
+ return baseIsMatch(object, matchData);
+ };
+ }
+ /**
+ * The base implementation of `_.matchesProperty` which does not clone `srcValue`.
+ *
+ * @private
+ * @param {string} path The path of the property to get.
+ * @param {*} srcValue The value to compare.
+ * @returns {Function} Returns the new function.
+ */
+ function baseMatchesProperty(path, srcValue) {
+ var isArr = isArray(path), isCommon = isKey(path) && isStrictComparable(srcValue), pathKey = path + '';
+ path = toPath(path);
+ return function (object) {
+ if (object == null) {
+ return false;
+ }
+ var key = pathKey;
+ object = toObject(object);
+ if ((isArr || !isCommon) && !(key in object)) {
+ object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
+ if (object == null) {
+ return false;
+ }
+ key = last(path);
+ object = toObject(object);
+ }
+ return object[key] === srcValue ? srcValue !== undefined || key in object : baseIsEqual(srcValue, object[key], undefined, true);
+ };
+ }
+ /**
+ * The base implementation of `_.merge` without support for argument juggling,
+ * multiple sources, and `this` binding `customizer` functions.
+ *
+ * @private
+ * @param {Object} object The destination object.
+ * @param {Object} source The source object.
+ * @param {Function} [customizer] The function to customize merged values.
+ * @param {Array} [stackA=[]] Tracks traversed source objects.
+ * @param {Array} [stackB=[]] Associates values with source counterparts.
+ * @returns {Object} Returns `object`.
+ */
+ function baseMerge(object, source, customizer, stackA, stackB) {
+ if (!isObject(object)) {
+ return object;
+ }
+ var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)), props = isSrcArr ? undefined : keys(source);
+ arrayEach(props || source, function (srcValue, key) {
+ if (props) {
+ key = srcValue;
+ srcValue = source[key];
+ }
+ if (isObjectLike(srcValue)) {
+ stackA || (stackA = []);
+ stackB || (stackB = []);
+ baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
+ } else {
+ var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined;
+ if (isCommon) {
+ result = srcValue;
+ }
+ if ((result !== undefined || isSrcArr && !(key in object)) && (isCommon || (result === result ? result !== value : value === value))) {
+ object[key] = result;
+ }
+ }
+ });
+ return object;
+ }
+ /**
+ * A specialized version of `baseMerge` for arrays and objects which performs
+ * deep merges and tracks traversed objects enabling objects with circular
+ * references to be merged.
+ *
+ * @private
+ * @param {Object} object The destination object.
+ * @param {Object} source The source object.
+ * @param {string} key The key of the value to merge.
+ * @param {Function} mergeFunc The function to merge values.
+ * @param {Function} [customizer] The function to customize merged values.
+ * @param {Array} [stackA=[]] Tracks traversed source objects.
+ * @param {Array} [stackB=[]] Associates values with source counterparts.
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ */
+ function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
+ var length = stackA.length, srcValue = source[key];
+ while (length--) {
+ if (stackA[length] == srcValue) {
+ object[key] = stackB[length];
+ return;
+ }
+ }
+ var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined;
+ if (isCommon) {
+ result = srcValue;
+ if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
+ result = isArray(value) ? value : isArrayLike(value) ? arrayCopy(value) : [];
+ } else if (isPlainObject(srcValue) || isArguments(srcValue)) {
+ result = isArguments(value) ? toPlainObject(value) : isPlainObject(value) ? value : {};
+ } else {
+ isCommon = false;
+ }
+ }
+ // Add the source value to the stack of traversed objects and associate
+ // it with its merged value.
+ stackA.push(srcValue);
+ stackB.push(result);
+ if (isCommon) {
+ // Recursively merge objects and arrays (susceptible to call stack limits).
+ object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
+ } else if (result === result ? result !== value : value === value) {
+ object[key] = result;
+ }
+ }
+ /**
+ * The base implementation of `_.property` without support for deep paths.
+ *
+ * @private
+ * @param {string} key The key of the property to get.
+ * @returns {Function} Returns the new function.
+ */
+ function baseProperty(key) {
+ return function (object) {
+ return object == null ? undefined : object[key];
+ };
+ }
+ /**
+ * A specialized version of `baseProperty` which supports deep paths.
+ *
+ * @private
+ * @param {Array|string} path The path of the property to get.
+ * @returns {Function} Returns the new function.
+ */
+ function basePropertyDeep(path) {
+ var pathKey = path + '';
+ path = toPath(path);
+ return function (object) {
+ return baseGet(object, path, pathKey);
+ };
+ }
+ /**
+ * The base implementation of `_.pullAt` without support for individual
+ * index arguments and capturing the removed elements.
+ *
+ * @private
+ * @param {Array} array The array to modify.
+ * @param {number[]} indexes The indexes of elements to remove.
+ * @returns {Array} Returns `array`.
+ */
+ function basePullAt(array, indexes) {
+ var length = array ? indexes.length : 0;
+ while (length--) {
+ var index = indexes[length];
+ if (index != previous && isIndex(index)) {
+ var previous = index;
+ splice.call(array, index, 1);
+ }
+ }
+ return array;
+ }
+ /**
+ * The base implementation of `_.random` without support for argument juggling
+ * and returning floating-point numbers.
+ *
+ * @private
+ * @param {number} min The minimum possible value.
+ * @param {number} max The maximum possible value.
+ * @returns {number} Returns the random number.
+ */
+ function baseRandom(min, max) {
+ return min + nativeFloor(nativeRandom() * (max - min + 1));
+ }
+ /**
+ * The base implementation of `_.reduce` and `_.reduceRight` without support
+ * for callback shorthands and `this` binding, which iterates over `collection`
+ * using the provided `eachFunc`.
+ *
+ * @private
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {*} accumulator The initial value.
+ * @param {boolean} initFromCollection Specify using the first or last element
+ * of `collection` as the initial value.
+ * @param {Function} eachFunc The function to iterate over `collection`.
+ * @returns {*} Returns the accumulated value.
+ */
+ function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) {
+ eachFunc(collection, function (value, index, collection) {
+ accumulator = initFromCollection ? (initFromCollection = false, value) : iteratee(accumulator, value, index, collection);
+ });
+ return accumulator;
+ }
+ /**
+ * The base implementation of `setData` without support for hot loop detection.
+ *
+ * @private
+ * @param {Function} func The function to associate metadata with.
+ * @param {*} data The metadata.
+ * @returns {Function} Returns `func`.
+ */
+ var baseSetData = !metaMap ? identity : function (func, data) {
+ metaMap.set(func, data);
+ return func;
+ };
+ /**
+ * The base implementation of `_.slice` without an iteratee call guard.
+ *
+ * @private
+ * @param {Array} array The array to slice.
+ * @param {number} [start=0] The start position.
+ * @param {number} [end=array.length] The end position.
+ * @returns {Array} Returns the slice of `array`.
+ */
+ function baseSlice(array, start, end) {
+ var index = -1, length = array.length;
+ start = start == null ? 0 : +start || 0;
+ if (start < 0) {
+ start = -start > length ? 0 : length + start;
+ }
+ end = end === undefined || end > length ? length : +end || 0;
+ if (end < 0) {
+ end += length;
+ }
+ length = start > end ? 0 : end - start >>> 0;
+ start >>>= 0;
+ var result = Array(length);
+ while (++index < length) {
+ result[index] = array[index + start];
+ }
+ return result;
+ }
+ /**
+ * The base implementation of `_.some` without support for callback shorthands
+ * and `this` binding.
+ *
+ * @private
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if any element passes the predicate check,
+ * else `false`.
+ */
+ function baseSome(collection, predicate) {
+ var result;
+ baseEach(collection, function (value, index, collection) {
+ result = predicate(value, index, collection);
+ return !result;
+ });
+ return !!result;
+ }
+ /**
+ * The base implementation of `_.sortBy` which uses `comparer` to define
+ * the sort order of `array` and replaces criteria objects with their
+ * corresponding values.
+ *
+ * @private
+ * @param {Array} array The array to sort.
+ * @param {Function} comparer The function to define sort order.
+ * @returns {Array} Returns `array`.
+ */
+ function baseSortBy(array, comparer) {
+ var length = array.length;
+ array.sort(comparer);
+ while (length--) {
+ array[length] = array[length].value;
+ }
+ return array;
+ }
+ /**
+ * The base implementation of `_.sortByOrder` without param guards.
+ *
+ * @private
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
+ * @param {boolean[]} orders The sort orders of `iteratees`.
+ * @returns {Array} Returns the new sorted array.
+ */
+ function baseSortByOrder(collection, iteratees, orders) {
+ var callback = getCallback(), index = -1;
+ iteratees = arrayMap(iteratees, function (iteratee) {
+ return callback(iteratee);
+ });
+ var result = baseMap(collection, function (value) {
+ var criteria = arrayMap(iteratees, function (iteratee) {
+ return iteratee(value);
+ });
+ return {
+ 'criteria': criteria,
+ 'index': ++index,
+ 'value': value
+ };
+ });
+ return baseSortBy(result, function (object, other) {
+ return compareMultiple(object, other, orders);
+ });
+ }
+ /**
+ * The base implementation of `_.sum` without support for callback shorthands
+ * and `this` binding.
+ *
+ * @private
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {number} Returns the sum.
+ */
+ function baseSum(collection, iteratee) {
+ var result = 0;
+ baseEach(collection, function (value, index, collection) {
+ result += +iteratee(value, index, collection) || 0;
+ });
+ return result;
+ }
+ /**
+ * The base implementation of `_.uniq` without support for callback shorthands
+ * and `this` binding.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {Function} [iteratee] The function invoked per iteration.
+ * @returns {Array} Returns the new duplicate free array.
+ */
+ function baseUniq(array, iteratee) {
+ var index = -1, indexOf = getIndexOf(), length = array.length, isCommon = indexOf === baseIndexOf, isLarge = isCommon && length >= LARGE_ARRAY_SIZE, seen = isLarge ? createCache() : null, result = [];
+ if (seen) {
+ indexOf = cacheIndexOf;
+ isCommon = false;
+ } else {
+ isLarge = false;
+ seen = iteratee ? [] : result;
+ }
+ outer:
+ while (++index < length) {
+ var value = array[index], computed = iteratee ? iteratee(value, index, array) : value;
+ if (isCommon && value === value) {
+ var seenIndex = seen.length;
+ while (seenIndex--) {
+ if (seen[seenIndex] === computed) {
+ continue outer;
+ }
+ }
+ if (iteratee) {
+ seen.push(computed);
+ }
+ result.push(value);
+ } else if (indexOf(seen, computed, 0) < 0) {
+ if (iteratee || isLarge) {
+ seen.push(computed);
+ }
+ result.push(value);
+ }
+ }
+ return result;
+ }
+ /**
+ * The base implementation of `_.values` and `_.valuesIn` which creates an
+ * array of `object` property values corresponding to the property names
+ * of `props`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array} props The property names to get values for.
+ * @returns {Object} Returns the array of property values.
+ */
+ function baseValues(object, props) {
+ var index = -1, length = props.length, result = Array(length);
+ while (++index < length) {
+ result[index] = object[props[index]];
+ }
+ return result;
+ }
+ /**
+ * The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`,
+ * and `_.takeWhile` without support for callback shorthands and `this` binding.
+ *
+ * @private
+ * @param {Array} array The array to query.
+ * @param {Function} predicate The function invoked per iteration.
+ * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Array} Returns the slice of `array`.
+ */
+ function baseWhile(array, predicate, isDrop, fromRight) {
+ var length = array.length, index = fromRight ? length : -1;
+ while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {
+ }
+ return isDrop ? baseSlice(array, fromRight ? 0 : index, fromRight ? index + 1 : length) : baseSlice(array, fromRight ? index + 1 : 0, fromRight ? length : index);
+ }
+ /**
+ * The base implementation of `wrapperValue` which returns the result of
+ * performing a sequence of actions on the unwrapped `value`, where each
+ * successive action is supplied the return value of the previous.
+ *
+ * @private
+ * @param {*} value The unwrapped value.
+ * @param {Array} actions Actions to peform to resolve the unwrapped value.
+ * @returns {*} Returns the resolved value.
+ */
+ function baseWrapperValue(value, actions) {
+ var result = value;
+ if (result instanceof LazyWrapper) {
+ result = result.value();
+ }
+ var index = -1, length = actions.length;
+ while (++index < length) {
+ var action = actions[index];
+ result = action.func.apply(action.thisArg, arrayPush([result], action.args));
+ }
+ return result;
+ }
+ /**
+ * Performs a binary search of `array` to determine the index at which `value`
+ * should be inserted into `array` in order to maintain its sort order.
+ *
+ * @private
+ * @param {Array} array The sorted array to inspect.
+ * @param {*} value The value to evaluate.
+ * @param {boolean} [retHighest] Specify returning the highest qualified index.
+ * @returns {number} Returns the index at which `value` should be inserted
+ * into `array`.
+ */
+ function binaryIndex(array, value, retHighest) {
+ var low = 0, high = array ? array.length : low;
+ if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
+ while (low < high) {
+ var mid = low + high >>> 1, computed = array[mid];
+ if ((retHighest ? computed <= value : computed < value) && computed !== null) {
+ low = mid + 1;
+ } else {
+ high = mid;
+ }
+ }
+ return high;
+ }
+ return binaryIndexBy(array, value, identity, retHighest);
+ }
+ /**
+ * This function is like `binaryIndex` except that it invokes `iteratee` for
+ * `value` and each element of `array` to compute their sort ranking. The
+ * iteratee is invoked with one argument; (value).
+ *
+ * @private
+ * @param {Array} array The sorted array to inspect.
+ * @param {*} value The value to evaluate.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {boolean} [retHighest] Specify returning the highest qualified index.
+ * @returns {number} Returns the index at which `value` should be inserted
+ * into `array`.
+ */
+ function binaryIndexBy(array, value, iteratee, retHighest) {
+ value = iteratee(value);
+ var low = 0, high = array ? array.length : 0, valIsNaN = value !== value, valIsNull = value === null, valIsUndef = value === undefined;
+ while (low < high) {
+ var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), isDef = computed !== undefined, isReflexive = computed === computed;
+ if (valIsNaN) {
+ var setLow = isReflexive || retHighest;
+ } else if (valIsNull) {
+ setLow = isReflexive && isDef && (retHighest || computed != null);
+ } else if (valIsUndef) {
+ setLow = isReflexive && (retHighest || isDef);
+ } else if (computed == null) {
+ setLow = false;
+ } else {
+ setLow = retHighest ? computed <= value : computed < value;
+ }
+ if (setLow) {
+ low = mid + 1;
+ } else {
+ high = mid;
+ }
+ }
+ return nativeMin(high, MAX_ARRAY_INDEX);
+ }
+ /**
+ * A specialized version of `baseCallback` which only supports `this` binding
+ * and specifying the number of arguments to provide to `func`.
+ *
+ * @private
+ * @param {Function} func The function to bind.
+ * @param {*} thisArg The `this` binding of `func`.
+ * @param {number} [argCount] The number of arguments to provide to `func`.
+ * @returns {Function} Returns the callback.
+ */
+ function bindCallback(func, thisArg, argCount) {
+ if (typeof func != 'function') {
+ return identity;
+ }
+ if (thisArg === undefined) {
+ return func;
+ }
+ switch (argCount) {
+ case 1:
+ return function (value) {
+ return func.call(thisArg, value);
+ };
+ case 3:
+ return function (value, index, collection) {
+ return func.call(thisArg, value, index, collection);
+ };
+ case 4:
+ return function (accumulator, value, index, collection) {
+ return func.call(thisArg, accumulator, value, index, collection);
+ };
+ case 5:
+ return function (value, other, key, object, source) {
+ return func.call(thisArg, value, other, key, object, source);
+ };
+ }
+ return function () {
+ return func.apply(thisArg, arguments);
+ };
+ }
+ /**
+ * Creates a clone of the given array buffer.
+ *
+ * @private
+ * @param {ArrayBuffer} buffer The array buffer to clone.
+ * @returns {ArrayBuffer} Returns the cloned array buffer.
+ */
+ function bufferClone(buffer) {
+ var result = new ArrayBuffer(buffer.byteLength), view = new Uint8Array(result);
+ view.set(new Uint8Array(buffer));
+ return result;
+ }
+ /**
+ * Creates an array that is the composition of partially applied arguments,
+ * placeholders, and provided arguments into a single array of arguments.
+ *
+ * @private
+ * @param {Array|Object} args The provided arguments.
+ * @param {Array} partials The arguments to prepend to those provided.
+ * @param {Array} holders The `partials` placeholder indexes.
+ * @returns {Array} Returns the new array of composed arguments.
+ */
+ function composeArgs(args, partials, holders) {
+ var holdersLength = holders.length, argsIndex = -1, argsLength = nativeMax(args.length - holdersLength, 0), leftIndex = -1, leftLength = partials.length, result = Array(leftLength + argsLength);
+ while (++leftIndex < leftLength) {
+ result[leftIndex] = partials[leftIndex];
+ }
+ while (++argsIndex < holdersLength) {
+ result[holders[argsIndex]] = args[argsIndex];
+ }
+ while (argsLength--) {
+ result[leftIndex++] = args[argsIndex++];
+ }
+ return result;
+ }
+ /**
+ * This function is like `composeArgs` except that the arguments composition
+ * is tailored for `_.partialRight`.
+ *
+ * @private
+ * @param {Array|Object} args The provided arguments.
+ * @param {Array} partials The arguments to append to those provided.
+ * @param {Array} holders The `partials` placeholder indexes.
+ * @returns {Array} Returns the new array of composed arguments.
+ */
+ function composeArgsRight(args, partials, holders) {
+ var holdersIndex = -1, holdersLength = holders.length, argsIndex = -1, argsLength = nativeMax(args.length - holdersLength, 0), rightIndex = -1, rightLength = partials.length, result = Array(argsLength + rightLength);
+ while (++argsIndex < argsLength) {
+ result[argsIndex] = args[argsIndex];
+ }
+ var offset = argsIndex;
+ while (++rightIndex < rightLength) {
+ result[offset + rightIndex] = partials[rightIndex];
+ }
+ while (++holdersIndex < holdersLength) {
+ result[offset + holders[holdersIndex]] = args[argsIndex++];
+ }
+ return result;
+ }
+ /**
+ * Creates a `_.countBy`, `_.groupBy`, `_.indexBy`, or `_.partition` function.
+ *
+ * @private
+ * @param {Function} setter The function to set keys and values of the accumulator object.
+ * @param {Function} [initializer] The function to initialize the accumulator object.
+ * @returns {Function} Returns the new aggregator function.
+ */
+ function createAggregator(setter, initializer) {
+ return function (collection, iteratee, thisArg) {
+ var result = initializer ? initializer() : {};
+ iteratee = getCallback(iteratee, thisArg, 3);
+ if (isArray(collection)) {
+ var index = -1, length = collection.length;
+ while (++index < length) {
+ var value = collection[index];
+ setter(result, value, iteratee(value, index, collection), collection);
+ }
+ } else {
+ baseEach(collection, function (value, key, collection) {
+ setter(result, value, iteratee(value, key, collection), collection);
+ });
+ }
+ return result;
+ };
+ }
+ /**
+ * Creates a `_.assign`, `_.defaults`, or `_.merge` function.
+ *
+ * @private
+ * @param {Function} assigner The function to assign values.
+ * @returns {Function} Returns the new assigner function.
+ */
+ function createAssigner(assigner) {
+ return restParam(function (object, sources) {
+ var index = -1, length = object == null ? 0 : sources.length, customizer = length > 2 ? sources[length - 2] : undefined, guard = length > 2 ? sources[2] : undefined, thisArg = length > 1 ? sources[length - 1] : undefined;
+ if (typeof customizer == 'function') {
+ customizer = bindCallback(customizer, thisArg, 5);
+ length -= 2;
+ } else {
+ customizer = typeof thisArg == 'function' ? thisArg : undefined;
+ length -= customizer ? 1 : 0;
+ }
+ if (guard && isIterateeCall(sources[0], sources[1], guard)) {
+ customizer = length < 3 ? undefined : customizer;
+ length = 1;
+ }
+ while (++index < length) {
+ var source = sources[index];
+ if (source) {
+ assigner(object, source, customizer);
+ }
+ }
+ return object;
+ });
+ }
+ /**
+ * Creates a `baseEach` or `baseEachRight` function.
+ *
+ * @private
+ * @param {Function} eachFunc The function to iterate over a collection.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new base function.
+ */
+ function createBaseEach(eachFunc, fromRight) {
+ return function (collection, iteratee) {
+ var length = collection ? getLength(collection) : 0;
+ if (!isLength(length)) {
+ return eachFunc(collection, iteratee);
+ }
+ var index = fromRight ? length : -1, iterable = toObject(collection);
+ while (fromRight ? index-- : ++index < length) {
+ if (iteratee(iterable[index], index, iterable) === false) {
+ break;
+ }
+ }
+ return collection;
+ };
+ }
+ /**
+ * Creates a base function for `_.forIn` or `_.forInRight`.
+ *
+ * @private
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new base function.
+ */
+ function createBaseFor(fromRight) {
+ return function (object, iteratee, keysFunc) {
+ var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1;
+ while (fromRight ? index-- : ++index < length) {
+ var key = props[index];
+ if (iteratee(iterable[key], key, iterable) === false) {
+ break;
+ }
+ }
+ return object;
+ };
+ }
+ /**
+ * Creates a function that wraps `func` and invokes it with the `this`
+ * binding of `thisArg`.
+ *
+ * @private
+ * @param {Function} func The function to bind.
+ * @param {*} [thisArg] The `this` binding of `func`.
+ * @returns {Function} Returns the new bound function.
+ */
+ function createBindWrapper(func, thisArg) {
+ var Ctor = createCtorWrapper(func);
+ function wrapper() {
+ var fn = this && this !== root && this instanceof wrapper ? Ctor : func;
+ return fn.apply(thisArg, arguments);
+ }
+ return wrapper;
+ }
+ /**
+ * Creates a `Set` cache object to optimize linear searches of large arrays.
+ *
+ * @private
+ * @param {Array} [values] The values to cache.
+ * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`.
+ */
+ function createCache(values) {
+ return nativeCreate && Set ? new SetCache(values) : null;
+ }
+ /**
+ * Creates a function that produces compound words out of the words in a
+ * given string.
+ *
+ * @private
+ * @param {Function} callback The function to combine each word.
+ * @returns {Function} Returns the new compounder function.
+ */
+ function createCompounder(callback) {
+ return function (string) {
+ var index = -1, array = words(deburr(string)), length = array.length, result = '';
+ while (++index < length) {
+ result = callback(result, array[index], index);
+ }
+ return result;
+ };
+ }
+ /**
+ * Creates a function that produces an instance of `Ctor` regardless of
+ * whether it was invoked as part of a `new` expression or by `call` or `apply`.
+ *
+ * @private
+ * @param {Function} Ctor The constructor to wrap.
+ * @returns {Function} Returns the new wrapped function.
+ */
+ function createCtorWrapper(Ctor) {
+ return function () {
+ // Use a `switch` statement to work with class constructors.
+ // See http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
+ // for more details.
+ var args = arguments;
+ switch (args.length) {
+ case 0:
+ return new Ctor();
+ case 1:
+ return new Ctor(args[0]);
+ case 2:
+ return new Ctor(args[0], args[1]);
+ case 3:
+ return new Ctor(args[0], args[1], args[2]);
+ case 4:
+ return new Ctor(args[0], args[1], args[2], args[3]);
+ case 5:
+ return new Ctor(args[0], args[1], args[2], args[3], args[4]);
+ case 6:
+ return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
+ case 7:
+ return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
+ }
+ var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args);
+ // Mimic the constructor's `return` behavior.
+ // See https://es5.github.io/#x13.2.2 for more details.
+ return isObject(result) ? result : thisBinding;
+ };
+ }
+ /**
+ * Creates a `_.curry` or `_.curryRight` function.
+ *
+ * @private
+ * @param {boolean} flag The curry bit flag.
+ * @returns {Function} Returns the new curry function.
+ */
+ function createCurry(flag) {
+ function curryFunc(func, arity, guard) {
+ if (guard && isIterateeCall(func, arity, guard)) {
+ arity = undefined;
+ }
+ var result = createWrapper(func, flag, undefined, undefined, undefined, undefined, undefined, arity);
+ result.placeholder = curryFunc.placeholder;
+ return result;
+ }
+ return curryFunc;
+ }
+ /**
+ * Creates a `_.defaults` or `_.defaultsDeep` function.
+ *
+ * @private
+ * @param {Function} assigner The function to assign values.
+ * @param {Function} customizer The function to customize assigned values.
+ * @returns {Function} Returns the new defaults function.
+ */
+ function createDefaults(assigner, customizer) {
+ return restParam(function (args) {
+ var object = args[0];
+ if (object == null) {
+ return object;
+ }
+ args.push(customizer);
+ return assigner.apply(undefined, args);
+ });
+ }
+ /**
+ * Creates a `_.max` or `_.min` function.
+ *
+ * @private
+ * @param {Function} comparator The function used to compare values.
+ * @param {*} exValue The initial extremum value.
+ * @returns {Function} Returns the new extremum function.
+ */
+ function createExtremum(comparator, exValue) {
+ return function (collection, iteratee, thisArg) {
+ if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
+ iteratee = undefined;
+ }
+ iteratee = getCallback(iteratee, thisArg, 3);
+ if (iteratee.length == 1) {
+ collection = isArray(collection) ? collection : toIterable(collection);
+ var result = arrayExtremum(collection, iteratee, comparator, exValue);
+ if (!(collection.length && result === exValue)) {
+ return result;
+ }
+ }
+ return baseExtremum(collection, iteratee, comparator, exValue);
+ };
+ }
+ /**
+ * Creates a `_.find` or `_.findLast` function.
+ *
+ * @private
+ * @param {Function} eachFunc The function to iterate over a collection.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new find function.
+ */
+ function createFind(eachFunc, fromRight) {
+ return function (collection, predicate, thisArg) {
+ predicate = getCallback(predicate, thisArg, 3);
+ if (isArray(collection)) {
+ var index = baseFindIndex(collection, predicate, fromRight);
+ return index > -1 ? collection[index] : undefined;
+ }
+ return baseFind(collection, predicate, eachFunc);
+ };
+ }
+ /**
+ * Creates a `_.findIndex` or `_.findLastIndex` function.
+ *
+ * @private
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new find function.
+ */
+ function createFindIndex(fromRight) {
+ return function (array, predicate, thisArg) {
+ if (!(array && array.length)) {
+ return -1;
+ }
+ predicate = getCallback(predicate, thisArg, 3);
+ return baseFindIndex(array, predicate, fromRight);
+ };
+ }
+ /**
+ * Creates a `_.findKey` or `_.findLastKey` function.
+ *
+ * @private
+ * @param {Function} objectFunc The function to iterate over an object.
+ * @returns {Function} Returns the new find function.
+ */
+ function createFindKey(objectFunc) {
+ return function (object, predicate, thisArg) {
+ predicate = getCallback(predicate, thisArg, 3);
+ return baseFind(object, predicate, objectFunc, true);
+ };
+ }
+ /**
+ * Creates a `_.flow` or `_.flowRight` function.
+ *
+ * @private
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new flow function.
+ */
+ function createFlow(fromRight) {
+ return function () {
+ var wrapper, length = arguments.length, index = fromRight ? length : -1, leftIndex = 0, funcs = Array(length);
+ while (fromRight ? index-- : ++index < length) {
+ var func = funcs[leftIndex++] = arguments[index];
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ if (!wrapper && LodashWrapper.prototype.thru && getFuncName(func) == 'wrapper') {
+ wrapper = new LodashWrapper([], true);
+ }
+ }
+ index = wrapper ? -1 : length;
+ while (++index < length) {
+ func = funcs[index];
+ var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined;
+ if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) {
+ wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
+ } else {
+ wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func);
+ }
+ }
+ return function () {
+ var args = arguments, value = args[0];
+ if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) {
+ return wrapper.plant(value).value();
+ }
+ var index = 0, result = length ? funcs[index].apply(this, args) : value;
+ while (++index < length) {
+ result = funcs[index].call(this, result);
+ }
+ return result;
+ };
+ };
+ }
+ /**
+ * Creates a function for `_.forEach` or `_.forEachRight`.
+ *
+ * @private
+ * @param {Function} arrayFunc The function to iterate over an array.
+ * @param {Function} eachFunc The function to iterate over a collection.
+ * @returns {Function} Returns the new each function.
+ */
+ function createForEach(arrayFunc, eachFunc) {
+ return function (collection, iteratee, thisArg) {
+ return typeof iteratee == 'function' && thisArg === undefined && isArray(collection) ? arrayFunc(collection, iteratee) : eachFunc(collection, bindCallback(iteratee, thisArg, 3));
+ };
+ }
+ /**
+ * Creates a function for `_.forIn` or `_.forInRight`.
+ *
+ * @private
+ * @param {Function} objectFunc The function to iterate over an object.
+ * @returns {Function} Returns the new each function.
+ */
+ function createForIn(objectFunc) {
+ return function (object, iteratee, thisArg) {
+ if (typeof iteratee != 'function' || thisArg !== undefined) {
+ iteratee = bindCallback(iteratee, thisArg, 3);
+ }
+ return objectFunc(object, iteratee, keysIn);
+ };
+ }
+ /**
+ * Creates a function for `_.forOwn` or `_.forOwnRight`.
+ *
+ * @private
+ * @param {Function} objectFunc The function to iterate over an object.
+ * @returns {Function} Returns the new each function.
+ */
+ function createForOwn(objectFunc) {
+ return function (object, iteratee, thisArg) {
+ if (typeof iteratee != 'function' || thisArg !== undefined) {
+ iteratee = bindCallback(iteratee, thisArg, 3);
+ }
+ return objectFunc(object, iteratee);
+ };
+ }
+ /**
+ * Creates a function for `_.mapKeys` or `_.mapValues`.
+ *
+ * @private
+ * @param {boolean} [isMapKeys] Specify mapping keys instead of values.
+ * @returns {Function} Returns the new map function.
+ */
+ function createObjectMapper(isMapKeys) {
+ return function (object, iteratee, thisArg) {
+ var result = {};
+ iteratee = getCallback(iteratee, thisArg, 3);
+ baseForOwn(object, function (value, key, object) {
+ var mapped = iteratee(value, key, object);
+ key = isMapKeys ? mapped : key;
+ value = isMapKeys ? value : mapped;
+ result[key] = value;
+ });
+ return result;
+ };
+ }
+ /**
+ * Creates a function for `_.padLeft` or `_.padRight`.
+ *
+ * @private
+ * @param {boolean} [fromRight] Specify padding from the right.
+ * @returns {Function} Returns the new pad function.
+ */
+ function createPadDir(fromRight) {
+ return function (string, length, chars) {
+ string = baseToString(string);
+ return (fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string);
+ };
+ }
+ /**
+ * Creates a `_.partial` or `_.partialRight` function.
+ *
+ * @private
+ * @param {boolean} flag The partial bit flag.
+ * @returns {Function} Returns the new partial function.
+ */
+ function createPartial(flag) {
+ var partialFunc = restParam(function (func, partials) {
+ var holders = replaceHolders(partials, partialFunc.placeholder);
+ return createWrapper(func, flag, undefined, partials, holders);
+ });
+ return partialFunc;
+ }
+ /**
+ * Creates a function for `_.reduce` or `_.reduceRight`.
+ *
+ * @private
+ * @param {Function} arrayFunc The function to iterate over an array.
+ * @param {Function} eachFunc The function to iterate over a collection.
+ * @returns {Function} Returns the new each function.
+ */
+ function createReduce(arrayFunc, eachFunc) {
+ return function (collection, iteratee, accumulator, thisArg) {
+ var initFromArray = arguments.length < 3;
+ return typeof iteratee == 'function' && thisArg === undefined && isArray(collection) ? arrayFunc(collection, iteratee, accumulator, initFromArray) : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc);
+ };
+ }
+ /**
+ * Creates a function that wraps `func` and invokes it with optional `this`
+ * binding of, partial application, and currying.
+ *
+ * @private
+ * @param {Function|string} func The function or method name to reference.
+ * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
+ * @param {*} [thisArg] The `this` binding of `func`.
+ * @param {Array} [partials] The arguments to prepend to those provided to the new function.
+ * @param {Array} [holders] The `partials` placeholder indexes.
+ * @param {Array} [partialsRight] The arguments to append to those provided to the new function.
+ * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
+ * @param {Array} [argPos] The argument positions of the new function.
+ * @param {number} [ary] The arity cap of `func`.
+ * @param {number} [arity] The arity of `func`.
+ * @returns {Function} Returns the new wrapped function.
+ */
+ function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
+ var isAry = bitmask & ARY_FLAG, isBind = bitmask & BIND_FLAG, isBindKey = bitmask & BIND_KEY_FLAG, isCurry = bitmask & CURRY_FLAG, isCurryBound = bitmask & CURRY_BOUND_FLAG, isCurryRight = bitmask & CURRY_RIGHT_FLAG, Ctor = isBindKey ? undefined : createCtorWrapper(func);
+ function wrapper() {
+ // Avoid `arguments` object use disqualifying optimizations by
+ // converting it to an array before providing it to other functions.
+ var length = arguments.length, index = length, args = Array(length);
+ while (index--) {
+ args[index] = arguments[index];
+ }
+ if (partials) {
+ args = composeArgs(args, partials, holders);
+ }
+ if (partialsRight) {
+ args = composeArgsRight(args, partialsRight, holdersRight);
+ }
+ if (isCurry || isCurryRight) {
+ var placeholder = wrapper.placeholder, argsHolders = replaceHolders(args, placeholder);
+ length -= argsHolders.length;
+ if (length < arity) {
+ var newArgPos = argPos ? arrayCopy(argPos) : undefined, newArity = nativeMax(arity - length, 0), newsHolders = isCurry ? argsHolders : undefined, newHoldersRight = isCurry ? undefined : argsHolders, newPartials = isCurry ? args : undefined, newPartialsRight = isCurry ? undefined : args;
+ bitmask |= isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG;
+ bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
+ if (!isCurryBound) {
+ bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
+ }
+ var newData = [
+ func,
+ bitmask,
+ thisArg,
+ newPartials,
+ newsHolders,
+ newPartialsRight,
+ newHoldersRight,
+ newArgPos,
+ ary,
+ newArity
+ ], result = createHybridWrapper.apply(undefined, newData);
+ if (isLaziable(func)) {
+ setData(result, newData);
+ }
+ result.placeholder = placeholder;
+ return result;
+ }
+ }
+ var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func;
+ if (argPos) {
+ args = reorder(args, argPos);
+ }
+ if (isAry && ary < args.length) {
+ args.length = ary;
+ }
+ if (this && this !== root && this instanceof wrapper) {
+ fn = Ctor || createCtorWrapper(func);
+ }
+ return fn.apply(thisBinding, args);
+ }
+ return wrapper;
+ }
+ /**
+ * Creates the padding required for `string` based on the given `length`.
+ * The `chars` string is truncated if the number of characters exceeds `length`.
+ *
+ * @private
+ * @param {string} string The string to create padding for.
+ * @param {number} [length=0] The padding length.
+ * @param {string} [chars=' '] The string used as padding.
+ * @returns {string} Returns the pad for `string`.
+ */
+ function createPadding(string, length, chars) {
+ var strLength = string.length;
+ length = +length;
+ if (strLength >= length || !nativeIsFinite(length)) {
+ return '';
+ }
+ var padLength = length - strLength;
+ chars = chars == null ? ' ' : chars + '';
+ return repeat(chars, nativeCeil(padLength / chars.length)).slice(0, padLength);
+ }
+ /**
+ * Creates a function that wraps `func` and invokes it with the optional `this`
+ * binding of `thisArg` and the `partials` prepended to those provided to
+ * the wrapper.
+ *
+ * @private
+ * @param {Function} func The function to partially apply arguments to.
+ * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
+ * @param {*} thisArg The `this` binding of `func`.
+ * @param {Array} partials The arguments to prepend to those provided to the new function.
+ * @returns {Function} Returns the new bound function.
+ */
+ function createPartialWrapper(func, bitmask, thisArg, partials) {
+ var isBind = bitmask & BIND_FLAG, Ctor = createCtorWrapper(func);
+ function wrapper() {
+ // Avoid `arguments` object use disqualifying optimizations by
+ // converting it to an array before providing it `func`.
+ var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength);
+ while (++leftIndex < leftLength) {
+ args[leftIndex] = partials[leftIndex];
+ }
+ while (argsLength--) {
+ args[leftIndex++] = arguments[++argsIndex];
+ }
+ var fn = this && this !== root && this instanceof wrapper ? Ctor : func;
+ return fn.apply(isBind ? thisArg : this, args);
+ }
+ return wrapper;
+ }
+ /**
+ * Creates a `_.ceil`, `_.floor`, or `_.round` function.
+ *
+ * @private
+ * @param {string} methodName The name of the `Math` method to use when rounding.
+ * @returns {Function} Returns the new round function.
+ */
+ function createRound(methodName) {
+ var func = Math[methodName];
+ return function (number, precision) {
+ precision = precision === undefined ? 0 : +precision || 0;
+ if (precision) {
+ precision = pow(10, precision);
+ return func(number * precision) / precision;
+ }
+ return func(number);
+ };
+ }
+ /**
+ * Creates a `_.sortedIndex` or `_.sortedLastIndex` function.
+ *
+ * @private
+ * @param {boolean} [retHighest] Specify returning the highest qualified index.
+ * @returns {Function} Returns the new index function.
+ */
+ function createSortedIndex(retHighest) {
+ return function (array, value, iteratee, thisArg) {
+ var callback = getCallback(iteratee);
+ return iteratee == null && callback === baseCallback ? binaryIndex(array, value, retHighest) : binaryIndexBy(array, value, callback(iteratee, thisArg, 1), retHighest);
+ };
+ }
+ /**
+ * Creates a function that either curries or invokes `func` with optional
+ * `this` binding and partially applied arguments.
+ *
+ * @private
+ * @param {Function|string} func The function or method name to reference.
+ * @param {number} bitmask The bitmask of flags.
+ * The bitmask may be composed of the following flags:
+ * 1 - `_.bind`
+ * 2 - `_.bindKey`
+ * 4 - `_.curry` or `_.curryRight` of a bound function
+ * 8 - `_.curry`
+ * 16 - `_.curryRight`
+ * 32 - `_.partial`
+ * 64 - `_.partialRight`
+ * 128 - `_.rearg`
+ * 256 - `_.ary`
+ * @param {*} [thisArg] The `this` binding of `func`.
+ * @param {Array} [partials] The arguments to be partially applied.
+ * @param {Array} [holders] The `partials` placeholder indexes.
+ * @param {Array} [argPos] The argument positions of the new function.
+ * @param {number} [ary] The arity cap of `func`.
+ * @param {number} [arity] The arity of `func`.
+ * @returns {Function} Returns the new wrapped function.
+ */
+ function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
+ var isBindKey = bitmask & BIND_KEY_FLAG;
+ if (!isBindKey && typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ var length = partials ? partials.length : 0;
+ if (!length) {
+ bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
+ partials = holders = undefined;
+ }
+ length -= holders ? holders.length : 0;
+ if (bitmask & PARTIAL_RIGHT_FLAG) {
+ var partialsRight = partials, holdersRight = holders;
+ partials = holders = undefined;
+ }
+ var data = isBindKey ? undefined : getData(func), newData = [
+ func,
+ bitmask,
+ thisArg,
+ partials,
+ holders,
+ partialsRight,
+ holdersRight,
+ argPos,
+ ary,
+ arity
+ ];
+ if (data) {
+ mergeData(newData, data);
+ bitmask = newData[1];
+ arity = newData[9];
+ }
+ newData[9] = arity == null ? isBindKey ? 0 : func.length : nativeMax(arity - length, 0) || 0;
+ if (bitmask == BIND_FLAG) {
+ var result = createBindWrapper(newData[0], newData[2]);
+ } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
+ result = createPartialWrapper.apply(undefined, newData);
+ } else {
+ result = createHybridWrapper.apply(undefined, newData);
+ }
+ var setter = data ? baseSetData : setData;
+ return setter(result, newData);
+ }
+ /**
+ * A specialized version of `baseIsEqualDeep` for arrays with support for
+ * partial deep comparisons.
+ *
+ * @private
+ * @param {Array} array The array to compare.
+ * @param {Array} other The other array to compare.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Function} [customizer] The function to customize comparing arrays.
+ * @param {boolean} [isLoose] Specify performing partial comparisons.
+ * @param {Array} [stackA] Tracks traversed `value` objects.
+ * @param {Array} [stackB] Tracks traversed `other` objects.
+ * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
+ */
+ function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) {
+ var index = -1, arrLength = array.length, othLength = other.length;
+ if (arrLength != othLength && !(isLoose && othLength > arrLength)) {
+ return false;
+ }
+ // Ignore non-index properties.
+ while (++index < arrLength) {
+ var arrValue = array[index], othValue = other[index], result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined;
+ if (result !== undefined) {
+ if (result) {
+ continue;
+ }
+ return false;
+ }
+ // Recursively compare arrays (susceptible to call stack limits).
+ if (isLoose) {
+ if (!arraySome(other, function (othValue) {
+ return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
+ })) {
+ return false;
+ }
+ } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) {
+ return false;
+ }
+ }
+ return true;
+ }
+ /**
+ * A specialized version of `baseIsEqualDeep` for comparing objects of
+ * the same `toStringTag`.
+ *
+ * **Note:** This function only supports comparing values with tags of
+ * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {string} tag The `toStringTag` of the objects to compare.
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ */
+ function equalByTag(object, other, tag) {
+ switch (tag) {
+ case boolTag:
+ case dateTag:
+ // Coerce dates and booleans to numbers, dates to milliseconds and booleans
+ // to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
+ return +object == +other;
+ case errorTag:
+ return object.name == other.name && object.message == other.message;
+ case numberTag:
+ // Treat `NaN` vs. `NaN` as equal.
+ return object != +object ? other != +other : object == +other;
+ case regexpTag:
+ case stringTag:
+ // Coerce regexes to strings and treat strings primitives and string
+ // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
+ return object == other + '';
+ }
+ return false;
+ }
+ /**
+ * A specialized version of `baseIsEqualDeep` for objects with support for
+ * partial deep comparisons.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Function} [customizer] The function to customize comparing values.
+ * @param {boolean} [isLoose] Specify performing partial comparisons.
+ * @param {Array} [stackA] Tracks traversed `value` objects.
+ * @param {Array} [stackB] Tracks traversed `other` objects.
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ */
+ function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
+ var objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length;
+ if (objLength != othLength && !isLoose) {
+ return false;
+ }
+ var index = objLength;
+ while (index--) {
+ var key = objProps[index];
+ if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
+ return false;
+ }
+ }
+ var skipCtor = isLoose;
+ while (++index < objLength) {
+ key = objProps[index];
+ var objValue = object[key], othValue = other[key], result = customizer ? customizer(isLoose ? othValue : objValue, isLoose ? objValue : othValue, key) : undefined;
+ // Recursively compare objects (susceptible to call stack limits).
+ if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) {
+ return false;
+ }
+ skipCtor || (skipCtor = key == 'constructor');
+ }
+ if (!skipCtor) {
+ var objCtor = object.constructor, othCtor = other.constructor;
+ // Non `Object` object instances with different constructors are not equal.
+ if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ /**
+ * Gets the appropriate "callback" function. If the `_.callback` method is
+ * customized this function returns the custom method, otherwise it returns
+ * the `baseCallback` function. If arguments are provided the chosen function
+ * is invoked with them and its result is returned.
+ *
+ * @private
+ * @returns {Function} Returns the chosen function or its result.
+ */
+ function getCallback(func, thisArg, argCount) {
+ var result = lodash.callback || callback;
+ result = result === callback ? baseCallback : result;
+ return argCount ? result(func, thisArg, argCount) : result;
+ }
+ /**
+ * Gets metadata for `func`.
+ *
+ * @private
+ * @param {Function} func The function to query.
+ * @returns {*} Returns the metadata for `func`.
+ */
+ var getData = !metaMap ? noop : function (func) {
+ return metaMap.get(func);
+ };
+ /**
+ * Gets the name of `func`.
+ *
+ * @private
+ * @param {Function} func The function to query.
+ * @returns {string} Returns the function name.
+ */
+ function getFuncName(func) {
+ var result = func.name + '', array = realNames[result], length = array ? array.length : 0;
+ while (length--) {
+ var data = array[length], otherFunc = data.func;
+ if (otherFunc == null || otherFunc == func) {
+ return data.name;
+ }
+ }
+ return result;
+ }
+ /**
+ * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
+ * customized this function returns the custom method, otherwise it returns
+ * the `baseIndexOf` function. If arguments are provided the chosen function
+ * is invoked with them and its result is returned.
+ *
+ * @private
+ * @returns {Function|number} Returns the chosen function or its result.
+ */
+ function getIndexOf(collection, target, fromIndex) {
+ var result = lodash.indexOf || indexOf;
+ result = result === indexOf ? baseIndexOf : result;
+ return collection ? result(collection, target, fromIndex) : result;
+ }
+ /**
+ * Gets the "length" property value of `object`.
+ *
+ * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
+ * that affects Safari on at least iOS 8.1-8.3 ARM64.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {*} Returns the "length" value.
+ */
+ var getLength = baseProperty('length');
+ /**
+ * Gets the propery names, values, and compare flags of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the match data of `object`.
+ */
+ function getMatchData(object) {
+ var result = pairs(object), length = result.length;
+ while (length--) {
+ result[length][2] = isStrictComparable(result[length][1]);
+ }
+ return result;
+ }
+ /**
+ * Gets the native function at `key` of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {string} key The key of the method to get.
+ * @returns {*} Returns the function if it's native, else `undefined`.
+ */
+ function getNative(object, key) {
+ var value = object == null ? undefined : object[key];
+ return isNative(value) ? value : undefined;
+ }
+ /**
+ * Gets the view, applying any `transforms` to the `start` and `end` positions.
+ *
+ * @private
+ * @param {number} start The start of the view.
+ * @param {number} end The end of the view.
+ * @param {Array} transforms The transformations to apply to the view.
+ * @returns {Object} Returns an object containing the `start` and `end`
+ * positions of the view.
+ */
+ function getView(start, end, transforms) {
+ var index = -1, length = transforms.length;
+ while (++index < length) {
+ var data = transforms[index], size = data.size;
+ switch (data.type) {
+ case 'drop':
+ start += size;
+ break;
+ case 'dropRight':
+ end -= size;
+ break;
+ case 'take':
+ end = nativeMin(end, start + size);
+ break;
+ case 'takeRight':
+ start = nativeMax(start, end - size);
+ break;
+ }
+ }
+ return {
+ 'start': start,
+ 'end': end
+ };
+ }
+ /**
+ * Initializes an array clone.
+ *
+ * @private
+ * @param {Array} array The array to clone.
+ * @returns {Array} Returns the initialized clone.
+ */
+ function initCloneArray(array) {
+ var length = array.length, result = new array.constructor(length);
+ // Add array properties assigned by `RegExp#exec`.
+ if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
+ result.index = array.index;
+ result.input = array.input;
+ }
+ return result;
+ }
+ /**
+ * Initializes an object clone.
+ *
+ * @private
+ * @param {Object} object The object to clone.
+ * @returns {Object} Returns the initialized clone.
+ */
+ function initCloneObject(object) {
+ var Ctor = object.constructor;
+ if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) {
+ Ctor = Object;
+ }
+ return new Ctor();
+ }
+ /**
+ * Initializes an object clone based on its `toStringTag`.
+ *
+ * **Note:** This function only supports cloning values with tags of
+ * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
+ *
+ * @private
+ * @param {Object} object The object to clone.
+ * @param {string} tag The `toStringTag` of the object to clone.
+ * @param {boolean} [isDeep] Specify a deep clone.
+ * @returns {Object} Returns the initialized clone.
+ */
+ function initCloneByTag(object, tag, isDeep) {
+ var Ctor = object.constructor;
+ switch (tag) {
+ case arrayBufferTag:
+ return bufferClone(object);
+ case boolTag:
+ case dateTag:
+ return new Ctor(+object);
+ case float32Tag:
+ case float64Tag:
+ case int8Tag:
+ case int16Tag:
+ case int32Tag:
+ case uint8Tag:
+ case uint8ClampedTag:
+ case uint16Tag:
+ case uint32Tag:
+ var buffer = object.buffer;
+ return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length);
+ case numberTag:
+ case stringTag:
+ return new Ctor(object);
+ case regexpTag:
+ var result = new Ctor(object.source, reFlags.exec(object));
+ result.lastIndex = object.lastIndex;
+ }
+ return result;
+ }
+ /**
+ * Invokes the method at `path` on `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path of the method to invoke.
+ * @param {Array} args The arguments to invoke the method with.
+ * @returns {*} Returns the result of the invoked method.
+ */
+ function invokePath(object, path, args) {
+ if (object != null && !isKey(path, object)) {
+ path = toPath(path);
+ object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
+ path = last(path);
+ }
+ var func = object == null ? object : object[path];
+ return func == null ? undefined : func.apply(object, args);
+ }
+ /**
+ * Checks if `value` is array-like.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
+ */
+ function isArrayLike(value) {
+ return value != null && isLength(getLength(value));
+ }
+ /**
+ * Checks if `value` is a valid array-like index.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
+ * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
+ */
+ function isIndex(value, length) {
+ value = typeof value == 'number' || reIsUint.test(value) ? +value : -1;
+ length = length == null ? MAX_SAFE_INTEGER : length;
+ return value > -1 && value % 1 == 0 && value < length;
+ }
+ /**
+ * Checks if the provided arguments are from an iteratee call.
+ *
+ * @private
+ * @param {*} value The potential iteratee value argument.
+ * @param {*} index The potential iteratee index or key argument.
+ * @param {*} object The potential iteratee object argument.
+ * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
+ */
+ function isIterateeCall(value, index, object) {
+ if (!isObject(object)) {
+ return false;
+ }
+ var type = typeof index;
+ if (type == 'number' ? isArrayLike(object) && isIndex(index, object.length) : type == 'string' && index in object) {
+ var other = object[index];
+ return value === value ? value === other : other !== other;
+ }
+ return false;
+ }
+ /**
+ * Checks if `value` is a property name and not a property path.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @param {Object} [object] The object to query keys on.
+ * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
+ */
+ function isKey(value, object) {
+ var type = typeof value;
+ if (type == 'string' && reIsPlainProp.test(value) || type == 'number') {
+ return true;
+ }
+ if (isArray(value)) {
+ return false;
+ }
+ var result = !reIsDeepProp.test(value);
+ return result || object != null && value in toObject(object);
+ }
+ /**
+ * Checks if `func` has a lazy counterpart.
+ *
+ * @private
+ * @param {Function} func The function to check.
+ * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`.
+ */
+ function isLaziable(func) {
+ var funcName = getFuncName(func), other = lodash[funcName];
+ if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
+ return false;
+ }
+ if (func === other) {
+ return true;
+ }
+ var data = getData(other);
+ return !!data && func === data[0];
+ }
+ /**
+ * Checks if `value` is a valid array-like length.
+ *
+ * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
+ */
+ function isLength(value) {
+ return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
+ }
+ /**
+ * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` if suitable for strict
+ * equality comparisons, else `false`.
+ */
+ function isStrictComparable(value) {
+ return value === value && !isObject(value);
+ }
+ /**
+ * Merges the function metadata of `source` into `data`.
+ *
+ * Merging metadata reduces the number of wrappers required to invoke a function.
+ * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
+ * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg`
+ * augment function arguments, making the order in which they are executed important,
+ * preventing the merging of metadata. However, we make an exception for a safe
+ * common case where curried functions have `_.ary` and or `_.rearg` applied.
+ *
+ * @private
+ * @param {Array} data The destination metadata.
+ * @param {Array} source The source metadata.
+ * @returns {Array} Returns `data`.
+ */
+ function mergeData(data, source) {
+ var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < ARY_FLAG;
+ var isCombo = srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG || srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8] || srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG;
+ // Exit early if metadata can't be merged.
+ if (!(isCommon || isCombo)) {
+ return data;
+ }
+ // Use source `thisArg` if available.
+ if (srcBitmask & BIND_FLAG) {
+ data[2] = source[2];
+ // Set when currying a bound function.
+ newBitmask |= bitmask & BIND_FLAG ? 0 : CURRY_BOUND_FLAG;
+ }
+ // Compose partial arguments.
+ var value = source[3];
+ if (value) {
+ var partials = data[3];
+ data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value);
+ data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]);
+ }
+ // Compose partial right arguments.
+ value = source[5];
+ if (value) {
+ partials = data[5];
+ data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value);
+ data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]);
+ }
+ // Use source `argPos` if available.
+ value = source[7];
+ if (value) {
+ data[7] = arrayCopy(value);
+ }
+ // Use source `ary` if it's smaller.
+ if (srcBitmask & ARY_FLAG) {
+ data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
+ }
+ // Use source `arity` if one is not provided.
+ if (data[9] == null) {
+ data[9] = source[9];
+ }
+ // Use source `func` and merge bitmasks.
+ data[0] = source[0];
+ data[1] = newBitmask;
+ return data;
+ }
+ /**
+ * Used by `_.defaultsDeep` to customize its `_.merge` use.
+ *
+ * @private
+ * @param {*} objectValue The destination object property value.
+ * @param {*} sourceValue The source object property value.
+ * @returns {*} Returns the value to assign to the destination object.
+ */
+ function mergeDefaults(objectValue, sourceValue) {
+ return objectValue === undefined ? sourceValue : merge(objectValue, sourceValue, mergeDefaults);
+ }
+ /**
+ * A specialized version of `_.pick` which picks `object` properties specified
+ * by `props`.
+ *
+ * @private
+ * @param {Object} object The source object.
+ * @param {string[]} props The property names to pick.
+ * @returns {Object} Returns the new object.
+ */
+ function pickByArray(object, props) {
+ object = toObject(object);
+ var index = -1, length = props.length, result = {};
+ while (++index < length) {
+ var key = props[index];
+ if (key in object) {
+ result[key] = object[key];
+ }
+ }
+ return result;
+ }
+ /**
+ * A specialized version of `_.pick` which picks `object` properties `predicate`
+ * returns truthy for.
+ *
+ * @private
+ * @param {Object} object The source object.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {Object} Returns the new object.
+ */
+ function pickByCallback(object, predicate) {
+ var result = {};
+ baseForIn(object, function (value, key, object) {
+ if (predicate(value, key, object)) {
+ result[key] = value;
+ }
+ });
+ return result;
+ }
+ /**
+ * Reorder `array` according to the specified indexes where the element at
+ * the first index is assigned as the first element, the element at
+ * the second index is assigned as the second element, and so on.
+ *
+ * @private
+ * @param {Array} array The array to reorder.
+ * @param {Array} indexes The arranged array indexes.
+ * @returns {Array} Returns `array`.
+ */
+ function reorder(array, indexes) {
+ var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = arrayCopy(array);
+ while (length--) {
+ var index = indexes[length];
+ array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
+ }
+ return array;
+ }
+ /**
+ * Sets metadata for `func`.
+ *
+ * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
+ * period of time, it will trip its breaker and transition to an identity function
+ * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070)
+ * for more details.
+ *
+ * @private
+ * @param {Function} func The function to associate metadata with.
+ * @param {*} data The metadata.
+ * @returns {Function} Returns `func`.
+ */
+ var setData = function () {
+ var count = 0, lastCalled = 0;
+ return function (key, value) {
+ var stamp = now(), remaining = HOT_SPAN - (stamp - lastCalled);
+ lastCalled = stamp;
+ if (remaining > 0) {
+ if (++count >= HOT_COUNT) {
+ return key;
+ }
+ } else {
+ count = 0;
+ }
+ return baseSetData(key, value);
+ };
+ }();
+ /**
+ * A fallback implementation of `Object.keys` which creates an array of the
+ * own enumerable property names of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ */
+ function shimKeys(object) {
+ var props = keysIn(object), propsLength = props.length, length = propsLength && object.length;
+ var allowIndexes = !!length && isLength(length) && (isArray(object) || isArguments(object));
+ var index = -1, result = [];
+ while (++index < propsLength) {
+ var key = props[index];
+ if (allowIndexes && isIndex(key, length) || hasOwnProperty.call(object, key)) {
+ result.push(key);
+ }
+ }
+ return result;
+ }
+ /**
+ * Converts `value` to an array-like object if it's not one.
+ *
+ * @private
+ * @param {*} value The value to process.
+ * @returns {Array|Object} Returns the array-like object.
+ */
+ function toIterable(value) {
+ if (value == null) {
+ return [];
+ }
+ if (!isArrayLike(value)) {
+ return values(value);
+ }
+ return isObject(value) ? value : Object(value);
+ }
+ /**
+ * Converts `value` to an object if it's not one.
+ *
+ * @private
+ * @param {*} value The value to process.
+ * @returns {Object} Returns the object.
+ */
+ function toObject(value) {
+ return isObject(value) ? value : Object(value);
+ }
+ /**
+ * Converts `value` to property path array if it's not one.
+ *
+ * @private
+ * @param {*} value The value to process.
+ * @returns {Array} Returns the property path array.
+ */
+ function toPath(value) {
+ if (isArray(value)) {
+ return value;
+ }
+ var result = [];
+ baseToString(value).replace(rePropName, function (match, number, quote, string) {
+ result.push(quote ? string.replace(reEscapeChar, '$1') : number || match);
+ });
+ return result;
+ }
+ /**
+ * Creates a clone of `wrapper`.
+ *
+ * @private
+ * @param {Object} wrapper The wrapper to clone.
+ * @returns {Object} Returns the cloned wrapper.
+ */
+ function wrapperClone(wrapper) {
+ return wrapper instanceof LazyWrapper ? wrapper.clone() : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__));
+ }
+ /*------------------------------------------------------------------------*/
+ /**
+ * Creates an array of elements split into groups the length of `size`.
+ * If `collection` can't be split evenly, the final chunk will be the remaining
+ * elements.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to process.
+ * @param {number} [size=1] The length of each chunk.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {Array} Returns the new array containing chunks.
+ * @example
+ *
+ * _.chunk(['a', 'b', 'c', 'd'], 2);
+ * // => [['a', 'b'], ['c', 'd']]
+ *
+ * _.chunk(['a', 'b', 'c', 'd'], 3);
+ * // => [['a', 'b', 'c'], ['d']]
+ */
+ function chunk(array, size, guard) {
+ if (guard ? isIterateeCall(array, size, guard) : size == null) {
+ size = 1;
+ } else {
+ size = nativeMax(nativeFloor(size) || 1, 1);
+ }
+ var index = 0, length = array ? array.length : 0, resIndex = -1, result = Array(nativeCeil(length / size));
+ while (index < length) {
+ result[++resIndex] = baseSlice(array, index, index += size);
+ }
+ return result;
+ }
+ /**
+ * Creates an array with all falsey values removed. The values `false`, `null`,
+ * `0`, `""`, `undefined`, and `NaN` are falsey.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to compact.
+ * @returns {Array} Returns the new array of filtered values.
+ * @example
+ *
+ * _.compact([0, 1, false, 2, '', 3]);
+ * // => [1, 2, 3]
+ */
+ function compact(array) {
+ var index = -1, length = array ? array.length : 0, resIndex = -1, result = [];
+ while (++index < length) {
+ var value = array[index];
+ if (value) {
+ result[++resIndex] = value;
+ }
+ }
+ return result;
+ }
+ /**
+ * Creates an array of unique `array` values not included in the other
+ * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * for equality comparisons.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to inspect.
+ * @param {...Array} [values] The arrays of values to exclude.
+ * @returns {Array} Returns the new array of filtered values.
+ * @example
+ *
+ * _.difference([1, 2, 3], [4, 2]);
+ * // => [1, 3]
+ */
+ var difference = restParam(function (array, values) {
+ return isObjectLike(array) && isArrayLike(array) ? baseDifference(array, baseFlatten(values, false, true)) : [];
+ });
+ /**
+ * Creates a slice of `array` with `n` elements dropped from the beginning.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to query.
+ * @param {number} [n=1] The number of elements to drop.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {Array} Returns the slice of `array`.
+ * @example
+ *
+ * _.drop([1, 2, 3]);
+ * // => [2, 3]
+ *
+ * _.drop([1, 2, 3], 2);
+ * // => [3]
+ *
+ * _.drop([1, 2, 3], 5);
+ * // => []
+ *
+ * _.drop([1, 2, 3], 0);
+ * // => [1, 2, 3]
+ */
+ function drop(array, n, guard) {
+ var length = array ? array.length : 0;
+ if (!length) {
+ return [];
+ }
+ if (guard ? isIterateeCall(array, n, guard) : n == null) {
+ n = 1;
+ }
+ return baseSlice(array, n < 0 ? 0 : n);
+ }
+ /**
+ * Creates a slice of `array` with `n` elements dropped from the end.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to query.
+ * @param {number} [n=1] The number of elements to drop.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {Array} Returns the slice of `array`.
+ * @example
+ *
+ * _.dropRight([1, 2, 3]);
+ * // => [1, 2]
+ *
+ * _.dropRight([1, 2, 3], 2);
+ * // => [1]
+ *
+ * _.dropRight([1, 2, 3], 5);
+ * // => []
+ *
+ * _.dropRight([1, 2, 3], 0);
+ * // => [1, 2, 3]
+ */
+ function dropRight(array, n, guard) {
+ var length = array ? array.length : 0;
+ if (!length) {
+ return [];
+ }
+ if (guard ? isIterateeCall(array, n, guard) : n == null) {
+ n = 1;
+ }
+ n = length - (+n || 0);
+ return baseSlice(array, 0, n < 0 ? 0 : n);
+ }
+ /**
+ * Creates a slice of `array` excluding elements dropped from the end.
+ * Elements are dropped until `predicate` returns falsey. The predicate is
+ * bound to `thisArg` and invoked with three arguments: (value, index, array).
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that match the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to query.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {Array} Returns the slice of `array`.
+ * @example
+ *
+ * _.dropRightWhile([1, 2, 3], function(n) {
+ * return n > 1;
+ * });
+ * // => [1]
+ *
+ * var users = [
+ * { 'user': 'barney', 'active': true },
+ * { 'user': 'fred', 'active': false },
+ * { 'user': 'pebbles', 'active': false }
+ * ];
+ *
+ * // using the `_.matches` callback shorthand
+ * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
+ * // => ['barney', 'fred']
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.pluck(_.dropRightWhile(users, 'active', false), 'user');
+ * // => ['barney']
+ *
+ * // using the `_.property` callback shorthand
+ * _.pluck(_.dropRightWhile(users, 'active'), 'user');
+ * // => ['barney', 'fred', 'pebbles']
+ */
+ function dropRightWhile(array, predicate, thisArg) {
+ return array && array.length ? baseWhile(array, getCallback(predicate, thisArg, 3), true, true) : [];
+ }
+ /**
+ * Creates a slice of `array` excluding elements dropped from the beginning.
+ * Elements are dropped until `predicate` returns falsey. The predicate is
+ * bound to `thisArg` and invoked with three arguments: (value, index, array).
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to query.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {Array} Returns the slice of `array`.
+ * @example
+ *
+ * _.dropWhile([1, 2, 3], function(n) {
+ * return n < 3;
+ * });
+ * // => [3]
+ *
+ * var users = [
+ * { 'user': 'barney', 'active': false },
+ * { 'user': 'fred', 'active': false },
+ * { 'user': 'pebbles', 'active': true }
+ * ];
+ *
+ * // using the `_.matches` callback shorthand
+ * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');
+ * // => ['fred', 'pebbles']
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.pluck(_.dropWhile(users, 'active', false), 'user');
+ * // => ['pebbles']
+ *
+ * // using the `_.property` callback shorthand
+ * _.pluck(_.dropWhile(users, 'active'), 'user');
+ * // => ['barney', 'fred', 'pebbles']
+ */
+ function dropWhile(array, predicate, thisArg) {
+ return array && array.length ? baseWhile(array, getCallback(predicate, thisArg, 3), true) : [];
+ }
+ /**
+ * Fills elements of `array` with `value` from `start` up to, but not
+ * including, `end`.
+ *
+ * **Note:** This method mutates `array`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to fill.
+ * @param {*} value The value to fill `array` with.
+ * @param {number} [start=0] The start position.
+ * @param {number} [end=array.length] The end position.
+ * @returns {Array} Returns `array`.
+ * @example
+ *
+ * var array = [1, 2, 3];
+ *
+ * _.fill(array, 'a');
+ * console.log(array);
+ * // => ['a', 'a', 'a']
+ *
+ * _.fill(Array(3), 2);
+ * // => [2, 2, 2]
+ *
+ * _.fill([4, 6, 8], '*', 1, 2);
+ * // => [4, '*', 8]
+ */
+ function fill(array, value, start, end) {
+ var length = array ? array.length : 0;
+ if (!length) {
+ return [];
+ }
+ if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
+ start = 0;
+ end = length;
+ }
+ return baseFill(array, value, start, end);
+ }
+ /**
+ * This method is like `_.find` except that it returns the index of the first
+ * element `predicate` returns truthy for instead of the element itself.
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to search.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {number} Returns the index of the found element, else `-1`.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'active': false },
+ * { 'user': 'fred', 'active': false },
+ * { 'user': 'pebbles', 'active': true }
+ * ];
+ *
+ * _.findIndex(users, function(chr) {
+ * return chr.user == 'barney';
+ * });
+ * // => 0
+ *
+ * // using the `_.matches` callback shorthand
+ * _.findIndex(users, { 'user': 'fred', 'active': false });
+ * // => 1
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.findIndex(users, 'active', false);
+ * // => 0
+ *
+ * // using the `_.property` callback shorthand
+ * _.findIndex(users, 'active');
+ * // => 2
+ */
+ var findIndex = createFindIndex();
+ /**
+ * This method is like `_.findIndex` except that it iterates over elements
+ * of `collection` from right to left.
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to search.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {number} Returns the index of the found element, else `-1`.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'active': true },
+ * { 'user': 'fred', 'active': false },
+ * { 'user': 'pebbles', 'active': false }
+ * ];
+ *
+ * _.findLastIndex(users, function(chr) {
+ * return chr.user == 'pebbles';
+ * });
+ * // => 2
+ *
+ * // using the `_.matches` callback shorthand
+ * _.findLastIndex(users, { 'user': 'barney', 'active': true });
+ * // => 0
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.findLastIndex(users, 'active', false);
+ * // => 2
+ *
+ * // using the `_.property` callback shorthand
+ * _.findLastIndex(users, 'active');
+ * // => 0
+ */
+ var findLastIndex = createFindIndex(true);
+ /**
+ * Gets the first element of `array`.
+ *
+ * @static
+ * @memberOf _
+ * @alias head
+ * @category Array
+ * @param {Array} array The array to query.
+ * @returns {*} Returns the first element of `array`.
+ * @example
+ *
+ * _.first([1, 2, 3]);
+ * // => 1
+ *
+ * _.first([]);
+ * // => undefined
+ */
+ function first(array) {
+ return array ? array[0] : undefined;
+ }
+ /**
+ * Flattens a nested array. If `isDeep` is `true` the array is recursively
+ * flattened, otherwise it's only flattened a single level.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to flatten.
+ * @param {boolean} [isDeep] Specify a deep flatten.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {Array} Returns the new flattened array.
+ * @example
+ *
+ * _.flatten([1, [2, 3, [4]]]);
+ * // => [1, 2, 3, [4]]
+ *
+ * // using `isDeep`
+ * _.flatten([1, [2, 3, [4]]], true);
+ * // => [1, 2, 3, 4]
+ */
+ function flatten(array, isDeep, guard) {
+ var length = array ? array.length : 0;
+ if (guard && isIterateeCall(array, isDeep, guard)) {
+ isDeep = false;
+ }
+ return length ? baseFlatten(array, isDeep) : [];
+ }
+ /**
+ * Recursively flattens a nested array.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to recursively flatten.
+ * @returns {Array} Returns the new flattened array.
+ * @example
+ *
+ * _.flattenDeep([1, [2, 3, [4]]]);
+ * // => [1, 2, 3, 4]
+ */
+ function flattenDeep(array) {
+ var length = array ? array.length : 0;
+ return length ? baseFlatten(array, true) : [];
+ }
+ /**
+ * Gets the index at which the first occurrence of `value` is found in `array`
+ * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * for equality comparisons. If `fromIndex` is negative, it's used as the offset
+ * from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
+ * performs a faster binary search.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to search.
+ * @param {*} value The value to search for.
+ * @param {boolean|number} [fromIndex=0] The index to search from or `true`
+ * to perform a binary search on a sorted array.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ * @example
+ *
+ * _.indexOf([1, 2, 1, 2], 2);
+ * // => 1
+ *
+ * // using `fromIndex`
+ * _.indexOf([1, 2, 1, 2], 2, 2);
+ * // => 3
+ *
+ * // performing a binary search
+ * _.indexOf([1, 1, 2, 2], 2, true);
+ * // => 2
+ */
+ function indexOf(array, value, fromIndex) {
+ var length = array ? array.length : 0;
+ if (!length) {
+ return -1;
+ }
+ if (typeof fromIndex == 'number') {
+ fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
+ } else if (fromIndex) {
+ var index = binaryIndex(array, value);
+ if (index < length && (value === value ? value === array[index] : array[index] !== array[index])) {
+ return index;
+ }
+ return -1;
+ }
+ return baseIndexOf(array, value, fromIndex || 0);
+ }
+ /**
+ * Gets all but the last element of `array`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to query.
+ * @returns {Array} Returns the slice of `array`.
+ * @example
+ *
+ * _.initial([1, 2, 3]);
+ * // => [1, 2]
+ */
+ function initial(array) {
+ return dropRight(array, 1);
+ }
+ /**
+ * Creates an array of unique values that are included in all of the provided
+ * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * for equality comparisons.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {...Array} [arrays] The arrays to inspect.
+ * @returns {Array} Returns the new array of shared values.
+ * @example
+ * _.intersection([1, 2], [4, 2], [2, 1]);
+ * // => [2]
+ */
+ var intersection = restParam(function (arrays) {
+ var othLength = arrays.length, othIndex = othLength, caches = Array(length), indexOf = getIndexOf(), isCommon = indexOf === baseIndexOf, result = [];
+ while (othIndex--) {
+ var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : [];
+ caches[othIndex] = isCommon && value.length >= 120 ? createCache(othIndex && value) : null;
+ }
+ var array = arrays[0], index = -1, length = array ? array.length : 0, seen = caches[0];
+ outer:
+ while (++index < length) {
+ value = array[index];
+ if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) {
+ var othIndex = othLength;
+ while (--othIndex) {
+ var cache = caches[othIndex];
+ if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) {
+ continue outer;
+ }
+ }
+ if (seen) {
+ seen.push(value);
+ }
+ result.push(value);
+ }
+ }
+ return result;
+ });
+ /**
+ * Gets the last element of `array`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to query.
+ * @returns {*} Returns the last element of `array`.
+ * @example
+ *
+ * _.last([1, 2, 3]);
+ * // => 3
+ */
+ function last(array) {
+ var length = array ? array.length : 0;
+ return length ? array[length - 1] : undefined;
+ }
+ /**
+ * This method is like `_.indexOf` except that it iterates over elements of
+ * `array` from right to left.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to search.
+ * @param {*} value The value to search for.
+ * @param {boolean|number} [fromIndex=array.length-1] The index to search from
+ * or `true` to perform a binary search on a sorted array.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ * @example
+ *
+ * _.lastIndexOf([1, 2, 1, 2], 2);
+ * // => 3
+ *
+ * // using `fromIndex`
+ * _.lastIndexOf([1, 2, 1, 2], 2, 2);
+ * // => 1
+ *
+ * // performing a binary search
+ * _.lastIndexOf([1, 1, 2, 2], 2, true);
+ * // => 3
+ */
+ function lastIndexOf(array, value, fromIndex) {
+ var length = array ? array.length : 0;
+ if (!length) {
+ return -1;
+ }
+ var index = length;
+ if (typeof fromIndex == 'number') {
+ index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1;
+ } else if (fromIndex) {
+ index = binaryIndex(array, value, true) - 1;
+ var other = array[index];
+ if (value === value ? value === other : other !== other) {
+ return index;
+ }
+ return -1;
+ }
+ if (value !== value) {
+ return indexOfNaN(array, index, true);
+ }
+ while (index--) {
+ if (array[index] === value) {
+ return index;
+ }
+ }
+ return -1;
+ }
+ /**
+ * Removes all provided values from `array` using
+ * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * for equality comparisons.
+ *
+ * **Note:** Unlike `_.without`, this method mutates `array`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to modify.
+ * @param {...*} [values] The values to remove.
+ * @returns {Array} Returns `array`.
+ * @example
+ *
+ * var array = [1, 2, 3, 1, 2, 3];
+ *
+ * _.pull(array, 2, 3);
+ * console.log(array);
+ * // => [1, 1]
+ */
+ function pull() {
+ var args = arguments, array = args[0];
+ if (!(array && array.length)) {
+ return array;
+ }
+ var index = 0, indexOf = getIndexOf(), length = args.length;
+ while (++index < length) {
+ var fromIndex = 0, value = args[index];
+ while ((fromIndex = indexOf(array, value, fromIndex)) > -1) {
+ splice.call(array, fromIndex, 1);
+ }
+ }
+ return array;
+ }
+ /**
+ * Removes elements from `array` corresponding to the given indexes and returns
+ * an array of the removed elements. Indexes may be specified as an array of
+ * indexes or as individual arguments.
+ *
+ * **Note:** Unlike `_.at`, this method mutates `array`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to modify.
+ * @param {...(number|number[])} [indexes] The indexes of elements to remove,
+ * specified as individual indexes or arrays of indexes.
+ * @returns {Array} Returns the new array of removed elements.
+ * @example
+ *
+ * var array = [5, 10, 15, 20];
+ * var evens = _.pullAt(array, 1, 3);
+ *
+ * console.log(array);
+ * // => [5, 15]
+ *
+ * console.log(evens);
+ * // => [10, 20]
+ */
+ var pullAt = restParam(function (array, indexes) {
+ indexes = baseFlatten(indexes);
+ var result = baseAt(array, indexes);
+ basePullAt(array, indexes.sort(baseCompareAscending));
+ return result;
+ });
+ /**
+ * Removes all elements from `array` that `predicate` returns truthy for
+ * and returns an array of the removed elements. The predicate is bound to
+ * `thisArg` and invoked with three arguments: (value, index, array).
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * **Note:** Unlike `_.filter`, this method mutates `array`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to modify.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {Array} Returns the new array of removed elements.
+ * @example
+ *
+ * var array = [1, 2, 3, 4];
+ * var evens = _.remove(array, function(n) {
+ * return n % 2 == 0;
+ * });
+ *
+ * console.log(array);
+ * // => [1, 3]
+ *
+ * console.log(evens);
+ * // => [2, 4]
+ */
+ function remove(array, predicate, thisArg) {
+ var result = [];
+ if (!(array && array.length)) {
+ return result;
+ }
+ var index = -1, indexes = [], length = array.length;
+ predicate = getCallback(predicate, thisArg, 3);
+ while (++index < length) {
+ var value = array[index];
+ if (predicate(value, index, array)) {
+ result.push(value);
+ indexes.push(index);
+ }
+ }
+ basePullAt(array, indexes);
+ return result;
+ }
+ /**
+ * Gets all but the first element of `array`.
+ *
+ * @static
+ * @memberOf _
+ * @alias tail
+ * @category Array
+ * @param {Array} array The array to query.
+ * @returns {Array} Returns the slice of `array`.
+ * @example
+ *
+ * _.rest([1, 2, 3]);
+ * // => [2, 3]
+ */
+ function rest(array) {
+ return drop(array, 1);
+ }
+ /**
+ * Creates a slice of `array` from `start` up to, but not including, `end`.
+ *
+ * **Note:** This method is used instead of `Array#slice` to support node
+ * lists in IE < 9 and to ensure dense arrays are returned.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to slice.
+ * @param {number} [start=0] The start position.
+ * @param {number} [end=array.length] The end position.
+ * @returns {Array} Returns the slice of `array`.
+ */
+ function slice(array, start, end) {
+ var length = array ? array.length : 0;
+ if (!length) {
+ return [];
+ }
+ if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
+ start = 0;
+ end = length;
+ }
+ return baseSlice(array, start, end);
+ }
+ /**
+ * Uses a binary search to determine the lowest index at which `value` should
+ * be inserted into `array` in order to maintain its sort order. If an iteratee
+ * function is provided it's invoked for `value` and each element of `array`
+ * to compute their sort ranking. The iteratee is bound to `thisArg` and
+ * invoked with one argument; (value).
+ *
+ * If a property name is provided for `iteratee` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `iteratee` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The sorted array to inspect.
+ * @param {*} value The value to evaluate.
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {number} Returns the index at which `value` should be inserted
+ * into `array`.
+ * @example
+ *
+ * _.sortedIndex([30, 50], 40);
+ * // => 1
+ *
+ * _.sortedIndex([4, 4, 5, 5], 5);
+ * // => 2
+ *
+ * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };
+ *
+ * // using an iteratee function
+ * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
+ * return this.data[word];
+ * }, dict);
+ * // => 1
+ *
+ * // using the `_.property` callback shorthand
+ * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
+ * // => 1
+ */
+ var sortedIndex = createSortedIndex();
+ /**
+ * This method is like `_.sortedIndex` except that it returns the highest
+ * index at which `value` should be inserted into `array` in order to
+ * maintain its sort order.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The sorted array to inspect.
+ * @param {*} value The value to evaluate.
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {number} Returns the index at which `value` should be inserted
+ * into `array`.
+ * @example
+ *
+ * _.sortedLastIndex([4, 4, 5, 5], 5);
+ * // => 4
+ */
+ var sortedLastIndex = createSortedIndex(true);
+ /**
+ * Creates a slice of `array` with `n` elements taken from the beginning.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to query.
+ * @param {number} [n=1] The number of elements to take.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {Array} Returns the slice of `array`.
+ * @example
+ *
+ * _.take([1, 2, 3]);
+ * // => [1]
+ *
+ * _.take([1, 2, 3], 2);
+ * // => [1, 2]
+ *
+ * _.take([1, 2, 3], 5);
+ * // => [1, 2, 3]
+ *
+ * _.take([1, 2, 3], 0);
+ * // => []
+ */
+ function take(array, n, guard) {
+ var length = array ? array.length : 0;
+ if (!length) {
+ return [];
+ }
+ if (guard ? isIterateeCall(array, n, guard) : n == null) {
+ n = 1;
+ }
+ return baseSlice(array, 0, n < 0 ? 0 : n);
+ }
+ /**
+ * Creates a slice of `array` with `n` elements taken from the end.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to query.
+ * @param {number} [n=1] The number of elements to take.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {Array} Returns the slice of `array`.
+ * @example
+ *
+ * _.takeRight([1, 2, 3]);
+ * // => [3]
+ *
+ * _.takeRight([1, 2, 3], 2);
+ * // => [2, 3]
+ *
+ * _.takeRight([1, 2, 3], 5);
+ * // => [1, 2, 3]
+ *
+ * _.takeRight([1, 2, 3], 0);
+ * // => []
+ */
+ function takeRight(array, n, guard) {
+ var length = array ? array.length : 0;
+ if (!length) {
+ return [];
+ }
+ if (guard ? isIterateeCall(array, n, guard) : n == null) {
+ n = 1;
+ }
+ n = length - (+n || 0);
+ return baseSlice(array, n < 0 ? 0 : n);
+ }
+ /**
+ * Creates a slice of `array` with elements taken from the end. Elements are
+ * taken until `predicate` returns falsey. The predicate is bound to `thisArg`
+ * and invoked with three arguments: (value, index, array).
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to query.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {Array} Returns the slice of `array`.
+ * @example
+ *
+ * _.takeRightWhile([1, 2, 3], function(n) {
+ * return n > 1;
+ * });
+ * // => [2, 3]
+ *
+ * var users = [
+ * { 'user': 'barney', 'active': true },
+ * { 'user': 'fred', 'active': false },
+ * { 'user': 'pebbles', 'active': false }
+ * ];
+ *
+ * // using the `_.matches` callback shorthand
+ * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
+ * // => ['pebbles']
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.pluck(_.takeRightWhile(users, 'active', false), 'user');
+ * // => ['fred', 'pebbles']
+ *
+ * // using the `_.property` callback shorthand
+ * _.pluck(_.takeRightWhile(users, 'active'), 'user');
+ * // => []
+ */
+ function takeRightWhile(array, predicate, thisArg) {
+ return array && array.length ? baseWhile(array, getCallback(predicate, thisArg, 3), false, true) : [];
+ }
+ /**
+ * Creates a slice of `array` with elements taken from the beginning. Elements
+ * are taken until `predicate` returns falsey. The predicate is bound to
+ * `thisArg` and invoked with three arguments: (value, index, array).
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to query.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {Array} Returns the slice of `array`.
+ * @example
+ *
+ * _.takeWhile([1, 2, 3], function(n) {
+ * return n < 3;
+ * });
+ * // => [1, 2]
+ *
+ * var users = [
+ * { 'user': 'barney', 'active': false },
+ * { 'user': 'fred', 'active': false},
+ * { 'user': 'pebbles', 'active': true }
+ * ];
+ *
+ * // using the `_.matches` callback shorthand
+ * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');
+ * // => ['barney']
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.pluck(_.takeWhile(users, 'active', false), 'user');
+ * // => ['barney', 'fred']
+ *
+ * // using the `_.property` callback shorthand
+ * _.pluck(_.takeWhile(users, 'active'), 'user');
+ * // => []
+ */
+ function takeWhile(array, predicate, thisArg) {
+ return array && array.length ? baseWhile(array, getCallback(predicate, thisArg, 3)) : [];
+ }
+ /**
+ * Creates an array of unique values, in order, from all of the provided arrays
+ * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * for equality comparisons.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {...Array} [arrays] The arrays to inspect.
+ * @returns {Array} Returns the new array of combined values.
+ * @example
+ *
+ * _.union([1, 2], [4, 2], [2, 1]);
+ * // => [1, 2, 4]
+ */
+ var union = restParam(function (arrays) {
+ return baseUniq(baseFlatten(arrays, false, true));
+ });
+ /**
+ * Creates a duplicate-free version of an array, using
+ * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * for equality comparisons, in which only the first occurence of each element
+ * is kept. Providing `true` for `isSorted` performs a faster search algorithm
+ * for sorted arrays. If an iteratee function is provided it's invoked for
+ * each element in the array to generate the criterion by which uniqueness
+ * is computed. The `iteratee` is bound to `thisArg` and invoked with three
+ * arguments: (value, index, array).
+ *
+ * If a property name is provided for `iteratee` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `iteratee` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @alias unique
+ * @category Array
+ * @param {Array} array The array to inspect.
+ * @param {boolean} [isSorted] Specify the array is sorted.
+ * @param {Function|Object|string} [iteratee] The function invoked per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Array} Returns the new duplicate-value-free array.
+ * @example
+ *
+ * _.uniq([2, 1, 2]);
+ * // => [2, 1]
+ *
+ * // using `isSorted`
+ * _.uniq([1, 1, 2], true);
+ * // => [1, 2]
+ *
+ * // using an iteratee function
+ * _.uniq([1, 2.5, 1.5, 2], function(n) {
+ * return this.floor(n);
+ * }, Math);
+ * // => [1, 2.5]
+ *
+ * // using the `_.property` callback shorthand
+ * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
+ * // => [{ 'x': 1 }, { 'x': 2 }]
+ */
+ function uniq(array, isSorted, iteratee, thisArg) {
+ var length = array ? array.length : 0;
+ if (!length) {
+ return [];
+ }
+ if (isSorted != null && typeof isSorted != 'boolean') {
+ thisArg = iteratee;
+ iteratee = isIterateeCall(array, isSorted, thisArg) ? undefined : isSorted;
+ isSorted = false;
+ }
+ var callback = getCallback();
+ if (!(iteratee == null && callback === baseCallback)) {
+ iteratee = callback(iteratee, thisArg, 3);
+ }
+ return isSorted && getIndexOf() === baseIndexOf ? sortedUniq(array, iteratee) : baseUniq(array, iteratee);
+ }
+ /**
+ * This method is like `_.zip` except that it accepts an array of grouped
+ * elements and creates an array regrouping the elements to their pre-zip
+ * configuration.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array of grouped elements to process.
+ * @returns {Array} Returns the new array of regrouped elements.
+ * @example
+ *
+ * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
+ * // => [['fred', 30, true], ['barney', 40, false]]
+ *
+ * _.unzip(zipped);
+ * // => [['fred', 'barney'], [30, 40], [true, false]]
+ */
+ function unzip(array) {
+ if (!(array && array.length)) {
+ return [];
+ }
+ var index = -1, length = 0;
+ array = arrayFilter(array, function (group) {
+ if (isArrayLike(group)) {
+ length = nativeMax(group.length, length);
+ return true;
+ }
+ });
+ var result = Array(length);
+ while (++index < length) {
+ result[index] = arrayMap(array, baseProperty(index));
+ }
+ return result;
+ }
+ /**
+ * This method is like `_.unzip` except that it accepts an iteratee to specify
+ * how regrouped values should be combined. The `iteratee` is bound to `thisArg`
+ * and invoked with four arguments: (accumulator, value, index, group).
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array of grouped elements to process.
+ * @param {Function} [iteratee] The function to combine regrouped values.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Array} Returns the new array of regrouped elements.
+ * @example
+ *
+ * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
+ * // => [[1, 10, 100], [2, 20, 200]]
+ *
+ * _.unzipWith(zipped, _.add);
+ * // => [3, 30, 300]
+ */
+ function unzipWith(array, iteratee, thisArg) {
+ var length = array ? array.length : 0;
+ if (!length) {
+ return [];
+ }
+ var result = unzip(array);
+ if (iteratee == null) {
+ return result;
+ }
+ iteratee = bindCallback(iteratee, thisArg, 4);
+ return arrayMap(result, function (group) {
+ return arrayReduce(group, iteratee, undefined, true);
+ });
+ }
+ /**
+ * Creates an array excluding all provided values using
+ * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * for equality comparisons.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {Array} array The array to filter.
+ * @param {...*} [values] The values to exclude.
+ * @returns {Array} Returns the new array of filtered values.
+ * @example
+ *
+ * _.without([1, 2, 1, 3], 1, 2);
+ * // => [3]
+ */
+ var without = restParam(function (array, values) {
+ return isArrayLike(array) ? baseDifference(array, values) : [];
+ });
+ /**
+ * Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
+ * of the provided arrays.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {...Array} [arrays] The arrays to inspect.
+ * @returns {Array} Returns the new array of values.
+ * @example
+ *
+ * _.xor([1, 2], [4, 2]);
+ * // => [1, 4]
+ */
+ function xor() {
+ var index = -1, length = arguments.length;
+ while (++index < length) {
+ var array = arguments[index];
+ if (isArrayLike(array)) {
+ var result = result ? arrayPush(baseDifference(result, array), baseDifference(array, result)) : array;
+ }
+ }
+ return result ? baseUniq(result) : [];
+ }
+ /**
+ * Creates an array of grouped elements, the first of which contains the first
+ * elements of the given arrays, the second of which contains the second elements
+ * of the given arrays, and so on.
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {...Array} [arrays] The arrays to process.
+ * @returns {Array} Returns the new array of grouped elements.
+ * @example
+ *
+ * _.zip(['fred', 'barney'], [30, 40], [true, false]);
+ * // => [['fred', 30, true], ['barney', 40, false]]
+ */
+ var zip = restParam(unzip);
+ /**
+ * The inverse of `_.pairs`; this method returns an object composed from arrays
+ * of property names and values. Provide either a single two dimensional array,
+ * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names
+ * and one of corresponding values.
+ *
+ * @static
+ * @memberOf _
+ * @alias object
+ * @category Array
+ * @param {Array} props The property names.
+ * @param {Array} [values=[]] The property values.
+ * @returns {Object} Returns the new object.
+ * @example
+ *
+ * _.zipObject([['fred', 30], ['barney', 40]]);
+ * // => { 'fred': 30, 'barney': 40 }
+ *
+ * _.zipObject(['fred', 'barney'], [30, 40]);
+ * // => { 'fred': 30, 'barney': 40 }
+ */
+ function zipObject(props, values) {
+ var index = -1, length = props ? props.length : 0, result = {};
+ if (length && !values && !isArray(props[0])) {
+ values = [];
+ }
+ while (++index < length) {
+ var key = props[index];
+ if (values) {
+ result[key] = values[index];
+ } else if (key) {
+ result[key[0]] = key[1];
+ }
+ }
+ return result;
+ }
+ /**
+ * This method is like `_.zip` except that it accepts an iteratee to specify
+ * how grouped values should be combined. The `iteratee` is bound to `thisArg`
+ * and invoked with four arguments: (accumulator, value, index, group).
+ *
+ * @static
+ * @memberOf _
+ * @category Array
+ * @param {...Array} [arrays] The arrays to process.
+ * @param {Function} [iteratee] The function to combine grouped values.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Array} Returns the new array of grouped elements.
+ * @example
+ *
+ * _.zipWith([1, 2], [10, 20], [100, 200], _.add);
+ * // => [111, 222]
+ */
+ var zipWith = restParam(function (arrays) {
+ var length = arrays.length, iteratee = length > 2 ? arrays[length - 2] : undefined, thisArg = length > 1 ? arrays[length - 1] : undefined;
+ if (length > 2 && typeof iteratee == 'function') {
+ length -= 2;
+ } else {
+ iteratee = length > 1 && typeof thisArg == 'function' ? (--length, thisArg) : undefined;
+ thisArg = undefined;
+ }
+ arrays.length = length;
+ return unzipWith(arrays, iteratee, thisArg);
+ });
+ /*------------------------------------------------------------------------*/
+ /**
+ * Creates a `lodash` object that wraps `value` with explicit method
+ * chaining enabled.
+ *
+ * @static
+ * @memberOf _
+ * @category Chain
+ * @param {*} value The value to wrap.
+ * @returns {Object} Returns the new `lodash` wrapper instance.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36 },
+ * { 'user': 'fred', 'age': 40 },
+ * { 'user': 'pebbles', 'age': 1 }
+ * ];
+ *
+ * var youngest = _.chain(users)
+ * .sortBy('age')
+ * .map(function(chr) {
+ * return chr.user + ' is ' + chr.age;
+ * })
+ * .first()
+ * .value();
+ * // => 'pebbles is 1'
+ */
+ function chain(value) {
+ var result = lodash(value);
+ result.__chain__ = true;
+ return result;
+ }
+ /**
+ * This method invokes `interceptor` and returns `value`. The interceptor is
+ * bound to `thisArg` and invoked with one argument; (value). The purpose of
+ * this method is to "tap into" a method chain in order to perform operations
+ * on intermediate results within the chain.
+ *
+ * @static
+ * @memberOf _
+ * @category Chain
+ * @param {*} value The value to provide to `interceptor`.
+ * @param {Function} interceptor The function to invoke.
+ * @param {*} [thisArg] The `this` binding of `interceptor`.
+ * @returns {*} Returns `value`.
+ * @example
+ *
+ * _([1, 2, 3])
+ * .tap(function(array) {
+ * array.pop();
+ * })
+ * .reverse()
+ * .value();
+ * // => [2, 1]
+ */
+ function tap(value, interceptor, thisArg) {
+ interceptor.call(thisArg, value);
+ return value;
+ }
+ /**
+ * This method is like `_.tap` except that it returns the result of `interceptor`.
+ *
+ * @static
+ * @memberOf _
+ * @category Chain
+ * @param {*} value The value to provide to `interceptor`.
+ * @param {Function} interceptor The function to invoke.
+ * @param {*} [thisArg] The `this` binding of `interceptor`.
+ * @returns {*} Returns the result of `interceptor`.
+ * @example
+ *
+ * _(' abc ')
+ * .chain()
+ * .trim()
+ * .thru(function(value) {
+ * return [value];
+ * })
+ * .value();
+ * // => ['abc']
+ */
+ function thru(value, interceptor, thisArg) {
+ return interceptor.call(thisArg, value);
+ }
+ /**
+ * Enables explicit method chaining on the wrapper object.
+ *
+ * @name chain
+ * @memberOf _
+ * @category Chain
+ * @returns {Object} Returns the new `lodash` wrapper instance.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36 },
+ * { 'user': 'fred', 'age': 40 }
+ * ];
+ *
+ * // without explicit chaining
+ * _(users).first();
+ * // => { 'user': 'barney', 'age': 36 }
+ *
+ * // with explicit chaining
+ * _(users).chain()
+ * .first()
+ * .pick('user')
+ * .value();
+ * // => { 'user': 'barney' }
+ */
+ function wrapperChain() {
+ return chain(this);
+ }
+ /**
+ * Executes the chained sequence and returns the wrapped result.
+ *
+ * @name commit
+ * @memberOf _
+ * @category Chain
+ * @returns {Object} Returns the new `lodash` wrapper instance.
+ * @example
+ *
+ * var array = [1, 2];
+ * var wrapped = _(array).push(3);
+ *
+ * console.log(array);
+ * // => [1, 2]
+ *
+ * wrapped = wrapped.commit();
+ * console.log(array);
+ * // => [1, 2, 3]
+ *
+ * wrapped.last();
+ * // => 3
+ *
+ * console.log(array);
+ * // => [1, 2, 3]
+ */
+ function wrapperCommit() {
+ return new LodashWrapper(this.value(), this.__chain__);
+ }
+ /**
+ * Creates a new array joining a wrapped array with any additional arrays
+ * and/or values.
+ *
+ * @name concat
+ * @memberOf _
+ * @category Chain
+ * @param {...*} [values] The values to concatenate.
+ * @returns {Array} Returns the new concatenated array.
+ * @example
+ *
+ * var array = [1];
+ * var wrapped = _(array).concat(2, [3], [[4]]);
+ *
+ * console.log(wrapped.value());
+ * // => [1, 2, 3, [4]]
+ *
+ * console.log(array);
+ * // => [1]
+ */
+ var wrapperConcat = restParam(function (values) {
+ values = baseFlatten(values);
+ return this.thru(function (array) {
+ return arrayConcat(isArray(array) ? array : [toObject(array)], values);
+ });
+ });
+ /**
+ * Creates a clone of the chained sequence planting `value` as the wrapped value.
+ *
+ * @name plant
+ * @memberOf _
+ * @category Chain
+ * @returns {Object} Returns the new `lodash` wrapper instance.
+ * @example
+ *
+ * var array = [1, 2];
+ * var wrapped = _(array).map(function(value) {
+ * return Math.pow(value, 2);
+ * });
+ *
+ * var other = [3, 4];
+ * var otherWrapped = wrapped.plant(other);
+ *
+ * otherWrapped.value();
+ * // => [9, 16]
+ *
+ * wrapped.value();
+ * // => [1, 4]
+ */
+ function wrapperPlant(value) {
+ var result, parent = this;
+ while (parent instanceof baseLodash) {
+ var clone = wrapperClone(parent);
+ if (result) {
+ previous.__wrapped__ = clone;
+ } else {
+ result = clone;
+ }
+ var previous = clone;
+ parent = parent.__wrapped__;
+ }
+ previous.__wrapped__ = value;
+ return result;
+ }
+ /**
+ * Reverses the wrapped array so the first element becomes the last, the
+ * second element becomes the second to last, and so on.
+ *
+ * **Note:** This method mutates the wrapped array.
+ *
+ * @name reverse
+ * @memberOf _
+ * @category Chain
+ * @returns {Object} Returns the new reversed `lodash` wrapper instance.
+ * @example
+ *
+ * var array = [1, 2, 3];
+ *
+ * _(array).reverse().value()
+ * // => [3, 2, 1]
+ *
+ * console.log(array);
+ * // => [3, 2, 1]
+ */
+ function wrapperReverse() {
+ var value = this.__wrapped__;
+ var interceptor = function (value) {
+ return value.reverse();
+ };
+ if (value instanceof LazyWrapper) {
+ var wrapped = value;
+ if (this.__actions__.length) {
+ wrapped = new LazyWrapper(this);
+ }
+ wrapped = wrapped.reverse();
+ wrapped.__actions__.push({
+ 'func': thru,
+ 'args': [interceptor],
+ 'thisArg': undefined
+ });
+ return new LodashWrapper(wrapped, this.__chain__);
+ }
+ return this.thru(interceptor);
+ }
+ /**
+ * Produces the result of coercing the unwrapped value to a string.
+ *
+ * @name toString
+ * @memberOf _
+ * @category Chain
+ * @returns {string} Returns the coerced string value.
+ * @example
+ *
+ * _([1, 2, 3]).toString();
+ * // => '1,2,3'
+ */
+ function wrapperToString() {
+ return this.value() + '';
+ }
+ /**
+ * Executes the chained sequence to extract the unwrapped value.
+ *
+ * @name value
+ * @memberOf _
+ * @alias run, toJSON, valueOf
+ * @category Chain
+ * @returns {*} Returns the resolved unwrapped value.
+ * @example
+ *
+ * _([1, 2, 3]).value();
+ * // => [1, 2, 3]
+ */
+ function wrapperValue() {
+ return baseWrapperValue(this.__wrapped__, this.__actions__);
+ }
+ /*------------------------------------------------------------------------*/
+ /**
+ * Creates an array of elements corresponding to the given keys, or indexes,
+ * of `collection`. Keys may be specified as individual arguments or as arrays
+ * of keys.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {...(number|number[]|string|string[])} [props] The property names
+ * or indexes of elements to pick, specified individually or in arrays.
+ * @returns {Array} Returns the new array of picked elements.
+ * @example
+ *
+ * _.at(['a', 'b', 'c'], [0, 2]);
+ * // => ['a', 'c']
+ *
+ * _.at(['barney', 'fred', 'pebbles'], 0, 2);
+ * // => ['barney', 'pebbles']
+ */
+ var at = restParam(function (collection, props) {
+ return baseAt(collection, baseFlatten(props));
+ });
+ /**
+ * Creates an object composed of keys generated from the results of running
+ * each element of `collection` through `iteratee`. The corresponding value
+ * of each key is the number of times the key was returned by `iteratee`.
+ * The `iteratee` is bound to `thisArg` and invoked with three arguments:
+ * (value, index|key, collection).
+ *
+ * If a property name is provided for `iteratee` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `iteratee` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Object} Returns the composed aggregate object.
+ * @example
+ *
+ * _.countBy([4.3, 6.1, 6.4], function(n) {
+ * return Math.floor(n);
+ * });
+ * // => { '4': 1, '6': 2 }
+ *
+ * _.countBy([4.3, 6.1, 6.4], function(n) {
+ * return this.floor(n);
+ * }, Math);
+ * // => { '4': 1, '6': 2 }
+ *
+ * _.countBy(['one', 'two', 'three'], 'length');
+ * // => { '3': 2, '5': 1 }
+ */
+ var countBy = createAggregator(function (result, value, key) {
+ hasOwnProperty.call(result, key) ? ++result[key] : result[key] = 1;
+ });
+ /**
+ * Checks if `predicate` returns truthy for **all** elements of `collection`.
+ * The predicate is bound to `thisArg` and invoked with three arguments:
+ * (value, index|key, collection).
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @alias all
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {boolean} Returns `true` if all elements pass the predicate check,
+ * else `false`.
+ * @example
+ *
+ * _.every([true, 1, null, 'yes'], Boolean);
+ * // => false
+ *
+ * var users = [
+ * { 'user': 'barney', 'active': false },
+ * { 'user': 'fred', 'active': false }
+ * ];
+ *
+ * // using the `_.matches` callback shorthand
+ * _.every(users, { 'user': 'barney', 'active': false });
+ * // => false
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.every(users, 'active', false);
+ * // => true
+ *
+ * // using the `_.property` callback shorthand
+ * _.every(users, 'active');
+ * // => false
+ */
+ function every(collection, predicate, thisArg) {
+ var func = isArray(collection) ? arrayEvery : baseEvery;
+ if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
+ predicate = undefined;
+ }
+ if (typeof predicate != 'function' || thisArg !== undefined) {
+ predicate = getCallback(predicate, thisArg, 3);
+ }
+ return func(collection, predicate);
+ }
+ /**
+ * Iterates over elements of `collection`, returning an array of all elements
+ * `predicate` returns truthy for. The predicate is bound to `thisArg` and
+ * invoked with three arguments: (value, index|key, collection).
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @alias select
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {Array} Returns the new filtered array.
+ * @example
+ *
+ * _.filter([4, 5, 6], function(n) {
+ * return n % 2 == 0;
+ * });
+ * // => [4, 6]
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36, 'active': true },
+ * { 'user': 'fred', 'age': 40, 'active': false }
+ * ];
+ *
+ * // using the `_.matches` callback shorthand
+ * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');
+ * // => ['barney']
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.pluck(_.filter(users, 'active', false), 'user');
+ * // => ['fred']
+ *
+ * // using the `_.property` callback shorthand
+ * _.pluck(_.filter(users, 'active'), 'user');
+ * // => ['barney']
+ */
+ function filter(collection, predicate, thisArg) {
+ var func = isArray(collection) ? arrayFilter : baseFilter;
+ predicate = getCallback(predicate, thisArg, 3);
+ return func(collection, predicate);
+ }
+ /**
+ * Iterates over elements of `collection`, returning the first element
+ * `predicate` returns truthy for. The predicate is bound to `thisArg` and
+ * invoked with three arguments: (value, index|key, collection).
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @alias detect
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to search.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {*} Returns the matched element, else `undefined`.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36, 'active': true },
+ * { 'user': 'fred', 'age': 40, 'active': false },
+ * { 'user': 'pebbles', 'age': 1, 'active': true }
+ * ];
+ *
+ * _.result(_.find(users, function(chr) {
+ * return chr.age < 40;
+ * }), 'user');
+ * // => 'barney'
+ *
+ * // using the `_.matches` callback shorthand
+ * _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
+ * // => 'pebbles'
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.result(_.find(users, 'active', false), 'user');
+ * // => 'fred'
+ *
+ * // using the `_.property` callback shorthand
+ * _.result(_.find(users, 'active'), 'user');
+ * // => 'barney'
+ */
+ var find = createFind(baseEach);
+ /**
+ * This method is like `_.find` except that it iterates over elements of
+ * `collection` from right to left.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to search.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {*} Returns the matched element, else `undefined`.
+ * @example
+ *
+ * _.findLast([1, 2, 3, 4], function(n) {
+ * return n % 2 == 1;
+ * });
+ * // => 3
+ */
+ var findLast = createFind(baseEachRight, true);
+ /**
+ * Performs a deep comparison between each element in `collection` and the
+ * source object, returning the first element that has equivalent property
+ * values.
+ *
+ * **Note:** This method supports comparing arrays, booleans, `Date` objects,
+ * numbers, `Object` objects, regexes, and strings. Objects are compared by
+ * their own, not inherited, enumerable properties. For comparing a single
+ * own or inherited property value see `_.matchesProperty`.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to search.
+ * @param {Object} source The object of property values to match.
+ * @returns {*} Returns the matched element, else `undefined`.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36, 'active': true },
+ * { 'user': 'fred', 'age': 40, 'active': false }
+ * ];
+ *
+ * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
+ * // => 'barney'
+ *
+ * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
+ * // => 'fred'
+ */
+ function findWhere(collection, source) {
+ return find(collection, baseMatches(source));
+ }
+ /**
+ * Iterates over elements of `collection` invoking `iteratee` for each element.
+ * The `iteratee` is bound to `thisArg` and invoked with three arguments:
+ * (value, index|key, collection). Iteratee functions may exit iteration early
+ * by explicitly returning `false`.
+ *
+ * **Note:** As with other "Collections" methods, objects with a "length" property
+ * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
+ * may be used for object iteration.
+ *
+ * @static
+ * @memberOf _
+ * @alias each
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Array|Object|string} Returns `collection`.
+ * @example
+ *
+ * _([1, 2]).forEach(function(n) {
+ * console.log(n);
+ * }).value();
+ * // => logs each value from left to right and returns the array
+ *
+ * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
+ * console.log(n, key);
+ * });
+ * // => logs each value-key pair and returns the object (iteration order is not guaranteed)
+ */
+ var forEach = createForEach(arrayEach, baseEach);
+ /**
+ * This method is like `_.forEach` except that it iterates over elements of
+ * `collection` from right to left.
+ *
+ * @static
+ * @memberOf _
+ * @alias eachRight
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Array|Object|string} Returns `collection`.
+ * @example
+ *
+ * _([1, 2]).forEachRight(function(n) {
+ * console.log(n);
+ * }).value();
+ * // => logs each value from right to left and returns the array
+ */
+ var forEachRight = createForEach(arrayEachRight, baseEachRight);
+ /**
+ * Creates an object composed of keys generated from the results of running
+ * each element of `collection` through `iteratee`. The corresponding value
+ * of each key is an array of the elements responsible for generating the key.
+ * The `iteratee` is bound to `thisArg` and invoked with three arguments:
+ * (value, index|key, collection).
+ *
+ * If a property name is provided for `iteratee` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `iteratee` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Object} Returns the composed aggregate object.
+ * @example
+ *
+ * _.groupBy([4.2, 6.1, 6.4], function(n) {
+ * return Math.floor(n);
+ * });
+ * // => { '4': [4.2], '6': [6.1, 6.4] }
+ *
+ * _.groupBy([4.2, 6.1, 6.4], function(n) {
+ * return this.floor(n);
+ * }, Math);
+ * // => { '4': [4.2], '6': [6.1, 6.4] }
+ *
+ * // using the `_.property` callback shorthand
+ * _.groupBy(['one', 'two', 'three'], 'length');
+ * // => { '3': ['one', 'two'], '5': ['three'] }
+ */
+ var groupBy = createAggregator(function (result, value, key) {
+ if (hasOwnProperty.call(result, key)) {
+ result[key].push(value);
+ } else {
+ result[key] = [value];
+ }
+ });
+ /**
+ * Checks if `target` is in `collection` using
+ * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
+ * for equality comparisons. If `fromIndex` is negative, it's used as the offset
+ * from the end of `collection`.
+ *
+ * @static
+ * @memberOf _
+ * @alias contains, include
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to search.
+ * @param {*} target The value to search for.
+ * @param {number} [fromIndex=0] The index to search from.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
+ * @returns {boolean} Returns `true` if a matching element is found, else `false`.
+ * @example
+ *
+ * _.includes([1, 2, 3], 1);
+ * // => true
+ *
+ * _.includes([1, 2, 3], 1, 2);
+ * // => false
+ *
+ * _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
+ * // => true
+ *
+ * _.includes('pebbles', 'eb');
+ * // => true
+ */
+ function includes(collection, target, fromIndex, guard) {
+ var length = collection ? getLength(collection) : 0;
+ if (!isLength(length)) {
+ collection = values(collection);
+ length = collection.length;
+ }
+ if (typeof fromIndex != 'number' || guard && isIterateeCall(target, fromIndex, guard)) {
+ fromIndex = 0;
+ } else {
+ fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex || 0;
+ }
+ return typeof collection == 'string' || !isArray(collection) && isString(collection) ? fromIndex <= length && collection.indexOf(target, fromIndex) > -1 : !!length && getIndexOf(collection, target, fromIndex) > -1;
+ }
+ /**
+ * Creates an object composed of keys generated from the results of running
+ * each element of `collection` through `iteratee`. The corresponding value
+ * of each key is the last element responsible for generating the key. The
+ * iteratee function is bound to `thisArg` and invoked with three arguments:
+ * (value, index|key, collection).
+ *
+ * If a property name is provided for `iteratee` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `iteratee` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Object} Returns the composed aggregate object.
+ * @example
+ *
+ * var keyData = [
+ * { 'dir': 'left', 'code': 97 },
+ * { 'dir': 'right', 'code': 100 }
+ * ];
+ *
+ * _.indexBy(keyData, 'dir');
+ * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
+ *
+ * _.indexBy(keyData, function(object) {
+ * return String.fromCharCode(object.code);
+ * });
+ * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
+ *
+ * _.indexBy(keyData, function(object) {
+ * return this.fromCharCode(object.code);
+ * }, String);
+ * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
+ */
+ var indexBy = createAggregator(function (result, value, key) {
+ result[key] = value;
+ });
+ /**
+ * Invokes the method at `path` of each element in `collection`, returning
+ * an array of the results of each invoked method. Any additional arguments
+ * are provided to each invoked method. If `methodName` is a function it's
+ * invoked for, and `this` bound to, each element in `collection`.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Array|Function|string} path The path of the method to invoke or
+ * the function invoked per iteration.
+ * @param {...*} [args] The arguments to invoke the method with.
+ * @returns {Array} Returns the array of results.
+ * @example
+ *
+ * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
+ * // => [[1, 5, 7], [1, 2, 3]]
+ *
+ * _.invoke([123, 456], String.prototype.split, '');
+ * // => [['1', '2', '3'], ['4', '5', '6']]
+ */
+ var invoke = restParam(function (collection, path, args) {
+ var index = -1, isFunc = typeof path == 'function', isProp = isKey(path), result = isArrayLike(collection) ? Array(collection.length) : [];
+ baseEach(collection, function (value) {
+ var func = isFunc ? path : isProp && value != null ? value[path] : undefined;
+ result[++index] = func ? func.apply(value, args) : invokePath(value, path, args);
+ });
+ return result;
+ });
+ /**
+ * Creates an array of values by running each element in `collection` through
+ * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
+ * arguments: (value, index|key, collection).
+ *
+ * If a property name is provided for `iteratee` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `iteratee` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * Many lodash methods are guarded to work as iteratees for methods like
+ * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
+ *
+ * The guarded methods are:
+ * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`,
+ * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`,
+ * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`,
+ * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`,
+ * `sum`, `uniq`, and `words`
+ *
+ * @static
+ * @memberOf _
+ * @alias collect
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Array} Returns the new mapped array.
+ * @example
+ *
+ * function timesThree(n) {
+ * return n * 3;
+ * }
+ *
+ * _.map([1, 2], timesThree);
+ * // => [3, 6]
+ *
+ * _.map({ 'a': 1, 'b': 2 }, timesThree);
+ * // => [3, 6] (iteration order is not guaranteed)
+ *
+ * var users = [
+ * { 'user': 'barney' },
+ * { 'user': 'fred' }
+ * ];
+ *
+ * // using the `_.property` callback shorthand
+ * _.map(users, 'user');
+ * // => ['barney', 'fred']
+ */
+ function map(collection, iteratee, thisArg) {
+ var func = isArray(collection) ? arrayMap : baseMap;
+ iteratee = getCallback(iteratee, thisArg, 3);
+ return func(collection, iteratee);
+ }
+ /**
+ * Creates an array of elements split into two groups, the first of which
+ * contains elements `predicate` returns truthy for, while the second of which
+ * contains elements `predicate` returns falsey for. The predicate is bound
+ * to `thisArg` and invoked with three arguments: (value, index|key, collection).
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {Array} Returns the array of grouped elements.
+ * @example
+ *
+ * _.partition([1, 2, 3], function(n) {
+ * return n % 2;
+ * });
+ * // => [[1, 3], [2]]
+ *
+ * _.partition([1.2, 2.3, 3.4], function(n) {
+ * return this.floor(n) % 2;
+ * }, Math);
+ * // => [[1.2, 3.4], [2.3]]
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36, 'active': false },
+ * { 'user': 'fred', 'age': 40, 'active': true },
+ * { 'user': 'pebbles', 'age': 1, 'active': false }
+ * ];
+ *
+ * var mapper = function(array) {
+ * return _.pluck(array, 'user');
+ * };
+ *
+ * // using the `_.matches` callback shorthand
+ * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper);
+ * // => [['pebbles'], ['barney', 'fred']]
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.map(_.partition(users, 'active', false), mapper);
+ * // => [['barney', 'pebbles'], ['fred']]
+ *
+ * // using the `_.property` callback shorthand
+ * _.map(_.partition(users, 'active'), mapper);
+ * // => [['fred'], ['barney', 'pebbles']]
+ */
+ var partition = createAggregator(function (result, value, key) {
+ result[key ? 0 : 1].push(value);
+ }, function () {
+ return [
+ [],
+ []
+ ];
+ });
+ /**
+ * Gets the property value of `path` from all elements in `collection`.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Array|string} path The path of the property to pluck.
+ * @returns {Array} Returns the property values.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36 },
+ * { 'user': 'fred', 'age': 40 }
+ * ];
+ *
+ * _.pluck(users, 'user');
+ * // => ['barney', 'fred']
+ *
+ * var userIndex = _.indexBy(users, 'user');
+ * _.pluck(userIndex, 'age');
+ * // => [36, 40] (iteration order is not guaranteed)
+ */
+ function pluck(collection, path) {
+ return map(collection, property(path));
+ }
+ /**
+ * Reduces `collection` to a value which is the accumulated result of running
+ * each element in `collection` through `iteratee`, where each successive
+ * invocation is supplied the return value of the previous. If `accumulator`
+ * is not provided the first element of `collection` is used as the initial
+ * value. The `iteratee` is bound to `thisArg` and invoked with four arguments:
+ * (accumulator, value, index|key, collection).
+ *
+ * Many lodash methods are guarded to work as iteratees for methods like
+ * `_.reduce`, `_.reduceRight`, and `_.transform`.
+ *
+ * The guarded methods are:
+ * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`,
+ * and `sortByOrder`
+ *
+ * @static
+ * @memberOf _
+ * @alias foldl, inject
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @param {*} [accumulator] The initial value.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {*} Returns the accumulated value.
+ * @example
+ *
+ * _.reduce([1, 2], function(total, n) {
+ * return total + n;
+ * });
+ * // => 3
+ *
+ * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
+ * result[key] = n * 3;
+ * return result;
+ * }, {});
+ * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
+ */
+ var reduce = createReduce(arrayReduce, baseEach);
+ /**
+ * This method is like `_.reduce` except that it iterates over elements of
+ * `collection` from right to left.
+ *
+ * @static
+ * @memberOf _
+ * @alias foldr
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @param {*} [accumulator] The initial value.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {*} Returns the accumulated value.
+ * @example
+ *
+ * var array = [[0, 1], [2, 3], [4, 5]];
+ *
+ * _.reduceRight(array, function(flattened, other) {
+ * return flattened.concat(other);
+ * }, []);
+ * // => [4, 5, 2, 3, 0, 1]
+ */
+ var reduceRight = createReduce(arrayReduceRight, baseEachRight);
+ /**
+ * The opposite of `_.filter`; this method returns the elements of `collection`
+ * that `predicate` does **not** return truthy for.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {Array} Returns the new filtered array.
+ * @example
+ *
+ * _.reject([1, 2, 3, 4], function(n) {
+ * return n % 2 == 0;
+ * });
+ * // => [1, 3]
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36, 'active': false },
+ * { 'user': 'fred', 'age': 40, 'active': true }
+ * ];
+ *
+ * // using the `_.matches` callback shorthand
+ * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');
+ * // => ['barney']
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.pluck(_.reject(users, 'active', false), 'user');
+ * // => ['fred']
+ *
+ * // using the `_.property` callback shorthand
+ * _.pluck(_.reject(users, 'active'), 'user');
+ * // => ['barney']
+ */
+ function reject(collection, predicate, thisArg) {
+ var func = isArray(collection) ? arrayFilter : baseFilter;
+ predicate = getCallback(predicate, thisArg, 3);
+ return func(collection, function (value, index, collection) {
+ return !predicate(value, index, collection);
+ });
+ }
+ /**
+ * Gets a random element or `n` random elements from a collection.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to sample.
+ * @param {number} [n] The number of elements to sample.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {*} Returns the random sample(s).
+ * @example
+ *
+ * _.sample([1, 2, 3, 4]);
+ * // => 2
+ *
+ * _.sample([1, 2, 3, 4], 2);
+ * // => [3, 1]
+ */
+ function sample(collection, n, guard) {
+ if (guard ? isIterateeCall(collection, n, guard) : n == null) {
+ collection = toIterable(collection);
+ var length = collection.length;
+ return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
+ }
+ var index = -1, result = toArray(collection), length = result.length, lastIndex = length - 1;
+ n = nativeMin(n < 0 ? 0 : +n || 0, length);
+ while (++index < n) {
+ var rand = baseRandom(index, lastIndex), value = result[rand];
+ result[rand] = result[index];
+ result[index] = value;
+ }
+ result.length = n;
+ return result;
+ }
+ /**
+ * Creates an array of shuffled values, using a version of the
+ * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to shuffle.
+ * @returns {Array} Returns the new shuffled array.
+ * @example
+ *
+ * _.shuffle([1, 2, 3, 4]);
+ * // => [4, 1, 3, 2]
+ */
+ function shuffle(collection) {
+ return sample(collection, POSITIVE_INFINITY);
+ }
+ /**
+ * Gets the size of `collection` by returning its length for array-like
+ * values or the number of own enumerable properties for objects.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to inspect.
+ * @returns {number} Returns the size of `collection`.
+ * @example
+ *
+ * _.size([1, 2, 3]);
+ * // => 3
+ *
+ * _.size({ 'a': 1, 'b': 2 });
+ * // => 2
+ *
+ * _.size('pebbles');
+ * // => 7
+ */
+ function size(collection) {
+ var length = collection ? getLength(collection) : 0;
+ return isLength(length) ? length : keys(collection).length;
+ }
+ /**
+ * Checks if `predicate` returns truthy for **any** element of `collection`.
+ * The function returns as soon as it finds a passing value and does not iterate
+ * over the entire collection. The predicate is bound to `thisArg` and invoked
+ * with three arguments: (value, index|key, collection).
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @alias any
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {boolean} Returns `true` if any element passes the predicate check,
+ * else `false`.
+ * @example
+ *
+ * _.some([null, 0, 'yes', false], Boolean);
+ * // => true
+ *
+ * var users = [
+ * { 'user': 'barney', 'active': true },
+ * { 'user': 'fred', 'active': false }
+ * ];
+ *
+ * // using the `_.matches` callback shorthand
+ * _.some(users, { 'user': 'barney', 'active': false });
+ * // => false
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.some(users, 'active', false);
+ * // => true
+ *
+ * // using the `_.property` callback shorthand
+ * _.some(users, 'active');
+ * // => true
+ */
+ function some(collection, predicate, thisArg) {
+ var func = isArray(collection) ? arraySome : baseSome;
+ if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
+ predicate = undefined;
+ }
+ if (typeof predicate != 'function' || thisArg !== undefined) {
+ predicate = getCallback(predicate, thisArg, 3);
+ }
+ return func(collection, predicate);
+ }
+ /**
+ * Creates an array of elements, sorted in ascending order by the results of
+ * running each element in a collection through `iteratee`. This method performs
+ * a stable sort, that is, it preserves the original sort order of equal elements.
+ * The `iteratee` is bound to `thisArg` and invoked with three arguments:
+ * (value, index|key, collection).
+ *
+ * If a property name is provided for `iteratee` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `iteratee` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Array} Returns the new sorted array.
+ * @example
+ *
+ * _.sortBy([1, 2, 3], function(n) {
+ * return Math.sin(n);
+ * });
+ * // => [3, 1, 2]
+ *
+ * _.sortBy([1, 2, 3], function(n) {
+ * return this.sin(n);
+ * }, Math);
+ * // => [3, 1, 2]
+ *
+ * var users = [
+ * { 'user': 'fred' },
+ * { 'user': 'pebbles' },
+ * { 'user': 'barney' }
+ * ];
+ *
+ * // using the `_.property` callback shorthand
+ * _.pluck(_.sortBy(users, 'user'), 'user');
+ * // => ['barney', 'fred', 'pebbles']
+ */
+ function sortBy(collection, iteratee, thisArg) {
+ if (collection == null) {
+ return [];
+ }
+ if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
+ iteratee = undefined;
+ }
+ var index = -1;
+ iteratee = getCallback(iteratee, thisArg, 3);
+ var result = baseMap(collection, function (value, key, collection) {
+ return {
+ 'criteria': iteratee(value, key, collection),
+ 'index': ++index,
+ 'value': value
+ };
+ });
+ return baseSortBy(result, compareAscending);
+ }
+ /**
+ * This method is like `_.sortBy` except that it can sort by multiple iteratees
+ * or property names.
+ *
+ * If a property name is provided for an iteratee the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If an object is provided for an iteratee the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees
+ * The iteratees to sort by, specified as individual values or arrays of values.
+ * @returns {Array} Returns the new sorted array.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'fred', 'age': 48 },
+ * { 'user': 'barney', 'age': 36 },
+ * { 'user': 'fred', 'age': 42 },
+ * { 'user': 'barney', 'age': 34 }
+ * ];
+ *
+ * _.map(_.sortByAll(users, ['user', 'age']), _.values);
+ * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
+ *
+ * _.map(_.sortByAll(users, 'user', function(chr) {
+ * return Math.floor(chr.age / 10);
+ * }), _.values);
+ * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
+ */
+ var sortByAll = restParam(function (collection, iteratees) {
+ if (collection == null) {
+ return [];
+ }
+ var guard = iteratees[2];
+ if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) {
+ iteratees.length = 1;
+ }
+ return baseSortByOrder(collection, baseFlatten(iteratees), []);
+ });
+ /**
+ * This method is like `_.sortByAll` except that it allows specifying the
+ * sort orders of the iteratees to sort by. If `orders` is unspecified, all
+ * values are sorted in ascending order. Otherwise, a value is sorted in
+ * ascending order if its corresponding order is "asc", and descending if "desc".
+ *
+ * If a property name is provided for an iteratee the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If an object is provided for an iteratee the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
+ * @param {boolean[]} [orders] The sort orders of `iteratees`.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
+ * @returns {Array} Returns the new sorted array.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'fred', 'age': 48 },
+ * { 'user': 'barney', 'age': 34 },
+ * { 'user': 'fred', 'age': 42 },
+ * { 'user': 'barney', 'age': 36 }
+ * ];
+ *
+ * // sort by `user` in ascending order and by `age` in descending order
+ * _.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values);
+ * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
+ */
+ function sortByOrder(collection, iteratees, orders, guard) {
+ if (collection == null) {
+ return [];
+ }
+ if (guard && isIterateeCall(iteratees, orders, guard)) {
+ orders = undefined;
+ }
+ if (!isArray(iteratees)) {
+ iteratees = iteratees == null ? [] : [iteratees];
+ }
+ if (!isArray(orders)) {
+ orders = orders == null ? [] : [orders];
+ }
+ return baseSortByOrder(collection, iteratees, orders);
+ }
+ /**
+ * Performs a deep comparison between each element in `collection` and the
+ * source object, returning an array of all elements that have equivalent
+ * property values.
+ *
+ * **Note:** This method supports comparing arrays, booleans, `Date` objects,
+ * numbers, `Object` objects, regexes, and strings. Objects are compared by
+ * their own, not inherited, enumerable properties. For comparing a single
+ * own or inherited property value see `_.matchesProperty`.
+ *
+ * @static
+ * @memberOf _
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to search.
+ * @param {Object} source The object of property values to match.
+ * @returns {Array} Returns the new filtered array.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },
+ * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }
+ * ];
+ *
+ * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');
+ * // => ['barney']
+ *
+ * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
+ * // => ['fred']
+ */
+ function where(collection, source) {
+ return filter(collection, baseMatches(source));
+ }
+ /*------------------------------------------------------------------------*/
+ /**
+ * Gets the number of milliseconds that have elapsed since the Unix epoch
+ * (1 January 1970 00:00:00 UTC).
+ *
+ * @static
+ * @memberOf _
+ * @category Date
+ * @example
+ *
+ * _.defer(function(stamp) {
+ * console.log(_.now() - stamp);
+ * }, _.now());
+ * // => logs the number of milliseconds it took for the deferred function to be invoked
+ */
+ var now = nativeNow || function () {
+ return new Date().getTime();
+ };
+ /*------------------------------------------------------------------------*/
+ /**
+ * The opposite of `_.before`; this method creates a function that invokes
+ * `func` once it's called `n` or more times.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {number} n The number of calls before `func` is invoked.
+ * @param {Function} func The function to restrict.
+ * @returns {Function} Returns the new restricted function.
+ * @example
+ *
+ * var saves = ['profile', 'settings'];
+ *
+ * var done = _.after(saves.length, function() {
+ * console.log('done saving!');
+ * });
+ *
+ * _.forEach(saves, function(type) {
+ * asyncSave({ 'type': type, 'complete': done });
+ * });
+ * // => logs 'done saving!' after the two async saves have completed
+ */
+ function after(n, func) {
+ if (typeof func != 'function') {
+ if (typeof n == 'function') {
+ var temp = n;
+ n = func;
+ func = temp;
+ } else {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ }
+ n = nativeIsFinite(n = +n) ? n : 0;
+ return function () {
+ if (--n < 1) {
+ return func.apply(this, arguments);
+ }
+ };
+ }
+ /**
+ * Creates a function that accepts up to `n` arguments ignoring any
+ * additional arguments.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to cap arguments for.
+ * @param {number} [n=func.length] The arity cap.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * _.map(['6', '8', '10'], _.ary(parseInt, 1));
+ * // => [6, 8, 10]
+ */
+ function ary(func, n, guard) {
+ if (guard && isIterateeCall(func, n, guard)) {
+ n = undefined;
+ }
+ n = func && n == null ? func.length : nativeMax(+n || 0, 0);
+ return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n);
+ }
+ /**
+ * Creates a function that invokes `func`, with the `this` binding and arguments
+ * of the created function, while it's called less than `n` times. Subsequent
+ * calls to the created function return the result of the last `func` invocation.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {number} n The number of calls at which `func` is no longer invoked.
+ * @param {Function} func The function to restrict.
+ * @returns {Function} Returns the new restricted function.
+ * @example
+ *
+ * jQuery('#add').on('click', _.before(5, addContactToList));
+ * // => allows adding up to 4 contacts to the list
+ */
+ function before(n, func) {
+ var result;
+ if (typeof func != 'function') {
+ if (typeof n == 'function') {
+ var temp = n;
+ n = func;
+ func = temp;
+ } else {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ }
+ return function () {
+ if (--n > 0) {
+ result = func.apply(this, arguments);
+ }
+ if (n <= 1) {
+ func = undefined;
+ }
+ return result;
+ };
+ }
+ /**
+ * Creates a function that invokes `func` with the `this` binding of `thisArg`
+ * and prepends any additional `_.bind` arguments to those provided to the
+ * bound function.
+ *
+ * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
+ * may be used as a placeholder for partially applied arguments.
+ *
+ * **Note:** Unlike native `Function#bind` this method does not set the "length"
+ * property of bound functions.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to bind.
+ * @param {*} thisArg The `this` binding of `func`.
+ * @param {...*} [partials] The arguments to be partially applied.
+ * @returns {Function} Returns the new bound function.
+ * @example
+ *
+ * var greet = function(greeting, punctuation) {
+ * return greeting + ' ' + this.user + punctuation;
+ * };
+ *
+ * var object = { 'user': 'fred' };
+ *
+ * var bound = _.bind(greet, object, 'hi');
+ * bound('!');
+ * // => 'hi fred!'
+ *
+ * // using placeholders
+ * var bound = _.bind(greet, object, _, '!');
+ * bound('hi');
+ * // => 'hi fred!'
+ */
+ var bind = restParam(function (func, thisArg, partials) {
+ var bitmask = BIND_FLAG;
+ if (partials.length) {
+ var holders = replaceHolders(partials, bind.placeholder);
+ bitmask |= PARTIAL_FLAG;
+ }
+ return createWrapper(func, bitmask, thisArg, partials, holders);
+ });
+ /**
+ * Binds methods of an object to the object itself, overwriting the existing
+ * method. Method names may be specified as individual arguments or as arrays
+ * of method names. If no method names are provided all enumerable function
+ * properties, own and inherited, of `object` are bound.
+ *
+ * **Note:** This method does not set the "length" property of bound functions.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Object} object The object to bind and assign the bound methods to.
+ * @param {...(string|string[])} [methodNames] The object method names to bind,
+ * specified as individual method names or arrays of method names.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * var view = {
+ * 'label': 'docs',
+ * 'onClick': function() {
+ * console.log('clicked ' + this.label);
+ * }
+ * };
+ *
+ * _.bindAll(view);
+ * jQuery('#docs').on('click', view.onClick);
+ * // => logs 'clicked docs' when the element is clicked
+ */
+ var bindAll = restParam(function (object, methodNames) {
+ methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object);
+ var index = -1, length = methodNames.length;
+ while (++index < length) {
+ var key = methodNames[index];
+ object[key] = createWrapper(object[key], BIND_FLAG, object);
+ }
+ return object;
+ });
+ /**
+ * Creates a function that invokes the method at `object[key]` and prepends
+ * any additional `_.bindKey` arguments to those provided to the bound function.
+ *
+ * This method differs from `_.bind` by allowing bound functions to reference
+ * methods that may be redefined or don't yet exist.
+ * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
+ * for more details.
+ *
+ * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
+ * builds, may be used as a placeholder for partially applied arguments.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Object} object The object the method belongs to.
+ * @param {string} key The key of the method.
+ * @param {...*} [partials] The arguments to be partially applied.
+ * @returns {Function} Returns the new bound function.
+ * @example
+ *
+ * var object = {
+ * 'user': 'fred',
+ * 'greet': function(greeting, punctuation) {
+ * return greeting + ' ' + this.user + punctuation;
+ * }
+ * };
+ *
+ * var bound = _.bindKey(object, 'greet', 'hi');
+ * bound('!');
+ * // => 'hi fred!'
+ *
+ * object.greet = function(greeting, punctuation) {
+ * return greeting + 'ya ' + this.user + punctuation;
+ * };
+ *
+ * bound('!');
+ * // => 'hiya fred!'
+ *
+ * // using placeholders
+ * var bound = _.bindKey(object, 'greet', _, '!');
+ * bound('hi');
+ * // => 'hiya fred!'
+ */
+ var bindKey = restParam(function (object, key, partials) {
+ var bitmask = BIND_FLAG | BIND_KEY_FLAG;
+ if (partials.length) {
+ var holders = replaceHolders(partials, bindKey.placeholder);
+ bitmask |= PARTIAL_FLAG;
+ }
+ return createWrapper(key, bitmask, object, partials, holders);
+ });
+ /**
+ * Creates a function that accepts one or more arguments of `func` that when
+ * called either invokes `func` returning its result, if all `func` arguments
+ * have been provided, or returns a function that accepts one or more of the
+ * remaining `func` arguments, and so on. The arity of `func` may be specified
+ * if `func.length` is not sufficient.
+ *
+ * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
+ * may be used as a placeholder for provided arguments.
+ *
+ * **Note:** This method does not set the "length" property of curried functions.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to curry.
+ * @param {number} [arity=func.length] The arity of `func`.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {Function} Returns the new curried function.
+ * @example
+ *
+ * var abc = function(a, b, c) {
+ * return [a, b, c];
+ * };
+ *
+ * var curried = _.curry(abc);
+ *
+ * curried(1)(2)(3);
+ * // => [1, 2, 3]
+ *
+ * curried(1, 2)(3);
+ * // => [1, 2, 3]
+ *
+ * curried(1, 2, 3);
+ * // => [1, 2, 3]
+ *
+ * // using placeholders
+ * curried(1)(_, 3)(2);
+ * // => [1, 2, 3]
+ */
+ var curry = createCurry(CURRY_FLAG);
+ /**
+ * This method is like `_.curry` except that arguments are applied to `func`
+ * in the manner of `_.partialRight` instead of `_.partial`.
+ *
+ * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
+ * builds, may be used as a placeholder for provided arguments.
+ *
+ * **Note:** This method does not set the "length" property of curried functions.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to curry.
+ * @param {number} [arity=func.length] The arity of `func`.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {Function} Returns the new curried function.
+ * @example
+ *
+ * var abc = function(a, b, c) {
+ * return [a, b, c];
+ * };
+ *
+ * var curried = _.curryRight(abc);
+ *
+ * curried(3)(2)(1);
+ * // => [1, 2, 3]
+ *
+ * curried(2, 3)(1);
+ * // => [1, 2, 3]
+ *
+ * curried(1, 2, 3);
+ * // => [1, 2, 3]
+ *
+ * // using placeholders
+ * curried(3)(1, _)(2);
+ * // => [1, 2, 3]
+ */
+ var curryRight = createCurry(CURRY_RIGHT_FLAG);
+ /**
+ * Creates a debounced function that delays invoking `func` until after `wait`
+ * milliseconds have elapsed since the last time the debounced function was
+ * invoked. The debounced function comes with a `cancel` method to cancel
+ * delayed invocations. Provide an options object to indicate that `func`
+ * should be invoked on the leading and/or trailing edge of the `wait` timeout.
+ * Subsequent calls to the debounced function return the result of the last
+ * `func` invocation.
+ *
+ * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
+ * on the trailing edge of the timeout only if the the debounced function is
+ * invoked more than once during the `wait` timeout.
+ *
+ * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
+ * for details over the differences between `_.debounce` and `_.throttle`.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to debounce.
+ * @param {number} [wait=0] The number of milliseconds to delay.
+ * @param {Object} [options] The options object.
+ * @param {boolean} [options.leading=false] Specify invoking on the leading
+ * edge of the timeout.
+ * @param {number} [options.maxWait] The maximum time `func` is allowed to be
+ * delayed before it's invoked.
+ * @param {boolean} [options.trailing=true] Specify invoking on the trailing
+ * edge of the timeout.
+ * @returns {Function} Returns the new debounced function.
+ * @example
+ *
+ * // avoid costly calculations while the window size is in flux
+ * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
+ *
+ * // invoke `sendMail` when the click event is fired, debouncing subsequent calls
+ * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
+ * 'leading': true,
+ * 'trailing': false
+ * }));
+ *
+ * // ensure `batchLog` is invoked once after 1 second of debounced calls
+ * var source = new EventSource('/stream');
+ * jQuery(source).on('message', _.debounce(batchLog, 250, {
+ * 'maxWait': 1000
+ * }));
+ *
+ * // cancel a debounced call
+ * var todoChanges = _.debounce(batchLog, 1000);
+ * Object.observe(models.todo, todoChanges);
+ *
+ * Object.observe(models, function(changes) {
+ * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
+ * todoChanges.cancel();
+ * }
+ * }, ['delete']);
+ *
+ * // ...at some point `models.todo` is changed
+ * models.todo.completed = true;
+ *
+ * // ...before 1 second has passed `models.todo` is deleted
+ * // which cancels the debounced `todoChanges` call
+ * delete models.todo;
+ */
+ function debounce(func, wait, options) {
+ var args, maxTimeoutId, result, stamp, thisArg, timeoutId, trailingCall, lastCalled = 0, maxWait = false, trailing = true;
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ wait = wait < 0 ? 0 : +wait || 0;
+ if (options === true) {
+ var leading = true;
+ trailing = false;
+ } else if (isObject(options)) {
+ leading = !!options.leading;
+ maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
+ trailing = 'trailing' in options ? !!options.trailing : trailing;
+ }
+ function cancel() {
+ if (timeoutId) {
+ clearTimeout(timeoutId);
+ }
+ if (maxTimeoutId) {
+ clearTimeout(maxTimeoutId);
+ }
+ lastCalled = 0;
+ maxTimeoutId = timeoutId = trailingCall = undefined;
+ }
+ function complete(isCalled, id) {
+ if (id) {
+ clearTimeout(id);
+ }
+ maxTimeoutId = timeoutId = trailingCall = undefined;
+ if (isCalled) {
+ lastCalled = now();
+ result = func.apply(thisArg, args);
+ if (!timeoutId && !maxTimeoutId) {
+ args = thisArg = undefined;
+ }
+ }
+ }
+ function delayed() {
+ var remaining = wait - (now() - stamp);
+ if (remaining <= 0 || remaining > wait) {
+ complete(trailingCall, maxTimeoutId);
+ } else {
+ timeoutId = setTimeout(delayed, remaining);
+ }
+ }
+ function maxDelayed() {
+ complete(trailing, timeoutId);
+ }
+ function debounced() {
+ args = arguments;
+ stamp = now();
+ thisArg = this;
+ trailingCall = trailing && (timeoutId || !leading);
+ if (maxWait === false) {
+ var leadingCall = leading && !timeoutId;
+ } else {
+ if (!maxTimeoutId && !leading) {
+ lastCalled = stamp;
+ }
+ var remaining = maxWait - (stamp - lastCalled), isCalled = remaining <= 0 || remaining > maxWait;
+ if (isCalled) {
+ if (maxTimeoutId) {
+ maxTimeoutId = clearTimeout(maxTimeoutId);
+ }
+ lastCalled = stamp;
+ result = func.apply(thisArg, args);
+ } else if (!maxTimeoutId) {
+ maxTimeoutId = setTimeout(maxDelayed, remaining);
+ }
+ }
+ if (isCalled && timeoutId) {
+ timeoutId = clearTimeout(timeoutId);
+ } else if (!timeoutId && wait !== maxWait) {
+ timeoutId = setTimeout(delayed, wait);
+ }
+ if (leadingCall) {
+ isCalled = true;
+ result = func.apply(thisArg, args);
+ }
+ if (isCalled && !timeoutId && !maxTimeoutId) {
+ args = thisArg = undefined;
+ }
+ return result;
+ }
+ debounced.cancel = cancel;
+ return debounced;
+ }
+ /**
+ * Defers invoking the `func` until the current call stack has cleared. Any
+ * additional arguments are provided to `func` when it's invoked.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to defer.
+ * @param {...*} [args] The arguments to invoke the function with.
+ * @returns {number} Returns the timer id.
+ * @example
+ *
+ * _.defer(function(text) {
+ * console.log(text);
+ * }, 'deferred');
+ * // logs 'deferred' after one or more milliseconds
+ */
+ var defer = restParam(function (func, args) {
+ return baseDelay(func, 1, args);
+ });
+ /**
+ * Invokes `func` after `wait` milliseconds. Any additional arguments are
+ * provided to `func` when it's invoked.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to delay.
+ * @param {number} wait The number of milliseconds to delay invocation.
+ * @param {...*} [args] The arguments to invoke the function with.
+ * @returns {number} Returns the timer id.
+ * @example
+ *
+ * _.delay(function(text) {
+ * console.log(text);
+ * }, 1000, 'later');
+ * // => logs 'later' after one second
+ */
+ var delay = restParam(function (func, wait, args) {
+ return baseDelay(func, wait, args);
+ });
+ /**
+ * Creates a function that returns the result of invoking the provided
+ * functions with the `this` binding of the created function, where each
+ * successive invocation is supplied the return value of the previous.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {...Function} [funcs] Functions to invoke.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * function square(n) {
+ * return n * n;
+ * }
+ *
+ * var addSquare = _.flow(_.add, square);
+ * addSquare(1, 2);
+ * // => 9
+ */
+ var flow = createFlow();
+ /**
+ * This method is like `_.flow` except that it creates a function that
+ * invokes the provided functions from right to left.
+ *
+ * @static
+ * @memberOf _
+ * @alias backflow, compose
+ * @category Function
+ * @param {...Function} [funcs] Functions to invoke.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * function square(n) {
+ * return n * n;
+ * }
+ *
+ * var addSquare = _.flowRight(square, _.add);
+ * addSquare(1, 2);
+ * // => 9
+ */
+ var flowRight = createFlow(true);
+ /**
+ * Creates a function that memoizes the result of `func`. If `resolver` is
+ * provided it determines the cache key for storing the result based on the
+ * arguments provided to the memoized function. By default, the first argument
+ * provided to the memoized function is coerced to a string and used as the
+ * cache key. The `func` is invoked with the `this` binding of the memoized
+ * function.
+ *
+ * **Note:** The cache is exposed as the `cache` property on the memoized
+ * function. Its creation may be customized by replacing the `_.memoize.Cache`
+ * constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
+ * method interface of `get`, `has`, and `set`.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to have its output memoized.
+ * @param {Function} [resolver] The function to resolve the cache key.
+ * @returns {Function} Returns the new memoizing function.
+ * @example
+ *
+ * var upperCase = _.memoize(function(string) {
+ * return string.toUpperCase();
+ * });
+ *
+ * upperCase('fred');
+ * // => 'FRED'
+ *
+ * // modifying the result cache
+ * upperCase.cache.set('fred', 'BARNEY');
+ * upperCase('fred');
+ * // => 'BARNEY'
+ *
+ * // replacing `_.memoize.Cache`
+ * var object = { 'user': 'fred' };
+ * var other = { 'user': 'barney' };
+ * var identity = _.memoize(_.identity);
+ *
+ * identity(object);
+ * // => { 'user': 'fred' }
+ * identity(other);
+ * // => { 'user': 'fred' }
+ *
+ * _.memoize.Cache = WeakMap;
+ * var identity = _.memoize(_.identity);
+ *
+ * identity(object);
+ * // => { 'user': 'fred' }
+ * identity(other);
+ * // => { 'user': 'barney' }
+ */
+ function memoize(func, resolver) {
+ if (typeof func != 'function' || resolver && typeof resolver != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ var memoized = function () {
+ var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
+ if (cache.has(key)) {
+ return cache.get(key);
+ }
+ var result = func.apply(this, args);
+ memoized.cache = cache.set(key, result);
+ return result;
+ };
+ memoized.cache = new memoize.Cache();
+ return memoized;
+ }
+ /**
+ * Creates a function that runs each argument through a corresponding
+ * transform function.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to wrap.
+ * @param {...(Function|Function[])} [transforms] The functions to transform
+ * arguments, specified as individual functions or arrays of functions.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * function doubled(n) {
+ * return n * 2;
+ * }
+ *
+ * function square(n) {
+ * return n * n;
+ * }
+ *
+ * var modded = _.modArgs(function(x, y) {
+ * return [x, y];
+ * }, square, doubled);
+ *
+ * modded(1, 2);
+ * // => [1, 4]
+ *
+ * modded(5, 10);
+ * // => [25, 20]
+ */
+ var modArgs = restParam(function (func, transforms) {
+ transforms = baseFlatten(transforms);
+ if (typeof func != 'function' || !arrayEvery(transforms, baseIsFunction)) {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ var length = transforms.length;
+ return restParam(function (args) {
+ var index = nativeMin(args.length, length);
+ while (index--) {
+ args[index] = transforms[index](args[index]);
+ }
+ return func.apply(this, args);
+ });
+ });
+ /**
+ * Creates a function that negates the result of the predicate `func`. The
+ * `func` predicate is invoked with the `this` binding and arguments of the
+ * created function.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} predicate The predicate to negate.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * function isEven(n) {
+ * return n % 2 == 0;
+ * }
+ *
+ * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
+ * // => [1, 3, 5]
+ */
+ function negate(predicate) {
+ if (typeof predicate != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ return function () {
+ return !predicate.apply(this, arguments);
+ };
+ }
+ /**
+ * Creates a function that is restricted to invoking `func` once. Repeat calls
+ * to the function return the value of the first call. The `func` is invoked
+ * with the `this` binding and arguments of the created function.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to restrict.
+ * @returns {Function} Returns the new restricted function.
+ * @example
+ *
+ * var initialize = _.once(createApplication);
+ * initialize();
+ * initialize();
+ * // `initialize` invokes `createApplication` once
+ */
+ function once(func) {
+ return before(2, func);
+ }
+ /**
+ * Creates a function that invokes `func` with `partial` arguments prepended
+ * to those provided to the new function. This method is like `_.bind` except
+ * it does **not** alter the `this` binding.
+ *
+ * The `_.partial.placeholder` value, which defaults to `_` in monolithic
+ * builds, may be used as a placeholder for partially applied arguments.
+ *
+ * **Note:** This method does not set the "length" property of partially
+ * applied functions.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to partially apply arguments to.
+ * @param {...*} [partials] The arguments to be partially applied.
+ * @returns {Function} Returns the new partially applied function.
+ * @example
+ *
+ * var greet = function(greeting, name) {
+ * return greeting + ' ' + name;
+ * };
+ *
+ * var sayHelloTo = _.partial(greet, 'hello');
+ * sayHelloTo('fred');
+ * // => 'hello fred'
+ *
+ * // using placeholders
+ * var greetFred = _.partial(greet, _, 'fred');
+ * greetFred('hi');
+ * // => 'hi fred'
+ */
+ var partial = createPartial(PARTIAL_FLAG);
+ /**
+ * This method is like `_.partial` except that partially applied arguments
+ * are appended to those provided to the new function.
+ *
+ * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
+ * builds, may be used as a placeholder for partially applied arguments.
+ *
+ * **Note:** This method does not set the "length" property of partially
+ * applied functions.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to partially apply arguments to.
+ * @param {...*} [partials] The arguments to be partially applied.
+ * @returns {Function} Returns the new partially applied function.
+ * @example
+ *
+ * var greet = function(greeting, name) {
+ * return greeting + ' ' + name;
+ * };
+ *
+ * var greetFred = _.partialRight(greet, 'fred');
+ * greetFred('hi');
+ * // => 'hi fred'
+ *
+ * // using placeholders
+ * var sayHelloTo = _.partialRight(greet, 'hello', _);
+ * sayHelloTo('fred');
+ * // => 'hello fred'
+ */
+ var partialRight = createPartial(PARTIAL_RIGHT_FLAG);
+ /**
+ * Creates a function that invokes `func` with arguments arranged according
+ * to the specified indexes where the argument value at the first index is
+ * provided as the first argument, the argument value at the second index is
+ * provided as the second argument, and so on.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to rearrange arguments for.
+ * @param {...(number|number[])} indexes The arranged argument indexes,
+ * specified as individual indexes or arrays of indexes.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var rearged = _.rearg(function(a, b, c) {
+ * return [a, b, c];
+ * }, 2, 0, 1);
+ *
+ * rearged('b', 'c', 'a')
+ * // => ['a', 'b', 'c']
+ *
+ * var map = _.rearg(_.map, [1, 0]);
+ * map(function(n) {
+ * return n * 3;
+ * }, [1, 2, 3]);
+ * // => [3, 6, 9]
+ */
+ var rearg = restParam(function (func, indexes) {
+ return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes));
+ });
+ /**
+ * Creates a function that invokes `func` with the `this` binding of the
+ * created function and arguments from `start` and beyond provided as an array.
+ *
+ * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters).
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to apply a rest parameter to.
+ * @param {number} [start=func.length-1] The start position of the rest parameter.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var say = _.restParam(function(what, names) {
+ * return what + ' ' + _.initial(names).join(', ') +
+ * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
+ * });
+ *
+ * say('hello', 'fred', 'barney', 'pebbles');
+ * // => 'hello fred, barney, & pebbles'
+ */
+ function restParam(func, start) {
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ start = nativeMax(start === undefined ? func.length - 1 : +start || 0, 0);
+ return function () {
+ var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length);
+ while (++index < length) {
+ rest[index] = args[start + index];
+ }
+ switch (start) {
+ case 0:
+ return func.call(this, rest);
+ case 1:
+ return func.call(this, args[0], rest);
+ case 2:
+ return func.call(this, args[0], args[1], rest);
+ }
+ var otherArgs = Array(start + 1);
+ index = -1;
+ while (++index < start) {
+ otherArgs[index] = args[index];
+ }
+ otherArgs[start] = rest;
+ return func.apply(this, otherArgs);
+ };
+ }
+ /**
+ * Creates a function that invokes `func` with the `this` binding of the created
+ * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
+ *
+ * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/Web/JavaScript/Reference/Operators/Spread_operator).
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to spread arguments over.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var say = _.spread(function(who, what) {
+ * return who + ' says ' + what;
+ * });
+ *
+ * say(['fred', 'hello']);
+ * // => 'fred says hello'
+ *
+ * // with a Promise
+ * var numbers = Promise.all([
+ * Promise.resolve(40),
+ * Promise.resolve(36)
+ * ]);
+ *
+ * numbers.then(_.spread(function(x, y) {
+ * return x + y;
+ * }));
+ * // => a Promise of 76
+ */
+ function spread(func) {
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ return function (array) {
+ return func.apply(this, array);
+ };
+ }
+ /**
+ * Creates a throttled function that only invokes `func` at most once per
+ * every `wait` milliseconds. The throttled function comes with a `cancel`
+ * method to cancel delayed invocations. Provide an options object to indicate
+ * that `func` should be invoked on the leading and/or trailing edge of the
+ * `wait` timeout. Subsequent calls to the throttled function return the
+ * result of the last `func` call.
+ *
+ * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
+ * on the trailing edge of the timeout only if the the throttled function is
+ * invoked more than once during the `wait` timeout.
+ *
+ * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
+ * for details over the differences between `_.throttle` and `_.debounce`.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {Function} func The function to throttle.
+ * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
+ * @param {Object} [options] The options object.
+ * @param {boolean} [options.leading=true] Specify invoking on the leading
+ * edge of the timeout.
+ * @param {boolean} [options.trailing=true] Specify invoking on the trailing
+ * edge of the timeout.
+ * @returns {Function} Returns the new throttled function.
+ * @example
+ *
+ * // avoid excessively updating the position while scrolling
+ * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
+ *
+ * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
+ * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
+ * 'trailing': false
+ * }));
+ *
+ * // cancel a trailing throttled call
+ * jQuery(window).on('popstate', throttled.cancel);
+ */
+ function throttle(func, wait, options) {
+ var leading = true, trailing = true;
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ if (options === false) {
+ leading = false;
+ } else if (isObject(options)) {
+ leading = 'leading' in options ? !!options.leading : leading;
+ trailing = 'trailing' in options ? !!options.trailing : trailing;
+ }
+ return debounce(func, wait, {
+ 'leading': leading,
+ 'maxWait': +wait,
+ 'trailing': trailing
+ });
+ }
+ /**
+ * Creates a function that provides `value` to the wrapper function as its
+ * first argument. Any additional arguments provided to the function are
+ * appended to those provided to the wrapper function. The wrapper is invoked
+ * with the `this` binding of the created function.
+ *
+ * @static
+ * @memberOf _
+ * @category Function
+ * @param {*} value The value to wrap.
+ * @param {Function} wrapper The wrapper function.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var p = _.wrap(_.escape, function(func, text) {
+ * return '<p>' + func(text) + '</p>';
+ * });
+ *
+ * p('fred, barney, & pebbles');
+ * // => '<p>fred, barney, & pebbles</p>'
+ */
+ function wrap(value, wrapper) {
+ wrapper = wrapper == null ? identity : wrapper;
+ return createWrapper(wrapper, PARTIAL_FLAG, undefined, [value], []);
+ }
+ /*------------------------------------------------------------------------*/
+ /**
+ * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned,
+ * otherwise they are assigned by reference. If `customizer` is provided it's
+ * invoked to produce the cloned values. If `customizer` returns `undefined`
+ * cloning is handled by the method instead. The `customizer` is bound to
+ * `thisArg` and invoked with up to three argument; (value [, index|key, object]).
+ *
+ * **Note:** This method is loosely based on the
+ * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
+ * The enumerable properties of `arguments` objects and objects created by
+ * constructors other than `Object` are cloned to plain `Object` objects. An
+ * empty object is returned for uncloneable values such as functions, DOM nodes,
+ * Maps, Sets, and WeakMaps.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to clone.
+ * @param {boolean} [isDeep] Specify a deep clone.
+ * @param {Function} [customizer] The function to customize cloning values.
+ * @param {*} [thisArg] The `this` binding of `customizer`.
+ * @returns {*} Returns the cloned value.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney' },
+ * { 'user': 'fred' }
+ * ];
+ *
+ * var shallow = _.clone(users);
+ * shallow[0] === users[0];
+ * // => true
+ *
+ * var deep = _.clone(users, true);
+ * deep[0] === users[0];
+ * // => false
+ *
+ * // using a customizer callback
+ * var el = _.clone(document.body, function(value) {
+ * if (_.isElement(value)) {
+ * return value.cloneNode(false);
+ * }
+ * });
+ *
+ * el === document.body
+ * // => false
+ * el.nodeName
+ * // => BODY
+ * el.childNodes.length;
+ * // => 0
+ */
+ function clone(value, isDeep, customizer, thisArg) {
+ if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) {
+ isDeep = false;
+ } else if (typeof isDeep == 'function') {
+ thisArg = customizer;
+ customizer = isDeep;
+ isDeep = false;
+ }
+ return typeof customizer == 'function' ? baseClone(value, isDeep, bindCallback(customizer, thisArg, 3)) : baseClone(value, isDeep);
+ }
+ /**
+ * Creates a deep clone of `value`. If `customizer` is provided it's invoked
+ * to produce the cloned values. If `customizer` returns `undefined` cloning
+ * is handled by the method instead. The `customizer` is bound to `thisArg`
+ * and invoked with up to three argument; (value [, index|key, object]).
+ *
+ * **Note:** This method is loosely based on the
+ * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
+ * The enumerable properties of `arguments` objects and objects created by
+ * constructors other than `Object` are cloned to plain `Object` objects. An
+ * empty object is returned for uncloneable values such as functions, DOM nodes,
+ * Maps, Sets, and WeakMaps.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to deep clone.
+ * @param {Function} [customizer] The function to customize cloning values.
+ * @param {*} [thisArg] The `this` binding of `customizer`.
+ * @returns {*} Returns the deep cloned value.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney' },
+ * { 'user': 'fred' }
+ * ];
+ *
+ * var deep = _.cloneDeep(users);
+ * deep[0] === users[0];
+ * // => false
+ *
+ * // using a customizer callback
+ * var el = _.cloneDeep(document.body, function(value) {
+ * if (_.isElement(value)) {
+ * return value.cloneNode(true);
+ * }
+ * });
+ *
+ * el === document.body
+ * // => false
+ * el.nodeName
+ * // => BODY
+ * el.childNodes.length;
+ * // => 20
+ */
+ function cloneDeep(value, customizer, thisArg) {
+ return typeof customizer == 'function' ? baseClone(value, true, bindCallback(customizer, thisArg, 3)) : baseClone(value, true);
+ }
+ /**
+ * Checks if `value` is greater than `other`.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {boolean} Returns `true` if `value` is greater than `other`, else `false`.
+ * @example
+ *
+ * _.gt(3, 1);
+ * // => true
+ *
+ * _.gt(3, 3);
+ * // => false
+ *
+ * _.gt(1, 3);
+ * // => false
+ */
+ function gt(value, other) {
+ return value > other;
+ }
+ /**
+ * Checks if `value` is greater than or equal to `other`.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {boolean} Returns `true` if `value` is greater than or equal to `other`, else `false`.
+ * @example
+ *
+ * _.gte(3, 1);
+ * // => true
+ *
+ * _.gte(3, 3);
+ * // => true
+ *
+ * _.gte(1, 3);
+ * // => false
+ */
+ function gte(value, other) {
+ return value >= other;
+ }
+ /**
+ * Checks if `value` is classified as an `arguments` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isArguments(function() { return arguments; }());
+ * // => true
+ *
+ * _.isArguments([1, 2, 3]);
+ * // => false
+ */
+ function isArguments(value) {
+ return isObjectLike(value) && isArrayLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
+ }
+ /**
+ * Checks if `value` is classified as an `Array` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isArray([1, 2, 3]);
+ * // => true
+ *
+ * _.isArray(function() { return arguments; }());
+ * // => false
+ */
+ var isArray = nativeIsArray || function (value) {
+ return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
+ };
+ /**
+ * Checks if `value` is classified as a boolean primitive or object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isBoolean(false);
+ * // => true
+ *
+ * _.isBoolean(null);
+ * // => false
+ */
+ function isBoolean(value) {
+ return value === true || value === false || isObjectLike(value) && objToString.call(value) == boolTag;
+ }
+ /**
+ * Checks if `value` is classified as a `Date` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isDate(new Date);
+ * // => true
+ *
+ * _.isDate('Mon April 23 2012');
+ * // => false
+ */
+ function isDate(value) {
+ return isObjectLike(value) && objToString.call(value) == dateTag;
+ }
+ /**
+ * Checks if `value` is a DOM element.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
+ * @example
+ *
+ * _.isElement(document.body);
+ * // => true
+ *
+ * _.isElement('<body>');
+ * // => false
+ */
+ function isElement(value) {
+ return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value);
+ }
+ /**
+ * Checks if `value` is empty. A value is considered empty unless it's an
+ * `arguments` object, array, string, or jQuery-like collection with a length
+ * greater than `0` or an object with own enumerable properties.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {Array|Object|string} value The value to inspect.
+ * @returns {boolean} Returns `true` if `value` is empty, else `false`.
+ * @example
+ *
+ * _.isEmpty(null);
+ * // => true
+ *
+ * _.isEmpty(true);
+ * // => true
+ *
+ * _.isEmpty(1);
+ * // => true
+ *
+ * _.isEmpty([1, 2, 3]);
+ * // => false
+ *
+ * _.isEmpty({ 'a': 1 });
+ * // => false
+ */
+ function isEmpty(value) {
+ if (value == null) {
+ return true;
+ }
+ if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) || isObjectLike(value) && isFunction(value.splice))) {
+ return !value.length;
+ }
+ return !keys(value).length;
+ }
+ /**
+ * Performs a deep comparison between two values to determine if they are
+ * equivalent. If `customizer` is provided it's invoked to compare values.
+ * If `customizer` returns `undefined` comparisons are handled by the method
+ * instead. The `customizer` is bound to `thisArg` and invoked with up to
+ * three arguments: (value, other [, index|key]).
+ *
+ * **Note:** This method supports comparing arrays, booleans, `Date` objects,
+ * numbers, `Object` objects, regexes, and strings. Objects are compared by
+ * their own, not inherited, enumerable properties. Functions and DOM nodes
+ * are **not** supported. Provide a customizer function to extend support
+ * for comparing other values.
+ *
+ * @static
+ * @memberOf _
+ * @alias eq
+ * @category Lang
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @param {Function} [customizer] The function to customize value comparisons.
+ * @param {*} [thisArg] The `this` binding of `customizer`.
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+ * @example
+ *
+ * var object = { 'user': 'fred' };
+ * var other = { 'user': 'fred' };
+ *
+ * object == other;
+ * // => false
+ *
+ * _.isEqual(object, other);
+ * // => true
+ *
+ * // using a customizer callback
+ * var array = ['hello', 'goodbye'];
+ * var other = ['hi', 'goodbye'];
+ *
+ * _.isEqual(array, other, function(value, other) {
+ * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {
+ * return true;
+ * }
+ * });
+ * // => true
+ */
+ function isEqual(value, other, customizer, thisArg) {
+ customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
+ var result = customizer ? customizer(value, other) : undefined;
+ return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
+ }
+ /**
+ * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
+ * `SyntaxError`, `TypeError`, or `URIError` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
+ * @example
+ *
+ * _.isError(new Error);
+ * // => true
+ *
+ * _.isError(Error);
+ * // => false
+ */
+ function isError(value) {
+ return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag;
+ }
+ /**
+ * Checks if `value` is a finite primitive number.
+ *
+ * **Note:** This method is based on [`Number.isFinite`](http://ecma-international.org/ecma-262/6.0/#sec-number.isfinite).
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
+ * @example
+ *
+ * _.isFinite(10);
+ * // => true
+ *
+ * _.isFinite('10');
+ * // => false
+ *
+ * _.isFinite(true);
+ * // => false
+ *
+ * _.isFinite(Object(10));
+ * // => false
+ *
+ * _.isFinite(Infinity);
+ * // => false
+ */
+ function isFinite(value) {
+ return typeof value == 'number' && nativeIsFinite(value);
+ }
+ /**
+ * Checks if `value` is classified as a `Function` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isFunction(_);
+ * // => true
+ *
+ * _.isFunction(/abc/);
+ * // => false
+ */
+ function isFunction(value) {
+ // The use of `Object#toString` avoids issues with the `typeof` operator
+ // in older versions of Chrome and Safari which return 'function' for regexes
+ // and Safari 8 which returns 'object' for typed array constructors.
+ return isObject(value) && objToString.call(value) == funcTag;
+ }
+ /**
+ * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
+ * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an object, else `false`.
+ * @example
+ *
+ * _.isObject({});
+ * // => true
+ *
+ * _.isObject([1, 2, 3]);
+ * // => true
+ *
+ * _.isObject(1);
+ * // => false
+ */
+ function isObject(value) {
+ // Avoid a V8 JIT bug in Chrome 19-20.
+ // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
+ var type = typeof value;
+ return !!value && (type == 'object' || type == 'function');
+ }
+ /**
+ * Performs a deep comparison between `object` and `source` to determine if
+ * `object` contains equivalent property values. If `customizer` is provided
+ * it's invoked to compare values. If `customizer` returns `undefined`
+ * comparisons are handled by the method instead. The `customizer` is bound
+ * to `thisArg` and invoked with three arguments: (value, other, index|key).
+ *
+ * **Note:** This method supports comparing properties of arrays, booleans,
+ * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions
+ * and DOM nodes are **not** supported. Provide a customizer function to extend
+ * support for comparing other values.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {Object} object The object to inspect.
+ * @param {Object} source The object of property values to match.
+ * @param {Function} [customizer] The function to customize value comparisons.
+ * @param {*} [thisArg] The `this` binding of `customizer`.
+ * @returns {boolean} Returns `true` if `object` is a match, else `false`.
+ * @example
+ *
+ * var object = { 'user': 'fred', 'age': 40 };
+ *
+ * _.isMatch(object, { 'age': 40 });
+ * // => true
+ *
+ * _.isMatch(object, { 'age': 36 });
+ * // => false
+ *
+ * // using a customizer callback
+ * var object = { 'greeting': 'hello' };
+ * var source = { 'greeting': 'hi' };
+ *
+ * _.isMatch(object, source, function(value, other) {
+ * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
+ * });
+ * // => true
+ */
+ function isMatch(object, source, customizer, thisArg) {
+ customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
+ return baseIsMatch(object, getMatchData(source), customizer);
+ }
+ /**
+ * Checks if `value` is `NaN`.
+ *
+ * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4)
+ * which returns `true` for `undefined` and other non-numeric values.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
+ * @example
+ *
+ * _.isNaN(NaN);
+ * // => true
+ *
+ * _.isNaN(new Number(NaN));
+ * // => true
+ *
+ * isNaN(undefined);
+ * // => true
+ *
+ * _.isNaN(undefined);
+ * // => false
+ */
+ function isNaN(value) {
+ // An `NaN` primitive is the only value that is not equal to itself.
+ // Perform the `toStringTag` check first to avoid errors with some host objects in IE.
+ return isNumber(value) && value != +value;
+ }
+ /**
+ * Checks if `value` is a native function.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
+ * @example
+ *
+ * _.isNative(Array.prototype.push);
+ * // => true
+ *
+ * _.isNative(_);
+ * // => false
+ */
+ function isNative(value) {
+ if (value == null) {
+ return false;
+ }
+ if (isFunction(value)) {
+ return reIsNative.test(fnToString.call(value));
+ }
+ return isObjectLike(value) && reIsHostCtor.test(value);
+ }
+ /**
+ * Checks if `value` is `null`.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
+ * @example
+ *
+ * _.isNull(null);
+ * // => true
+ *
+ * _.isNull(void 0);
+ * // => false
+ */
+ function isNull(value) {
+ return value === null;
+ }
+ /**
+ * Checks if `value` is classified as a `Number` primitive or object.
+ *
+ * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
+ * as numbers, use the `_.isFinite` method.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isNumber(8.4);
+ * // => true
+ *
+ * _.isNumber(NaN);
+ * // => true
+ *
+ * _.isNumber('8.4');
+ * // => false
+ */
+ function isNumber(value) {
+ return typeof value == 'number' || isObjectLike(value) && objToString.call(value) == numberTag;
+ }
+ /**
+ * Checks if `value` is a plain object, that is, an object created by the
+ * `Object` constructor or one with a `[[Prototype]]` of `null`.
+ *
+ * **Note:** This method assumes objects created by the `Object` constructor
+ * have no inherited enumerable properties.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * }
+ *
+ * _.isPlainObject(new Foo);
+ * // => false
+ *
+ * _.isPlainObject([1, 2, 3]);
+ * // => false
+ *
+ * _.isPlainObject({ 'x': 0, 'y': 0 });
+ * // => true
+ *
+ * _.isPlainObject(Object.create(null));
+ * // => true
+ */
+ function isPlainObject(value) {
+ var Ctor;
+ // Exit early for non `Object` objects.
+ if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) || !hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor))) {
+ return false;
+ }
+ // IE < 9 iterates inherited properties before own properties. If the first
+ // iterated property is an object's own property then there are no inherited
+ // enumerable properties.
+ var result;
+ // In most environments an object's own properties are iterated before
+ // its inherited properties. If the last iterated property is an object's
+ // own property then there are no inherited enumerable properties.
+ baseForIn(value, function (subValue, key) {
+ result = key;
+ });
+ return result === undefined || hasOwnProperty.call(value, result);
+ }
+ /**
+ * Checks if `value` is classified as a `RegExp` object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isRegExp(/abc/);
+ * // => true
+ *
+ * _.isRegExp('/abc/');
+ * // => false
+ */
+ function isRegExp(value) {
+ return isObject(value) && objToString.call(value) == regexpTag;
+ }
+ /**
+ * Checks if `value` is classified as a `String` primitive or object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isString('abc');
+ * // => true
+ *
+ * _.isString(1);
+ * // => false
+ */
+ function isString(value) {
+ return typeof value == 'string' || isObjectLike(value) && objToString.call(value) == stringTag;
+ }
+ /**
+ * Checks if `value` is classified as a typed array.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
+ * @example
+ *
+ * _.isTypedArray(new Uint8Array);
+ * // => true
+ *
+ * _.isTypedArray([]);
+ * // => false
+ */
+ function isTypedArray(value) {
+ return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
+ }
+ /**
+ * Checks if `value` is `undefined`.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
+ * @example
+ *
+ * _.isUndefined(void 0);
+ * // => true
+ *
+ * _.isUndefined(null);
+ * // => false
+ */
+ function isUndefined(value) {
+ return value === undefined;
+ }
+ /**
+ * Checks if `value` is less than `other`.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {boolean} Returns `true` if `value` is less than `other`, else `false`.
+ * @example
+ *
+ * _.lt(1, 3);
+ * // => true
+ *
+ * _.lt(3, 3);
+ * // => false
+ *
+ * _.lt(3, 1);
+ * // => false
+ */
+ function lt(value, other) {
+ return value < other;
+ }
+ /**
+ * Checks if `value` is less than or equal to `other`.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {boolean} Returns `true` if `value` is less than or equal to `other`, else `false`.
+ * @example
+ *
+ * _.lte(1, 3);
+ * // => true
+ *
+ * _.lte(3, 3);
+ * // => true
+ *
+ * _.lte(3, 1);
+ * // => false
+ */
+ function lte(value, other) {
+ return value <= other;
+ }
+ /**
+ * Converts `value` to an array.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to convert.
+ * @returns {Array} Returns the converted array.
+ * @example
+ *
+ * (function() {
+ * return _.toArray(arguments).slice(1);
+ * }(1, 2, 3));
+ * // => [2, 3]
+ */
+ function toArray(value) {
+ var length = value ? getLength(value) : 0;
+ if (!isLength(length)) {
+ return values(value);
+ }
+ if (!length) {
+ return [];
+ }
+ return arrayCopy(value);
+ }
+ /**
+ * Converts `value` to a plain object flattening inherited enumerable
+ * properties of `value` to own properties of the plain object.
+ *
+ * @static
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to convert.
+ * @returns {Object} Returns the converted plain object.
+ * @example
+ *
+ * function Foo() {
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.assign({ 'a': 1 }, new Foo);
+ * // => { 'a': 1, 'b': 2 }
+ *
+ * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
+ * // => { 'a': 1, 'b': 2, 'c': 3 }
+ */
+ function toPlainObject(value) {
+ return baseCopy(value, keysIn(value));
+ }
+ /*------------------------------------------------------------------------*/
+ /**
+ * Recursively merges own enumerable properties of the source object(s), that
+ * don't resolve to `undefined` into the destination object. Subsequent sources
+ * overwrite property assignments of previous sources. If `customizer` is
+ * provided it's invoked to produce the merged values of the destination and
+ * source properties. If `customizer` returns `undefined` merging is handled
+ * by the method instead. The `customizer` is bound to `thisArg` and invoked
+ * with five arguments: (objectValue, sourceValue, key, object, source).
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} [sources] The source objects.
+ * @param {Function} [customizer] The function to customize assigned values.
+ * @param {*} [thisArg] The `this` binding of `customizer`.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * var users = {
+ * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
+ * };
+ *
+ * var ages = {
+ * 'data': [{ 'age': 36 }, { 'age': 40 }]
+ * };
+ *
+ * _.merge(users, ages);
+ * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
+ *
+ * // using a customizer callback
+ * var object = {
+ * 'fruits': ['apple'],
+ * 'vegetables': ['beet']
+ * };
+ *
+ * var other = {
+ * 'fruits': ['banana'],
+ * 'vegetables': ['carrot']
+ * };
+ *
+ * _.merge(object, other, function(a, b) {
+ * if (_.isArray(a)) {
+ * return a.concat(b);
+ * }
+ * });
+ * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
+ */
+ var merge = createAssigner(baseMerge);
+ /**
+ * Assigns own enumerable properties of source object(s) to the destination
+ * object. Subsequent sources overwrite property assignments of previous sources.
+ * If `customizer` is provided it's invoked to produce the assigned values.
+ * The `customizer` is bound to `thisArg` and invoked with five arguments:
+ * (objectValue, sourceValue, key, object, source).
+ *
+ * **Note:** This method mutates `object` and is based on
+ * [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign).
+ *
+ * @static
+ * @memberOf _
+ * @alias extend
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} [sources] The source objects.
+ * @param {Function} [customizer] The function to customize assigned values.
+ * @param {*} [thisArg] The `this` binding of `customizer`.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
+ * // => { 'user': 'fred', 'age': 40 }
+ *
+ * // using a customizer callback
+ * var defaults = _.partialRight(_.assign, function(value, other) {
+ * return _.isUndefined(value) ? other : value;
+ * });
+ *
+ * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
+ * // => { 'user': 'barney', 'age': 36 }
+ */
+ var assign = createAssigner(function (object, source, customizer) {
+ return customizer ? assignWith(object, source, customizer) : baseAssign(object, source);
+ });
+ /**
+ * Creates an object that inherits from the given `prototype` object. If a
+ * `properties` object is provided its own enumerable properties are assigned
+ * to the created object.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} prototype The object to inherit from.
+ * @param {Object} [properties] The properties to assign to the object.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {Object} Returns the new object.
+ * @example
+ *
+ * function Shape() {
+ * this.x = 0;
+ * this.y = 0;
+ * }
+ *
+ * function Circle() {
+ * Shape.call(this);
+ * }
+ *
+ * Circle.prototype = _.create(Shape.prototype, {
+ * 'constructor': Circle
+ * });
+ *
+ * var circle = new Circle;
+ * circle instanceof Circle;
+ * // => true
+ *
+ * circle instanceof Shape;
+ * // => true
+ */
+ function create(prototype, properties, guard) {
+ var result = baseCreate(prototype);
+ if (guard && isIterateeCall(prototype, properties, guard)) {
+ properties = undefined;
+ }
+ return properties ? baseAssign(result, properties) : result;
+ }
+ /**
+ * Assigns own enumerable properties of source object(s) to the destination
+ * object for all destination properties that resolve to `undefined`. Once a
+ * property is set, additional values of the same property are ignored.
+ *
+ * **Note:** This method mutates `object`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} [sources] The source objects.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
+ * // => { 'user': 'barney', 'age': 36 }
+ */
+ var defaults = createDefaults(assign, assignDefaults);
+ /**
+ * This method is like `_.defaults` except that it recursively assigns
+ * default properties.
+ *
+ * **Note:** This method mutates `object`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} [sources] The source objects.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
+ * // => { 'user': { 'name': 'barney', 'age': 36 } }
+ *
+ */
+ var defaultsDeep = createDefaults(merge, mergeDefaults);
+ /**
+ * This method is like `_.find` except that it returns the key of the first
+ * element `predicate` returns truthy for instead of the element itself.
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to search.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
+ * @example
+ *
+ * var users = {
+ * 'barney': { 'age': 36, 'active': true },
+ * 'fred': { 'age': 40, 'active': false },
+ * 'pebbles': { 'age': 1, 'active': true }
+ * };
+ *
+ * _.findKey(users, function(chr) {
+ * return chr.age < 40;
+ * });
+ * // => 'barney' (iteration order is not guaranteed)
+ *
+ * // using the `_.matches` callback shorthand
+ * _.findKey(users, { 'age': 1, 'active': true });
+ * // => 'pebbles'
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.findKey(users, 'active', false);
+ * // => 'fred'
+ *
+ * // using the `_.property` callback shorthand
+ * _.findKey(users, 'active');
+ * // => 'barney'
+ */
+ var findKey = createFindKey(baseForOwn);
+ /**
+ * This method is like `_.findKey` except that it iterates over elements of
+ * a collection in the opposite order.
+ *
+ * If a property name is provided for `predicate` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `predicate` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to search.
+ * @param {Function|Object|string} [predicate=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
+ * @example
+ *
+ * var users = {
+ * 'barney': { 'age': 36, 'active': true },
+ * 'fred': { 'age': 40, 'active': false },
+ * 'pebbles': { 'age': 1, 'active': true }
+ * };
+ *
+ * _.findLastKey(users, function(chr) {
+ * return chr.age < 40;
+ * });
+ * // => returns `pebbles` assuming `_.findKey` returns `barney`
+ *
+ * // using the `_.matches` callback shorthand
+ * _.findLastKey(users, { 'age': 36, 'active': true });
+ * // => 'barney'
+ *
+ * // using the `_.matchesProperty` callback shorthand
+ * _.findLastKey(users, 'active', false);
+ * // => 'fred'
+ *
+ * // using the `_.property` callback shorthand
+ * _.findLastKey(users, 'active');
+ * // => 'pebbles'
+ */
+ var findLastKey = createFindKey(baseForOwnRight);
+ /**
+ * Iterates over own and inherited enumerable properties of an object invoking
+ * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked
+ * with three arguments: (value, key, object). Iteratee functions may exit
+ * iteration early by explicitly returning `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to iterate over.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.forIn(new Foo, function(value, key) {
+ * console.log(key);
+ * });
+ * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed)
+ */
+ var forIn = createForIn(baseFor);
+ /**
+ * This method is like `_.forIn` except that it iterates over properties of
+ * `object` in the opposite order.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to iterate over.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.forInRight(new Foo, function(value, key) {
+ * console.log(key);
+ * });
+ * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'
+ */
+ var forInRight = createForIn(baseForRight);
+ /**
+ * Iterates over own enumerable properties of an object invoking `iteratee`
+ * for each property. The `iteratee` is bound to `thisArg` and invoked with
+ * three arguments: (value, key, object). Iteratee functions may exit iteration
+ * early by explicitly returning `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to iterate over.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.forOwn(new Foo, function(value, key) {
+ * console.log(key);
+ * });
+ * // => logs 'a' and 'b' (iteration order is not guaranteed)
+ */
+ var forOwn = createForOwn(baseForOwn);
+ /**
+ * This method is like `_.forOwn` except that it iterates over properties of
+ * `object` in the opposite order.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to iterate over.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.forOwnRight(new Foo, function(value, key) {
+ * console.log(key);
+ * });
+ * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b'
+ */
+ var forOwnRight = createForOwn(baseForOwnRight);
+ /**
+ * Creates an array of function property names from all enumerable properties,
+ * own and inherited, of `object`.
+ *
+ * @static
+ * @memberOf _
+ * @alias methods
+ * @category Object
+ * @param {Object} object The object to inspect.
+ * @returns {Array} Returns the new array of property names.
+ * @example
+ *
+ * _.functions(_);
+ * // => ['after', 'ary', 'assign', ...]
+ */
+ function functions(object) {
+ return baseFunctions(object, keysIn(object));
+ }
+ /**
+ * Gets the property value at `path` of `object`. If the resolved value is
+ * `undefined` the `defaultValue` is used in its place.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path of the property to get.
+ * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
+ * @returns {*} Returns the resolved value.
+ * @example
+ *
+ * var object = { 'a': [{ 'b': { 'c': 3 } }] };
+ *
+ * _.get(object, 'a[0].b.c');
+ * // => 3
+ *
+ * _.get(object, ['a', '0', 'b', 'c']);
+ * // => 3
+ *
+ * _.get(object, 'a.b.c', 'default');
+ * // => 'default'
+ */
+ function get(object, path, defaultValue) {
+ var result = object == null ? undefined : baseGet(object, toPath(path), path + '');
+ return result === undefined ? defaultValue : result;
+ }
+ /**
+ * Checks if `path` is a direct property.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path to check.
+ * @returns {boolean} Returns `true` if `path` is a direct property, else `false`.
+ * @example
+ *
+ * var object = { 'a': { 'b': { 'c': 3 } } };
+ *
+ * _.has(object, 'a');
+ * // => true
+ *
+ * _.has(object, 'a.b.c');
+ * // => true
+ *
+ * _.has(object, ['a', 'b', 'c']);
+ * // => true
+ */
+ function has(object, path) {
+ if (object == null) {
+ return false;
+ }
+ var result = hasOwnProperty.call(object, path);
+ if (!result && !isKey(path)) {
+ path = toPath(path);
+ object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
+ if (object == null) {
+ return false;
+ }
+ path = last(path);
+ result = hasOwnProperty.call(object, path);
+ }
+ return result || isLength(object.length) && isIndex(path, object.length) && (isArray(object) || isArguments(object));
+ }
+ /**
+ * Creates an object composed of the inverted keys and values of `object`.
+ * If `object` contains duplicate values, subsequent values overwrite property
+ * assignments of previous values unless `multiValue` is `true`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to invert.
+ * @param {boolean} [multiValue] Allow multiple values per key.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {Object} Returns the new inverted object.
+ * @example
+ *
+ * var object = { 'a': 1, 'b': 2, 'c': 1 };
+ *
+ * _.invert(object);
+ * // => { '1': 'c', '2': 'b' }
+ *
+ * // with `multiValue`
+ * _.invert(object, true);
+ * // => { '1': ['a', 'c'], '2': ['b'] }
+ */
+ function invert(object, multiValue, guard) {
+ if (guard && isIterateeCall(object, multiValue, guard)) {
+ multiValue = undefined;
+ }
+ var index = -1, props = keys(object), length = props.length, result = {};
+ while (++index < length) {
+ var key = props[index], value = object[key];
+ if (multiValue) {
+ if (hasOwnProperty.call(result, value)) {
+ result[value].push(key);
+ } else {
+ result[value] = [key];
+ }
+ } else {
+ result[value] = key;
+ }
+ }
+ return result;
+ }
+ /**
+ * Creates an array of the own enumerable property names of `object`.
+ *
+ * **Note:** Non-object values are coerced to objects. See the
+ * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
+ * for more details.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.keys(new Foo);
+ * // => ['a', 'b'] (iteration order is not guaranteed)
+ *
+ * _.keys('hi');
+ * // => ['0', '1']
+ */
+ var keys = !nativeKeys ? shimKeys : function (object) {
+ var Ctor = object == null ? undefined : object.constructor;
+ if (typeof Ctor == 'function' && Ctor.prototype === object || typeof object != 'function' && isArrayLike(object)) {
+ return shimKeys(object);
+ }
+ return isObject(object) ? nativeKeys(object) : [];
+ };
+ /**
+ * Creates an array of the own and inherited enumerable property names of `object`.
+ *
+ * **Note:** Non-object values are coerced to objects.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.keysIn(new Foo);
+ * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
+ */
+ function keysIn(object) {
+ if (object == null) {
+ return [];
+ }
+ if (!isObject(object)) {
+ object = Object(object);
+ }
+ var length = object.length;
+ length = length && isLength(length) && (isArray(object) || isArguments(object)) && length || 0;
+ var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0;
+ while (++index < length) {
+ result[index] = index + '';
+ }
+ for (var key in object) {
+ if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
+ result.push(key);
+ }
+ }
+ return result;
+ }
+ /**
+ * The opposite of `_.mapValues`; this method creates an object with the
+ * same values as `object` and keys generated by running each own enumerable
+ * property of `object` through `iteratee`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Object} Returns the new mapped object.
+ * @example
+ *
+ * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
+ * return key + value;
+ * });
+ * // => { 'a1': 1, 'b2': 2 }
+ */
+ var mapKeys = createObjectMapper(true);
+ /**
+ * Creates an object with the same keys as `object` and values generated by
+ * running each own enumerable property of `object` through `iteratee`. The
+ * iteratee function is bound to `thisArg` and invoked with three arguments:
+ * (value, key, object).
+ *
+ * If a property name is provided for `iteratee` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `iteratee` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to iterate over.
+ * @param {Function|Object|string} [iteratee=_.identity] The function invoked
+ * per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Object} Returns the new mapped object.
+ * @example
+ *
+ * _.mapValues({ 'a': 1, 'b': 2 }, function(n) {
+ * return n * 3;
+ * });
+ * // => { 'a': 3, 'b': 6 }
+ *
+ * var users = {
+ * 'fred': { 'user': 'fred', 'age': 40 },
+ * 'pebbles': { 'user': 'pebbles', 'age': 1 }
+ * };
+ *
+ * // using the `_.property` callback shorthand
+ * _.mapValues(users, 'age');
+ * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
+ */
+ var mapValues = createObjectMapper();
+ /**
+ * The opposite of `_.pick`; this method creates an object composed of the
+ * own and inherited enumerable properties of `object` that are not omitted.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The source object.
+ * @param {Function|...(string|string[])} [predicate] The function invoked per
+ * iteration or property names to omit, specified as individual property
+ * names or arrays of property names.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {Object} Returns the new object.
+ * @example
+ *
+ * var object = { 'user': 'fred', 'age': 40 };
+ *
+ * _.omit(object, 'age');
+ * // => { 'user': 'fred' }
+ *
+ * _.omit(object, _.isNumber);
+ * // => { 'user': 'fred' }
+ */
+ var omit = restParam(function (object, props) {
+ if (object == null) {
+ return {};
+ }
+ if (typeof props[0] != 'function') {
+ var props = arrayMap(baseFlatten(props), String);
+ return pickByArray(object, baseDifference(keysIn(object), props));
+ }
+ var predicate = bindCallback(props[0], props[1], 3);
+ return pickByCallback(object, function (value, key, object) {
+ return !predicate(value, key, object);
+ });
+ });
+ /**
+ * Creates a two dimensional array of the key-value pairs for `object`,
+ * e.g. `[[key1, value1], [key2, value2]]`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the new array of key-value pairs.
+ * @example
+ *
+ * _.pairs({ 'barney': 36, 'fred': 40 });
+ * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
+ */
+ function pairs(object) {
+ object = toObject(object);
+ var index = -1, props = keys(object), length = props.length, result = Array(length);
+ while (++index < length) {
+ var key = props[index];
+ result[index] = [
+ key,
+ object[key]
+ ];
+ }
+ return result;
+ }
+ /**
+ * Creates an object composed of the picked `object` properties. Property
+ * names may be specified as individual arguments or as arrays of property
+ * names. If `predicate` is provided it's invoked for each property of `object`
+ * picking the properties `predicate` returns truthy for. The predicate is
+ * bound to `thisArg` and invoked with three arguments: (value, key, object).
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The source object.
+ * @param {Function|...(string|string[])} [predicate] The function invoked per
+ * iteration or property names to pick, specified as individual property
+ * names or arrays of property names.
+ * @param {*} [thisArg] The `this` binding of `predicate`.
+ * @returns {Object} Returns the new object.
+ * @example
+ *
+ * var object = { 'user': 'fred', 'age': 40 };
+ *
+ * _.pick(object, 'user');
+ * // => { 'user': 'fred' }
+ *
+ * _.pick(object, _.isString);
+ * // => { 'user': 'fred' }
+ */
+ var pick = restParam(function (object, props) {
+ if (object == null) {
+ return {};
+ }
+ return typeof props[0] == 'function' ? pickByCallback(object, bindCallback(props[0], props[1], 3)) : pickByArray(object, baseFlatten(props));
+ });
+ /**
+ * This method is like `_.get` except that if the resolved value is a function
+ * it's invoked with the `this` binding of its parent object and its result
+ * is returned.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path of the property to resolve.
+ * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
+ * @returns {*} Returns the resolved value.
+ * @example
+ *
+ * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
+ *
+ * _.result(object, 'a[0].b.c1');
+ * // => 3
+ *
+ * _.result(object, 'a[0].b.c2');
+ * // => 4
+ *
+ * _.result(object, 'a.b.c', 'default');
+ * // => 'default'
+ *
+ * _.result(object, 'a.b.c', _.constant('default'));
+ * // => 'default'
+ */
+ function result(object, path, defaultValue) {
+ var result = object == null ? undefined : object[path];
+ if (result === undefined) {
+ if (object != null && !isKey(path, object)) {
+ path = toPath(path);
+ object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
+ result = object == null ? undefined : object[last(path)];
+ }
+ result = result === undefined ? defaultValue : result;
+ }
+ return isFunction(result) ? result.call(object) : result;
+ }
+ /**
+ * Sets the property value of `path` on `object`. If a portion of `path`
+ * does not exist it's created.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to augment.
+ * @param {Array|string} path The path of the property to set.
+ * @param {*} value The value to set.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * var object = { 'a': [{ 'b': { 'c': 3 } }] };
+ *
+ * _.set(object, 'a[0].b.c', 4);
+ * console.log(object.a[0].b.c);
+ * // => 4
+ *
+ * _.set(object, 'x[0].y.z', 5);
+ * console.log(object.x[0].y.z);
+ * // => 5
+ */
+ function set(object, path, value) {
+ if (object == null) {
+ return object;
+ }
+ var pathKey = path + '';
+ path = object[pathKey] != null || isKey(path, object) ? [pathKey] : toPath(path);
+ var index = -1, length = path.length, lastIndex = length - 1, nested = object;
+ while (nested != null && ++index < length) {
+ var key = path[index];
+ if (isObject(nested)) {
+ if (index == lastIndex) {
+ nested[key] = value;
+ } else if (nested[key] == null) {
+ nested[key] = isIndex(path[index + 1]) ? [] : {};
+ }
+ }
+ nested = nested[key];
+ }
+ return object;
+ }
+ /**
+ * An alternative to `_.reduce`; this method transforms `object` to a new
+ * `accumulator` object which is the result of running each of its own enumerable
+ * properties through `iteratee`, with each invocation potentially mutating
+ * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked
+ * with four arguments: (accumulator, value, key, object). Iteratee functions
+ * may exit iteration early by explicitly returning `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Array|Object} object The object to iterate over.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @param {*} [accumulator] The custom accumulator value.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {*} Returns the accumulated value.
+ * @example
+ *
+ * _.transform([2, 3, 4], function(result, n) {
+ * result.push(n *= n);
+ * return n % 2 == 0;
+ * });
+ * // => [4, 9]
+ *
+ * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
+ * result[key] = n * 3;
+ * });
+ * // => { 'a': 3, 'b': 6 }
+ */
+ function transform(object, iteratee, accumulator, thisArg) {
+ var isArr = isArray(object) || isTypedArray(object);
+ iteratee = getCallback(iteratee, thisArg, 4);
+ if (accumulator == null) {
+ if (isArr || isObject(object)) {
+ var Ctor = object.constructor;
+ if (isArr) {
+ accumulator = isArray(object) ? new Ctor() : [];
+ } else {
+ accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : undefined);
+ }
+ } else {
+ accumulator = {};
+ }
+ }
+ (isArr ? arrayEach : baseForOwn)(object, function (value, index, object) {
+ return iteratee(accumulator, value, index, object);
+ });
+ return accumulator;
+ }
+ /**
+ * Creates an array of the own enumerable property values of `object`.
+ *
+ * **Note:** Non-object values are coerced to objects.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property values.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.values(new Foo);
+ * // => [1, 2] (iteration order is not guaranteed)
+ *
+ * _.values('hi');
+ * // => ['h', 'i']
+ */
+ function values(object) {
+ return baseValues(object, keys(object));
+ }
+ /**
+ * Creates an array of the own and inherited enumerable property values
+ * of `object`.
+ *
+ * **Note:** Non-object values are coerced to objects.
+ *
+ * @static
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property values.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.valuesIn(new Foo);
+ * // => [1, 2, 3] (iteration order is not guaranteed)
+ */
+ function valuesIn(object) {
+ return baseValues(object, keysIn(object));
+ }
+ /*------------------------------------------------------------------------*/
+ /**
+ * Checks if `n` is between `start` and up to but not including, `end`. If
+ * `end` is not specified it's set to `start` with `start` then set to `0`.
+ *
+ * @static
+ * @memberOf _
+ * @category Number
+ * @param {number} n The number to check.
+ * @param {number} [start=0] The start of the range.
+ * @param {number} end The end of the range.
+ * @returns {boolean} Returns `true` if `n` is in the range, else `false`.
+ * @example
+ *
+ * _.inRange(3, 2, 4);
+ * // => true
+ *
+ * _.inRange(4, 8);
+ * // => true
+ *
+ * _.inRange(4, 2);
+ * // => false
+ *
+ * _.inRange(2, 2);
+ * // => false
+ *
+ * _.inRange(1.2, 2);
+ * // => true
+ *
+ * _.inRange(5.2, 4);
+ * // => false
+ */
+ function inRange(value, start, end) {
+ start = +start || 0;
+ if (end === undefined) {
+ end = start;
+ start = 0;
+ } else {
+ end = +end || 0;
+ }
+ return value >= nativeMin(start, end) && value < nativeMax(start, end);
+ }
+ /**
+ * Produces a random number between `min` and `max` (inclusive). If only one
+ * argument is provided a number between `0` and the given number is returned.
+ * If `floating` is `true`, or either `min` or `max` are floats, a floating-point
+ * number is returned instead of an integer.
+ *
+ * @static
+ * @memberOf _
+ * @category Number
+ * @param {number} [min=0] The minimum possible value.
+ * @param {number} [max=1] The maximum possible value.
+ * @param {boolean} [floating] Specify returning a floating-point number.
+ * @returns {number} Returns the random number.
+ * @example
+ *
+ * _.random(0, 5);
+ * // => an integer between 0 and 5
+ *
+ * _.random(5);
+ * // => also an integer between 0 and 5
+ *
+ * _.random(5, true);
+ * // => a floating-point number between 0 and 5
+ *
+ * _.random(1.2, 5.2);
+ * // => a floating-point number between 1.2 and 5.2
+ */
+ function random(min, max, floating) {
+ if (floating && isIterateeCall(min, max, floating)) {
+ max = floating = undefined;
+ }
+ var noMin = min == null, noMax = max == null;
+ if (floating == null) {
+ if (noMax && typeof min == 'boolean') {
+ floating = min;
+ min = 1;
+ } else if (typeof max == 'boolean') {
+ floating = max;
+ noMax = true;
+ }
+ }
+ if (noMin && noMax) {
+ max = 1;
+ noMax = false;
+ }
+ min = +min || 0;
+ if (noMax) {
+ max = min;
+ min = 0;
+ } else {
+ max = +max || 0;
+ }
+ if (floating || min % 1 || max % 1) {
+ var rand = nativeRandom();
+ return nativeMin(min + rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1))), max);
+ }
+ return baseRandom(min, max);
+ }
+ /*------------------------------------------------------------------------*/
+ /**
+ * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to convert.
+ * @returns {string} Returns the camel cased string.
+ * @example
+ *
+ * _.camelCase('Foo Bar');
+ * // => 'fooBar'
+ *
+ * _.camelCase('--foo-bar');
+ * // => 'fooBar'
+ *
+ * _.camelCase('__foo_bar__');
+ * // => 'fooBar'
+ */
+ var camelCase = createCompounder(function (result, word, index) {
+ word = word.toLowerCase();
+ return result + (index ? word.charAt(0).toUpperCase() + word.slice(1) : word);
+ });
+ /**
+ * Capitalizes the first character of `string`.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to capitalize.
+ * @returns {string} Returns the capitalized string.
+ * @example
+ *
+ * _.capitalize('fred');
+ * // => 'Fred'
+ */
+ function capitalize(string) {
+ string = baseToString(string);
+ return string && string.charAt(0).toUpperCase() + string.slice(1);
+ }
+ /**
+ * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
+ * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to deburr.
+ * @returns {string} Returns the deburred string.
+ * @example
+ *
+ * _.deburr('déjà vu');
+ * // => 'deja vu'
+ */
+ function deburr(string) {
+ string = baseToString(string);
+ return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, '');
+ }
+ /**
+ * Checks if `string` ends with the given target string.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to search.
+ * @param {string} [target] The string to search for.
+ * @param {number} [position=string.length] The position to search from.
+ * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.
+ * @example
+ *
+ * _.endsWith('abc', 'c');
+ * // => true
+ *
+ * _.endsWith('abc', 'b');
+ * // => false
+ *
+ * _.endsWith('abc', 'b', 2);
+ * // => true
+ */
+ function endsWith(string, target, position) {
+ string = baseToString(string);
+ target = target + '';
+ var length = string.length;
+ position = position === undefined ? length : nativeMin(position < 0 ? 0 : +position || 0, length);
+ position -= target.length;
+ return position >= 0 && string.indexOf(target, position) == position;
+ }
+ /**
+ * Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to
+ * their corresponding HTML entities.
+ *
+ * **Note:** No other characters are escaped. To escape additional characters
+ * use a third-party library like [_he_](https://mths.be/he).
+ *
+ * Though the ">" character is escaped for symmetry, characters like
+ * ">" and "/" don't need escaping in HTML and have no special meaning
+ * unless they're part of a tag or unquoted attribute value.
+ * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
+ * (under "semi-related fun fact") for more details.
+ *
+ * Backticks are escaped because in Internet Explorer < 9, they can break out
+ * of attribute values or HTML comments. See [#59](https://html5sec.org/#59),
+ * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
+ * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
+ * for more details.
+ *
+ * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
+ * to reduce XSS vectors.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to escape.
+ * @returns {string} Returns the escaped string.
+ * @example
+ *
+ * _.escape('fred, barney, & pebbles');
+ * // => 'fred, barney, & pebbles'
+ */
+ function escape(string) {
+ // Reset `lastIndex` because in IE < 9 `String#replace` does not.
+ string = baseToString(string);
+ return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string;
+ }
+ /**
+ * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?",
+ * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to escape.
+ * @returns {string} Returns the escaped string.
+ * @example
+ *
+ * _.escapeRegExp('[lodash](https://lodash.com/)');
+ * // => '\[lodash\]\(https:\/\/lodash\.com\/\)'
+ */
+ function escapeRegExp(string) {
+ string = baseToString(string);
+ return string && reHasRegExpChars.test(string) ? string.replace(reRegExpChars, escapeRegExpChar) : string || '(?:)';
+ }
+ /**
+ * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to convert.
+ * @returns {string} Returns the kebab cased string.
+ * @example
+ *
+ * _.kebabCase('Foo Bar');
+ * // => 'foo-bar'
+ *
+ * _.kebabCase('fooBar');
+ * // => 'foo-bar'
+ *
+ * _.kebabCase('__foo_bar__');
+ * // => 'foo-bar'
+ */
+ var kebabCase = createCompounder(function (result, word, index) {
+ return result + (index ? '-' : '') + word.toLowerCase();
+ });
+ /**
+ * Pads `string` on the left and right sides if it's shorter than `length`.
+ * Padding characters are truncated if they can't be evenly divided by `length`.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to pad.
+ * @param {number} [length=0] The padding length.
+ * @param {string} [chars=' '] The string used as padding.
+ * @returns {string} Returns the padded string.
+ * @example
+ *
+ * _.pad('abc', 8);
+ * // => ' abc '
+ *
+ * _.pad('abc', 8, '_-');
+ * // => '_-abc_-_'
+ *
+ * _.pad('abc', 3);
+ * // => 'abc'
+ */
+ function pad(string, length, chars) {
+ string = baseToString(string);
+ length = +length;
+ var strLength = string.length;
+ if (strLength >= length || !nativeIsFinite(length)) {
+ return string;
+ }
+ var mid = (length - strLength) / 2, leftLength = nativeFloor(mid), rightLength = nativeCeil(mid);
+ chars = createPadding('', rightLength, chars);
+ return chars.slice(0, leftLength) + string + chars;
+ }
+ /**
+ * Pads `string` on the left side if it's shorter than `length`. Padding
+ * characters are truncated if they exceed `length`.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to pad.
+ * @param {number} [length=0] The padding length.
+ * @param {string} [chars=' '] The string used as padding.
+ * @returns {string} Returns the padded string.
+ * @example
+ *
+ * _.padLeft('abc', 6);
+ * // => ' abc'
+ *
+ * _.padLeft('abc', 6, '_-');
+ * // => '_-_abc'
+ *
+ * _.padLeft('abc', 3);
+ * // => 'abc'
+ */
+ var padLeft = createPadDir();
+ /**
+ * Pads `string` on the right side if it's shorter than `length`. Padding
+ * characters are truncated if they exceed `length`.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to pad.
+ * @param {number} [length=0] The padding length.
+ * @param {string} [chars=' '] The string used as padding.
+ * @returns {string} Returns the padded string.
+ * @example
+ *
+ * _.padRight('abc', 6);
+ * // => 'abc '
+ *
+ * _.padRight('abc', 6, '_-');
+ * // => 'abc_-_'
+ *
+ * _.padRight('abc', 3);
+ * // => 'abc'
+ */
+ var padRight = createPadDir(true);
+ /**
+ * Converts `string` to an integer of the specified radix. If `radix` is
+ * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,
+ * in which case a `radix` of `16` is used.
+ *
+ * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E)
+ * of `parseInt`.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} string The string to convert.
+ * @param {number} [radix] The radix to interpret `value` by.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {number} Returns the converted integer.
+ * @example
+ *
+ * _.parseInt('08');
+ * // => 8
+ *
+ * _.map(['6', '08', '10'], _.parseInt);
+ * // => [6, 8, 10]
+ */
+ function parseInt(string, radix, guard) {
+ // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`.
+ // Chrome fails to trim leading <BOM> whitespace characters.
+ // See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
+ if (guard ? isIterateeCall(string, radix, guard) : radix == null) {
+ radix = 0;
+ } else if (radix) {
+ radix = +radix;
+ }
+ string = trim(string);
+ return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
+ }
+ /**
+ * Repeats the given string `n` times.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to repeat.
+ * @param {number} [n=0] The number of times to repeat the string.
+ * @returns {string} Returns the repeated string.
+ * @example
+ *
+ * _.repeat('*', 3);
+ * // => '***'
+ *
+ * _.repeat('abc', 2);
+ * // => 'abcabc'
+ *
+ * _.repeat('abc', 0);
+ * // => ''
+ */
+ function repeat(string, n) {
+ var result = '';
+ string = baseToString(string);
+ n = +n;
+ if (n < 1 || !string || !nativeIsFinite(n)) {
+ return result;
+ }
+ // Leverage the exponentiation by squaring algorithm for a faster repeat.
+ // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
+ do {
+ if (n % 2) {
+ result += string;
+ }
+ n = nativeFloor(n / 2);
+ string += string;
+ } while (n);
+ return result;
+ }
+ /**
+ * Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case).
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to convert.
+ * @returns {string} Returns the snake cased string.
+ * @example
+ *
+ * _.snakeCase('Foo Bar');
+ * // => 'foo_bar'
+ *
+ * _.snakeCase('fooBar');
+ * // => 'foo_bar'
+ *
+ * _.snakeCase('--foo-bar');
+ * // => 'foo_bar'
+ */
+ var snakeCase = createCompounder(function (result, word, index) {
+ return result + (index ? '_' : '') + word.toLowerCase();
+ });
+ /**
+ * Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to convert.
+ * @returns {string} Returns the start cased string.
+ * @example
+ *
+ * _.startCase('--foo-bar');
+ * // => 'Foo Bar'
+ *
+ * _.startCase('fooBar');
+ * // => 'Foo Bar'
+ *
+ * _.startCase('__foo_bar__');
+ * // => 'Foo Bar'
+ */
+ var startCase = createCompounder(function (result, word, index) {
+ return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1));
+ });
+ /**
+ * Checks if `string` starts with the given target string.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to search.
+ * @param {string} [target] The string to search for.
+ * @param {number} [position=0] The position to search from.
+ * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`.
+ * @example
+ *
+ * _.startsWith('abc', 'a');
+ * // => true
+ *
+ * _.startsWith('abc', 'b');
+ * // => false
+ *
+ * _.startsWith('abc', 'b', 1);
+ * // => true
+ */
+ function startsWith(string, target, position) {
+ string = baseToString(string);
+ position = position == null ? 0 : nativeMin(position < 0 ? 0 : +position || 0, string.length);
+ return string.lastIndexOf(target, position) == position;
+ }
+ /**
+ * Creates a compiled template function that can interpolate data properties
+ * in "interpolate" delimiters, HTML-escape interpolated data properties in
+ * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
+ * properties may be accessed as free variables in the template. If a setting
+ * object is provided it takes precedence over `_.templateSettings` values.
+ *
+ * **Note:** In the development build `_.template` utilizes
+ * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
+ * for easier debugging.
+ *
+ * For more information on precompiling templates see
+ * [lodash's custom builds documentation](https://lodash.com/custom-builds).
+ *
+ * For more information on Chrome extension sandboxes see
+ * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The template string.
+ * @param {Object} [options] The options object.
+ * @param {RegExp} [options.escape] The HTML "escape" delimiter.
+ * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
+ * @param {Object} [options.imports] An object to import into the template as free variables.
+ * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
+ * @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
+ * @param {string} [options.variable] The data object variable name.
+ * @param- {Object} [otherOptions] Enables the legacy `options` param signature.
+ * @returns {Function} Returns the compiled template function.
+ * @example
+ *
+ * // using the "interpolate" delimiter to create a compiled template
+ * var compiled = _.template('hello <%= user %>!');
+ * compiled({ 'user': 'fred' });
+ * // => 'hello fred!'
+ *
+ * // using the HTML "escape" delimiter to escape data property values
+ * var compiled = _.template('<b><%- value %></b>');
+ * compiled({ 'value': '<script>' });
+ * // => '<b><script></b>'
+ *
+ * // using the "evaluate" delimiter to execute JavaScript and generate HTML
+ * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
+ * compiled({ 'users': ['fred', 'barney'] });
+ * // => '<li>fred</li><li>barney</li>'
+ *
+ * // using the internal `print` function in "evaluate" delimiters
+ * var compiled = _.template('<% print("hello " + user); %>!');
+ * compiled({ 'user': 'barney' });
+ * // => 'hello barney!'
+ *
+ * // using the ES delimiter as an alternative to the default "interpolate" delimiter
+ * var compiled = _.template('hello ${ user }!');
+ * compiled({ 'user': 'pebbles' });
+ * // => 'hello pebbles!'
+ *
+ * // using custom template delimiters
+ * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
+ * var compiled = _.template('hello {{ user }}!');
+ * compiled({ 'user': 'mustache' });
+ * // => 'hello mustache!'
+ *
+ * // using backslashes to treat delimiters as plain text
+ * var compiled = _.template('<%= "\\<%- value %\\>" %>');
+ * compiled({ 'value': 'ignored' });
+ * // => '<%- value %>'
+ *
+ * // using the `imports` option to import `jQuery` as `jq`
+ * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
+ * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
+ * compiled({ 'users': ['fred', 'barney'] });
+ * // => '<li>fred</li><li>barney</li>'
+ *
+ * // using the `sourceURL` option to specify a custom sourceURL for the template
+ * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
+ * compiled(data);
+ * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
+ *
+ * // using the `variable` option to ensure a with-statement isn't used in the compiled template
+ * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
+ * compiled.source;
+ * // => function(data) {
+ * // var __t, __p = '';
+ * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
+ * // return __p;
+ * // }
+ *
+ * // using the `source` property to inline compiled templates for meaningful
+ * // line numbers in error messages and a stack trace
+ * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
+ * var JST = {\
+ * "main": ' + _.template(mainText).source + '\
+ * };\
+ * ');
+ */
+ function template(string, options, otherOptions) {
+ // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
+ // and Laura Doktorova's doT.js (https://github.com/olado/doT).
+ var settings = lodash.templateSettings;
+ if (otherOptions && isIterateeCall(string, options, otherOptions)) {
+ options = otherOptions = undefined;
+ }
+ string = baseToString(string);
+ options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);
+ var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys);
+ var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = '__p += \'';
+ // Compile the regexp to match each delimiter.
+ var reDelimiters = RegExp((options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$', 'g');
+ // Use a sourceURL for easier debugging.
+ var sourceURL = '//# sourceURL=' + ('sourceURL' in options ? options.sourceURL : 'lodash.templateSources[' + ++templateCounter + ']') + '\n';
+ string.replace(reDelimiters, function (match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
+ interpolateValue || (interpolateValue = esTemplateValue);
+ // Escape characters that can't be included in string literals.
+ source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
+ // Replace delimiters with snippets.
+ if (escapeValue) {
+ isEscaping = true;
+ source += '\' +\n__e(' + escapeValue + ') +\n\'';
+ }
+ if (evaluateValue) {
+ isEvaluating = true;
+ source += '\';\n' + evaluateValue + ';\n__p += \'';
+ }
+ if (interpolateValue) {
+ source += '\' +\n((__t = (' + interpolateValue + ')) == null ? \'\' : __t) +\n\'';
+ }
+ index = offset + match.length;
+ // The JS engine embedded in Adobe products requires returning the `match`
+ // string in order to produce the correct `offset` value.
+ return match;
+ });
+ source += '\';\n';
+ // If `variable` is not specified wrap a with-statement around the generated
+ // code to add the data object to the top of the scope chain.
+ var variable = options.variable;
+ if (!variable) {
+ source = 'with (obj) {\n' + source + '\n}\n';
+ }
+ // Cleanup code by stripping empty strings.
+ source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source).replace(reEmptyStringMiddle, '$1').replace(reEmptyStringTrailing, '$1;');
+ // Frame code as the function body.
+ source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n') + 'var __t, __p = \'\'' + (isEscaping ? ', __e = _.escape' : '') + (isEvaluating ? ', __j = Array.prototype.join;\n' + 'function print() { __p += __j.call(arguments, \'\') }\n' : ';\n') + source + 'return __p\n}';
+ var result = attempt(function () {
+ return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
+ });
+ // Provide the compiled function's source by its `toString` method or
+ // the `source` property as a convenience for inlining compiled templates.
+ result.source = source;
+ if (isError(result)) {
+ throw result;
+ }
+ return result;
+ }
+ /**
+ * Removes leading and trailing whitespace or specified characters from `string`.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to trim.
+ * @param {string} [chars=whitespace] The characters to trim.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {string} Returns the trimmed string.
+ * @example
+ *
+ * _.trim(' abc ');
+ * // => 'abc'
+ *
+ * _.trim('-_-abc-_-', '_-');
+ * // => 'abc'
+ *
+ * _.map([' foo ', ' bar '], _.trim);
+ * // => ['foo', 'bar']
+ */
+ function trim(string, chars, guard) {
+ var value = string;
+ string = baseToString(string);
+ if (!string) {
+ return string;
+ }
+ if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
+ return string.slice(trimmedLeftIndex(string), trimmedRightIndex(string) + 1);
+ }
+ chars = chars + '';
+ return string.slice(charsLeftIndex(string, chars), charsRightIndex(string, chars) + 1);
+ }
+ /**
+ * Removes leading whitespace or specified characters from `string`.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to trim.
+ * @param {string} [chars=whitespace] The characters to trim.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {string} Returns the trimmed string.
+ * @example
+ *
+ * _.trimLeft(' abc ');
+ * // => 'abc '
+ *
+ * _.trimLeft('-_-abc-_-', '_-');
+ * // => 'abc-_-'
+ */
+ function trimLeft(string, chars, guard) {
+ var value = string;
+ string = baseToString(string);
+ if (!string) {
+ return string;
+ }
+ if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
+ return string.slice(trimmedLeftIndex(string));
+ }
+ return string.slice(charsLeftIndex(string, chars + ''));
+ }
+ /**
+ * Removes trailing whitespace or specified characters from `string`.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to trim.
+ * @param {string} [chars=whitespace] The characters to trim.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {string} Returns the trimmed string.
+ * @example
+ *
+ * _.trimRight(' abc ');
+ * // => ' abc'
+ *
+ * _.trimRight('-_-abc-_-', '_-');
+ * // => '-_-abc'
+ */
+ function trimRight(string, chars, guard) {
+ var value = string;
+ string = baseToString(string);
+ if (!string) {
+ return string;
+ }
+ if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
+ return string.slice(0, trimmedRightIndex(string) + 1);
+ }
+ return string.slice(0, charsRightIndex(string, chars + '') + 1);
+ }
+ /**
+ * Truncates `string` if it's longer than the given maximum string length.
+ * The last characters of the truncated string are replaced with the omission
+ * string which defaults to "...".
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to truncate.
+ * @param {Object|number} [options] The options object or maximum string length.
+ * @param {number} [options.length=30] The maximum string length.
+ * @param {string} [options.omission='...'] The string to indicate text is omitted.
+ * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {string} Returns the truncated string.
+ * @example
+ *
+ * _.trunc('hi-diddly-ho there, neighborino');
+ * // => 'hi-diddly-ho there, neighbo...'
+ *
+ * _.trunc('hi-diddly-ho there, neighborino', 24);
+ * // => 'hi-diddly-ho there, n...'
+ *
+ * _.trunc('hi-diddly-ho there, neighborino', {
+ * 'length': 24,
+ * 'separator': ' '
+ * });
+ * // => 'hi-diddly-ho there,...'
+ *
+ * _.trunc('hi-diddly-ho there, neighborino', {
+ * 'length': 24,
+ * 'separator': /,? +/
+ * });
+ * // => 'hi-diddly-ho there...'
+ *
+ * _.trunc('hi-diddly-ho there, neighborino', {
+ * 'omission': ' [...]'
+ * });
+ * // => 'hi-diddly-ho there, neig [...]'
+ */
+ function trunc(string, options, guard) {
+ if (guard && isIterateeCall(string, options, guard)) {
+ options = undefined;
+ }
+ var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION;
+ if (options != null) {
+ if (isObject(options)) {
+ var separator = 'separator' in options ? options.separator : separator;
+ length = 'length' in options ? +options.length || 0 : length;
+ omission = 'omission' in options ? baseToString(options.omission) : omission;
+ } else {
+ length = +options || 0;
+ }
+ }
+ string = baseToString(string);
+ if (length >= string.length) {
+ return string;
+ }
+ var end = length - omission.length;
+ if (end < 1) {
+ return omission;
+ }
+ var result = string.slice(0, end);
+ if (separator == null) {
+ return result + omission;
+ }
+ if (isRegExp(separator)) {
+ if (string.slice(end).search(separator)) {
+ var match, newEnd, substring = string.slice(0, end);
+ if (!separator.global) {
+ separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
+ }
+ separator.lastIndex = 0;
+ while (match = separator.exec(substring)) {
+ newEnd = match.index;
+ }
+ result = result.slice(0, newEnd == null ? end : newEnd);
+ }
+ } else if (string.indexOf(separator, end) != end) {
+ var index = result.lastIndexOf(separator);
+ if (index > -1) {
+ result = result.slice(0, index);
+ }
+ }
+ return result + omission;
+ }
+ /**
+ * The inverse of `_.escape`; this method converts the HTML entities
+ * `&`, `<`, `>`, `"`, `'`, and ``` in `string` to their
+ * corresponding characters.
+ *
+ * **Note:** No other HTML entities are unescaped. To unescape additional HTML
+ * entities use a third-party library like [_he_](https://mths.be/he).
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to unescape.
+ * @returns {string} Returns the unescaped string.
+ * @example
+ *
+ * _.unescape('fred, barney, & pebbles');
+ * // => 'fred, barney, & pebbles'
+ */
+ function unescape(string) {
+ string = baseToString(string);
+ return string && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string;
+ }
+ /**
+ * Splits `string` into an array of its words.
+ *
+ * @static
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to inspect.
+ * @param {RegExp|string} [pattern] The pattern to match words.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {Array} Returns the words of `string`.
+ * @example
+ *
+ * _.words('fred, barney, & pebbles');
+ * // => ['fred', 'barney', 'pebbles']
+ *
+ * _.words('fred, barney, & pebbles', /[^, ]+/g);
+ * // => ['fred', 'barney', '&', 'pebbles']
+ */
+ function words(string, pattern, guard) {
+ if (guard && isIterateeCall(string, pattern, guard)) {
+ pattern = undefined;
+ }
+ string = baseToString(string);
+ return string.match(pattern || reWords) || [];
+ }
+ /*------------------------------------------------------------------------*/
+ /**
+ * Attempts to invoke `func`, returning either the result or the caught error
+ * object. Any additional arguments are provided to `func` when it's invoked.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {Function} func The function to attempt.
+ * @returns {*} Returns the `func` result or error object.
+ * @example
+ *
+ * // avoid throwing errors for invalid selectors
+ * var elements = _.attempt(function(selector) {
+ * return document.querySelectorAll(selector);
+ * }, '>_>');
+ *
+ * if (_.isError(elements)) {
+ * elements = [];
+ * }
+ */
+ var attempt = restParam(function (func, args) {
+ try {
+ return func.apply(undefined, args);
+ } catch (e) {
+ return isError(e) ? e : new Error(e);
+ }
+ });
+ /**
+ * Creates a function that invokes `func` with the `this` binding of `thisArg`
+ * and arguments of the created function. If `func` is a property name the
+ * created callback returns the property value for a given element. If `func`
+ * is an object the created callback returns `true` for elements that contain
+ * the equivalent object properties, otherwise it returns `false`.
+ *
+ * @static
+ * @memberOf _
+ * @alias iteratee
+ * @category Utility
+ * @param {*} [func=_.identity] The value to convert to a callback.
+ * @param {*} [thisArg] The `this` binding of `func`.
+ * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
+ * @returns {Function} Returns the callback.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36 },
+ * { 'user': 'fred', 'age': 40 }
+ * ];
+ *
+ * // wrap to create custom callback shorthands
+ * _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
+ * var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
+ * if (!match) {
+ * return callback(func, thisArg);
+ * }
+ * return function(object) {
+ * return match[2] == 'gt'
+ * ? object[match[1]] > match[3]
+ * : object[match[1]] < match[3];
+ * };
+ * });
+ *
+ * _.filter(users, 'age__gt36');
+ * // => [{ 'user': 'fred', 'age': 40 }]
+ */
+ function callback(func, thisArg, guard) {
+ if (guard && isIterateeCall(func, thisArg, guard)) {
+ thisArg = undefined;
+ }
+ return isObjectLike(func) ? matches(func) : baseCallback(func, thisArg);
+ }
+ /**
+ * Creates a function that returns `value`.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {*} value The value to return from the new function.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var object = { 'user': 'fred' };
+ * var getter = _.constant(object);
+ *
+ * getter() === object;
+ * // => true
+ */
+ function constant(value) {
+ return function () {
+ return value;
+ };
+ }
+ /**
+ * This method returns the first argument provided to it.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {*} value Any value.
+ * @returns {*} Returns `value`.
+ * @example
+ *
+ * var object = { 'user': 'fred' };
+ *
+ * _.identity(object) === object;
+ * // => true
+ */
+ function identity(value) {
+ return value;
+ }
+ /**
+ * Creates a function that performs a deep comparison between a given object
+ * and `source`, returning `true` if the given object has equivalent property
+ * values, else `false`.
+ *
+ * **Note:** This method supports comparing arrays, booleans, `Date` objects,
+ * numbers, `Object` objects, regexes, and strings. Objects are compared by
+ * their own, not inherited, enumerable properties. For comparing a single
+ * own or inherited property value see `_.matchesProperty`.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {Object} source The object of property values to match.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36, 'active': true },
+ * { 'user': 'fred', 'age': 40, 'active': false }
+ * ];
+ *
+ * _.filter(users, _.matches({ 'age': 40, 'active': false }));
+ * // => [{ 'user': 'fred', 'age': 40, 'active': false }]
+ */
+ function matches(source) {
+ return baseMatches(baseClone(source, true));
+ }
+ /**
+ * Creates a function that compares the property value of `path` on a given
+ * object to `value`.
+ *
+ * **Note:** This method supports comparing arrays, booleans, `Date` objects,
+ * numbers, `Object` objects, regexes, and strings. Objects are compared by
+ * their own, not inherited, enumerable properties.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {Array|string} path The path of the property to get.
+ * @param {*} srcValue The value to match.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney' },
+ * { 'user': 'fred' }
+ * ];
+ *
+ * _.find(users, _.matchesProperty('user', 'fred'));
+ * // => { 'user': 'fred' }
+ */
+ function matchesProperty(path, srcValue) {
+ return baseMatchesProperty(path, baseClone(srcValue, true));
+ }
+ /**
+ * Creates a function that invokes the method at `path` on a given object.
+ * Any additional arguments are provided to the invoked method.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {Array|string} path The path of the method to invoke.
+ * @param {...*} [args] The arguments to invoke the method with.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var objects = [
+ * { 'a': { 'b': { 'c': _.constant(2) } } },
+ * { 'a': { 'b': { 'c': _.constant(1) } } }
+ * ];
+ *
+ * _.map(objects, _.method('a.b.c'));
+ * // => [2, 1]
+ *
+ * _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
+ * // => [1, 2]
+ */
+ var method = restParam(function (path, args) {
+ return function (object) {
+ return invokePath(object, path, args);
+ };
+ });
+ /**
+ * The opposite of `_.method`; this method creates a function that invokes
+ * the method at a given path on `object`. Any additional arguments are
+ * provided to the invoked method.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {Object} object The object to query.
+ * @param {...*} [args] The arguments to invoke the method with.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var array = _.times(3, _.constant),
+ * object = { 'a': array, 'b': array, 'c': array };
+ *
+ * _.map(['a[2]', 'c[0]'], _.methodOf(object));
+ * // => [2, 0]
+ *
+ * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
+ * // => [2, 0]
+ */
+ var methodOf = restParam(function (object, args) {
+ return function (path) {
+ return invokePath(object, path, args);
+ };
+ });
+ /**
+ * Adds all own enumerable function properties of a source object to the
+ * destination object. If `object` is a function then methods are added to
+ * its prototype as well.
+ *
+ * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
+ * avoid conflicts caused by modifying the original.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {Function|Object} [object=lodash] The destination object.
+ * @param {Object} source The object of functions to add.
+ * @param {Object} [options] The options object.
+ * @param {boolean} [options.chain=true] Specify whether the functions added
+ * are chainable.
+ * @returns {Function|Object} Returns `object`.
+ * @example
+ *
+ * function vowels(string) {
+ * return _.filter(string, function(v) {
+ * return /[aeiou]/i.test(v);
+ * });
+ * }
+ *
+ * _.mixin({ 'vowels': vowels });
+ * _.vowels('fred');
+ * // => ['e']
+ *
+ * _('fred').vowels().value();
+ * // => ['e']
+ *
+ * _.mixin({ 'vowels': vowels }, { 'chain': false });
+ * _('fred').vowels();
+ * // => ['e']
+ */
+ function mixin(object, source, options) {
+ if (options == null) {
+ var isObj = isObject(source), props = isObj ? keys(source) : undefined, methodNames = props && props.length ? baseFunctions(source, props) : undefined;
+ if (!(methodNames ? methodNames.length : isObj)) {
+ methodNames = false;
+ options = source;
+ source = object;
+ object = this;
+ }
+ }
+ if (!methodNames) {
+ methodNames = baseFunctions(source, keys(source));
+ }
+ var chain = true, index = -1, isFunc = isFunction(object), length = methodNames.length;
+ if (options === false) {
+ chain = false;
+ } else if (isObject(options) && 'chain' in options) {
+ chain = options.chain;
+ }
+ while (++index < length) {
+ var methodName = methodNames[index], func = source[methodName];
+ object[methodName] = func;
+ if (isFunc) {
+ object.prototype[methodName] = function (func) {
+ return function () {
+ var chainAll = this.__chain__;
+ if (chain || chainAll) {
+ var result = object(this.__wrapped__), actions = result.__actions__ = arrayCopy(this.__actions__);
+ actions.push({
+ 'func': func,
+ 'args': arguments,
+ 'thisArg': object
+ });
+ result.__chain__ = chainAll;
+ return result;
+ }
+ return func.apply(object, arrayPush([this.value()], arguments));
+ };
+ }(func);
+ }
+ }
+ return object;
+ }
+ /**
+ * Reverts the `_` variable to its previous value and returns a reference to
+ * the `lodash` function.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @returns {Function} Returns the `lodash` function.
+ * @example
+ *
+ * var lodash = _.noConflict();
+ */
+ function noConflict() {
+ root._ = oldDash;
+ return this;
+ }
+ /**
+ * A no-operation function that returns `undefined` regardless of the
+ * arguments it receives.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @example
+ *
+ * var object = { 'user': 'fred' };
+ *
+ * _.noop(object) === undefined;
+ * // => true
+ */
+ function noop() {
+ }
+ /**
+ * Creates a function that returns the property value at `path` on a
+ * given object.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {Array|string} path The path of the property to get.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var objects = [
+ * { 'a': { 'b': { 'c': 2 } } },
+ * { 'a': { 'b': { 'c': 1 } } }
+ * ];
+ *
+ * _.map(objects, _.property('a.b.c'));
+ * // => [2, 1]
+ *
+ * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
+ * // => [1, 2]
+ */
+ function property(path) {
+ return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
+ }
+ /**
+ * The opposite of `_.property`; this method creates a function that returns
+ * the property value at a given path on `object`.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {Object} object The object to query.
+ * @returns {Function} Returns the new function.
+ * @example
+ *
+ * var array = [0, 1, 2],
+ * object = { 'a': array, 'b': array, 'c': array };
+ *
+ * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
+ * // => [2, 0]
+ *
+ * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
+ * // => [2, 0]
+ */
+ function propertyOf(object) {
+ return function (path) {
+ return baseGet(object, toPath(path), path + '');
+ };
+ }
+ /**
+ * Creates an array of numbers (positive and/or negative) progressing from
+ * `start` up to, but not including, `end`. If `end` is not specified it's
+ * set to `start` with `start` then set to `0`. If `end` is less than `start`
+ * a zero-length range is created unless a negative `step` is specified.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {number} [start=0] The start of the range.
+ * @param {number} end The end of the range.
+ * @param {number} [step=1] The value to increment or decrement by.
+ * @returns {Array} Returns the new array of numbers.
+ * @example
+ *
+ * _.range(4);
+ * // => [0, 1, 2, 3]
+ *
+ * _.range(1, 5);
+ * // => [1, 2, 3, 4]
+ *
+ * _.range(0, 20, 5);
+ * // => [0, 5, 10, 15]
+ *
+ * _.range(0, -4, -1);
+ * // => [0, -1, -2, -3]
+ *
+ * _.range(1, 4, 0);
+ * // => [1, 1, 1]
+ *
+ * _.range(0);
+ * // => []
+ */
+ function range(start, end, step) {
+ if (step && isIterateeCall(start, end, step)) {
+ end = step = undefined;
+ }
+ start = +start || 0;
+ step = step == null ? 1 : +step || 0;
+ if (end == null) {
+ end = start;
+ start = 0;
+ } else {
+ end = +end || 0;
+ }
+ // Use `Array(length)` so engines like Chakra and V8 avoid slower modes.
+ // See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details.
+ var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length);
+ while (++index < length) {
+ result[index] = start;
+ start += step;
+ }
+ return result;
+ }
+ /**
+ * Invokes the iteratee function `n` times, returning an array of the results
+ * of each invocation. The `iteratee` is bound to `thisArg` and invoked with
+ * one argument; (index).
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {number} n The number of times to invoke `iteratee`.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {Array} Returns the array of results.
+ * @example
+ *
+ * var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
+ * // => [3, 6, 4]
+ *
+ * _.times(3, function(n) {
+ * mage.castSpell(n);
+ * });
+ * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2`
+ *
+ * _.times(3, function(n) {
+ * this.cast(n);
+ * }, mage);
+ * // => also invokes `mage.castSpell(n)` three times
+ */
+ function times(n, iteratee, thisArg) {
+ n = nativeFloor(n);
+ // Exit early to avoid a JSC JIT bug in Safari 8
+ // where `Array(0)` is treated as `Array(1)`.
+ if (n < 1 || !nativeIsFinite(n)) {
+ return [];
+ }
+ var index = -1, result = Array(nativeMin(n, MAX_ARRAY_LENGTH));
+ iteratee = bindCallback(iteratee, thisArg, 1);
+ while (++index < n) {
+ if (index < MAX_ARRAY_LENGTH) {
+ result[index] = iteratee(index);
+ } else {
+ iteratee(index);
+ }
+ }
+ return result;
+ }
+ /**
+ * Generates a unique ID. If `prefix` is provided the ID is appended to it.
+ *
+ * @static
+ * @memberOf _
+ * @category Utility
+ * @param {string} [prefix] The value to prefix the ID with.
+ * @returns {string} Returns the unique ID.
+ * @example
+ *
+ * _.uniqueId('contact_');
+ * // => 'contact_104'
+ *
+ * _.uniqueId();
+ * // => '105'
+ */
+ function uniqueId(prefix) {
+ var id = ++idCounter;
+ return baseToString(prefix) + id;
+ }
+ /*------------------------------------------------------------------------*/
+ /**
+ * Adds two numbers.
+ *
+ * @static
+ * @memberOf _
+ * @category Math
+ * @param {number} augend The first number to add.
+ * @param {number} addend The second number to add.
+ * @returns {number} Returns the sum.
+ * @example
+ *
+ * _.add(6, 4);
+ * // => 10
+ */
+ function add(augend, addend) {
+ return (+augend || 0) + (+addend || 0);
+ }
+ /**
+ * Calculates `n` rounded up to `precision`.
+ *
+ * @static
+ * @memberOf _
+ * @category Math
+ * @param {number} n The number to round up.
+ * @param {number} [precision=0] The precision to round up to.
+ * @returns {number} Returns the rounded up number.
+ * @example
+ *
+ * _.ceil(4.006);
+ * // => 5
+ *
+ * _.ceil(6.004, 2);
+ * // => 6.01
+ *
+ * _.ceil(6040, -2);
+ * // => 6100
+ */
+ var ceil = createRound('ceil');
+ /**
+ * Calculates `n` rounded down to `precision`.
+ *
+ * @static
+ * @memberOf _
+ * @category Math
+ * @param {number} n The number to round down.
+ * @param {number} [precision=0] The precision to round down to.
+ * @returns {number} Returns the rounded down number.
+ * @example
+ *
+ * _.floor(4.006);
+ * // => 4
+ *
+ * _.floor(0.046, 2);
+ * // => 0.04
+ *
+ * _.floor(4060, -2);
+ * // => 4000
+ */
+ var floor = createRound('floor');
+ /**
+ * Gets the maximum value of `collection`. If `collection` is empty or falsey
+ * `-Infinity` is returned. If an iteratee function is provided it's invoked
+ * for each value in `collection` to generate the criterion by which the value
+ * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
+ * arguments: (value, index, collection).
+ *
+ * If a property name is provided for `iteratee` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `iteratee` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Math
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [iteratee] The function invoked per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {*} Returns the maximum value.
+ * @example
+ *
+ * _.max([4, 2, 8, 6]);
+ * // => 8
+ *
+ * _.max([]);
+ * // => -Infinity
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36 },
+ * { 'user': 'fred', 'age': 40 }
+ * ];
+ *
+ * _.max(users, function(chr) {
+ * return chr.age;
+ * });
+ * // => { 'user': 'fred', 'age': 40 }
+ *
+ * // using the `_.property` callback shorthand
+ * _.max(users, 'age');
+ * // => { 'user': 'fred', 'age': 40 }
+ */
+ var max = createExtremum(gt, NEGATIVE_INFINITY);
+ /**
+ * Gets the minimum value of `collection`. If `collection` is empty or falsey
+ * `Infinity` is returned. If an iteratee function is provided it's invoked
+ * for each value in `collection` to generate the criterion by which the value
+ * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
+ * arguments: (value, index, collection).
+ *
+ * If a property name is provided for `iteratee` the created `_.property`
+ * style callback returns the property value of the given element.
+ *
+ * If a value is also provided for `thisArg` the created `_.matchesProperty`
+ * style callback returns `true` for elements that have a matching property
+ * value, else `false`.
+ *
+ * If an object is provided for `iteratee` the created `_.matches` style
+ * callback returns `true` for elements that have the properties of the given
+ * object, else `false`.
+ *
+ * @static
+ * @memberOf _
+ * @category Math
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [iteratee] The function invoked per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {*} Returns the minimum value.
+ * @example
+ *
+ * _.min([4, 2, 8, 6]);
+ * // => 2
+ *
+ * _.min([]);
+ * // => Infinity
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36 },
+ * { 'user': 'fred', 'age': 40 }
+ * ];
+ *
+ * _.min(users, function(chr) {
+ * return chr.age;
+ * });
+ * // => { 'user': 'barney', 'age': 36 }
+ *
+ * // using the `_.property` callback shorthand
+ * _.min(users, 'age');
+ * // => { 'user': 'barney', 'age': 36 }
+ */
+ var min = createExtremum(lt, POSITIVE_INFINITY);
+ /**
+ * Calculates `n` rounded to `precision`.
+ *
+ * @static
+ * @memberOf _
+ * @category Math
+ * @param {number} n The number to round.
+ * @param {number} [precision=0] The precision to round to.
+ * @returns {number} Returns the rounded number.
+ * @example
+ *
+ * _.round(4.006);
+ * // => 4
+ *
+ * _.round(4.006, 2);
+ * // => 4.01
+ *
+ * _.round(4060, -2);
+ * // => 4100
+ */
+ var round = createRound('round');
+ /**
+ * Gets the sum of the values in `collection`.
+ *
+ * @static
+ * @memberOf _
+ * @category Math
+ * @param {Array|Object|string} collection The collection to iterate over.
+ * @param {Function|Object|string} [iteratee] The function invoked per iteration.
+ * @param {*} [thisArg] The `this` binding of `iteratee`.
+ * @returns {number} Returns the sum.
+ * @example
+ *
+ * _.sum([4, 6]);
+ * // => 10
+ *
+ * _.sum({ 'a': 4, 'b': 6 });
+ * // => 10
+ *
+ * var objects = [
+ * { 'n': 4 },
+ * { 'n': 6 }
+ * ];
+ *
+ * _.sum(objects, function(object) {
+ * return object.n;
+ * });
+ * // => 10
+ *
+ * // using the `_.property` callback shorthand
+ * _.sum(objects, 'n');
+ * // => 10
+ */
+ function sum(collection, iteratee, thisArg) {
+ if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
+ iteratee = undefined;
+ }
+ iteratee = getCallback(iteratee, thisArg, 3);
+ return iteratee.length == 1 ? arraySum(isArray(collection) ? collection : toIterable(collection), iteratee) : baseSum(collection, iteratee);
+ }
+ /*------------------------------------------------------------------------*/
+ // Ensure wrappers are instances of `baseLodash`.
+ lodash.prototype = baseLodash.prototype;
+ LodashWrapper.prototype = baseCreate(baseLodash.prototype);
+ LodashWrapper.prototype.constructor = LodashWrapper;
+ LazyWrapper.prototype = baseCreate(baseLodash.prototype);
+ LazyWrapper.prototype.constructor = LazyWrapper;
+ // Add functions to the `Map` cache.
+ MapCache.prototype['delete'] = mapDelete;
+ MapCache.prototype.get = mapGet;
+ MapCache.prototype.has = mapHas;
+ MapCache.prototype.set = mapSet;
+ // Add functions to the `Set` cache.
+ SetCache.prototype.push = cachePush;
+ // Assign cache to `_.memoize`.
+ memoize.Cache = MapCache;
+ // Add functions that return wrapped values when chaining.
+ lodash.after = after;
+ lodash.ary = ary;
+ lodash.assign = assign;
+ lodash.at = at;
+ lodash.before = before;
+ lodash.bind = bind;
+ lodash.bindAll = bindAll;
+ lodash.bindKey = bindKey;
+ lodash.callback = callback;
+ lodash.chain = chain;
+ lodash.chunk = chunk;
+ lodash.compact = compact;
+ lodash.constant = constant;
+ lodash.countBy = countBy;
+ lodash.create = create;
+ lodash.curry = curry;
+ lodash.curryRight = curryRight;
+ lodash.debounce = debounce;
+ lodash.defaults = defaults;
+ lodash.defaultsDeep = defaultsDeep;
+ lodash.defer = defer;
+ lodash.delay = delay;
+ lodash.difference = difference;
+ lodash.drop = drop;
+ lodash.dropRight = dropRight;
+ lodash.dropRightWhile = dropRightWhile;
+ lodash.dropWhile = dropWhile;
+ lodash.fill = fill;
+ lodash.filter = filter;
+ lodash.flatten = flatten;
+ lodash.flattenDeep = flattenDeep;
+ lodash.flow = flow;
+ lodash.flowRight = flowRight;
+ lodash.forEach = forEach;
+ lodash.forEachRight = forEachRight;
+ lodash.forIn = forIn;
+ lodash.forInRight = forInRight;
+ lodash.forOwn = forOwn;
+ lodash.forOwnRight = forOwnRight;
+ lodash.functions = functions;
+ lodash.groupBy = groupBy;
+ lodash.indexBy = indexBy;
+ lodash.initial = initial;
+ lodash.intersection = intersection;
+ lodash.invert = invert;
+ lodash.invoke = invoke;
+ lodash.keys = keys;
+ lodash.keysIn = keysIn;
+ lodash.map = map;
+ lodash.mapKeys = mapKeys;
+ lodash.mapValues = mapValues;
+ lodash.matches = matches;
+ lodash.matchesProperty = matchesProperty;
+ lodash.memoize = memoize;
+ lodash.merge = merge;
+ lodash.method = method;
+ lodash.methodOf = methodOf;
+ lodash.mixin = mixin;
+ lodash.modArgs = modArgs;
+ lodash.negate = negate;
+ lodash.omit = omit;
+ lodash.once = once;
+ lodash.pairs = pairs;
+ lodash.partial = partial;
+ lodash.partialRight = partialRight;
+ lodash.partition = partition;
+ lodash.pick = pick;
+ lodash.pluck = pluck;
+ lodash.property = property;
+ lodash.propertyOf = propertyOf;
+ lodash.pull = pull;
+ lodash.pullAt = pullAt;
+ lodash.range = range;
+ lodash.rearg = rearg;
+ lodash.reject = reject;
+ lodash.remove = remove;
+ lodash.rest = rest;
+ lodash.restParam = restParam;
+ lodash.set = set;
+ lodash.shuffle = shuffle;
+ lodash.slice = slice;
+ lodash.sortBy = sortBy;
+ lodash.sortByAll = sortByAll;
+ lodash.sortByOrder = sortByOrder;
+ lodash.spread = spread;
+ lodash.take = take;
+ lodash.takeRight = takeRight;
+ lodash.takeRightWhile = takeRightWhile;
+ lodash.takeWhile = takeWhile;
+ lodash.tap = tap;
+ lodash.throttle = throttle;
+ lodash.thru = thru;
+ lodash.times = times;
+ lodash.toArray = toArray;
+ lodash.toPlainObject = toPlainObject;
+ lodash.transform = transform;
+ lodash.union = union;
+ lodash.uniq = uniq;
+ lodash.unzip = unzip;
+ lodash.unzipWith = unzipWith;
+ lodash.values = values;
+ lodash.valuesIn = valuesIn;
+ lodash.where = where;
+ lodash.without = without;
+ lodash.wrap = wrap;
+ lodash.xor = xor;
+ lodash.zip = zip;
+ lodash.zipObject = zipObject;
+ lodash.zipWith = zipWith;
+ // Add aliases.
+ lodash.backflow = flowRight;
+ lodash.collect = map;
+ lodash.compose = flowRight;
+ lodash.each = forEach;
+ lodash.eachRight = forEachRight;
+ lodash.extend = assign;
+ lodash.iteratee = callback;
+ lodash.methods = functions;
+ lodash.object = zipObject;
+ lodash.select = filter;
+ lodash.tail = rest;
+ lodash.unique = uniq;
+ // Add functions to `lodash.prototype`.
+ mixin(lodash, lodash);
+ /*------------------------------------------------------------------------*/
+ // Add functions that return unwrapped values when chaining.
+ lodash.add = add;
+ lodash.attempt = attempt;
+ lodash.camelCase = camelCase;
+ lodash.capitalize = capitalize;
+ lodash.ceil = ceil;
+ lodash.clone = clone;
+ lodash.cloneDeep = cloneDeep;
+ lodash.deburr = deburr;
+ lodash.endsWith = endsWith;
+ lodash.escape = escape;
+ lodash.escapeRegExp = escapeRegExp;
+ lodash.every = every;
+ lodash.find = find;
+ lodash.findIndex = findIndex;
+ lodash.findKey = findKey;
+ lodash.findLast = findLast;
+ lodash.findLastIndex = findLastIndex;
+ lodash.findLastKey = findLastKey;
+ lodash.findWhere = findWhere;
+ lodash.first = first;
+ lodash.floor = floor;
+ lodash.get = get;
+ lodash.gt = gt;
+ lodash.gte = gte;
+ lodash.has = has;
+ lodash.identity = identity;
+ lodash.includes = includes;
+ lodash.indexOf = indexOf;
+ lodash.inRange = inRange;
+ lodash.isArguments = isArguments;
+ lodash.isArray = isArray;
+ lodash.isBoolean = isBoolean;
+ lodash.isDate = isDate;
+ lodash.isElement = isElement;
+ lodash.isEmpty = isEmpty;
+ lodash.isEqual = isEqual;
+ lodash.isError = isError;
+ lodash.isFinite = isFinite;
+ lodash.isFunction = isFunction;
+ lodash.isMatch = isMatch;
+ lodash.isNaN = isNaN;
+ lodash.isNative = isNative;
+ lodash.isNull = isNull;
+ lodash.isNumber = isNumber;
+ lodash.isObject = isObject;
+ lodash.isPlainObject = isPlainObject;
+ lodash.isRegExp = isRegExp;
+ lodash.isString = isString;
+ lodash.isTypedArray = isTypedArray;
+ lodash.isUndefined = isUndefined;
+ lodash.kebabCase = kebabCase;
+ lodash.last = last;
+ lodash.lastIndexOf = lastIndexOf;
+ lodash.lt = lt;
+ lodash.lte = lte;
+ lodash.max = max;
+ lodash.min = min;
+ lodash.noConflict = noConflict;
+ lodash.noop = noop;
+ lodash.now = now;
+ lodash.pad = pad;
+ lodash.padLeft = padLeft;
+ lodash.padRight = padRight;
+ lodash.parseInt = parseInt;
+ lodash.random = random;
+ lodash.reduce = reduce;
+ lodash.reduceRight = reduceRight;
+ lodash.repeat = repeat;
+ lodash.result = result;
+ lodash.round = round;
+ lodash.runInContext = runInContext;
+ lodash.size = size;
+ lodash.snakeCase = snakeCase;
+ lodash.some = some;
+ lodash.sortedIndex = sortedIndex;
+ lodash.sortedLastIndex = sortedLastIndex;
+ lodash.startCase = startCase;
+ lodash.startsWith = startsWith;
+ lodash.sum = sum;
+ lodash.template = template;
+ lodash.trim = trim;
+ lodash.trimLeft = trimLeft;
+ lodash.trimRight = trimRight;
+ lodash.trunc = trunc;
+ lodash.unescape = unescape;
+ lodash.uniqueId = uniqueId;
+ lodash.words = words;
+ // Add aliases.
+ lodash.all = every;
+ lodash.any = some;
+ lodash.contains = includes;
+ lodash.eq = isEqual;
+ lodash.detect = find;
+ lodash.foldl = reduce;
+ lodash.foldr = reduceRight;
+ lodash.head = first;
+ lodash.include = includes;
+ lodash.inject = reduce;
+ mixin(lodash, function () {
+ var source = {};
+ baseForOwn(lodash, function (func, methodName) {
+ if (!lodash.prototype[methodName]) {
+ source[methodName] = func;
+ }
+ });
+ return source;
+ }(), false);
+ /*------------------------------------------------------------------------*/
+ // Add functions capable of returning wrapped and unwrapped values when chaining.
+ lodash.sample = sample;
+ lodash.prototype.sample = function (n) {
+ if (!this.__chain__ && n == null) {
+ return sample(this.value());
+ }
+ return this.thru(function (value) {
+ return sample(value, n);
+ });
+ };
+ /*------------------------------------------------------------------------*/
+ /**
+ * The semantic version number.
+ *
+ * @static
+ * @memberOf _
+ * @type string
+ */
+ lodash.VERSION = VERSION;
+ // Assign default placeholders.
+ arrayEach([
+ 'bind',
+ 'bindKey',
+ 'curry',
+ 'curryRight',
+ 'partial',
+ 'partialRight'
+ ], function (methodName) {
+ lodash[methodName].placeholder = lodash;
+ });
+ // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
+ arrayEach([
+ 'drop',
+ 'take'
+ ], function (methodName, index) {
+ LazyWrapper.prototype[methodName] = function (n) {
+ var filtered = this.__filtered__;
+ if (filtered && !index) {
+ return new LazyWrapper(this);
+ }
+ n = n == null ? 1 : nativeMax(nativeFloor(n) || 0, 0);
+ var result = this.clone();
+ if (filtered) {
+ result.__takeCount__ = nativeMin(result.__takeCount__, n);
+ } else {
+ result.__views__.push({
+ 'size': n,
+ 'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
+ });
+ }
+ return result;
+ };
+ LazyWrapper.prototype[methodName + 'Right'] = function (n) {
+ return this.reverse()[methodName](n).reverse();
+ };
+ });
+ // Add `LazyWrapper` methods that accept an `iteratee` value.
+ arrayEach([
+ 'filter',
+ 'map',
+ 'takeWhile'
+ ], function (methodName, index) {
+ var type = index + 1, isFilter = type != LAZY_MAP_FLAG;
+ LazyWrapper.prototype[methodName] = function (iteratee, thisArg) {
+ var result = this.clone();
+ result.__iteratees__.push({
+ 'iteratee': getCallback(iteratee, thisArg, 1),
+ 'type': type
+ });
+ result.__filtered__ = result.__filtered__ || isFilter;
+ return result;
+ };
+ });
+ // Add `LazyWrapper` methods for `_.first` and `_.last`.
+ arrayEach([
+ 'first',
+ 'last'
+ ], function (methodName, index) {
+ var takeName = 'take' + (index ? 'Right' : '');
+ LazyWrapper.prototype[methodName] = function () {
+ return this[takeName](1).value()[0];
+ };
+ });
+ // Add `LazyWrapper` methods for `_.initial` and `_.rest`.
+ arrayEach([
+ 'initial',
+ 'rest'
+ ], function (methodName, index) {
+ var dropName = 'drop' + (index ? '' : 'Right');
+ LazyWrapper.prototype[methodName] = function () {
+ return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
+ };
+ });
+ // Add `LazyWrapper` methods for `_.pluck` and `_.where`.
+ arrayEach([
+ 'pluck',
+ 'where'
+ ], function (methodName, index) {
+ var operationName = index ? 'filter' : 'map', createCallback = index ? baseMatches : property;
+ LazyWrapper.prototype[methodName] = function (value) {
+ return this[operationName](createCallback(value));
+ };
+ });
+ LazyWrapper.prototype.compact = function () {
+ return this.filter(identity);
+ };
+ LazyWrapper.prototype.reject = function (predicate, thisArg) {
+ predicate = getCallback(predicate, thisArg, 1);
+ return this.filter(function (value) {
+ return !predicate(value);
+ });
+ };
+ LazyWrapper.prototype.slice = function (start, end) {
+ start = start == null ? 0 : +start || 0;
+ var result = this;
+ if (result.__filtered__ && (start > 0 || end < 0)) {
+ return new LazyWrapper(result);
+ }
+ if (start < 0) {
+ result = result.takeRight(-start);
+ } else if (start) {
+ result = result.drop(start);
+ }
+ if (end !== undefined) {
+ end = +end || 0;
+ result = end < 0 ? result.dropRight(-end) : result.take(end - start);
+ }
+ return result;
+ };
+ LazyWrapper.prototype.takeRightWhile = function (predicate, thisArg) {
+ return this.reverse().takeWhile(predicate, thisArg).reverse();
+ };
+ LazyWrapper.prototype.toArray = function () {
+ return this.take(POSITIVE_INFINITY);
+ };
+ // Add `LazyWrapper` methods to `lodash.prototype`.
+ baseForOwn(LazyWrapper.prototype, function (func, methodName) {
+ var checkIteratee = /^(?:filter|map|reject)|While$/.test(methodName), retUnwrapped = /^(?:first|last)$/.test(methodName), lodashFunc = lodash[retUnwrapped ? 'take' + (methodName == 'last' ? 'Right' : '') : methodName];
+ if (!lodashFunc) {
+ return;
+ }
+ lodash.prototype[methodName] = function () {
+ var args = retUnwrapped ? [1] : arguments, chainAll = this.__chain__, value = this.__wrapped__, isHybrid = !!this.__actions__.length, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value);
+ if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
+ // Avoid lazy use if the iteratee has a "length" value other than `1`.
+ isLazy = useLazy = false;
+ }
+ var interceptor = function (value) {
+ return retUnwrapped && chainAll ? lodashFunc(value, 1)[0] : lodashFunc.apply(undefined, arrayPush([value], args));
+ };
+ var action = {
+ 'func': thru,
+ 'args': [interceptor],
+ 'thisArg': undefined
+ }, onlyLazy = isLazy && !isHybrid;
+ if (retUnwrapped && !chainAll) {
+ if (onlyLazy) {
+ value = value.clone();
+ value.__actions__.push(action);
+ return func.call(value);
+ }
+ return lodashFunc.call(undefined, this.value())[0];
+ }
+ if (!retUnwrapped && useLazy) {
+ value = onlyLazy ? value : new LazyWrapper(this);
+ var result = func.apply(value, args);
+ result.__actions__.push(action);
+ return new LodashWrapper(result, chainAll);
+ }
+ return this.thru(interceptor);
+ };
+ });
+ // Add `Array` and `String` methods to `lodash.prototype`.
+ arrayEach([
+ 'join',
+ 'pop',
+ 'push',
+ 'replace',
+ 'shift',
+ 'sort',
+ 'splice',
+ 'split',
+ 'unshift'
+ ], function (methodName) {
+ var func = (/^(?:replace|split)$/.test(methodName) ? stringProto : arrayProto)[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:join|pop|replace|shift)$/.test(methodName);
+ lodash.prototype[methodName] = function () {
+ var args = arguments;
+ if (retUnwrapped && !this.__chain__) {
+ return func.apply(this.value(), args);
+ }
+ return this[chainName](function (value) {
+ return func.apply(value, args);
+ });
+ };
+ });
+ // Map minified function names to their real names.
+ baseForOwn(LazyWrapper.prototype, function (func, methodName) {
+ var lodashFunc = lodash[methodName];
+ if (lodashFunc) {
+ var key = lodashFunc.name + '', names = realNames[key] || (realNames[key] = []);
+ names.push({
+ 'name': methodName,
+ 'func': lodashFunc
+ });
+ }
+ });
+ realNames[createHybridWrapper(undefined, BIND_KEY_FLAG).name] = [{
+ 'name': 'wrapper',
+ 'func': undefined
+ }];
+ // Add functions to the lazy wrapper.
+ LazyWrapper.prototype.clone = lazyClone;
+ LazyWrapper.prototype.reverse = lazyReverse;
+ LazyWrapper.prototype.value = lazyValue;
+ // Add chaining functions to the `lodash` wrapper.
+ lodash.prototype.chain = wrapperChain;
+ lodash.prototype.commit = wrapperCommit;
+ lodash.prototype.concat = wrapperConcat;
+ lodash.prototype.plant = wrapperPlant;
+ lodash.prototype.reverse = wrapperReverse;
+ lodash.prototype.toString = wrapperToString;
+ lodash.prototype.run = lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
+ // Add function aliases to the `lodash` wrapper.
+ lodash.prototype.collect = lodash.prototype.map;
+ lodash.prototype.head = lodash.prototype.first;
+ lodash.prototype.select = lodash.prototype.filter;
+ lodash.prototype.tail = lodash.prototype.rest;
+ return lodash;
+ }
+ /*--------------------------------------------------------------------------*/
+ // Export lodash.
+ var _ = runInContext();
+ // Some AMD build optimizers like r.js check for condition patterns like the following:
+ if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
+ // Define as an anonymous module so, through path mapping, it can be
+ // referenced as the "underscore" module.
+ define(function () {
+ return _;
+ });
+ } // Check for `exports` after `define` in case a build optimizer adds an `exports` object.
+ else if (freeExports && freeModule) {
+ // Export for Node.js or RingoJS.
+ if (moduleExports) {
+ (freeModule.exports = _)._ = _;
+ } // Export for Rhino with CommonJS support.
+ else {
+ freeExports._ = _;
+ }
+ }
+ $provide.constant('lodash', _);
+ }
+]);
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/build/ng-lodash.min.js b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/build/ng-lodash.min.js
new file mode 100644
index 0000000..4989a9e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/build/ng-lodash.min.js
@@ -0,0 +1,11 @@
+/**
+ * @license
+ * lodash 3.10.1 (Custom Build) <https://lodash.com/>
+ * Build: `lodash modern exports="amd,commonjs,node" iife="angular.module('ngLodash', []).constant('lodash', null).config(function ($provide) { %output% $provide.constant('lodash', _);});" --output build/ng-lodash.js`
+ * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
+ * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
+ * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ * Available under MIT license <https://lodash.com/license>
+ */
+angular.module("ngLodash",[]).constant("lodash",null).config(["$provide",function(a){function b(a,b){if(a!==b){var c=null===a,d=a===x,e=a===a,f=null===b,g=b===x,h=b===b;if(a>b&&!f||!e||c&&!g&&h||d&&h)return 1;if(b>a&&!c||!h||f&&!d&&e||g&&e)return-1}return 0}function c(a,b,c){for(var d=a.length,e=c?d:-1;c?e--:++e<d;)if(b(a[e],e,a))return e;return-1}function d(a,b,c){if(b!==b)return o(a,c);for(var d=c-1,e=a.length;++d<e;)if(a[d]===b)return d;return-1}function e(a){return"function"==typeof a||!1}function f(a){return null==a?"":a+""}function g(a,b){for(var c=-1,d=a.length;++c<d&&b.indexOf(a.charAt(c))>-1;);return c}function h(a,b){for(var c=a.length;c--&&b.indexOf(a.charAt(c))>-1;);return c}function i(a,c){return b(a.criteria,c.criteria)||a.index-c.index}function j(a,c,d){for(var e=-1,f=a.criteria,g=c.criteria,h=f.length,i=d.length;++e<h;){var j=b(f[e],g[e]);if(j){if(e>=i)return j;var k=d[e];return j*("asc"===k||k===!0?1:-1)}}return a.index-c.index}function k(a){return Qa[a]}function l(a){return Ra[a]}function m(a,b,c){return b?a=Ua[a]:c&&(a=Va[a]),"\\"+a}function n(a){return"\\"+Va[a]}function o(a,b,c){for(var d=a.length,e=b+(c?0:-1);c?e--:++e<d;){var f=a[e];if(f!==f)return e}return-1}function p(a){return!!a&&"object"==typeof a}function q(a){return 160>=a&&a>=9&&13>=a||32==a||160==a||5760==a||6158==a||a>=8192&&(8202>=a||8232==a||8233==a||8239==a||8287==a||12288==a||65279==a)}function r(a,b){for(var c=-1,d=a.length,e=-1,f=[];++c<d;)a[c]===b&&(a[c]=Q,f[++e]=c);return f}function s(a,b){for(var c,d=-1,e=a.length,f=-1,g=[];++d<e;){var h=a[d],i=b?b(h,d,a):h;d&&c===i||(c=i,g[++f]=h)}return g}function t(a){for(var b=-1,c=a.length;++b<c&&q(a.charCodeAt(b)););return b}function u(a){for(var b=a.length;b--&&q(a.charCodeAt(b)););return b}function v(a){return Sa[a]}function w(a){function q(a){if(p(a)&&!Dh(a)&&!(a instanceof ba)){if(a instanceof _)return a;if(ag.call(a,"__chain__")&&ag.call(a,"__wrapped__"))return md(a)}return new _(a)}function X(){}function _(a,b,c){this.__wrapped__=a,this.__actions__=c||[],this.__chain__=!!b}function ba(a){this.__wrapped__=a,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=Bg,this.__views__=[]}function Qa(){var a=new ba(this.__wrapped__);return a.__actions__=cb(this.__actions__),a.__dir__=this.__dir__,a.__filtered__=this.__filtered__,a.__iteratees__=cb(this.__iteratees__),a.__takeCount__=this.__takeCount__,a.__views__=cb(this.__views__),a}function Ra(){if(this.__filtered__){var a=new ba(this);a.__dir__=-1,a.__filtered__=!0}else a=this.clone(),a.__dir__*=-1;return a}function Sa(){var a=this.__wrapped__.value(),b=this.__dir__,c=Dh(a),d=0>b,e=c?a.length:0,f=Tc(0,e,this.__views__),g=f.start,h=f.end,i=h-g,j=d?h:g-1,k=this.__iteratees__,l=k.length,m=0,n=wg(i,this.__takeCount__);if(!c||M>e||e==i&&n==i)return cc(a,this.__actions__);var o=[];a:for(;i--&&n>m;){j+=b;for(var p=-1,q=a[j];++p<l;){var r=k[p],s=r.iteratee,t=r.type,u=s(q);if(t==O)q=u;else if(!u){if(t==N)continue a;break a}}o[m++]=q}return o}function Ta(){this.__data__={}}function Ua(a){return this.has(a)&&delete this.__data__[a]}function Va(a){return"__proto__"==a?x:this.__data__[a]}function Wa(a){return"__proto__"!=a&&ag.call(this.__data__,a)}function Xa(a,b){return"__proto__"!=a&&(this.__data__[a]=b),this}function Ya(a){var b=a?a.length:0;for(this.data={hash:qg(null),set:new kg};b--;)this.push(a[b])}function Za(a,b){var c=a.data,d="string"==typeof b||He(b)?c.set.has(b):c.hash[b];return d?0:-1}function $a(a){var b=this.data;"string"==typeof a||He(a)?b.set.add(a):b.hash[a]=!0}function _a(a,b){for(var c=-1,d=a.length,e=-1,f=b.length,g=Of(d+f);++c<d;)g[c]=a[c];for(;++e<f;)g[c++]=b[e];return g}function cb(a,b){var c=-1,d=a.length;for(b||(b=Of(d));++c<d;)b[c]=a[c];return b}function db(a,b){for(var c=-1,d=a.length;++c<d&&b(a[c],c,a)!==!1;);return a}function eb(a,b){for(var c=a.length;c--&&b(a[c],c,a)!==!1;);return a}function fb(a,b){for(var c=-1,d=a.length;++c<d;)if(!b(a[c],c,a))return!1;return!0}function gb(a,b,c,d){for(var e=-1,f=a.length,g=d,h=g;++e<f;){var i=a[e],j=+b(i);c(j,g)&&(g=j,h=i)}return h}function hb(a,b){for(var c=-1,d=a.length,e=-1,f=[];++c<d;){var g=a[c];b(g,c,a)&&(f[++e]=g)}return f}function ib(a,b){for(var c=-1,d=a.length,e=Of(d);++c<d;)e[c]=b(a[c],c,a);return e}function jb(a,b){for(var c=-1,d=b.length,e=a.length;++c<d;)a[e+c]=b[c];return a}function kb(a,b,c,d){var e=-1,f=a.length;for(d&&f&&(c=a[++e]);++e<f;)c=b(c,a[e],e,a);return c}function lb(a,b,c,d){var e=a.length;for(d&&e&&(c=a[--e]);e--;)c=b(c,a[e],e,a);return c}function mb(a,b){for(var c=-1,d=a.length;++c<d;)if(b(a[c],c,a))return!0;return!1}function nb(a,b){for(var c=a.length,d=0;c--;)d+=+b(a[c])||0;return d}function ob(a,b){return a===x?b:a}function pb(a,b,c,d){return a!==x&&ag.call(d,c)?a:b}function qb(a,b,c){for(var d=-1,e=Oh(b),f=e.length;++d<f;){var g=e[d],h=a[g],i=c(h,b[g],g,a,b);(i===i?i===h:h!==h)&&(h!==x||g in a)||(a[g]=i)}return a}function rb(a,b){return null==b?a:tb(b,Oh(b),a)}function sb(a,b){for(var c=-1,d=null==a,e=!d&&Yc(a),f=e?a.length:0,g=b.length,h=Of(g);++c<g;){var i=b[c];e?h[c]=Zc(i,f)?a[i]:x:h[c]=d?x:a[i]}return h}function tb(a,b,c){c||(c={});for(var d=-1,e=b.length;++d<e;){var f=b[d];c[f]=a[f]}return c}function ub(a,b,c){var d=typeof a;return"function"==d?b===x?a:fc(a,b,c):null==a?Bf:"object"==d?Nb(a):b===x?Hf(a):Ob(a,b)}function vb(a,b,c,d,e,f,g){var h;if(c&&(h=e?c(a,d,e):c(a)),h!==x)return h;if(!He(a))return a;var i=Dh(a);if(i){if(h=Uc(a),!b)return cb(a,h)}else{var j=cg.call(a),k=j==W;if(j!=Z&&j!=R&&(!k||e))return Pa[j]?Wc(a,j,b):e?a:{};if(h=Vc(k?{}:a),!b)return rb(h,a)}f||(f=[]),g||(g=[]);for(var l=f.length;l--;)if(f[l]==a)return g[l];return f.push(a),g.push(h),(i?db:Fb)(a,function(d,e){h[e]=vb(d,b,c,e,a,f,g)}),h}function wb(a,b,c){if("function"!=typeof a)throw new Xf(P);return lg(function(){a.apply(x,c)},b)}function xb(a,b){var c=a?a.length:0,e=[];if(!c)return e;var f=-1,g=Qc(),h=g===d,i=h&&b.length>=M?oc(b):null,j=b.length;i&&(g=Za,h=!1,b=i);a:for(;++f<c;){var k=a[f];if(h&&k===k){for(var l=j;l--;)if(b[l]===k)continue a;e.push(k)}else g(b,k,0)<0&&e.push(k)}return e}function yb(a,b){var c=!0;return Kg(a,function(a,d,e){return c=!!b(a,d,e)}),c}function zb(a,b,c,d){var e=d,f=e;return Kg(a,function(a,g,h){var i=+b(a,g,h);(c(i,e)||i===d&&i===f)&&(e=i,f=a)}),f}function Ab(a,b,c,d){var e=a.length;for(c=null==c?0:+c||0,0>c&&(c=-c>e?0:e+c),d=d===x||d>e?e:+d||0,0>d&&(d+=e),e=c>d?0:d>>>0,c>>>=0;e>c;)a[c++]=b;return a}function Bb(a,b){var c=[];return Kg(a,function(a,d,e){b(a,d,e)&&c.push(a)}),c}function Cb(a,b,c,d){var e;return c(a,function(a,c,f){return b(a,c,f)?(e=d?c:a,!1):void 0}),e}function Db(a,b,c,d){d||(d=[]);for(var e=-1,f=a.length;++e<f;){var g=a[e];p(g)&&Yc(g)&&(c||Dh(g)||ye(g))?b?Db(g,b,c,d):jb(d,g):c||(d[d.length]=g)}return d}function Eb(a,b){return Mg(a,b,_e)}function Fb(a,b){return Mg(a,b,Oh)}function Gb(a,b){return Ng(a,b,Oh)}function Hb(a,b){for(var c=-1,d=b.length,e=-1,f=[];++c<d;){var g=b[c];Ge(a[g])&&(f[++e]=g)}return f}function Ib(a,b,c){if(null!=a){c!==x&&c in kd(a)&&(b=[c]);for(var d=0,e=b.length;null!=a&&e>d;)a=a[b[d++]];return d&&d==e?a:x}}function Jb(a,b,c,d,e,f){return a===b?!0:null==a||null==b||!He(a)&&!p(b)?a!==a&&b!==b:Kb(a,b,Jb,c,d,e,f)}function Kb(a,b,c,d,e,f,g){var h=Dh(a),i=Dh(b),j=S,k=S;h||(j=cg.call(a),j==R?j=Z:j!=Z&&(h=Qe(a))),i||(k=cg.call(b),k==R?k=Z:k!=Z&&(i=Qe(b)));var l=j==Z,m=k==Z,n=j==k;if(n&&!h&&!l)return Mc(a,b,j);if(!e){var o=l&&ag.call(a,"__wrapped__"),p=m&&ag.call(b,"__wrapped__");if(o||p)return c(o?a.value():a,p?b.value():b,d,e,f,g)}if(!n)return!1;f||(f=[]),g||(g=[]);for(var q=f.length;q--;)if(f[q]==a)return g[q]==b;f.push(a),g.push(b);var r=(h?Lc:Nc)(a,b,c,d,e,f,g);return f.pop(),g.pop(),r}function Lb(a,b,c){var d=b.length,e=d,f=!c;if(null==a)return!e;for(a=kd(a);d--;){var g=b[d];if(f&&g[2]?g[1]!==a[g[0]]:!(g[0]in a))return!1}for(;++d<e;){g=b[d];var h=g[0],i=a[h],j=g[1];if(f&&g[2]){if(i===x&&!(h in a))return!1}else{var k=c?c(i,j,h):x;if(!(k===x?Jb(j,i,c,!0):k))return!1}}return!0}function Mb(a,b){var c=-1,d=Yc(a)?Of(a.length):[];return Kg(a,function(a,e,f){d[++c]=b(a,e,f)}),d}function Nb(a){var b=Rc(a);if(1==b.length&&b[0][2]){var c=b[0][0],d=b[0][1];return function(a){return null==a?!1:a[c]===d&&(d!==x||c in kd(a))}}return function(a){return Lb(a,b)}}function Ob(a,b){var c=Dh(a),d=_c(a)&&cd(b),e=a+"";return a=ld(a),function(f){if(null==f)return!1;var g=e;if(f=kd(f),(c||!d)&&!(g in f)){if(f=1==a.length?f:Ib(f,Wb(a,0,-1)),null==f)return!1;g=zd(a),f=kd(f)}return f[g]===b?b!==x||g in f:Jb(b,f[g],x,!0)}}function Pb(a,b,c,d,e){if(!He(a))return a;var f=Yc(b)&&(Dh(b)||Qe(b)),g=f?x:Oh(b);return db(g||b,function(h,i){if(g&&(i=h,h=b[i]),p(h))d||(d=[]),e||(e=[]),Qb(a,b,i,Pb,c,d,e);else{var j=a[i],k=c?c(j,h,i,a,b):x,l=k===x;l&&(k=h),k===x&&(!f||i in a)||!l&&(k===k?k===j:j!==j)||(a[i]=k)}}),a}function Qb(a,b,c,d,e,f,g){for(var h=f.length,i=b[c];h--;)if(f[h]==i)return void(a[c]=g[h]);var j=a[c],k=e?e(j,i,c,a,b):x,l=k===x;l&&(k=i,Yc(i)&&(Dh(i)||Qe(i))?k=Dh(j)?j:Yc(j)?cb(j):[]:Ne(i)||ye(i)?k=ye(j)?Ve(j):Ne(j)?j:{}:l=!1),f.push(i),g.push(k),l?a[c]=d(k,i,e,f,g):(k===k?k!==j:j===j)&&(a[c]=k)}function Rb(a){return function(b){return null==b?x:b[a]}}function Sb(a){var b=a+"";return a=ld(a),function(c){return Ib(c,a,b)}}function Tb(a,b){for(var c=a?b.length:0;c--;){var d=b[c];if(d!=e&&Zc(d)){var e=d;mg.call(a,d,1)}}return a}function Ub(a,b){return a+rg(zg()*(b-a+1))}function Vb(a,b,c,d,e){return e(a,function(a,e,f){c=d?(d=!1,a):b(c,a,e,f)}),c}function Wb(a,b,c){var d=-1,e=a.length;b=null==b?0:+b||0,0>b&&(b=-b>e?0:e+b),c=c===x||c>e?e:+c||0,0>c&&(c+=e),e=b>c?0:c-b>>>0,b>>>=0;for(var f=Of(e);++d<e;)f[d]=a[d+b];return f}function Xb(a,b){var c;return Kg(a,function(a,d,e){return c=b(a,d,e),!c}),!!c}function Yb(a,b){var c=a.length;for(a.sort(b);c--;)a[c]=a[c].value;return a}function Zb(a,b,c){var d=Oc(),e=-1;b=ib(b,function(a){return d(a)});var f=Mb(a,function(a){var c=ib(b,function(b){return b(a)});return{criteria:c,index:++e,value:a}});return Yb(f,function(a,b){return j(a,b,c)})}function $b(a,b){var c=0;return Kg(a,function(a,d,e){c+=+b(a,d,e)||0}),c}function _b(a,b){var c=-1,e=Qc(),f=a.length,g=e===d,h=g&&f>=M,i=h?oc():null,j=[];i?(e=Za,g=!1):(h=!1,i=b?[]:j);a:for(;++c<f;){var k=a[c],l=b?b(k,c,a):k;if(g&&k===k){for(var m=i.length;m--;)if(i[m]===l)continue a;b&&i.push(l),j.push(k)}else e(i,l,0)<0&&((b||h)&&i.push(l),j.push(k))}return j}function ac(a,b){for(var c=-1,d=b.length,e=Of(d);++c<d;)e[c]=a[b[c]];return e}function bc(a,b,c,d){for(var e=a.length,f=d?e:-1;(d?f--:++f<e)&&b(a[f],f,a););return c?Wb(a,d?0:f,d?f+1:e):Wb(a,d?f+1:0,d?e:f)}function cc(a,b){var c=a;c instanceof ba&&(c=c.value());for(var d=-1,e=b.length;++d<e;){var f=b[d];c=f.func.apply(f.thisArg,jb([c],f.args))}return c}function dc(a,b,c){var d=0,e=a?a.length:d;if("number"==typeof b&&b===b&&Eg>=e){for(;e>d;){var f=d+e>>>1,g=a[f];(c?b>=g:b>g)&&null!==g?d=f+1:e=f}return e}return ec(a,b,Bf,c)}function ec(a,b,c,d){b=c(b);for(var e=0,f=a?a.length:0,g=b!==b,h=null===b,i=b===x;f>e;){var j=rg((e+f)/2),k=c(a[j]),l=k!==x,m=k===k;if(g)var n=m||d;else n=h?m&&l&&(d||null!=k):i?m&&(d||l):null==k?!1:d?b>=k:b>k;n?e=j+1:f=j}return wg(f,Dg)}function fc(a,b,c){if("function"!=typeof a)return Bf;if(b===x)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 3:return function(c,d,e){return a.call(b,c,d,e)};case 4:return function(c,d,e,f){return a.call(b,c,d,e,f)};case 5:return function(c,d,e,f,g){return a.call(b,c,d,e,f,g)}}return function(){return a.apply(b,arguments)}}function gc(a){var b=new fg(a.byteLength),c=new ng(b);return c.set(new ng(a)),b}function hc(a,b,c){for(var d=c.length,e=-1,f=vg(a.length-d,0),g=-1,h=b.length,i=Of(h+f);++g<h;)i[g]=b[g];for(;++e<d;)i[c[e]]=a[e];for(;f--;)i[g++]=a[e++];return i}function ic(a,b,c){for(var d=-1,e=c.length,f=-1,g=vg(a.length-e,0),h=-1,i=b.length,j=Of(g+i);++f<g;)j[f]=a[f];for(var k=f;++h<i;)j[k+h]=b[h];for(;++d<e;)j[k+c[d]]=a[f++];return j}function jc(a,b){return function(c,d,e){var f=b?b():{};if(d=Oc(d,e,3),Dh(c))for(var g=-1,h=c.length;++g<h;){var i=c[g];a(f,i,d(i,g,c),c)}else Kg(c,function(b,c,e){a(f,b,d(b,c,e),e)});return f}}function kc(a){return qe(function(b,c){var d=-1,e=null==b?0:c.length,f=e>2?c[e-2]:x,g=e>2?c[2]:x,h=e>1?c[e-1]:x;for("function"==typeof f?(f=fc(f,h,5),e-=2):(f="function"==typeof h?h:x,e-=f?1:0),g&&$c(c[0],c[1],g)&&(f=3>e?x:f,e=1);++d<e;){var i=c[d];i&&a(b,i,f)}return b})}function lc(a,b){return function(c,d){var e=c?Qg(c):0;if(!bd(e))return a(c,d);for(var f=b?e:-1,g=kd(c);(b?f--:++f<e)&&d(g[f],f,g)!==!1;);return c}}function mc(a){return function(b,c,d){for(var e=kd(b),f=d(b),g=f.length,h=a?g:-1;a?h--:++h<g;){var i=f[h];if(c(e[i],i,e)===!1)break}return b}}function nc(a,b){function c(){var e=this&&this!==ab&&this instanceof c?d:a;return e.apply(b,arguments)}var d=qc(a);return c}function oc(a){return qg&&kg?new Ya(a):null}function pc(a){return function(b){for(var c=-1,d=yf(kf(b)),e=d.length,f="";++c<e;)f=a(f,d[c],c);return f}}function qc(a){return function(){var b=arguments;switch(b.length){case 0:return new a;case 1:return new a(b[0]);case 2:return new a(b[0],b[1]);case 3:return new a(b[0],b[1],b[2]);case 4:return new a(b[0],b[1],b[2],b[3]);case 5:return new a(b[0],b[1],b[2],b[3],b[4]);case 6:return new a(b[0],b[1],b[2],b[3],b[4],b[5]);case 7:return new a(b[0],b[1],b[2],b[3],b[4],b[5],b[6])}var c=Jg(a.prototype),d=a.apply(c,b);return He(d)?d:c}}function rc(a){function b(c,d,e){e&&$c(c,d,e)&&(d=x);var f=Kc(c,a,x,x,x,x,x,d);return f.placeholder=b.placeholder,f}return b}function sc(a,b){return qe(function(c){var d=c[0];return null==d?d:(c.push(b),a.apply(x,c))})}function tc(a,b){return function(c,d,e){if(e&&$c(c,d,e)&&(d=x),d=Oc(d,e,3),1==d.length){c=Dh(c)?c:jd(c);var f=gb(c,d,a,b);if(!c.length||f!==b)return f}return zb(c,d,a,b)}}function uc(a,b){return function(d,e,f){if(e=Oc(e,f,3),Dh(d)){var g=c(d,e,b);return g>-1?d[g]:x}return Cb(d,e,a)}}function vc(a){return function(b,d,e){return b&&b.length?(d=Oc(d,e,3),c(b,d,a)):-1}}function wc(a){return function(b,c,d){return c=Oc(c,d,3),Cb(b,c,a,!0)}}function xc(a){return function(){for(var b,c=arguments.length,d=a?c:-1,e=0,f=Of(c);a?d--:++d<c;){var g=f[e++]=arguments[d];if("function"!=typeof g)throw new Xf(P);!b&&_.prototype.thru&&"wrapper"==Pc(g)&&(b=new _([],!0))}for(d=b?-1:c;++d<c;){g=f[d];var h=Pc(g),i="wrapper"==h?Pg(g):x;b=i&&ad(i[0])&&i[1]==(G|C|E|H)&&!i[4].length&&1==i[9]?b[Pc(i[0])].apply(b,i[3]):1==g.length&&ad(g)?b[h]():b.thru(g)}return function(){var a=arguments,d=a[0];if(b&&1==a.length&&Dh(d)&&d.length>=M)return b.plant(d).value();for(var e=0,g=c?f[e].apply(this,a):d;++e<c;)g=f[e].call(this,g);return g}}}function yc(a,b){return function(c,d,e){return"function"==typeof d&&e===x&&Dh(c)?a(c,d):b(c,fc(d,e,3))}}function zc(a){return function(b,c,d){return("function"!=typeof c||d!==x)&&(c=fc(c,d,3)),a(b,c,_e)}}function Ac(a){return function(b,c,d){return("function"!=typeof c||d!==x)&&(c=fc(c,d,3)),a(b,c)}}function Bc(a){return function(b,c,d){var e={};return c=Oc(c,d,3),Fb(b,function(b,d,f){var g=c(b,d,f);d=a?g:d,b=a?b:g,e[d]=b}),e}}function Cc(a){return function(b,c,d){return b=f(b),(a?b:"")+Gc(b,c,d)+(a?"":b)}}function Dc(a){var b=qe(function(c,d){var e=r(d,b.placeholder);return Kc(c,a,x,d,e)});return b}function Ec(a,b){return function(c,d,e,f){var g=arguments.length<3;return"function"==typeof d&&f===x&&Dh(c)?a(c,d,e,g):Vb(c,Oc(d,f,4),e,g,b)}}function Fc(a,b,c,d,e,f,g,h,i,j){function k(){for(var t=arguments.length,u=t,v=Of(t);u--;)v[u]=arguments[u];if(d&&(v=hc(v,d,e)),f&&(v=ic(v,f,g)),o||q){var w=k.placeholder,y=r(v,w);if(t-=y.length,j>t){var B=h?cb(h):x,C=vg(j-t,0),D=o?y:x,G=o?x:y,H=o?v:x,I=o?x:v;b|=o?E:F,b&=~(o?F:E),p||(b&=~(z|A));var J=[a,b,c,H,D,I,G,B,i,C],K=Fc.apply(x,J);return ad(a)&&Rg(K,J),K.placeholder=w,K}}var L=m?c:this,M=n?L[a]:a;return h&&(v=hd(v,h)),l&&i<v.length&&(v.length=i),this&&this!==ab&&this instanceof k&&(M=s||qc(a)),M.apply(L,v)}var l=b&G,m=b&z,n=b&A,o=b&C,p=b&B,q=b&D,s=n?x:qc(a);return k}function Gc(a,b,c){var d=a.length;if(b=+b,d>=b||!tg(b))return"";var e=b-d;return c=null==c?" ":c+"",qf(c,pg(e/c.length)).slice(0,e)}function Hc(a,b,c,d){function e(){for(var b=-1,h=arguments.length,i=-1,j=d.length,k=Of(j+h);++i<j;)k[i]=d[i];for(;h--;)k[i++]=arguments[++b];var l=this&&this!==ab&&this instanceof e?g:a;return l.apply(f?c:this,k)}var f=b&z,g=qc(a);return e}function Ic(a){var b=Sf[a];return function(a,c){return c=c===x?0:+c||0,c?(c=ig(10,c),b(a*c)/c):b(a)}}function Jc(a){return function(b,c,d,e){var f=Oc(d);return null==d&&f===ub?dc(b,c,a):ec(b,c,f(d,e,1),a)}}function Kc(a,b,c,d,e,f,g,h){var i=b&A;if(!i&&"function"!=typeof a)throw new Xf(P);var j=d?d.length:0;if(j||(b&=~(E|F),d=e=x),j-=e?e.length:0,b&F){var k=d,l=e;d=e=x}var m=i?x:Pg(a),n=[a,b,c,d,e,k,l,f,g,h];if(m&&(dd(n,m),b=n[1],h=n[9]),n[9]=null==h?i?0:a.length:vg(h-j,0)||0,b==z)var o=nc(n[0],n[2]);else o=b!=E&&b!=(z|E)||n[4].length?Fc.apply(x,n):Hc.apply(x,n);var p=m?Og:Rg;return p(o,n)}function Lc(a,b,c,d,e,f,g){var h=-1,i=a.length,j=b.length;if(i!=j&&!(e&&j>i))return!1;for(;++h<i;){var k=a[h],l=b[h],m=d?d(e?l:k,e?k:l,h):x;if(m!==x){if(m)continue;return!1}if(e){if(!mb(b,function(a){return k===a||c(k,a,d,e,f,g)}))return!1}else if(k!==l&&!c(k,l,d,e,f,g))return!1}return!0}function Mc(a,b,c){switch(c){case T:case U:return+a==+b;case V:return a.name==b.name&&a.message==b.message;case Y:return a!=+a?b!=+b:a==+b;case $:case aa:return a==b+""}return!1}function Nc(a,b,c,d,e,f,g){var h=Oh(a),i=h.length,j=Oh(b),k=j.length;if(i!=k&&!e)return!1;for(var l=i;l--;){var m=h[l];if(!(e?m in b:ag.call(b,m)))return!1}for(var n=e;++l<i;){m=h[l];var o=a[m],p=b[m],q=d?d(e?p:o,e?o:p,m):x;if(!(q===x?c(o,p,d,e,f,g):q))return!1;n||(n="constructor"==m)}if(!n){var r=a.constructor,s=b.constructor;if(r!=s&&"constructor"in a&&"constructor"in b&&!("function"==typeof r&&r instanceof r&&"function"==typeof s&&s instanceof s))return!1}return!0}function Oc(a,b,c){var d=q.callback||zf;return d=d===zf?ub:d,c?d(a,b,c):d}function Pc(a){for(var b=a.name+"",c=Hg[b],d=c?c.length:0;d--;){var e=c[d],f=e.func;if(null==f||f==a)return e.name}return b}function Qc(a,b,c){var e=q.indexOf||xd;return e=e===xd?d:e,a?e(a,b,c):e}function Rc(a){for(var b=af(a),c=b.length;c--;)b[c][2]=cd(b[c][1]);return b}function Sc(a,b){var c=null==a?x:a[b];return Ke(c)?c:x}function Tc(a,b,c){for(var d=-1,e=c.length;++d<e;){var f=c[d],g=f.size;switch(f.type){case"drop":a+=g;break;case"dropRight":b-=g;break;case"take":b=wg(b,a+g);break;case"takeRight":a=vg(a,b-g)}}return{start:a,end:b}}function Uc(a){var b=a.length,c=new a.constructor(b);return b&&"string"==typeof a[0]&&ag.call(a,"index")&&(c.index=a.index,c.input=a.input),c}function Vc(a){var b=a.constructor;return"function"==typeof b&&b instanceof b||(b=Uf),new b}function Wc(a,b,c){var d=a.constructor;switch(b){case ca:return gc(a);case T:case U:return new d(+a);case da:case ea:case fa:case ga:case ha:case ia:case ja:case ka:case la:var e=a.buffer;return new d(c?gc(e):e,a.byteOffset,a.length);case Y:case aa:return new d(a);case $:var f=new d(a.source,Ea.exec(a));f.lastIndex=a.lastIndex}return f}function Xc(a,b,c){null==a||_c(b,a)||(b=ld(b),a=1==b.length?a:Ib(a,Wb(b,0,-1)),b=zd(b));var d=null==a?a:a[b];return null==d?x:d.apply(a,c)}function Yc(a){return null!=a&&bd(Qg(a))}function Zc(a,b){return a="number"==typeof a||Ha.test(a)?+a:-1,b=null==b?Fg:b,a>-1&&a%1==0&&b>a}function $c(a,b,c){if(!He(c))return!1;var d=typeof b;if("number"==d?Yc(c)&&Zc(b,c.length):"string"==d&&b in c){var e=c[b];return a===a?a===e:e!==e}return!1}function _c(a,b){var c=typeof a;if("string"==c&&xa.test(a)||"number"==c)return!0;if(Dh(a))return!1;var d=!wa.test(a);return d||null!=b&&a in kd(b)}function ad(a){var b=Pc(a),c=q[b];if("function"!=typeof c||!(b in ba.prototype))return!1;if(a===c)return!0;var d=Pg(c);return!!d&&a===d[0]}function bd(a){return"number"==typeof a&&a>-1&&a%1==0&&Fg>=a}function cd(a){return a===a&&!He(a)}function dd(a,b){var c=a[1],d=b[1],e=c|d,f=G>e,g=d==G&&c==C||d==G&&c==H&&a[7].length<=b[8]||d==(G|H)&&c==C;if(!f&&!g)return a;d&z&&(a[2]=b[2],e|=c&z?0:B);var h=b[3];if(h){var i=a[3];a[3]=i?hc(i,h,b[4]):cb(h),a[4]=i?r(a[3],Q):cb(b[4])}return h=b[5],h&&(i=a[5],a[5]=i?ic(i,h,b[6]):cb(h),a[6]=i?r(a[5],Q):cb(b[6])),h=b[7],h&&(a[7]=cb(h)),d&G&&(a[8]=null==a[8]?b[8]:wg(a[8],b[8])),null==a[9]&&(a[9]=b[9]),a[0]=b[0],a[1]=e,a}function ed(a,b){return a===x?b:Eh(a,b,ed)}function fd(a,b){a=kd(a);for(var c=-1,d=b.length,e={};++c<d;){var f=b[c];f in a&&(e[f]=a[f])}return e}function gd(a,b){var c={};return Eb(a,function(a,d,e){b(a,d,e)&&(c[d]=a)}),c}function hd(a,b){for(var c=a.length,d=wg(b.length,c),e=cb(a);d--;){var f=b[d];a[d]=Zc(f,c)?e[f]:x}return a}function id(a){for(var b=_e(a),c=b.length,d=c&&a.length,e=!!d&&bd(d)&&(Dh(a)||ye(a)),f=-1,g=[];++f<c;){var h=b[f];(e&&Zc(h,d)||ag.call(a,h))&&g.push(h)}return g}function jd(a){return null==a?[]:Yc(a)?He(a)?a:Uf(a):ef(a)}function kd(a){return He(a)?a:Uf(a)}function ld(a){if(Dh(a))return a;var b=[];return f(a).replace(ya,function(a,c,d,e){b.push(d?e.replace(Ca,"$1"):c||a)}),b}function md(a){return a instanceof ba?a.clone():new _(a.__wrapped__,a.__chain__,cb(a.__actions__))}function nd(a,b,c){b=(c?$c(a,b,c):null==b)?1:vg(rg(b)||1,1);for(var d=0,e=a?a.length:0,f=-1,g=Of(pg(e/b));e>d;)g[++f]=Wb(a,d,d+=b);return g}function od(a){for(var b=-1,c=a?a.length:0,d=-1,e=[];++b<c;){var f=a[b];f&&(e[++d]=f)}return e}function pd(a,b,c){var d=a?a.length:0;return d?((c?$c(a,b,c):null==b)&&(b=1),Wb(a,0>b?0:b)):[]}function qd(a,b,c){var d=a?a.length:0;return d?((c?$c(a,b,c):null==b)&&(b=1),b=d-(+b||0),Wb(a,0,0>b?0:b)):[]}function rd(a,b,c){return a&&a.length?bc(a,Oc(b,c,3),!0,!0):[]}function sd(a,b,c){return a&&a.length?bc(a,Oc(b,c,3),!0):[]}function td(a,b,c,d){var e=a?a.length:0;return e?(c&&"number"!=typeof c&&$c(a,b,c)&&(c=0,d=e),Ab(a,b,c,d)):[]}function ud(a){return a?a[0]:x}function vd(a,b,c){var d=a?a.length:0;return c&&$c(a,b,c)&&(b=!1),d?Db(a,b):[]}function wd(a){var b=a?a.length:0;return b?Db(a,!0):[]}function xd(a,b,c){var e=a?a.length:0;if(!e)return-1;if("number"==typeof c)c=0>c?vg(e+c,0):c;else if(c){var f=dc(a,b);return e>f&&(b===b?b===a[f]:a[f]!==a[f])?f:-1}return d(a,b,c||0)}function yd(a){return qd(a,1)}function zd(a){var b=a?a.length:0;return b?a[b-1]:x}function Ad(a,b,c){var d=a?a.length:0;if(!d)return-1;var e=d;if("number"==typeof c)e=(0>c?vg(d+c,0):wg(c||0,d-1))+1;else if(c){e=dc(a,b,!0)-1;var f=a[e];return(b===b?b===f:f!==f)?e:-1}if(b!==b)return o(a,e,!0);for(;e--;)if(a[e]===b)return e;return-1}function Bd(){var a=arguments,b=a[0];if(!b||!b.length)return b;for(var c=0,d=Qc(),e=a.length;++c<e;)for(var f=0,g=a[c];(f=d(b,g,f))>-1;)mg.call(b,f,1);return b}function Cd(a,b,c){var d=[];if(!a||!a.length)return d;var e=-1,f=[],g=a.length;for(b=Oc(b,c,3);++e<g;){var h=a[e];b(h,e,a)&&(d.push(h),f.push(e))}return Tb(a,f),d}function Dd(a){return pd(a,1)}function Ed(a,b,c){var d=a?a.length:0;return d?(c&&"number"!=typeof c&&$c(a,b,c)&&(b=0,c=d),Wb(a,b,c)):[]}function Fd(a,b,c){var d=a?a.length:0;return d?((c?$c(a,b,c):null==b)&&(b=1),Wb(a,0,0>b?0:b)):[]}function Gd(a,b,c){var d=a?a.length:0;return d?((c?$c(a,b,c):null==b)&&(b=1),b=d-(+b||0),Wb(a,0>b?0:b)):[]}function Hd(a,b,c){return a&&a.length?bc(a,Oc(b,c,3),!1,!0):[]}function Id(a,b,c){return a&&a.length?bc(a,Oc(b,c,3)):[]}function Jd(a,b,c,e){var f=a?a.length:0;if(!f)return[];null!=b&&"boolean"!=typeof b&&(e=c,c=$c(a,b,e)?x:b,b=!1);var g=Oc();return(null!=c||g!==ub)&&(c=g(c,e,3)),b&&Qc()===d?s(a,c):_b(a,c)}function Kd(a){if(!a||!a.length)return[];var b=-1,c=0;a=hb(a,function(a){return Yc(a)?(c=vg(a.length,c),!0):void 0});for(var d=Of(c);++b<c;)d[b]=ib(a,Rb(b));return d}function Ld(a,b,c){var d=a?a.length:0;if(!d)return[];var e=Kd(a);return null==b?e:(b=fc(b,c,4),ib(e,function(a){return kb(a,b,x,!0)}))}function Md(){for(var a=-1,b=arguments.length;++a<b;){var c=arguments[a];if(Yc(c))var d=d?jb(xb(d,c),xb(c,d)):c}return d?_b(d):[]}function Nd(a,b){var c=-1,d=a?a.length:0,e={};for(!d||b||Dh(a[0])||(b=[]);++c<d;){var f=a[c];b?e[f]=b[c]:f&&(e[f[0]]=f[1])}return e}function Od(a){var b=q(a);return b.__chain__=!0,b}function Pd(a,b,c){return b.call(c,a),a}function Qd(a,b,c){return b.call(c,a)}function Rd(){return Od(this)}function Sd(){return new _(this.value(),this.__chain__)}function Td(a){for(var b,c=this;c instanceof X;){var d=md(c);b?e.__wrapped__=d:b=d;var e=d;c=c.__wrapped__}return e.__wrapped__=a,b}function Ud(){var a=this.__wrapped__,b=function(a){return a.reverse()};if(a instanceof ba){var c=a;return this.__actions__.length&&(c=new ba(this)),c=c.reverse(),c.__actions__.push({func:Qd,args:[b],thisArg:x}),new _(c,this.__chain__)}return this.thru(b)}function Vd(){return this.value()+""}function Wd(){return cc(this.__wrapped__,this.__actions__)}function Xd(a,b,c){var d=Dh(a)?fb:yb;return c&&$c(a,b,c)&&(b=x),("function"!=typeof b||c!==x)&&(b=Oc(b,c,3)),d(a,b)}function Yd(a,b,c){var d=Dh(a)?hb:Bb;return b=Oc(b,c,3),d(a,b)}function Zd(a,b){return eh(a,Nb(b))}function $d(a,b,c,d){var e=a?Qg(a):0;return bd(e)||(a=ef(a),e=a.length),c="number"!=typeof c||d&&$c(b,c,d)?0:0>c?vg(e+c,0):c||0,"string"==typeof a||!Dh(a)&&Pe(a)?e>=c&&a.indexOf(b,c)>-1:!!e&&Qc(a,b,c)>-1}function _d(a,b,c){var d=Dh(a)?ib:Mb;return b=Oc(b,c,3),d(a,b)}function ae(a,b){return _d(a,Hf(b))}function be(a,b,c){var d=Dh(a)?hb:Bb;return b=Oc(b,c,3),d(a,function(a,c,d){return!b(a,c,d)})}function ce(a,b,c){if(c?$c(a,b,c):null==b){a=jd(a);var d=a.length;return d>0?a[Ub(0,d-1)]:x}var e=-1,f=Ue(a),d=f.length,g=d-1;for(b=wg(0>b?0:+b||0,d);++e<b;){var h=Ub(e,g),i=f[h];f[h]=f[e],f[e]=i}return f.length=b,f}function de(a){return ce(a,Bg)}function ee(a){var b=a?Qg(a):0;return bd(b)?b:Oh(a).length}function fe(a,b,c){var d=Dh(a)?mb:Xb;return c&&$c(a,b,c)&&(b=x),("function"!=typeof b||c!==x)&&(b=Oc(b,c,3)),d(a,b)}function ge(a,b,c){if(null==a)return[];c&&$c(a,b,c)&&(b=x);var d=-1;b=Oc(b,c,3);var e=Mb(a,function(a,c,e){return{criteria:b(a,c,e),index:++d,value:a}});return Yb(e,i)}function he(a,b,c,d){return null==a?[]:(d&&$c(b,c,d)&&(c=x),Dh(b)||(b=null==b?[]:[b]),Dh(c)||(c=null==c?[]:[c]),Zb(a,b,c))}function ie(a,b){return Yd(a,Nb(b))}function je(a,b){if("function"!=typeof b){if("function"!=typeof a)throw new Xf(P);var c=a;a=b,b=c}return a=tg(a=+a)?a:0,function(){return--a<1?b.apply(this,arguments):void 0}}function ke(a,b,c){return c&&$c(a,b,c)&&(b=x),b=a&&null==b?a.length:vg(+b||0,0),Kc(a,G,x,x,x,x,b)}function le(a,b){var c;if("function"!=typeof b){if("function"!=typeof a)throw new Xf(P);var d=a;a=b,b=d}return function(){return--a>0&&(c=b.apply(this,arguments)),1>=a&&(b=x),c}}function me(a,b,c){function d(){n&&gg(n),j&&gg(j),p=0,j=n=o=x}function e(b,c){c&&gg(c),j=n=o=x,b&&(p=ph(),k=a.apply(m,i),n||j||(i=m=x))}function f(){var a=b-(ph()-l);0>=a||a>b?e(o,j):n=lg(f,a)}function g(){e(r,n)}function h(){if(i=arguments,l=ph(),m=this,o=r&&(n||!s),q===!1)var c=s&&!n;else{j||s||(p=l);var d=q-(l-p),e=0>=d||d>q;e?(j&&(j=gg(j)),p=l,k=a.apply(m,i)):j||(j=lg(g,d))}return e&&n?n=gg(n):n||b===q||(n=lg(f,b)),c&&(e=!0,k=a.apply(m,i)),!e||n||j||(i=m=x),k}var i,j,k,l,m,n,o,p=0,q=!1,r=!0;if("function"!=typeof a)throw new Xf(P);if(b=0>b?0:+b||0,c===!0){var s=!0;r=!1}else He(c)&&(s=!!c.leading,q="maxWait"in c&&vg(+c.maxWait||0,b),r="trailing"in c?!!c.trailing:r);return h.cancel=d,h}function ne(a,b){if("function"!=typeof a||b&&"function"!=typeof b)throw new Xf(P);var c=function(){var d=arguments,e=b?b.apply(this,d):d[0],f=c.cache;if(f.has(e))return f.get(e);var g=a.apply(this,d);return c.cache=f.set(e,g),g};return c.cache=new ne.Cache,c}function oe(a){if("function"!=typeof a)throw new Xf(P);return function(){return!a.apply(this,arguments)}}function pe(a){return le(2,a)}function qe(a,b){if("function"!=typeof a)throw new Xf(P);return b=vg(b===x?a.length-1:+b||0,0),function(){for(var c=arguments,d=-1,e=vg(c.length-b,0),f=Of(e);++d<e;)f[d]=c[b+d];switch(b){case 0:return a.call(this,f);case 1:return a.call(this,c[0],f);case 2:return a.call(this,c[0],c[1],f)}var g=Of(b+1);for(d=-1;++d<b;)g[d]=c[d];return g[b]=f,a.apply(this,g)}}function re(a){if("function"!=typeof a)throw new Xf(P);return function(b){return a.apply(this,b)}}function se(a,b,c){var d=!0,e=!0;if("function"!=typeof a)throw new Xf(P);return c===!1?d=!1:He(c)&&(d="leading"in c?!!c.leading:d,e="trailing"in c?!!c.trailing:e),me(a,b,{leading:d,maxWait:+b,trailing:e})}function te(a,b){return b=null==b?Bf:b,Kc(b,E,x,[a],[])}function ue(a,b,c,d){return b&&"boolean"!=typeof b&&$c(a,b,c)?b=!1:"function"==typeof b&&(d=c,c=b,b=!1),"function"==typeof c?vb(a,b,fc(c,d,3)):vb(a,b)}function ve(a,b,c){return"function"==typeof b?vb(a,!0,fc(b,c,3)):vb(a,!0)}function we(a,b){return a>b}function xe(a,b){return a>=b}function ye(a){return p(a)&&Yc(a)&&ag.call(a,"callee")&&!jg.call(a,"callee")}function ze(a){return a===!0||a===!1||p(a)&&cg.call(a)==T}function Ae(a){return p(a)&&cg.call(a)==U}function Be(a){return!!a&&1===a.nodeType&&p(a)&&!Ne(a)}function Ce(a){return null==a?!0:Yc(a)&&(Dh(a)||Pe(a)||ye(a)||p(a)&&Ge(a.splice))?!a.length:!Oh(a).length}function De(a,b,c,d){c="function"==typeof c?fc(c,d,3):x;var e=c?c(a,b):x;return e===x?Jb(a,b,c):!!e}function Ee(a){return p(a)&&"string"==typeof a.message&&cg.call(a)==V}function Fe(a){return"number"==typeof a&&tg(a)}function Ge(a){return He(a)&&cg.call(a)==W}function He(a){var b=typeof a;return!!a&&("object"==b||"function"==b)}function Ie(a,b,c,d){return c="function"==typeof c?fc(c,d,3):x,Lb(a,Rc(b),c)}function Je(a){return Me(a)&&a!=+a}function Ke(a){return null==a?!1:Ge(a)?eg.test(_f.call(a)):p(a)&&Ga.test(a)}function Le(a){return null===a}function Me(a){return"number"==typeof a||p(a)&&cg.call(a)==Y}function Ne(a){var b;if(!p(a)||cg.call(a)!=Z||ye(a)||!ag.call(a,"constructor")&&(b=a.constructor,"function"==typeof b&&!(b instanceof b)))return!1;var c;return Eb(a,function(a,b){c=b}),c===x||ag.call(a,c)}function Oe(a){return He(a)&&cg.call(a)==$}function Pe(a){return"string"==typeof a||p(a)&&cg.call(a)==aa}function Qe(a){return p(a)&&bd(a.length)&&!!Oa[cg.call(a)]}function Re(a){return a===x}function Se(a,b){return b>a}function Te(a,b){return b>=a}function Ue(a){var b=a?Qg(a):0;return bd(b)?b?cb(a):[]:ef(a)}function Ve(a){return tb(a,_e(a))}function We(a,b,c){var d=Jg(a);return c&&$c(a,b,c)&&(b=x),b?rb(d,b):d}function Xe(a){return Hb(a,_e(a))}function Ye(a,b,c){var d=null==a?x:Ib(a,ld(b),b+"");return d===x?c:d}function Ze(a,b){if(null==a)return!1;var c=ag.call(a,b);if(!c&&!_c(b)){if(b=ld(b),a=1==b.length?a:Ib(a,Wb(b,0,-1)),null==a)return!1;b=zd(b),c=ag.call(a,b)}return c||bd(a.length)&&Zc(b,a.length)&&(Dh(a)||ye(a))}function $e(a,b,c){c&&$c(a,b,c)&&(b=x);for(var d=-1,e=Oh(a),f=e.length,g={};++d<f;){var h=e[d],i=a[h];b?ag.call(g,i)?g[i].push(h):g[i]=[h]:g[i]=h}return g}function _e(a){if(null==a)return[];He(a)||(a=Uf(a));var b=a.length;b=b&&bd(b)&&(Dh(a)||ye(a))&&b||0;for(var c=a.constructor,d=-1,e="function"==typeof c&&c.prototype===a,f=Of(b),g=b>0;++d<b;)f[d]=d+"";for(var h in a)g&&Zc(h,b)||"constructor"==h&&(e||!ag.call(a,h))||f.push(h);return f}function af(a){a=kd(a);for(var b=-1,c=Oh(a),d=c.length,e=Of(d);++b<d;){var f=c[b];e[b]=[f,a[f]]}return e}function bf(a,b,c){var d=null==a?x:a[b];return d===x&&(null==a||_c(b,a)||(b=ld(b),a=1==b.length?a:Ib(a,Wb(b,0,-1)),d=null==a?x:a[zd(b)]),d=d===x?c:d),Ge(d)?d.call(a):d}function cf(a,b,c){if(null==a)return a;var d=b+"";b=null!=a[d]||_c(b,a)?[d]:ld(b);for(var e=-1,f=b.length,g=f-1,h=a;null!=h&&++e<f;){var i=b[e];He(h)&&(e==g?h[i]=c:null==h[i]&&(h[i]=Zc(b[e+1])?[]:{})),h=h[i]}return a}function df(a,b,c,d){var e=Dh(a)||Qe(a);if(b=Oc(b,d,4),null==c)if(e||He(a)){var f=a.constructor;c=e?Dh(a)?new f:[]:Jg(Ge(f)?f.prototype:x)}else c={};return(e?db:Fb)(a,function(a,d,e){return b(c,a,d,e)}),c}function ef(a){return ac(a,Oh(a))}function ff(a){return ac(a,_e(a))}function gf(a,b,c){return b=+b||0,c===x?(c=b,b=0):c=+c||0,a>=wg(b,c)&&a<vg(b,c)}function hf(a,b,c){c&&$c(a,b,c)&&(b=c=x);var d=null==a,e=null==b;if(null==c&&(e&&"boolean"==typeof a?(c=a,a=1):"boolean"==typeof b&&(c=b,e=!0)),d&&e&&(b=1,e=!1),a=+a||0,e?(b=a,a=0):b=+b||0,c||a%1||b%1){var f=zg();return wg(a+f*(b-a+hg("1e-"+((f+"").length-1))),b)}return Ub(a,b)}function jf(a){return a=f(a),
+a&&a.charAt(0).toUpperCase()+a.slice(1)}function kf(a){return a=f(a),a&&a.replace(Ia,k).replace(Ba,"")}function lf(a,b,c){a=f(a),b+="";var d=a.length;return c=c===x?d:wg(0>c?0:+c||0,d),c-=b.length,c>=0&&a.indexOf(b,c)==c}function mf(a){return a=f(a),a&&sa.test(a)?a.replace(qa,l):a}function nf(a){return a=f(a),a&&Aa.test(a)?a.replace(za,m):a||"(?:)"}function of(a,b,c){a=f(a),b=+b;var d=a.length;if(d>=b||!tg(b))return a;var e=(b-d)/2,g=rg(e),h=pg(e);return c=Gc("",h,c),c.slice(0,g)+a+c}function pf(a,b,c){return(c?$c(a,b,c):null==b)?b=0:b&&(b=+b),a=tf(a),yg(a,b||(Fa.test(a)?16:10))}function qf(a,b){var c="";if(a=f(a),b=+b,1>b||!a||!tg(b))return c;do b%2&&(c+=a),b=rg(b/2),a+=a;while(b);return c}function rf(a,b,c){return a=f(a),c=null==c?0:wg(0>c?0:+c||0,a.length),a.lastIndexOf(b,c)==c}function sf(a,b,c){var d=q.templateSettings;c&&$c(a,b,c)&&(b=c=x),a=f(a),b=qb(rb({},c||b),d,pb);var e=qb(rb({},b.imports),d.imports,pb),g=Oh(e),h=ac(e,g),i,j,k=0,l=b.interpolate||Ja,m="__p += '",o=Vf((b.escape||Ja).source+"|"+l.source+"|"+(l===va?Da:Ja).source+"|"+(b.evaluate||Ja).source+"|$","g"),p="//# sourceURL="+("sourceURL"in b?b.sourceURL:"lodash.templateSources["+ ++Na+"]")+"\n";a.replace(o,function(b,c,d,e,f,g){return d||(d=e),m+=a.slice(k,g).replace(Ka,n),c&&(i=!0,m+="' +\n__e("+c+") +\n'"),f&&(j=!0,m+="';\n"+f+";\n__p += '"),d&&(m+="' +\n((__t = ("+d+")) == null ? '' : __t) +\n'"),k=g+b.length,b}),m+="';\n";var r=b.variable;r||(m="with (obj) {\n"+m+"\n}\n"),m=(j?m.replace(ma,""):m).replace(na,"$1").replace(oa,"$1;"),m="function("+(r||"obj")+") {\n"+(r?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(i?", __e = _.escape":"")+(j?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+m+"return __p\n}";var s=Zh(function(){return Rf(g,p+"return "+m).apply(x,h)});if(s.source=m,Ee(s))throw s;return s}function tf(a,b,c){var d=a;return(a=f(a))?(c?$c(d,b,c):null==b)?a.slice(t(a),u(a)+1):(b+="",a.slice(g(a,b),h(a,b)+1)):a}function uf(a,b,c){var d=a;return a=f(a),a?(c?$c(d,b,c):null==b)?a.slice(t(a)):a.slice(g(a,b+"")):a}function vf(a,b,c){var d=a;return a=f(a),a?(c?$c(d,b,c):null==b)?a.slice(0,u(a)+1):a.slice(0,h(a,b+"")+1):a}function wf(a,b,c){c&&$c(a,b,c)&&(b=x);var d=I,e=J;if(null!=b)if(He(b)){var g="separator"in b?b.separator:g;d="length"in b?+b.length||0:d,e="omission"in b?f(b.omission):e}else d=+b||0;if(a=f(a),d>=a.length)return a;var h=d-e.length;if(1>h)return e;var i=a.slice(0,h);if(null==g)return i+e;if(Oe(g)){if(a.slice(h).search(g)){var j,k,l=a.slice(0,h);for(g.global||(g=Vf(g.source,(Ea.exec(g)||"")+"g")),g.lastIndex=0;j=g.exec(l);)k=j.index;i=i.slice(0,null==k?h:k)}}else if(a.indexOf(g,h)!=h){var m=i.lastIndexOf(g);m>-1&&(i=i.slice(0,m))}return i+e}function xf(a){return a=f(a),a&&ra.test(a)?a.replace(pa,v):a}function yf(a,b,c){return c&&$c(a,b,c)&&(b=x),a=f(a),a.match(b||La)||[]}function zf(a,b,c){return c&&$c(a,b,c)&&(b=x),p(a)?Cf(a):ub(a,b)}function Af(a){return function(){return a}}function Bf(a){return a}function Cf(a){return Nb(vb(a,!0))}function Df(a,b){return Ob(a,vb(b,!0))}function Ef(a,b,c){if(null==c){var d=He(b),e=d?Oh(b):x,f=e&&e.length?Hb(b,e):x;(f?f.length:d)||(f=!1,c=b,b=a,a=this)}f||(f=Hb(b,Oh(b)));var g=!0,h=-1,i=Ge(a),j=f.length;c===!1?g=!1:He(c)&&"chain"in c&&(g=c.chain);for(;++h<j;){var k=f[h],l=b[k];a[k]=l,i&&(a.prototype[k]=function(b){return function(){var c=this.__chain__;if(g||c){var d=a(this.__wrapped__),e=d.__actions__=cb(this.__actions__);return e.push({func:b,args:arguments,thisArg:a}),d.__chain__=c,d}return b.apply(a,jb([this.value()],arguments))}}(l))}return a}function Ff(){return ab._=dg,this}function Gf(){}function Hf(a){return _c(a)?Rb(a):Sb(a)}function If(a){return function(b){return Ib(a,ld(b),b+"")}}function Jf(a,b,c){c&&$c(a,b,c)&&(b=c=x),a=+a||0,c=null==c?1:+c||0,null==b?(b=a,a=0):b=+b||0;for(var d=-1,e=vg(pg((b-a)/(c||1)),0),f=Of(e);++d<e;)f[d]=a,a+=c;return f}function Kf(a,b,c){if(a=rg(a),1>a||!tg(a))return[];var d=-1,e=Of(wg(a,Cg));for(b=fc(b,c,1);++d<a;)Cg>d?e[d]=b(d):b(d);return e}function Lf(a){var b=++bg;return f(a)+b}function Mf(a,b){return(+a||0)+(+b||0)}function Nf(a,b,c){return c&&$c(a,b,c)&&(b=x),b=Oc(b,c,3),1==b.length?nb(Dh(a)?a:jd(a),b):$b(a,b)}a=a?bb.defaults(ab.Object(),a,bb.pick(ab,Ma)):ab;var Of=a.Array,Pf=a.Date,Qf=a.Error,Rf=a.Function,Sf=a.Math,Tf=a.Number,Uf=a.Object,Vf=a.RegExp,Wf=a.String,Xf=a.TypeError,Yf=Of.prototype,Zf=Uf.prototype,$f=Wf.prototype,_f=Rf.prototype.toString,ag=Zf.hasOwnProperty,bg=0,cg=Zf.toString,dg=ab._,eg=Vf("^"+_f.call(ag).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),fg=a.ArrayBuffer,gg=a.clearTimeout,hg=a.parseFloat,ig=Sf.pow,jg=Zf.propertyIsEnumerable,kg=Sc(a,"Set"),lg=a.setTimeout,mg=Yf.splice,ng=a.Uint8Array,og=Sc(a,"WeakMap"),pg=Sf.ceil,qg=Sc(Uf,"create"),rg=Sf.floor,sg=Sc(Of,"isArray"),tg=a.isFinite,ug=Sc(Uf,"keys"),vg=Sf.max,wg=Sf.min,xg=Sc(Pf,"now"),yg=a.parseInt,zg=Sf.random,Ag=Tf.NEGATIVE_INFINITY,Bg=Tf.POSITIVE_INFINITY,Cg=4294967295,Dg=Cg-1,Eg=Cg>>>1,Fg=9007199254740991,Gg=og&&new og,Hg={},Ig=q.support={};q.templateSettings={escape:ta,evaluate:ua,interpolate:va,variable:"",imports:{_:q}};var Jg=function(){function a(){}return function(b){if(He(b)){a.prototype=b;var c=new a;a.prototype=x}return c||{}}}(),Kg=lc(Fb),Lg=lc(Gb,!0),Mg=mc(),Ng=mc(!0),Og=Gg?function(a,b){return Gg.set(a,b),a}:Bf,Pg=Gg?function(a){return Gg.get(a)}:Gf,Qg=Rb("length"),Rg=function(){var a=0,b=0;return function(c,d){var e=ph(),f=L-(e-b);if(b=e,f>0){if(++a>=K)return c}else a=0;return Og(c,d)}}(),Sg=qe(function(a,b){return p(a)&&Yc(a)?xb(a,Db(b,!1,!0)):[]}),Tg=vc(),Ug=vc(!0),Vg=qe(function(a){for(var b=a.length,c=b,e=Of(l),f=Qc(),g=f===d,h=[];c--;){var i=a[c]=Yc(i=a[c])?i:[];e[c]=g&&i.length>=120?oc(c&&i):null}var j=a[0],k=-1,l=j?j.length:0,m=e[0];a:for(;++k<l;)if(i=j[k],(m?Za(m,i):f(h,i,0))<0){for(var c=b;--c;){var n=e[c];if((n?Za(n,i):f(a[c],i,0))<0)continue a}m&&m.push(i),h.push(i)}return h}),Wg=qe(function(a,c){c=Db(c);var d=sb(a,c);return Tb(a,c.sort(b)),d}),Xg=Jc(),Yg=Jc(!0),Zg=qe(function(a){return _b(Db(a,!1,!0))}),$g=qe(function(a,b){return Yc(a)?xb(a,b):[]}),_g=qe(Kd),ah=qe(function(a){var b=a.length,c=b>2?a[b-2]:x,d=b>1?a[b-1]:x;return b>2&&"function"==typeof c?b-=2:(c=b>1&&"function"==typeof d?(--b,d):x,d=x),a.length=b,Ld(a,c,d)}),bh=qe(function(a){return a=Db(a),this.thru(function(b){return _a(Dh(b)?b:[kd(b)],a)})}),ch=qe(function(a,b){return sb(a,Db(b))}),dh=jc(function(a,b,c){ag.call(a,c)?++a[c]:a[c]=1}),eh=uc(Kg),fh=uc(Lg,!0),gh=yc(db,Kg),hh=yc(eb,Lg),ih=jc(function(a,b,c){ag.call(a,c)?a[c].push(b):a[c]=[b]}),jh=jc(function(a,b,c){a[c]=b}),kh=qe(function(a,b,c){var d=-1,e="function"==typeof b,f=_c(b),g=Yc(a)?Of(a.length):[];return Kg(a,function(a){var h=e?b:f&&null!=a?a[b]:x;g[++d]=h?h.apply(a,c):Xc(a,b,c)}),g}),lh=jc(function(a,b,c){a[c?0:1].push(b)},function(){return[[],[]]}),mh=Ec(kb,Kg),nh=Ec(lb,Lg),oh=qe(function(a,b){if(null==a)return[];var c=b[2];return c&&$c(b[0],b[1],c)&&(b.length=1),Zb(a,Db(b),[])}),ph=xg||function(){return(new Pf).getTime()},qh=qe(function(a,b,c){var d=z;if(c.length){var e=r(c,qh.placeholder);d|=E}return Kc(a,d,b,c,e)}),rh=qe(function(a,b){b=b.length?Db(b):Xe(a);for(var c=-1,d=b.length;++c<d;){var e=b[c];a[e]=Kc(a[e],z,a)}return a}),sh=qe(function(a,b,c){var d=z|A;if(c.length){var e=r(c,sh.placeholder);d|=E}return Kc(b,d,a,c,e)}),th=rc(C),uh=rc(D),vh=qe(function(a,b){return wb(a,1,b)}),wh=qe(function(a,b,c){return wb(a,b,c)}),xh=xc(),yh=xc(!0),zh=qe(function(a,b){if(b=Db(b),"function"!=typeof a||!fb(b,e))throw new Xf(P);var c=b.length;return qe(function(d){for(var e=wg(d.length,c);e--;)d[e]=b[e](d[e]);return a.apply(this,d)})}),Ah=Dc(E),Bh=Dc(F),Ch=qe(function(a,b){return Kc(a,H,x,x,x,Db(b))}),Dh=sg||function(a){return p(a)&&bd(a.length)&&cg.call(a)==S},Eh=kc(Pb),Fh=kc(function(a,b,c){return c?qb(a,b,c):rb(a,b)}),Gh=sc(Fh,ob),Hh=sc(Eh,ed),Ih=wc(Fb),Jh=wc(Gb),Kh=zc(Mg),Lh=zc(Ng),Mh=Ac(Fb),Nh=Ac(Gb),Oh=ug?function(a){var b=null==a?x:a.constructor;return"function"==typeof b&&b.prototype===a||"function"!=typeof a&&Yc(a)?id(a):He(a)?ug(a):[]}:id,Ph=Bc(!0),Qh=Bc(),Rh=qe(function(a,b){if(null==a)return{};if("function"!=typeof b[0]){var b=ib(Db(b),Wf);return fd(a,xb(_e(a),b))}var c=fc(b[0],b[1],3);return gd(a,function(a,b,d){return!c(a,b,d)})}),Sh=qe(function(a,b){return null==a?{}:"function"==typeof b[0]?gd(a,fc(b[0],b[1],3)):fd(a,Db(b))}),Th=pc(function(a,b,c){return b=b.toLowerCase(),a+(c?b.charAt(0).toUpperCase()+b.slice(1):b)}),Uh=pc(function(a,b,c){return a+(c?"-":"")+b.toLowerCase()}),Vh=Cc(),Wh=Cc(!0),Xh=pc(function(a,b,c){return a+(c?"_":"")+b.toLowerCase()}),Yh=pc(function(a,b,c){return a+(c?" ":"")+(b.charAt(0).toUpperCase()+b.slice(1))}),Zh=qe(function(a,b){try{return a.apply(x,b)}catch(c){return Ee(c)?c:new Qf(c)}}),$h=qe(function(a,b){return function(c){return Xc(c,a,b)}}),_h=qe(function(a,b){return function(c){return Xc(a,c,b)}}),ai=Ic("ceil"),bi=Ic("floor"),ci=tc(we,Ag),di=tc(Se,Bg),ei=Ic("round");return q.prototype=X.prototype,_.prototype=Jg(X.prototype),_.prototype.constructor=_,ba.prototype=Jg(X.prototype),ba.prototype.constructor=ba,Ta.prototype["delete"]=Ua,Ta.prototype.get=Va,Ta.prototype.has=Wa,Ta.prototype.set=Xa,Ya.prototype.push=$a,ne.Cache=Ta,q.after=je,q.ary=ke,q.assign=Fh,q.at=ch,q.before=le,q.bind=qh,q.bindAll=rh,q.bindKey=sh,q.callback=zf,q.chain=Od,q.chunk=nd,q.compact=od,q.constant=Af,q.countBy=dh,q.create=We,q.curry=th,q.curryRight=uh,q.debounce=me,q.defaults=Gh,q.defaultsDeep=Hh,q.defer=vh,q.delay=wh,q.difference=Sg,q.drop=pd,q.dropRight=qd,q.dropRightWhile=rd,q.dropWhile=sd,q.fill=td,q.filter=Yd,q.flatten=vd,q.flattenDeep=wd,q.flow=xh,q.flowRight=yh,q.forEach=gh,q.forEachRight=hh,q.forIn=Kh,q.forInRight=Lh,q.forOwn=Mh,q.forOwnRight=Nh,q.functions=Xe,q.groupBy=ih,q.indexBy=jh,q.initial=yd,q.intersection=Vg,q.invert=$e,q.invoke=kh,q.keys=Oh,q.keysIn=_e,q.map=_d,q.mapKeys=Ph,q.mapValues=Qh,q.matches=Cf,q.matchesProperty=Df,q.memoize=ne,q.merge=Eh,q.method=$h,q.methodOf=_h,q.mixin=Ef,q.modArgs=zh,q.negate=oe,q.omit=Rh,q.once=pe,q.pairs=af,q.partial=Ah,q.partialRight=Bh,q.partition=lh,q.pick=Sh,q.pluck=ae,q.property=Hf,q.propertyOf=If,q.pull=Bd,q.pullAt=Wg,q.range=Jf,q.rearg=Ch,q.reject=be,q.remove=Cd,q.rest=Dd,q.restParam=qe,q.set=cf,q.shuffle=de,q.slice=Ed,q.sortBy=ge,q.sortByAll=oh,q.sortByOrder=he,q.spread=re,q.take=Fd,q.takeRight=Gd,q.takeRightWhile=Hd,q.takeWhile=Id,q.tap=Pd,q.throttle=se,q.thru=Qd,q.times=Kf,q.toArray=Ue,q.toPlainObject=Ve,q.transform=df,q.union=Zg,q.uniq=Jd,q.unzip=Kd,q.unzipWith=Ld,q.values=ef,q.valuesIn=ff,q.where=ie,q.without=$g,q.wrap=te,q.xor=Md,q.zip=_g,q.zipObject=Nd,q.zipWith=ah,q.backflow=yh,q.collect=_d,q.compose=yh,q.each=gh,q.eachRight=hh,q.extend=Fh,q.iteratee=zf,q.methods=Xe,q.object=Nd,q.select=Yd,q.tail=Dd,q.unique=Jd,Ef(q,q),q.add=Mf,q.attempt=Zh,q.camelCase=Th,q.capitalize=jf,q.ceil=ai,q.clone=ue,q.cloneDeep=ve,q.deburr=kf,q.endsWith=lf,q.escape=mf,q.escapeRegExp=nf,q.every=Xd,q.find=eh,q.findIndex=Tg,q.findKey=Ih,q.findLast=fh,q.findLastIndex=Ug,q.findLastKey=Jh,q.findWhere=Zd,q.first=ud,q.floor=bi,q.get=Ye,q.gt=we,q.gte=xe,q.has=Ze,q.identity=Bf,q.includes=$d,q.indexOf=xd,q.inRange=gf,q.isArguments=ye,q.isArray=Dh,q.isBoolean=ze,q.isDate=Ae,q.isElement=Be,q.isEmpty=Ce,q.isEqual=De,q.isError=Ee,q.isFinite=Fe,q.isFunction=Ge,q.isMatch=Ie,q.isNaN=Je,q.isNative=Ke,q.isNull=Le,q.isNumber=Me,q.isObject=He,q.isPlainObject=Ne,q.isRegExp=Oe,q.isString=Pe,q.isTypedArray=Qe,q.isUndefined=Re,q.kebabCase=Uh,q.last=zd,q.lastIndexOf=Ad,q.lt=Se,q.lte=Te,q.max=ci,q.min=di,q.noConflict=Ff,q.noop=Gf,q.now=ph,q.pad=of,q.padLeft=Vh,q.padRight=Wh,q.parseInt=pf,q.random=hf,q.reduce=mh,q.reduceRight=nh,q.repeat=qf,q.result=bf,q.round=ei,q.runInContext=w,q.size=ee,q.snakeCase=Xh,q.some=fe,q.sortedIndex=Xg,q.sortedLastIndex=Yg,q.startCase=Yh,q.startsWith=rf,q.sum=Nf,q.template=sf,q.trim=tf,q.trimLeft=uf,q.trimRight=vf,q.trunc=wf,q.unescape=xf,q.uniqueId=Lf,q.words=yf,q.all=Xd,q.any=fe,q.contains=$d,q.eq=De,q.detect=eh,q.foldl=mh,q.foldr=nh,q.head=ud,q.include=$d,q.inject=mh,Ef(q,function(){var a={};return Fb(q,function(b,c){q.prototype[c]||(a[c]=b)}),a}(),!1),q.sample=ce,q.prototype.sample=function(a){return this.__chain__||null!=a?this.thru(function(b){return ce(b,a)}):ce(this.value())},q.VERSION=y,db(["bind","bindKey","curry","curryRight","partial","partialRight"],function(a){q[a].placeholder=q}),db(["drop","take"],function(a,b){ba.prototype[a]=function(c){var d=this.__filtered__;if(d&&!b)return new ba(this);c=null==c?1:vg(rg(c)||0,0);var e=this.clone();return d?e.__takeCount__=wg(e.__takeCount__,c):e.__views__.push({size:c,type:a+(e.__dir__<0?"Right":"")}),e},ba.prototype[a+"Right"]=function(b){return this.reverse()[a](b).reverse()}}),db(["filter","map","takeWhile"],function(a,b){var c=b+1,d=c!=O;ba.prototype[a]=function(a,b){var e=this.clone();return e.__iteratees__.push({iteratee:Oc(a,b,1),type:c}),e.__filtered__=e.__filtered__||d,e}}),db(["first","last"],function(a,b){var c="take"+(b?"Right":"");ba.prototype[a]=function(){return this[c](1).value()[0]}}),db(["initial","rest"],function(a,b){var c="drop"+(b?"":"Right");ba.prototype[a]=function(){return this.__filtered__?new ba(this):this[c](1)}}),db(["pluck","where"],function(a,b){var c=b?"filter":"map",d=b?Nb:Hf;ba.prototype[a]=function(a){return this[c](d(a))}}),ba.prototype.compact=function(){return this.filter(Bf)},ba.prototype.reject=function(a,b){return a=Oc(a,b,1),this.filter(function(b){return!a(b)})},ba.prototype.slice=function(a,b){a=null==a?0:+a||0;var c=this;return c.__filtered__&&(a>0||0>b)?new ba(c):(0>a?c=c.takeRight(-a):a&&(c=c.drop(a)),b!==x&&(b=+b||0,c=0>b?c.dropRight(-b):c.take(b-a)),c)},ba.prototype.takeRightWhile=function(a,b){return this.reverse().takeWhile(a,b).reverse()},ba.prototype.toArray=function(){return this.take(Bg)},Fb(ba.prototype,function(a,b){var c=/^(?:filter|map|reject)|While$/.test(b),d=/^(?:first|last)$/.test(b),e=q[d?"take"+("last"==b?"Right":""):b];e&&(q.prototype[b]=function(){var b=d?[1]:arguments,f=this.__chain__,g=this.__wrapped__,h=!!this.__actions__.length,i=g instanceof ba,j=b[0],k=i||Dh(g);k&&c&&"function"==typeof j&&1!=j.length&&(i=k=!1);var l=function(a){return d&&f?e(a,1)[0]:e.apply(x,jb([a],b))},m={func:Qd,args:[l],thisArg:x},n=i&&!h;if(d&&!f)return n?(g=g.clone(),g.__actions__.push(m),a.call(g)):e.call(x,this.value())[0];if(!d&&k){g=n?g:new ba(this);var o=a.apply(g,b);return o.__actions__.push(m),new _(o,f)}return this.thru(l)})}),db(["join","pop","push","replace","shift","sort","splice","split","unshift"],function(a){var b=(/^(?:replace|split)$/.test(a)?$f:Yf)[a],c=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",d=/^(?:join|pop|replace|shift)$/.test(a);q.prototype[a]=function(){var a=arguments;return d&&!this.__chain__?b.apply(this.value(),a):this[c](function(c){return b.apply(c,a)})}}),Fb(ba.prototype,function(a,b){var c=q[b];if(c){var d=c.name+"",e=Hg[d]||(Hg[d]=[]);e.push({name:b,func:c})}}),Hg[Fc(x,A).name]=[{name:"wrapper",func:x}],ba.prototype.clone=Qa,ba.prototype.reverse=Ra,ba.prototype.value=Sa,q.prototype.chain=Rd,q.prototype.commit=Sd,q.prototype.concat=bh,q.prototype.plant=Td,q.prototype.reverse=Ud,q.prototype.toString=Vd,q.prototype.run=q.prototype.toJSON=q.prototype.valueOf=q.prototype.value=Wd,q.prototype.collect=q.prototype.map,q.prototype.head=q.prototype.first,q.prototype.select=q.prototype.filter,q.prototype.tail=q.prototype.rest,q}var x,y="3.10.1",z=1,A=2,B=4,C=8,D=16,E=32,F=64,G=128,H=256,I=30,J="...",K=150,L=16,M=200,N=1,O=2,P="Expected a function",Q="__lodash_placeholder__",R="[object Arguments]",S="[object Array]",T="[object Boolean]",U="[object Date]",V="[object Error]",W="[object Function]",X="[object Map]",Y="[object Number]",Z="[object Object]",$="[object RegExp]",_="[object Set]",aa="[object String]",ba="[object WeakMap]",ca="[object ArrayBuffer]",da="[object Float32Array]",ea="[object Float64Array]",fa="[object Int8Array]",ga="[object Int16Array]",ha="[object Int32Array]",ia="[object Uint8Array]",ja="[object Uint8ClampedArray]",ka="[object Uint16Array]",la="[object Uint32Array]",ma=/\b__p \+= '';/g,na=/\b(__p \+=) '' \+/g,oa=/(__e\(.*?\)|\b__t\)) \+\n'';/g,pa=/&(?:amp|lt|gt|quot|#39|#96);/g,qa=/[&<>"'`]/g,ra=RegExp(pa.source),sa=RegExp(qa.source),ta=/<%-([\s\S]+?)%>/g,ua=/<%([\s\S]+?)%>/g,va=/<%=([\s\S]+?)%>/g,wa=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,xa=/^\w*$/,ya=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g,za=/^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g,Aa=RegExp(za.source),Ba=/[\u0300-\u036f\ufe20-\ufe23]/g,Ca=/\\(\\)?/g,Da=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Ea=/\w*$/,Fa=/^0[xX]/,Ga=/^\[object .+?Constructor\]$/,Ha=/^\d+$/,Ia=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g,Ja=/($^)/,Ka=/['\n\r\u2028\u2029\\]/g,La=function(){var a="[A-Z\\xc0-\\xd6\\xd8-\\xde]",b="[a-z\\xdf-\\xf6\\xf8-\\xff]+";return RegExp(a+"+(?="+a+b+")|"+a+"?"+b+"|"+a+"+|[0-9]+","g")}(),Ma=["Array","ArrayBuffer","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Math","Number","Object","RegExp","Set","String","_","clearTimeout","isFinite","parseFloat","parseInt","setTimeout","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap"],Na=-1,Oa={};Oa[da]=Oa[ea]=Oa[fa]=Oa[ga]=Oa[ha]=Oa[ia]=Oa[ja]=Oa[ka]=Oa[la]=!0,Oa[R]=Oa[S]=Oa[ca]=Oa[T]=Oa[U]=Oa[V]=Oa[W]=Oa[X]=Oa[Y]=Oa[Z]=Oa[$]=Oa[_]=Oa[aa]=Oa[ba]=!1;var Pa={};Pa[R]=Pa[S]=Pa[ca]=Pa[T]=Pa[U]=Pa[da]=Pa[ea]=Pa[fa]=Pa[ga]=Pa[ha]=Pa[Y]=Pa[Z]=Pa[$]=Pa[aa]=Pa[ia]=Pa[ja]=Pa[ka]=Pa[la]=!0,Pa[V]=Pa[W]=Pa[X]=Pa[_]=Pa[ba]=!1;var Qa={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss"},Ra={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},Sa={"&":"&","<":"<",">":">",""":'"',"'":"'","`":"`"},Ta={"function":!0,object:!0},Ua={0:"x30",1:"x31",2:"x32",3:"x33",4:"x34",5:"x35",6:"x36",7:"x37",8:"x38",9:"x39",A:"x41",B:"x42",C:"x43",D:"x44",E:"x45",F:"x46",a:"x61",b:"x62",c:"x63",d:"x64",e:"x65",f:"x66",n:"x6e",r:"x72",t:"x74",u:"x75",v:"x76",x:"x78"},Va={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Wa=Ta[typeof exports]&&exports&&!exports.nodeType&&exports,Xa=Ta[typeof module]&&module&&!module.nodeType&&module,Ya=Wa&&Xa&&"object"==typeof global&&global&&global.Object&&global,Za=Ta[typeof self]&&self&&self.Object&&self,$a=Ta[typeof window]&&window&&window.Object&&window,_a=Xa&&Xa.exports===Wa&&Wa,ab=Ya||$a!==(this&&this.window)&&$a||Za||this,bb=w();"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return bb}):Wa&&Xa&&(_a?(Xa.exports=bb)._=bb:Wa._=bb),a.constant("lodash",bb)}]);
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ng-lodash/package.json b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/package.json
new file mode 100644
index 0000000..3de6f34
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ng-lodash/package.json
@@ -0,0 +1,46 @@
+{
+ "name": "ng-lodash",
+ "version": "0.3.0",
+ "description": "An Angular module wrapper for lodash",
+ "main": "build/ng-lodash.js",
+ "scripts": {
+ "test": "grunt dist"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/rockabox/ng-lodash.git"
+ },
+ "keywords": [
+ "nglodash",
+ "angular",
+ "lodash"
+ ],
+ "author": [
+ "Rockabox <tech@rockabox.com> (http://rockabox.com)"
+ ],
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/rockabox/ng-lodash/issues"
+ },
+ "homepage": "https://github.com/rockabox/ng-lodash",
+ "devDependencies": {
+ "grunt": "~0.4.5",
+ "grunt-bower-task": "~0.4.0",
+ "grunt-cli": "~0.1.13",
+ "grunt-contrib-jshint": "~0.11.0",
+ "grunt-contrib-uglify": "~0.7.0",
+ "grunt-jscs": "~1.5.0",
+ "grunt-karma": "~0.10.1",
+ "grunt-lodash": "~0.5.0",
+ "lodash-cli": "~3.10.1",
+ "grunt-ngmin": "~0.0.3",
+ "jasmine-core": "~2.2.0",
+ "karma": "~0.12.16",
+ "karma-jasmine": "~0.3.1",
+ "karma-phantomjs-launcher": "~0.1.4",
+ "load-grunt-tasks": "~3.1.0"
+ },
+ "engines": {
+ "node": "~0.10.0"
+ }
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.bower.json b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.bower.json
new file mode 100644
index 0000000..c26a5c2
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.bower.json
@@ -0,0 +1,14 @@
+{
+ "name": "ui.bootstrap",
+ "homepage": "https://github.com/angular-ui/bootstrap",
+ "version": "0.14.3",
+ "_release": "0.14.3",
+ "_resolution": {
+ "type": "version",
+ "tag": "0.14.3",
+ "commit": "e9d6ec2a29998986cf7534f2d5ca6c5371639872"
+ },
+ "_source": "git://github.com/angular-ui/bootstrap.git",
+ "_target": "~0.14.3",
+ "_originalSource": "ui.bootstrap"
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.editorconfig b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.editorconfig
new file mode 100644
index 0000000..8565360
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.editorconfig
@@ -0,0 +1,18 @@
+# This file is for unifying the coding style for different editors and IDEs
+# editorconfig.org
+
+root = true
+
+[*]
+end_of_line = lf
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+
+# Tabs in JS unless otherwise specified
+[**.js]
+indent_style = space
+indent_size = 2
+
+[*.md]
+trim_trailing_whitespace = false
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.gitattributes b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.gitattributes
new file mode 100644
index 0000000..352204d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.gitattributes
@@ -0,0 +1,6 @@
+*.html eol=lf
+*.css eol=lf
+*.js eol=lf
+*.md eol=lf
+*.json eol=lf
+*.yml eol=lf
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.gitignore b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.gitignore
new file mode 100644
index 0000000..d106a75
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.gitignore
@@ -0,0 +1,23 @@
+lib-cov
+*.seed
+*.log
+*.csv
+*.dat
+*.out
+*.pid
+*.gz
+*.swp
+*.swo
+.DS_Store
+
+pids
+logs
+results
+dist
+# test coverage files
+coverage/
+
+node_modules
+npm-debug.log
+
+template/**/*.js
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.jshintrc b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.jshintrc
new file mode 100644
index 0000000..b36c317
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.jshintrc
@@ -0,0 +1,30 @@
+{
+ "curly": true,
+ "immed": true,
+ "newcap": true,
+ "noarg": true,
+ "sub": true,
+ "boss": true,
+ "eqnull": true,
+ "quotmark": "single",
+ "trailing": true,
+ "undef": true,
+ "browser": true,
+ "jquery": true,
+ "globals": {
+ "angular": false,
+
+ // For Jasmine
+ "after" : false,
+ "afterEach" : false,
+ "before" : false,
+ "beforeEach" : false,
+ "describe" : false,
+ "expect" : false,
+ "jasmine" : false,
+ "module" : false,
+ "spyOn" : false,
+ "inject" : false,
+ "it" : false
+ }
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.npmignore b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.npmignore
new file mode 100644
index 0000000..c447a4e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.npmignore
@@ -0,0 +1,39 @@
+lib-cov
+*.seed
+*.log
+*.csv
+*.dat
+*.out
+*.pid
+*.gz
+*.swp
+*.swo
+.DS_Store
+
+pids
+logs
+results
+# test coverage files
+coverage/
+
+node_modules
+npm-debug.log
+
+template/**/*.js
+
+.git
+docs
+misc
+src
+template
+.editorconfig
+.gitattributes
+.gitignore
+.jshintrc
+.travis.yml
+CONTRIBUTING.md
+Gruntfile.js
+karma.conf.js
+ROADMAP.md
+
+dist/assets
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.travis.yml b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.travis.yml
new file mode 100644
index 0000000..8be8967
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/.travis.yml
@@ -0,0 +1,11 @@
+language: node_js
+node_js:
+ - "0.12"
+
+before_install:
+ - export DISPLAY=:99.0
+ - sh -e /etc/init.d/xvfb start
+ - npm install --quiet -g grunt-cli karma
+
+script: grunt
+sudo: false
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/CHANGELOG.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/CHANGELOG.md
new file mode 100644
index 0000000..944768f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/CHANGELOG.md
@@ -0,0 +1,1344 @@
+<a name="0.14.3"></a>
+## [0.14.3](https://github.com/angular-ui/bootstrap/compare/0.14.2...v0.14.3) (2015-10-23)
+
+
+### Bug Fixes
+
+* **alert:** allow interpolations with dismiss-on-timeout ([de24f46](https://github.com/angular-ui/bootstrap/commit/de24f46)), closes [#4665](https://github.com/angular-ui/bootstrap/issues/4665) [#4666](https://github.com/angular-ui/bootstrap/issues/4666)
+* **buttons:** double toggle on spacebar ([e8808d3](https://github.com/angular-ui/bootstrap/commit/e8808d3)), closes [#4474](https://github.com/angular-ui/bootstrap/issues/4474) [#4630](https://github.com/angular-ui/bootstrap/issues/4630)
+* **collapse:** fix collapse animation timing ([6d1cd0f](https://github.com/angular-ui/bootstrap/commit/6d1cd0f)), closes [#4493](https://github.com/angular-ui/bootstrap/issues/4493)
+* **collapse:** trigger digest after ([3144633](https://github.com/angular-ui/bootstrap/commit/3144633)), closes [#4647](https://github.com/angular-ui/bootstrap/issues/4647) [#4628](https://github.com/angular-ui/bootstrap/issues/4628) [#4561](https://github.com/angular-ui/bootstrap/issues/4561) [#4651](https://github.com/angular-ui/bootstrap/issues/4651)
+* **datepicker:** datepicker-popup nest in dropdown ([134086a](https://github.com/angular-ui/bootstrap/commit/134086a)), closes [#4197](https://github.com/angular-ui/bootstrap/issues/4197) [#4693](https://github.com/angular-ui/bootstrap/issues/4693)
+* **datepicker:** fix support for literal format on popup ([7c3c631](https://github.com/angular-ui/bootstrap/commit/7c3c631)), closes [#4635](https://github.com/angular-ui/bootstrap/issues/4635) [#4616](https://github.com/angular-ui/bootstrap/issues/4616)
+* **tooltip:** delay timeouts ([02425b8](https://github.com/angular-ui/bootstrap/commit/02425b8)), closes [#4621](https://github.com/angular-ui/bootstrap/issues/4621) [#4618](https://github.com/angular-ui/bootstrap/issues/4618)
+* **tooltip:** null scope check in isOpen watch ([1f94104](https://github.com/angular-ui/bootstrap/commit/1f94104)), closes [#4697](https://github.com/angular-ui/bootstrap/issues/4697) [#4683](https://github.com/angular-ui/bootstrap/issues/4683)
+* **tooltip:** scrollbar flashing ([6c82b2b](https://github.com/angular-ui/bootstrap/commit/6c82b2b)), closes [#4550](https://github.com/angular-ui/bootstrap/issues/4550) [#4623](https://github.com/angular-ui/bootstrap/issues/4623) [#4458](https://github.com/angular-ui/bootstrap/issues/4458)
+* **typeahead:** dangling event listeners ([94fb282](https://github.com/angular-ui/bootstrap/commit/94fb282)), closes [#4632](https://github.com/angular-ui/bootstrap/issues/4632) [#4636](https://github.com/angular-ui/bootstrap/issues/4636)
+
+### Features
+
+* **datepicker:** add templateUrl support for pickers ([1f65d87](https://github.com/angular-ui/bootstrap/commit/1f65d87)), closes [#4432](https://github.com/angular-ui/bootstrap/issues/4432)
+* **datepicker:** preserve timezone with model ([0d64aad](https://github.com/angular-ui/bootstrap/commit/0d64aad)), closes [#4676](https://github.com/angular-ui/bootstrap/issues/4676)
+* **modal:** support $uibModalInstance ([97fd37e](https://github.com/angular-ui/bootstrap/commit/97fd37e)), closes [#4638](https://github.com/angular-ui/bootstrap/issues/4638) [#4661](https://github.com/angular-ui/bootstrap/issues/4661)
+
+
+
+<a name="0.14.2"></a>
+## [0.14.2](https://github.com/angular-ui/bootstrap/compare/0.14.1...v0.14.2) (2015-10-14)
+
+
+### Bug Fixes
+
+* **progressbar:** fix percentage calculation ([feb689c](https://github.com/angular-ui/bootstrap/commit/feb689c)), closes [#4471](https://github.com/angular-ui/bootstrap/issues/4471) [#4588](https://github.com/angular-ui/bootstrap/issues/4588) [#4452](https://github.com/angular-ui/bootstrap/issues/4452)
+* **tooltip:** clean up stackedMap on scope destroy ([ebb5e18](https://github.com/angular-ui/bootstrap/commit/ebb5e18)), closes [#4610](https://github.com/angular-ui/bootstrap/issues/4610) [#4604](https://github.com/angular-ui/bootstrap/issues/4604)
+* **tooltip:** popup close delay not respected ([6daf871](https://github.com/angular-ui/bootstrap/commit/6daf871)), closes [#4597](https://github.com/angular-ui/bootstrap/issues/4597) [#4567](https://github.com/angular-ui/bootstrap/issues/4567)
+
+
+
+<a name="0.14.1"></a>
+## [0.14.1](https://github.com/angular-ui/bootstrap/compare/0.14.0...v0.14.1) (2015-10-11)
+
+
+### Bug Fixes
+
+* **accordion:** make deprecated controller work with 1.3.x ([c5e6042](https://github.com/angular-ui/bootstrap/commit/c5e6042)), closes [#4574](https://github.com/angular-ui/bootstrap/issues/4574)
+* **alert:** make deprecated controller work with 1.3.x ([e8c8ee6](https://github.com/angular-ui/bootstrap/commit/e8c8ee6)), closes [#4576](https://github.com/angular-ui/bootstrap/issues/4576)
+* **buttons:** make deprecated controller work with 1.3.x ([1e3cbd8](https://github.com/angular-ui/bootstrap/commit/1e3cbd8)), closes [#4577](https://github.com/angular-ui/bootstrap/issues/4577)
+* **carousel:** make deprecated controller work with 1.3.x ([f6c7931](https://github.com/angular-ui/bootstrap/commit/f6c7931)), closes [#4578](https://github.com/angular-ui/bootstrap/issues/4578)
+* **datepicker:** make deprecated controller work with 1.3.x ([18371ab](https://github.com/angular-ui/bootstrap/commit/18371ab)), closes [#4586](https://github.com/angular-ui/bootstrap/issues/4586)
+* **dropdown:** make deprecated controller work with 1.3.x ([ae1a87c](https://github.com/angular-ui/bootstrap/commit/ae1a87c)), closes [#4585](https://github.com/angular-ui/bootstrap/issues/4585)
+* **pagination:** make deprecated controller work with 1.3.x ([d50e8d2](https://github.com/angular-ui/bootstrap/commit/d50e8d2)), closes [#4580](https://github.com/angular-ui/bootstrap/issues/4580)
+* **progressbar:** make deprecated controller work with 1.3.x ([1c5e479](https://github.com/angular-ui/bootstrap/commit/1c5e479)), closes [#4581](https://github.com/angular-ui/bootstrap/issues/4581)
+* **rating:** make deprecated controller work with 1.3.x ([ce1114a](https://github.com/angular-ui/bootstrap/commit/ce1114a)), closes [#4582](https://github.com/angular-ui/bootstrap/issues/4582)
+* **tabs:** make deprecated controller work with 1.3.x ([685bd6a](https://github.com/angular-ui/bootstrap/commit/685bd6a)), closes [#4583](https://github.com/angular-ui/bootstrap/issues/4583)
+* **timepicker:** make deprecated controller work with 1.3.x ([00f60ee](https://github.com/angular-ui/bootstrap/commit/00f60ee)), closes [#4584](https://github.com/angular-ui/bootstrap/issues/4584)
+
+### Features
+
+* **timepicker:** add accessibility improvements ([4ebecbc](https://github.com/angular-ui/bootstrap/commit/4ebecbc)), closes [#4569](https://github.com/angular-ui/bootstrap/issues/4569) [#4573](https://github.com/angular-ui/bootstrap/issues/4573)
+
+
+
+<a name="0.14.0"></a>
+# [0.14.0](https://github.com/angular-ui/bootstrap/compare/0.13.4...0.14.0) (2015-10-09)
+
+
+### Bug Fixes
+
+* **accordion:** coerce to boolean ([b864aa9](https://github.com/angular-ui/bootstrap/commit/b864aa9)), closes [#4385](https://github.com/angular-ui/bootstrap/issues/4385)
+* **accordion:** re-expose AccordionController ([5382226](https://github.com/angular-ui/bootstrap/commit/5382226)), closes [#4524](https://github.com/angular-ui/bootstrap/issues/4524)
+* **alert:** properly pass $event as local ([eb2366f](https://github.com/angular-ui/bootstrap/commit/eb2366f)), closes [#4386](https://github.com/angular-ui/bootstrap/issues/4386) [#4387](https://github.com/angular-ui/bootstrap/issues/4387)
+* **alert:** re-expose AlertController ([f561aa9](https://github.com/angular-ui/bootstrap/commit/f561aa9)), closes [#4525](https://github.com/angular-ui/bootstrap/issues/4525)
+* **buttons:** re-expose ButtonsController ([c0dbf79](https://github.com/angular-ui/bootstrap/commit/c0dbf79)), closes [#4526](https://github.com/angular-ui/bootstrap/issues/4526)
+* **carousel:** fix reading of `noTransition` ([2e26815](https://github.com/angular-ui/bootstrap/commit/2e26815)), closes [#4325](https://github.com/angular-ui/bootstrap/issues/4325)
+* **carousel:** improve accessibility ([da71159](https://github.com/angular-ui/bootstrap/commit/da71159)), closes [#4478](https://github.com/angular-ui/bootstrap/issues/4478) [#4479](https://github.com/angular-ui/bootstrap/issues/4479)
+* **carousel:** re-enable deprecated directives ([30e8aa7](https://github.com/angular-ui/bootstrap/commit/30e8aa7)), closes [#4527](https://github.com/angular-ui/bootstrap/issues/4527)
+* **carousel:** reset $currentTransition when no slides ([0b3d5bd](https://github.com/angular-ui/bootstrap/commit/0b3d5bd)), closes [#4532](https://github.com/angular-ui/bootstrap/issues/4532) [#4390](https://github.com/angular-ui/bootstrap/issues/4390)
+* **datepicker:** add check for `contains` ([868c0e2](https://github.com/angular-ui/bootstrap/commit/868c0e2)), closes [#4423](https://github.com/angular-ui/bootstrap/issues/4423) [#4411](https://github.com/angular-ui/bootstrap/issues/4411)
+* **datepicker:** add custom class to year picker ([0ad7cb9](https://github.com/angular-ui/bootstrap/commit/0ad7cb9)), closes [#4558](https://github.com/angular-ui/bootstrap/issues/4558) [#4546](https://github.com/angular-ui/bootstrap/issues/4546)
+* **datepicker:** change to `$popup` ([65814f1](https://github.com/angular-ui/bootstrap/commit/65814f1))
+* **datepicker:** datepicker-popup nest in dropdown ([6b4267b](https://github.com/angular-ui/bootstrap/commit/6b4267b)), closes [#4489](https://github.com/angular-ui/bootstrap/issues/4489) [#4197](https://github.com/angular-ui/bootstrap/issues/4197)
+* **datepicker:** remove focus management on date selection by keyboard ([36ecf60](https://github.com/angular-ui/bootstrap/commit/36ecf60)), closes [#4409](https://github.com/angular-ui/bootstrap/issues/4409)
+* **dropdown:** ensure class is present in dropdown-menu ([92ab48e](https://github.com/angular-ui/bootstrap/commit/92ab48e)), closes [#4523](https://github.com/angular-ui/bootstrap/issues/4523) [#4442](https://github.com/angular-ui/bootstrap/issues/4442)
+* **dropdown:** restore deprecated directives ([e7c5879](https://github.com/angular-ui/bootstrap/commit/e7c5879)), closes [#4514](https://github.com/angular-ui/bootstrap/issues/4514)
+* **modal:** fix for conflicts with ngTouch module on mobile devices ([508aceb](https://github.com/angular-ui/bootstrap/commit/508aceb)), closes [#2280](https://github.com/angular-ui/bootstrap/issues/2280) [#4357](https://github.com/angular-ui/bootstrap/issues/4357)
+* **progressbar:** re-expose ProgressController ([5604e59](https://github.com/angular-ui/bootstrap/commit/5604e59)), closes [#4528](https://github.com/angular-ui/bootstrap/issues/4528)
+* **rating:** re-expose RatingController ([aede646](https://github.com/angular-ui/bootstrap/commit/aede646)), closes [#4529](https://github.com/angular-ui/bootstrap/issues/4529)
+* **tabs:** re-expose TabsetController ([435924f](https://github.com/angular-ui/bootstrap/commit/435924f)), closes [#4530](https://github.com/angular-ui/bootstrap/issues/4530)
+* **timepicker:** re-expose TimepickerController ([3aa9841](https://github.com/angular-ui/bootstrap/commit/3aa9841)), closes [#4531](https://github.com/angular-ui/bootstrap/issues/4531)
+* **tooltip:** add display block to style ([b413a22](https://github.com/angular-ui/bootstrap/commit/b413a22)), closes [#4363](https://github.com/angular-ui/bootstrap/issues/4363) [#4379](https://github.com/angular-ui/bootstrap/issues/4379)
+* **tooltip:** check for ttScope in $$postDigest ([01b9624](https://github.com/angular-ui/bootstrap/commit/01b9624)), closes [#4555](https://github.com/angular-ui/bootstrap/issues/4555) [#4552](https://github.com/angular-ui/bootstrap/issues/4552)
+* **tooltip:** correct flash of reposition ([8fee75d](https://github.com/angular-ui/bootstrap/commit/8fee75d)), closes [#4363](https://github.com/angular-ui/bootstrap/issues/4363) [#4195](https://github.com/angular-ui/bootstrap/issues/4195)
+* **tooltip:** do nothing if `$scope` doesn't exist ([1e039e8](https://github.com/angular-ui/bootstrap/commit/1e039e8)), closes [#4346](https://github.com/angular-ui/bootstrap/issues/4346) [#3347](https://github.com/angular-ui/bootstrap/issues/3347)
+* **tooltip:** fix binding to multiple triggers ([d6cda93](https://github.com/angular-ui/bootstrap/commit/d6cda93)), closes [#4371](https://github.com/angular-ui/bootstrap/issues/4371) [#4384](https://github.com/angular-ui/bootstrap/issues/4384)
+* **tooltip:** isOpen to work with expressions ([5f68280](https://github.com/angular-ui/bootstrap/commit/5f68280)), closes [#4380](https://github.com/angular-ui/bootstrap/issues/4380) [#4362](https://github.com/angular-ui/bootstrap/issues/4362)
+* **tooltip:** properly gc popupTimeout ([ff52f52](https://github.com/angular-ui/bootstrap/commit/ff52f52)), closes [#2786](https://github.com/angular-ui/bootstrap/issues/2786)
+* **tooltip:** set `visibility: hidden` to avoid flicker ([f7cb8bc](https://github.com/angular-ui/bootstrap/commit/f7cb8bc)), closes [#4342](https://github.com/angular-ui/bootstrap/issues/4342)
+
+### Features
+
+* **accordion:** use uib- prefix ([0328a76](https://github.com/angular-ui/bootstrap/commit/0328a76)), closes [#4389](https://github.com/angular-ui/bootstrap/issues/4389)
+* **accordion:** use uib- prefix ([298ec8c](https://github.com/angular-ui/bootstrap/commit/298ec8c)), closes [#4503](https://github.com/angular-ui/bootstrap/issues/4503)
+* **alert:** use uib- prefix ([5e3a87a](https://github.com/angular-ui/bootstrap/commit/5e3a87a)), closes [#4406](https://github.com/angular-ui/bootstrap/issues/4406)
+* **buttons:** use uib- prefix ([5a1c2c9](https://github.com/angular-ui/bootstrap/commit/5a1c2c9)), closes [#4445](https://github.com/angular-ui/bootstrap/issues/4445)
+* **carousel:** use uib- prefix ([2e5bfac](https://github.com/angular-ui/bootstrap/commit/2e5bfac)), closes [#4501](https://github.com/angular-ui/bootstrap/issues/4501)
+* **collapse:** convert to use `$animateCss` ([533a9f0](https://github.com/angular-ui/bootstrap/commit/533a9f0)), closes [#4257](https://github.com/angular-ui/bootstrap/issues/4257)
+* **collapse:** use uib- prefix ([9bdb32e](https://github.com/angular-ui/bootstrap/commit/9bdb32e)), closes [#4370](https://github.com/angular-ui/bootstrap/issues/4370)
+* **dateparser:** reset parsers when $locale.id changes ([d9a521a](https://github.com/angular-ui/bootstrap/commit/d9a521a)), closes [#4286](https://github.com/angular-ui/bootstrap/issues/4286) [#4425](https://github.com/angular-ui/bootstrap/issues/4425)
+* **dateparser:** use uib- prefix ([0fa851f](https://github.com/angular-ui/bootstrap/commit/0fa851f)), closes [#4504](https://github.com/angular-ui/bootstrap/issues/4504)
+* **datepicker:** add uib- prefix ([44354f6](https://github.com/angular-ui/bootstrap/commit/44354f6)), closes [#4509](https://github.com/angular-ui/bootstrap/issues/4509)
+* **dropdown:** uib- prefix ([5bc0851](https://github.com/angular-ui/bootstrap/commit/5bc0851)), closes [#4510](https://github.com/angular-ui/bootstrap/issues/4510)
+* **modal:** Added ability to add CSS class to top window ([bd38e8f](https://github.com/angular-ui/bootstrap/commit/bd38e8f)), closes [#2524](https://github.com/angular-ui/bootstrap/issues/2524)
+* **modal:** add uib- prefix ([8c7b9e4](https://github.com/angular-ui/bootstrap/commit/8c7b9e4)), closes [#4511](https://github.com/angular-ui/bootstrap/issues/4511)
+* **pagination:** add uib- prefix ([9aea856](https://github.com/angular-ui/bootstrap/commit/9aea856)), closes [#4536](https://github.com/angular-ui/bootstrap/issues/4536)
+* **position:** add uib- prefix ([6158091](https://github.com/angular-ui/bootstrap/commit/6158091)), closes [#4507](https://github.com/angular-ui/bootstrap/issues/4507)
+* **progressbar:** add `aria-labelledby` support ([e6f3b87](https://github.com/angular-ui/bootstrap/commit/e6f3b87)), closes [#4350](https://github.com/angular-ui/bootstrap/issues/4350) [#4347](https://github.com/angular-ui/bootstrap/issues/4347)
+* **rating:** add `aria-valuetext` attribute ([72de2d8](https://github.com/angular-ui/bootstrap/commit/72de2d8)), closes [#4349](https://github.com/angular-ui/bootstrap/issues/4349) [#4347](https://github.com/angular-ui/bootstrap/issues/4347)
+* **rating:** user uib- prefix ([377b4b7](https://github.com/angular-ui/bootstrap/commit/377b4b7)), closes [#4502](https://github.com/angular-ui/bootstrap/issues/4502)
+* **tabs:** use uib- prefix ([d25a8c2](https://github.com/angular-ui/bootstrap/commit/d25a8c2)), closes [#4449](https://github.com/angular-ui/bootstrap/issues/4449)
+* **timepicker:** use uib- prefix ([504e653](https://github.com/angular-ui/bootstrap/commit/504e653)), closes [#4505](https://github.com/angular-ui/bootstrap/issues/4505)
+* **tooltip:** add uib- prefix ([f8bc038](https://github.com/angular-ui/bootstrap/commit/f8bc038)), closes [#4515](https://github.com/angular-ui/bootstrap/issues/4515)
+* **tooltip:** allow custom closing delay ([5f7051b](https://github.com/angular-ui/bootstrap/commit/5f7051b)), closes [#3576](https://github.com/angular-ui/bootstrap/issues/3576)
+* **tooltip:** hide tooltip when `esc` is hit ([c08509a](https://github.com/angular-ui/bootstrap/commit/c08509a)), closes [#4367](https://github.com/angular-ui/bootstrap/issues/4367) [#4248](https://github.com/angular-ui/bootstrap/issues/4248)
+* **typeahead:** add `appendElementToId` ([fdf53e6](https://github.com/angular-ui/bootstrap/commit/fdf53e6)), closes [#4231](https://github.com/angular-ui/bootstrap/issues/4231) [#4497](https://github.com/angular-ui/bootstrap/issues/4497)
+* **typeahead:** add customClass support for dropdown ([fa1cdfc](https://github.com/angular-ui/bootstrap/commit/fa1cdfc)), closes [#4332](https://github.com/angular-ui/bootstrap/issues/4332) [#4410](https://github.com/angular-ui/bootstrap/issues/4410)
+* **typeahead:** add uib- prefix ([9e5e1a2](https://github.com/angular-ui/bootstrap/commit/9e5e1a2)), closes [#4542](https://github.com/angular-ui/bootstrap/issues/4542)
+
+### Reverts
+
+* **dropdown:** undo adding of `open` class on body ([6f9f1fc](https://github.com/angular-ui/bootstrap/commit/6f9f1fc))
+
+
+### BREAKING CHANGES
+
+* Removes focus on datepicker on selection of a date via keyboard for accessibility reasons
+
+
+<a name="0.13.4"></a>
+## [0.13.4](https://github.com/angular-ui/bootstrap/compare/0.13.3...0.13.4) (2015-09-03)
+
+
+### Bug Fixes
+
+* **accordion:** add custom open class support ([575eb85](https://github.com/angular-ui/bootstrap/commit/575eb85)), closes [#4198](https://github.com/angular-ui/bootstrap/issues/4198)
+* **datepicker:** ensure the original target is not in popup ([9b2f7ac](https://github.com/angular-ui/bootstrap/commit/9b2f7ac)), closes [#4316](https://github.com/angular-ui/bootstrap/issues/4316) [#4314](https://github.com/angular-ui/bootstrap/issues/4314)
+* **dropdown:** fix display when using with append-to-body ([bf63cef](https://github.com/angular-ui/bootstrap/commit/bf63cef)), closes [#4305](https://github.com/angular-ui/bootstrap/issues/4305) [#4240](https://github.com/angular-ui/bootstrap/issues/4240)
+* **dropdown:** fix up arrow nav support ([defcbbb](https://github.com/angular-ui/bootstrap/commit/defcbbb)), closes [#4330](https://github.com/angular-ui/bootstrap/issues/4330) [#4327](https://github.com/angular-ui/bootstrap/issues/4327)
+* **modal:** Wait for animation before focus. ([937a1f3](https://github.com/angular-ui/bootstrap/commit/937a1f3)), closes [#4300](https://github.com/angular-ui/bootstrap/issues/4300) [#4274](https://github.com/angular-ui/bootstrap/issues/4274)
+* **modal:** correctly remove custom class ([ba2ce24](https://github.com/angular-ui/bootstrap/commit/ba2ce24)), closes [#4175](https://github.com/angular-ui/bootstrap/issues/4175) [#4171](https://github.com/angular-ui/bootstrap/issues/4171)
+* **modal:** fix allowing promises to be resolved ([b1e98b1](https://github.com/angular-ui/bootstrap/commit/b1e98b1)), closes [#4310](https://github.com/angular-ui/bootstrap/issues/4310) [#4309](https://github.com/angular-ui/bootstrap/issues/4309)
+* **progress:** rename to avoid conflict ([07a938d](https://github.com/angular-ui/bootstrap/commit/07a938d)), closes [#4255](https://github.com/angular-ui/bootstrap/issues/4255)
+* **tabs:** ensure tab selection only occurs once ([7d3ba1e](https://github.com/angular-ui/bootstrap/commit/7d3ba1e)), closes [#3060](https://github.com/angular-ui/bootstrap/issues/3060) [#4230](https://github.com/angular-ui/bootstrap/issues/4230) [#2883](https://github.com/angular-ui/bootstrap/issues/2883)
+* **timepicker:** leave view alone if either input is invalid ([818f7e5](https://github.com/angular-ui/bootstrap/commit/818f7e5)), closes [#4160](https://github.com/angular-ui/bootstrap/issues/4160) [#3825](https://github.com/angular-ui/bootstrap/issues/3825)
+* **tooltip:** correctly position tooltip ([457f10c](https://github.com/angular-ui/bootstrap/commit/457f10c)), closes [#4311](https://github.com/angular-ui/bootstrap/issues/4311) [#4195](https://github.com/angular-ui/bootstrap/issues/4195)
+* **tooltip:** fix jshint error ([17cc39f](https://github.com/angular-ui/bootstrap/commit/17cc39f))
+* **tooltip:** properly gc timeout on toggle of disabled ([f8eab55](https://github.com/angular-ui/bootstrap/commit/f8eab55)), closes [#4210](https://github.com/angular-ui/bootstrap/issues/4210) [#4204](https://github.com/angular-ui/bootstrap/issues/4204)
+* **tooltip:** switch to use raw DOM event bindings ([7556bed](https://github.com/angular-ui/bootstrap/commit/7556bed)), closes [#4322](https://github.com/angular-ui/bootstrap/issues/4322) [#4060](https://github.com/angular-ui/bootstrap/issues/4060)
+* **typeahead:** add support for ngModelOptions getterSetter ([ccaa627](https://github.com/angular-ui/bootstrap/commit/ccaa627)), closes [#3865](https://github.com/angular-ui/bootstrap/issues/3865) [#3823](https://github.com/angular-ui/bootstrap/issues/3823)
+* **typeahead:** release references on destruction ([695db9d](https://github.com/angular-ui/bootstrap/commit/695db9d)), closes [#4299](https://github.com/angular-ui/bootstrap/issues/4299) [#4298](https://github.com/angular-ui/bootstrap/issues/4298)
+* **typeahead:** use ng-bind-html ([bb9fa1a](https://github.com/angular-ui/bootstrap/commit/bb9fa1a)), closes [#3463](https://github.com/angular-ui/bootstrap/issues/3463) [#4073](https://github.com/angular-ui/bootstrap/issues/4073)
+
+### Features
+
+* **accordion:** allow custom panel class ([5ee23a4](https://github.com/angular-ui/bootstrap/commit/5ee23a4)), closes [#4242](https://github.com/angular-ui/bootstrap/issues/4242) [#3968](https://github.com/angular-ui/bootstrap/issues/3968)
+* **accordion:** support spacebar to toggle group ([aa5a991](https://github.com/angular-ui/bootstrap/commit/aa5a991)), closes [#4319](https://github.com/angular-ui/bootstrap/issues/4319) [#4249](https://github.com/angular-ui/bootstrap/issues/4249)
+* **buttons:** allow toggling via spacebar when focused ([bdfb289](https://github.com/angular-ui/bootstrap/commit/bdfb289)), closes [#4252](https://github.com/angular-ui/bootstrap/issues/4252) [#4259](https://github.com/angular-ui/bootstrap/issues/4259)
+* **buttons:** hide nested inputs ([a06afe6](https://github.com/angular-ui/bootstrap/commit/a06afe6)), closes [#4282](https://github.com/angular-ui/bootstrap/issues/4282)
+* **carousel:** add model binding support to slide ([dac087e](https://github.com/angular-ui/bootstrap/commit/dac087e)), closes [#4202](https://github.com/angular-ui/bootstrap/issues/4202) [#4201](https://github.com/angular-ui/bootstrap/issues/4201)
+* **dateparser:** add support for the `h` format ([550fe20](https://github.com/angular-ui/bootstrap/commit/550fe20)), closes [#4220](https://github.com/angular-ui/bootstrap/issues/4220)
+* **datepicker:** disable today button if invalid ([71e0b8a](https://github.com/angular-ui/bootstrap/commit/71e0b8a)), closes [#4199](https://github.com/angular-ui/bootstrap/issues/4199) [#3988](https://github.com/angular-ui/bootstrap/issues/3988)
+* **modal:** complete modal open resolution in order ([1bba8b4](https://github.com/angular-ui/bootstrap/commit/1bba8b4)), closes [#2443](https://github.com/angular-ui/bootstrap/issues/2443) [#4302](https://github.com/angular-ui/bootstrap/issues/4302) [#2404](https://github.com/angular-ui/bootstrap/issues/2404)
+* **modal:** support multiple open classes ([3d01c59](https://github.com/angular-ui/bootstrap/commit/3d01c59)), closes [#4226](https://github.com/angular-ui/bootstrap/issues/4226) [#4184](https://github.com/angular-ui/bootstrap/issues/4184)
+* **pagination:** add `ngDisabled` support for the pager ([ba734b4](https://github.com/angular-ui/bootstrap/commit/ba734b4)), closes [#4217](https://github.com/angular-ui/bootstrap/issues/4217) [#2856](https://github.com/angular-ui/bootstrap/issues/2856)
+* **pagination:** add `templateUrl` support ([64b5289](https://github.com/angular-ui/bootstrap/commit/64b5289)), closes [#4162](https://github.com/angular-ui/bootstrap/issues/4162)
+* **tabs:** add support for `x-tab-heading` ([1abfd05](https://github.com/angular-ui/bootstrap/commit/1abfd05)), closes [#4166](https://github.com/angular-ui/bootstrap/issues/4166) [#1893](https://github.com/angular-ui/bootstrap/issues/1893)
+* **timepicker:** add `templateUrl` and `controllerAs` support ([639d511](https://github.com/angular-ui/bootstrap/commit/639d511)), closes [#4275](https://github.com/angular-ui/bootstrap/issues/4275) [#4284](https://github.com/angular-ui/bootstrap/issues/4284)
+* **tooltip:** expose isOpen property ([99b87cc](https://github.com/angular-ui/bootstrap/commit/99b87cc)), closes [#4179](https://github.com/angular-ui/bootstrap/issues/4179) [#2148](https://github.com/angular-ui/bootstrap/issues/2148) [#590](https://github.com/angular-ui/bootstrap/issues/590)
+* **typeahead:** add `typeaheadFocusOnSelect` ([b5ecda3](https://github.com/angular-ui/bootstrap/commit/b5ecda3)), closes [#4212](https://github.com/angular-ui/bootstrap/issues/4212) [#4211](https://github.com/angular-ui/bootstrap/issues/4211) [#4206](https://github.com/angular-ui/bootstrap/issues/4206)
+* **typeahead:** add custom popup template support ([4b02648](https://github.com/angular-ui/bootstrap/commit/4b02648)), closes [#4320](https://github.com/angular-ui/bootstrap/issues/4320) [#3774](https://github.com/angular-ui/bootstrap/issues/3774)
+
+
+### Breaking Changes
+
+* **buttons**
+ * hide nested `<input>` elements on `btn-radio` and `btn-checkbox` directives.
+
+ Fixes #3264
+ Closes #4282
+
+ ([a06afe6](https://github.com/angular-ui/bootstrap/commit/a06afe6))
+
+* **dropdown**
+ * when using `append-to-body`, both the `dropdown` and `open` classes are added to the `<body>` element.
+ * this differs from the existing behavior in that it will no longer toggle based on the existing `dropdown` directive element, but on the `body` element instead.
+
+ Fixes #4240
+ Closes #4305
+
+ ([bf63cef](https://github.com/angular-ui/bootstrap/commit/bf63cef))
+
+* **tooltip**
+ * Switch to use `addEventListener` and `removeEventListener` to prevent jqLite/jQuery bug where the events are swallowed on disabled elements
+ * this affects custom events, which must now be dispatched with `element[0].dispatchEvent(new Event('customEvent'))`, as opposed to `element.trigger('customEvent')`
+
+ Fixes #4060
+ Closes #4322
+
+ ([7556bed](https://github.com/angular-ui/bootstrap/commit/7556beda486f26b40fb860448316e8a32457e9e9))
+
+* **typeahead**
+ * for security reasons, only whitelisted HTML should be added.
+ * the typeahead match template now uses `ng-bind-html` instead of `bind-html-unsafe`.
+ * typeahead now uses the `$sce` service when `ngSanitize` is present and logs a warning if it is not.
+
+ Fixes #2884
+ Closes #3463
+ Closes #4073
+
+ ([bb9fa1a](https://github.com/angular-ui/bootstrap/commit/bb9fa1a))
+
+
+<a name"0.13.3"></a>
+### 0.13.3 (2015-08-09)
+
+
+#### Bug Fixes
+
+* **accordion:**
+ * add `open` class when expanded ([ead15e37](https://github.com/angular-ui/bootstrap/commit/ead15e37), closes [#4152](https://github.com/angular-ui/bootstrap/issues/4152), [#3419](https://github.com/angular-ui/bootstrap/issues/3419))
+ * revert to empty href ([b18dc8f9](https://github.com/angular-ui/bootstrap/commit/b18dc8f9), closes [#4104](https://github.com/angular-ui/bootstrap/issues/4104))
+* **buttons:**
+ * change to use `attrs.disabled` ([c9b0d0b0](https://github.com/angular-ui/bootstrap/commit/c9b0d0b0), closes [#4088](https://github.com/angular-ui/bootstrap/issues/4088))
+ * allow selection of undisabled button ([707fbf55](https://github.com/angular-ui/bootstrap/commit/707fbf55), closes [#4088](https://github.com/angular-ui/bootstrap/issues/4088))
+* **carousel:**
+ * fix animation direction ([8359d73f](https://github.com/angular-ui/bootstrap/commit/8359d73f), closes [#4092](https://github.com/angular-ui/bootstrap/issues/4092), [#4087](https://github.com/angular-ui/bootstrap/issues/4087))
+ * fix sorting of indicators ([8056368e](https://github.com/angular-ui/bootstrap/commit/8056368e), closes [#4071](https://github.com/angular-ui/bootstrap/issues/4071), [#3764](https://github.com/angular-ui/bootstrap/issues/3764))
+* **dateparser:** Support 12-hour format and AM/PM ([1ecd82ce](https://github.com/angular-ui/bootstrap/commit/1ecd82ce), closes [#4117](https://github.com/angular-ui/bootstrap/issues/4117))
+* **datepicker:**
+ * commit safe apply on destruction ([74a8be4c](https://github.com/angular-ui/bootstrap/commit/74a8be4c), closes [#4079](https://github.com/angular-ui/bootstrap/issues/4079), [#4076](https://github.com/angular-ui/bootstrap/issues/4076))
+ * change to `dateDisabled` ([5245ccad](https://github.com/angular-ui/bootstrap/commit/5245ccad), closes [#2773](https://github.com/angular-ui/bootstrap/issues/2773), [#4080](https://github.com/angular-ui/bootstrap/issues/4080))
+* **dropdown:** handle `keyboard-nav` correctly ([0b37f088](https://github.com/angular-ui/bootstrap/commit/0b37f088), closes [#4110](https://github.com/angular-ui/bootstrap/issues/4110), [#4091](https://github.com/angular-ui/bootstrap/issues/4091))
+* **modal:**
+ * skipping ESC handling for form inputs ([a05b9c1a](https://github.com/angular-ui/bootstrap/commit/a05b9c1a), closes [#3551](https://github.com/angular-ui/bootstrap/issues/3551), [#2544](https://github.com/angular-ui/bootstrap/issues/2544))
+ * add `$animateCss` support ([c7f19d58](https://github.com/angular-ui/bootstrap/commit/c7f19d58), closes [#4121](https://github.com/angular-ui/bootstrap/issues/4121), [#4119](https://github.com/angular-ui/bootstrap/issues/4119))
+ * fix test ([e60c3ff6](https://github.com/angular-ui/bootstrap/commit/e60c3ff6))
+ * dismiss modal on unschedule destruction ([3584061f](https://github.com/angular-ui/bootstrap/commit/3584061f), closes [#4097](https://github.com/angular-ui/bootstrap/issues/4097), [#3694](https://github.com/angular-ui/bootstrap/issues/3694))
+* **progressbar:** fix `min-width` for Bootstrap 3.2 ([8dc13be9](https://github.com/angular-ui/bootstrap/commit/8dc13be9), closes [#4081](https://github.com/angular-ui/bootstrap/issues/4081), [#2511](https://github.com/angular-ui/bootstrap/issues/2511))
+* **tooltip:**
+ * add safety to `$apply` ([22b16f01](https://github.com/angular-ui/bootstrap/commit/22b16f01), closes [#3943](https://github.com/angular-ui/bootstrap/issues/3943), [#4150](https://github.com/angular-ui/bootstrap/issues/4150), [#516](https://github.com/angular-ui/bootstrap/issues/516))
+ * tooltip w/ template position ([895a2281](https://github.com/angular-ui/bootstrap/commit/895a2281))
+ * prevent opening when `tooltipPopupDelay` is present ([12c527af](https://github.com/angular-ui/bootstrap/commit/12c527af), closes [#4098](https://github.com/angular-ui/bootstrap/issues/4098), [#3611](https://github.com/angular-ui/bootstrap/issues/3611))
+* **typeahead:** return `null` if empty ([c7d3a660](https://github.com/angular-ui/bootstrap/commit/c7d3a660), closes [#4078](https://github.com/angular-ui/bootstrap/issues/4078), [#3176](https://github.com/angular-ui/bootstrap/issues/3176))
+
+
+#### Features
+
+* **accordion:**
+ * add `controllerAs` support ([9865ee8e](https://github.com/angular-ui/bootstrap/commit/9865ee8e), closes [#4138](https://github.com/angular-ui/bootstrap/issues/4138))
+ * add `templateUrl` support ([f777c320](https://github.com/angular-ui/bootstrap/commit/f777c320), closes [#4084](https://github.com/angular-ui/bootstrap/issues/4084))
+* **alert:** add `templateUrl` support ([88a885ca](https://github.com/angular-ui/bootstrap/commit/88a885ca), closes [#4139](https://github.com/angular-ui/bootstrap/issues/4139))
+* **buttons:** add `controllerAs` support ([02872dc1](https://github.com/angular-ui/bootstrap/commit/02872dc1), closes [#4140](https://github.com/angular-ui/bootstrap/issues/4140))
+* **carousel:**
+ * add `templateUrl` support ([a29c8f20](https://github.com/angular-ui/bootstrap/commit/a29c8f20), closes [#4141](https://github.com/angular-ui/bootstrap/issues/4141))
+ * expose carousel controller via `controllerAs` ([bfec07e4](https://github.com/angular-ui/bootstrap/commit/bfec07e4), closes [#4131](https://github.com/angular-ui/bootstrap/issues/4131))
+* **datepicker:**
+ * allow custom templates ([e04b06d7](https://github.com/angular-ui/bootstrap/commit/e04b06d7), closes [#4157](https://github.com/angular-ui/bootstrap/issues/4157), [#1913](https://github.com/angular-ui/bootstrap/issues/1913))
+ * add `onOpenFocus` support ([68afc4c6](https://github.com/angular-ui/bootstrap/commit/68afc4c6), closes [#2303](https://github.com/angular-ui/bootstrap/issues/2303), [#2546](https://github.com/angular-ui/bootstrap/issues/2546), [#4146](https://github.com/angular-ui/bootstrap/issues/4146))
+ * add support for dynamic `min-mode` and `max-mode` ([f3d263e1](https://github.com/angular-ui/bootstrap/commit/f3d263e1), closes [#3843](https://github.com/angular-ui/bootstrap/issues/3843), [#2618](https://github.com/angular-ui/bootstrap/issues/2618))
+ * allow suppression of log error ([bab1d375](https://github.com/angular-ui/bootstrap/commit/bab1d375), closes [#3836](https://github.com/angular-ui/bootstrap/issues/3836), [#4115](https://github.com/angular-ui/bootstrap/issues/4115))
+* **docs:**
+ * add explanation of eye icon ([265d429b](https://github.com/angular-ui/bootstrap/commit/265d429b), closes [#4120](https://github.com/angular-ui/bootstrap/issues/4120))
+ * add ngAnimate Plunker support ([a8a22cff](https://github.com/angular-ui/bootstrap/commit/a8a22cff), closes [#3648](https://github.com/angular-ui/bootstrap/issues/3648), [#4072](https://github.com/angular-ui/bootstrap/issues/4072))
+* **modal:**
+ * add ability to change class on body ([5a28ff76](https://github.com/angular-ui/bootstrap/commit/5a28ff76), closes [#2633](https://github.com/angular-ui/bootstrap/issues/2633), [#4132](https://github.com/angular-ui/bootstrap/issues/4132))
+ * allow users to resolve with strings ([89368856](https://github.com/angular-ui/bootstrap/commit/89368856), closes [#2676](https://github.com/angular-ui/bootstrap/issues/2676), [#4124](https://github.com/angular-ui/bootstrap/issues/4124))
+* **pagination:**
+ * add classes to assist with styling ([b21c9abd](https://github.com/angular-ui/bootstrap/commit/b21c9abd), closes [#4130](https://github.com/angular-ui/bootstrap/issues/4130), [#4142](https://github.com/angular-ui/bootstrap/issues/4142))
+ * add `templateUrl` support ([a0e1c91c](https://github.com/angular-ui/bootstrap/commit/a0e1c91c), closes [#4137](https://github.com/angular-ui/bootstrap/issues/4137))
+* **timepicker:**
+ * add documentation for max/min ([87fc242d](https://github.com/angular-ui/bootstrap/commit/87fc242d))
+ * Added min/max attributes for timepicker. ([6c0010be](https://github.com/angular-ui/bootstrap/commit/6c0010be), closes [#4019](https://github.com/angular-ui/bootstrap/issues/4019))
+* **tooltip:**
+ * remove unnecessary `$digest` ([901a7c66](https://github.com/angular-ui/bootstrap/commit/901a7c66), closes [#4151](https://github.com/angular-ui/bootstrap/issues/4151))
+ * add multiple trigger support ([ca9196fa](https://github.com/angular-ui/bootstrap/commit/ca9196fa), closes [#3987](https://github.com/angular-ui/bootstrap/issues/3987), [#4077](https://github.com/angular-ui/bootstrap/issues/4077))
+
+
+#### Breaking Changes
+
+* add `open` class to accordion group when expanded
+
+Closes #4152
+Closes #3419
+
+ ([ead15e37](https://github.com/angular-ui/bootstrap/commit/ead15e37))
+* Allow the user to hit `esc` inside an element in a modal and not exit the modal if the event has been `defaultPrevented`
+
+Closes #3551
+Fixes #2544
+
+ ([a05b9c1a](https://github.com/angular-ui/bootstrap/commit/a05b9c1a))
+* Change validation key to `dateDisabled` to align better with Angular's convention
+
+Closes #2773
+Closes #4080
+
+ ([5245ccad](https://github.com/angular-ui/bootstrap/commit/5245ccad))
+
+
+<a name"0.13.2"></a>
+### 0.13.2 (2015-08-02)
+
+
+#### Bug Fixes
+
+* **accordion:** apply disabled style to accordion-header ([0643fd3e](https://github.com/angular-ui/bootstrap/commit/0643fd3e), closes [#3599](https://github.com/angular-ui/bootstrap/issues/3599), [#3233](https://github.com/angular-ui/bootstrap/issues/3233))
+* **buttons:** respect disabled attribute ([42e1af5c](https://github.com/angular-ui/bootstrap/commit/42e1af5c), closes [#4026](https://github.com/angular-ui/bootstrap/issues/4026), [#4013](https://github.com/angular-ui/bootstrap/issues/4013))
+* **carousel:**
+ * fix animations with 1.4 ([f45b4a4c](https://github.com/angular-ui/bootstrap/commit/f45b4a4c), closes [#3946](https://github.com/angular-ui/bootstrap/issues/3946), [#4041](https://github.com/angular-ui/bootstrap/issues/4041), [#3811](https://github.com/angular-ui/bootstrap/issues/3811))
+ * clear `currentSlide` when there are no slides ([0c78026b](https://github.com/angular-ui/bootstrap/commit/0c78026b), closes [#4021](https://github.com/angular-ui/bootstrap/issues/4021))
+* **dateparser:** add type and validity check ([4f1e03f1](https://github.com/angular-ui/bootstrap/commit/4f1e03f1), closes [#3701](https://github.com/angular-ui/bootstrap/issues/3701), [#3759](https://github.com/angular-ui/bootstrap/issues/3759), [#3933](https://github.com/angular-ui/bootstrap/issues/3933), [#3609](https://github.com/angular-ui/bootstrap/issues/3609), [#3713](https://github.com/angular-ui/bootstrap/issues/3713), [#3736](https://github.com/angular-ui/bootstrap/issues/3736), [#3875](https://github.com/angular-ui/bootstrap/issues/3875), [#3937](https://github.com/angular-ui/bootstrap/issues/3937), [#3976](https://github.com/angular-ui/bootstrap/issues/3976))
+* **datepicker:**
+ * change to contains ([9f73d240](https://github.com/angular-ui/bootstrap/commit/9f73d240), closes [#4066](https://github.com/angular-ui/bootstrap/issues/4066), [#3076](https://github.com/angular-ui/bootstrap/issues/3076))
+ * *BREAKING CHANGE* remove `new Date` fallback ([ab4580fd](https://github.com/angular-ui/bootstrap/commit/ab4580fd), closes [#2513](https://github.com/angular-ui/bootstrap/issues/2513), [#3294](https://github.com/angular-ui/bootstrap/issues/3294), [#3344](https://github.com/angular-ui/bootstrap/issues/3344), [#3682](https://github.com/angular-ui/bootstrap/issues/3682), [#4092](https://github.com/angular-ui/bootstrap/issues/4092), [#1289](https://github.com/angular-ui/bootstrap/issues/1289), [#2446](https://github.com/angular-ui/bootstrap/issues/2446), [#3037](https://github.com/angular-ui/bootstrap/issues/3037), [#3104](https://github.com/angular-ui/bootstrap/issues/3104), [#3196](https://github.com/angular-ui/bootstrap/issues/3196), [#3206](https://github.com/angular-ui/bootstrap/issues/3206), [#3342](https://github.com/angular-ui/bootstrap/issues/3342), [#3617](https://github.com/angular-ui/bootstrap/issues/3617), [#3644](https://github.com/angular-ui/bootstrap/issues/3644))
+ * ensure `initDate` is on an object ([577b2a2a](https://github.com/angular-ui/bootstrap/commit/577b2a2a), closes [#3625](https://github.com/angular-ui/bootstrap/issues/3625))
+ * change to higher max date ([32e73280](https://github.com/angular-ui/bootstrap/commit/32e73280), closes [#4042](https://github.com/angular-ui/bootstrap/issues/4042))
+ * fix validation with `ngRequired` ([fe0d954a](https://github.com/angular-ui/bootstrap/commit/fe0d954a), closes [#4002](https://github.com/angular-ui/bootstrap/issues/4002), [#3862](https://github.com/angular-ui/bootstrap/issues/3862))
+ * set to `null` if not present ([a65a5fa1](https://github.com/angular-ui/bootstrap/commit/a65a5fa1), closes [#4014](https://github.com/angular-ui/bootstrap/issues/4014))
+* **dropdown:** add safety check for setIsOpen ([60e43160](https://github.com/angular-ui/bootstrap/commit/60e43160), closes [#4030](https://github.com/angular-ui/bootstrap/issues/4030))
+* **modal:**
+ * properly garbage collect DOM node ([1e8297be](https://github.com/angular-ui/bootstrap/commit/1e8297be), closes [#2875](https://github.com/angular-ui/bootstrap/issues/2875))
+ * fix `bindToController` implementation ([811bf96e](https://github.com/angular-ui/bootstrap/commit/811bf96e), closes [#4054](https://github.com/angular-ui/bootstrap/issues/4054), [#4051](https://github.com/angular-ui/bootstrap/issues/4051))
+ * animate backdrop concurrently with window ([c55ee4f5](https://github.com/angular-ui/bootstrap/commit/c55ee4f5), closes [#4039](https://github.com/angular-ui/bootstrap/issues/4039), [#4036](https://github.com/angular-ui/bootstrap/issues/4036))
+* **progressbar:**
+ * use more visible color ([1afc5d1d](https://github.com/angular-ui/bootstrap/commit/1afc5d1d), closes [#4044](https://github.com/angular-ui/bootstrap/issues/4044))
+ * allow max width of 100% ([2e9177e5](https://github.com/angular-ui/bootstrap/commit/2e9177e5), closes [#4027](https://github.com/angular-ui/bootstrap/issues/4027), [#4018](https://github.com/angular-ui/bootstrap/issues/4018))
+* **tooltip:**
+ * update tooltip placement dynamically ([13df1c93](https://github.com/angular-ui/bootstrap/commit/13df1c93), closes [#3980](https://github.com/angular-ui/bootstrap/issues/3980), [#3978](https://github.com/angular-ui/bootstrap/issues/3978))
+ * prevent 1px shift in Webkit/Blink ([632aa820](https://github.com/angular-ui/bootstrap/commit/632aa820), closes [#3964](https://github.com/angular-ui/bootstrap/issues/3964))
+* **typeahead:**
+ * reset matches if enter is hit ([25704838](https://github.com/angular-ui/bootstrap/commit/25704838), closes [#4063](https://github.com/angular-ui/bootstrap/issues/4063), [#3545](https://github.com/angular-ui/bootstrap/issues/3545))
+ * only reset matches if matches are present ([97e077e1](https://github.com/angular-ui/bootstrap/commit/97e077e1), closes [#3119](https://github.com/angular-ui/bootstrap/issues/3119))
+
+
+#### Features
+
+* **build:** add support for npm publishing ([27f7ca26](https://github.com/angular-ui/bootstrap/commit/27f7ca26), closes [#3108](https://github.com/angular-ui/bootstrap/issues/3108))
+* **modal:** trap focus in modal for tabbing ([a028d2aa](https://github.com/angular-ui/bootstrap/commit/a028d2aa), closes [#3689](https://github.com/angular-ui/bootstrap/issues/3689), [#4004](https://github.com/angular-ui/bootstrap/issues/4004), [#738](https://github.com/angular-ui/bootstrap/issues/738))
+* **popover:** add custom template support ([a9d3d253](https://github.com/angular-ui/bootstrap/commit/a9d3d253), closes [#4056](https://github.com/angular-ui/bootstrap/issues/4056), [#4057](https://github.com/angular-ui/bootstrap/issues/4057))
+* **rating:** add title support for stars ([713c8487](https://github.com/angular-ui/bootstrap/commit/713c8487), closes [#3621](https://github.com/angular-ui/bootstrap/issues/3621))
+* **typeahead:**
+ * add `noResults` indicator binding ([647cdd93](https://github.com/angular-ui/bootstrap/commit/647cdd93), closes [#2016](https://github.com/angular-ui/bootstrap/issues/2016), [#2792](https://github.com/angular-ui/bootstrap/issues/2792), [#4068](https://github.com/angular-ui/bootstrap/issues/4068))
+ * add `typeaheadSelectOnExact` support ([277b30ca](https://github.com/angular-ui/bootstrap/commit/277b30ca), closes [#3365](https://github.com/angular-ui/bootstrap/issues/3365), [#3310](https://github.com/angular-ui/bootstrap/issues/3310))
+
+
+<a name"0.13.1"></a>
+### 0.13.1 (2015-07-23)
+
+
+#### Bug Fixes
+
+* **accordion:** add CSP compliance for accordion & typeahead ([fb302c60](https://github.com/angular-ui/bootstrap/commit/fb302c60), closes [#3909](https://github.com/angular-ui/bootstrap/issues/3909), [#3904](https://github.com/angular-ui/bootstrap/issues/3904))
+* **alert:**
+ * adjust check for close attribute ([13a0354f](https://github.com/angular-ui/bootstrap/commit/13a0354f), closes [#3864](https://github.com/angular-ui/bootstrap/issues/3864), [#3890](https://github.com/angular-ui/bootstrap/issues/3890), [#3848](https://github.com/angular-ui/bootstrap/issues/3848))
+ * rename alert-dismissable to alert-dismissible ([d631af5a](https://github.com/angular-ui/bootstrap/commit/d631af5a))
+* **carousel:**
+ * change to avoid references to debug info ([ca07ad7c](https://github.com/angular-ui/bootstrap/commit/ca07ad7c), closes [#3795](https://github.com/angular-ui/bootstrap/issues/3795), [#3794](https://github.com/angular-ui/bootstrap/issues/3794))
+ * ensure there are slides present ([115d490a](https://github.com/angular-ui/bootstrap/commit/115d490a), closes [#3755](https://github.com/angular-ui/bootstrap/issues/3755))
+ * disable transition until animation completes ([ef45ecf8](https://github.com/angular-ui/bootstrap/commit/ef45ecf8), closes [#3729](https://github.com/angular-ui/bootstrap/issues/3729), [#3757](https://github.com/angular-ui/bootstrap/issues/3757))
+* **collapse:** fix occasional flickering ([ede9ea46](https://github.com/angular-ui/bootstrap/commit/ede9ea46), closes [#3804](https://github.com/angular-ui/bootstrap/issues/3804), [#3801](https://github.com/angular-ui/bootstrap/issues/3801))
+* **datepicker:**
+ * change to min width cells ([5567c432](https://github.com/angular-ui/bootstrap/commit/5567c432), closes [#4000](https://github.com/angular-ui/bootstrap/issues/4000), [#3941](https://github.com/angular-ui/bootstrap/issues/3941))
+ * fix OS dependent time zone issue ([f1412014](https://github.com/angular-ui/bootstrap/commit/f1412014), closes [#3079](https://github.com/angular-ui/bootstrap/issues/3079))
+ * Apply custom class to month ([eb3b32ec](https://github.com/angular-ui/bootstrap/commit/eb3b32ec), closes [#3863](https://github.com/angular-ui/bootstrap/issues/3863))
+ * check if getter.assign is function ([ed10899d](https://github.com/angular-ui/bootstrap/commit/ed10899d), closes [#3155](https://github.com/angular-ui/bootstrap/issues/3155), [#3345](https://github.com/angular-ui/bootstrap/issues/3345), [#3719](https://github.com/angular-ui/bootstrap/issues/3719))
+* **dropdown:**
+ * do not autoclose with outsideClick and append to body ([cc66a068](https://github.com/angular-ui/bootstrap/commit/cc66a068), closes [#3792](https://github.com/angular-ui/bootstrap/issues/3792), [#3645](https://github.com/angular-ui/bootstrap/issues/3645))
+ * avoid matching 138 & 140 ([41ebd984](https://github.com/angular-ui/bootstrap/commit/41ebd984))
+ * align when using dropdown-menu-body ([2332f14d](https://github.com/angular-ui/bootstrap/commit/2332f14d), closes [#3913](https://github.com/angular-ui/bootstrap/issues/3913), [#3820](https://github.com/angular-ui/bootstrap/issues/3820))
+ * call toggle after animation ([054341b7](https://github.com/angular-ui/bootstrap/commit/054341b7), closes [#3513](https://github.com/angular-ui/bootstrap/issues/3513), [#3655](https://github.com/angular-ui/bootstrap/issues/3655), [#3511](https://github.com/angular-ui/bootstrap/issues/3511))
+ * do not close on $locationChangeSuccess ([e5a1e88f](https://github.com/angular-ui/bootstrap/commit/e5a1e88f), closes [#3683](https://github.com/angular-ui/bootstrap/issues/3683), [#3704](https://github.com/angular-ui/bootstrap/issues/3704))
+* **modal:**
+ * backdrop animation on AngularJS 1.4 ([158d2676](https://github.com/angular-ui/bootstrap/commit/158d2676), closes [#3896](https://github.com/angular-ui/bootstrap/issues/3896))
+ * closing breaks on missing scope, 1.4 ([0286828b](https://github.com/angular-ui/bootstrap/commit/0286828b), closes [#3787](https://github.com/angular-ui/bootstrap/issues/3787), [#3806](https://github.com/angular-ui/bootstrap/issues/3806), [#3873](https://github.com/angular-ui/bootstrap/issues/3873), [#3888](https://github.com/angular-ui/bootstrap/issues/3888))
+ * remove illegal character ([dd4f3cc8](https://github.com/angular-ui/bootstrap/commit/dd4f3cc8), closes [#3893](https://github.com/angular-ui/bootstrap/issues/3893), [#3892](https://github.com/angular-ui/bootstrap/issues/3892))
+ * focus on body if element disappears ([988336cc](https://github.com/angular-ui/bootstrap/commit/988336cc), closes [#3653](https://github.com/angular-ui/bootstrap/issues/3653), [#3639](https://github.com/angular-ui/bootstrap/issues/3639))
+* **progressbar:** use max value on stacked progress bar ([36e0f0ea](https://github.com/angular-ui/bootstrap/commit/36e0f0ea), closes [#3830](https://github.com/angular-ui/bootstrap/issues/3830), [#3618](https://github.com/angular-ui/bootstrap/issues/3618))
+* **rating:** Set rating to 0 when same value is selected ([dbceec76](https://github.com/angular-ui/bootstrap/commit/dbceec76), closes [#3963](https://github.com/angular-ui/bootstrap/issues/3963), [#3246](https://github.com/angular-ui/bootstrap/issues/3246))
+* **tabs:** fix empty href ([2b27dcbf](https://github.com/angular-ui/bootstrap/commit/2b27dcbf), closes [#3799](https://github.com/angular-ui/bootstrap/issues/3799))
+* **typeahead:**
+ * select match on tab for iOS webview ([5b37bb8b](https://github.com/angular-ui/bootstrap/commit/5b37bb8b), closes [#3762](https://github.com/angular-ui/bootstrap/issues/3762), [#3699](https://github.com/angular-ui/bootstrap/issues/3699))
+ * don't close popup on right click ([7d1c4600](https://github.com/angular-ui/bootstrap/commit/7d1c4600), closes [#3975](https://github.com/angular-ui/bootstrap/issues/3975), [#3973](https://github.com/angular-ui/bootstrap/issues/3973))
+ * close dropdown on tab with no selection ([493510d0](https://github.com/angular-ui/bootstrap/commit/493510d0), closes [#3340](https://github.com/angular-ui/bootstrap/issues/3340))
+ * do not execute unnecessary $digest ([0d96221f](https://github.com/angular-ui/bootstrap/commit/0d96221f), closes [#2652](https://github.com/angular-ui/bootstrap/issues/2652), [#3791](https://github.com/angular-ui/bootstrap/issues/3791))
+ * add href to show cursor as pointer ([195e520e](https://github.com/angular-ui/bootstrap/commit/195e520e), closes [#3649](https://github.com/angular-ui/bootstrap/issues/3649))
+
+
+#### Features
+
+* **alert:** pass $event to close() ([44e06425](https://github.com/angular-ui/bootstrap/commit/44e06425), closes [#3828](https://github.com/angular-ui/bootstrap/issues/3828), [#3827](https://github.com/angular-ui/bootstrap/issues/3827))
+* **carousel:** add `noWrap` option to prevent re-cycling of slides ([7fb3840f](https://github.com/angular-ui/bootstrap/commit/7fb3840f), closes [#3462](https://github.com/angular-ui/bootstrap/issues/3462), [#3397](https://github.com/angular-ui/bootstrap/issues/3397))
+* **collapse:** add accessibility support ([92551342](https://github.com/angular-ui/bootstrap/commit/92551342), closes [#3920](https://github.com/angular-ui/bootstrap/issues/3920))
+* **dropdown:**
+ * add dropdown classes dynamically ([4af83ade](https://github.com/angular-ui/bootstrap/commit/4af83ade), closes [#3984](https://github.com/angular-ui/bootstrap/issues/3984), [#3986](https://github.com/angular-ui/bootstrap/issues/3986))
+ * add accessibility attributes ([14689e05](https://github.com/angular-ui/bootstrap/commit/14689e05), closes [#3951](https://github.com/angular-ui/bootstrap/issues/3951))
+ * add keynav support to dropdown ([62359370](https://github.com/angular-ui/bootstrap/commit/62359370), closes [#3685](https://github.com/angular-ui/bootstrap/issues/3685), [#3212](https://github.com/angular-ui/bootstrap/issues/3212), [#1228](https://github.com/angular-ui/bootstrap/issues/1228))
+ * support optional templates for dropdown menus ([83c4266c](https://github.com/angular-ui/bootstrap/commit/83c4266c))
+* **modal:** add support for bindToController ([8adfc833](https://github.com/angular-ui/bootstrap/commit/8adfc833), closes [#3965](https://github.com/angular-ui/bootstrap/issues/3965), [#3404](https://github.com/angular-ui/bootstrap/issues/3404))
+* **pagination:** add support for `ng-disabled` ([f6edfa5d](https://github.com/angular-ui/bootstrap/commit/f6edfa5d), closes [#3956](https://github.com/angular-ui/bootstrap/issues/3956))
+* **timepicker:** add `showSpinner` flag ([1f760eb3](https://github.com/angular-ui/bootstrap/commit/1f760eb3))
+* **typeahead:**
+ * add 'select on blur' option. ([68cac59a](https://github.com/angular-ui/bootstrap/commit/68cac59a), closes [#3445](https://github.com/angular-ui/bootstrap/issues/3445))
+ * popup position ([86bfec19](https://github.com/angular-ui/bootstrap/commit/86bfec19), closes [#3874](https://github.com/angular-ui/bootstrap/issues/3874))
+ * handles min-length of 0 ([a5a25141](https://github.com/angular-ui/bootstrap/commit/a5a25141), closes [#3600](https://github.com/angular-ui/bootstrap/issues/3600))
+
+
+<a name="0.13.0"></a>
+## 0.13.0 (2015-05-02)
+
+
+#### Bug Fixes
+
+* **accordion:**
+ * Made accordion heading tab-able for IE9-10 ([6abad509](https://github.com/angular-ui/bootstrap/commit/6abad509cd4d44c3ca432f2f21c9ecea0a206b53))
+ * noop for href in header to prevent page refresh with nested buttons canceling ev ([9ca4ec39](https://github.com/angular-ui/bootstrap/commit/9ca4ec399be0e0e8f6c3fe6fd924a7d94ce669b5))
+* **buttons:** add unit tests for buttons ([9468d723](https://github.com/angular-ui/bootstrap/commit/9468d7239dd6eed4a3a2945f6761f7a2fa97222b), closes [#3030](https://github.com/angular-ui/bootstrap/issues/3030))
+* **carousel:** respect the order of the slides ([b5f220fa](https://github.com/angular-ui/bootstrap/commit/b5f220fa8483f5743ba6ab3610f5064bf5c71be7), closes [#488](https://github.com/angular-ui/bootstrap/issues/488))
+* **changelog:** add comment on breaking change ([f02c1bbb](https://github.com/angular-ui/bootstrap/commit/f02c1bbbf7777bee9cbb4a038730fb475337a2c5), closes [#2675](https://github.com/angular-ui/bootstrap/issues/2675))
+* **dateparser:** add extra validation constraint to days ([c19b8879](https://github.com/angular-ui/bootstrap/commit/c19b8879e902e8753b4077e7983ec629242436fc))
+* **datepicker:**
+ * week count issues ([39e5fd3e](https://github.com/angular-ui/bootstrap/commit/39e5fd3e4981f311d237d21c37a89cde9f42f0d6), closes [#2506](https://github.com/angular-ui/bootstrap/issues/2506), [#3120](https://github.com/angular-ui/bootstrap/issues/3120), [#2306](https://github.com/angular-ui/bootstrap/issues/2306))
+ * make 'show-weeks' work on datepickerPopup ([d0cc7284](https://github.com/angular-ui/bootstrap/commit/d0cc72841b9641b768cc5eb184de2dbbaa804e2d), closes [#3143](https://github.com/angular-ui/bootstrap/issues/3143), [#3149](https://github.com/angular-ui/bootstrap/issues/3149))
+ * datepicker-popup compatibility with ngModelOptions ([d024dd77](https://github.com/angular-ui/bootstrap/commit/d024dd77ed6a20983bea5b90b75481c93f17980f), closes [#3349](https://github.com/angular-ui/bootstrap/issues/3349))
+ * disable title button when in max mode ([35b8512a](https://github.com/angular-ui/bootstrap/commit/35b8512ac7949eba7d432760f83748bb2bb893c1), closes [#3012](https://github.com/angular-ui/bootstrap/issues/3012))
+ * add shortcutPropagation to datepickerPopup ([13bd516c](https://github.com/angular-ui/bootstrap/commit/13bd516cfcc1b2ee940112675830f7ce3d93ea4f))
+ * fixed shortcut event kill by adding option ([89ab4580](https://github.com/angular-ui/bootstrap/commit/89ab4580cd3d0bbdf63e02fbebe2cb3a9f2616dd))
+ * fix initDate implementation in datepicker ([98e2bdfc](https://github.com/angular-ui/bootstrap/commit/98e2bdfc8b4dd108acdf3fac75a795675889bbc7))
+ * Fix init-date not applying on datepicker-popup ([c5b63ded](https://github.com/angular-ui/bootstrap/commit/c5b63ded0aebd7ae80f238bd0a33f1d9c0746dba))
+ * Make datepicker respect dateFormat inside ng-if ([2c2dba6d](https://github.com/angular-ui/bootstrap/commit/2c2dba6d145c95500efe7f6be6248d56ae1aebee))
+ * `ng-model` value can be a timestamp ([d253208b](https://github.com/angular-ui/bootstrap/commit/d253208bd7ebbd6209c6a25f70e010123198fcd7), closes [#2345](https://github.com/angular-ui/bootstrap/issues/2345))
+ * Parse date from $viewValue instead of $modelValue ([0ecf7faa](https://github.com/angular-ui/bootstrap/commit/0ecf7faad3b340e171e5c8ca17a17597fa6e6596))
+ * don't stop ESC propagation unless dropdown is open ([c2e5b284](https://github.com/angular-ui/bootstrap/commit/c2e5b284a31fc992b8230b89dc98ed757d155493), closes [#3096](https://github.com/angular-ui/bootstrap/issues/3096), [#3179](https://github.com/angular-ui/bootstrap/issues/3179))
+ * date formatting when using angular 1.3 fixes #2659 ([23936f9f](https://github.com/angular-ui/bootstrap/commit/23936f9f6ec7170b56c7f13345ae022c74fa3034), closes [#3293](https://github.com/angular-ui/bootstrap/issues/3293), [#3279](https://github.com/angular-ui/bootstrap/issues/3279), [#2440](https://github.com/angular-ui/bootstrap/issues/2440), [#2932](https://github.com/angular-ui/bootstrap/issues/2932), [#3074](https://github.com/angular-ui/bootstrap/issues/3074), [#2943](https://github.com/angular-ui/bootstrap/issues/2943), [#2733](https://github.com/angular-ui/bootstrap/issues/2733), [#3047](https://github.com/angular-ui/bootstrap/issues/3047), [#2659](https://github.com/angular-ui/bootstrap/issues/2659), [#2681](https://github.com/angular-ui/bootstrap/issues/2681))
+ * date formatting when using angular 1.3 fixes #2659 ([5f9afe5a](https://github.com/angular-ui/bootstrap/commit/5f9afe5a86af0e207eaacd6a9b1f202fd78d7009))
+* **demo:** Modify the demo app to play nice with Angular 1.3 ([aa0b6392](https://github.com/angular-ui/bootstrap/commit/aa0b6392db57d436d7c203cf05555d708c945322), closes [#3098](https://github.com/angular-ui/bootstrap/issues/3098))
+* **dropdown:** Fix $digest:inprog on dropdown dismissal ([4a06adba](https://github.com/angular-ui/bootstrap/commit/4a06adbac6c1c1fa6b0182ca9bd7335eda89c43f), closes [#3274](https://github.com/angular-ui/bootstrap/issues/3274))
+* **grunt:** fix typo in gruntfile ([f0cadb1f](https://github.com/angular-ui/bootstrap/commit/f0cadb1f1a6b8d994c2df3313a2121e92a36bddb), closes [#3589](https://github.com/angular-ui/bootstrap/issues/3589))
+* **modal:**
+ * Use attribute observe and add a render promise. ([99af5f8a](https://github.com/angular-ui/bootstrap/commit/99af5f8a369b13b018ec1e592d82a1a140cbb6bb))
+ * fix minor grammar error ([22a21448](https://github.com/angular-ui/bootstrap/commit/22a21448cbad1448bd4541bd0ce3fc8d3515943d), closes [#3519](https://github.com/angular-ui/bootstrap/issues/3519))
+ * Fix focus when the dialog is close or cancelled ([e6b105ae](https://github.com/angular-ui/bootstrap/commit/e6b105ae39bcbcf468c3e32057c6acb5ab50d4ce), closes [#2888](https://github.com/angular-ui/bootstrap/issues/2888))
+ * allow for custom user modal sizes ([85eeb954](https://github.com/angular-ui/bootstrap/commit/85eeb95428e0dd367cf3e251f2d01fc8dc899dd4), closes [#3429](https://github.com/angular-ui/bootstrap/issues/3429), [#3431](https://github.com/angular-ui/bootstrap/issues/3431))
+ * Autofocus corrects the second time that the modal is open ([e5f5f75b](https://github.com/angular-ui/bootstrap/commit/e5f5f75b370b6d4806da87bec575b7084e30c520), closes [#2802](https://github.com/angular-ui/bootstrap/issues/2802))
+ * fix messages on modal test failed ([ab919f9f](https://github.com/angular-ui/bootstrap/commit/ab919f9f89aeaaa336b5d3fe1aed1e0617b5a482))
+* **pagination:**
+ * remove focus from prior clicked elements ([33269bb6](https://github.com/angular-ui/bootstrap/commit/33269bb6b444cdca18e08063814d39c5ef502589), closes [#3488](https://github.com/angular-ui/bootstrap/issues/3488), [#3486](https://github.com/angular-ui/bootstrap/issues/3486))
+ * fixes issue when init called after watch triggered ([26b40903](https://github.com/angular-ui/bootstrap/commit/26b40903abf012b5d3d35154d6210119ac9a76d4), closes [#2257](https://github.com/angular-ui/bootstrap/issues/2257), [#2227](https://github.com/angular-ui/bootstrap/issues/2227))
+* **popover:**
+ * prevent wrong positioning from title ([c8156c7e](https://github.com/angular-ui/bootstrap/commit/c8156c7e21d0f3a61fc19d59644ae24c423eb5c6), closes [#3518](https://github.com/angular-ui/bootstrap/issues/3518))
+ * animations with ngAnimate ([c2ace472](https://github.com/angular-ui/bootstrap/commit/c2ace47225ecb337328a16d2c95744e0d37ce80f), closes [#3509](https://github.com/angular-ui/bootstrap/issues/3509), [#3375](https://github.com/angular-ui/bootstrap/issues/3375), [#3506](https://github.com/angular-ui/bootstrap/issues/3506))
+ * make it work with ngAnimate ([461087b5](https://github.com/angular-ui/bootstrap/commit/461087b5ff360e1d06d6724375ab29169a89fcf2), closes [#3482](https://github.com/angular-ui/bootstrap/issues/3482), [#3375](https://github.com/angular-ui/bootstrap/issues/3375))
+* **progressbar:** limit max width to 100% ([489961e1](https://github.com/angular-ui/bootstrap/commit/489961e1a0036ddab4e719a772382209a595f163), closes [#3005](https://github.com/angular-ui/bootstrap/issues/3005))
+* **tab:** change to `disable` attribute ([4bfae223](https://github.com/angular-ui/bootstrap/commit/4bfae2238d08d7edea8e6dfe99051192a16d6587), closes [#2677](https://github.com/angular-ui/bootstrap/issues/2677))
+* **timepicker:**
+ * move render logic to formatter ([b4bbc019](https://github.com/angular-ui/bootstrap/commit/b4bbc0198284d90085bd85840dffd030345d5211), closes [#3160](https://github.com/angular-ui/bootstrap/issues/3160), [#3427](https://github.com/angular-ui/bootstrap/issues/3427))
+ * remove ng-mousewheel binding ([a726b7cd](https://github.com/angular-ui/bootstrap/commit/a726b7cd47d417ed656aef3af012e7b6c7b00bf4), closes [#3442](https://github.com/angular-ui/bootstrap/issues/3442))
+ * fix widths of inputs when inside form-inline ([8e89440b](https://github.com/angular-ui/bootstrap/commit/8e89440ba86d26d74ed799843cde7f9f2bf26c0b))
+ * Stringify pad return when value >= 10 ([405dab65](https://github.com/angular-ui/bootstrap/commit/405dab65f72f5bed488eb8f5dfa5a1a848c4a606))
+* **tooltip:**
+ * template type should respect popup class ([6af627a8](https://github.com/angular-ui/bootstrap/commit/6af627a8edcbce0370ca2d90f9a575cd6770f6c1), closes [#3569](https://github.com/angular-ui/bootstrap/issues/3569))
+ * tooltip-html should not open if empty ([34044a77](https://github.com/angular-ui/bootstrap/commit/34044a77070bc809220e2ed6b628393889c40b86), closes [#3563](https://github.com/angular-ui/bootstrap/issues/3563))
+ * use correct prefix for -template ([9ca9d7f5](https://github.com/angular-ui/bootstrap/commit/9ca9d7f5263d8d5e0a9de18c2b75f64aca7c5255), closes [#3498](https://github.com/angular-ui/bootstrap/issues/3498), [#3473](https://github.com/angular-ui/bootstrap/issues/3473))
+ * Fix for issue #3167 ([87a36076](https://github.com/angular-ui/bootstrap/commit/87a3607632cae03ead57b377bb91ca27610e7730))
+* **typeahead:**
+ * Fix for memory-leak in typeahead ([b5a80c08](https://github.com/angular-ui/bootstrap/commit/b5a80c08f2364db2170766366cc7433661e737ae))
+ * reset 'parse' validation key ([c0a9c707](https://github.com/angular-ui/bootstrap/commit/c0a9c707903fa3dfc662887cd348ee2b0bf13f85), closes [#3166](https://github.com/angular-ui/bootstrap/issues/3166))
+ * resolve property length of undefined error ([950c22cd](https://github.com/angular-ui/bootstrap/commit/950c22cdab3d0b3479a0d0515ed64e57c9ff046b), closes [#2999](https://github.com/angular-ui/bootstrap/issues/2999), [#3178](https://github.com/angular-ui/bootstrap/issues/3178))
+ * set validity if model is set manually ([b0044433](https://github.com/angular-ui/bootstrap/commit/b004443371d75bb61e9a17a00a58b485c1279aee), closes [#3318](https://github.com/angular-ui/bootstrap/issues/3318))
+ * $compile match template after adding to DOM ([03446c56](https://github.com/angular-ui/bootstrap/commit/03446c56335d5ee0970f9730af215fea1dd53f48))
+
+
+#### Features
+
+* **dateparser:**
+ * Add support for HH, H, mm, m, ss, s formats ([971a1b57](https://github.com/angular-ui/bootstrap/commit/971a1b57394c1e1088564e0809c1341620586aa0), closes [#2509](https://github.com/angular-ui/bootstrap/issues/2509), [#3159](https://github.com/angular-ui/bootstrap/issues/3159), [#3417](https://github.com/angular-ui/bootstrap/issues/3417))
+ * add support for milliseconds ([82cb637d](https://github.com/angular-ui/bootstrap/commit/82cb637dd12288d9fa0d42783f672fc71b94ffda), closes [#3537](https://github.com/angular-ui/bootstrap/issues/3537))
+* **datepicker:**
+ * support HTML5 month input type ([aef8953c](https://github.com/angular-ui/bootstrap/commit/aef8953c792066c008d8ce97918153f756a39112), closes [#3499](https://github.com/angular-ui/bootstrap/issues/3499))
+ * support HTML5 date input type ([1a9e88fe](https://github.com/angular-ui/bootstrap/commit/1a9e88fe9e6a078943273012429788e742f8ebbd), closes [#3499](https://github.com/angular-ui/bootstrap/issues/3499))
+ * Add custom class to specific days via outside logic ([0bcd30c4](https://github.com/angular-ui/bootstrap/commit/0bcd30c4a6d65763e1c4d1b6820a4537a11e95ee))
+* **dropdown:**
+ * Dropdown append-to-body ([dfe9854b](https://github.com/angular-ui/bootstrap/commit/dfe9854be3d0ae82f361cefec19a6f692aa41591), closes [#3411](https://github.com/angular-ui/bootstrap/issues/3411), [#1030](https://github.com/angular-ui/bootstrap/issues/1030))
+ * Make Auto-Close Dropdowns optional. ([a50f1120](https://github.com/angular-ui/bootstrap/commit/a50f11201eeb18569dca0ac3bb157e43cb9d9076), closes [#2218](https://github.com/angular-ui/bootstrap/issues/2218), [#3045](https://github.com/angular-ui/bootstrap/issues/3045))
+* **modal:**
+ * Add a vetoable modal.closing event ([a5a82d9b](https://github.com/angular-ui/bootstrap/commit/a5a82d9be7dc0bd1cfd510bacf9aa411c6efe1bc))
+ * pass reason when opened promise rejected ([0ad208d6](https://github.com/angular-ui/bootstrap/commit/0ad208d6a0164517b85d8e8181e4a0fc98f4f5ec), closes [#2978](https://github.com/angular-ui/bootstrap/issues/2978))
+ * add option to disable animations ([5e661d47](https://github.com/angular-ui/bootstrap/commit/5e661d47d6698fdfebb52402eb1687e5697c0040), closes [#1007](https://github.com/angular-ui/bootstrap/issues/1007), [#2725](https://github.com/angular-ui/bootstrap/issues/2725))
+* **popover:**
+ * respect popover-class option ([88a41dce](https://github.com/angular-ui/bootstrap/commit/88a41dce86c33bf1e0665d880ca68d3535aed553), closes [#3569](https://github.com/angular-ui/bootstrap/issues/3569))
+ * use expression to fix usage with $sce ([422c8234](https://github.com/angular-ui/bootstrap/commit/422c823460663151e3482275d9c6749bb714a415), closes [#3558](https://github.com/angular-ui/bootstrap/issues/3558))
+ * add popover-template directive ([7e3179ab](https://github.com/angular-ui/bootstrap/commit/7e3179ab9fdbba6c00ff1c30f97b432b58f9eafb))
+* **progressbar:** allow dynamic update to max ([7ccff028](https://github.com/angular-ui/bootstrap/commit/7ccff028ff5ed19af63d9cf1f5e078223924f3a0))
+* **rating:** add rounding logic to rating value ([b076483c](https://github.com/angular-ui/bootstrap/commit/b076483caa9b672068ae8d0cbdfeaed68f530861), closes [#3413](https://github.com/angular-ui/bootstrap/issues/3413), [#3415](https://github.com/angular-ui/bootstrap/issues/3415))
+* **tabs:** it should not select first not active tab as selected ([91b5fb62](https://github.com/angular-ui/bootstrap/commit/91b5fb62eedbb600d6a6abe32376846f327a903d))
+* **timepicker:**
+ * always pad minutes ([6324486d](https://github.com/angular-ui/bootstrap/commit/6324486d70edc01fb28f61f0a68a6a490378d602), closes [#1598](https://github.com/angular-ui/bootstrap/issues/1598), [#3533](https://github.com/angular-ui/bootstrap/issues/3533))
+ * have up/down arrow keys control time selection ([22961157](https://github.com/angular-ui/bootstrap/commit/22961157ad4636db12336abba54cc893554b99d6))
+* **tooltip:**
+ * use expression to fix usage with $sce ([d867f830](https://github.com/angular-ui/bootstrap/commit/d867f8302d4632a34c81d151923b497f9af3fcfd), closes [#3558](https://github.com/angular-ui/bootstrap/issues/3558))
+ * add tooltip-html directive ([e31fcf0f](https://github.com/angular-ui/bootstrap/commit/e31fcf0fcb06580064d1e6375dbedb69f1c95f25), closes [#3496](https://github.com/angular-ui/bootstrap/issues/3496))
+ * add tooltip-template directive ([a1695114](https://github.com/angular-ui/bootstrap/commit/a1695114a245312878d315dfc9e369f98d573eae), closes [#220](https://github.com/angular-ui/bootstrap/issues/220))
+ * update position dynamically ([853fa457](https://github.com/angular-ui/bootstrap/commit/853fa4578a1f127fee9283e725d6e19789882121), closes [#96](https://github.com/angular-ui/bootstrap/issues/96), [#1109](https://github.com/angular-ui/bootstrap/issues/1109), [#2816](https://github.com/angular-ui/bootstrap/issues/2816), [#3435](https://github.com/angular-ui/bootstrap/issues/3435))
+ * Support for tooltip-class configuration ([d784354a](https://github.com/angular-ui/bootstrap/commit/d784354a53fa40597cb8c124405ea9a90b6f0b8e), closes [#3126](https://github.com/angular-ui/bootstrap/issues/3126))
+* **transition:** deprecate transition module ([8a552443](https://github.com/angular-ui/bootstrap/commit/8a552443741d1e5b4b29d9da9c7e9990fa37886c), closes [#3497](https://github.com/angular-ui/bootstrap/issues/3497))
+
+
+# 0.12.1 (2015-02-20)
+
+## Bug Fixes
+
+- **tooltip:**
+ - incorrect position when text wraps ([5726e3ef](http://github.com/angular-ui/bootstrap/commit/5726e3ef))
+
+<a name="0.12.0"></a>
+# 0.12.0 (2014-11-16)
+
+
+## Bug Fixes
+
+* **accordion:** make header links keyboard accessible ([992b2329](http://github.com/angular-ui/bootstrap/commit/992b23297cd100ab4e236fba469e3a70566a4163), closes [#2869](http://github.com/angular-ui/bootstrap/issues/2869))
+* **build:** make custom builds on demo site work ([390f2bf6](http://github.com/angular-ui/bootstrap/commit/390f2bf6b0846ee640e86ad87bbae8c449e53026), closes [#2960](http://github.com/angular-ui/bootstrap/issues/2960), [#2847](http://github.com/angular-ui/bootstrap/issues/2847), [#2625](http://github.com/angular-ui/bootstrap/issues/2625), [#2489](http://github.com/angular-ui/bootstrap/issues/2489), [#2357](http://github.com/angular-ui/bootstrap/issues/2357), [#2176](http://github.com/angular-ui/bootstrap/issues/2176), [#2892](http://github.com/angular-ui/bootstrap/issues/2892))
+* **carousel:** replaced $timeout with $interval when it was wrong ([392c0ad1](http://github.com/angular-ui/bootstrap/commit/392c0ad13ca9b65be5e77ac0c68de24ead8ea2ce), closes [#1308](http://github.com/angular-ui/bootstrap/issues/1308), [#2454](http://github.com/angular-ui/bootstrap/issues/2454), [#2776](http://github.com/angular-ui/bootstrap/issues/2776))
+* **datepicker:** correct button alignment when using bootstrap v3.2.0 ([460fbec7](http://github.com/angular-ui/bootstrap/commit/460fbec776c6d08d0e7db40aedd29d10ac48d7e9), closes [#2728](http://github.com/angular-ui/bootstrap/issues/2728))
+* **demo:** initial load of fragment URLs ([eab6daf6](http://github.com/angular-ui/bootstrap/commit/eab6daf64b3c963d8e285e254c75af5f97c24ec1), closes [#2762](http://github.com/angular-ui/bootstrap/issues/2762))
+* **dropdown:**
+ * compatibility with `$location` url rewriting ([ef095170](http://github.com/angular-ui/bootstrap/commit/ef09517061b0b4c0c9e9f85086635af33207ec54), closes [#2343](http://github.com/angular-ui/bootstrap/issues/2343))
+ * remove `C` restrictions to avoid conflicts ([192768e1](http://github.com/angular-ui/bootstrap/commit/192768e109b5c4a50c7dcd320e09d05fedd4298a), closes [#2156](http://github.com/angular-ui/bootstrap/issues/2156), [#2170](http://github.com/angular-ui/bootstrap/issues/2170))
+* **tabs:**
+ * make tab links keyboard accessible ([5df524b7](http://github.com/angular-ui/bootstrap/commit/5df524b77114bccdc9a49540e1eb52a564ee5dfd), closes [#2226](http://github.com/angular-ui/bootstrap/issues/2226), [#2290](http://github.com/angular-ui/bootstrap/issues/2290), [#2870](http://github.com/angular-ui/bootstrap/issues/2870), [#2304](http://github.com/angular-ui/bootstrap/issues/2304))
+ * don't select tabs on destroy ([9939867a](http://github.com/angular-ui/bootstrap/commit/9939867aba0b7b763588b18829b557c052ea69ba), closes [#2155](http://github.com/angular-ui/bootstrap/issues/2155), [#2596](http://github.com/angular-ui/bootstrap/issues/2596))
+* **tests:** usage of undefined variables ([34273ff0](http://github.com/angular-ui/bootstrap/commit/34273ff0107ecfa28438a7389d94ca619b8704e5))
+* **tooltip:**
+ * remove extra digest causing incompatibility ([32c4704b](http://github.com/angular-ui/bootstrap/commit/32c4704b748cecf2de4c651f2e5157c1ef6c88b1), closes [#2951](http://github.com/angular-ui/bootstrap/issues/2951), [#2959](http://github.com/angular-ui/bootstrap/issues/2959))
+ * show correct tooltip on `ng-repeat` ([b4832c4b](http://github.com/angular-ui/bootstrap/commit/b4832c4b551af7e580ed65d9e5aaee1ef9e6c53e), closes [#2935](http://github.com/angular-ui/bootstrap/issues/2935))
+ * memory leak on show/hide ([faf38d20](http://github.com/angular-ui/bootstrap/commit/faf38d20a49176f2016f7f7d4fa49a5c438a986e), closes [#2709](http://github.com/angular-ui/bootstrap/issues/2709), [#2919](http://github.com/angular-ui/bootstrap/issues/2919))
+ * remove child scope requirement ([8204c808](http://github.com/angular-ui/bootstrap/commit/8204c8088139165ac9b2ad3977a2c20570e434cb), closes [#1269](http://github.com/angular-ui/bootstrap/issues/1269), [#2320](http://github.com/angular-ui/bootstrap/issues/2320), [#2203](http://github.com/angular-ui/bootstrap/issues/2203))
+ * evaluate appendToBody on init ([e10d561f](http://github.com/angular-ui/bootstrap/commit/e10d561f92c2927be0ec429761fa229520fb9a51), closes [#2921](http://github.com/angular-ui/bootstrap/issues/2921))
+ * don't use an empty transclusion fn ([689c4d01](http://github.com/angular-ui/bootstrap/commit/689c4d017d303b6d758164ee12837a172bb01139), closes [#2825](http://github.com/angular-ui/bootstrap/issues/2825))
+* **typeahead:** don't leak DOM nodes ([1f6c3c92](http://github.com/angular-ui/bootstrap/commit/1f6c3c92af0e343c7e34b85ea6d270ac79bf6755))
+
+
+## Features
+
+* **alert:** allow alerts to be closed from a controller ([ca6fad67](http://github.com/angular-ui/bootstrap/commit/ca6fad675bf2aa793896bf3e086330667a5d9051), closes [#2399](http://github.com/angular-ui/bootstrap/issues/2399), [#2854](http://github.com/angular-ui/bootstrap/issues/2854))
+* **typeahead:** add focus-first option ([35d0cc1d](http://github.com/angular-ui/bootstrap/commit/35d0cc1d57302883840f7ad54a03918ae2df001d), closes [#908](http://github.com/angular-ui/bootstrap/issues/908), [#2916](http://github.com/angular-ui/bootstrap/issues/2916))
+
+
+## Breaking Changes
+
+* `tooltip-trigger` and `popover-trigger` are no longer watched
+attributes.
+([a65bea95](http://github.com/angular-ui/bootstrap/commit/a65bea95338802b026fd213805b095b5a0b5b393))
+This affects both popovers and tooltips. The *triggers are now set up
+once* and can no longer be changed after initialization.
+
+* `dropdown` and `dropdown-toggle` are attribute-only directives. ([192768e1](http://github.com/angular-ui/bootstrap/commit/192768e109b5c4a50c7dcd320e09d05fedd4298a))
+
+ Before:
+ ```html
+ <button class="dropdown-toggle" ...>
+ ```
+ After:
+ ```html
+ <button class="dropdown-toggle" dropdown-toggle ...>
+ ```
+
+
+# 0.11.2 (2014-09-26)
+
+Revert breaking change in **dropdown** ([1a998c4](http://github.com/angular-ui/bootstrap/commit/1a998c4))
+
+# 0.11.1 (2014-09-26)
+
+## Features
+
+- **modal:**
+ - add backdropClass option, similar to windowClass option ([353e6127](http://github.com/angular-ui/bootstrap/commit/353e6127))
+ - support alternative controllerAs syntax ([8d7c2a26](http://github.com/angular-ui/bootstrap/commit/8d7c2a26))
+ - allow templateUrl to be a function ([990015fb](http://github.com/angular-ui/bootstrap/commit/990015fb))
+
+## Bug Fixes
+
+- **alert:**
+ - correct binding of alert type class ([aa188aec](http://github.com/angular-ui/bootstrap/commit/aa188aec))
+- **dateparser:**
+ - do not parse if no format specified ([42cc3f26](http://github.com/angular-ui/bootstrap/commit/42cc3f26))
+- **datepicker:**
+ - correct `datepicker-mode` binding for popup ([63ae06c9](http://github.com/angular-ui/bootstrap/commit/63ae06c9))
+ - memory leak fix for datepicker ([08c150e1](http://github.com/angular-ui/bootstrap/commit/08c150e1))
+- **dropdown:**
+ - close after selecting an item ([3ac3b487](http://github.com/angular-ui/bootstrap/commit/3ac3b487))
+ - remove `C` restrictions to avoid conflicts ([7512b93f](http://github.com/angular-ui/bootstrap/commit/7512b93f))
+- **modal:**
+ - allow modal.{dismiss,close} to be called again ([1590920c](http://github.com/angular-ui/bootstrap/commit/1590920c))
+ - add a work-around for transclusion scope ([0b31e865](http://github.com/angular-ui/bootstrap/commit/0b31e865))
+ - allow in-lined controller-as controllers ([79105368](http://github.com/angular-ui/bootstrap/commit/79105368))
+ - respect autofocus on child elements ([e62ab94a](http://github.com/angular-ui/bootstrap/commit/e62ab94a))
+ - controllerAs not checked ([7b7cdf84](http://github.com/angular-ui/bootstrap/commit/7b7cdf84))
+- **tabs:**
+ - remove leading newline from a template ([a708fe6d](http://github.com/angular-ui/bootstrap/commit/a708fe6d))
+- **typeahead:**
+ - timeout cancellation when deleting characters ([5dc57927](http://github.com/angular-ui/bootstrap/commit/5dc57927))
+ - allow multiple line expression ([c7db0df4](http://github.com/angular-ui/bootstrap/commit/c7db0df4))
+ - replace ng-if with ng-show in matches popup ([a0be450d](http://github.com/angular-ui/bootstrap/commit/a0be450d))
+
+# 0.11.0 (2014-05-01)
+
+## Features
+
+- **accordion:**
+ - support `is-disabled` state ([9c43ae7c](http://github.com/angular-ui/bootstrap/commit/9c43ae7c))
+- **alert:**
+ - add WAI-ARIA markup ([9a2638bf](http://github.com/angular-ui/bootstrap/commit/9a2638bf))
+- **button:**
+ - allow uncheckable radio button ([82df4fb1](http://github.com/angular-ui/bootstrap/commit/82df4fb1))
+- **carousel:**
+ - Support swipe for touchscreen devices ([85140f84](http://github.com/angular-ui/bootstrap/commit/85140f84))
+- **dateParser:**
+ - add `dateParser` service ([bd2ae0ee](http://github.com/angular-ui/bootstrap/commit/bd2ae0ee))
+- **datepicker:**
+ - add `datepicker-mode`, `init-date` & today hint ([7f4b40eb](http://github.com/angular-ui/bootstrap/commit/7f4b40eb))
+ - make widget accessible ([2423f6d4](http://github.com/angular-ui/bootstrap/commit/2423f6d4))
+ - full six-week calendar ([b0b14343](http://github.com/angular-ui/bootstrap/commit/b0b14343))
+- **dropdown:**
+ - add WAI-ARIA attributes ([22ebd230](http://github.com/angular-ui/bootstrap/commit/22ebd230))
+ - focus toggle element when opening or closing with Esc` ([f715d052](http://github.com/angular-ui/bootstrap/commit/f715d052))
+- **dropdownToggle:**
+ - support programmatic trigger & toggle callback ([ae31079c](http://github.com/angular-ui/bootstrap/commit/ae31079c))
+ - add support for `escape` key ([1417c548](http://github.com/angular-ui/bootstrap/commit/1417c548))
+- **modal:**
+ - support custom template for modal window ([96def3d6](http://github.com/angular-ui/bootstrap/commit/96def3d6))
+ - support modal window sizes ([976f6083](http://github.com/angular-ui/bootstrap/commit/976f6083))
+ - improve accessibility - add role='dialog' ([60cee9dc](http://github.com/angular-ui/bootstrap/commit/60cee9dc))
+- **pagination:**
+ - plug into `ngModel` controller ([d65901cf](http://github.com/angular-ui/bootstrap/commit/d65901cf))
+- **progressbar:**
+ - make widget accessible ([9dfe3157](http://github.com/angular-ui/bootstrap/commit/9dfe3157))
+- **rating:**
+ - plug into `ngModel` controller ([47e227f6](http://github.com/angular-ui/bootstrap/commit/47e227f6))
+ - make widget accessible ([4f56e60e](http://github.com/angular-ui/bootstrap/commit/4f56e60e))
+- **tooltip:**
+ - support more positioning options ([3704db9a](http://github.com/angular-ui/bootstrap/commit/3704db9a))
+- **typeahead:**
+ - add WAI-ARIA markup ([5ca23e97](http://github.com/angular-ui/bootstrap/commit/5ca23e97))
+ - add `aria-owns` & `aria-activedescendant` roles ([4c76a858](http://github.com/angular-ui/bootstrap/commit/4c76a858))
+
+## Bug Fixes
+
+- **alert:**
+ - use interpolation for type attribute ([f0a129ad](http://github.com/angular-ui/bootstrap/commit/f0a129ad))
+ - add `alert-dismissable` class ([794954af](http://github.com/angular-ui/bootstrap/commit/794954af))
+- **carousel:**
+ - correct glyphicon ([3b6ab25b](http://github.com/angular-ui/bootstrap/commit/3b6ab25b))
+- **datepicker:**
+ - remove unneeded date creation ([68cb2e5a](http://github.com/angular-ui/bootstrap/commit/68cb2e5a))
+ - `Today` button should not set time ([e1993491](http://github.com/angular-ui/bootstrap/commit/e1993491))
+ - mark input field as invalid if the date is invalid ([467dd159](http://github.com/angular-ui/bootstrap/commit/467dd159))
+ - rename `dateFormat` to `datepickerPopup` in datepickerPopupConfig ([93da30d5](http://github.com/angular-ui/bootstrap/commit/93da30d5))
+ - parse input using dateParser ([e0eb1bce](http://github.com/angular-ui/bootstrap/commit/e0eb1bce))
+- **dropdown:**
+ - use $animate for adding and removing classes ([e8d5fefc](http://github.com/angular-ui/bootstrap/commit/e8d5fefc))
+ - unbind toggle element event on scope destroy ([890e2d37](http://github.com/angular-ui/bootstrap/commit/890e2d37))
+ - do not call `on-toggle` initially ([004dd1de](http://github.com/angular-ui/bootstrap/commit/004dd1de))
+ - ensure `on-toggle` works when `is-open` is not used ([06ad3bd5](http://github.com/angular-ui/bootstrap/commit/06ad3bd5))
+- **modal:**
+ - destroy modal scope after animation end ([dfc36fd9](http://github.com/angular-ui/bootstrap/commit/dfc36fd9))
+ - backdrop z-index when stacking modals ([94a7f593](http://github.com/angular-ui/bootstrap/commit/94a7f593))
+ - give a reason of rejection when escape key pressed ([cb31b875](http://github.com/angular-ui/bootstrap/commit/cb31b875))
+ - prevent default event when closing via escape key ([da951222](http://github.com/angular-ui/bootstrap/commit/da951222))
+ - toggle 'modal-open' class after animation ([4d641ca7](http://github.com/angular-ui/bootstrap/commit/4d641ca7))
+- **pagination:**
+ - take maxSize defaults into account ([a294c87f](http://github.com/angular-ui/bootstrap/commit/a294c87f))
+- **position:**
+ - remove deprecated body scrollTop and scrollLeft ([1ba07c1b](http://github.com/angular-ui/bootstrap/commit/1ba07c1b))
+- **progressbar:**
+ - allow fractional values for bar width ([0daa7a74](http://github.com/angular-ui/bootstrap/commit/0daa7a74))
+ - number filter in bar template and only for percent ([378a9337](http://github.com/angular-ui/bootstrap/commit/378a9337))
+- **tabs:**
+ - fire deselect before select callback ([7474c47b](http://github.com/angular-ui/bootstrap/commit/7474c47b))
+ - use interpolation for type attribute ([83ceb78a](http://github.com/angular-ui/bootstrap/commit/83ceb78a))
+ - remove `tabbable` class required for left/right tabs ([19468331](http://github.com/angular-ui/bootstrap/commit/19468331))
+- **timepicker:**
+ - evaluate correctly the `readonly-input` attribute ([f9b6c496](http://github.com/angular-ui/bootstrap/commit/f9b6c496))
+- **tooltip:**
+ - animation causes tooltip to hide on show ([2b429f5d](http://github.com/angular-ui/bootstrap/commit/2b429f5d))
+- **typeahead:**
+ - correctly handle append to body attribute ([10785736](http://github.com/angular-ui/bootstrap/commit/10785736))
+ - correctly higlight numeric matches ([09678b12](http://github.com/angular-ui/bootstrap/commit/09678b12))
+ - loading callback updates after blur ([6a830116](http://github.com/angular-ui/bootstrap/commit/6a830116))
+ - incompatibility with ng-focus ([d0024931](http://github.com/angular-ui/bootstrap/commit/d0024931))
+
+## Breaking Changes
+
+- **alert:**
+ Use interpolation for type attribute.
+
+ Before:
+
+ ```html
+ <alert type="'info'" ...></alert >
+ ```
+ or
+ ```html
+ <alert type="alert.type" ...></alert >
+ ```
+
+ After:
+
+ ```html
+ <alert type="info" ...></alert >
+ ```
+ or
+ ```html
+ <alert type="{{alert.type}}" ...></alert >
+ ```
+
+- **datepicker:**
+
+`show-weeks` is no longer a watched attribute
+`*-format` attributes have been renamed to `format-*`
+`min` attribute has been renamed to `min-date`
+`max` attribute has been renamed to `max-date`
+`Open on focus` has been removed. Read more on this ([comment](https://github.com/angular-ui/bootstrap/pull/1922#issuecomment-40491716)).
+`dateFormat` renamed to `datepickerPopup` in datepickerPopupConfig
+
+- **dropdown:**
+
+ Elements with the `dropdown-toggle` directive must have a parent element with the `dropdown` directive.
+
+- **pagination:**
+
+ Both `pagination` and `pager` are now integrated with `ngModelController`.
+ * `page` is replaced from `ng-model`.
+ * `on-select-page` is removed since `ng-change` can now be used.
+
+ Before:
+
+ ```html
+ <pagination page="current" on-select-page="changed(page)" ...></pagination>
+ ```
+
+ After:
+
+ ```html
+ <pagination ng-model="current" ng-change="changed()" ...></pagination>
+ ```
+
+- **rating:**
+ `rating` is now integrated with `ngModelController`.
+ * `value` is replaced from `ng-model`.
+
+ Before:
+
+ ```html
+ <rating value="rate" ...></rating>
+ ```
+
+ After:
+
+ ```html
+ <rating ng-model="rate" ...></rating>
+ ```
+
+- **tabs:**
+
+ Use interpolation for type attribute.
+
+ Before:
+
+ ```html
+ <tabset type="'pills'" ...></tabset >
+ <!-- or -->
+ <tabset type="navtype" ...></tabset>
+ ```
+
+ After:
+
+ ```html
+ <tabset type="pills" ...></tabset>
+ <!-- or -->
+ <tabset type="{{navtype}}" ...></tabset>
+ ```
+
+# 0.10.0 (2014-01-13)
+
+_This release adds AngularJS 1.2 support_
+
+## Features
+
+- **modal:**
+ - expose dismissAll on $modalStack ([bc8d21c1](http://github.com/angular-ui/bootstrap/commit/bc8d21c1))
+
+## Bug Fixes
+
+- **datepicker:**
+ - evaluate `show-weeks` from `datepicker-options` ([92c1715f](http://github.com/angular-ui/bootstrap/commit/92c1715f))
+- **modal:**
+ - leaking watchers due to scope re-use ([0754ad7b](http://github.com/angular-ui/bootstrap/commit/0754ad7b))
+ - support close animation ([1933488c](http://github.com/angular-ui/bootstrap/commit/1933488c))
+- **timepicker:**
+ - add correct type for meridian button ([bcf39efe](http://github.com/angular-ui/bootstrap/commit/bcf39efe))
+- **tooltip:**
+ - performance and scope fixes ([c0df3201](http://github.com/angular-ui/bootstrap/commit/c0df3201))
+
+# 0.9.0 (2013-12-28)
+
+_This release adds Bootstrap3 support_
+
+## Features
+
+- **accordion:**
+ - convert to bootstrap3 panel styling ([458a9bd3](http://github.com/angular-ui/bootstrap/commit/458a9bd3))
+- **carousel:**
+ - some changes for Bootstrap3 ([1f632b65](http://github.com/angular-ui/bootstrap/commit/1f632b65))
+- **collapse:**
+ - make collapse work with bootstrap3 ([517dff6e](http://github.com/angular-ui/bootstrap/commit/517dff6e))
+- **datepicker:**
+ - update to Bootstrap 3 ([37684330](http://github.com/angular-ui/bootstrap/commit/37684330))
+- **modal:**
+ - added bootstrap3 support ([444c488d](http://github.com/angular-ui/bootstrap/commit/444c488d))
+- **pagination:**
+ - support bootstrap3 ([3db699d7](http://github.com/angular-ui/bootstrap/commit/3db699d7))
+- **progressbar:**
+ - update to bootstrap3 ([5bcff623](http://github.com/angular-ui/bootstrap/commit/5bcff623))
+- **rating:**
+ - update rating to bootstrap3 ([7e60284e](http://github.com/angular-ui/bootstrap/commit/7e60284e))
+- **tabs:**
+ - add nav-justified ([3199dd88](http://github.com/angular-ui/bootstrap/commit/3199dd88))
+- **timepicker:**
+ - restyled for bootstrap 3 ([6724a721](http://github.com/angular-ui/bootstrap/commit/6724a721))
+- **typeahead:**
+ - update to Bootstrap 3 ([eadf934a](http://github.com/angular-ui/bootstrap/commit/eadf934a))
+
+## Bug Fixes
+
+- **alert:**
+ - update template to Bootstrap 3 ([dfc3b0bd](http://github.com/angular-ui/bootstrap/commit/dfc3b0bd))
+- **collapse:**
+ - Prevent consecutive transitions & tidy up code ([b0032d68](http://github.com/angular-ui/bootstrap/commit/b0032d68))
+ - fixes after rebase ([dc02ad1d](http://github.com/angular-ui/bootstrap/commit/dc02ad1d))
+- **rating:**
+ - user glyhicon classes ([d221d517](http://github.com/angular-ui/bootstrap/commit/d221d517))
+- **timepicker:**
+ - fix look with bootstrap3 ([9613b61b](http://github.com/angular-ui/bootstrap/commit/9613b61b))
+- **tooltip:**
+ - re-position tooltip after draw ([a99b3608](http://github.com/angular-ui/bootstrap/commit/a99b3608))
+
+# 0.8.0 (2013-12-28)
+
+## Features
+
+- **datepicker:**
+ - option whether to display button bar in popup ([4d158e0d](http://github.com/angular-ui/bootstrap/commit/4d158e0d))
+- **modal:**
+ - add modal-open class to body on modal open ([e76512fa](http://github.com/angular-ui/bootstrap/commit/e76512fa))
+- **progressbar:**
+ - add `max` attribute & support transclusion ([365573ab](http://github.com/angular-ui/bootstrap/commit/365573ab))
+- **timepicker:**
+ - default meridian labels based on locale ([8b1ab79a](http://github.com/angular-ui/bootstrap/commit/8b1ab79a))
+- **typeahead:**
+ - add typeahead-append-to-body option ([dd8eac22](http://github.com/angular-ui/bootstrap/commit/dd8eac22))
+
+## Bug Fixes
+
+- **accordion:**
+ - correct `is-open` handling for dynamic groups ([9ec21286](http://github.com/angular-ui/bootstrap/commit/9ec21286))
+- **carousel:**
+ - cancel timer on scope destruction ([5b9d929c](http://github.com/angular-ui/bootstrap/commit/5b9d929c))
+ - cancel goNext on scope destruction ([7515df45](http://github.com/angular-ui/bootstrap/commit/7515df45))
+- **collapse:**
+ - dont animate height changes from 0 to 0 ([81e014a8](http://github.com/angular-ui/bootstrap/commit/81e014a8))
+- **datepicker:**
+ - set default zero time after no date selected ([93cd0df8](http://github.com/angular-ui/bootstrap/commit/93cd0df8))
+ - fire `ngChange` on today/clear button press ([6b1c68fb](http://github.com/angular-ui/bootstrap/commit/6b1c68fb))
+ - remove datepicker's popup on scope destroy ([48955d69](http://github.com/angular-ui/bootstrap/commit/48955d69))
+ - remove edge case position updates ([1fbcb5d6](http://github.com/angular-ui/bootstrap/commit/1fbcb5d6))
+- **modal:**
+ - put backdrop in before window ([d64f4a97](http://github.com/angular-ui/bootstrap/commit/d64f4a97))
+ - grab reference to body when it is needed in lieu of when the factory is created ([dd415a98](http://github.com/angular-ui/bootstrap/commit/dd415a98))
+ - focus freshly opened modal ([709e679c](http://github.com/angular-ui/bootstrap/commit/709e679c))
+ - properly animate backdrops on each modal opening ([672a557a](http://github.com/angular-ui/bootstrap/commit/672a557a))
+- **tabs:**
+ - make nested tabs work ([c9acebbe](http://github.com/angular-ui/bootstrap/commit/c9acebbe))
+- **tooltip:**
+ - update tooltip content when empty ([60515ae1](http://github.com/angular-ui/bootstrap/commit/60515ae1))
+ - support IE8 ([5dd98238](http://github.com/angular-ui/bootstrap/commit/5dd98238))
+ - unbind element events on scope destroy ([3fe7aa8c](http://github.com/angular-ui/bootstrap/commit/3fe7aa8c))
+ - respect animate attribute ([54e614a8](http://github.com/angular-ui/bootstrap/commit/54e614a8))
+
+## Breaking Changes
+
+- **progressbar:**
+ The onFull/onEmpty handlers & auto/stacked types have been removed.
+
+ To migrate your code change your markup like below.
+
+ Before:
+
+```html
+ <progress percent="var" class="progress-warning"></progress>
+```
+
+ After:
+
+```html
+ <progressbar value="var" type="warning"></progressbar>
+```
+
+ and for stacked instead of passing array/objects you can do:
+
+```html
+ <progress><bar ng-repeat="obj in objs" value="obj.var" type="{{obj.type}}"></bar></progress>
+```
+
+# 0.7.0 (2013-11-22)
+
+## Features
+
+- **datepicker:**
+ - add i18n support for bar buttons in popup ([c6ba8d7f](http://github.com/angular-ui/bootstrap/commit/c6ba8d7f))
+ - dynamic date format for popup ([aa3eaa91](http://github.com/angular-ui/bootstrap/commit/aa3eaa91))
+ - datepicker-append-to-body attribute ([0cdc4609](http://github.com/angular-ui/bootstrap/commit/0cdc4609))
+- **dropdownToggle:**
+ - disable dropdown when it has the disabled class ([104bdd1b](http://github.com/angular-ui/bootstrap/commit/104bdd1b))
+- **tooltip:**
+ - add ability to enable / disable tooltip ([5d9bd058](http://github.com/angular-ui/bootstrap/commit/5d9bd058))
+
+## Bug Fixes
+
+- **accordion:**
+ - assign `is-open` to correct scope ([157f614a](http://github.com/angular-ui/bootstrap/commit/157f614a))
+- **collapse:**
+ - remove element height watching ([a72c635c](http://github.com/angular-ui/bootstrap/commit/a72c635c))
+ - add the "in" class for expanded panels ([9eca35a8](http://github.com/angular-ui/bootstrap/commit/9eca35a8))
+- **datepicker:**
+ - some IE8 compatibility improvements ([4540476f](http://github.com/angular-ui/bootstrap/commit/4540476f))
+ - set popup initial position in append-to-body case ([78a1e9d7](http://github.com/angular-ui/bootstrap/commit/78a1e9d7))
+ - properly handle showWeeks config option ([570dba90](http://github.com/angular-ui/bootstrap/commit/570dba90))
+- **modal:**
+ - correctly close modals with no backdrop ([e55c2de3](http://github.com/angular-ui/bootstrap/commit/e55c2de3))
+- **pagination:**
+ - fix altering of current page caused by totals change ([81164dae](http://github.com/angular-ui/bootstrap/commit/81164dae))
+ - handle extreme values for `total-items` ([8ecf93ed](http://github.com/angular-ui/bootstrap/commit/8ecf93ed))
+- **position:**
+ - correct positioning for SVG elements ([968e5407](http://github.com/angular-ui/bootstrap/commit/968e5407))
+- **tabs:**
+ - initial tab selection ([a08173ec](http://github.com/angular-ui/bootstrap/commit/a08173ec))
+- **timepicker:**
+ - use html5 for input elements ([53709f0f](http://github.com/angular-ui/bootstrap/commit/53709f0f))
+- **tooltip:**
+ - restore html-unsafe compatibility with AngularJS 1.2 ([08d8b21d](http://github.com/angular-ui/bootstrap/commit/08d8b21d))
+ - hide tooltips when content becomes empty ([cf5c27ae](http://github.com/angular-ui/bootstrap/commit/cf5c27ae))
+ - tackle DOM node and event handlers leak ([0d810acd](http://github.com/angular-ui/bootstrap/commit/0d810acd))
+- **typeahead:**
+ - do not set editable error when input is empty ([006986db](http://github.com/angular-ui/bootstrap/commit/006986db))
+ - remove popup flickering ([dde804b6](http://github.com/angular-ui/bootstrap/commit/dde804b6))
+ - don't show matches if an element is not focused ([d1f94530](http://github.com/angular-ui/bootstrap/commit/d1f94530))
+ - fix loading callback when deleting characters ([0149eff6](http://github.com/angular-ui/bootstrap/commit/0149eff6))
+ - prevent accidental form submission on ENTER ([253c49ff](http://github.com/angular-ui/bootstrap/commit/253c49ff))
+ - evaluate matches source against a correct scope ([fd21214d](http://github.com/angular-ui/bootstrap/commit/fd21214d))
+ - support IE8 ([0e9f9980](http://github.com/angular-ui/bootstrap/commit/0e9f9980))
+
+# 0.6.0 (2013-09-08)
+
+## Features
+
+- **modal:**
+ - rewrite $dialog as $modal ([d7a48523](http://github.com/angular-ui/bootstrap/commit/d7a48523))
+ - add support for custom window settings ([015625d1](http://github.com/angular-ui/bootstrap/commit/015625d1))
+ - expose $close and $dismiss options on modal's scope ([8d153acb](http://github.com/angular-ui/bootstrap/commit/8d153acb))
+- **pagination:**
+ - `total-items` & optional `items-per-page` API ([e55d9063](http://github.com/angular-ui/bootstrap/commit/e55d9063))
+- **rating:**
+ - add support for custom icons per instance ([20ab01ad](http://github.com/angular-ui/bootstrap/commit/20ab01ad))
+- **timepicker:**
+ - plug into `ngModel` controller ([b08e993f](http://github.com/angular-ui/bootstrap/commit/b08e993f))
+
+## Bug Fixes
+
+- **carousel:**
+ - correct reflow triggering on FFox and Safari ([d34f2de1](http://github.com/angular-ui/bootstrap/commit/d34f2de1))
+- **datepicker:**
+ - correctly manage focus without jQuery present ([d474824b](http://github.com/angular-ui/bootstrap/commit/d474824b))
+ - compatibility with angular 1.1.5 and no jquery ([bf30898d](http://github.com/angular-ui/bootstrap/commit/bf30898d))
+ - use $setViewValue for inner changes ([dd99f35d](http://github.com/angular-ui/bootstrap/commit/dd99f35d))
+- **modal:**
+ - insert backdrop before modal window ([d870f212](http://github.com/angular-ui/bootstrap/commit/d870f212))
+ - ie8 fix after $modal rewrite ([ff9d969e](http://github.com/angular-ui/bootstrap/commit/ff9d969e))
+ - opening a modal should not change default options ([82532d1b](http://github.com/angular-ui/bootstrap/commit/82532d1b))
+ - backdrop should cover previously opened modals ([7fce2fe8](http://github.com/angular-ui/bootstrap/commit/7fce2fe8))
+ - allow replacing object with default options ([8e7fbf06](http://github.com/angular-ui/bootstrap/commit/8e7fbf06))
+- **position:**
+ - fallback for IE8's scrollTop/Left for offset ([9aecd4ed](http://github.com/angular-ui/bootstrap/commit/9aecd4ed))
+- **tabs:**
+ - add DI array-style annotations ([aac4a0dd](http://github.com/angular-ui/bootstrap/commit/aac4a0dd))
+ - evaluate `vertical` on parent scope ([9af6f96e](http://github.com/angular-ui/bootstrap/commit/9af6f96e))
+- **timepicker:**
+ - add type attribute for meridian button ([1f89fd4b](http://github.com/angular-ui/bootstrap/commit/1f89fd4b))
+- **tooltip:**
+ - remove placement='mouse' option ([17163c22](http://github.com/angular-ui/bootstrap/commit/17163c22))
+- **typeahead:**
+ - fix label rendering for equal model and items names ([5de71216](http://github.com/angular-ui/bootstrap/commit/5de71216))
+ - set validity flag for non-editable inputs ([366e0c8a](http://github.com/angular-ui/bootstrap/commit/366e0c8a))
+ - plug in front of existing parsers ([80cef614](http://github.com/angular-ui/bootstrap/commit/80cef614))
+ - highlight return match if no query ([45dd9be1](http://github.com/angular-ui/bootstrap/commit/45dd9be1))
+ - keep pop-up on clicking input ([5f9e270d](http://github.com/angular-ui/bootstrap/commit/5f9e270d))
+ - remove dependency on ng-bind-html-unsafe ([75893393](http://github.com/angular-ui/bootstrap/commit/75893393))
+
+## Breaking Changes
+
+- **modal:**
+
+* `$dialog` service was refactored into `$modal`
+* `modal` directive was removed - use the `$modal` service instead
+
+Check the documentation for the `$modal` service to migrate from `$dialog`
+
+- **pagination:**
+ API has undergone some changes in order to be easier to use.
+ * `current-page` is replaced from `page`.
+ * Number of pages is not defined by `num-pages`, but from `total-items` &
+ `items-per-page` instead. If `items-per-page` is missing, default is 10.
+ * `num-pages` still exists but is just readonly.
+
+ Before:
+
+```html
+ <pagination num-pages="10" ...></pagination>
+```
+
+ After:
+
+```html
+ <pagination total-items="100" ...></pagination>
+```
+
+- **tooltip:**
+
+
+The placment='mouse' is gone with no equivalent
+
+# 0.5.0 (2013-08-04)
+
+## Features
+
+- **buttons:**
+ - support dynamic true / false values in btn-checkbox ([3e30cd94](http://github.com/angular-ui/bootstrap/commit/3e30cd94))
+- **datepicker:**
+ - `ngModelController` plug & new `datepickerPopup` ([dab18336](http://github.com/angular-ui/bootstrap/commit/dab18336))
+- **rating:**
+ - added onHover and onLeave. ([5b1115e3](http://github.com/angular-ui/bootstrap/commit/5b1115e3))
+- **tabs:**
+ - added onDeselect callback, used similarly as onSelect ([fe47c9bb](http://github.com/angular-ui/bootstrap/commit/fe47c9bb))
+ - add the ability to set the direction of the tabs ([220e7b60](http://github.com/angular-ui/bootstrap/commit/220e7b60))
+- **typeahead:**
+ - support custom templates for matched items ([e2238174](http://github.com/angular-ui/bootstrap/commit/e2238174))
+ - expose index to custom templates ([5ffae83d](http://github.com/angular-ui/bootstrap/commit/5ffae83d))
+
+## Bug Fixes
+
+- **datepicker:**
+ - handle correctly `min`/`max` when cleared ([566bdd16](http://github.com/angular-ui/bootstrap/commit/566bdd16))
+ - add type attribute for buttons ([25caf5fb](http://github.com/angular-ui/bootstrap/commit/25caf5fb))
+- **pagination:**
+ - handle `currentPage` number as string ([b1fa7bb8](http://github.com/angular-ui/bootstrap/commit/b1fa7bb8))
+ - use interpolation for text attributes ([f45815cb](http://github.com/angular-ui/bootstrap/commit/f45815cb))
+- **popover:**
+ - don't unbind event handlers created by other directives ([56f624a2](http://github.com/angular-ui/bootstrap/commit/56f624a2))
+ - correctly position popovers appended to body ([93a82af0](http://github.com/angular-ui/bootstrap/commit/93a82af0))
+- **rating:**
+ - evaluate `max` attribute on parent scope ([60619d51](http://github.com/angular-ui/bootstrap/commit/60619d51))
+- **tabs:**
+ - make tab contents be correctly connected to parent (#524) ([be7ecff0](http://github.com/angular-ui/bootstrap/commit/be7ecff0))
+ - Make tabset template correctly use tabset attributes (#584) ([8868f236](http://github.com/angular-ui/bootstrap/commit/8868f236))
+ - fix tab content compiling wrong (Closes #599, #631, #574) ([224bc2f5](http://github.com/angular-ui/bootstrap/commit/224bc2f5))
+ - make tabs added with active=true be selected ([360cd5ca](http://github.com/angular-ui/bootstrap/commit/360cd5ca))
+ - if tab is active at start, always select it ([ba1f741d](http://github.com/angular-ui/bootstrap/commit/ba1f741d))
+- **timepicker:**
+ - prevent date change ([ee741707](http://github.com/angular-ui/bootstrap/commit/ee741707))
+ - added wheel event to enable mousewheel on Firefox ([8dc92afa](http://github.com/angular-ui/bootstrap/commit/8dc92afa))
+- **tooltip:**
+ - fix positioning inside scrolling element ([63ae7e12](http://github.com/angular-ui/bootstrap/commit/63ae7e12))
+ - triggers should be local to tooltip instances ([58e8ef4f](http://github.com/angular-ui/bootstrap/commit/58e8ef4f))
+ - correctly handle initial events unbinding ([4fd5bf43](http://github.com/angular-ui/bootstrap/commit/4fd5bf43))
+ - bind correct 'hide' event handler ([d50b0547](http://github.com/angular-ui/bootstrap/commit/d50b0547))
+- **typeahead:**
+ - play nicelly with existing formatters ([d2df0b35](http://github.com/angular-ui/bootstrap/commit/d2df0b35))
+ - properly render initial input value ([c4e169cb](http://github.com/angular-ui/bootstrap/commit/c4e169cb))
+ - separate text field rendering and drop down rendering ([ea1e858a](http://github.com/angular-ui/bootstrap/commit/ea1e858a))
+ - fixed waitTime functionality ([90a8aa79](http://github.com/angular-ui/bootstrap/commit/90a8aa79))
+ - correctly close popup on match selection ([624fd5f5](http://github.com/angular-ui/bootstrap/commit/624fd5f5))
+
+## Breaking Changes
+
+- **pagination:**
+ The 'first-text', 'previous-text', 'next-text' and 'last-text'
+ attributes are now interpolated.
+
+ To migrate your code, remove quotes for constant attributes and/or
+ interpolate scope variables.
+
+ Before:
+
+```html
+ <pagination first-text="'<<'" ...></pagination>
+```
+ and/or
+
+```html
+ $scope.var1 = '<<';
+ <pagination first-text="var1" ...></pagination>
+```
+ After:
+
+```html
+ <pagination first-text="<<" ...></pagination>
+```
+ and/or
+
+```html
+ $scope.var1 = '<<';
+ <pagination first-text="{{var1}}" ...></pagination>
+```
+
+# 0.4.0 (2013-06-24)
+
+## Features
+
+- **buttons:**
+ - support dynamic values in btn-radio ([e8c5b548](http://github.com/angular-ui/bootstrap/commit/e8c5b548))
+- **carousel:**
+ - add option to prevent pause ([5f895c13](http://github.com/angular-ui/bootstrap/commit/5f895c13))
+- **datepicker:**
+ - add datepicker directive ([30a00a07](http://github.com/angular-ui/bootstrap/commit/30a00a07))
+- **pagination:**
+ - option for different mode when maxSize ([a023d082](http://github.com/angular-ui/bootstrap/commit/a023d082))
+ - add pager directive ([d9526475](http://github.com/angular-ui/bootstrap/commit/d9526475))
+- **tabs:**
+ - Change directive name, add features ([c5326595](http://github.com/angular-ui/bootstrap/commit/c5326595))
+ - support disabled state ([2b78dd16](http://github.com/angular-ui/bootstrap/commit/2b78dd16))
+ - add support for vertical option ([88d17a75](http://github.com/angular-ui/bootstrap/commit/88d17a75))
+ - add support for other navigation types, like 'pills' ([53e0a39f](http://github.com/angular-ui/bootstrap/commit/53e0a39f))
+- **timepicker:**
+ - add timepicker directive ([9bc5207b](http://github.com/angular-ui/bootstrap/commit/9bc5207b))
+- **tooltip:**
+ - add mouse placement option ([ace7bc60](http://github.com/angular-ui/bootstrap/commit/ace7bc60))
+ - add *-append-to-body attribute ([d0896263](http://github.com/angular-ui/bootstrap/commit/d0896263))
+ - add custom trigger support ([dfa53155](http://github.com/angular-ui/bootstrap/commit/dfa53155))
+- **typeahead:**
+ - support typeahead-on-select callback ([91ac17c9](http://github.com/angular-ui/bootstrap/commit/91ac17c9))
+ - support wait-ms option ([7f35a3f2](http://github.com/angular-ui/bootstrap/commit/7f35a3f2))
+
+## Bug Fixes
+
+- **accordion:**
+ - allow accordion heading directives as attributes. ([25f6e55c](http://github.com/angular-ui/bootstrap/commit/25f6e55c))
+- **carousel:**
+ - do not allow user to change slide if transitioning ([1d19663f](http://github.com/angular-ui/bootstrap/commit/1d19663f))
+ - make slide 'active' binding optional ([17d6c3b5](http://github.com/angular-ui/bootstrap/commit/17d6c3b5))
+ - fix error with deleting multiple slides at once ([3fcb70f0](http://github.com/angular-ui/bootstrap/commit/3fcb70f0))
+- **dialog:**
+ - remove dialogOpenClass to get in line with v2.3 ([f009b23f](http://github.com/angular-ui/bootstrap/commit/f009b23f))
+- **pagination:**
+ - bind *-text attributes ([e1bff6b7](http://github.com/angular-ui/bootstrap/commit/e1bff6b7))
+- **progressbar:**
+ - user `percent` attribute instead of `value`. ([58efec80](http://github.com/angular-ui/bootstrap/commit/58efec80))
+- **tooltip:**
+ - fix positioning error when appendToBody is set to true ([76fee1f9](http://github.com/angular-ui/bootstrap/commit/76fee1f9))
+ - close tooltips appended to body on location change ([041261b5](http://github.com/angular-ui/bootstrap/commit/041261b5))
+ - tooltips will hide on scope.$destroy ([3e5a58e5](http://github.com/angular-ui/bootstrap/commit/3e5a58e5))
+ - support of custom $interpolate.startSymbol ([88c94ee6](http://github.com/angular-ui/bootstrap/commit/88c94ee6))
+ - make sure tooltip scope is evicted from cache ([9246905a](http://github.com/angular-ui/bootstrap/commit/9246905a))
+- **typeahead:**
+ - return focus to the input after selecting a suggestion ([04a21e33](http://github.com/angular-ui/bootstrap/commit/04a21e33))
+
+## Breaking Changes
+
+- **pagination:**
+ The 'first-text', 'previous-text', 'next-text' and 'last-text'
+ attributes are now binded to parent scope.
+
+ To migrate your code, surround the text of these attributes with quotes.
+
+ Before:
+
+ ```html
+ <pagination first-text="<<"></pagination>
+ ```
+
+ After:
+
+ ```html
+ <pagination first-text="'<<'"></pagination>
+ ```
+
+- **progressbar:**
+ The 'value' is replaced by 'percent'.
+
+ Before:
+
+ ```html
+ <progress value="..."></progress>
+ ```
+
+ After:
+
+ ```html
+ <progress percent="..."></progress>
+ ```
+
+- **tabs:**
+ The 'tabs' directive has been renamed to 'tabset', and
+ the 'pane' directive has been renamed to 'tab'.
+
+ To migrate your code, follow the example below.
+
+ Before:
+
+ ```html
+ <tabs>
+ <pane heading="one">
+ First Content
+ </pane>
+ <pane ng-repeat="apple in basket" heading="{{apple.heading}}">
+ {{apple.content}}
+ </pane>
+ </tabs>
+ ```
+
+ After:
+
+ ```html
+ <tabset>
+ <tab heading="one">
+ First Content
+ </tab>
+ <tab ng-repeat="apple in basket" heading="{{apple.heading}}">
+ {{apple.content}}
+ </tab>
+ </tabset>
+ ```
+
+
+# 0.3.0 (2013-04-30)
+
+## Features
+
+- **progressbar:**
+ - add progressbar directive ([261f2072](https://github.com/angular-ui/bootstrap/commit/261f2072))
+- **rating:**
+ - add rating directive ([6b5e6369](https://github.com/angular-ui/bootstrap/commit/6b5e6369))
+- **typeahead:**
+ - support the editable property ([a40c3fbe](https://github.com/angular-ui/bootstrap/commit/a40c3fbe))
+ - support typeahead-loading bindable expression ([b58c9c88](https://github.com/angular-ui/bootstrap/commit/b58c9c88))
+- **tooltip:**
+ - added popup-delay option ([a79a2ba8](https://github.com/angular-ui/bootstrap/commit/a79a2ba8))
+ - added appendToBody to $tooltip ([1ee467f8](https://github.com/angular-ui/bootstrap/commit/1ee467f8))
+ - added tooltip-html-unsafe directive ([45ed2805](https://github.com/angular-ui/bootstrap/commit/45ed2805))
+ - support for custom triggers ([b1ba821b](https://github.com/angular-ui/bootstrap/commit/b1ba821b))
+
+## Bug Fixes
+
+- **alert:**
+ - don't show close button if no close callback specified ([c2645f4a](https://github.com/angular-ui/bootstrap/commit/c2645f4a))
+- **carousel:**
+ - Hide navigation indicators if only one slide ([aedc0565](https://github.com/angular-ui/bootstrap/commit/aedc0565))
+- **collapse:**
+ - remove reference to msTransition for IE10 ([55437b16](https://github.com/angular-ui/bootstrap/commit/55437b16))
+- **dialog:**
+ - set _open to false on init ([dcc9ef31](https://github.com/angular-ui/bootstrap/commit/dcc9ef31))
+ - close dialog on location change ([474ce52e](https://github.com/angular-ui/bootstrap/commit/474ce52e))
+ - IE8 fix to not set data() against text nodes ([a6c540e5](https://github.com/angular-ui/bootstrap/commit/a6c540e5))
+ - fix $apply in progres on $location change ([77e6acb9](https://github.com/angular-ui/bootstrap/commit/77e6acb9))
+- **tabs:**
+ - remove superfluous href from tabs template ([38c1badd](https://github.com/angular-ui/bootstrap/commit/38c1badd))
+- **tooltip:**
+ - fix positioning issues in tooltips and popovers ([6458f487](https://github.com/angular-ui/bootstrap/commit/6458f487))
+- **typeahead:**
+ - close matches popup on click outside typeahead ([acca7dcd](https://github.com/angular-ui/bootstrap/commit/acca7dcd))
+ - stop keydown event propagation when ESC pressed to discard matches ([22a00cd0](https://github.com/angular-ui/bootstrap/commit/22a00cd0))
+ - correctly render initial model value ([929a46fa](https://github.com/angular-ui/bootstrap/commit/929a46fa))
+ - correctly higlight matches if query contains regexp-special chars ([467afcd6](https://github.com/angular-ui/bootstrap/commit/467afcd6))
+ - fix matches pop-up positioning issues ([74beecdb](https://github.com/angular-ui/bootstrap/commit/74beecdb))
+
+# 0.2.0 (2013-03-03)
+
+## Features
+
+- **dialog:**
+ - Make $dialog 'resolve' property to work the same way of $routeProvider.when ([739f86f](https://github.com/angular-ui/bootstrap/commit/739f86f))
+- **modal:**
+ - allow global override of modal options ([acaf72b](https://github.com/angular-ui/bootstrap/commit/acaf72b))
+- **buttons:**
+ - add checkbox and radio buttons ([571ccf4](https://github.com/angular-ui/bootstrap/commit/571ccf4))
+- **carousel:**
+ - add slide indicators ([3b677ee](https://github.com/angular-ui/bootstrap/commit/3b677ee))
+- **typeahead:**
+ - add typeahead directive ([6a97da2](https://github.com/angular-ui/bootstrap/commit/6a97da2))
+- **accordion:**
+ - enable HTML in accordion headings ([3afcaa4](https://github.com/angular-ui/bootstrap/commit/3afcaa4))
+- **pagination:**
+ - add first/last link & constant congif options ([0ff0454](https://github.com/angular-ui/bootstrap/commit/0ff0454))
+
+## Bug fixes
+
+- **dialog:**
+ - update resolve section to new syntax ([1f87486](https://github.com/angular-ui/bootstrap/commit/1f87486))
+ - $compile entire modal ([7575b3c](https://github.com/angular-ui/bootstrap/commit/7575b3c))
+- **tooltip:**
+ - don't show tooltips if there is no content to show ([030901e](https://github.com/angular-ui/bootstrap/commit/030901e))
+ - fix placement issues ([a2bbf4d](https://github.com/angular-ui/bootstrap/commit/a2bbf4d))
+- **collapse:**
+ - Avoids fixed height on collapse ([ff5d119](https://github.com/angular-ui/bootstrap/commit/ff5d119))
+- **accordion:**
+ - fix minification issues ([f4da4d6](https://github.com/angular-ui/bootstrap/commit/f4da4d6))
+- **typeahead:**
+ - update inputs value on mapping where label is not derived from the model ([a5f64de](https://github.com/angular-ui/bootstrap/commit/a5f64de))
+
+# 0.1.0 (2013-02-02)
+
+_Very first, initial release_.
+
+## Features
+
+Version `0.1.0` was released with the following directives:
+
+* accordion
+* alert
+* carousel
+* dialog
+* dropdownToggle
+* modal
+* pagination
+* popover
+* tabs
+* tooltip
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/CODE_OF_CONDUCT.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..65c05c5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/CODE_OF_CONDUCT.md
@@ -0,0 +1,22 @@
+# Contributor Code of Conduct
+
+As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
+
+We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality.
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery
+* Personal attacks
+* Trolling or insulting/derogatory comments
+* Public or private harassment
+* Publishing other's private information, such as physical or electronic addresses, without explicit permission
+* Other unethical or unprofessional conduct.
+
+Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team.
+
+This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community.
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
+
+This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/)
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/CONTRIBUTING.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/CONTRIBUTING.md
new file mode 100644
index 0000000..3bbe218
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/CONTRIBUTING.md
@@ -0,0 +1,47 @@
+## Got a question or problem?
+
+Firstly, please go over our FAQ: https://github.com/angular-ui/bootstrap/wiki/FAQ
+
+Please, do not open issues for the general support questions as we want to keep GitHub issues for bug reports and feature requests. You've got much better chances of getting your question answered on [StackOverflow](http://stackoverflow.com/questions/tagged/angular-ui-bootstrap) where maintainers are looking at questions questions tagged with `angular-ui-bootstrap`.
+
+StackOverflow is a much better place to ask questions since:
+* there are hundreds of people willing to help on StackOverflow
+* questions and answers stay available for public viewing so your question / answer might help someone else
+* SO voting system assures that the best answers are prominently visible.
+
+To save your and our time we will be systematically closing all the issues that are requests for general support and redirecting people to StackOverflow.
+
+## You think you've found a bug?
+
+Oh, we are ashamed and want to fix it asap! But before fixing a bug we need to reproduce and confirm it. In order to reproduce bugs we will systematically ask you to provide a _minimal_ reproduce scenario using http://plnkr.co/. Having a live reproduce scenario gives us wealth of important information without going back & forth to you with additional questions like:
+* version of AngularJS used
+* version of this library that you are using
+* 3rd-party libraries used, if any
+* and most importantly - a use-case that fails
+
+A minimal reproduce scenario using http://plnkr.co/ allows us to quickly confirm a bug (or point out coding problem) as well as confirm that we are fixing the right problem.
+
+We will be insisting on a minimal reproduce scenario in order to save maintainers time and ultimately be able to fix more bugs. Interestingly, from our experience users often find coding problems themselves while preparing a minimal plunk. We understand that sometimes it might be hard to extract essentials bits of code from a larger code-base but we really need to isolate the problem before we can fix it.
+
+The best part is that you don't need to create plunks from scratch - you can use one from our [demo page](http://angular-ui.github.io/bootstrap/).
+
+Unfortunately we are not able to investigate / fix bugs without a minimal reproduce scenario using http://plnkr.co/, so if we don't hear back from you we are going to close an issue that don't have enough info to be reproduced.
+
+
+## You want to contribute some code?
+
+**NOTE: We are migrating all our components to use a prefix, in the meantime you will see both the new and the old directives separated by a comment. If you want to contribute with code, make all your changes on top of that comment.**
+
+We are always looking for the quality contributions and will be happy to accept your Pull Requests as long as those adhere to some basic rules:
+
+* Please make sure that your contribution fits well in the project's context:
+ * we are aiming at rebuilding bootstrap directives in pure AngularJS, without any dependencies on any external JavaScript library;
+ * the only dependency should be bootstrap CSS and its markup structure;
+ * directives should be html-agnostic as much as possible which in practice means:
+ * templates should be referred to using the `templateUrl` property
+ * it should be easy to change a default template to a custom one
+ * directives shouldn't manipulate DOM structure directly (when possible)
+* Please assure that you are submitting quality code, specifically make sure that:
+ * your directive has accompanying tests and all the tests are passing; don't hesitate to contact us (angular-ui@googlegroups.com) if you need any help with unit testing
+ * your PR doesn't break the build; check the Travis-CI build status after opening a PR and push corrective commits if anything goes wrong
+ * your commits conform to the conventions established [here](https://github.com/ajoslin/conventional-changelog/blob/master/conventions/angular.md)
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/Gruntfile.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/Gruntfile.js
new file mode 100644
index 0000000..147adb4
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/Gruntfile.js
@@ -0,0 +1,492 @@
+/* jshint node: true */
+var markdown = require('node-markdown').Markdown;
+var fs = require('fs');
+
+module.exports = function(grunt) {
+
+ grunt.loadNpmTasks('grunt-contrib-watch');
+ grunt.loadNpmTasks('grunt-contrib-concat');
+ grunt.loadNpmTasks('grunt-contrib-copy');
+ grunt.loadNpmTasks('grunt-contrib-jshint');
+ grunt.loadNpmTasks('grunt-contrib-uglify');
+ grunt.loadNpmTasks('grunt-html2js');
+ grunt.loadNpmTasks('grunt-karma');
+ grunt.loadNpmTasks('grunt-conventional-changelog');
+ grunt.loadNpmTasks('grunt-ddescribe-iit');
+
+ // Project configuration.
+ grunt.util.linefeed = '\n';
+
+ grunt.initConfig({
+ ngversion: '1.4.7',
+ bsversion: '3.1.1',
+ modules: [],//to be filled in by build task
+ pkg: grunt.file.readJSON('package.json'),
+ dist: 'dist',
+ filename: 'ui-bootstrap',
+ filenamecustom: '<%= filename %>-custom',
+ meta: {
+ modules: 'angular.module("ui.bootstrap", [<%= srcModules %>]);',
+ tplmodules: 'angular.module("ui.bootstrap.tpls", [<%= tplModules %>]);',
+ all: 'angular.module("ui.bootstrap", ["ui.bootstrap.tpls", <%= srcModules %>]);',
+ cssInclude: '',
+ cssFileBanner: '/* Include this file in your html if you are using the CSP mode. */\n\n',
+ cssFileDest: '<%= dist %>/<%= filename %>-<%= pkg.version %>-csp.css',
+ banner: ['/*',
+ ' * <%= pkg.name %>',
+ ' * <%= pkg.homepage %>\n',
+ ' * Version: <%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>',
+ ' * License: <%= pkg.license %>',
+ ' */\n'].join('\n')
+ },
+ delta: {
+ docs: {
+ files: ['misc/demo/index.html'],
+ tasks: ['after-test']
+ },
+ html: {
+ files: ['template/**/*.html'],
+ tasks: ['html2js', 'karma:watch:run']
+ },
+ js: {
+ files: ['src/**/*.js'],
+ //we don't need to jshint here, it slows down everything else
+ tasks: ['karma:watch:run']
+ }
+ },
+ concat: {
+ dist: {
+ options: {
+ banner: '<%= meta.banner %><%= meta.modules %>\n',
+ footer: '<%= meta.cssInclude %>'
+ },
+ src: [], //src filled in by build task
+ dest: '<%= dist %>/<%= filename %>-<%= pkg.version %>.js'
+ },
+ dist_tpls: {
+ options: {
+ banner: '<%= meta.banner %><%= meta.all %>\n<%= meta.tplmodules %>\n',
+ footer: '<%= meta.cssInclude %>'
+ },
+ src: [], //src filled in by build task
+ dest: '<%= dist %>/<%= filename %>-tpls-<%= pkg.version %>.js'
+ }
+ },
+ copy: {
+ demohtml: {
+ options: {
+ //process html files with gruntfile config
+ processContent: grunt.template.process
+ },
+ files: [{
+ expand: true,
+ src: ['**/*.html'],
+ cwd: 'misc/demo/',
+ dest: 'dist/'
+ }]
+ },
+ demoassets: {
+ files: [{
+ expand: true,
+ //Don't re-copy html files, we process those
+ src: ['**/**/*', '!**/*.html'],
+ cwd: 'misc/demo',
+ dest: 'dist/'
+ }]
+ }
+ },
+ uglify: {
+ options: {
+ banner: '<%= meta.banner %>'
+ },
+ dist:{
+ src:['<%= concat.dist.dest %>'],
+ dest:'<%= dist %>/<%= filename %>-<%= pkg.version %>.min.js'
+ },
+ dist_tpls:{
+ src:['<%= concat.dist_tpls.dest %>'],
+ dest:'<%= dist %>/<%= filename %>-tpls-<%= pkg.version %>.min.js'
+ }
+ },
+ html2js: {
+ dist: {
+ options: {
+ module: null, // no bundle module for all the html2js templates
+ base: '.'
+ },
+ files: [{
+ expand: true,
+ src: ['template/**/*.html'],
+ ext: '.html.js'
+ }]
+ }
+ },
+ jshint: {
+ files: ['Gruntfile.js','src/**/*.js'],
+ options: {
+ jshintrc: '.jshintrc'
+ }
+ },
+ karma: {
+ options: {
+ configFile: 'karma.conf.js'
+ },
+ watch: {
+ background: true
+ },
+ continuous: {
+ singleRun: true
+ },
+ jenkins: {
+ singleRun: true,
+ autoWatch: false,
+ colors: false,
+ reporters: ['dots', 'junit'],
+ browsers: ['Chrome', 'ChromeCanary', 'Firefox', 'Opera', '/Users/jenkins/bin/safari.sh']
+ },
+ travis: {
+ singleRun: true,
+ autoWatch: false,
+ reporters: ['dots'],
+ browsers: ['Firefox']
+ },
+ coverage: {
+ preprocessors: {
+ 'src/*/*.js': 'coverage'
+ },
+ reporters: ['progress', 'coverage']
+ }
+ },
+ conventionalChangelog: {
+ options: {
+ changelogOpts: {
+ preset: 'angular'
+ },
+ templateFile: 'misc/changelog.tpl.md'
+ },
+ release: {
+ src: 'CHANGELOG.md'
+ }
+ },
+ shell: {
+ //We use %version% and evluate it at run-time, because <%= pkg.version %>
+ //is only evaluated once
+ 'release-prepare': [
+ 'grunt before-test after-test',
+ 'grunt version', //remove "-SNAPSHOT"
+ 'grunt conventionalChangelog'
+ ],
+ 'release-complete': [
+ 'git commit CHANGELOG.md package.json -m "chore(release): v%version%"',
+ 'git tag %version%'
+ ],
+ 'release-start': [
+ 'grunt version:minor:"SNAPSHOT"',
+ 'git commit package.json -m "chore(release): Starting v%version%"'
+ ]
+ },
+ 'ddescribe-iit': {
+ files: [
+ 'src/**/*.spec.js'
+ ]
+ }
+ });
+
+ //register before and after test tasks so we've don't have to change cli
+ //options on the google's CI server
+ grunt.registerTask('before-test', ['enforce', 'ddescribe-iit', 'jshint', 'html2js']);
+ grunt.registerTask('after-test', ['build', 'copy']);
+
+ //Rename our watch task to 'delta', then make actual 'watch'
+ //task build things, then start test server
+ grunt.renameTask('watch', 'delta');
+ grunt.registerTask('watch', ['before-test', 'after-test', 'karma:watch', 'delta']);
+
+ // Default task.
+ grunt.registerTask('default', ['before-test', 'test', 'after-test']);
+
+ grunt.registerTask('enforce', 'Install commit message enforce script if it doesn\'t exist', function() {
+ if (!grunt.file.exists('.git/hooks/commit-msg')) {
+ grunt.file.copy('misc/validate-commit-msg.js', '.git/hooks/commit-msg');
+ require('fs').chmodSync('.git/hooks/commit-msg', '0755');
+ }
+ });
+
+ //Common ui.bootstrap module containing all modules for src and templates
+ //findModule: Adds a given module to config
+ var foundModules = {};
+ function findModule(name) {
+ if (foundModules[name]) { return; }
+ foundModules[name] = true;
+
+ function breakup(text, separator) {
+ return text.replace(/[A-Z]/g, function (match) {
+ return separator + match;
+ });
+ }
+ function ucwords(text) {
+ return text.replace(/^([a-z])|\s+([a-z])/g, function ($1) {
+ return $1.toUpperCase();
+ });
+ }
+ function enquote(str) {
+ return '"' + str + '"';
+ }
+
+ var module = {
+ name: name,
+ moduleName: enquote('ui.bootstrap.' + name),
+ displayName: ucwords(breakup(name, ' ')),
+ srcFiles: grunt.file.expand('src/'+name+'/*.js'),
+ cssFiles: grunt.file.expand('src/'+name+'/*.css'),
+ tplFiles: grunt.file.expand('template/'+name+'/*.html'),
+ tpljsFiles: grunt.file.expand('template/'+name+'/*.html.js'),
+ tplModules: grunt.file.expand('template/'+name+'/*.html').map(enquote),
+ dependencies: dependenciesForModule(name),
+ docs: {
+ md: grunt.file.expand('src/'+name+'/docs/*.md')
+ .map(grunt.file.read).map(markdown).join('\n'),
+ js: grunt.file.expand('src/'+name+'/docs/*.js')
+ .map(grunt.file.read).join('\n'),
+ html: grunt.file.expand('src/'+name+'/docs/*.html')
+ .map(grunt.file.read).join('\n')
+ }
+ };
+
+ var styles = {
+ css: [],
+ js: []
+ };
+ module.cssFiles.forEach(processCSS.bind(null, styles, true));
+ if (styles.css.length) {
+ module.css = styles.css.join('\n');
+ module.cssJs = styles.js.join('\n');
+ }
+
+ module.dependencies.forEach(findModule);
+ grunt.config('modules', grunt.config('modules').concat(module));
+ }
+
+ function dependenciesForModule(name) {
+ var deps = [];
+ grunt.file.expand('src/' + name + '/*.js')
+ .map(grunt.file.read)
+ .forEach(function(contents) {
+ //Strategy: find where module is declared,
+ //and from there get everything inside the [] and split them by comma
+ var moduleDeclIndex = contents.indexOf('angular.module(');
+ var depArrayStart = contents.indexOf('[', moduleDeclIndex);
+ var depArrayEnd = contents.indexOf(']', depArrayStart);
+ var dependencies = contents.substring(depArrayStart + 1, depArrayEnd);
+ dependencies.split(',').forEach(function(dep) {
+ if (dep.indexOf('ui.bootstrap.') > -1) {
+ var depName = dep.trim().replace('ui.bootstrap.','').replace(/['"]/g,'');
+ if (deps.indexOf(depName) < 0) {
+ deps.push(depName);
+ //Get dependencies for this new dependency
+ deps = deps.concat(dependenciesForModule(depName));
+ }
+ }
+ });
+ });
+ return deps;
+ }
+
+ grunt.registerTask('dist', 'Override dist directory', function() {
+ var dir = this.args[0];
+ if (dir) { grunt.config('dist', dir); }
+ });
+
+ grunt.registerTask('build', 'Create bootstrap build files', function() {
+ var _ = grunt.util._;
+
+ //If arguments define what modules to build, build those. Else, everything
+ if (this.args.length) {
+ this.args.forEach(findModule);
+ grunt.config('filename', grunt.config('filenamecustom'));
+ } else {
+ grunt.file.expand({
+ filter: 'isDirectory', cwd: '.'
+ }, 'src/*').forEach(function(dir) {
+ findModule(dir.split('/')[1]);
+ });
+ }
+
+ var modules = grunt.config('modules');
+ grunt.config('srcModules', _.pluck(modules, 'moduleName'));
+ grunt.config('tplModules', _.pluck(modules, 'tplModules').filter(function(tpls) { return tpls.length > 0;} ));
+ grunt.config('demoModules', modules
+ .filter(function(module) {
+ return module.docs.md && module.docs.js && module.docs.html;
+ })
+ .sort(function(a, b) {
+ if (a.name < b.name) { return -1; }
+ if (a.name > b.name) { return 1; }
+ return 0;
+ })
+ );
+
+ var cssStrings = _.flatten(_.compact(_.pluck(modules, 'css')));
+ var cssJsStrings = _.flatten(_.compact(_.pluck(modules, 'cssJs')));
+ if (cssStrings.length) {
+ grunt.config('meta.cssInclude', cssJsStrings.join('\n'));
+
+ grunt.file.write(grunt.config('meta.cssFileDest'), grunt.config('meta.cssFileBanner') +
+ cssStrings.join('\n'));
+
+ grunt.log.writeln('File ' + grunt.config('meta.cssFileDest') + ' created');
+ }
+
+ var moduleFileMapping = _.clone(modules, true);
+ moduleFileMapping.forEach(function (module) {
+ delete module.docs;
+ });
+
+ grunt.config('moduleFileMapping', moduleFileMapping);
+
+ var srcFiles = _.pluck(modules, 'srcFiles');
+ var tpljsFiles = _.pluck(modules, 'tpljsFiles');
+ //Set the concat task to concatenate the given src modules
+ grunt.config('concat.dist.src', grunt.config('concat.dist.src')
+ .concat(srcFiles));
+ //Set the concat-with-templates task to concat the given src & tpl modules
+ grunt.config('concat.dist_tpls.src', grunt.config('concat.dist_tpls.src')
+ .concat(srcFiles).concat(tpljsFiles));
+
+ grunt.task.run(['concat', 'uglify', 'makeModuleMappingFile', 'makeRawFilesJs', 'makeVersionsMappingFile']);
+ });
+
+ grunt.registerTask('test', 'Run tests on singleRun karma server', function () {
+ //this task can be executed in 3 different environments: local, Travis-CI and Jenkins-CI
+ //we need to take settings for each one into account
+ if (process.env.TRAVIS) {
+ grunt.task.run('karma:travis');
+ } else {
+ var isToRunJenkinsTask = !!this.args.length;
+ if(grunt.option('coverage')) {
+ var karmaOptions = grunt.config.get('karma.options'),
+ coverageOpts = grunt.config.get('karma.coverage');
+ grunt.util._.extend(karmaOptions, coverageOpts);
+ grunt.config.set('karma.options', karmaOptions);
+ }
+ grunt.task.run(this.args.length ? 'karma:jenkins' : 'karma:continuous');
+ }
+ });
+
+ grunt.registerTask('makeModuleMappingFile', function () {
+ var _ = grunt.util._;
+ var moduleMappingJs = 'dist/assets/module-mapping.json';
+ var moduleMappings = grunt.config('moduleFileMapping');
+ var moduleMappingsMap = _.object(_.pluck(moduleMappings, 'name'), moduleMappings);
+ var jsContent = JSON.stringify(moduleMappingsMap);
+ grunt.file.write(moduleMappingJs, jsContent);
+ grunt.log.writeln('File ' + moduleMappingJs.cyan + ' created.');
+ });
+
+ grunt.registerTask('makeRawFilesJs', function () {
+ var _ = grunt.util._;
+ var jsFilename = 'dist/assets/raw-files.json';
+ var genRawFilesJs = require('./misc/raw-files-generator');
+
+ genRawFilesJs(grunt, jsFilename, _.flatten(grunt.config('concat.dist_tpls.src')),
+ grunt.config('meta.banner'), grunt.config('meta.cssFileBanner'));
+ });
+
+ grunt.registerTask('makeVersionsMappingFile', function () {
+ var done = this.async();
+
+ var exec = require('child_process').exec;
+
+ var versionsMappingFile = 'dist/versions-mapping.json';
+
+ exec('git tag --sort -version:refname', function(error, stdout, stderr) {
+ // Let's remove the oldest 14 versions.
+ var versions = stdout.split('\n').slice(0, -14);
+ var jsContent = versions.map(function(version) {
+ return {
+ version: version,
+ url: '/bootstrap/versioned-docs/' + version
+ };
+ });
+ jsContent[0] = {
+ version: 'Current',
+ url: '/bootstrap'
+ };
+ grunt.file.write(versionsMappingFile, JSON.stringify(jsContent));
+ grunt.log.writeln('File ' + versionsMappingFile.cyan + ' created.');
+ done();
+ });
+
+ });
+
+ /**
+ * Logic from AngularJS
+ * https://github.com/angular/angular.js/blob/36831eccd1da37c089f2141a2c073a6db69f3e1d/lib/grunt/utils.js#L121-L145
+ */
+ function processCSS(state, minify, file) {
+ /* jshint quotmark: false */
+ var css = fs.readFileSync(file).toString(),
+ js;
+ state.css.push(css);
+
+ if(minify){
+ css = css
+ .replace(/\r?\n/g, '')
+ .replace(/\/\*.*?\*\//g, '')
+ .replace(/:\s+/g, ':')
+ .replace(/\s*\{\s*/g, '{')
+ .replace(/\s*\}\s*/g, '}')
+ .replace(/\s*\,\s*/g, ',')
+ .replace(/\s*\;\s*/g, ';');
+ }
+ //escape for js
+ css = css
+ .replace(/\\/g, '\\\\')
+ .replace(/'/g, "\\'")
+ .replace(/\r?\n/g, '\\n');
+ js = "!angular.$$csp() && angular.element(document).find('head').prepend('<style type=\"text/css\">" + css + "</style>');";
+ state.js.push(js);
+
+ return state;
+ }
+
+ function setVersion(type, suffix) {
+ var file = 'package.json';
+ var VERSION_REGEX = /([\'|\"]version[\'|\"][ ]*:[ ]*[\'|\"])([\d|.]*)(-\w+)*([\'|\"])/;
+ var contents = grunt.file.read(file);
+ var version;
+ contents = contents.replace(VERSION_REGEX, function(match, left, center) {
+ version = center;
+ if (type) {
+ version = require('semver').inc(version, type);
+ }
+ //semver.inc strips our suffix if it existed
+ if (suffix) {
+ version += '-' + suffix;
+ }
+ return left + version + '"';
+ });
+ grunt.log.ok('Version set to ' + version.cyan);
+ grunt.file.write(file, contents);
+ return version;
+ }
+
+ grunt.registerTask('version', 'Set version. If no arguments, it just takes off suffix', function() {
+ setVersion(this.args[0], this.args[1]);
+ });
+
+ grunt.registerMultiTask('shell', 'run shell commands', function() {
+ var self = this;
+ var sh = require('shelljs');
+ self.data.forEach(function(cmd) {
+ cmd = cmd.replace('%version%', grunt.file.readJSON('package.json').version);
+ grunt.log.ok(cmd);
+ var result = sh.exec(cmd,{silent:true});
+ if (result.code !== 0) {
+ grunt.fatal(result.output);
+ }
+ });
+ });
+
+ return grunt;
+};
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/LICENSE b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/LICENSE
new file mode 100644
index 0000000..18db5a5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/LICENSE
@@ -0,0 +1,22 @@
+The MIT License
+
+Copyright (c) 2012-2015 the AngularUI Team, https://github.com/organizations/angular-ui/teams/291112
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/README.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/README.md
new file mode 100644
index 0000000..10d868d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/README.md
@@ -0,0 +1,136 @@
+### UI Bootstrap - [AngularJS](http://angularjs.org/) directives specific to [Bootstrap](http://getbootstrap.com)
+
+[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/angular-ui/bootstrap?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+[![Build Status](https://secure.travis-ci.org/angular-ui/bootstrap.svg)](http://travis-ci.org/angular-ui/bootstrap)
+[![devDependency Status](https://david-dm.org/angular-ui/bootstrap/dev-status.svg?branch=master)](https://david-dm.org/angular-ui/bootstrap#info=devDependencies)
+
+### Quick links
+- [Demo](#demo)
+- [Angular 2](#angular-2)
+- [Installation](#installation)
+ - [NPM](#install-with-npm)
+ - [Bower](#install-with-bower)
+ - [NuGet](#install-with-nuget)
+ - [Custom](#custom-build)
+ - [Manual](#manual-download)
+- [Support](#support)
+ - [FAQ](#faq)
+ - [Code of Conduct](#code-of-conduct)
+ - [PREFIX MIGRATION GUIDE](#prefix-migration-guide)
+ - [Supported browsers](#supported-browsers)
+ - [Need help?](#need-help)
+ - [Found a bug?](#found-a-bug)
+- [Contributing to the project](#contributing-to-the-project)
+- [Development, meeting minutes, roadmap and more.](#development-meeting-minutes-roadmap-and-more)
+
+
+# Demo
+
+Do you want to see directives in action? Visit http://angular-ui.github.io/bootstrap/!
+
+# Angular 2
+
+Are you interested in Angular 2? We are on our way! Check out [ng-bootstrap](https://github.com/ui-bootstrap/core).
+
+# Installation
+
+Installation is easy as UI Bootstrap has minimal dependencies - only the AngularJS and Twitter Bootstrap's CSS are required.
+Note: Since version 0.13.0, UI Bootstrap depends on [ngAnimate](https://docs.angularjs.org/api/ngAnimate) for transitions and animations, such as the accordion, carousel, etc. Include `ngAnimate` in the module dependencies for your app in order to enable animation.
+
+Additionally, it is strongly recommended that for UI Bootstrap 0.13.3 and higher you use Angular 1.3.18 or higher due to animation fixes.
+
+#### Install with NPM
+
+```sh
+$ npm install angular-ui-bootstrap
+```
+
+This will install AngularJS and Bootstrap NPM packages.
+
+#### Install with Bower
+```sh
+$ bower install angular-bootstrap
+```
+
+Note: do not install 'angular-ui-bootstrap'. A separate repository - [bootstrap-bower](https://github.com/angular-ui/bootstrap-bower) - hosts the compiled javascript file and bower.json.
+
+#### Install with NuGet
+To install AngularJS UI Bootstrap, run the following command in the Package Manager Console
+
+```sh
+PM> Install-Package Angular.UI.Bootstrap
+```
+
+#### Custom build
+
+Head over to http://angular-ui.github.io/bootstrap/ and hit the *Custom build* button to create your own custom UI Bootstrap build, just the way you like it.
+
+#### Manual download
+
+After downloading dependencies (or better yet, referencing them from your favorite CDN) you need to download build version of this project. All the files and their purposes are described here:
+https://github.com/angular-ui/bootstrap/tree/gh-pages#build-files
+Don't worry, if you are not sure which file to take, opt for `ui-bootstrap-tpls-[version].min.js`.
+
+### Adding dependency to your project
+
+When you are done downloading all the dependencies and project files the only remaining part is to add dependencies on the `ui.bootstrap` AngularJS module:
+
+```js
+angular.module('myModule', ['ui.bootstrap']);
+```
+
+If you're a Browserify or Webpack user, you can do:
+
+```js
+var uibs = require('angular-ui-bootstrap');
+
+angular.module('myModule', [uibs]);
+```
+
+# Support
+
+## FAQ
+
+https://github.com/angular-ui/bootstrap/wiki/FAQ
+
+# Code of Conduct
+
+Take a moment to read or [Code of Conduct](CODE_OF_CONDUCT.md)
+
+## PREFIX MIGRATION GUIDE
+
+If you're updating your application to use prefixes, please check the [migration guide](https://github.com/angular-ui/bootstrap/wiki/Migration-guide-for-prefixes).
+
+## Supported browsers
+
+Directives from this repository are automatically tested with the following browsers:
+* Chrome (stable and canary channel)
+* Firefox
+* IE 9 and 10
+* Opera
+* Safari
+
+Modern mobile browsers should work without problems.
+
+## Need help?
+Need help using UI Bootstrap?
+
+* Live help in the IRC (`#angularjs` channel at the `freenode` network). Use this [webchat](https://webchat.freenode.net/) or your own IRC client.
+* Ask a question in [StackOverflow](http://stackoverflow.com/) under the [angular-ui-bootstrap](http://stackoverflow.com/questions/tagged/angular-ui-bootstrap) tag.
+
+**Please do not create new issues in this repository to ask questions about using UI Bootstrap**
+
+## Found a bug?
+Please take a look at [CONTRIBUTING.md](CONTRIBUTING.md#you-think-youve-found-a-bug) and submit your issue [here](https://github.com/angular-ui/bootstrap/issues/new).
+
+
+----
+
+
+# Contributing to the project
+
+We are always looking for the quality contributions! Please check the [CONTRIBUTING.md](CONTRIBUTING.md) for the contribution guidelines.
+
+# Development, meeting minutes, roadmap and more.
+
+Head over to the [Wiki](https://github.com/angular-ui/bootstrap/wiki) for notes on development for UI Bootstrap, meeting minutes from the UI Bootstrap team, roadmap plans, project philosophy and more.
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/karma.conf.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/karma.conf.js
new file mode 100644
index 0000000..c3da490
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/karma.conf.js
@@ -0,0 +1,73 @@
+// Karma configuration
+// Generated on Sat Mar 28 2015 11:17:34 GMT-0700 (PDT)
+
+module.exports = function(config) {
+ config.set({
+
+ // base path that will be used to resolve all patterns (eg. files, exclude)
+ basePath: '',
+
+
+ // frameworks to use
+ // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
+ frameworks: ['jasmine'],
+
+
+ // list of files / patterns to load in the browser
+ files: [
+ 'misc/test-lib/jquery-1.8.2.min.js',
+ 'node_modules/angular/angular.js',
+ 'node_modules/angular-mocks/angular-mocks.js',
+ 'node_modules/angular-sanitize/angular-sanitize.js',
+ 'misc/test-lib/helpers.js',
+ 'src/**/*.js',
+ 'template/**/*.js'
+ ],
+
+
+ // list of files to exclude
+ exclude: [
+ 'src/**/docs/*'
+ ],
+
+
+ // preprocess matching files before serving them to the browser
+ // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
+ preprocessors: {
+ },
+
+
+ // test results reporter to use
+ // possible values: 'dots', 'progress'
+ // available reporters: https://npmjs.org/browse/keyword/karma-reporter
+ reporters: ['progress'],
+
+ reportSlowerThan: 100,
+
+ // web server port
+ port: 9876,
+
+
+ // enable / disable colors in the output (reporters and logs)
+ colors: true,
+
+
+ // level of logging
+ // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
+ logLevel: config.LOG_INFO,
+
+
+ // enable / disable watching file and executing tests whenever any file changes
+ autoWatch: true,
+
+
+ // start these browsers
+ // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
+ browsers: ['Chrome'],
+
+
+ // Continuous Integration mode
+ // if true, Karma captures browsers, runs the tests and exits
+ singleRun: false
+ });
+};
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/changelog.tpl.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/changelog.tpl.md
new file mode 100644
index 0000000..712c490
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/changelog.tpl.md
@@ -0,0 +1,16 @@
+# <%= version%> (<%= today%>)
+<% if (_(changelog.feat).size() > 0) { %>
+## Features
+<% _(changelog.feat).keys().sort().forEach(function(scope) { %>
+- **<%= scope%>:** <% changelog.feat[scope].forEach(function(change) { %>
+ - <%= change.msg%> (<%= helpers.commitLink(change.sha1) %>) <% }); %><% }); %> <% } %>
+<% if (_(changelog.fix).size() > 0) { %>
+## Bug Fixes
+<% _(changelog.fix).keys().sort().forEach(function(scope) { %>
+- **<%= scope%>:** <% changelog.fix[scope].forEach(function(change) { %>
+ - <%= change.msg%> (<%= helpers.commitLink(change.sha1) %>) <% }); %><% }); %> <% } %>
+<% if (_(changelog.breaking).size() > 0) { %>
+## Breaking Changes
+<% _(changelog.breaking).keys().sort().forEach(function(scope) { %>
+- **<%= scope%>:** <% changelog.breaking[scope].forEach(function(change) { %>
+<%= change.msg%><% }); %><% }); %> <% } %>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/app.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/app.js
new file mode 100644
index 0000000..5c8580c
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/app.js
@@ -0,0 +1,315 @@
+/* global FastClick, smoothScroll */
+angular.module('ui.bootstrap.demo', ['ui.bootstrap', 'plunker', 'ngTouch', 'ngAnimate', 'ngSanitize'], function($httpProvider){
+ FastClick.attach(document.body);
+ delete $httpProvider.defaults.headers.common['X-Requested-With'];
+}).run(['$location', function($location){
+ //Allows us to navigate to the correct element on initialization
+ if ($location.path() !== '' && $location.path() !== '/') {
+ smoothScroll(document.getElementById($location.path().substring(1)), 500, function(el) {
+ location.replace('#' + el.id);
+ });
+ }
+}]).factory('buildFilesService', function ($http, $q) {
+
+ var moduleMap;
+ var rawFiles;
+
+ return {
+ getModuleMap: getModuleMap,
+ getRawFiles: getRawFiles,
+ get: function () {
+ return $q.all({
+ moduleMap: getModuleMap(),
+ rawFiles: getRawFiles()
+ });
+ }
+ };
+
+ function getModuleMap() {
+ return moduleMap ? $q.when(moduleMap) : $http.get('assets/module-mapping.json')
+ .then(function (result) {
+ moduleMap = result.data;
+ return moduleMap;
+ });
+ }
+
+ function getRawFiles() {
+ return rawFiles ? $q.when(rawFiles) : $http.get('assets/raw-files.json')
+ .then(function (result) {
+ rawFiles = result.data;
+ return rawFiles;
+ });
+ }
+
+})
+.controller('MainCtrl', MainCtrl)
+.controller('SelectModulesCtrl', SelectModulesCtrl)
+.controller('DownloadCtrl', DownloadCtrl);
+
+function MainCtrl($scope, $http, $document, $uibModal, orderByFilter) {
+ // Grab old version docs
+ $http.get('/versions-mapping.json')
+ .then(function(result) {
+ $scope.oldDocs = result.data;
+ });
+
+ $scope.showBuildModal = function() {
+ var modalInstance = $uibModal.open({
+ templateUrl: 'buildModal.html',
+ controller: 'SelectModulesCtrl',
+ resolve: {
+ modules: function(buildFilesService) {
+ return buildFilesService.getModuleMap()
+ .then(function (moduleMap) {
+ return Object.keys(moduleMap);
+ });
+ }
+ }
+ });
+ };
+
+ $scope.showDownloadModal = function() {
+ var modalInstance = $uibModal.open({
+ templateUrl: 'downloadModal.html',
+ controller: 'DownloadCtrl'
+ });
+ };
+}
+
+function SelectModulesCtrl($scope, $uibModalInstance, modules, buildFilesService) {
+ $scope.selectedModules = [];
+ $scope.modules = modules;
+
+ $scope.selectedChanged = function(module, selected) {
+ if (selected) {
+ $scope.selectedModules.push(module);
+ } else {
+ $scope.selectedModules.splice($scope.selectedModules.indexOf(module), 1);
+ }
+ };
+
+ $scope.downloadBuild = function () {
+ $uibModalInstance.close($scope.selectedModules);
+ };
+
+ $scope.cancel = function () {
+ $uibModalInstance.dismiss();
+ };
+
+ $scope.isOldBrowser = function () {
+ return isOldBrowser;
+ };
+
+ $scope.build = function (selectedModules, version) {
+ /* global JSZip, saveAs */
+ var moduleMap, rawFiles;
+
+ buildFilesService.get().then(function (buildFiles) {
+ moduleMap = buildFiles.moduleMap;
+ rawFiles = buildFiles.rawFiles;
+
+ generateBuild();
+ });
+
+ function generateBuild() {
+ var srcModuleNames = selectedModules
+ .map(function (module) {
+ return moduleMap[module];
+ })
+ .reduce(function (toBuild, module) {
+ addIfNotExists(toBuild, module.name);
+
+ module.dependencies.forEach(function (depName) {
+ addIfNotExists(toBuild, depName);
+ });
+ return toBuild;
+ }, []);
+
+ var srcModules = srcModuleNames
+ .map(function (moduleName) {
+ return moduleMap[moduleName];
+ });
+
+ var srcModuleFullNames = srcModules
+ .map(function (module) {
+ return module.moduleName;
+ });
+
+ var srcJsContent = srcModules
+ .reduce(function (buildFiles, module) {
+ return buildFiles.concat(module.srcFiles);
+ }, [])
+ .map(getFileContent)
+ .join('\n')
+ ;
+
+ var jsFile = createNoTplFile(srcModuleFullNames, srcJsContent);
+
+ var tplModuleNames = srcModules
+ .reduce(function (tplModuleNames, module) {
+ return tplModuleNames.concat(module.tplModules);
+ }, []);
+
+ var tplJsContent = srcModules
+ .reduce(function (buildFiles, module) {
+ return buildFiles.concat(module.tpljsFiles);
+ }, [])
+ .map(getFileContent)
+ .join('\n')
+ ;
+
+ var jsTplFile = createWithTplFile(srcModuleFullNames, srcJsContent, tplModuleNames, tplJsContent);
+
+ var cssContent = srcModules
+ .map(function (module) {
+ return module.css;
+ })
+ .filter(function (css) {
+ return css;
+ })
+ .join('\n')
+ ;
+
+ var cssJsContent = srcModules
+ .map(function (module) {
+ return module.cssJs;
+ })
+ .filter(function (cssJs) {
+ return cssJs;
+ })
+ .join('\n')
+ ;
+
+ var footer = cssJsContent;
+
+ var zip = new JSZip();
+ zip.file('ui-bootstrap-custom-' + version + '.js', rawFiles.banner + jsFile + footer);
+ zip.file('ui-bootstrap-custom-' + version + '.min.js', rawFiles.banner + uglify(jsFile + footer));
+ zip.file('ui-bootstrap-custom-tpls-' + version + '.js', rawFiles.banner + jsTplFile + footer);
+ zip.file('ui-bootstrap-custom-tpls-' + version + '.min.js', rawFiles.banner + uglify(jsTplFile + footer));
+ zip.file('ui-bootstrap-custom-tpls-' + version + '.min.js', rawFiles.banner + uglify(jsTplFile + footer));
+
+ if (cssContent) {
+ zip.file('ui-bootstrap-custom-' + version + '-csp.css', rawFiles.cssBanner + cssContent);
+ }
+
+ saveAs(zip.generate({type: 'blob'}), 'ui-bootstrap-custom-build.zip');
+ }
+
+ function createNoTplFile(srcModuleNames, srcJsContent) {
+ return 'angular.module("ui.bootstrap", [' + srcModuleNames.join(',') + ']);\n' +
+ srcJsContent;
+ }
+
+ function createWithTplFile(srcModuleNames, srcJsContent, tplModuleNames, tplJsContent) {
+ var depModuleNames = srcModuleNames.slice();
+ depModuleNames.unshift('"ui.bootstrap.tpls"');
+
+ return 'angular.module("ui.bootstrap", [' + depModuleNames.join(',') + ']);\n' +
+ 'angular.module("ui.bootstrap.tpls", [' + tplModuleNames.join(',') + ']);\n' +
+ srcJsContent + '\n' + tplJsContent;
+
+ }
+
+ function addIfNotExists(array, element) {
+ if (array.indexOf(element) == -1) {
+ array.push(element);
+ }
+ }
+
+ function getFileContent(fileName) {
+ return rawFiles.files[fileName];
+ }
+
+ function uglify(js) {
+ /* global UglifyJS */
+
+ var ast = UglifyJS.parse(js);
+ ast.figure_out_scope();
+
+ var compressor = UglifyJS.Compressor();
+ var compressedAst = ast.transform(compressor);
+
+ compressedAst.figure_out_scope();
+ compressedAst.compute_char_frequency();
+ compressedAst.mangle_names();
+
+ var stream = UglifyJS.OutputStream();
+ compressedAst.print(stream);
+
+ return stream.toString();
+ }
+ };
+}
+
+function DownloadCtrl($scope, $uibModalInstance) {
+ $scope.options = {
+ minified: true,
+ tpls: true
+ };
+
+ $scope.download = function (version) {
+ var options = $scope.options;
+
+ var downloadUrl = ['ui-bootstrap-'];
+ if (options.tpls) {
+ downloadUrl.push('tpls-');
+ }
+ downloadUrl.push(version);
+ if (options.minified) {
+ downloadUrl.push('.min');
+ }
+ downloadUrl.push('.js');
+
+ return downloadUrl.join('');
+ };
+
+ $scope.cancel = function () {
+ $uibModalInstance.dismiss();
+ };
+}
+
+/*
+ * The following compatibility check is from:
+ *
+ * Bootstrap Customizer (http://getbootstrap.com/customize/)
+ * Copyright 2011-2014 Twitter, Inc.
+ *
+ * Licensed under the Creative Commons Attribution 3.0 Unported License. For
+ * details, see http://creativecommons.org/licenses/by/3.0/.
+ */
+var isOldBrowser;
+(function () {
+
+ var supportsFile = (window.File && window.FileReader && window.FileList && window.Blob);
+ function failback() {
+ isOldBrowser = true;
+ }
+ /**
+ * Based on:
+ * Blob Feature Check v1.1.0
+ * https://github.com/ssorallen/blob-feature-check/
+ * License: Public domain (http://unlicense.org)
+ */
+ var url = window.URL;
+ var svg = new Blob(
+ ['<svg xmlns=\'http://www.w3.org/2000/svg\'></svg>'],
+ { type: 'image/svg+xml;charset=utf-8' }
+ );
+ var objectUrl = url.createObjectURL(svg);
+
+ if (/^blob:/.exec(objectUrl) === null || !supportsFile) {
+ // `URL.createObjectURL` created a URL that started with something other
+ // than "blob:", which means it has been polyfilled and is not supported by
+ // this browser.
+ failback();
+ } else {
+ angular.element('<img/>')
+ .on('load', function () {
+ isOldBrowser = false;
+ })
+ .on('error', failback)
+ .attr('src', objectUrl);
+ }
+
+ })();
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/demo.css b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/demo.css
new file mode 100644
index 0000000..d1cadcd
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/demo.css
@@ -0,0 +1,323 @@
+body {
+ opacity: 1;
+ -webkit-transition: opacity 1s ease;
+ -moz-transition: opacity 1s ease;
+ transition: opacity 1s;
+}
+
+.ng-cloak {
+ opacity: 0;
+}
+
+.ng-invalid {
+ border: 1px solid red !important;
+}
+
+section {
+ padding-top: 30px;
+}
+
+.page-header h1 > small > a {
+ color: #999;
+}
+.page-header h1 > small > a:hover {
+ text-decoration: none;
+}
+
+.footer {
+ text-align: center;
+ padding: 30px 0;
+ margin-top: 70px;
+ border-top: 1px solid #e5e5e5;
+ background-color: #f5f5f5;
+}
+
+.bs-social {
+ margin-top: 20px;
+ margin-bottom: 20px;
+ text-align: center;
+}
+
+@media (min-width: 768px) {
+
+ .bs-social {
+ text-align: left;
+ }
+
+}
+
+.nav, .pagination, .carousel, .panel-title a {
+ cursor: pointer;
+}
+
+.bs-social-buttons {
+ display: inline-block;
+ margin-bottom: 0;
+ padding-left: 0;
+ list-style: none;
+}
+.bs-social-buttons li {
+ display: inline-block;
+ padding: 5px 8px;
+ line-height: 1;
+}
+
+@media (max-width: 767px) {
+
+ .visible-xs.collapse.in {
+ display: block!important;
+ }
+ .visible-xs.collapse {
+ display: none!important;
+ }
+
+}
+
+.navbar .collapse {
+ border-top: 1px solid #e7e7e7;
+ margin-left: -15px;
+ margin-right: -15px;
+ padding-right: 15px;
+ padding-left: 15px;
+}
+
+.show-grid {
+ margin-bottom: 15px;
+}
+
+/*
+ * Container
+ *
+ * Tweak to width of container.
+ */
+
+/*@media (min-width: 1200px) {
+ .container{
+ max-width: 970px;
+ }
+}*/
+
+/*
+ * Tabs
+ *
+ * Tweaks to the Tabs.
+ */
+
+.code .nav-tabs {
+border-bottom: 1px solid #ccc;
+}
+
+.code pre, .code code {
+ border-top: none;
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+}
+
+.code .nav-tabs>li.active>a, .code .nav-tabs>li.active>a:hover, .code .nav-tabs>li.active>a:focus {
+background-color: #f8f8f8;
+border: 1px solid #ccc;
+border-bottom-color: transparent;
+}
+
+/*
+ * Button Inverse
+ *
+ * Buttons in the masthead.
+ */
+
+.btn-outline-inverse {
+color: #fff;
+background-color: transparent;
+border-color: #cdbfe3;
+margin: 10px;
+}
+
+@media (min-width: 768px) {
+
+ .btn-outline-inverse {
+ width: auto;
+ margin: 20px 5px 20px 0;
+ padding: 18px 24px;
+ font-size: 21px;
+ }
+
+}
+
+.btn-outline-inverse:hover, .btn-outline-inverse:focus, .btn-outline-inverse:active {
+color: #563d7c;
+text-shadow: none;
+background-color: #fff;
+border-color: #fff;
+}
+
+
+/* Page headers */
+.bs-header {
+ padding: 30px 15px 40px; /* side padding builds on .container 15px, so 30px */
+ font-size: 16px;
+ text-align: center;
+ text-shadow: 0 1px 0 rgba(0,0,0,.15);
+ color: #cdbfe3;
+ background-color: #563d7c;
+ background-image: url(header.png);
+}
+.bs-header a {
+ color: #fff;
+ font-weight: normal;
+}
+.bs-header h1 {
+ color: #fff;
+}
+.bs-header p {
+ font-weight: 200;
+ line-height: 1.4;
+}
+.bs-header .container {
+ position: relative;
+}
+
+@media (min-width: 768px) {
+ .bs-header {
+ font-size: 30px;
+ text-align: left;
+ }
+ .bs-header h1 {
+ font-size: 100px;
+ line-height: 1;
+ }
+}
+
+@media (min-width: 992px) {
+ .bs-header p {
+ margin-right: 25%;
+ }
+}
+
+.navbar-inner {
+ -webkit-box-shadow: 0 3px 3px rgba(0,0,0,0.175);
+ box-shadow: 0 3px 3px rgba(0,0,0,0.175);
+}
+
+/*
+ * Side navigation
+ *
+ * Scrollspy and affixed enhanced navigation to highlight sections and secondary
+ * sections of docs content.
+ */
+
+/* By default it's not affixed in mobile views, so undo that */
+.bs-sidebar.affix {
+ position: static;
+}
+
+/* First level of nav */
+.bs-sidenav {
+ margin-top: 30px;
+ margin-bottom: 30px;
+ padding-top: 10px;
+ padding-bottom: 10px;
+ text-shadow: 0 1px 0 #fff;
+ background-color: #f7f5fa;
+ border-radius: 5px;
+}
+
+/* All levels of nav */
+.bs-sidebar .nav > li > a {
+ display: block;
+ color: #716b7a;
+ padding: 5px 20px;
+}
+.bs-sidebar .nav > li > a:hover,
+.bs-sidebar .nav > li > a:focus {
+ text-decoration: none;
+ background-color: #e5e3e9;
+ border-right: 1px solid #dbd8e0;
+}
+.bs-sidebar .nav > .active > a,
+.bs-sidebar .nav > .active:hover > a,
+.bs-sidebar .nav > .active:focus > a {
+ font-weight: bold;
+ color: #563d7c;
+ background-color: transparent;
+ border-right: 1px solid #563d7c;
+}
+
+/* Nav: second level (shown on .active) */
+.bs-sidebar .nav .nav {
+ display: none; /* Hide by default, but at >768px, show it */
+ margin-bottom: 8px;
+}
+.bs-sidebar .nav .nav > li > a {
+ padding-top: 3px;
+ padding-bottom: 3px;
+ padding-left: 30px;
+ font-size: 90%;
+}
+
+/* Show and affix the side nav when space allows it */
+@media (min-width: 992px) {
+ .bs-sidebar .nav > .active > ul {
+ display: block;
+ }
+ /* Widen the fixed sidebar */
+ .bs-sidebar.affix,
+ .bs-sidebar.affix-bottom {
+ width: 213px;
+ }
+ .bs-sidebar.affix {
+ position: fixed; /* Undo the static from mobile first approach */
+ top: 80px;
+ }
+ .bs-sidebar.affix-bottom {
+ position: absolute; /* Undo the static from mobile first approach */
+ }
+ .bs-sidebar.affix-bottom .bs-sidenav,
+ .bs-sidebar.affix .bs-sidenav {
+ margin-top: 0;
+ margin-bottom: 0;
+ }
+}
+@media (min-width: 1200px) {
+ /* Widen the fixed sidebar again */
+ .bs-sidebar.affix-bottom,
+ .bs-sidebar.affix {
+ width: 263px;
+ }
+}
+
+
+/* Not enough room on mobile for markup tab, js tab, and plunk btn.
+ And no one cares about plunk button on a phone anyway */
+@media only screen and (max-device-width: 480px) {
+ #plunk-btn {
+ display: none;
+ }
+}
+
+.navbar-nav .dropdown .navbar-brand {
+ max-width: 100%;
+ margin-right: inherit;
+ margin-left: inherit;
+}
+
+.header-placeholder {
+ height: 50px;
+}
+
+@media screen and (min-width: 768px) {
+
+ .dropdown.open > .navbar-brand + .dropdown-menu {
+ left: 10px;
+ }
+
+ .header-placeholder {
+ height: 50px;
+ }
+
+ .navbar-nav .dropdown .navbar-brand {
+ max-width: 200px;
+ margin-right: 5px;
+ margin-left: 10px;
+ }
+
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/favicon.ico b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/favicon.ico
new file mode 100644
index 0000000..3d3f000
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/favicon.ico
Binary files differ
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/github-16px.png b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/github-16px.png
new file mode 100644
index 0000000..c99ab23
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/github-16px.png
Binary files differ
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/header.png b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/header.png
new file mode 100644
index 0000000..785dd10
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/header.png
Binary files differ
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/img/glyphicons-halflings-white.png b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/img/glyphicons-halflings-white.png
new file mode 100644
index 0000000..3bf6484
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/img/glyphicons-halflings-white.png
Binary files differ
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/img/glyphicons-halflings.png b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/img/glyphicons-halflings.png
new file mode 100644
index 0000000..a996999
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/img/glyphicons-halflings.png
Binary files differ
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/plunker.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/plunker.js
new file mode 100644
index 0000000..1e58610
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/plunker.js
@@ -0,0 +1,59 @@
+angular.module('plunker', [])
+
+ .factory('plunkGenerator', function ($document) {
+
+ return function (ngVersion, bsVersion, version, module, content) {
+
+ var form = angular.element('<form style="display: none;" method="post" action="http://plnkr.co/edit/?p=preview" target="_blank"></form>');
+ var addField = function (name, value) {
+ var input = angular.element('<input type="hidden" name="' + name + '">');
+ input.attr('value', value);
+ form.append(input);
+ };
+
+ var indexContent = function (content, version) {
+ return '<!doctype html>\n' +
+ '<html ng-app="ui.bootstrap.demo">\n' +
+ ' <head>\n' +
+ ' <script src="//ajax.googleapis.com/ajax/libs/angularjs/'+ngVersion+'/angular.js"></script>\n' +
+ ' <script src="//ajax.googleapis.com/ajax/libs/angularjs/'+ngVersion+'/angular-animate.js"></script>\n' +
+ ' <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-'+version+'.js"></script>\n' +
+ ' <script src="example.js"></script>\n' +
+ ' <link href="//netdna.bootstrapcdn.com/bootstrap/'+bsVersion+'/css/bootstrap.min.css" rel="stylesheet">\n' +
+ ' </head>\n' +
+ ' <body>\n\n' +
+ content + '\n' +
+ ' </body>\n' +
+ '</html>\n';
+ };
+
+ var scriptContent = function(content) {
+ return "angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);" + "\n" + content;
+ };
+
+ addField('description', 'http://angular-ui.github.io/bootstrap/');
+ addField('files[index.html]', indexContent(content.markup, version));
+ addField('files[example.js]', scriptContent(content.javascript));
+
+ $document.find('body').append(form);
+ form[0].submit();
+ form.remove();
+ };
+ })
+
+ .controller('PlunkerCtrl', function ($scope, plunkGenerator) {
+
+ $scope.content = {};
+
+ $scope.edit = function (ngVersion, bsVersion, version, module) {
+ plunkGenerator(ngVersion, bsVersion, version, module, $scope.content);
+ };
+ })
+
+ .directive('plunkerContent', function () {
+ return {
+ link:function (scope, element, attrs) {
+ scope.content[attrs.plunkerContent] = element.text().trim();
+ }
+ }
+ });
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow-generic.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow-generic.js
new file mode 100644
index 0000000..bfc5477
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow-generic.js
@@ -0,0 +1,59 @@
+/**
+ * Generic language patterns
+ *
+ * @author Craig Campbell
+ * @version 1.0.9
+ */
+Rainbow.extend([
+ {
+ 'matches': {
+ 1: {
+ 'name': 'keyword.operator',
+ 'pattern': /\=/g
+ },
+ 2: {
+ 'name': 'string',
+ 'matches': {
+ 'name': 'constant.character.escape',
+ 'pattern': /\\('|"){1}/g
+ }
+ }
+ },
+ 'pattern': /(\(|\s|\[|\=|:)(('|")([^\\\1]|\\.)*?(\3))/gm
+ },
+ {
+ 'name': 'comment',
+ 'pattern': /\/\*[\s\S]*?\*\/|(\/\/|\#)[\s\S]*?$/gm
+ },
+ {
+ 'name': 'constant.numeric',
+ 'pattern': /\b(\d+(\.\d+)?(e(\+|\-)?\d+)?(f|d)?|0x[\da-f]+)\b/gi
+ },
+ {
+ 'matches': {
+ 1: 'keyword'
+ },
+ 'pattern': /\b(and|array|as|bool(ean)?|c(atch|har|lass|onst)|d(ef|elete|o(uble)?)|e(cho|lse(if)?|xit|xtends|xcept)|f(inally|loat|or(each)?|unction)|global|if|import|int(eger)?|long|new|object|or|pr(int|ivate|otected)|public|return|self|st(ring|ruct|atic)|switch|th(en|is|row)|try|(un)?signed|var|void|while)(?=\(|\b)/gi
+ },
+ {
+ 'name': 'constant.language',
+ 'pattern': /true|false|null/g
+ },
+ {
+ 'name': 'keyword.operator',
+ 'pattern': /\+|\!|\-|&(gt|lt|amp);|\||\*|\=/g
+ },
+ {
+ 'matches': {
+ 1: 'function.call'
+ },
+ 'pattern': /(\w+?)(?=\()/g
+ },
+ {
+ 'matches': {
+ 1: 'storage.function',
+ 2: 'entity.name.function'
+ },
+ 'pattern': /(function)\s(.*?)(?=\()/g
+ }
+]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow-html.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow-html.js
new file mode 100644
index 0000000..f221888
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow-html.js
@@ -0,0 +1,83 @@
+/**
+ * HTML patterns
+ *
+ * @author Craig Campbell
+ * @version 1.0.7
+ */
+Rainbow.extend('html', [
+ {
+ 'name': 'source.php.embedded',
+ 'matches': {
+ 2: {
+ 'language': 'php'
+ }
+ },
+ 'pattern': /<\?=?(?!xml)(php)?([\s\S]*?)(\?>)/gm
+ },
+ {
+ 'name': 'source.css.embedded',
+ 'matches': {
+ 0: {
+ 'language': 'css'
+ }
+ },
+ 'pattern': /<style(.*?)>([\s\S]*?)<\/style>/gm
+ },
+ {
+ 'name': 'source.js.embedded',
+ 'matches': {
+ 0: {
+ 'language': 'javascript'
+ }
+ },
+ 'pattern': /<script(?! src)(.*?)>([\s\S]*?)<\/script>/gm
+ },
+ {
+ 'name': 'comment.html',
+ 'pattern': /<\!--[\S\s]*?-->/g
+ },
+ {
+ 'matches': {
+ 1: 'support.tag.open',
+ 2: 'support.tag.cclose'
+ },
+ 'pattern': /(<)|(\/?\??>)/g
+ },
+ {
+ 'name': 'support.tag',
+ 'matches': {
+ 1: 'support.tag',
+ 2: 'support.tag.special',
+ 3: 'support.tag-name'
+ },
+ 'pattern': /(<\??)(\/|\!?)(\w+)/g
+ },
+ {
+ 'matches': {
+ 1: 'support.attribute'
+ },
+ 'pattern': /([a-z-]+)(?=\=)/gi
+ },
+ {
+ 'matches': {
+ 1: 'support.operator',
+ 2: 'string.quote',
+ 3: 'string.value',
+ 4: 'string.quote'
+ },
+ 'pattern': /(=)('|")(.*?)(\2)/g
+ },
+ {
+ 'matches': {
+ 1: 'support.operator',
+ 2: 'support.value'
+ },
+ 'pattern': /(=)([a-zA-Z\-0-9]*)\b/g
+ },
+ {
+ 'matches': {
+ 1: 'support.attribute'
+ },
+ 'pattern': /\s(\w+)(?=\s|>)(?![\s\S]*<)/g
+ }
+], true);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow-javascript.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow-javascript.js
new file mode 100644
index 0000000..83b0d46
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow-javascript.js
@@ -0,0 +1,110 @@
+/**
+ * Javascript patterns
+ *
+ * @author Craig Campbell
+ * @version 1.0.7
+ */
+Rainbow.extend('javascript', [
+
+ /**
+ * matches $. or $(
+ */
+ {
+ 'name': 'selector',
+ 'pattern': /(\s|^)\$(?=\.|\()/g
+ },
+ {
+ 'name': 'support',
+ 'pattern': /\b(window|document)\b/g
+ },
+ {
+ 'matches': {
+ 1: 'support.property'
+ },
+ 'pattern': /\.(length|node(Name|Value))\b/g
+ },
+ {
+ 'matches': {
+ 1: 'support.function'
+ },
+ 'pattern': /(setTimeout|setInterval)(?=\()/g
+
+ },
+ {
+ 'matches': {
+ 1: 'support.method'
+ },
+ 'pattern': /\.(getAttribute|push|getElementById|getElementsByClassName|log|setTimeout|setInterval)(?=\()/g
+ },
+ {
+ 'matches': {
+ 1: 'support.tag.script',
+ 2: [
+ {
+ 'name': 'string',
+ 'pattern': /('|")(.*?)(\1)/g
+ },
+ {
+ 'name': 'entity.tag.script',
+ 'pattern': /(\w+)/g
+ }
+ ],
+ 3: 'support.tag.script'
+ },
+ 'pattern': /(<\/?)(script.*?)(>)/g
+ },
+
+ /**
+ * matches any escaped characters inside of a js regex pattern
+ *
+ * @see https://github.com/ccampbell/rainbow/issues/22
+ *
+ * this was causing single line comments to fail so it now makes sure
+ * the opening / is not directly followed by a *
+ *
+ * @todo check that there is valid regex in match group 1
+ */
+ {
+ 'name': 'string.regexp',
+ 'matches': {
+ 1: 'string.regexp.open',
+ 2: {
+ 'name': 'constant.regexp.escape',
+ 'pattern': /\\(.){1}/g
+ },
+ 3: 'string.regexp.cclose',
+ 4: 'string.regexp.modifier'
+ },
+ 'pattern': /(\/)(?!\*)(.+)(\/)([igm]{0,3})/g
+ },
+
+ /**
+ * matches runtime function declarations
+ */
+ {
+ 'matches': {
+ 1: 'storage',
+ 3: 'entity.function'
+ },
+ 'pattern': /(var)?(\s|^)(.*)(?=\s?=\s?function\()/g
+ },
+
+ /**
+ * matches constructor call
+ */
+ {
+ 'matches': {
+ 1: 'keyword',
+ 2: 'entity.function'
+ },
+ 'pattern': /(new)\s+(.*)(?=\()/g
+ },
+
+ /**
+ * matches any function call in the style functionName: function()
+ */
+ {
+ 'name': 'entity.function',
+ 'pattern': /(\w+)(?=:\s{0,}function)/g
+ }
+]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow.css b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow.css
new file mode 100644
index 0000000..0a82f65
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow.css
@@ -0,0 +1,88 @@
+/**
+ * GitHub theme
+ *
+ * @author Craig Campbell
+ * @version 1.0.4
+ */
+pre {
+ border: 1px solid #ccc;
+ word-wrap: break-word;
+ padding: 6px 10px;
+ line-height: 19px;
+ margin-bottom: 20px;
+}
+
+code {
+ border: 1px solid #eaeaea;
+ margin: 0 2px;
+ padding: 0 5px;
+ font-size: 12px;
+}
+
+pre code {
+ border: 0;
+ padding: 0;
+ margin: 0;
+ -moz-border-radius: 0;
+ -webkit-border-radius: 0;
+ border-radius: 0;
+}
+
+pre, code {
+ font-family: Consolas, 'Liberation Mono', Courier, monospace;
+ color: #333;
+ background: #f8f8f8;
+ -moz-border-radius: 3px;
+ -webkit-border-radius: 3px;
+ border-radius: 3px;
+}
+
+pre, pre code {
+ font-size: 13px;
+}
+
+pre .comment {
+ color: #998;
+}
+
+pre .support {
+ color: #0086B3;
+}
+
+pre .tag, pre .tag-name {
+ color: navy;
+}
+
+pre .keyword, pre .css-property, pre .vendor-prefix, pre .sass, pre .class, pre .id, pre .css-value, pre .entity.function, pre .storage.function {
+ font-weight: bold;
+}
+
+pre .css-property, pre .css-value, pre .vendor-prefix, pre .support.namespace {
+ color: #333;
+}
+
+pre .constant.numeric, pre .keyword.unit, pre .hex-color {
+ font-weight: normal;
+ color: #099;
+}
+
+pre .entity.class {
+ color: #458;
+}
+
+pre .entity.id, pre .entity.function {
+ color: #900;
+}
+
+pre .attribute, pre .variable {
+ color: teal;
+}
+
+pre .string, pre .support.value {
+ font-weight: normal;
+ color: #d14;
+}
+
+pre .regexp {
+ color: #009926;
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow.js
new file mode 100644
index 0000000..ed8894d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/rainbow.js
@@ -0,0 +1,773 @@
+/**
+ * Copyright 2012 Craig Campbell
+ *
+ * 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.
+ *
+ * Rainbow is a simple code syntax highlighter
+ *
+ * @preserve @version 1.1.8
+ * @url rainbowco.de
+ */
+window['Rainbow'] = (function() {
+
+ /**
+ * array of replacements to process at the end
+ *
+ * @type {Object}
+ */
+ var replacements = {},
+
+ /**
+ * an array of start and end positions of blocks to be replaced
+ *
+ * @type {Object}
+ */
+ replacement_positions = {},
+
+ /**
+ * an array of the language patterns specified for each language
+ *
+ * @type {Object}
+ */
+ language_patterns = {},
+
+ /**
+ * an array of languages and whether they should bypass the default patterns
+ *
+ * @type {Object}
+ */
+ bypass_defaults = {},
+
+ /**
+ * processing level
+ *
+ * replacements are stored at this level so if there is a sub block of code
+ * (for example php inside of html) it runs at a different level
+ *
+ * @type {number}
+ */
+ CURRENT_LEVEL = 0,
+
+ /**
+ * constant used to refer to the default language
+ *
+ * @type {number}
+ */
+ DEFAULT_LANGUAGE = 0,
+
+ /**
+ * used as counters so we can selectively call setTimeout
+ * after processing a certain number of matches/replacements
+ *
+ * @type {number}
+ */
+ match_counter = 0,
+
+ /**
+ * @type {number}
+ */
+ replacement_counter = 0,
+
+ /**
+ * @type {null|string}
+ */
+ global_class,
+
+ /**
+ * @type {null|Function}
+ */
+ onHighlight;
+
+ /**
+ * cross browser get attribute for an element
+ *
+ * @see http://stackoverflow.com/questions/3755227/cross-browser-javascript-getattribute-method
+ *
+ * @param {Node} el
+ * @param {string} attr attribute you are trying to get
+ * @returns {string|number}
+ */
+ function _attr(el, attr, attrs, i) {
+ var result = (el.getAttribute && el.getAttribute(attr)) || 0;
+
+ if (!result) {
+ attrs = el.attributes;
+
+ for (i = 0; i < attrs.length; ++i) {
+ if (attrs[i].nodeName === attr) {
+ return attrs[i].nodeValue;
+ }
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * adds a class to a given code block
+ *
+ * @param {Element} el
+ * @param {string} class_name class name to add
+ * @returns void
+ */
+ function _addClass(el, class_name) {
+ el.className += el.className ? ' ' + class_name : class_name;
+ }
+
+ /**
+ * checks if a block has a given class
+ *
+ * @param {Element} el
+ * @param {string} class_name class name to check for
+ * @returns {boolean}
+ */
+ function _hasClass(el, class_name) {
+ return (' ' + el.className + ' ').indexOf(' ' + class_name + ' ') > -1;
+ }
+
+ /**
+ * gets the language for this block of code
+ *
+ * @param {Element} block
+ * @returns {string|null}
+ */
+ function _getLanguageForBlock(block) {
+
+ // if this doesn't have a language but the parent does then use that
+ // this means if for example you have: <pre data-language="php">
+ // with a bunch of <code> blocks inside then you do not have
+ // to specify the language for each block
+ var language = _attr(block, 'data-language') || _attr(block.parentNode, 'data-language');
+
+ // this adds support for specifying language via a css class
+ // you can use the Google Code Prettify style: <pre class="lang-php">
+ // or the HTML5 style: <pre><code class="language-php">
+ if (!language) {
+ var pattern = /\blang(?:uage)?-(\w+)/,
+ match = block.className.match(pattern) || block.parentNode.className.match(pattern);
+
+ if (match) {
+ language = match[1];
+ }
+ }
+
+ return language;
+ }
+
+ /**
+ * makes sure html entities are always used for tags
+ *
+ * @param {string} code
+ * @returns {string}
+ */
+ function _htmlEntities(code) {
+ return code.replace(/</g, '<').replace(/>/g, '>').replace(/&(?![\w\#]+;)/g, '&');
+ }
+
+ /**
+ * determines if a new match intersects with an existing one
+ *
+ * @param {number} start1 start position of existing match
+ * @param {number} end1 end position of existing match
+ * @param {number} start2 start position of new match
+ * @param {number} end2 end position of new match
+ * @returns {boolean}
+ */
+ function _intersects(start1, end1, start2, end2) {
+ if (start2 >= start1 && start2 < end1) {
+ return true;
+ }
+
+ return end2 > start1 && end2 < end1;
+ }
+
+ /**
+ * determines if two different matches have complete overlap with each other
+ *
+ * @param {number} start1 start position of existing match
+ * @param {number} end1 end position of existing match
+ * @param {number} start2 start position of new match
+ * @param {number} end2 end position of new match
+ * @returns {boolean}
+ */
+ function _hasCompleteOverlap(start1, end1, start2, end2) {
+
+ // if the starting and end positions are exactly the same
+ // then the first one should stay and this one should be ignored
+ if (start2 == start1 && end2 == end1) {
+ return false;
+ }
+
+ return start2 <= start1 && end2 >= end1;
+ }
+
+ /**
+ * determines if the match passed in falls inside of an existing match
+ * this prevents a regex pattern from matching inside of a bigger pattern
+ *
+ * @param {number} start - start position of new match
+ * @param {number} end - end position of new match
+ * @returns {boolean}
+ */
+ function _matchIsInsideOtherMatch(start, end) {
+ for (var key in replacement_positions[CURRENT_LEVEL]) {
+ key = parseInt(key, 10);
+
+ // if this block completely overlaps with another block
+ // then we should remove the other block and return false
+ if (_hasCompleteOverlap(key, replacement_positions[CURRENT_LEVEL][key], start, end)) {
+ delete replacement_positions[CURRENT_LEVEL][key];
+ delete replacements[CURRENT_LEVEL][key];
+ }
+
+ if (_intersects(key, replacement_positions[CURRENT_LEVEL][key], start, end)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * takes a string of code and wraps it in a span tag based on the name
+ *
+ * @param {string} name name of the pattern (ie keyword.regex)
+ * @param {string} code block of code to wrap
+ * @returns {string}
+ */
+ function _wrapCodeInSpan(name, code) {
+ return '<span class="' + name.replace(/\./g, ' ') + (global_class ? ' ' + global_class : '') + '">' + code + '</span>';
+ }
+
+ /**
+ * finds out the position of group match for a regular expression
+ *
+ * @see http://stackoverflow.com/questions/1985594/how-to-find-index-of-groups-in-match
+ *
+ * @param {Object} match
+ * @param {number} group_number
+ * @returns {number}
+ */
+ function _indexOfGroup(match, group_number) {
+ var index = 0,
+ i;
+
+ for (i = 1; i < group_number; ++i) {
+ if (match[i]) {
+ index += match[i].length;
+ }
+ }
+
+ return index;
+ }
+
+ /**
+ * matches a regex pattern against a block of code
+ * finds all matches that should be processed and stores the positions
+ * of where they should be replaced within the string
+ *
+ * this is where pretty much all the work is done but it should not
+ * be called directly
+ *
+ * @param {RegExp} pattern
+ * @param {string} code
+ * @returns void
+ */
+ function _processPattern(regex, pattern, code, callback)
+ {
+ var match = regex.exec(code);
+
+ if (!match) {
+ return callback();
+ }
+
+ ++match_counter;
+
+ // treat match 0 the same way as name
+ if (!pattern['name'] && typeof pattern['matches'][0] == 'string') {
+ pattern['name'] = pattern['matches'][0];
+ delete pattern['matches'][0];
+ }
+
+ var replacement = match[0],
+ start_pos = match.index,
+ end_pos = match[0].length + start_pos,
+
+ /**
+ * callback to process the next match of this pattern
+ */
+ processNext = function() {
+ var nextCall = function() {
+ _processPattern(regex, pattern, code, callback);
+ };
+
+ // every 100 items we process let's call set timeout
+ // to let the ui breathe a little
+ return match_counter % 100 > 0 ? nextCall() : setTimeout(nextCall, 0);
+ };
+
+ // if this is not a child match and it falls inside of another
+ // match that already happened we should skip it and continue processing
+ if (_matchIsInsideOtherMatch(start_pos, end_pos)) {
+ return processNext();
+ }
+
+ /**
+ * callback for when a match was successfully processed
+ *
+ * @param {string} replacement
+ * @returns void
+ */
+ var onMatchSuccess = function(replacement) {
+ // if this match has a name then wrap it in a span tag
+ if (pattern['name']) {
+ replacement = _wrapCodeInSpan(pattern['name'], replacement);
+ }
+
+ // console.log('LEVEL', CURRENT_LEVEL, 'replace', match[0], 'with', replacement, 'at position', start_pos, 'to', end_pos);
+
+ // store what needs to be replaced with what at this position
+ if (!replacements[CURRENT_LEVEL]) {
+ replacements[CURRENT_LEVEL] = {};
+ replacement_positions[CURRENT_LEVEL] = {};
+ }
+
+ replacements[CURRENT_LEVEL][start_pos] = {
+ 'replace': match[0],
+ 'with': replacement
+ };
+
+ // store the range of this match so we can use it for comparisons
+ // with other matches later
+ replacement_positions[CURRENT_LEVEL][start_pos] = end_pos;
+
+ // process the next match
+ processNext();
+ },
+
+ // if this pattern has sub matches for different groups in the regex
+ // then we should process them one at a time by rerunning them through
+ // this function to generate the new replacement
+ //
+ // we run through them backwards because the match position of earlier
+ // matches will not change depending on what gets replaced in later
+ // matches
+ group_keys = keys(pattern['matches']),
+
+ /**
+ * callback for processing a sub group
+ *
+ * @param {number} i
+ * @param {Array} group_keys
+ * @param {Function} callback
+ */
+ processGroup = function(i, group_keys, callback) {
+ if (i >= group_keys.length) {
+ return callback(replacement);
+ }
+
+ var processNextGroup = function() {
+ processGroup(++i, group_keys, callback);
+ },
+ block = match[group_keys[i]];
+
+ // if there is no match here then move on
+ if (!block) {
+ return processNextGroup();
+ }
+
+ var group = pattern['matches'][group_keys[i]],
+ language = group['language'],
+
+ /**
+ * process group is what group we should use to actually process
+ * this match group
+ *
+ * for example if the subgroup pattern looks like this
+ * 2: {
+ * 'name': 'keyword',
+ * 'pattern': /true/g
+ * }
+ *
+ * then we use that as is, but if it looks like this
+ *
+ * 2: {
+ * 'name': 'keyword',
+ * 'matches': {
+ * 'name': 'special',
+ * 'pattern': /whatever/g
+ * }
+ * }
+ *
+ * we treat the 'matches' part as the pattern and keep
+ * the name around to wrap it with later
+ */
+ process_group = group['name'] && group['matches'] ? group['matches'] : group,
+
+ /**
+ * takes the code block matched at this group, replaces it
+ * with the highlighted block, and optionally wraps it with
+ * a span with a name
+ *
+ * @param {string} block
+ * @param {string} replace_block
+ * @param {string|null} match_name
+ */
+ _replaceAndContinue = function(block, replace_block, match_name) {
+ replacement = _replaceAtPosition(_indexOfGroup(match, group_keys[i]), block, match_name ? _wrapCodeInSpan(match_name, replace_block) : replace_block, replacement);
+ processNextGroup();
+ };
+
+ // if this is a sublanguage go and process the block using that language
+ if (language) {
+ return _highlightBlockForLanguage(block, language, function(code) {
+ _replaceAndContinue(block, code);
+ });
+ }
+
+ // if this is a string then this match is directly mapped to selector
+ // so all we have to do is wrap it in a span and continue
+ if (typeof group === 'string') {
+ return _replaceAndContinue(block, block, group);
+ }
+
+ // the process group can be a single pattern or an array of patterns
+ // _processCodeWithPatterns always expects an array so we convert it here
+ _processCodeWithPatterns(block, process_group.length ? process_group : [process_group], function(code) {
+ _replaceAndContinue(block, code, group['matches'] ? group['name'] : 0);
+ });
+ };
+
+ processGroup(0, group_keys, onMatchSuccess);
+ }
+
+ /**
+ * should a language bypass the default patterns?
+ *
+ * if you call Rainbow.extend() and pass true as the third argument
+ * it will bypass the defaults
+ */
+ function _bypassDefaultPatterns(language)
+ {
+ return bypass_defaults[language];
+ }
+
+ /**
+ * returns a list of regex patterns for this language
+ *
+ * @param {string} language
+ * @returns {Array}
+ */
+ function _getPatternsForLanguage(language) {
+ var patterns = language_patterns[language] || [],
+ default_patterns = language_patterns[DEFAULT_LANGUAGE] || [];
+
+ return _bypassDefaultPatterns(language) ? patterns : patterns.concat(default_patterns);
+ }
+
+ /**
+ * substring replace call to replace part of a string at a certain position
+ *
+ * @param {number} position the position where the replacement should happen
+ * @param {string} replace the text we want to replace
+ * @param {string} replace_with the text we want to replace it with
+ * @param {string} code the code we are doing the replacing in
+ * @returns {string}
+ */
+ function _replaceAtPosition(position, replace, replace_with, code) {
+ var sub_string = code.substr(position);
+ return code.substr(0, position) + sub_string.replace(replace, replace_with);
+ }
+
+ /**
+ * sorts an object by index descending
+ *
+ * @param {Object} object
+ * @return {Array}
+ */
+ function keys(object) {
+ var locations = [],
+ replacement,
+ pos;
+
+ for(var location in object) {
+ if (object.hasOwnProperty(location)) {
+ locations.push(location);
+ }
+ }
+
+ // numeric descending
+ return locations.sort(function(a, b) {
+ return b - a;
+ });
+ }
+
+ /**
+ * processes a block of code using specified patterns
+ *
+ * @param {string} code
+ * @param {Array} patterns
+ * @returns void
+ */
+ function _processCodeWithPatterns(code, patterns, callback)
+ {
+ // we have to increase the level here so that the
+ // replacements will not conflict with each other when
+ // processing sub blocks of code
+ ++CURRENT_LEVEL;
+
+ // patterns are processed one at a time through this function
+ function _workOnPatterns(patterns, i)
+ {
+ // still have patterns to process, keep going
+ if (i < patterns.length) {
+ return _processPattern(patterns[i]['pattern'], patterns[i], code, function() {
+ _workOnPatterns(patterns, ++i);
+ });
+ }
+
+ // we are done processing the patterns
+ // process the replacements and update the DOM
+ _processReplacements(code, function(code) {
+
+ // when we are done processing replacements
+ // we are done at this level so we can go back down
+ delete replacements[CURRENT_LEVEL];
+ delete replacement_positions[CURRENT_LEVEL];
+ --CURRENT_LEVEL;
+ callback(code);
+ });
+ }
+
+ _workOnPatterns(patterns, 0);
+ }
+
+ /**
+ * process replacements in the string of code to actually update the markup
+ *
+ * @param {string} code the code to process replacements in
+ * @param {Function} onComplete what to do when we are done processing
+ * @returns void
+ */
+ function _processReplacements(code, onComplete) {
+
+ /**
+ * processes a single replacement
+ *
+ * @param {string} code
+ * @param {Array} positions
+ * @param {number} i
+ * @param {Function} onComplete
+ * @returns void
+ */
+ function _processReplacement(code, positions, i, onComplete) {
+ if (i < positions.length) {
+ ++replacement_counter;
+ var pos = positions[i],
+ replacement = replacements[CURRENT_LEVEL][pos];
+ code = _replaceAtPosition(pos, replacement['replace'], replacement['with'], code);
+
+ // process next function
+ var next = function() {
+ _processReplacement(code, positions, ++i, onComplete);
+ };
+
+ // use a timeout every 250 to not freeze up the UI
+ return replacement_counter % 250 > 0 ? next() : setTimeout(next, 0);
+ }
+
+ onComplete(code);
+ }
+
+ var string_positions = keys(replacements[CURRENT_LEVEL]);
+ _processReplacement(code, string_positions, 0, onComplete);
+ }
+
+ /**
+ * takes a string of code and highlights it according to the language specified
+ *
+ * @param {string} code
+ * @param {string} language
+ * @param {Function} onComplete
+ * @returns void
+ */
+ function _highlightBlockForLanguage(code, language, onComplete) {
+ var patterns = _getPatternsForLanguage(language);
+ _processCodeWithPatterns(_htmlEntities(code), patterns, onComplete);
+ }
+
+ /**
+ * highlight an individual code block
+ *
+ * @param {Array} code_blocks
+ * @param {number} i
+ * @returns void
+ */
+ function _highlightCodeBlock(code_blocks, i, onComplete) {
+ if (i < code_blocks.length) {
+ var block = code_blocks[i],
+ language = _getLanguageForBlock(block);
+
+ if (!_hasClass(block, 'rainbow') && language) {
+ language = language.toLowerCase();
+
+ _addClass(block, 'rainbow');
+
+ return _highlightBlockForLanguage(block.innerHTML, language, function(code) {
+ block.innerHTML = code;
+
+ // reset the replacement arrays
+ replacements = {};
+ replacement_positions = {};
+
+ // if you have a listener attached tell it that this block is now highlighted
+ if (onHighlight) {
+ onHighlight(block, language);
+ }
+
+ // process the next block
+ setTimeout(function() {
+ _highlightCodeBlock(code_blocks, ++i, onComplete);
+ }, 0);
+ });
+ }
+ return _highlightCodeBlock(code_blocks, ++i, onComplete);
+ }
+
+ if (onComplete) {
+ onComplete();
+ }
+ }
+
+ /**
+ * start highlighting all the code blocks
+ *
+ * @returns void
+ */
+ function _highlight(node, onComplete) {
+
+ // the first argument can be an Event or a DOM Element
+ // I was originally checking instanceof Event but that makes it break
+ // when using mootools
+ //
+ // @see https://github.com/ccampbell/rainbow/issues/32
+ //
+ node = node && typeof node.getElementsByTagName == 'function' ? node : document;
+
+ var pre_blocks = node.getElementsByTagName('pre'),
+ code_blocks = node.getElementsByTagName('code'),
+ i,
+ final_blocks = [];
+
+ // @see http://stackoverflow.com/questions/2735067/how-to-convert-a-dom-node-list-to-an-array-in-javascript
+ // we are going to process all <code> blocks
+ for (i = 0; i < code_blocks.length; ++i) {
+ final_blocks.push(code_blocks[i]);
+ }
+
+ // loop through the pre blocks to see which ones we should add
+ for (i = 0; i < pre_blocks.length; ++i) {
+
+ // if the pre block has no code blocks then process it directly
+ if (!pre_blocks[i].getElementsByTagName('code').length) {
+ final_blocks.push(pre_blocks[i]);
+ }
+ }
+
+ _highlightCodeBlock(final_blocks, 0, onComplete);
+ }
+
+ /**
+ * public methods
+ */
+ return {
+
+ /**
+ * extends the language pattern matches
+ *
+ * @param {*} language name of language
+ * @param {*} patterns array of patterns to add on
+ * @param {boolean|null} bypass if true this will bypass the default language patterns
+ */
+ extend: function(language, patterns, bypass) {
+
+ // if there is only one argument then we assume that we want to
+ // extend the default language rules
+ if (arguments.length == 1) {
+ patterns = language;
+ language = DEFAULT_LANGUAGE;
+ }
+
+ bypass_defaults[language] = bypass;
+ language_patterns[language] = patterns.concat(language_patterns[language] || []);
+ },
+
+ /**
+ * call back to let you do stuff in your app after a piece of code has been highlighted
+ *
+ * @param {Function} callback
+ */
+ onHighlight: function(callback) {
+ onHighlight = callback;
+ },
+
+ /**
+ * method to set a global class that will be applied to all spans
+ *
+ * @param {string} class_name
+ */
+ addClass: function(class_name) {
+ global_class = class_name;
+ },
+
+ /**
+ * starts the magic rainbow
+ *
+ * @returns void
+ */
+ color: function() {
+
+ // if you want to straight up highlight a string you can pass the string of code,
+ // the language, and a callback function
+ if (typeof arguments[0] == 'string') {
+ return _highlightBlockForLanguage(arguments[0], arguments[1], arguments[2]);
+ }
+
+ // if you pass a callback function then we rerun the color function
+ // on all the code and call the callback function on complete
+ if (typeof arguments[0] == 'function') {
+ return _highlight(0, arguments[0]);
+ }
+
+ // otherwise we use whatever node you passed in with an optional
+ // callback function as the second parameter
+ _highlight(arguments[0], arguments[1]);
+ }
+ };
+}) ();
+
+/**
+ * adds event listener to start highlighting
+ */
+(function() {
+ if (window.addEventListener) {
+ return window.addEventListener('load', Rainbow.color, false);
+ }
+ window.attachEvent('onload', Rainbow.color);
+}) ();
+
+// When using Google closure compiler in advanced mode some methods
+// get renamed. This keeps a public reference to these methods so they can
+// still be referenced from outside this library.
+Rainbow["onHighlight"] = Rainbow.onHighlight;
+Rainbow["addClass"] = Rainbow.addClass;
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/smoothscroll-angular-custom.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/smoothscroll-angular-custom.js
new file mode 100644
index 0000000..e33586f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/smoothscroll-angular-custom.js
@@ -0,0 +1,97 @@
+/*
+ * https://github.com/alicelieutier/smoothScroll/
+ * A teeny tiny, standard compliant, smooth scroll script with ease-in-out effect and no jQuery (or any other dependancy, FWIW).
+ * MIT License
+ */
+window.smoothScroll = (function(){
+// We do not want this script to be applied in browsers that do not support those
+// That means no smoothscroll on IE9 and below.
+if(document.querySelectorAll === void 0 || window.pageYOffset === void 0 || history.pushState === void 0) { return; }
+
+// Get the top position of an element in the document
+var getTop = function(element) {
+ // return value of html.getBoundingClientRect().top ... IE : 0, other browsers : -pageYOffset
+ if(element.nodeName === 'HTML') return -window.pageYOffset
+ return element.getBoundingClientRect().top + window.pageYOffset;
+}
+// ease in out function thanks to:
+// http://blog.greweb.fr/2012/02/bezier-curve-based-easing-functions-from-concept-to-implementation/
+var easeInOutCubic = function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 }
+
+// calculate the scroll position we should be in
+// given the start and end point of the scroll
+// the time elapsed from the beginning of the scroll
+// and the total duration of the scroll (default 500ms)
+var position = function(start, end, elapsed, duration) {
+ if (elapsed > duration) return end;
+ return start + (end - start) * easeInOutCubic(elapsed / duration); // <-- you can change the easing funtion there
+ // return start + (end - start) * (elapsed / duration); // <-- this would give a linear scroll
+}
+
+// we use requestAnimationFrame to be called by the browser before every repaint
+// if the first argument is an element then scroll to the top of this element
+// if the first argument is numeric then scroll to this location
+// if the callback exist, it is called when the scrolling is finished
+var smoothScroll = function(el, duration, callback){
+ duration = duration || 500;
+ var start = window.pageYOffset;
+
+ if (typeof el === 'number') {
+ var end = parseInt(el);
+ } else {
+ var end = getTop(el);
+ }
+
+ var clock = Date.now();
+ var requestAnimationFrame = window.requestAnimationFrame ||
+ window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
+ function(fn){window.setTimeout(fn, 15);};
+
+ var step = function(){
+ var elapsed = Date.now() - clock;
+ window.scroll(0, position(start, end, elapsed, duration));
+ if (elapsed > duration) {
+ if (typeof callback === 'function') {
+ callback(el);
+ }
+ } else {
+ requestAnimationFrame(step);
+ }
+ }
+ step();
+}
+
+var linkHandler = function(ev) {
+ ev.preventDefault();
+
+ if (location.hash !== this.hash) {
+ //NOTE(@ajoslin): Changed this line to stop $digest errors
+ //window.history.pushState(null, null, this.hash)
+ angular.element(document).injector().get('$location').hash(this.hash);
+ }
+ // using the history api to solve issue #1 - back doesn't work
+ // most browser don't update :target when the history api is used:
+ // THIS IS A BUG FROM THE BROWSERS.
+ // change the scrolling duration in this call
+ var targetEl = document.getElementById(this.hash.substring(1));
+ if (targetEl) {
+ smoothScroll(document.getElementById(this.hash.substring(1)), 500, function(el) {
+ location.replace('#' + el.id)
+ // this will cause the :target to be activated.
+ });
+ }
+}
+
+// We look for all the internal links in the documents and attach the smoothscroll function
+document.addEventListener("DOMContentLoaded", function () {
+ var internal = document.querySelectorAll('a[href^="#"]'), a;
+ for(var i=internal.length; a=internal[--i];){
+ a.addEventListener("click", linkHandler, false);
+ }
+});
+
+// return smoothscroll API
+return smoothScroll;
+
+})();
+
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/uglifyjs.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/uglifyjs.js
new file mode 100644
index 0000000..2b09c57
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/assets/uglifyjs.js
@@ -0,0 +1,4 @@
+!function(n,e){"use strict";function t(n){for(var e=Object.create(null),t=0;t<n.length;++t)e[n[t]]=!0;return e}function r(n,e){return Array.prototype.slice.call(n,e||0)}function i(n){return n.split("")}function o(n,e){for(var t=e.length;--t>=0;)if(e[t]==n)return!0;return!1}function a(n,e){for(var t=0,r=e.length;r>t;++t)if(n(e[t]))return e[t]}function u(n,e){if(0>=e)return"";if(1==e)return n;var t=u(n,e>>1);return t+=t,1&e&&(t+=n),t}function s(n,e){Error.call(this,n),this.msg=n,this.defs=e}function c(n,e,t){n===!0&&(n={});var r=n||{};if(t)for(var i in r)r.hasOwnProperty(i)&&!e.hasOwnProperty(i)&&s.croak("`"+i+"` is not a supported option",e);for(var i in e)e.hasOwnProperty(i)&&(r[i]=n&&n.hasOwnProperty(i)?n[i]:e[i]);return r}function f(n,e){for(var t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);return n}function l(){}function p(n,e){n.indexOf(e)<0&&n.push(e)}function d(n,e){return n.replace(/\{(.+?)\}/g,function(n,t){return e[t]})}function h(n,e){for(var t=n.length;--t>=0;)n[t]===e&&n.splice(t,1)}function _(n,e){function t(n,t){for(var r=[],i=0,o=0,a=0;i<n.length&&o<t.length;)r[a++]=e(n[i],t[o])<=0?n[i++]:t[o++];return i<n.length&&r.push.apply(r,n.slice(i)),o<t.length&&r.push.apply(r,t.slice(o)),r}function r(n){if(n.length<=1)return n;var e=Math.floor(n.length/2),i=n.slice(0,e),o=n.slice(e);return i=r(i),o=r(o),t(i,o)}return n.length<2?n.slice():r(n)}function m(n,e){return n.filter(function(n){return e.indexOf(n)<0})}function v(n,e){return n.filter(function(n){return e.indexOf(n)>=0})}function g(n){function e(n){if(1==n.length)return t+="return str === "+JSON.stringify(n[0])+";";t+="switch(str){";for(var e=0;e<n.length;++e)t+="case "+JSON.stringify(n[e])+":";t+="return true}return false;"}n instanceof Array||(n=n.split(" "));var t="",r=[];n:for(var i=0;i<n.length;++i){for(var o=0;o<r.length;++o)if(r[o][0].length==n[i].length){r[o].push(n[i]);continue n}r.push([n[i]])}if(r.length>3){r.sort(function(n,e){return e.length-n.length}),t+="switch(str.length){";for(var i=0;i<r.length;++i){var a=r[i];t+="case "+a[0].length+":",e(a)}t+="}"}else e(n);return new Function("str",t)}function b(n,e){for(var t=n.length;--t>=0;)if(!e(n[t]))return!1;return!0}function y(){this._values=Object.create(null),this._size=0}function A(n,e,t,r){arguments.length<4&&(r=W),e=e?e.split(/\s+/):[];var i=e;r&&r.PROPS&&(e=e.concat(r.PROPS));for(var o="return function AST_"+n+"(props){ if (props) { ",a=e.length;--a>=0;)o+="this."+e[a]+" = props."+e[a]+";";var u=r&&new r;(u&&u.initialize||t&&t.initialize)&&(o+="this.initialize();"),o+="}}";var s=new Function(o)();if(u&&(s.prototype=u,s.BASE=r),r&&r.SUBCLASSES.push(s),s.prototype.CTOR=s,s.PROPS=e||null,s.SELF_PROPS=i,s.SUBCLASSES=[],n&&(s.prototype.TYPE=s.TYPE=n),t)for(a in t)t.hasOwnProperty(a)&&(/^\$/.test(a)?s[a.substr(1)]=t[a]:s.prototype[a]=t[a]);return s.DEFMETHOD=function(n,e){this.prototype[n]=e},s}function w(n,e){n.body instanceof Y?n.body._walk(e):n.body.forEach(function(n){n._walk(e)})}function E(n){this.visit=n,this.stack=[]}function D(n){return n>=97&&122>=n||n>=65&&90>=n||n>=170&&qt.letter.test(String.fromCharCode(n))}function F(n){return n>=48&&57>=n}function S(n){return F(n)||D(n)}function C(n){return qt.non_spacing_mark.test(n)||qt.space_combining_mark.test(n)}function k(n){return qt.connector_punctuation.test(n)}function x(n){return!St(n)&&/^[a-z_$][a-z0-9_$]*$/i.test(n)}function B(n){return 36==n||95==n||D(n)}function T(n){var e=n.charCodeAt(0);return B(e)||F(e)||8204==e||8205==e||C(n)||k(n)}function $(n){return/^[a-z_$][a-z0-9_$]*$/i.test(n)}function O(n){return xt.test(n)?parseInt(n.substr(2),16):Bt.test(n)?parseInt(n.substr(1),8):Tt.test(n)?parseFloat(n):void 0}function M(n,e,t,r){this.message=n,this.line=e,this.col=t,this.pos=r,this.stack=(new Error).stack}function N(n,e,t,r,i){throw new M(n,t,r,i)}function R(n,e,t){return n.type==e&&(null==t||n.value==t)}function q(n,e,t){function r(){return D.text.charAt(D.pos)}function i(n,e){var t=D.text.charAt(D.pos++);if(n&&!t)throw Ht;return"\n"==t?(D.newline_before=D.newline_before||!e,++D.line,D.col=0):++D.col,t}function o(n){for(;n-->0;)i()}function a(n){return D.text.substr(D.pos,n.length)==n}function u(n,e){var t=D.text.indexOf(n,D.pos);if(e&&-1==t)throw Ht;return t}function s(){D.tokline=D.line,D.tokcol=D.col,D.tokpos=D.pos}function c(n,t,r){D.regex_allowed="operator"==n&&!Pt(t)||"keyword"==n&&Ct(t)||"punc"==n&&Mt(t),C="punc"==n&&"."==t;var i={type:n,value:t,line:D.tokline,col:D.tokcol,pos:D.tokpos,endpos:D.pos,nlb:D.newline_before,file:e};if(!r){i.comments_before=D.comments_before,D.comments_before=[];for(var o=0,a=i.comments_before.length;a>o;o++)i.nlb=i.nlb||i.comments_before[o].nlb}return D.newline_before=!1,new L(i)}function f(){for(;Ot(r());)i()}function l(n){for(var e,t="",o=0;(e=r())&&n(e,o++);)t+=i();return t}function p(n){N(n,e,D.tokline,D.tokcol,D.tokpos)}function d(n){var e=!1,t=!1,r=!1,i="."==n,o=l(function(o,a){var u=o.charCodeAt(0);switch(u){case 120:case 88:return r?!1:r=!0;case 101:case 69:return r?!0:e?!1:e=t=!0;case 45:return t||0==a&&!n;case 43:return t;case t=!1,46:return i||r||e?!1:i=!0}return S(u)});n&&(o=n+o);var a=O(o);return isNaN(a)?void p("Invalid syntax: "+o):c("num",a)}function h(n){var e=i(!0,n);switch(e.charCodeAt(0)){case 110:return"\n";case 114:return"\r";case 116:return" ";case 98:return"\b";case 118:return"";case 102:return"\f";case 48:return"\x00";case 120:return String.fromCharCode(_(2));case 117:return String.fromCharCode(_(4));case 10:return"";default:return e}}function _(n){for(var e=0;n>0;--n){var t=parseInt(i(!0),16);isNaN(t)&&p("Invalid hex-character pattern in string"),e=e<<4|t}return e}function m(n){var e,t=D.regex_allowed,r=u("\n");return-1==r?(e=D.text.substr(D.pos),D.pos=D.text.length):(e=D.text.substring(D.pos,r),D.pos=r),D.comments_before.push(c(n,e,!0)),D.regex_allowed=t,E()}function v(){for(var n,e,t=!1,o="",a=!1;null!=(n=r());)if(t)"u"!=n&&p("Expecting UnicodeEscapeSequence -- uXXXX"),n=h(),T(n)||p("Unicode char: "+n.charCodeAt(0)+" is not valid in identifier"),o+=n,t=!1;else if("\\"==n)a=t=!0,i();else{if(!T(n))break;o+=i()}return Dt(o)&&a&&(e=o.charCodeAt(0).toString(16).toUpperCase(),o="\\u"+"0000".substr(e.length)+e+o.slice(1)),o}function g(n){function e(n){if(!r())return n;var t=n+r();return $t(t)?(i(),e(t)):n}return c("operator",e(n||i()))}function b(){switch(i(),r()){case"/":return i(),m("comment1");case"*":return i(),x()}return D.regex_allowed?$(""):g("/")}function y(){return i(),F(r().charCodeAt(0))?d("."):c("punc",".")}function A(){var n=v();return C?c("name",n):Ft(n)?c("atom",n):Dt(n)?$t(n)?c("operator",n):c("keyword",n):c("name",n)}function w(n,e){return function(t){try{return e(t)}catch(r){if(r!==Ht)throw r;p(n)}}}function E(n){if(null!=n)return $(n);if(f(),s(),t){if(a("<!--"))return o(4),m("comment3");if(a("-->")&&D.newline_before)return o(3),m("comment4")}var e=r();if(!e)return c("eof");var u=e.charCodeAt(0);switch(u){case 34:case 39:return k();case 46:return y();case 47:return b()}return F(u)?d():Nt(e)?c("punc",i()):kt(e)?g():92==u||B(u)?A():void p("Unexpected character '"+e+"'")}var D={text:n.replace(/\r\n?|[\n\u2028\u2029]/g,"\n").replace(/\uFEFF/g,""),filename:e,pos:0,tokpos:0,line:1,tokline:0,col:0,tokcol:0,newline_before:!1,regex_allowed:!1,comments_before:[]},C=!1,k=w("Unterminated string constant",function(){for(var n=i(),e="";;){var t=i(!0);if("\\"==t){var r=0,o=null;t=l(function(n){if(n>="0"&&"7">=n){if(!o)return o=n,++r;if("3">=o&&2>=r)return++r;if(o>="4"&&1>=r)return++r}return!1}),t=r>0?String.fromCharCode(parseInt(t,8)):h(!0)}else if(t==n)break;e+=t}return c("string",e)}),x=w("Unterminated multiline comment",function(){var n=D.regex_allowed,e=u("*/",!0),t=D.text.substring(D.pos,e),r=t.split("\n"),i=r.length;D.pos=e+2,D.line+=i-1,i>1?D.col=r[i-1].length:D.col+=r[i-1].length,D.col+=2;var o=D.newline_before=D.newline_before||t.indexOf("\n")>=0;return D.comments_before.push(c("comment2",t,!0)),D.regex_allowed=n,D.newline_before=o,E()}),$=w("Unterminated regular expression",function(n){for(var e,t=!1,r=!1;e=i(!0);)if(t)n+="\\"+e,t=!1;else if("["==e)r=!0,n+=e;else if("]"==e&&r)r=!1,n+=e;else{if("/"==e&&!r)break;"\\"==e?t=!0:n+=e}var o=v();return c("regexp",new RegExp(n,o))});return E.context=function(n){return n&&(D=n),D},E}function H(n,e){function t(n,e){return R(I.token,n,e)}function r(){return I.peeked||(I.peeked=I.input())}function i(){return I.prev=I.token,I.peeked?(I.token=I.peeked,I.peeked=null):I.token=I.input(),I.in_directives=I.in_directives&&("string"==I.token.type||t("punc",";")),I.token}function o(){return I.prev}function u(n,e,t,r){var i=I.input.context();N(n,i.filename,null!=e?e:i.tokline,null!=t?t:i.tokcol,null!=r?r:i.tokpos)}function s(n,e){u(e,n.line,n.col)}function f(n){null==n&&(n=I.token),s(n,"Unexpected token: "+n.type+" ("+n.value+")")}function l(n,e){return t(n,e)?i():void s(I.token,"Unexpected token "+I.token.type+" «"+I.token.value+"», expected "+n+" «"+e+"»")}function p(n){return l("punc",n)}function d(){return!e.strict&&(I.token.nlb||t("eof")||t("punc","}"))}function h(){t("punc",";")?i():d()||f()}function _(){p("(");var n=De(!0);return p(")"),n}function m(n){return function(){var e=I.token,t=n(),r=o();return t.start=e,t.end=r,t}}function v(){(t("operator","/")||t("operator","/="))&&(I.peeked=null,I.token=I.input(I.token.value.substr(1)))}function g(){var n=M(ut);a(function(e){return e.name==n.name},I.labels)&&u("Label "+n.name+" defined twice"),p(":"),I.labels.push(n);var e=U();return I.labels.pop(),e instanceof te||n.references.forEach(function(e){e instanceof Ae&&(e=e.label.start,u("Continue label `"+n.name+"` refers to non-IterationStatement.",e.line,e.col,e.pos))}),new ee({body:e,label:n})}function b(n){return new K({body:(n=De(!0),h(),n)})}function y(n){var e,t=null;d()||(t=M(ct,!0)),null!=t?(e=a(function(n){return n.name==t.name},I.labels),e||u("Undefined label "+t.name),t.thedef=e):0==I.in_loop&&u(n.TYPE+" not inside a loop or switch"),h();var r=new n({label:t});return e&&e.references.push(r),r}function A(){p("(");var n=null;return!t("punc",";")&&(n=t("keyword","var")?(i(),L(!0)):De(!0,!0),t("operator","in"))?(n instanceof Te&&n.definitions.length>1&&u("Only one variable declaration allowed in for..in loop"),i(),E(n)):w(n)}function w(n){p(";");var e=t("punc",";")?null:De(!0);p(";");var r=t("punc",")")?null:De(!0);return p(")"),new ae({init:n,condition:e,step:r,body:j(U)})}function E(n){var e=n instanceof Te?n.definitions[0].name:null,t=De(!0);return p(")"),new ue({init:n,name:e,object:t,body:j(U)})}function D(){var n=_(),e=U(),r=null;return t("keyword","else")&&(i(),r=U()),new we({condition:n,body:e,alternative:r})}function F(){p("{");for(var n=[];!t("punc","}");)t("eof")&&f(),n.push(U());return i(),n}function S(){p("{");for(var n,e=[],r=null,a=null;!t("punc","}");)t("eof")&&f(),t("keyword","case")?(a&&(a.end=o()),r=[],a=new Se({start:(n=I.token,i(),n),expression:De(!0),body:r}),e.push(a),p(":")):t("keyword","default")?(a&&(a.end=o()),r=[],a=new Fe({start:(n=I.token,i(),p(":"),n),body:r}),e.push(a)):(r||f(),r.push(U()));return a&&(a.end=o()),i(),e}function C(){var n=F(),e=null,r=null;if(t("keyword","catch")){var a=I.token;i(),p("(");var s=M(at);p(")"),e=new ke({start:a,argname:s,body:F(),end:o()})}if(t("keyword","finally")){var a=I.token;i(),r=new xe({start:a,body:F(),end:o()})}return e||r||u("Missing catch/finally blocks"),new Ce({body:n,bcatch:e,bfinally:r})}function k(n,e){for(var r=[];r.push(new Oe({start:I.token,name:M(e?tt:et),value:t("operator","=")?(i(),De(!1,n)):null,end:o()})),t("punc",",");)i();return r}function x(){var n,e=I.token;switch(e.type){case"name":case"keyword":n=O(st);break;case"num":n=new dt({start:e,end:e,value:e.value});break;case"string":n=new pt({start:e,end:e,value:e.value});break;case"regexp":n=new ht({start:e,end:e,value:e.value});break;case"atom":switch(e.value){case"false":n=new wt({start:e,end:e});break;case"true":n=new Et({start:e,end:e});break;case"null":n=new mt({start:e,end:e})}}return i(),n}function B(n,e,r){for(var o=!0,a=[];!t("punc",n)&&(o?o=!1:p(","),!e||!t("punc",n));)a.push(t("punc",",")&&r?new bt({start:I.token,end:I.token}):De(!1));return i(),a}function T(){var n=I.token;switch(i(),n.type){case"num":case"string":case"name":case"operator":case"keyword":case"atom":return n.value;default:f()}}function $(){var n=I.token;switch(i(),n.type){case"name":case"operator":case"keyword":case"atom":return n.value;default:f()}}function O(n){var e=I.token.value;return new("this"==e?ft:n)({name:String(e),start:I.token,end:I.token})}function M(n,e){if(!t("name"))return e||u("Name expected"),null;var r=O(n);return i(),r}function H(n,e,t){return"++"!=e&&"--"!=e||P(t)||u("Invalid use of "+e+" operator"),new n({operator:e,expression:t})}function z(n){return _e(le(!0),0,n)}function P(n){return e.strict?n instanceof ft?!1:n instanceof qe||n instanceof Ze:!0}function j(n){++I.in_loop;var e=n();return--I.in_loop,e}e=c(e,{strict:!1,filename:null,toplevel:null,expression:!1,html5_comments:!0});var I={input:"string"==typeof n?q(n,e.filename,e.html5_comments):n,token:null,prev:null,peeked:null,in_function:0,in_directives:!0,in_loop:0,labels:[]};I.token=i();var U=m(function(){var n;switch(v(),I.token.type){case"string":var e=I.in_directives,a=b();return e&&a.body instanceof pt&&!t("punc",",")?new G({value:a.body.value}):a;case"num":case"regexp":case"operator":case"atom":return b();case"name":return R(r(),"punc",":")?g():b();case"punc":switch(I.token.value){case"{":return new Z({start:I.token,body:F(),end:o()});case"[":case"(":return b();case";":return i(),new Q;default:f()}case"keyword":switch(n=I.token.value,i(),n){case"break":return y(ye);case"continue":return y(Ae);case"debugger":return h(),new X;case"do":return new ie({body:j(U),condition:(l("keyword","while"),n=_(),h(),n)});case"while":return new oe({condition:_(),body:j(U)});case"for":return A();case"function":return V(he);case"if":return D();case"return":return 0==I.in_function&&u("'return' outside of function"),new ve({value:t("punc",";")?(i(),null):d()?null:(n=De(!0),h(),n)});case"switch":return new Ee({expression:_(),body:j(S)});case"throw":return I.token.nlb&&u("Illegal newline after 'throw'"),new ge({value:(n=De(!0),h(),n)});case"try":return C();case"var":return n=L(),h(),n;case"const":return n=W(),h(),n;case"with":return new se({expression:_(),body:U()});default:f()}}}),V=function(n){var e=n===he,r=t("name")?M(e?it:ot):null;return e&&!r&&f(),p("("),new n({name:r,argnames:function(n,e){for(;!t("punc",")");)n?n=!1:p(","),e.push(M(rt));return i(),e}(!0,[]),body:function(n,e){++I.in_function,I.in_directives=!0,I.in_loop=0,I.labels=[];var t=F();return--I.in_function,I.in_loop=n,I.labels=e,t}(I.in_loop,I.labels)})},L=function(n){return new Te({start:o(),definitions:k(n,!1),end:o()})},W=function(){return new $e({start:o(),definitions:k(!1,!0),end:o()})},Y=function(){var n=I.token;l("operator","new");var e,r=J(!1);return t("punc","(")?(i(),e=B(")")):e=[],ce(new Ne({start:n,expression:r,args:e,end:o()}),!0)},J=function(n){if(t("operator","new"))return Y();var e=I.token;if(t("punc")){switch(e.value){case"(":i();var r=De(!0);return r.start=e,r.end=I.token,p(")"),ce(r,n);case"[":return ce(ne(),n);case"{":return ce(re(),n)}f()}if(t("keyword","function")){i();var a=V(de);return a.start=e,a.end=o(),ce(a,n)}return Vt[I.token.type]?ce(x(),n):void f()},ne=m(function(){return p("["),new We({elements:B("]",!e.strict,!0)})}),re=m(function(){p("{");for(var n=!0,r=[];!t("punc","}")&&(n?n=!1:p(","),e.strict||!t("punc","}"));){var a=I.token,u=a.type,s=T();if("name"==u&&!t("punc",":")){if("get"==s){r.push(new Je({start:a,key:x(),value:V(pe),end:o()}));continue}if("set"==s){r.push(new Ke({start:a,key:x(),value:V(pe),end:o()}));continue}}p(":"),r.push(new Ge({start:a,key:s,value:De(!1),end:o()}))}return i(),new Ye({properties:r})}),ce=function(n,e){var r=n.start;if(t("punc","."))return i(),ce(new He({start:r,expression:n,property:$(),end:o()}),e);if(t("punc","[")){i();var a=De(!0);return p("]"),ce(new ze({start:r,expression:n,property:a,end:o()}),e)}return e&&t("punc","(")?(i(),ce(new Me({start:r,expression:n,args:B(")"),end:o()}),!0)):n},le=function(n){var e=I.token;if(t("operator")&&zt(e.value)){i(),v();var r=H(je,e.value,le(n));return r.start=e,r.end=o(),r}for(var a=J(n);t("operator")&&Pt(I.token.value)&&!I.token.nlb;)a=H(Ie,I.token.value,a),a.start=e,a.end=I.token,i();return a},_e=function(n,e,r){var o=t("operator")?I.token.value:null;"in"==o&&r&&(o=null);var a=null!=o?It[o]:null;if(null!=a&&a>e){i();var u=_e(le(!0),a,r);return _e(new Ue({start:n.start,left:n,operator:o,right:u,end:u.end}),e,r)}return n},me=function(n){var e=I.token,r=z(n);if(t("operator","?")){i();var a=De(!1);return p(":"),new Ve({start:e,condition:r,consequent:a,alternative:De(!1,n),end:o()})}return r},be=function(n){var e=I.token,r=me(n),a=I.token.value;if(t("operator")&&jt(a)){if(P(r))return i(),new Le({start:e,left:r,operator:a,right:be(n),end:o()});u("Invalid assignment")}return r},De=function(n,e){var o=I.token,a=be(e);return n&&t("punc",",")?(i(),new Re({start:o,car:a,cdr:De(!0,e),end:r()})):a};return e.expression?De(!0):function(){for(var n=I.token,r=[];!t("eof");)r.push(U());var i=o(),a=e.toplevel;return a?(a.body=a.body.concat(r),a.end=i):a=new fe({start:n,body:r,end:i}),a}()}function z(n,e){E.call(this),this.before=n,this.after=e}function P(n,e,t){this.name=t.name,this.orig=[t],this.scope=n,this.references=[],this.global=!1,this.mangled_name=null,this.undeclared=!1,this.constant=!1,this.index=e}function j(n){function e(n,e){return n.replace(/[\u0080-\uffff]/g,function(n){var t=n.charCodeAt(0).toString(16);if(t.length<=2&&!e){for(;t.length<2;)t="0"+t;return"\\x"+t}for(;t.length<4;)t="0"+t;return"\\u"+t})}function t(t){var r=0,i=0;return t=t.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g,function(n){switch(n){case"\\":return"\\\\";case"\b":return"\\b";case"\f":return"\\f";case"\n":return"\\n";case"\r":return"\\r";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";case'"':return++r,'"';case"'":return++i,"'";case"\x00":return"\\x00"}return n}),n.ascii_only&&(t=e(t)),r>i?"'"+t.replace(/\x27/g,"\\'")+"'":'"'+t.replace(/\x22/g,'\\"')+'"'}function r(e){var r=t(e);return n.inline_script&&(r=r.replace(/<\x2fscript([>\/\t\n\f\r ])/gi,"<\\/script$1")),r}function i(t){return t=t.toString(),n.ascii_only&&(t=e(t,!0)),t}function o(e){return u(" ",n.indent_start+A-e*n.indent_level)}function a(){return k.charAt(k.length-1)}function s(){n.max_line_len&&w>n.max_line_len&&f("\n")}function f(e){e=String(e);var t=e.charAt(0);if(C&&(t&&!(";}".indexOf(t)<0)||/[;]$/.test(k)||(n.semicolons||x(t)?(F+=";",w++,D++):(F+="\n",D++,E++,w=0),n.beautify||(S=!1)),C=!1,s()),!n.beautify&&n.preserve_line&&q[q.length-1])for(var r=q[q.length-1].start.line;r>E;)F+="\n",D++,E++,w=0,S=!1;if(S){var i=a();(T(i)&&(T(t)||"\\"==t)||/^[\+\-\/]$/.test(t)&&t==i)&&(F+=" ",w++,D++),S=!1}var o=e.split(/\r?\n/),u=o.length-1;E+=u,0==u?w+=o[u].length:w=o[u].length,D+=e.length,k=e,F+=e}function p(){C=!1,f(";")}function d(){return A+n.indent_level}function h(n){var e;return f("{"),M(),O(d(),function(){e=n()}),$(),f("}"),e}function _(n){f("(");var e=n();return f(")"),e}function m(n){f("[");var e=n();return f("]"),e}function v(){f(","),B()}function b(){f(":"),n.space_colon&&B()}function y(){return F}n=c(n,{indent_start:0,indent_level:4,quote_keys:!1,space_colon:!0,ascii_only:!1,unescape_regexps:!1,inline_script:!1,width:80,max_line_len:32e3,beautify:!1,source_map:null,bracketize:!1,semicolons:!0,comments:!1,preserve_line:!1,screw_ie8:!1,preamble:null},!0);var A=0,w=0,E=1,D=0,F="",S=!1,C=!1,k=null,x=g("( [ + * / - , ."),B=n.beautify?function(){f(" ")}:function(){S=!0},$=n.beautify?function(e){n.beautify&&f(o(e?.5:0))}:l,O=n.beautify?function(n,e){n===!0&&(n=d());var t=A;A=n;var r=e();return A=t,r}:function(n,e){return e()},M=n.beautify?function(){f("\n")}:l,N=n.beautify?function(){f(";")}:function(){C=!0},R=n.source_map?function(e,t){try{e&&n.source_map.add(e.file||"?",E,w,e.line,e.col,t||"name"!=e.type?t:e.value)}catch(r){W.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]",{file:e.file,line:e.line,col:e.col,cline:E,ccol:w,name:t||""})}}:l;n.preamble&&f(n.preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g,"\n"));var q=[];return{get:y,toString:y,indent:$,indentation:function(){return A},current_width:function(){return w-A},should_break:function(){return n.width&&this.current_width()>=n.width},newline:M,print:f,space:B,comma:v,colon:b,last:function(){return k},semicolon:N,force_semicolon:p,to_ascii:e,print_name:function(n){f(i(n))},print_string:function(n){f(r(n))},next_indent:d,with_indent:O,with_block:h,with_parens:_,with_square:m,add_mapping:R,option:function(e){return n[e]},line:function(){return E},col:function(){return w},pos:function(){return D},push_node:function(n){q.push(n)},pop_node:function(){return q.pop()},stack:function(){return q},parent:function(n){return q[q.length-2-(n||0)]}}}function I(n,e){return this instanceof I?(z.call(this,this.before,this.after),void(this.options=c(n,{sequences:!e,properties:!e,dead_code:!e,drop_debugger:!e,unsafe:!1,unsafe_comps:!1,conditionals:!e,comparisons:!e,evaluate:!e,booleans:!e,loops:!e,unused:!e,hoist_funs:!e,keep_fargs:!1,hoist_vars:!1,if_return:!e,join_vars:!e,cascade:!e,side_effects:!e,pure_getters:!1,pure_funcs:null,negate_iife:!e,screw_ie8:!1,drop_console:!1,angular:!1,warnings:!0,global_defs:{}},!0))):new I(n,e)}function U(n){function e(e,i,o,a,u,s){if(r){var c=r.originalPositionFor({line:a,column:u});if(null===c.source)return;e=c.source,a=c.line,u=c.column,s=c.name}t.addMapping({generated:{line:i+n.dest_line_diff,column:o},original:{line:a+n.orig_line_diff,column:u},source:e,name:s})}n=c(n,{file:null,root:null,orig:null,orig_line_diff:0,dest_line_diff:0});var t=new MOZ_SourceMap.SourceMapGenerator({file:n.file,sourceRoot:n.root}),r=n.orig&&new MOZ_SourceMap.SourceMapConsumer(n.orig);return{add:e,get:function(){return t},toString:function(){return t.toString()}}}e.UglifyJS=n,s.prototype=Object.create(Error.prototype),s.prototype.constructor=s,s.croak=function(n,e){throw new s(n,e)};var V=function(){function n(n,o,a){function u(){var u=o(n[s],s),l=u instanceof r;return l&&(u=u.v),u instanceof e?(u=u.v,u instanceof t?f.push.apply(f,a?u.v.slice().reverse():u.v):f.push(u)):u!==i&&(u instanceof t?c.push.apply(c,a?u.v.slice().reverse():u.v):c.push(u)),l}var s,c=[],f=[];if(n instanceof Array)if(a){for(s=n.length;--s>=0&&!u(););c.reverse(),f.reverse()}else for(s=0;s<n.length&&!u();++s);else for(s in n)if(n.hasOwnProperty(s)&&u())break;return f.concat(c)}function e(n){this.v=n}function t(n){this.v=n}function r(n){this.v=n}n.at_top=function(n){return new e(n)},n.splice=function(n){return new t(n)},n.last=function(n){return new r(n)};var i=n.skip={};return n}();y.prototype={set:function(n,e){return this.has(n)||++this._size,this._values["$"+n]=e,this},add:function(n,e){return this.has(n)?this.get(n).push(e):this.set(n,[e]),this},get:function(n){return this._values["$"+n]},del:function(n){return this.has(n)&&(--this._size,delete this._values["$"+n]),this},has:function(n){return"$"+n in this._values},each:function(n){for(var e in this._values)n(this._values[e],e.substr(1))},size:function(){return this._size},map:function(n){var e=[];for(var t in this._values)e.push(n(this._values[t],t.substr(1)));return e}};var L=A("Token","type value line col pos endpos nlb comments_before file",{},null),W=A("Node","start end",{clone:function(){return new this.CTOR(this)},$documentation:"Base class of all AST nodes",$propdoc:{start:"[AST_Token] The first token of this node",end:"[AST_Token] The last token of this node"},_walk:function(n){return n._visit(this)},walk:function(n){return this._walk(n)}},null);W.warn_function=null,W.warn=function(n,e){W.warn_function&&W.warn_function(d(n,e))};var Y=A("Statement",null,{$documentation:"Base class of all statements"}),X=A("Debugger",null,{$documentation:"Represents a debugger statement"},Y),G=A("Directive","value scope",{$documentation:'Represents a directive, like "use strict";',$propdoc:{value:"[string] The value of this directive as a plain string (it's not an AST_String!)",scope:"[AST_Scope/S] The scope that this directive affects"}},Y),K=A("SimpleStatement","body",{$documentation:"A statement consisting of an expression, i.e. a = 1 + 2",$propdoc:{body:"[AST_Node] an expression node (should not be instanceof AST_Statement)"},_walk:function(n){return n._visit(this,function(){this.body._walk(n)})}},Y),J=A("Block","body",{$documentation:"A body of statements (usually bracketed)",$propdoc:{body:"[AST_Statement*] an array of statements"},_walk:function(n){return n._visit(this,function(){w(this,n)})}},Y),Z=A("BlockStatement",null,{$documentation:"A block statement"},J),Q=A("EmptyStatement",null,{$documentation:"The empty statement (empty block or simply a semicolon)",_walk:function(n){return n._visit(this)}},Y),ne=A("StatementWithBody","body",{$documentation:"Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",$propdoc:{body:"[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"},_walk:function(n){return n._visit(this,function(){this.body._walk(n)})}},Y),ee=A("LabeledStatement","label",{$documentation:"Statement with a label",$propdoc:{label:"[AST_Label] a label definition"},_walk:function(n){return n._visit(this,function(){this.label._walk(n),this.body._walk(n)})}},ne),te=A("IterationStatement",null,{$documentation:"Internal class. All loops inherit from it."},ne),re=A("DWLoop","condition",{$documentation:"Base class for do/while statements",$propdoc:{condition:"[AST_Node] the loop condition. Should not be instanceof AST_Statement"},_walk:function(n){return n._visit(this,function(){this.condition._walk(n),this.body._walk(n)})}},te),ie=A("Do",null,{$documentation:"A `do` statement"},re),oe=A("While",null,{$documentation:"A `while` statement"},re),ae=A("For","init condition step",{$documentation:"A `for` statement",$propdoc:{init:"[AST_Node?] the `for` initialization code, or null if empty",condition:"[AST_Node?] the `for` termination clause, or null if empty",step:"[AST_Node?] the `for` update clause, or null if empty"},_walk:function(n){return n._visit(this,function(){this.init&&this.init._walk(n),this.condition&&this.condition._walk(n),this.step&&this.step._walk(n),this.body._walk(n)})}},te),ue=A("ForIn","init name object",{$documentation:"A `for ... in` statement",$propdoc:{init:"[AST_Node] the `for/in` initialization code",name:"[AST_SymbolRef?] the loop variable, only if `init` is AST_Var",object:"[AST_Node] the object that we're looping through"},_walk:function(n){return n._visit(this,function(){this.init._walk(n),this.object._walk(n),this.body._walk(n)})}},te),se=A("With","expression",{$documentation:"A `with` statement",$propdoc:{expression:"[AST_Node] the `with` expression"},_walk:function(n){return n._visit(this,function(){this.expression._walk(n),this.body._walk(n)})}},ne),ce=A("Scope","directives variables functions uses_with uses_eval parent_scope enclosed cname",{$documentation:"Base class for all statements introducing a lexical scope",$propdoc:{directives:"[string*/S] an array of directives declared in this scope",variables:"[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",functions:"[Object/S] like `variables`, but only lists function declarations",uses_with:"[boolean/S] tells whether this scope uses the `with` statement",uses_eval:"[boolean/S] tells whether this scope contains a direct call to the global `eval`",parent_scope:"[AST_Scope?/S] link to the parent scope",enclosed:"[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",cname:"[integer/S] current index for mangling variables (used internally by the mangler)"}},J),fe=A("Toplevel","globals",{$documentation:"The toplevel scope",$propdoc:{globals:"[Object/S] a map of name -> SymbolDef for all undeclared names"},wrap_enclose:function(n){var e=this,t=[],r=[];n.forEach(function(n){var e=n.lastIndexOf(":");t.push(n.substr(0,e)),r.push(n.substr(e+1))});var i="(function("+r.join(",")+"){ '$ORIG'; })("+t.join(",")+")";return i=H(i),i=i.transform(new z(function(n){return n instanceof G&&"$ORIG"==n.value?V.splice(e.body):void 0}))},wrap_commonjs:function(n,e){var t=this,r=[];e&&(t.figure_out_scope(),t.walk(new E(function(n){n instanceof nt&&n.definition().global&&(a(function(e){return e.name==n.name},r)||r.push(n))})));var i="(function(exports, global){ global['"+n+"'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))";return i=H(i),i=i.transform(new z(function(n){if(n instanceof K&&(n=n.body,n instanceof pt))switch(n.getValue()){case"$ORIG":return V.splice(t.body);case"$EXPORTS":var e=[];return r.forEach(function(n){e.push(new K({body:new Le({left:new ze({expression:new st({name:"exports"}),property:new pt({value:n.name})}),operator:"=",right:new st(n)})}))}),V.splice(e)}}))}},ce),le=A("Lambda","name argnames uses_arguments",{$documentation:"Base class for functions",$propdoc:{name:"[AST_SymbolDeclaration?] the name of this function",argnames:"[AST_SymbolFunarg*] array of function arguments",uses_arguments:"[boolean/S] tells whether this function accesses the arguments array"},_walk:function(n){return n._visit(this,function(){this.name&&this.name._walk(n),this.argnames.forEach(function(e){e._walk(n)}),w(this,n)})}},ce),pe=A("Accessor",null,{$documentation:"A setter/getter function. The `name` property is always null."},le),de=A("Function",null,{$documentation:"A function expression"},le),he=A("Defun",null,{$documentation:"A function definition"},le),_e=A("Jump",null,{$documentation:"Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"},Y),me=A("Exit","value",{$documentation:"Base class for “exits” (`return` and `throw`)",$propdoc:{value:"[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"},_walk:function(n){return n._visit(this,this.value&&function(){this.value._walk(n)})}},_e),ve=A("Return",null,{$documentation:"A `return` statement"},me),ge=A("Throw",null,{$documentation:"A `throw` statement"},me),be=A("LoopControl","label",{$documentation:"Base class for loop control statements (`break` and `continue`)",$propdoc:{label:"[AST_LabelRef?] the label, or null if none"},_walk:function(n){return n._visit(this,this.label&&function(){this.label._walk(n)})}},_e),ye=A("Break",null,{$documentation:"A `break` statement"},be),Ae=A("Continue",null,{$documentation:"A `continue` statement"},be),we=A("If","condition alternative",{$documentation:"A `if` statement",$propdoc:{condition:"[AST_Node] the `if` condition",alternative:"[AST_Statement?] the `else` part, or null if not present"},_walk:function(n){return n._visit(this,function(){this.condition._walk(n),this.body._walk(n),this.alternative&&this.alternative._walk(n)})}},ne),Ee=A("Switch","expression",{$documentation:"A `switch` statement",$propdoc:{expression:"[AST_Node] the `switch` “discriminant”"},_walk:function(n){return n._visit(this,function(){this.expression._walk(n),w(this,n)})}},J),De=A("SwitchBranch",null,{$documentation:"Base class for `switch` branches"},J),Fe=A("Default",null,{$documentation:"A `default` switch branch"},De),Se=A("Case","expression",{$documentation:"A `case` switch branch",$propdoc:{expression:"[AST_Node] the `case` expression"},_walk:function(n){return n._visit(this,function(){this.expression._walk(n),w(this,n)})}},De),Ce=A("Try","bcatch bfinally",{$documentation:"A `try` statement",$propdoc:{bcatch:"[AST_Catch?] the catch block, or null if not present",bfinally:"[AST_Finally?] the finally block, or null if not present"},_walk:function(n){return n._visit(this,function(){w(this,n),this.bcatch&&this.bcatch._walk(n),this.bfinally&&this.bfinally._walk(n)})}},J),ke=A("Catch","argname",{$documentation:"A `catch` node; only makes sense as part of a `try` statement",$propdoc:{argname:"[AST_SymbolCatch] symbol for the exception"},_walk:function(n){return n._visit(this,function(){this.argname._walk(n),w(this,n)
+})}},J),xe=A("Finally",null,{$documentation:"A `finally` node; only makes sense as part of a `try` statement"},J),Be=A("Definitions","definitions",{$documentation:"Base class for `var` or `const` nodes (variable declarations/initializations)",$propdoc:{definitions:"[AST_VarDef*] array of variable definitions"},_walk:function(n){return n._visit(this,function(){this.definitions.forEach(function(e){e._walk(n)})})}},Y),Te=A("Var",null,{$documentation:"A `var` statement"},Be),$e=A("Const",null,{$documentation:"A `const` statement"},Be),Oe=A("VarDef","name value",{$documentation:"A variable declaration; only appears in a AST_Definitions node",$propdoc:{name:"[AST_SymbolVar|AST_SymbolConst] name of the variable",value:"[AST_Node?] initializer, or null of there's no initializer"},_walk:function(n){return n._visit(this,function(){this.name._walk(n),this.value&&this.value._walk(n)})}}),Me=A("Call","expression args",{$documentation:"A function call expression",$propdoc:{expression:"[AST_Node] expression to invoke as function",args:"[AST_Node*] array of arguments"},_walk:function(n){return n._visit(this,function(){this.expression._walk(n),this.args.forEach(function(e){e._walk(n)})})}}),Ne=A("New",null,{$documentation:"An object instantiation. Derives from a function call since it has exactly the same properties"},Me),Re=A("Seq","car cdr",{$documentation:"A sequence expression (two comma-separated expressions)",$propdoc:{car:"[AST_Node] first element in sequence",cdr:"[AST_Node] second element in sequence"},$cons:function(n,e){var t=new Re(n);return t.car=n,t.cdr=e,t},$from_array:function(n){if(0==n.length)return null;if(1==n.length)return n[0].clone();for(var e=null,t=n.length;--t>=0;)e=Re.cons(n[t],e);for(var r=e;r;){if(r.cdr&&!r.cdr.cdr){r.cdr=r.cdr.car;break}r=r.cdr}return e},to_array:function(){for(var n=this,e=[];n;){if(e.push(n.car),n.cdr&&!(n.cdr instanceof Re)){e.push(n.cdr);break}n=n.cdr}return e},add:function(n){for(var e=this;e;){if(!(e.cdr instanceof Re)){var t=Re.cons(e.cdr,n);return e.cdr=t}e=e.cdr}},_walk:function(n){return n._visit(this,function(){this.car._walk(n),this.cdr&&this.cdr._walk(n)})}}),qe=A("PropAccess","expression property",{$documentation:'Base class for property access expressions, i.e. `a.foo` or `a["foo"]`',$propdoc:{expression:"[AST_Node] the “container” expression",property:"[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node"}}),He=A("Dot",null,{$documentation:"A dotted property access expression",_walk:function(n){return n._visit(this,function(){this.expression._walk(n)})}},qe),ze=A("Sub",null,{$documentation:'Index-style property access, i.e. `a["foo"]`',_walk:function(n){return n._visit(this,function(){this.expression._walk(n),this.property._walk(n)})}},qe),Pe=A("Unary","operator expression",{$documentation:"Base class for unary expressions",$propdoc:{operator:"[string] the operator",expression:"[AST_Node] expression that this unary operator applies to"},_walk:function(n){return n._visit(this,function(){this.expression._walk(n)})}}),je=A("UnaryPrefix",null,{$documentation:"Unary prefix expression, i.e. `typeof i` or `++i`"},Pe),Ie=A("UnaryPostfix",null,{$documentation:"Unary postfix expression, i.e. `i++`"},Pe),Ue=A("Binary","left operator right",{$documentation:"Binary expression, i.e. `a + b`",$propdoc:{left:"[AST_Node] left-hand side expression",operator:"[string] the operator",right:"[AST_Node] right-hand side expression"},_walk:function(n){return n._visit(this,function(){this.left._walk(n),this.right._walk(n)})}}),Ve=A("Conditional","condition consequent alternative",{$documentation:"Conditional expression using the ternary operator, i.e. `a ? b : c`",$propdoc:{condition:"[AST_Node]",consequent:"[AST_Node]",alternative:"[AST_Node]"},_walk:function(n){return n._visit(this,function(){this.condition._walk(n),this.consequent._walk(n),this.alternative._walk(n)})}}),Le=A("Assign",null,{$documentation:"An assignment expression — `a = b + 5`"},Ue),We=A("Array","elements",{$documentation:"An array literal",$propdoc:{elements:"[AST_Node*] array of elements"},_walk:function(n){return n._visit(this,function(){this.elements.forEach(function(e){e._walk(n)})})}}),Ye=A("Object","properties",{$documentation:"An object literal",$propdoc:{properties:"[AST_ObjectProperty*] array of properties"},_walk:function(n){return n._visit(this,function(){this.properties.forEach(function(e){e._walk(n)})})}}),Xe=A("ObjectProperty","key value",{$documentation:"Base class for literal object properties",$propdoc:{key:"[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an arbitrary AST_Node.",value:"[AST_Node] property value. For setters and getters this is an AST_Function."},_walk:function(n){return n._visit(this,function(){this.value._walk(n)})}}),Ge=A("ObjectKeyVal",null,{$documentation:"A key: value object property"},Xe),Ke=A("ObjectSetter",null,{$documentation:"An object setter property"},Xe),Je=A("ObjectGetter",null,{$documentation:"An object getter property"},Xe),Ze=A("Symbol","scope name thedef",{$propdoc:{name:"[string] name of this symbol",scope:"[AST_Scope/S] the current scope (not necessarily the definition scope)",thedef:"[SymbolDef/S] the definition of this symbol"},$documentation:"Base class for all symbols"}),Qe=A("SymbolAccessor",null,{$documentation:"The name of a property accessor (setter/getter function)"},Ze),nt=A("SymbolDeclaration","init",{$documentation:"A declaration symbol (symbol in var/const, function name or argument, symbol in catch)",$propdoc:{init:"[AST_Node*/S] array of initializers for this declaration."}},Ze),et=A("SymbolVar",null,{$documentation:"Symbol defining a variable"},nt),tt=A("SymbolConst",null,{$documentation:"A constant declaration"},nt),rt=A("SymbolFunarg",null,{$documentation:"Symbol naming a function argument"},et),it=A("SymbolDefun",null,{$documentation:"Symbol defining a function"},nt),ot=A("SymbolLambda",null,{$documentation:"Symbol naming a function expression"},nt),at=A("SymbolCatch",null,{$documentation:"Symbol naming the exception in catch"},nt),ut=A("Label","references",{$documentation:"Symbol naming a label (declaration)",$propdoc:{references:"[AST_LoopControl*] a list of nodes referring to this label"},initialize:function(){this.references=[],this.thedef=this}},Ze),st=A("SymbolRef",null,{$documentation:"Reference to some symbol (not definition/declaration)"},Ze),ct=A("LabelRef",null,{$documentation:"Reference to a label symbol"},Ze),ft=A("This",null,{$documentation:"The `this` symbol"},Ze),lt=A("Constant",null,{$documentation:"Base class for all constants",getValue:function(){return this.value}}),pt=A("String","value",{$documentation:"A string literal",$propdoc:{value:"[string] the contents of this string"}},lt),dt=A("Number","value",{$documentation:"A number literal",$propdoc:{value:"[number] the numeric value"}},lt),ht=A("RegExp","value",{$documentation:"A regexp literal",$propdoc:{value:"[RegExp] the actual regexp"}},lt),_t=A("Atom",null,{$documentation:"Base class for atoms"},lt),mt=A("Null",null,{$documentation:"The `null` atom",value:null},_t),vt=A("NaN",null,{$documentation:"The impossible value",value:0/0},_t),gt=A("Undefined",null,{$documentation:"The `undefined` value",value:void 0},_t),bt=A("Hole",null,{$documentation:"A hole in an array",value:void 0},_t),yt=A("Infinity",null,{$documentation:"The `Infinity` value",value:1/0},_t),At=A("Boolean",null,{$documentation:"Base class for booleans"},_t),wt=A("False",null,{$documentation:"The `false` atom",value:!1},At),Et=A("True",null,{$documentation:"The `true` atom",value:!0},At);E.prototype={_visit:function(n,e){this.stack.push(n);var t=this.visit(n,e?function(){e.call(n)}:l);return!t&&e&&e.call(n),this.stack.pop(),t},parent:function(n){return this.stack[this.stack.length-2-(n||0)]},push:function(n){this.stack.push(n)},pop:function(){return this.stack.pop()},self:function(){return this.stack[this.stack.length-1]},find_parent:function(n){for(var e=this.stack,t=e.length;--t>=0;){var r=e[t];if(r instanceof n)return r}},has_directive:function(n){return this.find_parent(ce).has_directive(n)},in_boolean_context:function(){for(var n=this.stack,e=n.length,t=n[--e];e>0;){var r=n[--e];if(r instanceof we&&r.condition===t||r instanceof Ve&&r.condition===t||r instanceof re&&r.condition===t||r instanceof ae&&r.condition===t||r instanceof je&&"!"==r.operator&&r.expression===t)return!0;if(!(r instanceof Ue)||"&&"!=r.operator&&"||"!=r.operator)return!1;t=r}},loopcontrol_target:function(n){var e=this.stack;if(n)for(var t=e.length;--t>=0;){var r=e[t];if(r instanceof ee&&r.label.name==n.name)return r.body}else for(var t=e.length;--t>=0;){var r=e[t];if(r instanceof Ee||r instanceof te)return r}}};var Dt="break case catch const continue debugger default delete do else finally for function if in instanceof new return switch throw try typeof var void while with",Ft="false null true",St="abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized this throws transient volatile yield "+Ft+" "+Dt,Ct="return new delete throw else case";Dt=g(Dt),St=g(St),Ct=g(Ct),Ft=g(Ft);var kt=g(i("+-*&%=<>!?|~^")),xt=/^0x[0-9a-f]+$/i,Bt=/^0[0-7]+$/,Tt=/^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i,$t=g(["in","instanceof","typeof","new","void","delete","++","--","+","-","!","~","&","|","^","*","/","%",">>","<<",">>>","<",">","<=",">=","==","===","!=","!==","?","=","+=","-=","/=","*=","%=",">>=","<<=",">>>=","|=","^=","&=","&&","||"]),Ot=g(i(" \n\r \f ")),Mt=g(i("[{(,.;:")),Nt=g(i("[]{}(),;:")),Rt=g(i("gmsiy")),qt={letter:new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0523\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0621-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971\\u0972\\u097B-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D28\\u0D2A-\\u0D39\\u0D3D\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC\\u0EDD\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8B\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10D0-\\u10FA\\u10FC\\u1100-\\u1159\\u115F-\\u11A2\\u11A8-\\u11F9\\u1200-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u1676\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19A9\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u2094\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2C6F\\u2C71-\\u2C7D\\u2C80-\\u2CE4\\u2D00-\\u2D25\\u2D30-\\u2D65\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31B7\\u31F0-\\u31FF\\u3400\\u4DB5\\u4E00\\u9FC3\\uA000-\\uA48C\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA65F\\uA662-\\uA66E\\uA67F-\\uA697\\uA717-\\uA71F\\uA722-\\uA788\\uA78B\\uA78C\\uA7FB-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA90A-\\uA925\\uA930-\\uA946\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAC00\\uD7A3\\uF900-\\uFA2D\\uFA30-\\uFA6A\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"),non_spacing_mark:new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),space_combining_mark:new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"),connector_punctuation:new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")};M.prototype.toString=function(){return this.message+" (line: "+this.line+", col: "+this.col+", pos: "+this.pos+")\n\n"+this.stack};var Ht={},zt=g(["typeof","void","delete","--","++","!","~","-","+"]),Pt=g(["--","++"]),jt=g(["=","+=","-=","/=","*=","%=",">>=","<<=",">>>=","|=","^=","&="]),It=function(n,e){for(var t=0;t<n.length;++t)for(var r=n[t],i=0;i<r.length;++i)e[r[i]]=t+1;return e}([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]],{}),Ut=t(["for","do","while","switch"]),Vt=t(["atom","num","string","regexp","name"]);z.prototype=new E,function(n){function e(e,t){e.DEFMETHOD("transform",function(e,r){var i,o;return e.push(this),e.before&&(i=e.before(this,t,r)),i===n&&(e.after?(e.stack[e.stack.length-1]=i=this.clone(),t(i,e),o=e.after(i,r),o!==n&&(i=o)):(i=this,t(i,e))),e.pop(),i})}function t(n,e){return V(n,function(n){return n.transform(e,!0)})}e(W,l),e(ee,function(n,e){n.label=n.label.transform(e),n.body=n.body.transform(e)}),e(K,function(n,e){n.body=n.body.transform(e)}),e(J,function(n,e){n.body=t(n.body,e)}),e(re,function(n,e){n.condition=n.condition.transform(e),n.body=n.body.transform(e)}),e(ae,function(n,e){n.init&&(n.init=n.init.transform(e)),n.condition&&(n.condition=n.condition.transform(e)),n.step&&(n.step=n.step.transform(e)),n.body=n.body.transform(e)}),e(ue,function(n,e){n.init=n.init.transform(e),n.object=n.object.transform(e),n.body=n.body.transform(e)}),e(se,function(n,e){n.expression=n.expression.transform(e),n.body=n.body.transform(e)}),e(me,function(n,e){n.value&&(n.value=n.value.transform(e))}),e(be,function(n,e){n.label&&(n.label=n.label.transform(e))}),e(we,function(n,e){n.condition=n.condition.transform(e),n.body=n.body.transform(e),n.alternative&&(n.alternative=n.alternative.transform(e))}),e(Ee,function(n,e){n.expression=n.expression.transform(e),n.body=t(n.body,e)}),e(Se,function(n,e){n.expression=n.expression.transform(e),n.body=t(n.body,e)}),e(Ce,function(n,e){n.body=t(n.body,e),n.bcatch&&(n.bcatch=n.bcatch.transform(e)),n.bfinally&&(n.bfinally=n.bfinally.transform(e))}),e(ke,function(n,e){n.argname=n.argname.transform(e),n.body=t(n.body,e)}),e(Be,function(n,e){n.definitions=t(n.definitions,e)}),e(Oe,function(n,e){n.name=n.name.transform(e),n.value&&(n.value=n.value.transform(e))}),e(le,function(n,e){n.name&&(n.name=n.name.transform(e)),n.argnames=t(n.argnames,e),n.body=t(n.body,e)}),e(Me,function(n,e){n.expression=n.expression.transform(e),n.args=t(n.args,e)}),e(Re,function(n,e){n.car=n.car.transform(e),n.cdr=n.cdr.transform(e)}),e(He,function(n,e){n.expression=n.expression.transform(e)}),e(ze,function(n,e){n.expression=n.expression.transform(e),n.property=n.property.transform(e)}),e(Pe,function(n,e){n.expression=n.expression.transform(e)}),e(Ue,function(n,e){n.left=n.left.transform(e),n.right=n.right.transform(e)}),e(Ve,function(n,e){n.condition=n.condition.transform(e),n.consequent=n.consequent.transform(e),n.alternative=n.alternative.transform(e)}),e(We,function(n,e){n.elements=t(n.elements,e)}),e(Ye,function(n,e){n.properties=t(n.properties,e)}),e(Xe,function(n,e){n.value=n.value.transform(e)})}(),P.prototype={unmangleable:function(n){return this.global&&!(n&&n.toplevel)||this.undeclared||!(n&&n.eval)&&(this.scope.uses_eval||this.scope.uses_with)},mangle:function(n){if(!this.mangled_name&&!this.unmangleable(n)){var e=this.scope;!n.screw_ie8&&this.orig[0]instanceof ot&&(e=e.parent_scope),this.mangled_name=e.next_mangled(n,this)}}},fe.DEFMETHOD("figure_out_scope",function(n){n=c(n,{screw_ie8:!1});var e=this,t=e.parent_scope=null,r=null,i=0,o=new E(function(e,a){if(n.screw_ie8&&e instanceof ke){var u=t;return t=new ce(e),t.init_scope_vars(i),t.parent_scope=u,a(),t=u,!0}if(e instanceof ce){e.init_scope_vars(i);var u=e.parent_scope=t,s=r;return r=t=e,++i,a(),--i,t=u,r=s,!0}if(e instanceof G)return e.scope=t,p(t.directives,e.value),!0;if(e instanceof se)for(var c=t;c;c=c.parent_scope)c.uses_with=!0;else if(e instanceof Ze&&(e.scope=t),e instanceof ot)r.def_function(e);else if(e instanceof it)(e.scope=r.parent_scope).def_function(e);else if(e instanceof et||e instanceof tt){var f=r.def_variable(e);f.constant=e instanceof tt,f.init=o.parent().value}else e instanceof at&&(n.screw_ie8?t:r).def_variable(e)});e.walk(o);var a=null,u=e.globals=new y,o=new E(function(n,t){if(n instanceof le){var r=a;return a=n,t(),a=r,!0}if(n instanceof st){var i=n.name,s=n.scope.find_variable(i);if(s)n.thedef=s;else{var c;if(u.has(i)?c=u.get(i):(c=new P(e,u.size(),n),c.undeclared=!0,c.global=!0,u.set(i,c)),n.thedef=c,"eval"==i&&o.parent()instanceof Me)for(var f=n.scope;f&&!f.uses_eval;f=f.parent_scope)f.uses_eval=!0;a&&"arguments"==i&&(a.uses_arguments=!0)}return n.reference(),!0}});e.walk(o)}),ce.DEFMETHOD("init_scope_vars",function(n){this.directives=[],this.variables=new y,this.functions=new y,this.uses_with=!1,this.uses_eval=!1,this.parent_scope=null,this.enclosed=[],this.cname=-1,this.nesting=n}),ce.DEFMETHOD("strict",function(){return this.has_directive("use strict")}),le.DEFMETHOD("init_scope_vars",function(){ce.prototype.init_scope_vars.apply(this,arguments),this.uses_arguments=!1}),st.DEFMETHOD("reference",function(){var n=this.definition();n.references.push(this);for(var e=this.scope;e&&(p(e.enclosed,n),e!==n.scope);)e=e.parent_scope;this.frame=this.scope.nesting-n.scope.nesting}),ce.DEFMETHOD("find_variable",function(n){return n instanceof Ze&&(n=n.name),this.variables.get(n)||this.parent_scope&&this.parent_scope.find_variable(n)}),ce.DEFMETHOD("has_directive",function(n){return this.parent_scope&&this.parent_scope.has_directive(n)||(this.directives.indexOf(n)>=0?this:null)}),ce.DEFMETHOD("def_function",function(n){this.functions.set(n.name,this.def_variable(n))}),ce.DEFMETHOD("def_variable",function(n){var e;return this.variables.has(n.name)?(e=this.variables.get(n.name),e.orig.push(n)):(e=new P(this,this.variables.size(),n),this.variables.set(n.name,e),e.global=!this.parent_scope),n.thedef=e}),ce.DEFMETHOD("next_mangled",function(n){var e=this.enclosed;n:for(;;){var t=Lt(++this.cname);if(x(t)&&!(n.except.indexOf(t)>=0)){for(var r=e.length;--r>=0;){var i=e[r],o=i.mangled_name||i.unmangleable(n)&&i.name;if(t==o)continue n}return t}}}),de.DEFMETHOD("next_mangled",function(n,e){for(var t=e.orig[0]instanceof rt&&this.name&&this.name.definition();;){var r=le.prototype.next_mangled.call(this,n,e);if(!t||t.mangled_name!=r)return r}}),ce.DEFMETHOD("references",function(n){return n instanceof Ze&&(n=n.definition()),this.enclosed.indexOf(n)<0?null:n}),Ze.DEFMETHOD("unmangleable",function(n){return this.definition().unmangleable(n)}),Qe.DEFMETHOD("unmangleable",function(){return!0}),ut.DEFMETHOD("unmangleable",function(){return!1}),Ze.DEFMETHOD("unreferenced",function(){return 0==this.definition().references.length&&!(this.scope.uses_eval||this.scope.uses_with)}),Ze.DEFMETHOD("undeclared",function(){return this.definition().undeclared}),ct.DEFMETHOD("undeclared",function(){return!1}),ut.DEFMETHOD("undeclared",function(){return!1}),Ze.DEFMETHOD("definition",function(){return this.thedef}),Ze.DEFMETHOD("global",function(){return this.definition().global}),fe.DEFMETHOD("_default_mangler_options",function(n){return c(n,{except:[],eval:!1,sort:!1,toplevel:!1,screw_ie8:!1})}),fe.DEFMETHOD("mangle_names",function(n){n=this._default_mangler_options(n);var e=-1,t=[],r=new E(function(i,o){if(i instanceof ee){var a=e;return o(),e=a,!0}if(i instanceof ce){var u=(r.parent(),[]);return i.variables.each(function(e){n.except.indexOf(e.name)<0&&u.push(e)}),n.sort&&u.sort(function(n,e){return e.references.length-n.references.length}),void t.push.apply(t,u)}if(i instanceof ut){var s;do s=Lt(++e);while(!x(s));return i.mangled_name=s,!0}return n.screw_ie8&&i instanceof at?void t.push(i.definition()):void 0});this.walk(r),t.forEach(function(e){e.mangle(n)})}),fe.DEFMETHOD("compute_char_frequency",function(n){n=this._default_mangler_options(n);var e=new E(function(e){e instanceof lt?Lt.consider(e.print_to_string()):e instanceof ve?Lt.consider("return"):e instanceof ge?Lt.consider("throw"):e instanceof Ae?Lt.consider("continue"):e instanceof ye?Lt.consider("break"):e instanceof X?Lt.consider("debugger"):e instanceof G?Lt.consider(e.value):e instanceof oe?Lt.consider("while"):e instanceof ie?Lt.consider("do while"):e instanceof we?(Lt.consider("if"),e.alternative&&Lt.consider("else")):e instanceof Te?Lt.consider("var"):e instanceof $e?Lt.consider("const"):e instanceof le?Lt.consider("function"):e instanceof ae?Lt.consider("for"):e instanceof ue?Lt.consider("for in"):e instanceof Ee?Lt.consider("switch"):e instanceof Se?Lt.consider("case"):e instanceof Fe?Lt.consider("default"):e instanceof se?Lt.consider("with"):e instanceof Ke?Lt.consider("set"+e.key):e instanceof Je?Lt.consider("get"+e.key):e instanceof Ge?Lt.consider(e.key):e instanceof Ne?Lt.consider("new"):e instanceof ft?Lt.consider("this"):e instanceof Ce?Lt.consider("try"):e instanceof ke?Lt.consider("catch"):e instanceof xe?Lt.consider("finally"):e instanceof Ze&&e.unmangleable(n)?Lt.consider(e.name):e instanceof Pe||e instanceof Ue?Lt.consider(e.operator):e instanceof He&&Lt.consider(e.property)});this.walk(e),Lt.sort()});var Lt=function(){function n(){r=Object.create(null),t=i.split("").map(function(n){return n.charCodeAt(0)}),t.forEach(function(n){r[n]=0})}function e(n){var e="",r=54;do e+=String.fromCharCode(t[n%r]),n=Math.floor(n/r),r=64;while(n>0);return e}var t,r,i="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";return e.consider=function(n){for(var e=n.length;--e>=0;){var t=n.charCodeAt(e);t in r&&++r[t]}},e.sort=function(){t=_(t,function(n,e){return F(n)&&!F(e)?1:F(e)&&!F(n)?-1:r[e]-r[n]})},e.reset=n,n(),e.get=function(){return t},e.freq=function(){return r},e}();fe.DEFMETHOD("scope_warnings",function(n){n=c(n,{undeclared:!1,unreferenced:!0,assign_to_global:!0,func_arguments:!0,nested_defuns:!0,eval:!0});var e=new E(function(t){if(n.undeclared&&t instanceof st&&t.undeclared()&&W.warn("Undeclared symbol: {name} [{file}:{line},{col}]",{name:t.name,file:t.start.file,line:t.start.line,col:t.start.col}),n.assign_to_global){var r=null;t instanceof Le&&t.left instanceof st?r=t.left:t instanceof ue&&t.init instanceof st&&(r=t.init),r&&(r.undeclared()||r.global()&&r.scope!==r.definition().scope)&&W.warn("{msg}: {name} [{file}:{line},{col}]",{msg:r.undeclared()?"Accidental global?":"Assignment to global",name:r.name,file:r.start.file,line:r.start.line,col:r.start.col})}n.eval&&t instanceof st&&t.undeclared()&&"eval"==t.name&&W.warn("Eval is used [{file}:{line},{col}]",t.start),n.unreferenced&&(t instanceof nt||t instanceof ut)&&t.unreferenced()&&W.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]",{type:t instanceof ut?"Label":"Symbol",name:t.name,file:t.start.file,line:t.start.line,col:t.start.col}),n.func_arguments&&t instanceof le&&t.uses_arguments&&W.warn("arguments used in function {name} [{file}:{line},{col}]",{name:t.name?t.name.name:"anonymous",file:t.start.file,line:t.start.line,col:t.start.col}),n.nested_defuns&&t instanceof he&&!(e.parent()instanceof ce)&&W.warn('Function {name} declared in nested statement "{type}" [{file}:{line},{col}]',{name:t.name.name,type:e.parent().TYPE,file:t.start.file,line:t.start.line,col:t.start.col})});this.walk(e)}),function(){function n(n,e){n.DEFMETHOD("_codegen",e)}function e(n,e){n.DEFMETHOD("needs_parens",e)}function t(n){var e=n.parent();return e instanceof Pe?!0:e instanceof Ue&&!(e instanceof Le)?!0:e instanceof Me&&e.expression===this?!0:e instanceof Ve&&e.condition===this?!0:e instanceof qe&&e.expression===this?!0:void 0}function r(n,e,t){var r=n.length-1;n.forEach(function(n,i){n instanceof Q||(t.indent(),n.print(t),i==r&&e||(t.newline(),e&&t.newline()))})}function i(n,e){n.length>0?e.with_block(function(){r(n,!1,e)}):e.print("{}")}function o(n,e){if(e.option("bracketize"))return void h(n.body,e);if(!n.body)return e.force_semicolon();if(n.body instanceof ie&&!e.option("screw_ie8"))return void h(n.body,e);for(var t=n.body;;)if(t instanceof we){if(!t.alternative)return void h(n.body,e);t=t.alternative}else{if(!(t instanceof ne))break;t=t.body}s(n.body,e)}function a(n,e,t){if(t)try{n.walk(new E(function(n){if(n instanceof Ue&&"in"==n.operator)throw e})),n.print(e)}catch(r){if(r!==e)throw r;n.print(e,!0)}else n.print(e)}function u(n){return[92,47,46,43,42,63,40,41,91,93,123,125,36,94,58,124,33,10,13,0,65279,8232,8233].indexOf(n)<0}function s(n,e){e.option("bracketize")?!n||n instanceof Q?e.print("{}"):n instanceof Z?n.print(e):e.with_block(function(){e.indent(),n.print(e),e.newline()}):!n||n instanceof Q?e.force_semicolon():n.print(e)}function c(n){for(var e=n.stack(),t=e.length,r=e[--t],i=e[--t];t>0;){if(i instanceof Y&&i.body===r)return!0;if(!(i instanceof Re&&i.car===r||i instanceof Me&&i.expression===r&&!(i instanceof Ne)||i instanceof He&&i.expression===r||i instanceof ze&&i.expression===r||i instanceof Ve&&i.condition===r||i instanceof Ue&&i.left===r||i instanceof Ie&&i.expression===r))return!1;r=i,i=e[--t]}}function f(n,e){return 0==n.args.length&&!e.option("beautify")}function p(n){for(var e=n[0],t=e.length,r=1;r<n.length;++r)n[r].length<t&&(e=n[r],t=e.length);return e}function d(n){var e,t=n.toString(10),r=[t.replace(/^0\./,".").replace("e+","e")];return Math.floor(n)===n?(n>=0?r.push("0x"+n.toString(16).toLowerCase(),"0"+n.toString(8)):r.push("-0x"+(-n).toString(16).toLowerCase(),"-0"+(-n).toString(8)),(e=/^(.*?)(0+)$/.exec(n))&&r.push(e[1]+"e"+e[2].length)):(e=/^0?\.(0+)(.*)$/.exec(n))&&r.push(e[2]+"e-"+(e[1].length+e[2].length),t.substr(t.indexOf("."))),p(r)}function h(n,e){return n instanceof Z?void n.print(e):void e.with_block(function(){e.indent(),n.print(e),e.newline()})}function _(n,e){n.DEFMETHOD("add_source_map",function(n){e(this,n)})}function m(n,e){e.add_mapping(n.start)}W.DEFMETHOD("print",function(n,e){function t(){r.add_comments(n),r.add_source_map(n),i(r,n)}var r=this,i=r._codegen;n.push_node(r),e||r.needs_parens(n)?n.with_parens(t):t(),n.pop_node()}),W.DEFMETHOD("print_to_string",function(n){var e=j(n);return this.print(e),e.get()}),W.DEFMETHOD("add_comments",function(n){var e=n.option("comments"),t=this;if(e){var r=t.start;if(r&&!r._comments_dumped){r._comments_dumped=!0;var i=r.comments_before||[];t instanceof me&&t.value&&t.value.walk(new E(function(n){return n.start&&n.start.comments_before&&(i=i.concat(n.start.comments_before),n.start.comments_before=[]),n instanceof de||n instanceof We||n instanceof Ye?!0:void 0
+})),e.test?i=i.filter(function(n){return e.test(n.value)}):"function"==typeof e&&(i=i.filter(function(n){return e(t,n)})),i.forEach(function(e){/comment[134]/.test(e.type)?(n.print("//"+e.value+"\n"),n.indent()):"comment2"==e.type&&(n.print("/*"+e.value+"*/"),r.nlb?(n.print("\n"),n.indent()):n.space())})}}}),e(W,function(){return!1}),e(de,function(n){return c(n)}),e(Ye,function(n){return c(n)}),e(Pe,function(n){var e=n.parent();return e instanceof qe&&e.expression===this}),e(Re,function(n){var e=n.parent();return e instanceof Me||e instanceof Pe||e instanceof Ue||e instanceof Oe||e instanceof qe||e instanceof We||e instanceof Xe||e instanceof Ve}),e(Ue,function(n){var e=n.parent();if(e instanceof Me&&e.expression===this)return!0;if(e instanceof Pe)return!0;if(e instanceof qe&&e.expression===this)return!0;if(e instanceof Ue){var t=e.operator,r=It[t],i=this.operator,o=It[i];if(r>o||r==o&&this===e.right)return!0}}),e(qe,function(n){var e=n.parent();if(e instanceof Ne&&e.expression===this)try{this.walk(new E(function(n){if(n instanceof Me)throw e}))}catch(t){if(t!==e)throw t;return!0}}),e(Me,function(n){var e,t=n.parent();return t instanceof Ne&&t.expression===this?!0:this.expression instanceof de&&t instanceof qe&&t.expression===this&&(e=n.parent(1))instanceof Le&&e.left===t}),e(Ne,function(n){var e=n.parent();return f(this,n)&&(e instanceof qe||e instanceof Me&&e.expression===this)?!0:void 0}),e(dt,function(n){var e=n.parent();return this.getValue()<0&&e instanceof qe&&e.expression===this?!0:void 0}),e(vt,function(n){var e=n.parent();return e instanceof qe&&e.expression===this?!0:void 0}),e(Le,t),e(Ve,t),n(G,function(n,e){e.print_string(n.value),e.semicolon()}),n(X,function(n,e){e.print("debugger"),e.semicolon()}),ne.DEFMETHOD("_do_print_body",function(n){s(this.body,n)}),n(Y,function(n,e){n.body.print(e),e.semicolon()}),n(fe,function(n,e){r(n.body,!0,e),e.print("")}),n(ee,function(n,e){n.label.print(e),e.colon(),n.body.print(e)}),n(K,function(n,e){n.body.print(e),e.semicolon()}),n(Z,function(n,e){i(n.body,e)}),n(Q,function(n,e){e.semicolon()}),n(ie,function(n,e){e.print("do"),e.space(),n._do_print_body(e),e.space(),e.print("while"),e.space(),e.with_parens(function(){n.condition.print(e)}),e.semicolon()}),n(oe,function(n,e){e.print("while"),e.space(),e.with_parens(function(){n.condition.print(e)}),e.space(),n._do_print_body(e)}),n(ae,function(n,e){e.print("for"),e.space(),e.with_parens(function(){!n.init||n.init instanceof Q?e.print(";"):(n.init instanceof Be?n.init.print(e):a(n.init,e,!0),e.print(";"),e.space()),n.condition?(n.condition.print(e),e.print(";"),e.space()):e.print(";"),n.step&&n.step.print(e)}),e.space(),n._do_print_body(e)}),n(ue,function(n,e){e.print("for"),e.space(),e.with_parens(function(){n.init.print(e),e.space(),e.print("in"),e.space(),n.object.print(e)}),e.space(),n._do_print_body(e)}),n(se,function(n,e){e.print("with"),e.space(),e.with_parens(function(){n.expression.print(e)}),e.space(),n._do_print_body(e)}),le.DEFMETHOD("_do_print",function(n,e){var t=this;e||n.print("function"),t.name&&(n.space(),t.name.print(n)),n.with_parens(function(){t.argnames.forEach(function(e,t){t&&n.comma(),e.print(n)})}),n.space(),i(t.body,n)}),n(le,function(n,e){n._do_print(e)}),me.DEFMETHOD("_do_print",function(n,e){n.print(e),this.value&&(n.space(),this.value.print(n)),n.semicolon()}),n(ve,function(n,e){n._do_print(e,"return")}),n(ge,function(n,e){n._do_print(e,"throw")}),be.DEFMETHOD("_do_print",function(n,e){n.print(e),this.label&&(n.space(),this.label.print(n)),n.semicolon()}),n(ye,function(n,e){n._do_print(e,"break")}),n(Ae,function(n,e){n._do_print(e,"continue")}),n(we,function(n,e){e.print("if"),e.space(),e.with_parens(function(){n.condition.print(e)}),e.space(),n.alternative?(o(n,e),e.space(),e.print("else"),e.space(),s(n.alternative,e)):n._do_print_body(e)}),n(Ee,function(n,e){e.print("switch"),e.space(),e.with_parens(function(){n.expression.print(e)}),e.space(),n.body.length>0?e.with_block(function(){n.body.forEach(function(n,t){t&&e.newline(),e.indent(!0),n.print(e)})}):e.print("{}")}),De.DEFMETHOD("_do_print_body",function(n){this.body.length>0&&(n.newline(),this.body.forEach(function(e){n.indent(),e.print(n),n.newline()}))}),n(Fe,function(n,e){e.print("default:"),n._do_print_body(e)}),n(Se,function(n,e){e.print("case"),e.space(),n.expression.print(e),e.print(":"),n._do_print_body(e)}),n(Ce,function(n,e){e.print("try"),e.space(),i(n.body,e),n.bcatch&&(e.space(),n.bcatch.print(e)),n.bfinally&&(e.space(),n.bfinally.print(e))}),n(ke,function(n,e){e.print("catch"),e.space(),e.with_parens(function(){n.argname.print(e)}),e.space(),i(n.body,e)}),n(xe,function(n,e){e.print("finally"),e.space(),i(n.body,e)}),Be.DEFMETHOD("_do_print",function(n,e){n.print(e),n.space(),this.definitions.forEach(function(e,t){t&&n.comma(),e.print(n)});var t=n.parent(),r=t instanceof ae||t instanceof ue,i=r&&t.init===this;i||n.semicolon()}),n(Te,function(n,e){n._do_print(e,"var")}),n($e,function(n,e){n._do_print(e,"const")}),n(Oe,function(n,e){if(n.name.print(e),n.value){e.space(),e.print("="),e.space();var t=e.parent(1),r=t instanceof ae||t instanceof ue;a(n.value,e,r)}}),n(Me,function(n,e){n.expression.print(e),n instanceof Ne&&f(n,e)||e.with_parens(function(){n.args.forEach(function(n,t){t&&e.comma(),n.print(e)})})}),n(Ne,function(n,e){e.print("new"),e.space(),Me.prototype._codegen(n,e)}),Re.DEFMETHOD("_do_print",function(n){this.car.print(n),this.cdr&&(n.comma(),n.should_break()&&(n.newline(),n.indent()),this.cdr.print(n))}),n(Re,function(n,e){n._do_print(e)}),n(He,function(n,e){var t=n.expression;t.print(e),t instanceof dt&&t.getValue()>=0&&(/[xa-f.]/i.test(e.last())||e.print(".")),e.print("."),e.add_mapping(n.end),e.print_name(n.property)}),n(ze,function(n,e){n.expression.print(e),e.print("["),n.property.print(e),e.print("]")}),n(je,function(n,e){var t=n.operator;e.print(t),(/^[a-z]/i.test(t)||/[+-]$/.test(t)&&n.expression instanceof je&&/^[+-]/.test(n.expression.operator))&&e.space(),n.expression.print(e)}),n(Ie,function(n,e){n.expression.print(e),e.print(n.operator)}),n(Ue,function(n,e){n.left.print(e),e.space(),e.print(n.operator),"<"==n.operator&&n.right instanceof je&&"!"==n.right.operator&&n.right.expression instanceof je&&"--"==n.right.expression.operator?e.print(" "):e.space(),n.right.print(e)}),n(Ve,function(n,e){n.condition.print(e),e.space(),e.print("?"),e.space(),n.consequent.print(e),e.space(),e.colon(),n.alternative.print(e)}),n(We,function(n,e){e.with_square(function(){var t=n.elements,r=t.length;r>0&&e.space(),t.forEach(function(n,t){t&&e.comma(),n.print(e),t===r-1&&n instanceof bt&&e.comma()}),r>0&&e.space()})}),n(Ye,function(n,e){n.properties.length>0?e.with_block(function(){n.properties.forEach(function(n,t){t&&(e.print(","),e.newline()),e.indent(),n.print(e)}),e.newline()}):e.print("{}")}),n(Ge,function(n,e){var t=n.key;e.option("quote_keys")?e.print_string(t+""):("number"==typeof t||!e.option("beautify")&&+t+""==t)&&parseFloat(t)>=0?e.print(d(t)):(St(t)?e.option("screw_ie8"):$(t))?e.print_name(t):e.print_string(t),e.colon(),n.value.print(e)}),n(Ke,function(n,e){e.print("set"),e.space(),n.key.print(e),n.value._do_print(e,!0)}),n(Je,function(n,e){e.print("get"),e.space(),n.key.print(e),n.value._do_print(e,!0)}),n(Ze,function(n,e){var t=n.definition();e.print_name(t?t.mangled_name||t.name:n.name)}),n(gt,function(n,e){e.print("void 0")}),n(bt,l),n(yt,function(n,e){e.print("1/0")}),n(vt,function(n,e){e.print("0/0")}),n(ft,function(n,e){e.print("this")}),n(lt,function(n,e){e.print(n.getValue())}),n(pt,function(n,e){e.print_string(n.getValue())}),n(dt,function(n,e){e.print(d(n.getValue()))}),n(ht,function(n,e){var t=n.getValue().toString();e.option("ascii_only")?t=e.to_ascii(t):e.option("unescape_regexps")&&(t=t.split("\\\\").map(function(n){return n.replace(/\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g,function(n){var e=parseInt(n.substr(2),16);return u(e)?String.fromCharCode(e):n})}).join("\\\\")),e.print(t);var r=e.parent();r instanceof Ue&&/^in/.test(r.operator)&&r.left===n&&e.print(" ")}),_(W,l),_(G,m),_(X,m),_(Ze,m),_(_e,m),_(ne,m),_(ee,l),_(le,m),_(Ee,m),_(De,m),_(Z,m),_(fe,l),_(Ne,m),_(Ce,m),_(ke,m),_(xe,m),_(Be,m),_(lt,m),_(Xe,function(n,e){e.add_mapping(n.start,n.key)})}(),I.prototype=new z,f(I.prototype,{option:function(n){return this.options[n]},warn:function(){this.options.warnings&&W.warn.apply(W,arguments)},before:function(n,e){if(n._squeezed)return n;var t=!1;return n instanceof ce&&(n=n.hoist_declarations(this),t=!0),e(n,this),n=n.optimize(this),t&&n instanceof ce&&(n.drop_unused(this),e(n,this)),n._squeezed=!0,n}}),function(){function n(n,e){n.DEFMETHOD("optimize",function(n){var t=this;if(t._optimized)return t;var r=e(t,n);return r._optimized=!0,r===t?r:r.transform(n)})}function e(n,e,t){return t||(t={}),e&&(t.start||(t.start=e.start),t.end||(t.end=e.end)),new n(t)}function t(n,t,r){if(t instanceof W)return t.transform(n);switch(typeof t){case"string":return e(pt,r,{value:t}).optimize(n);case"number":return e(isNaN(t)?vt:dt,r,{value:t}).optimize(n);case"boolean":return e(t?Et:wt,r).optimize(n);case"undefined":return e(gt,r).optimize(n);default:if(null===t)return e(mt,r).optimize(n);if(t instanceof RegExp)return e(ht,r).optimize(n);throw new Error(d("Can't handle constant of type: {type}",{type:typeof t}))}}function r(n){if(null===n)return[];if(n instanceof Z)return n.body;if(n instanceof Q)return[];if(n instanceof Y)return[n];throw new Error("Can't convert thing to statement array")}function i(n){return null===n?!0:n instanceof Q?!0:n instanceof Z?0==n.body.length:!1}function u(n){return n instanceof Ee?n:(n instanceof ae||n instanceof ue||n instanceof re)&&n.body instanceof Z?n.body:n}function s(n,t){function i(n){function r(n,t){return e(K,n,{body:e(Le,n,{operator:"=",left:e(He,t,{expression:e(st,t,t),property:"$inject"}),right:e(We,n,{elements:n.argnames.map(function(n){return e(pt,n,{value:n.name})})})})})}return n.reduce(function(n,e){n.push(e);var i=e.start,o=i.comments_before;if(o&&o.length>0){var a=o.pop();/@ngInject/.test(a.value)&&(e instanceof he?n.push(r(e,e.name)):e instanceof Be?e.definitions.forEach(function(e){e.value&&e.value instanceof le&&n.push(r(e.value,e.name))}):t.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]",i))}return n},[])}function o(n){var e=[];return n.reduce(function(n,t){return t instanceof Z?(_=!0,n.push.apply(n,o(t.body))):t instanceof Q?_=!0:t instanceof G?e.indexOf(t.value)<0?(n.push(t),e.push(t.value)):_=!0:n.push(t),n},[])}function a(n,t){var i=t.self(),o=i instanceof le,a=[];n:for(var s=n.length;--s>=0;){var c=n[s];switch(!0){case o&&c instanceof ve&&!c.value&&0==a.length:_=!0;continue n;case c instanceof we:if(c.body instanceof ve){if((o&&0==a.length||a[0]instanceof ve&&!a[0].value)&&!c.body.value&&!c.alternative){_=!0;var f=e(K,c.condition,{body:c.condition});a.unshift(f);continue n}if(a[0]instanceof ve&&c.body.value&&a[0].value&&!c.alternative){_=!0,c=c.clone(),c.alternative=a[0],a[0]=c.transform(t);continue n}if((0==a.length||a[0]instanceof ve)&&c.body.value&&!c.alternative&&o){_=!0,c=c.clone(),c.alternative=a[0]||e(ve,c,{value:e(gt,c)}),a[0]=c.transform(t);continue n}if(!c.body.value&&o){_=!0,c=c.clone(),c.condition=c.condition.negate(t),c.body=e(Z,c,{body:r(c.alternative).concat(a)}),c.alternative=null,a=[c.transform(t)];continue n}if(1==a.length&&o&&a[0]instanceof K&&(!c.alternative||c.alternative instanceof K)){_=!0,a.push(e(ve,a[0],{value:e(gt,a[0])}).transform(t)),a=r(c.alternative).concat(a),a.unshift(c);continue n}}var l=m(c.body),p=l instanceof be?t.loopcontrol_target(l.label):null;if(l&&(l instanceof ve&&!l.value&&o||l instanceof Ae&&i===u(p)||l instanceof ye&&p instanceof Z&&i===p)){l.label&&h(l.label.thedef.references,l),_=!0;var d=r(c.body).slice(0,-1);c=c.clone(),c.condition=c.condition.negate(t),c.body=e(Z,c,{body:r(c.alternative).concat(a)}),c.alternative=e(Z,c,{body:d}),a=[c.transform(t)];continue n}var l=m(c.alternative),p=l instanceof be?t.loopcontrol_target(l.label):null;if(l&&(l instanceof ve&&!l.value&&o||l instanceof Ae&&i===u(p)||l instanceof ye&&p instanceof Z&&i===p)){l.label&&h(l.label.thedef.references,l),_=!0,c=c.clone(),c.body=e(Z,c.body,{body:r(c.body).concat(a)}),c.alternative=e(Z,c.alternative,{body:r(c.alternative).slice(0,-1)}),a=[c.transform(t)];continue n}a.unshift(c);break;default:a.unshift(c)}}return a}function s(n,e){var t=!1,r=n.length,i=e.self();return n=n.reduce(function(n,r){if(t)c(e,r,n);else{if(r instanceof be){var o=e.loopcontrol_target(r.label);r instanceof ye&&o instanceof Z&&u(o)===i||r instanceof Ae&&u(o)===i?r.label&&h(r.label.thedef.references,r):n.push(r)}else n.push(r);m(r)&&(t=!0)}return n},[]),_=n.length!=r,n}function f(n,t){function r(){i=Re.from_array(i),i&&o.push(e(K,i,{body:i})),i=[]}if(n.length<2)return n;var i=[],o=[];return n.forEach(function(n){n instanceof K?i.push(n.body):(r(),o.push(n))}),r(),o=l(o,t),_=o.length!=n.length,o}function l(n,t){function r(n){i.pop();var e=o.body;return e instanceof Re?e.add(n):e=Re.cons(e,n),e.transform(t)}var i=[],o=null;return n.forEach(function(n){if(o)if(n instanceof ae){var t={};try{o.body.walk(new E(function(n){if(n instanceof Ue&&"in"==n.operator)throw t})),!n.init||n.init instanceof Be?n.init||(n.init=o.body,i.pop()):n.init=r(n.init)}catch(a){if(a!==t)throw a}}else n instanceof we?n.condition=r(n.condition):n instanceof se?n.expression=r(n.expression):n instanceof me&&n.value?n.value=r(n.value):n instanceof me?n.value=r(e(gt,n)):n instanceof Ee&&(n.expression=r(n.expression));i.push(n),o=n instanceof K?n:null}),i}function p(n){var e=null;return n.reduce(function(n,t){return t instanceof Be&&e&&e.TYPE==t.TYPE?(e.definitions=e.definitions.concat(t.definitions),_=!0):t instanceof ae&&e instanceof Be&&(!t.init||t.init.TYPE==e.TYPE)?(_=!0,n.pop(),t.init?t.init.definitions=e.definitions.concat(t.init.definitions):t.init=e,n.push(t),e=t):(e=t,n.push(t)),n},[])}function d(n){n.forEach(function(n){n instanceof K&&(n.body=function t(n){return n.transform(new z(function(n){if(n instanceof Me&&n.expression instanceof de)return e(je,n,{operator:"!",expression:n});if(n instanceof Me)n.expression=t(n.expression);else if(n instanceof Re)n.car=t(n.car);else if(n instanceof Ve){var r=t(n.condition);if(r!==n.condition){n.condition=r;var i=n.consequent;n.consequent=n.alternative,n.alternative=i}}return n}))}(n.body))})}var _;do _=!1,t.option("angular")&&(n=i(n)),n=o(n),t.option("dead_code")&&(n=s(n,t)),t.option("if_return")&&(n=a(n,t)),t.option("sequences")&&(n=f(n,t)),t.option("join_vars")&&(n=p(n,t));while(_);return t.option("negate_iife")&&d(n,t),n}function c(n,e,t){n.warn("Dropping unreachable code [{file}:{line},{col}]",e.start),e.walk(new E(function(e){return e instanceof Be?(n.warn("Declarations in unreachable code! [{file}:{line},{col}]",e.start),e.remove_initializers(),t.push(e),!0):e instanceof he?(t.push(e),!0):e instanceof ce?!0:void 0}))}function f(n,e){return n.print_to_string().length>e.print_to_string().length?e:n}function m(n){return n&&n.aborts()}function v(n,t){function i(i){i=r(i),n.body instanceof Z?(n.body=n.body.clone(),n.body.body=i.concat(n.body.body.slice(1)),n.body=n.body.transform(t)):n.body=e(Z,n.body,{body:i}).transform(t),v(n,t)}var o=n.body instanceof Z?n.body.body[0]:n.body;o instanceof we&&(o.body instanceof ye&&t.loopcontrol_target(o.body.label)===n?(n.condition=n.condition?e(Ue,n.condition,{left:n.condition,operator:"&&",right:o.condition.negate(t)}):o.condition.negate(t),i(o.alternative)):o.alternative instanceof ye&&t.loopcontrol_target(o.alternative.label)===n&&(n.condition=n.condition?e(Ue,n.condition,{left:n.condition,operator:"&&",right:o.condition}):o.condition,i(o.body)))}function A(n,e){var t=e.option("pure_getters");e.options.pure_getters=!1;var r=n.has_side_effects(e);return e.options.pure_getters=t,r}function w(n,t){return t.option("booleans")&&t.in_boolean_context()?e(Et,n):n}n(W,function(n){return n}),W.DEFMETHOD("equivalent_to",function(n){return this.print_to_string()==n.print_to_string()}),function(n){var e=["!","delete"],t=["in","instanceof","==","!=","===","!==","<","<=",">=",">"];n(W,function(){return!1}),n(je,function(){return o(this.operator,e)}),n(Ue,function(){return o(this.operator,t)||("&&"==this.operator||"||"==this.operator)&&this.left.is_boolean()&&this.right.is_boolean()}),n(Ve,function(){return this.consequent.is_boolean()&&this.alternative.is_boolean()}),n(Le,function(){return"="==this.operator&&this.right.is_boolean()}),n(Re,function(){return this.cdr.is_boolean()}),n(Et,function(){return!0}),n(wt,function(){return!0})}(function(n,e){n.DEFMETHOD("is_boolean",e)}),function(n){n(W,function(){return!1}),n(pt,function(){return!0}),n(je,function(){return"typeof"==this.operator}),n(Ue,function(n){return"+"==this.operator&&(this.left.is_string(n)||this.right.is_string(n))}),n(Le,function(n){return("="==this.operator||"+="==this.operator)&&this.right.is_string(n)}),n(Re,function(n){return this.cdr.is_string(n)}),n(Ve,function(n){return this.consequent.is_string(n)&&this.alternative.is_string(n)}),n(Me,function(n){return n.option("unsafe")&&this.expression instanceof st&&"String"==this.expression.name&&this.expression.undeclared()})}(function(n,e){n.DEFMETHOD("is_string",e)}),function(n){function e(n,e){if(!e)throw new Error("Compressor must be passed");return n._eval(e)}W.DEFMETHOD("evaluate",function(e){if(!e.option("evaluate"))return[this];try{var r=this._eval(e);return[f(t(e,r,this),this),r]}catch(i){if(i!==n)throw i;return[this]}}),n(Y,function(){throw new Error(d("Cannot evaluate a statement [{file}:{line},{col}]",this.start))}),n(de,function(){throw n}),n(W,function(){throw n}),n(lt,function(){return this.getValue()}),n(je,function(t){var r=this.expression;switch(this.operator){case"!":return!e(r,t);case"typeof":if(r instanceof de)return"function";if(r=e(r,t),r instanceof RegExp)throw n;return typeof r;case"void":return void e(r,t);case"~":return~e(r,t);case"-":if(r=e(r,t),0===r)throw n;return-r;case"+":return+e(r,t)}throw n}),n(Ue,function(t){var r=this.left,i=this.right;switch(this.operator){case"&&":return e(r,t)&&e(i,t);case"||":return e(r,t)||e(i,t);case"|":return e(r,t)|e(i,t);case"&":return e(r,t)&e(i,t);case"^":return e(r,t)^e(i,t);case"+":return e(r,t)+e(i,t);case"*":return e(r,t)*e(i,t);case"/":return e(r,t)/e(i,t);case"%":return e(r,t)%e(i,t);case"-":return e(r,t)-e(i,t);case"<<":return e(r,t)<<e(i,t);case">>":return e(r,t)>>e(i,t);case">>>":return e(r,t)>>>e(i,t);case"==":return e(r,t)==e(i,t);case"===":return e(r,t)===e(i,t);case"!=":return e(r,t)!=e(i,t);case"!==":return e(r,t)!==e(i,t);case"<":return e(r,t)<e(i,t);case"<=":return e(r,t)<=e(i,t);case">":return e(r,t)>e(i,t);case">=":return e(r,t)>=e(i,t);case"in":return e(r,t)in e(i,t);case"instanceof":return e(r,t)instanceof e(i,t)}throw n}),n(Ve,function(n){return e(this.condition,n)?e(this.consequent,n):e(this.alternative,n)}),n(st,function(t){var r=this.definition();if(r&&r.constant&&r.init)return e(r.init,t);throw n}),n(He,function(t){if(t.option("unsafe")&&"length"==this.property){var r=e(this.expression,t);if("string"==typeof r)return r.length}throw n})}(function(n,e){n.DEFMETHOD("_eval",e)}),function(n){function t(n){return e(je,n,{operator:"!",expression:n})}n(W,function(){return t(this)}),n(Y,function(){throw new Error("Cannot negate a statement")}),n(de,function(){return t(this)}),n(je,function(){return"!"==this.operator?this.expression:t(this)}),n(Re,function(n){var e=this.clone();return e.cdr=e.cdr.negate(n),e}),n(Ve,function(n){var e=this.clone();return e.consequent=e.consequent.negate(n),e.alternative=e.alternative.negate(n),f(t(this),e)}),n(Ue,function(n){var e=this.clone(),r=this.operator;if(n.option("unsafe_comps"))switch(r){case"<=":return e.operator=">",e;case"<":return e.operator=">=",e;case">=":return e.operator="<",e;case">":return e.operator="<=",e}switch(r){case"==":return e.operator="!=",e;case"!=":return e.operator="==",e;case"===":return e.operator="!==",e;case"!==":return e.operator="===",e;case"&&":return e.operator="||",e.left=e.left.negate(n),e.right=e.right.negate(n),f(t(this),e);case"||":return e.operator="&&",e.left=e.left.negate(n),e.right=e.right.negate(n),f(t(this),e)}return t(this)})}(function(n,e){n.DEFMETHOD("negate",function(n){return e.call(this,n)})}),function(n){n(W,function(){return!0}),n(Q,function(){return!1}),n(lt,function(){return!1}),n(ft,function(){return!1}),n(Me,function(n){var e=n.option("pure_funcs");return e?e.indexOf(this.expression.print_to_string())<0:!0}),n(J,function(n){for(var e=this.body.length;--e>=0;)if(this.body[e].has_side_effects(n))return!0;return!1}),n(K,function(n){return this.body.has_side_effects(n)}),n(he,function(){return!0}),n(de,function(){return!1}),n(Ue,function(n){return this.left.has_side_effects(n)||this.right.has_side_effects(n)}),n(Le,function(){return!0}),n(Ve,function(n){return this.condition.has_side_effects(n)||this.consequent.has_side_effects(n)||this.alternative.has_side_effects(n)}),n(Pe,function(n){return"delete"==this.operator||"++"==this.operator||"--"==this.operator||this.expression.has_side_effects(n)}),n(st,function(){return!1}),n(Ye,function(n){for(var e=this.properties.length;--e>=0;)if(this.properties[e].has_side_effects(n))return!0;return!1}),n(Xe,function(n){return this.value.has_side_effects(n)}),n(We,function(n){for(var e=this.elements.length;--e>=0;)if(this.elements[e].has_side_effects(n))return!0;return!1}),n(He,function(n){return n.option("pure_getters")?this.expression.has_side_effects(n):!0}),n(ze,function(n){return n.option("pure_getters")?this.expression.has_side_effects(n)||this.property.has_side_effects(n):!0}),n(qe,function(n){return!n.option("pure_getters")}),n(Re,function(n){return this.car.has_side_effects(n)||this.cdr.has_side_effects(n)})}(function(n,e){n.DEFMETHOD("has_side_effects",e)}),function(n){function e(){var n=this.body.length;return n>0&&m(this.body[n-1])}n(Y,function(){return null}),n(_e,function(){return this}),n(Z,e),n(De,e),n(we,function(){return this.alternative&&m(this.body)&&m(this.alternative)})}(function(n,e){n.DEFMETHOD("aborts",e)}),n(G,function(n){return n.scope.has_directive(n.value)!==n.scope?e(Q,n):n}),n(X,function(n,t){return t.option("drop_debugger")?e(Q,n):n}),n(ee,function(n,t){return n.body instanceof ye&&t.loopcontrol_target(n.body.label)===n.body?e(Q,n):0==n.label.references.length?n.body:n}),n(J,function(n,e){return n.body=s(n.body,e),n}),n(Z,function(n,t){switch(n.body=s(n.body,t),n.body.length){case 1:return n.body[0];case 0:return e(Q,n)}return n}),ce.DEFMETHOD("drop_unused",function(n){var t=this;if(n.option("unused")&&!(t instanceof fe)&&!t.uses_eval){var r=[],i=new y,a=this,u=new E(function(e,o){if(e!==t){if(e instanceof he)return i.add(e.name.name,e),!0;if(e instanceof Be&&a===t)return e.definitions.forEach(function(e){e.value&&(i.add(e.name.name,e.value),e.value.has_side_effects(n)&&e.value.walk(u))}),!0;if(e instanceof st)return p(r,e.definition()),!0;if(e instanceof ce){var s=a;return a=e,o(),a=s,!0}}});t.walk(u);for(var s=0;s<r.length;++s)r[s].orig.forEach(function(n){var e=i.get(n.name);e&&e.forEach(function(n){var e=new E(function(n){n instanceof st&&p(r,n.definition())});n.walk(e)})});var c=new z(function(i,a,u){if(i instanceof le&&!(i instanceof pe)&&!n.option("keep_fargs"))for(var s=i.argnames,f=s.length;--f>=0;){var l=s[f];if(!l.unreferenced())break;s.pop(),n.warn("Dropping unused function argument {name} [{file}:{line},{col}]",{name:l.name,file:l.start.file,line:l.start.line,col:l.start.col})}if(i instanceof he&&i!==t)return o(i.name.definition(),r)?i:(n.warn("Dropping unused function {name} [{file}:{line},{col}]",{name:i.name.name,file:i.name.start.file,line:i.name.start.line,col:i.name.start.col}),e(Q,i));if(i instanceof Be&&!(c.parent()instanceof ue)){var p=i.definitions.filter(function(e){if(o(e.name.definition(),r))return!0;var t={name:e.name.name,file:e.name.start.file,line:e.name.start.line,col:e.name.start.col};return e.value&&e.value.has_side_effects(n)?(e._unused_side_effects=!0,n.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]",t),!0):(n.warn("Dropping unused variable {name} [{file}:{line},{col}]",t),!1)});p=_(p,function(n,e){return!n.value&&e.value?-1:!e.value&&n.value?1:0});for(var d=[],f=0;f<p.length;){var h=p[f];h._unused_side_effects?(d.push(h.value),p.splice(f,1)):(d.length>0&&(d.push(h.value),h.value=Re.from_array(d),d=[]),++f)}return d=d.length>0?e(Z,i,{body:[e(K,i,{body:Re.from_array(d)})]}):null,0!=p.length||d?0==p.length?d:(i.definitions=p,d&&(d.body.unshift(i),i=d),i):e(Q,i)}if(i instanceof ae&&(a(i,this),i.init instanceof Z)){var m=i.init.body.slice(0,-1);return i.init=i.init.body.slice(-1)[0].body,m.push(i),u?V.splice(m):e(Z,i,{body:m})}return i instanceof ce&&i!==t?i:void 0});t.transform(c)}}),ce.DEFMETHOD("hoist_declarations",function(n){var t=n.option("hoist_funs"),r=n.option("hoist_vars"),i=this;if(t||r){var o=[],u=[],s=new y,c=0,f=0;i.walk(new E(function(n){return n instanceof ce&&n!==i?!0:n instanceof Te?(++f,!0):void 0})),r=r&&f>1;var l=new z(function(n){if(n!==i){if(n instanceof G)return o.push(n),e(Q,n);if(n instanceof he&&t)return u.push(n),e(Q,n);if(n instanceof Te&&r){n.definitions.forEach(function(n){s.set(n.name.name,n),++c});var a=n.to_assignments(),f=l.parent();return f instanceof ue&&f.init===n?null==a?n.definitions[0].name:a:f instanceof ae&&f.init===n?a:a?e(K,n,{body:a}):e(Q,n)}if(n instanceof ce)return n}});if(i=i.transform(l),c>0){var p=[];if(s.each(function(n,e){i instanceof le&&a(function(e){return e.name==n.name.name},i.argnames)?s.del(e):(n=n.clone(),n.value=null,p.push(n),s.set(e,n))}),p.length>0){for(var d=0;d<i.body.length;){if(i.body[d]instanceof K){var _,m,v=i.body[d].body;if(v instanceof Le&&"="==v.operator&&(_=v.left)instanceof Ze&&s.has(_.name)){var g=s.get(_.name);if(g.value)break;g.value=v.right,h(p,g),p.push(g),i.body.splice(d,1);continue}if(v instanceof Re&&(m=v.car)instanceof Le&&"="==m.operator&&(_=m.left)instanceof Ze&&s.has(_.name)){var g=s.get(_.name);if(g.value)break;g.value=m.right,h(p,g),p.push(g),i.body[d].body=v.cdr;continue}}if(i.body[d]instanceof Q)i.body.splice(d,1);else{if(!(i.body[d]instanceof Z))break;var b=[d,1].concat(i.body[d].body);i.body.splice.apply(i.body,b)}}p=e(Te,i,{definitions:p}),u.push(p)}}i.body=o.concat(u,i.body)}return i}),n(K,function(n,t){return t.option("side_effects")&&!n.body.has_side_effects(t)?(t.warn("Dropping side-effect-free statement [{file}:{line},{col}]",n.start),e(Q,n)):n}),n(re,function(n,t){var r=n.condition.evaluate(t);if(n.condition=r[0],!t.option("loops"))return n;if(r.length>1){if(r[1])return e(ae,n,{body:n.body});if(n instanceof oe&&t.option("dead_code")){var i=[];return c(t,n.body,i),e(Z,n,{body:i})}}return n}),n(oe,function(n,t){return t.option("loops")?(n=re.prototype.optimize.call(n,t),n instanceof oe&&(v(n,t),n=e(ae,n,n).transform(t)),n):n}),n(ae,function(n,t){var r=n.condition;if(r&&(r=r.evaluate(t),n.condition=r[0]),!t.option("loops"))return n;if(r&&r.length>1&&!r[1]&&t.option("dead_code")){var i=[];return n.init instanceof Y?i.push(n.init):n.init&&i.push(e(K,n.init,{body:n.init})),c(t,n.body,i),e(Z,n,{body:i})}return v(n,t),n}),n(we,function(n,t){if(!t.option("conditionals"))return n;var r=n.condition.evaluate(t);if(n.condition=r[0],r.length>1)if(r[1]){if(t.warn("Condition always true [{file}:{line},{col}]",n.condition.start),t.option("dead_code")){var o=[];return n.alternative&&c(t,n.alternative,o),o.push(n.body),e(Z,n,{body:o}).transform(t)}}else if(t.warn("Condition always false [{file}:{line},{col}]",n.condition.start),t.option("dead_code")){var o=[];return c(t,n.body,o),n.alternative&&o.push(n.alternative),e(Z,n,{body:o}).transform(t)}i(n.alternative)&&(n.alternative=null);var a=n.condition.negate(t),u=f(n.condition,a)===a;if(n.alternative&&u){u=!1,n.condition=a;var s=n.body;n.body=n.alternative||e(Q),n.alternative=s}if(i(n.body)&&i(n.alternative))return e(K,n.condition,{body:n.condition}).transform(t);if(n.body instanceof K&&n.alternative instanceof K)return e(K,n,{body:e(Ve,n,{condition:n.condition,consequent:n.body.body,alternative:n.alternative.body})}).transform(t);if(i(n.alternative)&&n.body instanceof K)return u?e(K,n,{body:e(Ue,n,{operator:"||",left:a,right:n.body.body})}).transform(t):e(K,n,{body:e(Ue,n,{operator:"&&",left:n.condition,right:n.body.body})}).transform(t);if(n.body instanceof Q&&n.alternative&&n.alternative instanceof K)return e(K,n,{body:e(Ue,n,{operator:"||",left:n.condition,right:n.alternative.body})}).transform(t);if(n.body instanceof me&&n.alternative instanceof me&&n.body.TYPE==n.alternative.TYPE)return e(n.body.CTOR,n,{value:e(Ve,n,{condition:n.condition,consequent:n.body.value||e(gt,n.body).optimize(t),alternative:n.alternative.value||e(gt,n.alternative).optimize(t)})}).transform(t);if(n.body instanceof we&&!n.body.alternative&&!n.alternative&&(n.condition=e(Ue,n.condition,{operator:"&&",left:n.condition,right:n.body.condition}).transform(t),n.body=n.body.body),m(n.body)&&n.alternative){var l=n.alternative;return n.alternative=null,e(Z,n,{body:[n,l]}).transform(t)}if(m(n.alternative)){var p=n.body;return n.body=n.alternative,n.condition=u?a:n.condition.negate(t),n.alternative=null,e(Z,n,{body:[n,p]}).transform(t)}return n}),n(Ee,function(n,t){if(0==n.body.length&&t.option("conditionals"))return e(K,n,{body:n.expression}).transform(t);for(;;){var r=n.body[n.body.length-1];if(r){var i=r.body[r.body.length-1];if(i instanceof ye&&u(t.loopcontrol_target(i.label))===n&&r.body.pop(),r instanceof Fe&&0==r.body.length){n.body.pop();continue}}break}var o=n.expression.evaluate(t);n:if(2==o.length)try{if(n.expression=o[0],!t.option("dead_code"))break n;var a=o[1],s=!1,c=!1,f=!1,l=!1,p=!1,d=new z(function(r,i,o){if(r instanceof le||r instanceof K)return r;if(r instanceof Ee&&r===n)return r=r.clone(),i(r,this),p?r:e(Z,r,{body:r.body.reduce(function(n,e){return n.concat(e.body)},[])}).transform(t);if(r instanceof we||r instanceof Ce){var u=s;return s=!c,i(r,this),s=u,r}if(r instanceof ne||r instanceof Ee){var u=c;return c=!0,i(r,this),c=u,r}if(r instanceof ye&&this.loopcontrol_target(r.label)===n)return s?(p=!0,r):c?r:(l=!0,o?V.skip:e(Q,r));if(r instanceof De&&this.parent()===n){if(l)return V.skip;if(r instanceof Se){var d=r.expression.evaluate(t);if(d.length<2)throw n;return d[1]===a||f?(f=!0,m(r)&&(l=!0),i(r,this),r):V.skip}return i(r,this),r}});d.stack=t.stack.slice(),n=n.transform(d)}catch(h){if(h!==n)throw h}return n}),n(Se,function(n,e){return n.body=s(n.body,e),n}),n(Ce,function(n,e){return n.body=s(n.body,e),n}),Be.DEFMETHOD("remove_initializers",function(){this.definitions.forEach(function(n){n.value=null})}),Be.DEFMETHOD("to_assignments",function(){var n=this.definitions.reduce(function(n,t){if(t.value){var r=e(st,t.name,t.name);n.push(e(Le,t,{operator:"=",left:r,right:t.value}))}return n},[]);return 0==n.length?null:Re.from_array(n)}),n(Be,function(n){return 0==n.definitions.length?e(Q,n):n}),n(de,function(n,e){return n=le.prototype.optimize.call(n,e),e.option("unused")&&n.name&&n.name.unreferenced()&&(n.name=null),n}),n(Me,function(n,r){if(r.option("unsafe")){var i=n.expression;if(i instanceof st&&i.undeclared())switch(i.name){case"Array":if(1!=n.args.length)return e(We,n,{elements:n.args}).transform(r);break;case"Object":if(0==n.args.length)return e(Ye,n,{properties:[]});break;case"String":if(0==n.args.length)return e(pt,n,{value:""});if(n.args.length<=1)return e(Ue,n,{left:n.args[0],operator:"+",right:e(pt,n,{value:""})}).transform(r);break;case"Number":if(0==n.args.length)return e(dt,n,{value:0});if(1==n.args.length)return e(je,n,{expression:n.args[0],operator:"+"}).transform(r);case"Boolean":if(0==n.args.length)return e(wt,n);if(1==n.args.length)return e(je,n,{expression:e(je,null,{expression:n.args[0],operator:"!"}),operator:"!"}).transform(r);break;case"Function":if(b(n.args,function(n){return n instanceof pt}))try{var o="(function("+n.args.slice(0,-1).map(function(n){return n.value}).join(",")+"){"+n.args[n.args.length-1].value+"})()",a=H(o);
+a.figure_out_scope({screw_ie8:r.option("screw_ie8")});var u=new I(r.options);a=a.transform(u),a.figure_out_scope({screw_ie8:r.option("screw_ie8")}),a.mangle_names();var s;try{a.walk(new E(function(n){if(n instanceof le)throw s=n,a}))}catch(c){if(c!==a)throw c}var l=s.argnames.map(function(t,r){return e(pt,n.args[r],{value:t.print_to_string()})}),o=j();return Z.prototype._codegen.call(s,s,o),o=o.toString().replace(/^\{|\}$/g,""),l.push(e(pt,n.args[n.args.length-1],{value:o})),n.args=l,n}catch(c){if(!(c instanceof M))throw console.log(c),c;r.warn("Error parsing code passed to new Function [{file}:{line},{col}]",n.args[n.args.length-1].start),r.warn(c.toString())}}else{if(i instanceof He&&"toString"==i.property&&0==n.args.length)return e(Ue,n,{left:e(pt,n,{value:""}),operator:"+",right:i.expression}).transform(r);if(i instanceof He&&i.expression instanceof We&&"join"==i.property){var p=0==n.args.length?",":n.args[0].evaluate(r)[1];if(null!=p){var d=i.expression.elements.reduce(function(n,e){if(e=e.evaluate(r),0==n.length||1==e.length)n.push(e);else{var i=n[n.length-1];if(2==i.length){var o=""+i[1]+p+e[1];n[n.length-1]=[t(r,o,i[0]),o]}else n.push(e)}return n},[]);if(0==d.length)return e(pt,n,{value:""});if(1==d.length)return d[0][0];if(""==p){var h;return h=d[0][0]instanceof pt||d[1][0]instanceof pt?d.shift()[0]:e(pt,n,{value:""}),d.reduce(function(n,t){return e(Ue,t[0],{operator:"+",left:n,right:t[0]})},h).transform(r)}var _=n.clone();return _.expression=_.expression.clone(),_.expression.expression=_.expression.expression.clone(),_.expression.expression.elements=d.map(function(n){return n[0]}),f(n,_)}}}}return r.option("side_effects")&&n.expression instanceof de&&0==n.args.length&&!J.prototype.has_side_effects.call(n.expression,r)?e(gt,n).transform(r):r.option("drop_console")&&n.expression instanceof qe&&n.expression.expression instanceof st&&"console"==n.expression.expression.name&&n.expression.expression.undeclared()?e(gt,n).transform(r):n.evaluate(r)[0]}),n(Ne,function(n,t){if(t.option("unsafe")){var r=n.expression;if(r instanceof st&&r.undeclared())switch(r.name){case"Object":case"RegExp":case"Function":case"Error":case"Array":return e(Me,n,n).transform(t)}}return n}),n(Re,function(n,t){if(!t.option("side_effects"))return n;if(!n.car.has_side_effects(t)){var r;if(!(n.cdr instanceof st&&"eval"==n.cdr.name&&n.cdr.undeclared()&&(r=t.parent())instanceof Me&&r.expression===n))return n.cdr}if(t.option("cascade")){if(n.car instanceof Le&&!n.car.left.has_side_effects(t)){if(n.car.left.equivalent_to(n.cdr))return n.car;if(n.cdr instanceof Me&&n.cdr.expression.equivalent_to(n.car.left))return n.cdr.expression=n.car,n.cdr}if(!n.car.has_side_effects(t)&&!n.cdr.has_side_effects(t)&&n.car.equivalent_to(n.cdr))return n.car}return n.cdr instanceof je&&"void"==n.cdr.operator&&!n.cdr.expression.has_side_effects(t)?(n.cdr.operator=n.car,n.cdr):n.cdr instanceof gt?e(je,n,{operator:"void",expression:n.car}):n}),Pe.DEFMETHOD("lift_sequences",function(n){if(n.option("sequences")&&this.expression instanceof Re){var e=this.expression,t=e.to_array();return this.expression=t.pop(),t.push(this),e=Re.from_array(t).transform(n)}return this}),n(Ie,function(n,e){return n.lift_sequences(e)}),n(je,function(n,t){n=n.lift_sequences(t);var r=n.expression;if(t.option("booleans")&&t.in_boolean_context()){switch(n.operator){case"!":if(r instanceof je&&"!"==r.operator)return r.expression;break;case"typeof":return t.warn("Boolean expression always true [{file}:{line},{col}]",n.start),e(Et,n)}r instanceof Ue&&"!"==n.operator&&(n=f(n,r.negate(t)))}return n.evaluate(t)[0]}),Ue.DEFMETHOD("lift_sequences",function(n){if(n.option("sequences")){if(this.left instanceof Re){var e=this.left,t=e.to_array();return this.left=t.pop(),t.push(this),e=Re.from_array(t).transform(n)}if(this.right instanceof Re&&this instanceof Le&&!A(this.left,n)){var e=this.right,t=e.to_array();return this.right=t.pop(),t.push(this),e=Re.from_array(t).transform(n)}}return this});var D=g("== === != !== * & | ^");n(Ue,function(n,t){var r=t.has_directive("use asm")?l:function(e,r){if(r||!n.left.has_side_effects(t)&&!n.right.has_side_effects(t)){e&&(n.operator=e);var i=n.left;n.left=n.right,n.right=i}};if(D(n.operator)&&(n.right instanceof lt&&!(n.left instanceof lt)&&(n.left instanceof Ue&&It[n.left.operator]>=It[n.operator]||r(null,!0)),/^[!=]==?$/.test(n.operator))){if(n.left instanceof st&&n.right instanceof Ve){if(n.right.consequent instanceof st&&n.right.consequent.definition()===n.left.definition()){if(/^==/.test(n.operator))return n.right.condition;if(/^!=/.test(n.operator))return n.right.condition.negate(t)}if(n.right.alternative instanceof st&&n.right.alternative.definition()===n.left.definition()){if(/^==/.test(n.operator))return n.right.condition.negate(t);if(/^!=/.test(n.operator))return n.right.condition}}if(n.right instanceof st&&n.left instanceof Ve){if(n.left.consequent instanceof st&&n.left.consequent.definition()===n.right.definition()){if(/^==/.test(n.operator))return n.left.condition;if(/^!=/.test(n.operator))return n.left.condition.negate(t)}if(n.left.alternative instanceof st&&n.left.alternative.definition()===n.right.definition()){if(/^==/.test(n.operator))return n.left.condition.negate(t);if(/^!=/.test(n.operator))return n.left.condition}}}if(n=n.lift_sequences(t),t.option("comparisons"))switch(n.operator){case"===":case"!==":(n.left.is_string(t)&&n.right.is_string(t)||n.left.is_boolean()&&n.right.is_boolean())&&(n.operator=n.operator.substr(0,2));case"==":case"!=":n.left instanceof pt&&"undefined"==n.left.value&&n.right instanceof je&&"typeof"==n.right.operator&&t.option("unsafe")&&(n.right.expression instanceof st&&n.right.expression.undeclared()||(n.right=n.right.expression,n.left=e(gt,n.left).optimize(t),2==n.operator.length&&(n.operator+="=")))}if(t.option("booleans")&&t.in_boolean_context())switch(n.operator){case"&&":var i=n.left.evaluate(t),o=n.right.evaluate(t);if(i.length>1&&!i[1]||o.length>1&&!o[1])return t.warn("Boolean && always false [{file}:{line},{col}]",n.start),e(wt,n);if(i.length>1&&i[1])return o[0];if(o.length>1&&o[1])return i[0];break;case"||":var i=n.left.evaluate(t),o=n.right.evaluate(t);if(i.length>1&&i[1]||o.length>1&&o[1])return t.warn("Boolean || always true [{file}:{line},{col}]",n.start),e(Et,n);if(i.length>1&&!i[1])return o[0];if(o.length>1&&!o[1])return i[0];break;case"+":var i=n.left.evaluate(t),o=n.right.evaluate(t);if(i.length>1&&i[0]instanceof pt&&i[1]||o.length>1&&o[0]instanceof pt&&o[1])return t.warn("+ in boolean context always true [{file}:{line},{col}]",n.start),e(Et,n)}if(t.option("comparisons")){if(!(t.parent()instanceof Ue)||t.parent()instanceof Le){var a=e(je,n,{operator:"!",expression:n.negate(t)});n=f(n,a)}switch(n.operator){case"<":r(">");break;case"<=":r(">=")}}return"+"==n.operator&&n.right instanceof pt&&""===n.right.getValue()&&n.left instanceof Ue&&"+"==n.left.operator&&n.left.is_string(t)?n.left:(t.option("evaluate")&&"+"==n.operator&&(n.left instanceof lt&&n.right instanceof Ue&&"+"==n.right.operator&&n.right.left instanceof lt&&n.right.is_string(t)&&(n=e(Ue,n,{operator:"+",left:e(pt,null,{value:""+n.left.getValue()+n.right.left.getValue(),start:n.left.start,end:n.right.left.end}),right:n.right.right})),n.right instanceof lt&&n.left instanceof Ue&&"+"==n.left.operator&&n.left.right instanceof lt&&n.left.is_string(t)&&(n=e(Ue,n,{operator:"+",left:n.left.left,right:e(pt,null,{value:""+n.left.right.getValue()+n.right.getValue(),start:n.left.right.start,end:n.right.end})})),n.left instanceof Ue&&"+"==n.left.operator&&n.left.is_string(t)&&n.left.right instanceof lt&&n.right instanceof Ue&&"+"==n.right.operator&&n.right.left instanceof lt&&n.right.is_string(t)&&(n=e(Ue,n,{operator:"+",left:e(Ue,n.left,{operator:"+",left:n.left.left,right:e(pt,null,{value:""+n.left.right.getValue()+n.right.left.getValue(),start:n.left.right.start,end:n.right.left.end})}),right:n.right.right}))),n.right instanceof Ue&&n.right.operator==n.operator&&("*"==n.operator||"&&"==n.operator||"||"==n.operator)?(n.left=e(Ue,n.left,{operator:n.operator,left:n.left,right:n.right.left}),n.right=n.right.right,n.transform(t)):n.evaluate(t)[0])}),n(st,function(n,r){if(n.undeclared()){var i=r.option("global_defs");if(i&&i.hasOwnProperty(n.name))return t(r,i[n.name],n);switch(n.name){case"undefined":return e(gt,n);case"NaN":return e(vt,n);case"Infinity":return e(yt,n)}}return n}),n(gt,function(n,t){if(t.option("unsafe")){var r=t.find_parent(ce),i=r.find_variable("undefined");if(i){var o=e(st,n,{name:"undefined",scope:r,thedef:i});return o.reference(),o}}return n});var F=["+","-","/","*","%",">>","<<",">>>","|","^","&"];n(Le,function(n,e){return n=n.lift_sequences(e),"="==n.operator&&n.left instanceof st&&n.right instanceof Ue&&n.right.left instanceof st&&n.right.left.name==n.left.name&&o(n.right.operator,F)&&(n.operator=n.right.operator+"=",n.right=n.right.right),n}),n(Ve,function(n,t){if(!t.option("conditionals"))return n;if(n.condition instanceof Re){var r=n.condition.car;return n.condition=n.condition.cdr,Re.cons(r,n)}var i=n.condition.evaluate(t);if(i.length>1)return i[1]?(t.warn("Condition always true [{file}:{line},{col}]",n.start),n.consequent):(t.warn("Condition always false [{file}:{line},{col}]",n.start),n.alternative);var o=i[0].negate(t);f(i[0],o)===o&&(n=e(Ve,n,{condition:o,consequent:n.alternative,alternative:n.consequent}));var a=n.consequent,u=n.alternative;if(a instanceof Le&&u instanceof Le&&a.operator==u.operator&&a.left.equivalent_to(u.left))return e(Le,n,{operator:a.operator,left:a.left,right:e(Ve,n,{condition:n.condition,consequent:a.right,alternative:u.right})});if(a instanceof Me&&u.TYPE===a.TYPE&&a.args.length==u.args.length&&a.expression.equivalent_to(u.expression)){if(0==a.args.length)return e(Re,n,{car:n.condition,cdr:a});if(1==a.args.length)return a.args[0]=e(Ve,n,{condition:n.condition,consequent:a.args[0],alternative:u.args[0]}),a}return a instanceof Ve&&a.alternative.equivalent_to(u)?e(Ve,n,{condition:e(Ue,n,{left:n.condition,operator:"&&",right:a.condition}),consequent:a.consequent,alternative:u}):n}),n(At,function(n,t){if(t.option("booleans")){var r=t.parent();return r instanceof Ue&&("=="==r.operator||"!="==r.operator)?(t.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]",{operator:r.operator,value:n.value,file:r.start.file,line:r.start.line,col:r.start.col}),e(dt,n,{value:+n.value})):e(je,n,{operator:"!",expression:e(dt,n,{value:1-n.value})})}return n}),n(ze,function(n,t){var r=n.property;if(r instanceof pt&&t.option("properties")){if(r=r.getValue(),St(r)?t.option("screw_ie8"):$(r))return e(He,n,{expression:n.expression,property:r}).optimize(t);var i=parseFloat(r);isNaN(i)||i.toString()!=r||(n.property=e(dt,n.property,{value:i}))}return n}),n(He,function(n,e){return n.evaluate(e)[0]}),n(We,w),n(Ye,w),n(ht,w)}(),function(){function n(n){var r="prefix"in n?n.prefix:"UnaryExpression"==n.type?!0:!1;return new(r?je:Ie)({start:e(n),end:t(n),operator:n.operator,expression:i(n.argument)})}function e(n){return new L({file:n.loc&&n.loc.source,line:n.loc&&n.loc.start.line,col:n.loc&&n.loc.start.column,pos:n.start,endpos:n.start})}function t(n){return new L({file:n.loc&&n.loc.source,line:n.loc&&n.loc.end.line,col:n.loc&&n.loc.end.column,pos:n.end,endpos:n.end})}function r(n,r,a){var u="function From_Moz_"+n+"(M){\n";return u+="return new mytype({\nstart: my_start_token(M),\nend: my_end_token(M)",a&&a.split(/\s*,\s*/).forEach(function(n){var e=/([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(n);if(!e)throw new Error("Can't understand property map: "+n);var t="M."+e[1],r=e[2],i=e[3];if(u+=",\n"+i+": ","@"==r)u+=t+".map(from_moz)";else if(">"==r)u+="from_moz("+t+")";else if("="==r)u+=t;else{if("%"!=r)throw new Error("Can't understand operator in propmap: "+n);u+="from_moz("+t+").body"}}),u+="\n})}",u=new Function("mytype","my_start_token","my_end_token","from_moz","return("+u+")")(r,e,t,i),o[n]=u}function i(n){a.push(n);var e=null!=n?o[n.type](n):null;return a.pop(),e}var o={TryStatement:function(n){return new Ce({start:e(n),end:t(n),body:i(n.block).body,bcatch:i(n.handlers?n.handlers[0]:n.handler),bfinally:n.finalizer?new xe(i(n.finalizer)):null})},CatchClause:function(n){return new ke({start:e(n),end:t(n),argname:i(n.param),body:i(n.body).body})},ObjectExpression:function(n){return new Ye({start:e(n),end:t(n),properties:n.properties.map(function(n){var r=n.key,o="Identifier"==r.type?r.name:r.value,a={start:e(r),end:t(n.value),key:o,value:i(n.value)};switch(n.kind){case"init":return new Ge(a);case"set":return a.value.name=i(r),new Ke(a);case"get":return a.value.name=i(r),new Je(a)}})})},SequenceExpression:function(n){return Re.from_array(n.expressions.map(i))},MemberExpression:function(n){return new(n.computed?ze:He)({start:e(n),end:t(n),property:n.computed?i(n.property):n.property.name,expression:i(n.object)})},SwitchCase:function(n){return new(n.test?Se:Fe)({start:e(n),end:t(n),expression:i(n.test),body:n.consequent.map(i)})},Literal:function(n){var r=n.value,i={start:e(n),end:t(n)};if(null===r)return new mt(i);switch(typeof r){case"string":return i.value=r,new pt(i);case"number":return i.value=r,new dt(i);case"boolean":return new(r?Et:wt)(i);default:return i.value=r,new ht(i)}},UnaryExpression:n,UpdateExpression:n,Identifier:function(n){var r=a[a.length-2];return new("this"==n.name?ft:"LabeledStatement"==r.type?ut:"VariableDeclarator"==r.type&&r.id===n?"const"==r.kind?tt:et:"FunctionExpression"==r.type?r.id===n?ot:rt:"FunctionDeclaration"==r.type?r.id===n?it:rt:"CatchClause"==r.type?at:"BreakStatement"==r.type||"ContinueStatement"==r.type?ct:st)({start:e(n),end:t(n),name:n.name})}};r("Node",W),r("Program",fe,"body@body"),r("Function",de,"id>name, params@argnames, body%body"),r("EmptyStatement",Q),r("BlockStatement",Z,"body@body"),r("ExpressionStatement",K,"expression>body"),r("IfStatement",we,"test>condition, consequent>body, alternate>alternative"),r("LabeledStatement",ee,"label>label, body>body"),r("BreakStatement",ye,"label>label"),r("ContinueStatement",Ae,"label>label"),r("WithStatement",se,"object>expression, body>body"),r("SwitchStatement",Ee,"discriminant>expression, cases@body"),r("ReturnStatement",ve,"argument>value"),r("ThrowStatement",ge,"argument>value"),r("WhileStatement",oe,"test>condition, body>body"),r("DoWhileStatement",ie,"test>condition, body>body"),r("ForStatement",ae,"init>init, test>condition, update>step, body>body"),r("ForInStatement",ue,"left>init, right>object, body>body"),r("DebuggerStatement",X),r("FunctionDeclaration",he,"id>name, params@argnames, body%body"),r("VariableDeclaration",Te,"declarations@definitions"),r("VariableDeclarator",Oe,"id>name, init>value"),r("ThisExpression",ft),r("ArrayExpression",We,"elements@elements"),r("FunctionExpression",de,"id>name, params@argnames, body%body"),r("BinaryExpression",Ue,"operator=operator, left>left, right>right"),r("AssignmentExpression",Le,"operator=operator, left>left, right>right"),r("LogicalExpression",Ue,"operator=operator, left>left, right>right"),r("ConditionalExpression",Ve,"test>condition, consequent>consequent, alternate>alternative"),r("NewExpression",Ne,"callee>expression, arguments@args"),r("CallExpression",Me,"callee>expression, arguments@args");var a=null;W.from_mozilla_ast=function(n){var e=a;a=[];var t=i(n);return a=e,t}}(),n.array_to_hash=t,n.slice=r,n.characters=i,n.member=o,n.find_if=a,n.repeat_string=u,n.DefaultsError=s,n.defaults=c,n.merge=f,n.noop=l,n.MAP=V,n.push_uniq=p,n.string_template=d,n.remove=h,n.mergeSort=_,n.set_difference=m,n.set_intersection=v,n.makePredicate=g,n.all=b,n.Dictionary=y,n.DEFNODE=A,n.AST_Token=L,n.AST_Node=W,n.AST_Statement=Y,n.AST_Debugger=X,n.AST_Directive=G,n.AST_SimpleStatement=K,n.walk_body=w,n.AST_Block=J,n.AST_BlockStatement=Z,n.AST_EmptyStatement=Q,n.AST_StatementWithBody=ne,n.AST_LabeledStatement=ee,n.AST_IterationStatement=te,n.AST_DWLoop=re,n.AST_Do=ie,n.AST_While=oe,n.AST_For=ae,n.AST_ForIn=ue,n.AST_With=se,n.AST_Scope=ce,n.AST_Toplevel=fe,n.AST_Lambda=le,n.AST_Accessor=pe,n.AST_Function=de,n.AST_Defun=he,n.AST_Jump=_e,n.AST_Exit=me,n.AST_Return=ve,n.AST_Throw=ge,n.AST_LoopControl=be,n.AST_Break=ye,n.AST_Continue=Ae,n.AST_If=we,n.AST_Switch=Ee,n.AST_SwitchBranch=De,n.AST_Default=Fe,n.AST_Case=Se,n.AST_Try=Ce,n.AST_Catch=ke,n.AST_Finally=xe,n.AST_Definitions=Be,n.AST_Var=Te,n.AST_Const=$e,n.AST_VarDef=Oe,n.AST_Call=Me,n.AST_New=Ne,n.AST_Seq=Re,n.AST_PropAccess=qe,n.AST_Dot=He,n.AST_Sub=ze,n.AST_Unary=Pe,n.AST_UnaryPrefix=je,n.AST_UnaryPostfix=Ie,n.AST_Binary=Ue,n.AST_Conditional=Ve,n.AST_Assign=Le,n.AST_Array=We,n.AST_Object=Ye,n.AST_ObjectProperty=Xe,n.AST_ObjectKeyVal=Ge,n.AST_ObjectSetter=Ke,n.AST_ObjectGetter=Je,n.AST_Symbol=Ze,n.AST_SymbolAccessor=Qe,n.AST_SymbolDeclaration=nt,n.AST_SymbolVar=et,n.AST_SymbolConst=tt,n.AST_SymbolFunarg=rt,n.AST_SymbolDefun=it,n.AST_SymbolLambda=ot,n.AST_SymbolCatch=at,n.AST_Label=ut,n.AST_SymbolRef=st,n.AST_LabelRef=ct,n.AST_This=ft,n.AST_Constant=lt,n.AST_String=pt,n.AST_Number=dt,n.AST_RegExp=ht,n.AST_Atom=_t,n.AST_Null=mt,n.AST_NaN=vt,n.AST_Undefined=gt,n.AST_Hole=bt,n.AST_Infinity=yt,n.AST_Boolean=At,n.AST_False=wt,n.AST_True=Et,n.TreeWalker=E,n.KEYWORDS=Dt,n.KEYWORDS_ATOM=Ft,n.RESERVED_WORDS=St,n.KEYWORDS_BEFORE_EXPRESSION=Ct,n.OPERATOR_CHARS=kt,n.RE_HEX_NUMBER=xt,n.RE_OCT_NUMBER=Bt,n.RE_DEC_NUMBER=Tt,n.OPERATORS=$t,n.WHITESPACE_CHARS=Ot,n.PUNC_BEFORE_EXPRESSION=Mt,n.PUNC_CHARS=Nt,n.REGEXP_MODIFIERS=Rt,n.UNICODE=qt,n.is_letter=D,n.is_digit=F,n.is_alphanumeric_char=S,n.is_unicode_combining_mark=C,n.is_unicode_connector_punctuation=k,n.is_identifier=x,n.is_identifier_start=B,n.is_identifier_char=T,n.is_identifier_string=$,n.parse_js_number=O,n.JS_Parse_Error=M,n.js_error=N,n.is_token=R,n.EX_EOF=Ht,n.tokenizer=q,n.UNARY_PREFIX=zt,n.UNARY_POSTFIX=Pt,n.ASSIGNMENT=jt,n.PRECEDENCE=It,n.STATEMENTS_WITH_LABELS=Ut,n.ATOMIC_START_TOKEN=Vt,n.parse=H,n.TreeTransformer=z,n.SymbolDef=P,n.base54=Lt,n.OutputStream=j,n.Compressor=I,n.SourceMap=U}({},function(){return this}());
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/index.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/index.html
new file mode 100644
index 0000000..8a91a11
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/demo/index.html
@@ -0,0 +1,357 @@
+<!DOCTYPE html>
+<html lang="en" ng-app="ui.bootstrap.demo" id="top">
+<head>
+ <meta charset="utf-8">
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
+ <link rel="icon" href="assets/favicon.ico" />
+ <title>Angular directives for Bootstrap</title>
+ <meta name="description" content="AngularJS (Angular) native directives for Bootstrap. Small footprint (5kB gzipped!), no 3rd party JS dependencies (jQuery, bootstrap JS) required! Widgets: <% demoModules.forEach(function(module) { %><%= module.displayName %>, <% }); %>">
+ <meta name="google-site-verification" content="7lc5HyceLDqpV_6oNHteYFfxDJH7-S3DwnJKtNUKcRg" />
+ <script src="//cdnjs.cloudflare.com/ajax/libs/fastclick/0.6.7/fastclick.min.js"></script>
+ <script src="//cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.0.0/FileSaver.min.js"></script>
+ <script src="//cdnjs.cloudflare.com/ajax/libs/jszip/2.4.0/jszip.min.js"></script>
+ <script src="//ajax.googleapis.com/ajax/libs/angularjs/<%= ngversion %>/angular.min.js"></script>
+ <script src="//ajax.googleapis.com/ajax/libs/angularjs/<%= ngversion %>/angular-animate.min.js"></script>
+ <script src="//ajax.googleapis.com/ajax/libs/angularjs/<%= ngversion %>/angular-touch.min.js"></script>
+ <script src="//ajax.googleapis.com/ajax/libs/angularjs/<%= ngversion %>/angular-sanitize.js"></script>
+ <script src="ui-bootstrap-tpls-<%= pkg.version%>.min.js"></script>
+ <script src="assets/plunker.js"></script>
+ <script src="assets/app.js"></script>
+
+ <link href="//netdna.bootstrapcdn.com/bootstrap/<%= bsversion %>/css/bootstrap.min.css" rel="stylesheet"/>
+ <link rel="stylesheet" href="assets/rainbow.css"/>
+ <link rel="stylesheet" href="assets/demo.css"/>
+ <link rel="author" href="https://github.com/angular-ui/bootstrap/graphs/contributors">
+</head>
+<body class="ng-cloak" ng-controller="MainCtrl">
+<header class="navbar navbar-default navbar-fixed-top navbar-inner">
+ <div class="container">
+ <div class="navbar-header">
+ <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-3" ng-click="isCollapsed = !isCollapsed">
+ <span class="sr-only">Toggle navigation</span>
+ <span class="icon-bar"></span>
+ <span class="icon-bar"></span>
+ <span class="icon-bar"></span>
+ </button>
+ <a class="navbar-brand visible-xs" href="#">UI Bootstrap</a>
+ </div>
+ <nav class="hidden-xs">
+ <ul class="nav navbar-nav">
+ <a href="#top" role="button" class="navbar-brand">
+ UI Bootstrap
+ </a>
+ <li class="dropdown" uib-dropdown>
+ <a role="button" class="dropdown-toggle" uib-dropdown-toggle>
+ Directives <b class="caret"></b>
+ </a>
+ <ul class="dropdown-menu">
+ <% demoModules.forEach(function(module) { %><li><a href="#<%= module.name %>"><%= module.displayName %></a></li><% }); %>
+ </ul>
+ </li>
+ <li><a href="#getting_started">Getting started</a></li>
+ <li class="dropdown" uib-dropdown>
+ <a role="button" class="dropdown-toggle" uib-dropdown-toggle>
+ Previous docs <b class="caret"></b>
+ </a>
+ <ul class="dropdown-menu">
+ <li ng-repeat="version in oldDocs">
+ <a ng-href="{{version.url}}">{{version.version}}</a>
+ </li>
+ </ul>
+ </li>
+ </ul>
+ </nav>
+ <nav class="visible-xs" uib-collapse="!isCollapsed">
+ <ul class="nav navbar-nav">
+ <li><a href="#getting_started" ng-click="isCollapsed = !isCollapsed">Getting started</a></li>
+ <li><a href="#directives_small" ng-click="isCollapsed = !isCollapsed">Directives</a></li>
+ </ul>
+ </nav>
+ </div>
+</header>
+<div class="header-placeholder"></div>
+<div role="main">
+ <header class="bs-header text-center" id="overview">
+ <div class="container">
+ <h1>
+ UI Bootstrap
+ </h1>
+
+ <p>Bootstrap components written in pure <a href="http://angularjs.org">AngularJS</a> by the <a
+ href="http://angular-ui.github.io">AngularUI Team</a></p>
+
+ <p>
+ <a class="btn btn-outline-inverse btn-lg" href="https://github.com/angular-ui/bootstrap"><i class="icon-github"></i>Code on Github</a>
+ <button type="button" class="btn btn-outline-inverse btn-lg" ng-click="showDownloadModal()">
+ <i class="glyphicon glyphicon-download-alt"></i> Download <small>(<%= pkg.version%>)</small>
+ </button>
+ <button type="button" class="btn btn-outline-inverse btn-lg" ng-click="showBuildModal()"><i class="glyphicon glyphicon-wrench"></i> Create a Build</button>
+ </p>
+ </div>
+ <div class="bs-social container">
+ <ul class="bs-social-buttons">
+ <li>
+ <iframe src="//ghbtns.com/github-btn.html?user=angular-ui&repo=bootstrap&type=watch&count=true"
+ allowtransparency="true" frameborder="0" scrolling="0" width="110" height="20"></iframe>
+ </li>
+ <li>
+ <iframe src="//ghbtns.com/github-btn.html?user=angular-ui&repo=bootstrap&type=fork&count=true"
+ allowtransparency="true" frameborder="0" scrolling="0" width="110" height="20"></iframe>
+ </li>
+ <li>
+ <a href="https://twitter.com/share" class="twitter-share-button"
+ data-hashtags="angularjs">Tweet</a>
+ <script>!function (d, s, id) {
+ var js, fjs = d.getElementsByTagName(s)[0];
+ if (!d.getElementById(id)) {
+ js = d.createElement(s);
+ js.id = id;
+ js.src = "//platform.twitter.com/widgets.js";
+ fjs.parentNode.insertBefore(js, fjs);
+ }
+ }(document, "script", "twitter-wjs");</script>
+ </li>
+ <li>
+ <!-- Place this tag where you want the +1 button to render. -->
+ <div class="g-plusone" data-size="medium"></div>
+
+ <!-- Place this tag after the last +1 button tag. -->
+ <script type="text/javascript">
+ (function () {
+ var po = document.createElement('script');
+ po.type = 'text/javascript';
+ po.async = true;
+ po.src = 'https://apis.google.com/js/plusone.js';
+ var s = document.getElementsByTagName('script')[0];
+ s.parentNode.insertBefore(po, s);
+ })();
+ </script>
+ </li>
+ </ul>
+ </div>
+ </header>
+ <div class="container">
+ <div class="row">
+ <div class="col-md-12">
+ <section class="bs-sidebar visible-xs" id="directives_small">
+ <ul class="nav bs-sidenav">
+ <li><a href="#"><strong>Directives</strong></a></li>
+ <% demoModules.forEach(function(module) { %>
+ <li><a href="#<%= module.name %>"><%= module.displayName %></a></li>
+ <% }); %>
+ </ul>
+ </section>
+
+ <section id="getting_started">
+ <div class="page-header">
+ <h1>Getting started</h1>
+ </div>
+ <h3>Dependencies</h3>
+ <p>
+ This repository contains a set of <strong>native AngularJS directives</strong> based on
+ Bootstrap's markup and CSS. As a result no dependency on jQuery or Bootstrap's
+ JavaScript is required. The <strong>only required dependencies</strong> are:
+ </p>
+ <ul>
+ <li><a href="http://angularjs.org" target="_blank">AngularJS</a> (requires AngularJS 1.3.x, tested with <%= ngversion %>).
+ 0.12.0 is the last version of this library that supports AngularJS 1.2.x.</li>
+ <li><a href="http://getbootstrap.com" target="_blank">Bootstrap CSS</a> (tested with version <%= bsversion %>).
+ This version of the library (<%= pkg.version%>) works only with Bootstrap CSS in version 3.x.
+ 0.8.0 is the last version of this library that supports Bootstrap CSS in version 2.3.x.
+ </li>
+ </ul>
+ <h3>Files to download</h3>
+ <p>
+ Build files for all directives are distributed in several flavours: minified for production usage, un-minified
+ for development, with or without templates. All the options are described and can be
+ <a href="https://github.com/angular-ui/bootstrap/tree/gh-pages">downloaded from here</a>. It should be noted that the <code>-tpls</code> files contain the templates bundled in JavaScript, while the regular version does not contain the bundled templates. For more information, check out the FAQ <a href="https://github.com/angular-ui/bootstrap/wiki/FAQ#full-explanation">here</a> and the README <a href="https://github.com/angular-ui/bootstrap/tree/gh-pages#build-files">here</a>.
+ </p>
+ <p>Alternativelly, if you are only interested in a subset of directives, you can
+ <a ng-click="showBuildModal()">create your own build</a>.
+ </p>
+ <p>Whichever method you choose the good news that the overall size of a download is very small:
+ <76kB for all directives (~20kB with gzip compression!)</p>
+ <h3>Installation</h3>
+ <p>As soon as you've got all the files downloaded and included in your page you just need to declare
+ a dependency on the <code>ui.bootstrap</code> <a href="http://docs.angularjs.org/guide/module">module</a>:<br>
+ <pre><code>angular.module('myModule', ['ui.bootstrap']);</code></pre>
+ </p>
+ <p>You can fork one of the plunkers from this page to see a working example of what is described here.</p>
+ <h3>CSS</h3>
+ <p>Original Bootstrap's CSS depends on empty <code>href</code> attributes to style cursors for several components (pagination, tabs etc.).
+ But in AngularJS adding empty <code>href</code> attributes to link tags will cause unwanted route changes. This is why we need to remove empty <code>href</code> attributes from directive templates and as a result styling is not applied correctly. The remedy is simple, just add the following styling to your application: <pre><code>.nav, .pagination, .carousel, .panel-title a { cursor: pointer; }</code></pre>
+ </p>
+ <h3>FAQ</h3>
+ <p>Please check <a href="https://github.com/angular-ui/bootstrap/wiki/FAQ" target="_blank">our FAQ section</a> for common problems / solutions.</p>
+ <h3>Reading the documentation</h3>
+ <p>
+ Each of the components provided in <code>ui-bootstrap</code> have documentation and interactive Plunker examples.
+ </p>
+ <p>
+ For the directives, we list the different attributes with their default values, and whether they are readonly. In addition to this, some settings
+ have an eye icon next to them like this <i class="glyphicon glyphicon-eye-open"></i>. The eye means that the setting has an Angular
+ <a href="https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch" title="Angular $watch" target="_blank">$watch</a> listener applied to it.
+ </p>
+ <p>
+ For the services (you will recognize them with the <code>$</code> prefix), we list all the possible parameters you can pass to them and their default values if any.
+ </p>
+ <p>
+ Also, some components have default values that you can override globally within a <code>.config</code> function for example.
+ </p>
+ </section>
+ <% demoModules.forEach(function(module) { %>
+ <section id="<%= module.name %>">
+ <div class="page-header">
+ <h1><%= module.displayName %><small>
+ (<a target="_blank" href="https://github.com/angular-ui/bootstrap/tree/master/src/<%= module.name %>">ui.bootstrap.<%= module.name %></a>)
+ </small></h1>
+ </div>
+ <div class="row">
+ <div class="col-md-6 show-grid">
+ <%= module.docs.html %>
+ </div>
+ <div class="col-md-6">
+ <%= module.docs.md %>
+ </div>
+ </div>
+ <hr>
+ <div class="row code">
+ <div class="col-md-12" ng-controller="PlunkerCtrl">
+ <div class="pull-right">
+ <button type="button" class="btn btn-info plunk-btn" ng-click="edit('<%= ngversion%>', '<%= bsversion %>', '<%= pkg.version%>', '<%= module.name %>')"><i class="glyphicon glyphicon-edit"></i> Edit in plunker</button>
+ </div>
+ <uib-tabset>
+ <uib-tab heading="Markup">
+ <div plunker-content="markup">
+ <pre ng-non-bindable><code data-language="html"><%- module.docs.html %></code></pre>
+ </div>
+ </uib-tab>
+ <uib-tab heading="JavaScript">
+ <div plunker-content="javascript">
+ <pre ng-non-bindable><code data-language="javascript"><%- module.docs.js %></code></pre>
+ </div>
+ </uib-tab>
+ </uib-tabset>
+ </div>
+ </div>
+ </section>
+ <script><%= module.docs.js %></script>
+ <% }); %>
+ </div>
+ </div>
+ </div><!-- /.container -->
+</div><!-- /.main -->
+<footer class="footer">
+ <div class="container">
+ <p>Designed and built by <a href="https://github.com/angular-ui?tab=members" target="_blank">Angular-UI team</a> and <a href="https://github.com/angular-ui/bootstrap/graphs/contributors" target="_blank">contributors</a>.</p>
+ <p>Code licensed under <a href="https://github.com/angular-ui/bootstrap/blob/master/LICENSE"><%= pkg.license %> License</a>.</p>
+ <p><a href="https://github.com/angular-ui/bootstrap/issues?state=open">Issues</a></p>
+ </div>
+</footer>
+<script src="assets/rainbow.js"></script>
+<script src="assets/rainbow-generic.js"></script>
+<script src="assets/rainbow-javascript.js"></script>
+<script src="assets/rainbow-html.js"></script>
+<script type="text/ng-template" id="downloadModal.html">
+ <div class="modal-header"><h4 class="modal-title">Download Angular UI Bootstrap</h4></div>
+ <div class="modal-body">
+ <form class="form-horizontal">
+ <div class="form-group">
+ <label class="col-sm-3 control-label"><strong>Build</strong></label>
+ <div class="col-sm-9">
+ <span class="btn-group">
+ <button type="button" class="btn btn-default" ng-model="options.minified" uib-btn-radio="true">Minified</button>
+ <button type="button" class="btn btn-default" ng-model="options.minified" uib-btn-radio="false">Uncompressed</button>
+ </span>
+ <small class="help-block">Use <b>Minified</b> version in your deployed application. <b>Uncompressed</b> source code is useful only for debugging and development purpose.</small>
+ </div>
+ </div>
+ <div class="form-group">
+ <label class="col-sm-3 control-label"><strong>Include Templates</strong></label>
+ <div class="col-sm-9">
+ <span class="btn-group">
+ <button type="button" class="btn btn-default" ng-model="options.tpls" uib-btn-radio="true">Yes</button>
+ <button type="button" class="btn btn-default" ng-model="options.tpls" uib-btn-radio="false">No</button>
+ </span>
+ <small class="help-block">Whether you want to include the <i>default templates</i>, bundled with most of the directives. These templates are based on Bootstrap's markup and CSS.</small>
+ </div>
+ </div>
+ <div class="form-group">
+ <label class="col-sm-3 control-label"><strong>Bower</strong></label>
+ <div class="col-sm-9">
+ <small>If you are using Bower just run:</small>
+ <pre style="margin-bottom:0;">bower install angular-bootstrap</pre>
+ <small class="help-block"><a href="http://bower.io/" target="_blank">Bower</a> is a package manager for the web.</small>
+ </div>
+ </div>
+ </form>
+ </div>
+ <div class="modal-footer">
+ <a class="btn btn-default" ng-click="cancel()">Close</a>
+ <a class="btn btn-primary" ng-href="{{download('<%= pkg.version%>')}}" download><i class="glyphicon glyphicon-download-alt"></i> Download <%= pkg.version %></a>
+ </div>
+</script>
+<script type="text/ng-template" id="buildModal.html">
+ <div class="modal-header">
+ <h4>
+ Create a Custom Build
+ <br>
+ <small>Select the modules you wish to download</small>
+ </h4>
+ </div>
+ <div class="modal-body">
+ <div ng-show="isOldBrowser()">
+ Your current browser doesn't support creating custom builds.
+ Please take a second to <a href="http://browsehappy.com/">upgrade to a
+ more modern browser</a> (other than Safari).
+ </div>
+ <div ng-show="buildErrorText">
+ <h4 style="text-align: center;">{{buildErrorText}}</h4>
+ </div>
+ <div ng-hide="buildErrorText || isOldBrowser()">
+ <% modules.forEach(function(module,i) { %>
+ <% if (i % 3 === 0) {%>
+ <div class="btn-group" style="width: 100%;">
+ <% } %>
+ <button type="button" class="btn btn-default"
+ style="width: 33%; border-radius: 0;"
+ ng-class="{'btn-primary': module.<%= module.name %>}"
+ ng-model="module.<%= module.name %>"
+ uib-btn-checkbox
+ ng-change="selectedChanged('<%= module.name %>', module.<%= module.name %>)">
+ <%= module.displayName %>
+ </button>
+ <% if ((i+1) % 3 === 0) { //end button group%>
+ </div>
+ <% } %>
+ <% }); %>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <a class="btn btn-default" ng-click="cancel()">Close</a>
+ <a class="btn btn-primary" ng-hide="isOldBrowser()"
+ ng-disabled="isOldBrowser() !== false && !selectedModules.length"
+ ng-click="selectedModules.length && build(selectedModules, '<%= pkg.version %>')">
+ <i class="glyphicon glyphicon-download-alt"></i> Download {{selectedModules.length}} Modules
+ </a>
+ </div>
+</script>
+
+<script type="text/javascript">
+
+ var _gaq = _gaq || [];
+ _gaq.push(['_setAccount', 'UA-37467169-1']);
+ _gaq.push(['_trackPageview']);
+
+ (function() {
+ var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
+ ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+ var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
+ })();
+
+</script>
+<script src="assets/smoothscroll-angular-custom.js"></script>
+<script src="assets/uglifyjs.js"></script>
+</body>
+</html>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/raw-files-generator.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/raw-files-generator.js
new file mode 100644
index 0000000..4e563e6
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/raw-files-generator.js
@@ -0,0 +1,46 @@
+/*!
+ * Forked from:
+ * Bootstrap Grunt task for generating raw-files.min.js for the Customizer
+ * http://getbootstrap.com
+ * Copyright 2014 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ */
+
+/* jshint node: true */
+
+'use strict';
+var fs = require('fs');
+
+function getFiles(filePaths) {
+ var files = {};
+ filePaths
+ .forEach(function (path) {
+ files[path] = fs.readFileSync(path, 'utf8');
+ });
+ return files;
+}
+
+module.exports = function generateRawFilesJs(grunt, jsFilename, files, banner, cssBanner) {
+ if (!banner) {
+ banner = '';
+ }
+
+ if (!cssBanner) {
+ cssBanner = '';
+ }
+
+ var filesJsObject = {
+ banner: banner,
+ cssBanner: cssBanner,
+ files: getFiles(files),
+ };
+
+ var filesJsContent = JSON.stringify(filesJsObject);
+ try {
+ fs.writeFileSync(jsFilename, filesJsContent);
+ }
+ catch (err) {
+ grunt.fail.warn(err);
+ }
+ grunt.log.writeln('File ' + jsFilename.cyan + ' created.');
+};
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/test-lib/helpers.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/test-lib/helpers.js
new file mode 100644
index 0000000..452c7fd
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/test-lib/helpers.js
@@ -0,0 +1,57 @@
+// jasmine matcher for expecting an element to have a css class
+// https://github.com/angular/angular.js/blob/master/test/matchers.js
+beforeEach(function() {
+ jasmine.addMatchers({
+ toHaveClass: function(util, customEqualityTesters) {
+ return {
+ compare: function(actual, expected) {
+ var result = {
+ pass: actual.hasClass(expected)
+ };
+
+ if (result.pass) {
+ result.message = 'Expected "' + actual + '" not to have the "' + expected + '" class.';
+ } else {
+ result.message = 'Expected "' + actual + '" to have the "' + expected + '" class.';
+ }
+
+ return result;
+ }
+ }
+ },
+ toBeHidden: function(util, customEqualityTesters) {
+ return {
+ compare: function(actual) {
+ var result = {
+ pass: actual.hasClass('ng-hide') || actual.css('display') === 'none'
+ };
+
+ if (result.pass) {
+ result.message = 'Expected "' + actual + '" not to be hidden';
+ } else {
+ result.message = 'Expected "' + actual + '" to be hidden';
+ }
+
+ return result;
+ }
+ }
+ },
+ toHaveFocus: function(util, customEqualityTesters) {
+ return {
+ compare: function(actual) {
+ var result = {
+ pass: document.activeElement === actual[0]
+ };
+
+ if (result.pass) {
+ result.message = 'Expected "' + actual + '" not to have focus';
+ } else {
+ result.message = 'Expected "' + actual + '" to have focus';
+ }
+
+ return result;
+ }
+ }
+ }
+ });
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/test-lib/jquery-1.8.2.min.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/test-lib/jquery-1.8.2.min.js
new file mode 100644
index 0000000..bc3fbc8
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/test-lib/jquery-1.8.2.min.js
@@ -0,0 +1,2 @@
+/*! jQuery v1.8.2 jquery.com | jquery.org/license */
+(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bY(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bW.length;while(e--){b=bW[e]+c;if(b in a)return b}return d}function bZ(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function b$(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bZ(c)&&(e[f]=p._data(c,"olddisplay",cc(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b_(a,b,c){var d=bP.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function ca(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bV[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bV[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bV[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bV[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bV[e]+"Width"))||0));return f}function cb(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0||d==null){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bQ.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+ca(a,b,c||(f?"border":"content"),e)+"px"}function cc(a){if(bS[a])return bS[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bS[a]=c,c}function ci(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||ce.test(a)?d(a,e):ci(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ci(a+"["+e+"]",b[e],c,d);else d(a,b)}function cz(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cA(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cv;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cA(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cA(a,c,d,e,"*",g)),h}function cB(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cC(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cD(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cL(){try{return new a.XMLHttpRequest}catch(b){}}function cM(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cU(){return setTimeout(function(){cN=b},0),cN=p.now()}function cV(a,b){p.each(b,function(b,c){var d=(cT[b]||[]).concat(cT["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cW(a,b,c){var d,e=0,f=0,g=cS.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cN||cU(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cN||cU(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cX(k,j.opts.specialEasing);for(;e<g;e++){d=cS[e].call(j,a,k,j.opts);if(d)return d}return cV(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cX(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cY(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bZ(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cc(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cP.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cZ(a,b,c,d,e){return new cZ.prototype.init(a,b,c,d,e)}function c$(a,b){var c,d={height:a},e=0;b=b?1:0;for(;e<4;e+=2-b)c=bV[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function da(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.2",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o&&!o.call(" ")?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":(a+"").replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete")setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){var e=p.type(c);e==="function"&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&e!=="string"&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return a!=null?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||p.guid++:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")||(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.length,e=c.shift(),f=p._queueHooks(a,b),g=function(){p.dequeue(a,b)};e==="inprogress"&&(e=c.shift(),d--),e&&(b==="fx"&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)d=p._data(g[h],a+"queueHooks"),d&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)f.indexOf(" "+b[g]+" ")<0&&(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>=0)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>=0)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,d+""),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=b+""}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,needsContext:f&&p.expr.match.needsContext.test(f),namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=k.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click"))for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){h={},j=[];for(d=0;d<q;d++)l=o[d],m=l.selector,h[m]===b&&(h[m]=l.needsContext?p(m,this).index(f)>=0:p.find(m,this,null,[f]).length),h[m]&&j.push(l);j.length&&u.push({elem:f,matches:j})}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){i=u[d],c.currentTarget=i.elem;for(e=0;e<i.matches.length&&!c.isImmediatePropagationStopped();e++){l=i.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,g=((p.event.special[l.origType]||{}).handle||l.handler).apply(i.elem,r),g!==b&&(c.result=g,g===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),!V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length===1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bc(a,b,c,d){c=c||[],b=b||r;var e,f,i,j,k=b.nodeType;if(!a||typeof a!="string")return c;if(k!==1&&k!==9)return[];i=g(b);if(!i&&!d)if(e=P.exec(a))if(j=e[1]){if(k===9){f=b.getElementById(j);if(!f||!f.parentNode)return c;if(f.id===j)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(j))&&h(b,f)&&f.id===j)return c.push(f),c}else{if(e[2])return w.apply(c,x.call(b.getElementsByTagName(a),0)),c;if((j=e[3])&&_&&b.getElementsByClassName)return w.apply(c,x.call(b.getElementsByClassName(j),0)),c}return bp(a.replace(L,"$1"),b,c,d,i)}function bd(a){return function(b){var c=b.nodeName.toLowerCase();return c==="input"&&b.type===a}}function be(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}}function bf(a){return z(function(b){return b=+b,z(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function bg(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}function bh(a,b){var c,d,f,g,h,i,j,k=C[o][a];if(k)return b?0:k.slice(0);h=a,i=[],j=e.preFilter;while(h){if(!c||(d=M.exec(h)))d&&(h=h.slice(d[0].length)),i.push(f=[]);c=!1;if(d=N.exec(h))f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=d[0].replace(L," ");for(g in e.filter)(d=W[g].exec(h))&&(!j[g]||(d=j[g](d,r,!0)))&&(f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=g,c.matches=d);if(!c)break}return b?h.length:h?bc.error(a):C(a,i).slice(0)}function bi(a,b,d){var e=b.dir,f=d&&b.dir==="parentNode",g=u++;return b.first?function(b,c,d){while(b=b[e])if(f||b.nodeType===1)return a(b,c,d)}:function(b,d,h){if(!h){var i,j=t+" "+g+" ",k=j+c;while(b=b[e])if(f||b.nodeType===1){if((i=b[o])===k)return b.sizset;if(typeof i=="string"&&i.indexOf(j)===0){if(b.sizset)return b}else{b[o]=k;if(a(b,d,h))return b.sizset=!0,b;b.sizset=!1}}}else while(b=b[e])if(f||b.nodeType===1)if(a(b,d,h))return b}}function bj(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function bk(a,b,c,d,e){var f,g=[],h=0,i=a.length,j=b!=null;for(;h<i;h++)if(f=a[h])if(!c||c(f,d,e))g.push(f),j&&b.push(h);return g}function bl(a,b,c,d,e,f){return d&&!d[o]&&(d=bl(d)),e&&!e[o]&&(e=bl(e,f)),z(function(f,g,h,i){if(f&&e)return;var j,k,l,m=[],n=[],o=g.length,p=f||bo(b||"*",h.nodeType?[h]:h,[],f),q=a&&(f||!b)?bk(p,m,a,h,i):p,r=c?e||(f?a:o||d)?[]:g:q;c&&c(q,r,h,i);if(d){l=bk(r,n),d(l,[],h,i),j=l.length;while(j--)if(k=l[j])r[n[j]]=!(q[n[j]]=k)}if(f){j=a&&r.length;while(j--)if(k=r[j])f[m[j]]=!(g[m[j]]=k)}else r=bk(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):w.apply(g,r)})}function bm(a){var b,c,d,f=a.length,g=e.relative[a[0].type],h=g||e.relative[" "],i=g?1:0,j=bi(function(a){return a===b},h,!0),k=bi(function(a){return y.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==l)||((b=c).nodeType?j(a,c,d):k(a,c,d))}];for(;i<f;i++)if(c=e.relative[a[i].type])m=[bi(bj(m),c)];else{c=e.filter[a[i].type].apply(null,a[i].matches);if(c[o]){d=++i;for(;d<f;d++)if(e.relative[a[d].type])break;return bl(i>1&&bj(m),i>1&&a.slice(0,i-1).join("").replace(L,"$1"),c,i<d&&bm(a.slice(i,d)),d<f&&bm(a=a.slice(d)),d<f&&a.join(""))}m.push(c)}return bj(m)}function bn(a,b){var d=b.length>0,f=a.length>0,g=function(h,i,j,k,m){var n,o,p,q=[],s=0,u="0",x=h&&[],y=m!=null,z=l,A=h||f&&e.find.TAG("*",m&&i.parentNode||i),B=t+=z==null?1:Math.E;y&&(l=i!==r&&i,c=g.el);for(;(n=A[u])!=null;u++){if(f&&n){for(o=0;p=a[o];o++)if(p(n,i,j)){k.push(n);break}y&&(t=B,c=++g.el)}d&&((n=!p&&n)&&s--,h&&x.push(n))}s+=u;if(d&&u!==s){for(o=0;p=b[o];o++)p(x,q,i,j);if(h){if(s>0)while(u--)!x[u]&&!q[u]&&(q[u]=v.call(k));q=bk(q)}w.apply(k,q),y&&!h&&q.length>0&&s+b.length>1&&bc.uniqueSort(k)}return y&&(t=B,l=z),x};return g.el=0,d?z(g):g}function bo(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)bc(a,b[e],c,d);return c}function bp(a,b,c,d,f){var g,h,j,k,l,m=bh(a),n=m.length;if(!d&&m.length===1){h=m[0]=m[0].slice(0);if(h.length>2&&(j=h[0]).type==="ID"&&b.nodeType===9&&!f&&e.relative[h[1].type]){b=e.find.ID(j.matches[0].replace(V,""),b,f)[0];if(!b)return c;a=a.slice(h.shift().length)}for(g=W.POS.test(a)?-1:h.length-1;g>=0;g--){j=h[g];if(e.relative[k=j.type])break;if(l=e.find[k])if(d=l(j.matches[0].replace(V,""),R.test(h[0].type)&&b.parentNode||b,f)){h.splice(g,1),a=d.length&&h.join("");if(!a)return w.apply(c,x.call(d,0)),c;break}}}return i(a,m)(d,b,f,c,R.test(a)),c}function bq(){}var c,d,e,f,g,h,i,j,k,l,m=!0,n="undefined",o=("sizcache"+Math.random()).replace(".",""),q=String,r=a.document,s=r.documentElement,t=0,u=0,v=[].pop,w=[].push,x=[].slice,y=[].indexOf||function(a){var b=0,c=this.length;for(;b<c;b++)if(this[b]===a)return b;return-1},z=function(a,b){return a[o]=b==null||b,a},A=function(){var a={},b=[];return z(function(c,d){return b.push(c)>e.cacheLength&&delete a[b.shift()],a[c]=d},a)},B=A(),C=A(),D=A(),E="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",G=F.replace("w","w#"),H="([*^$|!~]?=)",I="\\["+E+"*("+F+")"+E+"*(?:"+H+E+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+G+")|)|)"+E+"*\\]",J=":("+F+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+I+")|[^:]|\\\\.)*|.*))\\)|)",K=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+E+"*((?:-\\d)?\\d*)"+E+"*\\)|)(?=[^-]|$)",L=new RegExp("^"+E+"+|((?:^|[^\\\\])(?:\\\\.)*)"+E+"+$","g"),M=new RegExp("^"+E+"*,"+E+"*"),N=new RegExp("^"+E+"*([\\x20\\t\\r\\n\\f>+~])"+E+"*"),O=new RegExp(J),P=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,Q=/^:not/,R=/[\x20\t\r\n\f]*[+~]/,S=/:not\($/,T=/h\d/i,U=/input|select|textarea|button/i,V=/\\(?!\\)/g,W={ID:new RegExp("^#("+F+")"),CLASS:new RegExp("^\\.("+F+")"),NAME:new RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:new RegExp("^("+F.replace("w","w*")+")"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+J),POS:new RegExp(K,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+E+"*(even|odd|(([+-]|)(\\d*)n|)"+E+"*(?:([+-]|)"+E+"*(\\d+)|))"+E+"*\\)|)","i"),needsContext:new RegExp("^"+E+"*[>+~]|"+K,"i")},X=function(a){var b=r.createElement("div");try{return a(b)}catch(c){return!1}finally{b=null}},Y=X(function(a){return a.appendChild(r.createComment("")),!a.getElementsByTagName("*").length}),Z=X(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==n&&a.firstChild.getAttribute("href")==="#"}),$=X(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),_=X(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||!a.getElementsByClassName("e").length?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length===2)}),ba=X(function(a){a.id=o+0,a.innerHTML="<a name='"+o+"'></a><div name='"+o+"'></div>",s.insertBefore(a,s.firstChild);var b=r.getElementsByName&&r.getElementsByName(o).length===2+r.getElementsByName(o+0).length;return d=!r.getElementById(o),s.removeChild(a),b});try{x.call(s.childNodes,0)[0].nodeType}catch(bb){x=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}bc.matches=function(a,b){return bc(a,null,null,b)},bc.matchesSelector=function(a,b){return bc(b,null,null,[a]).length>0},f=bc.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=f(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=f(b);return c},g=bc.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},h=bc.contains=s.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:s.compareDocumentPosition?function(a,b){return b&&!!(a.compareDocumentPosition(b)&16)}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc.attr=function(a,b){var c,d=g(a);return d||(b=b.toLowerCase()),(c=e.attrHandle[b])?c(a):d||$?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},e=bc.selectors={cacheLength:50,createPseudo:z,match:W,attrHandle:Z?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},find:{ID:d?function(a,b,c){if(typeof b.getElementById!==n&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==n&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==n&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:Y?function(a,b){if(typeof b.getElementsByTagName!==n)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c},NAME:ba&&function(a,b){if(typeof b.getElementsByName!==n)return b.getElementsByName(name)},CLASS:_&&function(a,b,c){if(typeof b.getElementsByClassName!==n&&!c)return b.getElementsByClassName(a)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(V,""),a[3]=(a[4]||a[5]||"").replace(V,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||bc.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&bc.error(a[0]),a},PSEUDO:function(a){var b,c;if(W.CHILD.test(a[0]))return null;if(a[3])a[2]=a[3];else if(b=a[4])O.test(b)&&(c=bh(b,!0))&&(c=b.indexOf(")",b.length-c)-b.length)&&(b=b.slice(0,c),a[0]=a[0].slice(0,c)),a[2]=b;return a.slice(0,3)}},filter:{ID:d?function(a){return a=a.replace(V,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(V,""),function(b){var c=typeof b.getAttributeNode!==n&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(V,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=B[o][a];return b||(b=B(a,new RegExp("(^|"+E+")"+a+"("+E+"|$)"))),function(a){return b.test(a.className||typeof a.getAttribute!==n&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return function(d,e){var f=bc.attr(d,a);return f==null?b==="!=":b?(f+="",b==="="?f===c:b==="!="?f!==c:b==="^="?c&&f.indexOf(c)===0:b==="*="?c&&f.indexOf(c)>-1:b==="$="?c&&f.substr(f.length-c.length)===c:b==="~="?(" "+f+" ").indexOf(c)>-1:b==="|="?f===c||f.substr(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d){return a==="nth"?function(a){var b,e,f=a.parentNode;if(c===1&&d===0)return!0;if(f){e=0;for(b=f.firstChild;b;b=b.nextSibling)if(b.nodeType===1){e++;if(a===b)break}}return e-=d,e===c||e%c===0&&e/c>=0}:function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b){var c,d=e.pseudos[a]||e.setFilters[a.toLowerCase()]||bc.error("unsupported pseudo: "+a);return d[o]?d(b):d.length>1?(c=[a,a,"",b],e.setFilters.hasOwnProperty(a.toLowerCase())?z(function(a,c){var e,f=d(a,b),g=f.length;while(g--)e=y.call(a,f[g]),a[e]=!(c[e]=f[g])}):function(a){return d(a,0,c)}):d}},pseudos:{not:z(function(a){var b=[],c=[],d=i(a.replace(L,"$1"));return d[o]?z(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)if(f=g[h])a[h]=!(b[h]=f)}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:z(function(a){return function(b){return bc(a,b).length>0}}),contains:z(function(a){return function(b){return(b.textContent||b.innerText||f(b)).indexOf(a)>-1}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!e.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},header:function(a){return T.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:bd("radio"),checkbox:bd("checkbox"),file:bd("file"),password:bd("password"),image:bd("image"),submit:be("submit"),reset:be("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return U.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement},first:bf(function(a,b,c){return[0]}),last:bf(function(a,b,c){return[b-1]}),eq:bf(function(a,b,c){return[c<0?c+b:c]}),even:bf(function(a,b,c){for(var d=0;d<b;d+=2)a.push(d);return a}),odd:bf(function(a,b,c){for(var d=1;d<b;d+=2)a.push(d);return a}),lt:bf(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:bf(function(a,b,c){for(var d=c<0?c+b:c;++d<b;)a.push(d);return a})}},j=s.compareDocumentPosition?function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,h=b.parentNode,i=g;if(g===h)return bg(a,b);if(!g)return-1;if(!h)return 1;while(i)e.unshift(i),i=i.parentNode;i=h;while(i)f.unshift(i),i=i.parentNode;c=e.length,d=f.length;for(var j=0;j<c&&j<d;j++)if(e[j]!==f[j])return bg(e[j],f[j]);return j===c?bg(a,f[j],-1):bg(e[j],b,1)},[0,0].sort(j),m=!k,bc.uniqueSort=function(a){var b,c=1;k=m,a.sort(j);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1);return a},bc.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},i=bc.compile=function(a,b){var c,d=[],e=[],f=D[o][a];if(!f){b||(b=bh(a)),c=b.length;while(c--)f=bm(b[c]),f[o]?d.push(f):e.push(f);f=D(a,bn(e,d))}return f},r.querySelectorAll&&function(){var a,b=bp,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[":focus"],f=[":active",":focus"],h=s.matchesSelector||s.mozMatchesSelector||s.webkitMatchesSelector||s.oMatchesSelector||s.msMatchesSelector;X(function(a){a.innerHTML="<select><option selected=''></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+E+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),X(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+E+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'/>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=new RegExp(e.join("|")),bp=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a))){var i,j,k=!0,l=o,m=d,n=d.nodeType===9&&a;if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){i=bh(a),(k=d.getAttribute("id"))?l=k.replace(c,"\\$&"):d.setAttribute("id",l),l="[id='"+l+"'] ",j=i.length;while(j--)i[j]=l+i[j].join("");m=R.test(a)&&d.parentNode||d,n=i.join(",")}if(n)try{return w.apply(f,x.call(m.querySelectorAll(n),0)),f}catch(p){}finally{k||d.removeAttribute("id")}}return b(a,d,f,g,h)},h&&(X(function(b){a=h.call(b,"div");try{h.call(b,"[test!='']:sizzle"),f.push("!=",J)}catch(c){}}),f=new RegExp(f.join("|")),bc.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!g(b)&&!f.test(c)&&(!e||!e.test(c)))try{var i=h.call(b,c);if(i||a||b.document&&b.document.nodeType!==11)return i}catch(j){}return bc(c,null,null,[b]).length>0})}(),e.pseudos.nth=e.pseudos.eq,e.filters=bq.prototype=e.pseudos,e.setFilters=new bq,bc.attr=p.attr,p.find=bc,p.expr=bc.selectors,p.expr[":"]=p.expr.pseudos,p.unique=bc.uniqueSort,p.text=bc.getText,p.isXMLDoc=bc.isXML,p.contains=bc.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=!c.nodeType&&c[0]||c,c=c.ownerDocument||c,a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=b===e&&bA,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(f=0;(h=a[f])!=null;f++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{s=s||bk(b),l=b.createElement("div"),s.appendChild(l),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(g=n.length-1;g>=0;--g)p.nodeName(n[g],"tbody")&&!n[g].childNodes.length&&n[g].parentNode.removeChild(n[g])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l.parentNode.removeChild(l)}h.nodeType?t.push(h):p.merge(t,h)}l&&(h=l=s=null);if(!p.support.appendChecked)for(f=0;(h=t[f])!=null;f++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(f=0;(h=t[f])!=null;f++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[f+1,0].concat(r)),f+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.chrome?b.webkit=!0:b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^(none|table(?!-c[ea]).+)/,bO=/^margin/,bP=new RegExp("^("+q+")(.*)$","i"),bQ=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bR=new RegExp("^([-+])=("+q+")","i"),bS={},bT={position:"absolute",visibility:"hidden",display:"block"},bU={letterSpacing:0,fontWeight:400},bV=["Top","Right","Bottom","Left"],bW=["Webkit","O","Moz","ms"],bX=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return b$(this,!0)},hide:function(){return b$(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bX.apply(this,arguments):this.each(function(){(c?a:bZ(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bY(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bR.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bY(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bU&&(f=bU[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h[c],d===""&&!p.contains(b.ownerDocument,b)&&(d=p.style(b,c)),bQ.test(d)&&bO.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bQ.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth===0&&bN.test(bH(a,"display"))?p.swap(a,bT,function(){return cb(a,b,d)}):cb(a,b,d)},set:function(a,c,d){return b_(a,c,d?ca(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bQ.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bV[d]+b]=e[d]||e[d-2]||e[0];return f}},bO.test(a)||(p.cssHooks[a+b].set=b_)});var cd=/%20/g,ce=/\[\]$/,cf=/\r?\n/g,cg=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ch=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ch.test(this.nodeName)||cg.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(cf,"\r\n")}}):{name:b.name,value:c.replace(cf,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ci(d,a[d],c,f);return e.join("&").replace(cd,"+")};var cj,ck,cl=/#.*$/,cm=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,co=/^(?:GET|HEAD)$/,cp=/^\/\//,cq=/\?/,cr=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cs=/([?&])_=[^&]*/,ct=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,cu=p.fn.load,cv={},cw={},cx=["*/"]+["*"];try{ck=f.href}catch(cy){ck=e.createElement("a"),ck.href="",ck=ck.href}cj=ct.exec(ck.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&cu)return cu.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):c&&typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cr,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cB(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cB(a,b),a},ajaxSettings:{url:ck,isLocal:cn.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cx},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cz(cv),ajaxTransport:cz(cw),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cC(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cD(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=(c||y)+"",k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cm.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(cl,"").replace(cp,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=ct.exec(l.url.toLowerCase())||!1,l.crossDomain=i&&i.join(":")+(i[3]?"":i[1]==="http:"?80:443)!==cj.join(":")+(cj[3]?"":cj[1]==="http:"?80:443)),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cA(cv,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!co.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cq.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cs,"$1_="+z);l.url=A+(A===l.url?(cq.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cx+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cA(cw,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cE=[],cF=/\?/,cG=/(=)\?(?=&|$)|\?\?/,cH=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cE.pop()||p.expando+"_"+cH++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cG.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cG.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cG,"$1"+f):m?c.data=i.replace(cG,"$1"+f):k&&(c.url+=(cF.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cE.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cI,cJ=a.ActiveXObject?function(){for(var a in cI)cI[a](0,1)}:!1,cK=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cL()||cM()}:cL,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cJ&&delete cI[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cK,cJ&&(cI||(cI={},p(a).unload(cJ)),cI[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cN,cO,cP=/^(?:toggle|show|hide)$/,cQ=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cR=/queueHooks$/,cS=[cY],cT={"*":[function(a,b){var c,d,e=this.createTween(a,b),f=cQ.exec(b),g=e.cur(),h=+g||0,i=1,j=20;if(f){c=+f[2],d=f[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&h){h=p.css(e.elem,a,!0)||c||1;do i=i||".5",h=h/i,p.style(e.elem,a,h+d);while(i!==(i=e.cur()/g)&&i!==1&&--j)}e.unit=d,e.start=h,e.end=f[1]?h+(f[1]+1)*c:c}return e}]};p.Animation=p.extend(cW,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cT[c]=cT[c]||[],cT[c].unshift(b)},prefilter:function(a,b){b?cS.unshift(a):cS.push(a)}}),p.Tween=cZ,cZ.prototype={constructor:cZ,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cZ.propHooks[this.prop];return a&&a.get?a.get(this):cZ.propHooks._default.get(this)},run:function(a){var b,c=cZ.propHooks[this.prop];return this.options.duration?this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cZ.propHooks._default.set(this),this}},cZ.prototype.init.prototype=cZ.prototype,cZ.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cZ.propHooks.scrollTop=cZ.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(c$(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bZ).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cW(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cR.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:c$("show"),slideUp:c$("hide"),slideToggle:c$("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cZ.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cO&&(cO=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cO),cO=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c_=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j={top:0,left:0},k=this[0],l=k&&k.ownerDocument;if(!l)return;return(d=l.body)===k?p.offset.bodyOffset(k):(c=l.documentElement,p.contains(c,k)?(typeof k.getBoundingClientRect!="undefined"&&(j=k.getBoundingClientRect()),e=da(l),f=c.clientTop||d.clientTop||0,g=c.clientLeft||d.clientLeft||0,h=e.pageYOffset||c.scrollTop,i=e.pageXOffset||c.scrollLeft,{top:j.top+h-f,left:j.left+i-g}):j)},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c_.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c_.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=da(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g,null)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window);
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/validate-commit-msg.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/validate-commit-msg.js
new file mode 100644
index 0000000..1a8df7f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/misc/validate-commit-msg.js
@@ -0,0 +1,106 @@
+#!/usr/bin/env node
+
+/**
+ * Git COMMIT-MSG hook for validating commit message
+ * See https://docs.google.com/document/d/1rk04jEuGfk9kYzfqCuOlPTSJw3hEDZJTBN5E5f1SALo/edit
+ *
+ * Installation:
+ * >> cd <angular-repo>
+ * >> ln -s validate-commit-msg.js .git/hooks/commit-msg
+ */
+var fs = require('fs');
+var util = require('util');
+
+
+var MAX_LENGTH = 70;
+var PATTERN = /^(?:fixup!\s*)?(\w*)(\((\w+)\))?\: (.*)$/;
+var IGNORED = /^WIP\:/;
+var TYPES = {
+ chore: true,
+ demo: true,
+ docs: true,
+ feat: true,
+ fix: true,
+ refactor: true,
+ revert: true,
+ style: true,
+ test: true
+};
+
+
+var error = function() {
+ // gitx does not display it
+ // http://gitx.lighthouseapp.com/projects/17830/tickets/294-feature-display-hook-error-message-when-hook-fails
+ // https://groups.google.com/group/gitx/browse_thread/thread/a03bcab60844b812
+ console.error('INVALID COMMIT MSG: ' + util.format.apply(null, arguments));
+};
+
+
+var validateMessage = function(message) {
+ var isValid = true;
+
+ if (IGNORED.test(message)) {
+ console.log('Commit message validation ignored.');
+ return true;
+ }
+
+ if (message.length > MAX_LENGTH) {
+ error('is longer than %d characters !', MAX_LENGTH);
+ isValid = false;
+ }
+
+ var match = PATTERN.exec(message);
+
+ if (!match) {
+ error('does not match "<type>(<scope>): <subject>" ! was: "' + message + '"\nNote: <scope> must be only letters.');
+ return false;
+ }
+
+ var type = match[1];
+ var scope = match[3];
+ var subject = match[4];
+
+ if (!TYPES.hasOwnProperty(type)) {
+ error('"%s" is not allowed type !', type);
+ return false;
+ }
+
+ // Some more ideas, do want anything like this ?
+ // - allow only specific scopes (eg. fix(docs) should not be allowed ?
+ // - auto correct the type to lower case ?
+ // - auto correct first letter of the subject to lower case ?
+ // - auto add empty line after subject ?
+ // - auto remove empty () ?
+ // - auto correct typos in type ?
+ // - store incorrect messages, so that we can learn
+
+ return isValid;
+};
+
+
+var firstLineFromBuffer = function(buffer) {
+ return buffer.toString().split('\n').shift();
+};
+
+
+
+// publish for testing
+exports.validateMessage = validateMessage;
+
+// hacky start if not run by jasmine :-D
+if (process.argv.join('').indexOf('jasmine-node') === -1) {
+ var commitMsgFile = process.argv[2];
+ var incorrectLogFile = commitMsgFile.replace('COMMIT_EDITMSG', 'logs/incorrect-commit-msgs');
+
+ fs.readFile(commitMsgFile, function(err, buffer) {
+ var msg = firstLineFromBuffer(buffer);
+
+ if (!validateMessage(msg)) {
+ fs.appendFile(incorrectLogFile, msg + '\n', function() {
+ process.exit(1);
+ });
+ } else {
+ process.exit(0);
+ }
+ });
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/package.json b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/package.json
new file mode 100644
index 0000000..0bc75a0
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/package.json
@@ -0,0 +1,39 @@
+{
+ "author": "https://github.com/angular-ui/bootstrap/graphs/contributors",
+ "name": "angular-ui-bootstrap",
+ "version": "0.14.3",
+ "homepage": "http://angular-ui.github.io/bootstrap/",
+ "dependencies": {},
+ "scripts":{
+ "test": "grunt"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/angular-ui/bootstrap.git"
+ },
+ "devDependencies": {
+ "angular": "^1.4.4",
+ "angular-mocks": "^1.4.4",
+ "angular-sanitize": "^1.4.4",
+ "grunt": "^0.4.5",
+ "grunt-contrib-concat": "^0.5.1",
+ "grunt-contrib-copy": "^0.8.0",
+ "grunt-contrib-jshint": "^0.11.1",
+ "grunt-contrib-uglify": "^0.9.1",
+ "grunt-contrib-watch": "^0.6.1",
+ "grunt-conventional-changelog": "^4.0.0",
+ "grunt-ddescribe-iit": "0.0.6",
+ "grunt-html2js": "^0.3.0",
+ "grunt-karma": "^0.12.0",
+ "jasmine-core": "^2.2.0",
+ "karma": "^0.13.3",
+ "karma-chrome-launcher": "^0.2.0",
+ "karma-coverage": "^0.5.0",
+ "karma-firefox-launcher": "^0.1.4",
+ "karma-jasmine": "^0.3.5",
+ "node-markdown": "0.1.1",
+ "semver": "^5.0.1",
+ "shelljs": "^0.5.1"
+ },
+ "license": "MIT"
+}
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/accordion.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/accordion.js
new file mode 100644
index 0000000..93a71ee
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/accordion.js
@@ -0,0 +1,249 @@
+angular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse'])
+
+.constant('uibAccordionConfig', {
+ closeOthers: true
+})
+
+.controller('UibAccordionController', ['$scope', '$attrs', 'uibAccordionConfig', function($scope, $attrs, accordionConfig) {
+ // This array keeps track of the accordion groups
+ this.groups = [];
+
+ // Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to
+ this.closeOthers = function(openGroup) {
+ var closeOthers = angular.isDefined($attrs.closeOthers) ?
+ $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers;
+ if (closeOthers) {
+ angular.forEach(this.groups, function(group) {
+ if (group !== openGroup) {
+ group.isOpen = false;
+ }
+ });
+ }
+ };
+
+ // This is called from the accordion-group directive to add itself to the accordion
+ this.addGroup = function(groupScope) {
+ var that = this;
+ this.groups.push(groupScope);
+
+ groupScope.$on('$destroy', function(event) {
+ that.removeGroup(groupScope);
+ });
+ };
+
+ // This is called from the accordion-group directive when to remove itself
+ this.removeGroup = function(group) {
+ var index = this.groups.indexOf(group);
+ if (index !== -1) {
+ this.groups.splice(index, 1);
+ }
+ };
+
+}])
+
+// The accordion directive simply sets up the directive controller
+// and adds an accordion CSS class to itself element.
+.directive('uibAccordion', function() {
+ return {
+ controller: 'UibAccordionController',
+ controllerAs: 'accordion',
+ transclude: true,
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/accordion/accordion.html';
+ }
+ };
+})
+
+// The accordion-group directive indicates a block of html that will expand and collapse in an accordion
+.directive('uibAccordionGroup', function() {
+ return {
+ require: '^uibAccordion', // We need this directive to be inside an accordion
+ transclude: true, // It transcludes the contents of the directive into the template
+ replace: true, // The element containing the directive will be replaced with the template
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/accordion/accordion-group.html';
+ },
+ scope: {
+ heading: '@', // Interpolate the heading attribute onto this scope
+ isOpen: '=?',
+ isDisabled: '=?'
+ },
+ controller: function() {
+ this.setHeading = function(element) {
+ this.heading = element;
+ };
+ },
+ link: function(scope, element, attrs, accordionCtrl) {
+ accordionCtrl.addGroup(scope);
+
+ scope.openClass = attrs.openClass || 'panel-open';
+ scope.panelClass = attrs.panelClass;
+ scope.$watch('isOpen', function(value) {
+ element.toggleClass(scope.openClass, !!value);
+ if (value) {
+ accordionCtrl.closeOthers(scope);
+ }
+ });
+
+ scope.toggleOpen = function($event) {
+ if (!scope.isDisabled) {
+ if (!$event || $event.which === 32) {
+ scope.isOpen = !scope.isOpen;
+ }
+ }
+ };
+ }
+ };
+})
+
+// Use accordion-heading below an accordion-group to provide a heading containing HTML
+.directive('uibAccordionHeading', function() {
+ return {
+ transclude: true, // Grab the contents to be used as the heading
+ template: '', // In effect remove this element!
+ replace: true,
+ require: '^uibAccordionGroup',
+ link: function(scope, element, attrs, accordionGroupCtrl, transclude) {
+ // Pass the heading to the accordion-group controller
+ // so that it can be transcluded into the right place in the template
+ // [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat]
+ accordionGroupCtrl.setHeading(transclude(scope, angular.noop));
+ }
+ };
+})
+
+// Use in the accordion-group template to indicate where you want the heading to be transcluded
+// You must provide the property on the accordion-group controller that will hold the transcluded element
+.directive('uibAccordionTransclude', function() {
+ return {
+ require: ['?^uibAccordionGroup', '?^accordionGroup'],
+ link: function(scope, element, attrs, controller) {
+ controller = controller[0] ? controller[0] : controller[1]; // Delete after we remove deprecation
+ scope.$watch(function() { return controller[attrs.uibAccordionTransclude]; }, function(heading) {
+ if (heading) {
+ element.find('span').html('');
+ element.find('span').append(heading);
+ }
+ });
+ }
+ };
+});
+
+/* Deprecated accordion below */
+
+angular.module('ui.bootstrap.accordion')
+
+ .value('$accordionSuppressWarning', false)
+
+ .controller('AccordionController', ['$scope', '$attrs', '$controller', '$log', '$accordionSuppressWarning', function($scope, $attrs, $controller, $log, $accordionSuppressWarning) {
+ if (!$accordionSuppressWarning) {
+ $log.warn('AccordionController is now deprecated. Use UibAccordionController instead.');
+ }
+
+ angular.extend(this, $controller('UibAccordionController', {
+ $scope: $scope,
+ $attrs: $attrs
+ }));
+ }])
+
+ .directive('accordion', ['$log', '$accordionSuppressWarning', function($log, $accordionSuppressWarning) {
+ return {
+ restrict: 'EA',
+ controller: 'AccordionController',
+ controllerAs: 'accordion',
+ transclude: true,
+ replace: false,
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/accordion/accordion.html';
+ },
+ link: function() {
+ if (!$accordionSuppressWarning) {
+ $log.warn('accordion is now deprecated. Use uib-accordion instead.');
+ }
+ }
+ };
+ }])
+
+ .directive('accordionGroup', ['$log', '$accordionSuppressWarning', function($log, $accordionSuppressWarning) {
+ return {
+ require: '^accordion', // We need this directive to be inside an accordion
+ restrict: 'EA',
+ transclude: true, // It transcludes the contents of the directive into the template
+ replace: true, // The element containing the directive will be replaced with the template
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/accordion/accordion-group.html';
+ },
+ scope: {
+ heading: '@', // Interpolate the heading attribute onto this scope
+ isOpen: '=?',
+ isDisabled: '=?'
+ },
+ controller: function() {
+ this.setHeading = function(element) {
+ this.heading = element;
+ };
+ },
+ link: function(scope, element, attrs, accordionCtrl) {
+ if (!$accordionSuppressWarning) {
+ $log.warn('accordion-group is now deprecated. Use uib-accordion-group instead.');
+ }
+
+ accordionCtrl.addGroup(scope);
+
+ scope.openClass = attrs.openClass || 'panel-open';
+ scope.panelClass = attrs.panelClass;
+ scope.$watch('isOpen', function(value) {
+ element.toggleClass(scope.openClass, !!value);
+ if (value) {
+ accordionCtrl.closeOthers(scope);
+ }
+ });
+
+ scope.toggleOpen = function($event) {
+ if (!scope.isDisabled) {
+ if (!$event || $event.which === 32) {
+ scope.isOpen = !scope.isOpen;
+ }
+ }
+ };
+ }
+ };
+ }])
+
+ .directive('accordionHeading', ['$log', '$accordionSuppressWarning', function($log, $accordionSuppressWarning) {
+ return {
+ restrict: 'EA',
+ transclude: true, // Grab the contents to be used as the heading
+ template: '', // In effect remove this element!
+ replace: true,
+ require: '^accordionGroup',
+ link: function(scope, element, attr, accordionGroupCtrl, transclude) {
+ if (!$accordionSuppressWarning) {
+ $log.warn('accordion-heading is now deprecated. Use uib-accordion-heading instead.');
+ }
+ // Pass the heading to the accordion-group controller
+ // so that it can be transcluded into the right place in the template
+ // [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat]
+ accordionGroupCtrl.setHeading(transclude(scope, angular.noop));
+ }
+ };
+ }])
+
+ .directive('accordionTransclude', ['$log', '$accordionSuppressWarning', function($log, $accordionSuppressWarning) {
+ return {
+ require: '^accordionGroup',
+ link: function(scope, element, attr, controller) {
+ if (!$accordionSuppressWarning) {
+ $log.warn('accordion-transclude is now deprecated. Use uib-accordion-transclude instead.');
+ }
+
+ scope.$watch(function() { return controller[attr.accordionTransclude]; }, function(heading) {
+ if (heading) {
+ element.find('span').html('');
+ element.find('span').append(heading);
+ }
+ });
+ }
+ };
+ }]);
+
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/docs/demo.html
new file mode 100644
index 0000000..d72479e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/docs/demo.html
@@ -0,0 +1,53 @@
+<div ng-controller="AccordionDemoCtrl">
+ <script type="text/ng-template" id="group-template.html">
+ <div class="panel {{panelClass || 'panel-default'}}">
+ <div class="panel-heading">
+ <h4 class="panel-title" style="color:#fa39c3">
+ <a href tabindex="0" class="accordion-toggle" ng-click="toggleOpen()" uib-accordion-transclude="heading"><span
+ ng-class="{'text-muted': isDisabled}">{{heading}}</span></a>
+ </h4>
+ </div>
+ <div class="panel-collapse collapse" uib-collapse="!isOpen">
+ <div class="panel-body" style="text-align: right" ng-transclude></div>
+ </div>
+ </div>
+ </script>
+
+ <p>
+ <button type="button" class="btn btn-default btn-sm" ng-click="status.open = !status.open">Toggle last panel</button>
+ <button type="button" class="btn btn-default btn-sm" ng-click="status.isFirstDisabled = ! status.isFirstDisabled">Enable / Disable first panel</button>
+ </p>
+
+ <div class="checkbox">
+ <label>
+ <input type="checkbox" ng-model="oneAtATime">
+ Open only one at a time
+ </label>
+ </div>
+ <uib-accordion close-others="oneAtATime">
+ <uib-accordion-group heading="Static Header, initially expanded" is-open="status.isFirstOpen" is-disabled="status.isFirstDisabled">
+ This content is straight in the template.
+ </uib-accordion-group>
+ <uib-accordion-group heading="{{group.title}}" ng-repeat="group in groups">
+ {{group.content}}
+ </uib-accordion-group>
+ <uib-accordion-group heading="Dynamic Body Content">
+ <p>The body of the uib-accordion group grows to fit the contents</p>
+ <button type="button" class="btn btn-default btn-sm" ng-click="addItem()">Add Item</button>
+ <div ng-repeat="item in items">{{item}}</div>
+ </uib-accordion-group>
+ <uib-accordion-group heading="Custom template" template-url="group-template.html">
+ Hello
+ </uib-accordion-group>
+ <uib-accordion-group heading="Delete account" panel-class="panel-danger">
+ <p>Please, to delete your account, click the button below</p>
+ <button class="btn btn-danger">Delete</button>
+ </uib-accordion-group>
+ <uib-accordion-group is-open="status.open">
+ <uib-accordion-heading>
+ I can have markup, too! <i class="pull-right glyphicon" ng-class="{'glyphicon-chevron-down': status.open, 'glyphicon-chevron-right': !status.open}"></i>
+ </uib-accordion-heading>
+ This is just some content to illustrate fancy headings.
+ </uib-accordion-group>
+ </uib-accordion>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/docs/demo.js
new file mode 100644
index 0000000..390bc03
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/docs/demo.js
@@ -0,0 +1,26 @@
+angular.module('ui.bootstrap.demo').controller('AccordionDemoCtrl', function ($scope) {
+ $scope.oneAtATime = true;
+
+ $scope.groups = [
+ {
+ title: 'Dynamic Group Header - 1',
+ content: 'Dynamic Group Body - 1'
+ },
+ {
+ title: 'Dynamic Group Header - 2',
+ content: 'Dynamic Group Body - 2'
+ }
+ ];
+
+ $scope.items = ['Item 1', 'Item 2', 'Item 3'];
+
+ $scope.addItem = function() {
+ var newItemNo = $scope.items.length + 1;
+ $scope.items.push('Item ' + newItemNo);
+ };
+
+ $scope.status = {
+ isFirstOpen: true,
+ isFirstDisabled: false
+ };
+});
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/docs/readme.md
new file mode 100644
index 0000000..1da9f22
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/docs/readme.md
@@ -0,0 +1,47 @@
+The **accordion directive** builds on top of the collapse directive to provide a list of items, with collapsible bodies that are collapsed or expanded by clicking on the item's header.
+
+The body of each accordion group is transcluded into the body of the collapsible element.
+
+### uib-accordion settings
+
+* `close-others`
+ _(Default: `true`)_ -
+ Control whether expanding an item will cause the other items to close.
+
+* `template-url`
+ _(Default: `template/accordion/accordion.html`)_ -
+ Add the ability to override the template used on the component.
+
+### uib-accordion-group settings
+
+* `is-disabled`
+ <i class="glyphicon glyphicon-eye-open"></i>
+ _(Default: `false`)_ -
+ Whether the accordion group is disabled or not.
+
+* `is-open`
+ <i class="glyphicon glyphicon-eye-open"></i>
+ _(Default: `false`)_ -
+ Whether accordion group is open or closed.
+
+* `heading`
+ _(Default: `none`)_ -
+ The clickable text on the group's header. You need one to be able to click on the header for toggling.
+
+* `panel-class`
+ _(Default: `panel-default`)_ -
+ Add ability to use Bootstrap's contextual panel classes (panel-primary, panel-success, panel-info, etc...) or your own. This must be a string.
+
+* `template-url`
+ _(Default: `template/accordion/accordion-group.html`)_ -
+ Add the ability to override the template used on the component.
+
+### Default settings `uibAccordionConfig`
+
+* `closeOthers`
+ _(Default: `true`)_ -
+ Control whether expanding an item will cause the other items to close.
+
+### Accordion heading
+
+Instead of the `heading` attribute on the `uib-accordion-group`, you can use an `uib-accordion-heading` element inside a group that will be used as the group's header.
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/test/accordion.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/test/accordion.spec.js
new file mode 100644
index 0000000..f7b669b
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/accordion/test/accordion.spec.js
@@ -0,0 +1,635 @@
+describe('uib-accordion', function() {
+ var $animate, $scope;
+
+ beforeEach(module('ui.bootstrap.accordion'));
+ beforeEach(module('ngAnimateMock'));
+ beforeEach(module('template/accordion/accordion.html'));
+ beforeEach(module('template/accordion/accordion-group.html'));
+
+ beforeEach(inject(function(_$animate_, $rootScope) {
+ $animate = _$animate_;
+ $scope = $rootScope;
+ }));
+
+ describe('controller', function () {
+ var ctrl, $element, $attrs;
+ beforeEach(inject(function($controller) {
+ $attrs = {};
+ ctrl = $controller('UibAccordionController', { $scope: $scope, $attrs: $attrs });
+ }));
+
+ describe('addGroup', function() {
+ it('adds a the specified panel to the collection', function() {
+ var group1, group2;
+ ctrl.addGroup(group1 = $scope.$new());
+ ctrl.addGroup(group2 = $scope.$new());
+ expect(ctrl.groups.length).toBe(2);
+ expect(ctrl.groups[0]).toBe(group1);
+ expect(ctrl.groups[1]).toBe(group2);
+ });
+ });
+
+ describe('closeOthers', function() {
+ var group1, group2, group3;
+ beforeEach(function() {
+ ctrl.addGroup(group1 = { isOpen: true, $on : angular.noop });
+ ctrl.addGroup(group2 = { isOpen: true, $on : angular.noop });
+ ctrl.addGroup(group3 = { isOpen: true, $on : angular.noop });
+ });
+ it('should close other panels if close-others attribute is not defined', function() {
+ delete $attrs.closeOthers;
+ ctrl.closeOthers(group2);
+ expect(group1.isOpen).toBe(false);
+ expect(group2.isOpen).toBe(true);
+ expect(group3.isOpen).toBe(false);
+ });
+
+ it('should close other panels if close-others attribute is true', function() {
+ $attrs.closeOthers = 'true';
+ ctrl.closeOthers(group3);
+ expect(group1.isOpen).toBe(false);
+ expect(group2.isOpen).toBe(false);
+ expect(group3.isOpen).toBe(true);
+ });
+
+ it('should not close other panels if close-others attribute is false', function() {
+ $attrs.closeOthers = 'false';
+ ctrl.closeOthers(group2);
+ expect(group1.isOpen).toBe(true);
+ expect(group2.isOpen).toBe(true);
+ expect(group3.isOpen).toBe(true);
+ });
+
+ describe('setting accordionConfig', function() {
+ var originalCloseOthers;
+ beforeEach(inject(function(uibAccordionConfig) {
+ originalCloseOthers = uibAccordionConfig.closeOthers;
+ uibAccordionConfig.closeOthers = false;
+ }));
+ afterEach(inject(function(uibAccordionConfig) {
+ // return it to the original value
+ uibAccordionConfig.closeOthers = originalCloseOthers;
+ }));
+
+ it('should not close other panels if accordionConfig.closeOthers is false', function() {
+ ctrl.closeOthers(group2);
+ expect(group1.isOpen).toBe(true);
+ expect(group2.isOpen).toBe(true);
+ expect(group3.isOpen).toBe(true);
+ });
+ });
+ });
+
+ describe('removeGroup', function() {
+ it('should remove the specified panel', function() {
+ var group1, group2, group3;
+ ctrl.addGroup(group1 = $scope.$new());
+ ctrl.addGroup(group2 = $scope.$new());
+ ctrl.addGroup(group3 = $scope.$new());
+ ctrl.removeGroup(group2);
+ expect(ctrl.groups.length).toBe(2);
+ expect(ctrl.groups[0]).toBe(group1);
+ expect(ctrl.groups[1]).toBe(group3);
+ });
+ it('should ignore remove of non-existing panel', function() {
+ var group1, group2;
+ ctrl.addGroup(group1 = $scope.$new());
+ ctrl.addGroup(group2 = $scope.$new());
+ expect(ctrl.groups.length).toBe(2);
+ ctrl.removeGroup({});
+ expect(ctrl.groups.length).toBe(2);
+ });
+ it('should remove a panel when the scope is destroyed', function() {
+ var group1, group2, group3;
+ ctrl.addGroup(group1 = $scope.$new());
+ ctrl.addGroup(group2 = $scope.$new());
+ ctrl.addGroup(group3 = $scope.$new());
+ group2.$destroy();
+ expect(ctrl.groups.length).toBe(2);
+ expect(ctrl.groups[0]).toBe(group1);
+ expect(ctrl.groups[1]).toBe(group3);
+ });
+ });
+ });
+
+ describe('uib-accordion', function() {
+ var scope, $compile, $templateCache, element;
+
+ beforeEach(inject(function($rootScope, _$compile_, _$templateCache_) {
+ scope = $rootScope;
+ $compile = _$compile_;
+ $templateCache = _$templateCache_;
+ }));
+
+ it('should expose the controller on the view', function() {
+ $templateCache.put('template/accordion/accordion.html', '<div>{{accordion.text}}</div>');
+
+ element = $compile('<uib-accordion></uib-accordion>')(scope);
+ scope.$digest();
+
+ var ctrl = element.controller('uibAccordion');
+ expect(ctrl).toBeDefined();
+
+ ctrl.text = 'foo';
+ scope.$digest();
+
+ expect(element.html()).toBe('<div class="ng-binding">foo</div>');
+ });
+
+ it('should allow custom templates', function() {
+ $templateCache.put('foo/bar.html', '<div>baz</div>');
+
+ element = $compile('<accordion template-url="foo/bar.html"></accordion>')(scope);
+ scope.$digest();
+ expect(element.html()).toBe('<div>baz</div>');
+ });
+ });
+
+ describe('uib-accordion-group', function() {
+
+ var scope, $compile;
+ var element, groups;
+ var findGroupLink = function(index) {
+ return groups.eq(index).find('a').eq(0);
+ };
+ var findGroupBody = function(index) {
+ return groups.eq(index).find('.panel-collapse').eq(0);
+ };
+
+ beforeEach(inject(function(_$rootScope_, _$compile_) {
+ scope = _$rootScope_;
+ $compile = _$compile_;
+ }));
+
+ it('should allow custom templates', inject(function($templateCache) {
+ $templateCache.put('foo/bar.html', '<div>baz</div>');
+
+ var tpl =
+ '<uib-accordion>' +
+ '<uib-accordion-group heading="title 1" template-url="foo/bar.html"></uib-accordion-group>' +
+ '</uib-accordion>';
+
+ element = $compile(tpl)(scope);
+ scope.$digest();
+ expect(element.find('[template-url]').html()).toBe('baz');
+ }));
+
+ describe('with static panels', function() {
+ beforeEach(function() {
+ var tpl =
+ '<uib-accordion>' +
+ '<uib-accordion-group heading="title 1">Content 1</uib-accordion-group>' +
+ '<uib-accordion-group heading="title 2">Content 2</uib-accordion-group>' +
+ '</uib-accordion>';
+ element = angular.element(tpl);
+ $compile(element)(scope);
+ scope.$digest();
+ groups = element.find('.panel');
+ });
+ afterEach(function() {
+ element.remove();
+ });
+
+ it('should create accordion panels with content', function() {
+ expect(groups.length).toEqual(2);
+ expect(findGroupLink(0).text()).toEqual('title 1');
+ expect(findGroupBody(0).text().trim()).toEqual('Content 1');
+ expect(findGroupLink(1).text()).toEqual('title 2');
+ expect(findGroupBody(1).text().trim()).toEqual('Content 2');
+ });
+
+ it('should change selected element on click', function() {
+ findGroupLink(0).click();
+ scope.$digest();
+ expect(findGroupBody(0).scope().isOpen).toBe(true);
+
+ findGroupLink(1).click();
+ scope.$digest();
+ expect(findGroupBody(0).scope().isOpen).toBe(false);
+ expect(findGroupBody(1).scope().isOpen).toBe(true);
+ });
+
+ it('should toggle element on click', function() {
+ findGroupLink(0).click();
+ scope.$digest();
+ expect(findGroupBody(0).scope().isOpen).toBe(true);
+ findGroupLink(0).click();
+ scope.$digest();
+ expect(findGroupBody(0).scope().isOpen).toBe(false);
+ });
+
+ it('should add, by default, "panel-open" when opened', function() {
+ var group = groups.eq(0);
+ findGroupLink(0).click();
+ scope.$digest();
+ expect(group).toHaveClass('panel-open');
+
+ findGroupLink(0).click();
+ scope.$digest();
+ expect(group).not.toHaveClass('panel-open');
+ });
+
+ it('should toggle element on spacebar when focused', function() {
+ var group = groups.eq(0);
+ findGroupLink(0)[0].focus();
+ var e = $.Event('keypress');
+ e.which = 32;
+ findGroupLink(0).trigger(e);
+
+ expect(group).toHaveClass('panel-open');
+
+ e = $.Event('keypress');
+ e.which = 32;
+ findGroupLink(0).trigger(e);
+
+ expect(group).not.toHaveClass('panel-open');
+ });
+
+ it('should not toggle with any other keyCode', function() {
+ var group = groups.eq(0);
+ findGroupLink(0)[0].focus();
+ var e = $.Event('keypress');
+ e.which = 65;
+ findGroupLink(0).trigger(e);
+
+ expect(group).not.toHaveClass('panel-open');
+ });
+ });
+
+ describe('with open-class attribute', function() {
+ beforeEach(function() {
+ var tpl =
+ '<uib-accordion>' +
+ '<uib-accordion-group heading="title 1" open-class="custom-open-class">Content 1</uib-accordion-group>' +
+ '<uib-accordion-group heading="title 2" open-class="custom-open-class">Content 2</uib-accordion-group>' +
+ '</uib-accordion>';
+ element = angular.element(tpl);
+ $compile(element)(scope);
+ scope.$digest();
+ groups = element.find('.panel');
+ });
+ afterEach(function() {
+ element.remove();
+ });
+
+ it('should add custom-open-class when opened', function() {
+ var group = groups.eq(0);
+ findGroupLink(0).click();
+ scope.$digest();
+ expect(group).toHaveClass('custom-open-class');
+
+ findGroupLink(0).click();
+ scope.$digest();
+ expect(group).not.toHaveClass('custom-open-class');
+ });
+ });
+
+ describe('with dynamic panels', function() {
+ var model;
+ beforeEach(function() {
+ var tpl =
+ '<uib-accordion>' +
+ '<uib-accordion-group ng-repeat="group in groups" heading="{{group.name}}">{{group.content}}</uib-accordion-group>' +
+ '</uib-accordion>';
+ element = angular.element(tpl);
+ model = [
+ {name: 'title 1', content: 'Content 1'},
+ {name: 'title 2', content: 'Content 2'}
+ ];
+
+ $compile(element)(scope);
+ scope.$digest();
+ });
+
+ it('should have no panels initially', function() {
+ groups = element.find('.panel');
+ expect(groups.length).toEqual(0);
+ });
+
+ it('should have a panel for each model item', function() {
+ scope.groups = model;
+ scope.$digest();
+ groups = element.find('.panel');
+ expect(groups.length).toEqual(2);
+ expect(findGroupLink(0).text()).toEqual('title 1');
+ expect(findGroupBody(0).text().trim()).toEqual('Content 1');
+ expect(findGroupLink(1).text()).toEqual('title 2');
+ expect(findGroupBody(1).text().trim()).toEqual('Content 2');
+ });
+
+ it('should react properly on removing items from the model', function() {
+ scope.groups = model;
+ scope.$digest();
+ groups = element.find('.panel');
+ expect(groups.length).toEqual(2);
+
+ scope.groups.splice(0,1);
+ scope.$digest();
+ groups = element.find('.panel');
+ expect(groups.length).toEqual(1);
+ });
+ });
+
+ describe('is-open attribute', function() {
+ beforeEach(function() {
+ var tpl =
+ '<uib-accordion>' +
+ '<uib-accordion-group heading="title 1" is-open="open.first">Content 1</uib-accordion-group>' +
+ '<uib-accordion-group heading="title 2" is-open="open.second">Content 2</uib-accordion-group>' +
+ '</uib-accordion>';
+ element = angular.element(tpl);
+ scope.open = { first: false, second: true };
+ $compile(element)(scope);
+ scope.$digest();
+ groups = element.find('.panel');
+ });
+
+ it('should open the panel with isOpen set to true', function() {
+ expect(findGroupBody(0).scope().isOpen).toBe(false);
+ expect(findGroupBody(1).scope().isOpen).toBe(true);
+ });
+
+ it('should toggle variable on element click', function() {
+ findGroupLink(0).click();
+ scope.$digest();
+ expect(scope.open.first).toBe(true);
+
+ findGroupLink(0).click();
+ scope.$digest();
+ expect(scope.open.second).toBe(false);
+ });
+ });
+
+ describe('is-open attribute with dynamic content', function() {
+ beforeEach(function() {
+ var tpl =
+ '<uib-accordion>' +
+ '<uib-accordion-group heading="title 1" is-open="open1"><div ng-repeat="item in items">{{item}}</div></uib-accordion-group>' +
+ '<uib-accordion-group heading="title 2" is-open="open2">Static content</uib-accordion-group>' +
+ '</uib-accordion>';
+ element = angular.element(tpl);
+ scope.items = ['Item 1', 'Item 2', 'Item 3'];
+ scope.open1 = true;
+ scope.open2 = false;
+ angular.element(document.body).append(element);
+ $compile(element)(scope);
+ scope.$digest();
+ $animate.flush();
+ groups = element.find('.panel');
+ });
+
+ afterEach(function() {
+ element.remove();
+ });
+
+ it('should have visible panel body when the group with isOpen set to true', function() {
+ expect(findGroupBody(0)).toHaveClass('in');
+ expect(findGroupBody(1)).not.toHaveClass('in');
+ });
+ });
+
+ describe('is-open attribute with dynamic groups', function() {
+ beforeEach(function() {
+ var tpl =
+ '<uib-accordion>' +
+ '<uib-accordion-group ng-repeat="group in groups" heading="{{group.name}}" is-open="group.open">{{group.content}}</uib-accordion-group>' +
+ '</uib-accordion>';
+ element = angular.element(tpl);
+ scope.groups = [
+ {name: 'title 1', content: 'Content 1', open: false},
+ {name: 'title 2', content: 'Content 2', open: true}
+ ];
+ $compile(element)(scope);
+ scope.$digest();
+
+ groups = element.find('.panel');
+ });
+
+ it('should have visible group body when the group with isOpen set to true', function() {
+ expect(findGroupBody(0).scope().isOpen).toBe(false);
+ expect(findGroupBody(1).scope().isOpen).toBe(true);
+ });
+
+ it('should toggle element on click', function() {
+ findGroupLink(0).click();
+ scope.$digest();
+ expect(findGroupBody(0).scope().isOpen).toBe(true);
+ expect(scope.groups[0].open).toBe(true);
+
+ findGroupLink(0).click();
+ scope.$digest();
+ expect(findGroupBody(0).scope().isOpen).toBe(false);
+ expect(scope.groups[0].open).toBe(false);
+ });
+ });
+
+ describe('`is-disabled` attribute', function() {
+ var groupBody;
+ beforeEach(function() {
+ var tpl =
+ '<uib-accordion>' +
+ '<uib-accordion-group heading="title 1" is-disabled="disabled">Content 1</uib-accordion-group>' +
+ '</uib-accordion>';
+ element = angular.element(tpl);
+ scope.disabled = true;
+ $compile(element)(scope);
+ scope.$digest();
+ groups = element.find('.panel');
+ groupBody = findGroupBody(0);
+ });
+
+ it('should open the panel with isOpen set to true', function() {
+ expect(groupBody.scope().isOpen).toBeFalsy();
+ });
+
+ it('should not toggle if disabled', function() {
+ findGroupLink(0).click();
+ scope.$digest();
+ expect(groupBody.scope().isOpen).toBeFalsy();
+ });
+
+ it('should toggle after enabling', function() {
+ scope.disabled = false;
+ scope.$digest();
+ expect(groupBody.scope().isOpen).toBeFalsy();
+
+ findGroupLink(0).click();
+ scope.$digest();
+ expect(groupBody.scope().isOpen).toBeTruthy();
+ });
+
+ it('should have text-muted styling', function() {
+ expect(findGroupLink(0).find('span:first')).toHaveClass('text-muted');
+ });
+ });
+
+ // This is re-used in both the uib-accordion-heading element and the uib-accordion-heading attribute tests
+ function isDisabledStyleCheck() {
+ var tpl =
+ '<uib-accordion ng-init="a = [1,2,3]">' +
+ '<uib-accordion-group heading="I get overridden" is-disabled="true">' +
+ '<uib-accordion-heading>Heading Element <span ng-repeat="x in a">{{x}}</span> </uib-accordion-heading>' +
+ 'Body' +
+ '</uib-accordion-group>' +
+ '</uib-accordion>';
+ scope.disabled = true;
+ element = $compile(tpl)(scope);
+ scope.$digest();
+ groups = element.find('.panel');
+
+ expect(findGroupLink(0).find('span').hasClass('text-muted')).toBe(true);
+ }
+
+ describe('uib-accordion-heading element', function() {
+ beforeEach(function() {
+ var tpl =
+ '<uib-accordion ng-init="a = [1,2,3]">' +
+ '<uib-accordion-group heading="I get overridden">' +
+ '<uib-accordion-heading>Heading Element <span ng-repeat="x in a">{{x}}</span> </uib-accordion-heading>' +
+ 'Body' +
+ '</uib-accordion-group>' +
+ '</uib-accordion>';
+ element = $compile(tpl)(scope);
+ scope.$digest();
+ groups = element.find('.panel');
+ });
+
+ it('transcludes the <uib-accordion-heading> content into the heading link', function() {
+ expect(findGroupLink(0).text()).toBe('Heading Element 123 ');
+ });
+
+ it('attaches the same scope to the transcluded heading and body', function() {
+ expect(findGroupLink(0).find('span.ng-scope').scope().$id).toBe(findGroupBody(0).find('span').scope().$id);
+ });
+
+ it('should wrap the transcluded content in a span', function() {
+ expect(findGroupLink(0).find('span:first').length).toEqual(1);
+ });
+
+ it('should have disabled styling when is-disabled is true', isDisabledStyleCheck);
+
+ });
+
+ describe('uib-accordion-heading attribute', function() {
+ beforeEach(function() {
+ var tpl =
+ '<uib-accordion ng-init="a = [1,2,3]">' +
+ '<uib-accordion-group heading="I get overridden">' +
+ '<div uib-accordion-heading>Heading Element <span ng-repeat="x in a">{{x}}</span> </div>' +
+ 'Body' +
+ '</uib-accordion-group>' +
+ '</uib-accordion>';
+ element = $compile(tpl)(scope);
+ scope.$digest();
+ groups = element.find('.panel');
+ });
+
+ it('transcludes the <uib-accordion-heading> content into the heading link', function() {
+ expect(findGroupLink(0).text()).toBe('Heading Element 123 ');
+ });
+
+ it('attaches the same scope to the transcluded heading and body', function() {
+ expect(findGroupLink(0).find('span.ng-scope').scope().$id).toBe(findGroupBody(0).find('span').scope().$id);
+ });
+
+ it('should have disabled styling when is-disabled is true', isDisabledStyleCheck);
+
+ });
+
+ describe('uib-accordion-heading, with repeating uib-accordion-groups', function() {
+ it('should clone the uib-accordion-heading for each group', function() {
+ element = $compile('<uib-accordion><uib-accordion-group ng-repeat="x in [1,2,3]"><uib-accordion-heading>{{x}}</uib-accordion-heading></uib-accordion-group></uib-accordion>')(scope);
+ scope.$digest();
+ groups = element.find('.panel');
+ expect(groups.length).toBe(3);
+ expect(findGroupLink(0).text()).toBe('1');
+ expect(findGroupLink(1).text()).toBe('2');
+ expect(findGroupLink(2).text()).toBe('3');
+ });
+ });
+
+ describe('uib-accordion-heading attribute, with repeating uib-accordion-groups', function() {
+ it('should clone the uib-accordion-heading for each group', function() {
+ element = $compile('<uib-accordion><uib-accordion-group ng-repeat="x in [1,2,3]"><div uib-accordion-heading>{{x}}</div></uib-accordion-group></uib-accordion>')(scope);
+ scope.$digest();
+ groups = element.find('.panel');
+ expect(groups.length).toBe(3);
+ expect(findGroupLink(0).text()).toBe('1');
+ expect(findGroupLink(1).text()).toBe('2');
+ expect(findGroupLink(2).text()).toBe('3');
+ });
+ });
+
+ describe('uib-accordion group panel class - #3968', function() {
+ it('should use the default value when panel class is falsy', function() {
+ element = $compile('<uib-accordion><uib-accordion-group heading="Heading">Content</uib-accordion-group></uib-accordion>')(scope);
+ scope.$digest();
+ groups = element.find('.panel');
+ expect(groups.eq(0)).toHaveClass('panel-default');
+
+ element = $compile('<uib-accordion><uib-accordion-group heading="Heading" panel-class="">Content</uib-accordion-group></uib-accordion>')(scope);
+ scope.$digest();
+ groups = element.find('.panel');
+ expect(groups.eq(0)).toHaveClass('panel-default');
+ });
+
+ it('should use the specified value when not falsy', function() {
+ element = $compile('<uib-accordion><uib-accordion-group heading="Heading" panel-class="custom-class">Content</uib-accordion-group></uib-accordion>')(scope);
+ scope.$digest();
+ groups = element.find('.panel');
+ expect(groups.eq(0)).toHaveClass('custom-class');
+ expect(groups.eq(0)).not.toHaveClass('panel-default');
+ });
+ });
+ });
+});
+
+/* Deprecation tests below */
+
+describe('accordion deprecation', function() {
+ beforeEach(module('ui.bootstrap.accordion'));
+ beforeEach(module('ngAnimateMock'));
+ beforeEach(module('template/accordion/accordion.html'));
+ beforeEach(module('template/accordion/accordion-group.html'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$accordionSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element =
+ '<accordion ng-init="a = [1,2,3]">' +
+ '<accordion-group heading="I get overridden">' +
+ '<div accordion-heading>Heading Element <span ng-repeat="x in a">{{x}}</span> </div>' +
+ 'Body' +
+ '</accordion-group>' +
+ '</accordion>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element =
+ '<accordion ng-init="a = [1,2,3]">' +
+ '<accordion-group heading="I get overridden">' +
+ '<div accordion-heading>Heading Element <span ng-repeat="x in a">{{x}}</span> </div>' +
+ 'Body' +
+ '</accordion-group>' +
+ '</accordion>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(4);
+ expect($log.warn.calls.argsFor(0)).toEqual(['AccordionController is now deprecated. Use UibAccordionController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['accordion-heading is now deprecated. Use uib-accordion-heading instead.']);
+ expect($log.warn.calls.argsFor(2)).toEqual(['accordion-group is now deprecated. Use uib-accordion-group instead.']);
+ expect($log.warn.calls.argsFor(3)).toEqual(['accordion is now deprecated. Use uib-accordion instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/alert.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/alert.js
new file mode 100644
index 0000000..4b007c6
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/alert.js
@@ -0,0 +1,68 @@
+angular.module('ui.bootstrap.alert', [])
+
+.controller('UibAlertController', ['$scope', '$attrs', '$interpolate', '$timeout', function($scope, $attrs, $interpolate, $timeout) {
+ $scope.closeable = !!$attrs.close;
+
+ var dismissOnTimeout = angular.isDefined($attrs.dismissOnTimeout) ?
+ $interpolate($attrs.dismissOnTimeout)($scope.$parent) : null;
+
+ if (dismissOnTimeout) {
+ $timeout(function() {
+ $scope.close();
+ }, parseInt(dismissOnTimeout, 10));
+ }
+}])
+
+.directive('uibAlert', function() {
+ return {
+ controller: 'UibAlertController',
+ controllerAs: 'alert',
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/alert/alert.html';
+ },
+ transclude: true,
+ replace: true,
+ scope: {
+ type: '@',
+ close: '&'
+ }
+ };
+});
+
+/* Deprecated alert below */
+
+angular.module('ui.bootstrap.alert')
+
+ .value('$alertSuppressWarning', false)
+
+ .controller('AlertController', ['$scope', '$attrs', '$controller', '$log', '$alertSuppressWarning', function($scope, $attrs, $controller, $log, $alertSuppressWarning) {
+ if (!$alertSuppressWarning) {
+ $log.warn('AlertController is now deprecated. Use UibAlertController instead.');
+ }
+
+ angular.extend(this, $controller('UibAlertController', {
+ $scope: $scope,
+ $attrs: $attrs
+ }));
+ }])
+
+ .directive('alert', ['$log', '$alertSuppressWarning', function($log, $alertSuppressWarning) {
+ return {
+ controller: 'AlertController',
+ controllerAs: 'alert',
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/alert/alert.html';
+ },
+ transclude: true,
+ replace: true,
+ scope: {
+ type: '@',
+ close: '&'
+ },
+ link: function() {
+ if (!$alertSuppressWarning) {
+ $log.warn('alert is now deprecated. Use uib-alert instead.');
+ }
+ }
+ };
+ }]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/docs/demo.html
new file mode 100644
index 0000000..e2ce4b3
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/docs/demo.html
@@ -0,0 +1,11 @@
+<div ng-controller="AlertDemoCtrl">
+ <script type="text/ng-template" id="alert.html">
+ <div class="alert" style="background-color:#fa39c3;color:white" role="alert">
+ <div ng-transclude></div>
+ </div>
+ </script>
+
+ <uib-alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</uib-alert>
+ <uib-alert template-url="alert.html">A happy alert!</uib-alert>
+ <button type="button" class='btn btn-default' ng-click="addAlert()">Add Alert</button>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/docs/demo.js
new file mode 100644
index 0000000..267a3ae
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/docs/demo.js
@@ -0,0 +1,14 @@
+angular.module('ui.bootstrap.demo').controller('AlertDemoCtrl', function ($scope) {
+ $scope.alerts = [
+ { type: 'danger', msg: 'Oh snap! Change a few things up and try submitting again.' },
+ { type: 'success', msg: 'Well done! You successfully read this important alert message.' }
+ ];
+
+ $scope.addAlert = function() {
+ $scope.alerts.push({msg: 'Another alert!'});
+ };
+
+ $scope.closeAlert = function(index) {
+ $scope.alerts.splice(index, 1);
+ };
+});
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/docs/readme.md
new file mode 100644
index 0000000..6d81bd4
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/docs/readme.md
@@ -0,0 +1,12 @@
+This directive can be used both to generate alerts from static and dynamic model data (using the `ng-repeat` directive).
+
+### uib-alert settings
+
+ * `close` _(Default: `none`)_ -
+ A callback function that gets fired when an `alert` is closed. If the attribute exists, a close button is displayed as well.
+ * `dismiss-on-timeout` _(Default: `none`)(Optional)_ -
+ Takes the number of milliseconds that specify the timeout duration, after which the alert will be closed. This attribute requires the presence of the `close` attribute.
+ * `template-url` _(Default: `template/alert/alert.html`)_ -
+ Add the ability to override the template used in the component.
+ * `type` _(Default: `warning`)_ -
+ Defines the type of the alert. Go to [bootstrap page](http://getbootstrap.com/components/#alerts) to see the type of alerts available.
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/test/alert.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/test/alert.spec.js
new file mode 100644
index 0000000..9946906
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/alert/test/alert.spec.js
@@ -0,0 +1,186 @@
+describe('uib-alert', function() {
+ var element, scope, $compile, $templateCache, $timeout;
+
+ beforeEach(module('ui.bootstrap.alert'));
+ beforeEach(module('template/alert/alert.html'));
+
+ beforeEach(inject(function($rootScope, _$compile_, _$templateCache_, _$timeout_) {
+ scope = $rootScope;
+ $compile = _$compile_;
+ $templateCache = _$templateCache_;
+ $timeout = _$timeout_;
+
+ element = angular.element(
+ '<div>' +
+ '<uib-alert ng-repeat="alert in alerts" type="{{alert.type}}"' +
+ 'close="removeAlert($index)">{{alert.msg}}' +
+ '</uib-alert>' +
+ '</div>');
+
+ scope.alerts = [
+ { msg:'foo', type:'success'},
+ { msg:'bar', type:'error'},
+ { msg:'baz'}
+ ];
+ }));
+
+ function createAlerts() {
+ $compile(element)(scope);
+ scope.$digest();
+ return element.find('.alert');
+ }
+
+ function findCloseButton(index) {
+ return element.find('.close').eq(index);
+ }
+
+ function findContent(index) {
+ return element.find('div[ng-transclude] span').eq(index);
+ }
+
+ it('should expose the controller to the view', function() {
+ $templateCache.put('template/alert/alert.html', '<div>{{alert.text}}</div>');
+
+ element = $compile('<uib-alert></uib-alert>')(scope);
+ scope.$digest();
+
+ var ctrl = element.controller('uib-alert');
+ expect(ctrl).toBeDefined();
+
+ ctrl.text = 'foo';
+ scope.$digest();
+
+ expect(element.html()).toBe('foo');
+ });
+
+ it('should support custom templates', function() {
+ $templateCache.put('foo/bar.html', '<div>baz</div>');
+
+ element = $compile('<uib-alert template-url="foo/bar.html"></uib-alert>')(scope);
+ scope.$digest();
+
+ expect(element.html()).toBe('baz');
+ });
+
+ it('should generate alerts using ng-repeat', function() {
+ var alerts = createAlerts();
+ expect(alerts.length).toEqual(3);
+ });
+
+ it('should use correct classes for different alert types', function() {
+ var alerts = createAlerts();
+ expect(alerts.eq(0)).toHaveClass('alert-success');
+ expect(alerts.eq(1)).toHaveClass('alert-error');
+ expect(alerts.eq(2)).toHaveClass('alert-warning');
+ });
+
+ it('should respect alert type binding', function() {
+ var alerts = createAlerts();
+ expect(alerts.eq(0)).toHaveClass('alert-success');
+
+ scope.alerts[0].type = 'error';
+ scope.$digest();
+
+ expect(alerts.eq(0)).toHaveClass('alert-error');
+ });
+
+ it('should show the alert content', function() {
+ var alerts = createAlerts();
+
+ for (var i = 0, n = alerts.length; i < n; i++) {
+ expect(findContent(i).text()).toBe(scope.alerts[i].msg);
+ }
+ });
+
+ it('should show close buttons and have the dismissible class', function() {
+ var alerts = createAlerts();
+
+ for (var i = 0, n = alerts.length; i < n; i++) {
+ expect(findCloseButton(i).css('display')).not.toBe('none');
+ expect(alerts.eq(i)).toHaveClass('alert-dismissible');
+ }
+ });
+
+ it('should fire callback when closed', function() {
+ var alerts = createAlerts();
+
+ scope.$apply(function() {
+ scope.removeAlert = jasmine.createSpy();
+ });
+
+ expect(findCloseButton(0).css('display')).not.toBe('none');
+ findCloseButton(1).click();
+
+ expect(scope.removeAlert).toHaveBeenCalledWith(1);
+ });
+
+ it('should not show close button and have the dismissible class if no close callback specified', function() {
+ element = $compile('<uib-alert>No close</uib-alert>')(scope);
+ scope.$digest();
+ expect(findCloseButton(0)).toBeHidden();
+ expect(element).not.toHaveClass('alert-dismissible');
+ });
+
+ it('should be possible to add additional classes for alert', function() {
+ var element = $compile('<uib-alert class="alert-block" type="info">Default alert!</uib-alert>')(scope);
+ scope.$digest();
+ expect(element).toHaveClass('alert-block');
+ expect(element).toHaveClass('alert-info');
+ });
+
+ it('should close automatically if dismiss-on-timeout is defined on the element', function() {
+ scope.removeAlert = jasmine.createSpy();
+ $compile('<uib-alert close="removeAlert()" dismiss-on-timeout="500">Default alert!</uib-alert>')(scope);
+ scope.$digest();
+
+ $timeout.flush();
+ expect(scope.removeAlert).toHaveBeenCalled();
+ });
+
+ it('should not close immediately with a dynamic dismiss-on-timeout', function() {
+ scope.removeAlert = jasmine.createSpy();
+ scope.dismissTime = 500;
+ $compile('<uib-alert close="removeAlert()" dismiss-on-timeout="{{dismissTime}}">Default alert!</uib-alert>')(scope);
+ scope.$digest();
+
+ $timeout.flush(100);
+ expect(scope.removeAlert).not.toHaveBeenCalled();
+
+ $timeout.flush(500);
+ expect(scope.removeAlert).toHaveBeenCalled();
+ });
+});
+
+/* Deprecation tests below */
+
+describe('alert deprecation', function() {
+ beforeEach(module('ui.bootstrap.alert'));
+ beforeEach(module('template/alert/alert.html'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$alertSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = '<alert></alert>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = '<alert></alert>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(2);
+ expect($log.warn.calls.argsFor(0)).toEqual(['AlertController is now deprecated. Use UibAlertController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['alert is now deprecated. Use uib-alert instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/buttons.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/buttons.js
new file mode 100644
index 0000000..14ed715
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/buttons.js
@@ -0,0 +1,199 @@
+angular.module('ui.bootstrap.buttons', [])
+
+.constant('uibButtonConfig', {
+ activeClass: 'active',
+ toggleEvent: 'click'
+})
+
+.controller('UibButtonsController', ['uibButtonConfig', function(buttonConfig) {
+ this.activeClass = buttonConfig.activeClass || 'active';
+ this.toggleEvent = buttonConfig.toggleEvent || 'click';
+}])
+
+.directive('uibBtnRadio', function() {
+ return {
+ require: ['uibBtnRadio', 'ngModel'],
+ controller: 'UibButtonsController',
+ controllerAs: 'buttons',
+ link: function(scope, element, attrs, ctrls) {
+ var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+
+ element.find('input').css({display: 'none'});
+
+ //model -> UI
+ ngModelCtrl.$render = function() {
+ element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.uibBtnRadio)));
+ };
+
+ //ui->model
+ element.on(buttonsCtrl.toggleEvent, function() {
+ if (attrs.disabled) {
+ return;
+ }
+
+ var isActive = element.hasClass(buttonsCtrl.activeClass);
+
+ if (!isActive || angular.isDefined(attrs.uncheckable)) {
+ scope.$apply(function() {
+ ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.uibBtnRadio));
+ ngModelCtrl.$render();
+ });
+ }
+ });
+ }
+ };
+})
+
+.directive('uibBtnCheckbox', function() {
+ return {
+ require: ['uibBtnCheckbox', 'ngModel'],
+ controller: 'UibButtonsController',
+ controllerAs: 'button',
+ link: function(scope, element, attrs, ctrls) {
+ var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+
+ element.find('input').css({display: 'none'});
+
+ function getTrueValue() {
+ return getCheckboxValue(attrs.btnCheckboxTrue, true);
+ }
+
+ function getFalseValue() {
+ return getCheckboxValue(attrs.btnCheckboxFalse, false);
+ }
+
+ function getCheckboxValue(attribute, defaultValue) {
+ return angular.isDefined(attribute) ? scope.$eval(attribute) : defaultValue;
+ }
+
+ //model -> UI
+ ngModelCtrl.$render = function() {
+ element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue()));
+ };
+
+ //ui->model
+ element.on(buttonsCtrl.toggleEvent, function() {
+ if (attrs.disabled) {
+ return;
+ }
+
+ scope.$apply(function() {
+ ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());
+ ngModelCtrl.$render();
+ });
+ });
+ }
+ };
+});
+
+/* Deprecated buttons below */
+
+angular.module('ui.bootstrap.buttons')
+
+ .value('$buttonsSuppressWarning', false)
+
+ .controller('ButtonsController', ['$controller', '$log', '$buttonsSuppressWarning', function($controller, $log, $buttonsSuppressWarning) {
+ if (!$buttonsSuppressWarning) {
+ $log.warn('ButtonsController is now deprecated. Use UibButtonsController instead.');
+ }
+
+ angular.extend(this, $controller('UibButtonsController'));
+ }])
+
+ .directive('btnRadio', ['$log', '$buttonsSuppressWarning', function($log, $buttonsSuppressWarning) {
+ return {
+ require: ['btnRadio', 'ngModel'],
+ controller: 'ButtonsController',
+ controllerAs: 'buttons',
+ link: function(scope, element, attrs, ctrls) {
+ if (!$buttonsSuppressWarning) {
+ $log.warn('btn-radio is now deprecated. Use uib-btn-radio instead.');
+ }
+
+ var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+
+ element.find('input').css({display: 'none'});
+
+ //model -> UI
+ ngModelCtrl.$render = function() {
+ element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio)));
+ };
+
+ //ui->model
+ element.bind(buttonsCtrl.toggleEvent, function() {
+ if (attrs.disabled) {
+ return;
+ }
+
+ var isActive = element.hasClass(buttonsCtrl.activeClass);
+
+ if (!isActive || angular.isDefined(attrs.uncheckable)) {
+ scope.$apply(function() {
+ ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.btnRadio));
+ ngModelCtrl.$render();
+ });
+ }
+ });
+ }
+ };
+ }])
+
+ .directive('btnCheckbox', ['$document', '$log', '$buttonsSuppressWarning', function($document, $log, $buttonsSuppressWarning) {
+ return {
+ require: ['btnCheckbox', 'ngModel'],
+ controller: 'ButtonsController',
+ controllerAs: 'button',
+ link: function(scope, element, attrs, ctrls) {
+ if (!$buttonsSuppressWarning) {
+ $log.warn('btn-checkbox is now deprecated. Use uib-btn-checkbox instead.');
+ }
+
+ var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+
+ element.find('input').css({display: 'none'});
+
+ function getTrueValue() {
+ return getCheckboxValue(attrs.btnCheckboxTrue, true);
+ }
+
+ function getFalseValue() {
+ return getCheckboxValue(attrs.btnCheckboxFalse, false);
+ }
+
+ function getCheckboxValue(attributeValue, defaultValue) {
+ var val = scope.$eval(attributeValue);
+ return angular.isDefined(val) ? val : defaultValue;
+ }
+
+ //model -> UI
+ ngModelCtrl.$render = function() {
+ element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue()));
+ };
+
+ //ui->model
+ element.bind(buttonsCtrl.toggleEvent, function() {
+ if (attrs.disabled) {
+ return;
+ }
+
+ scope.$apply(function() {
+ ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());
+ ngModelCtrl.$render();
+ });
+ });
+
+ //accessibility
+ element.on('keypress', function(e) {
+ if (attrs.disabled || e.which !== 32 || $document[0].activeElement !== element[0]) {
+ return;
+ }
+
+ scope.$apply(function() {
+ ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());
+ ngModelCtrl.$render();
+ });
+ });
+ }
+ };
+ }]);
+
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/docs/demo.html
new file mode 100644
index 0000000..72b0b39
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/docs/demo.html
@@ -0,0 +1,27 @@
+<div ng-controller="ButtonsCtrl">
+ <h4>Single toggle</h4>
+ <pre>{{singleModel}}</pre>
+ <button type="button" class="btn btn-primary" ng-model="singleModel" uib-btn-checkbox btn-checkbox-true="1" btn-checkbox-false="0">
+ Single Toggle
+ </button>
+ <h4>Checkbox</h4>
+ <pre>Model: {{checkModel}}</pre>
+ <pre>Results: {{checkResults}}</pre>
+ <div class="btn-group">
+ <label class="btn btn-primary" ng-model="checkModel.left" uib-btn-checkbox>Left</label>
+ <label class="btn btn-primary" ng-model="checkModel.middle" uib-btn-checkbox>Middle</label>
+ <label class="btn btn-primary" ng-model="checkModel.right" uib-btn-checkbox>Right</label>
+ </div>
+ <h4>Radio & Uncheckable Radio</h4>
+ <pre>{{radioModel || 'null'}}</pre>
+ <div class="btn-group">
+ <label class="btn btn-primary" ng-model="radioModel" uib-btn-radio="'Left'">Left</label>
+ <label class="btn btn-primary" ng-model="radioModel" uib-btn-radio="'Middle'">Middle</label>
+ <label class="btn btn-primary" ng-model="radioModel" uib-btn-radio="'Right'">Right</label>
+ </div>
+ <div class="btn-group">
+ <label class="btn btn-success" ng-model="radioModel" uib-btn-radio="'Left'" uncheckable>Left</label>
+ <label class="btn btn-success" ng-model="radioModel" uib-btn-radio="'Middle'" uncheckable>Middle</label>
+ <label class="btn btn-success" ng-model="radioModel" uib-btn-radio="'Right'" uncheckable>Right</label>
+ </div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/docs/demo.js
new file mode 100644
index 0000000..3d5760f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/docs/demo.js
@@ -0,0 +1,22 @@
+angular.module('ui.bootstrap.demo').controller('ButtonsCtrl', function ($scope) {
+ $scope.singleModel = 1;
+
+ $scope.radioModel = 'Middle';
+
+ $scope.checkModel = {
+ left: false,
+ middle: true,
+ right: false
+ };
+
+ $scope.checkResults = [];
+
+ $scope.$watchCollection('checkModel', function () {
+ $scope.checkResults = [];
+ angular.forEach($scope.checkModel, function (value, key) {
+ if (value) {
+ $scope.checkResults.push(key);
+ }
+ });
+ });
+});
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/docs/readme.md
new file mode 100644
index 0000000..9367d50
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/docs/readme.md
@@ -0,0 +1,36 @@
+With the buttons directive, we can make a group of buttons behave like a set of checkboxes (`uib-btn-checkbox`) or behave like a set of radio buttons (`uib-btn-radio`).
+
+### uib-btn-checkbox settings
+
+* `ng-model` -
+ Model where we set the checkbox status. By default `true` or `false`.
+
+* `btn-checkbox-true`
+ _(Default: `true`)_ -
+ Sets the value for the checked status.
+
+* `btn-checkbox-false`
+ _(Default: `false`)_ -
+ Sets the value for the unchecked status.
+
+### uib-btn-radio settings
+
+* `uib-btn-radio` -
+ Value to assign to the `ng-model` if we check this radio button.
+
+* `ng-model` -
+ Model where we set the radio status. All radio buttons in a group should use the same `ng-model`.
+
+* `uncheckable`
+ _(Boolean attribute)_ -
+ Whether a radio button can be unchecked or not.
+
+### Default settings `uibButtonConfig`
+
+* `activeClass`
+ _(Default: `active`)_ -
+ Class to apply to the checked buttons.
+
+* `toggleEvent`
+ _(Default: `click`)_ -
+ Event used to toggle the buttons.
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/test/buttons.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/test/buttons.spec.js
new file mode 100644
index 0000000..5cc81c5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/buttons/test/buttons.spec.js
@@ -0,0 +1,371 @@
+describe('buttons', function() {
+
+ var $scope, $compile;
+
+ beforeEach(module('ui.bootstrap.buttons'));
+ beforeEach(inject(function(_$rootScope_, _$compile_) {
+ $scope = _$rootScope_;
+ $compile = _$compile_;
+ }));
+
+ describe('checkbox', function() {
+ var compileButton = function(markup, scope) {
+ var el = $compile(markup)(scope);
+ scope.$digest();
+ return el;
+ };
+
+ it('should expose the controller to the view', inject(function($templateCache) {
+ var btn = compileButton('<button ng-model="model" uib-btn-checkbox>{{button.text}}</button>', $scope);
+ var ctrl = btn.controller('uibBtnCheckbox');
+ expect(ctrl).toBeDefined();
+
+ ctrl.text = 'foo';
+ $scope.$digest();
+
+ expect(btn.html()).toBe('foo');
+ }));
+
+ //model -> UI
+ it('should work correctly with default model values', function() {
+ $scope.model = false;
+ var btn = compileButton('<button ng-model="model" uib-btn-checkbox>click</button>', $scope);
+ expect(btn).not.toHaveClass('active');
+
+ $scope.model = true;
+ $scope.$digest();
+ expect(btn).toHaveClass('active');
+ });
+
+ it('should bind custom model values', function() {
+ $scope.model = 1;
+ var btn = compileButton('<button ng-model="model" uib-btn-checkbox btn-checkbox-true="1" btn-checkbox-false="0">click</button>', $scope);
+ expect(btn).toHaveClass('active');
+
+ $scope.model = 0;
+ $scope.$digest();
+ expect(btn).not.toHaveClass('active');
+ });
+
+ //UI-> model
+ it('should toggle default model values on click', function() {
+ $scope.model = false;
+ var btn = compileButton('<button ng-model="model" uib-btn-checkbox>click</button>', $scope);
+
+ btn.click();
+ expect($scope.model).toEqual(true);
+ expect(btn).toHaveClass('active');
+
+ btn.click();
+ expect($scope.model).toEqual(false);
+ expect(btn).not.toHaveClass('active');
+ });
+
+ it('should toggle custom model values on click', function() {
+ $scope.model = 0;
+ var btn = compileButton('<button ng-model="model" uib-btn-checkbox btn-checkbox-true="1" btn-checkbox-false="0">click</button>', $scope);
+
+ btn.click();
+ expect($scope.model).toEqual(1);
+ expect(btn).toHaveClass('active');
+
+ btn.click();
+ expect($scope.model).toEqual(0);
+ expect(btn).not.toHaveClass('active');
+ });
+
+ it('should monitor true / false value changes - issue 666', function() {
+
+ $scope.model = 1;
+ $scope.trueVal = 1;
+ var btn = compileButton('<button ng-model="model" uib-btn-checkbox btn-checkbox-true="trueVal">click</button>', $scope);
+
+ expect(btn).toHaveClass('active');
+ expect($scope.model).toEqual(1);
+
+ $scope.model = 2;
+ $scope.trueVal = 2;
+ $scope.$digest();
+
+ expect(btn).toHaveClass('active');
+ expect($scope.model).toEqual(2);
+ });
+
+ it('should not toggle when disabled - issue 4013', function() {
+ $scope.model = 1;
+ $scope.falseVal = 0;
+ var btn = compileButton('<button disabled ng-model="model" uib-btn-checkbox btn-checkbox-true="falseVal">click</button>', $scope);
+
+ expect(btn).not.toHaveClass('active');
+ expect($scope.model).toEqual(1);
+
+ btn.click();
+
+ expect(btn).not.toHaveClass('active');
+
+ $scope.$digest();
+
+ expect(btn).not.toHaveClass('active');
+ });
+
+ describe('setting buttonConfig', function() {
+ var uibButtonConfig, originalActiveClass, originalToggleEvent;
+
+ beforeEach(inject(function(_uibButtonConfig_) {
+ uibButtonConfig = _uibButtonConfig_;
+ originalActiveClass = uibButtonConfig.activeClass;
+ originalToggleEvent = uibButtonConfig.toggleEvent;
+ uibButtonConfig.activeClass = false;
+ uibButtonConfig.toggleEvent = false;
+ }));
+
+ afterEach(function() {
+ // return it to the original value
+ uibButtonConfig.activeClass = originalActiveClass;
+ uibButtonConfig.toggleEvent = originalToggleEvent;
+ });
+
+ it('should use default config when buttonConfig.activeClass and buttonConfig.toggleEvent is false', function() {
+ $scope.model = false;
+ var btn = compileButton('<button ng-model="model" uib-btn-checkbox>click</button>', $scope);
+ expect(btn).not.toHaveClass('active');
+
+ $scope.model = true;
+ $scope.$digest();
+ expect(btn).toHaveClass('active');
+ });
+
+ it('should be able to use a different active class', function() {
+ uibButtonConfig.activeClass = 'foo';
+ $scope.model = false;
+ var btn = compileButton('<button ng-model="model" uib-btn-checkbox>click</button>', $scope);
+ expect(btn).not.toHaveClass('foo');
+
+ $scope.model = true;
+ $scope.$digest();
+ expect(btn).toHaveClass('foo');
+ });
+
+ it('should be able to use a different toggle event', function() {
+ uibButtonConfig.toggleEvent = 'mouseenter';
+ $scope.model = false;
+ var btn = compileButton('<button ng-model="model" uib-btn-checkbox>click</button>', $scope);
+ expect(btn).not.toHaveClass('active');
+
+ btn.trigger('mouseenter');
+
+ $scope.$digest();
+ expect(btn).toHaveClass('active');
+ });
+ });
+
+ });
+
+ describe('radio', function() {
+
+ var compileButtons = function(markup, scope) {
+ var el = $compile('<div>'+markup+'</div>')(scope);
+ scope.$digest();
+ return el.find('button');
+ };
+
+ it('should expose the controller to the view', inject(function($templateCache) {
+ var btn = compileButtons('<button ng-model="model" uib-btn-radio="1">{{buttons.text}}</button>', $scope);
+ var ctrl = btn.controller('uibBtnRadio');
+ expect(ctrl).toBeDefined();
+
+ ctrl.text = 'foo';
+ $scope.$digest();
+
+ expect(btn.html()).toBe('foo');
+ }));
+
+ //model -> UI
+ it('should set active class based on model', function() {
+ var btns = compileButtons('<button ng-model="model" uib-btn-radio="1">click1</button><button ng-model="model" uib-btn-radio="2">click2</button>', $scope);
+ expect(btns.eq(0)).not.toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+
+ $scope.model = 2;
+ $scope.$digest();
+ expect(btns.eq(0)).not.toHaveClass('active');
+ expect(btns.eq(1)).toHaveClass('active');
+ });
+
+ //UI->model
+ it('should set active class via click', function() {
+ var btns = compileButtons('<button ng-model="model" uib-btn-radio="1">click1</button><button ng-model="model" uib-btn-radio="2">click2</button>', $scope);
+ expect($scope.model).toBeUndefined();
+
+ btns.eq(0).click();
+ expect($scope.model).toEqual(1);
+ expect(btns.eq(0)).toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+
+ btns.eq(1).click();
+ expect($scope.model).toEqual(2);
+ expect(btns.eq(1)).toHaveClass('active');
+ expect(btns.eq(0)).not.toHaveClass('active');
+ });
+
+ it('should watch uib-btn-radio values and update state accordingly', function() {
+ $scope.values = ['value1', 'value2'];
+
+ var btns = compileButtons('<button ng-model="model" uib-btn-radio="values[0]">click1</button><button ng-model="model" uib-btn-radio="values[1]">click2</button>', $scope);
+ expect(btns.eq(0)).not.toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+
+ $scope.model = 'value2';
+ $scope.$digest();
+ expect(btns.eq(0)).not.toHaveClass('active');
+ expect(btns.eq(1)).toHaveClass('active');
+
+ $scope.values[1] = 'value3';
+ $scope.model = 'value3';
+ $scope.$digest();
+ expect(btns.eq(0)).not.toHaveClass('active');
+ expect(btns.eq(1)).toHaveClass('active');
+ });
+
+ it('should do nothing when clicking an active radio', function() {
+ $scope.model = 1;
+ var btns = compileButtons('<button ng-model="model" uib-btn-radio="1">click1</button><button ng-model="model" uib-btn-radio="2">click2</button>', $scope);
+ expect(btns.eq(0)).toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+
+ btns.eq(0).click();
+ $scope.$digest();
+ expect(btns.eq(0)).toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+ });
+
+ it('should not toggle when disabled - issue 4013', function() {
+ $scope.model = 1;
+ var btns = compileButtons('<button ng-model="model" uib-btn-radio="1">click1</button><button disabled ng-model="model" uib-btn-radio="2">click2</button>', $scope);
+
+ expect(btns.eq(0)).toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+
+ btns.eq(1).click();
+
+ expect(btns.eq(0)).toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+
+ $scope.$digest();
+
+ expect(btns.eq(0)).toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+ });
+
+ it('should handle string values in uib-btn-radio value', function() {
+ $scope.model = 'Two';
+ var btns = compileButtons('<button ng-model="model" uib-btn-radio="\'One\'">click1</button><button ng-model="model" uib-btn-radio="\'Two\'">click2</button>', $scope);
+
+ expect(btns.eq(0)).not.toHaveClass('active');
+ expect(btns.eq(1)).toHaveClass('active');
+
+ btns.eq(0).click();
+ expect(btns.eq(0)).toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+ expect($scope.model).toEqual('One');
+
+ $scope.$digest();
+
+ expect(btns.eq(0)).toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+ expect($scope.model).toEqual('One');
+ });
+
+ describe('uncheckable', function() {
+ //model -> UI
+ it('should set active class based on model', function() {
+ var btns = compileButtons('<button ng-model="model" uib-btn-radio="1" uncheckable>click1</button><button ng-model="model" uib-btn-radio="2" uncheckable>click2</button>', $scope);
+ expect(btns.eq(0)).not.toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+
+ $scope.model = 2;
+ $scope.$digest();
+ expect(btns.eq(0)).not.toHaveClass('active');
+ expect(btns.eq(1)).toHaveClass('active');
+ });
+
+ //UI->model
+ it('should unset active class via click', function() {
+ var btns = compileButtons('<button ng-model="model" uib-btn-radio="1" uncheckable>click1</button><button ng-model="model" uib-btn-radio="2" uncheckable>click2</button>', $scope);
+ expect($scope.model).toBeUndefined();
+
+ btns.eq(0).click();
+ expect($scope.model).toEqual(1);
+ expect(btns.eq(0)).toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+
+ btns.eq(0).click();
+ expect($scope.model).toBeNull();
+ expect(btns.eq(1)).not.toHaveClass('active');
+ expect(btns.eq(0)).not.toHaveClass('active');
+ });
+
+ it('should watch uib-btn-radio values and update state', function() {
+ $scope.values = ['value1', 'value2'];
+
+ var btns = compileButtons('<button ng-model="model" uib-btn-radio="values[0]" uncheckable>click1</button><button ng-model="model" uib-btn-radio="values[1]" uncheckable>click2</button>', $scope);
+ expect(btns.eq(0)).not.toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+
+ $scope.model = 'value2';
+ $scope.$digest();
+ expect(btns.eq(0)).not.toHaveClass('active');
+ expect(btns.eq(1)).toHaveClass('active');
+
+ $scope.model = undefined;
+ $scope.$digest();
+ expect(btns.eq(0)).not.toHaveClass('active');
+ expect(btns.eq(1)).not.toHaveClass('active');
+ });
+ });
+ });
+});
+
+/* Deprecation tests below */
+
+describe('buttons deprecation', function() {
+ beforeEach(module('ui.bootstrap.buttons'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$buttonsSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = $compile('<button ng-model="model" btn-checkbox>click</button>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(0);
+
+ element = $compile('<button ng-model="model" btn-radio="1">click1</button><button ng-model="model" btn-radio="2">click2</button>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = $compile('<button ng-model="model" btn-checkbox>click</button>')($rootScope);
+ $rootScope.$digest();
+
+ element = $compile('<button ng-model="model" btn-radio="1">click1</button><button ng-model="model" btn-radio="2">click2</button>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(6);
+ expect($log.warn.calls.argsFor(0)).toEqual(['ButtonsController is now deprecated. Use UibButtonsController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['btn-checkbox is now deprecated. Use uib-btn-checkbox instead.']);
+ expect($log.warn.calls.argsFor(2)).toEqual(['ButtonsController is now deprecated. Use UibButtonsController instead.']);
+ expect($log.warn.calls.argsFor(3)).toEqual(['btn-radio is now deprecated. Use uib-btn-radio instead.']);
+ expect($log.warn.calls.argsFor(4)).toEqual(['ButtonsController is now deprecated. Use UibButtonsController instead.']);
+ expect($log.warn.calls.argsFor(5)).toEqual(['btn-radio is now deprecated. Use uib-btn-radio instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/carousel.css b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/carousel.css
new file mode 100644
index 0000000..061b304
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/carousel.css
@@ -0,0 +1,4 @@
+.ng-animate.item:not(.left):not(.right) {
+ -webkit-transition: 0s ease-in-out left;
+ transition: 0s ease-in-out left
+}
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/carousel.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/carousel.js
new file mode 100644
index 0000000..a3cb2aa
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/carousel.js
@@ -0,0 +1,496 @@
+/**
+ * @ngdoc overview
+ * @name ui.bootstrap.carousel
+ *
+ * @description
+ * AngularJS version of an image carousel.
+ *
+ */
+angular.module('ui.bootstrap.carousel', [])
+
+.controller('UibCarouselController', ['$scope', '$element', '$interval', '$animate', function($scope, $element, $interval, $animate) {
+ var self = this,
+ slides = self.slides = $scope.slides = [],
+ NEW_ANIMATE = angular.version.minor >= 4,
+ NO_TRANSITION = 'uib-noTransition',
+ SLIDE_DIRECTION = 'uib-slideDirection',
+ currentIndex = -1,
+ currentInterval, isPlaying;
+ self.currentSlide = null;
+
+ var destroyed = false;
+ /* direction: "prev" or "next" */
+ self.select = $scope.select = function(nextSlide, direction) {
+ var nextIndex = $scope.indexOfSlide(nextSlide);
+ //Decide direction if it's not given
+ if (direction === undefined) {
+ direction = nextIndex > self.getCurrentIndex() ? 'next' : 'prev';
+ }
+ //Prevent this user-triggered transition from occurring if there is already one in progress
+ if (nextSlide && nextSlide !== self.currentSlide && !$scope.$currentTransition) {
+ goNext(nextSlide, nextIndex, direction);
+ }
+ };
+
+ function goNext(slide, index, direction) {
+ // Scope has been destroyed, stop here.
+ if (destroyed) { return; }
+
+ angular.extend(slide, {direction: direction, active: true});
+ angular.extend(self.currentSlide || {}, {direction: direction, active: false});
+ if ($animate.enabled() && !$scope.noTransition && !$scope.$currentTransition &&
+ slide.$element && self.slides.length > 1) {
+ slide.$element.data(SLIDE_DIRECTION, slide.direction);
+ if (self.currentSlide && self.currentSlide.$element) {
+ self.currentSlide.$element.data(SLIDE_DIRECTION, slide.direction);
+ }
+
+ $scope.$currentTransition = true;
+ if (NEW_ANIMATE) {
+ $animate.on('addClass', slide.$element, function(element, phase) {
+ if (phase === 'close') {
+ $scope.$currentTransition = null;
+ $animate.off('addClass', element);
+ }
+ });
+ } else {
+ slide.$element.one('$animate:close', function closeFn() {
+ $scope.$currentTransition = null;
+ });
+ }
+ }
+
+ self.currentSlide = slide;
+ currentIndex = index;
+
+ //every time you change slides, reset the timer
+ restartTimer();
+ }
+
+ $scope.$on('$destroy', function() {
+ destroyed = true;
+ });
+
+ function getSlideByIndex(index) {
+ if (angular.isUndefined(slides[index].index)) {
+ return slides[index];
+ }
+ var i, len = slides.length;
+ for (i = 0; i < slides.length; ++i) {
+ if (slides[i].index == index) {
+ return slides[i];
+ }
+ }
+ }
+
+ self.getCurrentIndex = function() {
+ if (self.currentSlide && angular.isDefined(self.currentSlide.index)) {
+ return +self.currentSlide.index;
+ }
+ return currentIndex;
+ };
+
+ /* Allow outside people to call indexOf on slides array */
+ $scope.indexOfSlide = function(slide) {
+ return angular.isDefined(slide.index) ? +slide.index : slides.indexOf(slide);
+ };
+
+ $scope.next = function() {
+ var newIndex = (self.getCurrentIndex() + 1) % slides.length;
+
+ if (newIndex === 0 && $scope.noWrap()) {
+ $scope.pause();
+ return;
+ }
+
+ return self.select(getSlideByIndex(newIndex), 'next');
+ };
+
+ $scope.prev = function() {
+ var newIndex = self.getCurrentIndex() - 1 < 0 ? slides.length - 1 : self.getCurrentIndex() - 1;
+
+ if ($scope.noWrap() && newIndex === slides.length - 1) {
+ $scope.pause();
+ return;
+ }
+
+ return self.select(getSlideByIndex(newIndex), 'prev');
+ };
+
+ $scope.isActive = function(slide) {
+ return self.currentSlide === slide;
+ };
+
+ $scope.$watch('interval', restartTimer);
+ $scope.$watchCollection('slides', resetTransition);
+ $scope.$on('$destroy', resetTimer);
+
+ function restartTimer() {
+ resetTimer();
+ var interval = +$scope.interval;
+ if (!isNaN(interval) && interval > 0) {
+ currentInterval = $interval(timerFn, interval);
+ }
+ }
+
+ function resetTimer() {
+ if (currentInterval) {
+ $interval.cancel(currentInterval);
+ currentInterval = null;
+ }
+ }
+
+ function timerFn() {
+ var interval = +$scope.interval;
+ if (isPlaying && !isNaN(interval) && interval > 0 && slides.length) {
+ $scope.next();
+ } else {
+ $scope.pause();
+ }
+ }
+
+ function resetTransition(slides) {
+ if (!slides.length) {
+ $scope.$currentTransition = null;
+ }
+ }
+
+ $scope.play = function() {
+ if (!isPlaying) {
+ isPlaying = true;
+ restartTimer();
+ }
+ };
+ $scope.pause = function() {
+ if (!$scope.noPause) {
+ isPlaying = false;
+ resetTimer();
+ }
+ };
+
+ self.addSlide = function(slide, element) {
+ slide.$element = element;
+ slides.push(slide);
+ //if this is the first slide or the slide is set to active, select it
+ if (slides.length === 1 || slide.active) {
+ self.select(slides[slides.length - 1]);
+ if (slides.length === 1) {
+ $scope.play();
+ }
+ } else {
+ slide.active = false;
+ }
+ };
+
+ self.removeSlide = function(slide) {
+ if (angular.isDefined(slide.index)) {
+ slides.sort(function(a, b) {
+ return +a.index > +b.index;
+ });
+ }
+ //get the index of the slide inside the carousel
+ var index = slides.indexOf(slide);
+ slides.splice(index, 1);
+ if (slides.length > 0 && slide.active) {
+ if (index >= slides.length) {
+ self.select(slides[index - 1]);
+ } else {
+ self.select(slides[index]);
+ }
+ } else if (currentIndex > index) {
+ currentIndex--;
+ }
+
+ //clean the currentSlide when no more slide
+ if (slides.length === 0) {
+ self.currentSlide = null;
+ }
+ };
+
+ $scope.$watch('noTransition', function(noTransition) {
+ $element.data(NO_TRANSITION, noTransition);
+ });
+
+}])
+
+/**
+ * @ngdoc directive
+ * @name ui.bootstrap.carousel.directive:carousel
+ * @restrict EA
+ *
+ * @description
+ * Carousel is the outer container for a set of image 'slides' to showcase.
+ *
+ * @param {number=} interval The time, in milliseconds, that it will take the carousel to go to the next slide.
+ * @param {boolean=} noTransition Whether to disable transitions on the carousel.
+ * @param {boolean=} noPause Whether to disable pausing on the carousel (by default, the carousel interval pauses on hover).
+ *
+ * @example
+<example module="ui.bootstrap">
+ <file name="index.html">
+ <uib-carousel>
+ <uib-slide>
+ <img src="http://placekitten.com/150/150" style="margin:auto;">
+ <div class="carousel-caption">
+ <p>Beautiful!</p>
+ </div>
+ </uib-slide>
+ <uib-slide>
+ <img src="http://placekitten.com/100/150" style="margin:auto;">
+ <div class="carousel-caption">
+ <p>D'aww!</p>
+ </div>
+ </uib-slide>
+ </uib-carousel>
+ </file>
+ <file name="demo.css">
+ .carousel-indicators {
+ top: auto;
+ bottom: 15px;
+ }
+ </file>
+</example>
+ */
+.directive('uibCarousel', [function() {
+ return {
+ transclude: true,
+ replace: true,
+ controller: 'UibCarouselController',
+ controllerAs: 'carousel',
+ require: 'carousel',
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/carousel/carousel.html';
+ },
+ scope: {
+ interval: '=',
+ noTransition: '=',
+ noPause: '=',
+ noWrap: '&'
+ }
+ };
+}])
+
+/**
+ * @ngdoc directive
+ * @name ui.bootstrap.carousel.directive:slide
+ * @restrict EA
+ *
+ * @description
+ * Creates a slide inside a {@link ui.bootstrap.carousel.directive:carousel carousel}. Must be placed as a child of a carousel element.
+ *
+ * @param {boolean=} active Model binding, whether or not this slide is currently active.
+ * @param {number=} index The index of the slide. The slides will be sorted by this parameter.
+ *
+ * @example
+<example module="ui.bootstrap">
+ <file name="index.html">
+<div ng-controller="CarouselDemoCtrl">
+ <uib-carousel>
+ <uib-slide ng-repeat="slide in slides" active="slide.active" index="$index">
+ <img ng-src="{{slide.image}}" style="margin:auto;">
+ <div class="carousel-caption">
+ <h4>Slide {{$index}}</h4>
+ <p>{{slide.text}}</p>
+ </div>
+ </uib-slide>
+ </uib-carousel>
+ Interval, in milliseconds: <input type="number" ng-model="myInterval">
+ <br />Enter a negative number to stop the interval.
+</div>
+ </file>
+ <file name="script.js">
+function CarouselDemoCtrl($scope) {
+ $scope.myInterval = 5000;
+}
+ </file>
+ <file name="demo.css">
+ .carousel-indicators {
+ top: auto;
+ bottom: 15px;
+ }
+ </file>
+</example>
+*/
+
+.directive('uibSlide', function() {
+ return {
+ require: '^uibCarousel',
+ restrict: 'EA',
+ transclude: true,
+ replace: true,
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/carousel/slide.html';
+ },
+ scope: {
+ active: '=?',
+ actual: '=?',
+ index: '=?'
+ },
+ link: function (scope, element, attrs, carouselCtrl) {
+ carouselCtrl.addSlide(scope, element);
+ //when the scope is destroyed then remove the slide from the current slides array
+ scope.$on('$destroy', function() {
+ carouselCtrl.removeSlide(scope);
+ });
+
+ scope.$watch('active', function(active) {
+ if (active) {
+ carouselCtrl.select(scope);
+ }
+ });
+ }
+ };
+})
+
+.animation('.item', [
+ '$injector', '$animate',
+function ($injector, $animate) {
+ var NO_TRANSITION = 'uib-noTransition',
+ SLIDE_DIRECTION = 'uib-slideDirection',
+ $animateCss = null;
+
+ if ($injector.has('$animateCss')) {
+ $animateCss = $injector.get('$animateCss');
+ }
+
+ function removeClass(element, className, callback) {
+ element.removeClass(className);
+ if (callback) {
+ callback();
+ }
+ }
+
+ return {
+ beforeAddClass: function(element, className, done) {
+ // Due to transclusion, noTransition property is on parent's scope
+ if (className == 'active' && element.parent() && element.parent().parent() &&
+ !element.parent().parent().data(NO_TRANSITION)) {
+ var stopped = false;
+ var direction = element.data(SLIDE_DIRECTION);
+ var directionClass = direction == 'next' ? 'left' : 'right';
+ var removeClassFn = removeClass.bind(this, element,
+ directionClass + ' ' + direction, done);
+ element.addClass(direction);
+
+ if ($animateCss) {
+ $animateCss(element, {addClass: directionClass})
+ .start()
+ .done(removeClassFn);
+ } else {
+ $animate.addClass(element, directionClass).then(function () {
+ if (!stopped) {
+ removeClassFn();
+ }
+ done();
+ });
+ }
+
+ return function () {
+ stopped = true;
+ };
+ }
+ done();
+ },
+ beforeRemoveClass: function (element, className, done) {
+ // Due to transclusion, noTransition property is on parent's scope
+ if (className === 'active' && element.parent() && element.parent().parent() &&
+ !element.parent().parent().data(NO_TRANSITION)) {
+ var stopped = false;
+ var direction = element.data(SLIDE_DIRECTION);
+ var directionClass = direction == 'next' ? 'left' : 'right';
+ var removeClassFn = removeClass.bind(this, element, directionClass, done);
+
+ if ($animateCss) {
+ $animateCss(element, {addClass: directionClass})
+ .start()
+ .done(removeClassFn);
+ } else {
+ $animate.addClass(element, directionClass).then(function() {
+ if (!stopped) {
+ removeClassFn();
+ }
+ done();
+ });
+ }
+ return function() {
+ stopped = true;
+ };
+ }
+ done();
+ }
+ };
+}]);
+
+/* deprecated carousel below */
+
+angular.module('ui.bootstrap.carousel')
+
+.value('$carouselSuppressWarning', false)
+
+.controller('CarouselController', ['$scope', '$element', '$controller', '$log', '$carouselSuppressWarning', function($scope, $element, $controller, $log, $carouselSuppressWarning) {
+ if (!$carouselSuppressWarning) {
+ $log.warn('CarouselController is now deprecated. Use UibCarouselController instead.');
+ }
+
+ angular.extend(this, $controller('UibCarouselController', {
+ $scope: $scope,
+ $element: $element
+ }));
+}])
+
+.directive('carousel', ['$log', '$carouselSuppressWarning', function($log, $carouselSuppressWarning) {
+ return {
+ transclude: true,
+ replace: true,
+ controller: 'CarouselController',
+ controllerAs: 'carousel',
+ require: 'carousel',
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/carousel/carousel.html';
+ },
+ scope: {
+ interval: '=',
+ noTransition: '=',
+ noPause: '=',
+ noWrap: '&'
+ },
+ link: function() {
+ if (!$carouselSuppressWarning) {
+ $log.warn('carousel is now deprecated. Use uib-carousel instead.');
+ }
+ }
+ };
+}])
+
+.directive('slide', ['$log', '$carouselSuppressWarning', function($log, $carouselSuppressWarning) {
+ return {
+ require: '^carousel',
+ transclude: true,
+ replace: true,
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/carousel/slide.html';
+ },
+ scope: {
+ active: '=?',
+ actual: '=?',
+ index: '=?'
+ },
+ link: function (scope, element, attrs, carouselCtrl) {
+ if (!$carouselSuppressWarning) {
+ $log.warn('slide is now deprecated. Use uib-slide instead.');
+ }
+
+ carouselCtrl.addSlide(scope, element);
+ //when the scope is destroyed then remove the slide from the current slides array
+ scope.$on('$destroy', function() {
+ carouselCtrl.removeSlide(scope);
+ });
+
+ scope.$watch('active', function(active) {
+ if (active) {
+ carouselCtrl.select(scope);
+ }
+ });
+ }
+ };
+}]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/docs/README.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/docs/README.md
new file mode 100644
index 0000000..0fe1eba
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/docs/README.md
@@ -0,0 +1,11 @@
+Carousel creates a carousel similar to bootstrap's image carousel.
+
+The carousel also offers support for touchscreen devices in the form of swiping. To enable swiping, load the `ngTouch` module as a dependency.
+
+Use a `<uib-carousel>` element with `<uib-slide>` elements inside it. It will automatically cycle through the slides at a given rate, and a current-index variable will be kept in sync with the currently visible slide.
+
+Use the `no-wrap` attribute on a `<uib-carousel>` element to control the looping of slides; setting `no-wrap` to an expression which evaluates to a truthy value will prevent looping.
+
+Use the `template-url` attribute on a `<uib-carousel>` or `<uib-slide>` element to specify the url of a custom template to override the default templates.
+
+Use the `actual` attribute on a `<uib-slide>` element to bind the slide model (or any object of interest) onto the slide directive's `$scope`, which makes it available for customization in the carousel template.
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/docs/demo.html
new file mode 100644
index 0000000..0383722
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/docs/demo.html
@@ -0,0 +1,28 @@
+<div ng-controller="CarouselDemoCtrl">
+ <div style="height: 305px">
+ <uib-carousel interval="myInterval" no-wrap="noWrapSlides">
+ <uib-slide ng-repeat="slide in slides" active="slide.active">
+ <img ng-src="{{slide.image}}" style="margin:auto;">
+ <div class="carousel-caption">
+ <h4>Slide {{$index}}</h4>
+ <p>{{slide.text}}</p>
+ </div>
+ </uib-slide>
+ </uib-carousel>
+ </div>
+ <div class="row">
+ <div class="col-md-6">
+ <button type="button" class="btn btn-info" ng-click="addSlide()">Add Slide</button>
+ <div class="checkbox">
+ <label>
+ <input type="checkbox" ng-model="noWrapSlides">
+ Disable Slide Looping
+ </label>
+ </div>
+ </div>
+ <div class="col-md-6">
+ Interval, in milliseconds: <input type="number" class="form-control" ng-model="myInterval">
+ <br />Enter a negative number or 0 to stop the interval.
+ </div>
+ </div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/docs/demo.js
new file mode 100644
index 0000000..9b6607c
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/docs/demo.js
@@ -0,0 +1,16 @@
+angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope) {
+ $scope.myInterval = 5000;
+ $scope.noWrapSlides = false;
+ var slides = $scope.slides = [];
+ $scope.addSlide = function() {
+ var newWidth = 600 + slides.length + 1;
+ slides.push({
+ image: '//placekitten.com/' + newWidth + '/300',
+ text: ['More','Extra','Lots of','Surplus'][slides.length % 4] + ' ' +
+ ['Cats', 'Kittys', 'Felines', 'Cutes'][slides.length % 4]
+ });
+ };
+ for (var i=0; i<4; i++) {
+ $scope.addSlide();
+ }
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/test/carousel.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/test/carousel.spec.js
new file mode 100644
index 0000000..adb9c76
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/carousel/test/carousel.spec.js
@@ -0,0 +1,594 @@
+describe('carousel', function() {
+ beforeEach(module('ui.bootstrap.carousel', function($compileProvider, $provide) {
+ angular.forEach(['ngSwipeLeft', 'ngSwipeRight'], makeMock);
+ function makeMock(name) {
+ $provide.value(name + 'Directive', []); //remove existing directive if it exists
+ $compileProvider.directive(name, function() {
+ return function(scope, element, attr) {
+ element.on(name, function() {
+ scope.$apply(attr[name]);
+ });
+ };
+ });
+ }
+ }));
+ beforeEach(module('template/carousel/carousel.html', 'template/carousel/slide.html'));
+
+ var $rootScope, $compile, $controller, $interval, $templateCache;
+ beforeEach(inject(function(_$rootScope_, _$compile_, _$controller_, _$interval_, _$templateCache_) {
+ $rootScope = _$rootScope_;
+ $compile = _$compile_;
+ $controller = _$controller_;
+ $interval = _$interval_;
+ $templateCache = _$templateCache_;
+ }));
+
+ describe('basics', function() {
+ var elm, scope;
+ beforeEach(function() {
+ scope = $rootScope.$new();
+ scope.slides = [
+ {active:false,content:'one'},
+ {active:false,content:'two'},
+ {active:false,content:'three'}
+ ];
+ elm = $compile(
+ '<uib-carousel interval="interval" no-transition="true" no-pause="nopause">' +
+ '<uib-slide ng-repeat="slide in slides" active="slide.active">' +
+ '{{slide.content}}' +
+ '</uib-slide>' +
+ '</uib-carousel>'
+ )(scope);
+ scope.interval = 5000;
+ scope.nopause = undefined;
+ scope.$apply();
+ });
+
+ function testSlideActive(slideIndex) {
+ for (var i = 0; i < scope.slides.length; i++) {
+ if (i == slideIndex) {
+ expect(scope.slides[i].active).toBe(true);
+ } else {
+ expect(scope.slides[i].active).not.toBe(true);
+ }
+ }
+ }
+
+ it('should allow overriding of the carousel template', function() {
+ $templateCache.put('foo/bar.html', '<div>foo</div>');
+
+ elm = $compile('<uib-carousel template-url="foo/bar.html"></uib-carousel>')(scope);
+ $rootScope.$digest();
+
+ expect(elm.html()).toBe('foo');
+ });
+
+ it('should allow overriding of the slide template', function() {
+ $templateCache.put('foo/bar.html', '<div class="slide">bar</div>');
+
+ elm = $compile(
+ '<uib-carousel interval="interval" no-transition="true" no-pause="nopause">' +
+ '<uib-slide template-url="foo/bar.html"></uib-slide>' +
+ '</uib-carousel>'
+ )(scope);
+ $rootScope.$digest();
+
+ var slide = elm.find('.slide');
+ expect(slide.html()).toBe('bar');
+ });
+
+ it('should set the selected slide to active = true', function() {
+ expect(scope.slides[0].content).toBe('one');
+ testSlideActive(0);
+ scope.$apply('slides[1].active=true');
+ testSlideActive(1);
+ });
+
+ it('should create clickable prev nav button', function() {
+ var navPrev = elm.find('a.left');
+ var navNext = elm.find('a.right');
+
+ expect(navPrev.length).toBe(1);
+ expect(navNext.length).toBe(1);
+ });
+
+ it('should display clickable slide indicators', function () {
+ var indicators = elm.find('ol.carousel-indicators > li');
+ expect(indicators.length).toBe(3);
+ });
+
+ it('should stop cycling slides forward when noWrap is truthy', function () {
+ elm = $compile(
+ '<uib-carousel interval="interval" no-wrap="noWrap">' +
+ '<uib-slide ng-repeat="slide in slides" active="slide.active">' +
+ '{{slide.content}}' +
+ '</uib-slide>' +
+ '</uib-carousel>'
+ )(scope);
+
+ scope.noWrap = true;
+ scope.$apply();
+
+ scope = elm.isolateScope();
+ spyOn(scope, 'pause');
+
+ for (var i = 0; i < scope.slides.length - 1; ++i) {
+ scope.next();
+ }
+ testSlideActive(scope.slides.length - 1);
+ scope.next();
+ testSlideActive(scope.slides.length - 1);
+ expect(scope.pause).toHaveBeenCalled();
+ });
+
+ it('should stop cycling slides backward when noWrap is truthy', function () {
+ elm = $compile(
+ '<uib-carousel interval="interval" no-wrap="noWrap">' +
+ '<uib-slide ng-repeat="slide in slides" active="slide.active">' +
+ '{{slide.content}}' +
+ '</uib-slide>' +
+ '</uib-carousel>'
+ )(scope);
+
+ scope.noWrap = true;
+ scope.$apply();
+
+ scope = elm.isolateScope();
+ spyOn(scope, 'pause');
+
+ testSlideActive(0);
+ scope.prev();
+ testSlideActive(0);
+ expect(scope.pause).toHaveBeenCalled();
+ });
+
+ it('should hide navigation when only one slide', function () {
+ scope.slides = [{active:false,content:'one'}];
+ scope.$apply();
+ elm = $compile(
+ '<uib-carousel interval="interval" no-transition="true">' +
+ '<uib-slide ng-repeat="slide in slides" active="slide.active">' +
+ '{{slide.content}}' +
+ '</uib-slide>' +
+ '</uib-carousel>'
+ )(scope);
+ var indicators = elm.find('ol.carousel-indicators > li');
+ expect(indicators.length).toBe(0);
+
+ var navNext = elm.find('a.right');
+ expect(navNext.length).toBe(0);
+
+ var navPrev = elm.find('a.left');
+ expect(navPrev.length).toBe(0);
+ });
+
+ it('should show navigation when there are 3 slides', function () {
+ var indicators = elm.find('ol.carousel-indicators > li');
+ expect(indicators.length).not.toBe(0);
+
+ var navNext = elm.find('a.right');
+ expect(navNext.length).not.toBe(0);
+
+ var navPrev = elm.find('a.left');
+ expect(navPrev.length).not.toBe(0);
+ });
+
+ it('should go to next when clicking next button', function() {
+ var navNext = elm.find('a.right');
+ testSlideActive(0);
+ navNext.click();
+ testSlideActive(1);
+ navNext.click();
+ testSlideActive(2);
+ navNext.click();
+ testSlideActive(0);
+ });
+
+ it('should go to prev when clicking prev button', function() {
+ var navPrev = elm.find('a.left');
+ testSlideActive(0);
+ navPrev.click();
+ testSlideActive(2);
+ navPrev.click();
+ testSlideActive(1);
+ navPrev.click();
+ testSlideActive(0);
+ });
+
+ describe('swiping', function() {
+ it('should go next on swipeLeft', function() {
+ testSlideActive(0);
+ elm.triggerHandler('ngSwipeLeft');
+ testSlideActive(1);
+ });
+
+ it('should go prev on swipeRight', function() {
+ testSlideActive(0);
+ elm.triggerHandler('ngSwipeRight');
+ testSlideActive(2);
+ });
+ });
+
+ it('should select a slide when clicking on slide indicators', function () {
+ var indicators = elm.find('ol.carousel-indicators > li');
+ indicators.eq(1).click();
+ testSlideActive(1);
+ });
+
+ it('shouldnt go forward if interval is NaN or negative or has no slides', function() {
+ testSlideActive(0);
+ var previousInterval = scope.interval;
+ scope.$apply('interval = -1');
+ $interval.flush(previousInterval);
+ testSlideActive(0);
+ scope.$apply('interval = 1000');
+ $interval.flush(1000);
+ testSlideActive(1);
+ scope.$apply('interval = false');
+ $interval.flush(1000);
+ testSlideActive(1);
+ scope.$apply('interval = 1000');
+ $interval.flush(1000);
+ testSlideActive(2);
+ scope.$apply('slides = []');
+ $interval.flush(1000);
+ testSlideActive(2);
+ });
+
+ it('should bind the content to slides', function() {
+ var contents = elm.find('div.item');
+
+ expect(contents.length).toBe(3);
+ expect(contents.eq(0).text()).toBe('one');
+ expect(contents.eq(1).text()).toBe('two');
+ expect(contents.eq(2).text()).toBe('three');
+
+ scope.$apply(function() {
+ scope.slides[0].content = 'what';
+ scope.slides[1].content = 'no';
+ scope.slides[2].content = 'maybe';
+ });
+
+ expect(contents.eq(0).text()).toBe('what');
+ expect(contents.eq(1).text()).toBe('no');
+ expect(contents.eq(2).text()).toBe('maybe');
+ });
+
+ it('should be playing by default and cycle through slides', function() {
+ testSlideActive(0);
+ $interval.flush(scope.interval);
+ testSlideActive(1);
+ $interval.flush(scope.interval);
+ testSlideActive(2);
+ $interval.flush(scope.interval);
+ testSlideActive(0);
+ });
+
+ it('should pause and play on mouseover', function() {
+ testSlideActive(0);
+ $interval.flush(scope.interval);
+ testSlideActive(1);
+ elm.trigger('mouseenter');
+ testSlideActive(1);
+ $interval.flush(scope.interval);
+ testSlideActive(1);
+ elm.trigger('mouseleave');
+ $interval.flush(scope.interval);
+ testSlideActive(2);
+ });
+
+ it('should not pause on mouseover if noPause', function() {
+ scope.$apply('nopause = true');
+ testSlideActive(0);
+ elm.trigger('mouseenter');
+ $interval.flush(scope.interval);
+ testSlideActive(1);
+ elm.trigger('mouseleave');
+ $interval.flush(scope.interval);
+ testSlideActive(2);
+ });
+
+ it('should remove slide from dom and change active slide', function() {
+ scope.$apply('slides[2].active = true');
+ testSlideActive(2);
+ scope.$apply('slides.splice(0,1)');
+ expect(elm.find('div.item').length).toBe(2);
+ testSlideActive(1);
+ $interval.flush(scope.interval);
+ testSlideActive(0);
+ scope.$apply('slides.splice(1,1)');
+ expect(elm.find('div.item').length).toBe(1);
+ testSlideActive(0);
+ });
+
+ it('should change dom when you reassign ng-repeat slides array', function() {
+ scope.slides = [{content:'new1'},{content:'new2'},{content:'new3'}];
+ scope.$apply();
+ var contents = elm.find('div.item');
+ expect(contents.length).toBe(3);
+ expect(contents.eq(0).text()).toBe('new1');
+ expect(contents.eq(1).text()).toBe('new2');
+ expect(contents.eq(2).text()).toBe('new3');
+ });
+
+ it('should not change if next is clicked while transitioning', function() {
+ var carouselScope = elm.children().scope();
+ var next = elm.find('a.right');
+
+ testSlideActive(0);
+ carouselScope.$currentTransition = true;
+ next.click();
+
+ testSlideActive(0);
+
+ carouselScope.$currentTransition = null;
+ next.click();
+ testSlideActive(1);
+ });
+
+ it('issue 1414 - should not continue running timers after scope is destroyed', function() {
+ testSlideActive(0);
+ $interval.flush(scope.interval);
+ testSlideActive(1);
+ $interval.flush(scope.interval);
+ testSlideActive(2);
+ $interval.flush(scope.interval);
+ testSlideActive(0);
+ spyOn($interval, 'cancel').and.callThrough();
+ scope.$destroy();
+ expect($interval.cancel).toHaveBeenCalled();
+ });
+
+ it('issue 4390 - should reset the currentTransition if there are no slides', function() {
+ var carouselScope = elm.children().scope();
+ var next = elm.find('a.right');
+ scope.slides = [{content:'new1'},{content:'new2'},{content:'new3'}];
+ scope.$apply();
+
+ testSlideActive(0);
+ carouselScope.$currentTransition = true;
+
+ scope.slides = [];
+ scope.$apply();
+
+ expect(carouselScope.$currentTransition).toBe(null);
+ });
+
+ describe('slide order', function() {
+ beforeEach(function() {
+ scope.slides = [
+ {active:false,content:'one', id:1},
+ {active:false,content:'two', id:2},
+ {active:false,content:'three', id:3}
+ ];
+ elm = $compile(
+ '<uib-carousel interval="interval" no-transition="true" no-pause="nopause">' +
+ '<uib-slide ng-repeat="slide in slides | orderBy: \'id\' " active="slide.active" index="$index">' +
+ '{{slide.content}}' +
+ '</uib-slide>' +
+ '</uib-carousel>'
+ )(scope);
+ scope.$apply();
+ scope.slides[0].id = 3;
+ scope.slides[1].id = 1;
+ scope.slides[2].id = 2;
+ scope.$apply();
+ });
+
+ it('should change dom when an order of the slides was changed', function() {
+ testSlideActive(0);
+ var contents = elm.find('div.item');
+ expect(contents.length).toBe(3);
+ expect(contents.eq(0).text()).toBe('two');
+ expect(contents.eq(1).text()).toBe('three');
+ expect(contents.eq(2).text()).toBe('one');
+ });
+
+ it('should select next after order change', function() {
+ testSlideActive(0);
+ var next = elm.find('a.right');
+ next.click();
+ testSlideActive(1);
+ });
+
+ it('should select prev after order change', function() {
+ testSlideActive(0);
+ var prev = elm.find('a.left');
+ prev.click();
+ testSlideActive(2);
+ });
+
+ it('should add slide in the specified position', function() {
+ testSlideActive(0);
+ scope.slides[2].id = 4;
+ scope.slides.push({active:false,content:'four', id:2});
+ scope.$apply();
+ var contents = elm.find('div.item');
+ expect(contents.length).toBe(4);
+ expect(contents.eq(0).text()).toBe('two');
+ expect(contents.eq(1).text()).toBe('four');
+ expect(contents.eq(2).text()).toBe('one');
+ expect(contents.eq(3).text()).toBe('three');
+ });
+
+ it('should remove slide after order change', function() {
+ testSlideActive(0);
+ scope.slides.splice(1, 1);
+ scope.$apply();
+ var contents = elm.find('div.item');
+ expect(contents.length).toBe(2);
+ expect(contents.eq(0).text()).toBe('three');
+ expect(contents.eq(1).text()).toBe('one');
+ });
+
+ });
+
+ });
+
+ describe('controller', function() {
+ var scope, ctrl;
+ //create an array of slides and add to the scope
+ var slides = [{'content':1},{'content':2},{'content':3},{'content':4}];
+
+ beforeEach(function() {
+ scope = $rootScope.$new();
+ ctrl = $controller('UibCarouselController', {$scope: scope, $element: angular.element('<div></div>')});
+ for(var i = 0;i < slides.length;i++){
+ ctrl.addSlide(slides[i]);
+ }
+ });
+
+ describe('addSlide', function() {
+ it('should set first slide to active = true and the rest to false', function() {
+ angular.forEach(ctrl.slides, function(slide, i) {
+ if (i !== 0) {
+ expect(slide.active).not.toBe(true);
+ } else {
+ expect(slide.active).toBe(true);
+ }
+ });
+ });
+
+ it('should add new slide and change active to true if active is true on the added slide', function() {
+ var newSlide = {active: true};
+ expect(ctrl.slides.length).toBe(4);
+ ctrl.addSlide(newSlide);
+ expect(ctrl.slides.length).toBe(5);
+ expect(ctrl.slides[4].active).toBe(true);
+ expect(ctrl.slides[0].active).toBe(false);
+ });
+
+ it('should add a new slide and not change the active slide', function() {
+ var newSlide = {active: false};
+ expect(ctrl.slides.length).toBe(4);
+ ctrl.addSlide(newSlide);
+ expect(ctrl.slides.length).toBe(5);
+ expect(ctrl.slides[4].active).toBe(false);
+ expect(ctrl.slides[0].active).toBe(true);
+ });
+
+ it('should remove slide and change active slide if needed', function() {
+ expect(ctrl.slides.length).toBe(4);
+ ctrl.removeSlide(ctrl.slides[0]);
+ expect(ctrl.slides.length).toBe(3);
+ expect(ctrl.currentSlide).toBe(ctrl.slides[0]);
+ ctrl.select(ctrl.slides[2]);
+ ctrl.removeSlide(ctrl.slides[2]);
+ expect(ctrl.slides.length).toBe(2);
+ expect(ctrl.currentSlide).toBe(ctrl.slides[1]);
+ ctrl.removeSlide(ctrl.slides[0]);
+ expect(ctrl.slides.length).toBe(1);
+ expect(ctrl.currentSlide).toBe(ctrl.slides[0]);
+ });
+
+ it('issue 1414 - should not continue running timers after scope is destroyed', function() {
+ spyOn(scope, 'next').and.callThrough();
+ scope.interval = 2000;
+ scope.$digest();
+
+ $interval.flush(scope.interval);
+ expect(scope.next.calls.count()).toBe(1);
+
+ scope.$destroy();
+
+ $interval.flush(scope.interval);
+ expect(scope.next.calls.count()).toBe(1);
+ });
+ });
+
+ it('should be exposed in the template', inject(function($templateCache) {
+ $templateCache.put('template/carousel/carousel.html', '<div>{{carousel.text}}</div>');
+
+ var scope = $rootScope.$new();
+ var elm = $compile('<uib-carousel interval="bar" no-transition="false" no-pause="true"></uib-carousel>')(scope);
+ $rootScope.$digest();
+
+ var ctrl = elm.controller('uibCarousel');
+
+ expect(ctrl).toBeDefined();
+
+ ctrl.text = 'foo';
+ $rootScope.$digest();
+
+ expect(elm.html()).toBe('foo');
+ }));
+ });
+
+ it('should expose a custom model in the carousel slide', function() {
+ var scope = $rootScope.$new();
+ scope.slides = [
+ {active:false,content:'one'},
+ {active:false,content:'two'},
+ {active:false,content:'three'}
+ ];
+ var elm = $compile(
+ '<uib-carousel interval="interval" no-transition="true" no-pause="nopause">' +
+ '<uib-slide ng-repeat="slide in slides" active="slide.active" actual="slide">' +
+ '{{slide.content}}' +
+ '</uib-slide>' +
+ '</uib-carousel>'
+ )(scope);
+ $rootScope.$digest();
+
+ var ctrl = elm.controller('uibCarousel');
+
+ expect(angular.equals(ctrl.slides.map(function(slide) {
+ return slide.actual;
+ }), scope.slides)).toBe(true);
+ });
+});
+
+describe('carousel deprecation', function() {
+ beforeEach(module('ui.bootstrap.carousel'));
+ beforeEach(module('template/carousel/carousel.html', 'template/carousel/slide.html'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$carouselSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = '<carousel interval="interval" no-transition="true" no-pause="nopause">' +
+ '<slide ng-repeat="slide in slides" active="slide.active">' +
+ '{{slide.content}}' +
+ '</slide>' +
+ '</carousel>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = '<carousel interval="interval" no-transition="true" no-pause="nopause">' +
+ '<slide ng-repeat="slide in slides" active="slide.active">' +
+ '{{slide.content}}' +
+ '</slide>' +
+ '</carousel>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(2);
+ expect($log.warn.calls.argsFor(0)).toEqual(['CarouselController is now deprecated. Use UibCarouselController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['carousel is now deprecated. Use uib-carousel instead.']);
+ }));
+
+ it('should give warning by default for slider', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = '<carousel interval="interval" no-transition="true" no-pause="nopause">' +
+ '<slide></slide>' +
+ '</carousel>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(3);
+ expect($log.warn.calls.argsFor(0)).toEqual(['CarouselController is now deprecated. Use UibCarouselController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['slide is now deprecated. Use uib-slide instead.']);
+ expect($log.warn.calls.argsFor(2)).toEqual(['carousel is now deprecated. Use uib-carousel instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/collapse.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/collapse.js
new file mode 100644
index 0000000..c01e647
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/collapse.js
@@ -0,0 +1,159 @@
+angular.module('ui.bootstrap.collapse', [])
+
+ .directive('uibCollapse', ['$animate', '$injector', function($animate, $injector) {
+ var $animateCss = $injector.has('$animateCss') ? $injector.get('$animateCss') : null;
+ return {
+ link: function(scope, element, attrs) {
+ function expand() {
+ element.removeClass('collapse')
+ .addClass('collapsing')
+ .attr('aria-expanded', true)
+ .attr('aria-hidden', false);
+
+ if ($animateCss) {
+ $animateCss(element, {
+ addClass: 'in',
+ easing: 'ease',
+ to: { height: element[0].scrollHeight + 'px' }
+ }).start().finally(expandDone);
+ } else {
+ $animate.addClass(element, 'in', {
+ to: { height: element[0].scrollHeight + 'px' }
+ }).then(expandDone);
+ }
+ }
+
+ function expandDone() {
+ element.removeClass('collapsing')
+ .addClass('collapse')
+ .css({height: 'auto'});
+ }
+
+ function collapse() {
+ if (!element.hasClass('collapse') && !element.hasClass('in')) {
+ return collapseDone();
+ }
+
+ element
+ // IMPORTANT: The height must be set before adding "collapsing" class.
+ // Otherwise, the browser attempts to animate from height 0 (in
+ // collapsing class) to the given height here.
+ .css({height: element[0].scrollHeight + 'px'})
+ // initially all panel collapse have the collapse class, this removal
+ // prevents the animation from jumping to collapsed state
+ .removeClass('collapse')
+ .addClass('collapsing')
+ .attr('aria-expanded', false)
+ .attr('aria-hidden', true);
+
+ if ($animateCss) {
+ $animateCss(element, {
+ removeClass: 'in',
+ to: {height: '0'}
+ }).start().finally(collapseDone);
+ } else {
+ $animate.removeClass(element, 'in', {
+ to: {height: '0'}
+ }).then(collapseDone);
+ }
+ }
+
+ function collapseDone() {
+ element.css({height: '0'}); // Required so that collapse works when animation is disabled
+ element.removeClass('collapsing')
+ .addClass('collapse');
+ }
+
+ scope.$watch(attrs.uibCollapse, function(shouldCollapse) {
+ if (shouldCollapse) {
+ collapse();
+ } else {
+ expand();
+ }
+ });
+ }
+ };
+ }]);
+
+/* Deprecated collapse below */
+
+angular.module('ui.bootstrap.collapse')
+
+ .value('$collapseSuppressWarning', false)
+
+ .directive('collapse', ['$animate', '$injector', '$log', '$collapseSuppressWarning', function($animate, $injector, $log, $collapseSuppressWarning) {
+ var $animateCss = $injector.has('$animateCss') ? $injector.get('$animateCss') : null;
+ return {
+ link: function(scope, element, attrs) {
+ if (!$collapseSuppressWarning) {
+ $log.warn('collapse is now deprecated. Use uib-collapse instead.');
+ }
+
+ function expand() {
+ element.removeClass('collapse')
+ .addClass('collapsing')
+ .attr('aria-expanded', true)
+ .attr('aria-hidden', false);
+
+ if ($animateCss) {
+ $animateCss(element, {
+ easing: 'ease',
+ to: { height: element[0].scrollHeight + 'px' }
+ }).start().done(expandDone);
+ } else {
+ $animate.animate(element, {}, {
+ height: element[0].scrollHeight + 'px'
+ }).then(expandDone);
+ }
+ }
+
+ function expandDone() {
+ element.removeClass('collapsing')
+ .addClass('collapse in')
+ .css({height: 'auto'});
+ }
+
+ function collapse() {
+ if (!element.hasClass('collapse') && !element.hasClass('in')) {
+ return collapseDone();
+ }
+
+ element
+ // IMPORTANT: The height must be set before adding "collapsing" class.
+ // Otherwise, the browser attempts to animate from height 0 (in
+ // collapsing class) to the given height here.
+ .css({height: element[0].scrollHeight + 'px'})
+ // initially all panel collapse have the collapse class, this removal
+ // prevents the animation from jumping to collapsed state
+ .removeClass('collapse in')
+ .addClass('collapsing')
+ .attr('aria-expanded', false)
+ .attr('aria-hidden', true);
+
+ if ($animateCss) {
+ $animateCss(element, {
+ to: {height: '0'}
+ }).start().done(collapseDone);
+ } else {
+ $animate.animate(element, {}, {
+ height: '0'
+ }).then(collapseDone);
+ }
+ }
+
+ function collapseDone() {
+ element.css({height: '0'}); // Required so that collapse works when animation is disabled
+ element.removeClass('collapsing')
+ .addClass('collapse');
+ }
+
+ scope.$watch(attrs.collapse, function(shouldCollapse) {
+ if (shouldCollapse) {
+ collapse();
+ } else {
+ expand();
+ }
+ });
+ }
+ };
+ }]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/docs/demo.html
new file mode 100644
index 0000000..462bda3
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/docs/demo.html
@@ -0,0 +1,7 @@
+<div ng-controller="CollapseDemoCtrl">
+ <button type="button" class="btn btn-default" ng-click="isCollapsed = !isCollapsed">Toggle collapse</button>
+ <hr>
+ <div uib-collapse="isCollapsed">
+ <div class="well well-lg">Some content</div>
+ </div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/docs/demo.js
new file mode 100644
index 0000000..897eeca
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/docs/demo.js
@@ -0,0 +1,3 @@
+angular.module('ui.bootstrap.demo').controller('CollapseDemoCtrl', function ($scope) {
+ $scope.isCollapsed = false;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/docs/readme.md
new file mode 100644
index 0000000..b2bd63c
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/docs/readme.md
@@ -0,0 +1,8 @@
+**uib-collapse** provides a simple way to hide and show an element with a css transition
+
+### uib-collapse settings
+
+* `uib-collapse`
+ <i class="glyphicon glyphicon-eye-open"></i>
+ _(Default: `false`)_ -
+ Whether the element should be collapsed or not.
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/test/collapse.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/test/collapse.spec.js
new file mode 100644
index 0000000..5083904
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/collapse/test/collapse.spec.js
@@ -0,0 +1,165 @@
+describe('collapse directive', function() {
+ var element, scope, $compile, $animate;
+
+ beforeEach(module('ui.bootstrap.collapse'));
+ beforeEach(module('ngAnimateMock'));
+ beforeEach(inject(function(_$rootScope_, _$compile_, _$animate_) {
+ scope = _$rootScope_;
+ $compile = _$compile_;
+ $animate = _$animate_;
+ }));
+
+ beforeEach(function() {
+ element = $compile('<div uib-collapse="isCollapsed">Some Content</div>')(scope);
+ angular.element(document.body).append(element);
+ });
+
+ afterEach(function() {
+ element.remove();
+ });
+
+ it('should be hidden on initialization if isCollapsed = true', function() {
+ scope.isCollapsed = true;
+ scope.$digest();
+ expect(element.height()).toBe(0);
+ });
+
+ it('should collapse if isCollapsed = true on subsequent use', function() {
+ scope.isCollapsed = false;
+ scope.$digest();
+ $animate.flush();
+ scope.isCollapsed = true;
+ scope.$digest();
+ $animate.flush();
+ expect(element.height()).toBe(0);
+ });
+
+ it('should be shown on initialization if isCollapsed = false', function() {
+ scope.isCollapsed = false;
+ scope.$digest();
+ $animate.flush();
+ expect(element.height()).not.toBe(0);
+ });
+
+ it('should expand if isCollapsed = false on subsequent use', function() {
+ scope.isCollapsed = false;
+ scope.$digest();
+ $animate.flush();
+ scope.isCollapsed = true;
+ scope.$digest();
+ $animate.flush();
+ scope.isCollapsed = false;
+ scope.$digest();
+ $animate.flush();
+ expect(element.height()).not.toBe(0);
+ });
+
+ it('should expand if isCollapsed = true on subsequent uses', function() {
+ scope.isCollapsed = false;
+ scope.$digest();
+ $animate.flush();
+ scope.isCollapsed = true;
+ scope.$digest();
+ $animate.flush();
+ scope.isCollapsed = false;
+ scope.$digest();
+ $animate.flush();
+ scope.isCollapsed = true;
+ scope.$digest();
+ $animate.flush();
+ expect(element.height()).toBe(0);
+ });
+
+ it('should change aria-expanded attribute', function() {
+ scope.isCollapsed = false;
+ scope.$digest();
+ $animate.flush();
+ expect(element.attr('aria-expanded')).toBe('true');
+
+ scope.isCollapsed = true;
+ scope.$digest();
+ $animate.flush();
+ expect(element.attr('aria-expanded')).toBe('false');
+ });
+
+ it('should change aria-hidden attribute', function() {
+ scope.isCollapsed = false;
+ scope.$digest();
+ $animate.flush();
+ expect(element.attr('aria-hidden')).toBe('false');
+
+ scope.isCollapsed = true;
+ scope.$digest();
+ $animate.flush();
+ expect(element.attr('aria-hidden')).toBe('true');
+ });
+
+ describe('dynamic content', function() {
+ var element;
+
+ beforeEach(function() {
+ element = angular.element('<div uib-collapse="isCollapsed"><p>Initial content</p><div ng-show="exp">Additional content</div></div>');
+ $compile(element)(scope);
+ angular.element(document.body).append(element);
+ });
+
+ afterEach(function() {
+ element.remove();
+ });
+
+ it('should grow accordingly when content size inside collapse increases', function() {
+ scope.exp = false;
+ scope.isCollapsed = false;
+ scope.$digest();
+ $animate.flush();
+ var collapseHeight = element.height();
+ scope.exp = true;
+ scope.$digest();
+ expect(element.height()).toBeGreaterThan(collapseHeight);
+ });
+
+ it('should shrink accordingly when content size inside collapse decreases', function() {
+ scope.exp = true;
+ scope.isCollapsed = false;
+ scope.$digest();
+ $animate.flush();
+ var collapseHeight = element.height();
+ scope.exp = false;
+ scope.$digest();
+ expect(element.height()).toBeLessThan(collapseHeight);
+ });
+ });
+});
+
+/* Deprecation tests below */
+
+describe('collapse deprecation', function() {
+ beforeEach(module('ui.bootstrap.collapse'));
+ beforeEach(module('ngAnimateMock'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$collapseSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = $compile('<div collapse="isCollapsed">Some Content</div>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = $compile('<div collapse="isCollapsed">Some Content</div>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(1);
+ expect($log.warn.calls.argsFor(0)).toEqual(['collapse is now deprecated. Use uib-collapse instead.']);
+
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dateparser/dateparser.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dateparser/dateparser.js
new file mode 100644
index 0000000..0b4249f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dateparser/dateparser.js
@@ -0,0 +1,233 @@
+angular.module('ui.bootstrap.dateparser', [])
+
+.service('uibDateParser', ['$log', '$locale', 'orderByFilter', function($log, $locale, orderByFilter) {
+ // Pulled from https://github.com/mbostock/d3/blob/master/src/format/requote.js
+ var SPECIAL_CHARACTERS_REGEXP = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
+
+ var localeId;
+ var formatCodeToRegex;
+
+ this.init = function() {
+ localeId = $locale.id;
+
+ this.parsers = {};
+
+ formatCodeToRegex = {
+ 'yyyy': {
+ regex: '\\d{4}',
+ apply: function(value) { this.year = +value; }
+ },
+ 'yy': {
+ regex: '\\d{2}',
+ apply: function(value) { this.year = +value + 2000; }
+ },
+ 'y': {
+ regex: '\\d{1,4}',
+ apply: function(value) { this.year = +value; }
+ },
+ 'MMMM': {
+ regex: $locale.DATETIME_FORMATS.MONTH.join('|'),
+ apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); }
+ },
+ 'MMM': {
+ regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
+ apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); }
+ },
+ 'MM': {
+ regex: '0[1-9]|1[0-2]',
+ apply: function(value) { this.month = value - 1; }
+ },
+ 'M': {
+ regex: '[1-9]|1[0-2]',
+ apply: function(value) { this.month = value - 1; }
+ },
+ 'dd': {
+ regex: '[0-2][0-9]{1}|3[0-1]{1}',
+ apply: function(value) { this.date = +value; }
+ },
+ 'd': {
+ regex: '[1-2]?[0-9]{1}|3[0-1]{1}',
+ apply: function(value) { this.date = +value; }
+ },
+ 'EEEE': {
+ regex: $locale.DATETIME_FORMATS.DAY.join('|')
+ },
+ 'EEE': {
+ regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|')
+ },
+ 'HH': {
+ regex: '(?:0|1)[0-9]|2[0-3]',
+ apply: function(value) { this.hours = +value; }
+ },
+ 'hh': {
+ regex: '0[0-9]|1[0-2]',
+ apply: function(value) { this.hours = +value; }
+ },
+ 'H': {
+ regex: '1?[0-9]|2[0-3]',
+ apply: function(value) { this.hours = +value; }
+ },
+ 'h': {
+ regex: '[0-9]|1[0-2]',
+ apply: function(value) { this.hours = +value; }
+ },
+ 'mm': {
+ regex: '[0-5][0-9]',
+ apply: function(value) { this.minutes = +value; }
+ },
+ 'm': {
+ regex: '[0-9]|[1-5][0-9]',
+ apply: function(value) { this.minutes = +value; }
+ },
+ 'sss': {
+ regex: '[0-9][0-9][0-9]',
+ apply: function(value) { this.milliseconds = +value; }
+ },
+ 'ss': {
+ regex: '[0-5][0-9]',
+ apply: function(value) { this.seconds = +value; }
+ },
+ 's': {
+ regex: '[0-9]|[1-5][0-9]',
+ apply: function(value) { this.seconds = +value; }
+ },
+ 'a': {
+ regex: $locale.DATETIME_FORMATS.AMPMS.join('|'),
+ apply: function(value) {
+ if (this.hours === 12) {
+ this.hours = 0;
+ }
+
+ if (value === 'PM') {
+ this.hours += 12;
+ }
+ }
+ }
+ };
+ };
+
+ this.init();
+
+ function createParser(format) {
+ var map = [], regex = format.split('');
+
+ angular.forEach(formatCodeToRegex, function(data, code) {
+ var index = format.indexOf(code);
+
+ if (index > -1) {
+ format = format.split('');
+
+ regex[index] = '(' + data.regex + ')';
+ format[index] = '$'; // Custom symbol to define consumed part of format
+ for (var i = index + 1, n = index + code.length; i < n; i++) {
+ regex[i] = '';
+ format[i] = '$';
+ }
+ format = format.join('');
+
+ map.push({ index: index, apply: data.apply });
+ }
+ });
+
+ return {
+ regex: new RegExp('^' + regex.join('') + '$'),
+ map: orderByFilter(map, 'index')
+ };
+ }
+
+ this.parse = function(input, format, baseDate) {
+ if (!angular.isString(input) || !format) {
+ return input;
+ }
+
+ format = $locale.DATETIME_FORMATS[format] || format;
+ format = format.replace(SPECIAL_CHARACTERS_REGEXP, '\\$&');
+
+ if ($locale.id !== localeId) {
+ this.init();
+ }
+
+ if (!this.parsers[format]) {
+ this.parsers[format] = createParser(format);
+ }
+
+ var parser = this.parsers[format],
+ regex = parser.regex,
+ map = parser.map,
+ results = input.match(regex);
+
+ if (results && results.length) {
+ var fields, dt;
+ if (angular.isDate(baseDate) && !isNaN(baseDate.getTime())) {
+ fields = {
+ year: baseDate.getFullYear(),
+ month: baseDate.getMonth(),
+ date: baseDate.getDate(),
+ hours: baseDate.getHours(),
+ minutes: baseDate.getMinutes(),
+ seconds: baseDate.getSeconds(),
+ milliseconds: baseDate.getMilliseconds()
+ };
+ } else {
+ if (baseDate) {
+ $log.warn('dateparser:', 'baseDate is not a valid date');
+ }
+ fields = { year: 1900, month: 0, date: 1, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 };
+ }
+
+ for (var i = 1, n = results.length; i < n; i++) {
+ var mapper = map[i-1];
+ if (mapper.apply) {
+ mapper.apply.call(fields, results[i]);
+ }
+ }
+
+ if (isValid(fields.year, fields.month, fields.date)) {
+ if (angular.isDate(baseDate) && !isNaN(baseDate.getTime())) {
+ dt = new Date(baseDate);
+ dt.setFullYear(fields.year, fields.month, fields.date,
+ fields.hours, fields.minutes, fields.seconds,
+ fields.milliseconds || 0);
+ } else {
+ dt = new Date(fields.year, fields.month, fields.date,
+ fields.hours, fields.minutes, fields.seconds,
+ fields.milliseconds || 0);
+ }
+ }
+
+ return dt;
+ }
+ };
+
+ // Check if date is valid for specific month (and year for February).
+ // Month: 0 = Jan, 1 = Feb, etc
+ function isValid(year, month, date) {
+ if (date < 1) {
+ return false;
+ }
+
+ if (month === 1 && date > 28) {
+ return date === 29 && ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
+ }
+
+ if (month === 3 || month === 5 || month === 8 || month === 10) {
+ return date < 31;
+ }
+
+ return true;
+ }
+}]);
+
+/* Deprecated dateparser below */
+
+angular.module('ui.bootstrap.dateparser')
+
+.value('$dateParserSuppressWarning', false)
+
+.service('dateParser', ['$log', '$dateParserSuppressWarning', 'uibDateParser', function($log, $dateParserSuppressWarning, uibDateParser) {
+ if (!$dateParserSuppressWarning) {
+ $log.warn('dateParser is now deprecated. Use uibDateParser instead.');
+ }
+
+ angular.extend(this, uibDateParser);
+}]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dateparser/test/dateparser.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dateparser/test/dateparser.spec.js
new file mode 100644
index 0000000..fb8897c
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dateparser/test/dateparser.spec.js
@@ -0,0 +1,257 @@
+describe('date parser', function() {
+ var dateParser;
+
+ beforeEach(module('ui.bootstrap.dateparser'));
+ beforeEach(inject(function (uibDateParser) {
+ dateParser = uibDateParser;
+ }));
+
+ function expectParse(input, format, date) {
+ expect(dateParser.parse(input, format)).toEqual(date);
+ }
+
+ describe('with custom formats', function() {
+ it('should work correctly for `dd`, `MM`, `yyyy`', function() {
+ expectParse('17.11.2013', 'dd.MM.yyyy', new Date(2013, 10, 17, 0));
+ expectParse('31.12.2013', 'dd.MM.yyyy', new Date(2013, 11, 31, 0));
+ expectParse('08-03-1991', 'dd-MM-yyyy', new Date(1991, 2, 8, 0));
+ expectParse('03/05/1980', 'MM/dd/yyyy', new Date(1980, 2, 5, 0));
+ expectParse('10.01/1983', 'dd.MM/yyyy', new Date(1983, 0, 10, 0));
+ expectParse('11-09-1980', 'MM-dd-yyyy', new Date(1980, 10, 9, 0));
+ expectParse('2011/02/05', 'yyyy/MM/dd', new Date(2011, 1, 5, 0));
+ });
+
+ it('should work correctly for `yy`', function() {
+ expectParse('17.11.13', 'dd.MM.yy', new Date(2013, 10, 17, 0));
+ expectParse('02-05-11', 'dd-MM-yy', new Date(2011, 4, 2, 0));
+ expectParse('02/05/80', 'MM/dd/yy', new Date(2080, 1, 5, 0));
+ expectParse('55/02/05', 'yy/MM/dd', new Date(2055, 1, 5, 0));
+ expectParse('11-08-13', 'dd-MM-yy', new Date(2013, 7, 11, 0));
+ });
+
+ it('should work correctly for `M`', function() {
+ expectParse('8/11/2013', 'M/dd/yyyy', new Date(2013, 7, 11, 0));
+ expectParse('07.11.05', 'dd.M.yy', new Date(2005, 10, 7, 0));
+ expectParse('02-5-11', 'dd-M-yy', new Date(2011, 4, 2, 0));
+ expectParse('2/05/1980', 'M/dd/yyyy', new Date(1980, 1, 5, 0));
+ expectParse('1955/2/05', 'yyyy/M/dd', new Date(1955, 1, 5, 0));
+ expectParse('02-5-11', 'dd-M-yy', new Date(2011, 4, 2, 0));
+ });
+
+ it('should work correctly for `MMM`', function() {
+ expectParse('30.Sep.10', 'dd.MMM.yy', new Date(2010, 8, 30, 0));
+ expectParse('02-May-11', 'dd-MMM-yy', new Date(2011, 4, 2, 0));
+ expectParse('Feb/05/1980', 'MMM/dd/yyyy', new Date(1980, 1, 5, 0));
+ expectParse('1955/Feb/05', 'yyyy/MMM/dd', new Date(1955, 1, 5, 0));
+ });
+
+ it('should work correctly for `MMMM`', function() {
+ expectParse('17.November.13', 'dd.MMMM.yy', new Date(2013, 10, 17, 0));
+ expectParse('05-March-1980', 'dd-MMMM-yyyy', new Date(1980, 2, 5, 0));
+ expectParse('February/05/1980', 'MMMM/dd/yyyy', new Date(1980, 1, 5, 0));
+ expectParse('1949/December/20', 'yyyy/MMMM/dd', new Date(1949, 11, 20, 0));
+ });
+
+ it('should work correctly for `d`', function() {
+ expectParse('17.November.13', 'd.MMMM.yy', new Date(2013, 10, 17, 0));
+ expectParse('8-March-1991', 'd-MMMM-yyyy', new Date(1991, 2, 8, 0));
+ expectParse('February/5/1980', 'MMMM/d/yyyy', new Date(1980, 1, 5, 0));
+ expectParse('1955/February/5', 'yyyy/MMMM/d', new Date(1955, 1, 5, 0));
+ expectParse('11-08-13', 'd-MM-yy', new Date(2013, 7, 11, 0));
+ });
+
+ it('should work correctly for `HH`', function() {
+ expectParse('22.March.15.22', 'd.MMMM.yy.HH', new Date(2015, 2, 22, 22));
+ expectParse('8-March-1991-11', 'd-MMMM-yyyy-HH', new Date(1991, 2, 8, 11));
+ expectParse('February/5/1980/00', 'MMMM/d/yyyy/HH', new Date(1980, 1, 5, 0));
+ expectParse('1955/February/5 03', 'yyyy/MMMM/d HH', new Date(1955, 1, 5, 3));
+ expectParse('11-08-13 23', 'd-MM-yy HH', new Date(2013, 7, 11, 23));
+ });
+
+ it('should work correctly for `hh`', function() {
+ expectParse('22.March.15.22', 'd.MMMM.yy.hh', undefined);
+ expectParse('22.March.15.12', 'd.MMMM.yy.hh', new Date(2015, 2, 22, 12));
+ expectParse('8-March-1991-11', 'd-MMMM-yyyy-hh', new Date(1991, 2, 8, 11));
+ expectParse('February/5/1980/00', 'MMMM/d/yyyy/hh', new Date(1980, 1, 5, 0));
+ expectParse('1955/February/5 03', 'yyyy/MMMM/d hh', new Date(1955, 1, 5, 3));
+ expectParse('11-08-13 23', 'd-MM-yy hh', undefined);
+ expectParse('11-08-13 09', 'd-MM-yy hh', new Date(2013, 7, 11, 9));
+ });
+
+ it('should work correctly for `H`', function() {
+ expectParse('22.March.15.22', 'd.MMMM.yy.H', new Date(2015, 2, 22, 22));
+ expectParse('8-March-1991-11', 'd-MMMM-yyyy-H', new Date(1991, 2, 8, 11));
+ expectParse('February/5/1980/0', 'MMMM/d/yyyy/H', new Date(1980, 1, 5, 0));
+ expectParse('1955/February/5 3', 'yyyy/MMMM/d H', new Date(1955, 1, 5, 3));
+ expectParse('11-08-13 23', 'd-MM-yy H', new Date(2013, 7, 11, 23));
+ });
+
+ it('should work correctly for `h`', function() {
+ expectParse('22.March.15.12', 'd.MMMM.yy.h', new Date(2015, 2, 22, 12));
+ expectParse('8-March-1991-11', 'd-MMMM-yyyy-h', new Date(1991, 2, 8, 11));
+ expectParse('February/5/1980/0', 'MMMM/d/yyyy/h', new Date(1980, 1, 5, 0));
+ expectParse('1955/February/5 3', 'yyyy/MMMM/d h', new Date(1955, 1, 5, 3));
+ expectParse('11-08-13 3', 'd-MM-yy h', new Date(2013, 7, 11, 3));
+ });
+
+ it('should work correctly for `mm`', function() {
+ expectParse('22.March.15.22', 'd.MMMM.yy.mm', new Date(2015, 2, 22, 0, 22));
+ expectParse('8-March-1991-59', 'd-MMMM-yyyy-mm', new Date(1991, 2, 8, 0, 59));
+ expectParse('February/5/1980/00', 'MMMM/d/yyyy/mm', new Date(1980, 1, 5, 0, 0));
+ expectParse('1955/February/5 03', 'yyyy/MMMM/d mm', new Date(1955, 1, 5, 0, 3));
+ expectParse('11-08-13 46', 'd-MM-yy mm', new Date(2013, 7, 11, 0, 46));
+ expectParse('22.March.15.22:33', 'd.MMMM.yy.HH:mm', new Date(2015, 2, 22, 22, 33));
+ expectParse('22.March.15.2:01', 'd.MMMM.yy.H:mm', new Date(2015, 2, 22, 2, 1));
+ });
+
+ it('should work correctly for `m`', function() {
+ expectParse('22.March.15.22', 'd.MMMM.yy.m', new Date(2015, 2, 22, 0, 22));
+ expectParse('8-March-1991-59', 'd-MMMM-yyyy-m', new Date(1991, 2, 8, 0, 59));
+ expectParse('February/5/1980/0', 'MMMM/d/yyyy/m', new Date(1980, 1, 5, 0, 0));
+ expectParse('1955/February/5 3', 'yyyy/MMMM/d m', new Date(1955, 1, 5, 0, 3));
+ expectParse('11-08-13 46', 'd-MM-yy m', new Date(2013, 7, 11, 0, 46));
+ expectParse('22.March.15.22:3', 'd.MMMM.yy.HH:m', new Date(2015, 2, 22, 22, 3));
+ expectParse('22.March.15.2:1', 'd.MMMM.yy.H:m', new Date(2015, 2, 22, 2, 1));
+ });
+
+ it('should work correctly for `sss`', function() {
+ expectParse('22.March.15.123', 'd.MMMM.yy.sss', new Date(2015, 2, 22, 0, 0, 0, 123));
+ expectParse('8-March-1991-059', 'd-MMMM-yyyy-sss', new Date(1991, 2, 8, 0, 0, 0, 59));
+ expectParse('February/5/1980/000', 'MMMM/d/yyyy/sss', new Date(1980, 1, 5, 0, 0, 0));
+ expectParse('1955/February/5 003', 'yyyy/MMMM/d sss', new Date(1955, 1, 5, 0, 0, 0, 3));
+ expectParse('11-08-13 046', 'd-MM-yy sss', new Date(2013, 7, 11, 0, 0, 0, 46));
+ expectParse('22.March.15.22:33:044', 'd.MMMM.yy.HH:mm:sss', new Date(2015, 2, 22, 22, 33, 0, 44));
+ expectParse('22.March.15.0:0:001', 'd.MMMM.yy.H:m:sss', new Date(2015, 2, 22, 0, 0, 0, 1));
+ });
+
+ it('should work correctly for `ss`', function() {
+ expectParse('22.March.15.22', 'd.MMMM.yy.ss', new Date(2015, 2, 22, 0, 0, 22));
+ expectParse('8-March-1991-59', 'd-MMMM-yyyy-ss', new Date(1991, 2, 8, 0, 0, 59));
+ expectParse('February/5/1980/00', 'MMMM/d/yyyy/ss', new Date(1980, 1, 5, 0, 0, 0));
+ expectParse('1955/February/5 03', 'yyyy/MMMM/d ss', new Date(1955, 1, 5, 0, 0, 3));
+ expectParse('11-08-13 46', 'd-MM-yy ss', new Date(2013, 7, 11, 0, 0, 46));
+ expectParse('22.March.15.22:33:44', 'd.MMMM.yy.HH:mm:ss', new Date(2015, 2, 22, 22, 33, 44));
+ expectParse('22.March.15.0:0:01', 'd.MMMM.yy.H:m:ss', new Date(2015, 2, 22, 0, 0, 1));
+ });
+
+ it('should work correctly for `s`', function() {
+ expectParse('22.March.15.22', 'd.MMMM.yy.s', new Date(2015, 2, 22, 0, 0, 22));
+ expectParse('8-March-1991-59', 'd-MMMM-yyyy-s', new Date(1991, 2, 8, 0, 0, 59));
+ expectParse('February/5/1980/0', 'MMMM/d/yyyy/s', new Date(1980, 1, 5, 0, 0, 0));
+ expectParse('1955/February/5 3', 'yyyy/MMMM/d s', new Date(1955, 1, 5, 0, 0, 3));
+ expectParse('11-08-13 46', 'd-MM-yy s', new Date(2013, 7, 11, 0, 0, 46));
+ expectParse('22.March.15.22:33:4', 'd.MMMM.yy.HH:mm:s', new Date(2015, 2, 22, 22, 33, 4));
+ expectParse('22.March.15.22:3:4', 'd.MMMM.yy.HH:m:s', new Date(2015, 2, 22, 22, 3, 4));
+ });
+
+ it('should work correctly for `a`', function() {
+ expectParse('22.March.15.10AM', 'd.MMMM.yy.hha', new Date(2015, 2, 22, 10));
+ expectParse('22.March.15.10PM', 'd.MMMM.yy.hha', new Date(2015, 2, 22, 22));
+ expectParse('8-March-1991-11AM', 'd-MMMM-yyyy-hha', new Date(1991, 2, 8, 11));
+ expectParse('8-March-1991-11PM', 'd-MMMM-yyyy-hha', new Date(1991, 2, 8, 23));
+ expectParse('February/5/1980/12AM', 'MMMM/d/yyyy/hha', new Date(1980, 1, 5, 0));
+ expectParse('February/5/1980/12PM', 'MMMM/d/yyyy/hha', new Date(1980, 1, 5, 12));
+ expectParse('1955/February/5 03AM', 'yyyy/MMMM/d hha', new Date(1955, 1, 5, 3));
+ expectParse('1955/February/5 03PM', 'yyyy/MMMM/d hha', new Date(1955, 1, 5, 15));
+ expectParse('11-08-13 09AM', 'd-MM-yy hha', new Date(2013, 7, 11, 9));
+ expectParse('11-08-13 09PM', 'd-MM-yy hha', new Date(2013, 7, 11, 21));
+ });
+ });
+
+ describe('with predefined formats', function() {
+ it('should work correctly for `shortDate`', function() {
+ expectParse('9/3/10', 'shortDate', new Date(2010, 8, 3, 0));
+ });
+
+ it('should work correctly for `mediumDate`', function() {
+ expectParse('Sep 3, 2010', 'mediumDate', new Date(2010, 8, 3, 0));
+ });
+
+ it('should work correctly for `longDate`', function() {
+ expectParse('September 3, 2010', 'longDate', new Date(2010, 8, 3, 0));
+ });
+
+ it('should work correctly for `fullDate`', function() {
+ expectParse('Friday, September 3, 2010', 'fullDate', new Date(2010, 8, 3, 0));
+ });
+ });
+
+ describe('with edge case', function() {
+ it('should not work for invalid number of days in February', function() {
+ expect(dateParser.parse('29.02.2013', 'dd.MM.yyyy')).toBeUndefined();
+ });
+
+ it('should not work for 0 number of days', function() {
+ expect(dateParser.parse('00.02.2013', 'dd.MM.yyyy')).toBeUndefined();
+ });
+
+ it('should work for 29 days in February for leap years', function() {
+ expectParse('29.02.2000', 'dd.MM.yyyy', new Date(2000, 1, 29, 0));
+ });
+
+ it('should not work for 31 days for some months', function() {
+ expect(dateParser.parse('31-04-2013', 'dd-MM-yyyy')).toBeUndefined();
+ expect(dateParser.parse('November 31, 2013', 'MMMM d, yyyy')).toBeUndefined();
+ });
+
+ it('should work when base date is a string', function() {
+ expect(dateParser.parse('01-02-2034', 'dd-MM-yyyy', '05-06-2078')).toEqual(new Date(2034, 1, 1));
+ });
+
+ it('should work when base date is an invalid date', function() {
+ expect(dateParser.parse('30-12-2015', 'dd-MM-yyyy', new Date('foo'))).toEqual(new Date(2015, 11, 30));
+ });
+ });
+
+ it('should not parse non-string inputs', function() {
+ expect(dateParser.parse(123456, 'dd.MM.yyyy')).toBe(123456);
+ var date = new Date();
+ expect(dateParser.parse(date, 'dd.MM.yyyy')).toBe(date);
+ });
+
+ it('should not parse if no format is specified', function() {
+ expect(dateParser.parse('21.08.1951', '')).toBe('21.08.1951');
+ });
+
+ it('should reinitialize when locale changes', inject(function($locale) {
+ spyOn(dateParser, 'init').and.callThrough();
+ expect($locale.id).toBe('en-us');
+
+ $locale.id = 'en-uk';
+
+ dateParser.parse('22.March.15.22', 'd.MMMM.yy.s');
+
+ expect(dateParser.init).toHaveBeenCalled();
+ }));
+});
+
+/* Deprecation tests below */
+
+describe('date parser deprecation', function() {
+ beforeEach(module('ui.bootstrap.dateparser'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$dateParserSuppressWarning', true);
+ });
+
+ inject(function($log, dateParser) {
+ spyOn($log, 'warn');
+
+ dateParser.parse('01.10.2015', 'dd.MM.yyyy');
+
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($log) {
+ spyOn($log, 'warn');
+
+ inject(function(dateParser) {
+ dateParser.parse('01.10.2015', 'dd.MM.yyyy');
+
+ expect($log.warn.calls.count()).toBe(1);
+ expect($log.warn.calls.argsFor(0)).toEqual(['dateParser is now deprecated. Use uibDateParser instead.']);
+ });
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/datepicker.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/datepicker.js
new file mode 100644
index 0000000..7cf8759
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/datepicker.js
@@ -0,0 +1,1186 @@
+angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.position'])
+
+.value('$datepickerSuppressError', false)
+
+.constant('uibDatepickerConfig', {
+ formatDay: 'dd',
+ formatMonth: 'MMMM',
+ formatYear: 'yyyy',
+ formatDayHeader: 'EEE',
+ formatDayTitle: 'MMMM yyyy',
+ formatMonthTitle: 'yyyy',
+ datepickerMode: 'day',
+ minMode: 'day',
+ maxMode: 'year',
+ showWeeks: true,
+ startingDay: 0,
+ yearRange: 20,
+ minDate: null,
+ maxDate: null,
+ shortcutPropagation: false
+})
+
+.controller('UibDatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$log', 'dateFilter', 'uibDatepickerConfig', '$datepickerSuppressError', function($scope, $attrs, $parse, $interpolate, $log, dateFilter, datepickerConfig, $datepickerSuppressError) {
+ var self = this,
+ ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl;
+
+ // Modes chain
+ this.modes = ['day', 'month', 'year'];
+
+ // Configuration attributes
+ angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle',
+ 'showWeeks', 'startingDay', 'yearRange', 'shortcutPropagation'], function(key, index) {
+ self[key] = angular.isDefined($attrs[key]) ? (index < 6 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key];
+ });
+
+ // Watchable date attributes
+ angular.forEach(['minDate', 'maxDate'], function(key) {
+ if ($attrs[key]) {
+ $scope.$parent.$watch($parse($attrs[key]), function(value) {
+ self[key] = value ? new Date(value) : null;
+ self.refreshView();
+ });
+ } else {
+ self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null;
+ }
+ });
+
+ angular.forEach(['minMode', 'maxMode'], function(key) {
+ if ($attrs[key]) {
+ $scope.$parent.$watch($parse($attrs[key]), function(value) {
+ self[key] = angular.isDefined(value) ? value : $attrs[key];
+ $scope[key] = self[key];
+ if ((key == 'minMode' && self.modes.indexOf($scope.datepickerMode) < self.modes.indexOf(self[key])) || (key == 'maxMode' && self.modes.indexOf($scope.datepickerMode) > self.modes.indexOf(self[key]))) {
+ $scope.datepickerMode = self[key];
+ }
+ });
+ } else {
+ self[key] = datepickerConfig[key] || null;
+ $scope[key] = self[key];
+ }
+ });
+
+ $scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode;
+ $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000);
+
+ if (angular.isDefined($attrs.initDate)) {
+ this.activeDate = $scope.$parent.$eval($attrs.initDate) || new Date();
+ $scope.$parent.$watch($attrs.initDate, function(initDate) {
+ if (initDate && (ngModelCtrl.$isEmpty(ngModelCtrl.$modelValue) || ngModelCtrl.$invalid)) {
+ self.activeDate = initDate;
+ self.refreshView();
+ }
+ });
+ } else {
+ this.activeDate = new Date();
+ }
+
+ $scope.isActive = function(dateObject) {
+ if (self.compare(dateObject.date, self.activeDate) === 0) {
+ $scope.activeDateId = dateObject.uid;
+ return true;
+ }
+ return false;
+ };
+
+ this.init = function(ngModelCtrl_) {
+ ngModelCtrl = ngModelCtrl_;
+
+ ngModelCtrl.$render = function() {
+ self.render();
+ };
+ };
+
+ this.render = function() {
+ if (ngModelCtrl.$viewValue) {
+ var date = new Date(ngModelCtrl.$viewValue),
+ isValid = !isNaN(date);
+
+ if (isValid) {
+ this.activeDate = date;
+ } else if (!$datepickerSuppressError) {
+ $log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
+ }
+ }
+ this.refreshView();
+ };
+
+ this.refreshView = function() {
+ if (this.element) {
+ this._refreshView();
+
+ var date = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;
+ ngModelCtrl.$setValidity('dateDisabled', !date || (this.element && !this.isDisabled(date)));
+ }
+ };
+
+ this.createDateObject = function(date, format) {
+ var model = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;
+ return {
+ date: date,
+ label: dateFilter(date, format),
+ selected: model && this.compare(date, model) === 0,
+ disabled: this.isDisabled(date),
+ current: this.compare(date, new Date()) === 0,
+ customClass: this.customClass(date)
+ };
+ };
+
+ this.isDisabled = function(date) {
+ return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode})));
+ };
+
+ this.customClass = function(date) {
+ return $scope.customClass({date: date, mode: $scope.datepickerMode});
+ };
+
+ // Split array into smaller arrays
+ this.split = function(arr, size) {
+ var arrays = [];
+ while (arr.length > 0) {
+ arrays.push(arr.splice(0, size));
+ }
+ return arrays;
+ };
+
+ $scope.select = function(date) {
+ if ($scope.datepickerMode === self.minMode) {
+ var dt = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : new Date(0, 0, 0, 0, 0, 0, 0);
+ dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
+ ngModelCtrl.$setViewValue(dt);
+ ngModelCtrl.$render();
+ } else {
+ self.activeDate = date;
+ $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) - 1];
+ }
+ };
+
+ $scope.move = function(direction) {
+ var year = self.activeDate.getFullYear() + direction * (self.step.years || 0),
+ month = self.activeDate.getMonth() + direction * (self.step.months || 0);
+ self.activeDate.setFullYear(year, month, 1);
+ self.refreshView();
+ };
+
+ $scope.toggleMode = function(direction) {
+ direction = direction || 1;
+
+ if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) {
+ return;
+ }
+
+ $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) + direction];
+ };
+
+ // Key event mapper
+ $scope.keys = { 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down' };
+
+ var focusElement = function() {
+ self.element[0].focus();
+ };
+
+ // Listen for focus requests from popup directive
+ $scope.$on('uib:datepicker.focus', focusElement);
+
+ $scope.keydown = function(evt) {
+ var key = $scope.keys[evt.which];
+
+ if (!key || evt.shiftKey || evt.altKey) {
+ return;
+ }
+
+ evt.preventDefault();
+ if (!self.shortcutPropagation) {
+ evt.stopPropagation();
+ }
+
+ if (key === 'enter' || key === 'space') {
+ if (self.isDisabled(self.activeDate)) {
+ return; // do nothing
+ }
+ $scope.select(self.activeDate);
+ } else if (evt.ctrlKey && (key === 'up' || key === 'down')) {
+ $scope.toggleMode(key === 'up' ? 1 : -1);
+ } else {
+ self.handleKeyDown(key, evt);
+ self.refreshView();
+ }
+ };
+}])
+
+.controller('UibDaypickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) {
+ var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+
+ this.step = { months: 1 };
+ this.element = $element;
+ function getDaysInMonth(year, month) {
+ return ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0))) ? 29 : DAYS_IN_MONTH[month];
+ }
+
+ this.init = function(ctrl) {
+ angular.extend(ctrl, this);
+ scope.showWeeks = ctrl.showWeeks;
+ ctrl.refreshView();
+ };
+
+ this.getDates = function(startDate, n) {
+ var dates = new Array(n), current = new Date(startDate), i = 0, date;
+ while (i < n) {
+ date = new Date(current);
+ dates[i++] = date;
+ current.setDate(current.getDate() + 1);
+ }
+ return dates;
+ };
+
+ this._refreshView = function() {
+ var year = this.activeDate.getFullYear(),
+ month = this.activeDate.getMonth(),
+ firstDayOfMonth = new Date(this.activeDate);
+
+ firstDayOfMonth.setFullYear(year, month, 1);
+
+ var difference = this.startingDay - firstDayOfMonth.getDay(),
+ numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : - difference,
+ firstDate = new Date(firstDayOfMonth);
+
+ if (numDisplayedFromPreviousMonth > 0) {
+ firstDate.setDate(-numDisplayedFromPreviousMonth + 1);
+ }
+
+ // 42 is the number of days on a six-month calendar
+ var days = this.getDates(firstDate, 42);
+ for (var i = 0; i < 42; i ++) {
+ days[i] = angular.extend(this.createDateObject(days[i], this.formatDay), {
+ secondary: days[i].getMonth() !== month,
+ uid: scope.uniqueId + '-' + i
+ });
+ }
+
+ scope.labels = new Array(7);
+ for (var j = 0; j < 7; j++) {
+ scope.labels[j] = {
+ abbr: dateFilter(days[j].date, this.formatDayHeader),
+ full: dateFilter(days[j].date, 'EEEE')
+ };
+ }
+
+ scope.title = dateFilter(this.activeDate, this.formatDayTitle);
+ scope.rows = this.split(days, 7);
+
+ if (scope.showWeeks) {
+ scope.weekNumbers = [];
+ var thursdayIndex = (4 + 7 - this.startingDay) % 7,
+ numWeeks = scope.rows.length;
+ for (var curWeek = 0; curWeek < numWeeks; curWeek++) {
+ scope.weekNumbers.push(
+ getISO8601WeekNumber(scope.rows[curWeek][thursdayIndex].date));
+ }
+ }
+ };
+
+ this.compare = function(date1, date2) {
+ return (new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()));
+ };
+
+ function getISO8601WeekNumber(date) {
+ var checkDate = new Date(date);
+ checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday
+ var time = checkDate.getTime();
+ checkDate.setMonth(0); // Compare with Jan 1
+ checkDate.setDate(1);
+ return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
+ }
+
+ this.handleKeyDown = function(key, evt) {
+ var date = this.activeDate.getDate();
+
+ if (key === 'left') {
+ date = date - 1; // up
+ } else if (key === 'up') {
+ date = date - 7; // down
+ } else if (key === 'right') {
+ date = date + 1; // down
+ } else if (key === 'down') {
+ date = date + 7;
+ } else if (key === 'pageup' || key === 'pagedown') {
+ var month = this.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1);
+ this.activeDate.setMonth(month, 1);
+ date = Math.min(getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth()), date);
+ } else if (key === 'home') {
+ date = 1;
+ } else if (key === 'end') {
+ date = getDaysInMonth(this.activeDate.getFullYear(), this.activeDate.getMonth());
+ }
+ this.activeDate.setDate(date);
+ };
+}])
+
+.controller('UibMonthpickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) {
+ this.step = { years: 1 };
+ this.element = $element;
+
+ this.init = function(ctrl) {
+ angular.extend(ctrl, this);
+ ctrl.refreshView();
+ };
+
+ this._refreshView = function() {
+ var months = new Array(12),
+ year = this.activeDate.getFullYear(),
+ date;
+
+ for (var i = 0; i < 12; i++) {
+ date = new Date(this.activeDate);
+ date.setFullYear(year, i, 1);
+ months[i] = angular.extend(this.createDateObject(date, this.formatMonth), {
+ uid: scope.uniqueId + '-' + i
+ });
+ }
+
+ scope.title = dateFilter(this.activeDate, this.formatMonthTitle);
+ scope.rows = this.split(months, 3);
+ };
+
+ this.compare = function(date1, date2) {
+ return new Date(date1.getFullYear(), date1.getMonth()) - new Date(date2.getFullYear(), date2.getMonth());
+ };
+
+ this.handleKeyDown = function(key, evt) {
+ var date = this.activeDate.getMonth();
+
+ if (key === 'left') {
+ date = date - 1; // up
+ } else if (key === 'up') {
+ date = date - 3; // down
+ } else if (key === 'right') {
+ date = date + 1; // down
+ } else if (key === 'down') {
+ date = date + 3;
+ } else if (key === 'pageup' || key === 'pagedown') {
+ var year = this.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1);
+ this.activeDate.setFullYear(year);
+ } else if (key === 'home') {
+ date = 0;
+ } else if (key === 'end') {
+ date = 11;
+ }
+ this.activeDate.setMonth(date);
+ };
+}])
+
+.controller('UibYearpickerController', ['$scope', '$element', 'dateFilter', function(scope, $element, dateFilter) {
+ var range;
+ this.element = $element;
+
+ function getStartingYear(year) {
+ return parseInt((year - 1) / range, 10) * range + 1;
+ }
+
+ this.yearpickerInit = function() {
+ range = this.yearRange;
+ this.step = { years: range };
+ };
+
+ this._refreshView = function() {
+ var years = new Array(range), date;
+
+ for (var i = 0, start = getStartingYear(this.activeDate.getFullYear()); i < range; i++) {
+ date = new Date(this.activeDate);
+ date.setFullYear(start + i, 0, 1);
+ years[i] = angular.extend(this.createDateObject(date, this.formatYear), {
+ uid: scope.uniqueId + '-' + i
+ });
+ }
+
+ scope.title = [years[0].label, years[range - 1].label].join(' - ');
+ scope.rows = this.split(years, 5);
+ };
+
+ this.compare = function(date1, date2) {
+ return date1.getFullYear() - date2.getFullYear();
+ };
+
+ this.handleKeyDown = function(key, evt) {
+ var date = this.activeDate.getFullYear();
+
+ if (key === 'left') {
+ date = date - 1; // up
+ } else if (key === 'up') {
+ date = date - 5; // down
+ } else if (key === 'right') {
+ date = date + 1; // down
+ } else if (key === 'down') {
+ date = date + 5;
+ } else if (key === 'pageup' || key === 'pagedown') {
+ date += (key === 'pageup' ? - 1 : 1) * this.step.years;
+ } else if (key === 'home') {
+ date = getStartingYear(this.activeDate.getFullYear());
+ } else if (key === 'end') {
+ date = getStartingYear(this.activeDate.getFullYear()) + range - 1;
+ }
+ this.activeDate.setFullYear(date);
+ };
+}])
+
+.directive('uibDatepicker', function() {
+ return {
+ replace: true,
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/datepicker/datepicker.html';
+ },
+ scope: {
+ datepickerMode: '=?',
+ dateDisabled: '&',
+ customClass: '&',
+ shortcutPropagation: '&?'
+ },
+ require: ['uibDatepicker', '^ngModel'],
+ controller: 'UibDatepickerController',
+ controllerAs: 'datepicker',
+ link: function(scope, element, attrs, ctrls) {
+ var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+
+ datepickerCtrl.init(ngModelCtrl);
+ }
+ };
+})
+
+.directive('uibDaypicker', function() {
+ return {
+ replace: true,
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/datepicker/day.html';
+ },
+ require: ['^?uibDatepicker', 'uibDaypicker', '^?datepicker'],
+ controller: 'UibDaypickerController',
+ link: function(scope, element, attrs, ctrls) {
+ var datepickerCtrl = ctrls[0] || ctrls[2],
+ daypickerCtrl = ctrls[1];
+
+ daypickerCtrl.init(datepickerCtrl);
+ }
+ };
+})
+
+.directive('uibMonthpicker', function() {
+ return {
+ replace: true,
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/datepicker/month.html';
+ },
+ require: ['^?uibDatepicker', 'uibMonthpicker', '^?datepicker'],
+ controller: 'UibMonthpickerController',
+ link: function(scope, element, attrs, ctrls) {
+ var datepickerCtrl = ctrls[0] || ctrls[2],
+ monthpickerCtrl = ctrls[1];
+
+ monthpickerCtrl.init(datepickerCtrl);
+ }
+ };
+})
+
+.directive('uibYearpicker', function() {
+ return {
+ replace: true,
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/datepicker/year.html';
+ },
+ require: ['^?uibDatepicker', 'uibYearpicker', '^?datepicker'],
+ controller: 'UibYearpickerController',
+ link: function(scope, element, attrs, ctrls) {
+ var ctrl = ctrls[0] || ctrls[2];
+ angular.extend(ctrl, ctrls[1]);
+ ctrl.yearpickerInit();
+
+ ctrl.refreshView();
+ }
+ };
+})
+
+.constant('uibDatepickerPopupConfig', {
+ datepickerPopup: 'yyyy-MM-dd',
+ datepickerPopupTemplateUrl: 'template/datepicker/popup.html',
+ datepickerTemplateUrl: 'template/datepicker/datepicker.html',
+ html5Types: {
+ date: 'yyyy-MM-dd',
+ 'datetime-local': 'yyyy-MM-ddTHH:mm:ss.sss',
+ 'month': 'yyyy-MM'
+ },
+ currentText: 'Today',
+ clearText: 'Clear',
+ closeText: 'Done',
+ closeOnDateSelection: true,
+ appendToBody: false,
+ showButtonBar: true,
+ onOpenFocus: true
+})
+
+.controller('UibDatepickerPopupController', ['$scope', '$element', '$attrs', '$compile', '$parse', '$document', '$rootScope', '$uibPosition', 'dateFilter', 'uibDateParser', 'uibDatepickerPopupConfig', '$timeout',
+function(scope, element, attrs, $compile, $parse, $document, $rootScope, $position, dateFilter, dateParser, datepickerPopupConfig, $timeout) {
+ var self = this;
+ var cache = {},
+ isHtml5DateInput = false;
+ var dateFormat, closeOnDateSelection, appendToBody, onOpenFocus,
+ datepickerPopupTemplateUrl, datepickerTemplateUrl, popupEl, datepickerEl,
+ ngModel, $popup;
+
+ scope.watchData = {};
+
+ this.init = function(_ngModel_) {
+ ngModel = _ngModel_;
+ closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? scope.$parent.$eval(attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection;
+ appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? scope.$parent.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody;
+ onOpenFocus = angular.isDefined(attrs.onOpenFocus) ? scope.$parent.$eval(attrs.onOpenFocus) : datepickerPopupConfig.onOpenFocus;
+ datepickerPopupTemplateUrl = angular.isDefined(attrs.datepickerPopupTemplateUrl) ? attrs.datepickerPopupTemplateUrl : datepickerPopupConfig.datepickerPopupTemplateUrl;
+ datepickerTemplateUrl = angular.isDefined(attrs.datepickerTemplateUrl) ? attrs.datepickerTemplateUrl : datepickerPopupConfig.datepickerTemplateUrl;
+
+ scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? scope.$parent.$eval(attrs.showButtonBar) : datepickerPopupConfig.showButtonBar;
+
+ if (datepickerPopupConfig.html5Types[attrs.type]) {
+ dateFormat = datepickerPopupConfig.html5Types[attrs.type];
+ isHtml5DateInput = true;
+ } else {
+ dateFormat = attrs.datepickerPopup || attrs.uibDatepickerPopup || datepickerPopupConfig.datepickerPopup;
+ attrs.$observe('uibDatepickerPopup', function(value, oldValue) {
+ var newDateFormat = value || datepickerPopupConfig.datepickerPopup;
+ // Invalidate the $modelValue to ensure that formatters re-run
+ // FIXME: Refactor when PR is merged: https://github.com/angular/angular.js/pull/10764
+ if (newDateFormat !== dateFormat) {
+ dateFormat = newDateFormat;
+ ngModel.$modelValue = null;
+
+ if (!dateFormat) {
+ throw new Error('uibDatepickerPopup must have a date format specified.');
+ }
+ }
+ });
+ }
+
+ if (!dateFormat) {
+ throw new Error('uibDatepickerPopup must have a date format specified.');
+ }
+
+ if (isHtml5DateInput && attrs.datepickerPopup) {
+ throw new Error('HTML5 date input types do not support custom formats.');
+ }
+
+ // popup element used to display calendar
+ popupEl = angular.element('<div uib-datepicker-popup-wrap><div uib-datepicker></div></div>');
+ popupEl.attr({
+ 'ng-model': 'date',
+ 'ng-change': 'dateSelection(date)',
+ 'template-url': datepickerPopupTemplateUrl
+ });
+
+ // datepicker element
+ datepickerEl = angular.element(popupEl.children()[0]);
+ datepickerEl.attr('template-url', datepickerTemplateUrl);
+
+ if (isHtml5DateInput) {
+ if (attrs.type === 'month') {
+ datepickerEl.attr('datepicker-mode', '"month"');
+ datepickerEl.attr('min-mode', 'month');
+ }
+ }
+
+ if (attrs.datepickerOptions) {
+ var options = scope.$parent.$eval(attrs.datepickerOptions);
+ if (options && options.initDate) {
+ scope.initDate = options.initDate;
+ datepickerEl.attr('init-date', 'initDate');
+ delete options.initDate;
+ }
+ angular.forEach(options, function(value, option) {
+ datepickerEl.attr(cameltoDash(option), value);
+ });
+ }
+
+ angular.forEach(['minMode', 'maxMode', 'minDate', 'maxDate', 'datepickerMode', 'initDate', 'shortcutPropagation'], function(key) {
+ if (attrs[key]) {
+ var getAttribute = $parse(attrs[key]);
+ scope.$parent.$watch(getAttribute, function(value) {
+ scope.watchData[key] = value;
+ if (key === 'minDate' || key === 'maxDate') {
+ cache[key] = new Date(value);
+ }
+ });
+ datepickerEl.attr(cameltoDash(key), 'watchData.' + key);
+
+ // Propagate changes from datepicker to outside
+ if (key === 'datepickerMode') {
+ var setAttribute = getAttribute.assign;
+ scope.$watch('watchData.' + key, function(value, oldvalue) {
+ if (angular.isFunction(setAttribute) && value !== oldvalue) {
+ setAttribute(scope.$parent, value);
+ }
+ });
+ }
+ }
+ });
+ if (attrs.dateDisabled) {
+ datepickerEl.attr('date-disabled', 'dateDisabled({ date: date, mode: mode })');
+ }
+
+ if (attrs.showWeeks) {
+ datepickerEl.attr('show-weeks', attrs.showWeeks);
+ }
+
+ if (attrs.customClass) {
+ datepickerEl.attr('custom-class', 'customClass({ date: date, mode: mode })');
+ }
+
+ if (!isHtml5DateInput) {
+ // Internal API to maintain the correct ng-invalid-[key] class
+ ngModel.$$parserName = 'date';
+ ngModel.$validators.date = validator;
+ ngModel.$parsers.unshift(parseDate);
+ ngModel.$formatters.push(function(value) {
+ scope.date = value;
+ return ngModel.$isEmpty(value) ? value : dateFilter(value, dateFormat);
+ });
+ } else {
+ ngModel.$formatters.push(function(value) {
+ scope.date = value;
+ return value;
+ });
+ }
+
+ // Detect changes in the view from the text box
+ ngModel.$viewChangeListeners.push(function() {
+ scope.date = dateParser.parse(ngModel.$viewValue, dateFormat, scope.date);
+ });
+
+ element.bind('keydown', inputKeydownBind);
+
+ $popup = $compile(popupEl)(scope);
+ // Prevent jQuery cache memory leak (template is now redundant after linking)
+ popupEl.remove();
+
+ if (appendToBody) {
+ $document.find('body').append($popup);
+ } else {
+ element.after($popup);
+ }
+
+ scope.$on('$destroy', function() {
+ if (scope.isOpen === true) {
+ if (!$rootScope.$$phase) {
+ scope.$apply(function() {
+ scope.isOpen = false;
+ });
+ }
+ }
+
+ $popup.remove();
+ element.unbind('keydown', inputKeydownBind);
+ $document.unbind('click', documentClickBind);
+ });
+ };
+
+ scope.getText = function(key) {
+ return scope[key + 'Text'] || datepickerPopupConfig[key + 'Text'];
+ };
+
+ scope.isDisabled = function(date) {
+ if (date === 'today') {
+ date = new Date();
+ }
+
+ return ((scope.watchData.minDate && scope.compare(date, cache.minDate) < 0) ||
+ (scope.watchData.maxDate && scope.compare(date, cache.maxDate) > 0));
+ };
+
+ scope.compare = function(date1, date2) {
+ return (new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()) - new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()));
+ };
+
+ // Inner change
+ scope.dateSelection = function(dt) {
+ if (angular.isDefined(dt)) {
+ scope.date = dt;
+ }
+ var date = scope.date ? dateFilter(scope.date, dateFormat) : null; // Setting to NULL is necessary for form validators to function
+ element.val(date);
+ ngModel.$setViewValue(date);
+
+ if (closeOnDateSelection) {
+ scope.isOpen = false;
+ element[0].focus();
+ }
+ };
+
+ scope.keydown = function(evt) {
+ if (evt.which === 27) {
+ scope.isOpen = false;
+ element[0].focus();
+ }
+ };
+
+ scope.select = function(date) {
+ if (date === 'today') {
+ var today = new Date();
+ if (angular.isDate(scope.date)) {
+ date = new Date(scope.date);
+ date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate());
+ } else {
+ date = new Date(today.setHours(0, 0, 0, 0));
+ }
+ }
+ scope.dateSelection(date);
+ };
+
+ scope.close = function() {
+ scope.isOpen = false;
+ element[0].focus();
+ };
+
+ scope.$watch('isOpen', function(value) {
+ if (value) {
+ scope.position = appendToBody ? $position.offset(element) : $position.position(element);
+ scope.position.top = scope.position.top + element.prop('offsetHeight');
+
+ $timeout(function() {
+ if (onOpenFocus) {
+ scope.$broadcast('uib:datepicker.focus');
+ }
+ $document.bind('click', documentClickBind);
+ }, 0, false);
+ } else {
+ $document.unbind('click', documentClickBind);
+ }
+ });
+
+ function cameltoDash(string) {
+ return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); });
+ }
+
+ function parseDate(viewValue) {
+ if (angular.isNumber(viewValue)) {
+ // presumably timestamp to date object
+ viewValue = new Date(viewValue);
+ }
+
+ if (!viewValue) {
+ return null;
+ } else if (angular.isDate(viewValue) && !isNaN(viewValue)) {
+ return viewValue;
+ } else if (angular.isString(viewValue)) {
+ var date = dateParser.parse(viewValue, dateFormat, scope.date);
+ if (isNaN(date)) {
+ return undefined;
+ } else {
+ return date;
+ }
+ } else {
+ return undefined;
+ }
+ }
+
+ function validator(modelValue, viewValue) {
+ var value = modelValue || viewValue;
+
+ if (!attrs.ngRequired && !value) {
+ return true;
+ }
+
+ if (angular.isNumber(value)) {
+ value = new Date(value);
+ }
+ if (!value) {
+ return true;
+ } else if (angular.isDate(value) && !isNaN(value)) {
+ return true;
+ } else if (angular.isString(value)) {
+ var date = dateParser.parse(value, dateFormat);
+ return !isNaN(date);
+ } else {
+ return false;
+ }
+ }
+
+ function documentClickBind(event) {
+ var popup = $popup[0];
+ var dpContainsTarget = element[0].contains(event.target);
+ // The popup node may not be an element node
+ // In some browsers (IE) only element nodes have the 'contains' function
+ var popupContainsTarget = popup.contains !== undefined && popup.contains(event.target);
+ if (scope.isOpen && !(dpContainsTarget || popupContainsTarget)) {
+ scope.$apply(function() {
+ scope.isOpen = false;
+ });
+ }
+ }
+
+ function inputKeydownBind(evt) {
+ if (evt.which === 27 && scope.isOpen) {
+ evt.preventDefault();
+ evt.stopPropagation();
+ scope.$apply(function() {
+ scope.isOpen = false;
+ });
+ element[0].focus();
+ } else if (evt.which === 40 && !scope.isOpen) {
+ evt.preventDefault();
+ evt.stopPropagation();
+ scope.$apply(function() {
+ scope.isOpen = true;
+ });
+ }
+ }
+}])
+
+.directive('uibDatepickerPopup', function() {
+ return {
+ require: ['ngModel', 'uibDatepickerPopup'],
+ controller: 'UibDatepickerPopupController',
+ scope: {
+ isOpen: '=?',
+ currentText: '@',
+ clearText: '@',
+ closeText: '@',
+ dateDisabled: '&',
+ customClass: '&'
+ },
+ link: function(scope, element, attrs, ctrls) {
+ var ngModel = ctrls[0],
+ ctrl = ctrls[1];
+
+ ctrl.init(ngModel);
+ }
+ };
+})
+
+.directive('uibDatepickerPopupWrap', function() {
+ return {
+ replace: true,
+ transclude: true,
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/datepicker/popup.html';
+ }
+ };
+});
+
+/* Deprecated datepicker below */
+
+angular.module('ui.bootstrap.datepicker')
+
+.value('$datepickerSuppressWarning', false)
+
+.controller('DatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$log', 'dateFilter', 'uibDatepickerConfig', '$datepickerSuppressError', '$datepickerSuppressWarning', function($scope, $attrs, $parse, $interpolate, $log, dateFilter, datepickerConfig, $datepickerSuppressError, $datepickerSuppressWarning) {
+ if (!$datepickerSuppressWarning) {
+ $log.warn('DatepickerController is now deprecated. Use UibDatepickerController instead.');
+ }
+
+ var self = this,
+ ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl;
+
+ this.modes = ['day', 'month', 'year'];
+
+ angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle',
+ 'showWeeks', 'startingDay', 'yearRange', 'shortcutPropagation'], function(key, index) {
+ self[key] = angular.isDefined($attrs[key]) ? (index < 6 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key];
+ });
+
+ angular.forEach(['minDate', 'maxDate'], function(key) {
+ if ($attrs[key]) {
+ $scope.$parent.$watch($parse($attrs[key]), function(value) {
+ self[key] = value ? new Date(value) : null;
+ self.refreshView();
+ });
+ } else {
+ self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null;
+ }
+ });
+
+ angular.forEach(['minMode', 'maxMode'], function(key) {
+ if ($attrs[key]) {
+ $scope.$parent.$watch($parse($attrs[key]), function(value) {
+ self[key] = angular.isDefined(value) ? value : $attrs[key];
+ $scope[key] = self[key];
+ if ((key == 'minMode' && self.modes.indexOf($scope.datepickerMode) < self.modes.indexOf(self[key])) || (key == 'maxMode' && self.modes.indexOf($scope.datepickerMode) > self.modes.indexOf(self[key]))) {
+ $scope.datepickerMode = self[key];
+ }
+ });
+ } else {
+ self[key] = datepickerConfig[key] || null;
+ $scope[key] = self[key];
+ }
+ });
+
+ $scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode;
+ $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000);
+
+ if (angular.isDefined($attrs.initDate)) {
+ this.activeDate = $scope.$parent.$eval($attrs.initDate) || new Date();
+ $scope.$parent.$watch($attrs.initDate, function(initDate) {
+ if (initDate && (ngModelCtrl.$isEmpty(ngModelCtrl.$modelValue) || ngModelCtrl.$invalid)) {
+ self.activeDate = initDate;
+ self.refreshView();
+ }
+ });
+ } else {
+ this.activeDate = new Date();
+ }
+
+ $scope.isActive = function(dateObject) {
+ if (self.compare(dateObject.date, self.activeDate) === 0) {
+ $scope.activeDateId = dateObject.uid;
+ return true;
+ }
+ return false;
+ };
+
+ this.init = function(ngModelCtrl_) {
+ ngModelCtrl = ngModelCtrl_;
+
+ ngModelCtrl.$render = function() {
+ self.render();
+ };
+ };
+
+ this.render = function() {
+ if (ngModelCtrl.$viewValue) {
+ var date = new Date(ngModelCtrl.$viewValue),
+ isValid = !isNaN(date);
+
+ if (isValid) {
+ this.activeDate = date;
+ } else if (!$datepickerSuppressError) {
+ $log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
+ }
+ }
+ this.refreshView();
+ };
+
+ this.refreshView = function() {
+ if (this.element) {
+ this._refreshView();
+
+ var date = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;
+ ngModelCtrl.$setValidity('dateDisabled', !date || (this.element && !this.isDisabled(date)));
+ }
+ };
+
+ this.createDateObject = function(date, format) {
+ var model = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;
+ return {
+ date: date,
+ label: dateFilter(date, format),
+ selected: model && this.compare(date, model) === 0,
+ disabled: this.isDisabled(date),
+ current: this.compare(date, new Date()) === 0,
+ customClass: this.customClass(date)
+ };
+ };
+
+ this.isDisabled = function(date) {
+ return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode})));
+ };
+
+ this.customClass = function(date) {
+ return $scope.customClass({date: date, mode: $scope.datepickerMode});
+ };
+
+ // Split array into smaller arrays
+ this.split = function(arr, size) {
+ var arrays = [];
+ while (arr.length > 0) {
+ arrays.push(arr.splice(0, size));
+ }
+ return arrays;
+ };
+
+ this.fixTimeZone = function(date) {
+ var hours = date.getHours();
+ date.setHours(hours === 23 ? hours + 2 : 0);
+ };
+
+ $scope.select = function(date) {
+ if ($scope.datepickerMode === self.minMode) {
+ var dt = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : new Date(0, 0, 0, 0, 0, 0, 0);
+ dt.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
+ ngModelCtrl.$setViewValue(dt);
+ ngModelCtrl.$render();
+ } else {
+ self.activeDate = date;
+ $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) - 1];
+ }
+ };
+
+ $scope.move = function(direction) {
+ var year = self.activeDate.getFullYear() + direction * (self.step.years || 0),
+ month = self.activeDate.getMonth() + direction * (self.step.months || 0);
+ self.activeDate.setFullYear(year, month, 1);
+ self.refreshView();
+ };
+
+ $scope.toggleMode = function(direction) {
+ direction = direction || 1;
+
+ if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) {
+ return;
+ }
+
+ $scope.datepickerMode = self.modes[self.modes.indexOf($scope.datepickerMode) + direction];
+ };
+
+ // Key event mapper
+ $scope.keys = { 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down' };
+
+ var focusElement = function() {
+ self.element[0].focus();
+ };
+
+ $scope.$on('uib:datepicker.focus', focusElement);
+
+ $scope.keydown = function(evt) {
+ var key = $scope.keys[evt.which];
+
+ if (!key || evt.shiftKey || evt.altKey) {
+ return;
+ }
+
+ evt.preventDefault();
+ if (!self.shortcutPropagation) {
+ evt.stopPropagation();
+ }
+
+ if (key === 'enter' || key === 'space') {
+ if (self.isDisabled(self.activeDate)) {
+ return; // do nothing
+ }
+ $scope.select(self.activeDate);
+ } else if (evt.ctrlKey && (key === 'up' || key === 'down')) {
+ $scope.toggleMode(key === 'up' ? 1 : -1);
+ } else {
+ self.handleKeyDown(key, evt);
+ self.refreshView();
+ }
+ };
+}])
+
+.directive('datepicker', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) {
+ return {
+ replace: true,
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/datepicker/datepicker.html';
+ },
+ scope: {
+ datepickerMode: '=?',
+ dateDisabled: '&',
+ customClass: '&',
+ shortcutPropagation: '&?'
+ },
+ require: ['datepicker', '^ngModel'],
+ controller: 'DatepickerController',
+ controllerAs: 'datepicker',
+ link: function(scope, element, attrs, ctrls) {
+ if (!$datepickerSuppressWarning) {
+ $log.warn('datepicker is now deprecated. Use uib-datepicker instead.');
+ }
+
+ var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+
+ datepickerCtrl.init(ngModelCtrl);
+ }
+ };
+}])
+
+.directive('daypicker', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) {
+ return {
+ replace: true,
+ templateUrl: 'template/datepicker/day.html',
+ require: ['^datepicker', 'daypicker'],
+ controller: 'UibDaypickerController',
+ link: function(scope, element, attrs, ctrls) {
+ if (!$datepickerSuppressWarning) {
+ $log.warn('daypicker is now deprecated. Use uib-daypicker instead.');
+ }
+
+ var datepickerCtrl = ctrls[0],
+ daypickerCtrl = ctrls[1];
+
+ daypickerCtrl.init(datepickerCtrl);
+ }
+ };
+}])
+
+.directive('monthpicker', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) {
+ return {
+ replace: true,
+ templateUrl: 'template/datepicker/month.html',
+ require: ['^datepicker', 'monthpicker'],
+ controller: 'UibMonthpickerController',
+ link: function(scope, element, attrs, ctrls) {
+ if (!$datepickerSuppressWarning) {
+ $log.warn('monthpicker is now deprecated. Use uib-monthpicker instead.');
+ }
+
+ var datepickerCtrl = ctrls[0],
+ monthpickerCtrl = ctrls[1];
+
+ monthpickerCtrl.init(datepickerCtrl);
+ }
+ };
+}])
+
+.directive('yearpicker', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) {
+ return {
+ replace: true,
+ templateUrl: 'template/datepicker/year.html',
+ require: ['^datepicker', 'yearpicker'],
+ controller: 'UibYearpickerController',
+ link: function(scope, element, attrs, ctrls) {
+ if (!$datepickerSuppressWarning) {
+ $log.warn('yearpicker is now deprecated. Use uib-yearpicker instead.');
+ }
+
+ var ctrl = ctrls[0];
+ angular.extend(ctrl, ctrls[1]);
+ ctrl.yearpickerInit();
+
+ ctrl.refreshView();
+ }
+ };
+}])
+
+.directive('datepickerPopup', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) {
+ return {
+ require: ['ngModel', 'datepickerPopup'],
+ controller: 'UibDatepickerPopupController',
+ scope: {
+ isOpen: '=?',
+ currentText: '@',
+ clearText: '@',
+ closeText: '@',
+ dateDisabled: '&',
+ customClass: '&'
+ },
+ link: function(scope, element, attrs, ctrls) {
+ if (!$datepickerSuppressWarning) {
+ $log.warn('datepicker-popup is now deprecated. Use uib-datepicker-popup instead.');
+ }
+
+ var ngModel = ctrls[0],
+ ctrl = ctrls[1];
+
+ ctrl.init(ngModel);
+ }
+ };
+}])
+
+.directive('datepickerPopupWrap', ['$log', '$datepickerSuppressWarning', function($log, $datepickerSuppressWarning) {
+ return {
+ replace: true,
+ transclude: true,
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/datepicker/popup.html';
+ },
+ link: function() {
+ if (!$datepickerSuppressWarning) {
+ $log.warn('datepicker-popup-wrap is now deprecated. Use uib-datepicker-popup-wrap instead.');
+ }
+ }
+ };
+}]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/docs/demo.html
new file mode 100644
index 0000000..8a057a3
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/docs/demo.html
@@ -0,0 +1,52 @@
+<style>
+ .full button span {
+ background-color: limegreen;
+ border-radius: 32px;
+ color: black;
+ }
+ .partially button span {
+ background-color: orange;
+ border-radius: 32px;
+ color: black;
+ }
+</style>
+<div ng-controller="DatepickerDemoCtrl">
+ <pre>Selected date is: <em>{{dt | date:'fullDate' }}</em></pre>
+
+ <h4>Inline</h4>
+ <div style="display:inline-block; min-height:290px;">
+ <uib-datepicker ng-model="dt" min-date="minDate" show-weeks="true" class="well well-sm" custom-class="getDayClass(date, mode)"></uib-datepicker>
+ </div>
+
+ <h4>Popup</h4>
+ <div class="row">
+ <div class="col-md-6">
+ <p class="input-group">
+ <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="dt" is-open="status.opened" min-date="minDate" max-date="maxDate" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" close-text="Close" />
+ <span class="input-group-btn">
+ <button type="button" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
+ </span>
+ </p>
+ </div>
+
+ <div class="col-md-6">
+ <p class="input-group">
+ <input type="date" class="form-control" uib-datepicker-popup ng-model="dt" is-open="status.opened" min-date="minDate" max-date="maxDate" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" close-text="Close" />
+ <span class="input-group-btn">
+ <button type="button" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
+ </span>
+ </p>
+ </div>
+ </div>
+ <div class="row">
+ <div class="col-md-6">
+ <label>Format:</label> <select class="form-control" ng-model="format" ng-options="f for f in formats"><option></option></select>
+ </div>
+ </div>
+
+ <hr />
+ <button type="button" class="btn btn-sm btn-info" ng-click="today()">Today</button>
+ <button type="button" class="btn btn-sm btn-default" ng-click="setDate(2009, 7, 24)">2009-08-24</button>
+ <button type="button" class="btn btn-sm btn-danger" ng-click="clear()">Clear</button>
+ <button type="button" class="btn btn-sm btn-default" ng-click="toggleMin()" uib-tooltip="After today restriction">Min date</button>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/docs/demo.js
new file mode 100644
index 0000000..419cb3d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/docs/demo.js
@@ -0,0 +1,73 @@
+angular.module('ui.bootstrap.demo').controller('DatepickerDemoCtrl', function ($scope) {
+ $scope.today = function() {
+ $scope.dt = new Date();
+ };
+ $scope.today();
+
+ $scope.clear = function () {
+ $scope.dt = null;
+ };
+
+ // Disable weekend selection
+ $scope.disabled = function(date, mode) {
+ return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) );
+ };
+
+ $scope.toggleMin = function() {
+ $scope.minDate = $scope.minDate ? null : new Date();
+ };
+ $scope.toggleMin();
+ $scope.maxDate = new Date(2020, 5, 22);
+
+ $scope.open = function($event) {
+ $scope.status.opened = true;
+ };
+
+ $scope.setDate = function(year, month, day) {
+ $scope.dt = new Date(year, month, day);
+ };
+
+ $scope.dateOptions = {
+ formatYear: 'yy',
+ startingDay: 1
+ };
+
+ $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
+ $scope.format = $scope.formats[0];
+
+ $scope.status = {
+ opened: false
+ };
+
+ var tomorrow = new Date();
+ tomorrow.setDate(tomorrow.getDate() + 1);
+ var afterTomorrow = new Date();
+ afterTomorrow.setDate(tomorrow.getDate() + 2);
+ $scope.events =
+ [
+ {
+ date: tomorrow,
+ status: 'full'
+ },
+ {
+ date: afterTomorrow,
+ status: 'partially'
+ }
+ ];
+
+ $scope.getDayClass = function(date, mode) {
+ if (mode === 'day') {
+ var dayToCheck = new Date(date).setHours(0,0,0,0);
+
+ for (var i=0;i<$scope.events.length;i++){
+ var currentDay = new Date($scope.events[i].date).setHours(0,0,0,0);
+
+ if (dayToCheck === currentDay) {
+ return $scope.events[i].status;
+ }
+ }
+ }
+
+ return '';
+ };
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/docs/readme.md
new file mode 100644
index 0000000..956032a
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/docs/readme.md
@@ -0,0 +1,157 @@
+A clean, flexible, and fully customizable date picker.
+
+User can navigate through months and years.
+The datepicker shows dates that come from other than the main month being displayed. These other dates are also selectable.
+
+Everything is formatted using the [date filter](http://docs.angularjs.org/api/ng.filter:date) and thus is also localized.
+
+### Datepicker Settings ###
+
+All settings can be provided as attributes in the `uib-datepicker` or globally configured through the `uibDatepickerConfig`.
+
+ * `ng-model` <i class="glyphicon glyphicon-eye-open"></i>
+ :
+ The date object.
+
+ * `datepicker-mode` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: 'day')_ :
+ Current mode of the datepicker _(day|month|year)_. Can be used to initialize datepicker to specific mode.
+
+ * `min-date` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Default: null)_ :
+ Defines the minimum available date.
+
+ * `max-date` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Default: null)_ :
+ Defines the maximum available date.
+
+ * `date-disabled (date, mode)`
+ _(Default: null)_ :
+ An optional expression to disable visible options based on passing date and current mode _(day|month|year)_.
+
+ * `custom-class (date, mode)`
+ _(Default: null)_ :
+ An optional expression to add classes based on passing date and current mode _(day|month|year)_.
+
+ * `show-weeks`
+ _(Defaults: true)_ :
+ Whether to display week numbers.
+
+ * `starting-day`
+ _(Defaults: 0)_ :
+ Starting day of the week from 0-6 (0=Sunday, ..., 6=Saturday).
+
+ * `init-date`
+ :
+ The initial date view when no model value is specified.
+
+ * `min-mode`
+ _(Defaults: 'day')_ :
+ Set a lower limit for mode.
+
+ * `max-mode`
+ _(Defaults: 'year')_ :
+ Set an upper limit for mode.
+
+ * `format-day`
+ _(Default: 'dd')_ :
+ Format of day in month.
+
+ * `format-month`
+ _(Default: 'MMMM')_ :
+ Format of month in year.
+
+ * `format-year`
+ _(Default: 'yyyy')_ :
+ Format of year in year range.
+
+ * `format-day-header`
+ _(Default: 'EEE')_ :
+ Format of day in week header.
+
+ * `format-day-title`
+ _(Default: 'MMMM yyyy')_ :
+ Format of title when selecting day.
+
+ * `format-month-title`
+ _(Default: 'yyyy')_ :
+ Format of title when selecting month.
+
+ * `year-range`
+ _(Default: 20)_ :
+ Number of years displayed in year selection.
+
+ * `shortcut-propagation`
+ _(Default: false)_ :
+ An option to disable or enable shortcut's event propagation.
+
+ * `template-url`
+ _(Default: 'template/datepicker/datepicker.html')_ :
+ Allows overriding of default template of the datepicker
+
+
+### Popup Settings ###
+
+Options for datepicker can be passed as JSON using the `datepicker-options` attribute.
+Specific settings for the `uib-datepicker-popup`, that can globally configured through the `uibDatepickerPopupConfig`, are:
+
+ * `uib-datepicker-popup`
+ _(Default: 'yyyy-MM-dd')_ :
+ The format for displayed dates.
+
+ * `show-button-bar`
+ _(Default: true)_ :
+ Whether to display a button bar underneath the datepicker.
+
+ * `current-text`
+ _(Default: 'Today')_ :
+ The text to display for the current day button.
+
+ * `clear-text`
+ _(Default: 'Clear')_ :
+ The text to display for the clear button.
+
+ * `close-text`
+ _(Default: 'Done')_ :
+ The text to display for the close button.
+
+ * `close-on-date-selection`
+ _(Default: true)_ :
+ Whether to close calendar when a date is chosen.
+
+ * `datepicker-popup-template-url`
+ _(Default: 'template/datepicker/popup.html')_ :
+ Allows overriding of default template of the popup
+
+ * `datepicker-template-url`
+ _(Default: 'template/datepicker/datepicker.html')_ :
+ Allows overriding of default template of the datepicker used in popup
+
+ * `datepicker-append-to-body`
+ _(Default: false)_:
+ Append the datepicker popup element to `body`, rather than inserting after `datepicker-popup`. For global configuration, use `uibDatepickerPopupConfig.appendToBody`.
+
+ * `is-open` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Default: false)_:
+ Whether to show the datepicker.
+
+ * `on-open-focus`
+ _(Default: true)_:
+ Whether to focus the datepicker popup upon opening.
+
+### Keyboard Support ###
+
+Depending on datepicker's current mode, the date may refer either to day, month or year. Accordingly, the term view refers either to a month, year or year range.
+
+ * `Left`: Move focus to the previous date. Will move to the last date of the previous view, if the current date is the first date of a view.
+ * `Right`: Move focus to the next date. Will move to the first date of the following view, if the current date is the last date of a view.
+ * `Up`: Move focus to the same column of the previous row. Will wrap to the appropriate row in the previous view.
+ * `Down`: Move focus to the same column of the following row. Will wrap to the appropriate row in the following view.
+ * `PgUp`: Move focus to the same date of the previous view. If that date does not exist, focus is placed on the last date of the month.
+ * `PgDn`: Move focus to the same date of the following view. If that date does not exist, focus is placed on the last date of the month.
+ * `Home`: Move to the first date of the view.
+ * `End`: Move to the last date of the view.
+ * `Enter`/`Space`: Select date.
+ * `Ctrl`+`Up`: Move to an upper mode.
+ * `Ctrl`+`Down`: Move to a lower mode.
+ * `Esc`: Will close popup, and move focus to the input.
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/test/datepicker.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/test/datepicker.spec.js
new file mode 100644
index 0000000..6ab0ce8
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/datepicker/test/datepicker.spec.js
@@ -0,0 +1,2515 @@
+describe('datepicker directive', function() {
+ var $rootScope, $compile, $templateCache, element;
+ beforeEach(module('ui.bootstrap.datepicker'));
+ beforeEach(module('template/datepicker/datepicker.html'));
+ beforeEach(module('template/datepicker/day.html'));
+ beforeEach(module('template/datepicker/month.html'));
+ beforeEach(module('template/datepicker/year.html'));
+ beforeEach(module('template/datepicker/popup.html'));
+ beforeEach(module(function($compileProvider) {
+ $compileProvider.directive('dateModel', function() {
+ return {
+ restrict: 'A',
+ require: 'ngModel',
+ link: function(scope, element, attrs, modelController) {
+ modelController.$formatters.push(function(object) {
+ return new Date(object.date);
+ });
+
+ modelController.$parsers.push(function(date) {
+ return {
+ type: 'date',
+ date: date.toUTCString()
+ };
+ });
+ }
+ };
+ });
+ }));
+
+ function getTitleButton() {
+ return element.find('th').eq(1).find('button').first();
+ }
+
+ function getTitle() {
+ return getTitleButton().text();
+ }
+
+ function clickTitleButton() {
+ getTitleButton().click();
+ }
+
+ function clickPreviousButton(times) {
+ var el = element.find('th').eq(0).find('button').eq(0);
+ for (var i = 0, n = times || 1; i < n; i++) {
+ el.click();
+ }
+ }
+
+ function clickNextButton() {
+ element.find('th').eq(2).find('button').eq(0).click();
+ }
+
+ function getLabelsRow() {
+ return element.find('thead').find('tr').eq(1);
+ }
+
+ function getLabels(dayMode) {
+ var els = getLabelsRow().find('th'),
+ labels = [];
+ for (var i = dayMode ? 1 : 0, n = els.length; i < n; i++) {
+ labels.push(els.eq(i).text());
+ }
+ return labels;
+ }
+
+ function getWeeks() {
+ var rows = element.find('tbody').find('tr'),
+ weeks = [];
+ for (var i = 0, n = rows.length; i < n; i++) {
+ weeks.push(rows.eq(i).find('td').eq(0).first().text());
+ }
+ return weeks;
+ }
+
+ function getOptions(dayMode) {
+ var tr = element.find('tbody').find('tr');
+ var rows = [];
+
+ for (var j = 0, numRows = tr.length; j < numRows; j++) {
+ var cols = tr.eq(j).find('td'), days = [];
+ for (var i = dayMode ? 1 : 0, n = cols.length; i < n; i++) {
+ days.push(cols.eq(i).find('button').text());
+ }
+ rows.push(days);
+ }
+ return rows;
+ }
+
+ function clickOption(index) {
+ getAllOptionsEl().eq(index).click();
+ }
+
+ function getAllOptionsEl(dayMode) {
+ return element.find('tbody').find('button');
+ }
+
+ function selectedElementIndex() {
+ var buttons = getAllOptionsEl();
+ for (var i = 0; i < buttons.length; i++) {
+ if (angular.element(buttons[i]).hasClass('btn-info')) {
+ return i;
+ }
+ }
+ }
+
+ function expectSelectedElement(index) {
+ var buttons = getAllOptionsEl();
+ angular.forEach( buttons, function(button, idx) {
+ expect(angular.element(button).hasClass('btn-info')).toBe(idx === index);
+ });
+ }
+
+ function triggerKeyDown(element, key, ctrl) {
+ var keyCodes = {
+ 'enter': 13,
+ 'space': 32,
+ 'pageup': 33,
+ 'pagedown': 34,
+ 'end': 35,
+ 'home': 36,
+ 'left': 37,
+ 'up': 38,
+ 'right': 39,
+ 'down': 40,
+ 'esc': 27
+ };
+ var e = $.Event('keydown');
+ e.which = keyCodes[key];
+ if (ctrl) {
+ e.ctrlKey = true;
+ }
+ element.trigger(e);
+ }
+
+ describe('$datepickerSuppressError', function() {
+ var $compile,
+ $log,
+ $scope;
+
+ it('should not suppress log error message for ng-model date error by default', function() {
+ inject(function(_$log_, _$rootScope_, _$compile_) {
+ $log = _$log_;
+ $scope = _$rootScope_.$new();
+ $compile = _$compile_;
+ });
+
+ spyOn($log, 'error');
+ element = $compile('<uib-datepicker ng-model="locals.date"></uib-datepicker>')($scope);
+
+ $scope.locals = {
+ date: 'lalala'
+ };
+ $scope.$digest();
+ expect($log.error).toHaveBeenCalled();
+ });
+
+ it('should not suppress log error message for ng-model date error when false', function() {
+ module(function($provide) {
+ $provide.value('$datepickerSuppressError', false);
+ });
+
+ inject(function(_$log_, _$rootScope_, _$compile_) {
+ $log = _$log_;
+ $scope = _$rootScope_.$new();
+ $compile = _$compile_;
+ });
+
+ spyOn($log, 'error');
+ element = $compile('<uib-datepicker ng-model="locals.date"></uib-datepicker>')($scope);
+
+ $scope.locals = {
+ date: 'lalala'
+ };
+ $scope.$digest();
+ expect($log.error).toHaveBeenCalled();
+ });
+
+ it('should suppress log error message for ng-model date error when true', function() {
+ module(function($provide) {
+ $provide.value('$datepickerSuppressError', true);
+ });
+
+ inject(function(_$log_, _$rootScope_, _$compile_) {
+ $log = _$log_;
+ $scope = _$rootScope_.$new();
+ $compile = _$compile_;
+ });
+ spyOn($log, 'error');
+
+ element = $compile('<uib-datepicker ng-model="locals.date"></uib-datepicker>')($scope);
+
+ $scope.locals = {
+ date: 'lalala'
+ };
+ $scope.$digest();
+ expect($log.error).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('', function() {
+ beforeEach(inject(function(_$compile_, _$rootScope_, _$templateCache_) {
+ $compile = _$compile_;
+ $rootScope = _$rootScope_;
+ $rootScope.date = new Date('September 30, 2010 15:30:00');
+ $templateCache = _$templateCache_;
+ }));
+
+
+ describe('', function() {
+ beforeEach(function() {
+ element = $compile('<uib-datepicker ng-model="date"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('is has a `<table>` element', function() {
+ expect(element.find('table').length).toBe(1);
+ });
+
+ it('shows the correct title', function() {
+ expect(getTitle()).toBe('September 2010');
+ });
+
+ it('shows the label row & the correct day labels', function() {
+ expect(getLabelsRow().css('display')).not.toBe('none');
+ expect(getLabels(true)).toEqual(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']);
+ });
+
+ it('renders the calendar days correctly', function() {
+ expect(getOptions(true)).toEqual([
+ ['29', '30', '31', '01', '02', '03', '04'],
+ ['05', '06', '07', '08', '09', '10', '11'],
+ ['12', '13', '14', '15', '16', '17', '18'],
+ ['19', '20', '21', '22', '23', '24', '25'],
+ ['26', '27', '28', '29', '30', '01', '02'],
+ ['03', '04', '05', '06', '07', '08', '09']
+ ]);
+ });
+
+ it('renders the week numbers based on ISO 8601', function() {
+ expect(getWeeks()).toEqual(['35', '36', '37', '38', '39', '40']);
+ });
+
+ it('value is correct', function() {
+ expect($rootScope.date).toEqual(new Date('September 30, 2010 15:30:00'));
+ });
+
+ it('has `selected` only the correct day', function() {
+ expectSelectedElement(32);
+ });
+
+ it('has no `selected` day when model is cleared', function() {
+ $rootScope.date = null;
+ $rootScope.$digest();
+
+ expect($rootScope.date).toBe(null);
+ expectSelectedElement(null);
+ });
+
+ it('does not change current view when model is cleared', function() {
+ $rootScope.date = null;
+ $rootScope.$digest();
+
+ expect($rootScope.date).toBe(null);
+ expect(getTitle()).toBe('September 2010');
+ });
+
+ it('`disables` visible dates from other months', function() {
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).find('span').hasClass('text-muted')).toBe( index < 3 || index > 32 );
+ });
+ });
+
+ it('updates the model when a day is clicked', function() {
+ clickOption(17);
+ expect($rootScope.date).toEqual(new Date('September 15, 2010 15:30:00'));
+ });
+
+ it('moves to the previous month & renders correctly when `previous` button is clicked', function() {
+ clickPreviousButton();
+
+ expect(getTitle()).toBe('August 2010');
+ expect(getLabels(true)).toEqual(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']);
+ expect(getOptions(true)).toEqual([
+ ['01', '02', '03', '04', '05', '06', '07'],
+ ['08', '09', '10', '11', '12', '13', '14'],
+ ['15', '16', '17', '18', '19', '20', '21'],
+ ['22', '23', '24', '25', '26', '27', '28'],
+ ['29', '30', '31', '01', '02', '03', '04'],
+ ['05', '06', '07', '08', '09', '10', '11']
+ ]);
+
+ expectSelectedElement(null, null);
+ });
+
+ it('updates the model only when a day is clicked in the `previous` month', function() {
+ clickPreviousButton();
+ expect($rootScope.date).toEqual(new Date('September 30, 2010 15:30:00'));
+
+ clickOption(17);
+ expect($rootScope.date).toEqual(new Date('August 18, 2010 15:30:00'));
+ });
+
+ it('moves to the next month & renders correctly when `next` button is clicked', function() {
+ clickNextButton();
+
+ expect(getTitle()).toBe('October 2010');
+ expect(getLabels(true)).toEqual(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']);
+ expect(getOptions(true)).toEqual([
+ ['26', '27', '28', '29', '30', '01', '02'],
+ ['03', '04', '05', '06', '07', '08', '09'],
+ ['10', '11', '12', '13', '14', '15', '16'],
+ ['17', '18', '19', '20', '21', '22', '23'],
+ ['24', '25', '26', '27', '28', '29', '30'],
+ ['31', '01', '02', '03', '04', '05', '06']
+ ]);
+
+ expectSelectedElement(4);
+ });
+
+ it('updates the model only when a day is clicked in the `next` month', function() {
+ clickNextButton();
+ expect($rootScope.date).toEqual(new Date('September 30, 2010 15:30:00'));
+
+ clickOption(17);
+ expect($rootScope.date).toEqual(new Date('October 13, 2010 15:30:00'));
+ });
+
+ it('updates the calendar when a day of another month is selected', function() {
+ clickOption(33);
+ expect($rootScope.date).toEqual(new Date('October 01, 2010 15:30:00'));
+ expect(getTitle()).toBe('October 2010');
+ expect(getLabels(true)).toEqual(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']);
+ expect(getOptions(true)).toEqual([
+ ['26', '27', '28', '29', '30', '01', '02'],
+ ['03', '04', '05', '06', '07', '08', '09'],
+ ['10', '11', '12', '13', '14', '15', '16'],
+ ['17', '18', '19', '20', '21', '22', '23'],
+ ['24', '25', '26', '27', '28', '29', '30'],
+ ['31', '01', '02', '03', '04', '05', '06']
+ ]);
+
+ expectSelectedElement(5);
+ });
+
+ // issue #1697
+ it('should not "jump" months', function() {
+ $rootScope.date = new Date('January 30, 2014');
+ $rootScope.$digest();
+ clickNextButton();
+ expect(getTitle()).toBe('February 2014');
+ clickPreviousButton();
+ expect(getTitle()).toBe('January 2014');
+ });
+
+ it('should support custom templates', function() {
+ $templateCache.put('foo/bar.html', '<div>baz</div>');
+
+ element = $compile('<uib-datepicker ng-model="date" template-url="foo/bar.html"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect(element.html()).toBe('baz');
+ });
+
+ it('should support custom day, month and year templates', function() {
+ $templateCache.put('foo/day.html', '<div>day</div>');
+ $templateCache.put('foo/month.html', '<div>month</div>');
+ $templateCache.put('foo/year.html', '<div>year</div>');
+
+ $templateCache.put('foo/bar.html', '<div>' +
+ '<uib-daypicker template-url="foo/day.html"></uib-daypicker>' +
+ '<uib-monthpicker template-url="foo/month.html"></uib-monthpicker>' +
+ '<uib-yearpicker template-url="foo/year.html"></uib-yearpicker>' +
+ '</div>');
+
+ element = $compile('<uib-datepicker ng-model="date" template-url="foo/bar.html"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+
+ var expectedHtml = '<div template-url="foo/day.html">day</div><div template-url="foo/month.html">month</div><div template-url="foo/year.html">year</div>';
+
+ expect(element.html()).toBe(expectedHtml);
+ });
+
+ it('should expose the controller in the template', function() {
+ $templateCache.put('template/datepicker/datepicker.html', '<div>{{datepicker.text}}</div>');
+
+ element = $compile('<uib-datepicker ng-model="date"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+
+ var ctrl = element.controller('uib-datepicker');
+ expect(ctrl).toBeDefined();
+ expect(element.html()).toBe('');
+
+ ctrl.text = 'baz';
+ $rootScope.$digest();
+
+ expect(element.html()).toBe('baz');
+ });
+
+ describe('when `model` changes', function() {
+ function testCalendar() {
+ expect(getTitle()).toBe('November 2005');
+ expect(getOptions(true)).toEqual([
+ ['30', '31', '01', '02', '03', '04', '05'],
+ ['06', '07', '08', '09', '10', '11', '12'],
+ ['13', '14', '15', '16', '17', '18', '19'],
+ ['20', '21', '22', '23', '24', '25', '26'],
+ ['27', '28', '29', '30', '01', '02', '03'],
+ ['04', '05', '06', '07', '08', '09', '10']
+ ]);
+
+ expectSelectedElement(8);
+ }
+
+ describe('to a Date object', function() {
+ it('updates', function() {
+ $rootScope.date = new Date('November 7, 2005 23:30:00');
+ $rootScope.$digest();
+ testCalendar();
+ expect(angular.isDate($rootScope.date)).toBe(true);
+ });
+
+ it('to a date that is invalid, it doesn\`t update', function() {
+ $rootScope.date = new Date('pizza');
+ $rootScope.$digest();
+ expect(getTitle()).toBe('September 2010');
+ expect(angular.isDate($rootScope.date)).toBe(true);
+ expect(isNaN($rootScope.date)).toBe(true);
+ });
+ });
+
+ describe('not to a Date object', function() {
+ it('to a Number, it updates calendar', function() {
+ $rootScope.date = parseInt((new Date('November 7, 2005 23:30:00')).getTime(), 10);
+ $rootScope.$digest();
+ testCalendar();
+ expect(angular.isNumber($rootScope.date)).toBe(true);
+ });
+
+ it('to a string that can be parsed by Date, it updates calendar', function() {
+ $rootScope.date = 'November 7, 2005 23:30:00';
+ $rootScope.$digest();
+ testCalendar();
+ expect(angular.isString($rootScope.date)).toBe(true);
+ });
+
+ it('to a string that cannot be parsed by Date, it doesn\'t update', function() {
+ $rootScope.date = 'pizza';
+ $rootScope.$digest();
+ expect(getTitle()).toBe('September 2010');
+ expect($rootScope.date).toBe('pizza');
+ });
+ });
+ });
+
+ it('does not loop between after max mode', function() {
+ expect(getTitle()).toBe('September 2010');
+
+ clickTitleButton();
+ expect(getTitle()).toBe('2010');
+
+ clickTitleButton();
+ expect(getTitle()).toBe('2001 - 2020');
+
+ clickTitleButton();
+ expect(getTitle()).toBe('2001 - 2020');
+ });
+
+ describe('month selection mode', function() {
+ beforeEach(function() {
+ clickTitleButton();
+ });
+
+ it('shows the year as title', function() {
+ expect(getTitle()).toBe('2010');
+ });
+
+ it('shows months as options', function() {
+ expect(getOptions()).toEqual([
+ ['January', 'February', 'March'],
+ ['April', 'May', 'June'],
+ ['July', 'August', 'September'],
+ ['October', 'November', 'December']
+ ]);
+ });
+
+ it('does not change the model', function() {
+ expect($rootScope.date).toEqual(new Date('September 30, 2010 15:30:00'));
+ });
+
+ it('has `selected` only the correct month', function() {
+ expectSelectedElement(8);
+ });
+
+ it('moves to the previous year when `previous` button is clicked', function() {
+ clickPreviousButton();
+
+ expect(getTitle()).toBe('2009');
+ expect(getOptions()).toEqual([
+ ['January', 'February', 'March'],
+ ['April', 'May', 'June'],
+ ['July', 'August', 'September'],
+ ['October', 'November', 'December']
+ ]);
+
+ expectSelectedElement(null);
+ });
+
+ it('moves to the next year when `next` button is clicked', function() {
+ clickNextButton();
+
+ expect(getTitle()).toBe('2011');
+ expect(getOptions()).toEqual([
+ ['January', 'February', 'March'],
+ ['April', 'May', 'June'],
+ ['July', 'August', 'September'],
+ ['October', 'November', 'December']
+ ]);
+
+ expectSelectedElement(null);
+ });
+
+ it('renders correctly when a month is clicked', function() {
+ clickPreviousButton(5);
+ expect(getTitle()).toBe('2005');
+
+ clickOption(10);
+ expect($rootScope.date).toEqual(new Date('September 30, 2010 15:30:00'));
+ expect(getTitle()).toBe('November 2005');
+ expect(getOptions(true)).toEqual([
+ ['30', '31', '01', '02', '03', '04', '05'],
+ ['06', '07', '08', '09', '10', '11', '12'],
+ ['13', '14', '15', '16', '17', '18', '19'],
+ ['20', '21', '22', '23', '24', '25', '26'],
+ ['27', '28', '29', '30', '01', '02', '03'],
+ ['04', '05', '06', '07', '08', '09', '10']
+ ]);
+
+ clickOption(17);
+ expect($rootScope.date).toEqual(new Date('November 16, 2005 15:30:00'));
+ });
+ });
+
+ describe('year selection mode', function() {
+ beforeEach(function() {
+ clickTitleButton();
+ clickTitleButton();
+ });
+
+ it('shows the year range as title', function() {
+ expect(getTitle()).toBe('2001 - 2020');
+ });
+
+ it('shows years as options', function() {
+ expect(getOptions()).toEqual([
+ ['2001', '2002', '2003', '2004', '2005'],
+ ['2006', '2007', '2008', '2009', '2010'],
+ ['2011', '2012', '2013', '2014', '2015'],
+ ['2016', '2017', '2018', '2019', '2020']
+ ]);
+ });
+
+ it('does not change the model', function() {
+ expect($rootScope.date).toEqual(new Date('September 30, 2010 15:30:00'));
+ });
+
+ it('has `selected` only the selected year', function() {
+ expectSelectedElement(9);
+ });
+
+ it('moves to the previous year set when `previous` button is clicked', function() {
+ clickPreviousButton();
+
+ expect(getTitle()).toBe('1981 - 2000');
+ expect(getOptions()).toEqual([
+ ['1981', '1982', '1983', '1984', '1985'],
+ ['1986', '1987', '1988', '1989', '1990'],
+ ['1991', '1992', '1993', '1994', '1995'],
+ ['1996', '1997', '1998', '1999', '2000']
+ ]);
+ expectSelectedElement(null);
+ });
+
+ it('moves to the next year set when `next` button is clicked', function() {
+ clickNextButton();
+
+ expect(getTitle()).toBe('2021 - 2040');
+ expect(getOptions()).toEqual([
+ ['2021', '2022', '2023', '2024', '2025'],
+ ['2026', '2027', '2028', '2029', '2030'],
+ ['2031', '2032', '2033', '2034', '2035'],
+ ['2036', '2037', '2038', '2039', '2040']
+ ]);
+
+ expectSelectedElement(null);
+ });
+ });
+
+ describe('keyboard navigation', function() {
+ function getActiveLabel() {
+ return element.find('.active').eq(0).text();
+ }
+
+ describe('day mode', function() {
+ it('will be able to activate previous day', function() {
+ triggerKeyDown(element, 'left');
+ expect(getActiveLabel()).toBe('29');
+ });
+
+ it('will be able to select with enter', function() {
+ triggerKeyDown(element, 'left');
+ triggerKeyDown(element, 'enter');
+ expect($rootScope.date).toEqual(new Date('September 29, 2010 15:30:00'));
+ });
+
+ it('will be able to select with space', function() {
+ triggerKeyDown(element, 'left');
+ triggerKeyDown(element, 'space');
+ expect($rootScope.date).toEqual(new Date('September 29, 2010 15:30:00'));
+ });
+
+ it('will be able to activate next day', function() {
+ triggerKeyDown(element, 'right');
+ expect(getActiveLabel()).toBe('01');
+ expect(getTitle()).toBe('October 2010');
+ });
+
+ it('will be able to activate same day in previous week', function() {
+ triggerKeyDown(element, 'up');
+ expect(getActiveLabel()).toBe('23');
+ });
+
+ it('will be able to activate same day in next week', function() {
+ triggerKeyDown(element, 'down');
+ expect(getActiveLabel()).toBe('07');
+ expect(getTitle()).toBe('October 2010');
+ });
+
+ it('will be able to activate same date in previous month', function() {
+ triggerKeyDown(element, 'pageup');
+ expect(getActiveLabel()).toBe('30');
+ expect(getTitle()).toBe('August 2010');
+ });
+
+ it('will be able to activate same date in next month', function() {
+ triggerKeyDown(element, 'pagedown');
+ expect(getActiveLabel()).toBe('30');
+ expect(getTitle()).toBe('October 2010');
+ });
+
+ it('will be able to activate first day of the month', function() {
+ triggerKeyDown(element, 'home');
+ expect(getActiveLabel()).toBe('01');
+ expect(getTitle()).toBe('September 2010');
+ });
+
+ it('will be able to activate last day of the month', function() {
+ $rootScope.date = new Date('September 1, 2010 15:30:00');
+ $rootScope.$digest();
+
+ triggerKeyDown(element, 'end');
+ expect(getActiveLabel()).toBe('30');
+ expect(getTitle()).toBe('September 2010');
+ });
+
+ it('will be able to move to month mode', function() {
+ triggerKeyDown(element, 'up', true);
+ expect(getActiveLabel()).toBe('September');
+ expect(getTitle()).toBe('2010');
+ });
+
+ it('will not respond when trying to move to lower mode', function() {
+ triggerKeyDown(element, 'down', true);
+ expect(getActiveLabel()).toBe('30');
+ expect(getTitle()).toBe('September 2010');
+ });
+ });
+
+ describe('month mode', function() {
+ beforeEach(function() {
+ triggerKeyDown(element, 'up', true);
+ });
+
+ it('will be able to activate previous month', function() {
+ triggerKeyDown(element, 'left');
+ expect(getActiveLabel()).toBe('August');
+ });
+
+ it('will be able to activate next month', function() {
+ triggerKeyDown(element, 'right');
+ expect(getActiveLabel()).toBe('October');
+ });
+
+ it('will be able to activate same month in previous row', function() {
+ triggerKeyDown(element, 'up');
+ expect(getActiveLabel()).toBe('June');
+ });
+
+ it('will be able to activate same month in next row', function() {
+ triggerKeyDown(element, 'down');
+ expect(getActiveLabel()).toBe('December');
+ });
+
+ it('will be able to activate same date in previous year', function() {
+ triggerKeyDown(element, 'pageup');
+ expect(getActiveLabel()).toBe('September');
+ expect(getTitle()).toBe('2009');
+ });
+
+ it('will be able to activate same date in next year', function() {
+ triggerKeyDown(element, 'pagedown');
+ expect(getActiveLabel()).toBe('September');
+ expect(getTitle()).toBe('2011');
+ });
+
+ it('will be able to activate first month of the year', function() {
+ triggerKeyDown(element, 'home');
+ expect(getActiveLabel()).toBe('January');
+ expect(getTitle()).toBe('2010');
+ });
+
+ it('will be able to activate last month of the year', function() {
+ triggerKeyDown(element, 'end');
+ expect(getActiveLabel()).toBe('December');
+ expect(getTitle()).toBe('2010');
+ });
+
+ it('will be able to move to year mode', function() {
+ triggerKeyDown(element, 'up', true);
+ expect(getActiveLabel()).toBe('2010');
+ expect(getTitle()).toBe('2001 - 2020');
+ });
+
+ it('will be able to move to day mode', function() {
+ triggerKeyDown(element, 'down', true);
+ expect(getActiveLabel()).toBe('30');
+ expect(getTitle()).toBe('September 2010');
+ });
+
+ it('will move to day mode when selecting', function() {
+ triggerKeyDown(element, 'left', true);
+ triggerKeyDown(element, 'enter', true);
+ expect(getActiveLabel()).toBe('30');
+ expect(getTitle()).toBe('August 2010');
+ expect($rootScope.date).toEqual(new Date('September 30, 2010 15:30:00'));
+ });
+ });
+
+ describe('year mode', function() {
+ beforeEach(function() {
+ triggerKeyDown(element, 'up', true);
+ triggerKeyDown(element, 'up', true);
+ });
+
+ it('will be able to activate previous year', function() {
+ triggerKeyDown(element, 'left');
+ expect(getActiveLabel()).toBe('2009');
+ });
+
+ it('will be able to activate next year', function() {
+ triggerKeyDown(element, 'right');
+ expect(getActiveLabel()).toBe('2011');
+ });
+
+ it('will be able to activate same year in previous row', function() {
+ triggerKeyDown(element, 'up');
+ expect(getActiveLabel()).toBe('2005');
+ });
+
+ it('will be able to activate same year in next row', function() {
+ triggerKeyDown(element, 'down');
+ expect(getActiveLabel()).toBe('2015');
+ });
+
+ it('will be able to activate same date in previous view', function() {
+ triggerKeyDown(element, 'pageup');
+ expect(getActiveLabel()).toBe('1990');
+ });
+
+ it('will be able to activate same date in next view', function() {
+ triggerKeyDown(element, 'pagedown');
+ expect(getActiveLabel()).toBe('2030');
+ });
+
+ it('will be able to activate first year of the year', function() {
+ triggerKeyDown(element, 'home');
+ expect(getActiveLabel()).toBe('2001');
+ });
+
+ it('will be able to activate last year of the year', function() {
+ triggerKeyDown(element, 'end');
+ expect(getActiveLabel()).toBe('2020');
+ });
+
+ it('will not respond when trying to move to upper mode', function() {
+ triggerKeyDown(element, 'up', true);
+ expect(getTitle()).toBe('2001 - 2020');
+ });
+
+ it('will be able to move to month mode', function() {
+ triggerKeyDown(element, 'down', true);
+ expect(getActiveLabel()).toBe('September');
+ expect(getTitle()).toBe('2010');
+ });
+
+ it('will move to month mode when selecting', function() {
+ triggerKeyDown(element, 'left', true);
+ triggerKeyDown(element, 'enter', true);
+ expect(getActiveLabel()).toBe('September');
+ expect(getTitle()).toBe('2009');
+ expect($rootScope.date).toEqual(new Date('September 30, 2010 15:30:00'));
+ });
+ });
+
+ describe('`aria-activedescendant`', function() {
+ function checkActivedescendant() {
+ var activeId = element.find('table').attr('aria-activedescendant');
+ expect(element.find('#' + activeId + ' > button')).toHaveClass('active');
+ }
+
+ it('updates correctly', function() {
+ triggerKeyDown(element, 'left');
+ checkActivedescendant();
+
+ triggerKeyDown(element, 'down');
+ checkActivedescendant();
+
+ triggerKeyDown(element, 'up', true);
+ checkActivedescendant();
+
+ triggerKeyDown(element, 'up', true);
+ checkActivedescendant();
+ });
+ });
+ });
+ });
+
+ describe('attribute `starting-day`', function () {
+ beforeEach(function() {
+ $rootScope.startingDay = 1;
+ element = $compile('<uib-datepicker ng-model="date" starting-day="startingDay"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('shows the day labels rotated', function() {
+ expect(getLabels(true)).toEqual(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']);
+ });
+
+ it('renders the calendar days correctly', function() {
+ expect(getOptions(true)).toEqual([
+ ['30', '31', '01', '02', '03', '04', '05'],
+ ['06', '07', '08', '09', '10', '11', '12'],
+ ['13', '14', '15', '16', '17', '18', '19'],
+ ['20', '21', '22', '23', '24', '25', '26'],
+ ['27', '28', '29', '30', '01', '02', '03'],
+ ['04', '05', '06', '07', '08', '09', '10']
+ ]);
+ });
+
+ it('renders the week numbers correctly', function() {
+ expect(getWeeks()).toEqual(['35', '36', '37', '38', '39', '40']);
+ });
+ });
+
+ describe('attribute `show-weeks`', function() {
+ beforeEach(function() {
+ $rootScope.showWeeks = false;
+ element = $compile('<uib-datepicker ng-model="date" show-weeks="showWeeks"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('hides week numbers based on variable', function() {
+ expect(getLabelsRow().find('th').length).toEqual(7);
+ var tr = element.find('tbody').find('tr');
+ for (var i = 0; i < 5; i++) {
+ expect(tr.eq(i).find('td').length).toEqual(7);
+ }
+ });
+ });
+
+ describe('`min-date` attribute', function () {
+ beforeEach(function() {
+ $rootScope.mindate = new Date('September 12, 2010');
+ element = $compile('<uib-datepicker ng-model="date" min-date="mindate"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('disables appropriate days in current month', function() {
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(index < 14);
+ });
+ });
+
+ it('disables appropriate days when min date changes', function() {
+ $rootScope.mindate = new Date('September 5, 2010');
+ $rootScope.$digest();
+
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(index < 7);
+ });
+ });
+
+ it('invalidates when model is a disabled date', function() {
+ $rootScope.mindate = new Date('September 5, 2010');
+ $rootScope.date = new Date('September 2, 2010');
+ $rootScope.$digest();
+ expect(element.hasClass('ng-invalid')).toBeTruthy();
+ expect(element.hasClass('ng-invalid-date-disabled')).toBeTruthy();
+ });
+
+ it('disables all days in previous month', function() {
+ clickPreviousButton();
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(true);
+ });
+ });
+
+ it('disables no days in next month', function() {
+ clickNextButton();
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(false);
+ });
+ });
+
+ it('disables appropriate months in current year', function() {
+ clickTitleButton();
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(index < 8);
+ });
+ });
+
+ it('disables all months in previous year', function() {
+ clickTitleButton();
+ clickPreviousButton();
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(true);
+ });
+ });
+
+ it('disables no months in next year', function() {
+ clickTitleButton();
+ clickNextButton();
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(false);
+ });
+ });
+
+ it('enables everything before if it is cleared', function() {
+ $rootScope.mindate = null;
+ $rootScope.date = new Date('December 20, 1949');
+ $rootScope.$digest();
+
+ clickTitleButton();
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(false);
+ });
+ });
+
+ });
+
+ describe('`max-date` attribute', function() {
+ beforeEach(function() {
+ $rootScope.maxdate = new Date('September 25, 2010');
+ element = $compile('<uib-datepicker ng-model="date" max-date="maxdate"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('disables appropriate days in current month', function() {
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(index > 27);
+ });
+ });
+
+ it('disables appropriate days when max date changes', function() {
+ $rootScope.maxdate = new Date('September 18, 2010');
+ $rootScope.$digest();
+
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(index > 20);
+ });
+ });
+
+ it('invalidates when model is a disabled date', function() {
+ $rootScope.maxdate = new Date('September 18, 2010');
+ $rootScope.$digest();
+ expect(element.hasClass('ng-invalid')).toBeTruthy();
+ expect(element.hasClass('ng-invalid-date-disabled')).toBeTruthy();
+ });
+
+ it('disables no days in previous month', function() {
+ clickPreviousButton();
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(false);
+ });
+ });
+
+ it('disables all days in next month', function() {
+ clickNextButton();
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(true);
+ });
+ });
+
+ it('disables appropriate months in current year', function() {
+ clickTitleButton();
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(index > 8);
+ });
+ });
+
+ it('disables no months in previous year', function() {
+ clickTitleButton();
+ clickPreviousButton();
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(false);
+ });
+ });
+
+ it('disables all months in next year', function() {
+ clickTitleButton();
+ clickNextButton();
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(true);
+ });
+ });
+
+ it('enables everything after if it is cleared', function() {
+ $rootScope.maxdate = null;
+ $rootScope.$digest();
+ var buttons = getAllOptionsEl();
+ angular.forEach(buttons, function(button, index) {
+ expect(angular.element(button).prop('disabled')).toBe(false);
+ });
+ });
+ });
+
+ describe('date-disabled expression', function () {
+ beforeEach(function() {
+ $rootScope.dateDisabledHandler = jasmine.createSpy('dateDisabledHandler');
+ element = $compile('<uib-datepicker ng-model="date" date-disabled="dateDisabledHandler(date, mode)"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('executes the dateDisabled expression for each visible day plus one for validation', function() {
+ expect($rootScope.dateDisabledHandler.calls.count()).toEqual(42 + 1);
+ });
+
+ it('executes the dateDisabled expression for each visible month plus one for validation', function() {
+ $rootScope.dateDisabledHandler.calls.reset();
+ clickTitleButton();
+ expect($rootScope.dateDisabledHandler.calls.count()).toEqual(12 + 1);
+ });
+
+ it('executes the dateDisabled expression for each visible year plus one for validation', function() {
+ clickTitleButton();
+ $rootScope.dateDisabledHandler.calls.reset();
+ clickTitleButton();
+ expect($rootScope.dateDisabledHandler.calls.count()).toEqual(20 + 1);
+ });
+ });
+
+ describe('custom-class expression', function() {
+ beforeEach(function() {
+ $rootScope.customClassHandler = jasmine.createSpy('customClassHandler');
+ element = $compile('<uib-datepicker ng-model="date" custom-class="customClassHandler(date, mode)"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('executes the customClass expression for each visible day plus one for validation', function() {
+ expect($rootScope.customClassHandler.calls.count()).toEqual(42);
+ });
+
+ it('executes the customClass expression for each visible month plus one for validation', function() {
+ $rootScope.customClassHandler.calls.reset();
+ clickTitleButton();
+ expect($rootScope.customClassHandler.calls.count()).toEqual(12);
+ });
+
+ it('executes the customClass expression for each visible year plus one for validation', function() {
+ clickTitleButton();
+ $rootScope.customClassHandler.calls.reset();
+ clickTitleButton();
+ expect($rootScope.customClassHandler.calls.count()).toEqual(20);
+ });
+ });
+
+ describe('formatting', function() {
+ beforeEach(function() {
+ $rootScope.dayTitle = 'MMMM, yy';
+ element = $compile('<uib-datepicker ng-model="date"' +
+ 'format-day="d"' +
+ 'format-day-header="EEEE"' +
+ 'format-day-title="{{dayTitle}}"' +
+ 'format-month="MMM"' +
+ 'format-month-title="yy"' +
+ 'format-year="yy"' +
+ 'year-range="10"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('changes the title format in `day` mode', function() {
+ expect(getTitle()).toBe('September, 10');
+ });
+
+ it('changes the title & months format in `month` mode', function() {
+ clickTitleButton();
+
+ expect(getTitle()).toBe('10');
+ expect(getOptions()).toEqual([
+ ['Jan', 'Feb', 'Mar'],
+ ['Apr', 'May', 'Jun'],
+ ['Jul', 'Aug', 'Sep'],
+ ['Oct', 'Nov', 'Dec']
+ ]);
+ });
+
+ it('changes the title, year format & range in `year` mode', function() {
+ clickTitleButton();
+ clickTitleButton();
+
+ expect(getTitle()).toBe('01 - 10');
+ expect(getOptions()).toEqual([
+ ['01', '02', '03', '04', '05'],
+ ['06', '07', '08', '09', '10']
+ ]);
+ });
+
+ it('shows day labels', function() {
+ expect(getLabels(true)).toEqual(['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']);
+ });
+
+ it('changes the day format', function() {
+ expect(getOptions(true)).toEqual([
+ ['29', '30', '31', '1', '2', '3', '4'],
+ ['5', '6', '7', '8', '9', '10', '11'],
+ ['12', '13', '14', '15', '16', '17', '18'],
+ ['19', '20', '21', '22', '23', '24', '25'],
+ ['26', '27', '28', '29', '30', '1', '2'],
+ ['3', '4', '5', '6', '7', '8', '9']
+ ]);
+ });
+ });
+
+ describe('setting datepickerConfig', function() {
+ var originalConfig = {};
+ beforeEach(inject(function(uibDatepickerConfig) {
+ angular.extend(originalConfig, uibDatepickerConfig);
+ uibDatepickerConfig.formatDay = 'd';
+ uibDatepickerConfig.formatMonth = 'MMM';
+ uibDatepickerConfig.formatYear = 'yy';
+ uibDatepickerConfig.formatDayHeader = 'EEEE';
+ uibDatepickerConfig.formatDayTitle = 'MMM, yy';
+ uibDatepickerConfig.formatMonthTitle = 'yy';
+ uibDatepickerConfig.showWeeks = false;
+ uibDatepickerConfig.yearRange = 10;
+ uibDatepickerConfig.startingDay = 6;
+
+ element = $compile('<uib-datepicker ng-model="date"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+ afterEach(inject(function(uibDatepickerConfig) {
+ // return it to the original state
+ angular.extend(uibDatepickerConfig, originalConfig);
+ }));
+
+ it('changes the title format in `day` mode', function() {
+ expect(getTitle()).toBe('Sep, 10');
+ });
+
+ it('changes the title & months format in `month` mode', function() {
+ clickTitleButton();
+
+ expect(getTitle()).toBe('10');
+ expect(getOptions()).toEqual([
+ ['Jan', 'Feb', 'Mar'],
+ ['Apr', 'May', 'Jun'],
+ ['Jul', 'Aug', 'Sep'],
+ ['Oct', 'Nov', 'Dec']
+ ]);
+ });
+
+ it('changes the title, year format & range in `year` mode', function() {
+ clickTitleButton();
+ clickTitleButton();
+
+ expect(getTitle()).toBe('01 - 10');
+ expect(getOptions()).toEqual([
+ ['01', '02', '03', '04', '05'],
+ ['06', '07', '08', '09', '10']
+ ]);
+ });
+
+ it('changes the `starting-day` & day headers & format', function() {
+ expect(getLabels()).toEqual(['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']);
+ expect(getOptions(false)).toEqual([
+ ['28', '29', '30', '31', '1', '2', '3'],
+ ['4', '5', '6', '7', '8', '9', '10'],
+ ['11', '12', '13', '14', '15', '16', '17'],
+ ['18', '19', '20', '21', '22', '23', '24'],
+ ['25', '26', '27', '28', '29', '30', '1'],
+ ['2', '3', '4', '5', '6', '7', '8']
+ ]);
+ });
+
+ it('changes initial visibility for weeks', function() {
+ expect(getLabelsRow().find('th').length).toEqual(7);
+ var tr = element.find('tbody').find('tr');
+ for (var i = 0; i < 5; i++) {
+ expect(tr.eq(i).find('td').length).toEqual(7);
+ }
+ });
+
+ });
+
+ describe('setting datepickerPopupConfig', function() {
+ var originalConfig = {};
+ beforeEach(inject(function(uibDatepickerPopupConfig) {
+ angular.extend(originalConfig, uibDatepickerPopupConfig);
+ uibDatepickerPopupConfig.datepickerPopup = 'MM-dd-yyyy';
+
+ element = $compile('<input ng-model="date" uib-datepicker-popup>')($rootScope);
+ $rootScope.$digest();
+ }));
+ afterEach(inject(function(uibDatepickerPopupConfig) {
+ // return it to the original state
+ angular.extend(uibDatepickerPopupConfig, originalConfig);
+ }));
+
+ it('changes date format', function() {
+ expect(element.val()).toEqual('09-30-2010');
+ });
+
+ });
+
+ describe('setting datepickerPopupConfig inside ng-if', function() {
+ var originalConfig = {};
+ beforeEach(inject(function (uibDatepickerPopupConfig) {
+ angular.extend(originalConfig, uibDatepickerPopupConfig);
+ uibDatepickerPopupConfig.datepickerPopup = 'MM-dd-yyyy';
+
+ element = $compile('<div><div ng-if="true"><input ng-model="date" uib-datepicker-popup></div></div>')($rootScope);
+ $rootScope.$digest();
+ }));
+ afterEach(inject(function (uibDatepickerPopupConfig) {
+ // return it to the original state
+ angular.extend(uibDatepickerPopupConfig, originalConfig);
+ }));
+
+ it('changes date format', function () {
+ expect(element.find('input').val()).toEqual('09-30-2010');
+ });
+ });
+
+ describe('as popup', function () {
+ var inputEl, dropdownEl, $document, $sniffer, $timeout;
+
+ function assignElements(wrapElement) {
+ inputEl = wrapElement.find('input');
+ dropdownEl = wrapElement.find('ul');
+ element = dropdownEl.find('table');
+ }
+
+ function changeInputValueTo(el, value) {
+ el.val(value);
+ el.trigger($sniffer.hasEvent('input') ? 'input' : 'change');
+ $rootScope.$digest();
+ }
+
+ describe('initially', function () {
+ beforeEach(inject(function(_$document_, _$sniffer_) {
+ $document = _$document_;
+ $sniffer = _$sniffer_;
+ $rootScope.isopen = true;
+ $rootScope.date = new Date('September 30, 2010 15:30:00');
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ }));
+
+ it('does not to display datepicker initially', function() {
+ expect(dropdownEl.length).toBe(0);
+ });
+
+ it('to display the correct value in input', function() {
+ expect(inputEl.val()).toBe('2010-09-30');
+ });
+ });
+
+ describe('initially opened', function() {
+ var wrapElement;
+
+ beforeEach(inject(function(_$document_, _$sniffer_, _$timeout_) {
+ $document = _$document_;
+ $sniffer = _$sniffer_;
+ $timeout = _$timeout_;
+ $rootScope.isopen = true;
+ $rootScope.date = new Date('September 30, 2010 15:30:00');
+ wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup is-open="isopen"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ }));
+
+ it('datepicker is displayed', function() {
+ expect(dropdownEl.length).toBe(1);
+ });
+
+ it('renders the calendar correctly', function() {
+ expect(getLabelsRow().css('display')).not.toBe('none');
+ expect(getLabels(true)).toEqual(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']);
+ expect(getOptions(true)).toEqual([
+ ['29', '30', '31', '01', '02', '03', '04'],
+ ['05', '06', '07', '08', '09', '10', '11'],
+ ['12', '13', '14', '15', '16', '17', '18'],
+ ['19', '20', '21', '22', '23', '24', '25'],
+ ['26', '27', '28', '29', '30', '01', '02'],
+ ['03', '04', '05', '06', '07', '08', '09']
+ ]);
+ });
+
+ it('updates the input when a day is clicked', function() {
+ clickOption(17);
+ expect(inputEl.val()).toBe('2010-09-15');
+ expect($rootScope.date).toEqual(new Date('September 15, 2010 15:30:00'));
+ });
+
+ it('should mark the input field dirty when a day is clicked', function() {
+ expect(inputEl).toHaveClass('ng-pristine');
+ clickOption(17);
+ expect(inputEl).toHaveClass('ng-dirty');
+ });
+
+ it('updates the input correctly when model changes', function() {
+ $rootScope.date = new Date('January 10, 1983 10:00:00');
+ $rootScope.$digest();
+ expect(inputEl.val()).toBe('1983-01-10');
+ });
+
+ it('closes the dropdown when a day is clicked', function() {
+ expect(dropdownEl.length).toBe(1);
+
+ clickOption(17);
+ assignElements(wrapElement);
+ expect(dropdownEl.length).toBe(0);
+ });
+
+ it('updates the model & calendar when input value changes', function() {
+ changeInputValueTo(inputEl, '2010-09-15');
+
+ expect($rootScope.date.getFullYear()).toEqual(2010);
+ expect($rootScope.date.getMonth()).toEqual(8);
+ expect($rootScope.date.getDate()).toEqual(15);
+
+ expect(getOptions(true)).toEqual([
+ ['29', '30', '31', '01', '02', '03', '04'],
+ ['05', '06', '07', '08', '09', '10', '11'],
+ ['12', '13', '14', '15', '16', '17', '18'],
+ ['19', '20', '21', '22', '23', '24', '25'],
+ ['26', '27', '28', '29', '30', '01', '02'],
+ ['03', '04', '05', '06', '07', '08', '09']
+ ]);
+ expectSelectedElement(17);
+ });
+
+ it('closes when click outside of calendar', function() {
+ expect(dropdownEl.length).toBe(1);
+
+ $timeout.flush(0);
+ $document.find('body').click();
+ assignElements(wrapElement);
+ expect(dropdownEl.length).toBe(0);
+ });
+
+ it('sets `ng-invalid` for invalid input', function() {
+ changeInputValueTo(inputEl, 'pizza');
+
+ expect(inputEl).toHaveClass('ng-invalid');
+ expect(inputEl).toHaveClass('ng-invalid-date');
+ expect($rootScope.date).toBeUndefined();
+ expect(inputEl.val()).toBe('pizza');
+ });
+
+ it('unsets `ng-invalid` for valid input', function() {
+ changeInputValueTo(inputEl, 'pizza');
+ expect(inputEl).toHaveClass('ng-invalid-date');
+
+ $rootScope.date = new Date('August 11, 2013');
+ $rootScope.$digest();
+ expect(inputEl).not.toHaveClass('ng-invalid');
+ expect(inputEl).not.toHaveClass('ng-invalid-date');
+ });
+
+ describe('focus', function () {
+ beforeEach(function() {
+ var body = $document.find('body');
+ body.append(inputEl);
+ body.append(dropdownEl);
+ });
+
+ afterEach(function() {
+ inputEl.remove();
+ dropdownEl.remove();
+ });
+
+ it('returns to the input when ESC key is pressed in the popup and closes', function() {
+ expect(dropdownEl.length).toBe(1);
+
+ dropdownEl.find('button').eq(0).focus();
+ expect(document.activeElement.tagName).toBe('BUTTON');
+
+ triggerKeyDown(dropdownEl, 'esc');
+ assignElements(wrapElement);
+ expect(dropdownEl.length).toBe(0);
+ expect(document.activeElement.tagName).toBe('INPUT');
+ });
+
+ it('returns to the input when ESC key is pressed in the input and closes', function() {
+ expect(dropdownEl.length).toBe(1);
+
+ dropdownEl.find('button').eq(0).focus();
+ expect(document.activeElement.tagName).toBe('BUTTON');
+
+ triggerKeyDown(inputEl, 'esc');
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ expect(dropdownEl.length).toBe(0);
+ expect(document.activeElement.tagName).toBe('INPUT');
+ });
+
+ it('stops the ESC key from propagating if the dropdown is open, but not when closed', function() {
+ var documentKey = -1;
+ var getKey = function(evt) { documentKey = evt.which; };
+ $document.bind('keydown', getKey);
+
+ triggerKeyDown(inputEl, 'esc');
+ expect(documentKey).toBe(-1);
+
+ triggerKeyDown(inputEl, 'esc');
+ expect(documentKey).toBe(27);
+
+ $document.unbind('keydown', getKey);
+ });
+ });
+
+ describe('works with ngModelOptions', function () {
+ var $timeout;
+
+ beforeEach(inject(function(_$document_, _$sniffer_, _$timeout_) {
+ $document = _$document_;
+ $timeout = _$timeout_;
+ $rootScope.isopen = true;
+ $rootScope.date = new Date('September 30, 2010 15:30:00');
+ var wrapElement = $compile('<div><input ng-model="date" ' +
+ 'ng-model-options="{ debounce: 10000 }" ' +
+ 'uib-datepicker-popup is-open="isopen"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ }));
+
+ it('should change model and update calendar after debounce timeout', function() {
+ changeInputValueTo(inputEl, '1980-03-05');
+
+ expect($rootScope.date.getFullYear()).toEqual(2010);
+ expect($rootScope.date.getMonth()).toEqual(9 - 1);
+ expect($rootScope.date.getDate()).toEqual(30);
+
+ expect(getOptions(true)).toEqual([
+ ['29', '30', '31', '01', '02', '03', '04'],
+ ['05', '06', '07', '08', '09', '10', '11'],
+ ['12', '13', '14', '15', '16', '17', '18'],
+ ['19', '20', '21', '22', '23', '24', '25'],
+ ['26', '27', '28', '29', '30', '01', '02'],
+ ['03', '04', '05', '06', '07', '08', '09']
+ ]);
+
+ // No changes yet
+ $timeout.flush(2000);
+ expect($rootScope.date.getFullYear()).toEqual(2010);
+ expect($rootScope.date.getMonth()).toEqual(9 - 1);
+ expect($rootScope.date.getDate()).toEqual(30);
+
+ expect(getOptions(true)).toEqual([
+ ['29', '30', '31', '01', '02', '03', '04'],
+ ['05', '06', '07', '08', '09', '10', '11'],
+ ['12', '13', '14', '15', '16', '17', '18'],
+ ['19', '20', '21', '22', '23', '24', '25'],
+ ['26', '27', '28', '29', '30', '01', '02'],
+ ['03', '04', '05', '06', '07', '08', '09']
+ ]);
+
+ $timeout.flush(10000);
+ expect($rootScope.date.getFullYear()).toEqual(1980);
+ expect($rootScope.date.getMonth()).toEqual(2);
+ expect($rootScope.date.getDate()).toEqual(5);
+
+ expect(getOptions(true)).toEqual([
+ ['24', '25', '26', '27', '28', '29', '01'],
+ ['02', '03', '04', '05', '06', '07', '08'],
+ ['09', '10', '11', '12', '13', '14', '15'],
+ ['16', '17', '18', '19', '20', '21', '22'],
+ ['23', '24', '25', '26', '27', '28', '29'],
+ ['30', '31', '01', '02', '03', '04', '05']
+ ]);
+ expectSelectedElement( 10 );
+ });
+ });
+
+ describe('works with HTML5 date input types', function() {
+ var date2 = new Date('October 1, 2010 12:34:56.789');
+ beforeEach(inject(function(_$document_) {
+ $document = _$document_;
+ $rootScope.isopen = true;
+ $rootScope.date = new Date('September 30, 2010 15:30:00');
+ }));
+
+ it('works as date', function() {
+ setupInputWithType('date');
+ expect(dropdownEl.length).toBe(1);
+ expect(inputEl.val()).toBe('2010-09-30');
+
+ changeInputValueTo(inputEl, '1980-03-05');
+
+ expect($rootScope.date.getFullYear()).toEqual(1980);
+ expect($rootScope.date.getMonth()).toEqual(2);
+ expect($rootScope.date.getDate()).toEqual(5);
+
+ expect(getOptions(true)).toEqual([
+ ['24', '25', '26', '27', '28', '29', '01'],
+ ['02', '03', '04', '05', '06', '07', '08'],
+ ['09', '10', '11', '12', '13', '14', '15'],
+ ['16', '17', '18', '19', '20', '21', '22'],
+ ['23', '24', '25', '26', '27', '28', '29'],
+ ['30', '31', '01', '02', '03', '04', '05']
+ ]);
+ expect(selectedElementIndex()).toEqual(10);
+ });
+
+ it('works as datetime-local', function() {
+ setupInputWithType('datetime-local');
+ expect(inputEl.val()).toBe('2010-09-30T15:30:00.000');
+
+ changeInputValueTo(inputEl, '1980-03-05T12:34:56.000');
+
+ expect($rootScope.date.getFullYear()).toEqual(1980);
+ expect($rootScope.date.getMonth()).toEqual(2);
+ expect($rootScope.date.getDate()).toEqual(5);
+
+ expect(getOptions(true)).toEqual([
+ ['24', '25', '26', '27', '28', '29', '01'],
+ ['02', '03', '04', '05', '06', '07', '08'],
+ ['09', '10', '11', '12', '13', '14', '15'],
+ ['16', '17', '18', '19', '20', '21', '22'],
+ ['23', '24', '25', '26', '27', '28', '29'],
+ ['30', '31', '01', '02', '03', '04', '05']
+ ]);
+ expect(selectedElementIndex()).toEqual(10);
+ });
+
+ it('works as month', function() {
+ setupInputWithType('month');
+ expect(inputEl.val()).toBe('2010-09');
+
+ changeInputValueTo(inputEl, '1980-03');
+
+ expect($rootScope.date.getFullYear()).toEqual(1980);
+ expect($rootScope.date.getMonth()).toEqual(2);
+ expect($rootScope.date.getDate()).toEqual(30);
+
+ expect(getOptions()).toEqual([
+ ['January', 'February', 'March'],
+ ['April', 'May', 'June'],
+ ['July', 'August', 'September'],
+ ['October', 'November', 'December']
+ ]);
+ expect(selectedElementIndex()).toEqual(2);
+ });
+
+ function setupInputWithType(type) {
+ var wrapElement = $compile('<div><input type="' +
+ type + '" ng-model="date" uib-datepicker-popup is-open="isopen"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ }
+ });
+
+ });
+
+ describe('attribute `datepickerOptions`', function() {
+ describe('show-weeks', function() {
+ beforeEach(function() {
+ $rootScope.opts = {
+ 'show-weeks': false
+ };
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup datepicker-options="opts" is-open="true"></div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ });
+
+ it('hides week numbers based on variable', function() {
+ expect(getLabelsRow().find('th').length).toEqual(7);
+ var tr = element.find('tbody').find('tr');
+ for (var i = 0; i < 5; i++) {
+ expect(tr.eq(i).find('td').length).toEqual(7);
+ }
+ });
+ });
+
+ describe('init-date', function(){
+ beforeEach(function() {
+ $rootScope.date = null;
+ $rootScope.opts = {
+ 'initDate': new Date('November 9, 1980')
+ };
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup datepicker-options="opts" is-open="true"></div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ });
+
+ it('does not alter the model', function() {
+ expect($rootScope.date).toBe(null);
+ });
+
+ it('shows the correct title', function() {
+ expect(getTitle()).toBe('November 1980');
+ });
+ });
+ });
+
+ describe('attribute `init-date`', function() {
+ beforeEach(function() {
+ $rootScope.date = null;
+ $rootScope.initDate = new Date('November 9, 1980');
+ });
+
+ describe('when initially set', function() {
+ beforeEach(function() {
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup init-date="initDate" is-open="true"></div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ });
+
+ it('does not alter the model', function() {
+ expect($rootScope.date).toBe(null);
+ });
+
+ it('shows the correct title', function() {
+ expect(getTitle()).toBe('November 1980');
+ });
+ });
+
+ describe('when modified before date selected.', function() {
+ beforeEach(function() {
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup init-date="initDate" is-open="true"></div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+
+ $rootScope.initDate = new Date('December 20, 1981');
+ $rootScope.$digest();
+ });
+
+ it('does not alter the model', function() {
+ expect($rootScope.date).toBe(null);
+ });
+
+ it('shows the correct title', function() {
+ expect(getTitle()).toBe('December 1981');
+ });
+ });
+
+ describe('when modified after date selected.', function() {
+ beforeEach(function() {
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup init-date="initDate" is-open="true"></div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ $rootScope.date = new Date('April 1, 1982');
+ $rootScope.initDate = new Date('December 20, 1981');
+ $rootScope.$digest();
+ });
+
+ it('does not alter the model', function() {
+ expect($rootScope.date).toEqual(new Date('April 1, 1982'));
+ });
+
+ it('shows the correct title', function() {
+ expect(getTitle()).toBe('April 1982');
+ });
+ });
+ });
+
+ describe('toggles programatically by `open` attribute', function() {
+ var wrapElement;
+
+ beforeEach(inject(function() {
+ $rootScope.open = true;
+ wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup is-open="open"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ }));
+
+ it('to display initially', function() {
+ expect(dropdownEl.length).toBe(1);
+ });
+
+ it('to close / open from scope variable', function() {
+ expect(dropdownEl.length).toBe(1);
+ $rootScope.open = false;
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ expect(dropdownEl.length).toBe(0);
+
+ $rootScope.open = true;
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ expect(dropdownEl.length).toBe(1);
+ });
+ });
+
+ describe('custom format', function() {
+ beforeEach(inject(function() {
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup="dd-MMMM-yyyy" is-open="true"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ }));
+
+ it('to display the correct value in input', function() {
+ expect(inputEl.val()).toBe('30-September-2010');
+ });
+
+ it('updates the input when a day is clicked', function() {
+ clickOption(17);
+ expect(inputEl.val()).toBe('15-September-2010');
+ expect($rootScope.date).toEqual(new Date('September 15, 2010 15:30:00'));
+ });
+
+ it('updates the input correctly when model changes', function() {
+ $rootScope.date = new Date('January 10, 1983 10:00:00');
+ $rootScope.$digest();
+ expect(inputEl.val()).toBe('10-January-1983');
+ });
+ });
+
+ describe('dynamic custom format', function() {
+ beforeEach(inject(function() {
+ $rootScope.format = 'dd-MMMM-yyyy';
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup="{{format}}" is-open="true"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ }));
+
+ it('to display the correct value in input', function() {
+ expect(inputEl.val()).toBe('30-September-2010');
+ });
+
+ it('updates the input when a day is clicked', function() {
+ clickOption(17);
+ expect(inputEl.val()).toBe('15-September-2010');
+ expect($rootScope.date).toEqual(new Date('September 15, 2010 15:30:00'));
+ });
+
+ it('updates the input correctly when model changes', function() {
+ $rootScope.date = new Date('August 11, 2013 09:09:00');
+ $rootScope.$digest();
+ expect(inputEl.val()).toBe('11-August-2013');
+ });
+
+ it('updates the input correctly when format changes', function() {
+ $rootScope.format = 'dd/MM/yyyy';
+ $rootScope.$digest();
+ expect(inputEl.val()).toBe('30/09/2010');
+ });
+ });
+
+ describe('european format', function() {
+ it('dd.MM.yyyy', function() {
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup="dd.MM.yyyy"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+
+ changeInputValueTo(inputEl, '11.08.2013');
+ expect($rootScope.date.getFullYear()).toEqual(2013);
+ expect($rootScope.date.getMonth()).toEqual(7);
+ expect($rootScope.date.getDate()).toEqual(11);
+ });
+ });
+
+ describe('`close-on-date-selection` attribute', function() {
+ var wrapElement;
+ beforeEach(inject(function() {
+ $rootScope.close = false;
+ wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup close-on-date-selection="close" is-open="true"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ }));
+
+ it('does not close the dropdown when a day is clicked', function() {
+ clickOption(17);
+ assignElements(wrapElement);
+ expect(dropdownEl.length).toBe(1);
+ });
+ });
+
+ describe('button bar', function() {
+ var buttons, buttonBarElement;
+
+ function assignButtonBar() {
+ buttonBarElement = dropdownEl.find('li').eq(-1);
+ buttons = buttonBarElement.find('button');
+ }
+
+ describe('', function() {
+ var wrapElement;
+
+ beforeEach(inject(function() {
+ $rootScope.isopen = true;
+ wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup is-open="isopen"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ assignButtonBar();
+ }));
+
+ it('should exist', function() {
+ expect(dropdownEl.length).toBe(1);
+ expect(dropdownEl.find('li').length).toBe(2);
+ });
+
+ it('should have three buttons', function() {
+ expect(buttons.length).toBe(3);
+
+ expect(buttons.eq(0).text()).toBe('Today');
+ expect(buttons.eq(1).text()).toBe('Clear');
+ expect(buttons.eq(2).text()).toBe('Done');
+ });
+
+ it('should have a button to set today date without altering time part', function() {
+ var today = new Date();
+ buttons.eq(0).click();
+ expect($rootScope.date.getFullYear()).toBe(today.getFullYear());
+ expect($rootScope.date.getMonth()).toBe(today.getMonth());
+ expect($rootScope.date.getDate()).toBe(today.getDate());
+
+ expect($rootScope.date.getHours()).toBe(15);
+ expect($rootScope.date.getMinutes()).toBe(30);
+ expect($rootScope.date.getSeconds()).toBe(0);
+ });
+
+ it('should have a button to set today date if blank', function() {
+ $rootScope.date = null;
+ $rootScope.$digest();
+
+ var today = new Date();
+ buttons.eq(0).click();
+ expect($rootScope.date.getFullYear()).toBe(today.getFullYear());
+ expect($rootScope.date.getMonth()).toBe(today.getMonth());
+ expect($rootScope.date.getDate()).toBe(today.getDate());
+
+ expect($rootScope.date.getHours()).toBe(0);
+ expect($rootScope.date.getMinutes()).toBe(0);
+ expect($rootScope.date.getSeconds()).toBe(0);
+ });
+
+ it('should have a button to clear value', function() {
+ buttons.eq(1).click();
+ expect($rootScope.date).toBe(null);
+ });
+
+ it('should have a button to close calendar', function() {
+ buttons.eq(2).click();
+ assignElements(wrapElement);
+ expect(dropdownEl.length).toBe(0);
+ });
+ });
+
+ describe('customization', function() {
+ it('should change text from attributes', function() {
+ $rootScope.clearText = 'Null it!';
+ $rootScope.close = 'Close';
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup current-text="Now" clear-text="{{clearText}}" close-text="{{close}}ME" is-open="true"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ assignButtonBar();
+
+ expect(buttons.eq(0).text()).toBe('Now');
+ expect(buttons.eq(1).text()).toBe('Null it!');
+ expect(buttons.eq(2).text()).toBe('CloseME');
+ });
+
+ it('should disable today button if before min date', function() {
+ $rootScope.minDate = new Date().setDate(new Date().getDate() + 1);
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup min-date="minDate" is-open="true"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ assignButtonBar();
+
+ expect(buttons.eq(0).prop('disabled')).toBe(true);
+ });
+
+ it('should disable today button if after max date', function() {
+ $rootScope.maxDate = new Date().setDate(new Date().getDate() - 2);
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup max-date="maxDate" is-open="true"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ assignButtonBar();
+
+ expect(buttons.eq(0).prop('disabled')).toBe(true);
+ });
+
+ it('should remove bar', function() {
+ $rootScope.showBar = false;
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup show-button-bar="showBar" is-open="true"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ expect(dropdownEl.find('li').length).toBe(1);
+ });
+
+ it('should hide weeks column on popup', function() {
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup show-weeks="false" is-open="true"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+
+ expect(getLabelsRow().find('th').length).toEqual(7);
+ var tr = element.find('tbody').find('tr');
+ for (var i = 0; i < 5; i++) {
+ expect(tr.eq(i).find('td').length).toEqual(7);
+ }
+ });
+
+ it('should show weeks column on popup', function() {
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup show-weeks="true" is-open="true"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+
+ expect(getLabelsRow().find('th').eq(0)).not.toBeHidden();
+ var tr = element.find('tbody').find('tr');
+ for (var i = 0; i < 5; i++) {
+ expect(tr.eq(i).find('td').eq(0)).not.toBeHidden();
+ }
+ });
+ });
+
+ describe('`ng-change`', function() {
+ beforeEach(inject(function() {
+ $rootScope.changeHandler = jasmine.createSpy('changeHandler');
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup ng-change="changeHandler()" is-open="true"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ assignButtonBar();
+ }));
+
+ it('should be called when `today` is clicked', function() {
+ buttons.eq(0).click();
+ expect($rootScope.changeHandler).toHaveBeenCalled();
+ });
+
+ it('should be called when `clear` is clicked', function() {
+ buttons.eq(1).click();
+ expect($rootScope.changeHandler).toHaveBeenCalled();
+ });
+
+ it('should not be called when `close` is clicked', function() {
+ buttons.eq(2).click();
+ expect($rootScope.changeHandler).not.toHaveBeenCalled();
+ });
+ });
+ });
+
+ describe('use with `ng-required` directive', function() {
+ describe('`ng-required is true`', function() {
+ beforeEach(inject(function() {
+ $rootScope.date = '';
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup ng-required="true"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ }));
+
+ it('should be invalid initially and when no date', function() {
+ expect(inputEl.hasClass('ng-invalid')).toBeTruthy();
+ });
+
+ it('should be valid if model has been specified', function() {
+ $rootScope.date = new Date();
+ $rootScope.$digest();
+ expect(inputEl.hasClass('ng-valid')).toBeTruthy();
+ });
+
+ it('should be valid if model value is a valid timestamp', function() {
+ $rootScope.date = Date.now();
+ $rootScope.$digest();
+ expect(inputEl.hasClass('ng-valid')).toBeTruthy();
+ });
+ });
+ describe('`ng-required is false`', function() {
+ beforeEach(inject(function() {
+ $rootScope.date = '';
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup ng-required="false"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ }));
+
+ it('should be valid initially and when no date', function() {
+ expect(inputEl.hasClass('ng-valid')).toBeTruthy();
+ });
+ });
+ });
+
+ describe('use with `ng-change` directive', function() {
+ beforeEach(inject(function() {
+ $rootScope.changeHandler = jasmine.createSpy('changeHandler');
+ $rootScope.date = new Date('09/16/2010');
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup ng-required="true" ng-change="changeHandler()" is-open="true"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ }));
+
+ it('should not be called initially', function() {
+ expect($rootScope.changeHandler).not.toHaveBeenCalled();
+ });
+
+ it('should be called when a day is clicked', function() {
+ clickOption(17);
+ expect($rootScope.changeHandler).toHaveBeenCalled();
+ });
+
+ it('should not be called when model changes programatically', function() {
+ $rootScope.date = new Date();
+ $rootScope.$digest();
+ expect($rootScope.changeHandler).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('with datepicker-popup-template-url', function() {
+ beforeEach(function() {
+ $rootScope.date = new Date();
+ });
+
+ afterEach(function () {
+ $document.find('body').find('.dropdown-menu').remove();
+ });
+
+ it('should allow custom templates for the popup', function() {
+ $templateCache.put('foo/bar.html', '<div>baz</div>');
+
+ var elm = angular.element('<div><input ng-model="date" uib-datepicker-popup datepicker-popup-template-url="foo/bar.html" is-open="true"></div>');
+
+ $compile(elm)($rootScope);
+ $rootScope.$digest();
+
+ expect(elm.children().eq(1).html()).toBe('baz');
+ });
+ });
+
+ describe('with datepicker-template-url', function() {
+ beforeEach(function() {
+ $rootScope.date = new Date();
+ });
+
+ afterEach(function() {
+ $document.find('body').find('.dropdown-menu').remove();
+ });
+
+ it('should allow custom templates for the datepicker', function() {
+ $templateCache.put('foo/bar.html', '<div>baz</div>');
+
+ var elm = angular.element('<div><input ng-model="date" uib-datepicker-popup datepicker-template-url="foo/bar.html" is-open="true"></div>');
+
+ $compile(elm)($rootScope);
+ $rootScope.$digest();
+
+ var datepicker = elm.find('[uib-datepicker]');
+
+ expect(datepicker.html()).toBe('baz');
+ });
+ });
+
+ describe('with an append-to-body attribute', function() {
+ beforeEach(function() {
+ $rootScope.date = new Date();
+ });
+
+ afterEach(function() {
+ $document.find('body').children().remove();
+ });
+
+ it('should append to the body', function() {
+ var $body = $document.find('body'),
+ bodyLength = $body.children().length,
+ elm = angular.element(
+ '<div><input uib-datepicker-popup ng-model="date" datepicker-append-to-body="true" is-open="true" /></div>'
+ );
+ $compile(elm)($rootScope);
+ $rootScope.$digest();
+
+ expect($body.children().length).toEqual(bodyLength + 1);
+ expect(elm.children().length).toEqual(1);
+ });
+ it('should be removed on scope destroy', function() {
+ var $body = $document.find('body'),
+ bodyLength = $body.children().length,
+ isolatedScope = $rootScope.$new(),
+ elm = angular.element(
+ '<input uib-datepicker-popup ng-model="date" datepicker-append-to-body="true" is-open="true" />'
+ );
+ $compile(elm)(isolatedScope);
+ isolatedScope.$digest();
+ expect($body.children().length).toEqual(bodyLength + 1);
+ isolatedScope.$destroy();
+ expect($body.children().length).toEqual(bodyLength);
+ });
+ });
+
+ describe('with setting datepickerConfig.showWeeks to false', function() {
+ var originalConfig = {};
+ beforeEach(inject(function(uibDatepickerConfig) {
+ angular.extend(originalConfig, uibDatepickerConfig);
+ uibDatepickerConfig.showWeeks = false;
+
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup is-open="true"><div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ }));
+ afterEach(inject(function(uibDatepickerConfig) {
+ // return it to the original state
+ angular.extend(uibDatepickerConfig, originalConfig);
+ }));
+
+ it('changes initial visibility for weeks', function() {
+ expect(getLabelsRow().find('th').length).toEqual(7);
+ var tr = element.find('tbody').find('tr');
+ for (var i = 0; i < 5; i++) {
+ expect(tr.eq(i).find('td').length).toEqual(7);
+ }
+ });
+ });
+
+ describe('`datepicker-mode`', function() {
+ beforeEach(inject(function() {
+ $rootScope.date = new Date('August 11, 2013');
+ $rootScope.mode = 'month';
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup datepicker-mode="mode" is-open="true"></div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ }));
+
+ it('shows the correct title', function() {
+ expect(getTitle()).toBe('2013');
+ });
+
+ it('updates binding', function() {
+ clickTitleButton();
+ expect($rootScope.mode).toBe('year');
+ });
+ });
+
+ describe('attribute `initDate`', function() {
+ var weekHeader, weekElement;
+ beforeEach(function() {
+ $rootScope.date = null;
+ $rootScope.initDate = new Date('November 9, 1980');
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup init-date="initDate" is-open="true"></div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ });
+
+ it('should not alter the model', function() {
+ expect($rootScope.date).toBe(null);
+ });
+
+ it('shows the correct title', function() {
+ expect(getTitle()).toBe('November 1980');
+ });
+ });
+
+ describe('attribute `onOpenFocus`', function() {
+ beforeEach(function() {
+ $rootScope.date = null;
+ $rootScope.isopen = false;
+ var wrapElement = $compile('<div><input ng-model="date" uib-datepicker-popup on-open-focus="false" is-open="isopen"></div>')($rootScope);
+ $rootScope.$digest();
+ assignElements(wrapElement);
+ });
+
+ it('should remain focused on the input', function() {
+ var focused = true;
+ expect(dropdownEl.length).toBe(0);
+
+ inputEl[0].focus();
+ inputEl.on('blur', function() {
+ focused = false;
+ });
+ $rootScope.isopen = true;
+ $rootScope.$digest();
+
+ expect(inputEl.parent().find('.dropdown-menu').length).toBe(1);
+ expect(focused).toBe(true);
+ });
+ });
+ });
+
+ describe('with empty initial state', function() {
+ beforeEach(inject(function() {
+ $rootScope.date = null;
+ element = $compile('<uib-datepicker ng-model="date"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('is has a `<table>` element', function() {
+ expect(element.find('table').length).toBe(1);
+ });
+
+ it('is shows rows with days', function() {
+ expect(element.find('tbody').find('tr').length).toBeGreaterThan(3);
+ });
+
+ it('sets default 00:00:00 time for selected date', function() {
+ $rootScope.date = new Date('August 1, 2013');
+ $rootScope.$digest();
+ $rootScope.date = null;
+ $rootScope.$digest();
+
+ clickOption(14);
+ expect($rootScope.date).toEqual(new Date('August 11, 2013 00:00:00'));
+ });
+ });
+
+ describe('`init-date`', function() {
+ beforeEach(inject(function() {
+ $rootScope.date = null;
+ $rootScope.initDate = new Date('November 9, 1980');
+ element = $compile('<uib-datepicker ng-model="date" init-date="initDate"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('does not alter the model', function() {
+ expect($rootScope.date).toBe(null);
+ });
+
+ it('shows the correct title', function() {
+ expect(getTitle()).toBe('November 1980');
+ });
+ });
+
+ describe('`datepicker-mode`', function() {
+ beforeEach(inject(function() {
+ $rootScope.date = new Date('August 11, 2013');
+ $rootScope.mode = 'month';
+ element = $compile('<uib-datepicker ng-model="date" datepicker-mode="mode"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('shows the correct title', function() {
+ expect(getTitle()).toBe('2013');
+ });
+
+ it('updates binding', function() {
+ clickTitleButton();
+ expect($rootScope.mode).toBe('year');
+ });
+ });
+
+ describe('`min-mode`', function() {
+ beforeEach(inject(function() {
+ $rootScope.date = new Date('August 11, 2013');
+ $rootScope.mode = 'month';
+ $rootScope.minMode = 'month';
+ element = $compile('<uib-datepicker ng-model="date" min-mode="minMode" datepicker-mode="mode"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('does not move below it', function() {
+ expect(getTitle()).toBe('2013');
+ clickOption( 5 );
+ expect(getTitle()).toBe('2013');
+ clickTitleButton();
+ expect(getTitle()).toBe('2001 - 2020');
+ $rootScope.minMode = 'year';
+ $rootScope.$digest();
+ clickOption( 5 );
+ expect(getTitle()).toBe('2001 - 2020');
+ });
+
+ it('updates current mode if necessary', function() {
+ expect(getTitle()).toBe('2013');
+ $rootScope.minMode = 'year';
+ $rootScope.$digest();
+ expect(getTitle()).toBe('2001 - 2020');
+ });
+ });
+
+ describe('`max-mode`', function() {
+ beforeEach(inject(function() {
+ $rootScope.date = new Date('August 11, 2013');
+ $rootScope.maxMode = 'month';
+ element = $compile('<uib-datepicker ng-model="date" max-mode="maxMode"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('does not move above it', function() {
+ expect(getTitle()).toBe('August 2013');
+ clickTitleButton();
+ expect(getTitle()).toBe('2013');
+ clickTitleButton();
+ expect(getTitle()).toBe('2013');
+ clickOption( 10 );
+ expect(getTitle()).toBe('November 2013');
+ $rootScope.maxMode = 'day';
+ $rootScope.$digest();
+ clickTitleButton();
+ expect(getTitle()).toBe('November 2013');
+ });
+
+ it('disables the title button at it', function() {
+ expect(getTitleButton().prop('disabled')).toBe(false);
+ clickTitleButton();
+ expect(getTitleButton().prop('disabled')).toBe(true);
+ clickTitleButton();
+ expect(getTitleButton().prop('disabled')).toBe(true);
+ clickOption( 10 );
+ expect(getTitleButton().prop('disabled')).toBe(false);
+ $rootScope.maxMode = 'day';
+ $rootScope.$digest();
+ expect(getTitleButton().prop('disabled')).toBe(true);
+ });
+
+ it('updates current mode if necessary', function() {
+ expect(getTitle()).toBe('August 2013');
+ clickTitleButton();
+ expect(getTitle()).toBe('2013');
+ $rootScope.maxMode = 'day';
+ $rootScope.$digest();
+ expect(getTitle()).toBe('August 2013');
+ });
+ });
+
+ describe('with an ngModelController having formatters and parsers', function() {
+ beforeEach(inject(function() {
+ // Custom date object.
+ $rootScope.date = { type: 'date', date: 'April 1, 2015 00:00:00' };
+
+ // Use dateModel directive to add formatters and parsers to the
+ // ngModelController that translate the custom date object.
+ element = $compile('<uib-datepicker ng-model="date" date-model></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('updates the view', function() {
+ $rootScope.date = { type: 'date', date: 'April 15, 2015 00:00:00' };
+ $rootScope.$digest();
+
+ expectSelectedElement(17);
+ });
+
+ it('updates the model', function() {
+ clickOption(17);
+
+ expect($rootScope.date.type).toEqual('date');
+ expect(new Date($rootScope.date.date)).toEqual(new Date('April 15, 2015 00:00:00'));
+ });
+ });
+
+ describe('thursdays determine week count', function() {
+ beforeEach(inject(function() {
+ $rootScope.date = new Date('June 07, 2014');
+ }));
+
+ it('with the default starting day (sunday)', function() {
+ element = $compile('<uib-datepicker ng-model="date"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getWeeks()).toEqual(['23', '24', '25', '26', '27', '28']);
+ });
+
+ describe('when starting date', function() {
+ it('is monday', function() {
+ element = $compile('<uib-datepicker ng-model="date" starting-day="1"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getWeeks()).toEqual(['22', '23', '24', '25', '26', '27']);
+ });
+
+ it('is thursday', function() {
+ element = $compile('<uib-datepicker ng-model="date" starting-day="4"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getWeeks()).toEqual(['22', '23', '24', '25', '26', '27']);
+ });
+
+ it('is saturday', function() {
+ element = $compile('<uib-datepicker ng-model="date" starting-day="6"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getWeeks()).toEqual(['23', '24', '25', '26', '27', '28']);
+ });
+ });
+
+ describe('first week in january', function() {
+ it('in current year', function() {
+ $rootScope.date = new Date('January 07, 2014');
+ element = $compile('<uib-datepicker ng-model="date"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getWeeks()).toEqual(['1', '2', '3', '4', '5', '6']);
+ });
+
+ it('in last year', function() {
+ $rootScope.date = new Date('January 07, 2010');
+ element = $compile('<uib-datepicker ng-model="date"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getWeeks()).toEqual(['53', '1', '2', '3', '4', '5']);
+ });
+ });
+
+ describe('last week(s) in december', function() {
+ beforeEach(inject(function() {
+ $rootScope.date = new Date('December 07, 2014');
+ }));
+
+ it('in next year', function() {
+ element = $compile('<uib-datepicker ng-model="date"></uib-datepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getWeeks()).toEqual(['49', '50', '51', '52', '1', '2']);
+ });
+ });
+ });
+ });
+});
+
+/* deprecation tests below */
+
+describe('datepicker deprecation', function() {
+ beforeEach(module('ui.bootstrap.datepicker'));
+ beforeEach(module('template/datepicker/datepicker.html'));
+ beforeEach(module('template/datepicker/day.html'));
+ beforeEach(module('template/datepicker/month.html'));
+ beforeEach(module('template/datepicker/year.html'));
+ beforeEach(module('template/datepicker/popup.html'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$datepickerSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = $compile('<datepicker ng-model="date"></datepicker>')($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($log) {
+ spyOn($log, 'warn');
+
+ inject(function($compile, $templateCache, $rootScope) {
+ var datepickerTemplate =
+ '<div ng-switch="datepickerMode" role="application" ng-keydown="keydown($event)">' +
+ '<daypicker ng-switch-when="day" tabindex="0"></daypicker>' +
+ '<monthpicker ng-switch-when="month" tabindex="0"></monthpicker>' +
+ '<yearpicker ng-switch-when="year" tabindex="0"></yearpicker> ' +
+ '</div>';
+ $templateCache.put('template/datepicker/datepicker.html', datepickerTemplate);
+
+ var element = $compile('<datepicker ng-model="date"></datepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(3);
+ expect($log.warn.calls.argsFor(0)).toEqual(['DatepickerController is now deprecated. Use UibDatepickerController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['datepicker is now deprecated. Use uib-datepicker instead.']);
+ expect($log.warn.calls.argsFor(2)).toEqual(['daypicker is now deprecated. Use uib-daypicker instead.']);
+
+ $log.warn.calls.reset();
+
+ element = $compile('<datepicker datepicker-mode="\'month\'" ng-model="date"></datepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(3);
+ expect($log.warn.calls.argsFor(0)).toEqual(['DatepickerController is now deprecated. Use UibDatepickerController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['datepicker is now deprecated. Use uib-datepicker instead.']);
+ expect($log.warn.calls.argsFor(2)).toEqual(['monthpicker is now deprecated. Use uib-monthpicker instead.']);
+
+ $log.warn.calls.reset();
+
+ element = $compile('<datepicker datepicker-mode="\'year\'" ng-model="date"></datepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(3);
+ expect($log.warn.calls.argsFor(0)).toEqual(['DatepickerController is now deprecated. Use UibDatepickerController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['datepicker is now deprecated. Use uib-datepicker instead.']);
+ expect($log.warn.calls.argsFor(2)).toEqual(['yearpicker is now deprecated. Use uib-yearpicker instead.']);
+
+ $log.warn.calls.reset();
+
+ element = $compile('<input type="date" datepicker-popup ng-model="dt" />')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(1);
+ expect($log.warn.calls.argsFor(0)).toEqual(['datepicker-popup is now deprecated. Use uib-datepicker-popup instead.']);
+ });
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/docs/demo.html
new file mode 100644
index 0000000..7d6f146
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/docs/demo.html
@@ -0,0 +1,98 @@
+
+<div ng-controller="DropdownCtrl">
+ <!-- Simple dropdown -->
+ <span uib-dropdown on-toggle="toggled(open)">
+ <a href id="simple-dropdown" uib-dropdown-toggle>
+ Click me for a dropdown, yo!
+ </a>
+ <ul class="uib-dropdown-menu" aria-labelledby="simple-dropdown">
+ <li ng-repeat="choice in items">
+ <a href>{{choice}}</a>
+ </li>
+ </ul>
+ </span>
+
+ <!-- Single button -->
+ <div class="btn-group" uib-dropdown is-open="status.isopen">
+ <button id="single-button" type="button" class="btn btn-primary" uib-dropdown-toggle ng-disabled="disabled">
+ Button dropdown <span class="caret"></span>
+ </button>
+ <ul class="uib-dropdown-menu" role="menu" aria-labelledby="single-button">
+ <li role="menuitem"><a href="#">Action</a></li>
+ <li role="menuitem"><a href="#">Another action</a></li>
+ <li role="menuitem"><a href="#">Something else here</a></li>
+ <li class="divider"></li>
+ <li role="menuitem"><a href="#">Separated link</a></li>
+ </ul>
+ </div>
+
+ <!-- Split button -->
+ <div class="btn-group" uib-dropdown>
+ <button id="split-button" type="button" class="btn btn-danger">Action</button>
+ <button type="button" class="btn btn-danger" uib-dropdown-toggle>
+ <span class="caret"></span>
+ <span class="sr-only">Split button!</span>
+ </button>
+ <ul class="uib-dropdown-menu" role="menu" aria-labelledby="split-button">
+ <li role="menuitem"><a href="#">Action</a></li>
+ <li role="menuitem"><a href="#">Another action</a></li>
+ <li role="menuitem"><a href="#">Something else here</a></li>
+ <li class="divider"></li>
+ <li role="menuitem"><a href="#">Separated link</a></li>
+ </ul>
+ </div>
+
+ <!-- Single button using append-to-body -->
+ <div class="btn-group" uib-dropdown dropdown-append-to-body>
+ <button id="btn-append-to-body" type="button" class="btn btn-primary" uib-dropdown-toggle>
+ Dropdown on Body <span class="caret"></span>
+ </button>
+ <ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
+ <li role="menuitem"><a href="#">Action</a></li>
+ <li role="menuitem"><a href="#">Another action</a></li>
+ <li role="menuitem"><a href="#">Something else here</a></li>
+ <li class="divider"></li>
+ <li role="menuitem"><a href="#">Separated link</a></li>
+ </ul>
+ </div>
+
+ <!-- Single button using template-url -->
+ <div class="btn-group" uib-dropdown>
+ <button id="button-template-url" type="button" class="btn btn-primary" uib-dropdown-toggle ng-disabled="disabled">
+ Dropdown using template <span class="caret"></span>
+ </button>
+ <ul class="uib-dropdown-menu" template-url="dropdown.html" aria-labelledby="button-template-url">
+ </ul>
+ </div>
+
+ <hr />
+ <p>
+ <button type="button" class="btn btn-default btn-sm" ng-click="toggleDropdown($event)">Toggle button dropdown</button>
+ <button type="button" class="btn btn-warning btn-sm" ng-click="disabled = !disabled">Enable/Disable</button>
+ </p>
+
+ <hr>
+ <!-- Single button with keyboard nav -->
+ <div class="btn-group" uib-dropdown uib-keyboard-nav>
+ <button id="simple-btn-keyboard-nav" type="button" class="btn btn-primary" uib-dropdown-toggle>
+ Dropdown with keyboard navigation <span class="caret"></span>
+ </button>
+ <ul class="uib-dropdown-menu" role="menu" aria-labelledby="simple-btn-keyboard-nav">
+ <li role="menuitem"><a href="#">Action</a></li>
+ <li role="menuitem"><a href="#">Another action</a></li>
+ <li role="menuitem"><a href="#">Something else here</a></li>
+ <li class="divider"></li>
+ <li role="menuitem"><a href="#">Separated link</a></li>
+ </ul>
+ </div>
+
+ <script type="text/ng-template" id="dropdown.html">
+ <ul class="uib-dropdown-menu" role="menu" aria-labelledby="button-template-url">
+ <li role="menuitem"><a href="#">Action in Template</a></li>
+ <li role="menuitem"><a href="#">Another action in Template</a></li>
+ <li role="menuitem"><a href="#">Something else here</a></li>
+ <li class="divider"></li>
+ <li role="menuitem"><a href="#">Separated link in Template</a></li>
+ </ul>
+ </script>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/docs/demo.js
new file mode 100644
index 0000000..321d493
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/docs/demo.js
@@ -0,0 +1,21 @@
+angular.module('ui.bootstrap.demo').controller('DropdownCtrl', function ($scope, $log) {
+ $scope.items = [
+ 'The first choice!',
+ 'And another choice for you.',
+ 'but wait! A third!'
+ ];
+
+ $scope.status = {
+ isopen: false
+ };
+
+ $scope.toggled = function(open) {
+ $log.log('Dropdown is now: ', open);
+ };
+
+ $scope.toggleDropdown = function($event) {
+ $event.preventDefault();
+ $event.stopPropagation();
+ $scope.status.isopen = !$scope.status.isopen;
+ };
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/docs/readme.md
new file mode 100644
index 0000000..b8571a1
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/docs/readme.md
@@ -0,0 +1,19 @@
+
+Dropdown is a simple directive which will toggle a dropdown menu on click or programmatically.
+You can either use `is-open` to toggle or add inside a `<a uib-dropdown-toggle>` element to toggle it when is clicked.
+There is also the `on-toggle(open)` optional expression fired when dropdown changes state.
+
+Add `dropdown-append-to-body` to the `uib-dropdown` element to append to the inner `dropdown-menu` to the body.
+This is useful when the dropdown button is inside a div with `overflow: hidden`, and the menu would otherwise be hidden.
+
+Add `uib-keyboard-nav` to the `uib-dropdown` element to enable navigation of dropdown list elements with the arrow keys.
+
+By default the dropdown will automatically close if any of its elements is clicked, you can change this behavior by setting the `auto-close` option as follows:
+
+ * `always` - (Default) automatically closes the dropdown when any of its elements is clicked.
+ * `outsideClick` - closes the dropdown automatically only when the user clicks any element outside the dropdown.
+ * `disabled` - disables the auto close. You can then control the open/close status of the dropdown manually, by using `is-open`. Please notice that the dropdown will still close if the toggle is clicked, the `esc` key is pressed or another dropdown is open. The dropdown will no longer close on `$locationChangeSuccess` events.
+
+Optionally, you may specify a template for the dropdown menu using the `template-url` attribute. This is especially useful when you have multiple similar dropdowns in a repeater and you want to keep your HTML output lean and your number of scopes to a minimum. The template has full access to the scope in which the dropdown lies.
+
+Example: `<ul class="uib-dropdown-menu" template-url="custom-dropdown.html"></ul>`.
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/dropdown.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/dropdown.js
new file mode 100644
index 0000000..1e666f2
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/dropdown.js
@@ -0,0 +1,658 @@
+angular.module('ui.bootstrap.dropdown', ['ui.bootstrap.position'])
+
+.constant('uibDropdownConfig', {
+ openClass: 'open'
+})
+
+.service('uibDropdownService', ['$document', '$rootScope', function($document, $rootScope) {
+ var openScope = null;
+
+ this.open = function(dropdownScope) {
+ if (!openScope) {
+ $document.bind('click', closeDropdown);
+ $document.bind('keydown', keybindFilter);
+ }
+
+ if (openScope && openScope !== dropdownScope) {
+ openScope.isOpen = false;
+ }
+
+ openScope = dropdownScope;
+ };
+
+ this.close = function(dropdownScope) {
+ if (openScope === dropdownScope) {
+ openScope = null;
+ $document.unbind('click', closeDropdown);
+ $document.unbind('keydown', keybindFilter);
+ }
+ };
+
+ var closeDropdown = function(evt) {
+ // This method may still be called during the same mouse event that
+ // unbound this event handler. So check openScope before proceeding.
+ if (!openScope) { return; }
+
+ if (evt && openScope.getAutoClose() === 'disabled') { return ; }
+
+ var toggleElement = openScope.getToggleElement();
+ if (evt && toggleElement && toggleElement[0].contains(evt.target)) {
+ return;
+ }
+
+ var dropdownElement = openScope.getDropdownElement();
+ if (evt && openScope.getAutoClose() === 'outsideClick' &&
+ dropdownElement && dropdownElement[0].contains(evt.target)) {
+ return;
+ }
+
+ openScope.isOpen = false;
+
+ if (!$rootScope.$$phase) {
+ openScope.$apply();
+ }
+ };
+
+ var keybindFilter = function(evt) {
+ if (evt.which === 27) {
+ openScope.focusToggleElement();
+ closeDropdown();
+ } else if (openScope.isKeynavEnabled() && /(38|40)/.test(evt.which) && openScope.isOpen) {
+ evt.preventDefault();
+ evt.stopPropagation();
+ openScope.focusDropdownEntry(evt.which);
+ }
+ };
+}])
+
+.controller('UibDropdownController', ['$scope', '$element', '$attrs', '$parse', 'uibDropdownConfig', 'uibDropdownService', '$animate', '$uibPosition', '$document', '$compile', '$templateRequest', function($scope, $element, $attrs, $parse, dropdownConfig, uibDropdownService, $animate, $position, $document, $compile, $templateRequest) {
+ var self = this,
+ scope = $scope.$new(), // create a child scope so we are not polluting original one
+ templateScope,
+ openClass = dropdownConfig.openClass,
+ getIsOpen,
+ setIsOpen = angular.noop,
+ toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop,
+ appendToBody = false,
+ keynavEnabled =false,
+ selectedOption = null;
+
+
+ $element.addClass('dropdown');
+
+ this.init = function() {
+ if ($attrs.isOpen) {
+ getIsOpen = $parse($attrs.isOpen);
+ setIsOpen = getIsOpen.assign;
+
+ $scope.$watch(getIsOpen, function(value) {
+ scope.isOpen = !!value;
+ });
+ }
+
+ appendToBody = angular.isDefined($attrs.dropdownAppendToBody);
+ keynavEnabled = angular.isDefined($attrs.uibKeyboardNav);
+
+ if (appendToBody && self.dropdownMenu) {
+ $document.find('body').append(self.dropdownMenu);
+ $element.on('$destroy', function handleDestroyEvent() {
+ self.dropdownMenu.remove();
+ });
+ }
+ };
+
+ this.toggle = function(open) {
+ return scope.isOpen = arguments.length ? !!open : !scope.isOpen;
+ };
+
+ // Allow other directives to watch status
+ this.isOpen = function() {
+ return scope.isOpen;
+ };
+
+ scope.getToggleElement = function() {
+ return self.toggleElement;
+ };
+
+ scope.getAutoClose = function() {
+ return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled'
+ };
+
+ scope.getElement = function() {
+ return $element;
+ };
+
+ scope.isKeynavEnabled = function() {
+ return keynavEnabled;
+ };
+
+ scope.focusDropdownEntry = function(keyCode) {
+ var elems = self.dropdownMenu ? //If append to body is used.
+ (angular.element(self.dropdownMenu).find('a')) :
+ (angular.element($element).find('ul').eq(0).find('a'));
+
+ switch (keyCode) {
+ case (40): {
+ if (!angular.isNumber(self.selectedOption)) {
+ self.selectedOption = 0;
+ } else {
+ self.selectedOption = (self.selectedOption === elems.length - 1 ?
+ self.selectedOption :
+ self.selectedOption + 1);
+ }
+ break;
+ }
+ case (38): {
+ if (!angular.isNumber(self.selectedOption)) {
+ self.selectedOption = elems.length - 1;
+ } else {
+ self.selectedOption = self.selectedOption === 0 ?
+ 0 : self.selectedOption - 1;
+ }
+ break;
+ }
+ }
+ elems[self.selectedOption].focus();
+ };
+
+ scope.getDropdownElement = function() {
+ return self.dropdownMenu;
+ };
+
+ scope.focusToggleElement = function() {
+ if (self.toggleElement) {
+ self.toggleElement[0].focus();
+ }
+ };
+
+ scope.$watch('isOpen', function(isOpen, wasOpen) {
+ if (appendToBody && self.dropdownMenu) {
+ var pos = $position.positionElements($element, self.dropdownMenu, 'bottom-left', true);
+ var css = {
+ top: pos.top + 'px',
+ display: isOpen ? 'block' : 'none'
+ };
+
+ var rightalign = self.dropdownMenu.hasClass('dropdown-menu-right');
+ if (!rightalign) {
+ css.left = pos.left + 'px';
+ css.right = 'auto';
+ } else {
+ css.left = 'auto';
+ css.right = (window.innerWidth - (pos.left + $element.prop('offsetWidth'))) + 'px';
+ }
+
+ self.dropdownMenu.css(css);
+ }
+
+ $animate[isOpen ? 'addClass' : 'removeClass']($element, openClass).then(function() {
+ if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
+ toggleInvoker($scope, { open: !!isOpen });
+ }
+ });
+
+ if (isOpen) {
+ if (self.dropdownMenuTemplateUrl) {
+ $templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) {
+ templateScope = scope.$new();
+ $compile(tplContent.trim())(templateScope, function(dropdownElement) {
+ var newEl = dropdownElement;
+ self.dropdownMenu.replaceWith(newEl);
+ self.dropdownMenu = newEl;
+ });
+ });
+ }
+
+ scope.focusToggleElement();
+ uibDropdownService.open(scope);
+ } else {
+ if (self.dropdownMenuTemplateUrl) {
+ if (templateScope) {
+ templateScope.$destroy();
+ }
+ var newEl = angular.element('<ul class="dropdown-menu"></ul>');
+ self.dropdownMenu.replaceWith(newEl);
+ self.dropdownMenu = newEl;
+ }
+
+ uibDropdownService.close(scope);
+ self.selectedOption = null;
+ }
+
+ if (angular.isFunction(setIsOpen)) {
+ setIsOpen($scope, isOpen);
+ }
+ });
+
+ $scope.$on('$locationChangeSuccess', function() {
+ if (scope.getAutoClose() !== 'disabled') {
+ scope.isOpen = false;
+ }
+ });
+
+ var offDestroy = $scope.$on('$destroy', function() {
+ scope.$destroy();
+ });
+ scope.$on('$destroy', offDestroy);
+}])
+
+.directive('uibDropdown', function() {
+ return {
+ controller: 'UibDropdownController',
+ link: function(scope, element, attrs, dropdownCtrl) {
+ dropdownCtrl.init();
+ }
+ };
+})
+
+.directive('uibDropdownMenu', function() {
+ return {
+ restrict: 'AC',
+ require: '?^uibDropdown',
+ link: function(scope, element, attrs, dropdownCtrl) {
+ if (!dropdownCtrl || angular.isDefined(attrs.dropdownNested)) {
+ return;
+ }
+
+ element.addClass('dropdown-menu');
+
+ var tplUrl = attrs.templateUrl;
+ if (tplUrl) {
+ dropdownCtrl.dropdownMenuTemplateUrl = tplUrl;
+ }
+
+ if (!dropdownCtrl.dropdownMenu) {
+ dropdownCtrl.dropdownMenu = element;
+ }
+ }
+ };
+})
+
+.directive('uibKeyboardNav', function() {
+ return {
+ restrict: 'A',
+ require: '?^uibDropdown',
+ link: function(scope, element, attrs, dropdownCtrl) {
+ element.bind('keydown', function(e) {
+ if ([38, 40].indexOf(e.which) !== -1) {
+ e.preventDefault();
+ e.stopPropagation();
+
+ var elems = dropdownCtrl.dropdownMenu.find('a');
+
+ switch (e.which) {
+ case (40): { // Down
+ if (!angular.isNumber(dropdownCtrl.selectedOption)) {
+ dropdownCtrl.selectedOption = 0;
+ } else {
+ dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === elems.length -1 ?
+ dropdownCtrl.selectedOption : dropdownCtrl.selectedOption + 1;
+ }
+ break;
+ }
+ case (38): { // Up
+ if (!angular.isNumber(dropdownCtrl.selectedOption)) {
+ dropdownCtrl.selectedOption = elems.length - 1;
+ } else {
+ dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === 0 ?
+ 0 : dropdownCtrl.selectedOption - 1;
+ }
+ break;
+ }
+ }
+ elems[dropdownCtrl.selectedOption].focus();
+ }
+ });
+ }
+ };
+})
+
+.directive('uibDropdownToggle', function() {
+ return {
+ require: '?^uibDropdown',
+ link: function(scope, element, attrs, dropdownCtrl) {
+ if (!dropdownCtrl) {
+ return;
+ }
+
+ element.addClass('dropdown-toggle');
+
+ dropdownCtrl.toggleElement = element;
+
+ var toggleDropdown = function(event) {
+ event.preventDefault();
+
+ if (!element.hasClass('disabled') && !attrs.disabled) {
+ scope.$apply(function() {
+ dropdownCtrl.toggle();
+ });
+ }
+ };
+
+ element.bind('click', toggleDropdown);
+
+ // WAI-ARIA
+ element.attr({ 'aria-haspopup': true, 'aria-expanded': false });
+ scope.$watch(dropdownCtrl.isOpen, function(isOpen) {
+ element.attr('aria-expanded', !!isOpen);
+ });
+
+ scope.$on('$destroy', function() {
+ element.unbind('click', toggleDropdown);
+ });
+ }
+ };
+});
+
+/* Deprecated dropdown below */
+
+angular.module('ui.bootstrap.dropdown')
+
+.value('$dropdownSuppressWarning', false)
+
+.service('dropdownService', ['$log', '$dropdownSuppressWarning', 'uibDropdownService', function($log, $dropdownSuppressWarning, uibDropdownService) {
+ if (!$dropdownSuppressWarning) {
+ $log.warn('dropdownService is now deprecated. Use uibDropdownService instead.');
+ }
+
+ angular.extend(this, uibDropdownService);
+}])
+
+.controller('DropdownController', ['$scope', '$element', '$attrs', '$parse', 'uibDropdownConfig', 'uibDropdownService', '$animate', '$uibPosition', '$document', '$compile', '$templateRequest', '$log', '$dropdownSuppressWarning', function($scope, $element, $attrs, $parse, dropdownConfig, uibDropdownService, $animate, $position, $document, $compile, $templateRequest, $log, $dropdownSuppressWarning) {
+ if (!$dropdownSuppressWarning) {
+ $log.warn('DropdownController is now deprecated. Use UibDropdownController instead.');
+ }
+
+ var self = this,
+ scope = $scope.$new(), // create a child scope so we are not polluting original one
+ templateScope,
+ openClass = dropdownConfig.openClass,
+ getIsOpen,
+ setIsOpen = angular.noop,
+ toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop,
+ appendToBody = false,
+ keynavEnabled =false,
+ selectedOption = null;
+
+
+ $element.addClass('dropdown');
+
+ this.init = function() {
+ if ($attrs.isOpen) {
+ getIsOpen = $parse($attrs.isOpen);
+ setIsOpen = getIsOpen.assign;
+
+ $scope.$watch(getIsOpen, function(value) {
+ scope.isOpen = !!value;
+ });
+ }
+
+ appendToBody = angular.isDefined($attrs.dropdownAppendToBody);
+ keynavEnabled = angular.isDefined($attrs.uibKeyboardNav);
+
+ if (appendToBody && self.dropdownMenu) {
+ $document.find('body').append(self.dropdownMenu);
+ $element.on('$destroy', function handleDestroyEvent() {
+ self.dropdownMenu.remove();
+ });
+ }
+ };
+
+ this.toggle = function(open) {
+ return scope.isOpen = arguments.length ? !!open : !scope.isOpen;
+ };
+
+ // Allow other directives to watch status
+ this.isOpen = function() {
+ return scope.isOpen;
+ };
+
+ scope.getToggleElement = function() {
+ return self.toggleElement;
+ };
+
+ scope.getAutoClose = function() {
+ return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled'
+ };
+
+ scope.getElement = function() {
+ return $element;
+ };
+
+ scope.isKeynavEnabled = function() {
+ return keynavEnabled;
+ };
+
+ scope.focusDropdownEntry = function(keyCode) {
+ var elems = self.dropdownMenu ? //If append to body is used.
+ (angular.element(self.dropdownMenu).find('a')) :
+ (angular.element($element).find('ul').eq(0).find('a'));
+
+ switch (keyCode) {
+ case (40): {
+ if (!angular.isNumber(self.selectedOption)) {
+ self.selectedOption = 0;
+ } else {
+ self.selectedOption = (self.selectedOption === elems.length -1 ?
+ self.selectedOption :
+ self.selectedOption + 1);
+ }
+ break;
+ }
+ case (38): {
+ if (!angular.isNumber(self.selectedOption)) {
+ self.selectedOption = elems.length - 1;
+ } else {
+ self.selectedOption = self.selectedOption === 0 ?
+ 0 : self.selectedOption - 1;
+ }
+ break;
+ }
+ }
+ elems[self.selectedOption].focus();
+ };
+
+ scope.getDropdownElement = function() {
+ return self.dropdownMenu;
+ };
+
+ scope.focusToggleElement = function() {
+ if (self.toggleElement) {
+ self.toggleElement[0].focus();
+ }
+ };
+
+ scope.$watch('isOpen', function(isOpen, wasOpen) {
+ if (appendToBody && self.dropdownMenu) {
+ var pos = $position.positionElements($element, self.dropdownMenu, 'bottom-left', true);
+ var css = {
+ top: pos.top + 'px',
+ display: isOpen ? 'block' : 'none'
+ };
+
+ var rightalign = self.dropdownMenu.hasClass('dropdown-menu-right');
+ if (!rightalign) {
+ css.left = pos.left + 'px';
+ css.right = 'auto';
+ } else {
+ css.left = 'auto';
+ css.right = (window.innerWidth - (pos.left + $element.prop('offsetWidth'))) + 'px';
+ }
+
+ self.dropdownMenu.css(css);
+ }
+
+ $animate[isOpen ? 'addClass' : 'removeClass']($element, openClass).then(function() {
+ if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
+ toggleInvoker($scope, { open: !!isOpen });
+ }
+ });
+
+ if (isOpen) {
+ if (self.dropdownMenuTemplateUrl) {
+ $templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) {
+ templateScope = scope.$new();
+ $compile(tplContent.trim())(templateScope, function(dropdownElement) {
+ var newEl = dropdownElement;
+ self.dropdownMenu.replaceWith(newEl);
+ self.dropdownMenu = newEl;
+ });
+ });
+ }
+
+ scope.focusToggleElement();
+ uibDropdownService.open(scope);
+ } else {
+ if (self.dropdownMenuTemplateUrl) {
+ if (templateScope) {
+ templateScope.$destroy();
+ }
+ var newEl = angular.element('<ul class="dropdown-menu"></ul>');
+ self.dropdownMenu.replaceWith(newEl);
+ self.dropdownMenu = newEl;
+ }
+
+ uibDropdownService.close(scope);
+ self.selectedOption = null;
+ }
+
+ if (angular.isFunction(setIsOpen)) {
+ setIsOpen($scope, isOpen);
+ }
+ });
+
+ $scope.$on('$locationChangeSuccess', function() {
+ if (scope.getAutoClose() !== 'disabled') {
+ scope.isOpen = false;
+ }
+ });
+
+ var offDestroy = $scope.$on('$destroy', function() {
+ scope.$destroy();
+ });
+ scope.$on('$destroy', offDestroy);
+}])
+
+.directive('dropdown', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) {
+ return {
+ controller: 'DropdownController',
+ link: function(scope, element, attrs, dropdownCtrl) {
+ if (!$dropdownSuppressWarning) {
+ $log.warn('dropdown is now deprecated. Use uib-dropdown instead.');
+ }
+
+ dropdownCtrl.init();
+ }
+ };
+}])
+
+.directive('dropdownMenu', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) {
+ return {
+ restrict: 'AC',
+ require: '?^dropdown',
+ link: function(scope, element, attrs, dropdownCtrl) {
+ if (!dropdownCtrl || angular.isDefined(attrs.dropdownNested)) {
+ return;
+ }
+
+ if (!$dropdownSuppressWarning) {
+ $log.warn('dropdown-menu is now deprecated. Use uib-dropdown-menu instead.');
+ }
+
+ element.addClass('dropdown-menu');
+
+ var tplUrl = attrs.templateUrl;
+ if (tplUrl) {
+ dropdownCtrl.dropdownMenuTemplateUrl = tplUrl;
+ }
+
+ if (!dropdownCtrl.dropdownMenu) {
+ dropdownCtrl.dropdownMenu = element;
+ }
+ }
+ };
+}])
+
+.directive('keyboardNav', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) {
+ return {
+ restrict: 'A',
+ require: '?^dropdown',
+ link: function(scope, element, attrs, dropdownCtrl) {
+ if (!$dropdownSuppressWarning) {
+ $log.warn('keyboard-nav is now deprecated. Use uib-keyboard-nav instead.');
+ }
+
+ element.bind('keydown', function(e) {
+ if ([38, 40].indexOf(e.which) !== -1) {
+ e.preventDefault();
+ e.stopPropagation();
+
+ var elems = dropdownCtrl.dropdownMenu.find('a');
+
+ switch (e.which) {
+ case (40): { // Down
+ if (!angular.isNumber(dropdownCtrl.selectedOption)) {
+ dropdownCtrl.selectedOption = 0;
+ } else {
+ dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === elems.length -1 ?
+ dropdownCtrl.selectedOption : dropdownCtrl.selectedOption + 1;
+ }
+ break;
+ }
+ case (38): { // Up
+ if (!angular.isNumber(dropdownCtrl.selectedOption)) {
+ dropdownCtrl.selectedOption = elems.length - 1;
+ } else {
+ dropdownCtrl.selectedOption = dropdownCtrl.selectedOption === 0 ?
+ 0 : dropdownCtrl.selectedOption - 1;
+ }
+ break;
+ }
+ }
+ elems[dropdownCtrl.selectedOption].focus();
+ }
+ });
+ }
+ };
+}])
+
+.directive('dropdownToggle', ['$log', '$dropdownSuppressWarning', function($log, $dropdownSuppressWarning) {
+ return {
+ require: '?^dropdown',
+ link: function(scope, element, attrs, dropdownCtrl) {
+ if (!$dropdownSuppressWarning) {
+ $log.warn('dropdown-toggle is now deprecated. Use uib-dropdown-toggle instead.');
+ }
+
+ if (!dropdownCtrl) {
+ return;
+ }
+
+ element.addClass('dropdown-toggle');
+
+ dropdownCtrl.toggleElement = element;
+
+ var toggleDropdown = function(event) {
+ event.preventDefault();
+
+ if (!element.hasClass('disabled') && !attrs.disabled) {
+ scope.$apply(function() {
+ dropdownCtrl.toggle();
+ });
+ }
+ };
+
+ element.bind('click', toggleDropdown);
+
+ // WAI-ARIA
+ element.attr({ 'aria-haspopup': true, 'aria-expanded': false });
+ scope.$watch(dropdownCtrl.isOpen, function(isOpen) {
+ element.attr('aria-expanded', !!isOpen);
+ });
+
+ scope.$on('$destroy', function() {
+ element.unbind('click', toggleDropdown);
+ });
+ }
+ };
+}]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/test/dropdown.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/test/dropdown.spec.js
new file mode 100644
index 0000000..6d6a87d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/dropdown/test/dropdown.spec.js
@@ -0,0 +1,727 @@
+describe('dropdownToggle', function() {
+ var $animate, $compile, $rootScope, $document, $templateCache, dropdownConfig, element, $browser, $log;
+
+ beforeEach(module('ngAnimateMock'));
+ beforeEach(module('ui.bootstrap.dropdown'));
+
+ beforeEach(inject(function(_$animate_, _$compile_, _$rootScope_, _$document_, _$templateCache_, uibDropdownConfig, _$browser_, _$log_) {
+ $animate = _$animate_;
+ $compile = _$compile_;
+ $rootScope = _$rootScope_;
+ $document = _$document_;
+ $templateCache = _$templateCache_;
+ dropdownConfig = uibDropdownConfig;
+ $browser = _$browser_;
+ $log = _$log_;
+ }));
+
+ afterEach(function() {
+ element.remove();
+ });
+
+ var clickDropdownToggle = function(elm) {
+ elm = elm || element;
+ elm.find('a[uib-dropdown-toggle]').click();
+ };
+
+ var triggerKeyDown = function (element, keyCode) {
+ var e = $.Event('keydown');
+ e.which = keyCode;
+ element.trigger(e);
+ };
+
+ var isFocused = function(elm) {
+ return elm[0] === document.activeElement;
+ };
+
+ describe('basic', function() {
+ function dropdown() {
+ return $compile('<li uib-dropdown><a href uib-dropdown-toggle></a><ul><li><a href>Hello</a></li></ul></li>')($rootScope);
+ }
+
+ beforeEach(function() {
+ element = dropdown();
+ });
+
+ it('should toggle on `a` click', function() {
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+
+ it('should toggle when an option is clicked', function() {
+ $document.find('body').append(element);
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+
+ var optionEl = element.find('ul > li').eq(0).find('a').eq(0);
+ optionEl.click();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+
+ it('should close on document click', function() {
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ $document.click();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+
+ it('should close on escape key & focus toggle element', function() {
+ $document.find('body').append(element);
+ clickDropdownToggle();
+ triggerKeyDown($document, 27);
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ expect(isFocused(element.find('a'))).toBe(true);
+ });
+
+ it('should not close on backspace key', function() {
+ clickDropdownToggle();
+ triggerKeyDown($document, 8);
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ });
+
+ it('should close on $location change', function() {
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ $rootScope.$broadcast('$locationChangeSuccess');
+ $rootScope.$apply();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+
+ it('should only allow one dropdown to be open at once', function() {
+ var elm1 = dropdown();
+ var elm2 = dropdown();
+ expect(elm1.hasClass(dropdownConfig.openClass)).toBe(false);
+ expect(elm2.hasClass(dropdownConfig.openClass)).toBe(false);
+
+ clickDropdownToggle( elm1 );
+ expect(elm1.hasClass(dropdownConfig.openClass)).toBe(true);
+ expect(elm2.hasClass(dropdownConfig.openClass)).toBe(false);
+
+ clickDropdownToggle( elm2 );
+ expect(elm1.hasClass(dropdownConfig.openClass)).toBe(false);
+ expect(elm2.hasClass(dropdownConfig.openClass)).toBe(true);
+ });
+
+ it('should not toggle if the element has `disabled` class', function() {
+ var elm = $compile('<li uib-dropdown><a class="disabled" uib-dropdown-toggle></a><ul><li>Hello</li></ul></li>')($rootScope);
+ clickDropdownToggle( elm );
+ expect(elm.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+
+ it('should not toggle if the element is disabled', function() {
+ var elm = $compile('<li uib-dropdown><button disabled="disabled" uib-dropdown-toggle></button><ul><li>Hello</li></ul></li>')($rootScope);
+ elm.find('button').click();
+ expect(elm.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+
+ it('should not toggle if the element has `ng-disabled` as true', function() {
+ $rootScope.isdisabled = true;
+ var elm = $compile('<li uib-dropdown><div ng-disabled="isdisabled" uib-dropdown-toggle></div><ul><li>Hello</li></ul></li>')($rootScope);
+ $rootScope.$digest();
+ elm.find('div').click();
+ expect(elm.hasClass(dropdownConfig.openClass)).toBe(false);
+
+ $rootScope.isdisabled = false;
+ $rootScope.$digest();
+ elm.find('div').click();
+ expect(elm.hasClass(dropdownConfig.openClass)).toBe(true);
+ });
+
+ it('should unbind events on scope destroy', function() {
+ var $scope = $rootScope.$new();
+ var elm = $compile('<li uib-dropdown><button ng-disabled="isdisabled" uib-dropdown-toggle></button><ul><li>Hello</li></ul></li>')($scope);
+ $scope.$digest();
+
+ var buttonEl = elm.find('button');
+ buttonEl.click();
+ expect(elm.hasClass(dropdownConfig.openClass)).toBe(true);
+ buttonEl.click();
+ expect(elm.hasClass(dropdownConfig.openClass)).toBe(false);
+
+ $scope.$destroy();
+ buttonEl.click();
+ expect(elm.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+
+ // issue 270
+ it('executes other document click events normally', function() {
+ var checkboxEl = $compile('<input type="checkbox" ng-click="clicked = true" />')($rootScope);
+ $rootScope.$digest();
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ expect($rootScope.clicked).toBeFalsy();
+
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ expect($rootScope.clicked).toBeFalsy();
+
+ checkboxEl.click();
+ expect($rootScope.clicked).toBeTruthy();
+ });
+
+ // WAI-ARIA
+ it('should aria markup to the `dropdown-toggle`', function() {
+ var toggleEl = element.find('a');
+ expect(toggleEl.attr('aria-haspopup')).toBe('true');
+ expect(toggleEl.attr('aria-expanded')).toBe('false');
+
+ clickDropdownToggle();
+ expect(toggleEl.attr('aria-expanded')).toBe('true');
+ clickDropdownToggle();
+ expect(toggleEl.attr('aria-expanded')).toBe('false');
+ });
+
+ // pr/issue 3274
+ it('should not raise $digest:inprog if dismissed during a digest cycle', function() {
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+
+ $rootScope.$apply(function() {
+ $document.click();
+ });
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+ });
+
+ describe('using dropdownMenuTemplate', function() {
+ function dropdown() {
+ $templateCache.put('custom.html', '<ul class="uib-dropdown-menu"><li>Item 1</li></ul>');
+
+ return $compile('<li uib-dropdown><a href uib-dropdown-toggle></a><ul class="uib-dropdown-menu" template-url="custom.html"></ul></li>')($rootScope);
+ }
+
+ beforeEach(function() {
+ element = dropdown();
+ });
+
+ it('should apply custom template for dropdown menu', function() {
+ element.find('a').click();
+ expect(element.find('ul.uib-dropdown-menu').eq(0).find('li').eq(0).text()).toEqual('Item 1');
+ });
+
+ it('should clear ul when dropdown menu is closed', function() {
+ element.find('a').click();
+ expect(element.find('ul.uib-dropdown-menu').eq(0).find('li').eq(0).text()).toEqual('Item 1');
+ element.find('a').click();
+ expect(element.find('ul.uib-dropdown-menu').eq(0).find('li').length).toEqual(0);
+ });
+ });
+
+ describe('using dropdown-append-to-body', function() {
+ function dropdown() {
+ return $compile('<li uib-dropdown dropdown-append-to-body><a href uib-dropdown-toggle></a><ul class="uib-dropdown-menu" id="dropdown-menu"><li><a href>Hello On Body</a></li></ul></li>')($rootScope);
+ }
+
+ beforeEach(function() {
+ element = dropdown();
+ });
+
+ it('adds the menu to the body', function() {
+ expect($document.find('#dropdown-menu').parent()[0]).toBe($document.find('body')[0]);
+ });
+
+ it('removes the menu when the dropdown is removed', function() {
+ element.remove();
+ $rootScope.$digest();
+ expect($document.find('#dropdown-menu').length).toEqual(0);
+ });
+ });
+
+ describe('integration with $location URL rewriting', function() {
+ function dropdown() {
+ // Simulate URL rewriting behavior
+ $document.on('click', 'a[href="#something"]', function() {
+ $rootScope.$broadcast('$locationChangeSuccess');
+ $rootScope.$apply();
+ });
+
+ return $compile('<li uib-dropdown><a href uib-dropdown-toggle></a>' +
+ '<ul><li><a href="#something">Hello</a></li></ul></li>')($rootScope);
+ }
+
+ beforeEach(function() {
+ element = dropdown();
+ });
+
+ it('should close without errors on $location change', function() {
+ $document.find('body').append(element);
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ var optionEl = element.find('ul > li').eq(0).find('a').eq(0);
+ optionEl.click();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+ });
+
+ describe('without trigger', function() {
+ beforeEach(function() {
+ $rootScope.isopen = true;
+ element = $compile('<li uib-dropdown is-open="isopen"><ul><li>Hello</li></ul></li>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('should be open initially', function() {
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ });
+
+ it('should toggle when `is-open` changes', function() {
+ $rootScope.isopen = false;
+ $rootScope.$digest();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+ });
+
+ describe('`is-open`', function() {
+ beforeEach(function() {
+ $rootScope.isopen = true;
+ element = $compile('<li uib-dropdown is-open="isopen"><a href uib-dropdown-toggle></a><ul><li>Hello</li></ul></li>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('should be open initially', function() {
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ });
+
+ it('should change `is-open` binding when toggles', function() {
+ clickDropdownToggle();
+ expect($rootScope.isopen).toBe(false);
+ });
+
+ it('should toggle when `is-open` changes', function() {
+ $rootScope.isopen = false;
+ $rootScope.$digest();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+
+ it('focus toggle element when opening', function() {
+ $document.find('body').append(element);
+ clickDropdownToggle();
+ $rootScope.isopen = false;
+ $rootScope.$digest();
+ expect(isFocused(element.find('a'))).toBe(false);
+ $rootScope.isopen = true;
+ $rootScope.$digest();
+ expect(isFocused(element.find('a'))).toBe(true);
+ });
+ });
+
+ describe('`on-toggle`', function() {
+ beforeEach(function() {
+ $rootScope.toggleHandler = jasmine.createSpy('toggleHandler');
+ $rootScope.isopen = false;
+ element = $compile('<li uib-dropdown on-toggle="toggleHandler(open)" is-open="isopen"><a uib-dropdown-toggle></a><ul><li>Hello</li></ul></li>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('should not have been called initially', function() {
+ expect($rootScope.toggleHandler).not.toHaveBeenCalled();
+ });
+
+ it('should call it correctly when toggles', function() {
+ $rootScope.isopen = true;
+ $rootScope.$digest();
+
+ $animate.flush();
+ $rootScope.$digest();
+ expect($rootScope.toggleHandler).toHaveBeenCalledWith(true);
+
+ clickDropdownToggle();
+ $animate.flush();
+ $rootScope.$digest();
+ expect($rootScope.toggleHandler).toHaveBeenCalledWith(false);
+ });
+ });
+
+ describe('`on-toggle` with initially open', function() {
+ beforeEach(function() {
+ $rootScope.toggleHandler = jasmine.createSpy('toggleHandler');
+ $rootScope.isopen = true;
+ element = $compile('<li uib-dropdown on-toggle="toggleHandler(open)" is-open="isopen"><a uib-dropdown-toggle></a><ul><li>Hello</li></ul></li>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('should not have been called initially', function() {
+ expect($rootScope.toggleHandler).not.toHaveBeenCalled();
+ });
+
+ it('should call it correctly when toggles', function() {
+ $rootScope.isopen = false;
+ $rootScope.$digest();
+
+ $animate.flush();
+ $rootScope.$digest();
+ expect($rootScope.toggleHandler).toHaveBeenCalledWith(false);
+
+ $rootScope.isopen = true;
+ $rootScope.$digest();
+
+ $animate.flush();
+ $rootScope.$digest();
+ expect($rootScope.toggleHandler).toHaveBeenCalledWith(true);
+ });
+ });
+
+ describe('`on-toggle` without is-open', function() {
+ beforeEach(function() {
+ $rootScope.toggleHandler = jasmine.createSpy('toggleHandler');
+ element = $compile('<li uib-dropdown on-toggle="toggleHandler(open)"><a uib-dropdown-toggle></a><ul><li>Hello</li></ul></li>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('should not have been called initially', function() {
+ expect($rootScope.toggleHandler).not.toHaveBeenCalled();
+ });
+
+ it('should call it when clicked', function() {
+ clickDropdownToggle();
+
+ $animate.flush();
+ $rootScope.$digest();
+ expect($rootScope.toggleHandler).toHaveBeenCalledWith(true);
+
+ clickDropdownToggle();
+
+ $animate.flush();
+ $rootScope.$digest();
+ expect($rootScope.toggleHandler).toHaveBeenCalledWith(false);
+ });
+ });
+
+ describe('`auto-close` option', function() {
+ function dropdown(autoClose) {
+ return $compile('<li uib-dropdown ' +
+ (autoClose === void 0 ? '' : 'auto-close="'+autoClose+'"') +
+ '><a href uib-dropdown-toggle></a><ul><li><a href>Hello</a></li></ul></li>')($rootScope);
+ }
+
+ it('should close on document click if no auto-close is specified', function() {
+ element = dropdown();
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ $document.click();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+
+ it('should close on document click if empty auto-close is specified', function() {
+ element = dropdown('');
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ $document.click();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+
+ it('auto-close="disabled"', function() {
+ element = dropdown('disabled');
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ $document.click();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ });
+
+ describe('outsideClick', function() {
+ it('should close only on a click outside of the dropdown menu', function() {
+ element = dropdown('outsideClick');
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ element.find('ul li a').click();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ $document.click();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+
+ it('should work with dropdown-append-to-body', function() {
+ element = $compile('<li uib-dropdown dropdown-append-to-body auto-close="outsideClick"><a href uib-dropdown-toggle></a><ul class="uib-dropdown-menu" id="dropdown-menu"><li><a href>Hello On Body</a></li></ul></li>')($rootScope);
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ $document.find('#dropdown-menu').find('li').eq(0).trigger('click');
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ $document.click();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+ });
+
+ it('control with is-open', function() {
+ $rootScope.isopen = true;
+ element = $compile('<li uib-dropdown is-open="isopen" auto-close="disabled"><a href uib-dropdown-toggle></a><ul><li>Hello</li></ul></li>')($rootScope);
+ $rootScope.$digest();
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ //should remain open
+ $document.click();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ //now should close
+ $rootScope.isopen = false;
+ $rootScope.$digest();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+
+ it('should close anyway if toggle is clicked', function() {
+ element = dropdown('disabled');
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+
+ it('should close anyway if esc is pressed', function() {
+ element = dropdown('disabled');
+ $document.find('body').append(element);
+ clickDropdownToggle();
+ triggerKeyDown($document, 27);
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ expect(isFocused(element.find('a'))).toBe(true);
+ });
+
+ it('should close anyway if another dropdown is opened', function() {
+ var elm1 = dropdown('disabled');
+ var elm2 = dropdown();
+ expect(elm1.hasClass(dropdownConfig.openClass)).toBe(false);
+ expect(elm2.hasClass(dropdownConfig.openClass)).toBe(false);
+ clickDropdownToggle(elm1);
+ expect(elm1.hasClass(dropdownConfig.openClass)).toBe(true);
+ expect(elm2.hasClass(dropdownConfig.openClass)).toBe(false);
+ clickDropdownToggle(elm2);
+ expect(elm1.hasClass(dropdownConfig.openClass)).toBe(false);
+ expect(elm2.hasClass(dropdownConfig.openClass)).toBe(true);
+ });
+
+ it('should not close on $locationChangeSuccess if auto-close="disabled"', function() {
+ var elm1 = dropdown('disabled');
+ expect(elm1.hasClass(dropdownConfig.openClass)).toBe(false);
+ clickDropdownToggle(elm1);
+ expect(elm1.hasClass(dropdownConfig.openClass)).toBe(true);
+ $rootScope.$broadcast('$locationChangeSuccess');
+ $rootScope.$digest();
+ expect(elm1.hasClass(dropdownConfig.openClass)).toBe(true);
+ });
+ });
+
+ describe('`keyboard-nav` option', function() {
+ function dropdown() {
+ return $compile('<li uib-dropdown uib-keyboard-nav><a href uib-dropdown-toggle></a><ul><li><a href>Hello</a></li><li><a href>Hello Again</a></li></ul></li>')($rootScope);
+ }
+ beforeEach(function() {
+ element = dropdown();
+ });
+
+ it('should focus first list element when down arrow pressed', function() {
+ $document.find('body').append(element);
+ clickDropdownToggle();
+ triggerKeyDown($document, 40);
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ var optionEl = element.find('ul').eq(0).find('a').eq(0);
+ expect(isFocused(optionEl)).toBe(true);
+ });
+
+ it('should not focus first list element when down arrow pressed if closed', function() {
+ $document.find('body').append(element);
+ triggerKeyDown($document, 40);
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ var focusEl = element.find('ul').eq(0).find('a').eq(0);
+ expect(isFocused(focusEl)).toBe(false);
+ });
+
+ it('should focus second list element when down arrow pressed twice', function() {
+ $document.find('body').append(element);
+ clickDropdownToggle();
+ triggerKeyDown($document, 40);
+ triggerKeyDown($document, 40);
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ var focusEl = element.find('ul').eq(0).find('a').eq(1);
+ expect(isFocused(focusEl)).toBe(true);
+ });
+ });
+
+ describe('`keyboard-nav` option', function() {
+ function dropdown() {
+ return $compile('<li uib-dropdown uib-keyboard-nav><a href uib-dropdown-toggle></a><ul><li><a href>Hello</a></li><li><a href>Hello Again</a></li></ul></li>')($rootScope);
+ }
+ beforeEach(function() {
+ element = dropdown();
+ });
+
+ it('should focus first list element when down arrow pressed', function() {
+ $document.find('body').append(element);
+ clickDropdownToggle();
+ triggerKeyDown($document, 40);
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ var focusEl = element.find('ul').eq(0).find('a').eq(0);
+ expect(isFocused(focusEl)).toBe(true);
+ });
+
+ it('should not focus first list element when up arrow pressed after dropdown toggled', function() {
+ $document.find('body').append(element);
+ clickDropdownToggle();
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+
+ triggerKeyDown($document, 38);
+ var focusEl = element.find('ul').eq(0).find('a').eq(0);
+ expect(isFocused(focusEl)).toBe(false);
+ });
+
+ it('should focus last list element when up arrow pressed after dropdown toggled', function() {
+ $document.find('body').append(element);
+ clickDropdownToggle();
+ triggerKeyDown($document, 38);
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ var focusEl = element.find('ul').eq(0).find('a').eq(1);
+ expect(isFocused(focusEl)).toBe(true);
+ });
+
+ it('should not focus any list element when down arrow pressed if closed', function() {
+ $document.find('body').append(element);
+ triggerKeyDown($document, 40);
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ var focusEl = element.find('ul').eq(0).find('a');
+ expect(isFocused(focusEl[0])).toBe(false);
+ expect(isFocused(focusEl[1])).toBe(false);
+ });
+
+ it('should not change focus when other keys are pressed', function() {
+ $document.find('body').append(element);
+ clickDropdownToggle();
+ triggerKeyDown($document, 37);
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ var focusEl = element.find('ul').eq(0).find('a');
+ expect(isFocused(focusEl[0])).toBe(false);
+ expect(isFocused(focusEl[1])).toBe(false);
+ });
+
+ it('should focus second list element when down arrow pressed twice', function() {
+ $document.find('body').append(element);
+ clickDropdownToggle();
+ triggerKeyDown($document, 40);
+ triggerKeyDown($document, 40);
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ var focusEl = element.find('ul').eq(0).find('a').eq(1);
+ expect(isFocused(focusEl)).toBe(true);
+ });
+
+ it('should focus first list element when down arrow pressed 2x and up pressed 1x', function() {
+ $document.find('body').append(element);
+ clickDropdownToggle();
+ triggerKeyDown($document, 40);
+ triggerKeyDown($document, 40);
+
+ triggerKeyDown($document, 38);
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ var focusEl = element.find('ul').eq(0).find('a').eq(0);
+ expect(isFocused(focusEl)).toBe(true);
+ });
+
+ it('should stay focused on final list element if down pressed at list end', function() {
+ $document.find('body').append(element);
+ clickDropdownToggle();
+ triggerKeyDown($document, 40);
+ triggerKeyDown($document, 40);
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ var focusEl = element.find('ul').eq(0).find('a').eq(1);
+ expect(isFocused(focusEl)).toBe(true);
+
+ triggerKeyDown($document, 40);
+ expect(isFocused(focusEl)).toBe(true);
+ });
+
+ it('should close if esc is pressed while focused', function() {
+ element = dropdown('disabled');
+ $document.find('body').append(element);
+ clickDropdownToggle();
+
+ triggerKeyDown($document, 40);
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ var focusEl = element.find('ul').eq(0).find('a').eq(0);
+ expect(isFocused(focusEl)).toBe(true);
+
+ triggerKeyDown($document, 27);
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(false);
+ });
+ });
+
+ describe('`keyboard-nav` option with `dropdown-append-to-body` option', function() {
+ function dropdown() {
+ return $compile('<li uib-dropdown dropdown-append-to-body uib-keyboard-nav><a href uib-dropdown-toggle></a><ul class="uib-dropdown-menu" id="dropdown-menu"><li><a href>Hello On Body</a></li><li><a href>Hello Again</a></li></ul></li>')($rootScope);
+ }
+
+ beforeEach(function() {
+ element = dropdown();
+ });
+
+ it('should focus first list element when down arrow pressed', function() {
+ clickDropdownToggle();
+
+ triggerKeyDown(element, 40);
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ var focusEl = $document.find('ul').eq(0).find('a');
+ expect(isFocused(focusEl)).toBe(true);
+ });
+
+ it('should focus second list element when down arrow pressed twice', function() {
+ clickDropdownToggle();
+ triggerKeyDown(element, 40);
+ triggerKeyDown(element, 40);
+
+ expect(element.hasClass(dropdownConfig.openClass)).toBe(true);
+ var elem1 = $document.find('ul');
+ var elem2 = elem1.find('a');
+ var focusEl = $document.find('ul').eq(0).find('a').eq(1);
+ expect(isFocused(focusEl)).toBe(true);
+ });
+ });
+});
+
+/* Deprecation tests below */
+
+describe('dropdown deprecation', function() {
+ beforeEach(module('ngAnimateMock'));
+ beforeEach(module('ui.bootstrap.dropdown'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$dropdownSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+ var element = $compile('<li dropdown><a href dropdown-toggle></a><ul><li><a href>Hello</a></li></ul></li>')($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+ var element = $compile('<li dropdown><a href></a><ul><li><a href dropdown-toggle>Hello</a></li></ul></li>')($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(3);
+ expect($log.warn.calls.argsFor(0)).toEqual(['DropdownController is now deprecated. Use UibDropdownController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['dropdown-toggle is now deprecated. Use uib-dropdown-toggle instead.']);
+ expect($log.warn.calls.argsFor(2)).toEqual(['dropdown is now deprecated. Use uib-dropdown instead.']);
+ }));
+
+ it('should give warning by default for keyboardNav', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+ var element = $compile('<li dropdown keyboard-nav><a href ></a><ul><li><a href>Hello</a></li></ul></li>')($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(3);
+ expect($log.warn.calls.argsFor(0)).toEqual(['DropdownController is now deprecated. Use UibDropdownController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['keyboard-nav is now deprecated. Use uib-keyboard-nav instead.']);
+ expect($log.warn.calls.argsFor(2)).toEqual(['dropdown is now deprecated. Use uib-dropdown instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/docs/demo.html
new file mode 100644
index 0000000..ac96e07
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/docs/demo.html
@@ -0,0 +1,25 @@
+<div ng-controller="ModalDemoCtrl">
+ <script type="text/ng-template" id="myModalContent.html">
+ <div class="modal-header">
+ <h3 class="modal-title">I'm a modal!</h3>
+ </div>
+ <div class="modal-body">
+ <ul>
+ <li ng-repeat="item in items">
+ <a href="#" ng-click="$event.preventDefault(); selected.item = item">{{ item }}</a>
+ </li>
+ </ul>
+ Selected: <b>{{ selected.item }}</b>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-primary" type="button" ng-click="ok()">OK</button>
+ <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
+ </div>
+ </script>
+
+ <button type="button" class="btn btn-default" ng-click="open()">Open me!</button>
+ <button type="button" class="btn btn-default" ng-click="open('lg')">Large modal</button>
+ <button type="button" class="btn btn-default" ng-click="open('sm')">Small modal</button>
+ <button type="button" class="btn btn-default" ng-click="toggleAnimation()">Toggle Animation ({{ animationsEnabled }})</button>
+ <div ng-show="selected">Selection from a modal: {{ selected }}</div>
+</div>
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/docs/demo.js
new file mode 100644
index 0000000..60e3a5e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/docs/demo.js
@@ -0,0 +1,51 @@
+angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $uibModal, $log) {
+
+ $scope.items = ['item1', 'item2', 'item3'];
+
+ $scope.animationsEnabled = true;
+
+ $scope.open = function (size) {
+
+ var modalInstance = $uibModal.open({
+ animation: $scope.animationsEnabled,
+ templateUrl: 'myModalContent.html',
+ controller: 'ModalInstanceCtrl',
+ size: size,
+ resolve: {
+ items: function () {
+ return $scope.items;
+ }
+ }
+ });
+
+ modalInstance.result.then(function (selectedItem) {
+ $scope.selected = selectedItem;
+ }, function () {
+ $log.info('Modal dismissed at: ' + new Date());
+ });
+ };
+
+ $scope.toggleAnimation = function () {
+ $scope.animationsEnabled = !$scope.animationsEnabled;
+ };
+
+});
+
+// Please note that $modalInstance represents a modal window (instance) dependency.
+// It is not the same as the $uibModal service used above.
+
+angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, items) {
+
+ $scope.items = items;
+ $scope.selected = {
+ item: $scope.items[0]
+ };
+
+ $scope.ok = function () {
+ $uibModalInstance.close($scope.selected.item);
+ };
+
+ $scope.cancel = function () {
+ $uibModalInstance.dismiss('cancel');
+ };
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/docs/readme.md
new file mode 100644
index 0000000..e3c5064
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/docs/readme.md
@@ -0,0 +1,45 @@
+`$uibModal` is a service to quickly create AngularJS-powered modal windows.
+Creating custom modals is straightforward: create a partial view, its controller and reference them when using the service.
+
+The `$uibModal` service has only one method: `open(options)` where available options are like follows:
+
+* `templateUrl` - a path to a template representing modal's content
+* `template` - inline template representing the modal's content
+* `scope` - a scope instance to be used for the modal's content (actually the `$uibModal` service is going to create a child scope of a provided scope). Defaults to `$rootScope`
+* `controller` - a controller for a modal instance - it can initialize scope used by modal. Accepts the "controller-as" syntax in the form 'SomeCtrl as myctrl'; can be injected with `$uibModalInstance`
+* `controllerAs` - an alternative to the controller-as syntax, matching the API of directive definitions. Requires the `controller` option to be provided as well
+* `bindToController` - when used with `controllerAs` & set to `true`, it will bind the $scope properties onto the controller directly
+* `resolve` - members that will be resolved and passed to the controller as locals; it is equivalent of the `resolve` property for AngularJS routes
+* `animation` - set to false to disable animations on new modal/backdrop. Does not toggle animations for modals/backdrops that are already displayed.
+* `backdrop` - controls presence of a backdrop. Allowed values: true (default), false (no backdrop), `'static'` - backdrop is present but modal window is not closed when clicking outside of the modal window.
+* `keyboard` - indicates whether the dialog should be closable by hitting the ESC key, defaults to true
+* `backdropClass` - additional CSS class(es) to be added to a modal backdrop template
+* `windowClass` - additional CSS class(es) to be added to a modal window template
+* `windowTopClass` - CSS class(es) to be added to the top modal window
+* `windowTemplateUrl` - a path to a template overriding modal's window template
+* `size` - optional suffix of modal window class. The value used is appended to the `modal-` class, i.e. a value of `sm` gives `modal-sm`
+* `openedClass` - class added to the `body` element when the modal is opened. Defaults to `modal-open`
+
+Global defaults may be set for `$uibModal` via `$uibModalProvider.options`.
+
+The `open` method returns a modal instance, an object with the following properties:
+
+* `close(result)` - a method that can be used to close a modal, passing a result
+* `dismiss(reason)` - a method that can be used to dismiss a modal, passing a reason
+* `result` - a promise that is resolved when a modal is closed and rejected when a modal is dismissed
+* `opened` - a promise that is resolved when a modal gets opened after downloading content's template and resolving all variables
+* `rendered` - a promise that is resolved when a modal is rendered.
+
+In addition the scope associated with modal's content is augmented with 2 methods:
+
+* `$close(result)`
+* `$dismiss(reason)`
+
+Those methods make it easy to close a modal window without a need to create a dedicated controller.
+
+If the $scope is destroyed via unexpected mechanism, such as it being passed in the modal options and a $route/$state transition occurs, the modal will be dismissed with the value `$uibUnscheduledDestruction`.
+
+Finally, a `modal.closing` event is broadcast to the modal scope before the modal closes. If the listener calls
+preventDefault on the event, then the modal will remain open. The $close and $dismiss methods return true if the
+event was allowed. The event itself includes a parameter for the result/reason and a boolean parameter that indicates
+whether the modal is being closed (true) or dismissed.
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/modal.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/modal.js
new file mode 100644
index 0000000..93d07cf
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/modal.js
@@ -0,0 +1,933 @@
+angular.module('ui.bootstrap.modal', ['ui.bootstrap.stackedMap'])
+/**
+ * A helper, internal data structure that stores all references attached to key
+ */
+ .factory('$$multiMap', function() {
+ return {
+ createNew: function() {
+ var map = {};
+
+ return {
+ entries: function() {
+ return Object.keys(map).map(function(key) {
+ return {
+ key: key,
+ value: map[key]
+ };
+ });
+ },
+ get: function(key) {
+ return map[key];
+ },
+ hasKey: function(key) {
+ return !!map[key];
+ },
+ keys: function() {
+ return Object.keys(map);
+ },
+ put: function(key, value) {
+ if (!map[key]) {
+ map[key] = [];
+ }
+
+ map[key].push(value);
+ },
+ remove: function(key, value) {
+ var values = map[key];
+
+ if (!values) {
+ return;
+ }
+
+ var idx = values.indexOf(value);
+
+ if (idx !== -1) {
+ values.splice(idx, 1);
+ }
+
+ if (!values.length) {
+ delete map[key];
+ }
+ }
+ };
+ }
+ };
+ })
+
+/**
+ * A helper directive for the $modal service. It creates a backdrop element.
+ */
+ .directive('uibModalBackdrop', [
+ '$animate', '$injector', '$uibModalStack',
+ function($animate , $injector, $modalStack) {
+ var $animateCss = null;
+
+ if ($injector.has('$animateCss')) {
+ $animateCss = $injector.get('$animateCss');
+ }
+
+ return {
+ replace: true,
+ templateUrl: 'template/modal/backdrop.html',
+ compile: function(tElement, tAttrs) {
+ tElement.addClass(tAttrs.backdropClass);
+ return linkFn;
+ }
+ };
+
+ function linkFn(scope, element, attrs) {
+ // Temporary fix for prefixing
+ element.addClass('modal-backdrop');
+
+ if (attrs.modalInClass) {
+ if ($animateCss) {
+ $animateCss(element, {
+ addClass: attrs.modalInClass
+ }).start();
+ } else {
+ $animate.addClass(element, attrs.modalInClass);
+ }
+
+ scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) {
+ var done = setIsAsync();
+ if ($animateCss) {
+ $animateCss(element, {
+ removeClass: attrs.modalInClass
+ }).start().then(done);
+ } else {
+ $animate.removeClass(element, attrs.modalInClass).then(done);
+ }
+ });
+ }
+ }
+ }])
+
+ .directive('uibModalWindow', [
+ '$uibModalStack', '$q', '$animate', '$injector',
+ function($modalStack , $q , $animate, $injector) {
+ var $animateCss = null;
+
+ if ($injector.has('$animateCss')) {
+ $animateCss = $injector.get('$animateCss');
+ }
+
+ return {
+ scope: {
+ index: '@'
+ },
+ replace: true,
+ transclude: true,
+ templateUrl: function(tElement, tAttrs) {
+ return tAttrs.templateUrl || 'template/modal/window.html';
+ },
+ link: function(scope, element, attrs) {
+ element.addClass(attrs.windowClass || '');
+ element.addClass(attrs.windowTopClass || '');
+ scope.size = attrs.size;
+
+ scope.close = function(evt) {
+ var modal = $modalStack.getTop();
+ if (modal && modal.value.backdrop && modal.value.backdrop !== 'static' && (evt.target === evt.currentTarget)) {
+ evt.preventDefault();
+ evt.stopPropagation();
+ $modalStack.dismiss(modal.key, 'backdrop click');
+ }
+ };
+
+ // moved from template to fix issue #2280
+ element.on('click', scope.close);
+
+ // This property is only added to the scope for the purpose of detecting when this directive is rendered.
+ // We can detect that by using this property in the template associated with this directive and then use
+ // {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}.
+ scope.$isRendered = true;
+
+ // Deferred object that will be resolved when this modal is render.
+ var modalRenderDeferObj = $q.defer();
+ // Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready.
+ // In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template.
+ attrs.$observe('modalRender', function(value) {
+ if (value == 'true') {
+ modalRenderDeferObj.resolve();
+ }
+ });
+
+ modalRenderDeferObj.promise.then(function() {
+ var animationPromise = null;
+
+ if (attrs.modalInClass) {
+ if ($animateCss) {
+ animationPromise = $animateCss(element, {
+ addClass: attrs.modalInClass
+ }).start();
+ } else {
+ animationPromise = $animate.addClass(element, attrs.modalInClass);
+ }
+
+ scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) {
+ var done = setIsAsync();
+ if ($animateCss) {
+ $animateCss(element, {
+ removeClass: attrs.modalInClass
+ }).start().then(done);
+ } else {
+ $animate.removeClass(element, attrs.modalInClass).then(done);
+ }
+ });
+ }
+
+
+ $q.when(animationPromise).then(function() {
+ var inputWithAutofocus = element[0].querySelector('[autofocus]');
+ /**
+ * Auto-focusing of a freshly-opened modal element causes any child elements
+ * with the autofocus attribute to lose focus. This is an issue on touch
+ * based devices which will show and then hide the onscreen keyboard.
+ * Attempts to refocus the autofocus element via JavaScript will not reopen
+ * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus
+ * the modal element if the modal does not contain an autofocus element.
+ */
+ if (inputWithAutofocus) {
+ inputWithAutofocus.focus();
+ } else {
+ element[0].focus();
+ }
+ });
+
+ // Notify {@link $modalStack} that modal is rendered.
+ var modal = $modalStack.getTop();
+ if (modal) {
+ $modalStack.modalRendered(modal.key);
+ }
+ });
+ }
+ };
+ }])
+
+ .directive('uibModalAnimationClass', function() {
+ return {
+ compile: function(tElement, tAttrs) {
+ if (tAttrs.modalAnimation) {
+ tElement.addClass(tAttrs.uibModalAnimationClass);
+ }
+ }
+ };
+ })
+
+ .directive('uibModalTransclude', function() {
+ return {
+ link: function($scope, $element, $attrs, controller, $transclude) {
+ $transclude($scope.$parent, function(clone) {
+ $element.empty();
+ $element.append(clone);
+ });
+ }
+ };
+ })
+
+ .factory('$uibModalStack', [
+ '$animate', '$timeout', '$document', '$compile', '$rootScope',
+ '$q',
+ '$injector',
+ '$$multiMap',
+ '$$stackedMap',
+ function($animate , $timeout , $document , $compile , $rootScope ,
+ $q,
+ $injector,
+ $$multiMap,
+ $$stackedMap) {
+ var $animateCss = null;
+
+ if ($injector.has('$animateCss')) {
+ $animateCss = $injector.get('$animateCss');
+ }
+
+ var OPENED_MODAL_CLASS = 'modal-open';
+
+ var backdropDomEl, backdropScope;
+ var openedWindows = $$stackedMap.createNew();
+ var openedClasses = $$multiMap.createNew();
+ var $modalStack = {
+ NOW_CLOSING_EVENT: 'modal.stack.now-closing'
+ };
+
+ //Modal focus behavior
+ var focusableElementList;
+ var focusIndex = 0;
+ var tababbleSelector = 'a[href], area[href], input:not([disabled]), ' +
+ 'button:not([disabled]),select:not([disabled]), textarea:not([disabled]), ' +
+ 'iframe, object, embed, *[tabindex], *[contenteditable=true]';
+
+ function backdropIndex() {
+ var topBackdropIndex = -1;
+ var opened = openedWindows.keys();
+ for (var i = 0; i < opened.length; i++) {
+ if (openedWindows.get(opened[i]).value.backdrop) {
+ topBackdropIndex = i;
+ }
+ }
+ return topBackdropIndex;
+ }
+
+ $rootScope.$watch(backdropIndex, function(newBackdropIndex) {
+ if (backdropScope) {
+ backdropScope.index = newBackdropIndex;
+ }
+ });
+
+ function removeModalWindow(modalInstance, elementToReceiveFocus) {
+ var body = $document.find('body').eq(0);
+ var modalWindow = openedWindows.get(modalInstance).value;
+
+ //clean up the stack
+ openedWindows.remove(modalInstance);
+
+ removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, function() {
+ var modalBodyClass = modalWindow.openedClass || OPENED_MODAL_CLASS;
+ openedClasses.remove(modalBodyClass, modalInstance);
+ body.toggleClass(modalBodyClass, openedClasses.hasKey(modalBodyClass));
+ toggleTopWindowClass(true);
+ });
+ checkRemoveBackdrop();
+
+ //move focus to specified element if available, or else to body
+ if (elementToReceiveFocus && elementToReceiveFocus.focus) {
+ elementToReceiveFocus.focus();
+ } else {
+ body.focus();
+ }
+ }
+
+ // Add or remove "windowTopClass" from the top window in the stack
+ function toggleTopWindowClass(toggleSwitch) {
+ var modalWindow;
+
+ if (openedWindows.length() > 0) {
+ modalWindow = openedWindows.top().value;
+ modalWindow.modalDomEl.toggleClass(modalWindow.windowTopClass || '', toggleSwitch);
+ }
+ }
+
+ function checkRemoveBackdrop() {
+ //remove backdrop if no longer needed
+ if (backdropDomEl && backdropIndex() == -1) {
+ var backdropScopeRef = backdropScope;
+ removeAfterAnimate(backdropDomEl, backdropScope, function() {
+ backdropScopeRef = null;
+ });
+ backdropDomEl = undefined;
+ backdropScope = undefined;
+ }
+ }
+
+ function removeAfterAnimate(domEl, scope, done) {
+ var asyncDeferred;
+ var asyncPromise = null;
+ var setIsAsync = function() {
+ if (!asyncDeferred) {
+ asyncDeferred = $q.defer();
+ asyncPromise = asyncDeferred.promise;
+ }
+
+ return function asyncDone() {
+ asyncDeferred.resolve();
+ };
+ };
+ scope.$broadcast($modalStack.NOW_CLOSING_EVENT, setIsAsync);
+
+ // Note that it's intentional that asyncPromise might be null.
+ // That's when setIsAsync has not been called during the
+ // NOW_CLOSING_EVENT broadcast.
+ return $q.when(asyncPromise).then(afterAnimating);
+
+ function afterAnimating() {
+ if (afterAnimating.done) {
+ return;
+ }
+ afterAnimating.done = true;
+
+ if ($animateCss) {
+ $animateCss(domEl, {
+ event: 'leave'
+ }).start().then(function() {
+ domEl.remove();
+ });
+ } else {
+ $animate.leave(domEl);
+ }
+ scope.$destroy();
+ if (done) {
+ done();
+ }
+ }
+ }
+
+ $document.bind('keydown', function(evt) {
+ if (evt.isDefaultPrevented()) {
+ return evt;
+ }
+
+ var modal = openedWindows.top();
+ if (modal && modal.value.keyboard) {
+ switch (evt.which) {
+ case 27: {
+ evt.preventDefault();
+ $rootScope.$apply(function() {
+ $modalStack.dismiss(modal.key, 'escape key press');
+ });
+ break;
+ }
+ case 9: {
+ $modalStack.loadFocusElementList(modal);
+ var focusChanged = false;
+ if (evt.shiftKey) {
+ if ($modalStack.isFocusInFirstItem(evt)) {
+ focusChanged = $modalStack.focusLastFocusableElement();
+ }
+ } else {
+ if ($modalStack.isFocusInLastItem(evt)) {
+ focusChanged = $modalStack.focusFirstFocusableElement();
+ }
+ }
+
+ if (focusChanged) {
+ evt.preventDefault();
+ evt.stopPropagation();
+ }
+ break;
+ }
+ }
+ }
+ });
+
+ $modalStack.open = function(modalInstance, modal) {
+ var modalOpener = $document[0].activeElement,
+ modalBodyClass = modal.openedClass || OPENED_MODAL_CLASS;
+
+ toggleTopWindowClass(false);
+
+ openedWindows.add(modalInstance, {
+ deferred: modal.deferred,
+ renderDeferred: modal.renderDeferred,
+ modalScope: modal.scope,
+ backdrop: modal.backdrop,
+ keyboard: modal.keyboard,
+ openedClass: modal.openedClass,
+ windowTopClass: modal.windowTopClass
+ });
+
+ openedClasses.put(modalBodyClass, modalInstance);
+
+ var body = $document.find('body').eq(0),
+ currBackdropIndex = backdropIndex();
+
+ if (currBackdropIndex >= 0 && !backdropDomEl) {
+ backdropScope = $rootScope.$new(true);
+ backdropScope.index = currBackdropIndex;
+ var angularBackgroundDomEl = angular.element('<div uib-modal-backdrop="modal-backdrop"></div>');
+ angularBackgroundDomEl.attr('backdrop-class', modal.backdropClass);
+ if (modal.animation) {
+ angularBackgroundDomEl.attr('modal-animation', 'true');
+ }
+ backdropDomEl = $compile(angularBackgroundDomEl)(backdropScope);
+ body.append(backdropDomEl);
+ }
+
+ var angularDomEl = angular.element('<div uib-modal-window="modal-window"></div>');
+ angularDomEl.attr({
+ 'template-url': modal.windowTemplateUrl,
+ 'window-class': modal.windowClass,
+ 'window-top-class': modal.windowTopClass,
+ 'size': modal.size,
+ 'index': openedWindows.length() - 1,
+ 'animate': 'animate'
+ }).html(modal.content);
+ if (modal.animation) {
+ angularDomEl.attr('modal-animation', 'true');
+ }
+
+ var modalDomEl = $compile(angularDomEl)(modal.scope);
+ openedWindows.top().value.modalDomEl = modalDomEl;
+ openedWindows.top().value.modalOpener = modalOpener;
+ body.append(modalDomEl);
+ body.addClass(modalBodyClass);
+
+ $modalStack.clearFocusListCache();
+ };
+
+ function broadcastClosing(modalWindow, resultOrReason, closing) {
+ return !modalWindow.value.modalScope.$broadcast('modal.closing', resultOrReason, closing).defaultPrevented;
+ }
+
+ $modalStack.close = function(modalInstance, result) {
+ var modalWindow = openedWindows.get(modalInstance);
+ if (modalWindow && broadcastClosing(modalWindow, result, true)) {
+ modalWindow.value.modalScope.$$uibDestructionScheduled = true;
+ modalWindow.value.deferred.resolve(result);
+ removeModalWindow(modalInstance, modalWindow.value.modalOpener);
+ return true;
+ }
+ return !modalWindow;
+ };
+
+ $modalStack.dismiss = function(modalInstance, reason) {
+ var modalWindow = openedWindows.get(modalInstance);
+ if (modalWindow && broadcastClosing(modalWindow, reason, false)) {
+ modalWindow.value.modalScope.$$uibDestructionScheduled = true;
+ modalWindow.value.deferred.reject(reason);
+ removeModalWindow(modalInstance, modalWindow.value.modalOpener);
+ return true;
+ }
+ return !modalWindow;
+ };
+
+ $modalStack.dismissAll = function(reason) {
+ var topModal = this.getTop();
+ while (topModal && this.dismiss(topModal.key, reason)) {
+ topModal = this.getTop();
+ }
+ };
+
+ $modalStack.getTop = function() {
+ return openedWindows.top();
+ };
+
+ $modalStack.modalRendered = function(modalInstance) {
+ var modalWindow = openedWindows.get(modalInstance);
+ if (modalWindow) {
+ modalWindow.value.renderDeferred.resolve();
+ }
+ };
+
+ $modalStack.focusFirstFocusableElement = function() {
+ if (focusableElementList.length > 0) {
+ focusableElementList[0].focus();
+ return true;
+ }
+ return false;
+ };
+ $modalStack.focusLastFocusableElement = function() {
+ if (focusableElementList.length > 0) {
+ focusableElementList[focusableElementList.length - 1].focus();
+ return true;
+ }
+ return false;
+ };
+
+ $modalStack.isFocusInFirstItem = function(evt) {
+ if (focusableElementList.length > 0) {
+ return (evt.target || evt.srcElement) == focusableElementList[0];
+ }
+ return false;
+ };
+
+ $modalStack.isFocusInLastItem = function(evt) {
+ if (focusableElementList.length > 0) {
+ return (evt.target || evt.srcElement) == focusableElementList[focusableElementList.length - 1];
+ }
+ return false;
+ };
+
+ $modalStack.clearFocusListCache = function() {
+ focusableElementList = [];
+ focusIndex = 0;
+ };
+
+ $modalStack.loadFocusElementList = function(modalWindow) {
+ if (focusableElementList === undefined || !focusableElementList.length) {
+ if (modalWindow) {
+ var modalDomE1 = modalWindow.value.modalDomEl;
+ if (modalDomE1 && modalDomE1.length) {
+ focusableElementList = modalDomE1[0].querySelectorAll(tababbleSelector);
+ }
+ }
+ }
+ };
+
+ return $modalStack;
+ }])
+
+ .provider('$uibModal', function() {
+ var $modalProvider = {
+ options: {
+ animation: true,
+ backdrop: true, //can also be false or 'static'
+ keyboard: true
+ },
+ $get: ['$injector', '$rootScope', '$q', '$templateRequest', '$controller', '$uibModalStack', '$modalSuppressWarning', '$log',
+ function ($injector, $rootScope, $q, $templateRequest, $controller, $modalStack, $modalSuppressWarning, $log) {
+ var $modal = {};
+
+ function getTemplatePromise(options) {
+ return options.template ? $q.when(options.template) :
+ $templateRequest(angular.isFunction(options.templateUrl) ? (options.templateUrl)() : options.templateUrl);
+ }
+
+ function getResolvePromises(resolves) {
+ var promisesArr = [];
+ angular.forEach(resolves, function(value) {
+ if (angular.isFunction(value) || angular.isArray(value)) {
+ promisesArr.push($q.when($injector.invoke(value)));
+ } else if (angular.isString(value)) {
+ promisesArr.push($q.when($injector.get(value)));
+ } else {
+ promisesArr.push($q.when(value));
+ }
+ });
+ return promisesArr;
+ }
+
+ var promiseChain = null;
+ $modal.getPromiseChain = function() {
+ return promiseChain;
+ };
+
+ $modal.open = function(modalOptions) {
+ var modalResultDeferred = $q.defer();
+ var modalOpenedDeferred = $q.defer();
+ var modalRenderDeferred = $q.defer();
+
+ //prepare an instance of a modal to be injected into controllers and returned to a caller
+ var modalInstance = {
+ result: modalResultDeferred.promise,
+ opened: modalOpenedDeferred.promise,
+ rendered: modalRenderDeferred.promise,
+ close: function (result) {
+ return $modalStack.close(modalInstance, result);
+ },
+ dismiss: function (reason) {
+ return $modalStack.dismiss(modalInstance, reason);
+ }
+ };
+
+ //merge and clean up options
+ modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
+ modalOptions.resolve = modalOptions.resolve || {};
+
+ //verify options
+ if (!modalOptions.template && !modalOptions.templateUrl) {
+ throw new Error('One of template or templateUrl options is required.');
+ }
+
+ var templateAndResolvePromise =
+ $q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));
+
+ function resolveWithTemplate() {
+ return templateAndResolvePromise;
+ }
+
+ // Wait for the resolution of the existing promise chain.
+ // Then switch to our own combined promise dependency (regardless of how the previous modal fared).
+ // Then add to $modalStack and resolve opened.
+ // Finally clean up the chain variable if no subsequent modal has overwritten it.
+ var samePromise;
+ samePromise = promiseChain = $q.all([promiseChain])
+ .then(resolveWithTemplate, resolveWithTemplate)
+ .then(function resolveSuccess(tplAndVars) {
+
+ var modalScope = (modalOptions.scope || $rootScope).$new();
+ modalScope.$close = modalInstance.close;
+ modalScope.$dismiss = modalInstance.dismiss;
+
+ modalScope.$on('$destroy', function() {
+ if (!modalScope.$$uibDestructionScheduled) {
+ modalScope.$dismiss('$uibUnscheduledDestruction');
+ }
+ });
+
+ var ctrlInstance, ctrlLocals = {};
+ var resolveIter = 1;
+
+ //controllers
+ if (modalOptions.controller) {
+ ctrlLocals.$scope = modalScope;
+ ctrlLocals.$uibModalInstance = modalInstance;
+ Object.defineProperty(ctrlLocals, '$modalInstance', {
+ get: function() {
+ if (!$modalSuppressWarning) {
+ $log.warn('$modalInstance is now deprecated. Use $uibModalInstance instead.');
+ }
+
+ return modalInstance;
+ }
+ });
+ angular.forEach(modalOptions.resolve, function(value, key) {
+ ctrlLocals[key] = tplAndVars[resolveIter++];
+ });
+
+ ctrlInstance = $controller(modalOptions.controller, ctrlLocals);
+ if (modalOptions.controllerAs) {
+ if (modalOptions.bindToController) {
+ angular.extend(ctrlInstance, modalScope);
+ }
+
+ modalScope[modalOptions.controllerAs] = ctrlInstance;
+ }
+ }
+
+ $modalStack.open(modalInstance, {
+ scope: modalScope,
+ deferred: modalResultDeferred,
+ renderDeferred: modalRenderDeferred,
+ content: tplAndVars[0],
+ animation: modalOptions.animation,
+ backdrop: modalOptions.backdrop,
+ keyboard: modalOptions.keyboard,
+ backdropClass: modalOptions.backdropClass,
+ windowTopClass: modalOptions.windowTopClass,
+ windowClass: modalOptions.windowClass,
+ windowTemplateUrl: modalOptions.windowTemplateUrl,
+ size: modalOptions.size,
+ openedClass: modalOptions.openedClass
+ });
+ modalOpenedDeferred.resolve(true);
+
+ }, function resolveError(reason) {
+ modalOpenedDeferred.reject(reason);
+ modalResultDeferred.reject(reason);
+ })
+ .finally(function() {
+ if (promiseChain === samePromise) {
+ promiseChain = null;
+ }
+ });
+
+ return modalInstance;
+ };
+
+ return $modal;
+ }
+ ]
+ };
+
+ return $modalProvider;
+ });
+
+/* deprecated modal below */
+
+angular.module('ui.bootstrap.modal')
+
+ .value('$modalSuppressWarning', false)
+
+ /**
+ * A helper directive for the $modal service. It creates a backdrop element.
+ */
+ .directive('modalBackdrop', [
+ '$animate', '$injector', '$modalStack', '$log', '$modalSuppressWarning',
+ function($animate , $injector, $modalStack, $log, $modalSuppressWarning) {
+ var $animateCss = null;
+
+ if ($injector.has('$animateCss')) {
+ $animateCss = $injector.get('$animateCss');
+ }
+
+ return {
+ replace: true,
+ templateUrl: 'template/modal/backdrop.html',
+ compile: function(tElement, tAttrs) {
+ tElement.addClass(tAttrs.backdropClass);
+ return linkFn;
+ }
+ };
+
+ function linkFn(scope, element, attrs) {
+ if (!$modalSuppressWarning) {
+ $log.warn('modal-backdrop is now deprecated. Use uib-modal-backdrop instead.');
+ }
+ element.addClass('modal-backdrop');
+
+ if (attrs.modalInClass) {
+ if ($animateCss) {
+ $animateCss(element, {
+ addClass: attrs.modalInClass
+ }).start();
+ } else {
+ $animate.addClass(element, attrs.modalInClass);
+ }
+
+ scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) {
+ var done = setIsAsync();
+ if ($animateCss) {
+ $animateCss(element, {
+ removeClass: attrs.modalInClass
+ }).start().then(done);
+ } else {
+ $animate.removeClass(element, attrs.modalInClass).then(done);
+ }
+ });
+ }
+ }
+ }])
+
+ .directive('modalWindow', [
+ '$modalStack', '$q', '$animate', '$injector', '$log', '$modalSuppressWarning',
+ function($modalStack , $q , $animate, $injector, $log, $modalSuppressWarning) {
+ var $animateCss = null;
+
+ if ($injector.has('$animateCss')) {
+ $animateCss = $injector.get('$animateCss');
+ }
+
+ return {
+ scope: {
+ index: '@'
+ },
+ replace: true,
+ transclude: true,
+ templateUrl: function(tElement, tAttrs) {
+ return tAttrs.templateUrl || 'template/modal/window.html';
+ },
+ link: function(scope, element, attrs) {
+ if (!$modalSuppressWarning) {
+ $log.warn('modal-window is now deprecated. Use uib-modal-window instead.');
+ }
+ element.addClass(attrs.windowClass || '');
+ element.addClass(attrs.windowTopClass || '');
+ scope.size = attrs.size;
+
+ scope.close = function(evt) {
+ var modal = $modalStack.getTop();
+ if (modal && modal.value.backdrop && modal.value.backdrop !== 'static' && (evt.target === evt.currentTarget)) {
+ evt.preventDefault();
+ evt.stopPropagation();
+ $modalStack.dismiss(modal.key, 'backdrop click');
+ }
+ };
+
+ // moved from template to fix issue #2280
+ element.on('click', scope.close);
+
+ // This property is only added to the scope for the purpose of detecting when this directive is rendered.
+ // We can detect that by using this property in the template associated with this directive and then use
+ // {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}.
+ scope.$isRendered = true;
+
+ // Deferred object that will be resolved when this modal is render.
+ var modalRenderDeferObj = $q.defer();
+ // Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready.
+ // In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template.
+ attrs.$observe('modalRender', function(value) {
+ if (value == 'true') {
+ modalRenderDeferObj.resolve();
+ }
+ });
+
+ modalRenderDeferObj.promise.then(function() {
+ var animationPromise = null;
+
+ if (attrs.modalInClass) {
+ if ($animateCss) {
+ animationPromise = $animateCss(element, {
+ addClass: attrs.modalInClass
+ }).start();
+ } else {
+ animationPromise = $animate.addClass(element, attrs.modalInClass);
+ }
+
+ scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) {
+ var done = setIsAsync();
+ if ($animateCss) {
+ $animateCss(element, {
+ removeClass: attrs.modalInClass
+ }).start().then(done);
+ } else {
+ $animate.removeClass(element, attrs.modalInClass).then(done);
+ }
+ });
+ }
+
+
+ $q.when(animationPromise).then(function() {
+ var inputWithAutofocus = element[0].querySelector('[autofocus]');
+ /**
+ * Auto-focusing of a freshly-opened modal element causes any child elements
+ * with the autofocus attribute to lose focus. This is an issue on touch
+ * based devices which will show and then hide the onscreen keyboard.
+ * Attempts to refocus the autofocus element via JavaScript will not reopen
+ * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus
+ * the modal element if the modal does not contain an autofocus element.
+ */
+ if (inputWithAutofocus) {
+ inputWithAutofocus.focus();
+ } else {
+ element[0].focus();
+ }
+ });
+
+ // Notify {@link $modalStack} that modal is rendered.
+ var modal = $modalStack.getTop();
+ if (modal) {
+ $modalStack.modalRendered(modal.key);
+ }
+ });
+ }
+ };
+ }])
+
+ .directive('modalAnimationClass', [
+ '$log', '$modalSuppressWarning',
+ function ($log, $modalSuppressWarning) {
+ return {
+ compile: function(tElement, tAttrs) {
+ if (!$modalSuppressWarning) {
+ $log.warn('modal-animation-class is now deprecated. Use uib-modal-animation-class instead.');
+ }
+ if (tAttrs.modalAnimation) {
+ tElement.addClass(tAttrs.modalAnimationClass);
+ }
+ }
+ };
+ }])
+
+ .directive('modalTransclude', [
+ '$log', '$modalSuppressWarning',
+ function ($log, $modalSuppressWarning) {
+ return {
+ link: function($scope, $element, $attrs, controller, $transclude) {
+ if (!$modalSuppressWarning) {
+ $log.warn('modal-transclude is now deprecated. Use uib-modal-transclude instead.');
+ }
+ $transclude($scope.$parent, function(clone) {
+ $element.empty();
+ $element.append(clone);
+ });
+ }
+ };
+ }])
+
+ .service('$modalStack', [
+ '$animate', '$timeout', '$document', '$compile', '$rootScope',
+ '$q',
+ '$injector',
+ '$$multiMap',
+ '$$stackedMap',
+ '$uibModalStack',
+ '$log',
+ '$modalSuppressWarning',
+ function($animate , $timeout , $document , $compile , $rootScope ,
+ $q,
+ $injector,
+ $$multiMap,
+ $$stackedMap,
+ $uibModalStack,
+ $log,
+ $modalSuppressWarning) {
+ if (!$modalSuppressWarning) {
+ $log.warn('$modalStack is now deprecated. Use $uibModalStack instead.');
+ }
+
+ angular.extend(this, $uibModalStack);
+ }])
+
+ .provider('$modal', ['$uibModalProvider', function($uibModalProvider) {
+ angular.extend(this, $uibModalProvider);
+
+ this.$get = ['$injector', '$log', '$modalSuppressWarning',
+ function ($injector, $log, $modalSuppressWarning) {
+ if (!$modalSuppressWarning) {
+ $log.warn('$modal is now deprecated. Use $uibModal instead.');
+ }
+
+ return $injector.invoke($uibModalProvider.$get);
+ }];
+ }]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/test/modal.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/test/modal.spec.js
new file mode 100644
index 0000000..a427584
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/test/modal.spec.js
@@ -0,0 +1,1255 @@
+describe('$uibModal', function () {
+ var $animate, $controllerProvider, $rootScope, $document, $compile, $templateCache, $timeout, $q;
+ var $uibModal, $uibModalStack, $uibModalProvider;
+
+ beforeEach(module('ngAnimateMock'));
+ beforeEach(module('ui.bootstrap.modal'));
+ beforeEach(module('template/modal/backdrop.html'));
+ beforeEach(module('template/modal/window.html'));
+ beforeEach(module(function(_$controllerProvider_, _$uibModalProvider_){
+ $controllerProvider = _$controllerProvider_;
+ $uibModalProvider = _$uibModalProvider_;
+ }));
+
+ beforeEach(inject(function(_$animate_, _$rootScope_, _$document_, _$compile_, _$templateCache_, _$timeout_, _$q_, _$uibModal_, _$uibModalStack_) {
+ $animate = _$animate_;
+ $rootScope = _$rootScope_;
+ $document = _$document_;
+ $compile = _$compile_;
+ $templateCache = _$templateCache_;
+ $timeout = _$timeout_;
+ $q = _$q_;
+ $uibModal = _$uibModal_;
+ $uibModalStack = _$uibModalStack_;
+ }));
+
+ beforeEach(function() {
+ jasmine.addMatchers({
+ toBeResolvedWith: function(util, customEqualityTesters) {
+ return {
+ compare: function(promise, expected) {
+ promise.then(function(result) {
+ expect(result).toEqual(expected);
+
+ if (result === expected) {
+ result.message = 'Expected "' + angular.mock.dump(result) + '" not to be resolved with "' + expected + '".';
+ } else {
+ result.message = 'Expected "' + angular.mock.dump(result) + '" to be resolved with "' + expected + '".';
+ }
+ });
+
+ $rootScope.$digest();
+
+ return {pass: true};
+ }
+ };
+ },
+ toBeRejectedWith: function(util, customEqualityTesters) {
+ return {
+ compare: function(promise, expected) {
+ var result = {};
+
+ promise.then(function() {
+
+ }, function(result) {
+ expect(result).toEqual(expected);
+
+ if (result === expected) {
+ result.message = 'Expected "' + angular.mock.dump(result) + '" not to be rejected with "' + expected + '".';
+ } else {
+ result.message = 'Expected "' + angular.mock.dump(result) + '" to be rejected with "' + expected + '".';
+ }
+ });
+
+ $rootScope.$digest();
+
+ return {pass: true};
+ }
+ };
+ },
+ toHaveModalOpenWithContent: function(util, customEqualityTesters) {
+ return {
+ compare: function(actual, content, selector) {
+ var contentToCompare, modalDomEls = actual.find('body > div.modal > div.modal-dialog > div.modal-content');
+
+ contentToCompare = selector ? modalDomEls.find(selector) : modalDomEls;
+
+ var result = {
+ pass: modalDomEls.css('display') === 'block' && contentToCompare.html() === content
+ };
+
+ if (result.pass) {
+ result.message = '"Expected "' + angular.mock.dump(modalDomEls) + '" not to be open with "' + content + '".';
+ } else {
+ result.message = '"Expected "' + angular.mock.dump(modalDomEls) + '" to be open with "' + content + '".';
+ }
+
+ return result;
+ }
+ };
+ },
+ toHaveModalsOpen: function(util, customEqualityTesters) {
+ return {
+ compare: function(actual, expected) {
+ var modalDomEls = actual.find('body > div.modal');
+
+ var result = {
+ pass: util.equals(modalDomEls.length, expected, customEqualityTesters)
+ };
+
+ if (result.pass) {
+ result.message = 'Expected "' + angular.mock.dump(modalDomEls) + '" not to have "' + expected + '" modals opened.';
+ } else {
+ result.message = 'Expected "' + angular.mock.dump(modalDomEls) + '" to have "' + expected + '" modals opened.';
+ }
+
+ return result;
+ }
+ };
+ },
+ toHaveBackdrop: function(util, customEqualityTesters) {
+ return {
+ compare: function(actual, expected) {
+ var backdropDomEls = actual.find('body > div.modal-backdrop');
+
+ var result = {
+ pass: util.equals(backdropDomEls.length, 1, customEqualityTesters)
+ };
+
+ if (result.pass) {
+ result.message = 'Expected "' + angular.mock.dump(backdropDomEls) + '" not to be a backdrop element".';
+ } else {
+ result.message = 'Expected "' + angular.mock.dump(backdropDomEls) + '" to be a backdrop element".';
+ }
+
+ return result;
+ }
+ };
+ }
+ });
+ });
+
+ afterEach(function () {
+ var body = $document.find('body');
+ body.find('div.modal').remove();
+ body.find('div.modal-backdrop').remove();
+ body.removeClass('modal-open');
+ });
+
+ function triggerKeyDown(element, keyCode, shiftKey) {
+ var e = $.Event('keydown');
+ e.srcElement = element[0];
+ e.which = keyCode;
+ e.shiftKey = shiftKey;
+ element.trigger(e);
+ }
+
+ function open(modalOptions) {
+ var modal = $uibModal.open(modalOptions);
+ $rootScope.$digest();
+ $timeout.flush(0);
+ return modal;
+ }
+
+ function close(modal, result, noFlush) {
+ var closed = modal.close(result);
+ $rootScope.$digest();
+ if (!noFlush) {
+ $animate.flush();
+ $rootScope.$digest();
+ $animate.flush();
+ $rootScope.$digest();
+ }
+ return closed;
+ }
+
+ function dismiss(modal, reason, noFlush) {
+ var closed = modal.dismiss(reason);
+ $rootScope.$digest();
+ if (!noFlush) {
+ $animate.flush();
+ $rootScope.$digest();
+ $animate.flush();
+ $rootScope.$digest();
+ }
+ return closed;
+ }
+
+ describe('basic scenarios with default options', function() {
+ it('should open and dismiss a modal with a minimal set of options', function() {
+ var modal = open({template: '<div>Content</div>'});
+
+ expect($document).toHaveModalsOpen(1);
+ expect($document).toHaveModalOpenWithContent('Content', 'div');
+ expect($document).toHaveBackdrop();
+
+ dismiss(modal, 'closing in test');
+
+ expect($document).toHaveModalsOpen(0);
+
+ expect($document).not.toHaveBackdrop();
+ });
+
+ it('should not throw an exception on a second dismiss', function() {
+ var modal = open({template: '<div>Content</div>'});
+
+ expect($document).toHaveModalsOpen(1);
+ expect($document).toHaveModalOpenWithContent('Content', 'div');
+ expect($document).toHaveBackdrop();
+
+ dismiss(modal, 'closing in test');
+
+ expect($document).toHaveModalsOpen(0);
+
+ dismiss(modal, 'closing in test', true);
+ });
+
+ it('should not throw an exception on a second close', function() {
+ var modal = open({template: '<div>Content</div>'});
+
+ expect($document).toHaveModalsOpen(1);
+ expect($document).toHaveModalOpenWithContent('Content', 'div');
+ expect($document).toHaveBackdrop();
+
+ close(modal, 'closing in test');
+
+ expect($document).toHaveModalsOpen(0);
+
+ close(modal, 'closing in test', true);
+ });
+
+ it('should open a modal from templateUrl', function() {
+ $templateCache.put('content.html', '<div>URL Content</div>');
+ var modal = open({templateUrl: 'content.html'});
+
+ expect($document).toHaveModalsOpen(1);
+ expect($document).toHaveModalOpenWithContent('URL Content', 'div');
+ expect($document).toHaveBackdrop();
+
+ dismiss(modal, 'closing in test');
+
+ expect($document).toHaveModalsOpen(0);
+
+ expect($document).not.toHaveBackdrop();
+ });
+
+ it('should support closing on ESC', function() {
+ var modal = open({template: '<div>Content</div>'});
+ expect($document).toHaveModalsOpen(1);
+
+ triggerKeyDown($document, 27);
+ $animate.flush();
+ $rootScope.$digest();
+ $animate.flush();
+ $rootScope.$digest();
+
+ expect($document).toHaveModalsOpen(0);
+ });
+
+ it('should not close on ESC if event.preventDefault() was issued', function() {
+ var modal = open({template: '<div><button>x</button></div>' });
+ expect($document).toHaveModalsOpen(1);
+
+ var button = angular.element('button').on('keydown', preventKeyDown);
+
+ triggerKeyDown(button, 27);
+ $rootScope.$digest();
+
+ expect($document).toHaveModalsOpen(1);
+
+ button.off('keydown', preventKeyDown);
+
+ triggerKeyDown(button, 27);
+ $animate.flush();
+ $rootScope.$digest();
+ $animate.flush();
+ $rootScope.$digest();
+
+ expect($document).toHaveModalsOpen(0);
+
+ function preventKeyDown(evt) {
+ evt.preventDefault();
+ }
+ });
+
+ it('should support closing on backdrop click', function() {
+ var modal = open({template: '<div>Content</div>'});
+ expect($document).toHaveModalsOpen(1);
+
+ $document.find('body > div.modal').click();
+ $animate.flush();
+ $rootScope.$digest();
+ $animate.flush();
+ $rootScope.$digest();
+
+ expect($document).toHaveModalsOpen(0);
+ });
+
+ it('should return to the element which had focus before the dialog was invoked', function() {
+ var link = '<a href>Link</a>';
+ var element = angular.element(link);
+ angular.element(document.body).append(element);
+ element.focus();
+ expect(document.activeElement.tagName).toBe('A');
+
+ var modal = open({template: '<div>Content<button>inside modal</button></div>'});
+ $animate.flush();
+ $rootScope.$digest();
+ expect(document.activeElement.tagName).toBe('DIV');
+ expect($document).toHaveModalsOpen(1);
+
+ triggerKeyDown($document, 27);
+ $animate.flush();
+ $rootScope.$digest();
+ $animate.flush();
+ $rootScope.$digest();
+
+ expect(document.activeElement.tagName).toBe('A');
+ expect($document).toHaveModalsOpen(0);
+
+ element.remove();
+ });
+
+ it('should return to document.body if element which had focus before the dialog was invoked is gone, or is missing focus function', function() {
+ var link = '<a href>Link</a>';
+ var element = angular.element(link);
+ angular.element(document.body).append(element);
+ element.focus();
+ expect(document.activeElement.tagName).toBe('A');
+
+ var modal = open({template: '<div>Content</div>'});
+ $animate.flush();
+ $rootScope.$digest();
+ expect(document.activeElement.tagName).toBe('DIV');
+ expect($document).toHaveModalsOpen(1);
+
+ // Fake undefined focus function, happening in IE in certain
+ // iframe conditions. See issue 3639
+ element[0].focus = undefined;
+ triggerKeyDown($document, 27);
+ $animate.flush();
+ $rootScope.$digest();
+ $animate.flush();
+ $rootScope.$digest();
+
+ expect(document.activeElement.tagName).toBe('BODY');
+ expect($document).toHaveModalsOpen(0);
+ element.remove();
+ });
+
+ it('should resolve returned promise on close', function() {
+ var modal = open({template: '<div>Content</div>'});
+ close(modal, 'closed ok');
+
+ expect(modal.result).toBeResolvedWith('closed ok');
+ });
+
+ it('should reject returned promise on dismiss', function() {
+
+ var modal = open({template: '<div>Content</div>'});
+ dismiss(modal, 'esc');
+
+ expect(modal.result).toBeRejectedWith('esc');
+ });
+
+ it('should reject returned promise on unexpected closure', function() {
+ var scope = $rootScope.$new();
+ var modal = open({template: '<div>Content</div>', scope: scope});
+ scope.$destroy();
+
+ expect(modal.result).toBeRejectedWith('$uibUnscheduledDestruction');
+
+ $animate.flush();
+ $rootScope.$digest();
+ $animate.flush();
+ $rootScope.$digest();
+ expect($document).toHaveModalsOpen(0);
+ });
+
+ it('should expose a promise linked to the templateUrl / resolve promises', function() {
+ var modal = open({template: '<div>Content</div>', resolve: {
+ ok: function() {return $q.when('ok');}
+ }}
+ );
+ expect(modal.opened).toBeResolvedWith(true);
+ });
+
+ it('should expose a promise linked to the templateUrl / resolve promises and reject it if needed', function() {
+ var modal = open({template: '<div>Content</div>', resolve: {
+ ok: function() {return $q.reject('ko');}
+ }}
+ );
+ expect(modal.opened).toBeRejectedWith('ko');
+ });
+
+ it('should focus on the element that has autofocus attribute when the modal is open/reopen and the animations have finished', function() {
+ function openAndCloseModalWithAutofocusElement() {
+ var modal = open({template: '<div><input type="text" id="auto-focus-element" autofocus></div>'});
+ $animate.flush();
+ $rootScope.$digest();
+ expect(angular.element('#auto-focus-element')).toHaveFocus();
+
+ close(modal, 'closed ok');
+
+ expect(modal.result).toBeResolvedWith('closed ok');
+ }
+
+ openAndCloseModalWithAutofocusElement();
+ openAndCloseModalWithAutofocusElement();
+ });
+
+ it('should wait until the in animation is finished before attempting to focus the modal or autofocus element', function() {
+ function openAndCloseModalWithAutofocusElement() {
+ var modal = open({template: '<div><input type="text" id="auto-focus-element" autofocus></div>'});
+ expect(angular.element('#auto-focus-element')).not.toHaveFocus();
+
+ $animate.flush();
+ $rootScope.$digest();
+
+ expect(angular.element('#auto-focus-element')).toHaveFocus();
+
+ close(modal, 'closed ok');
+
+ expect(modal.result).toBeResolvedWith('closed ok');
+ }
+
+ function openAndCloseModalWithOutAutofocusElement() {
+ var link = '<a href>Link</a>';
+ var element = angular.element(link);
+ angular.element(document.body).append(element);
+ element.focus();
+ expect(document.activeElement.tagName).toBe('A');
+
+ var modal = open({template: '<div><input type="text"></div>'});
+ expect(document.activeElement.tagName).toBe('A');
+
+ $animate.flush();
+ $rootScope.$digest();
+
+ expect(document.activeElement.tagName).toBe('DIV');
+
+ close(modal, 'closed ok');
+
+ expect(modal.result).toBeResolvedWith('closed ok');
+ }
+
+ openAndCloseModalWithAutofocusElement();
+ openAndCloseModalWithOutAutofocusElement();
+ });
+
+ it('should change focus to first element when tab key was pressed', function() {
+ var initialPage = angular.element('<a href="#" id="cannot-get-focus-from-modal">Outland link</a>');
+ angular.element(document.body).append(initialPage);
+ initialPage.focus();
+
+ open({
+ template:'<a href="#" id="tab-focus-link"><input type="text" id="tab-focus-input1"/><input type="text" id="tab-focus-input2"/>' +
+ '<button id="tab-focus-button">Open me!</button>'
+ });
+ expect($document).toHaveModalsOpen(1);
+
+ var lastElement = angular.element(document.getElementById('tab-focus-button'));
+ lastElement.focus();
+ triggerKeyDown(lastElement, 9);
+ expect(document.activeElement.getAttribute('id')).toBe('tab-focus-link');
+
+ initialPage.remove();
+ });
+
+ it('should change focus to last element when shift+tab key is pressed', function() {
+ var initialPage = angular.element('<a href="#" id="cannot-get-focus-from-modal">Outland link</a>');
+ angular.element(document.body).append(initialPage);
+ initialPage.focus();
+
+ open({
+ template:'<a href="#" id="tab-focus-link"><input type="text" id="tab-focus-input1"/><input type="text" id="tab-focus-input2"/>' +
+ '<button id="tab-focus-button">Open me!</button>'
+ });
+ expect($document).toHaveModalsOpen(1);
+
+ var lastElement = angular.element(document.getElementById('tab-focus-link'));
+ lastElement.focus();
+ triggerKeyDown(lastElement, 9, true);
+ expect(document.activeElement.getAttribute('id')).toBe('tab-focus-button');
+
+ initialPage.remove();
+ });
+ });
+
+ describe('default options can be changed in a provider', function() {
+ it('should allow overriding default options in a provider', function() {
+ $uibModalProvider.options.backdrop = false;
+ var modal = open({template: '<div>Content</div>'});
+
+ expect($document).toHaveModalOpenWithContent('Content', 'div');
+ expect($document).not.toHaveBackdrop();
+ });
+
+ it('should accept new objects with default options in a provider', function() {
+ $uibModalProvider.options = {
+ backdrop: false
+ };
+ var modal = open({template: '<div>Content</div>'});
+
+ expect($document).toHaveModalOpenWithContent('Content', 'div');
+ expect($document).not.toHaveBackdrop();
+ });
+ });
+
+ describe('option by option', function () {
+ describe('template and templateUrl', function () {
+ it('should throw an error if none of template and templateUrl are provided', function() {
+ expect(function(){
+ var modal = open({});
+ }).toThrow(new Error('One of template or templateUrl options is required.'));
+ });
+
+ it('should not fail if a templateUrl contains leading / trailing white spaces', function() {
+
+ $templateCache.put('whitespace.html', ' <div>Whitespaces</div> ');
+ open({templateUrl: 'whitespace.html'});
+ expect($document).toHaveModalOpenWithContent('Whitespaces', 'div');
+ });
+
+ it('should accept template as a function', function() {
+ open({template: function() {
+ return '<div>From a function</div>';
+ }});
+
+ expect($document).toHaveModalOpenWithContent('From a function', 'div');
+ });
+
+ it('should not fail if a templateUrl as a function', function() {
+
+ $templateCache.put('whitespace.html', ' <div>Whitespaces</div> ');
+ open({templateUrl: function() {
+ return 'whitespace.html';
+ }});
+ expect($document).toHaveModalOpenWithContent('Whitespaces', 'div');
+ });
+ });
+
+ describe('controller', function() {
+ it('should accept controllers and inject modal instances', function() {
+ var TestCtrl = function($scope, $uibModalInstance) {
+ $scope.fromCtrl = 'Content from ctrl';
+ $scope.isModalInstance = angular.isObject($uibModalInstance) && angular.isFunction($uibModalInstance.close);
+ };
+
+ open({template: '<div>{{fromCtrl}} {{isModalInstance}}</div>', controller: TestCtrl});
+ expect($document).toHaveModalOpenWithContent('Content from ctrl true', 'div');
+ });
+
+ it('should accept controllerAs alias', function() {
+ $controllerProvider.register('TestCtrl', function($uibModalInstance) {
+ this.fromCtrl = 'Content from ctrl';
+ this.isModalInstance = angular.isObject($uibModalInstance) && angular.isFunction($uibModalInstance.close);
+ });
+
+ open({template: '<div>{{test.fromCtrl}} {{test.isModalInstance}}</div>', controller: 'TestCtrl as test'});
+ expect($document).toHaveModalOpenWithContent('Content from ctrl true', 'div');
+ });
+
+ it('should respect the controllerAs property as an alternative for the controller-as syntax', function() {
+ $controllerProvider.register('TestCtrl', function($uibModalInstance) {
+ this.fromCtrl = 'Content from ctrl';
+ this.isModalInstance = angular.isObject($uibModalInstance) && angular.isFunction($uibModalInstance.close);
+ });
+
+ open({template: '<div>{{test.fromCtrl}} {{test.isModalInstance}}</div>', controller: 'TestCtrl', controllerAs: 'test'});
+ expect($document).toHaveModalOpenWithContent('Content from ctrl true', 'div');
+ });
+
+ it('should allow defining in-place controller-as controllers', function() {
+ open({template: '<div>{{test.fromCtrl}} {{test.isModalInstance}}</div>', controller: function($uibModalInstance) {
+ this.fromCtrl = 'Content from ctrl';
+ this.isModalInstance = angular.isObject($uibModalInstance) && angular.isFunction($uibModalInstance.close);
+ }, controllerAs: 'test'});
+ expect($document).toHaveModalOpenWithContent('Content from ctrl true', 'div');
+ });
+
+ it('should allow usage of bindToController', function() {
+ open({template: '<div>{{test.fromCtrl}} {{test.isModalInstance}}</div>', controller: function($uibModalInstance) {
+ this.fromCtrl = 'Content from ctrl';
+ this.isModalInstance = angular.isObject($uibModalInstance) && angular.isFunction($uibModalInstance.close);
+ }, controllerAs: 'test', bindToController: true});
+ expect($document).toHaveModalOpenWithContent('Content from ctrl true', 'div');
+ });
+ });
+
+ describe('resolve', function() {
+ var ExposeCtrl = function($scope, value) {
+ $scope.value = value;
+ };
+
+ function modalDefinition(template, resolve) {
+ return {
+ template: template,
+ controller: ExposeCtrl,
+ resolve: resolve
+ };
+ }
+
+ it('should resolve simple values', function() {
+ open(modalDefinition('<div>{{value}}</div>', {
+ value: function() {
+ return 'Content from resolve';
+ }
+ }));
+
+ expect($document).toHaveModalOpenWithContent('Content from resolve', 'div');
+ });
+
+ it('should resolve string references to injectables', function() {
+ open({
+ controller: function($scope, $foo) {
+ $scope.value = 'Content from resolve';
+ expect($foo).toBe($uibModal);
+ },
+ resolve: {
+ $foo: '$uibModal'
+ },
+ template: '<div>{{value}}</div>'
+ });
+
+ expect($document).toHaveModalOpenWithContent('Content from resolve', 'div');
+ });
+
+ it('should resolve promises as promises', function() {
+ open({
+ controller: function($scope, $foo) {
+ $scope.value = 'Content from resolve';
+ expect($foo).toBe('bar');
+ },
+ resolve: {
+ $foo: $q.when('bar')
+ },
+ template: '<div>{{value}}</div>'
+ });
+ });
+
+ it('should delay showing modal if one of the resolves is a promise', function() {
+ open(modalDefinition('<div>{{value}}</div>', {
+ value: function() {
+ return $timeout(function() { return 'Promise'; }, 100);
+ }
+ }));
+ expect($document).toHaveModalsOpen(0);
+
+ $timeout.flush();
+ expect($document).toHaveModalOpenWithContent('Promise', 'div');
+ });
+
+ it('should not open dialog (and reject returned promise) if one of resolve fails', function() {
+ var deferred = $q.defer();
+
+ var modal = open(modalDefinition('<div>{{value}}</div>', {
+ value: function() {
+ return deferred.promise;
+ }
+ }));
+ expect($document).toHaveModalsOpen(0);
+
+ deferred.reject('error in test');
+ $rootScope.$digest();
+
+ expect($document).toHaveModalsOpen(0);
+ expect(modal.result).toBeRejectedWith('error in test');
+ });
+
+ it('should support injection with minification-safe syntax in resolve functions', function() {
+ open(modalDefinition('<div>{{value.id}}</div>', {
+ value: ['$locale', function (e) {
+ return e;
+ }]
+ }));
+
+ expect($document).toHaveModalOpenWithContent('en-us', 'div');
+ });
+
+ //TODO: resolves with dependency injection - do we want to support them?
+ });
+
+ describe('scope', function() {
+ it('should use custom scope if provided', function() {
+ var $scope = $rootScope.$new();
+ $scope.fromScope = 'Content from custom scope';
+ open({
+ template: '<div>{{fromScope}}</div>',
+ scope: $scope
+ });
+ expect($document).toHaveModalOpenWithContent('Content from custom scope', 'div');
+ });
+
+ it('should create and use child of $rootScope if custom scope not provided', function() {
+ var scopeTailBefore = $rootScope.$$childTail;
+
+ $rootScope.fromScope = 'Content from root scope';
+ open({
+ template: '<div>{{fromScope}}</div>'
+ });
+ expect($document).toHaveModalOpenWithContent('Content from root scope', 'div');
+ });
+ });
+
+ describe('keyboard', function () {
+ it('should not close modals if keyboard option is set to false', function() {
+ open({
+ template: '<div>No keyboard</div>',
+ keyboard: false
+ });
+
+ expect($document).toHaveModalsOpen(1);
+
+ triggerKeyDown($document, 27);
+ $rootScope.$digest();
+
+ expect($document).toHaveModalsOpen(1);
+ });
+ });
+
+ describe('backdrop', function() {
+
+ it('should not have any backdrop element if backdrop set to false', function() {
+ var modal = open({
+ template: '<div>No backdrop</div>',
+ backdrop: false
+ });
+ expect($document).toHaveModalOpenWithContent('No backdrop', 'div');
+ expect($document).not.toHaveBackdrop();
+
+ dismiss(modal);
+ expect($document).toHaveModalsOpen(0);
+ });
+
+ it('should not close modal on backdrop click if backdrop is specified as "static"', function() {
+ open({
+ template: '<div>Static backdrop</div>',
+ backdrop: 'static'
+ });
+
+ $document.find('body > div.modal-backdrop').click();
+ $rootScope.$digest();
+
+ expect($document).toHaveModalOpenWithContent('Static backdrop', 'div');
+ expect($document).toHaveBackdrop();
+ });
+
+ it('should contain backdrop in classes on each modal opening', function() {
+ var modal = open({ template: '<div>With backdrop</div>' });
+ $animate.flush();
+ var backdropEl = $document.find('body > div.modal-backdrop');
+ expect(backdropEl).toHaveClass('in');
+
+ dismiss(modal);
+
+ modal = open({ template: '<div>With backdrop</div>' });
+ $animate.flush();
+ backdropEl = $document.find('body > div.modal-backdrop');
+ expect(backdropEl).toHaveClass('in');
+
+ });
+
+ describe('custom backdrop classes', function () {
+ it('should support additional backdrop class as string', function() {
+ open({
+ template: '<div>With custom backdrop class</div>',
+ backdropClass: 'additional'
+ });
+
+ expect($document.find('div.modal-backdrop')).toHaveClass('additional');
+ });
+ });
+ });
+
+ describe('custom window classes', function() {
+ it('should support additional window class as string', function() {
+ open({
+ template: '<div>With custom window class</div>',
+ windowClass: 'additional'
+ });
+
+ expect($document.find('div.modal')).toHaveClass('additional');
+ });
+ });
+
+ describe('top window class', function () {
+ it('should support top class option', function () {
+ open({
+ template: '<div>With custom window top class</div>',
+ windowTopClass: 'top-class'
+ });
+
+ expect($document.find('div.modal')).toHaveClass('top-class');
+ });
+ });
+
+ describe('size', function() {
+ it('should support creating small modal dialogs', function() {
+ open({
+ template: '<div>Small modal dialog</div>',
+ size: 'sm'
+ });
+
+ expect($document.find('div.modal-dialog')).toHaveClass('modal-sm');
+ });
+
+ it('should support creating large modal dialogs', function() {
+ open({
+ template: '<div>Large modal dialog</div>',
+ size: 'lg'
+ });
+
+ expect($document.find('div.modal-dialog')).toHaveClass('modal-lg');
+ });
+
+ it('should support custom size modal dialogs', function() {
+ open({
+ template: '<div>Large modal dialog</div>',
+ size: 'custom'
+ });
+
+ expect($document.find('div.modal-dialog')).toHaveClass('modal-custom');
+ });
+ });
+
+ describe('animation', function() {
+ it('should have animation fade classes by default', function() {
+ open({
+ template: '<div>Small modal dialog</div>'
+ });
+
+ expect($document.find('.modal')).toHaveClass('fade');
+ expect($document.find('.modal-backdrop')).toHaveClass('fade');
+ });
+
+ it('should not have fade classes if animation false', function() {
+ open({
+ template: '<div>Small modal dialog</div>',
+ animation: false
+ });
+
+ expect($document.find('.modal')).not.toHaveClass('fade');
+ expect($document.find('.modal-backdrop')).not.toHaveClass('fade');
+ });
+ });
+
+ describe('openedClass', function() {
+ var body;
+
+ beforeEach(function() {
+ body = $document.find('body');
+ });
+
+ it('should add the modal-open class to the body element by default', function() {
+ open({
+ template: '<div>dummy modal</div>'
+ });
+
+ expect(body).toHaveClass('modal-open');
+ });
+
+ it('should add the custom class to the body element', function() {
+ open({
+ template: '<div>dummy modal</div>',
+ openedClass: 'foo'
+ });
+
+ expect(body).toHaveClass('foo');
+ expect(body).not.toHaveClass('modal-open');
+ });
+
+ it('should remove the custom class on closing of modal', function() {
+ var modal = open({
+ template: '<div>dummy modal</div>',
+ openedClass: 'foo'
+ });
+
+ expect(body).toHaveClass('foo');
+
+ close(modal);
+
+ expect(body).not.toHaveClass('foo');
+ });
+
+ it('should add multiple custom classes to the body element and remove appropriately', function() {
+ var modal1 = open({
+ template: '<div>dummy modal</div>',
+ openedClass: 'foo'
+ });
+
+ expect(body).toHaveClass('foo');
+ expect(body).not.toHaveClass('modal-open');
+
+ var modal2 = open({
+ template: '<div>dummy modal</div>',
+ openedClass: 'bar'
+ });
+
+ expect(body).toHaveClass('foo');
+ expect(body).toHaveClass('bar');
+ expect(body).not.toHaveClass('modal-open');
+
+ var modal3 = open({
+ template: '<div>dummy modal</div>',
+ openedClass: 'foo'
+ });
+
+ expect(body).toHaveClass('foo');
+ expect(body).toHaveClass('bar');
+ expect(body).not.toHaveClass('modal-open');
+
+ close(modal1);
+
+ expect(body).toHaveClass('foo');
+ expect(body).toHaveClass('bar');
+ expect(body).not.toHaveClass('modal-open');
+
+ close(modal2);
+
+ expect(body).toHaveClass('foo');
+ expect(body).not.toHaveClass('bar');
+ expect(body).not.toHaveClass('modal-open');
+
+ close(modal3);
+
+ expect(body).not.toHaveClass('foo');
+ expect(body).not.toHaveClass('bar');
+ expect(body).not.toHaveClass('modal-open');
+ });
+ });
+ });
+
+ describe('multiple modals', function() {
+ it('it should allow opening of multiple modals', function() {
+ var modal1 = open({template: '<div>Modal1</div>'});
+ var modal2 = open({template: '<div>Modal2</div>'});
+ expect($document).toHaveModalsOpen(2);
+
+ dismiss(modal2);
+ expect($document).toHaveModalsOpen(1);
+ expect($document).toHaveModalOpenWithContent('Modal1', 'div');
+
+ dismiss(modal1);
+ expect($document).toHaveModalsOpen(0);
+ });
+
+ it('should not close any modals on ESC if the topmost one does not allow it', function() {
+ var modal1 = open({template: '<div>Modal1</div>'});
+ var modal2 = open({template: '<div>Modal2</div>', keyboard: false});
+
+ triggerKeyDown($document, 27);
+ $rootScope.$digest();
+
+ expect($document).toHaveModalsOpen(2);
+ });
+
+ it('should not close any modals on click if a topmost modal does not have backdrop', function() {
+ var modal1 = open({template: '<div>Modal1</div>'});
+ var modal2 = open({template: '<div>Modal2</div>', backdrop: false});
+
+ $document.find('body > div.modal-backdrop').click();
+ $rootScope.$digest();
+
+ expect($document).toHaveModalsOpen(2);
+ });
+
+ it('multiple modals should not interfere with default options', function() {
+ var modal1 = open({template: '<div>Modal1</div>', backdrop: false});
+ var modal2 = open({template: '<div>Modal2</div>'});
+ $rootScope.$digest();
+
+ expect($document).toHaveBackdrop();
+ });
+
+ it('should add "modal-open" class when a modal gets opened', function() {
+ var body = $document.find('body');
+ expect(body).not.toHaveClass('modal-open');
+
+ var modal1 = open({template: '<div>Content1</div>'});
+ expect(body).toHaveClass('modal-open');
+
+ var modal2 = open({template: '<div>Content1</div>'});
+ expect(body).toHaveClass('modal-open');
+
+ dismiss(modal1);
+ expect(body).toHaveClass('modal-open');
+
+ dismiss(modal2);
+ expect(body).not.toHaveClass('modal-open');
+ });
+
+ it('should return to the element which had focus before the dialog is invoked', function() {
+ var link = '<a href>Link</a>';
+ var element = angular.element(link);
+ angular.element(document.body).append(element);
+ element.focus();
+ expect(document.activeElement.tagName).toBe('A');
+
+ var modal1 = open({template: '<div>Modal1<button id="focus">inside modal1</button></div>'});
+ $animate.flush();
+ $rootScope.$digest();
+ document.getElementById('focus').focus();
+ expect(document.activeElement.tagName).toBe('BUTTON');
+ expect($document).toHaveModalsOpen(1);
+
+ var modal2 = open({template: '<div>Modal2</div>'});
+ $animate.flush();
+ $rootScope.$digest();
+ expect(document.activeElement.tagName).toBe('DIV');
+ expect($document).toHaveModalsOpen(2);
+
+ dismiss(modal2);
+ expect(document.activeElement.tagName).toBe('BUTTON');
+ expect($document).toHaveModalsOpen(1);
+
+ dismiss(modal1);
+ expect(document.activeElement.tagName).toBe('A');
+ expect($document).toHaveModalsOpen(0);
+
+ element.remove();
+ });
+
+ it('should open modals and resolve the opened promises in order', function() {
+ // Opens a modal for each element in array order.
+ // Order is an array of non-repeating integers from 0..length-1 representing when to resolve that modal's promise.
+ // For example [1,2,0] would resolve the 3rd modal's promise first and the 2nd modal's promise last.
+ // Tests that the modals are added to $uibModalStack and that each resolves its "opened" promise sequentially.
+ // If an element is {reject:n} then n is still the order, but the corresponding promise is rejected.
+ // A rejection earlier in the open sequence should not affect modals opened later.
+ function test(order) {
+ var ds = []; // {index, deferred, reject}
+ var expected = ''; // 0..length-1
+ var actual = '';
+ angular.forEach(order, function(x, i) {
+ var reject = x.reject !== undefined;
+ if (reject) {
+ x = x.reject;
+ } else {
+ expected += i;
+ }
+ ds[x] = {index:i, deferred:$q.defer(), reject:reject};
+
+ var scope = $rootScope.$new();
+ scope.index = i;
+ open({
+ template: '<div>' + i + '</div>',
+ scope: scope,
+ resolve: {
+ x: function() { return ds[x].deferred.promise; }
+ }
+ }).opened.then(function() {
+ expect($uibModalStack.getTop().value.modalScope.index).toEqual(i);
+ actual += i;
+ });
+ });
+
+ angular.forEach(ds, function(d, i) {
+ if (d.reject) {
+ d.deferred.reject('rejected:' + d.index );
+ } else {
+ d.deferred.resolve('resolved:' + d.index );
+ }
+ $rootScope.$digest();
+ });
+
+ expect(actual).toEqual(expected);
+ expect($uibModal.getPromiseChain()).toEqual(null);
+ }
+
+ // Calls emit n! times on arrays of length n containing all non-repeating permutations of the integers 0..n-1.
+ function permute(n, emit) {
+ if (n < 1 || typeof emit !== 'function') {
+ return;
+ }
+ var a = [];
+ function _permute(depth) {
+ index: for (var i = 0; i < n; i++) {
+ for (var j = 0; j < depth; j++) {
+ if (a[j] === i) {
+ continue index; // already used
+ }
+ }
+
+ a[depth] = i;
+ if (depth + 1 === n) {
+ emit(angular.copy(a));
+ } else {
+ _permute(depth + 1);
+ }
+ }
+ }
+ _permute(0);
+ }
+
+ permute(2, function(a) { test(a); });
+ permute(2, function(a) { test(a.map(function(x, i) { return {reject:x}; })); });
+ permute(2, function(a) { test(a.map(function(x, i) { return i === 0 ? {reject:x} : x; })); });
+ permute(3, function(a) { test(a); });
+ permute(3, function(a) { test(a.map(function(x, i) { return {reject:x}; })); });
+ permute(3, function(a) { test(a.map(function(x, i) { return i === 0 ? {reject:x} : x; })); });
+ permute(3, function(a) { test(a.map(function(x, i) { return i === 1 ? {reject:x} : x; })); });
+ });
+
+ it('should have top class only on top window', function () {
+ var modal1 = open({template: '<div>Content1</div>', windowClass: 'modal1', windowTopClass: 'modal-top'});
+ expect($document.find('div.modal1')).toHaveClass('modal-top');
+ expect($document).toHaveModalsOpen(1);
+
+ var modal2 = open({template: '<div>Content1</div>', windowClass: 'modal2', windowTopClass: 'modal-top'});
+ expect($document.find('div.modal1')).not.toHaveClass('modal-top');
+ expect($document.find('div.modal2')).toHaveClass('modal-top');
+ expect($document).toHaveModalsOpen(2);
+
+ var modal3 = open({template: '<div>Content1</div>', windowClass: 'modal3', windowTopClass: 'modal-top'});
+ expect($document.find('div.modal1')).not.toHaveClass('modal-top');
+ expect($document.find('div.modal2')).not.toHaveClass('modal-top');
+ expect($document.find('div.modal3')).toHaveClass('modal-top');
+ expect($document).toHaveModalsOpen(3);
+
+ dismiss(modal2);
+ expect($document.find('div.modal1')).not.toHaveClass('modal-top');
+ expect($document.find('div.modal3')).toHaveClass('modal-top');
+ expect($document).toHaveModalsOpen(2);
+
+ close(modal3);
+ expect($document.find('div.modal1')).toHaveClass('modal-top');
+ expect($document).toHaveModalsOpen(1);
+ });
+ });
+
+ describe('modal.closing event', function() {
+ it('should close the modal contingent on the modal.closing event and return whether the modal closed', function() {
+ var preventDefault;
+ var modal;
+ var template = '<div>content</div>';
+
+ function TestCtrl($scope) {
+ $scope.$on('modal.closing', function(event, resultOrReason, closing) {
+ if (preventDefault) {
+ event.preventDefault();
+ }
+ });
+ }
+
+ modal = open({template: template, controller: TestCtrl});
+
+ preventDefault = true;
+ expect(close(modal, 'result', true)).toBeFalsy();
+ expect($document).toHaveModalsOpen(1);
+
+ preventDefault = false;
+ expect(close(modal, 'result')).toBeTruthy();
+ expect($document).toHaveModalsOpen(0);
+
+ modal = open({template: template, controller: TestCtrl});
+
+ preventDefault = true;
+ expect(dismiss(modal, 'result', true)).toBeFalsy();
+ expect($document).toHaveModalsOpen(1);
+
+ preventDefault = false;
+ expect(dismiss(modal, 'result')).toBeTruthy();
+ expect($document).toHaveModalsOpen(0);
+ });
+
+ it('should trigger modal.closing and pass result/reason and closing parameters to the event', function() {
+ var called;
+
+ called = false;
+ close(open({
+ template: '<div>content</div>',
+ controller: function($scope) {
+ $scope.$on('modal.closing', function(event, resultOrReason, closing) {
+ called = true;
+ expect(resultOrReason).toBe('result');
+ expect(closing).toBeTruthy();
+ });
+ }
+ }), 'result');
+ expect(called).toBeTruthy();
+
+ called = false;
+ dismiss(open({
+ template: '<div>content</div>',
+ controller: function($scope) {
+ $scope.$on('modal.closing', function(event, resultOrReason, closing) {
+ called = true;
+ expect(resultOrReason).toBe('reason');
+ expect(closing).toBeFalsy();
+ });
+ }
+ }), 'reason');
+ expect(called).toBeTruthy();
+ });
+ });
+});
+
+/* deprecation tests below */
+
+describe('$modal deprecation', function() {
+ beforeEach(module('ngAnimateMock'));
+ beforeEach(module('ui.bootstrap.modal'));
+ beforeEach(module('template/modal/backdrop.html'));
+ beforeEach(module('template/modal/window.html'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$modalSuppressWarning', true);
+ });
+
+ inject(function($modal, $timeout, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ $modal.open({template: '<div>Foo</div>', controller: function($modalInstance) {}});
+ $rootScope.$digest();
+ $timeout.flush(0);
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($log) {
+ spyOn($log, 'warn');
+
+ inject(function($compile, $templateCache, $rootScope, $modal, $timeout) {
+ var backdropTemplate =
+ '<div class="modal-backdrop"' +
+ 'modal-animation-class="fade"' +
+ 'modal-in-class="in"' +
+ 'ng-style="{\'z-index\': 1040 + (index && 1 || 0) + index*10}"' +
+ '></div>';
+ $templateCache.put('template/modal/backdrop.html', backdropTemplate);
+
+ var windowTemplate =
+ '<div modal-render="{{$isRendered}}" tabindex="-1" role="dialog" class="modal"' +
+ 'modal-animation-class="fade"' +
+ 'modal-in-class="in"' +
+ 'ng-style="{\'z-index\': 1050 + index*10, display: \'block\'}">' +
+ '<div class="modal-dialog" ng-class="size ? \'modal-\' + size : \'\'"><div class="modal-content" modal-transclude></div></div>' +
+ '</div>';
+ $templateCache.put('template/modal/window.html', windowTemplate);
+
+ $modal.open({template: '<div>Foo</div>', controller: function($modalInstance) {}});
+ $rootScope.$digest();
+ $timeout.flush(0);
+
+ expect($log.warn.calls.count()).toBe(6);
+ expect($log.warn.calls.argsFor(0)).toEqual(['$modal is now deprecated. Use $uibModal instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['$modalInstance is now deprecated. Use $uibModalInstance instead.']);
+ expect($log.warn.calls.argsFor(2)).toEqual(['$modalStack is now deprecated. Use $uibModalStack instead.']);
+ expect($log.warn.calls.argsFor(3)).toEqual(['modal-animation-class is now deprecated. Use uib-modal-animation-class instead.']);
+ expect($log.warn.calls.argsFor(4)).toEqual(['modal-animation-class is now deprecated. Use uib-modal-animation-class instead.']);
+ expect($log.warn.calls.argsFor(5)).toEqual(['modal-transclude is now deprecated. Use uib-modal-transclude instead.']);
+
+ $log.warn.calls.reset();
+ $compile('<div modal-backdrop></div>')($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.argsFor(1)).toEqual(['modal-backdrop is now deprecated. Use uib-modal-backdrop instead.']);
+
+ $log.warn.calls.reset();
+ $compile('<div modal-window></div>')($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.argsFor(2)).toEqual(['modal-window is now deprecated. Use uib-modal-window instead.']);
+ });
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/test/modalWindow.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/test/modalWindow.spec.js
new file mode 100644
index 0000000..60c00ae
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/test/modalWindow.spec.js
@@ -0,0 +1,46 @@
+describe('modal window', function() {
+ var $rootScope, $compile;
+
+ beforeEach(module('ui.bootstrap.modal'));
+ beforeEach(module('template/modal/window.html'));
+ beforeEach(inject(function (_$rootScope_, _$compile_) {
+ $rootScope = _$rootScope_;
+ $compile = _$compile_;
+ }));
+
+ it('should not use transclusion scope for modals content - issue 2110', function() {
+ $rootScope.animate = false;
+ $compile('<div uib-modal-window animate="animate"><span ng-init="foo=true"></span></div>')($rootScope);
+ $rootScope.$digest();
+
+ expect($rootScope.foo).toBeTruthy();
+ });
+
+ it('should support custom CSS classes as string', function() {
+ $rootScope.animate = false;
+ var windowEl = $compile('<div uib-modal-window animate="animate" window-class="test foo">content</div>')($rootScope);
+ $rootScope.$digest();
+
+ expect(windowEl).toHaveClass('test');
+ expect(windowEl).toHaveClass('foo');
+ });
+
+ it('should support window top class', function () {
+ $rootScope.animate = false;
+ var windowEl = $compile('<div uib-modal-window animate="animate" window-top-class="test foo">content</div>')($rootScope);
+ $rootScope.$digest();
+
+ expect(windowEl).toHaveClass('test');
+ expect(windowEl).toHaveClass('foo');
+ });
+
+ it('should support custom template url', inject(function($templateCache) {
+ $templateCache.put('window.html', '<div class="mywindow" ng-transclude></div>');
+
+ var windowEl = $compile('<div uib-modal-window template-url="window.html" window-class="test">content</div>')($rootScope);
+ $rootScope.$digest();
+
+ expect(windowEl).toHaveClass('mywindow');
+ expect(windowEl).toHaveClass('test');
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/test/multiMap.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/test/multiMap.spec.js
new file mode 100644
index 0000000..c89624e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/modal/test/multiMap.spec.js
@@ -0,0 +1,58 @@
+describe('multi map', function() {
+ var multiMap;
+
+ beforeEach(module('ui.bootstrap.modal'));
+ beforeEach(inject(function($$multiMap) {
+ multiMap = $$multiMap.createNew();
+ }));
+
+ it('should add and remove objects by key', function() {
+ multiMap.put('foo', 'bar');
+
+ expect(multiMap.get('foo')).toEqual(['bar']);
+
+ multiMap.put('foo', 'baz');
+
+ expect(multiMap.get('foo')).toEqual(['bar', 'baz']);
+
+ multiMap.remove('foo', 'bar');
+
+ expect(multiMap.get('foo')).toEqual(['baz']);
+
+ multiMap.remove('foo', 'baz');
+
+ expect(multiMap.hasKey('foo')).toBe(false);
+ });
+
+ it('should support getting the keys', function() {
+ multiMap.put('foo', 'bar');
+ multiMap.put('baz', 'boo');
+
+ expect(multiMap.keys()).toEqual(['foo', 'baz']);
+ });
+
+ it('should return all entries', function() {
+ multiMap.put('foo', 'bar');
+ multiMap.put('foo', 'bar2');
+ multiMap.put('baz', 'boo');
+
+ expect(multiMap.entries()).toEqual([
+ {
+ key: 'foo',
+ value: ['bar', 'bar2']
+ },
+ {
+ key: 'baz',
+ value: ['boo']
+ }
+ ]);
+ });
+
+ it('should preserve semantic of an empty key', function() {
+ expect(multiMap.get('key')).toBeUndefined();
+ });
+
+ it('should respect removal of non-existing elements', function() {
+ expect(multiMap.remove('foo', 'bar')).toBeUndefined();
+ });
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/docs/demo.html
new file mode 100644
index 0000000..16ec3ac
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/docs/demo.html
@@ -0,0 +1,19 @@
+<div ng-controller="PaginationDemoCtrl">
+ <h4>Default</h4>
+ <uib-pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()"></uib-pagination>
+ <uib-pagination boundary-links="true" total-items="totalItems" ng-model="currentPage" class="pagination-sm" previous-text="‹" next-text="›" first-text="«" last-text="»"></uib-pagination>
+ <uib-pagination direction-links="false" boundary-links="true" total-items="totalItems" ng-model="currentPage"></uib-pagination>
+ <uib-pagination direction-links="false" total-items="totalItems" ng-model="currentPage" num-pages="smallnumPages"></uib-pagination>
+ <pre>The selected page no: {{currentPage}}</pre>
+ <button type="button" class="btn btn-info" ng-click="setPage(3)">Set current page to: 3</button>
+
+ <hr />
+ <h4>Pager</h4>
+ <uib-pager total-items="totalItems" ng-model="currentPage"></uib-pager>
+
+ <hr />
+ <h4>Limit the maximum visible buttons</h4>
+ <uib-pagination total-items="bigTotalItems" ng-model="bigCurrentPage" max-size="maxSize" class="pagination-sm" boundary-links="true"></uib-pagination>
+ <uib-pagination total-items="bigTotalItems" ng-model="bigCurrentPage" max-size="maxSize" class="pagination-sm" boundary-links="true" rotate="false" num-pages="numPages"></uib-pagination>
+ <pre>Page: {{bigCurrentPage}} / {{numPages}}</pre>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/docs/demo.js
new file mode 100644
index 0000000..9791aab
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/docs/demo.js
@@ -0,0 +1,16 @@
+angular.module('ui.bootstrap.demo').controller('PaginationDemoCtrl', function ($scope, $log) {
+ $scope.totalItems = 64;
+ $scope.currentPage = 4;
+
+ $scope.setPage = function (pageNo) {
+ $scope.currentPage = pageNo;
+ };
+
+ $scope.pageChanged = function() {
+ $log.log('Page changed to: ' + $scope.currentPage);
+ };
+
+ $scope.maxSize = 5;
+ $scope.bigTotalItems = 175;
+ $scope.bigCurrentPage = 1;
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/docs/readme.md
new file mode 100644
index 0000000..07c89d5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/docs/readme.md
@@ -0,0 +1,91 @@
+
+A lightweight pagination directive that is focused on ... providing pagination & will take care of visualising a pagination bar and enable / disable buttons correctly!
+
+### Pagination Settings ###
+
+Settings can be provided as attributes in the `<uib-pagination>` or globally configured through the `uibPaginationConfig`.
+
+ * `ng-change`
+ :
+ `ng-change` can be used together with `ng-model` to call a function whenever the page changes.
+
+ * `ng-model` <i class="glyphicon glyphicon-eye-open"></i>
+ :
+ Current page number. First page is 1.
+
+ * `ng-disabled` <i class="glyphicon glyphicon-eye-open"></i>
+ :
+ Used to disable the pagination component
+
+ * `total-items` <i class="glyphicon glyphicon-eye-open"></i>
+ :
+ Total number of items in all pages.
+
+ * `items-per-page` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: 10)_ :
+ Maximum number of items per page. A value less than one indicates all items on one page.
+
+ * `max-size` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: null)_ :
+ Limit number for pagination size.
+
+ * `num-pages` <small class="badge">readonly</small>
+ _(Defaults: angular.noop)_ :
+ An optional expression assigned the total number of pages to display.
+
+ * `rotate`
+ _(Defaults: true)_ :
+ Whether to keep current page in the middle of the visible ones.
+
+ * `direction-links`
+ _(Default: true)_ :
+ Whether to display Previous / Next buttons.
+
+ * `previous-text`
+ _(Default: 'Previous')_ :
+ Text for Previous button.
+
+ * `next-text`
+ _(Default: 'Next')_ :
+ Text for Next button.
+
+ * `boundary-links`
+ _(Default: false)_ :
+ Whether to display First / Last buttons.
+
+ * `first-text`
+ _(Default: 'First')_ :
+ Text for First button.
+
+ * `last-text`
+ _(Default: 'Last')_ :
+ Text for Last button.
+
+ * `template-url`
+ _(Default: 'template/pagination/pagination.html')_ :
+ Override the template for the component with a custom provided template
+
+### Pager Settings ###
+
+Settings can be provided as attributes in the `<uib-pager>` or globally configured through the `uibPagerConfig`.
+For `ng-model`, `total-items`, `items-per-page` and `num-pages` see pagination settings. Other settings are:
+
+ * `align`
+ _(Default: true)_ :
+ Whether to align each link to the sides.
+
+ * `previous-text`
+ _(Default: '« Previous')_ :
+ Text for Previous button.
+
+ * `next-text`
+ _(Default: 'Next »')_ :
+ Text for Next button.
+
+ * `template-url`
+ _(Default: 'template/pagination/pager.html') :
+ Override the template for the component with a custom provided template
+
+ * `ng-disabled` <i class="glyphicon glyphicon-eye-open"></i>
+ :
+ Used to disable the pager component
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/pagination.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/pagination.js
new file mode 100644
index 0000000..1e75dcf
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/pagination.js
@@ -0,0 +1,457 @@
+angular.module('ui.bootstrap.pagination', [])
+.controller('UibPaginationController', ['$scope', '$attrs', '$parse', function($scope, $attrs, $parse) {
+ var self = this,
+ ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
+ setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop;
+
+ this.init = function(ngModelCtrl_, config) {
+ ngModelCtrl = ngModelCtrl_;
+ this.config = config;
+
+ ngModelCtrl.$render = function() {
+ self.render();
+ };
+
+ if ($attrs.itemsPerPage) {
+ $scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) {
+ self.itemsPerPage = parseInt(value, 10);
+ $scope.totalPages = self.calculateTotalPages();
+ });
+ } else {
+ this.itemsPerPage = config.itemsPerPage;
+ }
+
+ $scope.$watch('totalItems', function() {
+ $scope.totalPages = self.calculateTotalPages();
+ });
+
+ $scope.$watch('totalPages', function(value) {
+ setNumPages($scope.$parent, value); // Readonly variable
+
+ if ( $scope.page > value ) {
+ $scope.selectPage(value);
+ } else {
+ ngModelCtrl.$render();
+ }
+ });
+ };
+
+ this.calculateTotalPages = function() {
+ var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage);
+ return Math.max(totalPages || 0, 1);
+ };
+
+ this.render = function() {
+ $scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1;
+ };
+
+ $scope.selectPage = function(page, evt) {
+ if (evt) {
+ evt.preventDefault();
+ }
+
+ var clickAllowed = !$scope.ngDisabled || !evt;
+ if (clickAllowed && $scope.page !== page && page > 0 && page <= $scope.totalPages) {
+ if (evt && evt.target) {
+ evt.target.blur();
+ }
+ ngModelCtrl.$setViewValue(page);
+ ngModelCtrl.$render();
+ }
+ };
+
+ $scope.getText = function(key) {
+ return $scope[key + 'Text'] || self.config[key + 'Text'];
+ };
+
+ $scope.noPrevious = function() {
+ return $scope.page === 1;
+ };
+
+ $scope.noNext = function() {
+ return $scope.page === $scope.totalPages;
+ };
+}])
+
+.constant('uibPaginationConfig', {
+ itemsPerPage: 10,
+ boundaryLinks: false,
+ directionLinks: true,
+ firstText: 'First',
+ previousText: 'Previous',
+ nextText: 'Next',
+ lastText: 'Last',
+ rotate: true
+})
+
+.directive('uibPagination', ['$parse', 'uibPaginationConfig', function($parse, paginationConfig) {
+ return {
+ restrict: 'EA',
+ scope: {
+ totalItems: '=',
+ firstText: '@',
+ previousText: '@',
+ nextText: '@',
+ lastText: '@',
+ ngDisabled:'='
+ },
+ require: ['uibPagination', '?ngModel'],
+ controller: 'UibPaginationController',
+ controllerAs: 'pagination',
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/pagination/pagination.html';
+ },
+ replace: true,
+ link: function(scope, element, attrs, ctrls) {
+ var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+
+ if (!ngModelCtrl) {
+ return; // do nothing if no ng-model
+ }
+
+ // Setup configuration parameters
+ var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize,
+ rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate;
+ scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks;
+ scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks;
+
+ paginationCtrl.init(ngModelCtrl, paginationConfig);
+
+ if (attrs.maxSize) {
+ scope.$parent.$watch($parse(attrs.maxSize), function(value) {
+ maxSize = parseInt(value, 10);
+ paginationCtrl.render();
+ });
+ }
+
+ // Create page object used in template
+ function makePage(number, text, isActive) {
+ return {
+ number: number,
+ text: text,
+ active: isActive
+ };
+ }
+
+ function getPages(currentPage, totalPages) {
+ var pages = [];
+
+ // Default page limits
+ var startPage = 1, endPage = totalPages;
+ var isMaxSized = angular.isDefined(maxSize) && maxSize < totalPages;
+
+ // recompute if maxSize
+ if (isMaxSized) {
+ if (rotate) {
+ // Current page is displayed in the middle of the visible ones
+ startPage = Math.max(currentPage - Math.floor(maxSize/2), 1);
+ endPage = startPage + maxSize - 1;
+
+ // Adjust if limit is exceeded
+ if (endPage > totalPages) {
+ endPage = totalPages;
+ startPage = endPage - maxSize + 1;
+ }
+ } else {
+ // Visible pages are paginated with maxSize
+ startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1;
+
+ // Adjust last page if limit is exceeded
+ endPage = Math.min(startPage + maxSize - 1, totalPages);
+ }
+ }
+
+ // Add page number links
+ for (var number = startPage; number <= endPage; number++) {
+ var page = makePage(number, number, number === currentPage);
+ pages.push(page);
+ }
+
+ // Add links to move between page sets
+ if (isMaxSized && ! rotate) {
+ if (startPage > 1) {
+ var previousPageSet = makePage(startPage - 1, '...', false);
+ pages.unshift(previousPageSet);
+ }
+
+ if (endPage < totalPages) {
+ var nextPageSet = makePage(endPage + 1, '...', false);
+ pages.push(nextPageSet);
+ }
+ }
+
+ return pages;
+ }
+
+ var originalRender = paginationCtrl.render;
+ paginationCtrl.render = function() {
+ originalRender();
+ if (scope.page > 0 && scope.page <= scope.totalPages) {
+ scope.pages = getPages(scope.page, scope.totalPages);
+ }
+ };
+ }
+ };
+}])
+
+.constant('uibPagerConfig', {
+ itemsPerPage: 10,
+ previousText: '« Previous',
+ nextText: 'Next »',
+ align: true
+})
+
+.directive('uibPager', ['uibPagerConfig', function(pagerConfig) {
+ return {
+ restrict: 'EA',
+ scope: {
+ totalItems: '=',
+ previousText: '@',
+ nextText: '@',
+ ngDisabled: '='
+ },
+ require: ['uibPager', '?ngModel'],
+ controller: 'UibPaginationController',
+ controllerAs: 'pagination',
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/pagination/pager.html';
+ },
+ replace: true,
+ link: function(scope, element, attrs, ctrls) {
+ var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+
+ if (!ngModelCtrl) {
+ return; // do nothing if no ng-model
+ }
+
+ scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align;
+ paginationCtrl.init(ngModelCtrl, pagerConfig);
+ }
+ };
+}]);
+
+/* Deprecated Pagination Below */
+
+angular.module('ui.bootstrap.pagination')
+.value('$paginationSuppressWarning', false)
+.controller('PaginationController', ['$scope', '$attrs', '$parse', '$log', '$paginationSuppressWarning', function($scope, $attrs, $parse, $log, $paginationSuppressWarning) {
+ if (!$paginationSuppressWarning) {
+ $log.warn('PaginationController is now deprecated. Use UibPaginationController instead.');
+ }
+
+ var self = this,
+ ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
+ setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop;
+
+ this.init = function(ngModelCtrl_, config) {
+ ngModelCtrl = ngModelCtrl_;
+ this.config = config;
+
+ ngModelCtrl.$render = function() {
+ self.render();
+ };
+
+ if ($attrs.itemsPerPage) {
+ $scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) {
+ self.itemsPerPage = parseInt(value, 10);
+ $scope.totalPages = self.calculateTotalPages();
+ });
+ } else {
+ this.itemsPerPage = config.itemsPerPage;
+ }
+
+ $scope.$watch('totalItems', function() {
+ $scope.totalPages = self.calculateTotalPages();
+ });
+
+ $scope.$watch('totalPages', function(value) {
+ setNumPages($scope.$parent, value); // Readonly variable
+
+ if ( $scope.page > value ) {
+ $scope.selectPage(value);
+ } else {
+ ngModelCtrl.$render();
+ }
+ });
+ };
+
+ this.calculateTotalPages = function() {
+ var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage);
+ return Math.max(totalPages || 0, 1);
+ };
+
+ this.render = function() {
+ $scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1;
+ };
+
+ $scope.selectPage = function(page, evt) {
+ if (evt) {
+ evt.preventDefault();
+ }
+
+ var clickAllowed = !$scope.ngDisabled || !evt;
+ if (clickAllowed && $scope.page !== page && page > 0 && page <= $scope.totalPages) {
+ if (evt && evt.target) {
+ evt.target.blur();
+ }
+ ngModelCtrl.$setViewValue(page);
+ ngModelCtrl.$render();
+ }
+ };
+
+ $scope.getText = function(key) {
+ return $scope[key + 'Text'] || self.config[key + 'Text'];
+ };
+
+ $scope.noPrevious = function() {
+ return $scope.page === 1;
+ };
+
+ $scope.noNext = function() {
+ return $scope.page === $scope.totalPages;
+ };
+}])
+.directive('pagination', ['$parse', 'uibPaginationConfig', '$log', '$paginationSuppressWarning', function($parse, paginationConfig, $log, $paginationSuppressWarning) {
+ return {
+ restrict: 'EA',
+ scope: {
+ totalItems: '=',
+ firstText: '@',
+ previousText: '@',
+ nextText: '@',
+ lastText: '@',
+ ngDisabled:'='
+ },
+ require: ['pagination', '?ngModel'],
+ controller: 'PaginationController',
+ controllerAs: 'pagination',
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/pagination/pagination.html';
+ },
+ replace: true,
+ link: function(scope, element, attrs, ctrls) {
+ if (!$paginationSuppressWarning) {
+ $log.warn('pagination is now deprecated. Use uib-pagination instead.');
+ }
+ var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+
+ if (!ngModelCtrl) {
+ return; // do nothing if no ng-model
+ }
+
+ // Setup configuration parameters
+ var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize,
+ rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate;
+ scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks;
+ scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks;
+
+ paginationCtrl.init(ngModelCtrl, paginationConfig);
+
+ if (attrs.maxSize) {
+ scope.$parent.$watch($parse(attrs.maxSize), function(value) {
+ maxSize = parseInt(value, 10);
+ paginationCtrl.render();
+ });
+ }
+
+ // Create page object used in template
+ function makePage(number, text, isActive) {
+ return {
+ number: number,
+ text: text,
+ active: isActive
+ };
+ }
+
+ function getPages(currentPage, totalPages) {
+ var pages = [];
+
+ // Default page limits
+ var startPage = 1, endPage = totalPages;
+ var isMaxSized = angular.isDefined(maxSize) && maxSize < totalPages;
+
+ // recompute if maxSize
+ if (isMaxSized) {
+ if (rotate) {
+ // Current page is displayed in the middle of the visible ones
+ startPage = Math.max(currentPage - Math.floor(maxSize/2), 1);
+ endPage = startPage + maxSize - 1;
+
+ // Adjust if limit is exceeded
+ if (endPage > totalPages) {
+ endPage = totalPages;
+ startPage = endPage - maxSize + 1;
+ }
+ } else {
+ // Visible pages are paginated with maxSize
+ startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1;
+
+ // Adjust last page if limit is exceeded
+ endPage = Math.min(startPage + maxSize - 1, totalPages);
+ }
+ }
+
+ // Add page number links
+ for (var number = startPage; number <= endPage; number++) {
+ var page = makePage(number, number, number === currentPage);
+ pages.push(page);
+ }
+
+ // Add links to move between page sets
+ if (isMaxSized && ! rotate) {
+ if (startPage > 1) {
+ var previousPageSet = makePage(startPage - 1, '...', false);
+ pages.unshift(previousPageSet);
+ }
+
+ if (endPage < totalPages) {
+ var nextPageSet = makePage(endPage + 1, '...', false);
+ pages.push(nextPageSet);
+ }
+ }
+
+ return pages;
+ }
+
+ var originalRender = paginationCtrl.render;
+ paginationCtrl.render = function() {
+ originalRender();
+ if (scope.page > 0 && scope.page <= scope.totalPages) {
+ scope.pages = getPages(scope.page, scope.totalPages);
+ }
+ };
+ }
+ };
+}])
+
+.directive('pager', ['uibPagerConfig', '$log', '$paginationSuppressWarning', function(pagerConfig, $log, $paginationSuppressWarning) {
+ return {
+ restrict: 'EA',
+ scope: {
+ totalItems: '=',
+ previousText: '@',
+ nextText: '@',
+ ngDisabled: '='
+ },
+ require: ['pager', '?ngModel'],
+ controller: 'PaginationController',
+ controllerAs: 'pagination',
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/pagination/pager.html';
+ },
+ replace: true,
+ link: function(scope, element, attrs, ctrls) {
+ if (!$paginationSuppressWarning) {
+ $log.warn('pager is now deprecated. Use uib-pager instead.');
+ }
+ var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+
+ if (!ngModelCtrl) {
+ return; // do nothing if no ng-model
+ }
+
+ scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align;
+ paginationCtrl.init(ngModelCtrl, pagerConfig);
+ }
+ };
+}]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/test/pager.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/test/pager.spec.js
new file mode 100644
index 0000000..3756d70
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/test/pager.spec.js
@@ -0,0 +1,311 @@
+describe('pager directive', function() {
+ var $compile, $rootScope, $document, $templateCache, body, element;
+ beforeEach(module('ui.bootstrap.pagination'));
+ beforeEach(module('template/pagination/pager.html'));
+ beforeEach(inject(function(_$compile_, _$rootScope_, _$document_, _$templateCache_) {
+ $compile = _$compile_;
+ $rootScope = _$rootScope_;
+ $rootScope.total = 47; // 5 pages
+ $rootScope.currentPage = 3;
+ $document = _$document_;
+ $templateCache = _$templateCache_;
+ body = $document.find('body');
+ element = $compile('<uib-pager total-items="total" ng-model="currentPage"></uib-pager>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ function getPaginationBarSize() {
+ return element.find('li').length;
+ }
+
+ function getPaginationEl(index) {
+ return element.find('li').eq(index);
+ }
+
+ function clickPaginationEl(index) {
+ getPaginationEl(index).find('a').click();
+ }
+
+ function getPaginationLinkEl(elem, index) {
+ return elem.find('li').eq(index).find('a');
+ }
+
+ function updateCurrentPage(value) {
+ $rootScope.currentPage = value;
+ $rootScope.$digest();
+ }
+
+ it('has a "pager" css class', function() {
+ expect(element.hasClass('pager')).toBe(true);
+ });
+
+ it('contains 2 li elements', function() {
+ expect(getPaginationBarSize()).toBe(2);
+ expect(getPaginationEl(0).text()).toBe('« Previous');
+ expect(getPaginationEl(-1).text()).toBe('Next »');
+ });
+
+ it('aligns previous & next page', function() {
+ expect(getPaginationEl(0)).toHaveClass('previous');
+ expect(getPaginationEl(0)).not.toHaveClass('next');
+
+ expect(getPaginationEl(-1)).not.toHaveClass('previous');
+ expect(getPaginationEl(-1)).toHaveClass('next');
+ });
+
+ it('exposes the controller on the template', function() {
+ $templateCache.put('template/pagination/pager.html', '<div>{{pagination.text}}</div>');
+
+ element = $compile('<uib-pager></uib-pager>')($rootScope);
+ $rootScope.$digest();
+
+ var ctrl = element.controller('uibPager');
+ expect(ctrl).toBeDefined();
+
+ ctrl.text = 'foo';
+ $rootScope.$digest();
+
+ expect(element.html()).toBe('foo');
+ });
+
+ it('disables the "previous" link if current page is 1', function() {
+ updateCurrentPage(1);
+ expect(getPaginationEl(0)).toHaveClass('disabled');
+ });
+
+ it('disables the "next" link if current page is num-pages', function() {
+ updateCurrentPage(5);
+ expect(getPaginationEl(-1)).toHaveClass('disabled');
+ });
+
+ it('changes currentPage if the "previous" link is clicked', function() {
+ clickPaginationEl(0);
+ expect($rootScope.currentPage).toBe(2);
+ });
+
+ it('changes currentPage if the "next" link is clicked', function() {
+ clickPaginationEl(-1);
+ expect($rootScope.currentPage).toBe(4);
+ });
+
+ it('does not change the current page on "previous" click if already at first page', function() {
+ updateCurrentPage(1);
+ clickPaginationEl(0);
+ expect($rootScope.currentPage).toBe(1);
+ });
+
+ it('does not change the current page on "next" click if already at last page', function() {
+ updateCurrentPage(5);
+ clickPaginationEl(-1);
+ expect($rootScope.currentPage).toBe(5);
+ });
+
+ it('executes the `ng-change` expression when an element is clicked', function() {
+ $rootScope.selectPageHandler = jasmine.createSpy('selectPageHandler');
+ element = $compile('<uib-pager total-items="total" ng-model="currentPage" ng-change="selectPageHandler()"></uib-pager>')($rootScope);
+ $rootScope.$digest();
+
+ clickPaginationEl(-1);
+ expect($rootScope.selectPageHandler).toHaveBeenCalled();
+ });
+
+ it('does not changes the number of pages when `total-items` changes', function() {
+ $rootScope.total = 73; // 8 pages
+ $rootScope.$digest();
+
+ expect(getPaginationBarSize()).toBe(2);
+ expect(getPaginationEl(0).text()).toBe('« Previous');
+ expect(getPaginationEl(-1).text()).toBe('Next »');
+ });
+
+ it('should blur the "next" link after it has been clicked', function() {
+ body.append(element);
+ var linkEl = getPaginationLinkEl(element, -1);
+
+ linkEl.focus();
+ expect(linkEl).toHaveFocus();
+
+ linkEl.click();
+ expect(linkEl).not.toHaveFocus();
+
+ element.remove();
+ });
+
+ it('should blur the "prev" link after it has been clicked', function() {
+ body.append(element);
+ var linkEl = getPaginationLinkEl(element, -1);
+
+ linkEl.focus();
+ expect(linkEl).toHaveFocus();
+
+ linkEl.click();
+ expect(linkEl).not.toHaveFocus();
+
+ element.remove();
+ });
+
+ it('allows custom templates', function() {
+ $templateCache.put('foo/bar.html', '<div>baz</div>');
+
+ element = $compile('<pager template-url="foo/bar.html"></pager>')($rootScope);
+ $rootScope.$digest();
+
+ expect(element.html()).toBe('baz');
+ });
+
+ describe('`items-per-page`', function() {
+ beforeEach(function() {
+ $rootScope.perpage = 5;
+ element = $compile('<uib-pager total-items="total" items-per-page="perpage" ng-model="currentPage"></uib-pager>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('does not change the number of pages', function() {
+ expect(getPaginationBarSize()).toBe(2);
+ expect(getPaginationEl(0).text()).toBe('« Previous');
+ expect(getPaginationEl(-1).text()).toBe('Next »');
+ });
+
+ it('selects the last page when it is too big', function() {
+ $rootScope.perpage = 30;
+ $rootScope.$digest();
+
+ expect($rootScope.currentPage).toBe(2);
+ expect(getPaginationBarSize()).toBe(2);
+ expect(getPaginationEl(0)).not.toHaveClass('disabled');
+ expect(getPaginationEl(-1)).toHaveClass('disabled');
+ });
+ });
+
+ describe('when `page` is not a number', function() {
+ it('handles string', function() {
+ updateCurrentPage('1');
+ expect(getPaginationEl(0)).toHaveClass('disabled');
+
+ updateCurrentPage('05');
+ expect(getPaginationEl(-1)).toHaveClass('disabled');
+ });
+ });
+
+ describe('`num-pages`', function() {
+ beforeEach(function() {
+ $rootScope.numpg = null;
+ element = $compile('<uib-pager total-items="total" ng-model="currentPage" num-pages="numpg"></uib-pager>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('equals to total number of pages', function() {
+ expect($rootScope.numpg).toBe(5);
+ });
+ });
+
+ describe('setting `pagerConfig`', function() {
+ var originalConfig = {};
+ beforeEach(inject(function(uibPagerConfig) {
+ angular.extend(originalConfig, uibPagerConfig);
+ uibPagerConfig.previousText = 'PR';
+ uibPagerConfig.nextText = 'NE';
+ uibPagerConfig.align = false;
+ element = $compile('<uib-pager total-items="total" ng-model="currentPage"></uib-pager>')($rootScope);
+ $rootScope.$digest();
+ }));
+ afterEach(inject(function(uibPagerConfig) {
+ // return it to the original state
+ angular.extend(uibPagerConfig, originalConfig);
+ }));
+
+ it('should change paging text', function() {
+ expect(getPaginationEl(0).text()).toBe('PR');
+ expect(getPaginationEl(-1).text()).toBe('NE');
+ });
+
+ it('should not align previous & next page link', function() {
+ expect(getPaginationEl(0)).not.toHaveClass('previous');
+ expect(getPaginationEl(-1)).not.toHaveClass('next');
+ });
+ });
+
+ describe('override configuration from attributes', function() {
+ beforeEach(function() {
+ element = $compile('<uib-pager align="false" previous-text="<" next-text=">" total-items="total" ng-model="currentPage"></uib-pager>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('contains 2 li elements', function() {
+ expect(getPaginationBarSize()).toBe(2);
+ });
+
+ it('should change paging text from attributes', function() {
+ expect(getPaginationEl(0).text()).toBe('<');
+ expect(getPaginationEl(-1).text()).toBe('>');
+ });
+
+ it('should not align previous & next page link', function() {
+ expect(getPaginationEl(0)).not.toHaveClass('previous');
+ expect(getPaginationEl(-1)).not.toHaveClass('next');
+ });
+
+ it('changes "previous" & "next" text from interpolated attributes', function() {
+ $rootScope.previousText = '<<';
+ $rootScope.nextText = '>>';
+ element = $compile('<uib-pager align="false" previous-text="{{previousText}}" next-text="{{nextText}}" total-items="total" ng-model="currentPage"></uib-pager>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getPaginationEl(0).text()).toBe('<<');
+ expect(getPaginationEl(-1).text()).toBe('>>');
+ });
+ });
+
+ it('disables the component when ng-disabled is true', function() {
+ $rootScope.disable = true;
+
+ element = $compile('<uib-pager total-items="total" ng-disabled="disable" ng-model="currentPage"></uib-pager>')($rootScope);
+ $rootScope.$digest();
+ updateCurrentPage(2);
+
+ expect(getPaginationEl(0)).toHaveClass('disabled');
+ expect(getPaginationEl(-1)).toHaveClass('disabled');
+
+ $rootScope.disable = false;
+ $rootScope.$digest();
+
+ expect(getPaginationEl(0)).not.toHaveClass('disabled');
+ expect(getPaginationEl(-1)).not.toHaveClass('disabled');
+
+ $rootScope.disable = true;
+ $rootScope.$digest();
+
+ expect(getPaginationEl(0)).toHaveClass('disabled');
+ expect(getPaginationEl(-1)).toHaveClass('disabled');
+ });
+});
+
+describe('pager deprecation', function() {
+ beforeEach(module('ui.bootstrap.pagination'));
+ beforeEach(module('template/pagination/pager.html'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$paginationSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = $compile('<pager total-items="total" ng-model="currentPage"></pager>')($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = $compile('<pager total-items="total" ng-model="currentPage"></pager>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(2);
+ expect($log.warn.calls.argsFor(0)).toEqual(['PaginationController is now deprecated. Use UibPaginationController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['pager is now deprecated. Use uib-pager instead.']);
+ }));
+});
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/test/pagination.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/test/pagination.spec.js
new file mode 100644
index 0000000..a3ef250
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/pagination/test/pagination.spec.js
@@ -0,0 +1,766 @@
+describe('pagination directive', function() {
+ var $compile, $rootScope, $document, $templateCache, body, element;
+ beforeEach(module('ui.bootstrap.pagination'));
+ beforeEach(module('template/pagination/pagination.html'));
+ beforeEach(inject(function(_$compile_, _$rootScope_, _$document_, _$templateCache_) {
+ $compile = _$compile_;
+ $rootScope = _$rootScope_;
+ $rootScope.total = 47; // 5 pages
+ $rootScope.currentPage = 3;
+ $rootScope.disabled = false;
+ $document = _$document_;
+ $templateCache = _$templateCache_;
+ body = $document.find('body');
+ element = $compile('<uib-pagination total-items="total" ng-model="currentPage"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ function getPaginationBarSize() {
+ return element.find('li').length;
+ }
+
+ function getPaginationEl(index) {
+ return element.find('li').eq(index);
+ }
+
+ function clickPaginationEl(index) {
+ getPaginationEl(index).find('a').click();
+ }
+
+ function getPaginationLinkEl(elem, index) {
+ return elem.find('li').eq(index).find('a');
+ }
+
+ function updateCurrentPage(value) {
+ $rootScope.currentPage = value;
+ $rootScope.$digest();
+ }
+
+ function setDisabled(value) {
+ $rootScope.disabled = value;
+ $rootScope.$digest();
+ }
+
+ it('has a "pagination" css class', function() {
+ expect(element.hasClass('pagination')).toBe(true);
+ });
+
+ it('exposes the controller to the template', function() {
+ $templateCache.put('template/pagination/pagination.html', '<div>{{pagination.randomText}}</div>');
+ var scope = $rootScope.$new();
+
+ element = $compile('<uib-pagination></uib-pagination>')(scope);
+ $rootScope.$digest();
+
+ var ctrl = element.controller('uibPagination');
+
+ expect(ctrl).toBeDefined();
+
+ ctrl.randomText = 'foo';
+ $rootScope.$digest();
+
+ expect(element.html()).toBe('foo');
+ });
+
+ it('allows custom templates', function() {
+ $templateCache.put('foo/bar.html', '<div>baz</div>');
+ var scope = $rootScope.$new();
+
+ element = $compile('<uib-pagination template-url="foo/bar.html"></uib-pagination>')(scope);
+ $rootScope.$digest();
+
+ expect(element.html()).toBe('baz');
+ });
+
+ it('contains num-pages + 2 li elements', function() {
+ expect(getPaginationBarSize()).toBe(7);
+ expect(getPaginationEl(0).text()).toBe('Previous');
+ expect(getPaginationEl(-1).text()).toBe('Next');
+ });
+
+ it('has the number of the page as text in each page item', function() {
+ for (var i = 1; i <= 5; i++) {
+ expect(getPaginationEl(i).text()).toEqual(''+i);
+ }
+ });
+
+ it('sets the current page to be active', function() {
+ expect(getPaginationEl($rootScope.currentPage).hasClass('active')).toBe(true);
+ });
+
+ it('disables the "previous" link if current page is 1', function() {
+ updateCurrentPage(1);
+ expect(getPaginationEl(0).hasClass('disabled')).toBe(true);
+ });
+
+ it('disables the "next" link if current page is last', function() {
+ updateCurrentPage(5);
+ expect(getPaginationEl(-1).hasClass('disabled')).toBe(true);
+ });
+
+ it('changes currentPage if a page link is clicked', function() {
+ clickPaginationEl(2);
+ expect($rootScope.currentPage).toBe(2);
+ });
+
+ it('changes currentPage if the "previous" link is clicked', function() {
+ clickPaginationEl(0);
+ expect($rootScope.currentPage).toBe(2);
+ });
+
+ it('changes currentPage if the "next" link is clicked', function() {
+ clickPaginationEl(-1);
+ expect($rootScope.currentPage).toBe(4);
+ });
+
+ it('does not change the current page on "previous" click if already at first page', function() {
+ updateCurrentPage(1);
+ clickPaginationEl(0);
+ expect($rootScope.currentPage).toBe(1);
+ });
+
+ it('does not change the current page on "next" click if already at last page', function() {
+ updateCurrentPage(5);
+ clickPaginationEl(-1);
+ expect($rootScope.currentPage).toBe(5);
+ });
+
+ it('changes the number of pages when `total-items` changes', function() {
+ $rootScope.total = 78; // 8 pages
+ $rootScope.$digest();
+
+ expect(getPaginationBarSize()).toBe(10);
+ expect(getPaginationEl(0).text()).toBe('Previous');
+ expect(getPaginationEl(-1).text()).toBe('Next');
+ });
+
+ it('does not "break" when `total-items` is undefined', function() {
+ $rootScope.total = undefined;
+ $rootScope.$digest();
+
+ expect(getPaginationBarSize()).toBe(3); // Previous, 1, Next
+ expect(getPaginationEl(0)).toHaveClass('disabled');
+ expect(getPaginationEl(1)).toHaveClass('active');
+ expect(getPaginationEl(2)).toHaveClass('disabled');
+ });
+
+ it('does not "break" when `total-items` is negative', function() {
+ $rootScope.total = -1;
+ $rootScope.$digest();
+
+ expect(getPaginationBarSize()).toBe(3); // Previous, 1, Next
+ expect(getPaginationEl(0)).toHaveClass('disabled');
+ expect(getPaginationEl(1)).toHaveClass('active');
+ expect(getPaginationEl(2)).toHaveClass('disabled');
+ });
+
+ it('does not change the current page when `total-items` changes but is valid', function() {
+ $rootScope.currentPage = 1;
+ $rootScope.total = 18; // 2 pages
+ $rootScope.$digest();
+
+ expect($rootScope.currentPage).toBe(1);
+ });
+
+ it('should blur a page link after it has been clicked', function() {
+ body.append(element);
+ var linkEl = getPaginationLinkEl(element, 2);
+
+ linkEl.focus();
+ expect(linkEl).toHaveFocus();
+
+ linkEl.click();
+ expect(linkEl).not.toHaveFocus();
+
+ element.remove();
+ });
+
+ it('should blur the "next" link after it has been clicked', function() {
+ body.append(element);
+ var linkEl = getPaginationLinkEl(element, -1);
+
+ linkEl.focus();
+ expect(linkEl).toHaveFocus();
+
+ linkEl.click();
+ expect(linkEl).not.toHaveFocus();
+
+ element.remove();
+ });
+
+ it('should blur the "prev" link after it has been clicked', function() {
+ body.append(element);
+ var linkEl = getPaginationLinkEl(element, 0);
+
+ linkEl.focus();
+ expect(linkEl).toHaveFocus();
+
+ linkEl.click();
+ expect(linkEl).not.toHaveFocus();
+
+ element.remove();
+ });
+
+ describe('`items-per-page`', function() {
+ beforeEach(function() {
+ $rootScope.perpage = 5;
+ element = $compile('<uib-pagination total-items="total" items-per-page="perpage" ng-model="currentPage"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('changes the number of pages', function() {
+ expect(getPaginationBarSize()).toBe(12);
+ expect(getPaginationEl(0).text()).toBe('Previous');
+ expect(getPaginationEl(-1).text()).toBe('Next');
+ });
+
+ it('changes the number of pages when changes', function() {
+ $rootScope.perpage = 20;
+ $rootScope.$digest();
+
+ expect(getPaginationBarSize()).toBe(5);
+ expect(getPaginationEl(0).text()).toBe('Previous');
+ expect(getPaginationEl(-1).text()).toBe('Next');
+ });
+
+ it('selects the last page when current page is too big', function() {
+ $rootScope.perpage = 30;
+ $rootScope.$digest();
+
+ expect($rootScope.currentPage).toBe(2);
+ expect(getPaginationBarSize()).toBe(4);
+ expect(getPaginationEl(0).text()).toBe('Previous');
+ expect(getPaginationEl(-1).text()).toBe('Next');
+ });
+
+ it('displays a single page when it is negative', function() {
+ $rootScope.perpage = -1;
+ $rootScope.$digest();
+
+ expect(getPaginationBarSize()).toBe(3);
+ expect(getPaginationEl(0).text()).toBe('Previous');
+ expect(getPaginationEl(1).text()).toBe('1');
+ expect(getPaginationEl(-1).text()).toBe('Next');
+ });
+ });
+
+ describe('executes `ng-change` expression', function() {
+ beforeEach(function() {
+ $rootScope.selectPageHandler = jasmine.createSpy('selectPageHandler');
+ element = $compile('<uib-pagination total-items="total" ng-model="currentPage" ng-change="selectPageHandler()"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('when an element is clicked', function() {
+ clickPaginationEl(2);
+ expect($rootScope.selectPageHandler).toHaveBeenCalled();
+ });
+ });
+
+ describe('when `page` is not a number', function() {
+ it('handles numerical string', function() {
+ updateCurrentPage('2');
+ expect(getPaginationEl(2)).toHaveClass('active');
+
+ updateCurrentPage('04');
+ expect(getPaginationEl(4)).toHaveClass('active');
+ });
+
+ it('defaults to 1 if non-numeric', function() {
+ updateCurrentPage('pizza');
+ expect(getPaginationEl(1)).toHaveClass('active');
+ });
+ });
+
+ describe('with `max-size` option', function() {
+ beforeEach(function() {
+ $rootScope.total = 98; // 10 pages
+ $rootScope.currentPage = 3;
+ $rootScope.maxSize = 5;
+ element = $compile('<uib-pagination total-items="total" ng-model="currentPage" max-size="maxSize"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('contains maxsize + 2 li elements', function() {
+ expect(getPaginationBarSize()).toBe($rootScope.maxSize + 2);
+ expect(getPaginationEl(0).text()).toBe('Previous');
+ expect(getPaginationEl(-1).text()).toBe('Next');
+ });
+
+ it('shows the page number even if it can\'t be shown in the middle', function() {
+ updateCurrentPage(1);
+ expect(getPaginationEl(1)).toHaveClass('active');
+
+ updateCurrentPage(10);
+ expect(getPaginationEl(-2)).toHaveClass('active');
+ });
+
+ it('shows the page number in middle after the next link is clicked', function() {
+ updateCurrentPage(6);
+ clickPaginationEl(-1);
+
+ expect($rootScope.currentPage).toBe(7);
+ expect(getPaginationEl(3)).toHaveClass('active');
+ expect(getPaginationEl(3).text()).toBe(''+$rootScope.currentPage);
+ });
+
+ it('shows the page number in middle after the prev link is clicked', function() {
+ updateCurrentPage(7);
+ clickPaginationEl(0);
+
+ expect($rootScope.currentPage).toBe(6);
+ expect(getPaginationEl(3)).toHaveClass('active');
+ expect(getPaginationEl(3).text()).toBe(''+$rootScope.currentPage);
+ });
+
+ it('changes pagination bar size when max-size value changed', function() {
+ $rootScope.maxSize = 7;
+ $rootScope.$digest();
+ expect(getPaginationBarSize()).toBe(9);
+ });
+
+ it('sets the pagination bar size to num-pages, if max-size is greater than num-pages ', function() {
+ $rootScope.maxSize = 15;
+ $rootScope.$digest();
+ expect(getPaginationBarSize()).toBe(12);
+ });
+
+ it('should not change value of max-size expression, if max-size is greater than num-pages ', function() {
+ $rootScope.maxSize = 15;
+ $rootScope.$digest();
+ expect($rootScope.maxSize).toBe(15);
+ });
+
+ it('should not display page numbers, if max-size is zero', function() {
+ $rootScope.maxSize = 0;
+ $rootScope.$digest();
+ expect(getPaginationBarSize()).toBe(2);
+ expect(getPaginationEl(0).text()).toBe('Previous');
+ expect(getPaginationEl(-1).text()).toBe('Next');
+ });
+
+ it('should blur page link when visible range changes', function () {
+ body.append(element);
+ var linkEl = getPaginationLinkEl(element, 4);
+
+ linkEl.focus();
+ expect(linkEl).toHaveFocus();
+
+ linkEl.click();
+ expect(linkEl).not.toHaveFocus();
+
+ element.remove();
+ });
+ });
+
+ describe('with `max-size` option & no `rotate`', function() {
+ beforeEach(function() {
+ $rootScope.total = 115; // 12 pages
+ $rootScope.currentPage = 7;
+ $rootScope.maxSize = 5;
+ $rootScope.rotate = false;
+ element = $compile('<uib-pagination total-items="total" ng-model="currentPage" max-size="maxSize" rotate="rotate"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('contains maxsize + 4 elements', function() {
+ expect(getPaginationBarSize()).toBe($rootScope.maxSize + 4);
+ expect(getPaginationEl(0).text()).toBe('Previous');
+ expect(getPaginationEl(1).text()).toBe('...');
+ expect(getPaginationEl(2).text()).toBe('6');
+ expect(getPaginationEl(-3).text()).toBe('10');
+ expect(getPaginationEl(-2).text()).toBe('...');
+ expect(getPaginationEl(-1).text()).toBe('Next');
+ });
+
+ it('shows only the next ellipsis element on first page set', function() {
+ updateCurrentPage(3);
+ expect(getPaginationEl(1).text()).toBe('1');
+ expect(getPaginationEl(-3).text()).toBe('5');
+ expect(getPaginationEl(-2).text()).toBe('...');
+ });
+
+ it('shows only the previous ellipsis element on last page set', function() {
+ updateCurrentPage(12);
+ expect(getPaginationBarSize()).toBe(5);
+ expect(getPaginationEl(1).text()).toBe('...');
+ expect(getPaginationEl(2).text()).toBe('11');
+ expect(getPaginationEl(-2).text()).toBe('12');
+ });
+
+ it('moves to the previous set when first ellipsis is clicked', function() {
+ expect(getPaginationEl(1).text()).toBe('...');
+
+ clickPaginationEl(1);
+
+ expect($rootScope.currentPage).toBe(5);
+ expect(getPaginationEl(-3)).toHaveClass('active');
+ });
+
+ it('moves to the next set when last ellipsis is clicked', function() {
+ expect(getPaginationEl(-2).text()).toBe('...');
+
+ clickPaginationEl(-2);
+
+ expect($rootScope.currentPage).toBe(11);
+ expect(getPaginationEl(2)).toHaveClass('active');
+ });
+
+ it('should not display page numbers, if max-size is zero', function() {
+ $rootScope.maxSize = 0;
+ $rootScope.$digest();
+
+ expect(getPaginationBarSize()).toBe(2);
+ expect(getPaginationEl(0).text()).toBe('Previous');
+ expect(getPaginationEl(1).text()).toBe('Next');
+ });
+ });
+
+ describe('pagination directive with `boundary-links`', function() {
+ beforeEach(function() {
+ element = $compile('<uib-pagination boundary-links="true" total-items="total" ng-model="currentPage"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('contains num-pages + 4 li elements', function() {
+ expect(getPaginationBarSize()).toBe(9);
+ expect(getPaginationEl(0).text()).toBe('First');
+ expect(getPaginationEl(1).text()).toBe('Previous');
+ expect(getPaginationEl(-2).text()).toBe('Next');
+ expect(getPaginationEl(-1).text()).toBe('Last');
+ });
+
+ it('has first and last li elements visible', function() {
+ expect(getPaginationEl(0).css('display')).not.toBe('none');
+ expect(getPaginationEl(-1).css('display')).not.toBe('none');
+ });
+
+
+ it('disables the "first" & "previous" link if current page is 1', function() {
+ updateCurrentPage(1);
+
+ expect(getPaginationEl(0)).toHaveClass('disabled');
+ expect(getPaginationEl(1)).toHaveClass('disabled');
+ });
+
+ it('disables the "last" & "next" link if current page is num-pages', function() {
+ updateCurrentPage(5);
+
+ expect(getPaginationEl(-2)).toHaveClass('disabled');
+ expect(getPaginationEl(-1)).toHaveClass('disabled');
+ });
+
+ it('changes currentPage if the "first" link is clicked', function() {
+ clickPaginationEl(0);
+ expect($rootScope.currentPage).toBe(1);
+ });
+
+ it('changes currentPage if the "last" link is clicked', function() {
+ clickPaginationEl(-1);
+ expect($rootScope.currentPage).toBe(5);
+ });
+
+ it('does not change the current page on "first" click if already at first page', function() {
+ updateCurrentPage(1);
+ clickPaginationEl(0);
+ expect($rootScope.currentPage).toBe(1);
+ });
+
+ it('does not change the current page on "last" click if already at last page', function() {
+ updateCurrentPage(5);
+ clickPaginationEl(-1);
+ expect($rootScope.currentPage).toBe(5);
+ });
+
+ it('changes "first" & "last" text from attributes', function() {
+ element = $compile('<uib-pagination boundary-links="true" first-text="<<<" last-text=">>>" total-items="total" ng-model="currentPage"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getPaginationEl(0).text()).toBe('<<<');
+ expect(getPaginationEl(-1).text()).toBe('>>>');
+ });
+
+ it('changes "previous" & "next" text from attributes', function() {
+ element = $compile('<uib-pagination boundary-links="true" previous-text="<<" next-text=">>" total-items="total" ng-model="currentPage"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getPaginationEl(1).text()).toBe('<<');
+ expect(getPaginationEl(-2).text()).toBe('>>');
+ });
+
+ it('changes "first" & "last" text from interpolated attributes', function() {
+ $rootScope.myfirstText = '<<<';
+ $rootScope.mylastText = '>>>';
+ element = $compile('<uib-pagination boundary-links="true" first-text="{{myfirstText}}" last-text="{{mylastText}}" total-items="total" ng-model="currentPage"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getPaginationEl(0).text()).toBe('<<<');
+ expect(getPaginationEl(-1).text()).toBe('>>>');
+ });
+
+ it('changes "previous" & "next" text from interpolated attributes', function() {
+ $rootScope.previousText = '<<';
+ $rootScope.nextText = '>>';
+ element = $compile('<uib-pagination boundary-links="true" previous-text="{{previousText}}" next-text="{{nextText}}" total-items="total" ng-model="currentPage"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getPaginationEl(1).text()).toBe('<<');
+ expect(getPaginationEl(-2).text()).toBe('>>');
+ });
+
+ it('should blur the "first" link after it has been clicked', function() {
+ body.append(element);
+ var linkEl = getPaginationLinkEl(element, 0);
+
+ linkEl.focus();
+ expect(linkEl).toHaveFocus();
+
+ linkEl.click();
+ expect(linkEl).not.toHaveFocus();
+
+ element.remove();
+ });
+
+ it('should blur the "last" link after it has been clicked', function() {
+ body.append(element);
+ var linkEl = getPaginationLinkEl(element, -1);
+
+ linkEl.focus();
+ expect(linkEl).toHaveFocus();
+
+ linkEl.click();
+ expect(linkEl).not.toHaveFocus();
+
+ element.remove();
+ });
+ });
+
+ describe('pagination directive with just number links', function() {
+ beforeEach(function() {
+ element = $compile('<uib-pagination direction-links="false" total-items="total" ng-model="currentPage"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('contains num-pages li elements', function() {
+ expect(getPaginationBarSize()).toBe(5);
+ expect(getPaginationEl(0).text()).toBe('1');
+ expect(getPaginationEl(-1).text()).toBe('5');
+ });
+
+ it('has the number of the page as text in each page item', function() {
+ for(var i = 0; i < 5; i++) {
+ expect(getPaginationEl(i).text()).toEqual(''+(i+1));
+ }
+ });
+
+ it('sets the current page to be active', function() {
+ expect(getPaginationEl(2)).toHaveClass('active');
+ });
+
+ it('does not disable the "1" link if current page is 1', function() {
+ updateCurrentPage(1);
+
+ expect(getPaginationEl(0)).not.toHaveClass('disabled');
+ expect(getPaginationEl(0)).toHaveClass('active');
+ });
+
+ it('does not disable the "last" link if current page is last page', function() {
+ updateCurrentPage(5);
+
+ expect(getPaginationEl(-1)).not.toHaveClass('disabled');
+ expect(getPaginationEl(-1)).toHaveClass('active');
+ });
+
+ it('changes currentPage if a page link is clicked', function() {
+ clickPaginationEl(1);
+ expect($rootScope.currentPage).toBe(2);
+ });
+
+ it('changes the number of items when total items changes', function() {
+ $rootScope.total = 73; // 8 pages
+ $rootScope.$digest();
+
+ expect(getPaginationBarSize()).toBe(8);
+ expect(getPaginationEl(0).text()).toBe('1');
+ expect(getPaginationEl(-1).text()).toBe('8');
+ });
+ });
+
+ describe('with just boundary & number links', function() {
+ beforeEach(function() {
+ $rootScope.directions = false;
+ element = $compile('<uib-pagination boundary-links="true" direction-links="directions" total-items="total" ng-model="currentPage"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('contains number of pages + 2 li elements', function() {
+ expect(getPaginationBarSize()).toBe(7);
+ expect(getPaginationEl(0).text()).toBe('First');
+ expect(getPaginationEl(1).text()).toBe('1');
+ expect(getPaginationEl(-2).text()).toBe('5');
+ expect(getPaginationEl(-1).text()).toBe('Last');
+ });
+
+ it('disables the "first" & activates "1" link if current page is 1', function() {
+ updateCurrentPage(1);
+
+ expect(getPaginationEl(0)).toHaveClass('disabled');
+ expect(getPaginationEl(1)).not.toHaveClass('disabled');
+ expect(getPaginationEl(1)).toHaveClass('active');
+ });
+
+ it('disables the "last" & "next" link if current page is num-pages', function() {
+ updateCurrentPage(5);
+
+ expect(getPaginationEl(-2)).toHaveClass('active');
+ expect(getPaginationEl(-2)).not.toHaveClass('disabled');
+ expect(getPaginationEl(-1)).toHaveClass('disabled');
+ });
+ });
+
+ describe('`num-pages`', function () {
+ beforeEach(function() {
+ $rootScope.numpg = null;
+ element = $compile('<uib-pagination total-items="total" ng-model="currentPage" num-pages="numpg"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('equals to total number of pages', function() {
+ expect($rootScope.numpg).toBe(5);
+ });
+
+ it('changes when total number of pages change', function() {
+ $rootScope.total = 73; // 8 pages
+ $rootScope.$digest();
+ expect($rootScope.numpg).toBe(8);
+ });
+
+ it('shows minimun one page if total items are not defined and does not break binding', function() {
+ $rootScope.total = undefined;
+ $rootScope.$digest();
+ expect($rootScope.numpg).toBe(1);
+
+ $rootScope.total = 73; // 8 pages
+ $rootScope.$digest();
+ expect($rootScope.numpg).toBe(8);
+ });
+ });
+
+ describe('setting `paginationConfig`', function() {
+ var originalConfig, paginationConfig;
+ beforeEach(inject(function(_uibPaginationConfig_) {
+ originalConfig = angular.copy(_uibPaginationConfig_);
+ paginationConfig = _uibPaginationConfig_;
+ }));
+ afterEach(inject(function(_uibPaginationConfig_) {
+ // return it to the original stat
+ angular.copy(originalConfig, _uibPaginationConfig_);
+ }));
+
+ it('should change paging text', function() {
+ paginationConfig.boundaryLinks = true;
+ paginationConfig.directionLinks = true;
+ paginationConfig.firstText = 'FI';
+ paginationConfig.previousText = 'PR';
+ paginationConfig.nextText = 'NE';
+ paginationConfig.lastText = 'LA';
+ element = $compile('<uib-pagination total-items="total" ng-model="currentPage"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getPaginationEl(0).text()).toBe('FI');
+ expect(getPaginationEl(1).text()).toBe('PR');
+ expect(getPaginationEl(-2).text()).toBe('NE');
+ expect(getPaginationEl(-1).text()).toBe('LA');
+ });
+
+ it('contains number of pages + 2 li elements', function() {
+ paginationConfig.itemsPerPage = 5;
+ element = $compile('<uib-pagination total-items="total" ng-model="currentPage"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getPaginationBarSize()).toBe(12);
+ });
+
+ it('should take maxSize defaults into account', function() {
+ paginationConfig.maxSize = 2;
+ element = $compile('<uib-pagination total-items="total" ng-model="currentPage"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getPaginationBarSize()).toBe(4);
+ });
+ });
+
+ describe('override configuration from attributes', function() {
+ beforeEach(function() {
+ element = $compile('<uib-pagination boundary-links="true" first-text="<<" previous-text="<" next-text=">" last-text=">>" total-items="total" ng-model="currentPage"></uib-pagination>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('contains number of pages + 4 li elements', function() {
+ expect(getPaginationBarSize()).toBe(9);
+ });
+
+ it('should change paging text from attribute', function() {
+ expect(getPaginationEl(0).text()).toBe('<<');
+ expect(getPaginationEl(1).text()).toBe('<');
+ expect(getPaginationEl(-2).text()).toBe('>');
+ expect(getPaginationEl(-1).text()).toBe('>>');
+ });
+ });
+
+ describe('disabled with ngDisable', function() {
+ beforeEach(function() {
+ element = $compile('<uib-pagination total-items="total" ng-model="currentPage" ng-disabled="disabled"></uib-pagination>')($rootScope);
+ $rootScope.currentPage = 3;
+ $rootScope.$digest();
+ });
+
+ it('should not respond to clicking', function() {
+ setDisabled(true);
+ clickPaginationEl(2);
+ expect($rootScope.currentPage).toBe(3);
+ setDisabled(false);
+ clickPaginationEl(2);
+ expect($rootScope.currentPage).toBe(2);
+ });
+
+ it('should change the class of all buttons except selected one', function() {
+ setDisabled(false);
+ expect(getPaginationEl(3).hasClass('active')).toBe(true);
+ expect(getPaginationEl(4).hasClass('active')).toBe(false);
+ setDisabled(true);
+ expect(getPaginationEl(3).hasClass('disabled')).toBe(false);
+ expect(getPaginationEl(4).hasClass('disabled')).toBe(true);
+ });
+ });
+});
+
+describe('pagination deprecation', function() {
+ beforeEach(module('ui.bootstrap.pagination'));
+ beforeEach(module('template/pagination/pagination.html'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$paginationSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = $compile('<pagination></pagination>')($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = $compile('<pagination></pagination>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(2);
+ expect($log.warn.calls.argsFor(0)).toEqual(['PaginationController is now deprecated. Use UibPaginationController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['pagination is now deprecated. Use uib-pagination instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/docs/demo.html
new file mode 100644
index 0000000..bb90429
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/docs/demo.html
@@ -0,0 +1,44 @@
+<div ng-controller="PopoverDemoCtrl">
+ <h4>Dynamic</h4>
+ <div class="form-group">
+ <label>Popup Text:</label>
+ <input type="text" ng-model="dynamicPopover.content" class="form-control">
+ </div>
+ <div class="form-group">
+ <label>Popup Title:</label>
+ <input type="text" ng-model="dynamicPopover.title" class="form-control">
+ </div>
+ <div class="form-group">
+ <label>Popup Template:</label>
+ <input type="text" ng-model="dynamicPopover.templateUrl" class="form-control">
+ </div>
+ <button uib-popover="{{dynamicPopover.content}}" popover-title="{{dynamicPopover.title}}" type="button" class="btn btn-default">Dynamic Popover</button>
+
+ <button uib-popover-template="dynamicPopover.templateUrl" popover-title="{{dynamicPopover.title}}" type="button" class="btn btn-default">Popover With Template</button>
+
+ <script type="text/ng-template" id="myPopoverTemplate.html">
+ <div>{{dynamicPopover.content}}</div>
+ <div class="form-group">
+ <label>Popup Title:</label>
+ <input type="text" ng-model="dynamicPopover.title" class="form-control">
+ </div>
+ </script>
+ <hr />
+ <h4>Positional</h4>
+ <button popover-placement="top" uib-popover="On the Top!" type="button" class="btn btn-default">Top</button>
+ <button popover-placement="left" uib-popover="On the Left!" type="button" class="btn btn-default">Left</button>
+ <button popover-placement="right" uib-popover="On the Right!" type="button" class="btn btn-default">Right</button>
+ <button popover-placement="bottom" uib-popover="On the Bottom!" type="button" class="btn btn-default">Bottom</button>
+
+ <hr />
+ <h4>Triggers</h4>
+ <p>
+ <button uib-popover="I appeared on mouse enter!" popover-trigger="mouseenter" type="button" class="btn btn-default">Mouseenter</button>
+ </p>
+ <input type="text" value="Click me!" uib-popover="I appeared on focus! Click away and I'll vanish..." popover-trigger="focus" class="form-control">
+
+ <hr />
+ <h4>Other</h4>
+ <button popover-animation="true" uib-popover="I fade in and out!" type="button" class="btn btn-default">fading</button>
+ <button uib-popover="I have a title!" popover-title="The title." type="button" class="btn btn-default">title</button>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/docs/demo.js
new file mode 100644
index 0000000..0d94f28
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/docs/demo.js
@@ -0,0 +1,7 @@
+angular.module('ui.bootstrap.demo').controller('PopoverDemoCtrl', function ($scope) {
+ $scope.dynamicPopover = {
+ content: 'Hello, World!',
+ templateUrl: 'myPopoverTemplate.html',
+ title: 'Title'
+ };
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/docs/readme.md
new file mode 100644
index 0000000..5f91772
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/docs/readme.md
@@ -0,0 +1,49 @@
+A lightweight, extensible directive for fancy popover creation. The popover
+directive supports multiple placements, optional transition animation, and more.
+
+Like the Bootstrap jQuery plugin, the popover **requires** the tooltip
+module.
+
+There are two versions of the popover: `uib-popover` and `uib-popover-template`:
+
+- `uib-popover` takes text only and will escape any HTML provided for the popover
+ body.
+- `uib-popover-html` takes an expression that evaluates to an html string. *The user is responsible for ensuring the
+ content is safe to put into the DOM!*
+- `uib-popover-template` a URL representing the location of a template to
+ use for the popover body. Note that the contents of this template need to be
+ wrapped in a tag, e.g., `<div></div>`.
+
+The popover directives provides several optional attributes to control how it
+will display:
+
+- `popover-title`: A string to display as a fancy title.
+- `popover-placement`: Where to place it? Defaults to "top", but also accepts
+ "bottom", "left", "right".
+- `popover-animation`: Should it fade in and out? Defaults to "true".
+- `popover-popup-delay`: For how long should the user have to have the mouse
+ over the element before the popover shows (in milliseconds)? Defaults to 0.
+- `popover-popup-close-delay`: For how long should the popover remain open
+ after the close trigger event? Defaults to 0.
+- `popover-trigger`: What should trigger the show of the popover? See the
+ `tooltip` directive for supported values.
+- `popover-append-to-body`: Should the tooltip be appended to `$body` instead of
+ the parent element?
+- `popover-is-open` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Default: false)_:
+ Whether to show the popover.
+
+The popover directives require the `$position` service.
+
+The popover directive also supports various default configurations through the
+$tooltipProvider. See the [tooltip](#tooltip) section for more information.
+
+**Known issues**
+
+For Safari 7+ support, if you want to use **focus** `popover-trigger`, you need to use an anchor tag with a tab index. For example:
+
+```
+<a tabindex="0" uib-popover="Test" popover-trigger="focus" class="btn btn-default">
+ Click Me
+</a>
+```
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/popover.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/popover.js
new file mode 100644
index 0000000..bc46086
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/popover.js
@@ -0,0 +1,125 @@
+/**
+ * The following features are still outstanding: popup delay, animation as a
+ * function, placement as a function, inside, support for more triggers than
+ * just mouse enter/leave, and selector delegatation.
+ */
+angular.module('ui.bootstrap.popover', ['ui.bootstrap.tooltip'])
+
+.directive('uibPopoverTemplatePopup', function() {
+ return {
+ replace: true,
+ scope: { title: '@', contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&',
+ originScope: '&' },
+ templateUrl: 'template/popover/popover-template.html',
+ link: function(scope, element) {
+ element.addClass('popover');
+ }
+ };
+})
+
+.directive('uibPopoverTemplate', ['$uibTooltip', function($uibTooltip) {
+ return $uibTooltip('uibPopoverTemplate', 'popover', 'click', {
+ useContentExp: true
+ });
+}])
+
+.directive('uibPopoverHtmlPopup', function() {
+ return {
+ replace: true,
+ scope: { contentExp: '&', title: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
+ templateUrl: 'template/popover/popover-html.html',
+ link: function(scope, element) {
+ element.addClass('popover');
+ }
+ };
+})
+
+.directive('uibPopoverHtml', ['$uibTooltip', function($uibTooltip) {
+ return $uibTooltip('uibPopoverHtml', 'popover', 'click', {
+ useContentExp: true
+ });
+}])
+
+.directive('uibPopoverPopup', function() {
+ return {
+ replace: true,
+ scope: { title: '@', content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
+ templateUrl: 'template/popover/popover.html',
+ link: function(scope, element) {
+ element.addClass('popover');
+ }
+ };
+})
+
+.directive('uibPopover', ['$uibTooltip', function($uibTooltip) {
+ return $uibTooltip('uibPopover', 'popover', 'click');
+}]);
+
+/* Deprecated popover below */
+
+angular.module('ui.bootstrap.popover')
+
+.value('$popoverSuppressWarning', false)
+
+.directive('popoverTemplatePopup', ['$log', '$popoverSuppressWarning', function($log, $popoverSuppressWarning) {
+ return {
+ replace: true,
+ scope: { title: '@', contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&',
+ originScope: '&' },
+ templateUrl: 'template/popover/popover-template.html',
+ link: function(scope, element) {
+ if (!$popoverSuppressWarning) {
+ $log.warn('popover-template-popup is now deprecated. Use uib-popover-template-popup instead.');
+ }
+
+ element.addClass('popover');
+ }
+ };
+}])
+
+.directive('popoverTemplate', ['$tooltip', function($tooltip) {
+ return $tooltip('popoverTemplate', 'popover', 'click', {
+ useContentExp: true
+ });
+}])
+
+.directive('popoverHtmlPopup', ['$log', '$popoverSuppressWarning', function($log, $popoverSuppressWarning) {
+ return {
+ replace: true,
+ scope: { contentExp: '&', title: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
+ templateUrl: 'template/popover/popover-html.html',
+ link: function(scope, element) {
+ if (!$popoverSuppressWarning) {
+ $log.warn('popover-html-popup is now deprecated. Use uib-popover-html-popup instead.');
+ }
+
+ element.addClass('popover');
+ }
+ };
+}])
+
+.directive('popoverHtml', ['$tooltip', function($tooltip) {
+ return $tooltip('popoverHtml', 'popover', 'click', {
+ useContentExp: true
+ });
+}])
+
+.directive('popoverPopup', ['$log', '$popoverSuppressWarning', function($log, $popoverSuppressWarning) {
+ return {
+ replace: true,
+ scope: { title: '@', content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
+ templateUrl: 'template/popover/popover.html',
+ link: function(scope, element) {
+ if (!$popoverSuppressWarning) {
+ $log.warn('popover-popup is now deprecated. Use uib-popover-popup instead.');
+ }
+
+ element.addClass('popover');
+ }
+ };
+}])
+
+.directive('popover', ['$tooltip', function($tooltip) {
+
+ return $tooltip('popover', 'popover', 'click');
+}]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/test/popover-html.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/test/popover-html.spec.js
new file mode 100644
index 0000000..9c59daa
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/test/popover-html.spec.js
@@ -0,0 +1,250 @@
+describe('popover', function() {
+ var elm,
+ elmBody,
+ scope,
+ elmScope,
+ tooltipScope;
+
+ // load the popover code
+ beforeEach(module('ui.bootstrap.popover'));
+
+ // load the template
+ beforeEach(module('template/popover/popover-html.html'));
+
+ beforeEach(inject(function($rootScope, $compile, $sce) {
+ elmBody = angular.element(
+ '<div><span uib-popover-html="template">Selector Text</span></div>'
+ );
+
+ scope = $rootScope;
+ scope.template = $sce.trustAsHtml('<span>My template</span>');
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ }));
+
+ it('should not be open initially', inject(function() {
+ expect(tooltipScope.isOpen).toBe(false);
+
+ // We can only test *that* the popover-popup element wasn't created as the
+ // implementation is templated and replaced.
+ expect(elmBody.children().length).toBe(1);
+ }));
+
+ it('should open on click', inject(function() {
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ // We can only test *that* the popover-popup element was created as the
+ // implementation is templated and replaced.
+ expect(elmBody.children().length).toBe(2);
+ }));
+
+ it('should close on second click', inject(function() {
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(false);
+ }));
+
+ it('should not open on click if template is empty', inject(function() {
+ scope.template = null;
+ scope.$digest();
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(false);
+
+ expect(elmBody.children().length).toBe(1);
+ }));
+
+ it('should show updated text', inject(function($sce) {
+ scope.template = $sce.trustAsHtml('<span>My template</span>');
+ scope.$digest();
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ expect(elmBody.children().eq(1).text().trim()).toBe('My template');
+
+ scope.template = $sce.trustAsHtml('<span>Another template</span>');
+ scope.$digest();
+
+ expect(elmBody.children().eq(1).text().trim()).toBe('Another template');
+ }));
+
+ it('should hide popover when template becomes empty', inject(function($timeout) {
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ scope.template = '';
+ scope.$digest();
+
+ expect(tooltipScope.isOpen).toBe(false);
+
+ $timeout.flush();
+ expect(elmBody.children().length).toBe(1);
+ }));
+
+
+ it('should not unbind event handlers created by other directives - issue 456', inject(function($compile) {
+ scope.click = function() {
+ scope.clicked = !scope.clicked;
+ };
+
+ elmBody = angular.element(
+ '<div><input uib-popover-html="template" ng-click="click()" popover-trigger="mouseenter"/></div>'
+ );
+ $compile(elmBody)(scope);
+ scope.$digest();
+
+ elm = elmBody.find('input');
+
+ elm.trigger('mouseenter');
+ tooltipScope.$digest();
+ elm.trigger('mouseleave');
+ tooltipScope.$digest();
+ expect(scope.clicked).toBeFalsy();
+
+ elm.click();
+ expect(scope.clicked).toBeTruthy();
+ }));
+
+ it('should popup with animate class by default', inject(function() {
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ expect(elmBody.children().eq(1)).toHaveClass('fade');
+ }));
+
+ it('should popup without animate class when animation disabled', inject(function($compile) {
+ elmBody = angular.element(
+ '<div><span uib-popover-html="template" popover-animation="false">Selector Text</span></div>'
+ );
+
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+ expect(elmBody.children().eq(1)).not.toHaveClass('fade');
+ }));
+
+ describe('supports options', function() {
+ describe('placement', function() {
+ it('can specify an alternative, valid placement', inject(function($compile) {
+ elmBody = angular.element(
+ '<div><span uib-popover-html="template" popover-placement="left">Trigger here</span></div>'
+ );
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ expect(elmBody.children().length).toBe(2);
+ var ttipElement = elmBody.find('div.popover');
+ expect(ttipElement).toHaveClass('left');
+ }));
+
+ });
+
+ describe('class', function() {
+ it('can specify a custom class', inject(function($compile) {
+ elmBody = angular.element(
+ '<div><span uib-popover-html="template" popover-class="custom">Trigger here</span></div>'
+ );
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ expect(elmBody.children().length).toBe(2);
+ var ttipElement = elmBody.find('div.popover');
+ expect(ttipElement).toHaveClass('custom');
+ }));
+ });
+ });
+});
+
+/* Deprecation tests below */
+
+describe('popover deprecation', function() {
+ beforeEach(module('ui.bootstrap.popover'));
+ beforeEach(module('template/popover/popover-html.html'));
+
+ var elm, elmBody, elmScope, tooltipScope;
+
+ function trigger(element, evt) {
+ evt = new Event(evt);
+
+ element[0].dispatchEvent(evt);
+ element.scope().$$childTail.$digest();
+ }
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$popoverSuppressWarning', true);
+ $provide.value('$tooltipSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope, $sce) {
+ spyOn($log, 'warn');
+
+ $rootScope.html = 'I say: <strong class="hello">Hello!</strong>';
+ $rootScope.safeHtml = $sce.trustAsHtml($rootScope.html);
+ elmBody = angular.element('<div><span popover-html="safeHtml">Selector Text</span></div>');
+ $compile(elmBody)($rootScope);
+ $rootScope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ trigger(elm, 'mouseenter');
+ tooltipScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope, $sce) {
+ spyOn($log, 'warn');
+
+ $rootScope.html = 'I say: <strong class="hello">Hello!</strong>';
+ $rootScope.safeHtml = $sce.trustAsHtml($rootScope.html);
+ elmBody = angular.element('<div><span popover-html="safeHtml">Selector Text</span></div>');
+ $compile(elmBody)($rootScope);
+ $rootScope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(2);
+ expect($log.warn.calls.argsFor(0)).toEqual(['$tooltip is now deprecated. Use $uibTooltip instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['popover-html-popup is now deprecated. Use uib-popover-html-popup instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/test/popover-template.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/test/popover-template.spec.js
new file mode 100644
index 0000000..347f869
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/test/popover-template.spec.js
@@ -0,0 +1,180 @@
+describe('popover template', function() {
+ var elm,
+ elmBody,
+ scope,
+ elmScope,
+ tooltipScope;
+
+ // load the popover code
+ beforeEach(module('ui.bootstrap.popover'));
+
+ // load the template
+ beforeEach(module('template/popover/popover.html'));
+ beforeEach(module('template/popover/popover-template.html'));
+
+ beforeEach(inject(function($templateCache) {
+ $templateCache.put('myUrl', [200, '<span>{{ myTemplateText }}</span>', {}]);
+ }));
+
+ beforeEach(inject(function($rootScope, $compile) {
+ elmBody = angular.element(
+ '<div><span uib-popover-template="templateUrl">Selector Text</span></div>'
+ );
+
+ scope = $rootScope;
+ $compile(elmBody)(scope);
+ scope.templateUrl = 'myUrl';
+
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ }));
+
+ it('should open on click', inject(function() {
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ expect(elmBody.children().length ).toBe(2);
+ }));
+
+ it('should not open on click if templateUrl is empty', inject(function() {
+ scope.templateUrl = null;
+ scope.$digest();
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(false);
+
+ expect(elmBody.children().length).toBe(1);
+ }));
+
+ it('should show updated text', inject(function() {
+ scope.myTemplateText = 'some text';
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ scope.$digest();
+ expect(elmBody.children().eq(1).text().trim()).toBe('some text');
+
+ scope.myTemplateText = 'new text';
+ scope.$digest();
+
+ expect(elmBody.children().eq(1).text().trim()).toBe('new text');
+ }));
+
+ it('should hide popover when template becomes empty', inject(function($timeout) {
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ scope.templateUrl = '';
+ scope.$digest();
+
+ expect(tooltipScope.isOpen).toBe(false);
+
+ $timeout.flush();
+ expect(elmBody.children().length).toBe(1);
+ }));
+
+ describe('supports options', function() {
+ describe('placement', function() {
+ it('can specify an alternative, valid placement', inject(function($compile) {
+ elmBody = angular.element(
+ '<div><span uib-popover-template="templateUrl" popover-placement="left">Trigger</span></div>'
+ );
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ expect(elmBody.children().length).toBe(2);
+ var ttipElement = elmBody.find('div.popover');
+ expect(ttipElement).toHaveClass('left');
+ }));
+
+ });
+
+ describe('class', function() {
+ it('can specify a custom class', inject(function($compile) {
+ elmBody = angular.element(
+ '<div><span uib-popover-template="templateUrl" popover-class="custom">Trigger</span></div>'
+ );
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ expect(elmBody.children().length).toBe(2);
+ var ttipElement = elmBody.find('div.popover');
+ expect(ttipElement).toHaveClass('custom');
+ }));
+ });
+ });
+});
+
+/* Deprecation tests below */
+
+describe('popover template deprecation', function() {
+ beforeEach(module('ui.bootstrap.popover'));
+ beforeEach(module('template/popover/popover.html'));
+ beforeEach(module('template/popover/popover-template.html'));
+
+ var elm, elmBody, elmScope, tooltipScope;
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$popoverSuppressWarning', true);
+ $provide.value('$tooltipSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope, $templateCache) {
+ spyOn($log, 'warn');
+ $templateCache.put('myUrl', [200, '<span>{{ myTemplateText }}</span>', {}]);
+ $rootScope.templateUrl = 'myUrl';
+
+ elmBody = angular.element('<div><span popover-template="templateUrl">Selector Text</span></div>');
+ $compile(elmBody)($rootScope);
+ $rootScope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope, $templateCache) {
+ spyOn($log, 'warn');
+ $templateCache.put('myUrl', [200, '<span>{{ myTemplateText }}</span>', {}]);
+ $rootScope.templateUrl = 'myUrl';
+
+ elmBody = angular.element('<div><span popover-template="templateUrl">Selector Text</span></div>');
+ $compile(elmBody)($rootScope);
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(2);
+ expect($log.warn.calls.argsFor(0)).toEqual(['$tooltip is now deprecated. Use $uibTooltip instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['popover-template-popup is now deprecated. Use uib-popover-template-popup instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/test/popover.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/test/popover.spec.js
new file mode 100644
index 0000000..4ba0677
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/popover/test/popover.spec.js
@@ -0,0 +1,226 @@
+describe('popover', function() {
+ var elm,
+ elmBody,
+ scope,
+ elmScope,
+ tooltipScope;
+
+ // load the popover code
+ beforeEach(module('ui.bootstrap.popover'));
+
+ // load the template
+ beforeEach(module('template/popover/popover.html'));
+
+ beforeEach(inject(function($rootScope, $compile) {
+ elmBody = angular.element(
+ '<div><span uib-popover="popover text">Selector Text</span></div>'
+ );
+
+ scope = $rootScope;
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ }));
+
+ it('should not be open initially', inject(function() {
+ expect(tooltipScope.isOpen).toBe(false);
+
+ // We can only test *that* the popover-popup element wasn't created as the
+ // implementation is templated and replaced.
+ expect(elmBody.children().length).toBe(1);
+ }));
+
+ it('should open on click', inject(function() {
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ // We can only test *that* the popover-popup element was created as the
+ // implementation is templated and replaced.
+ expect(elmBody.children().length).toBe(2);
+ }));
+
+ it('should close on second click', inject(function() {
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(false);
+ }));
+
+ it('should not unbind event handlers created by other directives - issue 456', inject(function($compile) {
+ scope.click = function() {
+ scope.clicked = !scope.clicked;
+ };
+
+ elmBody = angular.element(
+ '<div><input uib-popover="Hello!" ng-click="click()" popover-trigger="mouseenter"/></div>'
+ );
+ $compile(elmBody)(scope);
+ scope.$digest();
+
+ elm = elmBody.find('input');
+
+ elm.trigger('mouseenter');
+ elm.trigger('mouseleave');
+ expect(scope.clicked).toBeFalsy();
+
+ elm.click();
+ expect(scope.clicked).toBeTruthy();
+ }));
+
+ it('should popup with animate class by default', inject(function() {
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ expect(elmBody.children().eq(1)).toHaveClass('fade');
+ }));
+
+ it('should popup without animate class when animation disabled', inject(function($compile) {
+ elmBody = angular.element(
+ '<div><span uib-popover="popover text" popover-animation="false">Selector Text</span></div>'
+ );
+
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+ expect(elmBody.children().eq(1)).not.toHaveClass('fade');
+ }));
+
+ describe('supports options', function() {
+ describe('placement', function() {
+ it('can specify an alternative, valid placement', inject(function($compile) {
+ elmBody = angular.element(
+ '<div><span uib-popover="popover text" popover-placement="left">Trigger here</span></div>'
+ );
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ expect(elmBody.children().length).toBe(2);
+ var ttipElement = elmBody.find('div.popover');
+ expect(ttipElement).toHaveClass('left');
+ }));
+ });
+
+ describe('class', function() {
+ it('can specify a custom class', inject(function($compile) {
+ elmBody = angular.element(
+ '<div><span uib-popover="popover text" popover-class="custom">Trigger here</span></div>'
+ );
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+
+ expect(elmBody.children().length).toBe(2);
+ var ttipElement = elmBody.find('div.popover');
+ expect(ttipElement).toHaveClass('custom');
+ }));
+ });
+
+ describe('is-open', function() {
+ beforeEach(inject(function ($compile) {
+ scope.isOpen = false;
+ elmBody = angular.element(
+ '<div><span uib-popover="popover text" popover-placement="left" popover-is-open="isOpen">Trigger here</span></div>'
+ );
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ }));
+
+ it('should show and hide with the controller value', function() {
+ expect(tooltipScope.isOpen).toBe(false);
+ elmScope.isOpen = true;
+ elmScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+ elmScope.isOpen = false;
+ elmScope.$digest();
+ expect(tooltipScope.isOpen).toBe(false);
+ });
+
+ it('should update the controller value', function() {
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(elmScope.isOpen).toBe(true);
+ elm.trigger('click');
+ tooltipScope.$digest();
+ expect(elmScope.isOpen).toBe(false);
+ });
+ });
+ });
+});
+
+/* Deprecation tests below */
+
+describe('popover deprecation', function() {
+ beforeEach(module('ui.bootstrap.popover'));
+ beforeEach(module('template/popover/popover.html'));
+
+ var elm, elmBody, elmScope, tooltipScope;
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$popoverSuppressWarning', true);
+ $provide.value('$tooltipSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ elmBody = angular.element('<div><span popover="popover text">Selector Text</span></div>');
+ $compile(elmBody)($rootScope);
+ $rootScope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ elmBody = angular.element('<div><span popover="popover text">Selector Text</span></div>');
+ $compile(elmBody)($rootScope);
+ $rootScope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ elm.trigger('click');
+ tooltipScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(2);
+ expect($log.warn.calls.argsFor(0)).toEqual(['$tooltip is now deprecated. Use $uibTooltip instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['popover-popup is now deprecated. Use uib-popover-popup instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/position/position.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/position/position.js
new file mode 100644
index 0000000..0502053
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/position/position.js
@@ -0,0 +1,164 @@
+angular.module('ui.bootstrap.position', [])
+
+/**
+ * A set of utility methods that can be use to retrieve position of DOM elements.
+ * It is meant to be used where we need to absolute-position DOM elements in
+ * relation to other, existing elements (this is the case for tooltips, popovers,
+ * typeahead suggestions etc.).
+ */
+ .factory('$uibPosition', ['$document', '$window', function($document, $window) {
+ function getStyle(el, cssprop) {
+ if (el.currentStyle) { //IE
+ return el.currentStyle[cssprop];
+ } else if ($window.getComputedStyle) {
+ return $window.getComputedStyle(el)[cssprop];
+ }
+ // finally try and get inline style
+ return el.style[cssprop];
+ }
+
+ /**
+ * Checks if a given element is statically positioned
+ * @param element - raw DOM element
+ */
+ function isStaticPositioned(element) {
+ return (getStyle(element, 'position') || 'static' ) === 'static';
+ }
+
+ /**
+ * returns the closest, non-statically positioned parentOffset of a given element
+ * @param element
+ */
+ var parentOffsetEl = function(element) {
+ var docDomEl = $document[0];
+ var offsetParent = element.offsetParent || docDomEl;
+ while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) {
+ offsetParent = offsetParent.offsetParent;
+ }
+ return offsetParent || docDomEl;
+ };
+
+ return {
+ /**
+ * Provides read-only equivalent of jQuery's position function:
+ * http://api.jquery.com/position/
+ */
+ position: function(element) {
+ var elBCR = this.offset(element);
+ var offsetParentBCR = { top: 0, left: 0 };
+ var offsetParentEl = parentOffsetEl(element[0]);
+ if (offsetParentEl != $document[0]) {
+ offsetParentBCR = this.offset(angular.element(offsetParentEl));
+ offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;
+ offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;
+ }
+
+ var boundingClientRect = element[0].getBoundingClientRect();
+ return {
+ width: boundingClientRect.width || element.prop('offsetWidth'),
+ height: boundingClientRect.height || element.prop('offsetHeight'),
+ top: elBCR.top - offsetParentBCR.top,
+ left: elBCR.left - offsetParentBCR.left
+ };
+ },
+
+ /**
+ * Provides read-only equivalent of jQuery's offset function:
+ * http://api.jquery.com/offset/
+ */
+ offset: function(element) {
+ var boundingClientRect = element[0].getBoundingClientRect();
+ return {
+ width: boundingClientRect.width || element.prop('offsetWidth'),
+ height: boundingClientRect.height || element.prop('offsetHeight'),
+ top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
+ left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
+ };
+ },
+
+ /**
+ * Provides coordinates for the targetEl in relation to hostEl
+ */
+ positionElements: function(hostEl, targetEl, positionStr, appendToBody) {
+ var positionStrParts = positionStr.split('-');
+ var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center';
+
+ var hostElPos,
+ targetElWidth,
+ targetElHeight,
+ targetElPos;
+
+ hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl);
+
+ targetElWidth = targetEl.prop('offsetWidth');
+ targetElHeight = targetEl.prop('offsetHeight');
+
+ var shiftWidth = {
+ center: function() {
+ return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2;
+ },
+ left: function() {
+ return hostElPos.left;
+ },
+ right: function() {
+ return hostElPos.left + hostElPos.width;
+ }
+ };
+
+ var shiftHeight = {
+ center: function() {
+ return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2;
+ },
+ top: function() {
+ return hostElPos.top;
+ },
+ bottom: function() {
+ return hostElPos.top + hostElPos.height;
+ }
+ };
+
+ switch (pos0) {
+ case 'right':
+ targetElPos = {
+ top: shiftHeight[pos1](),
+ left: shiftWidth[pos0]()
+ };
+ break;
+ case 'left':
+ targetElPos = {
+ top: shiftHeight[pos1](),
+ left: hostElPos.left - targetElWidth
+ };
+ break;
+ case 'bottom':
+ targetElPos = {
+ top: shiftHeight[pos0](),
+ left: shiftWidth[pos1]()
+ };
+ break;
+ default:
+ targetElPos = {
+ top: hostElPos.top - targetElHeight,
+ left: shiftWidth[pos1]()
+ };
+ break;
+ }
+
+ return targetElPos;
+ }
+ };
+ }]);
+
+/* Deprecated position below */
+
+angular.module('ui.bootstrap.position')
+
+.value('$positionSuppressWarning', false)
+
+.service('$position', ['$log', '$positionSuppressWarning', '$uibPosition', function($log, $positionSuppressWarning, $uibPosition) {
+ if (!$positionSuppressWarning) {
+ $log.warn('$position is now deprecated. Use $uibPosition instead.');
+ }
+
+ angular.extend(this, $uibPosition);
+}]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/position/test/position.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/position/test/position.spec.js
new file mode 100644
index 0000000..9b0f5a0
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/position/test/position.spec.js
@@ -0,0 +1,164 @@
+describe('position elements', function () {
+ var TargetElMock = function(width, height) {
+ this.width = width;
+ this.height = height;
+
+ this.prop = function(propName) {
+ return propName === 'offsetWidth' ? width : height;
+ };
+ };
+
+ var $position;
+
+ beforeEach(module('ui.bootstrap.position'));
+ beforeEach(inject(function($uibPosition) {
+ $position = $uibPosition;
+ }));
+ beforeEach(function () {
+ jasmine.addMatchers({
+ toBePositionedAt: function(util, customEqualityTesters) {
+ return {
+ compare: function(actual, top, left) {
+ var result = {
+ pass: util.equals(actual.top, top, customEqualityTesters) &&
+ util.equals(actual.left, left, customEqualityTesters)
+ };
+
+ if (result.pass) {
+ result.message = 'Expected "(' + actual.top + ', ' + actual.left + ')" not to be positioned at (' + top + ', ' + left + ')';
+ } else {
+ result.message = 'Expected "(' + actual.top + ', ' + actual.left + ')" to be positioned at (' + top + ', ' + left + ')';
+ }
+
+ return result;
+ }
+ };
+ }
+ });
+ });
+
+ describe('append-to-body: false', function() {
+ beforeEach(function() {
+ //mock position info normally queried from the DOM
+ $position.position = function() {
+ return {
+ width: 20,
+ height: 20,
+ top: 100,
+ left: 100
+ };
+ };
+ });
+
+ it('should position element on top-center by default', function() {
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'other')).toBePositionedAt(90, 105);
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'top')).toBePositionedAt(90, 105);
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'top-center')).toBePositionedAt(90, 105);
+ });
+
+ it('should position on top-left', function() {
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'top-left')).toBePositionedAt(90, 100);
+ });
+
+ it('should position on top-right', function() {
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'top-right')).toBePositionedAt(90, 120);
+ });
+
+ it('should position elements on bottom-center when "bottom" specified', function() {
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'bottom')).toBePositionedAt(120, 105);
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'bottom-center')).toBePositionedAt(120, 105);
+ });
+
+ it('should position elements on bottom-left', function() {
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'bottom-left')).toBePositionedAt(120, 100);
+ });
+
+ it('should position elements on bottom-right', function() {
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'bottom-right')).toBePositionedAt(120, 120);
+ });
+
+ it('should position elements on left-center when "left" specified', function() {
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'left')).toBePositionedAt(105, 90);
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'left-center')).toBePositionedAt(105, 90);
+ });
+
+ it('should position elements on left-top when "left-top" specified', function() {
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'left-top')).toBePositionedAt(100, 90);
+ });
+
+ it('should position elements on left-bottom when "left-bottom" specified', function() {
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'left-bottom')).toBePositionedAt(120, 90);
+ });
+
+ it('should position elements on right-center when "right" specified', function() {
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'right')).toBePositionedAt(105, 120);
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'right-center')).toBePositionedAt(105, 120);
+ });
+
+ it('should position elements on right-top when "right-top" specified', function() {
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'right-top')).toBePositionedAt(100, 120);
+ });
+
+ it('should position elements on right-top when "right-top" specified', function() {
+ expect($position.positionElements({}, new TargetElMock(10, 10), 'right-bottom')).toBePositionedAt(120, 120);
+ });
+ });
+});
+
+/* Deprecation tests below */
+
+describe('position deprecation', function() {
+ var TargetElMock = function(width, height) {
+ this.width = width;
+ this.height = height;
+
+ this.prop = function(propName) {
+ return propName === 'offsetWidth' ? width : height;
+ };
+ };
+ beforeEach(module('ui.bootstrap.position'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$positionSuppressWarning', true);
+ });
+
+ inject(function($log, $position) {
+ spyOn($log, 'warn');
+ //mock position info normally queried from the DOM
+ $position.position = function() {
+ return {
+ width: 20,
+ height: 20,
+ top: 100,
+ left: 100
+ };
+ };
+
+ $position.positionElements({}, new TargetElMock(10, 10), 'other');
+
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($log) {
+ spyOn($log, 'warn');
+
+ inject(function($position) {
+ //mock position info normally queried from the DOM
+ $position.position = function() {
+ return {
+ width: 20,
+ height: 20,
+ top: 100,
+ left: 100
+ };
+ };
+
+ $position.positionElements({}, new TargetElMock(10, 10), 'other');
+
+ expect($log.warn.calls.count()).toBe(1);
+ expect($log.warn.calls.argsFor(0)).toEqual(['$position is now deprecated. Use $uibPosition instead.']);
+ });
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/position/test/test.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/position/test/test.html
new file mode 100644
index 0000000..3ce65b8
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/position/test/test.html
@@ -0,0 +1,144 @@
+<!DOCTYPE html>
+<html lang="en" ng-app="position">
+<head>
+ <meta charset="utf-8">
+ <script src="../../../node_modules/angular/angular.js"></script>
+ <script src="../position.js"></script>
+ <style type="text/css">
+ .container {
+ border: 1px solid red;
+ }
+
+ .container-relative {
+ border: 1px solid red;
+ position: relative;
+ }
+
+ .content {
+ border: 5px solid #808080;
+ background-color: dodgerblue;
+ width: 200px;
+ }
+
+ .positioned {
+ border: 5px solid #808080;
+ background-color: green;
+ position: absolute;
+ }
+ </style>
+ <script type="text/javascript">
+ angular.module('position', ['ui.bootstrap.position']).directive('position', function ($compile, $position) {
+ return {
+ link: function (scope, element, attrs) {
+
+ var positionedEl = angular.element('<div class="positioned">Positioned</div>');
+ var elPosition = $position.position(element);
+ elPosition.left += elPosition.width;
+
+ positionedEl.css({left: elPosition.left + 'px', top: elPosition.top + 'px'});
+
+ if (attrs['position'] === 'body') {
+ angular.element(document.getElementsByTagName('body')[0]).after($compile(positionedEl)(scope));
+ } else {
+ element.after($compile(positionedEl)(scope));
+ }
+ }
+ };
+ });
+ </script>
+</head>
+<body class="container">
+<h3>Within body</h3>
+
+<div class="content" position>Content</div>
+
+<h3>Within statically positioned DIV</h3>
+
+<div class="container">
+ <div class="content" position>Content</div>
+</div>
+
+<h3>Within relative-positioned DIV - position specified in CSS</h3>
+
+<div class="container-relative">
+ <div class="content" position>Content</div>
+</div>
+
+<h3>Within relative-positioned DIV</h3>
+
+<div style="position: relative; left: 200px" class="container">
+ <div class="content" position>Content</div>
+</div>
+
+<h3>Within absolute-positioned DIV</h3>
+
+<div style="position: absolute; left: 400px; top: 400px" class="container">
+ <div class="content" position>Content - absolute</div>
+</div>
+
+<h3>Within overflowing absolute-positioned DIV</h3>
+<div class="container" style="height: 50px; overflow: scroll;overflow-x: hidden; position: absolute;">
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur non velit nulla. Suspendisse sit amet tempus diam. Sed at ultricies neque. Suspendisse id felis a sem placerat ornare. Donec auctor, purus at molestie tempor, arcu enim molestie lacus, ac imperdiet massa urna eu massa. Praesent velit tellus, scelerisque a fermentum ut, ornare in diam. Phasellus egestas molestie feugiat. Vivamus sit amet viverra metus.
+ <div class="content" position>Content absolute overflow</div>
+</div>
+
+<br>
+<br>
+<br>
+
+<h3>Next to a float element</h3>
+
+<div class="container">
+ <div class="content" style="float: right" position>Content</div>
+</div>
+
+<h3>Within a table</h3>
+<table class="container">
+ <tr>
+ <td>Some other content</td>
+ <td>
+ <div class="content" position>Content</div>
+ </td>
+ </tr>
+</table>
+
+<h3>Within a table that is inside a relative-positioned DIV</h3>
+
+<div style="position: relative; left: 200px" class="container">
+ <table class="container">
+ <tr>
+ <td>Some other content</td>
+ <td>
+ <div class="content" position>Content</div>
+ </td>
+ </tr>
+ </table>
+</div>
+
+<h3>Inside svg</h3>
+
+<svg height="300px" width="300px">
+ <rect x="0" y="0" height="300" width="300" fill="aliceblue"></rect>
+ <rect x="50" y="50" height="200" width="200" position="body" fill="white" stroke="red">
+ </rect>
+</svg>
+
+
+<h3>Inside looong text</h3>
+<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur non velit nulla. Suspendisse sit amet tempus diam. Sed at ultricies neque. Suspendisse id felis a sem placerat ornare. Donec auctor, purus at molestie tempor, arcu enim molestie lacus, ac imperdiet massa urna eu massa. Praesent velit tellus, scelerisque a fermentum ut, ornare in diam. Phasellus egestas molestie feugiat. Vivamus sit amet viverra metus.</p>
+<p>Etiam ultricies odio commodo erat ullamcorper sodales. Nullam ac dui ac libero dictum mollis. Quisque convallis adipiscing facilisis. In nec nisi velit, id auctor lectus. Cras interdum urna non felis lacinia vulputate. Integer dignissim, mi aliquam gravida auctor, massa odio cursus lorem, eu ultrices eros nisl tempus diam. Maecenas tristique pellentesque nisi sed adipiscing. Aenean hendrerit sapien quis arcu lobortis vitae pulvinar ante volutpat. Morbi consectetur erat eu lacus facilisis eu ullamcorper orci euismod. Quisque diam dui, interdum in suscipit et, fringilla non justo. Pellentesque non nibh odio. Proin sit amet massa sem.</p>
+<p>Nam in urna erat, at congue nisi. Donec eu tellus lorem, sed facilisis tellus. Aliquam suscipit faucibus ipsum, at hendrerit metus interdum at. Integer et eros ac lacus vulputate sagittis quis quis erat. Suspendisse consectetur vehicula purus vitae imperdiet. Suspendisse in augue magna, quis imperdiet enim. Nullam non diam ac erat auctor bibendum. Praesent ante mauris, egestas sit amet molestie sed, tristique at lorem. Nam at mi ac nisl venenatis semper nec eget mi. Pellentesque a lectus ac leo feugiat suscipit. Quisque tristique dui nec urna placerat a viverra mi iaculis. Ut et tellus et turpis sagittis iaculis nec eu magna. Sed quis nunc non arcu tincidunt ultricies viverra id mauris.</p>
+<p>Curabitur luctus rutrum ultricies. Aenean ut rutrum orci. Sed molestie lorem in leo cursus id feugiat nisi scelerisque. Maecenas pulvinar neque nec lacus feugiat dictum. Donec viverra felis nec nisi mollis feugiat. Phasellus vehicula, ligula at mattis porttitor, sapien urna hendrerit quam, at fringilla nisl quam vel elit. In eu lacus ligula. Praesent eget gravida nisl. Suspendisse velit diam, pellentesque a tempus quis, vestibulum vel leo.</p>
+<p>Maecenas feugiat ultrices laoreet. Sed congue posuere diam ac faucibus. Pellentesque eget leo ligula. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed nec quam eu tellus sagittis cursus a sit amet eros. Mauris sit amet orci at orci vulputate commodo ut ut nunc. Etiam sagittis erat ut nisi ultricies feugiat. Morbi sed eros nisi. Cras vitae augue in risus aliquet commodo non id est.</p>
+<div class="content" position>HERE</div>
+<p>Maecenas laoreet nisi pretium elit bibendum eget tempor nunc aliquet. Vivamus interdum nisi sit amet tortor fermentum congue. Suspendisse at posuere erat. Aliquam hendrerit ultricies nunc non adipiscing. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis molestie viverra nulla a aliquet. Nullam non eros vel sem vehicula suscipit. Ut sit amet arcu ac tortor dignissim viverra in a ligula.</p>
+
+
+<div style="position: fixed; bottom: 0" class="container">
+ <h3>Within fixed div</h3>
+ <div class="content" position>Content</div>
+</div>
+
+
+</body>
+</html>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/docs/demo.html
new file mode 100644
index 0000000..3073be7
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/docs/demo.html
@@ -0,0 +1,24 @@
+<div ng-controller="ProgressDemoCtrl">
+
+ <h3>Static</h3>
+ <div class="row">
+ <div class="col-sm-4"><uib-progressbar value="55"></uib-progressbar></div>
+ <div class="col-sm-4"><uib-progressbar class="progress-striped" value="22" type="warning">22%</uib-progressbar></div>
+ <div class="col-sm-4"><uib-progressbar class="progress-striped active" max="200" value="166" type="danger"><i>166 / 200</i></uib-progressbar></div>
+ </div>
+
+ <hr />
+ <h3>Dynamic <button type="button" class="btn btn-sm btn-primary" ng-click="random()">Randomize</button></h3>
+ <uib-progressbar max="max" value="dynamic"><span style="color:white; white-space:nowrap;">{{dynamic}} / {{max}}</span></uib-progressbar>
+
+ <small><em>No animation</em></small>
+ <uib-progressbar animate="false" value="dynamic" type="success"><b>{{dynamic}}%</b></uib-progressbar>
+
+ <small><em>Object (changes type based on value)</em></small>
+ <uib-progressbar class="progress-striped active" value="dynamic" type="{{type}}">{{type}} <i ng-show="showWarning">!!! Watch out !!!</i></uib-progressbar>
+
+ <hr />
+ <h3>Stacked <button type="button" class="btn btn-sm btn-primary" ng-click="randomStacked()">Randomize</button></h3>
+ <uib-progress><uib-bar ng-repeat="bar in stacked track by $index" value="bar.value" type="{{bar.type}}"><span ng-hide="bar.value < 5">{{bar.value}}%</span></uib-bar></uib-progress>
+
+</div>
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/docs/demo.js
new file mode 100644
index 0000000..c06561c
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/docs/demo.js
@@ -0,0 +1,38 @@
+angular.module('ui.bootstrap.demo').controller('ProgressDemoCtrl', function ($scope) {
+ $scope.max = 200;
+
+ $scope.random = function() {
+ var value = Math.floor((Math.random() * 100) + 1);
+ var type;
+
+ if (value < 25) {
+ type = 'success';
+ } else if (value < 50) {
+ type = 'info';
+ } else if (value < 75) {
+ type = 'warning';
+ } else {
+ type = 'danger';
+ }
+
+ $scope.showWarning = (type === 'danger' || type === 'warning');
+
+ $scope.dynamic = value;
+ $scope.type = type;
+ };
+ $scope.random();
+
+ $scope.randomStacked = function() {
+ $scope.stacked = [];
+ var types = ['success', 'info', 'warning', 'danger'];
+
+ for (var i = 0, n = Math.floor((Math.random() * 4) + 1); i < n; i++) {
+ var index = Math.floor((Math.random() * 4));
+ $scope.stacked.push({
+ value: Math.floor((Math.random() * 30) + 1),
+ type: types[index]
+ });
+ }
+ };
+ $scope.randomStacked();
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/docs/readme.md
new file mode 100644
index 0000000..45a4fe5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/docs/readme.md
@@ -0,0 +1,32 @@
+A progress bar directive that is focused on providing feedback on the progress of a workflow or action.
+
+It supports multiple (stacked) bars into the same `<uib-progress>` element or a single `<progressbar>` element with optional `max` attribute and transition animations.
+
+### Settings ###
+
+#### `<uib-progressbar>` ####
+
+ * `value` <i class="glyphicon glyphicon-eye-open"></i>
+ :
+ The current value of progress completed.
+
+ * `type`
+ _(Default: null)_ :
+ Style type. Possible values are 'success', 'warning' etc.
+
+ * `max`
+ _(Default: 100)_ :
+ A number that specifies the total value of bars that is required.
+
+ * `animate`
+ _(Default: true)_ :
+ Whether bars use transitions to achieve the width change.
+
+ * `title`
+ _(Default: progressbar)_ :
+ Title to use as label (for accessibility)
+
+### Stacked ###
+
+Place multiple `<uib-bar>`s into the same `<uib-progress>` element to stack them.
+`<uib-progress>` supports `max`, `animate`, and `title` & `<uib-bar>` supports `value`, `title`, and `type` attributes.
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/progressbar.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/progressbar.js
new file mode 100644
index 0000000..366aadb
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/progressbar.js
@@ -0,0 +1,224 @@
+angular.module('ui.bootstrap.progressbar', [])
+
+.constant('uibProgressConfig', {
+ animate: true,
+ max: 100
+})
+
+.controller('UibProgressController', ['$scope', '$attrs', 'uibProgressConfig', function($scope, $attrs, progressConfig) {
+ var self = this,
+ animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate;
+
+ this.bars = [];
+ $scope.max = angular.isDefined($scope.max) ? $scope.max : progressConfig.max;
+
+ this.addBar = function(bar, element, attrs) {
+ if (!animate) {
+ element.css({'transition': 'none'});
+ }
+
+ this.bars.push(bar);
+
+ bar.max = $scope.max;
+ bar.title = attrs && angular.isDefined(attrs.title) ? attrs.title : 'progressbar';
+
+ bar.$watch('value', function(value) {
+ bar.recalculatePercentage();
+ });
+
+ bar.recalculatePercentage = function() {
+ var totalPercentage = self.bars.reduce(function(total, bar) {
+ bar.percent = +(100 * bar.value / bar.max).toFixed(2);
+ return total + bar.percent;
+ }, 0);
+
+ if (totalPercentage > 100) {
+ bar.percent -= totalPercentage - 100;
+ }
+ };
+
+ bar.$on('$destroy', function() {
+ element = null;
+ self.removeBar(bar);
+ });
+ };
+
+ this.removeBar = function(bar) {
+ this.bars.splice(this.bars.indexOf(bar), 1);
+ this.bars.forEach(function (bar) {
+ bar.recalculatePercentage();
+ });
+ };
+
+ $scope.$watch('max', function(max) {
+ self.bars.forEach(function(bar) {
+ bar.max = $scope.max;
+ bar.recalculatePercentage();
+ });
+ });
+}])
+
+.directive('uibProgress', function() {
+ return {
+ replace: true,
+ transclude: true,
+ controller: 'UibProgressController',
+ require: 'uibProgress',
+ scope: {
+ max: '=?'
+ },
+ templateUrl: 'template/progressbar/progress.html'
+ };
+})
+
+.directive('uibBar', function() {
+ return {
+ replace: true,
+ transclude: true,
+ require: '^uibProgress',
+ scope: {
+ value: '=',
+ type: '@'
+ },
+ templateUrl: 'template/progressbar/bar.html',
+ link: function(scope, element, attrs, progressCtrl) {
+ progressCtrl.addBar(scope, element, attrs);
+ }
+ };
+})
+
+.directive('uibProgressbar', function() {
+ return {
+ replace: true,
+ transclude: true,
+ controller: 'UibProgressController',
+ scope: {
+ value: '=',
+ max: '=?',
+ type: '@'
+ },
+ templateUrl: 'template/progressbar/progressbar.html',
+ link: function(scope, element, attrs, progressCtrl) {
+ progressCtrl.addBar(scope, angular.element(element.children()[0]), {title: attrs.title});
+ }
+ };
+});
+
+/* Deprecated progressbar below */
+
+angular.module('ui.bootstrap.progressbar')
+
+.value('$progressSuppressWarning', false)
+
+.controller('ProgressController', ['$scope', '$attrs', 'uibProgressConfig', '$log', '$progressSuppressWarning', function($scope, $attrs, progressConfig, $log, $progressSuppressWarning) {
+ if (!$progressSuppressWarning) {
+ $log.warn('ProgressController is now deprecated. Use UibProgressController instead.');
+ }
+
+ var self = this,
+ animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate;
+
+ this.bars = [];
+ $scope.max = angular.isDefined($scope.max) ? $scope.max : progressConfig.max;
+
+ this.addBar = function(bar, element, attrs) {
+ if (!animate) {
+ element.css({'transition': 'none'});
+ }
+
+ this.bars.push(bar);
+
+ bar.max = $scope.max;
+ bar.title = attrs && angular.isDefined(attrs.title) ? attrs.title : 'progressbar';
+
+ bar.$watch('value', function(value) {
+ bar.recalculatePercentage();
+ });
+
+ bar.recalculatePercentage = function() {
+ bar.percent = +(100 * bar.value / bar.max).toFixed(2);
+
+ var totalPercentage = self.bars.reduce(function(total, bar) {
+ return total + bar.percent;
+ }, 0);
+
+ if (totalPercentage > 100) {
+ bar.percent -= totalPercentage - 100;
+ }
+ };
+
+ bar.$on('$destroy', function() {
+ element = null;
+ self.removeBar(bar);
+ });
+ };
+
+ this.removeBar = function(bar) {
+ this.bars.splice(this.bars.indexOf(bar), 1);
+ };
+
+ $scope.$watch('max', function(max) {
+ self.bars.forEach(function(bar) {
+ bar.max = $scope.max;
+ bar.recalculatePercentage();
+ });
+ });
+}])
+
+.directive('progress', ['$log', '$progressSuppressWarning', function($log, $progressSuppressWarning) {
+ return {
+ replace: true,
+ transclude: true,
+ controller: 'ProgressController',
+ require: 'progress',
+ scope: {
+ max: '=?',
+ title: '@?'
+ },
+ templateUrl: 'template/progressbar/progress.html',
+ link: function() {
+ if (!$progressSuppressWarning) {
+ $log.warn('progress is now deprecated. Use uib-progress instead.');
+ }
+ }
+ };
+}])
+
+.directive('bar', ['$log', '$progressSuppressWarning', function($log, $progressSuppressWarning) {
+ return {
+ replace: true,
+ transclude: true,
+ require: '^progress',
+ scope: {
+ value: '=',
+ type: '@'
+ },
+ templateUrl: 'template/progressbar/bar.html',
+ link: function(scope, element, attrs, progressCtrl) {
+ if (!$progressSuppressWarning) {
+ $log.warn('bar is now deprecated. Use uib-bar instead.');
+ }
+ progressCtrl.addBar(scope, element);
+ }
+ };
+}])
+
+.directive('progressbar', ['$log', '$progressSuppressWarning', function($log, $progressSuppressWarning) {
+ return {
+ replace: true,
+ transclude: true,
+ controller: 'ProgressController',
+ scope: {
+ value: '=',
+ max: '=?',
+ type: '@'
+ },
+ templateUrl: 'template/progressbar/progressbar.html',
+ link: function(scope, element, attrs, progressCtrl) {
+ if (!$progressSuppressWarning) {
+ $log.warn('progressbar is now deprecated. Use uib-progressbar instead.');
+ }
+ progressCtrl.addBar(scope, angular.element(element.children()[0]), {title: attrs.title});
+ }
+ };
+}]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/test/progressbar.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/test/progressbar.spec.js
new file mode 100644
index 0000000..8c487b2
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/progressbar/test/progressbar.spec.js
@@ -0,0 +1,421 @@
+describe('progressbar directive', function() {
+ var $rootScope, $compile, element;
+ beforeEach(module('ui.bootstrap.progressbar'));
+ beforeEach(module('template/progressbar/progressbar.html', 'template/progressbar/progress.html', 'template/progressbar/bar.html'));
+ beforeEach(inject(function(_$compile_, _$rootScope_) {
+ $compile = _$compile_;
+ $rootScope = _$rootScope_;
+ $rootScope.value = 22;
+ element = $compile('<uib-progressbar animate="false" value="value" title="foo">{{value}} %</uib-progressbar>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ var BAR_CLASS = 'progress-bar';
+
+ function getBar(i) {
+ return element.children().eq(i);
+ }
+
+ it('has a "progress" css class', function() {
+ expect(element).toHaveClass('progress');
+ });
+
+ it('contains one child element with "bar" css class', function() {
+ expect(element.children().length).toBe(1);
+ expect(getBar(0)).toHaveClass(BAR_CLASS);
+ });
+
+ it('has a "bar" element with expected width', function() {
+ expect(getBar(0).css('width')).toBe('22%');
+ });
+
+ it('has the appropriate aria markup', function() {
+ var bar = getBar(0);
+ expect(bar.attr('role')).toBe('progressbar');
+ expect(bar.attr('aria-valuemin')).toBe('0');
+ expect(bar.attr('aria-valuemax')).toBe('100');
+ expect(bar.attr('aria-valuenow')).toBe('22');
+ expect(bar.attr('aria-valuetext')).toBe('22%');
+ expect(bar.attr('aria-labelledby')).toBe('foo');
+ });
+
+ it('has the default aria-labelledby value of `progressbar`', function() {
+ element = $compile('<uib-progressbar animate="false" value="value">{{value}} %</uib-progressbar>')($rootScope);
+ $rootScope.$digest();
+ var bar = getBar(0);
+ expect(bar.attr('aria-labelledby')).toBe('progressbar');
+ });
+
+ it('transcludes "bar" text', function() {
+ expect(getBar(0).text()).toBe('22 %');
+ });
+
+ it('it should be possible to add additional classes', function() {
+ element = $compile('<progress class="progress-striped active" max="200"><bar class="pizza"></bar></progress>')($rootScope);
+ $rootScope.$digest();
+
+ expect(element).toHaveClass('progress-striped');
+ expect(element).toHaveClass('active');
+
+ expect(getBar(0)).toHaveClass('pizza');
+ });
+
+ it('adjusts the "bar" width and aria when value changes', function() {
+ $rootScope.value = 60;
+ $rootScope.$digest();
+
+ var bar = getBar(0);
+ expect(bar.css('width')).toBe('60%');
+
+ expect(bar.attr('aria-valuemin')).toBe('0');
+ expect(bar.attr('aria-valuemax')).toBe('100');
+ expect(bar.attr('aria-valuenow')).toBe('60');
+ expect(bar.attr('aria-valuetext')).toBe('60%');
+ });
+
+ it('allows fractional "bar" width values, rounded to two places', function() {
+ $rootScope.value = 5.625;
+ $rootScope.$digest();
+ expect(getBar(0).css('width')).toBe('5.63%');
+
+ $rootScope.value = 1.3;
+ $rootScope.$digest();
+ expect(getBar(0).css('width')).toBe('1.3%');
+ });
+
+ it('does not include decimals in aria values', function() {
+ $rootScope.value = 50.34;
+ $rootScope.$digest();
+
+ var bar = getBar(0);
+ expect(bar.css('width')).toBe('50.34%');
+ expect(bar.attr('aria-valuetext')).toBe('50%');
+ });
+
+ describe('"max" attribute', function() {
+ beforeEach(inject(function() {
+ $rootScope.max = 200;
+ element = $compile('<uib-progressbar max="max" animate="false" value="value">{{value}}/{{max}}</uib-progressbar>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('has the appropriate aria markup', function() {
+ expect(getBar(0).attr('aria-valuemax')).toBe('200');
+ });
+
+ it('adjusts the "bar" width', function() {
+ expect(element.children().eq(0).css('width')).toBe('11%');
+ });
+
+ it('adjusts the "bar" width when value changes', function() {
+ $rootScope.value = 60;
+ $rootScope.$digest();
+ expect(getBar(0).css('width')).toBe('30%');
+
+ $rootScope.value += 12;
+ $rootScope.$digest();
+ expect(getBar(0).css('width')).toBe('36%');
+
+ $rootScope.value = 0;
+ $rootScope.$digest();
+ expect(getBar(0).css('width')).toBe('0%');
+ });
+
+ it('transcludes "bar" text', function() {
+ expect(getBar(0).text()).toBe('22/200');
+ });
+
+ it('adjusts the valuemax when it changes', function() {
+ expect(getBar(0).attr('aria-valuemax')).toBe('200');
+ $rootScope.max = 300;
+ $rootScope.$digest();
+ expect(getBar(0).attr('aria-valuemax')).toBe('300');
+ });
+ });
+
+ describe('"type" attribute', function() {
+ beforeEach(inject(function() {
+ $rootScope.type = 'success';
+ element = $compile('<uib-progressbar value="value" type="{{type}}"></uib-progressbar>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('should use correct classes', function() {
+ expect(getBar(0)).toHaveClass(BAR_CLASS);
+ expect(getBar(0)).toHaveClass(BAR_CLASS + '-success');
+ });
+
+ it('should change classes if type changed', function() {
+ $rootScope.type = 'warning';
+ $rootScope.value += 1;
+ $rootScope.$digest();
+
+ var barEl = getBar(0);
+ expect(barEl).toHaveClass(BAR_CLASS);
+ expect(barEl).not.toHaveClass(BAR_CLASS + '-success');
+ expect(barEl).toHaveClass(BAR_CLASS + '-warning');
+ });
+ });
+
+ describe('stacked', function() {
+ beforeEach(inject(function() {
+ $rootScope.objects = [
+ { value: 10, title: 'foo', type: 'success' },
+ { value: 50, title: 'bar', type: 'warning' },
+ { value: 20, title: 'baz' }
+ ];
+ element = $compile('<uib-progress animate="false"><uib-bar ng-repeat="o in objects" value="o.value" type="{{o.type}}" title="{{o.title}}">{{o.value}}</uib-bar></uib-progress>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('contains the right number of bars', function() {
+ expect(element.children().length).toBe(3);
+ for (var i = 0; i < 3; i++) {
+ expect(getBar(i)).toHaveClass(BAR_CLASS);
+ }
+ });
+
+ it('renders each bar with the appropriate width', function() {
+ expect(getBar(0).css('width')).toBe('10%');
+ expect(getBar(1).css('width')).toBe('50%');
+ expect(getBar(2).css('width')).toBe('20%');
+ });
+
+ it('uses correct classes', function() {
+ expect(getBar(0)).toHaveClass(BAR_CLASS + '-success');
+ expect(getBar(0)).not.toHaveClass(BAR_CLASS + '-warning');
+
+ expect(getBar(1)).not.toHaveClass(BAR_CLASS + '-success');
+ expect(getBar(1)).toHaveClass(BAR_CLASS + '-warning');
+
+ expect(getBar(2)).not.toHaveClass(BAR_CLASS + '-success');
+ expect(getBar(2)).not.toHaveClass(BAR_CLASS + '-warning');
+ });
+
+ it('should change classes if type changed', function() {
+ $rootScope.objects = [
+ { value: 20, type: 'warning' },
+ { value: 50 },
+ { value: 30, type: 'info' }
+ ];
+ $rootScope.$digest();
+
+ expect(getBar(0)).not.toHaveClass(BAR_CLASS + '-success');
+ expect(getBar(0)).toHaveClass(BAR_CLASS + '-warning');
+
+ expect(getBar(1)).not.toHaveClass(BAR_CLASS + '-success');
+ expect(getBar(1)).not.toHaveClass(BAR_CLASS + '-warning');
+
+ expect(getBar(2)).toHaveClass(BAR_CLASS + '-info');
+ expect(getBar(2)).not.toHaveClass(BAR_CLASS + '-success');
+ expect(getBar(2)).not.toHaveClass(BAR_CLASS + '-warning');
+ });
+
+ it('should change classes if type changed', function() {
+ $rootScope.objects = [
+ { value: 70, type: 'info' }
+ ];
+ $rootScope.$digest();
+
+ expect(element.children().length).toBe(1);
+
+ expect(getBar(0)).toHaveClass(BAR_CLASS + '-info');
+ expect(getBar(0)).not.toHaveClass(BAR_CLASS + '-success');
+ expect(getBar(0)).not.toHaveClass(BAR_CLASS + '-warning');
+ });
+
+ it('should have the correct aria markup', function() {
+ expect(getBar(0).attr('aria-valuenow')).toBe('10');
+ expect(getBar(0).attr('aria-valuemin')).toBe('0');
+ expect(getBar(0).attr('aria-valuemax')).toBe('100');
+ expect(getBar(0).attr('aria-valuetext')).toBe('10%');
+ expect(getBar(0).attr('aria-labelledby')).toBe('foo');
+
+ expect(getBar(1).attr('aria-valuenow')).toBe('50');
+ expect(getBar(1).attr('aria-valuemin')).toBe('0');
+ expect(getBar(1).attr('aria-valuemax')).toBe('100');
+ expect(getBar(1).attr('aria-valuetext')).toBe('50%');
+ expect(getBar(1).attr('aria-labelledby')).toBe('bar');
+
+ expect(getBar(2).attr('aria-valuenow')).toBe('20');
+ expect(getBar(2).attr('aria-valuemin')).toBe('0');
+ expect(getBar(2).attr('aria-valuemax')).toBe('100');
+ expect(getBar(2).attr('aria-valuetext')).toBe('20%');
+ expect(getBar(2).attr('aria-labelledby')).toBe('baz');
+ });
+
+ it('should default to `progressbar`', function() {
+ $rootScope.objects = [
+ { value: 10, title: 'foo', type: 'success' },
+ { value: 50, title: 'bar', type: 'warning' },
+ { value: 20, title: 'baz' }
+ ];
+ element = $compile('<uib-progress animate="false"><uib-bar ng-repeat="o in objects" value="o.value" type="{{o.type}}">{{o.value}}</uib-bar></uib-progress>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getBar(0).attr('aria-labelledby')).toBe('progressbar');
+ expect(getBar(1).attr('aria-labelledby')).toBe('progressbar');
+ expect(getBar(2).attr('aria-labelledby')).toBe('progressbar');
+ });
+
+ describe('"max" attribute', function() {
+ beforeEach(inject(function() {
+ $rootScope.max = 200;
+ element = $compile('<uib-progress max="max" animate="false"><uib-bar ng-repeat="o in objects" value="o.value">{{o.value}}/{{max}}</uib-bar></uib-progress>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('has the appropriate aria markup', function() {
+ expect(getBar(0).attr('aria-valuemax')).toBe('200');
+ });
+
+ it('adjusts the "bar" width when it changes', function() {
+ expect(getBar(0).css('width')).toBe('5%');
+ $rootScope.max = 250;
+ $rootScope.$digest();
+ expect(getBar(0).css('width')).toBe('4%');
+ });
+
+ it('adjusts the "bar" width when value changes', function() {
+ $rootScope.objects[0].value = 60;
+ $rootScope.$digest();
+ expect(getBar(0).css('width')).toBe('30%');
+
+ $rootScope.objects[0].value += 12;
+ $rootScope.$digest();
+ expect(getBar(0).css('width')).toBe('36%');
+
+ $rootScope.objects[0].value = 0;
+ $rootScope.$digest();
+ expect(getBar(0).css('width')).toBe('0%');
+ });
+
+ it('transcludes "bar" text', function() {
+ expect(getBar(0).text()).toBe('10/200');
+ });
+
+ it('adjusts the valuemax when it changes', function() {
+ expect(getBar(0).attr('aria-valuemax')).toBe('200');
+ $rootScope.max = 300;
+ $rootScope.$digest();
+ expect(getBar(0).attr('aria-valuemax')).toBe('300');
+ });
+
+ it('should not have a total width over 100%', function() {
+ $rootScope.objects = [
+ { value: 60, type: 'warning' },
+ { value: 103 },
+ { value: 270, type: 'info' }
+ ];
+ $rootScope.max = 433;
+ $rootScope.$digest();
+ var totalWidth = 0;
+ for (var i = 0; i < 3; i++) {
+ totalWidth += parseFloat(getBar(i).css('width'));
+ }
+ expect(totalWidth.toFixed(2)).toBe('100.00');
+ });
+
+ it('should not have a total width over 37.65% when removing bar', function() {
+ $rootScope.objects = [
+ { value: 60, type: 'warning' },
+ { value: 103 },
+ { value: 270, type: 'info' }
+ ];
+ $rootScope.max = 433;
+ $rootScope.$digest();
+ var totalWidth = 0;
+ for (var i = 0; i < 3; i++) {
+ totalWidth += parseFloat(getBar(i).css('width'));
+ }
+ expect(totalWidth.toFixed(2)).toBe('100.00');
+
+ $rootScope.objects.splice(2, 1);
+ $rootScope.$digest();
+ totalWidth = 0;
+ for (i = 0; i < 2; i++) {
+ totalWidth += parseFloat(getBar(i).css('width'));
+ }
+ expect(totalWidth.toFixed(2)).toBe('37.65');
+ });
+ });
+ });
+});
+
+/* Deprecation tests below */
+
+describe('progressbar deprecation', function() {
+ beforeEach(module('ui.bootstrap.progressbar'));
+ beforeEach(module('template/progressbar/progress.html', 'template/progressbar/bar.html', 'template/progressbar/progressbar.html'));
+
+ describe('progress & bar directives', function() {
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$progressSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ $rootScope.objects = [
+ { value: 10, type: 'success' },
+ { value: 50, type: 'warning' },
+ { value: 20 }
+ ];
+ var element = $compile('<progress animate="false"><bar ng-repeat="o in objects" value="o.value" type="{{o.type}}">{{o.value}}</bar></progress>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ $rootScope.objects = [
+ { value: 10, type: 'success' },
+ { value: 50, type: 'warning' },
+ { value: 20 }
+ ];
+ var element = $compile('<progress animate="false"><bar ng-repeat="o in objects" value="o.value" type="{{o.type}}">{{o.value}}</bar></progress>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(5);
+ expect($log.warn.calls.argsFor(0)).toEqual(['ProgressController is now deprecated. Use UibProgressController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['progress is now deprecated. Use uib-progress instead.']);
+ expect($log.warn.calls.argsFor(2)).toEqual(['bar is now deprecated. Use uib-bar instead.']);
+ expect($log.warn.calls.argsFor(3)).toEqual(['bar is now deprecated. Use uib-bar instead.']);
+ expect($log.warn.calls.argsFor(4)).toEqual(['bar is now deprecated. Use uib-bar instead.']);
+ }));
+ });
+
+ describe('progressbar directive', function() {
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$progressSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ $rootScope.value = 22;
+ var element = $compile('<progressbar animate="false" value="value" title="foo">{{value}} %</progressbar>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ $rootScope.value = 22;
+ var element = $compile('<progressbar animate="false" value="value" title="foo">{{value}} %</progressbar>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(2);
+ expect($log.warn.calls.argsFor(0)).toEqual(['ProgressController is now deprecated. Use UibProgressController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['progressbar is now deprecated. Use uib-progressbar instead.']);
+ }));
+ });
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/docs/demo.html
new file mode 100644
index 0000000..1ad69f7
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/docs/demo.html
@@ -0,0 +1,15 @@
+<div ng-controller="RatingDemoCtrl">
+ <h4>Default</h4>
+ <uib-rating ng-model="rate" max="max" readonly="isReadonly" on-hover="hoveringOver(value)" on-leave="overStar = null" titles="['one','two','three']" aria-labelledby="default-rating"></uib-rating>
+ <span class="label" ng-class="{'label-warning': percent<30, 'label-info': percent>=30 && percent<70, 'label-success': percent>=70}" ng-show="overStar && !isReadonly">{{percent}}%</span>
+
+ <pre style="margin:15px 0;">Rate: <b>{{rate}}</b> - Readonly is: <i>{{isReadonly}}</i> - Hovering over: <b>{{overStar || "none"}}</b></pre>
+
+ <button type="button" class="btn btn-sm btn-danger" ng-click="rate = 0" ng-disabled="isReadonly">Clear</button>
+ <button type="button" class="btn btn-sm btn-default" ng-click="isReadonly = ! isReadonly">Toggle Readonly</button>
+ <hr />
+
+ <h4>Custom icons</h4>
+ <div ng-init="x = 5"><uib-rating ng-model="x" max="15" state-on="'glyphicon-ok-sign'" state-off="'glyphicon-ok-circle'" aria-labelledby="custom-icons-1"></uib-rating> <b>(<i>Rate:</i> {{x}})</b></div>
+ <div ng-init="y = 2"><uib-rating ng-model="y" rating-states="ratingStates" aria-labelledby="custom-icons-2"></uib-rating> <b>(<i>Rate:</i> {{y}})</b></div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/docs/demo.js
new file mode 100644
index 0000000..af6b4e9
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/docs/demo.js
@@ -0,0 +1,18 @@
+angular.module('ui.bootstrap.demo').controller('RatingDemoCtrl', function ($scope) {
+ $scope.rate = 7;
+ $scope.max = 10;
+ $scope.isReadonly = false;
+
+ $scope.hoveringOver = function(value) {
+ $scope.overStar = value;
+ $scope.percent = 100 * (value / $scope.max);
+ };
+
+ $scope.ratingStates = [
+ {stateOn: 'glyphicon-ok-sign', stateOff: 'glyphicon-ok-circle'},
+ {stateOn: 'glyphicon-star', stateOff: 'glyphicon-star-empty'},
+ {stateOn: 'glyphicon-heart', stateOff: 'glyphicon-ban-circle'},
+ {stateOn: 'glyphicon-heart'},
+ {stateOff: 'glyphicon-off'}
+ ];
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/docs/readme.md
new file mode 100644
index 0000000..45cbeb9
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/docs/readme.md
@@ -0,0 +1,41 @@
+Rating directive that will take care of visualising a star rating bar.
+
+### Settings ###
+
+#### `<uib-rating>` ####
+
+ * `ng-model` <i class="glyphicon glyphicon-eye-open"></i>
+ :
+ The current rate.
+
+ * `max`
+ _(Defaults: 5)_ :
+ Changes the number of icons.
+
+ * `readonly` <i class="icon-eye-open"></i>
+ _(Defaults: false)_ :
+ Prevent user's interaction.
+
+ * `titles`
+ _(Defaults: ["one", "two", "three", "four", "five"])_ :
+ An array of Strings defining titles for all icons
+
+ * `on-hover(value)`
+ :
+ An optional expression called when user's mouse is over a particular icon.
+
+ * `on-leave()`
+ :
+ An optional expression called when user's mouse leaves the control altogether.
+
+ * `state-on`
+ _(Defaults: null)_ :
+ A variable used in template to specify the state (class, src, etc) for selected icons.
+
+ * `state-off`
+ _(Defaults: null)_ :
+ A variable used in template to specify the state for unselected icons.
+
+ * `rating-states`
+ _(Defaults: null)_ :
+ An array of objects defining properties for all icons. In default template, `stateOn` & `stateOff` property is used to specify the icon's class.
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/rating.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/rating.js
new file mode 100644
index 0000000..b32a1a3
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/rating.js
@@ -0,0 +1,137 @@
+angular.module('ui.bootstrap.rating', [])
+
+.constant('uibRatingConfig', {
+ max: 5,
+ stateOn: null,
+ stateOff: null,
+ titles : ['one', 'two', 'three', 'four', 'five']
+})
+
+.controller('UibRatingController', ['$scope', '$attrs', 'uibRatingConfig', function($scope, $attrs, ratingConfig) {
+ var ngModelCtrl = { $setViewValue: angular.noop };
+
+ this.init = function(ngModelCtrl_) {
+ ngModelCtrl = ngModelCtrl_;
+ ngModelCtrl.$render = this.render;
+
+ ngModelCtrl.$formatters.push(function(value) {
+ if (angular.isNumber(value) && value << 0 !== value) {
+ value = Math.round(value);
+ }
+ return value;
+ });
+
+ this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn;
+ this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff;
+ var tmpTitles = angular.isDefined($attrs.titles) ? $scope.$parent.$eval($attrs.titles) : ratingConfig.titles ;
+ this.titles = angular.isArray(tmpTitles) && tmpTitles.length > 0 ?
+ tmpTitles : ratingConfig.titles;
+
+ var ratingStates = angular.isDefined($attrs.ratingStates) ?
+ $scope.$parent.$eval($attrs.ratingStates) :
+ new Array(angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max);
+ $scope.range = this.buildTemplateObjects(ratingStates);
+ };
+
+ this.buildTemplateObjects = function(states) {
+ for (var i = 0, n = states.length; i < n; i++) {
+ states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff, title: this.getTitle(i) }, states[i]);
+ }
+ return states;
+ };
+
+ this.getTitle = function(index) {
+ if (index >= this.titles.length) {
+ return index + 1;
+ } else {
+ return this.titles[index];
+ }
+ };
+
+ $scope.rate = function(value) {
+ if (!$scope.readonly && value >= 0 && value <= $scope.range.length) {
+ ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue === value ? 0 : value);
+ ngModelCtrl.$render();
+ }
+ };
+
+ $scope.enter = function(value) {
+ if (!$scope.readonly) {
+ $scope.value = value;
+ }
+ $scope.onHover({value: value});
+ };
+
+ $scope.reset = function() {
+ $scope.value = ngModelCtrl.$viewValue;
+ $scope.onLeave();
+ };
+
+ $scope.onKeydown = function(evt) {
+ if (/(37|38|39|40)/.test(evt.which)) {
+ evt.preventDefault();
+ evt.stopPropagation();
+ $scope.rate($scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1));
+ }
+ };
+
+ this.render = function() {
+ $scope.value = ngModelCtrl.$viewValue;
+ };
+}])
+
+.directive('uibRating', function() {
+ return {
+ require: ['uibRating', 'ngModel'],
+ scope: {
+ readonly: '=?',
+ onHover: '&',
+ onLeave: '&'
+ },
+ controller: 'UibRatingController',
+ templateUrl: 'template/rating/rating.html',
+ replace: true,
+ link: function(scope, element, attrs, ctrls) {
+ var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+ ratingCtrl.init(ngModelCtrl);
+ }
+ };
+});
+
+/* Deprecated rating below */
+
+angular.module('ui.bootstrap.rating')
+
+.value('$ratingSuppressWarning', false)
+
+.controller('RatingController', ['$scope', '$attrs', '$controller', '$log', '$ratingSuppressWarning', function($scope, $attrs, $controller, $log, $ratingSuppressWarning) {
+ if (!$ratingSuppressWarning) {
+ $log.warn('RatingController is now deprecated. Use UibRatingController instead.');
+ }
+
+ angular.extend(this, $controller('UibRatingController', {
+ $scope: $scope,
+ $attrs: $attrs
+ }));
+}])
+
+.directive('rating', ['$log', '$ratingSuppressWarning', function($log, $ratingSuppressWarning) {
+ return {
+ require: ['rating', 'ngModel'],
+ scope: {
+ readonly: '=?',
+ onHover: '&',
+ onLeave: '&'
+ },
+ controller: 'RatingController',
+ templateUrl: 'template/rating/rating.html',
+ replace: true,
+ link: function(scope, element, attrs, ctrls) {
+ if (!$ratingSuppressWarning) {
+ $log.warn('rating is now deprecated. Use uib-rating instead.');
+ }
+ var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+ ratingCtrl.init(ngModelCtrl);
+ }
+ };
+}]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/test/rating.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/test/rating.spec.js
new file mode 100644
index 0000000..e51bc69
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/rating/test/rating.spec.js
@@ -0,0 +1,361 @@
+describe('rating directive', function() {
+ var $rootScope, $compile, element;
+ beforeEach(module('ui.bootstrap.rating'));
+ beforeEach(module('template/rating/rating.html'));
+ beforeEach(inject(function(_$compile_, _$rootScope_) {
+ $compile = _$compile_;
+ $rootScope = _$rootScope_;
+ $rootScope.rate = 3;
+ element = $compile('<uib-rating ng-model="rate"></uib-rating>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ function getStars() {
+ return element.find('i');
+ }
+
+ function getStar(number) {
+ return getStars().eq(number - 1);
+ }
+
+ function getState(classOn, classOff) {
+ var stars = getStars();
+ var state = [];
+ for (var i = 0, n = stars.length; i < n; i++) {
+ state.push((stars.eq(i).hasClass(classOn || 'glyphicon-star') && ! stars.eq(i).hasClass(classOff || 'glyphicon-star-empty')));
+ }
+ return state;
+ }
+
+ function getTitles() {
+ var stars = getStars();
+ return stars.toArray().map(function(star) {
+ return angular.element(star).attr('title');
+ });
+ }
+
+ function triggerKeyDown(keyCode) {
+ var e = $.Event('keydown');
+ e.which = keyCode;
+ element.trigger(e);
+ }
+
+ it('contains the default number of icons', function() {
+ expect(getStars().length).toBe(5);
+ expect(element.attr('aria-valuemax')).toBe('5');
+ });
+
+ it('initializes the default star icons as selected', function() {
+ expect(getState()).toEqual([true, true, true, false, false]);
+ expect(element.attr('aria-valuenow')).toBe('3');
+ });
+
+ it('handles correctly the click event', function() {
+ getStar(2).click();
+ $rootScope.$digest();
+ expect(getState()).toEqual([true, true, false, false, false]);
+ expect($rootScope.rate).toBe(2);
+ expect(element.attr('aria-valuenow')).toBe('2');
+
+ getStar(5).click();
+ $rootScope.$digest();
+ expect(getState()).toEqual([true, true, true, true, true]);
+ expect($rootScope.rate).toBe(5);
+ expect(element.attr('aria-valuenow')).toBe('5');
+
+ getStar(5).click();
+ $rootScope.$digest();
+ expect(getState()).toEqual([false, false, false, false, false]);
+ expect($rootScope.rate).toBe(0);
+ expect(element.attr('aria-valuenow')).toBe('0');
+ });
+
+ it('handles correctly the hover event', function() {
+ getStar(2).trigger('mouseover');
+ $rootScope.$digest();
+ expect(getState()).toEqual([true, true, false, false, false]);
+ expect($rootScope.rate).toBe(3);
+
+ getStar(5).trigger('mouseover');
+ $rootScope.$digest();
+ expect(getState()).toEqual([true, true, true, true, true]);
+ expect($rootScope.rate).toBe(3);
+
+ element.trigger('mouseout');
+ expect(getState()).toEqual([true, true, true, false, false]);
+ expect($rootScope.rate).toBe(3);
+ });
+
+ it('rounds off the number of stars shown with decimal values', function() {
+ $rootScope.rate = 2.1;
+ $rootScope.$digest();
+
+ expect(getState()).toEqual([true, true, false, false, false]);
+ expect(element.attr('aria-valuenow')).toBe('2');
+
+ $rootScope.rate = 2.5;
+ $rootScope.$digest();
+
+ expect(getState()).toEqual([true, true, true, false, false]);
+ expect(element.attr('aria-valuenow')).toBe('3');
+ });
+
+ it('changes the number of selected icons when value changes', function() {
+ $rootScope.rate = 2;
+ $rootScope.$digest();
+
+ expect(getState()).toEqual([true, true, false, false, false]);
+ expect(element.attr('aria-valuenow')).toBe('2');
+ });
+
+ it('shows different number of icons when `max` attribute is set', function() {
+ element = $compile('<uib-rating ng-model="rate" max="7"></uib-rating>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getStars().length).toBe(7);
+ expect(element.attr('aria-valuemax')).toBe('7');
+ });
+
+ it('shows different number of icons when `max` attribute is from scope variable', function() {
+ $rootScope.max = 15;
+ element = $compile('<uib-rating ng-model="rate" max="max"></uib-rating>')($rootScope);
+ $rootScope.$digest();
+ expect(getStars().length).toBe(15);
+ expect(element.attr('aria-valuemax')).toBe('15');
+ });
+
+ it('handles readonly attribute', function() {
+ $rootScope.isReadonly = true;
+ element = $compile('<uib-rating ng-model="rate" readonly="isReadonly"></uib-rating>')($rootScope);
+ $rootScope.$digest();
+
+ expect(getState()).toEqual([true, true, true, false, false]);
+
+ var star5 = getStar(5);
+ star5.trigger('mouseover');
+ $rootScope.$digest();
+ expect(getState()).toEqual([true, true, true, false, false]);
+
+ $rootScope.isReadonly = false;
+ $rootScope.$digest();
+
+ star5.trigger('mouseover');
+ $rootScope.$digest();
+ expect(getState()).toEqual([true, true, true, true, true]);
+ });
+
+ it('should fire onHover', function() {
+ $rootScope.hoveringOver = jasmine.createSpy('hoveringOver');
+ element = $compile('<uib-rating ng-model="rate" on-hover="hoveringOver(value)"></uib-rating>')($rootScope);
+ $rootScope.$digest();
+
+ getStar(3).trigger('mouseover');
+ $rootScope.$digest();
+ expect($rootScope.hoveringOver).toHaveBeenCalledWith(3);
+ });
+
+ it('should fire onLeave', function() {
+ $rootScope.leaving = jasmine.createSpy('leaving');
+ element = $compile('<uib-rating ng-model="rate" on-leave="leaving()"></uib-rating>')($rootScope);
+ $rootScope.$digest();
+
+ element.trigger('mouseleave');
+ $rootScope.$digest();
+ expect($rootScope.leaving).toHaveBeenCalled();
+ });
+
+ describe('keyboard navigation', function() {
+ it('supports arrow keys', function() {
+ triggerKeyDown(38);
+ expect($rootScope.rate).toBe(4);
+
+ triggerKeyDown(37);
+ expect($rootScope.rate).toBe(3);
+ triggerKeyDown(40);
+ expect($rootScope.rate).toBe(2);
+
+ triggerKeyDown(39);
+ expect($rootScope.rate).toBe(3);
+ });
+
+ it('supports only arrow keys', function() {
+ $rootScope.rate = undefined;
+ $rootScope.$digest();
+
+ triggerKeyDown(36);
+ expect($rootScope.rate).toBe(undefined);
+
+ triggerKeyDown(41);
+ expect($rootScope.rate).toBe(undefined);
+ });
+
+ it('can get zero value but not negative', function() {
+ $rootScope.rate = 1;
+ $rootScope.$digest();
+
+ triggerKeyDown(37);
+ expect($rootScope.rate).toBe(0);
+
+ triggerKeyDown(37);
+ expect($rootScope.rate).toBe(0);
+ });
+
+ it('cannot get value above max', function() {
+ $rootScope.rate = 4;
+ $rootScope.$digest();
+
+ triggerKeyDown(38);
+ expect($rootScope.rate).toBe(5);
+
+ triggerKeyDown(38);
+ expect($rootScope.rate).toBe(5);
+ });
+ });
+
+ describe('custom states', function() {
+ beforeEach(inject(function() {
+ $rootScope.classOn = 'icon-ok-sign';
+ $rootScope.classOff = 'icon-ok-circle';
+ element = $compile('<uib-rating ng-model="rate" state-on="classOn" state-off="classOff"></uib-rating>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('changes the default icons', function() {
+ expect(getState($rootScope.classOn, $rootScope.classOff)).toEqual([true, true, true, false, false]);
+ });
+ });
+
+ describe('`rating-states`', function() {
+ beforeEach(inject(function() {
+ $rootScope.states = [
+ {stateOn: 'sign', stateOff: 'circle'},
+ {stateOn: 'heart', stateOff: 'ban'},
+ {stateOn: 'heart'},
+ {stateOff: 'off'}
+ ];
+ element = $compile('<uib-rating ng-model="rate" rating-states="states"></uib-rating>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('should define number of icon elements', function() {
+ expect(getStars().length).toBe(4);
+ expect(element.attr('aria-valuemax')).toBe('4');
+ });
+
+ it('handles each icon', function() {
+ var stars = getStars();
+
+ for (var i = 0; i < stars.length; i++) {
+ var star = stars.eq(i);
+ var state = $rootScope.states[i];
+ var isOn = i < $rootScope.rate;
+
+ expect(star.hasClass(state.stateOn)).toBe(isOn);
+ expect(star.hasClass(state.stateOff)).toBe(!isOn);
+ }
+ });
+ });
+
+ describe('setting uibRatingConfig', function() {
+ var originalConfig = {};
+ beforeEach(inject(function(uibRatingConfig) {
+ $rootScope.rate = 5;
+ angular.extend(originalConfig, uibRatingConfig);
+ uibRatingConfig.max = 10;
+ uibRatingConfig.stateOn = 'on';
+ uibRatingConfig.stateOff = 'off';
+ element = $compile('<uib-rating ng-model="rate"></uib-rating>')($rootScope);
+ $rootScope.$digest();
+ }));
+ afterEach(inject(function(uibRatingConfig) {
+ // return it to the original state
+ angular.extend(uibRatingConfig, originalConfig);
+ }));
+
+ it('should change number of icon elements', function() {
+ expect(getStars().length).toBe(10);
+ });
+
+ it('should change icon states', function() {
+ expect(getState('on', 'off')).toEqual([true, true, true, true, true, false, false, false, false, false]);
+ });
+ });
+
+ describe('Default title', function() {
+ it('should return the default title for each star', function() {
+ expect(getTitles()).toEqual(['one', 'two', 'three', 'four', 'five']);
+ });
+ });
+
+ describe('shows different title when `max` attribute is greater than the titles array ', function() {
+ var originalConfig = {};
+ beforeEach(inject(function(uibRatingConfig) {
+ $rootScope.rate = 5;
+ angular.extend(originalConfig, uibRatingConfig);
+ uibRatingConfig.max = 10;
+ element = $compile('<uib-rating ng-model="rate"></uib-rating>')($rootScope);
+ $rootScope.$digest();
+ }));
+ afterEach(inject(function(uibRatingConfig) {
+ // return it to the original state
+ angular.extend(uibRatingConfig, originalConfig);
+ }));
+
+ it('should return the default title for each star', function() {
+ expect(getTitles()).toEqual(['one', 'two', 'three', 'four', 'five', '6', '7', '8', '9', '10']);
+ });
+ });
+
+ describe('shows custom titles ', function() {
+ it('should return the custom title for each star', function() {
+ $rootScope.titles = [44,45,46];
+ element = $compile('<uib-rating ng-model="rate" titles="titles"></uib-rating>')($rootScope);
+ $rootScope.$digest();
+ expect(getTitles()).toEqual(['44', '45', '46', '4', '5']);
+ });
+ it('should return the default title if the custom title is empty', function() {
+ $rootScope.titles = [];
+ element = $compile('<uib-rating ng-model="rate" titles="titles"></uib-rating>')($rootScope);
+ $rootScope.$digest();
+ expect(getTitles()).toEqual(['one', 'two', 'three', 'four', 'five']);
+ });
+ it('should return the default title if the custom title is not an array', function() {
+ element = $compile('<uib-rating ng-model="rate" titles="test"></uib-rating>')($rootScope);
+ $rootScope.$digest();
+ expect(getTitles()).toEqual(['one', 'two', 'three', 'four', 'five']);
+ });
+ });
+});
+
+/* Deprecation tests below */
+
+describe('rating deprecation', function() {
+ beforeEach(module('ui.bootstrap.rating'));
+ beforeEach(module('template/rating/rating.html'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$ratingSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = $compile('<rating ng-model="rate"></rating>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = $compile('<rating ng-model="rate"></rating>')($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(2);
+ expect($log.warn.calls.argsFor(0)).toEqual(['RatingController is now deprecated. Use UibRatingController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['rating is now deprecated. Use uib-rating instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/stackedMap/stackedMap.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/stackedMap/stackedMap.js
new file mode 100644
index 0000000..bd97fb6
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/stackedMap/stackedMap.js
@@ -0,0 +1,54 @@
+angular.module('ui.bootstrap.stackedMap', [])
+/**
+ * A helper, internal data structure that acts as a map but also allows getting / removing
+ * elements in the LIFO order
+ */
+ .factory('$$stackedMap', function() {
+ return {
+ createNew: function() {
+ var stack = [];
+
+ return {
+ add: function(key, value) {
+ stack.push({
+ key: key,
+ value: value
+ });
+ },
+ get: function(key) {
+ for (var i = 0; i < stack.length; i++) {
+ if (key == stack[i].key) {
+ return stack[i];
+ }
+ }
+ },
+ keys: function() {
+ var keys = [];
+ for (var i = 0; i < stack.length; i++) {
+ keys.push(stack[i].key);
+ }
+ return keys;
+ },
+ top: function() {
+ return stack[stack.length - 1];
+ },
+ remove: function(key) {
+ var idx = -1;
+ for (var i = 0; i < stack.length; i++) {
+ if (key == stack[i].key) {
+ idx = i;
+ break;
+ }
+ }
+ return stack.splice(idx, 1)[0];
+ },
+ removeTop: function() {
+ return stack.splice(stack.length - 1, 1)[0];
+ },
+ length: function() {
+ return stack.length;
+ }
+ };
+ }
+ };
+ });
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/stackedMap/test/stackedMap.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/stackedMap/test/stackedMap.spec.js
new file mode 100644
index 0000000..62ad5d6
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/stackedMap/test/stackedMap.spec.js
@@ -0,0 +1,52 @@
+describe('stacked map', function() {
+ var stackedMap;
+
+ beforeEach(module('ui.bootstrap.modal'));
+ beforeEach(inject(function ($$stackedMap) {
+ stackedMap = $$stackedMap.createNew();
+ }));
+
+ it('should add and remove objects by key', function() {
+ stackedMap.add('foo', 'foo_value');
+ expect(stackedMap.length()).toEqual(1);
+ expect(stackedMap.get('foo').key).toEqual('foo');
+ expect(stackedMap.get('foo').value).toEqual('foo_value');
+
+ stackedMap.remove('foo');
+ expect(stackedMap.length()).toEqual(0);
+ expect(stackedMap.get('foo')).toBeUndefined();
+ });
+
+ it('should support listing keys', function() {
+ stackedMap.add('foo', 'foo_value');
+ stackedMap.add('bar', 'bar_value');
+
+ expect(stackedMap.keys()).toEqual(['foo', 'bar']);
+ });
+
+ it('should get topmost element', function() {
+ stackedMap.add('foo', 'foo_value');
+ stackedMap.add('bar', 'bar_value');
+ expect(stackedMap.length()).toEqual(2);
+
+ expect(stackedMap.top().key).toEqual('bar');
+ expect(stackedMap.length()).toEqual(2);
+ });
+
+ it('should remove topmost element', function() {
+ stackedMap.add('foo', 'foo_value');
+ stackedMap.add('bar', 'bar_value');
+
+ expect(stackedMap.removeTop().key).toEqual('bar');
+ expect(stackedMap.removeTop().key).toEqual('foo');
+ });
+
+ it('should preserve semantic of an empty stackedMap', function() {
+ expect(stackedMap.length()).toEqual(0);
+ expect(stackedMap.top()).toBeUndefined();
+ });
+
+ it('should ignore removal of non-existing elements', function() {
+ expect(stackedMap.remove('non-existing')).toBeUndefined();
+ });
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/docs/demo.html
new file mode 100644
index 0000000..8a848d3
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/docs/demo.html
@@ -0,0 +1,39 @@
+<div ng-controller="TabsDemoCtrl">
+ <p>Select a tab by setting active binding to true:</p>
+ <p>
+ <button type="button" class="btn btn-default btn-sm" ng-click="tabs[0].active = true">Select second tab</button>
+ <button type="button" class="btn btn-default btn-sm" ng-click="tabs[1].active = true">Select third tab</button>
+ </p>
+ <p>
+ <button type="button" class="btn btn-default btn-sm" ng-click="tabs[1].disabled = ! tabs[1].disabled">Enable / Disable third tab</button>
+ </p>
+ <hr />
+
+ <uib-tabset>
+ <uib-tab heading="Static title">Static content</uib-tab>
+ <uib-tab ng-repeat="tab in tabs" heading="{{tab.title}}" active="tab.active" disable="tab.disabled">
+ {{tab.content}}
+ </uib-tab>
+ <uib-tab select="alertMe()">
+ <uib-tab-heading>
+ <i class="glyphicon glyphicon-bell"></i> Alert!
+ </uib-tab-heading>
+ I've got an HTML heading, and a select callback. Pretty cool!
+ </uib-tab>
+ </uib-tabset>
+
+ <hr />
+
+ <uib-tabset vertical="true" type="pills">
+ <uib-tab heading="Vertical 1">Vertical content 1</uib-tab>
+ <uib-tab heading="Vertical 2">Vertical content 2</uib-tab>
+ </uib-tabset>
+
+ <hr />
+
+ <uib-tabset justified="true">
+ <uib-tab heading="Justified">Justified content</uib-tab>
+ <uib-tab heading="SJ">Short Labeled Justified content</uib-tab>
+ <uib-tab heading="Long Justified">Long Labeled Justified content</uib-tab>
+ </uib-tabset>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/docs/demo.js
new file mode 100644
index 0000000..f3d64fd
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/docs/demo.js
@@ -0,0 +1,12 @@
+angular.module('ui.bootstrap.demo').controller('TabsDemoCtrl', function ($scope, $window) {
+ $scope.tabs = [
+ { title:'Dynamic Title 1', content:'Dynamic content 1' },
+ { title:'Dynamic Title 2', content:'Dynamic content 2', disabled: true }
+ ];
+
+ $scope.alertMe = function() {
+ setTimeout(function() {
+ $window.alert('You\'ve selected the alert tab!');
+ });
+ };
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/docs/readme.md
new file mode 100644
index 0000000..d00461c
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/docs/readme.md
@@ -0,0 +1,40 @@
+AngularJS version of the tabs directive.
+
+### Settings ###
+
+#### `<uib-tabset>` ####
+
+ * `vertical`
+ _(Defaults: false)_ :
+ Whether tabs appear vertically stacked.
+
+ * `justified`
+ _(Defaults: false)_ :
+ Whether tabs fill the container and have a consistent width.
+
+ * `type`
+ _(Defaults: 'tabs')_ :
+ Navigation type. Possible values are 'tabs' and 'pills'.
+
+#### `<uib-tab>` ####
+
+ * `heading` or `<uib-tab-heading>`
+ :
+ Heading text or HTML markup.
+
+ * `active` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: false)_ :
+ Whether tab is currently selected.
+
+ * `disable` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: false)_ :
+ Whether tab is clickable and can be activated.
+ Note that this was previously the `disabled` attribute, which is now deprecated.
+
+ * `select()`
+ _(Defaults: null)_ :
+ An optional expression called when tab is activated.
+
+ * `deselect()`
+ _(Defaults: null)_ :
+ An optional expression called when tab is deactivated.
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/tabs.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/tabs.js
new file mode 100644
index 0000000..cb68c8d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/tabs.js
@@ -0,0 +1,439 @@
+
+/**
+ * @ngdoc overview
+ * @name ui.bootstrap.tabs
+ *
+ * @description
+ * AngularJS version of the tabs directive.
+ */
+
+angular.module('ui.bootstrap.tabs', [])
+
+.controller('UibTabsetController', ['$scope', function ($scope) {
+ var ctrl = this,
+ tabs = ctrl.tabs = $scope.tabs = [];
+
+ ctrl.select = function(selectedTab) {
+ angular.forEach(tabs, function(tab) {
+ if (tab.active && tab !== selectedTab) {
+ tab.active = false;
+ tab.onDeselect();
+ selectedTab.selectCalled = false;
+ }
+ });
+ selectedTab.active = true;
+ // only call select if it has not already been called
+ if (!selectedTab.selectCalled) {
+ selectedTab.onSelect();
+ selectedTab.selectCalled = true;
+ }
+ };
+
+ ctrl.addTab = function addTab(tab) {
+ tabs.push(tab);
+ // we can't run the select function on the first tab
+ // since that would select it twice
+ if (tabs.length === 1 && tab.active !== false) {
+ tab.active = true;
+ } else if (tab.active) {
+ ctrl.select(tab);
+ } else {
+ tab.active = false;
+ }
+ };
+
+ ctrl.removeTab = function removeTab(tab) {
+ var index = tabs.indexOf(tab);
+ //Select a new tab if the tab to be removed is selected and not destroyed
+ if (tab.active && tabs.length > 1 && !destroyed) {
+ //If this is the last tab, select the previous tab. else, the next tab.
+ var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1;
+ ctrl.select(tabs[newActiveIndex]);
+ }
+ tabs.splice(index, 1);
+ };
+
+ var destroyed;
+ $scope.$on('$destroy', function() {
+ destroyed = true;
+ });
+}])
+
+/**
+ * @ngdoc directive
+ * @name ui.bootstrap.tabs.directive:tabset
+ * @restrict EA
+ *
+ * @description
+ * Tabset is the outer container for the tabs directive
+ *
+ * @param {boolean=} vertical Whether or not to use vertical styling for the tabs.
+ * @param {boolean=} justified Whether or not to use justified styling for the tabs.
+ *
+ * @example
+<example module="ui.bootstrap">
+ <file name="index.html">
+ <uib-tabset>
+ <uib-tab heading="Tab 1"><b>First</b> Content!</uib-tab>
+ <uib-tab heading="Tab 2"><i>Second</i> Content!</uib-tab>
+ </uib-tabset>
+ <hr />
+ <uib-tabset vertical="true">
+ <uib-tab heading="Vertical Tab 1"><b>First</b> Vertical Content!</uib-tab>
+ <uib-tab heading="Vertical Tab 2"><i>Second</i> Vertical Content!</uib-tab>
+ </uib-tabset>
+ <uib-tabset justified="true">
+ <uib-tab heading="Justified Tab 1"><b>First</b> Justified Content!</uib-tab>
+ <uib-tab heading="Justified Tab 2"><i>Second</i> Justified Content!</uib-tab>
+ </uib-tabset>
+ </file>
+</example>
+ */
+.directive('uibTabset', function() {
+ return {
+ restrict: 'EA',
+ transclude: true,
+ replace: true,
+ scope: {
+ type: '@'
+ },
+ controller: 'UibTabsetController',
+ templateUrl: 'template/tabs/tabset.html',
+ link: function(scope, element, attrs) {
+ scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;
+ scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false;
+ }
+ };
+})
+
+/**
+ * @ngdoc directive
+ * @name ui.bootstrap.tabs.directive:tab
+ * @restrict EA
+ *
+ * @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}.
+ * @param {string=} select An expression to evaluate when the tab is selected.
+ * @param {boolean=} active A binding, telling whether or not this tab is selected.
+ * @param {boolean=} disabled A binding, telling whether or not this tab is disabled.
+ *
+ * @description
+ * Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}.
+ *
+ * @example
+<example module="ui.bootstrap">
+ <file name="index.html">
+ <div ng-controller="TabsDemoCtrl">
+ <button class="btn btn-small" ng-click="items[0].active = true">
+ Select item 1, using active binding
+ </button>
+ <button class="btn btn-small" ng-click="items[1].disabled = !items[1].disabled">
+ Enable/disable item 2, using disabled binding
+ </button>
+ <br />
+ <uib-tabset>
+ <uib-tab heading="Tab 1">First Tab</uib-tab>
+ <uib-tab select="alertMe()">
+ <uib-tab-heading><i class="icon-bell"></i> Alert me!</tab-heading>
+ Second Tab, with alert callback and html heading!
+ </uib-tab>
+ <uib-tab ng-repeat="item in items"
+ heading="{{item.title}}"
+ disabled="item.disabled"
+ active="item.active">
+ {{item.content}}
+ </uib-tab>
+ </uib-tabset>
+ </div>
+ </file>
+ <file name="script.js">
+ function TabsDemoCtrl($scope) {
+ $scope.items = [
+ { title:"Dynamic Title 1", content:"Dynamic Item 0" },
+ { title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true }
+ ];
+
+ $scope.alertMe = function() {
+ setTimeout(function() {
+ alert("You've selected the alert tab!");
+ });
+ };
+ };
+ </file>
+</example>
+ */
+
+/**
+ * @ngdoc directive
+ * @name ui.bootstrap.tabs.directive:tabHeading
+ * @restrict EA
+ *
+ * @description
+ * Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element.
+ *
+ * @example
+<example module="ui.bootstrap">
+ <file name="index.html">
+ <uib-tabset>
+ <uib-tab>
+ <uib-tab-heading><b>HTML</b> in my titles?!</tab-heading>
+ And some content, too!
+ </uib-tab>
+ <uib-tab>
+ <uib-tab-heading><i class="icon-heart"></i> Icon heading?!?</tab-heading>
+ That's right.
+ </uib-tab>
+ </uib-tabset>
+ </file>
+</example>
+ */
+.directive('uibTab', ['$parse', function($parse) {
+ return {
+ require: '^uibTabset',
+ restrict: 'EA',
+ replace: true,
+ templateUrl: 'template/tabs/tab.html',
+ transclude: true,
+ scope: {
+ active: '=?',
+ heading: '@',
+ onSelect: '&select', //This callback is called in contentHeadingTransclude
+ //once it inserts the tab's content into the dom
+ onDeselect: '&deselect'
+ },
+ controller: function() {
+ //Empty controller so other directives can require being 'under' a tab
+ },
+ link: function(scope, elm, attrs, tabsetCtrl, transclude) {
+ scope.$watch('active', function(active) {
+ if (active) {
+ tabsetCtrl.select(scope);
+ }
+ });
+
+ scope.disabled = false;
+ if (attrs.disable) {
+ scope.$parent.$watch($parse(attrs.disable), function(value) {
+ scope.disabled = !! value;
+ });
+ }
+
+ scope.select = function() {
+ if (!scope.disabled) {
+ scope.active = true;
+ }
+ };
+
+ tabsetCtrl.addTab(scope);
+ scope.$on('$destroy', function() {
+ tabsetCtrl.removeTab(scope);
+ });
+
+ //We need to transclude later, once the content container is ready.
+ //when this link happens, we're inside a tab heading.
+ scope.$transcludeFn = transclude;
+ }
+ };
+}])
+
+.directive('uibTabHeadingTransclude', function() {
+ return {
+ restrict: 'A',
+ require: ['?^uibTab', '?^tab'], // TODO: change to '^uibTab' after deprecation removal
+ link: function(scope, elm) {
+ scope.$watch('headingElement', function updateHeadingElement(heading) {
+ if (heading) {
+ elm.html('');
+ elm.append(heading);
+ }
+ });
+ }
+ };
+})
+
+.directive('uibTabContentTransclude', function() {
+ return {
+ restrict: 'A',
+ require: ['?^uibTabset', '?^tabset'], // TODO: change to '^uibTabset' after deprecation removal
+ link: function(scope, elm, attrs) {
+ var tab = scope.$eval(attrs.uibTabContentTransclude);
+
+ //Now our tab is ready to be transcluded: both the tab heading area
+ //and the tab content area are loaded. Transclude 'em both.
+ tab.$transcludeFn(tab.$parent, function(contents) {
+ angular.forEach(contents, function(node) {
+ if (isTabHeading(node)) {
+ //Let tabHeadingTransclude know.
+ tab.headingElement = node;
+ } else {
+ elm.append(node);
+ }
+ });
+ });
+ }
+ };
+
+ function isTabHeading(node) {
+ return node.tagName && (
+ node.hasAttribute('tab-heading') || // TODO: remove after deprecation removal
+ node.hasAttribute('data-tab-heading') || // TODO: remove after deprecation removal
+ node.hasAttribute('x-tab-heading') || // TODO: remove after deprecation removal
+ node.hasAttribute('uib-tab-heading') ||
+ node.hasAttribute('data-uib-tab-heading') ||
+ node.hasAttribute('x-uib-tab-heading') ||
+ node.tagName.toLowerCase() === 'tab-heading' || // TODO: remove after deprecation removal
+ node.tagName.toLowerCase() === 'data-tab-heading' || // TODO: remove after deprecation removal
+ node.tagName.toLowerCase() === 'x-tab-heading' || // TODO: remove after deprecation removal
+ node.tagName.toLowerCase() === 'uib-tab-heading' ||
+ node.tagName.toLowerCase() === 'data-uib-tab-heading' ||
+ node.tagName.toLowerCase() === 'x-uib-tab-heading'
+ );
+ }
+});
+
+/* deprecated tabs below */
+
+angular.module('ui.bootstrap.tabs')
+
+ .value('$tabsSuppressWarning', false)
+
+ .controller('TabsetController', ['$scope', '$controller', '$log', '$tabsSuppressWarning', function($scope, $controller, $log, $tabsSuppressWarning) {
+ if (!$tabsSuppressWarning) {
+ $log.warn('TabsetController is now deprecated. Use UibTabsetController instead.');
+ }
+
+ angular.extend(this, $controller('UibTabsetController', {
+ $scope: $scope
+ }));
+ }])
+
+ .directive('tabset', ['$log', '$tabsSuppressWarning', function($log, $tabsSuppressWarning) {
+ return {
+ restrict: 'EA',
+ transclude: true,
+ replace: true,
+ scope: {
+ type: '@'
+ },
+ controller: 'TabsetController',
+ templateUrl: 'template/tabs/tabset.html',
+ link: function(scope, element, attrs) {
+
+ if (!$tabsSuppressWarning) {
+ $log.warn('tabset is now deprecated. Use uib-tabset instead.');
+ }
+ scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;
+ scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false;
+ }
+ };
+ }])
+
+ .directive('tab', ['$parse', '$log', '$tabsSuppressWarning', function($parse, $log, $tabsSuppressWarning) {
+ return {
+ require: '^tabset',
+ restrict: 'EA',
+ replace: true,
+ templateUrl: 'template/tabs/tab.html',
+ transclude: true,
+ scope: {
+ active: '=?',
+ heading: '@',
+ onSelect: '&select', //This callback is called in contentHeadingTransclude
+ //once it inserts the tab's content into the dom
+ onDeselect: '&deselect'
+ },
+ controller: function() {
+ //Empty controller so other directives can require being 'under' a tab
+ },
+ link: function(scope, elm, attrs, tabsetCtrl, transclude) {
+ if (!$tabsSuppressWarning) {
+ $log.warn('tab is now deprecated. Use uib-tab instead.');
+ }
+
+ scope.$watch('active', function(active) {
+ if (active) {
+ tabsetCtrl.select(scope);
+ }
+ });
+
+ scope.disabled = false;
+ if (attrs.disable) {
+ scope.$parent.$watch($parse(attrs.disable), function(value) {
+ scope.disabled = !!value;
+ });
+ }
+
+ scope.select = function() {
+ if (!scope.disabled) {
+ scope.active = true;
+ }
+ };
+
+ tabsetCtrl.addTab(scope);
+ scope.$on('$destroy', function() {
+ tabsetCtrl.removeTab(scope);
+ });
+
+ //We need to transclude later, once the content container is ready.
+ //when this link happens, we're inside a tab heading.
+ scope.$transcludeFn = transclude;
+ }
+ };
+ }])
+
+ .directive('tabHeadingTransclude', ['$log', '$tabsSuppressWarning', function($log, $tabsSuppressWarning) {
+ return {
+ restrict: 'A',
+ require: '^tab',
+ link: function(scope, elm) {
+ if (!$tabsSuppressWarning) {
+ $log.warn('tab-heading-transclude is now deprecated. Use uib-tab-heading-transclude instead.');
+ }
+
+ scope.$watch('headingElement', function updateHeadingElement(heading) {
+ if (heading) {
+ elm.html('');
+ elm.append(heading);
+ }
+ });
+ }
+ };
+ }])
+
+ .directive('tabContentTransclude', ['$log', '$tabsSuppressWarning', function($log, $tabsSuppressWarning) {
+ return {
+ restrict: 'A',
+ require: '^tabset',
+ link: function(scope, elm, attrs) {
+ if (!$tabsSuppressWarning) {
+ $log.warn('tab-content-transclude is now deprecated. Use uib-tab-content-transclude instead.');
+ }
+
+ var tab = scope.$eval(attrs.tabContentTransclude);
+
+ //Now our tab is ready to be transcluded: both the tab heading area
+ //and the tab content area are loaded. Transclude 'em both.
+ tab.$transcludeFn(tab.$parent, function(contents) {
+ angular.forEach(contents, function(node) {
+ if (isTabHeading(node)) {
+ //Let tabHeadingTransclude know.
+ tab.headingElement = node;
+ }
+ else {
+ elm.append(node);
+ }
+ });
+ });
+ }
+ };
+
+ function isTabHeading(node) {
+ return node.tagName && (
+ node.hasAttribute('tab-heading') ||
+ node.hasAttribute('data-tab-heading') ||
+ node.hasAttribute('x-tab-heading') ||
+ node.tagName.toLowerCase() === 'tab-heading' ||
+ node.tagName.toLowerCase() === 'data-tab-heading' ||
+ node.tagName.toLowerCase() === 'x-tab-heading'
+ );
+ }
+ }]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/test/tabs.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/test/tabs.spec.js
new file mode 100644
index 0000000..1de3c25
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tabs/test/tabs.spec.js
@@ -0,0 +1,923 @@
+describe('tabs', function() {
+ var elm, scope;
+
+ beforeEach(module('ui.bootstrap.tabs'));
+ beforeEach(module('template/tabs/tabset.html'));
+ beforeEach(module('template/tabs/tab.html'));
+
+ function titles() {
+ return elm.find('ul.nav-tabs li');
+ }
+ function contents() {
+ return elm.find('div.tab-content div.tab-pane');
+ }
+
+ function expectTitles(titlesArray) {
+ var t = titles();
+ expect(t.length).toEqual(titlesArray.length);
+ for (var i=0; i<t.length; i++) {
+ expect(t.eq(i).text().trim()).toEqual(titlesArray[i]);
+ }
+ }
+
+ function expectContents(contentsArray) {
+ var c = contents();
+ expect(c.length).toEqual(contentsArray.length);
+ for (var i=0; i<c.length; i++) {
+ expect(c.eq(i).text().trim()).toEqual(contentsArray[i]);
+ }
+ }
+
+ describe('basics', function() {
+ beforeEach(inject(function($compile, $rootScope) {
+ scope = $rootScope.$new();
+ scope.first = '1';
+ scope.second = '2';
+ scope.actives = {};
+ scope.selectFirst = jasmine.createSpy();
+ scope.selectSecond = jasmine.createSpy();
+ scope.deselectFirst = jasmine.createSpy();
+ scope.deselectSecond = jasmine.createSpy();
+ elm = $compile([
+ '<uib-tabset class="hello" data-pizza="pepperoni">',
+ ' <uib-tab heading="First Tab {{first}}" active="actives.one" select="selectFirst()" deselect="deselectFirst()">',
+ ' first content is {{first}}',
+ ' </uib-tab>',
+ ' <uib-tab active="actives.two" select="selectSecond()" deselect="deselectSecond()">',
+ ' <uib-tab-heading><b>Second</b> Tab {{second}}</uib-tab-heading>',
+ ' second content is {{second}}',
+ ' </uib-tab>',
+ '</uib-tabset>'
+ ].join('\n'))(scope);
+ scope.$apply();
+ return elm;
+ }));
+
+ it('should pass class and other attributes on to tab template', function() {
+ expect(elm).toHaveClass('hello');
+ expect(elm.attr('data-pizza')).toBe('pepperoni');
+ });
+
+ it('should create clickable titles', function() {
+ var t = titles();
+ expect(t.length).toBe(2);
+ expect(t.find('a').eq(0).text()).toBe('First Tab 1');
+ //It should put the uib-tab-heading element into the 'a' title
+ expect(t.find('a').eq(1).children().is('uib-tab-heading')).toBe(true);
+ expect(t.find('a').eq(1).children().html()).toBe('<b>Second</b> Tab 2');
+ });
+
+ it('should bind tabs content and set first tab active', function() {
+ expectContents(['first content is 1', 'second content is 2']);
+ expect(titles().eq(0)).toHaveClass('active');
+ expect(titles().eq(1)).not.toHaveClass('active');
+ expect(scope.actives.one).toBe(true);
+ expect(scope.actives.two).toBeFalsy();
+ });
+
+ it('should change active on click', function() {
+ titles().eq(1).find('a').click();
+ expect(contents().eq(1)).toHaveClass('active');
+ expect(titles().eq(0)).not.toHaveClass('active');
+ expect(titles().eq(1)).toHaveClass('active');
+ expect(scope.actives.one).toBe(false);
+ expect(scope.actives.two).toBe(true);
+ });
+
+ it('should call select callback on select', function() {
+ titles().eq(1).find('a').click();
+ expect(scope.selectSecond).toHaveBeenCalled();
+ titles().eq(0).find('a').click();
+ expect(scope.selectFirst).toHaveBeenCalled();
+ });
+
+ it('should call deselect callback on deselect', function() {
+ titles().eq(1).find('a').click();
+ titles().eq(0).find('a').click();
+ expect(scope.deselectSecond).toHaveBeenCalled();
+ titles().eq(1).find('a').click();
+ expect(scope.deselectFirst).toHaveBeenCalled();
+ });
+ });
+
+ describe('basics with initial active tab', function() {
+ beforeEach(inject(function($compile, $rootScope) {
+ scope = $rootScope.$new();
+
+ function makeTab(active) {
+ return {
+ active: !!active,
+ select: jasmine.createSpy()
+ };
+ }
+ scope.tabs = [
+ makeTab(), makeTab(), makeTab(true), makeTab()
+ ];
+ elm = $compile([
+ '<uib-tabset>',
+ ' <uib-tab active="tabs[0].active" select="tabs[0].select()">',
+ ' </uib-tab>',
+ ' <uib-tab active="tabs[1].active" select="tabs[1].select()">',
+ ' </uib-tab>',
+ ' <uib-tab active="tabs[2].active" select="tabs[2].select()">',
+ ' </uib-tab>',
+ ' <uib-tab active="tabs[3].active" select="tabs[3].select()">',
+ ' </uib-tab>',
+ '</uib-tabset>'
+ ].join('\n'))(scope);
+ scope.$apply();
+ }));
+
+ function expectTabActive(activeTab) {
+ var _titles = titles();
+ angular.forEach(scope.tabs, function(tab, i) {
+ if (activeTab === tab) {
+ expect(tab.active).toBe(true);
+ //It should only call select ONCE for each select
+ expect(tab.select).toHaveBeenCalled();
+ expect(_titles.eq(i)).toHaveClass('active');
+ expect(contents().eq(i)).toHaveClass('active');
+ } else {
+ expect(tab.active).toBe(false);
+ expect(_titles.eq(i)).not.toHaveClass('active');
+ }
+ });
+ }
+
+ it('should make tab titles and set active tab active', function() {
+ expect(titles().length).toBe(scope.tabs.length);
+ expectTabActive(scope.tabs[2]);
+ });
+ });
+
+ describe('tab callback order', function() {
+ var execOrder;
+ beforeEach(inject(function($compile, $rootScope) {
+ scope = $rootScope.$new();
+ execOrder = [];
+ scope.actives = {};
+
+ scope.execute = function(id) {
+ execOrder.push(id);
+ };
+
+ elm = $compile([
+ '<div>',
+ ' <uib-tabset class="hello" data-pizza="pepperoni">',
+ ' <uib-tab heading="First Tab" active="actives.one" select="execute(\'select1\')" deselect="execute(\'deselect1\')"></uib-tab>',
+ ' <uib-tab select="execute(\'select2\')" deselect="execute(\'deselect2\')"></uib-tab>',
+ ' </uib-tabset>',
+ '</div>'
+ ].join('\n'))(scope);
+ scope.$apply();
+ return elm;
+ }));
+
+ it('should call select for the first tab', function() {
+ expect(execOrder).toEqual([ 'select1' ]);
+ });
+
+ it('should call deselect, then select', function() {
+ execOrder = [];
+
+ // Select second tab
+ titles().eq(1).find('a').click();
+ expect(execOrder).toEqual([ 'deselect1', 'select2' ]);
+
+ execOrder = [];
+
+ // Select again first tab
+ titles().eq(0).find('a').click();
+ expect(execOrder).toEqual([ 'deselect2', 'select1' ]);
+ });
+ });
+
+ describe('ng-repeat', function() {
+ var $compile, $rootScope;
+ beforeEach(inject(function(_$compile_, _$rootScope_) {
+ $compile = _$compile_;
+ $rootScope = _$rootScope_;
+ scope = $rootScope.$new();
+
+ scope.tabs = [
+ makeTab(), makeTab(), makeTab(true), makeTab()
+ ];
+ elm = $compile([
+ '<uib-tabset>',
+ ' <uib-tab ng-repeat="t in tabs" active="t.active" select="t.select()">',
+ ' <uib-tab-heading><b>heading</b> {{index}}</uib-tab-heading>',
+ ' content {{$index}}',
+ ' </uib-tab>',
+ '</uib-tabset>'
+ ].join('\n'))(scope);
+ scope.$apply();
+ }));
+
+ function makeTab(active) {
+ return {
+ active: !!active,
+ select: jasmine.createSpy()
+ };
+ }
+
+ function titles() {
+ return elm.find('ul.nav-tabs li');
+ }
+ function contents() {
+ return elm.find('div.tab-content div.tab-pane');
+ }
+
+ function expectTabActive(activeTab) {
+ var _titles = titles();
+ angular.forEach(scope.tabs, function(tab, i) {
+ if (activeTab === tab) {
+ expect(tab.active).toBe(true);
+ //It should only call select ONCE for each select
+ expect(tab.select).toHaveBeenCalled();
+ expect(_titles.eq(i)).toHaveClass('active');
+ expect(contents().eq(i).text().trim()).toBe('content ' + i);
+ expect(contents().eq(i)).toHaveClass('active');
+ } else {
+ expect(tab.active).toBe(false);
+ expect(_titles.eq(i)).not.toHaveClass('active');
+ }
+ });
+ }
+
+ it('should make tab titles and set active tab active', function() {
+ expect(titles().length).toBe(scope.tabs.length);
+ expectTabActive(scope.tabs[2]);
+ });
+
+ it('should switch active when clicking', function() {
+ titles().eq(3).find('a').click();
+ expectTabActive(scope.tabs[3]);
+ });
+
+ it('should switch active when setting active=true', function() {
+ scope.$apply('tabs[2].active = true');
+ expectTabActive(scope.tabs[2]);
+ });
+
+ it('should deselect all when no tabs are active', function() {
+ angular.forEach(scope.tabs, function(t) { t.active = false; });
+ scope.$apply();
+ expectTabActive(null);
+ expect(contents().filter('.active').length).toBe(0);
+
+ scope.tabs[2].active = true;
+ scope.$apply();
+ expectTabActive(scope.tabs[2]);
+ });
+
+ it('should not select twice', function() {
+ elm.remove();
+ elm = null;
+ scope = $rootScope.$new();
+
+ scope.tabs = [
+ makeTab(), makeTab(), makeTab(true), makeTab()
+ ];
+ scope.foo = {active: true};
+ scope.select = jasmine.createSpy();
+ elm = $compile([
+ '<uib-tabset>',
+ ' <uib-tab ng-repeat="t in tabs" active="t.active" select="select()">',
+ ' <uib-tab-heading><b>heading</b> {{index}}</uib-tab-heading>',
+ ' content {{$index}}',
+ ' </uib-tab>',
+ ' <uib-tab active="foo.active" select="select()">',
+ ' <uib-tab-heading><b>heading</b> foo</uib-tab-heading>',
+ ' content foo',
+ ' </uib-tab>',
+ '</uib-tabset>'
+ ].join('\n'))(scope);
+ scope.$apply();
+
+ expect(scope.select.calls.count()).toBe(1);
+ });
+ });
+
+ describe('advanced uib-tab-heading element', function() {
+ beforeEach(inject(function($compile, $rootScope, $sce) {
+ scope = $rootScope.$new();
+ scope.myHtml = $sce.trustAsHtml('<b>hello</b>, there!');
+ scope.value = true;
+ elm = $compile([
+ '<uib-tabset>',
+ ' <uib-tab>',
+ ' <uib-tab-heading ng-bind-html="myHtml" ng-show="value"></uib-tab-heading>',
+ ' </uib-tab>',
+ ' <uib-tab><data-uib-tab-heading>1</data-uib-tab-heading></uib-tab>',
+ ' <uib-tab><div data-uib-tab-heading>2</div></uib-tab>',
+ ' <uib-tab><div uib-tab-heading>3</div></uib-tab>',
+ '</uib-tabset>'
+ ].join('\n'))(scope);
+ scope.$apply();
+ }));
+
+ function heading() {
+ return elm.find('ul li a').children();
+ }
+
+ it('should create a heading bound to myHtml', function() {
+ expect(heading().eq(0).html()).toBe('<b>hello</b>, there!');
+ });
+
+ it('should hide and show the heading depending on value', function() {
+ expect(heading().eq(0)).not.toBeHidden();
+ scope.$apply('value = false');
+ expect(heading().eq(0)).toBeHidden();
+ scope.$apply('value = true');
+ expect(heading().eq(0)).not.toBeHidden();
+ });
+
+ it('should have a uib-tab-heading no matter what syntax was used', function() {
+ expect(heading().eq(1).text()).toBe('1');
+ expect(heading().eq(2).text()).toBe('2');
+ expect(heading().eq(3).text()).toBe('3');
+ });
+
+ });
+
+ //Tests that http://git.io/lG6I9Q is fixed
+ describe('tab ordering', function() {
+ beforeEach(inject(function($compile, $rootScope) {
+ scope = $rootScope.$new();
+ scope.tabs = [
+ { title:'Title 1', available:true },
+ { title:'Title 2', available:true },
+ { title:'Title 3', available:true }
+ ];
+ elm = $compile([
+ '<uib-tabset>',
+ ' <!-- a comment -->',
+ ' <div>div that makes troubles</div>',
+ ' <uib-tab heading="first">First Static</uib-tab>',
+ ' <div>another div that may do evil</div>',
+ ' <uib-tab ng-repeat="tab in tabs | filter:tabIsAvailable" active="tab.active" heading="{{tab.title}}">some content</uib-tab>',
+ ' <!-- another comment -->',
+ ' <uib-tab heading="mid">Mid Static</uib-tab>',
+ ' a text node',
+ ' <!-- another comment -->',
+ ' <span>yet another span that may do evil</span>',
+ ' <uib-tab ng-repeat="tab in tabs | filter:tabIsAvailable" active="tab.active" heading="Second {{tab.title}}">some content</uib-tab>',
+ ' a text node',
+ ' <span>yet another span that may do evil</span>',
+ ' <!-- another comment -->',
+ ' <uib-tab heading="last">Last Static</uib-tab>',
+ ' a text node',
+ ' <span>yet another span that may do evil</span>',
+ ' <!-- another comment -->',
+ '</uib-tabset>'
+ ].join('\n'))(scope);
+
+ scope.tabIsAvailable = function(tab) {
+ return tab.available;
+ };
+ }));
+
+ it('should preserve correct ordering', function() {
+ function titles() {
+ return elm.find('ul.nav-tabs li a');
+ }
+ scope.$apply();
+ expect(titles().length).toBe(9);
+ scope.$apply('tabs[1].available=false');
+ scope.$digest();
+ expect(titles().length).toBe(7);
+ scope.$apply('tabs[0].available=false');
+ scope.$digest();
+ expect(titles().length).toBe(5);
+ scope.$apply('tabs[2].available=false');
+ scope.$digest();
+ expect(titles().length).toBe(3);
+ scope.$apply('tabs[0].available=true');
+ scope.$digest();
+ expect(titles().length).toBe(5);
+ scope.$apply('tabs[1].available=true');
+ scope.$apply('tabs[2].available=true');
+ scope.$digest();
+ expect(titles().length).toBe(9);
+ expect(titles().eq(0).text().trim()).toBe('first');
+ expect(titles().eq(1).text().trim()).toBe('Title 1');
+ expect(titles().eq(2).text().trim()).toBe('Title 2');
+ expect(titles().eq(3).text().trim()).toBe('Title 3');
+ expect(titles().eq(4).text().trim()).toBe('mid');
+ expect(titles().eq(5).text().trim()).toBe('Second Title 1');
+ expect(titles().eq(6).text().trim()).toBe('Second Title 2');
+ expect(titles().eq(7).text().trim()).toBe('Second Title 3');
+ expect(titles().eq(8).text().trim()).toBe('last');
+ });
+ });
+
+ describe('uib-tabset controller', function() {
+ function mockTab(isActive) {
+ var _isActive;
+ if (isActive || isActive === false) {
+ _isActive = isActive;
+ }
+
+ return {
+ active: _isActive,
+ onSelect : angular.noop,
+ onDeselect : angular.noop
+ };
+ }
+
+ var ctrl;
+ beforeEach(inject(function($controller, $rootScope) {
+ scope = $rootScope;
+ //instantiate the controller stand-alone, without the directive
+ ctrl = $controller('UibTabsetController', {$scope: scope});
+ }));
+
+ describe('select', function() {
+ it('should mark given tab selected', function() {
+ var tab = mockTab();
+
+ ctrl.select(tab);
+ expect(tab.active).toBe(true);
+ });
+
+
+ it('should deselect other tabs', function() {
+ var tab1 = mockTab(), tab2 = mockTab(), tab3 = mockTab();
+
+ ctrl.addTab(tab1);
+ ctrl.addTab(tab2);
+ ctrl.addTab(tab3);
+
+ ctrl.select(tab1);
+ expect(tab1.active).toBe(true);
+ expect(tab2.active).toBe(false);
+ expect(tab3.active).toBe(false);
+
+ ctrl.select(tab2);
+ expect(tab1.active).toBe(false);
+ expect(tab2.active).toBe(true);
+ expect(tab3.active).toBe(false);
+
+ ctrl.select(tab3);
+ expect(tab1.active).toBe(false);
+ expect(tab2.active).toBe(false);
+ expect(tab3.active).toBe(true);
+ });
+ });
+
+
+ describe('addTab', function() {
+ it('should append tab', function() {
+ var tab1 = mockTab(), tab2 = mockTab();
+
+ expect(ctrl.tabs).toEqual([]);
+
+ ctrl.addTab(tab1);
+ expect(ctrl.tabs).toEqual([tab1]);
+
+ ctrl.addTab(tab2);
+ expect(ctrl.tabs).toEqual([tab1, tab2]);
+ });
+
+ it('should select the first one', function() {
+ var tab1 = mockTab(), tab2 = mockTab();
+
+ ctrl.addTab(tab1);
+ expect(tab1.active).toBe(true);
+
+ ctrl.addTab(tab2);
+ expect(tab1.active).toBe(true);
+ });
+
+ it('should not select first active === false tab as selected', function() {
+ var tab = mockTab(false);
+
+ ctrl.addTab(tab);
+ expect(tab.active).toBe(false);
+ });
+
+ it('should select a tab added that\'s already active', function() {
+ var tab1 = mockTab(), tab2 = mockTab(true);
+ ctrl.addTab(tab1);
+ expect(tab1.active).toBe(true);
+
+ ctrl.addTab(tab2);
+ expect(tab1.active).toBe(false);
+ expect(tab2.active).toBe(true);
+ });
+ });
+ });
+
+ describe('remove', function() {
+ it('should remove title tabs when elements are destroyed and change selection', inject(function($controller, $compile, $rootScope) {
+ scope = $rootScope.$new();
+ elm = $compile('<uib-tabset><uib-tab heading="1">Hello</uib-tab><uib-tab ng-repeat="i in list" heading="tab {{i}}">content {{i}}</uib-tab></uib-tabset>')(scope);
+ scope.$apply();
+
+ expectTitles(['1']);
+ expectContents(['Hello']);
+
+ scope.$apply('list = [1,2,3]');
+ expectTitles(['1', 'tab 1', 'tab 2', 'tab 3']);
+ expectContents(['Hello', 'content 1', 'content 2', 'content 3']);
+
+ // Select last tab
+ titles().find('a').eq(3).click();
+ expect(contents().eq(3)).toHaveClass('active');
+ expect(titles().eq(3)).toHaveClass('active');
+
+ // Remove last tab
+ scope.$apply('list = [1,2]');
+ expectTitles(['1', 'tab 1', 'tab 2']);
+ expectContents(['Hello', 'content 1', 'content 2']);
+
+ // "tab 2" is now selected
+ expect(titles().eq(2)).toHaveClass('active');
+ expect(contents().eq(2)).toHaveClass('active');
+
+ // Select 2nd tab ("tab 1")
+ titles().find('a').eq(1).click();
+ expect(titles().eq(1)).toHaveClass('active');
+ expect(contents().eq(1)).toHaveClass('active');
+
+ // Remove 2nd tab
+ scope.$apply('list = [2]');
+ expectTitles(['1', 'tab 2']);
+ expectContents(['Hello', 'content 2']);
+
+ // New 2nd tab is now selected
+ expect(titles().eq(1)).toHaveClass('active');
+ expect(contents().eq(1)).toHaveClass('active');
+ }));
+
+ it('should not select tabs when being destroyed', inject(function($controller, $compile, $rootScope) {
+ var selectList = [],
+ deselectList = [],
+ getTab = function(active) {
+ return {
+ active: active,
+ select : function() {
+ selectList.push('select');
+ },
+ deselect : function() {
+ deselectList.push('deselect');
+ }
+ };
+ };
+
+ scope = $rootScope.$new();
+ scope.tabs = [
+ getTab(true),
+ getTab(false)
+ ];
+ elm = $compile([
+ '<uib-tabset>',
+ ' <uib-tab ng-repeat="t in tabs" active="t.active" select="t.select()" deselect="t.deselect()">',
+ ' <uib-tab-heading><b>heading</b> {{index}}</uib-tab-heading>',
+ ' content {{$index}}',
+ ' </uib-tab>',
+ '</uib-tabset>'
+ ].join('\n'))(scope);
+ scope.$apply();
+
+ // The first tab is selected the during the initial $digest.
+ expect(selectList.length).toEqual(1);
+
+ // Destroy the tabs - we should not trigger selection/deselection any more.
+ scope.$destroy();
+ expect(selectList.length).toEqual(1);
+ expect(deselectList.length).toEqual(0);
+ }));
+ });
+
+ describe('disable', function() {
+ beforeEach(inject(function($compile, $rootScope) {
+ scope = $rootScope.$new();
+
+ function makeTab(disable) {
+ return {
+ active: false,
+ select: jasmine.createSpy(),
+ disable: disable
+ };
+ }
+ scope.tabs = [
+ makeTab(false), makeTab(true), makeTab(false), makeTab(true)
+ ];
+ elm = $compile([
+ '<uib-tabset>',
+ ' <uib-tab ng-repeat="t in tabs" active="t.active" select="t.select()" disable="t.disable">',
+ ' <uib-tab-heading><b>heading</b> {{index}}</uib-tab-heading>',
+ ' content {{$index}}',
+ ' </uib-tab>',
+ '</uib-tabset>'
+ ].join('\n'))(scope);
+ scope.$apply();
+ }));
+
+ function expectTabActive(activeTab) {
+ var _titles = titles();
+ angular.forEach(scope.tabs, function(tab, i) {
+ if (activeTab === tab) {
+ expect(tab.active).toBe(true);
+ expect(tab.select.calls.count()).toBe( (tab.disable) ? 0 : 1 );
+ expect(_titles.eq(i)).toHaveClass('active');
+ expect(contents().eq(i).text().trim()).toBe('content ' + i);
+ expect(contents().eq(i)).toHaveClass('active');
+ } else {
+ expect(tab.active).toBe(false);
+ expect(_titles.eq(i)).not.toHaveClass('active');
+ }
+ });
+ }
+
+ it('should not switch active when clicking on title', function() {
+ titles().eq(2).find('a').click();
+ expectTabActive(scope.tabs[2]);
+
+ titles().eq(3).find('a').click();
+ expectTabActive(scope.tabs[2]);
+ });
+
+ it('should toggle between states', function() {
+ expect(titles().eq(3)).toHaveClass('disabled');
+ scope.$apply('tabs[3].disable = false');
+ expect(titles().eq(3)).not.toHaveClass('disabled');
+
+ expect(titles().eq(2)).not.toHaveClass('disabled');
+ scope.$apply('tabs[2].disable = true');
+ expect(titles().eq(2)).toHaveClass('disabled');
+ });
+ });
+
+ describe('vertical', function() {
+ beforeEach(inject(function($compile, $rootScope) {
+ scope = $rootScope.$new();
+ scope.vertical = true;
+ elm = $compile('<uib-tabset vertical="vertical"></uib-tabset>')(scope);
+ scope.$apply();
+ }));
+
+ it('to stack tabs', function() {
+ expect(elm.find('ul.nav-tabs')).toHaveClass('nav-stacked');
+ });
+ });
+
+ describe('justified', function() {
+ beforeEach(inject(function($compile, $rootScope) {
+ scope = $rootScope.$new();
+ scope.justified = true;
+ elm = $compile('<uib-tabset justified="justified"></uib-tabset>')(scope);
+ scope.$apply();
+ }));
+
+ it('to justify tabs', function() {
+ expect(elm.find('ul.nav-tabs')).toHaveClass('nav-justified');
+ });
+ });
+
+ describe('type', function() {
+ beforeEach(inject(function($compile, $rootScope) {
+ scope = $rootScope.$new();
+ scope.navType = 'pills';
+
+ elm = $compile('<uib-tabset type="{{navType}}"></uib-tabset>')(scope);
+ scope.$apply();
+ }));
+
+ it('to show pills', function() {
+ expect(elm.find('ul')).toHaveClass('nav-pills');
+ expect(elm.find('ul')).not.toHaveClass('nav-tabs');
+ });
+ });
+
+ //https://github.com/angular-ui/bootstrap/issues/524
+ describe('child compilation', function() {
+ var elm;
+ beforeEach(inject(function($compile, $rootScope) {
+ elm = $compile('<uib-tabset><uib-tab><div></div></uib-tab></uib-tabset></div>')($rootScope.$new());
+ $rootScope.$apply();
+ }));
+
+ it('should hookup the tab\'s children to the tab with $compile', function() {
+ var tabChild = $('.tab-pane', elm).children().first();
+ expect(tabChild.inheritedData('$uibTabsetController')).toBeTruthy();
+ });
+ });
+
+ //https://github.com/angular-ui/bootstrap/issues/631
+ describe('ng-options in content', function() {
+ var elm;
+ it('should render correct amount of options', inject(function($compile, $rootScope) {
+ var scope = $rootScope.$new();
+ elm = $compile('<uib-tabset><uib-tab><select ng-model="foo" ng-options="i for i in [1,2,3]"></uib-tab></uib-tabset>')(scope);
+ scope.$apply();
+
+ var select = elm.find('select');
+ scope.$apply();
+ expect(select.children().length).toBe(4);
+ }));
+ });
+
+ //https://github.com/angular-ui/bootstrap/issues/599
+ describe('ng-repeat in content', function() {
+ var elm;
+ it('should render ng-repeat', inject(function($compile, $rootScope) {
+ var scope = $rootScope.$new();
+ scope.tabs = [
+ {title:'a', array:[1,2,3]},
+ {title:'b', array:[2,3,4]},
+ {title:'c', array:[3,4,5]}
+ ];
+ elm = $compile('<div><uib-tabset>' +
+ '<uib-tab ng-repeat="tab in tabs" heading="{{tab.title}}">' +
+ '<uib-tab-heading>{{$index}}</uib-tab-heading>' +
+ '<span ng-repeat="a in tab.array">{{a}},</span>' +
+ '</uib-tab>' +
+ '</uib-tabset></div>')(scope);
+ scope.$apply();
+
+ var contents = elm.find('.tab-pane');
+ expect(contents.eq(0).text().trim()).toEqual('1,2,3,');
+ expect(contents.eq(1).text().trim()).toEqual('2,3,4,');
+ expect(contents.eq(2).text().trim()).toEqual('3,4,5,');
+ }));
+ });
+
+ //https://github.com/angular-ui/bootstrap/issues/783
+ describe('nested tabs', function() {
+ var elm;
+ it('should render without errors', inject(function($compile, $rootScope) {
+ var scope = $rootScope.$new();
+ elm = $compile([
+ '<div>',
+ ' <uib-tabset class="tabbable">',
+ ' <uib-tab heading="Tab 1">',
+ ' <uib-tabset class="tabbable">',
+ ' <uib-tab heading="Tab 1A">',
+ ' </uib-tab>',
+ ' </uib-tabset>',
+ ' </uib-tab>',
+ ' <uib-tab heading="Tab 2">',
+ ' <uib-tabset class="tabbable">',
+ ' <uib-tab heading="Tab 2A">',
+ ' </uib-tab>',
+ ' </uib-tabset>',
+ ' </uib-tab>',
+ ' </uib-tabset>',
+ '</div>'
+ ].join('\n'))(scope);
+ scope.$apply();
+
+ // 1 outside tabset, 2 nested tabsets
+ expect(elm.find('.tabbable').length).toEqual(3);
+ }));
+
+ it('should render with the correct scopes', inject(function($compile, $rootScope) {
+ var scope = $rootScope.$new();
+ scope.tab1Text = 'abc';
+ scope.tab1aText = '123';
+ scope.tab1aHead = '123';
+ scope.tab2aaText = '456';
+ elm = $compile([
+ '<div>',
+ ' <uib-tabset class="tabbable">',
+ ' <uib-tab heading="Tab 1">',
+ ' <uib-tabset class="tabbable">',
+ ' <uib-tab heading="{{ tab1aHead }}">',
+ ' {{ tab1aText }}',
+ ' </uib-tab>',
+ ' </uib-tabset>',
+ ' <span class="tab-1">{{ tab1Text }}</span>',
+ ' </uib-tab>',
+ ' <uib-tab heading="Tab 2">',
+ ' <uib-tabset class="tabbable">',
+ ' <uib-tab heading="Tab 2A">',
+ ' <uib-tabset class="tabbable">',
+ ' <uib-tab heading="Tab 2AA">',
+ ' <span class="tab-2aa">{{ tab2aaText }}</span>',
+ ' </uib-tab>',
+ ' </uib-tabset>',
+ ' </uib-tab>',
+ ' </uib-tabset>',
+ ' </uib-tab>',
+ ' </uib-tabset>',
+ '</div>'
+ ].join('\n'))(scope);
+ scope.$apply();
+
+ var outsideTabset = elm.find('.tabbable').eq(0);
+ var nestedTabset = outsideTabset.find('.tabbable');
+
+ expect(elm.find('.tabbable').length).toEqual(4);
+ expect(outsideTabset.find('.tab-pane').eq(0).find('.tab-1').text().trim()).toEqual(scope.tab1Text);
+ expect(nestedTabset.find('.tab-pane').eq(0).text().trim()).toEqual(scope.tab1aText);
+ expect(nestedTabset.find('ul.nav-tabs li').eq(0).text().trim()).toEqual(scope.tab1aHead);
+ expect(nestedTabset.eq(2).find('.tab-pane').eq(0).find('.tab-2aa').text().trim()).toEqual(scope.tab2aaText);
+ }));
+
+ it('ng-repeat works with nested tabs', inject(function($compile, $rootScope) {
+ var scope = $rootScope.$new();
+ scope.tabs = [
+ {
+ tabs: [
+ {
+ content: 'tab1a'
+ },
+ {
+ content: 'tab2a'
+ }
+ ],
+ content: 'tab1'
+ }
+ ];
+ elm = $compile([
+ '<div>',
+ ' <uib-tabset>',
+ ' <uib-tab ng-repeat="tab in tabs">',
+ ' <uib-tabset>',
+ ' <uib-tab ng-repeat="innerTab in tab.tabs">',
+ ' <span class="inner-tab-content">{{ innerTab.content }}</span>',
+ ' </uib-tab>',
+ ' </uib-tabset>',
+ ' <span class="outer-tab-content">{{ tab.content }}</span>',
+ ' </uib-tab>',
+ ' </uib-tabset>',
+ '</div>'
+ ].join('\n'))(scope);
+ scope.$apply();
+
+ expect(elm.find('.inner-tab-content').eq(0).text().trim()).toEqual(scope.tabs[0].tabs[0].content);
+ expect(elm.find('.inner-tab-content').eq(1).text().trim()).toEqual(scope.tabs[0].tabs[1].content);
+ expect(elm.find('.outer-tab-content').eq(0).text().trim()).toEqual(scope.tabs[0].content);
+ }));
+ });
+});
+
+/* deprecation tests below */
+
+describe('tab deprecation', function() {
+ beforeEach(module('ui.bootstrap.tabs'));
+ beforeEach(module('template/tabs/tabset.html'));
+ beforeEach(module('template/tabs/tab.html'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$tabsSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element =
+ '<tabset>' +
+ '<tab>' +
+ '<tab-heading>Tab Heading One</tab-heading>' +
+ '<div>Tab One Contents</div>' +
+ '</tab>' +
+ '<tab heading="Tab Heading Two">' +
+ '<div>Tab Two Contents</div>' +
+ '</tab>' +
+ '</tabset>';
+ $compile(element)($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($templateCache, $compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var tabSetTemplate =
+ '<div>' +
+ '<ul class="nav nav-{{type || \'tabs\'}}" ng-class="{\'nav-stacked\': vertical, \'nav-justified\': justified}" ng-transclude></ul>' +
+ '<div class="tab-content">' +
+ '<div class="tab-pane" ng-repeat="tab in tabs" ng-class="{active: tab.active}" tab-content-transclude="tab"></div>' +
+ '</div>' +
+ '</div>';
+ $templateCache.put('template/tabs/tabset.html', tabSetTemplate);
+
+ var tabTemplate =
+ '<li ng-class="{active: active, disabled: disabled}">' +
+ '<a href ng-click="select()" tab-heading-transclude>{{heading}}</a>' +
+ '</li>';
+ $templateCache.put('template/tabs/tab.html', tabTemplate);
+
+ var element =
+ '<tabset>' +
+ '<tab>' +
+ '<tab-heading>Tab Heading One</tab-heading>' +
+ '<div>Tab One Contents</div>' +
+ '</tab>' +
+ '</tabset>';
+ $compile(element)($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(5);
+ expect($log.warn.calls.argsFor(0)).toEqual(['TabsetController is now deprecated. Use UibTabsetController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['tab-heading-transclude is now deprecated. Use uib-tab-heading-transclude instead.']);
+ expect($log.warn.calls.argsFor(2)).toEqual(['tab is now deprecated. Use uib-tab instead.']);
+ expect($log.warn.calls.argsFor(3)).toEqual(['tabset is now deprecated. Use uib-tabset instead.']);
+ expect($log.warn.calls.argsFor(4)).toEqual(['tab-content-transclude is now deprecated. Use uib-tab-content-transclude instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/docs/demo.html
new file mode 100644
index 0000000..8bf9e9f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/docs/demo.html
@@ -0,0 +1,24 @@
+<div ng-controller="TimepickerDemoCtrl">
+
+ <uib-timepicker ng-model="mytime" ng-change="changed()" hour-step="hstep" minute-step="mstep" show-meridian="ismeridian"></uib-timepicker>
+
+ <pre class="alert alert-info">Time is: {{mytime | date:'shortTime' }}</pre>
+
+ <div class="row">
+ <div class="col-xs-6">
+ Hours step is:
+ <select class="form-control" ng-model="hstep" ng-options="opt for opt in options.hstep"></select>
+ </div>
+ <div class="col-xs-6">
+ Minutes step is:
+ <select class="form-control" ng-model="mstep" ng-options="opt for opt in options.mstep"></select>
+ </div>
+ </div>
+
+ <hr>
+
+ <button type="button" class="btn btn-info" ng-click="toggleMode()">12H / 24H</button>
+ <button type="button" class="btn btn-default" ng-click="update()">Set to 14:00</button>
+ <button type="button" class="btn btn-danger" ng-click="clear()">Clear</button>
+
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/docs/demo.js
new file mode 100644
index 0000000..8c9ade2
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/docs/demo.js
@@ -0,0 +1,31 @@
+angular.module('ui.bootstrap.demo').controller('TimepickerDemoCtrl', function ($scope, $log) {
+ $scope.mytime = new Date();
+
+ $scope.hstep = 1;
+ $scope.mstep = 15;
+
+ $scope.options = {
+ hstep: [1, 2, 3],
+ mstep: [1, 5, 10, 15, 25, 30]
+ };
+
+ $scope.ismeridian = true;
+ $scope.toggleMode = function() {
+ $scope.ismeridian = ! $scope.ismeridian;
+ };
+
+ $scope.update = function() {
+ var d = new Date();
+ d.setHours( 14 );
+ d.setMinutes( 0 );
+ $scope.mytime = d;
+ };
+
+ $scope.changed = function () {
+ $log.log('Time changed to: ' + $scope.mytime);
+ };
+
+ $scope.clear = function() {
+ $scope.mytime = null;
+ };
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/docs/readme.md
new file mode 100644
index 0000000..4e2a231
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/docs/readme.md
@@ -0,0 +1,56 @@
+A lightweight & configurable timepicker directive.
+
+### Settings ###
+
+All settings can be provided as attributes in the `<uib-timepicker>` or globally configured through the `uibTimepickerConfig`.
+
+ * `ng-model` <i class="glyphicon glyphicon-eye-open"></i>
+ :
+ The Date object that provides the time state.
+
+ * `template-url` (Defaults: `template/timepicker/timepicker.html`) :
+ Add the ability to override the template used on the component.
+
+ * `hour-step` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: 1)_ :
+ Number of hours to increase or decrease when using a button.
+
+ * `minute-step` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: 1)_ :
+ Number of minutes to increase or decrease when using a button.
+
+ * `show-meridian` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: true)_ :
+ Whether to display 12H or 24H mode.
+
+ * `meridians`
+ _(Defaults: null)_ :
+ Meridian labels based on locale. To override you must supply an array like ['AM', 'PM'].
+
+ * `readonly-input`
+ _(Defaults: false)_ :
+ Whether user can type inside the hours & minutes input.
+
+ * `mousewheel`
+ _(Defaults: true)_ :
+ Whether user can scroll inside the hours & minutes input to increase or decrease it's values.
+
+ * `arrowkeys`
+ _(Defaults: true)_ :
+ Whether user can use up/down arrowkeys inside the hours & minutes input to increase or decrease it's values.
+
+ * `show-spinners`
+ _(Defaults: true)_ :
+ Shows spinner arrows above and below the inputs
+
+ * `min`
+ _(Defaults: undefined)_ :
+ Minimum time a user can select
+
+ * `max`
+ _(Defaults: undefined)_ :
+ Maximum time a user can select
+
+ * `tabindex`
+ _(Defaults: 0)_ :
+ Sets tabindex for each control in timepicker
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/test/timepicker.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/test/timepicker.spec.js
new file mode 100644
index 0000000..8e13cea
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/test/timepicker.spec.js
@@ -0,0 +1,1774 @@
+describe('timepicker directive', function() {
+ var $rootScope, $compile, $templateCache, element;
+
+ beforeEach(module('ui.bootstrap.timepicker'));
+ beforeEach(module('template/timepicker/timepicker.html'));
+ beforeEach(inject(function(_$compile_, _$rootScope_, _$templateCache_) {
+ $compile = _$compile_;
+ $rootScope = _$rootScope_;
+ $rootScope.time = newTime(14, 40);
+ $templateCache = _$templateCache_;
+
+ element = $compile('<uib-timepicker ng-model="time"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ function newTime(hours, minutes) {
+ var time = new Date();
+ time.setHours(hours, minutes, 0, 0);
+ return time;
+ }
+
+ function getTimeState(withoutMeridian) {
+ var inputs = element.find('input');
+
+ var state = [];
+ for (var i = 0; i < 2; i ++) {
+ state.push(inputs.eq(i).val());
+ }
+ if (withoutMeridian !== true) {
+ state.push(getMeridianButton().text());
+ }
+ return state;
+ }
+
+ function getModelState() {
+ return [ $rootScope.time.getHours(), $rootScope.time.getMinutes() ];
+ }
+
+ function getArrow(isUp, tdIndex) {
+ return element.find('tr').eq(isUp ? 0 : 2).find('td').eq(tdIndex).find('a').eq(0);
+ }
+
+ function getHoursButton(isUp) {
+ return getArrow(isUp, 0);
+ }
+
+ function getMinutesButton(isUp) {
+ return getArrow(isUp, 2);
+ }
+
+ function getMeridianButton() {
+ return element.find('button').eq(0);
+ }
+
+ function doClick(button, n) {
+ for (var i = 0, max = n || 1; i < max; i++) {
+ button.click();
+ $rootScope.$digest();
+ }
+ }
+
+ function wheelThatMouse(delta) {
+ var e = $.Event('mousewheel');
+ e.wheelDelta = delta;
+ return e;
+ }
+
+ function wheelThatOtherMouse(delta) {
+ var e = $.Event('wheel');
+ e.deltaY = delta;
+ return e;
+ }
+
+ function keydown(key) {
+ var e = $.Event('keydown');
+ switch(key) {
+ case 'left':
+ e.which = 37;
+ break;
+ case 'up':
+ e.which = 38;
+ break;
+ case 'right':
+ e.which = 39;
+ break;
+ case 'down':
+ e.which = 40;
+ break;
+ }
+ return e;
+ }
+
+ it('contains three row & three input elements', function() {
+ expect(element.find('tr').length).toBe(3);
+ expect(element.find('input').length).toBe(2);
+ expect(element.find('button').length).toBe(1);
+ });
+
+ it('has initially the correct time & meridian', function() {
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+ });
+
+ it('should be pristine', function() {
+ expect(element.controller('ngModel').$pristine).toBe(true);
+ });
+
+ it('has `selected` current time when model is initially cleared', function() {
+ $rootScope.time = null;
+ element = $compile('<uib-timepicker ng-model="time"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect($rootScope.time).toBe(null);
+ expect(getTimeState()).not.toEqual(['', '', '']);
+ });
+
+ it('changes inputs when model changes value', function() {
+ $rootScope.time = newTime(11, 50);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['11', '50', 'AM']);
+ expect(getModelState()).toEqual([11, 50]);
+
+ $rootScope.time = newTime(16, 40);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '40', 'PM']);
+ expect(getModelState()).toEqual([16, 40]);
+ });
+
+ it('increases / decreases hours when arrows are clicked', function() {
+ var up = getHoursButton(true);
+ var down = getHoursButton(false);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['03', '40', 'PM']);
+ expect(getModelState()).toEqual([15, 40]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['01', '40', 'PM']);
+ expect(getModelState()).toEqual([13, 40]);
+ });
+
+ it('increase / decreases minutes by default step when arrows are clicked', function() {
+ var up = getMinutesButton(true);
+ var down = getMinutesButton(false);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['02', '41', 'PM']);
+ expect(getModelState()).toEqual([14, 41]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['02', '39', 'PM']);
+ expect(getModelState()).toEqual([14, 39]);
+ });
+
+ it('meridian button has correct type', function() {
+ var button = getMeridianButton();
+ expect(button.attr('type')).toBe('button');
+ });
+
+ it('toggles meridian when button is clicked', function() {
+ var button = getMeridianButton();
+
+ doClick(button);
+ expect(getTimeState()).toEqual(['02', '40', 'AM']);
+ expect(getModelState()).toEqual([2, 40]);
+
+ doClick(button);
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ doClick(button);
+ expect(getTimeState()).toEqual(['02', '40', 'AM']);
+ expect(getModelState()).toEqual([2, 40]);
+ });
+
+ it('has minutes "connected" to hours', function() {
+ var up = getMinutesButton(true);
+ var down = getMinutesButton(false);
+
+ doClick(up, 10);
+ expect(getTimeState()).toEqual(['02', '50', 'PM']);
+ expect(getModelState()).toEqual([14, 50]);
+
+ doClick(up, 10);
+ expect(getTimeState()).toEqual(['03', '00', 'PM']);
+ expect(getModelState()).toEqual([15, 0]);
+
+ doClick(up, 10);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['03', '10', 'PM']);
+ expect(getModelState()).toEqual([15, 10]);
+
+ doClick(down, 10);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['03', '00', 'PM']);
+ expect(getModelState()).toEqual([15, 0]);
+
+ doClick(down, 10);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '50', 'PM']);
+ expect(getModelState()).toEqual([14, 50]);
+ });
+
+ it('has hours "connected" to meridian', function() {
+ var up = getHoursButton(true);
+ var down = getHoursButton(false);
+
+ // AM -> PM
+ $rootScope.time = newTime(11, 0);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['11', '00', 'AM']);
+ expect(getModelState()).toEqual([11, 0]);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['12', '00', 'PM']);
+ expect(getModelState()).toEqual([12, 0]);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['01', '00', 'PM']);
+ expect(getModelState()).toEqual([13, 0]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['12', '00', 'PM']);
+ expect(getModelState()).toEqual([12, 0]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['11', '00', 'AM']);
+ expect(getModelState()).toEqual([11, 0]);
+
+ // PM -> AM
+ $rootScope.time = newTime(23, 0);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['11', '00', 'PM']);
+ expect(getModelState()).toEqual([23, 0]);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['12', '00', 'AM']);
+ expect(getModelState()).toEqual([0, 0]);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['01', '00', 'AM']);
+ expect(getModelState()).toEqual([01, 0]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['12', '00', 'AM']);
+ expect(getModelState()).toEqual([0, 0]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['11', '00', 'PM']);
+ expect(getModelState()).toEqual([23, 0]);
+ });
+
+ it('changes only the time part when hours change', function() {
+ $rootScope.time = newTime(23, 50);
+ $rootScope.$digest();
+
+ var date = $rootScope.time.getDate();
+ var up = getHoursButton(true);
+ doClick(up);
+
+ expect(getTimeState()).toEqual(['12', '50', 'AM']);
+ expect(getModelState()).toEqual([0, 50]);
+ expect(date).toEqual($rootScope.time.getDate());
+ });
+
+ it('changes only the time part when minutes change', function() {
+ element = $compile('<uib-timepicker ng-model="time" minute-step="15"></uib-timepicker>')($rootScope);
+ $rootScope.time = newTime(0, 0);
+ $rootScope.$digest();
+
+ var date = $rootScope.time.getDate();
+ var up = getMinutesButton(true);
+ doClick(up, 2);
+ expect(getTimeState()).toEqual(['12', '30', 'AM']);
+ expect(getModelState()).toEqual([0, 30]);
+ expect(date).toEqual($rootScope.time.getDate());
+
+ var down = getMinutesButton(false);
+ doClick(down, 2);
+ expect(getTimeState()).toEqual(['12', '00', 'AM']);
+ expect(getModelState()).toEqual([0, 0]);
+ expect(date).toEqual($rootScope.time.getDate());
+
+ doClick(down, 2);
+ expect(getTimeState()).toEqual(['11', '30', 'PM']);
+ expect(getModelState()).toEqual([23, 30]);
+ expect(date).toEqual($rootScope.time.getDate());
+ });
+
+ it('responds properly on "mousewheel" events', function() {
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0), minutesEl = inputs.eq(1);
+ var upMouseWheelEvent = wheelThatMouse(1);
+ var downMouseWheelEvent = wheelThatMouse(-1);
+
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ // UP
+ hoursEl.trigger( upMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['03', '40', 'PM']);
+ expect(getModelState()).toEqual([15, 40]);
+
+ hoursEl.trigger( upMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '40', 'PM']);
+ expect(getModelState()).toEqual([16, 40]);
+
+ minutesEl.trigger( upMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '41', 'PM']);
+ expect(getModelState()).toEqual([16, 41]);
+
+ minutesEl.trigger( upMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '42', 'PM']);
+ expect(getModelState()).toEqual([16, 42]);
+
+ // DOWN
+ minutesEl.trigger( downMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '41', 'PM']);
+ expect(getModelState()).toEqual([16, 41]);
+
+ minutesEl.trigger( downMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '40', 'PM']);
+ expect(getModelState()).toEqual([16, 40]);
+
+ hoursEl.trigger( downMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['03', '40', 'PM']);
+ expect(getModelState()).toEqual([15, 40]);
+
+ hoursEl.trigger( downMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+ });
+
+ it('responds properly on "wheel" events', function() {
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0), minutesEl = inputs.eq(1);
+ var upMouseWheelEvent = wheelThatOtherMouse(-1);
+ var downMouseWheelEvent = wheelThatOtherMouse(1);
+
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ // UP
+ hoursEl.trigger( upMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['03', '40', 'PM']);
+ expect(getModelState()).toEqual([15, 40]);
+
+ hoursEl.trigger( upMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '40', 'PM']);
+ expect(getModelState()).toEqual([16, 40]);
+
+ minutesEl.trigger( upMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '41', 'PM']);
+ expect(getModelState()).toEqual([16, 41]);
+
+ minutesEl.trigger( upMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '42', 'PM']);
+ expect(getModelState()).toEqual([16, 42]);
+
+ // DOWN
+ minutesEl.trigger( downMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '41', 'PM']);
+ expect(getModelState()).toEqual([16, 41]);
+
+ minutesEl.trigger( downMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '40', 'PM']);
+ expect(getModelState()).toEqual([16, 40]);
+
+ hoursEl.trigger( downMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['03', '40', 'PM']);
+ expect(getModelState()).toEqual([15, 40]);
+
+ hoursEl.trigger( downMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+ });
+
+ it('responds properly on "keydown" events', function() {
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0), minutesEl = inputs.eq(1);
+ var upKeydownEvent = keydown('up');
+ var downKeydownEvent = keydown('down');
+ var leftKeydownEvent = keydown('left');
+
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ // UP
+ hoursEl.trigger( upKeydownEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['03', '40', 'PM']);
+ expect(getModelState()).toEqual([15, 40]);
+
+ hoursEl.trigger( upKeydownEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '40', 'PM']);
+ expect(getModelState()).toEqual([16, 40]);
+
+ minutesEl.trigger( upKeydownEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '41', 'PM']);
+ expect(getModelState()).toEqual([16, 41]);
+
+ minutesEl.trigger( upKeydownEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '42', 'PM']);
+ expect(getModelState()).toEqual([16, 42]);
+
+ // DOWN
+ minutesEl.trigger( downKeydownEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '41', 'PM']);
+ expect(getModelState()).toEqual([16, 41]);
+
+ minutesEl.trigger( downKeydownEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '40', 'PM']);
+ expect(getModelState()).toEqual([16, 40]);
+
+ hoursEl.trigger( downKeydownEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['03', '40', 'PM']);
+ expect(getModelState()).toEqual([15, 40]);
+
+ hoursEl.trigger( downKeydownEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ // Other keydown
+ hoursEl.trigger( leftKeydownEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ minutesEl.trigger( leftKeydownEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+ });
+
+ describe('attributes', function() {
+ beforeEach(function() {
+ $rootScope.hstep = 2;
+ $rootScope.mstep = 30;
+ $rootScope.time = newTime(14, 0);
+ element = $compile('<uib-timepicker ng-model="time" hour-step="hstep" minute-step="mstep"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ it('increases / decreases hours by configurable step', function() {
+ var up = getHoursButton(true);
+ var down = getHoursButton(false);
+
+ expect(getTimeState()).toEqual(['02', '00', 'PM']);
+ expect(getModelState()).toEqual([14, 0]);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['04', '00', 'PM']);
+ expect(getModelState()).toEqual([16, 0]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['02', '00', 'PM']);
+ expect(getModelState()).toEqual([14, 0]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['12', '00', 'PM']);
+ expect(getModelState()).toEqual([12, 0]);
+
+ // Change step
+ $rootScope.hstep = 3;
+ $rootScope.$digest();
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['03', '00', 'PM']);
+ expect(getModelState()).toEqual([15, 0]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['12', '00', 'PM']);
+ expect(getModelState()).toEqual([12, 0]);
+ });
+
+ it('increases / decreases minutes by configurable step', function() {
+ var up = getMinutesButton(true);
+ var down = getMinutesButton(false);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['02', '30', 'PM']);
+ expect(getModelState()).toEqual([14, 30]);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['03', '00', 'PM']);
+ expect(getModelState()).toEqual([15, 0]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['02', '30', 'PM']);
+ expect(getModelState()).toEqual([14, 30]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['02', '00', 'PM']);
+ expect(getModelState()).toEqual([14, 0]);
+
+ // Change step
+ $rootScope.mstep = 15;
+ $rootScope.$digest();
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['02', '15', 'PM']);
+ expect(getModelState()).toEqual([14, 15]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['02', '00', 'PM']);
+ expect(getModelState()).toEqual([14, 0]);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['01', '45', 'PM']);
+ expect(getModelState()).toEqual([13, 45]);
+ });
+
+ it('responds properly on "mousewheel" events with configurable steps', function() {
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0), minutesEl = inputs.eq(1);
+ var upMouseWheelEvent = wheelThatMouse(1);
+ var downMouseWheelEvent = wheelThatMouse(-1);
+
+ expect(getTimeState()).toEqual(['02', '00', 'PM']);
+ expect(getModelState()).toEqual([14, 0]);
+
+ // UP
+ hoursEl.trigger( upMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '00', 'PM']);
+ expect(getModelState()).toEqual([16, 0]);
+
+ minutesEl.trigger( upMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '30', 'PM']);
+ expect(getModelState()).toEqual([16, 30]);
+
+ // DOWN
+ minutesEl.trigger( downMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '00', 'PM']);
+ expect(getModelState()).toEqual([16, 0]);
+
+ hoursEl.trigger( downMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '00', 'PM']);
+ expect(getModelState()).toEqual([14, 0]);
+ });
+
+ it('responds properly on "wheel" events with configurable steps', function() {
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0), minutesEl = inputs.eq(1);
+ var upMouseWheelEvent = wheelThatOtherMouse(-1);
+ var downMouseWheelEvent = wheelThatOtherMouse(1);
+
+ expect(getTimeState()).toEqual(['02', '00', 'PM']);
+ expect(getModelState()).toEqual([14, 0]);
+
+ // UP
+ hoursEl.trigger( upMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '00', 'PM']);
+ expect(getModelState()).toEqual([16, 0]);
+
+ minutesEl.trigger( upMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '30', 'PM']);
+ expect(getModelState()).toEqual([16, 30]);
+
+ // DOWN
+ minutesEl.trigger( downMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '00', 'PM']);
+ expect(getModelState()).toEqual([16, 0]);
+
+ hoursEl.trigger( downMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '00', 'PM']);
+ expect(getModelState()).toEqual([14, 0]);
+ });
+
+ it('can handle strings as steps', function() {
+ var upHours = getHoursButton(true);
+ var upMinutes = getMinutesButton(true);
+
+ expect(getTimeState()).toEqual(['02', '00', 'PM']);
+ expect(getModelState()).toEqual([14, 0]);
+
+ $rootScope.hstep = '4';
+ $rootScope.mstep = '20';
+ $rootScope.$digest();
+
+ doClick(upHours);
+ expect(getTimeState()).toEqual(['06', '00', 'PM']);
+ expect(getModelState()).toEqual([18, 0]);
+
+ doClick(upMinutes);
+ expect(getTimeState()).toEqual(['06', '20', 'PM']);
+ expect(getModelState()).toEqual([18, 20]);
+ });
+
+ });
+
+ describe('12 / 24 hour mode', function() {
+ beforeEach(function() {
+ $rootScope.meridian = false;
+ $rootScope.time = newTime(14, 10);
+ element = $compile('<uib-timepicker ng-model="time" show-meridian="meridian"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+ });
+
+ function getMeridianTd() {
+ return element.find('tr').eq(1).find('td').eq(3);
+ }
+
+ it('initially displays correct time when `show-meridian` is false', function() {
+ expect(getTimeState(true)).toEqual(['14', '10']);
+ expect(getModelState()).toEqual([14, 10]);
+ expect(getMeridianTd()).toBeHidden();
+ });
+
+ it('toggles correctly between different modes', function() {
+ expect(getTimeState(true)).toEqual(['14', '10']);
+
+ $rootScope.meridian = true;
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '10', 'PM']);
+ expect(getModelState()).toEqual([14, 10]);
+ expect(getMeridianTd()).not.toBeHidden();
+
+ $rootScope.meridian = false;
+ $rootScope.$digest();
+ expect(getTimeState(true)).toEqual(['14', '10']);
+ expect(getModelState()).toEqual([14, 10]);
+ expect(getMeridianTd()).toBeHidden();
+ });
+
+ it('handles correctly initially empty model on parent element', function() {
+ $rootScope.time = null;
+ element = $compile('<span ng-model="time"><uib-timepicker show-meridian="meridian"></uib-timepicker></span>')($rootScope);
+ $rootScope.$digest();
+
+ expect($rootScope.time).toBe(null);
+ });
+ });
+
+ describe('`meridians` attribute', function() {
+ beforeEach(inject(function() {
+ $rootScope.meridiansArray = ['am', 'pm'];
+ element = $compile('<uib-timepicker ng-model="time" meridians="meridiansArray"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('displays correctly', function() {
+ expect(getTimeState()[2]).toBe('pm');
+ });
+
+ it('toggles correctly', function() {
+ $rootScope.time = newTime(2, 40);
+ $rootScope.$digest();
+ expect(getTimeState()[2]).toBe('am');
+ });
+ });
+
+ describe('`readonly-input` attribute', function() {
+ beforeEach(inject(function() {
+ $rootScope.meridiansArray = ['am', 'pm'];
+ element = $compile('<uib-timepicker ng-model="time" readonly-input="true"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('should make inputs readonly', function() {
+ var inputs = element.find('input');
+ expect(inputs.eq(0).attr('readonly')).toBe('readonly');
+ expect(inputs.eq(1).attr('readonly')).toBe('readonly');
+ });
+ });
+
+ describe('setting timepickerConfig steps', function() {
+ var originalConfig = {};
+ beforeEach(inject(function(_$compile_, _$rootScope_, uibTimepickerConfig) {
+ angular.extend(originalConfig, uibTimepickerConfig);
+ uibTimepickerConfig.hourStep = 2;
+ uibTimepickerConfig.minuteStep = 10;
+ uibTimepickerConfig.showMeridian = false;
+ element = $compile('<uib-timepicker ng-model="time"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+ afterEach(inject(function(uibTimepickerConfig) {
+ // return it to the original state
+ angular.extend(uibTimepickerConfig, originalConfig);
+ }));
+
+ it('does not affect the initial value', function() {
+ expect(getTimeState(true)).toEqual(['14', '40']);
+ expect(getModelState()).toEqual([14, 40]);
+ });
+
+ it('increases / decreases hours with configured step', function() {
+ var up = getHoursButton(true);
+ var down = getHoursButton(false);
+
+ doClick(up, 2);
+ expect(getTimeState(true)).toEqual(['18', '40']);
+ expect(getModelState()).toEqual([18, 40]);
+
+ doClick(down, 3);
+ expect(getTimeState(true)).toEqual(['12', '40']);
+ expect(getModelState()).toEqual([12, 40]);
+ });
+
+ it('increases / decreases minutes with configured step', function() {
+ var up = getMinutesButton(true);
+ var down = getMinutesButton(false);
+
+ doClick(up);
+ expect(getTimeState(true)).toEqual(['14', '50']);
+ expect(getModelState()).toEqual([14, 50]);
+
+ doClick(down, 3);
+ expect(getTimeState(true)).toEqual(['14', '20']);
+ expect(getModelState()).toEqual([14, 20]);
+ });
+ });
+
+ describe('setting timepickerConfig meridian labels', function() {
+ var originalConfig = {};
+ beforeEach(inject(function(_$compile_, _$rootScope_, uibTimepickerConfig) {
+ angular.extend(originalConfig, uibTimepickerConfig);
+ uibTimepickerConfig.meridians = ['π.μ.', 'μ.μ.'];
+ uibTimepickerConfig.showMeridian = true;
+ element = $compile('<uib-timepicker ng-model="time"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+ afterEach(inject(function(uibTimepickerConfig) {
+ // return it to the original state
+ angular.extend(uibTimepickerConfig, originalConfig);
+ }));
+
+ it('displays correctly', function() {
+ expect(getTimeState()).toEqual(['02', '40', 'μ.μ.']);
+ expect(getModelState()).toEqual([14, 40]);
+ });
+
+ it('toggles correctly', function() {
+ $rootScope.time = newTime(2, 40);
+ $rootScope.$digest();
+
+ expect(getTimeState()).toEqual(['02', '40', 'π.μ.']);
+ expect(getModelState()).toEqual([2, 40]);
+ });
+ });
+
+ describe('$formatter', function() {
+ var ngModel,
+ date;
+
+ beforeEach(function() {
+ ngModel = element.controller('ngModel');
+ date = new Date('Mon Mar 23 2015 14:40:11 GMT-0700 (PDT)');
+ });
+
+ it('should have one formatter', function() {
+ expect(ngModel.$formatters.length).toBe(1);
+ });
+
+ it('should convert a date to a new reference representing the same date', function() {
+ expect(ngModel.$formatters[0](date)).toEqual(date);
+ });
+
+ it('should convert a valid date string to a date object', function() {
+ expect(ngModel.$formatters[0]('Mon Mar 23 2015 14:40:11 GMT-0700 (PDT)')).toEqual(date);
+ });
+
+ it('should set falsy values as null', function() {
+ expect(ngModel.$formatters[0](undefined)).toBe(null);
+ expect(ngModel.$formatters[0](null)).toBe(null);
+ expect(ngModel.$formatters[0]('')).toBe(null);
+ expect(ngModel.$formatters[0](0)).toBe(null);
+ expect(ngModel.$formatters[0](NaN)).toBe(null);
+ });
+ });
+
+ describe('user input validation', function() {
+ var changeInputValueTo;
+
+ beforeEach(inject(function($sniffer) {
+ changeInputValueTo = function(inputEl, value) {
+ inputEl.val(value);
+ inputEl.trigger($sniffer.hasEvent('input') ? 'input' : 'change');
+ $rootScope.$digest();
+ };
+ }));
+
+ function getHoursInputEl() {
+ return element.find('input').eq(0);
+ }
+
+ function getMinutesInputEl() {
+ return element.find('input').eq(1);
+ }
+
+ it('has initially the correct time & meridian', function() {
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+ });
+
+ it('updates hours & pads on input change & pads on blur', function() {
+ var el = getHoursInputEl();
+
+ changeInputValueTo(el, 5);
+ expect(getTimeState()).toEqual(['5', '40', 'PM']);
+ expect(getModelState()).toEqual([17, 40]);
+
+ el.blur();
+ expect(getTimeState()).toEqual(['05', '40', 'PM']);
+ expect(getModelState()).toEqual([17, 40]);
+ });
+
+ it('updates minutes & pads on input change & pads on blur', function() {
+ var el = getMinutesInputEl();
+
+ changeInputValueTo(el, 9);
+ expect(getTimeState()).toEqual(['02', '9', 'PM']);
+ expect(getModelState()).toEqual([14, 9]);
+
+ el.blur();
+ expect(getTimeState()).toEqual(['02', '09', 'PM']);
+ expect(getModelState()).toEqual([14, 9]);
+ });
+
+ it('clears model when input hours is invalid & alerts the UI', function() {
+ var el = getHoursInputEl();
+
+ changeInputValueTo(el, 'pizza');
+ expect($rootScope.time).toBe(null);
+ expect(el.parent().hasClass('has-error')).toBe(true);
+ expect(element.hasClass('ng-invalid-time')).toBe(true);
+
+ changeInputValueTo(el, 8);
+ el.blur();
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['08', '40', 'PM']);
+ expect(getModelState()).toEqual([20, 40]);
+ expect(el.parent().hasClass('has-error')).toBe(false);
+ expect(element.hasClass('ng-invalid-time')).toBe(false);
+ });
+
+ it('clears model when input minutes is invalid & alerts the UI', function() {
+ var el = getMinutesInputEl();
+
+ changeInputValueTo(el, 'pizza');
+ expect($rootScope.time).toBe(null);
+ expect(el.parent().hasClass('has-error')).toBe(true);
+ expect(element.hasClass('ng-invalid-time')).toBe(true);
+
+ changeInputValueTo(el, 22);
+ expect(getTimeState()).toEqual(['02', '22', 'PM']);
+ expect(getModelState()).toEqual([14, 22]);
+ expect(el.parent().hasClass('has-error')).toBe(false);
+ expect(element.hasClass('ng-invalid-time')).toBe(false);
+ });
+
+ it('leaves view alone when hours are invalid and minutes are updated', function() {
+ var hoursEl = getHoursInputEl(),
+ minutesEl = getMinutesInputEl();
+
+ changeInputValueTo(hoursEl, '25');
+ hoursEl.blur();
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['25', '40', 'PM']);
+
+ changeInputValueTo(minutesEl, '2');
+ minutesEl.blur();
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['25', '2', 'PM']);
+ });
+
+ it('leaves view alone when minutes are invalid and hours are updated', function() {
+ var hoursEl = getHoursInputEl(),
+ minutesEl = getMinutesInputEl();
+
+ changeInputValueTo(minutesEl, '61');
+ minutesEl.blur();
+ $rootScope.$digest();
+ expect($rootScope.time).toBe(null);
+ expect(getTimeState()).toEqual(['02', '61', 'PM']);
+
+ changeInputValueTo(hoursEl, '2');
+ hoursEl.blur();
+ $rootScope.$digest();
+ expect($rootScope.time).toBe(null);
+ expect(getTimeState()).toEqual(['2', '61', 'PM']);
+ });
+
+ it('handles 12/24H mode change', function() {
+ $rootScope.meridian = true;
+ element = $compile('<uib-timepicker ng-model="time" show-meridian="meridian"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+
+ var el = getHoursInputEl();
+
+ changeInputValueTo(el, '16');
+ expect($rootScope.time).toBe(null);
+ expect(el.parent().hasClass('has-error')).toBe(true);
+ expect(element.hasClass('ng-invalid-time')).toBe(true);
+
+ $rootScope.meridian = false;
+ $rootScope.$digest();
+ expect(getTimeState(true)).toEqual(['16', '40']);
+ expect(getModelState()).toEqual([16, 40]);
+ expect(element.hasClass('ng-invalid-time')).toBe(false);
+ });
+
+ it('should have a default tabindex of 0', function() {
+ element = $compile('<uib-timepicker ng-model="time"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect(element.isolateScope().tabindex).toBe(0);
+ });
+
+ it('should have the correct tabindex', function() {
+ element = $compile('<uib-timepicker ng-model="time" tabindex="5"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+
+ expect(element.attr('tabindex')).toBe(undefined);
+ expect(element.isolateScope().tabindex).toBe('5');
+ });
+ });
+
+ describe('when model is not a Date', function() {
+ beforeEach(inject(function() {
+ element = $compile('<uib-timepicker ng-model="time"></uib-timepicker>')($rootScope);
+ }));
+
+ it('should not be invalid when the model is null', function() {
+ $rootScope.time = null;
+ $rootScope.$digest();
+ expect(element.hasClass('ng-invalid-time')).toBe(false);
+ });
+
+ it('should not be invalid when the model is undefined', function() {
+ $rootScope.time = undefined;
+ $rootScope.$digest();
+ expect(element.hasClass('ng-invalid-time')).toBe(false);
+ });
+
+ it('should not be invalid when the model is a valid string date representation', function() {
+ $rootScope.time = 'September 30, 2010 15:30:00';
+ $rootScope.$digest();
+ expect(element.hasClass('ng-invalid-time')).toBe(false);
+ expect(getTimeState()).toEqual(['03', '30', 'PM']);
+ });
+
+ it('should be invalid when the model is not a valid string date representation', function() {
+ $rootScope.time = 'pizza';
+ $rootScope.$digest();
+ expect(element.hasClass('ng-invalid-time')).toBe(true);
+ });
+
+ it('should return valid when the model becomes valid', function() {
+ $rootScope.time = 'pizza';
+ $rootScope.$digest();
+ expect(element.hasClass('ng-invalid-time')).toBe(true);
+
+ $rootScope.time = new Date();
+ $rootScope.$digest();
+ expect(element.hasClass('ng-invalid-time')).toBe(false);
+ });
+
+ it('should return valid when the model is cleared', function() {
+ $rootScope.time = 'pizza';
+ $rootScope.$digest();
+ expect(element.hasClass('ng-invalid-time')).toBe(true);
+
+ $rootScope.time = null;
+ $rootScope.$digest();
+ expect(element.hasClass('ng-invalid-time')).toBe(false);
+ });
+ });
+
+ describe('use with `ng-required` directive', function() {
+ beforeEach(inject(function() {
+ $rootScope.time = null;
+ element = $compile('<uib-timepicker ng-model="time" ng-required="true"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('should be invalid initially', function() {
+ expect(element.hasClass('ng-invalid')).toBe(true);
+ });
+
+ it('should be valid if model has been specified', function() {
+ $rootScope.time = new Date();
+ $rootScope.$digest();
+ expect(element.hasClass('ng-invalid')).toBe(false);
+ });
+ });
+
+ describe('use with `ng-change` directive', function() {
+ beforeEach(inject(function() {
+ $rootScope.changeHandler = jasmine.createSpy('changeHandler');
+ $rootScope.time = new Date();
+ element = $compile('<uib-timepicker ng-model="time" ng-change="changeHandler()"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+ }));
+
+ it('should not be called initially', function() {
+ expect($rootScope.changeHandler).not.toHaveBeenCalled();
+ });
+
+ it('should be called when hours / minutes buttons clicked', function() {
+ var btn1 = getHoursButton(true);
+ var btn2 = getMinutesButton(false);
+
+ doClick(btn1, 2);
+ doClick(btn2, 3);
+ $rootScope.$digest();
+ expect($rootScope.changeHandler.calls.count()).toBe(5);
+ });
+
+ it('should not be called when model changes programatically', function() {
+ $rootScope.time = new Date();
+ $rootScope.$digest();
+ expect($rootScope.changeHandler).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('when used with min', function() {
+ var changeInputValueTo;
+ beforeEach(inject(function($sniffer) {
+ element = $compile('<uib-timepicker ng-model="time" min="min"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+ changeInputValueTo = function(inputEl, value) {
+ inputEl.val(value);
+ inputEl.trigger($sniffer.hasEvent('input') ? 'input' : 'change');
+ $rootScope.$digest();
+ };
+ }));
+
+ it('should not decrease hours when it would result in a time earlier than min', function() {
+ var down = getHoursButton(false);
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0);
+ var downMouseWheelEvent = wheelThatMouse(-1);
+ var downKeydownEvent = keydown('down');
+
+ $rootScope.min = newTime(13, 41);
+ $rootScope.$digest();
+
+ expect(down.hasClass('disabled')).toBe(true);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ hoursEl.trigger( downMouseWheelEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ hoursEl.trigger( downKeydownEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+ });
+
+ it('should decrease hours when it would not result in a time earlier than min', function() {
+ var down = getHoursButton(false);
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0);
+ var downMouseWheelEvent = wheelThatMouse(-1);
+ var downKeydownEvent = keydown('down');
+
+ $rootScope.min = newTime(0, 0);
+ $rootScope.$digest();
+
+ expect(down.hasClass('disabled')).toBe(false);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['01', '40', 'PM']);
+ expect(getModelState()).toEqual([13, 40]);
+
+ hoursEl.trigger(downMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['12', '40', 'PM']);
+ expect(getModelState()).toEqual([12, 40]);
+
+ hoursEl.trigger(downKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['11', '40', 'AM']);
+ expect(getModelState()).toEqual([11, 40]);
+ });
+
+ it('should not decrease minutes when it would result in a time ealier than min', function() {
+ var down = getMinutesButton(false);
+ var inputs = element.find('input');
+ var minutesEl = inputs.eq(1);
+ var downMouseWheelEvent = wheelThatMouse(-1);
+ var downKeydownEvent = keydown('down');
+
+ $rootScope.min = newTime(14, 40);
+ $rootScope.$digest();
+
+ expect(down.hasClass('disabled')).toBe(true);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ minutesEl.trigger(downMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ minutesEl.trigger(downKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+ });
+
+ it('should decrease minutes when it would not result in a time ealier than min', function() {
+ var down = getMinutesButton(false);
+ var inputs = element.find('input');
+ var minutesEl = inputs.eq(1);
+ var downMouseWheelEvent = wheelThatMouse(-1);
+ var downKeydownEvent = keydown('down');
+
+ $rootScope.min = newTime(0, 0);
+ $rootScope.$digest();
+
+ expect(down.hasClass('disabled')).toBe(false);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['02', '39', 'PM']);
+ expect(getModelState()).toEqual([14, 39]);
+
+ minutesEl.trigger(downMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '38', 'PM']);
+ expect(getModelState()).toEqual([14, 38]);
+
+ minutesEl.trigger(downKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '37', 'PM']);
+ expect(getModelState()).toEqual([14, 37]);
+ });
+
+ it('should not increase hours when time would rollover to a time earlier than min', function() {
+ var up = getHoursButton(true);
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0);
+ var upMouseWheelEvent = wheelThatMouse(1);
+ var upKeydownEvent = keydown('up');
+
+ $rootScope.time = newTime(23, 59);
+ $rootScope.min = newTime(13, 40);
+ $rootScope.$digest();
+
+ expect(up.hasClass('disabled')).toBe(true);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['11', '59', 'PM']);
+ expect(getModelState()).toEqual([23, 59]);
+
+ hoursEl.trigger(upMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['11', '59', 'PM']);
+ expect(getModelState()).toEqual([23, 59]);
+
+ hoursEl.trigger(upKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['11', '59', 'PM']);
+ expect(getModelState()).toEqual([23, 59]);
+ });
+
+ it('should increase hours when time would rollover to a time not earlier than min', function() {
+ var up = getHoursButton(true);
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0);
+ var upMouseWheelEvent = wheelThatMouse(1);
+ var upKeydownEvent = keydown('up');
+
+ $rootScope.min = newTime(0, 0);
+
+ $rootScope.time = newTime(23, 59);
+ $rootScope.$digest();
+
+ expect(up.hasClass('disabled')).toBe(false);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['12', '59', 'AM']);
+ expect(getModelState()).toEqual([0, 59]);
+
+ $rootScope.time = newTime(23, 59);
+ $rootScope.$digest();
+
+ hoursEl.trigger(upMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['12', '59', 'AM']);
+ expect(getModelState()).toEqual([0, 59]);
+
+ $rootScope.time = newTime(23, 59);
+ $rootScope.$digest();
+
+ hoursEl.trigger(upKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['12', '59', 'AM']);
+ expect(getModelState()).toEqual([0, 59]);
+ });
+
+
+ it('should not increase minutes when time would rollover to a time earlier than min', function() {
+ var up = getMinutesButton(true);
+ var inputs = element.find('input');
+ var minutesEl = inputs.eq(1);
+ var upMouseWheelEvent = wheelThatMouse(1);
+ var upKeydownEvent = keydown('up');
+
+ $rootScope.time = newTime(23, 59);
+ $rootScope.min = newTime(13, 40);
+ $rootScope.$digest();
+
+ expect(up.hasClass('disabled')).toBe(true);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['11', '59', 'PM']);
+ expect(getModelState()).toEqual([23, 59]);
+
+ minutesEl.trigger(upMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['11', '59', 'PM']);
+ expect(getModelState()).toEqual([23, 59]);
+
+ minutesEl.trigger(upKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['11', '59', 'PM']);
+ expect(getModelState()).toEqual([23, 59]);
+ });
+
+ it('should increase minutes when time would rollover to a time not earlier than min', function() {
+ var up = getMinutesButton(true);
+ var inputs = element.find('input');
+ var minutesEl = inputs.eq(1);
+ var upMouseWheelEvent = wheelThatMouse(1);
+ var upKeydownEvent = keydown('up');
+
+ $rootScope.min = newTime(0, 0);
+
+ $rootScope.time = newTime(23, 59);
+ $rootScope.$digest();
+
+ expect(up.hasClass('disabled')).toBe(false);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['12', '00', 'AM']);
+ expect(getModelState()).toEqual([0, 0]);
+
+ $rootScope.time = newTime(23, 59);
+ $rootScope.$digest();
+
+ minutesEl.trigger(upMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['12', '00', 'AM']);
+ expect(getModelState()).toEqual([0, 0]);
+
+ $rootScope.time = newTime(23, 59);
+ $rootScope.$digest();
+
+ minutesEl.trigger(upKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['12', '00', 'AM']);
+ expect(getModelState()).toEqual([0, 0]);
+ });
+
+ it('should not change meridian when it would result a in time earlier than min', function() {
+ var button = getMeridianButton();
+
+ $rootScope.min = newTime(2, 41);
+ $rootScope.$digest();
+
+ expect(button.hasClass('disabled')).toBe(true);
+
+ doClick(button);
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+ });
+
+ it('should change meridian when it would not result in a time earlier than min', function() {
+ var button = getMeridianButton();
+
+ $rootScope.min = newTime(2, 39);
+ $rootScope.$digest();
+
+ expect(button.hasClass('disabled')).toBe(false);
+
+ doClick(button);
+ expect(getTimeState()).toEqual(['02', '40', 'AM']);
+ expect(getModelState()).toEqual([2, 40]);
+ });
+
+ it('should return invalid when the hours are changes such that the time is earlier than min', function() {
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0);
+
+ $rootScope.min = newTime(14, 0);
+ $rootScope.$digest();
+
+ changeInputValueTo(hoursEl, 1);
+ expect($rootScope.time).toBe(null);
+ expect(hoursEl.parent().hasClass('has-error')).toBe(true);
+ expect(element.hasClass('ng-invalid-time')).toBe(true);
+ });
+
+ it('should return valid when the hours are changes such that the time is not earlier than min', function() {
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0);
+
+ $rootScope.min = newTime(14, 41);
+ $rootScope.$digest();
+
+ changeInputValueTo(hoursEl, 3);
+ expect(getTimeState()).toEqual(['3', '40', 'PM']);
+ expect(getModelState()).toEqual([15, 40]);
+ expect(hoursEl.parent().hasClass('has-error')).toBe(false);
+ expect(element.hasClass('ng-invalid-time')).toBe(false);
+ });
+
+ it('should return invalid when the minutes are changes such that the time is earlier than min', function() {
+ var inputs = element.find('input');
+ var minutesEl = inputs.eq(1);
+
+ $rootScope.min = newTime(14, 30);
+ $rootScope.$digest();
+
+ changeInputValueTo(minutesEl, 1);
+ expect($rootScope.time).toBe(null);
+ expect(minutesEl.parent().hasClass('has-error')).toBe(true);
+ expect(element.hasClass('ng-invalid-time')).toBe(true);
+ });
+
+ it('should return valid when the minutes are changes such that the time is not earlier than min', function() {
+ var inputs = element.find('input');
+ var minutesEl = inputs.eq(1);
+
+ $rootScope.min = newTime(14, 41);
+ $rootScope.$digest();
+
+ changeInputValueTo(minutesEl, 42);
+ expect(getTimeState()).toEqual(['02', '42', 'PM']);
+ expect(getModelState()).toEqual([14, 42]);
+ expect(minutesEl.parent().hasClass('has-error')).toBe(false);
+ expect(element.hasClass('ng-invalid-time')).toBe(false);
+ });
+ });
+
+ describe('when used with max', function() {
+ var changeInputValueTo;
+ beforeEach(inject(function($sniffer) {
+ element = $compile('<timepicker ng-model="time" max="max"></timepicker>')($rootScope);
+ $rootScope.$digest();
+ changeInputValueTo = function (inputEl, value) {
+ inputEl.val(value);
+ inputEl.trigger($sniffer.hasEvent('input') ? 'input' : 'change');
+ $rootScope.$digest();
+ };
+ }));
+
+ it('should not increase hours when it would result in a time later than max', function() {
+ var up = getHoursButton(true);
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0);
+ var upMouseWheelEvent = wheelThatMouse(1);
+ var upKeydownEvent = keydown('up');
+
+ $rootScope.max = newTime(15, 39);
+ $rootScope.$digest();
+
+ expect(up.hasClass('disabled')).toBe(true);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ hoursEl.trigger(upMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ hoursEl.trigger(upKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+ });
+
+ it('should increase hours when it would not result in a time later than max', function() {
+ var up = getHoursButton(true);
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0);
+ var upMouseWheelEvent = wheelThatMouse(1);
+ var upKeydownEvent = keydown('up');
+
+ $rootScope.max = newTime(23, 59);
+ $rootScope.$digest();
+
+ expect(up.hasClass('disabled')).toBe(false);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['03', '40', 'PM']);
+ expect(getModelState()).toEqual([15, 40]);
+
+ hoursEl.trigger(upMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['04', '40', 'PM']);
+ expect(getModelState()).toEqual([16, 40]);
+
+ hoursEl.trigger(upKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['05', '40', 'PM']);
+ expect(getModelState()).toEqual([17, 40]);
+ });
+
+ it('should not increase minutes when it would result in a time later than max', function() {
+ var up = getMinutesButton(true);
+ var inputs = element.find('input');
+ var minutesEl = inputs.eq(1);
+ var upMouseWheelEvent = wheelThatMouse(1);
+ var upKeydownEvent = keydown('up');
+
+ $rootScope.max = newTime(14, 40);
+ $rootScope.$digest();
+
+ expect(up.hasClass('disabled')).toBe(true);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ minutesEl.trigger(upMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+
+ minutesEl.trigger(upKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+ });
+
+ it('should increase minutes when it would not result in a time later than max', function() {
+ var up = getMinutesButton(true);
+ var inputs = element.find('input');
+ var minutesEl = inputs.eq(1);
+ var upMouseWheelEvent = wheelThatMouse(1);
+ var upKeydownEvent = keydown('up');
+
+ $rootScope.max = newTime(23, 59);
+ $rootScope.$digest();
+
+ expect(up.hasClass('disabled')).toBe(false);
+
+ doClick(up);
+ expect(getTimeState()).toEqual(['02', '41', 'PM']);
+ expect(getModelState()).toEqual([14, 41]);
+
+ minutesEl.trigger(upMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '42', 'PM']);
+ expect(getModelState()).toEqual([14, 42]);
+
+ minutesEl.trigger(upKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['02', '43', 'PM']);
+ expect(getModelState()).toEqual([14, 43]);
+ });
+
+ it('should not decrease hours when time would rollover to a time later than max', function() {
+ var down = getHoursButton(false);
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0);
+ var downMouseWheelEvent = wheelThatMouse(-1);
+ var downKeydownEvent = keydown('down');
+
+ $rootScope.time = newTime(0, 0);
+ $rootScope.max = newTime(13, 40);
+ $rootScope.$digest();
+
+ expect(down.hasClass('disabled')).toBe(true);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['12', '00', 'AM']);
+ expect(getModelState()).toEqual([0, 0]);
+
+ hoursEl.trigger(downMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['12', '00', 'AM']);
+ expect(getModelState()).toEqual([0, 0]);
+
+ hoursEl.trigger(downKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['12', '00', 'AM']);
+ expect(getModelState()).toEqual([0, 0]);
+ });
+
+ it('should decrease hours when time would rollover to a time not later than max', function() {
+ var down = getHoursButton(false);
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0);
+ var downMouseWheelEvent = wheelThatMouse(-1);
+ var downKeydownEvent = keydown('down');
+
+ $rootScope.max = newTime(23, 59);
+
+ $rootScope.time = newTime(0, 0);
+ $rootScope.$digest();
+
+ expect(down.hasClass('disabled')).toBe(false);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['11', '00', 'PM']);
+ expect(getModelState()).toEqual([23, 0]);
+
+ $rootScope.time = newTime(0, 0);
+ $rootScope.$digest();
+
+ hoursEl.trigger(downMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['11', '00', 'PM']);
+ expect(getModelState()).toEqual([23, 0]);
+
+ $rootScope.time = newTime(0, 0);
+ $rootScope.$digest();
+
+ hoursEl.trigger(downKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['11', '00', 'PM']);
+ expect(getModelState()).toEqual([23, 0]);
+ });
+
+ it('should not decrease minutes when time would rollover to a time later than max', function() {
+ var down = getMinutesButton(false);
+ var inputs = element.find('input');
+ var minutesEl = inputs.eq(1);
+ var downMouseWheelEvent = wheelThatMouse(-1);
+ var downKeydownEvent = keydown('down');
+
+ $rootScope.time = newTime(0, 0);
+ $rootScope.max = newTime(13, 40);
+ $rootScope.$digest();
+
+ expect(down.hasClass('disabled')).toBe(true);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['12', '00', 'AM']);
+ expect(getModelState()).toEqual([0, 0]);
+
+ minutesEl.trigger(downMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['12', '00', 'AM']);
+ expect(getModelState()).toEqual([0, 0]);
+
+ minutesEl.trigger(downKeydownEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['12', '00', 'AM']);
+ expect(getModelState()).toEqual([0, 0]);
+ });
+
+ it('should decrease minutes when time would rollover to a time not later than max', function() {
+ var down = getMinutesButton(false);
+ var inputs = element.find('input');
+ var minutesEl = inputs.eq(1);
+ var downMouseWheelEvent = wheelThatMouse(-1);
+ var downKeydownEvent = keydown('down');
+
+ $rootScope.max = newTime(23, 59);
+
+ $rootScope.time = newTime(0, 0);
+ $rootScope.$digest();
+
+ expect(down.hasClass('disabled')).toBe(false);
+
+ doClick(down);
+ expect(getTimeState()).toEqual(['11', '59', 'PM']);
+ expect(getModelState()).toEqual([23, 59]);
+
+ $rootScope.time = newTime(0, 0);
+ $rootScope.$digest();
+
+ minutesEl.trigger(downMouseWheelEvent);
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['11', '59', 'PM']);
+ expect(getModelState()).toEqual([23, 59]);
+
+ $rootScope.time = newTime(0, 0);
+ $rootScope.$digest();
+
+ minutesEl.trigger( downKeydownEvent );
+ $rootScope.$digest();
+ expect(getTimeState()).toEqual(['11', '59', 'PM']);
+ expect(getModelState()).toEqual([23, 59]);
+ });
+
+ it('should not change meridian when it would result a in time later than max', function() {
+ var button = getMeridianButton();
+
+ $rootScope.time = newTime(2, 40);
+ $rootScope.max = newTime(14, 39);
+ $rootScope.$digest();
+
+ expect(button.hasClass('disabled')).toBe(true);
+
+ doClick(button);
+ expect(getTimeState()).toEqual(['02', '40', 'AM']);
+ expect(getModelState()).toEqual([2, 40]);
+ });
+
+ it('should change meridian when it would not result in a time later than max', function() {
+ var button = getMeridianButton();
+
+ $rootScope.time = newTime(2, 40);
+ $rootScope.max = newTime(14, 41);
+ $rootScope.$digest();
+
+ expect(button.hasClass('disabled')).toBe(false);
+
+ doClick(button);
+ expect(getTimeState()).toEqual(['02', '40', 'PM']);
+ expect(getModelState()).toEqual([14, 40]);
+ });
+
+ it('should return invalid when the hours are changes such that the time is later than max', function() {
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0);
+
+ $rootScope.max = newTime(14, 0);
+ $rootScope.$digest();
+
+ changeInputValueTo(hoursEl, 3);
+ expect($rootScope.time).toBe(null);
+ expect(hoursEl.parent().hasClass('has-error')).toBe(true);
+ expect(element.hasClass('ng-invalid-time')).toBe(true);
+ });
+
+ it('should return valid when the hours are changes such that the time is not later than max', function() {
+ var inputs = element.find('input');
+ var hoursEl = inputs.eq(0);
+
+ $rootScope.max = newTime(15, 41);
+ $rootScope.$digest();
+
+ changeInputValueTo(hoursEl, 3);
+ expect(getTimeState()).toEqual(['3', '40', 'PM']);
+ expect(getModelState()).toEqual([15, 40]);
+ expect(hoursEl.parent().hasClass('has-error')).toBe(false);
+ expect(element.hasClass('ng-invalid-time')).toBe(false);
+ });
+
+ it('should return invalid when the minutes are changes such that the time is later than max', function() {
+ var inputs = element.find('input');
+ var minutesEl = inputs.eq(1);
+
+ $rootScope.max = newTime(14, 50);
+ $rootScope.$digest();
+
+ changeInputValueTo(minutesEl, 51);
+ expect($rootScope.time).toBe(null);
+ expect(minutesEl.parent().hasClass('has-error')).toBe(true);
+ expect(element.hasClass('ng-invalid-time')).toBe(true);
+ });
+
+ it('should return valid when the minutes are changes such that the time is not later than max', function() {
+ var inputs = element.find('input');
+ var minutesEl = inputs.eq(1);
+
+ $rootScope.max = newTime(14, 42);
+ $rootScope.$digest();
+
+ changeInputValueTo(minutesEl, 41);
+ expect(getTimeState()).toEqual(['02', '41', 'PM']);
+ expect(getModelState()).toEqual([14, 41]);
+ expect(minutesEl.parent().hasClass('has-error')).toBe(false);
+ expect(element.hasClass('ng-invalid-time')).toBe(false);
+ });
+ });
+
+ describe('custom template and controllerAs', function() {
+ it('should allow custom templates', function() {
+ $templateCache.put('foo/bar.html', '<div>baz</div>');
+
+ element = $compile('<uib-timepicker ng-model="time" template-url="foo/bar.html"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+ expect(element[0].tagName.toLowerCase()).toBe('div');
+ expect(element.html()).toBe('baz');
+ });
+
+ it('should expose the controller on the view', function() {
+ $templateCache.put('template/timepicker/timepicker.html', '<div><div>{{timepicker.text}}</div></div>');
+
+ element = $compile('<uib-timepicker ng-model="time"></uib-timepicker>')($rootScope);
+ $rootScope.$digest();
+
+ var ctrl = element.controller('uibTimepicker');
+ expect(ctrl).toBeDefined();
+
+ ctrl.text = 'foo';
+ $rootScope.$digest();
+
+ expect(element.html()).toBe('<div class="ng-binding">foo</div>');
+ });
+ });
+});
+
+/* Deprecation tests below */
+
+describe('timepicker deprecation', function() {
+ beforeEach(module('ui.bootstrap.timepicker'));
+ beforeEach(module('ngAnimateMock'));
+ beforeEach(module('template/timepicker/timepicker.html'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$timepickerSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ $rootScope.time = new Date().setHours(14, 40, 0, 0);
+ var element = '<timepicker ng-model="time"></timepicker>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ $rootScope.time = new Date().setHours(14, 40, 0, 0);
+ var element = '<timepicker ng-model="time"></timepicker>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(2);
+ expect($log.warn.calls.argsFor(0)).toEqual(['TimepickerController is now deprecated. Use UibTimepickerController instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['timepicker is now deprecated. Use uib-timepicker instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/timepicker.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/timepicker.js
new file mode 100644
index 0000000..0c5173e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/timepicker/timepicker.js
@@ -0,0 +1,426 @@
+angular.module('ui.bootstrap.timepicker', [])
+
+.constant('uibTimepickerConfig', {
+ hourStep: 1,
+ minuteStep: 1,
+ showMeridian: true,
+ meridians: null,
+ readonlyInput: false,
+ mousewheel: true,
+ arrowkeys: true,
+ showSpinners: true
+})
+
+.controller('UibTimepickerController', ['$scope', '$element', '$attrs', '$parse', '$log', '$locale', 'uibTimepickerConfig', function($scope, $element, $attrs, $parse, $log, $locale, timepickerConfig) {
+ var selected = new Date(),
+ ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
+ meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS;
+
+ $scope.tabindex = angular.isDefined($attrs.tabindex) ? $attrs.tabindex : 0;
+ $element.removeAttr('tabindex');
+
+ this.init = function(ngModelCtrl_, inputs) {
+ ngModelCtrl = ngModelCtrl_;
+ ngModelCtrl.$render = this.render;
+
+ ngModelCtrl.$formatters.unshift(function(modelValue) {
+ return modelValue ? new Date(modelValue) : null;
+ });
+
+ var hoursInputEl = inputs.eq(0),
+ minutesInputEl = inputs.eq(1);
+
+ var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel;
+ if (mousewheel) {
+ this.setupMousewheelEvents(hoursInputEl, minutesInputEl);
+ }
+
+ var arrowkeys = angular.isDefined($attrs.arrowkeys) ? $scope.$parent.$eval($attrs.arrowkeys) : timepickerConfig.arrowkeys;
+ if (arrowkeys) {
+ this.setupArrowkeyEvents(hoursInputEl, minutesInputEl);
+ }
+
+ $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput;
+ this.setupInputEvents(hoursInputEl, minutesInputEl);
+ };
+
+ var hourStep = timepickerConfig.hourStep;
+ if ($attrs.hourStep) {
+ $scope.$parent.$watch($parse($attrs.hourStep), function(value) {
+ hourStep = parseInt(value, 10);
+ });
+ }
+
+ var minuteStep = timepickerConfig.minuteStep;
+ if ($attrs.minuteStep) {
+ $scope.$parent.$watch($parse($attrs.minuteStep), function(value) {
+ minuteStep = parseInt(value, 10);
+ });
+ }
+
+ var min;
+ $scope.$parent.$watch($parse($attrs.min), function(value) {
+ var dt = new Date(value);
+ min = isNaN(dt) ? undefined : dt;
+ });
+
+ var max;
+ $scope.$parent.$watch($parse($attrs.max), function(value) {
+ var dt = new Date(value);
+ max = isNaN(dt) ? undefined : dt;
+ });
+
+ $scope.noIncrementHours = function() {
+ var incrementedSelected = addMinutes(selected, hourStep * 60);
+ return incrementedSelected > max ||
+ (incrementedSelected < selected && incrementedSelected < min);
+ };
+
+ $scope.noDecrementHours = function() {
+ var decrementedSelected = addMinutes(selected, -hourStep * 60);
+ return decrementedSelected < min ||
+ (decrementedSelected > selected && decrementedSelected > max);
+ };
+
+ $scope.noIncrementMinutes = function() {
+ var incrementedSelected = addMinutes(selected, minuteStep);
+ return incrementedSelected > max ||
+ (incrementedSelected < selected && incrementedSelected < min);
+ };
+
+ $scope.noDecrementMinutes = function() {
+ var decrementedSelected = addMinutes(selected, -minuteStep);
+ return decrementedSelected < min ||
+ (decrementedSelected > selected && decrementedSelected > max);
+ };
+
+ $scope.noToggleMeridian = function() {
+ if (selected.getHours() < 13) {
+ return addMinutes(selected, 12 * 60) > max;
+ } else {
+ return addMinutes(selected, -12 * 60) < min;
+ }
+ };
+
+ // 12H / 24H mode
+ $scope.showMeridian = timepickerConfig.showMeridian;
+ if ($attrs.showMeridian) {
+ $scope.$parent.$watch($parse($attrs.showMeridian), function(value) {
+ $scope.showMeridian = !!value;
+
+ if (ngModelCtrl.$error.time) {
+ // Evaluate from template
+ var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate();
+ if (angular.isDefined(hours) && angular.isDefined(minutes)) {
+ selected.setHours(hours);
+ refresh();
+ }
+ } else {
+ updateTemplate();
+ }
+ });
+ }
+
+ // Get $scope.hours in 24H mode if valid
+ function getHoursFromTemplate() {
+ var hours = parseInt($scope.hours, 10);
+ var valid = $scope.showMeridian ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);
+ if (!valid) {
+ return undefined;
+ }
+
+ if ($scope.showMeridian) {
+ if (hours === 12) {
+ hours = 0;
+ }
+ if ($scope.meridian === meridians[1]) {
+ hours = hours + 12;
+ }
+ }
+ return hours;
+ }
+
+ function getMinutesFromTemplate() {
+ var minutes = parseInt($scope.minutes, 10);
+ return (minutes >= 0 && minutes < 60) ? minutes : undefined;
+ }
+
+ function pad(value) {
+ return (angular.isDefined(value) && value.toString().length < 2) ? '0' + value : value.toString();
+ }
+
+ // Respond on mousewheel spin
+ this.setupMousewheelEvents = function(hoursInputEl, minutesInputEl) {
+ var isScrollingUp = function(e) {
+ if (e.originalEvent) {
+ e = e.originalEvent;
+ }
+ //pick correct delta variable depending on event
+ var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY;
+ return (e.detail || delta > 0);
+ };
+
+ hoursInputEl.bind('mousewheel wheel', function(e) {
+ $scope.$apply(isScrollingUp(e) ? $scope.incrementHours() : $scope.decrementHours());
+ e.preventDefault();
+ });
+
+ minutesInputEl.bind('mousewheel wheel', function(e) {
+ $scope.$apply(isScrollingUp(e) ? $scope.incrementMinutes() : $scope.decrementMinutes());
+ e.preventDefault();
+ });
+
+ };
+
+ // Respond on up/down arrowkeys
+ this.setupArrowkeyEvents = function(hoursInputEl, minutesInputEl) {
+ hoursInputEl.bind('keydown', function(e) {
+ if (e.which === 38) { // up
+ e.preventDefault();
+ $scope.incrementHours();
+ $scope.$apply();
+ } else if (e.which === 40) { // down
+ e.preventDefault();
+ $scope.decrementHours();
+ $scope.$apply();
+ }
+ });
+
+ minutesInputEl.bind('keydown', function(e) {
+ if (e.which === 38) { // up
+ e.preventDefault();
+ $scope.incrementMinutes();
+ $scope.$apply();
+ } else if (e.which === 40) { // down
+ e.preventDefault();
+ $scope.decrementMinutes();
+ $scope.$apply();
+ }
+ });
+ };
+
+ this.setupInputEvents = function(hoursInputEl, minutesInputEl) {
+ if ($scope.readonlyInput) {
+ $scope.updateHours = angular.noop;
+ $scope.updateMinutes = angular.noop;
+ return;
+ }
+
+ var invalidate = function(invalidHours, invalidMinutes) {
+ ngModelCtrl.$setViewValue(null);
+ ngModelCtrl.$setValidity('time', false);
+ if (angular.isDefined(invalidHours)) {
+ $scope.invalidHours = invalidHours;
+ }
+ if (angular.isDefined(invalidMinutes)) {
+ $scope.invalidMinutes = invalidMinutes;
+ }
+ };
+
+ $scope.updateHours = function() {
+ var hours = getHoursFromTemplate(),
+ minutes = getMinutesFromTemplate();
+
+ if (angular.isDefined(hours) && angular.isDefined(minutes)) {
+ selected.setHours(hours);
+ if (selected < min || selected > max) {
+ invalidate(true);
+ } else {
+ refresh('h');
+ }
+ } else {
+ invalidate(true);
+ }
+ };
+
+ hoursInputEl.bind('blur', function(e) {
+ if (!$scope.invalidHours && $scope.hours < 10) {
+ $scope.$apply(function() {
+ $scope.hours = pad($scope.hours);
+ });
+ }
+ });
+
+ $scope.updateMinutes = function() {
+ var minutes = getMinutesFromTemplate(),
+ hours = getHoursFromTemplate();
+
+ if (angular.isDefined(minutes) && angular.isDefined(hours)) {
+ selected.setMinutes(minutes);
+ if (selected < min || selected > max) {
+ invalidate(undefined, true);
+ } else {
+ refresh('m');
+ }
+ } else {
+ invalidate(undefined, true);
+ }
+ };
+
+ minutesInputEl.bind('blur', function(e) {
+ if (!$scope.invalidMinutes && $scope.minutes < 10) {
+ $scope.$apply(function() {
+ $scope.minutes = pad($scope.minutes);
+ });
+ }
+ });
+
+ };
+
+ this.render = function() {
+ var date = ngModelCtrl.$viewValue;
+
+ if (isNaN(date)) {
+ ngModelCtrl.$setValidity('time', false);
+ $log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
+ } else {
+ if (date) {
+ selected = date;
+ }
+
+ if (selected < min || selected > max) {
+ ngModelCtrl.$setValidity('time', false);
+ $scope.invalidHours = true;
+ $scope.invalidMinutes = true;
+ } else {
+ makeValid();
+ }
+ updateTemplate();
+ }
+ };
+
+ // Call internally when we know that model is valid.
+ function refresh(keyboardChange) {
+ makeValid();
+ ngModelCtrl.$setViewValue(new Date(selected));
+ updateTemplate(keyboardChange);
+ }
+
+ function makeValid() {
+ ngModelCtrl.$setValidity('time', true);
+ $scope.invalidHours = false;
+ $scope.invalidMinutes = false;
+ }
+
+ function updateTemplate(keyboardChange) {
+ var hours = selected.getHours(), minutes = selected.getMinutes();
+
+ if ($scope.showMeridian) {
+ hours = (hours === 0 || hours === 12) ? 12 : hours % 12; // Convert 24 to 12 hour system
+ }
+
+ $scope.hours = keyboardChange === 'h' ? hours : pad(hours);
+ if (keyboardChange !== 'm') {
+ $scope.minutes = pad(minutes);
+ }
+ $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];
+ }
+
+ function addMinutes(date, minutes) {
+ var dt = new Date(date.getTime() + minutes * 60000);
+ var newDate = new Date(date);
+ newDate.setHours(dt.getHours(), dt.getMinutes());
+ return newDate;
+ }
+
+ function addMinutesToSelected(minutes) {
+ selected = addMinutes(selected, minutes);
+ refresh();
+ }
+
+ $scope.showSpinners = angular.isDefined($attrs.showSpinners) ?
+ $scope.$parent.$eval($attrs.showSpinners) : timepickerConfig.showSpinners;
+
+ $scope.incrementHours = function() {
+ if (!$scope.noIncrementHours()) {
+ addMinutesToSelected(hourStep * 60);
+ }
+ };
+
+ $scope.decrementHours = function() {
+ if (!$scope.noDecrementHours()) {
+ addMinutesToSelected(-hourStep * 60);
+ }
+ };
+
+ $scope.incrementMinutes = function() {
+ if (!$scope.noIncrementMinutes()) {
+ addMinutesToSelected(minuteStep);
+ }
+ };
+
+ $scope.decrementMinutes = function() {
+ if (!$scope.noDecrementMinutes()) {
+ addMinutesToSelected(-minuteStep);
+ }
+ };
+
+ $scope.toggleMeridian = function() {
+ if (!$scope.noToggleMeridian()) {
+ addMinutesToSelected(12 * 60 * (selected.getHours() < 12 ? 1 : -1));
+ }
+ };
+}])
+
+.directive('uibTimepicker', function() {
+ return {
+ restrict: 'EA',
+ require: ['uibTimepicker', '?^ngModel'],
+ controller: 'UibTimepickerController',
+ controllerAs: 'timepicker',
+ replace: true,
+ scope: {},
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/timepicker/timepicker.html';
+ },
+ link: function(scope, element, attrs, ctrls) {
+ var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+
+ if (ngModelCtrl) {
+ timepickerCtrl.init(ngModelCtrl, element.find('input'));
+ }
+ }
+ };
+});
+
+/* Deprecated timepicker below */
+
+angular.module('ui.bootstrap.timepicker')
+
+.value('$timepickerSuppressWarning', false)
+
+.controller('TimepickerController', ['$scope', '$element', '$attrs', '$controller', '$log', '$timepickerSuppressWarning', function($scope, $element, $attrs, $controller, $log, $timepickerSuppressWarning) {
+ if (!$timepickerSuppressWarning) {
+ $log.warn('TimepickerController is now deprecated. Use UibTimepickerController instead.');
+ }
+
+ angular.extend(this, $controller('UibTimepickerController', {
+ $scope: $scope,
+ $element: $element,
+ $attrs: $attrs
+ }));
+}])
+
+.directive('timepicker', ['$log', '$timepickerSuppressWarning', function($log, $timepickerSuppressWarning) {
+ return {
+ restrict: 'EA',
+ require: ['timepicker', '?^ngModel'],
+ controller: 'TimepickerController',
+ controllerAs: 'timepicker',
+ replace: true,
+ scope: {},
+ templateUrl: function(element, attrs) {
+ return attrs.templateUrl || 'template/timepicker/timepicker.html';
+ },
+ link: function(scope, element, attrs, ctrls) {
+ if (!$timepickerSuppressWarning) {
+ $log.warn('timepicker is now deprecated. Use uib-timepicker instead.');
+ }
+ var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];
+
+ if (ngModelCtrl) {
+ timepickerCtrl.init(ngModelCtrl, element.find('input'));
+ }
+ }
+ };
+}]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/docs/demo.html
new file mode 100644
index 0000000..795f365
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/docs/demo.html
@@ -0,0 +1,69 @@
+<div ng-controller="TooltipDemoCtrl">
+ <div class="form-group">
+ <label>Dynamic Tooltip Text</label>
+ <input type="text" ng-model="dynamicTooltipText" class="form-control">
+ </div>
+ <div class="form-group">
+ <label>Dynamic Tooltip Popup Text</label>
+ <input type="text" ng-model="dynamicTooltip" class="form-control">
+ </div>
+ <p>
+ Pellentesque <a href="#" uib-tooltip="{{dynamicTooltip}}">{{dynamicTooltipText}}</a>,
+ sit amet venenatis urna cursus eget nunc scelerisque viverra mauris, in
+ aliquam. Tincidunt lobortis feugiat vivamus at
+ <a href="#" tooltip-placement="left" uib-tooltip="On the Left!">left</a> eget
+ arcu dictum varius duis at consectetur lorem. Vitae elementum curabitur
+ <a href="#" tooltip-placement="right" uib-tooltip="On the Right!">right</a>
+ nunc sed velit dignissim sodales ut eu sem integer vitae. Turpis egestas
+ <a href="#" tooltip-placement="bottom" uib-tooltip="On the Bottom!">bottom</a>
+ pharetra convallis posuere morbi leo urna,
+ <a href="#" tooltip-animation="false" uib-tooltip="I don't fade. :-(">fading</a>
+ at elementum eu, facilisis sed odio morbi quis commodo odio. In cursus
+ <a href="#" tooltip-popup-delay='1000' uib-tooltip='appears with delay'>show delay</a>
+ turpis massa tincidunt dui ut. In cursus
+ <a href="#" tooltip-popup-close-delay='1000' uib-tooltip='hides with delay'>hide delay</a>
+ <a href="#" uib-tooltip-template="'myTooltipTemplate.html'">Custom template</a>
+ nunc sed velit dignissim sodales ut eu sem integer vitae. Turpis egestas
+ </p>
+
+ <p>
+ I can even contain HTML. <a href="#" uib-tooltip-html="htmlTooltip">Check me out!</a>
+ </p>
+
+ <p>
+ <style>
+ /* Specify styling for tooltip contents */
+ .tooltip.customClass .tooltip-inner {
+ color: #880000;
+ background-color: #ffff66;
+ box-shadow: 0 6px 12px rgba(0,0,0,.175);
+ }
+ /* Hide arrow */
+ .tooltip.customClass .tooltip-arrow {
+ display: none;
+ }
+ </style>
+ I can have a custom class. <a href="#" uib-tooltip="I can have a custom class applied to me!" tooltip-class="customClass">Check me out!</a>
+ </p>
+
+ <form role="form">
+ <div class="form-group">
+ <label>Or use custom triggers, like focus: </label>
+ <input type="text" value="Click me!" uib-tooltip="See? Now click away..." tooltip-trigger="focus" tooltip-placement="right" class="form-control" />
+ </div>
+
+ <div class="form-group" ng-class="{'has-error' : !inputModel}">
+ <label>Disable tooltips conditionally:</label>
+ <input type="text" ng-model="inputModel" class="form-control"
+ placeholder="Hover over this for a tooltip until this is filled"
+ uib-tooltip="Enter something in this input field to disable this tooltip"
+ tooltip-placement="top"
+ tooltip-trigger="mouseenter"
+ tooltip-enable="!inputModel" />
+ </div>
+ </form>
+
+ <script type="text/ng-template" id="myTooltipTemplate.html">
+ <span>Special Tooltip with <strong>markup</strong> and {{ dynamicTooltipText }}</span>
+ </script>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/docs/demo.js
new file mode 100644
index 0000000..18c2794
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/docs/demo.js
@@ -0,0 +1,5 @@
+angular.module('ui.bootstrap.demo').controller('TooltipDemoCtrl', function ($scope, $sce) {
+ $scope.dynamicTooltip = 'Hello, World!';
+ $scope.dynamicTooltipText = 'dynamic';
+ $scope.htmlTooltip = $sce.trustAsHtml('I\'ve been made <b>bold</b>!');
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/docs/readme.md
new file mode 100644
index 0000000..16d4cdb
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/docs/readme.md
@@ -0,0 +1,80 @@
+A lightweight, extensible directive for fancy tooltip creation. The tooltip
+directive supports multiple placements, optional transition animation, and more.
+
+There are three versions of the tooltip: `uib-tooltip`, `uib-tooltip-template`, and
+`uib-tooltip-html-unsafe`:
+
+- `uib-tooltip` takes text only and will escape any HTML provided.
+- `uib-tooltip-template` takes text that specifies the location of a template to
+ use for the tooltip. Note that this needs to be wrapped in a tag.
+- `uib-tooltip-html` takes
+ whatever HTML is provided and displays it in a tooltip; *The user is responsible for ensuring the
+ content is safe to put into the DOM!*
+- `uib-tooltip-html-unsafe` -- deprecated in favour of `tooltip-html`
+
+The tooltip directives provide several optional attributes to control how they
+will display:
+
+- `tooltip-placement`: Where to place it? Defaults to "top", but also accepts
+ "bottom", "left", "right".
+- `tooltip-animation`: Should it fade in and out? Defaults to "true".
+- `tooltip-popup-delay`: For how long should the user have to have the mouse
+ over the element before the tooltip shows (in milliseconds)? Defaults to 0.
+- `tooltip-close-popup-delay`: For how long should the tooltip remain open
+ after the close trigger event? Defaults to 0.
+- `tooltip-trigger`: What should trigger a show of the tooltip? Supports a space separated list of event names.
+ Note: this attribute is no longer observable. See `tooltip-enable`.
+- `tooltip-enable`: Is it enabled? It will enable or disable the configured
+ `tooltip-trigger`.
+- `tooltip-append-to-body`: Should the tooltip be appended to `$body` instead of
+ the parent element?
+- `tooltip-class`: Custom class to be applied to the tooltip.
+- `tooltip-is-open` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Default: false)_:
+ Whether to show the tooltip.
+
+The tooltip directives require the `$position` service.
+
+**Triggers**
+
+The following show triggers are supported out of the box, along with their
+provided hide triggers:
+
+- `mouseenter`: `mouseleave`
+- `click`: `click`
+- `focus`: `blur`
+- `none`: ``
+
+For any non-supported value, the trigger will be used to both show and hide the
+tooltip. Using the 'none' trigger will disable the internal trigger(s), one can
+then use the `tooltip-is-open` attribute exclusively to show and hide the tooltip.
+
+**$uibTooltipProvider**
+
+Through the `$uibTooltipProvider`, you can change the way tooltips and popovers
+behave by default; the attributes above always take precedence. The following
+methods are available:
+
+- `setTriggers(obj)`: Extends the default trigger mappings mentioned above
+ with mappings of your own. E.g. `{ 'openTrigger': 'closeTrigger' }`.
+- `options(obj)`: Provide a set of defaults for certain tooltip and popover
+ attributes. Currently supports 'placement', 'animation', 'popupDelay', and
+ `appendToBody`. Here are the defaults:
+
+ <pre>
+ placement: 'top',
+ animation: true,
+ popupDelay: 0,
+ popupCloseDelay: 500,
+ appendToBody: false
+ </pre>
+
+**Known issues**
+
+For Safari 7+ support, if you want to use the **focus** `tooltip-trigger`, you need to use an anchor tag with a tab index. For example:
+
+```
+<a tabindex="0" uib-tooltip="Test" tooltip-trigger="focus" class="btn btn-default">
+ Click Me
+</a>
+```
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/test/tooltip-template.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/test/tooltip-template.spec.js
new file mode 100644
index 0000000..ad1c973
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/test/tooltip-template.spec.js
@@ -0,0 +1,146 @@
+describe('tooltip template', function() {
+ var elm,
+ elmBody,
+ scope,
+ elmScope,
+ tooltipScope;
+
+ // load the popover code
+ beforeEach(module('ui.bootstrap.tooltip'));
+
+ // load the template
+ beforeEach(module('template/tooltip/tooltip-template-popup.html'));
+
+ beforeEach(inject(function($templateCache) {
+ $templateCache.put('myUrl', [200, '<span>{{ myTemplateText }}</span>', {}]);
+ }));
+
+ beforeEach(inject(function($rootScope, $compile) {
+ elmBody = angular.element(
+ '<div><span uib-tooltip-template="templateUrl">Selector Text</span></div>'
+ );
+
+ scope = $rootScope;
+ $compile(elmBody)(scope);
+ scope.templateUrl = 'myUrl';
+
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ }));
+
+ function trigger(element, evt) {
+ evt = new Event(evt);
+
+ element[0].dispatchEvent(evt);
+ element.scope().$$childTail.$digest();
+ }
+
+ it('should open on mouseenter', inject(function() {
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(true);
+
+ expect(elmBody.children().length).toBe(2);
+ }));
+
+ it('should not open on mouseenter if templateUrl is empty', inject(function() {
+ scope.templateUrl = null;
+ scope.$digest();
+
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(false);
+
+ expect(elmBody.children().length).toBe(1);
+ }));
+
+ it('should show updated text', inject(function() {
+ scope.myTemplateText = 'some text';
+
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(true);
+ scope.$digest();
+
+ expect(elmBody.children().eq(1).text().trim()).toBe('some text');
+
+ scope.myTemplateText = 'new text';
+ scope.$digest();
+
+ expect(elmBody.children().eq(1).text().trim()).toBe('new text');
+ }));
+
+ it('should hide tooltip when template becomes empty', inject(function($timeout) {
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(true);
+
+ scope.templateUrl = '';
+ scope.$digest();
+
+ expect(tooltipScope.isOpen).toBe(false);
+
+ $timeout.flush();
+ expect(elmBody.children().length).toBe(1);
+ }));
+});
+
+/* Deprecation tests below */
+
+describe('tooltip template deprecation', function() {
+ beforeEach(module('ui.bootstrap.tooltip'));
+ beforeEach(module('template/tooltip/tooltip-template-popup.html'));
+
+ var elm, elmBody, elmScope, tooltipScope;
+
+ function trigger(element, evt) {
+ evt = new Event(evt);
+
+ element[0].dispatchEvent(evt);
+ element.scope().$$childTail.$digest();
+ }
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$tooltipSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope, $templateCache) {
+ spyOn($log, 'warn');
+ $templateCache.put('myUrl', [200, '<span>{{ myTemplateText }}</span>', {}]);
+ $rootScope.templateUrl = 'myUrl';
+
+ elmBody = angular.element('<div><span tooltip-template="templateUrl">Selector Text</span></div>');
+ $compile(elmBody)($rootScope);
+ $rootScope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ trigger(elm, 'mouseenter');
+
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope, $templateCache) {
+ spyOn($log, 'warn');
+ $templateCache.put('myUrl', [200, '<span>{{ myTemplateText }}</span>', {}]);
+ $rootScope.templateUrl = 'myUrl';
+
+ var element = '<div><span tooltip-template="templateUrl">Selector Text</span></div>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+
+ elmBody = angular.element('<div><span tooltip-template="templateUrl">Selector Text</span></div>');
+ $compile(elmBody)($rootScope);
+ $rootScope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ trigger(elm, 'mouseenter');
+
+ expect($log.warn.calls.count()).toBe(2);
+ expect($log.warn.calls.argsFor(0)).toEqual(['$tooltip is now deprecated. Use $uibTooltip instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['tooltip-template-popup is now deprecated. Use uib-tooltip-template-popup instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/test/tooltip.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/test/tooltip.spec.js
new file mode 100644
index 0000000..bbc8efb
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/test/tooltip.spec.js
@@ -0,0 +1,1070 @@
+describe('tooltip', function() {
+ var elm,
+ elmBody,
+ scope,
+ elmScope,
+ tooltipScope,
+ $document;
+
+ // load the tooltip code
+ beforeEach(module('ui.bootstrap.tooltip'));
+
+ // load the template
+ beforeEach(module('template/tooltip/tooltip-popup.html'));
+
+ beforeEach(inject(function($rootScope, $compile, _$document_) {
+ elmBody = angular.element(
+ '<div><span uib-tooltip="tooltip text" tooltip-animation="false">Selector Text</span></div>'
+ );
+
+ $document = _$document_;
+ scope = $rootScope;
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ }));
+
+ function trigger(element, evt) {
+ evt = new Event(evt);
+
+ element[0].dispatchEvent(evt);
+ element.scope().$$childTail.$digest();
+ }
+
+ it('should not be open initially', inject(function() {
+ expect(tooltipScope.isOpen).toBe(false);
+
+ // We can only test *that* the tooltip-popup element wasn't created as the
+ // implementation is templated and replaced.
+ expect(elmBody.children().length).toBe(1);
+ }));
+
+ it('should open on mouseenter', inject(function() {
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(true);
+
+ // We can only test *that* the tooltip-popup element was created as the
+ // implementation is templated and replaced.
+ expect(elmBody.children().length).toBe(2);
+ }));
+
+ it('should close on mouseleave', inject(function() {
+ trigger(elm, 'mouseenter');
+ trigger(elm, 'mouseleave');
+ expect(tooltipScope.isOpen).toBe(false);
+ }));
+
+ it('should not animate on animation set to false', inject(function() {
+ expect(tooltipScope.animation).toBe(false);
+ }));
+
+ it('should have default placement of "top"', inject(function() {
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.placement).toBe('top');
+ }));
+
+ it('should allow specification of placement', inject(function($compile) {
+ elm = $compile(angular.element(
+ '<span uib-tooltip="tooltip text" tooltip-placement="bottom">Selector Text</span>'
+ ))(scope);
+ scope.$apply();
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.placement).toBe('bottom');
+ }));
+
+ it('should update placement dynamically', inject(function($compile, $timeout) {
+ scope.place = 'bottom';
+ elm = $compile(angular.element(
+ '<span uib-tooltip="tooltip text" tooltip-placement="{{place}}">Selector Text</span>'
+ ))(scope);
+ scope.$apply();
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.placement).toBe('bottom');
+
+ scope.place = 'right';
+ scope.$digest();
+ $timeout.flush();
+ expect(tooltipScope.placement).toBe('right');
+ }));
+
+ it('should work inside an ngRepeat', inject(function($compile) {
+ elm = $compile(angular.element(
+ '<ul>'+
+ '<li ng-repeat="item in items">'+
+ '<span uib-tooltip="{{item.tooltip}}">{{item.name}}</span>'+
+ '</li>'+
+ '</ul>'
+ ))(scope);
+
+ scope.items = [
+ { name: 'One', tooltip: 'First Tooltip' }
+ ];
+
+ scope.$digest();
+
+ var tt = angular.element(elm.find('li > span')[0]);
+ trigger(tt, 'mouseenter');
+
+ expect(tt.text()).toBe(scope.items[0].name);
+
+ tooltipScope = tt.scope().$$childTail;
+ expect(tooltipScope.content).toBe(scope.items[0].tooltip);
+
+ trigger(tt, 'mouseleave');
+ expect(tooltipScope.isOpen).toBeFalsy();
+ }));
+
+ it('should show correct text when in an ngRepeat', inject(function($compile, $timeout) {
+ elm = $compile(angular.element(
+ '<ul>'+
+ '<li ng-repeat="item in items">'+
+ '<span uib-tooltip="{{item.tooltip}}">{{item.name}}</span>'+
+ '</li>'+
+ '</ul>'
+ ))(scope);
+
+ scope.items = [
+ { name: 'One', tooltip: 'First Tooltip' },
+ { name: 'Second', tooltip: 'Second Tooltip' }
+ ];
+
+ scope.$digest();
+
+ var tt_1 = angular.element(elm.find('li > span')[0]);
+ var tt_2 = angular.element(elm.find('li > span')[1]);
+
+ trigger(tt_1, 'mouseenter');
+ trigger(tt_1, 'mouseleave');
+
+ $timeout.flush();
+
+ trigger(tt_2, 'mouseenter');
+
+ expect(tt_1.text()).toBe(scope.items[0].name);
+ expect(tt_2.text()).toBe(scope.items[1].name);
+
+ tooltipScope = tt_2.scope().$$childTail;
+ expect(tooltipScope.content).toBe(scope.items[1].tooltip);
+ expect(elm.find('.tooltip-inner').text()).toBe(scope.items[1].tooltip);
+
+ trigger(tt_2, 'mouseleave');
+ }));
+
+ it('should only have an isolate scope on the popup', inject(function($compile) {
+ var ttScope;
+
+ scope.tooltipMsg = 'Tooltip Text';
+ scope.alt = 'Alt Message';
+
+ elmBody = $compile(angular.element(
+ '<div><span alt={{alt}} uib-tooltip="{{tooltipMsg}}" tooltip-animation="false">Selector Text</span></div>'
+ ))(scope);
+
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+
+ trigger(elm, 'mouseenter');
+ expect(elm.attr('alt')).toBe(scope.alt);
+
+ ttScope = angular.element(elmBody.children()[1]).isolateScope();
+ expect(ttScope.placement).toBe('top');
+ expect(ttScope.content).toBe(scope.tooltipMsg);
+
+ trigger(elm, 'mouseleave');
+
+ //Isolate scope contents should be the same after hiding and showing again (issue 1191)
+ trigger(elm, 'mouseenter');
+
+ ttScope = angular.element(elmBody.children()[1]).isolateScope();
+ expect(ttScope.placement).toBe('top');
+ expect(ttScope.content).toBe(scope.tooltipMsg);
+ }));
+
+ it('should not show tooltips if there is nothing to show - issue #129', inject(function($compile) {
+ elmBody = $compile(angular.element(
+ '<div><span uib-tooltip="">Selector Text</span></div>'
+ ))(scope);
+ scope.$digest();
+ elmBody.find('span').trigger('mouseenter');
+
+ expect(elmBody.children().length).toBe(1);
+ }));
+
+ it('should close the tooltip when its trigger element is destroyed', inject(function() {
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(true);
+
+ elm.remove();
+ elmScope.$destroy();
+ expect(elmBody.children().length).toBe(0);
+ }));
+
+ it('issue 1191 - scope on the popup should always be child of correct element scope', function() {
+ var ttScope;
+ trigger(elm, 'mouseenter');
+
+ ttScope = angular.element(elmBody.children()[1]).scope();
+ expect(ttScope.$parent).toBe(tooltipScope);
+
+ trigger(elm, 'mouseleave');
+
+ // After leaving and coming back, the scope's parent should be the same
+ trigger(elm, 'mouseenter');
+
+ ttScope = angular.element(elmBody.children()[1]).scope();
+ expect(ttScope.$parent).toBe(tooltipScope);
+
+ trigger(elm, 'mouseleave');
+ });
+
+ describe('with specified enable expression', function() {
+ beforeEach(inject(function($compile) {
+ scope.enable = false;
+ elmBody = $compile(angular.element(
+ '<div><span uib-tooltip="tooltip text" tooltip-enable="enable">Selector Text</span></div>'
+ ))(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ }));
+
+ it('should not open ', inject(function() {
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBeFalsy();
+ expect(elmBody.children().length).toBe(1);
+ }));
+
+ it('should open', inject(function() {
+ scope.enable = true;
+ scope.$digest();
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBeTruthy();
+ expect(elmBody.children().length).toBe(2);
+ }));
+ });
+
+ describe('with specified popup delay', function() {
+ var $timeout;
+ beforeEach(inject(function($compile, _$timeout_) {
+ $timeout = _$timeout_;
+ scope.delay = '1000';
+ elm = $compile(angular.element(
+ '<span uib-tooltip="tooltip text" tooltip-popup-delay="{{delay}}" ng-disabled="disabled">Selector Text</span>'
+ ))(scope);
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ scope.$digest();
+ }));
+
+ it('should open after timeout', function() {
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(false);
+
+ $timeout.flush();
+ expect(tooltipScope.isOpen).toBe(true);
+ });
+
+ it('should not open if mouseleave before timeout', function() {
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(false);
+
+ trigger(elm, 'mouseleave');
+ $timeout.flush();
+ expect(tooltipScope.isOpen).toBe(false);
+ });
+
+ it('should use default popup delay if specified delay is not a number', function() {
+ scope.delay = 'text1000';
+ scope.$digest();
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(true);
+ });
+
+ it('should not open if disabled is present', function() {
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(false);
+
+ $timeout.flush(500);
+ expect(tooltipScope.isOpen).toBe(false);
+ elmScope.disabled = true;
+ elmScope.$digest();
+
+ expect(tooltipScope.isOpen).toBe(false);
+ });
+
+ it('should open when not disabled after being disabled - issue #4204', function() {
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(false);
+
+ $timeout.flush(500);
+ elmScope.disabled = true;
+ elmScope.$digest();
+
+ $timeout.flush(500);
+ expect(tooltipScope.isOpen).toBe(false);
+
+ elmScope.disabled = false;
+ elmScope.$digest();
+
+ trigger(elm, 'mouseenter');
+ $timeout.flush();
+
+ expect(tooltipScope.isOpen).toBe(true);
+ });
+
+ it('should close the tooltips in order', inject(function($compile) {
+ var elm2 = $compile('<div><span uib-tooltip="tooltip #2" tooltip-is-open="isOpen2">Selector Text</span></div>')(scope);
+ scope.$digest();
+ elm2 = elm2.find('span');
+ var tooltipScope2 = elm2.scope().$$childTail;
+ tooltipScope2.isOpen = false;
+ scope.$digest();
+
+ trigger(elm, 'mouseenter');
+ tooltipScope2.$digest();
+ $timeout.flush();
+ expect(tooltipScope.isOpen).toBe(true);
+ expect(tooltipScope2.isOpen).toBe(false);
+
+ trigger(elm2, 'mouseenter');
+ tooltipScope2.$digest();
+ $timeout.flush();
+ expect(tooltipScope.isOpen).toBe(true);
+ expect(tooltipScope2.isOpen).toBe(true);
+
+ var evt = $.Event('keypress');
+ evt.which = 27;
+
+ $document.trigger(evt);
+ tooltipScope.$digest();
+ tooltipScope2.$digest();
+
+ expect(tooltipScope.isOpen).toBe(true);
+ expect(tooltipScope2.isOpen).toBe(false);
+
+ var evt2 = $.Event('keypress');
+ evt2.which = 27;
+
+ $document.trigger(evt2);
+ tooltipScope.$digest();
+ tooltipScope2.$digest();
+
+ expect(tooltipScope.isOpen).toBe(false);
+ expect(tooltipScope2.isOpen).toBe(false);
+ }));
+ });
+
+ describe('with specified popup close delay', function() {
+ var $timeout;
+ beforeEach(inject(function($compile, _$timeout_) {
+ $timeout = _$timeout_;
+ scope.delay = '1000';
+ elm = $compile(angular.element(
+ '<span uib-tooltip="tooltip text" tooltip-popup-close-delay="{{delay}}" ng-disabled="disabled">Selector Text</span>'
+ ))(scope);
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ scope.$digest();
+ }));
+
+ it('should close after timeout', function() {
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(true);
+ trigger(elm, 'mouseleave');
+ $timeout.flush();
+ expect(tooltipScope.isOpen).toBe(false);
+ });
+
+ it('should use default popup close delay if specified delay is not a number and close immediately', function() {
+ scope.delay = 'text1000';
+ scope.$digest();
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.popupCloseDelay).toBe(0);
+ expect(tooltipScope.isOpen).toBe(true);
+ trigger(elm, 'mouseleave');
+ $timeout.flush();
+ expect(tooltipScope.isOpen).toBe(false);
+ });
+
+ it('should open when not disabled after being disabled and close after delay - issue #4204', function() {
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(true);
+
+ elmScope.disabled = true;
+ elmScope.$digest();
+
+ $timeout.flush(500);
+ expect(tooltipScope.isOpen).toBe(false);
+
+ elmScope.disabled = false;
+ elmScope.$digest();
+
+ trigger(elm, 'mouseenter');
+
+ expect(tooltipScope.isOpen).toBe(true);
+ trigger(elm, 'mouseleave');
+ $timeout.flush();
+ expect(tooltipScope.isOpen).toBe(false);
+ });
+ });
+
+ describe('with specified popup and popup close delay', function() {
+ var $timeout;
+ beforeEach(inject(function($compile, _$timeout_) {
+ $timeout = _$timeout_;
+ scope.delay = '1000';
+ elm = $compile(angular.element(
+ '<span uib-tooltip="tooltip text" tooltip-popup-close-delay="{{delay}}" tooltip-popup-close-delay="{{delay}}" ng-disabled="disabled">Selector Text</span>'
+ ))(scope);
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ scope.$digest();
+ }));
+
+ it('should not open if mouseleave before timeout', function() {
+ trigger(elm, 'mouseenter');
+ $timeout.flush(500);
+ trigger(elm, 'mouseleave');
+ $timeout.flush();
+
+ expect(tooltipScope.isOpen).toBe(false);
+ });
+ });
+
+ describe('with an is-open attribute', function() {
+ beforeEach(inject(function ($compile) {
+ scope.isOpen = false;
+ elm = $compile(angular.element(
+ '<span uib-tooltip="tooltip text" tooltip-is-open="isOpen" >Selector Text</span>'
+ ))(scope);
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ scope.$digest();
+ }));
+
+ it('should show and hide with the controller value', function() {
+ expect(tooltipScope.isOpen).toBe(false);
+ elmScope.isOpen = true;
+ elmScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+ elmScope.isOpen = false;
+ elmScope.$digest();
+ expect(tooltipScope.isOpen).toBe(false);
+ });
+
+ it('should update the controller value', function() {
+ trigger(elm, 'mouseenter');
+ expect(elmScope.isOpen).toBe(true);
+ trigger(elm, 'mouseleave');
+ expect(elmScope.isOpen).toBe(false);
+ });
+ });
+
+ describe('with an is-open attribute expression', function() {
+ beforeEach(inject(function($compile) {
+ scope.isOpen = false;
+ elm = $compile(angular.element(
+ '<span uib-tooltip="tooltip text" tooltip-is-open="isOpen === true" >Selector Text</span>'
+ ))(scope);
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ scope.$digest();
+ }));
+
+ it('should show and hide with the expression', function() {
+ expect(tooltipScope.isOpen).toBe(false);
+ elmScope.isOpen = true;
+ elmScope.$digest();
+ expect(tooltipScope.isOpen).toBe(true);
+ elmScope.isOpen = false;
+ elmScope.$digest();
+ expect(tooltipScope.isOpen).toBe(false);
+ });
+ });
+
+ describe('with a trigger attribute', function() {
+ var scope, elmBody, elm, elmScope;
+
+ beforeEach(inject(function($rootScope) {
+ scope = $rootScope;
+ }));
+
+ it('should use it to show but set the hide trigger based on the map for mapped triggers', inject(function($compile) {
+ elmBody = angular.element(
+ '<div><input uib-tooltip="Hello!" tooltip-trigger="focus" /></div>'
+ );
+ $compile(elmBody)(scope);
+ scope.$apply();
+ elm = elmBody.find('input');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ expect(tooltipScope.isOpen).toBeFalsy();
+ trigger(elm, 'focus');
+ expect(tooltipScope.isOpen).toBeTruthy();
+ trigger(elm, 'blur');
+ expect(tooltipScope.isOpen).toBeFalsy();
+ }));
+
+ it('should use it as both the show and hide triggers for unmapped triggers', inject(function($compile) {
+ elmBody = angular.element(
+ '<div><input uib-tooltip="Hello!" tooltip-trigger="fakeTriggerAttr" /></div>'
+ );
+ $compile(elmBody)(scope);
+ scope.$apply();
+ elm = elmBody.find('input');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ expect(tooltipScope.isOpen).toBeFalsy();
+ trigger(elm, 'fakeTriggerAttr');
+ expect(tooltipScope.isOpen).toBeTruthy();
+ trigger(elm, 'fakeTriggerAttr');
+ expect(tooltipScope.isOpen).toBeFalsy();
+ }));
+
+ it('should only set up triggers once', inject(function($compile) {
+ scope.test = true;
+ elmBody = angular.element(
+ '<div>' +
+ '<input uib-tooltip="Hello!" tooltip-trigger="{{ (test && \'mouseenter\' || \'click\') }}" />' +
+ '<input uib-tooltip="Hello!" tooltip-trigger="{{ (test && \'mouseenter\' || \'click\') }}" />' +
+ '</div>'
+ );
+
+ $compile(elmBody)(scope);
+ scope.$apply();
+ var elm1 = elmBody.find('input').eq(0);
+ var elm2 = elmBody.find('input').eq(1);
+ var elmScope1 = elm1.scope();
+ var elmScope2 = elm2.scope();
+ var tooltipScope2 = elmScope2.$$childTail;
+
+ scope.$apply('test = false');
+
+ // click trigger isn't set
+ elm2.click();
+ expect(tooltipScope2.isOpen).toBeFalsy();
+
+ // mouseenter trigger is still set
+ trigger(elm2, 'mouseenter');
+ expect(tooltipScope2.isOpen).toBeTruthy();
+ }));
+
+ it('should accept multiple triggers based on the map for mapped triggers', inject(function($compile) {
+ elmBody = angular.element(
+ '<div><input uib-tooltip="Hello!" tooltip-trigger="focus fakeTriggerAttr" /></div>'
+ );
+ $compile(elmBody)(scope);
+ scope.$apply();
+ elm = elmBody.find('input');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ expect(tooltipScope.isOpen).toBeFalsy();
+ trigger(elm, 'focus');
+ expect(tooltipScope.isOpen).toBeTruthy();
+ trigger(elm, 'blur');
+ expect(tooltipScope.isOpen).toBeFalsy();
+ trigger(elm, 'fakeTriggerAttr');
+ expect(tooltipScope.isOpen).toBeTruthy();
+ trigger(elm, 'fakeTriggerAttr');
+ expect(tooltipScope.isOpen).toBeFalsy();
+ }));
+
+ it('should not show when trigger is set to "none"', inject(function($compile) {
+ elmBody = angular.element(
+ '<div><input uib-tooltip="Hello!" tooltip-trigger="none" /></div>'
+ );
+ $compile(elmBody)(scope);
+ scope.$apply();
+ elm = elmBody.find('input');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ expect(tooltipScope.isOpen).toBeFalsy();
+ elm.trigger('mouseenter');
+ expect(tooltipScope.isOpen).toBeFalsy();
+ }));
+ });
+
+ describe('with an append-to-body attribute', function() {
+ var scope, elmBody, elm, elmScope, $body;
+
+ beforeEach(inject(function($rootScope) {
+ scope = $rootScope;
+ }));
+
+ afterEach(function() {
+ $body.find('.tooltip').remove();
+ });
+
+ it('should append to the body', inject(function($compile, $document) {
+ $body = $document.find('body');
+ elmBody = angular.element(
+ '<div><span uib-tooltip="tooltip text" tooltip-append-to-body="true">Selector Text</span></div>'
+ );
+
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ var bodyLength = $body.children().length;
+ trigger(elm, 'mouseenter');
+
+ expect(tooltipScope.isOpen).toBe(true);
+ expect(elmBody.children().length).toBe(1);
+ expect($body.children().length).toEqual(bodyLength + 1);
+ }));
+ });
+
+ describe('cleanup', function() {
+ var elmBody, elm, elmScope, tooltipScope;
+
+ function inCache() {
+ var match = false;
+
+ angular.forEach(angular.element.cache, function(item) {
+ if (item.data && item.data.$scope === tooltipScope) {
+ match = true;
+ }
+ });
+
+ return match;
+ }
+
+ beforeEach(inject(function($compile, $rootScope) {
+ elmBody = angular.element('<div><input uib-tooltip="Hello!" tooltip-trigger="fooTrigger" /></div>');
+
+ $compile(elmBody)($rootScope);
+ $rootScope.$apply();
+
+ elm = elmBody.find('input');
+ elmScope = elm.scope();
+ trigger(elm, 'fooTrigger');
+ tooltipScope = elmScope.$$childTail.$$childTail;
+ }));
+
+ it('should not contain a cached reference when not visible', inject(function($timeout) {
+ expect(inCache()).toBeTruthy();
+ elmScope.$destroy();
+ expect(inCache()).toBeFalsy();
+ }));
+ });
+
+ describe('observers', function() {
+ var elmBody, elm, elmScope, scope, tooltipScope;
+
+ beforeEach(inject(function($compile, $rootScope) {
+ scope = $rootScope;
+ scope.content = 'tooltip content';
+ scope.placement = 'top';
+ elmBody = angular.element('<div><input uib-tooltip="{{content}}" tooltip-placement={{placement}} /></div>');
+ $compile(elmBody)(scope);
+ scope.$apply();
+
+ elm = elmBody.find('input');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ }));
+
+ it('should be removed when tooltip hides', inject(function($timeout) {
+ expect(tooltipScope.content).toBe(undefined);
+ expect(tooltipScope.placement).toBe(undefined);
+
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.content).toBe('tooltip content');
+ expect(tooltipScope.placement).toBe('top');
+ scope.content = 'tooltip content updated';
+
+ scope.placement = 'bottom';
+ scope.$apply();
+ expect(tooltipScope.content).toBe('tooltip content updated');
+ expect(tooltipScope.placement).toBe('bottom');
+
+ trigger(elm, 'mouseleave');
+ $timeout.flush();
+ scope.content = 'tooltip content updated after close';
+ scope.placement = 'left';
+ scope.$apply();
+ expect(tooltipScope.content).toBe('tooltip content updated');
+ expect(tooltipScope.placement).toBe('bottom');
+ }));
+ });
+});
+
+describe('tooltipWithDifferentSymbols', function() {
+ var elmBody;
+
+ // load the tooltip code
+ beforeEach(module('ui.bootstrap.tooltip'));
+
+ // load the template
+ beforeEach(module('template/tooltip/tooltip-popup.html'));
+
+ // configure interpolate provider to use [[ ]] instead of {{ }}
+ beforeEach(module(function($interpolateProvider) {
+ $interpolateProvider.startSymbol('[[');
+ $interpolateProvider.startSymbol(']]');
+ }));
+
+ function trigger(element, evt) {
+ evt = new Event(evt);
+
+ element[0].dispatchEvent(evt);
+ element.scope().$$childTail.$digest();
+ }
+
+ it('should show the correct tooltip text', inject(function($compile, $rootScope) {
+ elmBody = angular.element(
+ '<div><input type="text" uib-tooltip="My tooltip" tooltip-trigger="focus" tooltip-placement="right" /></div>'
+ );
+ $compile(elmBody)($rootScope);
+ $rootScope.$apply();
+ var elmInput = elmBody.find('input');
+ trigger(elmInput, 'focus');
+
+ expect(elmInput.next().find('div').next().html()).toBe('My tooltip');
+ }));
+});
+
+describe('tooltip positioning', function() {
+ var elm, elmBody, elmScope, tooltipScope, scope;
+ var $position;
+
+ // load the tooltip code
+ beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider) {
+ $tooltipProvider.options({ animation: false });
+ }));
+
+ // load the template
+ beforeEach(module('template/tooltip/tooltip-popup.html'));
+
+ beforeEach(inject(function($rootScope, $compile, $uibPosition) {
+ $position = $uibPosition;
+ spyOn($position, 'positionElements').and.callThrough();
+
+ scope = $rootScope;
+ scope.text = 'Some Text';
+
+ elmBody = $compile(angular.element(
+ '<div><span uib-tooltip="{{ text }}">Selector Text</span></div>'
+ ))(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ }));
+
+ function trigger(element, evt) {
+ evt = new Event(evt);
+
+ element[0].dispatchEvent(evt);
+ element.scope().$$childTail.$digest();
+ }
+
+ it('should re-position when value changes', inject(function($timeout) {
+ trigger(elm, 'mouseenter');
+
+ scope.$digest();
+ $timeout.flush();
+ var startingPositionCalls = $position.positionElements.calls.count();
+
+ scope.text = 'New Text';
+ scope.$digest();
+ $timeout.flush();
+ expect(elm.attr('uib-tooltip')).toBe('New Text');
+ expect($position.positionElements.calls.count()).toEqual(startingPositionCalls + 1);
+ // Check that positionElements was called with elm
+ expect($position.positionElements.calls.argsFor(startingPositionCalls)[0][0])
+ .toBe(elm[0]);
+
+ scope.$digest();
+ $timeout.verifyNoPendingTasks();
+ expect($position.positionElements.calls.count()).toEqual(startingPositionCalls + 1);
+ expect($position.positionElements.calls.argsFor(startingPositionCalls)[0][0])
+ .toBe(elm[0]);
+ scope.$digest();
+ }));
+
+});
+
+describe('tooltipHtml', function() {
+ var elm, elmBody, elmScope, tooltipScope, scope;
+
+ // load the tooltip code
+ beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider) {
+ $tooltipProvider.options({ animation: false });
+ }));
+
+ // load the template
+ beforeEach(module('template/tooltip/tooltip-html-popup.html'));
+
+ beforeEach(inject(function($rootScope, $compile, $sce) {
+ scope = $rootScope;
+ scope.html = 'I say: <strong class="hello">Hello!</strong>';
+ scope.safeHtml = $sce.trustAsHtml(scope.html);
+
+ elmBody = $compile(angular.element(
+ '<div><span uib-tooltip-html="safeHtml">Selector Text</span></div>'
+ ))(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ }));
+
+ function trigger(element, evt) {
+ evt = new Event(evt);
+
+ element[0].dispatchEvent(evt);
+ element.scope().$$childTail.$digest();
+ }
+
+ it('should render html properly', inject(function() {
+ trigger(elm, 'mouseenter');
+ expect(elmBody.find('.tooltip-inner').html()).toBe(scope.html);
+ }));
+
+ it('should not open if html is empty', function() {
+ scope.safeHtml = null;
+ scope.$digest();
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(false);
+ });
+
+ it('should show on mouseenter and hide on mouseleave', inject(function($sce) {
+ expect(tooltipScope.isOpen).toBe(false);
+
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(true);
+ expect(elmBody.children().length).toBe(2);
+
+ expect($sce.getTrustedHtml(tooltipScope.contentExp())).toEqual(scope.html);
+
+ trigger(elm, 'mouseleave');
+ expect(tooltipScope.isOpen).toBe(false);
+ expect(elmBody.children().length).toBe(1);
+ }));
+});
+
+describe('$tooltipProvider', function() {
+ var elm,
+ elmBody,
+ scope,
+ elmScope,
+ tooltipScope;
+
+ function trigger(element, evt) {
+ evt = new Event(evt);
+
+ element[0].dispatchEvent(evt);
+ element.scope().$$childTail.$digest();
+ }
+
+ describe('popupDelay', function() {
+ beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider) {
+ $tooltipProvider.options({popupDelay: 1000});
+ }));
+
+ // load the template
+ beforeEach(module('template/tooltip/tooltip-popup.html'));
+
+ beforeEach(inject(function($rootScope, $compile) {
+ elmBody = angular.element(
+ '<div><span uib-tooltip="tooltip text">Selector Text</span></div>'
+ );
+
+ scope = $rootScope;
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+ }));
+
+ it('should open after timeout', inject(function($timeout) {
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(false);
+
+ $timeout.flush();
+ expect(tooltipScope.isOpen).toBe(true);
+ }));
+ });
+
+ describe('appendToBody', function() {
+ var $body;
+
+ beforeEach(module('template/tooltip/tooltip-popup.html'));
+ beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider) {
+ $tooltipProvider.options({ appendToBody: true });
+ }));
+
+ afterEach(function() {
+ $body.find('.tooltip').remove();
+ });
+
+ it('should append to the body', inject(function($rootScope, $compile, $document) {
+ $body = $document.find('body');
+ elmBody = angular.element(
+ '<div><span uib-tooltip="tooltip text">Selector Text</span></div>'
+ );
+
+ scope = $rootScope;
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ var bodyLength = $body.children().length;
+ trigger(elm, 'mouseenter');
+
+ expect(tooltipScope.isOpen).toBe(true);
+ expect(elmBody.children().length).toBe(1);
+ expect($body.children().length).toEqual(bodyLength + 1);
+ }));
+
+ it('should close on location change', inject(function($rootScope, $compile) {
+ elmBody = angular.element(
+ '<div><span uib-tooltip="tooltip text">Selector Text</span></div>'
+ );
+
+ scope = $rootScope;
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBe(true);
+
+ scope.$broadcast('$locationChangeSuccess');
+ scope.$digest();
+ expect(tooltipScope.isOpen).toBe(false);
+ }));
+ });
+
+ describe('triggers', function() {
+ describe('triggers with a mapped value', function() {
+ beforeEach(module('ui.bootstrap.tooltip', function($uibTooltipProvider) {
+ $uibTooltipProvider.options({trigger: 'focus'});
+ }));
+
+ // load the template
+ beforeEach(module('template/tooltip/tooltip-popup.html'));
+
+ it('should use the show trigger and the mapped value for the hide trigger', inject(function($rootScope, $compile) {
+ elmBody = angular.element(
+ '<div><input uib-tooltip="tooltip text" /></div>'
+ );
+
+ scope = $rootScope;
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('input');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ expect(tooltipScope.isOpen).toBeFalsy();
+ trigger(elm, 'focus');
+ expect(tooltipScope.isOpen).toBeTruthy();
+ trigger(elm, 'blur');
+ expect(tooltipScope.isOpen).toBeFalsy();
+ }));
+
+ it('should override the show and hide triggers if there is an attribute', inject(function($rootScope, $compile) {
+ elmBody = angular.element(
+ '<div><input uib-tooltip="tooltip text" tooltip-trigger="mouseenter"/></div>'
+ );
+
+ scope = $rootScope;
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('input');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ expect(tooltipScope.isOpen).toBeFalsy();
+ trigger(elm, 'mouseenter');
+ expect(tooltipScope.isOpen).toBeTruthy();
+ trigger(elm, 'mouseleave');
+ expect(tooltipScope.isOpen).toBeFalsy();
+ }));
+ });
+
+ describe('triggers with a custom mapped value', function() {
+ beforeEach(module('ui.bootstrap.tooltip', function($uibTooltipProvider) {
+ $uibTooltipProvider.setTriggers({ customOpenTrigger: 'foo bar' });
+ $uibTooltipProvider.options({trigger: 'customOpenTrigger'});
+ }));
+
+ // load the template
+ beforeEach(module('template/tooltip/tooltip-popup.html'));
+
+ it('should use the show trigger and the mapped value for the hide trigger', inject(function($rootScope, $compile) {
+ elmBody = angular.element(
+ '<div><input uib-tooltip="tooltip text" /></div>'
+ );
+
+ scope = $rootScope;
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('input');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ expect(tooltipScope.isOpen).toBeFalsy();
+ trigger(elm, 'customOpenTrigger');
+ expect(tooltipScope.isOpen).toBeTruthy();
+ trigger(elm, 'foo');
+ expect(tooltipScope.isOpen).toBeFalsy();
+ trigger(elm, 'customOpenTrigger');
+ expect(tooltipScope.isOpen).toBeTruthy();
+ trigger(elm, 'bar');
+ expect(tooltipScope.isOpen).toBeFalsy();
+ }));
+ });
+
+ describe('triggers without a mapped value', function() {
+ beforeEach(module('ui.bootstrap.tooltip', function($uibTooltipProvider) {
+ $uibTooltipProvider.options({trigger: 'fakeTrigger'});
+ }));
+
+ // load the template
+ beforeEach(module('template/tooltip/tooltip-popup.html'));
+
+ it('should use the show trigger to hide', inject(function($rootScope, $compile) {
+ elmBody = angular.element(
+ '<div><span uib-tooltip="tooltip text">Selector Text</span></div>'
+ );
+
+ scope = $rootScope;
+ $compile(elmBody)(scope);
+ scope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ expect(tooltipScope.isOpen).toBeFalsy();
+ trigger(elm, 'fakeTrigger');
+ expect(tooltipScope.isOpen).toBeTruthy();
+ trigger(elm, 'fakeTrigger');
+ expect(tooltipScope.isOpen).toBeFalsy();
+ }));
+ });
+ });
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/test/tooltip2.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/test/tooltip2.spec.js
new file mode 100644
index 0000000..2ed8e2b
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/test/tooltip2.spec.js
@@ -0,0 +1,282 @@
+describe('tooltip directive', function() {
+ var $rootScope, $compile, $document, $timeout;
+
+ beforeEach(module('ui.bootstrap.tooltip'));
+ beforeEach(module('template/tooltip/tooltip-popup.html'));
+ beforeEach(module('template/tooltip/tooltip-template-popup.html'));
+ beforeEach(module('template/tooltip/tooltip-html-popup.html'));
+ beforeEach(inject(function(_$rootScope_, _$compile_, _$document_, _$timeout_) {
+ $rootScope = _$rootScope_;
+ $compile = _$compile_;
+ $document = _$document_;
+ $timeout = _$timeout_;
+ }));
+
+ beforeEach(function() {
+ jasmine.addMatchers({
+ toHaveOpenTooltips: function(util, customEqualityTesters) {
+ return {
+ compare: function(actual, noOfOpened) {
+ var ttipElements = actual.find('div.tooltip');
+ noOfOpened = noOfOpened || 1;
+
+ var result = {
+ pass: util.equals(ttipElements.length, noOfOpened, customEqualityTesters)
+ };
+
+ if (result.message) {
+ result.message = 'Expected "' + angular.mock.dump(ttipElements) + '" not to have "' + ttipElements.length + '" opened tooltips.';
+ } else {
+ result.message = 'Expected "' + angular.mock.dump(ttipElements) + '" to have "' + ttipElements.length + '" opened tooltips.';
+ }
+
+ return result;
+ }
+ };
+ }
+ });
+ });
+
+ function compileTooltip(ttipMarkup) {
+ var fragment = $compile('<div>' + ttipMarkup + '</div>')($rootScope);
+ $rootScope.$digest();
+ return fragment;
+ }
+
+ function closeTooltip(hostEl, triggerEvt, shouldNotFlush) {
+ trigger(hostEl, triggerEvt || 'mouseleave');
+ hostEl.scope().$$childTail.$digest();
+ if (!shouldNotFlush) {
+ $timeout.flush();
+ }
+ }
+
+ function trigger(element, evt) {
+ evt = new Event(evt);
+
+ element[0].dispatchEvent(evt);
+ element.scope().$$childTail.$digest();
+ }
+
+ describe('basic scenarios with default options', function() {
+ it('shows default tooltip on mouse enter and closes on mouse leave', function() {
+ var fragment = compileTooltip('<span uib-tooltip="tooltip text">Trigger here</span>');
+
+ trigger(fragment.find('span'), 'mouseenter');
+ expect(fragment).toHaveOpenTooltips();
+
+ closeTooltip(fragment.find('span'));
+ expect(fragment).not.toHaveOpenTooltips();
+ });
+
+ it('should not show a tooltip when its content is empty', function() {
+ var fragment = compileTooltip('<span uib-tooltip=""></span>');
+ trigger(fragment.find('span'), 'mouseenter');
+ expect(fragment).not.toHaveOpenTooltips();
+ });
+
+ it('should not show a tooltip when its content becomes empty', function() {
+ $rootScope.content = 'some text';
+ var fragment = compileTooltip('<span uib-tooltip="{{ content }}"></span>');
+
+ trigger(fragment.find('span'), 'mouseenter');
+ expect(fragment).toHaveOpenTooltips();
+
+ $rootScope.content = '';
+ $rootScope.$digest();
+ $timeout.flush();
+ expect(fragment).not.toHaveOpenTooltips();
+ });
+
+ it('should update tooltip when its content becomes empty', function() {
+ $rootScope.content = 'some text';
+ var fragment = compileTooltip('<span uib-tooltip="{{ content }}"></span>');
+
+ $rootScope.content = '';
+ $rootScope.$digest();
+
+ trigger(fragment.find('span'), 'mouseenter');
+ expect(fragment).not.toHaveOpenTooltips();
+ });
+ });
+
+ describe('option by option', function() {
+ var tooltipTypes = {
+ 'tooltip': 'uib-tooltip="tooltip text"',
+ 'tooltip-html': 'uib-tooltip-html="tooltipSafeHtml"',
+ 'tooltip-template': 'uib-tooltip-template="\'tooltipTextUrl\'"'
+ };
+
+ beforeEach(inject(function($sce, $templateCache) {
+ $rootScope.tooltipText = 'tooltip text';
+ $rootScope.tooltipSafeHtml = $sce.trustAsHtml('tooltip text');
+ $templateCache.put('tooltipTextUrl', [200, '<span>tooltip text</span>', {}]);
+ }));
+
+ angular.forEach(tooltipTypes, function(html, key) {
+ describe(key, function() {
+ describe('placement', function() {
+ it('can specify an alternative, valid placement', function() {
+ var fragment = compileTooltip('<span ' + html + ' tooltip-placement="left">Trigger here</span>');
+ trigger(fragment.find('span'), 'mouseenter');
+
+ var ttipElement = fragment.find('div.tooltip');
+ expect(fragment).toHaveOpenTooltips();
+ expect(ttipElement).toHaveClass('left');
+
+ closeTooltip(fragment.find('span'));
+ expect(fragment).not.toHaveOpenTooltips();
+ });
+ });
+
+ describe('class', function() {
+ it('can specify a custom class', function() {
+ var fragment = compileTooltip('<span ' + html + ' tooltip-class="custom">Trigger here</span>');
+ trigger(fragment.find('span'), 'mouseenter');
+
+ var ttipElement = fragment.find('div.tooltip');
+ expect(fragment).toHaveOpenTooltips();
+ expect(ttipElement).toHaveClass('custom');
+
+ closeTooltip(fragment.find('span'));
+ expect(fragment).not.toHaveOpenTooltips();
+ });
+ });
+ });
+ });
+ });
+
+ it('should show even after close trigger is called multiple times - issue #1847', function() {
+ var fragment = compileTooltip('<span uib-tooltip="tooltip text">Trigger here</span>');
+
+ trigger(fragment.find('span'), 'mouseenter');
+ expect(fragment).toHaveOpenTooltips();
+
+ closeTooltip(fragment.find('span'), null, true);
+ // Close trigger is called again before timer completes
+ // The close trigger can be called any number of times (even after close has already been called)
+ // since users can trigger the hide triggers manually.
+ closeTooltip(fragment.find('span'), null, true);
+ expect(fragment).toHaveOpenTooltips();
+
+ trigger(fragment.find('span'), 'mouseenter');
+ expect(fragment).toHaveOpenTooltips();
+
+ $timeout.flush();
+ expect(fragment).toHaveOpenTooltips();
+ });
+
+ it('should hide even after show trigger is called multiple times', function() {
+ var fragment = compileTooltip('<span uib-tooltip="tooltip text" tooltip-popup-delay="1000">Trigger here</span>');
+
+ trigger(fragment.find('span'), 'mouseenter');
+ trigger(fragment.find('span'), 'mouseenter');
+
+ closeTooltip(fragment.find('span'));
+ expect(fragment).not.toHaveOpenTooltips();
+ });
+
+ it('should not show tooltips element is disabled (button) - issue #3167', function() {
+ var fragment = compileTooltip('<button uib-tooltip="cancel!" ng-disabled="disabled" ng-click="disabled = true">Cancel</button>');
+
+ trigger(fragment.find('button'), 'mouseenter');
+ expect(fragment).toHaveOpenTooltips();
+
+ trigger(fragment.find('button'), 'click');
+ $timeout.flush();
+ // One needs to flush deferred functions before checking there is no tooltip.
+ expect(fragment).not.toHaveOpenTooltips();
+ });
+});
+
+/* Deprecation tests below */
+
+describe('tooltip deprecation', function() {
+ beforeEach(module('ui.bootstrap.tooltip'));
+ beforeEach(module('template/tooltip/tooltip-popup.html'));
+ beforeEach(module('template/tooltip/tooltip-template-popup.html'));
+ beforeEach(module('template/tooltip/tooltip-html-popup.html'));
+
+ describe('tooltip', function() {
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$tooltipSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = '<div><span tooltip="tooltip text">Trigger here</span></div>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = '<div><span tooltip="tooltip text">Trigger here</span></div>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(1);
+ expect($log.warn.calls.argsFor(0)).toEqual(['$tooltip is now deprecated. Use $uibTooltip instead.']);
+ }));
+ });
+
+ describe('tooltip html', function() {
+ var elm, elmBody, elmScope, tooltipScope;
+
+ function trigger(element, evt) {
+ evt = new Event(evt);
+
+ element[0].dispatchEvent(evt);
+ element.scope().$$childTail.$digest();
+ }
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$tooltipSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope, $sce) {
+ spyOn($log, 'warn');
+
+ $rootScope.html = 'I say: <strong class="hello">Hello!</strong>';
+ $rootScope.safeHtml = $sce.trustAsHtml($rootScope.html);
+ elmBody = angular.element('<div><span tooltip-html="safeHtml">Selector Text</span></div>');
+ $compile(elmBody)($rootScope);
+ $rootScope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ trigger(elm, 'mouseenter');
+ tooltipScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope, $sce) {
+ spyOn($log, 'warn');
+
+ $rootScope.html = 'I say: <strong class="hello">Hello!</strong>';
+ $rootScope.safeHtml = $sce.trustAsHtml($rootScope.html);
+ elmBody = angular.element('<div><span tooltip-html="safeHtml">Selector Text</span></div>');
+ $compile(elmBody)($rootScope);
+ $rootScope.$digest();
+ elm = elmBody.find('span');
+ elmScope = elm.scope();
+ tooltipScope = elmScope.$$childTail;
+
+ trigger(elm, 'mouseenter');
+ tooltipScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(2);
+ expect($log.warn.calls.argsFor(0)).toEqual(['$tooltip is now deprecated. Use $uibTooltip instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['tooltip-html-popup is now deprecated. Use uib-tooltip-html-popup instead.']);
+ }));
+ });
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/tooltip.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/tooltip.js
new file mode 100644
index 0000000..cbc7e97
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/tooltip/tooltip.js
@@ -0,0 +1,833 @@
+/**
+ * The following features are still outstanding: animation as a
+ * function, placement as a function, inside, support for more triggers than
+ * just mouse enter/leave, html tooltips, and selector delegation.
+ */
+angular.module('ui.bootstrap.tooltip', ['ui.bootstrap.position', 'ui.bootstrap.stackedMap'])
+
+/**
+ * The $tooltip service creates tooltip- and popover-like directives as well as
+ * houses global options for them.
+ */
+.provider('$uibTooltip', function() {
+ // The default options tooltip and popover.
+ var defaultOptions = {
+ placement: 'top',
+ animation: true,
+ popupDelay: 0,
+ popupCloseDelay: 0,
+ useContentExp: false
+ };
+
+ // Default hide triggers for each show trigger
+ var triggerMap = {
+ 'mouseenter': 'mouseleave',
+ 'click': 'click',
+ 'focus': 'blur',
+ 'none': ''
+ };
+
+ // The options specified to the provider globally.
+ var globalOptions = {};
+
+ /**
+ * `options({})` allows global configuration of all tooltips in the
+ * application.
+ *
+ * var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) {
+ * // place tooltips left instead of top by default
+ * $tooltipProvider.options( { placement: 'left' } );
+ * });
+ */
+ this.options = function(value) {
+ angular.extend(globalOptions, value);
+ };
+
+ /**
+ * This allows you to extend the set of trigger mappings available. E.g.:
+ *
+ * $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' );
+ */
+ this.setTriggers = function setTriggers(triggers) {
+ angular.extend(triggerMap, triggers);
+ };
+
+ /**
+ * This is a helper function for translating camel-case to snake-case.
+ */
+ function snake_case(name) {
+ var regexp = /[A-Z]/g;
+ var separator = '-';
+ return name.replace(regexp, function(letter, pos) {
+ return (pos ? separator : '') + letter.toLowerCase();
+ });
+ }
+
+ /**
+ * Returns the actual instance of the $tooltip service.
+ * TODO support multiple triggers
+ */
+ this.$get = ['$window', '$compile', '$timeout', '$document', '$uibPosition', '$interpolate', '$rootScope', '$parse', '$$stackedMap', function($window, $compile, $timeout, $document, $position, $interpolate, $rootScope, $parse, $$stackedMap) {
+ var openedTooltips = $$stackedMap.createNew();
+ $document.on('keypress', function(e) {
+ if (e.which === 27) {
+ var last = openedTooltips.top();
+ if (last) {
+ last.value.close();
+ openedTooltips.removeTop();
+ last = null;
+ }
+ }
+ });
+
+ return function $tooltip(ttType, prefix, defaultTriggerShow, options) {
+ options = angular.extend({}, defaultOptions, globalOptions, options);
+
+ /**
+ * Returns an object of show and hide triggers.
+ *
+ * If a trigger is supplied,
+ * it is used to show the tooltip; otherwise, it will use the `trigger`
+ * option passed to the `$tooltipProvider.options` method; else it will
+ * default to the trigger supplied to this directive factory.
+ *
+ * The hide trigger is based on the show trigger. If the `trigger` option
+ * was passed to the `$tooltipProvider.options` method, it will use the
+ * mapped trigger from `triggerMap` or the passed trigger if the map is
+ * undefined; otherwise, it uses the `triggerMap` value of the show
+ * trigger; else it will just use the show trigger.
+ */
+ function getTriggers(trigger) {
+ var show = (trigger || options.trigger || defaultTriggerShow).split(' ');
+ var hide = show.map(function(trigger) {
+ return triggerMap[trigger] || trigger;
+ });
+ return {
+ show: show,
+ hide: hide
+ };
+ }
+
+ var directiveName = snake_case(ttType);
+
+ var startSym = $interpolate.startSymbol();
+ var endSym = $interpolate.endSymbol();
+ var template =
+ '<div '+ directiveName + '-popup '+
+ 'title="' + startSym + 'title' + endSym + '" '+
+ (options.useContentExp ?
+ 'content-exp="contentExp()" ' :
+ 'content="' + startSym + 'content' + endSym + '" ') +
+ 'placement="' + startSym + 'placement' + endSym + '" '+
+ 'popup-class="' + startSym + 'popupClass' + endSym + '" '+
+ 'animation="animation" ' +
+ 'is-open="isOpen"' +
+ 'origin-scope="origScope" ' +
+ 'style="visibility: hidden; display: block; top: -9999px; left: -9999px;"' +
+ '>' +
+ '</div>';
+
+ return {
+ compile: function(tElem, tAttrs) {
+ var tooltipLinker = $compile(template);
+
+ return function link(scope, element, attrs, tooltipCtrl) {
+ var tooltip;
+ var tooltipLinkedScope;
+ var transitionTimeout;
+ var showTimeout;
+ var hideTimeout;
+ var positionTimeout;
+ var appendToBody = angular.isDefined(options.appendToBody) ? options.appendToBody : false;
+ var triggers = getTriggers(undefined);
+ var hasEnableExp = angular.isDefined(attrs[prefix + 'Enable']);
+ var ttScope = scope.$new(true);
+ var repositionScheduled = false;
+ var isOpenParse = angular.isDefined(attrs[prefix + 'IsOpen']) ? $parse(attrs[prefix + 'IsOpen']) : false;
+ var contentParse = options.useContentExp ? $parse(attrs[ttType]) : false;
+ var observers = [];
+
+ var positionTooltip = function() {
+ // check if tooltip exists and is not empty
+ if (!tooltip || !tooltip.html()) { return; }
+
+ if (!positionTimeout) {
+ positionTimeout = $timeout(function() {
+ // Reset the positioning.
+ tooltip.css({ top: 0, left: 0 });
+
+ // Now set the calculated positioning.
+ var ttCss = $position.positionElements(element, tooltip, ttScope.placement, appendToBody);
+ ttCss.top += 'px';
+ ttCss.left += 'px';
+ ttCss.visibility = 'visible';
+ tooltip.css(ttCss);
+
+ positionTimeout = null;
+ }, 0, false);
+ }
+ };
+
+ // Set up the correct scope to allow transclusion later
+ ttScope.origScope = scope;
+
+ // By default, the tooltip is not open.
+ // TODO add ability to start tooltip opened
+ ttScope.isOpen = false;
+ openedTooltips.add(ttScope, {
+ close: hide
+ });
+
+ function toggleTooltipBind() {
+ if (!ttScope.isOpen) {
+ showTooltipBind();
+ } else {
+ hideTooltipBind();
+ }
+ }
+
+ // Show the tooltip with delay if specified, otherwise show it immediately
+ function showTooltipBind() {
+ if (hasEnableExp && !scope.$eval(attrs[prefix + 'Enable'])) {
+ return;
+ }
+
+ cancelHide();
+ prepareTooltip();
+
+ if (ttScope.popupDelay) {
+ // Do nothing if the tooltip was already scheduled to pop-up.
+ // This happens if show is triggered multiple times before any hide is triggered.
+ if (!showTimeout) {
+ showTimeout = $timeout(show, ttScope.popupDelay, false);
+ }
+ } else {
+ show();
+ }
+ }
+
+ function hideTooltipBind() {
+ cancelShow();
+
+ if (ttScope.popupCloseDelay) {
+ if (!hideTimeout) {
+ hideTimeout = $timeout(hide, ttScope.popupCloseDelay, false);
+ }
+ } else {
+ hide();
+ }
+ }
+
+ // Show the tooltip popup element.
+ function show() {
+ cancelShow();
+ cancelHide();
+
+ // Don't show empty tooltips.
+ if (!ttScope.content) {
+ return angular.noop;
+ }
+
+ createTooltip();
+
+ // And show the tooltip.
+ ttScope.$evalAsync(function() {
+ ttScope.isOpen = true;
+ assignIsOpen(true);
+ positionTooltip();
+ });
+ }
+
+ function cancelShow() {
+ if (showTimeout) {
+ $timeout.cancel(showTimeout);
+ showTimeout = null;
+ }
+
+ if (positionTimeout) {
+ $timeout.cancel(positionTimeout);
+ positionTimeout = null;
+ }
+ }
+
+ // Hide the tooltip popup element.
+ function hide() {
+ cancelShow();
+ cancelHide();
+
+ if (!ttScope) {
+ return;
+ }
+
+ // First things first: we don't show it anymore.
+ ttScope.$evalAsync(function() {
+ ttScope.isOpen = false;
+ assignIsOpen(false);
+ // And now we remove it from the DOM. However, if we have animation, we
+ // need to wait for it to expire beforehand.
+ // FIXME: this is a placeholder for a port of the transitions library.
+ // The fade transition in TWBS is 150ms.
+ if (ttScope.animation) {
+ if (!transitionTimeout) {
+ transitionTimeout = $timeout(removeTooltip, 150, false);
+ }
+ } else {
+ removeTooltip();
+ }
+ });
+ }
+
+ function cancelHide() {
+ if (hideTimeout) {
+ $timeout.cancel(hideTimeout);
+ hideTimeout = null;
+ }
+ if (transitionTimeout) {
+ $timeout.cancel(transitionTimeout);
+ transitionTimeout = null;
+ }
+ }
+
+ function createTooltip() {
+ // There can only be one tooltip element per directive shown at once.
+ if (tooltip) {
+ return;
+ }
+
+ tooltipLinkedScope = ttScope.$new();
+ tooltip = tooltipLinker(tooltipLinkedScope, function(tooltip) {
+ if (appendToBody) {
+ $document.find('body').append(tooltip);
+ } else {
+ element.after(tooltip);
+ }
+ });
+
+ prepObservers();
+ }
+
+ function removeTooltip() {
+ unregisterObservers();
+
+ transitionTimeout = null;
+ if (tooltip) {
+ tooltip.remove();
+ tooltip = null;
+ }
+ if (tooltipLinkedScope) {
+ tooltipLinkedScope.$destroy();
+ tooltipLinkedScope = null;
+ }
+ }
+
+ /**
+ * Set the inital scope values. Once
+ * the tooltip is created, the observers
+ * will be added to keep things in synch.
+ */
+ function prepareTooltip() {
+ ttScope.title = attrs[prefix + 'Title'];
+ if (contentParse) {
+ ttScope.content = contentParse(scope);
+ } else {
+ ttScope.content = attrs[ttType];
+ }
+
+ ttScope.popupClass = attrs[prefix + 'Class'];
+ ttScope.placement = angular.isDefined(attrs[prefix + 'Placement']) ? attrs[prefix + 'Placement'] : options.placement;
+
+ var delay = parseInt(attrs[prefix + 'PopupDelay'], 10);
+ var closeDelay = parseInt(attrs[prefix + 'PopupCloseDelay'], 10);
+ ttScope.popupDelay = !isNaN(delay) ? delay : options.popupDelay;
+ ttScope.popupCloseDelay = !isNaN(closeDelay) ? closeDelay : options.popupCloseDelay;
+ }
+
+ function assignIsOpen(isOpen) {
+ if (isOpenParse && angular.isFunction(isOpenParse.assign)) {
+ isOpenParse.assign(scope, isOpen);
+ }
+ }
+
+ ttScope.contentExp = function() {
+ return ttScope.content;
+ };
+
+ /**
+ * Observe the relevant attributes.
+ */
+ attrs.$observe('disabled', function(val) {
+ if (val) {
+ cancelShow();
+ }
+
+ if (val && ttScope.isOpen) {
+ hide();
+ }
+ });
+
+ if (isOpenParse) {
+ scope.$watch(isOpenParse, function(val) {
+ /*jshint -W018 */
+ if (ttScope && !val === ttScope.isOpen) {
+ toggleTooltipBind();
+ }
+ /*jshint +W018 */
+ });
+ }
+
+ function prepObservers() {
+ observers.length = 0;
+
+ if (contentParse) {
+ observers.push(
+ scope.$watch(contentParse, function(val) {
+ ttScope.content = val;
+ if (!val && ttScope.isOpen) {
+ hide();
+ }
+ })
+ );
+
+ observers.push(
+ tooltipLinkedScope.$watch(function() {
+ if (!repositionScheduled) {
+ repositionScheduled = true;
+ tooltipLinkedScope.$$postDigest(function() {
+ repositionScheduled = false;
+ if (ttScope && ttScope.isOpen) {
+ positionTooltip();
+ }
+ });
+ }
+ })
+ );
+ } else {
+ observers.push(
+ attrs.$observe(ttType, function(val) {
+ ttScope.content = val;
+ if (!val && ttScope.isOpen) {
+ hide();
+ } else {
+ positionTooltip();
+ }
+ })
+ );
+ }
+
+ observers.push(
+ attrs.$observe(prefix + 'Title', function(val) {
+ ttScope.title = val;
+ if (ttScope.isOpen) {
+ positionTooltip();
+ }
+ })
+ );
+
+ observers.push(
+ attrs.$observe(prefix + 'Placement', function(val) {
+ ttScope.placement = val ? val : options.placement;
+ if (ttScope.isOpen) {
+ positionTooltip();
+ }
+ })
+ );
+ }
+
+ function unregisterObservers() {
+ if (observers.length) {
+ angular.forEach(observers, function(observer) {
+ observer();
+ });
+ observers.length = 0;
+ }
+ }
+
+ var unregisterTriggers = function() {
+ triggers.show.forEach(function(trigger) {
+ element.unbind(trigger, showTooltipBind);
+ });
+ triggers.hide.forEach(function(trigger) {
+ trigger.split(' ').forEach(function(hideTrigger) {
+ element[0].removeEventListener(hideTrigger, hideTooltipBind);
+ });
+ });
+ };
+
+ function prepTriggers() {
+ var val = attrs[prefix + 'Trigger'];
+ unregisterTriggers();
+
+ triggers = getTriggers(val);
+
+ if (triggers.show !== 'none') {
+ triggers.show.forEach(function(trigger, idx) {
+ // Using raw addEventListener due to jqLite/jQuery bug - #4060
+ if (trigger === triggers.hide[idx]) {
+ element[0].addEventListener(trigger, toggleTooltipBind);
+ } else if (trigger) {
+ element[0].addEventListener(trigger, showTooltipBind);
+ triggers.hide[idx].split(' ').forEach(function(trigger) {
+ element[0].addEventListener(trigger, hideTooltipBind);
+ });
+ }
+
+ element.on('keypress', function(e) {
+ if (e.which === 27) {
+ hideTooltipBind();
+ }
+ });
+ });
+ }
+ }
+
+ prepTriggers();
+
+ var animation = scope.$eval(attrs[prefix + 'Animation']);
+ ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation;
+
+ var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']);
+ appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody;
+
+ // if a tooltip is attached to <body> we need to remove it on
+ // location change as its parent scope will probably not be destroyed
+ // by the change.
+ if (appendToBody) {
+ scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess() {
+ if (ttScope.isOpen) {
+ hide();
+ }
+ });
+ }
+
+ // Make sure tooltip is destroyed and removed.
+ scope.$on('$destroy', function onDestroyTooltip() {
+ cancelShow();
+ cancelHide();
+ unregisterTriggers();
+ removeTooltip();
+ openedTooltips.remove(ttScope);
+ ttScope = null;
+ });
+ };
+ }
+ };
+ };
+ }];
+})
+
+// This is mostly ngInclude code but with a custom scope
+.directive('uibTooltipTemplateTransclude', [
+ '$animate', '$sce', '$compile', '$templateRequest',
+function ($animate , $sce , $compile , $templateRequest) {
+ return {
+ link: function(scope, elem, attrs) {
+ var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope);
+
+ var changeCounter = 0,
+ currentScope,
+ previousElement,
+ currentElement;
+
+ var cleanupLastIncludeContent = function() {
+ if (previousElement) {
+ previousElement.remove();
+ previousElement = null;
+ }
+
+ if (currentScope) {
+ currentScope.$destroy();
+ currentScope = null;
+ }
+
+ if (currentElement) {
+ $animate.leave(currentElement).then(function() {
+ previousElement = null;
+ });
+ previousElement = currentElement;
+ currentElement = null;
+ }
+ };
+
+ scope.$watch($sce.parseAsResourceUrl(attrs.uibTooltipTemplateTransclude), function(src) {
+ var thisChangeId = ++changeCounter;
+
+ if (src) {
+ //set the 2nd param to true to ignore the template request error so that the inner
+ //contents and scope can be cleaned up.
+ $templateRequest(src, true).then(function(response) {
+ if (thisChangeId !== changeCounter) { return; }
+ var newScope = origScope.$new();
+ var template = response;
+
+ var clone = $compile(template)(newScope, function(clone) {
+ cleanupLastIncludeContent();
+ $animate.enter(clone, elem);
+ });
+
+ currentScope = newScope;
+ currentElement = clone;
+
+ currentScope.$emit('$includeContentLoaded', src);
+ }, function() {
+ if (thisChangeId === changeCounter) {
+ cleanupLastIncludeContent();
+ scope.$emit('$includeContentError', src);
+ }
+ });
+ scope.$emit('$includeContentRequested', src);
+ } else {
+ cleanupLastIncludeContent();
+ }
+ });
+
+ scope.$on('$destroy', cleanupLastIncludeContent);
+ }
+ };
+}])
+
+/**
+ * Note that it's intentional that these classes are *not* applied through $animate.
+ * They must not be animated as they're expected to be present on the tooltip on
+ * initialization.
+ */
+.directive('uibTooltipClasses', function() {
+ return {
+ restrict: 'A',
+ link: function(scope, element, attrs) {
+ if (scope.placement) {
+ element.addClass(scope.placement);
+ }
+
+ if (scope.popupClass) {
+ element.addClass(scope.popupClass);
+ }
+
+ if (scope.animation()) {
+ element.addClass(attrs.tooltipAnimationClass);
+ }
+ }
+ };
+})
+
+.directive('uibTooltipPopup', function() {
+ return {
+ replace: true,
+ scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
+ templateUrl: 'template/tooltip/tooltip-popup.html',
+ link: function(scope, element) {
+ element.addClass('tooltip');
+ }
+ };
+})
+
+.directive('uibTooltip', [ '$uibTooltip', function($uibTooltip) {
+ return $uibTooltip('uibTooltip', 'tooltip', 'mouseenter');
+}])
+
+.directive('uibTooltipTemplatePopup', function() {
+ return {
+ replace: true,
+ scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&',
+ originScope: '&' },
+ templateUrl: 'template/tooltip/tooltip-template-popup.html',
+ link: function(scope, element) {
+ element.addClass('tooltip');
+ }
+ };
+})
+
+.directive('uibTooltipTemplate', ['$uibTooltip', function($uibTooltip) {
+ return $uibTooltip('uibTooltipTemplate', 'tooltip', 'mouseenter', {
+ useContentExp: true
+ });
+}])
+
+.directive('uibTooltipHtmlPopup', function() {
+ return {
+ replace: true,
+ scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
+ templateUrl: 'template/tooltip/tooltip-html-popup.html',
+ link: function(scope, element) {
+ element.addClass('tooltip');
+ }
+ };
+})
+
+.directive('uibTooltipHtml', ['$uibTooltip', function($uibTooltip) {
+ return $uibTooltip('uibTooltipHtml', 'tooltip', 'mouseenter', {
+ useContentExp: true
+ });
+}]);
+
+/* Deprecated tooltip below */
+
+angular.module('ui.bootstrap.tooltip')
+
+.value('$tooltipSuppressWarning', false)
+
+.provider('$tooltip', ['$uibTooltipProvider', function($uibTooltipProvider) {
+ angular.extend(this, $uibTooltipProvider);
+
+ this.$get = ['$log', '$tooltipSuppressWarning', '$injector', function($log, $tooltipSuppressWarning, $injector) {
+ if (!$tooltipSuppressWarning) {
+ $log.warn('$tooltip is now deprecated. Use $uibTooltip instead.');
+ }
+
+ return $injector.invoke($uibTooltipProvider.$get);
+ }];
+}])
+
+// This is mostly ngInclude code but with a custom scope
+.directive('tooltipTemplateTransclude', [
+ '$animate', '$sce', '$compile', '$templateRequest', '$log', '$tooltipSuppressWarning',
+function ($animate , $sce , $compile , $templateRequest, $log, $tooltipSuppressWarning) {
+ return {
+ link: function(scope, elem, attrs) {
+ if (!$tooltipSuppressWarning) {
+ $log.warn('tooltip-template-transclude is now deprecated. Use uib-tooltip-template-transclude instead.');
+ }
+
+ var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope);
+
+ var changeCounter = 0,
+ currentScope,
+ previousElement,
+ currentElement;
+
+ var cleanupLastIncludeContent = function() {
+ if (previousElement) {
+ previousElement.remove();
+ previousElement = null;
+ }
+ if (currentScope) {
+ currentScope.$destroy();
+ currentScope = null;
+ }
+ if (currentElement) {
+ $animate.leave(currentElement).then(function() {
+ previousElement = null;
+ });
+ previousElement = currentElement;
+ currentElement = null;
+ }
+ };
+
+ scope.$watch($sce.parseAsResourceUrl(attrs.tooltipTemplateTransclude), function(src) {
+ var thisChangeId = ++changeCounter;
+
+ if (src) {
+ //set the 2nd param to true to ignore the template request error so that the inner
+ //contents and scope can be cleaned up.
+ $templateRequest(src, true).then(function(response) {
+ if (thisChangeId !== changeCounter) { return; }
+ var newScope = origScope.$new();
+ var template = response;
+
+ var clone = $compile(template)(newScope, function(clone) {
+ cleanupLastIncludeContent();
+ $animate.enter(clone, elem);
+ });
+
+ currentScope = newScope;
+ currentElement = clone;
+
+ currentScope.$emit('$includeContentLoaded', src);
+ }, function() {
+ if (thisChangeId === changeCounter) {
+ cleanupLastIncludeContent();
+ scope.$emit('$includeContentError', src);
+ }
+ });
+ scope.$emit('$includeContentRequested', src);
+ } else {
+ cleanupLastIncludeContent();
+ }
+ });
+
+ scope.$on('$destroy', cleanupLastIncludeContent);
+ }
+ };
+}])
+
+.directive('tooltipClasses', ['$log', '$tooltipSuppressWarning', function($log, $tooltipSuppressWarning) {
+ return {
+ restrict: 'A',
+ link: function(scope, element, attrs) {
+ if (!$tooltipSuppressWarning) {
+ $log.warn('tooltip-classes is now deprecated. Use uib-tooltip-classes instead.');
+ }
+
+ if (scope.placement) {
+ element.addClass(scope.placement);
+ }
+ if (scope.popupClass) {
+ element.addClass(scope.popupClass);
+ }
+ if (scope.animation()) {
+ element.addClass(attrs.tooltipAnimationClass);
+ }
+ }
+ };
+}])
+
+.directive('tooltipPopup', ['$log', '$tooltipSuppressWarning', function($log, $tooltipSuppressWarning) {
+ return {
+ replace: true,
+ scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
+ templateUrl: 'template/tooltip/tooltip-popup.html',
+ link: function(scope, element) {
+ if (!$tooltipSuppressWarning) {
+ $log.warn('tooltip-popup is now deprecated. Use uib-tooltip-popup instead.');
+ }
+
+ element.addClass('tooltip');
+ }
+ };
+}])
+
+.directive('tooltip', ['$tooltip', function($tooltip) {
+ return $tooltip('tooltip', 'tooltip', 'mouseenter');
+}])
+
+.directive('tooltipTemplatePopup', ['$log', '$tooltipSuppressWarning', function($log, $tooltipSuppressWarning) {
+ return {
+ replace: true,
+ scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&',
+ originScope: '&' },
+ templateUrl: 'template/tooltip/tooltip-template-popup.html',
+ link: function(scope, element) {
+ if (!$tooltipSuppressWarning) {
+ $log.warn('tooltip-template-popup is now deprecated. Use uib-tooltip-template-popup instead.');
+ }
+
+ element.addClass('tooltip');
+ }
+ };
+}])
+
+.directive('tooltipTemplate', ['$tooltip', function($tooltip) {
+ return $tooltip('tooltipTemplate', 'tooltip', 'mouseenter', {
+ useContentExp: true
+ });
+}])
+
+.directive('tooltipHtmlPopup', ['$log', '$tooltipSuppressWarning', function($log, $tooltipSuppressWarning) {
+ return {
+ replace: true,
+ scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
+ templateUrl: 'template/tooltip/tooltip-html-popup.html',
+ link: function(scope, element) {
+ if (!$tooltipSuppressWarning) {
+ $log.warn('tooltip-html-popup is now deprecated. Use uib-tooltip-html-popup instead.');
+ }
+
+ element.addClass('tooltip');
+ }
+ };
+}])
+
+.directive('tooltipHtml', ['$tooltip', function($tooltip) {
+ return $tooltip('tooltipHtml', 'tooltip', 'mouseenter', {
+ useContentExp: true
+ });
+}]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/docs/demo.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/docs/demo.html
new file mode 100644
index 0000000..ff4dea9
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/docs/demo.html
@@ -0,0 +1,74 @@
+<style>
+ .typeahead-demo .custom-popup-wrapper {
+ position: absolute;
+ top: 100%;
+ left: 0;
+ z-index: 1000;
+ display: none;
+ background-color: #f9f9f9;
+ }
+
+ .typeahead-demo .custom-popup-wrapper > .message {
+ padding: 10px 20px;
+ border-bottom: 1px solid #ddd;
+ color: #868686;
+ }
+
+ .typeahead-demo .custom-popup-wrapper > .dropdown-menu {
+ position: static;
+ float: none;
+ display: block;
+ min-width: 160px;
+ background-color: transparent;
+ border: none;
+ border-radius: 0;
+ box-shadow: none;
+ }
+</style>
+
+<script type="text/ng-template" id="customTemplate.html">
+ <a>
+ <img ng-src="http://upload.wikimedia.org/wikipedia/commons/thumb/{{match.model.flag}}" width="16">
+ <span ng-bind-html="match.label | uibTypeaheadHighlight:query"></span>
+ </a>
+</script>
+
+<script type="text/ng-template" id="customPopupTemplate.html">
+ <div class="custom-popup-wrapper"
+ ng-style="{top: position().top+'px', left: position().left+'px'}"
+ style="display: block;"
+ ng-show="isOpen() && !moveInProgress"
+ aria-hidden="{{!isOpen()}}">
+ <p class="message">select location from drop down.</p>
+
+ <ul class="dropdown-menu" role="listbox">
+ <li ng-repeat="match in matches track by $index" ng-class="{active: isActive($index) }"
+ ng-mouseenter="selectActive($index)" ng-click="selectMatch($index)" role="option" id="{{::match.id}}">
+ <div uib-typeahead-match index="$index" match="match" query="query" template-url="templateUrl"></div>
+ </li>
+ </ul>
+ </div>
+</script>
+
+<div class='container-fluid typeahead-demo' ng-controller="TypeaheadCtrl">
+
+ <h4>Static arrays</h4>
+ <pre>Model: {{selected | json}}</pre>
+ <input type="text" ng-model="selected" uib-typeahead="state for state in states | filter:$viewValue | limitTo:8" class="form-control">
+
+ <h4>Asynchronous results</h4>
+ <pre>Model: {{asyncSelected | json}}</pre>
+ <input type="text" ng-model="asyncSelected" placeholder="Locations loaded via $http" uib-typeahead="address for address in getLocation($viewValue)" typeahead-loading="loadingLocations" typeahead-no-results="noResults" class="form-control">
+ <i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>
+ <div ng-show="noResults">
+ <i class="glyphicon glyphicon-remove"></i> No Results Found
+ </div>
+
+ <h4>Custom templates for results</h4>
+ <pre>Model: {{customSelected | json}}</pre>
+ <input type="text" ng-model="customSelected" placeholder="Custom template" uib-typeahead="state as state.name for state in statesWithFlags | filter:{name:$viewValue}" typeahead-template-url="customTemplate.html" class="form-control">
+
+ <h4>Custom popup templates for typeahead's dropdown</h4>
+ <pre>Model: {{customPopupSelected | json}}</pre>
+ <input type="text" ng-model="customPopupSelected" placeholder="Custom popup template" uib-typeahead="state as state.name for state in statesWithFlags | filter:{name:$viewValue}" typeahead-popup-template-url="customPopupTemplate.html" class="form-control">
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/docs/demo.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/docs/demo.js
new file mode 100644
index 0000000..0148ec4
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/docs/demo.js
@@ -0,0 +1,20 @@
+angular.module('ui.bootstrap.demo').controller('TypeaheadCtrl', function($scope, $http) {
+
+ $scope.selected = undefined;
+ $scope.states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Dakota', 'North Carolina', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];
+ // Any function returning a promise object can be used to load values asynchronously
+ $scope.getLocation = function(val) {
+ return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
+ params: {
+ address: val,
+ sensor: false
+ }
+ }).then(function(response){
+ return response.data.results.map(function(item){
+ return item.formatted_address;
+ });
+ });
+ };
+
+ $scope.statesWithFlags = [{'name':'Alabama','flag':'5/5c/Flag_of_Alabama.svg/45px-Flag_of_Alabama.svg.png'},{'name':'Alaska','flag':'e/e6/Flag_of_Alaska.svg/43px-Flag_of_Alaska.svg.png'},{'name':'Arizona','flag':'9/9d/Flag_of_Arizona.svg/45px-Flag_of_Arizona.svg.png'},{'name':'Arkansas','flag':'9/9d/Flag_of_Arkansas.svg/45px-Flag_of_Arkansas.svg.png'},{'name':'California','flag':'0/01/Flag_of_California.svg/45px-Flag_of_California.svg.png'},{'name':'Colorado','flag':'4/46/Flag_of_Colorado.svg/45px-Flag_of_Colorado.svg.png'},{'name':'Connecticut','flag':'9/96/Flag_of_Connecticut.svg/39px-Flag_of_Connecticut.svg.png'},{'name':'Delaware','flag':'c/c6/Flag_of_Delaware.svg/45px-Flag_of_Delaware.svg.png'},{'name':'Florida','flag':'f/f7/Flag_of_Florida.svg/45px-Flag_of_Florida.svg.png'},{'name':'Georgia','flag':'5/54/Flag_of_Georgia_%28U.S._state%29.svg/46px-Flag_of_Georgia_%28U.S._state%29.svg.png'},{'name':'Hawaii','flag':'e/ef/Flag_of_Hawaii.svg/46px-Flag_of_Hawaii.svg.png'},{'name':'Idaho','flag':'a/a4/Flag_of_Idaho.svg/38px-Flag_of_Idaho.svg.png'},{'name':'Illinois','flag':'0/01/Flag_of_Illinois.svg/46px-Flag_of_Illinois.svg.png'},{'name':'Indiana','flag':'a/ac/Flag_of_Indiana.svg/45px-Flag_of_Indiana.svg.png'},{'name':'Iowa','flag':'a/aa/Flag_of_Iowa.svg/44px-Flag_of_Iowa.svg.png'},{'name':'Kansas','flag':'d/da/Flag_of_Kansas.svg/46px-Flag_of_Kansas.svg.png'},{'name':'Kentucky','flag':'8/8d/Flag_of_Kentucky.svg/46px-Flag_of_Kentucky.svg.png'},{'name':'Louisiana','flag':'e/e0/Flag_of_Louisiana.svg/46px-Flag_of_Louisiana.svg.png'},{'name':'Maine','flag':'3/35/Flag_of_Maine.svg/45px-Flag_of_Maine.svg.png'},{'name':'Maryland','flag':'a/a0/Flag_of_Maryland.svg/45px-Flag_of_Maryland.svg.png'},{'name':'Massachusetts','flag':'f/f2/Flag_of_Massachusetts.svg/46px-Flag_of_Massachusetts.svg.png'},{'name':'Michigan','flag':'b/b5/Flag_of_Michigan.svg/45px-Flag_of_Michigan.svg.png'},{'name':'Minnesota','flag':'b/b9/Flag_of_Minnesota.svg/46px-Flag_of_Minnesota.svg.png'},{'name':'Mississippi','flag':'4/42/Flag_of_Mississippi.svg/45px-Flag_of_Mississippi.svg.png'},{'name':'Missouri','flag':'5/5a/Flag_of_Missouri.svg/46px-Flag_of_Missouri.svg.png'},{'name':'Montana','flag':'c/cb/Flag_of_Montana.svg/45px-Flag_of_Montana.svg.png'},{'name':'Nebraska','flag':'4/4d/Flag_of_Nebraska.svg/46px-Flag_of_Nebraska.svg.png'},{'name':'Nevada','flag':'f/f1/Flag_of_Nevada.svg/45px-Flag_of_Nevada.svg.png'},{'name':'New Hampshire','flag':'2/28/Flag_of_New_Hampshire.svg/45px-Flag_of_New_Hampshire.svg.png'},{'name':'New Jersey','flag':'9/92/Flag_of_New_Jersey.svg/45px-Flag_of_New_Jersey.svg.png'},{'name':'New Mexico','flag':'c/c3/Flag_of_New_Mexico.svg/45px-Flag_of_New_Mexico.svg.png'},{'name':'New York','flag':'1/1a/Flag_of_New_York.svg/46px-Flag_of_New_York.svg.png'},{'name':'North Carolina','flag':'b/bb/Flag_of_North_Carolina.svg/45px-Flag_of_North_Carolina.svg.png'},{'name':'North Dakota','flag':'e/ee/Flag_of_North_Dakota.svg/38px-Flag_of_North_Dakota.svg.png'},{'name':'Ohio','flag':'4/4c/Flag_of_Ohio.svg/46px-Flag_of_Ohio.svg.png'},{'name':'Oklahoma','flag':'6/6e/Flag_of_Oklahoma.svg/45px-Flag_of_Oklahoma.svg.png'},{'name':'Oregon','flag':'b/b9/Flag_of_Oregon.svg/46px-Flag_of_Oregon.svg.png'},{'name':'Pennsylvania','flag':'f/f7/Flag_of_Pennsylvania.svg/45px-Flag_of_Pennsylvania.svg.png'},{'name':'Rhode Island','flag':'f/f3/Flag_of_Rhode_Island.svg/32px-Flag_of_Rhode_Island.svg.png'},{'name':'South Carolina','flag':'6/69/Flag_of_South_Carolina.svg/45px-Flag_of_South_Carolina.svg.png'},{'name':'South Dakota','flag':'1/1a/Flag_of_South_Dakota.svg/46px-Flag_of_South_Dakota.svg.png'},{'name':'Tennessee','flag':'9/9e/Flag_of_Tennessee.svg/46px-Flag_of_Tennessee.svg.png'},{'name':'Texas','flag':'f/f7/Flag_of_Texas.svg/45px-Flag_of_Texas.svg.png'},{'name':'Utah','flag':'f/f6/Flag_of_Utah.svg/45px-Flag_of_Utah.svg.png'},{'name':'Vermont','flag':'4/49/Flag_of_Vermont.svg/46px-Flag_of_Vermont.svg.png'},{'name':'Virginia','flag':'4/47/Flag_of_Virginia.svg/44px-Flag_of_Virginia.svg.png'},{'name':'Washington','flag':'5/54/Flag_of_Washington.svg/46px-Flag_of_Washington.svg.png'},{'name':'West Virginia','flag':'2/22/Flag_of_West_Virginia.svg/46px-Flag_of_West_Virginia.svg.png'},{'name':'Wisconsin','flag':'2/22/Flag_of_Wisconsin.svg/45px-Flag_of_Wisconsin.svg.png'},{'name':'Wyoming','flag':'b/bc/Flag_of_Wyoming.svg/43px-Flag_of_Wyoming.svg.png'}];
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/docs/readme.md b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/docs/readme.md
new file mode 100644
index 0000000..e5539fd
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/docs/readme.md
@@ -0,0 +1,80 @@
+Typeahead is a AngularJS version of [Bootstrap v2's typeahead plugin](http://getbootstrap.com/2.3.2/javascript.html#typeahead).
+This directive can be used to quickly create elegant typeaheads with any form text input.
+
+It is very well integrated into AngularJS as it uses a subset of the
+[select directive](http://docs.angularjs.org/api/ng.directive:select) syntax, which is very flexible. Supported expressions are:
+
+* _label_ for _value_ in _sourceArray_
+* _select_ as _label_ for _value_ in _sourceArray_
+
+The `sourceArray` expression can use a special `$viewValue` variable that corresponds to the value entered inside the input.
+
+This directive works with promises, meaning you can retrieve matches using the `$http` service with minimal effort.
+
+The typeahead directives provide several attributes:
+
+* `ng-model` <i class="glyphicon glyphicon-eye-open"></i>
+ :
+ Assignable angular expression to data-bind to
+
+* `typeahead` <i class="glyphicon glyphicon-eye-open"></i>
+ :
+ Comprehension Angular expression (see [select directive](http://docs.angularjs.org/api/ng.directive:select))
+
+* `typeahead-append-to-body` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: false)_ : Should the typeahead popup be appended to $body instead of the parent element?
+
+* `typeahead-append-to-element-id`
+ _(Defaults: false)_ : Should the typeahead popup be appended to an element id instead of the parent element?
+
+* `typeahead-editable`
+ _(Defaults: true)_ :
+ Should it restrict model values to the ones selected from the popup only ?
+
+* `typeahead-focus-first`
+ _(Defaults: true)_ :
+ Should the first match automatically be focused as you type?
+
+* `typeahead-input-formatter` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: undefined)_ :
+ Format the ng-model result after selection
+
+* `typeahead-loading` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: angular.noop)_ :
+ Binding to a variable that indicates if matches are being retrieved asynchronously
+
+* `typeahead-min-length` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: 1)_ :
+ Minimal no of characters that needs to be entered before typeahead kicks-in. Must be greater than or equal to 1.
+
+* `typeahead-no-results` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: angular.noop)_ :
+ Binding to a variable that indicates if no matching results were found
+
+* `typeahead-on-select($item, $model, $label)`
+ _(Defaults: null)_ :
+ A callback executed when a match is selected
+
+* `typeahead-select-on-exact`
+ _(Defaults: false)_ :
+ Should it automatically select an item when there is one option that exactly matches the user input?
+
+* `typeahead-template-url` <i class="glyphicon glyphicon-eye-open"></i>
+ :
+ Set custom item template
+
+* `typeahead-popup-template-url`
+ _(Defaults: `template/typeahead/typeahead-popup.html`)_ :
+ Set custom popup template
+
+* `typeahead-wait-ms` <i class="glyphicon glyphicon-eye-open"></i>
+ _(Defaults: 0)_ :
+ Minimal wait time after last character typed before typeahead kicks-in
+
+* `typeahead-select-on-blur`
+ _(Defaults: false)_ :
+ On blur, select the currently highlighted match
+
+* `typeahead-focus-on-select`
+ _(Defaults: true) :
+ On selection, focus the input element the typeahead directive is associated with
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead-highlight-ngsanitize.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead-highlight-ngsanitize.spec.js
new file mode 100644
index 0000000..de24319
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead-highlight-ngsanitize.spec.js
@@ -0,0 +1,16 @@
+describe('Security concerns', function() {
+ var highlightFilter, $sanitize, logSpy;
+
+ beforeEach(module('ui.bootstrap.typeahead', 'ngSanitize'));
+
+ beforeEach(inject(function (uibTypeaheadHighlightFilter, _$sanitize_, $log) {
+ highlightFilter = uibTypeaheadHighlightFilter;
+ $sanitize = _$sanitize_;
+ logSpy = spyOn($log, 'warn');
+ }));
+
+ it('should not call the $log service when ngSanitize is present', function() {
+ highlightFilter('before <script src="">match</script> after', 'match');
+ expect(logSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead-highlight.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead-highlight.spec.js
new file mode 100644
index 0000000..c696587
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead-highlight.spec.js
@@ -0,0 +1,80 @@
+describe('typeaheadHighlight', function () {
+
+ var highlightFilter, $log, $sce, logSpy;
+
+ beforeEach(module('ui.bootstrap.typeahead'));
+
+ beforeEach(inject(function(_$log_, _$sce_) {
+ $log = _$log_;
+ $sce = _$sce_;
+ logSpy = spyOn($log, 'warn');
+ }));
+
+ beforeEach(inject(function(uibTypeaheadHighlightFilter) {
+ highlightFilter = uibTypeaheadHighlightFilter;
+ }));
+
+ it('should higlight a match', function() {
+ expect($sce.getTrustedHtml(highlightFilter('before match after', 'match'))).toEqual('before <strong>match</strong> after');
+ });
+
+ it('should higlight a match with mixed case', function() {
+ expect($sce.getTrustedHtml(highlightFilter('before MaTch after', 'match'))).toEqual('before <strong>MaTch</strong> after');
+ });
+
+ it('should higlight all matches', function() {
+ expect($sce.getTrustedHtml(highlightFilter('before MaTch after match', 'match'))).toEqual('before <strong>MaTch</strong> after <strong>match</strong>');
+ });
+
+ it('should do nothing if no match', function() {
+ expect($sce.getTrustedHtml(highlightFilter('before match after', 'nomatch'))).toEqual('before match after');
+ });
+
+ it('should do nothing if no or empty query', function() {
+ expect($sce.getTrustedHtml(highlightFilter('before match after', ''))).toEqual('before match after');
+ expect($sce.getTrustedHtml(highlightFilter('before match after', null))).toEqual('before match after');
+ expect($sce.getTrustedHtml(highlightFilter('before match after', undefined))).toEqual('before match after');
+ });
+
+ it('issue 316 - should work correctly for regexp reserved words', function() {
+ expect($sce.getTrustedHtml(highlightFilter('before (match after', '(match'))).toEqual('before <strong>(match</strong> after');
+ });
+
+ it('issue 1777 - should work correctly with numeric values', function() {
+ expect($sce.getTrustedHtml(highlightFilter(123, '2'))).toEqual('1<strong>2</strong>3');
+ });
+
+ it('should show a warning when this component is being used unsafely', function() {
+ highlightFilter('<i>before</i> match after', 'match');
+ expect(logSpy).toHaveBeenCalled();
+ });
+});
+
+/* Deprecation tests below */
+
+describe('typeahead highlightFilter deprecated', function(){
+ var highlightFilter, $log, $sce, logSpy;
+
+ beforeEach(module('ui.bootstrap.typeahead'));
+
+ it('should supress the warning by default', function(){
+ module(function($provide) {
+ $provide.value('$typeaheadSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope, typeaheadHighlightFilter, $sce){
+ spyOn($log, 'warn');
+ var highlightFilter = typeaheadHighlightFilter;
+ $sce.getTrustedHtml(highlightFilter('before match after', 'match'));
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should decrecate typeaheadHighlightFilter', inject(function($compile, $log, $rootScope, typeaheadHighlightFilter, $sce){
+ spyOn($log, 'warn');
+ var highlightFilter = typeaheadHighlightFilter;
+ $sce.getTrustedHtml(highlightFilter('before match after', 'match'));
+ expect($log.warn.calls.count()).toBe(1);
+ expect($log.warn.calls.argsFor(0)).toEqual(['typeaheadHighlight is now deprecated. Use uibTypeaheadHighlight instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead-parser.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead-parser.spec.js
new file mode 100644
index 0000000..f19aec5
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead-parser.spec.js
@@ -0,0 +1,79 @@
+describe('syntax parser', function() {
+ var typeaheadParser, scope, filterFilter;
+
+ beforeEach(module('ui.bootstrap.typeahead'));
+ beforeEach(inject(function(_$rootScope_, _filterFilter_, _typeaheadParser_) {
+ typeaheadParser = _typeaheadParser_;
+ scope = _$rootScope_;
+ filterFilter = _filterFilter_;
+ }));
+
+ it('should parse the simplest array-based syntax', function() {
+ scope.states = ['Alabama', 'California', 'Delaware'];
+ var result = typeaheadParser.parse('state for state in states | filter:$viewValue');
+
+ var itemName = result.itemName;
+ var locals = {$viewValue:'al'};
+ expect(result.source(scope, locals)).toEqual(['Alabama', 'California']);
+
+ locals[itemName] = 'Alabama';
+ expect(result.viewMapper(scope, locals)).toEqual('Alabama');
+ expect(result.modelMapper(scope, locals)).toEqual('Alabama');
+ });
+
+ it('should parse the simplest function-based syntax', function() {
+ scope.getStates = function($viewValue) {
+ return filterFilter(['Alabama', 'California', 'Delaware'], $viewValue);
+ };
+ var result = typeaheadParser.parse('state for state in getStates($viewValue)');
+
+ var itemName = result.itemName;
+ var locals = {$viewValue:'al'};
+ expect(result.source(scope, locals)).toEqual(['Alabama', 'California']);
+
+ locals[itemName] = 'Alabama';
+ expect(result.viewMapper(scope, locals)).toEqual('Alabama');
+ expect(result.modelMapper(scope, locals)).toEqual('Alabama');
+ });
+
+ it('should allow to specify custom model mapping that is used as a label as well', function () {
+ scope.states = [
+ {code:'AL', name:'Alabama'},
+ {code:'CA', name:'California'},
+ {code:'DE', name:'Delaware'}
+ ];
+ var result = typeaheadParser.parse('state.name for state in states | filter:$viewValue | orderBy:"name":true');
+
+ var itemName = result.itemName;
+ expect(itemName).toEqual('state');
+ expect(result.source(scope, {$viewValue:'al'})).toEqual([
+ {code:'CA', name:'California'},
+ {code:'AL', name:'Alabama'}
+ ]);
+
+ var locals = {$viewValue:'al'};
+ locals[itemName] = {code:'AL', name:'Alabama'};
+ expect(result.viewMapper(scope, locals)).toEqual('Alabama');
+ expect(result.modelMapper(scope, locals)).toEqual('Alabama');
+ });
+
+ it('should allow to specify custom view and model mappers', function() {
+ scope.states = [
+ {code:'AL', name:'Alabama'},
+ {code:'CA', name:'California'},
+ {code:'DE', name:'Delaware'}
+ ];
+ var result = typeaheadParser.parse('state.code as state.name + " ("+state.code+")" for state in states | filter:$viewValue | orderBy:"name":true');
+
+ var itemName = result.itemName;
+ expect(result.source(scope, {$viewValue:'al'})).toEqual([
+ {code:'CA', name:'California'},
+ {code:'AL', name:'Alabama'}
+ ]);
+
+ var locals = {$viewValue:'al'};
+ locals[itemName] = {code:'AL', name:'Alabama'};
+ expect(result.viewMapper(scope, locals)).toEqual('Alabama (AL)');
+ expect(result.modelMapper(scope, locals)).toEqual('AL');
+ });
+});
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead-popup.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead-popup.spec.js
new file mode 100644
index 0000000..6393660
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead-popup.spec.js
@@ -0,0 +1,101 @@
+describe('typeaheadPopup - result rendering', function() {
+ var scope, $rootScope, $compile;
+
+ beforeEach(module('ui.bootstrap.typeahead'));
+ beforeEach(module('template/typeahead/typeahead-popup.html'));
+ beforeEach(module('template/typeahead/typeahead-match.html'));
+ beforeEach(inject(function(_$rootScope_, _$compile_) {
+ $rootScope = _$rootScope_;
+ scope = $rootScope.$new();
+ $compile = _$compile_;
+ }));
+
+ it('should render initial results', function() {
+ scope.matches = ['foo', 'bar', 'baz'];
+ scope.active = 1;
+
+ var el = $compile('<div><uib-typeahead-popup matches="matches" active="active" select="select(activeIdx)"></uib-typeahead-popup></div>')(scope);
+ $rootScope.$digest();
+
+ var liElems = el.find('li');
+ expect(liElems.length).toEqual(3);
+ expect(liElems.eq(0)).not.toHaveClass('active');
+ expect(liElems.eq(1)).toHaveClass('active');
+ expect(liElems.eq(2)).not.toHaveClass('active');
+ });
+
+ it('should change active item on mouseenter', function() {
+ scope.matches = ['foo', 'bar', 'baz'];
+ scope.active = 1;
+
+ var el = $compile('<div><uib-typeahead-popup matches="matches" active="active" select="select(activeIdx)"></uib-typeahead-popup></div>')(scope);
+ $rootScope.$digest();
+
+ var liElems = el.find('li');
+ expect(liElems.eq(1)).toHaveClass('active');
+ expect(liElems.eq(2)).not.toHaveClass('active');
+
+ liElems.eq(2).trigger('mouseenter');
+
+ expect(liElems.eq(1)).not.toHaveClass('active');
+ expect(liElems.eq(2)).toHaveClass('active');
+ });
+
+ it('should select an item on mouse click', function() {
+ scope.matches = ['foo', 'bar', 'baz'];
+ scope.active = 1;
+ $rootScope.select = angular.noop;
+ spyOn($rootScope, 'select');
+
+ var el = $compile('<div><uib-typeahead-popup matches="matches" active="active" select="select(activeIdx)"></uib-typeahead-popup></div>')(scope);
+ $rootScope.$digest();
+
+ var liElems = el.find('li');
+ liElems.eq(2).find('a').trigger('click');
+ expect($rootScope.select).toHaveBeenCalledWith(2);
+ });
+});
+
+/* Deprecation tests below */
+
+describe('typeaheadPopup deprecation', function() {
+ beforeEach(module('ui.bootstrap.typeahead'));
+ beforeEach(module('ngSanitize'));
+ beforeEach(module('template/typeahead/typeahead-popup.html'));
+ beforeEach(module('template/typeahead/typeahead-match.html'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$typeaheadSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ var scope = $rootScope.$new();
+ scope.matches = ['foo', 'bar', 'baz'];
+ scope.active = 1;
+ $rootScope.select = angular.noop;
+ spyOn($log, 'warn');
+
+ var element = '<div><typeahead-popup matches="matches" active="active" select="select(activeIdx)"></typeahead-popup></div>';
+ element = $compile(element)(scope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ var scope = $rootScope.$new();
+ scope.matches = ['foo', 'bar', 'baz'];
+ scope.active = 1;
+ $rootScope.select = angular.noop;
+ spyOn($log, 'warn');
+
+ var element = '<div><typeahead-popup matches="matches" active="active" select="select(activeIdx)"></typeahead-popup></div>';
+ element = $compile(element)(scope);
+
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(1);
+ expect($log.warn.calls.argsFor(0)).toEqual(['typeahead-popup is now deprecated. Use uib-typeahead-popup instead.']);
+ }));
+});
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead.spec.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead.spec.js
new file mode 100644
index 0000000..040a228
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/test/typeahead.spec.js
@@ -0,0 +1,1097 @@
+describe('typeahead tests', function() {
+ var $scope, $compile, $document, $templateCache, $timeout, $window;
+ var changeInputValueTo;
+
+ beforeEach(module('ui.bootstrap.typeahead'));
+ beforeEach(module('ngSanitize'));
+ beforeEach(module('template/typeahead/typeahead-popup.html'));
+ beforeEach(module('template/typeahead/typeahead-match.html'));
+ beforeEach(module(function($compileProvider) {
+ $compileProvider.directive('formatter', function() {
+ return {
+ require: 'ngModel',
+ link: function (scope, elm, attrs, ngModelCtrl) {
+ ngModelCtrl.$formatters.unshift(function(viewVal) {
+ return 'formatted' + viewVal;
+ });
+ }
+ };
+ });
+ $compileProvider.directive('childDirective', function() {
+ return {
+ restrict: 'A',
+ require: '^parentDirective',
+ link: function(scope, element, attrs, ctrl) {}
+ };
+ });
+ }));
+ beforeEach(inject(function(_$rootScope_, _$compile_, _$document_, _$templateCache_, _$timeout_, _$window_, $sniffer) {
+ $scope = _$rootScope_;
+ $scope.source = ['foo', 'bar', 'baz'];
+ $scope.states = [
+ {code: 'AL', name: 'Alaska'},
+ {code: 'CL', name: 'California'}
+ ];
+ $compile = _$compile_;
+ $document = _$document_;
+ $templateCache = _$templateCache_;
+ $timeout = _$timeout_;
+ $window = _$window_;
+ changeInputValueTo = function(element, value) {
+ var inputEl = findInput(element);
+ inputEl.val(value);
+ inputEl.trigger($sniffer.hasEvent('input') ? 'input' : 'change');
+ $scope.$digest();
+ };
+ }));
+
+ //utility functions
+ var prepareInputEl = function(inputTpl) {
+ var el = $compile(angular.element(inputTpl))($scope);
+ $scope.$digest();
+ return el;
+ };
+
+ var findInput = function(element) {
+ return element.find('input');
+ };
+
+ var findDropDown = function(element) {
+ return element.find('ul.dropdown-menu');
+ };
+
+ var findMatches = function(element) {
+ return findDropDown(element).find('li');
+ };
+
+ var triggerKeyDown = function(element, keyCode) {
+ var inputEl = findInput(element);
+ var e = $.Event('keydown');
+ e.which = keyCode;
+ inputEl.trigger(e);
+ };
+
+ //custom matchers
+ beforeEach(function () {
+ jasmine.addMatchers({
+ toBeClosed: function(util, customEqualityTesters) {
+ return {
+ compare: function(actual, expected) {
+ var typeaheadEl = findDropDown(actual);
+
+ var result = {
+ pass: util.equals(typeaheadEl.hasClass('ng-hide'), true, customEqualityTesters)
+ };
+
+ if (result.pass) {
+ result.message = 'Expected "' + angular.mock.dump(typeaheadEl) + '" not to be closed.';
+ } else {
+ result.message = 'Expected "' + angular.mock.dump(typeaheadEl) + '" to be closed.';
+ }
+
+ return result;
+ }
+ };
+ },
+ toBeOpenWithActive: function(util, customEqualityTesters) {
+ return {
+ compare: function(actual, noOfMatches, activeIdx) {
+ var typeaheadEl = findDropDown(actual);
+ var liEls = findMatches(actual);
+
+ var result = {
+ pass: util.equals(typeaheadEl.length, 1, customEqualityTesters) &&
+ util.equals(typeaheadEl.hasClass('ng-hide'), false, customEqualityTesters) &&
+ util.equals(liEls.length, noOfMatches, customEqualityTesters) &&
+ activeIdx === -1 ? !$(liEls).hasClass('active') : $(liEls[activeIdx]).hasClass('active')
+ };
+
+ if (result.pass) {
+ result.message = 'Expected "' + actual + '" not to be opened.';
+ } else {
+ result.message = 'Expected "' + actual + '" to be opened.';
+ }
+
+ return result;
+ }
+ };
+ }
+ });
+ });
+
+ afterEach(function() {
+ findDropDown($document.find('body')).remove();
+ });
+
+ //coarse grained, "integration" tests
+ describe('initial state and model changes', function() {
+ it('should be closed by default', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source"></div>');
+ expect(element).toBeClosed();
+ });
+
+ it('should correctly render initial state if the "as" keyword is used', function() {
+ $scope.result = $scope.states[0];
+
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="state as state.name for state in states"></div>');
+ var inputEl = findInput(element);
+
+ expect(inputEl.val()).toEqual('Alaska');
+ });
+
+ it('should default to bound model for initial rendering if there is not enough info to render label', function() {
+ $scope.result = $scope.states[0].code;
+
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="state.code as state.name + state.code for state in states"></div>');
+ var inputEl = findInput(element);
+
+ expect(inputEl.val()).toEqual('AL');
+ });
+
+ it('should not get open on model change', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source"></div>');
+ $scope.$apply(function () {
+ $scope.result = 'foo';
+ });
+ expect(element).toBeClosed();
+ });
+ });
+
+ describe('basic functionality', function() {
+ it('should open and close typeahead based on matches', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue"></div>');
+ var inputEl = findInput(element);
+ var ownsId = inputEl.attr('aria-owns');
+
+ expect(inputEl.attr('aria-expanded')).toBe('false');
+ expect(inputEl.attr('aria-activedescendant')).toBeUndefined();
+
+ changeInputValueTo(element, 'ba');
+ expect(element).toBeOpenWithActive(2, 0);
+ expect(findDropDown(element).attr('id')).toBe(ownsId);
+ expect(inputEl.attr('aria-expanded')).toBe('true');
+ var activeOptionId = ownsId + '-option-0';
+ expect(inputEl.attr('aria-activedescendant')).toBe(activeOptionId);
+ expect(findDropDown(element).find('li.active').attr('id')).toBe(activeOptionId);
+
+ changeInputValueTo(element, '');
+ expect(element).toBeClosed();
+ expect(inputEl.attr('aria-expanded')).toBe('false');
+ expect(inputEl.attr('aria-activedescendant')).toBeUndefined();
+ });
+
+ it('should allow expressions over multiple lines', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source \n' +
+ '| filter:$viewValue"></div>');
+ changeInputValueTo(element, 'ba');
+ expect(element).toBeOpenWithActive(2, 0);
+
+ changeInputValueTo(element, '');
+ expect(element).toBeClosed();
+ });
+
+ it('should not open typeahead if input value smaller than a defined threshold', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-min-length="2"></div>');
+ changeInputValueTo(element, 'b');
+ expect(element).toBeClosed();
+ });
+
+ it('should support custom model selecting function', function() {
+ $scope.updaterFn = function(selectedItem) {
+ return 'prefix' + selectedItem;
+ };
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="updaterFn(item) as item for item in source | filter:$viewValue"></div>');
+ changeInputValueTo(element, 'f');
+ triggerKeyDown(element, 13);
+ expect($scope.result).toEqual('prefixfoo');
+ });
+
+ it('should support custom label rendering function', function() {
+ $scope.formatterFn = function(sourceItem) {
+ return 'prefix' + sourceItem;
+ };
+
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item as formatterFn(item) for item in source | filter:$viewValue"></div>');
+ changeInputValueTo(element, 'fo');
+ var matchHighlight = findMatches(element).find('a').html();
+ expect(matchHighlight).toEqual('prefix<strong>fo</strong>o');
+ });
+
+ it('should by default bind view value to model even if not part of matches', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue"></div>');
+ changeInputValueTo(element, 'not in matches');
+ expect($scope.result).toEqual('not in matches');
+ });
+
+ it('should support the editable property to limit model bindings to matches only', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-editable="false"></div>');
+ changeInputValueTo(element, 'not in matches');
+ expect($scope.result).toEqual(undefined);
+ });
+
+ it('should set validation errors for non-editable inputs', function() {
+ var element = prepareInputEl(
+ '<div><form name="form">' +
+ '<input name="input" ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-editable="false">' +
+ '</form></div>');
+
+ changeInputValueTo(element, 'not in matches');
+ expect($scope.result).toEqual(undefined);
+ expect($scope.form.input.$error.editable).toBeTruthy();
+
+ changeInputValueTo(element, 'foo');
+ triggerKeyDown(element, 13);
+ expect($scope.result).toEqual('foo');
+ expect($scope.form.input.$error.editable).toBeFalsy();
+ });
+
+ it('should not set editable validation error for empty input', function() {
+ var element = prepareInputEl(
+ '<div><form name="form">' +
+ '<input name="input" ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-editable="false">' +
+ '</form></div>');
+
+ changeInputValueTo(element, 'not in matches');
+ expect($scope.result).toEqual(undefined);
+ expect($scope.form.input.$error.editable).toBeTruthy();
+ changeInputValueTo(element, '');
+ expect($scope.result).toEqual(null);
+ expect($scope.form.input.$error.editable).toBeFalsy();
+ });
+
+ it('should bind loading indicator expression', inject(function($timeout) {
+ $scope.isLoading = false;
+ $scope.loadMatches = function(viewValue) {
+ return $timeout(function() {
+ return [];
+ }, 1000);
+ };
+
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in loadMatches()" typeahead-loading="isLoading"></div>');
+ changeInputValueTo(element, 'foo');
+
+ expect($scope.isLoading).toBeTruthy();
+ $timeout.flush();
+ expect($scope.isLoading).toBeFalsy();
+ }));
+
+ it('should support timeout before trying to match $viewValue', inject(function($timeout) {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-wait-ms="200"></div>');
+ changeInputValueTo(element, 'foo');
+ expect(element).toBeClosed();
+
+ $timeout.flush();
+ expect(element).toBeOpenWithActive(1, 0);
+ }));
+
+ it('should cancel old timeouts when something is typed within waitTime', inject(function($timeout) {
+ var values = [];
+ $scope.loadMatches = function(viewValue) {
+ values.push(viewValue);
+ return $scope.source;
+ };
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in loadMatches($viewValue) | filter:$viewValue" typeahead-wait-ms="200"></div>');
+ changeInputValueTo(element, 'first');
+ changeInputValueTo(element, 'second');
+
+ $timeout.flush();
+
+ expect(values).not.toContain('first');
+ }));
+
+ it('should allow timeouts when something is typed after waitTime has passed', inject(function($timeout) {
+ var values = [];
+
+ $scope.loadMatches = function(viewValue) {
+ values.push(viewValue);
+ return $scope.source;
+ };
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in loadMatches($viewValue) | filter:$viewValue" typeahead-wait-ms="200"></div>');
+
+ changeInputValueTo(element, 'first');
+ $timeout.flush();
+
+ expect(values).toContain('first');
+
+ changeInputValueTo(element, 'second');
+ $timeout.flush();
+
+ expect(values).toContain('second');
+ }));
+
+ it('should support custom popup templates', function() {
+ $templateCache.put('custom.html', '<div class="custom">foo</div>');
+
+ var element = prepareInputEl('<div><input ng-model="result" typeahead-popup-template-url="custom.html" uib-typeahead="state as state.name for state in states | filter:$viewValue"></div>');
+
+ changeInputValueTo(element, 'Al');
+
+ expect(element.find('.custom').text()).toBe('foo');
+ });
+
+ it('should support custom templates for matched items', function() {
+ $templateCache.put('custom.html', '<p>{{ index }} {{ match.label }}</p>');
+
+ var element = prepareInputEl('<div><input ng-model="result" typeahead-template-url="custom.html" uib-typeahead="state as state.name for state in states | filter:$viewValue"></div>');
+
+ changeInputValueTo(element, 'Al');
+
+ expect(findMatches(element).eq(0).find('p').text()).toEqual('0 Alaska');
+ });
+
+ it('should support directives which require controllers in custom templates for matched items', function() {
+ $templateCache.put('custom.html', '<p child-directive>{{ index }} {{ match.label }}</p>');
+
+ var element = prepareInputEl('<div><input ng-model="result" typeahead-template-url="custom.html" uib-typeahead="state as state.name for state in states | filter:$viewValue"></div>');
+
+ element.data('$parentDirectiveController', {});
+
+ changeInputValueTo(element, 'Al');
+
+ expect(findMatches(element).eq(0).find('p').text()).toEqual('0 Alaska');
+ });
+
+ it('should throw error on invalid expression', function() {
+ var prepareInvalidDir = function() {
+ prepareInputEl('<div><input ng-model="result" uib-typeahead="an invalid expression"></div>');
+ };
+ expect(prepareInvalidDir).toThrow();
+ });
+ });
+
+ describe('selecting a match', function() {
+ it('should select a match on enter', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'b');
+ triggerKeyDown(element, 13);
+
+ expect($scope.result).toEqual('bar');
+ expect(inputEl.val()).toEqual('bar');
+ expect(element).toBeClosed();
+ });
+
+ it('should select a match on tab', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'b');
+ triggerKeyDown(element, 9);
+
+ expect($scope.result).toEqual('bar');
+ expect(inputEl.val()).toEqual('bar');
+ expect(element).toBeClosed();
+ });
+
+ it('should not select any match on blur without \'select-on-blur=true\' option', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'b');
+ inputEl.blur(); // input loses focus
+
+ // no change
+ expect($scope.result).toEqual('b');
+ expect(inputEl.val()).toEqual('b');
+ });
+
+ it('should select a match on blur with \'select-on-blur=true\' option', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-select-on-blur="true"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'b');
+ inputEl.blur(); // input loses focus
+
+ // first element should be selected
+ expect($scope.result).toEqual('bar');
+ expect(inputEl.val()).toEqual('bar');
+ });
+
+ it('should select match on click', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'b');
+ var match = $(findMatches(element)[1]).find('a')[0];
+
+ $(match).click();
+ $scope.$digest();
+
+ expect($scope.result).toEqual('baz');
+ expect(inputEl.val()).toEqual('baz');
+ expect(element).toBeClosed();
+ });
+
+ it('should invoke select callback on select', function() {
+ $scope.onSelect = function($item, $model, $label) {
+ $scope.$item = $item;
+ $scope.$model = $model;
+ $scope.$label = $label;
+ };
+ var element = prepareInputEl('<div><input ng-model="result" typeahead-on-select="onSelect($item, $model, $label)" uib-typeahead="state.code as state.name for state in states | filter:$viewValue"></div>');
+
+ changeInputValueTo(element, 'Alas');
+ triggerKeyDown(element, 13);
+
+ expect($scope.result).toEqual('AL');
+ expect($scope.$item).toEqual($scope.states[0]);
+ expect($scope.$model).toEqual('AL');
+ expect($scope.$label).toEqual('Alaska');
+ });
+
+ it('should correctly update inputs value on mapping where label is not derived from the model', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="state.code as state.name for state in states | filter:$viewValue"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'Alas');
+ triggerKeyDown(element, 13);
+
+ expect($scope.result).toEqual('AL');
+ expect(inputEl.val()).toEqual('AL');
+ });
+
+ it('should bind no results indicator as true when no matches returned', inject(function($timeout) {
+ $scope.isNoResults = false;
+ $scope.loadMatches = function(viewValue) {
+ return $timeout(function() {
+ return [];
+ }, 1000);
+ };
+
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in loadMatches()" typeahead-no-results="isNoResults"></div>');
+ changeInputValueTo(element, 'foo');
+
+ expect($scope.isNoResults).toBeFalsy();
+ $timeout.flush();
+ expect($scope.isNoResults).toBeTruthy();
+ }));
+
+ it('should bind no results indicator as false when matches are returned', inject(function($timeout) {
+ $scope.isNoResults = false;
+ $scope.loadMatches = function(viewValue) {
+ return $timeout(function() {
+ return [viewValue];
+ }, 1000);
+ };
+
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in loadMatches()" typeahead-no-results="isNoResults"></div>');
+ changeInputValueTo(element, 'foo');
+
+ expect($scope.isNoResults).toBeFalsy();
+ $timeout.flush();
+ expect($scope.isNoResults).toBeFalsy();
+ }));
+
+ it('should not focus the input if `typeahead-focus-on-select` is false', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-focus-on-select="false"></div>');
+ $document.find('body').append(element);
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'b');
+ var match = $(findMatches(element)[1]).find('a')[0];
+
+ $(match).click();
+ $scope.$digest();
+ $timeout.flush();
+
+ expect(document.activeElement).not.toBe(inputEl[0]);
+ expect($scope.result).toEqual('baz');
+ });
+ });
+
+ describe('select on exact match', function() {
+ it('should select on an exact match when set', function() {
+ $scope.onSelect = jasmine.createSpy('onSelect');
+ var element = prepareInputEl('<div><input ng-model="result" typeahead-editable="false" typeahead-on-select="onSelect()" uib-typeahead="item for item in source | filter:$viewValue" typeahead-select-on-exact="true"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'bar');
+
+ expect($scope.result).toEqual('bar');
+ expect(inputEl.val()).toEqual('bar');
+ expect(element).toBeClosed();
+ expect($scope.onSelect).toHaveBeenCalled();
+ });
+
+ it('should not select on an exact match by default', function() {
+ $scope.onSelect = jasmine.createSpy('onSelect');
+ var element = prepareInputEl('<div><input ng-model="result" typeahead-editable="false" typeahead-on-select="onSelect()" uib-typeahead="item for item in source | filter:$viewValue"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'bar');
+
+ expect($scope.result).toBeUndefined();
+ expect(inputEl.val()).toEqual('bar');
+ expect($scope.onSelect.calls.any()).toBe(false);
+ });
+
+ it('should not be case sensitive when select on an exact match', function() {
+ $scope.onSelect = jasmine.createSpy('onSelect');
+ var element = prepareInputEl('<div><input ng-model="result" typeahead-editable="false" typeahead-on-select="onSelect()" uib-typeahead="item for item in source | filter:$viewValue" typeahead-select-on-exact="true"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'BaR');
+
+ expect($scope.result).toEqual('bar');
+ expect(inputEl.val()).toEqual('bar');
+ expect(element).toBeClosed();
+ expect($scope.onSelect).toHaveBeenCalled();
+ });
+
+ it('should not auto select when not a match with one potential result left', function() {
+ $scope.onSelect = jasmine.createSpy('onSelect');
+ var element = prepareInputEl('<div><input ng-model="result" typeahead-editable="false" typeahead-on-select="onSelect()" uib-typeahead="item for item in source | filter:$viewValue" typeahead-select-on-exact="true"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'fo');
+
+ expect($scope.result).toBeUndefined();
+ expect(inputEl.val()).toEqual('fo');
+ expect($scope.onSelect.calls.any()).toBe(false);
+ });
+ });
+
+ describe('pop-up interaction', function() {
+ var element;
+
+ beforeEach(function() {
+ element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue"></div>');
+ });
+
+ it('should activate prev/next matches on up/down keys', function() {
+ changeInputValueTo(element, 'b');
+ expect(element).toBeOpenWithActive(2, 0);
+
+ // Down arrow key
+ triggerKeyDown(element, 40);
+ expect(element).toBeOpenWithActive(2, 1);
+
+ // Down arrow key goes back to first element
+ triggerKeyDown(element, 40);
+ expect(element).toBeOpenWithActive(2, 0);
+
+ // Up arrow key goes back to last element
+ triggerKeyDown(element, 38);
+ expect(element).toBeOpenWithActive(2, 1);
+
+ // Up arrow key goes back to first element
+ triggerKeyDown(element, 38);
+ expect(element).toBeOpenWithActive(2, 0);
+ });
+
+ it('should close popup on escape key', function() {
+ changeInputValueTo(element, 'b');
+ expect(element).toBeOpenWithActive(2, 0);
+
+ // Escape key
+ triggerKeyDown(element, 27);
+ expect(element).toBeClosed();
+ });
+
+ it('should highlight match on mouseenter', function() {
+ changeInputValueTo(element, 'b');
+ expect(element).toBeOpenWithActive(2, 0);
+
+ findMatches(element).eq(1).trigger('mouseenter');
+ expect(element).toBeOpenWithActive(2, 1);
+ });
+ });
+
+ describe('promises', function() {
+ var element, deferred;
+
+ beforeEach(inject(function($q) {
+ deferred = $q.defer();
+ $scope.source = function() {
+ return deferred.promise;
+ };
+ element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source()"></div>');
+ }));
+
+ it('should display matches from promise', function() {
+ changeInputValueTo(element, 'c');
+ expect(element).toBeClosed();
+
+ deferred.resolve(['good', 'stuff']);
+ $scope.$digest();
+ expect(element).toBeOpenWithActive(2, 0);
+ });
+
+ it('should not display anything when promise is rejected', function() {
+ changeInputValueTo(element, 'c');
+ expect(element).toBeClosed();
+
+ deferred.reject('fail');
+ $scope.$digest();
+ expect(element).toBeClosed();
+ });
+
+ it('PR #3178, resolves #2999 - should not return property "length" of undefined for undefined matches', function() {
+ changeInputValueTo(element, 'c');
+ expect(element).toBeClosed();
+
+ deferred.resolve();
+ $scope.$digest();
+ expect(element).toBeClosed();
+ });
+ });
+
+ describe('non-regressions tests', function() {
+
+ it('issue 231 - closes matches popup on click outside typeahead', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue"></div>');
+
+ changeInputValueTo(element, 'b');
+
+ $document.find('body').click();
+ $scope.$digest();
+
+ expect(element).toBeClosed();
+ });
+
+ it('issue 591 - initial formatting for un-selected match and complex label expression', function() {
+ var inputEl = findInput(prepareInputEl('<div><input ng-model="result" uib-typeahead="state as state.name + \' \' + state.code for state in states | filter:$viewValue"></div>'));
+ expect(inputEl.val()).toEqual('');
+ });
+
+ it('issue 786 - name of internal model should not conflict with scope model name', function() {
+ $scope.state = $scope.states[0];
+ var element = prepareInputEl('<div><input ng-model="state" uib-typeahead="state as state.name for state in states | filter:$viewValue"></div>');
+ var inputEl = findInput(element);
+
+ expect(inputEl.val()).toEqual('Alaska');
+ });
+
+ it('issue 863 - it should work correctly with input type="email"', function() {
+ $scope.emails = ['foo@host.com', 'bar@host.com'];
+ var element = prepareInputEl('<div><input type="email" ng-model="email" uib-typeahead="email for email in emails | filter:$viewValue"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'bar');
+ expect(element).toBeOpenWithActive(1, 0);
+
+ triggerKeyDown(element, 13);
+
+ expect($scope.email).toEqual('bar@host.com');
+ expect(inputEl.val()).toEqual('bar@host.com');
+ });
+
+ it('issue 964 - should not show popup with matches if an element is not focused', function() {
+ $scope.items = function(viewValue) {
+ return $timeout(function() {
+ return [viewValue];
+ });
+ };
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in items($viewValue)"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'match');
+ $scope.$digest();
+
+ inputEl.blur();
+ $timeout.flush();
+
+ expect(element).toBeClosed();
+ });
+
+ it('should properly update loading callback if an element is not focused', function() {
+ $scope.items = function(viewValue) {
+ return $timeout(function(){
+ return [viewValue];
+ });
+ };
+ var element = prepareInputEl('<div><input ng-model="result" typeahead-loading="isLoading" uib-typeahead="item for item in items($viewValue)"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'match');
+ $scope.$digest();
+
+ inputEl.blur();
+ $timeout.flush();
+
+ expect($scope.isLoading).toBeFalsy();
+ });
+
+ it('issue 1140 - should properly update loading callback when deleting characters', function() {
+ $scope.items = function(viewValue) {
+ return $timeout(function() {
+ return [viewValue];
+ });
+ };
+ var element = prepareInputEl('<div><input ng-model="result" typeahead-min-length="2" typeahead-loading="isLoading" uib-typeahead="item for item in items($viewValue)"></div>');
+
+ changeInputValueTo(element, 'match');
+ $scope.$digest();
+
+ expect($scope.isLoading).toBeTruthy();
+
+ changeInputValueTo(element, 'm');
+ $timeout.flush();
+ $scope.$digest();
+
+ expect($scope.isLoading).toBeFalsy();
+ });
+
+ it('should cancel old timeout when deleting characters', inject(function($timeout) {
+ var values = [];
+ $scope.loadMatches = function(viewValue) {
+ values.push(viewValue);
+ return $scope.source;
+ };
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in loadMatches($viewValue) | filter:$viewValue" typeahead-min-length="2" typeahead-wait-ms="200"></div>');
+ changeInputValueTo(element, 'match');
+ changeInputValueTo(element, 'm');
+
+ $timeout.flush();
+
+ expect(values).not.toContain('match');
+ }));
+
+ describe('', function() {
+ // Dummy describe to be able to create an after hook for this tests
+ var element;
+
+ it('does not close matches popup on click in input', function() {
+ element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue"></div>');
+ var inputEl = findInput(element);
+
+ // Note that this bug can only be found when element is in the document
+ $document.find('body').append(element);
+
+ changeInputValueTo(element, 'b');
+
+ inputEl.click();
+ $scope.$digest();
+
+ expect(element).toBeOpenWithActive(2, 0);
+ });
+
+ it('issue #1773 - should not trigger an error when used with ng-focus', function() {
+ element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" ng-focus="foo()"></div>');
+ var inputEl = findInput(element);
+
+ // Note that this bug can only be found when element is in the document
+ $document.find('body').append(element);
+
+ changeInputValueTo(element, 'b');
+ var match = $(findMatches(element)[1]).find('a')[0];
+
+ $(match).click();
+ $scope.$digest();
+ });
+
+ afterEach(function() {
+ element.remove();
+ });
+ });
+
+ it('issue #1238 - allow names like "query" to be used inside "in" expressions ', function() {
+ $scope.query = function() {
+ return ['foo', 'bar'];
+ };
+
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in query($viewValue)"></div>');
+ changeInputValueTo(element, 'bar');
+
+ expect(element).toBeOpenWithActive(2, 0);
+ });
+
+ it('issue #3318 - should set model validity to true when set manually', function() {
+ var element = prepareInputEl(
+ '<div><form name="form">' +
+ '<input name="input" ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-editable="false">' +
+ '</form></div>');
+
+ changeInputValueTo(element, 'not in matches');
+ $scope.$apply(function() {
+ $scope.result = 'manually set';
+ });
+
+ expect($scope.result).toEqual('manually set');
+ expect($scope.form.input.$valid).toBeTruthy();
+ });
+
+ it('issue #3166 - should set \'parse\' key as valid when selecting a perfect match and not editable', function() {
+ var element = prepareInputEl('<div ng-form="test"><input name="typeahead" ng-model="result" uib-typeahead="state as state.name for state in states | filter:$viewValue" typeahead-editable="false"></div>');
+ var inputEl = findInput(element);
+
+ changeInputValueTo(element, 'Alaska');
+ triggerKeyDown(element, 13);
+
+ expect($scope.test.typeahead.$error.parse).toBeUndefined();
+ });
+
+ it('issue #3823 - should support ng-model-options getterSetter', function() {
+ function resultSetter(state) {
+ return state;
+ }
+ $scope.result = resultSetter;
+ var element = prepareInputEl('<div><input name="typeahead" ng-model="result" ng-model-options="{getterSetter: true}" uib-typeahead="state as state.name for state in states | filter:$viewValue" typeahead-editable="false"></div>');
+
+ changeInputValueTo(element, 'Alaska');
+ triggerKeyDown(element, 13);
+
+ expect($scope.result).toBe(resultSetter);
+ });
+ });
+
+ describe('input formatting', function() {
+ it('should co-operate with existing formatters', function() {
+ $scope.result = $scope.states[0];
+
+ var element = prepareInputEl('<div><input ng-model="result.name" formatter uib-typeahead="state.name for state in states | filter:$viewValue"></div>'),
+ inputEl = findInput(element);
+
+ expect(inputEl.val()).toEqual('formatted' + $scope.result.name);
+ });
+
+ it('should support a custom input formatting function', function() {
+ $scope.result = $scope.states[0];
+ $scope.formatInput = function($model) {
+ return $model.code;
+ };
+
+ var element = prepareInputEl('<div><input ng-model="result" typeahead-input-formatter="formatInput($model)" uib-typeahead="state as state.name for state in states | filter:$viewValue"></div>'),
+ inputEl = findInput(element);
+
+ expect(inputEl.val()).toEqual('AL');
+ expect($scope.result).toEqual($scope.states[0]);
+ });
+ });
+
+ describe('append to element id', function() {
+ it('append typeahead results to element', function() {
+ $document.find('body').append('<div id="myElement"></div>');
+ var element = prepareInputEl('<div><input name="input" ng-model="result" uib-typeahead="item for item in states | filter:$viewValue" typeahead-append-to-element-id="myElement"></div>');
+ changeInputValueTo(element, 'al');
+ expect($document.find('#myElement')).toBeOpenWithActive(2, 0);
+ $document.find('#myElement').remove();
+ });
+ });
+
+ describe('append to body', function() {
+ afterEach(function() {
+ angular.element($window).off('resize');
+ $document.find('body').off('scroll');
+ });
+
+ it('append typeahead results to body', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-append-to-body="true"></div>');
+ changeInputValueTo(element, 'ba');
+ expect($document.find('body')).toBeOpenWithActive(2, 0);
+ });
+
+ it('should not append to body when value of the attribute is false', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-append-to-body="false"></div>');
+ changeInputValueTo(element, 'ba');
+ expect(findDropDown($document.find('body')).length).toEqual(0);
+ });
+
+ it('should have right position after scroll', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-append-to-body="true"></div>');
+ var dropdown = findDropDown($document.find('body'));
+ var body = angular.element(document.body);
+
+ // Set body height to allow scrolling
+ body.css({height:'10000px'});
+
+ // Scroll top
+ window.scroll(0, 1000);
+
+ // Set input value to show dropdown
+ changeInputValueTo(element, 'ba');
+
+ // Init position of dropdown must be 1000px
+ expect(dropdown.css('top') ).toEqual('1000px');
+
+ // After scroll, must have new position
+ window.scroll(0, 500);
+ body.triggerHandler('scroll');
+ $timeout.flush();
+ expect(dropdown.css('top')).toEqual('500px');
+ });
+ });
+
+ describe('focus first', function() {
+ it('should focus the first element by default', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue"></div>');
+ changeInputValueTo(element, 'b');
+ expect(element).toBeOpenWithActive(2, 0);
+
+ // Down arrow key
+ triggerKeyDown(element, 40);
+ expect(element).toBeOpenWithActive(2, 1);
+
+ // Down arrow key goes back to first element
+ triggerKeyDown(element, 40);
+ expect(element).toBeOpenWithActive(2, 0);
+
+ // Up arrow key goes back to last element
+ triggerKeyDown(element, 38);
+ expect(element).toBeOpenWithActive(2, 1);
+
+ // Up arrow key goes back to first element
+ triggerKeyDown(element, 38);
+ expect(element).toBeOpenWithActive(2, 0);
+ });
+
+ it('should not focus the first element until keys are pressed', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-focus-first="false"></div>');
+ changeInputValueTo(element, 'b');
+ expect(element).toBeOpenWithActive(2, -1);
+
+ // Down arrow key goes to first element
+ triggerKeyDown(element, 40);
+ expect(element).toBeOpenWithActive(2, 0);
+
+ // Down arrow key goes to second element
+ triggerKeyDown(element, 40);
+ expect(element).toBeOpenWithActive(2, 1);
+
+ // Down arrow key goes back to first element
+ triggerKeyDown(element, 40);
+ expect(element).toBeOpenWithActive(2, 0);
+
+ // Up arrow key goes back to last element
+ triggerKeyDown(element, 38);
+ expect(element).toBeOpenWithActive(2, 1);
+
+ // Up arrow key goes back to first element
+ triggerKeyDown(element, 38);
+ expect(element).toBeOpenWithActive(2, 0);
+
+ // New input goes back to no focus
+ changeInputValueTo(element, 'a');
+ changeInputValueTo(element, 'b');
+ expect(element).toBeOpenWithActive(2, -1);
+
+ // Up arrow key goes to last element
+ triggerKeyDown(element, 38);
+ expect(element).toBeOpenWithActive(2, 1);
+ });
+ });
+
+ it('should not capture enter or tab when an item is not focused', function() {
+ $scope.select_count = 0;
+ $scope.onSelect = function($item, $model, $label) {
+ $scope.select_count = $scope.select_count + 1;
+ };
+ var element = prepareInputEl('<div><input ng-model="result" ng-keydown="keyDownEvent = $event" uib-typeahead="item for item in source | filter:$viewValue" typeahead-on-select="onSelect($item, $model, $label)" typeahead-focus-first="false"></div>');
+ changeInputValueTo(element, 'b');
+
+ // enter key should not be captured when nothing is focused
+ triggerKeyDown(element, 13);
+ expect($scope.keyDownEvent.isDefaultPrevented()).toBeFalsy();
+ expect($scope.select_count).toEqual(0);
+
+ // tab key should close the dropdown when nothing is focused
+ triggerKeyDown(element, 9);
+ expect($scope.keyDownEvent.isDefaultPrevented()).toBeFalsy();
+ expect($scope.select_count).toEqual(0);
+ expect(element).toBeClosed();
+ });
+
+ it('should capture enter or tab when an item is focused', function() {
+ $scope.select_count = 0;
+ $scope.onSelect = function($item, $model, $label) {
+ $scope.select_count = $scope.select_count + 1;
+ };
+ var element = prepareInputEl('<div><input ng-model="result" ng-keydown="keyDownEvent = $event" uib-typeahead="item for item in source | filter:$viewValue" typeahead-on-select="onSelect($item, $model, $label)" typeahead-focus-first="false"></div>');
+ changeInputValueTo(element, 'b');
+
+ // down key should be captured and focus first element
+ triggerKeyDown(element, 40);
+ expect($scope.keyDownEvent.isDefaultPrevented()).toBeTruthy();
+ expect(element).toBeOpenWithActive(2, 0);
+
+ // enter key should be captured now that something is focused
+ triggerKeyDown(element, 13);
+ expect($scope.keyDownEvent.isDefaultPrevented()).toBeTruthy();
+ expect($scope.select_count).toEqual(1);
+ });
+
+ describe('minLength set to 0', function() {
+ it('should open typeahead if input is changed to empty string if defined threshold is 0', function() {
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-min-length="0"></div>');
+ changeInputValueTo(element, '');
+ expect(element).toBeOpenWithActive(3, 0);
+ });
+ });
+
+ describe('event listeners', function() {
+ afterEach(function() {
+ angular.element($window).off('resize');
+ $document.find('body').off('scroll');
+ });
+
+ it('should register event listeners when attached to body', function() {
+ spyOn(window, 'addEventListener');
+ spyOn(document.body, 'addEventListener');
+
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-append-to-body="true"></div>');
+
+ expect(window.addEventListener).toHaveBeenCalledWith('resize', jasmine.any(Function), false);
+ expect(document.body.addEventListener).toHaveBeenCalledWith('scroll', jasmine.any(Function), false);
+ });
+
+ it('should remove event listeners when attached to body', function() {
+ spyOn(window, 'removeEventListener');
+ spyOn(document.body, 'removeEventListener');
+
+ var element = prepareInputEl('<div><input ng-model="result" uib-typeahead="item for item in source | filter:$viewValue" typeahead-append-to-body="true"></div>');
+ $scope.$destroy();
+
+ expect(window.removeEventListener).toHaveBeenCalledWith('resize', jasmine.any(Function), false);
+ expect(document.body.removeEventListener).toHaveBeenCalledWith('scroll', jasmine.any(Function), false);
+ });
+ });
+});
+
+/* Deprecation tests below */
+
+describe('typeahead deprecation', function() {
+ beforeEach(module('ui.bootstrap.typeahead'));
+ beforeEach(module('ngSanitize'));
+ beforeEach(module('template/typeahead/typeahead-popup.html'));
+ beforeEach(module('template/typeahead/typeahead-match.html'));
+
+ it('should suppress warning', function() {
+ module(function($provide) {
+ $provide.value('$typeaheadSuppressWarning', true);
+ });
+
+ inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = '<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue" typeahead-min-length="0"></div>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+ expect($log.warn.calls.count()).toBe(0);
+ });
+ });
+
+ it('should give warning by default', inject(function($compile, $log, $rootScope) {
+ spyOn($log, 'warn');
+
+ var element = '<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue" typeahead-min-length="0"></div>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(3);
+ expect($log.warn.calls.argsFor(0)).toEqual(['typeaheadParser is now deprecated. Use uibTypeaheadParser instead.']);
+ expect($log.warn.calls.argsFor(1)).toEqual(['typeahead is now deprecated. Use uib-typeahead instead.']);
+ expect($log.warn.calls.argsFor(2)).toEqual(['typeahead-popup is now deprecated. Use uib-typeahead-popup instead.']);
+ }));
+
+ it('should deprecate typeaheadMatch', inject(function($compile, $log, $rootScope, $templateCache, $sniffer){
+ spyOn($log, 'warn');
+
+ var element = '<div typeahead-match index=\"$index\" match=\"match\" query=\"query\" template-url=\"templateUrl\"></div>';
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+
+ expect($log.warn.calls.count()).toBe(1);
+ expect($log.warn.calls.argsFor(0)).toEqual(['typeahead-match is now deprecated. Use uib-typeahead-match instead.']);
+ }));
+});
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/typeahead.js b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/typeahead.js
new file mode 100644
index 0000000..aa88842
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/src/typeahead/typeahead.js
@@ -0,0 +1,1060 @@
+angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position'])
+
+/**
+ * A helper service that can parse typeahead's syntax (string provided by users)
+ * Extracted to a separate service for ease of unit testing
+ */
+ .factory('uibTypeaheadParser', ['$parse', function($parse) {
+ // 00000111000000000000022200000000000000003333333333333330000000000044000
+ var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/;
+ return {
+ parse: function(input) {
+ var match = input.match(TYPEAHEAD_REGEXP);
+ if (!match) {
+ throw new Error(
+ 'Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' +
+ ' but got "' + input + '".');
+ }
+
+ return {
+ itemName: match[3],
+ source: $parse(match[4]),
+ viewMapper: $parse(match[2] || match[1]),
+ modelMapper: $parse(match[1])
+ };
+ }
+ };
+ }])
+
+ .controller('UibTypeaheadController', ['$scope', '$element', '$attrs', '$compile', '$parse', '$q', '$timeout', '$document', '$window', '$rootScope', '$uibPosition', 'uibTypeaheadParser',
+ function(originalScope, element, attrs, $compile, $parse, $q, $timeout, $document, $window, $rootScope, $position, typeaheadParser) {
+ var HOT_KEYS = [9, 13, 27, 38, 40];
+ var eventDebounceTime = 200;
+ var modelCtrl, ngModelOptions;
+ //SUPPORTED ATTRIBUTES (OPTIONS)
+
+ //minimal no of characters that needs to be entered before typeahead kicks-in
+ var minLength = originalScope.$eval(attrs.typeaheadMinLength);
+ if (!minLength && minLength !== 0) {
+ minLength = 1;
+ }
+
+ //minimal wait time after last character typed before typeahead kicks-in
+ var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0;
+
+ //should it restrict model values to the ones selected from the popup only?
+ var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false;
+
+ //binding to a variable that indicates if matches are being retrieved asynchronously
+ var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;
+
+ //a callback executed when a match is selected
+ var onSelectCallback = $parse(attrs.typeaheadOnSelect);
+
+ //should it select highlighted popup value when losing focus?
+ var isSelectOnBlur = angular.isDefined(attrs.typeaheadSelectOnBlur) ? originalScope.$eval(attrs.typeaheadSelectOnBlur) : false;
+
+ //binding to a variable that indicates if there were no results after the query is completed
+ var isNoResultsSetter = $parse(attrs.typeaheadNoResults).assign || angular.noop;
+
+ var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;
+
+ var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false;
+
+ var appendToElementId = attrs.typeaheadAppendToElementId || false;
+
+ var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false;
+
+ //If input matches an item of the list exactly, select it automatically
+ var selectOnExact = attrs.typeaheadSelectOnExact ? originalScope.$eval(attrs.typeaheadSelectOnExact) : false;
+
+ //INTERNAL VARIABLES
+
+ //model setter executed upon match selection
+ var parsedModel = $parse(attrs.ngModel);
+ var invokeModelSetter = $parse(attrs.ngModel + '($$$p)');
+ var $setModelValue = function(scope, newValue) {
+ if (angular.isFunction(parsedModel(originalScope)) &&
+ ngModelOptions && ngModelOptions.$options && ngModelOptions.$options.getterSetter) {
+ return invokeModelSetter(scope, {$$$p: newValue});
+ } else {
+ return parsedModel.assign(scope, newValue);
+ }
+ };
+
+ //expressions used by typeahead
+ var parserResult = typeaheadParser.parse(attrs.uibTypeahead);
+
+ var hasFocus;
+
+ //Used to avoid bug in iOS webview where iOS keyboard does not fire
+ //mousedown & mouseup events
+ //Issue #3699
+ var selected;
+
+ //create a child scope for the typeahead directive so we are not polluting original scope
+ //with typeahead-specific data (matches, query etc.)
+ var scope = originalScope.$new();
+ var offDestroy = originalScope.$on('$destroy', function() {
+ scope.$destroy();
+ });
+ scope.$on('$destroy', offDestroy);
+
+ // WAI-ARIA
+ var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000);
+ element.attr({
+ 'aria-autocomplete': 'list',
+ 'aria-expanded': false,
+ 'aria-owns': popupId
+ });
+
+ //pop-up element used to display matches
+ var popUpEl = angular.element('<div uib-typeahead-popup></div>');
+ popUpEl.attr({
+ id: popupId,
+ matches: 'matches',
+ active: 'activeIdx',
+ select: 'select(activeIdx)',
+ 'move-in-progress': 'moveInProgress',
+ query: 'query',
+ position: 'position'
+ });
+ //custom item template
+ if (angular.isDefined(attrs.typeaheadTemplateUrl)) {
+ popUpEl.attr('template-url', attrs.typeaheadTemplateUrl);
+ }
+
+ if (angular.isDefined(attrs.typeaheadPopupTemplateUrl)) {
+ popUpEl.attr('popup-template-url', attrs.typeaheadPopupTemplateUrl);
+ }
+
+ var resetMatches = function() {
+ scope.matches = [];
+ scope.activeIdx = -1;
+ element.attr('aria-expanded', false);
+ };
+
+ var getMatchId = function(index) {
+ return popupId + '-option-' + index;
+ };
+
+ // Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead.
+ // This attribute is added or removed automatically when the `activeIdx` changes.
+ scope.$watch('activeIdx', function(index) {
+ if (index < 0) {
+ element.removeAttr('aria-activedescendant');
+ } else {
+ element.attr('aria-activedescendant', getMatchId(index));
+ }
+ });
+
+ var inputIsExactMatch = function(inputValue, index) {
+ if (scope.matches.length > index && inputValue) {
+ return inputValue.toUpperCase() === scope.matches[index].label.toUpperCase();
+ }
+
+ return false;
+ };
+
+ var getMatchesAsync = function(inputValue) {
+ var locals = {$viewValue: inputValue};
+ isLoadingSetter(originalScope, true);
+ isNoResultsSetter(originalScope, false);
+ $q.when(parserResult.source(originalScope, locals)).then(function(matches) {
+ //it might happen that several async queries were in progress if a user were typing fast
+ //but we are interested only in responses that correspond to the current view value
+ var onCurrentRequest = (inputValue === modelCtrl.$viewValue);
+ if (onCurrentRequest && hasFocus) {
+ if (matches && matches.length > 0) {
+ scope.activeIdx = focusFirst ? 0 : -1;
+ isNoResultsSetter(originalScope, false);
+ scope.matches.length = 0;
+
+ //transform labels
+ for (var i = 0; i < matches.length; i++) {
+ locals[parserResult.itemName] = matches[i];
+ scope.matches.push({
+ id: getMatchId(i),
+ label: parserResult.viewMapper(scope, locals),
+ model: matches[i]
+ });
+ }
+
+ scope.query = inputValue;
+ //position pop-up with matches - we need to re-calculate its position each time we are opening a window
+ //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
+ //due to other elements being rendered
+ recalculatePosition();
+
+ element.attr('aria-expanded', true);
+
+ //Select the single remaining option if user input matches
+ if (selectOnExact && scope.matches.length === 1 && inputIsExactMatch(inputValue, 0)) {
+ scope.select(0);
+ }
+ } else {
+ resetMatches();
+ isNoResultsSetter(originalScope, true);
+ }
+ }
+ if (onCurrentRequest) {
+ isLoadingSetter(originalScope, false);
+ }
+ }, function() {
+ resetMatches();
+ isLoadingSetter(originalScope, false);
+ isNoResultsSetter(originalScope, true);
+ });
+ };
+
+ // bind events only if appendToBody params exist - performance feature
+ if (appendToBody) {
+ angular.element($window).bind('resize', fireRecalculating);
+ $document.find('body').bind('scroll', fireRecalculating);
+ }
+
+ // Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
+ var timeoutEventPromise;
+
+ // Default progress type
+ scope.moveInProgress = false;
+
+ function fireRecalculating() {
+ if (!scope.moveInProgress) {
+ scope.moveInProgress = true;
+ scope.$digest();
+ }
+
+ // Cancel previous timeout
+ if (timeoutEventPromise) {
+ $timeout.cancel(timeoutEventPromise);
+ }
+
+ // Debounced executing recalculate after events fired
+ timeoutEventPromise = $timeout(function() {
+ // if popup is visible
+ if (scope.matches.length) {
+ recalculatePosition();
+ }
+
+ scope.moveInProgress = false;
+ }, eventDebounceTime);
+ }
+
+ // recalculate actual position and set new values to scope
+ // after digest loop is popup in right position
+ function recalculatePosition() {
+ scope.position = appendToBody ? $position.offset(element) : $position.position(element);
+ scope.position.top += element.prop('offsetHeight');
+ }
+
+ //we need to propagate user's query so we can higlight matches
+ scope.query = undefined;
+
+ //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
+ var timeoutPromise;
+
+ var scheduleSearchWithTimeout = function(inputValue) {
+ timeoutPromise = $timeout(function() {
+ getMatchesAsync(inputValue);
+ }, waitTime);
+ };
+
+ var cancelPreviousTimeout = function() {
+ if (timeoutPromise) {
+ $timeout.cancel(timeoutPromise);
+ }
+ };
+
+ resetMatches();
+
+ scope.select = function(activeIdx) {
+ //called from within the $digest() cycle
+ var locals = {};
+ var model, item;
+
+ selected = true;
+ locals[parserResult.itemName] = item = scope.matches[activeIdx].model;
+ model = parserResult.modelMapper(originalScope, locals);
+ $setModelValue(originalScope, model);
+ modelCtrl.$setValidity('editable', true);
+ modelCtrl.$setValidity('parse', true);
+
+ onSelectCallback(originalScope, {
+ $item: item,
+ $model: model,
+ $label: parserResult.viewMapper(originalScope, locals)
+ });
+
+ resetMatches();
+
+ //return focus to the input element if a match was selected via a mouse click event
+ // use timeout to avoid $rootScope:inprog error
+ if (scope.$eval(attrs.typeaheadFocusOnSelect) !== false) {
+ $timeout(function() { element[0].focus(); }, 0, false);
+ }
+ };
+
+ //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
+ element.bind('keydown', function(evt) {
+ //typeahead is open and an "interesting" key was pressed
+ if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
+ return;
+ }
+
+ // if there's nothing selected (i.e. focusFirst) and enter or tab is hit, clear the results
+ if (scope.activeIdx === -1 && (evt.which === 9 || evt.which === 13)) {
+ resetMatches();
+ scope.$digest();
+ return;
+ }
+
+ evt.preventDefault();
+
+ if (evt.which === 40) {
+ scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
+ scope.$digest();
+ } else if (evt.which === 38) {
+ scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1;
+ scope.$digest();
+ } else if (evt.which === 13 || evt.which === 9) {
+ scope.$apply(function () {
+ scope.select(scope.activeIdx);
+ });
+ } else if (evt.which === 27) {
+ evt.stopPropagation();
+
+ resetMatches();
+ scope.$digest();
+ }
+ });
+
+ element.bind('blur', function() {
+ if (isSelectOnBlur && scope.matches.length && scope.activeIdx !== -1 && !selected) {
+ selected = true;
+ scope.$apply(function() {
+ scope.select(scope.activeIdx);
+ });
+ }
+ hasFocus = false;
+ selected = false;
+ });
+
+ // Keep reference to click handler to unbind it.
+ var dismissClickHandler = function(evt) {
+ // Issue #3973
+ // Firefox treats right click as a click on document
+ if (element[0] !== evt.target && evt.which !== 3 && scope.matches.length !== 0) {
+ resetMatches();
+ if (!$rootScope.$$phase) {
+ scope.$digest();
+ }
+ }
+ };
+
+ $document.bind('click', dismissClickHandler);
+
+ originalScope.$on('$destroy', function() {
+ $document.unbind('click', dismissClickHandler);
+ if (appendToBody || appendToElementId) {
+ $popup.remove();
+ }
+
+ if (appendToBody) {
+ angular.element($window).unbind('resize', fireRecalculating);
+ $document.find('body').unbind('scroll', fireRecalculating);
+ }
+ // Prevent jQuery cache memory leak
+ popUpEl.remove();
+ });
+
+ var $popup = $compile(popUpEl)(scope);
+
+ if (appendToBody) {
+ $document.find('body').append($popup);
+ } else if (appendToElementId !== false) {
+ angular.element($document[0].getElementById(appendToElementId)).append($popup);
+ } else {
+ element.after($popup);
+ }
+
+ this.init = function(_modelCtrl, _ngModelOptions) {
+ modelCtrl = _modelCtrl;
+ ngModelOptions = _ngModelOptions;
+
+ //plug into $parsers pipeline to open a typeahead on view changes initiated from DOM
+ //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
+ modelCtrl.$parsers.unshift(function(inputValue) {
+ hasFocus = true;
+
+ if (minLength === 0 || inputValue && inputValue.length >= minLength) {
+ if (waitTime > 0) {
+ cancelPreviousTimeout();
+ scheduleSearchWithTimeout(inputValue);
+ } else {
+ getMatchesAsync(inputValue);
+ }
+ } else {
+ isLoadingSetter(originalScope, false);
+ cancelPreviousTimeout();
+ resetMatches();
+ }
+
+ if (isEditable) {
+ return inputValue;
+ } else {
+ if (!inputValue) {
+ // Reset in case user had typed something previously.
+ modelCtrl.$setValidity('editable', true);
+ return null;
+ } else {
+ modelCtrl.$setValidity('editable', false);
+ return undefined;
+ }
+ }
+ });
+
+ modelCtrl.$formatters.push(function(modelValue) {
+ var candidateViewValue, emptyViewValue;
+ var locals = {};
+
+ // The validity may be set to false via $parsers (see above) if
+ // the model is restricted to selected values. If the model
+ // is set manually it is considered to be valid.
+ if (!isEditable) {
+ modelCtrl.$setValidity('editable', true);
+ }
+
+ if (inputFormatter) {
+ locals.$model = modelValue;
+ return inputFormatter(originalScope, locals);
+ } else {
+ //it might happen that we don't have enough info to properly render input value
+ //we need to check for this situation and simply return model value if we can't apply custom formatting
+ locals[parserResult.itemName] = modelValue;
+ candidateViewValue = parserResult.viewMapper(originalScope, locals);
+ locals[parserResult.itemName] = undefined;
+ emptyViewValue = parserResult.viewMapper(originalScope, locals);
+
+ return candidateViewValue !== emptyViewValue ? candidateViewValue : modelValue;
+ }
+ });
+ };
+ }])
+
+ .directive('uibTypeahead', function() {
+ return {
+ controller: 'UibTypeaheadController',
+ require: ['ngModel', '^?ngModelOptions', 'uibTypeahead'],
+ link: function(originalScope, element, attrs, ctrls) {
+ ctrls[2].init(ctrls[0], ctrls[1]);
+ }
+ };
+ })
+
+ .directive('uibTypeaheadPopup', function() {
+ return {
+ scope: {
+ matches: '=',
+ query: '=',
+ active: '=',
+ position: '&',
+ moveInProgress: '=',
+ select: '&'
+ },
+ replace: true,
+ templateUrl: function(element, attrs) {
+ return attrs.popupTemplateUrl || 'template/typeahead/typeahead-popup.html';
+ },
+ link: function(scope, element, attrs) {
+ scope.templateUrl = attrs.templateUrl;
+
+ scope.isOpen = function() {
+ return scope.matches.length > 0;
+ };
+
+ scope.isActive = function(matchIdx) {
+ return scope.active == matchIdx;
+ };
+
+ scope.selectActive = function(matchIdx) {
+ scope.active = matchIdx;
+ };
+
+ scope.selectMatch = function(activeIdx) {
+ scope.select({activeIdx:activeIdx});
+ };
+ }
+ };
+ })
+
+ .directive('uibTypeaheadMatch', ['$templateRequest', '$compile', '$parse', function($templateRequest, $compile, $parse) {
+ return {
+ scope: {
+ index: '=',
+ match: '=',
+ query: '='
+ },
+ link:function(scope, element, attrs) {
+ var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html';
+ $templateRequest(tplUrl).then(function(tplContent) {
+ $compile(tplContent.trim())(scope, function(clonedElement) {
+ element.replaceWith(clonedElement);
+ });
+ });
+ }
+ };
+ }])
+
+ .filter('uibTypeaheadHighlight', ['$sce', '$injector', '$log', function($sce, $injector, $log) {
+ var isSanitizePresent;
+ isSanitizePresent = $injector.has('$sanitize');
+
+ function escapeRegexp(queryToEscape) {
+ // Regex: capture the whole query string and replace it with the string that will be used to match
+ // the results, for example if the capture is "a" the result will be \a
+ return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
+ }
+
+ function containsHtml(matchItem) {
+ return /<.*>/g.test(matchItem);
+ }
+
+ return function(matchItem, query) {
+ if (!isSanitizePresent && containsHtml(matchItem)) {
+ $log.warn('Unsafe use of typeahead please use ngSanitize'); // Warn the user about the danger
+ }
+ matchItem = query? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem; // Replaces the capture string with a the same string inside of a "strong" tag
+ if (!isSanitizePresent) {
+ matchItem = $sce.trustAsHtml(matchItem); // If $sanitize is not present we pack the string in a $sce object for the ng-bind-html directive
+ }
+ return matchItem;
+ };
+ }]);
+
+/* Deprecated typeahead below */
+
+angular.module('ui.bootstrap.typeahead')
+ .value('$typeaheadSuppressWarning', false)
+ .service('typeaheadParser', ['$parse', 'uibTypeaheadParser', '$log', '$typeaheadSuppressWarning', function($parse, uibTypeaheadParser, $log, $typeaheadSuppressWarning) {
+ if (!$typeaheadSuppressWarning) {
+ $log.warn('typeaheadParser is now deprecated. Use uibTypeaheadParser instead.');
+ }
+
+ return uibTypeaheadParser;
+ }])
+
+ .directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$window', '$rootScope', '$uibPosition', 'typeaheadParser', '$log', '$typeaheadSuppressWarning',
+ function($compile, $parse, $q, $timeout, $document, $window, $rootScope, $position, typeaheadParser, $log, $typeaheadSuppressWarning) {
+ var HOT_KEYS = [9, 13, 27, 38, 40];
+ var eventDebounceTime = 200;
+ return {
+ require: ['ngModel', '^?ngModelOptions'],
+ link: function(originalScope, element, attrs, ctrls) {
+ if (!$typeaheadSuppressWarning) {
+ $log.warn('typeahead is now deprecated. Use uib-typeahead instead.');
+ }
+ var modelCtrl = ctrls[0];
+ var ngModelOptions = ctrls[1];
+ //SUPPORTED ATTRIBUTES (OPTIONS)
+
+ //minimal no of characters that needs to be entered before typeahead kicks-in
+ var minLength = originalScope.$eval(attrs.typeaheadMinLength);
+ if (!minLength && minLength !== 0) {
+ minLength = 1;
+ }
+
+ //minimal wait time after last character typed before typeahead kicks-in
+ var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0;
+
+ //should it restrict model values to the ones selected from the popup only?
+ var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false;
+
+ //binding to a variable that indicates if matches are being retrieved asynchronously
+ var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;
+
+ //a callback executed when a match is selected
+ var onSelectCallback = $parse(attrs.typeaheadOnSelect);
+
+ //should it select highlighted popup value when losing focus?
+ var isSelectOnBlur = angular.isDefined(attrs.typeaheadSelectOnBlur) ? originalScope.$eval(attrs.typeaheadSelectOnBlur) : false;
+
+ //binding to a variable that indicates if there were no results after the query is completed
+ var isNoResultsSetter = $parse(attrs.typeaheadNoResults).assign || angular.noop;
+
+ var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;
+
+ var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false;
+
+ var appendToElementId = attrs.typeaheadAppendToElementId || false;
+
+ var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false;
+
+ //If input matches an item of the list exactly, select it automatically
+ var selectOnExact = attrs.typeaheadSelectOnExact ? originalScope.$eval(attrs.typeaheadSelectOnExact) : false;
+
+ //INTERNAL VARIABLES
+
+ //model setter executed upon match selection
+ var parsedModel = $parse(attrs.ngModel);
+ var invokeModelSetter = $parse(attrs.ngModel + '($$$p)');
+ var $setModelValue = function(scope, newValue) {
+ if (angular.isFunction(parsedModel(originalScope)) &&
+ ngModelOptions && ngModelOptions.$options && ngModelOptions.$options.getterSetter) {
+ return invokeModelSetter(scope, {$$$p: newValue});
+ } else {
+ return parsedModel.assign(scope, newValue);
+ }
+ };
+
+ //expressions used by typeahead
+ var parserResult = typeaheadParser.parse(attrs.typeahead);
+
+ var hasFocus;
+
+ //Used to avoid bug in iOS webview where iOS keyboard does not fire
+ //mousedown & mouseup events
+ //Issue #3699
+ var selected;
+
+ //create a child scope for the typeahead directive so we are not polluting original scope
+ //with typeahead-specific data (matches, query etc.)
+ var scope = originalScope.$new();
+ var offDestroy = originalScope.$on('$destroy', function() {
+ scope.$destroy();
+ });
+ scope.$on('$destroy', offDestroy);
+
+ // WAI-ARIA
+ var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000);
+ element.attr({
+ 'aria-autocomplete': 'list',
+ 'aria-expanded': false,
+ 'aria-owns': popupId
+ });
+
+ //pop-up element used to display matches
+ var popUpEl = angular.element('<div typeahead-popup></div>');
+ popUpEl.attr({
+ id: popupId,
+ matches: 'matches',
+ active: 'activeIdx',
+ select: 'select(activeIdx)',
+ 'move-in-progress': 'moveInProgress',
+ query: 'query',
+ position: 'position'
+ });
+ //custom item template
+ if (angular.isDefined(attrs.typeaheadTemplateUrl)) {
+ popUpEl.attr('template-url', attrs.typeaheadTemplateUrl);
+ }
+
+ if (angular.isDefined(attrs.typeaheadPopupTemplateUrl)) {
+ popUpEl.attr('popup-template-url', attrs.typeaheadPopupTemplateUrl);
+ }
+
+ var resetMatches = function() {
+ scope.matches = [];
+ scope.activeIdx = -1;
+ element.attr('aria-expanded', false);
+ };
+
+ var getMatchId = function(index) {
+ return popupId + '-option-' + index;
+ };
+
+ // Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead.
+ // This attribute is added or removed automatically when the `activeIdx` changes.
+ scope.$watch('activeIdx', function(index) {
+ if (index < 0) {
+ element.removeAttr('aria-activedescendant');
+ } else {
+ element.attr('aria-activedescendant', getMatchId(index));
+ }
+ });
+
+ var inputIsExactMatch = function(inputValue, index) {
+ if (scope.matches.length > index && inputValue) {
+ return inputValue.toUpperCase() === scope.matches[index].label.toUpperCase();
+ }
+
+ return false;
+ };
+
+ var getMatchesAsync = function(inputValue) {
+ var locals = {$viewValue: inputValue};
+ isLoadingSetter(originalScope, true);
+ isNoResultsSetter(originalScope, false);
+ $q.when(parserResult.source(originalScope, locals)).then(function(matches) {
+ //it might happen that several async queries were in progress if a user were typing fast
+ //but we are interested only in responses that correspond to the current view value
+ var onCurrentRequest = (inputValue === modelCtrl.$viewValue);
+ if (onCurrentRequest && hasFocus) {
+ if (matches && matches.length > 0) {
+ scope.activeIdx = focusFirst ? 0 : -1;
+ isNoResultsSetter(originalScope, false);
+ scope.matches.length = 0;
+
+ //transform labels
+ for (var i = 0; i < matches.length; i++) {
+ locals[parserResult.itemName] = matches[i];
+ scope.matches.push({
+ id: getMatchId(i),
+ label: parserResult.viewMapper(scope, locals),
+ model: matches[i]
+ });
+ }
+
+ scope.query = inputValue;
+ //position pop-up with matches - we need to re-calculate its position each time we are opening a window
+ //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
+ //due to other elements being rendered
+ recalculatePosition();
+
+ element.attr('aria-expanded', true);
+
+ //Select the single remaining option if user input matches
+ if (selectOnExact && scope.matches.length === 1 && inputIsExactMatch(inputValue, 0)) {
+ scope.select(0);
+ }
+ } else {
+ resetMatches();
+ isNoResultsSetter(originalScope, true);
+ }
+ }
+ if (onCurrentRequest) {
+ isLoadingSetter(originalScope, false);
+ }
+ }, function() {
+ resetMatches();
+ isLoadingSetter(originalScope, false);
+ isNoResultsSetter(originalScope, true);
+ });
+ };
+
+ // bind events only if appendToBody params exist - performance feature
+ if (appendToBody) {
+ angular.element($window).bind('resize', fireRecalculating);
+ $document.find('body').bind('scroll', fireRecalculating);
+ }
+
+ // Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
+ var timeoutEventPromise;
+
+ // Default progress type
+ scope.moveInProgress = false;
+
+ function fireRecalculating() {
+ if (!scope.moveInProgress) {
+ scope.moveInProgress = true;
+ scope.$digest();
+ }
+
+ // Cancel previous timeout
+ if (timeoutEventPromise) {
+ $timeout.cancel(timeoutEventPromise);
+ }
+
+ // Debounced executing recalculate after events fired
+ timeoutEventPromise = $timeout(function() {
+ // if popup is visible
+ if (scope.matches.length) {
+ recalculatePosition();
+ }
+
+ scope.moveInProgress = false;
+ }, eventDebounceTime);
+ }
+
+ // recalculate actual position and set new values to scope
+ // after digest loop is popup in right position
+ function recalculatePosition() {
+ scope.position = appendToBody ? $position.offset(element) : $position.position(element);
+ scope.position.top += element.prop('offsetHeight');
+ }
+
+ resetMatches();
+
+ //we need to propagate user's query so we can higlight matches
+ scope.query = undefined;
+
+ //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
+ var timeoutPromise;
+
+ var scheduleSearchWithTimeout = function(inputValue) {
+ timeoutPromise = $timeout(function() {
+ getMatchesAsync(inputValue);
+ }, waitTime);
+ };
+
+ var cancelPreviousTimeout = function() {
+ if (timeoutPromise) {
+ $timeout.cancel(timeoutPromise);
+ }
+ };
+
+ //plug into $parsers pipeline to open a typeahead on view changes initiated from DOM
+ //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
+ modelCtrl.$parsers.unshift(function(inputValue) {
+ hasFocus = true;
+
+ if (minLength === 0 || inputValue && inputValue.length >= minLength) {
+ if (waitTime > 0) {
+ cancelPreviousTimeout();
+ scheduleSearchWithTimeout(inputValue);
+ } else {
+ getMatchesAsync(inputValue);
+ }
+ } else {
+ isLoadingSetter(originalScope, false);
+ cancelPreviousTimeout();
+ resetMatches();
+ }
+
+ if (isEditable) {
+ return inputValue;
+ } else {
+ if (!inputValue) {
+ // Reset in case user had typed something previously.
+ modelCtrl.$setValidity('editable', true);
+ return null;
+ } else {
+ modelCtrl.$setValidity('editable', false);
+ return undefined;
+ }
+ }
+ });
+
+ modelCtrl.$formatters.push(function(modelValue) {
+ var candidateViewValue, emptyViewValue;
+ var locals = {};
+
+ // The validity may be set to false via $parsers (see above) if
+ // the model is restricted to selected values. If the model
+ // is set manually it is considered to be valid.
+ if (!isEditable) {
+ modelCtrl.$setValidity('editable', true);
+ }
+
+ if (inputFormatter) {
+ locals.$model = modelValue;
+ return inputFormatter(originalScope, locals);
+ } else {
+ //it might happen that we don't have enough info to properly render input value
+ //we need to check for this situation and simply return model value if we can't apply custom formatting
+ locals[parserResult.itemName] = modelValue;
+ candidateViewValue = parserResult.viewMapper(originalScope, locals);
+ locals[parserResult.itemName] = undefined;
+ emptyViewValue = parserResult.viewMapper(originalScope, locals);
+
+ return candidateViewValue !== emptyViewValue ? candidateViewValue : modelValue;
+ }
+ });
+
+ scope.select = function(activeIdx) {
+ //called from within the $digest() cycle
+ var locals = {};
+ var model, item;
+
+ selected = true;
+ locals[parserResult.itemName] = item = scope.matches[activeIdx].model;
+ model = parserResult.modelMapper(originalScope, locals);
+ $setModelValue(originalScope, model);
+ modelCtrl.$setValidity('editable', true);
+ modelCtrl.$setValidity('parse', true);
+
+ onSelectCallback(originalScope, {
+ $item: item,
+ $model: model,
+ $label: parserResult.viewMapper(originalScope, locals)
+ });
+
+ resetMatches();
+
+ //return focus to the input element if a match was selected via a mouse click event
+ // use timeout to avoid $rootScope:inprog error
+ if (scope.$eval(attrs.typeaheadFocusOnSelect) !== false) {
+ $timeout(function() { element[0].focus(); }, 0, false);
+ }
+ };
+
+ //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
+ element.bind('keydown', function(evt) {
+ //typeahead is open and an "interesting" key was pressed
+ if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
+ return;
+ }
+
+ // if there's nothing selected (i.e. focusFirst) and enter or tab is hit, clear the results
+ if (scope.activeIdx === -1 && (evt.which === 9 || evt.which === 13)) {
+ resetMatches();
+ scope.$digest();
+ return;
+ }
+
+ evt.preventDefault();
+
+ if (evt.which === 40) {
+ scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
+ scope.$digest();
+ } else if (evt.which === 38) {
+ scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1;
+ scope.$digest();
+ } else if (evt.which === 13 || evt.which === 9) {
+ scope.$apply(function () {
+ scope.select(scope.activeIdx);
+ });
+ } else if (evt.which === 27) {
+ evt.stopPropagation();
+
+ resetMatches();
+ scope.$digest();
+ }
+ });
+
+ element.bind('blur', function() {
+ if (isSelectOnBlur && scope.matches.length && scope.activeIdx !== -1 && !selected) {
+ selected = true;
+ scope.$apply(function() {
+ scope.select(scope.activeIdx);
+ });
+ }
+ hasFocus = false;
+ selected = false;
+ });
+
+ // Keep reference to click handler to unbind it.
+ var dismissClickHandler = function(evt) {
+ // Issue #3973
+ // Firefox treats right click as a click on document
+ if (element[0] !== evt.target && evt.which !== 3 && scope.matches.length !== 0) {
+ resetMatches();
+ if (!$rootScope.$$phase) {
+ scope.$digest();
+ }
+ }
+ };
+
+ $document.bind('click', dismissClickHandler);
+
+ originalScope.$on('$destroy', function() {
+ $document.unbind('click', dismissClickHandler);
+ if (appendToBody || appendToElementId) {
+ $popup.remove();
+ }
+
+ if (appendToBody) {
+ angular.element($window).unbind('resize', fireRecalculating);
+ $document.find('body').unbind('scroll', fireRecalculating);
+ }
+ // Prevent jQuery cache memory leak
+ popUpEl.remove();
+ });
+
+ var $popup = $compile(popUpEl)(scope);
+
+ if (appendToBody) {
+ $document.find('body').append($popup);
+ } else if (appendToElementId !== false) {
+ angular.element($document[0].getElementById(appendToElementId)).append($popup);
+ } else {
+ element.after($popup);
+ }
+ }
+ };
+ }])
+
+ .directive('typeaheadPopup', ['$typeaheadSuppressWarning', '$log', function($typeaheadSuppressWarning, $log) {
+ return {
+ scope: {
+ matches: '=',
+ query: '=',
+ active: '=',
+ position: '&',
+ moveInProgress: '=',
+ select: '&'
+ },
+ replace: true,
+ templateUrl: function(element, attrs) {
+ return attrs.popupTemplateUrl || 'template/typeahead/typeahead-popup.html';
+ },
+ link: function(scope, element, attrs) {
+
+ if (!$typeaheadSuppressWarning) {
+ $log.warn('typeahead-popup is now deprecated. Use uib-typeahead-popup instead.');
+ }
+ scope.templateUrl = attrs.templateUrl;
+
+ scope.isOpen = function() {
+ return scope.matches.length > 0;
+ };
+
+ scope.isActive = function(matchIdx) {
+ return scope.active == matchIdx;
+ };
+
+ scope.selectActive = function(matchIdx) {
+ scope.active = matchIdx;
+ };
+
+ scope.selectMatch = function(activeIdx) {
+ scope.select({activeIdx:activeIdx});
+ };
+ }
+ };
+ }])
+
+ .directive('typeaheadMatch', ['$templateRequest', '$compile', '$parse', '$typeaheadSuppressWarning', '$log', function($templateRequest, $compile, $parse, $typeaheadSuppressWarning, $log) {
+ return {
+ restrict: 'EA',
+ scope: {
+ index: '=',
+ match: '=',
+ query: '='
+ },
+ link:function(scope, element, attrs) {
+ if (!$typeaheadSuppressWarning) {
+ $log.warn('typeahead-match is now deprecated. Use uib-typeahead-match instead.');
+ }
+
+ var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html';
+ $templateRequest(tplUrl).then(function(tplContent) {
+ $compile(tplContent.trim())(scope, function(clonedElement) {
+ element.replaceWith(clonedElement);
+ });
+ });
+ }
+ };
+ }])
+
+ .filter('typeaheadHighlight', ['$sce', '$injector', '$log', '$typeaheadSuppressWarning', function($sce, $injector, $log, $typeaheadSuppressWarning) {
+ var isSanitizePresent;
+ isSanitizePresent = $injector.has('$sanitize');
+
+ function escapeRegexp(queryToEscape) {
+ // Regex: capture the whole query string and replace it with the string that will be used to match
+ // the results, for example if the capture is "a" the result will be \a
+ return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
+ }
+
+ function containsHtml(matchItem) {
+ return /<.*>/g.test(matchItem);
+ }
+
+ return function(matchItem, query) {
+ if (!$typeaheadSuppressWarning) {
+ $log.warn('typeaheadHighlight is now deprecated. Use uibTypeaheadHighlight instead.');
+ }
+
+ if (!isSanitizePresent && containsHtml(matchItem)) {
+ $log.warn('Unsafe use of typeahead please use ngSanitize'); // Warn the user about the danger
+ }
+
+ matchItem = query? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem; // Replaces the capture string with a the same string inside of a "strong" tag
+ if (!isSanitizePresent) {
+ matchItem = $sce.trustAsHtml(matchItem); // If $sanitize is not present we pack the string in a $sce object for the ng-bind-html directive
+ }
+
+ return matchItem;
+ };
+ }]);
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/accordion/accordion-group.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/accordion/accordion-group.html
new file mode 100644
index 0000000..1dc4c8e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/accordion/accordion-group.html
@@ -0,0 +1,10 @@
+<div class="panel {{panelClass || 'panel-default'}}">
+ <div class="panel-heading" ng-keypress="toggleOpen($event)">
+ <h4 class="panel-title">
+ <a href tabindex="0" class="accordion-toggle" ng-click="toggleOpen()" uib-accordion-transclude="heading"><span ng-class="{'text-muted': isDisabled}">{{heading}}</span></a>
+ </h4>
+ </div>
+ <div class="panel-collapse collapse" uib-collapse="!isOpen">
+ <div class="panel-body" ng-transclude></div>
+ </div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/accordion/accordion.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/accordion/accordion.html
new file mode 100644
index 0000000..ba428f3
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/accordion/accordion.html
@@ -0,0 +1 @@
+<div class="panel-group" ng-transclude></div>
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/alert/alert.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/alert/alert.html
new file mode 100644
index 0000000..0885587
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/alert/alert.html
@@ -0,0 +1,7 @@
+<div class="alert" ng-class="['alert-' + (type || 'warning'), closeable ? 'alert-dismissible' : null]" role="alert">
+ <button ng-show="closeable" type="button" class="close" ng-click="close({$event: $event})">
+ <span aria-hidden="true">×</span>
+ <span class="sr-only">Close</span>
+ </button>
+ <div ng-transclude></div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/carousel/carousel.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/carousel/carousel.html
new file mode 100644
index 0000000..372c547
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/carousel/carousel.html
@@ -0,0 +1,16 @@
+<div ng-mouseenter="pause()" ng-mouseleave="play()" class="carousel" ng-swipe-right="prev()" ng-swipe-left="next()">
+ <div class="carousel-inner" ng-transclude></div>
+ <a role="button" href class="left carousel-control" ng-click="prev()" ng-show="slides.length > 1">
+ <span aria-hidden="true" class="glyphicon glyphicon-chevron-left"></span>
+ <span class="sr-only">previous</span>
+ </a>
+ <a role="button" href class="right carousel-control" ng-click="next()" ng-show="slides.length > 1">
+ <span aria-hidden="true" class="glyphicon glyphicon-chevron-right"></span>
+ <span class="sr-only">next</span>
+ </a>
+ <ol class="carousel-indicators" ng-show="slides.length > 1">
+ <li ng-repeat="slide in slides | orderBy:indexOfSlide track by $index" ng-class="{ active: isActive(slide) }" ng-click="select(slide)">
+ <span class="sr-only">slide {{ $index + 1 }} of {{ slides.length }}<span ng-if="isActive(slide)">, currently active</span></span>
+ </li>
+ </ol>
+</div>
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/carousel/slide.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/carousel/slide.html
new file mode 100644
index 0000000..5220139
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/carousel/slide.html
@@ -0,0 +1,3 @@
+<div ng-class="{
+ 'active': active
+ }" class="item text-center" ng-transclude></div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/datepicker.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/datepicker.html
new file mode 100644
index 0000000..d515832
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/datepicker.html
@@ -0,0 +1,5 @@
+<div ng-switch="datepickerMode" role="application" ng-keydown="keydown($event)">
+ <uib-daypicker ng-switch-when="day" tabindex="0"></uib-daypicker>
+ <uib-monthpicker ng-switch-when="month" tabindex="0"></uib-monthpicker>
+ <uib-yearpicker ng-switch-when="year" tabindex="0"></uib-yearpicker>
+</div>
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/day.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/day.html
new file mode 100644
index 0000000..91cf57a
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/day.html
@@ -0,0 +1,21 @@
+<table role="grid" aria-labelledby="{{::uniqueId}}-title" aria-activedescendant="{{activeDateId}}">
+ <thead>
+ <tr>
+ <th><button type="button" class="btn btn-default btn-sm pull-left" ng-click="move(-1)" tabindex="-1"><i class="glyphicon glyphicon-chevron-left"></i></button></th>
+ <th colspan="{{::5 + showWeeks}}"><button id="{{::uniqueId}}-title" role="heading" aria-live="assertive" aria-atomic="true" type="button" class="btn btn-default btn-sm" ng-click="toggleMode()" ng-disabled="datepickerMode === maxMode" tabindex="-1" style="width:100%;"><strong>{{title}}</strong></button></th>
+ <th><button type="button" class="btn btn-default btn-sm pull-right" ng-click="move(1)" tabindex="-1"><i class="glyphicon glyphicon-chevron-right"></i></button></th>
+ </tr>
+ <tr>
+ <th ng-if="showWeeks" class="text-center"></th>
+ <th ng-repeat="label in ::labels track by $index" class="text-center"><small aria-label="{{::label.full}}">{{::label.abbr}}</small></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr ng-repeat="row in rows track by $index">
+ <td ng-if="showWeeks" class="text-center h6"><em>{{ weekNumbers[$index] }}</em></td>
+ <td ng-repeat="dt in row track by dt.date" class="text-center" role="gridcell" id="{{::dt.uid}}" ng-class="::dt.customClass">
+ <button type="button" style="min-width:100%;" class="btn btn-default btn-sm" ng-class="{'btn-info': dt.selected, active: isActive(dt)}" ng-click="select(dt.date)" ng-disabled="dt.disabled" tabindex="-1"><span ng-class="::{'text-muted': dt.secondary, 'text-info': dt.current}">{{::dt.label}}</span></button>
+ </td>
+ </tr>
+ </tbody>
+</table>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/month.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/month.html
new file mode 100644
index 0000000..cebd053
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/month.html
@@ -0,0 +1,16 @@
+<table role="grid" aria-labelledby="{{::uniqueId}}-title" aria-activedescendant="{{activeDateId}}">
+ <thead>
+ <tr>
+ <th><button type="button" class="btn btn-default btn-sm pull-left" ng-click="move(-1)" tabindex="-1"><i class="glyphicon glyphicon-chevron-left"></i></button></th>
+ <th><button id="{{::uniqueId}}-title" role="heading" aria-live="assertive" aria-atomic="true" type="button" class="btn btn-default btn-sm" ng-click="toggleMode()" ng-disabled="datepickerMode === maxMode" tabindex="-1" style="width:100%;"><strong>{{title}}</strong></button></th>
+ <th><button type="button" class="btn btn-default btn-sm pull-right" ng-click="move(1)" tabindex="-1"><i class="glyphicon glyphicon-chevron-right"></i></button></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr ng-repeat="row in rows track by $index">
+ <td ng-repeat="dt in row track by dt.date" class="text-center" role="gridcell" id="{{::dt.uid}}" ng-class="::dt.customClass">
+ <button type="button" style="min-width:100%;" class="btn btn-default" ng-class="{'btn-info': dt.selected, active: isActive(dt)}" ng-click="select(dt.date)" ng-disabled="dt.disabled" tabindex="-1"><span ng-class="::{'text-info': dt.current}">{{::dt.label}}</span></button>
+ </td>
+ </tr>
+ </tbody>
+</table>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/popup.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/popup.html
new file mode 100644
index 0000000..e3dda67
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/popup.html
@@ -0,0 +1,10 @@
+<ul class="dropdown-menu" dropdown-nested ng-if="isOpen" style="display: block" ng-style="{top: position.top+'px', left: position.left+'px'}" ng-keydown="keydown($event)" ng-click="$event.stopPropagation()">
+ <li ng-transclude></li>
+ <li ng-if="showButtonBar" style="padding:10px 9px 2px">
+ <span class="btn-group pull-left">
+ <button type="button" class="btn btn-sm btn-info" ng-click="select('today')" ng-disabled="isDisabled('today')">{{ getText('current') }}</button>
+ <button type="button" class="btn btn-sm btn-danger" ng-click="select(null)">{{ getText('clear') }}</button>
+ </span>
+ <button type="button" class="btn btn-sm btn-success pull-right" ng-click="close()">{{ getText('close') }}</button>
+ </li>
+</ul>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/year.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/year.html
new file mode 100644
index 0000000..8606f0d
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/datepicker/year.html
@@ -0,0 +1,16 @@
+<table role="grid" aria-labelledby="{{::uniqueId}}-title" aria-activedescendant="{{activeDateId}}">
+ <thead>
+ <tr>
+ <th><button type="button" class="btn btn-default btn-sm pull-left" ng-click="move(-1)" tabindex="-1"><i class="glyphicon glyphicon-chevron-left"></i></button></th>
+ <th colspan="3"><button id="{{::uniqueId}}-title" role="heading" aria-live="assertive" aria-atomic="true" type="button" class="btn btn-default btn-sm" ng-click="toggleMode()" ng-disabled="datepickerMode === maxMode" tabindex="-1" style="width:100%;"><strong>{{title}}</strong></button></th>
+ <th><button type="button" class="btn btn-default btn-sm pull-right" ng-click="move(1)" tabindex="-1"><i class="glyphicon glyphicon-chevron-right"></i></button></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr ng-repeat="row in rows track by $index">
+ <td ng-repeat="dt in row track by dt.date" class="text-center" role="gridcell" id="{{::dt.uid}}" ng-class="::dt.customClass">
+ <button type="button" style="min-width:100%;" class="btn btn-default" ng-class="{'btn-info': dt.selected, active: isActive(dt)}" ng-click="select(dt.date)" ng-disabled="dt.disabled" tabindex="-1"><span ng-class="::{'text-info': dt.current}">{{::dt.label}}</span></button>
+ </td>
+ </tr>
+ </tbody>
+</table>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/modal/backdrop.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/modal/backdrop.html
new file mode 100644
index 0000000..214273e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/modal/backdrop.html
@@ -0,0 +1,4 @@
+<div uib-modal-animation-class="fade"
+ modal-in-class="in"
+ ng-style="{'z-index': 1040 + (index && 1 || 0) + index*10}"
+></div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/modal/window.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/modal/window.html
new file mode 100644
index 0000000..ae17e40
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/modal/window.html
@@ -0,0 +1,6 @@
+<div modal-render="{{$isRendered}}" tabindex="-1" role="dialog" class="modal"
+ uib-modal-animation-class="fade"
+ modal-in-class="in"
+ ng-style="{'z-index': 1050 + index*10, display: 'block'}">
+ <div class="modal-dialog" ng-class="size ? 'modal-' + size : ''"><div class="modal-content" uib-modal-transclude></div></div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/pagination/pager.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/pagination/pager.html
new file mode 100644
index 0000000..46f227f
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/pagination/pager.html
@@ -0,0 +1,4 @@
+<ul class="pager">
+ <li ng-class="{disabled: noPrevious()||ngDisabled, previous: align}"><a href ng-click="selectPage(page - 1, $event)">{{::getText('previous')}}</a></li>
+ <li ng-class="{disabled: noNext()||ngDisabled, next: align}"><a href ng-click="selectPage(page + 1, $event)">{{::getText('next')}}</a></li>
+</ul>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/pagination/pagination.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/pagination/pagination.html
new file mode 100644
index 0000000..f55a7b6
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/pagination/pagination.html
@@ -0,0 +1,7 @@
+<ul class="pagination">
+ <li ng-if="::boundaryLinks" ng-class="{disabled: noPrevious()||ngDisabled}" class="pagination-first"><a href ng-click="selectPage(1, $event)">{{::getText('first')}}</a></li>
+ <li ng-if="::directionLinks" ng-class="{disabled: noPrevious()||ngDisabled}" class="pagination-prev"><a href ng-click="selectPage(page - 1, $event)">{{::getText('previous')}}</a></li>
+ <li ng-repeat="page in pages track by $index" ng-class="{active: page.active,disabled: ngDisabled&&!page.active}" class="pagination-page"><a href ng-click="selectPage(page.number, $event)">{{page.text}}</a></li>
+ <li ng-if="::directionLinks" ng-class="{disabled: noNext()||ngDisabled}" class="pagination-next"><a href ng-click="selectPage(page + 1, $event)">{{::getText('next')}}</a></li>
+ <li ng-if="::boundaryLinks" ng-class="{disabled: noNext()||ngDisabled}" class="pagination-last"><a href ng-click="selectPage(totalPages, $event)">{{::getText('last')}}</a></li>
+</ul>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/popover/popover-html.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/popover/popover-html.html
new file mode 100644
index 0000000..3751ca8
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/popover/popover-html.html
@@ -0,0 +1,10 @@
+<div tooltip-animation-class="fade"
+ uib-tooltip-classes
+ ng-class="{ in: isOpen() }">
+ <div class="arrow"></div>
+
+ <div class="popover-inner">
+ <h3 class="popover-title" ng-bind="title" ng-if="title"></h3>
+ <div class="popover-content" ng-bind-html="contentExp()"></div>
+ </div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/popover/popover-template.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/popover/popover-template.html
new file mode 100644
index 0000000..914d1d4
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/popover/popover-template.html
@@ -0,0 +1,12 @@
+<div tooltip-animation-class="fade"
+ uib-tooltip-classes
+ ng-class="{ in: isOpen() }">
+ <div class="arrow"></div>
+
+ <div class="popover-inner">
+ <h3 class="popover-title" ng-bind="title" ng-if="title"></h3>
+ <div class="popover-content"
+ uib-tooltip-template-transclude="contentExp()"
+ tooltip-template-transclude-scope="originScope()"></div>
+ </div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/popover/popover.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/popover/popover.html
new file mode 100644
index 0000000..91a7883
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/popover/popover.html
@@ -0,0 +1,10 @@
+<div tooltip-animation-class="fade"
+ uib-tooltip-classes
+ ng-class="{ in: isOpen() }">
+ <div class="arrow"></div>
+
+ <div class="popover-inner">
+ <h3 class="popover-title" ng-bind="title" ng-if="title"></h3>
+ <div class="popover-content" ng-bind="content"></div>
+ </div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/progressbar/bar.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/progressbar/bar.html
new file mode 100644
index 0000000..b5b61e0
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/progressbar/bar.html
@@ -0,0 +1 @@
+<div class="progress-bar" ng-class="type && 'progress-bar-' + type" role="progressbar" aria-valuenow="{{value}}" aria-valuemin="0" aria-valuemax="{{max}}" ng-style="{width: (percent < 100 ? percent : 100) + '%'}" aria-valuetext="{{percent | number:0}}%" aria-labelledby="{{::title}}" style="min-width: 0;" ng-transclude></div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/progressbar/progress.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/progressbar/progress.html
new file mode 100644
index 0000000..38ee9f7
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/progressbar/progress.html
@@ -0,0 +1 @@
+<div class="progress" ng-transclude aria-labelledby="{{::title}}"></div>
\ No newline at end of file
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/progressbar/progressbar.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/progressbar/progressbar.html
new file mode 100644
index 0000000..dbfa5aa
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/progressbar/progressbar.html
@@ -0,0 +1,3 @@
+<div class="progress">
+ <div class="progress-bar" ng-class="type && 'progress-bar-' + type" role="progressbar" aria-valuenow="{{value}}" aria-valuemin="0" aria-valuemax="{{max}}" ng-style="{width: (percent < 100 ? percent : 100) + '%'}" aria-valuetext="{{percent | number:0}}%" aria-labelledby="{{::title}}" style="min-width: 0;" ng-transclude></div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/rating/rating.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/rating/rating.html
new file mode 100644
index 0000000..5543b03
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/rating/rating.html
@@ -0,0 +1,4 @@
+<span ng-mouseleave="reset()" ng-keydown="onKeydown($event)" tabindex="0" role="slider" aria-valuemin="0" aria-valuemax="{{range.length}}" aria-valuenow="{{value}}">
+ <span ng-repeat-start="r in range track by $index" class="sr-only">({{ $index < value ? '*' : ' ' }})</span>
+ <i ng-repeat-end ng-mouseenter="enter($index + 1)" ng-click="rate($index + 1)" class="glyphicon" ng-class="$index < value && (r.stateOn || 'glyphicon-star') || (r.stateOff || 'glyphicon-star-empty')" ng-attr-title="{{r.title}}" aria-valuetext="{{r.title}}"></i>
+</span>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tabs/tab.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tabs/tab.html
new file mode 100644
index 0000000..0d8a42e
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tabs/tab.html
@@ -0,0 +1,3 @@
+<li ng-class="{active: active, disabled: disabled}">
+ <a href ng-click="select()" uib-tab-heading-transclude>{{heading}}</a>
+</li>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tabs/tabset.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tabs/tabset.html
new file mode 100644
index 0000000..294c86a
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tabs/tabset.html
@@ -0,0 +1,10 @@
+<div>
+ <ul class="nav nav-{{type || 'tabs'}}" ng-class="{'nav-stacked': vertical, 'nav-justified': justified}" ng-transclude></ul>
+ <div class="tab-content">
+ <div class="tab-pane"
+ ng-repeat="tab in tabs"
+ ng-class="{active: tab.active}"
+ uib-tab-content-transclude="tab">
+ </div>
+ </div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/timepicker/timepicker.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/timepicker/timepicker.html
new file mode 100644
index 0000000..1873841
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/timepicker/timepicker.html
@@ -0,0 +1,26 @@
+<table>
+ <tbody>
+ <tr class="text-center" ng-show="::showSpinners">
+ <td><a ng-click="incrementHours()" ng-class="{disabled: noIncrementHours()}" class="btn btn-link" ng-disabled="noIncrementHours()" tabindex="{{::tabindex}}"><span class="glyphicon glyphicon-chevron-up"></span></a></td>
+ <td> </td>
+ <td><a ng-click="incrementMinutes()" ng-class="{disabled: noIncrementMinutes()}" class="btn btn-link" ng-disabled="noIncrementMinutes()" tabindex="{{::tabindex}}"><span class="glyphicon glyphicon-chevron-up"></span></a></td>
+ <td ng-show="showMeridian"></td>
+ </tr>
+ <tr>
+ <td class="form-group" ng-class="{'has-error': invalidHours}">
+ <input style="width:50px;" type="text" ng-model="hours" ng-change="updateHours()" class="form-control text-center" ng-readonly="::readonlyInput" maxlength="2" tabindex="{{::tabindex}}">
+ </td>
+ <td>:</td>
+ <td class="form-group" ng-class="{'has-error': invalidMinutes}">
+ <input style="width:50px;" type="text" ng-model="minutes" ng-change="updateMinutes()" class="form-control text-center" ng-readonly="::readonlyInput" maxlength="2" tabindex="{{::tabindex}}">
+ </td>
+ <td ng-show="showMeridian"><button type="button" ng-class="{disabled: noToggleMeridian()}" class="btn btn-default text-center" ng-click="toggleMeridian()" ng-disabled="noToggleMeridian()" tabindex="{{::tabindex}}">{{meridian}}</button></td>
+ </tr>
+ <tr class="text-center" ng-show="::showSpinners">
+ <td><a ng-click="decrementHours()" ng-class="{disabled: noDecrementHours()}" class="btn btn-link" ng-disabled="noDecrementHours()" tabindex="{{::tabindex}}"><span class="glyphicon glyphicon-chevron-down"></span></a></td>
+ <td> </td>
+ <td><a ng-click="decrementMinutes()" ng-class="{disabled: noDecrementMinutes()}" class="btn btn-link" ng-disabled="noDecrementMinutes()" tabindex="{{::tabindex}}"><span class="glyphicon glyphicon-chevron-down"></span></a></td>
+ <td ng-show="showMeridian"></td>
+ </tr>
+ </tbody>
+</table>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tooltip/tooltip-html-popup.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tooltip/tooltip-html-popup.html
new file mode 100644
index 0000000..dae22b7
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tooltip/tooltip-html-popup.html
@@ -0,0 +1,7 @@
+<div
+ tooltip-animation-class="fade"
+ uib-tooltip-classes
+ ng-class="{ in: isOpen() }">
+ <div class="tooltip-arrow"></div>
+ <div class="tooltip-inner" ng-bind-html="contentExp()"></div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tooltip/tooltip-popup.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tooltip/tooltip-popup.html
new file mode 100644
index 0000000..711fc56
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tooltip/tooltip-popup.html
@@ -0,0 +1,7 @@
+<div
+ tooltip-animation-class="fade"
+ uib-tooltip-classes
+ ng-class="{ in: isOpen() }">
+ <div class="tooltip-arrow"></div>
+ <div class="tooltip-inner" ng-bind="content"></div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tooltip/tooltip-template-popup.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tooltip/tooltip-template-popup.html
new file mode 100644
index 0000000..e83bff3
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/tooltip/tooltip-template-popup.html
@@ -0,0 +1,9 @@
+<div
+ tooltip-animation-class="fade"
+ uib-tooltip-classes
+ ng-class="{ in: isOpen() }">
+ <div class="tooltip-arrow"></div>
+ <div class="tooltip-inner"
+ uib-tooltip-template-transclude="contentExp()"
+ tooltip-template-transclude-scope="originScope()"></div>
+</div>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/typeahead/typeahead-match.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/typeahead/typeahead-match.html
new file mode 100644
index 0000000..c64462b
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/typeahead/typeahead-match.html
@@ -0,0 +1 @@
+<a href tabindex="-1" ng-bind-html="match.label | uibTypeaheadHighlight:query"></a>
diff --git a/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/typeahead/typeahead-popup.html b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/typeahead/typeahead-popup.html
new file mode 100644
index 0000000..20a362b
--- /dev/null
+++ b/xos-apps/auto-scale/gui/src/vendor/ui.bootstrap/template/typeahead/typeahead-popup.html
@@ -0,0 +1,5 @@
+<ul class="dropdown-menu" ng-show="isOpen() && !moveInProgress" ng-style="{top: position().top+'px', left: position().left+'px'}" style="display: block;" role="listbox" aria-hidden="{{!isOpen()}}">
+ <li ng-repeat="match in matches track by $index" ng-class="{active: isActive($index) }" ng-mouseenter="selectActive($index)" ng-click="selectMatch($index)" role="option" id="{{::match.id}}">
+ <div uib-typeahead-match index="$index" match="match" query="query" template-url="templateUrl"></div>
+ </li>
+</ul>
diff --git a/xos-apps/auto-scale/xos_auto_scaling_app.py b/xos-apps/auto-scale/xos_auto_scaling_app.py
new file mode 100644
index 0000000..ee51bb3
--- /dev/null
+++ b/xos-apps/auto-scale/xos_auto_scaling_app.py
@@ -0,0 +1,305 @@
+import socket
+import requests
+import urllib2
+import json
+import msgpack
+import collections
+import time, thread, threading
+
+from flask import request, Request, jsonify
+from flask import Flask
+from flask import make_response
+app = Flask(__name__)
+
+projects_map = {}
+xos_tenant_info_map = {}
+xos_instances_info_map = {}
+
+UDP_IP = "0.0.0.0"
+UDP_PORT = 12346
+
+@app.route('/autoscaledata',methods=['GET'])
+def autoscaledata():
+ response = app.make_response(json.dumps(projects_map.values()))
+ response.mimetype="application/json"
+ return response
+
+def acquire_xos_monitoring_channel():
+ url = "http://ctl:9999/xoslib/monitoringchannel/"
+ admin_auth=("padmin@vicci.org", "letmein") # use your XOS username and password
+ monitoring_channels = requests.get(url, auth=admin_auth).json()
+ ceilometer_url = None
+ if not monitoring_channels:
+ print 'SRIKANTH: No monitoring channels for this user...'
+ return None
+ else:
+ monitoring_channel = monitoring_channels[0]
+ while not monitoring_channel['ceilometer_url']:
+ print 'SRIKANTH: Waiting for monitoring channel create'
+ sleep(0.5)
+ monitoring_channel = requests.get(url, auth=admin_auth).json()[0]
+ #TODO: Wait until URL is completely UP
+ while True:
+ print 'SRIKANTH: Waiting for ceilometer proxy URL %s is available' % monitoring_channel['ceilometer_url']
+ try:
+ response = urllib2.urlopen(monitoring_channel['ceilometer_url'],timeout=1)
+ break
+ except urllib2.HTTPError, e:
+ print 'SRIKANTH: HTTP error %s' % e.reason
+ break
+ except urllib2.URLError, e:
+ print 'SRIKANTH: URL error %s' % e.reason
+ pass
+ return monitoring_channel
+
+def print_samples():
+ print ""
+ print ""
+ for project in projects_map.keys():
+ print "service=%s slice=%s, alarm_state=%s" % (projects_map[project]['service'], projects_map[project]['slice'] if projects_map[project]['slice'] else project, projects_map[project]['alarm'])
+ for resource in projects_map[project]['resources'].keys():
+ print "resource=%s" % (projects_map[project]['resources'][resource]['xos_instance_info']['instance_name'] if projects_map[project]['resources'][resource]['xos_instance_info'] else resource)
+ for i in projects_map[project]['resources'][resource]['queue']:
+ print " time=%s val=%s" % ( i['timestamp'],i['counter_volume'])
+
+def periodic_print():
+ print_samples()
+ #Print every 1minute
+ threading.Timer(20, periodic_print).start()
+
+
+CPU_UPPER_THRESHOLD = 80 #80%
+CPU_LOWER_THRESHOLD = 30 #30%
+CPU_THRESHOLD_REPEAT = 3
+INITIAL_STATE = 'normal_config'
+SCALE_UP_EVALUATION = 'scale_up_eval'
+SCALE_DOWN_EVALUATION = 'scale_down_eval'
+SCALE_UP_ALARM = 'scale_up'
+SCALE_DOWN_ALARM = 'scale_down'
+
+def loadAllXosTenantInfo():
+ print "SRIKANTH: Loading all XOS tenant info"
+ url = "http://ctl:9999/xos/controllerslices/"
+ admin_auth=("padmin@vicci.org", "letmein") # use your XOS username and password
+ controller_slices = requests.get(url, auth=admin_auth).json()
+ for cslice in controller_slices:
+ slice = requests.get(cslice['slice'], auth=admin_auth).json()
+ slice_name = slice['humanReadableName']
+ if slice['service']:
+ service = requests.get(slice['service'], auth=admin_auth).json()
+ service_name = service['humanReadableName']
+ else:
+ service_name = None
+ xos_tenant_info_map[cslice['tenant_id']] = {'service':service_name, 'slice':slice_name}
+ print "SRIKANTH: Project: %s Service:%s Slice:%s" % (cslice['tenant_id'],service_name,slice_name)
+
+def loadAllXosInstanceInfo():
+ print "SRIKANTH: Loading all XOS instance info"
+ url = "http://ctl:9999/xos/instances/"
+ admin_auth=("padmin@vicci.org", "letmein") # use your XOS username and password
+ xos_instances = requests.get(url, auth=admin_auth).json()
+ for instance in xos_instances:
+ xos_instances_info_map[instance['instance_uuid']] = {'instance_name':instance['instance_name']}
+
+def getXosTenantInfo(project):
+ xos_tenant_info = xos_tenant_info_map.get(project, None)
+ if xos_tenant_info:
+ return xos_tenant_info
+ else:
+ loadAllXosTenantInfo()
+ xos_tenant_info = xos_tenant_info_map.get(project, None)
+ if not xos_tenant_info:
+ print "SRIKANTH: Project %s has no associated XOS slice" % project
+ return xos_tenant_info
+
+def getXosInstanceInfo(resource):
+ xos_instance_info = xos_instances_info_map.get(resource, None)
+ if xos_instance_info:
+ return xos_instance_info
+ else:
+ loadAllXosInstanceInfo()
+ xos_instance_info = xos_instances_info_map.get(resource, None)
+ if not xos_instance_info:
+ print "SRIKANTH: Resource %s has no associated XOS instance" % project
+ return xos_instance_info
+
+def handle_adjust_scale(project, adjust):
+ if (adjust != 'up') and (adjust != 'down'):
+ print "SRIKANTH: Invalid adjust value %s " % adjust
+ return
+ current_instances = len(projects_map[project]['resources'].keys())
+ if (current_instances <=1 and adjust == 'down'):
+ print "SRIKANTH: %s is running with already minimum instances and can not scale down further " % project
+ return
+ if (current_instances >=2 and adjust == 'up'):
+ print "SRIKANTH: %s is running with already maximum instances and can not scale up further " % project
+ return
+ #xos_tenant = getXosTenantInfo(project)
+ xos_service = projects_map[project]['service']
+ xos_slice = projects_map[project]['slice']
+ if not xos_service or not xos_slice:
+ print "SRIKANTH: Can not handle adjust_scale for Project %s because not associated with any service or slice" % project
+ return
+ print "SRIKANTH: SCALE %s for Project %s, Slice=%s, Service=%s from current=%d to new=%d" % (adjust, project, xos_slice, xos_service, current_instances, current_instances+1 if (adjust=='up') else current_instances-1)
+ query_params = {'service':xos_service, 'slice_hint':xos_slice, 'scale':current_instances+1 if (adjust=='up') else current_instances-1}
+ url = "http://ctl:9999/xoslib/serviceadjustscale/"
+ admin_auth=("padmin@vicci.org", "letmein") # use your XOS username and password
+ response = requests.get(url, params=query_params, auth=admin_auth).json()
+ print "SRIKANTH: XOS adjust_scale response: %s" % response
+
+def periodic_cpu_threshold_evaluator():
+ for project in projects_map.keys():
+ aggregate_cpu_util = sum([resource['queue'][-1]['counter_volume'] \
+ for resource in projects_map[project]['resources'].values()]) \
+ /len(projects_map[project]['resources'].keys())
+
+ if (projects_map[project]['alarm'] == INITIAL_STATE or
+ projects_map[project]['alarm'] == SCALE_UP_ALARM or
+ projects_map[project]['alarm'] == SCALE_DOWN_ALARM):
+ if aggregate_cpu_util > CPU_UPPER_THRESHOLD:
+ projects_map[project]['uthreadshold_count'] = 1
+ projects_map[project]['alarm'] = SCALE_UP_EVALUATION
+ if projects_map[project]['uthreadshold_count'] >= CPU_THRESHOLD_REPEAT:
+ projects_map[project]['alarm'] = SCALE_UP_ALARM
+ handle_adjust_scale(project, 'up')
+ elif aggregate_cpu_util < CPU_LOWER_THRESHOLD:
+ projects_map[project]['lthreadshold_count'] = 1
+ projects_map[project]['alarm'] = SCALE_DOWN_EVALUATION
+ if projects_map[project]['lthreadshold_count'] >= CPU_THRESHOLD_REPEAT:
+ projects_map[project]['alarm'] = SCALE_DOWN_ALARM
+ handle_adjust_scale(project, 'down')
+ else:
+ projects_map[project]['uthreadshold_count'] = 0
+ projects_map[project]['lthreadshold_count'] = 0
+ projects_map[project]['alarm'] = INITIAL_STATE
+ elif projects_map[project]['alarm'] == SCALE_UP_EVALUATION:
+ if aggregate_cpu_util > CPU_UPPER_THRESHOLD:
+ projects_map[project]['uthreadshold_count'] += 1
+ if projects_map[project]['uthreadshold_count'] >= CPU_THRESHOLD_REPEAT:
+ projects_map[project]['alarm'] = SCALE_UP_ALARM
+ handle_adjust_scale(project, 'up')
+ elif aggregate_cpu_util < CPU_LOWER_THRESHOLD:
+ projects_map[project]['lthreadshold_count'] += 1
+ projects_map[project]['alarm'] = SCALE_DOWN_EVALUATION
+ else:
+ projects_map[project]['uthreadshold_count'] = 0
+ projects_map[project]['alarm'] = INITIAL_STATE
+ elif projects_map[project]['alarm'] == SCALE_DOWN_EVALUATION:
+ if aggregate_cpu_util < CPU_LOWER_THRESHOLD:
+ projects_map[project]['lthreadshold_count'] += 1
+ if projects_map[project]['lthreadshold_count'] >= CPU_THRESHOLD_REPEAT:
+ projects_map[project]['alarm'] = SCALE_DOWN_ALARM
+ handle_adjust_scale(project, 'down')
+ elif aggregate_cpu_util > CPU_UPPER_THRESHOLD:
+ projects_map[project]['uthreadshold_count'] += 1
+ projects_map[project]['alarm'] = SCALE_UP_EVALUATION
+ else:
+ projects_map[project]['lthreadshold_count'] = 0
+ projects_map[project]['alarm'] = INITIAL_STATE
+ threading.Timer(20, periodic_cpu_threshold_evaluator).start()
+
+def read_notification_from_ceilometer(host,port):
+ udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
+ udp.bind((host, port))
+
+ while True:
+ data, source = udp.recvfrom(64000)
+ try:
+ sample = msgpack.loads(data, encoding='utf-8')
+ if sample['counter_name'] == 'instance':
+ if 'delete' in sample['resource_metadata']['event_type']:
+ xosTenantInfo = getXosTenantInfo(sample['project_id'])
+ xosResourceInfo = getXosInstanceInfo(sample['resource_id'])
+ print "SRIKANTH: Project %s Instance %s is getting deleted" % (xosTenantInfo['slice'] if xosTenantInfo['slice'] else sample['project_id'],xosResourceInfo)
+ if sample['project_id'] not in projects_map.keys():
+ continue
+ if sample['resource_id'] not in projects_map[sample['project_id']]['resources'].keys():
+ continue
+ projects_map[sample['project_id']]['resources'].pop(sample['resource_id'], None)
+ continue
+ elif sample['counter_name'] != 'cpu_util':
+ continue
+ if sample['project_id'] not in projects_map.keys():
+ projects_map[sample['project_id']] = {}
+ xosTenantInfo = getXosTenantInfo(sample['project_id'])
+ projects_map[sample['project_id']]['project_id'] = sample['project_id']
+ projects_map[sample['project_id']]['slice'] = xosTenantInfo['slice']
+ projects_map[sample['project_id']]['service'] = xosTenantInfo['service']
+ projects_map[sample['project_id']]['resources'] = {}
+ projects_map[sample['project_id']]['uthreadshold_count'] = 0
+ projects_map[sample['project_id']]['lthreadshold_count'] = 0
+ projects_map[sample['project_id']]['alarm'] = INITIAL_STATE
+ resource_map = projects_map[sample['project_id']]['resources']
+ if sample['resource_id'] not in resource_map.keys():
+ resource_map[sample['resource_id']] = {}
+ resource_map[sample['resource_id']]['xos_instance_info'] = getXosInstanceInfo(sample['resource_id'])
+ resource_map[sample['resource_id']]['queue'] = []
+ samples_queue = resource_map[sample['resource_id']]['queue']
+ sample = {'counter_name':sample['counter_name'],
+ 'project_id':sample['project_id'],
+ 'resource_id':sample['resource_id'],
+ 'timestamp':sample['timestamp'],
+ 'counter_unit':sample['counter_unit'],
+ 'counter_volume':sample['counter_volume']}
+ deque = collections.deque(samples_queue, maxlen=10)
+ deque.append(sample)
+ resource_map[sample['resource_id']]['queue'] = list(deque)
+ except Exception as e:
+ print e
+
+def setup_webserver():
+ try:
+ #config = ConfigParser.ConfigParser()
+ #config.read('pub_sub.conf')
+ #webserver_host = config.get('WEB_SERVER','webserver_host')
+ #webserver_port = int (config.get('WEB_SERVER','webserver_port'))
+ #client_host = config.get('CLIENT','client_host')
+ #client_port = int (config.get('CLIENT','client_port'))
+
+ #log_level = config.get('LOGGING','level')
+ #log_file = config.get('LOGGING','filename')
+
+ #level = LEVELS.get(log_level, logging.NOTSET)
+ #logging.basicConfig(filename=log_file,format='%(asctime)s %(levelname)s %(message)s',\
+ # datefmt=_DEFAULT_LOG_DATE_FORMAT,level=level)
+ webserver_host = '0.0.0.0'
+ webserver_port = 9991
+
+ except Exception as e:
+ print("* Error in config file:",e.__str__())
+ logging.error("* Error in confing file:%s",e.__str__())
+ else:
+ app.run(host=webserver_host,port=webserver_port,debug=True, use_reloader=False)
+
+
+def main():
+ monitoring_channel = acquire_xos_monitoring_channel()
+ if not monitoring_channel:
+ print 'SRIKANTH: XOS monitoring_channel is not created... Create it before using this app'
+ return
+ loadAllXosTenantInfo()
+ loadAllXosInstanceInfo()
+ thread.start_new(read_notification_from_ceilometer,(UDP_IP,UDP_PORT,))
+ ceilometer_url = monitoring_channel['ceilometer_url']
+ subscribe_data = {"sub_info":"cpu_util","app_id":"xos_auto_scale","target":"udp://10.11.10.1:12346"}
+ subscribe_url = ceilometer_url + 'v2/subscribe'
+ response = requests.post(subscribe_url, data=json.dumps(subscribe_data))
+ print 'SRIKANTH: Ceilometer meter "cpu_util" Subscription status:%s' % response.text
+ #TODO: Fix the typo in 'sucess'
+ if (not 'sucess' in response.text) and (not 'already exists' in response.text):
+ print 'SRIKANTH: Ceilometer meter "cpu_util" Subscription unsuccessful...Exiting'
+ return
+ subscribe_data = {"sub_info":"instance","app_id":"xos_auto_scale2","target":"udp://10.11.10.1:12346"}
+ subscribe_url = ceilometer_url + 'v2/subscribe'
+ response = requests.post(subscribe_url, data=json.dumps(subscribe_data))
+ print 'SRIKANTH: Ceilometer meter "instance" Subscription status:%s' % response.text
+ #TODO: Fix the typo in 'sucess'
+ if (not 'sucess' in response.text) and (not 'already exists' in response.text):
+ print 'SRIKANTH: Ceilometer meter "instance"Subscription unsuccessful...Exiting'
+ return
+ periodic_cpu_threshold_evaluator()
+ periodic_print()
+ setup_webserver()
+
+if __name__ == "__main__":
+ main()
diff --git a/xos.deps b/xos.deps
deleted file mode 100644
index 6eae1fc..0000000
--- a/xos.deps
+++ /dev/null
@@ -1,47 +0,0 @@
-{
- "Node": [
- "Site",
- "Deployment"
- ],
- "Slice": [
- "Site"
- ],
- "ReservedResource": [
- "Sliver"
- ],
- "SliceMembership": [
- "User",
- "Slice",
- "Role"
- ],
- "NetworkSlice": [
- "Network",
- "Slice"
- ],
- "Tag": [
- "Project"
- ],
- "User": [
- "Site"
- ],
- "SliceTag": [
- "Slice"
- ],
- "Reservation": [
- "Slice"
- ],
- "NetworkSliver": [
- "Network",
- "Sliver"
- ],
- "SitePrivilege": [
- "User",
- "Site",
- "Role"
- ],
- "Sliver": [
- "Image",
- "Slice",
- "Node"
- ]
-}
diff --git a/xos.spec b/xos.spec
deleted file mode 100644
index c585e7e..0000000
--- a/xos.spec
+++ /dev/null
@@ -1,158 +0,0 @@
-Summary: OpenCloud core services
-Name: xos
-Version: 1.2.0
-Release: 5
-License: GPL+
-Group: Development/Tools
-Source0: %{_tmppath}/%{name}-%{version}.tar.gz
-BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}
-requires: postgresql
-requires: postgresql-server
-requires: python-psycopg2
-requires: graphviz
-requires: graphviz-devel
-requires: graphviz-python
-requires: libxslt-devel
-requires: python-pip
-requires: tar
-requires: gcc
-requires: python-httplib2
-requires: GeoIP
-requires: wget
-
-%description
-%{summary}
-
-%prep
-%setup -q
-
-%build
-# Empty section.
-
-%pre
-pip-python install django==1.7
-pip-python install djangorestframework==2.4.4
-pip-python install markdown # Markdown support for the browseable API.
-pip-python install pyyaml # YAML content-type support.
-pip-python install django-filter # Filtering support
-pip-python install lxml # XML manipulation library
-pip-python install netaddr # IP Addr library
-pip-python install pytz
-pip-python install django-timezones
-pip-python install requests
-pip-python install django-crispy-forms
-pip-python install django-geoposition
-pip-python install django-extensions
-pip-python install django-suit
-pip-python install django-evolution
-pip-python install django-bitfield
-pip-python install django-ipware
-pip-python install django-encrypted-fields
-pip-python install python-keyczar
-pip-python install python-keystoneclient
-pip-python install python-novaclient
-pip-python install python-neutronclient
-pip-python install python-glanceclient
-pip-python install python-ceilometerclient
-pip-python install django_rest_swagger
-
-
-easy_install django_evolution
-easy_install python_gflags
-easy_install google_api_python_client
-
-if [ ! -f /usr/lib/python2.7/site-packages/suit/static/suit/js/jquery-1.9.1.min.js ]; then
- wget -P /usr/lib/python2.7/site-packages/suit/static/suit/js http://code.jquery.com/jquery-1.9.1.min.js
-fi
-
-if [ ! -f /usr/share/GeoIP/GeoLiteCity.dat ]; then
- rm -f /usr/share/GeoIP/GeoLiteCity.*
- wget -P /usr/share/GeoIP http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
- gzip -d /usr/share/GeoIP/GeoLiteCity*.gz
-fi
-
-if [ "$1" == 2 ] ; then
- if [[ -e /opt/xos/scripts/opencloud ]]; then
- echo "UPGRADE - saving current state"
- /opt/xos/scripts/opencloud dumpdata
- fi
-fi
-
-%install
-rm -rf %{buildroot}
-mkdir -p %{buildroot}
-install -d %{buildroot}/opt/xos
-install -d %{buildroot}/etc/init.d
-
-# in builddir
-
-rm -rf %{buildroot}/opt/xos
-# don't copy symbolic links (they are handled in %post)
-rsync -rptgoD ./xos %{buildroot}/opt/.
-cp observer-initscript %{buildroot}/etc/init.d/xosobserver
-
-find %{buildroot}/opt/xos -type f -print | sed "s@^$RPM_BUILD_ROOT@@g" > %{_tmppath}/tmp-filelist
-echo /etc/init.d/xosobserver >> %{_tmppath}/tmp-filelist
-
-# remove config files from the file list (see %config below)
-cat > %{_tmppath}/config-files << "EOF"
-/opt/xos/xos_config
-/opt/xos/deployment_auth.py
-EOF
-
-sort %{_tmppath}/tmp-filelist > %{_tmppath}/tmp-filelist.sorted
-sort %{_tmppath}/config-files > %{_tmppath}/config-files.sorted
-comm -13 %{_tmppath}/config-files.sorted %{_tmppath}/tmp-filelist.sorted > %{_tmppath}/tmp-filelist
-
-cp %{_tmppath}/tmp-filelist /tmp/tmp-filelist
-
-
-%clean
-rm -rf %{buildroot}
-
-%files -f %{_tmppath}/tmp-filelist
-%defattr(-,root,root,-)
-%config /opt/xos/xos_config
-%config /opt/xos/deployment_auth.py
-%config /opt/xos/model-deps
-
-%post
-ln -s openstack_observer /opt/xos/observer
-#ln -s config-opencloud.py /opt/xos/syndicate_observer/syndicatelib_config/config.py
-
-if [ ! -e /opt/xos/public_keys ]; then
- cd /opt/xos
- scripts/opencloud genkeys
-fi
-
-if [ "$1" == 1 ] ; then
- echo "NEW INSTALL - initializing database"
- /opt/xos/scripts/opencloud initdb
-else
- # scripts/opencloud will choose evolve or migrate depending on django version
- echo "UPGRADE - doing evolution/migration"
- /opt/xos/scripts/opencloud evolvedb
-fi
-
-# Clone ansible with latest openstack modules
-git clone --recursive git://github.com/ansible/ansible.git /opt/ansible
-mkdir -p /etc/ansible
-echo > /etc/ansible/hosts << "EOF"
-[localhost]
-127.0.0.1
-EOF
-
-
-# start the server
-/opt/xos/scripts/opencloud runserver
-
-%preun
-if [ "$1" = 0 ] ; then
- echo "UNINSTALL - destroying xos"
- rm -rf /opt/xos
-fi
-
-%changelog
-* Sat Feb 22 2014 Siobhan Tully 1.0.0
-- First Build
-
diff --git a/xos/README.md b/xos/README.md
new file mode 100644
index 0000000..daec000
--- /dev/null
+++ b/xos/README.md
@@ -0,0 +1,21 @@
+## XOS Source Tree
+
+This is the main directory for XOS. Sub-directories include:
+
+* configurations -- collection of canned configurations
+* core -- core model definitions
+* generators -- tools to generate auxiliary structures from data model
+* model_policies -- invariants on the data model
+* nginx, uwsgi -- related to web server that runs XOS
+* openstack -- client-side interaction with OpenStack (to be depreciated)
+* services -- model definitions for a set of services
+* synchronizers -- collection of synchronizers
+* templates -- Django GUI templates
+* test -- system-wide tests to be collected here
+* tosca -- tosca modeling layer on top of RESTful API
+* tools -- assorted tools and scripts
+* xos -- common source code for all Django applications
+* xos_configuration -- top-level XOS configuration parameters
+
+Of these, configuration, services, and synchronizers are most
+relevant to developers.
diff --git a/xos/apigen/hpc-api.template.py b/xos/apigen/hpc-api.template.py
deleted file mode 100644
index 301346b..0000000
--- a/xos/apigen/hpc-api.template.py
+++ /dev/null
@@ -1,211 +0,0 @@
-from rest_framework.decorators import api_view
-from rest_framework.response import Response
-from rest_framework.reverse import reverse
-from rest_framework import serializers
-from rest_framework import generics
-from rest_framework import status
-from rest_framework.generics import GenericAPIView
-from hpc.models import *
-from django.forms import widgets
-from rest_framework import filters
-from django.conf.urls import patterns, url
-from rest_framework.exceptions import PermissionDenied as RestFrameworkPermissionDenied
-from django.core.exceptions import PermissionDenied as DjangoPermissionDenied
-from apibase import XOSRetrieveUpdateDestroyAPIView, XOSListCreateAPIView, XOSNotAuthenticated
-
-if hasattr(serializers, "ReadOnlyField"):
- # rest_framework 3.x
- IdField = serializers.ReadOnlyField
-else:
- # rest_framework 2.x
- IdField = serializers.Field
-
-"""
- Schema of the generator object:
- all: Set of all Model objects
- all_if(regex): Set of Model objects that match regex
-
- Model object:
- plural: English plural of object name
- camel: CamelCase version of object name
- refs: list of references to other Model objects
- props: list of properties minus refs
-
- TODO: Deal with subnets
-"""
-
-def get_hpc_REST_patterns():
- return patterns('',
- url(r'^hpcapi/$', hpc_api_root),
- {% for object in generator.rest_models %}
- url(r'hpcapi/{{ object.rest_name }}/$', {{ object.camel }}List.as_view(), name='{{ object.singular }}-list'),
- url(r'hpcapi/{{ object.rest_name }}/(?P<pk>[a-zA-Z0-9\-]+)/$', {{ object.camel }}Detail.as_view(), name ='{{ object.singular }}-detail'),
- {% endfor %}
- )
-
-@api_view(['GET'])
-def hpc_api_root(request, format=None):
- return Response({
- {% for object in generator.rest_models %}'{{ object.plural }}': reverse('{{ object }}-list', request=request, format=format),
- {% endfor %}
- })
-
-# Based on serializers.py
-
-class XOSModelSerializer(serializers.ModelSerializer):
- def save_object(self, obj, **kwargs):
-
- """ rest_framework can't deal with ManyToMany relations that have a
- through table. In xos, most of the through tables we have
- use defaults or blank fields, so there's no reason why we shouldn't
- be able to save these objects.
-
- So, let's strip out these m2m relations, and deal with them ourself.
- """
- obj._complex_m2m_data={};
- if getattr(obj, '_m2m_data', None):
- for relatedObject in obj._meta.get_all_related_many_to_many_objects():
- if (relatedObject.field.rel.through._meta.auto_created):
- # These are non-trough ManyToMany relations and
- # can be updated just fine
- continue
- fieldName = relatedObject.get_accessor_name()
- if fieldName in obj._m2m_data.keys():
- obj._complex_m2m_data[fieldName] = (relatedObject, obj._m2m_data[fieldName])
- del obj._m2m_data[fieldName]
-
- serializers.ModelSerializer.save_object(self, obj, **kwargs);
-
- for (accessor, stuff) in obj._complex_m2m_data.items():
- (relatedObject, data) = stuff
- through = relatedObject.field.rel.through
- local_fieldName = relatedObject.field.m2m_reverse_field_name()
- remote_fieldName = relatedObject.field.m2m_field_name()
-
- # get the current set of existing relations
- existing = through.objects.filter(**{local_fieldName: obj});
-
- data_ids = [item.id for item in data]
- existing_ids = [getattr(item,remote_fieldName).id for item in existing]
-
- #print "data_ids", data_ids
- #print "existing_ids", existing_ids
-
- # remove relations that are in 'existing' but not in 'data'
- for item in list(existing):
- if (getattr(item,remote_fieldName).id not in data_ids):
- print "delete", getattr(item,remote_fieldName)
- item.delete() #(purge=True)
-
- # add relations that are in 'data' but not in 'existing'
- for item in data:
- if (item.id not in existing_ids):
- #print "add", item
- newModel = through(**{local_fieldName: obj, remote_fieldName: item})
- newModel.save()
-
-{% for object in generator.rest_models %}
-
-class {{ object.camel }}Serializer(serializers.HyperlinkedModelSerializer):
- id = IdField()
- {% for ref in object.refs %}
- {% if ref.multi %}
- {{ ref.plural }} = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='{{ ref }}-detail')
- {% else %}
- {{ ref }} = serializers.HyperlinkedRelatedField(read_only=True, view_name='{{ ref }}-detail')
- {% endif %}
- {% endfor %}
- humanReadableName = serializers.SerializerMethodField("getHumanReadableName")
- validators = serializers.SerializerMethodField("getValidators")
- def getHumanReadableName(self, obj):
- return str(obj)
- def getValidators(self, obj):
- try:
- return obj.getValidators()
- except:
- return None
- class Meta:
- model = {{ object.camel }}
- fields = ('humanReadableName', 'validators', {% for prop in object.props %}'{{ prop }}',{% endfor %}{% for ref in object.refs %}{%if ref.multi %}'{{ ref.plural }}'{% else %}'{{ ref }}'{% endif %},{% endfor %})
-
-class {{ object.camel }}IdSerializer(XOSModelSerializer):
- id = IdField()
- {% for ref in object.refs %}
- {% if ref.multi %}
- {{ ref.plural }} = serializers.PrimaryKeyRelatedField(many=True, queryset = {{ ref.camel }}.objects.all())
- {% else %}
- {{ ref }} = serializers.PrimaryKeyRelatedField( queryset = {{ ref.camel }}.objects.all())
- {% endif %}
- {% endfor %}
- humanReadableName = serializers.SerializerMethodField("getHumanReadableName")
- validators = serializers.SerializerMethodField("getValidators")
- def getHumanReadableName(self, obj):
- return str(obj)
- def getValidators(self, obj):
- try:
- return obj.getValidators()
- except:
- return None
- class Meta:
- model = {{ object.camel }}
- fields = ('humanReadableName', 'validators', {% for prop in object.props %}'{{ prop }}',{% endfor %}{% for ref in object.refs %}{%if ref.multi %}'{{ ref.plural }}'{% else %}'{{ ref }}'{% endif %},{% endfor %})
-
-
-{% endfor %}
-
-serializerLookUp = {
-{% for object in generator.rest_models %}
- {{ object.camel }}: {{ object.camel }}Serializer,
-{% endfor %}
- None: None,
- }
-
-# Based on core/views/*.py
-{% for object in generator.rest_models %}
-
-class {{ object.camel }}List(XOSListCreateAPIView):
- queryset = {{ object.camel }}.objects.select_related().all()
- serializer_class = {{ object.camel }}Serializer
- id_serializer_class = {{ object.camel }}IdSerializer
- filter_backends = (filters.DjangoFilterBackend,)
- filter_fields = ({% for prop in object.props %}'{{ prop }}',{% endfor %}{% for ref in object.refs %}{%if ref.multi %}'{{ ref.plural }}'{% else %}'{{ ref }}'{% endif %},{% endfor %})
-
- def get_serializer_class(self):
- no_hyperlinks=False
- if hasattr(self.request,"QUERY_PARAMS"):
- no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False)
- if (no_hyperlinks):
- return self.id_serializer_class
- else:
- return self.serializer_class
-
- def get_queryset(self):
- if (not self.request.user.is_authenticated()):
- raise XOSNotAuthenticated()
- return {{ object.camel }}.select_by_user(self.request.user)
-
-
-class {{ object.camel }}Detail(XOSRetrieveUpdateDestroyAPIView):
- queryset = {{ object.camel }}.objects.select_related().all()
- serializer_class = {{ object.camel }}Serializer
- id_serializer_class = {{ object.camel }}IdSerializer
-
- def get_serializer_class(self):
- no_hyperlinks=False
- if hasattr(self.request,"QUERY_PARAMS"):
- no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False)
- if (no_hyperlinks):
- return self.id_serializer_class
- else:
- return self.serializer_class
-
- def get_queryset(self):
- if (not self.request.user.is_authenticated()):
- raise XOSNotAuthenticated()
- return {{ object.camel }}.select_by_user(self.request.user)
-
- # update() is handled by XOSRetrieveUpdateDestroyAPIView
-
- # destroy() is handled by XOSRetrieveUpdateDestroyAPIView
-
-{% endfor %}
diff --git a/xos/apigen/modelgen b/xos/apigen/modelgen
deleted file mode 100644
index 63cf5b7..0000000
--- a/xos/apigen/modelgen
+++ /dev/null
@@ -1,204 +0,0 @@
-#!/usr/bin/python
-
-import os
-import pdb
-import copy
-import sys
-import json
-import re
-from django.template import Context, Template
-from optparse import OptionParser
-
-# Django set up
-
-sys.path.append('.')
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-from django.db.models.fields.related import ForeignKey, ManyToManyField
-
-options = None
-
-def singular(foo, keys):
- for k in keys:
- if (foo==k+'es'):
- return k
- elif (foo==k+'s'):
- return k
- raise Exception('Plural to singular error for %s'%foo)
-
-g = globals()
-
-def enum_classes(apps):
- model_classes = []
- for app in apps:
- app = app + ".models"
- models_module = __import__(app)
- for part in app.split(".")[1:]:
- if hasattr(models_module, "PlCoreBase"):
- break
- models_module = getattr(models_module,part)
-
- PlCoreBase = getattr(models_module,"PlCoreBase")
-
- for classname in dir(models_module):
- c = getattr(models_module, classname, None)
- if type(c)==type(PlCoreBase) and c.__name__ not in options.blacklist:
- model_classes.append(c)
-
- return model_classes
-
-class GenObj(object):
- def __str__(self):
- return str(self.model.__name__.lower())
-
- def __init__(self, m):
- self.model = m
- self.props = []
- self.refs = []
- self.plural_name = None
-
- def plural(self):
- if (self.plural_name):
- return self.plural_name
- else:
- name = str(self)
- if (name.endswith('s')):
- return name+'es'
- else:
- return name+'s'
-
- def singular(self):
- return str(self)
-
- def rest_name(self):
- # These are things that either for historic reasons or due to incorrect naming,
- # got called something different than the autogen thinks they should be
- # called.
- REST_FIXUP = {'controllernetworkses': 'controllernetworks',
- 'controllerimageses': 'controllerimages',
- 'controllersliceses': 'controllerslices',
- 'controlleruserses': 'controllerusers',
- 'sitedeploymentses': 'sitedeployments',
- 'siteroles': 'site_roles',
- 'sliceprivileges': 'slice_privileges',
- 'sliceroles': 'slice_roles',
- }
- return REST_FIXUP.get(self.plural(), self.plural())
-
- def camel(self):
- name = str(self.model.__name__)
- return name
-
-class Generator(dict):
- def all(self):
- return self.values()
-
- def rest_models(self):
- norest = [x.lower() for x in options.norest]
- return [v for v in self.values() if not (str(v) in norest)]
-
- def regex(self, r):
- filtered = filter(lambda o:re.match(r,str(o)), self.values())
- return filtered
-
- def add_object(self, o):
- obj = GenObj(o)
- fields = o._meta.fields
- self[str(obj).lower()]=obj
-
- def compute_links(self):
- for obj in self.values():
- #if (str(obj)=='network'):
- # pdb.set_trace()
- fields = obj.model._meta.fields
- for f in fields:
- if (f and f.rel):
- to_name = str(f.rel.to)
- else:
- to_name = None
-
- if type(f)==ForeignKey and to_name and to_name in self.keys():
- refobj = self[f.to_name]
-
- if (str(obj)=='slice' and f.to_name=='networks'):
- obj.refs.append(refobj)
- related_name = f.related_query_name()
- if (related_name!='+' and related_name.lower()!=str(obj).lower()):
- cobj = copy.deepcopy(obj)
- cobj.multi = True
- cobj.plural_name = related_name
- refobj.refs.append(cobj)
- elif f.name.endswith("_ptr"):
- # django inherited model, for example HPCService
- # cause swagger and REST to break
- pass
- else:
- obj.props.append(f.name)
-
- m2m = obj.model._meta.many_to_many
- for f in m2m:
- try:
- related_model_name = f.m2m_reverse_field_name()
- except:
- related_model_name = f.m2m_db_table().rsplit('_',1)[-1]
-
- related_name = f.related_query_name()
- if related_model_name in self.keys():
- #print "XXX1", obj, f, related_name, related_model_name
- refobj = self[related_model_name]
- cobj = copy.deepcopy(obj)
- cobj.multi=True
- refobj.refs.append(cobj)
-
- # deal with upgradeFrom_rel_+
- if (related_name.endswith("+")):
- continue
-
- if (related_name!='+') and related_model_name in self: # and related_name.lower()!=str(obj).lower()):
- refobj = self[related_model_name]
- #print "XXX2", obj, f, related_name, related_model_name, refobj.plural_name
- cobj = copy.deepcopy(refobj)
- cobj.multi = True
-
- obj.refs.append(cobj)
-
-
-
-
-def main():
- global options
- parser = OptionParser(usage="modelgen [options] <template_fn>", )
-
- parser.add_option("-a", "--app", dest="apps",
- help="list of applications to parse", metavar="APP", default=[], action="append")
- parser.add_option("-b", "--blacklist", dest="blacklist",
- help="add model name to blacklist", metavar="MODEL", default=["SingletonModel", "PlCoreBase"], action="append")
- parser.add_option("-n", "--no-rest", dest="norest",
- help="do not generate rest api for model", metavar="MODEL", default=["SingletonModel", "PlCoreBase"], action="append")
-
- (options, args) = parser.parse_args(sys.argv[1:])
-
- if not options.apps:
- options.apps = ["core"]
-
- if len(args)!=1:
- print 'Usage: modelgen [options] <template_fn>'
- exit(1)
-
- output = args[0]
-
- generator = Generator()
-
- models = enum_classes(options.apps)
-
- for m in models:
- generator.add_object(m)
-
- generator.compute_links()
- template_contents = open(output).read()
- template = Template(template_contents)
- context = Context({'generator':generator})
- print template.render(context)
-
-
-if (__name__=='__main__'):
- main()
diff --git a/xos/ceilometer/admin.py b/xos/ceilometer/admin.py
deleted file mode 100644
index 3ed70b2..0000000
--- a/xos/ceilometer/admin.py
+++ /dev/null
@@ -1,102 +0,0 @@
-from django.contrib import admin
-
-from ceilometer.models import *
-from django import forms
-from django.utils.safestring import mark_safe
-from django.contrib.auth.admin import UserAdmin
-from django.contrib.admin.widgets import FilteredSelectMultiple
-from django.contrib.auth.forms import ReadOnlyPasswordHashField
-from django.contrib.auth.signals import user_logged_in
-from django.utils import timezone
-from django.contrib.contenttypes import generic
-from suit.widgets import LinkedSelect
-from core.admin import ServiceAppAdmin,SliceInline,ServiceAttrAsTabInline, ReadOnlyAwareAdmin, XOSTabularInline, ServicePrivilegeInline, TenantRootTenantInline, TenantRootPrivilegeInline
-from core.middleware import get_request
-
-from functools import update_wrapper
-from django.contrib.admin.views.main import ChangeList
-from django.core.urlresolvers import reverse
-from django.contrib.admin.utils import quote
-
-class CeilometerServiceAdmin(ReadOnlyAwareAdmin):
- model = CeilometerService
- verbose_name = "Ceilometer Service"
- verbose_name_plural = "Ceilometer Service"
- list_display = ("backend_status_icon", "name", "enabled")
- list_display_links = ('backend_status_icon', 'name', )
- fieldsets = [(None, {'fields': ['backend_status_text', 'name','enabled','versionNumber', 'description',"view_url","icon_url" ], 'classes':['suit-tab suit-tab-general']})]
- readonly_fields = ('backend_status_text', )
- inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
-
- extracontext_registered_admins = True
-
- user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
-
- suit_form_tabs =(('general', 'Ceilometer Service Details'),
- ('administration', 'Administration'),
- ('slices','Slices'),
- ('serviceattrs','Additional Attributes'),
- ('serviceprivileges','Privileges'),
- )
-
- suit_form_includes = (('ceilometeradmin.html', 'top', 'administration'),
- )
-
- def queryset(self, request):
- return CeilometerService.get_service_objects_by_user(request.user)
-
-class MonitoringChannelForm(forms.ModelForm):
- creator = forms.ModelChoiceField(queryset=User.objects.all())
-
- def __init__(self,*args,**kwargs):
- super (MonitoringChannelForm,self ).__init__(*args,**kwargs)
- self.fields['kind'].widget.attrs['readonly'] = True
- self.fields['provider_service'].queryset = CeilometerService.get_service_objects().all()
- if self.instance:
- # fields for the attributes
- self.fields['creator'].initial = self.instance.creator
- if (not self.instance) or (not self.instance.pk):
- # default fields for an 'add' form
- self.fields['kind'].initial = CEILOMETER_KIND
- self.fields['creator'].initial = get_request().user
- if CeilometerService.get_service_objects().exists():
- self.fields["provider_service"].initial = CeilometerService.get_service_objects().all()[0]
-
-
- def save(self, commit=True):
- self.instance.creator = self.cleaned_data.get("creator")
- return super(MonitoringChannelForm, self).save(commit=commit)
-
- class Meta:
- model = MonitoringChannel
-
-class MonitoringChannelAdmin(ReadOnlyAwareAdmin):
- list_display = ('backend_status_icon', 'id', )
- list_display_links = ('backend_status_icon', 'id')
- fieldsets = [ (None, {'fields': ['backend_status_text', 'kind', 'provider_service', 'service_specific_attribute',
- 'ceilometer_url', 'tenant_list_str',
- 'instance', 'creator'],
- 'classes':['suit-tab suit-tab-general']})]
- readonly_fields = ('backend_status_text', 'instance', 'service_specific_attribute', 'ceilometer_url', 'tenant_list_str')
- form = MonitoringChannelForm
-
- suit_form_tabs = (('general','Details'),)
- actions=['delete_selected_objects']
-
- def get_actions(self, request):
- actions = super(MonitoringChannelAdmin, self).get_actions(request)
- if 'delete_selected' in actions:
- del actions['delete_selected']
- return actions
-
- def delete_selected_objects(self, request, queryset):
- for obj in queryset:
- obj.delete()
- delete_selected_objects.short_description = "Delete Selected MonitoringChannel Objects"
-
- def queryset(self, request):
- return MonitoringChannel.get_tenant_objects_by_user(request.user)
-
-admin.site.register(CeilometerService, CeilometerServiceAdmin)
-admin.site.register(MonitoringChannel, MonitoringChannelAdmin)
-
diff --git a/xos/configurations/bash/Dockerfile.bash b/xos/configurations/bash/Dockerfile.bash
deleted file mode 100644
index a9c224d..0000000
--- a/xos/configurations/bash/Dockerfile.bash
+++ /dev/null
@@ -1,13 +0,0 @@
-RUN mkdir -p /root/setup
-ADD xos/configurations/common/admin-openrc.sh /root/setup/
-ADD xos/configurations/common/controller_settings /root/setup/
-ADD xos/configurations/common/flat_net_name /root/setup/
-ADD xos/configurations/common/cloudlab-nodes.yaml /opt/xos/configurations/commmon/
-ADD xos/configurations/common/id_rsa.pub /root/setup/padmin_public_key
-ADD xos/configurations/common/node_key.pub /root/setup/node_key.pub
-ADD xos/configurations/common/node_key /root/setup/node_key
-ADD xos/configurations/common/ceilometer_url /root/setup/ceilometer_url
-
-CMD /usr/bin/make -C /opt/xos/configurations/bash -f Makefile.inside; /bin/bash
-
-#CMD ["/bin/bash"]
diff --git a/xos/configurations/bash/Makefile b/xos/configurations/bash/Makefile
deleted file mode 100644
index a668a55..0000000
--- a/xos/configurations/bash/Makefile
+++ /dev/null
@@ -1,11 +0,0 @@
-MYIP:=$(shell hostname -i)
-
-test: common_cloudlab
- rm ../../xos_configuration/*
- cp ../common/xos_common_config ../../xos_configuration/
- cat ../common/Dockerfile.common Dockerfile.bash > Dockerfile
- cd ../../..; sudo docker build -t xos -f xos/configurations/bash/Dockerfile .
- sudo docker run -i --tty --add-host="ctl:$(MYIP)" -p 9999:8000 xos
-
-common_cloudlab:
- make -C ../common -f Makefile.cloudlab
diff --git a/xos/configurations/bash/Makefile.inside b/xos/configurations/bash/Makefile.inside
deleted file mode 100644
index 176ef47..0000000
--- a/xos/configurations/bash/Makefile.inside
+++ /dev/null
@@ -1,7 +0,0 @@
-all: setup_xos
-
-setup_xos:
- bash /opt/xos/scripts/docker_setup_xos
- python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/fixtures.yaml
- python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/cloudlab.yaml
- python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/cloudlab-nodes.yaml
diff --git a/xos/configurations/bash/README b/xos/configurations/bash/README
deleted file mode 100644
index 83322a0..0000000
--- a/xos/configurations/bash/README
+++ /dev/null
@@ -1,5 +0,0 @@
-This configuration launches XOS on Cloudlab, leaving the user in an interactive bash session.
-
-The django UI is not started automatically. To start it, execute the following commands from the bash session:
- cd /opt/xos
- scripts/opencloud runserver
diff --git a/xos/configurations/bash/copyin-vtn.sh b/xos/configurations/bash/copyin-vtn.sh
new file mode 100644
index 0000000..ef18704
--- /dev/null
+++ b/xos/configurations/bash/copyin-vtn.sh
@@ -0,0 +1,12 @@
+#! /bin/bash
+
+export SETUPDIR=/root/setup
+
+# copy in file necessary to setup VTN
+
+cd ../cord
+CONTAINER=$( docker ps|grep "xos"|awk '{print $NF}' )
+make vtn_network_cfg_json
+docker cp $SETUPDIR/vtn-network-cfg.json $CONTAINER:/root/setup/
+docker cp ../common/id_rsa.pub $CONTAINER:/opt/xos/observers/onos/onos_key.pub
+docker cp ../common/id_rsa $CONTAINER:/opt/xos/observers/onos/onos_key
diff --git a/xos/configurations/common/Dockerfile.common b/xos/configurations/common/Dockerfile.common
index d78585a..fd27593 100644
--- a/xos/configurations/common/Dockerfile.common
+++ b/xos/configurations/common/Dockerfile.common
@@ -34,7 +34,7 @@
RUN pip install djangorestframework==2.4.4
RUN pip install markdown # Markdown support for the browseable API.
RUN pip install pyyaml # YAML content-type support.
-RUN pip install django-filter # Filtering support
+RUN pip install django-filter==0.11.0 # Filtering support
RUN pip install lxml # XML manipulation library
RUN pip install netaddr # IP Addr library
RUN pip install pytz
@@ -103,8 +103,8 @@
# Initscript is broken in Ubuntu
#ADD observer-initscript /etc/init.d/xosobserver
-RUN chmod +x /opt/xos/scripts/opencloud
-RUN /opt/xos/scripts/opencloud genkeys
+RUN chmod +x /opt/xos/tools/xos-manage
+RUN /opt/xos/tools/xos-manage genkeys
# Workaround for AUFS issue
# https://github.com/docker/docker/issues/783#issuecomment-56013588
@@ -118,7 +118,7 @@
# RUN sed -i 's/DEBUG = False/DEBUG = True/' /opt/xos/xos/settings.py
# Cruft to workaround problems with migrations, should go away...
-RUN /opt/xos/scripts/opencloud remigrate
+RUN /opt/xos/tools/xos-manage remigrate
# git clone uses cached copy, doesn't pick up latest
RUN git -C /opt/ansible pull
@@ -140,4 +140,4 @@
# Define default command.
#CMD ["/bin/bash"]
-#CMD /opt/xos/scripts/docker_start_xos
+#CMD /opt/xos/tools/docker_start_xos
diff --git a/xos/configurations/common/Makefile.cloudlab b/xos/configurations/common/Makefile.cloudlab
index 6e609d7..7ab8a54 100644
--- a/xos/configurations/common/Makefile.cloudlab
+++ b/xos/configurations/common/Makefile.cloudlab
@@ -1,35 +1,41 @@
MYFLATLANIF:=$(shell netstat -i |grep "flat"|awk '{print $$1}' )
+ifndef MYFLATLANIF
+$(error MYFLATLANIF is empty)
+endif
MYFLATLANIP:=$(shell ifconfig $(MYFLATLANIF) | grep "inet addr" | awk -F: '{print $$2}' | awk '{print $$1}' )
+SETUPDIR:=../setup
-all: prereqs admin-openrc flat_name nodes_yaml public_key private_key ceilometer_url node_key
+all: prereqs admin-openrc flat_name nodes_yaml public_key private_key ceilometer_url other_keys
prereqs:
make -f Makefile.prereqs
+ mkdir -p $(SETUPDIR)
admin-openrc:
- sudo cat /root/setup/admin-openrc.sh > admin-openrc.sh
- sudo cat /root/setup/settings > controller_settings
- echo 'CONTROLLER_FLAT_LAN_IP=$(MYFLATLANIP)' >> controller_settings
+ sudo cat /root/setup/admin-openrc.sh > $(SETUPDIR)/admin-openrc.sh
+ sudo cat /root/setup/settings > $(SETUPDIR)/controller_settings
+ echo 'CONTROLLER_FLAT_LAN_IP=$(MYFLATLANIP)' >> $(SETUPDIR)/controller_settings
flat_name:
- sudo bash -c "source /root/setup/admin-openrc.sh ; neutron net-list" |grep flat|awk '{printf "%s",$$4}' > flat_net_name
- [ -s flat_net_name ] # throw error if flat_net_name is empty
+ bash -c "source $(SETUPDIR)/admin-openrc.sh ; neutron net-list" |grep flat|awk '{printf "%s",$$4}' > $(SETUPDIR)/flat_net_name
+ [ -s $(SETUPDIR)/flat_net_name ] # throw error if flat_net_name is empty
nodes_yaml:
- bash ./make-cloudlab-nodes-yaml.sh
+ export SETUPDIR=$(SETUPDIR); bash ./make-nodes-yaml.sh
ceilometer_url:
- echo http://`hostname -i`/xosmetering/ > ceilometer_url
+ echo http://`hostname -i`/xosmetering/ > $(SETUPDIR)/ceilometer_url
public_key: ~/.ssh/id_rsa.pub
- cp ~/.ssh/id_rsa.pub .
+ cp ~/.ssh/id_rsa.pub $(SETUPDIR)
private_key: ~/.ssh/id_rsa
- cp ~/.ssh/id_rsa .
+ cp ~/.ssh/id_rsa $(SETUPDIR)
~/.ssh/id_rsa.pub:
cat /dev/zero | ssh-keygen -q -N ""
-node_key:
- sudo cat /root/setup/id_rsa > node_key
- sudo cat /root/setup/id_rsa.pub > node_key.pub
+other_keys: public_key private_key
+ sudo cat /root/setup/id_rsa > $(SETUPDIR)/node_key
+ sudo cat /root/setup/id_rsa.pub > $(SETUPDIR)/node_key.pub
+ sudo cp $(SETUPDIR)/id_rsa.pub $(SETUPDIR)/padmin_public_key
diff --git a/xos/configurations/common/Makefile.devstack b/xos/configurations/common/Makefile.devstack
index 2f31696..e60434e 100644
--- a/xos/configurations/common/Makefile.devstack
+++ b/xos/configurations/common/Makefile.devstack
@@ -1,34 +1,42 @@
# This shouldn't be hardcoded
DEVSTACK_ROOT:=~/devstack
+SETUPDIR:=../setup
-all: prereqs admin-openrc flat_name nodes_yaml public_key private_key ceilometer_url node_key
+all: prereqs admin-openrc flat_name nodes_yaml public_key private_key ceilometer_url other_keys net_fix
prereqs:
make -f Makefile.prereqs
+ sudo pip install httpie --upgrade
+ mkdir -p $(SETUPDIR)
admin-openrc:
- bash ./devstack-creds.sh $(DEVSTACK_ROOT) > admin-openrc.sh
- touch controller_settings
+ bash ./devstack-creds.sh $(DEVSTACK_ROOT) > $(SETUPDIR)/admin-openrc.sh
+ touch $(SETUPDIR)/controller_settings
flat_name:
- echo private|tr -d '\n' > flat_net_name
- bash -c "source admin-openrc.sh; openstack network set --share private"
+ echo private|tr -d '\n' > $(SETUPDIR)/flat_net_name
+ bash -c "source $(SETUPDIR)/admin-openrc.sh; openstack network set --share private"
nodes_yaml:
- bash ./make-cloudlab-nodes-yaml.sh
+ export SETUPDIR=$(SETUPDIR); bash ./make-nodes-yaml.sh
ceilometer_url:
- echo http://`hostname -i`/xosmetering/ > ceilometer_url
+ echo http://`hostname -i`/xosmetering/ > $(SETUPDIR)/ceilometer_url
public_key: ~/.ssh/id_rsa.pub
- cp ~/.ssh/id_rsa.pub .
+ cp ~/.ssh/id_rsa.pub $(SETUPDIR)
private_key: ~/.ssh/id_rsa
- cp ~/.ssh/id_rsa .
+ cp ~/.ssh/id_rsa $(SETUPDIR)
~/.ssh/id_rsa.pub:
cat /dev/zero | ssh-keygen -q -N ""
-node_key:
- sudo cat ~/.ssh/id_rsa > node_key
- sudo cat ~/.ssh/id_rsa.pub > node_key.pub
+other_keys: public_key private_key
+ cp $(SETUPDIR)/id_rsa $(SETUPDIR)/node_key
+ cp $(SETUPDIR)/id_rsa.pub $(SETUPDIR)/node_key.pub
+ cp $(SETUPDIR)/id_rsa.pub $(SETUPDIR)/padmin_public_key
+
+net_fix:
+ sudo devstack/net-fix.sh
+ bash -c "source $(SETUPDIR)/admin-openrc.sh; neutron subnet-update private-subnet --dns-nameservers list=true 8.8.8.8 8.8.4.4"
diff --git a/xos/configurations/common/Makefile.opencloud b/xos/configurations/common/Makefile.opencloud
new file mode 100644
index 0000000..8cf9f29
--- /dev/null
+++ b/xos/configurations/common/Makefile.opencloud
@@ -0,0 +1,40 @@
+MYFLATLANIF:=$(shell netstat -i |grep "flat"|awk '{print $$1}' )
+MYFLATLANIP:=$(shell ifconfig $(MYFLATLANIF) | grep "inet addr" | awk -F: '{print $$2}' | awk '{print $$1}' )
+SETUPDIR:=../setup
+
+all: prereqs admin-openrc flat_name nodes_yaml public_key private_key ceilometer_url node_key
+
+prereqs:
+ make -f Makefile.prereqs
+ mkdir -p $(SETUPDIR)
+
+admin-openrc:
+ sudo cat /root/setup/admin-openrc.sh > $(SETUPDIR)/admin-openrc.sh
+ sudo cat /root/setup/settings > $(SETUPDIR)/controller_settings
+ echo 'CONTROLLER_FLAT_LAN_IP=$(MYFLATLANIP)' >> $(SETUPDIR)/controller_settings
+
+flat_name:
+ sudo bash -c "source /root/setup/admin-openrc.sh ; neutron net-list" |grep flat|awk '{printf "%s",$$4}' > $(SETUPDIR)/flat_net_name
+ [ -s $(SETUPDIR)/flat_net_name ] # throw error if flat_net_name is empty
+
+nodes_yaml:
+ bash ./make-nodes-yaml.sh > $(SETUPDIR)/nodes.yaml
+
+ceilometer_url:
+ echo http://`hostname -i`/xosmetering/ > $(SETUPDIR)/ceilometer_url
+
+public_key: ~/.ssh/id_rsa.pub
+ cp ~/.ssh/id_rsa.pub $(SETUPDIR)
+
+private_key: ~/.ssh/id_rsa
+ cp ~/.ssh/id_rsa $(SETUPDIR)
+
+~/.ssh/id_rsa.pub:
+ cat /dev/zero | ssh-keygen -q -N ""
+
+node_key:
+ sudo cat /root/setup/id_rsa > $(SETUPDIR)/node_key
+ sudo cat /root/setup/id_rsa.pub > $(SETUPDIR)/node_key.pub
+
+images:
+ source admin-openrc.sh; glance image-show trusty-server-multi-nic || glance image-create --name trusty-server-multi-nic --disk-format qcow2 --file /proj/xos-PG0/acb/images/trusty-server-multi-nic.img --container-format bare
diff --git a/xos/configurations/common/Makefile.prereqs b/xos/configurations/common/Makefile.prereqs
index 0325224..fce51be 100644
--- a/xos/configurations/common/Makefile.prereqs
+++ b/xos/configurations/common/Makefile.prereqs
@@ -3,11 +3,14 @@
ifeq ($(UBUNTU),0)
# ******************* apt-based distros ***************************
-prereqs: /usr/bin/http docker
+prereqs: /usr/bin/http docker /usr/bin/curl /usr/local/bin/docker-compose
-/usr/bin/http:
+/usr/bin/http:
sudo apt-get -y install httpie
+/usr/bin/curl:
+ sudo apt-get -y install curl
+
docker:
which docker > /dev/null || wget -qO- https://get.docker.com/ | sh
sudo usermod -aG docker $(shell whoami)
@@ -18,11 +21,11 @@
# (untested / work-in-progress)
-prereqs: /usr/bin/pip /usr/bin/http docker
+prereqs: /usr/bin/pip /usr/bin/http docker /usr/local/bin/docker-compose
/usr/bin/pip:
curl "https://bootstrap.pypa.io/get-pip.py" -o "get-pip.py"
- sudo python ./get-pip.py
+ sudo python ./get-pip.py
docker:
which docker > /dev/null || wget -qO- https://get.docker.com/ | sh
@@ -32,3 +35,7 @@
sudo pip install httpie
endif
+
+/usr/local/bin/docker-compose:
+ sudo bash -c "curl -L https://github.com/docker/compose/releases/download/1.5.2/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose"
+ sudo chmod +x /usr/local/bin/docker-compose
diff --git a/xos/configurations/common/base.yaml b/xos/configurations/common/base.yaml
new file mode 100644
index 0000000..3638dd9
--- /dev/null
+++ b/xos/configurations/common/base.yaml
@@ -0,0 +1,89 @@
+tosca_definitions_version: tosca_simple_yaml_1_0
+
+# Note:
+# assumes the following have been created and filled with appropriate data:
+# /root/setup/admin_openrc
+# /root/setup/flat_net_name
+# /root/setup/padmin_public_key
+
+description: >
+ * Adds OpenCloud Sites, Deployments, and Controllers.
+
+imports:
+ - custom_types/xos.yaml
+
+topology_template:
+ node_templates:
+ trusty-server-multi-nic:
+ type: tosca.nodes.Image
+ properties:
+ disk_format: QCOW2
+ container_format: BARE
+
+ MyDeployment:
+ type: tosca.nodes.Deployment
+ properties:
+ flavors: m1.large, m1.medium, m1.small
+ requirements:
+ - image:
+ node: trusty-server-multi-nic
+ relationship: tosca.relationships.SupportsImage
+
+ CloudLab:
+ type: tosca.nodes.Controller
+ requirements:
+ - deployment:
+ node: MyDeployment
+ relationship: tosca.relationships.ControllerDeployment
+ properties:
+ backend_type: OpenStack
+ version: Kilo
+ auth_url: { get_script_env: [ SELF, adminrc, OS_AUTH_URL, LOCAL_FILE] }
+ admin_user: { get_script_env: [ SELF, adminrc, OS_USERNAME, LOCAL_FILE] }
+ admin_password: { get_script_env: [ SELF, adminrc, OS_PASSWORD, LOCAL_FILE] }
+ admin_tenant: { get_script_env: [ SELF, adminrc, OS_TENANT_NAME, LOCAL_FILE] }
+ rabbit_user: { get_script_env: [ SELF, controller_settings, RABBIT_USER, LOCAL_FILE] }
+ rabbit_password: { get_script_env: [ SELF, controller_settings, RABBIT_PASS, LOCAL_FILE] }
+ rabbit_host: { get_script_env: [ SELF, controller_settings, CONTROLLER_FLAT_LAN_IP, LOCAL_FILE] }
+ domain: Default
+ artifacts:
+ adminrc: /root/setup/admin-openrc.sh
+ controller_settings: /root/setup/controller_settings
+
+ mysite:
+ type: tosca.nodes.Site
+ properties:
+ display_name: MySite
+ site_url: http://opencloud.us/
+ requirements:
+ - deployment:
+ node: MyDeployment
+ relationship: tosca.relationships.SiteDeployment
+ requirements:
+ - controller:
+ node: CloudLab
+ relationship: tosca.relationships.UsesController
+
+ Public shared IPv4:
+ type: tosca.nodes.NetworkTemplate
+ properties:
+ visibility: private
+ translation: NAT
+ shared_network_name: { get_artifact: [ SELF, flat_net_name, LOCAL_FILE] }
+ artifacts:
+ flat_net_name: /root/setup/flat_net_name
+
+ padmin@vicci.org:
+ type: tosca.nodes.User
+ requirements:
+ - site:
+ node: mysite
+ relationship: tosca.relationships.MemberOfSite
+ properties:
+ public_key: { get_artifact: [ SELF, pubkey, LOCAL_FILE ] }
+ is_admin: true
+ is_active: true
+ firstname: XOS
+ lastname: admin
+ artifacts:
+ pubkey: /root/setup/padmin_public_key
diff --git a/xos/configurations/common/cloudlab.yaml b/xos/configurations/common/cloudlab.yaml
deleted file mode 100644
index a0beeeb..0000000
--- a/xos/configurations/common/cloudlab.yaml
+++ /dev/null
@@ -1,89 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0
-
-# Note:
-# assumes the following have been created and filled with appropriate data:
-# /root/setup/admin_openrc
-# /root/setup/flat_net_name
-# /root/setup/padmin_public_key
-
-description: >
- * Adds OpenCloud Sites, Deployments, and Controllers.
-
-imports:
- - custom_types/xos.yaml
-
-topology_template:
- node_templates:
- trusty-server-multi-nic:
- type: tosca.nodes.Image
- properties:
- disk_format: QCOW2
- container_format: BARE
-
- MyDeployment:
- type: tosca.nodes.Deployment
- properties:
- flavors: m1.large, m1.medium, m1.small
- requirements:
- - image:
- node: trusty-server-multi-nic
- relationship: tosca.relationships.SupportsImage
-
- CloudLab:
- type: tosca.nodes.Controller
- requirements:
- - deployment:
- node: MyDeployment
- relationship: tosca.relationships.ControllerDeployment
- properties:
- backend_type: OpenStack
- version: Juno
- auth_url: { get_script_env: [ SELF, adminrc, OS_AUTH_URL, LOCAL_FILE] }
- admin_user: { get_script_env: [ SELF, adminrc, OS_USERNAME, LOCAL_FILE] }
- admin_password: { get_script_env: [ SELF, adminrc, OS_PASSWORD, LOCAL_FILE] }
- admin_tenant: { get_script_env: [ SELF, adminrc, OS_TENANT_NAME, LOCAL_FILE] }
- rabbit_user: { get_script_env: [ SELF, controller_settings, RABBIT_USER, LOCAL_FILE] }
- rabbit_password: { get_script_env: [ SELF, controller_settings, RABBIT_PASS, LOCAL_FILE] }
- rabbit_host: { get_script_env: [ SELF, controller_settings, CONTROLLER_FLAT_LAN_IP, LOCAL_FILE] }
- domain: Default
- artifacts:
- adminrc: /root/setup/admin-openrc.sh
- controller_settings: /root/setup/controller_settings
-
- mysite:
- type: tosca.nodes.Site
- properties:
- display_name: MySite
- site_url: http://opencloud.us/
- requirements:
- - deployment:
- node: MyDeployment
- relationship: tosca.relationships.SiteDeployment
- requirements:
- - controller:
- node: CloudLab
- relationship: tosca.relationships.UsesController
-
- Public shared IPv4:
- type: tosca.nodes.NetworkTemplate
- properties:
- visibility: private
- translation: NAT
- shared_network_name: { get_artifact: [ SELF, flat_net_name, LOCAL_FILE] }
- artifacts:
- flat_net_name: /root/setup/flat_net_name
-
- padmin@vicci.org:
- type: tosca.nodes.User
- requirements:
- - site:
- node: mysite
- relationship: tosca.relationships.MemberOfSite
- properties:
- public_key: { get_artifact: [ SELF, pubkey, LOCAL_FILE ] }
- is_admin: true
- is_active: true
- firstname: XOS
- lastname: admin
- artifacts:
- pubkey: /root/setup/padmin_public_key
diff --git a/xos/configurations/common/devstack.yaml b/xos/configurations/common/devstack.yaml
deleted file mode 100644
index cd17b1c..0000000
--- a/xos/configurations/common/devstack.yaml
+++ /dev/null
@@ -1,87 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0
-
-# Note:
-# assumes the following have been created and filled with appropriate data:
-# /root/setup/admin_openrc
-# /root/setup/flat_net_name
-# /root/setup/padmin_public_key
-
-description: >
- * Adds OpenCloud Sites, Deployments, and Controllers.
-
-imports:
- - custom_types/xos.yaml
-
-topology_template:
- node_templates:
- cirros-0.3.4-x86_64-uec:
- type: tosca.nodes.Image
- properties:
- disk_format: RAW
- container_format: BARE
-
- MyDeployment:
- type: tosca.nodes.Deployment
- properties:
- flavors: m1.large, m1.medium, m1.small
- requirements:
- - image:
- node: cirros-0.3.4-x86_64-uec
- relationship: tosca.relationships.SupportsImage
-
- CloudLab:
- type: tosca.nodes.Controller
- requirements:
- - deployment:
- node: MyDeployment
- relationship: tosca.relationships.ControllerDeployment
- properties:
- backend_type: OpenStack
- version: Kilo
- auth_url: { get_script_env: [ SELF, adminrc, OS_AUTH_URL, LOCAL_FILE] }
- admin_user: { get_script_env: [ SELF, adminrc, OS_USERNAME, LOCAL_FILE] }
- admin_password: { get_script_env: [ SELF, adminrc, OS_PASSWORD, LOCAL_FILE] }
- admin_tenant: { get_script_env: [ SELF, adminrc, OS_TENANT_NAME, LOCAL_FILE] }
- rabbit_user: { get_script_env: [ SELF, controller_settings, RABBIT_USER, LOCAL_FILE] }
- rabbit_password: { get_script_env: [ SELF, controller_settings, RABBIT_PASS, LOCAL_FILE] }
- rabbit_host: { get_script_env: [ SELF, controller_settings, CONTROLLER_IP, LOCAL_FILE] }
- domain: Default
- artifacts:
- adminrc: /root/setup/admin-openrc.sh
- controller_settings: /root/setup/controller_settings
-
- mysite:
- type: tosca.nodes.Site
- properties:
- display_name: MySite
- site_url: http://opencloud.us/
- requirements:
- - deployment:
- node: MyDeployment
- relationship: tosca.relationships.SiteDeployment
- requirements:
- - controller:
- node: CloudLab
- relationship: tosca.relationships.UsesController
-
- Public shared IPv4:
- type: tosca.nodes.NetworkTemplate
- properties:
- visibility: private
- translation: NAT
- shared_network_name: private
-
- padmin@vicci.org:
- type: tosca.nodes.User
- requirements:
- - site:
- node: mysite
- relationship: tosca.relationships.MemberOfSite
- properties:
- public_key: { get_artifact: [ SELF, pubkey, LOCAL_FILE ] }
- is_admin: true
- is_active: true
- firstname: XOS
- lastname: admin
- artifacts:
- pubkey: /root/setup/padmin_public_key
diff --git a/xos/configurations/devstack/local.conf b/xos/configurations/common/devstack/local.conf
similarity index 100%
rename from xos/configurations/devstack/local.conf
rename to xos/configurations/common/devstack/local.conf
diff --git a/xos/configurations/devstack/net-fix.sh b/xos/configurations/common/devstack/net-fix.sh
similarity index 100%
rename from xos/configurations/devstack/net-fix.sh
rename to xos/configurations/common/devstack/net-fix.sh
diff --git a/xos/configurations/common/make-cloudlab-nodes-yaml.sh b/xos/configurations/common/make-cloudlab-nodes-yaml.sh
deleted file mode 100644
index f2555a4..0000000
--- a/xos/configurations/common/make-cloudlab-nodes-yaml.sh
+++ /dev/null
@@ -1,37 +0,0 @@
-#FN=/opt/xos/configurations/common/cloudlab-nodes.yaml
-FN=cloudlab-nodes.yaml
-
-rm -f $FN
-
-cat >> $FN <<EOF
-tosca_definitions_version: tosca_simple_yaml_1_0
-
-imports:
- - custom_types/xos.yaml
-
-description: autogenerated cloudlab nodes file
-
-topology_template:
- node_templates:
- MyDeployment:
- type: tosca.nodes.Deployment
- mysite:
- type: tosca.nodes.Site
-EOF
-
-NODES=$( bash -c "source ./admin-openrc.sh ; nova hypervisor-list" |grep enabled|awk '{print $4}' )
-I=0
-for NODE in $NODES; do
- echo $NODE
- cat >> $FN <<EOF
- $NODE:
- type: tosca.nodes.Node
- requirements:
- - site:
- node: mysite
- relationship: tosca.relationships.MemberOfSite
- - deployment:
- node: MyDeployment
- relationship: tosca.relationships.MemberOfDeployment
-EOF
-done
diff --git a/xos/configurations/common/make-nodes-yaml.sh b/xos/configurations/common/make-nodes-yaml.sh
new file mode 100644
index 0000000..1c0003a
--- /dev/null
+++ b/xos/configurations/common/make-nodes-yaml.sh
@@ -0,0 +1,36 @@
+FN=$SETUPDIR/nodes.yaml
+
+rm -f $FN
+
+cat >> $FN <<EOF
+tosca_definitions_version: tosca_simple_yaml_1_0
+
+imports:
+ - custom_types/xos.yaml
+
+description: autogenerated nodes file
+
+topology_template:
+ node_templates:
+ MyDeployment:
+ type: tosca.nodes.Deployment
+ mysite:
+ type: tosca.nodes.Site
+EOF
+
+NODES=$( bash -c "source $SETUPDIR/admin-openrc.sh ; nova hypervisor-list" |grep enabled|awk '{print $4}' )
+I=0
+for NODE in $NODES; do
+ echo $NODE
+ cat >> $FN <<EOF
+ $NODE:
+ type: tosca.nodes.Node
+ requirements:
+ - site:
+ node: mysite
+ relationship: tosca.relationships.MemberOfSite
+ - deployment:
+ node: MyDeployment
+ relationship: tosca.relationships.MemberOfDeployment
+EOF
+done
diff --git a/xos/configurations/common/xos_common_config b/xos/configurations/common/xos_common_config
index df30b54..b06098e 100644
--- a/xos/configurations/common/xos_common_config
+++ b/xos/configurations/common/xos_common_config
@@ -33,7 +33,7 @@
[observer]
pretend=False
-backoff_disabled=False
+backoff_disabled=True
images_directory=/opt/xos/images
dependency_graph=/opt/xos/model-deps
logfile=/var/log/xos_backend.log
diff --git a/xos/configurations/cord/Dockerfile.cord b/xos/configurations/cord/Dockerfile.cord
index a436871..9fde1b0 100644
--- a/xos/configurations/cord/Dockerfile.cord
+++ b/xos/configurations/cord/Dockerfile.cord
@@ -2,7 +2,7 @@
ADD xos/configurations/common/admin-openrc.sh /root/setup/
ADD xos/configurations/common/controller_settings /root/setup/
ADD xos/configurations/common/flat_net_name /root/setup/
-ADD xos/configurations/common/cloudlab-nodes.yaml /opt/xos/configurations/commmon/
+ADD xos/configurations/common/nodes.yaml /opt/xos/configurations/commmon/
ADD xos/configurations/common/id_rsa.pub /root/setup/padmin_public_key
ADD xos/configurations/common/id_rsa.pub /opt/xos/observers/vcpe/vcpe_public_key
ADD xos/configurations/common/id_rsa /opt/xos/observers/vcpe/vcpe_private_key
diff --git a/xos/configurations/cord/Makefile b/xos/configurations/cord/Makefile
index 80b71e0..c95d9dd 100644
--- a/xos/configurations/cord/Makefile
+++ b/xos/configurations/cord/Makefile
@@ -1,40 +1,48 @@
+SETUPDIR:=../setup
MYIP:=$(shell hostname -i)
-RUNNING_CONTAINER:=$(shell sudo docker ps|grep "xos"|awk '{print $$NF}')
-LAST_CONTAINER=$(shell sudo docker ps -l -q)
-cord: common_cloudlab ceilometer_dashboard virtualbng_json vtn_network_cfg_json
- rm ../../xos_configuration/*
- echo "# Autogenerated -- do not edit" > Dockerfile
- cat ../common/Dockerfile.common Dockerfile.cord >> Dockerfile
- cp ../common/xos_common_config ../../xos_configuration/
- cp ./xos_cord_config ../../xos_configuration/
- cd ../../..; sudo docker build -t xos -f xos/configurations/cord/Dockerfile .
- sudo docker run -d --add-host="ctl:$(MYIP)" -p 9999:8000 xos
+cloudlab: common_cloudlab cord
+
+devstack: upgrade_pkgs common_devstack devstack_net_fix cord
+
+cord: ceilometer_dashboard virtualbng_json vtn_network_cfg_json
+ sudo MYIP=$(MYIP) docker-compose up -d
bash ../common/wait_for_xos.sh
+ sudo MYIP=$(MYIP) docker-compose run xos python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/fixtures.yaml
+ sudo MYIP=$(MYIP) docker-compose run xos python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/base.yaml
+ sudo MYIP=$(MYIP) docker-compose run xos python /opt/xos/tosca/run.py padmin@vicci.org /root/setup/nodes.yaml
+ sudo MYIP=$(MYIP) docker-compose run xos python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/cord/cord.yaml
+ sudo MYIP=$(MYIP) docker-compose run xos python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/cord/ceilometer.yaml
common_cloudlab:
make -C ../common -f Makefile.cloudlab
+common_devstack:
+ make -C ../common -f Makefile.devstack
+
ceilometer_dashboard:
- #NOTE: The below dashboard install scripts assume
+ #NOTE: The below dashboard install scripts assume
#clouldlab openstack environment created using "OpenStack" profile
- bash install_xos_ceilometer_dashboard.sh
+ #bash install_xos_ceilometer_dashboard.sh
bash install_ceilometer_patch.sh
virtualbng_json:
- bash make-virtualbng-json.sh
+ export SETUPDIR=$(SETUPDIR); bash make-virtualbng-json.sh
vtn_network_cfg_json:
- bash make-vtn-networkconfig-json.sh
+ export SETUPDIR=$(SETUPDIR); bash make-vtn-networkconfig-json.sh
stop:
- sudo docker stop $(RUNNING_CONTAINER)
+ sudo MYIP=$(MYIP) docker-compose stop
+
+rm:
+ sudo MYIP=$(MYIP) docker-compose rm
showlogs:
- sudo docker logs $(LAST_CONTAINER)
+ sudo MYIP=$(MYIP) docker-compose logs
-enter:
- sudo docker exec -t -i $(RUNNING_CONTAINER) bash
+ps:
+ sudo MYIP=$(MYIP) docker-compose ps
dataplane: etc_hosts
cd dataplane; ./gen-inventory.sh > hosts
@@ -55,7 +63,14 @@
# reboot the vBNG ONOS
cd dataplane; ansible -i hosts onos_vbng -m shell -s -a "docker restart ONOS"
-cleanup: stop
+cleanup: stop rm
cd dataplane; ./cleanup.sh
- bash -c "source ../common/admin-openrc.sh; nova list --all-tenants; neutron net-list"
- echo "Don't forget to clean up containers"
+ bash -c "source ../setup/admin-openrc.sh; nova list --all-tenants; neutron net-list"
+ echo "Don't forget to clean up vCPE containers"
+
+devstack_net_fix:
+ sudo ../common/devstack/net-fix.sh
+ sudo bash -c "source ../setup/admin-openrc.sh; neutron subnet-update private-subnet --dns-nameservers list=true 8.8.8.8 8.8.4.4"
+
+upgrade_pkgs:
+ sudo pip install httpie --upgrade
diff --git a/xos/configurations/cord/Makefile.inside b/xos/configurations/cord/Makefile.inside
index b8e23f8..d7bdbaf 100644
--- a/xos/configurations/cord/Makefile.inside
+++ b/xos/configurations/cord/Makefile.inside
@@ -1,10 +1,10 @@
all: setup_xos run_develserver
setup_xos:
- bash /opt/xos/scripts/docker_setup_xos
+ bash /opt/xos/tools/docker_setup_xos
python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/fixtures.yaml
- python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/cloudlab.yaml
- python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/cloudlab-nodes.yaml
+ python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/base.yaml
+ python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/nodes.yaml
python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/cord/cord.yaml
python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/cord/ceilometer.yaml
diff --git a/xos/configurations/cord/README-VTN.md b/xos/configurations/cord/README-VTN.md
index d585d5c..b51bae7 100644
--- a/xos/configurations/cord/README-VTN.md
+++ b/xos/configurations/cord/README-VTN.md
@@ -1,8 +1,19 @@
vtn notes:
-inside the xos container:
+see also: https://github.com/hyunsun/documentations/wiki/Neutron-ONOS-Integration-for-CORD-VTN#onos-setup
+
+VTN doesn't seem to like cloudlab's networks (flat-net-1, ext-net, etc). I've placed a script in xos/scripts/ called destroy-all-networks.sh that will automate tearing down all of cloudlab's neutron networks.
+
+ cd xos/scripts
+ ./destroy-all-networks.sh
+
+inside the xos container, update the configuration. Make sure to restart Openstack Synchronizer afterward. Might be a good idea to restart the XOS UI as well:
python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/tosca/samples/vtn.yaml
+ emacs /opt/xos/xos_configuration/xos_common_config
+ [networking]
+ use_vtn=True
+ supervisorctl restart observer
ctl node:
@@ -10,6 +21,7 @@
ONOS_VTN_HOSTNAME="cp-2.smbaker-xos5.xos-pg0.clemson.cloudlab.us"
apt-get -y install python-pip
pip install -U setuptools pip
+ pip install testrepository
git clone https://github.com/openstack/networking-onos.git
cd networking-onos
python setup.py install
@@ -18,28 +30,78 @@
# not still an issue lurking...
cat > /usr/local/etc/neutron/plugins/ml2/conf_onos.ini <<EOF
[ml2_onos]
- url_path = http://$ONOS_VTN_HOSTNAME:8181/onos/vtn
+ url_path = http://$ONOS_VTN_HOSTNAME:8181/onos/openstackswitching
username = karaf
password = karaf
EOF
emacs /etc/neutron/plugins/ml2/ml2_conf.ini
update settings as per vtn docs ([ml2] and [ml2_type_vxlan] sections)
- systemctl restart neutron-server
+ systemctl stop neutron-server
+ # I started neutron manually to make sure it's using exactly the right config
+ # files. Maybe it can be restarted using systemctl instead...
+ /usr/bin/neutron-server --config-file /etc/neutron/neutron.conf --config-file /etc/neutron/plugins/ml2/ml2_conf.ini --config-file /usr/local/etc/neutron/plugins/ml2/conf_onos.ini
-Compute node that has the ONOS Container
+Neutron driver arg-parsing issue
- # we need NAT rule so the neutron vtn plugin can talk to onos
- # change 172.17.0.2 to the IP address for the ONOS container (use "docker inspect")
- iptables -t nat -A PREROUTING -i br-ex -p tcp --dport 8101 -j DNAT --to-destination 172.17.0.2
+ # For some reason, the VTN Neutron plugin isn't getting its arguments from neutron
+ emacs /usr/local/lib/python2.7/dist-packages/networking_onos/plugins/ml2/driver.py
+ hard-code self.onos_path and self.onos_auth
+
+Compute nodes and nm nodes:
-Compute nodes (all of them):
-
- systemctl stop neutron-plugin-openvswitch-agent
- /usr/share/openvswitch/scripts/ovs-ctl
- update settings as per vtn docs to make port 6640 visible
- service openvswitch-switch restart
-
-VTN doesn't seem to like cloudlab's networks (flat-net-1, ext-net, etc). You might have to delete them all.
+ cd xos/configurations/cord/dataplane
+ ./generate-bm.sh > hosts-bm
+ ansible-playbook -i hosts-bm dataplane-vtn.yaml
+ # the playbook will:
+ # 1) turn off neutron openvswitch-agent
+ # 2) set openvswitch to listen on port 6641
+ # 3) restart openvswitch
+ # 4) delete any existing br-int bridge
+ # 5) [nm only] turn off neutron-dhcp-agent
For development, I suggest using the bash configuration (remember to start the ONOS observer manually) so that
there aren't a bunch of preexisting Neutron networks and nova instances to get in the way.
+
+Notes:
+* I've configured the OpenvSwitch switches to use port 6641 instead of port 6640. This is because the VTN app listens on 6640
+itself, and since we're running it in docker 'host' networking mode now, it would conflict with an Openvswitch that was
+also listening on 6640.
+* Adding use_vtn=True to the [networking] section in the XOS config file has two effects: 1) it sets the gateway in sync_controller_networks, and 2) it disables automatic creation of nat-net for new slices. This is because VTN will fail if there is no gateway on a network, and because we don't have nat-net under the VTN configuration.
+* When using of-vfctl to look at flow rules, if you get a protocol error, try "ovs-ofctl show -O OpenFlow13 br-int "
+* Note that the VTN Synchronizer isn't started automatically. It's only use for inter-Service connectivity, so no need to mess with it until intra-Slice connectivity is working first.
+* Note that the VTN Synchronizer won't connect non-access networks. Any network templates you want VTN to connect must have Access set to "Direct" or "Indirect".
+
+There is no management network yet, so no way to SSH into the slices. I've been setting up a VNC tunnel, like this:
+
+ # on compute node, run the following and note the IP address and port number
+ virsh vncdisplay <instance-id>
+
+ # from home
+ ssh -o "GatewayPorts yes" -L <port+5900>:<IP>:<port+5900> <username>@<compute_node_hostname>
+
+ # example
+ ssh -o "GatewayPorts yes" -L 5901:192.168.0.7:5901 smbaker@cp-1.smbaker-xos3.xos-pg0.clemson.cloudlab.us
+
+Then open a VNC session to the local port on your local machine. You'll have a console on the Instance. The username is "Ubuntu" and the password can be obtained from your cloudlab experiment description
+
+Things that can be tested:
+
+* Create an Instance, it should have a Private network, and there should be a tap attached from the instance to br-int
+* Two Instances in the same Slice can talk to one another. They can be on the same machine or different machines.
+* Two Slices can talk to one another if the slices are associated with Services and those Services have a Tenancy relationship between them. Note that 1) The VTN Synchronizer must be running, 2) There must be a Private network with Access=[Direct|Indirect], and 3) The connectivity is unidirectional, from subscriber service to provider service.
+
+Testing service composition
+
+1. Change the private network template's 'Access' field from None to Direct
+2. Create a Service, Service-A
+3. Enter Slice Admin for Slice-1 and assign it to Service-A
+4. Create a Service, Service-B
+5. Enter Slice Admin for Slice-2 and assign it to Service-B
+6. Enter Service Admin for Service-B, Go to Tenancy Tab
+7. In the 'Provided Tenants' section of Service-B, create a Tenant with Subsciber-Service=Serivce-A.
+8. Start the VTN Observer. It will send a REST request to VTN app.
+9. Launch tcpdump in one of Slice-2's instances
+10. From Slice-1, start pinging the instance in Slice-2 where you launched tcpdump
+11. You should see the pings arrive and responses sent out. Note that the ping responses will not reach Slice-1, since VTN traffic is unidirectional.
+12. Delete the Tenancy relation you created in Step #7. The ping traffic should no longer appear in the tcpdump.
+
diff --git a/xos/configurations/cord/dataplane/change_controller.sh b/xos/configurations/cord/dataplane/change_controller.sh
new file mode 100755
index 0000000..2b961ee
--- /dev/null
+++ b/xos/configurations/cord/dataplane/change_controller.sh
@@ -0,0 +1,13 @@
+#! /bin/bash
+
+# put IP address of node running ONOS VTN App here
+DESIRED_CONTROLLER="tcp:130.127.133.24:6653"
+
+while [[ 1 ]]; do
+ CONTROLLER=`ovs-vsctl get-controller br-int`
+ if [[ "$CONTROLLER" == "tcp:172.17.0.2:6653" ]]; then
+ ovs-vsctl set-controller br-int $DESIRED_CONTROLLER
+ echo "changed controller from $CONTROLLER to $DESIRED_CONTROLLER"
+ fi
+ sleep 10s
+done
diff --git a/xos/configurations/cord/dataplane/cleanup.sh b/xos/configurations/cord/dataplane/cleanup.sh
index 721f054..9860de7 100755
--- a/xos/configurations/cord/dataplane/cleanup.sh
+++ b/xos/configurations/cord/dataplane/cleanup.sh
@@ -13,7 +13,7 @@
neutron net-delete $NETWORK
}
-source ../../common/admin-openrc.sh
+source ../../setup/admin-openrc.sh
echo "Deleting VMs"
# Delete all VMs
diff --git a/xos/configurations/cord/dataplane/dataplane-vtn.yaml b/xos/configurations/cord/dataplane/dataplane-vtn.yaml
new file mode 100644
index 0000000..f6561b5
--- /dev/null
+++ b/xos/configurations/cord/dataplane/dataplane-vtn.yaml
@@ -0,0 +1,31 @@
+---
+- hosts: baremetal:nm
+
+ user: root
+ sudo: no
+ tasks:
+ - name: stop neutron openvswitch agent
+ service: name=neutron-plugin-openvswitch-agent state=stopped
+
+ - name: Update openvswitch config
+ lineinfile:
+ dest=/usr/share/openvswitch/scripts/ovs-ctl
+ insertafter="set ovsdb-server.*DB_FILE.*"
+ regexp=".*set.*--remote=ptcp.*"
+ line=" set \"$@\" --remote=ptcp:6641"
+ state=present
+
+ - name: Restart openvswitch
+ service: name=openvswitch-switch state=restarted
+
+ - name: Delete br-int
+ shell: ovs-vsctl show | grep -i br-int > /dev/null && ovs-vsctl del-br br-int
+ ignore_errors: yes
+
+- hosts: nm
+
+ user: root
+ sudo: no
+ tasks:
+ - name: stop neutron dhcp agent
+ service: name=neutron-dhcp-agent state=stopped
diff --git a/xos/configurations/cord/dataplane/gen-etc-hosts.sh b/xos/configurations/cord/dataplane/gen-etc-hosts.sh
index ce98731..6c07ef9 100755
--- a/xos/configurations/cord/dataplane/gen-etc-hosts.sh
+++ b/xos/configurations/cord/dataplane/gen-etc-hosts.sh
@@ -1,7 +1,7 @@
#!/bin/bash
# set -x
-source ../../common/admin-openrc.sh
+source ../../setup/admin-openrc.sh
get_ip () {
LABEL=$1
diff --git a/xos/configurations/cord/dataplane/gen-inventory.sh b/xos/configurations/cord/dataplane/gen-inventory.sh
index 590376d..74a5ac8 100755
--- a/xos/configurations/cord/dataplane/gen-inventory.sh
+++ b/xos/configurations/cord/dataplane/gen-inventory.sh
@@ -1,7 +1,7 @@
#!/bin/bash
# set -x
-source ../../common/admin-openrc.sh
+source ../../setup/admin-openrc.sh
get_ip () {
LABEL=$1
diff --git a/xos/configurations/cord/dataplane/generate-bm.sh b/xos/configurations/cord/dataplane/generate-bm.sh
index 25f6fa5..f9b8787 100755
--- a/xos/configurations/cord/dataplane/generate-bm.sh
+++ b/xos/configurations/cord/dataplane/generate-bm.sh
@@ -1,4 +1,4 @@
-source ../../common/admin-openrc.sh
+source ../../setup/admin-openrc.sh
get_ip () {
LABEL=$1
@@ -9,7 +9,7 @@
GRENAMES=()
BM_IPS=()
-NODES=`sudo bash -c "source /root/setup/admin-openrc.sh ; nova hypervisor-list" |grep cloudlab|awk '{print $4}'`
+NODES=`sudo bash -c "source ../../setup/admin-openrc.sh ; nova hypervisor-list" |grep enabled|awk '{print $4}'`
I=1
for NODE in $NODES; do
BM_SSH_IP=`getent hosts $NODE | awk '{ print $1 }'`
@@ -29,9 +29,16 @@
echo switch_volt ansible_ssh_host=$( get_ip mysite_volt flat-lan-1-net) grenames=\"$GRE_NAMES\" bm_ips=\"$BM_IPS\"
+NM=`grep "^nm" /root/setup/fqdn.map | awk '{ print $2 }'`
+echo "nm1 ansible_ssh_host=$NM ansible_ssh_private_key_file=/root/.ssh/id_rsa"
+
echo "[baremetal]"
I=1
for NODE in $NODES; do
echo bm$I
I=$((I+1))
done
+
+# now for the network management node
+echo "[nm]"
+echo "nm1"
diff --git a/xos/configurations/cord/docker-compose.yml b/xos/configurations/cord/docker-compose.yml
new file mode 100644
index 0000000..83af3f9
--- /dev/null
+++ b/xos/configurations/cord/docker-compose.yml
@@ -0,0 +1,95 @@
+xos_db:
+ image: xosproject/xos-postgres
+ expose:
+ - "5432"
+
+xos_synchronizer_openstack:
+ command: bash -c "sleep 120 ; python /opt/xos/synchronizers/openstack/xos-synchronizer.py"
+ image: xosproject/xos-synchronizer-openstack
+ labels:
+ org.xosproject.kind: synchronizer
+ org.xosproject.target: openstack
+ links:
+ - xos_db
+ extra_hosts:
+ - ctl:${MYIP}
+ volumes:
+ - ../common/xos_common_config:/opt/xos/xos_configuration/xos_common_config:ro
+ - ./xos_cord_config:/opt/xos/xos_configuration/xos_cord_config:ro
+ - ../setup:/root/setup:ro
+
+xos_synchronizer_onos:
+ image: xosproject/xos-synchronizer-openstack
+ command: bash -c "sleep 120 ; python /opt/xos/synchronizers/onos/onos-synchronizer.py -C /opt/xos/synchronizers/onos/onos_synchronizer_config"
+ labels:
+ org.xosproject.kind: synchronizer
+ org.xosproject.target: onos
+ links:
+ - xos_db
+ extra_hosts:
+ - ctl:${MYIP}
+ volumes:
+ - ../setup/id_rsa:/opt/xos/observers/onos/onos_key:ro # private key
+
+xos_synchronizer_vcpe:
+ image: xosproject/xos-synchronizer-openstack
+ #command: /usr/bin/supervisord -c /opt/xos/observers/vcpe/supervisor/vcpe-observer.conf
+ command: bash -c "sleep 120 ; python /opt/xos/synchronizers/vcpe/vcpe-synchronizer.py -C /opt/xos/synchronizers/vcpe/vcpe_synchronizer_config"
+ labels:
+ org.xosproject.kind: synchronizer
+ org.xosproject.target: vcpe
+ links:
+ - xos_db
+ extra_hosts:
+ - ctl:${MYIP}
+ volumes:
+ - ../setup/id_rsa:/opt/xos/observers/vcpe/vcpe_private_key:ro # private key
+ - ../setup:/root/setup:ro
+
+xos_synchronizer_vbng:
+ image: xosproject/xos-synchronizer-openstack
+ command: bash -c "sleep 120 ; python /opt/xos/synchronizers/vbng/vbng-synchronizer.py -C /opt/xos/synchronizers/vbng/vbng_synchronizer_config"
+ labels:
+ org.xosproject.kind: synchronizer
+ org.xosproject.target: vbng
+ links:
+ - xos_db
+ extra_hosts:
+ - ctl:${MYIP}
+
+xos_synchronizer_monitoring_channel:
+ image: xosproject/xos-synchronizer-openstack
+ #command: /usr/bin/supervisord -c /opt/xos/observers/monitoring_channel/supervisor/monitoring_channel_observer.conf
+ command: bash -c "sleep 120 ; python /opt/xos/synchronizers/monitoring_channel/monitoring_channel_synchronizer.py -C /opt/xos/synchronizers/monitoring_channel/monitoring_channel_synchronizer_config"
+ labels:
+ org.xosproject.kind: synchronizer
+ org.xosproject.target: monitoring_channel
+ links:
+ - xos_db
+ extra_hosts:
+ - ctl:${MYIP}
+ volumes:
+ - ../setup/id_rsa:/opt/xos/observers/monitoring_channel/monitoring_channel_private_key:ro # private key
+
+
+# FUTURE
+#xos_swarm_synchronizer:
+# image: xosproject/xos-swarm-synchronizer
+# labels:
+# org.xosproject.kind: synchronizer
+# org.xosproject.target: swarm
+
+xos:
+ image: xosproject/xos
+ command: python /opt/xos/manage.py runserver 0.0.0.0:8000 --insecure --makemigrations
+ ports:
+ - "9999:8000"
+ links:
+ - xos_db
+ volumes:
+ - ../setup:/root/setup:ro
+ - ../common/xos_common_config:/opt/xos/xos_configuration/xos_common_config:ro
+ - ./xos_cord_config:/opt/xos/xos_configuration/xos_cord_config:ro
+ - ../setup/id_rsa.pub:/opt/xos/observers/onos/onos_key.pub:ro
+ - ../setup/id_rsa.pub:/opt/xos/observers/vcpe/vcpe_public_key:ro
+ - ../setup/id_rsa.pub:/opt/xos/observers/monitoring_channel/monitoring_channel_public_key:ro
diff --git a/xos/configurations/cord/etc_xos_metering.tar.gz b/xos/configurations/cord/etc_xos_metering.tar.gz
deleted file mode 100644
index 53689db..0000000
--- a/xos/configurations/cord/etc_xos_metering.tar.gz
+++ /dev/null
Binary files differ
diff --git a/xos/configurations/cord/install_ceilometer_vcpe_notification_listener.sh b/xos/configurations/cord/install_ceilometer_vcpe_notification_listener.sh
deleted file mode 100644
index 50a4132..0000000
--- a/xos/configurations/cord/install_ceilometer_vcpe_notification_listener.sh
+++ /dev/null
@@ -1,16 +0,0 @@
-if [ -d /usr/lib/python2.7/dist-packages/ceilometer/network/ext_services ]; then
- echo "Seems VCPE notification listeners are already enabled in ceilometer... so exiting gracefully..."
- exit 0
-fi
-echo "Verifying if all the required files are present"
-if [ ! -f ceilometer_vcpe_notification_agent.tar.gz ];
-then
- echo "File ceilometer_vcpe_notification_agent.tar.gz not found"
- exit 1
-fi
-echo "Copying the ceilometer vcpe notification agent files /usr/lib/python2.7/dist-packages/ceilometer"
-tar -xzf ceilometer_vcpe_notification_agent.tar.gz
-sudo mv ceilometer/network/ext_services /usr/lib/python2.7/dist-packages/ceilometer/network/
-sudo mv ceilometer-2015.1.1.egg-info/entry_points.txt /usr/lib/python2.7/dist-packages/ceilometer-2015.1.1.egg-info/
-echo "Restarting ceilometer-agent-notification"
-sudo service ceilometer-agent-notification restart
diff --git a/xos/configurations/cord/install_xos_ceilometer_dashboard.sh b/xos/configurations/cord/install_xos_ceilometer_dashboard.sh
deleted file mode 100755
index ed72f54..0000000
--- a/xos/configurations/cord/install_xos_ceilometer_dashboard.sh
+++ /dev/null
@@ -1,25 +0,0 @@
-if [ -d /usr/share/xos-metering ]; then
- echo "Seems xos ceilometer dashboard is already installed... so exiting gracefully..."
- exit 0
-fi
-echo "Verifying if all the required files are present"
-if [ ! -f xos_metering_dashboard.tar.gz ];
-then
- echo "File xos_metering_dashboard.tar.gz not found"
- exit 1
-fi
-if [ ! -f etc_xos_metering.tar.gz ];
-then
- echo "File etc_xos_metering.tar.gz not found"
- exit 1
-fi
-echo "Copying the xos ceilometer dashboard files /usr/share/ and /etc/apache2/"
-tar -xzf xos_metering_dashboard.tar.gz
-sudo mv xos-metering /usr/share/
-tar -xzf etc_xos_metering.tar.gz
-sudo mv xos-metering /etc/
-sudo mv apache2/conf-available/xos-metering.conf /etc/apache2/conf-available/
-cd /etc/apache2/conf-enabled/
-sudo ln -s ../conf-available/xos-metering.conf xos-metering.conf
-echo "Restarting apache2"
-sudo service apache2 restart
diff --git a/xos/configurations/cord/make-virtualbng-json.sh b/xos/configurations/cord/make-virtualbng-json.sh
index 0e1d350..8eb971b 100644
--- a/xos/configurations/cord/make-virtualbng-json.sh
+++ b/xos/configurations/cord/make-virtualbng-json.sh
@@ -1,5 +1,4 @@
-#FN=/opt/xos/configurations/common/cloudlab-nodes.yaml
-FN=virtualbng.json
+FN=$SETUPDIR/virtualbng.json
rm -f $FN
@@ -15,7 +14,7 @@
"hosts" : {
EOF
-NODES=$( sudo bash -c "source /root/setup/admin-openrc.sh ; nova hypervisor-list" |grep cloudlab|awk '{print $4}' )
+NODES=$( sudo bash -c "source $SETUPDIR/admin-openrc.sh ; nova hypervisor-list" |grep enabled|awk '{print $4}' )
NODECOUNT=0
for NODE in $NODES; do
diff --git a/xos/configurations/cord/make-vtn-networkconfig-json.sh b/xos/configurations/cord/make-vtn-networkconfig-json.sh
index 918674a..5256292 100755
--- a/xos/configurations/cord/make-vtn-networkconfig-json.sh
+++ b/xos/configurations/cord/make-vtn-networkconfig-json.sh
@@ -1,4 +1,6 @@
-FN=vtn-network-cfg.json
+FN=$SETUPDIR/vtn-network-cfg.json
+
+echo "Writing to $FN"
rm -f $FN
@@ -10,7 +12,11 @@
"nodes" : [
EOF
-NODES=$( sudo bash -c "source /root/setup/admin-openrc.sh ; nova hypervisor-list" |grep cloudlab|awk '{print $4}' )
+NODES=$( sudo bash -c "source $SETUPDIR/admin-openrc.sh ; nova hypervisor-list" |grep enabled|awk '{print $4}' )
+
+# also configure ONOS to manage the nm node
+NM=`grep "^nm" /root/setup/fqdn.map | awk '{ print $2 }'`
+NODES="$NODES $NM"
NODECOUNT=0
for NODE in $NODES; do
@@ -27,7 +33,7 @@
{
"hostname": "$NODE",
"ovsdbIp": "$NODEIP",
- "ovsdbPort": "6640",
+ "ovsdbPort": "6641",
"bridgeId": "of:000000000000000$I"
EOF
if [[ "$I" -lt "$NODECOUNT" ]]; then
@@ -38,7 +44,7 @@
done
# get the openstack admin password and username
-source /root/setup/admin-openrc.sh
+source $SETUPDIR/admin-openrc.sh
HOSTNAME=`hostname`
NEUTRONIP=`getent hosts $HOSTNAME | awk '{ print $1 }'`
@@ -46,7 +52,7 @@
cat >> $FN <<EOF
]
- }
+ }
},
"org.onosproject.openstackswitching" : {
"openstackswitching" : {
diff --git a/xos/configurations/cord/xos_metering_dashboard.tar.gz b/xos/configurations/cord/xos_metering_dashboard.tar.gz
deleted file mode 100644
index 3b4d127..0000000
--- a/xos/configurations/cord/xos_metering_dashboard.tar.gz
+++ /dev/null
Binary files differ
diff --git a/xos/configurations/devel/Dockerfile.devel b/xos/configurations/devel/Dockerfile.devel
deleted file mode 100644
index 60c0143..0000000
--- a/xos/configurations/devel/Dockerfile.devel
+++ /dev/null
@@ -1,14 +0,0 @@
-RUN mkdir -p /root/setup
-ADD xos/configurations/common/admin-openrc.sh /root/setup/
-ADD xos/configurations/common/controller_settings /root/setup/
-ADD xos/configurations/common/flat_net_name /root/setup/
-ADD xos/configurations/common/cloudlab-nodes.yaml /opt/xos/configurations/commmon/
-ADD xos/configurations/common/id_rsa.pub /root/setup/padmin_public_key
-ADD xos/configurations/common/id_rsa /opt/xos/observers/helloworldservice_complete/helloworldservice_private_key
-ADD xos/configurations/common/node_key.pub /root/setup/node_key.pub
-ADD xos/configurations/common/node_key /root/setup/node_key
-ADD xos/configurations/common/ceilometer_url /root/setup/ceilometer_url
-
-CMD /usr/bin/make -C /opt/xos/configurations/devel -f Makefile.inside; /bin/bash
-
-#CMD ["/bin/bash"]
diff --git a/xos/configurations/devel/Makefile b/xos/configurations/devel/Makefile
index eb5802a..b4f3fcf 100644
--- a/xos/configurations/devel/Makefile
+++ b/xos/configurations/devel/Makefile
@@ -1,19 +1,14 @@
MYIP:=$(shell hostname -i)
-RUNNING_CONTAINER:=$(shell sudo docker ps|grep "xos"|awk '{print $$NF}')
-LAST_CONTAINER=$(shell sudo docker ps -l -q)
cloudlab: common_cloudlab xos
-devstack: upgrade_pkgs common_devstack devstack_net_fix xos
+devstack: upgrade_pkgs common_devstack xos
xos:
- rm ../../xos_configuration/*
- cp ../common/xos_common_config ../../xos_configuration/
- echo "# Autogenerated -- do not edit" > Dockerfile
- cat ../common/Dockerfile.common Dockerfile.devel >> Dockerfile
- cd ../../..; sudo docker build -t xosproject/xos-devel -f xos/configurations/devel/Dockerfile .
- sudo docker run -d --add-host="ctl:$(MYIP)" -p 9999:8000 xosproject/xos-devel
+ sudo MYIP=$(MYIP) docker-compose up -d
bash ../common/wait_for_xos.sh
+ sudo MYIP=$(MYIP) docker-compose run xos python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/base.yaml
+ sudo MYIP=$(MYIP) docker-compose run xos python /opt/xos/tosca/run.py padmin@vicci.org /root/setup/nodes.yaml
common_cloudlab:
make -C ../common -f Makefile.cloudlab
@@ -22,17 +17,28 @@
make -C ../common -f Makefile.devstack
stop:
- sudo docker stop $(RUNNING_CONTAINER)
+ sudo MYIP=$(MYIP) docker-compose stop
showlogs:
- sudo docker logs $(LAST_CONTAINER)
+ sudo MYIP=$(MYIP) docker-compose logs
-enter:
- sudo docker exec -t -i $(RUNNING_CONTAINER) bash
+rm: stop
+ sudo MYIP=$(MYIP) docker-compose rm
-devstack_net_fix:
- sudo ../devstack/net-fix.sh
- sudo bash -c "source ../common/admin-openrc.sh; neutron subnet-update private-subnet --dns-nameservers list=true 8.8.8.8 8.8.4.4"
+ps:
+ sudo MYIP=$(MYIP) docker-compose ps
+
+enter-xos:
+ sudo docker exec -it devel_xos_1 bash
+
+enter-synchronizer:
+ sudo docker exec -it devel_xos_synchronizer_openstack_1 bash
upgrade_pkgs:
sudo pip install httpie --upgrade
+
+rebuild_xos:
+ make -C ../../../containers/xos devel
+
+rebuild_synchronizer:
+ make -C ../../../containers/synchronizer
diff --git a/xos/configurations/devel/Makefile.inside b/xos/configurations/devel/Makefile.inside
deleted file mode 100644
index 57cde4c..0000000
--- a/xos/configurations/devel/Makefile.inside
+++ /dev/null
@@ -1,9 +0,0 @@
-all: setup_xos run_develserver
-
-setup_xos:
- bash /opt/xos/scripts/docker_setup_xos
- python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/cloudlab.yaml
- python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/cloudlab-nodes.yaml
-
-run_develserver:
- cd /opt/xos; python manage.py runserver 0.0.0.0:8000 --insecure
diff --git a/xos/configurations/devel/README.md b/xos/configurations/devel/README.md
index 54a51a8..2361396 100644
--- a/xos/configurations/devel/README.md
+++ b/xos/configurations/devel/README.md
@@ -1,8 +1,8 @@
# XOS development environment
This configuration can be used to do basic end-to-end development of XOS. It launches
-an XOS container, runs the XOS develserver, and configures XOS to talk to an OpenStack
-backend.
+XOS in three Docker containers (development GUI, Synchronizer, database) and configures XOS
+to talk to an OpenStack backend. *docker-compose* is used to manage the containers.
## How to run it
@@ -42,7 +42,7 @@
~$ git clone https://github.com/open-cloud/xos.git
~$ git clone https://git.openstack.org/openstack-dev/devstack
~$ cd devstack
-~/devstack$ cp ../xos/xos/configurations/devstack/local.conf .
+~/devstack$ cp ../xos/xos/configurations/common/devstack/local.conf .
~/devstack$ ./stack.sh
~/devstack$ cd ../xos/xos/configurations/devel/
~/xos/xos/configurations/devel$ make devstack
@@ -56,3 +56,19 @@
Note that there are some issues with the networking setup in this configuration:
VMs do not have a working DNS configuration in `/etc/resolv.conf`. If you fix this
manually then everything should work.
+
+## Docker Helpers
+
+Stop the containers: `make stop`
+
+Restart the containers: `make stop; make [cloudlab|devstack]`
+
+Delete the containers and relaunch them: `make rm; make [cloudlab|devstack]`
+
+View logs: `make showlogs`
+
+See what containers are running: `make ps`
+
+Open a shell on the XOS container: `make enter-xos`
+
+Open a shell on the Synchronizer container: `make enter-synchronizer`
diff --git a/xos/configurations/devel/docker-compose.yml b/xos/configurations/devel/docker-compose.yml
new file mode 100644
index 0000000..803e57c
--- /dev/null
+++ b/xos/configurations/devel/docker-compose.yml
@@ -0,0 +1,35 @@
+xos_db:
+ image: xosproject/xos-postgres
+ expose:
+ - "5432"
+
+xos_synchronizer_openstack:
+ image: xosproject/xos-synchronizer-openstack
+ command: bash -c "sleep 120; python /opt/xos/synchronizers/openstack/xos-synchronizer.py"
+ labels:
+ org.xosproject.kind: synchronizer
+ org.xosproject.target: openstack
+ links:
+ - xos_db
+ extra_hosts:
+ - ctl:${MYIP}
+ volumes:
+ - ../common/xos_common_config:/opt/xos/xos_configuration/xos_common_config:ro
+
+# FUTURE
+#xos_swarm_synchronizer:
+# image: xosproject/xos-swarm-synchronizer
+# labels:
+# org.xosproject.kind: synchronizer
+# org.xosproject.target: swarm
+
+xos:
+ image: xosproject/xos
+ command: python /opt/xos/manage.py runserver 0.0.0.0:8000 --insecure --makemigrations
+ ports:
+ - "9999:8000"
+ links:
+ - xos_db
+ volumes:
+ - ../setup:/root/setup:ro
+ - ../common/xos_common_config:/opt/xos/xos_configuration/xos_common_config:ro
diff --git a/xos/configurations/frontend/Dockerfile.frontend b/xos/configurations/frontend/Dockerfile.frontend
deleted file mode 100644
index 8372fbf..0000000
--- a/xos/configurations/frontend/Dockerfile.frontend
+++ /dev/null
@@ -1,13 +0,0 @@
-
-###############################################################################
-########################## START FRONTEND TASKS ###############################
-###############################################################################
-
-RUN mkdir -p /root/setup
-
-RUN echo "autostart=false" >> /etc/supervisor/conf.d/observer.conf
-
-# TODO
-# - Enter /opt/xos/core/xoslib and run npm install
-
-CMD /usr/bin/make -C /opt/xos/configurations/frontend -f Makefile.inside
diff --git a/xos/configurations/frontend/Makefile b/xos/configurations/frontend/Makefile
index e30877a..4c95f90 100644
--- a/xos/configurations/frontend/Makefile
+++ b/xos/configurations/frontend/Makefile
@@ -1,37 +1,22 @@
MYIP:=$(shell hostname -i)
-RUNNING_CONTAINER=$(shell sudo docker ps|grep "xos"|awk '{print $$NF}')
-LAST_CONTAINER=$(shell sudo docker ps -l -q)
-XOS_FOLDER=$(shell pwd)
-
-all: frontend
frontend:
- rm ../../xos_configuration/*
- sudo apt-get -y install httpie
- cat ../common/Dockerfile.common Dockerfile.frontend > Dockerfile
- cp ../common/xos_common_config ../../xos_configuration/
- cd ../../..; sudo docker build -t xos -f xos/configurations/frontend/Dockerfile .
- sudo docker run -v $(XOS_FOLDER)/../../core/xoslib:/opt/xos/core/xoslib -p 9999:8000 --add-host="0.0.0.0:127.0.0.1" xos
+ sudo make -f ../common/Makefile.prereqs
+ sudo docker-compose up -d
bash ../common/wait_for_xos.sh
- echo $(RUNNING_CONTAINER)
-
-interactive:
- rm ../../xos_configuration/*
- cat ../common/Dockerfile.common Dockerfile.frontend > Dockerfile
- cp ../common/xos_common_config ../../xos_configuration/
- #cp ../cord/xos_cord_config ../../xos_configuration/
- cd ../../..; sudo docker build -t xos -f xos/configurations/frontend/Dockerfile .
- echo "Inside the container run: /usr/bin/make -C /opt/xos/configurations/frontend -f Makefile.inside"
- sudo docker run -it -v $(shell pwd)/../..:/opt/xos -p 9999:8000 --add-host="0.0.0.0:127.0.0.1" xos
+ sudo docker-compose run xos python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/frontend/sample.yaml
stop:
- sudo docker stop $(RUNNING_CONTAINER)
-
-start:
- sudo docker start $(LAST_CONTAINER)
+ sudo docker-compose stop
showlogs:
- sudo docker logs $(LAST_CONTAINER)
+ sudo docker-compose logs
-enter:
- sudo docker exec -t -i $(RUNNING_CONTAINER) bash
+rm: stop
+ sudo docker-compose rm
+
+ps:
+ sudo docker-compose ps
+
+enter-xos:
+ sudo docker exec -ti frontend_xos_1 bash
diff --git a/xos/configurations/frontend/Makefile.inside b/xos/configurations/frontend/Makefile.inside
deleted file mode 100644
index 48046b2..0000000
--- a/xos/configurations/frontend/Makefile.inside
+++ /dev/null
@@ -1,12 +0,0 @@
-all: setup_xos run_develserver
-
-setup_xos:
- chmod +x /opt/xos/scripts/opencloud;
- /opt/xos/scripts/opencloud genkeys;
-# /opt/xos/scripts/opencloud remigrate;
- bash /opt/xos/tosca/install_tosca.sh;
- bash /opt/xos/scripts/docker_setup_xos
- python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/frontend/sample.yaml
-
-run_develserver:
- cd /opt/xos; python manage.py runserver 0.0.0.0:8000 --insecure
diff --git a/xos/configurations/frontend/README.md b/xos/configurations/frontend/README.md
index db3c99f..1cf244d 100644
--- a/xos/configurations/frontend/README.md
+++ b/xos/configurations/frontend/README.md
@@ -1,11 +1,7 @@
# XOS UI Development
-This configuration launches an XOS container on Cloudlab that runs the XOS develserver. The container is left running
-in the backgorund.
-
-The observer is not started, and there is no openstack backend connected for XOS.
-
-This configuration is intended for developing the XOS GUI.
+This configuration launches the XOS GUI and database in separate containers
+using docker-compose. The Synchronizer is not started and there is no openstack backend connected for XOS. This configuration is intended for developing the XOS GUI.
## Getting Started
@@ -14,20 +10,27 @@
You'll be able to visit XOS at `0.0.0.0:9000` and the `xos/core/xoslib` folder is shared with the container. This means that any update to that folder is automatically reported in the container.
->If you need to work on the Django application there is an alternative command to setup your config. Using `make interactive` instead of `make` an interactive container will be set up and the whole `xos` folder is shared.
->
-> _NOTE: once the container has started, be sure to isse `CMD /usr/bin/make -C /opt/xos/configurations/frontend -f Makefile.inside` command. Please be carefull and do not commit migrations, private keys or other autogenerated files.
+If you need to work on the Django application itself, comment out the "sleep" command
+for the `xos` container in docker-compose.yml and run `make`. Once the containers are
+up then type `make enter` to enter the running container.
+
+> _NOTE:
+> Please be careful and do not commit migrations, private keys or other autogenerated files._
### Docker Helpers
-Stop the container: `make stop`
+Stop the containers: `make stop`
-Restart (without rebuilding): `make start`
+Restart the containers: `make stop; make`
-Open a container shell: `make enter`
+Delete the containers and relaunch them: `make rm; make`
View logs: `make showlogs`
+See what containers are running: `make ps`
+
+Open a shell on the XOS container: `make enter-xos`
+
## Docs
You can find a Swagger documentation for endpoint at: `http://0.0.0.0:9000/docs/`
@@ -48,6 +51,5 @@
This project is following [Google JavaScript Style Guide](https://google.github.io/styleguide/javascriptguide.xml). To contribute please install [Eslint](http://eslint.org/) in your editor and run `npm run eslint` before commit.
-> _NOTE_
+> _NOTE_:
> Many of the already present file were not Style compliant. Linting for them has been disabled as it was to time consuming fix all of them. If **you are going to work** on that files, please **start fixing style issues**, and then **remove the `/* eslint-disable */`** comment
-
diff --git a/xos/configurations/frontend/docker-compose.yml b/xos/configurations/frontend/docker-compose.yml
new file mode 100644
index 0000000..2779deb
--- /dev/null
+++ b/xos/configurations/frontend/docker-compose.yml
@@ -0,0 +1,23 @@
+xos_db:
+ image: xosproject/xos-postgres
+ expose:
+ - "5432"
+
+# FUTURE
+#xos_swarm_synchronizer:
+# image: xosproject/xos-swarm-synchronizer
+# labels:
+# org.xosproject.kind: synchronizer
+# org.xosproject.target: swarm
+
+xos:
+ image: xosproject/xos
+ command: python /opt/xos/manage.py runserver 0.0.0.0:8000 --insecure --makemigrations
+ #command: sleep 86400 # For interactive session
+ ports:
+ - "9999:8000"
+ links:
+ - xos_db
+ volumes:
+ - ../common/xos_common_config:/opt/xos/xos_configuration/xos_common_config:ro
+ - ../../core/xoslib:/opt/xos/core/xoslib:ro
diff --git a/xos/configurations/kilo-install/Dockerfile b/xos/configurations/kilo-install/Dockerfile
deleted file mode 100644
index f0ced90..0000000
--- a/xos/configurations/kilo-install/Dockerfile
+++ /dev/null
@@ -1,154 +0,0 @@
-# Autogenerated -- do not edit
-FROM ubuntu:14.04.2
-MAINTAINER Andy Bavier <acb@cs.princeton.edu>
-
-# XXX Workaround for docker bug:
-# https://github.com/docker/docker/issues/6345
-# Kernel 3.15 breaks docker, uss the line below as a workaround
-# until there is a fix
-RUN ln -s -f /bin/true /usr/bin/chfn
-# XXX End workaround
-
-# Install.
-RUN apt-get update && apt-get install -y \
- git \
- postgresql \
- python-psycopg2 \
- graphviz \
- graphviz-dev \
- libxslt1.1 \
- libxslt1-dev \
- python-pip \
- tar \
- gcc \
- python-httplib2 \
- geoip-database \
- libgeoip1 \
- wget \
- curl \
- python-dev \
- libyaml-dev \
- pkg-config \
- python-pycurl
-
-RUN pip install django==1.7
-RUN pip install djangorestframework==2.4.4
-RUN pip install markdown # Markdown support for the browseable API.
-RUN pip install pyyaml # YAML content-type support.
-RUN pip install django-filter # Filtering support
-RUN pip install lxml # XML manipulation library
-RUN pip install netaddr # IP Addr library
-RUN pip install pytz
-RUN pip install django-timezones
-RUN pip install requests
-RUN pip install django-crispy-forms
-RUN pip install django-geoposition
-RUN pip install django-extensions
-RUN pip install django-suit
-RUN pip install django-bitfield
-RUN pip install django-ipware
-RUN pip install django-encrypted-fields
-RUN pip install python-keyczar
-RUN pip install pygraphviz
-RUN pip install dnslib
-
-RUN DEBIAN_FRONTEND=noninteractive apt-get install -y python-keystoneclient
-RUN DEBIAN_FRONTEND=noninteractive apt-get install -y python-novaclient
-RUN DEBIAN_FRONTEND=noninteractive apt-get install -y python-neutronclient
-RUN DEBIAN_FRONTEND=noninteractive apt-get install -y python-glanceclient
-RUN DEBIAN_FRONTEND=noninteractive apt-get install -y python-ceilometerclient
-
-RUN pip install django_rest_swagger
-
-RUN DEBIAN_FRONTEND=noninteractive apt-get install -y python-setuptools
-RUN easy_install django_evolution
-RUN easy_install python_gflags
-RUN easy_install --upgrade httplib2
-RUN easy_install google_api_python_client
-RUN easy_install httplib2.ca_certs_locater
-
-# Install custom Ansible
-RUN DEBIAN_FRONTEND=noninteractive apt-get install -y python-crypto
-RUN DEBIAN_FRONTEND=noninteractive apt-get install -y python-yaml
-RUN DEBIAN_FRONTEND=noninteractive apt-get install -y openssh-client
-RUN DEBIAN_FRONTEND=noninteractive apt-get install -y python-paramiko
-RUN DEBIAN_FRONTEND=noninteractive apt-get install -y python-jinja2
-RUN DEBIAN_FRONTEND=noninteractive apt-get install -y python-httplib2
-RUN git clone -b release1.8.2 git://github.com/ansible/ansible.git /opt/ansible
-RUN git clone -b release1.8.2 git://github.com/ansible/ansible-modules-extras.git /opt/ansible/lib/ansible/modules/extras
-RUN git clone -b release1.8.2 git://github.com/ansible/ansible-modules-extras.git /opt/ansible/v2/ansible/modules/extras
-RUN git clone git://github.com/sb98052/ansible-modules-core.git /opt/ansible/lib/ansible/modules/core
-RUN git clone git://github.com/sb98052/ansible-modules-core.git /opt/ansible/v2/ansible/modules/core
-ADD ansible-hosts /etc/ansible/hosts
-
-ADD http://code.jquery.com/jquery-1.9.1.min.js /usr/local/lib/python2.7/dist-packages/suit/static/suit/js/
-
-# For Observer
-RUN git clone git://git.planet-lab.org/fofum.git /tmp/fofum
-RUN cd /tmp/fofum; python setup.py install
-RUN rm -rf /tmp/fofum
-
-RUN mkdir -p /usr/local/share /bin
-ADD http://phantomjs.googlecode.com/files/phantomjs-1.7.0-linux-x86_64.tar.bz2 /usr/local/share/
-RUN tar jxvf /usr/local/share/phantomjs-1.7.0-linux-x86_64.tar.bz2 -C /usr/local/share/
-RUN rm -f /usr/local/share/phantomjs-1.7.0-linux-x86_64.tar.bz2
-RUN ln -s /usr/local/share/phantomjs-1.7.0-linux-x86_64 /usr/local/share/phantomjs
-RUN ln -s /usr/local/share/phantomjs/bin/phantomjs /bin/phantomjs
-
-# Supervisor
-RUN DEBIAN_FRONTEND=noninteractive apt-get install -y supervisor
-ADD observer.conf /etc/supervisor/conf.d/
-
-# Get XOS
-ADD xos /opt/xos
-
-# Initscript is broken in Ubuntu
-#ADD observer-initscript /etc/init.d/xosobserver
-
-RUN chmod +x /opt/xos/scripts/opencloud
-RUN /opt/xos/scripts/opencloud genkeys
-
-# Workaround for AUFS issue
-# https://github.com/docker/docker/issues/783#issuecomment-56013588
-RUN mkdir /etc/ssl/private-copy; mv /etc/ssl/private/* /etc/ssl/private-copy/; rm -r /etc/ssl/private; mv /etc/ssl/private-copy /etc/ssl/private; chmod -R 0700 /etc/ssl/private; chown -R postgres /etc/ssl/private
-
-# Set postgres password to match default value in settings.py
-RUN service postgresql start; sudo -u postgres psql -c "alter user postgres with password 'password';"
-
-# Turn DEBUG on so that devel server will serve static files
-# (not necessary if --insecure is passed to 'manage.py runserver')
-# RUN sed -i 's/DEBUG = False/DEBUG = True/' /opt/xos/xos/settings.py
-
-# Cruft to workaround problems with migrations, should go away...
-RUN /opt/xos/scripts/opencloud remigrate
-
-# git clone uses cached copy, doesn't pick up latest
-RUN git -C /opt/ansible pull
-RUN git -C /opt/ansible/lib/ansible/modules/core pull
-RUN git -C /opt/ansible/v2/ansible/modules/core pull
-
-# install Tosca engine
-RUN apt-get install -y m4
-RUN pip install python-dateutil
-RUN bash /opt/xos/tosca/install_tosca.sh
-
-EXPOSE 8000
-
-# Set environment variables.
-ENV HOME /root
-
-# Define working directory.
-WORKDIR /root
-
-# Define default command.
-#CMD ["/bin/bash"]
-#CMD /opt/xos/scripts/docker_start_xos
-RUN mkdir -p /root/setup
-ADD xos/configurations/common/admin-openrc.sh /root/setup/
-RUN bash -c 'echo "nat-net" > /root/setup/flat_net_name'
-ADD xos/configurations/common/cloudlab-nodes.yaml /opt/xos/configurations/commmon/
-ADD xos/configurations/common/id_rsa.pub /root/setup/padmin_public_key
-
-CMD /usr/bin/make -C /opt/xos/configurations/kilo-install -f Makefile.inside; /bin/bash
-
-#CMD ["/bin/bash"]
diff --git a/xos/configurations/kilo-install/Dockerfile.kilo-install b/xos/configurations/kilo-install/Dockerfile.kilo-install
deleted file mode 100644
index fabfcd8..0000000
--- a/xos/configurations/kilo-install/Dockerfile.kilo-install
+++ /dev/null
@@ -1,8 +0,0 @@
-RUN mkdir -p /root/setup
-ADD xos/configurations/common/admin-openrc.sh /root/setup/
-ADD xos/configurations/common/cloudlab-nodes.yaml /opt/xos/configurations/commmon/
-ADD xos/configurations/common/id_rsa.pub /root/setup/padmin_public_key
-
-CMD /usr/bin/make -C /opt/xos/configurations/kilo-install -f Makefile.inside; /bin/bash
-
-#CMD ["/bin/bash"]
diff --git a/xos/configurations/kilo-install/Makefile b/xos/configurations/kilo-install/Makefile
deleted file mode 100644
index 108df7a..0000000
--- a/xos/configurations/kilo-install/Makefile
+++ /dev/null
@@ -1,38 +0,0 @@
-MYIP:=$(shell hostname -i)
-RUNNING_CONTAINER:=$(shell sudo docker ps|grep "xos"|awk '{print $$NF}')
-LAST_CONTAINER=$(shell sudo docker ps -l -q)
-
-# For installing XOS on a node that is not the OpenStack head node
-MGMT_SUBNET="192.168.122.0/24"
-HEAD_NODE_IP="130.127.133.61"
-
-test: common_cloudlab images
- echo "# Autogenerated -- do not edit" > Dockerfile
- cat ../common/Dockerfile.common Dockerfile.kilo-install >> Dockerfile
- cd ../../..; sudo docker build -t xos -f xos/configurations/kilo-install/Dockerfile .
- sudo docker run -d -p 9999:8000 -v /usr/local/share/ca-certificates:/usr/local/share/ca-certificates:ro xos
- bash ../common/wait_for_xos.sh
-
-common_cloudlab:
- make -C ../common -f Makefile.cloudlab
-
-stop:
- sudo docker stop $(RUNNING_CONTAINER)
-
-showlogs:
- sudo docker logs $(LAST_CONTAINER)
-
-enter:
- sudo docker exec -t -i $(RUNNING_CONTAINER) bash
-
-images:
- sudo bash -c "source /root/setup/admin-openrc.sh; \
- glance image-show trusty-server-multi-nic || \
- glance image-create --name trusty-server-multi-nic \
- --disk-format qcow2 \
- --file /proj/xos-PG0/acb/images/trusty-server-multi-nic.img \
- --container-format bare"
-
-remote_head_node:
- sudo iptables -t nat -A OUTPUT -p tcp -d $MGMT_SUBNET -j DNAT --to-destination $HEAD_NODE_IP
- sudo iptables -t nat -A PREROUTING -p tcp -d $MGMT_SUBNET -j DNAT --to-destination $HEAD_NODE_IP
diff --git a/xos/configurations/kilo-install/Makefile.inside b/xos/configurations/kilo-install/Makefile.inside
deleted file mode 100644
index c49841a..0000000
--- a/xos/configurations/kilo-install/Makefile.inside
+++ /dev/null
@@ -1,12 +0,0 @@
-all: setup_xos update_certificates run_develserver
-
-setup_xos:
- bash /opt/xos/scripts/docker_setup_xos
- python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/kilo-install/cloudlab.yaml
- python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/cloudlab-nodes.yaml
-
-update_certificates:
- update-ca-certificates
-
-run_develserver:
- cd /opt/xos; python manage.py runserver 0.0.0.0:8000 --insecure
diff --git a/xos/configurations/kilo-install/README b/xos/configurations/kilo-install/README
deleted file mode 100644
index 2ff7549..0000000
--- a/xos/configurations/kilo-install/README
+++ /dev/null
@@ -1,8 +0,0 @@
-This configuration is based on the "devel" configuration for CloudLab. It is
-meant to work with an OpenStack Kilo cluster installed on CloudLab using the
-procedure documented here:
-
-https://github.com/andybavier/opencloud-cluster-setup
-
-It launches an XOS container on Cloudlab that runs the XOS develserver. The
-container is left running in the background.
diff --git a/xos/configurations/kilo-install/cloudlab.yaml b/xos/configurations/kilo-install/cloudlab.yaml
deleted file mode 100644
index f92442c..0000000
--- a/xos/configurations/kilo-install/cloudlab.yaml
+++ /dev/null
@@ -1,76 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0
-
-# Note:
-# assumes the following have been created and filled with appropriate data:
-# /root/setup/admin_openrc
-# /root/setup/flat_net_name
-# /root/setup/padmin_public_key
-
-description: >
- * Adds OpenCloud Sites, Deployments, and Controllers.
-
-imports:
- - custom_types/xos.yaml
-
-topology_template:
- node_templates:
- trusty-server-multi-nic:
- type: tosca.nodes.Image
- properties:
- disk_format: QCOW2
- container_format: BARE
-
- MyDeployment:
- type: tosca.nodes.Deployment
- properties:
- flavors: m1.large, m1.medium, m1.small
- requirements:
- - image:
- node: trusty-server-multi-nic
- relationship: tosca.relationships.SupportsImage
-
- CloudLab:
- type: tosca.nodes.Controller
- requirements:
- - deployment:
- node: MyDeployment
- relationship: tosca.relationships.ControllerDeployment
- properties:
- backend_type: OpenStack
- version: Juno
- auth_url: { get_script_env: [ SELF, adminrc, OS_AUTH_URL, LOCAL_FILE] }
- admin_user: { get_script_env: [ SELF, adminrc, OS_USERNAME, LOCAL_FILE] }
- admin_password: { get_script_env: [ SELF, adminrc, OS_PASSWORD, LOCAL_FILE] }
- admin_tenant: { get_script_env: [ SELF, adminrc, OS_TENANT_NAME, LOCAL_FILE] }
- domain: Default
- artifacts:
- adminrc: /root/setup/admin-openrc.sh
-
- mysite:
- type: tosca.nodes.Site
- properties:
- display_name: MySite
- site_url: http://opencloud.us/
- requirements:
- - deployment:
- node: MyDeployment
- relationship: tosca.relationships.SiteDeployment
- requirements:
- - controller:
- node: CloudLab
- relationship: tosca.relationships.UsesController
-
- padmin@vicci.org:
- type: tosca.nodes.User
- requirements:
- - site:
- node: mysite
- relationship: tosca.relationships.MemberOfSite
- properties:
- public_key: { get_artifact: [ SELF, pubkey, LOCAL_FILE ] }
- is_admin: true
- is_active: true
- firstname: XOS
- lastname: admin
- artifacts:
- pubkey: /root/setup/padmin_public_key
diff --git a/xos/configurations/test/Dockerfile.test b/xos/configurations/test/Dockerfile.test
deleted file mode 100644
index eb39645..0000000
--- a/xos/configurations/test/Dockerfile.test
+++ /dev/null
@@ -1,9 +0,0 @@
-RUN mkdir -p /root/setup
-ADD xos/configurations/common/admin-openrc.sh /root/setup/
-ADD xos/configurations/common/flat_net_name /root/setup/
-ADD xos/configurations/common/cloudlab-nodes.yaml /opt/xos/configurations/commmon/
-ADD xos/configurations/common/id_rsa.pub /root/setup/padmin_public_key
-
-CMD ["/usr/bin/make", "-C", "/opt/xos/configurations/test", "-f", "Makefile.inside"]
-
-#CMD ["/bin/bash"]
diff --git a/xos/configurations/test/Makefile b/xos/configurations/test/Makefile
index b1cca93..a79e322 100644
--- a/xos/configurations/test/Makefile
+++ b/xos/configurations/test/Makefile
@@ -1,10 +1,38 @@
MYIP:=$(shell hostname -i)
-test: common_cloudlab
- cat ../common/Dockerfile.common Dockerfile.test > Dockerfile
- cd ../../..; sudo docker build -t xos -f xos/configurations/test/Dockerfile .
- # sudo docker run -d --add-host="ctl:$(MYIP)" -p 9999:8000 xos
- sudo docker run -i --tty --add-host="ctl:$(MYIP)" -p 9999:8000 xos
+cloudlab: common_cloudlab xos
+
+devstack: upgrade_pkgs common_devstack devstack_net_fix xos
+
+xos:
+ sudo MYIP=$(MYIP) docker-compose up -d
+ bash ../common/wait_for_xos.sh
+ sudo MYIP=$(MYIP) docker-compose run xos python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/base.yaml
+ sudo MYIP=$(MYIP) docker-compose run xos python /opt/xos/tosca/run.py padmin@vicci.org /root/setup/nodes.yaml
+ sudo MYIP=$(MYIP) docker-compose run xos bash -c "cd /opt/xos/tosca/tests; python ./alltests.py"
+ sudo MYIP=$(MYIP) docker-compose run xos bash -c "cd /opt/xos/tosca/tests; python ./allObserverTests.py"
common_cloudlab:
make -C ../common -f Makefile.cloudlab
+
+common_devstack:
+ make -C ../common -f Makefile.devstack
+
+stop:
+ sudo MYIP=$(MYIP) docker-compose stop
+
+showlogs:
+ sudo MYIP=$(MYIP) docker-compose logs
+
+rm: stop
+ sudo MYIP=$(MYIP) docker-compose rm
+
+ps:
+ sudo MYIP=$(MYIP) docker-compose ps
+
+devstack_net_fix:
+ sudo ../common/devstack/net-fix.sh
+ sudo bash -c "source ../setup/admin-openrc.sh; neutron subnet-update private-subnet --dns-nameservers list=true 8.8.8.8 8.8.4.4"
+
+upgrade_pkgs:
+ sudo pip install httpie --upgrade
diff --git a/xos/configurations/test/Makefile.inside b/xos/configurations/test/Makefile.inside
deleted file mode 100644
index d6c6de1..0000000
--- a/xos/configurations/test/Makefile.inside
+++ /dev/null
@@ -1,13 +0,0 @@
-all: setup_xos run_tests
-
-setup_xos:
- bash /opt/xos/scripts/docker_setup_xos
- python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/cloudlab.yaml
- python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/cloudlab-nodes.yaml
- echo sleeping 30 seconds
- sleep 30
-
-run_tests:
- supervisorctl stop observer
- cd /opt/xos/tosca/tests; python ./alltests.py
- cd /opt/xos/tosca/tests; python ./allObserverTests.py
diff --git a/xos/configurations/test/docker-compose.yml b/xos/configurations/test/docker-compose.yml
new file mode 100644
index 0000000..91cd4e3
--- /dev/null
+++ b/xos/configurations/test/docker-compose.yml
@@ -0,0 +1,24 @@
+xos_db:
+ image: xosproject/xos-postgres
+ expose:
+ - "5432"
+
+# FUTURE
+#xos_swarm_synchronizer:
+# image: xosproject/xos-swarm-synchronizer
+# labels:
+# org.xosproject.kind: synchronizer
+# org.xosproject.target: swarm
+
+xos:
+ image: xosproject/xos-synchronizer-openstack # Because we test the observer too
+ command: python /opt/xos/manage.py runserver 0.0.0.0:8000 --insecure --makemigrations
+ ports:
+ - "9999:8000"
+ links:
+ - xos_db
+ extra_hosts:
+ - ctl:${MYIP}
+ volumes:
+ - ../setup:/root/setup:ro
+ - ../common/xos_common_config:/opt/xos/xos_configuration/xos_common_config:ro
diff --git a/xos/configurations/vtn/Makefile b/xos/configurations/vtn/Makefile
new file mode 100644
index 0000000..59feb2d
--- /dev/null
+++ b/xos/configurations/vtn/Makefile
@@ -0,0 +1,49 @@
+SETUPDIR:=../setup
+MYIP:=$(shell hostname -i)
+
+cloudlab: common_cloudlab ansible_hosts xos
+
+devstack: upgrade_pkgs common_devstack ansible_hosts xos
+
+xos: vtn_network_cfg_json
+ sudo MYIP=$(MYIP) docker-compose up -d
+ bash ../common/wait_for_xos.sh
+ sudo MYIP=$(MYIP) docker-compose run xos python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/configurations/common/base.yaml
+ sudo MYIP=$(MYIP) docker-compose run xos python /opt/xos/tosca/run.py padmin@vicci.org /root/setup/nodes.yaml
+ sudo MYIP=$(MYIP) docker-compose run xos python /opt/xos/tosca/run.py padmin@vicci.org /opt/xos/tosca/samples/vtn.yaml
+
+common_cloudlab:
+ make -C ../common -f Makefile.cloudlab
+
+common_devstack:
+ make -C ../common -f Makefile.devstack
+
+vtn_network_cfg_json:
+ export SETUPDIR=$(SETUPDIR); bash ../cord/make-vtn-networkconfig-json.sh
+
+ansible_hosts:
+ sudo bash -c "export SETUPDIR=$(SETUPDIR); scripts/gen-inventory.sh"
+
+stop:
+ sudo MYIP=$(MYIP) docker-compose stop
+
+showlogs:
+ sudo MYIP=$(MYIP) docker-compose logs
+
+rm: stop
+ sudo MYIP=$(MYIP) docker-compose rm
+
+ps:
+ sudo MYIP=$(MYIP) docker-compose ps
+
+enter-xos:
+ sudo docker exec -it vtn_xos_1 bash
+
+enter-synchronizer:
+ sudo docker exec -it vtn_xos_synchronizer_openstack_1 bash
+
+upgrade_pkgs:
+ sudo pip install httpie --upgrade
+
+destroy-networks:
+ sudo ../../tools/destroy-all-networks.sh
diff --git a/xos/configurations/vtn/README.md b/xos/configurations/vtn/README.md
new file mode 100644
index 0000000..0fac0a5
--- /dev/null
+++ b/xos/configurations/vtn/README.md
@@ -0,0 +1,78 @@
+# XOS+VTN development environment
+
+This goal is to use this configuration to do basic end-to-end development of XOS and VTN.
+It launches
+XOS in three Docker containers (development GUI, Synchronizer, database) and configures XOS
+to talk to an OpenStack backend. *docker-compose* is used to manage the containers.
+
+See [the VTN README](../cord/README-VTN.md) for more information.
+
+## How to run it
+
+The configuration can be either run on [CloudLab](http://cloudlab.us) (controlling
+an OpenStack backend set up by a CloudLab profile) or used with a basic
+[DevStack](http://docs.openstack.org/developer/devstack/) configuration.
+
+### CloudLab
+
+To get started on CloudLab:
+* Create an experiment using the *OpenStack* profile. Choose *Kilo* and
+disable security groups.
+* Wait until you get an email from CloudLab with title "OpenStack Instance Finished Setting Up".
+* Login to the *ctl* node of your experiment and run:
+```
+ctl:~$ git clone https://github.com/open-cloud/xos.git
+ctl:~$ cd xos/xos/configurations/vtn/
+ctl:~/xos/xos/configurations/vtn$ make cloudlab
+```
+
+The configuration provides an Ansible script that automates the configuration
+steps outlined in [the VTN README](../cord/README-VTN.md). Run:
+```
+ctl:~/xos/xos/configurations/vtn$ make destroy-networks
+ctl:~/xos/xos/configurations/vtn$ sudo ansible-playbook setup.yml
+```
+
+
+### DevStack
+
+*NOTE: THIS CONFIGURATION IS NOT YET WORKING WITH DEVSTACK.*
+
+The following instructions can be used to install DevStack and XOS together
+on a single node. This setup has been run successfully in a VirtualBox VM
+with 2 CPUs and 4096 GB RAM.
+
+First, if you happen to be installing DevStack on a CloudLab node, you can
+configure about 1TB of unallocated disk space for DevStack as follows:
+```
+~$ sudo mkdir -p /opt/stack
+~$ sudo /usr/testbed/bin/mkextrafs /opt/stack
+```
+
+To install DevStack and XOS:
+
+```
+~$ git clone https://github.com/open-cloud/xos.git
+~$ git clone https://git.openstack.org/openstack-dev/devstack
+~$ cd devstack
+~/devstack$ cp ../xos/xos/configurations/common/devstack/local.conf .
+~/devstack$ ./stack.sh
+~/devstack$ cd ../xos/xos/configurations/devel/
+~/xos/xos/configurations/devel$ make devstack
+```
+
+## Docker Helpers
+
+Stop the containers: `make stop`
+
+Restart the containers: `make stop; make [cloudlab|devstack]`
+
+Delete the containers and relaunch them: `make rm; make [cloudlab|devstack]`
+
+View logs: `make showlogs`
+
+See what containers are running: `make ps`
+
+Open a shell on the XOS container: `make enter-xos`
+
+Open a shell on the Synchronizer container: `make enter-synchronizer`
diff --git a/xos/configurations/vtn/docker-compose.yml b/xos/configurations/vtn/docker-compose.yml
new file mode 100644
index 0000000..c54927b
--- /dev/null
+++ b/xos/configurations/vtn/docker-compose.yml
@@ -0,0 +1,54 @@
+xos_db:
+ image: xosproject/xos-postgres
+ expose:
+ - "5432"
+
+xos_synchronizer_openstack:
+ image: xosproject/xos-synchronizer-openstack
+ command: bash -c "python /opt/xos/synchronizers/openstack/xos-synchronizer.py"
+ labels:
+ org.xosproject.kind: synchronizer
+ org.xosproject.target: openstack
+ links:
+ - xos_db
+ extra_hosts:
+ - ctl:${MYIP}
+ volumes:
+ - ../setup:/root/setup:ro
+ - ../common/xos_common_config:/opt/xos/xos_configuration/xos_common_config:ro
+ - ./files/xos_vtn_config:/opt/xos/xos_configuration/xos_vtn_config:ro
+
+
+xos_synchronizer_onos:
+ image: xosproject/xos-synchronizer-openstack
+ command: bash -c "python /opt/xos/observers/onos/onos-observer.py -C /opt/xos/observers/onos/onos_observer_config"
+ labels:
+ org.xosproject.kind: synchronizer
+ org.xosproject.target: onos
+ links:
+ - xos_db
+ extra_hosts:
+ - ctl:${MYIP}
+ volumes:
+ - ../setup:/root/setup:ro
+ - ../setup/id_rsa:/opt/xos/observers/onos/onos_key:ro # private key
+
+# FUTURE
+#xos_swarm_synchronizer:
+# image: xosproject/xos-swarm-synchronizer
+# labels:
+# org.xosproject.kind: synchronizer
+# org.xosproject.target: swarm
+
+xos:
+ image: xosproject/xos
+ command: python /opt/xos/manage.py runserver 0.0.0.0:8000 --insecure --makemigrations
+ ports:
+ - "9999:8000"
+ links:
+ - xos_db
+ volumes:
+ - ../setup:/root/setup:ro
+ - ../common/xos_common_config:/opt/xos/xos_configuration/xos_common_config:ro
+ - ./files/xos_vtn_config:/opt/xos/xos_configuration/xos_vtn_config:ro
+ - ../setup/id_rsa.pub:/opt/xos/observers/onos/onos_key.pub:ro
diff --git a/xos/configurations/vtn/files/neutron-supervisor.conf b/xos/configurations/vtn/files/neutron-supervisor.conf
new file mode 100644
index 0000000..591df7d
--- /dev/null
+++ b/xos/configurations/vtn/files/neutron-supervisor.conf
@@ -0,0 +1,2 @@
+[program:neutron-server]
+command=/usr/bin/python /usr/bin/neutron-server --config-file=/etc/neutron/plugins/ml2/ml2_conf.ini --config-file=/etc/neutron/neutron.conf --config-file /usr/local/etc/neutron/plugins/ml2/conf_onos.ini --log-file=/var/log/neutron/neutron-server.log
diff --git a/xos/configurations/vtn/files/xos_vtn_config b/xos/configurations/vtn/files/xos_vtn_config
new file mode 100644
index 0000000..5dfd459
--- /dev/null
+++ b/xos/configurations/vtn/files/xos_vtn_config
@@ -0,0 +1,2 @@
+[networking]
+use_vtn=True
diff --git a/xos/configurations/vtn/scripts/gen-inventory.sh b/xos/configurations/vtn/scripts/gen-inventory.sh
new file mode 100755
index 0000000..f793a9a
--- /dev/null
+++ b/xos/configurations/vtn/scripts/gen-inventory.sh
@@ -0,0 +1,29 @@
+FN=/etc/ansible/hosts
+
+echo "Writing to $FN"
+
+rm -f $FN
+
+cat >> $FN <<EOF
+localhost
+
+[nodes]
+EOF
+
+NODES=$( sudo bash -c "source $SETUPDIR/admin-openrc.sh ; nova hypervisor-list" |grep enabled|awk '{print $4}' )
+
+# also configure ONOS to manage the nm node
+NM=`grep "^nm" /root/setup/fqdn.map | awk '{ print $2 }'`
+NODES="$NODES $NM"
+
+for NODE in $NODES; do
+ cat >> $FN <<EOF
+$NODE
+EOF
+done
+
+cat >> $FN <<EOF
+[nodes:vars]
+ansible_ssh_user=root
+ansible_ssh_key=/root/setup/id_rsa
+EOF
diff --git a/xos/configurations/vtn/setup.yml b/xos/configurations/vtn/setup.yml
new file mode 100644
index 0000000..ed7cd59
--- /dev/null
+++ b/xos/configurations/vtn/setup.yml
@@ -0,0 +1,51 @@
+---
+- hosts: localhost
+ connection: local
+ sudo: yes
+ vars:
+ vtn_host: cp-1.devel.xos-pg0.apt.emulab.net
+ tasks:
+ - apt: name={{ item }} state=installed
+ with_items:
+ - python-pip
+ - supervisor
+
+ - pip: name={{ item }} state=latest
+ with_items:
+ - setuptools
+ - pip
+ - testrepository
+ - git: repo=https://github.com/openstack/networking-onos.git
+ dest=/srv/networking-onos
+ - shell: cd /srv/networking-onos; python setup.py install
+
+ # Edit /etc/neutron/plugins/ml2/ml2_conf.ini
+ - ini_file: dest=/usr/local/etc/neutron/plugins/ml2/conf_onos.ini
+ section=onos option=url_path value=http://{{ vtn_host }}:8181/onos/openstackswitching
+ - ini_file: dest=/usr/local/etc/neutron/plugins/ml2/conf_onos.ini
+ section=onos option=username value=karaf
+ - ini_file: dest=/usr/local/etc/neutron/plugins/ml2/conf_onos.ini
+ section=onos option=password value=karaf
+
+ # Edit /etc/neutron/neutron.conf
+# - ini_file: dest=/etc/neutron/neutron.conf
+# section=DEFAULT option=core_plugin value=neutron.plugins.ml2.plugin.Ml2Plugin
+
+ # Edit /etc/neutron/plugins/ml2/ml2_conf.ini
+ - ini_file: dest=/etc/neutron/plugins/ml2/ml2_conf.ini
+ section=ml2 option=tenant_network_types value=vxlan
+ - ini_file: dest=/etc/neutron/plugins/ml2/ml2_conf.ini
+ section=ml2 option=type_drivers value=vxlan
+ - ini_file: dest=/etc/neutron/plugins/ml2/ml2_conf.ini
+ section=ml2 option=mechanism_drivers value=onos_ml2
+ - ini_file: dest=/etc/neutron/plugins/ml2/ml2_conf.ini
+ section=ml2_type_vxlan option=vni_ranges value=1001:2000
+
+ - service: name=neutron-server state=stopped enabled=no
+ # Run neutron-server with extra config file
+ - copy: src=files/neutron-supervisor.conf dest=/etc/supervisor/conf.d/
+ - shell: supervisorctl reload
+
+# - shell: ../../scripts/destroy-all-networks.sh
+ - shell: cd ../cord/dataplane; bash ./generate-bm.sh > hosts-bm
+ - shell: cd ../cord/dataplane; ansible-playbook -i hosts-bm dataplane-vtn.yaml
diff --git a/xos/cord/admin.py b/xos/cord/admin.py
deleted file mode 100644
index 686d8ae..0000000
--- a/xos/cord/admin.py
+++ /dev/null
@@ -1,370 +0,0 @@
-from django.contrib import admin
-
-from cord.models import *
-from django import forms
-from django.utils.safestring import mark_safe
-from django.contrib.auth.admin import UserAdmin
-from django.contrib.admin.widgets import FilteredSelectMultiple
-from django.contrib.auth.forms import ReadOnlyPasswordHashField
-from django.contrib.auth.signals import user_logged_in
-from django.utils import timezone
-from django.contrib.contenttypes import generic
-from suit.widgets import LinkedSelect
-from core.admin import ServiceAppAdmin,SliceInline,ServiceAttrAsTabInline, ReadOnlyAwareAdmin, XOSTabularInline, ServicePrivilegeInline, TenantRootTenantInline, TenantRootPrivilegeInline
-from core.middleware import get_request
-
-from functools import update_wrapper
-from django.contrib.admin.views.main import ChangeList
-from django.core.urlresolvers import reverse
-from django.contrib.admin.utils import quote
-
-#-----------------------------------------------------------------------------
-# vOLT
-#-----------------------------------------------------------------------------
-
-class VOLTServiceAdmin(ReadOnlyAwareAdmin):
- model = VOLTService
- verbose_name = "vOLT Service"
- verbose_name_plural = "vOLT Service"
- list_display = ("backend_status_icon", "name", "enabled")
- list_display_links = ('backend_status_icon', 'name', )
- fieldsets = [(None, {'fields': ['backend_status_text', 'name','enabled','versionNumber', 'description',"view_url","icon_url" ], 'classes':['suit-tab suit-tab-general']})]
- readonly_fields = ('backend_status_text', )
- inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
-
- extracontext_registered_admins = True
-
- user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
-
- suit_form_tabs =(('general', 'vOLT Service Details'),
- ('administration', 'Administration'),
- #('tools', 'Tools'),
- ('slices','Slices'),
- ('serviceattrs','Additional Attributes'),
- ('serviceprivileges','Privileges'),
- )
-
- suit_form_includes = (('voltadmin.html', 'top', 'administration'),
- ) #('hpctools.html', 'top', 'tools') )
-
- def queryset(self, request):
- return VOLTService.get_service_objects_by_user(request.user)
-
-class VOLTTenantForm(forms.ModelForm):
- s_tag = forms.CharField()
- c_tag = forms.CharField()
- creator = forms.ModelChoiceField(queryset=User.objects.all())
-
- def __init__(self,*args,**kwargs):
- super (VOLTTenantForm,self ).__init__(*args,**kwargs)
- self.fields['kind'].widget.attrs['readonly'] = True
- self.fields['provider_service'].queryset = VOLTService.get_service_objects().all()
- if self.instance:
- # fields for the attributes
- self.fields['c_tag'].initial = self.instance.c_tag
- self.fields['s_tag'].initial = self.instance.s_tag
- self.fields['creator'].initial = self.instance.creator
- if (not self.instance) or (not self.instance.pk):
- # default fields for an 'add' form
- self.fields['kind'].initial = VOLT_KIND
- self.fields['creator'].initial = get_request().user
- if VOLTService.get_service_objects().exists():
- self.fields["provider_service"].initial = VOLTService.get_service_objects().all()[0]
-
- def save(self, commit=True):
- self.instance.s_tag = self.cleaned_data.get("s_tag")
- self.instance.c_tag = self.cleaned_data.get("c_tag")
- self.instance.creator = self.cleaned_data.get("creator")
- return super(VOLTTenantForm, self).save(commit=commit)
-
- class Meta:
- model = VOLTTenant
-
-class VOLTTenantAdmin(ReadOnlyAwareAdmin):
- list_display = ('backend_status_icon', 'id', 'service_specific_id', 's_tag', 'c_tag', 'subscriber_root' )
- list_display_links = ('backend_status_icon', 'id')
- fieldsets = [ (None, {'fields': ['backend_status_text', 'kind', 'provider_service', 'subscriber_root', 'service_specific_id', # 'service_specific_attribute',
- 's_tag', 'c_tag', 'creator'],
- 'classes':['suit-tab suit-tab-general']})]
- readonly_fields = ('backend_status_text', 'service_specific_attribute')
- form = VOLTTenantForm
-
- suit_form_tabs = (('general','Details'),)
-
- def queryset(self, request):
- return VOLTTenant.get_tenant_objects_by_user(request.user)
-
-#-----------------------------------------------------------------------------
-# vCPE
-#-----------------------------------------------------------------------------
-
-class VCPEServiceForm(forms.ModelForm):
- bbs_api_hostname = forms.CharField(required=False)
- bbs_api_port = forms.IntegerField(required=False)
- bbs_server = forms.CharField(required=False)
- backend_network_label = forms.CharField(required=False)
- bbs_slice = forms.ModelChoiceField(queryset=Slice.objects.all(), required=False)
-
- def __init__(self,*args,**kwargs):
- super (VCPEServiceForm,self ).__init__(*args,**kwargs)
- if self.instance:
- self.fields['bbs_api_hostname'].initial = self.instance.bbs_api_hostname
- self.fields['bbs_api_port'].initial = self.instance.bbs_api_port
- self.fields['bbs_server'].initial = self.instance.bbs_server
- self.fields['backend_network_label'].initial = self.instance.backend_network_label
- self.fields['bbs_slice'].initial = self.instance.bbs_slice
-
- def save(self, commit=True):
- self.instance.bbs_api_hostname = self.cleaned_data.get("bbs_api_hostname")
- self.instance.bbs_api_port = self.cleaned_data.get("bbs_api_port")
- self.instance.bbs_server = self.cleaned_data.get("bbs_server")
- self.instance.backend_network_label = self.cleaned_data.get("backend_network_label")
- self.instance.bbs_slice = self.cleaned_data.get("bbs_slice")
- return super(VCPEServiceForm, self).save(commit=commit)
-
- class Meta:
- model = VCPEService
-
-class VCPEServiceAdmin(ReadOnlyAwareAdmin):
- model = VCPEService
- verbose_name = "vCPE Service"
- verbose_name_plural = "vCPE Service"
- list_display = ("backend_status_icon", "name", "enabled")
- list_display_links = ('backend_status_icon', 'name', )
- fieldsets = [(None, {'fields': ['backend_status_text', 'name','enabled','versionNumber', 'description', "view_url", "icon_url", "service_specific_attribute",],
- 'classes':['suit-tab suit-tab-general']}),
- ("backend config", {'fields': [ "backend_network_label", "bbs_api_hostname", "bbs_api_port", "bbs_server", "bbs_slice"],
- 'classes':['suit-tab suit-tab-backend']}) ]
- readonly_fields = ('backend_status_text', "service_specific_attribute")
- inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
- form = VCPEServiceForm
-
- extracontext_registered_admins = True
-
- user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
-
- suit_form_tabs =(('general', 'Service Details'),
- ('backend', 'Backend Config'),
- ('administration', 'Administration'),
- #('tools', 'Tools'),
- ('slices','Slices'),
- ('serviceattrs','Additional Attributes'),
- ('serviceprivileges','Privileges') ,
- )
-
- suit_form_includes = (('vcpeadmin.html', 'top', 'administration'),
- ) #('hpctools.html', 'top', 'tools') )
-
- def queryset(self, request):
- return VCPEService.get_service_objects_by_user(request.user)
-
-class VCPETenantForm(forms.ModelForm):
- bbs_account = forms.CharField(required=False)
- creator = forms.ModelChoiceField(queryset=User.objects.all())
- instance = forms.ModelChoiceField(queryset=Instance.objects.all(),required=False)
- last_ansible_hash = forms.CharField(required=False)
-
- def __init__(self,*args,**kwargs):
- super (VCPETenantForm,self ).__init__(*args,**kwargs)
- self.fields['kind'].widget.attrs['readonly'] = True
- self.fields['provider_service'].queryset = VCPEService.get_service_objects().all()
- if self.instance:
- # fields for the attributes
- self.fields['bbs_account'].initial = self.instance.bbs_account
- self.fields['creator'].initial = self.instance.creator
- self.fields['instance'].initial = self.instance.instance
- self.fields['last_ansible_hash'].initial = self.instance.last_ansible_hash
- if (not self.instance) or (not self.instance.pk):
- # default fields for an 'add' form
- self.fields['kind'].initial = VCPE_KIND
- self.fields['creator'].initial = get_request().user
- if VCPEService.get_service_objects().exists():
- self.fields["provider_service"].initial = VCPEService.get_service_objects().all()[0]
-
- def save(self, commit=True):
- self.instance.creator = self.cleaned_data.get("creator")
- self.instance.instance = self.cleaned_data.get("instance")
- self.instance.last_ansible_hash = self.cleaned_data.get("last_ansible_hash")
- return super(VCPETenantForm, self).save(commit=commit)
-
- class Meta:
- model = VCPETenant
-
-class VCPETenantAdmin(ReadOnlyAwareAdmin):
- list_display = ('backend_status_icon', 'id', 'subscriber_tenant' )
- list_display_links = ('backend_status_icon', 'id')
- fieldsets = [ (None, {'fields': ['backend_status_text', 'kind', 'provider_service', 'subscriber_tenant', 'service_specific_id', # 'service_specific_attribute',
- 'bbs_account', 'creator', 'instance', 'last_ansible_hash'],
- 'classes':['suit-tab suit-tab-general']})]
- readonly_fields = ('backend_status_text', 'service_specific_attribute', 'bbs_account')
- form = VCPETenantForm
-
- suit_form_tabs = (('general','Details'),)
-
- def queryset(self, request):
- return VCPETenant.get_tenant_objects_by_user(request.user)
-
-#-----------------------------------------------------------------------------
-# vBNG
-#-----------------------------------------------------------------------------
-
-class VBNGServiceForm(forms.ModelForm):
- vbng_url = forms.CharField(required=False)
-
- def __init__(self,*args,**kwargs):
- super (VBNGServiceForm,self ).__init__(*args,**kwargs)
- if self.instance:
- self.fields['vbng_url'].initial = self.instance.vbng_url
-
- def save(self, commit=True):
- self.instance.vbng_url = self.cleaned_data.get("vbng_url")
- return super(VBNGServiceForm, self).save(commit=commit)
-
- class Meta:
- model = VBNGService
-
-class VBNGServiceAdmin(ReadOnlyAwareAdmin):
- model = VBNGService
- verbose_name = "vBNG Service"
- verbose_name_plural = "vBNG Service"
- list_display = ("backend_status_icon", "name", "enabled")
- list_display_links = ('backend_status_icon', 'name', )
- fieldsets = [(None, {'fields': ['backend_status_text', 'name','enabled','versionNumber', 'description', "view_url", "icon_url",
- 'vbng_url' ],
- 'classes':['suit-tab suit-tab-general']})]
- readonly_fields = ('backend_status_text', )
- inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
- form = VBNGServiceForm
-
- extracontext_registered_admins = True
-
- user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
-
- suit_form_tabs =(('general', 'vBNG Service Details'),
- ('administration', 'Administration'),
- #('tools', 'Tools'),
- ('slices','Slices'),
- ('serviceattrs','Additional Attributes'),
- ('serviceprivileges','Privileges'),
- )
-
- suit_form_includes = (('vbngadmin.html', 'top', 'administration'),
- ) #('hpctools.html', 'top', 'tools') )
-
- def queryset(self, request):
- return VBNGService.get_service_objects_by_user(request.user)
-
-class VBNGTenantForm(forms.ModelForm):
- routeable_subnet = forms.CharField(required=False)
- mapped_hostname = forms.CharField(required=False)
- mapped_ip = forms.CharField(required=False)
- mapped_mac = forms.CharField(required=False)
-
- def __init__(self,*args,**kwargs):
- super (VBNGTenantForm,self ).__init__(*args,**kwargs)
- self.fields['kind'].widget.attrs['readonly'] = True
- self.fields['provider_service'].queryset = VBNGService.get_service_objects().all()
- if self.instance:
- # fields for the attributes
- self.fields['routeable_subnet'].initial = self.instance.routeable_subnet
- self.fields['mapped_hostname'].initial = self.instance.mapped_hostname
- self.fields['mapped_ip'].initial = self.instance.mapped_ip
- self.fields['mapped_mac'].initial = self.instance.mapped_mac
- if (not self.instance) or (not self.instance.pk):
- # default fields for an 'add' form
- self.fields['kind'].initial = VBNG_KIND
- if VBNGService.get_service_objects().exists():
- self.fields["provider_service"].initial = VBNGService.get_service_objects().all()[0]
-
- def save(self, commit=True):
- self.instance.routeable_subnet = self.cleaned_data.get("routeable_subnet")
- self.instance.mapped_hostname = self.cleaned_data.get("mapped_hostname")
- self.instance.mapped_ip = self.cleaned_data.get("mapped_ip")
- self.instance.mapped_mac = self.cleaned_data.get("mapped_mac")
- return super(VBNGTenantForm, self).save(commit=commit)
-
- class Meta:
- model = VBNGTenant
-
-class VBNGTenantAdmin(ReadOnlyAwareAdmin):
- list_display = ('backend_status_icon', 'id', 'subscriber_tenant' )
- list_display_links = ('backend_status_icon', 'id')
- fieldsets = [ (None, {'fields': ['backend_status_text', 'kind', 'provider_service', 'subscriber_tenant', 'service_specific_id', # 'service_specific_attribute',
- 'routeable_subnet', 'mapped_hostname', 'mapped_ip', 'mapped_mac'],
- 'classes':['suit-tab suit-tab-general']})]
- readonly_fields = ('backend_status_text', 'service_specific_attribute')
- form = VBNGTenantForm
-
- suit_form_tabs = (('general','Details'),)
-
- def queryset(self, request):
- return VBNGTenant.get_tenant_objects_by_user(request.user)
-
-#-----------------------------------------------------------------------------
-# CordSubscriberRoot
-#-----------------------------------------------------------------------------
-
-class VOLTTenantInline(XOSTabularInline):
- model = VOLTTenant
- fields = ['provider_service', 'subscriber_root', 'service_specific_id']
- readonly_fields = ['provider_service', 'subscriber_root', 'service_specific_id']
- extra = 0
- max_num = 0
- suit_classes = 'suit-tab suit-tab-volttenants'
- fk_name = 'subscriber_root'
- verbose_name = 'subscribed tenant'
- verbose_name_plural = 'subscribed tenants'
-
- @property
- def selflink_reverse_path(self):
- return "admin:cord_volttenant_change"
-
- def queryset(self, request):
- qs = super(VOLTTenantInline, self).queryset(request)
- return qs.filter(kind=VOLT_KIND)
-
-class CordSubscriberRootForm(forms.ModelForm):
- url_filter_level = forms.CharField(required = False)
-
- def __init__(self,*args,**kwargs):
- super (CordSubscriberRootForm,self ).__init__(*args,**kwargs)
- self.fields['kind'].widget.attrs['readonly'] = True
- if self.instance:
- self.fields['url_filter_level'].initial = self.instance.url_filter_level
- if (not self.instance) or (not self.instance.pk):
- # default fields for an 'add' form
- self.fields['kind'].initial = CORD_SUBSCRIBER_KIND
-
- def save(self, commit=True):
- self.instance.url_filter_level = self.cleaned_data.get("url_filter_level")
- return super(CordSubscriberRootForm, self).save(commit=commit)
-
- class Meta:
- model = CordSubscriberRoot
-
-class CordSubscriberRootAdmin(ReadOnlyAwareAdmin):
- list_display = ('backend_status_icon', 'id', 'name', )
- list_display_links = ('backend_status_icon', 'id', 'name', )
- fieldsets = [ (None, {'fields': ['backend_status_text', 'kind', 'name', 'service_specific_id', # 'service_specific_attribute',
- 'url_filter_level'],
- 'classes':['suit-tab suit-tab-general']})]
- readonly_fields = ('backend_status_text', 'service_specific_attribute', 'bbs_account')
- form = CordSubscriberRootForm
- inlines = (VOLTTenantInline, TenantRootPrivilegeInline)
-
- suit_form_tabs =(('general', 'Cord Subscriber Root Details'),
- ('volttenants','VOLT Tenancy'),
- ('tenantrootprivileges','Privileges')
- )
-
- def queryset(self, request):
- return CordSubscriberRoot.get_tenant_objects_by_user(request.user)
-
-admin.site.register(VOLTService, VOLTServiceAdmin)
-admin.site.register(VOLTTenant, VOLTTenantAdmin)
-admin.site.register(VCPEService, VCPEServiceAdmin)
-admin.site.register(VCPETenant, VCPETenantAdmin)
-admin.site.register(VBNGService, VBNGServiceAdmin)
-admin.site.register(VBNGTenant, VBNGTenantAdmin)
-admin.site.register(CordSubscriberRoot, CordSubscriberRootAdmin)
-
diff --git a/xos/cord/models.py b/xos/cord/models.py
deleted file mode 100644
index 1a81419..0000000
--- a/xos/cord/models.py
+++ /dev/null
@@ -1,802 +0,0 @@
-from django.db import models
-from core.models import Service, PlCoreBase, Slice, Instance, Tenant, TenantWithContainer, Node, Image, User, Flavor, Subscriber, NetworkParameter, NetworkParameterType, Port
-from core.models.plcorebase import StrippedCharField
-import os
-from django.db import models, transaction
-from django.forms.models import model_to_dict
-from django.db.models import Q
-from operator import itemgetter, attrgetter, methodcaller
-import traceback
-from xos.exceptions import *
-
-"""
-import os
-import sys
-sys.path.append("/opt/xos")
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-import django
-from core.models import *
-from hpc.models import *
-from cord.models import *
-django.setup()
-
-t = VOLTTenant()
-t.caller = User.objects.all()[0]
-t.save()
-
-for v in VOLTTenant.get_tenant_objects().all():
- v.caller = User.objects.all()[0]
- v.delete()
-
-for v in VCPETenant.get_tenant_objects().all():
- v.caller = User.objects.all()[0]
- v.delete()
-
-for v in VOLTTenant.get_tenant_objects().all():
- v.caller = User.objects.all()[0]
- v.delete()
-
-for v in VOLTTenant.get_tenant_objects().all():
- if not v.creator:
- v.creator= User.objects.all()[0]
- v.save()
-
-for v in VCPETenant.get_tenant_objects().all():
- if not v.creator:
- v.creator= User.objects.all()[0]
- v.save()
-"""
-
-class ConfigurationError(Exception):
- pass
-
-VOLT_KIND = "vOLT"
-VCPE_KIND = "vCPE"
-VBNG_KIND = "vBNG"
-CORD_SUBSCRIBER_KIND = "CordSubscriberRoot"
-
-# -------------------------------------------
-# CordSubscriberRoot
-# -------------------------------------------
-
-class CordSubscriberRoot(Subscriber):
- class Meta:
- proxy = True
-
- KIND = CORD_SUBSCRIBER_KIND
-
- default_attributes = {"firewall_enable": False,
- "firewall_rules": "accept all anywhere anywhere",
- "url_filter_enable": False,
- "url_filter_rules": "allow all",
- "url_filter_level": "PG",
- "cdn_enable": False,
- "users": [],
- "is_demo_user": False }
-
- sync_attributes = ("firewall_enable",
- "firewall_rules",
- "url_filter_enable",
- "url_filter_rules",
- "cdn_enable",)
-
- def __init__(self, *args, **kwargs):
- super(CordSubscriberRoot, self).__init__(*args, **kwargs)
- self.cached_volt = None
- self._initial_url_filter_enable = self.url_filter_enable
-
- @property
- def volt(self):
- volt = self.get_newest_subscribed_tenant(VOLTTenant)
- if not volt:
- return None
-
- # always return the same object when possible
- if (self.cached_volt) and (self.cached_volt.id == volt.id):
- return self.cached_volt
-
- #volt.caller = self.creator
- self.cached_volt = volt
- return volt
-
- @property
- def firewall_enable(self):
- return self.get_attribute("firewall_enable", self.default_attributes["firewall_enable"])
-
- @firewall_enable.setter
- def firewall_enable(self, value):
- self.set_attribute("firewall_enable", value)
-
- @property
- def firewall_rules(self):
- return self.get_attribute("firewall_rules", self.default_attributes["firewall_rules"])
-
- @firewall_rules.setter
- def firewall_rules(self, value):
- self.set_attribute("firewall_rules", value)
-
- @property
- def url_filter_enable(self):
- return self.get_attribute("url_filter_enable", self.default_attributes["url_filter_enable"])
-
- @url_filter_enable.setter
- def url_filter_enable(self, value):
- self.set_attribute("url_filter_enable", value)
-
- @property
- def url_filter_level(self):
- return self.get_attribute("url_filter_level", self.default_attributes["url_filter_level"])
-
- @url_filter_level.setter
- def url_filter_level(self, value):
- self.set_attribute("url_filter_level", value)
-
- @property
- def url_filter_rules(self):
- return self.get_attribute("url_filter_rules", self.default_attributes["url_filter_rules"])
-
- @url_filter_rules.setter
- def url_filter_rules(self, value):
- self.set_attribute("url_filter_rules", value)
-
- @property
- def cdn_enable(self):
- return self.get_attribute("cdn_enable", self.default_attributes["cdn_enable"])
-
- @cdn_enable.setter
- def cdn_enable(self, value):
- self.set_attribute("cdn_enable", value)
-
- @property
- def users(self):
- return self.get_attribute("users", self.default_attributes["users"])
-
- @users.setter
- def users(self, value):
- self.set_attribute("users", value)
-
- def find_user(self, uid):
- uid = int(uid)
- for user in self.users:
- if user["id"] == uid:
- return user
- return None
-
- def update_user(self, uid, **kwargs):
- # kwargs may be "level" or "mac"
- # Setting one of these to None will cause None to be stored in the db
- uid = int(uid)
- users = self.users
- for user in users:
- if user["id"] == uid:
- for arg in kwargs.keys():
- user[arg] = kwargs[arg]
- self.users = users
- return user
- raise ValueError("User %d not found" % uid)
-
- def create_user(self, **kwargs):
- if "name" not in kwargs:
- raise XOSMissingField("The name field is required")
-
- for user in self.users:
- if kwargs["name"] == user["name"]:
- raise XOSDuplicateKey("User %s already exists" % kwargs["name"])
-
- uids = [x["id"] for x in self.users]
- if uids:
- uid = max(uids)+1
- else:
- uid = 0
- newuser = kwargs.copy()
- newuser["id"] = uid
-
- users = self.users
- users.append(newuser)
- self.users = users
-
- return newuser
-
- def delete_user(self, uid):
- uid = int(uid)
- users = self.users
- for user in users:
- if user["id"]==uid:
- users.remove(user)
- self.users = users
- return
-
- raise ValueError("Users %d not found" % uid)
-
- @property
- def services(self):
- return {"cdn": self.cdn_enable,
- "url_filter": self.url_filter_enable,
- "firewall": self.firewall_enable}
-
- @services.setter
- def services(self, value):
- pass
-
- def save(self, *args, **kwargs):
- if (not hasattr(self, 'caller') or not self.caller.is_admin):
- if (self.has_field_changed("service_specific_id")):
- raise XOSPermissionDenied("You do not have permission to change service_specific_id")
- super(CordSubscriberRoot, self).save(*args, **kwargs)
- if (self.volt) and (self.volt.vcpe): # and (self._initial_url_filter_enabled != self.url_filter_enable):
- # 1) trigger manage_bbs_account to run
- # 2) trigger vcpe observer to wake up
- self.volt.vcpe.save()
-
- @property
- def is_demo_user(self):
- return self.get_attribute("is_demo_user", self.default_attributes["is_demo_user"])
-
- @is_demo_user.setter
- def is_demo_user(self, value):
- self.set_attribute("is_demo_user", value)
-
-# -------------------------------------------
-# VOLT
-# -------------------------------------------
-
-class VOLTService(Service):
- KIND = VOLT_KIND
-
- class Meta:
- app_label = "cord"
- verbose_name = "vOLT Service"
- proxy = True
-
-class VOLTTenant(Tenant):
- class Meta:
- proxy = True
-
- KIND = VOLT_KIND
-
- default_attributes = {"vlan_id": None, "s_tag": None, "c_tag": None}
- def __init__(self, *args, **kwargs):
- volt_services = VOLTService.get_service_objects().all()
- if volt_services:
- self._meta.get_field("provider_service").default = volt_services[0].id
- super(VOLTTenant, self).__init__(*args, **kwargs)
- self.cached_vcpe = None
-
- @property
- def s_tag(self):
- return self.get_attribute("s_tag", self.default_attributes["s_tag"])
-
- @s_tag.setter
- def s_tag(self, value):
- self.set_attribute("s_tag", value)
-
- @property
- def c_tag(self):
- return self.get_attribute("c_tag", self.default_attributes["c_tag"])
-
- @c_tag.setter
- def c_tag(self, value):
- self.set_attribute("c_tag", value)
-
- # for now, vlan_id is a synonym for c_tag
-
- @property
- def vlan_id(self):
- return self.c_tag
-
- @vlan_id.setter
- def vlan_id(self, value):
- self.c_tag = value
-
- @property
- def vcpe(self):
- vcpe = self.get_newest_subscribed_tenant(VCPETenant)
- if not vcpe:
- return None
-
- # always return the same object when possible
- if (self.cached_vcpe) and (self.cached_vcpe.id == vcpe.id):
- return self.cached_vcpe
-
- vcpe.caller = self.creator
- self.cached_vcpe = vcpe
- return vcpe
-
- @vcpe.setter
- def vcpe(self, value):
- raise XOSConfigurationError("vOLT.vCPE cannot be set this way -- create a new vCPE object and set its subscriber_tenant instead")
-
- @property
- def subscriber(self):
- if not self.subscriber_root:
- return None
- subs = CordSubscriberRoot.objects.filter(id=self.subscriber_root.id)
- if not subs:
- return None
- return subs[0]
-
- @property
- def creator(self):
- if getattr(self, "cached_creator", None):
- return self.cached_creator
- creator_id=self.get_attribute("creator_id")
- if not creator_id:
- return None
- users=User.objects.filter(id=creator_id)
- if not users:
- return None
- user=users[0]
- self.cached_creator = users[0]
- return user
-
- @creator.setter
- def creator(self, value):
- if value:
- value = value.id
- if (value != self.get_attribute("creator_id", None)):
- self.cached_creator=None
- self.set_attribute("creator_id", value)
-
- def manage_vcpe(self):
- # Each VOLT object owns exactly one VCPE object
-
- if self.deleted:
- return
-
- if self.vcpe is None:
- vcpeServices = VCPEService.get_service_objects().all()
- if not vcpeServices:
- raise XOSConfigurationError("No VCPE Services available")
-
- vcpe = VCPETenant(provider_service = vcpeServices[0],
- subscriber_tenant = self)
- vcpe.caller = self.creator
- vcpe.save()
-
- def manage_subscriber(self):
- if (self.subscriber_root is None):
- # The vOLT is not connected to a Subscriber, so either find an
- # existing subscriber with the same SSID, or autogenerate a new
- # subscriber.
- #
- # TODO: This probably goes away when we rethink the ONOS-to-XOS
- # vOLT API.
-
- subs = CordSubscriberRoot.get_tenant_objects().filter(service_specific_id = self.service_specific_id)
- if subs:
- sub = subs[0]
- else:
- sub = CordSubscriberRoot(service_specific_id = self.service_specific_id,
- name = "autogenerated-for-vOLT-%s" % self.id)
- sub.save()
- self.subscriber_root = sub
- self.save()
-
- def cleanup_vcpe(self):
- if self.vcpe:
- # print "XXX cleanup vcpe", self.vcpe
- self.vcpe.delete()
-
- def cleanup_orphans(self):
- # ensure vOLT only has one vCPE
- cur_vcpe = self.vcpe
- for vcpe in list(self.get_subscribed_tenants(VCPETenant)):
- if (not cur_vcpe) or (vcpe.id != cur_vcpe.id):
- # print "XXX clean up orphaned vcpe", vcpe
- vcpe.delete()
-
- def save(self, *args, **kwargs):
- self.validate_unique_service_specific_id()
-
- if (self.subscriber_root is not None):
- subs = self.subscriber_root.get_subscribed_tenants(VOLTTenant)
- if (subs) and (self not in subs):
- raise XOSDuplicateKey("Subscriber should only be linked to one vOLT")
-
- if not self.creator:
- if not getattr(self, "caller", None):
- # caller must be set when creating a vCPE since it creates a slice
- raise XOSProgrammingError("VOLTTenant's self.caller was not set")
- self.creator = self.caller
- if not self.creator:
- raise XOSProgrammingError("VOLTTenant's self.creator was not set")
-
- super(VOLTTenant, self).save(*args, **kwargs)
- model_policy_volt(self.pk)
- #self.manage_vcpe()
- #self.manage_subscriber()
- #self.cleanup_orphans()
-
- def delete(self, *args, **kwargs):
- self.cleanup_vcpe()
- super(VOLTTenant, self).delete(*args, **kwargs)
-
-def model_policy_volt(pk):
- # TODO: this should be made in to a real model_policy
- with transaction.atomic():
- volt = VOLTTenant.objects.select_for_update().filter(pk=pk)
- if not volt:
- return
- volt = volt[0]
- volt.manage_vcpe()
- volt.manage_subscriber()
- volt.cleanup_orphans()
-
-# -------------------------------------------
-# VCPE
-# -------------------------------------------
-
-class VCPEService(Service):
- KIND = VCPE_KIND
-
- simple_attributes = ( ("bbs_api_hostname", None),
- ("bbs_api_port", None),
- ("bbs_server", None),
- ("backend_network_label", "hpc_client"), )
-
- def __init__(self, *args, **kwargs):
- super(VCPEService, self).__init__(*args, **kwargs)
-
- class Meta:
- app_label = "cord"
- verbose_name = "vCPE Service"
- proxy = True
-
- def allocate_bbs_account(self):
- vcpes = VCPETenant.get_tenant_objects().all()
- bbs_accounts = [vcpe.bbs_account for vcpe in vcpes]
-
- # There's a bit of a race here; some other user could be trying to
- # allocate a bbs_account at the same time we are.
-
- for i in range(2,21):
- account_name = "bbs%02d@onlab.us" % i
- if (account_name not in bbs_accounts):
- return account_name
-
- raise XOSConfigurationError("We've run out of available broadbandshield accounts. Delete some vcpe and try again.")
-
- @property
- def bbs_slice(self):
- bbs_slice_id=self.get_attribute("bbs_slice_id")
- if not bbs_slice_id:
- return None
- bbs_slices=Slice.objects.filter(id=bbs_slice_id)
- if not bbs_slices:
- return None
- return bbs_slices[0]
-
- @bbs_slice.setter
- def bbs_slice(self, value):
- if value:
- value = value.id
- self.set_attribute("bbs_slice_id", value)
-
-VCPEService.setup_simple_attributes()
-
-
-class VCPETenant(TenantWithContainer):
- class Meta:
- proxy = True
-
- KIND = VCPE_KIND
-
- sync_attributes = ("nat_ip", "nat_mac",
- "lan_ip", "lan_mac",
- "wan_ip", "wan_mac", "wan_container_mac",
- "private_ip", "private_mac",
- "hpc_client_ip", "hpc_client_mac")
-
- default_attributes = {"instance_id": None,
- "container_id": None,
- "users": [],
- "bbs_account": None,
- "last_ansible_hash": None}
-
- def __init__(self, *args, **kwargs):
- super(VCPETenant, self).__init__(*args, **kwargs)
- self.cached_vbng=None
-
- @property
- def vbng(self):
- vbng = self.get_newest_subscribed_tenant(VBNGTenant)
- if not vbng:
- return None
-
- # always return the same object when possible
- if (self.cached_vbng) and (self.cached_vbng.id == vbng.id):
- return self.cached_vbng
-
- vbng.caller = self.creator
- self.cached_vbng = vbng
- return vbng
-
- @vbng.setter
- def vbng(self, value):
- raise XOSConfigurationError("vCPE.vBNG cannot be set this way -- create a new vBNG object and set it's subscriber_tenant instead")
-
- @property
- def volt(self):
- if not self.subscriber_tenant:
- return None
- volts = VOLTTenant.objects.filter(id=self.subscriber_tenant.id)
- if not volts:
- return None
- return volts[0]
-
- @property
- def bbs_account(self):
- return self.get_attribute("bbs_account", self.default_attributes["bbs_account"])
-
- @bbs_account.setter
- def bbs_account(self, value):
- return self.set_attribute("bbs_account", value)
-
- @property
- def last_ansible_hash(self):
- return self.get_attribute("last_ansible_hash", self.default_attributes["last_ansible_hash"])
-
- @last_ansible_hash.setter
- def last_ansible_hash(self, value):
- return self.set_attribute("last_ansible_hash", value)
-
- @property
- def ssh_command(self):
- if self.instance:
- return self.instance.get_ssh_command()
- else:
- return "no-instance"
-
- @ssh_command.setter
- def ssh_command(self, value):
- pass
-
- @property
- def addresses(self):
- if self.instance:
- ports = self.instance.ports.all()
- elif self.container:
- ports = self.container.ports.all()
- else:
- return {}
-
- addresses = {}
- for ns in ports:
- if "lan" in ns.network.name.lower():
- addresses["lan"] = (ns.ip, ns.mac)
- elif "wan" in ns.network.name.lower():
- addresses["wan"] = (ns.ip, ns.mac)
- elif "private" in ns.network.name.lower():
- addresses["private"] = (ns.ip, ns.mac)
- elif "nat" in ns.network.name.lower():
- addresses["nat"] = (ns.ip, ns.mac)
- elif "hpc_client" in ns.network.name.lower():
- addresses["hpc_client"] = (ns.ip, ns.mac)
- return addresses
-
- @property
- def nat_ip(self):
- return self.addresses.get("nat", (None,None) )[0]
-
- @property
- def nat_mac(self):
- return self.addresses.get("nat", (None,None) )[1]
-
- @property
- def lan_ip(self):
- return self.addresses.get("lan", (None, None) )[0]
-
- @property
- def lan_mac(self):
- return self.addresses.get("lan", (None, None) )[1]
-
- @property
- def wan_ip(self):
- return self.addresses.get("wan", (None, None) )[0]
-
- @property
- def wan_mac(self):
- return self.addresses.get("wan", (None, None) )[1]
-
- # Generate the MAC for the container interface connected to WAN
- @property
- def wan_container_mac(self):
- (a, b, c, d) = self.wan_ip.split('.')
- return "02:42:%02x:%02x:%02x:%02x" % (int(a), int(b), int(c), int(d))
-
- @property
- def private_ip(self):
- return self.addresses.get("private", (None, None) )[0]
-
- @property
- def private_mac(self):
- return self.addresses.get("private", (None, None) )[1]
-
- @property
- def hpc_client_ip(self):
- return self.addresses.get("hpc_client", (None, None) )[0]
-
- @property
- def hpc_client_mac(self):
- return self.addresses.get("hpc_client", (None, None) )[1]
-
- @property
- def is_synced(self):
- return (self.enacted is not None) and (self.enacted >= self.updated)
-
- @is_synced.setter
- def is_synced(self, value):
- pass
-
- def manage_vbng(self):
- # Each vCPE object owns exactly one vBNG object
-
- if self.deleted:
- return
-
- if self.vbng is None:
- vbngServices = VBNGService.get_service_objects().all()
- if not vbngServices:
- raise XOSConfigurationError("No VBNG Services available")
-
- vbng = VBNGTenant(provider_service = vbngServices[0],
- subscriber_tenant = self)
- vbng.caller = self.creator
- vbng.save()
-
- def cleanup_vbng(self):
- if self.vbng:
- # print "XXX cleanup vnbg", self.vbng
- self.vbng.delete()
-
- def cleanup_orphans(self):
- # ensure vCPE only has one vBNG
- cur_vbng = self.vbng
- for vbng in list(self.get_subscribed_tenants(VBNGTenant)):
- if (not cur_vbng) or (vbng.id != cur_vbng.id):
- # print "XXX clean up orphaned vbng", vbng
- vbng.delete()
-
- if self.orig_instance_id and (self.orig_instance_id != self.get_attribute("instance_id")):
- instances=Instance.objects.filter(id=self.orig_instance_id)
- if instances:
- # print "XXX clean up orphaned instance", instances[0]
- instances[0].delete()
-
- def manage_bbs_account(self):
- if self.deleted:
- return
-
- if self.volt and self.volt.subscriber and self.volt.subscriber.url_filter_enable:
- if not self.bbs_account:
- # make sure we use the proxied VCPEService object, not the generic Service object
- vcpe_service = VCPEService.objects.get(id=self.provider_service.id)
- self.bbs_account = vcpe_service.allocate_bbs_account()
- super(VCPETenant, self).save()
- else:
- if self.bbs_account:
- self.bbs_account = None
- super(VCPETenant, self).save()
-
- def find_or_make_port(self, instance, network, **kwargs):
- port = Port.objects.filter(instance=instance, network=network)
- if port:
- port = port[0]
- else:
- port = Port(instance=instance, network=network, **kwargs)
- port.save()
- return port
-
- def save_instance(self, instance):
- with transaction.atomic():
- instance.volumes = "/etc/dnsmasq.d,/etc/ufw"
- super(VCPETenant, self).save_instance(instance)
-
- if instance.isolation in ["container", "container_vm"]:
- lan_networks = [x for x in instance.slice.networks.all() if "lan" in x.name]
- if not lan_networks:
- raise XOSProgrammingError("No lan_network")
- port = self.find_or_make_port(instance, lan_networks[0], ip="192.168.0.1", port_id="unmanaged")
- port.set_parameter("c_tag", self.volt.c_tag)
- port.set_parameter("s_tag", self.volt.s_tag)
- port.set_parameter("device", "eth1")
- port.set_parameter("bridge", "br-lan")
-
- wan_networks = [x for x in instance.slice.networks.all() if "wan" in x.name]
- if not wan_networks:
- raise XOSProgrammingError("No wan_network")
- port = self.find_or_make_port(instance, wan_networks[0])
- port.set_parameter("next_hop", value="10.0.1.253") # FIX ME
- port.set_parameter("device", "eth0")
-
- def save(self, *args, **kwargs):
- if not self.creator:
- if not getattr(self, "caller", None):
- # caller must be set when creating a vCPE since it creates a slice
- raise XOSProgrammingError("VCPETenant's self.caller was not set")
- self.creator = self.caller
- if not self.creator:
- raise XOSProgrammingError("VCPETenant's self.creator was not set")
-
- super(VCPETenant, self).save(*args, **kwargs)
- model_policy_vcpe(self.pk)
- #self.manage_instance()
- #self.manage_vbng()
- #self.manage_bbs_account()
- #self.cleanup_orphans()
-
- def delete(self, *args, **kwargs):
- self.cleanup_vbng()
- self.cleanup_container()
- super(VCPETenant, self).delete(*args, **kwargs)
-
-def model_policy_vcpe(pk):
- # TODO: this should be made in to a real model_policy
- with transaction.atomic():
- vcpe = VCPETenant.objects.select_for_update().filter(pk=pk)
- if not vcpe:
- return
- vcpe = vcpe[0]
- vcpe.manage_container()
- vcpe.manage_vbng()
- vcpe.manage_bbs_account()
- vcpe.cleanup_orphans()
-
-#----------------------------------------------------------------------------
-# vBNG
-#----------------------------------------------------------------------------
-
-class VBNGService(Service):
- KIND = VBNG_KIND
-
- simple_attributes = ( ("vbng_url", ""), ) # "http://10.0.3.136:8181/onos/virtualbng/"
-
- class Meta:
- app_label = "cord"
- verbose_name = "vBNG Service"
- proxy = True
-
-VBNGService.setup_simple_attributes()
-
-class VBNGTenant(Tenant):
- class Meta:
- proxy = True
-
- KIND = VBNG_KIND
-
- default_attributes = {"routeable_subnet": "",
- "mapped_ip": "",
- "mapped_mac": "",
- "mapped_hostname": ""}
-
- @property
- def routeable_subnet(self):
- return self.get_attribute("routeable_subnet", self.default_attributes["routeable_subnet"])
-
- @routeable_subnet.setter
- def routeable_subnet(self, value):
- self.set_attribute("routeable_subnet", value)
-
- @property
- def mapped_ip(self):
- return self.get_attribute("mapped_ip", self.default_attributes["mapped_ip"])
-
- @mapped_ip.setter
- def mapped_ip(self, value):
- self.set_attribute("mapped_ip", value)
-
- @property
- def mapped_mac(self):
- return self.get_attribute("mapped_mac", self.default_attributes["mapped_mac"])
-
- @mapped_mac.setter
- def mapped_mac(self, value):
- self.set_attribute("mapped_mac", value)
-
- @property
- def mapped_hostname(self):
- return self.get_attribute("mapped_hostname", self.default_attributes["mapped_hostname"])
-
- @mapped_hostname.setter
- def mapped_hostname(self, value):
- self.set_attribute("mapped_hostname", value)
diff --git a/xos/cord/templates/vbngadmin.html b/xos/cord/templates/vbngadmin.html
deleted file mode 100644
index 721f76c..0000000
--- a/xos/cord/templates/vbngadmin.html
+++ /dev/null
@@ -1,6 +0,0 @@
-<div class = "left-nav">
-<ul>
-<li><a href="/admin/cord/vbngtenant/">vBNG Tenants</a></li>
-</ul>
-</div>
-
diff --git a/xos/cord/templates/vcpeadmin.html b/xos/cord/templates/vcpeadmin.html
deleted file mode 100644
index 7a5d43f..0000000
--- a/xos/cord/templates/vcpeadmin.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<div class = "left-nav">
-<ul>
-<li><a href="/admin/cord/vcpetenant/">vCPE Tenants</a></li>
-<li><a href="/admin/dashboard/cord/">Subscriber View</a></li>
-</ul>
-</div>
-
diff --git a/xos/cord/templates/voltadmin.html b/xos/cord/templates/voltadmin.html
deleted file mode 100644
index 5bf28ff..0000000
--- a/xos/cord/templates/voltadmin.html
+++ /dev/null
@@ -1,6 +0,0 @@
-<div class = "left-nav">
-<ul>
-<li><a href="/admin/cord/volttenant/">vOLT Tenants</a></li>
-</ul>
-</div>
-
diff --git a/xos/core/__init__.py b/xos/core/__init__.py
index e69de29..e01f9cd 100644
--- a/xos/core/__init__.py
+++ b/xos/core/__init__.py
@@ -0,0 +1 @@
+# from tests import *
diff --git a/xos/core/admin.py b/xos/core/admin.py
index 97e76ff..bc083c4 100644
--- a/xos/core/admin.py
+++ b/xos/core/admin.py
@@ -34,10 +34,41 @@
def backend_icon(obj):
(icon, tooltip) = obj.get_backend_icon()
+
icon_url = ICON_URLS.get(icon, "unknown")
+ (exponent,last_success,last_failure,failures) = obj.get_backend_details()
+
+ # FIXME: Need to clean this up by separating Javascript from Python
+ if (obj.pk):
+ script = """
+ <script type="text/javascript">
+ $(document).ready(function () {
+ $("#show_details_%d").click(function () {
+ $("#status%d").dialog({modal: true, height: 200, width: 200 });
+ });
+ });
+ </script>
+ """%(obj.pk,obj.pk)
+
+ div = """
+ <div style="display:none;" id="status%d" title="Details">
+ <p>Backoff Exponent: %r</p>
+ <p>Last Success: %r</p>
+ <p>Failures: %r</p>
+ <p>Last Failure: %r</p>
+ </div>
+ """%(obj.pk,exponent,last_success,failures,last_failure)
+ a = '<a id="show_details_%d" href="#">'%obj.pk
+ astop = '</a>'
+ else:
+ div = ''
+ script = ''
+ a = ''
+ astop = ''
+
if tooltip:
- return '<span style="min-width:16px;" title="%s"><img src="%s"></span>' % (tooltip, icon_url)
+ return '%s %s <span style="min-width:16px;" title="%s">%s<img src="%s">%s</span>' % (script, div, tooltip, a, icon_url, astop)
else:
return '<span style="min-width:16px;"><img src="%s"></span>' % icon_url
@@ -163,15 +194,15 @@
# for Service admins to render their Administration page
if getattr(self, "extracontext_registered_admins", False):
admins=[]
- for model, model_admin in admin.site._registry.items():
- if model == self.model:
- continue
- if model._meta.app_label == self.model._meta.app_label:
- info = {"app": model._meta.app_label,
- "model": model._meta.model_name,
- "name": capfirst(model._meta.verbose_name_plural),
- "url": self.url_for_model_changelist(request,model) }
- admins.append(info)
+ for model, model_admin in admin.site._registry.items():
+ if model == self.model:
+ continue
+ if model._meta.app_label == self.model._meta.app_label:
+ info = {"app": model._meta.app_label,
+ "model": model._meta.model_name,
+ "name": capfirst(model._meta.verbose_name_plural),
+ "url": self.url_for_model_changelist(request,model) }
+ admins.append(info)
extra_context["registered_admins"] = admins
def change_view(self,request,object_id, extra_context=None):
diff --git a/xos/core/api/auth.py b/xos/core/api/auth.py
deleted file mode 100644
index 8796f14..0000000
--- a/xos/core/api/auth.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from openstack.client import OpenStackClient
-
-def auth_check(username, password, tenant):
- client = OpenStackClient(username=username,
- password=password,
- tenant=tenant)
- client.authenticate()
- return client
diff --git a/xos/core/api/deployment_networks.py b/xos/core/api/deployment_networks.py
deleted file mode 100644
index ee1f68e..0000000
--- a/xos/core/api/deployment_networks.py
+++ /dev/null
@@ -1,40 +0,0 @@
-from types import StringTypes
-from core.models import Deployment
-from django.contrib.auth import authenticate
-
-def _get_deployment_networks(filter):
- if isinstance(filter, StringTypes) and filter.isdigit():
- filter = int(filter)
- if isinstance(filter, int):
- deployment_networks = Deployment.objects.filter(id=filter)
- elif isinstance(filter, StringTypes):
- deployment_networks = Deployment.objects.filter(name=filter)
- elif isinstance(filter, dict):
- deployment_networks = Deployment.objects.filter(**filter)
- else:
- deployment_networks = []
- return deployment_networks
-
-def add_deployment_network(auth, name):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- deployment = Deployment(name=name)
- deployment.save()
- return deployment
-
-def delete_deployment_network(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- deployments = _get_deployment_networks(filter)
- for deployment in deployments:
- deployment.delete()
- return 1
-
-def get_deployment_networks(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- deployments = _get_deployment_networks(filter)
- return deployments
-
-
-
diff --git a/xos/core/api/images.py b/xos/core/api/images.py
deleted file mode 100644
index 933216f..0000000
--- a/xos/core/api/images.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from types import StringTypes
-from django.contrib.auth import authenticate
-from core.models import Image
-
-def _get_images(filter):
- if isinstance(filter, StringTypes) and filter.isdigit():
- filter = int(filter)
- if isinstance(filter, int):
- images = Image.objects.filter(id=filter)
- elif isinstance(filter, StringTypes):
- images = Image.objects.filter(name=filter)
- elif isinstance(filter, dict):
- images = Image.objects.filter(**filter)
- else:
- images = []
- return images
-
-def add_image(auth, fields={}):
- """not implemented"""
- return
-
-def delete_image(auth, filter={}):
- """not implemented"""
- return 1
-
-def get_images(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- images = _get_images(filter)
- return images
-
-
-
diff --git a/xos/core/api/instances.py b/xos/core/api/instances.py
deleted file mode 100644
index 92e928c..0000000
--- a/xos/core/api/instances.py
+++ /dev/null
@@ -1,65 +0,0 @@
-from types import StringTypes
-from django.contrib.auth import authenticate
-from openstack.manager import OpenStackManager
-from core.models import Instance, Slice
-from core.api.images import _get_images
-from core.api.slices import _get_slices
-from core.api.deployment_networks import _get_deployment_networks
-from core.api.nodes import _get_nodes
-
-def _get_instances(filter):
- if isinstance(filter, StringTypes) and filter.isdigit():
- filter = int(filter)
- if isinstance(filter, int):
- instances = Instance.objects.filter(id=filter)
- elif isinstance(filter, StringTypes):
- instances = Instance.objects.filter(name=filter)
- elif isinstance(filter, dict):
- instances = Instance.objects.filter(**filter)
- else:
- instances = []
- return instances
-
-def add_instance(auth, fields):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
-
- images = _get_images(fields.get('image'))
- slices = _get_slices(fields.get('slice'))
- deployment_networks = _get_deployment_networks(fields.get('deploymentNetwork'))
- nodes = _get_nodes(fields.get('node'))
- if images: fields['image'] = images[0]
- if slices: fields['slice'] = slices[0]
- if deployment_networks: fields['deploymentNetwork'] = deployment_networks[0]
- if nodes: fields['node'] = nodes[0]
-
- instance = Instance(**fields)
- auth['tenant'] = instance.slice.name
- instance.os_manager = OpenStackManager(auth=auth, caller = user)
- instance.save()
- return instance
-
-def update_instance(auth, instance, **fields):
- return
-
-def delete_instance(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- instances = _get_instances(filter)
- for instance in instances:
- auth['tenant'] = instance.slice.name
- slice.os_manager = OpenStackManager(auth=auth, caller = user)
- instance.delete()
- return 1
-
-def get_instances(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- if 'slice' in filter:
- slices = _get_slices(filter.get('slice'))
- if slices: filter['slice'] = slices[0]
- instances = _get_instances(filter)
- return instances
-
-
-
diff --git a/xos/core/api/nodes.py b/xos/core/api/nodes.py
deleted file mode 100644
index 4f7ceeb..0000000
--- a/xos/core/api/nodes.py
+++ /dev/null
@@ -1,36 +0,0 @@
-from types import StringTypes
-from django.contrib.auth import authenticate
-from core.models import Node
-
-def _get_nodes(filter):
- if isinstance(filter, StringTypes) and filter.isdigit():
- filter = int(filter)
- if isinstance(filter, int):
- nodes = Node.objects.filter(id=filter)
- elif isinstance(filter, StringTypes):
- nodes = Node.objects.filter(name=filter)
- elif isinstance(filter, dict):
- nodes = Node.objects.filter(**filter)
- else:
- nodes = []
- return nodes
-
-def add_node(auth, fields={}):
- """not implemented"""
- return
-
-def delete_node(auth, filter={}):
- """not implemented"""
- return 1
-
-def update_node(auth, id, fields={}):
- return
-
-def get_nodes(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- nodes = _get_nodes(filter)
- return nodes
-
-
-
diff --git a/xos/core/api/roles.py b/xos/core/api/roles.py
deleted file mode 100644
index 4ea05c9..0000000
--- a/xos/core/api/roles.py
+++ /dev/null
@@ -1,44 +0,0 @@
-from types import StringTypes
-from django.contrib.auth import authenticate
-from openstack.manager import OpenStackManager
-from core.models import Role
-
-
-def _get_roles(filter):
- if isinstance(filter, StringTypes) and filter.isdigit():
- filter = int(filter)
- if isinstance(filter, int):
- roles = Role.objects.filter(id=filter)
- elif isinstance(filter, StringTypes):
- roles = Role.objects.filter(role_type=filter)
- elif isinstance(filter, dict):
- roles = Role.objects.filter(**filter)
- else:
- roles = []
- return roles
-
-def add_role(auth, name):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- auth['tenant'] = user.site.login_base
-
- role = Role(role_type=name)
- role.os_manager = OpenStackManager(auth=auth, caller = user)
- role.save()
- return role
-
-def delete_role(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- roles = _get_roles(filter)
- for role in roles:
- auth['tenant'] = user.site.login_base
- role.os_manager = OpenStackManager(auth=auth, caller = user)
- role.delete()
- return 1
-
-def get_roles(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- return _get_roles(filter)
-
diff --git a/xos/core/api/site_privileges.py b/xos/core/api/site_privileges.py
deleted file mode 100644
index 6d79701..0000000
--- a/xos/core/api/site_privileges.py
+++ /dev/null
@@ -1,73 +0,0 @@
-from types import StringTypes
-import re
-from django.contrib.auth import authenticate
-from openstack.manager import OpenStackManager
-from core.models import SitePrivilege
-from core.api.users import _get_users
-from core.api.sites import _get_sites
-from core.api.roles import _get_roles
-
-
-def _get_site_privileges(filter):
- if isinstance(filter, StringTypes) and filter.isdigit():
- filter = int(filter)
- if isinstance(filter, int):
- site_privileges = SitePrivilege.objects.filter(id=filter)
- elif isinstance(filter, StringTypes):
- site_privileges = SitePrivilege.objects.filter(name=filter)
- elif isinstance(filter, dict):
- site_privileges = SitePrivilege.objects.filter(**filter)
- else:
- site_privileges = []
- return site_privileges
-
-def add_site_privilege(auth, fields):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
-
- users = _get_user(fields.get('user'))
- sites = _get_slice(fields.get('site'))
- roles = _get_role(fields.get('role'))
-
- if users: fields['user'] = users[0]
- if slices: fields['site'] = sites[0]
- if roles: fields['role'] = roles[0]
-
- auth['tenant'] = sites[0].login_base
- site_privilege = SitePrivilege(**fields)
- site_privilege.os_manager = OpenStackManager(auth=auth, caller = user)
- site_privilege.save()
- return site_privilege
-
-def update_site_privilege(auth, id, **fields):
- return
-
-def delete_site_privilege(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- auth['tenant'] = user.site.login_base
- manager = OpenStackManager(auth=auth, caller = user)
-
- site_privileges = _get_site_privileges(filter)
- for site_privilege in site_privileges:
- auth['tenant'] = user.site.login_base
- site_privilege.os_manager = OpenStackManager(auth=auth, caller = user)
- site_privilege.delete()
- return 1
-
-def get_site_privileges(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- users = _get_users(filter.get('user'))
- sites = _get_slices(filter.get('site'))
- roles = _get_roles(filter.get('role'))
-
- if users: filter['user'] = users[0]
- if sites: filter['site'] = sites[0]
- if roles: filter['role'] = roles[0]
-
- site_privileges = _get_site_privileges(filter)
- return site_privileges
-
-
-
diff --git a/xos/core/api/sites.py b/xos/core/api/sites.py
deleted file mode 100644
index 123f139..0000000
--- a/xos/core/api/sites.py
+++ /dev/null
@@ -1,60 +0,0 @@
-from types import StringTypes
-from django.contrib.auth import authenticate
-from openstack.manager import OpenStackManager
-from core.models import Site
-
-def _get_sites(filter):
- if isinstance(filter, StringTypes) and filter.isdigit():
- filter = int(filter)
- if isinstance(filter, int):
- sites = Site.objects.filter(id=filter)
- elif isinstance(filter, StringTypes):
- sites = Site.objects.filter(login_base=filter)
- elif isinstance(filter, dict):
- sites = Site.objects.filter(**filter)
- else:
- sites = []
- return sites
-
-def add_site(auth, fields):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- auth['tenant'] = user.site.login_base
-
- site = Site(**fields)
- site.os_manager = OpenStackManager(auth=auth, caller = user)
- site.save()
- return site
-
-def update_site(auth, id, **fields):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- auth['tenant'] = user.site.login_base
-
- sites = _get_sites(id)
- if not sites:
- return
-
- site = Site[0]
- site.os_manager = OpenStackManager(auth=auth, caller = user)
- site.update(**fields)
- return site
-
-def delete_site(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- auth['tenant'] = user.site.login_base
- sites = _get_sites(id)
- for site in sites:
- site.os_manager = OpenStackManager(auth=auth, caller = user)
- site.delete()
- return 1
-
-def get_sites(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- sites = _get_sites(filter)
- return sites
-
-
-
diff --git a/xos/core/api/slice_memberships.py b/xos/core/api/slice_memberships.py
deleted file mode 100644
index 3e25ae7..0000000
--- a/xos/core/api/slice_memberships.py
+++ /dev/null
@@ -1,70 +0,0 @@
-from types import StringTypes
-from django.contrib.auth import authenticate
-from openstack.manager import OpenStackManager
-from core.models import SliceMembership
-from core.api.users import _get_users
-from core.api.slices import _get_slices
-from core.api.roles import _get_roles
-
-def _get_slice_memberships(filter):
- if isinstance(filter, StringTypes) and filter.isdigit():
- filter = int(filter)
- if isinstance(filter, int):
- slice_memberships = SitePrivilege.objects.filter(id=filter)
- elif isinstance(filter, StringTypes):
- slice_memberships = SitePrivilege.objects.filter(name=filter)
- elif isinstance(filter, dict):
- slice_memberships = SitePrivilege.objects.filter(**filter)
- else:
- slice_memberships = []
- return slice_memberships
-
-
-def add_slice_membership(auth, fields):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
-
- users = _get_users(fields.get('user'))
- slices = _get_slices(fields.get('slice'))
- roles = _get_roles(fields.get('role'))
-
- if users: fields['user'] = users[0]
- if slices: fields['slice'] = slices[0]
- if roles: fields['role'] = roles[0]
-
- slice_membership = SliceMembership(**fields)
- auth['tenant'] = sites[0].login_base
- slice_membership.os_manager = OpenStackManager(auth=auth, caller = user)
- slice_membership.save()
- return slice_membership
-
-def update_slice_membership(auth, id, **fields):
- return
-
-def delete_slice_membership(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- auth['tenant'] = user.site.login_base
-
- slice_memberships = _get_slice_memberships(filter)
- for slice_membership in slice_memberships:
- slice_membership.os_manager = OpenStackManager(auth=auth, caller = user)
- slice_membership.delete()
- return 1
-
-def get_slice_memberships(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- users = _get_users(fields.get('user'))
- slices = _get_slices(fields.get('slice'))
- roles = _get_roles(fields.get('role'))
-
- if users: fields['user'] = users[0]
- if slices: fields['slice'] = slices[0]
- if roles: fields['role'] = roles[0]
-
- slice_memberships = _get_slice_memberships(filter)
- return slice_memberships
-
-
-
diff --git a/xos/core/api/slices.py b/xos/core/api/slices.py
deleted file mode 100644
index c9e94a2..0000000
--- a/xos/core/api/slices.py
+++ /dev/null
@@ -1,74 +0,0 @@
-import re
-from types import StringTypes
-from django.contrib.auth import authenticate
-from openstack.manager import OpenStackManager
-from core.models import Slice
-from core.api.sites import _get_sites
-
-def _get_slices(filter):
- if isinstance(filter, StringTypes) and filter.isdigit():
- filter = int(filter)
- if isinstance(filter, int):
- slices = Slice.objects.filter(id=filter)
- elif isinstance(filter, StringTypes):
- slices = Slice.objects.filter(name=filter)
- elif isinstance(filter, dict):
- slices = Slice.objects.filter(**filter)
- else:
- slices = []
- return slices
-
-
-def add_slice(auth, fields):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- auth['tenant'] = user.site.login_base
-
- login_base = fields['name'][:fields['name'].find('_')]
- sites = _get_sites(login_base)
- if sites: fields['site'] = sites[0]
- slice = Slice(**fields)
- slice.os_manager = OpenStackManager(auth=auth, caller = user)
- slice.save()
- return slice
-
-def update_slice(auth, id, **fields):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- auth['tenant'] = user.site.login_base
-
- slices = _get_slices(id)
- if not slices:
- return
- slice = slices[0]
- sites = _get_sites(fields.get('site'))
- if sites: fields['site'] = sites[0]
-
- slice.os_manager = OpenStackManager(auth=auth, caller = user)
- for (k,v) in fields.items():
- setattr(slice, k, v)
- slice.save()
-
- return slice
-
-def delete_slice(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- auth['tenant'] = user.site.login_base
- slices = _get_slices(filter)
- for slice in slices:
- slice.os_manager = OpenStackManager(auth=auth, caller = user)
- slice.delete()
- return 1
-
-def get_slices(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- if 'site' in filter:
- sites = _get_sites(filter.get('site'))
- if sites: filter['site'] = sites[0]
- slices = _get_slices(filter)
- return slices
-
-
-
diff --git a/xos/core/api/subnets.py b/xos/core/api/subnets.py
deleted file mode 100644
index d618eda..0000000
--- a/xos/core/api/subnets.py
+++ /dev/null
@@ -1,74 +0,0 @@
-import commands
-from types import StringTypes
-from openstack.client import OpenStackClient
-from openstack.driver import OpenStackDriver
-from core.api.auth import auth_check
-from core.models import Subnet
-from core.api.slices import _get_slices
-
-
-def _get_subnets(filter):
- if isinstance(filter, StringTypes) and filter.isdigit():
- filter = int(filter)
- if isinstance(filter, int):
- subnets = Subnet.objects.filter(id=filter)
- elif isinstance(filter, StringTypes):
- # the name is the subnet's slice's name
- slices = _get_slices(filter)
- slice = None
- if slices: slice=slices[0]
- subnets = Subnet.objects.filter(slice=slice)
- elif isinstance(filter, dict):
- subnets = Subnet.objects.filter(**filter)
- else:
- subnets = []
- return subnets
-
-def add_subnet(auth, fields):
- driver = OpenStackDriver(client = auth_check(auth))
- slices = _get_slices(fields.get('slice'))
- if slices: fields['slice'] = slices[0]
- subnet = Subnet(**fields)
- # create quantum subnet
- quantum_subnet = driver.create_subnet(name= subnet.slice.name,
- network_id=subnet.slice.network_id,
- cidr_ip = subnet.cidr,
- ip_version=subnet.ip_version,
- start = subnet.start,
- end = subnet.end)
- subnet.subnet_id=quantum_subnet['id']
- ## set dns servers
- #driver.update_subnet(subnet.id, {'dns_nameservers': ['8.8.8.8', '8.8.4.4']})
-
- # add subnet as interface to slice's router
- try: driver.add_router_interface(subnet.slice.router_id, subnet.subnet_id)
- except: pass
- #add_route = 'route add -net %s dev br-ex gw 10.100.0.5' % self.cidr
- commands.getstatusoutput(add_route)
- subnet.save()
- return subnet
-
-def update_subnet(auth, subnet, **fields):
- return
-
-def delete_subnet(auth, filter={}):
- driver = OpenStackDriver(client = auth_check(auth))
- subnets = Subnet.objects.filter(**filter)
- for subnet in subnets:
- driver.delete_router_interface(subnet.slice.router_id, subnet.subnet_id)
- driver.delete_subnet(subnet.subnet_id)
- subnet.delete()
- #del_route = 'route del -net %s' % subnet.cidr
- commands.getstatusoutput(del_route)
- return 1
-
-def get_subnets(auth, filter={}):
- client = auth_check(auth)
- if 'slice' in filter:
- slice = _get_slice(filter.get('slice'))
- if slice: filter['slice'] = slice
- subnets = Subnet.objects.filter(**filter)
- return subnets
-
-
-
diff --git a/xos/core/api/users.py b/xos/core/api/users.py
deleted file mode 100644
index 08e851c..0000000
--- a/xos/core/api/users.py
+++ /dev/null
@@ -1,75 +0,0 @@
-from types import StringTypes
-from django.contrib.auth import authenticate
-from openstack.manager import OpenStackManager
-from core.models import User, Site
-from core.api.sites import _get_sites
-
-def _get_users(filter):
- if isinstance(filter, StringTypes) and filter.isdigit():
- filter = int(filter)
- if isinstance(filter, int):
- users = User.objects.filter(id=filter)
- elif isinstance(filter, StringTypes):
- users = User.objects.filter(email=filter)
- elif isinstance(filter, dict):
- users = User.objects.filter(**filter)
- else:
- users = []
- return users
-
-def add_user(auth, fields):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- auth['tenant'] = user.site.login_base
-
- sites = _get_sites(fields.get('site'))
- if sites: fields['site'] = sites[0]
- user = User(**fields)
- user.os_manager = OpenStackManager(auth=auth, caller = user)
- user.save()
- return user
-
-def update_user(auth, id, **fields):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- auth['tenant'] = user.site.login_base
-
- users = User.objects.filter(id=id)
- if not users:
- return
-
- user = users[0]
- nova_fields = {}
- if 'email' in fields:
- nova_fields['name'] = fields['email'][:self.email.find('@')]
- nova_fields['email'] = fields['email']
- if 'password' in fields:
- nova_fields['password'] = fields['password']
- if 'enabled' in fields:
- nova_fields['enabled'] = fields['enabled']
- sites = _get_sites(fields.get('site'))
- if sites: fields['site'] = sites[0]
- user.os_manager = OpenStackManager(auth=auth, caller = user)
- for (k,v) in fields.items():
- setattr(user, k, v)
- user.save()
- return user
-
-def delete_user(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- auth['tenant'] = user.site.login_base
- users = _get_users(filter)
- for user in users:
- user.os_manager = OpenStackManager(auth=auth, caller = user)
- user.delete()
- return 1
-
-def get_users(auth, filter={}):
- user = authenticate(username=auth.get('username'),
- password=auth.get('password'))
- users = _get_users(filter)
- return users
-
-
-
diff --git a/xos/core/api_root.py b/xos/core/api_root.py
deleted file mode 100644
index c3d69f1..0000000
--- a/xos/core/api_root.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from rest_framework.decorators import api_view
-from rest_framework.response import Response
-from rest_framework.reverse import reverse
-
-@api_view(['GET'])
-def api_root(request, format=None):
- return Response({
- 'deployments': reverse('deployment-list', request=request, format=format),
- 'images': reverse('image-list', request=request, format=format),
- 'nodes': reverse('node-list', request=request, format=format),
- 'projects': reverse('project-list', request=request, format=format),
- 'reservations': reverse('reservation-list', request=request, format=format),
- 'roles': reverse('role-list', request=request, format=format),
- 'serviceclasses': reverse('serviceclass-list', request=request, format=format),
- 'serviceresources': reverse('serviceresource-list', request=request, format=format),
- 'sites': reverse('site-list', request=request, format=format),
- 'slices': reverse('slice-list', request=request, format=format),
- 'instances': reverse('instance-list', request=request, format=format),
- 'tags': reverse('tag-list', request=request, format=format),
- 'users': reverse('user-list', request=request, format=format),
- })
diff --git a/xos/core/dashboard/views/view_common.py b/xos/core/dashboard/views/view_common.py
index 0ef422e..ba78ffd 100644
--- a/xos/core/dashboard/views/view_common.py
+++ b/xos/core/dashboard/views/view_common.py
@@ -4,9 +4,9 @@
import datetime
from pprint import pprint
import json
-from syndicate_storage.models import *
+from services.syndicate_storage.models import *
from core.models import *
-from hpc.models import ContentProvider
+from services.hpc.models import ContentProvider
from operator import attrgetter
from django import template
from django.views.decorators.csrf import csrf_exempt
diff --git a/xos/core/fixtures/initial_data.json b/xos/core/fixtures/core_initial_data.json
similarity index 100%
rename from xos/core/fixtures/initial_data.json
rename to xos/core/fixtures/core_initial_data.json
diff --git a/xos/core/models/__init__.py b/xos/core/models/__init__.py
index c380e9c..a022cae 100644
--- a/xos/core/models/__init__.py
+++ b/xos/core/models/__init__.py
@@ -2,7 +2,7 @@
from .project import Project
from .singletonmodel import SingletonModel
from .service import Service, Tenant, TenantWithContainer, CoarseTenant, ServicePrivilege, TenantRoot, TenantRootPrivilege, TenantRootRole, Subscriber, Provider
-from .service import ServiceAttribute, TenantAttribute
+from .service import ServiceAttribute, TenantAttribute, ServiceRole
from .tag import Tag
from .role import Role
from .site import Site, Deployment, DeploymentRole, DeploymentPrivilege, Controller, ControllerRole, ControllerSite, SiteDeployment
diff --git a/xos/core/models/instance.py b/xos/core/models/instance.py
index cd7dd26..62a86c4 100644
--- a/xos/core/models/instance.py
+++ b/xos/core/models/instance.py
@@ -15,7 +15,6 @@
from core.models import Flavor
from django.contrib.contenttypes import generic
from xos.config import Config
-from monitor import driver as monitor
from django.core.exceptions import PermissionDenied, ValidationError
config = Config()
diff --git a/xos/core/models/plcorebase.py b/xos/core/models/plcorebase.py
index 360792f..5c0d7ab 100644
--- a/xos/core/models/plcorebase.py
+++ b/xos/core/models/plcorebase.py
@@ -1,4 +1,5 @@
import datetime
+import json
import os
import sys
from django import db
@@ -8,13 +9,13 @@
from django.forms.models import model_to_dict
from django.utils import timezone
from django.core.exceptions import PermissionDenied
-import model_policy
+import synchronizers.model_policy
from model_autodeletion import ephemeral_models
from cgi import escape as html_escape
try:
# This is a no-op if observer_disabled is set to 1 in the config file
- from observer import *
+ from synchronizers.base import *
except:
print >> sys.stderr, "import of observer failed! printing traceback and disabling observer:"
import traceback
@@ -118,6 +119,38 @@
validators[field.name] = l
return validators
+ def get_backend_details(self):
+ try:
+ scratchpad = json.loads(self.backend_register)
+ except AttributeError:
+ return (None, None, None, None)
+
+ try:
+ exponent = scratchpad['exponent']
+ except KeyError:
+ exponent = None
+
+ try:
+ last_success_time = scratchpad['last_success']
+ dt = datetime.datetime.fromtimestamp(last_success_time)
+ last_success = dt.strftime("%Y-%m-%d %H:%M")
+ except KeyError:
+ last_success = None
+
+ try:
+ failures = scratchpad['failures']
+ except KeyError:
+ failures=None
+
+ try:
+ last_failure_time = scratchpad['last_failure']
+ dt = datetime.datetime.fromtimestamp(last_failure_time)
+ last_failure = dt.strftime("%Y-%m-%d %H:%M")
+ except KeyError:
+ last_failure = None
+
+ return (exponent, last_success, last_failure, failures)
+
def get_backend_icon(self):
is_perfect = (self.backend_status is not None) and self.backend_status.startswith("1 -")
is_good = (self.backend_status is not None) and (self.backend_status.startswith("0 -") or self.backend_status.startswith("1 -"))
diff --git a/xos/core/models/service.py b/xos/core/models/service.py
index 7cf2a6b..b5ba737 100644
--- a/xos/core/models/service.py
+++ b/xos/core/models/service.py
@@ -174,9 +174,9 @@
for ns in slice.networkslices.all():
if not ns.network:
continue
- if ns.network.template.access in ["direct", "indirect"]:
- # skip access networks; we want to use the private network
- continue
+# if ns.network.template.access in ["direct", "indirect"]:
+# # skip access networks; we want to use the private network
+# continue
if ns.network.name in ["wan_network", "lan_network"]:
# we don't want to attach to the vCPE's lan or wan network
# we only want to attach to its private network
diff --git a/xos/core/models/slice.py b/xos/core/models/slice.py
index 84622cf..42e3a25 100644
--- a/xos/core/models/slice.py
+++ b/xos/core/models/slice.py
@@ -15,6 +15,7 @@
from core.models import Flavor, Image
from core.models.plcorebase import StrippedCharField
from django.core.exceptions import PermissionDenied, ValidationError
+from xos.exceptions import *
# Create your models here.
@@ -52,13 +53,13 @@
site = Site.objects.get(id=self.site.id)
# allow preexisting slices to keep their original name for now
if not self.id and not self.name.startswith(site.login_base):
- raise ValidationError('slice name must begin with %s' % site.login_base)
+ raise XOSValidationError('slice name must begin with %s' % site.login_base)
if self.name == site.login_base+"_":
- raise ValidationError('slice name is too short')
+ raise XOSValidationError('slice name is too short')
if " " in self.name:
- raise ValidationError('slice name must not contain spaces')
+ raise XOSValidationError('slice name must not contain spaces')
if self.serviceClass is None:
# We allowed None=True for serviceClass because Django evolution
@@ -82,7 +83,7 @@
raise PermissionDenied("Insufficient privileges to change slice creator")
if not self.creator:
- raise ValidationError('slice has no creator')
+ raise XOSValidationError('slice has no creator')
if self.network=="Private Only":
# "Private Only" was the default from the old Tenant View
diff --git a/xos/core/models/user.py b/xos/core/models/user.py
index cb90145..0b8e3af 100644
--- a/xos/core/models/user.py
+++ b/xos/core/models/user.py
@@ -15,12 +15,12 @@
from timezones.fields import TimeZoneField
from operator import itemgetter, attrgetter
from core.middleware import get_request
-import model_policy
+import synchronizers.model_policy
# ------ from plcorebase.py ------
try:
# This is a no-op if observer_disabled is set to 1 in the config file
- from observer import *
+ from synchronizers.base import *
except:
print >> sys.stderr, "import of observer failed! printing traceback and disabling observer:"
import traceback
diff --git a/xos/core/static/donw_arrow.png b/xos/core/static/down_arrow.png
similarity index 100%
rename from xos/core/static/donw_arrow.png
rename to xos/core/static/down_arrow.png
Binary files differ
diff --git a/xos/core/tests.py b/xos/core/tests.py
index e3d7faa..06bf678 100644
--- a/xos/core/tests.py
+++ b/xos/core/tests.py
@@ -1,128 +1,337 @@
+# TEST
+# To execute these tests use `python manage.py test core`
+
#!/usr/bin/env python
from django.test import TestCase
-from core.models import *
-from rest_framework.test import *
-from genapi import *
+from django.contrib.auth.models import User
+from rest_framework import status
+from rest_framework.test import APIClient
+from rest_framework.test import APITestCase
import json
-from datetime import datetime
+from django.forms.models import model_to_dict
-FIXTURES_FILE = 'core/fixtures/initial_data.json'
-MODELS = ['Deployment','Image','Node','Reservation','Slice','Instance','User']
+from core.models import *
-def is_dynamic_type(x):
- t = type(x)
- return t in [datetime]
+print "-------------------------- Let's test!!!!!!!! --------------------------"
-class APITestCase(TestCase):
- def setUp(self):
- self.init_data=json.loads(open(FIXTURES_FILE).read())
- self.data_dict={}
- self.hidden_keys={}
+from django.apps import apps
+from django.test.client import Client
+from django.test import testcases
+from django.http import SimpleCookie, HttpRequest, QueryDict
+from importlib import import_module
+from django.conf import settings
+class FixedClient(Client):
+ def login(self, **credentials):
+ """
+ Sets the Factory to appear as if it has successfully logged into a site.
- for d in self.init_data:
- model_tag = d['model']
- model_name = model_tag.split('.')[1]
+ Returns True if login is possible; False if the provided credentials
+ are incorrect, or the user is inactive, or if the sessions framework is
+ not available.
+ """
+ from django.contrib.auth import authenticate, login
+ user = authenticate(**credentials)
+ if (user and user.is_active and
+ apps.is_installed('django.contrib.sessions')):
+ engine = import_module(settings.SESSION_ENGINE)
- try:
- self.data_dict[model_name].append(d)
- except:
- self.data_dict[model_name]=[d]
+ # Create a fake request to store login details.
+ request = HttpRequest()
- # Any admin user would do
- self.calling_user = User('sapan@onlab.us')
- self.client = APIClient()
- self.client.force_authenticate(user=self.calling_user)
+ # XOS's admin.py requires these to be filled in
+ request.POST = {"username": credentials["username"],
+ "password": credentials["password"]}
+
+ if self.session:
+ request.session = self.session
+ else:
+ request.session = engine.SessionStore()
+ login(request, user)
+
+ # Save the session values.
+ request.session.save()
+
+ # Set the cookie to represent the session.
+ session_cookie = settings.SESSION_COOKIE_NAME
+ self.cookies[session_cookie] = request.session.session_key
+ cookie_data = {
+ 'max-age': None,
+ 'path': '/',
+ 'domain': settings.SESSION_COOKIE_DOMAIN,
+ 'secure': settings.SESSION_COOKIE_SECURE or None,
+ 'expires': None,
+ }
+ self.cookies[session_cookie].update(cookie_data)
+
+ return True
+ else:
+ return False
+
+class FixedAPITestCase(testcases.TestCase):
+ client_class = FixedClient
+
+# Environment Tests - Should pass everytime, if not something in the config is broken.
+class SimpleTest(TestCase):
+ fixtures = []
+
+ def test_basic_addition(self):
+ """
+ Tests that 1 + 1 always equals 2.
+ """
+ self.assertEqual(1 + 1, 2)
- def check_items(self, response, data_list):
- rdict = {}
- for r in response:
- rdict['%d'%r['id']]=r
+# Site Test
+class SiteTest(TestCase):
+ fixtures = []
- for d in data_list:
- match = True
- try:
- item = rdict['%d'%d['pk']]
- except Exception,e:
- print 'API missing item %d / %r'%(d['pk'],rdict.keys())
- raise e
+ def setUp(self):
+ Site.objects.create(
+ name="Test Site",
+ login_base="test_"
+ )
- fields=d['fields']
- fields['id']=d['pk']
-
- for k in item.keys():
- try:
- resp_val = fields[k]
- except KeyError:
- if (not self.hidden_keys.has_key(k)):
- print 'Hidden key %s'%k
- self.hidden_keys[k]=True
-
- continue
-
- if (item[k]!=resp_val and not is_dynamic_type(item[k])):
- if (type(resp_val)==type(item[k])):
- print 'Key %s did not match: 1. %r 2. %r'%(k,item[k],resp_val)
- print fields
- match = False
+ def test_read_site(self):
+ """
+ Should read a site in the DB.
+ """
+ site = Site.objects.get(name="Test Site")
+ # print(site._meta.get_all_field_names())
+ self.assertEqual(site.login_base, "test_")
+class UnautheticatedRequest(FixedAPITestCase):
+ fixtures = []
- def create(self, model, mplural, record):
- request = self.client.put('/xos/%s/'%mplural,record['fields'])
+ def test_require_authentication(self):
+ """
+ Ensure that request must be authenticated
+ """
+ response = self.client.get('/xos/sites/', format='json')
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- #if (len2==len1):
- # raise Exception('Could not delete %s/%d'%(model,pk))
- return
+class SiteTestAPI(FixedAPITestCase):
+ fixtures = []
- def update(self, model, mplural, pk):
- src_record = self.data_dict[model.lower()][0]
- record_to_update = src_record['fields']
- now = datetime.now()
- record_to_update['enacted']=now
- response = self.client.put('/xos/%s/%d/'%(mplural,pk),record_to_update)
- self.assertEqual(response.data['enacted'],now)
+ def setUp(self):
+ self.site = Site.objects.create(
+ name="Test Site",
+ login_base="test_"
+ )
+ self.user = User(
+ username='testuser',
+ email='test@mail.org',
+ password='testing',
+ site=self.site,
+ is_admin=True
+ )
+ self.user.save()
+ self.client.login(username='test@mail.org', password='testing')
- return
+ def test_read_site_API(self):
+ """
+ Read a Site trough API
+ """
+ response = self.client.get('/xos/sites/', format='json')
+ parsed = json.loads(response.content)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(parsed), 1)
+ self.assertEqual(parsed[0]['login_base'], 'test_')
- def delete(self, model, mplural, pk):
- mclass = globals()[model]
- len1 = len(mclass.objects.all())
- response = self.client.delete('/xos/%s/%d/'%(mplural,pk))
- len2 = len(mclass.objects.all())
- self.assertNotEqual(len1,len2)
+ def test_create_site_API(self):
+ """
+ Create a Site trough API
+ """
+ data = {
+ 'name': "Another Test Site",
+ 'login_base': "another_test_",
+ 'location': [10, 20],
+ 'abbreviated_name': 'test'
+ }
+ response = self.client.post('/xos/sites/', data, format='json')
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(Site.objects.count(), 2)
+ self.assertEqual(Site.objects.filter(name="Another Test Site").count(), 1)
- return
- def retrieve(self, m, mplural, mlower):
- response = self.client.get('/xos/%s/'%mplural)
- #force_authenticate(request,user=self.calling_user)
- self.check_items(response.data,self.data_dict[mlower])
+class SliceTestAPI(FixedAPITestCase):
+ fixtures = []
- return
+ def setUp(self):
+ self.site = Site.objects.create(
+ name="Test Site",
+ login_base="test_"
+ )
+ self.pi = SiteRole.objects.create(role='pi')
+ self.user = User(
+ username='testuser',
+ email='test@mail.org',
+ password='testing',
+ site=self.site
+ )
+ self.user.save()
+ self.siteprivileges = SitePrivilege.objects.create(
+ user=self.user,
+ site=self.site,
+ role=self.pi
+ )
+ self.serviceClass = ServiceClass.objects.create(
+ name='Test Service Class'
+ )
+ self.client.login(username='test@mail.org', password='testing')
- def test_initial_retrieve(self):
- for m in MODELS:
- print 'Checking retrieve on %s...'%m
- self.retrieve(m, m.lower()+'s',m.lower())
+ def test_create_site_slice(self):
+ """
+ Add a slice to a given site
+ """
+ data = {
+ 'name': "test_slice",
+ 'site': self.site.id,
+ 'serviceClass': self.serviceClass.id
+ }
+ response = self.client.post('/xos/slices/?no_hyperlinks=1', data, format='json')
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
-
- def test_update(self):
- for m in MODELS:
- print 'Checking update on %s...'%m
- first = self.data_dict[m.lower()][0]['pk']
- self.update(m, m.lower()+'s',int(first))
-
- def test_delete(self):
- for m in MODELS:
- print 'Checking delete on %s...'%m
- first = self.data_dict[m.lower()][0]['pk']
- self.delete(m, m.lower()+'s',int(first))
+ def test_validation_slice_name(self):
+ """
+ The slice name should start with site.login_base
+ curl -H "Accept: application/json; indent=4" -u padmin@vicci.org:letmein 'http://xos:9999/xos/slices/?no_hyperlinks=1' -H "Content-Type: application/json" -X POST --data '{"name": "test", "site":"1", "serviceClass":1}'
+ """
+ data = {
+ 'name': "wrong_slice",
+ 'site': self.site.id,
+ 'serviceClass': self.serviceClass.id
+ }
+ response = self.client.post('/xos/slices/?no_hyperlinks=1', data, format='json')
+ parsed = json.loads(response.content)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(parsed['detail']['specific_error'], "slice name must begin with test_")
- def test_create(self):
- for m in MODELS:
- print 'Checking create on %s...'%m
- first = self.data_dict[m.lower()][0]
- self.create(m, m.lower()+'s',first)
+ def test_only_admin_can_change_creator(self):
+ """
+ Only an admin can change the creator of a slice
+ """
+ slice = Slice.objects.create(
+ name="test_slice",
+ site=self.site,
+ serviceClass=self.serviceClass,
+ creator=self.user
+ )
+ user2 = User(
+ username='another_testuser',
+ email='another_test@mail.org',
+ password='testing',
+ site=self.site
+ )
+ user2.save()
+
+ data = model_to_dict(slice)
+ data['creator'] = user2.id
+ json_data = json.dumps(data)
+
+ response = self.client.put('/xos/slices/%s/?no_hyperlinks=1' % slice.id, json_data, format='json', content_type="application/json")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ parsed = json.loads(response.content)
+ self.assertEqual(parsed['detail']['specific_error'], "Insufficient privileges to change slice creator")
+
+class ServiceTestAPI(FixedAPITestCase):
+ fixtures = []
+
+ def setUp(self):
+ self.site = Site.objects.create(
+ name="Test Site",
+ login_base="test_"
+ )
+ self.admin = User(
+ username='testadmin',
+ email='admin@mail.org',
+ password='testing',
+ site=self.site,
+ is_admin=True
+ )
+ self.admin.save()
+
+ self.user = User(
+ username='testuser',
+ email='user@mail.org',
+ password='testing',
+ site=self.site
+ )
+ self.user.save()
+
+ self.service1 = Service.objects.create(
+ name="fakeService1",
+ versionNumber="1.0.0",
+ published=True,
+ enabled=True
+ )
+
+ self.service2 = Service.objects.create(
+ name="fakeService1",
+ versionNumber="1.0.0",
+ published=True,
+ enabled=True
+ )
+
+ self.service_role = ServiceRole.objects.create(role='admin')
+
+ self.service_privileges = ServicePrivilege.objects.create(
+ user=self.user,
+ service=self.service2,
+ role=self.service_role
+ )
+
+ # TODO
+ # [x] admin view all service
+ # [ ] user view only service2
+ # [x] admin view a specific service service
+ # [ ] user view can't view a specific service
+ # [ ] user update service2
+ # [ ] usercan NOT update service2
+ # [x] admin update service1
+ def test_admin_read_all_service(self):
+ """
+ Admin should read all the services
+ """
+ self.client.login(username='admin@mail.org', password='testing')
+ response = self.client.get('/xos/services/', format='json')
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(json.loads(response.content)), 2)
+
+ # need to understand how slices are related
+ def xtest_user_read_all_service(self):
+ """
+ User should read only service for which have privileges
+ """
+ self.client.login(username='user@mail.org', password='testing')
+ response = self.client.get('/xos/services/', format='json')
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(json.loads(response.content)), 1)
+
+ def test_admin_read_one_service(self):
+ """
+ Read a given service
+ """
+ self.client.login(username='admin@mail.org', password='testing')
+ response = self.client.get('/xos/services/%s/' % self.service1.id, format='json')
+ parsed = json.loads(response.content)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(parsed['name'], self.service1.name)
+
+ def test_admin_update_service(self):
+ """
+ Update a given service
+ """
+ data = model_to_dict(self.service1)
+ data['name'] = "newName"
+ json_data = json.dumps(data)
+
+ self.client.login(username='admin@mail.org', password='testing')
+ response = self.client.put('/xos/services/%s/' % self.service1.id, json_data, format='json', content_type="application/json")
+ parsed = json.loads(response.content)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ model = Service.objects.get(id=self.service1.id)
+ self.assertEqual(model.name, data['name'])
+
\ No newline at end of file
diff --git a/xos/core/views/deployments.py b/xos/core/views/deployments.py
deleted file mode 100644
index 285a53a..0000000
--- a/xos/core/views/deployments.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from core.serializers import DeploymentSerializer
-from rest_framework import generics
-from core.models import Deployment
-
-class DeploymentList(generics.ListCreateAPIView):
- queryset = Deployment.objects.all()
- serializer_class = DeploymentSerializer
-
-class DeploymentDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = Deployment.objects.all()
- serializer_class = DeploymentSerializer
-
diff --git a/xos/core/views/hpc_config.py b/xos/core/views/hpc_config.py
index c83c01b..a181a1c 100644
--- a/xos/core/views/hpc_config.py
+++ b/xos/core/views/hpc_config.py
@@ -1,8 +1,7 @@
from django.http import HttpResponse, HttpResponseServerError
-from monitor import driver
from core.models import *
-from hpc.models import *
-from requestrouter.models import *
+from services.hpc.models import *
+from services.requestrouter.models import *
import xos.settings
import json
import os
@@ -110,22 +109,22 @@
ENABLE_PLC=False
ENABLE_PS=True
BASE_HRN="princeton"
-RELEVANT_SERVICE_NAMES=['vcoblitz', 'coredirect', 'codnsdemux', "syndicate_comon_server"]
-COBLITZ_SLICE_NAME=BASE_HRN+"_vcoblitz"
+RELEVANT_SERVICE_NAMES=['vcoblitz', 'coredirect', 'codnsdemux', "syndicate_comon_server"]
+COBLITZ_SLICE_NAME=BASE_HRN+"_vcoblitz"
COBLITZ_SLICE_ID=70
COBLITZ_PS_SLICE_NAME="{hpc_slicename}"
DNSREDIR_SLICE_NAME=BASE_HRN+"_coredirect"
-DNSREDIR_SLICE_ID=71
-DNSREDIR_PS_SLICE_NAME="{redir_slicename}"
-DNSDEMUX_SLICE_NAME=BASE_HRN+"_codnsdemux"
-DNSDEMUX_SLICE_ID=69
-DNSDEMUX_PS_SLICE_NAME="{demux_slicename}"
-CMI_URL="http://{cmi_hostname}/"
-CMI_HTTP_PORT="8004"
-CMI_HTTPS_PORT="8003"
-PUPPET_MASTER_HOSTNAME="{cmi_hostname}"
-PUPPET_MASTER_PORT="8140"
-PS_HOSTNAME="{xos_hostname}"
+DNSREDIR_SLICE_ID=71
+DNSREDIR_PS_SLICE_NAME="{redir_slicename}"
+DNSDEMUX_SLICE_NAME=BASE_HRN+"_codnsdemux"
+DNSDEMUX_SLICE_ID=69
+DNSDEMUX_PS_SLICE_NAME="{demux_slicename}"
+CMI_URL="http://{cmi_hostname}/"
+CMI_HTTP_PORT="8004"
+CMI_HTTPS_PORT="8003"
+PUPPET_MASTER_HOSTNAME="{cmi_hostname}"
+PUPPET_MASTER_PORT="8140"
+PS_HOSTNAME="{xos_hostname}"
PS_PORT="{xos_port}"
COBLITZ_PORT_80={hpc_port80}
""".format(**d))
diff --git a/xos/core/views/images.py b/xos/core/views/images.py
deleted file mode 100644
index 5ea5d76..0000000
--- a/xos/core/views/images.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from core.serializers import ImageSerializer
-from rest_framework import generics
-from core.models import Image
-
-class ImageList(generics.ListCreateAPIView):
- queryset = Image.objects.all()
- serializer_class = ImageSerializer
-
-class ImageDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = Image.objects.all()
- serializer_class = ImageSerializer
-
diff --git a/xos/core/views/instances.py b/xos/core/views/instances.py
deleted file mode 100644
index e424538..0000000
--- a/xos/core/views/instances.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from core.serializers import InstanceSerializer
-from rest_framework import generics
-from core.models import Instance
-
-class InstanceList(generics.ListCreateAPIView):
- queryset = Instance.objects.all()
- serializer_class = InstanceSerializer
-
-class InstanceDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = Instance.objects.all()
- serializer_class = InstanceSerializer
-
-
diff --git a/xos/core/views/nodes.py b/xos/core/views/nodes.py
deleted file mode 100644
index 8706114..0000000
--- a/xos/core/views/nodes.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from core.serializers import NodeSerializer
-from rest_framework import generics
-from core.models import Node
-
-class NodeList(generics.ListCreateAPIView):
- queryset = Node.objects.all()
- serializer_class = NodeSerializer
-
-class NodeDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = Node.objects.all()
- serializer_class = NodeSerializer
-
-
diff --git a/xos/core/views/observer.py b/xos/core/views/observer.py
index 2912db9..3aabc4a 100644
--- a/xos/core/views/observer.py
+++ b/xos/core/views/observer.py
@@ -1,5 +1,4 @@
from django.http import HttpResponse
-from monitor import driver
from core.models import *
import json
import os
diff --git a/xos/core/views/projects.py b/xos/core/views/projects.py
deleted file mode 100644
index c5311d5..0000000
--- a/xos/core/views/projects.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from core.serializers import ProjectSerializer
-from rest_framework import generics
-from core.models import Project
-
-class ProjectList(generics.ListCreateAPIView):
- queryset = Project.objects.all()
- serializer_class = ProjectSerializer
-
-class ProjectDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = Project.objects.all()
- serializer_class = ProjectSerializer
-
-
diff --git a/xos/core/views/reservations.py b/xos/core/views/reservations.py
deleted file mode 100644
index 03f79eb..0000000
--- a/xos/core/views/reservations.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from core.serializers import ReservationSerializer
-from rest_framework import generics
-from core.models import Reservation
-
-class ReservationList(generics.ListCreateAPIView):
- queryset = Reservation.objects.all()
- serializer_class = ReservationSerializer
-
-class ReservationDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = Reservation.objects.all()
- serializer_class = ReservationSerializer
-
-
diff --git a/xos/core/views/roles.py b/xos/core/views/roles.py
deleted file mode 100644
index 13c9917..0000000
--- a/xos/core/views/roles.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from core.serializers import RoleSerializer
-from rest_framework import generics
-from core.models import Role
-
-class RoleList(generics.ListCreateAPIView):
- queryset = Role.objects.all()
- serializer_class = RoleSerializer
-
-class RoleDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = Role.objects.all()
- serializer_class = RoleSerializer
-
-
diff --git a/xos/core/views/serviceGraph.py b/xos/core/views/serviceGraph.py
new file mode 100644
index 0000000..5ce0581
--- /dev/null
+++ b/xos/core/views/serviceGraph.py
@@ -0,0 +1,140 @@
+from django.http import HttpResponse
+from django.views.generic import TemplateView, View
+from django import template
+from core.models import *
+import json
+import os
+import time
+import tempfile
+
+class ServiceGridView(TemplateView):
+ head_template = r"""{% extends "admin/dashboard/dashboard_base.html" %}
+ {% load admin_static %}
+ {% block content %}
+ """
+
+ tail_template = r"{% endblock %}"
+
+ def get(self, request, name="root", *args, **kwargs):
+ head_template = self.head_template
+ tail_template = self.tail_template
+
+ html = '<table class="service-grid"><tr>'
+
+ icons=[]
+ for service in Service.objects.all():
+ view_url = service.view_url
+ if (not view_url):
+ view_url = "/admin/core/service/$id$/"
+ view_url = view_url.replace("$id$", str(service.id))
+
+ image_url = service.icon_url
+ if (not image_url):
+ image_url = "/static/primarycons_blue/gear_2.png"
+
+ icons.append( {"name": service.name, "view_url": view_url, "image_url": image_url} )
+
+ icons.append( {"name": "Tenancy Graph", "view_url": "/serviceGraph.png", "image_url": "/static/primarycons_blue/service_graph.png", "horiz_rule": True} )
+ icons.append( {"name": "Add Service", "view_url": "/admin/core/service/add/", "image_url": "/static/primarycons_blue/plus.png"} )
+
+ i=0
+ for icon in icons:
+ if icon.get("horiz_rule", False):
+ html = html + "</tr><tr><td colspan=4><hr></td></tr><tr>"
+ i=0
+
+ service_name = icon["name"]
+ view_url = icon["view_url"]
+ image_url = icon["image_url"]
+
+ if (i%4) == 0:
+ html = html + '</tr><tr>'
+
+ html = html + '<td width=96 height=128 valign=top align=center><a class="service-grid-icon" href="%s"><img src="%s" height=64 width=64></img></a>' % (view_url, image_url)
+ html = html + '<p><a class="service-grid-icon-link" href="%s">%s</a></p></td>' % (view_url, service_name)
+ i=i+1
+
+ html = html + '</tr></table>'
+
+ t = template.Template(head_template + html + self.tail_template)
+
+ response_kwargs = {}
+ response_kwargs.setdefault('content_type', self.content_type)
+ return self.response_class(
+ request = request,
+ template = t,
+ **response_kwargs)
+
+class ServiceGraphViewOld(TemplateView):
+ # this attempt used networkx
+ # yum -y install python-matplotlib python-networkx
+ # pip-python install -upgrade networkx
+ # pip-python install graphviz pygraphviz
+
+ def get(self, request, name="root", *args, **kwargs):
+ import networkx as nx
+ import matplotlib as mpl
+ mpl.use("Agg")
+ import matplotlib.pyplot as plt
+ import nxedges
+
+ plt.figure(figsize=(10,8))
+
+ g = nx.DiGraph()
+
+ labels = {}
+ for service in Service.objects.all():
+ g.add_node(service.id)
+ if len(service.name)>8:
+ labels[service.id] = service.name[:8] + "\n" + service.name[8:]
+ else:
+ labels[service.id] = service.name
+
+ for tenant in CoarseTenant.objects.all():
+ if (not tenant.provider_service) or (not tenant.subscriber_service):
+ continue
+ g.add_edge(tenant.subscriber_service.id, tenant.provider_service.id)
+
+ pos = nx.graphviz_layout(g)
+ nxedges.xos_draw_networkx_edges(g,pos,arrow_len=30)
+ nx.draw_networkx_nodes(g,pos,node_size=5000)
+ nx.draw_networkx_labels(g,pos,labels,font_size=12)
+ #plt.axis('off')
+ plt.savefig("/tmp/foo.png")
+
+ return HttpResponse(open("/tmp/foo.png","r").read(), content_type="image/png")
+
+class ServiceGraphView(TemplateView):
+ # this attempt just uses graphviz directly
+ # yum -y install graphviz
+ # pip-python install pygraphviz
+
+ def get(self, request, name="root", *args, **kwargs):
+ import pygraphviz as pgv
+
+ g = pgv.AGraph(directed=True)
+ g.graph_attr.update(size="8,4!")
+ g.graph_attr.update(dpi="100")
+ #g.graph_attr.update(nodesep="2.5")
+ g.graph_attr.update(overlap="false")
+ g.graph_attr.update(graphdir="TB")
+
+ for service in Service.objects.all():
+ provided_tenants = Tenant.objects.filter(provider_service=service, subscriber_service__isnull=False)
+ subscribed_tenants = Tenant.objects.filter(subscriber_service=service, provider_service__isnull=False)
+ if not (provided_tenants or subscribed_tenants):
+ # nodes with no edges aren't interesting
+ continue
+ g.add_node(service.id, label=service.name)
+
+ for tenant in Tenant.objects.all():
+ if (not tenant.provider_service) or (not tenant.subscriber_service):
+ continue
+ g.add_edge(tenant.subscriber_service.id, tenant.provider_service.id)
+
+ tf = tempfile.TemporaryFile()
+ g.layout(prog="dot")
+ g.draw(path=tf, format="png")
+ tf.seek(0)
+
+ return HttpResponse(tf.read(), content_type="image/png")
diff --git a/xos/core/views/serviceclasses.py b/xos/core/views/serviceclasses.py
deleted file mode 100644
index b8b1b70..0000000
--- a/xos/core/views/serviceclasses.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from core.serializers import ServiceClassSerializer
-from rest_framework import generics
-from core.models import ServiceClass
-
-class ServiceClassList(generics.ListCreateAPIView):
- queryset = ServiceClass.objects.all()
- serializer_class = ServiceClassSerializer
-
-class ServiceClassDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = ServiceClass.objects.all()
- serializer_class = ServiceClassSerializer
-
-
diff --git a/xos/core/views/serviceresources.py b/xos/core/views/serviceresources.py
deleted file mode 100644
index e394c18..0000000
--- a/xos/core/views/serviceresources.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from core.serializers import ServiceResourceSerializer
-from rest_framework import generics
-from core.models import ServiceResource
-
-class ServiceResourceList(generics.ListCreateAPIView):
- queryset = ServiceResource.objects.all()
- serializer_class = ServiceResourceSerializer
-
-class ServiceResourceDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = ServiceResource.objects.all()
- serializer_class = ServiceResourceSerializer
-
-
diff --git a/xos/core/views/services.py b/xos/core/views/services.py
deleted file mode 100644
index e11988b..0000000
--- a/xos/core/views/services.py
+++ /dev/null
@@ -1,141 +0,0 @@
-from django.http import HttpResponse
-from django.views.generic import TemplateView, View
-from django import template
-from monitor import driver
-from core.models import *
-import json
-import os
-import time
-import tempfile
-
-class ServiceGridView(TemplateView):
- head_template = r"""{% extends "admin/dashboard/dashboard_base.html" %}
- {% load admin_static %}
- {% block content %}
- """
-
- tail_template = r"{% endblock %}"
-
- def get(self, request, name="root", *args, **kwargs):
- head_template = self.head_template
- tail_template = self.tail_template
-
- html = '<table class="service-grid"><tr>'
-
- icons=[]
- for service in Service.objects.all():
- view_url = service.view_url
- if (not view_url):
- view_url = "/admin/core/service/$id$/"
- view_url = view_url.replace("$id$", str(service.id))
-
- image_url = service.icon_url
- if (not image_url):
- image_url = "/static/primarycons_blue/gear_2.png"
-
- icons.append( {"name": service.name, "view_url": view_url, "image_url": image_url} )
-
- icons.append( {"name": "Tenancy Graph", "view_url": "/serviceGraph.png", "image_url": "/static/primarycons_blue/service_graph.png", "horiz_rule": True} )
- icons.append( {"name": "Add Service", "view_url": "/admin/core/service/add/", "image_url": "/static/primarycons_blue/plus.png"} )
-
- i=0
- for icon in icons:
- if icon.get("horiz_rule", False):
- html = html + "</tr><tr><td colspan=4><hr></td></tr><tr>"
- i=0
-
- service_name = icon["name"]
- view_url = icon["view_url"]
- image_url = icon["image_url"]
-
- if (i%4) == 0:
- html = html + '</tr><tr>'
-
- html = html + '<td width=96 height=128 valign=top align=center><a class="service-grid-icon" href="%s"><img src="%s" height=64 width=64></img></a>' % (view_url, image_url)
- html = html + '<p><a class="service-grid-icon-link" href="%s">%s</a></p></td>' % (view_url, service_name)
- i=i+1
-
- html = html + '</tr></table>'
-
- t = template.Template(head_template + html + self.tail_template)
-
- response_kwargs = {}
- response_kwargs.setdefault('content_type', self.content_type)
- return self.response_class(
- request = request,
- template = t,
- **response_kwargs)
-
-class ServiceGraphViewOld(TemplateView):
- # this attempt used networkx
- # yum -y install python-matplotlib python-networkx
- # pip-python install -upgrade networkx
- # pip-python install graphviz pygraphviz
-
- def get(self, request, name="root", *args, **kwargs):
- import networkx as nx
- import matplotlib as mpl
- mpl.use("Agg")
- import matplotlib.pyplot as plt
- import nxedges
-
- plt.figure(figsize=(10,8))
-
- g = nx.DiGraph()
-
- labels = {}
- for service in Service.objects.all():
- g.add_node(service.id)
- if len(service.name)>8:
- labels[service.id] = service.name[:8] + "\n" + service.name[8:]
- else:
- labels[service.id] = service.name
-
- for tenant in CoarseTenant.objects.all():
- if (not tenant.provider_service) or (not tenant.subscriber_service):
- continue
- g.add_edge(tenant.subscriber_service.id, tenant.provider_service.id)
-
- pos = nx.graphviz_layout(g)
- nxedges.xos_draw_networkx_edges(g,pos,arrow_len=30)
- nx.draw_networkx_nodes(g,pos,node_size=5000)
- nx.draw_networkx_labels(g,pos,labels,font_size=12)
- #plt.axis('off')
- plt.savefig("/tmp/foo.png")
-
- return HttpResponse(open("/tmp/foo.png","r").read(), content_type="image/png")
-
-class ServiceGraphView(TemplateView):
- # this attempt just uses graphviz directly
- # yum -y install graphviz
- # pip-python install pygraphviz
-
- def get(self, request, name="root", *args, **kwargs):
- import pygraphviz as pgv
-
- g = pgv.AGraph(directed=True)
- g.graph_attr.update(size="8,4!")
- g.graph_attr.update(dpi="100")
- #g.graph_attr.update(nodesep="2.5")
- g.graph_attr.update(overlap="false")
- g.graph_attr.update(graphdir="TB")
-
- for service in Service.objects.all():
- provided_tenants = Tenant.objects.filter(provider_service=service, subscriber_service__isnull=False)
- subscribed_tenants = Tenant.objects.filter(subscriber_service=service, provider_service__isnull=False)
- if not (provided_tenants or subscribed_tenants):
- # nodes with no edges aren't interesting
- continue
- g.add_node(service.id, label=service.name)
-
- for tenant in Tenant.objects.all():
- if (not tenant.provider_service) or (not tenant.subscriber_service):
- continue
- g.add_edge(tenant.subscriber_service.id, tenant.provider_service.id)
-
- tf = tempfile.TemporaryFile()
- g.layout(prog="dot")
- g.draw(path=tf, format="png")
- tf.seek(0)
-
- return HttpResponse(tf.read(), content_type="image/png")
diff --git a/xos/core/views/site_privileges.py b/xos/core/views/site_privileges.py
deleted file mode 100644
index 90053e5..0000000
--- a/xos/core/views/site_privileges.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from core.serializers import SitePrivilegeSerializer
-from rest_framework import generics
-from core.models import SitePrivilege
-
-class SitePrivilegeList(generics.ListCreateAPIView):
- queryset = SitePrivilege.objects.all()
- serializer_class = SitePrivilegeSerializer
-
-class SitePrivilegeDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = SitePrivilege.objects.all()
- serializer_class = SitePrivilegeSerializer
-
-
diff --git a/xos/core/views/sites.py b/xos/core/views/sites.py
deleted file mode 100644
index 4ec9cb2..0000000
--- a/xos/core/views/sites.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from core.serializers import SiteSerializer
-from rest_framework import generics
-from core.models import Site
-
-class SiteList(generics.ListCreateAPIView):
- queryset = Site.objects.all()
- serializer_class = SiteSerializer
-
-class SiteDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = Site.objects.all()
- serializer_class = SiteSerializer
diff --git a/xos/core/views/slice_privileges.py b/xos/core/views/slice_privileges.py
deleted file mode 100644
index 4dd1f93..0000000
--- a/xos/core/views/slice_privileges.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from core.serializers import SlicePrivilegeSerializer
-from rest_framework import generics
-from core.models import SlicePrivilege
-
-class SlicePrivilegeList(generics.ListCreateAPIView):
- queryset = SlicePrivilege.objects.all()
- serializer_class = SlicePrivilegeSerializer
-
-class SlicePrivilegeDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = SlicePrivilege.objects.all()
- serializer_class = SlicePrivilegeSerializer
-
-
diff --git a/xos/core/views/slices.py b/xos/core/views/slices.py
deleted file mode 100644
index e3ab139..0000000
--- a/xos/core/views/slices.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from core.serializers import SliceSerializer
-from rest_framework import generics
-from core.models import Slice
-
-class SliceList(generics.ListCreateAPIView):
- queryset = Slice.objects.all()
- serializer_class = SliceSerializer
-
-class SliceDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = Slice.objects.all()
- serializer_class = SliceSerializer
-
-
diff --git a/xos/core/views/stats.py b/xos/core/views/stats.py
deleted file mode 100644
index f0cdd74..0000000
--- a/xos/core/views/stats.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from django.http import HttpResponse
-from monitor import driver
-from core.models import *
-import json
-
-def Stats(request):
- model = request.GET['model_name']
- pk = int(request.GET['pk'])
- meter = request.GET['meter']
- controller_name = request.GET['controller_name']
-
- controller = Controller.objects.filter(name=controller_name)
-
- if len(controller)==0:
- return HttpResponse(json.dumps({"stat_list": [], "error": "not found"}))
-
- controller=controller[0]
- keystone = {'username':controller.admin_user, 'password':controller.admin_password, 'tenant_name':controller.admin_tenant, 'auth_url':controller.auth_url, 'cacert':'/etc/ssl/certs/ca-certificates.crt'}
-
- for k,v in keystone.items():
- keystone['os_'+k] = v
-
- meters = driver.get_meter(meter, model, pk, keystone)
- return HttpResponse(json.dumps(meters))
diff --git a/xos/core/views/subnets.py b/xos/core/views/subnets.py
deleted file mode 100644
index 881f615..0000000
--- a/xos/core/views/subnets.py
+++ /dev/null
@@ -1,66 +0,0 @@
-from django.http import Http404
-from rest_framework.views import APIView
-from rest_framework.response import Response
-from rest_framework import status
-
-from core.api.subnets import add_subnet, delete_subnet, get_subnets, update_subnet
-from core.serializers import SubnetSerializer
-from util.request import parse_request
-
-
-class SubnetListCreate(APIView):
- """
- List all subnets or create a new subnet.
- """
-
- def post(self, request, format = None):
- data = parse_request(request.DATA)
- if 'auth' not in data:
- return Response(status=status.HTTP_400_BAD_REQUEST)
- elif 'subnet' in data:
- subnet = add_subnet(data['auth'], data['subnet'])
- serializer = SubnetSerializer(subnet)
- return Response(serializer.data, status=status.HTTP_201_CREATED)
- else:
- subnets = get_subnets(data['auth'])
- serializer = SubnetSerializer(subnets, many=True)
- return Response(serializer.data)
-
-
-class SubnetRetrieveUpdateDestroy(APIView):
- """
- Retrieve, update or delete a subnet
- """
-
- def post(self, request, pk, format=None):
- """Retrieve a subnet"""
- data = parse_request(request.DATA)
- if 'auth' not in data:
- return Response(status=status.HTTP_400_BAD_REQUEST)
- subnets = get_subnets(data['auth'], {'id': pk})
- if not subnets:
- return Response(status=status.HTTP_404_NOT_FOUND)
- serializer = SubnetSerializer(subnets[0])
- return Response(serializer.data)
-
- def put(self, request, pk, format=None):
- """update a subnet"""
- data = parse_request(request.DATA)
- if 'auth' not in data:
- return Response(status=status.HTTP_400_BAD_REQUEST)
- elif 'subnet' not in data:
- return Response(status=status.HTTP_400_BAD_REQUEST)
-
- subnet = update_subnet(pk, data['subnet'])
- serializer = SubnetSerializer(subnet)
- return Response(serializer.data)
-
- def delete(self, request, pk, format=None):
- data = parse_request(request.DATA)
- if 'auth' not in data:
- return Response(status=status.HTTP_400_BAD_REQUEST)
- delete_subnet(data['auth'], {'id': pk})
- return Response(status=status.HTTP_204_NO_CONTENT)
-
-
-
diff --git a/xos/core/views/tags.py b/xos/core/views/tags.py
deleted file mode 100644
index ba8a035..0000000
--- a/xos/core/views/tags.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from core.serializers import TagSerializer
-from rest_framework import generics
-from core.models import Tag
-
-class TagList(generics.ListCreateAPIView):
- queryset = Tag.objects.all()
- serializer_class = TagSerializer
-
-class TagDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = Tag.objects.all()
- serializer_class = TagSerializer
-
-
diff --git a/xos/core/views/users.py b/xos/core/views/users.py
deleted file mode 100644
index 06ac0f3..0000000
--- a/xos/core/views/users.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from core.serializers import UserSerializer
-from rest_framework import generics
-from core.models import User
-
-class UserList(generics.ListCreateAPIView):
- queryset = User.objects.all()
- serializer_class = UserSerializer
-
-class UserDetail(generics.RetrieveUpdateDestroyAPIView):
- queryset = User.objects.all()
- serializer_class = UserSerializer
diff --git a/xos/core/xoslib/dashboards/xosCeilometerDashboard.html b/xos/core/xoslib/dashboards/xosCeilometerDashboard.html
index 22511f4..82eeee8 100644
--- a/xos/core/xoslib/dashboards/xosCeilometerDashboard.html
+++ b/xos/core/xoslib/dashboards/xosCeilometerDashboard.html
@@ -5,7 +5,6 @@
<!-- inject:css -->
<link rel="stylesheet" href="/../../static/css/xosCeilometerDashboard.css">
<!-- endinject -->
-<link rel="stylesheet" href="css/ceilometerDashboard.css">
<div id="xosCeilometerDashboard">
<div ui-view ng-class="stateName"></div>
</div>
diff --git a/xos/core/xoslib/methods/ceilometerview.py b/xos/core/xoslib/methods/ceilometerview.py
index a65bd11..825cce4 100644
--- a/xos/core/xoslib/methods/ceilometerview.py
+++ b/xos/core/xoslib/methods/ceilometerview.py
@@ -10,14 +10,13 @@
from rest_framework import generics
from rest_framework.views import APIView
from core.models import *
-from ceilometer.models import *
+from services.ceilometer.models import *
from django.forms import widgets
from django.utils import datastructures
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
-from syndicate_storage.models import Volume
from django.core.exceptions import PermissionDenied
-from util.logger import observer_logger as logger
+from xos.logger import observer_logger as logger
# This REST API endpoint provides information that the ceilometer view needs to display
diff --git a/xos/core/xoslib/methods/cordsubscriber.py b/xos/core/xoslib/methods/cordsubscriber.py
index 3892014..49e32a5 100644
--- a/xos/core/xoslib/methods/cordsubscriber.py
+++ b/xos/core/xoslib/methods/cordsubscriber.py
@@ -9,7 +9,7 @@
from core.models import *
from django.forms import widgets
from django.conf.urls import patterns, url
-from cord.models import VOLTTenant, VBNGTenant, CordSubscriberRoot
+from services.cord.models import VOLTTenant, VBNGTenant, CordSubscriberRoot
from core.xoslib.objects.cordsubscriber import CordSubscriber
from plus import PlusSerializerMixin, XOSViewSet
from django.shortcuts import get_object_or_404
@@ -207,8 +207,8 @@
def list(self, request):
object_list = self.filter_queryset(self.get_queryset())
-
- serializer = self.get_serializer(object_list, many=True)
+
+ serializer = self.get_serializer(object_list, many=True)
return Response({"subscribers": serializer.data})
@@ -306,10 +306,10 @@
raise XOSMissingField("subscriber has no bbs_account")
result=subprocess.check_output(["python", "/opt/xos/observers/vcpe/broadbandshield.py", "dump", subscriber.volt.vcpe.bbs_account, "123"])
- if request.GET.get("theformat",None)=="text":
- from django.http import HttpResponse
- return HttpResponse(result, content_type="text/plain")
- else:
+ if request.GET.get("theformat",None)=="text":
+ from django.http import HttpResponse
+ return HttpResponse(result, content_type="text/plain")
+ else:
return Response( {"bbs_dump": result } )
def setup_demo_subscriber(self, subscriber):
@@ -392,15 +392,15 @@
# contact vBNG service and dump current list of mappings
def get_vbng_dump(self, request, pk=None):
result=subprocess.check_output(["curl", "http://10.0.3.136:8181/onos/virtualbng/privateip/map"])
- if request.GET.get("theformat",None)=="text":
- from django.http import HttpResponse
- result = json.loads(result)["map"]
-
- lines = []
- for row in result:
- for k in row.keys():
- lines.append( "%s %s" % (k, row[k]) )
-
- return HttpResponse("\n".join(lines), content_type="text/plain")
- else:
+ if request.GET.get("theformat",None)=="text":
+ from django.http import HttpResponse
+ result = json.loads(result)["map"]
+
+ lines = []
+ for row in result:
+ for k in row.keys():
+ lines.append( "%s %s" % (k, row[k]) )
+
+ return HttpResponse("\n".join(lines), content_type="text/plain")
+ else:
return Response( {"vbng_dump": json.loads(result)["map"] } )
diff --git a/xos/core/xoslib/methods/hpcview.py b/xos/core/xoslib/methods/hpcview.py
index 1118eda..199bc09 100644
--- a/xos/core/xoslib/methods/hpcview.py
+++ b/xos/core/xoslib/methods/hpcview.py
@@ -5,10 +5,9 @@
from rest_framework import generics
from rest_framework.views import APIView
from core.models import *
-from hpc.models import *
-from requestrouter.models import *
+from services.hpc.models import *
+from services.requestrouter.models import *
from django.forms import widgets
-from syndicate_storage.models import Volume
from django.core.exceptions import PermissionDenied
from django.contrib.contenttypes.models import ContentType
import json
diff --git a/xos/core/xoslib/methods/monitoringchannel.py b/xos/core/xoslib/methods/monitoringchannel.py
index baab346..66ca2ae 100644
--- a/xos/core/xoslib/methods/monitoringchannel.py
+++ b/xos/core/xoslib/methods/monitoringchannel.py
@@ -6,7 +6,7 @@
from rest_framework import status
from core.models import *
from django.forms import widgets
-from ceilometer.models import MonitoringChannel, CeilometerService
+from services.ceilometer.models import MonitoringChannel, CeilometerService
from plus import PlusSerializerMixin
from xos.apibase import XOSListCreateAPIView, XOSRetrieveUpdateDestroyAPIView, XOSPermissionDenied
diff --git a/xos/core/xoslib/methods/sshkeys.py b/xos/core/xoslib/methods/sshkeys.py
index 8413e65..6223540 100644
--- a/xos/core/xoslib/methods/sshkeys.py
+++ b/xos/core/xoslib/methods/sshkeys.py
@@ -6,7 +6,6 @@
from rest_framework.views import APIView
from core.models import *
from django.forms import widgets
-from syndicate_storage.models import Volume
from django.core.exceptions import PermissionDenied
from xos.exceptions import XOSNotFound
diff --git a/xos/core/xoslib/methods/tenantview.py b/xos/core/xoslib/methods/tenantview.py
index 6922c17..e505b1c 100644
--- a/xos/core/xoslib/methods/tenantview.py
+++ b/xos/core/xoslib/methods/tenantview.py
@@ -6,7 +6,7 @@
from rest_framework.views import APIView
from core.models import *
from django.forms import widgets
-from syndicate_storage.models import Volume
+from services.syndicate_storage.models import Volume
from django.core.exceptions import PermissionDenied
# This REST API endpoint contains a bunch of misc information that the
diff --git a/xos/core/xoslib/methods/volttenant.py b/xos/core/xoslib/methods/volttenant.py
index bf48290..3adb995 100644
--- a/xos/core/xoslib/methods/volttenant.py
+++ b/xos/core/xoslib/methods/volttenant.py
@@ -6,7 +6,7 @@
from rest_framework import status
from core.models import *
from django.forms import widgets
-from cord.models import VOLTTenant, VOLTService
+from services.cord.models import VOLTTenant, VOLTService
from plus import PlusSerializerMixin
from xos.apibase import XOSListCreateAPIView, XOSRetrieveUpdateDestroyAPIView, XOSPermissionDenied
diff --git a/xos/core/xoslib/ngXosViews/ceilometerDashboard/env/default.js b/xos/core/xoslib/ngXosViews/ceilometerDashboard/env/default.js
index 8fc0bd5..778faac 100644
--- a/xos/core/xoslib/ngXosViews/ceilometerDashboard/env/default.js
+++ b/xos/core/xoslib/ngXosViews/ceilometerDashboard/env/default.js
@@ -8,6 +8,6 @@
module.exports = {
host: 'http://clnode015.clemson.cloudlab.us:9999/',
- xoscsrftoken: 'w0qMPZCk8nByQh9Zy86nPs5OM5G5lKdb',
- xossessionid: 'kvv2aa1il6u4i7j6yu2399r4tdpdeoxz'
+ xoscsrftoken: 'gvAeNnr2DoQMorphFSxs4nXDSIDAT61Q',
+ xossessionid: 'qu69xzr4u5755w9hhuqa0djxacvi9k9i'
};
diff --git a/xos/core/xoslib/ngXosViews/ceilometerDashboard/src/css/ceilometerDashboard.css b/xos/core/xoslib/ngXosViews/ceilometerDashboard/src/css/ceilometerDashboard.css
index 879d7b4..4e6fa88 100644
--- a/xos/core/xoslib/ngXosViews/ceilometerDashboard/src/css/ceilometerDashboard.css
+++ b/xos/core/xoslib/ngXosViews/ceilometerDashboard/src/css/ceilometerDashboard.css
@@ -49,6 +49,7 @@
top: 0;
left: 0;
width: 100%;
+ margin-bottom: 50px;
}
/* LOADER */
@@ -121,8 +122,9 @@
[ui-view] {
position: absolute;
top: 0;
- bottom: 0;
+ left: 0;
width: 100%;
+ margin-bottom: 100px;
}
/* FROM DASHBOARD TO DETAIL */
diff --git a/xos/core/xoslib/ngXosViews/ceilometerDashboard/src/index.html b/xos/core/xoslib/ngXosViews/ceilometerDashboard/src/index.html
index bcd71a4..6363764 100644
--- a/xos/core/xoslib/ngXosViews/ceilometerDashboard/src/index.html
+++ b/xos/core/xoslib/ngXosViews/ceilometerDashboard/src/index.html
@@ -9,7 +9,6 @@
<link rel="stylesheet" href="/css/ceilometerDashboard.css">
<link rel="stylesheet" href="/css/dev.css">
<!-- endinject -->
-<link rel="stylesheet" href="css/ceilometerDashboard.css">
<div ng-app="xos.ceilometerDashboard" id="xosCeilometerDashboard">
<div ui-view ng-class="stateName"></div>
</div>
diff --git a/xos/core/xoslib/ngXosViews/ceilometerDashboard/src/templates/ceilometer-stats.tpl.html b/xos/core/xoslib/ngXosViews/ceilometerDashboard/src/templates/ceilometer-stats.tpl.html
index 1f5ff11..531f0cf 100644
--- a/xos/core/xoslib/ngXosViews/ceilometerDashboard/src/templates/ceilometer-stats.tpl.html
+++ b/xos/core/xoslib/ngXosViews/ceilometerDashboard/src/templates/ceilometer-stats.tpl.html
@@ -8,13 +8,42 @@
<table class="table" ng-if="vm.stats.length > 0">
<tr>
- <th>Type:</th>
- <th>Meter:</th>
- <th>Unit:</th>
- <th>Value:</th>
+ <th>
+ <a ng-click="order = 'category'">Type:</a>
+ </th>
+ <th>
+ <a ng-click="order = 'resource_name'">Resource:</a>
+ </th>
+ <th>
+ <a ng-click="order = 'meter'">Meter:</a>
+ </th>
+ <th>
+ Unit:
+ </th>
+ <th>
+ Value:
+ </th>
</tr>
- <tr ng-repeat="item in vm.stats">
+ <!-- <tr>
+ <td>
+ <input type="text" ng-model="query.category">
+ </td>
+ <td>
+ <input type="text" ng-model="query.resource_name">
+ </td>
+ <td>
+ <input type="text" ng-model="query.meter">
+ </td>
+ <td>
+ <input type="text" ng-model="query.unit">
+ </td>
+ <td>
+ <input type="text" ng-model="query.value">
+ </td>
+ </tr> -->
+ <tr ng-repeat="item in vm.stats | orderBy:order">
<td>{{item.category}}</td>
+ <td>{{item.resource_name}}</td>
<td>{{item.meter}}</td>
<td>{{item.unit}}</td>
<td>{{item.value}}</td>
diff --git a/xos/core/xoslib/objects/cordsubscriber.py b/xos/core/xoslib/objects/cordsubscriber.py
index 089c91b..d859cd2 100644
--- a/xos/core/xoslib/objects/cordsubscriber.py
+++ b/xos/core/xoslib/objects/cordsubscriber.py
@@ -1,5 +1,5 @@
from core.models import Slice, SlicePrivilege, SliceRole, Instance, Site, Node, User
-from cord.models import VOLTTenant, CordSubscriberRoot
+from services.cord.models import VOLTTenant, CordSubscriberRoot
from plus import PlusObjectMixin
from operator import itemgetter, attrgetter
from rest_framework.exceptions import APIException
@@ -10,9 +10,9 @@
sys.path.append("/opt/xos")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
import django
-from core.models import *
-from hpc.models import *
-from cord.models import *
+from core.models import *
+from services.hpc.models import *
+from services.cord.models import *
django.setup()
from core.xoslib.objects.cordsubscriber import CordSubscriber
c=CordSubscriber.get_tenant_objects().select_related().all()[0]
diff --git a/xos/core/xoslib/static/css/xosCeilometerDashboard.css b/xos/core/xoslib/static/css/xosCeilometerDashboard.css
index 8aad3b2..35773d8 100644
--- a/xos/core/xoslib/static/css/xosCeilometerDashboard.css
+++ b/xos/core/xoslib/static/css/xosCeilometerDashboard.css
@@ -1 +1 @@
-#xosCeilometerDashboard{position:relative}.panel{margin-top:10px}.panel-body:not(:first-child){border-top:1px solid #e3e3e3}.panel-body .row{margin-top:10px}.chart{width:100%;height:300px}.btn-chart,.btn-chart:hover{color:#fff}.side-container{position:relative}.service-list{margin-top:-10px}.service-list h3{margin-top:0;margin-bottom:0}.service-list a{text-decoration:none;color:#333}.meters,.stats{margin-top:25px;position:absolute;top:0;left:0;width:100%}.loader{font-size:10px;margin:150px auto;text-indent:-9999em;width:11em;height:11em;border-radius:50%;background:#fff;background:linear-gradient(to right,#fff 10%,rgba(255,255,255,0) 42%);position:relative;animation:load3 1.4s infinite linear;transform:translateZ(0)}.loader:before{width:50%;height:50%;background:#105e9e;border-radius:100% 0 0;position:absolute;top:0;left:0;content:''}.loader:after{background:#fff;width:75%;height:75%;border-radius:50%;content:'';margin:auto;position:absolute;top:0;left:0;bottom:0;right:0}@keyframes load3{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}[ui-view]{position:absolute;top:0;bottom:0;width:100%}[ui-view].ceilometerDashboard.ng-leave{animation:1s bounceOutLeft ease}[ui-view].samples.ng-enter{animation:1s bounceInRight ease}[ui-view].samples.ng-leave{animation:1s bounceOutRight ease}[ui-view].ceilometerDashboard.ng-enter{animation:1s bounceInLeft ease}.animate .animate-slide-left.ng-hide-remove{animation:.5s bounceInRight ease}.animate .animate-slide-left.ng-hide-add{animation:.5s bounceOutRight ease}@keyframes bounceInRight{from,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1.000)}from{opacity:0;transform:translate3d(3000px,0,0)}60%{opacity:1;transform:translate3d(-25px,0,0)}75%{transform:translate3d(10px,0,0)}90%{transform:translate3d(-5px,0,0)}to{transform:none}}@keyframes bounceInLeft{from,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1.000)}0%{opacity:0;transform:translate3d(-3000px,0,0)}60%{opacity:1;transform:translate3d(25px,0,0)}75%{transform:translate3d(-10px,0,0)}90%{transform:translate3d(5px,0,0)}to{transform:none}}@keyframes slideInUp{from{transform:translate3d(0,100%,0);visibility:visible}to{transform:translate3d(0,0,0)}}@keyframes bounceOutRight{20%{opacity:1;transform:translate3d(-20px,0,0)}to{opacity:0;transform:translate3d(2000px,0,0)}}@keyframes bounceOutLeft{20%{opacity:1;transform:translate3d(20px,0,0)}to{opacity:0;transform:translate3d(-2000px,0,0)}}@keyframes slideOutDown{from{transform:translate3d(0,0,0)}to{visibility:hidden;transform:translate3d(0,100%,0)}}
\ No newline at end of file
+#xosCeilometerDashboard{position:relative}.panel{margin-top:10px}.panel-body:not(:first-child){border-top:1px solid #e3e3e3}.panel-body .row{margin-top:10px}.chart{width:100%;height:300px}.btn-chart,.btn-chart:hover{color:#fff}.side-container{position:relative}.service-list{margin-top:-10px}.service-list h3{margin-top:0;margin-bottom:0}.service-list a{text-decoration:none;color:#333}.meters,.stats{margin-top:25px;position:absolute;top:0;left:0;width:100%}.loader{font-size:10px;margin:150px auto;text-indent:-9999em;width:11em;height:11em;border-radius:50%;background:#fff;background:linear-gradient(to right,#fff 10%,rgba(255,255,255,0) 42%);position:relative;animation:load3 1.4s infinite linear;transform:translateZ(0)}.loader:before{width:50%;height:50%;background:#105e9e;border-radius:100% 0 0;position:absolute;top:0;left:0;content:''}.loader:after{background:#fff;width:75%;height:75%;border-radius:50%;content:'';margin:auto;position:absolute;top:0;left:0;bottom:0;right:0}@keyframes load3{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}[ui-view]{position:absolute;top:0;left:0;width:100%;margin-bottom:100px}[ui-view].ceilometerDashboard.ng-leave{animation:1s bounceOutLeft ease}[ui-view].samples.ng-enter{animation:1s bounceInRight ease}[ui-view].samples.ng-leave{animation:1s bounceOutRight ease}[ui-view].ceilometerDashboard.ng-enter{animation:1s bounceInLeft ease}.animate .animate-slide-left.ng-hide-remove{animation:.5s bounceInRight ease}.animate .animate-slide-left.ng-hide-add{animation:.5s bounceOutRight ease}@keyframes bounceInRight{from,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1.000)}from{opacity:0;transform:translate3d(3000px,0,0)}60%{opacity:1;transform:translate3d(-25px,0,0)}75%{transform:translate3d(10px,0,0)}90%{transform:translate3d(-5px,0,0)}to{transform:none}}@keyframes bounceInLeft{from,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1.000)}0%{opacity:0;transform:translate3d(-3000px,0,0)}60%{opacity:1;transform:translate3d(25px,0,0)}75%{transform:translate3d(-10px,0,0)}90%{transform:translate3d(5px,0,0)}to{transform:none}}@keyframes slideInUp{from{transform:translate3d(0,100%,0);visibility:visible}to{transform:translate3d(0,0,0)}}@keyframes bounceOutRight{20%{opacity:1;transform:translate3d(-20px,0,0)}to{opacity:0;transform:translate3d(2000px,0,0)}}@keyframes bounceOutLeft{20%{opacity:1;transform:translate3d(20px,0,0)}to{opacity:0;transform:translate3d(-2000px,0,0)}}@keyframes slideOutDown{from{transform:translate3d(0,0,0)}to{visibility:hidden;transform:translate3d(0,100%,0)}}
\ No newline at end of file
diff --git a/xos/core/xoslib/static/js/xosCeilometerDashboard.js b/xos/core/xoslib/static/js/xosCeilometerDashboard.js
index 5aa7234..ebe0d50 100644
--- a/xos/core/xoslib/static/js/xosCeilometerDashboard.js
+++ b/xos/core/xoslib/static/js/xosCeilometerDashboard.js
@@ -1 +1 @@
-"use strict";angular.module("xos.ceilometerDashboard",["ngResource","ngCookies","ngLodash","ui.router","xos.helpers","ngAnimate","chart.js","ui.bootstrap.accordion"]).config(["$stateProvider","$urlRouterProvider",function(e,t){e.state("ceilometerDashboard",{url:"/",template:"<ceilometer-dashboard></ceilometer-dashboard>"}).state("samples",{url:"/:name/:tenant/samples",template:"<ceilometer-samples></ceilometer-samples>"}),t.otherwise("/")}]).config(["$httpProvider",function(e){e.interceptors.push("NoHyperlinks")}]).run(["$rootScope",function(e){e.stateName="ceilometerDashboard",e.$on("$stateChangeStart",function(t,s){e.stateName=s.name})}]).service("Ceilometer",["$http","$q","lodash",function(e,t,s){var n=this;this.resourceMap={},this.getMeters=function(){var r=t.defer();return e.get("/xoslib/meters/",{cache:!0}).then(function(e){var t=s.groupBy(e.data,"resource_id");n.resourceMap=s.reduce(Object.keys(t),function(e,s){return e[s]=t[s][0].resource_name,e},{}),r.resolve(e.data)})["catch"](function(e){r.reject(e)}),r.promise},this.getSamples=function(s,n){var r=t.defer();return e.get("/xoslib/metersamples/",{params:{meter:s,tenant:n}}).then(function(e){r.resolve(e.data)})["catch"](function(e){r.reject(e)}),r.promise},this.getStats=function(n){var r=t.defer();return e.get("/xoslib/meterstatistics/",{cache:!0}).then(function(e){r.resolve(s.filter(e.data,{slice:n}))})["catch"](function(e){r.reject(e)}),r.promise}}]).directive("ceilometerDashboard",["lodash",function(e){return{restrict:"E",scope:{},bindToController:!0,controllerAs:"vm",templateUrl:"templates/ceilometer-dashboard.tpl.html",controller:["Ceilometer",function(t){var s=this;this.loadMeters=function(){s.loader=!0,t.getMeters().then(function(t){s.projects=e.groupBy(t,"service"),e.forEach(Object.keys(s.projects),function(t){s.projects[t]=e.groupBy(s.projects[t],"slice"),e.forEach(Object.keys(s.projects[t]),function(n){s.projects[t][n]=e.groupBy(s.projects[t][n],"resource_name")})})})["catch"](function(e){s.error=e.data.detail})["finally"](function(){s.loader=!1})},this.loadMeters(),this.selectService=function(e){s.selectedResources=null,s.selectedResource=null,s.selectedMeters=null,s.selectedService=e},this.selectedResources=null,this.selectResources=function(e,t){s.selectedResources=null,s.selectedResource=null,s.selectedMeters=null,s.selectedResources=e,s.selectedSlice=t},this.selectedMeters=null,this.selectMeters=function(e,t){s.selectedMeters=e,s.selectedResource=t}}]}}]).directive("ceilometerSamples",["lodash","$stateParams",function(e,t){return{restrict:"E",scope:{name:"=name",tenant:"=tenant"},bindToController:!0,controllerAs:"vm",templateUrl:"templates/ceilometer-samples.tpl.html",controller:["Ceilometer",function(s){var n=this;if(this.chartColors=["#286090","#F7464A","#46BFBD","#FDB45C","#97BBCD","#4D5360","#8c4f9f"],this.chart={series:[],labels:[],data:[]},Chart.defaults.global.colours=this.chartColors,this.chartType="line",!t.name||!t.tenant)throw new Error("Missing Name and Tenant Params!");this.name=t.name,this.tenant=t.tenant,this.getLabels=function(e){return e.reduce(function(e,t){var s=new Date(t.timestamp);return e.push(s.getHours()+":"+((s.getMinutes()<10?"0":"")+s.getMinutes())+":"+s.getSeconds()),e},[])},this.getData=function(e){return e.reduce(function(e,t){return e.push(t.volume),e},[])},this.chartMeters=[],this.addMeterToChart=function(t){n.chart.labels=n.getLabels(e.sortBy(n.samplesList[t],"timestamp")),n.chart.series.push(t),n.chart.data.push(n.getData(e.sortBy(n.samplesList[t],"timestamp"))),n.chartMeters.push(n.samplesList[t][0]),e.remove(n.sampleLabels,{id:t})},this.removeFromChart=function(t){n.chart.data.splice(n.chart.series.indexOf(t.resource_id),1),n.chart.series.splice(n.chart.series.indexOf(t.resource_id),1),n.chartMeters.splice(e.findIndex(n.chartMeters,{resource_id:t.resource_id}),1),n.sampleLabels.push({id:t.resource_id,name:t.resource_name})},this.formatSamplesLabels=function(t){return e.uniq(t,"resource_id").reduce(function(e,t){return e.push({id:t.resource_id,name:t.resource_name}),e},[])},this.showSamples=function(){n.loader=!0,s.getSamples(n.name).then(function(t){n.samplesList=e.groupBy(t,"resource_id"),n.sampleLabels=n.formatSamplesLabels(t),n.addMeterToChart(n.tenant)})["catch"](function(e){n.error=e.data.detail})["finally"](function(){n.loader=!1})},this.showSamples()}]}}]).directive("ceilometerStats",function(){return{restrict:"E",scope:{name:"=name"},bindToController:!0,controllerAs:"vm",templateUrl:"templates/ceilometer-stats.tpl.html",controller:["$scope","Ceilometer",function(e,t){var s=this;this.getStats=function(){s.loader=!0,t.getStats(s.name).then(function(e){s.stats=e})["catch"](function(e){s.error=e.data})["finally"](function(){s.loader=!1})},this.getStats(),e.$watch(function(){return s.name},function(){s.getStats()})}]}}).filter("orderObjectByKey",["lodash",function(e){return function(t){return t?e.reduce(Object.keys(t).reverse(),function(e,s){return e[s]=t[s],e},{}):void 0}}]),angular.module("xos.ceilometerDashboard").run(["$templateCache",function(e){e.put("templates/accordion-group.html",'<div class="panel {{panelClass || \'panel-default\'}}">\n <div class="panel-heading" ng-keypress="toggleOpen($event)">\n <h3>\n <a href tabindex="0" class="accordion-toggle" ng-click="toggleOpen()" uib-accordion-transclude="heading"><span ng-class="{\'text-muted\': isDisabled}">{{heading}}</span></a>\n </h3>\n </div>\n <div class="panel-collapse collapse" uib-collapse="!isOpen">\n <div class="panel-body" ng-transclude></div>\n </div>\n</div>\n'),e.put("templates/accordion.html",'<div class="panel-group" ng-transclude></div>'),e.put("templates/ceilometer-dashboard.tpl.html",'<div class="row">\n <div class="col-sm-10">\n <h1>XOS Monitoring Statistics</h1>\n </div>\n <div class="col-xs-2 text-right">\n <a href="" class="btn btn-default" \n ng-show="vm.selectedResources && !vm.showStats"\n ng-click="vm.showStats = true">\n <i class="glyphicon glyphicon-transfer"></i>\n </a>\n <a href="" class="btn btn-default" \n ng-show="vm.selectedResources && vm.showStats"\n ng-click="vm.showStats = false">\n <i class="glyphicon glyphicon-transfer"></i>\n </a>\n </div>\n</div>\n\n<div class="row" ng-show="vm.loader">\n <div class="col-xs-12">\n <div class="loader">Loading</div>\n </div>\n</div>\n\n<section ng-hide="vm.loader" ng-class="{animate: !vm.loader}">\n <div class="row">\n <div class="col-sm-3 service-list">\n <h3>XOS Service: </h3>\n <uib-accordion close-others="true" template-url="templates/accordion.html">\n <uib-accordion-group\n ng-repeat="(service, slices) in vm.projects | orderObjectByKey"\n template-url="templates/accordion-group.html"\n heading="{{service}}">\n <h4>Slices:</h4>\n <a ng-repeat="(slice, resources) in slices" \n ng-class="{active: slice === vm.selectedSlice}"\n ng-click="vm.selectResources(resources, slice)"\n href="#" class="list-group-item" >\n {{slice}} <i class="glyphicon glyphicon-chevron-right pull-right"></i>\n </a>\n </uib-accordion-group>\n </uib-accordion>\n </div>\n <section class="side-container col-sm-9">\n <div class="row">\n <article ng-hide="!vm.showStats" class="stats animate-slide-left">\n <div class="col-xs-12">\n <div class="list-group">\n <div class="list-group-item">\n <h3>Stats</h3>\n </div>\n <div class="list-group-item">\n <ceilometer-stats ng-if="vm.selectedSlice" name="vm.selectedSlice"></ceilometer-stats>\n </div>\n </div>\n </div>\n </article>\n <article ng-hide="vm.showStats" class="meters animate-slide-left">\n <div class="col-sm-4 animate-slide-left" ng-hide="!vm.selectedResources">\n <div class="list-group">\n <div class="list-group-item">\n <h3>Resources</h3>\n </div>\n <a href="#" \n ng-click="vm.selectMeters(meters, resource)" \n class="list-group-item" \n ng-repeat="(resource, meters) in vm.selectedResources" \n ng-class="{active: resource === vm.selectedResource}">\n {{resource}} <i class="glyphicon glyphicon-chevron-right pull-right"></i>\n </a>\n </div>\n </div>\n <div class="col-sm-8 animate-slide-left" ng-hide="!vm.selectedMeters">\n <div class="list-group">\n <div class="list-group-item">\n <h3>Meters</h3>\n </div>\n <div class="list-group-item">\n <div class="row">\n <div class="col-xs-6">\n <label>Name:</label>\n </div>\n <div class="col-xs-3">\n <label>Unit:</label>\n </div>\n <div class="col-xs-3"></div>\n </div>\n <div class="row" ng-click="vm.selectMeters(meters)" ng-repeat="meter in vm.selectedMeters" style="margin-bottom: 10px;">\n <div class="col-xs-6">\n {{meter.name}}\n </div>\n <div class="col-xs-3">\n {{meter.unit}}\n </div>\n <div class="col-xs-3">\n <a ui-sref="samples({name: meter.name, tenant: meter.resource_id})" class="btn btn-primary">\n <i class="glyphicon glyphicon-search"></i>\n </a>\n </div>\n </div>\n </div>\n </div>\n </div>\n </article>\n </div>\n </section>\n </div>\n</section>\n<section ng-if="!vm.loader && vm.error">\n <div class="alert alert-danger">\n {{vm.error}}\n </div>\n</section>\n'),e.put("templates/ceilometer-samples.tpl.html",'<!-- <pre>{{ vm | json}}</pre> -->\n\n<div class="row">\n <div class="col-xs-10">\n <h1>{{vm.name | uppercase}}</h1>\n </div>\n <div class="col-xs-2">\n <a ui-sref="ceilometerDashboard" class="btn btn-primary pull-right">\n <i class="glyphicon glyphicon-arrow-left"></i> Back to list\n </a>\n </div>\n</div>\n<div class="row" ng-show="vm.loader">\n <div class="col-xs-12">\n <div class="loader">Loading</div>\n </div>\n</div>\n<section ng-if="!vm.loader && !vm.error">\n <div class="row">\n <form class="form-inline col-xs-8" ng-submit="vm.addMeterToChart(vm.addMeterValue)">\n <select ng-model="vm.addMeterValue" class="form-control" ng-options="resource.id as resource.name for resource in vm.sampleLabels"></select>\n <button class="btn btn-success"> \n <i class="glyphicon glyphicon-plus"></i> Add\n </button>\n </form>\n <div class="col-xs-4 text-right">\n <a ng-click="vm.chartType = \'line\'" class="btn" ng-class="{\'btn-default\': vm.chartType != \'bar\', \'btn-primary\': vm.chartType == \'line\'}">Lines</a>\n <a ng-click="vm.chartType = \'bar\'" class="btn" ng-class="{\'btn-default\': vm.chartType != \'line\', \'btn-primary\': vm.chartType == \'bar\'}">Bars</a>\n </div>\n </div>\n <div class="row" ng-if="!vm.loader">\n <div class="col-xs-12">\n <canvas ng-if="vm.chartType === \'line\'" id="line" class="chart chart-line" chart-data="vm.chart.data" chart-options="{datasetFill: false}"\n chart-labels="vm.chart.labels" chart-legend="false" chart-series="vm.chart.series">\n </canvas>\n <canvas ng-if="vm.chartType === \'bar\'" id="bar" class="chart chart-bar" chart-data="vm.chart.data"\n chart-labels="vm.chart.labels" chart-legend="false" chart-series="vm.chart.series">\n </canvas>\n <!-- <pre>{{vm.chartMeters | json}}</pre> -->\n </div>\n </div>\n <div class="row" ng-if="!vm.loader">\n <div class="col-xs-12">\n <a ng-click="vm.removeFromChart(meter)" class="btn btn-chart" ng-style="{\'background-color\': vm.chartColors[$index]}" ng-repeat="meter in vm.chartMeters">\n {{meter.resource_name}}\n </a>\n </div>\n </div>\n</section>\n<section ng-if="!vm.loader && vm.error">\n <div class="alert alert-danger">\n {{vm.error}}\n </div>\n</section>'),e.put("templates/ceilometer-stats.tpl.html",'<div ng-show="vm.loader" class="loader">Loading</div>\n\n<section ng-if="!vm.loader && !vm.error">\n\n <div class="alert alert-danger" ng-if="vm.stats.length == 0">\n No result\n </div> \n\n <table class="table" ng-if="vm.stats.length > 0">\n <tr>\n <th>Type:</th>\n <th>Meter:</th>\n <th>Unit:</th>\n <th>Value:</th>\n </tr>\n <tr ng-repeat="item in vm.stats">\n <td>{{item.type}}</td>\n <td>{{item.meter}}</td>\n <td>{{item.unit}}</td>\n <td>{{item.value}}</td>\n </tr>\n </table>\n</section>\n\n<section ng-if="!vm.loader && vm.error">\n <div class="alert alert-danger">\n {{vm.error}}\n </div>\n</section>\n')}]),angular.module("xos.ceilometerDashboard").run(["$location",function(e){e.path("/")}]),angular.bootstrap(angular.element("#xosCeilometerDashboard"),["xos.ceilometerDashboard"]);
\ No newline at end of file
+"use strict";angular.module("xos.ceilometerDashboard",["ngResource","ngCookies","ngLodash","ui.router","xos.helpers","ngAnimate","chart.js","ui.bootstrap.accordion"]).config(["$stateProvider","$urlRouterProvider",function(e,t){e.state("ceilometerDashboard",{url:"/",template:"<ceilometer-dashboard></ceilometer-dashboard>"}).state("samples",{url:"/:name/:tenant/samples",template:"<ceilometer-samples></ceilometer-samples>"}),t.otherwise("/")}]).config(["$httpProvider",function(e){e.interceptors.push("NoHyperlinks")}]).run(["$rootScope",function(e){e.stateName="ceilometerDashboard",e.$on("$stateChangeStart",function(t,s){e.stateName=s.name})}]).service("Ceilometer",["$http","$q","lodash",function(e,t,s){this.getMeters=function(){var s=t.defer();return e.get("/xoslib/meters/",{cache:!0}).then(function(e){s.resolve(e.data)})["catch"](function(e){s.reject(e)}),s.promise},this.getSamples=function(s,n){var r=t.defer();return e.get("/xoslib/metersamples/",{params:{meter:s,tenant:n}}).then(function(e){r.resolve(e.data)})["catch"](function(e){r.reject(e)}),r.promise},this.getStats=function(n){var r=t.defer();return e.get("/xoslib/meterstatistics/",{cache:!0}).then(function(e){r.resolve(s.filter(e.data,{slice:n}))})["catch"](function(e){r.reject(e)}),r.promise},this.selectedService=null,this.selectedSlice=null,this.selectedResource=null}]).directive("ceilometerDashboard",["lodash",function(e){return{restrict:"E",scope:{},bindToController:!0,controllerAs:"vm",templateUrl:"templates/ceilometer-dashboard.tpl.html",controller:["Ceilometer",function(t){var s=this;console.log(t.selectedService,t.selectedSlice,t.selectedResource),this.accordion={open:{}},this.openPanels=function(){t.selectedService&&(s.accordion.open[t.selectedService]=!0,t.selectedSlice&&(s.selectedSlice=t.selectedSlice,s.selectedResources=s.projects[t.selectedService][t.selectedSlice],t.selectedResource&&(s.selectedResource=t.selectedResource,s.selectedMeters=s.selectedResources[t.selectedResource])))},this.loadMeters=function(){s.loader=!0,t.getMeters().then(function(t){s.projects=e.groupBy(t,"service"),e.forEach(Object.keys(s.projects),function(t){s.projects[t]=e.groupBy(s.projects[t],"slice"),e.forEach(Object.keys(s.projects[t]),function(n){s.projects[t][n]=e.groupBy(s.projects[t][n],"resource_name")})}),s.openPanels()})["catch"](function(e){s.error=e.data.detail})["finally"](function(){s.loader=!1})},this.loadMeters(),this.selectedResources=null,this.selectResources=function(e,n,r){s.selectedResources=null,s.selectedResource=null,s.selectedMeters=null,s.selectedResources=e,s.selectedSlice=n,s.selectedService=r,t.selectedSlice=n,t.selectedService=r},this.selectedMeters=null,this.selectMeters=function(e,n){s.selectedMeters=e,t.selectedResource=n,s.selectedResource=n}}]}}]).directive("ceilometerSamples",["lodash","$stateParams",function(e,t){return{restrict:"E",scope:{name:"=name",tenant:"=tenant"},bindToController:!0,controllerAs:"vm",templateUrl:"templates/ceilometer-samples.tpl.html",controller:["Ceilometer",function(s){var n=this;if(this.chartColors=["#286090","#F7464A","#46BFBD","#FDB45C","#97BBCD","#4D5360","#8c4f9f"],this.chart={series:[],labels:[],data:[]},Chart.defaults.global.colours=this.chartColors,this.chartType="line",!t.name||!t.tenant)throw new Error("Missing Name and Tenant Params!");this.name=t.name,this.tenant=t.tenant,this.getLabels=function(e){return e.reduce(function(e,t){var s=new Date(t.timestamp);return e.push(s.getHours()+":"+((s.getMinutes()<10?"0":"")+s.getMinutes())+":"+s.getSeconds()),e},[])},this.getData=function(e){return e.reduce(function(e,t){return e.push(t.volume),e},[])},this.chartMeters=[],this.addMeterToChart=function(t){n.chart.labels=n.getLabels(e.sortBy(n.samplesList[t],"timestamp")),n.chart.series.push(t),n.chart.data.push(n.getData(e.sortBy(n.samplesList[t],"timestamp"))),n.chartMeters.push(n.samplesList[t][0]),e.remove(n.sampleLabels,{id:t})},this.removeFromChart=function(t){n.chart.data.splice(n.chart.series.indexOf(t.project_id),1),n.chart.series.splice(n.chart.series.indexOf(t.project_id),1),n.chartMeters.splice(e.findIndex(n.chartMeters,{project_id:t.project_id}),1),n.sampleLabels.push({id:t.project_id,name:t.resource_name||t.project_id})},this.formatSamplesLabels=function(t){return e.uniq(t,"project_id").reduce(function(e,t){return e.push({id:t.project_id,name:t.resource_name||t.project_id}),e},[])},this.showSamples=function(){n.loader=!0,s.getSamples(n.name).then(function(t){n.samplesList=e.groupBy(t,"project_id"),n.sampleLabels=n.formatSamplesLabels(t),n.addMeterToChart(n.tenant)})["catch"](function(e){n.error=e.data.detail})["finally"](function(){n.loader=!1})},this.showSamples()}]}}]).directive("ceilometerStats",function(){return{restrict:"E",scope:{name:"=name"},bindToController:!0,controllerAs:"vm",templateUrl:"templates/ceilometer-stats.tpl.html",controller:["$scope","Ceilometer",function(e,t){var s=this;this.getStats=function(){s.loader=!0,t.getStats(s.name).then(function(e){s.stats=e})["catch"](function(e){s.error=e.data})["finally"](function(){s.loader=!1})},this.getStats(),e.$watch(function(){return s.name},function(){s.getStats()})}]}}).filter("orderObjectByKey",["lodash",function(e){return function(t){return t?e.reduce(Object.keys(t).reverse(),function(e,s){return e[s]=t[s],e},{}):void 0}}]),angular.module("xos.ceilometerDashboard").run(["$templateCache",function(e){e.put("templates/accordion-group.html",'<div class="panel {{panelClass || \'panel-default\'}}">\n <div class="panel-heading" ng-keypress="toggleOpen($event)">\n <h3>\n <a href tabindex="0" class="accordion-toggle" ng-click="toggleOpen()" uib-accordion-transclude="heading"><span ng-class="{\'text-muted\': isDisabled}">{{heading}}</span></a>\n </h3>\n </div>\n <div class="panel-collapse collapse" uib-collapse="!isOpen">\n <div class="panel-body" ng-transclude></div>\n </div>\n</div>\n'),e.put("templates/accordion.html",'<div class="panel-group" ng-transclude></div>'),e.put("templates/ceilometer-dashboard.tpl.html",'<div class="row">\n <div class="col-sm-10">\n <h1>XOS Monitoring Statistics</h1>\n </div>\n <div class="col-xs-2 text-right">\n <a href="" class="btn btn-default" \n ng-show="vm.selectedResources && !vm.showStats"\n ng-click="vm.showStats = true">\n <i class="glyphicon glyphicon-transfer"></i>\n </a>\n <a href="" class="btn btn-default" \n ng-show="vm.selectedResources && vm.showStats"\n ng-click="vm.showStats = false">\n <i class="glyphicon glyphicon-transfer"></i>\n </a>\n </div>\n</div>\n\n<div class="row" ng-show="vm.loader">\n <div class="col-xs-12">\n <div class="loader">Loading</div>\n </div>\n</div>\n\n<section ng-hide="vm.loader" ng-class="{animate: !vm.loader}">\n <div class="row">\n <div class="col-sm-3 service-list">\n <h3>XOS Service: </h3>\n <uib-accordion close-others="true" template-url="templates/accordion.html">\n <uib-accordion-group\n ng-repeat="(service, slices) in vm.projects | orderObjectByKey"\n template-url="templates/accordion-group.html"\n is-open="vm.accordion.open[service]"\n heading="{{service}}">\n <h4>Slices:</h4>\n <a ng-repeat="(slice, resources) in slices" \n ng-class="{active: slice === vm.selectedSlice}"\n ng-click="vm.selectResources(resources, slice, service)"\n href="#" class="list-group-item" >\n {{slice}} <i class="glyphicon glyphicon-chevron-right pull-right"></i>\n </a>\n </uib-accordion-group>\n </uib-accordion>\n </div>\n <section class="side-container col-sm-9">\n <div class="row">\n <article ng-hide="!vm.showStats" class="stats animate-slide-left">\n <div class="col-xs-12">\n <div class="list-group">\n <div class="list-group-item">\n <h3>Stats</h3>\n </div>\n <div class="list-group-item">\n <ceilometer-stats ng-if="vm.selectedSlice" name="vm.selectedSlice"></ceilometer-stats>\n </div>\n </div>\n </div>\n </article>\n <article ng-hide="vm.showStats" class="meters animate-slide-left">\n <div class="col-sm-4 animate-slide-left" ng-hide="!vm.selectedResources">\n <div class="list-group">\n <div class="list-group-item">\n <h3>Resources</h3>\n </div>\n <a href="#" \n ng-click="vm.selectMeters(meters, resource)" \n class="list-group-item" \n ng-repeat="(resource, meters) in vm.selectedResources" \n ng-class="{active: resource === vm.selectedResource}">\n {{resource}} <i class="glyphicon glyphicon-chevron-right pull-right"></i>\n </a>\n </div>\n </div>\n <div class="col-sm-8 animate-slide-left" ng-hide="!vm.selectedMeters">\n <div class="list-group">\n <div class="list-group-item">\n <h3>Meters</h3>\n </div>\n <div class="list-group-item">\n <div class="row">\n <div class="col-xs-6">\n <label>Name:</label>\n </div>\n <div class="col-xs-3">\n <label>Unit:</label>\n </div>\n <div class="col-xs-3"></div>\n </div>\n <div class="row" ng-repeat="meter in vm.selectedMeters" style="margin-bottom: 10px;">\n <div class="col-xs-6">\n {{meter.name}}\n </div>\n <div class="col-xs-3">\n {{meter.unit}}\n </div>\n <div class="col-xs-3">\n <a ui-sref="samples({name: meter.name, tenant: meter.project_id})" class="btn btn-primary">\n <i class="glyphicon glyphicon-search"></i>\n </a>\n </div>\n </div>\n </div>\n </div>\n </div>\n </article>\n </div>\n </section>\n </div>\n</section>\n<section ng-if="!vm.loader && vm.error">\n <div class="alert alert-danger">\n {{vm.error}}\n </div>\n</section>\n'),e.put("templates/ceilometer-samples.tpl.html",'<!-- <pre>{{ vm | json}}</pre> -->\n\n<div class="row">\n <div class="col-xs-10">\n <h1>{{vm.name | uppercase}}</h1>\n </div>\n <div class="col-xs-2">\n <a ui-sref="ceilometerDashboard" class="btn btn-primary pull-right">\n <i class="glyphicon glyphicon-arrow-left"></i> Back to list\n </a>\n </div>\n</div>\n<div class="row" ng-show="vm.loader">\n <div class="col-xs-12">\n <div class="loader">Loading</div>\n </div>\n</div>\n<section ng-if="!vm.loader && !vm.error">\n <div class="row">\n <form class="form-inline col-xs-8" ng-submit="vm.addMeterToChart(vm.addMeterValue)">\n <select ng-model="vm.addMeterValue" class="form-control" ng-options="resource.id as resource.name for resource in vm.sampleLabels"></select>\n <button class="btn btn-success"> \n <i class="glyphicon glyphicon-plus"></i> Add\n </button>\n </form>\n <div class="col-xs-4 text-right">\n <a ng-click="vm.chartType = \'line\'" class="btn" ng-class="{\'btn-default\': vm.chartType != \'bar\', \'btn-primary\': vm.chartType == \'line\'}">Lines</a>\n <a ng-click="vm.chartType = \'bar\'" class="btn" ng-class="{\'btn-default\': vm.chartType != \'line\', \'btn-primary\': vm.chartType == \'bar\'}">Bars</a>\n </div>\n </div>\n <div class="row" ng-if="!vm.loader">\n <div class="col-xs-12">\n <canvas ng-if="vm.chartType === \'line\'" id="line" class="chart chart-line" chart-data="vm.chart.data" chart-options="{datasetFill: false}"\n chart-labels="vm.chart.labels" chart-legend="false" chart-series="vm.chart.series">\n </canvas>\n <canvas ng-if="vm.chartType === \'bar\'" id="bar" class="chart chart-bar" chart-data="vm.chart.data"\n chart-labels="vm.chart.labels" chart-legend="false" chart-series="vm.chart.series">\n </canvas>\n <!-- <pre>{{vm.chartMeters | json}}</pre> -->\n </div>\n </div>\n <div class="row" ng-if="!vm.loader">\n <div class="col-xs-12">\n <a ng-click="vm.removeFromChart(meter)" class="btn btn-chart" ng-style="{\'background-color\': vm.chartColors[$index]}" ng-repeat="meter in vm.chartMeters">\n {{meter.resource_name || meter.resource_id}}\n </a>\n </div>\n </div>\n</section>\n<section ng-if="!vm.loader && vm.error">\n <div class="alert alert-danger">\n {{vm.error}}\n </div>\n</section>'),e.put("templates/ceilometer-stats.tpl.html",'<div ng-show="vm.loader" class="loader">Loading</div>\n\n<section ng-if="!vm.loader && !vm.error">\n\n <div class="alert alert-danger" ng-if="vm.stats.length == 0">\n No result\n </div> \n\n <table class="table" ng-if="vm.stats.length > 0">\n <tr>\n <th>\n <a ng-click="order = \'category\'">Type:</a>\n </th>\n <th>\n <a ng-click="order = \'resource_name\'">Resource:</a>\n </th>\n <th>\n <a ng-click="order = \'meter\'">Meter:</a>\n </th>\n <th>\n Unit:\n </th>\n <th>\n Value:\n </th>\n </tr>\n <!-- <tr>\n <td>\n <input type="text" ng-model="query.category">\n </td>\n <td>\n <input type="text" ng-model="query.resource_name">\n </td>\n <td>\n <input type="text" ng-model="query.meter">\n </td>\n <td>\n <input type="text" ng-model="query.unit">\n </td>\n <td>\n <input type="text" ng-model="query.value">\n </td>\n </tr> -->\n <tr ng-repeat="item in vm.stats | orderBy:order">\n <td>{{item.category}}</td>\n <td>{{item.resource_name}}</td>\n <td>{{item.meter}}</td>\n <td>{{item.unit}}</td>\n <td>{{item.value}}</td>\n </tr>\n </table>\n</section>\n\n<section ng-if="!vm.loader && vm.error">\n <div class="alert alert-danger">\n {{vm.error}}\n </div>\n</section>\n')}]),angular.module("xos.ceilometerDashboard").run(["$location",function(e){e.path("/")}]),angular.bootstrap(angular.element("#xosCeilometerDashboard"),["xos.ceilometerDashboard"]);
\ No newline at end of file
diff --git a/xos/dependency_walker.py b/xos/dependency_walker.py
deleted file mode 100644
index d99b783..0000000
--- a/xos/dependency_walker.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import imp
-from xos.config import Config, XOS_DIR
-import inspect
-import time
-import traceback
-import commands
-import threading
-import json
-import pdb
-from core.models import *
-
-from util.logger import Logger, logging
-logger = Logger(level=logging.INFO)
-
-missing_links={}
-
-try:
- dep_data = open(Config().dependency_graph).read()
-except:
- dep_data = open(XOS_DIR + '/model-deps').read()
-
-dependencies = json.loads(dep_data)
-
-inv_dependencies = {}
-for k, lst in dependencies.items():
- for v in lst:
- try:
- inv_dependencies[v].append(k)
- except KeyError:
- inv_dependencies[v]=[k]
-
-
-def plural(name):
- if (name.endswith('s')):
- return name+'es'
- else:
- return name+'s'
-
-
-def walk_deps(fn, object):
- model = object.__class__.__name__
- try:
- deps = dependencies[model]
- except:
- deps = []
- return __walk_deps(fn, object, deps)
-
-def walk_inv_deps(fn, object):
- model = object.__class__.__name__
- try:
- deps = inv_dependencies[model]
- except:
- deps = []
- return __walk_deps(fn, object, deps)
-
-def __walk_deps(fn, object, deps):
- model = object.__class__.__name__
- ret = []
- for dep in deps:
- #print "Checking dep %s"%dep
- peer=None
- link = dep.lower()
- try:
- peer = getattr(object, link)
- except AttributeError:
- link = plural(link)
- try:
- peer = getattr(object, link)
- except AttributeError:
- if not missing_links.has_key(model+'.'+link):
- print "Model %s missing link for dependency %s"%(model, link)
- logger.log_exc("WARNING: Model %s missing link for dependency %s."%(model, link))
- missing_links[model+'.'+link]=True
-
-
- if (peer):
- try:
- peer_objects = peer.all()
- except AttributeError:
- peer_objects = [peer]
- except:
- peer_objects = []
-
- for o in peer_objects:
- #if (isinstance(o,PlCoreBase)):
- if (hasattr(o,'updated')):
- fn(o, object)
- ret.append(o)
- # Uncomment the following line to enable recursion
- # walk_inv_deps(fn, o)
- return ret
-
-def p(x,source):
- print x,x.__class__.__name__
- return
-
-def main():
- #pdb.set_trace()
- s = Slice.objects.filter(name='princeton_sapan62')
- #pdb.set_trace()
- print walk_inv_deps(p,s[0])
-
-if __name__=='__main__':
- main()
diff --git a/xos/deployment_auth.py b/xos/deployment_auth.py
deleted file mode 100644
index f7383ea..0000000
--- a/xos/deployment_auth.py
+++ /dev/null
@@ -1,25 +0,0 @@
-##
-# This file contains the auth credentials used to access openstack deployments
-# we wish to manage. The 'default' credentials will be used for any deployments
-# not specifed here.
-#
-
-deployment_auth = {
-# Example
-# 'deployment_name': {
-# 'user': 'email@domain.com',
-# 'pasword': 'password',
-# 'tenant': 'tenant',
-# 'url': 'http://localhost:5000/v2.0/',
-# 'token': 'ADMIN',
-# 'endpoint': 'http://localhost:35357/v2.0/'
-# },
-
- 'default': {
- 'user': 'admin@domain.com',
- 'password': 'admin',
- 'tenant': 'admin',
- 'url': 'http://localhost:5000/v2.0/'
- },
-
-}
diff --git a/xos/dmdot b/xos/dmdot
deleted file mode 100755
index f438aad..0000000
--- a/xos/dmdot
+++ /dev/null
@@ -1,98 +0,0 @@
-#!/usr/bin/python
-
-import os
-import pdb
-import sys
-import json
-
-sys.path.append('.')
-
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-
-from django.db.models.fields.related import ForeignKey
-
-# defaults
-apps = ["core", "hpc", "cord", "requestrouter", "services.onos"]
-output = "-json"
-
-# syntax: dmdot [-json | -dot] [app_name]
-
-# poor man's argument parser
-for arg in sys.argv[1:]:
- if arg.startswith("-"):
- output = arg
- else:
- apps+= [arg]
-
-model_classes = []
-class_names = []
-lower_class_names = {}
-synonyms = {
- 'user':'creator'
-}
-
-for app in apps:
- app = app + ".models"
- #models_module = imp.load_source(app, ".")
- models_module = __import__(app)
- for part in app.split(".")[1:]:
- if hasattr(models_module, "PlCoreBase"):
- break
- models_module = getattr(models_module,part)
-
- PlCoreBase = getattr(models_module,"PlCoreBase")
-
- for classname in dir(models_module):
- c = getattr(models_module, classname, None)
- if type(c)==type(PlCoreBase):
- model_classes.append(c)
- class_names.append(c.__name__)
- lower_class_names[c.__name__.lower()] = c
- try:
- synonym = synonyms[c.__name__.lower()]
- lower_class_names[synonym] = c
- except:
- pass
-
-
-# django doesn't use the correct case in field.name.title() for objects that
-# have CamelCased class names. So, compare everything in lower case.
-
-if (output=='-dot'):
- print "digraph plstack {";
- for c in model_classes:
- fields = c._meta.fields
-
- for f in fields:
- if type(f)==ForeignKey and f.name.lower().split('_') in lower_class_names:
- linked_class = lower_class_names[f.name.lower()]
- if ('backref' in f.name):
- print '\t"%s"->"%s";'%(linked_class.__name__,c.__name__)
- else:
- print '\t"%s"->"%s";'%(c.__name__,linked_class.__name__)
- print "}\n";
-elif (output=='-json'):
- d = {}
- for c in model_classes:
- fields = c._meta.fields
-
- for f in fields:
- field_type = f.name.lower().split('_')[0]
- if type(f)==ForeignKey and field_type in lower_class_names:
- linked_class = lower_class_names[field_type]
- if ('backref' in f.name.lower()):
- a = linked_class.__name__
- b = c.__name__
- else:
- b = linked_class.__name__
- a = c.__name__
-
- try:
- if (b not in d[a]):
- d[a].append(b)
- except KeyError:
- d[c.__name__]=[linked_class.__name__]
- #d['ControllerNetwork'].append('SliceDeployments')
- print json.dumps(d,indent=4)
-
-
diff --git a/xos/ec2_observer/backend.py b/xos/ec2_observer/backend.py
deleted file mode 100644
index 1a2545d..0000000
--- a/xos/ec2_observer/backend.py
+++ /dev/null
@@ -1,22 +0,0 @@
-import threading
-import time
-from ec2_observer.event_loop import XOSObserver
-from ec2_observer.event_manager import EventListener
-from util.logger import Logger, logging
-
-logger = Logger(level=logging.INFO)
-
-class Backend:
-
- def run(self):
- # start the openstack observer
- observer = XOSObserver()
- observer_thread = threading.Thread(target=observer.run)
- observer_thread.start()
-
- # start event listene
- event_manager = EventListener(wake_up=observer.wake_up)
- event_manager_thread = threading.Thread(target=event_manager.run)
- event_manager_thread.start()
- logger.log_exc("Exception in child thread")
-
diff --git a/xos/ec2_observer/deleters/instance_deleter.py b/xos/ec2_observer/deleters/instance_deleter.py
deleted file mode 100644
index 60f9e47..0000000
--- a/xos/ec2_observer/deleters/instance_deleter.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from core.models import Instance, SliceDeployments
-from observer.deleter import Deleter
-
-class InstanceDeleter(Deleter):
- model='Instance'
-
- def call(self, pk):
- instance = Instance.objects.get(pk=pk)
- if instance.instance_id:
- driver = self.driver.client_driver(caller=instance.creator,
- tenant=instance.slice.name,
- deployment=instance.deploymentNetwork.name)
- driver.destroy_instance(instance.instance_id)
- instance.delete()
diff --git a/xos/ec2_observer/deleters/network_deleter.py b/xos/ec2_observer/deleters/network_deleter.py
deleted file mode 100644
index 0d21fda..0000000
--- a/xos/ec2_observer/deleters/network_deleter.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from core.models import Network, NetworkDeployments
-from observer.deleter import Deleter
-from observer.deleters.network_deployment_deleter import NetworkDeploymentDeleter
-from util.logger import Logger, logging
-
-logger = Logger(level=logging.INFO)
-
-class NetworkDeleter(Deleter):
- model='Network'
-
- def call(self, pk):
- network = Network.objects.get(pk=pk)
- network_deployment_deleter = NetworkDeploymentDeleter()
- for network_deployment in NetworkDeployments.objects.filter(network=network):
- try:
- network_deployment_deleter(network_deployment.id)
- except:
- logger.log_exc("Failed to delte network deployment %s" % network_deployment)
- network.delete()
diff --git a/xos/ec2_observer/deleters/network_deployment_deleter.py b/xos/ec2_observer/deleters/network_deployment_deleter.py
deleted file mode 100644
index 72b10b2..0000000
--- a/xos/ec2_observer/deleters/network_deployment_deleter.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from core.models import Network, NetworkDeployments
-from observer.deleter import Deleter
-from openstack.driver import OpenStackDriver
-
-class NetworkDeploymentDeleter(Deleter):
- model='NetworkDeployment'
-
- def call(self, pk):
- network_deployment = NetworkDeployments.objects.get(pk=pk)
- driver = OpenStackDriver().client_driver(caller=network_deployment.network.owner.creator,
- tenant=network_deployment.network.owner.name,
- deployment=network_deployment.deployment.name)
- if (network_deployment.router_id) and (network_deployment.subnet_id):
- driver.delete_router_interface(network_deployment.router_id, network_deployment.subnet_id)
- if network_deployment.subnet_id:
- driver.delete_subnet(network_deployment.subnet_id)
- if network_deployment.router_id:
- driver.delete_router(network_deployment.router_id)
- if network_deployment.net_id:
- driver.delete_network(network_deployment.net_id)
- network_deployment.delete()
diff --git a/xos/ec2_observer/deleters/network_instance_deleter.py b/xos/ec2_observer/deleters/network_instance_deleter.py
deleted file mode 100644
index 8a8f516..0000000
--- a/xos/ec2_observer/deleters/network_instance_deleter.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from core.models import NetworkInstance
-from observer.deleter import Deleter
-
-class NetworkInstanceDeleter(Deleter):
- model='NetworkInstance'
-
- def call(self, pk):
- network_instance = NetworkInstances.objects.get(pk=pk)
- # handle openstack delete
-
- network_instance.delete()
-
-
diff --git a/xos/ec2_observer/deleters/site_deleter.py b/xos/ec2_observer/deleters/site_deleter.py
deleted file mode 100644
index 88a4008..0000000
--- a/xos/ec2_observer/deleters/site_deleter.py
+++ /dev/null
@@ -1,14 +0,0 @@
-from core.models import Site, SiteDeployment
-from observer.deleter import Deleter
-from observer.deleters.site_deployment_deleter import SiteDeploymentDeleter
-
-class SiteDeleter(Deleter):
- model='Site'
-
- def call(self, pk):
- site = Site.objects.get(pk=pk)
- site_deployments = SiteDeployment.objects.filter(site=site)
- site_deployment_deleter = SiteDeploymentDeleter()
- for site_deployment in site_deployments:
- site_deployment_deleter(site_deployment.id)
- site.delete()
diff --git a/xos/ec2_observer/deleters/site_deployment_deleter.py b/xos/ec2_observer/deleters/site_deployment_deleter.py
deleted file mode 100644
index db344cd..0000000
--- a/xos/ec2_observer/deleters/site_deployment_deleter.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from core.models import Site, SiteDeployment
-from observer.deleter import Deleter
-
-class SiteDeploymentDeleter(Deleter):
- model='SiteDeployment'
-
- def call(self, pk):
- site_deployment = SiteDeployment.objects.get(pk=pk)
- if site_deployment.tenant_id:
- driver = self.driver.admin_driver(deployment=site_deployment.deployment.name)
- driver.delete_tenant(site_deployment.tenant_id)
- site_deployment.delete()
diff --git a/xos/ec2_observer/deleters/slice_deleter.py b/xos/ec2_observer/deleters/slice_deleter.py
deleted file mode 100644
index 7e9dfd4..0000000
--- a/xos/ec2_observer/deleters/slice_deleter.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from core.models import Slice, SliceDeployments, User
-from observer.deleter import Deleter
-from observer.deleters.slice_deployment_deleter import SliceDeploymentsDeleter
-from util.logger import Logger, logging
-
-logger = Logger(level=logging.INFO)
-
-class SliceDeleter(Deleter):
- model='Slice'
-
- def call(self, pk):
- slice = Slice.objects.get(pk=pk)
- slice_deployment_deleter = SliceDeploymentsDeleter()
- for slice_deployment in SliceDeployments.objects.filter(slice=slice):
- try:
- slice_deployment_deleter(slice_deployment.id)
- except:
- logger.log_exc("Failed to delete slice_deployment %s" % slice_deployment)
- slice.delete()
diff --git a/xos/ec2_observer/deleters/slice_deployment_deleter.py b/xos/ec2_observer/deleters/slice_deployment_deleter.py
deleted file mode 100644
index 6f1aec0..0000000
--- a/xos/ec2_observer/deleters/slice_deployment_deleter.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from core.models import Slice, SliceDeployments, User
-from observer.deleter import Deleter
-from openstack.driver import OpenStackDriver
-
-class SliceDeploymentsDeleter(Deleter):
- model='SliceDeployments'
-
- def call(self, pk):
- slice_deployment = SliceDeployments.objects.get(pk=pk)
- user = User.objects.get(id=slice_deployment.slice.creator.id)
- driver = OpenStackDriver().admin_driver(deployment=slice_deployment.deployment.name)
- client_driver = driver.client_driver(caller=user,
- tenant=slice_deployment.slice.name,
- deployment=slice_deployment.deployment.name)
-
- if slice_deployment.router_id and slice_deployment.subnet_id:
- client_driver.delete_router_interface(slice_deployment.router_id, slice_deployment.subnet_id)
- if slice_deployment.subnet_id:
- client_driver.delete_subnet(slice_deployment.subnet_id)
- if slice_deployment.router_id:
- client_driver.delete_router(slice_deployment.router_id)
- if slice_deployment.network_id:
- client_driver.delete_network(slice_deployment.network_id)
- if slice_deployment.tenant_id:
- driver.delete_tenant(slice_deployment.tenant_id)
- # delete external route
- #subnet = None
- #subnets = client_driver.shell.quantum.list_subnets()['subnets']
- #for snet in subnets:
- # if snet['id'] == slice_deployment.subnet_id:
- # subnet = snet
- #if subnet:
- # driver.delete_external_route(subnet)
- slice_deployment.delete()
diff --git a/xos/ec2_observer/deleters/user_deleter.py b/xos/ec2_observer/deleters/user_deleter.py
deleted file mode 100644
index 3930eb0..0000000
--- a/xos/ec2_observer/deleters/user_deleter.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from core.models import User, UserDeployments
-from observer.deleter import Deleter
-from observer.deleters.user_deployment_deleter import UserDeploymentsDeleter
-
-class UserDeleter(Deleter):
- model='User'
-
- def call(self, pk):
- user = User.objects.get(pk=pk)
- user_deployment_deleter = UserDeploymentsDeleter()
- for user_deployment in UserDeployments.objects.filter(user=user):
- user_deployment_deleter(user_deployment.id)
- user.delete()
diff --git a/xos/ec2_observer/deleters/user_deployment_deleter.py b/xos/ec2_observer/deleters/user_deployment_deleter.py
deleted file mode 100644
index 4bc7619..0000000
--- a/xos/ec2_observer/deleters/user_deployment_deleter.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from core.models import User, UserDeployments
-from observer.deleter import Deleter
-
-class UserDeploymentsDeleter(Deleter):
- model='UserDeployments'
-
- def call(self, pk):
- user_deployment = UserDeployments.objects.get(pk=pk)
- if user_deployment.user.kuser_id:
- driver = self.driver.admin_driver(deployment=user_deployment.deployment.name)
- driver.delete_user(user_deployment.user.kuser_id)
- user_deployment.delete()
diff --git a/xos/ec2_observer/ec2_backend.py b/xos/ec2_observer/ec2_backend.py
deleted file mode 100644
index a26ddfd..0000000
--- a/xos/ec2_observer/ec2_backend.py
+++ /dev/null
@@ -1,24 +0,0 @@
-import threading
-import time
-from ec2_observer.event_loop import XOSObserver
-from ec2_observer.event_manager import EventListener
-from util.logger import Logger, logging
-
-logger = Logger(level=logging.INFO)
-
-class Backend:
-
- def run(self):
- try:
- # start the openstack observer
- observer = XOSObserver()
- observer_thread = threading.Thread(target=observer.run)
- observer_thread.start()
-
- # start event listene
- event_manager = EventListener(wake_up=observer.wake_up)
- event_manager_thread = threading.Thread(target=event_manager.run)
- event_manager_thread.start()
- except:
- logger.log_exc("Exception in child thread")
-
diff --git a/xos/ec2_observer/error_mapper.py b/xos/ec2_observer/error_mapper.py
deleted file mode 100644
index 3039a56..0000000
--- a/xos/ec2_observer/error_mapper.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from xos.config import Config
-from util.logger import Logger, logging, logger
-
-class ErrorMapper:
- def __init__(self, error_map_file):
- self.error_map = {}
- try:
- error_map_lines = open(error_map_file).read().splitlines()
- for l in error_map_lines:
- if (not l.startswith('#')):
- splits = l.split('->')
- k,v = map(lambda i:i.rstrip(),splits)
- self.error_map[k]=v
- except:
- logging.info('Could not read error map')
-
-
- def map(self, error):
- return self.error_map[error]
-
-
-
-
-
-
diff --git a/xos/ec2_observer/event_loop.py b/xos/ec2_observer/event_loop.py
deleted file mode 100644
index fb91ee8..0000000
--- a/xos/ec2_observer/event_loop.py
+++ /dev/null
@@ -1,393 +0,0 @@
-import os
-import imp
-import inspect
-import time
-import traceback
-import commands
-import threading
-import json
-import pdb
-
-from datetime import datetime
-from collections import defaultdict
-from core.models import *
-from django.db.models import F, Q
-#from openstack.manager import OpenStackManager
-from openstack.driver import OpenStackDriver
-from util.logger import Logger, logging, logger
-#from timeout import timeout
-from xos.config import Config, XOS_DIR
-from observer.steps import *
-from syncstep import SyncStep
-from toposort import toposort
-from observer.error_mapper import *
-
-debug_mode = False
-
-logger = Logger(level=logging.INFO)
-
-class StepNotReady(Exception):
- pass
-
-class NoOpDriver:
- def __init__(self):
- self.enabled = True
- self.dependency_graph = None
-
-STEP_STATUS_WORKING=1
-STEP_STATUS_OK=2
-STEP_STATUS_KO=3
-
-def invert_graph(g):
- ig = {}
- for k,v in g.items():
- for v0 in v:
- try:
- ig[v0].append(k)
- except:
- ig=[k]
- return ig
-
-class XOSObserver:
- #sync_steps = [SyncNetworks,SyncNetworkInstances,SyncSites,SyncSitePrivilege,SyncSlices,SyncSliceMemberships,SyncInstances,SyncInstanceIps,SyncExternalRoutes,SyncUsers,SyncRoles,SyncNodes,SyncImages,GarbageCollector]
- sync_steps = []
-
-
- def __init__(self):
- # The Condition object that gets signalled by Feefie events
- self.step_lookup = {}
- self.load_sync_step_modules()
- self.load_sync_steps()
- self.event_cond = threading.Condition()
-
- self.driver_kind = getattr(Config(), "observer_driver", "openstack")
- if self.driver_kind=="openstack":
- self.driver = OpenStackDriver()
- else:
- self.driver = NoOpDriver()
-
- def wait_for_event(self, timeout):
- self.event_cond.acquire()
- self.event_cond.wait(timeout)
- self.event_cond.release()
-
- def wake_up(self):
- logger.info('Wake up routine called. Event cond %r'%self.event_cond)
- self.event_cond.acquire()
- self.event_cond.notify()
- self.event_cond.release()
-
- def load_sync_step_modules(self, step_dir=None):
- if step_dir is None:
- if hasattr(Config(), "observer_steps_dir"):
- step_dir = Config().observer_steps_dir
- else:
- step_dir = XOS_DIR + "/observer/steps"
-
- for fn in os.listdir(step_dir):
- pathname = os.path.join(step_dir,fn)
- if os.path.isfile(pathname) and fn.endswith(".py") and (fn!="__init__.py"):
- module = imp.load_source(fn[:-3],pathname)
- for classname in dir(module):
- c = getattr(module, classname, None)
-
- # make sure 'c' is a descendent of SyncStep and has a
- # provides field (this eliminates the abstract base classes
- # since they don't have a provides)
-
- if inspect.isclass(c) and issubclass(c, SyncStep) and hasattr(c,"provides") and (c not in self.sync_steps):
- self.sync_steps.append(c)
- logger.info('loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps]))
- # print 'loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps])
-
- def load_sync_steps(self):
- dep_path = Config().observer_dependency_graph
- logger.info('Loading model dependency graph from %s' % dep_path)
- try:
- # This contains dependencies between records, not sync steps
- self.model_dependency_graph = json.loads(open(dep_path).read())
- except Exception,e:
- raise e
-
- try:
- backend_path = Config().observer_pl_dependency_graph
- logger.info('Loading backend dependency graph from %s' % backend_path)
- # This contains dependencies between backend records
- self.backend_dependency_graph = json.loads(open(backend_path).read())
- except Exception,e:
- logger.info('Backend dependency graph not loaded')
- # We can work without a backend graph
- self.backend_dependency_graph = {}
-
- provides_dict = {}
- for s in self.sync_steps:
- self.step_lookup[s.__name__] = s
- for m in s.provides:
- try:
- provides_dict[m.__name__].append(s.__name__)
- except KeyError:
- provides_dict[m.__name__]=[s.__name__]
-
- step_graph = {}
- for k,v in self.model_dependency_graph.iteritems():
- try:
- for source in provides_dict[k]:
- for m in v:
- try:
- for dest in provides_dict[m]:
- # no deps, pass
- try:
- if (dest not in step_graph[source]):
- step_graph[source].append(dest)
- except:
- step_graph[source]=[dest]
- except KeyError:
- pass
-
- except KeyError:
- pass
- # no dependencies, pass
-
- #import pdb
- #pdb.set_trace()
- if (self.backend_dependency_graph):
- backend_dict = {}
- for s in self.sync_steps:
- for m in s.serves:
- backend_dict[m]=s.__name__
-
- for k,v in backend_dependency_graph.iteritems():
- try:
- source = backend_dict[k]
- for m in v:
- try:
- dest = backend_dict[m]
- except KeyError:
- # no deps, pass
- pass
- step_graph[source]=dest
-
- except KeyError:
- pass
- # no dependencies, pass
-
- self.dependency_graph = step_graph
- self.deletion_dependency_graph = invert_graph(step_graph)
-
- self.ordered_steps = toposort(self.dependency_graph, map(lambda s:s.__name__,self.sync_steps))
- print "Order of steps=",self.ordered_steps
- self.load_run_times()
-
-
- def check_duration(self, step, duration):
- try:
- if (duration > step.deadline):
- logger.info('Sync step %s missed deadline, took %.2f seconds'%(step.name,duration))
- except AttributeError:
- # S doesn't have a deadline
- pass
-
- def update_run_time(self, step, deletion):
- if (not deletion):
- self.last_run_times[step.__name__]=time.time()
- else:
- self.last_deletion_run_times[step.__name__]=time.time()
-
-
- def check_schedule(self, step, deletion):
- last_run_times = self.last_run_times if not deletion else self.last_deletion_run_times
-
- time_since_last_run = time.time() - last_run_times.get(step.__name__, 0)
- try:
- if (time_since_last_run < step.requested_interval):
- raise StepNotReady
- except AttributeError:
- logger.info('Step %s does not have requested_interval set'%step.__name__)
- raise StepNotReady
-
- def load_run_times(self):
- try:
- jrun_times = open('/tmp/observer_run_times').read()
- self.last_run_times = json.loads(jrun_times)
- except:
- self.last_run_times={}
- for e in self.ordered_steps:
- self.last_run_times[e]=0
- try:
- jrun_times = open('/tmp/observer_deletion_run_times').read()
- self.last_deletion_run_times = json.loads(jrun_times)
- except:
- self.last_deletion_run_times={}
- for e in self.ordered_steps:
- self.last_deletion_run_times[e]=0
-
-
- def save_run_times(self):
- run_times = json.dumps(self.last_run_times)
- open('/tmp/observer_run_times','w').write(run_times)
-
- deletion_run_times = json.dumps(self.last_deletion_run_times)
- open('/tmp/observer_deletion_run_times','w').write(deletion_run_times)
-
- def check_class_dependency(self, step, failed_steps):
- step.dependenices = []
- for obj in step.provides:
- step.dependenices.extend(self.model_dependency_graph.get(obj.__name__, []))
- for failed_step in failed_steps:
- if (failed_step in step.dependencies):
- raise StepNotReady
-
- def sync(self, S, deletion):
- step = self.step_lookup[S]
- start_time=time.time()
-
- dependency_graph = self.dependency_graph if not deletion else self.deletion_dependency_graph
-
- # Wait for step dependencies to be met
- try:
- deps = self.dependency_graph[S]
- has_deps = True
- except KeyError:
- has_deps = False
-
- if (has_deps):
- for d in deps:
- cond = self.step_conditions[d]
- cond.acquire()
- if (self.step_status[d] is STEP_STATUS_WORKING):
- cond.wait()
- cond.release()
- go = self.step_status[d] == STEP_STATUS_OK
- else:
- go = True
-
- if (not go):
- self.failed_steps.append(sync_step)
- my_status = STEP_STATUS_KO
- else:
- sync_step = step(driver=self.driver,error_map=self.error_mapper)
- sync_step.__name__ = step.__name__
- sync_step.dependencies = []
- try:
- mlist = sync_step.provides
-
- for m in mlist:
- sync_step.dependencies.extend(self.model_dependency_graph[m.__name__])
- except KeyError:
- pass
- sync_step.debug_mode = debug_mode
-
- should_run = False
- try:
- # Various checks that decide whether
- # this step runs or not
- self.check_class_dependency(sync_step, self.failed_steps) # dont run Slices if Sites failed
- self.check_schedule(sync_step, deletion) # dont run sync_network_routes if time since last run < 1 hour
- should_run = True
- except StepNotReady:
- logging.info('Step not ready: %s'%sync_step.__name__)
- self.failed_steps.append(sync_step)
- my_status = STEP_STATUS_KO
- except Exception,e:
- logging.error('%r',e)
- logger.log_exc("sync step failed: %r. Deletion: %r"%(sync_step,deletion))
- self.failed_steps.append(sync_step)
- my_status = STEP_STATUS_KO
-
- if (should_run):
- try:
- duration=time.time() - start_time
-
- logger.info('Executing step %s' % sync_step.__name__)
-
- failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion)
-
- self.check_duration(sync_step, duration)
-
- if failed_objects:
- self.failed_step_objects.update(failed_objects)
-
- my_status = STEP_STATUS_OK
- self.update_run_time(sync_step,deletion)
- except Exception,e:
- logging.error('Model step failed. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!',e)
- logger.log_exc(e)
- self.failed_steps.append(S)
- my_status = STEP_STATUS_KO
- else:
- my_status = STEP_STATUS_OK
-
- try:
- my_cond = self.step_conditions[S]
- my_cond.acquire()
- self.step_status[S]=my_status
- my_cond.notify_all()
- my_cond.release()
- except KeyError,e:
- logging.info('Step %r is a leaf')
- pass
-
- def run(self):
- if not self.driver.enabled:
- return
-
- if (self.driver_kind=="openstack") and (not self.driver.has_openstack):
- return
-
- while True:
- try:
- error_map_file = getattr(Config(), "error_map_path", XOS_DIR + "/error_map.txt")
- self.error_mapper = ErrorMapper(error_map_file)
-
- # Set of whole steps that failed
- self.failed_steps = []
-
- # Set of individual objects within steps that failed
- self.failed_step_objects = set()
-
- # Set up conditions and step status
- # This is needed for steps to run in parallel
- # while obeying dependencies.
-
- providers = set()
- for v in self.dependency_graph.values():
- if (v):
- providers.update(v)
-
- self.step_conditions = {}
- self.step_status = {}
- for p in list(providers):
- self.step_conditions[p] = threading.Condition()
- self.step_status[p] = STEP_STATUS_WORKING
-
-
- logger.info('Waiting for event')
- tBeforeWait = time.time()
- self.wait_for_event(timeout=30)
- logger.info('Observer woke up')
-
- # Two passes. One for sync, the other for deletion.
- for deletion in [False,True]:
- threads = []
- logger.info('Deletion=%r...'%deletion)
- schedule = self.ordered_steps if not deletion else reversed(self.ordered_steps)
-
- for S in schedule:
- thread = threading.Thread(target=self.sync, args=(S, deletion))
-
- logger.info('Deletion=%r...'%deletion)
- threads.append(thread)
-
- # Start threads
- for t in threads:
- t.start()
-
- # Wait for all threads to finish before continuing with the run loop
- for t in threads:
- t.join()
-
- self.save_run_times()
- except Exception, e:
- logging.error('Core error. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!',e)
- logger.log_exc("Exception in observer run loop")
- traceback.print_exc()
diff --git a/xos/ec2_observer/steps/sync_instances.py b/xos/ec2_observer/steps/sync_instances.py
deleted file mode 100644
index 3dc5f0e..0000000
--- a/xos/ec2_observer/steps/sync_instances.py
+++ /dev/null
@@ -1,117 +0,0 @@
-import os
-import json
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from ec2_observer.syncstep import SyncStep
-from core.models.instance import Instance
-from core.models.slice import SlicePrivilege, SliceDeployments
-from core.models.network import Network, NetworkSlice, NetworkDeployments
-from util.logger import Logger, logging
-from ec2_observer.awslib import *
-from core.models.site import *
-from core.models.slice import *
-from ec2_observer.creds import *
-import pdb
-
-logger = Logger(level=logging.INFO)
-
-class SyncInstances(SyncStep):
- provides=[Instance]
- requested_interval=0
-
- def fetch_pending(self, deletion):
- if deletion:
- object_source = Instance.deleted_objects
- else:
- object_source = Instance.objects
-
- all_instances = object_source.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
- my_instances = []
-
- for instance in all_instances:
- sd = SliceDeployments.objects.filter(Q(slice=instance.slice))
- if (sd):
- if (sd.deployment.name=='Amazon EC2'):
- my_instances.append(instance)
- if (instance.node.deployment.name=='Amazon EC2'):
- my_instances.append(instance)
- return my_instances
-
- def delete_record(self, instance):
- user = instance.creator
- e = get_creds(user=user, site=user.site)
- result = aws_run('ec2 terminate-instances --instance-ids=%s'%instance.instance_id, env=e)
-
- def sync_record(self, instance):
- logger.info("sync'ing instance:%s deployment:%s " % (instance, instance.node.deployment))
-
- if not instance.instance_id:
- # public keys
- slice_memberships = SlicePrivilege.objects.filter(slice=instance.slice)
- pubkeys = [sm.user.public_key for sm in slice_memberships if sm.user.public_key]
-
- if instance.creator.public_key:
- pubkeys.append(instance.creator.public_key)
-
- if instance.slice.creator.public_key:
- pubkeys.append(instance.slice.creator.public_key)
-
- # netowrks
- # include all networks available to the slice and/or associated network templates
- #nics = []
- #networks = [ns.network for ns in NetworkSlice.objects.filter(slice=instance.slice)]
- #network_deployments = NetworkDeployments.objects.filter(network__in=networks,
- #deployment=instance.node.deployment)
- # Gather private networks first. This includes networks with a template that has
- # visibility = private and translation = none
- #for network_deployment in network_deployments:
- # if network_deployment.network.template.visibility == 'private' and \
- # network_deployment.network.template.translation == 'none':
- # nics.append({'net-id': network_deployment.net_id})
-
- # now include network template
- #network_templates = [network.template.sharedNetworkName for network in networks \
- # if network.template.sharedNetworkName]
- #for net in driver.shell.quantum.list_networks()['networks']:
- # if net['name'] in network_templates:
- # nics.append({'net-id': net['id']})
- # look up image id
-
- instance_type = instance.node.name.rsplit('.',1)[0]
-
- # Bail out of we don't have a key
- key_name = instance.creator.email.lower().replace('@', 'AT').replace('.', '')
- u = instance.creator
- s = u.site
- e = get_creds(user=u, site=s)
- key_sig = aws_run('ec2 describe-key-pairs', env=e)
- ec2_keys = key_sig['KeyPairs']
- key_found = False
- for key in ec2_keys:
- if (key['KeyName']==key_name):
- key_found = True
- break
-
- if (not key_found):
- # set backend_status
- raise Exception('Will not sync instance without key')
-
- image_id = instance.image.path
- instance_sig = aws_run('ec2 run-instances --image-id %s --instance-type %s --count 1 --key-name %s --placement AvailabilityZone=%s'%(image_id,instance_type,key_name,instance.node.site.name), env=e)
- instance.instance_id = instance_sig['Instances'][0]['InstanceId']
- instance.save()
- state = instance_sig['Instances'][0]['State']['Code']
- if (state==16):
- instance.ip = instance_sig['Instances'][0]['PublicIpAddress']
- instance.save()
- else:
- # This status message should go into backend_status
- raise Exception('Waiting for instance to start')
- else:
- ret = aws_run('ec2 describe-instances --instance-ids %s'%instance.instance_id, env=e)
- state = ret['Reservations'][0]['Instances'][0]['State']['Code']
- if (state==16):
- instance.ip = ret['Reservations'][0]['Instances'][0]['PublicIpAddress']
- instance.save()
-
diff --git a/xos/ec2_observer/syncstep.py b/xos/ec2_observer/syncstep.py
deleted file mode 100644
index e15e719..0000000
--- a/xos/ec2_observer/syncstep.py
+++ /dev/null
@@ -1,101 +0,0 @@
-import os
-import base64
-from datetime import datetime
-
-from django.db.models import F, Q
-
-from xos.config import Config
-from util.logger import Logger, logging
-from observer.steps import *
-
-logger = Logger(level=logging.INFO)
-
-class FailedDependency(Exception):
- pass
-
-class SyncStep:
- """ A XOS Sync step.
-
- Attributes:
- psmodel Model name the step synchronizes
- dependencies list of names of models that must be synchronized first if the current model depends on them
- """
- slow=False
- def get_prop(self, prop):
- try:
- sync_config_dir = Config().sync_config_dir
- except:
- sync_config_dir = '/etc/xos/sync' # XXX TODO: update path
- prop_config_path = '/'.join(sync_config_dir,self.name,prop)
- return open(prop_config_path).read().rstrip()
-
- def __init__(self, **args):
- """Initialize a sync step
- Keyword arguments:
- name -- Name of the step
- provides -- XOS models sync'd by this step
- """
- dependencies = []
- self.driver = args.get('driver')
- self.error_map = args.get('error_map')
-
- try:
- self.soft_deadline = int(self.get_prop('soft_deadline_seconds'))
- except:
- self.soft_deadline = 5 # 5 seconds
-
- return
-
- def fetch_pending(self, deletion=False):
- # This is the most common implementation of fetch_pending
- # Steps should override it if they have their own logic
- # for figuring out what objects are outstanding.
- main_obj = self.provides[0]
- if (not deletion):
- objs = main_obj.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
- else:
- objs = main_obj.deleted_objects.all()
-
- return objs
- #return Instance.objects.filter(ip=None)
-
- def check_dependencies(self, obj, failed):
- for dep in self.dependencies:
- peer_name = dep[0].lower() + dep[1:] # django names are camelCased with the first letter lower
- peer_object = getattr(obj, peer_name)
-
- # peer_object can be None, and if so there
- # is no object-level dependency
- if (peer_object and peer_object.pk==failed.pk):
- raise FailedDependency
-
- def call(self, failed=[], deletion=False):
- pending = self.fetch_pending(deletion)
- for o in pending:
- try:
- for f in failed:
- self.check_dependencies(o,f) # Raises exception if failed
- if (deletion):
- self.delete_record(o)
- o.delete(purge=True)
- else:
- self.sync_record(o)
- o.enacted = datetime.now() # Is this the same timezone? XXX
- o.backend_status = "OK"
- o.save(update_fields=['enacted'])
- except Exception,e:
- try:
- o.backend_status = self.error_map.map(str(e))
- except:
- o.backend_status = str(e)
-
- if (o.pk):
- o.save(update_fields=['backend_status'])
-
- logger.log_exc("sync step failed!")
- failed.append(o)
-
- return failed
-
- def __call__(self, **args):
- return self.call(**args)
diff --git a/xos/core/api/__init__.py b/xos/generate/__init__.py
similarity index 100%
rename from xos/core/api/__init__.py
rename to xos/generate/__init__.py
diff --git a/xos/generate/dependency_walker.py b/xos/generate/dependency_walker.py
new file mode 100644
index 0000000..210ec0f
--- /dev/null
+++ b/xos/generate/dependency_walker.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python
+
+import os
+import imp
+from xos.config import Config, XOS_DIR
+import inspect
+import time
+import traceback
+import commands
+import threading
+import json
+import pdb
+from core.models import *
+
+from xos.logger import Logger, logging
+logger = Logger(level=logging.INFO)
+
+missing_links={}
+
+try:
+ dep_data = open(Config().dependency_graph).read()
+except:
+ dep_data = open(XOS_DIR + '/model-deps').read()
+
+dependencies = json.loads(dep_data)
+
+inv_dependencies = {}
+for k, lst in dependencies.items():
+ for v in lst:
+ try:
+ inv_dependencies[v].append(k)
+ except KeyError:
+ inv_dependencies[v]=[k]
+
+
+def plural(name):
+ if (name.endswith('s')):
+ return name+'es'
+ else:
+ return name+'s'
+
+
+def walk_deps(fn, object):
+ model = object.__class__.__name__
+ try:
+ deps = dependencies[model]
+ except:
+ deps = []
+ return __walk_deps(fn, object, deps)
+
+def walk_inv_deps(fn, object):
+ model = object.__class__.__name__
+ try:
+ deps = inv_dependencies[model]
+ except:
+ deps = []
+ return __walk_deps(fn, object, deps)
+
+def __walk_deps(fn, object, deps):
+ model = object.__class__.__name__
+ ret = []
+ for dep in deps:
+ #print "Checking dep %s"%dep
+ peer=None
+ link = dep.lower()
+ try:
+ peer = getattr(object, link)
+ except AttributeError:
+ link = plural(link)
+ try:
+ peer = getattr(object, link)
+ except AttributeError:
+ if not missing_links.has_key(model+'.'+link):
+ print "Model %s missing link for dependency %s"%(model, link)
+ logger.log_exc("WARNING: Model %s missing link for dependency %s."%(model, link))
+ missing_links[model+'.'+link]=True
+
+
+ if (peer):
+ try:
+ peer_objects = peer.all()
+ except AttributeError:
+ peer_objects = [peer]
+ except:
+ peer_objects = []
+
+ for o in peer_objects:
+ #if (isinstance(o,PlCoreBase)):
+ if (hasattr(o,'updated')):
+ fn(o, object)
+ ret.append(o)
+ # Uncomment the following line to enable recursion
+ # walk_inv_deps(fn, o)
+ return ret
+
+def p(x,source):
+ print x,x.__class__.__name__
+ return
+
+def main():
+ #pdb.set_trace()
+ s = Slice.objects.filter(name='princeton_sapan62')
+ #pdb.set_trace()
+ print walk_inv_deps(p,s[0])
+
+if __name__=='__main__':
+ main()
diff --git a/xos/helloworld/view.py b/xos/helloworld/view.py
deleted file mode 100644
index 7024747..0000000
--- a/xos/helloworld/view.py
+++ /dev/null
@@ -1,58 +0,0 @@
-from django.http import HttpResponse
-from django.views.generic import TemplateView, View
-from django import template
-from monitor import driver
-from core.models import *
-from helloworld.models import *
-import json
-import os
-import time
-import tempfile
-
-class HelloWorldView(TemplateView):
- head_template = r"""{% extends "admin/dashboard/dashboard_base.html" %}
- {% load admin_static %}
- {% block content %}
- """
-
- tail_template = r"{% endblock %}"
-
- def get(self, request, name="root", *args, **kwargs):
- head_template = self.head_template
- tail_template = self.tail_template
-
- try:
- hello_name = request.GET['hello_name']
- world_name = request.GET['world_name']
- instance_id_str = request.GET['instance_id']
- instance_id = int(instance_id_str)
-
- i = Instance.objects.get(pk=instance_id)
- i.pk=None
- i.userData=None
- i.instance_id=None
- i.instance_name=None
- i.enacted=None
- i.save()
- h = Hello(name=hello_name,instance_backref=i)
- h.save()
- w = World(hello=h,name=world_name)
- w.save()
-
- t = template.Template(head_template + 'Done. New instance id: %r'%i.pk + self.tail_template)
- except KeyError:
- html = """<form>
- Hello string: <input type="text" name="hello_name" placeholder="Planet"><br>
- World string: <input type="text" name="world_name" placeholder="Earth"><br>
- Id of instance to copy: <input type="text" name="instance_id" placeholder="3"><br>
- <input type="submit" value="Submit">
- </form>"""
-
- t = template.Template(head_template + html + self.tail_template)
-
- response_kwargs = {}
- response_kwargs.setdefault('content_type', self.content_type)
- return self.response_class(
- request = request,
- template = t,
- **response_kwargs)
diff --git a/xos/helloworldservice_complete/admin.py b/xos/helloworldservice_complete/admin.py
deleted file mode 100644
index 9a3e4f7..0000000
--- a/xos/helloworldservice_complete/admin.py
+++ /dev/null
@@ -1,141 +0,0 @@
-
-from core.admin import ReadOnlyAwareAdmin, SliceInline
-from core.middleware import get_request
-from core.models import User
-from django import forms
-from django.contrib import admin
-from helloworldservice_complete.models import HelloWorldServiceComplete, HelloWorldTenantComplete, HELLO_WORLD_KIND
-
-# The class to provide an admin interface on the web for the service.
-# We do only configuration here and don't change any logic because the logic
-# is taken care of for us by ReadOnlyAwareAdmin
-class HelloWorldServiceCompleteAdmin(ReadOnlyAwareAdmin):
- # We must set the model so that the admin knows what fields to use
- model = HelloWorldServiceComplete
- verbose_name = "Hello World Service"
- verbose_name_plural = "Hello World Services"
-
- # Setting list_display creates columns on the admin page, each value here
- # is a column, the column is populated for every instance of the model.
- list_display = ("backend_status_icon", "name", "enabled")
-
- # Used to indicate which values in the columns of the admin form are links.
- list_display_links = ('backend_status_icon', 'name', )
-
- # Denotes the sections of the form, the fields in the section, and the
- # CSS classes used to style them. We represent this as a set of tuples, each
- # tuple as a name (or None) and a set of fields and classes.
- # Here the first section does not have a name so we use none. That first
- # section has several fields indicated in the 'fields' attribute, and styled
- # by the classes indicated in the 'classes' attribute. The classes given
- # here are important for rendering the tabs on the form. To give the tabs
- # we must assign the classes suit-tab and suit-tab-<name> where
- # where <name> will be used later.
- fieldsets = [(None, {'fields': ['backend_status_text', 'name', 'enabled',
- 'versionNumber', 'description', "view_url"],
- 'classes':['suit-tab suit-tab-general']})]
-
- # Denotes the fields that are readonly and cannot be changed.
- readonly_fields = ('backend_status_text', )
-
- # Inlines are used to denote other models that can be edited on the same
- # form as this one. In this case the service form also allows changes
- # to slices.
- inlines = [SliceInline]
-
- extracontext_registered_admins = True
-
- # Denotes the fields that can be changed by an admin but not be all users
- user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
-
- # Associates fieldsets from this form and from the inlines.
- # The format here are tuples, of (<name>, tab title). <name> comes from the
- # <name> in the fieldsets.
- suit_form_tabs = (('general', 'Hello World Service Details'),
- ('administration', 'Tenants'),
- ('slices', 'Slices'),)
-
- # Used to include a template for a tab. Here we include the
- # helloworldserviceadmin template in the top position for the administration
- # tab.
- suit_form_includes = (('helloworldserviceadmin.html',
- 'top',
- 'administration'),)
-
- # Used to get the objects for this model that are associated with the
- # requesting user.
- def queryset(self, request):
- return HelloWorldServiceComplete.get_service_objects_by_user(request.user)
-
-# Class to represent the form to add and edit tenants.
-# We need to define this instead of just using an admin like we did for the
-# service because tenants vary more than services and there isn't a common form.
-# This allows us to change the python behavior for the admin form to save extra
-# fields and control defaults.
-class HelloWorldTenantCompleteForm(forms.ModelForm):
- # Defines a field for the creator of this service. It is a dropdown which
- # is populated with all of the users.
- creator = forms.ModelChoiceField(queryset=User.objects.all())
- # Defines a text field for the display message, it is not required.
- display_message = forms.CharField(required=False)
-
- def __init__(self, *args, **kwargs):
- super(HelloWorldTenantCompleteForm, self).__init__(*args, **kwargs)
- # Set the kind field to readonly
- self.fields['kind'].widget.attrs['readonly'] = True
- # Define the logic for obtaining the objects for the provider_service
- # dropdown of the tenant form.
- self.fields[
- 'provider_service'].queryset = HelloWorldServiceComplete.get_service_objects().all()
- # Set the initial kind to HELLO_WORLD_KIND for this tenant.
- self.fields['kind'].initial = HELLO_WORLD_KIND
- # If there is an instance of this model then we can set the initial
- # form values to the existing values.
- if self.instance:
- self.fields['creator'].initial = self.instance.creator
- self.fields[
- 'display_message'].initial = self.instance.display_message
-
- # If there is not an instance then we need to set initial values.
- if (not self.instance) or (not self.instance.pk):
- self.fields['creator'].initial = get_request().user
- if HelloWorldServiceComplete.get_service_objects().exists():
- self.fields["provider_service"].initial = HelloWorldServiceComplete.get_service_objects().all()[0]
-
- # This function describes what happens when the save button is pressed on
- # the tenant form. In this case we set the values for the instance that were
- # entered.
- def save(self, commit=True):
- self.instance.creator = self.cleaned_data.get("creator")
- self.instance.display_message = self.cleaned_data.get(
- "display_message")
- return super(HelloWorldTenantCompleteForm, self).save(commit=commit)
-
- class Meta:
- model = HelloWorldTenantComplete
-
-# Define the admin form for the tenant. This uses a similar structure as the
-# service but uses HelloWorldTenantCompleteForm to change the python behavior.
-
-
-class HelloWorldTenantCompleteAdmin(ReadOnlyAwareAdmin):
- verbose_name = "Hello World Tenant"
- verbose_name_plural = "Hello World Tenants"
- list_display = ('id', 'backend_status_icon', 'instance', 'display_message')
- list_display_links = ('backend_status_icon', 'instance', 'display_message',
- 'id')
- fieldsets = [(None, {'fields': ['backend_status_text', 'kind',
- 'provider_service', 'instance', 'creator',
- 'display_message'],
- 'classes': ['suit-tab suit-tab-general']})]
- readonly_fields = ('backend_status_text', 'instance',)
- form = HelloWorldTenantCompleteForm
-
- suit_form_tabs = (('general', 'Details'),)
-
- def queryset(self, request):
- return HelloWorldTenantComplete.get_tenant_objects_by_user(request.user)
-
-# Associate the admin forms with the models.
-admin.site.register(HelloWorldServiceComplete, HelloWorldServiceCompleteAdmin)
-admin.site.register(HelloWorldTenantComplete, HelloWorldTenantCompleteAdmin)
diff --git a/xos/hpc/admin.py b/xos/hpc/admin.py
deleted file mode 100644
index de876ac..0000000
--- a/xos/hpc/admin.py
+++ /dev/null
@@ -1,227 +0,0 @@
-from django.contrib import admin
-
-from hpc.models import *
-from django import forms
-from django.utils.safestring import mark_safe
-from django.contrib.auth.admin import UserAdmin
-from django.contrib.admin.widgets import FilteredSelectMultiple
-from django.contrib.auth.forms import ReadOnlyPasswordHashField
-from django.contrib.auth.signals import user_logged_in
-from django.utils import timezone
-from django.contrib.contenttypes import generic
-from suit.widgets import LinkedSelect
-from core.admin import ServiceAppAdmin,SliceInline,ServiceAttrAsTabInline, ReadOnlyAwareAdmin, XOSTabularInline, SliderWidget, ServicePrivilegeInline
-from core.middleware import get_request
-
-from functools import update_wrapper
-from django.contrib.admin.views.main import ChangeList
-from django.core.urlresolvers import reverse, NoReverseMatch
-from django.contrib.admin.utils import quote
-
-from filteredadmin import FilteredChangeList, FilteredAdmin, FilteredInline
-
-class HpcServiceForm(forms.ModelForm):
- scale = forms.IntegerField(widget = SliderWidget, required=False)
-
- def __init__(self, *args, **kwargs):
- super(HpcServiceForm, self).__init__(*args, **kwargs)
- self.fields['scale'].initial = kwargs["instance"].scale
-
- def save(self, *args, **kwargs):
- if self.cleaned_data['scale']:
- self.instance.scale = self.cleaned_data['scale']
-
- return super(HpcServiceForm, self).save(*args, **kwargs)
-
-class HpcServiceAdmin(ReadOnlyAwareAdmin):
- model = HpcService
- verbose_name = "HPC Service"
- verbose_name_plural = "HPC Service"
- list_display = ("backend_status_icon", "name","enabled")
- list_display_links = ('backend_status_icon', 'name', )
- fieldsets = [(None, {'fields': ['backend_status_text', 'name','scale','enabled','versionNumber', 'description', "cmi_hostname", "hpc_port80", "watcher_hpc_network", "watcher_dnsredir_network", "watcher_dnsdemux_network"], 'classes':['suit-tab suit-tab-general']})]
- readonly_fields = ('backend_status_text', )
- inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
- form = HpcServiceForm
-
- extracontext_registered_admins = True
-
- user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
-
- suit_form_tabs =(('general', 'HPC Service Details'),
- ('administration', 'Administration'),
- ('tools', 'Tools'),
- ('slices','Slices'),
- ('serviceattrs','Additional Attributes'),
- ('serviceprivileges','Privileges'),
- )
-
- suit_form_includes = (('hpcadmin.html', 'top', 'administration'),
- ('hpctools.html', 'top', 'tools') )
-
- def url_for_model_changelist(self, request, model):
- if not request.resolver_match.args:
- return reverse('admin:%s_%s_changelist' % (model._meta.app_label, model._meta.model_name), current_app=model._meta.app_label)
- else:
- obj_id = request.resolver_match.args[0]
- changelist_url = reverse('admin:%s_%s_filteredchangelist' % (model._meta.app_label, model._meta.model_name), args=(obj_id,), current_app=model._meta.app_label)
- return changelist_url
-
-class HPCAdmin(FilteredAdmin):
- # Change the application breadcrumb to point to an HPC Service if one is
- # defined
-
- custom_app_breadcrumb_name = "Hpc"
- @property
- def custom_app_breadcrumb_url(self):
- services = HpcService.objects.all()
- if len(services)==1:
- return "/admin/hpc/hpcservice/%s/" % services[0].id
- else:
- return "/admin/hpc/hpcservice/"
-
-class CDNPrefixInline(FilteredInline):
- model = CDNPrefix
- extra = 0
- suit_classes = 'suit-tab suit-tab-prefixes'
- fields = ('backend_status_icon', 'cdn_prefix_id', 'prefix', 'defaultOriginServer', 'enabled')
- readonly_fields = ('backend_status_icon', 'cdn_prefix_id',)
-
-class OriginServerInline(FilteredInline):
- model = OriginServer
- extra = 0
- suit_classes = 'suit-tab suit-tab-origins'
- fields = ('backend_status_icon', 'origin_server_id', 'url')
- readonly_fields = ('backend_status_icon', 'origin_server_id')
-
-class ContentProviderInline(FilteredInline):
- model = ContentProvider
- extra = 0
- suit_classes = 'suit-tab suit-tab-cps'
- fields = ('backend_status_icon', 'content_provider_id', 'name', 'enabled')
- readonly_fields = ('backend_status_icon', 'content_provider_id',)
-
-class OriginServerAdmin(HPCAdmin):
- list_display = ('backend_status_icon', 'url','protocol','redirects','contentProvider','authenticated','enabled' )
- list_display_links = ('backend_status_icon', 'url', )
-
- fields = ('backend_status_text', 'url','protocol','redirects','contentProvider','authenticated','enabled','origin_server_id','description' )
- readonly_fields = ('backend_status_text', 'origin_server_id',)
- user_readonly_fields = ('url','protocol','redirects','contentProvider','authenticated','enabled','origin_server_id','description')
-
-class ContentProviderForm(forms.ModelForm):
- users = forms.ModelMultipleChoiceField(
- queryset=User.objects.all(),
- required=False,
- help_text="Select which users can manage this ContentProvider",
- widget=FilteredSelectMultiple(
- verbose_name=('Users'), is_stacked=False
- )
- )
-
- class Meta:
- model = ContentProvider
- widgets = {
- 'serviceProvider' : LinkedSelect
- }
-
- def __init__(self, *args, **kwargs):
- request = kwargs.pop('request', None)
- super(ContentProviderForm, self).__init__(*args, **kwargs)
-
- if self.instance and self.instance.pk:
- self.fields['users'].initial = self.instance.users.all()
-
-class ContentProviderAdmin(HPCAdmin):
- form = ContentProviderForm
- list_display = ('backend_status_icon', 'name','description','enabled' )
- list_display_links = ('backend_status_icon', 'name', )
- readonly_fields = ('backend_status_text', )
- admin_readonly_fields = ('backend_status_text', )
- cp_readonly_fields = ('backend_status_text', 'name', 'enabled', 'serviceProvider', 'users')
- fieldsets = [ (None, {'fields': ['backend_status_text', 'name','enabled','description','serviceProvider','users'], 'classes':['suit-tab suit-tab-general']})]
-
- inlines = [CDNPrefixInline, OriginServerInline]
-
- user_readonly_fields = ('name','description','enabled','serviceProvider','users')
-
- suit_form_tabs = (('general','Details'),('prefixes','CDN Prefixes'), ('origins','Origin Servers'))
-
- def change_view(self,request, *args, **kwargs):
- if request.user.is_admin:
- self.readonly_fields = self.admin_readonly_fields
- else:
- self.readonly_fields = self.cp_readonly_fields
-
- return super(ContentProviderAdmin, self).change_view(request, *args, **kwargs)
-
- def has_add_permission(self, request):
- return request.user.is_admin
-
- def has_delete_permission(self, request, obj=None):
- return request.user.is_admin
-
-class ServiceProviderAdmin(HPCAdmin):
- list_display = ('backend_status_icon', 'name', 'description', 'enabled')
- list_display_links = ('backend_status_icon', 'name', )
- fieldsets = [
- (None, {'fields': ['backend_status_text', 'name','description','enabled', 'hpcService'], 'classes':['suit-tab suit-tab-general']})]
-#, ('Content Providers', {'fields':['contentProviders'],'classes':['suit-tab suit-tab-cps']})]
-
- readonly_fields = ('backend_status_text', )
- user_readonly_fields = ('name', 'description', 'enabled')
-
- suit_form_tabs = (('general','Details'),('cps','Content Providers'))
- inlines = [ContentProviderInline]
-
-class CDNPrefixForm(forms.ModelForm):
- class Meta:
- widgets = {
- 'contentProvider' : LinkedSelect
- }
-
-class CDNPrefixAdmin(HPCAdmin):
- form = CDNPrefixForm
- list_display = ['backend_status_icon', 'prefix','contentProvider']
- list_display_links = ('backend_status_icon', 'prefix', )
- fields = ['backend_status_text', 'prefix', 'contentProvider', 'cdn_prefix_id', 'description', 'defaultOriginServer', 'enabled']
- readonly_fields = ('backend_status_text', )
- user_readonly_fields = ['prefix','contentProvider', "cdn_prefix_id", "description", "defaultOriginServer", "enabled"]
-
-class SiteMapAdmin(HPCAdmin):
- model = SiteMap
- verbose_name = "Site Map"
- verbose_name_plural = "Site Map"
- list_display = ("backend_status_icon", "name", "contentProvider", "serviceProvider")
- list_display_links = ('backend_status_icon', 'name', )
- fields = ['backend_status_text', 'name', 'hpcService', 'cdnPrefix', 'contentProvider', 'serviceProvider', 'map', 'map_id']
- user_readonly_fields = ('backend_status_text', "name", "hpcService", "cdnPrefix", "contentProvider", "serviceProvider", "description", "map")
- readonly_fields = ('backend_status_text', )
-
-class AccessMapAdmin(HPCAdmin):
- model = AccessMap
- verbose_name = "Access Map"
- verbose_name_plural = "Access Map"
- list_display = ("backend_status_icon", "name", "contentProvider")
- list_display_links = ('backend_status_icon', 'name', )
- user_readonly_fields = ('backend_status_text', "name", "contentProvider", "description", "map")
- readonly_fields = ('backend_status_text', )
-
-class HpcHealthCheckAdmin(HPCAdmin):
- model = HpcHealthCheck
- verbose_name = "Health Check"
- verbose_name = "Health Checks"
- list_display = ["backend_status_icon", "resource_name", "kind"]
- list_display_links = ["backend_status_icon", "resource_name"]
- fields = ["backend_status_text", "hpcService", "resource_name", "kind", "result_contains", "result_min_size", "result_max_size"]
- readonly_fields = ["backend_status_text",]
-
-admin.site.register(ServiceProvider, ServiceProviderAdmin)
-admin.site.register(ContentProvider, ContentProviderAdmin)
-admin.site.register(CDNPrefix, CDNPrefixAdmin)
-admin.site.register(OriginServer,OriginServerAdmin)
-admin.site.register(HpcService, HpcServiceAdmin)
-admin.site.register(SiteMap, SiteMapAdmin)
-admin.site.register(AccessMap, AccessMapAdmin)
-admin.site.register(HpcHealthCheck, HpcHealthCheckAdmin)
-
diff --git a/xos/hpc/filteredadmin.py b/xos/hpc/filteredadmin.py
deleted file mode 100644
index 4ef3fe3..0000000
--- a/xos/hpc/filteredadmin.py
+++ /dev/null
@@ -1,191 +0,0 @@
-from django.contrib import admin
-
-from django import forms
-from hpc.models import HpcService
-from core.admin import ServiceAppAdmin,SliceInline,ServiceAttrAsTabInline, ReadOnlyAwareAdmin, XOSTabularInline, SliderWidget, ServicePrivilegeInline
-from core.middleware import get_request
-
-from functools import update_wrapper
-from django.contrib.admin.views.main import ChangeList
-from django.core.urlresolvers import reverse, NoReverseMatch
-from django.contrib.admin.utils import quote
-
-import threading
-_thread_locals = threading.local()
-
-class FilteredChangeList(ChangeList):
- """ A special ChangeList with a doctored url_for_result function that
- points to the filteredchange view instead of the default change
- view.
- """
-
- def __init__(self, request, *args, **kwargs):
- self.service = getattr(request, "hpcService", None)
- self.embedded = getattr(request, "embedded", False)
- super(FilteredChangeList, self).__init__(request, *args, **kwargs)
-
- def url_for_result(self, result):
- if (self.service is None):
- return super(FilteredChangeList, self).url_for_result(result)
-
- pk = getattr(result, self.pk_attname)
- if self.embedded:
- return reverse('admin:%s_%s_embeddedfilteredchange' % (self.opts.app_label,
- self.opts.model_name),
- args=(quote(self.service.id), quote(pk),),
- current_app=self.model_admin.admin_site.name)
-
- else:
- return reverse('admin:%s_%s_filteredchange' % (self.opts.app_label,
- self.opts.model_name),
- args=(quote(self.service.id), quote(pk),),
- current_app=self.model_admin.admin_site.name)
-
-class FilteredAdmin(ReadOnlyAwareAdmin):
- """
- One approach to filtering the HPC Admin views by HPCService. Encode
- the HPCService into the URL for the changelist view. Then we could do our
- custom filtering in self.filtered_changelist_view.
-
- To make this work, a few changes needed to be made to the change and
- change_list templates.
-
- 1) "custom_changelist_breadcrumb_url" is used to replace the breadcrumb
- in change and add views with one that will point back to the filtered
- list.
-
- 2) "custom_add_url" is used to replace the Add button's URL with one
- that points to the filtered add view.
-
- TODO: Save & Add Another,
- the add link when the changelist is empty
- """
-
- @property
- def change_list_template(self):
- return _thread_locals.change_list_template
-
- @property
- def change_form_template(self):
- return _thread_locals.change_form_template
-
- def get_urls(self):
- from django.conf.urls import patterns, url
-
- def wrap(view):
- def wrapper(*args, **kwargs):
- return self.admin_site.admin_view(view)(*args, **kwargs)
- return update_wrapper(wrapper, view)
-
- urls = super(FilteredAdmin, self).get_urls()
- info = self.model._meta.app_label, self.model._meta.model_name
- my_urls = [
- url(r'^(.+)/filteredlist/$', wrap(self.filtered_changelist_view), name="%s_%s_filteredchangelist" % info),
- url(r'^(.+)/embeddedfilteredlist/$', wrap(self.embedded_filtered_changelist_view), name="%s_%s_embeddedfilteredchangelist" % info),
- url(r'^(.+)/(.+)/filteredchange$', wrap(self.filtered_change_view), name='%s_%s_filteredchange' % info),
- url(r'^(.+)/(.+)/embeddedfilteredchange$', wrap(self.embedded_filtered_change_view), name='%s_%s_embeddedfilteredchange' % info),
- url(r'^(.+)/filteredadd/$', wrap(self.filtered_add_view), name='%s_%s_filteredadd' % info),
- url(r'^(.+)/embeddedfilteredadd/$', wrap(self.embedded_filtered_add_view), name='%s_%s_embeddedfilteredadd' % info),
- ]
- return my_urls + urls
-
- def add_extra_context(self, request, extra_context):
- super(FilteredAdmin, self).add_extra_context(request, extra_context)
-
- if getattr(request,"hpcService",None) is not None:
- extra_context["custom_changelist_breadcrumb_url"] = "/admin/hpc/%s/%s/filteredlist/" % (self.model._meta.model_name, str(request.hpcService.id))
- if getattr(request,"embedded",False):
- extra_context["custom_add_url"] = "/admin/hpc/%s/%s/embeddedfilteredadd/" % (self.model._meta.model_name, str(request.hpcService.id))
- else:
- extra_context["custom_add_url"] = "/admin/hpc/%s/%s/filteredadd/" % (self.model._meta.model_name, str(request.hpcService.id))
- if len(request.resolver_match.args)>1:
- # this is only useful on change views, not changelist views
- extra_context["custom_delete_url"] = "/admin/hpc/%s/%s/delete/" % (self.model._meta.model_name, request.resolver_match.args[1])
-
- extra_context["show_save"] = False
- extra_context["show_save_and_add_another"] = False
-
- def changelist_view(self, *args, **kwargs):
- if "template" in kwargs:
- _thread_locals.change_list_template = kwargs["template"]
- del kwargs["template"]
- else:
- _thread_locals.change_list_template = "admin/change_list_bc.html"
- return super(FilteredAdmin, self).changelist_view(*args, **kwargs)
-
- def filtered_changelist_view(self, request, hpcServiceId, extra_context=None):
- request.hpcService = HpcService.objects.get(id=hpcServiceId)
- return self.changelist_view(request, extra_context=extra_context)
-
- def embedded_filtered_changelist_view(self, request, hpcServiceId, extra_context=None):
- request.hpcService = HpcService.objects.get(id=hpcServiceId)
- request.embedded = True
- return self.changelist_view(request, template="admin/change_list_embedded.html", extra_context=extra_context)
-
- def change_view(self, *args, **kwargs):
- if "template" in kwargs:
- _thread_locals.change_form_template = kwargs["template"]
- del kwargs["template"]
- else:
- _thread_locals.change_form_template = "admin/change_form_bc.html"
- return super(FilteredAdmin, self).change_view(*args, **kwargs)
-
- def filtered_change_view(self, request, hpcServiceId, object_id, extra_context=None):
- request.hpcService = HpcService.objects.get(id=hpcServiceId)
- return self.change_view(request, object_id, extra_context=extra_context)
-
- def embedded_filtered_change_view(self, request, hpcServiceId, object_id, extra_context=None):
- request.hpcService = HpcService.objects.get(id=hpcServiceId)
- request.embedded = True
- return self.change_view(request, object_id, template="admin/change_form_embedded.html", extra_context=extra_context)
-
- def add_view(self, *args, **kwargs):
- if "template" in kwargs:
- _thread_locals.change_form_template = kwargs["template"]
- del kwargs["template"]
- else:
- _thread_locals.change_form_template = "admin/change_form_bc.html"
- return super(FilteredAdmin, self).add_view(*args, **kwargs)
-
- def filtered_add_view(self, request, hpcServiceId, extra_context=None):
- request.hpcService = HpcService.objects.get(id=hpcServiceId)
- return self.add_view(request, extra_context=extra_context)
-
- def embedded_filtered_add_view(self, request, hpcServiceId, extra_context=None):
- request.hpcService = HpcService.objects.get(id=hpcServiceId)
- request.embedded = True
- return self.add_view(request, template="admin/change_form_embedded.html", extra_context=extra_context)
-
- def get_queryset(self, request):
- # request.hpcService will be set in filtered_changelist_view so we can
- # use it to filter what will be displayed in the list.
- qs = self.model.objects.all()
- if (getattr(request,"hpcService",None) is not None) and (hasattr(self.model, "filter_by_hpcService")):
- qs = self.model.filter_by_hpcService(qs, request.hpcService)
- return qs
-
- def get_changelist(self, request, **kwargs):
- # We implement a custom ChangeList, so the URLs point to the
- # filtered_change_view rather than the default change_view.
- return FilteredChangeList
-
-class FilteredInline(XOSTabularInline):
- def get_change_url(self, id):
- request = get_request()
- embedded = getattr(request, "embedded", False)
- service_id = request.resolver_match.args[0]
-
- if embedded:
- reverse_path = "admin:%s_embeddedfilteredchange" % (self.selflink_model._meta.db_table)
- args = (service_id, id)
- else:
- reverse_path = "admin:%s_filteredchange" % (self.selflink_model._meta.db_table)
- args = (service_id, id)
-
- try:
- url = reverse(reverse_path, args=args, current_app=self.selflink_model._meta.app_label)
- except NoReverseMatch:
- return None
-
- return url
-
diff --git a/xos/hpc_wizard/README b/xos/hpc_wizard/README
deleted file mode 100644
index 06b12b5..0000000
--- a/xos/hpc_wizard/README
+++ /dev/null
@@ -1,10 +0,0 @@
-Two files are purposely not included in the git repository:
- bigquery_credentials.dat
- client_secrets.json
-
-These files must be manually installed.
-
-Additionally, the following packages must be installed:
- yum -y install python-httplib2
- easy_install python_gflags
- easy_install google_api_python_client
diff --git a/xos/hpc_wizard/bigquery_analytics.py b/xos/hpc_wizard/bigquery_analytics.py
deleted file mode 100644
index cb3038a..0000000
--- a/xos/hpc_wizard/bigquery_analytics.py
+++ /dev/null
@@ -1,290 +0,0 @@
-import re
-import base64
-import requests
-import urllib
-import json
-import httplib2
-import threading
-import os
-import sys
-import time
-import traceback
-
-from apiclient.discovery import build
-from apiclient.errors import HttpError
-from oauth2client.client import AccessTokenRefreshError
-from oauth2client.client import OAuth2WebServerFlow
-from oauth2client.client import flow_from_clientsecrets
-from oauth2client.file import Storage
-from oauth2client.tools import run_flow,run
-
-from bigquery_config import BIGQUERY_SECRETS_FN, BIGQUERY_CREDENTIALS_FN
-
-"""
-yum -y install python-httplib2
-easy_install python_gflags
-easy_install google_api_python_client
-"""
-
-PROJECT_NUMBER = '549187599759'
-
-try:
- FLOW = flow_from_clientsecrets(BIGQUERY_SECRETS_FN,
- scope='https://www.googleapis.com/auth/bigquery')
- BIGQUERY_AVAILABLE = True
-except:
- print >> sys.stderr, "exception while initializing bigquery flow"
- traceback.print_exc()
- FLOW = None
- BIGQUERY_AVAILABLE = False
-
-MINUTE_MS = 60*1000
-HOUR_MS = 60*60*1000
-
-# global to hold cached mappings
-mappings = {}
-reverse_mappings = {}
-
-def to_number(s):
- try:
- if "." in str(s):
- return float(s)
- else:
- return int(s)
- except:
- return 0
-
-class MappingException(Exception):
- pass
-
-class BigQueryAnalytics:
- def __init__(self, table = "demoevents"):
- self.projectName = "vicci"
- self.tableName = table
-
- def reload_mapping(self):
- global mappings, reverse_mappings
- mappings[self.tableName] = json.loads(self.fetch_mapping(table=self.tableName))
- reverse_mappings[self.tableName] = {v:k for k, v in mappings[self.tableName].items()}
-
- def fetch_mapping(self, m=0, table="events"):
- req = 'http://cloud-scrutiny.appspot.com/command?action=get_allocations&multiplexer=%d&table=%s'% (m,table)
- resp = requests.get(req)
- if (resp.status_code==200):
- return resp.text
- else:
- raise Exception('Error accessing register allocations: %d'%resp.status_code)
-
- def run_query_raw(self, query):
- try:
- file("/tmp/query_log","a").write("query %s\n" % query)
- except:
- pass
-
- p = re.compile('%[a-zA-z_]*')
-
- try:
- query = p.sub(self.remap, query)
- except MappingException:
- self.reload_mapping()
- query = p.sub(self.remap, query)
-
- try:
- file("/tmp/query_log","a").write("remapped query %s\n" % query)
- except:
- pass
-
- storage = Storage(BIGQUERY_CREDENTIALS_FN)
- credentials = storage.get()
-
- if credentials is None or credentials.invalid:
- credentials = run(FLOW, storage)
-
- http = httplib2.Http()
- http = credentials.authorize(http)
-
- service = build('bigquery', 'v2', http=http)
-
- body = {"query": query,
- "timeoutMs": 60000}
- response = service.jobs().query(projectId=PROJECT_NUMBER, body=body).execute()
-
- return response
-
- def translate_schema(self, response):
- for field in response["schema"]["fields"]:
- field["name"] = reverse_mappings[self.tableName].get(field["name"], field["name"])
-
- def run_query(self, query):
- if not BIGQUERY_AVAILABLE:
- print >> sys.stderr, "bigquery_analytics: bigquery flow is not available. returning empty result."
- return []
-
- response = self.run_query_raw(query)
-
- fieldNames = []
- for field in response["schema"]["fields"]:
- fieldNames.append(field["name"])
-
- result = []
- if "rows" in response:
- for row in response["rows"]:
- this_result = {}
- for (i,column) in enumerate(row["f"]):
- this_result[reverse_mappings[self.tableName].get(fieldNames[i],fieldNames[i])] = column["v"]
- result.append(this_result)
-
- return result
-
- """ Filter_results, groupby_results, do_computed_fields, and postprocess_results
- are all used for postprocessing queries. The idea is to do one query that
- includes the ungrouped and unfiltered data, and cache it for multiple
- consumers who will filter and group it as necessary.
-
- TODO: Find a more generalized source for these sorts operations. Perhaps
- put the results in SQLite and then run SQL queries against it.
- """
-
- def filter_results(self, rows, name, value):
- result = [row for row in rows if row.get(name)==value]
- return result
-
- def groupby_results(self, rows, groupBy=[], sum=[], count=[], avg=[], maxi=[]):
- new_rows = {}
- for row in rows:
- groupby_key = [row.get(k, None) for k in groupBy]
-
- if str(groupby_key) not in new_rows:
- new_row = {}
- for k in groupBy:
- new_row[k] = row.get(k, None)
-
- new_rows[str(groupby_key)] = new_row
- else:
- new_row = new_rows[str(groupby_key)]
-
- for k in sum:
- new_row["sum_" + k] = new_row.get("sum_" + k, 0) + to_number(row.get(k,0))
-
- for k in avg:
- new_row["avg_" + k] = new_row.get("avg_" + k, 0) + to_number(row.get(k,0))
- new_row["avg_base_" + k] = new_row.get("avg_base_"+k,0) + 1
-
- for k in maxi:
- new_row["max_" + k] = max(new_row.get("max_" + k, 0), to_number(row.get(k,0)))
-
- for k in count:
- v = row.get(k,None)
- dl = new_row["distinct_" + k] = new_row.get("distinct_" + k, [])
- if (v not in dl):
- dl.append(v)
-
- #new_row["count_" + k] = new_row.get("count_" + k, 0) + 1
-
- for row in new_rows.values():
- for k in avg:
- row["avg_" + k] = float(row["avg_" + k]) / row["avg_base_" + k]
- del row["avg_base_" + k]
-
- for k in count:
- new_row["count_" + k] = len(new_row.get("distinct_" + k, []))
-
- return new_rows.values()
-
- def do_computed_fields(self, rows, computed=[]):
- computedFieldNames=[]
- for row in rows:
- for k in computed:
- if "/" in k:
- parts = k.split("/")
- computedFieldName = "computed_" + parts[0].replace("%","")+"_div_"+parts[1].replace("%","")
- try:
- row[computedFieldName] = to_number(row[parts[0]]) / to_number(row[parts[1]])
- except:
- pass
-
- if computedFieldName not in computedFieldNames:
- computedFieldNames.append(computedFieldName)
- return (computedFieldNames, rows)
-
- def postprocess_results(self, rows, filter={}, groupBy=[], sum=[], count=[], avg=[], computed=[], maxi=[], maxDeltaTime=None):
- sum = [x.replace("%","") for x in sum]
- count = [x.replace("%","") for x in count]
- avg = [x.replace("%","") for x in avg]
- computed = [x.replace("%","") for x in computed]
- maxi = [x.replace("%","") for x in maxi]
- groupBy = [x.replace("%","") for x in groupBy]
-
- for (k,v) in filter.items():
- rows = self.filter_results(rows, k, v)
-
- if rows:
- if maxDeltaTime is not None:
- maxTime = max([float(row["time"]) for row in rows])
- rows = [row for row in rows if float(row["time"])>=maxTime-maxDeltaTime]
-
- (computedFieldNames, rows) = self.do_computed_fields(rows, computed)
- sum = sum + computedFieldNames
- if groupBy:
- rows = self.groupby_results(rows, groupBy, sum, count, avg, maxi)
- return rows
-
- def remap(self, match):
- if not self.tableName in mappings:
- raise MappingException("no mapping for table %s" % self.tableName)
-
- mapping = mappings[self.tableName]
-
- token = match.group()[1:]
- if token in mapping:
- return mapping[token]
- else:
- raise MappingException('unknown token %s' % token)
-
- def dump_table(self, rows, keys=None):
- if not keys:
- keys = rows[0].keys()
-
- lens = {}
- for key in keys:
- lens[key] = len(key)
-
- for row in rows:
- for key in keys:
- thislen = len(str(row.get(key,"")))
- lens[key] = max(lens.get(key,0), thislen)
-
- for key in keys:
- print "%*s" % (lens[key], key),
- print
-
- for row in rows:
- for key in keys:
- print "%*s" % (lens[key], str(row.get(key,""))),
- print
-
- def schema_to_cols(self, schema):
- fields = schema["fields"]
-
- colTypes = {"STRING": "string", "INTEGER": "number", "FLOAT": "number", "TIMESTAMP": "date"}
-
- cols = []
- i=0
- for field in fields:
- col = {"type": colTypes[field["type"]],
- "id": "Col%d" % i,
- "label": reverse_mappings[self.tableName].get(field["name"],field["name"])}
- cols.append(col)
- i=i+1
-
- return cols
-
-def main():
- bq = BigQueryAnalytics()
-
- rows = bq.run_query("select %hostname,SUM(%bytes_sent) from [vicci.demoevents] group by %hostname")
-
- bq.dump_table(rows)
-
-if __name__ == "__main__":
- main()
diff --git a/xos/hpc_wizard/bigquery_config.py b/xos/hpc_wizard/bigquery_config.py
deleted file mode 100644
index 345acf2..0000000
--- a/xos/hpc_wizard/bigquery_config.py
+++ /dev/null
@@ -1,3 +0,0 @@
-BIGQUERY_DIR = "/opt/xos"
-BIGQUERY_SECRETS_FN = os.path.join(BIGQUERY_DIR, "hpc_wizard/client_secrets.json")
-BIGQUERY_CREDENTIALS_FN = os.path.join(BIGQUERY_DIR, "hpc_wizard/bigquery_credentials.dat")
diff --git a/xos/hpc_wizard/query.py b/xos/hpc_wizard/query.py
deleted file mode 100644
index 874022e..0000000
--- a/xos/hpc_wizard/query.py
+++ /dev/null
@@ -1,278 +0,0 @@
-import re
-import base64
-import requests
-import urllib
-import json
-import httplib2
-import threading
-import os
-import time
-import traceback
-
-from apiclient.discovery import build
-from apiclient.errors import HttpError
-from oauth2client.client import AccessTokenRefreshError
-from oauth2client.client import OAuth2WebServerFlow
-from oauth2client.client import flow_from_clientsecrets
-from oauth2client.file import Storage
-from oauth2client.tools import run_flow,run
-
-from bigquery_config import BIGQUERY_SECRETS_FN, BIGQUERY_CREDENTIALS_FN
-
-"""
-yum -y install python-httplib2
-easy_install python_gflags
-easy_install google_api_python_client
-"""
-
-
-PROJECT_NUMBER = '549187599759'
-
-try:
- FLOW = flow_from_clientsecrets(BIGQUERY_SECRETS_FN,
- scope='https://www.googleapis.com/auth/bigquery')
-except:
- print "exception while initializing bigquery flow"
- traceback.print_exc()
- FLOW = None
-
-MINUTE_MS = 60*1000
-HOUR_MS = 60*60*1000
-
-class HpcQuery:
- def __init__(self):
- self.mapping = json.loads(self.fetch_mapping(table="demoevents"))
- self.reverse_mapping = {v:k for k, v in self.mapping.items()}
-
- def fetch_mapping(self, m=0, table="events"):
- req = 'http://cloud-scrutiny.appspot.com/command?action=get_allocations&multiplexer=%d&table=%s'% (m,table)
- resp = requests.get(req)
- if (resp.status_code==200):
- return resp.text
- else:
- raise Exception('Error accessing register allocations: %d'%resp.status_code)
-
- def run_query_old(self, query):
- req = 'http://cloud-scrutiny.appspot.com/command?action=send_query&q=%s' % urllib.quote(query)
- resp = requests.get(req)
- if (resp.status_code==200):
- return resp.text
- else:
- raise Exception('Error running query: %d'%resp.status_code)
- return resp
-
- def run_query(self, query):
- storage = Storage(BIGQUERY_CREDENTIALS_FN)
- credentials = storage.get()
-
- if credentials is None or credentials.invalid:
- credentials = run(FLOW, storage)
-
- http = httplib2.Http()
- http = credentials.authorize(http)
-
- service = build('bigquery', 'v2', http=http)
-
- body = {"query": query}
- response = service.jobs().query(projectId=PROJECT_NUMBER, body=body).execute()
-
- fieldNames = []
- for field in response["schema"]["fields"]:
- fieldNames.append(field["name"])
-
- result = []
- if "rows" in response:
- for row in response["rows"]:
- this_result = {}
- for (i,column) in enumerate(row["f"]):
- this_result[self.reverse_mapping.get(fieldNames[i],fieldNames[i])] = column["v"]
- result.append(this_result)
-
- return result
-
- def remap(self, match):
- token = match.group()[1:]
- if token in self.mapping:
- return self.mapping[token]
- else:
- raise Exception('unknown token %s' % token)
-
- def get_usage(self, cp=None, hostname=None, site=None, slice=None, timeStart=-HOUR_MS, timeStop=-1, groupBy=["%hostname", "%cp"]):
- where = []
- if slice is not None:
- where.append("%slice='" + slice + "'")
- if cp is not None:
- where.append("%cp='" + cp + "'")
- if hostname is not None:
- where.append("%hostname='" + hostname + "'")
- if site is not None:
- where.append("%hostname contains " + site)
- where.append("%bytes_sent>0")
- where = "WHERE " + " AND ".join(where)
-
- if timeStart is not None:
- tableName = "[vicci.demoevents@%d-%d]" % (timeStart,timeStop)
- else:
- tableName = "[vicci.demoevents]"
-
- query = "SELECT %hostname,%cp,sum(%bytes_sent) as sum_bytes_sent,sum(%bytes_hit) as sum_bytes_hit, AVG(%bandwidth) as avg_bandwidth," + \
- " MAX(TIMESTAMP_TO_MSEC(time))-MIN(TIMESTAMP_TO_MSEC(time)) as time_delta FROM " + \
- tableName + " " + where
-
- if groupBy:
- query = query + " GROUP BY " + ",".join(groupBy)
-
- p = re.compile('%[a-zA-z_]*')
- query = p.sub(self.remap, query)
-
- rows = self.run_query(query)
-
- for row in rows:
- row["sum_bytes_sent"] = int(row.get("sum_bytes_sent",0))
- row["sum_bytes_hit"] = int(row.get("sum_bytes_hit",0))
- row["avg_bandwidth"] = int(float(row.get("avg_bandwidth",0)))
- row["time_delta"] = float(row.get("time_delta",0.0))/1000.0
-
- elapsed = (timeStop-timeStart)/1000
- KBps = int(row.get("sum_bytes_sent",0)) / elapsed / 1024
- row["KBps"] = KBps
-
- return rows
-
- def sites_from_usage(self, rows, nodes_to_sites={}):
- sites = {}
- for row in rows:
- hostname = row["hostname"]
-
- if hostname in nodes_to_sites:
- site_name = nodes_to_sites[hostname]
- else:
- parts = hostname.split(".")
- if len(parts)<=2:
- continue
- site_name = parts[1]
-
- if not (site_name in sites):
- row = row.copy()
- row["site"] = site_name
- row["max_avg_bandwidth"] = row["avg_bandwidth"]
- # sites table doesn't care about hostnames or avg_bandwidth
- del row["hostname"]
- del row["avg_bandwidth"]
- sites[site_name] = row
- else:
- site_row = sites[site_name]
- site_row["sum_bytes_sent"] = site_row["sum_bytes_sent"] + row["sum_bytes_sent"]
- site_row["sum_bytes_hit"] = site_row["sum_bytes_hit"] + row["sum_bytes_hit"]
- site_row["max_avg_bandwidth"] = max(site_row["max_avg_bandwidth"], row["avg_bandwidth"])
- site_row["time_delta"] = max(site_row["time_delta"], row["time_delta"])
-
- return sites.values()
-
- def get_usage_sites(self, cp=None, slice=None, timeStart=-HOUR_MS, timeStop=-1):
- rows = self.get_usage(cp=cp, slice=slice, timeStart=timeStart, timeStop=timeStop)
-
- return self.sites_from_usage(rows)
-
- def dump_table(self, rows, keys=None):
- if not keys:
- keys = rows[0].keys()
-
- lens = {}
- for key in keys:
- lens[key] = len(key)
-
- for row in rows:
- for key in keys:
- thislen = len(str(row.get(key,"")))
- lens[key] = max(lens.get(key,0), thislen)
-
- for key in keys:
- print "%*s" % (lens[key], key),
- print
-
- for row in rows:
- for key in keys:
- print "%*s" % (lens[key], str(row.get(key,""))),
- print
-
-class HpcQueryThread(HpcQuery, threading.Thread):
- def __init__(self, interval=30, slice=None, timeStart=-HOUR_MS, cp=None, nodes_to_sites={}):
- threading.Thread.__init__(self)
- HpcQuery.__init__(self)
- self.daemon = True
- self.interval = interval
- self.timeStart = timeStart
- self.nodes_to_sites = nodes_to_sites
- self.slice = slice
- self.cp = cp
- self.data_version = 0
- self.please_die = False
- self.update_time = time.time()
- self.start()
-
- def is_stalled(self):
- if time.time()-self.update_time > 300:
- return True
- else:
- return False
-
- def run(self):
- while not self.please_die:
- try:
- self.rows = self.get_usage(timeStart=self.timeStart, cp=self.cp, slice=self.slice)
- self.site_rows = self.sites_from_usage(self.rows, self.nodes_to_sites)
- self.update_time = time.time()
- self.new_data()
- self.data_version += 1
- except:
- file("/tmp/hpcquery_fail.txt","a").write(traceback.format_exc() + "\n")
- time.sleep(self.interval)
-
- def new_data(self):
- pass
-
-class HpcDumpThread(HpcQueryThread):
- def __init__(self, interval=30, slice=None, timeStart=-HOUR_MS, cp=None):
- HpcQueryThread.__init__(self, interval, slice, timeStart, cp)
-
- def new_data(self):
- os.system("clear")
-
- print "update %d, data for last %d minutes" % (self.data_version, -self.timeStart/1000/60)
- print
-
- self.dump_table(self.rows, ["hostname", "cp", "sum_bytes_sent", "sum_bytes_hit", "KBps"])
- print
- self.dump_table(self.site_rows, ["site", "cp", "sum_bytes_sent", "sum_bytes_hit", "KBps"])
- print
-
-
-def main_old():
- hq = HpcQuery()
-# print hq.mapping
-
- print "5 minute"
- hq.dump_table(hq.get_usage(timeStart=-MINUTE_MS*5), ["hostname", "cp", "sum_bytes_sent", "sum_bytes_hit", "KBps"])
- print
- hq.dump_table(hq.get_usage_sites(timeStart=-MINUTE_MS*5), ["site", "cp", "sum_bytes_sent", "sum_bytes_hit", "KBps"])
- print
-
- print "1 hour"
- hq.dump_table(hq.get_usage(), ["hostname", "cp", "sum_bytes_sent", "sum_bytes_hit", "KBps"])
- print
- hq.dump_table(hq.get_usage_sites(), ["site", "cp", "sum_bytes_sent", "sum_bytes_hit", "KBps"])
- print
-
- print "24 hours"
- hq.dump_table(hq.get_usage(timeStart=-HOUR_MS*24), ["hostname", "cp", "sum_bytes_sent", "sum_bytes_hit", "KBps"])
- hq.dump_table(hq.get_usage_sites(timeStart=-HOUR_MS*24), ["site", "cp", "sum_bytes_sent", "sum_bytes_hit", "KBps"])
- print
-
-def main():
- hd = HpcDumpThread()
- while True:
- time.sleep(30)
-
-if __name__ == "__main__":
- main()
diff --git a/xos/hpc_wizard/xos_analytics.py b/xos/hpc_wizard/xos_analytics.py
deleted file mode 100644
index 9502aa1..0000000
--- a/xos/hpc_wizard/xos_analytics.py
+++ /dev/null
@@ -1,475 +0,0 @@
-from bigquery_analytics import BigQueryAnalytics, BIGQUERY_AVAILABLE
-import datetime
-import re
-import os
-import sys
-import time
-import json
-import traceback
-import urllib2
-
-# XXX hardcoded path
-sys.path.append("/opt/xos")
-
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-from django.conf import settings
-from django import db
-from django.db import connection
-from core.models import Slice, Instance, ServiceClass, Reservation, Tag, Network, User, Node, Image, Deployment, Site, NetworkTemplate, NetworkSlice, Service
-
-BLUE_LOAD=5000000
-RED_LOAD=15000000
-
-glo_cached_queries = {}
-
-class XOSAnalytics(BigQueryAnalytics):
- def __init__(self, tableName=None):
- if not tableName:
- tableName = settings.BIGQUERY_TABLE
-
- BigQueryAnalytics.__init__(self, tableName)
-
- def service_to_sliceNames(self, serviceName):
- service=Service.objects.get(name=serviceName)
- try:
- slices = service.slices.all()
- except:
- # BUG in data model -- Slice.service has related name 'service' and
- # it should be 'slices'
- slices = service.service.all()
-
- return [slice.name for slice in slices]
-
- def compose_query(self, filter={}, timeBucket="60", avg=[], sum=[], count=[], computed=[], val=[], groupBy=["Time"], orderBy=["Time"], tableName=None, latest=False, maxAge=60*60):
- if tableName is None:
- tableName = self.tableName
-
- maxAge = maxAge * 1000
- tablePart = "[%s.%s@-%d--1]" % ("vicci", tableName, maxAge)
-
- fields = []
- fieldNames = []
- srcFieldNames = ["time"]
-
- fields.append("SEC_TO_TIMESTAMP(INTEGER(TIMESTAMP_TO_SEC(time)/%s)*%s) as Time" % (str(timeBucket),str(timeBucket)))
- #fields.append("INTEGER(TIMESTAMP_TO_SEC(time)/%s)*%s as Time" % (str(timeBucket),str(timeBucket)))
-
- for fieldName in avg:
- fields.append("AVG(%s) as avg_%s" % (fieldName, fieldName.replace("%","")))
- fieldNames.append("avg_%s" % fieldName.replace("%",""))
- srcFieldNames.append(fieldName)
-
- for fieldName in sum:
- fields.append("SUM(%s) as sum_%s" % (fieldName, fieldName.replace("%","")))
- fieldNames.append("sum_%s" % fieldName.replace("%",""))
- srcFieldNames.append(fieldName)
-
- for fieldName in count:
- fields.append("COUNT(distinct %s) as count_%s" % (fieldName, fieldName.replace("%","")))
- fieldNames.append("count_%s" % fieldName.replace("%",""))
- srcFieldNames.append(fieldName)
-
- for fieldName in val:
- fields.append(fieldName)
- fieldNames.append(fieldName)
- srcFieldNames.append(fieldName)
-
- for fieldName in computed:
- operator = "/"
- parts = fieldName.split("/")
- computedFieldName = "computed_" + parts[0].replace("%","")+"_div_"+parts[1].replace("%","")
- if len(parts)==1:
- operator = "*"
- parts = computed.split("*")
- computedFieldName = "computed_" + parts[0].replace("%","")+"_mult_"+parts[1].replace("%","")
- fields.append("SUM(%s)%sSUM(%s) as %s" % (parts[0], operator, parts[1], computedFieldName))
- fieldNames.append(computedFieldName)
- srcFieldNames.append(parts[0])
- srcFieldNames.append(parts[1])
-
- for fieldName in groupBy:
- if (fieldName not in ["Time"]):
- fields.append(fieldName)
- fieldNames.append(fieldName)
- srcFieldNames.append(fieldName)
-
- fields = ", ".join(fields)
-
- where = []
-
- if filter.get("slice",None):
- where.append("%%slice='%s'" % filter["slice"])
- if filter.get("site",None):
- where.append("%%site='%s'" % filter["site"])
- if filter.get("node",None):
- where.append("%%hostname='%s'" % filter["node"])
- if filter.get("event",None):
- where.append("event='%s'" % filter["event"])
- if filter.get("service",None):
- sliceNames = self.service_to_sliceNames(filter["service"])
- if sliceNames:
- where.append("(" + " OR ".join(["%%slice='%s'" % sliceName for sliceName in sliceNames]) +")")
-
- if where:
- where = " WHERE " + " AND ".join(where)
- else:
- where =""
-
- if groupBy:
- groupBySub = " GROUP BY " + ",".join(groupBy + ["%hostname"])
- groupBy = " GROUP BY " + ",".join(groupBy)
- else:
- groupBySub = " GROUP BY %hostname"
- groupBy = ""
-
- if orderBy:
- orderBy = " ORDER BY " + ",".join(orderBy)
- else:
- orderBy = ""
-
- if latest:
- latestFields = ["table1.%s as %s" % (x,x) for x in srcFieldNames]
- latestFields = ", ".join(latestFields)
- tablePart = """(SELECT %s FROM %s AS table1
- JOIN
- (SELECT %%hostname, event, max(time) as maxtime from %s GROUP BY %%hostname, event) AS latest
- ON
- table1.%%hostname = latest.%%hostname AND table1.event = latest.event AND table1.time = latest.maxtime)""" % (latestFields, tablePart, tablePart)
-
- if computed:
- subQuery = "SELECT %%hostname, %s FROM %s" % (fields, tablePart)
- if where:
- subQuery = subQuery + where
- subQuery = subQuery + groupBySub
-
- sumFields = []
- for fieldName in fieldNames:
- if fieldName.startswith("avg"):
- sumFields.append("AVG(%s) as avg_%s"%(fieldName,fieldName))
- sumFields.append("MAX(%s) as max_%s"%(fieldName,fieldName))
- elif (fieldName.startswith("count")) or (fieldName.startswith("sum")) or (fieldName.startswith("computed")):
- sumFields.append("SUM(%s) as sum_%s"%(fieldName,fieldName))
- else:
- sumFields.append(fieldName)
-
- sumFields = ",".join(sumFields)
-
- query = "SELECT %s, %s FROM (%s)" % ("Time", sumFields, subQuery)
- if groupBy:
- query = query + groupBy
- if orderBy:
- query = query + orderBy
- else:
- query = "SELECT %s FROM %s" % (fields, tablePart)
- if where:
- query = query + " " + where
- if groupBy:
- query = query + groupBy
- if orderBy:
- query = query + orderBy
-
- return query
-
- def get_list_from_req(self, req, name, default=[]):
- value = req.GET.get(name, None)
- if not value:
- return default
- value=value.replace("@","%")
- return value.split(",")
-
- def format_result(self, format, result, query, dataSourceUrl):
- if not BIGQUERY_AVAILABLE:
- msg = "BigQuery Statistics Unavaiable"
- else:
- msg = None
-
- if (format == "json_dicts"):
- result = {"query": query, "rows": result, "dataSourceUrl": dataSourceUrl, "msg": msg}
- return ("application/javascript", json.dumps(result))
-
- elif (format == "json_arrays"):
- new_result = []
- for row in result:
- new_row = []
- for key in sorted(row.keys()):
- new_row.append(row[key])
- new_result.append(new_row)
- new_result = {"query": query, "rows": new_result, "msg": msg}
- return ("application/javascript", json.dumps(new_result))
-
- elif (format == "html_table"):
- new_rows = []
- for row in result:
- new_row = []
- for key in sorted(row.keys()):
- new_row.append("<TD>%s</TD>" % str(row[key]))
- new_rows.append("<TR>%s</TR>" % "".join(new_row))
-
- new_result = "<TABLE>%s</TABLE>" % "\n".join(new_rows)
-
- return ("text/html", new_result)
-
- def merge_datamodel_sites(self, rows, slice=None):
- """ For a query that included "site" in its groupby, merge in the
- opencloud site information.
- """
-
- if slice:
- try:
- slice = Slice.objects.get(name=slice)
- except:
- slice = None
-
- for row in rows:
- sitename = row["site"]
- try:
- model_site = Site.objects.get(name=sitename)
- except:
- # we didn't find it in the data model
- continue
-
- allocated_instances = 0
- if model_site and slice:
- for instance in slice.instances.all():
- if instance.node.site == model_site:
- allocated_instances = allocated_instances + 1
-
- row["lat"] = float(model_site.location.latitude)
- row["long"] = float(model_site.location.longitude)
- row["url"] = model_site.site_url
- row["numNodes"] = model_site.nodes.count()
- row["allocated_instances"] = allocated_instances
-
- max_cpu = row.get("max_avg_cpu", row.get("max_cpu",0))
- cpu=float(max_cpu)/100.0
- row["hotness"] = max(0.0, ((cpu*RED_LOAD) - BLUE_LOAD)/(RED_LOAD-BLUE_LOAD))
-
- def compose_cached_query(self, querySpec='default'):
- """ Compose a query that returns the 'most recent' row for each (hostname, event)
- pair.
-
- Note that groupByFields cannot contain any values that are 'Null' or those
- rows will be excluded. For example, if groupByFields includes cp, then
- there will be no libvirt_event rows, since libvirt_event does not have
- cp.
-
- This means we can't really have 'one query to rule them'. Settle on
- having a couple of different queries, and have the caller specify
- which one he wants.
- """
-
- fieldNames = ["%hostname", "%bytes_sent", "%bytes_hit", "%healthy", "time", "event", "%site", "%elapsed", "%cpu"]
-
- if querySpec=="default":
- groupByFields = ["%hostname", "event"]
- elif (querySpec=="hpc"):
- fieldNames.append("%cp")
- groupByFields = ["%hostname", "event", "%cp"]
- else:
- raise ValueError("Unknown queryspec %s" % querySpec)
-
- fields = ["table1.%s AS %s" % (x,x) for x in fieldNames]
- fields = ", ".join(fields)
-
- tableDesc = "%s.%s" % (self.projectName, self.tableName)
-
- groupByOn = ["table1.time = latest.maxtime"]
- for field in groupByFields:
- groupByOn.append("table1.%s = latest.%s" % (field, field))
-
- groupByOn = " AND ".join(groupByOn)
- groupByFields = ", ".join(groupByFields)
-
- base_query = "SELECT %s FROM [%s@-3600000--1] AS table1 JOIN (SELECT %s, max(time) as maxtime from [%s@-3600000--1] GROUP BY %s) AS latest ON %s" % \
- (fields, tableDesc, groupByFields, tableDesc, groupByFields, groupByOn)
-
- return base_query
-
- def get_cached_query_results(self, q, wait=True):
- global glo_cached_queries
-
- if q in glo_cached_queries:
- if (time.time() - glo_cached_queries[q]["time"]) <= 60:
- print "using cached query"
- return glo_cached_queries[q]["rows"]
-
- if not wait:
- return None
-
- print "refreshing cached query"
- result = self.run_query(q)
- glo_cached_queries[q] = {"time": time.time(), "rows": result}
-
- return result
-
- def process_request(self, req):
- print req.GET
-
- tqx = req.GET.get("tqx", None)
-
- slice = req.GET.get("slice", None)
- site = req.GET.get("site", None)
- node = req.GET.get("node", None)
- service = req.GET.get("service", None)
- event = req.GET.get("event", "libvirt_heartbeat")
- cp = req.GET.get("cp", None)
-
- format = req.GET.get("format", "json_dicts")
-
- timeBucket = int(req.GET.get("timeBucket", 60))
- avg = self.get_list_from_req(req, "avg")
- sum = self.get_list_from_req(req, "sum")
- count = self.get_list_from_req(req, "count")
- computed = self.get_list_from_req(req, "computed")
- groupBy = self.get_list_from_req(req, "groupBy", ["Time"])
- orderBy = self.get_list_from_req(req, "orderBy", ["Time"])
-
- maxRows = req.GET.get("maxRows", None)
- mergeDataModelSites = req.GET.get("mergeDataModelSites", None)
-
- maxAge = int(req.GET.get("maxAge", 60*60))
-
- cached = req.GET.get("cached", None)
- cachedGroupBy = self.get_list_from_req(req, "cachedGroupBy", ["doesnotexist"])
-
- filter={}
- if slice:
- filter["slice"] = slice
- if site:
- filter["site"] = site
- if node:
- filter["hostname"] = node
- if event:
- filter["event"] = event
- if cp:
- filter["cp"] = cp
-
- q = self.compose_query(filter, timeBucket, avg, sum, count, computed, [], groupBy, orderBy, maxAge=maxAge)
-
- print q
-
- dataSourceUrl = "http://" + req.META["SERVER_NAME"] + ":" + req.META["SERVER_PORT"] + req.META["PATH_INFO"] + "?" + req.META["QUERY_STRING"].replace("format=","origFormat=").replace("%","%25") + "&format=charts";
-
- if (format=="dataSourceUrl"):
- result = {"dataSourceUrl": dataSourceUrl}
- return ("application/javascript", result)
-
- elif (format=="raw"):
- result = self.run_query_raw(q)
- result["dataSourceUrl"] = dataSourceUrl
-
- result = json.dumps(result);
-
- return ("application/javascript", result)
-
- elif (format=="nodata"):
- result = {"dataSourceUrl": dataSourceUrl, "query": q}
- result = json.dumps(result);
- return {"application/javascript", result}
-
- elif (format=="charts"):
- bq_result = self.run_query_raw(q)
-
- # cloudscrutiny code is probably better!
- table = {}
- table["cols"] = self.schema_to_cols(bq_result["schema"])
- rows = []
- if "rows" in bq_result:
- for row in bq_result["rows"]:
- rowcols = []
- for (colnum,col) in enumerate(row["f"]):
- if (colnum==0):
- dt = datetime.datetime.fromtimestamp(float(col["v"]))
- rowcols.append({"v": 'new Date("%s")' % dt.isoformat()})
- else:
- try:
- rowcols.append({"v": float(col["v"])})
- except:
- rowcols.append({"v": col["v"]})
- rows.append({"c": rowcols})
- table["rows"] = rows
-
- if tqx:
- reqId = tqx.strip("reqId:")
- else:
- reqId = "0"
-
- result = {"status": "okColumnChart", "reqId": reqId, "table": table, "version": "0.6"}
-
- result = "google.visualization.Query.setResponse(" + json.dumps(result) + ");"
-
- def unquote_it(x): return x.group()[1:-1].replace('\\"', '"')
-
- p = re.compile(r'"new Date\(\\"[^"]*\\"\)"')
- result=p.sub(unquote_it, result)
-
- return ("application/javascript", result)
-
- else:
- if cached:
- results = self.get_cached_query_results(self.compose_cached_query(cached))
-
- result = self.postprocess_results(results, filter=filter, sum=sum, count=count, avg=avg, computed=computed, maxDeltaTime=120, groupBy=cachedGroupBy)
- else:
- result = self.run_query(q)
-
- if maxRows:
- result = result[-int(maxRows):]
-
- if mergeDataModelSites:
- self.merge_datamodel_sites(result)
-
- return self.format_result(format, result, q, dataSourceUrl)
-
-def DoXOSAnalytics(request):
- bq = XOSAnalytics()
- result = bq.process_request(request)
-
- return result
-
-def main():
- bq = XOSAnalytics(tableName="demoevents")
-
- q = bq.compose_cached_query()
- results = bq.run_query(q)
-
- #results = bq.postprocess_results(results,
- # filter={"slice": "HyperCache"},
- # groupBy=["site"],
- # computed=["bytes_sent/elapsed"],
- # sum=["bytes_sent", "computed_bytes_sent_div_elapsed"], avg=["cpu"],
- # maxDeltaTime=60)
-
- #results = bq.postprocess_results(results, filter={"slice": "HyperCache"}, maxi=["cpu"], count=["hostname"], computed=["bytes_sent/elapsed"], groupBy=["Time", "site"], maxDeltaTime=80)
-
- results = bq.postprocess_results(results,filter={"event": "libvirt_heartbeat"}, avg=["cpu"], count=["hostname"], groupBy=["doesnotexist"])
-
- bq.dump_table(results)
-
- sys.exit(0)
-
- q=bq.compose_query(sum=["%bytes_sent"], avg=["%cpu"], latest=True, groupBy=["Time", "%site"])
- print q
- bq.dump_table(bq.run_query(q))
-
- q=bq.compose_query(avg=["%cpu","%bandwidth"], count=["%hostname"], slice="HyperCache")
- print q
- bq.dump_table(bq.run_query(q))
-
- q=bq.compose_query(computed=["%bytes_sent/%elapsed"])
- print
- print q
- bq.dump_table(bq.run_query(q))
-
- q=bq.compose_query(timeBucket=60*60, avg=["%cpu"], count=["%hostname"], computed=["%bytes_sent/%elapsed"])
- print
- print q
- bq.dump_table(bq.run_query(q))
-
-if __name__ == "__main__":
- main()
-
-
-
-
-
diff --git a/xos/importer/__init__.py b/xos/importer/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/xos/importer/__init__.py
+++ /dev/null
diff --git a/xos/importer/plclassic/__init__.py b/xos/importer/plclassic/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/xos/importer/plclassic/__init__.py
+++ /dev/null
diff --git a/xos/importer/plclassic/importer.py b/xos/importer/plclassic/importer.py
deleted file mode 100644
index de8628b..0000000
--- a/xos/importer/plclassic/importer.py
+++ /dev/null
@@ -1,70 +0,0 @@
-import os
-#os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-import sys
-from optparse import OptionParser
-from getpass import getpass
-import xmlrpclib
-from plclassic.site_importer import SiteImporter
-from plclassic.user_importer import UserImporter
-from plclassic.slice_importer import SliceImporter
-from plclassic.instance_importer import InstanceImporter
-
-
-class Call:
- def __init__(self, callable, auth):
- self.callable = callable
- self.auth = auth
-
- def __call__(self, *args, **kwds):
- a = [self.auth] + list(args)
- return self.callable(*a)
-
-class API():
- def __init__(self, username, password, url):
- self.auth = {'AuthMethod': 'password',
- 'Username': username,
- 'AuthString': password}
- self.server = xmlrpclib.ServerProxy(url, allow_none=True)
-
- def __getattr__(self, name):
- return Call(getattr(self.server, name), self.auth)
-
-class Importer:
-
- def __init__(self, username, password, url):
- api = API(username, password, url)
- self.sites = SiteImporter(api)
- self.slices = SliceImporter(api)
- self.users = UserImporter(api)
- self.instances = InstanceImporter(api)
-
- def run(self):
- self.sites.run()
- self.users.run()
- self.slices.run(remote_sites=self.sites.remote_sites,
- local_sites=self.sites.local_sites)
- self.instances.run()
-
-
-
-if __name__ == '__main__':
- parser = OptionParser()
-
- parser.add_option("-u", "--username", dest="username",
- help="PLC username with which to authenticate")
- parser.add_option("", "--url", dest="url",
- help="PLC url to contact")
-
- (config, args) = parser.parse_args()
- if len(sys.argv) == 1:
- parser.print_help()
- sys.exit(1)
-
- password = None
- try:
- password = getpass()
- except (EOFError, KeyboardInterrupt):
- print
- sys.exit(0)
-
- Importer(config.username, password, config.url).run()
diff --git a/xos/importer/plclassic/instance_importer.py b/xos/importer/plclassic/instance_importer.py
deleted file mode 100644
index 0858572..0000000
--- a/xos/importer/plclassic/instance_importer.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from PLC.Nodes import Nodes
-
-class InstanceImporter:
-
- def __init__(self, api):
- self.api = api
-
- def run(self):
- return
diff --git a/xos/importer/plclassic/role_importer.py b/xos/importer/plclassic/role_importer.py
deleted file mode 100644
index 107587a..0000000
--- a/xos/importer/plclassic/role_importer.py
+++ /dev/null
@@ -1,9 +0,0 @@
-class RoleImporter:
-
- def __init__(self, api):
- self.api = api
-
- def run(self):
-
- return
-
diff --git a/xos/importer/plclassic/site_importer.py b/xos/importer/plclassic/site_importer.py
deleted file mode 100644
index 2ee8157..0000000
--- a/xos/importer/plclassic/site_importer.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from core.models import Site
-
-class SiteImporter:
-
- def __init__(self, api):
- self.api = api
- self.remote_sites = {}
- self.local_sites = {}
-
- def run(self):
- db_sites = Site.objects.all()
- for db_site in db_sites:
- self.local_sites[db_site.login_base] = db_site
- print "%s local sites" % len(db_sites)
-
- sites = self.api.GetSites({'peer_id': None})
- print "%s remote sites" % len(sites)
- count = 0
- for site in sites:
- self.remote_sites[site['site_id']] = site
- if site['login_base'] not in self.local_sites:
- new_site = Site(name=site['name'],
- login_base=site['login_base'],
- site_url=site['url'],
- enabled=site['enabled'],
- longitude=site['longitude'],
- latitude=site['latitude'],
- is_public=site['is_public'],
- abbreviated_name=site['abbreviated_name'])
- new_site.save()
- count += 1
- self.local_sites[new_site.login_base] = new_site
- print "imported %s sites" % count
diff --git a/xos/importer/plclassic/slice_importer.py b/xos/importer/plclassic/slice_importer.py
deleted file mode 100644
index b2dd84f..0000000
--- a/xos/importer/plclassic/slice_importer.py
+++ /dev/null
@@ -1,46 +0,0 @@
-from core.models import Slice
-
-class SliceImporter:
-
- def __init__(self, api):
- self.api = api
- self.remote_slices = {}
- self.local_slices = {}
-
- def run(self, remote_sites={}, local_sites={}):
- if not remote_sites:
- sites = self.api.GetSites({'peer_id': None})
- for site in sites:
- remote_sites[site['site_id']] = site
-
-
- if not local_sites:
- from core.models import Site
- sites = Site.objects.all()
- for site in sites:
- local_sites[site.login_base] = site
-
- db_slices = Slice.objects.all()
- for db_slice in db_slices:
- self.local_slices[db_slice.name] = db_slice
- print "%s local slices" % len(db_slices)
-
- slices = self.api.GetSlices({'peer_id': None})
- print "%s remote slices" % len(slices)
- count = 0
- for slice in slices:
- self.remote_slices[slice['slice_id']] = slice
- if slice['name'] not in self.local_slices:
- site = local_sites[remote_sites[slice['site_id']]['login_base']]
- new_slice = Slice(name=slice['name'],
- omf_friendly = False,
- description = slice['description'],
- slice_url = slice['url'],
- site = site)
- new_slice.save()
- count += 1
- self.local_slices[new_slice.name] = new_slice
- print "Imported %s slices" % count
-
-
-
diff --git a/xos/importer/plclassic/user_importer.py b/xos/importer/plclassic/user_importer.py
deleted file mode 100644
index 21d74b6..0000000
--- a/xos/importer/plclassic/user_importer.py
+++ /dev/null
@@ -1,19 +0,0 @@
-
-class UserImporter:
-
- def __init__(self, api):
- self.api = api
- self.users = {}
-
- def run(self):
- users = self.api.GetPersons()
-
- def save_site_privs(self, user):
- # update site roles
- pass
-
- def save_slice_privs(self, user):
- # update slice roles
- pass
-
-
diff --git a/xos/manage.py b/xos/manage.py
index 5d09794..219d0e7 100644
--- a/xos/manage.py
+++ b/xos/manage.py
@@ -3,21 +3,22 @@
import sys
if __name__ == "__main__":
+ os.chdir('..') # <<<---This is what you want to add
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
from django.core.management import execute_from_command_line
if "--makemigrations" in sys.argv:
- os.system("/opt/xos/scripts/opencloud makemigrations")
+ os.system("/opt/xos/tools/xos-manage makemigrations")
sys.argv.remove("--makemigrations")
if "--nomodelpolicy" in sys.argv:
- import model_policy
+ import synchronizers.model_policy as model_policy
model_policy.EnableModelPolicy(False)
sys.argv.remove("--nomodelpolicy")
if "--noobserver" in sys.argv:
- import observer
+ import synchronizers.base as observer
observer.EnableObserver(False)
sys.argv.remove("--noobserver")
diff --git a/xos/model_policies/model_policy_ControllerSlice.py b/xos/model_policies/model_policy_ControllerSlice.py
deleted file mode 100644
index 1861c66..0000000
--- a/xos/model_policies/model_policy_ControllerSlice.py
+++ /dev/null
@@ -1,16 +0,0 @@
-def handle(controller_slice):
- from core.models import ControllerSlice, Slice
-
- try:
- my_status_code = int(controller_slice.backend_status[0])
- try:
- his_status_code = int(controller_slice.slice.backend_status[0])
- except:
- his_status_code = 0
-
- if (my_status_code not in [0,his_status_code]):
- controller_slice.slice.backend_status = controller_slice.backend_status
- controller_slice.slice.save(update_fields = ['backend_status'])
- except Exception,e:
- print str(e)
- pass
diff --git a/xos/model_policies/model_policy_Slice.py b/xos/model_policies/model_policy_Slice.py
deleted file mode 100644
index bbfbcc4..0000000
--- a/xos/model_policies/model_policy_Slice.py
+++ /dev/null
@@ -1,87 +0,0 @@
-def handle_delete(slice):
- from core.models import Controller, ControllerSlice, SiteDeployment, Network, NetworkSlice,NetworkTemplate, Slice
- from collections import defaultdict
-
- public_nets = []
- private_net = None
- networks = Network.objects.filter(owner=slice)
-
- for n in networks:
- n.delete()
-
- # Note that sliceprivileges and slicecontrollers are autodeleted, through the dependency graph
-
-def handle(slice):
- from core.models import Controller, ControllerSlice, SiteDeployment, Network, NetworkSlice,NetworkTemplate, Slice
- from collections import defaultdict
-
- print "MODEL POLICY: slice", slice
-
- # slice = Slice.get(slice_id)
-
- controller_slices = ControllerSlice.objects.filter(slice=slice)
- existing_controllers = [cs.controller for cs in controller_slices]
-
- print "MODEL POLICY: slice existing_controllers=", existing_controllers
-
- all_controllers = Controller.objects.all()
- for controller in all_controllers:
- if controller not in existing_controllers:
- print "MODEL POLICY: slice adding controller", controller
- sd = ControllerSlice(slice=slice, controller=controller)
- sd.save()
-
- # make sure slice has at least 1 public and 1 private networkd
- public_nets = []
- private_nets = []
- networks = Network.objects.filter(owner=slice)
- for network in networks:
- if not network.autoconnect:
- continue
- if network.template.name == 'Public dedicated IPv4':
- public_nets.append(network)
- elif network.template.name == 'Public shared IPv4':
- public_nets.append(network)
- elif network.template.name == 'Private':
- private_nets.append(network)
- if not public_nets:
- # ensure there is at least one public network, and default it to dedicated
- nat_net = Network(
- name = slice.name+'-nat',
- template = NetworkTemplate.objects.get(name='Public shared IPv4'),
- owner = slice
- )
- nat_net.save()
- public_nets.append(nat_net)
- print "MODEL POLICY: slice", slice, "made nat-net"
-
- if not private_nets:
- private_net = Network(
- name = slice.name+'-private',
- template = NetworkTemplate.objects.get(name='Private'),
- owner = slice
- )
- private_net.save()
- print "MODEL POLICY: slice", slice, "made private net"
- private_nets = [private_net]
- # create slice networks
- public_net_slice = None
- private_net_slice = None
- net_slices = NetworkSlice.objects.filter(slice=slice, network__in=private_nets+public_nets)
- for net_slice in net_slices:
- if net_slice.network in public_nets:
- public_net_slice = net_slice
- elif net_slice.network in private_nets:
- private_net_slice = net_slice
- if not public_net_slice:
- public_net_slice = NetworkSlice(slice=slice, network=public_nets[0])
- public_net_slice.save()
- print "MODEL POLICY: slice", slice, "made public_net_slice"
- if not private_net_slice:
- private_net_slice = NetworkSlice(slice=slice, network=private_nets[0])
- private_net_slice.save()
- print "MODEL POLICY: slice", slice, "made private_net_slice"
-
- print "MODEL POLICY: slice", slice, "DONE"
-
-
diff --git a/xos/model_policy.py b/xos/model_policy.py
deleted file mode 100644
index 9462b35..0000000
--- a/xos/model_policy.py
+++ /dev/null
@@ -1,139 +0,0 @@
-from django.db.models.signals import post_save
-from django.dispatch import receiver
-import pdb
-from dependency_walker import *
-import model_policies
-from util.logger import logger
-from datetime import datetime
-import time
-from core.models import *
-from django.db import reset_queries
-from django.db.transaction import atomic
-from django.db.models import F, Q
-
-modelPolicyEnabled = True
-bad_instances=[]
-
-def EnableModelPolicy(x):
- global modelPolicyEnabled
- modelPolicyEnabled = x
-
-def update_wp(d, o):
- try:
- save_fields = []
- if (d.write_protect != o.write_protect):
- d.write_protect = o.write_protect
- save_fields.append('write_protect')
- if (save_fields):
- d.save(update_fields=save_fields)
- except AttributeError,e:
- raise e
-
-def update_dep(d, o):
- try:
- print 'Trying to update %s'%d
- save_fields = []
- if (d.updated < o.updated):
- save_fields = ['updated']
-
- if (save_fields):
- d.save(update_fields=save_fields)
- except AttributeError,e:
- raise e
- except Exception,e:
- logger.info('Could not save %r. Exception: %r'%(d,e))
-
-def delete_if_inactive(d, o):
- try:
- d.delete()
- print "Deleted %s (%s)"%(d,d.__class__.__name__)
- except:
- pass
- return
-
-
-@atomic
-def execute_model_policy(instance, deleted):
- # Automatic dirtying
- if (instance in bad_instances):
- return
-
- # These are the models whose children get deleted when they are
- delete_policy_models = ['Slice','Instance','Network']
- sender_name = instance.__class__.__name__
- policy_name = 'model_policy_%s'%sender_name
- noargs = False
-
- if (not deleted):
- walk_inv_deps(update_dep, instance)
- walk_deps(update_wp, instance)
- elif (sender_name in delete_policy_models):
- walk_inv_deps(delete_if_inactive, instance)
-
-
-
- try:
- policy_handler = getattr(model_policies, policy_name, None)
- logger.error("POLICY HANDLER: %s %s" % (policy_name, policy_handler))
- if policy_handler is not None:
- if (deleted):
- try:
- policy_handler.handle_delete(instance)
- except AttributeError:
- pass
- else:
- policy_handler.handle(instance)
- except:
- logger.log_exc("Model Policy Error:")
-
- try:
- instance.policed=datetime.now()
- instance.save(update_fields=['policed'])
- except:
- logging.error('Object %r is defective'%instance)
- bad_instances.append(instance)
-
-def noop(o,p):
- pass
-
-def run_policy():
- while (True):
- start = time.time()
- run_policy_once()
- if (time.time()-start<1):
- time.sleep(1)
-
-def run_policy_once():
- from core.models import Instance,Slice,Controller,Network,User,SlicePrivilege,Site,SitePrivilege,Image,ControllerSlice,ControllerUser,ControllerSite
- models = [Controller, Site, SitePrivilege, Image, ControllerSlice, ControllerSite, ControllerUser, User, Slice, Network, Instance, SlicePrivilege]
- objects = []
- deleted_objects = []
-
- for m in models:
- res = m.objects.filter(Q(policed__lt=F('updated')) | Q(policed=None))
- objects.extend(res)
- res = m.deleted_objects.filter(Q(policed__lt=F('updated')) | Q(policed=None))
- deleted_objects.extend(res)
-
- for o in objects:
- execute_model_policy(o, o.deleted)
-
- for o in deleted_objects:
- execute_model_policy(o, True)
-
- # Reap non-sync'd models here
- reaped = [Slice]
-
- for m in reaped:
- dobjs = m.deleted_objects.all()
- for d in dobjs:
- deps = walk_inv_deps(noop, d)
- if (not deps):
- print 'Purging object %r'%d
- d.delete(purge=True)
-
- try:
- reset_queries()
- except:
- # this shouldn't happen, but in case it does, catch it...
- logger.log_exc("exception in reset_queries")
diff --git a/xos/monitor/__init__.py b/xos/monitor/__init__.py
deleted file mode 100644
index 6debf82..0000000
--- a/xos/monitor/__init__.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from xos.settings import STATISTICS_DRIVER
-
-if (STATISTICS_DRIVER=="ceilometer"):
- from observer import ceilometer
- driver = ceilometer.CeilometerDriver()
-elif (not STATISTICS_DRIVER) or (STATISTICS_DRIVER.lower() == "none"):
- # disabled
- driver = None
-else:
- driver = None
- print "WARNING: Unknown statistics driver %s" % STATISTICS_DRIVER
diff --git a/xos/monitor/monitordriver.py b/xos/monitor/monitordriver.py
deleted file mode 100644
index 50e208c..0000000
--- a/xos/monitor/monitordriver.py
+++ /dev/null
@@ -1,20 +0,0 @@
-# Implement this interface
-# to serve as a driver for analytics
-
-class DashboardStatistics(dict):
- def __init__(self):
- self['stat_list'] = []
- self['average'] = 0
- self['sum'] = 0
- self['unit'] = 'units'
- self['stat_list']=[]
- # stat_list is a list of dicts
- # [ {'timestamp': datetime, 'value': value} ]
-
-
-class MonitorDriver:
- def __init__(self):
- pass
-
- def get_meter(self, meter_name, obj, pk, credentials=None):
- pass
diff --git a/xos/neutron_extension/1:2013.2.2-0ubuntu1~cloud0/nat.py b/xos/neutron_extension/1:2013.2.2-0ubuntu1~cloud0/nat.py
deleted file mode 100644
index 04e39f1..0000000
--- a/xos/neutron_extension/1:2013.2.2-0ubuntu1~cloud0/nat.py
+++ /dev/null
@@ -1,50 +0,0 @@
-from neutron.api.v2 import attributes
-
-FORWARD_PORTS = 'nat:forward_ports'
-
-EXTENDED_ATTRIBUTES_2_0 = {
- 'ports': {
- FORWARD_PORTS: {'allow_post': True, 'allow_put': True,
- 'default': attributes.ATTR_NOT_SPECIFIED,
- 'is_visible': True},
- }
-}
-
-
-class Nat(object):
- """Extension class supporting OpenCloud NAT networking
-
- This class is used by Quantum's extension framework to make
- metadata about the OpenCloud Port extension available to
- clients. No new resources are defined by this extension. Instead,
- the existing Port resource's request and response messages are
- extended with attributes in the OpenCloud namespace.
- """
-
- @classmethod
- def get_name(cls):
- return "OpenCloud NAT Networking Extension"
-
- @classmethod
- def get_alias(cls):
- return "nat"
-
- @classmethod
- def get_description(cls):
- return "Add TCP/UDP port forwarding through NAT to Quantum Port objects"
-
- @classmethod
- def get_namespace(cls):
- # return "http://docs.openstack.org/ext/provider/api/v1.0"
- # Nothing there right now
- return "http://www.vicci.org/ext/opencloud/nat/api/v0.1"
-
- @classmethod
- def get_updated(cls):
- return "2013-09-12T10:00:00-00:00"
-
- def get_extended_resources(self, version):
- if version == "2.0":
- return EXTENDED_ATTRIBUTES_2_0
- else:
- return {}
diff --git a/xos/neutron_extension/1:2013.2.2-0ubuntu1~cloud0/ovs_db_v2.py b/xos/neutron_extension/1:2013.2.2-0ubuntu1~cloud0/ovs_db_v2.py
deleted file mode 100644
index 39cf315..0000000
--- a/xos/neutron_extension/1:2013.2.2-0ubuntu1~cloud0/ovs_db_v2.py
+++ /dev/null
@@ -1,425 +0,0 @@
-# vim: tabstop=4 shiftwidth=4 softtabstop=4
-# Copyright 2011 Nicira Networks, 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.
-# @author: Aaron Rosen, Nicira Networks, Inc.
-# @author: Bob Kukura, Red Hat, Inc.
-
-from sqlalchemy import func
-from sqlalchemy.orm import exc
-
-from neutron.common import exceptions as q_exc
-import neutron.db.api as db
-from neutron.db import models_v2
-from neutron.db import securitygroups_db as sg_db
-from neutron.extensions import securitygroup as ext_sg
-from neutron import manager
-from neutron.openstack.common.db import exception as db_exc
-from neutron.openstack.common import log as logging
-from neutron.plugins.openvswitch.common import constants
-from neutron.plugins.openvswitch import ovs_models_v2
-
-LOG = logging.getLogger(__name__)
-
-
-def initialize():
- db.configure_db()
-
-
-def get_network_binding(session, network_id):
- session = session or db.get_session()
- try:
- binding = (session.query(ovs_models_v2.NetworkBinding).
- filter_by(network_id=network_id).
- one())
- return binding
- except exc.NoResultFound:
- return
-
-
-def add_network_binding(session, network_id, network_type,
- physical_network, segmentation_id):
- with session.begin(subtransactions=True):
- binding = ovs_models_v2.NetworkBinding(network_id, network_type,
- physical_network,
- segmentation_id)
- session.add(binding)
-
-def get_port_forwarding(session, port_id):
- session = session or db.get_session()
- try:
- forward = (session.query(ovs_models_v2.PortForwarding).
- filter_by(port_id=port_id).one())
- return forward['forward_ports']
- except exc.NoResultFound:
- return
-
-def clear_port_forwarding(session, port_id):
- with session.begin(subtransactions=True):
- try:
- # Get rid of old port bindings
- forward = (session.query(ovs_models_v2.PortForwarding).
- filter_by(port_id=port_id).one())
- if forward:
- session.delete(forward)
- except exc.NoResultFound:
- pass
-
-def add_port_forwarding(session, port_id, forward_ports):
- with session.begin(subtransactions=True):
- forward = ovs_models_v2.PortForwarding(port_id, forward_ports)
- session.add(forward)
-
-def sync_vlan_allocations(network_vlan_ranges):
- """Synchronize vlan_allocations table with configured VLAN ranges."""
-
- session = db.get_session()
- with session.begin():
- # get existing allocations for all physical networks
- allocations = dict()
- allocs = (session.query(ovs_models_v2.VlanAllocation).
- all())
- for alloc in allocs:
- if alloc.physical_network not in allocations:
- allocations[alloc.physical_network] = set()
- allocations[alloc.physical_network].add(alloc)
-
- # process vlan ranges for each configured physical network
- for physical_network, vlan_ranges in network_vlan_ranges.iteritems():
- # determine current configured allocatable vlans for this
- # physical network
- vlan_ids = set()
- for vlan_range in vlan_ranges:
- vlan_ids |= set(xrange(vlan_range[0], vlan_range[1] + 1))
-
- # remove from table unallocated vlans not currently allocatable
- if physical_network in allocations:
- for alloc in allocations[physical_network]:
- try:
- # see if vlan is allocatable
- vlan_ids.remove(alloc.vlan_id)
- except KeyError:
- # it's not allocatable, so check if its allocated
- if not alloc.allocated:
- # it's not, so remove it from table
- LOG.debug(_("Removing vlan %(vlan_id)s on "
- "physical network "
- "%(physical_network)s from pool"),
- {'vlan_id': alloc.vlan_id,
- 'physical_network': physical_network})
- session.delete(alloc)
- del allocations[physical_network]
-
- # add missing allocatable vlans to table
- for vlan_id in sorted(vlan_ids):
- alloc = ovs_models_v2.VlanAllocation(physical_network, vlan_id)
- session.add(alloc)
-
- # remove from table unallocated vlans for any unconfigured physical
- # networks
- for allocs in allocations.itervalues():
- for alloc in allocs:
- if not alloc.allocated:
- LOG.debug(_("Removing vlan %(vlan_id)s on physical "
- "network %(physical_network)s from pool"),
- {'vlan_id': alloc.vlan_id,
- 'physical_network': alloc.physical_network})
- session.delete(alloc)
-
-
-def get_vlan_allocation(physical_network, vlan_id):
- session = db.get_session()
- try:
- alloc = (session.query(ovs_models_v2.VlanAllocation).
- filter_by(physical_network=physical_network,
- vlan_id=vlan_id).
- one())
- return alloc
- except exc.NoResultFound:
- return
-
-
-def reserve_vlan(session):
- with session.begin(subtransactions=True):
- alloc = (session.query(ovs_models_v2.VlanAllocation).
- filter_by(allocated=False).
- with_lockmode('update').
- first())
- if alloc:
- LOG.debug(_("Reserving vlan %(vlan_id)s on physical network "
- "%(physical_network)s from pool"),
- {'vlan_id': alloc.vlan_id,
- 'physical_network': alloc.physical_network})
- alloc.allocated = True
- return (alloc.physical_network, alloc.vlan_id)
- raise q_exc.NoNetworkAvailable()
-
-
-def reserve_specific_vlan(session, physical_network, vlan_id):
- with session.begin(subtransactions=True):
- try:
- alloc = (session.query(ovs_models_v2.VlanAllocation).
- filter_by(physical_network=physical_network,
- vlan_id=vlan_id).
- with_lockmode('update').
- one())
- if alloc.allocated:
- if vlan_id == constants.FLAT_VLAN_ID:
- raise q_exc.FlatNetworkInUse(
- physical_network=physical_network)
- else:
- raise q_exc.VlanIdInUse(vlan_id=vlan_id,
- physical_network=physical_network)
- LOG.debug(_("Reserving specific vlan %(vlan_id)s on physical "
- "network %(physical_network)s from pool"),
- {'vlan_id': vlan_id,
- 'physical_network': physical_network})
- alloc.allocated = True
- except exc.NoResultFound:
- LOG.debug(_("Reserving specific vlan %(vlan_id)s on physical "
- "network %(physical_network)s outside pool"),
- {'vlan_id': vlan_id,
- 'physical_network': physical_network})
- alloc = ovs_models_v2.VlanAllocation(physical_network, vlan_id)
- alloc.allocated = True
- session.add(alloc)
-
-
-def release_vlan(session, physical_network, vlan_id, network_vlan_ranges):
- with session.begin(subtransactions=True):
- try:
- alloc = (session.query(ovs_models_v2.VlanAllocation).
- filter_by(physical_network=physical_network,
- vlan_id=vlan_id).
- with_lockmode('update').
- one())
- alloc.allocated = False
- inside = False
- for vlan_range in network_vlan_ranges.get(physical_network, []):
- if vlan_id >= vlan_range[0] and vlan_id <= vlan_range[1]:
- inside = True
- break
- if not inside:
- session.delete(alloc)
- LOG.debug(_("Releasing vlan %(vlan_id)s on physical network "
- "%(physical_network)s outside pool"),
- {'vlan_id': vlan_id,
- 'physical_network': physical_network})
- else:
- LOG.debug(_("Releasing vlan %(vlan_id)s on physical network "
- "%(physical_network)s to pool"),
- {'vlan_id': vlan_id,
- 'physical_network': physical_network})
- except exc.NoResultFound:
- LOG.warning(_("vlan_id %(vlan_id)s on physical network "
- "%(physical_network)s not found"),
- {'vlan_id': vlan_id,
- 'physical_network': physical_network})
-
-
-def sync_tunnel_allocations(tunnel_id_ranges):
- """Synchronize tunnel_allocations table with configured tunnel ranges."""
-
- # determine current configured allocatable tunnels
- tunnel_ids = set()
- for tunnel_id_range in tunnel_id_ranges:
- tun_min, tun_max = tunnel_id_range
- if tun_max + 1 - tun_min > 1000000:
- LOG.error(_("Skipping unreasonable tunnel ID range "
- "%(tun_min)s:%(tun_max)s"),
- {'tun_min': tun_min, 'tun_max': tun_max})
- else:
- tunnel_ids |= set(xrange(tun_min, tun_max + 1))
-
- session = db.get_session()
- with session.begin():
- # remove from table unallocated tunnels not currently allocatable
- allocs = (session.query(ovs_models_v2.TunnelAllocation).
- all())
- for alloc in allocs:
- try:
- # see if tunnel is allocatable
- tunnel_ids.remove(alloc.tunnel_id)
- except KeyError:
- # it's not allocatable, so check if its allocated
- if not alloc.allocated:
- # it's not, so remove it from table
- LOG.debug(_("Removing tunnel %s from pool"),
- alloc.tunnel_id)
- session.delete(alloc)
-
- # add missing allocatable tunnels to table
- for tunnel_id in sorted(tunnel_ids):
- alloc = ovs_models_v2.TunnelAllocation(tunnel_id)
- session.add(alloc)
-
-
-def get_tunnel_allocation(tunnel_id):
- session = db.get_session()
- try:
- alloc = (session.query(ovs_models_v2.TunnelAllocation).
- filter_by(tunnel_id=tunnel_id).
- with_lockmode('update').
- one())
- return alloc
- except exc.NoResultFound:
- return
-
-
-def reserve_tunnel(session):
- with session.begin(subtransactions=True):
- alloc = (session.query(ovs_models_v2.TunnelAllocation).
- filter_by(allocated=False).
- with_lockmode('update').
- first())
- if alloc:
- LOG.debug(_("Reserving tunnel %s from pool"), alloc.tunnel_id)
- alloc.allocated = True
- return alloc.tunnel_id
- raise q_exc.NoNetworkAvailable()
-
-
-def reserve_specific_tunnel(session, tunnel_id):
- with session.begin(subtransactions=True):
- try:
- alloc = (session.query(ovs_models_v2.TunnelAllocation).
- filter_by(tunnel_id=tunnel_id).
- with_lockmode('update').
- one())
- if alloc.allocated:
- raise q_exc.TunnelIdInUse(tunnel_id=tunnel_id)
- LOG.debug(_("Reserving specific tunnel %s from pool"), tunnel_id)
- alloc.allocated = True
- except exc.NoResultFound:
- LOG.debug(_("Reserving specific tunnel %s outside pool"),
- tunnel_id)
- alloc = ovs_models_v2.TunnelAllocation(tunnel_id)
- alloc.allocated = True
- session.add(alloc)
-
-
-def release_tunnel(session, tunnel_id, tunnel_id_ranges):
- with session.begin(subtransactions=True):
- try:
- alloc = (session.query(ovs_models_v2.TunnelAllocation).
- filter_by(tunnel_id=tunnel_id).
- with_lockmode('update').
- one())
- alloc.allocated = False
- inside = False
- for tunnel_id_range in tunnel_id_ranges:
- if (tunnel_id >= tunnel_id_range[0]
- and tunnel_id <= tunnel_id_range[1]):
- inside = True
- break
- if not inside:
- session.delete(alloc)
- LOG.debug(_("Releasing tunnel %s outside pool"), tunnel_id)
- else:
- LOG.debug(_("Releasing tunnel %s to pool"), tunnel_id)
- except exc.NoResultFound:
- LOG.warning(_("tunnel_id %s not found"), tunnel_id)
-
-
-def get_port(port_id):
- session = db.get_session()
- try:
- port = session.query(models_v2.Port).filter_by(id=port_id).one()
- except exc.NoResultFound:
- port = None
- return port
-
-
-def get_port_from_device(port_id):
- """Get port from database."""
- LOG.debug(_("get_port_with_securitygroups() called:port_id=%s"), port_id)
- session = db.get_session()
- sg_binding_port = sg_db.SecurityGroupPortBinding.port_id
-
- query = session.query(models_v2.Port,
- sg_db.SecurityGroupPortBinding.security_group_id)
- query = query.outerjoin(sg_db.SecurityGroupPortBinding,
- models_v2.Port.id == sg_binding_port)
- query = query.filter(models_v2.Port.id == port_id)
- port_and_sgs = query.all()
- if not port_and_sgs:
- return None
- port = port_and_sgs[0][0]
- plugin = manager.NeutronManager.get_plugin()
- port_dict = plugin._make_port_dict(port)
- port_dict[ext_sg.SECURITYGROUPS] = [
- sg_id for port_, sg_id in port_and_sgs if sg_id]
- port_dict['security_group_rules'] = []
- port_dict['security_group_source_groups'] = []
- port_dict['fixed_ips'] = [ip['ip_address']
- for ip in port['fixed_ips']]
- return port_dict
-
-
-def set_port_status(port_id, status):
- session = db.get_session()
- try:
- port = session.query(models_v2.Port).filter_by(id=port_id).one()
- port['status'] = status
- session.merge(port)
- session.flush()
- except exc.NoResultFound:
- raise q_exc.PortNotFound(port_id=port_id)
-
-
-def get_tunnel_endpoints():
- session = db.get_session()
-
- tunnels = session.query(ovs_models_v2.TunnelEndpoint)
- return [{'id': tunnel.id,
- 'ip_address': tunnel.ip_address} for tunnel in tunnels]
-
-
-def _generate_tunnel_id(session):
- max_tunnel_id = session.query(
- func.max(ovs_models_v2.TunnelEndpoint.id)).scalar() or 0
- return max_tunnel_id + 1
-
-
-def add_tunnel_endpoint(ip, max_retries=10):
- """Return the endpoint of the given IP address or generate a new one."""
-
- # NOTE(rpodolyaka): generation of a new tunnel endpoint must be put into a
- # repeatedly executed transactional block to ensure it
- # doesn't conflict with any other concurrently executed
- # DB transactions in spite of the specified transactions
- # isolation level value
- for i in xrange(max_retries):
- LOG.debug(_('Adding a tunnel endpoint for %s'), ip)
- try:
- session = db.get_session()
- with session.begin(subtransactions=True):
- tunnel = (session.query(ovs_models_v2.TunnelEndpoint).
- filter_by(ip_address=ip).with_lockmode('update').
- first())
-
- if tunnel is None:
- tunnel_id = _generate_tunnel_id(session)
- tunnel = ovs_models_v2.TunnelEndpoint(ip, tunnel_id)
- session.add(tunnel)
-
- return tunnel
- except db_exc.DBDuplicateEntry:
- # a concurrent transaction has been commited, try again
- LOG.debug(_('Adding a tunnel endpoint failed due to a concurrent'
- 'transaction had been commited (%s attempts left)'),
- max_retries - (i + 1))
-
- raise q_exc.NeutronException(
- message=_('Unable to generate a new tunnel id'))
diff --git a/xos/neutron_extension/1:2013.2.2-0ubuntu1~cloud0/ovs_models_v2.py b/xos/neutron_extension/1:2013.2.2-0ubuntu1~cloud0/ovs_models_v2.py
deleted file mode 100644
index 7e022f5..0000000
--- a/xos/neutron_extension/1:2013.2.2-0ubuntu1~cloud0/ovs_models_v2.py
+++ /dev/null
@@ -1,118 +0,0 @@
-# vim: tabstop=4 shiftwidth=4 softtabstop=4
-# Copyright 2011 Nicira Networks, 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.
-# @author: Aaron Rosen, Nicira Networks, Inc.
-# @author: Bob Kukura, Red Hat, Inc.
-
-
-from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, PickleType
-from sqlalchemy.schema import UniqueConstraint
-
-from neutron.db.models_v2 import model_base
-
-
-class VlanAllocation(model_base.BASEV2):
- """Represents allocation state of vlan_id on physical network."""
- __tablename__ = 'ovs_vlan_allocations'
-
- physical_network = Column(String(64), nullable=False, primary_key=True)
- vlan_id = Column(Integer, nullable=False, primary_key=True,
- autoincrement=False)
- allocated = Column(Boolean, nullable=False)
-
- def __init__(self, physical_network, vlan_id):
- self.physical_network = physical_network
- self.vlan_id = vlan_id
- self.allocated = False
-
- def __repr__(self):
- return "<VlanAllocation(%s,%d,%s)>" % (self.physical_network,
- self.vlan_id, self.allocated)
-
-
-class TunnelAllocation(model_base.BASEV2):
- """Represents allocation state of tunnel_id."""
- __tablename__ = 'ovs_tunnel_allocations'
-
- tunnel_id = Column(Integer, nullable=False, primary_key=True,
- autoincrement=False)
- allocated = Column(Boolean, nullable=False)
-
- def __init__(self, tunnel_id):
- self.tunnel_id = tunnel_id
- self.allocated = False
-
- def __repr__(self):
- return "<TunnelAllocation(%d,%s)>" % (self.tunnel_id, self.allocated)
-
-
-class NetworkBinding(model_base.BASEV2):
- """Represents binding of virtual network to physical realization."""
- __tablename__ = 'ovs_network_bindings'
-
- network_id = Column(String(36),
- ForeignKey('networks.id', ondelete="CASCADE"),
- primary_key=True)
- # 'gre', 'vlan', 'flat', 'local'
- network_type = Column(String(32), nullable=False)
- physical_network = Column(String(64))
- segmentation_id = Column(Integer) # tunnel_id or vlan_id
-
- def __init__(self, network_id, network_type, physical_network,
- segmentation_id):
- self.network_id = network_id
- self.network_type = network_type
- self.physical_network = physical_network
- self.segmentation_id = segmentation_id
-
- def __repr__(self):
- return "<NetworkBinding(%s,%s,%s,%d)>" % (self.network_id,
- self.network_type,
- self.physical_network,
- self.segmentation_id)
-
-class PortForwarding(model_base.BASEV2):
- """Ports to be forwarded through NAT """
- __tablename__ = 'ovs_port_forwarding'
-
- port_id = Column(String(36),
- ForeignKey('ports.id', ondelete="CASCADE"),
- primary_key=True)
- forward_ports = Column(PickleType)
-
- def __init__(self, port_id, forward_ports):
- self.port_id = port_id
- self.forward_ports = forward_ports
-
- def __repr__(self):
- return "<PortForwarding(%s,%s)>" % (self.port_id, self.forward_ports)
-
-class TunnelEndpoint(model_base.BASEV2):
- """Represents tunnel endpoint in RPC mode."""
- __tablename__ = 'ovs_tunnel_endpoints'
- __table_args__ = (
- UniqueConstraint('id', name='uniq_ovs_tunnel_endpoints0id'),
- )
-
- ip_address = Column(String(64), primary_key=True)
- id = Column(Integer, nullable=False)
-
- def __init__(self, ip_address, id):
- self.ip_address = ip_address
- self.id = id
-
- def __repr__(self):
- return "<TunnelEndpoint(%s,%s)>" % (self.ip_address, self.id)
-
diff --git a/xos/neutron_extension/1:2013.2.2-0ubuntu1~cloud0/ovs_neutron_plugin.py b/xos/neutron_extension/1:2013.2.2-0ubuntu1~cloud0/ovs_neutron_plugin.py
deleted file mode 100644
index abf0f80..0000000
--- a/xos/neutron_extension/1:2013.2.2-0ubuntu1~cloud0/ovs_neutron_plugin.py
+++ /dev/null
@@ -1,708 +0,0 @@
-# vim: tabstop=4 shiftwidth=4 softtabstop=4
-# Copyright 2011 Nicira Networks, 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.
-# @author: Somik Behera, Nicira Networks, Inc.
-# @author: Brad Hall, Nicira Networks, Inc.
-# @author: Dan Wendlandt, Nicira Networks, Inc.
-# @author: Dave Lapsley, Nicira Networks, Inc.
-# @author: Aaron Rosen, Nicira Networks, Inc.
-# @author: Bob Kukura, Red Hat, Inc.
-# @author: Seetharama Ayyadevara, Freescale Semiconductor, Inc.
-
-import sys
-
-from oslo.config import cfg
-
-from neutron.agent import securitygroups_rpc as sg_rpc
-from neutron.api.rpc.agentnotifiers import dhcp_rpc_agent_api
-from neutron.api.rpc.agentnotifiers import l3_rpc_agent_api
-from neutron.api.v2 import attributes
-from neutron.common import constants as q_const
-from neutron.common import exceptions as q_exc
-from neutron.common import rpc as q_rpc
-from neutron.common import topics
-from neutron.common import utils
-from neutron.db import agents_db
-from neutron.db import agentschedulers_db
-from neutron.db import allowedaddresspairs_db as addr_pair_db
-from neutron.db import db_base_plugin_v2
-from neutron.db import dhcp_rpc_base
-from neutron.db import external_net_db
-from neutron.db import extradhcpopt_db
-from neutron.db import extraroute_db
-from neutron.db import l3_agentschedulers_db
-from neutron.db import l3_gwmode_db
-from neutron.db import l3_rpc_base
-from neutron.db import portbindings_db
-from neutron.db import quota_db # noqa
-from neutron.db import securitygroups_rpc_base as sg_db_rpc
-from neutron.extensions import allowedaddresspairs as addr_pair
-from neutron.extensions import extra_dhcp_opt as edo_ext
-from neutron.extensions import portbindings
-from neutron.extensions import providernet as provider
-from neutron.extensions import nat
-from neutron import manager
-from neutron.openstack.common import importutils
-from neutron.openstack.common import log as logging
-from neutron.openstack.common import rpc
-from neutron.openstack.common.rpc import proxy
-from neutron.plugins.common import constants as svc_constants
-from neutron.plugins.common import utils as plugin_utils
-from neutron.plugins.openvswitch.common import config # noqa
-from neutron.plugins.openvswitch.common import constants
-from neutron.plugins.openvswitch import ovs_db_v2
-
-
-LOG = logging.getLogger(__name__)
-
-
-class OVSRpcCallbacks(dhcp_rpc_base.DhcpRpcCallbackMixin,
- l3_rpc_base.L3RpcCallbackMixin,
- sg_db_rpc.SecurityGroupServerRpcCallbackMixin):
-
- # history
- # 1.0 Initial version
- # 1.1 Support Security Group RPC
-
- RPC_API_VERSION = '1.1'
-
- def __init__(self, notifier, tunnel_type):
- self.notifier = notifier
- self.tunnel_type = tunnel_type
-
- def create_rpc_dispatcher(self):
- '''Get the rpc dispatcher for this manager.
-
- If a manager would like to set an rpc API version, or support more than
- one class as the target of rpc messages, override this method.
- '''
- return q_rpc.PluginRpcDispatcher([self,
- agents_db.AgentExtRpcCallback()])
-
- @classmethod
- def get_port_from_device(cls, device):
- port = ovs_db_v2.get_port_from_device(device)
- if port:
- port['device'] = device
- return port
-
- def get_device_details(self, rpc_context, **kwargs):
- """Agent requests device details."""
- agent_id = kwargs.get('agent_id')
- device = kwargs.get('device')
- LOG.debug(_("Device %(device)s details requested from %(agent_id)s"),
- {'device': device, 'agent_id': agent_id})
- port = ovs_db_v2.get_port(device)
- if port:
- binding = ovs_db_v2.get_network_binding(None, port['network_id'])
- entry = {'device': device,
- 'network_id': port['network_id'],
- 'port_id': port['id'],
- 'admin_state_up': port['admin_state_up'],
- 'network_type': binding.network_type,
- 'segmentation_id': binding.segmentation_id,
- 'physical_network': binding.physical_network}
- new_status = (q_const.PORT_STATUS_ACTIVE if port['admin_state_up']
- else q_const.PORT_STATUS_DOWN)
- if port['status'] != new_status:
- ovs_db_v2.set_port_status(port['id'], new_status)
- else:
- entry = {'device': device}
- LOG.debug(_("%s can not be found in database"), device)
- return entry
-
- def update_device_down(self, rpc_context, **kwargs):
- """Device no longer exists on agent."""
- agent_id = kwargs.get('agent_id')
- device = kwargs.get('device')
- host = kwargs.get('host')
- port = ovs_db_v2.get_port(device)
- LOG.debug(_("Device %(device)s no longer exists on %(agent_id)s"),
- {'device': device, 'agent_id': agent_id})
- if port:
- entry = {'device': device,
- 'exists': True}
- plugin = manager.NeutronManager.get_plugin()
- if (host and
- not plugin.get_port_host(rpc_context, port['id']) == host):
- LOG.debug(_("Device %(device)s not bound to the"
- " agent host %(host)s"),
- {'device': device, 'host': host})
- elif port['status'] != q_const.PORT_STATUS_DOWN:
- # Set port status to DOWN
- ovs_db_v2.set_port_status(port['id'],
- q_const.PORT_STATUS_DOWN)
- else:
- entry = {'device': device,
- 'exists': False}
- LOG.debug(_("%s can not be found in database"), device)
- return entry
-
- def update_device_up(self, rpc_context, **kwargs):
- """Device is up on agent."""
- agent_id = kwargs.get('agent_id')
- device = kwargs.get('device')
- host = kwargs.get('host')
- port = ovs_db_v2.get_port(device)
- LOG.debug(_("Device %(device)s up on %(agent_id)s"),
- {'device': device, 'agent_id': agent_id})
- plugin = manager.NeutronManager.get_plugin()
- if port:
- if (host and
- not plugin.get_port_host(rpc_context, port['id']) == host):
- LOG.debug(_("Device %(device)s not bound to the"
- " agent host %(host)s"),
- {'device': device, 'host': host})
- return
- elif port['status'] != q_const.PORT_STATUS_ACTIVE:
- ovs_db_v2.set_port_status(port['id'],
- q_const.PORT_STATUS_ACTIVE)
- else:
- LOG.debug(_("%s can not be found in database"), device)
-
- def tunnel_sync(self, rpc_context, **kwargs):
- """Update new tunnel.
-
- Updates the datbase with the tunnel IP. All listening agents will also
- be notified about the new tunnel IP.
- """
- tunnel_ip = kwargs.get('tunnel_ip')
- # Update the database with the IP
- tunnel = ovs_db_v2.add_tunnel_endpoint(tunnel_ip)
- tunnels = ovs_db_v2.get_tunnel_endpoints()
- entry = dict()
- entry['tunnels'] = tunnels
- # Notify all other listening agents
- self.notifier.tunnel_update(rpc_context, tunnel.ip_address,
- tunnel.id, self.tunnel_type)
- # Return the list of tunnels IP's to the agent
- return entry
-
-
-class AgentNotifierApi(proxy.RpcProxy,
- sg_rpc.SecurityGroupAgentRpcApiMixin):
- '''Agent side of the openvswitch rpc API.
-
- API version history:
- 1.0 - Initial version.
-
- '''
-
- BASE_RPC_API_VERSION = '1.0'
-
- def __init__(self, topic):
- super(AgentNotifierApi, self).__init__(
- topic=topic, default_version=self.BASE_RPC_API_VERSION)
- self.topic_network_delete = topics.get_topic_name(topic,
- topics.NETWORK,
- topics.DELETE)
- self.topic_port_update = topics.get_topic_name(topic,
- topics.PORT,
- topics.UPDATE)
- self.topic_tunnel_update = topics.get_topic_name(topic,
- constants.TUNNEL,
- topics.UPDATE)
-
- def network_delete(self, context, network_id):
- self.fanout_cast(context,
- self.make_msg('network_delete',
- network_id=network_id),
- topic=self.topic_network_delete)
-
- def port_update(self, context, port, network_type, segmentation_id,
- physical_network):
- self.fanout_cast(context,
- self.make_msg('port_update',
- port=port,
- network_type=network_type,
- segmentation_id=segmentation_id,
- physical_network=physical_network),
- topic=self.topic_port_update)
-
- def tunnel_update(self, context, tunnel_ip, tunnel_id, tunnel_type):
- self.fanout_cast(context,
- self.make_msg('tunnel_update',
- tunnel_ip=tunnel_ip,
- tunnel_id=tunnel_id,
- tunnel_type=tunnel_type),
- topic=self.topic_tunnel_update)
-
-
-class OVSNeutronPluginV2(db_base_plugin_v2.NeutronDbPluginV2,
- external_net_db.External_net_db_mixin,
- extraroute_db.ExtraRoute_db_mixin,
- l3_gwmode_db.L3_NAT_db_mixin,
- sg_db_rpc.SecurityGroupServerRpcMixin,
- l3_agentschedulers_db.L3AgentSchedulerDbMixin,
- agentschedulers_db.DhcpAgentSchedulerDbMixin,
- portbindings_db.PortBindingMixin,
- extradhcpopt_db.ExtraDhcpOptMixin,
- addr_pair_db.AllowedAddressPairsMixin):
-
- """Implement the Neutron abstractions using Open vSwitch.
-
- Depending on whether tunneling is enabled, either a GRE, VXLAN tunnel or
- a new VLAN is created for each network. An agent is relied upon to
- perform the actual OVS configuration on each host.
-
- The provider extension is also supported. As discussed in
- https://bugs.launchpad.net/neutron/+bug/1023156, this class could
- be simplified, and filtering on extended attributes could be
- handled, by adding support for extended attributes to the
- NeutronDbPluginV2 base class. When that occurs, this class should
- be updated to take advantage of it.
-
- The port binding extension enables an external application relay
- information to and from the plugin.
- """
-
- # This attribute specifies whether the plugin supports or not
- # bulk/pagination/sorting operations. Name mangling is used in
- # order to ensure it is qualified by class
- __native_bulk_support = True
- __native_pagination_support = True
- __native_sorting_support = True
-
- _supported_extension_aliases = ["provider", "external-net", "router",
- "ext-gw-mode", "binding", "quotas",
- "security-group", "agent", "extraroute",
- "l3_agent_scheduler",
- "dhcp_agent_scheduler",
- "extra_dhcp_opt",
- "allowed-address-pairs",
- "nat"]
-
- @property
- def supported_extension_aliases(self):
- if not hasattr(self, '_aliases'):
- aliases = self._supported_extension_aliases[:]
- sg_rpc.disable_security_group_extension_if_noop_driver(aliases)
- self._aliases = aliases
- return self._aliases
-
- def __init__(self, configfile=None):
- self.base_binding_dict = {
- portbindings.VIF_TYPE: portbindings.VIF_TYPE_OVS,
- portbindings.CAPABILITIES: {
- portbindings.CAP_PORT_FILTER:
- 'security-group' in self.supported_extension_aliases}}
- ovs_db_v2.initialize()
- self._parse_network_vlan_ranges()
- ovs_db_v2.sync_vlan_allocations(self.network_vlan_ranges)
- self.tenant_network_type = cfg.CONF.OVS.tenant_network_type
- if self.tenant_network_type not in [constants.TYPE_LOCAL,
- constants.TYPE_VLAN,
- constants.TYPE_GRE,
- constants.TYPE_VXLAN,
- constants.TYPE_NONE]:
- LOG.error(_("Invalid tenant_network_type: %s. "
- "Server terminated!"),
- self.tenant_network_type)
- sys.exit(1)
- self.enable_tunneling = cfg.CONF.OVS.enable_tunneling
- self.tunnel_type = None
- if self.enable_tunneling:
- self.tunnel_type = cfg.CONF.OVS.tunnel_type or constants.TYPE_GRE
- elif cfg.CONF.OVS.tunnel_type:
- self.tunnel_type = cfg.CONF.OVS.tunnel_type
- self.enable_tunneling = True
- self.tunnel_id_ranges = []
- if self.enable_tunneling:
- self._parse_tunnel_id_ranges()
- ovs_db_v2.sync_tunnel_allocations(self.tunnel_id_ranges)
- elif self.tenant_network_type in constants.TUNNEL_NETWORK_TYPES:
- LOG.error(_("Tunneling disabled but tenant_network_type is '%s'. "
- "Server terminated!"), self.tenant_network_type)
- sys.exit(1)
- self.setup_rpc()
- self.network_scheduler = importutils.import_object(
- cfg.CONF.network_scheduler_driver
- )
- self.router_scheduler = importutils.import_object(
- cfg.CONF.router_scheduler_driver
- )
-
- def setup_rpc(self):
- # RPC support
- self.service_topics = {svc_constants.CORE: topics.PLUGIN,
- svc_constants.L3_ROUTER_NAT: topics.L3PLUGIN}
- self.conn = rpc.create_connection(new=True)
- self.notifier = AgentNotifierApi(topics.AGENT)
- self.agent_notifiers[q_const.AGENT_TYPE_DHCP] = (
- dhcp_rpc_agent_api.DhcpAgentNotifyAPI()
- )
- self.agent_notifiers[q_const.AGENT_TYPE_L3] = (
- l3_rpc_agent_api.L3AgentNotify
- )
- self.callbacks = OVSRpcCallbacks(self.notifier, self.tunnel_type)
- self.dispatcher = self.callbacks.create_rpc_dispatcher()
- for svc_topic in self.service_topics.values():
- self.conn.create_consumer(svc_topic, self.dispatcher, fanout=False)
- # Consume from all consumers in a thread
- self.conn.consume_in_thread()
-
- def _parse_network_vlan_ranges(self):
- try:
- self.network_vlan_ranges = plugin_utils.parse_network_vlan_ranges(
- cfg.CONF.OVS.network_vlan_ranges)
- except Exception as ex:
- LOG.error(_("%s. Server terminated!"), ex)
- sys.exit(1)
- LOG.info(_("Network VLAN ranges: %s"), self.network_vlan_ranges)
-
- def _parse_tunnel_id_ranges(self):
- for entry in cfg.CONF.OVS.tunnel_id_ranges:
- entry = entry.strip()
- try:
- tun_min, tun_max = entry.split(':')
- self.tunnel_id_ranges.append((int(tun_min), int(tun_max)))
- except ValueError as ex:
- LOG.error(_("Invalid tunnel ID range: "
- "'%(range)s' - %(e)s. Server terminated!"),
- {'range': entry, 'e': ex})
- sys.exit(1)
- LOG.info(_("Tunnel ID ranges: %s"), self.tunnel_id_ranges)
-
- def _extend_network_dict_provider(self, context, network):
- binding = ovs_db_v2.get_network_binding(context.session,
- network['id'])
- network[provider.NETWORK_TYPE] = binding.network_type
- if binding.network_type in constants.TUNNEL_NETWORK_TYPES:
- network[provider.PHYSICAL_NETWORK] = None
- network[provider.SEGMENTATION_ID] = binding.segmentation_id
- elif binding.network_type == constants.TYPE_FLAT:
- network[provider.PHYSICAL_NETWORK] = binding.physical_network
- network[provider.SEGMENTATION_ID] = None
- elif binding.network_type == constants.TYPE_VLAN:
- network[provider.PHYSICAL_NETWORK] = binding.physical_network
- network[provider.SEGMENTATION_ID] = binding.segmentation_id
- elif binding.network_type == constants.TYPE_LOCAL:
- network[provider.PHYSICAL_NETWORK] = None
- network[provider.SEGMENTATION_ID] = None
-
- def _process_provider_create(self, context, attrs):
- network_type = attrs.get(provider.NETWORK_TYPE)
- physical_network = attrs.get(provider.PHYSICAL_NETWORK)
- segmentation_id = attrs.get(provider.SEGMENTATION_ID)
-
- network_type_set = attributes.is_attr_set(network_type)
- physical_network_set = attributes.is_attr_set(physical_network)
- segmentation_id_set = attributes.is_attr_set(segmentation_id)
-
- if not (network_type_set or physical_network_set or
- segmentation_id_set):
- return (None, None, None)
-
- if not network_type_set:
- msg = _("provider:network_type required")
- raise q_exc.InvalidInput(error_message=msg)
- elif network_type == constants.TYPE_FLAT:
- if segmentation_id_set:
- msg = _("provider:segmentation_id specified for flat network")
- raise q_exc.InvalidInput(error_message=msg)
- else:
- segmentation_id = constants.FLAT_VLAN_ID
- elif network_type == constants.TYPE_VLAN:
- if not segmentation_id_set:
- msg = _("provider:segmentation_id required")
- raise q_exc.InvalidInput(error_message=msg)
- if not utils.is_valid_vlan_tag(segmentation_id):
- msg = (_("provider:segmentation_id out of range "
- "(%(min_id)s through %(max_id)s)") %
- {'min_id': q_const.MIN_VLAN_TAG,
- 'max_id': q_const.MAX_VLAN_TAG})
- raise q_exc.InvalidInput(error_message=msg)
- elif network_type in constants.TUNNEL_NETWORK_TYPES:
- if not self.enable_tunneling:
- msg = _("%s networks are not enabled") % network_type
- raise q_exc.InvalidInput(error_message=msg)
- if physical_network_set:
- msg = _("provider:physical_network specified for %s "
- "network") % network_type
- raise q_exc.InvalidInput(error_message=msg)
- else:
- physical_network = None
- if not segmentation_id_set:
- msg = _("provider:segmentation_id required")
- raise q_exc.InvalidInput(error_message=msg)
- elif network_type == constants.TYPE_LOCAL:
- if physical_network_set:
- msg = _("provider:physical_network specified for local "
- "network")
- raise q_exc.InvalidInput(error_message=msg)
- else:
- physical_network = None
- if segmentation_id_set:
- msg = _("provider:segmentation_id specified for local "
- "network")
- raise q_exc.InvalidInput(error_message=msg)
- else:
- segmentation_id = None
- else:
- msg = _("provider:network_type %s not supported") % network_type
- raise q_exc.InvalidInput(error_message=msg)
-
- if network_type in [constants.TYPE_VLAN, constants.TYPE_FLAT]:
- if physical_network_set:
- if physical_network not in self.network_vlan_ranges:
- msg = _("Unknown provider:physical_network "
- "%s") % physical_network
- raise q_exc.InvalidInput(error_message=msg)
- elif 'default' in self.network_vlan_ranges:
- physical_network = 'default'
- else:
- msg = _("provider:physical_network required")
- raise q_exc.InvalidInput(error_message=msg)
-
- return (network_type, physical_network, segmentation_id)
-
- def create_network(self, context, network):
- (network_type, physical_network,
- segmentation_id) = self._process_provider_create(context,
- network['network'])
-
- session = context.session
- #set up default security groups
- tenant_id = self._get_tenant_id_for_create(
- context, network['network'])
- self._ensure_default_security_group(context, tenant_id)
-
- with session.begin(subtransactions=True):
- if not network_type:
- # tenant network
- network_type = self.tenant_network_type
- if network_type == constants.TYPE_NONE:
- raise q_exc.TenantNetworksDisabled()
- elif network_type == constants.TYPE_VLAN:
- (physical_network,
- segmentation_id) = ovs_db_v2.reserve_vlan(session)
- elif network_type in constants.TUNNEL_NETWORK_TYPES:
- segmentation_id = ovs_db_v2.reserve_tunnel(session)
- # no reservation needed for TYPE_LOCAL
- else:
- # provider network
- if network_type in [constants.TYPE_VLAN, constants.TYPE_FLAT]:
- ovs_db_v2.reserve_specific_vlan(session, physical_network,
- segmentation_id)
- elif network_type in constants.TUNNEL_NETWORK_TYPES:
- ovs_db_v2.reserve_specific_tunnel(session, segmentation_id)
- # no reservation needed for TYPE_LOCAL
- net = super(OVSNeutronPluginV2, self).create_network(context,
- network)
- ovs_db_v2.add_network_binding(session, net['id'], network_type,
- physical_network, segmentation_id)
-
- self._process_l3_create(context, net, network['network'])
- self._extend_network_dict_provider(context, net)
- # note - exception will rollback entire transaction
- LOG.debug(_("Created network: %s"), net['id'])
- return net
-
- def update_network(self, context, id, network):
- provider._raise_if_updates_provider_attributes(network['network'])
-
- session = context.session
- with session.begin(subtransactions=True):
- net = super(OVSNeutronPluginV2, self).update_network(context, id,
- network)
- self._process_l3_update(context, net, network['network'])
- self._extend_network_dict_provider(context, net)
- return net
-
- def delete_network(self, context, id):
- session = context.session
- with session.begin(subtransactions=True):
- binding = ovs_db_v2.get_network_binding(session, id)
- super(OVSNeutronPluginV2, self).delete_network(context, id)
- if binding.network_type in constants.TUNNEL_NETWORK_TYPES:
- ovs_db_v2.release_tunnel(session, binding.segmentation_id,
- self.tunnel_id_ranges)
- elif binding.network_type in [constants.TYPE_VLAN,
- constants.TYPE_FLAT]:
- ovs_db_v2.release_vlan(session, binding.physical_network,
- binding.segmentation_id,
- self.network_vlan_ranges)
- # the network_binding record is deleted via cascade from
- # the network record, so explicit removal is not necessary
- self.notifier.network_delete(context, id)
-
- def get_network(self, context, id, fields=None):
- session = context.session
- with session.begin(subtransactions=True):
- net = super(OVSNeutronPluginV2, self).get_network(context,
- id, None)
- self._extend_network_dict_provider(context, net)
- return self._fields(net, fields)
-
- def get_networks(self, context, filters=None, fields=None,
- sorts=None,
- limit=None, marker=None, page_reverse=False):
- session = context.session
- with session.begin(subtransactions=True):
- nets = super(OVSNeutronPluginV2,
- self).get_networks(context, filters, None, sorts,
- limit, marker, page_reverse)
- for net in nets:
- self._extend_network_dict_provider(context, net)
-
- return [self._fields(net, fields) for net in nets]
-
- def create_port(self, context, port):
- # Set port status as 'DOWN'. This will be updated by agent
- port['port']['status'] = q_const.PORT_STATUS_DOWN
- port_data = port['port']
- session = context.session
- with session.begin(subtransactions=True):
- self._ensure_default_security_group_on_port(context, port)
- sgids = self._get_security_groups_on_port(context, port)
- dhcp_opts = port['port'].get(edo_ext.EXTRADHCPOPTS, [])
- port = super(OVSNeutronPluginV2, self).create_port(context, port)
- self._process_portbindings_create_and_update(context,
- port_data, port)
- self._process_port_create_security_group(context, port, sgids)
- self._process_port_create_extra_dhcp_opts(context, port,
- dhcp_opts)
- port[addr_pair.ADDRESS_PAIRS] = (
- self._process_create_allowed_address_pairs(
- context, port,
- port_data.get(addr_pair.ADDRESS_PAIRS)))
- self.notify_security_groups_member_updated(context, port)
- return port
-
- def _extend_port_dict_nat(self, context, port):
- forward = ovs_db_v2.get_port_forwarding(context.session, port['id'])
- if forward:
- port[nat.FORWARD_PORTS] = forward
- else:
- port[nat.FORWARD_PORTS] = None
-
- def _process_nat_update(self, context, attrs, id):
- forward_ports = attrs.get(nat.FORWARD_PORTS)
- forward_ports_set = attributes.is_attr_set(forward_ports)
-
- if not forward_ports_set:
- return None
-
- # LOG.info("forward ports %s" % forward_ports)
- valid_protocols = ["tcp", "udp"]
- for entry in forward_ports:
- if not isinstance(entry, dict):
- msg = _("nat:forward_ports: must specify a list of dicts (ex: 'l4_protocol=tcp,l4_port=80')")
- raise q_exc.InvalidInput(error_message=msg)
- if not ("l4_protocol" in entry and "l4_port" in entry):
- msg = _("nat:forward_ports: dict is missing l4_protocol and l4_port (ex: 'l4_protocol=tcp,l4_port=80')")
- raise q_exc.InvalidInput(error_message=msg)
- if entry['l4_protocol'] not in valid_protocols:
- msg = _("nat:forward_ports: invalid protocol (only tcp and udp allowed)")
- raise q_exc.InvalidInput(error_message=msg)
-
- l4_port = entry['l4_port']
- if ":" in l4_port:
- try:
- (first, last) = l4_port.split(":")
- first = int(first)
- last = int(last)
- except:
- msg = _("nat:forward_ports: l4_port range must be integer:integer")
- raise q_exc.InvalidInput(error_message=msg)
- else:
- try:
- l4_port = int(l4_port)
- except:
- msg = _("nat:forward_ports: l4_port must be an integer")
- raise q_exc.InvalidInput(error_message=msg)
-
- return forward_ports
-
- def get_port(self, context, id, fields=None):
- session = context.session
- with session.begin(subtransactions=True):
- port = super(OVSNeutronPluginV2, self).get_port(context, id, None)
- self._extend_port_dict_nat(context, port)
- return self._fields(port, fields)
-
- def get_ports(self, context, filters=None, fields=None):
- session = context.session
- with session.begin(subtransactions=True):
- ports = super(OVSNeutronPluginV2, self).get_ports(context, filters,
- None)
- for port in ports:
- self._extend_port_dict_nat(context, port)
-
- return [self._fields(port, fields) for port in ports]
-
- def update_port(self, context, id, port):
- forward_ports = self._process_nat_update(context, port['port'], id)
-
- session = context.session
- need_port_update_notify = False
- changed_fixed_ips = 'fixed_ips' in port['port']
- with session.begin(subtransactions=True):
- original_port = super(OVSNeutronPluginV2, self).get_port(
- context, id)
- updated_port = super(OVSNeutronPluginV2, self).update_port(
- context, id, port)
- if addr_pair.ADDRESS_PAIRS in port['port']:
- self._delete_allowed_address_pairs(context, id)
- self._process_create_allowed_address_pairs(
- context, updated_port,
- port['port'][addr_pair.ADDRESS_PAIRS])
- need_port_update_notify = True
- elif changed_fixed_ips:
- self._check_fixed_ips_and_address_pairs_no_overlap(
- context, updated_port)
-
- if forward_ports:
- ovs_db_v2.clear_port_forwarding(session, updated_port['id'])
- ovs_db_v2.add_port_forwarding(session, updated_port['id'], forward_ports)
- self._extend_port_dict_nat(context, updated_port)
-
- need_port_update_notify |= self.update_security_group_on_port(
- context, id, port, original_port, updated_port)
- self._process_portbindings_create_and_update(context,
- port['port'],
- updated_port)
- need_port_update_notify |= self._update_extra_dhcp_opts_on_port(
- context, id, port, updated_port)
-
- need_port_update_notify |= self.is_security_group_member_updated(
- context, original_port, updated_port)
- if original_port['admin_state_up'] != updated_port['admin_state_up']:
- need_port_update_notify = True
-
- if need_port_update_notify:
- binding = ovs_db_v2.get_network_binding(None,
- updated_port['network_id'])
- self.notifier.port_update(context, updated_port,
- binding.network_type,
- binding.segmentation_id,
- binding.physical_network)
- return updated_port
-
- def delete_port(self, context, id, l3_port_check=True):
-
- # if needed, check to see if this is a port owned by
- # and l3-router. If so, we should prevent deletion.
- if l3_port_check:
- self.prevent_l3_port_deletion(context, id)
-
- session = context.session
- with session.begin(subtransactions=True):
- self.disassociate_floatingips(context, id)
- port = self.get_port(context, id)
- self._delete_port_security_group_bindings(context, id)
- super(OVSNeutronPluginV2, self).delete_port(context, id)
-
- self.notify_security_groups_member_updated(context, port)
diff --git a/xos/observers/base/SyncInstanceUsingAnsible.py b/xos/observers/base/SyncInstanceUsingAnsible.py
deleted file mode 100644
index 5bb8250..0000000
--- a/xos/observers/base/SyncInstanceUsingAnsible.py
+++ /dev/null
@@ -1,184 +0,0 @@
-import hashlib
-import os
-import socket
-import sys
-import base64
-import time
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from observer.ansible import run_template_ssh
-from core.models import Service, Slice, ControllerSlice, ControllerUser
-from util.logger import Logger, logging
-
-logger = Logger(level=logging.INFO)
-
-class SyncInstanceUsingAnsible(SyncStep):
- # All of the following should be defined for classes derived from this
- # base class. Examples below use VCPETenant.
-
- # provides=[VCPETenant]
- # observes=VCPETenant
- # requested_interval=0
- # template_name = "sync_vcpetenant.yaml"
- # service_key_name = "/opt/xos/observers/vcpe/vcpe_private_key"
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
-
- def defer_sync(self, o, reason):
- logger.info("defer object %s due to %s" % (str(o), reason))
- raise Exception("defer object %s due to %s" % (str(o), reason))
-
- def get_extra_attributes(self, o):
- # This is a place to include extra attributes that aren't part of the
- # object itself.
-
- return {}
-
- def get_instance(self, o):
- # We need to know what instance is associated with the object. Let's
- # assume 'o' has a field called 'instance'. If the field is called
- # something else, or if custom logic is needed, then override this
- # method.
-
- return o.instance
-
- def run_playbook(self, o, fields, template_name=None):
- if not template_name:
- template_name = self.template_name
- tStart = time.time()
- run_template_ssh(template_name, fields)
- logger.info("playbook execution time %d" % int(time.time()-tStart))
-
- def pre_sync_hook(self, o, fields):
- pass
-
- def post_sync_hook(self, o, fields):
- pass
-
- def sync_fields(self, o, fields):
- self.run_playbook(o, fields)
-
- def prepare_record(self, o):
- pass
-
- def get_node(self,o):
- return o.node
-
- def get_node_key(self, node):
- return "/root/setup/node_key"
-
- def get_ansible_fields(self, instance):
- # return all of the fields that tell Ansible how to talk to the context
- # that's setting up the container.
-
- if (instance.isolation == "vm"):
- # legacy where container was configured by sync_vcpetenant.py
-
- fields = { "instance_name": instance.name,
- "hostname": instance.node.name,
- "instance_id": instance.instance_id,
- "username": "ubuntu",
- }
- key_name = self.service_key_name
- elif (instance.isolation == "container"):
- # container on bare metal
- node = self.get_node(instance)
- hostname = node.name
- fields = { "hostname": hostname,
- "baremetal_ssh": True,
- "instance_name": "rootcontext",
- "username": "root",
- "container_name": "%s-%s" % (instance.slice.name, str(instance.id))
- }
- key_name = self.get_node_key(node)
- else:
- # container in a VM
- if not instance.parent:
- raise Exception("Container-in-VM has no parent")
- if not instance.parent.instance_id:
- raise Exception("Container-in-VM parent is not yet instantiated")
- if not instance.parent.slice.service:
- raise Exception("Container-in-VM parent has no service")
- if not instance.parent.slice.service.private_key_fn:
- raise Exception("Container-in-VM parent service has no private_key_fn")
- fields = { "hostname": instance.parent.node.name,
- "instance_name": instance.parent.name,
- "instance_id": instance.parent.instance_id,
- "username": "ubuntu",
- "nat_ip": instance.parent.get_ssh_ip(),
- "container_name": "%s-%s" % (instance.slice.name, str(instance.id))
- }
- key_name = instance.parent.slice.service.private_key_fn
-
- if not os.path.exists(key_name):
- raise Exception("Node key %s does not exist" % node_key_name)
-
- key = file(key_name).read()
-
- fields["private_key"] = key
-
- # now the ceilometer stuff
-
- cslice = ControllerSlice.objects.get(slice=instance.slice)
- if not cslice:
- raise Exception("Controller slice object for %s does not exist" % instance.slice.name)
-
- cuser = ControllerUser.objects.get(user=instance.creator)
- if not cuser:
- raise Exception("Controller user object for %s does not exist" % instance.creator)
-
- fields.update({"keystone_tenant_id": cslice.tenant_id,
- "keystone_user_id": cuser.kuser_id,
- "rabbit_user": instance.controller.rabbit_user,
- "rabbit_password": instance.controller.rabbit_password,
- "rabbit_host": instance.controller.rabbit_host})
-
- return fields
-
- def sync_record(self, o):
- logger.info("sync'ing object %s" % str(o))
-
- self.prepare_record(o)
-
- instance = self.get_instance(o)
-
- if isinstance(instance, basestring):
- # sync to some external host
-
- # XXX - this probably needs more work...
-
- fields = { "hostname": instance,
- "instance_id": "ubuntu", # this is the username to log into
- "private_key": service.key,
- }
- else:
- # sync to an XOS instance
- if not instance:
- self.defer_sync(o, "waiting on instance")
- return
-
- if not instance.instance_name:
- self.defer_sync(o, "waiting on instance.instance_name")
- return
-
- fields = self.get_ansible_fields(instance)
-
- fields["ansible_tag"] = o.__class__.__name__ + "_" + str(o.id)
-
- # If 'o' defines a 'sync_attributes' list, then we'll copy those
- # attributes into the Ansible recipe's field list automatically.
- if hasattr(o, "sync_attributes"):
- for attribute_name in o.sync_attributes:
- fields[attribute_name] = getattr(o, attribute_name)
-
- fields.update(self.get_extra_attributes(o))
-
- self.sync_fields(o, fields)
-
- o.save()
-
- def delete_record(self, m):
- pass
-
diff --git a/xos/observers/base/SyncSliverUsingAnsible.py b/xos/observers/base/SyncSliverUsingAnsible.py
deleted file mode 100644
index 9455780..0000000
--- a/xos/observers/base/SyncSliverUsingAnsible.py
+++ /dev/null
@@ -1,95 +0,0 @@
-import hashlib
-import os
-import socket
-import sys
-import base64
-import time
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from observer.ansible import run_template_ssh
-from core.models import Service, Slice
-from util.logger import Logger, logging
-
-logger = Logger(level=logging.INFO)
-
-class SyncInstanceUsingAnsible(SyncStep):
- # All of the following should be defined for classes derived from this
- # base class. Examples below use VCPETenant.
-
- # provides=[VCPETenant]
- # observes=VCPETenant
- # requested_interval=0
- # template_name = "sync_vcpetenant.yaml"
- # service_key_name = "/opt/xos/observers/vcpe/vcpe_private_key"
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
-
- def defer_sync(self, o, reason):
- logger.info("defer object %s due to %s" % (str(o), reason))
- raise Exception("defer object %s due to %s" % (str(o), reason))
-
- def get_extra_attributes(self, o):
- # This is a place to include extra attributes that aren't part of the
- # object itself.
-
- return {}
-
- def get_instance(self, o):
- # We need to know what instance is associated with the object. Let's
- # assume 'o' has a field called 'instance'. If the field is called
- # something else, or if custom logic is needed, then override this
- # method.
-
- return o.instance
-
- def run_playbook(self, o, fields):
- tStart = time.time()
- run_template_ssh(self.template_name, fields)
- logger.info("playbook execution time %d" % int(time.time()-tStart))
-
- def pre_sync_hook(self, o, fields):
- pass
-
- def post_sync_hook(self, o, fields):
- pass
-
- def sync_fields(self, o, fields):
- self.run_playbook(o, fields)
-
- def sync_record(self, o):
- logger.info("sync'ing object %s" % str(o))
-
- instance = self.get_instance(o)
- if not instance:
- self.defer_sync(o, "waiting on instance")
- return
-
- if not os.path.exists(self.service_key_name):
- raise Exception("Service key %s does not exist" % self.service_key_name)
-
- service_key = file(self.service_key_name).read()
-
- fields = { "instance_name": instance.name,
- "hostname": instance.node.name,
- "instance_id": instance.instance_id,
- "private_key": service_key,
- "ansible_tag": "vcpe_tenant_" + str(o.id)
- }
-
- # If 'o' defines a 'sync_attributes' list, then we'll copy those
- # attributes into the Ansible recipe's field list automatically.
- if hasattr(o, "sync_attributes"):
- for attribute_name in o.sync_attributes:
- fields[attribute_name] = getattr(o, attribute_name)
-
- fields.update(self.get_extra_attributes(o))
-
- self.sync_fields(o, fields)
-
- o.save()
-
- def delete_record(self, m):
- pass
-
diff --git a/xos/observers/base/__init__.py b/xos/observers/base/__init__.py
deleted file mode 100644
index 8b13789..0000000
--- a/xos/observers/base/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/xos/observers/helloworld/helloworld-observer.py b/xos/observers/helloworld/helloworld-observer.py
deleted file mode 100755
index d6a71ff..0000000
--- a/xos/observers/helloworld/helloworld-observer.py
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/usr/bin/env python
-
-# This imports and runs ../../xos-observer.py
-
-import importlib
-import os
-import sys
-observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../..")
-sys.path.append(observer_path)
-mod = importlib.import_module("xos-observer")
-mod.main()
diff --git a/xos/observers/helloworld/helloworld_config b/xos/observers/helloworld/helloworld_config
deleted file mode 100644
index e32ee0c..0000000
--- a/xos/observers/helloworld/helloworld_config
+++ /dev/null
@@ -1,47 +0,0 @@
-[plc]
-name=plc
-deployment=plc
-
-[db]
-name=xos
-user=postgres
-password=password
-host=localhost
-port=5432
-
-[api]
-host=localhost
-port=8000
-ssl_key=None
-ssl_cert=None
-ca_ssl_cert=None
-ratelimit_enabled=0
-omf_enabled=0
-mail_support_address=support@localhost
-nova_enabled=True
-logfile=/var/log/xos.log
-
-[nova]
-admin_user=admin@domain.com
-admin_password=admin
-admin_tenant=admin
-url=http://localhost:5000/v2.0/
-default_image=None
-default_flavor=m1.small
-default_security_group=default
-ca_ssl_cert=/etc/ssl/certs/ca-certificates.crt
-
-[observer]
-pretend=False
-backoff_disabled=False
-images_directory=/opt/xos/images
-dependency_graph=/opt/xos/model-deps
-logfile=/var/log/xos_backend.log
-steps_dir=/opt/xos/observers/helloworld/steps
-applist=helloworld
-
-[gui]
-disable_minidashboard=True
-#branding_name=CORD
-#branding_css=/static/cord.css
-#branding_icon=/static/onos-logo.png
diff --git a/xos/observers/helloworld/steps/sync_hello.py b/xos/observers/helloworld/steps/sync_hello.py
deleted file mode 100644
index 7071ea0..0000000
--- a/xos/observers/helloworld/steps/sync_hello.py
+++ /dev/null
@@ -1,26 +0,0 @@
-import os
-import sys
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from helloworld.models import Hello,World
-from util.logger import Logger, logging
-
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-logger = Logger(level=logging.INFO)
-
-class SyncHello(SyncStep):
- provides=[Hello]
- observes=Hello
- requested_interval=0
-
- def sync_record(self, record):
- instance = record.instance_backref
- instance.userData="packages:\n - apache2\nruncmd:\n - update-rc.d apache2 enable\n - service apache2 start\nwrite_files:\n- content: Hello %s\n path: /var/www/html/hello.txt"%record.name
- instance.save()
-
- def delete_record(self, m):
- return
diff --git a/xos/observers/helloworld/steps/sync_world.py b/xos/observers/helloworld/steps/sync_world.py
deleted file mode 100644
index 01e285f..0000000
--- a/xos/observers/helloworld/steps/sync_world.py
+++ /dev/null
@@ -1,25 +0,0 @@
-import os
-import sys
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from helloworld.models import Hello,World
-from util.logger import Logger, logging
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-logger = Logger(level=logging.INFO)
-
-class SyncWorld(SyncStep):
- provides=[World]
- observes=World
- requested_interval=0
-
- def sync_record(self, record):
- open('/tmp/hello-synchronizer','w').write(record.name)
-
- def delete_record(self, m):
- return
diff --git a/xos/observers/helloworldservice_complete/helloworldservice-observer.py b/xos/observers/helloworldservice_complete/helloworldservice-observer.py
deleted file mode 100755
index 75dcc46..0000000
--- a/xos/observers/helloworldservice_complete/helloworldservice-observer.py
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/usr/bin/env python
-
-# This imports and runs ../../xos-observer.py
-# Runs the standard XOS observer
-
-import importlib
-import os
-import sys
-observer_path = os.path.join(os.path.dirname(
- os.path.realpath(__file__)), "../..")
-sys.path.append(observer_path)
-mod = importlib.import_module("xos-observer")
-mod.main()
diff --git a/xos/observers/helloworldservice_complete/helloworldservice_config b/xos/observers/helloworldservice_complete/helloworldservice_config
deleted file mode 100644
index 716e3a0..0000000
--- a/xos/observers/helloworldservice_complete/helloworldservice_config
+++ /dev/null
@@ -1,36 +0,0 @@
-# Required by XOS
-[db]
-name=xos
-user=postgres
-password=password
-host=localhost
-port=5432
-
-# Required by XOS
-[api]
-nova_enabled=True
-
-# Sets options for the observer
-[observer]
-# Optional name
-name=helloworldservice
-# This is the location to the dependency graph you generate
-dependency_graph=/opt/xos/observers/helloworldservice_complete/model-deps
-# The location of your SyncSteps
-steps_dir=/opt/xos/observers/helloworldservice_complete/steps
-# A temporary directory that will be used by ansible
-sys_dir=/opt/xos/observers/helloworldservice_complete/sys
-# Location of the file to save logging messages to the backend log is often used
-logfile=/var/log/xos_backend.log
-# If this option is true, then nothing will change, we simply pretend to run
-pretend=False
-# If this is False then XOS will use an exponential backoff when the observer
-# fails, since we will be waiting for an instance, we don't want this.
-backoff_disabled=True
-# We want the output from ansible to be logged
-save_ansible_output=True
-# This determines how we SSH to a client, if this is set to True then we try
-# to ssh using the instance name as a proxy, if this is disabled we ssh using
-# the NAT IP of the instance. On CloudLab the first option will fail so we must
-# set this to False
-proxy_ssh=False
diff --git a/xos/observers/helloworldservice_complete/steps/sync_helloworldtenant.py b/xos/observers/helloworldservice_complete/steps/sync_helloworldtenant.py
deleted file mode 100644
index a4b5435..0000000
--- a/xos/observers/helloworldservice_complete/steps/sync_helloworldtenant.py
+++ /dev/null
@@ -1,48 +0,0 @@
-import os
-import sys
-from django.db.models import Q, F
-from helloworldservice_complete.models import HelloWorldServiceComplete, HelloWorldTenantComplete
-from observers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
-
-parentdir = os.path.join(os.path.dirname(__file__), "..")
-sys.path.insert(0, parentdir)
-
-# Class to define how we sync a tenant. Using SyncInstanceUsingAnsible we
-# indicate where the find the YAML for ansible, where to find the SSH key,
-# and the logic for determining what tenant needs updating, what additional
-# attributes are needed, and how to delete an instance.
-class SyncHelloWorldTenantComplete(SyncInstanceUsingAnsible):
- # Indicates the position in the data model, this will run when XOS needs to
- # enact a HelloWorldTenantComplete
- provides = [HelloWorldTenantComplete]
- # The actual model being enacted, usually the same as provides.
- observes = HelloWorldTenantComplete
- # Number of milliseconds between interruptions of the observer
- requested_interval = 0
- # The ansible template to run
- template_name = "sync_helloworldtenant.yaml"
- # The location of the SSH private key to use when ansible connects to
- # instances.
- service_key_name = "/opt/xos/observers/helloworldservice_complete/helloworldservice_private_key"
-
- def __init__(self, *args, **kwargs):
- super(SyncHelloWorldTenantComplete, self).__init__(*args, **kwargs)
-
- # Defines the logic for determining what HelloWorldTenantCompletes need to be
- # enacted.
- def fetch_pending(self, deleted):
- # If the update is not a deletion, then we get all of the instnaces that
- # have been updated or have not been enacted.
- if (not deleted):
- objs = HelloWorldTenantComplete.get_tenant_objects().filter(
- Q(enacted__lt=F('updated')) | Q(enacted=None), Q(lazy_blocked=False))
- else:
- # If this is a deletion we get all of the deleted tenants..
- objs = HelloWorldTenantComplete.get_deleted_tenant_objects()
-
- return objs
-
- # Gets the attributes that are used by the Ansible template but are not
- # part of the set of default attributes.
- def get_extra_attributes(self, o):
- return {"display_message": o.display_message}
diff --git a/xos/observers/hpc/fsck.py b/xos/observers/hpc/fsck.py
deleted file mode 100644
index 0c551f8..0000000
--- a/xos/observers/hpc/fsck.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/env python
-import argparse
-import imp
-import inspect
-import os
-import sys
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-sys.path.append("/opt/xos")
-from xos.config import Config, DEFAULT_CONFIG_FN, XOS_DIR
-from util.logger import Logger, logging
-from observer.syncstep import SyncStep
-
-try:
- from django import setup as django_setup # django 1.7
-except:
- django_setup = False
-
-logger = Logger(level=logging.INFO)
-
-class XOSConsistencyCheck:
- def __init__(self):
- self.sync_steps = []
- self.load_sync_step_modules()
-
- def load_sync_step_modules(self, step_dir=None):
- if step_dir is None:
- if hasattr(Config(), "observer_steps_dir"):
- step_dir = Config().observer_steps_dir
- else:
- step_dir = XOS_DIR+"/observer/steps"
-
- for fn in os.listdir(step_dir):
- pathname = os.path.join(step_dir,fn)
- if os.path.isfile(pathname) and fn.endswith(".py") and (fn!="__init__.py"):
- module = imp.load_source(fn[:-3],pathname)
- for classname in dir(module):
- c = getattr(module, classname, None)
-
- # make sure 'c' is a descendent of SyncStep and has a
- # provides field (this eliminates the abstract base classes
- # since they don't have a provides)
-
- if inspect.isclass(c) and issubclass(c, SyncStep) and hasattr(c,"provides") and (c not in self.sync_steps):
- self.sync_steps.append(c)
- logger.info('loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps]))
-
- def run(self):
- updated = True
- while updated:
- updated = False
-
- for step in self.sync_steps:
- if hasattr(step, "consistency_check"):
- updated = updated or step(driver=None).consistency_check()
-
- if updated:
- logger.info('re-running consistency checks because something changed')
-
-def main():
- if not "-C" in sys.argv:
- print >> sys.stderr, "You probably wanted to use -C " + XOS_DIR + "/hpc_observer/hpc_observer_config"
-
- # Generate command line parser
- parser = argparse.ArgumentParser(usage='%(prog)s [options]')
- # smbaker: util/config.py parses sys.argv[] directly to get config file name; include the option here to avoid
- # throwing unrecognized argument exceptions
- parser.add_argument('-C', '--config', dest='config_file', action='store', default=DEFAULT_CONFIG_FN,
- help='Name of config file.')
- args = parser.parse_args()
-
- if django_setup: # 1.7
- django_setup()
-
- cc = XOSConsistencyCheck()
- cc.run()
-
-if __name__ == '__main__':
- main()
-
diff --git a/xos/observers/hpc/hpc-observer.py b/xos/observers/hpc/hpc-observer.py
deleted file mode 100755
index d6a71ff..0000000
--- a/xos/observers/hpc/hpc-observer.py
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/usr/bin/env python
-
-# This imports and runs ../../xos-observer.py
-
-import importlib
-import os
-import sys
-observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../..")
-sys.path.append(observer_path)
-mod = importlib.import_module("xos-observer")
-mod.main()
diff --git a/xos/observers/hpc/hpc_observer_config b/xos/observers/hpc/hpc_observer_config
deleted file mode 100644
index 326e731..0000000
--- a/xos/observers/hpc/hpc_observer_config
+++ /dev/null
@@ -1,36 +0,0 @@
-
-[plc]
-name=plc
-deployment=VICCI
-
-[db]
-name=xos
-user=postgres
-password=password
-host=localhost
-port=5432
-
-[api]
-host=128.112.171.237
-port=8000
-ssl_key=None
-ssl_cert=None
-ca_ssl_cert=None
-ratelimit_enabled=0
-omf_enabled=0
-mail_support_address=support@localhost
-nova_enabled=True
-
-[observer]
-name=hpc
-dependency_graph=/opt/xos/observers/hpc/model-deps
-steps_dir=/opt/xos/observers/hpc/steps
-deleters_dir=/opt/xos/observers/hpc/deleters
-log_file=console
-#/var/log/hpc.log
-driver=None
-#cmi_hostname=openclouddev0.internet2.edu
-
-[feefie]
-client_id='vicci_dev_central'
-user_id='pl'
diff --git a/xos/observers/hpc/hpc_watcher.py b/xos/observers/hpc/hpc_watcher.py
deleted file mode 100644
index 7c49aae..0000000
--- a/xos/observers/hpc/hpc_watcher.py
+++ /dev/null
@@ -1,629 +0,0 @@
-"""
- hpc_watcher.py
-
- Daemon to watch the health of HPC and RR instances.
-
- This deamon uses HpcHealthCheck objects in the Data Model to conduct
- periodic tests of HPC and RR nodes. Two types of Health Checks are
- supported:
-
- kind="dns": checks the request routers to make sure that a DNS
- name is resolveable and returns the right kind of records.
-
- resource_name should be set to the domain name to lookup.
-
- result_contains is option and can be used to hold "A", "CNAME", or
- a particular address or hostname that should be contained in the
- query's answer.
-
- kind="http": checks the hpc nodes to make sure that a URL can be
- retrieved from the node.
-
- resource_name should be set to the HostName:Url to fetch. For
- example, cdn-stream.htm.fiu.edu:/hft2441/intro.mp4
-
- In addition to the above, HPC heartbeat probes are conducted, similar to
- the ones that dnsredir conducts.
-
- The results of health checks are stored in a tag attached to the Instance
- the healthcheck was conducted against. If all healthchecks of a particular
- variety were successful for a instance, then "success" will be stored in
- the tag. Otherwise, the first healthcheck to fail will be stored in the
- tag.
-
- Ubuntu prereqs:
- apt-get install python-pycurl
- pip install dnslib
-"""
-
-import os
-import socket
-import sys
-sys.path.append("/opt/xos")
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-import django
-from django.contrib.contenttypes.models import ContentType
-from core.models import *
-from hpc.models import *
-from requestrouter.models import *
-django.setup()
-import time
-import pycurl
-import traceback
-import json
-from StringIO import StringIO
-
-from dnslib.dns import DNSRecord,DNSHeader,DNSQuestion,QTYPE
-from dnslib.digparser import DigParser
-
-from threading import Thread, Condition
-
-"""
-from dnslib import *
-q = DNSRecord(q=DNSQuestion("cdn-stream.htm.fiu.edu"))
-a_pkt = q.send("150.135.65.10", tcp=False, timeout=10)
-a = DNSRecord.parse(a_pkt)
-
-from dnslib import *
-q = DNSRecord(q=DNSQuestion("onlab.vicci.org"))
-a_pkt = q.send("150.135.65.10", tcp=False, timeout=10)
-a = DNSRecord.parse(a_pkt)
-"""
-
-class WorkQueue:
- def __init__(self):
- self.job_cv = Condition()
- self.jobs = []
- self.result_cv = Condition()
- self.results = []
- self.outstanding = 0
-
- def get_job(self):
- self.job_cv.acquire()
- while not self.jobs:
- self.job_cv.wait()
- result = self.jobs.pop()
- self.job_cv.release()
- return result
-
- def submit_job(self, job):
- self.job_cv.acquire()
- self.jobs.append(job)
- self.job_cv.notify()
- self.job_cv.release()
- self.outstanding = self.outstanding + 1
-
- def get_result(self):
- self.result_cv.acquire()
- while not self.results:
- self.result_cv.wait()
- result = self.results.pop()
- self.result_cv.release()
- self.outstanding = self.outstanding - 1
- return result
-
- def submit_result(self, result):
- self.result_cv.acquire()
- self.results.append(result)
- self.result_cv.notify()
- self.result_cv.release()
-
-class DnsResolver(Thread):
- def __init__(self, queue):
- Thread.__init__(self)
- self.queue = queue
- self.daemon = True
- self.start()
-
- def run(self):
- while True:
- job = self.queue.get_job()
- self.handle_job(job)
- self.queue.submit_result(job)
-
- def handle_job(self, job):
- domain = job["domain"]
- server = job["server"]
- port = job["port"]
- result_contains = job.get("result_contains", None)
-
- try:
- q = DNSRecord(q=DNSQuestion(domain)) #, getattr(QTYPE,"A")))
-
- a_pkt = q.send(server, port, tcp=False, timeout=10)
- a = DNSRecord.parse(a_pkt)
-
- found_record = False
- for record in a.rr:
- if (not result_contains):
- QTYPE_A = getattr(QTYPE,"A")
- QTYPE_CNAME = getattr(QTYPE, "CNAME")
- if ((record.rtype==QTYPE_A) or (record.qtype==QTYPE_CNAME)):
- found_record = True
- else:
- tmp = QTYPE.get(record.rtype) + str(record.rdata)
- if (result_contains in tmp):
- found_record = True
-
- if not found_record:
- if result_contains:
- job["status"] = "%s,No %s records" % (domain, result_contains)
- else:
- job["status"] = "%s,No A or CNAME records" % domain
-
- return
-
- except Exception, e:
- job["status"] = "%s,Exception: %s" % (domain, str(e))
- return
-
- job["status"] = "success"
-
-class HpcHeartbeat(Thread):
- def __init__(self, queue):
- Thread.__init__(self)
- self.queue = queue
- self.daemon = True
- self.start()
-
- def run(self):
- while True:
- job = self.queue.get_job()
- self.handle_job(job)
- self.queue.submit_result(job)
-
- def curl_error_message(self, e):
- if e.args[0] == 6:
- return "couldn't resolve host"
- if e.args[0] == 7:
- return "failed to connect"
- return "curl error %d" % e.args[0]
-
- def handle_job(self, job):
- server = job["server"]
- port = job["port"]
-
- try:
- buffer = StringIO()
- c = pycurl.Curl()
-
- c.setopt(c.URL, "http://%s:%s/heartbeat" % (server, port))
- c.setopt(c.WRITEDATA, buffer)
- c.setopt(c.HTTPHEADER, ['host: hpc-heartbeat', 'X-heartbeat: 1'])
- c.setopt(c.TIMEOUT, 10)
- c.setopt(c.CONNECTTIMEOUT, 10)
- c.setopt(c.NOSIGNAL, 1)
-
- try:
- c.perform()
- response_code = c.getinfo(c.RESPONSE_CODE)
- except Exception, e:
- #traceback.print_exc()
- job["status"] = self.curl_error_message(e)
- return
- finally:
- c.close()
-
- if response_code != 200:
- job["status"] = "error response %d" % response_code
- return
-
- except Exception, e:
- job["status"] = "Exception: %s" % str(e)
- return
-
- job["status"] = "success"
-
-class HpcFetchUrl(Thread):
- def __init__(self, queue):
- Thread.__init__(self)
- self.queue = queue
- self.daemon = True
- self.start()
-
- def run(self):
- while True:
- job = self.queue.get_job()
- self.handle_job(job)
- self.queue.submit_result(job)
-
- def curl_error_message(self, e):
- if e.args[0] == 6:
- return "couldn't resolve host"
- if e.args[0] == 7:
- return "failed to connect"
- return "curl error %d" % e.args[0]
-
- def handle_job(self, job):
- server = job["server"]
- port = job["port"]
- url = job["url"]
- domain = job["domain"]
-
- def progress(download_t, download_d, upload_t, upload_d):
- # limit download size to a megabyte
- if (download_d > 1024*1024):
- return 1
- else:
- return 0
-
- try:
- buffer = StringIO()
- c = pycurl.Curl()
-
- c.setopt(c.URL, "http://%s:%s/%s" % (server, port, url))
- c.setopt(c.WRITEDATA, buffer)
- c.setopt(c.HTTPHEADER, ['host: ' + domain])
- c.setopt(c.TIMEOUT, 10)
- c.setopt(c.CONNECTTIMEOUT, 10)
- c.setopt(c.NOSIGNAL, 1)
- c.setopt(c.NOPROGRESS, 0)
- c.setopt(c.PROGRESSFUNCTION, progress)
-
- try:
- try:
- c.perform()
- except Exception, e:
- # prevent callback abort from raising exception
- if (e.args[0] != pycurl.E_ABORTED_BY_CALLBACK):
- raise
- response_code = c.getinfo(c.RESPONSE_CODE)
- bytes_downloaded = int(c.getinfo(c.SIZE_DOWNLOAD))
- total_time = float(c.getinfo(c.TOTAL_TIME))
- except Exception, e:
- #traceback.print_exc()
- job["status"] = self.curl_error_message(e)
- return
- finally:
- c.close()
-
- if response_code != 200:
- job["status"] = "error response %s" % str(response_code)
- return
-
- except Exception, e:
- #traceback.print_exc()
- job["status"] = "Exception: %s" % str(e)
- return
-
- job["status"] = "success"
- job["bytes_downloaded"] = bytes_downloaded
- job["total_time"] = total_time
-
-class WatcherWorker(Thread):
- def __init__(self, queue):
- Thread.__init__(self)
- self.queue = queue
- self.daemon = True
- self.start()
-
- def run(self):
- while True:
- job = self.queue.get_job()
- self.handle_job(job)
- self.queue.submit_result(job)
-
- def curl_error_message(self, e):
- if e.args[0] == 6:
- return "couldn't resolve host"
- if e.args[0] == 7:
- return "failed to connect"
- return "curl error %d" % e.args[0]
-
- def handle_job(self, job):
- server = job["server"]
- port = job["port"]
-
- try:
- buffer = StringIO()
- c = pycurl.Curl()
-
- c.setopt(c.URL, "http://%s:%s/" % (server, port))
- c.setopt(c.WRITEDATA, buffer)
- c.setopt(c.TIMEOUT, 10)
- c.setopt(c.CONNECTTIMEOUT, 10)
- c.setopt(c.NOSIGNAL, 1)
-
- try:
- c.perform()
- response_code = c.getinfo(c.RESPONSE_CODE)
- except Exception, e:
- #traceback.print_exc()
- job["status"] = json.dumps( {"status": self.curl_error_message(e)} )
- return
- finally:
- c.close()
-
- if response_code != 200:
- job["status"] = json.dumps( {"status": "error response %d" % response_code} )
- return
-
- d = json.loads(buffer.getvalue())
- d["status"] = "success";
- job["status"] = json.dumps(d)
-
- except Exception, e:
- job["status"] = json.dumps( {"status": "Exception: %s" % str(e)} )
- return
-
-class BaseWatcher(Thread):
- def __init__(self):
- Thread.__init__(self)
- self.daemon = True
-
- def get_public_ip(self, service, instance):
- network_name = None
- if "hpc" in instance.slice.name:
- network_name = getattr(service, "watcher_hpc_network", None)
- elif "demux" in instance.slice.name:
- network_name = getattr(service, "watcher_dnsdemux_network", None)
- elif "redir" in instance.slice.name:
- network_name = getattr(service, "watcher_dnsredir_network", None)
-
- if network_name and network_name.lower()=="nat":
- return None
-
- if (network_name is None) or (network_name=="") or (network_name.lower()=="public"):
- return instance.get_public_ip()
-
- for ns in instance.ports.all():
- if (ns.ip) and (ns.network.name==network_name):
- return ns.ip
-
- raise ValueError("Couldn't find network %s" % str(network_name))
-
- def set_status(self, instance, service, kind, msg, check_error=True):
- #print instance.node.name, kind, msg
- if check_error:
- instance.has_error = (msg!="success")
-
- instance_type = ContentType.objects.get_for_model(instance)
-
- t = Tag.objects.filter(service=service, name=kind+".msg", content_type__pk=instance_type.id, object_id=instance.id)
- if t:
- t=t[0]
- if (t.value != msg):
- t.value = msg
- t.save()
- else:
- Tag(service=service, name=kind+".msg", content_object = instance, value=msg).save()
-
- t = Tag.objects.filter(service=service, name=kind+".time", content_type__pk=instance_type.id, object_id=instance.id)
- if t:
- t=t[0]
- t.value = str(time.time())
- t.save()
- else:
- Tag(service=service, name=kind+".time", content_object = instance, value=str(time.time())).save()
-
- def get_service_slices(self, service, kind=None):
- try:
- slices = service.slices.all()
- except:
- # buggy data model
- slices = service.service.all()
-
- if kind:
- return [x for x in slices if (kind in x.name)]
- else:
- return list(slices)
-
-class RRWatcher(BaseWatcher):
- def __init__(self):
- BaseWatcher.__init__(self)
-
- self.resolver_queue = WorkQueue()
- for i in range(0,10):
- DnsResolver(queue = self.resolver_queue)
-
- def check_request_routers(self, service, instances):
- for instance in instances:
- instance.has_error = False
-
- try:
- ip = self.get_public_ip(service, instance)
- except Exception, e:
- self.set_status(instance, service, "watcher.DNS", "exception: %s" % str(e))
- continue
- if not ip:
- try:
- ip = socket.gethostbyname(instance.node.name)
- except:
- self.set_status(instance, service, "watcher.DNS", "dns resolution failure")
- continue
-
- if not ip:
- self.set_status(instance, service, "watcher.DNS", "no IP address")
- continue
-
- checks = HpcHealthCheck.objects.filter(kind="dns")
- if not checks:
- self.set_status(instance, service, "watcher.DNS", "no DNS HealthCheck tests configured")
-
- for check in checks:
- self.resolver_queue.submit_job({"domain": check.resource_name, "server": ip, "port": 53, "instance": instance, "result_contains": check.result_contains})
-
- while self.resolver_queue.outstanding > 0:
- result = self.resolver_queue.get_result()
- instance = result["instance"]
- if (result["status"]!="success") and (not instance.has_error):
- self.set_status(instance, service, "watcher.DNS", result["status"])
-
- for instance in instances:
- if not instance.has_error:
- self.set_status(instance, service, "watcher.DNS", "success")
-
- def run_once(self):
- for hpcService in HpcService.objects.all():
- for slice in self.get_service_slices(hpcService, "dnsdemux"):
- self.check_request_routers(hpcService, slice.instances.all())
-
- for rrService in RequestRouterService.objects.all():
- for slice in self.get_service_slices(rrService, "dnsdemux"):
- self.check_request_routers(rrService, slice.instances.all())
-
- def run(self):
- while True:
- self.run_once()
- time.sleep(10)
-
- django.db.reset_queries()
-
-class HpcProber(BaseWatcher):
- def __init__(self):
- BaseWatcher.__init__(self)
-
- self.heartbeat_queue = WorkQueue()
- for i in range(0, 10):
- HpcHeartbeat(queue = self.heartbeat_queue)
-
- def probe_hpc(self, service, instances):
- for instance in instances:
- instance.has_error = False
-
- self.heartbeat_queue.submit_job({"server": instance.node.name, "port": 8009, "instance": instance})
-
- while self.heartbeat_queue.outstanding > 0:
- result = self.heartbeat_queue.get_result()
- instance = result["instance"]
- if (result["status"]!="success") and (not instance.has_error):
- self.set_status(instance, service, "watcher.HPC-hb", result["status"])
-
- for instance in instances:
- if not instance.has_error:
- self.set_status(instance, service, "watcher.HPC-hb", "success")
-
- def run_once(self):
- for hpcService in HpcService.objects.all():
- for slice in self.get_service_slices(hpcService, "hpc"):
- self.probe_hpc(hpcService, slice.instances.all())
-
- def run(self):
- while True:
- self.run_once()
- time.sleep(10)
-
- django.db.reset_queries()
-
-class HpcFetcher(BaseWatcher):
- def __init__(self):
- BaseWatcher.__init__(self)
-
- self.fetch_queue = WorkQueue()
- for i in range(0, 10):
- HpcFetchUrl(queue = self.fetch_queue)
-
- def fetch_hpc(self, service, instances):
- for instance in instances:
- instance.has_error = False
- instance.url_status = []
-
- checks = HpcHealthCheck.objects.filter(kind="http")
- if not checks:
- self.set_status(instance, service, "watcher.HPC-fetch", "no HTTP HealthCheck tests configured")
-
- for check in checks:
- if (not check.resource_name) or (":" not in check.resource_name):
- self.set_status(instance, service, "watcher.HPC-fetch", "malformed resource_name: " + str(check.resource_name))
- break
-
- (domain, url) = check.resource_name.split(":",1)
-
- self.fetch_queue.submit_job({"server": instance.node.name, "port": 80, "instance": instance, "domain": domain, "url": url})
-
- while self.fetch_queue.outstanding > 0:
- result = self.fetch_queue.get_result()
- instance = result["instance"]
- if (result["status"] == "success"):
- instance.url_status.append( (result["domain"] + result["url"], "success", result["bytes_downloaded"], result["total_time"]) )
- if (result["status"]!="success") and (not instance.has_error):
- self.set_status(instance, service, "watcher.HPC-fetch", result["status"])
-
- for instance in instances:
- self.set_status(instance, service, "watcher.HPC-fetch-urls", json.dumps(instance.url_status), check_error=False)
- if not instance.has_error:
- self.set_status(instance, service, "watcher.HPC-fetch", "success")
-
- def run_once(self):
- for hpcService in HpcService.objects.all():
- for slice in self.get_service_slices(hpcService, "hpc"):
- try:
- self.fetch_hpc(hpcService, slice.instances.all())
- except:
- traceback.print_exc()
-
- def run(self):
- while True:
- self.run_once()
- time.sleep(10)
-
- django.db.reset_queries()
-
-class WatcherFetcher(BaseWatcher):
- def __init__(self):
- BaseWatcher.__init__(self)
-
- self.fetch_queue = WorkQueue()
- for i in range(0, 10):
- WatcherWorker(queue = self.fetch_queue)
-
- def fetch_watcher(self, service, instances):
- for instance in instances:
- try:
- ip = self.get_public_ip(service, instance)
- except Exception, e:
- self.set_status(instance, service, "watcher.watcher", json.dumps({"status": "exception: %s" % str(e)}) )
- continue
- if not ip:
- try:
- ip = socket.gethostbyname(instance.node.name)
- except:
- self.set_status(instance, service, "watcher.watcher", json.dumps({"status": "dns resolution failure"}) )
- continue
-
- if not ip:
- self.set_status(instance, service, "watcher.watcher", json.dumps({"status": "no IP address"}) )
- continue
-
- port = 8015
- if ("redir" in instance.slice.name):
- port = 8016
- elif ("demux" in instance.slice.name):
- port = 8017
-
- self.fetch_queue.submit_job({"server": ip, "port": port, "instance": instance})
-
- while self.fetch_queue.outstanding > 0:
- result = self.fetch_queue.get_result()
- instance = result["instance"]
- self.set_status(instance, service, "watcher.watcher", result["status"])
-
- def run_once(self):
- for hpcService in HpcService.objects.all():
- for slice in self.get_service_slices(hpcService):
- self.fetch_watcher(hpcService, slice.instances.all())
-
- def run(self):
- while True:
- self.run_once()
- time.sleep(10)
-
- django.db.reset_queries()
-
-
-if __name__ == "__main__":
- if "--once" in sys.argv:
- RRWatcher().run_once()
- HpcProber().run_once()
- HpcFetcher().run_once()
- WatcherFetcher().run_once()
- else:
- RRWatcher().start()
- HpcProber().start()
- HpcFetcher().start()
- WatcherFetcher().start()
-
- print "Running forever..."
- while True:
- time.sleep(60)
-
diff --git a/xos/observers/hpc/hpclib.py b/xos/observers/hpc/hpclib.py
deleted file mode 100644
index 51864a5..0000000
--- a/xos/observers/hpc/hpclib.py
+++ /dev/null
@@ -1,126 +0,0 @@
-import os
-import base64
-import string
-import sys
-import xmlrpclib
-
-if __name__ == '__main__':
- sys.path.append("/opt/xos")
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-
-from xos.config import Config
-from core.models import Service
-from hpc.models import HpcService
-from requestrouter.models import RequestRouterService
-from util.logger import Logger, logging
-
-logger = Logger(level=logging.INFO)
-
-class APIHelper:
- def __init__(self, proxy, auth, method=None):
- self.proxy = proxy
- self.auth = auth
- self.method = method
-
- def __getattr__(self, name):
- if name.startswith("_"):
- return getattr(self, name)
- else:
- return APIHelper(self.proxy, self.auth, name)
-
- def __call__(self, *args):
- method = getattr(self.proxy, self.method)
- return method(self.auth, *args)
-
-class CmiClient:
- def __init__(self, hostname, port=8003, username="apiuser", password="apiuser"):
- self.connect_api(hostname, port, username, password)
-
- def connect_api(self, hostname, port=8003, username="apiuser", password="apiuser"):
- #print "https://%s:%d/COAPI/" % (hostname, port)
- cob = xmlrpclib.ServerProxy("https://%s:%d/COAPI/" % (hostname, port), allow_none=True)
- cob_auth = {}
- cob_auth["Username"] = username
- cob_auth["AuthString"] = password
- cob_auth["AuthMethod"] = "password"
-
- onev = xmlrpclib.ServerProxy("https://%s:%d/ONEV_API/" % (hostname, port), allow_none=True)
- onev_auth = {}
- onev_auth["Username"] = username
- onev_auth["AuthString"] = password
- onev_auth["AuthMethod"] = "password"
-
- self.cob = APIHelper(cob, cob_auth)
- self.onev = APIHelper(onev, onev_auth)
-
-class HpcLibrary:
- def __init__(self):
- self._client = None
-
- def make_account_name(self, x):
- x=x.lower()
- y = ""
- for c in x:
- if (c in (string.lowercase + string.digits)):
- y = y + c
- return y[:20]
-
- def get_hpc_service(self):
- hpc_service_name = getattr(Config(), "observer_hpc_service", None)
- if hpc_service_name:
- hpc_service = HpcService.objects.filter(name = hpc_service_name)
- else:
- hpc_service = HpcService.objects.all()
-
- if not hpc_service:
- if hpc_service_name:
- raise Exception("No HPC Service with name %s" % hpc_service_name)
- else:
- raise Exception("No HPC Services")
- hpc_service = hpc_service[0]
-
- return hpc_service
-
- def get_cmi_hostname(self, hpc_service=None):
- if getattr(Config(),"observer_cmi_hostname",None):
- return getattr(Config(),"observer_cmi_hostname")
-
- if (hpc_service is None):
- hpc_service = self.get_hpc_service()
-
- if hpc_service.cmi_hostname:
- return hpc_service.cmi_hostname
-
- try:
- slices = hpc_service.slices.all()
- except:
- # deal with buggy data model
- slices = hpc_service.service.all()
-
- for slice in slices:
- if slice.name.endswith("cmi"):
- for instance in slice.instances.all():
- if instance.node:
- return instance.node.name
-
- raise Exception("Failed to find a CMI instance")
-
- @property
- def client(self):
- if self._client is None:
- self._client = CmiClient(self.get_cmi_hostname())
- return self._client
-
-if __name__ == '__main__':
- import django
- django.setup()
-
- lib = HpcLibrary()
-
- print "testing API connection to", lib.get_cmi_hostname()
- lib.client.cob.GetNewObjects()
- lib.client.onev.ListAll("CDN")
-
-
-
-
diff --git a/xos/observers/hpc/steps/garbage_collector.py b/xos/observers/hpc/steps/garbage_collector.py
deleted file mode 100644
index 3ccffee..0000000
--- a/xos/observers/hpc/steps/garbage_collector.py
+++ /dev/null
@@ -1,67 +0,0 @@
-import os
-import sys
-import base64
-import traceback
-from collections import defaultdict
-from django.db.models import F, Q
-from xos.config import Config
-from util.logger import Logger, logging
-from observer.syncstep import SyncStep
-from hpc.models import ServiceProvider, ContentProvider, CDNPrefix, OriginServer
-from core.models import *
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-from hpclib import HpcLibrary
-
-logger = Logger(level=logging.INFO)
-
-class GarbageCollector(SyncStep, HpcLibrary):
-# requested_interval = 86400
- requested_interval = 0
- provides=[]
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
- HpcLibrary.__init__(self)
-
- def call(self, **args):
- logger.info("running garbage collector")
- try:
- self.gc_originservers()
- self.gc_cdnprefixes()
- self.gc_contentproviders()
- self.gc_serviceproviders()
- except:
- traceback.print_exc()
-
- def gc_onev(self, ps_class, ps_idField, onev_className, onev_idField):
- # get the CMI's objects
- onev_objs = self.client.onev.ListAll(onev_className)
-
- # get the data model's objects,
- ps_objs = ps_class.objects.filter(enacted__isnull=False)
- ps_ids = [str(getattr(x,ps_idField,None)) for x in ps_objs]
-
- # for each onev object, if it's id does not exist in a data model
- # object, then delete it.
- for onev_obj in onev_objs:
- onev_id = onev_obj[onev_idField]
- if str(onev_id) not in ps_ids:
- logger.info("garbage collecting %s %s" % (onev_className, str(onev_id)))
- self.client.onev.Delete(onev_className, onev_id)
-
- def gc_originservers(self):
- self.gc_onev(OriginServer, "origin_server_id", "OriginServer", "origin_server_id")
-
- def gc_cdnprefixes(self):
- self.gc_onev(CDNPrefix, "cdn_prefix_id", "CDNPrefix", "cdn_prefix_id")
-
- def gc_contentproviders(self):
- self.gc_onev(ContentProvider, "content_provider_id", "ContentProvider", "content_provider_id")
-
- def gc_serviceproviders(self):
- self.gc_onev(ServiceProvider, "service_provider_id", "ServiceProvider", "service_provider_id")
-
diff --git a/xos/observers/hpc/steps/sync_cdnprefix.py b/xos/observers/hpc/steps/sync_cdnprefix.py
deleted file mode 100644
index c22eb51..0000000
--- a/xos/observers/hpc/steps/sync_cdnprefix.py
+++ /dev/null
@@ -1,101 +0,0 @@
-import os
-import sys
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from core.models import Service
-from hpc.models import ServiceProvider, ContentProvider, CDNPrefix
-from util.logger import Logger, logging
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-from hpclib import HpcLibrary
-
-logger = Logger(level=logging.INFO)
-
-class SyncCDNPrefix(SyncStep, HpcLibrary):
- provides=[CDNPrefix]
- observes=CDNPrefix
- requested_interval=0
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
- HpcLibrary.__init__(self)
-
- def filter_hpc_service(self, objs):
- hpcService = self.get_hpc_service()
-
- return [x for x in objs if x.contentProvider.serviceProvider.hpcService == hpcService]
-
- def fetch_pending(self, deleted):
- #self.consistency_check()
-
- return self.filter_hpc_service(SyncStep.fetch_pending(self, deleted))
-
- def consistency_check(self):
- # set to true if something changed
- result=False
-
- # sanity check to make sure our PS objects have CMI objects behind them
- all_p_ids = [x["cdn_prefix_id"] for x in self.client.onev.ListAll("CDNPrefix")]
-
- all_p_ids = []
- all_origins = {}
- for x in self.client.onev.ListAll("CDNPrefix"):
- id = x["cdn_prefix_id"]
- all_p_ids.append(id)
- all_origins[id] = x.get("default_origin_server", None)
-
- for p in CDNPrefix.objects.all():
- if (p.cdn_prefix_id is None):
- continue
-
- if (p.cdn_prefix_id not in all_p_ids):
- logger.info("CDN Prefix %s was not found on CMI" % p.cdn_prefix_id)
- p.cdn_prefix_id=None
- p.save()
- result = True
-
- if (p.defaultOriginServer!=None) and (all_origins.get(p.cdn_prefix_id,None) != p.defaultOriginServer.url):
- logger.info("CDN Prefix %s does not have default origin server on CMI" % str(p))
- p.save() # this will set updated>enacted and force observer to re-sync
- result = True
-
- return result
-
- def sync_record(self, cp):
- logger.info("sync'ing cdn prefix %s" % str(cp))
-
- if (not cp.contentProvider) or (not cp.contentProvider.content_provider_id):
- raise Exception("CDN Prefix %s is linked to a contentProvider without an id" % str(cp))
-
- cpid = cp.contentProvider.content_provider_id
-
- cp_dict = {"service": "HyperCache", "enabled": cp.enabled, "content_provider_id": cpid, "cdn_prefix": cp.prefix}
-
- if cp.defaultOriginServer and cp.defaultOriginServer.url:
- if (not cp.defaultOriginServer.origin_server_id):
- # It's probably a bad idea to try to set defaultOriginServer before
- # we've crated defaultOriginServer.
- raise Exception("cdn prefix %s is waiting for it's default origin server to get an id" % str(cp))
-
- cp_dict["default_origin_server"] = cp.defaultOriginServer.url
-
- #print cp_dict
-
- if not cp.cdn_prefix_id:
- id = self.client.onev.Create("CDNPrefix", cp_dict)
- cp.cdn_prefix_id = id
- else:
- del cp_dict["content_provider_id"] # this can't be updated
- del cp_dict["cdn_prefix"] # this can't be updated either
- self.client.onev.Update("CDNPrefix", cp.cdn_prefix_id, cp_dict)
-
- cp.save()
-
- def delete_record(self, m):
- if m.cdn_prefix_id is not None:
- self.client.onev.Delete("CDNPrefix", m.cdn_prefix_id)
diff --git a/xos/observers/hpc/steps/sync_contentprovider.py b/xos/observers/hpc/steps/sync_contentprovider.py
deleted file mode 100644
index 3732466..0000000
--- a/xos/observers/hpc/steps/sync_contentprovider.py
+++ /dev/null
@@ -1,78 +0,0 @@
-import os
-import sys
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from core.models import Service
-from hpc.models import ServiceProvider, ContentProvider
-from util.logger import Logger, logging
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-from hpclib import HpcLibrary
-
-logger = Logger(level=logging.INFO)
-
-class SyncContentProvider(SyncStep, HpcLibrary):
- provides=[ContentProvider]
- observes=ContentProvider
- requested_interval=0
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
- HpcLibrary.__init__(self)
-
- def filter_hpc_service(self, objs):
- hpcService = self.get_hpc_service()
-
- return [x for x in objs if x.serviceProvider.hpcService == hpcService]
-
- def fetch_pending(self, deleted):
- #self.consistency_check()
-
- return self.filter_hpc_service(SyncStep.fetch_pending(self, deleted))
-
- def consistency_check(self):
- # set to true if something changed
- result=False
-
- # sanity check to make sure our PS objects have CMI objects behind them
- all_cp_ids = [x["content_provider_id"] for x in self.client.onev.ListAll("ContentProvider")]
- for cp in ContentProvider.objects.all():
- if (cp.content_provider_id is not None) and (cp.content_provider_id not in all_cp_ids):
- logger.info("Content provider %s was not found on CMI" % cp.content_provider_id)
- cp.content_provider_id=None
- cp.save()
- result = True
-
- return result
-
- def sync_record(self, cp):
- logger.info("sync'ing content provider %s" % str(cp))
- account_name = self.make_account_name(cp.name)
-
- if (not cp.serviceProvider) or (not cp.serviceProvider.service_provider_id):
- raise Exception("ContentProvider %s is linked to a serviceProvider with no id" % str(cp))
-
- spid = cp.serviceProvider.service_provider_id
-
- cp_dict = {"account": account_name, "name": cp.name, "enabled": cp.enabled}
-
- #print cp_dict
-
- if not cp.content_provider_id:
- cp_dict["service_provider_id"] = spid
- id = self.client.onev.Create("ContentProvider", cp_dict)
- cp.content_provider_id = id
- else:
- self.client.onev.Update("ContentProvider", cp.content_provider_id, cp_dict)
-
- cp.save()
-
- def delete_record(self, m):
- if m.content_provider_id is not None:
- self.client.onev.Delete("ContentProvider", m.content_provider_id)
-
diff --git a/xos/observers/hpc/steps/sync_hpcservices.py b/xos/observers/hpc/steps/sync_hpcservices.py
deleted file mode 100644
index ffb8b3a..0000000
--- a/xos/observers/hpc/steps/sync_hpcservices.py
+++ /dev/null
@@ -1,43 +0,0 @@
-import os
-import sys
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from core.models import Service
-from hpc.models import HpcService
-from requestrouter.models import RequestRouterService
-from util.logger import Logger, logging
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-from hpclib import HpcLibrary
-
-logger = Logger(level=logging.INFO)
-
-class SyncHpcService(SyncStep, HpcLibrary):
- provides=[HpcService]
- observes=HpcService
- requested_interval=0
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
- HpcLibrary.__init__(self)
-
- def filter_hpc_service(self, objs):
- hpcService = self.get_hpc_service()
-
- return [x for x in objs if x == hpcService]
-
- def fetch_pending(self, deleted):
- # Looks like deletion is not supported for this object - Sapan
- if (deleted):
- return []
- else:
- return self.filter_hpc_service(HpcService.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)))
-
- def sync_record(self, hpc_service):
- logger.info("sync'ing hpc_service %s" % str(hpc_service))
- hpc_service.save()
diff --git a/xos/observers/hpc/steps/sync_originserver.py b/xos/observers/hpc/steps/sync_originserver.py
deleted file mode 100644
index 851590a..0000000
--- a/xos/observers/hpc/steps/sync_originserver.py
+++ /dev/null
@@ -1,92 +0,0 @@
-import os
-import sys
-import base64
-
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from core.models import Service
-from hpc.models import ServiceProvider, ContentProvider, CDNPrefix, OriginServer
-from util.logger import Logger, logging
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-from hpclib import HpcLibrary
-
-logger = Logger(level=logging.INFO)
-
-class SyncOriginServer(SyncStep, HpcLibrary):
- provides=[OriginServer]
- observes=OriginServer
- requested_interval=0
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
- HpcLibrary.__init__(self)
-
- def filter_hpc_service(self, objs):
- hpcService = self.get_hpc_service()
-
- return [x for x in objs if x.contentProvider.serviceProvider.hpcService == hpcService]
-
- def fetch_pending(self, deleted):
- #self.consistency_check()
-
- return self.filter_hpc_service(SyncStep.fetch_pending(self, deleted))
-
- def consistency_check(self):
- # set to true if something changed
- result=False
-
- # sanity check to make sure our PS objects have CMI objects behind them
- all_ors_ids = [x["origin_server_id"] for x in self.client.onev.ListAll("OriginServer")]
- for ors in OriginServer.objects.all():
- if (ors.origin_server_id is not None) and (ors.origin_server_id not in all_ors_ids):
- # we have an origin server ID, but it doesn't exist in the CMI
- # something went wrong
- # start over
- logger.info("origin server %s was not found on CMI" % ors.origin_server_id)
- ors.origin_server_id=None
- ors.save()
- result = True
-
- return result
-
- def sync_record(self, ors):
- logger.info("sync'ing origin server %s" % str(ors))
-
- if (not ors.contentProvider) or (not ors.contentProvider.content_provider_id):
- raise Exception("Origin Server %s is linked to a contentProvider with no id" % str(ors))
-
- cpid = ors.contentProvider.content_provider_id
-
- # validation requires URL start with http://
- url = ors.url
- if not url.startswith("http://"):
- url = "http://" + url
-
- ors_dict = {"authenticated_content": ors.authenticated, "zone_redirects": ors.redirects, "content_provider_id": cpid, "url": url, "service_type": "HyperCache", "caching_type": "Optimistic", "description": ors.description}
- if not ors_dict["description"]:
- ors_dict["description"] = "blank"
-
- #print os_dict
-
- if not ors.origin_server_id:
- id = self.client.onev.Create("OriginServer", ors_dict)
- ors.origin_server_id = id
- else:
- self.client.onev.Update("OriginServer", ors.origin_server_id, ors_dict)
-
- # ... something breaks (analytics) if the URL starts with http://, so we
- # change it in cob after we added it via onev.
- url = url[7:]
- self.client.cob.UpdateContent(ors.origin_server_id, {"url": url})
-
- ors.silent = True
- ors.save()
-
- def delete_record(self, m):
- if m.origin_server_id is not None:
- self.client.onev.Delete("OriginServer", m.origin_server_id)
diff --git a/xos/observers/hpc/steps/sync_serviceprovider.py b/xos/observers/hpc/steps/sync_serviceprovider.py
deleted file mode 100644
index ff7e2f6..0000000
--- a/xos/observers/hpc/steps/sync_serviceprovider.py
+++ /dev/null
@@ -1,67 +0,0 @@
-import os
-import sys
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from core.models import Service
-from hpc.models import ServiceProvider
-from util.logger import Logger, logging
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-from hpclib import HpcLibrary
-
-logger = Logger(level=logging.INFO)
-
-class SyncServiceProvider(SyncStep, HpcLibrary):
- provides=[ServiceProvider]
- observes=ServiceProvider
- requested_interval=0
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
- HpcLibrary.__init__(self)
-
- def filter_hpc_service(self, objs):
- hpcService = self.get_hpc_service()
-
- return [x for x in objs if x.hpcService == hpcService]
-
- def fetch_pending(self, deleted):
- #self.consistency_check()
-
- return self.filter_hpc_service(SyncStep.fetch_pending(self, deleted))
-
- def consistency_check(self):
- # set to true if something changed
- result=False
-
- # sanity check to make sure our PS objects have CMI objects behind them
- all_sp_ids = [x["service_provider_id"] for x in self.client.onev.ListAll("ServiceProvider")]
- for sp in ServiceProvider.objects.all():
- if (sp.service_provider_id is not None) and (sp.service_provider_id not in all_sp_ids):
- logger.info("Service provider %s was not found on CMI" % sp.service_provider_id)
- sp.service_provider_id=None
- sp.save()
- result = True
-
- return result
-
- def sync_record(self, sp):
- logger.info("sync'ing service provider %s" % str(sp))
- account_name = self.make_account_name(sp.name)
- sp_dict = {"account": account_name, "name": sp.name, "enabled": sp.enabled}
- if not sp.service_provider_id:
- id = self.client.onev.Create("ServiceProvider", sp_dict)
- sp.service_provider_id = id
- else:
- self.client.onev.Update("ServiceProvider", sp.service_provider_id, sp_dict)
-
- sp.save()
-
- def delete_record(self, m):
- if m.service_provider_id is not None:
- self.client.onev.Delete("ServiceProvider", m.service_provider_id)
diff --git a/xos/observers/hpc/steps/sync_sitemap.py b/xos/observers/hpc/steps/sync_sitemap.py
deleted file mode 100644
index e406fc3..0000000
--- a/xos/observers/hpc/steps/sync_sitemap.py
+++ /dev/null
@@ -1,118 +0,0 @@
-import os
-import sys
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from core.models import Service
-from hpc.models import ServiceProvider, ContentProvider, CDNPrefix, SiteMap
-from util.logger import Logger, logging
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-from hpclib import HpcLibrary
-
-logger = Logger(level=logging.INFO)
-
-class SyncSiteMap(SyncStep, HpcLibrary):
- provides=[SiteMap]
- observes=SiteMap
- requested_interval=0
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
- HpcLibrary.__init__(self)
-
- def filter_hpc_service(self, objs):
- hpcService = self.get_hpc_service()
-
- filtered_objs = []
- for x in objs:
- if ((x.hpcService == hpcService) or
- ((x.serviceProvider != None) and (x.serviceProvider.hpcService == hpcService)) or
- ((x.contentProvider != None) and (x.contentProvider.serviceProvider.hpcService == hpcService)) or
- ((x.cdnPrefix!= None) and (x.cdnPrefix.contentProvider.serviceProvider.hpcService == hpcService))):
- filtered_objs.append(x)
-
- return filtered_objs
-
- def fetch_pending(self, deleted):
- return self.filter_hpc_service(SyncStep.fetch_pending(self, deleted))
-
- def consistency_check(self):
- # set to true if something changed
- result=False
-
- # sanity check to make sure our PS objects have CMI objects behind them
- all_map_ids = [x["map_id"] for x in self.client.onev.ListAll("Map")]
- for map in SiteMap.objects.all():
- if (map.map_id is not None) and (map.map_id not in all_map_ids):
- logger.info("Map %s was not found on CMI" % map.map_id)
- map.map_id=None
- map.save()
- result = True
-
- return result
-
- def update_bind(self, map, map_dict, field_name, to_name, ids):
- for id in ids:
- if (not id in map_dict.get(field_name, [])):
- print "Bind Map", map.map_id, "to", to_name, id
- self.client.onev.Bind("Map", map.map_id, to_name, id)
-
- for id in map_dict.get(field_name, []):
- if (not id in ids):
- print "Unbind Map", map.map_id, "from", to_name, id
- self.client.onev.UnBind("map", map.map_id, to_name, id)
-
- def sync_record(self, map):
- logger.info("sync'ing SiteMap %s" % str(map))
-
- if not map.map:
- # no contents
- return
-
- content = map.map.read()
-
- map_dict = {"name": map.name, "type": "site", "content": content}
-
- cdn_prefix_ids=[]
- service_provider_ids=[]
- content_provider_ids=[]
-
- if (map.contentProvider):
- if not map.contentProvider.content_provider_id:
- raise Exception("Map %s links to a contentProvider with no id" % map.name)
- conent_provider_ids = [map.contentProvider.content_provider_id]
-
- if (map.serviceProvider):
- if not map.serviceProvider.service_provider_id:
- raise Exception("Map %s links to a serviceProvider with no id" % map.name)
- service_provider_ids = [map.serviceProvider.service_provider_id]
-
- if (map.cdnPrefix):
- if not map.cdnPrefix.cdn_prefix_id:
- raise Exception("Map %s links to a cdnPrefix with no id" % map.name)
- cdn_prefix_ids = [map.cdnPrefix.cdn_prefix_id]
-
- if not map.map_id:
- print "Create Map", map_dict
- id = self.client.onev.Create("Map", map_dict)
- map.map_id = id
- else:
- print "Update Map", map_dict
- # these things we probably cannot update
- del map_dict["name"]
- self.client.onev.Update("Map", map.map_id, map_dict)
-
- cmi_map_dict = self.client.onev.Read("Map", map.map_id)
-
- self.update_bind(map, cmi_map_dict, "cdn_prefix_ids", "CDNPrefix", cdn_prefix_ids)
-
- map.save()
-
- def delete_record(self, m):
- if m.map_id is not None:
- self.client.onev.Delete("Map", m.map_id)
diff --git a/xos/observers/monitoring_channel/monitoring_channel_observer.py b/xos/observers/monitoring_channel/monitoring_channel_observer.py
deleted file mode 100755
index d6a71ff..0000000
--- a/xos/observers/monitoring_channel/monitoring_channel_observer.py
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/usr/bin/env python
-
-# This imports and runs ../../xos-observer.py
-
-import importlib
-import os
-import sys
-observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../..")
-sys.path.append(observer_path)
-mod = importlib.import_module("xos-observer")
-mod.main()
diff --git a/xos/observers/monitoring_channel/monitoring_channel_observer_config b/xos/observers/monitoring_channel/monitoring_channel_observer_config
deleted file mode 100644
index 922a019..0000000
--- a/xos/observers/monitoring_channel/monitoring_channel_observer_config
+++ /dev/null
@@ -1,40 +0,0 @@
-
-[plc]
-name=plc
-deployment=VICCI
-
-[db]
-name=xos
-user=postgres
-password=password
-host=localhost
-port=5432
-
-[api]
-host=128.112.171.237
-port=8000
-ssl_key=None
-ssl_cert=None
-ca_ssl_cert=None
-ratelimit_enabled=0
-omf_enabled=0
-mail_support_address=support@localhost
-nova_enabled=True
-
-[observer]
-name=monitoring_channel
-dependency_graph=/opt/xos/observers/monitoring_channel/model-deps
-steps_dir=/opt/xos/observers/monitoring_channel/steps
-sys_dir=/opt/xos/observers/monitoring_channel/sys
-deleters_dir=/opt/xos/observers/monitoring_channel/deleters
-log_file=console
-driver=None
-pretend=False
-backoff_disabled=True
-save_ansible_output=True
-proxy_ssh=True
-full_setup=True
-
-[feefie]
-client_id='vicci_dev_central'
-user_id='pl'
diff --git a/xos/observers/monitoring_channel/steps/sync_monitoringchannel.py b/xos/observers/monitoring_channel/steps/sync_monitoringchannel.py
deleted file mode 100644
index 919b4ea..0000000
--- a/xos/observers/monitoring_channel/steps/sync_monitoringchannel.py
+++ /dev/null
@@ -1,74 +0,0 @@
-import hashlib
-import os
-import socket
-import sys
-import base64
-import time
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from observer.ansible import run_template_ssh
-from observers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
-from core.models import Service, Slice
-from ceilometer.models import MonitoringChannel
-from util.logger import Logger, logging
-
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-logger = Logger(level=logging.INFO)
-
-class SyncMonitoringChannel(SyncInstanceUsingAnsible):
- provides=[MonitoringChannel]
- observes=MonitoringChannel
- requested_interval=0
- template_name = "sync_monitoringchannel.yaml"
- service_key_name = "/opt/xos/observers/monitoring_channel/monitoring_channel_private_key"
-
- def __init__(self, *args, **kwargs):
- super(SyncMonitoringChannel, self).__init__(*args, **kwargs)
-
- def fetch_pending(self, deleted):
- if (not deleted):
- objs = MonitoringChannel.get_tenant_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
- else:
- objs = MonitoringChannel.get_deleted_tenant_objects()
-
- return objs
-
- def get_extra_attributes(self, o):
- # This is a place to include extra attributes. In the case of Monitoring Channel, we need to know
- # 1) Allowed tenant ids
- # 2) Ceilometer API service endpoint URL if running externally
- # 3) Credentials to access Ceilometer API service
-
- instance = self.get_instance(o)
-
- try:
- full_setup = Config().observer_full_setup
- except:
- full_setup = True
-
- fields = {"unique_id": o.id,
- "allowed_tenant_ids": o.tenant_list,
- "auth_url":instance.controller.auth_url,
- "admin_user":instance.controller.admin_user,
- "admin_password":instance.controller.admin_password,
- "admin_tenant":instance.controller.admin_tenant,
- "full_setup": full_setup}
-
- return fields
-
- def run_playbook(self, o, fields):
- #ansible_hash = hashlib.md5(repr(sorted(fields.items()))).hexdigest()
- #quick_update = (o.last_ansible_hash == ansible_hash)
-
- #if quick_update:
- # logger.info("quick_update triggered; skipping ansible recipe")
- #else:
- super(SyncMonitoringChannel, self).run_playbook(o, fields)
-
- #o.last_ansible_hash = ansible_hash
-
- def delete_record(self, m):
- pass
diff --git a/xos/observers/monitoring_channel/steps/sync_monitoringchannel.yaml b/xos/observers/monitoring_channel/steps/sync_monitoringchannel.yaml
deleted file mode 100644
index fb4b73d..0000000
--- a/xos/observers/monitoring_channel/steps/sync_monitoringchannel.yaml
+++ /dev/null
@@ -1,90 +0,0 @@
----
-- hosts: {{ instance_name }}
- gather_facts: False
- connection: ssh
- user: ubuntu
- sudo: yes
- vars:
- unique_id: {{ unique_id }}
- auth_url: {{ auth_url }}
- admin_user: {{ admin_user }}
- admin_password: {{ admin_password }}
- admin_tenant: {{ admin_tenant }}
- shared_lan_ip: {{ private_ip }}
- shared_lan_mac: {{ private_mac }}
- headnode_flat_lan_ip: {{ rabbit_host }}
- ceilometer_client_acess_ip: {{ ceilometer_ip }}
- ceilometer_client_acess_mac: {{ ceilometer_mac }}
- ceilometer_host_port: {{ ceilometer_port }}
- allowed_tenant_ids:
- {% for allowed_tenant_id in allowed_tenant_ids %}
- - {{ allowed_tenant_id }}
- {% endfor %}
-
- tasks:
-{% if full_setup %}
- - name: Docker repository
- copy: src=/opt/xos/observers/monitoring_channel/files/docker.list
- dest=/etc/apt/sources.list.d/docker.list
-
- - name: Import the repository key
- apt_key: keyserver=keyserver.ubuntu.com id=36A1D7869245C8950F966E92D8576A8BA88D21E9
-
- - name: install Docker
- apt: name=lxc-docker-1.5.0 state=present update_cache=yes
-
- - name: install python-setuptools
- apt: name=python-setuptools state=present
-
- - name: install pip
- easy_install: name=pip
-
- - name: install docker-py
- pip: name=docker-py version=0.5.3
-
- - name: install Pipework
- get_url: url=https://raw.githubusercontent.com/jpetazzo/pipework/master/pipework
- dest=/usr/local/bin/pipework
- mode=0755
-
- - name: Disable resolvconf service
- shell: service resolvconf stop
- shell: echo manual > /etc/init/resolvconf.override
- shell: rm -f /etc/resolv.conf
-
- - name: Install resolv.conf
- copy: src=/opt/xos/observers/monitoring_channel/files/vm-resolv.conf
- dest=/etc/resolv.conf
-{% endif %}
-
- - name: ceilometer proxy config
- template: src=/opt/xos/observers/monitoring_channel/templates/ceilometer_proxy_config.j2 dest=/usr/local/share/monitoring-channel-{{ unique_id }}_ceilometer_proxy_config mode=0777
-
- - name: Monitoring channel upstart
- template: src=/opt/xos/observers/monitoring_channel/templates/monitoring-channel.conf.j2 dest=/etc/init/monitoring-channel-{{ unique_id }}.conf
-
- - name: Monitoring channel startup script
- template: src=/opt/xos/observers/monitoring_channel/templates/start-monitoring-channel.sh.j2 dest=/usr/local/sbin/start-monitoring-channel-{{ unique_id }}.sh mode=0755
- notify:
-# - restart monitoring-channel
- - stop monitoring-channel
- - remove container
- - start monitoring-channel
-
-# These are samples, not necessary for correct function of demo
-
- - name: Make sure Monitoring channel service is running
- service: name=monitoring-channel-{{ unique_id }} state=started
-
- handlers:
- - name: restart monitoring-channel
- shell: service monitoring-channel-{{ unique_id }} stop; sleep 1; service vcpe-{{ unique_id }} start
-
- - name: stop monitoring-channel
- service: name=monitoring-channel-{{ unique_id }} state=stopped
-
- - name: remove container
- docker: name=monitoring-channel-{{ unique_id }} state=absent image=docker-vcpe
-
- - name: start monitoring-channel
- service: name=monitoring-channel-{{ unique_id }} state=started
diff --git a/xos/observers/monitoring_channel/templates/ceilometer_pub_sub_consumer.py b/xos/observers/monitoring_channel/templates/ceilometer_pub_sub_consumer.py
deleted file mode 100644
index 7d111e3..0000000
--- a/xos/observers/monitoring_channel/templates/ceilometer_pub_sub_consumer.py
+++ /dev/null
@@ -1,248 +0,0 @@
-import socket
-import requests
-import urllib2
-import json
-import msgpack
-import collections
-import time, thread, threading
-
-projects_map = {}
-xos_tenant_info_map = {}
-xos_instances_info_map = {}
-
-UDP_IP = "0.0.0.0"
-UDP_PORT = 12346
-
-def acquire_xos_monitoring_channel():
- url = "http://ctl:9999/xoslib/monitoringchannel/"
- admin_auth=("padmin@vicci.org", "letmein") # use your XOS username and password
- monitoring_channels = requests.get(url, auth=admin_auth).json()
- ceilometer_url = None
- if not monitoring_channels:
- print 'SRIKANTH: No monitoring channels for this user...'
- return None
- else:
- monitoring_channel = monitoring_channels[0]
- while not monitoring_channel['ceilometer_url']:
- print 'SRIKANTH: Waiting for monitoring channel create'
- sleep(0.5)
- monitoring_channel = requests.get(url, auth=admin_auth).json()[0]
- #TODO: Wait until URL is completely UP
- while True:
- print 'SRIKANTH: Waiting for ceilometer proxy URL %s is available' % monitoring_channel['ceilometer_url']
- try:
- response = urllib2.urlopen(monitoring_channel['ceilometer_url'],timeout=1)
- break
- except urllib2.HTTPError, e:
- print 'SRIKANTH: HTTP error %s' % e.reason
- break
- except urllib2.URLError, e:
- print 'SRIKANTH: URL error %(reason)s' % e.reason
- pass
- return monitoring_channel
-
-def print_samples():
- print ""
- print ""
- for project in projects_map.keys():
- print "service=%s slice=%s, alarm_state=%s" % (projects_map[project]['xos_tenant_info']['service'] if projects_map[project]['xos_tenant_info'] else None, projects_map[project]['xos_tenant_info']['slice'] if projects_map[project]['xos_tenant_info'] else project, projects_map[project]['alarm'])
- for resource in projects_map[project]['resources'].keys():
- print "resource=%s" % (projects_map[project]['resources'][resource]['xos_instance_info']['instance_name'] if projects_map[project]['resources'][resource]['xos_instance_info'] else resource)
- for i in projects_map[project]['resources'][resource]['queue']:
- print " time=%s val=%s" % ( i['timestamp'],i['counter_volume'])
-
-def periodic_print():
- print_samples()
- #Print every 1minute
- threading.Timer(60, periodic_print).start()
-
-
-CPU_UPPER_THRESHOLD = 80 #80%
-CPU_LOWER_THRESHOLD = 30 #30%
-CPU_THRESHOLD_REPEAT = 3
-INITIAL_STATE = 'normal_config'
-SCALE_UP_EVALUATION = 'scale_up_eval'
-SCALE_DOWN_EVALUATION = 'scale_down_eval'
-SCALE_UP_ALARM = 'scale_up'
-SCALE_DOWN_ALARM = 'scale_down'
-
-def loadAllXosTenantInfo():
- print "SRIKANTH: Loading all XOS tenant info"
- url = "http://ctl:9999/xos/controllerslices/"
- admin_auth=("padmin@vicci.org", "letmein") # use your XOS username and password
- controller_slices = requests.get(url, auth=admin_auth).json()
- for cslice in controller_slices:
- slice = requests.get(cslice['slice'], auth=admin_auth).json()
- slice_name = slice['humanReadableName']
- if slice['service']:
- service = requests.get(slice['service'], auth=admin_auth).json()
- service_name = service['humanReadableName']
- else:
- service_name = None
- xos_tenant_info_map[cslice['tenant_id']] = {'service':service_name, 'slice':slice_name}
- print "SRIKANTH: Project: %s Service:%s Slice:%s" % (cslice['tenant_id'],service_name,slice_name)
-
-def loadAllXosInstanceInfo():
- print "SRIKANTH: Loading all XOS instance info"
- url = "http://130.127.133.87:9999/xos/instances/"
- admin_auth=("padmin@vicci.org", "letmein") # use your XOS username and password
- xos_instances = requests.get(url, auth=admin_auth).json()
- for instance in xos_instances:
- xos_instances_info_map[instance['instance_uuid']] = {'instance_name':instance['instance_name']}
-
-def getXosTenantInfo(project):
- xos_tenant_info = xos_tenant_info_map.get(project, None)
- if xos_tenant_info:
- return xos_tenant_info
- else:
- loadAllXosTenantInfo()
- xos_tenant_info = xos_tenant_info_map.get(project, None)
- if not xos_tenant_info:
- print "SRIKANTH: Project %s has no associated XOS slice" % project
- return xos_tenant_info
-
-def getXosInstanceInfo(resource):
- xos_instance_info = xos_instances_info_map.get(resource, None)
- if xos_instance_info:
- return xos_instance_info
- else:
- loadAllXosInstanceInfo()
- xos_instance_info = xos_instances_info_map.get(resource, None)
- if not xos_instance_info:
- print "SRIKANTH: Resource %s has no associated XOS instance" % project
- return xos_instance_info
-
-def handle_adjust_scale(project, adjust):
- if (adjust != 'up') and (adjust != 'down'):
- print "SRIKANTH: Invalid adjust value %s " % adjust
- return
- current_instances = len(projects_map[project]['resources'].keys())
- if (current_instances <=1 and adjust == 'down'):
- print "SRIKANTH: %s is running with already minimum instances and can not scale down further " % project
- return
- if (current_instances >=2 and adjust == 'up'):
- print "SRIKANTH: %s is running with already maximum instances and can not scale up further " % project
- return
- #xos_tenant = getXosTenantInfo(project)
- xos_tenant = projects_map[project]['xos_tenant_info']
- if not xos_tenant:
- print "SRIKANTH: Can not handle adjust_scale for Project %s because not associated with any slice" % project
- return
- xos_service = xos_tenant['service']
- xos_slice = xos_tenant['slice']
- if not xos_service or not xos_slice:
- print "SRIKANTH: Can not handle adjust_scale for Project %s because not associated with any service or slice" % project
- return
- print "SRIKANTH: SCALE %s for Project %s, Slice=%s, Service=%s from current=%d to new=%d" % (adjust, project, xos_slice, xos_service, current_instances, current_instances+1 if (adjust=='up') else current_instances-1)
- query_params = {'service':xos_service, 'slice_hint':xos_slice, 'scale':current_instances+1 if (adjust=='up') else current_instances-1}
- url = "http://ctl:9999/xoslib/serviceadjustscale/"
- admin_auth=("padmin@vicci.org", "letmein") # use your XOS username and password
- response = requests.get(url, params=query_params, auth=admin_auth).json()
- print "SRIKANTH: XOS adjust_scale response: %s" % response
-
-def periodic_cpu_threshold_evaluator():
- for project in projects_map.keys():
- aggregate_cpu_util = sum([resource['queue'][-1]['counter_volume'] \
- for resource in projects_map[project]['resources'].values()]) \
- /len(projects_map[project]['resources'].keys())
-
- if (projects_map[project]['alarm'] == INITIAL_STATE or
- projects_map[project]['alarm'] == SCALE_UP_ALARM or
- projects_map[project]['alarm'] == SCALE_DOWN_ALARM):
- if aggregate_cpu_util > CPU_UPPER_THRESHOLD:
- projects_map[project]['uthreadshold_count'] = 1
- projects_map[project]['alarm'] = SCALE_UP_EVALUATION
- if projects_map[project]['uthreadshold_count'] >= CPU_THRESHOLD_REPEAT:
- projects_map[project]['alarm'] = SCALE_UP_ALARM
- handle_adjust_scale(project, 'up')
- elif aggregate_cpu_util < CPU_LOWER_THRESHOLD:
- projects_map[project]['lthreadshold_count'] = 1
- projects_map[project]['alarm'] = SCALE_DOWN_EVALUATION
- if projects_map[project]['lthreadshold_count'] >= CPU_THRESHOLD_REPEAT:
- projects_map[project]['alarm'] = SCALE_DOWN_ALARM
- handle_adjust_scale(project, 'down')
- else:
- projects_map[project]['uthreadshold_count'] = 0
- projects_map[project]['lthreadshold_count'] = 0
- projects_map[project]['alarm'] = INITIAL_STATE
- elif projects_map[project]['alarm'] == SCALE_UP_EVALUATION:
- if aggregate_cpu_util > CPU_UPPER_THRESHOLD:
- projects_map[project]['uthreadshold_count'] += 1
- if projects_map[project]['uthreadshold_count'] >= CPU_THRESHOLD_REPEAT:
- projects_map[project]['alarm'] = SCALE_UP_ALARM
- handle_adjust_scale(project, 'up')
- elif aggregate_cpu_util < CPU_LOWER_THRESHOLD:
- projects_map[project]['lthreadshold_count'] += 1
- projects_map[project]['alarm'] = SCALE_DOWN_EVALUATION
- else:
- projects_map[project]['uthreadshold_count'] = 0
- projects_map[project]['alarm'] = INITIAL_STATE
- elif projects_map[project]['alarm'] == SCALE_DOWN_EVALUATION:
- if aggregate_cpu_util < CPU_LOWER_THRESHOLD:
- projects_map[project]['lthreadshold_count'] += 1
- if projects_map[project]['lthreadshold_count'] >= CPU_THRESHOLD_REPEAT:
- projects_map[project]['alarm'] = SCALE_DOWN_ALARM
- handle_adjust_scale(project, 'down')
- elif aggregate_cpu_util > CPU_UPPER_THRESHOLD:
- projects_map[project]['uthreadshold_count'] += 1
- projects_map[project]['alarm'] = SCALE_UP_EVALUATION
- else:
- projects_map[project]['lthreadshold_count'] = 0
- projects_map[project]['alarm'] = INITIAL_STATE
- threading.Timer(60, periodic_cpu_threshold_evaluator).start()
-
-def read_notification_from_ceilometer(host,port):
- udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
- udp.bind((host, port))
-
- while True:
- data, source = udp.recvfrom(64000)
- try:
- sample = msgpack.loads(data, encoding='utf-8')
- if sample['counter_name'] != 'cpu_util':
- continue
- if sample['project_id'] not in projects_map.keys():
- projects_map[sample['project_id']] = {}
- projects_map[sample['project_id']]['xos_tenant_info'] = getXosTenantInfo(sample['project_id'])
- projects_map[sample['project_id']]['resources'] = {}
- projects_map[sample['project_id']]['uthreadshold_count'] = 0
- projects_map[sample['project_id']]['lthreadshold_count'] = 0
- projects_map[sample['project_id']]['alarm'] = INITIAL_STATE
- resource_map = projects_map[sample['project_id']]['resources']
- if sample['resource_id'] not in resource_map.keys():
- resource_map[sample['resource_id']] = {}
- resource_map[sample['resource_id']]['xos_instance_info'] = getXosInstanceInfo(sample['resource_id'])
- resource_map[sample['resource_id']]['queue'] = collections.deque(maxlen=10)
- samples_map = resource_map[sample['resource_id']]['queue']
- sample = {'counter_name':sample['counter_name'],
- 'project_id':sample['project_id'],
- 'resource_id':sample['resource_id'],
- 'timestamp':sample['timestamp'],
- 'counter_unit':sample['counter_unit'],
- 'counter_volume':sample['counter_volume']}
- samples_map.append(sample)
- except Exception as e:
- print e
-
-def main():
- monitoring_channel = acquire_xos_monitoring_channel()
- if not monitoring_channel:
- print 'SRIKANTH: XOS monitoring_channel is not created... Create it before using this app'
- return
- loadAllXosTenantInfo()
- loadAllXosInstanceInfo()
- thread.start_new(read_notification_from_ceilometer,(UDP_IP,UDP_PORT,))
- ceilometer_url = monitoring_channel['ceilometer_url']
- subscribe_data = {"sub_info":"cpu_util","app_id":"xos_auto_scale","target":"udp://10.11.10.1:12346"}
- subscribe_url = ceilometer_url + 'v2/subscribe'
- response = requests.post(subscribe_url, data=json.dumps(subscribe_data))
- print 'SRIKANTH: Ceilometer Subscription status:%s' % response.text
- #TODO: Fix the typo in 'sucess'
- if (not 'sucess' in response.text) and (not 'already exists' in response.text):
- print 'SRIKANTH: Ceilometer Subscription unsuccessful...Exiting'
- return
- periodic_cpu_threshold_evaluator()
- periodic_print()
-
-if __name__ == "__main__":
- main()
diff --git a/xos/observers/onos/onos-observer.py b/xos/observers/onos/onos-observer.py
deleted file mode 100755
index d6a71ff..0000000
--- a/xos/observers/onos/onos-observer.py
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/usr/bin/env python
-
-# This imports and runs ../../xos-observer.py
-
-import importlib
-import os
-import sys
-observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../..")
-sys.path.append(observer_path)
-mod = importlib.import_module("xos-observer")
-mod.main()
diff --git a/xos/observers/onos/onos_observer_config b/xos/observers/onos/onos_observer_config
deleted file mode 100644
index 3c6d63d..0000000
--- a/xos/observers/onos/onos_observer_config
+++ /dev/null
@@ -1,41 +0,0 @@
-
-[plc]
-name=plc
-deployment=VICCI
-
-[db]
-name=xos
-user=postgres
-password=password
-host=localhost
-port=5432
-
-[api]
-host=128.112.171.237
-port=8000
-ssl_key=None
-ssl_cert=None
-ca_ssl_cert=None
-ratelimit_enabled=0
-omf_enabled=0
-mail_support_address=support@localhost
-nova_enabled=True
-
-[observer]
-name=onos
-dependency_graph=/opt/xos/observers/onos/model-deps
-steps_dir=/opt/xos/observers/onos/steps
-sys_dir=/opt/xos/observers/onos/sys
-deleters_dir=/opt/xos/observers/onos/deleters
-log_file=console
-driver=None
-pretend=False
-backoff_disabled=True
-save_ansible_output=True
-# set proxy_ssh to false on cloudlab
-proxy_ssh=False
-full_setup=True
-
-[feefie]
-client_id='vicci_dev_central'
-user_id='pl'
diff --git a/xos/observers/onos/scripts/dockerip.sh b/xos/observers/onos/scripts/dockerip.sh
deleted file mode 100644
index 4bf355d..0000000
--- a/xos/observers/onos/scripts/dockerip.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-
-docker inspect --format '{{ .NetworkSettings.IPAddress }}' $1 | tr -d '\n' | tr -d '\r'
-
diff --git a/xos/observers/onos/steps/sync_onosapp.py b/xos/observers/onos/steps/sync_onosapp.py
deleted file mode 100644
index 0feb2e5..0000000
--- a/xos/observers/onos/steps/sync_onosapp.py
+++ /dev/null
@@ -1,136 +0,0 @@
-import hashlib
-import os
-import socket
-import sys
-import base64
-import time
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from observer.ansible import run_template_ssh
-from observers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
-from core.models import Service, Slice
-from services.onos.models import ONOSService, ONOSApp
-from util.logger import Logger, logging
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-logger = Logger(level=logging.INFO)
-
-class SyncONOSApp(SyncInstanceUsingAnsible):
- provides=[ONOSApp]
- observes=ONOSApp
- requested_interval=0
- template_name = "sync_onosapp.yaml"
- service_key_name = "/opt/xos/observers/onos/onos_key"
-
- def __init__(self, *args, **kwargs):
- super(SyncONOSApp, self).__init__(*args, **kwargs)
-
- def fetch_pending(self, deleted):
- if (not deleted):
- objs = ONOSApp.get_tenant_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
- else:
- objs = ONOSApp.get_deleted_tenant_objects()
-
- return objs
-
- def get_instance(self, o):
- # We assume the ONOS service owns a slice, so pick one of the instances
- # inside that slice to sync to.
-
- serv = self.get_onos_service(o)
-
- if serv.use_external_host:
- return serv.use_external_host
-
- if serv.slices.exists():
- slice = serv.slices.all()[0]
- if slice.instances.exists():
- return slice.instances.all()[0]
-
- return None
-
- def get_onos_service(self, o):
- if not o.provider_service:
- return None
-
- onoses = ONOSService.get_service_objects().filter(id=o.provider_service.id)
- if not onoses:
- return None
-
- return onoses[0]
-
- def get_files_dir(self, o):
- if not hasattr(Config(), "observer_steps_dir"):
- # make steps_dir mandatory; there's no valid reason for it to not
- # be defined.
- raise Exception("observer_steps_dir is not defined in config file")
-
- step_dir = Config().observer_steps_dir
-
- return os.path.join(step_dir, "..", "files", str(self.get_onos_service(o).id), o.name)
-
- def write_configs(self, o):
- o.config_fns = []
- o.rest_configs = []
- o.files_dir = self.get_files_dir(o)
-
- if not os.path.exists(o.files_dir):
- os.makedirs(o.files_dir)
-
- # Combine the service attributes with the tenant attributes. Tenant
- # attribute can override service attributes.
- attrs = o.provider_service.serviceattribute_dict
- attrs.update(o.tenantattribute_dict)
-
- for (name, value) in attrs.items():
- if name.startswith("config_"):
- fn = name[7:] # .replace("_json",".json")
- o.config_fns.append(fn)
- file(os.path.join(o.files_dir, fn),"w").write(value)
- if name.startswith("rest_"):
- fn = name[5:].replace("/","_")
- endpoint = name[5:]
- # Ansible goes out of it's way to make our life difficult. If
- # 'lookup' sees a file that it thinks contains json, then it'll
- # insist on parsing and return a json object. We just want
- # a string, so prepend a space and then strip the space off
- # later.
- file(os.path.join(o.files_dir, fn),"w").write(" " +value)
- o.rest_configs.append( {"endpoint": endpoint, "fn": fn} )
-
- def prepare_record(self, o):
- self.write_configs(o)
-
- def get_extra_attributes(self, o):
- instance = self.get_instance(o)
-
- fields={}
- fields["files_dir"] = o.files_dir
- fields["appname"] = o.name
- fields["nat_ip"] = instance.get_ssh_ip()
- fields["config_fns"] = o.config_fns
- fields["rest_configs"] = o.rest_configs
- if o.dependencies:
- fields["dependencies"] = [x.strip() for x in o.dependencies.split(",")]
- else:
- fields["dependencies"] = []
-
- if (instance.isolation=="container"):
- fields["ONOS_container"] = "%s-%s" % (instance.slice.name, str(instance.id))
- else:
- fields["ONOS_container"] = "ONOS"
- return fields
-
- def sync_fields(self, o, fields):
- # the super causes the playbook to be run
- super(SyncONOSApp, self).sync_fields(o, fields)
-
- def run_playbook(self, o, fields):
- super(SyncONOSApp, self).run_playbook(o, fields)
-
- def delete_record(self, m):
- pass
diff --git a/xos/observers/onos/steps/sync_onosapp.yaml b/xos/observers/onos/steps/sync_onosapp.yaml
deleted file mode 100644
index 496fad0..0000000
--- a/xos/observers/onos/steps/sync_onosapp.yaml
+++ /dev/null
@@ -1,91 +0,0 @@
----
-- hosts: {{ instance_name }}
- gather_facts: False
- connection: ssh
- user: {{ username }}
- sudo: yes
- vars:
- appname: {{ appname }}
- dependencies: {{ dependencies }}
-{% if rest_configs %}
- rest_configs:
-{% for rest_config in rest_configs %}
- - endpoint: {{ rest_config.endpoint }}
- body: "{{ '{{' }} lookup('file', '{{ files_dir }}/{{ rest_config.fn }}') {{ '}}' }}"
-{% endfor %}
-{% endif %}
-
- tasks:
-
- - name: Get Docker IP
- script: /opt/xos/observers/onos/scripts/dockerip.sh {{ ONOS_container }}
- register: onosaddr
-
- - name: Wait for ONOS to come up
- wait_for:
- host={{ '{{' }} onosaddr.stdout {{ '}}' }}
- port={{ '{{' }} item {{ '}}' }}
- state=present
- with_items:
- - 8101
- - 8181
- - 9876
-
- - name: Config file directory
- file:
- path=/home/ubuntu/{{ appname }}/
- state=directory
-
-{% if config_fns %}
- - name: Copy over configuration files
- copy:
- src={{ files_dir }}/{{ '{{' }} item {{ '}}' }}
- dest=/home/ubuntu/{{ appname }}/{{ '{{' }} item {{ '}}' }}
- with_items:
- {% for config_fn in config_fns %}
- - {{ config_fn }}
- {% endfor %}
-
- - name: Make sure config directory exists
- shell: docker exec {{ ONOS_container }} mkdir -p /root/onos/config/
- sudo: yes
-
- - name: Copy config files into container
- shell: docker cp {{ appname }}/{{ '{{' }} item {{ '}}' }} {{ ONOS_container }}:/root/onos/config/
- sudo: yes
- with_items:
- {% for config_fn in config_fns %}
- - {{ config_fn }}
- {% endfor %}
-{% endif %}
-
- # Don't know how to check for this condition, just wait
- - name: Wait for ONOS to install the apps
- wait_for: timeout=15
-
-{% if dependencies %}
- - name: Add dependencies to ONOS
- uri:
- url: http://{{ '{{' }} onosaddr.stdout {{ '}}' }}:8181/onos/v1/applications/{{ '{{' }} item {{ '}}' }}/active
- method: POST
- user: karaf
- password: karaf
- with_items:
- {% for dependency in dependencies %}
- - {{ dependency }}
- {% endfor %}
-{% endif %}
-
-{% if rest_configs %}
-# Do this after services have been activated, or it will cause an exception.
-# vOLT will re-read its net config; vbng may not.
- - name: Add ONOS configuration values
- uri:
- url: http://{{ '{{' }} onosaddr.stdout {{ '}}' }}:8181/{{ '{{' }} item.endpoint {{ '}}' }} #http://localhost:8181/onos/v1/network/configuration/
- body: "{{ '{{' }} item.body {{ '}}' }}"
- body_format: raw
- method: POST
- user: karaf
- password: karaf
- with_items: "rest_configs"
-{% endif %}
diff --git a/xos/observers/onos/steps/sync_onosservice.py b/xos/observers/onos/steps/sync_onosservice.py
deleted file mode 100644
index 420904a..0000000
--- a/xos/observers/onos/steps/sync_onosservice.py
+++ /dev/null
@@ -1,77 +0,0 @@
-import hashlib
-import os
-import socket
-import sys
-import base64
-import time
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from observer.ansible import run_template_ssh
-from observers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
-from core.models import Service, Slice
-from services.onos.models import ONOSService, ONOSApp
-from util.logger import Logger, logging
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-logger = Logger(level=logging.INFO)
-
-class SyncONOSService(SyncInstanceUsingAnsible):
- provides=[ONOSService]
- observes=ONOSService
- requested_interval=0
- template_name = "sync_onosservice.yaml"
- service_key_name = "/opt/xos/observers/onos/onos_key"
-
- def __init__(self, *args, **kwargs):
- super(SyncONOSService, self).__init__(*args, **kwargs)
-
- def fetch_pending(self, deleted):
- if (not deleted):
- objs = ONOSService.get_service_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
- else:
- objs = ONOSService.get_deleted_service_objects()
-
- return objs
-
- def get_instance(self, o):
- # We assume the ONOS service owns a slice, so pick one of the instances
- # inside that slice to sync to.
-
- serv = o
-
- if serv.use_external_host:
- return serv.use_external_host
-
- if serv.slices.exists():
- slice = serv.slices.all()[0]
- if slice.instances.exists():
- return slice.instances.all()[0]
-
- return None
-
- def get_extra_attributes(self, o):
- fields={}
- fields["instance_hostname"] = self.get_instance(o).instance_name.replace("_","-")
- fields["appname"] = o.name
- fields["nat_ip"] = self.get_instance(o).get_ssh_ip()
- fields["ONOS_container"] = "ONOS"
- return fields
-
- def sync_fields(self, o, fields):
- # the super causes the playbook to be run
- super(SyncONOSService, self).sync_fields(o, fields)
-
- def run_playbook(self, o, fields):
- instance = self.get_instance(o)
- if (instance.isolation=="container"):
- # If the instance is already a container, then we don't need to
- # install ONOS.
- return
- super(SyncONOSService, self).run_playbook(o, fields)
-
- def delete_record(self, m):
- pass
diff --git a/xos/observers/onos/supervisor/onos-observer.conf b/xos/observers/onos/supervisor/onos-observer.conf
deleted file mode 100644
index 16afa8c..0000000
--- a/xos/observers/onos/supervisor/onos-observer.conf
+++ /dev/null
@@ -1,2 +0,0 @@
-[program:onos-observer]
-command=python /opt/xos/observers/onos/onos-observer.py -C /opt/xos/observers/onos/onos_observer_config
diff --git a/xos/observers/vbng/steps/sync_vbngtenant.py b/xos/observers/vbng/steps/sync_vbngtenant.py
deleted file mode 100644
index 1347e2f..0000000
--- a/xos/observers/vbng/steps/sync_vbngtenant.py
+++ /dev/null
@@ -1,142 +0,0 @@
-import os
-import requests
-import socket
-import sys
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from observer.ansible import run_template_ssh
-from core.models import Service
-from cord.models import VCPEService, VCPETenant, VBNGTenant, VBNGService
-from hpc.models import HpcService, CDNPrefix
-from util.logger import Logger, logging
-
-# VBNG_API = "http://10.0.3.136:8181/onos/virtualbng/privateip/"
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-logger = Logger(level=logging.INFO)
-
-class SyncVBNGTenant(SyncStep):
- provides=[VCPETenant]
- observes=VCPETenant
- requested_interval=0
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
-
- def fetch_pending(self, deleted):
- if (not deleted):
- objs = VBNGTenant.get_tenant_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
- else:
- objs = VBNGTenant.get_deleted_tenant_objects()
-
- return objs
-
- def defer_sync(self, o, reason):
- logger.info("defer object %s due to %s" % (str(o), reason))
- raise Exception("defer object %s due to %s" % (str(o), reason))
-
- def get_vbng_service(self, o):
- if not o.provider_service:
- raise Exception("vBNG tenant %s has no provider_service" % str(o.id))
- services = VBNGService.get_service_objects().filter(id = o.provider_service.id)
- if not services:
- raise Exception("vBNG tenant %s is associated with the wrong kind of provider_service" % str(o.id))
- return services[0]
-
- def get_vbng_url(self, o):
- service = self.get_vbng_service(o)
-
- # if the service object specifies a vbng_url, then use it
- if service.vbng_url:
- return service.vbng_url
-
- # otherwise, see if the service has tenancy in ONOS
- for tenant in service.subscribed_tenants.all():
- if tenant.provider_service and tenant.provider_service.kind == "onos":
- onos_service = tenant.provider_service
- if not onos_service.slices.exists():
- raise Exception("vBNG service is linked to an ONOSApp, but the App's Service has no slices")
- onos_slice = onos_service.slices.all()[0]
- if not onos_slice.instances.exists():
- raise Exception("vBNG service is linked to an ONOSApp, but the App's Service's Slice has no instances")
- instance = onos_slice.instances.all()[0]
-
- #onos_app = ONOSApp.objects.filter(id = tenant.id)
- #instance = onos_app.instance
- #if not instance:
- # raise Exception("ONOSApp has no instance")
-
- if not instance.instance_name:
- raise Exception("vBNG service is linked to an ONOSApp, but the App's Service's Slice's first instance is not instantiated")
- ip = instance.get_network_ip("nat")
- if not ip:
- raise Exception("vBNG service is linked to an ONOSApp, but the App's Service's Slice's first instance does not have an ip")
-
- logger.info("Using ip %s from ONOS Instance %s" % (ip, instance))
-
- return "http://%s:8181/onos/virtualbng/" % ip
-
- raise Exception("vBNG service does not have vbng_url set, and is not linked to an ONOSApp")
-
- def get_private_interface(self, o):
- vcpes = VCPETenant.get_tenant_objects().all()
- vcpes = [x for x in vcpes if (x.vbng is not None) and (x.vbng.id == o.id)]
- if not vcpes:
- raise Exception("No vCPE tenant is associated with vBNG %s" % str(o.id))
- if len(vcpes)>1:
- raise Exception("More than one vCPE tenant is associated with vBNG %s" % str(o.id))
-
- vcpe = vcpes[0]
- instance = vcpe.instance
-
- if not instance:
- raise Exception("No instance associated with vBNG %s" % str(o.id))
-
- if not vcpe.wan_ip:
- self.defer_sync(o, "does not have a WAN IP yet")
-
- if not vcpe.wan_container_mac:
- # this should never happen; container MAC is computed from WAN IP
- self.defer_sync(o, "does not have a WAN container MAC yet")
-
- return (vcpe.wan_ip, vcpe.wan_container_mac, vcpe.instance.node.name)
-
- def sync_record(self, o):
- logger.info("sync'ing VBNGTenant %s" % str(o))
-
- if not o.routeable_subnet:
- (private_ip, private_mac, private_hostname) = self.get_private_interface(o)
- logger.info("contacting vBNG service to request mapping for private ip %s mac %s host %s" % (private_ip, private_mac, private_hostname) )
-
- url = self.get_vbng_url(o) + "privateip/%s/%s/%s" % (private_ip, private_mac, private_hostname)
- logger.info( "vbng url: %s" % url )
- r = requests.post(url )
- if (r.status_code != 200):
- raise Exception("Received error from bng service (%d)" % r.status_code)
- logger.info("received public IP %s from private IP %s" % (r.text, private_ip))
-
- if r.text == "0":
- raise Exception("VBNG service failed to return a routeable_subnet (probably ran out)")
-
- o.routeable_subnet = r.text
- o.mapped_ip = private_ip
- o.mapped_mac = private_mac
- o.mapped_hostname = private_hostname
-
- o.save()
-
- def delete_record(self, o):
- logger.info("deleting VBNGTenant %s" % str(o))
-
- if o.mapped_ip:
- private_ip = o.mapped_ip
- logger.info("contacting vBNG service to delete private ip %s" % private_ip)
- r = requests.delete(self.get_vbng_url(o) + "privateip/%s" % private_ip, )
- if (r.status_code != 200):
- raise Exception("Received error from bng service (%d)" % r.status_code)
-
diff --git a/xos/observers/vbng/vbng-observer.py b/xos/observers/vbng/vbng-observer.py
deleted file mode 100755
index d6a71ff..0000000
--- a/xos/observers/vbng/vbng-observer.py
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/usr/bin/env python
-
-# This imports and runs ../../xos-observer.py
-
-import importlib
-import os
-import sys
-observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../..")
-sys.path.append(observer_path)
-mod = importlib.import_module("xos-observer")
-mod.main()
diff --git a/xos/observers/vbng/vbng_observer_config b/xos/observers/vbng/vbng_observer_config
deleted file mode 100644
index b75d498..0000000
--- a/xos/observers/vbng/vbng_observer_config
+++ /dev/null
@@ -1,38 +0,0 @@
-
-[plc]
-name=plc
-deployment=VICCI
-
-[db]
-name=xos
-user=postgres
-password=password
-host=localhost
-port=5432
-
-[api]
-host=128.112.171.237
-port=8000
-ssl_key=None
-ssl_cert=None
-ca_ssl_cert=None
-ratelimit_enabled=0
-omf_enabled=0
-mail_support_address=support@localhost
-nova_enabled=True
-
-[observer]
-name=vbng
-dependency_graph=/opt/xos/observers/vbng/model-deps
-steps_dir=/opt/xos/observers/vbng/steps
-sys_dir=/opt/xos/observers/vbng/sys
-deleters_dir=/opt/xos/observers/vbng/deleters
-log_file=console
-#/var/log/hpc.log
-driver=None
-pretend=False
-backoff_disabled=True
-
-[feefie]
-client_id='vicci_dev_central'
-user_id='pl'
diff --git a/xos/observers/vcpe/observer_ansible_test.py b/xos/observers/vcpe/observer_ansible_test.py
deleted file mode 100644
index 77715af..0000000
--- a/xos/observers/vcpe/observer_ansible_test.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/usr/bin/env python
-import os
-import sys
-
-sys.path.append("../..")
-import observer.ansible
-
-print sys.argv
-
-private_key="""-----BEGIN RSA PRIVATE KEY-----
-MIIEpQIBAAKCAQEAtJiuarud5S4Y2quDeWyaS0UCQGQtfuSzzNhplFwujYnJGL65
-e14REtv+UuHGymyr/SfkTrBd8vH5NI2UZ/4sZW13ieI/1d97OeVe2+ct0Y4BaFEI
-3Hja6DIpsY3Q2cBQsWUwc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yRgBTgQh
-VwLw/AZ4PvoyWMdbAENApgECgYEAvFikosYP09XTyIPaKaOKY5iqqBoSC1GucSOB
-jAG+T3k5dxB6nQS0nYQUomvqak7drqnT6O33Lrr5ySrW5nCjnmvgJZwvv+Rp1bDM
-K5uRT8caPpJ+Wcp4TUdPi3BVA2MOHVDyEJg3AH/D1+DL/IgGQ/JcwOHsKt61iLhO
-EBXj5zECgYEAk+HuwksUPkSxg/AiJGbapGDK6XGymEUzo2duWlnofRqGcZ3NT3bB
-/kDI1KxQdlpODXSi4/BuTpbQiFOrzcEq5e5ytoMxlCHh3Fl3Jxl+JlgO21vAUvP6
-4SET7Q/6LxmfBlCVRg0dXDwcfJLgbnWxyvprIcz4e0FSFVZTBs/6tFk=
------END RSA PRIVATE KEY-----
-"""
-
-observer.ansible.run_template_ssh("test.yaml",
- {"instance_name": "onlab_test405-378",
- "instance_id": "instance-0000004d",
- "hostname": "node67.washington.vicci.org",
- "private_key": private_key})
-
diff --git a/xos/observers/vcpe/steps/sync_vcpetenant.py b/xos/observers/vcpe/steps/sync_vcpetenant.py
deleted file mode 100644
index 0985d22..0000000
--- a/xos/observers/vcpe/steps/sync_vcpetenant.py
+++ /dev/null
@@ -1,235 +0,0 @@
-import hashlib
-import os
-import socket
-import sys
-import base64
-import time
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from observer.ansible import run_template_ssh
-from observers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
-from core.models import Service, Slice
-from cord.models import VCPEService, VCPETenant, VOLTTenant
-from hpc.models import HpcService, CDNPrefix
-from util.logger import Logger, logging
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-from broadbandshield import BBS
-
-logger = Logger(level=logging.INFO)
-
-PARENTAL_MECHANISM="dnsmasq"
-ENABLE_QUICK_UPDATE=False
-
-class SyncVCPETenant(SyncInstanceUsingAnsible):
- provides=[VCPETenant]
- observes=VCPETenant
- requested_interval=0
- template_name = "sync_vcpetenant.yaml"
- service_key_name = "/opt/xos/observers/vcpe/vcpe_private_key"
-
- def __init__(self, *args, **kwargs):
- super(SyncVCPETenant, self).__init__(*args, **kwargs)
-
- def fetch_pending(self, deleted):
- if (not deleted):
- objs = VCPETenant.get_tenant_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
- else:
- objs = VCPETenant.get_deleted_tenant_objects()
-
- return objs
-
- def get_vcpe_service(self, o):
- if not o.provider_service:
- return None
-
- vcpes = VCPEService.get_service_objects().filter(id=o.provider_service.id)
- if not vcpes:
- return None
-
- return vcpes[0]
-
- def get_extra_attributes(self, o):
- # This is a place to include extra attributes that aren't part of the
- # object itself. In the case of vCPE, we need to know:
- # 1) the addresses of dnsdemux, to setup dnsmasq in the vCPE
- # 2) CDN prefixes, so we know what URLs to send to dnsdemux
- # 3) BroadBandShield server addresses, for parental filtering
- # 4) vlan_ids, for setting up networking in the vCPE VM
-
- vcpe_service = self.get_vcpe_service(o)
-
- dnsdemux_ip = None
- if vcpe_service.backend_network_label:
- # Connect to dnsdemux using the network specified by
- # vcpe_service.backend_network_label
- for service in HpcService.objects.all():
- for slice in service.slices.all():
- if "dnsdemux" in slice.name:
- for instance in slice.instances.all():
- for ns in instance.ports.all():
- if ns.ip and ns.network.labels and (vcpe_service.backend_network_label in ns.network.labels):
- dnsdemux_ip = ns.ip
- if not dnsdemux_ip:
- logger.info("failed to find a dnsdemux on network %s" % vcpe_service.backend_network_label)
- else:
- # Connect to dnsdemux using the instance's public address
- for service in HpcService.objects.all():
- for slice in service.slices.all():
- if "dnsdemux" in slice.name:
- for instance in slice.instances.all():
- if dnsdemux_ip=="none":
- try:
- dnsdemux_ip = socket.gethostbyname(instance.node.name)
- except:
- pass
- if not dnsdemux_ip:
- logger.info("failed to find a dnsdemux with a public address")
-
- dnsdemux_ip = dnsdemux_ip or "none"
-
- cdn_prefixes = []
- for prefix in CDNPrefix.objects.all():
- cdn_prefixes.append(prefix.prefix)
-
- # Broadbandshield can either be set up internally, using vcpe_service.bbs_slice,
- # or it can be setup externally using vcpe_service.bbs_server.
-
- bbs_addrs = []
- if vcpe_service.bbs_slice:
- if vcpe_service.backend_network_label:
- for bbs_instance in vcpe_service.bbs_slice.instances.all():
- for ns in bbs_instance.ports.all():
- if ns.ip and ns.network.labels and (vcpe_service.backend_network_label in ns.network.labels):
- bbs_addrs.append(ns.ip)
- else:
- logger.info("unsupported configuration -- bbs_slice is set, but backend_network_label is not")
- if not bbs_addrs:
- logger.info("failed to find any usable addresses on bbs_slice")
- elif vcpe_service.bbs_server:
- bbs_addrs.append(vcpe_service.bbs_server)
- else:
- logger.info("neither bbs_slice nor bbs_server is configured in the vCPE")
-
- vlan_ids = []
- s_tags = []
- c_tags = []
- if o.volt:
- vlan_ids.append(o.volt.vlan_id) # XXX remove this
- s_tags.append(o.volt.s_tag)
- c_tags.append(o.volt.c_tag)
-
- try:
- full_setup = Config().observer_full_setup
- except:
- full_setup = True
-
- safe_macs=[]
- if o.volt and o.volt.subscriber:
- for user in o.volt.subscriber.users:
- level = user.get("level",None)
- mac = user.get("mac",None)
- if level in ["G", "PG"]:
- if mac:
- safe_macs.append(mac)
-
- fields = {"vlan_ids": vlan_ids, # XXX remove this
- "s_tags": s_tags,
- "c_tags": c_tags,
- "dnsdemux_ip": dnsdemux_ip,
- "cdn_prefixes": cdn_prefixes,
- "bbs_addrs": bbs_addrs,
- "full_setup": full_setup,
- "isolation": o.instance.isolation,
- "safe_browsing_macs": safe_macs}
-
- # add in the sync_attributes that come from the SubscriberRoot object
-
- if o.volt and o.volt.subscriber and hasattr(o.volt.subscriber, "sync_attributes"):
- for attribute_name in o.volt.subscriber.sync_attributes:
- fields[attribute_name] = getattr(o.volt.subscriber, attribute_name)
-
- return fields
-
- def sync_fields(self, o, fields):
- # the super causes the playbook to be run
-
- super(SyncVCPETenant, self).sync_fields(o, fields)
-
- # now do all of our broadbandshield stuff...
-
- service = self.get_vcpe_service(o)
- if not service:
- # Ansible uses the service's keypair in order to SSH into the
- # instance. It would be bad if the slice had no service.
-
- raise Exception("Slice %s is not associated with a service" % instance.slice.name)
-
- # Make sure the slice is configured properly
- if (service != o.instance.slice.service):
- raise Exception("Slice %s is associated with some service that is not %s" % (str(instance.slice), str(service)))
-
- # only enable filtering if we have a subscriber object (see below)
- url_filter_enable = False
-
- # for attributes that come from CordSubscriberRoot
- if o.volt and o.volt.subscriber:
- url_filter_enable = o.volt.subscriber.url_filter_enable
- url_filter_level = o.volt.subscriber.url_filter_level
- url_filter_users = o.volt.subscriber.users
-
- if PARENTAL_MECHANISM=="broadbandshield":
- # disable url_filter if there are no bbs_addrs
- if url_filter_enable and (not fields.get("bbs_addrs",[])):
- logger.info("disabling url_filter because there are no bbs_addrs")
- url_filter_enable = False
-
- if url_filter_enable:
- bbs_hostname = None
- if service.bbs_api_hostname and service.bbs_api_port:
- bbs_hostname = service.bbs_api_hostname
- else:
- # TODO: extract from slice
- bbs_hostname = "cordcompute01.onlab.us"
-
- if service.bbs_api_port:
- bbs_port = service.bbs_api_port
- else:
- bbs_port = 8018
-
- if not bbs_hostname:
- logger.info("broadbandshield is not configured")
- else:
- tStart = time.time()
- bbs = BBS(o.bbs_account, "123", bbs_hostname, bbs_port)
- bbs.sync(url_filter_level, url_filter_users)
-
- if o.hpc_client_ip:
- logger.info("associate account %s with ip %s" % (o.bbs_account, o.hpc_client_ip))
- bbs.associate(o.hpc_client_ip)
- else:
- logger.info("no hpc_client_ip to associate")
-
- logger.info("bbs update time %d" % int(time.time()-tStart))
-
-
- def run_playbook(self, o, fields):
- ansible_hash = hashlib.md5(repr(sorted(fields.items()))).hexdigest()
- quick_update = (o.last_ansible_hash == ansible_hash)
-
- if ENABLE_QUICK_UPDATE and quick_update:
- logger.info("quick_update triggered; skipping ansible recipe")
- else:
- if o.instance.isolation in ["container", "container_vm"]:
- super(SyncVCPETenant, self).run_playbook(o, fields, "sync_vcpetenant_new.yaml")
- else:
- super(SyncVCPETenant, self).run_playbook(o, fields)
-
- o.last_ansible_hash = ansible_hash
-
- def delete_record(self, m):
- pass
diff --git a/xos/observers/vcpe/steps/sync_vcpetenant.yaml b/xos/observers/vcpe/steps/sync_vcpetenant.yaml
deleted file mode 100644
index db6ecf5..0000000
--- a/xos/observers/vcpe/steps/sync_vcpetenant.yaml
+++ /dev/null
@@ -1,174 +0,0 @@
----
-- hosts: {{ instance_name }}
- gather_facts: False
- connection: ssh
- user: ubuntu
- sudo: yes
- vars:
- cdn_enable: {{ cdn_enable }}
- dnsdemux_ip: {{ dnsdemux_ip }}
- firewall_enable: {{ firewall_enable }}
- url_filter_enable: {{ url_filter_enable }}
- vlan_ids:
- {% for vlan_id in vlan_ids %}
- - {{ vlan_id }}
- {% endfor %}
- c_tags:
- {% for c_tag in c_tags %}
- - {{ c_tag }}
- {% endfor %}
- s_tags:
- {% for s_tag in s_tags %}
- - {{ s_tag }}
- {% endfor %}
- firewall_rules:
- {% for firewall_rule in firewall_rules.split("\n") %}
- - {{ firewall_rule }}
- {% endfor %}
- cdn_prefixes:
- {% for prefix in cdn_prefixes %}
- - {{ prefix }}
- {% endfor %}
- bbs_addrs:
- {% for bbs_addr in bbs_addrs %}
- - {{ bbs_addr }}
- {% endfor %}
- nat_ip: {{ nat_ip }}
- nat_mac: {{ nat_mac }}
- lan_ip: {{ lan_ip }}
- lan_mac: {{ lan_mac }}
- wan_ip: {{ wan_ip }}
- wan_mac: {{ wan_mac }}
- wan_container_mac: {{ wan_container_mac }}
- wan_next_hop: 10.0.1.253 # FIX ME
- private_ip: {{ private_ip }}
- private_mac: {{ private_mac }}
- hpc_client_ip: {{ hpc_client_ip }}
- hpc_client_mac: {{ hpc_client_mac }}
- keystone_tenant_id: {{ keystone_tenant_id }}
- keystone_user_id: {{ keystone_user_id }}
- rabbit_user: {{ rabbit_user }}
- rabbit_password: {{ rabbit_password }}
- rabbit_host: {{ rabbit_host }}
- safe_browsing:
- {% for mac in safe_browsing_macs %}
- - {{ mac }}
- {% endfor %}
-
- tasks:
-{% if full_setup %}
- - name: Docker repository
- copy: src=/opt/xos/observers/vcpe/files/docker.list
- dest=/etc/apt/sources.list.d/docker.list
-
- - name: Import the repository key
- apt_key: keyserver=keyserver.ubuntu.com id=36A1D7869245C8950F966E92D8576A8BA88D21E9
-
- - name: install Docker
- apt: name=lxc-docker-1.5.0 state=present update_cache=yes
-
- - name: install python-setuptools
- apt: name=python-setuptools state=present
-
- - name: install pip
- easy_install: name=pip
-
- - name: install docker-py
- pip: name=docker-py version=0.5.3
-
- - name: install Pipework
- get_url: url=https://raw.githubusercontent.com/jpetazzo/pipework/master/pipework
- dest=/usr/local/bin/pipework
- mode=0755
-
- - name: make sure /etc/dnsmasq.d exists
- file: path=/etc/dnsmasq.d state=directory owner=root group=root
-
- - name: Disable resolvconf service
- shell: service resolvconf stop
- shell: echo manual > /etc/init/resolvconf.override
- shell: rm -f /etc/resolv.conf
-
- - name: Install resolv.conf
- copy: src=/opt/xos/observers/vcpe/files/vm-resolv.conf
- dest=/etc/resolv.conf
-
- - name: Verify if vcpe_stats_notifier ([] is to avoid capturing the shell process) cron job is already running
- shell: pgrep -f [v]cpe_stats_notifier | wc -l
- register: cron_job_pids_count
-
-# - name: DEBUG
-# debug: var=cron_job_pids_count.stdout
-
- - name: make sure ~/bin exists
- file: path=~/bin state=directory owner=root group=root
- when: cron_job_pids_count.stdout == "0"
-
- - name: Copy cron job to destination
- copy: src=/opt/xos/observers/vcpe/vcpe_stats_notifier.py
- dest=~/bin/vcpe_stats_notifier.py
- when: cron_job_pids_count.stdout == "0"
-
- - name: install python-kombu
- apt: name=python-kombu state=present
- when: cron_job_pids_count.stdout == "0"
-
- - name: Initiate vcpe_stats_notifier cron job
- command: python ~/bin/vcpe_stats_notifier.py --keystone_tenant_id={{ keystone_tenant_id }} --keystone_user_id={{ keystone_user_id }} --rabbit_user={{ rabbit_user }} --rabbit_password={{ rabbit_password }} --rabbit_host={{ rabbit_host }} --vcpeservice_rabbit_exchange='vcpeservice'
- async: 9999999999999999
- poll: 0
- when: cron_job_pids_count.stdout == "0"
-{% endif %}
-
- - name: vCPE upstart
- template: src=/opt/xos/observers/vcpe/templates/vcpe.conf.j2 dest=/etc/init/vcpe-{{ s_tags[0] }}-{{ c_tags[0] }}.conf
-
- - name: vCPE startup script
- template: src=/opt/xos/observers/vcpe/templates/start-vcpe.sh.j2 dest=/usr/local/sbin/start-vcpe-{{ s_tags[0] }}-{{ c_tags[0] }}.sh mode=0755
- notify:
-# - restart vcpe
- - stop vcpe
- - remove container
- - start vcpe
-
- - name: create /etc/vcpe-{{ s_tags[0] }}-{{ c_tags[0] }}/dnsmasq.d
- file: path=/etc/vcpe-{{ s_tags[0] }}-{{ c_tags[0] }}/dnsmasq.d state=directory owner=root group=root
-
- - name: vCPE basic dnsmasq config
- copy: src=/opt/xos/observers/vcpe/files/vcpe.dnsmasq dest=/etc/vcpe-{{ s_tags[0] }}-{{ c_tags[0] }}/dnsmasq.d/vcpe.conf owner=root group=root
- notify:
- - restart dnsmasq
-
- - name: dnsmasq config
- template: src=/opt/xos/observers/vcpe/templates/dnsmasq_servers.j2 dest=/etc/vcpe-{{ s_tags[0] }}-{{ c_tags[0] }}/dnsmasq.d/servers.conf owner=root group=root
- notify:
- - restart dnsmasq
-
-# These are samples, not necessary for correct function of demo
-
-# - name: networking info
-# template: src=/opt/xos/observers/vcpe/templates/vlan_sample.j2 dest=/etc/vlan_sample owner=root group=root
-
-# - name: firewall info
-# template: src=/opt/xos/observers/vcpe/templates/firewall_sample.j2 dest=/etc/firewall_sample owner=root group=root
-
- - name: Make sure vCPE service is running
- service: name=vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} state=started
-
- handlers:
- # Dnsmasq is automatically restarted in the container
- - name: restart dnsmasq
- shell: docker exec vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} killall dnsmasq
-
- - name: restart vcpe
- shell: service vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} stop; sleep 1; service vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} start
-
- - name: stop vcpe
- service: name=vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} state=stopped
-
- - name: remove container
- docker: name=vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} state=absent image=docker-vcpe
-
- - name: start vcpe
- service: name=vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} state=started
-
diff --git a/xos/observers/vcpe/steps/sync_vcpetenant_new.yaml b/xos/observers/vcpe/steps/sync_vcpetenant_new.yaml
deleted file mode 100644
index eb647b6..0000000
--- a/xos/observers/vcpe/steps/sync_vcpetenant_new.yaml
+++ /dev/null
@@ -1,105 +0,0 @@
----
-- hosts: {{ instance_name }}
- gather_facts: False
- connection: ssh
- user: {{ username }}
- sudo: yes
- vars:
- container_name: {{ container_name }}
- cdn_enable: {{ cdn_enable }}
- dnsdemux_ip: {{ dnsdemux_ip }}
- firewall_enable: {{ firewall_enable }}
- url_filter_enable: {{ url_filter_enable }}
- vlan_ids:
- {% for vlan_id in vlan_ids %}
- - {{ vlan_id }}
- {% endfor %}
- c_tags:
- {% for c_tag in c_tags %}
- - {{ c_tag }}
- {% endfor %}
- s_tags:
- {% for s_tag in s_tags %}
- - {{ s_tag }}
- {% endfor %}
- firewall_rules:
- {% for firewall_rule in firewall_rules.split("\n") %}
- - {{ firewall_rule }}
- {% endfor %}
- cdn_prefixes:
- {% for prefix in cdn_prefixes %}
- - {{ prefix }}
- {% endfor %}
- bbs_addrs:
- {% for bbs_addr in bbs_addrs %}
- - {{ bbs_addr }}
- {% endfor %}
- nat_ip: {{ nat_ip }}
- nat_mac: {{ nat_mac }}
- lan_ip: {{ lan_ip }}
- lan_mac: {{ lan_mac }}
- wan_ip: {{ wan_ip }}
- wan_mac: {{ wan_mac }}
- wan_container_mac: {{ wan_container_mac }}
- wan_next_hop: 10.0.1.253 # FIX ME
- private_ip: {{ private_ip }}
- private_mac: {{ private_mac }}
- hpc_client_ip: {{ hpc_client_ip }}
- hpc_client_mac: {{ hpc_client_mac }}
- keystone_tenant_id: {{ keystone_tenant_id }}
- keystone_user_id: {{ keystone_user_id }}
- rabbit_user: {{ rabbit_user }}
- rabbit_password: {{ rabbit_password }}
- rabbit_host: {{ rabbit_host }}
- safe_browsing:
- {% for mac in safe_browsing_macs %}
- - {{ mac }}
- {% endfor %}
-
- tasks:
- - name: vCPE basic dnsmasq config
- copy: src=/opt/xos/observers/vcpe/files/vcpe.dnsmasq dest=/var/container_volumes/{{ container_name }}/etc/dnsmasq.d/vcpe.conf owner=root group=root
- notify:
- - restart dnsmasq
-
- - name: dnsmasq config
- template: src=/opt/xos/observers/vcpe/templates/dnsmasq_servers.j2 dest=/var/container_volumes/{{ container_name }}/etc/dnsmasq.d/servers.conf owner=root group=root
- notify:
- - restart dnsmasq
-
- - name: create directory for "safe" config
- file: path=/var/container_volumes/{{ container_name }}/etc/dnsmasq.d/safe state=directory
-
- - name: dnsmasq "safe" config
- template: src=/opt/xos/observers/vcpe/templates/dnsmasq_safe_servers.j2 dest=/var/container_volumes/{{ container_name }}/etc/dnsmasq.d/safe/servers.conf owner=root group=root
- notify:
- - restart dnsmasq
-
- - name: copy base ufw files
- synchronize: src=/opt/xos/observers/vcpe/files/etc/ufw/ dest=/var/container_volumes/{{ container_name }}/etc/ufw/
- notify:
- - reload ufw
-
- - name: redirection rules for safe DNS
- template: src=/opt/xos/observers/vcpe/templates/before.rules.j2 dest=/var/container_volumes/{{ container_name }}/etc/ufw/before.rules owner=root group=root
- notify:
- - reload ufw
-
- - name: base ufw setup uses /etc/rc.local
- copy: src=/opt/xos/observers/vcpe/files/etc/rc.local dest=/var/container_volumes/{{ container_name }}/etc/ owner=root group=root
- notify:
- - copy in /etc/rc.local
-
- handlers:
- # Dnsmasq is automatically restarted in the container
- - name: restart dnsmasq
- shell: docker exec {{ container_name }} /usr/bin/killall dnsmasq
-
- - name: reload ufw
- shell: docker exec {{ container_name }} bash -c "/sbin/iptables -t nat -F PREROUTING; /usr/sbin/ufw reload"
-
- # Use docker cp instead of single-file volume
- # The reason is that changes to external file volume don't show up inside the container
- # Probably Ansible deletes and then recreates the external file, and container has old version
- - name: copy in /etc/rc.local
- shell: docker cp /var/container_volumes/{{ container_name }}/etc/rc.local {{ container_name }}:/etc/
diff --git a/xos/observers/vcpe/vcpe-observer.py b/xos/observers/vcpe/vcpe-observer.py
deleted file mode 100755
index d6a71ff..0000000
--- a/xos/observers/vcpe/vcpe-observer.py
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/usr/bin/env python
-
-# This imports and runs ../../xos-observer.py
-
-import importlib
-import os
-import sys
-observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../..")
-sys.path.append(observer_path)
-mod = importlib.import_module("xos-observer")
-mod.main()
diff --git a/xos/observers/vcpe/vcpe_observer_config b/xos/observers/vcpe/vcpe_observer_config
deleted file mode 100644
index afd1501..0000000
--- a/xos/observers/vcpe/vcpe_observer_config
+++ /dev/null
@@ -1,41 +0,0 @@
-
-[plc]
-name=plc
-deployment=VICCI
-
-[db]
-name=xos
-user=postgres
-password=password
-host=localhost
-port=5432
-
-[api]
-host=128.112.171.237
-port=8000
-ssl_key=None
-ssl_cert=None
-ca_ssl_cert=None
-ratelimit_enabled=0
-omf_enabled=0
-mail_support_address=support@localhost
-nova_enabled=True
-
-[observer]
-name=vcpe
-dependency_graph=/opt/xos/observers/vcpe/model-deps
-steps_dir=/opt/xos/observers/vcpe/steps
-sys_dir=/opt/xos/observers/vcpe/sys
-deleters_dir=/opt/xos/observers/vcpe/deleters
-log_file=console
-#/var/log/hpc.log
-driver=None
-pretend=False
-backoff_disabled=True
-save_ansible_output=True
-proxy_ssh=True
-full_setup=True
-
-[feefie]
-client_id='vicci_dev_central'
-user_id='pl'
diff --git a/xos/observers/vtn/steps/sync_tenant.py b/xos/observers/vtn/steps/sync_tenant.py
deleted file mode 100644
index 45f8722..0000000
--- a/xos/observers/vtn/steps/sync_tenant.py
+++ /dev/null
@@ -1,48 +0,0 @@
-import os
-import requests
-import socket
-import sys
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from core.models import Service
-from core.models.service import COARSE_KIND
-from cord.models import Tenant
-from util.logger import Logger, logging
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-logger = Logger(level=logging.INFO)
-
-class SyncTenant(SyncStep):
- provides=[Tenant]
- observes=Tenant
- requested_interval=0
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
- self.saved_vtn_maps = [] # TODO: load this
-
- def call(self, **args):
- logger.info("sync'ing vtn services")
- for service in Service.objects.all():
- for id in service.get_vtn_src_ids():
- dependencies = service.get_vtn_dependencies_ids()
- if dependencies:
- for dependency in dependencies:
- vtn_maps.append( (id, dependency) )
-
- for vtn_map in vtn_maps:
- if not (vtn_map in self.saved_vtn_maps):
- pass # call vtn rest api to add map
-
- for vtn_map in self.saved_vtn_maps:
- if not vtn_map in vtn_maps:
- pass # call vtn rest api to delete map
-
- self.saved_vtn_maps = vtn_maps
- # TODO: save this
-
diff --git a/xos/observers/vtn/vtn-observer.py b/xos/observers/vtn/vtn-observer.py
deleted file mode 100755
index d6a71ff..0000000
--- a/xos/observers/vtn/vtn-observer.py
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/usr/bin/env python
-
-# This imports and runs ../../xos-observer.py
-
-import importlib
-import os
-import sys
-observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../..")
-sys.path.append(observer_path)
-mod = importlib.import_module("xos-observer")
-mod.main()
diff --git a/xos/observers/vtn/vtn_observer_config b/xos/observers/vtn/vtn_observer_config
deleted file mode 100644
index 19e9a39..0000000
--- a/xos/observers/vtn/vtn_observer_config
+++ /dev/null
@@ -1,38 +0,0 @@
-
-[plc]
-name=plc
-deployment=VICCI
-
-[db]
-name=xos
-user=postgres
-password=password
-host=localhost
-port=5432
-
-[api]
-host=128.112.171.237
-port=8000
-ssl_key=None
-ssl_cert=None
-ca_ssl_cert=None
-ratelimit_enabled=0
-omf_enabled=0
-mail_support_address=support@localhost
-nova_enabled=True
-
-[observer]
-name=vtn
-dependency_graph=/opt/xos/observers/vtn/model-deps
-steps_dir=/opt/xos/observers/vtn/steps
-sys_dir=/opt/xos/observers/vtn/sys
-deleters_dir=/opt/xos/observers/vtn/deleters
-log_file=console
-#/var/log/hpc.log
-driver=None
-pretend=False
-backoff_disabled=True
-
-[feefie]
-client_id='vicci_dev_central'
-user_id='pl'
diff --git a/xos/openstack_observer/ansible.py b/xos/openstack_observer/ansible.py
deleted file mode 100644
index 94b09bd..0000000
--- a/xos/openstack_observer/ansible.py
+++ /dev/null
@@ -1,211 +0,0 @@
-#!/usr/bin/env python
-import jinja2
-import tempfile
-import os
-import json
-import pdb
-import string
-import random
-import re
-import traceback
-import subprocess
-from xos.config import Config, XOS_DIR
-from util.logger import observer_logger
-
-try:
- step_dir = Config().observer_steps_dir
- sys_dir = Config().observer_sys_dir
-except:
- step_dir = XOS_DIR + '/observer/steps'
- sys_dir = '/opt/opencloud'
-
-os_template_loader = jinja2.FileSystemLoader( searchpath=step_dir)
-os_template_env = jinja2.Environment(loader=os_template_loader)
-
-def parse_output(msg):
- lines = msg.splitlines()
- results = []
-
- observer_logger.info(msg)
-
- for l in lines:
- magic_str = 'ok: [127.0.0.1] => '
- magic_str2 = 'changed: [127.0.0.1] => '
- if (l.startswith(magic_str)):
- w = len(magic_str)
- str = l[w:]
- d = json.loads(str)
- results.append(d)
- elif (l.startswith(magic_str2)):
- w = len(magic_str2)
- str = l[w:]
- d = json.loads(str)
- results.append(d)
-
-
- return results
-
-def parse_unreachable(msg):
- total_unreachable=0
- total_failed=0
- for l in msg.splitlines():
- x = re.findall('ok=([0-9]+).*changed=([0-9]+).*unreachable=([0-9]+).*failed=([0-9]+)', l)
- if x:
- (ok, changed, unreachable, failed) = x[0]
- ok=int(ok)
- changed=int(changed)
- unreachable=int(unreachable)
- failed=int(failed)
-
- total_unreachable += unreachable
- total_failed += failed
- return {'unreachable':total_unreachable,'failed':total_failed}
-
-
-def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
- return ''.join(random.choice(chars) for _ in range(size))
-
-def shellquote(s):
- return "'" + s.replace("'", "'\\''") + "'"
-
-def get_playbook_fn(opts, path):
- if not opts.get("ansible_tag", None):
- # if no ansible_tag is in the options, then generate a unique one
- objname= id_generator()
- opts = opts.copy()
- opts["ansible_tag"] = objname
-
- objname = opts["ansible_tag"]
-
- os.system('mkdir -p %s' % os.path.join(sys_dir, path))
- return (opts, os.path.join(sys_dir,path,objname))
-
-def run_template(name, opts, path='', expected_num=None, ansible_config=None, ansible_hosts=None, run_ansible_script=None):
- template = os_template_env.get_template(name)
- buffer = template.render(opts)
-
- (opts, fqp) = get_playbook_fn(opts, path)
-
- f = open(fqp,'w')
- f.write(buffer)
- f.flush()
-
- # This is messy -- there's no way to specify ansible config file from
- # the command line, but we can specify it using the environment.
- env = os.environ.copy()
- if ansible_config:
- env["ANSIBLE_CONFIG"] = ansible_config
- if ansible_hosts:
- env["ANSIBLE_HOSTS"] = ansible_hosts
-
- if (not Config().observer_pretend):
- if not run_ansible_script:
- run_ansible_script = os.path.join(XOS_DIR, "observer/run_ansible")
-
- process = subprocess.Popen("%s %s" % (run_ansible_script, shellquote(fqp)), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
- msg = process.stdout.read()
- err_msg = process.stderr.read()
-
- if getattr(Config(), "observer_save_ansible_output", False):
- try:
- open(fqp+".out","w").write(msg)
- open(fqp+".err","w").write(err_msg)
- except:
- # fail silently
- pass
-
- else:
- msg = open(fqp+'.out').read()
-
- try:
- ok_results = parse_output(msg)
- if (expected_num is not None) and (len(ok_results) != expected_num):
- raise ValueError('Unexpected num %s!=%d' % (str(expected_num), len(ok_results)) )
-
- parsed = parse_unreachable(msg)
- total_unreachable = parsed['unreachable']
- failed = parsed['failed']
- if (failed):
- raise ValueError('Ansible playbook failed.')
-
- if (total_unreachable > 0):
- raise ValueError("Unreachable results in ansible recipe")
- except ValueError,e:
- all_fatal = [e.message] + re.findall(r'^msg: (.*)',msg,re.MULTILINE)
- all_fatal2 = re.findall(r'^ERROR: (.*)',msg,re.MULTILINE)
-
- all_fatal.extend(all_fatal2)
- try:
- error = ' // '.join(all_fatal)
- except:
- pass
- raise Exception(error)
-
- return ok_results
-
-def run_template_ssh(name, opts, path='', expected_num=None):
- instance_name = opts["instance_name"]
- hostname = opts["hostname"]
- private_key = opts["private_key"]
- baremetal_ssh = opts.get("baremetal_ssh",False)
- if baremetal_ssh:
- # no instance_id or nat_ip for baremetal
- # we never proxy to baremetal
- proxy_ssh = False
- else:
- instance_id = opts["instance_id"]
- nat_ip = opts["nat_ip"]
- try:
- proxy_ssh = Config().observer_proxy_ssh
- except:
- proxy_ssh = True
-
- (opts, fqp) = get_playbook_fn(opts, path)
- private_key_pathname = fqp + ".key"
- config_pathname = fqp + ".config"
- hosts_pathname = fqp + ".hosts"
-
- f = open(private_key_pathname, "w")
- f.write(private_key)
- f.close()
-
- f = open(config_pathname, "w")
- f.write("[ssh_connection]\n")
- if proxy_ssh:
- proxy_command = "ProxyCommand ssh -q -i %s -o StrictHostKeyChecking=no %s@%s" % (private_key_pathname, instance_id, hostname)
- f.write('ssh_args = -o "%s"\n' % proxy_command)
- f.write('scp_if_ssh = True\n')
- f.write('pipelining = True\n')
- f.write('\n[defaults]\n')
- f.write('host_key_checking = False\n')
- f.close()
-
- f = open(hosts_pathname, "w")
- f.write("[%s]\n" % instance_name)
- if proxy_ssh or baremetal_ssh:
- f.write("%s ansible_ssh_private_key_file=%s\n" % (hostname, private_key_pathname))
- else:
- # acb: Login user is hardcoded, this is not great
- f.write("%s ansible_ssh_private_key_file=%s ansible_ssh_user=ubuntu\n" % (nat_ip, private_key_pathname))
- f.close()
-
- # SSH will complain if private key is world or group readable
- os.chmod(private_key_pathname, 0600)
-
- print "ANSIBLE_CONFIG=%s" % config_pathname
- print "ANSIBLE_HOSTS=%s" % hosts_pathname
-
- return run_template(name, opts, path, ansible_config = config_pathname, ansible_hosts = hosts_pathname, run_ansible_script="/opt/xos/observer/run_ansible_verbose")
-
-
-
-def main():
- run_template('ansible/sync_user_deployments.yaml',{ "endpoint" : "http://172.31.38.128:5000/v2.0/",
- "name" : "Sapan Bhatia",
- "email": "gwsapan@gmail.com",
- "password": "foobar",
- "admin_user":"admin",
- "admin_password":"6a789bf69dd647e2",
- "admin_tenant":"admin",
- "tenant":"demo",
- "roles":['user','admin'] })
diff --git a/xos/openstack_observer/backend.py b/xos/openstack_observer/backend.py
deleted file mode 100644
index 5657491..0000000
--- a/xos/openstack_observer/backend.py
+++ /dev/null
@@ -1,46 +0,0 @@
-import os
-import sys
-import threading
-import time
-from observer.event_loop import XOSObserver
-from observer.event_manager import EventListener
-from util.logger import Logger, logging
-from model_policy import run_policy
-from xos.config import Config
-
-logger = Logger(level=logging.INFO)
-
-class Backend:
-
- def run(self):
- # start the openstack observer
- observer = XOSObserver()
- observer_thread = threading.Thread(target=observer.run)
- observer_thread.start()
-
- # start model policies thread
- observer_name = getattr(Config(), "observer_name", "")
- if (not observer_name):
- model_policy_thread = threading.Thread(target=run_policy)
- model_policy_thread.start()
- else:
- model_policy_thread = None
- print "Skipping model policies thread for service observer."
-
-
- # start event listene
- #event_manager = EventListener(wake_up=observer.wake_up)
- #event_manager_thread = threading.Thread(target=event_manager.run)
- #event_manager_thread.start()
-
- while True:
- try:
- time.sleep(1000)
- except KeyboardInterrupt:
- print "exiting due to keyboard interrupt"
- # TODO: See about setting the threads as daemons
- observer_thread._Thread__stop()
- if model_policy_thread:
- model_policy_thread._Thread__stop()
- sys.exit(1)
-
diff --git a/xos/openstack_observer/ceilometer.py b/xos/openstack_observer/ceilometer.py
deleted file mode 100644
index 792515e..0000000
--- a/xos/openstack_observer/ceilometer.py
+++ /dev/null
@@ -1,120 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-from ceilometerclient import client
-from os import environ as env
-import keystoneclient.v2_0.client as ksclient
-import re
-import datetime
-import time
-from monitor.monitordriver import *
-import pdb
-
-def object_to_filter(model_name, pk):
- from core.models import *
- filter_dict = {
- 'ControllerSlice':[ControllerSlice, 'tenant_id', 'project_id'],
- 'Instance':[Instance, 'instance_id', 'resource_id'],
- 'ControllerSite':[ControllerSite, 'tenant_id', 'project_id']
- }
-
- mod,field,tag = filter_dict[model_name]
- obj = mod.objects.get(pk=pk)
- return '%s=%s'%(tag,getattr(obj,field))
-
-
-def cli_to_array(cli_query):
- '''This converts from the cli list of queries to what is required
- by the python api.
- so from:
- "this<=34;that=foo"
- to
- "[{field=this,op=le,value=34},{field=that,op=eq,value=foo}]"
- '''
- if cli_query is None:
- return None
-
- op_lookup = {'!=': 'ne',
- '>=': 'ge',
- '<=': 'le',
- '>': 'gt',
- '<': 'lt',
- '=': 'eq'}
-
- def split_by_op(string):
- # two character split (<=,!=)
- frags = re.findall(r'([[a-zA-Z0-9_.]+)([><!]=)([^ -,\t\n\r\f\v]+)',
- string)
- if len(frags) == 0:
- #single char split (<,=)
- frags = re.findall(r'([a-zA-Z0-9_.]+)([><=])([^ -,\t\n\r\f\v]+)',
- string)
- return frags
-
- opts = []
- queries = cli_query.split(';')
- for q in queries:
- frag = split_by_op(q)
- if len(frag) > 1:
- raise ValueError('incorrect seperator %s in query "%s"' %
- ('(should be ";")', q))
- if len(frag) == 0:
- raise ValueError('invalid query %s' % q)
- query = frag[0]
- opt = {}
- opt['field'] = query[0]
- opt['op'] = op_lookup[query[1]]
- opt['value'] = query[2]
- opts.append(opt)
- return opts
-
-def meters_to_stats(meters):
- stats = DashboardStatistics()
- for m in meters:
- timestamp = m.duration_start
- stats['stat_list'].append({'timestamp':timestamp, 'value':m.sum})
- stats['sum']+=m.sum
- stats['average']+=m.sum
- stats['unit'] = 'ns'
-
- if (len(meters)):
- stats['average']/=len(meters)
- else:
- stats['average']=0
- return stats
-
-
-class CeilometerDriver(MonitorDriver):
- def get_meter(self, meter, obj, pk, keystone=None):
- if (not keystone):
- keystone={}
- keystone['os_username']=env['OS_USERNAME']
- keystone['os_password']=env['OS_PASSWORD']
- keystone['os_auth_url']=env['OS_AUTH_URL']
- keystone['os_tenant_name']=env['OS_TENANT_NAME']
- keystone['os_cacert']=env['OS_CACERT']
- keystone['os_region_name']=env['OS_REGION_NAME']
-
- keystone['username']=env['OS_USERNAME']
- keystone['password']=env['OS_PASSWORD']
- keystone['auth_url']=env['OS_AUTH_URL']
- keystone['tenant_name']=env['OS_TENANT_NAME']
- keystone['cacert']=env['OS_CACERT']
- keystone['region_name']=env['OS_REGION_NAME']
-
- keystone['auth_plugin']=client.AuthPlugin(**keystone)
-
- ceilometer = client.get_client(2,**keystone)
-
- cur_ts = datetime.datetime.fromtimestamp(time.time()-86400)
- str_ts = cur_ts.strftime('%Y-%m-%dT%H:%M:%S')
-
- object_filter = object_to_filter(obj, pk)
- filter=';'.join([object_filter,'timestamp>%s'%str_ts])
- #query = cli_to_array("project_id=124de34266b24f57957345cdb43cc9ff;timestamp>2014-12-11T00:00:00")
- query = cli_to_array(filter)
-
- meters = ceilometer.statistics.list(meter,q=query,period=3600)
-
- stats = meters_to_stats(meters)
- return stats
diff --git a/xos/openstack_observer/deleter.py b/xos/openstack_observer/deleter.py
deleted file mode 100644
index 93fa572..0000000
--- a/xos/openstack_observer/deleter.py
+++ /dev/null
@@ -1,16 +0,0 @@
-import os
-import base64
-from xos.config import Config
-
-class Deleter:
- model=None # Must be overridden
-
- def __init__(self, *args, **kwargs):
- pass
-
- def call(self, pk, model_dict):
- # Fetch object from XOS db and delete it
- pass
-
- def __call__(self, *args, **kwargs):
- return self.call(*args, **kwargs)
diff --git a/xos/openstack_observer/error_mapper.py b/xos/openstack_observer/error_mapper.py
deleted file mode 100644
index 3039a56..0000000
--- a/xos/openstack_observer/error_mapper.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from xos.config import Config
-from util.logger import Logger, logging, logger
-
-class ErrorMapper:
- def __init__(self, error_map_file):
- self.error_map = {}
- try:
- error_map_lines = open(error_map_file).read().splitlines()
- for l in error_map_lines:
- if (not l.startswith('#')):
- splits = l.split('->')
- k,v = map(lambda i:i.rstrip(),splits)
- self.error_map[k]=v
- except:
- logging.info('Could not read error map')
-
-
- def map(self, error):
- return self.error_map[error]
-
-
-
-
-
-
diff --git a/xos/openstack_observer/event_loop.py b/xos/openstack_observer/event_loop.py
deleted file mode 100644
index 0ac626b..0000000
--- a/xos/openstack_observer/event_loop.py
+++ /dev/null
@@ -1,527 +0,0 @@
-import os
-import imp
-import inspect
-import time
-import sys
-import traceback
-import commands
-import threading
-import json
-import pdb
-import pprint
-
-
-from datetime import datetime
-from collections import defaultdict
-from core.models import *
-from django.db.models import F, Q
-from django.db import connection
-from django.db import reset_queries
-#from openstack.manager import OpenStackManager
-from openstack.driver import OpenStackDriver
-from util.logger import Logger, logging, logger
-#from timeout import timeout
-from xos.config import Config, XOS_DIR
-from observer.steps import *
-from syncstep import SyncStep
-from toposort import toposort
-from observer.error_mapper import *
-from openstack_observer.openstacksyncstep import OpenStackSyncStep
-from observer.steps.sync_object import SyncObject
-
-# Load app models
-
-try:
- app_module_names = Config().observer_applist.split(',')
-except AttributeError:
- app_module_names = []
-
-if (type(app_module_names)!=list):
- app_module_names=[app_module_names]
-
-app_modules = []
-
-for m in app_module_names:
- model_path = m+'.models'
- module = __import__(model_path,fromlist=[m])
- app_modules.append(module)
-
-
-debug_mode = False
-
-class bcolors:
- HEADER = '\033[95m'
- OKBLUE = '\033[94m'
- OKGREEN = '\033[92m'
- WARNING = '\033[93m'
- FAIL = '\033[91m'
- ENDC = '\033[0m'
- BOLD = '\033[1m'
- UNDERLINE = '\033[4m'
-
-logger = Logger(level=logging.INFO)
-
-class StepNotReady(Exception):
- pass
-
-class NoOpDriver:
- def __init__(self):
- self.enabled = True
- self.dependency_graph = None
-
-STEP_STATUS_WORKING=1
-STEP_STATUS_OK=2
-STEP_STATUS_KO=3
-
-def invert_graph(g):
- ig = {}
- for k,v in g.items():
- for v0 in v:
- try:
- ig[v0].append(k)
- except:
- ig[v0]=[k]
- return ig
-
-class XOSObserver:
- sync_steps = []
-
-
- def __init__(self):
- # The Condition object that gets signalled by Feefie events
- self.step_lookup = {}
- self.load_sync_step_modules()
- self.load_sync_steps()
- self.event_cond = threading.Condition()
-
- self.driver_kind = getattr(Config(), "observer_driver", "openstack")
- self.observer_name = getattr(Config(), "observer_name", "")
- if self.driver_kind=="openstack":
- self.driver = OpenStackDriver()
- else:
- self.driver = NoOpDriver()
-
- def consolePrint(self, what):
- if getattr(Config(), "observer_console_print", True):
- print what
-
- def wait_for_event(self, timeout):
- self.event_cond.acquire()
- self.event_cond.wait(timeout)
- self.event_cond.release()
-
- def wake_up(self):
- logger.info('Wake up routine called. Event cond %r'%self.event_cond)
- self.event_cond.acquire()
- self.event_cond.notify()
- self.event_cond.release()
-
- def load_sync_step_modules(self, step_dir=None):
- if step_dir is None:
- if hasattr(Config(), "observer_steps_dir"):
- step_dir = Config().observer_steps_dir
- else:
- step_dir = XOS_DIR + "/observer/steps"
-
- for fn in os.listdir(step_dir):
- pathname = os.path.join(step_dir,fn)
- if os.path.isfile(pathname) and fn.endswith(".py") and (fn!="__init__.py"):
- module = imp.load_source(fn[:-3],pathname)
- for classname in dir(module):
- c = getattr(module, classname, None)
-
- # make sure 'c' is a descendent of SyncStep and has a
- # provides field (this eliminates the abstract base classes
- # since they don't have a provides)
-
- if inspect.isclass(c) and (issubclass(c, SyncStep) or issubclass(c,OpenStackSyncStep)) and hasattr(c,"provides") and (c not in self.sync_steps):
- self.sync_steps.append(c)
- logger.info('loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps]))
-
- def load_sync_steps(self):
- dep_path = Config().observer_dependency_graph
- logger.info('Loading model dependency graph from %s' % dep_path)
- try:
- # This contains dependencies between records, not sync steps
- self.model_dependency_graph = json.loads(open(dep_path).read())
- for left,lst in self.model_dependency_graph.items():
- new_lst = []
- for k in lst:
- try:
- tup = (k,k.lower())
- new_lst.append(tup)
- deps = self.model_dependency_graph[k]
- except:
- self.model_dependency_graph[k] = []
-
- self.model_dependency_graph[left] = new_lst
- except Exception,e:
- raise e
-
- try:
- backend_path = Config().observer_pl_dependency_graph
- logger.info('Loading backend dependency graph from %s' % backend_path)
- # This contains dependencies between backend records
- self.backend_dependency_graph = json.loads(open(backend_path).read())
- for k,v in self.backend_dependency_graph.items():
- try:
- self.model_dependency_graph[k].extend(v)
- except KeyError:
- self.model_dependency_graphp[k] = v
-
- except Exception,e:
- logger.info('Backend dependency graph not loaded')
- # We can work without a backend graph
- self.backend_dependency_graph = {}
-
- provides_dict = {}
- for s in self.sync_steps:
- self.step_lookup[s.__name__] = s
- for m in s.provides:
- try:
- provides_dict[m.__name__].append(s.__name__)
- except KeyError:
- provides_dict[m.__name__]=[s.__name__]
-
- step_graph = {}
- phantom_steps = []
- for k,v in self.model_dependency_graph.items():
- try:
- for source in provides_dict[k]:
- if (not v):
- step_graph[source] = []
-
- for m,_ in v:
- try:
- for dest in provides_dict[m]:
- # no deps, pass
- try:
- if (dest not in step_graph[source]):
- step_graph[source].append(dest)
- except:
- step_graph[source]=[dest]
- except KeyError:
- if (not provides_dict.has_key(m)):
- try:
- step_graph[source]+=['#%s'%m]
- except:
- step_graph[source]=['#%s'%m]
-
- phantom_steps+=['#%s'%m]
- pass
-
- except KeyError:
- pass
- # no dependencies, pass
-
-
- self.dependency_graph = step_graph
- self.deletion_dependency_graph = invert_graph(step_graph)
-
- pp = pprint.PrettyPrinter(indent=4)
- logger.info(pp.pformat(step_graph))
- self.ordered_steps = toposort(self.dependency_graph, phantom_steps+map(lambda s:s.__name__,self.sync_steps))
- self.ordered_steps = [i for i in self.ordered_steps if i!='SyncObject']
-
- logger.info("Order of steps=%s" % self.ordered_steps)
-
- self.load_run_times()
-
-
- def check_duration(self, step, duration):
- try:
- if (duration > step.deadline):
- logger.info('Sync step %s missed deadline, took %.2f seconds'%(step.name,duration))
- except AttributeError:
- # S doesn't have a deadline
- pass
-
- def update_run_time(self, step, deletion):
- if (not deletion):
- self.last_run_times[step.__name__]=time.time()
- else:
- self.last_deletion_run_times[step.__name__]=time.time()
-
-
- def check_schedule(self, step, deletion):
- last_run_times = self.last_run_times if not deletion else self.last_deletion_run_times
-
- time_since_last_run = time.time() - last_run_times.get(step.__name__, 0)
- try:
- if (time_since_last_run < step.requested_interval):
- raise StepNotReady
- except AttributeError:
- logger.info('Step %s does not have requested_interval set'%step.__name__)
- raise StepNotReady
-
- def load_run_times(self):
- try:
- jrun_times = open('/tmp/%sobserver_run_times'%self.observer_name).read()
- self.last_run_times = json.loads(jrun_times)
- except:
- self.last_run_times={}
- for e in self.ordered_steps:
- self.last_run_times[e]=0
- try:
- jrun_times = open('/tmp/%sobserver_deletion_run_times'%self.observer_name).read()
- self.last_deletion_run_times = json.loads(jrun_times)
- except:
- self.last_deletion_run_times={}
- for e in self.ordered_steps:
- self.last_deletion_run_times[e]=0
-
- def lookup_step_class(self,s):
- if ('#' in s):
- return SyncObject
- else:
- step = self.step_lookup[s]
- return step
-
- def lookup_step(self,s):
- if ('#' in s):
- objname = s[1:]
- so = SyncObject()
-
- try:
- obj = globals()[objname]
- except:
- for m in app_modules:
- if (hasattr(m,objname)):
- obj = getattr(m,objname)
-
- so.provides=[obj]
- so.observes=[obj]
- step = so
- else:
- step_class = self.step_lookup[s]
- step = step_class(driver=self.driver,error_map=self.error_mapper)
- return step
-
- def save_run_times(self):
- run_times = json.dumps(self.last_run_times)
- open('/tmp/%sobserver_run_times'%self.observer_name,'w').write(run_times)
-
- deletion_run_times = json.dumps(self.last_deletion_run_times)
- open('/tmp/%sobserver_deletion_run_times'%self.observer_name,'w').write(deletion_run_times)
-
- def check_class_dependency(self, step, failed_steps):
- step.dependenices = []
- for obj in step.provides:
- lst = self.model_dependency_graph.get(obj.__name__, [])
- nlst = map(lambda(a,b):b,lst)
- step.dependenices.extend(nlst)
- for failed_step in failed_steps:
- if (failed_step in step.dependencies):
- raise StepNotReady
-
- def sync(self, S, deletion):
- try:
- step = self.lookup_step_class(S)
- start_time=time.time()
-
- logger.info("Starting to work on step %s, deletion=%s" % (step.__name__, str(deletion)))
-
- dependency_graph = self.dependency_graph if not deletion else self.deletion_dependency_graph
- step_conditions = self.step_conditions# if not deletion else self.deletion_step_conditions
- step_status = self.step_status# if not deletion else self.deletion_step_status
-
- # Wait for step dependencies to be met
- try:
- deps = dependency_graph[S]
- has_deps = True
- except KeyError:
- has_deps = False
-
- go = True
-
- failed_dep = None
- if (has_deps):
- for d in deps:
- if d==step.__name__:
- logger.info(" step %s self-wait skipped" % step.__name__)
- go = True
- continue
-
- cond = step_conditions[d]
- cond.acquire()
- if (step_status[d] is STEP_STATUS_WORKING):
- logger.info(" step %s wait on dep %s" % (step.__name__, d))
- cond.wait()
- elif step_status[d] == STEP_STATUS_OK:
- go = True
- else:
- go = False
- failed_dep = d
- cond.release()
- if (not go):
- break
- else:
- go = True
-
- if (not go):
- self.consolePrint(bcolors.FAIL + "Step %r skipped on %r" % (step,failed_dep) + bcolors.ENDC)
- # SMBAKER: sync_step was not defined here, so I changed
- # this from 'sync_step' to 'step'. Verify.
- self.failed_steps.append(step)
- my_status = STEP_STATUS_KO
- else:
- sync_step = self.lookup_step(S)
- sync_step. __name__= step.__name__
- sync_step.dependencies = []
- try:
- mlist = sync_step.provides
-
- try:
- for m in mlist:
- lst = self.model_dependency_graph[m.__name__]
- nlst = map(lambda(a,b):b,lst)
- sync_step.dependencies.extend(nlst)
- except Exception,e:
- raise e
-
- except KeyError:
- pass
- sync_step.debug_mode = debug_mode
-
- should_run = False
- try:
- # Various checks that decide whether
- # this step runs or not
- self.check_class_dependency(sync_step, self.failed_steps) # dont run Slices if Sites failed
- self.check_schedule(sync_step, deletion) # dont run sync_network_routes if time since last run < 1 hour
- should_run = True
- except StepNotReady:
- logger.info('Step not ready: %s'%sync_step.__name__)
- self.failed_steps.append(sync_step)
- my_status = STEP_STATUS_KO
- except Exception,e:
- logger.error('%r' % e)
- logger.log_exc("sync step failed: %r. Deletion: %r"%(sync_step,deletion))
- self.failed_steps.append(sync_step)
- my_status = STEP_STATUS_KO
-
- if (should_run):
- try:
- duration=time.time() - start_time
-
- logger.info('Executing step %s, deletion=%s' % (sync_step.__name__, deletion))
-
- self.consolePrint(bcolors.OKBLUE + "Executing step %s" % sync_step.__name__ + bcolors.ENDC)
- failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion)
-
- self.check_duration(sync_step, duration)
-
- if failed_objects:
- self.failed_step_objects.update(failed_objects)
-
- logger.info("Step %r succeeded" % sync_step.__name__)
- self.consolePrint(bcolors.OKGREEN + "Step %r succeeded" % sync_step.__name__ + bcolors.ENDC)
- my_status = STEP_STATUS_OK
- self.update_run_time(sync_step,deletion)
- except Exception,e:
- self.consolePrint(bcolors.FAIL + "Model step %r failed" % (sync_step.__name__) + bcolors.ENDC)
- logger.error('Model step %r failed. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!' % (sync_step.__name__, e))
- logger.log_exc(e)
- self.failed_steps.append(S)
- my_status = STEP_STATUS_KO
- else:
- logger.info("Step %r succeeded due to non-run" % step)
- my_status = STEP_STATUS_OK
-
- try:
- my_cond = step_conditions[S]
- my_cond.acquire()
- step_status[S]=my_status
- my_cond.notify_all()
- my_cond.release()
- except KeyError,e:
- logger.info('Step %r is a leaf' % step)
- pass
- finally:
- try:
- reset_queries()
- except:
- # this shouldn't happen, but in case it does, catch it...
- logger.log_exc("exception in reset_queries")
-
- connection.close()
-
- def run(self):
- if not self.driver.enabled:
- return
-
- if (self.driver_kind=="openstack") and (not self.driver.has_openstack):
- return
-
- while True:
- logger.info('Waiting for event')
- self.wait_for_event(timeout=5)
- logger.info('Observer woke up')
-
- self.run_once()
-
- def run_once(self):
- try:
- loop_start = time.time()
- error_map_file = getattr(Config(), "error_map_path", XOS_DIR + "/error_map.txt")
- self.error_mapper = ErrorMapper(error_map_file)
-
- # Two passes. One for sync, the other for deletion.
- for deletion in [False,True]:
- # Set of individual objects within steps that failed
- self.failed_step_objects = set()
-
- # Set up conditions and step status
- # This is needed for steps to run in parallel
- # while obeying dependencies.
-
- providers = set()
- dependency_graph = self.dependency_graph if not deletion else self.deletion_dependency_graph
-
- for v in dependency_graph.values():
- if (v):
- providers.update(v)
-
- self.step_conditions = {}
- self.step_status = {}
-
- for p in list(providers):
- self.step_conditions[p] = threading.Condition()
-
- self.step_status[p] = STEP_STATUS_WORKING
-
- self.failed_steps = []
-
- threads = []
- logger.info('Deletion=%r...'%deletion)
- schedule = self.ordered_steps if not deletion else reversed(self.ordered_steps)
-
- for S in schedule:
- thread = threading.Thread(target=self.sync, args=(S, deletion))
-
- logger.info('Deletion=%r...'%deletion)
- threads.append(thread)
-
- # Start threads
- for t in threads:
- t.start()
-
- # another spot to clean up debug state
- try:
- reset_queries()
- except:
- # this shouldn't happen, but in case it does, catch it...
- logger.log_exc("exception in reset_queries")
-
- # Wait for all threads to finish before continuing with the run loop
- for t in threads:
- t.join()
-
- self.save_run_times()
-
- loop_end = time.time()
- open('/tmp/%sobserver_last_run'%self.observer_name,'w').write(json.dumps({'last_run': loop_end, 'last_duration':loop_end - loop_start}))
- except Exception, e:
- logger.error('Core error. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!' % e)
- logger.log_exc("Exception in observer run loop")
- traceback.print_exc()
diff --git a/xos/openstack_observer/steps/purge_disabled_users.py b/xos/openstack_observer/steps/purge_disabled_users.py
deleted file mode 100644
index b5168e3..0000000
--- a/xos/openstack_observer/steps/purge_disabled_users.py
+++ /dev/null
@@ -1,25 +0,0 @@
-import os
-import base64
-import datetime
-from django.db.models import F, Q
-from xos.config import Config
-from observer.openstacksyncstep import OpenStackSyncStep
-from core.models.user import User
-from util.logger import observer_logger as logger
-
-class SyncRoles(OpenStackSyncStep):
- provides=[User]
- requested_interval=0
- observes=User
-
- def fetch_pending(self, deleted):
- if (deleted):
- # users marked as deleted
- return User.deleted_objects.all()
- else:
- # disabled users that haven't been updated in over a week
- one_week_ago = datetime.datetime.now() - datetime.timedelta(days=7)
- return User.objects.filter(is_active=False, updated__gt=one_week_ago)
-
- def sync_record(self, user):
- user.delete()
diff --git a/xos/openstack_observer/steps/sync_container.py b/xos/openstack_observer/steps/sync_container.py
deleted file mode 100644
index adb81c9..0000000
--- a/xos/openstack_observer/steps/sync_container.py
+++ /dev/null
@@ -1,163 +0,0 @@
-import hashlib
-import os
-import socket
-import sys
-import base64
-import time
-from django.db.models import F, Q
-from xos.config import Config
-from observers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
-from observer.syncstep import SyncStep, DeferredException
-from observer.ansible import run_template_ssh
-from core.models import Service, Slice, Instance
-from services.onos.models import ONOSService, ONOSApp
-from util.logger import Logger, logging
-
-# hpclibrary will be in steps/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-logger = Logger(level=logging.INFO)
-
-class SyncContainer(SyncInstanceUsingAnsible):
- provides=[Instance]
- observes=Instance
- requested_interval=0
- template_name = "sync_container.yaml"
-
- def __init__(self, *args, **kwargs):
- super(SyncContainer, self).__init__(*args, **kwargs)
-
- def fetch_pending(self, deletion=False):
- objs = super(SyncContainer, self).fetch_pending(deletion)
- objs = [x for x in objs if x.isolation in ["container", "container_vm"]]
- return objs
-
- def get_instance_port(self, container_port):
- for p in container_port.network.links.all():
- if (p.instance) and (p.instance.isolation=="vm") and (p.instance.node == container_port.instance.node) and (p.mac):
- return p
- return None
-
- def get_parent_port_mac(self, instance, port):
- if not instance.parent:
- raise Exception("instance has no parent")
- for parent_port in instance.parent.ports.all():
- if parent_port.network == port.network:
- if not parent_port.mac:
- raise DeferredException("parent port on network %s does not have mac yet" % parent_port.network.name)
- return parent_port.mac
- raise Exception("failed to find corresponding parent port for network %s" % port.network.name)
-
- def get_ports(self, o):
- i=0
- ports = []
- if (o.slice.network in ["host", "bridged"]):
- pass # no ports in host or bridged mode
- else:
- for port in o.ports.all():
- if (not port.ip):
- # 'unmanaged' ports may have an ip, but no mac
- # XXX: are there any ports that have a mac but no ip?
- raise DeferredException("Port on network %s is not yet ready" % port.network.name)
-
- pd={}
- pd["mac"] = port.mac or ""
- pd["ip"] = port.ip or ""
- pd["xos_network_id"] = port.network.id
-
- if port.network.name == "wan_network":
- if port.ip:
- (a, b, c, d) = port.ip.split('.')
- pd["mac"] = "02:42:%02x:%02x:%02x:%02x" % (int(a), int(b), int(c), int(d))
-
-
- if o.isolation == "container":
- # container on bare metal
- instance_port = self.get_instance_port(port)
- if not instance_port:
- raise DeferredException("No instance on slice for port on network %s" % port.network.name)
-
- pd["snoop_instance_mac"] = instance_port.mac
- pd["snoop_instance_id"] = instance_port.instance.instance_id
- pd["src_device"] = ""
- pd["bridge"] = "br-int"
- else:
- # container in VM
- pd["snoop_instance_mac"] = ""
- pd["snoop_instance_id"] = ""
- pd["parent_mac"] = self.get_parent_port_mac(o, port)
- pd["bridge"] = ""
-
- for (k,v) in port.get_parameters().items():
- pd[k] = v
-
- ports.append(pd)
-
- # for any ports that don't have a device, assign one
- used_ports = [x["device"] for x in ports if ("device" in x)]
- avail_ports = ["eth%d"%i for i in range(0,64) if ("eth%d"%i not in used_ports)]
- for port in ports:
- if not port.get("device",None):
- port["device"] = avail_ports.pop(0)
-
- return ports
-
- def get_extra_attributes(self, o):
- fields={}
- fields["ansible_tag"] = "container-%s" % str(o.id)
- if o.image.tag:
- fields["docker_image"] = o.image.path + ":" + o.image.tag
- else:
- fields["docker_image"] = o.image.path
- fields["ports"] = self.get_ports(o)
- if o.volumes:
- fields["volumes"] = [x.strip() for x in o.volumes.split(",")]
- else:
- fields["volumes"] = ""
- fields["network_method"] = o.slice.network or "default"
- return fields
-
- def sync_record(self, o):
- logger.info("sync'ing object %s" % str(o))
-
- fields = self.get_ansible_fields(o)
-
- # If 'o' defines a 'sync_attributes' list, then we'll copy those
- # attributes into the Ansible recipe's field list automatically.
- if hasattr(o, "sync_attributes"):
- for attribute_name in o.sync_attributes:
- fields[attribute_name] = getattr(o, attribute_name)
-
- fields.update(self.get_extra_attributes(o))
-
- self.run_playbook(o, fields)
-
- o.instance_id = fields["container_name"]
- o.instance_name = fields["container_name"]
-
- o.save()
-
- def delete_record(self, o):
- logger.info("delete'ing object %s" % str(o))
-
- fields = self.get_ansible_fields(o)
-
- # If 'o' defines a 'sync_attributes' list, then we'll copy those
- # attributes into the Ansible recipe's field list automatically.
- if hasattr(o, "sync_attributes"):
- for attribute_name in o.sync_attributes:
- fields[attribute_name] = getattr(o, attribute_name)
-
- fields.update(self.get_extra_attributes(o))
-
- self.run_playbook(o, fields, "teardown_container.yaml")
-
- def run_playbook(self, o, fields, template_name=None):
- if not template_name:
- template_name = self.template_name
- tStart = time.time()
- run_template_ssh(template_name, fields, path="container")
- logger.info("playbook execution time %d" % int(time.time()-tStart))
-
-
diff --git a/xos/openstack_observer/steps/sync_controller_images.py b/xos/openstack_observer/steps/sync_controller_images.py
deleted file mode 100644
index 551d9ac..0000000
--- a/xos/openstack_observer/steps/sync_controller_images.py
+++ /dev/null
@@ -1,44 +0,0 @@
-import os
-import base64
-from collections import defaultdict
-from django.db.models import F, Q
-from xos.config import Config
-from observer.openstacksyncstep import OpenStackSyncStep
-from observer.syncstep import *
-from core.models import Controller
-from core.models import Image, ControllerImages
-from util.logger import observer_logger as logger
-from observer.ansible import *
-import json
-
-class SyncControllerImages(OpenStackSyncStep):
- provides=[ControllerImages]
- observes = ControllerImages
- requested_interval=0
- playbook='sync_controller_images.yaml'
-
- def fetch_pending(self, deleted):
- if (deleted):
- return []
-
- # now we return all images that need to be enacted
- return ControllerImages.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
-
- def map_sync_inputs(self, controller_image):
- image_fields = {'endpoint':controller_image.controller.auth_url,
- 'endpoint_v3': controller_image.controller.auth_url_v3,
- 'admin_user':controller_image.controller.admin_user,
- 'admin_password':controller_image.controller.admin_password,
- 'domain': controller_image.controller.domain,
- 'name':controller_image.image.name,
- 'filepath':controller_image.image.path,
- 'ansible_tag': '%s@%s'%(controller_image.image.name,controller_image.controller.name), # name of ansible playbook
- }
-
- return image_fields
-
- def map_sync_outputs(self, controller_image, res):
- image_id = res[0]['id']
- controller_image.glance_image_id = image_id
- controller_image.backend_status = '1 - OK'
- controller_image.save()
diff --git a/xos/openstack_observer/steps/sync_controller_networks.py b/xos/openstack_observer/steps/sync_controller_networks.py
deleted file mode 100644
index b646936..0000000
--- a/xos/openstack_observer/steps/sync_controller_networks.py
+++ /dev/null
@@ -1,122 +0,0 @@
-import os
-import base64
-from collections import defaultdict
-from netaddr import IPAddress, IPNetwork
-from django.db.models import F, Q
-from xos.config import Config
-from observer.openstacksyncstep import OpenStackSyncStep
-from observer.syncstep import *
-from core.models.network import *
-from core.models.slice import *
-from core.models.instance import Instance
-from util.logger import observer_logger as logger
-from observer.ansible import *
-from openstack.driver import OpenStackDriver
-import json
-
-import pdb
-
-class SyncControllerNetworks(OpenStackSyncStep):
- requested_interval = 0
- provides=[Network]
- observes=ControllerNetwork
- playbook='sync_controller_networks.yaml'
-
- def alloc_subnet(self, uuid):
- # 16 bits only
- uuid_masked = uuid & 0xffff
- a = 10
- b = uuid_masked >> 8
- c = uuid_masked & 0xff
- d = 0
-
- cidr = '%d.%d.%d.%d/24'%(a,b,c,d)
- return cidr
-
-
- def save_controller_network(self, controller_network):
- network_name = controller_network.network.name
- subnet_name = '%s-%d'%(network_name,controller_network.pk)
- cidr = self.alloc_subnet(controller_network.pk)
- self.cidr=cidr
- slice = controller_network.network.owner
-
- network_fields = {'endpoint':controller_network.controller.auth_url,
- 'endpoint_v3': controller_network.controller.auth_url_v3,
- 'admin_user':slice.creator.email,
- 'tenant_name':slice.name,
- 'admin_password':slice.creator.remote_password,
- 'domain': controller_network.controller.domain,
- 'name':network_name,
- 'subnet_name':subnet_name,
- 'ansible_tag':'%s-%s@%s'%(network_name,slice.slicename,controller_network.controller.name),
- 'cidr':cidr,
- 'delete':False
- }
- return network_fields
-
- def map_sync_outputs(self, controller_network,res):
- network_id = res[0]['id']
- subnet_id = res[1]['id']
- controller_network.net_id = network_id
- controller_network.subnet = self.cidr
- controller_network.subnet_id = subnet_id
- controller_network.backend_status = '1 - OK'
- controller_network.save()
-
-
- def map_sync_inputs(self, controller_network):
- # XXX This check should really be made from booleans, rather than using hardcoded network names
- if (controller_network.network.template.name not in ['Private', 'Private-Indirect', 'Private-Direct']):
- logger.info("skipping network controller %s because it is not private" % controller_network)
- # We only sync private networks
- return SyncStep.SYNC_WITHOUT_RUNNING
-
- if not controller_network.controller.admin_user:
- logger.info("controller %r has no admin_user, skipping" % controller_network.controller)
- return
-
- if controller_network.network.owner and controller_network.network.owner.creator:
- return self.save_controller_network(controller_network)
- else:
- raise Exception('Could not save network controller %s'%controller_network)
-
- def map_delete_inputs(self, controller_network):
- # XXX This check should really be made from booleans, rather than using hardcoded network names
- if (controller_network.network.template.name not in ['Private', 'Private-Indirect', 'Private-Direct']):
- # We only sync private networks
- return
- try:
- slice = controller_network.network.owner # XXX: FIXME!!
- except:
- raise Exception('Could not get slice for Network %s'%controller_network.network.name)
-
- network_name = controller_network.network.name
- subnet_name = '%s-%d'%(network_name,controller_network.pk)
- cidr = controller_network.subnet
- network_fields = {'endpoint':controller_network.controller.auth_url,
- 'admin_user':slice.creator.email, # XXX: FIXME
- 'tenant_name':slice.name, # XXX: FIXME
- 'admin_password':slice.creator.remote_password,
- 'name':network_name,
- 'subnet_name':subnet_name,
- 'ansible_tag':'%s-%s@%s'%(network_name,slice.slicename,controller_network.controller.name),
- 'cidr':cidr,
- 'delete':True
- }
-
- return network_fields
-
- """
- driver = OpenStackDriver().client_driver(caller=controller_network.network.owner.creator,
- tenant=controller_network.network.owner.name,
- controller=controller_network.controller.name)
- if (controller_network.router_id) and (controller_network.subnet_id):
- driver.delete_router_interface(controller_network.router_id, controller_network.subnet_id)
- if controller_network.subnet_id:
- driver.delete_subnet(controller_network.subnet_id)
- if controller_network.router_id:
- driver.delete_router(controller_network.router_id)
- if controller_network.net_id:
- driver.delete_network(controller_network.net_id)
- """
diff --git a/xos/openstack_observer/steps/sync_controller_networks.yaml b/xos/openstack_observer/steps/sync_controller_networks.yaml
deleted file mode 100644
index bbf8ec2..0000000
--- a/xos/openstack_observer/steps/sync_controller_networks.yaml
+++ /dev/null
@@ -1,35 +0,0 @@
----
-- hosts: 127.0.0.1
- connection: local
- tasks:
- - quantum_network:
- auth_url={{ endpoint }}
- login_username={{ admin_user }}
- login_tenant_name={{ tenant_name }}
- login_password={{ admin_password }}
- tenant_name={{ tenant_name }}
- name={{ name }}
- {% if delete %}
- state=absent
- {% else %}
- state=present
- {% endif %}
- shared=true
- {% if not delete %}
- - quantum_subnet:
- auth_url={{ endpoint }}
- login_username={{ admin_user }}
- login_tenant_name={{ tenant_name }}
- login_password={{ admin_password }}
- tenant_name={{ tenant_name }}
- name={{ subnet_name }}
- network_name={{ name }}
- {% if delete %}
- state=absent
- {% else %}
- state=present
- no_gateway=true
- dns_nameservers=8.8.8.8
- cidr={{ cidr }}
- {% endif %}
- {% endif %}
diff --git a/xos/openstack_observer/steps/sync_controller_site_privileges.py b/xos/openstack_observer/steps/sync_controller_site_privileges.py
deleted file mode 100644
index d257536..0000000
--- a/xos/openstack_observer/steps/sync_controller_site_privileges.py
+++ /dev/null
@@ -1,84 +0,0 @@
-import os
-import base64
-from collections import defaultdict
-from django.db.models import F, Q
-from xos.config import Config
-from observer.openstacksyncstep import OpenStackSyncStep
-from observer.syncstep import *
-from core.models.site import Controller, SitePrivilege
-from core.models.user import User
-from core.models.controlleruser import ControllerUser, ControllerSitePrivilege
-from util.logger import observer_logger as logger
-from observer.ansible import *
-import json
-
-class SyncControllerSitePrivileges(OpenStackSyncStep):
- provides=[SitePrivilege]
- requested_interval=0
- observes=ControllerSitePrivilege
- playbook='sync_controller_users.yaml'
-
- def map_sync_inputs(self, controller_site_privilege):
- controller_register = json.loads(controller_site_privilege.controller.backend_register)
- if not controller_site_privilege.controller.admin_user:
- logger.info("controller %r has no admin_user, skipping" % controller_site_privilege.controller)
- return
-
- roles = [controller_site_privilege.site_privilege.role.role]
- # setup user home site roles at controller
- if not controller_site_privilege.site_privilege.user.site:
- raise Exception('Siteless user %s'%controller_site_privilege.site_privilege.user.email)
- else:
- # look up tenant id for the user's site at the controller
- #ctrl_site_deployments = SiteDeployment.objects.filter(
- # site_deployment__site=controller_site_privilege.user.site,
- # controller=controller_site_privilege.controller)
-
- #if ctrl_site_deployments:
- # # need the correct tenant id for site at the controller
- # tenant_id = ctrl_site_deployments[0].tenant_id
- # tenant_name = ctrl_site_deployments[0].site_deployment.site.login_base
- user_fields = {
- 'endpoint':controller_site_privilege.controller.auth_url,
- 'endpoint_v3': controller_site_privilege.controller.auth_url_v3,
- 'domain': controller_site_privilege.controller.domain,
- 'name': controller_site_privilege.site_privilege.user.email,
- 'email': controller_site_privilege.site_privilege.user.email,
- 'password': controller_site_privilege.site_privilege.user.remote_password,
- 'admin_user': controller_site_privilege.controller.admin_user,
- 'admin_password': controller_site_privilege.controller.admin_password,
- 'ansible_tag':'%s@%s'%(controller_site_privilege.site_privilege.user.email.replace('@','-at-'),controller_site_privilege.controller.name),
- 'admin_tenant': controller_site_privilege.controller.admin_tenant,
- 'roles':roles,
- 'tenant':controller_site_privilege.site_privilege.site.login_base}
-
- return user_fields
-
- def map_sync_outputs(self, controller_site_privilege, res):
- # results is an array in which each element corresponds to an
- # "ok" string received per operation. If we get as many oks as
- # the number of operations we issued, that means a grand success.
- # Otherwise, the number of oks tell us which operation failed.
- controller_site_privilege.role_id = res[0]['id']
- controller_site_privilege.save()
-
- def delete_record(self, controller_site_privilege):
- controller_register = json.loads(controller_site_privilege.controller.backend_register)
- if (controller_register.get('disabled',False)):
- raise InnocuousException('Controller %s is disabled'%controller_site_privilege.controller.name)
-
- if controller_site_privilege.role_id:
- driver = self.driver.admin_driver(controller=controller_site_privilege.controller)
- user = ControllerUser.objects.get(
- controller=controller_site_privilege.controller,
- user=controller_site_privilege.site_privilege.user
- )
- site = ControllerSite.objects.get(
- controller=controller_site_privilege.controller,
- user=controller_site_privilege.site_privilege.user
- )
- driver.delete_user_role(
- user.kuser_id,
- site.tenant_id,
- controller_site_privilege.site_prvilege.role.role
- )
diff --git a/xos/openstack_observer/steps/sync_controller_sites.py b/xos/openstack_observer/steps/sync_controller_sites.py
deleted file mode 100644
index 614d435..0000000
--- a/xos/openstack_observer/steps/sync_controller_sites.py
+++ /dev/null
@@ -1,67 +0,0 @@
-import os
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from openstack_observer.openstacksyncstep import OpenStackSyncStep
-from core.models.site import *
-from observer.syncstep import *
-from observer.ansible import *
-from util.logger import observer_logger as logger
-import json
-
-class SyncControllerSites(OpenStackSyncStep):
- requested_interval=0
- provides=[Site]
- observes=ControllerSite
- playbook = 'sync_controller_sites.yaml'
-
- def fetch_pending(self, deleted=False):
- lobjs = ControllerSite.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False),Q(controller__isnull=False))
- return lobjs
-
- def map_sync_inputs(self, controller_site):
- tenant_fields = {'endpoint':controller_site.controller.auth_url,
- 'endpoint_v3': controller_site.controller.auth_url_v3,
- 'domain': controller_site.controller.domain,
- 'admin_user': controller_site.controller.admin_user,
- 'admin_password': controller_site.controller.admin_password,
- 'admin_tenant': controller_site.controller.admin_tenant,
- 'ansible_tag': '%s@%s'%(controller_site.site.login_base,controller_site.controller.name), # name of ansible playbook
- 'tenant': controller_site.site.login_base,
- 'tenant_description': controller_site.site.name}
- return tenant_fields
-
- def map_sync_outputs(self, controller_site, res):
- controller_site.tenant_id = res[0]['id']
- controller_site.backend_status = '1 - OK'
- controller_site.save()
-
- def delete_record(self, controller_site):
- controller_register = json.loads(controller_site.controller.backend_register)
- if (controller_register.get('disabled',False)):
- raise InnocuousException('Controller %s is disabled'%controller_site.controller.name)
-
- if controller_site.tenant_id:
- driver = self.driver.admin_driver(controller=controller_site.controller)
- driver.delete_tenant(controller_site.tenant_id)
-
- """
- Ansible does not support tenant deletion yet
-
- import pdb
- pdb.set_trace()
- template = os_template_env.get_template('delete_controller_sites.yaml')
- tenant_fields = {'endpoint':controller_site.controller.auth_url,
- 'admin_user': controller_site.controller.admin_user,
- 'admin_password': controller_site.controller.admin_password,
- 'admin_tenant': 'admin',
- 'ansible_tag': 'controller_sites/%s@%s'%(controller_site.controller_site.site.login_base,controller_site.controller_site.deployment.name), # name of ansible playbook
- 'tenant': controller_site.controller_site.site.login_base,
- 'delete': True}
-
- rendered = template.render(tenant_fields)
- res = run_template('sync_controller_sites.yaml', tenant_fields)
-
- if (len(res)!=1):
- raise Exception('Could not assign roles for user %s'%tenant_fields['tenant'])
- """
diff --git a/xos/openstack_observer/steps/sync_controller_slice_privileges.py b/xos/openstack_observer/steps/sync_controller_slice_privileges.py
deleted file mode 100644
index 948ea57..0000000
--- a/xos/openstack_observer/steps/sync_controller_slice_privileges.py
+++ /dev/null
@@ -1,79 +0,0 @@
-import os
-import base64
-from collections import defaultdict
-from django.db.models import F, Q
-from xos.config import Config
-from observer.openstacksyncstep import OpenStackSyncStep
-from observer.syncstep import *
-from core.models.slice import Controller, SlicePrivilege
-from core.models.user import User
-from core.models.controlleruser import ControllerUser, ControllerSlicePrivilege
-from observer.ansible import *
-from util.logger import observer_logger as logger
-import json
-
-class SyncControllerSlicePrivileges(OpenStackSyncStep):
- provides=[SlicePrivilege]
- requested_interval=0
- observes=ControllerSlicePrivilege
- playbook = 'sync_controller_users.yaml'
-
- def map_inputs(self, controller_slice_privilege):
- if not controller_slice_privilege.controller.admin_user:
- logger.info("controller %r has no admin_user, skipping" % controller_slice_privilege.controller)
- return
-
- template = os_template_env.get_template('sync_controller_users.yaml')
- roles = [controller_slice_privilege.slice_privilege.role.role]
- # setup user home slice roles at controller
- if not controller_slice_privilege.slice_privilege.user.site:
- raise Exception('Sliceless user %s'%controller_slice_privilege.slice_privilege.user.email)
- else:
- # look up tenant id for the user's slice at the controller
- #ctrl_slice_deployments = SliceDeployment.objects.filter(
- # slice_deployment__slice=controller_slice_privilege.user.slice,
- # controller=controller_slice_privilege.controller)
-
- #if ctrl_slice_deployments:
- # # need the correct tenant id for slice at the controller
- # tenant_id = ctrl_slice_deployments[0].tenant_id
- # tenant_name = ctrl_slice_deployments[0].slice_deployment.slice.login_base
- user_fields = {
- 'endpoint':controller_slice_privilege.controller.auth_url,
- 'endpoint_v3': controller_slice_privilege.controller.auth_url_v3,
- 'domain': controller_slice_privilege.controller.domain,
- 'name': controller_slice_privilege.slice_privilege.user.email,
- 'email': controller_slice_privilege.slice_privilege.user.email,
- 'password': controller_slice_privilege.slice_privilege.user.remote_password,
- 'admin_user': controller_slice_privilege.controller.admin_user,
- 'admin_password': controller_slice_privilege.controller.admin_password,
- 'ansible_tag':'%s@%s@%s'%(controller_slice_privilege.slice_privilege.user.email.replace('@','-at-'),controller_slice_privilege.slice_privilege.slice.name,controller_slice_privilege.controller.name),
- 'admin_tenant': controller_slice_privilege.controller.admin_tenant,
- 'roles':roles,
- 'tenant':controller_slice_privilege.slice_privilege.slice.name}
- return user_fields
-
- def map_sync_outputs(self, controller_slice_privilege, res):
- controller_slice_privilege.role_id = res[0]['id']
- controller_slice_privilege.save()
-
- def delete_record(self, controller_slice_privilege):
- controller_register = json.loads(controller_slice_privilege.controller.backend_register)
- if (controller_register.get('disabled',False)):
- raise InnocuousException('Controller %s is disabled'%controller_slice_privilege.controller.name)
-
- if controller_slice_privilege.role_id:
- driver = self.driver.admin_driver(controller=controller_slice_privilege.controller)
- user = ControllerUser.objects.get(
- controller=controller_slice_privilege.controller,
- user=controller_slice_privilege.slice_privilege.user
- )
- slice = ControllerSlice.objects.get(
- controller=controller_slice_privilege.controller,
- user=controller_slice_privilege.slice_privilege.user
- )
- driver.delete_user_role(
- user.kuser_id,
- slice.tenant_id,
- controller_slice_privilege.slice_prvilege.role.role
- )
diff --git a/xos/openstack_observer/steps/sync_controller_slices.py b/xos/openstack_observer/steps/sync_controller_slices.py
deleted file mode 100644
index 9904aef..0000000
--- a/xos/openstack_observer/steps/sync_controller_slices.py
+++ /dev/null
@@ -1,84 +0,0 @@
-import os
-import base64
-from collections import defaultdict
-from netaddr import IPAddress, IPNetwork
-from django.db.models import F, Q
-from xos.config import Config
-from observer.openstacksyncstep import OpenStackSyncStep
-from observer.syncstep import *
-from core.models import *
-from observer.ansible import *
-from openstack.driver import OpenStackDriver
-from util.logger import observer_logger as logger
-import json
-
-class SyncControllerSlices(OpenStackSyncStep):
- provides=[Slice]
- requested_interval=0
- observes=ControllerSlice
- playbook='sync_controller_slices.yaml'
-
- def map_sync_inputs(self, controller_slice):
- logger.info("sync'ing slice controller %s" % controller_slice)
-
- if not controller_slice.controller.admin_user:
- logger.info("controller %r has no admin_user, skipping" % controller_slice.controller)
- return
-
- controller_users = ControllerUser.objects.filter(user=controller_slice.slice.creator,
- controller=controller_slice.controller)
- if not controller_users:
- raise Exception("slice createor %s has not accout at controller %s" % (controller_slice.slice.creator, controller_slice.controller.name))
- else:
- controller_user = controller_users[0]
- roles = ['admin']
-
- max_instances=int(controller_slice.slice.max_instances)
- tenant_fields = {'endpoint':controller_slice.controller.auth_url,
- 'endpoint_v3': controller_slice.controller.auth_url_v3,
- 'domain': controller_slice.controller.domain,
- 'admin_user': controller_slice.controller.admin_user,
- 'admin_password': controller_slice.controller.admin_password,
- 'admin_tenant': 'admin',
- 'tenant': controller_slice.slice.name,
- 'tenant_description': controller_slice.slice.description,
- 'roles':roles,
- 'name':controller_user.user.email,
- 'ansible_tag':'%s@%s'%(controller_slice.slice.name,controller_slice.controller.name),
- 'max_instances':max_instances}
-
- return tenant_fields
-
- def map_sync_outputs(self, controller_slice, res):
- tenant_id = res[0]['id']
- if (not controller_slice.tenant_id):
- try:
- driver = OpenStackDriver().admin_driver(controller=controller_slice.controller)
- driver.shell.nova.quotas.update(tenant_id=tenant_id, instances=int(controller_slice.slice.max_instances))
- except:
- logger.log_exc('Could not update quota for %s'%controller_slice.slice.name)
- raise Exception('Could not update quota for %s'%controller_slice.slice.name)
-
- controller_slice.tenant_id = tenant_id
- controller_slice.backend_status = '1 - OK'
- controller_slice.save()
-
-
- def map_delete_inputs(self, controller_slice):
- controller_users = ControllerUser.objects.filter(user=controller_slice.slice.creator,
- controller=controller_slice.controller)
- if not controller_users:
- raise Exception("slice createor %s has not accout at controller %s" % (controller_slice.slice.creator, controller_slice.controller.name))
- else:
- controller_user = controller_users[0]
-
- tenant_fields = {'endpoint':controller_slice.controller.auth_url,
- 'admin_user': controller_slice.controller.admin_user,
- 'admin_password': controller_slice.controller.admin_password,
- 'admin_tenant': 'admin',
- 'tenant': controller_slice.slice.name,
- 'tenant_description': controller_slice.slice.description,
- 'name':controller_user.user.email,
- 'ansible_tag':'%s@%s'%(controller_slice.slice.name,controller_slice.controller.name),
- 'delete': True}
- return tenant_fields
diff --git a/xos/openstack_observer/steps/sync_controller_users.py b/xos/openstack_observer/steps/sync_controller_users.py
deleted file mode 100644
index 4062453..0000000
--- a/xos/openstack_observer/steps/sync_controller_users.py
+++ /dev/null
@@ -1,69 +0,0 @@
-import os
-import base64
-from collections import defaultdict
-from django.db.models import F, Q
-from xos.config import Config
-from observer.openstacksyncstep import OpenStackSyncStep
-from observer.syncstep import *
-from core.models.site import Controller, SiteDeployment, SiteDeployment
-from core.models.user import User
-from core.models.controlleruser import ControllerUser
-from observer.ansible import *
-from util.logger import observer_logger as logger
-import json
-
-class SyncControllerUsers(OpenStackSyncStep):
- provides=[User]
- requested_interval=0
- observes=ControllerUser
- playbook='sync_controller_users.yaml'
-
- def map_sync_inputs(self, controller_user):
- if not controller_user.controller.admin_user:
- logger.info("controller %r has no admin_user, skipping" % controller_user.controller)
- return
-
- # All users will have at least the 'user' role at their home site/tenant.
- # We must also check if the user should have the admin role
- roles = ['user']
- if controller_user.user.is_admin:
- roles.append('admin')
-
- # setup user home site roles at controller
- if not controller_user.user.site:
- raise Exception('Siteless user %s'%controller_user.user.email)
- else:
- # look up tenant id for the user's site at the controller
- #ctrl_site_deployments = SiteDeployment.objects.filter(
- # site_deployment__site=controller_user.user.site,
- # controller=controller_user.controller)
-
- #if ctrl_site_deployments:
- # # need the correct tenant id for site at the controller
- # tenant_id = ctrl_site_deployments[0].tenant_id
- # tenant_name = ctrl_site_deployments[0].site_deployment.site.login_base
- user_fields = {
- 'endpoint':controller_user.controller.auth_url,
- 'endpoint_v3': controller_user.controller.auth_url_v3,
- 'domain': controller_user.controller.domain,
- 'name': controller_user.user.email,
- 'email': controller_user.user.email,
- 'password': controller_user.user.remote_password,
- 'admin_user': controller_user.controller.admin_user,
- 'admin_password': controller_user.controller.admin_password,
- 'ansible_tag':'%s@%s'%(controller_user.user.email.replace('@','-at-'),controller_user.controller.name),
- 'admin_tenant': controller_user.controller.admin_tenant,
- 'roles':roles,
- 'tenant':controller_user.user.site.login_base
- }
- return user_fields
-
- def map_sync_outputs(self, controller_user, res):
- controller_user.kuser_id = res[0]['id']
- controller_user.backend_status = '1 - OK'
- controller_user.save()
-
- def delete_record(self, controller_user):
- if controller_user.kuser_id:
- driver = self.driver.admin_driver(controller=controller_user.controller)
- driver.delete_user(controller_user.kuser_id)
diff --git a/xos/openstack_observer/steps/sync_images.py b/xos/openstack_observer/steps/sync_images.py
deleted file mode 100644
index d126834..0000000
--- a/xos/openstack_observer/steps/sync_images.py
+++ /dev/null
@@ -1,52 +0,0 @@
-import os
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from observer.openstacksyncstep import OpenStackSyncStep
-from core.models.image import Image
-from util.logger import observer_logger as logger
-
-class SyncImages(OpenStackSyncStep):
- provides=[Image]
- requested_interval=0
- observes=Image
-
- def fetch_pending(self, deleted):
- # Images come from the back end
- # You can't delete them
- if (deleted):
- logger.info("SyncImages: returning because deleted=True")
- return []
-
- # get list of images on disk
- images_path = Config().observer_images_directory
-
- logger.info("SyncImages: deleted=False, images_path=%s" % images_path)
-
- available_images = {}
- if os.path.exists(images_path):
- for f in os.listdir(images_path):
- filename = os.path.join(images_path, f)
- if os.path.isfile(filename):
- available_images[f] = filename
-
- logger.info("SyncImages: available_images = %s" % str(available_images))
-
- images = Image.objects.all()
- image_names = [image.name for image in images]
-
- for image_name in available_images:
- #remove file extension
- clean_name = ".".join(image_name.split('.')[:-1])
- if clean_name not in image_names:
- logger.info("SyncImages: adding %s" % clean_name)
- image = Image(name=clean_name,
- disk_format='raw',
- container_format='bare',
- path = available_images[image_name])
- image.save()
-
- return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
-
- def sync_record(self, image):
- image.save()
diff --git a/xos/openstack_observer/steps/sync_instances.py b/xos/openstack_observer/steps/sync_instances.py
deleted file mode 100644
index 815c83e..0000000
--- a/xos/openstack_observer/steps/sync_instances.py
+++ /dev/null
@@ -1,174 +0,0 @@
-import os
-import base64
-import socket
-from django.db.models import F, Q
-from xos.config import Config
-from xos.settings import RESTAPI_HOSTNAME, RESTAPI_PORT
-from observer.openstacksyncstep import OpenStackSyncStep
-from core.models.instance import Instance
-from core.models.slice import Slice, SlicePrivilege, ControllerSlice
-from core.models.network import Network, NetworkSlice, ControllerNetwork
-from observer.ansible import *
-from observer.syncstep import *
-from util.logger import observer_logger as logger
-
-def escape(s):
- s = s.replace('\n',r'\n').replace('"',r'\"')
- return s
-
-class SyncInstances(OpenStackSyncStep):
- provides=[Instance]
- requested_interval=0
- observes=Instance
- playbook='sync_instances.yaml'
-
- def fetch_pending(self, deletion=False):
- objs = super(SyncInstances, self).fetch_pending(deletion)
- objs = [x for x in objs if x.isolation=="vm"]
- return objs
-
- def get_userdata(self, instance, pubkeys):
- userdata = '#cloud-config\n\nopencloud:\n slicename: "%s"\n hostname: "%s"\n restapi_hostname: "%s"\n restapi_port: "%s"\n' % (instance.slice.name, instance.node.name, RESTAPI_HOSTNAME, str(RESTAPI_PORT))
- userdata += 'ssh_authorized_keys:\n'
- for key in pubkeys:
- userdata += ' - %s\n' % key
- return userdata
-
- def map_sync_inputs(self, instance):
- inputs = {}
- metadata_update = {}
- if (instance.numberCores):
- metadata_update["cpu_cores"] = str(instance.numberCores)
-
- for tag in instance.slice.tags.all():
- if tag.name.startswith("sysctl-"):
- metadata_update[tag.name] = tag.value
-
- slice_memberships = SlicePrivilege.objects.filter(slice=instance.slice)
- pubkeys = set([sm.user.public_key for sm in slice_memberships if sm.user.public_key])
- if instance.creator.public_key:
- pubkeys.add(instance.creator.public_key)
-
- if instance.slice.creator.public_key:
- pubkeys.add(instance.slice.creator.public_key)
-
- if instance.slice.service and instance.slice.service.public_key:
- pubkeys.add(instance.slice.service.public_key)
-
- nics = []
- networks = [ns.network for ns in NetworkSlice.objects.filter(slice=instance.slice)]
- controller_networks = ControllerNetwork.objects.filter(network__in=networks,
- controller=instance.node.site_deployment.controller)
-
- for controller_network in controller_networks:
-
- # Lenient exception - causes slow backoff
- if controller_network.network.template.visibility == 'private' and \
- controller_network.network.template.translation == 'none':
- if not controller_network.net_id:
- raise DeferredException("Instance %s Private Network %s has no id; Try again later" % (instance, controller_network.network.name))
- nics.append(controller_network.net_id)
-
- # now include network template
- network_templates = [network.template.shared_network_name for network in networks \
- if network.template.shared_network_name]
-
- #driver = self.driver.client_driver(caller=instance.creator, tenant=instance.slice.name, controller=instance.controllerNetwork)
- driver = self.driver.admin_driver(tenant='admin', controller=instance.node.site_deployment.controller)
- nets = driver.shell.quantum.list_networks()['networks']
- for net in nets:
- if net['name'] in network_templates:
- nics.append(net['id'])
-
- if (not nics):
- for net in nets:
- if net['name']=='public':
- nics.append(net['id'])
-
- image_name = None
- controller_images = instance.image.controllerimages.filter(controller=instance.node.site_deployment.controller)
- if controller_images:
- image_name = controller_images[0].image.name
- logger.info("using image from ControllerImage object: " + str(image_name))
-
- if image_name is None:
- controller_driver = self.driver.admin_driver(controller=instance.node.site_deployment.controller)
- images = controller_driver.shell.glanceclient.images.list()
- for image in images:
- if image.name == instance.image.name or not image_name:
- image_name = image.name
- logger.info("using image from glance: " + str(image_name))
-
- try:
- legacy = Config().observer_legacy
- except:
- legacy = False
-
- if (legacy):
- host_filter = instance.node.name.split('.',1)[0]
- else:
- host_filter = instance.node.name.strip()
-
- availability_zone_filter = 'nova:%s'%host_filter
- instance_name = '%s-%d'%(instance.slice.name,instance.id)
- self.instance_name = instance_name
-
- userData = self.get_userdata(instance, pubkeys)
- if instance.userData:
- userData += instance.userData
-
- controller = instance.node.site_deployment.controller
- fields = {'endpoint':controller.auth_url,
- 'endpoint_v3': controller.auth_url_v3,
- 'domain': controller.domain,
- 'admin_user': instance.creator.email,
- 'admin_password': instance.creator.remote_password,
- 'admin_tenant': instance.slice.name,
- 'tenant': instance.slice.name,
- 'tenant_description': instance.slice.description,
- 'name':instance_name,
- 'ansible_tag':instance_name,
- 'availability_zone': availability_zone_filter,
- 'image_name':image_name,
- 'flavor_name':instance.flavor.name,
- 'nics':nics,
- 'meta':metadata_update,
- 'user_data':r'%s'%escape(userData)}
- return fields
-
-
- def map_sync_outputs(self, instance, res):
- instance_id = res[0]['info']['OS-EXT-SRV-ATTR:instance_name']
- instance_uuid = res[0]['id']
-
- try:
- hostname = res[0]['info']['OS-EXT-SRV-ATTR:hypervisor_hostname']
- ip = socket.gethostbyname(hostname)
- instance.ip = ip
- except:
- pass
-
- instance.instance_id = instance_id
- instance.instance_uuid = instance_uuid
- instance.instance_name = self.instance_name
- instance.save()
-
-
- def map_delete_inputs(self, instance):
- controller_register = json.loads(instance.node.site_deployment.controller.backend_register)
-
- if (controller_register.get('disabled',False)):
- raise InnocuousException('Controller %s is disabled'%instance.node.site_deployment.controller.name)
-
- instance_name = '%s-%d'%(instance.slice.name,instance.id)
- controller = instance.node.site_deployment.controller
- input = {'endpoint':controller.auth_url,
- 'admin_user': instance.creator.email,
- 'admin_password': instance.creator.remote_password,
- 'admin_tenant': instance.slice.name,
- 'tenant': instance.slice.name,
- 'tenant_description': instance.slice.description,
- 'name':instance_name,
- 'ansible_tag':instance_name,
- 'delete': True}
- return input
diff --git a/xos/openstack_observer/steps/sync_object.py b/xos/openstack_observer/steps/sync_object.py
deleted file mode 100644
index a289c95..0000000
--- a/xos/openstack_observer/steps/sync_object.py
+++ /dev/null
@@ -1,20 +0,0 @@
-import os
-import base64
-from collections import defaultdict
-from django.db.models import F, Q
-from xos.config import Config
-from observer.openstacksyncstep import OpenStackSyncStep
-from observer.syncstep import *
-from core.models import *
-from observer.ansible import *
-from openstack.driver import OpenStackDriver
-from util.logger import observer_logger as logger
-import json
-
-class SyncObject(OpenStackSyncStep):
- provides=[] # Caller fills this in
- requested_interval=0
- observes=[] # Caller fills this in
-
- def sync_record(self, r):
- raise DeferredException('Waiting for Service dependency: %r'%r)
diff --git a/xos/openstack_observer/steps/sync_ports.py b/xos/openstack_observer/steps/sync_ports.py
deleted file mode 100644
index bfdde8c..0000000
--- a/xos/openstack_observer/steps/sync_ports.py
+++ /dev/null
@@ -1,196 +0,0 @@
-import os
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from observer.openstacksyncstep import OpenStackSyncStep
-from core.models import Controller
-from core.models.network import *
-from util.logger import observer_logger as logger
-
-class SyncPorts(OpenStackSyncStep):
- requested_interval = 0 # 3600
- provides=[Port]
- observes=Port
-
- # The way it works is to enumerate the all of the ports that quantum
- # has, and then work backward from each port's network-id to determine
- # which Network is associated from the port.
-
- def call(self, **args):
- logger.info("sync'ing network instances")
-
- ports = Port.objects.all()
- ports_by_id = {}
- ports_by_neutron_port = {}
- for port in ports:
- ports_by_id[port.id] = port
- ports_by_neutron_port[port.port_id] = port
-
- networks = Network.objects.all()
- networks_by_id = {}
- for network in networks:
- for nd in network.controllernetworks.all():
- networks_by_id[nd.net_id] = network
-
- #logger.info("networks_by_id = ")
- #for (network_id, network) in networks_by_id.items():
- # logger.info(" %s: %s" % (network_id, network.name))
-
- instances = Instance.objects.all()
- instances_by_instance_uuid = {}
- for instance in instances:
- instances_by_instance_uuid[instance.instance_uuid] = instance
-
- # Get all ports in all controllers
-
- ports_by_id = {}
- templates_by_id = {}
- for controller in Controller.objects.all():
- if not controller.admin_tenant:
- logger.info("controller %s has no admin_tenant" % controller)
- continue
- try:
- driver = self.driver.admin_driver(controller = controller)
- ports = driver.shell.quantum.list_ports()["ports"]
- except:
- logger.log_exc("failed to get ports from controller %s" % controller)
- continue
-
- for port in ports:
- ports_by_id[port["id"]] = port
-
- # public-nat and public-dedicated networks don't have a net-id anywhere
- # in the data model, so build up a list of which ids map to which network
- # templates.
- try:
- neutron_networks = driver.shell.quantum.list_networks()["networks"]
- except:
- print "failed to get networks from controller %s" % controller
- continue
- for network in neutron_networks:
- for template in NetworkTemplate.objects.all():
- if template.shared_network_name == network["name"]:
- templates_by_id[network["id"]] = template
-
- for port in ports_by_id.values():
- #logger.info("port %s" % str(port))
- if port["id"] in ports_by_neutron_port:
- # we already have it
- #logger.info("already accounted for port %s" % port["id"])
- continue
-
- if port["device_owner"] != "compute:nova":
- # we only want the ports that connect to instances
- #logger.info("port %s is not a compute port, it is a %s" % (port["id"], port["device_owner"]))
- continue
-
- instance = instances_by_instance_uuid.get(port['device_id'], None)
- if not instance:
- logger.info("no instance for port %s device_id %s" % (port["id"], port['device_id']))
- continue
-
- network = networks_by_id.get(port['network_id'], None)
- if not network:
- # maybe it's public-nat or public-dedicated. Search the templates for
- # the id, then see if the instance's slice has some network that uses
- # that template
- template = templates_by_id.get(port['network_id'], None)
- if template and instance.slice:
- for candidate_network in instance.slice.networks.all():
- if candidate_network.template == template:
- network=candidate_network
- if not network:
- logger.info("no network for port %s network %s" % (port["id"], port["network_id"]))
-
- # we know it's associated with a instance, but we don't know
- # which network it is part of.
-
- continue
-
- if network.template.shared_network_name:
- # If it's a shared network template, then more than one network
- # object maps to the quantum network. We have to do a whole bunch
- # of extra work to find the right one.
- networks = network.template.network_set.all()
- network = None
- for candidate_network in networks:
- if (candidate_network.owner == instance.slice):
- logger.info("found network %s" % candidate_network)
- network = candidate_network
-
- if not network:
- logger.info("failed to find the correct network for a shared template for port %s network %s" % (port["id"], port["network_id"]))
- continue
-
- if not port["fixed_ips"]:
- logger.info("port %s has no fixed_ips" % port["id"])
- continue
-
- ip=port["fixed_ips"][0]["ip_address"]
- mac=port["mac_address"]
- logger.info("creating Port (%s, %s, %s, %s)" % (str(network), str(instance), ip, str(port["id"])))
-
- ns = Port(network=network,
- instance=instance,
- ip=ip,
- mac=mac,
- port_id=port["id"])
-
- try:
- ns.save()
- except:
- logger.log_exc("failed to save port %s" % str(ns))
- continue
-
- # For ports that were created by the user, find that ones
- # that don't have neutron ports, and create them.
- for port in Port.objects.filter(Q(port_id__isnull=True), Q(instance__isnull=False) ):
- logger.info("XXX working on port %s" % port)
- controller = port.instance.node.site_deployment.controller
- slice = port.instance.slice
-
- if controller:
- cn=port.network.controllernetworks.filter(controller=controller)
- if not cn:
- logger.log_exc("no controllernetwork for %s" % port)
- continue
- cn=cn[0]
- if cn.lazy_blocked:
- cn.lazy_blocked=False
- cn.save()
- logger.info("deferring port %s because controllerNetwork was lazy-blocked" % port)
- continue
- if not cn.net_id:
- logger.info("deferring port %s because controllerNetwork does not have a port-id yet" % port)
- continue
- try:
- # We need to use a client driver that specifies the tenant
- # of the destination instance. Nova-compute will not connect
- # ports to instances if the port's tenant does not match
- # the instance's tenant.
-
- # A bunch of stuff to compensate for OpenStackDriver.client_driveR()
- # not being in working condition.
- from openstack.client import OpenStackClient
- from openstack.driver import OpenStackDriver
- caller = port.network.owner.creator
- auth = {'username': caller.email,
- 'password': caller.remote_password,
- 'tenant': slice.name}
- client = OpenStackClient(controller=controller, **auth) # cacert=self.config.nova_ca_ssl_cert,
- driver = OpenStackDriver(client=client)
-
- neutron_port = driver.shell.quantum.create_port({"port": {"network_id": cn.net_id}})["port"]
- port.port_id = neutron_port["id"]
- if neutron_port["fixed_ips"]:
- port.ip = neutron_port["fixed_ips"][0]["ip_address"]
- port.mac = neutron_port["mac_address"]
- except:
- logger.log_exc("failed to create neutron port for %s" % port)
- continue
- port.save()
-
- def delete_record(self, network_instance):
- # Nothing to do, this is an OpenCloud object
- pass
-
diff --git a/xos/openstack_observer/steps/sync_roles.py b/xos/openstack_observer/steps/sync_roles.py
deleted file mode 100644
index c4bbe3f..0000000
--- a/xos/openstack_observer/steps/sync_roles.py
+++ /dev/null
@@ -1,23 +0,0 @@
-import os
-import base64
-from django.db.models import F, Q
-from xos.config import Config
-from observer.openstacksyncstep import OpenStackSyncStep
-from core.models.role import Role
-from core.models.site import SiteRole, Controller, ControllerRole
-from core.models.slice import SliceRole
-from util.logger import observer_logger as logger
-
-class SyncRoles(OpenStackSyncStep):
- provides=[Role]
- requested_interval=0
- observes=[SiteRole,SliceRole,ControllerRole]
-
- def sync_record(self, role):
- if not role.enacted:
- controllers = Controller.objects.all()
- for controller in controllers:
- driver = self.driver.admin_driver(controller=controller)
- driver.create_role(role.role)
- role.save()
-
diff --git a/xos/openstack_observer/syncstep.py b/xos/openstack_observer/syncstep.py
deleted file mode 100644
index 21327d7..0000000
--- a/xos/openstack_observer/syncstep.py
+++ /dev/null
@@ -1,296 +0,0 @@
-import os
-import base64
-from datetime import datetime
-from xos.config import Config
-from util.logger import Logger, logging
-from observer.steps import *
-from django.db.models import F, Q
-from core.models import *
-from django.db import reset_queries
-from observer.ansible import *
-from dependency_walker import *
-
-import json
-import time
-import pdb
-
-logger = Logger(level=logging.INFO)
-
-def f7(seq):
- seen = set()
- seen_add = seen.add
- return [ x for x in seq if not (x in seen or seen_add(x))]
-
-def elim_dups(backend_str):
- strs = backend_str.split(' // ')
- strs2 = f7(strs)
- return ' // '.join(strs2)
-
-def deepgetattr(obj, attr):
- return reduce(getattr, attr.split('.'), obj)
-
-
-class InnocuousException(Exception):
- pass
-
-class DeferredException(Exception):
- pass
-
-class FailedDependency(Exception):
- pass
-
-class SyncStep(object):
- """ An XOS Sync step.
-
- Attributes:
- psmodel Model name the step synchronizes
- dependencies list of names of models that must be synchronized first if the current model depends on them
- """
-
- # map_sync_outputs can return this value to cause a step to be marked
- # successful without running ansible. Used for sync_network_controllers
- # on nat networks.
- SYNC_WITHOUT_RUNNING = "sync_without_running"
-
- slow=False
- def get_prop(self, prop):
- try:
- sync_config_dir = Config().sync_config_dir
- except:
- sync_config_dir = '/etc/xos/sync'
- prop_config_path = '/'.join(sync_config_dir,self.name,prop)
- return open(prop_config_path).read().rstrip()
-
- def __init__(self, **args):
- """Initialize a sync step
- Keyword arguments:
- name -- Name of the step
- provides -- XOS models sync'd by this step
- """
- dependencies = []
- self.driver = args.get('driver')
- self.error_map = args.get('error_map')
-
- try:
- self.soft_deadline = int(self.get_prop('soft_deadline_seconds'))
- except:
- self.soft_deadline = 5 # 5 seconds
-
- return
-
- def fetch_pending(self, deletion=False):
- # This is the most common implementation of fetch_pending
- # Steps should override it if they have their own logic
- # for figuring out what objects are outstanding.
-
- main_objs = self.observes
- if (type(main_objs) is not list):
- main_objs=[main_objs]
-
- objs = []
- for main_obj in main_objs:
- if (not deletion):
- lobjs = main_obj.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False),Q(no_sync=False))
- else:
- lobjs = main_obj.deleted_objects.all()
- objs.extend(lobjs)
-
- return objs
- #return Instance.objects.filter(ip=None)
-
- def check_dependencies(self, obj, failed):
- for dep in self.dependencies:
- peer_name = dep[0].lower() + dep[1:] # django names are camelCased with the first letter lower
-
- peer_objects=[]
- try:
- peer_names = plural(peer_name)
- peer_object_list=[]
-
- try:
- peer_object_list.append(deepgetattr(obj, peer_name))
- except:
- pass
-
- try:
- peer_object_list.append(deepgetattr(obj, peer_names))
- except:
- pass
-
- for peer_object in peer_object_list:
- try:
- peer_objects.extend(peer_object.all())
- except AttributeError:
- peer_objects.append(peer_object)
- except:
- peer_objects = []
-
- if (hasattr(obj,'controller')):
- try:
- peer_objects = filter(lambda o:o.controller==obj.controller, peer_objects)
- except AttributeError:
- pass
-
- if (failed in peer_objects):
- if (obj.backend_status!=failed.backend_status):
- obj.backend_status = failed.backend_status
- obj.save(update_fields=['backend_status'])
- raise FailedDependency("Failed dependency for %s:%s peer %s:%s failed %s:%s" % (obj.__class__.__name__, str(getattr(obj,"pk","no_pk")), peer_object.__class__.__name__, str(getattr(peer_object,"pk","no_pk")), failed.__class__.__name__, str(getattr(failed,"pk","no_pk"))))
-
-
- def sync_record(self, o):
- try:
- controller = o.get_controller()
- controller_register = json.loads(o.node.site_deployment.controller.backend_register)
-
- if (controller_register.get('disabled',False)):
- raise InnocuousException('Controller %s is disabled'%sliver.node.site_deployment.controller.name)
- except AttributeError:
- pass
-
- tenant_fields = self.map_sync_inputs(o)
- if tenant_fields == SyncStep.SYNC_WITHOUT_RUNNING:
- return
- main_objs=self.observes
- if (type(main_objs) is list):
- main_objs=main_objs[0]
-
- path = ''.join(main_objs.__name__).lower()
- res = run_template(self.playbook,tenant_fields,path=path)
-
- try:
- self.map_sync_outputs(o,res)
- except AttributeError:
- pass
-
- def delete_record(self, o):
- try:
- controller = o.get_controller()
- controller_register = json.loads(o.node.site_deployment.controller.backend_register)
-
- if (controller_register.get('disabled',False)):
- raise InnocuousException('Controller %s is disabled'%sliver.node.site_deployment.controller.name)
- except AttributeError:
- pass
-
- tenant_fields = self.map_delete_inputs(o)
-
- main_objs=self.observes
- if (type(main_objs) is list):
- main_objs=main_objs[0]
-
- path = ''.join(main_objs.__name__).lower()
-
- tenant_fields['delete']=True
- res = run_template(self.playbook,tenant_fields,path=path)
- try:
- self.map_delete_outputs(o,res)
- except AttributeError:
- pass
-
- def call(self, failed=[], deletion=False):
- #if ('Instance' in self.__class__.__name__):
- # pdb.set_trace()
-
- pending = self.fetch_pending(deletion)
-
- for o in pending:
- # another spot to clean up debug state
- try:
- reset_queries()
- except:
- # this shouldn't happen, but in case it does, catch it...
- logger.log_exc("exception in reset_queries")
-
- sync_failed = False
- try:
- backoff_disabled = Config().observer_backoff_disabled
- except:
- backoff_disabled = 0
-
- try:
- scratchpad = json.loads(o.backend_register)
- if (scratchpad):
- next_run = scratchpad['next_run']
- if (not backoff_disabled and next_run>time.time()):
- sync_failed = True
- except:
- logger.log_exc("Exception while loading scratchpad")
- pass
-
- if (not sync_failed):
- try:
- for f in failed:
- self.check_dependencies(o,f) # Raises exception if failed
- if (deletion):
- self.delete_record(o)
- o.delete(purge=True)
- else:
- self.sync_record(o)
- o.enacted = datetime.now() # Is this the same timezone? XXX
- scratchpad = {'next_run':0, 'exponent':0}
- o.backend_register = json.dumps(scratchpad)
- o.backend_status = "1 - OK"
- o.save(update_fields=['enacted','backend_status','backend_register'])
- except (InnocuousException,Exception,DeferredException) as e:
- logger.log_exc("sync step failed!")
- try:
- if (o.backend_status.startswith('2 - ')):
- str_e = '%s // %r'%(o.backend_status[4:],e)
- str_e = elim_dups(str_e)
- else:
- str_e = '%r'%e
- except:
- str_e = '%r'%e
-
- try:
- error = self.error_map.map(str_e)
- except:
- error = '%s'%str_e
-
- if isinstance(e, InnocuousException) and not force_error:
- o.backend_status = '1 - %s'%error
- else:
- o.backend_status = '2 - %s'%error
-
- try:
- scratchpad = json.loads(o.backend_register)
- scratchpad['exponent']
- except:
- logger.log_exc("Exception while updating scratchpad")
- scratchpad = {'next_run':0, 'exponent':0}
-
- # Second failure
- if (scratchpad['exponent']):
- if isinstance(e,DeferredException):
- delay = scratchpad['exponent'] * 60 # 1 minute
- else:
- delay = scratchpad['exponent'] * 600 # 10 minutes
- # cap delays at 8 hours
- if (delay>8*60*60):
- delay=8*60*60
- scratchpad['next_run'] = time.time() + delay
-
- scratchpad['exponent']+=1
-
- o.backend_register = json.dumps(scratchpad)
-
- # TOFIX:
- # DatabaseError: value too long for type character varying(140)
- if (o.pk):
- try:
- o.backend_status = o.backend_status[:1024]
- o.save(update_fields=['backend_status','backend_register','updated'])
- except:
- print "Could not update backend status field!"
- pass
- sync_failed = True
-
-
- if (sync_failed):
- failed.append(o)
-
- return failed
-
- def __call__(self, **args):
- return self.call(**args)
diff --git a/xos/redhat/xos-observer.service b/xos/redhat/xos-observer.service
deleted file mode 100644
index 43734f1..0000000
--- a/xos/redhat/xos-observer.service
+++ /dev/null
@@ -1,14 +0,0 @@
-[Unit]
-Description=XOS Observer
-After=syslog.target network.target
-
-[Service]
-Type=forking
-User=root
-PIDFile=/var/run/xos-observer.pid
-ExecStart=/usr/sbin/daemonize -c /opt/xos -p /var/run/xos-observer.pid /opt/xos/xos-observer.py
-ExecStop=kill $(cat /var/run/xos-observer.pid)
-
-[Install]
-WantedBy=multi-user.target
-
diff --git a/xos/requestrouter/admin.py b/xos/requestrouter/admin.py
deleted file mode 100644
index 510dd27..0000000
--- a/xos/requestrouter/admin.py
+++ /dev/null
@@ -1,63 +0,0 @@
-from django.contrib import admin
-
-from requestrouter.models import *
-from django import forms
-from django.utils.safestring import mark_safe
-from django.contrib.auth.admin import UserAdmin
-from django.contrib.admin.widgets import FilteredSelectMultiple
-from django.contrib.auth.forms import ReadOnlyPasswordHashField
-from django.contrib.auth.signals import user_logged_in
-from django.utils import timezone
-from django.contrib.contenttypes import generic
-from suit.widgets import LinkedSelect
-from core.admin import ServiceAppAdmin,SliceInline,ServiceAttrAsTabInline, ReadOnlyAwareAdmin, ServicePrivilegeInline
-
-class RequestRouterAdmin(ReadOnlyAwareAdmin):
- # Change the application breadcrumb to point to an RR Service if one is
- # defined
-
- change_form_template = "admin/change_form_bc.html"
- change_list_template = "admin/change_list_bc.html"
- custom_app_breadcrumb_name = "Request Router"
- @property
- def custom_app_breadcrumb_url(self):
- services = RequestRouterService.objects.all()
- if len(services)==1:
- return "/admin/requestrouter/requestrouterservice/%s/" % services[0].id
- else:
- return "/admin/requestrouter/requestrouterservice/"
-
-class RequestRouterServiceAdmin(ServiceAppAdmin):
- model = RequestRouterService
- verbose_name = "Request Router Service"
- verbose_name_plural = "Request Router Service"
- list_display = ("name","enabled")
- fieldsets = [(None, {'fields': ['name','enabled','versionNumber', 'description','behindNat','defaultTTL','defaultAction','lastResortAction','maxAnswers'], 'classes':['suit-tab suit-tab-general']})]
- inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
-
- user_readonly_fields = ["name", "enabled", "versionNumber", "description", "behindNat", "defaultTTL", "defaultAction", "lastResortAction", "maxAnswers"]
-
- suit_form_tabs =(('general', 'Request Router Service Details'),
- ('administration', 'Administration'),
- ('slices','Slices'),
- ('serviceattrs','Additional Attributes'),
- ('serviceprivileges','Privileges'),
- )
-
- suit_form_includes = (('rradmin.html', 'top', 'administration'),)
-
-class ServiceMapAdmin(RequestRouterAdmin):
- model = ServiceMap
- verbose_name = "Service Map"
- verbose_name_plural = "Service Map"
- list_display = ("name", "owner", "slice", "prefix")
- fieldsets = [(None, {'fields': ['name','owner','slice', 'prefix','siteMap','accessMap'], 'classes':['suit-tab suit-tab-general']})]
-
- user_readonly_fields = ["name", "owner", "slice", "prefix", "siteMap", "accessMap"]
-
- suit_form_tabs =(('general', 'Service Map Details'),
- )
-
-admin.site.register(RequestRouterService, RequestRouterServiceAdmin)
-admin.site.register(ServiceMap, ServiceMapAdmin)
-
diff --git a/xos/rr_observer/deleters/servicemap_deleter.py b/xos/rr_observer/deleters/servicemap_deleter.py
deleted file mode 100644
index d0a707f..0000000
--- a/xos/rr_observer/deleters/servicemap_deleter.py
+++ /dev/null
@@ -1,42 +0,0 @@
-import os
-import sys
-import traceback
-from requestrouter.models import ServiceMap
-from observer.deleter import Deleter
-from util.logger import Logger, logging
-from xos.config import Config, XOS_DIR
-
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-from rrlib import RequestRouterLibrary
-from configurationPush import ConfigurationPush
-import rrlib_config
-
-logger = Logger(level=logging.INFO)
-
-class ServiceMapDeleter(Deleter, RequestRouterLibrary, ConfigurationPush):
- model='ServiceMap'
-
- def __init__(self, **args):
- Deleter.__init__(self, **args)
- RequestRouterLibrary.__init__(self)
- ConfigurationPush.__init__(self)
-
-
- def call(self, pk, model_dict):
- try:
- servicemap = ServiceMap.objects.get(pk=pk)
- service_uid = self.get_servicemap_uid(servicemap)
- self.config_push(service_uid, rrlib_config.REDIR_USER, XOS_DIR + "/rr_observer/playbook/site_redir_delete.yml", "/etc/ansible/requestrouter/dnsredir/hosts")
- self.config_push(service_uid, rrlib_config.DEMUX_USER, XOS_DIR + "/rr_observer/playbook/site_demux_delete.yml", "/etc/ansible/requestrouter/dnsdemux/hosts")
- print "XXX delete ServiceMap %s", servicemap.name
- return True
- except Exception, e:
- traceback.print_exc()
- logger.exception("Failed to erase map '%s'" % map_name)
- return False
-
-if __name__ == "__main__":
- smap = ServiceMapDeleter()
- smap.call( 6, {'name': 'Service23'} )
diff --git a/xos/rr_observer/rr_observer_config b/xos/rr_observer/rr_observer_config
deleted file mode 100644
index 5ca423e..0000000
--- a/xos/rr_observer/rr_observer_config
+++ /dev/null
@@ -1,36 +0,0 @@
-
-[plc]
-name=plc
-#deployment=VICCI
-deployment=VINI
-
-[db]
-name=xos
-user=plstackuser
-#password=2uMDYtJK
-password=1HL07C0E
-host=localhost
-port=5432
-
-[api]
-host=128.112.171.237
-port=8000
-ssl_key=None
-ssl_cert=None
-ca_ssl_cert=None
-ratelimit_enabled=0
-omf_enabled=0
-mail_support_address=support@localhost
-nova_enabled=True
-
-[observer]
-dependency_graph=/opt/xos/rr_observer/model-deps
-steps_dir=/opt/xos/rr_observer/steps
-deleters_dir=/opt/xos/rr_observer/deleters
-log_file=console
-#/var/log/hpc.log
-driver=None
-
-#[feefie]
-#client_id='vicci_dev_central'
-#user_id='pl'
diff --git a/xos/rr_observer/rrlib.py b/xos/rr_observer/rrlib.py
deleted file mode 100644
index 6968dcd..0000000
--- a/xos/rr_observer/rrlib.py
+++ /dev/null
@@ -1,203 +0,0 @@
-import os
-import base64
-import string
-import sys
-import socket
-from sets import Set
-if __name__ == '__main__':
- sys.path.append("/opt/xos")
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-
-from xos.config import Config
-from core.models import Service
-from requestrouter.models import RequestRouterService, ServiceMap
-from util.logger import Logger, logging
-import rrlib_config
-
-logger = Logger(level=logging.INFO)
-
-'''
-Conventions:
-1) All dnsredir backend will listen at port 9000+ servicemap.pk ( where pk is the primary key generated in django model)
-'''
-
-class RequestRouterLibrary:
-
- def __init__(self):
- pass
-
- def gen_slice_info(self, service=None):
- """generates instance information from slice of request router
- """
-
- if (service is None ):
- service = RequestRouterService.objects.get()
-
- mapping = {}
- #static mapping for demo purpose
- #mapping["node47.princeton.vicci.org"] = "128.112.171.112"
- mapping["node48.princeton.vicci.org"] = "128.112.171.114"
-
- '''for slice in service.service.all():
- name = slice.name
- for instance in slice.instances.all():
- mapping[instance.name] = str(instance.ip)
- '''
- return mapping
-
- def gen_servicemap_slice_info(self, servicemap):
- """generates instance information from slice of servicemap
- """
-
- wzone = Set(['arizona', 'stanford', 'on.lab', 'housten']) # zone=1 in cooden.conf
- ezone = Set(['princeton', 'atlanta', 'new york', 'georgia tech']) # zone=2 in coodeen.conf
-
- mapping_zone = {}
- mapping_ip = {}
- slice = servicemap.slice
- name = slice.name
- for instance in slice.instances.all():
- mapping_ip[instance.node.name] = socket.gethostbyname(instance.node.name)
- #print "instance name "+instance.name+str(instance.ip)+"\n"
- site = instance.node.site.name
- if(site.lower() in wzone):
- mapping_zone[instance.node.name] = str(1)
- else:
- mapping_zone[instance.node.name] = str(2)
-
- return mapping_ip, mapping_zone
-
-
-
- def gen_slice_file(self, service):
- """ generates host file for the slice information
- to be used by ansible to push configuration files
- """
-
- mapping = self.gen_slice_info(service)
-
- fn = "/etc/ansible/requestrouter/dnsredir/hosts"
- f = open(fn, "w")
- for (k,v) in mapping.items():
- f.write("%s\n" % k)
-
- fn = "/etc/ansible/requestrouter/dnsdemux/hosts"
- f = open(fn, "w")
- for (k,v) in mapping.items():
- f.write("%s\n" % k)
-
-
- def get_servicemap_uid(self, servicemap):
- seq = ("service_", str(servicemap.pk));
- return "".join(seq)
-
- def get_service_port(self, servicemap):
- return str(9000+servicemap.pk)
-
- def gen_dnsredir_serviceconf(self, servicemap):
- objname = self.get_servicemap_uid(servicemap)
-
- rr_mapping = self.gen_slice_info(None)
-
- #generate dnsredir.conf file parameters to be used in static file.
- mapping = {}
- mapping["port_listen"] = self.get_service_port(servicemap)
- mapping["configdir"] = rrlib_config.DNSREDIR_CONFIGDIR_PREFIX+objname+".d/"
- mapping["logdir"] = rrlib_config.DNSREDIR_LOGDIR_PREFIX+objname+".d"
- mapping["pidfile"] = rrlib_config.DNSREDIR_PIDFILE_PREFIX+objname+".pid"
- mapping["domain_name"] = servicemap.prefix
- mapping["heartbeat_port"] = rrlib_config.HEARTBEAT_PORT
-
- #generate dnsredir.conf file
-
- fn = "./temp_config/dnsredir/"+objname+".conf"
- f = open(fn, "w")
- for (k,v) in rr_mapping.items():
- f.write(mapping["domain_name"]+". NS "+k+". "+v+" 3600 \n" % mapping)
-
-
- f.write("""
-Default_TTL 30
-
-Port %(port_listen)s
-
-ConfigDir %(configdir)s
-
-MapsDir maps.d
-
-HTTPPort %(heartbeat_port)d
-
-PidFile %(pidfile)s
-
-HttpRequestPort 8081
-
-""" % mapping)
-
- #generate configdirectory
-
- os.mkdir("./temp_config/dnsredir/"+objname+".d")
-
- #geenrate codeen_nodes.conf
- mapping_ip, mapping_zone = self.gen_servicemap_slice_info(servicemap)
-
- codeen_name = "./temp_config/dnsredir/"+objname+".d/codeen_nodes.conf"
- f = open(codeen_name, "w")
- for (k,v) in mapping_zone.items():
- f.write(k+" zone="+v+" \n")
-
- iptxt = "./temp_config/dnsredir/"+objname+".d/node-to-ip.txt"
- f = open(iptxt, "w")
- for (k,v) in mapping_ip.items():
- f.write(k+" "+v+" \n")
-
- #generate maps directory
- os.mkdir("./temp_config/dnsredir/"+objname+".d/maps.d")
-
- # redirection map
- map = "./temp_config/dnsredir/"+objname+".d/maps.d/map.conf"
- f = open(map, "w")
- #hardcoded probable public IP masks from arizona and princeton region respectively
- f.write("prefix "+servicemap.prefix+" \n")
- f.write("map 150.135.211.252/32 zone 1 || zone 2 \n")
- f.write("map 128.112.171.112/24 zone 2 || zone 1 \n")
- f.write("map 0.0.0.0/0 zone 1 || zone 2 \n")
-
-
- def gen_dnsdemux_serviceconf(self, servicemap):
- '''
- generates frontend service*.conf file for each of the service
- It assumes that there is a dnsdemux frontend running on the RR istallation and will
- just add a conf file for each service in /etc/dnsdemux/default
- '''
- objname = self.get_servicemap_uid(servicemap)
- #generate dnsdemux.conf file parameters to be used in static file.
-
- port_listen = self.get_service_port(servicemap)
- domain_name = servicemap.prefix
- #generate service specific .conf file
-
- rr_mapping = self.gen_slice_info(None)
-
- fn = "./temp_config/dnsdemux/"+objname+".conf"
- f = open(fn, "w")
-
- for (k,v) in rr_mapping.items():
- f.write("Forward "+v+" "+port_listen+" 8081 "+domain_name+".\n")
-
-
- def teardown_temp_configfiles(self, objname):
- if os.path.exists("./temp_config/dnsdemux/"+objname+".conf"):
- os.remove("./temp_config/dnsdemux/"+objname+".conf")
- if os.path.exists("./temp_config/dnsredir/"+objname+".d/maps.d/map.conf"):
- os.remove("./temp_config/dnsredir/"+objname+".d/maps.d/map.conf")
- if os.path.exists("./temp_config/dnsredir/"+objname+".d/maps.d"):
- os.rmdir("./temp_config/dnsredir/"+objname+".d/maps.d")
- if os.path.exists("./temp_config/dnsredir/"+objname+".d/node-to-ip.txt"):
- os.remove("./temp_config/dnsredir/"+objname+".d/node-to-ip.txt")
- if os.path.exists("./temp_config/dnsredir/"+objname+".d/codeen_nodes.conf"):
- os.remove("./temp_config/dnsredir/"+objname+".d/codeen_nodes.conf")
- if os.path.exists("./temp_config/dnsredir/"+objname+".d"):
- os.rmdir("./temp_config/dnsredir/"+objname+".d")
- if os.path.exists("./temp_config/dnsredir/"+objname+".conf"):
- os.remove("./temp_config/dnsredir/"+objname+".conf")
-
diff --git a/xos/rr_observer/steps/sync_requestrouterservices.py b/xos/rr_observer/steps/sync_requestrouterservices.py
deleted file mode 100644
index db63c5b..0000000
--- a/xos/rr_observer/steps/sync_requestrouterservices.py
+++ /dev/null
@@ -1,46 +0,0 @@
-import os
-import sys
-import base64
-import traceback
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from core.models import Service
-from requestrouter.models import RequestRouterService
-from util.logger import Logger, logging
-
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-from rrlib import RequestRouterLibrary
-
-logger = Logger(level=logging.INFO)
-
-class SyncRequestRouterService(SyncStep, RequestRouterLibrary):
- provides=[RequestRouterService]
- requested_interval=0
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
- RequestRouterLibrary.__init__(self)
-
- def fetch_pending(self):
- try:
- ret = RequestRouterService.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
- return ret
- except Exception, e:
- traceback.print_exc()
- return None
-
- def sync_record(self, rr_service):
- try:
- print "syncing service!"
- logger.info("sync'ing rr_service %s" % str(rr_service))
- self.gen_slice_file(rr_service)
- rr_service.save()
- return True
- except Exception, e:
- traceback.print_exc()
- return False
-
-
diff --git a/xos/rr_observer/steps/sync_servicemap.py b/xos/rr_observer/steps/sync_servicemap.py
deleted file mode 100644
index 1ec54aa..0000000
--- a/xos/rr_observer/steps/sync_servicemap.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import sys
-import base64
-import traceback
-from django.db.models import F, Q
-from xos.config import Config, XOS_DIR
-from observer.syncstep import SyncStep
-from core.models import Service
-from requestrouter.models import ServiceMap
-from util.logger import Logger, logging
-
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-from rrlib import RequestRouterLibrary
-from configurationPush import ConfigurationPush
-import rrlib_config
-
-logger = Logger(level=logging.INFO)
-
-class SyncServiceMap(SyncStep, RequestRouterLibrary, ConfigurationPush):
- provides=[ServiceMap]
- requested_interval=0
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
- RequestRouterLibrary.__init__(self)
- ConfigurationPush.__init__(self)
-
- def fetch_pending(self):
- try:
- ret = ServiceMap.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
- return ret
- except Exception, e:
- traceback.print_exc()
- return None
-
- def sync_record(self, servicemap):
- try:
- print "sync! %s " % self.get_servicemap_uid(servicemap)
- self.gen_dnsredir_serviceconf(servicemap)
- self.gen_dnsdemux_serviceconf(servicemap)
- # push generated files from temp_config
- service_uid = self.get_servicemap_uid(servicemap)
- self.config_push(service_uid, rrlib_config.REDIR_USER, XOS_DIR + "/rr_observer/playbook/site_redir.yml", "/etc/ansible/requestrouter/dnsredir/hosts")
- self.config_push(service_uid, rrlib_config.DEMUX_USER, XOS_DIR + "/rr_observer/playbook/site_demux.yml", "/etc/ansible/requestrouter/dnsdemux/hosts")
- self.teardown_temp_configfiles(service_uid)
- except Exception, e:
- traceback.print_exc()
- return False
-
-if __name__ == "__main__":
- sv = SyncServiceMap()
-
- recs = sv.fetch_pending()
-
- for rec in recs:
- sv.sync_record( rec )
diff --git a/xos/scripts/docker_start_xos b/xos/scripts/docker_start_xos
deleted file mode 100755
index eee9b8f..0000000
--- a/xos/scripts/docker_start_xos
+++ /dev/null
@@ -1,7 +0,0 @@
-#! /bin/bash
-
-bash /opt/xos/scripts/docker_setup_xos
-
-cd /opt/xos
-PUBLIC_HOSTNAME=`./xos-config.py get server_hostname $HOSTNAME`
-python manage.py runserver $PUBLIC_HOSTNAME:8000 --insecure
diff --git a/xos/scripts/opencloud b/xos/scripts/opencloud
deleted file mode 100755
index 6b3e737..0000000
--- a/xos/scripts/opencloud
+++ /dev/null
@@ -1,237 +0,0 @@
-#!/bin/bash
-
-if [ -z "$1" ]; then
- echo usage: $0 "[initdb | createdb | dropdb | syncdb | runserver | resetdb | dumpdata]"
- exit
-fi
-
-XOS_DIR=/opt/xos
-BACKUP_DIR=/opt/xos_backups
-DBNAME=xos
-
-DJANGO_17=`python -c "import django; from distutils.version import StrictVersion; print int(StrictVersion(django.get_version()) >= StrictVersion('1.7'))"`
-
-cd $XOS_DIR
-
-function is_ubuntu {
- if ! which lsb_release &> /dev/null; then
- # lsb_release is not installed
- return 1
- fi
- if lsb_release -i | grep -i ubuntu &> /dev/null; then
- return 0
- fi
- return 2
-}
-
-function ensure_postgres_running {
- # "sudo -u postgres pg_ctl -D /var/lib/postgres/data status" doesn't work
- # right on Vicci, so let's try to detect it by seeing if the port is
- # being listened on
-
- netstat -nl | grep -i ":5432 " > /dev/null
- if [[ $? == 0 ]]; then
- echo "Postgres is already running"
- return
- fi
-
- # note that initdb isn't needed in Ubuntu distributions, and calling it
- # will throw spurious error messages
- if ! is_ubuntu; then
- service postgresql initdb
- fi
- service postgresql start
-
- netstat -nl | grep -i ":5432 " > /dev/null
- if [[ $? != 0 ]]; then
- # it's still not running...
- # this is intended for Vicci where some D-Bus issue is
- # preventing systemctl from working properly.
- echo "Trying fallback mechanism to start Postgres"
- sudo -u postgres initdb -D /var/lib/pgsql/data/
- sudo -u postgres pg_ctl -D /var/lib/pgsql/data -l logfile start
- fi
-
-}
-
-function wait_postgres {
- sudo -u postgres psql -c '\q'
- while [[ "$?" != "0" ]]; do
- echo Waiting for postgres to start
- sleep 1
- sudo -u postgres psql -c '\q'
- done
-}
-
-function db_exists {
- sudo -u postgres psql $DBNAME -c '\q' 2>/dev/null
- return $?
-}
-
-function createdb {
- wait_postgres
- echo "Creating XOS database..."
- sudo -u postgres createdb $DBNAME
-}
-function dropdb {
- echo "Dropping XOS database..."
- sudo -u postgres dropdb $DBNAME
-}
-function syncdb {
- echo "Syncing XOS services..."
- python $XOS_DIR/manage.py syncdb --noinput
- if [[ $DJANGO_17 ]]; then
- echo "Loading initial data from fixture..."
- python $XOS_DIR/manage.py --noobserver --nomodelpolicy loaddata $XOS_DIR/core/fixtures/initial_data.json
- fi
-}
-function evolvedb {
- echo "Evolving XOS services..."
- python $XOS_DIR/manage.py evolve --hint --execute --noinput
-}
-function migratedb {
- echo "Migrating XOS services..."
- python $XOS_DIR/manage.py migrate
-}
-function stopserver {
- echo "Stopping any running XOS Service(s)"
- pkill -f "python.*runserver"
-}
-function runserver {
- ensure_postgres_running
- PUBLIC_HOSTNAME=`$XOS_DIR/xos-config.py get server_hostname $HOSTNAME`
- echo "Starting XOS Service on $PUBLIC_HOSTNAME:8000"
- python manage.py runserver $PUBLIC_HOSTNAME:8000 --insecure&
-}
-
-function dumpdata {
- mkdir -p $BACKUP_DIR
- FN="$BACKUP_DIR/dumpdata-`date +%Y-%m-%d_%H:%M:%S`.json"
- echo "Saving data to $FN"
- python manage.py dumpdata core hpc syndicate_storage requestrouter -a --indent 4 > $FN
- if [[ ! -f $FN ]]; then
- echo "FAILED to create $FN"
- exit
- fi
- SIZE=$(du -k "$FN" | cut -f 1)
- if [[ $SIZE -lt 9 ]]; then
- echo "Dumpdata was empty. Deleting and aborting"
- rm $FN
- exit
- fi
- rm -f $BACKUP_DIR/dumpdata-latest.json
- ln -s $FN $BACKUP_DIR/dumpdata-latest.json
-}
-
-function genkeys {
- mkdir -p public_keys
- mkdir -p private_keys
- echo "Generating keys"
- keyczart create --location=private_keys --name="OpenCloud" --purpose=crypt --asymmetric=rsa
- keyczart addkey --location=private_keys --status=primary --size=1024
- keyczart pubkey --location=private_keys --destination=public_keys
- if [[ ! -f public_keys/1 ]]; then
- echo "FAILED to create keys"
- exit
- fi
-}
-
-function makemigrations {
- rm -rf /opt/xos/*/migrations /opt/xos/services/*/migrations
- python ./manage.py makemigrations core
- python ./manage.py makemigrations hpc
- python ./manage.py makemigrations requestrouter
- python ./manage.py makemigrations syndicate_storage
- python ./manage.py makemigrations cord
- python ./manage.py makemigrations ceilometer
- python ./manage.py makemigrations helloworldservice_complete
- python ./manage.py makemigrations onos
- #python ./manage.py makemigrations servcomp
-}
-
-function remigrate {
- if db_exists; then
- dropdb
- fi
- makemigrations
-}
-
-COMMAND=$1
-
-if [ "$COMMAND" = "initdb" ]; then
- stopserver
- ensure_postgres_running
- createdb
- syncdb
-fi
-if [ "$COMMAND" = "repairdb" ]; then
- stopserver
- ensure_postgres_running
- dumpdata
- # TODO: This is where we could run migration scripts to upgrade the
- # dumped data to the new models.
- mv $XOS_DIR/core/fixtures/initial_data.json $XOS_DIR/core/fixtures/initial_data.json-old
- cp $BACKUP_DIR/dumpdata-latest.json $XOS_DIR/core/fixtures/initial_data.json
- dropdb
- createdb
- syncdb
-fi
-if [ "$COMMAND" = "restoredb" ]; then
- if [[ ! -f $BACKUP_DIR/dumpdata-latest.json ]]; then
- echo There is no dumpdata to restore
- exit
- fi
- stopserver
- ensure_postgres_running
- mv $XOS_DIR/core/fixtures/initial_data.json $XOS_DIR/core/fixtures/initial_data.json-old
- cp $BACKUP_DIR/dumpdata-latest.json $XOS_DIR/core/fixtures/initial_data.json
- dropdb
- createdb
- syncdb
-fi
-if [ "$COMMAND" = "evolvedb" -o "$COMMAND" = "migratedb" ]; then
- stopserver
- ensure_postgres_running
- if [[ $DJANGO_17 ]]; then
- migratedb
- else
- evolvedb
- fi
-fi
-if [ "$COMMAND" = "resetdb" ]; then
- stopserver
- ensure_postgres_running
- dropdb
- createdb
- syncdb
-fi
-if [ "$COMMAND" = "syncdb" ]; then
- stopserver
- syncdb
-fi
-if [ "$COMMAND" = "runserver" ]; then
- stopserver
- runserver
-fi
-if [ "$COMMAND" = "stopserver" ]; then
- stopserver
-fi
-if [ "$COMMAND" = "dumpdata" ]; then
- dumpdata
-fi
-if [ "$COMMAND" = "genkeys" ]; then
- genkeys
-fi
-if [ "$COMMAND" = "generateapi" ]; then
- python apigen/modelgen apigen/api.template.py > xos/xosapi.py
-fi
-if [ "$COMMAND" = "remigrate" ]; then
- ensure_postgres_running
- remigrate
- createdb
- syncdb
-fi
-if [ "$COMMAND" = "makemigrations" ]; then
- makemigrations
- syncdb
-fi
diff --git a/xos/servcomp/__init__.py b/xos/servcomp/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/xos/servcomp/__init__.py
+++ /dev/null
diff --git a/xos/servcomp/admin.py b/xos/servcomp/admin.py
deleted file mode 100644
index 3abd7cd..0000000
--- a/xos/servcomp/admin.py
+++ /dev/null
@@ -1,68 +0,0 @@
-from django.contrib import admin
-
-from servcomp.models import *
-from django import forms
-from django.utils.safestring import mark_safe
-from django.contrib.auth.admin import UserAdmin
-from django.contrib.admin.widgets import FilteredSelectMultiple
-from django.contrib.auth.forms import ReadOnlyPasswordHashField
-from django.contrib.auth.signals import user_logged_in
-from django.utils import timezone
-from django.contrib.contenttypes import generic
-from suit.widgets import LinkedSelect
-from core.admin import SingletonAdmin,SliceInline,ServiceAttrAsTabInline, ReadOnlyAwareAdmin, XOSTabularInline
-
-class ServiceInline(XOSTabularInline):
- model = CompositionServiceThrough
- verbose_name = "Service"
- verbose_name_plural = "Services"
- extra = 0
- #suit_classes = 'suit-tab suit-tab-general'
- fields = ('backend_status_icon', 'service', 'order')
- readonly_fields = ('backend_status_icon',)
-
-class CompositionServiceAdmin(SingletonAdmin):
- model = CompositionService
- verbose_name = "Composition Service"
- verbose_name_plural = "Composition Service"
- list_display = ("backend_status_icon", "name","enabled")
- list_display_links = ('backend_status_icon', 'name', )
- fieldsets = [(None, {'fields': ['backend_status_text', 'name','enabled','versionNumber', 'description'], 'classes':['suit-tab suit-tab-general']})]
- readonly_fields = ('backend_status_text', )
- inlines = [SliceInline,ServiceAttrAsTabInline]
-
- user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
-
- suit_form_tabs =(('general', 'Composition Service Details'),
- ('slices','Slices'),
- ('serviceattrs','Additional Attributes'),
- )
-
-class CompositionForm(forms.ModelForm):
- model = Composition
- class Media:
- js = ('/static/js/menu-sort-2.js',)
-
-class CompositionAdmin(ReadOnlyAwareAdmin):
- list_display = ('backend_status_icon', 'name' )
- list_display_links = ('backend_status_icon', 'name' )
- form = CompositionForm
-
- fields = ('backend_status_text', 'name')
- readonly_fields = ('backend_status_text', )
- user_readonly_fields = ('name',)
-
- inlines = [ServiceInline]
-
-class EndUserAdmin(ReadOnlyAwareAdmin):
- list_display = ('backend_status_icon', 'email', 'macAddress', 'composition' )
- list_display_links = ('backend_status_icon', 'email' )
-
- fields = ('backend_status_text', 'email', 'firstName', 'lastName', 'macAddress', 'composition')
- readonly_fields = ('backend_status_text', )
- user_readonly_fields = ('email', 'firstName', 'lastName', 'macAddress')
-
-admin.site.register(CompositionService, CompositionServiceAdmin)
-admin.site.register(Composition, CompositionAdmin)
-admin.site.register(EndUser, EndUserAdmin)
-
diff --git a/xos/servcomp/migrations/__init__.py b/xos/servcomp/migrations/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/xos/servcomp/migrations/__init__.py
+++ /dev/null
diff --git a/xos/servcomp/models.py b/xos/servcomp/models.py
deleted file mode 100644
index 192554a..0000000
--- a/xos/servcomp/models.py
+++ /dev/null
@@ -1,43 +0,0 @@
-from django.db import models
-from core.models import User, Service, SingletonModel, PlCoreBase
-import os
-from django.db import models
-from django.forms.models import model_to_dict
-
-class CompositionService(SingletonModel,Service):
- class Meta:
- app_label = "servcomp"
- verbose_name = "Service Composition Service"
-
-class Composition(PlCoreBase):
- class Meta:
- app_label = "servcomp"
-
- name = models.CharField(max_length=255);
- services = models.ManyToManyField(Service, through='CompositionServiceThrough', blank=True);
-
- def __unicode__(self):
- return self.name
-
-class CompositionServiceThrough(PlCoreBase):
- class Meta:
- app_label = "servcomp"
- ordering = ("order", )
-
- composition = models.ForeignKey(Composition)
- service = models.ForeignKey(Service, related_name="compositions")
- order = models.IntegerField(default=0)
-
-class EndUser(PlCoreBase):
- class Meta:
- app_label = "servcomp"
-
- email = models.CharField(max_length=255)
- firstName = models.CharField(max_length=80)
- lastName = models.CharField(max_length=80)
- macAddress = models.CharField(max_length=80)
- composition = models.ForeignKey(Composition, related_name="endUsers", blank=True, null=True)
-
- def __unicode__(self):
- return self.email
-
diff --git a/xos/servcomp/static/js/menu-sort-2.js b/xos/servcomp/static/js/menu-sort-2.js
deleted file mode 100644
index d7e3005..0000000
--- a/xos/servcomp/static/js/menu-sort-2.js
+++ /dev/null
@@ -1,21 +0,0 @@
-jQuery(function($) {
- $("div.inline-group").sortable({
- axis: 'y',
- placeholder: 'ui-state-highlight',
- forcePlaceholderSize: 'true',
- items: '.row1, .row2',
- update: update
- });
- $("div.inline-group").disableSelection();
-});
-function update() {
- $('.row1, .row2').each(function(i) {
- $(this).find('input[id$=order]').val(i+1);
- });
-}
-jQuery(document).ready(function($){
-// $(this).find('input[id$=order]').parent('div').parent('div').hide().parent().parent().css('cursor','move');
- $(this).find('input[id$=order]').parent('td').hide().parent('tr').parent('tbody').parent('table').find("th:contains('Order')").hide();
- $(this).find('input[id$=order]').parent('td').hide().parent('tr').parent('tbody').parent('table').css('cursor','move');
- $('.add-row a').click(update);
-});
diff --git a/xos/ceilometer/__init__.py b/xos/services/ceilometer/__init__.py
similarity index 100%
rename from xos/ceilometer/__init__.py
rename to xos/services/ceilometer/__init__.py
diff --git a/xos/services/ceilometer/admin.py b/xos/services/ceilometer/admin.py
new file mode 100644
index 0000000..ed8e47a
--- /dev/null
+++ b/xos/services/ceilometer/admin.py
@@ -0,0 +1,102 @@
+from django.contrib import admin
+
+from services.ceilometer.models import *
+from django import forms
+from django.utils.safestring import mark_safe
+from django.contrib.auth.admin import UserAdmin
+from django.contrib.admin.widgets import FilteredSelectMultiple
+from django.contrib.auth.forms import ReadOnlyPasswordHashField
+from django.contrib.auth.signals import user_logged_in
+from django.utils import timezone
+from django.contrib.contenttypes import generic
+from suit.widgets import LinkedSelect
+from core.admin import ServiceAppAdmin,SliceInline,ServiceAttrAsTabInline, ReadOnlyAwareAdmin, XOSTabularInline, ServicePrivilegeInline, TenantRootTenantInline, TenantRootPrivilegeInline
+from core.middleware import get_request
+
+from functools import update_wrapper
+from django.contrib.admin.views.main import ChangeList
+from django.core.urlresolvers import reverse
+from django.contrib.admin.utils import quote
+
+class CeilometerServiceAdmin(ReadOnlyAwareAdmin):
+ model = CeilometerService
+ verbose_name = "Ceilometer Service"
+ verbose_name_plural = "Ceilometer Service"
+ list_display = ("backend_status_icon", "name", "enabled")
+ list_display_links = ('backend_status_icon', 'name', )
+ fieldsets = [(None, {'fields': ['backend_status_text', 'name','enabled','versionNumber', 'description',"view_url","icon_url" ], 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text', )
+ inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
+
+ extracontext_registered_admins = True
+
+ user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
+
+ suit_form_tabs =(('general', 'Ceilometer Service Details'),
+ ('administration', 'Administration'),
+ ('slices','Slices'),
+ ('serviceattrs','Additional Attributes'),
+ ('serviceprivileges','Privileges'),
+ )
+
+ suit_form_includes = (('ceilometeradmin.html', 'top', 'administration'),
+ )
+
+ def queryset(self, request):
+ return CeilometerService.get_service_objects_by_user(request.user)
+
+class MonitoringChannelForm(forms.ModelForm):
+ creator = forms.ModelChoiceField(queryset=User.objects.all())
+
+ def __init__(self,*args,**kwargs):
+ super (MonitoringChannelForm,self ).__init__(*args,**kwargs)
+ self.fields['kind'].widget.attrs['readonly'] = True
+ self.fields['provider_service'].queryset = CeilometerService.get_service_objects().all()
+ if self.instance:
+ # fields for the attributes
+ self.fields['creator'].initial = self.instance.creator
+ if (not self.instance) or (not self.instance.pk):
+ # default fields for an 'add' form
+ self.fields['kind'].initial = CEILOMETER_KIND
+ self.fields['creator'].initial = get_request().user
+ if CeilometerService.get_service_objects().exists():
+ self.fields["provider_service"].initial = CeilometerService.get_service_objects().all()[0]
+
+
+ def save(self, commit=True):
+ self.instance.creator = self.cleaned_data.get("creator")
+ return super(MonitoringChannelForm, self).save(commit=commit)
+
+ class Meta:
+ model = MonitoringChannel
+
+class MonitoringChannelAdmin(ReadOnlyAwareAdmin):
+ list_display = ('backend_status_icon', 'id', )
+ list_display_links = ('backend_status_icon', 'id')
+ fieldsets = [ (None, {'fields': ['backend_status_text', 'kind', 'provider_service', 'service_specific_attribute',
+ 'ceilometer_url', 'tenant_list_str',
+ 'instance', 'creator'],
+ 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text', 'instance', 'service_specific_attribute', 'ceilometer_url', 'tenant_list_str')
+ form = MonitoringChannelForm
+
+ suit_form_tabs = (('general','Details'),)
+ actions=['delete_selected_objects']
+
+ def get_actions(self, request):
+ actions = super(MonitoringChannelAdmin, self).get_actions(request)
+ if 'delete_selected' in actions:
+ del actions['delete_selected']
+ return actions
+
+ def delete_selected_objects(self, request, queryset):
+ for obj in queryset:
+ obj.delete()
+ delete_selected_objects.short_description = "Delete Selected MonitoringChannel Objects"
+
+ def queryset(self, request):
+ return MonitoringChannel.get_tenant_objects_by_user(request.user)
+
+admin.site.register(CeilometerService, CeilometerServiceAdmin)
+admin.site.register(MonitoringChannel, MonitoringChannelAdmin)
+
diff --git a/xos/ceilometer/models.py b/xos/services/ceilometer/models.py
similarity index 100%
rename from xos/ceilometer/models.py
rename to xos/services/ceilometer/models.py
diff --git a/xos/ceilometer/templates/ceilometeradmin.html b/xos/services/ceilometer/templates/ceilometeradmin.html
similarity index 100%
rename from xos/ceilometer/templates/ceilometeradmin.html
rename to xos/services/ceilometer/templates/ceilometeradmin.html
diff --git a/xos/cord/__init__.py b/xos/services/cord/__init__.py
similarity index 100%
rename from xos/cord/__init__.py
rename to xos/services/cord/__init__.py
diff --git a/xos/services/cord/admin.py b/xos/services/cord/admin.py
new file mode 100644
index 0000000..5f1a285
--- /dev/null
+++ b/xos/services/cord/admin.py
@@ -0,0 +1,370 @@
+from django.contrib import admin
+
+from services.cord.models import *
+from django import forms
+from django.utils.safestring import mark_safe
+from django.contrib.auth.admin import UserAdmin
+from django.contrib.admin.widgets import FilteredSelectMultiple
+from django.contrib.auth.forms import ReadOnlyPasswordHashField
+from django.contrib.auth.signals import user_logged_in
+from django.utils import timezone
+from django.contrib.contenttypes import generic
+from suit.widgets import LinkedSelect
+from core.admin import ServiceAppAdmin,SliceInline,ServiceAttrAsTabInline, ReadOnlyAwareAdmin, XOSTabularInline, ServicePrivilegeInline, TenantRootTenantInline, TenantRootPrivilegeInline
+from core.middleware import get_request
+
+from functools import update_wrapper
+from django.contrib.admin.views.main import ChangeList
+from django.core.urlresolvers import reverse
+from django.contrib.admin.utils import quote
+
+#-----------------------------------------------------------------------------
+# vOLT
+#-----------------------------------------------------------------------------
+
+class VOLTServiceAdmin(ReadOnlyAwareAdmin):
+ model = VOLTService
+ verbose_name = "vOLT Service"
+ verbose_name_plural = "vOLT Service"
+ list_display = ("backend_status_icon", "name", "enabled")
+ list_display_links = ('backend_status_icon', 'name', )
+ fieldsets = [(None, {'fields': ['backend_status_text', 'name','enabled','versionNumber', 'description',"view_url","icon_url" ], 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text', )
+ inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
+
+ extracontext_registered_admins = True
+
+ user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
+
+ suit_form_tabs =(('general', 'vOLT Service Details'),
+ ('administration', 'Administration'),
+ #('tools', 'Tools'),
+ ('slices','Slices'),
+ ('serviceattrs','Additional Attributes'),
+ ('serviceprivileges','Privileges'),
+ )
+
+ suit_form_includes = (('voltadmin.html', 'top', 'administration'),
+ ) #('hpctools.html', 'top', 'tools') )
+
+ def queryset(self, request):
+ return VOLTService.get_service_objects_by_user(request.user)
+
+class VOLTTenantForm(forms.ModelForm):
+ s_tag = forms.CharField()
+ c_tag = forms.CharField()
+ creator = forms.ModelChoiceField(queryset=User.objects.all())
+
+ def __init__(self,*args,**kwargs):
+ super (VOLTTenantForm,self ).__init__(*args,**kwargs)
+ self.fields['kind'].widget.attrs['readonly'] = True
+ self.fields['provider_service'].queryset = VOLTService.get_service_objects().all()
+ if self.instance:
+ # fields for the attributes
+ self.fields['c_tag'].initial = self.instance.c_tag
+ self.fields['s_tag'].initial = self.instance.s_tag
+ self.fields['creator'].initial = self.instance.creator
+ if (not self.instance) or (not self.instance.pk):
+ # default fields for an 'add' form
+ self.fields['kind'].initial = VOLT_KIND
+ self.fields['creator'].initial = get_request().user
+ if VOLTService.get_service_objects().exists():
+ self.fields["provider_service"].initial = VOLTService.get_service_objects().all()[0]
+
+ def save(self, commit=True):
+ self.instance.s_tag = self.cleaned_data.get("s_tag")
+ self.instance.c_tag = self.cleaned_data.get("c_tag")
+ self.instance.creator = self.cleaned_data.get("creator")
+ return super(VOLTTenantForm, self).save(commit=commit)
+
+ class Meta:
+ model = VOLTTenant
+
+class VOLTTenantAdmin(ReadOnlyAwareAdmin):
+ list_display = ('backend_status_icon', 'id', 'service_specific_id', 's_tag', 'c_tag', 'subscriber_root' )
+ list_display_links = ('backend_status_icon', 'id')
+ fieldsets = [ (None, {'fields': ['backend_status_text', 'kind', 'provider_service', 'subscriber_root', 'service_specific_id', # 'service_specific_attribute',
+ 's_tag', 'c_tag', 'creator'],
+ 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text', 'service_specific_attribute')
+ form = VOLTTenantForm
+
+ suit_form_tabs = (('general','Details'),)
+
+ def queryset(self, request):
+ return VOLTTenant.get_tenant_objects_by_user(request.user)
+
+#-----------------------------------------------------------------------------
+# vCPE
+#-----------------------------------------------------------------------------
+
+class VCPEServiceForm(forms.ModelForm):
+ bbs_api_hostname = forms.CharField(required=False)
+ bbs_api_port = forms.IntegerField(required=False)
+ bbs_server = forms.CharField(required=False)
+ backend_network_label = forms.CharField(required=False)
+ bbs_slice = forms.ModelChoiceField(queryset=Slice.objects.all(), required=False)
+
+ def __init__(self,*args,**kwargs):
+ super (VCPEServiceForm,self ).__init__(*args,**kwargs)
+ if self.instance:
+ self.fields['bbs_api_hostname'].initial = self.instance.bbs_api_hostname
+ self.fields['bbs_api_port'].initial = self.instance.bbs_api_port
+ self.fields['bbs_server'].initial = self.instance.bbs_server
+ self.fields['backend_network_label'].initial = self.instance.backend_network_label
+ self.fields['bbs_slice'].initial = self.instance.bbs_slice
+
+ def save(self, commit=True):
+ self.instance.bbs_api_hostname = self.cleaned_data.get("bbs_api_hostname")
+ self.instance.bbs_api_port = self.cleaned_data.get("bbs_api_port")
+ self.instance.bbs_server = self.cleaned_data.get("bbs_server")
+ self.instance.backend_network_label = self.cleaned_data.get("backend_network_label")
+ self.instance.bbs_slice = self.cleaned_data.get("bbs_slice")
+ return super(VCPEServiceForm, self).save(commit=commit)
+
+ class Meta:
+ model = VCPEService
+
+class VCPEServiceAdmin(ReadOnlyAwareAdmin):
+ model = VCPEService
+ verbose_name = "vCPE Service"
+ verbose_name_plural = "vCPE Service"
+ list_display = ("backend_status_icon", "name", "enabled")
+ list_display_links = ('backend_status_icon', 'name', )
+ fieldsets = [(None, {'fields': ['backend_status_text', 'name','enabled','versionNumber', 'description', "view_url", "icon_url", "service_specific_attribute",],
+ 'classes':['suit-tab suit-tab-general']}),
+ ("backend config", {'fields': [ "backend_network_label", "bbs_api_hostname", "bbs_api_port", "bbs_server", "bbs_slice"],
+ 'classes':['suit-tab suit-tab-backend']}) ]
+ readonly_fields = ('backend_status_text', "service_specific_attribute")
+ inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
+ form = VCPEServiceForm
+
+ extracontext_registered_admins = True
+
+ user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
+
+ suit_form_tabs =(('general', 'Service Details'),
+ ('backend', 'Backend Config'),
+ ('administration', 'Administration'),
+ #('tools', 'Tools'),
+ ('slices','Slices'),
+ ('serviceattrs','Additional Attributes'),
+ ('serviceprivileges','Privileges') ,
+ )
+
+ suit_form_includes = (('vcpeadmin.html', 'top', 'administration'),
+ ) #('hpctools.html', 'top', 'tools') )
+
+ def queryset(self, request):
+ return VCPEService.get_service_objects_by_user(request.user)
+
+class VCPETenantForm(forms.ModelForm):
+ bbs_account = forms.CharField(required=False)
+ creator = forms.ModelChoiceField(queryset=User.objects.all())
+ instance = forms.ModelChoiceField(queryset=Instance.objects.all(),required=False)
+ last_ansible_hash = forms.CharField(required=False)
+
+ def __init__(self,*args,**kwargs):
+ super (VCPETenantForm,self ).__init__(*args,**kwargs)
+ self.fields['kind'].widget.attrs['readonly'] = True
+ self.fields['provider_service'].queryset = VCPEService.get_service_objects().all()
+ if self.instance:
+ # fields for the attributes
+ self.fields['bbs_account'].initial = self.instance.bbs_account
+ self.fields['creator'].initial = self.instance.creator
+ self.fields['instance'].initial = self.instance.instance
+ self.fields['last_ansible_hash'].initial = self.instance.last_ansible_hash
+ if (not self.instance) or (not self.instance.pk):
+ # default fields for an 'add' form
+ self.fields['kind'].initial = VCPE_KIND
+ self.fields['creator'].initial = get_request().user
+ if VCPEService.get_service_objects().exists():
+ self.fields["provider_service"].initial = VCPEService.get_service_objects().all()[0]
+
+ def save(self, commit=True):
+ self.instance.creator = self.cleaned_data.get("creator")
+ self.instance.instance = self.cleaned_data.get("instance")
+ self.instance.last_ansible_hash = self.cleaned_data.get("last_ansible_hash")
+ return super(VCPETenantForm, self).save(commit=commit)
+
+ class Meta:
+ model = VCPETenant
+
+class VCPETenantAdmin(ReadOnlyAwareAdmin):
+ list_display = ('backend_status_icon', 'id', 'subscriber_tenant' )
+ list_display_links = ('backend_status_icon', 'id')
+ fieldsets = [ (None, {'fields': ['backend_status_text', 'kind', 'provider_service', 'subscriber_tenant', 'service_specific_id', # 'service_specific_attribute',
+ 'bbs_account', 'creator', 'instance', 'last_ansible_hash'],
+ 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text', 'service_specific_attribute', 'bbs_account')
+ form = VCPETenantForm
+
+ suit_form_tabs = (('general','Details'),)
+
+ def queryset(self, request):
+ return VCPETenant.get_tenant_objects_by_user(request.user)
+
+#-----------------------------------------------------------------------------
+# vBNG
+#-----------------------------------------------------------------------------
+
+class VBNGServiceForm(forms.ModelForm):
+ vbng_url = forms.CharField(required=False)
+
+ def __init__(self,*args,**kwargs):
+ super (VBNGServiceForm,self ).__init__(*args,**kwargs)
+ if self.instance:
+ self.fields['vbng_url'].initial = self.instance.vbng_url
+
+ def save(self, commit=True):
+ self.instance.vbng_url = self.cleaned_data.get("vbng_url")
+ return super(VBNGServiceForm, self).save(commit=commit)
+
+ class Meta:
+ model = VBNGService
+
+class VBNGServiceAdmin(ReadOnlyAwareAdmin):
+ model = VBNGService
+ verbose_name = "vBNG Service"
+ verbose_name_plural = "vBNG Service"
+ list_display = ("backend_status_icon", "name", "enabled")
+ list_display_links = ('backend_status_icon', 'name', )
+ fieldsets = [(None, {'fields': ['backend_status_text', 'name','enabled','versionNumber', 'description', "view_url", "icon_url",
+ 'vbng_url' ],
+ 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text', )
+ inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
+ form = VBNGServiceForm
+
+ extracontext_registered_admins = True
+
+ user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
+
+ suit_form_tabs =(('general', 'vBNG Service Details'),
+ ('administration', 'Administration'),
+ #('tools', 'Tools'),
+ ('slices','Slices'),
+ ('serviceattrs','Additional Attributes'),
+ ('serviceprivileges','Privileges'),
+ )
+
+ suit_form_includes = (('vbngadmin.html', 'top', 'administration'),
+ ) #('hpctools.html', 'top', 'tools') )
+
+ def queryset(self, request):
+ return VBNGService.get_service_objects_by_user(request.user)
+
+class VBNGTenantForm(forms.ModelForm):
+ routeable_subnet = forms.CharField(required=False)
+ mapped_hostname = forms.CharField(required=False)
+ mapped_ip = forms.CharField(required=False)
+ mapped_mac = forms.CharField(required=False)
+
+ def __init__(self,*args,**kwargs):
+ super (VBNGTenantForm,self ).__init__(*args,**kwargs)
+ self.fields['kind'].widget.attrs['readonly'] = True
+ self.fields['provider_service'].queryset = VBNGService.get_service_objects().all()
+ if self.instance:
+ # fields for the attributes
+ self.fields['routeable_subnet'].initial = self.instance.routeable_subnet
+ self.fields['mapped_hostname'].initial = self.instance.mapped_hostname
+ self.fields['mapped_ip'].initial = self.instance.mapped_ip
+ self.fields['mapped_mac'].initial = self.instance.mapped_mac
+ if (not self.instance) or (not self.instance.pk):
+ # default fields for an 'add' form
+ self.fields['kind'].initial = VBNG_KIND
+ if VBNGService.get_service_objects().exists():
+ self.fields["provider_service"].initial = VBNGService.get_service_objects().all()[0]
+
+ def save(self, commit=True):
+ self.instance.routeable_subnet = self.cleaned_data.get("routeable_subnet")
+ self.instance.mapped_hostname = self.cleaned_data.get("mapped_hostname")
+ self.instance.mapped_ip = self.cleaned_data.get("mapped_ip")
+ self.instance.mapped_mac = self.cleaned_data.get("mapped_mac")
+ return super(VBNGTenantForm, self).save(commit=commit)
+
+ class Meta:
+ model = VBNGTenant
+
+class VBNGTenantAdmin(ReadOnlyAwareAdmin):
+ list_display = ('backend_status_icon', 'id', 'subscriber_tenant' )
+ list_display_links = ('backend_status_icon', 'id')
+ fieldsets = [ (None, {'fields': ['backend_status_text', 'kind', 'provider_service', 'subscriber_tenant', 'service_specific_id', # 'service_specific_attribute',
+ 'routeable_subnet', 'mapped_hostname', 'mapped_ip', 'mapped_mac'],
+ 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text', 'service_specific_attribute')
+ form = VBNGTenantForm
+
+ suit_form_tabs = (('general','Details'),)
+
+ def queryset(self, request):
+ return VBNGTenant.get_tenant_objects_by_user(request.user)
+
+#-----------------------------------------------------------------------------
+# CordSubscriberRoot
+#-----------------------------------------------------------------------------
+
+class VOLTTenantInline(XOSTabularInline):
+ model = VOLTTenant
+ fields = ['provider_service', 'subscriber_root', 'service_specific_id']
+ readonly_fields = ['provider_service', 'subscriber_root', 'service_specific_id']
+ extra = 0
+ max_num = 0
+ suit_classes = 'suit-tab suit-tab-volttenants'
+ fk_name = 'subscriber_root'
+ verbose_name = 'subscribed tenant'
+ verbose_name_plural = 'subscribed tenants'
+
+ @property
+ def selflink_reverse_path(self):
+ return "admin:cord_volttenant_change"
+
+ def queryset(self, request):
+ qs = super(VOLTTenantInline, self).queryset(request)
+ return qs.filter(kind=VOLT_KIND)
+
+class CordSubscriberRootForm(forms.ModelForm):
+ url_filter_level = forms.CharField(required = False)
+
+ def __init__(self,*args,**kwargs):
+ super (CordSubscriberRootForm,self ).__init__(*args,**kwargs)
+ self.fields['kind'].widget.attrs['readonly'] = True
+ if self.instance:
+ self.fields['url_filter_level'].initial = self.instance.url_filter_level
+ if (not self.instance) or (not self.instance.pk):
+ # default fields for an 'add' form
+ self.fields['kind'].initial = CORD_SUBSCRIBER_KIND
+
+ def save(self, commit=True):
+ self.instance.url_filter_level = self.cleaned_data.get("url_filter_level")
+ return super(CordSubscriberRootForm, self).save(commit=commit)
+
+ class Meta:
+ model = CordSubscriberRoot
+
+class CordSubscriberRootAdmin(ReadOnlyAwareAdmin):
+ list_display = ('backend_status_icon', 'id', 'name', )
+ list_display_links = ('backend_status_icon', 'id', 'name', )
+ fieldsets = [ (None, {'fields': ['backend_status_text', 'kind', 'name', 'service_specific_id', # 'service_specific_attribute',
+ 'url_filter_level'],
+ 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text', 'service_specific_attribute', 'bbs_account')
+ form = CordSubscriberRootForm
+ inlines = (VOLTTenantInline, TenantRootPrivilegeInline)
+
+ suit_form_tabs =(('general', 'Cord Subscriber Root Details'),
+ ('volttenants','VOLT Tenancy'),
+ ('tenantrootprivileges','Privileges')
+ )
+
+ def queryset(self, request):
+ return CordSubscriberRoot.get_tenant_objects_by_user(request.user)
+
+admin.site.register(VOLTService, VOLTServiceAdmin)
+admin.site.register(VOLTTenant, VOLTTenantAdmin)
+admin.site.register(VCPEService, VCPEServiceAdmin)
+admin.site.register(VCPETenant, VCPETenantAdmin)
+admin.site.register(VBNGService, VBNGServiceAdmin)
+admin.site.register(VBNGTenant, VBNGTenantAdmin)
+admin.site.register(CordSubscriberRoot, CordSubscriberRootAdmin)
+
diff --git a/xos/services/cord/models.py b/xos/services/cord/models.py
new file mode 100644
index 0000000..4b794b4
--- /dev/null
+++ b/xos/services/cord/models.py
@@ -0,0 +1,802 @@
+from django.db import models
+from core.models import Service, PlCoreBase, Slice, Instance, Tenant, TenantWithContainer, Node, Image, User, Flavor, Subscriber, NetworkParameter, NetworkParameterType, Port
+from core.models.plcorebase import StrippedCharField
+import os
+from django.db import models, transaction
+from django.forms.models import model_to_dict
+from django.db.models import Q
+from operator import itemgetter, attrgetter, methodcaller
+import traceback
+from xos.exceptions import *
+
+"""
+import os
+import sys
+sys.path.append("/opt/xos")
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+import django
+from core.models import *
+from services.hpc.models import *
+from services.cord.models import *
+django.setup()
+
+t = VOLTTenant()
+t.caller = User.objects.all()[0]
+t.save()
+
+for v in VOLTTenant.get_tenant_objects().all():
+ v.caller = User.objects.all()[0]
+ v.delete()
+
+for v in VCPETenant.get_tenant_objects().all():
+ v.caller = User.objects.all()[0]
+ v.delete()
+
+for v in VOLTTenant.get_tenant_objects().all():
+ v.caller = User.objects.all()[0]
+ v.delete()
+
+for v in VOLTTenant.get_tenant_objects().all():
+ if not v.creator:
+ v.creator= User.objects.all()[0]
+ v.save()
+
+for v in VCPETenant.get_tenant_objects().all():
+ if not v.creator:
+ v.creator= User.objects.all()[0]
+ v.save()
+"""
+
+class ConfigurationError(Exception):
+ pass
+
+VOLT_KIND = "vOLT"
+VCPE_KIND = "vCPE"
+VBNG_KIND = "vBNG"
+CORD_SUBSCRIBER_KIND = "CordSubscriberRoot"
+
+# -------------------------------------------
+# CordSubscriberRoot
+# -------------------------------------------
+
+class CordSubscriberRoot(Subscriber):
+ class Meta:
+ proxy = True
+
+ KIND = CORD_SUBSCRIBER_KIND
+
+ default_attributes = {"firewall_enable": False,
+ "firewall_rules": "accept all anywhere anywhere",
+ "url_filter_enable": False,
+ "url_filter_rules": "allow all",
+ "url_filter_level": "PG",
+ "cdn_enable": False,
+ "users": [],
+ "is_demo_user": False }
+
+ sync_attributes = ("firewall_enable",
+ "firewall_rules",
+ "url_filter_enable",
+ "url_filter_rules",
+ "cdn_enable",)
+
+ def __init__(self, *args, **kwargs):
+ super(CordSubscriberRoot, self).__init__(*args, **kwargs)
+ self.cached_volt = None
+ self._initial_url_filter_enable = self.url_filter_enable
+
+ @property
+ def volt(self):
+ volt = self.get_newest_subscribed_tenant(VOLTTenant)
+ if not volt:
+ return None
+
+ # always return the same object when possible
+ if (self.cached_volt) and (self.cached_volt.id == volt.id):
+ return self.cached_volt
+
+ #volt.caller = self.creator
+ self.cached_volt = volt
+ return volt
+
+ @property
+ def firewall_enable(self):
+ return self.get_attribute("firewall_enable", self.default_attributes["firewall_enable"])
+
+ @firewall_enable.setter
+ def firewall_enable(self, value):
+ self.set_attribute("firewall_enable", value)
+
+ @property
+ def firewall_rules(self):
+ return self.get_attribute("firewall_rules", self.default_attributes["firewall_rules"])
+
+ @firewall_rules.setter
+ def firewall_rules(self, value):
+ self.set_attribute("firewall_rules", value)
+
+ @property
+ def url_filter_enable(self):
+ return self.get_attribute("url_filter_enable", self.default_attributes["url_filter_enable"])
+
+ @url_filter_enable.setter
+ def url_filter_enable(self, value):
+ self.set_attribute("url_filter_enable", value)
+
+ @property
+ def url_filter_level(self):
+ return self.get_attribute("url_filter_level", self.default_attributes["url_filter_level"])
+
+ @url_filter_level.setter
+ def url_filter_level(self, value):
+ self.set_attribute("url_filter_level", value)
+
+ @property
+ def url_filter_rules(self):
+ return self.get_attribute("url_filter_rules", self.default_attributes["url_filter_rules"])
+
+ @url_filter_rules.setter
+ def url_filter_rules(self, value):
+ self.set_attribute("url_filter_rules", value)
+
+ @property
+ def cdn_enable(self):
+ return self.get_attribute("cdn_enable", self.default_attributes["cdn_enable"])
+
+ @cdn_enable.setter
+ def cdn_enable(self, value):
+ self.set_attribute("cdn_enable", value)
+
+ @property
+ def users(self):
+ return self.get_attribute("users", self.default_attributes["users"])
+
+ @users.setter
+ def users(self, value):
+ self.set_attribute("users", value)
+
+ def find_user(self, uid):
+ uid = int(uid)
+ for user in self.users:
+ if user["id"] == uid:
+ return user
+ return None
+
+ def update_user(self, uid, **kwargs):
+ # kwargs may be "level" or "mac"
+ # Setting one of these to None will cause None to be stored in the db
+ uid = int(uid)
+ users = self.users
+ for user in users:
+ if user["id"] == uid:
+ for arg in kwargs.keys():
+ user[arg] = kwargs[arg]
+ self.users = users
+ return user
+ raise ValueError("User %d not found" % uid)
+
+ def create_user(self, **kwargs):
+ if "name" not in kwargs:
+ raise XOSMissingField("The name field is required")
+
+ for user in self.users:
+ if kwargs["name"] == user["name"]:
+ raise XOSDuplicateKey("User %s already exists" % kwargs["name"])
+
+ uids = [x["id"] for x in self.users]
+ if uids:
+ uid = max(uids)+1
+ else:
+ uid = 0
+ newuser = kwargs.copy()
+ newuser["id"] = uid
+
+ users = self.users
+ users.append(newuser)
+ self.users = users
+
+ return newuser
+
+ def delete_user(self, uid):
+ uid = int(uid)
+ users = self.users
+ for user in users:
+ if user["id"]==uid:
+ users.remove(user)
+ self.users = users
+ return
+
+ raise ValueError("Users %d not found" % uid)
+
+ @property
+ def services(self):
+ return {"cdn": self.cdn_enable,
+ "url_filter": self.url_filter_enable,
+ "firewall": self.firewall_enable}
+
+ @services.setter
+ def services(self, value):
+ pass
+
+ def save(self, *args, **kwargs):
+ if (not hasattr(self, 'caller') or not self.caller.is_admin):
+ if (self.has_field_changed("service_specific_id")):
+ raise XOSPermissionDenied("You do not have permission to change service_specific_id")
+ super(CordSubscriberRoot, self).save(*args, **kwargs)
+ if (self.volt) and (self.volt.vcpe): # and (self._initial_url_filter_enabled != self.url_filter_enable):
+ # 1) trigger manage_bbs_account to run
+ # 2) trigger vcpe observer to wake up
+ self.volt.vcpe.save()
+
+ @property
+ def is_demo_user(self):
+ return self.get_attribute("is_demo_user", self.default_attributes["is_demo_user"])
+
+ @is_demo_user.setter
+ def is_demo_user(self, value):
+ self.set_attribute("is_demo_user", value)
+
+# -------------------------------------------
+# VOLT
+# -------------------------------------------
+
+class VOLTService(Service):
+ KIND = VOLT_KIND
+
+ class Meta:
+ app_label = "cord"
+ verbose_name = "vOLT Service"
+ proxy = True
+
+class VOLTTenant(Tenant):
+ class Meta:
+ proxy = True
+
+ KIND = VOLT_KIND
+
+ default_attributes = {"vlan_id": None, "s_tag": None, "c_tag": None}
+ def __init__(self, *args, **kwargs):
+ volt_services = VOLTService.get_service_objects().all()
+ if volt_services:
+ self._meta.get_field("provider_service").default = volt_services[0].id
+ super(VOLTTenant, self).__init__(*args, **kwargs)
+ self.cached_vcpe = None
+
+ @property
+ def s_tag(self):
+ return self.get_attribute("s_tag", self.default_attributes["s_tag"])
+
+ @s_tag.setter
+ def s_tag(self, value):
+ self.set_attribute("s_tag", value)
+
+ @property
+ def c_tag(self):
+ return self.get_attribute("c_tag", self.default_attributes["c_tag"])
+
+ @c_tag.setter
+ def c_tag(self, value):
+ self.set_attribute("c_tag", value)
+
+ # for now, vlan_id is a synonym for c_tag
+
+ @property
+ def vlan_id(self):
+ return self.c_tag
+
+ @vlan_id.setter
+ def vlan_id(self, value):
+ self.c_tag = value
+
+ @property
+ def vcpe(self):
+ vcpe = self.get_newest_subscribed_tenant(VCPETenant)
+ if not vcpe:
+ return None
+
+ # always return the same object when possible
+ if (self.cached_vcpe) and (self.cached_vcpe.id == vcpe.id):
+ return self.cached_vcpe
+
+ vcpe.caller = self.creator
+ self.cached_vcpe = vcpe
+ return vcpe
+
+ @vcpe.setter
+ def vcpe(self, value):
+ raise XOSConfigurationError("vOLT.vCPE cannot be set this way -- create a new vCPE object and set its subscriber_tenant instead")
+
+ @property
+ def subscriber(self):
+ if not self.subscriber_root:
+ return None
+ subs = CordSubscriberRoot.objects.filter(id=self.subscriber_root.id)
+ if not subs:
+ return None
+ return subs[0]
+
+ @property
+ def creator(self):
+ if getattr(self, "cached_creator", None):
+ return self.cached_creator
+ creator_id=self.get_attribute("creator_id")
+ if not creator_id:
+ return None
+ users=User.objects.filter(id=creator_id)
+ if not users:
+ return None
+ user=users[0]
+ self.cached_creator = users[0]
+ return user
+
+ @creator.setter
+ def creator(self, value):
+ if value:
+ value = value.id
+ if (value != self.get_attribute("creator_id", None)):
+ self.cached_creator=None
+ self.set_attribute("creator_id", value)
+
+ def manage_vcpe(self):
+ # Each VOLT object owns exactly one VCPE object
+
+ if self.deleted:
+ return
+
+ if self.vcpe is None:
+ vcpeServices = VCPEService.get_service_objects().all()
+ if not vcpeServices:
+ raise XOSConfigurationError("No VCPE Services available")
+
+ vcpe = VCPETenant(provider_service = vcpeServices[0],
+ subscriber_tenant = self)
+ vcpe.caller = self.creator
+ vcpe.save()
+
+ def manage_subscriber(self):
+ if (self.subscriber_root is None):
+ # The vOLT is not connected to a Subscriber, so either find an
+ # existing subscriber with the same SSID, or autogenerate a new
+ # subscriber.
+ #
+ # TODO: This probably goes away when we rethink the ONOS-to-XOS
+ # vOLT API.
+
+ subs = CordSubscriberRoot.get_tenant_objects().filter(service_specific_id = self.service_specific_id)
+ if subs:
+ sub = subs[0]
+ else:
+ sub = CordSubscriberRoot(service_specific_id = self.service_specific_id,
+ name = "autogenerated-for-vOLT-%s" % self.id)
+ sub.save()
+ self.subscriber_root = sub
+ self.save()
+
+ def cleanup_vcpe(self):
+ if self.vcpe:
+ # print "XXX cleanup vcpe", self.vcpe
+ self.vcpe.delete()
+
+ def cleanup_orphans(self):
+ # ensure vOLT only has one vCPE
+ cur_vcpe = self.vcpe
+ for vcpe in list(self.get_subscribed_tenants(VCPETenant)):
+ if (not cur_vcpe) or (vcpe.id != cur_vcpe.id):
+ # print "XXX clean up orphaned vcpe", vcpe
+ vcpe.delete()
+
+ def save(self, *args, **kwargs):
+ self.validate_unique_service_specific_id()
+
+ if (self.subscriber_root is not None):
+ subs = self.subscriber_root.get_subscribed_tenants(VOLTTenant)
+ if (subs) and (self not in subs):
+ raise XOSDuplicateKey("Subscriber should only be linked to one vOLT")
+
+ if not self.creator:
+ if not getattr(self, "caller", None):
+ # caller must be set when creating a vCPE since it creates a slice
+ raise XOSProgrammingError("VOLTTenant's self.caller was not set")
+ self.creator = self.caller
+ if not self.creator:
+ raise XOSProgrammingError("VOLTTenant's self.creator was not set")
+
+ super(VOLTTenant, self).save(*args, **kwargs)
+ model_policy_volt(self.pk)
+ #self.manage_vcpe()
+ #self.manage_subscriber()
+ #self.cleanup_orphans()
+
+ def delete(self, *args, **kwargs):
+ self.cleanup_vcpe()
+ super(VOLTTenant, self).delete(*args, **kwargs)
+
+def model_policy_volt(pk):
+ # TODO: this should be made in to a real model_policy
+ with transaction.atomic():
+ volt = VOLTTenant.objects.select_for_update().filter(pk=pk)
+ if not volt:
+ return
+ volt = volt[0]
+ volt.manage_vcpe()
+ volt.manage_subscriber()
+ volt.cleanup_orphans()
+
+# -------------------------------------------
+# VCPE
+# -------------------------------------------
+
+class VCPEService(Service):
+ KIND = VCPE_KIND
+
+ simple_attributes = ( ("bbs_api_hostname", None),
+ ("bbs_api_port", None),
+ ("bbs_server", None),
+ ("backend_network_label", "hpc_client"), )
+
+ def __init__(self, *args, **kwargs):
+ super(VCPEService, self).__init__(*args, **kwargs)
+
+ class Meta:
+ app_label = "cord"
+ verbose_name = "vCPE Service"
+ proxy = True
+
+ def allocate_bbs_account(self):
+ vcpes = VCPETenant.get_tenant_objects().all()
+ bbs_accounts = [vcpe.bbs_account for vcpe in vcpes]
+
+ # There's a bit of a race here; some other user could be trying to
+ # allocate a bbs_account at the same time we are.
+
+ for i in range(2,21):
+ account_name = "bbs%02d@onlab.us" % i
+ if (account_name not in bbs_accounts):
+ return account_name
+
+ raise XOSConfigurationError("We've run out of available broadbandshield accounts. Delete some vcpe and try again.")
+
+ @property
+ def bbs_slice(self):
+ bbs_slice_id=self.get_attribute("bbs_slice_id")
+ if not bbs_slice_id:
+ return None
+ bbs_slices=Slice.objects.filter(id=bbs_slice_id)
+ if not bbs_slices:
+ return None
+ return bbs_slices[0]
+
+ @bbs_slice.setter
+ def bbs_slice(self, value):
+ if value:
+ value = value.id
+ self.set_attribute("bbs_slice_id", value)
+
+VCPEService.setup_simple_attributes()
+
+
+class VCPETenant(TenantWithContainer):
+ class Meta:
+ proxy = True
+
+ KIND = VCPE_KIND
+
+ sync_attributes = ("nat_ip", "nat_mac",
+ "lan_ip", "lan_mac",
+ "wan_ip", "wan_mac", "wan_container_mac",
+ "private_ip", "private_mac",
+ "hpc_client_ip", "hpc_client_mac")
+
+ default_attributes = {"instance_id": None,
+ "container_id": None,
+ "users": [],
+ "bbs_account": None,
+ "last_ansible_hash": None}
+
+ def __init__(self, *args, **kwargs):
+ super(VCPETenant, self).__init__(*args, **kwargs)
+ self.cached_vbng=None
+
+ @property
+ def vbng(self):
+ vbng = self.get_newest_subscribed_tenant(VBNGTenant)
+ if not vbng:
+ return None
+
+ # always return the same object when possible
+ if (self.cached_vbng) and (self.cached_vbng.id == vbng.id):
+ return self.cached_vbng
+
+ vbng.caller = self.creator
+ self.cached_vbng = vbng
+ return vbng
+
+ @vbng.setter
+ def vbng(self, value):
+ raise XOSConfigurationError("vCPE.vBNG cannot be set this way -- create a new vBNG object and set it's subscriber_tenant instead")
+
+ @property
+ def volt(self):
+ if not self.subscriber_tenant:
+ return None
+ volts = VOLTTenant.objects.filter(id=self.subscriber_tenant.id)
+ if not volts:
+ return None
+ return volts[0]
+
+ @property
+ def bbs_account(self):
+ return self.get_attribute("bbs_account", self.default_attributes["bbs_account"])
+
+ @bbs_account.setter
+ def bbs_account(self, value):
+ return self.set_attribute("bbs_account", value)
+
+ @property
+ def last_ansible_hash(self):
+ return self.get_attribute("last_ansible_hash", self.default_attributes["last_ansible_hash"])
+
+ @last_ansible_hash.setter
+ def last_ansible_hash(self, value):
+ return self.set_attribute("last_ansible_hash", value)
+
+ @property
+ def ssh_command(self):
+ if self.instance:
+ return self.instance.get_ssh_command()
+ else:
+ return "no-instance"
+
+ @ssh_command.setter
+ def ssh_command(self, value):
+ pass
+
+ @property
+ def addresses(self):
+ if self.instance:
+ ports = self.instance.ports.all()
+ elif self.container:
+ ports = self.container.ports.all()
+ else:
+ return {}
+
+ addresses = {}
+ for ns in ports:
+ if "lan" in ns.network.name.lower():
+ addresses["lan"] = (ns.ip, ns.mac)
+ elif "wan" in ns.network.name.lower():
+ addresses["wan"] = (ns.ip, ns.mac)
+ elif "private" in ns.network.name.lower():
+ addresses["private"] = (ns.ip, ns.mac)
+ elif "nat" in ns.network.name.lower():
+ addresses["nat"] = (ns.ip, ns.mac)
+ elif "hpc_client" in ns.network.name.lower():
+ addresses["hpc_client"] = (ns.ip, ns.mac)
+ return addresses
+
+ @property
+ def nat_ip(self):
+ return self.addresses.get("nat", (None,None) )[0]
+
+ @property
+ def nat_mac(self):
+ return self.addresses.get("nat", (None,None) )[1]
+
+ @property
+ def lan_ip(self):
+ return self.addresses.get("lan", (None, None) )[0]
+
+ @property
+ def lan_mac(self):
+ return self.addresses.get("lan", (None, None) )[1]
+
+ @property
+ def wan_ip(self):
+ return self.addresses.get("wan", (None, None) )[0]
+
+ @property
+ def wan_mac(self):
+ return self.addresses.get("wan", (None, None) )[1]
+
+ # Generate the MAC for the container interface connected to WAN
+ @property
+ def wan_container_mac(self):
+ (a, b, c, d) = self.wan_ip.split('.')
+ return "02:42:%02x:%02x:%02x:%02x" % (int(a), int(b), int(c), int(d))
+
+ @property
+ def private_ip(self):
+ return self.addresses.get("private", (None, None) )[0]
+
+ @property
+ def private_mac(self):
+ return self.addresses.get("private", (None, None) )[1]
+
+ @property
+ def hpc_client_ip(self):
+ return self.addresses.get("hpc_client", (None, None) )[0]
+
+ @property
+ def hpc_client_mac(self):
+ return self.addresses.get("hpc_client", (None, None) )[1]
+
+ @property
+ def is_synced(self):
+ return (self.enacted is not None) and (self.enacted >= self.updated)
+
+ @is_synced.setter
+ def is_synced(self, value):
+ pass
+
+ def manage_vbng(self):
+ # Each vCPE object owns exactly one vBNG object
+
+ if self.deleted:
+ return
+
+ if self.vbng is None:
+ vbngServices = VBNGService.get_service_objects().all()
+ if not vbngServices:
+ raise XOSConfigurationError("No VBNG Services available")
+
+ vbng = VBNGTenant(provider_service = vbngServices[0],
+ subscriber_tenant = self)
+ vbng.caller = self.creator
+ vbng.save()
+
+ def cleanup_vbng(self):
+ if self.vbng:
+ # print "XXX cleanup vnbg", self.vbng
+ self.vbng.delete()
+
+ def cleanup_orphans(self):
+ # ensure vCPE only has one vBNG
+ cur_vbng = self.vbng
+ for vbng in list(self.get_subscribed_tenants(VBNGTenant)):
+ if (not cur_vbng) or (vbng.id != cur_vbng.id):
+ # print "XXX clean up orphaned vbng", vbng
+ vbng.delete()
+
+ if self.orig_instance_id and (self.orig_instance_id != self.get_attribute("instance_id")):
+ instances=Instance.objects.filter(id=self.orig_instance_id)
+ if instances:
+ # print "XXX clean up orphaned instance", instances[0]
+ instances[0].delete()
+
+ def manage_bbs_account(self):
+ if self.deleted:
+ return
+
+ if self.volt and self.volt.subscriber and self.volt.subscriber.url_filter_enable:
+ if not self.bbs_account:
+ # make sure we use the proxied VCPEService object, not the generic Service object
+ vcpe_service = VCPEService.objects.get(id=self.provider_service.id)
+ self.bbs_account = vcpe_service.allocate_bbs_account()
+ super(VCPETenant, self).save()
+ else:
+ if self.bbs_account:
+ self.bbs_account = None
+ super(VCPETenant, self).save()
+
+ def find_or_make_port(self, instance, network, **kwargs):
+ port = Port.objects.filter(instance=instance, network=network)
+ if port:
+ port = port[0]
+ else:
+ port = Port(instance=instance, network=network, **kwargs)
+ port.save()
+ return port
+
+ def save_instance(self, instance):
+ with transaction.atomic():
+ instance.volumes = "/etc/dnsmasq.d,/etc/ufw"
+ super(VCPETenant, self).save_instance(instance)
+
+ if instance.isolation in ["container", "container_vm"]:
+ lan_networks = [x for x in instance.slice.networks.all() if "lan" in x.name]
+ if not lan_networks:
+ raise XOSProgrammingError("No lan_network")
+ port = self.find_or_make_port(instance, lan_networks[0], ip="192.168.0.1", port_id="unmanaged")
+ port.set_parameter("c_tag", self.volt.c_tag)
+ port.set_parameter("s_tag", self.volt.s_tag)
+ port.set_parameter("device", "eth1")
+ port.set_parameter("bridge", "br-lan")
+
+ wan_networks = [x for x in instance.slice.networks.all() if "wan" in x.name]
+ if not wan_networks:
+ raise XOSProgrammingError("No wan_network")
+ port = self.find_or_make_port(instance, wan_networks[0])
+ port.set_parameter("next_hop", value="10.0.1.253") # FIX ME
+ port.set_parameter("device", "eth0")
+
+ def save(self, *args, **kwargs):
+ if not self.creator:
+ if not getattr(self, "caller", None):
+ # caller must be set when creating a vCPE since it creates a slice
+ raise XOSProgrammingError("VCPETenant's self.caller was not set")
+ self.creator = self.caller
+ if not self.creator:
+ raise XOSProgrammingError("VCPETenant's self.creator was not set")
+
+ super(VCPETenant, self).save(*args, **kwargs)
+ model_policy_vcpe(self.pk)
+ #self.manage_instance()
+ #self.manage_vbng()
+ #self.manage_bbs_account()
+ #self.cleanup_orphans()
+
+ def delete(self, *args, **kwargs):
+ self.cleanup_vbng()
+ self.cleanup_container()
+ super(VCPETenant, self).delete(*args, **kwargs)
+
+def model_policy_vcpe(pk):
+ # TODO: this should be made in to a real model_policy
+ with transaction.atomic():
+ vcpe = VCPETenant.objects.select_for_update().filter(pk=pk)
+ if not vcpe:
+ return
+ vcpe = vcpe[0]
+ vcpe.manage_container()
+ vcpe.manage_vbng()
+ vcpe.manage_bbs_account()
+ vcpe.cleanup_orphans()
+
+#----------------------------------------------------------------------------
+# vBNG
+#----------------------------------------------------------------------------
+
+class VBNGService(Service):
+ KIND = VBNG_KIND
+
+ simple_attributes = ( ("vbng_url", ""), ) # "http://10.0.3.136:8181/onos/virtualbng/"
+
+ class Meta:
+ app_label = "cord"
+ verbose_name = "vBNG Service"
+ proxy = True
+
+VBNGService.setup_simple_attributes()
+
+class VBNGTenant(Tenant):
+ class Meta:
+ proxy = True
+
+ KIND = VBNG_KIND
+
+ default_attributes = {"routeable_subnet": "",
+ "mapped_ip": "",
+ "mapped_mac": "",
+ "mapped_hostname": ""}
+
+ @property
+ def routeable_subnet(self):
+ return self.get_attribute("routeable_subnet", self.default_attributes["routeable_subnet"])
+
+ @routeable_subnet.setter
+ def routeable_subnet(self, value):
+ self.set_attribute("routeable_subnet", value)
+
+ @property
+ def mapped_ip(self):
+ return self.get_attribute("mapped_ip", self.default_attributes["mapped_ip"])
+
+ @mapped_ip.setter
+ def mapped_ip(self, value):
+ self.set_attribute("mapped_ip", value)
+
+ @property
+ def mapped_mac(self):
+ return self.get_attribute("mapped_mac", self.default_attributes["mapped_mac"])
+
+ @mapped_mac.setter
+ def mapped_mac(self, value):
+ self.set_attribute("mapped_mac", value)
+
+ @property
+ def mapped_hostname(self):
+ return self.get_attribute("mapped_hostname", self.default_attributes["mapped_hostname"])
+
+ @mapped_hostname.setter
+ def mapped_hostname(self, value):
+ self.set_attribute("mapped_hostname", value)
diff --git a/xos/cord/rest_examples/add_volt_tenant.sh b/xos/services/cord/rest_examples/add_volt_tenant.sh
similarity index 100%
rename from xos/cord/rest_examples/add_volt_tenant.sh
rename to xos/services/cord/rest_examples/add_volt_tenant.sh
diff --git a/xos/cord/rest_examples/config.sh b/xos/services/cord/rest_examples/config.sh
similarity index 100%
rename from xos/cord/rest_examples/config.sh
rename to xos/services/cord/rest_examples/config.sh
diff --git a/xos/cord/rest_examples/delete_volt_tenant.sh b/xos/services/cord/rest_examples/delete_volt_tenant.sh
similarity index 100%
rename from xos/cord/rest_examples/delete_volt_tenant.sh
rename to xos/services/cord/rest_examples/delete_volt_tenant.sh
diff --git a/xos/cord/rest_examples/list_cord_subscribers.sh b/xos/services/cord/rest_examples/list_cord_subscribers.sh
similarity index 100%
rename from xos/cord/rest_examples/list_cord_subscribers.sh
rename to xos/services/cord/rest_examples/list_cord_subscribers.sh
diff --git a/xos/cord/rest_examples/list_volt_tenants.sh b/xos/services/cord/rest_examples/list_volt_tenants.sh
similarity index 100%
rename from xos/cord/rest_examples/list_volt_tenants.sh
rename to xos/services/cord/rest_examples/list_volt_tenants.sh
diff --git a/xos/services/cord/templates/vbngadmin.html b/xos/services/cord/templates/vbngadmin.html
new file mode 100644
index 0000000..cceaee0
--- /dev/null
+++ b/xos/services/cord/templates/vbngadmin.html
@@ -0,0 +1,6 @@
+<div class = "row text-center">
+ <div class="col-xs-12">
+ <a class="btn btn-primary" href="/admin/cord/vbngtenant/">vBNG Tenants</a>
+ </div>
+</div>
+
diff --git a/xos/services/cord/templates/vcpeadmin.html b/xos/services/cord/templates/vcpeadmin.html
new file mode 100644
index 0000000..a21dabe
--- /dev/null
+++ b/xos/services/cord/templates/vcpeadmin.html
@@ -0,0 +1,9 @@
+<div class = "row text-center">
+ <div class="col-xs-6">
+ <a class="btn btn-primary" href="/admin/cord/vcpetenant/">vCPE Tenants</a>
+ </div>
+ <div class="col-xs-6">
+ <a class="btn btn-primary" href="/admin/dashboard/cord/">Subscriber View</a>
+ </div>
+</div>
+
diff --git a/xos/services/cord/templates/voltadmin.html b/xos/services/cord/templates/voltadmin.html
new file mode 100644
index 0000000..e6887c5
--- /dev/null
+++ b/xos/services/cord/templates/voltadmin.html
@@ -0,0 +1,6 @@
+<div class = "row text-center">
+ <div class="col-xs-12">
+ <a href="/admin/cord/volttenant/">vOLT Tenants</a>
+ </div>
+</div>
+
diff --git a/xos/helloworld/__init__.py b/xos/services/helloworld/__init__.py
similarity index 100%
rename from xos/helloworld/__init__.py
rename to xos/services/helloworld/__init__.py
diff --git a/xos/helloworld/models.py b/xos/services/helloworld/models.py
similarity index 100%
rename from xos/helloworld/models.py
rename to xos/services/helloworld/models.py
diff --git a/xos/services/helloworld/view.py b/xos/services/helloworld/view.py
new file mode 100644
index 0000000..6ad9ae1
--- /dev/null
+++ b/xos/services/helloworld/view.py
@@ -0,0 +1,57 @@
+from django.http import HttpResponse
+from django.views.generic import TemplateView, View
+from django import template
+from core.models import *
+from services.helloworld.models import *
+import json
+import os
+import time
+import tempfile
+
+class HelloWorldView(TemplateView):
+ head_template = r"""{% extends "admin/dashboard/dashboard_base.html" %}
+ {% load admin_static %}
+ {% block content %}
+ """
+
+ tail_template = r"{% endblock %}"
+
+ def get(self, request, name="root", *args, **kwargs):
+ head_template = self.head_template
+ tail_template = self.tail_template
+
+ try:
+ hello_name = request.GET['hello_name']
+ world_name = request.GET['world_name']
+ instance_id_str = request.GET['instance_id']
+ instance_id = int(instance_id_str)
+
+ i = Instance.objects.get(pk=instance_id)
+ i.pk=None
+ i.userData=None
+ i.instance_id=None
+ i.instance_name=None
+ i.enacted=None
+ i.save()
+ h = Hello(name=hello_name,instance_backref=i)
+ h.save()
+ w = World(hello=h,name=world_name)
+ w.save()
+
+ t = template.Template(head_template + 'Done. New instance id: %r'%i.pk + self.tail_template)
+ except KeyError:
+ html = """<form>
+ Hello string: <input type="text" name="hello_name" placeholder="Planet"><br>
+ World string: <input type="text" name="world_name" placeholder="Earth"><br>
+ Id of instance to copy: <input type="text" name="instance_id" placeholder="3"><br>
+ <input type="submit" value="Submit">
+ </form>"""
+
+ t = template.Template(head_template + html + self.tail_template)
+
+ response_kwargs = {}
+ response_kwargs.setdefault('content_type', self.content_type)
+ return self.response_class(
+ request = request,
+ template = t,
+ **response_kwargs)
diff --git a/xos/helloworldservice_complete/__init__.py b/xos/services/helloworldservice_complete/__init__.py
similarity index 100%
rename from xos/helloworldservice_complete/__init__.py
rename to xos/services/helloworldservice_complete/__init__.py
diff --git a/xos/services/helloworldservice_complete/admin.py b/xos/services/helloworldservice_complete/admin.py
new file mode 100644
index 0000000..3c8e793
--- /dev/null
+++ b/xos/services/helloworldservice_complete/admin.py
@@ -0,0 +1,141 @@
+
+from core.admin import ReadOnlyAwareAdmin, SliceInline
+from core.middleware import get_request
+from core.models import User
+from django import forms
+from django.contrib import admin
+from services.helloworldservice_complete.models import HelloWorldServiceComplete, HelloWorldTenantComplete, HELLO_WORLD_KIND
+
+# The class to provide an admin interface on the web for the service.
+# We do only configuration here and don't change any logic because the logic
+# is taken care of for us by ReadOnlyAwareAdmin
+class HelloWorldServiceCompleteAdmin(ReadOnlyAwareAdmin):
+ # We must set the model so that the admin knows what fields to use
+ model = HelloWorldServiceComplete
+ verbose_name = "Hello World Service"
+ verbose_name_plural = "Hello World Services"
+
+ # Setting list_display creates columns on the admin page, each value here
+ # is a column, the column is populated for every instance of the model.
+ list_display = ("backend_status_icon", "name", "enabled")
+
+ # Used to indicate which values in the columns of the admin form are links.
+ list_display_links = ('backend_status_icon', 'name', )
+
+ # Denotes the sections of the form, the fields in the section, and the
+ # CSS classes used to style them. We represent this as a set of tuples, each
+ # tuple as a name (or None) and a set of fields and classes.
+ # Here the first section does not have a name so we use none. That first
+ # section has several fields indicated in the 'fields' attribute, and styled
+ # by the classes indicated in the 'classes' attribute. The classes given
+ # here are important for rendering the tabs on the form. To give the tabs
+ # we must assign the classes suit-tab and suit-tab-<name> where
+ # where <name> will be used later.
+ fieldsets = [(None, {'fields': ['backend_status_text', 'name', 'enabled',
+ 'versionNumber', 'description', "view_url"],
+ 'classes':['suit-tab suit-tab-general']})]
+
+ # Denotes the fields that are readonly and cannot be changed.
+ readonly_fields = ('backend_status_text', )
+
+ # Inlines are used to denote other models that can be edited on the same
+ # form as this one. In this case the service form also allows changes
+ # to slices.
+ inlines = [SliceInline]
+
+ extracontext_registered_admins = True
+
+ # Denotes the fields that can be changed by an admin but not be all users
+ user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
+
+ # Associates fieldsets from this form and from the inlines.
+ # The format here are tuples, of (<name>, tab title). <name> comes from the
+ # <name> in the fieldsets.
+ suit_form_tabs = (('general', 'Hello World Service Details'),
+ ('administration', 'Tenants'),
+ ('slices', 'Slices'),)
+
+ # Used to include a template for a tab. Here we include the
+ # helloworldserviceadmin template in the top position for the administration
+ # tab.
+ suit_form_includes = (('helloworldserviceadmin.html',
+ 'top',
+ 'administration'),)
+
+ # Used to get the objects for this model that are associated with the
+ # requesting user.
+ def queryset(self, request):
+ return HelloWorldServiceComplete.get_service_objects_by_user(request.user)
+
+# Class to represent the form to add and edit tenants.
+# We need to define this instead of just using an admin like we did for the
+# service because tenants vary more than services and there isn't a common form.
+# This allows us to change the python behavior for the admin form to save extra
+# fields and control defaults.
+class HelloWorldTenantCompleteForm(forms.ModelForm):
+ # Defines a field for the creator of this service. It is a dropdown which
+ # is populated with all of the users.
+ creator = forms.ModelChoiceField(queryset=User.objects.all())
+ # Defines a text field for the display message, it is not required.
+ display_message = forms.CharField(required=False)
+
+ def __init__(self, *args, **kwargs):
+ super(HelloWorldTenantCompleteForm, self).__init__(*args, **kwargs)
+ # Set the kind field to readonly
+ self.fields['kind'].widget.attrs['readonly'] = True
+ # Define the logic for obtaining the objects for the provider_service
+ # dropdown of the tenant form.
+ self.fields[
+ 'provider_service'].queryset = HelloWorldServiceComplete.get_service_objects().all()
+ # Set the initial kind to HELLO_WORLD_KIND for this tenant.
+ self.fields['kind'].initial = HELLO_WORLD_KIND
+ # If there is an instance of this model then we can set the initial
+ # form values to the existing values.
+ if self.instance:
+ self.fields['creator'].initial = self.instance.creator
+ self.fields[
+ 'display_message'].initial = self.instance.display_message
+
+ # If there is not an instance then we need to set initial values.
+ if (not self.instance) or (not self.instance.pk):
+ self.fields['creator'].initial = get_request().user
+ if HelloWorldServiceComplete.get_service_objects().exists():
+ self.fields["provider_service"].initial = HelloWorldServiceComplete.get_service_objects().all()[0]
+
+ # This function describes what happens when the save button is pressed on
+ # the tenant form. In this case we set the values for the instance that were
+ # entered.
+ def save(self, commit=True):
+ self.instance.creator = self.cleaned_data.get("creator")
+ self.instance.display_message = self.cleaned_data.get(
+ "display_message")
+ return super(HelloWorldTenantCompleteForm, self).save(commit=commit)
+
+ class Meta:
+ model = HelloWorldTenantComplete
+
+# Define the admin form for the tenant. This uses a similar structure as the
+# service but uses HelloWorldTenantCompleteForm to change the python behavior.
+
+
+class HelloWorldTenantCompleteAdmin(ReadOnlyAwareAdmin):
+ verbose_name = "Hello World Tenant"
+ verbose_name_plural = "Hello World Tenants"
+ list_display = ('id', 'backend_status_icon', 'instance', 'display_message')
+ list_display_links = ('backend_status_icon', 'instance', 'display_message',
+ 'id')
+ fieldsets = [(None, {'fields': ['backend_status_text', 'kind',
+ 'provider_service', 'instance', 'creator',
+ 'display_message'],
+ 'classes': ['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text', 'instance',)
+ form = HelloWorldTenantCompleteForm
+
+ suit_form_tabs = (('general', 'Details'),)
+
+ def queryset(self, request):
+ return HelloWorldTenantComplete.get_tenant_objects_by_user(request.user)
+
+# Associate the admin forms with the models.
+admin.site.register(HelloWorldServiceComplete, HelloWorldServiceCompleteAdmin)
+admin.site.register(HelloWorldTenantComplete, HelloWorldTenantCompleteAdmin)
diff --git a/xos/helloworldservice_complete/models.py b/xos/services/helloworldservice_complete/models.py
similarity index 100%
rename from xos/helloworldservice_complete/models.py
rename to xos/services/helloworldservice_complete/models.py
diff --git a/xos/helloworldservice_complete/templates/helloworldserviceadmin.html b/xos/services/helloworldservice_complete/templates/helloworldserviceadmin.html
similarity index 100%
rename from xos/helloworldservice_complete/templates/helloworldserviceadmin.html
rename to xos/services/helloworldservice_complete/templates/helloworldserviceadmin.html
diff --git a/xos/hpc/__init__.py b/xos/services/hpc/__init__.py
similarity index 100%
rename from xos/hpc/__init__.py
rename to xos/services/hpc/__init__.py
diff --git a/xos/services/hpc/admin.py b/xos/services/hpc/admin.py
new file mode 100644
index 0000000..d9f28c6
--- /dev/null
+++ b/xos/services/hpc/admin.py
@@ -0,0 +1,228 @@
+from django.contrib import admin
+
+from services.hpc.models import *
+from django import forms
+from django.utils.safestring import mark_safe
+from django.contrib.auth.admin import UserAdmin
+from django.contrib.admin.widgets import FilteredSelectMultiple
+from django.contrib.auth.forms import ReadOnlyPasswordHashField
+from django.contrib.auth.signals import user_logged_in
+from django.utils import timezone
+from django.contrib.contenttypes import generic
+from suit.widgets import LinkedSelect
+from core.admin import ServiceAppAdmin,SliceInline,ServiceAttrAsTabInline, ReadOnlyAwareAdmin, XOSTabularInline, SliderWidget, ServicePrivilegeInline
+from core.middleware import get_request
+
+from functools import update_wrapper
+from django.contrib.admin.views.main import ChangeList
+from django.core.urlresolvers import reverse, NoReverseMatch
+from django.contrib.admin.utils import quote
+
+from filteredadmin import FilteredChangeList, FilteredAdmin, FilteredInline
+
+class HpcServiceForm(forms.ModelForm):
+ scale = forms.IntegerField(widget = SliderWidget, required=False)
+
+ def __init__(self, *args, **kwargs):
+ super(HpcServiceForm, self).__init__(*args, **kwargs)
+ if ("instance" in kwargs) and (hasattr(kwargs["instance"], "scale")):
+ self.fields['scale'].initial = kwargs["instance"].scale
+
+ def save(self, *args, **kwargs):
+ if self.cleaned_data['scale']:
+ self.instance.scale = self.cleaned_data['scale']
+
+ return super(HpcServiceForm, self).save(*args, **kwargs)
+
+class HpcServiceAdmin(ReadOnlyAwareAdmin):
+ model = HpcService
+ verbose_name = "HPC Service"
+ verbose_name_plural = "HPC Service"
+ list_display = ("backend_status_icon", "name","enabled")
+ list_display_links = ('backend_status_icon', 'name', )
+ fieldsets = [(None, {'fields': ['backend_status_text', 'name','scale','enabled','versionNumber', 'description', "cmi_hostname", "hpc_port80", "watcher_hpc_network", "watcher_dnsredir_network", "watcher_dnsdemux_network"], 'classes':['suit-tab suit-tab-general']})]
+ readonly_fields = ('backend_status_text', )
+ inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
+ form = HpcServiceForm
+
+ extracontext_registered_admins = True
+
+ user_readonly_fields = ["name", "enabled", "versionNumber", "description"]
+
+ suit_form_tabs =(('general', 'HPC Service Details'),
+ ('administration', 'Administration'),
+ ('tools', 'Tools'),
+ ('slices','Slices'),
+ ('serviceattrs','Additional Attributes'),
+ ('serviceprivileges','Privileges'),
+ )
+
+ suit_form_includes = (('hpcadmin.html', 'top', 'administration'),
+ ('hpctools.html', 'top', 'tools') )
+
+ def url_for_model_changelist(self, request, model):
+ if not request.resolver_match.args:
+ return reverse('admin:%s_%s_changelist' % (model._meta.app_label, model._meta.model_name), current_app=model._meta.app_label)
+ else:
+ obj_id = request.resolver_match.args[0]
+ changelist_url = reverse('admin:%s_%s_filteredchangelist' % (model._meta.app_label, model._meta.model_name), args=(obj_id,), current_app=model._meta.app_label)
+ return changelist_url
+
+class HPCAdmin(FilteredAdmin):
+ # Change the application breadcrumb to point to an HPC Service if one is
+ # defined
+
+ custom_app_breadcrumb_name = "Hpc"
+ @property
+ def custom_app_breadcrumb_url(self):
+ services = HpcService.objects.all()
+ if len(services)==1:
+ return "/admin/hpc/hpcservice/%s/" % services[0].id
+ else:
+ return "/admin/hpc/hpcservice/"
+
+class CDNPrefixInline(FilteredInline):
+ model = CDNPrefix
+ extra = 0
+ suit_classes = 'suit-tab suit-tab-prefixes'
+ fields = ('backend_status_icon', 'cdn_prefix_id', 'prefix', 'defaultOriginServer', 'enabled')
+ readonly_fields = ('backend_status_icon', 'cdn_prefix_id',)
+
+class OriginServerInline(FilteredInline):
+ model = OriginServer
+ extra = 0
+ suit_classes = 'suit-tab suit-tab-origins'
+ fields = ('backend_status_icon', 'origin_server_id', 'url')
+ readonly_fields = ('backend_status_icon', 'origin_server_id')
+
+class ContentProviderInline(FilteredInline):
+ model = ContentProvider
+ extra = 0
+ suit_classes = 'suit-tab suit-tab-cps'
+ fields = ('backend_status_icon', 'content_provider_id', 'name', 'enabled')
+ readonly_fields = ('backend_status_icon', 'content_provider_id',)
+
+class OriginServerAdmin(HPCAdmin):
+ list_display = ('backend_status_icon', 'url','protocol','redirects','contentProvider','authenticated','enabled' )
+ list_display_links = ('backend_status_icon', 'url', )
+
+ fields = ('backend_status_text', 'url','protocol','redirects','contentProvider','authenticated','enabled','origin_server_id','description' )
+ readonly_fields = ('backend_status_text', 'origin_server_id',)
+ user_readonly_fields = ('url','protocol','redirects','contentProvider','authenticated','enabled','origin_server_id','description')
+
+class ContentProviderForm(forms.ModelForm):
+ users = forms.ModelMultipleChoiceField(
+ queryset=User.objects.all(),
+ required=False,
+ help_text="Select which users can manage this ContentProvider",
+ widget=FilteredSelectMultiple(
+ verbose_name=('Users'), is_stacked=False
+ )
+ )
+
+ class Meta:
+ model = ContentProvider
+ widgets = {
+ 'serviceProvider' : LinkedSelect
+ }
+
+ def __init__(self, *args, **kwargs):
+ request = kwargs.pop('request', None)
+ super(ContentProviderForm, self).__init__(*args, **kwargs)
+
+ if self.instance and self.instance.pk:
+ self.fields['users'].initial = self.instance.users.all()
+
+class ContentProviderAdmin(HPCAdmin):
+ form = ContentProviderForm
+ list_display = ('backend_status_icon', 'name','description','enabled' )
+ list_display_links = ('backend_status_icon', 'name', )
+ readonly_fields = ('backend_status_text', )
+ admin_readonly_fields = ('backend_status_text', )
+ cp_readonly_fields = ('backend_status_text', 'name', 'enabled', 'serviceProvider', 'users')
+ fieldsets = [ (None, {'fields': ['backend_status_text', 'name','enabled','description','serviceProvider','users'], 'classes':['suit-tab suit-tab-general']})]
+
+ inlines = [CDNPrefixInline, OriginServerInline]
+
+ user_readonly_fields = ('name','description','enabled','serviceProvider','users')
+
+ suit_form_tabs = (('general','Details'),('prefixes','CDN Prefixes'), ('origins','Origin Servers'))
+
+ def change_view(self,request, *args, **kwargs):
+ if request.user.is_admin:
+ self.readonly_fields = self.admin_readonly_fields
+ else:
+ self.readonly_fields = self.cp_readonly_fields
+
+ return super(ContentProviderAdmin, self).change_view(request, *args, **kwargs)
+
+ def has_add_permission(self, request):
+ return request.user.is_admin
+
+ def has_delete_permission(self, request, obj=None):
+ return request.user.is_admin
+
+class ServiceProviderAdmin(HPCAdmin):
+ list_display = ('backend_status_icon', 'name', 'description', 'enabled')
+ list_display_links = ('backend_status_icon', 'name', )
+ fieldsets = [
+ (None, {'fields': ['backend_status_text', 'name','description','enabled', 'hpcService'], 'classes':['suit-tab suit-tab-general']})]
+#, ('Content Providers', {'fields':['contentProviders'],'classes':['suit-tab suit-tab-cps']})]
+
+ readonly_fields = ('backend_status_text', )
+ user_readonly_fields = ('name', 'description', 'enabled')
+
+ suit_form_tabs = (('general','Details'),('cps','Content Providers'))
+ inlines = [ContentProviderInline]
+
+class CDNPrefixForm(forms.ModelForm):
+ class Meta:
+ widgets = {
+ 'contentProvider' : LinkedSelect
+ }
+
+class CDNPrefixAdmin(HPCAdmin):
+ form = CDNPrefixForm
+ list_display = ['backend_status_icon', 'prefix','contentProvider']
+ list_display_links = ('backend_status_icon', 'prefix', )
+ fields = ['backend_status_text', 'prefix', 'contentProvider', 'cdn_prefix_id', 'description', 'defaultOriginServer', 'enabled']
+ readonly_fields = ('backend_status_text', )
+ user_readonly_fields = ['prefix','contentProvider', "cdn_prefix_id", "description", "defaultOriginServer", "enabled"]
+
+class SiteMapAdmin(HPCAdmin):
+ model = SiteMap
+ verbose_name = "Site Map"
+ verbose_name_plural = "Site Map"
+ list_display = ("backend_status_icon", "name", "contentProvider", "serviceProvider")
+ list_display_links = ('backend_status_icon', 'name', )
+ fields = ['backend_status_text', 'name', 'hpcService', 'cdnPrefix', 'contentProvider', 'serviceProvider', 'map', 'map_id']
+ user_readonly_fields = ('backend_status_text', "name", "hpcService", "cdnPrefix", "contentProvider", "serviceProvider", "description", "map")
+ readonly_fields = ('backend_status_text', )
+
+class AccessMapAdmin(HPCAdmin):
+ model = AccessMap
+ verbose_name = "Access Map"
+ verbose_name_plural = "Access Map"
+ list_display = ("backend_status_icon", "name", "contentProvider")
+ list_display_links = ('backend_status_icon', 'name', )
+ user_readonly_fields = ('backend_status_text', "name", "contentProvider", "description", "map")
+ readonly_fields = ('backend_status_text', )
+
+class HpcHealthCheckAdmin(HPCAdmin):
+ model = HpcHealthCheck
+ verbose_name = "Health Check"
+ verbose_name = "Health Checks"
+ list_display = ["backend_status_icon", "resource_name", "kind"]
+ list_display_links = ["backend_status_icon", "resource_name"]
+ fields = ["backend_status_text", "hpcService", "resource_name", "kind", "result_contains", "result_min_size", "result_max_size"]
+ readonly_fields = ["backend_status_text",]
+
+admin.site.register(ServiceProvider, ServiceProviderAdmin)
+admin.site.register(ContentProvider, ContentProviderAdmin)
+admin.site.register(CDNPrefix, CDNPrefixAdmin)
+admin.site.register(OriginServer,OriginServerAdmin)
+admin.site.register(HpcService, HpcServiceAdmin)
+admin.site.register(SiteMap, SiteMapAdmin)
+admin.site.register(AccessMap, AccessMapAdmin)
+admin.site.register(HpcHealthCheck, HpcHealthCheckAdmin)
+
diff --git a/xos/services/hpc/filteredadmin.py b/xos/services/hpc/filteredadmin.py
new file mode 100644
index 0000000..b677b54
--- /dev/null
+++ b/xos/services/hpc/filteredadmin.py
@@ -0,0 +1,191 @@
+from django.contrib import admin
+
+from django import forms
+from services.hpc.models import HpcService
+from core.admin import ServiceAppAdmin,SliceInline,ServiceAttrAsTabInline, ReadOnlyAwareAdmin, XOSTabularInline, SliderWidget, ServicePrivilegeInline
+from core.middleware import get_request
+
+from functools import update_wrapper
+from django.contrib.admin.views.main import ChangeList
+from django.core.urlresolvers import reverse, NoReverseMatch
+from django.contrib.admin.utils import quote
+
+import threading
+_thread_locals = threading.local()
+
+class FilteredChangeList(ChangeList):
+ """ A special ChangeList with a doctored url_for_result function that
+ points to the filteredchange view instead of the default change
+ view.
+ """
+
+ def __init__(self, request, *args, **kwargs):
+ self.service = getattr(request, "hpcService", None)
+ self.embedded = getattr(request, "embedded", False)
+ super(FilteredChangeList, self).__init__(request, *args, **kwargs)
+
+ def url_for_result(self, result):
+ if (self.service is None):
+ return super(FilteredChangeList, self).url_for_result(result)
+
+ pk = getattr(result, self.pk_attname)
+ if self.embedded:
+ return reverse('admin:%s_%s_embeddedfilteredchange' % (self.opts.app_label,
+ self.opts.model_name),
+ args=(quote(self.service.id), quote(pk),),
+ current_app=self.model_admin.admin_site.name)
+
+ else:
+ return reverse('admin:%s_%s_filteredchange' % (self.opts.app_label,
+ self.opts.model_name),
+ args=(quote(self.service.id), quote(pk),),
+ current_app=self.model_admin.admin_site.name)
+
+class FilteredAdmin(ReadOnlyAwareAdmin):
+ """
+ One approach to filtering the HPC Admin views by HPCService. Encode
+ the HPCService into the URL for the changelist view. Then we could do our
+ custom filtering in self.filtered_changelist_view.
+
+ To make this work, a few changes needed to be made to the change and
+ change_list templates.
+
+ 1) "custom_changelist_breadcrumb_url" is used to replace the breadcrumb
+ in change and add views with one that will point back to the filtered
+ list.
+
+ 2) "custom_add_url" is used to replace the Add button's URL with one
+ that points to the filtered add view.
+
+ TODO: Save & Add Another,
+ the add link when the changelist is empty
+ """
+
+ @property
+ def change_list_template(self):
+ return _thread_locals.change_list_template
+
+ @property
+ def change_form_template(self):
+ return _thread_locals.change_form_template
+
+ def get_urls(self):
+ from django.conf.urls import patterns, url
+
+ def wrap(view):
+ def wrapper(*args, **kwargs):
+ return self.admin_site.admin_view(view)(*args, **kwargs)
+ return update_wrapper(wrapper, view)
+
+ urls = super(FilteredAdmin, self).get_urls()
+ info = self.model._meta.app_label, self.model._meta.model_name
+ my_urls = [
+ url(r'^(.+)/filteredlist/$', wrap(self.filtered_changelist_view), name="%s_%s_filteredchangelist" % info),
+ url(r'^(.+)/embeddedfilteredlist/$', wrap(self.embedded_filtered_changelist_view), name="%s_%s_embeddedfilteredchangelist" % info),
+ url(r'^(.+)/(.+)/filteredchange$', wrap(self.filtered_change_view), name='%s_%s_filteredchange' % info),
+ url(r'^(.+)/(.+)/embeddedfilteredchange$', wrap(self.embedded_filtered_change_view), name='%s_%s_embeddedfilteredchange' % info),
+ url(r'^(.+)/filteredadd/$', wrap(self.filtered_add_view), name='%s_%s_filteredadd' % info),
+ url(r'^(.+)/embeddedfilteredadd/$', wrap(self.embedded_filtered_add_view), name='%s_%s_embeddedfilteredadd' % info),
+ ]
+ return my_urls + urls
+
+ def add_extra_context(self, request, extra_context):
+ super(FilteredAdmin, self).add_extra_context(request, extra_context)
+
+ if getattr(request,"hpcService",None) is not None:
+ extra_context["custom_changelist_breadcrumb_url"] = "/admin/hpc/%s/%s/filteredlist/" % (self.model._meta.model_name, str(request.hpcService.id))
+ if getattr(request,"embedded",False):
+ extra_context["custom_add_url"] = "/admin/hpc/%s/%s/embeddedfilteredadd/" % (self.model._meta.model_name, str(request.hpcService.id))
+ else:
+ extra_context["custom_add_url"] = "/admin/hpc/%s/%s/filteredadd/" % (self.model._meta.model_name, str(request.hpcService.id))
+ if len(request.resolver_match.args)>1:
+ # this is only useful on change views, not changelist views
+ extra_context["custom_delete_url"] = "/admin/hpc/%s/%s/delete/" % (self.model._meta.model_name, request.resolver_match.args[1])
+
+ extra_context["show_save"] = False
+ extra_context["show_save_and_add_another"] = False
+
+ def changelist_view(self, *args, **kwargs):
+ if "template" in kwargs:
+ _thread_locals.change_list_template = kwargs["template"]
+ del kwargs["template"]
+ else:
+ _thread_locals.change_list_template = "admin/change_list_bc.html"
+ return super(FilteredAdmin, self).changelist_view(*args, **kwargs)
+
+ def filtered_changelist_view(self, request, hpcServiceId, extra_context=None):
+ request.hpcService = HpcService.objects.get(id=hpcServiceId)
+ return self.changelist_view(request, extra_context=extra_context)
+
+ def embedded_filtered_changelist_view(self, request, hpcServiceId, extra_context=None):
+ request.hpcService = HpcService.objects.get(id=hpcServiceId)
+ request.embedded = True
+ return self.changelist_view(request, template="admin/change_list_embedded.html", extra_context=extra_context)
+
+ def change_view(self, *args, **kwargs):
+ if "template" in kwargs:
+ _thread_locals.change_form_template = kwargs["template"]
+ del kwargs["template"]
+ else:
+ _thread_locals.change_form_template = "admin/change_form_bc.html"
+ return super(FilteredAdmin, self).change_view(*args, **kwargs)
+
+ def filtered_change_view(self, request, hpcServiceId, object_id, extra_context=None):
+ request.hpcService = HpcService.objects.get(id=hpcServiceId)
+ return self.change_view(request, object_id, extra_context=extra_context)
+
+ def embedded_filtered_change_view(self, request, hpcServiceId, object_id, extra_context=None):
+ request.hpcService = HpcService.objects.get(id=hpcServiceId)
+ request.embedded = True
+ return self.change_view(request, object_id, template="admin/change_form_embedded.html", extra_context=extra_context)
+
+ def add_view(self, *args, **kwargs):
+ if "template" in kwargs:
+ _thread_locals.change_form_template = kwargs["template"]
+ del kwargs["template"]
+ else:
+ _thread_locals.change_form_template = "admin/change_form_bc.html"
+ return super(FilteredAdmin, self).add_view(*args, **kwargs)
+
+ def filtered_add_view(self, request, hpcServiceId, extra_context=None):
+ request.hpcService = HpcService.objects.get(id=hpcServiceId)
+ return self.add_view(request, extra_context=extra_context)
+
+ def embedded_filtered_add_view(self, request, hpcServiceId, extra_context=None):
+ request.hpcService = HpcService.objects.get(id=hpcServiceId)
+ request.embedded = True
+ return self.add_view(request, template="admin/change_form_embedded.html", extra_context=extra_context)
+
+ def get_queryset(self, request):
+ # request.hpcService will be set in filtered_changelist_view so we can
+ # use it to filter what will be displayed in the list.
+ qs = self.model.objects.all()
+ if (getattr(request,"hpcService",None) is not None) and (hasattr(self.model, "filter_by_hpcService")):
+ qs = self.model.filter_by_hpcService(qs, request.hpcService)
+ return qs
+
+ def get_changelist(self, request, **kwargs):
+ # We implement a custom ChangeList, so the URLs point to the
+ # filtered_change_view rather than the default change_view.
+ return FilteredChangeList
+
+class FilteredInline(XOSTabularInline):
+ def get_change_url(self, id):
+ request = get_request()
+ embedded = getattr(request, "embedded", False)
+ service_id = request.resolver_match.args[0]
+
+ if embedded:
+ reverse_path = "admin:%s_embeddedfilteredchange" % (self.selflink_model._meta.db_table)
+ args = (service_id, id)
+ else:
+ reverse_path = "admin:%s_filteredchange" % (self.selflink_model._meta.db_table)
+ args = (service_id, id)
+
+ try:
+ url = reverse(reverse_path, args=args, current_app=self.selflink_model._meta.app_label)
+ except NoReverseMatch:
+ return None
+
+ return url
+
diff --git a/xos/hpc/migrations/0001_initial.py b/xos/services/hpc/migrations/0001_initial.py
similarity index 100%
rename from xos/hpc/migrations/0001_initial.py
rename to xos/services/hpc/migrations/0001_initial.py
diff --git a/xos/hpc/migrations/__init__.py b/xos/services/hpc/migrations/__init__.py
similarity index 100%
rename from xos/hpc/migrations/__init__.py
rename to xos/services/hpc/migrations/__init__.py
diff --git a/xos/hpc/models.py b/xos/services/hpc/models.py
similarity index 100%
rename from xos/hpc/models.py
rename to xos/services/hpc/models.py
diff --git a/xos/hpc/templates/hpcadmin.html b/xos/services/hpc/templates/hpcadmin.html
similarity index 100%
rename from xos/hpc/templates/hpcadmin.html
rename to xos/services/hpc/templates/hpcadmin.html
diff --git a/xos/hpc/templates/hpctools.html b/xos/services/hpc/templates/hpctools.html
similarity index 100%
rename from xos/hpc/templates/hpctools.html
rename to xos/services/hpc/templates/hpctools.html
diff --git a/xos/hpc/tests.py b/xos/services/hpc/tests.py
similarity index 100%
rename from xos/hpc/tests.py
rename to xos/services/hpc/tests.py
diff --git a/xos/hpc/views.py b/xos/services/hpc/views.py
similarity index 100%
rename from xos/hpc/views.py
rename to xos/services/hpc/views.py
diff --git a/xos/services/onos/admin.py b/xos/services/onos/admin.py
index d13a991..3f9f96c 100644
--- a/xos/services/onos/admin.py
+++ b/xos/services/onos/admin.py
@@ -21,19 +21,19 @@
class ONOSServiceForm(forms.ModelForm):
use_external_host = forms.CharField(required=False)
- def __init__(self,*args,**kwargs):
- super (ONOSServiceForm,self ).__init__(*args,**kwargs)
- if self.instance:
- # fields for the attributes
- self.fields['use_external_host'].initial = self.instance.use_external_host
-
- def save(self, commit=True):
- self.instance.use_external_host = self.cleaned_data.get("use_external_host")
- return super(ONOSServiceForm, self).save(commit=commit)
-
- class Meta:
- model = ONOSService
-
+ def __init__(self,*args,**kwargs):
+ super (ONOSServiceForm,self ).__init__(*args,**kwargs)
+ if self.instance:
+ # fields for the attributes
+ self.fields['use_external_host'].initial = self.instance.use_external_host
+
+ def save(self, commit=True):
+ self.instance.use_external_host = self.cleaned_data.get("use_external_host")
+ return super(ONOSServiceForm, self).save(commit=commit)
+
+ class Meta:
+ model = ONOSService
+
class ONOSServiceAdmin(ReadOnlyAwareAdmin):
model = ONOSService
verbose_name = "ONOS Service"
@@ -67,29 +67,29 @@
name = forms.CharField()
dependencies = forms.CharField(required=False)
- def __init__(self,*args,**kwargs):
- super (ONOSAppForm,self ).__init__(*args,**kwargs)
- self.fields['kind'].widget.attrs['readonly'] = True
- self.fields['provider_service'].queryset = ONOSService.get_service_objects().all()
- if self.instance:
- # fields for the attributes
- self.fields['creator'].initial = self.instance.creator
- self.fields['name'].initial = self.instance.name
- self.fields['dependencies'].initial = self.instance.dependencies
- if (not self.instance) or (not self.instance.pk):
- # default fields for an 'add' form
- self.fields['kind'].initial = ONOS_KIND
- self.fields['creator'].initial = get_request().user
- if ONOSService.get_service_objects().exists():
- self.fields["provider_service"].initial = ONOSService.get_service_objects().all()[0]
-
- def save(self, commit=True):
- self.instance.creator = self.cleaned_data.get("creator")
- self.instance.name = self.cleaned_data.get("name")
- self.instance.dependencies = self.cleaned_data.get("dependencies")
- return super(ONOSAppForm, self).save(commit=commit)
-
- class Meta:
+ def __init__(self,*args,**kwargs):
+ super (ONOSAppForm,self ).__init__(*args,**kwargs)
+ self.fields['kind'].widget.attrs['readonly'] = True
+ self.fields['provider_service'].queryset = ONOSService.get_service_objects().all()
+ if self.instance:
+ # fields for the attributes
+ self.fields['creator'].initial = self.instance.creator
+ self.fields['name'].initial = self.instance.name
+ self.fields['dependencies'].initial = self.instance.dependencies
+ if (not self.instance) or (not self.instance.pk):
+ # default fields for an 'add' form
+ self.fields['kind'].initial = ONOS_KIND
+ self.fields['creator'].initial = get_request().user
+ if ONOSService.get_service_objects().exists():
+ self.fields["provider_service"].initial = ONOSService.get_service_objects().all()[0]
+
+ def save(self, commit=True):
+ self.instance.creator = self.cleaned_data.get("creator")
+ self.instance.name = self.cleaned_data.get("name")
+ self.instance.dependencies = self.cleaned_data.get("dependencies")
+ return super(ONOSAppForm, self).save(commit=commit)
+
+ class Meta:
model = ONOSApp
class ONOSAppAdmin(ReadOnlyAwareAdmin):
diff --git a/xos/requestrouter/__init__.py b/xos/services/requestrouter/__init__.py
similarity index 100%
rename from xos/requestrouter/__init__.py
rename to xos/services/requestrouter/__init__.py
diff --git a/xos/services/requestrouter/admin.py b/xos/services/requestrouter/admin.py
new file mode 100644
index 0000000..6d9e2fe
--- /dev/null
+++ b/xos/services/requestrouter/admin.py
@@ -0,0 +1,63 @@
+from django.contrib import admin
+
+from services.requestrouter.models import *
+from django import forms
+from django.utils.safestring import mark_safe
+from django.contrib.auth.admin import UserAdmin
+from django.contrib.admin.widgets import FilteredSelectMultiple
+from django.contrib.auth.forms import ReadOnlyPasswordHashField
+from django.contrib.auth.signals import user_logged_in
+from django.utils import timezone
+from django.contrib.contenttypes import generic
+from suit.widgets import LinkedSelect
+from core.admin import ServiceAppAdmin,SliceInline,ServiceAttrAsTabInline, ReadOnlyAwareAdmin, ServicePrivilegeInline
+
+class RequestRouterAdmin(ReadOnlyAwareAdmin):
+ # Change the application breadcrumb to point to an RR Service if one is
+ # defined
+
+ change_form_template = "admin/change_form_bc.html"
+ change_list_template = "admin/change_list_bc.html"
+ custom_app_breadcrumb_name = "Request Router"
+ @property
+ def custom_app_breadcrumb_url(self):
+ services = RequestRouterService.objects.all()
+ if len(services)==1:
+ return "/admin/requestrouter/requestrouterservice/%s/" % services[0].id
+ else:
+ return "/admin/requestrouter/requestrouterservice/"
+
+class RequestRouterServiceAdmin(ServiceAppAdmin):
+ model = RequestRouterService
+ verbose_name = "Request Router Service"
+ verbose_name_plural = "Request Router Service"
+ list_display = ("name","enabled")
+ fieldsets = [(None, {'fields': ['name','enabled','versionNumber', 'description','behindNat','defaultTTL','defaultAction','lastResortAction','maxAnswers'], 'classes':['suit-tab suit-tab-general']})]
+ inlines = [SliceInline,ServiceAttrAsTabInline,ServicePrivilegeInline]
+
+ user_readonly_fields = ["name", "enabled", "versionNumber", "description", "behindNat", "defaultTTL", "defaultAction", "lastResortAction", "maxAnswers"]
+
+ suit_form_tabs =(('general', 'Request Router Service Details'),
+ ('administration', 'Administration'),
+ ('slices','Slices'),
+ ('serviceattrs','Additional Attributes'),
+ ('serviceprivileges','Privileges'),
+ )
+
+ suit_form_includes = (('rradmin.html', 'top', 'administration'),)
+
+class ServiceMapAdmin(RequestRouterAdmin):
+ model = ServiceMap
+ verbose_name = "Service Map"
+ verbose_name_plural = "Service Map"
+ list_display = ("name", "owner", "slice", "prefix")
+ fieldsets = [(None, {'fields': ['name','owner','slice', 'prefix','siteMap','accessMap'], 'classes':['suit-tab suit-tab-general']})]
+
+ user_readonly_fields = ["name", "owner", "slice", "prefix", "siteMap", "accessMap"]
+
+ suit_form_tabs =(('general', 'Service Map Details'),
+ )
+
+admin.site.register(RequestRouterService, RequestRouterServiceAdmin)
+admin.site.register(ServiceMap, ServiceMapAdmin)
+
diff --git a/xos/requestrouter/migrations/0001_initial.py b/xos/services/requestrouter/migrations/0001_initial.py
similarity index 100%
rename from xos/requestrouter/migrations/0001_initial.py
rename to xos/services/requestrouter/migrations/0001_initial.py
diff --git a/xos/requestrouter/migrations/__init__.py b/xos/services/requestrouter/migrations/__init__.py
similarity index 100%
rename from xos/requestrouter/migrations/__init__.py
rename to xos/services/requestrouter/migrations/__init__.py
diff --git a/xos/requestrouter/models.py b/xos/services/requestrouter/models.py
similarity index 100%
rename from xos/requestrouter/models.py
rename to xos/services/requestrouter/models.py
diff --git a/xos/requestrouter/templates/rradmin.html b/xos/services/requestrouter/templates/rradmin.html
similarity index 100%
rename from xos/requestrouter/templates/rradmin.html
rename to xos/services/requestrouter/templates/rradmin.html
diff --git a/xos/syndicate_storage/__init__.py b/xos/services/syndicate_storage/__init__.py
similarity index 100%
rename from xos/syndicate_storage/__init__.py
rename to xos/services/syndicate_storage/__init__.py
diff --git a/xos/services/syndicate_storage/admin.py b/xos/services/syndicate_storage/admin.py
new file mode 100644
index 0000000..779f83b
--- /dev/null
+++ b/xos/services/syndicate_storage/admin.py
@@ -0,0 +1,158 @@
+from django.contrib import admin
+
+from services.syndicate_storage.models import *
+from django import forms
+from django.utils.safestring import mark_safe
+from django.contrib.auth.admin import UserAdmin
+from django.contrib.admin.widgets import FilteredSelectMultiple
+from django.contrib.auth.forms import ReadOnlyPasswordHashField
+from django.contrib.auth.signals import user_logged_in
+from django.utils import timezone
+from django.contrib.contenttypes import generic
+from suit.widgets import LinkedSelect
+from core.admin import ReadOnlyAwareAdmin,ServiceAppAdmin,SliceInline,ServiceAttrAsTabInline,XOSBaseAdmin, XOSTabularInline
+from suit.widgets import LinkedSelect
+from django.core.exceptions import ValidationError, ObjectDoesNotExist
+
+class SyndicateAdmin(ReadOnlyAwareAdmin):
+ # Change the application breadcrumb to point to an RR Service if one is
+ # defined
+
+ change_form_template = "admin/change_form_bc.html"
+ change_list_template = "admin/change_list_bc.html"
+ custom_app_breadcrumb_name = "Syndicate_Storage"
+ @property
+ def custom_app_breadcrumb_url(self):
+ services = SyndicateService.objects.all()
+ if len(services)==1:
+ return "/admin/syndicate_storage/syndicateservice/%s/" % services[0].id
+ else:
+ return "/admin/syncdicate_storage/syndicateservice/"
+
+class SyndicateServiceAdmin(ServiceAppAdmin):
+ model = SyndicateService
+ verbose_name = "Syndicate Storage"
+ verbose_name_plural = "Syndicate Storage"
+ list_display = ("name","enabled")
+ fieldsets = [(None, {'fields': ['name','enabled','versionNumber', 'description',], 'classes':['suit-tab suit-tab-general']})]
+ inlines = [SliceInline,ServiceAttrAsTabInline]
+
+ user_readonly_fields = ['name','enabled','versionNumber','description']
+
+ suit_form_tabs =(('general', 'Syndicate Storage Details'),
+ ('administration', 'Administration'),
+ ('slices','Slices'),
+ ('serviceattrs','Additional Attributes'),
+ )
+
+ suit_form_includes = (('syndicateadmin.html', 'top', 'administration'),)
+
+
+class VolumeAccessRightInline(XOSTabularInline):
+ model = VolumeAccessRight
+ extra = 0
+ suit_classes = 'suit-tab suit-tab-volumeAccessRights'
+
+
+class VolumeSliceFormSet( forms.models.BaseInlineFormSet ):
+ # verify that our VolumeSlice is valid
+
+ @classmethod
+ def verify_unchanged( cls, volume_pk, slice_pk, field_name, new_value ):
+ vs = None
+ try:
+ vs = VolumeSlice.objects.get( volume_id=volume_pk, slice_id=slice_pk )
+ except ObjectDoesNotExist, dne:
+ return True, None
+
+ old_value = getattr( vs, field_name )
+ if old_value != new_value:
+ return False, old_value
+ else:
+ return True, None
+
+
+ def clean( self ):
+ for form in self.forms:
+ # check each inline's cleaned data, if it's valid
+ cleaned_data = None
+ try:
+ if form.cleaned_data:
+ cleaned_data = form.cleaned_data
+ except AttributeError:
+ continue
+
+ # verify that the ports haven't changed
+ volume_pk = cleaned_data['volume_id'].pk
+ slice_pk = cleaned_data['slice_id'].pk
+
+ if not cleaned_data.has_key('UG_portnum'):
+ raise ValidationError("Missing UG port number")
+
+ if not cleaned_data.has_key('RG_portnum'):
+ raise ValidationError("Missing RG port number")
+
+ rc1, old_peer_port = VolumeSliceFormSet.verify_unchanged( volume_pk, slice_pk, 'UG_portnum', cleaned_data['UG_portnum'] )
+ rc2, old_replicate_port = VolumeSliceFormSet.verify_unchanged( volume_pk, slice_pk, 'RG_portnum', cleaned_data['RG_portnum'] )
+
+ err1str = ""
+ err2str = ""
+ if not rc1:
+ err1str = "change %s back to %s" % (cleaned_data['UG_portnum'], old_peer_port)
+ if not rc2:
+ err2str = " and change %s back to %s" % (cleaned_data['RG_portnum'], old_replicate_port )
+
+ if not rc1 or not rc2:
+ raise ValidationError("At this time, port numbers cannot be changed once they are set. Please %s %s" % (err1str, err2str))
+
+
+
+class VolumeSliceInline(XOSTabularInline):
+ model = VolumeSlice
+ extra = 0
+ suit_classes = 'suit-tab suit-tab-volumeSlices'
+ fields = ['volume_id', 'slice_id', 'cap_read_data', 'cap_write_data', 'cap_host_data', 'UG_portnum', 'RG_portnum']
+
+ formset = VolumeSliceFormSet
+
+ readonly_fields = ['credentials_blob']
+
+
+class VolumeAdmin(SyndicateAdmin):
+ model = Volume
+
+ def get_readonly_fields(self, request, obj=None ):
+ always_readonly = []
+ if obj == None:
+ # all fields are editable on add
+ return always_readonly
+
+ else:
+ # can't change owner, slice id, or block size on update
+ return ['blocksize', 'owner_id'] + always_readonly
+
+
+ list_display = ['name', 'owner_id']
+
+ detailsFieldList = ['name', 'owner_id', 'description','blocksize', 'private','archive', 'cap_read_data', 'cap_write_data', 'cap_host_data' ]
+
+ fieldsets = [
+ (None, {'fields': detailsFieldList, 'classes':['suit-tab suit-tab-general']}),
+ ]
+
+ inlines = [VolumeAccessRightInline, VolumeSliceInline]
+
+ user_readonly_fields = ['name','owner_id','description','blocksize','private', 'archive', 'cap_read_data', 'cap_write_data', 'cap_host_data']
+
+ suit_form_tabs =(('general', 'Volume Details'),
+ ('volumeSlices', 'Slices'),
+ ('volumeAccessRights', 'Volume Access Rights'))
+
+ def queryset(self, request):
+ # only show volumes that are public, or owned by the caller
+ return Volume.select_by_user(request.user)
+
+
+# left panel:
+admin.site.register(SyndicateService, SyndicateServiceAdmin)
+admin.site.register(Volume, VolumeAdmin)
diff --git a/xos/services/syndicate_storage/migrations/0001_initial.py b/xos/services/syndicate_storage/migrations/0001_initial.py
new file mode 100644
index 0000000..f0065ce
--- /dev/null
+++ b/xos/services/syndicate_storage/migrations/0001_initial.py
@@ -0,0 +1,127 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+import services.syndicate_storage.models
+import django.utils.timezone
+from django.conf import settings
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ('core', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='SliceSecret',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('secret', services.syndicate_storage.models.ObserverSecretValue(help_text=b"Shared secret between OpenCloud and this slice's Syndicate daemons.", blank=True)),
+ ('slice_id', models.ForeignKey(to='core.Slice')),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ migrations.CreateModel(
+ name='SyndicatePrincipal',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('created', models.DateTimeField(default=django.utils.timezone.now, auto_now_add=True)),
+ ('updated', models.DateTimeField(default=django.utils.timezone.now, auto_now=True)),
+ ('enacted', models.DateTimeField(default=None, null=True, blank=True)),
+ ('backend_status', models.CharField(default=b'Provisioning in progress', max_length=140)),
+ ('deleted', models.BooleanField(default=False)),
+ ('principal_id', models.TextField(unique=True)),
+ ('public_key_pem', models.TextField()),
+ ('sealed_private_key', models.TextField()),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ migrations.CreateModel(
+ name='SyndicateService',
+ fields=[
+ ('service_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='core.Service')),
+ ],
+ options={
+ 'verbose_name': 'Syndicate Service',
+ 'verbose_name_plural': 'Syndicate Service',
+ },
+ bases=('core.service', models.Model),
+ ),
+ migrations.CreateModel(
+ name='Volume',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('created', models.DateTimeField(default=django.utils.timezone.now, auto_now_add=True)),
+ ('updated', models.DateTimeField(default=django.utils.timezone.now, auto_now=True)),
+ ('enacted', models.DateTimeField(default=None, null=True, blank=True)),
+ ('backend_status', models.CharField(default=b'Provisioning in progress', max_length=140)),
+ ('deleted', models.BooleanField(default=False)),
+ ('name', models.CharField(help_text=b'Human-readable, searchable name of the Volume', max_length=64)),
+ ('description', models.TextField(help_text=b'Human-readable description of what this Volume is used for.', max_length=130, null=True, blank=True)),
+ ('blocksize', models.PositiveIntegerField(help_text=b'Number of bytes per block.')),
+ ('private', models.BooleanField(default=True, help_text=b'Indicates if the Volume is visible to users other than the Volume Owner and Syndicate Administrators.')),
+ ('archive', models.BooleanField(default=False, help_text=b'Indicates if this Volume is read-only, and only an Aquisition Gateway owned by the Volume owner (or Syndicate admin) can write to it.')),
+ ('cap_read_data', models.BooleanField(default=True, help_text=b'VM can read Volume data')),
+ ('cap_write_data', models.BooleanField(default=True, help_text=b'VM can write Volume data')),
+ ('cap_host_data', models.BooleanField(default=True, help_text=b'VM can host Volume data')),
+ ('owner_id', models.ForeignKey(verbose_name=b'Owner', to=settings.AUTH_USER_MODEL)),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ migrations.CreateModel(
+ name='VolumeAccessRight',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('created', models.DateTimeField(default=django.utils.timezone.now, auto_now_add=True)),
+ ('updated', models.DateTimeField(default=django.utils.timezone.now, auto_now=True)),
+ ('enacted', models.DateTimeField(default=None, null=True, blank=True)),
+ ('backend_status', models.CharField(default=b'Provisioning in progress', max_length=140)),
+ ('deleted', models.BooleanField(default=False)),
+ ('cap_read_data', models.BooleanField(default=True, help_text=b'VM can read Volume data')),
+ ('cap_write_data', models.BooleanField(default=True, help_text=b'VM can write Volume data')),
+ ('cap_host_data', models.BooleanField(default=True, help_text=b'VM can host Volume data')),
+ ('owner_id', models.ForeignKey(verbose_name=b'user', to=settings.AUTH_USER_MODEL)),
+ ('volume', models.ForeignKey(to='syndicate_storage.Volume')),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ migrations.CreateModel(
+ name='VolumeSlice',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('created', models.DateTimeField(default=django.utils.timezone.now, auto_now_add=True)),
+ ('updated', models.DateTimeField(default=django.utils.timezone.now, auto_now=True)),
+ ('enacted', models.DateTimeField(default=None, null=True, blank=True)),
+ ('backend_status', models.CharField(default=b'Provisioning in progress', max_length=140)),
+ ('deleted', models.BooleanField(default=False)),
+ ('cap_read_data', models.BooleanField(default=True, help_text=b'VM can read Volume data')),
+ ('cap_write_data', models.BooleanField(default=True, help_text=b'VM can write Volume data')),
+ ('cap_host_data', models.BooleanField(default=True, help_text=b'VM can host Volume data')),
+ ('UG_portnum', models.PositiveIntegerField(help_text=b'User Gateway port. Any port above 1024 will work, but it must be available slice-wide.', verbose_name=b'UG port')),
+ ('RG_portnum', models.PositiveIntegerField(help_text=b'Replica Gateway port. Any port above 1024 will work, but it must be available slice-wide.', verbose_name=b'RG port')),
+ ('credentials_blob', models.TextField(help_text=b'Encrypted slice credentials, sealed with the slice secret.', null=True, blank=True)),
+ ('slice_id', models.ForeignKey(verbose_name=b'Slice', to='core.Slice')),
+ ('volume_id', models.ForeignKey(verbose_name=b'Volume', to='syndicate_storage.Volume')),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ migrations.AddField(
+ model_name='volume',
+ name='slice_id',
+ field=models.ManyToManyField(to='core.Slice', through='syndicate_storage.VolumeSlice'),
+ preserve_default=True,
+ ),
+ ]
diff --git a/xos/syndicate_storage/migrations/__init__.py b/xos/services/syndicate_storage/migrations/__init__.py
similarity index 100%
rename from xos/syndicate_storage/migrations/__init__.py
rename to xos/services/syndicate_storage/migrations/__init__.py
diff --git a/xos/services/syndicate_storage/models.py b/xos/services/syndicate_storage/models.py
new file mode 100644
index 0000000..27db059
--- /dev/null
+++ b/xos/services/syndicate_storage/models.py
@@ -0,0 +1,259 @@
+from core.models import User,Site,Service,SingletonModel,PlCoreBase,Slice,SlicePrivilege
+import os
+from django.db import models
+from django.db.models import Q
+from django.forms.models import model_to_dict
+from django.core.exceptions import ValidationError, ObjectDoesNotExist
+
+# Create your models here.
+
+class SyndicateService(SingletonModel,Service):
+ class Meta:
+ app_label = "syndicate_storage"
+ verbose_name = "Syndicate Service"
+ verbose_name_plural = "Syndicate Service"
+
+ def __unicode__(self): return u'Syndicate Service'
+
+
+class SyndicatePrincipal(PlCoreBase):
+ class Meta:
+ app_label = "syndicate_storage"
+
+ # for now, this is a user email address
+ principal_id = models.TextField(unique=True)
+ public_key_pem = models.TextField()
+ sealed_private_key = models.TextField()
+
+ def __unicode__self(self): return "%s" % self.principal_id
+
+
+class Volume(PlCoreBase):
+ class Meta:
+ app_label = "syndicate_storage"
+
+ name = models.CharField(max_length=64, help_text="Human-readable, searchable name of the Volume")
+
+ owner_id = models.ForeignKey(User, verbose_name='Owner')
+
+ description = models.TextField(null=True, blank=True,max_length=130, help_text="Human-readable description of what this Volume is used for.")
+ blocksize = models.PositiveIntegerField(help_text="Number of bytes per block.")
+ private = models.BooleanField(default=True, help_text="Indicates if the Volume is visible to users other than the Volume Owner and Syndicate Administrators.")
+ archive = models.BooleanField(default=False, help_text="Indicates if this Volume is read-only, and only an Aquisition Gateway owned by the Volume owner (or Syndicate admin) can write to it.")
+
+ cap_read_data = models.BooleanField(default=True, help_text="VM can read Volume data")
+ cap_write_data = models.BooleanField(default=True, help_text="VM can write Volume data")
+ cap_host_data = models.BooleanField(default=True, help_text="VM can host Volume data")
+
+ slice_id = models.ManyToManyField(Slice, through="VolumeSlice")
+
+ def __unicode__(self): return self.name
+
+
+ @staticmethod
+ def select_by_user(user):
+ """
+ Only return Volumes accessible by the user.
+ Admin users can see everything.
+ """
+ if user.is_admin:
+ qs = Volume.objects.all()
+ else:
+ qs = Volume.objects.filter( Q(owner_id=user) | Q(private=False) )
+
+ return qs
+
+
+class VolumeAccessRight(PlCoreBase):
+ class Meta:
+ app_label = "syndicate_storage"
+
+ owner_id = models.ForeignKey(User, verbose_name='user')
+
+ volume = models.ForeignKey(Volume)
+
+ cap_read_data = models.BooleanField(default=True, help_text="VM can read Volume data")
+ cap_write_data = models.BooleanField(default=True, help_text="VM can write Volume data")
+ cap_host_data = models.BooleanField(default=True, help_text="VM can host Volume data")
+
+
+ def __unicode__(self): return "%s-%s" % (self.owner_id.email, self.volume.name)
+
+
+class ObserverSecretValue( models.TextField ):
+ class Meta:
+ app_label = "syndicate_storage"
+
+ __metaclass__ = models.SubfieldBase
+
+ MAGIC_PREFIX = "$SECRET$:"
+
+ @classmethod
+ def is_encrypted( cls, secret_str ):
+ # all encrypted secrets start with MAGIC_PREFIX, which is NOT base64-encoded
+ return secret_str.startswith( cls.MAGIC_PREFIX )
+
+ @classmethod
+ def unserialize( cls, serialized_ciphertext ):
+ # strip prefix and return ciphertext
+ return serialized_ciphertext[len(cls.MAGIC_PREFIX):]
+
+ @classmethod
+ def serialize( cls, ciphertext ):
+ # prepend a magic prefix so we know it's encrypted
+ return cls.MAGIC_PREFIX + ciphertext
+
+ def to_python( self, secret_str ):
+ """
+ Decrypt the value with the Observer key
+ """
+
+ # is this in the clear?
+ if not ObserverSecretValue.is_encrypted( secret_str ):
+ # nothing to do
+ return secret_str
+
+ # otherwise, decrypt it
+ from observers.syndicate import syndicatelib
+
+ # get observer private key
+ config = syndicatelib.get_config()
+
+ try:
+ observer_pkey_path = config.SYNDICATE_PRIVATE_KEY
+ observer_pkey_pem = syndicatelib.get_private_key_pem( observer_pkey_path )
+ except:
+ raise syndicatelib.SyndicateObserverError( "Internal Syndicate Observer error: failed to load Observer private key" )
+
+ # deserialize
+ secret_str = ObserverSecretValue.unserialize( secret_str )
+
+ # decrypt
+ if secret_str is not None and len(secret_str) > 0:
+
+ slice_secret = syndicatelib.decrypt_slice_secret( observer_pkey_pem, secret_str )
+
+ if slice_secret is not None:
+ return slice_secret
+
+ else:
+ raise syndicatelib.SyndicateObserverError( "Internal Syndicate Observer error: failed to decrypt slice secret value" )
+ else:
+ return None
+
+
+ def pre_save( self, model_inst, add ):
+ """
+ Encrypt the value with the Observer key
+ """
+
+ from observers.syndicate import syndicatelib
+
+ # get observer private key
+ config = syndicatelib.get_config()
+
+ try:
+ observer_pkey_path = config.SYNDICATE_PRIVATE_KEY
+ observer_pkey_pem = syndicatelib.get_private_key_pem( observer_pkey_path )
+ except:
+ raise syndicatelib.SyndicateObserverError( "Internal Syndicate Observer error: failed to load Observer private key" )
+
+ slice_secret = getattr(model_inst, self.attname )
+
+ if slice_secret is not None:
+
+ # encrypt it
+ sealed_slice_secret = syndicatelib.encrypt_slice_secret( observer_pkey_pem, slice_secret )
+
+ return ObserverSecretValue.serialize( sealed_slice_secret )
+
+ else:
+ raise syndicatelib.SyndicateObserverError( "Internal Syndicate Observer error: No slice secret generated" )
+
+
+class SliceSecret(models.Model): # NOTE: not a PlCoreBase
+ class Meta:
+ app_label = "syndicate_storage"
+
+ slice_id = models.ForeignKey(Slice)
+ secret = ObserverSecretValue(blank=True, help_text="Shared secret between OpenCloud and this slice's Syndicate daemons.")
+
+ def __unicode__(self): return self.slice_id.name
+
+ @staticmethod
+ def select_by_user(user):
+ """
+ Only return slice secrets for slices where this user has 'admin' role.
+ Admin users can see everything.
+ """
+ if user.is_admin:
+ qs = SliceSecret.objects.all()
+ else:
+ visible_slice_ids = [sp.slice.id for sp in SlicePrivilege.objects.filter(user=user,role__role='admin')]
+ qs = SliceSecret.objects.filter(slice_id__id__in=visible_slice_ids)
+
+ return qs
+
+
+class VolumeSlice(PlCoreBase):
+ class Meta:
+ app_label = "syndicate_storage"
+
+ volume_id = models.ForeignKey(Volume, verbose_name="Volume")
+ slice_id = models.ForeignKey(Slice, verbose_name="Slice")
+
+ cap_read_data = models.BooleanField(default=True, help_text="VM can read Volume data")
+ cap_write_data = models.BooleanField(default=True, help_text="VM can write Volume data")
+ cap_host_data = models.BooleanField(default=True, help_text="VM can host Volume data")
+
+ UG_portnum = models.PositiveIntegerField(help_text="User Gateway port. Any port above 1024 will work, but it must be available slice-wide.", verbose_name="UG port")
+ RG_portnum = models.PositiveIntegerField(help_text="Replica Gateway port. Any port above 1024 will work, but it must be available slice-wide.", verbose_name="RG port")
+
+ credentials_blob = models.TextField(null=True, blank=True, help_text="Encrypted slice credentials, sealed with the slice secret.")
+
+ def __unicode__(self): return "%s-%s" % (self.volume_id.name, self.slice_id.name)
+
+ def clean(self):
+ """
+ Verify that our fields are in order:
+ * UG_portnum and RG_portnum have to be valid port numbers between 1025 and 65534
+ * UG_portnum and RG_portnum cannot be changed once set.
+ * UG_portnum and RG_portnum are unique
+ """
+
+ if self.UG_portnum == self.RG_portnum:
+ raise ValidationError( "UG and RG ports must be unique" )
+
+ if self.UG_portnum < 1025 or self.UG_portnum > 65534:
+ raise ValidationError( "UG port number must be between 1025 and 65534" )
+
+ if self.RG_portnum < 1025 or self.RG_portnum > 65534:
+ raise ValidationError( "RG port number must be between 1025 and 65534" )
+
+
+ def save(self, *args, **kw):
+ """
+ Make sure a SliceSecret exists for this slice
+ """
+
+ from observers.syndicate import syndicatelib
+
+ # get observer private key
+ config = syndicatelib.get_config()
+
+ try:
+ observer_pkey_path = config.SYNDICATE_PRIVATE_KEY
+ observer_pkey_pem = syndicatelib.get_private_key_pem( observer_pkey_path )
+ except:
+ raise syndicatelib.SyndicateObserverError( "Internal Syndicate Observer error: failed to load Observer private key" )
+
+ # get or create the slice secret
+ slice_secret = syndicatelib.get_or_create_slice_secret( observer_pkey_pem, None, slice_fk=self.slice_id )
+
+ if slice_secret is None:
+ raise SyndicateObserverError( "Failed to get or create slice secret for %s" % self.slice_id.name )
+
+ super(VolumeSlice, self).save(*args, **kw)
+
+
+
diff --git a/xos/syndicate_storage/templates/syndicateadmin.html b/xos/services/syndicate_storage/templates/syndicateadmin.html
similarity index 100%
rename from xos/syndicate_storage/templates/syndicateadmin.html
rename to xos/services/syndicate_storage/templates/syndicateadmin.html
diff --git a/xos/observers/__init__.py b/xos/synchronizers/__init__.py
similarity index 100%
rename from xos/observers/__init__.py
rename to xos/synchronizers/__init__.py
diff --git a/xos/synchronizers/base/SyncInstanceUsingAnsible.py b/xos/synchronizers/base/SyncInstanceUsingAnsible.py
new file mode 100644
index 0000000..335932f
--- /dev/null
+++ b/xos/synchronizers/base/SyncInstanceUsingAnsible.py
@@ -0,0 +1,221 @@
+import hashlib
+import os
+import socket
+import sys
+import base64
+import time
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from synchronizers.base.ansible import run_template_ssh
+from core.models import Service, Slice, ControllerSlice, ControllerUser
+from xos.logger import Logger, logging
+
+logger = Logger(level=logging.INFO)
+
+class SyncInstanceUsingAnsible(SyncStep):
+ # All of the following should be defined for classes derived from this
+ # base class. Examples below use VCPETenant.
+
+ # provides=[VCPETenant]
+ # observes=VCPETenant
+ # requested_interval=0
+ # template_name = "sync_vcpetenant.yaml"
+ # service_key_name = "/opt/xos/observers/vcpe/vcpe_private_key"
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+
+ def defer_sync(self, o, reason):
+ logger.info("defer object %s due to %s" % (str(o), reason))
+ raise Exception("defer object %s due to %s" % (str(o), reason))
+
+ def get_extra_attributes(self, o):
+ # This is a place to include extra attributes that aren't part of the
+ # object itself.
+
+ return {}
+
+ def get_instance(self, o):
+ # We need to know what instance is associated with the object. Let's
+ # assume 'o' has a field called 'instance'. If the field is called
+ # something else, or if custom logic is needed, then override this
+ # method.
+
+ return o.instance
+
+ def run_playbook(self, o, fields, template_name=None):
+ if not template_name:
+ template_name = self.template_name
+ tStart = time.time()
+ run_template_ssh(template_name, fields)
+ logger.info("playbook execution time %d" % int(time.time()-tStart))
+
+ def pre_sync_hook(self, o, fields):
+ pass
+
+ def post_sync_hook(self, o, fields):
+ pass
+
+ def sync_fields(self, o, fields):
+ self.run_playbook(o, fields)
+
+ def prepare_record(self, o):
+ pass
+
+ def get_node(self,o):
+ return o.node
+
+ def get_node_key(self, node):
+ return "/root/setup/node_key"
+
+ def get_ansible_fields(self, instance):
+ # return all of the fields that tell Ansible how to talk to the context
+ # that's setting up the container.
+
+ if (instance.isolation == "vm"):
+ # legacy where container was configured by sync_vcpetenant.py
+
+ fields = { "instance_name": instance.name,
+ "hostname": instance.node.name,
+ "instance_id": instance.instance_id,
+ "username": "ubuntu",
+ }
+ key_name = self.service_key_name
+ elif (instance.isolation == "container"):
+ # container on bare metal
+ node = self.get_node(instance)
+ hostname = node.name
+ fields = { "hostname": hostname,
+ "baremetal_ssh": True,
+ "instance_name": "rootcontext",
+ "username": "root",
+ "container_name": "%s-%s" % (instance.slice.name, str(instance.id))
+ }
+ key_name = self.get_node_key(node)
+ else:
+ # container in a VM
+ if not instance.parent:
+ raise Exception("Container-in-VM has no parent")
+ if not instance.parent.instance_id:
+ raise Exception("Container-in-VM parent is not yet instantiated")
+ if not instance.parent.slice.service:
+ raise Exception("Container-in-VM parent has no service")
+ if not instance.parent.slice.service.private_key_fn:
+ raise Exception("Container-in-VM parent service has no private_key_fn")
+ fields = { "hostname": instance.parent.node.name,
+ "instance_name": instance.parent.name,
+ "instance_id": instance.parent.instance_id,
+ "username": "ubuntu",
+ "nat_ip": instance.parent.get_ssh_ip(),
+ "container_name": "%s-%s" % (instance.slice.name, str(instance.id))
+ }
+ key_name = instance.parent.slice.service.private_key_fn
+
+ if not os.path.exists(key_name):
+ raise Exception("Node key %s does not exist" % key_name)
+
+ key = file(key_name).read()
+
+ fields["private_key"] = key
+
+ # now the ceilometer stuff
+
+ cslice = ControllerSlice.objects.get(slice=instance.slice)
+ if not cslice:
+ raise Exception("Controller slice object for %s does not exist" % instance.slice.name)
+
+ cuser = ControllerUser.objects.get(user=instance.creator)
+ if not cuser:
+ raise Exception("Controller user object for %s does not exist" % instance.creator)
+
+ fields.update({"keystone_tenant_id": cslice.tenant_id,
+ "keystone_user_id": cuser.kuser_id,
+ "rabbit_user": instance.controller.rabbit_user,
+ "rabbit_password": instance.controller.rabbit_password,
+ "rabbit_host": instance.controller.rabbit_host})
+
+ return fields
+
+ def sync_record(self, o):
+ logger.info("sync'ing object %s" % str(o))
+
+ self.prepare_record(o)
+
+ instance = self.get_instance(o)
+
+ if isinstance(instance, basestring):
+ # sync to some external host
+
+ # XXX - this probably needs more work...
+
+ fields = { "hostname": instance,
+ "instance_id": "ubuntu", # this is the username to log into
+ "private_key": service.key,
+ }
+ else:
+ # sync to an XOS instance
+ if not instance:
+ self.defer_sync(o, "waiting on instance")
+ return
+
+ if not instance.instance_name:
+ self.defer_sync(o, "waiting on instance.instance_name")
+ return
+
+ fields = self.get_ansible_fields(instance)
+
+ fields["ansible_tag"] = o.__class__.__name__ + "_" + str(o.id)
+
+ # If 'o' defines a 'sync_attributes' list, then we'll copy those
+ # attributes into the Ansible recipe's field list automatically.
+ if hasattr(o, "sync_attributes"):
+ for attribute_name in o.sync_attributes:
+ fields[attribute_name] = getattr(o, attribute_name)
+
+ fields.update(self.get_extra_attributes(o))
+
+ self.sync_fields(o, fields)
+
+ o.save()
+
+ def delete_record(self, o):
+ try:
+ controller = o.get_controller()
+ controller_register = json.loads(o.node.site_deployment.controller.backend_register)
+
+ if (controller_register.get('disabled',False)):
+ raise InnocuousException('Controller %s is disabled'%o.node.site_deployment.controller.name)
+ except AttributeError:
+ pass
+
+ instance = self.get_instance(o)
+ if isinstance(instance, basestring):
+ # sync to some external host
+
+ # XXX - this probably needs more work...
+
+ fields = { "hostname": instance,
+ "instance_id": "ubuntu", # this is the username to log into
+ "private_key": service.key,
+ }
+ else:
+ # sync to an XOS instance
+ fields = self.get_ansible_fields(instance)
+
+ fields["ansible_tag"] = o.__class__.__name__ + "_" + str(o.id)
+
+ # If 'o' defines a 'sync_attributes' list, then we'll copy those
+ # attributes into the Ansible recipe's field list automatically.
+ if hasattr(o, "sync_attributes"):
+ for attribute_name in o.sync_attributes:
+ fields[attribute_name] = getattr(o, attribute_name)
+
+ fields.update(self.map_delete_inputs(o))
+
+ fields['delete']=True
+ res = self.run_playbook(o,fields)
+ try:
+ self.map_delete_outputs(o,res)
+ except AttributeError:
+ pass
diff --git a/xos/synchronizers/base/SyncSliverUsingAnsible.py b/xos/synchronizers/base/SyncSliverUsingAnsible.py
new file mode 100644
index 0000000..c64e5ea
--- /dev/null
+++ b/xos/synchronizers/base/SyncSliverUsingAnsible.py
@@ -0,0 +1,95 @@
+import hashlib
+import os
+import socket
+import sys
+import base64
+import time
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from synchronizers.base.ansible import run_template_ssh
+from core.models import Service, Slice
+from xos.logger import Logger, logging
+
+logger = Logger(level=logging.INFO)
+
+class SyncInstanceUsingAnsible(SyncStep):
+ # All of the following should be defined for classes derived from this
+ # base class. Examples below use VCPETenant.
+
+ # provides=[VCPETenant]
+ # observes=VCPETenant
+ # requested_interval=0
+ # template_name = "sync_vcpetenant.yaml"
+ # service_key_name = "/opt/xos/observers/vcpe/vcpe_private_key"
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+
+ def defer_sync(self, o, reason):
+ logger.info("defer object %s due to %s" % (str(o), reason))
+ raise Exception("defer object %s due to %s" % (str(o), reason))
+
+ def get_extra_attributes(self, o):
+ # This is a place to include extra attributes that aren't part of the
+ # object itself.
+
+ return {}
+
+ def get_instance(self, o):
+ # We need to know what instance is associated with the object. Let's
+ # assume 'o' has a field called 'instance'. If the field is called
+ # something else, or if custom logic is needed, then override this
+ # method.
+
+ return o.instance
+
+ def run_playbook(self, o, fields):
+ tStart = time.time()
+ run_template_ssh(self.template_name, fields)
+ logger.info("playbook execution time %d" % int(time.time()-tStart))
+
+ def pre_sync_hook(self, o, fields):
+ pass
+
+ def post_sync_hook(self, o, fields):
+ pass
+
+ def sync_fields(self, o, fields):
+ self.run_playbook(o, fields)
+
+ def sync_record(self, o):
+ logger.info("sync'ing object %s" % str(o))
+
+ instance = self.get_instance(o)
+ if not instance:
+ self.defer_sync(o, "waiting on instance")
+ return
+
+ if not os.path.exists(self.service_key_name):
+ raise Exception("Service key %s does not exist" % self.service_key_name)
+
+ service_key = file(self.service_key_name).read()
+
+ fields = { "instance_name": instance.name,
+ "hostname": instance.node.name,
+ "instance_id": instance.instance_id,
+ "private_key": service_key,
+ "ansible_tag": "vcpe_tenant_" + str(o.id)
+ }
+
+ # If 'o' defines a 'sync_attributes' list, then we'll copy those
+ # attributes into the Ansible recipe's field list automatically.
+ if hasattr(o, "sync_attributes"):
+ for attribute_name in o.sync_attributes:
+ fields[attribute_name] = getattr(o, attribute_name)
+
+ fields.update(self.get_extra_attributes(o))
+
+ self.sync_fields(o, fields)
+
+ o.save()
+
+ def delete_record(self, m):
+ pass
+
diff --git a/xos/openstack_observer/__init__.py b/xos/synchronizers/base/__init__.py
similarity index 100%
rename from xos/openstack_observer/__init__.py
rename to xos/synchronizers/base/__init__.py
diff --git a/xos/synchronizers/base/ansible.py b/xos/synchronizers/base/ansible.py
new file mode 100644
index 0000000..17a0c45
--- /dev/null
+++ b/xos/synchronizers/base/ansible.py
@@ -0,0 +1,211 @@
+#!/usr/bin/env python
+import jinja2
+import tempfile
+import os
+import json
+import pdb
+import string
+import random
+import re
+import traceback
+import subprocess
+from xos.config import Config, XOS_DIR
+from xos.logger import observer_logger
+
+try:
+ step_dir = Config().observer_steps_dir
+ sys_dir = Config().observer_sys_dir
+except:
+ step_dir = XOS_DIR + '/synchronizers/openstack/steps'
+ sys_dir = '/opt/opencloud'
+
+os_template_loader = jinja2.FileSystemLoader( searchpath=step_dir)
+os_template_env = jinja2.Environment(loader=os_template_loader)
+
+def parse_output(msg):
+ lines = msg.splitlines()
+ results = []
+
+ observer_logger.info(msg)
+
+ for l in lines:
+ magic_str = 'ok: [127.0.0.1] => '
+ magic_str2 = 'changed: [127.0.0.1] => '
+ if (l.startswith(magic_str)):
+ w = len(magic_str)
+ str = l[w:]
+ d = json.loads(str)
+ results.append(d)
+ elif (l.startswith(magic_str2)):
+ w = len(magic_str2)
+ str = l[w:]
+ d = json.loads(str)
+ results.append(d)
+
+
+ return results
+
+def parse_unreachable(msg):
+ total_unreachable=0
+ total_failed=0
+ for l in msg.splitlines():
+ x = re.findall('ok=([0-9]+).*changed=([0-9]+).*unreachable=([0-9]+).*failed=([0-9]+)', l)
+ if x:
+ (ok, changed, unreachable, failed) = x[0]
+ ok=int(ok)
+ changed=int(changed)
+ unreachable=int(unreachable)
+ failed=int(failed)
+
+ total_unreachable += unreachable
+ total_failed += failed
+ return {'unreachable':total_unreachable,'failed':total_failed}
+
+
+def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
+ return ''.join(random.choice(chars) for _ in range(size))
+
+def shellquote(s):
+ return "'" + s.replace("'", "'\\''") + "'"
+
+def get_playbook_fn(opts, path):
+ if not opts.get("ansible_tag", None):
+ # if no ansible_tag is in the options, then generate a unique one
+ objname= id_generator()
+ opts = opts.copy()
+ opts["ansible_tag"] = objname
+
+ objname = opts["ansible_tag"]
+
+ os.system('mkdir -p %s' % os.path.join(sys_dir, path))
+ return (opts, os.path.join(sys_dir,path,objname))
+
+def run_template(name, opts, path='', expected_num=None, ansible_config=None, ansible_hosts=None, run_ansible_script=None):
+ template = os_template_env.get_template(name)
+ buffer = template.render(opts)
+
+ (opts, fqp) = get_playbook_fn(opts, path)
+
+ f = open(fqp,'w')
+ f.write(buffer)
+ f.flush()
+
+ # This is messy -- there's no way to specify ansible config file from
+ # the command line, but we can specify it using the environment.
+ env = os.environ.copy()
+ if ansible_config:
+ env["ANSIBLE_CONFIG"] = ansible_config
+ if ansible_hosts:
+ env["ANSIBLE_HOSTS"] = ansible_hosts
+
+ if (not Config().observer_pretend):
+ if not run_ansible_script:
+ run_ansible_script = os.path.join(XOS_DIR, "observer/run_ansible")
+
+ process = subprocess.Popen("%s %s" % (run_ansible_script, shellquote(fqp)), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
+ msg = process.stdout.read()
+ err_msg = process.stderr.read()
+
+ if getattr(Config(), "observer_save_ansible_output", False):
+ try:
+ open(fqp+".out","w").write(msg)
+ open(fqp+".err","w").write(err_msg)
+ except:
+ # fail silently
+ pass
+
+ else:
+ msg = open(fqp+'.out').read()
+
+ try:
+ ok_results = parse_output(msg)
+ if (expected_num is not None) and (len(ok_results) != expected_num):
+ raise ValueError('Unexpected num %s!=%d' % (str(expected_num), len(ok_results)) )
+
+ parsed = parse_unreachable(msg)
+ total_unreachable = parsed['unreachable']
+ failed = parsed['failed']
+ if (failed):
+ raise ValueError('Ansible playbook failed.')
+
+ if (total_unreachable > 0):
+ raise ValueError("Unreachable results in ansible recipe")
+ except ValueError,e:
+ all_fatal = [e.message] + re.findall(r'^msg: (.*)',msg,re.MULTILINE)
+ all_fatal2 = re.findall(r'^ERROR: (.*)',msg,re.MULTILINE)
+
+ all_fatal.extend(all_fatal2)
+ try:
+ error = ' // '.join(all_fatal)
+ except:
+ pass
+ raise Exception(error)
+
+ return ok_results
+
+def run_template_ssh(name, opts, path='', expected_num=None):
+ instance_name = opts["instance_name"]
+ hostname = opts["hostname"]
+ private_key = opts["private_key"]
+ baremetal_ssh = opts.get("baremetal_ssh",False)
+ if baremetal_ssh:
+ # no instance_id or nat_ip for baremetal
+ # we never proxy to baremetal
+ proxy_ssh = False
+ else:
+ instance_id = opts["instance_id"]
+ nat_ip = opts["nat_ip"]
+ try:
+ proxy_ssh = Config().observer_proxy_ssh
+ except:
+ proxy_ssh = True
+
+ (opts, fqp) = get_playbook_fn(opts, path)
+ private_key_pathname = fqp + ".key"
+ config_pathname = fqp + ".config"
+ hosts_pathname = fqp + ".hosts"
+
+ f = open(private_key_pathname, "w")
+ f.write(private_key)
+ f.close()
+
+ f = open(config_pathname, "w")
+ f.write("[ssh_connection]\n")
+ if proxy_ssh:
+ proxy_command = "ProxyCommand ssh -q -i %s -o StrictHostKeyChecking=no %s@%s" % (private_key_pathname, instance_id, hostname)
+ f.write('ssh_args = -o "%s"\n' % proxy_command)
+ f.write('scp_if_ssh = True\n')
+ f.write('pipelining = True\n')
+ f.write('\n[defaults]\n')
+ f.write('host_key_checking = False\n')
+ f.close()
+
+ f = open(hosts_pathname, "w")
+ f.write("[%s]\n" % instance_name)
+ if proxy_ssh or baremetal_ssh:
+ f.write("%s ansible_ssh_private_key_file=%s\n" % (hostname, private_key_pathname))
+ else:
+ # acb: Login user is hardcoded, this is not great
+ f.write("%s ansible_ssh_private_key_file=%s ansible_ssh_user=ubuntu\n" % (nat_ip, private_key_pathname))
+ f.close()
+
+ # SSH will complain if private key is world or group readable
+ os.chmod(private_key_pathname, 0600)
+
+ print "ANSIBLE_CONFIG=%s" % config_pathname
+ print "ANSIBLE_HOSTS=%s" % hosts_pathname
+
+ return run_template(name, opts, path, ansible_config = config_pathname, ansible_hosts = hosts_pathname, run_ansible_script="/opt/xos/observer/run_ansible_verbose")
+
+
+
+def main():
+ run_template('ansible/sync_user_deployments.yaml',{ "endpoint" : "http://172.31.38.128:5000/v2.0/",
+ "name" : "Sapan Bhatia",
+ "email": "gwsapan@gmail.com",
+ "password": "foobar",
+ "admin_user":"admin",
+ "admin_password":"6a789bf69dd647e2",
+ "admin_tenant":"admin",
+ "tenant":"demo",
+ "roles":['user','admin'] })
diff --git a/xos/synchronizers/base/backend.py b/xos/synchronizers/base/backend.py
new file mode 100644
index 0000000..5f11d46
--- /dev/null
+++ b/xos/synchronizers/base/backend.py
@@ -0,0 +1,46 @@
+import os
+import sys
+import threading
+import time
+from synchronizers.base.event_loop import XOSObserver
+from synchronizers.base.event_manager import EventListener
+from xos.logger import Logger, logging
+from synchronizers.model_policy import run_policy
+from xos.config import Config
+
+logger = Logger(level=logging.INFO)
+
+class Backend:
+
+ def run(self):
+ # start the openstack observer
+ observer = XOSObserver()
+ observer_thread = threading.Thread(target=observer.run)
+ observer_thread.start()
+
+ # start model policies thread
+ observer_name = getattr(Config(), "observer_name", "")
+ if (not observer_name):
+ model_policy_thread = threading.Thread(target=run_policy)
+ model_policy_thread.start()
+ else:
+ model_policy_thread = None
+ print "Skipping model policies thread for service observer."
+
+
+ # start event listene
+ #event_manager = EventListener(wake_up=observer.wake_up)
+ #event_manager_thread = threading.Thread(target=event_manager.run)
+ #event_manager_thread.start()
+
+ while True:
+ try:
+ time.sleep(1000)
+ except KeyboardInterrupt:
+ print "exiting due to keyboard interrupt"
+ # TODO: See about setting the threads as daemons
+ observer_thread._Thread__stop()
+ if model_policy_thread:
+ model_policy_thread._Thread__stop()
+ sys.exit(1)
+
diff --git a/xos/synchronizers/base/backend.py.bak b/xos/synchronizers/base/backend.py.bak
new file mode 100644
index 0000000..6e46b85
--- /dev/null
+++ b/xos/synchronizers/base/backend.py.bak
@@ -0,0 +1,34 @@
+import threading
+import time
+from observer.event_loop import XOSObserver
+from observer.event_manager import EventListener
+from util.logger import Logger, logging
+from model_policy import run_policy
+from xos.config import Config
+
+logger = Logger(level=logging.INFO)
+
+class Backend:
+
+ def run(self):
+ # start the openstack observer
+ observer = XOSObserver()
+ observer_thread = threading.Thread(target=observer.run)
+ observer_thread.start()
+
+ # start model policies thread
+ observer_name = getattr(Config(), "observer_name", "")
+ if (not observer_name):
+ model_policy_thread = threading.Thread(target=run_policy)
+ model_policy_thread.start()
+ else:
+ print "Skipping model policies thread for service observer."
+
+ model_policy_thread = threading.Thread(target=run_policy)
+ model_policy_thread.start()
+
+ # start event listene
+ event_manager = EventListener(wake_up=observer.wake_up)
+ event_manager_thread = threading.Thread(target=event_manager.run)
+ event_manager_thread.start()
+
diff --git a/xos/synchronizers/base/controller.diff b/xos/synchronizers/base/controller.diff
new file mode 100644
index 0000000..865b83e
--- /dev/null
+++ b/xos/synchronizers/base/controller.diff
@@ -0,0 +1,37 @@
+diff -up xos/model_policies/model_policy_Controller.py.orig xos/model_policies/model_policy_Controller.py
+--- xos/model_policies/model_policy_Controller.py.orig 2015-01-19 20:09:13.000000000 +0000
++++ xos/model_policies/model_policy_Controller.py 2015-04-07 21:48:51.462215000 +0000
+@@ -1,6 +1,6 @@
+
+ def handle(controller):
+- from core.models import Controller, Site, ControllerSite, Slice, ControllerSlice, User, ControllerUser
++ from core.models import Controller, Site, ControllerSite, Slice, ControllerSlice, User, ControllerUser, ControllerImages, ControllerNetwork
+ from collections import defaultdict
+
+ # relations for all sites
+@@ -36,3 +36,25 @@ def handle(controller):
+ controller not in ctrls_by_user[user]:
+ controller_user = ControllerUser(controller=controller, user=user)
+ controller_user.save()
++ # relations for all networks
++ ctrls_by_network = defaultdict(list)
++ ctrl_networks = ControllerNetwork.objects.all()
++ for ctrl_network in ctrl_networks:
++ ctrls_by_network[ctrl_network.network].append(ctrl_network.controller)
++ networks = Network.objects.all()
++ for network in networks:
++ if network not in ctrls_by_network or \
++ controller not in ctrls_by_network[network]:
++ controller_network = ControllerNetwork(controller=controller, network=network)
++ controller_network.save()
++ # relations for all images
++ ctrls_by_image = defaultdict(list)
++ ctrl_images = ControllerImages.objects.all()
++ for ctrl_image in ctrl_images:
++ ctrls_by_image[ctrl_image.image].append(ctrl_image.controller)
++ images = Image.objects.all()
++ for image in images:
++ if image not in ctrls_by_image or \
++ controller not in ctrls_by_image[image]:
++ controller_image = ControllerImages(controller=controller, image=image)
++ controller_image.save()
diff --git a/xos/ec2_observer/deleter.py b/xos/synchronizers/base/deleter.py
similarity index 100%
rename from xos/ec2_observer/deleter.py
rename to xos/synchronizers/base/deleter.py
diff --git a/xos/synchronizers/base/error_mapper.py b/xos/synchronizers/base/error_mapper.py
new file mode 100644
index 0000000..9eb878d
--- /dev/null
+++ b/xos/synchronizers/base/error_mapper.py
@@ -0,0 +1,25 @@
+from xos.config import Config
+from xos.logger import Logger, logging, logger
+
+class ErrorMapper:
+ def __init__(self, error_map_file):
+ self.error_map = {}
+ try:
+ error_map_lines = open(error_map_file).read().splitlines()
+ for l in error_map_lines:
+ if (not l.startswith('#')):
+ splits = l.split('->')
+ k,v = map(lambda i:i.rstrip(),splits)
+ self.error_map[k]=v
+ except:
+ logging.info('Could not read error map')
+
+
+ def map(self, error):
+ return self.error_map[error]
+
+
+
+
+
+
diff --git a/xos/synchronizers/base/event_loop.py b/xos/synchronizers/base/event_loop.py
new file mode 100644
index 0000000..6cfc9f6
--- /dev/null
+++ b/xos/synchronizers/base/event_loop.py
@@ -0,0 +1,527 @@
+import os
+import imp
+import inspect
+import time
+import sys
+import traceback
+import commands
+import threading
+import json
+import pdb
+import pprint
+
+
+from datetime import datetime
+from collections import defaultdict
+from core.models import *
+from django.db.models import F, Q
+from django.db import connection
+from django.db import reset_queries
+#from openstack.manager import OpenStackManager
+from openstack.driver import OpenStackDriver
+from xos.logger import Logger, logging, logger
+#from timeout import timeout
+from xos.config import Config, XOS_DIR
+from synchronizers.base.steps import *
+from syncstep import SyncStep
+from toposort import toposort
+from synchronizers.base.error_mapper import *
+from synchronizers.openstack.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.steps.sync_object import SyncObject
+
+# Load app models
+
+try:
+ app_module_names = Config().observer_applist.split(',')
+except AttributeError:
+ app_module_names = []
+
+if (type(app_module_names)!=list):
+ app_module_names=[app_module_names]
+
+app_modules = []
+
+for m in app_module_names:
+ model_path = m+'.models'
+ module = __import__(model_path,fromlist=[m])
+ app_modules.append(module)
+
+
+debug_mode = False
+
+class bcolors:
+ HEADER = '\033[95m'
+ OKBLUE = '\033[94m'
+ OKGREEN = '\033[92m'
+ WARNING = '\033[93m'
+ FAIL = '\033[91m'
+ ENDC = '\033[0m'
+ BOLD = '\033[1m'
+ UNDERLINE = '\033[4m'
+
+logger = Logger(level=logging.INFO)
+
+class StepNotReady(Exception):
+ pass
+
+class NoOpDriver:
+ def __init__(self):
+ self.enabled = True
+ self.dependency_graph = None
+
+STEP_STATUS_WORKING=1
+STEP_STATUS_OK=2
+STEP_STATUS_KO=3
+
+def invert_graph(g):
+ ig = {}
+ for k,v in g.items():
+ for v0 in v:
+ try:
+ ig[v0].append(k)
+ except:
+ ig[v0]=[k]
+ return ig
+
+class XOSObserver:
+ sync_steps = []
+
+
+ def __init__(self):
+ # The Condition object that gets signalled by Feefie events
+ self.step_lookup = {}
+ self.load_sync_step_modules()
+ self.load_sync_steps()
+ self.event_cond = threading.Condition()
+
+ self.driver_kind = getattr(Config(), "observer_driver", "openstack")
+ self.observer_name = getattr(Config(), "observer_name", "")
+ if self.driver_kind=="openstack":
+ self.driver = OpenStackDriver()
+ else:
+ self.driver = NoOpDriver()
+
+ def consolePrint(self, what):
+ if getattr(Config(), "observer_console_print", True):
+ print what
+
+ def wait_for_event(self, timeout):
+ self.event_cond.acquire()
+ self.event_cond.wait(timeout)
+ self.event_cond.release()
+
+ def wake_up(self):
+ logger.info('Wake up routine called. Event cond %r'%self.event_cond)
+ self.event_cond.acquire()
+ self.event_cond.notify()
+ self.event_cond.release()
+
+ def load_sync_step_modules(self, step_dir=None):
+ if step_dir is None:
+ if hasattr(Config(), "observer_steps_dir"):
+ step_dir = Config().observer_steps_dir
+ else:
+ step_dir = XOS_DIR + "/synchronizers/openstack/steps"
+
+ for fn in os.listdir(step_dir):
+ pathname = os.path.join(step_dir,fn)
+ if os.path.isfile(pathname) and fn.endswith(".py") and (fn!="__init__.py"):
+ module = imp.load_source(fn[:-3],pathname)
+ for classname in dir(module):
+ c = getattr(module, classname, None)
+
+ # make sure 'c' is a descendent of SyncStep and has a
+ # provides field (this eliminates the abstract base classes
+ # since they don't have a provides)
+
+ if inspect.isclass(c) and (issubclass(c, SyncStep) or issubclass(c,OpenStackSyncStep)) and hasattr(c,"provides") and (c not in self.sync_steps):
+ self.sync_steps.append(c)
+ logger.info('loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps]))
+
+ def load_sync_steps(self):
+ dep_path = Config().observer_dependency_graph
+ logger.info('Loading model dependency graph from %s' % dep_path)
+ try:
+ # This contains dependencies between records, not sync steps
+ self.model_dependency_graph = json.loads(open(dep_path).read())
+ for left,lst in self.model_dependency_graph.items():
+ new_lst = []
+ for k in lst:
+ try:
+ tup = (k,k.lower())
+ new_lst.append(tup)
+ deps = self.model_dependency_graph[k]
+ except:
+ self.model_dependency_graph[k] = []
+
+ self.model_dependency_graph[left] = new_lst
+ except Exception,e:
+ raise e
+
+ try:
+ backend_path = Config().observer_pl_dependency_graph
+ logger.info('Loading backend dependency graph from %s' % backend_path)
+ # This contains dependencies between backend records
+ self.backend_dependency_graph = json.loads(open(backend_path).read())
+ for k,v in self.backend_dependency_graph.items():
+ try:
+ self.model_dependency_graph[k].extend(v)
+ except KeyError:
+ self.model_dependency_graphp[k] = v
+
+ except Exception,e:
+ logger.info('Backend dependency graph not loaded')
+ # We can work without a backend graph
+ self.backend_dependency_graph = {}
+
+ provides_dict = {}
+ for s in self.sync_steps:
+ self.step_lookup[s.__name__] = s
+ for m in s.provides:
+ try:
+ provides_dict[m.__name__].append(s.__name__)
+ except KeyError:
+ provides_dict[m.__name__]=[s.__name__]
+
+ step_graph = {}
+ phantom_steps = []
+ for k,v in self.model_dependency_graph.items():
+ try:
+ for source in provides_dict[k]:
+ if (not v):
+ step_graph[source] = []
+
+ for m,_ in v:
+ try:
+ for dest in provides_dict[m]:
+ # no deps, pass
+ try:
+ if (dest not in step_graph[source]):
+ step_graph[source].append(dest)
+ except:
+ step_graph[source]=[dest]
+ except KeyError:
+ if (not provides_dict.has_key(m)):
+ try:
+ step_graph[source]+=['#%s'%m]
+ except:
+ step_graph[source]=['#%s'%m]
+
+ phantom_steps+=['#%s'%m]
+ pass
+
+ except KeyError:
+ pass
+ # no dependencies, pass
+
+
+ self.dependency_graph = step_graph
+ self.deletion_dependency_graph = invert_graph(step_graph)
+
+ pp = pprint.PrettyPrinter(indent=4)
+ logger.info(pp.pformat(step_graph))
+ self.ordered_steps = toposort(self.dependency_graph, phantom_steps+map(lambda s:s.__name__,self.sync_steps))
+ self.ordered_steps = [i for i in self.ordered_steps if i!='SyncObject']
+
+ logger.info("Order of steps=%s" % self.ordered_steps)
+
+ self.load_run_times()
+
+
+ def check_duration(self, step, duration):
+ try:
+ if (duration > step.deadline):
+ logger.info('Sync step %s missed deadline, took %.2f seconds'%(step.name,duration))
+ except AttributeError:
+ # S doesn't have a deadline
+ pass
+
+ def update_run_time(self, step, deletion):
+ if (not deletion):
+ self.last_run_times[step.__name__]=time.time()
+ else:
+ self.last_deletion_run_times[step.__name__]=time.time()
+
+
+ def check_schedule(self, step, deletion):
+ last_run_times = self.last_run_times if not deletion else self.last_deletion_run_times
+
+ time_since_last_run = time.time() - last_run_times.get(step.__name__, 0)
+ try:
+ if (time_since_last_run < step.requested_interval):
+ raise StepNotReady
+ except AttributeError:
+ logger.info('Step %s does not have requested_interval set'%step.__name__)
+ raise StepNotReady
+
+ def load_run_times(self):
+ try:
+ jrun_times = open('/tmp/%sobserver_run_times'%self.observer_name).read()
+ self.last_run_times = json.loads(jrun_times)
+ except:
+ self.last_run_times={}
+ for e in self.ordered_steps:
+ self.last_run_times[e]=0
+ try:
+ jrun_times = open('/tmp/%sobserver_deletion_run_times'%self.observer_name).read()
+ self.last_deletion_run_times = json.loads(jrun_times)
+ except:
+ self.last_deletion_run_times={}
+ for e in self.ordered_steps:
+ self.last_deletion_run_times[e]=0
+
+ def lookup_step_class(self,s):
+ if ('#' in s):
+ return SyncObject
+ else:
+ step = self.step_lookup[s]
+ return step
+
+ def lookup_step(self,s):
+ if ('#' in s):
+ objname = s[1:]
+ so = SyncObject()
+
+ try:
+ obj = globals()[objname]
+ except:
+ for m in app_modules:
+ if (hasattr(m,objname)):
+ obj = getattr(m,objname)
+
+ so.provides=[obj]
+ so.observes=[obj]
+ step = so
+ else:
+ step_class = self.step_lookup[s]
+ step = step_class(driver=self.driver,error_map=self.error_mapper)
+ return step
+
+ def save_run_times(self):
+ run_times = json.dumps(self.last_run_times)
+ open('/tmp/%sobserver_run_times'%self.observer_name,'w').write(run_times)
+
+ deletion_run_times = json.dumps(self.last_deletion_run_times)
+ open('/tmp/%sobserver_deletion_run_times'%self.observer_name,'w').write(deletion_run_times)
+
+ def check_class_dependency(self, step, failed_steps):
+ step.dependenices = []
+ for obj in step.provides:
+ lst = self.model_dependency_graph.get(obj.__name__, [])
+ nlst = map(lambda(a,b):b,lst)
+ step.dependenices.extend(nlst)
+ for failed_step in failed_steps:
+ if (failed_step in step.dependencies):
+ raise StepNotReady
+
+ def sync(self, S, deletion):
+ try:
+ step = self.lookup_step_class(S)
+ start_time=time.time()
+
+ logger.info("Starting to work on step %s, deletion=%s" % (step.__name__, str(deletion)))
+
+ dependency_graph = self.dependency_graph if not deletion else self.deletion_dependency_graph
+ step_conditions = self.step_conditions# if not deletion else self.deletion_step_conditions
+ step_status = self.step_status# if not deletion else self.deletion_step_status
+
+ # Wait for step dependencies to be met
+ try:
+ deps = dependency_graph[S]
+ has_deps = True
+ except KeyError:
+ has_deps = False
+
+ go = True
+
+ failed_dep = None
+ if (has_deps):
+ for d in deps:
+ if d==step.__name__:
+ logger.info(" step %s self-wait skipped" % step.__name__)
+ go = True
+ continue
+
+ cond = step_conditions[d]
+ cond.acquire()
+ if (step_status[d] is STEP_STATUS_WORKING):
+ logger.info(" step %s wait on dep %s" % (step.__name__, d))
+ cond.wait()
+ elif step_status[d] == STEP_STATUS_OK:
+ go = True
+ else:
+ go = False
+ failed_dep = d
+ cond.release()
+ if (not go):
+ break
+ else:
+ go = True
+
+ if (not go):
+ self.consolePrint(bcolors.FAIL + "Step %r skipped on %r" % (step,failed_dep) + bcolors.ENDC)
+ # SMBAKER: sync_step was not defined here, so I changed
+ # this from 'sync_step' to 'step'. Verify.
+ self.failed_steps.append(step)
+ my_status = STEP_STATUS_KO
+ else:
+ sync_step = self.lookup_step(S)
+ sync_step. __name__= step.__name__
+ sync_step.dependencies = []
+ try:
+ mlist = sync_step.provides
+
+ try:
+ for m in mlist:
+ lst = self.model_dependency_graph[m.__name__]
+ nlst = map(lambda(a,b):b,lst)
+ sync_step.dependencies.extend(nlst)
+ except Exception,e:
+ raise e
+
+ except KeyError:
+ pass
+ sync_step.debug_mode = debug_mode
+
+ should_run = False
+ try:
+ # Various checks that decide whether
+ # this step runs or not
+ self.check_class_dependency(sync_step, self.failed_steps) # dont run Slices if Sites failed
+ self.check_schedule(sync_step, deletion) # dont run sync_network_routes if time since last run < 1 hour
+ should_run = True
+ except StepNotReady:
+ logger.info('Step not ready: %s'%sync_step.__name__)
+ self.failed_steps.append(sync_step)
+ my_status = STEP_STATUS_KO
+ except Exception,e:
+ logger.error('%r' % e)
+ logger.log_exc("sync step failed: %r. Deletion: %r"%(sync_step,deletion))
+ self.failed_steps.append(sync_step)
+ my_status = STEP_STATUS_KO
+
+ if (should_run):
+ try:
+ duration=time.time() - start_time
+
+ logger.info('Executing step %s, deletion=%s' % (sync_step.__name__, deletion))
+
+ self.consolePrint(bcolors.OKBLUE + "Executing step %s" % sync_step.__name__ + bcolors.ENDC)
+ failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion)
+
+ self.check_duration(sync_step, duration)
+
+ if failed_objects:
+ self.failed_step_objects.update(failed_objects)
+
+ logger.info("Step %r succeeded" % sync_step.__name__)
+ self.consolePrint(bcolors.OKGREEN + "Step %r succeeded" % sync_step.__name__ + bcolors.ENDC)
+ my_status = STEP_STATUS_OK
+ self.update_run_time(sync_step,deletion)
+ except Exception,e:
+ self.consolePrint(bcolors.FAIL + "Model step %r failed" % (sync_step.__name__) + bcolors.ENDC)
+ logger.error('Model step %r failed. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!' % (sync_step.__name__, e))
+ logger.log_exc(e)
+ self.failed_steps.append(S)
+ my_status = STEP_STATUS_KO
+ else:
+ logger.info("Step %r succeeded due to non-run" % step)
+ my_status = STEP_STATUS_OK
+
+ try:
+ my_cond = step_conditions[S]
+ my_cond.acquire()
+ step_status[S]=my_status
+ my_cond.notify_all()
+ my_cond.release()
+ except KeyError,e:
+ logger.info('Step %r is a leaf' % step)
+ pass
+ finally:
+ try:
+ reset_queries()
+ except:
+ # this shouldn't happen, but in case it does, catch it...
+ logger.log_exc("exception in reset_queries")
+
+ connection.close()
+
+ def run(self):
+ if not self.driver.enabled:
+ return
+
+ if (self.driver_kind=="openstack") and (not self.driver.has_openstack):
+ return
+
+ while True:
+ logger.info('Waiting for event')
+ self.wait_for_event(timeout=5)
+ logger.info('Observer woke up')
+
+ self.run_once()
+
+ def run_once(self):
+ try:
+ loop_start = time.time()
+ error_map_file = getattr(Config(), "error_map_path", XOS_DIR + "/error_map.txt")
+ self.error_mapper = ErrorMapper(error_map_file)
+
+ # Two passes. One for sync, the other for deletion.
+ for deletion in [False,True]:
+ # Set of individual objects within steps that failed
+ self.failed_step_objects = set()
+
+ # Set up conditions and step status
+ # This is needed for steps to run in parallel
+ # while obeying dependencies.
+
+ providers = set()
+ dependency_graph = self.dependency_graph if not deletion else self.deletion_dependency_graph
+
+ for v in dependency_graph.values():
+ if (v):
+ providers.update(v)
+
+ self.step_conditions = {}
+ self.step_status = {}
+
+ for p in list(providers):
+ self.step_conditions[p] = threading.Condition()
+
+ self.step_status[p] = STEP_STATUS_WORKING
+
+ self.failed_steps = []
+
+ threads = []
+ logger.info('Deletion=%r...'%deletion)
+ schedule = self.ordered_steps if not deletion else reversed(self.ordered_steps)
+
+ for S in schedule:
+ thread = threading.Thread(target=self.sync, args=(S, deletion))
+
+ logger.info('Deletion=%r...'%deletion)
+ threads.append(thread)
+
+ # Start threads
+ for t in threads:
+ t.start()
+
+ # another spot to clean up debug state
+ try:
+ reset_queries()
+ except:
+ # this shouldn't happen, but in case it does, catch it...
+ logger.log_exc("exception in reset_queries")
+
+ # Wait for all threads to finish before continuing with the run loop
+ for t in threads:
+ t.join()
+
+ self.save_run_times()
+
+ loop_end = time.time()
+ open('/tmp/%sobserver_last_run'%self.observer_name,'w').write(json.dumps({'last_run': loop_end, 'last_duration':loop_end - loop_start}))
+ except Exception, e:
+ logger.error('Core error. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!' % e)
+ logger.log_exc("Exception in observer run loop")
+ traceback.print_exc()
diff --git a/xos/openstack_observer/event_manager.py b/xos/synchronizers/base/event_manager.py
similarity index 100%
rename from xos/openstack_observer/event_manager.py
rename to xos/synchronizers/base/event_manager.py
diff --git a/xos/synchronizers/base/observer b/xos/synchronizers/base/observer
new file mode 120000
index 0000000..ae75af5
--- /dev/null
+++ b/xos/synchronizers/base/observer
@@ -0,0 +1 @@
+openstack_observer
\ No newline at end of file
diff --git a/xos/openstack_observer/openstacksyncstep.py b/xos/synchronizers/base/openstacksyncstep.py
similarity index 100%
rename from xos/openstack_observer/openstacksyncstep.py
rename to xos/synchronizers/base/openstacksyncstep.py
diff --git a/xos/openstack_observer/run_ansible b/xos/synchronizers/base/run_ansible
similarity index 100%
rename from xos/openstack_observer/run_ansible
rename to xos/synchronizers/base/run_ansible
diff --git a/xos/openstack_observer/run_ansible_verbose b/xos/synchronizers/base/run_ansible_verbose
similarity index 100%
rename from xos/openstack_observer/run_ansible_verbose
rename to xos/synchronizers/base/run_ansible_verbose
diff --git a/xos/openstack_observer/steps/__init__.py b/xos/synchronizers/base/steps/__init__.py
similarity index 100%
rename from xos/openstack_observer/steps/__init__.py
rename to xos/synchronizers/base/steps/__init__.py
diff --git a/xos/openstack_observer/steps/delete_slivers.yaml b/xos/synchronizers/base/steps/delete_slivers.yaml
similarity index 100%
rename from xos/openstack_observer/steps/delete_slivers.yaml
rename to xos/synchronizers/base/steps/delete_slivers.yaml
diff --git a/xos/synchronizers/base/steps/purge_disabled_users.py b/xos/synchronizers/base/steps/purge_disabled_users.py
new file mode 100644
index 0000000..0973b8c
--- /dev/null
+++ b/xos/synchronizers/base/steps/purge_disabled_users.py
@@ -0,0 +1,25 @@
+import os
+import base64
+import datetime
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from core.models.user import User
+from xos.logger import observer_logger as logger
+
+class SyncRoles(OpenStackSyncStep):
+ provides=[User]
+ requested_interval=0
+ observes=User
+
+ def fetch_pending(self, deleted):
+ if (deleted):
+ # users marked as deleted
+ return User.deleted_objects.all()
+ else:
+ # disabled users that haven't been updated in over a week
+ one_week_ago = datetime.datetime.now() - datetime.timedelta(days=7)
+ return User.objects.filter(is_active=False, updated__gt=one_week_ago)
+
+ def sync_record(self, user):
+ user.delete()
diff --git a/xos/openstack_observer/steps/sliver.yaml b/xos/synchronizers/base/steps/sliver.yaml
similarity index 100%
rename from xos/openstack_observer/steps/sliver.yaml
rename to xos/synchronizers/base/steps/sliver.yaml
diff --git a/xos/synchronizers/base/steps/sync_container.py b/xos/synchronizers/base/steps/sync_container.py
new file mode 100644
index 0000000..d647aef
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_container.py
@@ -0,0 +1,163 @@
+import hashlib
+import os
+import socket
+import sys
+import base64
+import time
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
+from synchronizers.base.syncstep import SyncStep, DeferredException
+from synchronizers.base.ansible import run_template_ssh
+from core.models import Service, Slice, Instance
+from services.onos.models import ONOSService, ONOSApp
+from xos.logger import Logger, logging
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+logger = Logger(level=logging.INFO)
+
+class SyncContainer(SyncInstanceUsingAnsible):
+ provides=[Instance]
+ observes=Instance
+ requested_interval=0
+ template_name = "sync_container.yaml"
+
+ def __init__(self, *args, **kwargs):
+ super(SyncContainer, self).__init__(*args, **kwargs)
+
+ def fetch_pending(self, deletion=False):
+ objs = super(SyncContainer, self).fetch_pending(deletion)
+ objs = [x for x in objs if x.isolation in ["container", "container_vm"]]
+ return objs
+
+ def get_instance_port(self, container_port):
+ for p in container_port.network.links.all():
+ if (p.instance) and (p.instance.isolation=="vm") and (p.instance.node == container_port.instance.node) and (p.mac):
+ return p
+ return None
+
+ def get_parent_port_mac(self, instance, port):
+ if not instance.parent:
+ raise Exception("instance has no parent")
+ for parent_port in instance.parent.ports.all():
+ if parent_port.network == port.network:
+ if not parent_port.mac:
+ raise DeferredException("parent port on network %s does not have mac yet" % parent_port.network.name)
+ return parent_port.mac
+ raise Exception("failed to find corresponding parent port for network %s" % port.network.name)
+
+ def get_ports(self, o):
+ i=0
+ ports = []
+ if (o.slice.network in ["host", "bridged"]):
+ pass # no ports in host or bridged mode
+ else:
+ for port in o.ports.all():
+ if (not port.ip):
+ # 'unmanaged' ports may have an ip, but no mac
+ # XXX: are there any ports that have a mac but no ip?
+ raise DeferredException("Port on network %s is not yet ready" % port.network.name)
+
+ pd={}
+ pd["mac"] = port.mac or ""
+ pd["ip"] = port.ip or ""
+ pd["xos_network_id"] = port.network.id
+
+ if port.network.name == "wan_network":
+ if port.ip:
+ (a, b, c, d) = port.ip.split('.')
+ pd["mac"] = "02:42:%02x:%02x:%02x:%02x" % (int(a), int(b), int(c), int(d))
+
+
+ if o.isolation == "container":
+ # container on bare metal
+ instance_port = self.get_instance_port(port)
+ if not instance_port:
+ raise DeferredException("No instance on slice for port on network %s" % port.network.name)
+
+ pd["snoop_instance_mac"] = instance_port.mac
+ pd["snoop_instance_id"] = instance_port.instance.instance_id
+ pd["src_device"] = ""
+ pd["bridge"] = "br-int"
+ else:
+ # container in VM
+ pd["snoop_instance_mac"] = ""
+ pd["snoop_instance_id"] = ""
+ pd["parent_mac"] = self.get_parent_port_mac(o, port)
+ pd["bridge"] = ""
+
+ for (k,v) in port.get_parameters().items():
+ pd[k] = v
+
+ ports.append(pd)
+
+ # for any ports that don't have a device, assign one
+ used_ports = [x["device"] for x in ports if ("device" in x)]
+ avail_ports = ["eth%d"%i for i in range(0,64) if ("eth%d"%i not in used_ports)]
+ for port in ports:
+ if not port.get("device",None):
+ port["device"] = avail_ports.pop(0)
+
+ return ports
+
+ def get_extra_attributes(self, o):
+ fields={}
+ fields["ansible_tag"] = "container-%s" % str(o.id)
+ if o.image.tag:
+ fields["docker_image"] = o.image.path + ":" + o.image.tag
+ else:
+ fields["docker_image"] = o.image.path
+ fields["ports"] = self.get_ports(o)
+ if o.volumes:
+ fields["volumes"] = [x.strip() for x in o.volumes.split(",")]
+ else:
+ fields["volumes"] = ""
+ fields["network_method"] = o.slice.network or "default"
+ return fields
+
+ def sync_record(self, o):
+ logger.info("sync'ing object %s" % str(o))
+
+ fields = self.get_ansible_fields(o)
+
+ # If 'o' defines a 'sync_attributes' list, then we'll copy those
+ # attributes into the Ansible recipe's field list automatically.
+ if hasattr(o, "sync_attributes"):
+ for attribute_name in o.sync_attributes:
+ fields[attribute_name] = getattr(o, attribute_name)
+
+ fields.update(self.get_extra_attributes(o))
+
+ self.run_playbook(o, fields)
+
+ o.instance_id = fields["container_name"]
+ o.instance_name = fields["container_name"]
+
+ o.save()
+
+ def delete_record(self, o):
+ logger.info("delete'ing object %s" % str(o))
+
+ fields = self.get_ansible_fields(o)
+
+ # If 'o' defines a 'sync_attributes' list, then we'll copy those
+ # attributes into the Ansible recipe's field list automatically.
+ if hasattr(o, "sync_attributes"):
+ for attribute_name in o.sync_attributes:
+ fields[attribute_name] = getattr(o, attribute_name)
+
+ fields.update(self.get_extra_attributes(o))
+
+ self.run_playbook(o, fields, "teardown_container.yaml")
+
+ def run_playbook(self, o, fields, template_name=None):
+ if not template_name:
+ template_name = self.template_name
+ tStart = time.time()
+ run_template_ssh(template_name, fields, path="container")
+ logger.info("playbook execution time %d" % int(time.time()-tStart))
+
+
diff --git a/xos/openstack_observer/steps/sync_container.yaml b/xos/synchronizers/base/steps/sync_container.yaml
similarity index 100%
rename from xos/openstack_observer/steps/sync_container.yaml
rename to xos/synchronizers/base/steps/sync_container.yaml
diff --git a/xos/synchronizers/base/steps/sync_controller_images.py b/xos/synchronizers/base/steps/sync_controller_images.py
new file mode 100644
index 0000000..c1e5136
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_controller_images.py
@@ -0,0 +1,44 @@
+import os
+import base64
+from collections import defaultdict
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models import Controller
+from core.models import Image, ControllerImages
+from xos.logger import observer_logger as logger
+from synchronizers.base.ansible import *
+import json
+
+class SyncControllerImages(OpenStackSyncStep):
+ provides=[ControllerImages]
+ observes = ControllerImages
+ requested_interval=0
+ playbook='sync_controller_images.yaml'
+
+ def fetch_pending(self, deleted):
+ if (deleted):
+ return []
+
+ # now we return all images that need to be enacted
+ return ControllerImages.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
+
+ def map_sync_inputs(self, controller_image):
+ image_fields = {'endpoint':controller_image.controller.auth_url,
+ 'endpoint_v3': controller_image.controller.auth_url_v3,
+ 'admin_user':controller_image.controller.admin_user,
+ 'admin_password':controller_image.controller.admin_password,
+ 'domain': controller_image.controller.domain,
+ 'name':controller_image.image.name,
+ 'filepath':controller_image.image.path,
+ 'ansible_tag': '%s@%s'%(controller_image.image.name,controller_image.controller.name), # name of ansible playbook
+ }
+
+ return image_fields
+
+ def map_sync_outputs(self, controller_image, res):
+ image_id = res[0]['id']
+ controller_image.glance_image_id = image_id
+ controller_image.backend_status = '1 - OK'
+ controller_image.save()
diff --git a/xos/openstack_observer/steps/sync_controller_images.yaml b/xos/synchronizers/base/steps/sync_controller_images.yaml
similarity index 100%
rename from xos/openstack_observer/steps/sync_controller_images.yaml
rename to xos/synchronizers/base/steps/sync_controller_images.yaml
diff --git a/xos/synchronizers/base/steps/sync_controller_networks.py b/xos/synchronizers/base/steps/sync_controller_networks.py
new file mode 100644
index 0000000..990cb87
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_controller_networks.py
@@ -0,0 +1,136 @@
+import os
+import base64
+from collections import defaultdict
+from netaddr import IPAddress, IPNetwork
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models.network import *
+from core.models.slice import *
+from core.models.instance import Instance
+from xos.logger import observer_logger as logger
+from synchronizers.base.ansible import *
+from openstack.driver import OpenStackDriver
+from xos.config import Config
+import json
+
+import pdb
+
+class SyncControllerNetworks(OpenStackSyncStep):
+ requested_interval = 0
+ provides=[Network]
+ observes=ControllerNetwork
+ playbook='sync_controller_networks.yaml'
+
+ def alloc_subnet(self, uuid):
+ # 16 bits only
+ uuid_masked = uuid & 0xffff
+ a = 10
+ b = uuid_masked >> 8
+ c = uuid_masked & 0xff
+ d = 0
+
+ cidr = '%d.%d.%d.%d/24'%(a,b,c,d)
+ return cidr
+
+ def alloc_gateway(self, uuid):
+ # 16 bits only
+ uuid_masked = uuid & 0xffff
+ a = 10
+ b = uuid_masked >> 8
+ c = uuid_masked & 0xff
+ d = 1
+
+ gateway = '%d.%d.%d.%d'%(a,b,c,d)
+ return gateway
+
+
+ def save_controller_network(self, controller_network):
+ network_name = controller_network.network.name
+ subnet_name = '%s-%d'%(network_name,controller_network.pk)
+ cidr = self.alloc_subnet(controller_network.pk)
+ self.cidr=cidr
+ slice = controller_network.network.owner
+
+ network_fields = {'endpoint':controller_network.controller.auth_url,
+ 'endpoint_v3': controller_network.controller.auth_url_v3,
+ 'admin_user':slice.creator.email,
+ 'tenant_name':slice.name,
+ 'admin_password':slice.creator.remote_password,
+ 'domain': controller_network.controller.domain,
+ 'name':network_name,
+ 'subnet_name':subnet_name,
+ 'ansible_tag':'%s-%s@%s'%(network_name,slice.slicename,controller_network.controller.name),
+ 'cidr':cidr,
+ 'gateway':self.alloc_gateway(controller_network.pk),
+ 'use_vtn':getattr(Config(), "networking_use_vtn", False),
+ 'delete':False
+ }
+ return network_fields
+
+ def map_sync_outputs(self, controller_network,res):
+ network_id = res[0]['id']
+ subnet_id = res[1]['id']
+ controller_network.net_id = network_id
+ controller_network.subnet = self.cidr
+ controller_network.subnet_id = subnet_id
+ controller_network.backend_status = '1 - OK'
+ controller_network.save()
+
+
+ def map_sync_inputs(self, controller_network):
+ # XXX This check should really be made from booleans, rather than using hardcoded network names
+ if (controller_network.network.template.name not in ['Private', 'Private-Indirect', 'Private-Direct']):
+ logger.info("skipping network controller %s because it is not private" % controller_network)
+ # We only sync private networks
+ return SyncStep.SYNC_WITHOUT_RUNNING
+
+ if not controller_network.controller.admin_user:
+ logger.info("controller %r has no admin_user, skipping" % controller_network.controller)
+ return
+
+ if controller_network.network.owner and controller_network.network.owner.creator:
+ return self.save_controller_network(controller_network)
+ else:
+ raise Exception('Could not save network controller %s'%controller_network)
+
+ def map_delete_inputs(self, controller_network):
+ # XXX This check should really be made from booleans, rather than using hardcoded network names
+ if (controller_network.network.template.name not in ['Private', 'Private-Indirect', 'Private-Direct']):
+ # We only sync private networks
+ return
+ try:
+ slice = controller_network.network.owner # XXX: FIXME!!
+ except:
+ raise Exception('Could not get slice for Network %s'%controller_network.network.name)
+
+ network_name = controller_network.network.name
+ subnet_name = '%s-%d'%(network_name,controller_network.pk)
+ cidr = controller_network.subnet
+ network_fields = {'endpoint':controller_network.controller.auth_url,
+ 'admin_user':slice.creator.email, # XXX: FIXME
+ 'tenant_name':slice.name, # XXX: FIXME
+ 'admin_password':slice.creator.remote_password,
+ 'name':network_name,
+ 'subnet_name':subnet_name,
+ 'ansible_tag':'%s-%s@%s'%(network_name,slice.slicename,controller_network.controller.name),
+ 'cidr':cidr,
+ 'delete':True
+ }
+
+ return network_fields
+
+ """
+ driver = OpenStackDriver().client_driver(caller=controller_network.network.owner.creator,
+ tenant=controller_network.network.owner.name,
+ controller=controller_network.controller.name)
+ if (controller_network.router_id) and (controller_network.subnet_id):
+ driver.delete_router_interface(controller_network.router_id, controller_network.subnet_id)
+ if controller_network.subnet_id:
+ driver.delete_subnet(controller_network.subnet_id)
+ if controller_network.router_id:
+ driver.delete_router(controller_network.router_id)
+ if controller_network.net_id:
+ driver.delete_network(controller_network.net_id)
+ """
diff --git a/xos/synchronizers/base/steps/sync_controller_networks.yaml b/xos/synchronizers/base/steps/sync_controller_networks.yaml
new file mode 100644
index 0000000..b885516
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_controller_networks.yaml
@@ -0,0 +1,39 @@
+---
+- hosts: 127.0.0.1
+ connection: local
+ tasks:
+ - quantum_network:
+ auth_url={{ endpoint }}
+ login_username={{ admin_user }}
+ login_tenant_name={{ tenant_name }}
+ login_password={{ admin_password }}
+ tenant_name={{ tenant_name }}
+ name={{ name }}
+ {% if delete %}
+ state=absent
+ {% else %}
+ state=present
+ {% endif %}
+ shared=true
+ {% if not delete %}
+ - quantum_subnet:
+ auth_url={{ endpoint }}
+ login_username={{ admin_user }}
+ login_tenant_name={{ tenant_name }}
+ login_password={{ admin_password }}
+ tenant_name={{ tenant_name }}
+ name={{ subnet_name }}
+ network_name={{ name }}
+ {% if delete %}
+ state=absent
+ {% else %}
+ state=present
+ {% if use_vtn %}
+ gateway_ip={{ gateway }}
+ {% else %}
+ no_gateway=true
+ {% endif %}
+ dns_nameservers=8.8.8.8
+ cidr={{ cidr }}
+ {% endif %}
+ {% endif %}
diff --git a/xos/synchronizers/base/steps/sync_controller_site_privileges.py b/xos/synchronizers/base/steps/sync_controller_site_privileges.py
new file mode 100644
index 0000000..59919fe
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_controller_site_privileges.py
@@ -0,0 +1,84 @@
+import os
+import base64
+from collections import defaultdict
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models.site import Controller, SitePrivilege
+from core.models.user import User
+from core.models.controlleruser import ControllerUser, ControllerSitePrivilege
+from xos.logger import observer_logger as logger
+from synchronizers.base.ansible import *
+import json
+
+class SyncControllerSitePrivileges(OpenStackSyncStep):
+ provides=[SitePrivilege]
+ requested_interval=0
+ observes=ControllerSitePrivilege
+ playbook='sync_controller_users.yaml'
+
+ def map_sync_inputs(self, controller_site_privilege):
+ controller_register = json.loads(controller_site_privilege.controller.backend_register)
+ if not controller_site_privilege.controller.admin_user:
+ logger.info("controller %r has no admin_user, skipping" % controller_site_privilege.controller)
+ return
+
+ roles = [controller_site_privilege.site_privilege.role.role]
+ # setup user home site roles at controller
+ if not controller_site_privilege.site_privilege.user.site:
+ raise Exception('Siteless user %s'%controller_site_privilege.site_privilege.user.email)
+ else:
+ # look up tenant id for the user's site at the controller
+ #ctrl_site_deployments = SiteDeployment.objects.filter(
+ # site_deployment__site=controller_site_privilege.user.site,
+ # controller=controller_site_privilege.controller)
+
+ #if ctrl_site_deployments:
+ # # need the correct tenant id for site at the controller
+ # tenant_id = ctrl_site_deployments[0].tenant_id
+ # tenant_name = ctrl_site_deployments[0].site_deployment.site.login_base
+ user_fields = {
+ 'endpoint':controller_site_privilege.controller.auth_url,
+ 'endpoint_v3': controller_site_privilege.controller.auth_url_v3,
+ 'domain': controller_site_privilege.controller.domain,
+ 'name': controller_site_privilege.site_privilege.user.email,
+ 'email': controller_site_privilege.site_privilege.user.email,
+ 'password': controller_site_privilege.site_privilege.user.remote_password,
+ 'admin_user': controller_site_privilege.controller.admin_user,
+ 'admin_password': controller_site_privilege.controller.admin_password,
+ 'ansible_tag':'%s@%s'%(controller_site_privilege.site_privilege.user.email.replace('@','-at-'),controller_site_privilege.controller.name),
+ 'admin_tenant': controller_site_privilege.controller.admin_tenant,
+ 'roles':roles,
+ 'tenant':controller_site_privilege.site_privilege.site.login_base}
+
+ return user_fields
+
+ def map_sync_outputs(self, controller_site_privilege, res):
+ # results is an array in which each element corresponds to an
+ # "ok" string received per operation. If we get as many oks as
+ # the number of operations we issued, that means a grand success.
+ # Otherwise, the number of oks tell us which operation failed.
+ controller_site_privilege.role_id = res[0]['id']
+ controller_site_privilege.save()
+
+ def delete_record(self, controller_site_privilege):
+ controller_register = json.loads(controller_site_privilege.controller.backend_register)
+ if (controller_register.get('disabled',False)):
+ raise InnocuousException('Controller %s is disabled'%controller_site_privilege.controller.name)
+
+ if controller_site_privilege.role_id:
+ driver = self.driver.admin_driver(controller=controller_site_privilege.controller)
+ user = ControllerUser.objects.get(
+ controller=controller_site_privilege.controller,
+ user=controller_site_privilege.site_privilege.user
+ )
+ site = ControllerSite.objects.get(
+ controller=controller_site_privilege.controller,
+ user=controller_site_privilege.site_privilege.user
+ )
+ driver.delete_user_role(
+ user.kuser_id,
+ site.tenant_id,
+ controller_site_privilege.site_prvilege.role.role
+ )
diff --git a/xos/synchronizers/base/steps/sync_controller_sites.py b/xos/synchronizers/base/steps/sync_controller_sites.py
new file mode 100644
index 0000000..1b3c2ba
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_controller_sites.py
@@ -0,0 +1,67 @@
+import os
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.openstack.openstacksyncstep import OpenStackSyncStep
+from core.models.site import *
+from synchronizers.base.syncstep import *
+from synchronizers.base.ansible import *
+from xos.logger import observer_logger as logger
+import json
+
+class SyncControllerSites(OpenStackSyncStep):
+ requested_interval=0
+ provides=[Site]
+ observes=ControllerSite
+ playbook = 'sync_controller_sites.yaml'
+
+ def fetch_pending(self, deleted=False):
+ lobjs = ControllerSite.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False),Q(controller__isnull=False))
+ return lobjs
+
+ def map_sync_inputs(self, controller_site):
+ tenant_fields = {'endpoint':controller_site.controller.auth_url,
+ 'endpoint_v3': controller_site.controller.auth_url_v3,
+ 'domain': controller_site.controller.domain,
+ 'admin_user': controller_site.controller.admin_user,
+ 'admin_password': controller_site.controller.admin_password,
+ 'admin_tenant': controller_site.controller.admin_tenant,
+ 'ansible_tag': '%s@%s'%(controller_site.site.login_base,controller_site.controller.name), # name of ansible playbook
+ 'tenant': controller_site.site.login_base,
+ 'tenant_description': controller_site.site.name}
+ return tenant_fields
+
+ def map_sync_outputs(self, controller_site, res):
+ controller_site.tenant_id = res[0]['id']
+ controller_site.backend_status = '1 - OK'
+ controller_site.save()
+
+ def delete_record(self, controller_site):
+ controller_register = json.loads(controller_site.controller.backend_register)
+ if (controller_register.get('disabled',False)):
+ raise InnocuousException('Controller %s is disabled'%controller_site.controller.name)
+
+ if controller_site.tenant_id:
+ driver = self.driver.admin_driver(controller=controller_site.controller)
+ driver.delete_tenant(controller_site.tenant_id)
+
+ """
+ Ansible does not support tenant deletion yet
+
+ import pdb
+ pdb.set_trace()
+ template = os_template_env.get_template('delete_controller_sites.yaml')
+ tenant_fields = {'endpoint':controller_site.controller.auth_url,
+ 'admin_user': controller_site.controller.admin_user,
+ 'admin_password': controller_site.controller.admin_password,
+ 'admin_tenant': 'admin',
+ 'ansible_tag': 'controller_sites/%s@%s'%(controller_site.controller_site.site.login_base,controller_site.controller_site.deployment.name), # name of ansible playbook
+ 'tenant': controller_site.controller_site.site.login_base,
+ 'delete': True}
+
+ rendered = template.render(tenant_fields)
+ res = run_template('sync_controller_sites.yaml', tenant_fields)
+
+ if (len(res)!=1):
+ raise Exception('Could not assign roles for user %s'%tenant_fields['tenant'])
+ """
diff --git a/xos/openstack_observer/steps/sync_controller_sites.yaml b/xos/synchronizers/base/steps/sync_controller_sites.yaml
similarity index 100%
rename from xos/openstack_observer/steps/sync_controller_sites.yaml
rename to xos/synchronizers/base/steps/sync_controller_sites.yaml
diff --git a/xos/synchronizers/base/steps/sync_controller_slice_privileges.py b/xos/synchronizers/base/steps/sync_controller_slice_privileges.py
new file mode 100644
index 0000000..b78e4a0
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_controller_slice_privileges.py
@@ -0,0 +1,79 @@
+import os
+import base64
+from collections import defaultdict
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models.slice import Controller, SlicePrivilege
+from core.models.user import User
+from core.models.controlleruser import ControllerUser, ControllerSlicePrivilege
+from synchronizers.base.ansible import *
+from xos.logger import observer_logger as logger
+import json
+
+class SyncControllerSlicePrivileges(OpenStackSyncStep):
+ provides=[SlicePrivilege]
+ requested_interval=0
+ observes=ControllerSlicePrivilege
+ playbook = 'sync_controller_users.yaml'
+
+ def map_inputs(self, controller_slice_privilege):
+ if not controller_slice_privilege.controller.admin_user:
+ logger.info("controller %r has no admin_user, skipping" % controller_slice_privilege.controller)
+ return
+
+ template = os_template_env.get_template('sync_controller_users.yaml')
+ roles = [controller_slice_privilege.slice_privilege.role.role]
+ # setup user home slice roles at controller
+ if not controller_slice_privilege.slice_privilege.user.site:
+ raise Exception('Sliceless user %s'%controller_slice_privilege.slice_privilege.user.email)
+ else:
+ # look up tenant id for the user's slice at the controller
+ #ctrl_slice_deployments = SliceDeployment.objects.filter(
+ # slice_deployment__slice=controller_slice_privilege.user.slice,
+ # controller=controller_slice_privilege.controller)
+
+ #if ctrl_slice_deployments:
+ # # need the correct tenant id for slice at the controller
+ # tenant_id = ctrl_slice_deployments[0].tenant_id
+ # tenant_name = ctrl_slice_deployments[0].slice_deployment.slice.login_base
+ user_fields = {
+ 'endpoint':controller_slice_privilege.controller.auth_url,
+ 'endpoint_v3': controller_slice_privilege.controller.auth_url_v3,
+ 'domain': controller_slice_privilege.controller.domain,
+ 'name': controller_slice_privilege.slice_privilege.user.email,
+ 'email': controller_slice_privilege.slice_privilege.user.email,
+ 'password': controller_slice_privilege.slice_privilege.user.remote_password,
+ 'admin_user': controller_slice_privilege.controller.admin_user,
+ 'admin_password': controller_slice_privilege.controller.admin_password,
+ 'ansible_tag':'%s@%s@%s'%(controller_slice_privilege.slice_privilege.user.email.replace('@','-at-'),controller_slice_privilege.slice_privilege.slice.name,controller_slice_privilege.controller.name),
+ 'admin_tenant': controller_slice_privilege.controller.admin_tenant,
+ 'roles':roles,
+ 'tenant':controller_slice_privilege.slice_privilege.slice.name}
+ return user_fields
+
+ def map_sync_outputs(self, controller_slice_privilege, res):
+ controller_slice_privilege.role_id = res[0]['id']
+ controller_slice_privilege.save()
+
+ def delete_record(self, controller_slice_privilege):
+ controller_register = json.loads(controller_slice_privilege.controller.backend_register)
+ if (controller_register.get('disabled',False)):
+ raise InnocuousException('Controller %s is disabled'%controller_slice_privilege.controller.name)
+
+ if controller_slice_privilege.role_id:
+ driver = self.driver.admin_driver(controller=controller_slice_privilege.controller)
+ user = ControllerUser.objects.get(
+ controller=controller_slice_privilege.controller,
+ user=controller_slice_privilege.slice_privilege.user
+ )
+ slice = ControllerSlice.objects.get(
+ controller=controller_slice_privilege.controller,
+ user=controller_slice_privilege.slice_privilege.user
+ )
+ driver.delete_user_role(
+ user.kuser_id,
+ slice.tenant_id,
+ controller_slice_privilege.slice_prvilege.role.role
+ )
diff --git a/xos/synchronizers/base/steps/sync_controller_slices.py b/xos/synchronizers/base/steps/sync_controller_slices.py
new file mode 100644
index 0000000..97d8c29
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_controller_slices.py
@@ -0,0 +1,84 @@
+import os
+import base64
+from collections import defaultdict
+from netaddr import IPAddress, IPNetwork
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models import *
+from synchronizers.base.ansible import *
+from openstack.driver import OpenStackDriver
+from xos.logger import observer_logger as logger
+import json
+
+class SyncControllerSlices(OpenStackSyncStep):
+ provides=[Slice]
+ requested_interval=0
+ observes=ControllerSlice
+ playbook='sync_controller_slices.yaml'
+
+ def map_sync_inputs(self, controller_slice):
+ logger.info("sync'ing slice controller %s" % controller_slice)
+
+ if not controller_slice.controller.admin_user:
+ logger.info("controller %r has no admin_user, skipping" % controller_slice.controller)
+ return
+
+ controller_users = ControllerUser.objects.filter(user=controller_slice.slice.creator,
+ controller=controller_slice.controller)
+ if not controller_users:
+ raise Exception("slice createor %s has not accout at controller %s" % (controller_slice.slice.creator, controller_slice.controller.name))
+ else:
+ controller_user = controller_users[0]
+ roles = ['admin']
+
+ max_instances=int(controller_slice.slice.max_instances)
+ tenant_fields = {'endpoint':controller_slice.controller.auth_url,
+ 'endpoint_v3': controller_slice.controller.auth_url_v3,
+ 'domain': controller_slice.controller.domain,
+ 'admin_user': controller_slice.controller.admin_user,
+ 'admin_password': controller_slice.controller.admin_password,
+ 'admin_tenant': 'admin',
+ 'tenant': controller_slice.slice.name,
+ 'tenant_description': controller_slice.slice.description,
+ 'roles':roles,
+ 'name':controller_user.user.email,
+ 'ansible_tag':'%s@%s'%(controller_slice.slice.name,controller_slice.controller.name),
+ 'max_instances':max_instances}
+
+ return tenant_fields
+
+ def map_sync_outputs(self, controller_slice, res):
+ tenant_id = res[0]['id']
+ if (not controller_slice.tenant_id):
+ try:
+ driver = OpenStackDriver().admin_driver(controller=controller_slice.controller)
+ driver.shell.nova.quotas.update(tenant_id=tenant_id, instances=int(controller_slice.slice.max_instances))
+ except:
+ logger.log_exc('Could not update quota for %s'%controller_slice.slice.name)
+ raise Exception('Could not update quota for %s'%controller_slice.slice.name)
+
+ controller_slice.tenant_id = tenant_id
+ controller_slice.backend_status = '1 - OK'
+ controller_slice.save()
+
+
+ def map_delete_inputs(self, controller_slice):
+ controller_users = ControllerUser.objects.filter(user=controller_slice.slice.creator,
+ controller=controller_slice.controller)
+ if not controller_users:
+ raise Exception("slice createor %s has not accout at controller %s" % (controller_slice.slice.creator, controller_slice.controller.name))
+ else:
+ controller_user = controller_users[0]
+
+ tenant_fields = {'endpoint':controller_slice.controller.auth_url,
+ 'admin_user': controller_slice.controller.admin_user,
+ 'admin_password': controller_slice.controller.admin_password,
+ 'admin_tenant': 'admin',
+ 'tenant': controller_slice.slice.name,
+ 'tenant_description': controller_slice.slice.description,
+ 'name':controller_user.user.email,
+ 'ansible_tag':'%s@%s'%(controller_slice.slice.name,controller_slice.controller.name),
+ 'delete': True}
+ return tenant_fields
diff --git a/xos/synchronizers/base/steps/sync_controller_slices.py.bak b/xos/synchronizers/base/steps/sync_controller_slices.py.bak
new file mode 100644
index 0000000..e04da8e
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_controller_slices.py.bak
@@ -0,0 +1,95 @@
+import os
+import base64
+from collections import defaultdict
+from netaddr import IPAddress, IPNetwork
+from django.db.models import F, Q
+from xos.config import Config
+from observer.openstacksyncstep import OpenStackSyncStep
+from core.models import *
+from observer.ansible import *
+from openstack.driver import OpenStackDriver
+from util.logger import observer_logger as logger
+import json
+
+class SyncControllerSlices(OpenStackSyncStep):
+ provides=[Slice]
+ requested_interval=0
+ observes=ControllerSlice
+
+ def fetch_pending(self, deleted):
+ if (deleted):
+ return ControllerSlice.deleted_objects.all()
+ else:
+ return ControllerSlice.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
+
+ def sync_record(self, controller_slice):
+ logger.info("sync'ing slice controller %s" % controller_slice)
+
+ controller_register = json.loads(controller_slice.controller.backend_register)
+ if (controller_register.get('disabled',False)):
+ raise Exception('Controller %s is disabled'%controller_slice.controller.name)
+
+ if not controller_slice.controller.admin_user:
+ logger.info("controller %r has no admin_user, skipping" % controller_slice.controller)
+ return
+
+ controller_users = ControllerUser.objects.filter(user=controller_slice.slice.creator,
+ controller=controller_slice.controller)
+ if not controller_users:
+ raise Exception("slice createor %s has not accout at controller %s" % (controller_slice.slice.creator, controller_slice.controller.name))
+ else:
+ controller_user = controller_users[0]
+ roles = ['Admin']
+
+ max_instances=int(controller_slice.slice.max_slivers)
+ tenant_fields = {'endpoint':controller_slice.controller.auth_url,
+ 'admin_user': controller_slice.controller.admin_user,
+ 'admin_password': controller_slice.controller.admin_password,
+ 'admin_tenant': 'admin',
+ 'tenant': controller_slice.slice.name,
+ 'tenant_description': controller_slice.slice.description,
+ 'roles':roles,
+ 'name':controller_user.user.email,
+ 'ansible_tag':'%s@%s'%(controller_slice.slice.name,controller_slice.controller.name),
+ 'max_instances':max_instances}
+
+ expected_num = len(roles)+1
+ res = run_template('sync_controller_slices.yaml', tenant_fields, path='controller_slices', expected_num=expected_num)
+ tenant_id = res[0]['id']
+ if (not controller_slice.tenant_id):
+ try:
+ driver = OpenStackDriver().admin_driver(controller=controller_slice.controller)
+ driver.shell.nova.quotas.update(tenant_id=controller_slice.tenant_id, instances=int(controller_slice.slice.max_slivers))
+ except:
+ logger.log_exc('Could not update quota for %s'%controller_slice.slice.name)
+ raise Exception('Could not update quota for %s'%controller_slice.slice.name)
+
+ controller_slice.tenant_id = tenant_id
+ controller_slice.backend_status = '1 - OK'
+ controller_slice.save()
+
+
+ def delete_record(self, controller_slice):
+ controller_register = json.loads(controller_slice.controller.backend_register)
+ if (controller_register.get('disabled',False)):
+ raise Exception('Controller %s is disabled'%controller_slice.controller.name)
+
+ controller_users = ControllerUser.objects.filter(user=controller_slice.slice.creator,
+ controller=controller_slice.controller)
+ if not controller_users:
+ raise Exception("slice createor %s has not accout at controller %s" % (controller_slice.slice.creator, controller_slice.controller.name))
+ else:
+ controller_user = controller_users[0]
+
+ tenant_fields = {'endpoint':controller_slice.controller.auth_url,
+ 'admin_user': controller_slice.controller.admin_user,
+ 'admin_password': controller_slice.controller.admin_password,
+ 'admin_tenant': 'admin',
+ 'tenant': controller_slice.slice.name,
+ 'tenant_description': controller_slice.slice.description,
+ 'name':controller_user.user.email,
+ 'ansible_tag':'%s@%s'%(controller_slice.slice.name,controller_slice.controller.name),
+ 'delete': True}
+
+ expected_num = 1
+ res = run_template('sync_controller_slices.yaml', tenant_fields, path='controller_slices', expected_num=expected_num)
diff --git a/xos/openstack_observer/steps/sync_controller_slices.yaml b/xos/synchronizers/base/steps/sync_controller_slices.yaml
similarity index 100%
rename from xos/openstack_observer/steps/sync_controller_slices.yaml
rename to xos/synchronizers/base/steps/sync_controller_slices.yaml
diff --git a/xos/synchronizers/base/steps/sync_controller_users.py b/xos/synchronizers/base/steps/sync_controller_users.py
new file mode 100644
index 0000000..9af48e5
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_controller_users.py
@@ -0,0 +1,69 @@
+import os
+import base64
+from collections import defaultdict
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models.site import Controller, SiteDeployment, SiteDeployment
+from core.models.user import User
+from core.models.controlleruser import ControllerUser
+from synchronizers.base.ansible import *
+from xos.logger import observer_logger as logger
+import json
+
+class SyncControllerUsers(OpenStackSyncStep):
+ provides=[User]
+ requested_interval=0
+ observes=ControllerUser
+ playbook='sync_controller_users.yaml'
+
+ def map_sync_inputs(self, controller_user):
+ if not controller_user.controller.admin_user:
+ logger.info("controller %r has no admin_user, skipping" % controller_user.controller)
+ return
+
+ # All users will have at least the 'user' role at their home site/tenant.
+ # We must also check if the user should have the admin role
+ roles = ['user']
+ if controller_user.user.is_admin:
+ roles.append('admin')
+
+ # setup user home site roles at controller
+ if not controller_user.user.site:
+ raise Exception('Siteless user %s'%controller_user.user.email)
+ else:
+ # look up tenant id for the user's site at the controller
+ #ctrl_site_deployments = SiteDeployment.objects.filter(
+ # site_deployment__site=controller_user.user.site,
+ # controller=controller_user.controller)
+
+ #if ctrl_site_deployments:
+ # # need the correct tenant id for site at the controller
+ # tenant_id = ctrl_site_deployments[0].tenant_id
+ # tenant_name = ctrl_site_deployments[0].site_deployment.site.login_base
+ user_fields = {
+ 'endpoint':controller_user.controller.auth_url,
+ 'endpoint_v3': controller_user.controller.auth_url_v3,
+ 'domain': controller_user.controller.domain,
+ 'name': controller_user.user.email,
+ 'email': controller_user.user.email,
+ 'password': controller_user.user.remote_password,
+ 'admin_user': controller_user.controller.admin_user,
+ 'admin_password': controller_user.controller.admin_password,
+ 'ansible_tag':'%s@%s'%(controller_user.user.email.replace('@','-at-'),controller_user.controller.name),
+ 'admin_tenant': controller_user.controller.admin_tenant,
+ 'roles':roles,
+ 'tenant':controller_user.user.site.login_base
+ }
+ return user_fields
+
+ def map_sync_outputs(self, controller_user, res):
+ controller_user.kuser_id = res[0]['id']
+ controller_user.backend_status = '1 - OK'
+ controller_user.save()
+
+ def delete_record(self, controller_user):
+ if controller_user.kuser_id:
+ driver = self.driver.admin_driver(controller=controller_user.controller)
+ driver.delete_user(controller_user.kuser_id)
diff --git a/xos/openstack_observer/steps/sync_controller_users.yaml b/xos/synchronizers/base/steps/sync_controller_users.yaml
similarity index 100%
rename from xos/openstack_observer/steps/sync_controller_users.yaml
rename to xos/synchronizers/base/steps/sync_controller_users.yaml
diff --git a/xos/synchronizers/base/steps/sync_images.py b/xos/synchronizers/base/steps/sync_images.py
new file mode 100644
index 0000000..8049ac1
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_images.py
@@ -0,0 +1,52 @@
+import os
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from core.models.image import Image
+from xos.logger import observer_logger as logger
+
+class SyncImages(OpenStackSyncStep):
+ provides=[Image]
+ requested_interval=0
+ observes=Image
+
+ def fetch_pending(self, deleted):
+ # Images come from the back end
+ # You can't delete them
+ if (deleted):
+ logger.info("SyncImages: returning because deleted=True")
+ return []
+
+ # get list of images on disk
+ images_path = Config().observer_images_directory
+
+ logger.info("SyncImages: deleted=False, images_path=%s" % images_path)
+
+ available_images = {}
+ if os.path.exists(images_path):
+ for f in os.listdir(images_path):
+ filename = os.path.join(images_path, f)
+ if os.path.isfile(filename):
+ available_images[f] = filename
+
+ logger.info("SyncImages: available_images = %s" % str(available_images))
+
+ images = Image.objects.all()
+ image_names = [image.name for image in images]
+
+ for image_name in available_images:
+ #remove file extension
+ clean_name = ".".join(image_name.split('.')[:-1])
+ if clean_name not in image_names:
+ logger.info("SyncImages: adding %s" % clean_name)
+ image = Image(name=clean_name,
+ disk_format='raw',
+ container_format='bare',
+ path = available_images[image_name])
+ image.save()
+
+ return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
+
+ def sync_record(self, image):
+ image.save()
diff --git a/xos/synchronizers/base/steps/sync_instances.py b/xos/synchronizers/base/steps/sync_instances.py
new file mode 100644
index 0000000..335ca4a
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_instances.py
@@ -0,0 +1,174 @@
+import os
+import base64
+import socket
+from django.db.models import F, Q
+from xos.config import Config
+from xos.settings import RESTAPI_HOSTNAME, RESTAPI_PORT
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from core.models.instance import Instance
+from core.models.slice import Slice, SlicePrivilege, ControllerSlice
+from core.models.network import Network, NetworkSlice, ControllerNetwork
+from synchronizers.base.ansible import *
+from synchronizers.base.syncstep import *
+from xos.logger import observer_logger as logger
+
+def escape(s):
+ s = s.replace('\n',r'\n').replace('"',r'\"')
+ return s
+
+class SyncInstances(OpenStackSyncStep):
+ provides=[Instance]
+ requested_interval=0
+ observes=Instance
+ playbook='sync_instances.yaml'
+
+ def fetch_pending(self, deletion=False):
+ objs = super(SyncInstances, self).fetch_pending(deletion)
+ objs = [x for x in objs if x.isolation=="vm"]
+ return objs
+
+ def get_userdata(self, instance, pubkeys):
+ userdata = '#cloud-config\n\nopencloud:\n slicename: "%s"\n hostname: "%s"\n restapi_hostname: "%s"\n restapi_port: "%s"\n' % (instance.slice.name, instance.node.name, RESTAPI_HOSTNAME, str(RESTAPI_PORT))
+ userdata += 'ssh_authorized_keys:\n'
+ for key in pubkeys:
+ userdata += ' - %s\n' % key
+ return userdata
+
+ def map_sync_inputs(self, instance):
+ inputs = {}
+ metadata_update = {}
+ if (instance.numberCores):
+ metadata_update["cpu_cores"] = str(instance.numberCores)
+
+ for tag in instance.slice.tags.all():
+ if tag.name.startswith("sysctl-"):
+ metadata_update[tag.name] = tag.value
+
+ slice_memberships = SlicePrivilege.objects.filter(slice=instance.slice)
+ pubkeys = set([sm.user.public_key for sm in slice_memberships if sm.user.public_key])
+ if instance.creator.public_key:
+ pubkeys.add(instance.creator.public_key)
+
+ if instance.slice.creator.public_key:
+ pubkeys.add(instance.slice.creator.public_key)
+
+ if instance.slice.service and instance.slice.service.public_key:
+ pubkeys.add(instance.slice.service.public_key)
+
+ nics = []
+ networks = [ns.network for ns in NetworkSlice.objects.filter(slice=instance.slice)]
+ controller_networks = ControllerNetwork.objects.filter(network__in=networks,
+ controller=instance.node.site_deployment.controller)
+
+ for controller_network in controller_networks:
+
+ # Lenient exception - causes slow backoff
+ if controller_network.network.template.visibility == 'private' and \
+ controller_network.network.template.translation == 'none':
+ if not controller_network.net_id:
+ raise DeferredException("Instance %s Private Network %s has no id; Try again later" % (instance, controller_network.network.name))
+ nics.append(controller_network.net_id)
+
+ # now include network template
+ network_templates = [network.template.shared_network_name for network in networks \
+ if network.template.shared_network_name]
+
+ #driver = self.driver.client_driver(caller=instance.creator, tenant=instance.slice.name, controller=instance.controllerNetwork)
+ driver = self.driver.admin_driver(tenant='admin', controller=instance.node.site_deployment.controller)
+ nets = driver.shell.quantum.list_networks()['networks']
+ for net in nets:
+ if net['name'] in network_templates:
+ nics.append(net['id'])
+
+ if (not nics):
+ for net in nets:
+ if net['name']=='public':
+ nics.append(net['id'])
+
+ image_name = None
+ controller_images = instance.image.controllerimages.filter(controller=instance.node.site_deployment.controller)
+ if controller_images:
+ image_name = controller_images[0].image.name
+ logger.info("using image from ControllerImage object: " + str(image_name))
+
+ if image_name is None:
+ controller_driver = self.driver.admin_driver(controller=instance.node.site_deployment.controller)
+ images = controller_driver.shell.glanceclient.images.list()
+ for image in images:
+ if image.name == instance.image.name or not image_name:
+ image_name = image.name
+ logger.info("using image from glance: " + str(image_name))
+
+ try:
+ legacy = Config().observer_legacy
+ except:
+ legacy = False
+
+ if (legacy):
+ host_filter = instance.node.name.split('.',1)[0]
+ else:
+ host_filter = instance.node.name.strip()
+
+ availability_zone_filter = 'nova:%s'%host_filter
+ instance_name = '%s-%d'%(instance.slice.name,instance.id)
+ self.instance_name = instance_name
+
+ userData = self.get_userdata(instance, pubkeys)
+ if instance.userData:
+ userData += instance.userData
+
+ controller = instance.node.site_deployment.controller
+ fields = {'endpoint':controller.auth_url,
+ 'endpoint_v3': controller.auth_url_v3,
+ 'domain': controller.domain,
+ 'admin_user': instance.creator.email,
+ 'admin_password': instance.creator.remote_password,
+ 'admin_tenant': instance.slice.name,
+ 'tenant': instance.slice.name,
+ 'tenant_description': instance.slice.description,
+ 'name':instance_name,
+ 'ansible_tag':instance_name,
+ 'availability_zone': availability_zone_filter,
+ 'image_name':image_name,
+ 'flavor_name':instance.flavor.name,
+ 'nics':nics,
+ 'meta':metadata_update,
+ 'user_data':r'%s'%escape(userData)}
+ return fields
+
+
+ def map_sync_outputs(self, instance, res):
+ instance_id = res[0]['info']['OS-EXT-SRV-ATTR:instance_name']
+ instance_uuid = res[0]['id']
+
+ try:
+ hostname = res[0]['info']['OS-EXT-SRV-ATTR:hypervisor_hostname']
+ ip = socket.gethostbyname(hostname)
+ instance.ip = ip
+ except:
+ pass
+
+ instance.instance_id = instance_id
+ instance.instance_uuid = instance_uuid
+ instance.instance_name = self.instance_name
+ instance.save()
+
+
+ def map_delete_inputs(self, instance):
+ controller_register = json.loads(instance.node.site_deployment.controller.backend_register)
+
+ if (controller_register.get('disabled',False)):
+ raise InnocuousException('Controller %s is disabled'%instance.node.site_deployment.controller.name)
+
+ instance_name = '%s-%d'%(instance.slice.name,instance.id)
+ controller = instance.node.site_deployment.controller
+ input = {'endpoint':controller.auth_url,
+ 'admin_user': instance.creator.email,
+ 'admin_password': instance.creator.remote_password,
+ 'admin_tenant': instance.slice.name,
+ 'tenant': instance.slice.name,
+ 'tenant_description': instance.slice.description,
+ 'name':instance_name,
+ 'ansible_tag':instance_name,
+ 'delete': True}
+ return input
diff --git a/xos/openstack_observer/steps/sync_instances.yaml b/xos/synchronizers/base/steps/sync_instances.yaml
similarity index 100%
rename from xos/openstack_observer/steps/sync_instances.yaml
rename to xos/synchronizers/base/steps/sync_instances.yaml
diff --git a/xos/synchronizers/base/steps/sync_object.py b/xos/synchronizers/base/steps/sync_object.py
new file mode 100644
index 0000000..a6a939f
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_object.py
@@ -0,0 +1,20 @@
+import os
+import base64
+from collections import defaultdict
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models import *
+from synchronizers.base.ansible import *
+from openstack.driver import OpenStackDriver
+from xos.logger import observer_logger as logger
+import json
+
+class SyncObject(OpenStackSyncStep):
+ provides=[] # Caller fills this in
+ requested_interval=0
+ observes=[] # Caller fills this in
+
+ def sync_record(self, r):
+ raise DeferredException('Waiting for Service dependency: %r'%r)
diff --git a/xos/synchronizers/base/steps/sync_ports.py b/xos/synchronizers/base/steps/sync_ports.py
new file mode 100644
index 0000000..21376e5
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_ports.py
@@ -0,0 +1,196 @@
+import os
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from core.models import Controller
+from core.models.network import *
+from xos.logger import observer_logger as logger
+
+class SyncPorts(OpenStackSyncStep):
+ requested_interval = 0 # 3600
+ provides=[Port]
+ observes=Port
+
+ # The way it works is to enumerate the all of the ports that quantum
+ # has, and then work backward from each port's network-id to determine
+ # which Network is associated from the port.
+
+ def call(self, **args):
+ logger.info("sync'ing network instances")
+
+ ports = Port.objects.all()
+ ports_by_id = {}
+ ports_by_neutron_port = {}
+ for port in ports:
+ ports_by_id[port.id] = port
+ ports_by_neutron_port[port.port_id] = port
+
+ networks = Network.objects.all()
+ networks_by_id = {}
+ for network in networks:
+ for nd in network.controllernetworks.all():
+ networks_by_id[nd.net_id] = network
+
+ #logger.info("networks_by_id = ")
+ #for (network_id, network) in networks_by_id.items():
+ # logger.info(" %s: %s" % (network_id, network.name))
+
+ instances = Instance.objects.all()
+ instances_by_instance_uuid = {}
+ for instance in instances:
+ instances_by_instance_uuid[instance.instance_uuid] = instance
+
+ # Get all ports in all controllers
+
+ ports_by_id = {}
+ templates_by_id = {}
+ for controller in Controller.objects.all():
+ if not controller.admin_tenant:
+ logger.info("controller %s has no admin_tenant" % controller)
+ continue
+ try:
+ driver = self.driver.admin_driver(controller = controller)
+ ports = driver.shell.quantum.list_ports()["ports"]
+ except:
+ logger.log_exc("failed to get ports from controller %s" % controller)
+ continue
+
+ for port in ports:
+ ports_by_id[port["id"]] = port
+
+ # public-nat and public-dedicated networks don't have a net-id anywhere
+ # in the data model, so build up a list of which ids map to which network
+ # templates.
+ try:
+ neutron_networks = driver.shell.quantum.list_networks()["networks"]
+ except:
+ print "failed to get networks from controller %s" % controller
+ continue
+ for network in neutron_networks:
+ for template in NetworkTemplate.objects.all():
+ if template.shared_network_name == network["name"]:
+ templates_by_id[network["id"]] = template
+
+ for port in ports_by_id.values():
+ #logger.info("port %s" % str(port))
+ if port["id"] in ports_by_neutron_port:
+ # we already have it
+ #logger.info("already accounted for port %s" % port["id"])
+ continue
+
+ if port["device_owner"] != "compute:nova":
+ # we only want the ports that connect to instances
+ #logger.info("port %s is not a compute port, it is a %s" % (port["id"], port["device_owner"]))
+ continue
+
+ instance = instances_by_instance_uuid.get(port['device_id'], None)
+ if not instance:
+ logger.info("no instance for port %s device_id %s" % (port["id"], port['device_id']))
+ continue
+
+ network = networks_by_id.get(port['network_id'], None)
+ if not network:
+ # maybe it's public-nat or public-dedicated. Search the templates for
+ # the id, then see if the instance's slice has some network that uses
+ # that template
+ template = templates_by_id.get(port['network_id'], None)
+ if template and instance.slice:
+ for candidate_network in instance.slice.networks.all():
+ if candidate_network.template == template:
+ network=candidate_network
+ if not network:
+ logger.info("no network for port %s network %s" % (port["id"], port["network_id"]))
+
+ # we know it's associated with a instance, but we don't know
+ # which network it is part of.
+
+ continue
+
+ if network.template.shared_network_name:
+ # If it's a shared network template, then more than one network
+ # object maps to the quantum network. We have to do a whole bunch
+ # of extra work to find the right one.
+ networks = network.template.network_set.all()
+ network = None
+ for candidate_network in networks:
+ if (candidate_network.owner == instance.slice):
+ logger.info("found network %s" % candidate_network)
+ network = candidate_network
+
+ if not network:
+ logger.info("failed to find the correct network for a shared template for port %s network %s" % (port["id"], port["network_id"]))
+ continue
+
+ if not port["fixed_ips"]:
+ logger.info("port %s has no fixed_ips" % port["id"])
+ continue
+
+ ip=port["fixed_ips"][0]["ip_address"]
+ mac=port["mac_address"]
+ logger.info("creating Port (%s, %s, %s, %s)" % (str(network), str(instance), ip, str(port["id"])))
+
+ ns = Port(network=network,
+ instance=instance,
+ ip=ip,
+ mac=mac,
+ port_id=port["id"])
+
+ try:
+ ns.save()
+ except:
+ logger.log_exc("failed to save port %s" % str(ns))
+ continue
+
+ # For ports that were created by the user, find that ones
+ # that don't have neutron ports, and create them.
+ for port in Port.objects.filter(Q(port_id__isnull=True), Q(instance__isnull=False) ):
+ logger.info("XXX working on port %s" % port)
+ controller = port.instance.node.site_deployment.controller
+ slice = port.instance.slice
+
+ if controller:
+ cn=port.network.controllernetworks.filter(controller=controller)
+ if not cn:
+ logger.log_exc("no controllernetwork for %s" % port)
+ continue
+ cn=cn[0]
+ if cn.lazy_blocked:
+ cn.lazy_blocked=False
+ cn.save()
+ logger.info("deferring port %s because controllerNetwork was lazy-blocked" % port)
+ continue
+ if not cn.net_id:
+ logger.info("deferring port %s because controllerNetwork does not have a port-id yet" % port)
+ continue
+ try:
+ # We need to use a client driver that specifies the tenant
+ # of the destination instance. Nova-compute will not connect
+ # ports to instances if the port's tenant does not match
+ # the instance's tenant.
+
+ # A bunch of stuff to compensate for OpenStackDriver.client_driveR()
+ # not being in working condition.
+ from openstack.client import OpenStackClient
+ from openstack.driver import OpenStackDriver
+ caller = port.network.owner.creator
+ auth = {'username': caller.email,
+ 'password': caller.remote_password,
+ 'tenant': slice.name}
+ client = OpenStackClient(controller=controller, **auth) # cacert=self.config.nova_ca_ssl_cert,
+ driver = OpenStackDriver(client=client)
+
+ neutron_port = driver.shell.quantum.create_port({"port": {"network_id": cn.net_id}})["port"]
+ port.port_id = neutron_port["id"]
+ if neutron_port["fixed_ips"]:
+ port.ip = neutron_port["fixed_ips"][0]["ip_address"]
+ port.mac = neutron_port["mac_address"]
+ except:
+ logger.log_exc("failed to create neutron port for %s" % port)
+ continue
+ port.save()
+
+ def delete_record(self, network_instance):
+ # Nothing to do, this is an OpenCloud object
+ pass
+
diff --git a/xos/synchronizers/base/steps/sync_roles.py b/xos/synchronizers/base/steps/sync_roles.py
new file mode 100644
index 0000000..e859316
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_roles.py
@@ -0,0 +1,23 @@
+import os
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from core.models.role import Role
+from core.models.site import SiteRole, Controller, ControllerRole
+from core.models.slice import SliceRole
+from xos.logger import observer_logger as logger
+
+class SyncRoles(OpenStackSyncStep):
+ provides=[Role]
+ requested_interval=0
+ observes=[SiteRole,SliceRole,ControllerRole]
+
+ def sync_record(self, role):
+ if not role.enacted:
+ controllers = Controller.objects.all()
+ for controller in controllers:
+ driver = self.driver.admin_driver(controller=controller)
+ driver.create_role(role.role)
+ role.save()
+
diff --git a/xos/synchronizers/base/steps/sync_slivers.py.bak b/xos/synchronizers/base/steps/sync_slivers.py.bak
new file mode 100644
index 0000000..c4240fa
--- /dev/null
+++ b/xos/synchronizers/base/steps/sync_slivers.py.bak
@@ -0,0 +1,179 @@
+import os
+import base64
+import socket
+from django.db.models import F, Q
+from xos.config import Config
+from xos.settings import RESTAPI_HOSTNAME, RESTAPI_PORT
+from observer.openstacksyncstep import OpenStackSyncStep
+from core.models.sliver import Sliver
+from core.models.slice import Slice, SlicePrivilege, ControllerSlice
+from core.models.network import Network, NetworkSlice, ControllerNetwork
+from observer.ansible import *
+from util.logger import observer_logger as logger
+
+def escape(s):
+ s = s.replace('\n',r'\n').replace('"',r'\"')
+ return s
+
+class SyncSlivers(OpenStackSyncStep):
+ provides=[Sliver]
+ requested_interval=0
+ observes=Sliver
+
+ def get_userdata(self, sliver, pubkeys):
+ userdata = '#cloud-config\n\nopencloud:\n slicename: "%s"\n hostname: "%s"\n restapi_hostname: "%s"\n restapi_port: "%s"\n' % (sliver.slice.name, sliver.node.name, RESTAPI_HOSTNAME, str(RESTAPI_PORT))
+ userdata += 'ssh_authorized_keys:\n'
+ for key in pubkeys:
+ userdata += ' - %s\n' % key
+ return userdata
+
+ def sync_record(self, sliver):
+ logger.info("sync'ing sliver:%s slice:%s controller:%s " % (sliver, sliver.slice.name, sliver.node.site_deployment.controller))
+ controller_register = json.loads(sliver.node.site_deployment.controller.backend_register)
+
+ if (controller_register.get('disabled',False)):
+ raise Exception('Controller %s is disabled'%sliver.node.site_deployment.controller.name)
+
+ metadata_update = {}
+ if (sliver.numberCores):
+ metadata_update["cpu_cores"] = str(sliver.numberCores)
+
+ for tag in sliver.slice.tags.all():
+ if tag.name.startswith("sysctl-"):
+ metadata_update[tag.name] = tag.value
+
+ # public keys
+ slice_memberships = SlicePrivilege.objects.filter(slice=sliver.slice)
+ pubkeys = set([sm.user.public_key for sm in slice_memberships if sm.user.public_key])
+ if sliver.creator.public_key:
+ pubkeys.add(sliver.creator.public_key)
+
+ if sliver.slice.creator.public_key:
+ pubkeys.add(sliver.slice.creator.public_key)
+
+ if sliver.slice.service and sliver.slice.service.public_key:
+ pubkeys.add(sliver.slice.service.public_key)
+
+ if sliver.slice.service and sliver.slice.service.public_key:
+ pubkeys.add(sliver.slice.service.public_key)
+
+ nics = []
+ networks = [ns.network for ns in NetworkSlice.objects.filter(slice=sliver.slice)]
+ controller_networks = ControllerNetwork.objects.filter(network__in=networks,
+ controller=sliver.node.site_deployment.controller)
+
+ for controller_network in controller_networks:
+ if controller_network.network.template.visibility == 'private' and \
+ controller_network.network.template.translation == 'none':
+ if not controller_network.net_id:
+ raise Exception("Private Network %s has no id; Try again later" % controller_network.network.name)
+ nics.append(controller_network.net_id)
+
+ # now include network template
+ network_templates = [network.template.shared_network_name for network in networks \
+ if network.template.shared_network_name]
+
+ #driver = self.driver.client_driver(caller=sliver.creator, tenant=sliver.slice.name, controller=sliver.controllerNetwork)
+ driver = self.driver.admin_driver(tenant='admin', controller=sliver.node.site_deployment.controller)
+ nets = driver.shell.quantum.list_networks()['networks']
+ for net in nets:
+ if net['name'] in network_templates:
+ nics.append(net['id'])
+
+ if (not nics):
+ for net in nets:
+ if net['name']=='public':
+ nics.append(net['id'])
+
+ image_id = None
+ controller_images = sliver.image.controllerimages.filter(controller=sliver.node.site_deployment.controller)
+ if controller_images:
+ image_id = controller_images[0].glance_image_id
+ logger.info("using image_id from ControllerImage object: " + str(image_id))
+
+ if image_id is None:
+ controller_driver = self.driver.admin_driver(controller=sliver.node.site_deployment.controller)
+ image_id = None
+ images = controller_driver.shell.glanceclient.images.list()
+ for image in images:
+ if image.name == sliver.image.name or not image_id:
+ image_id = image.id
+ logger.info("using image_id from glance: " + str(image_id))
+
+ try:
+ legacy = Config().observer_legacy
+ except:
+ legacy = False
+
+ if (legacy):
+ host_filter = sliver.node.name.split('.',1)[0]
+ else:
+ host_filter = sliver.node.name.strip()
+
+ availability_zone_filter = 'nova:%s'%host_filter
+ sliver_name = '%s-%d'%(sliver.slice.name,sliver.id)
+
+ userData = self.get_userdata(sliver, pubkeys)
+ if sliver.userData:
+ userData = sliver.userData
+
+ controller = sliver.node.site_deployment.controller
+ tenant_fields = {'endpoint':controller.auth_url,
+ 'admin_user': sliver.creator.email,
+ 'admin_password': sliver.creator.remote_password,
+ 'admin_tenant': sliver.slice.name,
+ 'tenant': sliver.slice.name,
+ 'tenant_description': sliver.slice.description,
+ 'name':sliver_name,
+ 'ansible_tag':sliver_name,
+ 'availability_zone': availability_zone_filter,
+ 'image_id':image_id,
+ 'flavor_id':sliver.flavor.id,
+ 'nics':nics,
+ 'meta':metadata_update,
+ 'user_data':r'%s'%escape(userData)}
+
+ res = run_template('sync_slivers.yaml', tenant_fields,path='slivers', expected_num=1)
+ sliver_id = res[0]['info']['OS-EXT-SRV-ATTR:instance_name']
+ sliver_uuid = res[0]['id']
+
+ try:
+ hostname = res[0]['info']['OS-EXT-SRV-ATTR:hypervisor_hostname']
+ ip = socket.gethostbyname(hostname)
+ sliver.ip = ip
+ except:
+ pass
+
+ sliver.instance_id = sliver_id
+ sliver.instance_uuid = sliver_uuid
+ sliver.instance_name = sliver_name
+ sliver.save()
+
+ def delete_record(self, sliver):
+ controller_register = json.loads(sliver.node.site_deployment.controller.backend_register)
+
+ if (controller_register.get('disabled',False)):
+ raise Exception('Controller %s is disabled'%sliver.node.site_deployment.controller.name)
+
+ sliver_name = '%s-%d'%(sliver.slice.name,sliver.id)
+ controller = sliver.node.site_deployment.controller
+ tenant_fields = {'endpoint':controller.auth_url,
+ 'admin_user': sliver.creator.email,
+ 'admin_password': sliver.creator.remote_password,
+ 'admin_tenant': sliver.slice.name,
+ 'tenant': sliver.slice.name,
+ 'tenant_description': sliver.slice.description,
+ 'name':sliver_name,
+ 'ansible_tag':sliver_name,
+ 'delete': True}
+
+ try:
+ res = run_template('sync_slivers.yaml', tenant_fields,path='slivers', expected_num=1)
+ except Exception,e:
+ print "Could not sync %s"%sliver_name
+ #import traceback
+ #traceback.print_exc()
+ raise e
+
+ if (len(res)!=1):
+ raise Exception('Could not delete sliver %s'%sliver.slice.name)
diff --git a/xos/openstack_observer/steps/teardown_container.yaml b/xos/synchronizers/base/steps/teardown_container.yaml
similarity index 100%
rename from xos/openstack_observer/steps/teardown_container.yaml
rename to xos/synchronizers/base/steps/teardown_container.yaml
diff --git a/xos/synchronizers/base/syncstep-portal.py b/xos/synchronizers/base/syncstep-portal.py
new file mode 100644
index 0000000..66ec1af
--- /dev/null
+++ b/xos/synchronizers/base/syncstep-portal.py
@@ -0,0 +1,221 @@
+import os
+import base64
+from datetime import datetime
+from xos.config import Config
+from xos.logger import Logger, logging
+from synchronizers.base.steps import *
+from django.db.models import F, Q
+from core.models import *
+from django.db import reset_queries
+import json
+import time
+import pdb
+import traceback
+
+logger = Logger(level=logging.INFO)
+
+def f7(seq):
+ seen = set()
+ seen_add = seen.add
+ return [ x for x in seq if not (x in seen or seen_add(x))]
+
+def elim_dups(backend_str):
+ strs = backend_str.split('/')
+ strs = map(lambda x:x.split('(')[0],strs)
+ strs2 = f7(strs)
+ return '/'.join(strs2)
+
+def deepgetattr(obj, attr):
+ return reduce(getattr, attr.split('.'), obj)
+
+
+class InnocuousException(Exception):
+ pass
+
+class FailedDependency(Exception):
+ pass
+
+class SyncStep(object):
+ """ An XOS Sync step.
+
+ Attributes:
+ psmodel Model name the step synchronizes
+ dependencies list of names of models that must be synchronized first if the current model depends on them
+ """
+ slow=False
+ def get_prop(prop):
+ try:
+ sync_config_dir = Config().sync_config_dir
+ except:
+ sync_config_dir = '/etc/xos/sync'
+ prop_config_path = '/'.join(sync_config_dir,self.name,prop)
+ return open(prop_config_path).read().rstrip()
+
+ def __init__(self, **args):
+ """Initialize a sync step
+ Keyword arguments:
+ name -- Name of the step
+ provides -- XOS models sync'd by this step
+ """
+ dependencies = []
+ self.driver = args.get('driver')
+ self.error_map = args.get('error_map')
+
+ try:
+ self.soft_deadline = int(self.get_prop('soft_deadline_seconds'))
+ except:
+ self.soft_deadline = 5 # 5 seconds
+
+ return
+
+ def fetch_pending(self, deletion=False):
+ # This is the most common implementation of fetch_pending
+ # Steps should override it if they have their own logic
+ # for figuring out what objects are outstanding.
+ main_obj = self.observes
+ if (not deletion):
+ objs = main_obj.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
+ else:
+ objs = main_obj.deleted_objects.all()
+
+ return objs
+ #return Sliver.objects.filter(ip=None)
+
+ def check_dependencies(self, obj, failed):
+ for dep in self.dependencies:
+ peer_name = dep[0].lower() + dep[1:] # django names are camelCased with the first letter lower
+
+ try:
+ peer_object = deepgetattr(obj, peer_name)
+ try:
+ peer_objects = peer_object.all()
+ except AttributeError:
+ peer_objects = [peer_object]
+ except:
+ peer_objects = []
+
+ if (hasattr(obj,'controller')):
+ try:
+ peer_objects = filter(lambda o:o.controller==obj.controller, peer_objects)
+ except AttributeError:
+ pass
+
+ if (failed in peer_objects):
+ if (obj.backend_status!=failed.backend_status):
+ obj.backend_status = failed.backend_status
+ obj.save(update_fields=['backend_status'])
+ raise FailedDependency("Failed dependency for %s:%s peer %s:%s failed %s:%s" % (obj.__class__.__name__, str(getattr(obj,"pk","no_pk")), peer_object.__class__.__name__, str(getattr(peer_object,"pk","no_pk")), failed.__class__.__name__, str(getattr(failed,"pk","no_pk"))))
+
+ def call(self, failed=[], deletion=False):
+ pending = self.fetch_pending(deletion)
+ for o in pending:
+ # another spot to clean up debug state
+ try:
+ reset_queries()
+ except:
+ # this shouldn't happen, but in case it does, catch it...
+ logger.log_exc("exception in reset_queries")
+
+ sync_failed = False
+ try:
+ backoff_disabled = Config().observer_backoff_disabled
+ except:
+ backoff_disabled = 0
+
+ try:
+ scratchpad = json.loads(o.backend_register)
+ if (scratchpad):
+ next_run = scratchpad['next_run']
+ if (not backoff_disabled and next_run>time.time()):
+ sync_failed = True
+ except:
+ logger.log_exc("Exception while loading scratchpad")
+ pass
+
+ if (not sync_failed):
+ try:
+ for f in failed:
+ self.check_dependencies(o,f) # Raises exception if failed
+ if (deletion):
+ self.delete_record(o)
+ o.delete(purge=True)
+ else:
+ self.sync_record(o)
+ o.enacted = datetime.now() # Is this the same timezone? XXX
+ scratchpad = {'next_run':0, 'exponent':0}
+ o.backend_register = json.dumps(scratchpad)
+ o.backend_status = "1 - OK"
+ o.save(update_fields=['enacted','backend_status','backend_register'])
+ except (InnocuousException,Exception) as e:
+ logger.log_exc("Syncstep caught exception")
+
+ force_error = False
+ try:
+ if (o.backend_status.startswith('2 - ')):
+ force_error = False # Already in error state
+ str_e = '%s/%s'%(o.backend_status[4:],str(e))
+ str_e = elim_dups(str_e)
+ else:
+ str_e = str(e)
+ except:
+ str_e = str(e)
+
+ if (not str_e):
+ str_e = 'Unknown'
+
+ try:
+ error = self.error_map.map(str_e)
+ except:
+ error = str_e
+
+ if isinstance(e, InnocuousException) and not force_error:
+ o.backend_status = '1 - %s'%error
+ else:
+ o.backend_status = '2 - %s'%error
+
+ cmd = 'wget -O /dev/null -q "http://xoslnprof.appspot.com/command?action=pushlog&node=1&log_path=/%s/%s"'%(self.__class__.__name__,error)
+ os.system(cmd)
+
+ try:
+ scratchpad = json.loads(o.backend_register)
+ scratchpad['exponent']
+ except:
+ logger.log_exc("Exception while updating scratchpad")
+ scratchpad = {'next_run':0, 'exponent':0}
+
+ # Second failure
+ if (scratchpad['exponent']):
+ delay = scratchpad['exponent'] * 600 # 10 minutes
+ if (delay<1440):
+ delay = 1440
+ scratchpad['next_run'] = time.time() + delay
+
+ scratchpad['exponent']+=1
+
+ o.backend_register = json.dumps(scratchpad)
+
+ # TOFIX:
+ # DatabaseError: value too long for type character varying(140)
+ if (o.pk):
+ try:
+ o.backend_status = o.backend_status[:1024]
+ o.save(update_fields=['backend_status','backend_register','updated'])
+ except:
+ print "Could not update backend status field!"
+ pass
+ sync_failed = True
+
+
+ if (sync_failed):
+ failed.append(o)
+
+ return failed
+
+ def sync_record(self, o):
+ return
+
+ def delete_record(self, o):
+ return
+
+ def __call__(self, **args):
+ return self.call(**args)
\ No newline at end of file
diff --git a/xos/synchronizers/base/syncstep.py b/xos/synchronizers/base/syncstep.py
new file mode 100644
index 0000000..bdab8f3
--- /dev/null
+++ b/xos/synchronizers/base/syncstep.py
@@ -0,0 +1,307 @@
+import os
+import base64
+from datetime import datetime
+from xos.config import Config
+from xos.logger import Logger, logging
+from synchronizers.base.steps import *
+from django.db.models import F, Q
+from core.models import *
+from django.db import reset_queries
+from synchronizers.base.ansible import *
+from generate.dependency_walker import *
+
+from time import time
+import json
+import time
+import pdb
+
+logger = Logger(level=logging.INFO)
+
+def f7(seq):
+ seen = set()
+ seen_add = seen.add
+ return [ x for x in seq if not (x in seen or seen_add(x))]
+
+def elim_dups(backend_str):
+ strs = backend_str.split(' // ')
+ strs2 = f7(strs)
+ return ' // '.join(strs2)
+
+def deepgetattr(obj, attr):
+ return reduce(getattr, attr.split('.'), obj)
+
+
+class InnocuousException(Exception):
+ pass
+
+class DeferredException(Exception):
+ pass
+
+class FailedDependency(Exception):
+ pass
+
+class SyncStep(object):
+ """ An XOS Sync step.
+
+ Attributes:
+ psmodel Model name the step synchronizes
+ dependencies list of names of models that must be synchronized first if the current model depends on them
+ """
+
+ # map_sync_outputs can return this value to cause a step to be marked
+ # successful without running ansible. Used for sync_network_controllers
+ # on nat networks.
+ SYNC_WITHOUT_RUNNING = "sync_without_running"
+
+ slow=False
+ def get_prop(self, prop):
+ try:
+ sync_config_dir = Config().sync_config_dir
+ except:
+ sync_config_dir = '/etc/xos/sync'
+ prop_config_path = '/'.join(sync_config_dir,self.name,prop)
+ return open(prop_config_path).read().rstrip()
+
+ def __init__(self, **args):
+ """Initialize a sync step
+ Keyword arguments:
+ name -- Name of the step
+ provides -- XOS models sync'd by this step
+ """
+ dependencies = []
+ self.driver = args.get('driver')
+ self.error_map = args.get('error_map')
+
+ try:
+ self.soft_deadline = int(self.get_prop('soft_deadline_seconds'))
+ except:
+ self.soft_deadline = 5 # 5 seconds
+
+ return
+
+ def fetch_pending(self, deletion=False):
+ # This is the most common implementation of fetch_pending
+ # Steps should override it if they have their own logic
+ # for figuring out what objects are outstanding.
+
+ main_objs = self.observes
+ if (type(main_objs) is not list):
+ main_objs=[main_objs]
+
+ objs = []
+ for main_obj in main_objs:
+ if (not deletion):
+ lobjs = main_obj.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False),Q(no_sync=False))
+ else:
+ lobjs = main_obj.deleted_objects.all()
+ objs.extend(lobjs)
+
+ return objs
+ #return Instance.objects.filter(ip=None)
+
+ def check_dependencies(self, obj, failed):
+ for dep in self.dependencies:
+ peer_name = dep[0].lower() + dep[1:] # django names are camelCased with the first letter lower
+
+ peer_objects=[]
+ try:
+ peer_names = plural(peer_name)
+ peer_object_list=[]
+
+ try:
+ peer_object_list.append(deepgetattr(obj, peer_name))
+ except:
+ pass
+
+ try:
+ peer_object_list.append(deepgetattr(obj, peer_names))
+ except:
+ pass
+
+ for peer_object in peer_object_list:
+ try:
+ peer_objects.extend(peer_object.all())
+ except AttributeError:
+ peer_objects.append(peer_object)
+ except:
+ peer_objects = []
+
+ if (hasattr(obj,'controller')):
+ try:
+ peer_objects = filter(lambda o:o.controller==obj.controller, peer_objects)
+ except AttributeError:
+ pass
+
+ if (failed in peer_objects):
+ if (obj.backend_status!=failed.backend_status):
+ obj.backend_status = failed.backend_status
+ obj.save(update_fields=['backend_status'])
+ raise FailedDependency("Failed dependency for %s:%s peer %s:%s failed %s:%s" % (obj.__class__.__name__, str(getattr(obj,"pk","no_pk")), peer_object.__class__.__name__, str(getattr(peer_object,"pk","no_pk")), failed.__class__.__name__, str(getattr(failed,"pk","no_pk"))))
+
+
+ def sync_record(self, o):
+ try:
+ controller = o.get_controller()
+ controller_register = json.loads(o.node.site_deployment.controller.backend_register)
+
+ if (controller_register.get('disabled',False)):
+ raise InnocuousException('Controller %s is disabled'%sliver.node.site_deployment.controller.name)
+ except AttributeError:
+ pass
+
+ tenant_fields = self.map_sync_inputs(o)
+ if tenant_fields == SyncStep.SYNC_WITHOUT_RUNNING:
+ return
+ main_objs=self.observes
+ if (type(main_objs) is list):
+ main_objs=main_objs[0]
+
+ path = ''.join(main_objs.__name__).lower()
+ res = run_template(self.playbook,tenant_fields,path=path)
+
+ try:
+ self.map_sync_outputs(o,res)
+ except AttributeError:
+ pass
+
+ def delete_record(self, o):
+ try:
+ controller = o.get_controller()
+ controller_register = json.loads(o.node.site_deployment.controller.backend_register)
+
+ if (controller_register.get('disabled',False)):
+ raise InnocuousException('Controller %s is disabled'%sliver.node.site_deployment.controller.name)
+ except AttributeError:
+ pass
+
+ tenant_fields = self.map_delete_inputs(o)
+
+ main_objs=self.observes
+ if (type(main_objs) is list):
+ main_objs=main_objs[0]
+
+ path = ''.join(main_objs.__name__).lower()
+
+ tenant_fields['delete']=True
+ res = run_template(self.playbook,tenant_fields,path=path)
+ try:
+ self.map_delete_outputs(o,res)
+ except AttributeError:
+ pass
+
+ def call(self, failed=[], deletion=False):
+ #if ('Instance' in self.__class__.__name__):
+ # pdb.set_trace()
+
+ pending = self.fetch_pending(deletion)
+
+ for o in pending:
+ # another spot to clean up debug state
+ try:
+ reset_queries()
+ except:
+ # this shouldn't happen, but in case it does, catch it...
+ logger.log_exc("exception in reset_queries")
+
+ sync_failed = False
+ try:
+ backoff_disabled = Config().observer_backoff_disabled
+ except:
+ backoff_disabled = 0
+
+ try:
+ scratchpad = json.loads(o.backend_register)
+ if (scratchpad):
+ next_run = scratchpad['next_run']
+ if (not backoff_disabled and next_run>time.time()):
+ sync_failed = True
+ except:
+ logger.log_exc("Exception while loading scratchpad")
+ pass
+
+ if (not sync_failed):
+ try:
+ for f in failed:
+ self.check_dependencies(o,f) # Raises exception if failed
+ if (deletion):
+ self.delete_record(o)
+ o.delete(purge=True)
+ else:
+ self.sync_record(o)
+ o.enacted = datetime.now() # Is this the same timezone? XXX
+ scratchpad = {'next_run':0, 'exponent':0, 'last_success':time.time()}
+ o.backend_register = json.dumps(scratchpad)
+ o.backend_status = "1 - OK"
+ o.save(update_fields=['enacted','backend_status','backend_register'])
+ except (InnocuousException,Exception,DeferredException) as e:
+ logger.log_exc("sync step failed!")
+ try:
+ if (o.backend_status.startswith('2 - ')):
+ str_e = '%s // %r'%(o.backend_status[4:],e)
+ str_e = elim_dups(str_e)
+ else:
+ str_e = '%r'%e
+ except:
+ str_e = '%r'%e
+
+ try:
+ error = self.error_map.map(str_e)
+ except:
+ error = '%s'%str_e
+
+ if isinstance(e, InnocuousException) and not force_error:
+ o.backend_status = '1 - %s'%error
+ else:
+ o.backend_status = '2 - %s'%error
+
+ try:
+ scratchpad = json.loads(o.backend_register)
+ scratchpad['exponent']
+ except:
+ logger.log_exc("Exception while updating scratchpad")
+ scratchpad = {'next_run':0, 'exponent':0, 'last_success':time.time(),'failures':0}
+
+ # Second failure
+ if (scratchpad['exponent']):
+ if isinstance(e,DeferredException):
+ delay = scratchpad['exponent'] * 60 # 1 minute
+ else:
+ delay = scratchpad['exponent'] * 600 # 10 minutes
+ # cap delays at 8 hours
+ if (delay>8*60*60):
+ delay=8*60*60
+ scratchpad['next_run'] = time.time() + delay
+
+ try:
+ scratchpad['exponent']+=1
+ except:
+ scratchpad['exponent']=1
+
+ try:
+ scratchpad['failures']+=1
+ except KeyError:
+ scratchpad['failures']=1
+
+ scratchpad['last_failure']=time.time()
+
+ o.backend_register = json.dumps(scratchpad)
+
+ # TOFIX:
+ # DatabaseError: value too long for type character varying(140)
+ if (o.pk):
+ try:
+ o.backend_status = o.backend_status[:1024]
+ o.save(update_fields=['backend_status','backend_register','updated'])
+ except:
+ print "Could not update backend status field!"
+ pass
+ sync_failed = True
+
+
+ if (sync_failed):
+ failed.append(o)
+
+ return failed
+
+ def __call__(self, **args):
+ return self.call(**args)
diff --git a/xos/synchronizers/base/syncstep.py.bak b/xos/synchronizers/base/syncstep.py.bak
new file mode 100644
index 0000000..a1f242b
--- /dev/null
+++ b/xos/synchronizers/base/syncstep.py.bak
@@ -0,0 +1,203 @@
+import os
+import base64
+from datetime import datetime
+from xos.config import Config
+from util.logger import Logger, logging
+from observer.steps import *
+from django.db.models import F, Q
+from core.models import *
+import json
+import time
+import pdb
+import traceback
+
+logger = Logger(level=logging.INFO)
+
+def f7(seq):
+ seen = set()
+ seen_add = seen.add
+ return [ x for x in seq if not (x in seen or seen_add(x))]
+
+def elim_dups(backend_str):
+ strs = backend_str.split(' // ')
+ strs2 = f7(strs)
+ return ' // '.join(strs2)
+
+def deepgetattr(obj, attr):
+ return reduce(getattr, attr.split('.'), obj)
+
+
+class InnocuousException(Exception):
+ pass
+
+class FailedDependency(Exception):
+ pass
+
+class SyncStep(object):
+ """ An XOS Sync step.
+
+ Attributes:
+ psmodel Model name the step synchronizes
+ dependencies list of names of models that must be synchronized first if the current model depends on them
+ """
+ slow=False
+ def get_prop(self, prop):
+ try:
+ sync_config_dir = Config().sync_config_dir
+ except:
+ sync_config_dir = '/etc/xos/sync'
+ prop_config_path = '/'.join(sync_config_dir,self.name,prop)
+ return open(prop_config_path).read().rstrip()
+
+ def __init__(self, **args):
+ """Initialize a sync step
+ Keyword arguments:
+ name -- Name of the step
+ provides -- XOS models sync'd by this step
+ """
+ dependencies = []
+ self.driver = args.get('driver')
+ self.error_map = args.get('error_map')
+
+ try:
+ self.soft_deadline = int(self.get_prop('soft_deadline_seconds'))
+ except:
+ self.soft_deadline = 5 # 5 seconds
+
+ return
+
+ def fetch_pending(self, deletion=False):
+ # This is the most common implementation of fetch_pending
+ # Steps should override it if they have their own logic
+ # for figuring out what objects are outstanding.
+ main_obj = self.observes
+ if (not deletion):
+ objs = main_obj.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
+ else:
+ objs = main_obj.deleted_objects.all()
+
+ return objs
+ #return Sliver.objects.filter(ip=None)
+
+ def check_dependencies(self, obj, failed):
+ for dep in self.dependencies:
+ peer_name = dep[0].lower() + dep[1:] # django names are camelCased with the first letter lower
+
+ try:
+ peer_object = deepgetattr(obj, peer_name)
+ try:
+ peer_objects = peer_object.all()
+ except AttributeError:
+ peer_objects = [peer_object]
+ except:
+ peer_objects = []
+
+ if (hasattr(obj,'controller')):
+ try:
+ peer_objects = filter(lambda o:o.controller==obj.controller, peer_objects)
+ except AttributeError:
+ pass
+
+ if (failed in peer_objects):
+ if (obj.backend_status!=failed.backend_status):
+ obj.backend_status = failed.backend_status
+ obj.save(update_fields=['backend_status'])
+ raise FailedDependency("Failed dependency for %s:%s peer %s:%s failed %s:%s" % (obj.__class__.__name__, str(getattr(obj,"pk","no_pk")), peer_object.__class__.__name__, str(getattr(peer_object,"pk","no_pk")), failed.__class__.__name__, str(getattr(failed,"pk","no_pk"))))
+
+ def call(self, failed=[], deletion=False):
+ pending = self.fetch_pending(deletion)
+ for o in pending:
+ sync_failed = False
+ try:
+ backoff_disabled = Config().observer_backoff_disabled
+ except:
+ backoff_disabled = 0
+
+ try:
+ scratchpad = json.loads(o.backend_register)
+ if (scratchpad):
+ next_run = scratchpad['next_run']
+ if (not backoff_disabled and next_run>time.time()):
+ sync_failed = True
+ except:
+ logger.log_exc("Exception while loading scratchpad")
+ pass
+
+ if (not sync_failed):
+ try:
+ for f in failed:
+ self.check_dependencies(o,f) # Raises exception if failed
+ if (deletion):
+ self.delete_record(o)
+ o.delete(purge=True)
+ else:
+ self.sync_record(o)
+ o.enacted = datetime.now() # Is this the same timezone? XXX
+ scratchpad = {'next_run':0, 'exponent':0}
+ o.backend_register = json.dumps(scratchpad)
+ o.backend_status = "1 - OK"
+ o.save(update_fields=['enacted','backend_status','backend_register'])
+ except (InnocuousException,Exception) as e:
+ logger.log_exc("sync step failed!")
+ try:
+ if (o.backend_status.startswith('2 - ')):
+ str_e = '%s // %r'%(o.backend_status[4:],e)
+ str_e = elim_dups(str_e)
+ else:
+ str_e = '%r'%e
+ except:
+ str_e = '%r'%e
+
+ try:
+ error = self.error_map.map(str_e)
+ except:
+ error = '2 - %s'%str_e
+
+ if isinstance(e, InnocuousException) and not force_error:
+ o.backend_status = '1 - %s'%error
+ else:
+ o.backend_status = '3 - %s'%error
+
+ try:
+ scratchpad = json.loads(o.backend_register)
+ scratchpad['exponent']
+ except:
+ logger.log_exc("Exception while updating scratchpad")
+ scratchpad = {'next_run':0, 'exponent':0}
+
+ # Second failure
+ if (scratchpad['exponent']):
+ delay = scratchpad['exponent'] * 600 # 10 minutes
+ if (delay<1440):
+ delay = 1440
+ scratchpad['next_run'] = time.time() + delay
+
+ scratchpad['exponent']+=1
+
+ o.backend_register = json.dumps(scratchpad)
+
+ # TOFIX:
+ # DatabaseError: value too long for type character varying(140)
+ if (o.pk):
+ try:
+ o.backend_status = o.backend_status[:1024]
+ o.save(update_fields=['backend_status','backend_register','updated'])
+ except:
+ print "Could not update backend status field!"
+ pass
+ sync_failed = True
+
+
+ if (sync_failed):
+ failed.append(o)
+
+ return failed
+
+ def sync_record(self, o):
+ return
+
+ def delete_record(self, o):
+ return
+
+ def __call__(self, **args):
+ return self.call(**args)
diff --git a/xos/openstack_observer/templates/container.conf.j2 b/xos/synchronizers/base/templates/container.conf.j2
similarity index 100%
rename from xos/openstack_observer/templates/container.conf.j2
rename to xos/synchronizers/base/templates/container.conf.j2
diff --git a/xos/openstack_observer/templates/container.service.j2 b/xos/synchronizers/base/templates/container.service.j2
similarity index 100%
rename from xos/openstack_observer/templates/container.service.j2
rename to xos/synchronizers/base/templates/container.service.j2
diff --git a/xos/openstack_observer/templates/start-container.sh.j2 b/xos/synchronizers/base/templates/start-container.sh.j2
similarity index 100%
rename from xos/openstack_observer/templates/start-container.sh.j2
rename to xos/synchronizers/base/templates/start-container.sh.j2
diff --git a/xos/openstack_observer/templates/stop-container.sh.j2 b/xos/synchronizers/base/templates/stop-container.sh.j2
similarity index 100%
rename from xos/openstack_observer/templates/stop-container.sh.j2
rename to xos/synchronizers/base/templates/stop-container.sh.j2
diff --git a/xos/openstack_observer/toposort.py b/xos/synchronizers/base/toposort.py
similarity index 100%
rename from xos/openstack_observer/toposort.py
rename to xos/synchronizers/base/toposort.py
diff --git a/xos/synchronizers/base/xos-synchronizer.py b/xos/synchronizers/base/xos-synchronizer.py
new file mode 100644
index 0000000..3fffd33
--- /dev/null
+++ b/xos/synchronizers/base/xos-synchronizer.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python
+import os
+import argparse
+import sys
+
+sys.path.append('/opt/xos')
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+from synchronizers.base.backend import Backend
+from xos.config import Config, DEFAULT_CONFIG_FN
+from core.models import Instance
+from xos.logger import Logger, logging, logger
+from django.db import ProgrammingError
+import time
+
+try:
+ from django import setup as django_setup # django 1.7
+except:
+ django_setup = False
+
+config = Config()
+
+# after http://www.erlenstar.demon.co.uk/unix/faq_2.html
+def daemon():
+ """Daemonize the current process."""
+ if os.fork() != 0: os._exit(0)
+ os.setsid()
+ if os.fork() != 0: os._exit(0)
+ os.umask(0)
+ devnull = os.open(os.devnull, os.O_RDWR)
+ os.dup2(devnull, 0)
+ # xxx fixme - this is just to make sure that nothing gets stupidly lost - should use devnull
+ logdir=os.path.dirname(config.observer_logfile)
+ # when installed in standalone we might not have httpd installed
+ if not os.path.isdir(logdir): os.mkdir(logdir)
+ crashlog = os.open('%s'%config.observer_logfile, os.O_RDWR | os.O_APPEND | os.O_CREAT, 0644)
+ os.dup2(crashlog, 1)
+ os.dup2(crashlog, 2)
+
+ if hasattr(config, "observer_pidfile"):
+ pidfile = config.get("observer_pidfile")
+ else:
+ pidfile = "/var/run/xosobserver.pid"
+ try:
+ file(pidfile,"w").write(str(os.getpid()))
+ except:
+ print "failed to create pidfile %s" % pidfile
+
+def main():
+ # Generate command line parser
+ parser = argparse.ArgumentParser(usage='%(prog)s [options]')
+ parser.add_argument('-d', '--daemon', dest='daemon', action='store_true', default=False,
+ help='Run as daemon.')
+ # smbaker: util/config.py parses sys.argv[] directly to get config file name; include the option here to avoid
+ # throwing unrecognized argument exceptions
+ parser.add_argument('-C', '--config', dest='config_file', action='store', default=DEFAULT_CONFIG_FN,
+ help='Name of config file.')
+ args = parser.parse_args()
+
+ if args.daemon: daemon()
+
+ if django_setup: # 1.7
+ django_setup()
+
+ models_active = False
+ wait = False
+ while not models_active:
+ try:
+ _ = Instance.objects.first()
+ models_active = True
+ except ProgrammingError:
+ logger.info('Waiting for data model to come up before starting...')
+ wait = True
+
+ if (wait):
+ time.sleep(60) # Safety factor, seeing that we stumbled waiting for the data model to come up.
+ backend = Backend()
+ backend.run()
+
+if __name__ == '__main__':
+
+ main()
diff --git a/xos/ec2_observer/__init__.py b/xos/synchronizers/ec2/__init__.py
similarity index 100%
rename from xos/ec2_observer/__init__.py
rename to xos/synchronizers/ec2/__init__.py
diff --git a/xos/ec2_observer/aws_lib.py b/xos/synchronizers/ec2/aws_lib.py
similarity index 100%
rename from xos/ec2_observer/aws_lib.py
rename to xos/synchronizers/ec2/aws_lib.py
diff --git a/xos/ec2_observer/awslib.py b/xos/synchronizers/ec2/awslib.py
similarity index 100%
rename from xos/ec2_observer/awslib.py
rename to xos/synchronizers/ec2/awslib.py
diff --git a/xos/synchronizers/ec2/backend.py b/xos/synchronizers/ec2/backend.py
new file mode 100644
index 0000000..7288e61
--- /dev/null
+++ b/xos/synchronizers/ec2/backend.py
@@ -0,0 +1,22 @@
+import threading
+import time
+from ec2_observer.event_loop import XOSObserver
+from ec2_observer.event_manager import EventListener
+from xos.logger import Logger, logging
+
+logger = Logger(level=logging.INFO)
+
+class Backend:
+
+ def run(self):
+ # start the openstack observer
+ observer = XOSObserver()
+ observer_thread = threading.Thread(target=observer.run)
+ observer_thread.start()
+
+ # start event listene
+ event_manager = EventListener(wake_up=observer.wake_up)
+ event_manager_thread = threading.Thread(target=event_manager.run)
+ event_manager_thread.start()
+ logger.log_exc("Exception in child thread")
+
diff --git a/xos/ec2_observer/creds.py b/xos/synchronizers/ec2/creds.py
similarity index 100%
rename from xos/ec2_observer/creds.py
rename to xos/synchronizers/ec2/creds.py
diff --git a/xos/ec2_observer/deleter.py b/xos/synchronizers/ec2/deleter.py
similarity index 100%
copy from xos/ec2_observer/deleter.py
copy to xos/synchronizers/ec2/deleter.py
diff --git a/xos/ec2_observer/deleters/__init__.py b/xos/synchronizers/ec2/deleters/__init__.py
similarity index 100%
rename from xos/ec2_observer/deleters/__init__.py
rename to xos/synchronizers/ec2/deleters/__init__.py
diff --git a/xos/synchronizers/ec2/deleters/instance_deleter.py b/xos/synchronizers/ec2/deleters/instance_deleter.py
new file mode 100644
index 0000000..ba454e7
--- /dev/null
+++ b/xos/synchronizers/ec2/deleters/instance_deleter.py
@@ -0,0 +1,14 @@
+from core.models import Instance, SliceDeployments
+from synchronizers.base.deleter import Deleter
+
+class InstanceDeleter(Deleter):
+ model='Instance'
+
+ def call(self, pk):
+ instance = Instance.objects.get(pk=pk)
+ if instance.instance_id:
+ driver = self.driver.client_driver(caller=instance.creator,
+ tenant=instance.slice.name,
+ deployment=instance.deploymentNetwork.name)
+ driver.destroy_instance(instance.instance_id)
+ instance.delete()
diff --git a/xos/synchronizers/ec2/deleters/network_deleter.py b/xos/synchronizers/ec2/deleters/network_deleter.py
new file mode 100644
index 0000000..aa9ef59
--- /dev/null
+++ b/xos/synchronizers/ec2/deleters/network_deleter.py
@@ -0,0 +1,19 @@
+from core.models import Network, NetworkDeployments
+from synchronizers.base.deleter import Deleter
+from synchronizers.base.deleters.network_deployment_deleter import NetworkDeploymentDeleter
+from xos.logger import Logger, logging
+
+logger = Logger(level=logging.INFO)
+
+class NetworkDeleter(Deleter):
+ model='Network'
+
+ def call(self, pk):
+ network = Network.objects.get(pk=pk)
+ network_deployment_deleter = NetworkDeploymentDeleter()
+ for network_deployment in NetworkDeployments.objects.filter(network=network):
+ try:
+ network_deployment_deleter(network_deployment.id)
+ except:
+ logger.log_exc("Failed to delte network deployment %s" % network_deployment)
+ network.delete()
diff --git a/xos/synchronizers/ec2/deleters/network_deployment_deleter.py b/xos/synchronizers/ec2/deleters/network_deployment_deleter.py
new file mode 100644
index 0000000..f8aaa29
--- /dev/null
+++ b/xos/synchronizers/ec2/deleters/network_deployment_deleter.py
@@ -0,0 +1,21 @@
+from core.models import Network, NetworkDeployments
+from synchronizers.base.deleter import Deleter
+from openstack.driver import OpenStackDriver
+
+class NetworkDeploymentDeleter(Deleter):
+ model='NetworkDeployment'
+
+ def call(self, pk):
+ network_deployment = NetworkDeployments.objects.get(pk=pk)
+ driver = OpenStackDriver().client_driver(caller=network_deployment.network.owner.creator,
+ tenant=network_deployment.network.owner.name,
+ deployment=network_deployment.deployment.name)
+ if (network_deployment.router_id) and (network_deployment.subnet_id):
+ driver.delete_router_interface(network_deployment.router_id, network_deployment.subnet_id)
+ if network_deployment.subnet_id:
+ driver.delete_subnet(network_deployment.subnet_id)
+ if network_deployment.router_id:
+ driver.delete_router(network_deployment.router_id)
+ if network_deployment.net_id:
+ driver.delete_network(network_deployment.net_id)
+ network_deployment.delete()
diff --git a/xos/synchronizers/ec2/deleters/network_instance_deleter.py b/xos/synchronizers/ec2/deleters/network_instance_deleter.py
new file mode 100644
index 0000000..21fe87f
--- /dev/null
+++ b/xos/synchronizers/ec2/deleters/network_instance_deleter.py
@@ -0,0 +1,13 @@
+from core.models import NetworkInstance
+from synchronizers.base.deleter import Deleter
+
+class NetworkInstanceDeleter(Deleter):
+ model='NetworkInstance'
+
+ def call(self, pk):
+ network_instance = NetworkInstances.objects.get(pk=pk)
+ # handle openstack delete
+
+ network_instance.delete()
+
+
diff --git a/xos/synchronizers/ec2/deleters/site_deleter.py b/xos/synchronizers/ec2/deleters/site_deleter.py
new file mode 100644
index 0000000..832baf9
--- /dev/null
+++ b/xos/synchronizers/ec2/deleters/site_deleter.py
@@ -0,0 +1,14 @@
+from core.models import Site, SiteDeployment
+from synchronizers.base.deleter import Deleter
+from synchronizers.base.deleters.site_deployment_deleter import SiteDeploymentDeleter
+
+class SiteDeleter(Deleter):
+ model='Site'
+
+ def call(self, pk):
+ site = Site.objects.get(pk=pk)
+ site_deployments = SiteDeployment.objects.filter(site=site)
+ site_deployment_deleter = SiteDeploymentDeleter()
+ for site_deployment in site_deployments:
+ site_deployment_deleter(site_deployment.id)
+ site.delete()
diff --git a/xos/synchronizers/ec2/deleters/site_deployment_deleter.py b/xos/synchronizers/ec2/deleters/site_deployment_deleter.py
new file mode 100644
index 0000000..794b438
--- /dev/null
+++ b/xos/synchronizers/ec2/deleters/site_deployment_deleter.py
@@ -0,0 +1,12 @@
+from core.models import Site, SiteDeployment
+from synchronizers.base.deleter import Deleter
+
+class SiteDeploymentDeleter(Deleter):
+ model='SiteDeployment'
+
+ def call(self, pk):
+ site_deployment = SiteDeployment.objects.get(pk=pk)
+ if site_deployment.tenant_id:
+ driver = self.driver.admin_driver(deployment=site_deployment.deployment.name)
+ driver.delete_tenant(site_deployment.tenant_id)
+ site_deployment.delete()
diff --git a/xos/synchronizers/ec2/deleters/slice_deleter.py b/xos/synchronizers/ec2/deleters/slice_deleter.py
new file mode 100644
index 0000000..49bf692
--- /dev/null
+++ b/xos/synchronizers/ec2/deleters/slice_deleter.py
@@ -0,0 +1,19 @@
+from core.models import Slice, SliceDeployments, User
+from synchronizers.base.deleter import Deleter
+from synchronizers.base.deleters.slice_deployment_deleter import SliceDeploymentsDeleter
+from xos.logger import Logger, logging
+
+logger = Logger(level=logging.INFO)
+
+class SliceDeleter(Deleter):
+ model='Slice'
+
+ def call(self, pk):
+ slice = Slice.objects.get(pk=pk)
+ slice_deployment_deleter = SliceDeploymentsDeleter()
+ for slice_deployment in SliceDeployments.objects.filter(slice=slice):
+ try:
+ slice_deployment_deleter(slice_deployment.id)
+ except:
+ logger.log_exc("Failed to delete slice_deployment %s" % slice_deployment)
+ slice.delete()
diff --git a/xos/synchronizers/ec2/deleters/slice_deployment_deleter.py b/xos/synchronizers/ec2/deleters/slice_deployment_deleter.py
new file mode 100644
index 0000000..39c557a
--- /dev/null
+++ b/xos/synchronizers/ec2/deleters/slice_deployment_deleter.py
@@ -0,0 +1,34 @@
+from core.models import Slice, SliceDeployments, User
+from synchronizers.base.deleter import Deleter
+from openstack.driver import OpenStackDriver
+
+class SliceDeploymentsDeleter(Deleter):
+ model='SliceDeployments'
+
+ def call(self, pk):
+ slice_deployment = SliceDeployments.objects.get(pk=pk)
+ user = User.objects.get(id=slice_deployment.slice.creator.id)
+ driver = OpenStackDriver().admin_driver(deployment=slice_deployment.deployment.name)
+ client_driver = driver.client_driver(caller=user,
+ tenant=slice_deployment.slice.name,
+ deployment=slice_deployment.deployment.name)
+
+ if slice_deployment.router_id and slice_deployment.subnet_id:
+ client_driver.delete_router_interface(slice_deployment.router_id, slice_deployment.subnet_id)
+ if slice_deployment.subnet_id:
+ client_driver.delete_subnet(slice_deployment.subnet_id)
+ if slice_deployment.router_id:
+ client_driver.delete_router(slice_deployment.router_id)
+ if slice_deployment.network_id:
+ client_driver.delete_network(slice_deployment.network_id)
+ if slice_deployment.tenant_id:
+ driver.delete_tenant(slice_deployment.tenant_id)
+ # delete external route
+ #subnet = None
+ #subnets = client_driver.shell.quantum.list_subnets()['subnets']
+ #for snet in subnets:
+ # if snet['id'] == slice_deployment.subnet_id:
+ # subnet = snet
+ #if subnet:
+ # driver.delete_external_route(subnet)
+ slice_deployment.delete()
diff --git a/xos/synchronizers/ec2/deleters/user_deleter.py b/xos/synchronizers/ec2/deleters/user_deleter.py
new file mode 100644
index 0000000..12c8224
--- /dev/null
+++ b/xos/synchronizers/ec2/deleters/user_deleter.py
@@ -0,0 +1,13 @@
+from core.models import User, UserDeployments
+from synchronizers.base.deleter import Deleter
+from synchronizers.base.deleters.user_deployment_deleter import UserDeploymentsDeleter
+
+class UserDeleter(Deleter):
+ model='User'
+
+ def call(self, pk):
+ user = User.objects.get(pk=pk)
+ user_deployment_deleter = UserDeploymentsDeleter()
+ for user_deployment in UserDeployments.objects.filter(user=user):
+ user_deployment_deleter(user_deployment.id)
+ user.delete()
diff --git a/xos/synchronizers/ec2/deleters/user_deployment_deleter.py b/xos/synchronizers/ec2/deleters/user_deployment_deleter.py
new file mode 100644
index 0000000..3b6113b
--- /dev/null
+++ b/xos/synchronizers/ec2/deleters/user_deployment_deleter.py
@@ -0,0 +1,12 @@
+from core.models import User, UserDeployments
+from synchronizers.base.deleter import Deleter
+
+class UserDeploymentsDeleter(Deleter):
+ model='UserDeployments'
+
+ def call(self, pk):
+ user_deployment = UserDeployments.objects.get(pk=pk)
+ if user_deployment.user.kuser_id:
+ driver = self.driver.admin_driver(deployment=user_deployment.deployment.name)
+ driver.delete_user(user_deployment.user.kuser_id)
+ user_deployment.delete()
diff --git a/xos/ec2_observer/dmdot b/xos/synchronizers/ec2/dmdot
similarity index 100%
rename from xos/ec2_observer/dmdot
rename to xos/synchronizers/ec2/dmdot
diff --git a/xos/synchronizers/ec2/ec2_backend.py b/xos/synchronizers/ec2/ec2_backend.py
new file mode 100644
index 0000000..7edf63c
--- /dev/null
+++ b/xos/synchronizers/ec2/ec2_backend.py
@@ -0,0 +1,24 @@
+import threading
+import time
+from ec2_observer.event_loop import XOSObserver
+from ec2_observer.event_manager import EventListener
+from xos.logger import Logger, logging
+
+logger = Logger(level=logging.INFO)
+
+class Backend:
+
+ def run(self):
+ try:
+ # start the openstack observer
+ observer = XOSObserver()
+ observer_thread = threading.Thread(target=observer.run)
+ observer_thread.start()
+
+ # start event listene
+ event_manager = EventListener(wake_up=observer.wake_up)
+ event_manager_thread = threading.Thread(target=event_manager.run)
+ event_manager_thread.start()
+ except:
+ logger.log_exc("Exception in child thread")
+
diff --git a/xos/synchronizers/ec2/error_mapper.py b/xos/synchronizers/ec2/error_mapper.py
new file mode 100644
index 0000000..9eb878d
--- /dev/null
+++ b/xos/synchronizers/ec2/error_mapper.py
@@ -0,0 +1,25 @@
+from xos.config import Config
+from xos.logger import Logger, logging, logger
+
+class ErrorMapper:
+ def __init__(self, error_map_file):
+ self.error_map = {}
+ try:
+ error_map_lines = open(error_map_file).read().splitlines()
+ for l in error_map_lines:
+ if (not l.startswith('#')):
+ splits = l.split('->')
+ k,v = map(lambda i:i.rstrip(),splits)
+ self.error_map[k]=v
+ except:
+ logging.info('Could not read error map')
+
+
+ def map(self, error):
+ return self.error_map[error]
+
+
+
+
+
+
diff --git a/xos/synchronizers/ec2/event_loop.py b/xos/synchronizers/ec2/event_loop.py
new file mode 100644
index 0000000..cfeb212
--- /dev/null
+++ b/xos/synchronizers/ec2/event_loop.py
@@ -0,0 +1,393 @@
+import os
+import imp
+import inspect
+import time
+import traceback
+import commands
+import threading
+import json
+import pdb
+
+from datetime import datetime
+from collections import defaultdict
+from core.models import *
+from django.db.models import F, Q
+#from openstack.manager import OpenStackManager
+from openstack.driver import OpenStackDriver
+from xos.logger import Logger, logging, logger
+#from timeout import timeout
+from xos.config import Config, XOS_DIR
+from synchronizers.base.steps import *
+from syncstep import SyncStep
+from toposort import toposort
+from synchronizers.base.error_mapper import *
+
+debug_mode = False
+
+logger = Logger(level=logging.INFO)
+
+class StepNotReady(Exception):
+ pass
+
+class NoOpDriver:
+ def __init__(self):
+ self.enabled = True
+ self.dependency_graph = None
+
+STEP_STATUS_WORKING=1
+STEP_STATUS_OK=2
+STEP_STATUS_KO=3
+
+def invert_graph(g):
+ ig = {}
+ for k,v in g.items():
+ for v0 in v:
+ try:
+ ig[v0].append(k)
+ except:
+ ig=[k]
+ return ig
+
+class XOSObserver:
+ #sync_steps = [SyncNetworks,SyncNetworkInstances,SyncSites,SyncSitePrivilege,SyncSlices,SyncSliceMemberships,SyncInstances,SyncInstanceIps,SyncExternalRoutes,SyncUsers,SyncRoles,SyncNodes,SyncImages,GarbageCollector]
+ sync_steps = []
+
+
+ def __init__(self):
+ # The Condition object that gets signalled by Feefie events
+ self.step_lookup = {}
+ self.load_sync_step_modules()
+ self.load_sync_steps()
+ self.event_cond = threading.Condition()
+
+ self.driver_kind = getattr(Config(), "observer_driver", "openstack")
+ if self.driver_kind=="openstack":
+ self.driver = OpenStackDriver()
+ else:
+ self.driver = NoOpDriver()
+
+ def wait_for_event(self, timeout):
+ self.event_cond.acquire()
+ self.event_cond.wait(timeout)
+ self.event_cond.release()
+
+ def wake_up(self):
+ logger.info('Wake up routine called. Event cond %r'%self.event_cond)
+ self.event_cond.acquire()
+ self.event_cond.notify()
+ self.event_cond.release()
+
+ def load_sync_step_modules(self, step_dir=None):
+ if step_dir is None:
+ if hasattr(Config(), "observer_steps_dir"):
+ step_dir = Config().observer_steps_dir
+ else:
+ step_dir = XOS_DIR + "/observer/steps"
+
+ for fn in os.listdir(step_dir):
+ pathname = os.path.join(step_dir,fn)
+ if os.path.isfile(pathname) and fn.endswith(".py") and (fn!="__init__.py"):
+ module = imp.load_source(fn[:-3],pathname)
+ for classname in dir(module):
+ c = getattr(module, classname, None)
+
+ # make sure 'c' is a descendent of SyncStep and has a
+ # provides field (this eliminates the abstract base classes
+ # since they don't have a provides)
+
+ if inspect.isclass(c) and issubclass(c, SyncStep) and hasattr(c,"provides") and (c not in self.sync_steps):
+ self.sync_steps.append(c)
+ logger.info('loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps]))
+ # print 'loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps])
+
+ def load_sync_steps(self):
+ dep_path = Config().observer_dependency_graph
+ logger.info('Loading model dependency graph from %s' % dep_path)
+ try:
+ # This contains dependencies between records, not sync steps
+ self.model_dependency_graph = json.loads(open(dep_path).read())
+ except Exception,e:
+ raise e
+
+ try:
+ backend_path = Config().observer_pl_dependency_graph
+ logger.info('Loading backend dependency graph from %s' % backend_path)
+ # This contains dependencies between backend records
+ self.backend_dependency_graph = json.loads(open(backend_path).read())
+ except Exception,e:
+ logger.info('Backend dependency graph not loaded')
+ # We can work without a backend graph
+ self.backend_dependency_graph = {}
+
+ provides_dict = {}
+ for s in self.sync_steps:
+ self.step_lookup[s.__name__] = s
+ for m in s.provides:
+ try:
+ provides_dict[m.__name__].append(s.__name__)
+ except KeyError:
+ provides_dict[m.__name__]=[s.__name__]
+
+ step_graph = {}
+ for k,v in self.model_dependency_graph.iteritems():
+ try:
+ for source in provides_dict[k]:
+ for m in v:
+ try:
+ for dest in provides_dict[m]:
+ # no deps, pass
+ try:
+ if (dest not in step_graph[source]):
+ step_graph[source].append(dest)
+ except:
+ step_graph[source]=[dest]
+ except KeyError:
+ pass
+
+ except KeyError:
+ pass
+ # no dependencies, pass
+
+ #import pdb
+ #pdb.set_trace()
+ if (self.backend_dependency_graph):
+ backend_dict = {}
+ for s in self.sync_steps:
+ for m in s.serves:
+ backend_dict[m]=s.__name__
+
+ for k,v in backend_dependency_graph.iteritems():
+ try:
+ source = backend_dict[k]
+ for m in v:
+ try:
+ dest = backend_dict[m]
+ except KeyError:
+ # no deps, pass
+ pass
+ step_graph[source]=dest
+
+ except KeyError:
+ pass
+ # no dependencies, pass
+
+ self.dependency_graph = step_graph
+ self.deletion_dependency_graph = invert_graph(step_graph)
+
+ self.ordered_steps = toposort(self.dependency_graph, map(lambda s:s.__name__,self.sync_steps))
+ print "Order of steps=",self.ordered_steps
+ self.load_run_times()
+
+
+ def check_duration(self, step, duration):
+ try:
+ if (duration > step.deadline):
+ logger.info('Sync step %s missed deadline, took %.2f seconds'%(step.name,duration))
+ except AttributeError:
+ # S doesn't have a deadline
+ pass
+
+ def update_run_time(self, step, deletion):
+ if (not deletion):
+ self.last_run_times[step.__name__]=time.time()
+ else:
+ self.last_deletion_run_times[step.__name__]=time.time()
+
+
+ def check_schedule(self, step, deletion):
+ last_run_times = self.last_run_times if not deletion else self.last_deletion_run_times
+
+ time_since_last_run = time.time() - last_run_times.get(step.__name__, 0)
+ try:
+ if (time_since_last_run < step.requested_interval):
+ raise StepNotReady
+ except AttributeError:
+ logger.info('Step %s does not have requested_interval set'%step.__name__)
+ raise StepNotReady
+
+ def load_run_times(self):
+ try:
+ jrun_times = open('/tmp/observer_run_times').read()
+ self.last_run_times = json.loads(jrun_times)
+ except:
+ self.last_run_times={}
+ for e in self.ordered_steps:
+ self.last_run_times[e]=0
+ try:
+ jrun_times = open('/tmp/observer_deletion_run_times').read()
+ self.last_deletion_run_times = json.loads(jrun_times)
+ except:
+ self.last_deletion_run_times={}
+ for e in self.ordered_steps:
+ self.last_deletion_run_times[e]=0
+
+
+ def save_run_times(self):
+ run_times = json.dumps(self.last_run_times)
+ open('/tmp/observer_run_times','w').write(run_times)
+
+ deletion_run_times = json.dumps(self.last_deletion_run_times)
+ open('/tmp/observer_deletion_run_times','w').write(deletion_run_times)
+
+ def check_class_dependency(self, step, failed_steps):
+ step.dependenices = []
+ for obj in step.provides:
+ step.dependenices.extend(self.model_dependency_graph.get(obj.__name__, []))
+ for failed_step in failed_steps:
+ if (failed_step in step.dependencies):
+ raise StepNotReady
+
+ def sync(self, S, deletion):
+ step = self.step_lookup[S]
+ start_time=time.time()
+
+ dependency_graph = self.dependency_graph if not deletion else self.deletion_dependency_graph
+
+ # Wait for step dependencies to be met
+ try:
+ deps = self.dependency_graph[S]
+ has_deps = True
+ except KeyError:
+ has_deps = False
+
+ if (has_deps):
+ for d in deps:
+ cond = self.step_conditions[d]
+ cond.acquire()
+ if (self.step_status[d] is STEP_STATUS_WORKING):
+ cond.wait()
+ cond.release()
+ go = self.step_status[d] == STEP_STATUS_OK
+ else:
+ go = True
+
+ if (not go):
+ self.failed_steps.append(sync_step)
+ my_status = STEP_STATUS_KO
+ else:
+ sync_step = step(driver=self.driver,error_map=self.error_mapper)
+ sync_step.__name__ = step.__name__
+ sync_step.dependencies = []
+ try:
+ mlist = sync_step.provides
+
+ for m in mlist:
+ sync_step.dependencies.extend(self.model_dependency_graph[m.__name__])
+ except KeyError:
+ pass
+ sync_step.debug_mode = debug_mode
+
+ should_run = False
+ try:
+ # Various checks that decide whether
+ # this step runs or not
+ self.check_class_dependency(sync_step, self.failed_steps) # dont run Slices if Sites failed
+ self.check_schedule(sync_step, deletion) # dont run sync_network_routes if time since last run < 1 hour
+ should_run = True
+ except StepNotReady:
+ logging.info('Step not ready: %s'%sync_step.__name__)
+ self.failed_steps.append(sync_step)
+ my_status = STEP_STATUS_KO
+ except Exception,e:
+ logging.error('%r',e)
+ logger.log_exc("sync step failed: %r. Deletion: %r"%(sync_step,deletion))
+ self.failed_steps.append(sync_step)
+ my_status = STEP_STATUS_KO
+
+ if (should_run):
+ try:
+ duration=time.time() - start_time
+
+ logger.info('Executing step %s' % sync_step.__name__)
+
+ failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion)
+
+ self.check_duration(sync_step, duration)
+
+ if failed_objects:
+ self.failed_step_objects.update(failed_objects)
+
+ my_status = STEP_STATUS_OK
+ self.update_run_time(sync_step,deletion)
+ except Exception,e:
+ logging.error('Model step failed. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!',e)
+ logger.log_exc(e)
+ self.failed_steps.append(S)
+ my_status = STEP_STATUS_KO
+ else:
+ my_status = STEP_STATUS_OK
+
+ try:
+ my_cond = self.step_conditions[S]
+ my_cond.acquire()
+ self.step_status[S]=my_status
+ my_cond.notify_all()
+ my_cond.release()
+ except KeyError,e:
+ logging.info('Step %r is a leaf')
+ pass
+
+ def run(self):
+ if not self.driver.enabled:
+ return
+
+ if (self.driver_kind=="openstack") and (not self.driver.has_openstack):
+ return
+
+ while True:
+ try:
+ error_map_file = getattr(Config(), "error_map_path", XOS_DIR + "/error_map.txt")
+ self.error_mapper = ErrorMapper(error_map_file)
+
+ # Set of whole steps that failed
+ self.failed_steps = []
+
+ # Set of individual objects within steps that failed
+ self.failed_step_objects = set()
+
+ # Set up conditions and step status
+ # This is needed for steps to run in parallel
+ # while obeying dependencies.
+
+ providers = set()
+ for v in self.dependency_graph.values():
+ if (v):
+ providers.update(v)
+
+ self.step_conditions = {}
+ self.step_status = {}
+ for p in list(providers):
+ self.step_conditions[p] = threading.Condition()
+ self.step_status[p] = STEP_STATUS_WORKING
+
+
+ logger.info('Waiting for event')
+ tBeforeWait = time.time()
+ self.wait_for_event(timeout=30)
+ logger.info('Observer woke up')
+
+ # Two passes. One for sync, the other for deletion.
+ for deletion in [False,True]:
+ threads = []
+ logger.info('Deletion=%r...'%deletion)
+ schedule = self.ordered_steps if not deletion else reversed(self.ordered_steps)
+
+ for S in schedule:
+ thread = threading.Thread(target=self.sync, args=(S, deletion))
+
+ logger.info('Deletion=%r...'%deletion)
+ threads.append(thread)
+
+ # Start threads
+ for t in threads:
+ t.start()
+
+ # Wait for all threads to finish before continuing with the run loop
+ for t in threads:
+ t.join()
+
+ self.save_run_times()
+ except Exception, e:
+ logging.error('Core error. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!',e)
+ logger.log_exc("Exception in observer run loop")
+ traceback.print_exc()
diff --git a/xos/ec2_observer/event_manager.py b/xos/synchronizers/ec2/event_manager.py
similarity index 100%
rename from xos/ec2_observer/event_manager.py
rename to xos/synchronizers/ec2/event_manager.py
diff --git a/xos/ec2_observer/steps/__init__.py b/xos/synchronizers/ec2/steps/__init__.py
similarity index 100%
rename from xos/ec2_observer/steps/__init__.py
rename to xos/synchronizers/ec2/steps/__init__.py
diff --git a/xos/ec2_observer/steps/sync_deployments.py b/xos/synchronizers/ec2/steps/sync_deployments.py
similarity index 100%
rename from xos/ec2_observer/steps/sync_deployments.py
rename to xos/synchronizers/ec2/steps/sync_deployments.py
diff --git a/xos/ec2_observer/steps/sync_images.py b/xos/synchronizers/ec2/steps/sync_images.py
similarity index 100%
rename from xos/ec2_observer/steps/sync_images.py
rename to xos/synchronizers/ec2/steps/sync_images.py
diff --git a/xos/synchronizers/ec2/steps/sync_instances.py b/xos/synchronizers/ec2/steps/sync_instances.py
new file mode 100644
index 0000000..fc11e05
--- /dev/null
+++ b/xos/synchronizers/ec2/steps/sync_instances.py
@@ -0,0 +1,117 @@
+import os
+import json
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from ec2_observer.syncstep import SyncStep
+from core.models.instance import Instance
+from core.models.slice import SlicePrivilege, SliceDeployments
+from core.models.network import Network, NetworkSlice, NetworkDeployments
+from xos.logger import Logger, logging
+from ec2_observer.awslib import *
+from core.models.site import *
+from core.models.slice import *
+from ec2_observer.creds import *
+import pdb
+
+logger = Logger(level=logging.INFO)
+
+class SyncInstances(SyncStep):
+ provides=[Instance]
+ requested_interval=0
+
+ def fetch_pending(self, deletion):
+ if deletion:
+ object_source = Instance.deleted_objects
+ else:
+ object_source = Instance.objects
+
+ all_instances = object_source.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
+ my_instances = []
+
+ for instance in all_instances:
+ sd = SliceDeployments.objects.filter(Q(slice=instance.slice))
+ if (sd):
+ if (sd.deployment.name=='Amazon EC2'):
+ my_instances.append(instance)
+ if (instance.node.deployment.name=='Amazon EC2'):
+ my_instances.append(instance)
+ return my_instances
+
+ def delete_record(self, instance):
+ user = instance.creator
+ e = get_creds(user=user, site=user.site)
+ result = aws_run('ec2 terminate-instances --instance-ids=%s'%instance.instance_id, env=e)
+
+ def sync_record(self, instance):
+ logger.info("sync'ing instance:%s deployment:%s " % (instance, instance.node.deployment))
+
+ if not instance.instance_id:
+ # public keys
+ slice_memberships = SlicePrivilege.objects.filter(slice=instance.slice)
+ pubkeys = [sm.user.public_key for sm in slice_memberships if sm.user.public_key]
+
+ if instance.creator.public_key:
+ pubkeys.append(instance.creator.public_key)
+
+ if instance.slice.creator.public_key:
+ pubkeys.append(instance.slice.creator.public_key)
+
+ # netowrks
+ # include all networks available to the slice and/or associated network templates
+ #nics = []
+ #networks = [ns.network for ns in NetworkSlice.objects.filter(slice=instance.slice)]
+ #network_deployments = NetworkDeployments.objects.filter(network__in=networks,
+ #deployment=instance.node.deployment)
+ # Gather private networks first. This includes networks with a template that has
+ # visibility = private and translation = none
+ #for network_deployment in network_deployments:
+ # if network_deployment.network.template.visibility == 'private' and \
+ # network_deployment.network.template.translation == 'none':
+ # nics.append({'net-id': network_deployment.net_id})
+
+ # now include network template
+ #network_templates = [network.template.sharedNetworkName for network in networks \
+ # if network.template.sharedNetworkName]
+ #for net in driver.shell.quantum.list_networks()['networks']:
+ # if net['name'] in network_templates:
+ # nics.append({'net-id': net['id']})
+ # look up image id
+
+ instance_type = instance.node.name.rsplit('.',1)[0]
+
+ # Bail out of we don't have a key
+ key_name = instance.creator.email.lower().replace('@', 'AT').replace('.', '')
+ u = instance.creator
+ s = u.site
+ e = get_creds(user=u, site=s)
+ key_sig = aws_run('ec2 describe-key-pairs', env=e)
+ ec2_keys = key_sig['KeyPairs']
+ key_found = False
+ for key in ec2_keys:
+ if (key['KeyName']==key_name):
+ key_found = True
+ break
+
+ if (not key_found):
+ # set backend_status
+ raise Exception('Will not sync instance without key')
+
+ image_id = instance.image.path
+ instance_sig = aws_run('ec2 run-instances --image-id %s --instance-type %s --count 1 --key-name %s --placement AvailabilityZone=%s'%(image_id,instance_type,key_name,instance.node.site.name), env=e)
+ instance.instance_id = instance_sig['Instances'][0]['InstanceId']
+ instance.save()
+ state = instance_sig['Instances'][0]['State']['Code']
+ if (state==16):
+ instance.ip = instance_sig['Instances'][0]['PublicIpAddress']
+ instance.save()
+ else:
+ # This status message should go into backend_status
+ raise Exception('Waiting for instance to start')
+ else:
+ ret = aws_run('ec2 describe-instances --instance-ids %s'%instance.instance_id, env=e)
+ state = ret['Reservations'][0]['Instances'][0]['State']['Code']
+ if (state==16):
+ instance.ip = ret['Reservations'][0]['Instances'][0]['PublicIpAddress']
+ instance.save()
+
diff --git a/xos/ec2_observer/steps/sync_site_deployments.py b/xos/synchronizers/ec2/steps/sync_site_deployments.py
similarity index 100%
rename from xos/ec2_observer/steps/sync_site_deployments.py
rename to xos/synchronizers/ec2/steps/sync_site_deployments.py
diff --git a/xos/ec2_observer/steps/sync_sites.py b/xos/synchronizers/ec2/steps/sync_sites.py
similarity index 100%
rename from xos/ec2_observer/steps/sync_sites.py
rename to xos/synchronizers/ec2/steps/sync_sites.py
diff --git a/xos/ec2_observer/steps/sync_users.py b/xos/synchronizers/ec2/steps/sync_users.py
similarity index 100%
rename from xos/ec2_observer/steps/sync_users.py
rename to xos/synchronizers/ec2/steps/sync_users.py
diff --git a/xos/synchronizers/ec2/syncstep.py b/xos/synchronizers/ec2/syncstep.py
new file mode 100644
index 0000000..3cba48b
--- /dev/null
+++ b/xos/synchronizers/ec2/syncstep.py
@@ -0,0 +1,101 @@
+import os
+import base64
+from datetime import datetime
+
+from django.db.models import F, Q
+
+from xos.config import Config
+from xos.logger import Logger, logging
+from synchronizers.base.steps import *
+
+logger = Logger(level=logging.INFO)
+
+class FailedDependency(Exception):
+ pass
+
+class SyncStep:
+ """ A XOS Sync step.
+
+ Attributes:
+ psmodel Model name the step synchronizes
+ dependencies list of names of models that must be synchronized first if the current model depends on them
+ """
+ slow=False
+ def get_prop(self, prop):
+ try:
+ sync_config_dir = Config().sync_config_dir
+ except:
+ sync_config_dir = '/etc/xos/sync' # XXX TODO: update path
+ prop_config_path = '/'.join(sync_config_dir,self.name,prop)
+ return open(prop_config_path).read().rstrip()
+
+ def __init__(self, **args):
+ """Initialize a sync step
+ Keyword arguments:
+ name -- Name of the step
+ provides -- XOS models sync'd by this step
+ """
+ dependencies = []
+ self.driver = args.get('driver')
+ self.error_map = args.get('error_map')
+
+ try:
+ self.soft_deadline = int(self.get_prop('soft_deadline_seconds'))
+ except:
+ self.soft_deadline = 5 # 5 seconds
+
+ return
+
+ def fetch_pending(self, deletion=False):
+ # This is the most common implementation of fetch_pending
+ # Steps should override it if they have their own logic
+ # for figuring out what objects are outstanding.
+ main_obj = self.provides[0]
+ if (not deletion):
+ objs = main_obj.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
+ else:
+ objs = main_obj.deleted_objects.all()
+
+ return objs
+ #return Instance.objects.filter(ip=None)
+
+ def check_dependencies(self, obj, failed):
+ for dep in self.dependencies:
+ peer_name = dep[0].lower() + dep[1:] # django names are camelCased with the first letter lower
+ peer_object = getattr(obj, peer_name)
+
+ # peer_object can be None, and if so there
+ # is no object-level dependency
+ if (peer_object and peer_object.pk==failed.pk):
+ raise FailedDependency
+
+ def call(self, failed=[], deletion=False):
+ pending = self.fetch_pending(deletion)
+ for o in pending:
+ try:
+ for f in failed:
+ self.check_dependencies(o,f) # Raises exception if failed
+ if (deletion):
+ self.delete_record(o)
+ o.delete(purge=True)
+ else:
+ self.sync_record(o)
+ o.enacted = datetime.now() # Is this the same timezone? XXX
+ o.backend_status = "OK"
+ o.save(update_fields=['enacted'])
+ except Exception,e:
+ try:
+ o.backend_status = self.error_map.map(str(e))
+ except:
+ o.backend_status = str(e)
+
+ if (o.pk):
+ o.save(update_fields=['backend_status'])
+
+ logger.log_exc("sync step failed!")
+ failed.append(o)
+
+ return failed
+
+ def __call__(self, **args):
+ return self.call(**args)
diff --git a/xos/ec2_observer/toposort.py b/xos/synchronizers/ec2/toposort.py
similarity index 100%
rename from xos/ec2_observer/toposort.py
rename to xos/synchronizers/ec2/toposort.py
diff --git a/xos/ec2_observer/xos.deps b/xos/synchronizers/ec2/xos.deps
similarity index 100%
rename from xos/ec2_observer/xos.deps
rename to xos/synchronizers/ec2/xos.deps
diff --git a/xos/synchronizers/helloworld/helloworld-synchronizer.py b/xos/synchronizers/helloworld/helloworld-synchronizer.py
new file mode 100755
index 0000000..84bec4f
--- /dev/null
+++ b/xos/synchronizers/helloworld/helloworld-synchronizer.py
@@ -0,0 +1,11 @@
+#!/usr/bin/env python
+
+# This imports and runs ../../xos-observer.py
+
+import importlib
+import os
+import sys
+observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../../synchronizers/base")
+sys.path.append(observer_path)
+mod = importlib.import_module("xos-synchronizer")
+mod.main()
diff --git a/xos/synchronizers/helloworld/helloworld_config b/xos/synchronizers/helloworld/helloworld_config
new file mode 100644
index 0000000..1f67242
--- /dev/null
+++ b/xos/synchronizers/helloworld/helloworld_config
@@ -0,0 +1,47 @@
+[plc]
+name=plc
+deployment=plc
+
+[db]
+name=xos
+user=postgres
+password=password
+host=localhost
+port=5432
+
+[api]
+host=localhost
+port=8000
+ssl_key=None
+ssl_cert=None
+ca_ssl_cert=None
+ratelimit_enabled=0
+omf_enabled=0
+mail_support_address=support@localhost
+nova_enabled=True
+logfile=/var/log/xos.log
+
+[nova]
+admin_user=admin@domain.com
+admin_password=admin
+admin_tenant=admin
+url=http://localhost:5000/v2.0/
+default_image=None
+default_flavor=m1.small
+default_security_group=default
+ca_ssl_cert=/etc/ssl/certs/ca-certificates.crt
+
+[observer]
+pretend=False
+backoff_disabled=False
+images_directory=/opt/xos/images
+dependency_graph=/opt/xos/model-deps
+logfile=/var/log/xos_backend.log
+steps_dir=/opt/xos/synchronizers/helloworld/steps
+applist=helloworld
+
+[gui]
+disable_minidashboard=True
+#branding_name=CORD
+#branding_css=/static/cord.css
+#branding_icon=/static/onos-logo.png
diff --git a/xos/observers/helloworld/model-deps b/xos/synchronizers/helloworld/model-deps
similarity index 100%
rename from xos/observers/helloworld/model-deps
rename to xos/synchronizers/helloworld/model-deps
diff --git a/xos/observers/helloworld/nohup.out b/xos/synchronizers/helloworld/nohup.out
similarity index 100%
rename from xos/observers/helloworld/nohup.out
rename to xos/synchronizers/helloworld/nohup.out
diff --git a/xos/observers/helloworld/run.sh b/xos/synchronizers/helloworld/run.sh
similarity index 100%
rename from xos/observers/helloworld/run.sh
rename to xos/synchronizers/helloworld/run.sh
diff --git a/xos/observers/helloworld/start.sh b/xos/synchronizers/helloworld/start.sh
similarity index 100%
rename from xos/observers/helloworld/start.sh
rename to xos/synchronizers/helloworld/start.sh
diff --git a/xos/synchronizers/helloworld/steps/sync_hello.py b/xos/synchronizers/helloworld/steps/sync_hello.py
new file mode 100644
index 0000000..55d318a
--- /dev/null
+++ b/xos/synchronizers/helloworld/steps/sync_hello.py
@@ -0,0 +1,26 @@
+import os
+import sys
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from services.helloworld.models import Hello,World
+from xos.logger import Logger, logging
+
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+logger = Logger(level=logging.INFO)
+
+class SyncHello(SyncStep):
+ provides=[Hello]
+ observes=Hello
+ requested_interval=0
+
+ def sync_record(self, record):
+ instance = record.instance_backref
+ instance.userData="packages:\n - apache2\nruncmd:\n - update-rc.d apache2 enable\n - service apache2 start\nwrite_files:\n- content: Hello %s\n path: /var/www/html/hello.txt"%record.name
+ instance.save()
+
+ def delete_record(self, m):
+ return
diff --git a/xos/synchronizers/helloworld/steps/sync_world.py b/xos/synchronizers/helloworld/steps/sync_world.py
new file mode 100644
index 0000000..a4e7e3c
--- /dev/null
+++ b/xos/synchronizers/helloworld/steps/sync_world.py
@@ -0,0 +1,25 @@
+import os
+import sys
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from services.helloworld.models import Hello,World
+from xos.logger import Logger, logging
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+logger = Logger(level=logging.INFO)
+
+class SyncWorld(SyncStep):
+ provides=[World]
+ observes=World
+ requested_interval=0
+
+ def sync_record(self, record):
+ open('/tmp/hello-synchronizer','w').write(record.name)
+
+ def delete_record(self, m):
+ return
diff --git a/xos/observers/helloworld/stop.sh b/xos/synchronizers/helloworld/stop.sh
similarity index 100%
rename from xos/observers/helloworld/stop.sh
rename to xos/synchronizers/helloworld/stop.sh
diff --git a/xos/synchronizers/helloworldservice_complete/helloworldservice-synchronizer.py b/xos/synchronizers/helloworldservice_complete/helloworldservice-synchronizer.py
new file mode 100755
index 0000000..95f4081
--- /dev/null
+++ b/xos/synchronizers/helloworldservice_complete/helloworldservice-synchronizer.py
@@ -0,0 +1,13 @@
+#!/usr/bin/env python
+
+# This imports and runs ../../xos-observer.py
+# Runs the standard XOS observer
+
+import importlib
+import os
+import sys
+observer_path = os.path.join(os.path.dirname(
+ os.path.realpath(__file__)), "../../synchronizers/base")
+sys.path.append(observer_path)
+mod = importlib.import_module("xos-synchronizer")
+mod.main()
diff --git a/xos/synchronizers/helloworldservice_complete/helloworldservice_config b/xos/synchronizers/helloworldservice_complete/helloworldservice_config
new file mode 100644
index 0000000..b779d0e
--- /dev/null
+++ b/xos/synchronizers/helloworldservice_complete/helloworldservice_config
@@ -0,0 +1,36 @@
+# Required by XOS
+[db]
+name=xos
+user=postgres
+password=password
+host=localhost
+port=5432
+
+# Required by XOS
+[api]
+nova_enabled=True
+
+# Sets options for the observer
+[observer]
+# Optional name
+name=helloworldservice
+# This is the location to the dependency graph you generate
+dependency_graph=/opt/xos/observers/helloworldservice_complete/model-deps
+# The location of your SyncSteps
+steps_dir=/opt/xos/synchronizers/helloworldservice_complete/steps
+# A temporary directory that will be used by ansible
+sys_dir=/opt/xos/observers/helloworldservice_complete/sys
+# Location of the file to save logging messages to the backend log is often used
+logfile=/var/log/xos_backend.log
+# If this option is true, then nothing will change, we simply pretend to run
+pretend=False
+# If this is False then XOS will use an exponential backoff when the observer
+# fails, since we will be waiting for an instance, we don't want this.
+backoff_disabled=True
+# We want the output from ansible to be logged
+save_ansible_output=True
+# This determines how we SSH to a client, if this is set to True then we try
+# to ssh using the instance name as a proxy, if this is disabled we ssh using
+# the NAT IP of the instance. On CloudLab the first option will fail so we must
+# set this to False
+proxy_ssh=False
diff --git a/xos/observers/helloworldservice_complete/model-deps b/xos/synchronizers/helloworldservice_complete/model-deps
similarity index 100%
rename from xos/observers/helloworldservice_complete/model-deps
rename to xos/synchronizers/helloworldservice_complete/model-deps
diff --git a/xos/observers/helloworldservice_complete/run.sh b/xos/synchronizers/helloworldservice_complete/run.sh
similarity index 100%
rename from xos/observers/helloworldservice_complete/run.sh
rename to xos/synchronizers/helloworldservice_complete/run.sh
diff --git a/xos/synchronizers/helloworldservice_complete/steps/sync_helloworldtenant.py b/xos/synchronizers/helloworldservice_complete/steps/sync_helloworldtenant.py
new file mode 100644
index 0000000..b7ed2a8
--- /dev/null
+++ b/xos/synchronizers/helloworldservice_complete/steps/sync_helloworldtenant.py
@@ -0,0 +1,48 @@
+import os
+import sys
+from django.db.models import Q, F
+from services.helloworldservice_complete.models import HelloWorldServiceComplete, HelloWorldTenantComplete
+from synchronizers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
+
+parentdir = os.path.join(os.path.dirname(__file__), "..")
+sys.path.insert(0, parentdir)
+
+# Class to define how we sync a tenant. Using SyncInstanceUsingAnsible we
+# indicate where the find the YAML for ansible, where to find the SSH key,
+# and the logic for determining what tenant needs updating, what additional
+# attributes are needed, and how to delete an instance.
+class SyncHelloWorldTenantComplete(SyncInstanceUsingAnsible):
+ # Indicates the position in the data model, this will run when XOS needs to
+ # enact a HelloWorldTenantComplete
+ provides = [HelloWorldTenantComplete]
+ # The actual model being enacted, usually the same as provides.
+ observes = HelloWorldTenantComplete
+ # Number of milliseconds between interruptions of the observer
+ requested_interval = 0
+ # The ansible template to run
+ template_name = "sync_helloworldtenant.yaml"
+ # The location of the SSH private key to use when ansible connects to
+ # instances.
+ service_key_name = "/opt/xos/observers/helloworldservice_complete/helloworldservice_private_key"
+
+ def __init__(self, *args, **kwargs):
+ super(SyncHelloWorldTenantComplete, self).__init__(*args, **kwargs)
+
+ # Defines the logic for determining what HelloWorldTenantCompletes need to be
+ # enacted.
+ def fetch_pending(self, deleted):
+ # If the update is not a deletion, then we get all of the instnaces that
+ # have been updated or have not been enacted.
+ if (not deleted):
+ objs = HelloWorldTenantComplete.get_tenant_objects().filter(
+ Q(enacted__lt=F('updated')) | Q(enacted=None), Q(lazy_blocked=False))
+ else:
+ # If this is a deletion we get all of the deleted tenants..
+ objs = HelloWorldTenantComplete.get_deleted_tenant_objects()
+
+ return objs
+
+ # Gets the attributes that are used by the Ansible template but are not
+ # part of the set of default attributes.
+ def get_extra_attributes(self, o):
+ return {"display_message": o.display_message}
diff --git a/xos/observers/helloworldservice_complete/steps/sync_helloworldtenant.yaml b/xos/synchronizers/helloworldservice_complete/steps/sync_helloworldtenant.yaml
similarity index 100%
rename from xos/observers/helloworldservice_complete/steps/sync_helloworldtenant.yaml
rename to xos/synchronizers/helloworldservice_complete/steps/sync_helloworldtenant.yaml
diff --git a/xos/observers/helloworldservice_complete/stop.sh b/xos/synchronizers/helloworldservice_complete/stop.sh
similarity index 100%
rename from xos/observers/helloworldservice_complete/stop.sh
rename to xos/synchronizers/helloworldservice_complete/stop.sh
diff --git a/xos/observers/hpc/Makefile b/xos/synchronizers/hpc/Makefile
similarity index 100%
rename from xos/observers/hpc/Makefile
rename to xos/synchronizers/hpc/Makefile
diff --git a/xos/synchronizers/hpc/fsck.py b/xos/synchronizers/hpc/fsck.py
new file mode 100644
index 0000000..448bfb7
--- /dev/null
+++ b/xos/synchronizers/hpc/fsck.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python
+import argparse
+import imp
+import inspect
+import os
+import sys
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+sys.path.append("/opt/xos")
+from xos.config import Config, DEFAULT_CONFIG_FN, XOS_DIR
+from xos.logger import Logger, logging
+from synchronizers.base.syncstep import SyncStep
+
+try:
+ from django import setup as django_setup # django 1.7
+except:
+ django_setup = False
+
+logger = Logger(level=logging.INFO)
+
+class XOSConsistencyCheck:
+ def __init__(self):
+ self.sync_steps = []
+ self.load_sync_step_modules()
+
+ def load_sync_step_modules(self, step_dir=None):
+ if step_dir is None:
+ if hasattr(Config(), "observer_steps_dir"):
+ step_dir = Config().observer_steps_dir
+ else:
+ step_dir = XOS_DIR+"/observer/steps"
+
+ for fn in os.listdir(step_dir):
+ pathname = os.path.join(step_dir,fn)
+ if os.path.isfile(pathname) and fn.endswith(".py") and (fn!="__init__.py"):
+ module = imp.load_source(fn[:-3],pathname)
+ for classname in dir(module):
+ c = getattr(module, classname, None)
+
+ # make sure 'c' is a descendent of SyncStep and has a
+ # provides field (this eliminates the abstract base classes
+ # since they don't have a provides)
+
+ if inspect.isclass(c) and issubclass(c, SyncStep) and hasattr(c,"provides") and (c not in self.sync_steps):
+ self.sync_steps.append(c)
+ logger.info('loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps]))
+
+ def run(self):
+ updated = True
+ while updated:
+ updated = False
+
+ for step in self.sync_steps:
+ if hasattr(step, "consistency_check"):
+ updated = updated or step(driver=None).consistency_check()
+
+ if updated:
+ logger.info('re-running consistency checks because something changed')
+
+def main():
+ if not "-C" in sys.argv:
+ print >> sys.stderr, "You probably wanted to use -C " + XOS_DIR + "/hpc_observer/hpc_observer_config"
+
+ # Generate command line parser
+ parser = argparse.ArgumentParser(usage='%(prog)s [options]')
+ # smbaker: util/config.py parses sys.argv[] directly to get config file name; include the option here to avoid
+ # throwing unrecognized argument exceptions
+ parser.add_argument('-C', '--config', dest='config_file', action='store', default=DEFAULT_CONFIG_FN,
+ help='Name of config file.')
+ args = parser.parse_args()
+
+ if django_setup: # 1.7
+ django_setup()
+
+ cc = XOSConsistencyCheck()
+ cc.run()
+
+if __name__ == '__main__':
+ main()
+
diff --git a/xos/synchronizers/hpc/hpc-synchronizer.py b/xos/synchronizers/hpc/hpc-synchronizer.py
new file mode 100755
index 0000000..84bec4f
--- /dev/null
+++ b/xos/synchronizers/hpc/hpc-synchronizer.py
@@ -0,0 +1,11 @@
+#!/usr/bin/env python
+
+# This imports and runs ../../xos-observer.py
+
+import importlib
+import os
+import sys
+observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../../synchronizers/base")
+sys.path.append(observer_path)
+mod = importlib.import_module("xos-synchronizer")
+mod.main()
diff --git a/xos/synchronizers/hpc/hpc_synchronizer_config b/xos/synchronizers/hpc/hpc_synchronizer_config
new file mode 100644
index 0000000..9d4e70a
--- /dev/null
+++ b/xos/synchronizers/hpc/hpc_synchronizer_config
@@ -0,0 +1,36 @@
+
+[plc]
+name=plc
+deployment=VICCI
+
+[db]
+name=xos
+user=postgres
+password=password
+host=localhost
+port=5432
+
+[api]
+host=128.112.171.237
+port=8000
+ssl_key=None
+ssl_cert=None
+ca_ssl_cert=None
+ratelimit_enabled=0
+omf_enabled=0
+mail_support_address=support@localhost
+nova_enabled=True
+
+[observer]
+name=hpc
+dependency_graph=/opt/xos/synchronizers/hpc/model-deps
+steps_dir=/opt/xos/synchronizers/hpc/steps
+deleters_dir=/opt/xos/synchronizers/hpc/deleters
+log_file=console
+#/var/log/hpc.log
+driver=None
+#cmi_hostname=openclouddev0.internet2.edu
+
+[feefie]
+client_id='vicci_dev_central'
+user_id='pl'
diff --git a/xos/synchronizers/hpc/hpc_watcher.py b/xos/synchronizers/hpc/hpc_watcher.py
new file mode 100644
index 0000000..d2efdcc
--- /dev/null
+++ b/xos/synchronizers/hpc/hpc_watcher.py
@@ -0,0 +1,629 @@
+"""
+ hpc_watcher.py
+
+ Daemon to watch the health of HPC and RR instances.
+
+ This deamon uses HpcHealthCheck objects in the Data Model to conduct
+ periodic tests of HPC and RR nodes. Two types of Health Checks are
+ supported:
+
+ kind="dns": checks the request routers to make sure that a DNS
+ name is resolveable and returns the right kind of records.
+
+ resource_name should be set to the domain name to lookup.
+
+ result_contains is option and can be used to hold "A", "CNAME", or
+ a particular address or hostname that should be contained in the
+ query's answer.
+
+ kind="http": checks the hpc nodes to make sure that a URL can be
+ retrieved from the node.
+
+ resource_name should be set to the HostName:Url to fetch. For
+ example, cdn-stream.htm.fiu.edu:/hft2441/intro.mp4
+
+ In addition to the above, HPC heartbeat probes are conducted, similar to
+ the ones that dnsredir conducts.
+
+ The results of health checks are stored in a tag attached to the Instance
+ the healthcheck was conducted against. If all healthchecks of a particular
+ variety were successful for a instance, then "success" will be stored in
+ the tag. Otherwise, the first healthcheck to fail will be stored in the
+ tag.
+
+ Ubuntu prereqs:
+ apt-get install python-pycurl
+ pip install dnslib
+"""
+
+import os
+import socket
+import sys
+sys.path.append("/opt/xos")
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+import django
+from django.contrib.contenttypes.models import ContentType
+from core.models import *
+from services.hpc.models import *
+from services.requestrouter.models import *
+django.setup()
+import time
+import pycurl
+import traceback
+import json
+from StringIO import StringIO
+
+from dnslib.dns import DNSRecord,DNSHeader,DNSQuestion,QTYPE
+from dnslib.digparser import DigParser
+
+from threading import Thread, Condition
+
+"""
+from dnslib import *
+q = DNSRecord(q=DNSQuestion("cdn-stream.htm.fiu.edu"))
+a_pkt = q.send("150.135.65.10", tcp=False, timeout=10)
+a = DNSRecord.parse(a_pkt)
+
+from dnslib import *
+q = DNSRecord(q=DNSQuestion("onlab.vicci.org"))
+a_pkt = q.send("150.135.65.10", tcp=False, timeout=10)
+a = DNSRecord.parse(a_pkt)
+"""
+
+class WorkQueue:
+ def __init__(self):
+ self.job_cv = Condition()
+ self.jobs = []
+ self.result_cv = Condition()
+ self.results = []
+ self.outstanding = 0
+
+ def get_job(self):
+ self.job_cv.acquire()
+ while not self.jobs:
+ self.job_cv.wait()
+ result = self.jobs.pop()
+ self.job_cv.release()
+ return result
+
+ def submit_job(self, job):
+ self.job_cv.acquire()
+ self.jobs.append(job)
+ self.job_cv.notify()
+ self.job_cv.release()
+ self.outstanding = self.outstanding + 1
+
+ def get_result(self):
+ self.result_cv.acquire()
+ while not self.results:
+ self.result_cv.wait()
+ result = self.results.pop()
+ self.result_cv.release()
+ self.outstanding = self.outstanding - 1
+ return result
+
+ def submit_result(self, result):
+ self.result_cv.acquire()
+ self.results.append(result)
+ self.result_cv.notify()
+ self.result_cv.release()
+
+class DnsResolver(Thread):
+ def __init__(self, queue):
+ Thread.__init__(self)
+ self.queue = queue
+ self.daemon = True
+ self.start()
+
+ def run(self):
+ while True:
+ job = self.queue.get_job()
+ self.handle_job(job)
+ self.queue.submit_result(job)
+
+ def handle_job(self, job):
+ domain = job["domain"]
+ server = job["server"]
+ port = job["port"]
+ result_contains = job.get("result_contains", None)
+
+ try:
+ q = DNSRecord(q=DNSQuestion(domain)) #, getattr(QTYPE,"A")))
+
+ a_pkt = q.send(server, port, tcp=False, timeout=10)
+ a = DNSRecord.parse(a_pkt)
+
+ found_record = False
+ for record in a.rr:
+ if (not result_contains):
+ QTYPE_A = getattr(QTYPE,"A")
+ QTYPE_CNAME = getattr(QTYPE, "CNAME")
+ if ((record.rtype==QTYPE_A) or (record.qtype==QTYPE_CNAME)):
+ found_record = True
+ else:
+ tmp = QTYPE.get(record.rtype) + str(record.rdata)
+ if (result_contains in tmp):
+ found_record = True
+
+ if not found_record:
+ if result_contains:
+ job["status"] = "%s,No %s records" % (domain, result_contains)
+ else:
+ job["status"] = "%s,No A or CNAME records" % domain
+
+ return
+
+ except Exception, e:
+ job["status"] = "%s,Exception: %s" % (domain, str(e))
+ return
+
+ job["status"] = "success"
+
+class HpcHeartbeat(Thread):
+ def __init__(self, queue):
+ Thread.__init__(self)
+ self.queue = queue
+ self.daemon = True
+ self.start()
+
+ def run(self):
+ while True:
+ job = self.queue.get_job()
+ self.handle_job(job)
+ self.queue.submit_result(job)
+
+ def curl_error_message(self, e):
+ if e.args[0] == 6:
+ return "couldn't resolve host"
+ if e.args[0] == 7:
+ return "failed to connect"
+ return "curl error %d" % e.args[0]
+
+ def handle_job(self, job):
+ server = job["server"]
+ port = job["port"]
+
+ try:
+ buffer = StringIO()
+ c = pycurl.Curl()
+
+ c.setopt(c.URL, "http://%s:%s/heartbeat" % (server, port))
+ c.setopt(c.WRITEDATA, buffer)
+ c.setopt(c.HTTPHEADER, ['host: hpc-heartbeat', 'X-heartbeat: 1'])
+ c.setopt(c.TIMEOUT, 10)
+ c.setopt(c.CONNECTTIMEOUT, 10)
+ c.setopt(c.NOSIGNAL, 1)
+
+ try:
+ c.perform()
+ response_code = c.getinfo(c.RESPONSE_CODE)
+ except Exception, e:
+ #traceback.print_exc()
+ job["status"] = self.curl_error_message(e)
+ return
+ finally:
+ c.close()
+
+ if response_code != 200:
+ job["status"] = "error response %d" % response_code
+ return
+
+ except Exception, e:
+ job["status"] = "Exception: %s" % str(e)
+ return
+
+ job["status"] = "success"
+
+class HpcFetchUrl(Thread):
+ def __init__(self, queue):
+ Thread.__init__(self)
+ self.queue = queue
+ self.daemon = True
+ self.start()
+
+ def run(self):
+ while True:
+ job = self.queue.get_job()
+ self.handle_job(job)
+ self.queue.submit_result(job)
+
+ def curl_error_message(self, e):
+ if e.args[0] == 6:
+ return "couldn't resolve host"
+ if e.args[0] == 7:
+ return "failed to connect"
+ return "curl error %d" % e.args[0]
+
+ def handle_job(self, job):
+ server = job["server"]
+ port = job["port"]
+ url = job["url"]
+ domain = job["domain"]
+
+ def progress(download_t, download_d, upload_t, upload_d):
+ # limit download size to a megabyte
+ if (download_d > 1024*1024):
+ return 1
+ else:
+ return 0
+
+ try:
+ buffer = StringIO()
+ c = pycurl.Curl()
+
+ c.setopt(c.URL, "http://%s:%s/%s" % (server, port, url))
+ c.setopt(c.WRITEDATA, buffer)
+ c.setopt(c.HTTPHEADER, ['host: ' + domain])
+ c.setopt(c.TIMEOUT, 10)
+ c.setopt(c.CONNECTTIMEOUT, 10)
+ c.setopt(c.NOSIGNAL, 1)
+ c.setopt(c.NOPROGRESS, 0)
+ c.setopt(c.PROGRESSFUNCTION, progress)
+
+ try:
+ try:
+ c.perform()
+ except Exception, e:
+ # prevent callback abort from raising exception
+ if (e.args[0] != pycurl.E_ABORTED_BY_CALLBACK):
+ raise
+ response_code = c.getinfo(c.RESPONSE_CODE)
+ bytes_downloaded = int(c.getinfo(c.SIZE_DOWNLOAD))
+ total_time = float(c.getinfo(c.TOTAL_TIME))
+ except Exception, e:
+ #traceback.print_exc()
+ job["status"] = self.curl_error_message(e)
+ return
+ finally:
+ c.close()
+
+ if response_code != 200:
+ job["status"] = "error response %s" % str(response_code)
+ return
+
+ except Exception, e:
+ #traceback.print_exc()
+ job["status"] = "Exception: %s" % str(e)
+ return
+
+ job["status"] = "success"
+ job["bytes_downloaded"] = bytes_downloaded
+ job["total_time"] = total_time
+
+class WatcherWorker(Thread):
+ def __init__(self, queue):
+ Thread.__init__(self)
+ self.queue = queue
+ self.daemon = True
+ self.start()
+
+ def run(self):
+ while True:
+ job = self.queue.get_job()
+ self.handle_job(job)
+ self.queue.submit_result(job)
+
+ def curl_error_message(self, e):
+ if e.args[0] == 6:
+ return "couldn't resolve host"
+ if e.args[0] == 7:
+ return "failed to connect"
+ return "curl error %d" % e.args[0]
+
+ def handle_job(self, job):
+ server = job["server"]
+ port = job["port"]
+
+ try:
+ buffer = StringIO()
+ c = pycurl.Curl()
+
+ c.setopt(c.URL, "http://%s:%s/" % (server, port))
+ c.setopt(c.WRITEDATA, buffer)
+ c.setopt(c.TIMEOUT, 10)
+ c.setopt(c.CONNECTTIMEOUT, 10)
+ c.setopt(c.NOSIGNAL, 1)
+
+ try:
+ c.perform()
+ response_code = c.getinfo(c.RESPONSE_CODE)
+ except Exception, e:
+ #traceback.print_exc()
+ job["status"] = json.dumps( {"status": self.curl_error_message(e)} )
+ return
+ finally:
+ c.close()
+
+ if response_code != 200:
+ job["status"] = json.dumps( {"status": "error response %d" % response_code} )
+ return
+
+ d = json.loads(buffer.getvalue())
+ d["status"] = "success";
+ job["status"] = json.dumps(d)
+
+ except Exception, e:
+ job["status"] = json.dumps( {"status": "Exception: %s" % str(e)} )
+ return
+
+class BaseWatcher(Thread):
+ def __init__(self):
+ Thread.__init__(self)
+ self.daemon = True
+
+ def get_public_ip(self, service, instance):
+ network_name = None
+ if "hpc" in instance.slice.name:
+ network_name = getattr(service, "watcher_hpc_network", None)
+ elif "demux" in instance.slice.name:
+ network_name = getattr(service, "watcher_dnsdemux_network", None)
+ elif "redir" in instance.slice.name:
+ network_name = getattr(service, "watcher_dnsredir_network", None)
+
+ if network_name and network_name.lower()=="nat":
+ return None
+
+ if (network_name is None) or (network_name=="") or (network_name.lower()=="public"):
+ return instance.get_public_ip()
+
+ for ns in instance.ports.all():
+ if (ns.ip) and (ns.network.name==network_name):
+ return ns.ip
+
+ raise ValueError("Couldn't find network %s" % str(network_name))
+
+ def set_status(self, instance, service, kind, msg, check_error=True):
+ #print instance.node.name, kind, msg
+ if check_error:
+ instance.has_error = (msg!="success")
+
+ instance_type = ContentType.objects.get_for_model(instance)
+
+ t = Tag.objects.filter(service=service, name=kind+".msg", content_type__pk=instance_type.id, object_id=instance.id)
+ if t:
+ t=t[0]
+ if (t.value != msg):
+ t.value = msg
+ t.save()
+ else:
+ Tag(service=service, name=kind+".msg", content_object = instance, value=msg).save()
+
+ t = Tag.objects.filter(service=service, name=kind+".time", content_type__pk=instance_type.id, object_id=instance.id)
+ if t:
+ t=t[0]
+ t.value = str(time.time())
+ t.save()
+ else:
+ Tag(service=service, name=kind+".time", content_object = instance, value=str(time.time())).save()
+
+ def get_service_slices(self, service, kind=None):
+ try:
+ slices = service.slices.all()
+ except:
+ # buggy data model
+ slices = service.service.all()
+
+ if kind:
+ return [x for x in slices if (kind in x.name)]
+ else:
+ return list(slices)
+
+class RRWatcher(BaseWatcher):
+ def __init__(self):
+ BaseWatcher.__init__(self)
+
+ self.resolver_queue = WorkQueue()
+ for i in range(0,10):
+ DnsResolver(queue = self.resolver_queue)
+
+ def check_request_routers(self, service, instances):
+ for instance in instances:
+ instance.has_error = False
+
+ try:
+ ip = self.get_public_ip(service, instance)
+ except Exception, e:
+ self.set_status(instance, service, "watcher.DNS", "exception: %s" % str(e))
+ continue
+ if not ip:
+ try:
+ ip = socket.gethostbyname(instance.node.name)
+ except:
+ self.set_status(instance, service, "watcher.DNS", "dns resolution failure")
+ continue
+
+ if not ip:
+ self.set_status(instance, service, "watcher.DNS", "no IP address")
+ continue
+
+ checks = HpcHealthCheck.objects.filter(kind="dns")
+ if not checks:
+ self.set_status(instance, service, "watcher.DNS", "no DNS HealthCheck tests configured")
+
+ for check in checks:
+ self.resolver_queue.submit_job({"domain": check.resource_name, "server": ip, "port": 53, "instance": instance, "result_contains": check.result_contains})
+
+ while self.resolver_queue.outstanding > 0:
+ result = self.resolver_queue.get_result()
+ instance = result["instance"]
+ if (result["status"]!="success") and (not instance.has_error):
+ self.set_status(instance, service, "watcher.DNS", result["status"])
+
+ for instance in instances:
+ if not instance.has_error:
+ self.set_status(instance, service, "watcher.DNS", "success")
+
+ def run_once(self):
+ for hpcService in HpcService.objects.all():
+ for slice in self.get_service_slices(hpcService, "dnsdemux"):
+ self.check_request_routers(hpcService, slice.instances.all())
+
+ for rrService in RequestRouterService.objects.all():
+ for slice in self.get_service_slices(rrService, "dnsdemux"):
+ self.check_request_routers(rrService, slice.instances.all())
+
+ def run(self):
+ while True:
+ self.run_once()
+ time.sleep(10)
+
+ django.db.reset_queries()
+
+class HpcProber(BaseWatcher):
+ def __init__(self):
+ BaseWatcher.__init__(self)
+
+ self.heartbeat_queue = WorkQueue()
+ for i in range(0, 10):
+ HpcHeartbeat(queue = self.heartbeat_queue)
+
+ def probe_hpc(self, service, instances):
+ for instance in instances:
+ instance.has_error = False
+
+ self.heartbeat_queue.submit_job({"server": instance.node.name, "port": 8009, "instance": instance})
+
+ while self.heartbeat_queue.outstanding > 0:
+ result = self.heartbeat_queue.get_result()
+ instance = result["instance"]
+ if (result["status"]!="success") and (not instance.has_error):
+ self.set_status(instance, service, "watcher.HPC-hb", result["status"])
+
+ for instance in instances:
+ if not instance.has_error:
+ self.set_status(instance, service, "watcher.HPC-hb", "success")
+
+ def run_once(self):
+ for hpcService in HpcService.objects.all():
+ for slice in self.get_service_slices(hpcService, "hpc"):
+ self.probe_hpc(hpcService, slice.instances.all())
+
+ def run(self):
+ while True:
+ self.run_once()
+ time.sleep(10)
+
+ django.db.reset_queries()
+
+class HpcFetcher(BaseWatcher):
+ def __init__(self):
+ BaseWatcher.__init__(self)
+
+ self.fetch_queue = WorkQueue()
+ for i in range(0, 10):
+ HpcFetchUrl(queue = self.fetch_queue)
+
+ def fetch_hpc(self, service, instances):
+ for instance in instances:
+ instance.has_error = False
+ instance.url_status = []
+
+ checks = HpcHealthCheck.objects.filter(kind="http")
+ if not checks:
+ self.set_status(instance, service, "watcher.HPC-fetch", "no HTTP HealthCheck tests configured")
+
+ for check in checks:
+ if (not check.resource_name) or (":" not in check.resource_name):
+ self.set_status(instance, service, "watcher.HPC-fetch", "malformed resource_name: " + str(check.resource_name))
+ break
+
+ (domain, url) = check.resource_name.split(":",1)
+
+ self.fetch_queue.submit_job({"server": instance.node.name, "port": 80, "instance": instance, "domain": domain, "url": url})
+
+ while self.fetch_queue.outstanding > 0:
+ result = self.fetch_queue.get_result()
+ instance = result["instance"]
+ if (result["status"] == "success"):
+ instance.url_status.append( (result["domain"] + result["url"], "success", result["bytes_downloaded"], result["total_time"]) )
+ if (result["status"]!="success") and (not instance.has_error):
+ self.set_status(instance, service, "watcher.HPC-fetch", result["status"])
+
+ for instance in instances:
+ self.set_status(instance, service, "watcher.HPC-fetch-urls", json.dumps(instance.url_status), check_error=False)
+ if not instance.has_error:
+ self.set_status(instance, service, "watcher.HPC-fetch", "success")
+
+ def run_once(self):
+ for hpcService in HpcService.objects.all():
+ for slice in self.get_service_slices(hpcService, "hpc"):
+ try:
+ self.fetch_hpc(hpcService, slice.instances.all())
+ except:
+ traceback.print_exc()
+
+ def run(self):
+ while True:
+ self.run_once()
+ time.sleep(10)
+
+ django.db.reset_queries()
+
+class WatcherFetcher(BaseWatcher):
+ def __init__(self):
+ BaseWatcher.__init__(self)
+
+ self.fetch_queue = WorkQueue()
+ for i in range(0, 10):
+ WatcherWorker(queue = self.fetch_queue)
+
+ def fetch_watcher(self, service, instances):
+ for instance in instances:
+ try:
+ ip = self.get_public_ip(service, instance)
+ except Exception, e:
+ self.set_status(instance, service, "watcher.watcher", json.dumps({"status": "exception: %s" % str(e)}) )
+ continue
+ if not ip:
+ try:
+ ip = socket.gethostbyname(instance.node.name)
+ except:
+ self.set_status(instance, service, "watcher.watcher", json.dumps({"status": "dns resolution failure"}) )
+ continue
+
+ if not ip:
+ self.set_status(instance, service, "watcher.watcher", json.dumps({"status": "no IP address"}) )
+ continue
+
+ port = 8015
+ if ("redir" in instance.slice.name):
+ port = 8016
+ elif ("demux" in instance.slice.name):
+ port = 8017
+
+ self.fetch_queue.submit_job({"server": ip, "port": port, "instance": instance})
+
+ while self.fetch_queue.outstanding > 0:
+ result = self.fetch_queue.get_result()
+ instance = result["instance"]
+ self.set_status(instance, service, "watcher.watcher", result["status"])
+
+ def run_once(self):
+ for hpcService in HpcService.objects.all():
+ for slice in self.get_service_slices(hpcService):
+ self.fetch_watcher(hpcService, slice.instances.all())
+
+ def run(self):
+ while True:
+ self.run_once()
+ time.sleep(10)
+
+ django.db.reset_queries()
+
+
+if __name__ == "__main__":
+ if "--once" in sys.argv:
+ RRWatcher().run_once()
+ HpcProber().run_once()
+ HpcFetcher().run_once()
+ WatcherFetcher().run_once()
+ else:
+ RRWatcher().start()
+ HpcProber().start()
+ HpcFetcher().start()
+ WatcherFetcher().start()
+
+ print "Running forever..."
+ while True:
+ time.sleep(60)
+
diff --git a/xos/synchronizers/hpc/hpclib.py b/xos/synchronizers/hpc/hpclib.py
new file mode 100644
index 0000000..bb1c263
--- /dev/null
+++ b/xos/synchronizers/hpc/hpclib.py
@@ -0,0 +1,126 @@
+import os
+import base64
+import string
+import sys
+import xmlrpclib
+
+if __name__ == '__main__':
+ sys.path.append("/opt/xos")
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+
+from xos.config import Config
+from core.models import Service
+from services.hpc.models import HpcService
+from services.requestrouter.models import RequestRouterService
+from xos.logger import Logger, logging
+
+logger = Logger(level=logging.INFO)
+
+class APIHelper:
+ def __init__(self, proxy, auth, method=None):
+ self.proxy = proxy
+ self.auth = auth
+ self.method = method
+
+ def __getattr__(self, name):
+ if name.startswith("_"):
+ return getattr(self, name)
+ else:
+ return APIHelper(self.proxy, self.auth, name)
+
+ def __call__(self, *args):
+ method = getattr(self.proxy, self.method)
+ return method(self.auth, *args)
+
+class CmiClient:
+ def __init__(self, hostname, port=8003, username="apiuser", password="apiuser"):
+ self.connect_api(hostname, port, username, password)
+
+ def connect_api(self, hostname, port=8003, username="apiuser", password="apiuser"):
+ #print "https://%s:%d/COAPI/" % (hostname, port)
+ cob = xmlrpclib.ServerProxy("https://%s:%d/COAPI/" % (hostname, port), allow_none=True)
+ cob_auth = {}
+ cob_auth["Username"] = username
+ cob_auth["AuthString"] = password
+ cob_auth["AuthMethod"] = "password"
+
+ onev = xmlrpclib.ServerProxy("https://%s:%d/ONEV_API/" % (hostname, port), allow_none=True)
+ onev_auth = {}
+ onev_auth["Username"] = username
+ onev_auth["AuthString"] = password
+ onev_auth["AuthMethod"] = "password"
+
+ self.cob = APIHelper(cob, cob_auth)
+ self.onev = APIHelper(onev, onev_auth)
+
+class HpcLibrary:
+ def __init__(self):
+ self._client = None
+
+ def make_account_name(self, x):
+ x=x.lower()
+ y = ""
+ for c in x:
+ if (c in (string.lowercase + string.digits)):
+ y = y + c
+ return y[:20]
+
+ def get_hpc_service(self):
+ hpc_service_name = getattr(Config(), "observer_hpc_service", None)
+ if hpc_service_name:
+ hpc_service = HpcService.objects.filter(name = hpc_service_name)
+ else:
+ hpc_service = HpcService.objects.all()
+
+ if not hpc_service:
+ if hpc_service_name:
+ raise Exception("No HPC Service with name %s" % hpc_service_name)
+ else:
+ raise Exception("No HPC Services")
+ hpc_service = hpc_service[0]
+
+ return hpc_service
+
+ def get_cmi_hostname(self, hpc_service=None):
+ if getattr(Config(),"observer_cmi_hostname",None):
+ return getattr(Config(),"observer_cmi_hostname")
+
+ if (hpc_service is None):
+ hpc_service = self.get_hpc_service()
+
+ if hpc_service.cmi_hostname:
+ return hpc_service.cmi_hostname
+
+ try:
+ slices = hpc_service.slices.all()
+ except:
+ # deal with buggy data model
+ slices = hpc_service.service.all()
+
+ for slice in slices:
+ if slice.name.endswith("cmi"):
+ for instance in slice.instances.all():
+ if instance.node:
+ return instance.node.name
+
+ raise Exception("Failed to find a CMI instance")
+
+ @property
+ def client(self):
+ if self._client is None:
+ self._client = CmiClient(self.get_cmi_hostname())
+ return self._client
+
+if __name__ == '__main__':
+ import django
+ django.setup()
+
+ lib = HpcLibrary()
+
+ print "testing API connection to", lib.get_cmi_hostname()
+ lib.client.cob.GetNewObjects()
+ lib.client.onev.ListAll("CDN")
+
+
+
+
diff --git a/xos/observers/hpc/model-deps b/xos/synchronizers/hpc/model-deps
similarity index 100%
rename from xos/observers/hpc/model-deps
rename to xos/synchronizers/hpc/model-deps
diff --git a/xos/observers/hpc/run.sh b/xos/synchronizers/hpc/run.sh
similarity index 100%
rename from xos/observers/hpc/run.sh
rename to xos/synchronizers/hpc/run.sh
diff --git a/xos/observers/hpc/start.sh b/xos/synchronizers/hpc/start.sh
similarity index 100%
rename from xos/observers/hpc/start.sh
rename to xos/synchronizers/hpc/start.sh
diff --git a/xos/synchronizers/hpc/steps/garbage_collector.py b/xos/synchronizers/hpc/steps/garbage_collector.py
new file mode 100644
index 0000000..658f7a1
--- /dev/null
+++ b/xos/synchronizers/hpc/steps/garbage_collector.py
@@ -0,0 +1,67 @@
+import os
+import sys
+import base64
+import traceback
+from collections import defaultdict
+from django.db.models import F, Q
+from xos.config import Config
+from xos.logger import Logger, logging
+from synchronizers.base.syncstep import SyncStep
+from services.hpc.models import ServiceProvider, ContentProvider, CDNPrefix, OriginServer
+from core.models import *
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+from hpclib import HpcLibrary
+
+logger = Logger(level=logging.INFO)
+
+class GarbageCollector(SyncStep, HpcLibrary):
+# requested_interval = 86400
+ requested_interval = 0
+ provides=[]
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+ HpcLibrary.__init__(self)
+
+ def call(self, **args):
+ logger.info("running garbage collector")
+ try:
+ self.gc_originservers()
+ self.gc_cdnprefixes()
+ self.gc_contentproviders()
+ self.gc_serviceproviders()
+ except:
+ traceback.print_exc()
+
+ def gc_onev(self, ps_class, ps_idField, onev_className, onev_idField):
+ # get the CMI's objects
+ onev_objs = self.client.onev.ListAll(onev_className)
+
+ # get the data model's objects,
+ ps_objs = ps_class.objects.filter(enacted__isnull=False)
+ ps_ids = [str(getattr(x,ps_idField,None)) for x in ps_objs]
+
+ # for each onev object, if it's id does not exist in a data model
+ # object, then delete it.
+ for onev_obj in onev_objs:
+ onev_id = onev_obj[onev_idField]
+ if str(onev_id) not in ps_ids:
+ logger.info("garbage collecting %s %s" % (onev_className, str(onev_id)))
+ self.client.onev.Delete(onev_className, onev_id)
+
+ def gc_originservers(self):
+ self.gc_onev(OriginServer, "origin_server_id", "OriginServer", "origin_server_id")
+
+ def gc_cdnprefixes(self):
+ self.gc_onev(CDNPrefix, "cdn_prefix_id", "CDNPrefix", "cdn_prefix_id")
+
+ def gc_contentproviders(self):
+ self.gc_onev(ContentProvider, "content_provider_id", "ContentProvider", "content_provider_id")
+
+ def gc_serviceproviders(self):
+ self.gc_onev(ServiceProvider, "service_provider_id", "ServiceProvider", "service_provider_id")
+
diff --git a/xos/synchronizers/hpc/steps/sync_cdnprefix.py b/xos/synchronizers/hpc/steps/sync_cdnprefix.py
new file mode 100644
index 0000000..7439633
--- /dev/null
+++ b/xos/synchronizers/hpc/steps/sync_cdnprefix.py
@@ -0,0 +1,101 @@
+import os
+import sys
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from core.models import Service
+from services.hpc.models import ServiceProvider, ContentProvider, CDNPrefix
+from xos.logger import Logger, logging
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+from hpclib import HpcLibrary
+
+logger = Logger(level=logging.INFO)
+
+class SyncCDNPrefix(SyncStep, HpcLibrary):
+ provides=[CDNPrefix]
+ observes=CDNPrefix
+ requested_interval=0
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+ HpcLibrary.__init__(self)
+
+ def filter_hpc_service(self, objs):
+ hpcService = self.get_hpc_service()
+
+ return [x for x in objs if x.contentProvider.serviceProvider.hpcService == hpcService]
+
+ def fetch_pending(self, deleted):
+ #self.consistency_check()
+
+ return self.filter_hpc_service(SyncStep.fetch_pending(self, deleted))
+
+ def consistency_check(self):
+ # set to true if something changed
+ result=False
+
+ # sanity check to make sure our PS objects have CMI objects behind them
+ all_p_ids = [x["cdn_prefix_id"] for x in self.client.onev.ListAll("CDNPrefix")]
+
+ all_p_ids = []
+ all_origins = {}
+ for x in self.client.onev.ListAll("CDNPrefix"):
+ id = x["cdn_prefix_id"]
+ all_p_ids.append(id)
+ all_origins[id] = x.get("default_origin_server", None)
+
+ for p in CDNPrefix.objects.all():
+ if (p.cdn_prefix_id is None):
+ continue
+
+ if (p.cdn_prefix_id not in all_p_ids):
+ logger.info("CDN Prefix %s was not found on CMI" % p.cdn_prefix_id)
+ p.cdn_prefix_id=None
+ p.save()
+ result = True
+
+ if (p.defaultOriginServer!=None) and (all_origins.get(p.cdn_prefix_id,None) != p.defaultOriginServer.url):
+ logger.info("CDN Prefix %s does not have default origin server on CMI" % str(p))
+ p.save() # this will set updated>enacted and force observer to re-sync
+ result = True
+
+ return result
+
+ def sync_record(self, cp):
+ logger.info("sync'ing cdn prefix %s" % str(cp))
+
+ if (not cp.contentProvider) or (not cp.contentProvider.content_provider_id):
+ raise Exception("CDN Prefix %s is linked to a contentProvider without an id" % str(cp))
+
+ cpid = cp.contentProvider.content_provider_id
+
+ cp_dict = {"service": "HyperCache", "enabled": cp.enabled, "content_provider_id": cpid, "cdn_prefix": cp.prefix}
+
+ if cp.defaultOriginServer and cp.defaultOriginServer.url:
+ if (not cp.defaultOriginServer.origin_server_id):
+ # It's probably a bad idea to try to set defaultOriginServer before
+ # we've crated defaultOriginServer.
+ raise Exception("cdn prefix %s is waiting for it's default origin server to get an id" % str(cp))
+
+ cp_dict["default_origin_server"] = cp.defaultOriginServer.url
+
+ #print cp_dict
+
+ if not cp.cdn_prefix_id:
+ id = self.client.onev.Create("CDNPrefix", cp_dict)
+ cp.cdn_prefix_id = id
+ else:
+ del cp_dict["content_provider_id"] # this can't be updated
+ del cp_dict["cdn_prefix"] # this can't be updated either
+ self.client.onev.Update("CDNPrefix", cp.cdn_prefix_id, cp_dict)
+
+ cp.save()
+
+ def delete_record(self, m):
+ if m.cdn_prefix_id is not None:
+ self.client.onev.Delete("CDNPrefix", m.cdn_prefix_id)
diff --git a/xos/synchronizers/hpc/steps/sync_contentprovider.py b/xos/synchronizers/hpc/steps/sync_contentprovider.py
new file mode 100644
index 0000000..c58cb5e
--- /dev/null
+++ b/xos/synchronizers/hpc/steps/sync_contentprovider.py
@@ -0,0 +1,78 @@
+import os
+import sys
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from core.models import Service
+from services.hpc.models import ServiceProvider, ContentProvider
+from xos.logger import Logger, logging
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+from hpclib import HpcLibrary
+
+logger = Logger(level=logging.INFO)
+
+class SyncContentProvider(SyncStep, HpcLibrary):
+ provides=[ContentProvider]
+ observes=ContentProvider
+ requested_interval=0
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+ HpcLibrary.__init__(self)
+
+ def filter_hpc_service(self, objs):
+ hpcService = self.get_hpc_service()
+
+ return [x for x in objs if x.serviceProvider.hpcService == hpcService]
+
+ def fetch_pending(self, deleted):
+ #self.consistency_check()
+
+ return self.filter_hpc_service(SyncStep.fetch_pending(self, deleted))
+
+ def consistency_check(self):
+ # set to true if something changed
+ result=False
+
+ # sanity check to make sure our PS objects have CMI objects behind them
+ all_cp_ids = [x["content_provider_id"] for x in self.client.onev.ListAll("ContentProvider")]
+ for cp in ContentProvider.objects.all():
+ if (cp.content_provider_id is not None) and (cp.content_provider_id not in all_cp_ids):
+ logger.info("Content provider %s was not found on CMI" % cp.content_provider_id)
+ cp.content_provider_id=None
+ cp.save()
+ result = True
+
+ return result
+
+ def sync_record(self, cp):
+ logger.info("sync'ing content provider %s" % str(cp))
+ account_name = self.make_account_name(cp.name)
+
+ if (not cp.serviceProvider) or (not cp.serviceProvider.service_provider_id):
+ raise Exception("ContentProvider %s is linked to a serviceProvider with no id" % str(cp))
+
+ spid = cp.serviceProvider.service_provider_id
+
+ cp_dict = {"account": account_name, "name": cp.name, "enabled": cp.enabled}
+
+ #print cp_dict
+
+ if not cp.content_provider_id:
+ cp_dict["service_provider_id"] = spid
+ id = self.client.onev.Create("ContentProvider", cp_dict)
+ cp.content_provider_id = id
+ else:
+ self.client.onev.Update("ContentProvider", cp.content_provider_id, cp_dict)
+
+ cp.save()
+
+ def delete_record(self, m):
+ if m.content_provider_id is not None:
+ self.client.onev.Delete("ContentProvider", m.content_provider_id)
+
diff --git a/xos/synchronizers/hpc/steps/sync_hpcservices.py b/xos/synchronizers/hpc/steps/sync_hpcservices.py
new file mode 100644
index 0000000..e49f93f
--- /dev/null
+++ b/xos/synchronizers/hpc/steps/sync_hpcservices.py
@@ -0,0 +1,43 @@
+import os
+import sys
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from core.models import Service
+from services.hpc.models import HpcService
+from services.requestrouter.models import RequestRouterService
+from xos.logger import Logger, logging
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+from hpclib import HpcLibrary
+
+logger = Logger(level=logging.INFO)
+
+class SyncHpcService(SyncStep, HpcLibrary):
+ provides=[HpcService]
+ observes=HpcService
+ requested_interval=0
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+ HpcLibrary.__init__(self)
+
+ def filter_hpc_service(self, objs):
+ hpcService = self.get_hpc_service()
+
+ return [x for x in objs if x == hpcService]
+
+ def fetch_pending(self, deleted):
+ # Looks like deletion is not supported for this object - Sapan
+ if (deleted):
+ return []
+ else:
+ return self.filter_hpc_service(HpcService.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)))
+
+ def sync_record(self, hpc_service):
+ logger.info("sync'ing hpc_service %s" % str(hpc_service))
+ hpc_service.save()
diff --git a/xos/synchronizers/hpc/steps/sync_originserver.py b/xos/synchronizers/hpc/steps/sync_originserver.py
new file mode 100644
index 0000000..0a675e1
--- /dev/null
+++ b/xos/synchronizers/hpc/steps/sync_originserver.py
@@ -0,0 +1,92 @@
+import os
+import sys
+import base64
+
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from core.models import Service
+from services.hpc.models import ServiceProvider, ContentProvider, CDNPrefix, OriginServer
+from xos.logger import Logger, logging
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+from hpclib import HpcLibrary
+
+logger = Logger(level=logging.INFO)
+
+class SyncOriginServer(SyncStep, HpcLibrary):
+ provides=[OriginServer]
+ observes=OriginServer
+ requested_interval=0
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+ HpcLibrary.__init__(self)
+
+ def filter_hpc_service(self, objs):
+ hpcService = self.get_hpc_service()
+
+ return [x for x in objs if x.contentProvider.serviceProvider.hpcService == hpcService]
+
+ def fetch_pending(self, deleted):
+ #self.consistency_check()
+
+ return self.filter_hpc_service(SyncStep.fetch_pending(self, deleted))
+
+ def consistency_check(self):
+ # set to true if something changed
+ result=False
+
+ # sanity check to make sure our PS objects have CMI objects behind them
+ all_ors_ids = [x["origin_server_id"] for x in self.client.onev.ListAll("OriginServer")]
+ for ors in OriginServer.objects.all():
+ if (ors.origin_server_id is not None) and (ors.origin_server_id not in all_ors_ids):
+ # we have an origin server ID, but it doesn't exist in the CMI
+ # something went wrong
+ # start over
+ logger.info("origin server %s was not found on CMI" % ors.origin_server_id)
+ ors.origin_server_id=None
+ ors.save()
+ result = True
+
+ return result
+
+ def sync_record(self, ors):
+ logger.info("sync'ing origin server %s" % str(ors))
+
+ if (not ors.contentProvider) or (not ors.contentProvider.content_provider_id):
+ raise Exception("Origin Server %s is linked to a contentProvider with no id" % str(ors))
+
+ cpid = ors.contentProvider.content_provider_id
+
+ # validation requires URL start with http://
+ url = ors.url
+ if not url.startswith("http://"):
+ url = "http://" + url
+
+ ors_dict = {"authenticated_content": ors.authenticated, "zone_redirects": ors.redirects, "content_provider_id": cpid, "url": url, "service_type": "HyperCache", "caching_type": "Optimistic", "description": ors.description}
+ if not ors_dict["description"]:
+ ors_dict["description"] = "blank"
+
+ #print os_dict
+
+ if not ors.origin_server_id:
+ id = self.client.onev.Create("OriginServer", ors_dict)
+ ors.origin_server_id = id
+ else:
+ self.client.onev.Update("OriginServer", ors.origin_server_id, ors_dict)
+
+ # ... something breaks (analytics) if the URL starts with http://, so we
+ # change it in cob after we added it via onev.
+ url = url[7:]
+ self.client.cob.UpdateContent(ors.origin_server_id, {"url": url})
+
+ ors.silent = True
+ ors.save()
+
+ def delete_record(self, m):
+ if m.origin_server_id is not None:
+ self.client.onev.Delete("OriginServer", m.origin_server_id)
diff --git a/xos/synchronizers/hpc/steps/sync_serviceprovider.py b/xos/synchronizers/hpc/steps/sync_serviceprovider.py
new file mode 100644
index 0000000..0cf145f
--- /dev/null
+++ b/xos/synchronizers/hpc/steps/sync_serviceprovider.py
@@ -0,0 +1,67 @@
+import os
+import sys
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from core.models import Service
+from services.hpc.models import ServiceProvider
+from xos.logger import Logger, logging
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+from hpclib import HpcLibrary
+
+logger = Logger(level=logging.INFO)
+
+class SyncServiceProvider(SyncStep, HpcLibrary):
+ provides=[ServiceProvider]
+ observes=ServiceProvider
+ requested_interval=0
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+ HpcLibrary.__init__(self)
+
+ def filter_hpc_service(self, objs):
+ hpcService = self.get_hpc_service()
+
+ return [x for x in objs if x.hpcService == hpcService]
+
+ def fetch_pending(self, deleted):
+ #self.consistency_check()
+
+ return self.filter_hpc_service(SyncStep.fetch_pending(self, deleted))
+
+ def consistency_check(self):
+ # set to true if something changed
+ result=False
+
+ # sanity check to make sure our PS objects have CMI objects behind them
+ all_sp_ids = [x["service_provider_id"] for x in self.client.onev.ListAll("ServiceProvider")]
+ for sp in ServiceProvider.objects.all():
+ if (sp.service_provider_id is not None) and (sp.service_provider_id not in all_sp_ids):
+ logger.info("Service provider %s was not found on CMI" % sp.service_provider_id)
+ sp.service_provider_id=None
+ sp.save()
+ result = True
+
+ return result
+
+ def sync_record(self, sp):
+ logger.info("sync'ing service provider %s" % str(sp))
+ account_name = self.make_account_name(sp.name)
+ sp_dict = {"account": account_name, "name": sp.name, "enabled": sp.enabled}
+ if not sp.service_provider_id:
+ id = self.client.onev.Create("ServiceProvider", sp_dict)
+ sp.service_provider_id = id
+ else:
+ self.client.onev.Update("ServiceProvider", sp.service_provider_id, sp_dict)
+
+ sp.save()
+
+ def delete_record(self, m):
+ if m.service_provider_id is not None:
+ self.client.onev.Delete("ServiceProvider", m.service_provider_id)
diff --git a/xos/synchronizers/hpc/steps/sync_sitemap.py b/xos/synchronizers/hpc/steps/sync_sitemap.py
new file mode 100644
index 0000000..885c616
--- /dev/null
+++ b/xos/synchronizers/hpc/steps/sync_sitemap.py
@@ -0,0 +1,118 @@
+import os
+import sys
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from core.models import Service
+from services.hpc.models import ServiceProvider, ContentProvider, CDNPrefix, SiteMap
+from xos.logger import Logger, logging
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+from hpclib import HpcLibrary
+
+logger = Logger(level=logging.INFO)
+
+class SyncSiteMap(SyncStep, HpcLibrary):
+ provides=[SiteMap]
+ observes=SiteMap
+ requested_interval=0
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+ HpcLibrary.__init__(self)
+
+ def filter_hpc_service(self, objs):
+ hpcService = self.get_hpc_service()
+
+ filtered_objs = []
+ for x in objs:
+ if ((x.hpcService == hpcService) or
+ ((x.serviceProvider != None) and (x.serviceProvider.hpcService == hpcService)) or
+ ((x.contentProvider != None) and (x.contentProvider.serviceProvider.hpcService == hpcService)) or
+ ((x.cdnPrefix!= None) and (x.cdnPrefix.contentProvider.serviceProvider.hpcService == hpcService))):
+ filtered_objs.append(x)
+
+ return filtered_objs
+
+ def fetch_pending(self, deleted):
+ return self.filter_hpc_service(SyncStep.fetch_pending(self, deleted))
+
+ def consistency_check(self):
+ # set to true if something changed
+ result=False
+
+ # sanity check to make sure our PS objects have CMI objects behind them
+ all_map_ids = [x["map_id"] for x in self.client.onev.ListAll("Map")]
+ for map in SiteMap.objects.all():
+ if (map.map_id is not None) and (map.map_id not in all_map_ids):
+ logger.info("Map %s was not found on CMI" % map.map_id)
+ map.map_id=None
+ map.save()
+ result = True
+
+ return result
+
+ def update_bind(self, map, map_dict, field_name, to_name, ids):
+ for id in ids:
+ if (not id in map_dict.get(field_name, [])):
+ print "Bind Map", map.map_id, "to", to_name, id
+ self.client.onev.Bind("Map", map.map_id, to_name, id)
+
+ for id in map_dict.get(field_name, []):
+ if (not id in ids):
+ print "Unbind Map", map.map_id, "from", to_name, id
+ self.client.onev.UnBind("map", map.map_id, to_name, id)
+
+ def sync_record(self, map):
+ logger.info("sync'ing SiteMap %s" % str(map))
+
+ if not map.map:
+ # no contents
+ return
+
+ content = map.map.read()
+
+ map_dict = {"name": map.name, "type": "site", "content": content}
+
+ cdn_prefix_ids=[]
+ service_provider_ids=[]
+ content_provider_ids=[]
+
+ if (map.contentProvider):
+ if not map.contentProvider.content_provider_id:
+ raise Exception("Map %s links to a contentProvider with no id" % map.name)
+ conent_provider_ids = [map.contentProvider.content_provider_id]
+
+ if (map.serviceProvider):
+ if not map.serviceProvider.service_provider_id:
+ raise Exception("Map %s links to a serviceProvider with no id" % map.name)
+ service_provider_ids = [map.serviceProvider.service_provider_id]
+
+ if (map.cdnPrefix):
+ if not map.cdnPrefix.cdn_prefix_id:
+ raise Exception("Map %s links to a cdnPrefix with no id" % map.name)
+ cdn_prefix_ids = [map.cdnPrefix.cdn_prefix_id]
+
+ if not map.map_id:
+ print "Create Map", map_dict
+ id = self.client.onev.Create("Map", map_dict)
+ map.map_id = id
+ else:
+ print "Update Map", map_dict
+ # these things we probably cannot update
+ del map_dict["name"]
+ self.client.onev.Update("Map", map.map_id, map_dict)
+
+ cmi_map_dict = self.client.onev.Read("Map", map.map_id)
+
+ self.update_bind(map, cmi_map_dict, "cdn_prefix_ids", "CDNPrefix", cdn_prefix_ids)
+
+ map.save()
+
+ def delete_record(self, m):
+ if m.map_id is not None:
+ self.client.onev.Delete("Map", m.map_id)
diff --git a/xos/observers/hpc/stop.sh b/xos/synchronizers/hpc/stop.sh
similarity index 100%
rename from xos/observers/hpc/stop.sh
rename to xos/synchronizers/hpc/stop.sh
diff --git a/xos/observers/hpc/supervisor/hpc-observer.conf b/xos/synchronizers/hpc/supervisor/hpc-observer.conf
similarity index 100%
rename from xos/observers/hpc/supervisor/hpc-observer.conf
rename to xos/synchronizers/hpc/supervisor/hpc-observer.conf
diff --git a/xos/observers/hpc/supervisor/hpc-watcher.conf b/xos/synchronizers/hpc/supervisor/hpc-watcher.conf
similarity index 100%
rename from xos/observers/hpc/supervisor/hpc-watcher.conf
rename to xos/synchronizers/hpc/supervisor/hpc-watcher.conf
diff --git a/xos/synchronizers/model_policy.py b/xos/synchronizers/model_policy.py
new file mode 100644
index 0000000..b8fdd5d
--- /dev/null
+++ b/xos/synchronizers/model_policy.py
@@ -0,0 +1,139 @@
+from django.db.models.signals import post_save
+from django.dispatch import receiver
+import pdb
+from generate.dependency_walker import *
+from synchronizers.openstack import model_policies
+from xos.logger import logger
+from datetime import datetime
+import time
+from core.models import *
+from django.db import reset_queries
+from django.db.transaction import atomic
+from django.db.models import F, Q
+
+modelPolicyEnabled = True
+bad_instances=[]
+
+def EnableModelPolicy(x):
+ global modelPolicyEnabled
+ modelPolicyEnabled = x
+
+def update_wp(d, o):
+ try:
+ save_fields = []
+ if (d.write_protect != o.write_protect):
+ d.write_protect = o.write_protect
+ save_fields.append('write_protect')
+ if (save_fields):
+ d.save(update_fields=save_fields)
+ except AttributeError,e:
+ raise e
+
+def update_dep(d, o):
+ try:
+ print 'Trying to update %s'%d
+ save_fields = []
+ if (d.updated < o.updated):
+ save_fields = ['updated']
+
+ if (save_fields):
+ d.save(update_fields=save_fields)
+ except AttributeError,e:
+ raise e
+ except Exception,e:
+ logger.info('Could not save %r. Exception: %r'%(d,e))
+
+def delete_if_inactive(d, o):
+ try:
+ d.delete()
+ print "Deleted %s (%s)"%(d,d.__class__.__name__)
+ except:
+ pass
+ return
+
+
+@atomic
+def execute_model_policy(instance, deleted):
+ # Automatic dirtying
+ if (instance in bad_instances):
+ return
+
+ # These are the models whose children get deleted when they are
+ delete_policy_models = ['Slice','Instance','Network']
+ sender_name = instance.__class__.__name__
+ policy_name = 'model_policy_%s'%sender_name
+ noargs = False
+
+ if (not deleted):
+ walk_inv_deps(update_dep, instance)
+ walk_deps(update_wp, instance)
+ elif (sender_name in delete_policy_models):
+ walk_inv_deps(delete_if_inactive, instance)
+
+
+
+ try:
+ policy_handler = getattr(model_policies, policy_name, None)
+ logger.error("POLICY HANDLER: %s %s" % (policy_name, policy_handler))
+ if policy_handler is not None:
+ if (deleted):
+ try:
+ policy_handler.handle_delete(instance)
+ except AttributeError:
+ pass
+ else:
+ policy_handler.handle(instance)
+ except:
+ logger.log_exc("Model Policy Error:")
+
+ try:
+ instance.policed=datetime.now()
+ instance.save(update_fields=['policed'])
+ except:
+ logging.error('Object %r is defective'%instance)
+ bad_instances.append(instance)
+
+def noop(o,p):
+ pass
+
+def run_policy():
+ while (True):
+ start = time.time()
+ run_policy_once()
+ if (time.time()-start<1):
+ time.sleep(1)
+
+def run_policy_once():
+ from core.models import Instance,Slice,Controller,Network,User,SlicePrivilege,Site,SitePrivilege,Image,ControllerSlice,ControllerUser,ControllerSite
+ models = [Controller, Site, SitePrivilege, Image, ControllerSlice, ControllerSite, ControllerUser, User, Slice, Network, Instance, SlicePrivilege]
+ objects = []
+ deleted_objects = []
+
+ for m in models:
+ res = m.objects.filter(Q(policed__lt=F('updated')) | Q(policed=None))
+ objects.extend(res)
+ res = m.deleted_objects.filter(Q(policed__lt=F('updated')) | Q(policed=None))
+ deleted_objects.extend(res)
+
+ for o in objects:
+ execute_model_policy(o, o.deleted)
+
+ for o in deleted_objects:
+ execute_model_policy(o, True)
+
+ # Reap non-sync'd models here
+ reaped = [Slice]
+
+ for m in reaped:
+ dobjs = m.deleted_objects.all()
+ for d in dobjs:
+ deps = walk_inv_deps(noop, d)
+ if (not deps):
+ print 'Purging object %r'%d
+ d.delete(purge=True)
+
+ try:
+ reset_queries()
+ except:
+ # this shouldn't happen, but in case it does, catch it...
+ logger.log_exc("exception in reset_queries")
diff --git a/xos/observers/monitoring_channel/files/docker.list b/xos/synchronizers/monitoring_channel/files/docker.list
similarity index 100%
rename from xos/observers/monitoring_channel/files/docker.list
rename to xos/synchronizers/monitoring_channel/files/docker.list
diff --git a/xos/observers/monitoring_channel/files/vm-resolv.conf b/xos/synchronizers/monitoring_channel/files/vm-resolv.conf
similarity index 100%
rename from xos/observers/monitoring_channel/files/vm-resolv.conf
rename to xos/synchronizers/monitoring_channel/files/vm-resolv.conf
diff --git a/xos/observers/monitoring_channel/model-deps b/xos/synchronizers/monitoring_channel/model-deps
similarity index 100%
rename from xos/observers/monitoring_channel/model-deps
rename to xos/synchronizers/monitoring_channel/model-deps
diff --git a/xos/synchronizers/monitoring_channel/monitoring_channel_synchronizer.py b/xos/synchronizers/monitoring_channel/monitoring_channel_synchronizer.py
new file mode 100755
index 0000000..84bec4f
--- /dev/null
+++ b/xos/synchronizers/monitoring_channel/monitoring_channel_synchronizer.py
@@ -0,0 +1,11 @@
+#!/usr/bin/env python
+
+# This imports and runs ../../xos-observer.py
+
+import importlib
+import os
+import sys
+observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../../synchronizers/base")
+sys.path.append(observer_path)
+mod = importlib.import_module("xos-synchronizer")
+mod.main()
diff --git a/xos/synchronizers/monitoring_channel/monitoring_channel_synchronizer_config b/xos/synchronizers/monitoring_channel/monitoring_channel_synchronizer_config
new file mode 100644
index 0000000..8c6578f
--- /dev/null
+++ b/xos/synchronizers/monitoring_channel/monitoring_channel_synchronizer_config
@@ -0,0 +1,41 @@
+
+[plc]
+name=plc
+deployment=VICCI
+
+[db]
+name=xos
+user=postgres
+password=password
+host=localhost
+port=5432
+
+[api]
+host=128.112.171.237
+port=8000
+ssl_key=None
+ssl_cert=None
+ca_ssl_cert=None
+ratelimit_enabled=0
+omf_enabled=0
+mail_support_address=support@localhost
+nova_enabled=True
+
+[observer]
+name=monitoring_channel
+dependency_graph=/opt/xos/synchronizers/monitoring_channel/model-deps
+steps_dir=/opt/xos/synchronizers/monitoring_channel/steps
+sys_dir=/opt/xos/synchronizers/monitoring_channel/sys
+deleters_dir=/opt/xos/synchronizers/monitoring_channel/deleters
+log_file=console
+driver=None
+pretend=False
+backoff_disabled=True
+save_ansible_output=True
+# set proxy_ssh to false on cloudlab
+proxy_ssh=False
+full_setup=True
+
+[feefie]
+client_id='vicci_dev_central'
+user_id='pl'
diff --git a/xos/synchronizers/monitoring_channel/steps/sync_monitoringchannel.py b/xos/synchronizers/monitoring_channel/steps/sync_monitoringchannel.py
new file mode 100644
index 0000000..2e4eca8
--- /dev/null
+++ b/xos/synchronizers/monitoring_channel/steps/sync_monitoringchannel.py
@@ -0,0 +1,76 @@
+import hashlib
+import os
+import socket
+import sys
+import base64
+import time
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from synchronizers.base.ansible import run_template_ssh
+from synchronizers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
+from core.models import Service, Slice
+from services.ceilometer.models import MonitoringChannel
+from xos.logger import Logger, logging
+
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+logger = Logger(level=logging.INFO)
+
+class SyncMonitoringChannel(SyncInstanceUsingAnsible):
+ provides=[MonitoringChannel]
+ observes=MonitoringChannel
+ requested_interval=0
+ template_name = "sync_monitoringchannel.yaml"
+ service_key_name = "/opt/xos/observers/monitoring_channel/monitoring_channel_private_key"
+
+ def __init__(self, *args, **kwargs):
+ super(SyncMonitoringChannel, self).__init__(*args, **kwargs)
+
+ def fetch_pending(self, deleted):
+ if (not deleted):
+ objs = MonitoringChannel.get_tenant_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
+ else:
+ objs = MonitoringChannel.get_deleted_tenant_objects()
+
+ return objs
+
+ def get_extra_attributes(self, o):
+ # This is a place to include extra attributes. In the case of Monitoring Channel, we need to know
+ # 1) Allowed tenant ids
+ # 2) Ceilometer API service endpoint URL if running externally
+ # 3) Credentials to access Ceilometer API service
+
+ instance = self.get_instance(o)
+
+ try:
+ full_setup = Config().observer_full_setup
+ except:
+ full_setup = True
+
+ fields = {"unique_id": o.id,
+ "allowed_tenant_ids": o.tenant_list,
+ "auth_url":instance.controller.auth_url,
+ "admin_user":instance.controller.admin_user,
+ "admin_password":instance.controller.admin_password,
+ "admin_tenant":instance.controller.admin_tenant,
+ "full_setup": full_setup}
+
+ return fields
+
+ def run_playbook(self, o, fields):
+ #ansible_hash = hashlib.md5(repr(sorted(fields.items()))).hexdigest()
+ #quick_update = (o.last_ansible_hash == ansible_hash)
+
+ #if quick_update:
+ # logger.info("quick_update triggered; skipping ansible recipe")
+ #else:
+ super(SyncMonitoringChannel, self).run_playbook(o, fields)
+
+ #o.last_ansible_hash = ansible_hash
+
+ def map_delete_inputs(self, o):
+ fields = {"unique_id": o.id,
+ "delete": True}
+ return fields
diff --git a/xos/synchronizers/monitoring_channel/steps/sync_monitoringchannel.yaml b/xos/synchronizers/monitoring_channel/steps/sync_monitoringchannel.yaml
new file mode 100644
index 0000000..6c5fc8c
--- /dev/null
+++ b/xos/synchronizers/monitoring_channel/steps/sync_monitoringchannel.yaml
@@ -0,0 +1,104 @@
+---
+- hosts: {{ instance_name }}
+ gather_facts: False
+ connection: ssh
+ user: ubuntu
+ sudo: yes
+ vars:
+ unique_id: {{ unique_id }}
+ auth_url: {{ auth_url }}
+ admin_user: {{ admin_user }}
+ admin_password: {{ admin_password }}
+ admin_tenant: {{ admin_tenant }}
+ shared_lan_ip: {{ private_ip }}
+ shared_lan_mac: {{ private_mac }}
+ headnode_flat_lan_ip: {{ rabbit_host }}
+ ceilometer_client_acess_ip: {{ ceilometer_ip }}
+ ceilometer_client_acess_mac: {{ ceilometer_mac }}
+ ceilometer_host_port: {{ ceilometer_port }}
+ allowed_tenant_ids:
+ {% for allowed_tenant_id in allowed_tenant_ids %}
+ - {{ allowed_tenant_id }}
+ {% endfor %}
+
+ tasks:
+{% if delete %}
+ - name: Remove tenant
+# FIXME: Adding dummy template action to avoid "action attribute missing in task" error
+ template: src=/opt/xos/observers/monitoring_channel/templates/ceilometer_proxy_config.j2 dest=/usr/local/share/monitoring-channel-{{ unique_id }}_ceilometer_proxy_config mode=0777
+ notify:
+ - stop monitoring-channel
+ - remove container
+{% else %}
+{% if full_setup %}
+ - name: Docker repository
+ copy: src=/opt/xos/observers/monitoring_channel/files/docker.list
+ dest=/etc/apt/sources.list.d/docker.list
+
+ - name: Import the repository key
+ apt_key: keyserver=keyserver.ubuntu.com id=36A1D7869245C8950F966E92D8576A8BA88D21E9
+
+ - name: install Docker
+ apt: name=lxc-docker state=present update_cache=yes
+
+ - name: install python-setuptools
+ apt: name=python-setuptools state=present
+
+ - name: install pip
+ easy_install: name=pip
+
+ - name: install docker-py
+ pip: name=docker-py version=0.5.3
+
+ - name: install Pipework
+ get_url: url=https://raw.githubusercontent.com/jpetazzo/pipework/master/pipework
+ dest=/usr/local/bin/pipework
+ mode=0755
+
+ - name: Disable resolvconf service
+ shell: service resolvconf stop
+ shell: echo manual > /etc/init/resolvconf.override
+ shell: rm -f /etc/resolv.conf
+
+ - name: Install resolv.conf
+ copy: src=/opt/xos/observers/monitoring_channel/files/vm-resolv.conf
+ dest=/etc/resolv.conf
+{% endif %}
+
+ - name: ceilometer proxy config
+ template: src=/opt/xos/observers/monitoring_channel/templates/ceilometer_proxy_config.j2 dest=/usr/local/share/monitoring-channel-{{ unique_id }}_ceilometer_proxy_config mode=0777
+ notify:
+# - restart monitoring-channel
+ - stop monitoring-channel
+ - remove container
+ - start monitoring-channel
+
+ - name: Monitoring channel upstart
+ template: src=/opt/xos/observers/monitoring_channel/templates/monitoring-channel.conf.j2 dest=/etc/init/monitoring-channel-{{ unique_id }}.conf
+
+ - name: Monitoring channel startup script
+ template: src=/opt/xos/observers/monitoring_channel/templates/start-monitoring-channel.sh.j2 dest=/usr/local/sbin/start-monitoring-channel-{{ unique_id }}.sh mode=0755
+ notify:
+# - restart monitoring-channel
+ - stop monitoring-channel
+ - remove container
+ - start monitoring-channel
+
+# These are samples, not necessary for correct function of demo
+
+ - name: Make sure Monitoring channel service is running
+ service: name=monitoring-channel-{{ unique_id }} state=started
+{% endif %}
+
+ handlers:
+ - name: restart monitoring-channel
+ shell: service monitoring-channel-{{ unique_id }} stop; sleep 1; service monitoring-channel-{{ unique_id }} start
+
+ - name: stop monitoring-channel
+ service: name=monitoring-channel-{{ unique_id }} state=stopped
+
+ - name: remove container
+ docker: name=monitoring-channel-{{ unique_id }} state=absent image=monitoring-channel
+
+ - name: start monitoring-channel
+ service: name=monitoring-channel-{{ unique_id }} state=started
diff --git a/xos/observers/monitoring_channel/supervisor/monitoring_channel_observer.conf b/xos/synchronizers/monitoring_channel/supervisor/monitoring_channel_observer.conf
similarity index 100%
rename from xos/observers/monitoring_channel/supervisor/monitoring_channel_observer.conf
rename to xos/synchronizers/monitoring_channel/supervisor/monitoring_channel_observer.conf
diff --git a/xos/observers/monitoring_channel/templates/Dockerfile.monitoring_channel b/xos/synchronizers/monitoring_channel/templates/Dockerfile.monitoring_channel
similarity index 100%
rename from xos/observers/monitoring_channel/templates/Dockerfile.monitoring_channel
rename to xos/synchronizers/monitoring_channel/templates/Dockerfile.monitoring_channel
diff --git a/xos/observers/monitoring_channel/templates/ceilometer_proxy_config.j2 b/xos/synchronizers/monitoring_channel/templates/ceilometer_proxy_config.j2
similarity index 100%
rename from xos/observers/monitoring_channel/templates/ceilometer_proxy_config.j2
rename to xos/synchronizers/monitoring_channel/templates/ceilometer_proxy_config.j2
diff --git a/xos/observers/monitoring_channel/templates/ceilometer_proxy_server.py b/xos/synchronizers/monitoring_channel/templates/ceilometer_proxy_server.py
similarity index 100%
rename from xos/observers/monitoring_channel/templates/ceilometer_proxy_server.py
rename to xos/synchronizers/monitoring_channel/templates/ceilometer_proxy_server.py
diff --git a/xos/observers/monitoring_channel/templates/monitoring-channel.conf.j2 b/xos/synchronizers/monitoring_channel/templates/monitoring-channel.conf.j2
similarity index 100%
rename from xos/observers/monitoring_channel/templates/monitoring-channel.conf.j2
rename to xos/synchronizers/monitoring_channel/templates/monitoring-channel.conf.j2
diff --git a/xos/observers/monitoring_channel/templates/start-monitoring-channel.sh.j2 b/xos/synchronizers/monitoring_channel/templates/start-monitoring-channel.sh.j2
similarity index 100%
rename from xos/observers/monitoring_channel/templates/start-monitoring-channel.sh.j2
rename to xos/synchronizers/monitoring_channel/templates/start-monitoring-channel.sh.j2
diff --git a/xos/observers/monitoring_channel/templates/start_ceilometer_proxy b/xos/synchronizers/monitoring_channel/templates/start_ceilometer_proxy
similarity index 100%
rename from xos/observers/monitoring_channel/templates/start_ceilometer_proxy
rename to xos/synchronizers/monitoring_channel/templates/start_ceilometer_proxy
diff --git a/xos/observers/onos/model-deps b/xos/synchronizers/onos/model-deps
similarity index 100%
rename from xos/observers/onos/model-deps
rename to xos/synchronizers/onos/model-deps
diff --git a/xos/synchronizers/onos/onos-synchronizer.py b/xos/synchronizers/onos/onos-synchronizer.py
new file mode 100755
index 0000000..84bec4f
--- /dev/null
+++ b/xos/synchronizers/onos/onos-synchronizer.py
@@ -0,0 +1,11 @@
+#!/usr/bin/env python
+
+# This imports and runs ../../xos-observer.py
+
+import importlib
+import os
+import sys
+observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../../synchronizers/base")
+sys.path.append(observer_path)
+mod = importlib.import_module("xos-synchronizer")
+mod.main()
diff --git a/xos/synchronizers/onos/onos_synchronizer_config b/xos/synchronizers/onos/onos_synchronizer_config
new file mode 100644
index 0000000..c6ceece
--- /dev/null
+++ b/xos/synchronizers/onos/onos_synchronizer_config
@@ -0,0 +1,41 @@
+
+[plc]
+name=plc
+deployment=VICCI
+
+[db]
+name=xos
+user=postgres
+password=password
+host=localhost
+port=5432
+
+[api]
+host=128.112.171.237
+port=8000
+ssl_key=None
+ssl_cert=None
+ca_ssl_cert=None
+ratelimit_enabled=0
+omf_enabled=0
+mail_support_address=support@localhost
+nova_enabled=True
+
+[observer]
+name=onos
+dependency_graph=/opt/xos/synchronizers/onos/model-deps
+steps_dir=/opt/xos/synchronizers/onos/steps
+sys_dir=/opt/xos/synchronizers/onos/sys
+deleters_dir=/opt/xos/synchronizers/onos/deleters
+log_file=console
+driver=None
+pretend=False
+backoff_disabled=True
+save_ansible_output=True
+# set proxy_ssh to false on cloudlab
+proxy_ssh=False
+full_setup=True
+
+[feefie]
+client_id='vicci_dev_central'
+user_id='pl'
diff --git a/xos/observers/onos/run.sh b/xos/synchronizers/onos/run.sh
similarity index 100%
rename from xos/observers/onos/run.sh
rename to xos/synchronizers/onos/run.sh
diff --git a/xos/synchronizers/onos/scripts/dockerip.sh b/xos/synchronizers/onos/scripts/dockerip.sh
new file mode 100644
index 0000000..732c3fe
--- /dev/null
+++ b/xos/synchronizers/onos/scripts/dockerip.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+
+MODE=`docker inspect --format '{{ .HostConfig.NetworkMode }}' $1 | tr -d '\n' | tr -d '\r'`
+if [[ "$MODE" == "host" ]]; then
+ echo -n "127.0.0.1"
+else
+ docker inspect --format '{{ .NetworkSettings.IPAddress }}' $1 | tr -d '\n' | tr -d '\r'
+fi
+
diff --git a/xos/observers/onos/start.sh b/xos/synchronizers/onos/start.sh
similarity index 100%
rename from xos/observers/onos/start.sh
rename to xos/synchronizers/onos/start.sh
diff --git a/xos/synchronizers/onos/steps/sync_onosapp.py b/xos/synchronizers/onos/steps/sync_onosapp.py
new file mode 100644
index 0000000..91eec44
--- /dev/null
+++ b/xos/synchronizers/onos/steps/sync_onosapp.py
@@ -0,0 +1,167 @@
+import hashlib
+import os
+import socket
+import socket
+import sys
+import base64
+import time
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from synchronizers.base.ansible import run_template_ssh
+from synchronizers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
+from core.models import Service, Slice
+from services.onos.models import ONOSService, ONOSApp
+from xos.logger import Logger, logging
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+logger = Logger(level=logging.INFO)
+
+class SyncONOSApp(SyncInstanceUsingAnsible):
+ provides=[ONOSApp]
+ observes=ONOSApp
+ requested_interval=0
+ template_name = "sync_onosapp.yaml"
+ service_key_name = "/opt/xos/observers/onos/onos_key"
+
+ def __init__(self, *args, **kwargs):
+ super(SyncONOSApp, self).__init__(*args, **kwargs)
+
+ def fetch_pending(self, deleted):
+ if (not deleted):
+ objs = ONOSApp.get_tenant_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
+ else:
+ objs = ONOSApp.get_deleted_tenant_objects()
+
+ return objs
+
+ def get_instance(self, o):
+ # We assume the ONOS service owns a slice, so pick one of the instances
+ # inside that slice to sync to.
+
+ serv = self.get_onos_service(o)
+
+ if serv.use_external_host:
+ return serv.use_external_host
+
+ if serv.slices.exists():
+ slice = serv.slices.all()[0]
+ if slice.instances.exists():
+ return slice.instances.all()[0]
+
+ return None
+
+ def get_onos_service(self, o):
+ if not o.provider_service:
+ return None
+
+ onoses = ONOSService.get_service_objects().filter(id=o.provider_service.id)
+ if not onoses:
+ return None
+
+ return onoses[0]
+
+ def get_files_dir(self, o):
+ if not hasattr(Config(), "observer_steps_dir"):
+ # make steps_dir mandatory; there's no valid reason for it to not
+ # be defined.
+ raise Exception("observer_steps_dir is not defined in config file")
+
+ step_dir = Config().observer_steps_dir
+
+ return os.path.join(step_dir, "..", "files", str(self.get_onos_service(o).id), o.name)
+
+ def get_cluster_configuration(self, o):
+ instance = self.get_instance(o)
+ if not instance:
+ raise "No instance for ONOS App"
+ node_ips = [socket.gethostbyname(instance.node.name)]
+
+ ipPrefix = ".".join(node_ips[0].split(".")[:3]) + ".*"
+ result = '{ "nodes": ['
+ result = result + ",".join(['{ "ip": "%s"}' % ip for ip in node_ips])
+ result = result + '], "ipPrefix": "%s"}' % ipPrefix
+ return result
+
+
+ def write_configs(self, o):
+ o.config_fns = []
+ o.rest_configs = []
+ o.files_dir = self.get_files_dir(o)
+
+ if not os.path.exists(o.files_dir):
+ os.makedirs(o.files_dir)
+
+ # Combine the service attributes with the tenant attributes. Tenant
+ # attribute can override service attributes.
+ attrs = o.provider_service.serviceattribute_dict
+ attrs.update(o.tenantattribute_dict)
+
+ ordered_attrs = attrs.keys()
+
+ o.early_rest_configs=[]
+ if ("cordvtn" in o.dependencies):
+ # For VTN, since it's running in a docker host container, we need
+ # to make sure it configures the cluster using the right ip addresses.
+ # NOTE: rest_onos/v1/cluster/configuration/ will reboot the cluster and
+ # must go first.
+ name="rest_onos/v1/cluster/configuration/"
+ value= self.get_cluster_configuration(o)
+ fn = name[5:].replace("/","_")
+ endpoint = name[5:]
+ file(os.path.join(o.files_dir, fn),"w").write(" " +value)
+ o.early_rest_configs.append( {"endpoint": endpoint, "fn": fn} )
+
+ for name in attrs.keys():
+ value = attrs[name]
+ if name.startswith("config_"):
+ fn = name[7:] # .replace("_json",".json")
+ o.config_fns.append(fn)
+ file(os.path.join(o.files_dir, fn),"w").write(value)
+ if name.startswith("rest_"):
+ fn = name[5:].replace("/","_")
+ endpoint = name[5:]
+ # Ansible goes out of it's way to make our life difficult. If
+ # 'lookup' sees a file that it thinks contains json, then it'll
+ # insist on parsing and return a json object. We just want
+ # a string, so prepend a space and then strip the space off
+ # later.
+ file(os.path.join(o.files_dir, fn),"w").write(" " +value)
+ o.rest_configs.append( {"endpoint": endpoint, "fn": fn} )
+
+ def prepare_record(self, o):
+ self.write_configs(o)
+
+ def get_extra_attributes(self, o):
+ instance = self.get_instance(o)
+
+ fields={}
+ fields["files_dir"] = o.files_dir
+ fields["appname"] = o.name
+ fields["nat_ip"] = instance.get_ssh_ip()
+ fields["config_fns"] = o.config_fns
+ fields["rest_configs"] = o.rest_configs
+ fields["early_rest_configs"] = o.early_rest_configs
+ if o.dependencies:
+ fields["dependencies"] = [x.strip() for x in o.dependencies.split(",")]
+ else:
+ fields["dependencies"] = []
+
+ if (instance.isolation=="container"):
+ fields["ONOS_container"] = "%s-%s" % (instance.slice.name, str(instance.id))
+ else:
+ fields["ONOS_container"] = "ONOS"
+ return fields
+
+ def sync_fields(self, o, fields):
+ # the super causes the playbook to be run
+ super(SyncONOSApp, self).sync_fields(o, fields)
+
+ def run_playbook(self, o, fields):
+ super(SyncONOSApp, self).run_playbook(o, fields)
+
+ def delete_record(self, m):
+ pass
diff --git a/xos/synchronizers/onos/steps/sync_onosapp.yaml b/xos/synchronizers/onos/steps/sync_onosapp.yaml
new file mode 100644
index 0000000..a03368b
--- /dev/null
+++ b/xos/synchronizers/onos/steps/sync_onosapp.yaml
@@ -0,0 +1,114 @@
+---
+- hosts: {{ instance_name }}
+ gather_facts: False
+ connection: ssh
+ user: {{ username }}
+ sudo: yes
+ vars:
+ appname: {{ appname }}
+ dependencies: {{ dependencies }}
+{% if rest_configs %}
+ rest_configs:
+{% for rest_config in rest_configs %}
+ - endpoint: {{ rest_config.endpoint }}
+ body: "{{ '{{' }} lookup('file', '{{ files_dir }}/{{ rest_config.fn }}') {{ '}}' }}"
+{% endfor %}
+{% endif %}
+{% if early_rest_configs %}
+ early_rest_configs:
+{% for early_rest_config in early_rest_configs %}
+ - endpoint: {{ early_rest_config.endpoint }}
+ body: "{{ '{{' }} lookup('file', '{{ files_dir }}/{{ early_rest_config.fn }}') {{ '}}' }}"
+{% endfor %}
+{% endif %}
+
+ tasks:
+
+ - name: Get Docker IP
+ script: /opt/xos/observers/onos/scripts/dockerip.sh {{ ONOS_container }}
+ register: onosaddr
+
+ - name: Wait for ONOS to come up
+ wait_for:
+ host={{ '{{' }} onosaddr.stdout {{ '}}' }}
+ port={{ '{{' }} item {{ '}}' }}
+ state=present
+ with_items:
+ - 8101
+ - 8181
+ - 9876
+
+ - name: Config file directory
+ file:
+ path=/home/ubuntu/{{ appname }}/
+ state=directory
+
+{% if config_fns %}
+ - name: Copy over configuration files
+ copy:
+ src={{ files_dir }}/{{ '{{' }} item {{ '}}' }}
+ dest=/home/ubuntu/{{ appname }}/{{ '{{' }} item {{ '}}' }}
+ with_items:
+ {% for config_fn in config_fns %}
+ - {{ config_fn }}
+ {% endfor %}
+
+ - name: Make sure config directory exists
+ shell: docker exec {{ ONOS_container }} mkdir -p /root/onos/config/
+ sudo: yes
+
+ - name: Copy config files into container
+ shell: docker cp {{ appname }}/{{ '{{' }} item {{ '}}' }} {{ ONOS_container }}:/root/onos/config/
+ sudo: yes
+ with_items:
+ {% for config_fn in config_fns %}
+ - {{ config_fn }}
+ {% endfor %}
+{% endif %}
+
+ # Don't know how to check for this condition, just wait
+ - name: Wait for ONOS to install the apps
+ wait_for: timeout=15
+
+{% if early_rest_configs %}
+ - name: Add ONOS early configuration values
+ uri:
+ url: http://{{ '{{' }} onosaddr.stdout {{ '}}' }}:8181/{{ '{{' }} item.endpoint {{ '}}' }}
+ body: "{{ '{{' }} item.body {{ '}}' }}"
+ body_format: raw
+ method: POST
+ user: karaf
+ password: karaf
+ with_items: "early_rest_configs"
+
+ # Don't know how to check for this condition, just wait
+ - name: Wait for ONOS to restart
+ wait_for: timeout=15
+{% endif %}
+
+{% if dependencies %}
+ - name: Add dependencies to ONOS
+ uri:
+ url: http://{{ '{{' }} onosaddr.stdout {{ '}}' }}:8181/onos/v1/applications/{{ '{{' }} item {{ '}}' }}/active
+ method: POST
+ user: karaf
+ password: karaf
+ with_items:
+ {% for dependency in dependencies %}
+ - {{ dependency }}
+ {% endfor %}
+{% endif %}
+
+{% if rest_configs %}
+# Do this after services have been activated, or it will cause an exception.
+# vOLT will re-read its net config; vbng may not.
+ - name: Add ONOS configuration values
+ uri:
+ url: http://{{ '{{' }} onosaddr.stdout {{ '}}' }}:8181/{{ '{{' }} item.endpoint {{ '}}' }} #http://localhost:8181/onos/v1/network/configuration/
+ body: "{{ '{{' }} item.body {{ '}}' }}"
+ body_format: raw
+ method: POST
+ user: karaf
+ password: karaf
+ with_items: "rest_configs"
+{% endif %}
diff --git a/xos/synchronizers/onos/steps/sync_onosservice.py b/xos/synchronizers/onos/steps/sync_onosservice.py
new file mode 100644
index 0000000..0474dc6
--- /dev/null
+++ b/xos/synchronizers/onos/steps/sync_onosservice.py
@@ -0,0 +1,77 @@
+import hashlib
+import os
+import socket
+import sys
+import base64
+import time
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from synchronizers.base.ansible import run_template_ssh
+from synchronizers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
+from core.models import Service, Slice
+from services.onos.models import ONOSService, ONOSApp
+from xos.logger import Logger, logging
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+logger = Logger(level=logging.INFO)
+
+class SyncONOSService(SyncInstanceUsingAnsible):
+ provides=[ONOSService]
+ observes=ONOSService
+ requested_interval=0
+ template_name = "sync_onosservice.yaml"
+ service_key_name = "/opt/xos/observers/onos/onos_key"
+
+ def __init__(self, *args, **kwargs):
+ super(SyncONOSService, self).__init__(*args, **kwargs)
+
+ def fetch_pending(self, deleted):
+ if (not deleted):
+ objs = ONOSService.get_service_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
+ else:
+ objs = ONOSService.get_deleted_service_objects()
+
+ return objs
+
+ def get_instance(self, o):
+ # We assume the ONOS service owns a slice, so pick one of the instances
+ # inside that slice to sync to.
+
+ serv = o
+
+ if serv.use_external_host:
+ return serv.use_external_host
+
+ if serv.slices.exists():
+ slice = serv.slices.all()[0]
+ if slice.instances.exists():
+ return slice.instances.all()[0]
+
+ return None
+
+ def get_extra_attributes(self, o):
+ fields={}
+ fields["instance_hostname"] = self.get_instance(o).instance_name.replace("_","-")
+ fields["appname"] = o.name
+ fields["nat_ip"] = self.get_instance(o).get_ssh_ip()
+ fields["ONOS_container"] = "ONOS"
+ return fields
+
+ def sync_fields(self, o, fields):
+ # the super causes the playbook to be run
+ super(SyncONOSService, self).sync_fields(o, fields)
+
+ def run_playbook(self, o, fields):
+ instance = self.get_instance(o)
+ if (instance.isolation=="container"):
+ # If the instance is already a container, then we don't need to
+ # install ONOS.
+ return
+ super(SyncONOSService, self).run_playbook(o, fields)
+
+ def delete_record(self, m):
+ pass
diff --git a/xos/observers/onos/steps/sync_onosservice.yaml b/xos/synchronizers/onos/steps/sync_onosservice.yaml
similarity index 100%
rename from xos/observers/onos/steps/sync_onosservice.yaml
rename to xos/synchronizers/onos/steps/sync_onosservice.yaml
diff --git a/xos/observers/onos/stop.sh b/xos/synchronizers/onos/stop.sh
similarity index 100%
rename from xos/observers/onos/stop.sh
rename to xos/synchronizers/onos/stop.sh
diff --git a/xos/synchronizers/onos/supervisor/onos-observer.conf b/xos/synchronizers/onos/supervisor/onos-observer.conf
new file mode 100644
index 0000000..36e00d9
--- /dev/null
+++ b/xos/synchronizers/onos/supervisor/onos-observer.conf
@@ -0,0 +1,9 @@
+[supervisord]
+logfile=/var/log/supervisord.log ; (main log file;default $CWD/supervisord.log)
+pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
+nodaemon=true
+
+[program:synchronizer]
+command=python /opt/xos/observers/onos/onos-observer.py -C /opt/xos/observers/onos/onos_observer_config
+stderr_logfile=/var/log/supervisor/synchronizer.err.log
+stdout_logfile=/var/log/supervisor/synchronizer.out.log
diff --git a/xos/openstack_observer/__init__.py b/xos/synchronizers/openstack/__init__.py
similarity index 100%
copy from xos/openstack_observer/__init__.py
copy to xos/synchronizers/openstack/__init__.py
diff --git a/xos/synchronizers/openstack/ansible.py b/xos/synchronizers/openstack/ansible.py
new file mode 100644
index 0000000..fda2300
--- /dev/null
+++ b/xos/synchronizers/openstack/ansible.py
@@ -0,0 +1,211 @@
+#!/usr/bin/env python
+import jinja2
+import tempfile
+import os
+import json
+import pdb
+import string
+import random
+import re
+import traceback
+import subprocess
+from xos.config import Config, XOS_DIR
+from xos.logger import observer_logger
+
+try:
+ step_dir = Config().observer_steps_dir
+ sys_dir = Config().observer_sys_dir
+except:
+ step_dir = XOS_DIR + '/observer/steps'
+ sys_dir = '/opt/opencloud'
+
+os_template_loader = jinja2.FileSystemLoader( searchpath=step_dir)
+os_template_env = jinja2.Environment(loader=os_template_loader)
+
+def parse_output(msg):
+ lines = msg.splitlines()
+ results = []
+
+ observer_logger.info(msg)
+
+ for l in lines:
+ magic_str = 'ok: [127.0.0.1] => '
+ magic_str2 = 'changed: [127.0.0.1] => '
+ if (l.startswith(magic_str)):
+ w = len(magic_str)
+ str = l[w:]
+ d = json.loads(str)
+ results.append(d)
+ elif (l.startswith(magic_str2)):
+ w = len(magic_str2)
+ str = l[w:]
+ d = json.loads(str)
+ results.append(d)
+
+
+ return results
+
+def parse_unreachable(msg):
+ total_unreachable=0
+ total_failed=0
+ for l in msg.splitlines():
+ x = re.findall('ok=([0-9]+).*changed=([0-9]+).*unreachable=([0-9]+).*failed=([0-9]+)', l)
+ if x:
+ (ok, changed, unreachable, failed) = x[0]
+ ok=int(ok)
+ changed=int(changed)
+ unreachable=int(unreachable)
+ failed=int(failed)
+
+ total_unreachable += unreachable
+ total_failed += failed
+ return {'unreachable':total_unreachable,'failed':total_failed}
+
+
+def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
+ return ''.join(random.choice(chars) for _ in range(size))
+
+def shellquote(s):
+ return "'" + s.replace("'", "'\\''") + "'"
+
+def get_playbook_fn(opts, path):
+ if not opts.get("ansible_tag", None):
+ # if no ansible_tag is in the options, then generate a unique one
+ objname= id_generator()
+ opts = opts.copy()
+ opts["ansible_tag"] = objname
+
+ objname = opts["ansible_tag"]
+
+ os.system('mkdir -p %s' % os.path.join(sys_dir, path))
+ return (opts, os.path.join(sys_dir,path,objname))
+
+def run_template(name, opts, path='', expected_num=None, ansible_config=None, ansible_hosts=None, run_ansible_script=None):
+ template = os_template_env.get_template(name)
+ buffer = template.render(opts)
+
+ (opts, fqp) = get_playbook_fn(opts, path)
+
+ f = open(fqp,'w')
+ f.write(buffer)
+ f.flush()
+
+ # This is messy -- there's no way to specify ansible config file from
+ # the command line, but we can specify it using the environment.
+ env = os.environ.copy()
+ if ansible_config:
+ env["ANSIBLE_CONFIG"] = ansible_config
+ if ansible_hosts:
+ env["ANSIBLE_HOSTS"] = ansible_hosts
+
+ if (not Config().observer_pretend):
+ if not run_ansible_script:
+ run_ansible_script = os.path.join(XOS_DIR, "observer/run_ansible")
+
+ process = subprocess.Popen("%s %s" % (run_ansible_script, shellquote(fqp)), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
+ msg = process.stdout.read()
+ err_msg = process.stderr.read()
+
+ if getattr(Config(), "observer_save_ansible_output", False):
+ try:
+ open(fqp+".out","w").write(msg)
+ open(fqp+".err","w").write(err_msg)
+ except:
+ # fail silently
+ pass
+
+ else:
+ msg = open(fqp+'.out').read()
+
+ try:
+ ok_results = parse_output(msg)
+ if (expected_num is not None) and (len(ok_results) != expected_num):
+ raise ValueError('Unexpected num %s!=%d' % (str(expected_num), len(ok_results)) )
+
+ parsed = parse_unreachable(msg)
+ total_unreachable = parsed['unreachable']
+ failed = parsed['failed']
+ if (failed):
+ raise ValueError('Ansible playbook failed.')
+
+ if (total_unreachable > 0):
+ raise ValueError("Unreachable results in ansible recipe")
+ except ValueError,e:
+ all_fatal = [e.message] + re.findall(r'^msg: (.*)',msg,re.MULTILINE)
+ all_fatal2 = re.findall(r'^ERROR: (.*)',msg,re.MULTILINE)
+
+ all_fatal.extend(all_fatal2)
+ try:
+ error = ' // '.join(all_fatal)
+ except:
+ pass
+ raise Exception(error)
+
+ return ok_results
+
+def run_template_ssh(name, opts, path='', expected_num=None):
+ instance_name = opts["instance_name"]
+ hostname = opts["hostname"]
+ private_key = opts["private_key"]
+ baremetal_ssh = opts.get("baremetal_ssh",False)
+ if baremetal_ssh:
+ # no instance_id or nat_ip for baremetal
+ # we never proxy to baremetal
+ proxy_ssh = False
+ else:
+ instance_id = opts["instance_id"]
+ nat_ip = opts["nat_ip"]
+ try:
+ proxy_ssh = Config().observer_proxy_ssh
+ except:
+ proxy_ssh = True
+
+ (opts, fqp) = get_playbook_fn(opts, path)
+ private_key_pathname = fqp + ".key"
+ config_pathname = fqp + ".config"
+ hosts_pathname = fqp + ".hosts"
+
+ f = open(private_key_pathname, "w")
+ f.write(private_key)
+ f.close()
+
+ f = open(config_pathname, "w")
+ f.write("[ssh_connection]\n")
+ if proxy_ssh:
+ proxy_command = "ProxyCommand ssh -q -i %s -o StrictHostKeyChecking=no %s@%s" % (private_key_pathname, instance_id, hostname)
+ f.write('ssh_args = -o "%s"\n' % proxy_command)
+ f.write('scp_if_ssh = True\n')
+ f.write('pipelining = True\n')
+ f.write('\n[defaults]\n')
+ f.write('host_key_checking = False\n')
+ f.close()
+
+ f = open(hosts_pathname, "w")
+ f.write("[%s]\n" % instance_name)
+ if proxy_ssh or baremetal_ssh:
+ f.write("%s ansible_ssh_private_key_file=%s\n" % (hostname, private_key_pathname))
+ else:
+ # acb: Login user is hardcoded, this is not great
+ f.write("%s ansible_ssh_private_key_file=%s ansible_ssh_user=ubuntu\n" % (nat_ip, private_key_pathname))
+ f.close()
+
+ # SSH will complain if private key is world or group readable
+ os.chmod(private_key_pathname, 0600)
+
+ print "ANSIBLE_CONFIG=%s" % config_pathname
+ print "ANSIBLE_HOSTS=%s" % hosts_pathname
+
+ return run_template(name, opts, path, ansible_config = config_pathname, ansible_hosts = hosts_pathname, run_ansible_script="/opt/xos/observer/run_ansible_verbose")
+
+
+
+def main():
+ run_template('ansible/sync_user_deployments.yaml',{ "endpoint" : "http://172.31.38.128:5000/v2.0/",
+ "name" : "Sapan Bhatia",
+ "email": "gwsapan@gmail.com",
+ "password": "foobar",
+ "admin_user":"admin",
+ "admin_password":"6a789bf69dd647e2",
+ "admin_tenant":"admin",
+ "tenant":"demo",
+ "roles":['user','admin'] })
diff --git a/xos/synchronizers/openstack/backend.py b/xos/synchronizers/openstack/backend.py
new file mode 100644
index 0000000..5f11d46
--- /dev/null
+++ b/xos/synchronizers/openstack/backend.py
@@ -0,0 +1,46 @@
+import os
+import sys
+import threading
+import time
+from synchronizers.base.event_loop import XOSObserver
+from synchronizers.base.event_manager import EventListener
+from xos.logger import Logger, logging
+from synchronizers.model_policy import run_policy
+from xos.config import Config
+
+logger = Logger(level=logging.INFO)
+
+class Backend:
+
+ def run(self):
+ # start the openstack observer
+ observer = XOSObserver()
+ observer_thread = threading.Thread(target=observer.run)
+ observer_thread.start()
+
+ # start model policies thread
+ observer_name = getattr(Config(), "observer_name", "")
+ if (not observer_name):
+ model_policy_thread = threading.Thread(target=run_policy)
+ model_policy_thread.start()
+ else:
+ model_policy_thread = None
+ print "Skipping model policies thread for service observer."
+
+
+ # start event listene
+ #event_manager = EventListener(wake_up=observer.wake_up)
+ #event_manager_thread = threading.Thread(target=event_manager.run)
+ #event_manager_thread.start()
+
+ while True:
+ try:
+ time.sleep(1000)
+ except KeyboardInterrupt:
+ print "exiting due to keyboard interrupt"
+ # TODO: See about setting the threads as daemons
+ observer_thread._Thread__stop()
+ if model_policy_thread:
+ model_policy_thread._Thread__stop()
+ sys.exit(1)
+
diff --git a/xos/ec2_observer/deleter.py b/xos/synchronizers/openstack/deleter.py
similarity index 100%
copy from xos/ec2_observer/deleter.py
copy to xos/synchronizers/openstack/deleter.py
diff --git a/xos/synchronizers/openstack/error_mapper.py b/xos/synchronizers/openstack/error_mapper.py
new file mode 100644
index 0000000..9eb878d
--- /dev/null
+++ b/xos/synchronizers/openstack/error_mapper.py
@@ -0,0 +1,25 @@
+from xos.config import Config
+from xos.logger import Logger, logging, logger
+
+class ErrorMapper:
+ def __init__(self, error_map_file):
+ self.error_map = {}
+ try:
+ error_map_lines = open(error_map_file).read().splitlines()
+ for l in error_map_lines:
+ if (not l.startswith('#')):
+ splits = l.split('->')
+ k,v = map(lambda i:i.rstrip(),splits)
+ self.error_map[k]=v
+ except:
+ logging.info('Could not read error map')
+
+
+ def map(self, error):
+ return self.error_map[error]
+
+
+
+
+
+
diff --git a/xos/synchronizers/openstack/event_loop.py b/xos/synchronizers/openstack/event_loop.py
new file mode 100644
index 0000000..6cfc9f6
--- /dev/null
+++ b/xos/synchronizers/openstack/event_loop.py
@@ -0,0 +1,527 @@
+import os
+import imp
+import inspect
+import time
+import sys
+import traceback
+import commands
+import threading
+import json
+import pdb
+import pprint
+
+
+from datetime import datetime
+from collections import defaultdict
+from core.models import *
+from django.db.models import F, Q
+from django.db import connection
+from django.db import reset_queries
+#from openstack.manager import OpenStackManager
+from openstack.driver import OpenStackDriver
+from xos.logger import Logger, logging, logger
+#from timeout import timeout
+from xos.config import Config, XOS_DIR
+from synchronizers.base.steps import *
+from syncstep import SyncStep
+from toposort import toposort
+from synchronizers.base.error_mapper import *
+from synchronizers.openstack.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.steps.sync_object import SyncObject
+
+# Load app models
+
+try:
+ app_module_names = Config().observer_applist.split(',')
+except AttributeError:
+ app_module_names = []
+
+if (type(app_module_names)!=list):
+ app_module_names=[app_module_names]
+
+app_modules = []
+
+for m in app_module_names:
+ model_path = m+'.models'
+ module = __import__(model_path,fromlist=[m])
+ app_modules.append(module)
+
+
+debug_mode = False
+
+class bcolors:
+ HEADER = '\033[95m'
+ OKBLUE = '\033[94m'
+ OKGREEN = '\033[92m'
+ WARNING = '\033[93m'
+ FAIL = '\033[91m'
+ ENDC = '\033[0m'
+ BOLD = '\033[1m'
+ UNDERLINE = '\033[4m'
+
+logger = Logger(level=logging.INFO)
+
+class StepNotReady(Exception):
+ pass
+
+class NoOpDriver:
+ def __init__(self):
+ self.enabled = True
+ self.dependency_graph = None
+
+STEP_STATUS_WORKING=1
+STEP_STATUS_OK=2
+STEP_STATUS_KO=3
+
+def invert_graph(g):
+ ig = {}
+ for k,v in g.items():
+ for v0 in v:
+ try:
+ ig[v0].append(k)
+ except:
+ ig[v0]=[k]
+ return ig
+
+class XOSObserver:
+ sync_steps = []
+
+
+ def __init__(self):
+ # The Condition object that gets signalled by Feefie events
+ self.step_lookup = {}
+ self.load_sync_step_modules()
+ self.load_sync_steps()
+ self.event_cond = threading.Condition()
+
+ self.driver_kind = getattr(Config(), "observer_driver", "openstack")
+ self.observer_name = getattr(Config(), "observer_name", "")
+ if self.driver_kind=="openstack":
+ self.driver = OpenStackDriver()
+ else:
+ self.driver = NoOpDriver()
+
+ def consolePrint(self, what):
+ if getattr(Config(), "observer_console_print", True):
+ print what
+
+ def wait_for_event(self, timeout):
+ self.event_cond.acquire()
+ self.event_cond.wait(timeout)
+ self.event_cond.release()
+
+ def wake_up(self):
+ logger.info('Wake up routine called. Event cond %r'%self.event_cond)
+ self.event_cond.acquire()
+ self.event_cond.notify()
+ self.event_cond.release()
+
+ def load_sync_step_modules(self, step_dir=None):
+ if step_dir is None:
+ if hasattr(Config(), "observer_steps_dir"):
+ step_dir = Config().observer_steps_dir
+ else:
+ step_dir = XOS_DIR + "/synchronizers/openstack/steps"
+
+ for fn in os.listdir(step_dir):
+ pathname = os.path.join(step_dir,fn)
+ if os.path.isfile(pathname) and fn.endswith(".py") and (fn!="__init__.py"):
+ module = imp.load_source(fn[:-3],pathname)
+ for classname in dir(module):
+ c = getattr(module, classname, None)
+
+ # make sure 'c' is a descendent of SyncStep and has a
+ # provides field (this eliminates the abstract base classes
+ # since they don't have a provides)
+
+ if inspect.isclass(c) and (issubclass(c, SyncStep) or issubclass(c,OpenStackSyncStep)) and hasattr(c,"provides") and (c not in self.sync_steps):
+ self.sync_steps.append(c)
+ logger.info('loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps]))
+
+ def load_sync_steps(self):
+ dep_path = Config().observer_dependency_graph
+ logger.info('Loading model dependency graph from %s' % dep_path)
+ try:
+ # This contains dependencies between records, not sync steps
+ self.model_dependency_graph = json.loads(open(dep_path).read())
+ for left,lst in self.model_dependency_graph.items():
+ new_lst = []
+ for k in lst:
+ try:
+ tup = (k,k.lower())
+ new_lst.append(tup)
+ deps = self.model_dependency_graph[k]
+ except:
+ self.model_dependency_graph[k] = []
+
+ self.model_dependency_graph[left] = new_lst
+ except Exception,e:
+ raise e
+
+ try:
+ backend_path = Config().observer_pl_dependency_graph
+ logger.info('Loading backend dependency graph from %s' % backend_path)
+ # This contains dependencies between backend records
+ self.backend_dependency_graph = json.loads(open(backend_path).read())
+ for k,v in self.backend_dependency_graph.items():
+ try:
+ self.model_dependency_graph[k].extend(v)
+ except KeyError:
+ self.model_dependency_graphp[k] = v
+
+ except Exception,e:
+ logger.info('Backend dependency graph not loaded')
+ # We can work without a backend graph
+ self.backend_dependency_graph = {}
+
+ provides_dict = {}
+ for s in self.sync_steps:
+ self.step_lookup[s.__name__] = s
+ for m in s.provides:
+ try:
+ provides_dict[m.__name__].append(s.__name__)
+ except KeyError:
+ provides_dict[m.__name__]=[s.__name__]
+
+ step_graph = {}
+ phantom_steps = []
+ for k,v in self.model_dependency_graph.items():
+ try:
+ for source in provides_dict[k]:
+ if (not v):
+ step_graph[source] = []
+
+ for m,_ in v:
+ try:
+ for dest in provides_dict[m]:
+ # no deps, pass
+ try:
+ if (dest not in step_graph[source]):
+ step_graph[source].append(dest)
+ except:
+ step_graph[source]=[dest]
+ except KeyError:
+ if (not provides_dict.has_key(m)):
+ try:
+ step_graph[source]+=['#%s'%m]
+ except:
+ step_graph[source]=['#%s'%m]
+
+ phantom_steps+=['#%s'%m]
+ pass
+
+ except KeyError:
+ pass
+ # no dependencies, pass
+
+
+ self.dependency_graph = step_graph
+ self.deletion_dependency_graph = invert_graph(step_graph)
+
+ pp = pprint.PrettyPrinter(indent=4)
+ logger.info(pp.pformat(step_graph))
+ self.ordered_steps = toposort(self.dependency_graph, phantom_steps+map(lambda s:s.__name__,self.sync_steps))
+ self.ordered_steps = [i for i in self.ordered_steps if i!='SyncObject']
+
+ logger.info("Order of steps=%s" % self.ordered_steps)
+
+ self.load_run_times()
+
+
+ def check_duration(self, step, duration):
+ try:
+ if (duration > step.deadline):
+ logger.info('Sync step %s missed deadline, took %.2f seconds'%(step.name,duration))
+ except AttributeError:
+ # S doesn't have a deadline
+ pass
+
+ def update_run_time(self, step, deletion):
+ if (not deletion):
+ self.last_run_times[step.__name__]=time.time()
+ else:
+ self.last_deletion_run_times[step.__name__]=time.time()
+
+
+ def check_schedule(self, step, deletion):
+ last_run_times = self.last_run_times if not deletion else self.last_deletion_run_times
+
+ time_since_last_run = time.time() - last_run_times.get(step.__name__, 0)
+ try:
+ if (time_since_last_run < step.requested_interval):
+ raise StepNotReady
+ except AttributeError:
+ logger.info('Step %s does not have requested_interval set'%step.__name__)
+ raise StepNotReady
+
+ def load_run_times(self):
+ try:
+ jrun_times = open('/tmp/%sobserver_run_times'%self.observer_name).read()
+ self.last_run_times = json.loads(jrun_times)
+ except:
+ self.last_run_times={}
+ for e in self.ordered_steps:
+ self.last_run_times[e]=0
+ try:
+ jrun_times = open('/tmp/%sobserver_deletion_run_times'%self.observer_name).read()
+ self.last_deletion_run_times = json.loads(jrun_times)
+ except:
+ self.last_deletion_run_times={}
+ for e in self.ordered_steps:
+ self.last_deletion_run_times[e]=0
+
+ def lookup_step_class(self,s):
+ if ('#' in s):
+ return SyncObject
+ else:
+ step = self.step_lookup[s]
+ return step
+
+ def lookup_step(self,s):
+ if ('#' in s):
+ objname = s[1:]
+ so = SyncObject()
+
+ try:
+ obj = globals()[objname]
+ except:
+ for m in app_modules:
+ if (hasattr(m,objname)):
+ obj = getattr(m,objname)
+
+ so.provides=[obj]
+ so.observes=[obj]
+ step = so
+ else:
+ step_class = self.step_lookup[s]
+ step = step_class(driver=self.driver,error_map=self.error_mapper)
+ return step
+
+ def save_run_times(self):
+ run_times = json.dumps(self.last_run_times)
+ open('/tmp/%sobserver_run_times'%self.observer_name,'w').write(run_times)
+
+ deletion_run_times = json.dumps(self.last_deletion_run_times)
+ open('/tmp/%sobserver_deletion_run_times'%self.observer_name,'w').write(deletion_run_times)
+
+ def check_class_dependency(self, step, failed_steps):
+ step.dependenices = []
+ for obj in step.provides:
+ lst = self.model_dependency_graph.get(obj.__name__, [])
+ nlst = map(lambda(a,b):b,lst)
+ step.dependenices.extend(nlst)
+ for failed_step in failed_steps:
+ if (failed_step in step.dependencies):
+ raise StepNotReady
+
+ def sync(self, S, deletion):
+ try:
+ step = self.lookup_step_class(S)
+ start_time=time.time()
+
+ logger.info("Starting to work on step %s, deletion=%s" % (step.__name__, str(deletion)))
+
+ dependency_graph = self.dependency_graph if not deletion else self.deletion_dependency_graph
+ step_conditions = self.step_conditions# if not deletion else self.deletion_step_conditions
+ step_status = self.step_status# if not deletion else self.deletion_step_status
+
+ # Wait for step dependencies to be met
+ try:
+ deps = dependency_graph[S]
+ has_deps = True
+ except KeyError:
+ has_deps = False
+
+ go = True
+
+ failed_dep = None
+ if (has_deps):
+ for d in deps:
+ if d==step.__name__:
+ logger.info(" step %s self-wait skipped" % step.__name__)
+ go = True
+ continue
+
+ cond = step_conditions[d]
+ cond.acquire()
+ if (step_status[d] is STEP_STATUS_WORKING):
+ logger.info(" step %s wait on dep %s" % (step.__name__, d))
+ cond.wait()
+ elif step_status[d] == STEP_STATUS_OK:
+ go = True
+ else:
+ go = False
+ failed_dep = d
+ cond.release()
+ if (not go):
+ break
+ else:
+ go = True
+
+ if (not go):
+ self.consolePrint(bcolors.FAIL + "Step %r skipped on %r" % (step,failed_dep) + bcolors.ENDC)
+ # SMBAKER: sync_step was not defined here, so I changed
+ # this from 'sync_step' to 'step'. Verify.
+ self.failed_steps.append(step)
+ my_status = STEP_STATUS_KO
+ else:
+ sync_step = self.lookup_step(S)
+ sync_step. __name__= step.__name__
+ sync_step.dependencies = []
+ try:
+ mlist = sync_step.provides
+
+ try:
+ for m in mlist:
+ lst = self.model_dependency_graph[m.__name__]
+ nlst = map(lambda(a,b):b,lst)
+ sync_step.dependencies.extend(nlst)
+ except Exception,e:
+ raise e
+
+ except KeyError:
+ pass
+ sync_step.debug_mode = debug_mode
+
+ should_run = False
+ try:
+ # Various checks that decide whether
+ # this step runs or not
+ self.check_class_dependency(sync_step, self.failed_steps) # dont run Slices if Sites failed
+ self.check_schedule(sync_step, deletion) # dont run sync_network_routes if time since last run < 1 hour
+ should_run = True
+ except StepNotReady:
+ logger.info('Step not ready: %s'%sync_step.__name__)
+ self.failed_steps.append(sync_step)
+ my_status = STEP_STATUS_KO
+ except Exception,e:
+ logger.error('%r' % e)
+ logger.log_exc("sync step failed: %r. Deletion: %r"%(sync_step,deletion))
+ self.failed_steps.append(sync_step)
+ my_status = STEP_STATUS_KO
+
+ if (should_run):
+ try:
+ duration=time.time() - start_time
+
+ logger.info('Executing step %s, deletion=%s' % (sync_step.__name__, deletion))
+
+ self.consolePrint(bcolors.OKBLUE + "Executing step %s" % sync_step.__name__ + bcolors.ENDC)
+ failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion)
+
+ self.check_duration(sync_step, duration)
+
+ if failed_objects:
+ self.failed_step_objects.update(failed_objects)
+
+ logger.info("Step %r succeeded" % sync_step.__name__)
+ self.consolePrint(bcolors.OKGREEN + "Step %r succeeded" % sync_step.__name__ + bcolors.ENDC)
+ my_status = STEP_STATUS_OK
+ self.update_run_time(sync_step,deletion)
+ except Exception,e:
+ self.consolePrint(bcolors.FAIL + "Model step %r failed" % (sync_step.__name__) + bcolors.ENDC)
+ logger.error('Model step %r failed. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!' % (sync_step.__name__, e))
+ logger.log_exc(e)
+ self.failed_steps.append(S)
+ my_status = STEP_STATUS_KO
+ else:
+ logger.info("Step %r succeeded due to non-run" % step)
+ my_status = STEP_STATUS_OK
+
+ try:
+ my_cond = step_conditions[S]
+ my_cond.acquire()
+ step_status[S]=my_status
+ my_cond.notify_all()
+ my_cond.release()
+ except KeyError,e:
+ logger.info('Step %r is a leaf' % step)
+ pass
+ finally:
+ try:
+ reset_queries()
+ except:
+ # this shouldn't happen, but in case it does, catch it...
+ logger.log_exc("exception in reset_queries")
+
+ connection.close()
+
+ def run(self):
+ if not self.driver.enabled:
+ return
+
+ if (self.driver_kind=="openstack") and (not self.driver.has_openstack):
+ return
+
+ while True:
+ logger.info('Waiting for event')
+ self.wait_for_event(timeout=5)
+ logger.info('Observer woke up')
+
+ self.run_once()
+
+ def run_once(self):
+ try:
+ loop_start = time.time()
+ error_map_file = getattr(Config(), "error_map_path", XOS_DIR + "/error_map.txt")
+ self.error_mapper = ErrorMapper(error_map_file)
+
+ # Two passes. One for sync, the other for deletion.
+ for deletion in [False,True]:
+ # Set of individual objects within steps that failed
+ self.failed_step_objects = set()
+
+ # Set up conditions and step status
+ # This is needed for steps to run in parallel
+ # while obeying dependencies.
+
+ providers = set()
+ dependency_graph = self.dependency_graph if not deletion else self.deletion_dependency_graph
+
+ for v in dependency_graph.values():
+ if (v):
+ providers.update(v)
+
+ self.step_conditions = {}
+ self.step_status = {}
+
+ for p in list(providers):
+ self.step_conditions[p] = threading.Condition()
+
+ self.step_status[p] = STEP_STATUS_WORKING
+
+ self.failed_steps = []
+
+ threads = []
+ logger.info('Deletion=%r...'%deletion)
+ schedule = self.ordered_steps if not deletion else reversed(self.ordered_steps)
+
+ for S in schedule:
+ thread = threading.Thread(target=self.sync, args=(S, deletion))
+
+ logger.info('Deletion=%r...'%deletion)
+ threads.append(thread)
+
+ # Start threads
+ for t in threads:
+ t.start()
+
+ # another spot to clean up debug state
+ try:
+ reset_queries()
+ except:
+ # this shouldn't happen, but in case it does, catch it...
+ logger.log_exc("exception in reset_queries")
+
+ # Wait for all threads to finish before continuing with the run loop
+ for t in threads:
+ t.join()
+
+ self.save_run_times()
+
+ loop_end = time.time()
+ open('/tmp/%sobserver_last_run'%self.observer_name,'w').write(json.dumps({'last_run': loop_end, 'last_duration':loop_end - loop_start}))
+ except Exception, e:
+ logger.error('Core error. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!' % e)
+ logger.log_exc("Exception in observer run loop")
+ traceback.print_exc()
diff --git a/xos/openstack_observer/event_manager.py b/xos/synchronizers/openstack/event_manager.py
similarity index 100%
copy from xos/openstack_observer/event_manager.py
copy to xos/synchronizers/openstack/event_manager.py
diff --git a/xos/model_policies/__init__.py b/xos/synchronizers/openstack/model_policies/__init__.py
similarity index 100%
rename from xos/model_policies/__init__.py
rename to xos/synchronizers/openstack/model_policies/__init__.py
diff --git a/xos/model_policies/model_policy_Controller.py b/xos/synchronizers/openstack/model_policies/model_policy_Controller.py
similarity index 100%
rename from xos/model_policies/model_policy_Controller.py
rename to xos/synchronizers/openstack/model_policies/model_policy_Controller.py
diff --git a/xos/model_policies/model_policy_ControllerSite.py b/xos/synchronizers/openstack/model_policies/model_policy_ControllerSite.py
similarity index 100%
rename from xos/model_policies/model_policy_ControllerSite.py
rename to xos/synchronizers/openstack/model_policies/model_policy_ControllerSite.py
diff --git a/xos/synchronizers/openstack/model_policies/model_policy_ControllerSlice.py b/xos/synchronizers/openstack/model_policies/model_policy_ControllerSlice.py
new file mode 100644
index 0000000..bfe7995
--- /dev/null
+++ b/xos/synchronizers/openstack/model_policies/model_policy_ControllerSlice.py
@@ -0,0 +1,25 @@
+def handle(controller_slice):
+ from core.models import ControllerSlice, Slice
+
+ try:
+ my_status_code = int(controller_slice.backend_status[0])
+ try:
+ his_status_code = int(controller_slice.slice.backend_status[0])
+ except:
+ his_status_code = 0
+
+ fields = []
+ if (my_status_code not in [0,his_status_code]):
+ controller_slice.slice.backend_status = controller_slice.backend_status
+ fields+=['backend_status']
+
+ if (controller_slice.backend_register != controller_slice.slice.backend_register):
+ controller_slice.slice.backend_register = controller_slice.backend_register
+ fields+=['backend_register']
+
+ controller_slice.slice.save(update_fields = fields)
+
+
+ except Exception,e:
+ print str(e)
+ pass
diff --git a/xos/model_policies/model_policy_ControllerUser.py b/xos/synchronizers/openstack/model_policies/model_policy_ControllerUser.py
similarity index 100%
rename from xos/model_policies/model_policy_ControllerUser.py
rename to xos/synchronizers/openstack/model_policies/model_policy_ControllerUser.py
diff --git a/xos/model_policies/model_policy_Image.py b/xos/synchronizers/openstack/model_policies/model_policy_Image.py
similarity index 100%
rename from xos/model_policies/model_policy_Image.py
rename to xos/synchronizers/openstack/model_policies/model_policy_Image.py
diff --git a/xos/model_policies/model_policy_Instance.py b/xos/synchronizers/openstack/model_policies/model_policy_Instance.py
similarity index 100%
rename from xos/model_policies/model_policy_Instance.py
rename to xos/synchronizers/openstack/model_policies/model_policy_Instance.py
diff --git a/xos/model_policies/model_policy_Network.py b/xos/synchronizers/openstack/model_policies/model_policy_Network.py
similarity index 100%
rename from xos/model_policies/model_policy_Network.py
rename to xos/synchronizers/openstack/model_policies/model_policy_Network.py
diff --git a/xos/model_policies/model_policy_Site.py b/xos/synchronizers/openstack/model_policies/model_policy_Site.py
similarity index 100%
rename from xos/model_policies/model_policy_Site.py
rename to xos/synchronizers/openstack/model_policies/model_policy_Site.py
diff --git a/xos/model_policies/model_policy_SitePrivilege.py b/xos/synchronizers/openstack/model_policies/model_policy_SitePrivilege.py
similarity index 100%
rename from xos/model_policies/model_policy_SitePrivilege.py
rename to xos/synchronizers/openstack/model_policies/model_policy_SitePrivilege.py
diff --git a/xos/synchronizers/openstack/model_policies/model_policy_Slice.py b/xos/synchronizers/openstack/model_policies/model_policy_Slice.py
new file mode 100644
index 0000000..dfdcb4f
--- /dev/null
+++ b/xos/synchronizers/openstack/model_policies/model_policy_Slice.py
@@ -0,0 +1,97 @@
+from xos.config import Config
+
+def handle_delete(slice):
+ from core.models import Controller, ControllerSlice, SiteDeployment, Network, NetworkSlice,NetworkTemplate, Slice
+ from collections import defaultdict
+
+ public_nets = []
+ private_net = None
+ networks = Network.objects.filter(owner=slice)
+
+ for n in networks:
+ n.delete()
+
+ # Note that sliceprivileges and slicecontrollers are autodeleted, through the dependency graph
+
+def handle(slice):
+ from core.models import Controller, ControllerSlice, SiteDeployment, Network, NetworkSlice,NetworkTemplate, Slice
+ from collections import defaultdict
+
+ # only create nat_net if not using VTN
+ support_nat_net = not getattr(Config(), "networking_use_vtn", False)
+
+ print "MODEL POLICY: slice", slice
+
+ # slice = Slice.get(slice_id)
+
+ controller_slices = ControllerSlice.objects.filter(slice=slice)
+ existing_controllers = [cs.controller for cs in controller_slices]
+
+ print "MODEL POLICY: slice existing_controllers=", existing_controllers
+
+ all_controllers = Controller.objects.all()
+ for controller in all_controllers:
+ if controller not in existing_controllers:
+ print "MODEL POLICY: slice adding controller", controller
+ sd = ControllerSlice(slice=slice, controller=controller)
+ sd.save()
+
+ if slice.network in ["host", "bridged"]:
+ # Host and Bridged docker containers need no networks and they will
+ # only get in the way.
+ print "MODEL POLICY: Skipping network creation"
+ else:
+ # make sure slice has at least 1 public and 1 private networkd
+ public_nets = []
+ private_nets = []
+ networks = Network.objects.filter(owner=slice)
+ for network in networks:
+ if not network.autoconnect:
+ continue
+ if network.template.name == 'Public dedicated IPv4':
+ public_nets.append(network)
+ elif network.template.name == 'Public shared IPv4':
+ public_nets.append(network)
+ elif network.template.name == 'Private':
+ private_nets.append(network)
+ if support_nat_net and (not public_nets):
+ # ensure there is at least one public network, and default it to dedicated
+ nat_net = Network(
+ name = slice.name+'-nat',
+ template = NetworkTemplate.objects.get(name='Public shared IPv4'),
+ owner = slice
+ )
+ nat_net.save()
+ public_nets.append(nat_net)
+ print "MODEL POLICY: slice", slice, "made nat-net"
+
+ if not private_nets:
+ private_net = Network(
+ name = slice.name+'-private',
+ template = NetworkTemplate.objects.get(name='Private'),
+ owner = slice
+ )
+ private_net.save()
+ print "MODEL POLICY: slice", slice, "made private net"
+ private_nets = [private_net]
+ # create slice networks
+ public_net_slice = None
+ private_net_slice = None
+ net_slices = NetworkSlice.objects.filter(slice=slice, network__in=private_nets+public_nets)
+ for net_slice in net_slices:
+ if net_slice.network in public_nets:
+ public_net_slice = net_slice
+ elif net_slice.network in private_nets:
+ private_net_slice = net_slice
+ if support_nat_net and (not public_net_slice):
+ public_net_slice = NetworkSlice(slice=slice, network=public_nets[0])
+ public_net_slice.save()
+ print "MODEL POLICY: slice", slice, "made public_net_slice"
+ if not private_net_slice:
+ private_net_slice = NetworkSlice(slice=slice, network=private_nets[0])
+ private_net_slice.save()
+ print "MODEL POLICY: slice", slice, "made private_net_slice"
+
+ print "MODEL POLICY: slice", slice, "DONE"
+
+
diff --git a/xos/model_policies/model_policy_SlicePrivilege.py b/xos/synchronizers/openstack/model_policies/model_policy_SlicePrivilege.py
similarity index 100%
rename from xos/model_policies/model_policy_SlicePrivilege.py
rename to xos/synchronizers/openstack/model_policies/model_policy_SlicePrivilege.py
diff --git a/xos/model_policies/model_policy_Sliver.py b/xos/synchronizers/openstack/model_policies/model_policy_Sliver.py
similarity index 100%
rename from xos/model_policies/model_policy_Sliver.py
rename to xos/synchronizers/openstack/model_policies/model_policy_Sliver.py
diff --git a/xos/model_policies/model_policy_User.py b/xos/synchronizers/openstack/model_policies/model_policy_User.py
similarity index 100%
rename from xos/model_policies/model_policy_User.py
rename to xos/synchronizers/openstack/model_policies/model_policy_User.py
diff --git a/xos/openstack_observer/openstacksyncstep.py b/xos/synchronizers/openstack/openstacksyncstep.py
similarity index 100%
copy from xos/openstack_observer/openstacksyncstep.py
copy to xos/synchronizers/openstack/openstacksyncstep.py
diff --git a/xos/openstack_observer/run_ansible b/xos/synchronizers/openstack/run_ansible
similarity index 100%
copy from xos/openstack_observer/run_ansible
copy to xos/synchronizers/openstack/run_ansible
diff --git a/xos/openstack_observer/run_ansible_verbose b/xos/synchronizers/openstack/run_ansible_verbose
similarity index 100%
copy from xos/openstack_observer/run_ansible_verbose
copy to xos/synchronizers/openstack/run_ansible_verbose
diff --git a/xos/openstack_observer/steps/__init__.py b/xos/synchronizers/openstack/steps/__init__.py
similarity index 100%
copy from xos/openstack_observer/steps/__init__.py
copy to xos/synchronizers/openstack/steps/__init__.py
diff --git a/xos/openstack_observer/steps/delete_slivers.yaml b/xos/synchronizers/openstack/steps/delete_slivers.yaml
similarity index 100%
copy from xos/openstack_observer/steps/delete_slivers.yaml
copy to xos/synchronizers/openstack/steps/delete_slivers.yaml
diff --git a/xos/synchronizers/openstack/steps/purge_disabled_users.py b/xos/synchronizers/openstack/steps/purge_disabled_users.py
new file mode 100644
index 0000000..0973b8c
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/purge_disabled_users.py
@@ -0,0 +1,25 @@
+import os
+import base64
+import datetime
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from core.models.user import User
+from xos.logger import observer_logger as logger
+
+class SyncRoles(OpenStackSyncStep):
+ provides=[User]
+ requested_interval=0
+ observes=User
+
+ def fetch_pending(self, deleted):
+ if (deleted):
+ # users marked as deleted
+ return User.deleted_objects.all()
+ else:
+ # disabled users that haven't been updated in over a week
+ one_week_ago = datetime.datetime.now() - datetime.timedelta(days=7)
+ return User.objects.filter(is_active=False, updated__gt=one_week_ago)
+
+ def sync_record(self, user):
+ user.delete()
diff --git a/xos/openstack_observer/steps/sliver.yaml b/xos/synchronizers/openstack/steps/sliver.yaml
similarity index 100%
copy from xos/openstack_observer/steps/sliver.yaml
copy to xos/synchronizers/openstack/steps/sliver.yaml
diff --git a/xos/synchronizers/openstack/steps/sync_container.py b/xos/synchronizers/openstack/steps/sync_container.py
new file mode 100644
index 0000000..d647aef
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_container.py
@@ -0,0 +1,163 @@
+import hashlib
+import os
+import socket
+import sys
+import base64
+import time
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
+from synchronizers.base.syncstep import SyncStep, DeferredException
+from synchronizers.base.ansible import run_template_ssh
+from core.models import Service, Slice, Instance
+from services.onos.models import ONOSService, ONOSApp
+from xos.logger import Logger, logging
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+logger = Logger(level=logging.INFO)
+
+class SyncContainer(SyncInstanceUsingAnsible):
+ provides=[Instance]
+ observes=Instance
+ requested_interval=0
+ template_name = "sync_container.yaml"
+
+ def __init__(self, *args, **kwargs):
+ super(SyncContainer, self).__init__(*args, **kwargs)
+
+ def fetch_pending(self, deletion=False):
+ objs = super(SyncContainer, self).fetch_pending(deletion)
+ objs = [x for x in objs if x.isolation in ["container", "container_vm"]]
+ return objs
+
+ def get_instance_port(self, container_port):
+ for p in container_port.network.links.all():
+ if (p.instance) and (p.instance.isolation=="vm") and (p.instance.node == container_port.instance.node) and (p.mac):
+ return p
+ return None
+
+ def get_parent_port_mac(self, instance, port):
+ if not instance.parent:
+ raise Exception("instance has no parent")
+ for parent_port in instance.parent.ports.all():
+ if parent_port.network == port.network:
+ if not parent_port.mac:
+ raise DeferredException("parent port on network %s does not have mac yet" % parent_port.network.name)
+ return parent_port.mac
+ raise Exception("failed to find corresponding parent port for network %s" % port.network.name)
+
+ def get_ports(self, o):
+ i=0
+ ports = []
+ if (o.slice.network in ["host", "bridged"]):
+ pass # no ports in host or bridged mode
+ else:
+ for port in o.ports.all():
+ if (not port.ip):
+ # 'unmanaged' ports may have an ip, but no mac
+ # XXX: are there any ports that have a mac but no ip?
+ raise DeferredException("Port on network %s is not yet ready" % port.network.name)
+
+ pd={}
+ pd["mac"] = port.mac or ""
+ pd["ip"] = port.ip or ""
+ pd["xos_network_id"] = port.network.id
+
+ if port.network.name == "wan_network":
+ if port.ip:
+ (a, b, c, d) = port.ip.split('.')
+ pd["mac"] = "02:42:%02x:%02x:%02x:%02x" % (int(a), int(b), int(c), int(d))
+
+
+ if o.isolation == "container":
+ # container on bare metal
+ instance_port = self.get_instance_port(port)
+ if not instance_port:
+ raise DeferredException("No instance on slice for port on network %s" % port.network.name)
+
+ pd["snoop_instance_mac"] = instance_port.mac
+ pd["snoop_instance_id"] = instance_port.instance.instance_id
+ pd["src_device"] = ""
+ pd["bridge"] = "br-int"
+ else:
+ # container in VM
+ pd["snoop_instance_mac"] = ""
+ pd["snoop_instance_id"] = ""
+ pd["parent_mac"] = self.get_parent_port_mac(o, port)
+ pd["bridge"] = ""
+
+ for (k,v) in port.get_parameters().items():
+ pd[k] = v
+
+ ports.append(pd)
+
+ # for any ports that don't have a device, assign one
+ used_ports = [x["device"] for x in ports if ("device" in x)]
+ avail_ports = ["eth%d"%i for i in range(0,64) if ("eth%d"%i not in used_ports)]
+ for port in ports:
+ if not port.get("device",None):
+ port["device"] = avail_ports.pop(0)
+
+ return ports
+
+ def get_extra_attributes(self, o):
+ fields={}
+ fields["ansible_tag"] = "container-%s" % str(o.id)
+ if o.image.tag:
+ fields["docker_image"] = o.image.path + ":" + o.image.tag
+ else:
+ fields["docker_image"] = o.image.path
+ fields["ports"] = self.get_ports(o)
+ if o.volumes:
+ fields["volumes"] = [x.strip() for x in o.volumes.split(",")]
+ else:
+ fields["volumes"] = ""
+ fields["network_method"] = o.slice.network or "default"
+ return fields
+
+ def sync_record(self, o):
+ logger.info("sync'ing object %s" % str(o))
+
+ fields = self.get_ansible_fields(o)
+
+ # If 'o' defines a 'sync_attributes' list, then we'll copy those
+ # attributes into the Ansible recipe's field list automatically.
+ if hasattr(o, "sync_attributes"):
+ for attribute_name in o.sync_attributes:
+ fields[attribute_name] = getattr(o, attribute_name)
+
+ fields.update(self.get_extra_attributes(o))
+
+ self.run_playbook(o, fields)
+
+ o.instance_id = fields["container_name"]
+ o.instance_name = fields["container_name"]
+
+ o.save()
+
+ def delete_record(self, o):
+ logger.info("delete'ing object %s" % str(o))
+
+ fields = self.get_ansible_fields(o)
+
+ # If 'o' defines a 'sync_attributes' list, then we'll copy those
+ # attributes into the Ansible recipe's field list automatically.
+ if hasattr(o, "sync_attributes"):
+ for attribute_name in o.sync_attributes:
+ fields[attribute_name] = getattr(o, attribute_name)
+
+ fields.update(self.get_extra_attributes(o))
+
+ self.run_playbook(o, fields, "teardown_container.yaml")
+
+ def run_playbook(self, o, fields, template_name=None):
+ if not template_name:
+ template_name = self.template_name
+ tStart = time.time()
+ run_template_ssh(template_name, fields, path="container")
+ logger.info("playbook execution time %d" % int(time.time()-tStart))
+
+
diff --git a/xos/openstack_observer/steps/sync_container.yaml b/xos/synchronizers/openstack/steps/sync_container.yaml
similarity index 100%
copy from xos/openstack_observer/steps/sync_container.yaml
copy to xos/synchronizers/openstack/steps/sync_container.yaml
diff --git a/xos/synchronizers/openstack/steps/sync_controller_images.py b/xos/synchronizers/openstack/steps/sync_controller_images.py
new file mode 100644
index 0000000..c1e5136
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_controller_images.py
@@ -0,0 +1,44 @@
+import os
+import base64
+from collections import defaultdict
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models import Controller
+from core.models import Image, ControllerImages
+from xos.logger import observer_logger as logger
+from synchronizers.base.ansible import *
+import json
+
+class SyncControllerImages(OpenStackSyncStep):
+ provides=[ControllerImages]
+ observes = ControllerImages
+ requested_interval=0
+ playbook='sync_controller_images.yaml'
+
+ def fetch_pending(self, deleted):
+ if (deleted):
+ return []
+
+ # now we return all images that need to be enacted
+ return ControllerImages.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
+
+ def map_sync_inputs(self, controller_image):
+ image_fields = {'endpoint':controller_image.controller.auth_url,
+ 'endpoint_v3': controller_image.controller.auth_url_v3,
+ 'admin_user':controller_image.controller.admin_user,
+ 'admin_password':controller_image.controller.admin_password,
+ 'domain': controller_image.controller.domain,
+ 'name':controller_image.image.name,
+ 'filepath':controller_image.image.path,
+ 'ansible_tag': '%s@%s'%(controller_image.image.name,controller_image.controller.name), # name of ansible playbook
+ }
+
+ return image_fields
+
+ def map_sync_outputs(self, controller_image, res):
+ image_id = res[0]['id']
+ controller_image.glance_image_id = image_id
+ controller_image.backend_status = '1 - OK'
+ controller_image.save()
diff --git a/xos/openstack_observer/steps/sync_controller_images.yaml b/xos/synchronizers/openstack/steps/sync_controller_images.yaml
similarity index 100%
copy from xos/openstack_observer/steps/sync_controller_images.yaml
copy to xos/synchronizers/openstack/steps/sync_controller_images.yaml
diff --git a/xos/synchronizers/openstack/steps/sync_controller_networks.py b/xos/synchronizers/openstack/steps/sync_controller_networks.py
new file mode 100644
index 0000000..990cb87
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_controller_networks.py
@@ -0,0 +1,136 @@
+import os
+import base64
+from collections import defaultdict
+from netaddr import IPAddress, IPNetwork
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models.network import *
+from core.models.slice import *
+from core.models.instance import Instance
+from xos.logger import observer_logger as logger
+from synchronizers.base.ansible import *
+from openstack.driver import OpenStackDriver
+from xos.config import Config
+import json
+
+import pdb
+
+class SyncControllerNetworks(OpenStackSyncStep):
+ requested_interval = 0
+ provides=[Network]
+ observes=ControllerNetwork
+ playbook='sync_controller_networks.yaml'
+
+ def alloc_subnet(self, uuid):
+ # 16 bits only
+ uuid_masked = uuid & 0xffff
+ a = 10
+ b = uuid_masked >> 8
+ c = uuid_masked & 0xff
+ d = 0
+
+ cidr = '%d.%d.%d.%d/24'%(a,b,c,d)
+ return cidr
+
+ def alloc_gateway(self, uuid):
+ # 16 bits only
+ uuid_masked = uuid & 0xffff
+ a = 10
+ b = uuid_masked >> 8
+ c = uuid_masked & 0xff
+ d = 1
+
+ gateway = '%d.%d.%d.%d'%(a,b,c,d)
+ return gateway
+
+
+ def save_controller_network(self, controller_network):
+ network_name = controller_network.network.name
+ subnet_name = '%s-%d'%(network_name,controller_network.pk)
+ cidr = self.alloc_subnet(controller_network.pk)
+ self.cidr=cidr
+ slice = controller_network.network.owner
+
+ network_fields = {'endpoint':controller_network.controller.auth_url,
+ 'endpoint_v3': controller_network.controller.auth_url_v3,
+ 'admin_user':slice.creator.email,
+ 'tenant_name':slice.name,
+ 'admin_password':slice.creator.remote_password,
+ 'domain': controller_network.controller.domain,
+ 'name':network_name,
+ 'subnet_name':subnet_name,
+ 'ansible_tag':'%s-%s@%s'%(network_name,slice.slicename,controller_network.controller.name),
+ 'cidr':cidr,
+ 'gateway':self.alloc_gateway(controller_network.pk),
+ 'use_vtn':getattr(Config(), "networking_use_vtn", False),
+ 'delete':False
+ }
+ return network_fields
+
+ def map_sync_outputs(self, controller_network,res):
+ network_id = res[0]['id']
+ subnet_id = res[1]['id']
+ controller_network.net_id = network_id
+ controller_network.subnet = self.cidr
+ controller_network.subnet_id = subnet_id
+ controller_network.backend_status = '1 - OK'
+ controller_network.save()
+
+
+ def map_sync_inputs(self, controller_network):
+ # XXX This check should really be made from booleans, rather than using hardcoded network names
+ if (controller_network.network.template.name not in ['Private', 'Private-Indirect', 'Private-Direct']):
+ logger.info("skipping network controller %s because it is not private" % controller_network)
+ # We only sync private networks
+ return SyncStep.SYNC_WITHOUT_RUNNING
+
+ if not controller_network.controller.admin_user:
+ logger.info("controller %r has no admin_user, skipping" % controller_network.controller)
+ return
+
+ if controller_network.network.owner and controller_network.network.owner.creator:
+ return self.save_controller_network(controller_network)
+ else:
+ raise Exception('Could not save network controller %s'%controller_network)
+
+ def map_delete_inputs(self, controller_network):
+ # XXX This check should really be made from booleans, rather than using hardcoded network names
+ if (controller_network.network.template.name not in ['Private', 'Private-Indirect', 'Private-Direct']):
+ # We only sync private networks
+ return
+ try:
+ slice = controller_network.network.owner # XXX: FIXME!!
+ except:
+ raise Exception('Could not get slice for Network %s'%controller_network.network.name)
+
+ network_name = controller_network.network.name
+ subnet_name = '%s-%d'%(network_name,controller_network.pk)
+ cidr = controller_network.subnet
+ network_fields = {'endpoint':controller_network.controller.auth_url,
+ 'admin_user':slice.creator.email, # XXX: FIXME
+ 'tenant_name':slice.name, # XXX: FIXME
+ 'admin_password':slice.creator.remote_password,
+ 'name':network_name,
+ 'subnet_name':subnet_name,
+ 'ansible_tag':'%s-%s@%s'%(network_name,slice.slicename,controller_network.controller.name),
+ 'cidr':cidr,
+ 'delete':True
+ }
+
+ return network_fields
+
+ """
+ driver = OpenStackDriver().client_driver(caller=controller_network.network.owner.creator,
+ tenant=controller_network.network.owner.name,
+ controller=controller_network.controller.name)
+ if (controller_network.router_id) and (controller_network.subnet_id):
+ driver.delete_router_interface(controller_network.router_id, controller_network.subnet_id)
+ if controller_network.subnet_id:
+ driver.delete_subnet(controller_network.subnet_id)
+ if controller_network.router_id:
+ driver.delete_router(controller_network.router_id)
+ if controller_network.net_id:
+ driver.delete_network(controller_network.net_id)
+ """
diff --git a/xos/synchronizers/openstack/steps/sync_controller_networks.yaml b/xos/synchronizers/openstack/steps/sync_controller_networks.yaml
new file mode 100644
index 0000000..b885516
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_controller_networks.yaml
@@ -0,0 +1,39 @@
+---
+- hosts: 127.0.0.1
+ connection: local
+ tasks:
+ - quantum_network:
+ auth_url={{ endpoint }}
+ login_username={{ admin_user }}
+ login_tenant_name={{ tenant_name }}
+ login_password={{ admin_password }}
+ tenant_name={{ tenant_name }}
+ name={{ name }}
+ {% if delete %}
+ state=absent
+ {% else %}
+ state=present
+ {% endif %}
+ shared=true
+ {% if not delete %}
+ - quantum_subnet:
+ auth_url={{ endpoint }}
+ login_username={{ admin_user }}
+ login_tenant_name={{ tenant_name }}
+ login_password={{ admin_password }}
+ tenant_name={{ tenant_name }}
+ name={{ subnet_name }}
+ network_name={{ name }}
+ {% if delete %}
+ state=absent
+ {% else %}
+ state=present
+ {% if use_vtn %}
+ gateway_ip={{ gateway }}
+ {% else %}
+ no_gateway=true
+ {% endif %}
+ dns_nameservers=8.8.8.8
+ cidr={{ cidr }}
+ {% endif %}
+ {% endif %}
diff --git a/xos/synchronizers/openstack/steps/sync_controller_site_privileges.py b/xos/synchronizers/openstack/steps/sync_controller_site_privileges.py
new file mode 100644
index 0000000..59919fe
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_controller_site_privileges.py
@@ -0,0 +1,84 @@
+import os
+import base64
+from collections import defaultdict
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models.site import Controller, SitePrivilege
+from core.models.user import User
+from core.models.controlleruser import ControllerUser, ControllerSitePrivilege
+from xos.logger import observer_logger as logger
+from synchronizers.base.ansible import *
+import json
+
+class SyncControllerSitePrivileges(OpenStackSyncStep):
+ provides=[SitePrivilege]
+ requested_interval=0
+ observes=ControllerSitePrivilege
+ playbook='sync_controller_users.yaml'
+
+ def map_sync_inputs(self, controller_site_privilege):
+ controller_register = json.loads(controller_site_privilege.controller.backend_register)
+ if not controller_site_privilege.controller.admin_user:
+ logger.info("controller %r has no admin_user, skipping" % controller_site_privilege.controller)
+ return
+
+ roles = [controller_site_privilege.site_privilege.role.role]
+ # setup user home site roles at controller
+ if not controller_site_privilege.site_privilege.user.site:
+ raise Exception('Siteless user %s'%controller_site_privilege.site_privilege.user.email)
+ else:
+ # look up tenant id for the user's site at the controller
+ #ctrl_site_deployments = SiteDeployment.objects.filter(
+ # site_deployment__site=controller_site_privilege.user.site,
+ # controller=controller_site_privilege.controller)
+
+ #if ctrl_site_deployments:
+ # # need the correct tenant id for site at the controller
+ # tenant_id = ctrl_site_deployments[0].tenant_id
+ # tenant_name = ctrl_site_deployments[0].site_deployment.site.login_base
+ user_fields = {
+ 'endpoint':controller_site_privilege.controller.auth_url,
+ 'endpoint_v3': controller_site_privilege.controller.auth_url_v3,
+ 'domain': controller_site_privilege.controller.domain,
+ 'name': controller_site_privilege.site_privilege.user.email,
+ 'email': controller_site_privilege.site_privilege.user.email,
+ 'password': controller_site_privilege.site_privilege.user.remote_password,
+ 'admin_user': controller_site_privilege.controller.admin_user,
+ 'admin_password': controller_site_privilege.controller.admin_password,
+ 'ansible_tag':'%s@%s'%(controller_site_privilege.site_privilege.user.email.replace('@','-at-'),controller_site_privilege.controller.name),
+ 'admin_tenant': controller_site_privilege.controller.admin_tenant,
+ 'roles':roles,
+ 'tenant':controller_site_privilege.site_privilege.site.login_base}
+
+ return user_fields
+
+ def map_sync_outputs(self, controller_site_privilege, res):
+ # results is an array in which each element corresponds to an
+ # "ok" string received per operation. If we get as many oks as
+ # the number of operations we issued, that means a grand success.
+ # Otherwise, the number of oks tell us which operation failed.
+ controller_site_privilege.role_id = res[0]['id']
+ controller_site_privilege.save()
+
+ def delete_record(self, controller_site_privilege):
+ controller_register = json.loads(controller_site_privilege.controller.backend_register)
+ if (controller_register.get('disabled',False)):
+ raise InnocuousException('Controller %s is disabled'%controller_site_privilege.controller.name)
+
+ if controller_site_privilege.role_id:
+ driver = self.driver.admin_driver(controller=controller_site_privilege.controller)
+ user = ControllerUser.objects.get(
+ controller=controller_site_privilege.controller,
+ user=controller_site_privilege.site_privilege.user
+ )
+ site = ControllerSite.objects.get(
+ controller=controller_site_privilege.controller,
+ user=controller_site_privilege.site_privilege.user
+ )
+ driver.delete_user_role(
+ user.kuser_id,
+ site.tenant_id,
+ controller_site_privilege.site_prvilege.role.role
+ )
diff --git a/xos/synchronizers/openstack/steps/sync_controller_sites.py b/xos/synchronizers/openstack/steps/sync_controller_sites.py
new file mode 100644
index 0000000..1b3c2ba
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_controller_sites.py
@@ -0,0 +1,67 @@
+import os
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.openstack.openstacksyncstep import OpenStackSyncStep
+from core.models.site import *
+from synchronizers.base.syncstep import *
+from synchronizers.base.ansible import *
+from xos.logger import observer_logger as logger
+import json
+
+class SyncControllerSites(OpenStackSyncStep):
+ requested_interval=0
+ provides=[Site]
+ observes=ControllerSite
+ playbook = 'sync_controller_sites.yaml'
+
+ def fetch_pending(self, deleted=False):
+ lobjs = ControllerSite.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False),Q(controller__isnull=False))
+ return lobjs
+
+ def map_sync_inputs(self, controller_site):
+ tenant_fields = {'endpoint':controller_site.controller.auth_url,
+ 'endpoint_v3': controller_site.controller.auth_url_v3,
+ 'domain': controller_site.controller.domain,
+ 'admin_user': controller_site.controller.admin_user,
+ 'admin_password': controller_site.controller.admin_password,
+ 'admin_tenant': controller_site.controller.admin_tenant,
+ 'ansible_tag': '%s@%s'%(controller_site.site.login_base,controller_site.controller.name), # name of ansible playbook
+ 'tenant': controller_site.site.login_base,
+ 'tenant_description': controller_site.site.name}
+ return tenant_fields
+
+ def map_sync_outputs(self, controller_site, res):
+ controller_site.tenant_id = res[0]['id']
+ controller_site.backend_status = '1 - OK'
+ controller_site.save()
+
+ def delete_record(self, controller_site):
+ controller_register = json.loads(controller_site.controller.backend_register)
+ if (controller_register.get('disabled',False)):
+ raise InnocuousException('Controller %s is disabled'%controller_site.controller.name)
+
+ if controller_site.tenant_id:
+ driver = self.driver.admin_driver(controller=controller_site.controller)
+ driver.delete_tenant(controller_site.tenant_id)
+
+ """
+ Ansible does not support tenant deletion yet
+
+ import pdb
+ pdb.set_trace()
+ template = os_template_env.get_template('delete_controller_sites.yaml')
+ tenant_fields = {'endpoint':controller_site.controller.auth_url,
+ 'admin_user': controller_site.controller.admin_user,
+ 'admin_password': controller_site.controller.admin_password,
+ 'admin_tenant': 'admin',
+ 'ansible_tag': 'controller_sites/%s@%s'%(controller_site.controller_site.site.login_base,controller_site.controller_site.deployment.name), # name of ansible playbook
+ 'tenant': controller_site.controller_site.site.login_base,
+ 'delete': True}
+
+ rendered = template.render(tenant_fields)
+ res = run_template('sync_controller_sites.yaml', tenant_fields)
+
+ if (len(res)!=1):
+ raise Exception('Could not assign roles for user %s'%tenant_fields['tenant'])
+ """
diff --git a/xos/openstack_observer/steps/sync_controller_sites.yaml b/xos/synchronizers/openstack/steps/sync_controller_sites.yaml
similarity index 100%
copy from xos/openstack_observer/steps/sync_controller_sites.yaml
copy to xos/synchronizers/openstack/steps/sync_controller_sites.yaml
diff --git a/xos/synchronizers/openstack/steps/sync_controller_slice_privileges.py b/xos/synchronizers/openstack/steps/sync_controller_slice_privileges.py
new file mode 100644
index 0000000..b78e4a0
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_controller_slice_privileges.py
@@ -0,0 +1,79 @@
+import os
+import base64
+from collections import defaultdict
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models.slice import Controller, SlicePrivilege
+from core.models.user import User
+from core.models.controlleruser import ControllerUser, ControllerSlicePrivilege
+from synchronizers.base.ansible import *
+from xos.logger import observer_logger as logger
+import json
+
+class SyncControllerSlicePrivileges(OpenStackSyncStep):
+ provides=[SlicePrivilege]
+ requested_interval=0
+ observes=ControllerSlicePrivilege
+ playbook = 'sync_controller_users.yaml'
+
+ def map_inputs(self, controller_slice_privilege):
+ if not controller_slice_privilege.controller.admin_user:
+ logger.info("controller %r has no admin_user, skipping" % controller_slice_privilege.controller)
+ return
+
+ template = os_template_env.get_template('sync_controller_users.yaml')
+ roles = [controller_slice_privilege.slice_privilege.role.role]
+ # setup user home slice roles at controller
+ if not controller_slice_privilege.slice_privilege.user.site:
+ raise Exception('Sliceless user %s'%controller_slice_privilege.slice_privilege.user.email)
+ else:
+ # look up tenant id for the user's slice at the controller
+ #ctrl_slice_deployments = SliceDeployment.objects.filter(
+ # slice_deployment__slice=controller_slice_privilege.user.slice,
+ # controller=controller_slice_privilege.controller)
+
+ #if ctrl_slice_deployments:
+ # # need the correct tenant id for slice at the controller
+ # tenant_id = ctrl_slice_deployments[0].tenant_id
+ # tenant_name = ctrl_slice_deployments[0].slice_deployment.slice.login_base
+ user_fields = {
+ 'endpoint':controller_slice_privilege.controller.auth_url,
+ 'endpoint_v3': controller_slice_privilege.controller.auth_url_v3,
+ 'domain': controller_slice_privilege.controller.domain,
+ 'name': controller_slice_privilege.slice_privilege.user.email,
+ 'email': controller_slice_privilege.slice_privilege.user.email,
+ 'password': controller_slice_privilege.slice_privilege.user.remote_password,
+ 'admin_user': controller_slice_privilege.controller.admin_user,
+ 'admin_password': controller_slice_privilege.controller.admin_password,
+ 'ansible_tag':'%s@%s@%s'%(controller_slice_privilege.slice_privilege.user.email.replace('@','-at-'),controller_slice_privilege.slice_privilege.slice.name,controller_slice_privilege.controller.name),
+ 'admin_tenant': controller_slice_privilege.controller.admin_tenant,
+ 'roles':roles,
+ 'tenant':controller_slice_privilege.slice_privilege.slice.name}
+ return user_fields
+
+ def map_sync_outputs(self, controller_slice_privilege, res):
+ controller_slice_privilege.role_id = res[0]['id']
+ controller_slice_privilege.save()
+
+ def delete_record(self, controller_slice_privilege):
+ controller_register = json.loads(controller_slice_privilege.controller.backend_register)
+ if (controller_register.get('disabled',False)):
+ raise InnocuousException('Controller %s is disabled'%controller_slice_privilege.controller.name)
+
+ if controller_slice_privilege.role_id:
+ driver = self.driver.admin_driver(controller=controller_slice_privilege.controller)
+ user = ControllerUser.objects.get(
+ controller=controller_slice_privilege.controller,
+ user=controller_slice_privilege.slice_privilege.user
+ )
+ slice = ControllerSlice.objects.get(
+ controller=controller_slice_privilege.controller,
+ user=controller_slice_privilege.slice_privilege.user
+ )
+ driver.delete_user_role(
+ user.kuser_id,
+ slice.tenant_id,
+ controller_slice_privilege.slice_prvilege.role.role
+ )
diff --git a/xos/synchronizers/openstack/steps/sync_controller_slices.py b/xos/synchronizers/openstack/steps/sync_controller_slices.py
new file mode 100644
index 0000000..97d8c29
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_controller_slices.py
@@ -0,0 +1,84 @@
+import os
+import base64
+from collections import defaultdict
+from netaddr import IPAddress, IPNetwork
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models import *
+from synchronizers.base.ansible import *
+from openstack.driver import OpenStackDriver
+from xos.logger import observer_logger as logger
+import json
+
+class SyncControllerSlices(OpenStackSyncStep):
+ provides=[Slice]
+ requested_interval=0
+ observes=ControllerSlice
+ playbook='sync_controller_slices.yaml'
+
+ def map_sync_inputs(self, controller_slice):
+ logger.info("sync'ing slice controller %s" % controller_slice)
+
+ if not controller_slice.controller.admin_user:
+ logger.info("controller %r has no admin_user, skipping" % controller_slice.controller)
+ return
+
+ controller_users = ControllerUser.objects.filter(user=controller_slice.slice.creator,
+ controller=controller_slice.controller)
+ if not controller_users:
+ raise Exception("slice createor %s has not accout at controller %s" % (controller_slice.slice.creator, controller_slice.controller.name))
+ else:
+ controller_user = controller_users[0]
+ roles = ['admin']
+
+ max_instances=int(controller_slice.slice.max_instances)
+ tenant_fields = {'endpoint':controller_slice.controller.auth_url,
+ 'endpoint_v3': controller_slice.controller.auth_url_v3,
+ 'domain': controller_slice.controller.domain,
+ 'admin_user': controller_slice.controller.admin_user,
+ 'admin_password': controller_slice.controller.admin_password,
+ 'admin_tenant': 'admin',
+ 'tenant': controller_slice.slice.name,
+ 'tenant_description': controller_slice.slice.description,
+ 'roles':roles,
+ 'name':controller_user.user.email,
+ 'ansible_tag':'%s@%s'%(controller_slice.slice.name,controller_slice.controller.name),
+ 'max_instances':max_instances}
+
+ return tenant_fields
+
+ def map_sync_outputs(self, controller_slice, res):
+ tenant_id = res[0]['id']
+ if (not controller_slice.tenant_id):
+ try:
+ driver = OpenStackDriver().admin_driver(controller=controller_slice.controller)
+ driver.shell.nova.quotas.update(tenant_id=tenant_id, instances=int(controller_slice.slice.max_instances))
+ except:
+ logger.log_exc('Could not update quota for %s'%controller_slice.slice.name)
+ raise Exception('Could not update quota for %s'%controller_slice.slice.name)
+
+ controller_slice.tenant_id = tenant_id
+ controller_slice.backend_status = '1 - OK'
+ controller_slice.save()
+
+
+ def map_delete_inputs(self, controller_slice):
+ controller_users = ControllerUser.objects.filter(user=controller_slice.slice.creator,
+ controller=controller_slice.controller)
+ if not controller_users:
+ raise Exception("slice createor %s has not accout at controller %s" % (controller_slice.slice.creator, controller_slice.controller.name))
+ else:
+ controller_user = controller_users[0]
+
+ tenant_fields = {'endpoint':controller_slice.controller.auth_url,
+ 'admin_user': controller_slice.controller.admin_user,
+ 'admin_password': controller_slice.controller.admin_password,
+ 'admin_tenant': 'admin',
+ 'tenant': controller_slice.slice.name,
+ 'tenant_description': controller_slice.slice.description,
+ 'name':controller_user.user.email,
+ 'ansible_tag':'%s@%s'%(controller_slice.slice.name,controller_slice.controller.name),
+ 'delete': True}
+ return tenant_fields
diff --git a/xos/openstack_observer/steps/sync_controller_slices.yaml b/xos/synchronizers/openstack/steps/sync_controller_slices.yaml
similarity index 100%
copy from xos/openstack_observer/steps/sync_controller_slices.yaml
copy to xos/synchronizers/openstack/steps/sync_controller_slices.yaml
diff --git a/xos/synchronizers/openstack/steps/sync_controller_users.py b/xos/synchronizers/openstack/steps/sync_controller_users.py
new file mode 100644
index 0000000..9af48e5
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_controller_users.py
@@ -0,0 +1,69 @@
+import os
+import base64
+from collections import defaultdict
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models.site import Controller, SiteDeployment, SiteDeployment
+from core.models.user import User
+from core.models.controlleruser import ControllerUser
+from synchronizers.base.ansible import *
+from xos.logger import observer_logger as logger
+import json
+
+class SyncControllerUsers(OpenStackSyncStep):
+ provides=[User]
+ requested_interval=0
+ observes=ControllerUser
+ playbook='sync_controller_users.yaml'
+
+ def map_sync_inputs(self, controller_user):
+ if not controller_user.controller.admin_user:
+ logger.info("controller %r has no admin_user, skipping" % controller_user.controller)
+ return
+
+ # All users will have at least the 'user' role at their home site/tenant.
+ # We must also check if the user should have the admin role
+ roles = ['user']
+ if controller_user.user.is_admin:
+ roles.append('admin')
+
+ # setup user home site roles at controller
+ if not controller_user.user.site:
+ raise Exception('Siteless user %s'%controller_user.user.email)
+ else:
+ # look up tenant id for the user's site at the controller
+ #ctrl_site_deployments = SiteDeployment.objects.filter(
+ # site_deployment__site=controller_user.user.site,
+ # controller=controller_user.controller)
+
+ #if ctrl_site_deployments:
+ # # need the correct tenant id for site at the controller
+ # tenant_id = ctrl_site_deployments[0].tenant_id
+ # tenant_name = ctrl_site_deployments[0].site_deployment.site.login_base
+ user_fields = {
+ 'endpoint':controller_user.controller.auth_url,
+ 'endpoint_v3': controller_user.controller.auth_url_v3,
+ 'domain': controller_user.controller.domain,
+ 'name': controller_user.user.email,
+ 'email': controller_user.user.email,
+ 'password': controller_user.user.remote_password,
+ 'admin_user': controller_user.controller.admin_user,
+ 'admin_password': controller_user.controller.admin_password,
+ 'ansible_tag':'%s@%s'%(controller_user.user.email.replace('@','-at-'),controller_user.controller.name),
+ 'admin_tenant': controller_user.controller.admin_tenant,
+ 'roles':roles,
+ 'tenant':controller_user.user.site.login_base
+ }
+ return user_fields
+
+ def map_sync_outputs(self, controller_user, res):
+ controller_user.kuser_id = res[0]['id']
+ controller_user.backend_status = '1 - OK'
+ controller_user.save()
+
+ def delete_record(self, controller_user):
+ if controller_user.kuser_id:
+ driver = self.driver.admin_driver(controller=controller_user.controller)
+ driver.delete_user(controller_user.kuser_id)
diff --git a/xos/openstack_observer/steps/sync_controller_users.yaml b/xos/synchronizers/openstack/steps/sync_controller_users.yaml
similarity index 100%
copy from xos/openstack_observer/steps/sync_controller_users.yaml
copy to xos/synchronizers/openstack/steps/sync_controller_users.yaml
diff --git a/xos/synchronizers/openstack/steps/sync_images.py b/xos/synchronizers/openstack/steps/sync_images.py
new file mode 100644
index 0000000..8049ac1
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_images.py
@@ -0,0 +1,52 @@
+import os
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from core.models.image import Image
+from xos.logger import observer_logger as logger
+
+class SyncImages(OpenStackSyncStep):
+ provides=[Image]
+ requested_interval=0
+ observes=Image
+
+ def fetch_pending(self, deleted):
+ # Images come from the back end
+ # You can't delete them
+ if (deleted):
+ logger.info("SyncImages: returning because deleted=True")
+ return []
+
+ # get list of images on disk
+ images_path = Config().observer_images_directory
+
+ logger.info("SyncImages: deleted=False, images_path=%s" % images_path)
+
+ available_images = {}
+ if os.path.exists(images_path):
+ for f in os.listdir(images_path):
+ filename = os.path.join(images_path, f)
+ if os.path.isfile(filename):
+ available_images[f] = filename
+
+ logger.info("SyncImages: available_images = %s" % str(available_images))
+
+ images = Image.objects.all()
+ image_names = [image.name for image in images]
+
+ for image_name in available_images:
+ #remove file extension
+ clean_name = ".".join(image_name.split('.')[:-1])
+ if clean_name not in image_names:
+ logger.info("SyncImages: adding %s" % clean_name)
+ image = Image(name=clean_name,
+ disk_format='raw',
+ container_format='bare',
+ path = available_images[image_name])
+ image.save()
+
+ return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
+
+ def sync_record(self, image):
+ image.save()
diff --git a/xos/synchronizers/openstack/steps/sync_instances.py b/xos/synchronizers/openstack/steps/sync_instances.py
new file mode 100644
index 0000000..335ca4a
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_instances.py
@@ -0,0 +1,174 @@
+import os
+import base64
+import socket
+from django.db.models import F, Q
+from xos.config import Config
+from xos.settings import RESTAPI_HOSTNAME, RESTAPI_PORT
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from core.models.instance import Instance
+from core.models.slice import Slice, SlicePrivilege, ControllerSlice
+from core.models.network import Network, NetworkSlice, ControllerNetwork
+from synchronizers.base.ansible import *
+from synchronizers.base.syncstep import *
+from xos.logger import observer_logger as logger
+
+def escape(s):
+ s = s.replace('\n',r'\n').replace('"',r'\"')
+ return s
+
+class SyncInstances(OpenStackSyncStep):
+ provides=[Instance]
+ requested_interval=0
+ observes=Instance
+ playbook='sync_instances.yaml'
+
+ def fetch_pending(self, deletion=False):
+ objs = super(SyncInstances, self).fetch_pending(deletion)
+ objs = [x for x in objs if x.isolation=="vm"]
+ return objs
+
+ def get_userdata(self, instance, pubkeys):
+ userdata = '#cloud-config\n\nopencloud:\n slicename: "%s"\n hostname: "%s"\n restapi_hostname: "%s"\n restapi_port: "%s"\n' % (instance.slice.name, instance.node.name, RESTAPI_HOSTNAME, str(RESTAPI_PORT))
+ userdata += 'ssh_authorized_keys:\n'
+ for key in pubkeys:
+ userdata += ' - %s\n' % key
+ return userdata
+
+ def map_sync_inputs(self, instance):
+ inputs = {}
+ metadata_update = {}
+ if (instance.numberCores):
+ metadata_update["cpu_cores"] = str(instance.numberCores)
+
+ for tag in instance.slice.tags.all():
+ if tag.name.startswith("sysctl-"):
+ metadata_update[tag.name] = tag.value
+
+ slice_memberships = SlicePrivilege.objects.filter(slice=instance.slice)
+ pubkeys = set([sm.user.public_key for sm in slice_memberships if sm.user.public_key])
+ if instance.creator.public_key:
+ pubkeys.add(instance.creator.public_key)
+
+ if instance.slice.creator.public_key:
+ pubkeys.add(instance.slice.creator.public_key)
+
+ if instance.slice.service and instance.slice.service.public_key:
+ pubkeys.add(instance.slice.service.public_key)
+
+ nics = []
+ networks = [ns.network for ns in NetworkSlice.objects.filter(slice=instance.slice)]
+ controller_networks = ControllerNetwork.objects.filter(network__in=networks,
+ controller=instance.node.site_deployment.controller)
+
+ for controller_network in controller_networks:
+
+ # Lenient exception - causes slow backoff
+ if controller_network.network.template.visibility == 'private' and \
+ controller_network.network.template.translation == 'none':
+ if not controller_network.net_id:
+ raise DeferredException("Instance %s Private Network %s has no id; Try again later" % (instance, controller_network.network.name))
+ nics.append(controller_network.net_id)
+
+ # now include network template
+ network_templates = [network.template.shared_network_name for network in networks \
+ if network.template.shared_network_name]
+
+ #driver = self.driver.client_driver(caller=instance.creator, tenant=instance.slice.name, controller=instance.controllerNetwork)
+ driver = self.driver.admin_driver(tenant='admin', controller=instance.node.site_deployment.controller)
+ nets = driver.shell.quantum.list_networks()['networks']
+ for net in nets:
+ if net['name'] in network_templates:
+ nics.append(net['id'])
+
+ if (not nics):
+ for net in nets:
+ if net['name']=='public':
+ nics.append(net['id'])
+
+ image_name = None
+ controller_images = instance.image.controllerimages.filter(controller=instance.node.site_deployment.controller)
+ if controller_images:
+ image_name = controller_images[0].image.name
+ logger.info("using image from ControllerImage object: " + str(image_name))
+
+ if image_name is None:
+ controller_driver = self.driver.admin_driver(controller=instance.node.site_deployment.controller)
+ images = controller_driver.shell.glanceclient.images.list()
+ for image in images:
+ if image.name == instance.image.name or not image_name:
+ image_name = image.name
+ logger.info("using image from glance: " + str(image_name))
+
+ try:
+ legacy = Config().observer_legacy
+ except:
+ legacy = False
+
+ if (legacy):
+ host_filter = instance.node.name.split('.',1)[0]
+ else:
+ host_filter = instance.node.name.strip()
+
+ availability_zone_filter = 'nova:%s'%host_filter
+ instance_name = '%s-%d'%(instance.slice.name,instance.id)
+ self.instance_name = instance_name
+
+ userData = self.get_userdata(instance, pubkeys)
+ if instance.userData:
+ userData += instance.userData
+
+ controller = instance.node.site_deployment.controller
+ fields = {'endpoint':controller.auth_url,
+ 'endpoint_v3': controller.auth_url_v3,
+ 'domain': controller.domain,
+ 'admin_user': instance.creator.email,
+ 'admin_password': instance.creator.remote_password,
+ 'admin_tenant': instance.slice.name,
+ 'tenant': instance.slice.name,
+ 'tenant_description': instance.slice.description,
+ 'name':instance_name,
+ 'ansible_tag':instance_name,
+ 'availability_zone': availability_zone_filter,
+ 'image_name':image_name,
+ 'flavor_name':instance.flavor.name,
+ 'nics':nics,
+ 'meta':metadata_update,
+ 'user_data':r'%s'%escape(userData)}
+ return fields
+
+
+ def map_sync_outputs(self, instance, res):
+ instance_id = res[0]['info']['OS-EXT-SRV-ATTR:instance_name']
+ instance_uuid = res[0]['id']
+
+ try:
+ hostname = res[0]['info']['OS-EXT-SRV-ATTR:hypervisor_hostname']
+ ip = socket.gethostbyname(hostname)
+ instance.ip = ip
+ except:
+ pass
+
+ instance.instance_id = instance_id
+ instance.instance_uuid = instance_uuid
+ instance.instance_name = self.instance_name
+ instance.save()
+
+
+ def map_delete_inputs(self, instance):
+ controller_register = json.loads(instance.node.site_deployment.controller.backend_register)
+
+ if (controller_register.get('disabled',False)):
+ raise InnocuousException('Controller %s is disabled'%instance.node.site_deployment.controller.name)
+
+ instance_name = '%s-%d'%(instance.slice.name,instance.id)
+ controller = instance.node.site_deployment.controller
+ input = {'endpoint':controller.auth_url,
+ 'admin_user': instance.creator.email,
+ 'admin_password': instance.creator.remote_password,
+ 'admin_tenant': instance.slice.name,
+ 'tenant': instance.slice.name,
+ 'tenant_description': instance.slice.description,
+ 'name':instance_name,
+ 'ansible_tag':instance_name,
+ 'delete': True}
+ return input
diff --git a/xos/openstack_observer/steps/sync_instances.yaml b/xos/synchronizers/openstack/steps/sync_instances.yaml
similarity index 100%
copy from xos/openstack_observer/steps/sync_instances.yaml
copy to xos/synchronizers/openstack/steps/sync_instances.yaml
diff --git a/xos/synchronizers/openstack/steps/sync_object.py b/xos/synchronizers/openstack/steps/sync_object.py
new file mode 100644
index 0000000..a6a939f
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_object.py
@@ -0,0 +1,20 @@
+import os
+import base64
+from collections import defaultdict
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from synchronizers.base.syncstep import *
+from core.models import *
+from synchronizers.base.ansible import *
+from openstack.driver import OpenStackDriver
+from xos.logger import observer_logger as logger
+import json
+
+class SyncObject(OpenStackSyncStep):
+ provides=[] # Caller fills this in
+ requested_interval=0
+ observes=[] # Caller fills this in
+
+ def sync_record(self, r):
+ raise DeferredException('Waiting for Service dependency: %r'%r)
diff --git a/xos/synchronizers/openstack/steps/sync_ports.py b/xos/synchronizers/openstack/steps/sync_ports.py
new file mode 100644
index 0000000..21376e5
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_ports.py
@@ -0,0 +1,196 @@
+import os
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from core.models import Controller
+from core.models.network import *
+from xos.logger import observer_logger as logger
+
+class SyncPorts(OpenStackSyncStep):
+ requested_interval = 0 # 3600
+ provides=[Port]
+ observes=Port
+
+ # The way it works is to enumerate the all of the ports that quantum
+ # has, and then work backward from each port's network-id to determine
+ # which Network is associated from the port.
+
+ def call(self, **args):
+ logger.info("sync'ing network instances")
+
+ ports = Port.objects.all()
+ ports_by_id = {}
+ ports_by_neutron_port = {}
+ for port in ports:
+ ports_by_id[port.id] = port
+ ports_by_neutron_port[port.port_id] = port
+
+ networks = Network.objects.all()
+ networks_by_id = {}
+ for network in networks:
+ for nd in network.controllernetworks.all():
+ networks_by_id[nd.net_id] = network
+
+ #logger.info("networks_by_id = ")
+ #for (network_id, network) in networks_by_id.items():
+ # logger.info(" %s: %s" % (network_id, network.name))
+
+ instances = Instance.objects.all()
+ instances_by_instance_uuid = {}
+ for instance in instances:
+ instances_by_instance_uuid[instance.instance_uuid] = instance
+
+ # Get all ports in all controllers
+
+ ports_by_id = {}
+ templates_by_id = {}
+ for controller in Controller.objects.all():
+ if not controller.admin_tenant:
+ logger.info("controller %s has no admin_tenant" % controller)
+ continue
+ try:
+ driver = self.driver.admin_driver(controller = controller)
+ ports = driver.shell.quantum.list_ports()["ports"]
+ except:
+ logger.log_exc("failed to get ports from controller %s" % controller)
+ continue
+
+ for port in ports:
+ ports_by_id[port["id"]] = port
+
+ # public-nat and public-dedicated networks don't have a net-id anywhere
+ # in the data model, so build up a list of which ids map to which network
+ # templates.
+ try:
+ neutron_networks = driver.shell.quantum.list_networks()["networks"]
+ except:
+ print "failed to get networks from controller %s" % controller
+ continue
+ for network in neutron_networks:
+ for template in NetworkTemplate.objects.all():
+ if template.shared_network_name == network["name"]:
+ templates_by_id[network["id"]] = template
+
+ for port in ports_by_id.values():
+ #logger.info("port %s" % str(port))
+ if port["id"] in ports_by_neutron_port:
+ # we already have it
+ #logger.info("already accounted for port %s" % port["id"])
+ continue
+
+ if port["device_owner"] != "compute:nova":
+ # we only want the ports that connect to instances
+ #logger.info("port %s is not a compute port, it is a %s" % (port["id"], port["device_owner"]))
+ continue
+
+ instance = instances_by_instance_uuid.get(port['device_id'], None)
+ if not instance:
+ logger.info("no instance for port %s device_id %s" % (port["id"], port['device_id']))
+ continue
+
+ network = networks_by_id.get(port['network_id'], None)
+ if not network:
+ # maybe it's public-nat or public-dedicated. Search the templates for
+ # the id, then see if the instance's slice has some network that uses
+ # that template
+ template = templates_by_id.get(port['network_id'], None)
+ if template and instance.slice:
+ for candidate_network in instance.slice.networks.all():
+ if candidate_network.template == template:
+ network=candidate_network
+ if not network:
+ logger.info("no network for port %s network %s" % (port["id"], port["network_id"]))
+
+ # we know it's associated with a instance, but we don't know
+ # which network it is part of.
+
+ continue
+
+ if network.template.shared_network_name:
+ # If it's a shared network template, then more than one network
+ # object maps to the quantum network. We have to do a whole bunch
+ # of extra work to find the right one.
+ networks = network.template.network_set.all()
+ network = None
+ for candidate_network in networks:
+ if (candidate_network.owner == instance.slice):
+ logger.info("found network %s" % candidate_network)
+ network = candidate_network
+
+ if not network:
+ logger.info("failed to find the correct network for a shared template for port %s network %s" % (port["id"], port["network_id"]))
+ continue
+
+ if not port["fixed_ips"]:
+ logger.info("port %s has no fixed_ips" % port["id"])
+ continue
+
+ ip=port["fixed_ips"][0]["ip_address"]
+ mac=port["mac_address"]
+ logger.info("creating Port (%s, %s, %s, %s)" % (str(network), str(instance), ip, str(port["id"])))
+
+ ns = Port(network=network,
+ instance=instance,
+ ip=ip,
+ mac=mac,
+ port_id=port["id"])
+
+ try:
+ ns.save()
+ except:
+ logger.log_exc("failed to save port %s" % str(ns))
+ continue
+
+ # For ports that were created by the user, find that ones
+ # that don't have neutron ports, and create them.
+ for port in Port.objects.filter(Q(port_id__isnull=True), Q(instance__isnull=False) ):
+ logger.info("XXX working on port %s" % port)
+ controller = port.instance.node.site_deployment.controller
+ slice = port.instance.slice
+
+ if controller:
+ cn=port.network.controllernetworks.filter(controller=controller)
+ if not cn:
+ logger.log_exc("no controllernetwork for %s" % port)
+ continue
+ cn=cn[0]
+ if cn.lazy_blocked:
+ cn.lazy_blocked=False
+ cn.save()
+ logger.info("deferring port %s because controllerNetwork was lazy-blocked" % port)
+ continue
+ if not cn.net_id:
+ logger.info("deferring port %s because controllerNetwork does not have a port-id yet" % port)
+ continue
+ try:
+ # We need to use a client driver that specifies the tenant
+ # of the destination instance. Nova-compute will not connect
+ # ports to instances if the port's tenant does not match
+ # the instance's tenant.
+
+ # A bunch of stuff to compensate for OpenStackDriver.client_driveR()
+ # not being in working condition.
+ from openstack.client import OpenStackClient
+ from openstack.driver import OpenStackDriver
+ caller = port.network.owner.creator
+ auth = {'username': caller.email,
+ 'password': caller.remote_password,
+ 'tenant': slice.name}
+ client = OpenStackClient(controller=controller, **auth) # cacert=self.config.nova_ca_ssl_cert,
+ driver = OpenStackDriver(client=client)
+
+ neutron_port = driver.shell.quantum.create_port({"port": {"network_id": cn.net_id}})["port"]
+ port.port_id = neutron_port["id"]
+ if neutron_port["fixed_ips"]:
+ port.ip = neutron_port["fixed_ips"][0]["ip_address"]
+ port.mac = neutron_port["mac_address"]
+ except:
+ logger.log_exc("failed to create neutron port for %s" % port)
+ continue
+ port.save()
+
+ def delete_record(self, network_instance):
+ # Nothing to do, this is an OpenCloud object
+ pass
+
diff --git a/xos/synchronizers/openstack/steps/sync_roles.py b/xos/synchronizers/openstack/steps/sync_roles.py
new file mode 100644
index 0000000..e859316
--- /dev/null
+++ b/xos/synchronizers/openstack/steps/sync_roles.py
@@ -0,0 +1,23 @@
+import os
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.openstacksyncstep import OpenStackSyncStep
+from core.models.role import Role
+from core.models.site import SiteRole, Controller, ControllerRole
+from core.models.slice import SliceRole
+from xos.logger import observer_logger as logger
+
+class SyncRoles(OpenStackSyncStep):
+ provides=[Role]
+ requested_interval=0
+ observes=[SiteRole,SliceRole,ControllerRole]
+
+ def sync_record(self, role):
+ if not role.enacted:
+ controllers = Controller.objects.all()
+ for controller in controllers:
+ driver = self.driver.admin_driver(controller=controller)
+ driver.create_role(role.role)
+ role.save()
+
diff --git a/xos/openstack_observer/steps/teardown_container.yaml b/xos/synchronizers/openstack/steps/teardown_container.yaml
similarity index 100%
copy from xos/openstack_observer/steps/teardown_container.yaml
copy to xos/synchronizers/openstack/steps/teardown_container.yaml
diff --git a/xos/synchronizers/openstack/syncstep.py b/xos/synchronizers/openstack/syncstep.py
new file mode 100644
index 0000000..bdab8f3
--- /dev/null
+++ b/xos/synchronizers/openstack/syncstep.py
@@ -0,0 +1,307 @@
+import os
+import base64
+from datetime import datetime
+from xos.config import Config
+from xos.logger import Logger, logging
+from synchronizers.base.steps import *
+from django.db.models import F, Q
+from core.models import *
+from django.db import reset_queries
+from synchronizers.base.ansible import *
+from generate.dependency_walker import *
+
+from time import time
+import json
+import time
+import pdb
+
+logger = Logger(level=logging.INFO)
+
+def f7(seq):
+ seen = set()
+ seen_add = seen.add
+ return [ x for x in seq if not (x in seen or seen_add(x))]
+
+def elim_dups(backend_str):
+ strs = backend_str.split(' // ')
+ strs2 = f7(strs)
+ return ' // '.join(strs2)
+
+def deepgetattr(obj, attr):
+ return reduce(getattr, attr.split('.'), obj)
+
+
+class InnocuousException(Exception):
+ pass
+
+class DeferredException(Exception):
+ pass
+
+class FailedDependency(Exception):
+ pass
+
+class SyncStep(object):
+ """ An XOS Sync step.
+
+ Attributes:
+ psmodel Model name the step synchronizes
+ dependencies list of names of models that must be synchronized first if the current model depends on them
+ """
+
+ # map_sync_outputs can return this value to cause a step to be marked
+ # successful without running ansible. Used for sync_network_controllers
+ # on nat networks.
+ SYNC_WITHOUT_RUNNING = "sync_without_running"
+
+ slow=False
+ def get_prop(self, prop):
+ try:
+ sync_config_dir = Config().sync_config_dir
+ except:
+ sync_config_dir = '/etc/xos/sync'
+ prop_config_path = '/'.join(sync_config_dir,self.name,prop)
+ return open(prop_config_path).read().rstrip()
+
+ def __init__(self, **args):
+ """Initialize a sync step
+ Keyword arguments:
+ name -- Name of the step
+ provides -- XOS models sync'd by this step
+ """
+ dependencies = []
+ self.driver = args.get('driver')
+ self.error_map = args.get('error_map')
+
+ try:
+ self.soft_deadline = int(self.get_prop('soft_deadline_seconds'))
+ except:
+ self.soft_deadline = 5 # 5 seconds
+
+ return
+
+ def fetch_pending(self, deletion=False):
+ # This is the most common implementation of fetch_pending
+ # Steps should override it if they have their own logic
+ # for figuring out what objects are outstanding.
+
+ main_objs = self.observes
+ if (type(main_objs) is not list):
+ main_objs=[main_objs]
+
+ objs = []
+ for main_obj in main_objs:
+ if (not deletion):
+ lobjs = main_obj.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False),Q(no_sync=False))
+ else:
+ lobjs = main_obj.deleted_objects.all()
+ objs.extend(lobjs)
+
+ return objs
+ #return Instance.objects.filter(ip=None)
+
+ def check_dependencies(self, obj, failed):
+ for dep in self.dependencies:
+ peer_name = dep[0].lower() + dep[1:] # django names are camelCased with the first letter lower
+
+ peer_objects=[]
+ try:
+ peer_names = plural(peer_name)
+ peer_object_list=[]
+
+ try:
+ peer_object_list.append(deepgetattr(obj, peer_name))
+ except:
+ pass
+
+ try:
+ peer_object_list.append(deepgetattr(obj, peer_names))
+ except:
+ pass
+
+ for peer_object in peer_object_list:
+ try:
+ peer_objects.extend(peer_object.all())
+ except AttributeError:
+ peer_objects.append(peer_object)
+ except:
+ peer_objects = []
+
+ if (hasattr(obj,'controller')):
+ try:
+ peer_objects = filter(lambda o:o.controller==obj.controller, peer_objects)
+ except AttributeError:
+ pass
+
+ if (failed in peer_objects):
+ if (obj.backend_status!=failed.backend_status):
+ obj.backend_status = failed.backend_status
+ obj.save(update_fields=['backend_status'])
+ raise FailedDependency("Failed dependency for %s:%s peer %s:%s failed %s:%s" % (obj.__class__.__name__, str(getattr(obj,"pk","no_pk")), peer_object.__class__.__name__, str(getattr(peer_object,"pk","no_pk")), failed.__class__.__name__, str(getattr(failed,"pk","no_pk"))))
+
+
+ def sync_record(self, o):
+ try:
+ controller = o.get_controller()
+ controller_register = json.loads(o.node.site_deployment.controller.backend_register)
+
+ if (controller_register.get('disabled',False)):
+ raise InnocuousException('Controller %s is disabled'%sliver.node.site_deployment.controller.name)
+ except AttributeError:
+ pass
+
+ tenant_fields = self.map_sync_inputs(o)
+ if tenant_fields == SyncStep.SYNC_WITHOUT_RUNNING:
+ return
+ main_objs=self.observes
+ if (type(main_objs) is list):
+ main_objs=main_objs[0]
+
+ path = ''.join(main_objs.__name__).lower()
+ res = run_template(self.playbook,tenant_fields,path=path)
+
+ try:
+ self.map_sync_outputs(o,res)
+ except AttributeError:
+ pass
+
+ def delete_record(self, o):
+ try:
+ controller = o.get_controller()
+ controller_register = json.loads(o.node.site_deployment.controller.backend_register)
+
+ if (controller_register.get('disabled',False)):
+ raise InnocuousException('Controller %s is disabled'%sliver.node.site_deployment.controller.name)
+ except AttributeError:
+ pass
+
+ tenant_fields = self.map_delete_inputs(o)
+
+ main_objs=self.observes
+ if (type(main_objs) is list):
+ main_objs=main_objs[0]
+
+ path = ''.join(main_objs.__name__).lower()
+
+ tenant_fields['delete']=True
+ res = run_template(self.playbook,tenant_fields,path=path)
+ try:
+ self.map_delete_outputs(o,res)
+ except AttributeError:
+ pass
+
+ def call(self, failed=[], deletion=False):
+ #if ('Instance' in self.__class__.__name__):
+ # pdb.set_trace()
+
+ pending = self.fetch_pending(deletion)
+
+ for o in pending:
+ # another spot to clean up debug state
+ try:
+ reset_queries()
+ except:
+ # this shouldn't happen, but in case it does, catch it...
+ logger.log_exc("exception in reset_queries")
+
+ sync_failed = False
+ try:
+ backoff_disabled = Config().observer_backoff_disabled
+ except:
+ backoff_disabled = 0
+
+ try:
+ scratchpad = json.loads(o.backend_register)
+ if (scratchpad):
+ next_run = scratchpad['next_run']
+ if (not backoff_disabled and next_run>time.time()):
+ sync_failed = True
+ except:
+ logger.log_exc("Exception while loading scratchpad")
+ pass
+
+ if (not sync_failed):
+ try:
+ for f in failed:
+ self.check_dependencies(o,f) # Raises exception if failed
+ if (deletion):
+ self.delete_record(o)
+ o.delete(purge=True)
+ else:
+ self.sync_record(o)
+ o.enacted = datetime.now() # Is this the same timezone? XXX
+ scratchpad = {'next_run':0, 'exponent':0, 'last_success':time.time()}
+ o.backend_register = json.dumps(scratchpad)
+ o.backend_status = "1 - OK"
+ o.save(update_fields=['enacted','backend_status','backend_register'])
+ except (InnocuousException,Exception,DeferredException) as e:
+ logger.log_exc("sync step failed!")
+ try:
+ if (o.backend_status.startswith('2 - ')):
+ str_e = '%s // %r'%(o.backend_status[4:],e)
+ str_e = elim_dups(str_e)
+ else:
+ str_e = '%r'%e
+ except:
+ str_e = '%r'%e
+
+ try:
+ error = self.error_map.map(str_e)
+ except:
+ error = '%s'%str_e
+
+ if isinstance(e, InnocuousException) and not force_error:
+ o.backend_status = '1 - %s'%error
+ else:
+ o.backend_status = '2 - %s'%error
+
+ try:
+ scratchpad = json.loads(o.backend_register)
+ scratchpad['exponent']
+ except:
+ logger.log_exc("Exception while updating scratchpad")
+ scratchpad = {'next_run':0, 'exponent':0, 'last_success':time.time(),'failures':0}
+
+ # Second failure
+ if (scratchpad['exponent']):
+ if isinstance(e,DeferredException):
+ delay = scratchpad['exponent'] * 60 # 1 minute
+ else:
+ delay = scratchpad['exponent'] * 600 # 10 minutes
+ # cap delays at 8 hours
+ if (delay>8*60*60):
+ delay=8*60*60
+ scratchpad['next_run'] = time.time() + delay
+
+ try:
+ scratchpad['exponent']+=1
+ except:
+ scratchpad['exponent']=1
+
+ try:
+ scratchpad['failures']+=1
+ except KeyError:
+ scratchpad['failures']=1
+
+ scratchpad['last_failure']=time.time()
+
+ o.backend_register = json.dumps(scratchpad)
+
+ # TOFIX:
+ # DatabaseError: value too long for type character varying(140)
+ if (o.pk):
+ try:
+ o.backend_status = o.backend_status[:1024]
+ o.save(update_fields=['backend_status','backend_register','updated'])
+ except:
+ print "Could not update backend status field!"
+ pass
+ sync_failed = True
+
+
+ if (sync_failed):
+ failed.append(o)
+
+ return failed
+
+ def __call__(self, **args):
+ return self.call(**args)
diff --git a/xos/openstack_observer/templates/container.conf.j2 b/xos/synchronizers/openstack/templates/container.conf.j2
similarity index 100%
copy from xos/openstack_observer/templates/container.conf.j2
copy to xos/synchronizers/openstack/templates/container.conf.j2
diff --git a/xos/openstack_observer/templates/container.service.j2 b/xos/synchronizers/openstack/templates/container.service.j2
similarity index 100%
copy from xos/openstack_observer/templates/container.service.j2
copy to xos/synchronizers/openstack/templates/container.service.j2
diff --git a/xos/openstack_observer/templates/start-container.sh.j2 b/xos/synchronizers/openstack/templates/start-container.sh.j2
similarity index 100%
copy from xos/openstack_observer/templates/start-container.sh.j2
copy to xos/synchronizers/openstack/templates/start-container.sh.j2
diff --git a/xos/openstack_observer/templates/stop-container.sh.j2 b/xos/synchronizers/openstack/templates/stop-container.sh.j2
similarity index 100%
copy from xos/openstack_observer/templates/stop-container.sh.j2
copy to xos/synchronizers/openstack/templates/stop-container.sh.j2
diff --git a/xos/openstack_observer/toposort.py b/xos/synchronizers/openstack/toposort.py
similarity index 100%
copy from xos/openstack_observer/toposort.py
copy to xos/synchronizers/openstack/toposort.py
diff --git a/xos/synchronizers/openstack/xos-synchronizer.py b/xos/synchronizers/openstack/xos-synchronizer.py
new file mode 100644
index 0000000..3fffd33
--- /dev/null
+++ b/xos/synchronizers/openstack/xos-synchronizer.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python
+import os
+import argparse
+import sys
+
+sys.path.append('/opt/xos')
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+from synchronizers.base.backend import Backend
+from xos.config import Config, DEFAULT_CONFIG_FN
+from core.models import Instance
+from xos.logger import Logger, logging, logger
+from django.db import ProgrammingError
+import time
+
+try:
+ from django import setup as django_setup # django 1.7
+except:
+ django_setup = False
+
+config = Config()
+
+# after http://www.erlenstar.demon.co.uk/unix/faq_2.html
+def daemon():
+ """Daemonize the current process."""
+ if os.fork() != 0: os._exit(0)
+ os.setsid()
+ if os.fork() != 0: os._exit(0)
+ os.umask(0)
+ devnull = os.open(os.devnull, os.O_RDWR)
+ os.dup2(devnull, 0)
+ # xxx fixme - this is just to make sure that nothing gets stupidly lost - should use devnull
+ logdir=os.path.dirname(config.observer_logfile)
+ # when installed in standalone we might not have httpd installed
+ if not os.path.isdir(logdir): os.mkdir(logdir)
+ crashlog = os.open('%s'%config.observer_logfile, os.O_RDWR | os.O_APPEND | os.O_CREAT, 0644)
+ os.dup2(crashlog, 1)
+ os.dup2(crashlog, 2)
+
+ if hasattr(config, "observer_pidfile"):
+ pidfile = config.get("observer_pidfile")
+ else:
+ pidfile = "/var/run/xosobserver.pid"
+ try:
+ file(pidfile,"w").write(str(os.getpid()))
+ except:
+ print "failed to create pidfile %s" % pidfile
+
+def main():
+ # Generate command line parser
+ parser = argparse.ArgumentParser(usage='%(prog)s [options]')
+ parser.add_argument('-d', '--daemon', dest='daemon', action='store_true', default=False,
+ help='Run as daemon.')
+ # smbaker: util/config.py parses sys.argv[] directly to get config file name; include the option here to avoid
+ # throwing unrecognized argument exceptions
+ parser.add_argument('-C', '--config', dest='config_file', action='store', default=DEFAULT_CONFIG_FN,
+ help='Name of config file.')
+ args = parser.parse_args()
+
+ if args.daemon: daemon()
+
+ if django_setup: # 1.7
+ django_setup()
+
+ models_active = False
+ wait = False
+ while not models_active:
+ try:
+ _ = Instance.objects.first()
+ models_active = True
+ except ProgrammingError:
+ logger.info('Waiting for data model to come up before starting...')
+ wait = True
+
+ if (wait):
+ time.sleep(60) # Safety factor, seeing that we stumbled waiting for the data model to come up.
+ backend = Backend()
+ backend.run()
+
+if __name__ == '__main__':
+
+ main()
diff --git a/xos/rr_observer/configurationPush.py b/xos/synchronizers/requestrouter/configurationPush.py
similarity index 100%
rename from xos/rr_observer/configurationPush.py
rename to xos/synchronizers/requestrouter/configurationPush.py
diff --git a/xos/synchronizers/requestrouter/deleters/servicemap_deleter.py b/xos/synchronizers/requestrouter/deleters/servicemap_deleter.py
new file mode 100644
index 0000000..d2efd64
--- /dev/null
+++ b/xos/synchronizers/requestrouter/deleters/servicemap_deleter.py
@@ -0,0 +1,42 @@
+import os
+import sys
+import traceback
+from services.requestrouter.models import ServiceMap
+from synchronizers.base.deleter import Deleter
+from xos.logger import Logger, logging
+from xos.config import Config, XOS_DIR
+
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+from rrlib import RequestRouterLibrary
+from configurationPush import ConfigurationPush
+import rrlib_config
+
+logger = Logger(level=logging.INFO)
+
+class ServiceMapDeleter(Deleter, RequestRouterLibrary, ConfigurationPush):
+ model='ServiceMap'
+
+ def __init__(self, **args):
+ Deleter.__init__(self, **args)
+ RequestRouterLibrary.__init__(self)
+ ConfigurationPush.__init__(self)
+
+
+ def call(self, pk, model_dict):
+ try:
+ servicemap = ServiceMap.objects.get(pk=pk)
+ service_uid = self.get_servicemap_uid(servicemap)
+ self.config_push(service_uid, rrlib_config.REDIR_USER, XOS_DIR + "/observers/requestrouter/playbook/site_redir_delete.yml", "/etc/ansible/requestrouter/dnsredir/hosts")
+ self.config_push(service_uid, rrlib_config.DEMUX_USER, XOS_DIR + "/observers/requestrouter/playbook/site_demux_delete.yml", "/etc/ansible/requestrouter/dnsdemux/hosts")
+ print "XXX delete ServiceMap %s", servicemap.name
+ return True
+ except Exception, e:
+ traceback.print_exc()
+ logger.exception("Failed to erase map '%s'" % map_name)
+ return False
+
+if __name__ == "__main__":
+ smap = ServiceMapDeleter()
+ smap.call( 6, {'name': 'Service23'} )
diff --git a/xos/rr_observer/model-deps b/xos/synchronizers/requestrouter/model-deps
similarity index 100%
rename from xos/rr_observer/model-deps
rename to xos/synchronizers/requestrouter/model-deps
diff --git a/xos/rr_observer/playbook/roles/delete_demux/handlers/main.yml b/xos/synchronizers/requestrouter/playbook/roles/delete_demux/handlers/main.yml
similarity index 100%
rename from xos/rr_observer/playbook/roles/delete_demux/handlers/main.yml
rename to xos/synchronizers/requestrouter/playbook/roles/delete_demux/handlers/main.yml
diff --git a/xos/rr_observer/playbook/roles/delete_demux/tasks/main.yml b/xos/synchronizers/requestrouter/playbook/roles/delete_demux/tasks/main.yml
similarity index 100%
rename from xos/rr_observer/playbook/roles/delete_demux/tasks/main.yml
rename to xos/synchronizers/requestrouter/playbook/roles/delete_demux/tasks/main.yml
diff --git a/xos/rr_observer/playbook/roles/delete_demux/vars/main.yml b/xos/synchronizers/requestrouter/playbook/roles/delete_demux/vars/main.yml
similarity index 100%
rename from xos/rr_observer/playbook/roles/delete_demux/vars/main.yml
rename to xos/synchronizers/requestrouter/playbook/roles/delete_demux/vars/main.yml
diff --git a/xos/rr_observer/playbook/roles/delete_redir/handlers/main.yml b/xos/synchronizers/requestrouter/playbook/roles/delete_redir/handlers/main.yml
similarity index 100%
rename from xos/rr_observer/playbook/roles/delete_redir/handlers/main.yml
rename to xos/synchronizers/requestrouter/playbook/roles/delete_redir/handlers/main.yml
diff --git a/xos/rr_observer/playbook/roles/delete_redir/tasks/main.yml b/xos/synchronizers/requestrouter/playbook/roles/delete_redir/tasks/main.yml
similarity index 100%
rename from xos/rr_observer/playbook/roles/delete_redir/tasks/main.yml
rename to xos/synchronizers/requestrouter/playbook/roles/delete_redir/tasks/main.yml
diff --git a/xos/rr_observer/playbook/roles/delete_redir/vars/main.yml b/xos/synchronizers/requestrouter/playbook/roles/delete_redir/vars/main.yml
similarity index 100%
rename from xos/rr_observer/playbook/roles/delete_redir/vars/main.yml
rename to xos/synchronizers/requestrouter/playbook/roles/delete_redir/vars/main.yml
diff --git a/xos/rr_observer/playbook/roles/demux/handlers/main.yml b/xos/synchronizers/requestrouter/playbook/roles/demux/handlers/main.yml
similarity index 100%
rename from xos/rr_observer/playbook/roles/demux/handlers/main.yml
rename to xos/synchronizers/requestrouter/playbook/roles/demux/handlers/main.yml
diff --git a/xos/rr_observer/playbook/roles/demux/tasks/main.yml b/xos/synchronizers/requestrouter/playbook/roles/demux/tasks/main.yml
similarity index 100%
rename from xos/rr_observer/playbook/roles/demux/tasks/main.yml
rename to xos/synchronizers/requestrouter/playbook/roles/demux/tasks/main.yml
diff --git a/xos/rr_observer/playbook/roles/demux/vars/main.yml b/xos/synchronizers/requestrouter/playbook/roles/demux/vars/main.yml
similarity index 100%
rename from xos/rr_observer/playbook/roles/demux/vars/main.yml
rename to xos/synchronizers/requestrouter/playbook/roles/demux/vars/main.yml
diff --git a/xos/rr_observer/playbook/roles/redir/handlers/main.yml b/xos/synchronizers/requestrouter/playbook/roles/redir/handlers/main.yml
similarity index 100%
rename from xos/rr_observer/playbook/roles/redir/handlers/main.yml
rename to xos/synchronizers/requestrouter/playbook/roles/redir/handlers/main.yml
diff --git a/xos/rr_observer/playbook/roles/redir/tasks/main.yml b/xos/synchronizers/requestrouter/playbook/roles/redir/tasks/main.yml
similarity index 100%
rename from xos/rr_observer/playbook/roles/redir/tasks/main.yml
rename to xos/synchronizers/requestrouter/playbook/roles/redir/tasks/main.yml
diff --git a/xos/rr_observer/playbook/roles/redir/vars/main.yml b/xos/synchronizers/requestrouter/playbook/roles/redir/vars/main.yml
similarity index 100%
rename from xos/rr_observer/playbook/roles/redir/vars/main.yml
rename to xos/synchronizers/requestrouter/playbook/roles/redir/vars/main.yml
diff --git a/xos/rr_observer/playbook/site_demux.yml b/xos/synchronizers/requestrouter/playbook/site_demux.yml
similarity index 100%
rename from xos/rr_observer/playbook/site_demux.yml
rename to xos/synchronizers/requestrouter/playbook/site_demux.yml
diff --git a/xos/rr_observer/playbook/site_demux_delete.yml b/xos/synchronizers/requestrouter/playbook/site_demux_delete.yml
similarity index 100%
rename from xos/rr_observer/playbook/site_demux_delete.yml
rename to xos/synchronizers/requestrouter/playbook/site_demux_delete.yml
diff --git a/xos/rr_observer/playbook/site_redir.yml b/xos/synchronizers/requestrouter/playbook/site_redir.yml
similarity index 100%
rename from xos/rr_observer/playbook/site_redir.yml
rename to xos/synchronizers/requestrouter/playbook/site_redir.yml
diff --git a/xos/rr_observer/playbook/site_redir_delete.yml b/xos/synchronizers/requestrouter/playbook/site_redir_delete.yml
similarity index 100%
rename from xos/rr_observer/playbook/site_redir_delete.yml
rename to xos/synchronizers/requestrouter/playbook/site_redir_delete.yml
diff --git a/xos/synchronizers/requestrouter/rr_synchronizer_config b/xos/synchronizers/requestrouter/rr_synchronizer_config
new file mode 100644
index 0000000..179540e
--- /dev/null
+++ b/xos/synchronizers/requestrouter/rr_synchronizer_config
@@ -0,0 +1,36 @@
+
+[plc]
+name=plc
+#deployment=VICCI
+deployment=VINI
+
+[db]
+name=xos
+user=plstackuser
+#password=2uMDYtJK
+password=1HL07C0E
+host=localhost
+port=5432
+
+[api]
+host=128.112.171.237
+port=8000
+ssl_key=None
+ssl_cert=None
+ca_ssl_cert=None
+ratelimit_enabled=0
+omf_enabled=0
+mail_support_address=support@localhost
+nova_enabled=True
+
+[observer]
+dependency_graph=/opt/xos/synchronizers/requestrouter/model-deps
+steps_dir=/opt/xos/synchronizers/requestrouter/steps
+deleters_dir=/opt/xos/synchronizers/requestrouter/deleters
+log_file=console
+#/var/log/hpc.log
+driver=None
+
+#[feefie]
+#client_id='vicci_dev_central'
+#user_id='pl'
diff --git a/xos/synchronizers/requestrouter/rrlib.py b/xos/synchronizers/requestrouter/rrlib.py
new file mode 100644
index 0000000..e2100b0
--- /dev/null
+++ b/xos/synchronizers/requestrouter/rrlib.py
@@ -0,0 +1,203 @@
+import os
+import base64
+import string
+import sys
+import socket
+from sets import Set
+if __name__ == '__main__':
+ sys.path.append("/opt/xos")
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+
+from xos.config import Config
+from core.models import Service
+from services.requestrouter.models import RequestRouterService, ServiceMap
+from xos.logger import Logger, logging
+import rrlib_config
+
+logger = Logger(level=logging.INFO)
+
+'''
+Conventions:
+1) All dnsredir backend will listen at port 9000+ servicemap.pk ( where pk is the primary key generated in django model)
+'''
+
+class RequestRouterLibrary:
+
+ def __init__(self):
+ pass
+
+ def gen_slice_info(self, service=None):
+ """generates instance information from slice of request router
+ """
+
+ if (service is None ):
+ service = RequestRouterService.objects.get()
+
+ mapping = {}
+ #static mapping for demo purpose
+ #mapping["node47.princeton.vicci.org"] = "128.112.171.112"
+ mapping["node48.princeton.vicci.org"] = "128.112.171.114"
+
+ '''for slice in service.service.all():
+ name = slice.name
+ for instance in slice.instances.all():
+ mapping[instance.name] = str(instance.ip)
+ '''
+ return mapping
+
+ def gen_servicemap_slice_info(self, servicemap):
+ """generates instance information from slice of servicemap
+ """
+
+ wzone = Set(['arizona', 'stanford', 'on.lab', 'housten']) # zone=1 in cooden.conf
+ ezone = Set(['princeton', 'atlanta', 'new york', 'georgia tech']) # zone=2 in coodeen.conf
+
+ mapping_zone = {}
+ mapping_ip = {}
+ slice = servicemap.slice
+ name = slice.name
+ for instance in slice.instances.all():
+ mapping_ip[instance.node.name] = socket.gethostbyname(instance.node.name)
+ #print "instance name "+instance.name+str(instance.ip)+"\n"
+ site = instance.node.site.name
+ if(site.lower() in wzone):
+ mapping_zone[instance.node.name] = str(1)
+ else:
+ mapping_zone[instance.node.name] = str(2)
+
+ return mapping_ip, mapping_zone
+
+
+
+ def gen_slice_file(self, service):
+ """ generates host file for the slice information
+ to be used by ansible to push configuration files
+ """
+
+ mapping = self.gen_slice_info(service)
+
+ fn = "/etc/ansible/requestrouter/dnsredir/hosts"
+ f = open(fn, "w")
+ for (k,v) in mapping.items():
+ f.write("%s\n" % k)
+
+ fn = "/etc/ansible/requestrouter/dnsdemux/hosts"
+ f = open(fn, "w")
+ for (k,v) in mapping.items():
+ f.write("%s\n" % k)
+
+
+ def get_servicemap_uid(self, servicemap):
+ seq = ("service_", str(servicemap.pk));
+ return "".join(seq)
+
+ def get_service_port(self, servicemap):
+ return str(9000+servicemap.pk)
+
+ def gen_dnsredir_serviceconf(self, servicemap):
+ objname = self.get_servicemap_uid(servicemap)
+
+ rr_mapping = self.gen_slice_info(None)
+
+ #generate dnsredir.conf file parameters to be used in static file.
+ mapping = {}
+ mapping["port_listen"] = self.get_service_port(servicemap)
+ mapping["configdir"] = rrlib_config.DNSREDIR_CONFIGDIR_PREFIX+objname+".d/"
+ mapping["logdir"] = rrlib_config.DNSREDIR_LOGDIR_PREFIX+objname+".d"
+ mapping["pidfile"] = rrlib_config.DNSREDIR_PIDFILE_PREFIX+objname+".pid"
+ mapping["domain_name"] = servicemap.prefix
+ mapping["heartbeat_port"] = rrlib_config.HEARTBEAT_PORT
+
+ #generate dnsredir.conf file
+
+ fn = "./temp_config/dnsredir/"+objname+".conf"
+ f = open(fn, "w")
+ for (k,v) in rr_mapping.items():
+ f.write(mapping["domain_name"]+". NS "+k+". "+v+" 3600 \n" % mapping)
+
+
+ f.write("""
+Default_TTL 30
+
+Port %(port_listen)s
+
+ConfigDir %(configdir)s
+
+MapsDir maps.d
+
+HTTPPort %(heartbeat_port)d
+
+PidFile %(pidfile)s
+
+HttpRequestPort 8081
+
+""" % mapping)
+
+ #generate configdirectory
+
+ os.mkdir("./temp_config/dnsredir/"+objname+".d")
+
+ #geenrate codeen_nodes.conf
+ mapping_ip, mapping_zone = self.gen_servicemap_slice_info(servicemap)
+
+ codeen_name = "./temp_config/dnsredir/"+objname+".d/codeen_nodes.conf"
+ f = open(codeen_name, "w")
+ for (k,v) in mapping_zone.items():
+ f.write(k+" zone="+v+" \n")
+
+ iptxt = "./temp_config/dnsredir/"+objname+".d/node-to-ip.txt"
+ f = open(iptxt, "w")
+ for (k,v) in mapping_ip.items():
+ f.write(k+" "+v+" \n")
+
+ #generate maps directory
+ os.mkdir("./temp_config/dnsredir/"+objname+".d/maps.d")
+
+ # redirection map
+ map = "./temp_config/dnsredir/"+objname+".d/maps.d/map.conf"
+ f = open(map, "w")
+ #hardcoded probable public IP masks from arizona and princeton region respectively
+ f.write("prefix "+servicemap.prefix+" \n")
+ f.write("map 150.135.211.252/32 zone 1 || zone 2 \n")
+ f.write("map 128.112.171.112/24 zone 2 || zone 1 \n")
+ f.write("map 0.0.0.0/0 zone 1 || zone 2 \n")
+
+
+ def gen_dnsdemux_serviceconf(self, servicemap):
+ '''
+ generates frontend service*.conf file for each of the service
+ It assumes that there is a dnsdemux frontend running on the RR istallation and will
+ just add a conf file for each service in /etc/dnsdemux/default
+ '''
+ objname = self.get_servicemap_uid(servicemap)
+ #generate dnsdemux.conf file parameters to be used in static file.
+
+ port_listen = self.get_service_port(servicemap)
+ domain_name = servicemap.prefix
+ #generate service specific .conf file
+
+ rr_mapping = self.gen_slice_info(None)
+
+ fn = "./temp_config/dnsdemux/"+objname+".conf"
+ f = open(fn, "w")
+
+ for (k,v) in rr_mapping.items():
+ f.write("Forward "+v+" "+port_listen+" 8081 "+domain_name+".\n")
+
+
+ def teardown_temp_configfiles(self, objname):
+ if os.path.exists("./temp_config/dnsdemux/"+objname+".conf"):
+ os.remove("./temp_config/dnsdemux/"+objname+".conf")
+ if os.path.exists("./temp_config/dnsredir/"+objname+".d/maps.d/map.conf"):
+ os.remove("./temp_config/dnsredir/"+objname+".d/maps.d/map.conf")
+ if os.path.exists("./temp_config/dnsredir/"+objname+".d/maps.d"):
+ os.rmdir("./temp_config/dnsredir/"+objname+".d/maps.d")
+ if os.path.exists("./temp_config/dnsredir/"+objname+".d/node-to-ip.txt"):
+ os.remove("./temp_config/dnsredir/"+objname+".d/node-to-ip.txt")
+ if os.path.exists("./temp_config/dnsredir/"+objname+".d/codeen_nodes.conf"):
+ os.remove("./temp_config/dnsredir/"+objname+".d/codeen_nodes.conf")
+ if os.path.exists("./temp_config/dnsredir/"+objname+".d"):
+ os.rmdir("./temp_config/dnsredir/"+objname+".d")
+ if os.path.exists("./temp_config/dnsredir/"+objname+".conf"):
+ os.remove("./temp_config/dnsredir/"+objname+".conf")
+
diff --git a/xos/rr_observer/rrlib_config.py b/xos/synchronizers/requestrouter/rrlib_config.py
similarity index 100%
rename from xos/rr_observer/rrlib_config.py
rename to xos/synchronizers/requestrouter/rrlib_config.py
diff --git a/xos/synchronizers/requestrouter/steps/sync_requestrouterservices.py b/xos/synchronizers/requestrouter/steps/sync_requestrouterservices.py
new file mode 100644
index 0000000..c9648ff
--- /dev/null
+++ b/xos/synchronizers/requestrouter/steps/sync_requestrouterservices.py
@@ -0,0 +1,46 @@
+import os
+import sys
+import base64
+import traceback
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from core.models import Service
+from services.requestrouter.models import RequestRouterService
+from xos.logger import Logger, logging
+
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+from rrlib import RequestRouterLibrary
+
+logger = Logger(level=logging.INFO)
+
+class SyncRequestRouterService(SyncStep, RequestRouterLibrary):
+ provides=[RequestRouterService]
+ requested_interval=0
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+ RequestRouterLibrary.__init__(self)
+
+ def fetch_pending(self):
+ try:
+ ret = RequestRouterService.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
+ return ret
+ except Exception, e:
+ traceback.print_exc()
+ return None
+
+ def sync_record(self, rr_service):
+ try:
+ print "syncing service!"
+ logger.info("sync'ing rr_service %s" % str(rr_service))
+ self.gen_slice_file(rr_service)
+ rr_service.save()
+ return True
+ except Exception, e:
+ traceback.print_exc()
+ return False
+
+
diff --git a/xos/synchronizers/requestrouter/steps/sync_servicemap.py b/xos/synchronizers/requestrouter/steps/sync_servicemap.py
new file mode 100644
index 0000000..bef7e42
--- /dev/null
+++ b/xos/synchronizers/requestrouter/steps/sync_servicemap.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python
+
+import os
+import sys
+import base64
+import traceback
+from django.db.models import F, Q
+from xos.config import Config, XOS_DIR
+from synchronizers.base.syncstep import SyncStep
+from core.models import Service
+from services.requestrouter.models import ServiceMap
+from xos.logger import Logger, logging
+
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+from rrlib import RequestRouterLibrary
+from configurationPush import ConfigurationPush
+import rrlib_config
+
+logger = Logger(level=logging.INFO)
+
+class SyncServiceMap(SyncStep, RequestRouterLibrary, ConfigurationPush):
+ provides=[ServiceMap]
+ requested_interval=0
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+ RequestRouterLibrary.__init__(self)
+ ConfigurationPush.__init__(self)
+
+ def fetch_pending(self):
+ try:
+ ret = ServiceMap.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
+ return ret
+ except Exception, e:
+ traceback.print_exc()
+ return None
+
+ def sync_record(self, servicemap):
+ try:
+ print "sync! %s " % self.get_servicemap_uid(servicemap)
+ self.gen_dnsredir_serviceconf(servicemap)
+ self.gen_dnsdemux_serviceconf(servicemap)
+ # push generated files from temp_config
+ service_uid = self.get_servicemap_uid(servicemap)
+ self.config_push(service_uid, rrlib_config.REDIR_USER, XOS_DIR + "/observers/requestrouter/playbook/site_redir.yml", "/etc/ansible/requestrouter/dnsredir/hosts")
+ self.config_push(service_uid, rrlib_config.DEMUX_USER, XOS_DIR + "/observers/requestrouter/playbook/site_demux.yml", "/etc/ansible/requestrouter/dnsdemux/hosts")
+ self.teardown_temp_configfiles(service_uid)
+ except Exception, e:
+ traceback.print_exc()
+ return False
+
+if __name__ == "__main__":
+ sv = SyncServiceMap()
+
+ recs = sv.fetch_pending()
+
+ for rec in recs:
+ sv.sync_record( rec )
diff --git a/xos/syndicate_storage/__init__.py b/xos/synchronizers/syndicate/__init__.py
similarity index 100%
copy from xos/syndicate_storage/__init__.py
copy to xos/synchronizers/syndicate/__init__.py
diff --git a/xos/syndicate_observer/model-deps b/xos/synchronizers/syndicate/model-deps
similarity index 100%
rename from xos/syndicate_observer/model-deps
rename to xos/synchronizers/syndicate/model-deps
diff --git a/xos/syndicate_observer/requirements.py b/xos/synchronizers/syndicate/requirements.py
similarity index 100%
rename from xos/syndicate_observer/requirements.py
rename to xos/synchronizers/syndicate/requirements.py
diff --git a/xos/synchronizers/syndicate/run.sh b/xos/synchronizers/syndicate/run.sh
new file mode 100644
index 0000000..82960a9
--- /dev/null
+++ b/xos/synchronizers/syndicate/run.sh
@@ -0,0 +1,2 @@
+export XOS_DIR=/opt/xos
+python syndicate-backend.py -C $XOS_DIR/observers/syndicate/syndicate_observer_config
diff --git a/xos/synchronizers/syndicate/start.sh b/xos/synchronizers/syndicate/start.sh
new file mode 100644
index 0000000..1c408a1
--- /dev/null
+++ b/xos/synchronizers/syndicate/start.sh
@@ -0,0 +1,2 @@
+export XOS_DIR=/opt/xos
+nohup python syndicate-backend.py -C $XOS_DIR/observers/syndicate/syndicate_observer_config > /dev/null 2>&1 &
diff --git a/xos/synchronizers/syndicate/steps/sync_volume.py b/xos/synchronizers/syndicate/steps/sync_volume.py
new file mode 100644
index 0000000..e6dc90b
--- /dev/null
+++ b/xos/synchronizers/syndicate/steps/sync_volume.py
@@ -0,0 +1,138 @@
+#!/usr/bin/env python
+
+import os
+import sys
+import traceback
+import base64
+
+if __name__ == "__main__":
+ # for testing
+ if os.getenv("OPENCLOUD_PYTHONPATH"):
+ sys.path.append( os.getenv("OPENCLOUD_PYTHONPATH") )
+ else:
+ print >> sys.stderr, "No OPENCLOUD_PYTHONPATH variable set. Assuming that OpenCloud is in PYTHONPATH"
+
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+
+
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from core.models import Service
+from services.syndicate_storage.models import Volume
+
+import logging
+from logging import Logger
+logging.basicConfig( format='[%(levelname)s] [%(module)s:%(lineno)d] %(message)s' )
+logger = logging.getLogger()
+logger.setLevel( logging.INFO )
+
+# point to planetstack
+if __name__ != "__main__":
+ if os.getenv("OPENCLOUD_PYTHONPATH") is not None:
+ sys.path.insert(0, os.getenv("OPENCLOUD_PYTHONPATH"))
+ else:
+ logger.warning("No OPENCLOUD_PYTHONPATH set; assuming your PYTHONPATH works")
+
+# syndicatelib will be in stes/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+import syndicatelib
+
+
+class SyncVolume(SyncStep):
+ provides=[Volume]
+ requested_interval=0
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+
+ def sync_record(self, volume):
+ """
+ Synchronize a Volume record with Syndicate.
+ """
+
+ logger.info( "Sync Volume = %s\n\n" % volume.name )
+
+ user_email = volume.owner_id.email
+ config = syndicatelib.get_config()
+
+ volume_principal_id = syndicatelib.make_volume_principal_id( user_email, volume.name )
+
+ # get the observer secret
+ try:
+ observer_secret = config.SYNDICATE_OPENCLOUD_SECRET
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("config is missing SYNDICATE_OPENCLOUD_SECRET")
+ raise e
+
+ # volume owner must exist as a Syndicate user...
+ try:
+ rc, user = syndicatelib.ensure_principal_exists( volume_principal_id, observer_secret, is_admin=False, max_UGs=1100, max_RGs=1)
+ assert rc == True, "Failed to create or read volume principal '%s'" % volume_principal_id
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("Failed to ensure principal '%s' exists" % volume_principal_id )
+ raise e
+
+ # volume must exist
+
+ # create or update the Volume
+ try:
+ new_volume = syndicatelib.ensure_volume_exists( volume_principal_id, volume, user=user )
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("Failed to ensure volume '%s' exists" % volume.name )
+ raise e
+
+ # did we create the Volume?
+ if new_volume is not None:
+ # we're good
+ pass
+
+ # otherwise, just update it
+ else:
+ try:
+ rc = syndicatelib.update_volume( volume )
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("Failed to update volume '%s', exception = %s" % (volume.name, e.message))
+ raise e
+
+ return True
+
+ def delete_record(self, volume):
+ try:
+ volume_name = volume.name
+ syndicatelib.ensure_volume_absent( volume_name )
+ except Exception, e:
+ traceback.print_exc()
+ logger.exception("Failed to erase volume '%s'" % volume_name)
+ raise e
+
+
+
+
+
+if __name__ == "__main__":
+ sv = SyncVolume()
+
+
+ # first, set all volumes to not-enacted so we can test
+ for v in Volume.objects.all():
+ v.enacted = None
+ v.save()
+
+ # NOTE: for resetting only
+ if len(sys.argv) > 1 and sys.argv[1] == "reset":
+ sys.exit(0)
+
+ recs = sv.fetch_pending()
+
+ for rec in recs:
+ rc = sv.sync_record( rec )
+ if not rc:
+ print "\n\nFailed to sync %s\n\n" % (rec.name)
+
diff --git a/xos/synchronizers/syndicate/steps/sync_volumeaccessright.py b/xos/synchronizers/syndicate/steps/sync_volumeaccessright.py
new file mode 100644
index 0000000..2889502
--- /dev/null
+++ b/xos/synchronizers/syndicate/steps/sync_volumeaccessright.py
@@ -0,0 +1,116 @@
+#!/usr/bin/env python
+
+import os
+import sys
+import base64
+import traceback
+
+if __name__ == "__main__":
+ # for testing
+ if os.getenv("OPENCLOUD_PYTHONPATH"):
+ sys.path.append( os.getenv("OPENCLOUD_PYTHONPATH") )
+ else:
+ print >> sys.stderr, "No OPENCLOUD_PYTHONPATH variable set. Assuming that OpenCloud is in PYTHONPATH"
+
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from core.models import Service
+
+import logging
+from logging import Logger
+logging.basicConfig( format='[%(levelname)s] [%(module)s:%(lineno)d] %(message)s' )
+logger = logging.getLogger()
+logger.setLevel( logging.INFO )
+
+# point to planetstack
+if __name__ != "__main__":
+ if os.getenv("OPENCLOUD_PYTHONPATH") is not None:
+ sys.path.insert(0, os.getenv("OPENCLOUD_PYTHONPATH"))
+ else:
+ logger.warning("No OPENCLOUD_PYTHONPATH set; assuming your PYTHONPATH works")
+
+from services.syndicate_storage.models import VolumeAccessRight
+
+# syndicatelib will be in stes/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+import syndicatelib
+
+class SyncVolumeAccessRight(SyncStep):
+ provides=[VolumeAccessRight]
+ requested_interval=0
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+
+ def sync_record(self, vac):
+
+ syndicate_caps = "UNKNOWN" # for exception handling
+
+ # get arguments
+ config = syndicatelib.get_config()
+ user_email = vac.owner_id.email
+ volume_name = vac.volume.name
+ syndicate_caps = syndicatelib.opencloud_caps_to_syndicate_caps( vac.cap_read_data, vac.cap_write_data, vac.cap_host_data )
+
+ logger.info( "Sync VolumeAccessRight for (%s, %s)" % (user_email, volume_name) )
+
+ # validate config
+ try:
+ RG_port = config.SYNDICATE_RG_DEFAULT_PORT
+ observer_secret = config.SYNDICATE_OPENCLOUD_SECRET
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("syndicatelib config is missing SYNDICATE_RG_DEFAULT_PORT, SYNDICATE_OPENCLOUD_SECRET")
+ raise e
+
+ # ensure the user exists and has credentials
+ try:
+ rc, user = syndicatelib.ensure_principal_exists( user_email, observer_secret, is_admin=False, max_UGs=1100, max_RGs=1 )
+ assert rc is True, "Failed to ensure principal %s exists (rc = %s,%s)" % (user_email, rc, user)
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("Failed to ensure user '%s' exists" % user_email )
+ raise e
+
+ # make the access right for the user to create their own UGs, and provision an RG for this user that will listen on localhost.
+ # the user will have to supply their own RG closure.
+ try:
+ rc = syndicatelib.setup_volume_access( user_email, volume_name, syndicate_caps, RG_port, observer_secret )
+ assert rc is True, "Failed to setup volume access for %s in %s" % (user_email, volume_name)
+
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("Faoed to ensure user %s can access Volume %s with rights %s" % (user_email, volume_name, syndicate_caps))
+ raise e
+
+ return True
+
+ # Jude: this will simply go on to purge the object from
+ # OpenCloud. The previous 'deleter' version was a no-op also.
+ def delete_record(self, obj):
+ pass
+
+
+if __name__ == "__main__":
+
+ # first, set all VolumeAccessRights to not-enacted so we can test
+ for v in VolumeAccessRight.objects.all():
+ v.enacted = None
+ v.save()
+
+ # NOTE: for resetting only
+ if len(sys.argv) > 1 and sys.argv[1] == "reset":
+ sys.exit(0)
+
+
+ sv = SyncVolumeAccessRight()
+ recs = sv.fetch_pending()
+
+ for rec in recs:
+ sv.sync_record( rec )
+
diff --git a/xos/synchronizers/syndicate/steps/sync_volumeslice.py b/xos/synchronizers/syndicate/steps/sync_volumeslice.py
new file mode 100644
index 0000000..1be61b9
--- /dev/null
+++ b/xos/synchronizers/syndicate/steps/sync_volumeslice.py
@@ -0,0 +1,158 @@
+#!/usr/bin/env python
+
+import os
+import sys
+import base64
+import traceback
+
+if __name__ == "__main__":
+ # for testing
+ if os.getenv("OPENCLOUD_PYTHONPATH"):
+ sys.path.append( os.getenv("OPENCLOUD_PYTHONPATH") )
+ else:
+ print >> sys.stderr, "No OPENCLOUD_PYTHONPATH variable set. Assuming that OpenCloud is in PYTHONPATH"
+
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from core.models import Service, Slice
+
+import logging
+from logging import Logger
+logging.basicConfig( format='[%(levelname)s] [%(module)s:%(lineno)d] %(message)s' )
+logger = logging.getLogger()
+logger.setLevel( logging.INFO )
+
+# point to planetstack
+if __name__ != "__main__":
+ if os.getenv("OPENCLOUD_PYTHONPATH") is not None:
+ sys.path.insert(0, os.getenv("OPENCLOUD_PYTHONPATH"))
+ else:
+ logger.warning("No OPENCLOUD_PYTHONPATH set; assuming your PYTHONPATH works")
+
+from services.syndicate_storage.models import VolumeSlice,VolumeAccessRight,Volume
+
+# syndicatelib will be in stes/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+import syndicatelib
+
+
+class SyncVolumeSlice(SyncStep):
+ provides=[VolumeSlice]
+ requested_interval=0
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+
+ def sync_record(self, vs):
+
+ logger.info("Sync VolumeSlice for (%s, %s)" % (vs.volume_id.name, vs.slice_id.name))
+
+ # extract arguments...
+ user_email = vs.slice_id.creator.email
+ slice_name = vs.slice_id.name
+ volume_name = vs.volume_id.name
+ syndicate_caps = syndicatelib.opencloud_caps_to_syndicate_caps( vs.cap_read_data, vs.cap_write_data, vs.cap_host_data )
+ RG_port = vs.RG_portnum
+ UG_port = vs.UG_portnum
+ slice_secret = None
+
+ config = syndicatelib.get_config()
+ try:
+ observer_secret = config.SYNDICATE_OPENCLOUD_SECRET
+ RG_closure = config.SYNDICATE_RG_CLOSURE
+ observer_pkey_path = config.SYNDICATE_PRIVATE_KEY
+ syndicate_url = config.SYNDICATE_SMI_URL
+
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("syndicatelib config is missing one or more of the following: SYNDICATE_OPENCLOUD_SECRET, SYNDICATE_RG_CLOSURE, SYNDICATE_PRIVATE_KEY, SYNDICATE_SMI_URL")
+ raise e
+
+ # get secrets...
+ try:
+ observer_pkey_pem = syndicatelib.get_private_key_pem( observer_pkey_path )
+ assert observer_pkey_pem is not None, "Failed to load Observer private key"
+
+ # get/create the slice secret
+ slice_secret = syndicatelib.get_or_create_slice_secret( observer_pkey_pem, slice_name )
+ assert slice_secret is not None, "Failed to get or create slice secret for %s" % slice_name
+
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("Failed to load secret credentials")
+ raise e
+
+ # make sure there's a slice-controlled Syndicate user account for the slice owner
+ slice_principal_id = syndicatelib.make_slice_principal_id( user_email, slice_name )
+
+ try:
+ rc, user = syndicatelib.ensure_principal_exists( slice_principal_id, observer_secret, is_admin=False, max_UGs=1100, max_RGs=1 )
+ assert rc is True, "Failed to ensure principal %s exists (rc = %s,%s)" % (slice_principal_id, rc, user)
+ except Exception, e:
+ traceback.print_exc()
+ logger.error('Failed to ensure slice user %s exists' % slice_principal_id)
+ raise e
+
+ # grant the slice-owning user the ability to provision UGs in this Volume, and also provision for the user the (single) RG the slice will instantiate in each VM.
+ try:
+ rc = syndicatelib.setup_volume_access( slice_principal_id, volume_name, syndicate_caps, RG_port, observer_secret, RG_closure=RG_closure )
+ assert rc is True, "Failed to set up Volume access for slice %s in %s" % (slice_principal_id, volume_name)
+
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("Failed to set up Volume access for slice %s in %s" % (slice_principal_id, volume_name))
+ raise e
+
+ # generate and save slice credentials....
+ try:
+ slice_cred = syndicatelib.save_slice_credentials( observer_pkey_pem, syndicate_url, slice_principal_id, volume_name, slice_name, observer_secret, slice_secret, UG_port, existing_user=user )
+ assert slice_cred is not None, "Failed to generate slice credential for %s in %s" % (slice_principal_id, volume_name )
+
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("Failed to generate slice credential for %s in %s" % (slice_principal_id, volume_name))
+ raise e
+
+ # ... and push them all out.
+ try:
+ rc = syndicatelib.push_credentials_to_slice( slice_name, slice_cred )
+ assert rc is True, "Failed to push credentials to slice %s for volume %s" % (slice_name, volume_name)
+
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("Failed to push slice credentials to %s for volume %s" % (slice_name, volume_name))
+ raise e
+
+ return True
+
+ # This method will simply cause the object to be purged from OpenCloud
+ def delete_record(self, volume_slice):
+ pass
+
+
+if __name__ == "__main__":
+ sv = SyncVolumeSlice()
+
+ # first, set all VolumeSlice to not-enacted so we can test
+ for v in VolumeSlice.objects.all():
+ v.enacted = None
+ v.save()
+
+ # NOTE: for resetting only
+ if len(sys.argv) > 1 and sys.argv[1] == "reset":
+ sys.exit(0)
+
+ recs = sv.fetch_pending()
+
+ for rec in recs:
+ if rec.slice_id.creator is None:
+ print "Ignoring slice %s, since it has no creator" % (rec.slice_id)
+ continue
+
+ sv.sync_record( rec )
+
diff --git a/xos/syndicate_observer/stop.sh b/xos/synchronizers/syndicate/stop.sh
similarity index 100%
rename from xos/syndicate_observer/stop.sh
rename to xos/synchronizers/syndicate/stop.sh
diff --git a/xos/synchronizers/syndicate/syndicate-backend.py b/xos/synchronizers/syndicate/syndicate-backend.py
new file mode 100644
index 0000000..9b53c77
--- /dev/null
+++ b/xos/synchronizers/syndicate/syndicate-backend.py
@@ -0,0 +1,10 @@
+#!/usr/bin/env python
+import os
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+from synchronizers.base.backend import Backend
+
+if __name__ == '__main__':
+
+ backend = Backend()
+ backend.run()
+
diff --git a/xos/synchronizers/syndicate/syndicate_synchronizer_config b/xos/synchronizers/syndicate/syndicate_synchronizer_config
new file mode 100644
index 0000000..7c9d2d2
--- /dev/null
+++ b/xos/synchronizers/syndicate/syndicate_synchronizer_config
@@ -0,0 +1,35 @@
+
+[plc]
+name=plc
+deployment=VICCI
+
+[db]
+name=xos
+#user=plstackuser
+#password=2uMDYtJK
+user=postgres
+password=password
+host=localhost
+port=5432
+
+[api]
+host=128.112.171.237
+port=8000
+ssl_key=None
+ssl_cert=None
+ca_ssl_cert=None
+ratelimit_enabled=0
+omf_enabled=0
+mail_support_address=support@localhost
+nova_enabled=True
+
+[observer]
+dependency_graph=/opt/xos/synchronizers/syndicate/model-deps
+steps_dir=/opt/xos/synchronizers/syndicate/steps
+deleters_dir=/opt/xos/synchronizers/syndicate/deleters
+log_file=console
+driver=None
+
+[feefie]
+client_id='vicci_dev_central'
+user_id='pl'
diff --git a/xos/synchronizers/syndicate/syndicatelib.py b/xos/synchronizers/syndicate/syndicatelib.py
new file mode 100644
index 0000000..56bd120
--- /dev/null
+++ b/xos/synchronizers/syndicate/syndicatelib.py
@@ -0,0 +1,1353 @@
+#!/usr/bin/env python
+
+"""
+Define some common methods for the Syndicate observer.
+"""
+import os
+import sys
+import random
+import json
+import time
+import requests
+import traceback
+import base64
+import BaseHTTPServer
+import setproctitle
+import threading
+import urllib
+
+from Crypto.Hash import SHA256 as HashAlg
+from Crypto.PublicKey import RSA as CryptoKey
+from Crypto import Random
+from Crypto.Signature import PKCS1_PSS as CryptoSigner
+
+import logging
+from logging import Logger
+logging.basicConfig( format='[%(levelname)s] [%(module)s:%(lineno)d] %(message)s' )
+logger = logging.getLogger()
+logger.setLevel( logging.INFO )
+
+# get config package
+import syndicatelib_config.config as CONFIG
+
+# get the Syndicate modules
+import syndicate
+
+import syndicate.client.bin.syntool as syntool
+import syndicate.client.common.msconfig as msconfig
+import syndicate.client.common.api as api
+import syndicate.util.storage as syndicate_storage
+import syndicate.util.watchdog as syndicate_watchdog
+import syndicate.util.daemonize as syndicate_daemon
+import syndicate.util.crypto as syndicate_crypto
+import syndicate.util.provisioning as syndicate_provisioning
+import syndicate.syndicate as c_syndicate
+
+# for testing
+TESTING = False
+class FakeObject(object):
+ def __init__(self):
+ pass
+
+if os.getenv("OPENCLOUD_PYTHONPATH") is not None:
+ sys.path.insert(0, os.getenv("OPENCLOUD_PYTHONPATH"))
+else:
+ logger.warning("No OPENCLOUD_PYTHONPATH set. Assuming Syndicate models are in your PYTHONPATH")
+
+try:
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+
+ # get our models
+ import services.syndicate_storage.models as models
+
+ # get OpenCloud models
+ from core.models import Slice,Instance
+
+ from django.core.exceptions import ObjectDoesNotExist
+ from django.db import IntegrityError
+
+except ImportError, ie:
+ logger.warning("Failed to import models; some tests will not work")
+
+ # create a fake "models" package that has exactly the members we need for testing.
+ models = FakeObject()
+ models.Volume = FakeObject()
+ models.Volume.CAP_READ_DATA = 1
+ models.Volume.CAP_WRITE_DATA = 2
+ models.Volume.CAP_HOST_DATA = 4
+
+ TESTING = True
+
+
+#-------------------------------
+class SyndicateObserverError( Exception ):
+ pass
+
+#-------------------------------
+def get_config():
+ """
+ Return the imported config
+ """
+ return CONFIG
+
+
+#-------------------------------
+def make_openid_url( email ):
+ """
+ Generate an OpenID identity URL from an email address.
+ """
+ return os.path.join( CONFIG.SYNDICATE_OPENID_TRUSTROOT, "id", email )
+
+
+#-------------------------------
+def connect_syndicate( username=CONFIG.SYNDICATE_OPENCLOUD_USER, password=CONFIG.SYNDICATE_OPENCLOUD_PASSWORD, user_pkey_pem=CONFIG.SYNDICATE_OPENCLOUD_PKEY ):
+ """
+ Connect to the OpenCloud Syndicate SMI, using the OpenCloud user credentials.
+ """
+ debug = True
+ if hasattr(CONFIG, "DEBUG"):
+ debug = CONFIG.DEBUG
+
+ client = syntool.Client( username, CONFIG.SYNDICATE_SMI_URL,
+ password=password,
+ user_pkey_pem=user_pkey_pem,
+ debug=debug )
+
+ return client
+
+
+#-------------------------------
+def opencloud_caps_to_syndicate_caps( cap_read, cap_write, cap_host ):
+ """
+ Convert OpenCloud capability bits from the UI into Syndicate's capability bits.
+ """
+ syn_caps = 0
+
+ if cap_read:
+ syn_caps |= (msconfig.GATEWAY_CAP_READ_DATA | msconfig.GATEWAY_CAP_READ_METADATA)
+ if cap_write:
+ syn_caps |= (msconfig.GATEWAY_CAP_WRITE_DATA | msconfig.GATEWAY_CAP_WRITE_METADATA)
+ if cap_host:
+ syn_caps |= (msconfig.GATEWAY_CAP_COORDINATE)
+
+ return syn_caps
+
+#-------------------------------
+def ensure_user_exists( user_email, **user_kw ):
+ """
+ Given an OpenCloud user, ensure that the corresponding
+ Syndicate user exists on the MS. This method does NOT
+ create any OpenCloud-specific data.
+
+ Return the (created, user), where created==True if the user
+ was created and created==False if the user was read.
+ Raise an exception on error.
+ """
+
+ client = connect_syndicate()
+ user_openid_url = make_openid_url( user_email )
+
+ return syndicate_provisioning.ensure_user_exists( client, user_email, user_openid_url, **user_kw )
+
+
+#-------------------------------
+def ensure_user_absent( user_email ):
+ """
+ Ensure that a given OpenCloud user's associated Syndicate user record
+ has been deleted. This method does NOT delete any OpenCloud-specific data.
+
+ Returns True on success
+ Raises an exception on error
+ """
+
+ client = connect_syndicate()
+
+ return client.delete_user( user_email )
+
+
+#-------------------------------
+def make_volume_principal_id( user_email, volume_name ):
+ """
+ Create a principal id for a Volume owner.
+ """
+
+ volume_name_safe = urllib.quote( volume_name )
+
+ return "volume_%s.%s" % (volume_name_safe, user_email)
+
+
+#-------------------------------
+def make_slice_principal_id( user_email, slice_name ):
+ """
+ Create a principal id for a slice owner.
+ """
+
+ slice_name_safe = urllib.quote( slice_name )
+
+ return "slice_%s.%s" % (slice_name, user_email)
+
+
+#-------------------------------
+def ensure_principal_exists( user_email, observer_secret, **user_kw ):
+ """
+ Ensure that a Syndicate user exists, as well as its OpenCloud-specific data.
+
+ Return (True, (None OR user)) on success. Returns a user if the user was created.
+ Return (False, None) on error
+ """
+
+ try:
+ created, new_user = ensure_user_exists( user_email, **user_kw )
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("Failed to ensure user '%s' exists" % user_email )
+ return (False, None)
+
+ # if we created a new user, then save its (sealed) credentials to the Django DB
+ if created:
+ try:
+ rc = put_principal_data( user_email, observer_secret, new_user['signing_public_key'], new_user['signing_private_key'] )
+ assert rc == True, "Failed to save SyndicatePrincipal"
+ except Exception, e:
+ traceback.print_exc()
+ logger.error("Failed to save private key for principal %s" % (user_email))
+ return (False, None)
+
+ return (True, new_user)
+
+
+
+#-------------------------------
+def ensure_principal_absent( user_email ):
+ """
+ Ensure that a Syndicate user does not exists, and remove the OpenCloud-specific data.
+
+ Return True on success.
+ """
+
+ ensure_user_absent( user_email )
+ delete_principal_data( user_email )
+ return True
+
+#-------------------------------
+def ensure_volume_exists( user_email, opencloud_volume, user=None ):
+ """
+ Given the email address of a user, ensure that the given
+ Volume exists and is owned by that user.
+ Do not try to ensure that the user exists.
+
+ Return the Volume if we created it, or return None if we did not.
+ Raise an exception on error.
+ """
+ client = connect_syndicate()
+
+ try:
+ volume = client.read_volume( opencloud_volume.name )
+ except Exception, e:
+ # transport error
+ logger.exception(e)
+ raise e
+
+ if volume is None:
+ # the volume does not exist....try to create it
+ vol_name = opencloud_volume.name
+ vol_blocksize = opencloud_volume.blocksize
+ vol_description = opencloud_volume.description
+ vol_private = opencloud_volume.private
+ vol_archive = opencloud_volume.archive
+ vol_default_gateway_caps = opencloud_caps_to_syndicate_caps( opencloud_volume.cap_read_data, opencloud_volume.cap_write_data, opencloud_volume.cap_host_data )
+
+ try:
+ vol_info = client.create_volume( user_email, vol_name, vol_description, vol_blocksize,
+ private=vol_private,
+ archive=vol_archive,
+ active=True,
+ default_gateway_caps=vol_default_gateway_caps,
+ store_private_key=False,
+ metadata_private_key="MAKE_METADATA_KEY" )
+
+ except Exception, e:
+ # transport error
+ logger.exception(e)
+ raise e
+
+ else:
+ # successfully created the volume!
+ return vol_info
+
+ else:
+
+ # volume already exists. Verify its owned by this user.
+ if user is None:
+ try:
+ user = client.read_user( volume['owner_id'] )
+ except Exception, e:
+ # transport error, or user doesn't exist (either is unacceptable)
+ logger.exception(e)
+ raise e
+
+ if user is None or user['email'] != user_email:
+ raise Exception("Volume '%s' already exists, but is NOT owned by '%s'" % (opencloud_volume.name, user_email) )
+
+ # we're good!
+ return None
+
+
+#-------------------------------
+def ensure_volume_absent( volume_name ):
+ """
+ Given an OpenCloud volume, ensure that the corresponding Syndicate
+ Volume does not exist.
+ """
+
+ client = connect_syndicate()
+
+ # this is idempotent, and returns True even if the Volume doesn't exist
+ return client.delete_volume( volume_name )
+
+
+#-------------------------------
+def update_volume( opencloud_volume ):
+ """
+ Update a Syndicate Volume from an OpenCloud Volume model.
+ Fails if the Volume does not exist in Syndicate.
+ """
+
+ client = connect_syndicate()
+
+ vol_name = opencloud_volume.name
+ vol_description = opencloud_volume.description
+ vol_private = opencloud_volume.private
+ vol_archive = opencloud_volume.archive
+ vol_default_gateway_caps = opencloud_caps_to_syndicate_caps( opencloud_volume.cap_read_data, opencloud_volume.cap_write_data, opencloud_volume.cap_host_data )
+
+ try:
+ rc = client.update_volume( vol_name,
+ description=vol_description,
+ private=vol_private,
+ archive=vol_archive,
+ default_gateway_caps=vol_default_gateway_caps )
+
+ if not rc:
+ raise Exception("update_volume(%s) failed!" % vol_name )
+
+ except Exception, e:
+ # transort or method error
+ logger.exception(e)
+ return False
+
+ else:
+ return True
+
+
+#-------------------------------
+def ensure_volume_access_right_exists( user_email, volume_name, caps, allowed_gateways=[msconfig.GATEWAY_TYPE_UG] ):
+ """
+ Ensure that a particular user has particular access to a particular volume.
+ Do not try to ensure that the user or volume exist, however!
+ """
+ client = connect_syndicate()
+ return syndicate_provisioning.ensure_volume_access_right_exists( client, user_email, volume_name, caps, allowed_gateways )
+
+#-------------------------------
+def ensure_volume_access_right_absent( user_email, volume_name ):
+ """
+ Ensure that acess to a particular volume is revoked.
+ """
+ client = connect_syndicate()
+ return syndicate_provisioning.ensure_volume_access_right_absent( client, user_email, volume_name )
+
+
+#-------------------------------
+def setup_volume_access( user_email, volume_name, caps, RG_port, slice_secret, RG_closure=None ):
+ """
+ Set up the Volume to allow the slice to provision UGs in it, and to fire up RGs.
+ * create the Volume Access Right for the user, so (s)he can create Gateways.
+ * provision a single Replica Gateway, serving on localhost.
+ """
+ client = connect_syndicate()
+
+ try:
+ rc = ensure_volume_access_right_exists( user_email, volume_name, caps )
+ assert rc is True, "Failed to create access right for %s in %s" % (user_email, volume_name)
+
+ except Exception, e:
+ logger.exception(e)
+ return False
+
+ RG_name = syndicate_provisioning.make_gateway_name( "OpenCloud", "RG", volume_name, "localhost" )
+ RG_key_password = syndicate_provisioning.make_gateway_private_key_password( RG_name, slice_secret )
+
+ try:
+ rc = syndicate_provisioning.ensure_RG_exists( client, user_email, volume_name, RG_name, "localhost", RG_port, RG_key_password, closure=RG_closure )
+ except Exception, e:
+ logger.exception(e)
+ return False
+
+ return True
+
+
+#-------------------------------
+def teardown_volume_access( user_email, volume_name ):
+ """
+ Revoke access to a Volume for a User.
+ * remove the user's Volume Access Right
+ * remove the use'rs gateways
+ """
+ client = connect_syndicate()
+
+ # block the user from creating more gateways, and delete the gateways
+ try:
+ rc = client.remove_user_from_volume( user_email, volume_name )
+ assert rc is True, "Failed to remove access right for %s in %s" % (user_email, volume_name)
+
+ except Exception, e:
+ logger.exception(e)
+ return False
+
+ return True
+
+
+#-------------------------------
+def create_sealed_and_signed_blob( private_key_pem, secret, data ):
+ """
+ Create a sealed and signed message.
+ """
+
+ # seal it with the password
+ logger.info("Sealing credential data")
+
+ rc, sealed_data = c_syndicate.password_seal( data, secret )
+ if rc != 0:
+ logger.error("Failed to seal data with the secret, rc = %s" % rc)
+ return None
+
+ msg = syndicate_crypto.sign_and_serialize_json( private_key_pem, sealed_data )
+ if msg is None:
+ logger.error("Failed to sign credential")
+ return None
+
+ return msg
+
+
+#-------------------------------
+def verify_and_unseal_blob( public_key_pem, secret, blob_data ):
+ """
+ verify and unseal a serialized string of JSON
+ """
+
+ # verify it
+ rc, sealed_data = syndicate_crypto.verify_and_parse_json( public_key_pem, blob_data )
+ if rc != 0:
+ logger.error("Failed to verify and parse blob, rc = %s" % rc)
+ return None
+
+ logger.info("Unsealing credential data")
+
+ rc, data = c_syndicate.password_unseal( sealed_data, secret )
+ if rc != 0:
+ logger.error("Failed to unseal blob, rc = %s" % rc )
+ return None
+
+ return data
+
+
+#-------------------------------
+def create_volume_list_blob( private_key_pem, slice_secret, volume_list ):
+ """
+ Create a sealed volume list, signed with the private key.
+ """
+ list_data = {
+ "volumes": volume_list
+ }
+
+ list_data_str = json.dumps( list_data )
+
+ msg = create_sealed_and_signed_blob( private_key_pem, slice_secret, list_data_str )
+ if msg is None:
+ logger.error("Failed to seal volume list")
+ return None
+
+ return msg
+
+
+#-------------------------------
+def create_slice_credential_blob( private_key_pem, slice_name, slice_secret, syndicate_url, volume_name, volume_owner, UG_port, user_pkey_pem ):
+ """
+ Create a sealed, signed, encoded slice credentials blob.
+ """
+
+ # create and serialize the data
+ cred_data = {
+ "syndicate_url": syndicate_url,
+ "volume_name": volume_name,
+ "volume_owner": volume_owner,
+ "slice_name": slice_name,
+ "slice_UG_port": UG_port,
+ "principal_pkey_pem": user_pkey_pem,
+ }
+
+ cred_data_str = json.dumps( cred_data )
+
+ msg = create_sealed_and_signed_blob( private_key_pem, slice_secret, cred_data_str )
+ if msg is None:
+ logger.error("Failed to seal volume list")
+ return None
+
+ return msg
+
+
+#-------------------------------
+def put_principal_data( user_email, observer_secret, public_key_pem, private_key_pem ):
+ """
+ Seal and store the principal's private key into the database, in a SyndicatePrincipal object,
+ so the instance-side Syndicate daemon syndicated.py can get them later.
+ Overwrite an existing principal if one exists.
+ """
+
+ sealed_private_key = create_sealed_and_signed_blob( private_key_pem, observer_secret, private_key_pem )
+ if sealed_private_key is None:
+ return False
+
+ try:
+ sp = models.SyndicatePrincipal( sealed_private_key=sealed_private_key, public_key_pem=public_key_pem, principal_id=user_email )
+ sp.save()
+ except IntegrityError, e:
+ logger.error("WARN: overwriting existing principal %s" % user_email)
+ sp.delete()
+ sp.save()
+
+ return True
+
+
+#-------------------------------
+def delete_principal_data( user_email ):
+ """
+ Delete an OpenCloud SyndicatePrincipal object.
+ """
+
+ sp = get_principal_data( user_email )
+ if sp is not None:
+ sp.delete()
+
+ return True
+
+
+#-------------------------------
+def get_principal_data( user_email ):
+ """
+ Get a SyndicatePrincipal record from the database
+ """
+
+ try:
+ sp = models.SyndicatePrincipal.objects.get( principal_id=user_email )
+ return sp
+ except ObjectDoesNotExist:
+ logger.error("No SyndicatePrincipal record for %s" % user_email)
+ return None
+
+
+
+#-------------------------------
+def get_principal_pkey( user_email, observer_secret ):
+ """
+ Fetch and unseal the private key of a SyndicatePrincipal.
+ """
+
+ sp = get_principal_data( user_email )
+ if sp is None:
+ logger.error("Failed to find private key for principal %s" % user_email )
+ return None
+
+ public_key_pem = sp.public_key_pem
+ sealed_private_key_pem = sp.sealed_private_key
+
+ # unseal
+ private_key_pem = verify_and_unseal_blob(public_key_pem, observer_secret, sealed_private_key_pem)
+ if private_key_pem is None:
+ logger.error("Failed to unseal private key")
+
+ return private_key_pem
+
+
+#-------------------------------
+def get_private_key_pem( pkey_path ):
+ """
+ Get a private key from storage, PEM-encoded.
+ """
+
+ # get the OpenCloud private key
+ observer_pkey = syndicate_storage.read_private_key( pkey_path )
+ if observer_pkey is None:
+ logger.error("Failed to load Observer private key")
+ return None
+
+ observer_pkey_pem = observer_pkey.exportKey()
+
+ return observer_pkey_pem
+
+
+#-------------------------------
+def encrypt_slice_secret( observer_pkey_pem, slice_secret ):
+ """
+ Encrypt and serialize the slice secret with the Observer private key
+ """
+
+ # get the public key
+ try:
+ observer_pubkey_pem = CryptoKey.importKey( observer_pkey_pem ).publickey().exportKey()
+ except Exception, e:
+ logger.exception(e)
+ logger.error("Failed to derive public key from private key")
+ return None
+
+ # encrypt the data
+ rc, sealed_slice_secret = c_syndicate.encrypt_data( observer_pkey_pem, observer_pubkey_pem, slice_secret )
+
+ if rc != 0:
+ logger.error("Failed to encrypt slice secret")
+ return None
+
+ sealed_slice_secret_b64 = base64.b64encode( sealed_slice_secret )
+
+ return sealed_slice_secret_b64
+
+
+#-------------------------------
+def decrypt_slice_secret( observer_pkey_pem, sealed_slice_secret_b64 ):
+ """
+ Unserialize and decrypt a slice secret
+ """
+
+ # get the public key
+ try:
+ observer_pubkey_pem = CryptoKey.importKey( observer_pkey_pem ).publickey().exportKey()
+ except Exception, e:
+ logger.exception(e)
+ logger.error("Failed to derive public key from private key")
+ return None
+
+ sealed_slice_secret = base64.b64decode( sealed_slice_secret_b64 )
+
+ # decrypt it
+ rc, slice_secret = c_syndicate.decrypt_data( observer_pubkey_pem, observer_pkey_pem, sealed_slice_secret )
+
+ if rc != 0:
+ logger.error("Failed to decrypt '%s', rc = %d" % (sealed_slice_secret_b64, rc))
+ return None
+
+ return slice_secret
+
+
+#--------------------------------
+def get_slice_secret( observer_pkey_pem, slice_name, slice_fk=None ):
+ """
+ Get the shared secret for a slice.
+ """
+
+ ss = None
+
+ # get the sealed slice secret from Django
+ try:
+ if slice_fk is not None:
+ ss = models.SliceSecret.objects.get( slice_id=slice_fk )
+ else:
+ ss = models.SliceSecret.objects.get( slice_id__name=slice_name )
+ except ObjectDoesNotExist, e:
+ logger.error("Failed to load slice secret for (%s, %s)" % (slice_fk, slice_name) )
+ return None
+
+ return ss.secret
+
+
+#-------------------------------
+def put_slice_secret( observer_pkey_pem, slice_name, slice_secret, slice_fk=None, opencloud_slice=None ):
+ """
+ Put the shared secret for a slice, encrypting it first.
+ """
+
+ ss = None
+
+ if opencloud_slice is None:
+ # look up the slice
+ try:
+ if slice_fk is None:
+ opencloud_slice = models.Slice.objects.get( name=slice_name )
+ else:
+ opencloud_slice = models.Slice.objects.get( id=slice_fk.id )
+ except Exception, e:
+ logger.exception(e)
+ logger.error("Failed to load slice (%s, %s)" % (slice_fk, slice_name) )
+ return False
+
+ ss = models.SliceSecret( slice_id=opencloud_slice, secret=slice_secret )
+
+ ss.save()
+
+ return True
+
+
+#-------------------------------
+def get_or_create_slice_secret( observer_pkey_pem, slice_name, slice_fk=None ):
+ """
+ Get a slice secret if it already exists, or generate a slice secret if one does not.
+ """
+
+ slice_secret = get_slice_secret( observer_pkey_pem, slice_name, slice_fk=slice_fk )
+ if slice_secret is None or len(slice_secret) == 0:
+
+ # generate a slice secret
+ slice_secret = "".join( random.sample("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 32) )
+
+ # store it
+ rc = put_slice_secret( observer_pkey_pem, slice_name, slice_secret, slice_fk=slice_fk )
+
+ if not rc:
+ raise SyndicateObserverError("Failed to create slice secret for (%s, %s)" % (slice_fk, slice_name))
+
+ return slice_secret
+
+
+#-------------------------------
+def generate_slice_credentials( observer_pkey_pem, syndicate_url, user_email, volume_name, slice_name, observer_secret, slice_secret, UG_port, existing_user=None ):
+ """
+ Generate and return the set of credentials to be sent off to the slice VMs.
+ exisitng_user is a Syndicate user, as a dictionary.
+
+ Return None on failure
+ """
+
+ # get the user's private key
+ logger.info("Obtaining private key for %s" % user_email)
+
+ # it might be in the existing_user...
+ user_pkey_pem = None
+ if existing_user is not None:
+ user_pkey_pem = existing_user.get('signing_private_key', None)
+
+ # no luck?
+ if user_pkey_pem is None:
+ try:
+ # get it from Django DB
+ user_pkey_pem = get_principal_pkey( user_email, observer_secret )
+ assert user_pkey_pem is not None, "No private key for %s" % user_email
+
+ except:
+ traceback.print_exc()
+ logger.error("Failed to get private key; cannot generate credentials for %s in %s" % (user_email, volume_name) )
+ return None
+
+ # generate a credetials blob
+ logger.info("Generating credentials for %s's slice" % (user_email))
+ try:
+ creds = create_slice_credential_blob( observer_pkey_pem, slice_name, slice_secret, syndicate_url, volume_name, user_email, UG_port, user_pkey_pem )
+ assert creds is not None, "Failed to create credentials for %s" % user_email
+
+ except:
+ traceback.print_exc()
+ logger.error("Failed to generate credentials for %s in %s" % (user_email, volume_name))
+ return None
+
+ return creds
+
+
+#-------------------------------
+def save_slice_credentials( observer_pkey_pem, syndicate_url, user_email, volume_name, slice_name, observer_secret, slice_secret, UG_port, existing_user=None ):
+ """
+ Create and save a credentials blob to a VolumeSlice.
+ Return the creds on success.
+ Return None on failure
+ """
+
+ creds = generate_slice_credentials( observer_pkey_pem, syndicate_url, user_email, volume_name, slice_name, observer_secret, slice_secret, UG_port, existing_user=existing_user )
+ ret = None
+
+ if creds is not None:
+ # save it
+ vs = get_volumeslice( volume_name, slice_name )
+
+ if vs is not None:
+ vs.credentials_blob = creds
+ vs.save()
+
+ # success!
+ ret = creds
+ else:
+ logger.error("Failed to look up VolumeSlice(%s, %s)" % (volume_name, slice_name))
+
+ else:
+ logger.error("Failed to generate credentials for %s, %s" % (volume_name, slice_name))
+
+ return ret
+
+
+#-------------------------------
+def get_volumeslice_volume_names( slice_name ):
+ """
+ Get the list of Volume names from the datastore.
+ """
+ try:
+ all_vs = models.VolumeSlice.objects.filter( slice_id__name = slice_name )
+ volume_names = []
+ for vs in all_vs:
+ volume_names.append( vs.volume_id.name )
+
+ return volume_names
+ except Exception, e:
+ logger.exception(e)
+ logger.error("Failed to query datastore for volumes mounted in %s" % slice_name)
+ return None
+
+
+#-------------------------------
+def get_volumeslice( volume_name, slice_name ):
+ """
+ Get a volumeslice record from the datastore.
+ """
+ try:
+ vs = models.VolumeSlice.objects.get( volume_id__name = volume_name, slice_id__name = slice_name )
+ return vs
+ except Exception, e:
+ logger.exception(e)
+ logger.error("Failed to query datastore for volumes (mounted in %s)" % (slice_name if (slice_name is not None or len(slice_name) > 0) else "UNKNOWN"))
+ return None
+
+
+#-------------------------------
+def do_push( instance_hosts, portnum, payload ):
+ """
+ Push a payload to a list of instances.
+ NOTE: this has to be done in one go, since we can't import grequests
+ into the global namespace (without wrecking havoc on the credential server),
+ but it has to stick around for the push to work.
+ """
+
+ global TESTING, CONFIG
+
+ from gevent import monkey
+
+ if TESTING:
+ monkey.patch_all()
+
+ else:
+ # make gevents runnabale from multiple threads (or Django will complain)
+ monkey.patch_all(socket=True, dns=True, time=True, select=True, thread=False, os=True, ssl=True, httplib=False, aggressive=True)
+
+ import grequests
+
+ # fan-out
+ requests = []
+ for sh in instance_hosts:
+ rs = grequests.post( "http://" + sh + ":" + str(portnum), data={"observer_message": payload}, timeout=getattr(CONFIG, "SYNDICATE_HTTP_PUSH_TIMEOUT", 60) )
+ requests.append( rs )
+
+ # fan-in
+ responses = grequests.map( requests )
+
+ assert len(responses) == len(requests), "grequests error: len(responses) != len(requests)"
+
+ for i in xrange(0,len(requests)):
+ resp = responses[i]
+ req = requests[i]
+
+ if resp is None:
+ logger.error("Failed to connect to %s" % (req.url))
+ continue
+
+ # verify they all worked
+ if resp.status_code != 200:
+ logger.error("Failed to POST to %s, status code = %s" % (resp.url, resp.status_code))
+ continue
+
+ return True
+
+
+#-------------------------------
+def get_slice_hostnames( slice_name ):
+ """
+ Query the Django DB and get the list of hosts running in a slice.
+ """
+
+ openstack_slice = Slice.objects.get( name=slice_name )
+ if openstack_slice is None:
+ logger.error("No such slice '%s'" % slice_name)
+ return None
+
+ hostnames = [s.node.name for s in openstack_slice.instances.all()]
+
+ return hostnames
+
+
+#-------------------------------
+def push_credentials_to_slice( slice_name, payload ):
+ """
+ Push a credentials payload to the VMs in a slice.
+ """
+ hostnames = get_slice_hostnames( slice_name )
+ return do_push( hostnames, CONFIG.SYNDICATE_SLIVER_PORT, payload )
+
+
+#-------------------------------
+class CredentialServerHandler( BaseHTTPServer.BaseHTTPRequestHandler ):
+ """
+ HTTP server handler that allows syndicated.py instances to poll
+ for volume state.
+
+ NOTE: this is a fall-back mechanism. The observer should push new
+ volume state to the slices' instances. However, if that fails, the
+ instances are configured to poll for volume state periodically. This
+ server allows them to do just that.
+
+ Responses:
+ GET /<slicename> -- Reply with the signed sealed list of volume names, encrypted by the slice secret
+ GET /<slicename>/<volumename> -- Reply with the signed sealed volume access credentials, encrypted by the slice secret
+
+ !!! TEMPORARY !!!
+ GET /<slicename>/SYNDICATE_SLICE_SECRET -- Reply with the slice secret (TEMPORARY)
+
+
+ NOTE: We want to limit who can learn which Volumes a slice can access, so we'll seal its instances'
+ credentials with the SliceSecret secret. The instances (which have the slice-wide secret) can then decrypt it.
+ However, sealing the listing is a time-consuming process (on the order of 10s), so we only want
+ to do it when we have to. Since *anyone* can ask for the ciphertext of the volume list,
+ we will cache the list ciphertext for each slice for a long-ish amount of time, so we don't
+ accidentally DDoS this server. This necessarily means that the instance might see a stale
+ volume listing, but that's okay, since the Observer is eventually consistent anyway.
+ """
+
+ cached_volumes_json = {} # map slice_name --> (volume name, timeout)
+ cached_volumes_json_lock = threading.Lock()
+
+ CACHED_VOLUMES_JSON_LIFETIME = 3600 # one hour
+
+ SLICE_SECRET_NAME = "SYNDICATE_SLICE_SECRET"
+
+ def parse_request_path( self, path ):
+ """
+ Parse the URL path into a slice name and (possibly) a volume name or SLICE_SECRET_NAME
+ """
+ path_parts = path.strip("/").split("/")
+
+ if len(path_parts) == 0:
+ # invalid
+ return (None, None)
+
+ if len(path_parts) > 2:
+ # invalid
+ return (None, None)
+
+ slice_name = path_parts[0]
+ if len(slice_name) == 0:
+ # empty string is invalid
+ return (None, None)
+
+ volume_name = None
+
+ if len(path_parts) > 1:
+ volume_name = path_parts[1]
+
+ return slice_name, volume_name
+
+
+ def reply_data( self, data, datatype="application/json" ):
+ """
+ Give back a 200 response with data.
+ """
+ self.send_response( 200 )
+ self.send_header( "Content-Type", datatype )
+ self.send_header( "Content-Length", len(data) )
+ self.end_headers()
+
+ self.wfile.write( data )
+ return
+
+
+ def get_volumes_message( self, private_key_pem, observer_secret, slice_name ):
+ """
+ Get the json-ized list of volumes this slice is attached to.
+ Check the cache, evict stale data if necessary, and on miss,
+ regenerate the slice volume list.
+ """
+
+ # block the cache.
+ # NOTE: don't release the lock until we've generated credentials.
+ # Chances are, there's a thundering herd of instances coming online.
+ # Block them all until we've generated their slice's credentials,
+ # and then serve them the cached one.
+
+ self.cached_volumes_json_lock.acquire()
+
+ ret = None
+ volume_list_json, cache_timeout = self.cached_volumes_json.get( slice_name, (None, None) )
+
+ if (cache_timeout is not None) and cache_timeout < time.time():
+ # expired
+ volume_list_json = None
+
+ if volume_list_json is None:
+ # generate a new list and cache it.
+
+ volume_names = get_volumeslice_volume_names( slice_name )
+ if volume_names is None:
+ # nothing to do...
+ ret = None
+
+ else:
+ # get the slice secret
+ slice_secret = get_slice_secret( private_key_pem, slice_name )
+
+ if slice_secret is None:
+ # no such slice
+ logger.error("No slice secret for %s" % slice_name)
+ ret = None
+
+ else:
+ # seal and sign
+ ret = create_volume_list_blob( private_key_pem, slice_secret, volume_names )
+
+ # cache this
+ if ret is not None:
+ self.cached_volumes_json[ slice_name ] = (ret, time.time() + self.CACHED_VOLUMES_JSON_LIFETIME )
+
+ else:
+ # hit the cache
+ ret = volume_list_json
+
+ self.cached_volumes_json_lock.release()
+
+ return ret
+
+
+ def do_GET( self ):
+ """
+ Handle one GET
+ """
+ slice_name, volume_name = self.parse_request_path( self.path )
+
+ # valid request?
+ if volume_name is None and slice_name is None:
+ self.send_error( 400 )
+
+ # slice secret request?
+ elif volume_name == self.SLICE_SECRET_NAME and slice_name is not None:
+
+ # get the slice secret
+ ret = get_slice_secret( self.server.private_key_pem, slice_name )
+
+ if ret is not None:
+ self.reply_data( ret )
+ return
+ else:
+ self.send_error( 404 )
+
+ # volume list request?
+ elif volume_name is None and slice_name is not None:
+
+ # get the list of volumes for this slice
+ ret = self.get_volumes_message( self.server.private_key_pem, self.server.observer_secret, slice_name )
+
+ if ret is not None:
+ self.reply_data( ret )
+ return
+ else:
+ self.send_error( 404 )
+
+ # volume credential request?
+ elif volume_name is not None and slice_name is not None:
+
+ # get the VolumeSlice record
+ vs = get_volumeslice( volume_name, slice_name )
+ if vs is None:
+ # not found
+ self.send_error( 404 )
+ return
+
+ else:
+ ret = vs.credentials_blob
+ if ret is not None:
+ self.reply_data( vs.credentials_blob )
+ else:
+ # not generated???
+ print ""
+ print vs
+ print ""
+ self.send_error( 503 )
+ return
+
+ else:
+ # shouldn't get here...
+ self.send_error( 500 )
+ return
+
+
+#-------------------------------
+class CredentialServer( BaseHTTPServer.HTTPServer ):
+
+ def __init__(self, private_key_pem, observer_secret, server, req_handler ):
+ self.private_key_pem = private_key_pem
+ self.observer_secret = observer_secret
+ BaseHTTPServer.HTTPServer.__init__( self, server, req_handler )
+
+
+#-------------------------------
+def credential_server_spawn( old_exit_status ):
+ """
+ Start our credential server (i.e. in a separate process, started by the watchdog)
+ """
+
+ setproctitle.setproctitle( "syndicate-credential-server" )
+
+ private_key = syndicate_storage.read_private_key( CONFIG.SYNDICATE_PRIVATE_KEY )
+ if private_key is None:
+ # exit code 255 will be ignored...
+ logger.error("Cannot load private key. Exiting...")
+ sys.exit(255)
+
+ logger.info("Starting Syndicate Observer credential server on port %s" % CONFIG.SYNDICATE_HTTP_PORT)
+
+ srv = CredentialServer( private_key.exportKey(), CONFIG.SYNDICATE_OPENCLOUD_SECRET, ('', CONFIG.SYNDICATE_HTTP_PORT), CredentialServerHandler)
+ srv.serve_forever()
+
+
+#-------------------------------
+def ensure_credential_server_running( foreground=False, run_once=False ):
+ """
+ Instantiate our credential server and keep it running.
+ """
+
+ # is the watchdog running?
+ pids = syndicate_watchdog.find_by_attrs( "syndicate-credential-server-watchdog", {} )
+ if len(pids) > 0:
+ # it's running
+ return True
+
+ if foreground:
+ # run in foreground
+
+ if run_once:
+ return credential_server_spawn( 0 )
+
+ else:
+ return syndicate_watchdog.main( credential_server_spawn, respawn_exit_statuses=range(1,254) )
+
+
+ # not running, and not foregrounding. fork a new one
+ try:
+ watchdog_pid = os.fork()
+ except OSError, oe:
+ logger.error("Failed to fork, errno = %s" % oe.errno)
+ return False
+
+ if watchdog_pid != 0:
+
+ # child--become watchdog
+ setproctitle.setproctitle( "syndicate-credential-server-watchdog" )
+
+ if run_once:
+ syndicate_daemon.daemonize( lambda: credential_server_spawn(0), logfile_path=getattr(CONFIG, "SYNDICATE_HTTP_LOGFILE", None) )
+
+ else:
+ syndicate_daemon.daemonize( lambda: syndicate_watchdog.main( credential_server_spawn, respawn_exit_statuses=range(1,254) ), logfile_path=getattr(CONFIG, "SYNDICATE_HTTP_LOGFILE", None) )
+
+
+#-------------------------------
+# Begin functional tests.
+# Any method starting with ft_ is a functional test.
+#-------------------------------
+
+#-------------------------------
+def ft_syndicate_access():
+ """
+ Functional tests for ensuring objects exist and don't exist in Syndicate.
+ """
+
+ fake_user = FakeObject()
+ fake_user.email = "fakeuser@opencloud.us"
+
+ print "\nensure_user_exists(%s)\n" % fake_user.email
+ ensure_user_exists( fake_user.email, is_admin=False, max_UGs=1100, max_RGs=1 )
+
+ print "\nensure_user_exists(%s)\n" % fake_user.email
+ ensure_user_exists( fake_user.email, is_admin=False, max_UGs=1100, max_RGs=1 )
+
+ fake_volume = FakeObject()
+ fake_volume.name = "fakevolume"
+ fake_volume.description = "This is a fake volume, created for funtional testing"
+ fake_volume.blocksize = 1024
+ fake_volume.cap_read_data = True
+ fake_volume.cap_write_data = True
+ fake_volume.cap_host_data = False
+ fake_volume.archive = False
+ fake_volume.private = True
+
+ # test idempotency
+ print "\nensure_volume_exists(%s)\n" % fake_volume.name
+ ensure_volume_exists( fake_user.email, fake_volume )
+
+ print "\nensure_volume_exists(%s)\n" % fake_volume.name
+ ensure_volume_exists( fake_user.email, fake_volume )
+
+ print "\nensure_volume_access_right_exists(%s,%s)\n" % (fake_user.email, fake_volume.name)
+ ensure_volume_access_right_exists( fake_user.email, fake_volume.name, 31 )
+
+ print "\nensure_volume_access_right_exists(%s,%s)\n" % (fake_user.email, fake_volume.name)
+ ensure_volume_access_right_exists( fake_user.email, fake_volume.name, 31 )
+
+ print "\nensure_volume_access_right_absent(%s,%s)\n" % (fake_user.email, fake_volume.name)
+ ensure_volume_access_right_absent( fake_user.email, fake_volume.name )
+
+ print "\nensure_volume_access_right_absent(%s,%s)\n" % (fake_user.email, fake_volume.name)
+ ensure_volume_access_right_absent( fake_user.email, fake_volume.name )
+
+ print "\nensure_volume_absent(%s)\n" % fake_volume.name
+ ensure_volume_absent( fake_volume.name )
+
+ print "\nensure_volume_absent(%s)\n" % fake_volume.name
+ ensure_volume_absent( fake_volume.name )
+
+ print "\nensure_user_absent(%s)\n" % fake_user.email
+ ensure_user_absent( fake_user.email )
+
+ print "\nensure_user_absent(%s)\n" % fake_user.email
+ ensure_user_absent( fake_user.email )
+
+
+
+
+ print "\nensure_principal_exists(%s)\n" % fake_user.email
+ ensure_principal_exists( fake_user.email, "asdf", is_admin=False, max_UGs=1100, max_RGs=1 )
+
+ print "\nensure_principal_exists(%s)\n" % fake_user.email
+ ensure_principal_exists( fake_user.email, "asdf", is_admin=False, max_UGs=1100, max_RGs=1 )
+
+ print "\nensure_volume_exists(%s)\n" % fake_volume.name
+ ensure_volume_exists( fake_user.email, fake_volume )
+
+ print "\nsetup_volume_access(%s, %s)\n" % (fake_user.email, fake_volume.name)
+ setup_volume_access( fake_user.email, fake_volume.name, 31, 38800, "abcdef" )
+
+ print "\nsetup_volume_access(%s, %s)\n" % (fake_user.email, fake_volume.name)
+ setup_volume_access( fake_user.email, fake_volume.name, 31, 38800, "abcdef" )
+
+ print "\nteardown_volume_access(%s, %s)\n" % (fake_user.email, fake_volume.name )
+ teardown_volume_access( fake_user.email, fake_volume.name )
+
+ print "\nteardown_volume_access(%s, %s)\n" % (fake_user.email, fake_volume.name )
+ teardown_volume_access( fake_user.email, fake_volume.name )
+
+ print "\nensure_volume_absent(%s)\n" % fake_volume.name
+ ensure_volume_absent( fake_volume.name )
+
+ print "\nensure_principal_absent(%s)\n" % fake_user.email
+ ensure_principal_absent( fake_user.email )
+
+
+
+#-------------------------------
+def ft_volumeslice( slice_name ):
+ """
+ Functional tests for reading VolumeSlice information
+ """
+ print "slice: %s" % slice_name
+
+ volumes = get_volumeslice_volume_names( slice_name )
+
+ print "volumes mounted in slice %s:" % slice_name
+ for v in volumes:
+ print " %s:" % v
+
+ vs = get_volumeslice( v, slice_name )
+
+ print " %s" % dir(vs)
+
+
+#-------------------------------
+def ft_get_slice_hostnames( slice_name ):
+ """
+ Functional tests for getting slice hostnames
+ """
+
+ print "Get slice hostnames for %s" % slice_name
+
+ hostnames = get_slice_hostnames( slice_name )
+ import pprint
+
+ pp = pprint.PrettyPrinter()
+
+ pp.pprint( hostnames )
+
+
+#-------------------------------
+def ft_syndicate_principal():
+ """
+ Functional tests for creating, reading, and deleting SyndicatePrincipals.
+ """
+ print "generating key pair"
+ pubkey_pem, privkey_pem = api.generate_key_pair( 4096 )
+
+ user_email = "fakeuser@opencloud.us"
+
+ print "saving principal"
+ put_principal_data( user_email, "asdf", pubkey_pem, privkey_pem )
+
+ print "fetching principal private key"
+ saved_privkey_pem = get_principal_pkey( user_email, "asdf" )
+
+ assert saved_privkey_pem is not None, "Could not fetch saved private key"
+ assert saved_privkey_pem == privkey_pem, "Saved private key does not match actual private key"
+
+ print "delete principal"
+
+ delete_principal_data( user_email )
+
+ print "make sure its deleted..."
+
+ saved_privkey_pem = get_principal_pkey( user_email, "asdf" )
+
+ assert saved_privkey_pem is None, "Principal key not deleted"
+
+
+#-------------------------------
+def ft_credential_server():
+ """
+ Functional test for the credential server
+ """
+ ensure_credential_server_running( run_once=True, foreground=True )
+
+
+#-------------------------------
+def ft_seal_and_unseal():
+ """
+ Functional test for sealing/unsealing data
+ """
+ print "generating key pair"
+ pubkey_pem, privkey_pem = api.generate_key_pair( 4096 )
+
+ sealed_buf = create_sealed_and_signed_blob( privkey_pem, "foo", "hello world")
+ print "sealed data is:\n\n%s\n\n" % sealed_buf
+
+ buf = verify_and_unseal_blob( pubkey_pem, "foo", sealed_buf )
+ print "unsealed data is: \n\n%s\n\n" % buf
+
+
+# run functional tests
+if __name__ == "__main__":
+ sys.path.append("/opt/xos")
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+
+ if len(sys.argv) < 2:
+ print "Usage: %s testname [args]" % sys.argv[0]
+
+ # call a method starting with ft_, and then pass the rest of argv as its arguments
+ testname = sys.argv[1]
+ ft_testname = "ft_%s" % testname
+
+ test_call = "%s(%s)" % (ft_testname, ",".join(sys.argv[2:]))
+
+ print "calling %s" % test_call
+
+ rc = eval( test_call )
+
+ print "result = %s" % rc
+
+
diff --git a/xos/syndicate_observer/syndicatelib_config/__init__.py b/xos/synchronizers/syndicate/syndicatelib_config/__init__.py
similarity index 100%
rename from xos/syndicate_observer/syndicatelib_config/__init__.py
rename to xos/synchronizers/syndicate/syndicatelib_config/__init__.py
diff --git a/xos/synchronizers/syndicate/syndicatelib_config/config-jude.py b/xos/synchronizers/syndicate/syndicatelib_config/config-jude.py
new file mode 100644
index 0000000..9e0f1fd
--- /dev/null
+++ b/xos/synchronizers/syndicate/syndicatelib_config/config-jude.py
@@ -0,0 +1,21 @@
+#!/usr/bin/env python
+
+# configuration for syndicatelib
+SYNDICATE_SMI_URL="http://localhost:8080"
+
+SYNDICATE_OPENID_TRUSTROOT="http://localhost:8081"
+
+SYNDICATE_OPENCLOUD_USER="judecn@gmail.com"
+SYNDICATE_OPENCLOUD_PASSWORD="nya"
+
+SYNDICATE_PYTHONPATH="/home/jude/Desktop/research/git/syndicate/build/out/python"
+
+SYNDICATE_PRIVATE_KEY="/home/jude/Desktop/research/git/syndicate/opencloud/observers/syndicate/syndicatelib_config/pollserver.pem"
+SYNDICATE_OPENCLOUD_SECRET="e4988309a5005edb8ea185f16f607938c0fb7657e4d7609853bcb7c4884d1c92"
+
+SYNDICATE_HTTP_PORT=65321
+
+SYNDICATE_RG_CLOSURE="/home/jude/Desktop/research/git/syndicate/build/out/python/syndicate/rg/drivers/disk"
+SYNDICATE_RG_DEFAULT_PORT=38800
+
+DEBUG=True
diff --git a/xos/synchronizers/syndicate/syndicatelib_config/config-opencloud.py b/xos/synchronizers/syndicate/syndicatelib_config/config-opencloud.py
new file mode 100644
index 0000000..b3add16
--- /dev/null
+++ b/xos/synchronizers/syndicate/syndicatelib_config/config-opencloud.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+
+# ---------------------------------
+# This is the configuration file used by the Syndicate observer.
+# It is a well-formed Python file, and will be imported into the
+# observer as a Python module. This means you can run any config-
+# generation code here you like, but all of the following global
+# variables must be defined.
+# ---------------------------------
+
+# URL to the Syndicate SMI. For example, https://syndicate-metadata.appspot.com
+SYNDICATE_SMI_URL="http://localhost:8080"
+
+# If you are going to use OpenID to authenticate the Syndicate instance daemon,
+# this is the OpenID provider URL. It is currently used only to generate
+# identity pages for users, so you can put whatever you want here for now.
+SYNDICATE_OPENID_TRUSTROOT="http://localhost:8081"
+
+# This is the observer's user account on Syndicate. You must create it out-of-band
+# prior to using the observer, and it must be an admin user since it will
+# create other users (i.e. for slices).
+SYNDICATE_OPENCLOUD_USER="jcnelson@cs.princeton.edu"
+
+# This is the password for the observer to authenticate itself to Syndicate.
+SYNDICATE_OPENCLOUD_PASSWORD="nya"
+
+# If the observer uses public-key authentication with Syndicate, you will
+# need to identify the absolute path to its private key here. It must be
+# a 4096-bit PEM-encoded RSA key, and the Syndicate observer's user account
+# must have been given the public key on activation.
+SYNDICATE_OPENCLOUD_PKEY=None
+
+# This is the location on disk where Syndicate observer code can be found,
+# if it is not already in the Python path. This is optional.
+SYNDICATE_PYTHONPATH="/root/syndicate/build/out/python"
+
+# This is the location of the observer's private key. It must be an absolute
+# path, and refer to a 4096-bit PEM-encoded RSA key.
+SYNDICATE_PRIVATE_KEY="/opt/xos/observers/syndicate/syndicatelib_config/pollserver.pem"
+
+# This is the master secret used to generate secrets to seal sensitive information sent to the
+# Syndicate instance mount daemons. It is also used to seal sensitive information
+# stored to the Django database.
+# TODO: think of a way to not have to store this on disk. Maybe we feed into the
+# observer when it starts up?
+SYNDICATE_OPENCLOUD_SECRET="e4988309a5005edb8ea185f16f607938c0fb7657e4d7609853bcb7c4884d1c92"
+
+# This is the default port number on which a Syndicate Replica Gateway
+# will be provisioned. It's a well-known port, and can be the same across
+# instances, since in OpenCloud, an RG instance only listens to localhost.
+SYNDICATE_RG_DEFAULT_PORT=38800
+
+# This is the absolute path to the RG's storage driver (which will be automatically
+# pushed to instances by Syndicate). See https://github.com/jcnelson/syndicate/wiki/Replica-Gateways
+SYNDICATE_RG_CLOSURE=None
+
+# This is the port number the observer listens on for GETs from the Syndicate instance mount
+# daemons. Normally, the oserver pushes (encrypted) commands to the daemons, but if the
+# daemons are NAT'ed or temporarily partitioned, they will pull commands instead.
+SYNDICATE_HTTP_PORT=65321
+
+# This is the path to the logfile for the observer's HTTP server.
+SYNDICATE_HTTP_LOGFILE="/tmp/syndicate-observer.log"
+
+# This is the number of seconds to wait for pushing a slice credential before timing out.
+SYNDICATE_HTTP_PUSH_TIMEOUT=60
+
+# This is the port number the Syndicate instance mount daemons listen on. The observer will
+# push commands to them on this port.
+SYNDICATE_SLIVER_PORT=65322
+
+# If true, print verbose debug messages.
+DEBUG=True
diff --git a/xos/synchronizers/syndicate/syndicatelib_config/config.py b/xos/synchronizers/syndicate/syndicatelib_config/config.py
new file mode 100644
index 0000000..b3add16
--- /dev/null
+++ b/xos/synchronizers/syndicate/syndicatelib_config/config.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python
+
+# ---------------------------------
+# This is the configuration file used by the Syndicate observer.
+# It is a well-formed Python file, and will be imported into the
+# observer as a Python module. This means you can run any config-
+# generation code here you like, but all of the following global
+# variables must be defined.
+# ---------------------------------
+
+# URL to the Syndicate SMI. For example, https://syndicate-metadata.appspot.com
+SYNDICATE_SMI_URL="http://localhost:8080"
+
+# If you are going to use OpenID to authenticate the Syndicate instance daemon,
+# this is the OpenID provider URL. It is currently used only to generate
+# identity pages for users, so you can put whatever you want here for now.
+SYNDICATE_OPENID_TRUSTROOT="http://localhost:8081"
+
+# This is the observer's user account on Syndicate. You must create it out-of-band
+# prior to using the observer, and it must be an admin user since it will
+# create other users (i.e. for slices).
+SYNDICATE_OPENCLOUD_USER="jcnelson@cs.princeton.edu"
+
+# This is the password for the observer to authenticate itself to Syndicate.
+SYNDICATE_OPENCLOUD_PASSWORD="nya"
+
+# If the observer uses public-key authentication with Syndicate, you will
+# need to identify the absolute path to its private key here. It must be
+# a 4096-bit PEM-encoded RSA key, and the Syndicate observer's user account
+# must have been given the public key on activation.
+SYNDICATE_OPENCLOUD_PKEY=None
+
+# This is the location on disk where Syndicate observer code can be found,
+# if it is not already in the Python path. This is optional.
+SYNDICATE_PYTHONPATH="/root/syndicate/build/out/python"
+
+# This is the location of the observer's private key. It must be an absolute
+# path, and refer to a 4096-bit PEM-encoded RSA key.
+SYNDICATE_PRIVATE_KEY="/opt/xos/observers/syndicate/syndicatelib_config/pollserver.pem"
+
+# This is the master secret used to generate secrets to seal sensitive information sent to the
+# Syndicate instance mount daemons. It is also used to seal sensitive information
+# stored to the Django database.
+# TODO: think of a way to not have to store this on disk. Maybe we feed into the
+# observer when it starts up?
+SYNDICATE_OPENCLOUD_SECRET="e4988309a5005edb8ea185f16f607938c0fb7657e4d7609853bcb7c4884d1c92"
+
+# This is the default port number on which a Syndicate Replica Gateway
+# will be provisioned. It's a well-known port, and can be the same across
+# instances, since in OpenCloud, an RG instance only listens to localhost.
+SYNDICATE_RG_DEFAULT_PORT=38800
+
+# This is the absolute path to the RG's storage driver (which will be automatically
+# pushed to instances by Syndicate). See https://github.com/jcnelson/syndicate/wiki/Replica-Gateways
+SYNDICATE_RG_CLOSURE=None
+
+# This is the port number the observer listens on for GETs from the Syndicate instance mount
+# daemons. Normally, the oserver pushes (encrypted) commands to the daemons, but if the
+# daemons are NAT'ed or temporarily partitioned, they will pull commands instead.
+SYNDICATE_HTTP_PORT=65321
+
+# This is the path to the logfile for the observer's HTTP server.
+SYNDICATE_HTTP_LOGFILE="/tmp/syndicate-observer.log"
+
+# This is the number of seconds to wait for pushing a slice credential before timing out.
+SYNDICATE_HTTP_PUSH_TIMEOUT=60
+
+# This is the port number the Syndicate instance mount daemons listen on. The observer will
+# push commands to them on this port.
+SYNDICATE_SLIVER_PORT=65322
+
+# If true, print verbose debug messages.
+DEBUG=True
diff --git a/xos/syndicate_observer/syndicatelib_config/pollserver.pem b/xos/synchronizers/syndicate/syndicatelib_config/pollserver.pem
similarity index 100%
rename from xos/syndicate_observer/syndicatelib_config/pollserver.pem
rename to xos/synchronizers/syndicate/syndicatelib_config/pollserver.pem
diff --git a/xos/observers/vbng/model-deps b/xos/synchronizers/vbng/model-deps
similarity index 100%
rename from xos/observers/vbng/model-deps
rename to xos/synchronizers/vbng/model-deps
diff --git a/xos/observers/vbng/run.sh b/xos/synchronizers/vbng/run.sh
similarity index 100%
rename from xos/observers/vbng/run.sh
rename to xos/synchronizers/vbng/run.sh
diff --git a/xos/observers/vbng/start.sh b/xos/synchronizers/vbng/start.sh
similarity index 100%
rename from xos/observers/vbng/start.sh
rename to xos/synchronizers/vbng/start.sh
diff --git a/xos/synchronizers/vbng/steps/sync_vbngtenant.py b/xos/synchronizers/vbng/steps/sync_vbngtenant.py
new file mode 100644
index 0000000..94875f4
--- /dev/null
+++ b/xos/synchronizers/vbng/steps/sync_vbngtenant.py
@@ -0,0 +1,142 @@
+import os
+import requests
+import socket
+import sys
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from synchronizers.base.ansible import run_template_ssh
+from core.models import Service
+from services.cord.models import VCPEService, VCPETenant, VBNGTenant, VBNGService
+from services.hpc.models import HpcService, CDNPrefix
+from xos.logger import Logger, logging
+
+# VBNG_API = "http://10.0.3.136:8181/onos/virtualbng/privateip/"
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+logger = Logger(level=logging.INFO)
+
+class SyncVBNGTenant(SyncStep):
+ provides=[VCPETenant]
+ observes=VCPETenant
+ requested_interval=0
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+
+ def fetch_pending(self, deleted):
+ if (not deleted):
+ objs = VBNGTenant.get_tenant_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
+ else:
+ objs = VBNGTenant.get_deleted_tenant_objects()
+
+ return objs
+
+ def defer_sync(self, o, reason):
+ logger.info("defer object %s due to %s" % (str(o), reason))
+ raise Exception("defer object %s due to %s" % (str(o), reason))
+
+ def get_vbng_service(self, o):
+ if not o.provider_service:
+ raise Exception("vBNG tenant %s has no provider_service" % str(o.id))
+ services = VBNGService.get_service_objects().filter(id = o.provider_service.id)
+ if not services:
+ raise Exception("vBNG tenant %s is associated with the wrong kind of provider_service" % str(o.id))
+ return services[0]
+
+ def get_vbng_url(self, o):
+ service = self.get_vbng_service(o)
+
+ # if the service object specifies a vbng_url, then use it
+ if service.vbng_url:
+ return service.vbng_url
+
+ # otherwise, see if the service has tenancy in ONOS
+ for tenant in service.subscribed_tenants.all():
+ if tenant.provider_service and tenant.provider_service.kind == "onos":
+ onos_service = tenant.provider_service
+ if not onos_service.slices.exists():
+ raise Exception("vBNG service is linked to an ONOSApp, but the App's Service has no slices")
+ onos_slice = onos_service.slices.all()[0]
+ if not onos_slice.instances.exists():
+ raise Exception("vBNG service is linked to an ONOSApp, but the App's Service's Slice has no instances")
+ instance = onos_slice.instances.all()[0]
+
+ #onos_app = ONOSApp.objects.filter(id = tenant.id)
+ #instance = onos_app.instance
+ #if not instance:
+ # raise Exception("ONOSApp has no instance")
+
+ if not instance.instance_name:
+ raise Exception("vBNG service is linked to an ONOSApp, but the App's Service's Slice's first instance is not instantiated")
+ ip = instance.get_network_ip("nat")
+ if not ip:
+ raise Exception("vBNG service is linked to an ONOSApp, but the App's Service's Slice's first instance does not have an ip")
+
+ logger.info("Using ip %s from ONOS Instance %s" % (ip, instance))
+
+ return "http://%s:8181/onos/virtualbng/" % ip
+
+ raise Exception("vBNG service does not have vbng_url set, and is not linked to an ONOSApp")
+
+ def get_private_interface(self, o):
+ vcpes = VCPETenant.get_tenant_objects().all()
+ vcpes = [x for x in vcpes if (x.vbng is not None) and (x.vbng.id == o.id)]
+ if not vcpes:
+ raise Exception("No vCPE tenant is associated with vBNG %s" % str(o.id))
+ if len(vcpes)>1:
+ raise Exception("More than one vCPE tenant is associated with vBNG %s" % str(o.id))
+
+ vcpe = vcpes[0]
+ instance = vcpe.instance
+
+ if not instance:
+ raise Exception("No instance associated with vBNG %s" % str(o.id))
+
+ if not vcpe.wan_ip:
+ self.defer_sync(o, "does not have a WAN IP yet")
+
+ if not vcpe.wan_container_mac:
+ # this should never happen; container MAC is computed from WAN IP
+ self.defer_sync(o, "does not have a WAN container MAC yet")
+
+ return (vcpe.wan_ip, vcpe.wan_container_mac, vcpe.instance.node.name)
+
+ def sync_record(self, o):
+ logger.info("sync'ing VBNGTenant %s" % str(o))
+
+ if not o.routeable_subnet:
+ (private_ip, private_mac, private_hostname) = self.get_private_interface(o)
+ logger.info("contacting vBNG service to request mapping for private ip %s mac %s host %s" % (private_ip, private_mac, private_hostname) )
+
+ url = self.get_vbng_url(o) + "privateip/%s/%s/%s" % (private_ip, private_mac, private_hostname)
+ logger.info( "vbng url: %s" % url )
+ r = requests.post(url )
+ if (r.status_code != 200):
+ raise Exception("Received error from bng service (%d)" % r.status_code)
+ logger.info("received public IP %s from private IP %s" % (r.text, private_ip))
+
+ if r.text == "0":
+ raise Exception("VBNG service failed to return a routeable_subnet (probably ran out)")
+
+ o.routeable_subnet = r.text
+ o.mapped_ip = private_ip
+ o.mapped_mac = private_mac
+ o.mapped_hostname = private_hostname
+
+ o.save()
+
+ def delete_record(self, o):
+ logger.info("deleting VBNGTenant %s" % str(o))
+
+ if o.mapped_ip:
+ private_ip = o.mapped_ip
+ logger.info("contacting vBNG service to delete private ip %s" % private_ip)
+ r = requests.delete(self.get_vbng_url(o) + "privateip/%s" % private_ip, )
+ if (r.status_code != 200):
+ raise Exception("Received error from bng service (%d)" % r.status_code)
+
diff --git a/xos/observers/vbng/stop.sh b/xos/synchronizers/vbng/stop.sh
similarity index 100%
rename from xos/observers/vbng/stop.sh
rename to xos/synchronizers/vbng/stop.sh
diff --git a/xos/observers/vbng/supervisor/vbng-observer.conf b/xos/synchronizers/vbng/supervisor/vbng-observer.conf
similarity index 100%
rename from xos/observers/vbng/supervisor/vbng-observer.conf
rename to xos/synchronizers/vbng/supervisor/vbng-observer.conf
diff --git a/xos/synchronizers/vbng/vbng-synchronizer.py b/xos/synchronizers/vbng/vbng-synchronizer.py
new file mode 100755
index 0000000..84bec4f
--- /dev/null
+++ b/xos/synchronizers/vbng/vbng-synchronizer.py
@@ -0,0 +1,11 @@
+#!/usr/bin/env python
+
+# This imports and runs ../../xos-observer.py
+
+import importlib
+import os
+import sys
+observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../../synchronizers/base")
+sys.path.append(observer_path)
+mod = importlib.import_module("xos-synchronizer")
+mod.main()
diff --git a/xos/synchronizers/vbng/vbng_synchronizer_config b/xos/synchronizers/vbng/vbng_synchronizer_config
new file mode 100644
index 0000000..d613ce3
--- /dev/null
+++ b/xos/synchronizers/vbng/vbng_synchronizer_config
@@ -0,0 +1,38 @@
+
+[plc]
+name=plc
+deployment=VICCI
+
+[db]
+name=xos
+user=postgres
+password=password
+host=localhost
+port=5432
+
+[api]
+host=128.112.171.237
+port=8000
+ssl_key=None
+ssl_cert=None
+ca_ssl_cert=None
+ratelimit_enabled=0
+omf_enabled=0
+mail_support_address=support@localhost
+nova_enabled=True
+
+[observer]
+name=vbng
+dependency_graph=/opt/xos/synchronizers/vbng/model-deps
+steps_dir=/opt/xos/synchronizers/vbng/steps
+sys_dir=/opt/xos/synchronizers/vbng/sys
+deleters_dir=/opt/xos/synchronizers/vbng/deleters
+log_file=console
+#/var/log/hpc.log
+driver=None
+pretend=False
+backoff_disabled=True
+
+[feefie]
+client_id='vicci_dev_central'
+user_id='pl'
diff --git a/xos/observers/vcpe/broadbandshield.py b/xos/synchronizers/vcpe/broadbandshield.py
similarity index 100%
rename from xos/observers/vcpe/broadbandshield.py
rename to xos/synchronizers/vcpe/broadbandshield.py
diff --git a/xos/observers/vcpe/files/docker.list b/xos/synchronizers/vcpe/files/docker.list
similarity index 100%
rename from xos/observers/vcpe/files/docker.list
rename to xos/synchronizers/vcpe/files/docker.list
diff --git a/xos/observers/vcpe/files/etc/rc.local b/xos/synchronizers/vcpe/files/etc/rc.local
similarity index 100%
rename from xos/observers/vcpe/files/etc/rc.local
rename to xos/synchronizers/vcpe/files/etc/rc.local
diff --git a/xos/observers/vcpe/files/etc/ufw/after.init b/xos/synchronizers/vcpe/files/etc/ufw/after.init
similarity index 100%
rename from xos/observers/vcpe/files/etc/ufw/after.init
rename to xos/synchronizers/vcpe/files/etc/ufw/after.init
diff --git a/xos/observers/vcpe/files/etc/ufw/after.rules b/xos/synchronizers/vcpe/files/etc/ufw/after.rules
similarity index 100%
rename from xos/observers/vcpe/files/etc/ufw/after.rules
rename to xos/synchronizers/vcpe/files/etc/ufw/after.rules
diff --git a/xos/observers/vcpe/files/etc/ufw/after6.rules b/xos/synchronizers/vcpe/files/etc/ufw/after6.rules
similarity index 100%
rename from xos/observers/vcpe/files/etc/ufw/after6.rules
rename to xos/synchronizers/vcpe/files/etc/ufw/after6.rules
diff --git a/xos/synchronizers/vcpe/files/etc/ufw/applications.d/openssh-server b/xos/synchronizers/vcpe/files/etc/ufw/applications.d/openssh-server
new file mode 100644
index 0000000..9bbe906
--- /dev/null
+++ b/xos/synchronizers/vcpe/files/etc/ufw/applications.d/openssh-server
@@ -0,0 +1,4 @@
+[OpenSSH]
+title=Secure shell server, an rshd replacement
+description=OpenSSH is a free implementation of the Secure Shell protocol.
+ports=22/tcp
diff --git a/xos/observers/vcpe/files/etc/ufw/before.init b/xos/synchronizers/vcpe/files/etc/ufw/before.init
similarity index 100%
rename from xos/observers/vcpe/files/etc/ufw/before.init
rename to xos/synchronizers/vcpe/files/etc/ufw/before.init
diff --git a/xos/observers/vcpe/files/etc/ufw/before6.rules b/xos/synchronizers/vcpe/files/etc/ufw/before6.rules
similarity index 100%
rename from xos/observers/vcpe/files/etc/ufw/before6.rules
rename to xos/synchronizers/vcpe/files/etc/ufw/before6.rules
diff --git a/xos/observers/vcpe/files/etc/ufw/sysctl.conf b/xos/synchronizers/vcpe/files/etc/ufw/sysctl.conf
similarity index 100%
rename from xos/observers/vcpe/files/etc/ufw/sysctl.conf
rename to xos/synchronizers/vcpe/files/etc/ufw/sysctl.conf
diff --git a/xos/observers/vcpe/files/etc/ufw/ufw.conf b/xos/synchronizers/vcpe/files/etc/ufw/ufw.conf
similarity index 100%
rename from xos/observers/vcpe/files/etc/ufw/ufw.conf
rename to xos/synchronizers/vcpe/files/etc/ufw/ufw.conf
diff --git a/xos/observers/vcpe/files/vcpe.conf b/xos/synchronizers/vcpe/files/vcpe.conf
similarity index 100%
rename from xos/observers/vcpe/files/vcpe.conf
rename to xos/synchronizers/vcpe/files/vcpe.conf
diff --git a/xos/observers/vcpe/files/vcpe.dnsmasq b/xos/synchronizers/vcpe/files/vcpe.dnsmasq
similarity index 100%
rename from xos/observers/vcpe/files/vcpe.dnsmasq
rename to xos/synchronizers/vcpe/files/vcpe.dnsmasq
diff --git a/xos/observers/vcpe/files/vm-resolv.conf b/xos/synchronizers/vcpe/files/vm-resolv.conf
similarity index 100%
rename from xos/observers/vcpe/files/vm-resolv.conf
rename to xos/synchronizers/vcpe/files/vm-resolv.conf
diff --git a/xos/observers/vcpe/model-deps b/xos/synchronizers/vcpe/model-deps
similarity index 100%
rename from xos/observers/vcpe/model-deps
rename to xos/synchronizers/vcpe/model-deps
diff --git a/xos/synchronizers/vcpe/observer_ansible_test.py b/xos/synchronizers/vcpe/observer_ansible_test.py
new file mode 100644
index 0000000..b28da63
--- /dev/null
+++ b/xos/synchronizers/vcpe/observer_ansible_test.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+import os
+import sys
+
+sys.path.append("../..")
+import synchronizers.base.ansible
+
+print sys.argv
+
+private_key="""-----BEGIN RSA PRIVATE KEY-----
+MIIEpQIBAAKCAQEAtJiuarud5S4Y2quDeWyaS0UCQGQtfuSzzNhplFwujYnJGL65
+e14REtv+UuHGymyr/SfkTrBd8vH5NI2UZ/4sZW13ieI/1d97OeVe2+ct0Y4Ba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F84/yX6d2Goenyw4wzkA8QDQoJxu789yRgBTgQh
+VwLw/AZ4PvoyWMdbAENApgECgYEAvFikosYP09XTyIPaKaOKY5iqqBoSC1GucSOB
+jAG+T3k5dxB6nQS0nYQUomvqak7drqnT6O33Lrr5ySrW5nCjnmvgJZwvv+Rp1bDM
+K5uRT8caPpJ+Wcp4TUdPi3BVA2MOHVDyEJg3AH/D1+DL/IgGQ/JcwOHsKt61iLhO
+EBXj5zECgYEAk+HuwksUPkSxg/AiJGbapGDK6XGymEUzo2duWlnofRqGcZ3NT3bB
+/kDI1KxQdlpODXSi4/BuTpbQiFOrzcEq5e5ytoMxlCHh3Fl3Jxl+JlgO21vAUvP6
+4SET7Q/6LxmfBlCVRg0dXDwcfJLgbnWxyvprIcz4e0FSFVZTBs/6tFk=
+-----END RSA PRIVATE KEY-----
+"""
+
+observer.ansible.run_template_ssh("test.yaml",
+ {"instance_name": "onlab_test405-378",
+ "instance_id": "instance-0000004d",
+ "hostname": "node67.washington.vicci.org",
+ "private_key": private_key})
+
diff --git a/xos/observers/vcpe/run.sh b/xos/synchronizers/vcpe/run.sh
similarity index 100%
rename from xos/observers/vcpe/run.sh
rename to xos/synchronizers/vcpe/run.sh
diff --git a/xos/observers/vcpe/start-bbs.sh b/xos/synchronizers/vcpe/start-bbs.sh
similarity index 100%
rename from xos/observers/vcpe/start-bbs.sh
rename to xos/synchronizers/vcpe/start-bbs.sh
diff --git a/xos/observers/vcpe/start.sh b/xos/synchronizers/vcpe/start.sh
similarity index 100%
rename from xos/observers/vcpe/start.sh
rename to xos/synchronizers/vcpe/start.sh
diff --git a/xos/observers/vcpe/steps/ansible_test/README b/xos/synchronizers/vcpe/steps/ansible_test/README
similarity index 100%
rename from xos/observers/vcpe/steps/ansible_test/README
rename to xos/synchronizers/vcpe/steps/ansible_test/README
diff --git a/xos/observers/vcpe/steps/ansible_test/inventory.txt b/xos/synchronizers/vcpe/steps/ansible_test/inventory.txt
similarity index 100%
rename from xos/observers/vcpe/steps/ansible_test/inventory.txt
rename to xos/synchronizers/vcpe/steps/ansible_test/inventory.txt
diff --git a/xos/observers/vcpe/steps/ansible_test/test.sh b/xos/synchronizers/vcpe/steps/ansible_test/test.sh
similarity index 100%
rename from xos/observers/vcpe/steps/ansible_test/test.sh
rename to xos/synchronizers/vcpe/steps/ansible_test/test.sh
diff --git a/xos/observers/vcpe/steps/ansible_test/test.yaml b/xos/synchronizers/vcpe/steps/ansible_test/test.yaml
similarity index 100%
rename from xos/observers/vcpe/steps/ansible_test/test.yaml
rename to xos/synchronizers/vcpe/steps/ansible_test/test.yaml
diff --git a/xos/observers/vcpe/steps/ansible_test/xos.py b/xos/synchronizers/vcpe/steps/ansible_test/xos.py
similarity index 100%
rename from xos/observers/vcpe/steps/ansible_test/xos.py
rename to xos/synchronizers/vcpe/steps/ansible_test/xos.py
diff --git a/xos/synchronizers/vcpe/steps/sync_vcpetenant.py b/xos/synchronizers/vcpe/steps/sync_vcpetenant.py
new file mode 100644
index 0000000..691671a
--- /dev/null
+++ b/xos/synchronizers/vcpe/steps/sync_vcpetenant.py
@@ -0,0 +1,235 @@
+import hashlib
+import os
+import socket
+import sys
+import base64
+import time
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from synchronizers.base.ansible import run_template_ssh
+from synchronizers.base.SyncInstanceUsingAnsible import SyncInstanceUsingAnsible
+from core.models import Service, Slice
+from services.cord.models import VCPEService, VCPETenant, VOLTTenant
+from services.hpc.models import HpcService, CDNPrefix
+from xos.logger import Logger, logging
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+from broadbandshield import BBS
+
+logger = Logger(level=logging.INFO)
+
+PARENTAL_MECHANISM="dnsmasq"
+ENABLE_QUICK_UPDATE=False
+
+class SyncVCPETenant(SyncInstanceUsingAnsible):
+ provides=[VCPETenant]
+ observes=VCPETenant
+ requested_interval=0
+ template_name = "sync_vcpetenant.yaml"
+ service_key_name = "/opt/xos/observers/vcpe/vcpe_private_key"
+
+ def __init__(self, *args, **kwargs):
+ super(SyncVCPETenant, self).__init__(*args, **kwargs)
+
+ def fetch_pending(self, deleted):
+ if (not deleted):
+ objs = VCPETenant.get_tenant_objects().filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
+ else:
+ objs = VCPETenant.get_deleted_tenant_objects()
+
+ return objs
+
+ def get_vcpe_service(self, o):
+ if not o.provider_service:
+ return None
+
+ vcpes = VCPEService.get_service_objects().filter(id=o.provider_service.id)
+ if not vcpes:
+ return None
+
+ return vcpes[0]
+
+ def get_extra_attributes(self, o):
+ # This is a place to include extra attributes that aren't part of the
+ # object itself. In the case of vCPE, we need to know:
+ # 1) the addresses of dnsdemux, to setup dnsmasq in the vCPE
+ # 2) CDN prefixes, so we know what URLs to send to dnsdemux
+ # 3) BroadBandShield server addresses, for parental filtering
+ # 4) vlan_ids, for setting up networking in the vCPE VM
+
+ vcpe_service = self.get_vcpe_service(o)
+
+ dnsdemux_ip = None
+ if vcpe_service.backend_network_label:
+ # Connect to dnsdemux using the network specified by
+ # vcpe_service.backend_network_label
+ for service in HpcService.objects.all():
+ for slice in service.slices.all():
+ if "dnsdemux" in slice.name:
+ for instance in slice.instances.all():
+ for ns in instance.ports.all():
+ if ns.ip and ns.network.labels and (vcpe_service.backend_network_label in ns.network.labels):
+ dnsdemux_ip = ns.ip
+ if not dnsdemux_ip:
+ logger.info("failed to find a dnsdemux on network %s" % vcpe_service.backend_network_label)
+ else:
+ # Connect to dnsdemux using the instance's public address
+ for service in HpcService.objects.all():
+ for slice in service.slices.all():
+ if "dnsdemux" in slice.name:
+ for instance in slice.instances.all():
+ if dnsdemux_ip=="none":
+ try:
+ dnsdemux_ip = socket.gethostbyname(instance.node.name)
+ except:
+ pass
+ if not dnsdemux_ip:
+ logger.info("failed to find a dnsdemux with a public address")
+
+ dnsdemux_ip = dnsdemux_ip or "none"
+
+ cdn_prefixes = []
+ for prefix in CDNPrefix.objects.all():
+ cdn_prefixes.append(prefix.prefix)
+
+ # Broadbandshield can either be set up internally, using vcpe_service.bbs_slice,
+ # or it can be setup externally using vcpe_service.bbs_server.
+
+ bbs_addrs = []
+ if vcpe_service.bbs_slice:
+ if vcpe_service.backend_network_label:
+ for bbs_instance in vcpe_service.bbs_slice.instances.all():
+ for ns in bbs_instance.ports.all():
+ if ns.ip and ns.network.labels and (vcpe_service.backend_network_label in ns.network.labels):
+ bbs_addrs.append(ns.ip)
+ else:
+ logger.info("unsupported configuration -- bbs_slice is set, but backend_network_label is not")
+ if not bbs_addrs:
+ logger.info("failed to find any usable addresses on bbs_slice")
+ elif vcpe_service.bbs_server:
+ bbs_addrs.append(vcpe_service.bbs_server)
+ else:
+ logger.info("neither bbs_slice nor bbs_server is configured in the vCPE")
+
+ vlan_ids = []
+ s_tags = []
+ c_tags = []
+ if o.volt:
+ vlan_ids.append(o.volt.vlan_id) # XXX remove this
+ s_tags.append(o.volt.s_tag)
+ c_tags.append(o.volt.c_tag)
+
+ try:
+ full_setup = Config().observer_full_setup
+ except:
+ full_setup = True
+
+ safe_macs=[]
+ if o.volt and o.volt.subscriber:
+ for user in o.volt.subscriber.users:
+ level = user.get("level",None)
+ mac = user.get("mac",None)
+ if level in ["G", "PG"]:
+ if mac:
+ safe_macs.append(mac)
+
+ fields = {"vlan_ids": vlan_ids, # XXX remove this
+ "s_tags": s_tags,
+ "c_tags": c_tags,
+ "dnsdemux_ip": dnsdemux_ip,
+ "cdn_prefixes": cdn_prefixes,
+ "bbs_addrs": bbs_addrs,
+ "full_setup": full_setup,
+ "isolation": o.instance.isolation,
+ "safe_browsing_macs": safe_macs}
+
+ # add in the sync_attributes that come from the SubscriberRoot object
+
+ if o.volt and o.volt.subscriber and hasattr(o.volt.subscriber, "sync_attributes"):
+ for attribute_name in o.volt.subscriber.sync_attributes:
+ fields[attribute_name] = getattr(o.volt.subscriber, attribute_name)
+
+ return fields
+
+ def sync_fields(self, o, fields):
+ # the super causes the playbook to be run
+
+ super(SyncVCPETenant, self).sync_fields(o, fields)
+
+ # now do all of our broadbandshield stuff...
+
+ service = self.get_vcpe_service(o)
+ if not service:
+ # Ansible uses the service's keypair in order to SSH into the
+ # instance. It would be bad if the slice had no service.
+
+ raise Exception("Slice %s is not associated with a service" % instance.slice.name)
+
+ # Make sure the slice is configured properly
+ if (service != o.instance.slice.service):
+ raise Exception("Slice %s is associated with some service that is not %s" % (str(instance.slice), str(service)))
+
+ # only enable filtering if we have a subscriber object (see below)
+ url_filter_enable = False
+
+ # for attributes that come from CordSubscriberRoot
+ if o.volt and o.volt.subscriber:
+ url_filter_enable = o.volt.subscriber.url_filter_enable
+ url_filter_level = o.volt.subscriber.url_filter_level
+ url_filter_users = o.volt.subscriber.users
+
+ if PARENTAL_MECHANISM=="broadbandshield":
+ # disable url_filter if there are no bbs_addrs
+ if url_filter_enable and (not fields.get("bbs_addrs",[])):
+ logger.info("disabling url_filter because there are no bbs_addrs")
+ url_filter_enable = False
+
+ if url_filter_enable:
+ bbs_hostname = None
+ if service.bbs_api_hostname and service.bbs_api_port:
+ bbs_hostname = service.bbs_api_hostname
+ else:
+ # TODO: extract from slice
+ bbs_hostname = "cordcompute01.onlab.us"
+
+ if service.bbs_api_port:
+ bbs_port = service.bbs_api_port
+ else:
+ bbs_port = 8018
+
+ if not bbs_hostname:
+ logger.info("broadbandshield is not configured")
+ else:
+ tStart = time.time()
+ bbs = BBS(o.bbs_account, "123", bbs_hostname, bbs_port)
+ bbs.sync(url_filter_level, url_filter_users)
+
+ if o.hpc_client_ip:
+ logger.info("associate account %s with ip %s" % (o.bbs_account, o.hpc_client_ip))
+ bbs.associate(o.hpc_client_ip)
+ else:
+ logger.info("no hpc_client_ip to associate")
+
+ logger.info("bbs update time %d" % int(time.time()-tStart))
+
+
+ def run_playbook(self, o, fields):
+ ansible_hash = hashlib.md5(repr(sorted(fields.items()))).hexdigest()
+ quick_update = (o.last_ansible_hash == ansible_hash)
+
+ if ENABLE_QUICK_UPDATE and quick_update:
+ logger.info("quick_update triggered; skipping ansible recipe")
+ else:
+ if o.instance.isolation in ["container", "container_vm"]:
+ super(SyncVCPETenant, self).run_playbook(o, fields, "sync_vcpetenant_new.yaml")
+ else:
+ super(SyncVCPETenant, self).run_playbook(o, fields)
+
+ o.last_ansible_hash = ansible_hash
+
+ def delete_record(self, m):
+ pass
diff --git a/xos/synchronizers/vcpe/steps/sync_vcpetenant.yaml b/xos/synchronizers/vcpe/steps/sync_vcpetenant.yaml
new file mode 100644
index 0000000..fdc21da
--- /dev/null
+++ b/xos/synchronizers/vcpe/steps/sync_vcpetenant.yaml
@@ -0,0 +1,174 @@
+---
+- hosts: {{ instance_name }}
+ gather_facts: False
+ connection: ssh
+ user: ubuntu
+ sudo: yes
+ vars:
+ cdn_enable: {{ cdn_enable }}
+ dnsdemux_ip: {{ dnsdemux_ip }}
+ firewall_enable: {{ firewall_enable }}
+ url_filter_enable: {{ url_filter_enable }}
+ vlan_ids:
+ {% for vlan_id in vlan_ids %}
+ - {{ vlan_id }}
+ {% endfor %}
+ c_tags:
+ {% for c_tag in c_tags %}
+ - {{ c_tag }}
+ {% endfor %}
+ s_tags:
+ {% for s_tag in s_tags %}
+ - {{ s_tag }}
+ {% endfor %}
+ firewall_rules:
+ {% for firewall_rule in firewall_rules.split("\n") %}
+ - {{ firewall_rule }}
+ {% endfor %}
+ cdn_prefixes:
+ {% for prefix in cdn_prefixes %}
+ - {{ prefix }}
+ {% endfor %}
+ bbs_addrs:
+ {% for bbs_addr in bbs_addrs %}
+ - {{ bbs_addr }}
+ {% endfor %}
+ nat_ip: {{ nat_ip }}
+ nat_mac: {{ nat_mac }}
+ lan_ip: {{ lan_ip }}
+ lan_mac: {{ lan_mac }}
+ wan_ip: {{ wan_ip }}
+ wan_mac: {{ wan_mac }}
+ wan_container_mac: {{ wan_container_mac }}
+ wan_next_hop: 10.0.1.253 # FIX ME
+ private_ip: {{ private_ip }}
+ private_mac: {{ private_mac }}
+ hpc_client_ip: {{ hpc_client_ip }}
+ hpc_client_mac: {{ hpc_client_mac }}
+ keystone_tenant_id: {{ keystone_tenant_id }}
+ keystone_user_id: {{ keystone_user_id }}
+ rabbit_user: {{ rabbit_user }}
+ rabbit_password: {{ rabbit_password }}
+ rabbit_host: {{ rabbit_host }}
+ safe_browsing:
+ {% for mac in safe_browsing_macs %}
+ - {{ mac }}
+ {% endfor %}
+
+ tasks:
+{% if full_setup %}
+ - name: Docker repository
+ copy: src=/opt/xos/observers/vcpe/files/docker.list
+ dest=/etc/apt/sources.list.d/docker.list
+
+ - name: Import the repository key
+ apt_key: keyserver=keyserver.ubuntu.com id=36A1D7869245C8950F966E92D8576A8BA88D21E9
+
+ - name: install Docker
+ apt: name=lxc-docker state=present update_cache=yes
+
+ - name: install python-setuptools
+ apt: name=python-setuptools state=present
+
+ - name: install pip
+ easy_install: name=pip
+
+ - name: install docker-py
+ pip: name=docker-py version=0.5.3
+
+ - name: install Pipework
+ get_url: url=https://raw.githubusercontent.com/jpetazzo/pipework/master/pipework
+ dest=/usr/local/bin/pipework
+ mode=0755
+
+ - name: make sure /etc/dnsmasq.d exists
+ file: path=/etc/dnsmasq.d state=directory owner=root group=root
+
+ - name: Disable resolvconf service
+ shell: service resolvconf stop
+ shell: echo manual > /etc/init/resolvconf.override
+ shell: rm -f /etc/resolv.conf
+
+ - name: Install resolv.conf
+ copy: src=/opt/xos/observers/vcpe/files/vm-resolv.conf
+ dest=/etc/resolv.conf
+
+ - name: Verify if vcpe_stats_notifier ([] is to avoid capturing the shell process) cron job is already running
+ shell: pgrep -f [v]cpe_stats_notifier | wc -l
+ register: cron_job_pids_count
+
+# - name: DEBUG
+# debug: var=cron_job_pids_count.stdout
+
+ - name: make sure ~/bin exists
+ file: path=~/bin state=directory owner=root group=root
+ when: cron_job_pids_count.stdout == "0"
+
+ - name: Copy cron job to destination
+ copy: src=/opt/xos/observers/vcpe/vcpe_stats_notifier.py
+ dest=~/bin/vcpe_stats_notifier.py
+ when: cron_job_pids_count.stdout == "0"
+
+ - name: install python-kombu
+ apt: name=python-kombu state=present
+ when: cron_job_pids_count.stdout == "0"
+
+ - name: Initiate vcpe_stats_notifier cron job
+ command: python ~/bin/vcpe_stats_notifier.py --keystone_tenant_id={{ keystone_tenant_id }} --keystone_user_id={{ keystone_user_id }} --rabbit_user={{ rabbit_user }} --rabbit_password={{ rabbit_password }} --rabbit_host={{ rabbit_host }} --vcpeservice_rabbit_exchange='vcpeservice'
+ async: 9999999999999999
+ poll: 0
+ when: cron_job_pids_count.stdout == "0"
+{% endif %}
+
+ - name: vCPE upstart
+ template: src=/opt/xos/observers/vcpe/templates/vcpe.conf.j2 dest=/etc/init/vcpe-{{ s_tags[0] }}-{{ c_tags[0] }}.conf
+
+ - name: vCPE startup script
+ template: src=/opt/xos/observers/vcpe/templates/start-vcpe.sh.j2 dest=/usr/local/sbin/start-vcpe-{{ s_tags[0] }}-{{ c_tags[0] }}.sh mode=0755
+ notify:
+# - restart vcpe
+ - stop vcpe
+ - remove container
+ - start vcpe
+
+ - name: create /etc/vcpe-{{ s_tags[0] }}-{{ c_tags[0] }}/dnsmasq.d
+ file: path=/etc/vcpe-{{ s_tags[0] }}-{{ c_tags[0] }}/dnsmasq.d state=directory owner=root group=root
+
+ - name: vCPE basic dnsmasq config
+ copy: src=/opt/xos/observers/vcpe/files/vcpe.dnsmasq dest=/etc/vcpe-{{ s_tags[0] }}-{{ c_tags[0] }}/dnsmasq.d/vcpe.conf owner=root group=root
+ notify:
+ - restart dnsmasq
+
+ - name: dnsmasq config
+ template: src=/opt/xos/observers/vcpe/templates/dnsmasq_servers.j2 dest=/etc/vcpe-{{ s_tags[0] }}-{{ c_tags[0] }}/dnsmasq.d/servers.conf owner=root group=root
+ notify:
+ - restart dnsmasq
+
+# These are samples, not necessary for correct function of demo
+
+# - name: networking info
+# template: src=/opt/xos/observers/vcpe/templates/vlan_sample.j2 dest=/etc/vlan_sample owner=root group=root
+
+# - name: firewall info
+# template: src=/opt/xos/observers/vcpe/templates/firewall_sample.j2 dest=/etc/firewall_sample owner=root group=root
+
+ - name: Make sure vCPE service is running
+ service: name=vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} state=started
+
+ handlers:
+ # Dnsmasq is automatically restarted in the container
+ - name: restart dnsmasq
+ shell: docker exec vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} killall dnsmasq
+
+ - name: restart vcpe
+ shell: service vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} stop; sleep 1; service vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} start
+
+ - name: stop vcpe
+ service: name=vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} state=stopped
+
+ - name: remove container
+ docker: name=vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} state=absent image=docker-vcpe
+
+ - name: start vcpe
+ service: name=vcpe-{{ s_tags[0] }}-{{ c_tags[0] }} state=started
+
diff --git a/xos/synchronizers/vcpe/steps/sync_vcpetenant_new.yaml b/xos/synchronizers/vcpe/steps/sync_vcpetenant_new.yaml
new file mode 100644
index 0000000..6c7166f
--- /dev/null
+++ b/xos/synchronizers/vcpe/steps/sync_vcpetenant_new.yaml
@@ -0,0 +1,131 @@
+---
+- hosts: {{ instance_name }}
+ gather_facts: False
+ connection: ssh
+ user: {{ username }}
+ sudo: yes
+ vars:
+ container_name: {{ container_name }}
+ cdn_enable: {{ cdn_enable }}
+ dnsdemux_ip: {{ dnsdemux_ip }}
+ firewall_enable: {{ firewall_enable }}
+ url_filter_enable: {{ url_filter_enable }}
+ vlan_ids:
+ {% for vlan_id in vlan_ids %}
+ - {{ vlan_id }}
+ {% endfor %}
+ c_tags:
+ {% for c_tag in c_tags %}
+ - {{ c_tag }}
+ {% endfor %}
+ s_tags:
+ {% for s_tag in s_tags %}
+ - {{ s_tag }}
+ {% endfor %}
+ firewall_rules:
+ {% for firewall_rule in firewall_rules.split("\n") %}
+ - {{ firewall_rule }}
+ {% endfor %}
+ cdn_prefixes:
+ {% for prefix in cdn_prefixes %}
+ - {{ prefix }}
+ {% endfor %}
+ bbs_addrs:
+ {% for bbs_addr in bbs_addrs %}
+ - {{ bbs_addr }}
+ {% endfor %}
+ nat_ip: {{ nat_ip }}
+ nat_mac: {{ nat_mac }}
+ lan_ip: {{ lan_ip }}
+ lan_mac: {{ lan_mac }}
+ wan_ip: {{ wan_ip }}
+ wan_mac: {{ wan_mac }}
+ wan_container_mac: {{ wan_container_mac }}
+ wan_next_hop: 10.0.1.253 # FIX ME
+ private_ip: {{ private_ip }}
+ private_mac: {{ private_mac }}
+ hpc_client_ip: {{ hpc_client_ip }}
+ hpc_client_mac: {{ hpc_client_mac }}
+ keystone_tenant_id: {{ keystone_tenant_id }}
+ keystone_user_id: {{ keystone_user_id }}
+ rabbit_user: {{ rabbit_user }}
+ rabbit_password: {{ rabbit_password }}
+ rabbit_host: {{ rabbit_host }}
+ safe_browsing:
+ {% for mac in safe_browsing_macs %}
+ - {{ mac }}
+ {% endfor %}
+
+ tasks:
+ - name: Verify if vcpe_stats_notifier ([] is to avoid capturing the shell process) cron job is already running
+ shell: pgrep -f [v]cpe_stats_notifier | wc -l
+ register: cron_job_pids_count
+
+# - name: DEBUG
+# debug: var=cron_job_pids_count.stdout
+
+ - name: make sure ~/bin exists
+ file: path=~/bin state=directory owner=root group=root
+ when: cron_job_pids_count.stdout == "0"
+
+ - name: Copy cron job to destination
+ copy: src=/opt/xos/observers/vcpe/vcpe_stats_notifier.py
+ dest=~/bin/vcpe_stats_notifier.py
+ when: cron_job_pids_count.stdout == "0"
+
+ - name: install python-kombu
+ apt: name=python-kombu state=present
+ when: cron_job_pids_count.stdout == "0"
+
+ - name: Initiate vcpe_stats_notifier cron job
+ command: python ~/bin/vcpe_stats_notifier.py --keystone_tenant_id={{ keystone_tenant_id }} --keystone_user_id={{ keystone_user_id }} --rabbit_user={{ rabbit_user }} --rabbit_password={{ rabbit_password }} --rabbit_host={{ rabbit_host }} --vcpeservice_rabbit_exchange='vcpeservice'
+ async: 9999999999999999
+ poll: 0
+ when: cron_job_pids_count.stdout == "0"
+
+ - name: vCPE basic dnsmasq config
+ copy: src=/opt/xos/observers/vcpe/files/vcpe.dnsmasq dest=/var/container_volumes/{{ container_name }}/etc/dnsmasq.d/vcpe.conf owner=root group=root
+ notify:
+ - restart dnsmasq
+
+ - name: dnsmasq config
+ template: src=/opt/xos/observers/vcpe/templates/dnsmasq_servers.j2 dest=/var/container_volumes/{{ container_name }}/etc/dnsmasq.d/servers.conf owner=root group=root
+ notify:
+ - restart dnsmasq
+
+ - name: create directory for "safe" config
+ file: path=/var/container_volumes/{{ container_name }}/etc/dnsmasq.d/safe state=directory
+
+ - name: dnsmasq "safe" config
+ template: src=/opt/xos/observers/vcpe/templates/dnsmasq_safe_servers.j2 dest=/var/container_volumes/{{ container_name }}/etc/dnsmasq.d/safe/servers.conf owner=root group=root
+ notify:
+ - restart dnsmasq
+
+ - name: copy base ufw files
+ synchronize: src=/opt/xos/observers/vcpe/files/etc/ufw/ dest=/var/container_volumes/{{ container_name }}/etc/ufw/
+ notify:
+ - reload ufw
+
+ - name: redirection rules for safe DNS
+ template: src=/opt/xos/observers/vcpe/templates/before.rules.j2 dest=/var/container_volumes/{{ container_name }}/etc/ufw/before.rules owner=root group=root
+ notify:
+ - reload ufw
+
+ - name: base ufw setup uses /etc/rc.local
+ copy: src=/opt/xos/observers/vcpe/files/etc/rc.local dest=/var/container_volumes/{{ container_name }}/etc/ owner=root group=root
+ notify:
+ - copy in /etc/rc.local
+
+ handlers:
+ # Dnsmasq is automatically restarted in the container
+ - name: restart dnsmasq
+ shell: docker exec {{ container_name }} /usr/bin/killall dnsmasq
+
+ - name: reload ufw
+ shell: docker exec {{ container_name }} bash -c "/sbin/iptables -t nat -F PREROUTING; /usr/sbin/ufw reload"
+
+ # Use docker cp instead of single-file volume
+ # The reason is that changes to external file volume don't show up inside the container
+ # Probably Ansible deletes and then recreates the external file, and container has old version
+ - name: copy in /etc/rc.local
+ shell: docker cp /var/container_volumes/{{ container_name }}/etc/rc.local {{ container_name }}:/etc/
diff --git a/xos/observers/vcpe/steps/test.yaml b/xos/synchronizers/vcpe/steps/test.yaml
similarity index 100%
rename from xos/observers/vcpe/steps/test.yaml
rename to xos/synchronizers/vcpe/steps/test.yaml
diff --git a/xos/observers/vcpe/stop.sh b/xos/synchronizers/vcpe/stop.sh
similarity index 100%
rename from xos/observers/vcpe/stop.sh
rename to xos/synchronizers/vcpe/stop.sh
diff --git a/xos/observers/vcpe/supervisor/vcpe-observer.conf b/xos/synchronizers/vcpe/supervisor/vcpe-observer.conf
similarity index 100%
rename from xos/observers/vcpe/supervisor/vcpe-observer.conf
rename to xos/synchronizers/vcpe/supervisor/vcpe-observer.conf
diff --git a/xos/observers/vcpe/templates/before.rules.j2 b/xos/synchronizers/vcpe/templates/before.rules.j2
similarity index 100%
rename from xos/observers/vcpe/templates/before.rules.j2
rename to xos/synchronizers/vcpe/templates/before.rules.j2
diff --git a/xos/observers/vcpe/templates/dnsmasq_safe_servers.j2 b/xos/synchronizers/vcpe/templates/dnsmasq_safe_servers.j2
similarity index 100%
rename from xos/observers/vcpe/templates/dnsmasq_safe_servers.j2
rename to xos/synchronizers/vcpe/templates/dnsmasq_safe_servers.j2
diff --git a/xos/observers/vcpe/templates/dnsmasq_servers.j2 b/xos/synchronizers/vcpe/templates/dnsmasq_servers.j2
similarity index 100%
rename from xos/observers/vcpe/templates/dnsmasq_servers.j2
rename to xos/synchronizers/vcpe/templates/dnsmasq_servers.j2
diff --git a/xos/observers/vcpe/templates/firewall_sample.j2 b/xos/synchronizers/vcpe/templates/firewall_sample.j2
similarity index 100%
rename from xos/observers/vcpe/templates/firewall_sample.j2
rename to xos/synchronizers/vcpe/templates/firewall_sample.j2
diff --git a/xos/observers/vcpe/templates/start-vcpe.sh.j2 b/xos/synchronizers/vcpe/templates/start-vcpe.sh.j2
similarity index 100%
rename from xos/observers/vcpe/templates/start-vcpe.sh.j2
rename to xos/synchronizers/vcpe/templates/start-vcpe.sh.j2
diff --git a/xos/observers/vcpe/templates/vcpe.conf.j2 b/xos/synchronizers/vcpe/templates/vcpe.conf.j2
similarity index 100%
rename from xos/observers/vcpe/templates/vcpe.conf.j2
rename to xos/synchronizers/vcpe/templates/vcpe.conf.j2
diff --git a/xos/observers/vcpe/templates/vlan_sample.j2 b/xos/synchronizers/vcpe/templates/vlan_sample.j2
similarity index 100%
rename from xos/observers/vcpe/templates/vlan_sample.j2
rename to xos/synchronizers/vcpe/templates/vlan_sample.j2
diff --git a/xos/synchronizers/vcpe/vcpe-synchronizer.py b/xos/synchronizers/vcpe/vcpe-synchronizer.py
new file mode 100755
index 0000000..84bec4f
--- /dev/null
+++ b/xos/synchronizers/vcpe/vcpe-synchronizer.py
@@ -0,0 +1,11 @@
+#!/usr/bin/env python
+
+# This imports and runs ../../xos-observer.py
+
+import importlib
+import os
+import sys
+observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../../synchronizers/base")
+sys.path.append(observer_path)
+mod = importlib.import_module("xos-synchronizer")
+mod.main()
diff --git a/xos/observers/vcpe/vcpe_stats_notifier.py b/xos/synchronizers/vcpe/vcpe_stats_notifier.py
similarity index 100%
rename from xos/observers/vcpe/vcpe_stats_notifier.py
rename to xos/synchronizers/vcpe/vcpe_stats_notifier.py
diff --git a/xos/synchronizers/vcpe/vcpe_synchronizer_config b/xos/synchronizers/vcpe/vcpe_synchronizer_config
new file mode 100644
index 0000000..110b8e2
--- /dev/null
+++ b/xos/synchronizers/vcpe/vcpe_synchronizer_config
@@ -0,0 +1,42 @@
+
+[plc]
+name=plc
+deployment=VICCI
+
+[db]
+name=xos
+user=postgres
+password=password
+host=localhost
+port=5432
+
+[api]
+host=128.112.171.237
+port=8000
+ssl_key=None
+ssl_cert=None
+ca_ssl_cert=None
+ratelimit_enabled=0
+omf_enabled=0
+mail_support_address=support@localhost
+nova_enabled=True
+
+[observer]
+name=vcpe
+dependency_graph=/opt/xos/synchronizers/vcpe/model-deps
+steps_dir=/opt/xos/synchronizers/vcpe/steps
+sys_dir=/opt/xos/synchronizers/vcpe/sys
+deleters_dir=/opt/xos/synchronizers/vcpe/deleters
+log_file=console
+#/var/log/hpc.log
+driver=None
+pretend=False
+backoff_disabled=True
+save_ansible_output=True
+# set proxy_ssh to false on cloudlab
+proxy_ssh=False
+full_setup=True
+
+[feefie]
+client_id='vicci_dev_central'
+user_id='pl'
diff --git a/xos/observers/vtn/model-deps b/xos/synchronizers/vtn/model-deps
similarity index 100%
rename from xos/observers/vtn/model-deps
rename to xos/synchronizers/vtn/model-deps
diff --git a/xos/observers/vtn/run.sh b/xos/synchronizers/vtn/run.sh
similarity index 100%
rename from xos/observers/vtn/run.sh
rename to xos/synchronizers/vtn/run.sh
diff --git a/xos/observers/vtn/start.sh b/xos/synchronizers/vtn/start.sh
similarity index 100%
rename from xos/observers/vtn/start.sh
rename to xos/synchronizers/vtn/start.sh
diff --git a/xos/synchronizers/vtn/steps/sync_tenant.py b/xos/synchronizers/vtn/steps/sync_tenant.py
new file mode 100644
index 0000000..cc374be
--- /dev/null
+++ b/xos/synchronizers/vtn/steps/sync_tenant.py
@@ -0,0 +1,95 @@
+import os
+import requests
+import socket
+import sys
+import base64
+from django.db.models import F, Q
+from xos.config import Config
+from synchronizers.base.syncstep import SyncStep
+from core.models import Service
+from core.models.service import COARSE_KIND
+from services.cord.models import Tenant
+from xos.logger import Logger, logging
+from requests.auth import HTTPBasicAuth
+
+# hpclibrary will be in steps/..
+parentdir = os.path.join(os.path.dirname(__file__),"..")
+sys.path.insert(0,parentdir)
+
+logger = Logger(level=logging.INFO)
+
+# XXX should save and load this
+glo_saved_vtn_maps = []
+
+class SyncTenant(SyncStep):
+ provides=[Tenant]
+ observes=Tenant
+ requested_interval=0
+
+ def __init__(self, **args):
+ SyncStep.__init__(self, **args)
+
+ def get_vtn_onos_service(self):
+# vtn_tenant = Tenant.objects.filter(name="VTN_ONOS_app") # XXX fixme - hardcoded
+# if not vtn_tenant:
+# raise "No VTN Onos App found"
+# vtn_tenant = vtn_tenant[0]
+#
+# vtn_service = vtn_tenant.provider_service
+ vtn_service = Service.objects.filter(name="service_ONOS_VTN") # XXX fixme - harcoded
+ if not vtn_service:
+ raise "No VTN Onos Service"
+
+ return vtn_service[0]
+
+ def get_vtn_addr(self):
+ vtn_service = self.get_vtn_onos_service()
+
+ if not vtn_service.slices.exists():
+ raise "VTN Service has no slices"
+
+ vtn_slice = vtn_service.slices.all()[0]
+
+ if not vtn_slice.instances.exists():
+ raise "VTN Slice has no instances"
+
+ vtn_instance = vtn_slice.instances.all()[0]
+
+ return vtn_instance.node.name
+
+ def call(self, **args):
+ global glo_saved_vtn_maps
+
+ logger.info("sync'ing vtn services")
+
+ vtn_maps = []
+ for service in Service.objects.all():
+ for id in service.get_vtn_src_ids():
+ dependencies = service.get_vtn_dependencies_ids()
+ if dependencies:
+ for dependency in dependencies:
+ vtn_maps.append( (id, dependency) )
+
+ for vtn_map in vtn_maps:
+ if not (vtn_map in glo_saved_vtn_maps):
+ # call vtn rest api to add map
+ url = "http://" + self.get_vtn_addr() + ":8181/onos/cordvtn/service-dependency/%s/%s" % (vtn_map[0], vtn_map[1])
+
+ print "POST %s" % url
+ r = requests.post(url, auth=HTTPBasicAuth('karaf', 'karaf') ) # XXX fixme - hardcoded auth
+ if (r.status_code != 200):
+ raise Exception("Received error from vtn service (%d)" % r.status_code)
+
+ for vtn_map in glo_saved_vtn_maps:
+ if not vtn_map in vtn_maps:
+ # call vtn rest api to delete map
+ url = "http://" + self.get_vtn_addr() + ":8181/onos/cordvtn/service-dependency/%s/%s" % (vtn_map[0],vtn_map[1])
+
+ print "DELETE %s" % url
+ r = requests.delete(url, auth=HTTPBasicAuth('karaf', 'karaf') ) # XXX fixme - hardcoded auth
+ if (r.status_code != 200):
+ raise Exception("Received error from vtn service (%d)" % r.status_code)
+
+ glo_saved_vtn_maps = vtn_maps
+ # TODO: save this
+
diff --git a/xos/observers/vtn/stop.sh b/xos/synchronizers/vtn/stop.sh
similarity index 100%
rename from xos/observers/vtn/stop.sh
rename to xos/synchronizers/vtn/stop.sh
diff --git a/xos/observers/vtn/supervisor/vtn-observer.conf b/xos/synchronizers/vtn/supervisor/vtn-observer.conf
similarity index 100%
rename from xos/observers/vtn/supervisor/vtn-observer.conf
rename to xos/synchronizers/vtn/supervisor/vtn-observer.conf
diff --git a/xos/synchronizers/vtn/vtn-synchronizer.py b/xos/synchronizers/vtn/vtn-synchronizer.py
new file mode 100755
index 0000000..84bec4f
--- /dev/null
+++ b/xos/synchronizers/vtn/vtn-synchronizer.py
@@ -0,0 +1,11 @@
+#!/usr/bin/env python
+
+# This imports and runs ../../xos-observer.py
+
+import importlib
+import os
+import sys
+observer_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"../../synchronizers/base")
+sys.path.append(observer_path)
+mod = importlib.import_module("xos-synchronizer")
+mod.main()
diff --git a/xos/synchronizers/vtn/vtn_synchronizer_config b/xos/synchronizers/vtn/vtn_synchronizer_config
new file mode 100644
index 0000000..302a096
--- /dev/null
+++ b/xos/synchronizers/vtn/vtn_synchronizer_config
@@ -0,0 +1,38 @@
+
+[plc]
+name=plc
+deployment=VICCI
+
+[db]
+name=xos
+user=postgres
+password=password
+host=localhost
+port=5432
+
+[api]
+host=128.112.171.237
+port=8000
+ssl_key=None
+ssl_cert=None
+ca_ssl_cert=None
+ratelimit_enabled=0
+omf_enabled=0
+mail_support_address=support@localhost
+nova_enabled=True
+
+[observer]
+name=vtn
+dependency_graph=/opt/xos/synchronizers/vtn/model-deps
+steps_dir=/opt/xos/synchronizers/vtn/steps
+sys_dir=/opt/xos/synchronizers/vtn/sys
+deleters_dir=/opt/xos/synchronizers/vtn/deleters
+log_file=console
+#/var/log/hpc.log
+driver=None
+pretend=False
+backoff_disabled=True
+
+[feefie]
+client_id='vicci_dev_central'
+user_id='pl'
diff --git a/xos/syndicate_observer/__init__.py b/xos/syndicate_observer/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/xos/syndicate_observer/__init__.py
+++ /dev/null
diff --git a/xos/syndicate_observer/run.sh b/xos/syndicate_observer/run.sh
deleted file mode 100644
index 824a248..0000000
--- a/xos/syndicate_observer/run.sh
+++ /dev/null
@@ -1,2 +0,0 @@
-export XOS_DIR=/opt/xos
-python syndicate-backend.py -C $XOS_DIR/syndicate_observer/syndicate_observer_config
diff --git a/xos/syndicate_observer/start.sh b/xos/syndicate_observer/start.sh
deleted file mode 100644
index 313d504..0000000
--- a/xos/syndicate_observer/start.sh
+++ /dev/null
@@ -1,2 +0,0 @@
-export XOS_DIR=/opt/xos
-nohup python syndicate-backend.py -C $XOS_DIR/syndicate_observer/syndicate_observer_config > /dev/null 2>&1 &
diff --git a/xos/syndicate_observer/steps/sync_volume.py b/xos/syndicate_observer/steps/sync_volume.py
deleted file mode 100644
index 726908c..0000000
--- a/xos/syndicate_observer/steps/sync_volume.py
+++ /dev/null
@@ -1,138 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import sys
-import traceback
-import base64
-
-if __name__ == "__main__":
- # for testing
- if os.getenv("OPENCLOUD_PYTHONPATH"):
- sys.path.append( os.getenv("OPENCLOUD_PYTHONPATH") )
- else:
- print >> sys.stderr, "No OPENCLOUD_PYTHONPATH variable set. Assuming that OpenCloud is in PYTHONPATH"
-
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-
-
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from core.models import Service
-from syndicate_storage.models import Volume
-
-import logging
-from logging import Logger
-logging.basicConfig( format='[%(levelname)s] [%(module)s:%(lineno)d] %(message)s' )
-logger = logging.getLogger()
-logger.setLevel( logging.INFO )
-
-# point to planetstack
-if __name__ != "__main__":
- if os.getenv("OPENCLOUD_PYTHONPATH") is not None:
- sys.path.insert(0, os.getenv("OPENCLOUD_PYTHONPATH"))
- else:
- logger.warning("No OPENCLOUD_PYTHONPATH set; assuming your PYTHONPATH works")
-
-# syndicatelib will be in stes/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-import syndicatelib
-
-
-class SyncVolume(SyncStep):
- provides=[Volume]
- requested_interval=0
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
-
- def sync_record(self, volume):
- """
- Synchronize a Volume record with Syndicate.
- """
-
- logger.info( "Sync Volume = %s\n\n" % volume.name )
-
- user_email = volume.owner_id.email
- config = syndicatelib.get_config()
-
- volume_principal_id = syndicatelib.make_volume_principal_id( user_email, volume.name )
-
- # get the observer secret
- try:
- observer_secret = config.SYNDICATE_OPENCLOUD_SECRET
- except Exception, e:
- traceback.print_exc()
- logger.error("config is missing SYNDICATE_OPENCLOUD_SECRET")
- raise e
-
- # volume owner must exist as a Syndicate user...
- try:
- rc, user = syndicatelib.ensure_principal_exists( volume_principal_id, observer_secret, is_admin=False, max_UGs=1100, max_RGs=1)
- assert rc == True, "Failed to create or read volume principal '%s'" % volume_principal_id
- except Exception, e:
- traceback.print_exc()
- logger.error("Failed to ensure principal '%s' exists" % volume_principal_id )
- raise e
-
- # volume must exist
-
- # create or update the Volume
- try:
- new_volume = syndicatelib.ensure_volume_exists( volume_principal_id, volume, user=user )
- except Exception, e:
- traceback.print_exc()
- logger.error("Failed to ensure volume '%s' exists" % volume.name )
- raise e
-
- # did we create the Volume?
- if new_volume is not None:
- # we're good
- pass
-
- # otherwise, just update it
- else:
- try:
- rc = syndicatelib.update_volume( volume )
- except Exception, e:
- traceback.print_exc()
- logger.error("Failed to update volume '%s', exception = %s" % (volume.name, e.message))
- raise e
-
- return True
-
- def delete_record(self, volume):
- try:
- volume_name = volume.name
- syndicatelib.ensure_volume_absent( volume_name )
- except Exception, e:
- traceback.print_exc()
- logger.exception("Failed to erase volume '%s'" % volume_name)
- raise e
-
-
-
-
-
-if __name__ == "__main__":
- sv = SyncVolume()
-
-
- # first, set all volumes to not-enacted so we can test
- for v in Volume.objects.all():
- v.enacted = None
- v.save()
-
- # NOTE: for resetting only
- if len(sys.argv) > 1 and sys.argv[1] == "reset":
- sys.exit(0)
-
- recs = sv.fetch_pending()
-
- for rec in recs:
- rc = sv.sync_record( rec )
- if not rc:
- print "\n\nFailed to sync %s\n\n" % (rec.name)
-
diff --git a/xos/syndicate_observer/steps/sync_volumeaccessright.py b/xos/syndicate_observer/steps/sync_volumeaccessright.py
deleted file mode 100644
index e68b6af..0000000
--- a/xos/syndicate_observer/steps/sync_volumeaccessright.py
+++ /dev/null
@@ -1,116 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import sys
-import base64
-import traceback
-
-if __name__ == "__main__":
- # for testing
- if os.getenv("OPENCLOUD_PYTHONPATH"):
- sys.path.append( os.getenv("OPENCLOUD_PYTHONPATH") )
- else:
- print >> sys.stderr, "No OPENCLOUD_PYTHONPATH variable set. Assuming that OpenCloud is in PYTHONPATH"
-
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from core.models import Service
-
-import logging
-from logging import Logger
-logging.basicConfig( format='[%(levelname)s] [%(module)s:%(lineno)d] %(message)s' )
-logger = logging.getLogger()
-logger.setLevel( logging.INFO )
-
-# point to planetstack
-if __name__ != "__main__":
- if os.getenv("OPENCLOUD_PYTHONPATH") is not None:
- sys.path.insert(0, os.getenv("OPENCLOUD_PYTHONPATH"))
- else:
- logger.warning("No OPENCLOUD_PYTHONPATH set; assuming your PYTHONPATH works")
-
-from syndicate_storage.models import VolumeAccessRight
-
-# syndicatelib will be in stes/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-import syndicatelib
-
-class SyncVolumeAccessRight(SyncStep):
- provides=[VolumeAccessRight]
- requested_interval=0
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
-
- def sync_record(self, vac):
-
- syndicate_caps = "UNKNOWN" # for exception handling
-
- # get arguments
- config = syndicatelib.get_config()
- user_email = vac.owner_id.email
- volume_name = vac.volume.name
- syndicate_caps = syndicatelib.opencloud_caps_to_syndicate_caps( vac.cap_read_data, vac.cap_write_data, vac.cap_host_data )
-
- logger.info( "Sync VolumeAccessRight for (%s, %s)" % (user_email, volume_name) )
-
- # validate config
- try:
- RG_port = config.SYNDICATE_RG_DEFAULT_PORT
- observer_secret = config.SYNDICATE_OPENCLOUD_SECRET
- except Exception, e:
- traceback.print_exc()
- logger.error("syndicatelib config is missing SYNDICATE_RG_DEFAULT_PORT, SYNDICATE_OPENCLOUD_SECRET")
- raise e
-
- # ensure the user exists and has credentials
- try:
- rc, user = syndicatelib.ensure_principal_exists( user_email, observer_secret, is_admin=False, max_UGs=1100, max_RGs=1 )
- assert rc is True, "Failed to ensure principal %s exists (rc = %s,%s)" % (user_email, rc, user)
- except Exception, e:
- traceback.print_exc()
- logger.error("Failed to ensure user '%s' exists" % user_email )
- raise e
-
- # make the access right for the user to create their own UGs, and provision an RG for this user that will listen on localhost.
- # the user will have to supply their own RG closure.
- try:
- rc = syndicatelib.setup_volume_access( user_email, volume_name, syndicate_caps, RG_port, observer_secret )
- assert rc is True, "Failed to setup volume access for %s in %s" % (user_email, volume_name)
-
- except Exception, e:
- traceback.print_exc()
- logger.error("Faoed to ensure user %s can access Volume %s with rights %s" % (user_email, volume_name, syndicate_caps))
- raise e
-
- return True
-
- # Jude: this will simply go on to purge the object from
- # OpenCloud. The previous 'deleter' version was a no-op also.
- def delete_record(self, obj):
- pass
-
-
-if __name__ == "__main__":
-
- # first, set all VolumeAccessRights to not-enacted so we can test
- for v in VolumeAccessRight.objects.all():
- v.enacted = None
- v.save()
-
- # NOTE: for resetting only
- if len(sys.argv) > 1 and sys.argv[1] == "reset":
- sys.exit(0)
-
-
- sv = SyncVolumeAccessRight()
- recs = sv.fetch_pending()
-
- for rec in recs:
- sv.sync_record( rec )
-
diff --git a/xos/syndicate_observer/steps/sync_volumeslice.py b/xos/syndicate_observer/steps/sync_volumeslice.py
deleted file mode 100644
index 3217d7a..0000000
--- a/xos/syndicate_observer/steps/sync_volumeslice.py
+++ /dev/null
@@ -1,158 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import sys
-import base64
-import traceback
-
-if __name__ == "__main__":
- # for testing
- if os.getenv("OPENCLOUD_PYTHONPATH"):
- sys.path.append( os.getenv("OPENCLOUD_PYTHONPATH") )
- else:
- print >> sys.stderr, "No OPENCLOUD_PYTHONPATH variable set. Assuming that OpenCloud is in PYTHONPATH"
-
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-
-from django.db.models import F, Q
-from xos.config import Config
-from observer.syncstep import SyncStep
-from core.models import Service, Slice
-
-import logging
-from logging import Logger
-logging.basicConfig( format='[%(levelname)s] [%(module)s:%(lineno)d] %(message)s' )
-logger = logging.getLogger()
-logger.setLevel( logging.INFO )
-
-# point to planetstack
-if __name__ != "__main__":
- if os.getenv("OPENCLOUD_PYTHONPATH") is not None:
- sys.path.insert(0, os.getenv("OPENCLOUD_PYTHONPATH"))
- else:
- logger.warning("No OPENCLOUD_PYTHONPATH set; assuming your PYTHONPATH works")
-
-from syndicate_storage.models import VolumeSlice,VolumeAccessRight,Volume
-
-# syndicatelib will be in stes/..
-parentdir = os.path.join(os.path.dirname(__file__),"..")
-sys.path.insert(0,parentdir)
-
-import syndicatelib
-
-
-class SyncVolumeSlice(SyncStep):
- provides=[VolumeSlice]
- requested_interval=0
-
- def __init__(self, **args):
- SyncStep.__init__(self, **args)
-
- def sync_record(self, vs):
-
- logger.info("Sync VolumeSlice for (%s, %s)" % (vs.volume_id.name, vs.slice_id.name))
-
- # extract arguments...
- user_email = vs.slice_id.creator.email
- slice_name = vs.slice_id.name
- volume_name = vs.volume_id.name
- syndicate_caps = syndicatelib.opencloud_caps_to_syndicate_caps( vs.cap_read_data, vs.cap_write_data, vs.cap_host_data )
- RG_port = vs.RG_portnum
- UG_port = vs.UG_portnum
- slice_secret = None
-
- config = syndicatelib.get_config()
- try:
- observer_secret = config.SYNDICATE_OPENCLOUD_SECRET
- RG_closure = config.SYNDICATE_RG_CLOSURE
- observer_pkey_path = config.SYNDICATE_PRIVATE_KEY
- syndicate_url = config.SYNDICATE_SMI_URL
-
- except Exception, e:
- traceback.print_exc()
- logger.error("syndicatelib config is missing one or more of the following: SYNDICATE_OPENCLOUD_SECRET, SYNDICATE_RG_CLOSURE, SYNDICATE_PRIVATE_KEY, SYNDICATE_SMI_URL")
- raise e
-
- # get secrets...
- try:
- observer_pkey_pem = syndicatelib.get_private_key_pem( observer_pkey_path )
- assert observer_pkey_pem is not None, "Failed to load Observer private key"
-
- # get/create the slice secret
- slice_secret = syndicatelib.get_or_create_slice_secret( observer_pkey_pem, slice_name )
- assert slice_secret is not None, "Failed to get or create slice secret for %s" % slice_name
-
- except Exception, e:
- traceback.print_exc()
- logger.error("Failed to load secret credentials")
- raise e
-
- # make sure there's a slice-controlled Syndicate user account for the slice owner
- slice_principal_id = syndicatelib.make_slice_principal_id( user_email, slice_name )
-
- try:
- rc, user = syndicatelib.ensure_principal_exists( slice_principal_id, observer_secret, is_admin=False, max_UGs=1100, max_RGs=1 )
- assert rc is True, "Failed to ensure principal %s exists (rc = %s,%s)" % (slice_principal_id, rc, user)
- except Exception, e:
- traceback.print_exc()
- logger.error('Failed to ensure slice user %s exists' % slice_principal_id)
- raise e
-
- # grant the slice-owning user the ability to provision UGs in this Volume, and also provision for the user the (single) RG the slice will instantiate in each VM.
- try:
- rc = syndicatelib.setup_volume_access( slice_principal_id, volume_name, syndicate_caps, RG_port, observer_secret, RG_closure=RG_closure )
- assert rc is True, "Failed to set up Volume access for slice %s in %s" % (slice_principal_id, volume_name)
-
- except Exception, e:
- traceback.print_exc()
- logger.error("Failed to set up Volume access for slice %s in %s" % (slice_principal_id, volume_name))
- raise e
-
- # generate and save slice credentials....
- try:
- slice_cred = syndicatelib.save_slice_credentials( observer_pkey_pem, syndicate_url, slice_principal_id, volume_name, slice_name, observer_secret, slice_secret, UG_port, existing_user=user )
- assert slice_cred is not None, "Failed to generate slice credential for %s in %s" % (slice_principal_id, volume_name )
-
- except Exception, e:
- traceback.print_exc()
- logger.error("Failed to generate slice credential for %s in %s" % (slice_principal_id, volume_name))
- raise e
-
- # ... and push them all out.
- try:
- rc = syndicatelib.push_credentials_to_slice( slice_name, slice_cred )
- assert rc is True, "Failed to push credentials to slice %s for volume %s" % (slice_name, volume_name)
-
- except Exception, e:
- traceback.print_exc()
- logger.error("Failed to push slice credentials to %s for volume %s" % (slice_name, volume_name))
- raise e
-
- return True
-
- # This method will simply cause the object to be purged from OpenCloud
- def delete_record(self, volume_slice):
- pass
-
-
-if __name__ == "__main__":
- sv = SyncVolumeSlice()
-
- # first, set all VolumeSlice to not-enacted so we can test
- for v in VolumeSlice.objects.all():
- v.enacted = None
- v.save()
-
- # NOTE: for resetting only
- if len(sys.argv) > 1 and sys.argv[1] == "reset":
- sys.exit(0)
-
- recs = sv.fetch_pending()
-
- for rec in recs:
- if rec.slice_id.creator is None:
- print "Ignoring slice %s, since it has no creator" % (rec.slice_id)
- continue
-
- sv.sync_record( rec )
-
diff --git a/xos/syndicate_observer/syndicate-backend.py b/xos/syndicate_observer/syndicate-backend.py
deleted file mode 100644
index 32670d9..0000000
--- a/xos/syndicate_observer/syndicate-backend.py
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/usr/bin/env python
-import os
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-from observer.backend import Backend
-
-if __name__ == '__main__':
-
- backend = Backend()
- backend.run()
-
diff --git a/xos/syndicate_observer/syndicate_observer_config b/xos/syndicate_observer/syndicate_observer_config
deleted file mode 100644
index 768f758..0000000
--- a/xos/syndicate_observer/syndicate_observer_config
+++ /dev/null
@@ -1,35 +0,0 @@
-
-[plc]
-name=plc
-deployment=VICCI
-
-[db]
-name=xos
-#user=plstackuser
-#password=2uMDYtJK
-user=postgres
-password=password
-host=localhost
-port=5432
-
-[api]
-host=128.112.171.237
-port=8000
-ssl_key=None
-ssl_cert=None
-ca_ssl_cert=None
-ratelimit_enabled=0
-omf_enabled=0
-mail_support_address=support@localhost
-nova_enabled=True
-
-[observer]
-dependency_graph=/opt/xos/syndicate_observer/model-deps
-steps_dir=/opt/xos/syndicate_observer/steps
-deleters_dir=/opt/xos/syndicate_observer/deleters
-log_file=console
-driver=None
-
-[feefie]
-client_id='vicci_dev_central'
-user_id='pl'
diff --git a/xos/syndicate_observer/syndicatelib.py b/xos/syndicate_observer/syndicatelib.py
deleted file mode 100644
index 9044a48..0000000
--- a/xos/syndicate_observer/syndicatelib.py
+++ /dev/null
@@ -1,1353 +0,0 @@
-#!/usr/bin/env python
-
-"""
-Define some common methods for the Syndicate observer.
-"""
-import os
-import sys
-import random
-import json
-import time
-import requests
-import traceback
-import base64
-import BaseHTTPServer
-import setproctitle
-import threading
-import urllib
-
-from Crypto.Hash import SHA256 as HashAlg
-from Crypto.PublicKey import RSA as CryptoKey
-from Crypto import Random
-from Crypto.Signature import PKCS1_PSS as CryptoSigner
-
-import logging
-from logging import Logger
-logging.basicConfig( format='[%(levelname)s] [%(module)s:%(lineno)d] %(message)s' )
-logger = logging.getLogger()
-logger.setLevel( logging.INFO )
-
-# get config package
-import syndicatelib_config.config as CONFIG
-
-# get the Syndicate modules
-import syndicate
-
-import syndicate.client.bin.syntool as syntool
-import syndicate.client.common.msconfig as msconfig
-import syndicate.client.common.api as api
-import syndicate.util.storage as syndicate_storage
-import syndicate.util.watchdog as syndicate_watchdog
-import syndicate.util.daemonize as syndicate_daemon
-import syndicate.util.crypto as syndicate_crypto
-import syndicate.util.provisioning as syndicate_provisioning
-import syndicate.syndicate as c_syndicate
-
-# for testing
-TESTING = False
-class FakeObject(object):
- def __init__(self):
- pass
-
-if os.getenv("OPENCLOUD_PYTHONPATH") is not None:
- sys.path.insert(0, os.getenv("OPENCLOUD_PYTHONPATH"))
-else:
- logger.warning("No OPENCLOUD_PYTHONPATH set. Assuming Syndicate models are in your PYTHONPATH")
-
-try:
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-
- # get our models
- import syndicate_storage.models as models
-
- # get OpenCloud models
- from core.models import Slice,Instance
-
- from django.core.exceptions import ObjectDoesNotExist
- from django.db import IntegrityError
-
-except ImportError, ie:
- logger.warning("Failed to import models; some tests will not work")
-
- # create a fake "models" package that has exactly the members we need for testing.
- models = FakeObject()
- models.Volume = FakeObject()
- models.Volume.CAP_READ_DATA = 1
- models.Volume.CAP_WRITE_DATA = 2
- models.Volume.CAP_HOST_DATA = 4
-
- TESTING = True
-
-
-#-------------------------------
-class SyndicateObserverError( Exception ):
- pass
-
-#-------------------------------
-def get_config():
- """
- Return the imported config
- """
- return CONFIG
-
-
-#-------------------------------
-def make_openid_url( email ):
- """
- Generate an OpenID identity URL from an email address.
- """
- return os.path.join( CONFIG.SYNDICATE_OPENID_TRUSTROOT, "id", email )
-
-
-#-------------------------------
-def connect_syndicate( username=CONFIG.SYNDICATE_OPENCLOUD_USER, password=CONFIG.SYNDICATE_OPENCLOUD_PASSWORD, user_pkey_pem=CONFIG.SYNDICATE_OPENCLOUD_PKEY ):
- """
- Connect to the OpenCloud Syndicate SMI, using the OpenCloud user credentials.
- """
- debug = True
- if hasattr(CONFIG, "DEBUG"):
- debug = CONFIG.DEBUG
-
- client = syntool.Client( username, CONFIG.SYNDICATE_SMI_URL,
- password=password,
- user_pkey_pem=user_pkey_pem,
- debug=debug )
-
- return client
-
-
-#-------------------------------
-def opencloud_caps_to_syndicate_caps( cap_read, cap_write, cap_host ):
- """
- Convert OpenCloud capability bits from the UI into Syndicate's capability bits.
- """
- syn_caps = 0
-
- if cap_read:
- syn_caps |= (msconfig.GATEWAY_CAP_READ_DATA | msconfig.GATEWAY_CAP_READ_METADATA)
- if cap_write:
- syn_caps |= (msconfig.GATEWAY_CAP_WRITE_DATA | msconfig.GATEWAY_CAP_WRITE_METADATA)
- if cap_host:
- syn_caps |= (msconfig.GATEWAY_CAP_COORDINATE)
-
- return syn_caps
-
-#-------------------------------
-def ensure_user_exists( user_email, **user_kw ):
- """
- Given an OpenCloud user, ensure that the corresponding
- Syndicate user exists on the MS. This method does NOT
- create any OpenCloud-specific data.
-
- Return the (created, user), where created==True if the user
- was created and created==False if the user was read.
- Raise an exception on error.
- """
-
- client = connect_syndicate()
- user_openid_url = make_openid_url( user_email )
-
- return syndicate_provisioning.ensure_user_exists( client, user_email, user_openid_url, **user_kw )
-
-
-#-------------------------------
-def ensure_user_absent( user_email ):
- """
- Ensure that a given OpenCloud user's associated Syndicate user record
- has been deleted. This method does NOT delete any OpenCloud-specific data.
-
- Returns True on success
- Raises an exception on error
- """
-
- client = connect_syndicate()
-
- return client.delete_user( user_email )
-
-
-#-------------------------------
-def make_volume_principal_id( user_email, volume_name ):
- """
- Create a principal id for a Volume owner.
- """
-
- volume_name_safe = urllib.quote( volume_name )
-
- return "volume_%s.%s" % (volume_name_safe, user_email)
-
-
-#-------------------------------
-def make_slice_principal_id( user_email, slice_name ):
- """
- Create a principal id for a slice owner.
- """
-
- slice_name_safe = urllib.quote( slice_name )
-
- return "slice_%s.%s" % (slice_name, user_email)
-
-
-#-------------------------------
-def ensure_principal_exists( user_email, observer_secret, **user_kw ):
- """
- Ensure that a Syndicate user exists, as well as its OpenCloud-specific data.
-
- Return (True, (None OR user)) on success. Returns a user if the user was created.
- Return (False, None) on error
- """
-
- try:
- created, new_user = ensure_user_exists( user_email, **user_kw )
- except Exception, e:
- traceback.print_exc()
- logger.error("Failed to ensure user '%s' exists" % user_email )
- return (False, None)
-
- # if we created a new user, then save its (sealed) credentials to the Django DB
- if created:
- try:
- rc = put_principal_data( user_email, observer_secret, new_user['signing_public_key'], new_user['signing_private_key'] )
- assert rc == True, "Failed to save SyndicatePrincipal"
- except Exception, e:
- traceback.print_exc()
- logger.error("Failed to save private key for principal %s" % (user_email))
- return (False, None)
-
- return (True, new_user)
-
-
-
-#-------------------------------
-def ensure_principal_absent( user_email ):
- """
- Ensure that a Syndicate user does not exists, and remove the OpenCloud-specific data.
-
- Return True on success.
- """
-
- ensure_user_absent( user_email )
- delete_principal_data( user_email )
- return True
-
-#-------------------------------
-def ensure_volume_exists( user_email, opencloud_volume, user=None ):
- """
- Given the email address of a user, ensure that the given
- Volume exists and is owned by that user.
- Do not try to ensure that the user exists.
-
- Return the Volume if we created it, or return None if we did not.
- Raise an exception on error.
- """
- client = connect_syndicate()
-
- try:
- volume = client.read_volume( opencloud_volume.name )
- except Exception, e:
- # transport error
- logger.exception(e)
- raise e
-
- if volume is None:
- # the volume does not exist....try to create it
- vol_name = opencloud_volume.name
- vol_blocksize = opencloud_volume.blocksize
- vol_description = opencloud_volume.description
- vol_private = opencloud_volume.private
- vol_archive = opencloud_volume.archive
- vol_default_gateway_caps = opencloud_caps_to_syndicate_caps( opencloud_volume.cap_read_data, opencloud_volume.cap_write_data, opencloud_volume.cap_host_data )
-
- try:
- vol_info = client.create_volume( user_email, vol_name, vol_description, vol_blocksize,
- private=vol_private,
- archive=vol_archive,
- active=True,
- default_gateway_caps=vol_default_gateway_caps,
- store_private_key=False,
- metadata_private_key="MAKE_METADATA_KEY" )
-
- except Exception, e:
- # transport error
- logger.exception(e)
- raise e
-
- else:
- # successfully created the volume!
- return vol_info
-
- else:
-
- # volume already exists. Verify its owned by this user.
- if user is None:
- try:
- user = client.read_user( volume['owner_id'] )
- except Exception, e:
- # transport error, or user doesn't exist (either is unacceptable)
- logger.exception(e)
- raise e
-
- if user is None or user['email'] != user_email:
- raise Exception("Volume '%s' already exists, but is NOT owned by '%s'" % (opencloud_volume.name, user_email) )
-
- # we're good!
- return None
-
-
-#-------------------------------
-def ensure_volume_absent( volume_name ):
- """
- Given an OpenCloud volume, ensure that the corresponding Syndicate
- Volume does not exist.
- """
-
- client = connect_syndicate()
-
- # this is idempotent, and returns True even if the Volume doesn't exist
- return client.delete_volume( volume_name )
-
-
-#-------------------------------
-def update_volume( opencloud_volume ):
- """
- Update a Syndicate Volume from an OpenCloud Volume model.
- Fails if the Volume does not exist in Syndicate.
- """
-
- client = connect_syndicate()
-
- vol_name = opencloud_volume.name
- vol_description = opencloud_volume.description
- vol_private = opencloud_volume.private
- vol_archive = opencloud_volume.archive
- vol_default_gateway_caps = opencloud_caps_to_syndicate_caps( opencloud_volume.cap_read_data, opencloud_volume.cap_write_data, opencloud_volume.cap_host_data )
-
- try:
- rc = client.update_volume( vol_name,
- description=vol_description,
- private=vol_private,
- archive=vol_archive,
- default_gateway_caps=vol_default_gateway_caps )
-
- if not rc:
- raise Exception("update_volume(%s) failed!" % vol_name )
-
- except Exception, e:
- # transort or method error
- logger.exception(e)
- return False
-
- else:
- return True
-
-
-#-------------------------------
-def ensure_volume_access_right_exists( user_email, volume_name, caps, allowed_gateways=[msconfig.GATEWAY_TYPE_UG] ):
- """
- Ensure that a particular user has particular access to a particular volume.
- Do not try to ensure that the user or volume exist, however!
- """
- client = connect_syndicate()
- return syndicate_provisioning.ensure_volume_access_right_exists( client, user_email, volume_name, caps, allowed_gateways )
-
-#-------------------------------
-def ensure_volume_access_right_absent( user_email, volume_name ):
- """
- Ensure that acess to a particular volume is revoked.
- """
- client = connect_syndicate()
- return syndicate_provisioning.ensure_volume_access_right_absent( client, user_email, volume_name )
-
-
-#-------------------------------
-def setup_volume_access( user_email, volume_name, caps, RG_port, slice_secret, RG_closure=None ):
- """
- Set up the Volume to allow the slice to provision UGs in it, and to fire up RGs.
- * create the Volume Access Right for the user, so (s)he can create Gateways.
- * provision a single Replica Gateway, serving on localhost.
- """
- client = connect_syndicate()
-
- try:
- rc = ensure_volume_access_right_exists( user_email, volume_name, caps )
- assert rc is True, "Failed to create access right for %s in %s" % (user_email, volume_name)
-
- except Exception, e:
- logger.exception(e)
- return False
-
- RG_name = syndicate_provisioning.make_gateway_name( "OpenCloud", "RG", volume_name, "localhost" )
- RG_key_password = syndicate_provisioning.make_gateway_private_key_password( RG_name, slice_secret )
-
- try:
- rc = syndicate_provisioning.ensure_RG_exists( client, user_email, volume_name, RG_name, "localhost", RG_port, RG_key_password, closure=RG_closure )
- except Exception, e:
- logger.exception(e)
- return False
-
- return True
-
-
-#-------------------------------
-def teardown_volume_access( user_email, volume_name ):
- """
- Revoke access to a Volume for a User.
- * remove the user's Volume Access Right
- * remove the use'rs gateways
- """
- client = connect_syndicate()
-
- # block the user from creating more gateways, and delete the gateways
- try:
- rc = client.remove_user_from_volume( user_email, volume_name )
- assert rc is True, "Failed to remove access right for %s in %s" % (user_email, volume_name)
-
- except Exception, e:
- logger.exception(e)
- return False
-
- return True
-
-
-#-------------------------------
-def create_sealed_and_signed_blob( private_key_pem, secret, data ):
- """
- Create a sealed and signed message.
- """
-
- # seal it with the password
- logger.info("Sealing credential data")
-
- rc, sealed_data = c_syndicate.password_seal( data, secret )
- if rc != 0:
- logger.error("Failed to seal data with the secret, rc = %s" % rc)
- return None
-
- msg = syndicate_crypto.sign_and_serialize_json( private_key_pem, sealed_data )
- if msg is None:
- logger.error("Failed to sign credential")
- return None
-
- return msg
-
-
-#-------------------------------
-def verify_and_unseal_blob( public_key_pem, secret, blob_data ):
- """
- verify and unseal a serialized string of JSON
- """
-
- # verify it
- rc, sealed_data = syndicate_crypto.verify_and_parse_json( public_key_pem, blob_data )
- if rc != 0:
- logger.error("Failed to verify and parse blob, rc = %s" % rc)
- return None
-
- logger.info("Unsealing credential data")
-
- rc, data = c_syndicate.password_unseal( sealed_data, secret )
- if rc != 0:
- logger.error("Failed to unseal blob, rc = %s" % rc )
- return None
-
- return data
-
-
-#-------------------------------
-def create_volume_list_blob( private_key_pem, slice_secret, volume_list ):
- """
- Create a sealed volume list, signed with the private key.
- """
- list_data = {
- "volumes": volume_list
- }
-
- list_data_str = json.dumps( list_data )
-
- msg = create_sealed_and_signed_blob( private_key_pem, slice_secret, list_data_str )
- if msg is None:
- logger.error("Failed to seal volume list")
- return None
-
- return msg
-
-
-#-------------------------------
-def create_slice_credential_blob( private_key_pem, slice_name, slice_secret, syndicate_url, volume_name, volume_owner, UG_port, user_pkey_pem ):
- """
- Create a sealed, signed, encoded slice credentials blob.
- """
-
- # create and serialize the data
- cred_data = {
- "syndicate_url": syndicate_url,
- "volume_name": volume_name,
- "volume_owner": volume_owner,
- "slice_name": slice_name,
- "slice_UG_port": UG_port,
- "principal_pkey_pem": user_pkey_pem,
- }
-
- cred_data_str = json.dumps( cred_data )
-
- msg = create_sealed_and_signed_blob( private_key_pem, slice_secret, cred_data_str )
- if msg is None:
- logger.error("Failed to seal volume list")
- return None
-
- return msg
-
-
-#-------------------------------
-def put_principal_data( user_email, observer_secret, public_key_pem, private_key_pem ):
- """
- Seal and store the principal's private key into the database, in a SyndicatePrincipal object,
- so the instance-side Syndicate daemon syndicated.py can get them later.
- Overwrite an existing principal if one exists.
- """
-
- sealed_private_key = create_sealed_and_signed_blob( private_key_pem, observer_secret, private_key_pem )
- if sealed_private_key is None:
- return False
-
- try:
- sp = models.SyndicatePrincipal( sealed_private_key=sealed_private_key, public_key_pem=public_key_pem, principal_id=user_email )
- sp.save()
- except IntegrityError, e:
- logger.error("WARN: overwriting existing principal %s" % user_email)
- sp.delete()
- sp.save()
-
- return True
-
-
-#-------------------------------
-def delete_principal_data( user_email ):
- """
- Delete an OpenCloud SyndicatePrincipal object.
- """
-
- sp = get_principal_data( user_email )
- if sp is not None:
- sp.delete()
-
- return True
-
-
-#-------------------------------
-def get_principal_data( user_email ):
- """
- Get a SyndicatePrincipal record from the database
- """
-
- try:
- sp = models.SyndicatePrincipal.objects.get( principal_id=user_email )
- return sp
- except ObjectDoesNotExist:
- logger.error("No SyndicatePrincipal record for %s" % user_email)
- return None
-
-
-
-#-------------------------------
-def get_principal_pkey( user_email, observer_secret ):
- """
- Fetch and unseal the private key of a SyndicatePrincipal.
- """
-
- sp = get_principal_data( user_email )
- if sp is None:
- logger.error("Failed to find private key for principal %s" % user_email )
- return None
-
- public_key_pem = sp.public_key_pem
- sealed_private_key_pem = sp.sealed_private_key
-
- # unseal
- private_key_pem = verify_and_unseal_blob(public_key_pem, observer_secret, sealed_private_key_pem)
- if private_key_pem is None:
- logger.error("Failed to unseal private key")
-
- return private_key_pem
-
-
-#-------------------------------
-def get_private_key_pem( pkey_path ):
- """
- Get a private key from storage, PEM-encoded.
- """
-
- # get the OpenCloud private key
- observer_pkey = syndicate_storage.read_private_key( pkey_path )
- if observer_pkey is None:
- logger.error("Failed to load Observer private key")
- return None
-
- observer_pkey_pem = observer_pkey.exportKey()
-
- return observer_pkey_pem
-
-
-#-------------------------------
-def encrypt_slice_secret( observer_pkey_pem, slice_secret ):
- """
- Encrypt and serialize the slice secret with the Observer private key
- """
-
- # get the public key
- try:
- observer_pubkey_pem = CryptoKey.importKey( observer_pkey_pem ).publickey().exportKey()
- except Exception, e:
- logger.exception(e)
- logger.error("Failed to derive public key from private key")
- return None
-
- # encrypt the data
- rc, sealed_slice_secret = c_syndicate.encrypt_data( observer_pkey_pem, observer_pubkey_pem, slice_secret )
-
- if rc != 0:
- logger.error("Failed to encrypt slice secret")
- return None
-
- sealed_slice_secret_b64 = base64.b64encode( sealed_slice_secret )
-
- return sealed_slice_secret_b64
-
-
-#-------------------------------
-def decrypt_slice_secret( observer_pkey_pem, sealed_slice_secret_b64 ):
- """
- Unserialize and decrypt a slice secret
- """
-
- # get the public key
- try:
- observer_pubkey_pem = CryptoKey.importKey( observer_pkey_pem ).publickey().exportKey()
- except Exception, e:
- logger.exception(e)
- logger.error("Failed to derive public key from private key")
- return None
-
- sealed_slice_secret = base64.b64decode( sealed_slice_secret_b64 )
-
- # decrypt it
- rc, slice_secret = c_syndicate.decrypt_data( observer_pubkey_pem, observer_pkey_pem, sealed_slice_secret )
-
- if rc != 0:
- logger.error("Failed to decrypt '%s', rc = %d" % (sealed_slice_secret_b64, rc))
- return None
-
- return slice_secret
-
-
-#--------------------------------
-def get_slice_secret( observer_pkey_pem, slice_name, slice_fk=None ):
- """
- Get the shared secret for a slice.
- """
-
- ss = None
-
- # get the sealed slice secret from Django
- try:
- if slice_fk is not None:
- ss = models.SliceSecret.objects.get( slice_id=slice_fk )
- else:
- ss = models.SliceSecret.objects.get( slice_id__name=slice_name )
- except ObjectDoesNotExist, e:
- logger.error("Failed to load slice secret for (%s, %s)" % (slice_fk, slice_name) )
- return None
-
- return ss.secret
-
-
-#-------------------------------
-def put_slice_secret( observer_pkey_pem, slice_name, slice_secret, slice_fk=None, opencloud_slice=None ):
- """
- Put the shared secret for a slice, encrypting it first.
- """
-
- ss = None
-
- if opencloud_slice is None:
- # look up the slice
- try:
- if slice_fk is None:
- opencloud_slice = models.Slice.objects.get( name=slice_name )
- else:
- opencloud_slice = models.Slice.objects.get( id=slice_fk.id )
- except Exception, e:
- logger.exception(e)
- logger.error("Failed to load slice (%s, %s)" % (slice_fk, slice_name) )
- return False
-
- ss = models.SliceSecret( slice_id=opencloud_slice, secret=slice_secret )
-
- ss.save()
-
- return True
-
-
-#-------------------------------
-def get_or_create_slice_secret( observer_pkey_pem, slice_name, slice_fk=None ):
- """
- Get a slice secret if it already exists, or generate a slice secret if one does not.
- """
-
- slice_secret = get_slice_secret( observer_pkey_pem, slice_name, slice_fk=slice_fk )
- if slice_secret is None or len(slice_secret) == 0:
-
- # generate a slice secret
- slice_secret = "".join( random.sample("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 32) )
-
- # store it
- rc = put_slice_secret( observer_pkey_pem, slice_name, slice_secret, slice_fk=slice_fk )
-
- if not rc:
- raise SyndicateObserverError("Failed to create slice secret for (%s, %s)" % (slice_fk, slice_name))
-
- return slice_secret
-
-
-#-------------------------------
-def generate_slice_credentials( observer_pkey_pem, syndicate_url, user_email, volume_name, slice_name, observer_secret, slice_secret, UG_port, existing_user=None ):
- """
- Generate and return the set of credentials to be sent off to the slice VMs.
- exisitng_user is a Syndicate user, as a dictionary.
-
- Return None on failure
- """
-
- # get the user's private key
- logger.info("Obtaining private key for %s" % user_email)
-
- # it might be in the existing_user...
- user_pkey_pem = None
- if existing_user is not None:
- user_pkey_pem = existing_user.get('signing_private_key', None)
-
- # no luck?
- if user_pkey_pem is None:
- try:
- # get it from Django DB
- user_pkey_pem = get_principal_pkey( user_email, observer_secret )
- assert user_pkey_pem is not None, "No private key for %s" % user_email
-
- except:
- traceback.print_exc()
- logger.error("Failed to get private key; cannot generate credentials for %s in %s" % (user_email, volume_name) )
- return None
-
- # generate a credetials blob
- logger.info("Generating credentials for %s's slice" % (user_email))
- try:
- creds = create_slice_credential_blob( observer_pkey_pem, slice_name, slice_secret, syndicate_url, volume_name, user_email, UG_port, user_pkey_pem )
- assert creds is not None, "Failed to create credentials for %s" % user_email
-
- except:
- traceback.print_exc()
- logger.error("Failed to generate credentials for %s in %s" % (user_email, volume_name))
- return None
-
- return creds
-
-
-#-------------------------------
-def save_slice_credentials( observer_pkey_pem, syndicate_url, user_email, volume_name, slice_name, observer_secret, slice_secret, UG_port, existing_user=None ):
- """
- Create and save a credentials blob to a VolumeSlice.
- Return the creds on success.
- Return None on failure
- """
-
- creds = generate_slice_credentials( observer_pkey_pem, syndicate_url, user_email, volume_name, slice_name, observer_secret, slice_secret, UG_port, existing_user=existing_user )
- ret = None
-
- if creds is not None:
- # save it
- vs = get_volumeslice( volume_name, slice_name )
-
- if vs is not None:
- vs.credentials_blob = creds
- vs.save()
-
- # success!
- ret = creds
- else:
- logger.error("Failed to look up VolumeSlice(%s, %s)" % (volume_name, slice_name))
-
- else:
- logger.error("Failed to generate credentials for %s, %s" % (volume_name, slice_name))
-
- return ret
-
-
-#-------------------------------
-def get_volumeslice_volume_names( slice_name ):
- """
- Get the list of Volume names from the datastore.
- """
- try:
- all_vs = models.VolumeSlice.objects.filter( slice_id__name = slice_name )
- volume_names = []
- for vs in all_vs:
- volume_names.append( vs.volume_id.name )
-
- return volume_names
- except Exception, e:
- logger.exception(e)
- logger.error("Failed to query datastore for volumes mounted in %s" % slice_name)
- return None
-
-
-#-------------------------------
-def get_volumeslice( volume_name, slice_name ):
- """
- Get a volumeslice record from the datastore.
- """
- try:
- vs = models.VolumeSlice.objects.get( volume_id__name = volume_name, slice_id__name = slice_name )
- return vs
- except Exception, e:
- logger.exception(e)
- logger.error("Failed to query datastore for volumes (mounted in %s)" % (slice_name if (slice_name is not None or len(slice_name) > 0) else "UNKNOWN"))
- return None
-
-
-#-------------------------------
-def do_push( instance_hosts, portnum, payload ):
- """
- Push a payload to a list of instances.
- NOTE: this has to be done in one go, since we can't import grequests
- into the global namespace (without wrecking havoc on the credential server),
- but it has to stick around for the push to work.
- """
-
- global TESTING, CONFIG
-
- from gevent import monkey
-
- if TESTING:
- monkey.patch_all()
-
- else:
- # make gevents runnabale from multiple threads (or Django will complain)
- monkey.patch_all(socket=True, dns=True, time=True, select=True, thread=False, os=True, ssl=True, httplib=False, aggressive=True)
-
- import grequests
-
- # fan-out
- requests = []
- for sh in instance_hosts:
- rs = grequests.post( "http://" + sh + ":" + str(portnum), data={"observer_message": payload}, timeout=getattr(CONFIG, "SYNDICATE_HTTP_PUSH_TIMEOUT", 60) )
- requests.append( rs )
-
- # fan-in
- responses = grequests.map( requests )
-
- assert len(responses) == len(requests), "grequests error: len(responses) != len(requests)"
-
- for i in xrange(0,len(requests)):
- resp = responses[i]
- req = requests[i]
-
- if resp is None:
- logger.error("Failed to connect to %s" % (req.url))
- continue
-
- # verify they all worked
- if resp.status_code != 200:
- logger.error("Failed to POST to %s, status code = %s" % (resp.url, resp.status_code))
- continue
-
- return True
-
-
-#-------------------------------
-def get_slice_hostnames( slice_name ):
- """
- Query the Django DB and get the list of hosts running in a slice.
- """
-
- openstack_slice = Slice.objects.get( name=slice_name )
- if openstack_slice is None:
- logger.error("No such slice '%s'" % slice_name)
- return None
-
- hostnames = [s.node.name for s in openstack_slice.instances.all()]
-
- return hostnames
-
-
-#-------------------------------
-def push_credentials_to_slice( slice_name, payload ):
- """
- Push a credentials payload to the VMs in a slice.
- """
- hostnames = get_slice_hostnames( slice_name )
- return do_push( hostnames, CONFIG.SYNDICATE_SLIVER_PORT, payload )
-
-
-#-------------------------------
-class CredentialServerHandler( BaseHTTPServer.BaseHTTPRequestHandler ):
- """
- HTTP server handler that allows syndicated.py instances to poll
- for volume state.
-
- NOTE: this is a fall-back mechanism. The observer should push new
- volume state to the slices' instances. However, if that fails, the
- instances are configured to poll for volume state periodically. This
- server allows them to do just that.
-
- Responses:
- GET /<slicename> -- Reply with the signed sealed list of volume names, encrypted by the slice secret
- GET /<slicename>/<volumename> -- Reply with the signed sealed volume access credentials, encrypted by the slice secret
-
- !!! TEMPORARY !!!
- GET /<slicename>/SYNDICATE_SLICE_SECRET -- Reply with the slice secret (TEMPORARY)
-
-
- NOTE: We want to limit who can learn which Volumes a slice can access, so we'll seal its instances'
- credentials with the SliceSecret secret. The instances (which have the slice-wide secret) can then decrypt it.
- However, sealing the listing is a time-consuming process (on the order of 10s), so we only want
- to do it when we have to. Since *anyone* can ask for the ciphertext of the volume list,
- we will cache the list ciphertext for each slice for a long-ish amount of time, so we don't
- accidentally DDoS this server. This necessarily means that the instance might see a stale
- volume listing, but that's okay, since the Observer is eventually consistent anyway.
- """
-
- cached_volumes_json = {} # map slice_name --> (volume name, timeout)
- cached_volumes_json_lock = threading.Lock()
-
- CACHED_VOLUMES_JSON_LIFETIME = 3600 # one hour
-
- SLICE_SECRET_NAME = "SYNDICATE_SLICE_SECRET"
-
- def parse_request_path( self, path ):
- """
- Parse the URL path into a slice name and (possibly) a volume name or SLICE_SECRET_NAME
- """
- path_parts = path.strip("/").split("/")
-
- if len(path_parts) == 0:
- # invalid
- return (None, None)
-
- if len(path_parts) > 2:
- # invalid
- return (None, None)
-
- slice_name = path_parts[0]
- if len(slice_name) == 0:
- # empty string is invalid
- return (None, None)
-
- volume_name = None
-
- if len(path_parts) > 1:
- volume_name = path_parts[1]
-
- return slice_name, volume_name
-
-
- def reply_data( self, data, datatype="application/json" ):
- """
- Give back a 200 response with data.
- """
- self.send_response( 200 )
- self.send_header( "Content-Type", datatype )
- self.send_header( "Content-Length", len(data) )
- self.end_headers()
-
- self.wfile.write( data )
- return
-
-
- def get_volumes_message( self, private_key_pem, observer_secret, slice_name ):
- """
- Get the json-ized list of volumes this slice is attached to.
- Check the cache, evict stale data if necessary, and on miss,
- regenerate the slice volume list.
- """
-
- # block the cache.
- # NOTE: don't release the lock until we've generated credentials.
- # Chances are, there's a thundering herd of instances coming online.
- # Block them all until we've generated their slice's credentials,
- # and then serve them the cached one.
-
- self.cached_volumes_json_lock.acquire()
-
- ret = None
- volume_list_json, cache_timeout = self.cached_volumes_json.get( slice_name, (None, None) )
-
- if (cache_timeout is not None) and cache_timeout < time.time():
- # expired
- volume_list_json = None
-
- if volume_list_json is None:
- # generate a new list and cache it.
-
- volume_names = get_volumeslice_volume_names( slice_name )
- if volume_names is None:
- # nothing to do...
- ret = None
-
- else:
- # get the slice secret
- slice_secret = get_slice_secret( private_key_pem, slice_name )
-
- if slice_secret is None:
- # no such slice
- logger.error("No slice secret for %s" % slice_name)
- ret = None
-
- else:
- # seal and sign
- ret = create_volume_list_blob( private_key_pem, slice_secret, volume_names )
-
- # cache this
- if ret is not None:
- self.cached_volumes_json[ slice_name ] = (ret, time.time() + self.CACHED_VOLUMES_JSON_LIFETIME )
-
- else:
- # hit the cache
- ret = volume_list_json
-
- self.cached_volumes_json_lock.release()
-
- return ret
-
-
- def do_GET( self ):
- """
- Handle one GET
- """
- slice_name, volume_name = self.parse_request_path( self.path )
-
- # valid request?
- if volume_name is None and slice_name is None:
- self.send_error( 400 )
-
- # slice secret request?
- elif volume_name == self.SLICE_SECRET_NAME and slice_name is not None:
-
- # get the slice secret
- ret = get_slice_secret( self.server.private_key_pem, slice_name )
-
- if ret is not None:
- self.reply_data( ret )
- return
- else:
- self.send_error( 404 )
-
- # volume list request?
- elif volume_name is None and slice_name is not None:
-
- # get the list of volumes for this slice
- ret = self.get_volumes_message( self.server.private_key_pem, self.server.observer_secret, slice_name )
-
- if ret is not None:
- self.reply_data( ret )
- return
- else:
- self.send_error( 404 )
-
- # volume credential request?
- elif volume_name is not None and slice_name is not None:
-
- # get the VolumeSlice record
- vs = get_volumeslice( volume_name, slice_name )
- if vs is None:
- # not found
- self.send_error( 404 )
- return
-
- else:
- ret = vs.credentials_blob
- if ret is not None:
- self.reply_data( vs.credentials_blob )
- else:
- # not generated???
- print ""
- print vs
- print ""
- self.send_error( 503 )
- return
-
- else:
- # shouldn't get here...
- self.send_error( 500 )
- return
-
-
-#-------------------------------
-class CredentialServer( BaseHTTPServer.HTTPServer ):
-
- def __init__(self, private_key_pem, observer_secret, server, req_handler ):
- self.private_key_pem = private_key_pem
- self.observer_secret = observer_secret
- BaseHTTPServer.HTTPServer.__init__( self, server, req_handler )
-
-
-#-------------------------------
-def credential_server_spawn( old_exit_status ):
- """
- Start our credential server (i.e. in a separate process, started by the watchdog)
- """
-
- setproctitle.setproctitle( "syndicate-credential-server" )
-
- private_key = syndicate_storage.read_private_key( CONFIG.SYNDICATE_PRIVATE_KEY )
- if private_key is None:
- # exit code 255 will be ignored...
- logger.error("Cannot load private key. Exiting...")
- sys.exit(255)
-
- logger.info("Starting Syndicate Observer credential server on port %s" % CONFIG.SYNDICATE_HTTP_PORT)
-
- srv = CredentialServer( private_key.exportKey(), CONFIG.SYNDICATE_OPENCLOUD_SECRET, ('', CONFIG.SYNDICATE_HTTP_PORT), CredentialServerHandler)
- srv.serve_forever()
-
-
-#-------------------------------
-def ensure_credential_server_running( foreground=False, run_once=False ):
- """
- Instantiate our credential server and keep it running.
- """
-
- # is the watchdog running?
- pids = syndicate_watchdog.find_by_attrs( "syndicate-credential-server-watchdog", {} )
- if len(pids) > 0:
- # it's running
- return True
-
- if foreground:
- # run in foreground
-
- if run_once:
- return credential_server_spawn( 0 )
-
- else:
- return syndicate_watchdog.main( credential_server_spawn, respawn_exit_statuses=range(1,254) )
-
-
- # not running, and not foregrounding. fork a new one
- try:
- watchdog_pid = os.fork()
- except OSError, oe:
- logger.error("Failed to fork, errno = %s" % oe.errno)
- return False
-
- if watchdog_pid != 0:
-
- # child--become watchdog
- setproctitle.setproctitle( "syndicate-credential-server-watchdog" )
-
- if run_once:
- syndicate_daemon.daemonize( lambda: credential_server_spawn(0), logfile_path=getattr(CONFIG, "SYNDICATE_HTTP_LOGFILE", None) )
-
- else:
- syndicate_daemon.daemonize( lambda: syndicate_watchdog.main( credential_server_spawn, respawn_exit_statuses=range(1,254) ), logfile_path=getattr(CONFIG, "SYNDICATE_HTTP_LOGFILE", None) )
-
-
-#-------------------------------
-# Begin functional tests.
-# Any method starting with ft_ is a functional test.
-#-------------------------------
-
-#-------------------------------
-def ft_syndicate_access():
- """
- Functional tests for ensuring objects exist and don't exist in Syndicate.
- """
-
- fake_user = FakeObject()
- fake_user.email = "fakeuser@opencloud.us"
-
- print "\nensure_user_exists(%s)\n" % fake_user.email
- ensure_user_exists( fake_user.email, is_admin=False, max_UGs=1100, max_RGs=1 )
-
- print "\nensure_user_exists(%s)\n" % fake_user.email
- ensure_user_exists( fake_user.email, is_admin=False, max_UGs=1100, max_RGs=1 )
-
- fake_volume = FakeObject()
- fake_volume.name = "fakevolume"
- fake_volume.description = "This is a fake volume, created for funtional testing"
- fake_volume.blocksize = 1024
- fake_volume.cap_read_data = True
- fake_volume.cap_write_data = True
- fake_volume.cap_host_data = False
- fake_volume.archive = False
- fake_volume.private = True
-
- # test idempotency
- print "\nensure_volume_exists(%s)\n" % fake_volume.name
- ensure_volume_exists( fake_user.email, fake_volume )
-
- print "\nensure_volume_exists(%s)\n" % fake_volume.name
- ensure_volume_exists( fake_user.email, fake_volume )
-
- print "\nensure_volume_access_right_exists(%s,%s)\n" % (fake_user.email, fake_volume.name)
- ensure_volume_access_right_exists( fake_user.email, fake_volume.name, 31 )
-
- print "\nensure_volume_access_right_exists(%s,%s)\n" % (fake_user.email, fake_volume.name)
- ensure_volume_access_right_exists( fake_user.email, fake_volume.name, 31 )
-
- print "\nensure_volume_access_right_absent(%s,%s)\n" % (fake_user.email, fake_volume.name)
- ensure_volume_access_right_absent( fake_user.email, fake_volume.name )
-
- print "\nensure_volume_access_right_absent(%s,%s)\n" % (fake_user.email, fake_volume.name)
- ensure_volume_access_right_absent( fake_user.email, fake_volume.name )
-
- print "\nensure_volume_absent(%s)\n" % fake_volume.name
- ensure_volume_absent( fake_volume.name )
-
- print "\nensure_volume_absent(%s)\n" % fake_volume.name
- ensure_volume_absent( fake_volume.name )
-
- print "\nensure_user_absent(%s)\n" % fake_user.email
- ensure_user_absent( fake_user.email )
-
- print "\nensure_user_absent(%s)\n" % fake_user.email
- ensure_user_absent( fake_user.email )
-
-
-
-
- print "\nensure_principal_exists(%s)\n" % fake_user.email
- ensure_principal_exists( fake_user.email, "asdf", is_admin=False, max_UGs=1100, max_RGs=1 )
-
- print "\nensure_principal_exists(%s)\n" % fake_user.email
- ensure_principal_exists( fake_user.email, "asdf", is_admin=False, max_UGs=1100, max_RGs=1 )
-
- print "\nensure_volume_exists(%s)\n" % fake_volume.name
- ensure_volume_exists( fake_user.email, fake_volume )
-
- print "\nsetup_volume_access(%s, %s)\n" % (fake_user.email, fake_volume.name)
- setup_volume_access( fake_user.email, fake_volume.name, 31, 38800, "abcdef" )
-
- print "\nsetup_volume_access(%s, %s)\n" % (fake_user.email, fake_volume.name)
- setup_volume_access( fake_user.email, fake_volume.name, 31, 38800, "abcdef" )
-
- print "\nteardown_volume_access(%s, %s)\n" % (fake_user.email, fake_volume.name )
- teardown_volume_access( fake_user.email, fake_volume.name )
-
- print "\nteardown_volume_access(%s, %s)\n" % (fake_user.email, fake_volume.name )
- teardown_volume_access( fake_user.email, fake_volume.name )
-
- print "\nensure_volume_absent(%s)\n" % fake_volume.name
- ensure_volume_absent( fake_volume.name )
-
- print "\nensure_principal_absent(%s)\n" % fake_user.email
- ensure_principal_absent( fake_user.email )
-
-
-
-#-------------------------------
-def ft_volumeslice( slice_name ):
- """
- Functional tests for reading VolumeSlice information
- """
- print "slice: %s" % slice_name
-
- volumes = get_volumeslice_volume_names( slice_name )
-
- print "volumes mounted in slice %s:" % slice_name
- for v in volumes:
- print " %s:" % v
-
- vs = get_volumeslice( v, slice_name )
-
- print " %s" % dir(vs)
-
-
-#-------------------------------
-def ft_get_slice_hostnames( slice_name ):
- """
- Functional tests for getting slice hostnames
- """
-
- print "Get slice hostnames for %s" % slice_name
-
- hostnames = get_slice_hostnames( slice_name )
- import pprint
-
- pp = pprint.PrettyPrinter()
-
- pp.pprint( hostnames )
-
-
-#-------------------------------
-def ft_syndicate_principal():
- """
- Functional tests for creating, reading, and deleting SyndicatePrincipals.
- """
- print "generating key pair"
- pubkey_pem, privkey_pem = api.generate_key_pair( 4096 )
-
- user_email = "fakeuser@opencloud.us"
-
- print "saving principal"
- put_principal_data( user_email, "asdf", pubkey_pem, privkey_pem )
-
- print "fetching principal private key"
- saved_privkey_pem = get_principal_pkey( user_email, "asdf" )
-
- assert saved_privkey_pem is not None, "Could not fetch saved private key"
- assert saved_privkey_pem == privkey_pem, "Saved private key does not match actual private key"
-
- print "delete principal"
-
- delete_principal_data( user_email )
-
- print "make sure its deleted..."
-
- saved_privkey_pem = get_principal_pkey( user_email, "asdf" )
-
- assert saved_privkey_pem is None, "Principal key not deleted"
-
-
-#-------------------------------
-def ft_credential_server():
- """
- Functional test for the credential server
- """
- ensure_credential_server_running( run_once=True, foreground=True )
-
-
-#-------------------------------
-def ft_seal_and_unseal():
- """
- Functional test for sealing/unsealing data
- """
- print "generating key pair"
- pubkey_pem, privkey_pem = api.generate_key_pair( 4096 )
-
- sealed_buf = create_sealed_and_signed_blob( privkey_pem, "foo", "hello world")
- print "sealed data is:\n\n%s\n\n" % sealed_buf
-
- buf = verify_and_unseal_blob( pubkey_pem, "foo", sealed_buf )
- print "unsealed data is: \n\n%s\n\n" % buf
-
-
-# run functional tests
-if __name__ == "__main__":
- sys.path.append("/opt/xos")
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-
- if len(sys.argv) < 2:
- print "Usage: %s testname [args]" % sys.argv[0]
-
- # call a method starting with ft_, and then pass the rest of argv as its arguments
- testname = sys.argv[1]
- ft_testname = "ft_%s" % testname
-
- test_call = "%s(%s)" % (ft_testname, ",".join(sys.argv[2:]))
-
- print "calling %s" % test_call
-
- rc = eval( test_call )
-
- print "result = %s" % rc
-
-
diff --git a/xos/syndicate_observer/syndicatelib_config/config-jude.py b/xos/syndicate_observer/syndicatelib_config/config-jude.py
deleted file mode 100644
index 81e7478..0000000
--- a/xos/syndicate_observer/syndicatelib_config/config-jude.py
+++ /dev/null
@@ -1,21 +0,0 @@
-#!/usr/bin/env python
-
-# configuration for syndicatelib
-SYNDICATE_SMI_URL="http://localhost:8080"
-
-SYNDICATE_OPENID_TRUSTROOT="http://localhost:8081"
-
-SYNDICATE_OPENCLOUD_USER="judecn@gmail.com"
-SYNDICATE_OPENCLOUD_PASSWORD="nya"
-
-SYNDICATE_PYTHONPATH="/home/jude/Desktop/research/git/syndicate/build/out/python"
-
-SYNDICATE_PRIVATE_KEY="/home/jude/Desktop/research/git/syndicate/opencloud/syndicate_observer/syndicatelib_config/pollserver.pem"
-SYNDICATE_OPENCLOUD_SECRET="e4988309a5005edb8ea185f16f607938c0fb7657e4d7609853bcb7c4884d1c92"
-
-SYNDICATE_HTTP_PORT=65321
-
-SYNDICATE_RG_CLOSURE="/home/jude/Desktop/research/git/syndicate/build/out/python/syndicate/rg/drivers/disk"
-SYNDICATE_RG_DEFAULT_PORT=38800
-
-DEBUG=True
diff --git a/xos/syndicate_observer/syndicatelib_config/config-opencloud.py b/xos/syndicate_observer/syndicatelib_config/config-opencloud.py
deleted file mode 100644
index 3cd2950..0000000
--- a/xos/syndicate_observer/syndicatelib_config/config-opencloud.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/env python
-
-# ---------------------------------
-# This is the configuration file used by the Syndicate observer.
-# It is a well-formed Python file, and will be imported into the
-# observer as a Python module. This means you can run any config-
-# generation code here you like, but all of the following global
-# variables must be defined.
-# ---------------------------------
-
-# URL to the Syndicate SMI. For example, https://syndicate-metadata.appspot.com
-SYNDICATE_SMI_URL="http://localhost:8080"
-
-# If you are going to use OpenID to authenticate the Syndicate instance daemon,
-# this is the OpenID provider URL. It is currently used only to generate
-# identity pages for users, so you can put whatever you want here for now.
-SYNDICATE_OPENID_TRUSTROOT="http://localhost:8081"
-
-# This is the observer's user account on Syndicate. You must create it out-of-band
-# prior to using the observer, and it must be an admin user since it will
-# create other users (i.e. for slices).
-SYNDICATE_OPENCLOUD_USER="jcnelson@cs.princeton.edu"
-
-# This is the password for the observer to authenticate itself to Syndicate.
-SYNDICATE_OPENCLOUD_PASSWORD="nya"
-
-# If the observer uses public-key authentication with Syndicate, you will
-# need to identify the absolute path to its private key here. It must be
-# a 4096-bit PEM-encoded RSA key, and the Syndicate observer's user account
-# must have been given the public key on activation.
-SYNDICATE_OPENCLOUD_PKEY=None
-
-# This is the location on disk where Syndicate observer code can be found,
-# if it is not already in the Python path. This is optional.
-SYNDICATE_PYTHONPATH="/root/syndicate/build/out/python"
-
-# This is the location of the observer's private key. It must be an absolute
-# path, and refer to a 4096-bit PEM-encoded RSA key.
-SYNDICATE_PRIVATE_KEY="/opt/xos/syndicate_observer/syndicatelib_config/pollserver.pem"
-
-# This is the master secret used to generate secrets to seal sensitive information sent to the
-# Syndicate instance mount daemons. It is also used to seal sensitive information
-# stored to the Django database.
-# TODO: think of a way to not have to store this on disk. Maybe we feed into the
-# observer when it starts up?
-SYNDICATE_OPENCLOUD_SECRET="e4988309a5005edb8ea185f16f607938c0fb7657e4d7609853bcb7c4884d1c92"
-
-# This is the default port number on which a Syndicate Replica Gateway
-# will be provisioned. It's a well-known port, and can be the same across
-# instances, since in OpenCloud, an RG instance only listens to localhost.
-SYNDICATE_RG_DEFAULT_PORT=38800
-
-# This is the absolute path to the RG's storage driver (which will be automatically
-# pushed to instances by Syndicate). See https://github.com/jcnelson/syndicate/wiki/Replica-Gateways
-SYNDICATE_RG_CLOSURE=None
-
-# This is the port number the observer listens on for GETs from the Syndicate instance mount
-# daemons. Normally, the oserver pushes (encrypted) commands to the daemons, but if the
-# daemons are NAT'ed or temporarily partitioned, they will pull commands instead.
-SYNDICATE_HTTP_PORT=65321
-
-# This is the path to the logfile for the observer's HTTP server.
-SYNDICATE_HTTP_LOGFILE="/tmp/syndicate-observer.log"
-
-# This is the number of seconds to wait for pushing a slice credential before timing out.
-SYNDICATE_HTTP_PUSH_TIMEOUT=60
-
-# This is the port number the Syndicate instance mount daemons listen on. The observer will
-# push commands to them on this port.
-SYNDICATE_SLIVER_PORT=65322
-
-# If true, print verbose debug messages.
-DEBUG=True
diff --git a/xos/syndicate_observer/syndicatelib_config/config.py b/xos/syndicate_observer/syndicatelib_config/config.py
deleted file mode 100644
index 3cd2950..0000000
--- a/xos/syndicate_observer/syndicatelib_config/config.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/env python
-
-# ---------------------------------
-# This is the configuration file used by the Syndicate observer.
-# It is a well-formed Python file, and will be imported into the
-# observer as a Python module. This means you can run any config-
-# generation code here you like, but all of the following global
-# variables must be defined.
-# ---------------------------------
-
-# URL to the Syndicate SMI. For example, https://syndicate-metadata.appspot.com
-SYNDICATE_SMI_URL="http://localhost:8080"
-
-# If you are going to use OpenID to authenticate the Syndicate instance daemon,
-# this is the OpenID provider URL. It is currently used only to generate
-# identity pages for users, so you can put whatever you want here for now.
-SYNDICATE_OPENID_TRUSTROOT="http://localhost:8081"
-
-# This is the observer's user account on Syndicate. You must create it out-of-band
-# prior to using the observer, and it must be an admin user since it will
-# create other users (i.e. for slices).
-SYNDICATE_OPENCLOUD_USER="jcnelson@cs.princeton.edu"
-
-# This is the password for the observer to authenticate itself to Syndicate.
-SYNDICATE_OPENCLOUD_PASSWORD="nya"
-
-# If the observer uses public-key authentication with Syndicate, you will
-# need to identify the absolute path to its private key here. It must be
-# a 4096-bit PEM-encoded RSA key, and the Syndicate observer's user account
-# must have been given the public key on activation.
-SYNDICATE_OPENCLOUD_PKEY=None
-
-# This is the location on disk where Syndicate observer code can be found,
-# if it is not already in the Python path. This is optional.
-SYNDICATE_PYTHONPATH="/root/syndicate/build/out/python"
-
-# This is the location of the observer's private key. It must be an absolute
-# path, and refer to a 4096-bit PEM-encoded RSA key.
-SYNDICATE_PRIVATE_KEY="/opt/xos/syndicate_observer/syndicatelib_config/pollserver.pem"
-
-# This is the master secret used to generate secrets to seal sensitive information sent to the
-# Syndicate instance mount daemons. It is also used to seal sensitive information
-# stored to the Django database.
-# TODO: think of a way to not have to store this on disk. Maybe we feed into the
-# observer when it starts up?
-SYNDICATE_OPENCLOUD_SECRET="e4988309a5005edb8ea185f16f607938c0fb7657e4d7609853bcb7c4884d1c92"
-
-# This is the default port number on which a Syndicate Replica Gateway
-# will be provisioned. It's a well-known port, and can be the same across
-# instances, since in OpenCloud, an RG instance only listens to localhost.
-SYNDICATE_RG_DEFAULT_PORT=38800
-
-# This is the absolute path to the RG's storage driver (which will be automatically
-# pushed to instances by Syndicate). See https://github.com/jcnelson/syndicate/wiki/Replica-Gateways
-SYNDICATE_RG_CLOSURE=None
-
-# This is the port number the observer listens on for GETs from the Syndicate instance mount
-# daemons. Normally, the oserver pushes (encrypted) commands to the daemons, but if the
-# daemons are NAT'ed or temporarily partitioned, they will pull commands instead.
-SYNDICATE_HTTP_PORT=65321
-
-# This is the path to the logfile for the observer's HTTP server.
-SYNDICATE_HTTP_LOGFILE="/tmp/syndicate-observer.log"
-
-# This is the number of seconds to wait for pushing a slice credential before timing out.
-SYNDICATE_HTTP_PUSH_TIMEOUT=60
-
-# This is the port number the Syndicate instance mount daemons listen on. The observer will
-# push commands to them on this port.
-SYNDICATE_SLIVER_PORT=65322
-
-# If true, print verbose debug messages.
-DEBUG=True
diff --git a/xos/syndicate_storage/admin.py b/xos/syndicate_storage/admin.py
deleted file mode 100644
index 66e07dd..0000000
--- a/xos/syndicate_storage/admin.py
+++ /dev/null
@@ -1,158 +0,0 @@
-from django.contrib import admin
-
-from syndicate_storage.models import *
-from django import forms
-from django.utils.safestring import mark_safe
-from django.contrib.auth.admin import UserAdmin
-from django.contrib.admin.widgets import FilteredSelectMultiple
-from django.contrib.auth.forms import ReadOnlyPasswordHashField
-from django.contrib.auth.signals import user_logged_in
-from django.utils import timezone
-from django.contrib.contenttypes import generic
-from suit.widgets import LinkedSelect
-from core.admin import ReadOnlyAwareAdmin,ServiceAppAdmin,SliceInline,ServiceAttrAsTabInline,XOSBaseAdmin, XOSTabularInline
-from suit.widgets import LinkedSelect
-from django.core.exceptions import ValidationError, ObjectDoesNotExist
-
-class SyndicateAdmin(ReadOnlyAwareAdmin):
- # Change the application breadcrumb to point to an RR Service if one is
- # defined
-
- change_form_template = "admin/change_form_bc.html"
- change_list_template = "admin/change_list_bc.html"
- custom_app_breadcrumb_name = "Syndicate_Storage"
- @property
- def custom_app_breadcrumb_url(self):
- services = SyndicateService.objects.all()
- if len(services)==1:
- return "/admin/syndicate_storage/syndicateservice/%s/" % services[0].id
- else:
- return "/admin/syncdicate_storage/syndicateservice/"
-
-class SyndicateServiceAdmin(ServiceAppAdmin):
- model = SyndicateService
- verbose_name = "Syndicate Storage"
- verbose_name_plural = "Syndicate Storage"
- list_display = ("name","enabled")
- fieldsets = [(None, {'fields': ['name','enabled','versionNumber', 'description',], 'classes':['suit-tab suit-tab-general']})]
- inlines = [SliceInline,ServiceAttrAsTabInline]
-
- user_readonly_fields = ['name','enabled','versionNumber','description']
-
- suit_form_tabs =(('general', 'Syndicate Storage Details'),
- ('administration', 'Administration'),
- ('slices','Slices'),
- ('serviceattrs','Additional Attributes'),
- )
-
- suit_form_includes = (('syndicateadmin.html', 'top', 'administration'),)
-
-
-class VolumeAccessRightInline(XOSTabularInline):
- model = VolumeAccessRight
- extra = 0
- suit_classes = 'suit-tab suit-tab-volumeAccessRights'
-
-
-class VolumeSliceFormSet( forms.models.BaseInlineFormSet ):
- # verify that our VolumeSlice is valid
-
- @classmethod
- def verify_unchanged( cls, volume_pk, slice_pk, field_name, new_value ):
- vs = None
- try:
- vs = VolumeSlice.objects.get( volume_id=volume_pk, slice_id=slice_pk )
- except ObjectDoesNotExist, dne:
- return True, None
-
- old_value = getattr( vs, field_name )
- if old_value != new_value:
- return False, old_value
- else:
- return True, None
-
-
- def clean( self ):
- for form in self.forms:
- # check each inline's cleaned data, if it's valid
- cleaned_data = None
- try:
- if form.cleaned_data:
- cleaned_data = form.cleaned_data
- except AttributeError:
- continue
-
- # verify that the ports haven't changed
- volume_pk = cleaned_data['volume_id'].pk
- slice_pk = cleaned_data['slice_id'].pk
-
- if not cleaned_data.has_key('UG_portnum'):
- raise ValidationError("Missing UG port number")
-
- if not cleaned_data.has_key('RG_portnum'):
- raise ValidationError("Missing RG port number")
-
- rc1, old_peer_port = VolumeSliceFormSet.verify_unchanged( volume_pk, slice_pk, 'UG_portnum', cleaned_data['UG_portnum'] )
- rc2, old_replicate_port = VolumeSliceFormSet.verify_unchanged( volume_pk, slice_pk, 'RG_portnum', cleaned_data['RG_portnum'] )
-
- err1str = ""
- err2str = ""
- if not rc1:
- err1str = "change %s back to %s" % (cleaned_data['UG_portnum'], old_peer_port)
- if not rc2:
- err2str = " and change %s back to %s" % (cleaned_data['RG_portnum'], old_replicate_port )
-
- if not rc1 or not rc2:
- raise ValidationError("At this time, port numbers cannot be changed once they are set. Please %s %s" % (err1str, err2str))
-
-
-
-class VolumeSliceInline(XOSTabularInline):
- model = VolumeSlice
- extra = 0
- suit_classes = 'suit-tab suit-tab-volumeSlices'
- fields = ['volume_id', 'slice_id', 'cap_read_data', 'cap_write_data', 'cap_host_data', 'UG_portnum', 'RG_portnum']
-
- formset = VolumeSliceFormSet
-
- readonly_fields = ['credentials_blob']
-
-
-class VolumeAdmin(SyndicateAdmin):
- model = Volume
-
- def get_readonly_fields(self, request, obj=None ):
- always_readonly = []
- if obj == None:
- # all fields are editable on add
- return always_readonly
-
- else:
- # can't change owner, slice id, or block size on update
- return ['blocksize', 'owner_id'] + always_readonly
-
-
- list_display = ['name', 'owner_id']
-
- detailsFieldList = ['name', 'owner_id', 'description','blocksize', 'private','archive', 'cap_read_data', 'cap_write_data', 'cap_host_data' ]
-
- fieldsets = [
- (None, {'fields': detailsFieldList, 'classes':['suit-tab suit-tab-general']}),
- ]
-
- inlines = [VolumeAccessRightInline, VolumeSliceInline]
-
- user_readonly_fields = ['name','owner_id','description','blocksize','private', 'archive', 'cap_read_data', 'cap_write_data', 'cap_host_data']
-
- suit_form_tabs =(('general', 'Volume Details'),
- ('volumeSlices', 'Slices'),
- ('volumeAccessRights', 'Volume Access Rights'))
-
- def queryset(self, request):
- # only show volumes that are public, or owned by the caller
- return Volume.select_by_user(request.user)
-
-
-# left panel:
-admin.site.register(SyndicateService, SyndicateServiceAdmin)
-admin.site.register(Volume, VolumeAdmin)
diff --git a/xos/syndicate_storage/migrations/0001_initial.py b/xos/syndicate_storage/migrations/0001_initial.py
deleted file mode 100644
index 51c8f94..0000000
--- a/xos/syndicate_storage/migrations/0001_initial.py
+++ /dev/null
@@ -1,127 +0,0 @@
-# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
-
-from django.db import models, migrations
-import syndicate_storage.models
-import django.utils.timezone
-from django.conf import settings
-
-
-class Migration(migrations.Migration):
-
- dependencies = [
- migrations.swappable_dependency(settings.AUTH_USER_MODEL),
- ('core', '0001_initial'),
- ]
-
- operations = [
- migrations.CreateModel(
- name='SliceSecret',
- fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('secret', syndicate_storage.models.ObserverSecretValue(help_text=b"Shared secret between OpenCloud and this slice's Syndicate daemons.", blank=True)),
- ('slice_id', models.ForeignKey(to='core.Slice')),
- ],
- options={
- },
- bases=(models.Model,),
- ),
- migrations.CreateModel(
- name='SyndicatePrincipal',
- fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('created', models.DateTimeField(default=django.utils.timezone.now, auto_now_add=True)),
- ('updated', models.DateTimeField(default=django.utils.timezone.now, auto_now=True)),
- ('enacted', models.DateTimeField(default=None, null=True, blank=True)),
- ('backend_status', models.CharField(default=b'Provisioning in progress', max_length=140)),
- ('deleted', models.BooleanField(default=False)),
- ('principal_id', models.TextField(unique=True)),
- ('public_key_pem', models.TextField()),
- ('sealed_private_key', models.TextField()),
- ],
- options={
- },
- bases=(models.Model,),
- ),
- migrations.CreateModel(
- name='SyndicateService',
- fields=[
- ('service_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='core.Service')),
- ],
- options={
- 'verbose_name': 'Syndicate Service',
- 'verbose_name_plural': 'Syndicate Service',
- },
- bases=('core.service', models.Model),
- ),
- migrations.CreateModel(
- name='Volume',
- fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('created', models.DateTimeField(default=django.utils.timezone.now, auto_now_add=True)),
- ('updated', models.DateTimeField(default=django.utils.timezone.now, auto_now=True)),
- ('enacted', models.DateTimeField(default=None, null=True, blank=True)),
- ('backend_status', models.CharField(default=b'Provisioning in progress', max_length=140)),
- ('deleted', models.BooleanField(default=False)),
- ('name', models.CharField(help_text=b'Human-readable, searchable name of the Volume', max_length=64)),
- ('description', models.TextField(help_text=b'Human-readable description of what this Volume is used for.', max_length=130, null=True, blank=True)),
- ('blocksize', models.PositiveIntegerField(help_text=b'Number of bytes per block.')),
- ('private', models.BooleanField(default=True, help_text=b'Indicates if the Volume is visible to users other than the Volume Owner and Syndicate Administrators.')),
- ('archive', models.BooleanField(default=False, help_text=b'Indicates if this Volume is read-only, and only an Aquisition Gateway owned by the Volume owner (or Syndicate admin) can write to it.')),
- ('cap_read_data', models.BooleanField(default=True, help_text=b'VM can read Volume data')),
- ('cap_write_data', models.BooleanField(default=True, help_text=b'VM can write Volume data')),
- ('cap_host_data', models.BooleanField(default=True, help_text=b'VM can host Volume data')),
- ('owner_id', models.ForeignKey(verbose_name=b'Owner', to=settings.AUTH_USER_MODEL)),
- ],
- options={
- },
- bases=(models.Model,),
- ),
- migrations.CreateModel(
- name='VolumeAccessRight',
- fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('created', models.DateTimeField(default=django.utils.timezone.now, auto_now_add=True)),
- ('updated', models.DateTimeField(default=django.utils.timezone.now, auto_now=True)),
- ('enacted', models.DateTimeField(default=None, null=True, blank=True)),
- ('backend_status', models.CharField(default=b'Provisioning in progress', max_length=140)),
- ('deleted', models.BooleanField(default=False)),
- ('cap_read_data', models.BooleanField(default=True, help_text=b'VM can read Volume data')),
- ('cap_write_data', models.BooleanField(default=True, help_text=b'VM can write Volume data')),
- ('cap_host_data', models.BooleanField(default=True, help_text=b'VM can host Volume data')),
- ('owner_id', models.ForeignKey(verbose_name=b'user', to=settings.AUTH_USER_MODEL)),
- ('volume', models.ForeignKey(to='syndicate_storage.Volume')),
- ],
- options={
- },
- bases=(models.Model,),
- ),
- migrations.CreateModel(
- name='VolumeSlice',
- fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('created', models.DateTimeField(default=django.utils.timezone.now, auto_now_add=True)),
- ('updated', models.DateTimeField(default=django.utils.timezone.now, auto_now=True)),
- ('enacted', models.DateTimeField(default=None, null=True, blank=True)),
- ('backend_status', models.CharField(default=b'Provisioning in progress', max_length=140)),
- ('deleted', models.BooleanField(default=False)),
- ('cap_read_data', models.BooleanField(default=True, help_text=b'VM can read Volume data')),
- ('cap_write_data', models.BooleanField(default=True, help_text=b'VM can write Volume data')),
- ('cap_host_data', models.BooleanField(default=True, help_text=b'VM can host Volume data')),
- ('UG_portnum', models.PositiveIntegerField(help_text=b'User Gateway port. Any port above 1024 will work, but it must be available slice-wide.', verbose_name=b'UG port')),
- ('RG_portnum', models.PositiveIntegerField(help_text=b'Replica Gateway port. Any port above 1024 will work, but it must be available slice-wide.', verbose_name=b'RG port')),
- ('credentials_blob', models.TextField(help_text=b'Encrypted slice credentials, sealed with the slice secret.', null=True, blank=True)),
- ('slice_id', models.ForeignKey(verbose_name=b'Slice', to='core.Slice')),
- ('volume_id', models.ForeignKey(verbose_name=b'Volume', to='syndicate_storage.Volume')),
- ],
- options={
- },
- bases=(models.Model,),
- ),
- migrations.AddField(
- model_name='volume',
- name='slice_id',
- field=models.ManyToManyField(to='core.Slice', through='syndicate_storage.VolumeSlice'),
- preserve_default=True,
- ),
- ]
diff --git a/xos/syndicate_storage/models.py b/xos/syndicate_storage/models.py
deleted file mode 100644
index e2f98be..0000000
--- a/xos/syndicate_storage/models.py
+++ /dev/null
@@ -1,259 +0,0 @@
-from core.models import User,Site,Service,SingletonModel,PlCoreBase,Slice,SlicePrivilege
-import os
-from django.db import models
-from django.db.models import Q
-from django.forms.models import model_to_dict
-from django.core.exceptions import ValidationError, ObjectDoesNotExist
-
-# Create your models here.
-
-class SyndicateService(SingletonModel,Service):
- class Meta:
- app_label = "syndicate_storage"
- verbose_name = "Syndicate Service"
- verbose_name_plural = "Syndicate Service"
-
- def __unicode__(self): return u'Syndicate Service'
-
-
-class SyndicatePrincipal(PlCoreBase):
- class Meta:
- app_label = "syndicate_storage"
-
- # for now, this is a user email address
- principal_id = models.TextField(unique=True)
- public_key_pem = models.TextField()
- sealed_private_key = models.TextField()
-
- def __unicode__self(self): return "%s" % self.principal_id
-
-
-class Volume(PlCoreBase):
- class Meta:
- app_label = "syndicate_storage"
-
- name = models.CharField(max_length=64, help_text="Human-readable, searchable name of the Volume")
-
- owner_id = models.ForeignKey(User, verbose_name='Owner')
-
- description = models.TextField(null=True, blank=True,max_length=130, help_text="Human-readable description of what this Volume is used for.")
- blocksize = models.PositiveIntegerField(help_text="Number of bytes per block.")
- private = models.BooleanField(default=True, help_text="Indicates if the Volume is visible to users other than the Volume Owner and Syndicate Administrators.")
- archive = models.BooleanField(default=False, help_text="Indicates if this Volume is read-only, and only an Aquisition Gateway owned by the Volume owner (or Syndicate admin) can write to it.")
-
- cap_read_data = models.BooleanField(default=True, help_text="VM can read Volume data")
- cap_write_data = models.BooleanField(default=True, help_text="VM can write Volume data")
- cap_host_data = models.BooleanField(default=True, help_text="VM can host Volume data")
-
- slice_id = models.ManyToManyField(Slice, through="VolumeSlice")
-
- def __unicode__(self): return self.name
-
-
- @staticmethod
- def select_by_user(user):
- """
- Only return Volumes accessible by the user.
- Admin users can see everything.
- """
- if user.is_admin:
- qs = Volume.objects.all()
- else:
- qs = Volume.objects.filter( Q(owner_id=user) | Q(private=False) )
-
- return qs
-
-
-class VolumeAccessRight(PlCoreBase):
- class Meta:
- app_label = "syndicate_storage"
-
- owner_id = models.ForeignKey(User, verbose_name='user')
-
- volume = models.ForeignKey(Volume)
-
- cap_read_data = models.BooleanField(default=True, help_text="VM can read Volume data")
- cap_write_data = models.BooleanField(default=True, help_text="VM can write Volume data")
- cap_host_data = models.BooleanField(default=True, help_text="VM can host Volume data")
-
-
- def __unicode__(self): return "%s-%s" % (self.owner_id.email, self.volume.name)
-
-
-class ObserverSecretValue( models.TextField ):
- class Meta:
- app_label = "syndicate_storage"
-
- __metaclass__ = models.SubfieldBase
-
- MAGIC_PREFIX = "$SECRET$:"
-
- @classmethod
- def is_encrypted( cls, secret_str ):
- # all encrypted secrets start with MAGIC_PREFIX, which is NOT base64-encoded
- return secret_str.startswith( cls.MAGIC_PREFIX )
-
- @classmethod
- def unserialize( cls, serialized_ciphertext ):
- # strip prefix and return ciphertext
- return serialized_ciphertext[len(cls.MAGIC_PREFIX):]
-
- @classmethod
- def serialize( cls, ciphertext ):
- # prepend a magic prefix so we know it's encrypted
- return cls.MAGIC_PREFIX + ciphertext
-
- def to_python( self, secret_str ):
- """
- Decrypt the value with the Observer key
- """
-
- # is this in the clear?
- if not ObserverSecretValue.is_encrypted( secret_str ):
- # nothing to do
- return secret_str
-
- # otherwise, decrypt it
- from syndicate_observer import syndicatelib
-
- # get observer private key
- config = syndicatelib.get_config()
-
- try:
- observer_pkey_path = config.SYNDICATE_PRIVATE_KEY
- observer_pkey_pem = syndicatelib.get_private_key_pem( observer_pkey_path )
- except:
- raise syndicatelib.SyndicateObserverError( "Internal Syndicate Observer error: failed to load Observer private key" )
-
- # deserialize
- secret_str = ObserverSecretValue.unserialize( secret_str )
-
- # decrypt
- if secret_str is not None and len(secret_str) > 0:
-
- slice_secret = syndicatelib.decrypt_slice_secret( observer_pkey_pem, secret_str )
-
- if slice_secret is not None:
- return slice_secret
-
- else:
- raise syndicatelib.SyndicateObserverError( "Internal Syndicate Observer error: failed to decrypt slice secret value" )
- else:
- return None
-
-
- def pre_save( self, model_inst, add ):
- """
- Encrypt the value with the Observer key
- """
-
- from syndicate_observer import syndicatelib
-
- # get observer private key
- config = syndicatelib.get_config()
-
- try:
- observer_pkey_path = config.SYNDICATE_PRIVATE_KEY
- observer_pkey_pem = syndicatelib.get_private_key_pem( observer_pkey_path )
- except:
- raise syndicatelib.SyndicateObserverError( "Internal Syndicate Observer error: failed to load Observer private key" )
-
- slice_secret = getattr(model_inst, self.attname )
-
- if slice_secret is not None:
-
- # encrypt it
- sealed_slice_secret = syndicatelib.encrypt_slice_secret( observer_pkey_pem, slice_secret )
-
- return ObserverSecretValue.serialize( sealed_slice_secret )
-
- else:
- raise syndicatelib.SyndicateObserverError( "Internal Syndicate Observer error: No slice secret generated" )
-
-
-class SliceSecret(models.Model): # NOTE: not a PlCoreBase
- class Meta:
- app_label = "syndicate_storage"
-
- slice_id = models.ForeignKey(Slice)
- secret = ObserverSecretValue(blank=True, help_text="Shared secret between OpenCloud and this slice's Syndicate daemons.")
-
- def __unicode__(self): return self.slice_id.name
-
- @staticmethod
- def select_by_user(user):
- """
- Only return slice secrets for slices where this user has 'admin' role.
- Admin users can see everything.
- """
- if user.is_admin:
- qs = SliceSecret.objects.all()
- else:
- visible_slice_ids = [sp.slice.id for sp in SlicePrivilege.objects.filter(user=user,role__role='admin')]
- qs = SliceSecret.objects.filter(slice_id__id__in=visible_slice_ids)
-
- return qs
-
-
-class VolumeSlice(PlCoreBase):
- class Meta:
- app_label = "syndicate_storage"
-
- volume_id = models.ForeignKey(Volume, verbose_name="Volume")
- slice_id = models.ForeignKey(Slice, verbose_name="Slice")
-
- cap_read_data = models.BooleanField(default=True, help_text="VM can read Volume data")
- cap_write_data = models.BooleanField(default=True, help_text="VM can write Volume data")
- cap_host_data = models.BooleanField(default=True, help_text="VM can host Volume data")
-
- UG_portnum = models.PositiveIntegerField(help_text="User Gateway port. Any port above 1024 will work, but it must be available slice-wide.", verbose_name="UG port")
- RG_portnum = models.PositiveIntegerField(help_text="Replica Gateway port. Any port above 1024 will work, but it must be available slice-wide.", verbose_name="RG port")
-
- credentials_blob = models.TextField(null=True, blank=True, help_text="Encrypted slice credentials, sealed with the slice secret.")
-
- def __unicode__(self): return "%s-%s" % (self.volume_id.name, self.slice_id.name)
-
- def clean(self):
- """
- Verify that our fields are in order:
- * UG_portnum and RG_portnum have to be valid port numbers between 1025 and 65534
- * UG_portnum and RG_portnum cannot be changed once set.
- * UG_portnum and RG_portnum are unique
- """
-
- if self.UG_portnum == self.RG_portnum:
- raise ValidationError( "UG and RG ports must be unique" )
-
- if self.UG_portnum < 1025 or self.UG_portnum > 65534:
- raise ValidationError( "UG port number must be between 1025 and 65534" )
-
- if self.RG_portnum < 1025 or self.RG_portnum > 65534:
- raise ValidationError( "RG port number must be between 1025 and 65534" )
-
-
- def save(self, *args, **kw):
- """
- Make sure a SliceSecret exists for this slice
- """
-
- from syndicate_observer import syndicatelib
-
- # get observer private key
- config = syndicatelib.get_config()
-
- try:
- observer_pkey_path = config.SYNDICATE_PRIVATE_KEY
- observer_pkey_pem = syndicatelib.get_private_key_pem( observer_pkey_path )
- except:
- raise syndicatelib.SyndicateObserverError( "Internal Syndicate Observer error: failed to load Observer private key" )
-
- # get or create the slice secret
- slice_secret = syndicatelib.get_or_create_slice_secret( observer_pkey_pem, None, slice_fk=self.slice_id )
-
- if slice_secret is None:
- raise SyndicateObserverError( "Failed to get or create slice secret for %s" % self.slice_id.name )
-
- super(VolumeSlice, self).save(*args, **kw)
-
-
-
diff --git a/xos/templates/README.md b/xos/templates/README.md
new file mode 100644
index 0000000..af46be9
--- /dev/null
+++ b/xos/templates/README.md
@@ -0,0 +1,5 @@
+# DJANGO TEMPLATES
+
+These are the templates used by the Django Application to render the UI.
+
+More information are available in the [Django Documentation](https://docs.djangoproject.com/es/1.9/topics/templates/)
\ No newline at end of file
diff --git a/xos/templates/cord_admin/base.html b/xos/templates/cord_admin/base.html
deleted file mode 100644
index db5ccbf..0000000
--- a/xos/templates/cord_admin/base.html
+++ /dev/null
@@ -1,287 +0,0 @@
-{% load admin_static %}{% load suit_tags %}{% load url from future %}<!DOCTYPE html>
-<html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}>
-<head>
- <title>{% block title %} {%if title %} {{ title }} | {% endif %} CORD {% endblock %}</title>
- <link rel="stylesheet" type="text/css" href="{% block stylesheet %}{% endblock %}"/>
- <link rel="stylesheet" type="text/css" href="{% static 'suit/bootstrap/css/bootstrap.min.css' %}" media="all"/>
- <link rel="stylesheet" type="text/css" href="{% static 'suit/css/suit.css' %}" media="all">
- <link rel="stylesheet" type="text/css" href="{% static 'xos.css' %}" media="all">
- <link rel="stylesheet" type="text/css" href="{% static 'cord.css' %}" media="all">
- {% block extrastyle %}{% endblock %}
- {% if LANGUAGE_BIDI %}<link rel="stylesheet" type="text/css" href="{% block stylesheet_rtl %}{% static "admin/css/rtl.css" %}{% endblock %}"/>{% endif %}
- <script type="text/javascript">window.__admin_media_prefix__ = "{% filter escapejs %}{% static "admin/" %}{% endfilter %}";</script>
- <script src="{% static 'suit/js/jquery-1.9.1.min.js' %}"></script>
- <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
- <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
- <script type="text/javascript" src="{% static 'log4javascript-1.4.6/log4javascript.js' %}"></script>
- <script type="text/javascript" src="{% static 'uploadTextarea.js' %}"></script>
- <script type="text/javascript" src="{% static 'observer_status.js' %}"></script>
-
- <script type="text/javascript">var Suit = { $: $.noConflict() }; if (!$) $ = Suit.$; </script>
- {% if 'SHOW_REQUIRED_ASTERISK'|suit_conf %}
- <style type="text/css">.required:after { content: '*'; margin: 0 0 0 5px; position: absolute; color: #ccc;}</style>
- {% endif %}
- {% block extrahead %}{% endblock %}
- {% block blockbots %}
- <meta name="robots" content="NONE,NOARCHIVE"/>{% endblock %}
- <link rel="shortcut icon" href="{% static 'favicon.png' %}">
-</head>
-{% load i18n %}
-
-<body class="{% if is_popup %}popup {% endif %}{% block bodyclass %}{% endblock %}">
-
-<div id="dialog-placeholder">
-<!-- This is a placeholder for dialog boxes, like the observer calendar -->
-</div>
-
-<!-- Sticky footer wrap -->
-<div id="wrap">
-
- <!-- Container -->
- {% block container %}
- <div id="container">
-
- {% block logo %}
- <a href="{% url 'admin:index' %}"><h1 id="site-name"><img class="logo" height="70" width="259" src="{% static 'open-cloud-login-themed-light.png' %}"/></h1></a>
- {% endblock %}
- {% block header %}
- {% if not is_popup %}
- <!-- Header -->
- <div id="header" class="header">
-
- <div id="branding">
- {% block quick-search %}
- {% with 'SEARCH_URL'|suit_conf as search_url %}
- {% if search_url %}
- <form class="form-search nav-quick-search" autocomplete="off" action="{% if '/' in search_url %}{{ search_url }}{% else %}{% url search_url %}{% endif %}" method="GET">
- <i class="input-icon icon-search"></i>
- <input type="text" name="q" class="input-medium search-query" id="quick-search">
- <input type="submit" class="submit" value="">
- </form>
- {% endif %}
- {% endwith %}
- {% endblock %}
- </div>
-
- {% block header_time %}
- <div id="branding2">
- <!--<div class="header-content header-content-first">
- <div class="header-column icon">
- <i class="icon-time"></i>
- </div>
- <div class="header-column">
- <span class="date"> {% suit_date %}</span><br>
- <span class="time" id="clock">{% suit_time %}</span>
- </div>
- </div>-->
-
- {% endblock %}
-
- {% block header_content %}
- <!--<div class="header-content">
- <div class="header-column icon">
- <i class="icon-comment"></i>
- </div>
- <div class="header-column">
- <a href="" class="grey"><b>2</b> new messages</a>
- </div>
- </div>-->
- {% endblock %}
-
- {% if user.is_active and user.is_staff %}
- <div id="user-tools">
- {% trans 'Welcome,' %}
- <a href="http://{{ request.get_host}}/admin/core/user/{{user.id}}">{{user.email}}</a>
- <span id="observer-status"></span>
- <span class="user-links">
- {% block userlinks %}
- {% url 'django-admindocs-docroot' as docsroot %}
- {% if docsroot %}
- <a href="http://guide.xosproject.org/">{% trans 'Documentation' %}</a>
- <span class="separator">|</span>
- {% endif %}
- <a href="{% url 'admin:password_change' %}">{% trans 'Change password' %}</a>
- <span class="separator">|</span>
- <a href="{% url 'admin:logout' %}">{% trans 'Log out' %}</a>
- </span>
- {% endblock %}
- </div>
- {% endif %}
-
- {% block nav-global %}{% endblock %}
-
- </div>
- </div>
- {% endif %}
- <!-- END Header -->
- {% endblock %}
-
-
- <div class="suit-columns {{ is_popup|yesno:'one-column,two-columns' }}">
-
- {% block content-center %}
- <div id="suit-center" class="suit-column">
-
- {% if not is_popup %}
- {% block minidash %}
- <div id=openCloudTopPage>
- {% include "admin/newminidashboard.html" %}
- </div>
- {% endblock %}
-
- {% block breadcrumbs %}
- <ul class="breadcrumb">
- <li><a href="{% url 'admin:index' %}">{% trans 'Home' %}</a>
- {% if title %}
- <span class="divider">»</span>
- </li>
- <li class="active">
- {{ title }}
- {% endif %}
- </li>
- </ul>
- {% endblock %}
- {% endif %}
-
- {% block messages %}
- {% if messages %}
-
- {% for message in messages %}
- <div class="alert alert-{% firstof message.tags 'info' %}">
- <button class="close" data-dismiss="alert">×</button>
- <strong>
- {% if message.tags %}{{ message.tags|capfirst }}{% else %}
- Message{% endif %}!</strong>
- {{ message }}
- </div>
- {% endfor %}
- {% endif %}
- {% endblock messages %}
-
- <!-- Content -->
- <div id="content" class="{% block coltype %}colM{% endblock %} row-fluid">
- {% block pretitle %}{% endblock %}
- {% block content_title %}{% if title %}
- <h2 class="content-title">{{ title }}</h2>
- {% endif %}{% endblock %}
- {% block content %}
- {% block object-tools %}{% endblock %}
- {{ content }}
- {% endblock %}
- {% block sidebar_content %}
- {% block sidebar %}{% endblock %}
- {% endblock %}
- </div>
- <!-- END Content -->
- <span class="clearfix"></span>
- </div>
- {% endblock %}
-
-
- {% block content-left %}
- {% if not user.is_appuser %}
- {% if not is_popup %}
- <div id="suit-left" class="suit-column">
-
-
- {% include 'suit/menu.html' %}
-
- </div>
- {% endif %}
- {% endif %}
- {% endblock %}
-
- </div>
- </div>
- {% endblock %}
-
- {% if not is_popup %}
- <!-- Sticky footer push -->
- <div id="push"></div>
- {% endif %}
-
-</div>
-
-{% block footer %}
- {% if not is_popup %}
- <div id="footer" class="footer">
- <div class="content">
- <div class="tools">
- {% block footer_links %}
- <a href="http://djangosuit.com/support/" target="_blank" class="icon"><i class="icon-question-sign"></i>Support</a>
- <a href="http://djangosuit.com/pricing/" target="_blank" class="icon"><i class="icon-bookmark"></i>Licence</a>
- <a href="http://github.com/darklow/django-suit/issues" target="_blank" class="icon"><i class="icon-comment"></i>Report a bug</a>
- {% endblock %}
- </div>
-
- <div class="statusMsg" id="statusMsg">
- <!-- this is a placeholder for xoslib views to display status messages -->
- </div>
-
- <!-- <div class="copyright">
- {% block copyright %}
- Copyright © 2013 DjangoSuit.com<br>Developed by <a href="http://djangosuit.com" target="_blank">DjangoSuit.com</a>
- {% endblock %}
- </div> -->
-
- <div class="branding">{% block footer_branding %}
- CORD
- {% endblock %}</div>
- </div>
- </div>
- {% endif %}
-{% endblock %}
-
- <script src="{% static 'suit/bootstrap/js/bootstrap.min.js' %}"></script>
- <script src="{% static 'suit/js/suit.js' %}"></script>
- <script type="text/javascript" src="//www.google.com/jsapi"></script>
- <!-- src="{% static 'xos_graphs.js' %}" -->
-
- {% block extrajs %}{% endblock %}
-<script src="http://d3js.org/d3.v3.js"></script>
- <div class="modal fade hide" id="chartsModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
- <div class="modal-dialog">
- <div class="modal-content">
- <!--<div class="modal-header">
- <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
- <h4 class="modal-title" id="myModalLabel">OpenCloud</h4>
- </div>-->
- <div class="modal-body" style="overflow-y:hidden; overflow-x:hidden;">
- <div class="chartContainer">
- <div class="row">
- <div class=" padding">
- </div>
- </div>
-
- <div class="row">
- <div class=" heading">
- <p id="chartHeading" class="heading">OpenCloud</p>
- </div>
- </div>
- <div class="row">
- <div class="padding"></div>
- <div class="padding"></div>
- </div>
- <div class="row">
- <div id="graph" class="graph">
- </div>
- </div>
- </div>
- <div id="graph_work" style="display:none"></div>
- </div>
- <!--<div class="modal-footer">
- <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
- </div>-->
- </div><!-- /.modal-content -->
- </div><!-- /.modal-dialog -->
- </div><!-- /.modal -->
-
-
-<script>
-
-
-
-
-</script>
-</body>
-</html>
diff --git a/xos/templates/cord_admin/base_site.html b/xos/templates/cord_admin/base_site.html
deleted file mode 100644
index 80d39fe..0000000
--- a/xos/templates/cord_admin/base_site.html
+++ /dev/null
@@ -1,57 +0,0 @@
-{% extends "admin/base.html" %}
-{% load admin_static %}
-
-{# Additional <head> content here, some extra meta tags or favicon #}
-{#{% block extrahead %}#}
-{#{% endblock %}#}
-
-
-{# Additional CSS includes #}
-{# {% block extrastyle %} #}
-{# {% endblock %} #}
-
-
-{# Additional JS files in footer, right before </body> #}
-{#{% block extrajs %}#}
-{# <script type="text/javascript" src="{% static 'js/my_project.js' %}"></script>#}
-{#{% endblock %}#}
-
-
-{# Footer links (left side) #}
-{#{% block footer_links %}#}
-{# <a href="/docs/" class="icon"><i class="icon-question-sign"></i>Documentation</a>#}
-{#{% endblock %}#}
-
-{# Additional header content like notifications or language switcher #}
-{#{% block header_content %}#}
-{# {{ block.super }}#}
-{# <div class="header-content">#}
-{# <!-- First icon column -->#}
-{# <div class="header-column icon">#}
-{# <i class="icon-home"></i><br>#}
-{# <i class="icon-cog"></i>#}
-{# </div>#}
-{# <div class="header-column" style="margin-right: 20px">#}
-{# <a href="/" class="grey">Front-end</a><br>#}
-{# <a href="" class="grey">One more link</a>#}
-{# </div>#}
-{# <!-- Second icon column -->#}
-{# <div class="header-column icon">#}
-{# <i class="icon-comment"></i>#}
-{# </div>#}
-{# <div class="header-column">#}
-{# <a href="" class="grey">5 new messages</a>#}
-{# </div>#}
-{# </div>#}
-{#{% endblock %}#}
-
-{# Footer branding name (center) #}
-{% block footer_branding %}
-CORD
-{% endblock %}
-
-
-{# Footer copyright (right side) #}
-{% block copyright %}
-{# Copyright © 2013 Client<br>Developed by <a href="http://yoursite.com" target="_blank">YourName</a> #}
-{% endblock %}
diff --git a/xos/templates/cord_admin/dashboard_base.html b/xos/templates/cord_admin/dashboard_base.html
deleted file mode 100644
index bde87c2..0000000
--- a/xos/templates/cord_admin/dashboard_base.html
+++ /dev/null
@@ -1,92 +0,0 @@
-{% extends "admin/base.html" %}
-{% load admin_static %}
-
-{% block extrahead %}
-<link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">
-<link rel="stylesheet" type="text/css" href="{% static 'suit/css/suit.css' %}" media="all">
-<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables_themeroller.css">
-<link rel="stylesheet" type="text/css" href="{% static 'xos.css' %}" media="all">
-<link rel="stylesheet" type="text/css" href="{% static 'cord.css' %}" media="all">
-<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
-<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />
-<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
-
-
-<!-- no need to include jquery here as it's already included by base.html. Including it multiple times will break mtuity statistics. -->
-<!-- src="http://code.jquery.com/jquery-1.9.1.js" -->
-
-<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
-<script src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
-<script type="text/javascript" src="{% static 'log4javascript-1.4.6/log4javascript.js' %}"></script>
-<script src="{% static 'js/Leaflet.MakiMarkers.js' %}" > </script>
-
-<script>
- $(function() {
- $( "#hometabs" ).tabs({active: 0, //event: "mouseover"
- //collapsible: true
- });
- });
-
-var consoleAppender = new log4javascript.BrowserConsoleAppender();
-var patternLayout = new log4javascript.PatternLayout("%d{HH:mm:ss,SSS} %l{s:l} %-5p - %m{1}%n");
-consoleAppender.setLayout(patternLayout);
-//var log = log4javascript.getDefaultLogger();
-var log = log4javascript.getRootLogger();
-log.addAppender(consoleAppender);
-log.setLevel(log4javascript.Level.ERROR);
-
-function confirmDialog(title,msg) {
- var dialog = $('<div>'+msg+'</div>');
- var def = $.Deferred();
-
- $(dialog).dialog({
- resizable: false,
- title: title,
- autoOpen: true,
- modal: true,
- dialogClass: "dashboard-hpc-instance",
- buttons: {
- 'OK': function() {
- def.resolve();
- log.debug("Chose to add a instance");
- $( this ).dialog( "close" );
- },
- 'Cancel': function() {
- def.reject();
- $( this ).dialog( "close" );
- }
- },
- close: {
- }
- });
- return def.promise();
-}
-
-function errorDialog(title,msg) {
- var dialog = $('<div>'+msg+'</div>');
- var def = $.Deferred();
-
- $(dialog).dialog({
- resizable: false,
- title: title,
- autoOpen: true,
- modal: true,
- dialogClass: "dashboard-hpc-instance",
- buttons: {
- 'OK': function() {
- def.resolve();
- $( this ).dialog( "close" );
- },
- },
- close: {
- }
- });
- return def.promise();
-}
-
-</script>
-{% endblock %}
-
-{% block content %}
-dashboard goes here
-{% endblock %}
diff --git a/xos/templates/cord_admin/login.html b/xos/templates/cord_admin/login.html
deleted file mode 100644
index a586acf..0000000
--- a/xos/templates/cord_admin/login.html
+++ /dev/null
@@ -1,161 +0,0 @@
-{% extends "admin/base_site_login.html" %}
-{% load i18n admin_static %}
-
-{% block extrastyle %}{{ block.super }}
-<link rel="stylesheet" type="text/css" href="/static/suit/bootstrap/css/bootstrap.min.css" media="all"/>
-<link rel="stylesheet" type="text/css" href="{% static "xos.css" %}" />
-<link rel="stylesheet" type="text/css" href="{% static "cord.css" %}" />
-<script src="{% static 'suit/js/jquery-1.9.1.min.js' %}"></script>
-<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
-{% endblock %}
-
-
-{% block bodyclass %}login{% endblock %}
-
-{% block nav-global %}{% endblock %}
-
-{% block content_title %}{% endblock %}
-
-{% block breadcrumbs %}{% endblock %}
-
-{% block content %}
-{% if form.errors and not form.non_field_errors and not form.this_is_the_login_form.errors %}
-<p class="errornote">
-{% blocktrans count counter=form.errors.items|length %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
-</p>
-{% endif %}
-
-{% if form.non_field_errors or form.this_is_the_login_form.errors %}
-{% for error in form.non_field_errors %}
-<p class="errornote">
- {{ error }}
-</p>
-{% endfor %}
-{% for error in form.this_is_the_login_form.errors %}
-<p class="errornote">
- {{ error }}
-</p>
-{% endfor %}
-{% endif %}
-<div id="wrap">
-<div id="content-main">
-<h1><i class="icon-lock icon-white"></i> OpenCloud</h1>
-<form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %}
- <div class="form-row">
- {% if not form.this_is_the_login_form.errors %}{{ form.username.errors }}{% endif %}
- {{ form.username }}
- </div>
- <div class="form-row">
- {% if not form.this_is_the_login_form.errors %}{{ form.password.errors }}{% endif %}
- {{ form.password }}
- <input type="hidden" name="this_is_the_login_form" value="1" />
- <input type="hidden" name="old_next" value="{{ next }}" />
- <input type="hidden" name="next" value="/loggedin/?orig_next={{ next }}" />
- </div>
- <div class="submit-row">
- <input type="submit" class="btn btn-info" value="{% trans 'SIGN IN' %}" />
- </div>
- <div id="requestAccountLink">{% trans 'Request a new Account' %}</div>
-</form>
-
-<div id="request-account-form" title="Request an Account" style="display: none;">
- <form>
- <fieldset>
- <div class="request-form-row">
- <label for="request-first-name">First Name</label>
- <input type="text" name="request-first-name" id="request-first-name">
- </div>
- <div class="request-form-row">
- <label for="request-last-name">Last Name</label>
- <input type="text" name="request-last-name" id="request-last-name">
- </div>
- <div class="request-form-row">
- <label for="request-email">Email</label>
- <input type="text" name="request-email" id="request-email">
- </div>
- <div class="request-form-row">
- <label for="request-site-name">Site</label><br>
- <select id="request-site-name" name="request-site-name">
- <option>---------</option>
- {% for site in sites %}
- {% if site.allowNewUsers %}
- <option>{{ site.name }}</option>
- {% endif %}
- {% endfor %}
- </select>
- </div>
- <div class="submit-row">
- <input id ="request-signup" class="btn btn-info" value="SIGN UP">
- </div>
- </fieldset>
- </form>
-</div>
-</div>
-</div>
-
-
-<script type="text/javascript">
-$(function() {
- initRequest();
-});
-function initRequest(){
- $.ajax({
- url: '/tenantview',
- dataType: 'json',
- success: function (data) {
- var sites = data['sitesToBeRequested'];
- console.log(sites);
- for (site in sites){
- $("#request-site-name").append("<option>" + site + "</option>");
- }
- }
- });
-}
-$("#requestAccountLink").unbind().click(function(){
- $("#request-account-form").dialog({
- autoOpen: false,
- modal: true,
- dialogClass: "requestDialog",
- });
- $("#request-account-form").dialog("open");
-})
-$("#request-signup").unbind().click(function(){
- $.ajax({
- url: '/requestaccess/',
- dataType: 'json',
- data: {
- email: $("#request-email").val(),
- firstname: $("#request-first-name").val(),
- lastname: $("#request-last-name").val(),
- site: $("#request-site-name").val(),
- csrfmiddlewaretoken: "{{ csrf_token }}", // < here
- state: "inactive"
- },
- async: false,
- type: 'POST',
- success: function (response) {
- if (response && response.error) {
- if (response.error == "already_approved") {
- alert("Your request has already been proccessed and approved. We are sending you another email with a new temporary password");
- return;
- } else if (response.error == "already_pending") {
- alert("Your request is already pending and awaiting approval");
- return;
- } else if (response.error == "is_deleted") {
- alert("Your user record is in a deleted state. Please contact OpenCloud support");
- return;
- }
- }
- $("#request-account-form").dialog("close");
- alert("Your request has been submitted");
- },
- error:function (xhr, textStatus, thrownError){
- alert("Error:", textStatus + " " + xhr.responseText);
- }
- });
-})
-document.getElementById('id_username').focus()
-</script>
-</div>
-</div>
-{% endblock %}
diff --git a/xos/templates/registration/logged_out.html b/xos/templates/registration/logged_out.html
deleted file mode 100644
index 476a713..0000000
--- a/xos/templates/registration/logged_out.html
+++ /dev/null
@@ -1,12 +0,0 @@
-{% extends "admin/base_site.html" %}
-{% load i18n %}
-
-{% block breadcrumbs %}<div class="breadcrumbs"><a href="{% url 'admin:index' %}">{% trans 'Home' %}</a></div>{% endblock %}
-
-{% block content %}
-
-<p>{% trans "Thanks for spending some quality time with the Web site today." %}</p>
-
-<p><a href="{% url 'admin:loggedin' %}">{% trans 'Log in again' %}</a></p>
-
-{% endblock %}
diff --git a/xos/apigen/api.template.py b/xos/tools/apigen/api.template.py
similarity index 100%
rename from xos/apigen/api.template.py
rename to xos/tools/apigen/api.template.py
diff --git a/xos/apigen/deps.template.json b/xos/tools/apigen/deps.template.json
similarity index 100%
rename from xos/apigen/deps.template.json
rename to xos/tools/apigen/deps.template.json
diff --git a/xos/apigen/dot.template.dot b/xos/tools/apigen/dot.template.dot
similarity index 100%
rename from xos/apigen/dot.template.dot
rename to xos/tools/apigen/dot.template.dot
diff --git a/xos/tools/apigen/hpc-api.template.py b/xos/tools/apigen/hpc-api.template.py
new file mode 100644
index 0000000..56aa074
--- /dev/null
+++ b/xos/tools/apigen/hpc-api.template.py
@@ -0,0 +1,211 @@
+from rest_framework.decorators import api_view
+from rest_framework.response import Response
+from rest_framework.reverse import reverse
+from rest_framework import serializers
+from rest_framework import generics
+from rest_framework import status
+from rest_framework.generics import GenericAPIView
+from services.hpc.models import *
+from django.forms import widgets
+from rest_framework import filters
+from django.conf.urls import patterns, url
+from rest_framework.exceptions import PermissionDenied as RestFrameworkPermissionDenied
+from django.core.exceptions import PermissionDenied as DjangoPermissionDenied
+from apibase import XOSRetrieveUpdateDestroyAPIView, XOSListCreateAPIView, XOSNotAuthenticated
+
+if hasattr(serializers, "ReadOnlyField"):
+ # rest_framework 3.x
+ IdField = serializers.ReadOnlyField
+else:
+ # rest_framework 2.x
+ IdField = serializers.Field
+
+"""
+ Schema of the generator object:
+ all: Set of all Model objects
+ all_if(regex): Set of Model objects that match regex
+
+ Model object:
+ plural: English plural of object name
+ camel: CamelCase version of object name
+ refs: list of references to other Model objects
+ props: list of properties minus refs
+
+ TODO: Deal with subnets
+"""
+
+def get_hpc_REST_patterns():
+ return patterns('',
+ url(r'^hpcapi/$', hpc_api_root),
+ {% for object in generator.rest_models %}
+ url(r'hpcapi/{{ object.rest_name }}/$', {{ object.camel }}List.as_view(), name='{{ object.singular }}-list'),
+ url(r'hpcapi/{{ object.rest_name }}/(?P<pk>[a-zA-Z0-9\-]+)/$', {{ object.camel }}Detail.as_view(), name ='{{ object.singular }}-detail'),
+ {% endfor %}
+ )
+
+@api_view(['GET'])
+def hpc_api_root(request, format=None):
+ return Response({
+ {% for object in generator.rest_models %}'{{ object.plural }}': reverse('{{ object }}-list', request=request, format=format),
+ {% endfor %}
+ })
+
+# Based on serializers.py
+
+class XOSModelSerializer(serializers.ModelSerializer):
+ def save_object(self, obj, **kwargs):
+
+ """ rest_framework can't deal with ManyToMany relations that have a
+ through table. In xos, most of the through tables we have
+ use defaults or blank fields, so there's no reason why we shouldn't
+ be able to save these objects.
+
+ So, let's strip out these m2m relations, and deal with them ourself.
+ """
+ obj._complex_m2m_data={};
+ if getattr(obj, '_m2m_data', None):
+ for relatedObject in obj._meta.get_all_related_many_to_many_objects():
+ if (relatedObject.field.rel.through._meta.auto_created):
+ # These are non-trough ManyToMany relations and
+ # can be updated just fine
+ continue
+ fieldName = relatedObject.get_accessor_name()
+ if fieldName in obj._m2m_data.keys():
+ obj._complex_m2m_data[fieldName] = (relatedObject, obj._m2m_data[fieldName])
+ del obj._m2m_data[fieldName]
+
+ serializers.ModelSerializer.save_object(self, obj, **kwargs);
+
+ for (accessor, stuff) in obj._complex_m2m_data.items():
+ (relatedObject, data) = stuff
+ through = relatedObject.field.rel.through
+ local_fieldName = relatedObject.field.m2m_reverse_field_name()
+ remote_fieldName = relatedObject.field.m2m_field_name()
+
+ # get the current set of existing relations
+ existing = through.objects.filter(**{local_fieldName: obj});
+
+ data_ids = [item.id for item in data]
+ existing_ids = [getattr(item,remote_fieldName).id for item in existing]
+
+ #print "data_ids", data_ids
+ #print "existing_ids", existing_ids
+
+ # remove relations that are in 'existing' but not in 'data'
+ for item in list(existing):
+ if (getattr(item,remote_fieldName).id not in data_ids):
+ print "delete", getattr(item,remote_fieldName)
+ item.delete() #(purge=True)
+
+ # add relations that are in 'data' but not in 'existing'
+ for item in data:
+ if (item.id not in existing_ids):
+ #print "add", item
+ newModel = through(**{local_fieldName: obj, remote_fieldName: item})
+ newModel.save()
+
+{% for object in generator.rest_models %}
+
+class {{ object.camel }}Serializer(serializers.HyperlinkedModelSerializer):
+ id = IdField()
+ {% for ref in object.refs %}
+ {% if ref.multi %}
+ {{ ref.plural }} = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='{{ ref }}-detail')
+ {% else %}
+ {{ ref }} = serializers.HyperlinkedRelatedField(read_only=True, view_name='{{ ref }}-detail')
+ {% endif %}
+ {% endfor %}
+ humanReadableName = serializers.SerializerMethodField("getHumanReadableName")
+ validators = serializers.SerializerMethodField("getValidators")
+ def getHumanReadableName(self, obj):
+ return str(obj)
+ def getValidators(self, obj):
+ try:
+ return obj.getValidators()
+ except:
+ return None
+ class Meta:
+ model = {{ object.camel }}
+ fields = ('humanReadableName', 'validators', {% for prop in object.props %}'{{ prop }}',{% endfor %}{% for ref in object.refs %}{%if ref.multi %}'{{ ref.plural }}'{% else %}'{{ ref }}'{% endif %},{% endfor %})
+
+class {{ object.camel }}IdSerializer(XOSModelSerializer):
+ id = IdField()
+ {% for ref in object.refs %}
+ {% if ref.multi %}
+ {{ ref.plural }} = serializers.PrimaryKeyRelatedField(many=True, queryset = {{ ref.camel }}.objects.all())
+ {% else %}
+ {{ ref }} = serializers.PrimaryKeyRelatedField( queryset = {{ ref.camel }}.objects.all())
+ {% endif %}
+ {% endfor %}
+ humanReadableName = serializers.SerializerMethodField("getHumanReadableName")
+ validators = serializers.SerializerMethodField("getValidators")
+ def getHumanReadableName(self, obj):
+ return str(obj)
+ def getValidators(self, obj):
+ try:
+ return obj.getValidators()
+ except:
+ return None
+ class Meta:
+ model = {{ object.camel }}
+ fields = ('humanReadableName', 'validators', {% for prop in object.props %}'{{ prop }}',{% endfor %}{% for ref in object.refs %}{%if ref.multi %}'{{ ref.plural }}'{% else %}'{{ ref }}'{% endif %},{% endfor %})
+
+
+{% endfor %}
+
+serializerLookUp = {
+{% for object in generator.rest_models %}
+ {{ object.camel }}: {{ object.camel }}Serializer,
+{% endfor %}
+ None: None,
+ }
+
+# Based on core/views/*.py
+{% for object in generator.rest_models %}
+
+class {{ object.camel }}List(XOSListCreateAPIView):
+ queryset = {{ object.camel }}.objects.select_related().all()
+ serializer_class = {{ object.camel }}Serializer
+ id_serializer_class = {{ object.camel }}IdSerializer
+ filter_backends = (filters.DjangoFilterBackend,)
+ filter_fields = ({% for prop in object.props %}'{{ prop }}',{% endfor %}{% for ref in object.refs %}{%if ref.multi %}'{{ ref.plural }}'{% else %}'{{ ref }}'{% endif %},{% endfor %})
+
+ def get_serializer_class(self):
+ no_hyperlinks=False
+ if hasattr(self.request,"QUERY_PARAMS"):
+ no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False)
+ if (no_hyperlinks):
+ return self.id_serializer_class
+ else:
+ return self.serializer_class
+
+ def get_queryset(self):
+ if (not self.request.user.is_authenticated()):
+ raise XOSNotAuthenticated()
+ return {{ object.camel }}.select_by_user(self.request.user)
+
+
+class {{ object.camel }}Detail(XOSRetrieveUpdateDestroyAPIView):
+ queryset = {{ object.camel }}.objects.select_related().all()
+ serializer_class = {{ object.camel }}Serializer
+ id_serializer_class = {{ object.camel }}IdSerializer
+
+ def get_serializer_class(self):
+ no_hyperlinks=False
+ if hasattr(self.request,"QUERY_PARAMS"):
+ no_hyperlinks = self.request.QUERY_PARAMS.get('no_hyperlinks', False)
+ if (no_hyperlinks):
+ return self.id_serializer_class
+ else:
+ return self.serializer_class
+
+ def get_queryset(self):
+ if (not self.request.user.is_authenticated()):
+ raise XOSNotAuthenticated()
+ return {{ object.camel }}.select_by_user(self.request.user)
+
+ # update() is handled by XOSRetrieveUpdateDestroyAPIView
+
+ # destroy() is handled by XOSRetrieveUpdateDestroyAPIView
+
+{% endfor %}
diff --git a/xos/apigen/list.txt b/xos/tools/apigen/list.txt
similarity index 100%
rename from xos/apigen/list.txt
rename to xos/tools/apigen/list.txt
diff --git a/xos/tools/apigen/modelgen b/xos/tools/apigen/modelgen
new file mode 100644
index 0000000..72cce08
--- /dev/null
+++ b/xos/tools/apigen/modelgen
@@ -0,0 +1,214 @@
+#!/usr/bin/python
+
+import os
+import pdb
+import copy
+import sys
+import json
+import re
+from django.template import Context, Template
+from optparse import OptionParser
+
+# Django set up
+
+sys.path.append('.')
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+from django.db.models.fields.related import ForeignKey, ManyToManyField
+
+options = None
+
+def singular(foo, keys):
+ for k in keys:
+ if (foo==k+'es'):
+ return k
+ elif (foo==k+'s'):
+ return k
+ raise Exception('Plural to singular error for %s'%foo)
+
+g = globals()
+
+def enum_classes(apps):
+ model_classes = []
+ for app in apps:
+ app = app + ".models"
+ models_module = __import__(app)
+ for part in app.split(".")[1:]:
+ if hasattr(models_module, "PlCoreBase"):
+ break
+ models_module = getattr(models_module,part)
+
+ PlCoreBase = getattr(models_module,"PlCoreBase")
+
+ for classname in dir(models_module):
+ c = getattr(models_module, classname, None)
+ if type(c)==type(PlCoreBase) and c.__name__ not in options.blacklist:
+ model_classes.append(c)
+
+ return model_classes
+
+class GenObj(object):
+ def __str__(self):
+ return str(self.model.__name__.lower())
+
+ def __init__(self, m):
+ self.model = m
+ self.props = []
+ self.refs = []
+ self.plural_name = None
+
+ def plural(self):
+ if (self.plural_name):
+ return self.plural_name
+ else:
+ name = str(self)
+ if (name.endswith('s')):
+ return name+'es'
+ else:
+ return name+'s'
+
+ def singular(self):
+ return str(self)
+
+ def rest_name(self):
+ # These are things that either for historic reasons or due to incorrect naming,
+ # got called something different than the autogen thinks they should be
+ # called.
+ REST_FIXUP = {'controllernetworkses': 'controllernetworks',
+ 'controllerimageses': 'controllerimages',
+ 'controllersliceses': 'controllerslices',
+ 'controlleruserses': 'controllerusers',
+ 'sitedeploymentses': 'sitedeployments',
+ 'siteroles': 'site_roles',
+ 'sliceprivileges': 'slice_privileges',
+ 'sliceroles': 'slice_roles',
+ }
+ return REST_FIXUP.get(self.plural(), self.plural())
+
+ def camel(self):
+ name = str(self.model.__name__)
+ return name
+
+class Generator(dict):
+ def all(self):
+ return self.values()
+
+ def rest_models(self):
+ norest = [x.lower() for x in options.norest]
+ return [v for v in self.values() if not (str(v) in norest)]
+
+ def regex(self, r):
+ filtered = filter(lambda o:re.match(r,str(o)), self.values())
+ return filtered
+
+ def add_object(self, o):
+ obj = GenObj(o)
+ fields = o._meta.fields
+ self[str(obj).lower()]=obj
+
+ def compute_links(self):
+ for obj in self.values():
+ #if (str(obj)=='network'):
+ # pdb.set_trace()
+ fields = obj.model._meta.fields
+ for f in fields:
+ if (f and f.rel):
+ to_name = str(f.rel.to)
+ else:
+ to_name = None
+
+ if type(f)==ForeignKey and to_name and to_name in self.keys():
+ refobj = self[f.to_name]
+
+ if (str(obj)=='slice' and f.to_name=='networks'):
+ obj.refs.append(refobj)
+ related_name = f.related_query_name()
+ if (related_name!='+' and related_name.lower()!=str(obj).lower()):
+ cobj = copy.deepcopy(obj)
+ cobj.multi = True
+ cobj.plural_name = related_name
+ refobj.refs.append(cobj)
+ elif f.name.endswith("_ptr"):
+ # django inherited model, for example HPCService
+ # cause swagger and REST to break
+ pass
+ else:
+ obj.props.append(f.name)
+
+ m2m = obj.model._meta.many_to_many
+ for f in m2m:
+ try:
+ related_model_name = f.m2m_reverse_field_name()
+ except:
+ related_model_name = f.m2m_db_table().rsplit('_',1)[-1]
+
+ related_name = f.related_query_name()
+ if related_model_name in self.keys():
+ #print "XXX1", obj, f, related_name, related_model_name
+ refobj = self[related_model_name]
+ cobj = copy.deepcopy(obj)
+ cobj.multi=True
+ refobj.refs.append(cobj)
+
+ # deal with upgradeFrom_rel_+
+ if (related_name.endswith("+")):
+ continue
+
+ if (related_name!='+') and related_model_name in self: # and related_name.lower()!=str(obj).lower()):
+ refobj = self[related_model_name]
+ #print "XXX2", obj, f, related_name, related_model_name, refobj.plural_name
+ cobj = copy.deepcopy(refobj)
+ cobj.multi = True
+
+ obj.refs.append(cobj)
+
+
+
+
+def main():
+ global options
+ parser = OptionParser(usage="modelgen [options] <template_fn>", )
+
+ parser.add_option("-a", "--app", dest="apps",
+ help="list of applications to parse", metavar="APP", default=[], action="append")
+ parser.add_option("-b", "--blacklist", dest="blacklist",
+ help="add model name to blacklist", metavar="MODEL", default=["SingletonModel", "PlCoreBase"], action="append")
+ parser.add_option("-n", "--no-rest", dest="norest",
+ help="do not generate rest api for model", metavar="MODEL", default=["SingletonModel", "PlCoreBase"], action="append")
+
+ (options, args) = parser.parse_args(sys.argv[1:])
+
+ if not options.apps:
+ options.apps = ["core"]
+
+ if len(args)!=1:
+ print 'Usage: modelgen [options] <template_fn>'
+ exit(1)
+
+ template_name = os.path.abspath(args[0])
+
+ # try to make sure we're running from the right place
+ if (not os.path.exists("core")):
+ if (os.path.exists("../core")):
+ os.chdir("..")
+ elif (os.path.exists("../../core")):
+ os.chdir("../..")
+ else:
+ print >> sys.stderr, "Are you sure you're running modelgen from the root of an XOS installation"
+ sys.exit(-1)
+
+ generator = Generator()
+
+ models = enum_classes(options.apps)
+
+ for m in models:
+ generator.add_object(m)
+
+ generator.compute_links()
+ template_contents = open(template_name).read()
+ template = Template(template_contents)
+ context = Context({'generator':generator})
+ print template.render(context)
+
+
+if (__name__=='__main__'):
+ main()
diff --git a/xos/apigen/simple.template.txt b/xos/tools/apigen/simple.template.txt
similarity index 100%
rename from xos/apigen/simple.template.txt
rename to xos/tools/apigen/simple.template.txt
diff --git a/xos/apigen/style.template b/xos/tools/apigen/style.template
similarity index 100%
rename from xos/apigen/style.template
rename to xos/tools/apigen/style.template
diff --git a/xos/tools/chuckmove b/xos/tools/chuckmove
new file mode 100755
index 0000000..5a77876
--- /dev/null
+++ b/xos/tools/chuckmove
@@ -0,0 +1,82 @@
+#!/usr/bin/python
+
+from pyparsing import *
+from optparse import OptionParser
+import os
+from os.path import join,exists
+from shutil import copy
+
+usage = "usage: %prog --old <old namespace> --new <new namespace> <directory root>"
+
+parser = OptionParser(usage=usage)
+
+parser.add_option("-q", "--quiet",
+ action="store_false", dest="verbose",
+ help="be vewwy quiet (I'm hunting wabbits)")
+
+parser.add_option("-r", "--reuse",
+ action="store_false", dest="reuse",
+ help="Reuse .orig files. Dangerous!")
+
+parser.add_option("-o", "--old",
+ metavar="old", help="Old namespace")
+
+parser.add_option("-n", "--new",
+ default="new", help="New namespace")
+
+(options, args) = parser.parse_args()
+
+old_ns = options.old
+new_ns = options.new
+
+# grammar
+
+comment = '#' + SkipTo(lineEnd)
+
+module_ns = Word(alphanums + '-' + '_' + '.' + '*')
+old_module_ns = Combine(old_ns + Optional(Combine('.'+module_ns)))
+end_of_python_line = Or([lineEnd,comment])
+
+as_suffix = 'as' + module_ns
+
+import_pure = 'import' + old_module_ns
+import_pure_line = import_pure + Optional(as_suffix) + end_of_python_line
+
+import_from = 'from' + old_module_ns + 'import' + commaSeparatedList
+import_from_line = import_from + Optional(as_suffix) + end_of_python_line
+
+import_line = Or([import_pure_line, import_from_line])
+
+# Make a list of Python files to deal with
+
+try:
+ f = args[0]
+except IndexError:
+ print 'Specify a directory root'
+ exit(1)
+
+for root, dirs, files in os.walk(f):
+ for n in files:
+ if (n.endswith('.py')):
+ full_path = '/'.join([root,n])
+ orig_path = full_path + '.orig'
+ if (options.verbose):
+ print 'Working on %s:'%full_path
+ if (not os.path.exists(orig_path) or not options.reuse):
+ if (options.verbose):
+ print 'Copying %s->%s:'%(full_path,orig_path)
+ copy(full_path, orig_path)
+ f_contents = open(orig_path).read()
+ new_contents = []
+ for l in f_contents.splitlines():
+ try:
+ match = import_line.parseString(l)
+ l = l.replace(old_ns, new_ns)
+ except ParseException:
+ pass
+ new_contents.append(l)
+
+ new_file = '\n'.join(new_contents)
+ if (f_contents.endswith('\n')):
+ new_file+='\n'
+ open(full_path,'w').write(new_file)
diff --git a/xos/tools/chuckmove.README b/xos/tools/chuckmove.README
new file mode 100644
index 0000000..5039548
--- /dev/null
+++ b/xos/tools/chuckmove.README
@@ -0,0 +1,27 @@
+Hi,
+
+I've written a tool called 'chuckmove' for helping move Python modules around in a source tree. You use it as follows. Lets say you want to relocate a module to a different location in the tree, and also rename it. So for instance, x is to become y.z. The syntax you use is:
+
+chuckmove -o x -n y.z <root directory>
+
+Invoking this command makes the tool recursively descend into the root directory, make a backup copy of each file (adding the prefix '.orig') and rewrite the imports in it, so that "import x" gets turned into "import y.z"
+
+It recognizes Python grammar, so it works with all of these forms:
+
+from x import a
+from x.b import c
+import x.d.e.f as foo # Comments are also handled
+
+...with the nit that lines with syntax/grammatical errors are left as is.
+
+For example, for the observer/synchronizer changes, I just had to do the following:
+
+chuckmove -o observer -n synchronizers.base xos
+
+...and then to generate a patch with the changes:
+
+gendiff xos .orig
+
+It's checked into the xos repository under tools (with a README file!).
+
+Sapan
diff --git a/xos/tools/cleanup_unique.py b/xos/tools/cleanup_unique.py
index a637df1..4df82f4 100644
--- a/xos/tools/cleanup_unique.py
+++ b/xos/tools/cleanup_unique.py
@@ -4,8 +4,8 @@
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
import django
from core.models import *
-from hpc.models import *
-from cord.models import *
+from services.hpc.models import *
+from services.cord.models import *
django.setup()
for obj in ControllerNetwork.deleted_objects.all():
diff --git a/xos/tools/copy-opencloud.py b/xos/tools/copy-opencloud.py
deleted file mode 100644
index d71ebad..0000000
--- a/xos/tools/copy-opencloud.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#! /usr/bin/env python
-
-import base64
-import os
-import sys
-import subprocess
-import StringIO
-
-if len(sys.argv)<3:
- print >> sys.stderr, "syntax: copy-opencloud <srcfn> <desthost:destfn>"
- sys.exit(-1)
-
-srcfn = sys.argv[1]
-dest = sys.argv[2]
-
-if not ":" in dest:
- print >> sys.stderr, "malformed desthost:destfn"
- sys.exit(-1)
-
-(hostname,destfn) = dest.split(":",1)
-
-if destfn.endswith("/"):
- destfn = destfn + os.path.basename(srcfn)
-
-enctext = base64.b64encode(open(srcfn).read())
-#script = 'sudo bash -C "base64 -d -i > %s <<EOF\n%s\nEOF\n"' % (destfn, enctext)
-script = 'base64 -d -i > %s <<EOF\n%s\nEOF\n' % (destfn, enctext)
-
-
-file("/tmp/script","w").write(script)
-
-p = subprocess.Popen(["ssh", "-A", hostname], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
-print p.communicate(input=script)[0]
-
-
-"""
-SRCPATHNAME=$1
-DESTHOSTNAME=$2
-DESTPATHNAME=$3
-echo "base64 -d -i > $DESTPATHNAME <<EOF" > /tmp/ssh-up
-base64 $SRCPATHNAME >> /tmp/ssh-up
-echo "EOF" >> /tmp/ssh-up
-ssh -A $DESTHOSTNAME < /tmp/ssh-up
-"""
diff --git a/xos/tools/destroy-all-networks.sh b/xos/tools/destroy-all-networks.sh
new file mode 100755
index 0000000..f590683
--- /dev/null
+++ b/xos/tools/destroy-all-networks.sh
@@ -0,0 +1,34 @@
+#! /bin/bash
+
+# This will destroy all neutron networks, routers, and ports on Cloudlab.
+# It even destroys ext-net, flat-net, and tun-net
+# Don't use it unless you really want that to happen.
+
+source /root/setup/admin-openrc.sh
+
+echo "Lots of stuff will fail -- don't worry about it"
+
+PORTS=`neutron port-list | grep -v "+----" | grep -v "mac_address" | awk '{print $2}'`
+for PORT in $PORTS; do
+ echo "Deleting port $PORT"
+ neutron port-delete $PORT
+done
+
+NET_SUBNETS=`neutron net-list | grep -v "+----" | grep -v "subnets" | awk '{print $6}'`
+ROUTERS=`neutron router-list | grep -v "+----" | grep -v "external_gateway_info" | awk '{print $2}'`
+
+for ROUTER in $ROUTERS; do
+for SUBNET in $NET_SUBNETS; do
+neutron router-interface-delete $ROUTER $SUBNET
+done
+neutron router-delete $ROUTER
+done
+
+echo "Stuff below this line shouldn't fail"
+
+NETS=`neutron net-list | grep -v "+----" | grep -v "subnets" | awk '{print $2}'`
+for NET in $NETS; do
+ echo "Deleting network"
+ neutron net-delete $NET
+done
+
\ No newline at end of file
diff --git a/xos/tools/diff-opencloud.py b/xos/tools/diff-opencloud.py
deleted file mode 100644
index 4b6511c..0000000
--- a/xos/tools/diff-opencloud.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#! /usr/bin/env python
-
-import base64
-import os
-import sys
-import subprocess
-import StringIO
-
-if len(sys.argv)<3:
- print >> sys.stderr, "syntax: diff-opencloud <localfn> <remotehost:remotefn>"
- sys.exit(-1)
-
-srcfn = sys.argv[1]
-dest = sys.argv[2]
-
-if not ":" in dest:
- print >> sys.stderr, "malformed desthost:destfn"
- sys.exit(-1)
-
-(hostname,destfn) = dest.split(":",1)
-
-if destfn.endswith("/"):
- destfn = destfn + os.path.basename(srcfn)
-
-script = 'echo START; base64 %s' % destfn
-
-file("/tmp/script","w").write(script)
-
-p = subprocess.Popen(["ssh", "-A", hostname], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-(enctext,stderr) = p.communicate(input=script)
-
-if stderr:
- print >> sys.stderr, stderr
-
-if "No such file" in stderr:
- sys.exit(-1)
-
-enctext = enctext.split("START")[1]
-
-text = base64.b64decode(enctext)
-
-file("/tmp/diff-src","w").write(text)
-os.system("diff /tmp/diff-src %s" % srcfn)
-
-"""
-SRCPATHNAME=$1
-DESTHOSTNAME=$2
-DESTPATHNAME=$3
-echo "base64 -d -i > $DESTPATHNAME <<EOF" > /tmp/ssh-up
-base64 $SRCPATHNAME >> /tmp/ssh-up
-echo "EOF" >> /tmp/ssh-up
-ssh -A $DESTHOSTNAME < /tmp/ssh-up
-"""
diff --git a/xos/tools/dmdot b/xos/tools/dmdot
new file mode 100755
index 0000000..a57c0b1
--- /dev/null
+++ b/xos/tools/dmdot
@@ -0,0 +1,106 @@
+#!/usr/bin/python
+
+import os
+import pdb
+import sys
+import json
+
+sys.path.append('.')
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+
+from django.db.models.fields.related import ForeignKey
+
+# try to make sure we're running from the right place
+if (not os.path.exists("core")):
+ if (os.path.exists("../core")):
+ os.chdir("..")
+ else:
+ print >> sys.stderr, "Are you sure you're running dmdot from the root of an XOS installation"
+ sys.exit(-1)
+
+# defaults
+apps = ["core", "services.hpc", "services.cord", "services.requestrouter", "services.onos"]
+output = "-json"
+
+# syntax: dmdot [-json | -dot] [app_name]
+
+# poor man's argument parser
+for arg in sys.argv[1:]:
+ if arg.startswith("-"):
+ output = arg
+ else:
+ apps+= [arg]
+
+model_classes = []
+class_names = []
+lower_class_names = {}
+synonyms = {
+ 'user':'creator'
+}
+
+for app in apps:
+ app = app + ".models"
+ #models_module = imp.load_source(app, ".")
+ models_module = __import__(app)
+ for part in app.split(".")[1:]:
+ if hasattr(models_module, "PlCoreBase"):
+ break
+ models_module = getattr(models_module,part)
+
+ PlCoreBase = getattr(models_module,"PlCoreBase")
+
+ for classname in dir(models_module):
+ c = getattr(models_module, classname, None)
+ if type(c)==type(PlCoreBase):
+ model_classes.append(c)
+ class_names.append(c.__name__)
+ lower_class_names[c.__name__.lower()] = c
+ try:
+ synonym = synonyms[c.__name__.lower()]
+ lower_class_names[synonym] = c
+ except:
+ pass
+
+
+# django doesn't use the correct case in field.name.title() for objects that
+# have CamelCased class names. So, compare everything in lower case.
+
+if (output=='-dot'):
+ print "digraph plstack {";
+ for c in model_classes:
+ fields = c._meta.fields
+
+ for f in fields:
+ if type(f)==ForeignKey and f.name.lower().split('_') in lower_class_names:
+ linked_class = lower_class_names[f.name.lower()]
+ if ('backref' in f.name):
+ print '\t"%s"->"%s";'%(linked_class.__name__,c.__name__)
+ else:
+ print '\t"%s"->"%s";'%(c.__name__,linked_class.__name__)
+ print "}\n";
+elif (output=='-json'):
+ d = {}
+ for c in model_classes:
+ fields = c._meta.fields
+
+ for f in fields:
+ field_type = f.name.lower().split('_')[0]
+ if type(f)==ForeignKey and field_type in lower_class_names:
+ linked_class = lower_class_names[field_type]
+ if ('backref' in f.name.lower()):
+ a = linked_class.__name__
+ b = c.__name__
+ else:
+ b = linked_class.__name__
+ a = c.__name__
+
+ try:
+ if (b not in d[a]):
+ d[a].append(b)
+ except KeyError:
+ d[c.__name__]=[linked_class.__name__]
+ #d['ControllerNetwork'].append('SliceDeployments')
+ print json.dumps(d,indent=4)
+
+
diff --git a/xos/scripts/docker_setup_xos b/xos/tools/docker_setup_xos
similarity index 100%
rename from xos/scripts/docker_setup_xos
rename to xos/tools/docker_setup_xos
diff --git a/xos/tools/docker_start_xos b/xos/tools/docker_start_xos
new file mode 100755
index 0000000..3b82e71
--- /dev/null
+++ b/xos/tools/docker_start_xos
@@ -0,0 +1,7 @@
+#! /bin/bash
+
+bash /opt/xos/tools/docker_setup_xos
+
+cd /opt/xos
+PUBLIC_HOSTNAME="0.0.0.0"
+python manage.py runserver $PUBLIC_HOSTNAME:8000 --insecure
diff --git a/xos/tools/init-xos.py b/xos/tools/init-xos.py
deleted file mode 100644
index 433d444..0000000
--- a/xos/tools/init-xos.py
+++ /dev/null
@@ -1,64 +0,0 @@
-import os
-import sys
-sys.path.append("/opt/xos")
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-import django
-from core.models import *
-django.setup()
-
-# python ./manage.py sqlflush | python ./manage.py dbshell
-
-os.system("python /opt/xos/manage.py sqlflush | python /opt/xos/manage.py dbshell")
-
-ADMIN_USERNAME = "padmin@vicci.org"
-ADMIN_PASSWORD = "letmein"
-FLAVORS = ["m1.small", "m1.medium", "m1.large"]
-SITE_ROLES = ["admin", "pi", "tech"]
-SLICE_ROLES = ["admin", "access"]
-DEPLOYMENT_ROLES = ["admin"]
-
-d = Deployment(name="MyDeployment")
-d.save()
-
-s = Site(name="MySite", enabled=True, login_base="mysite", is_public=True, abbreviated_name="mysite")
-s.save()
-
-sd = SiteDeployment(site=s, deployment=d)
-sd.save();
-
-u = User(email = ADMIN_USERNAME, password=ADMIN_PASSWORD, is_admin=True, is_active=True, site=s, firstname="XOS",
- lastname="admin")
-u.save()
-
-for flavor_name in FLAVORS:
- f = Flavor(name=flavor_name, flavor=flavor_name)
- f.save()
- f.deployments.add(d)
- f.save()
-
-for site_role_name in SITE_ROLES:
- sr = SiteRole(role=site_role_name)
- sr.save()
-
-for slice_role_name in SLICE_ROLES:
- sr = SliceRole(role=slice_role_name)
- sr.save()
-
-for deployment_role_name in DEPLOYMENT_ROLES:
- dr = DeploymentRole(role=deployment_role_name)
- dr.save()
-
-DashboardView(name="xsh", url="template:xsh", enabled=True).save()
-DashboardView(name="Customize", url="template:customize", enabled=True).save()
-tv=DashboardView(name="Tenant", url="template:xosTenant", enabled=True)
-tv.save()
-tv.deployments.add(d)
-tv.save()
-DashboardView(name="Developer", url="template:xosDeveloper_datatables", enabled=True).save()
-
-ServiceClass(name="Best Effort", description="Best Effort").save()
-
-NetworkTemplate(name="Private", description="A private virtual network", visibility="private", translation="none", topology_kind="bigswitch", controller_kind="none").save()
-NetworkTemplate(name="Public shared IPv4", description="Connect a instance to the public network", visibility="private", translation="NAT", shared_network_name="nat-net", topology_kind="bigswitch", controller_kind="none").save()
-NetworkTemplate(name="Public dedicated IPv4", description="Connect a instance to the public network", visibility="public", translation="none", shared_network_name="ext-net", topology_kind="bigswitch", controller_kind="none").save()
-
diff --git a/xos/tools/purge.py b/xos/tools/purge.py
index 1df479d..023c2fe 100644
--- a/xos/tools/purge.py
+++ b/xos/tools/purge.py
@@ -4,8 +4,8 @@
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
import django
from core.models import *
-from hpc.models import *
-from cord.models import *
+from services.hpc.models import *
+from services.cord.models import *
django.setup()
def purge(cls):
diff --git a/xos/tools/xos-config.py b/xos/tools/xos-config.py
new file mode 100755
index 0000000..67ca4f6
--- /dev/null
+++ b/xos/tools/xos-config.py
@@ -0,0 +1,32 @@
+#!/usr/bin/env python
+import sys
+
+# add the parent directory to sys.path
+import os,sys,inspect
+currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
+parentdir = os.path.dirname(currentdir)
+sys.path.append(parentdir)
+
+from xos.config import Config
+
+def help():
+ print "syntax: %s get name [default]" % sys.argv[0]
+
+def main():
+ c = Config()
+
+ if len(sys.argv)<=1:
+ help()
+ return
+
+ if sys.argv[1] == "get":
+ if len(sys.argv)==4:
+ print getattr(c, sys.argv[2], sys.argv[3])
+ elif len(sys.argv)==3:
+ print getattr(c, sys.argv[2])
+ else:
+ help()
+ else:
+ help()
+
+main()
diff --git a/xos/tools/xos-manage b/xos/tools/xos-manage
new file mode 100755
index 0000000..4783bf5
--- /dev/null
+++ b/xos/tools/xos-manage
@@ -0,0 +1,237 @@
+#!/bin/bash
+
+if [ -z "$1" ]; then
+ echo usage: $0 "[initdb | createdb | dropdb | syncdb | runserver | resetdb | dumpdata]"
+ exit
+fi
+
+XOS_DIR=/opt/xos
+BACKUP_DIR=/opt/xos_backups
+DBNAME=xos
+
+DJANGO_17=`python -c "import django; from distutils.version import StrictVersion; print int(StrictVersion(django.get_version()) >= StrictVersion('1.7'))"`
+
+cd $XOS_DIR
+
+function is_ubuntu {
+ if ! which lsb_release &> /dev/null; then
+ # lsb_release is not installed
+ return 1
+ fi
+ if lsb_release -i | grep -i ubuntu &> /dev/null; then
+ return 0
+ fi
+ return 2
+}
+
+function ensure_postgres_running {
+ # "sudo -u postgres pg_ctl -D /var/lib/postgres/data status" doesn't work
+ # right on Vicci, so let's try to detect it by seeing if the port is
+ # being listened on
+
+ netstat -nl | grep -i ":5432 " > /dev/null
+ if [[ $? == 0 ]]; then
+ echo "Postgres is already running"
+ return
+ fi
+
+ # note that initdb isn't needed in Ubuntu distributions, and calling it
+ # will throw spurious error messages
+ if ! is_ubuntu; then
+ service postgresql initdb
+ fi
+ service postgresql start
+
+ netstat -nl | grep -i ":5432 " > /dev/null
+ if [[ $? != 0 ]]; then
+ # it's still not running...
+ # this is intended for Vicci where some D-Bus issue is
+ # preventing systemctl from working properly.
+ echo "Trying fallback mechanism to start Postgres"
+ sudo -u postgres initdb -D /var/lib/pgsql/data/
+ sudo -u postgres pg_ctl -D /var/lib/pgsql/data -l logfile start
+ fi
+
+}
+
+function wait_postgres {
+ sudo -u postgres psql -c '\q'
+ while [[ "$?" != "0" ]]; do
+ echo Waiting for postgres to start
+ sleep 1
+ sudo -u postgres psql -c '\q'
+ done
+}
+
+function db_exists {
+ sudo -u postgres psql $DBNAME -c '\q' 2>/dev/null
+ return $?
+}
+
+function createdb {
+ wait_postgres
+ echo "Creating XOS database..."
+ sudo -u postgres createdb $DBNAME
+}
+function dropdb {
+ echo "Dropping XOS database..."
+ sudo -u postgres dropdb $DBNAME
+}
+function syncdb {
+ echo "Syncing XOS services..."
+ python $XOS_DIR/manage.py syncdb --noinput
+ if [[ $DJANGO_17 ]]; then
+ echo "Loading initial data from fixture..."
+ python $XOS_DIR/manage.py --noobserver --nomodelpolicy loaddata $XOS_DIR/core/fixtures/core_initial_data.json
+ fi
+}
+function evolvedb {
+ echo "Evolving XOS services..."
+ python $XOS_DIR/manage.py evolve --hint --execute --noinput
+}
+function migratedb {
+ echo "Migrating XOS services..."
+ python $XOS_DIR/manage.py migrate
+}
+function stopserver {
+ echo "Stopping any running XOS Service(s)"
+ pkill -f "python.*runserver"
+}
+function runserver {
+ ensure_postgres_running
+ PUBLIC_HOSTNAME="0.0.0.0"
+ echo "Starting XOS Service on $PUBLIC_HOSTNAME:8000"
+ python manage.py runserver $PUBLIC_HOSTNAME:8000 --insecure&
+}
+
+function dumpdata {
+ mkdir -p $BACKUP_DIR
+ FN="$BACKUP_DIR/dumpdata-`date +%Y-%m-%d_%H:%M:%S`.json"
+ echo "Saving data to $FN"
+ python manage.py dumpdata core hpc syndicate_storage requestrouter -a --indent 4 > $FN
+ if [[ ! -f $FN ]]; then
+ echo "FAILED to create $FN"
+ exit
+ fi
+ SIZE=$(du -k "$FN" | cut -f 1)
+ if [[ $SIZE -lt 9 ]]; then
+ echo "Dumpdata was empty. Deleting and aborting"
+ rm $FN
+ exit
+ fi
+ rm -f $BACKUP_DIR/dumpdata-latest.json
+ ln -s $FN $BACKUP_DIR/dumpdata-latest.json
+}
+
+function genkeys {
+ mkdir -p public_keys
+ mkdir -p private_keys
+ echo "Generating keys"
+ keyczart create --location=private_keys --name="OpenCloud" --purpose=crypt --asymmetric=rsa
+ keyczart addkey --location=private_keys --status=primary --size=1024
+ keyczart pubkey --location=private_keys --destination=public_keys
+ if [[ ! -f public_keys/1 ]]; then
+ echo "FAILED to create keys"
+ exit
+ fi
+}
+
+function makemigrations {
+ rm -rf /opt/xos/*/migrations /opt/xos/services/*/migrations
+ python ./manage.py makemigrations core
+ python ./manage.py makemigrations hpc
+ python ./manage.py makemigrations requestrouter
+ python ./manage.py makemigrations syndicate_storage
+ python ./manage.py makemigrations cord
+ python ./manage.py makemigrations ceilometer
+ python ./manage.py makemigrations helloworldservice_complete
+ python ./manage.py makemigrations onos
+ #python ./manage.py makemigrations servcomp
+}
+
+function remigrate {
+ if db_exists; then
+ dropdb
+ fi
+ makemigrations
+}
+
+COMMAND=$1
+
+if [ "$COMMAND" = "initdb" ]; then
+ stopserver
+ ensure_postgres_running
+ createdb
+ syncdb
+fi
+if [ "$COMMAND" = "repairdb" ]; then
+ stopserver
+ ensure_postgres_running
+ dumpdata
+ # TODO: This is where we could run migration scripts to upgrade the
+ # dumped data to the new models.
+ mv $XOS_DIR/core/fixtures/core_initial_data.json $XOS_DIR/core/fixtures/core_initial_data.json-old
+ cp $BACKUP_DIR/dumpdata-latest.json $XOS_DIR/core/fixtures/core_initial_data.json
+ dropdb
+ createdb
+ syncdb
+fi
+if [ "$COMMAND" = "restoredb" ]; then
+ if [[ ! -f $BACKUP_DIR/dumpdata-latest.json ]]; then
+ echo There is no dumpdata to restore
+ exit
+ fi
+ stopserver
+ ensure_postgres_running
+ mv $XOS_DIR/core/fixtures/core_initial_data.json $XOS_DIR/core/fixtures/core_initial_data.json-old
+ cp $BACKUP_DIR/dumpdata-latest.json $XOS_DIR/core/fixtures/core_initial_data.json
+ dropdb
+ createdb
+ syncdb
+fi
+if [ "$COMMAND" = "evolvedb" -o "$COMMAND" = "migratedb" ]; then
+ stopserver
+ ensure_postgres_running
+ if [[ $DJANGO_17 ]]; then
+ migratedb
+ else
+ evolvedb
+ fi
+fi
+if [ "$COMMAND" = "resetdb" ]; then
+ stopserver
+ ensure_postgres_running
+ dropdb
+ createdb
+ syncdb
+fi
+if [ "$COMMAND" = "syncdb" ]; then
+ stopserver
+ syncdb
+fi
+if [ "$COMMAND" = "runserver" ]; then
+ stopserver
+ runserver
+fi
+if [ "$COMMAND" = "stopserver" ]; then
+ stopserver
+fi
+if [ "$COMMAND" = "dumpdata" ]; then
+ dumpdata
+fi
+if [ "$COMMAND" = "genkeys" ]; then
+ genkeys
+fi
+if [ "$COMMAND" = "generateapi" ]; then
+ python apigen/modelgen apigen/api.template.py > xos/xosapi.py
+fi
+if [ "$COMMAND" = "remigrate" ]; then
+ ensure_postgres_running
+ remigrate
+ createdb
+ syncdb
+fi
+if [ "$COMMAND" = "makemigrations" ]; then
+ makemigrations
+ syncdb
+fi
diff --git a/xos/tosca/resources/CORDSubscriber.py b/xos/tosca/resources/CORDSubscriber.py
index 45f5ee3..4097ca9 100644
--- a/xos/tosca/resources/CORDSubscriber.py
+++ b/xos/tosca/resources/CORDSubscriber.py
@@ -7,7 +7,7 @@
import pdb
from core.models import User
-from cord.models import CordSubscriberRoot
+from services.cord.models import CordSubscriberRoot
from xosresource import XOSResource
diff --git a/xos/tosca/resources/CORDUser.py b/xos/tosca/resources/CORDUser.py
index 78883f2..566e205 100644
--- a/xos/tosca/resources/CORDUser.py
+++ b/xos/tosca/resources/CORDUser.py
@@ -7,7 +7,7 @@
import pdb
from core.models import User
-from cord.models import CordSubscriberRoot
+from services.cord.models import CordSubscriberRoot
from xosresource import XOSResource
diff --git a/xos/tosca/resources/VOLTTenant.py b/xos/tosca/resources/VOLTTenant.py
index 20c4dfb..ae1692d 100644
--- a/xos/tosca/resources/VOLTTenant.py
+++ b/xos/tosca/resources/VOLTTenant.py
@@ -7,7 +7,7 @@
import pdb
from core.models import User
-from cord.models import VOLTTenant, VOLTService, CordSubscriberRoot, VOLT_KIND
+from services.cord.models import VOLTTenant, VOLTService, CordSubscriberRoot, VOLT_KIND
from xosresource import XOSResource
diff --git a/xos/tosca/resources/cdnprefix.py b/xos/tosca/resources/cdnprefix.py
index 8fbdd19..5faaca8 100644
--- a/xos/tosca/resources/cdnprefix.py
+++ b/xos/tosca/resources/cdnprefix.py
@@ -5,7 +5,7 @@
sys.path.append("/opt/tosca")
from translator.toscalib.tosca_template import ToscaTemplate
-from hpc.models import CDNPrefix, ContentProvider
+from services.hpc.models import CDNPrefix, ContentProvider
from xosresource import XOSResource
diff --git a/xos/tosca/resources/cdnservice.py b/xos/tosca/resources/cdnservice.py
index 4dbc561..4082938 100644
--- a/xos/tosca/resources/cdnservice.py
+++ b/xos/tosca/resources/cdnservice.py
@@ -5,7 +5,7 @@
sys.path.append("/opt/tosca")
from translator.toscalib.tosca_template import ToscaTemplate
-from hpc.models import HpcService
+from services.hpc.models import HpcService
from service import XOSService
diff --git a/xos/tosca/resources/ceilometertenant.py b/xos/tosca/resources/ceilometertenant.py
index 6599f33..cb3a623 100644
--- a/xos/tosca/resources/ceilometertenant.py
+++ b/xos/tosca/resources/ceilometertenant.py
@@ -6,7 +6,7 @@
from translator.toscalib.tosca_template import ToscaTemplate
import pdb
-from ceilometer.models import MonitoringChannel, CeilometerService
+from services.ceilometer.models import MonitoringChannel, CeilometerService
from xosresource import XOSResource
diff --git a/xos/tosca/resources/contentprovider.py b/xos/tosca/resources/contentprovider.py
index d63ea82..06ca02e 100644
--- a/xos/tosca/resources/contentprovider.py
+++ b/xos/tosca/resources/contentprovider.py
@@ -5,7 +5,7 @@
sys.path.append("/opt/tosca")
from translator.toscalib.tosca_template import ToscaTemplate
-from hpc.models import ContentProvider, ServiceProvider
+from services.hpc.models import ContentProvider, ServiceProvider
from xosresource import XOSResource
diff --git a/xos/tosca/resources/originserver.py b/xos/tosca/resources/originserver.py
index 0f50f04..196ce2e 100644
--- a/xos/tosca/resources/originserver.py
+++ b/xos/tosca/resources/originserver.py
@@ -5,7 +5,7 @@
sys.path.append("/opt/tosca")
from translator.toscalib.tosca_template import ToscaTemplate
-from hpc.models import OriginServer, ContentProvider
+from services.hpc.models import OriginServer, ContentProvider
from xosresource import XOSResource
diff --git a/xos/tosca/resources/serviceprovider.py b/xos/tosca/resources/serviceprovider.py
index 0ca401b..8faec6c 100644
--- a/xos/tosca/resources/serviceprovider.py
+++ b/xos/tosca/resources/serviceprovider.py
@@ -5,7 +5,7 @@
sys.path.append("/opt/tosca")
from translator.toscalib.tosca_template import ToscaTemplate
-from hpc.models import ServiceProvider, HpcService
+from services.hpc.models import ServiceProvider, HpcService
from xosresource import XOSResource
diff --git a/xos/tosca/resources/tenant.py b/xos/tosca/resources/tenant.py
index 831f6eb..21b8e88 100644
--- a/xos/tosca/resources/tenant.py
+++ b/xos/tosca/resources/tenant.py
@@ -7,7 +7,7 @@
from translator.toscalib.tosca_template import ToscaTemplate
import pdb
-from ceilometer.models import Tenant, Service
+from core.models import Tenant, Service
from xosresource import XOSResource
diff --git a/xos/tosca/resources/vbngservice.py b/xos/tosca/resources/vbngservice.py
index 1fc8d25..28d4a1d 100644
--- a/xos/tosca/resources/vbngservice.py
+++ b/xos/tosca/resources/vbngservice.py
@@ -5,7 +5,7 @@
sys.path.append("/opt/tosca")
from translator.toscalib.tosca_template import ToscaTemplate
-from cord.models import VBNGService
+from services.cord.models import VBNGService
from service import XOSService
diff --git a/xos/tosca/resources/vcpeservice.py b/xos/tosca/resources/vcpeservice.py
index 8df7231..abcdea9 100644
--- a/xos/tosca/resources/vcpeservice.py
+++ b/xos/tosca/resources/vcpeservice.py
@@ -5,7 +5,7 @@
sys.path.append("/opt/tosca")
from translator.toscalib.tosca_template import ToscaTemplate
-from cord.models import VCPEService
+from services.cord.models import VCPEService
from service import XOSService
diff --git a/xos/tosca/resources/xosresource.py b/xos/tosca/resources/xosresource.py
index 9c4f479..fa14380 100644
--- a/xos/tosca/resources/xosresource.py
+++ b/xos/tosca/resources/xosresource.py
@@ -62,7 +62,7 @@
def get_property_default(self, name, default=None):
props = self.nodetemplate.get_properties()
- if props and name in props.keys():
+ if props and name in props.keys():
return props[name].value
return default
diff --git a/xos/tosca/samples/helloworld-chain.yaml b/xos/tosca/samples/helloworld-chain.yaml
index 8959f7f..2b5cd53 100644
--- a/xos/tosca/samples/helloworld-chain.yaml
+++ b/xos/tosca/samples/helloworld-chain.yaml
@@ -20,7 +20,7 @@
type: tosca.nodes.Image
service_vcpe:
- type: tosca.nodes.Service
+ type: tosca.nodes.VCPEService
requirements:
- helloworld_tenant:
node: service_helloworld
@@ -37,7 +37,7 @@
properties:
kind: helloworldservice_complete
service_specific_attribute: "{\"display_message\": \"Hello World from Tosca\"}"
- model: helloworldservice_complete.models.HelloWorldTenantComplete
+ model: services.helloworldservice_complete.models.HelloWorldTenantComplete
requirements:
- provider_service:
node: service_helloworld
diff --git a/xos/tosca/samples/vtn.yaml b/xos/tosca/samples/vtn.yaml
index 5ce4670..4683b70 100644
--- a/xos/tosca/samples/vtn.yaml
+++ b/xos/tosca/samples/vtn.yaml
@@ -24,7 +24,7 @@
node: service_ONOS_VTN
relationship: tosca.relationships.TenantOfService
properties:
- dependencies: org.onosproject.openstackswitching, org.onosproject.cordvtn
+ dependencies: org.onosproject.openflow, org.onosproject.dhcp, org.onosproject.openstackswitching, org.onosproject.cordvtn
rest_onos/v1/network/configuration/: { get_artifact: [ SELF, vtn_network_cfg_json, LOCAL_FILE ] }
artifacts:
vtn_network_cfg_json: /root/setup/vtn-network-cfg.json
@@ -56,7 +56,7 @@
node: docker-onos
relationship: tosca.relationships.UsesImage
properties:
- network: bridged
+ network: host
default_isolation: container
# Virtual machines
diff --git a/xos/tosca/tests/basetest.py b/xos/tosca/tests/basetest.py
index d9701d7..7dda96f 100644
--- a/xos/tosca/tests/basetest.py
+++ b/xos/tosca/tests/basetest.py
@@ -1,19 +1,19 @@
import os
import random
import string
-import sys
-
-# add the parent parent directory to sys.path
-# XXX this is very hackish :(
-import os,sys,inspect
-currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
-parentdir = os.path.dirname(currentdir)
-sys.path.append(parentdir)
-parentparentdir = os.path.dirname(parentdir)
-sys.path.append(parentparentdir)
-
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-import django
+import sys
+
+# add the parent parent directory to sys.path
+# XXX this is very hackish :(
+import os,sys,inspect
+currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
+parentdir = os.path.dirname(currentdir)
+sys.path.append(parentdir)
+parentparentdir = os.path.dirname(parentdir)
+sys.path.append(parentparentdir)
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
+import django
django.setup()
from tosca.engine import XOSTosca
diff --git a/xos/tosca/tests/observerUserTest.py b/xos/tosca/tests/observerUserTest.py
index 44b47d3..a6b5897 100644
--- a/xos/tosca/tests/observerUserTest.py
+++ b/xos/tosca/tests/observerUserTest.py
@@ -48,14 +48,14 @@
node: %s
relationship: tosca.relationships.UsesController
johndoe@foo.bar:
- type: tosca.nodes.User
- properties:
- password: letmein
- firstname: john
- lastname: doe
- requirements:
- - site:
- node: testsite
+ type: tosca.nodes.User
+ properties:
+ password: letmein
+ firstname: john
+ lastname: doe
+ requirements:
+ - site:
+ node: testsite
relationship: tosca.relationships.MemberOfSite
""" % (self.get_usable_deployment(), self.get_usable_controller()))
diff --git a/xos/tosca/tests/observertest.py b/xos/tosca/tests/observertest.py
index 1ec8797..4c8d5df 100644
--- a/xos/tosca/tests/observertest.py
+++ b/xos/tosca/tests/observertest.py
@@ -5,10 +5,10 @@
import subprocess
import sys
-from observer.event_loop import XOSObserver
-from model_policy import run_policy_once
+from synchronizers.base.event_loop import XOSObserver
+from synchronizers.model_policy import run_policy_once
from xos.config import set_override
-from util.logger import Logger, observer_logger
+from xos.logger import Logger, observer_logger
class BaseObserverToscaTest(BaseToscaTest):
hide_observer_output = True
diff --git a/xos/urlfilter/migrations/0001_initial.py b/xos/urlfilter/migrations/0001_initial.py
deleted file mode 100644
index da06233..0000000
--- a/xos/urlfilter/migrations/0001_initial.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
-
-from django.db import models, migrations
-
-
-class Migration(migrations.Migration):
-
- dependencies = [
- ('core', '0005_network_ports'),
- ]
-
- operations = [
- migrations.CreateModel(
- name='UrlFilterService',
- fields=[
- ('service_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='core.Service')),
- ],
- options={
- 'verbose_name': 'URL Filter Service',
- },
- bases=('core.service', models.Model),
- ),
- ]
diff --git a/xos/urlfilter/migrations/__init__.py b/xos/urlfilter/migrations/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/xos/urlfilter/migrations/__init__.py
+++ /dev/null
diff --git a/xos/util/__init__.py b/xos/util/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/xos/util/__init__.py
+++ /dev/null
diff --git a/xos/util/glob.py b/xos/util/glob.py
deleted file mode 100644
index 833ce35..0000000
--- a/xos/util/glob.py
+++ /dev/null
@@ -1,8 +0,0 @@
-import os, fnmatch
-
-def recursive_glob(treeroot, pattern):
- results = []
- for base, dirs, files in os.walk(treeroot):
- goodfiles = fnmatch.filter(files, pattern)
- results.extend(os.path.join(base, f) for f in goodfiles)
- return results
diff --git a/xos/util/request.py b/xos/util/request.py
deleted file mode 100644
index 3769b19..0000000
--- a/xos/util/request.py
+++ /dev/null
@@ -1,14 +0,0 @@
-import ast
-from django.http.request import QueryDict
-
-def parse_request(request):
- d = {}
- if isinstance(request, unicode):
- d = ast.literal_eval(request)
- elif isinstance(request, QueryDict):
- for (k,v) in request.items():
- d[k] = ast.literal_eval(v)
- elif isinstance(request, dict):
- d = request
-
- return d
diff --git a/xos/xos-config.py b/xos/xos-config.py
deleted file mode 100755
index 66f48f8..0000000
--- a/xos/xos-config.py
+++ /dev/null
@@ -1,25 +0,0 @@
-#!/usr/bin/env python
-import sys
-from xos.config import Config
-
-def help():
- print "syntax: %s get name [default]" % sys.argv[0]
-
-def main():
- c = Config()
-
- if len(sys.argv)<=1:
- help()
- return
-
- if sys.argv[1] == "get":
- if len(sys.argv)==4:
- print getattr(c, sys.argv[2], sys.argv[3])
- elif len(sys.argv)==3:
- print getattr(c, sys.argv[2])
- else:
- help()
- else:
- help()
-
-main()
diff --git a/xos/xos-observer.py b/xos/xos-observer.py
deleted file mode 100644
index b85b29b..0000000
--- a/xos/xos-observer.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/env python
-import os
-import argparse
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
-from observer.backend import Backend
-from xos.config import Config, DEFAULT_CONFIG_FN
-
-try:
- from django import setup as django_setup # django 1.7
-except:
- django_setup = False
-
-config = Config()
-
-# after http://www.erlenstar.demon.co.uk/unix/faq_2.html
-def daemon():
- """Daemonize the current process."""
- if os.fork() != 0: os._exit(0)
- os.setsid()
- if os.fork() != 0: os._exit(0)
- os.umask(0)
- devnull = os.open(os.devnull, os.O_RDWR)
- os.dup2(devnull, 0)
- # xxx fixme - this is just to make sure that nothing gets stupidly lost - should use devnull
- logdir=os.path.dirname(config.observer_logfile)
- # when installed in standalone we might not have httpd installed
- if not os.path.isdir(logdir): os.mkdir(logdir)
- crashlog = os.open('%s'%config.observer_logfile, os.O_RDWR | os.O_APPEND | os.O_CREAT, 0644)
- os.dup2(crashlog, 1)
- os.dup2(crashlog, 2)
-
- if hasattr(config, "observer_pidfile"):
- pidfile = config.get("observer_pidfile")
- else:
- pidfile = "/var/run/xosobserver.pid"
- try:
- file(pidfile,"w").write(str(os.getpid()))
- except:
- print "failed to create pidfile %s" % pidfile
-
-def main():
- # Generate command line parser
- parser = argparse.ArgumentParser(usage='%(prog)s [options]')
- parser.add_argument('-d', '--daemon', dest='daemon', action='store_true', default=False,
- help='Run as daemon.')
- # smbaker: util/config.py parses sys.argv[] directly to get config file name; include the option here to avoid
- # throwing unrecognized argument exceptions
- parser.add_argument('-C', '--config', dest='config_file', action='store', default=DEFAULT_CONFIG_FN,
- help='Name of config file.')
- args = parser.parse_args()
-
- if args.daemon: daemon()
-
- if django_setup: # 1.7
- django_setup()
-
- backend = Backend()
- backend.run()
-
-if __name__ == '__main__':
-
- main()
diff --git a/xos/xos/admin_customize/README.md b/xos/xos/admin_customize/README.md
new file mode 100644
index 0000000..ecc4520
--- /dev/null
+++ b/xos/xos/admin_customize/README.md
@@ -0,0 +1 @@
+admin_customize contains django UI elements (such as templatetags) that are common to all django apps within XOS.
diff --git a/xos/admin_customize/__init__.py b/xos/xos/admin_customize/__init__.py
similarity index 100%
rename from xos/admin_customize/__init__.py
rename to xos/xos/admin_customize/__init__.py
diff --git a/xos/admin_customize/templatetags/__init__.py b/xos/xos/admin_customize/templatetags/__init__.py
similarity index 100%
rename from xos/admin_customize/templatetags/__init__.py
rename to xos/xos/admin_customize/templatetags/__init__.py
diff --git a/xos/admin_customize/templatetags/admin_modify.py b/xos/xos/admin_customize/templatetags/admin_modify.py
similarity index 100%
rename from xos/admin_customize/templatetags/admin_modify.py
rename to xos/xos/admin_customize/templatetags/admin_modify.py
diff --git a/xos/xos/config.py b/xos/xos/config.py
index 7a64de9..8ae7816 100644
--- a/xos/xos/config.py
+++ b/xos/xos/config.py
@@ -6,7 +6,7 @@
import tempfile
import codecs
from StringIO import StringIO
-from util.xml import Xml
+from xml_util import Xml
default_config = \
"""
@@ -82,6 +82,7 @@
try:
if os.path.isdir(filename):
config_list = list(reversed(os.listdir(filename)))
+ config_list.remove('README.md')
config_list = [os.path.join(filename, s) for s in config_list]
self.config.read(config_list)
else:
diff --git a/xos/xos/hpcapi.py b/xos/xos/hpcapi.py
index 9de4989..28bdd7b 100644
--- a/xos/xos/hpcapi.py
+++ b/xos/xos/hpcapi.py
@@ -5,7 +5,7 @@
from rest_framework import generics
from rest_framework import status
from rest_framework.generics import GenericAPIView
-from hpc.models import *
+from services.hpc.models import *
from django.forms import widgets
from rest_framework import filters
from django.conf.urls import patterns, url
diff --git a/xos/util/logger.py b/xos/xos/logger.py
similarity index 100%
rename from xos/util/logger.py
rename to xos/xos/logger.py
diff --git a/xos/xos/settings.py b/xos/xos/settings.py
index e276954..3792224 100644
--- a/xos/xos/settings.py
+++ b/xos/xos/settings.py
@@ -166,22 +166,20 @@
# Uncomment the next line to enable the admin:
# 'suit',
'xos.apps.MyDjangoSuitConfig',
- 'admin_customize',
+ 'xos.admin_customize',
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
'rest_framework',
'django_extensions',
'core',
- 'hpc',
- 'cord',
- 'helloworldservice_complete',
+ 'services.hpc',
+ 'services.cord',
+ 'services.helloworldservice_complete',
'services.onos',
- 'ceilometer',
- 'requestrouter',
-# 'urlfilter',
-# 'servcomp',
- 'syndicate_storage',
+ 'services.ceilometer',
+ 'services.requestrouter',
+ 'services.syndicate_storage',
'geoposition',
'rest_framework_swagger',
)
diff --git a/xos/xos/urls.py b/xos/xos/urls.py
index 3660282..4c3f07d 100644
--- a/xos/xos/urls.py
+++ b/xos/xos/urls.py
@@ -8,8 +8,8 @@
from hpcapi import *
from core.views.legacyapi import LegacyXMLRPC
-from core.views.services import ServiceGridView, ServiceGraphView
-from helloworld.view import *
+from core.views.serviceGraph import ServiceGridView, ServiceGraphView
+from services.helloworld.view import *
#from core.views.analytics import AnalyticsAjaxView
from core.models import *
from rest_framework import generics
@@ -27,7 +27,6 @@
urlpatterns = patterns('',
# Examples:
- url(r'^stats', 'core.views.stats.Stats', name='stats'),
url(r'^observer', 'core.views.observer.Observer', name='observer'),
url(r'^helloworld', HelloWorldView.as_view(), name='helloWorld'),
url(r'^serviceGrid', ServiceGridView.as_view(), name='serviceGrid'),
diff --git a/xos/util/xml.py b/xos/xos/xml_util.py
similarity index 100%
rename from xos/util/xml.py
rename to xos/xos/xml_util.py
diff --git a/xos/xos_configuration/README.md b/xos/xos_configuration/README.md
new file mode 100644
index 0000000..044d7e0
--- /dev/null
+++ b/xos/xos_configuration/README.md
@@ -0,0 +1,99 @@
+# Managing Configurations
+
+XOS comes with several pre-configured envirnments. The main available configurations are:
+
+- Frontend Only
+- - CORD
+Every configurations come with different settings and different features, from GUI elements to Services.
+
+__NOTE: in this folder files should not be added. They will broke the configuration system.__
+
+## Basic configuration
+
+A common configuration file is saved in `xos/configurations/common/xos_common_config`. In this file are stored all the common configurations for XOS.
+
+This is the base config:
+``
+[plc]
+name=plc
+deployment=plc
+
+[db]
+name=xos
+user=postgres
+password=password
+host=localhost
+port=5432
+
+[api]
+host=localhost
+port=8000
+ssl_key=None
+ssl_cert=None
+ca_ssl_cert=None
+ratelimit_enabled=0
+omf_enabled=0
+mail_support_address=support@localhost
+nova_enabled=True
+logfile=/var/log/xos.log
+
+[nova]
+admin_user=admin@domain.com
+admin_password=admin
+admin_tenant=admin
+url=http://localhost:5000/v2.0/
+default_image=None
+default_flavor=m1.small
+default_security_group=default
+ca_ssl_cert=/etc/ssl/certs/ca-certificates.crt
+
+[observer]
+pretend=False
+backoff_disabled=False
+images_directory=/opt/xos/images
+dependency_graph=/opt/xos/model-deps
+logfile=/var/log/xos_backend.log
+
+[gui]
+disable_minidashboard=True
+branding_name=Open Cloud
+#branding_css= #no branding css is provided by default
+branding_icon=/static/logo.png
+
+``
+
+## Extending configuration
+
+### How it works
+
+In some environment some changes to the configuration are needed, to achieve this XOS reads configurations from a `xos/xos_configuration`.
+
+All the configuration files in this folder will be parsed with [ConfigParser](https://docs.python.org/2/library/configparser.html).
+
+### Exetending a configuration
+
+_An example is available in the CORD config_
+
+These are the basic step to extend a configuration.
+_From now we'll use `myConf` as placeholder for the current configuration._
+
+**Local Config**
+
+- In your configuration create a new config file named: `xos_<myConf>_config`
+Sample local config:
+``
+[gui]
+branding_name=A BRAND NAME
+branding_icon=/static/my_logo.png
+``
+
+_The file above will change the displayed brand name and the logo in the UI_
+
+**Makefile Changes**
+- Clean the configuration folder: `rm ../../xos_configuration/*`
+- - Add the common config: `cp ../common/xos_common_config ../../xos_configuration/`
+- - Add the local config: `cp ./xos_<myConf>_config ../../xos_configuration/`
+_IMPORTANT: this instructions have to be executed before `docker build`_
+
+
+
diff --git a/xos/xos_configuration/xos_common_config b/xos/xos_configuration/xos_common_config
index b86d618..df30b54 100755
--- a/xos/xos_configuration/xos_common_config
+++ b/xos/xos_configuration/xos_common_config
@@ -40,6 +40,5 @@
[gui]
disable_minidashboard=True
-#branding_name=CORD
-#branding_css=/static/cord.css
-#branding_icon=/static/onos-logo.png
+branding_name=Open Cloud
+branding_icon=/static/logo.png