text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />

/**
 * This class is used as a set of methods that are applied to the prototype of a
 * Model to decorate it with a Node API. This means that models used in conjunction with a tree
 * will have all of the tree related methods available on the model. In general this class will
 * not be used directly by the developer. This class also creates extra fields on the model if
 * they do not exist, to help maintain the tree state and UI. These fields are documented as
 * config options.
 */
Ext.define('Ext.data.NodeInterface', {
    requires: ['Ext.data.Field'],

    /**
     * @cfg {String} parentId
     * ID of parent node.
     */

    /**
     * @cfg {Number} index
     * The position of the node inside its parent. When parent has 4 children and the node is third amongst them,
     * index will be 2.
     */

    /**
     * @cfg {Number} depth
     * The number of parents this node has. A root node has depth 0, a child of it depth 1, and so on...
     */

    /**
     * @cfg {Boolean} [expanded=false]
     * True if the node is expanded.
     */

    /**
     * @cfg {Boolean} [expandable=false]
     * Set to true to allow for expanding/collapsing of this node.
     */

    /**
     * @cfg {Boolean} [checked=null]
     * Set to true or false to show a checkbox alongside this node.
     */

    /**
     * @cfg {Boolean} [leaf=false]
     * Set to true to indicate that this child can have no children. The expand icon/arrow will then not be
     * rendered for this node.
     */

    /**
     * @cfg {String} cls
     * CSS class to apply for this node.
     */

    /**
     * @cfg {String} iconCls
     * CSS class to apply for this node's icon.
     */

    /**
     * @cfg {String} icon
     * URL for this node's icon.
     */

    /**
     * @cfg {Boolean} root
     * True if this is the root node.
     */

    /**
     * @cfg {Boolean} isLast
     * True if this is the last node.
     */

    /**
     * @cfg {Boolean} isFirst
     * True if this is the first node.
     */

    /**
     * @cfg {Boolean} [allowDrop=true]
     * Set to false to deny dropping on this node.
     */

    /**
     * @cfg {Boolean} [allowDrag=true]
     * Set to false to deny dragging of this node.
     */

    /**
     * @cfg {Boolean} [loaded=false]
     * True if the node has finished loading.
     */

    /**
     * @cfg {Boolean} [loading=false]
     * True if the node is currently loading.
     */

    /**
     * @cfg {String} href
     * An URL for a link that's created when this config is specified.
     */

    /**
     * @cfg {String} hrefTarget
     * Target for link. Only applicable when {@link #href} also specified.
     */

    /**
     * @cfg {String} qtip
     * Tooltip text to show on this node.
     */

    /**
     * @cfg {String} qtitle
     * Tooltip title.
     */

    /**
     * @cfg {String} text
     * The text for to show on node label.
     */

    /**
     * @cfg {Ext.data.NodeInterface[]} children
     * Array of child nodes.
     */

    /**
     * @property nextSibling
     * A reference to this node's next sibling node. `null` if this node does not have a next sibling.
     */

    /**
     * @property previousSibling
     * A reference to this node's previous sibling node. `null` if this node does not have a previous sibling.
     */

    /**
     * @property parentNode
     * A reference to this node's parent node. `null` if this node is the root node.
     */

    /**
     * @property lastChild
     * A reference to this node's last child node. `null` if this node has no children.
     */

    /**
     * @property firstChild
     * A reference to this node's first child node. `null` if this node has no children.
     */

    /**
     * @property childNodes
     * An array of this nodes children.  Array will be empty if this node has no chidren.
     */

    statics: {
        /**
         * This method allows you to decorate a Model's class to implement the NodeInterface.
         * This adds a set of methods, new events, new properties and new fields on every Record.
         * @param {Ext.Class/Ext.data.Model} modelClass The Model class or an instance of the Model class you want to
         * decorate the prototype of.
         * @static
         */
        decorate: function(modelClass) {
            var idName, idType;

            // get the reference to the model class, in case the argument was a string or a record
            if (typeof modelClass == 'string') {
                modelClass = Ext.ModelManager.getModel(modelClass);
            } else if (modelClass.isModel) {
                modelClass = Ext.ModelManager.getModel(modelClass.modelName);
            }

            // avoid unnecessary work in case the model was already decorated
            if (modelClass.prototype.isNode) {
                return;
            }

            idName = modelClass.prototype.idProperty;
            idField = modelClass.prototype.fields.get(idName);
            idType = modelClass.prototype.fields.get(idName).type.type;
            modelClass.override(this.getPrototypeBody());
            this.applyFields(modelClass, [
                {name: 'parentId',   type: idType,    defaultValue: null, useNull: idField.useNull},
                {name: 'index',      type: 'int',     defaultValue: null, persist: false},
                {name: 'depth',      type: 'int',     defaultValue: 0, persist: false},
                {name: 'expanded',   type: 'bool',    defaultValue: false, persist: false},
                {name: 'expandable', type: 'bool',    defaultValue: true, persist: false},
                {name: 'checked',    type: 'auto',    defaultValue: null, persist: false},
                {name: 'leaf',       type: 'bool',    defaultValue: false},
                {name: 'cls',        type: 'string',  defaultValue: null, persist: false},
                {name: 'iconCls',    type: 'string',  defaultValue: null, persist: false},
                {name: 'icon',       type: 'string',  defaultValue: null, persist: false},
                {name: 'root',       type: 'boolean', defaultValue: false, persist: false},
                {name: 'isLast',     type: 'boolean', defaultValue: false, persist: false},
                {name: 'isFirst',    type: 'boolean', defaultValue: false, persist: false},
                {name: 'allowDrop',  type: 'boolean', defaultValue: true, persist: false},
                {name: 'allowDrag',  type: 'boolean', defaultValue: true, persist: false},
                {name: 'loaded',     type: 'boolean', defaultValue: false, persist: false},
                {name: 'loading',    type: 'boolean', defaultValue: false, persist: false},
                {name: 'href',       type: 'string',  defaultValue: null, persist: false},
                {name: 'hrefTarget', type: 'string',  defaultValue: null, persist: false},
                {name: 'qtip',       type: 'string',  defaultValue: null, persist: false},
                {name: 'qtitle',     type: 'string',  defaultValue: null, persist: false},
                {name: 'children',   type: 'auto',   defaultValue: null, persist: false}
            ]);
        },

        applyFields: function(modelClass, addFields) {
            var modelPrototype = modelClass.prototype,
                fields = modelPrototype.fields,
                keys = fields.keys,
                ln = addFields.length,
                addField, i;

            for (i = 0; i < ln; i++) {
                addField = addFields[i];
                if (!Ext.Array.contains(keys, addField.name)) {
                    fields.add(new Ext.data.Field(addField));
                }
            }

        },

        getPrototypeBody: function() {
            return {
                /**
                 * @property {Boolean} isNode
                 * `true` in this class to identify an object as an instantiated Node, or subclass thereof.
                 */
                isNode: true,

                constructor: function() {
                    var me = this;
                    this.callParent(arguments);
                    Ext.applyIf(me, {
                        firstChild: null,
                        lastChild: null,
                        parentNode: null,
                        previousSibling: null,
                        nextSibling: null,
                        childNodes: []
                    });
                    me.enableBubble([
                        /**
                         * @event append
                         * Fires when a new child node is appended
                         * @param {Ext.data.NodeInterface} this This node
                         * @param {Ext.data.NodeInterface} node The newly appended node
                         * @param {Number} index The index of the newly appended node
                         */
                        "append",

                        /**
                         * @event remove
                         * Fires when a child node is removed
                         * @param {Ext.data.NodeInterface} this This node
                         * @param {Ext.data.NodeInterface} node The removed node
                         * @param {Boolean} isMove `true` if the child node is being removed so it can be moved to another position in the tree.
                         * (a side effect of calling {@link Ext.data.NodeInterface#appendChild appendChild} or
                         * {@link Ext.data.NodeInterface#insertBefore insertBefore} with a node that already has a parentNode)
                         */
                        "remove",

                        /**
                         * @event move
                         * Fires when this node is moved to a new location in the tree
                         * @param {Ext.data.NodeInterface} this This node
                         * @param {Ext.data.NodeInterface} oldParent The old parent of this node
                         * @param {Ext.data.NodeInterface} newParent The new parent of this node
                         * @param {Number} index The index it was moved to
                         */
                        "move",

                        /**
                         * @event insert
                         * Fires when a new child node is inserted.
                         * @param {Ext.data.NodeInterface} this This node
                         * @param {Ext.data.NodeInterface} node The child node inserted
                         * @param {Ext.data.NodeInterface} refNode The child node the node was inserted before
                         */
                        "insert",

                        /**
                         * @event beforeappend
                         * Fires before a new child is appended, return false to cancel the append.
                         * @param {Ext.data.NodeInterface} this This node
                         * @param {Ext.data.NodeInterface} node The child node to be appended
                         */
                        "beforeappend",

                        /**
                         * @event beforeremove
                         * Fires before a child is removed, return false to cancel the remove.
                         * @param {Ext.data.NodeInterface} this This node
                         * @param {Ext.data.NodeInterface} node The child node to be removed
                         * @param {Boolean} isMove `true` if the child node is being removed so it can be moved to another position in the tree.
                         * (a side effect of calling {@link Ext.data.NodeInterface#appendChild appendChild} or
                         * {@link Ext.data.NodeInterface#insertBefore insertBefore} with a node that already has a parentNode)
                         */
                        "beforeremove",

                        /**
                         * @event beforemove
                         * Fires before this node is moved to a new location in the tree. Return false to cancel the move.
                         * @param {Ext.data.NodeInterface} this This node
                         * @param {Ext.data.NodeInterface} oldParent The parent of this node
                         * @param {Ext.data.NodeInterface} newParent The new parent this node is moving to
                         * @param {Number} index The index it is being moved to
                         */
                        "beforemove",

                         /**
                          * @event beforeinsert
                          * Fires before a new child is inserted, return false to cancel the insert.
                          * @param {Ext.data.NodeInterface} this This node
                          * @param {Ext.data.NodeInterface} node The child node to be inserted
                          * @param {Ext.data.NodeInterface} refNode The child node the node is being inserted before
                          */
                        "beforeinsert",

                        /**
                         * @event expand
                         * Fires when this node is expanded.
                         * @param {Ext.data.NodeInterface} this The expanding node
                         */
                        "expand",

                        /**
                         * @event collapse
                         * Fires when this node is collapsed.
                         * @param {Ext.data.NodeInterface} this The collapsing node
                         */
                        "collapse",

                        /**
                         * @event beforeexpand
                         * Fires before this node is expanded.
                         * @param {Ext.data.NodeInterface} this The expanding node
                         */
                        "beforeexpand",

                        /**
                         * @event beforecollapse
                         * Fires before this node is collapsed.
                         * @param {Ext.data.NodeInterface} this The collapsing node
                         */
                        "beforecollapse",

                        /**
                         * @event sort
                         * Fires when this node's childNodes are sorted.
                         * @param {Ext.data.NodeInterface} this This node.
                         * @param {Ext.data.NodeInterface[]} childNodes The childNodes of this node.
                         */
                        "sort"
                    ]);
                    return me;
                },
                /**
                 * Ensures that the passed object is an instance of a Record with the NodeInterface applied
                 * @return {Ext.data.NodeInterface}
                 */
                createNode: function(node) {
                    if (Ext.isObject(node) && !node.isModel) {
                        node = Ext.ModelManager.create(node, this.modelName);
                    }
                    // The node may already decorated, but may not have been
                    // so when the model constructor was called. If not,
                    // setup defaults here
                    if (!node.childNodes) {
                        Ext.applyIf(node, {
                            firstChild: null,
                            lastChild: null,
                            parentNode: null,
                            previousSibling: null,
                            nextSibling: null,
                            childNodes: []
                        });
                    }
                    return node;
                },

                /**
                 * Returns true if this node is a leaf
                 * @return {Boolean}
                 */
                isLeaf : function() {
                    return this.get('leaf') === true;
                },

                /**
                 * Sets the first child of this node
                 * @private
                 * @param {Ext.data.NodeInterface} node
                 */
                setFirstChild : function(node) {
                    this.firstChild = node;
                },

                /**
                 * Sets the last child of this node
                 * @private
                 * @param {Ext.data.NodeInterface} node
                 */
                setLastChild : function(node) {
                    this.lastChild = node;
                },

                /**
                 * Updates general data of this node like isFirst, isLast, depth. This
                 * method is internally called after a node is moved. This shouldn't
                 * have to be called by the developer unless they are creating custom
                 * Tree plugins.
                 * @return {Boolean}
                 */
                updateInfo: function(commit) {
                    var me = this,
                        isRoot = me.isRoot(),
                        parentNode = me.parentNode,
                        isFirst = (!parentNode || isRoot ? true : parentNode.firstChild === me),
                        isLast = (!parentNode || isRoot ? true : parentNode.lastChild === me),
                        depth = 0,
                        parent = me,
                        children = me.childNodes,
                        len = children.length,
                        i = 0,
                        phantom = me.phantom;

                    while (parent.parentNode) {
                        ++depth;
                        parent = parent.parentNode;
                    }

                    me.beginEdit();
                    me.set({
                        isFirst: isFirst,
                        isLast: isLast,
                        depth: depth,
                        index: parentNode ? parentNode.indexOf(me) : 0,
                        parentId: parentNode ? parentNode.getId() : null
                    });
                    me.endEdit(true);
                    if (commit) {
                        me.commit();
                        me.phantom = phantom;
                    }

                    for (i = 0; i < len; i++) {
                        children[i].updateInfo(commit);
                    }
                },

                /**
                 * Returns true if this node is the last child of its parent
                 * @return {Boolean}
                 */
                isLast : function() {
                   return this.get('isLast');
                },

                /**
                 * Returns true if this node is the first child of its parent
                 * @return {Boolean}
                 */
                isFirst : function() {
                   return this.get('isFirst');
                },

                /**
                 * Returns true if this node has one or more child nodes, else false.
                 * @return {Boolean}
                 */
                hasChildNodes : function() {
                    return !this.isLeaf() && this.childNodes.length > 0;
                },

                /**
                 * Returns true if this node has one or more child nodes, or if the <tt>expandable</tt>
                 * node attribute is explicitly specified as true, otherwise returns false.
                 * @return {Boolean}
                 */
                isExpandable : function() {
                    var me = this;

                    if (me.get('expandable')) {
                        return !(me.isLeaf() || (me.isLoaded() && !me.hasChildNodes()));
                    }
                    return false;
                },

                triggerUIUpdate: function(){
                    // This isn't ideal, however none of the underlying fields have changed
                    // but we still need to update the UI
                    this.afterEdit([]);
                },

                /**
                 * Inserts node(s) as the last child node of this node.
                 *
                 * If the node was previously a child node of another parent node, it will be removed from that node first.
                 *
                 * @param {Ext.data.NodeInterface/Ext.data.NodeInterface[]} node The node or Array of nodes to append
                 * @return {Ext.data.NodeInterface} The appended node if single append, or null if an array was passed
                 */
                appendChild : function(node, suppressEvents, commit) {
                    var me = this,
                        i, ln,
                        index,
                        oldParent,
                        ps;

                    // if passed an array do them one by one
                    if (Ext.isArray(node)) {
                        // suspend auto syncing while we append all the nodes
                        me.callStore('suspendAutoSync');
                        for (i = 0, ln = node.length - 1; i < ln; i++) {
                            me.appendChild(node[i]);
                        }
                        // resume auto syncing before we append the last node
                        me.callStore('resumeAutoSync');
                        me.appendChild(node[ln]);
                    } else {
                        // Make sure it is a record
                        node = me.createNode(node);

                        if (suppressEvents !== true && (!me.hasListeners.beforeappend || me.fireEvent("beforeappend", me, node) === false)) {
                            return false;
                        }

                        index = me.childNodes.length;
                        oldParent = node.parentNode;

                        // it's a move, make sure we move it cleanly
                        if (oldParent) {
                            if (suppressEvents !== true && (!me.hasListeners.beforeremove || node.fireEvent("beforemove", node, oldParent, me, index) === false)) {
                                return false;
                            }
                            oldParent.removeChild(node, false, false, true);
                        }

                        index = me.childNodes.length;
                        if (index === 0) {
                            me.setFirstChild(node);
                        }

                        me.childNodes.push(node);
                        node.parentNode = me;
                        node.nextSibling = null;

                        me.setLastChild(node);

                        ps = me.childNodes[index - 1];
                        if (ps) {
                            node.previousSibling = ps;
                            ps.nextSibling = node;
                            ps.updateInfo(commit);
                        } else {
                            node.previousSibling = null;
                        }

                        node.updateInfo(commit);

                        // As soon as we append a child to this node, we are loaded
                        if (!me.isLoaded()) {
                            me.set('loaded', true);
                        } else if (me.childNodes.length === 1) {
                            me.triggerUIUpdate();
                        }

                        if(!node.isLeaf() && node.phantom) {
                            node.set('loaded', true);
                        }

                        if (suppressEvents !== true) {
                            me.fireEvent("append", me, node, index);

                            if (oldParent) {
                                node.fireEvent("move", node, oldParent, me, index);
                            }
                        }

                        return node;
                    }
                },

                /**
                 * Returns the bubble target for this node
                 * @private
                 * @return {Object} The bubble target
                 */
                getBubbleTarget: function() {
                    return this.parentNode;
                },

                /**
                 * Removes a child node from this node.
                 * @param {Ext.data.NodeInterface} node The node to remove
                 * @param {Boolean} [destroy=false] True to destroy the node upon removal.
                 * @return {Ext.data.NodeInterface} The removed node
                 */
                removeChild : function(node, destroy, suppressEvents, isMove) {
                    var me = this,
                        index = me.indexOf(node),
                        i, childCount;

                    if (index == -1 || (suppressEvents !== true && (!me.hasListeners.beforeremove || me.fireEvent("beforeremove", me, node, !!isMove) === false))) {
                        return false;
                    }

                    // remove it from childNodes collection
                    Ext.Array.erase(me.childNodes, index, 1);

                    // update child refs
                    if (me.firstChild == node) {
                        me.setFirstChild(node.nextSibling);
                    }
                    if (me.lastChild == node) {
                        me.setLastChild(node.previousSibling);
                    }

                    // update siblings
                    if (node.previousSibling) {
                        node.previousSibling.nextSibling = node.nextSibling;
                    }
                    if (node.nextSibling) {
                        node.nextSibling.previousSibling = node.previousSibling;
                    }

                    // update the info for all siblings starting at the index before the node's old index (or 0 if the removed node was the firstChild)
                    for(i = index > 0 ? index - 1 : 0, childCount = me.childNodes.length; i < childCount; i++) {
                        me.childNodes[i].updateInfo();
                    }

                    // If this node suddenly doesnt have childnodes anymore, update myself
                    if (!me.childNodes.length) {
                        me.triggerUIUpdate();
                    }

                    if (suppressEvents !== true) {
                        if (me.hasListeners.remove) {
                            me.fireEvent("remove", me, node, !!isMove);
                        }
                    }

                    if (destroy) {
                        node.destroy(true);
                    } else {
                        node.clear();
                    }

                    return node;
                },

                /**
                 * Creates a copy (clone) of this Node.
                 * @param {String} [id] A new id, defaults to this Node's id.
                 * @param {Boolean} [deep=false] True to recursively copy all child Nodes into the new Node.
                 * False to copy without child Nodes.
                 * @return {Ext.data.NodeInterface} A copy of this Node.
                 */
                copy: function(newId, deep) {
                    var me = this,
                        result = me.callOverridden(arguments),
                        len = me.childNodes ? me.childNodes.length : 0,
                        i;

                    // Move child nodes across to the copy if required
                    if (deep) {
                        for (i = 0; i < len; i++) {
                            result.appendChild(me.childNodes[i].copy(true));
                        }
                    }
                    return result;
                },

                /**
                 * Clears the node.
                 * @private
                 * @param {Boolean} [destroy=false] True to destroy the node.
                 */
                clear : function(destroy) {
                    var me = this;

                    // clear any references from the node
                    me.parentNode = me.previousSibling = me.nextSibling = null;
                    if (destroy) {
                        me.firstChild = me.lastChild = null;
                    }
                },

                /**
                 * Destroys the node.
                 */
                destroy : function(silent) {
                    /*
                     * Silent is to be used in a number of cases
                     * 1) When setRoot is called.
                     * 2) When destroy on the tree is called
                     * 3) For destroying child nodes on a node
                     */
                    var me      = this,
                        options = me.destroyOptions,
                        nodes   = me.childNodes,
                        nLen    = nodes.length,
                        n;

                    if (silent === true) {
                        me.clear(true);

                        for (n = 0; n < nLen; n++) {
                            nodes[n].destroy(true);
                        }

                        me.childNodes = null;
                        delete me.destroyOptions;
                        me.callOverridden([options]);
                    } else {
                        me.destroyOptions = silent;
                        // overridden method will be called, since remove will end up calling destroy(true);
                        me.remove(true);
                    }
                },

                /**
                 * Inserts the first node before the second node in this nodes childNodes collection.
                 * @param {Ext.data.NodeInterface} node The node to insert
                 * @param {Ext.data.NodeInterface} refNode The node to insert before (if null the node is appended)
                 * @return {Ext.data.NodeInterface} The inserted node
                 */
                insertBefore : function(node, refNode, suppressEvents) {
                    var me = this,
                        index     = me.indexOf(refNode),
                        oldParent = node.parentNode,
                        refIndex  = index,
                        childCount, ps, i;

                    if (!refNode) { // like standard Dom, refNode can be null for append
                        return me.appendChild(node);
                    }

                    // nothing to do
                    if (node == refNode) {
                        return false;
                    }

                    // Make sure it is a record with the NodeInterface
                    node = me.createNode(node);

                    if (suppressEvents !== true && (!me.hasListeners.beforeinsert || me.fireEvent("beforeinsert", me, node, refNode) === false)) {
                        return false;
                    }

                    // when moving internally, indexes will change after remove
                    if (oldParent == me && me.indexOf(node) < index) {
                        refIndex--;
                    }

                    // it's a move, make sure we move it cleanly
                    if (oldParent) {
                        if (suppressEvents !== true && (!me.hasListeners.beforeremove || node.fireEvent("beforemove", node, oldParent, me, index, refNode) === false)) {
                            return false;
                        }
                        oldParent.removeChild(node, false, false, true);
                    }

                    if (refIndex === 0) {
                        me.setFirstChild(node);
                    }

                    Ext.Array.splice(me.childNodes, refIndex, 0, node);
                    node.parentNode = me;

                    node.nextSibling = refNode;
                    refNode.previousSibling = node;

                    ps = me.childNodes[refIndex - 1];
                    if (ps) {
                        node.previousSibling = ps;
                        ps.nextSibling = node;
                    } else {
                        node.previousSibling = null;
                    }

                    // update the info for all siblings starting at the index before the node's insertion point (or 0 if the inserted node is the firstChild)
                    for(i = refIndex > 0 ? refIndex - 1 : 0, childCount = me.childNodes.length; i < childCount; i++) {
                        me.childNodes[i].updateInfo();
                    }

                    if (!me.isLoaded()) {
                        me.set('loaded', true);
                    }
                    // If this node didnt have any childnodes before, update myself
                    else if (me.childNodes.length === 1) {
                        me.triggerUIUpdate();
                    }

                    if(!node.isLeaf() && node.phantom) {
                        node.set('loaded', true);
                    }

                    if (suppressEvents !== true) {
                        if (me.hasListeners.insert) {
                            me.fireEvent("insert", me, node, refNode);
                        }

                        if (oldParent && me.hasListeners.move) {
                            node.fireEvent("move", node, oldParent, me, refIndex, refNode);
                        }
                    }

                    return node;
                },

                /**
                 * Inserts a node into this node.
                 * @param {Number} index The zero-based index to insert the node at
                 * @param {Ext.data.NodeInterface} node The node to insert
                 * @return {Ext.data.NodeInterface} The node you just inserted
                 */
                insertChild: function(index, node) {
                    var sibling = this.childNodes[index];
                    if (sibling) {
                        return this.insertBefore(node, sibling);
                    }
                    else {
                        return this.appendChild(node);
                    }
                },

                /**
                 * Removes this node from its parent
                 * @param {Boolean} [destroy=false] True to destroy the node upon removal.
                 * @return {Ext.data.NodeInterface} this
                 */
                remove : function(destroy, suppressEvents) {
                    var parentNode = this.parentNode;

                    if (parentNode) {
                        parentNode.removeChild(this, destroy, suppressEvents);
                    }
                    return this;
                },

                /**
                 * Removes all child nodes from this node.
                 * @param {Boolean} [destroy=false] <True to destroy the node upon removal.
                 * @return {Ext.data.NodeInterface} this
                 */
                removeAll : function(destroy, suppressEvents) {
                    var cn = this.childNodes,
                        n;

                    while ((n = cn[0])) {
                        this.removeChild(n, destroy, suppressEvents);
                    }
                    return this;
                },

                /**
                 * Returns the child node at the specified index.
                 * @param {Number} index
                 * @return {Ext.data.NodeInterface}
                 */
                getChildAt : function(index) {
                    return this.childNodes[index];
                },

                /**
                 * Replaces one child node in this node with another.
                 * @param {Ext.data.NodeInterface} newChild The replacement node
                 * @param {Ext.data.NodeInterface} oldChild The node to replace
                 * @return {Ext.data.NodeInterface} The replaced node
                 */
                replaceChild : function(newChild, oldChild, suppressEvents) {
                    var s = oldChild ? oldChild.nextSibling : null;

                    this.removeChild(oldChild, false, suppressEvents);
                    this.insertBefore(newChild, s, suppressEvents);
                    return oldChild;
                },

                /**
                 * Returns the index of a child node
                 * @param {Ext.data.NodeInterface} node
                 * @return {Number} The index of the node or -1 if it was not found
                 */
                indexOf : function(child) {
                    return Ext.Array.indexOf(this.childNodes, child);
                },

                /**
                 * Returns the index of a child node that matches the id
                 * @param {String} id The id of the node to find
                 * @return {Number} The index of the node or -1 if it was not found
                 */
                indexOfId: function(id) {
                    var childNodes = this.childNodes,
                        len = childNodes.length,
                        i = 0;

                    for (; i < len; ++i) {
                        if (childNodes[i].getId() === id) {
                            return i;
                        }
                    }
                    return -1;
                },

                /**
                 * Gets the hierarchical path from the root of the current node.
                 * @param {String} [field] The field to construct the path from. Defaults to the model idProperty.
                 * @param {String} [separator="/"] A separator to use.
                 * @return {String} The node path
                 */
                getPath: function(field, separator) {
                    field = field || this.idProperty;
                    separator = separator || '/';

                    var path = [this.get(field)],
                        parent = this.parentNode;

                    while (parent) {
                        path.unshift(parent.get(field));
                        parent = parent.parentNode;
                    }
                    return separator + path.join(separator);
                },

                /**
                 * Returns depth of this node (the root node has a depth of 0)
                 * @return {Number}
                 */
                getDepth : function() {
                    return this.get('depth');
                },

                /**
                 * Bubbles up the tree from this node, calling the specified function with each node. The arguments to the function
                 * will be the args provided or the current node. If the function returns false at any point,
                 * the bubble is stopped.
                 * @param {Function} fn The function to call
                 * @param {Object} [scope] The scope (this reference) in which the function is executed. Defaults to the current Node.
                 * @param {Array} [args] The args to call the function with. Defaults to passing the current Node.
                 */
                bubble : function(fn, scope, args) {
                    var p = this;
                    while (p) {
                        if (fn.apply(scope || p, args || [p]) === false) {
                            break;
                        }
                        p = p.parentNode;
                    }
                },

                //<deprecated since=0.99>
                cascade: function() {
                    if (Ext.isDefined(Ext.global.console)) {
                        Ext.global.console.warn('Ext.data.Node: cascade has been deprecated. Please use cascadeBy instead.');
                    }
                    return this.cascadeBy.apply(this, arguments);
                },
                //</deprecated>

                /**
                 * Cascades down the tree from this node, calling the specified function with each node. The arguments to the function
                 * will be the args provided or the current node. If the function returns false at any point,
                 * the cascade is stopped on that branch.
                 * @param {Function} fn The function to call
                 * @param {Object} [scope] The scope (this reference) in which the function is executed. Defaults to the current Node.
                 * @param {Array} [args] The args to call the function with. Defaults to passing the current Node.
                 */
                cascadeBy : function(fn, scope, args) {
                    if (fn.apply(scope || this, args || [this]) !== false) {
                        var childNodes = this.childNodes,
                            length     = childNodes.length,
                            i;

                        for (i = 0; i < length; i++) {
                            childNodes[i].cascadeBy(fn, scope, args);
                        }
                    }
                },

                /**
                 * Interates the child nodes of this node, calling the specified function with each node. The arguments to the function
                 * will be the args provided or the current node. If the function returns false at any point,
                 * the iteration stops.
                 * @param {Function} fn The function to call
                 * @param {Object} [scope] The scope (this reference) in which the function is executed. Defaults to the current Node in iteration.
                 * @param {Array} [args] The args to call the function with. Defaults to passing the current Node.
                 */
                eachChild : function(fn, scope, args) {
                    var childNodes = this.childNodes,
                        length     = childNodes.length,
                        i;

                    for (i = 0; i < length; i++) {
                        if (fn.apply(scope || this, args || [childNodes[i]]) === false) {
                            break;
                        }
                    }
                },

                /**
                 * Finds the first child that has the attribute with the specified value.
                 * @param {String} attribute The attribute name
                 * @param {Object} value The value to search for
                 * @param {Boolean} [deep=false] True to search through nodes deeper than the immediate children
                 * @return {Ext.data.NodeInterface} The found child or null if none was found
                 */
                findChild : function(attribute, value, deep) {
                    return this.findChildBy(function() {
                        return this.get(attribute) == value;
                    }, null, deep);
                },

                /**
                 * Finds the first child by a custom function. The child matches if the function passed returns true.
                 * @param {Function} fn A function which must return true if the passed Node is the required Node.
                 * @param {Object} [scope] The scope (this reference) in which the function is executed. Defaults to the Node being tested.
                 * @param {Boolean} [deep=false] True to search through nodes deeper than the immediate children
                 * @return {Ext.data.NodeInterface} The found child or null if none was found
                 */
                findChildBy : function(fn, scope, deep) {
                    var cs = this.childNodes,
                        len = cs.length,
                        i = 0, n, res;

                    for (; i < len; i++) {
                        n = cs[i];
                        if (fn.call(scope || n, n) === true) {
                            return n;
                        }
                        else if (deep) {
                            res = n.findChildBy(fn, scope, deep);
                            if (res !== null) {
                                return res;
                            }
                        }
                    }

                    return null;
                },

                /**
                 * Returns true if this node is an ancestor (at any point) of the passed node.
                 * @param {Ext.data.NodeInterface} node
                 * @return {Boolean}
                 */
                contains : function(node) {
                    return node.isAncestor(this);
                },

                /**
                 * Returns true if the passed node is an ancestor (at any point) of this node.
                 * @param {Ext.data.NodeInterface} node
                 * @return {Boolean}
                 */
                isAncestor : function(node) {
                    var p = this.parentNode;
                    while (p) {
                        if (p == node) {
                            return true;
                        }
                        p = p.parentNode;
                    }
                    return false;
                },

                /**
                 * Sorts this nodes children using the supplied sort function.
                 * @param {Function} fn A function which, when passed two Nodes, returns -1, 0 or 1 depending upon required sort order.
                 * @param {Boolean} [recursive=false] True to apply this sort recursively
                 * @param {Boolean} [suppressEvent=false] True to not fire a sort event.
                 */
                sort : function(sortFn, recursive, suppressEvent) {
                    var cs  = this.childNodes,
                        ln = cs.length,
                        i, n;

                    if (ln > 0) {
                        Ext.Array.sort(cs, sortFn);
                        for (i = 0; i < ln; i++) {
                            n = cs[i];
                            n.previousSibling = cs[i-1];
                            n.nextSibling = cs[i+1];

                            if (i === 0) {
                                this.setFirstChild(n);
                            }
                            if (i == ln - 1) {
                                this.setLastChild(n);
                            }
                            n.updateInfo();
                            if (recursive && !n.isLeaf()) {
                                n.sort(sortFn, true, true);
                            }
                        }

                        if (suppressEvent !== true) {
                            this.fireEvent('sort', this, cs);
                        }
                    }
                },

                /**
                 * Returns true if this node is expaned
                 * @return {Boolean}
                 */
                isExpanded: function() {
                    return this.get('expanded');
                },

                /**
                 * Returns true if this node is loaded
                 * @return {Boolean}
                 */
                isLoaded: function() {
                    return this.get('loaded');
                },

                /**
                 * Returns true if this node is loading
                 * @return {Boolean}
                 */
                isLoading: function() {
                    return this.get('loading');
                },

                /**
                 * Returns true if this node is the root node
                 * @return {Boolean}
                 */
                isRoot: function() {
                    return !this.parentNode;
                },

                /**
                 * Returns true if this node is visible
                 * @return {Boolean}
                 */
                isVisible: function() {
                    var parent = this.parentNode;
                    while (parent) {
                        if (!parent.isExpanded()) {
                            return false;
                        }
                        parent = parent.parentNode;
                    }
                    return true;
                },

                /**
                 * Expand this node.
                 * @param {Boolean} [recursive=false] True to recursively expand all the children
                 * @param {Function} [callback] The function to execute once the expand completes
                 * @param {Object} [scope] The scope to run the callback in
                 */
                expand: function(recursive, callback, scope) {
                    var me = this;

                    // all paths must call the callback (eventually) or things like
                    // selectPath fail

                    // First we start by checking if this node is a parent
                    if (!me.isLeaf()) {
                        // If it's loaded, wait until it loads before proceeding
                        if (me.isLoading()) {
                            me.on('expand', function(){
                                me.expand(recursive, callback, scope);
                            }, me, {single: true});
                        } else {
                            // Now we check if this record is already expanding or expanded
                            if (!me.isExpanded()) {
                                // The TreeStore actually listens for the beforeexpand method and checks
                                // whether we have to asynchronously load the children from the server
                                // first. Thats why we pass a callback function to the event that the
                                // store can call once it has loaded and parsed all the children.
                                me.fireEvent('beforeexpand', me, function() {
                                    me.set('expanded', true);
                                    if (me.hasListeners.expand) {
                                        me.fireEvent('expand', me, me.childNodes, false);
                                    }

                                    // Call the expandChildren method if recursive was set to true
                                    if (recursive) {
                                        me.expandChildren(true, callback, scope);
                                    } else {
                                        Ext.callback(callback, scope || me, [me.childNodes]);
                                    }
                                }, me);
                            } else if (recursive) {
                                // If it is is already expanded but we want to recursively expand then call expandChildren
                                me.expandChildren(true, callback, scope);
                            } else {
                                Ext.callback(callback, scope || me, [me.childNodes]);
                            }
                        }
                    } else {
                        // If it's not then we fire the callback right away
                        Ext.callback(callback, scope || me); // leaf = no childNodes
                    }
                },

                /**
                 * Expand all the children of this node.
                 * @param {Boolean} [recursive=false] True to recursively expand all the children
                 * @param {Function} [callback] The function to execute once all the children are expanded
                 * @param {Object} [scope] The scope to run the callback in
                 */
                expandChildren: function(recursive, callback, scope) {
                    var me = this,
                        i = 0,
                        nodes = me.childNodes,
                        ln = nodes.length,
                        node,
                        expanding = 0;

                    for (; i < ln; ++i) {
                        node = nodes[i];
                        if (!node.isLeaf()) {
                            expanding++;
                            nodes[i].expand(recursive, function () {
                                expanding--;
                                if (callback && !expanding) {
                                    Ext.callback(callback, scope || me, [me.childNodes]);
                                }
                            });
                        }
                    }

                    if (!expanding && callback) {
                        Ext.callback(callback, scope || me, [me.childNodes]);                    }
                },

                /**
                 * Collapse this node.
                 * @param {Boolean} [recursive=false] True to recursively collapse all the children
                 * @param {Function} [callback] The function to execute once the collapse completes
                 * @param {Object} [scope] The scope to run the callback in
                 */
                collapse: function(recursive, callback, scope) {
                    var me = this;

                    // First we start by checking if this node is a parent
                    if (!me.isLeaf()) {
                        // Now we check if this record is already collapsing or collapsed
                        if (!me.collapsing && me.isExpanded()) {
                            me.fireEvent('beforecollapse', me, function() {
                                me.set('expanded', false);
                                if (me.hasListeners.collapse) {
                                    me.fireEvent('collapse', me, me.childNodes, false);
                                }

                                // Call the collapseChildren method if recursive was set to true
                                if (recursive) {
                                    me.collapseChildren(true, callback, scope);
                                }
                                else {
                                    Ext.callback(callback, scope || me, [me.childNodes]);
                                }
                            }, me);
                        }
                        // If it is is already collapsed but we want to recursively collapse then call collapseChildren
                        else if (recursive) {
                            me.collapseChildren(true, callback, scope);
                        } else {
                            Ext.callback(callback, scope || me, [me.childNodes]);
                        }
                    }
                    // If it's not then we fire the callback right away
                    else {
                        Ext.callback(callback, scope || me, [me.childNodes]);
                    }
                },

                /**
                 * Collapse all the children of this node.
                 * @param {Function} [recursive=false] True to recursively collapse all the children
                 * @param {Function} [callback] The function to execute once all the children are collapsed
                 * @param {Object} [scope] The scope to run the callback in
                 */
                collapseChildren: function(recursive, callback, scope) {
                    var me = this,
                        i = 0,
                        nodes = me.childNodes,
                        ln = nodes.length,
                        node,
                        collapsing = 0;

                    for (; i < ln; ++i) {
                        node = nodes[i];
                        if (!node.isLeaf()) {
                            collapsing++;
                            nodes[i].collapse(recursive, function () {
                                collapsing--;
                                if (callback && !collapsing) {
                                    Ext.callback(callback, scope || me, [me.childNodes]);
                                }
                            });
                        }
                    }

                    if (!collapsing && callback) {
                        Ext.callback(callback, scope || me, [me.childNodes]);
                    }
                }
            };
        }
    }
});


text:
package com.yf.designPattern.prototype;

import java.util.HashMap;
import java.util.Map;

public class ShapeCache {
	private static Map<String, Shape> maps = new HashMap<String, Shape>();

	public static void loadCache() {
		Circle circle = new Circle();
		circle.setId("1");
		maps.put(circle.getId(), circle);

		Square square = new Square();
		square.setId("2");
		maps.put(square.getId(), square);

		Rectangle rectangle = new Rectangle();
		rectangle.setId("3");
		maps.put(rectangle.getId(), rectangle);
	}

	public  static  Shape  getShape(String shapeId) throws CloneNotSupportedException{
		Shape shape=maps.get(shapeId);
		return  (Shape) shape.clone();
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

/**
 * Chat conversion handler
 */
class moodle1_mod_chat_handler extends moodle1_mod_handler {

    /** @var moodle1_file_manager */
    protected $fileman = null;

    /** @var int cmid */
    protected $moduleid = null;

    /**
     * Declare the paths in moodle.xml we are able to convert
     *
     * The method returns list of {@link convert_path} instances.
     * For each path returned, the corresponding conversion method must be
     * defined.
     *
     * Note that the path /MOODLE_BACKUP/COURSE/MODULES/MOD/CHAT does not
     * actually exist in the file. The last element with the module name was
     * appended by the moodle1_converter class.
     *
     * @return array of {@link convert_path} instances
     */
    public function get_paths() {
        return array(
            new convert_path(
                'chat', '/MOODLE_BACKUP/COURSE/MODULES/MOD/CHAT',
                array(
                    'newfields' => array(
                        'introformat' => 0
                    )
                )
            )
        );
    }

    /**
     * This is executed every time we have one /MOODLE_BACKUP/COURSE/MODULES/MOD/CHAT
     * data available
     */
    public function process_chat($data) {
        global $CFG;

        // get the course module id and context id
        $instanceid     = $data['id'];
        $cminfo         = $this->get_cminfo($instanceid);
        $this->moduleid = $cminfo['id'];
        $contextid      = $this->converter->get_contextid(CONTEXT_MODULE, $this->moduleid);

        // replay the upgrade step 2010050101
        if ($CFG->texteditors !== 'textarea') {
            $data['intro']       = text_to_html($data['intro'], false, false, true);
            $data['introformat'] = FORMAT_HTML;
        }

        // get a fresh new file manager for this instance
        $this->fileman = $this->converter->get_file_manager($contextid, 'mod_chat');

        // convert course files embedded into the intro
        $this->fileman->filearea = 'intro';
        $this->fileman->itemid   = 0;
        $data['intro'] = moodle1_converter::migrate_referenced_files($data['intro'], $this->fileman);

        // start writing chat.xml
        $this->open_xml_writer("activities/chat_{$this->moduleid}/chat.xml");
        $this->xmlwriter->begin_tag('activity', array('id' => $instanceid, 'moduleid' => $this->moduleid,
            'modulename' => 'chat', 'contextid' => $contextid));
        $this->xmlwriter->begin_tag('chat', array('id' => $instanceid));

        foreach ($data as $field => $value) {
            if ($field <> 'id') {
                $this->xmlwriter->full_tag($field, $value);
            }
        }

        $this->xmlwriter->begin_tag('messages');

        return $data;
    }

    /**
     * This is executed every time we have one /MOODLE_BACKUP/COURSE/MODULES/MOD/CHAT/MESSAGES/MESSAGE
     * data available
     */
    public function process_chat_message($data) {
        //@todo process user data
        //$this->write_xml('message', $data, array('/message/id'));
    }

    /**
     * This is executed when we reach the closing </MOD> tag of our 'chat' path
     */
    public function on_chat_end() {
        // close chat.xml
        $this->xmlwriter->end_tag('messages');
        $this->xmlwriter->end_tag('chat');
        $this->xmlwriter->end_tag('activity');
        $this->close_xml_writer();

        // write inforef.xml
        $this->open_xml_writer("activities/chat_{$this->moduleid}/inforef.xml");
        $this->xmlwriter->begin_tag('inforef');
        $this->xmlwriter->begin_tag('fileref');
        foreach ($this->fileman->get_fileids() as $fileid) {
            $this->write_xml('file', array('id' => $fileid));
        }
        $this->xmlwriter->end_tag('fileref');
        $this->xmlwriter->end_tag('inforef');
        $this->close_xml_writer();
    }
}


text:
from unittest import mock

import netaddr
from oslo_utils import uuidutils

from neutron.objects import port_forwarding
from neutron.objects import router
from neutron.tests import tools
from neutron.tests.unit.objects import test_base as obj_test_base
from neutron.tests.unit import testlib_api

class PortForwardingObjectTestCase(obj_test_base.BaseObjectIfaceTestCase):

    _test_class = port_forwarding.PortForwarding

    def setUp(self):
        super(PortForwardingObjectTestCase, self).setUp()
        # 'portforwardings' table will store the 'internal_ip_address' and
        # 'internal_port' as a single 'socket' column.
        # Port forwarding object accepts 'internal_ip_address' and
        # 'internal_port', but can not filter the records in db, so the
        # valid filters can not contain them.
        not_supported_filter_fields = ['internal_ip_address', 'internal_port']
        invalid_fields = set(
            self._test_class.synthetic_fields).union(
            set(not_supported_filter_fields))
        self.valid_field = [f for f in self._test_class.fields
                            if f not in invalid_fields][0]

        self.mock_load_fip = mock.patch.object(
            self._test_class, '_load_attr_from_fip', autospec=True,
            side_effect=self._mock_load_attr_from_fip).start()

        for obj_fields in self.obj_fields:
            obj_fields['floating_ip_address'] = tools.get_random_ip_address(4)
            obj_fields['router_id'] = uuidutils.generate_uuid()

    def _mock_load_attr_from_fip(self, fp_obj, attrname):
        def random_generate_fip_db(fip_id):
            fip_fields = self.get_random_db_fields(router.FloatingIP)
            fip_fields['id'] = fip_id
            fip_fields['floating_ip_address'] = tools.get_random_ip_address(4)
            return router.FloatingIP.db_model(**fip_fields)

        if not fp_obj.db_obj:
            fp_db_attrs = {
                'floatingip_id': fp_obj.floatingip_id,
                'external_port_start': fp_obj.external_port,
                'external_port_end': fp_obj.external_port,
                'internal_neutron_port_id': fp_obj.internal_port_id,
                'protocol': fp_obj.protocol,
                'internal_port_start': fp_obj.internal_port,
                'internal_port_end': fp_obj.internal_port,
                'floating_ip': random_generate_fip_db(fp_obj.floatingip_id)
            }
            fp_obj._captured_db_model = (
                port_forwarding.PortForwarding.db_model(**fp_db_attrs))

        if not fp_obj.db_obj.floating_ip:
            fp_obj.db_obj.floating_ip = random_generate_fip_db(
                fp_obj.floatingip_id)

        # From PortForwarding._load_attr_from_fip
        value = getattr(fp_obj.db_obj.floating_ip, attrname)
        setattr(self, attrname, value)
        fp_obj.obj_reset_changes([attrname])

class PortForwardingDbObjectTestCase(obj_test_base.BaseDbObjectTestCase,
                                     testlib_api.SqlTestCase):

    _test_class = port_forwarding.PortForwarding

    def setUp(self):
        super(PortForwardingDbObjectTestCase, self).setUp()
        self.update_obj_fields(
            {'floatingip_id':
                lambda: self._create_test_fip_id_for_port_forwarding(),
             'internal_port_id': lambda: self._create_test_port_id()})
        # 'portforwardings' table will store the 'internal_ip_address' and
        # 'internal_port' as a single 'socket' column.
        # Port forwarding object accepts 'internal_ip_address' and
        # 'internal_port', but can not filter the records in db, so the
        # valid filters can not contain them.
        not_supported_filter_fields = ['internal_ip_address', 'internal_port']
        invalid_fields = set(
            self._test_class.synthetic_fields).union(
            set(not_supported_filter_fields))
        self.valid_field = [f for f in self._test_class.fields
                            if f not in invalid_fields][0]
        self.valid_field_filter = {self.valid_field:
                                   self.obj_fields[-1][self.valid_field]}

    def _create_test_fip_id_for_port_forwarding(self):
        fake_fip = '172.23.3.0'
        ext_net_id = self._create_external_network_id()
        router_id = self._create_test_router_id()
        values = {
            'floating_ip_address': netaddr.IPAddress(fake_fip),
            'floating_network_id': ext_net_id,
            'floating_port_id': self._create_test_port_id(
                network_id=ext_net_id),
            'router_id': router_id,
        }
        fip_obj = router.FloatingIP(self.context, **values)
        fip_obj.create()
        return fip_obj.id

    def test_db_obj(self):
        # The reason for rewriting this test is:
        # 1. Currently, the existing test_db_obj test in
        #    obj_test_base.BaseDbObjectTestCase is not suitable for the case,
        #    for example, the db model is not the same with obj fields
        #    definition.
        # 2. For port forwarding, the db model will store and accept 'socket',
        #    but the obj fields just only support accepting the parameters
        #    generate 'socket', such as 'internal_ip_address' and
        #    'internal_port'.
        obj = self._make_object(self.obj_fields[0])
        self.assertIsNone(obj.db_obj)

        obj.create()
        self.assertIsNotNone(obj.db_obj)

        fields_to_update = self.get_updatable_fields(self.obj_fields[1])
        if fields_to_update:
            old_fields = {}
            for key, val in fields_to_update.items():
                db_model_attr = (
                    obj.fields_need_translation.get(key, key))

                old_fields[db_model_attr] = obj.db_obj[
                    db_model_attr] if hasattr(
                    obj.db_obj, db_model_attr) else getattr(
                    obj, db_model_attr)
                setattr(obj, key, val)
            obj.update()
            self.assertIsNotNone(obj.db_obj)
            # Then check all update fields had been updated.
            for k, v in obj.modify_fields_to_db(fields_to_update).items():
                self.assertEqual(v, obj.db_obj[k], '%s attribute differs' % k)

        obj.delete()
        self.assertIsNone(obj.db_obj)

    def test_get_objects_queries_constant(self):
        # NOTE(bzhao) Port Forwarding uses query FLoatingIP for injecting
        # floating_ip_address and router_id, not depends on relationship,
        # so it will cost extra SQL query each time for finding the
        # associated Floating IP by floatingip_id each time(or each
        # Port Forwarding Object). Rework this if this customized OVO
        # needs to be changed.
        pass


text:
package edu.pitt.apollo.restrunmanagerserviceconnector;

import edu.pitt.apollo.connector.RunManagerServiceConnector;
import edu.pitt.apollo.exception.DatastoreException;
import edu.pitt.apollo.exception.JobRunningServiceException;
import edu.pitt.apollo.exception.RunManagementException;
import edu.pitt.apollo.restserviceconnectorcommon.RestServiceUtils;
import edu.pitt.apollo.restserviceconnectorcommon.exception.RestServiceException;
import edu.pitt.apollo.services_common.v4_0_2.*;
import edu.pitt.apollo.types.v4_0_2.SoftwareIdentification;

import java.math.BigInteger;
import java.util.List;

/**
 *
 * @author nem41
 */
public class RestRunManagerServiceConnector extends RunManagerServiceConnector {

	private final String restServiceUri;
	private final RestServiceUtils restServiceUtils = new RestServiceUtils();

	public RestRunManagerServiceConnector(String url) {
		super(url);
		restServiceUri = serviceUrl + "/ws/";
	}

	// implementation methods
	@Override
	public List<BigInteger> getRunIdsAssociatedWithSimulationGroupForRun(BigInteger runId, Authentication authentication) throws RunManagementException {
		String uri = restServiceUri + "run/" + runId + "/rungroup";
		try {
			return restServiceUtils.makeGetRequestCheckResponseAndGetObjects(uri, authentication, BigInteger.class);
		} catch (RestServiceException ex) {
			throw new RunManagementException(ex.getMessage());
		}
	}

	@Override
	public SoftwareIdentification getSoftwareIdentificationForRun(BigInteger runId, Authentication authentication) throws RunManagementException {

		String uri = restServiceUri + "run/" + runId + "/softwareIdentification";
		try {
			return restServiceUtils.makeGetRequestCheckResponseAndGetObject(uri, authentication, SoftwareIdentification.class);
		} catch (RestServiceException ex) {
			throw new RunManagementException(ex.getMessage());
		}
	}

	@Override
	public InsertRunResult insertRun(RunMessage message, Authentication authentication) throws RunManagementException {
		String uri = restServiceUri + "runs";
		try {
			return restServiceUtils.makePostRequestCheckResponseAndGetObject(uri, authentication, message, InsertRunResult.class);
		} catch (RestServiceException ex) {
			throw new RunManagementException(ex.getMessage());
		}
	}

	@Override
	public void updateStatusOfRun(BigInteger runId, MethodCallStatusEnum statusEnumToSet, String messageToSet, Authentication authentication) throws RunManagementException {
		String uri = restServiceUri + "run/" + runId + "/status?";
		uri += "&methodCallStatusEnum=" + statusEnumToSet + "&statusMessage=" + messageToSet;
		try {
			restServiceUtils.makePostRequestAndCheckResponse(uri, authentication, "");
		} catch (RestServiceException ex) {
			throw new RunManagementException(ex.getMessage());
		}
	}

	@Override
	public void updateLastServiceToBeCalledForRun(BigInteger runId, SoftwareIdentification softwareIdentification, Authentication authentication) throws RunManagementException {
		String uri = "run/" + runId + "/lastServiceToBeCalled?";
		uri += "&softwareName=" + softwareIdentification.getSoftwareName() + "&softwareVersion=" + softwareIdentification.getSoftwareVersion()
				+ "&softwareDeveloper=" + softwareIdentification.getSoftwareDeveloper() + "&softwareTypeEnum=" + softwareIdentification.getSoftwareType();
		try {
			restServiceUtils.makePostRequestAndCheckResponse(uri, authentication, "");
		} catch (RestServiceException ex) {
			throw new RunManagementException(ex.getMessage());
		}
	}

	@Override
	public SoftwareIdentification getLastServiceToBeCalledForRun(BigInteger runId, Authentication authentication) throws RunManagementException {
		String uri = restServiceUri + "run/" + runId + "/lastServiceToBeCalled";
		try {
			return restServiceUtils.makeGetRequestCheckResponseAndGetObject(uri, authentication, SoftwareIdentification.class);
		} catch (RestServiceException ex) {
			throw new RunManagementException(ex.getMessage());
		}
	}

	@Override
	public void addRunIdsToSimulationGroupForRun(BigInteger runId, List<BigInteger> runIds, Authentication authentication) throws RunManagementException {
		String uri = restServiceUri + "run/" + runId + "/rungroup";

		StringBuilder listOfRunIds = new StringBuilder();
		for (BigInteger id : runIds) {
			listOfRunIds.append(id).append(",");
		}
		listOfRunIds.deleteCharAt(listOfRunIds.length() - 1);
		uri += "&runIdsToAssociate=" + listOfRunIds.toString();
		try {
			restServiceUtils.makePostRequestAndCheckResponse(uri, authentication, "");
		} catch (RestServiceException ex) {
			throw new RunManagementException(ex.getMessage());
		}
	}

	@Override
	public void removeRunData(BigInteger runId, Authentication authentication) throws RunManagementException {
		String uri = restServiceUri + "run/" + runId;
		try {
			restServiceUtils.makePostRequestAndCheckResponse(uri, authentication, "");
		} catch (RestServiceException ex) {
			throw new RunManagementException(ex.getMessage());
		}
	}

	@Override
	public MethodCallStatus getRunStatus(BigInteger runId, Authentication authentication) throws RunManagementException {
		String uri = restServiceUri + "run/" + runId + "/status";
		try {
			return restServiceUtils.makeGetRequestCheckResponseAndGetObject(uri, authentication, MethodCallStatus.class);
		} catch (RestServiceException ex) {
			throw new RunManagementException(ex.getMessage());
		}
	}

	@Override
	public void run(BigInteger runId, Authentication authentication) throws JobRunningServiceException {
		String uri = restServiceUri + "run/" + runId + "?";
		uri += "&action=" + RunActionEnum.START;
		try {
			restServiceUtils.makePostRequestAndCheckResponse(uri, authentication, "");
		} catch (RestServiceException ex) {
			throw new JobRunningServiceException(ex.getMessage());
		}
	}

	@Override
	public void terminate(BigInteger runId, Authentication authentication) throws JobRunningServiceException {
		String uri = "run/" + runId + "?";
		uri += "&action=" + RunActionEnum.TERMINATE;
		try {
			restServiceUtils.makePostRequestAndCheckResponse(uri, authentication, "");
		} catch (RestServiceException ex) {
			throw new JobRunningServiceException(ex.getMessage());
		}
	}

	@Override
	public List<ServiceRecord> getListOfRegisteredSoftwareRecords(Authentication authentication) throws DatastoreException {
		String uri = restServiceUri + "software";
		try {
			return restServiceUtils.makeGetRequestCheckResponseAndGetObjects(uri, authentication, ServiceRecord.class);
		} catch (RestServiceException ex) {
			throw new DatastoreException(ex.getMessage());
		}
	}

	@Override
	public String getURLForSoftwareIdentification(SoftwareIdentification softwareId, Authentication authentication) throws DatastoreException {
		String uri = restServiceUri + "software/url?";
		uri += "&softwareName=" + softwareId.getSoftwareName() + "&softwareVersion=" + softwareId.getSoftwareVersion()
				+ "&softwareDeveloper=" + softwareId.getSoftwareDeveloper() + "&softwareTypeEnum=" + softwareId.getSoftwareType();
		try {
			return restServiceUtils.makeGetRequestCheckResponseAndGetObject(uri, authentication, String.class);
		} catch (RestServiceException ex) {
			throw new DatastoreException(ex.getMessage());
		}
	}
}


text:
using ResotelApp.Models;
using ResotelApp.ViewModels.Utils;
using System;
using System.ComponentModel;

namespace ResotelApp.ViewModels.Entities
{
    /// <summary>
    /// ViewModel pendant of PaymentEntity with changes notifications
    /// </summary>
    class PaymentEntity : IEntity, INotifyPropertyChanged, IDataErrorInfo
    {
        private PropertyChangeSupport _pcs;
        private double _requiredAmmount;
        private Booking _booking;

        public DateTime? Date
        {
            get { return _booking.Payment.Date; }
            set
            {
                _booking.Payment.Date = value;
                _pcs.NotifyChange();
            }
        }

        public double Ammount
        {
            get { return _booking.Payment.Ammount; }
            set
            {
                _booking.Payment.Ammount = value;
                _pcs.NotifyChange();
            }
        }

        public PaymentMode Mode
        {
            get { return _booking.Payment.Mode; }
            set
            {
                _booking.Payment.Mode = value;
                _pcs.NotifyChange();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged
        {
            add { _pcs.Handler += value; }
            remove { _pcs.Handler -= value; }
        }

        public Payment Payment
        {
            get { return _booking.Payment; }
        }

        string IDataErrorInfo.Error
        {
            get
            {
                string error = ((IDataErrorInfo)_booking.Payment).Error;
                if(Math.Abs(_requiredAmmount - _booking.Payment.Ammount) > 0.009)
                {
                    error = $"Le montant du paiement doit être de {_requiredAmmount}";
                }
                return error;
            }
        }

        string IDataErrorInfo.this[string columnName]
        {
            get
            {
                string error = ((IDataErrorInfo)_booking.Payment)[columnName];
                if (columnName == nameof(Ammount) && Math.Abs(_requiredAmmount - _booking.Payment.Ammount) > 0.009)
                {
                    error = $"Le montant du paiement doit être de {_requiredAmmount:0.00}";
                }
                return error;
            }
        }

        public PaymentEntity(Booking booking)
        {
            _pcs = new PropertyChangeSupport(this);
            _booking = booking;
            _requiredAmmount = booking.Total;
            _booking.Payment = booking.Payment;
        }
    }
}


text:
package com.sun.tools.example.debug.event;

import com.sun.jdi.*;
import com.sun.jdi.event.*;

public abstract class WatchpointEventSet extends LocatableEventSet {

    private static final long serialVersionUID = 5606285209703845409L;

    WatchpointEventSet(EventSet jdiEventSet) {
        super(jdiEventSet);
    }

    /**
     * Returns the field that is about to be accessed/modified.
     *
     * @return a {@link Field} which mirrors the field
     * in the target VM.
     */
    public Field getField() {
        return ((WatchpointEvent)oneEvent).field();
    }

    /**
     * Returns the object whose field is about to be accessed/modified.
     * Return null is the access is to a static field.
     *
     * @return a {@link ObjectReference} which mirrors the event's
     * object in the target VM.
     */
    public ObjectReference getObject() {
        return ((WatchpointEvent)oneEvent).object();
    }

    /**
     * Current value of the field.
     */
    public Value getValueCurrent() {
        return ((WatchpointEvent)oneEvent).valueCurrent();
    }
}


text:
$(document).ready(function(){
    var game = new Phaser.Game(600, 600, Phaser.AUTO, 'prueba', { preload: preload, create: create, update: update });
    var platforms;
    var player;
    var livesplayer1 = 3;
    var livesplayer2 = 3;
    var firing = false;
    var firing2 = false;
    var player1isDead = false;
    var player2isDead = false;
    var scoreplayer1 = 0;
    var scoreplayer2 = 0;
    var newball = true;
    var tiempobolas = 20000;
    var powerup1 = false;
    var powerup2 = false;
    function preload(){
    game.load.image('sky', 'assets/sky.png');
    game.load.image('ground', 'assets/platform.png');
    game.load.image('star', 'assets/star.png');
    game.load.spritesheet('dude', 'assets/player.png', 32, 34);
    game.load.spritesheet('dude2', 'assets/player2.png', 32, 34)
    game.load.image('bullet', 'assets/laser_bullet.png');
    game.load.image('long_bullet', 'assets/superlong_bullet.png');
    game.load.image('ball', 'assets/big_red_ball.png');
    game.load.image('ball3', 'assets/medium_red_ball.png');
    game.load.image('ball2', 'assets/small_red_ball.png');
    game.load.image('ball1', 'assets/small_small_red_ball.png');
    game.load.image('starvader', 'assets/starvader.png');
    game.load.image('oeste', 'assets/oeste.png');
    game.load.image('gameover', 'assets/gameover.jpg');
    }

    var scake = 3;
    var gravity = 600;
    var cursors2 = [];

    function create(){
        game.physics.startSystem(Phaser.Physics.ARCADE);
        generateBackground();
        bullets = game.add.group();
        bullets2 = game.add.group();
        platforms = game.add.group();
        platforms.enableBody = true;

        var ground = platforms.create(0, game.world.height - 64, 'ground', 3);
        var ceil = platforms.create(0, 0, 'ground');
        ground.scale.setTo(4, 2);
        ceil.scale.setTo(4,2);

        generatePlatforms();

        ground.body.immovable = true;
        ceil.body.immovable = true;

        //BALAS

        bullets.enableBody = true;
        bullets.physicsBodyType = Phaser.Physics.ARCADE;
        bullets2.enableBody = true;
        bullets2.physicsBodyType = Phaser.Physics.ARCADE;

        for (var i = 0; i<20; i++){
            var b = bullets.create(0,0, 'bullet');
            b.name = 'bullet'+i;
            b.exists = false;
            b.visible = false;
            b.checkWorldBounds = true;
            b.events.onOutOfBounds.add(resetBullet, this);
            b.scale.setTo(0.04, 0.04);

            var bul = bullets2.create(0,0, 'bullet');
            bul.name = 'bullet'+i;
            bul.exists = false;
            bul.visible = false;
            bul.checkWorldBounds = true;
            bul.events.onOutOfBounds.add(resetBullet2, this);
            bul.scale.setTo(0.04, 0.04);
        }

        //PLAYER

        player = game.add.sprite(32, game.world.height-150, 'dude');
        game.physics.arcade.enable(player);

        player.body.bounce.y = 0.1;
        player.body.gravity.y = 300;
        player.body.collideWorldBounds = true;

        player.animations.add('moveleft', [0, 1, 2, 3], 10, true);
        player.animations.add('moveright', [13, 14, 15, 16], 10, true);

        player2 = game.add.sprite(game.world.width-100, game.world.height-150, 'dude2');
        game.physics.arcade.enable(player2);

        player2.body.bounce.y = 0.1;
        player2.body.gravity.y = 300;
        player2.body.collideWorldBounds = true;

        player2.animations.add('moveleft', [0, 1, 2, 3], 10, true);
        player2.animations.add('moveright', [13, 14, 15, 16], 10, true);

        long_bullet_instance = bullets.create(player.x, player.y, 'long_bullet');
        long_bullet_instance.exists = false;
        long_bullet_instance.visible = false;
        game.world.sendToBack(long_bullet_instance);

        long_bullet_instance2 = bullets2.create(player2.x, player2.y, 'long_bullet');
        long_bullet_instance2.exists = false;
        long_bullet_instance2.visible = false;
        game.world.sendToBack(long_bullet_instance2);

        //MOVIMIENTO

        cursors = game.input.keyboard.createCursorKeys();
        spacebar = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
        spacebar.onDown.add(fireLongBullet, this);
        game.input.keyboard.addKeyCapture([Phaser.Keyboard.SPACEBAR]);
        cursors2[0]=game.input.keyboard.addKey(Phaser.Keyboard.A);
        cursors2[1]=game.input.keyboard.addKey(Phaser.Keyboard.D);
        cursors2[3] = game.input.keyboard.addKey(Phaser.Keyboard.W);
        cursors2[3].onDown.add(fireLongBullet2, this);
        game.input.keyboard.addKeyCapture([Phaser.Keyboard.SPACEBAR]);

        //BOLAS
        balls = game.add.group();
        ball = balls.create(400,200, 'ball');
        game.physics.enable(balls, Phaser.Physics.ARCADE);

        //POWER UPS
        powerups = game.add.group();

        //  This makes the game world bounce-able
        ball.body.collideWorldBounds = true;

        //  This sets the image bounce energy for the horizontal
        //  and vertical vectors (as an x,y point). "1" is 100% energy return
        ball.body.bounce.setTo(1, 1);
        //balls.createMultiple(250, 'bullets', 0, false);

        ball.scale.setTo(scake, scake);
        //ball.body.collideWorldBounds = true;
        player.body.collideWorldBounds = true;
        player2.body.collideWorldBounds = true
        //ball.body.collide('platforms');
        ball.body.bounce.setTo(1, 1);
        ball.body.velocity.setTo(100, 100);
        ball.body.gravity.setTo(0, gravity);
        ball.size = 4;

        //Score
        scoreText1 = game.add.text(16, 20, 'Score P1: 0', { fontSize: '32px', fill: '#FFFFFF' });
        scoreText2 = game.add.text(350, 20, 'Score P2: 0', { fontSize: '32px', fill: '#FFFFFF' });
        //Lives
        livesText = game.add.text(0, 550, 'Lives P1: ' + livesplayer1, { fontSize: '32px', fill: '#FFFFFF' });
        livesText2 = game.add.text(400, 550, 'Lives P2: ' + livesplayer2, { fontSize: '32px', fill: '#FFFFFF' });

    }

    function dividirBolas(ball){
            var velox = Math.abs(ball.body.velocity.x);
            var veloy = Math.abs(ball.body.velocity.y);
        if (ball.size > 1){
            var newball1 = balls.create(ball.position.x-5,ball.position.y, 'ball'+(ball.size-1));
            var newball2 = balls.create(ball.position.x+5,ball.position.y, 'ball'+(ball.size-1));
            game.physics.enable(newball1, Phaser.Physics.ARCADE);
            game.physics.enable(newball2, Phaser.Physics.ARCADE);
            newball1.body.collideWorldBounds = true;
            newball1.body.bounce.setTo(1, 1);
            newball1.scale.setTo(scake, scake);
            newball1.body.collideWorldBounds = true;
            newball1.body.velocity.setTo(20 + velox, veloy/1.25);
            newball1.body.gravity.setTo(0, gravity);
            newball2.body.collideWorldBounds = true;
            newball2.body.bounce.setTo(1, 1);
            newball2.scale.setTo(scake, scake);
            newball2.body.collideWorldBounds = true;
            newball2.body.velocity.setTo(-25 - velox, veloy/1.25);
            newball2.body.gravity.setTo(0, gravity);
            newball1.size = ball.size -1;
            newball2.size = ball.size -1;
            generatePowerUp(ball);
        }
    }

    function update(){
        //la función de abajo hace que acabe la partida pero no sale bien el texto
        gameOver();
        var hitPlatform = game.physics.arcade.collide(player, platforms);
        var hitPlatform2 = game.physics.arcade.collide(player2, platforms);
        game.physics.arcade.collide(balls, platforms);
        game.physics.arcade.collide(powerups, platforms);
        game.physics.arcade.collide(bullets, platforms, killLongBullet, null, this);
        game.physics.arcade.overlap(balls, bullets, collisionBall, null, this);
        game.physics.arcade.collide(bullets2, platforms, killLongBullet2, null, this);
        game.physics.arcade.overlap(balls, bullets2, collisionBall2, null, this);
        game.physics.arcade.overlap(powerups, player, getPowerUp,null,this);
        game.physics.arcade.overlap(powerups, player2, getPowerUp2,null,this);

        if (!player1isDead){
            game.physics.arcade.overlap(balls, player, playerDeath);
        }

        if (!player2isDead){
            game.physics.arcade.overlap(balls, player2, playerDeath2);
        }

        if (newball){
            newball = false;
            setTimeout(generarBolas,tiempobolas);
            tiempobolas = tiempobolas - 1000;
        }

        player.body.velocity.x = 0;
        if(cursors.left.isDown){
            player.body.velocity.x = -150;
            player.animations.play('moveleft');
            if(player.position.x == 0 ){
                player.position.x = game.world.width;
            }
        }
        else if(cursors.right.isDown){
            player.body.velocity.x = 150;
            player.animations.play('moveright');
            if(player.position.x >= game.world.width-40){
                player.position.x = 0;
            }
        }

        else{
            player.animations.stop();
            player.frame = 4;
        }

        player2.body.velocity.x = 0;
        if(cursors2[0].isDown){
            player2.body.velocity.x = -150;
            player2.animations.play('moveleft');
            if(player2.position.x == 0 ){
                player2.position.x = game.world.width;
            }
        }
        else if(cursors2[1].isDown){
            player2.body.velocity.x = 150;
            player2.animations.play('moveright');
            if(player2.position.x >= game.world.width-40){
                player2.position.x = 0;
            }
        }

        else{
            player2.animations.stop();
            player2.frame = 4;
        }

    }

    function fireBullet(){
        var bullet = bullets.getFirstExists(false);
        if(bullet){
            bullet.reset(player.x, player.y);
            bullet.body.velocity.y = -300;
        }
    }

    function fireBullet2(){
        var bullet2 = bullets2.getFirstExists(false);
        if(bullet2){
            bullet2.reset(player2.x, player2.y);
            bullet2.body.velocity.y = -300;
        }
    }

    function resetBullet(bullet){
        bullets.kill();
    }
    function resetBullet2(bullet){
        bullets2.kill();
    }

    function fireLongBullet(){
        if(powerup1){
            if(!player1isDead){
                fireBullet();
            }
        }
        else{
            if(!firing){
                firing = true;
                long_bullet_instance.reset(player.x, player.y);
                long_bullet_instance.body.velocity.y = -200;
            }
        }
    }
    function fireLongBullet2(){
        if(powerup2){
            if(!player2isDead){
                fireBullet2();
            }
        }
        else{
            if(!firing2){
                firing2 = true;
                long_bullet_instance2.reset(player2.x, player2.y);
                long_bullet_instance2.body.velocity.y = -200;
            }
        }
    }

    function collisionBall(ball1, bullet){
        bullet.kill();
        firing = false;
        scoreplayer1 += 10;
        scoreText1.text = 'Score p1: ' + scoreplayer1;
        dividirBolas(ball1);
        ball1.kill();
    }
    function collisionBall2(ball1, bullet){
        bullet.kill();
        firing2 = false;
        scoreplayer2 += 10;
        scoreText2.text = 'Score p2: ' + scoreplayer2;
        dividirBolas(ball1);
        ball1.kill();
    }

    function killLongBullet(bullet, platform){
        if(platform.y<game.world.height-100){
            bullet.kill();
            firing = false;
        }
    }
    function killLongBullet2(bullet, platform){
        if(platform.y<game.world.height-100){
            bullet.kill();
            firing2 = false;
        }
    }

    function generatePlatforms(){
        var numberOfPlatforms = Math.floor(Math.random()* 3) +1;
        var ledge;
        var positions = [];

        for(var i = 0; i<numberOfPlatforms; i++){

            var position = new worldPosition();

            if(positions.length<=0){
                positions.push(position);
            }
            else{
                var tooClose = true;
                while(tooClose){
                    tooClose = false;
                    for(var j = 0; j<positions.length; j++){
                        var funcRet = position.checkPosition(positions[j]);
                        if(!tooClose){
                            tooClose = funcRet;
                        }
                    }
                    console.log("a");
                }
                positions.push(position);
            }

            var scaleX = Math.random() * ((0.7 - 0.5) + 0.3).toFixed(2);

            ledge = platforms.create(position.x, position.y, 'ground');
            ledge.scale.setTo(scaleX, 1);
            ledge.body.immovable = true;

        }

    }

    function worldPosition (){
        this.x = Math.floor(Math.random() *  game.world.width);
        this.y = Math.floor(Math.random() * (game.world.height - game.world.height/2)) + game.world.height/4;
        this.checkPosition = function(pos){
            if(this.y<(pos.y+50) && this.y>(pos.y-50) && this.x<(pos.x+200) && this.x>(pos.x-200)){
                this.x =  Math.floor(Math.random() *  game.world.width);
                this.y = Math.floor(Math.random() * (game.world.height - game.world.height/2)) + game.world.height/4;
               return true;
            }
            else{
                return false;
            }
        }
    }

    function playerDeath(){
        livesplayer1--;
        livesText.text = 'Lives P1: ' + livesplayer1;
        firing = true;
        player.kill();
        player1isDead = true;
        if (livesplayer1 != 0){
        setTimeout(playerReset, 1500);
        setTimeout(changeplayer1death, 3000);
        }
    }

    function playerDeath2(){
        livesplayer2--;
        livesText2.text = 'Lives P2: ' + livesplayer2;
        firing2 = true;
        player2.kill();
        player2isDead = true;
        if (livesplayer2 != 0){
        setTimeout(playerReset2, 1500);
        setTimeout(changeplayer2death, 3000);
        }
    }

    function playerReset(){
        firing = false;
        player.reset(0, game.world.height-150);
    }
    function playerReset2(){
        firing2 = false;
        player2.reset(0, game.world.height-150);
    }

    function generateBackground(){
        var background = Math.floor((Math.random() * 10) + 1);
        if (background < 5){
            sky = game.add.sprite(-180, 0, 'oeste');
        } else {
            sky = game.add.sprite(-100, 0, 'starvader');
        }
        sky.scale.setTo(0.8, 0.8);
    }

    function showGameOverText(){
        var gameoverbackground = game.add.sprite(0, 0, 'gameover');
        var stateText = game.add.text(game.world.width/2-130, game.world.height/2-50, 'GAME OVER', { fontSize: '40px', fill: '#420B3E' });
        var stateText2 = game.add.text(game.world.width/2-130, game.world.height/2, 'Volviendo a menú en 3, 2, 1...', { fontSize: '20px', fill: '#420B3E' });
    }

    function gameOver(){
        if (livesplayer1<=0 && livesplayer2<=0){
            showGameOverText();
            setTimeout(redireccionarAMenu, 3000);

        }
    }

    function redireccionarAMenu(){
        window.location.replace("index.html");
    }

    function changeplayer1death(){
        player1isDead = false;
    }

    function changeplayer2death(){
        player2isDead = false;
    }

    function generarBolas(){
        var newball3 = balls.create(400,200, 'ball');
        game.physics.enable(newball3, Phaser.Physics.ARCADE);
        newball3.body.collideWorldBounds = true;
        newball3.body.bounce.setTo(1, 1);
        newball3.scale.setTo(scake, scake);
        newball3.body.velocity.setTo(100, 100);
        newball3.body.gravity.setTo(0, gravity);
        newball3.size = 4;
        newball = true;
    }

    function generatePowerUp(ball){
        var num = Math.floor((Math.random() * 10) + 1);
        if (num > 7 ){
            var powerup = powerups.create(ball.position.x, ball.position.y, 'star');
            game.physics.arcade.enable(powerup);
            powerup.body.gravity.y = 100;
            powerup.body.collideWorldBounds = true;
        }
    }

    //
    function getPowerUp(p,pow){
        powerup1 = true;
        pow.kill();
        setTimeout(unablePowerUp1,10000);
    }
    function getPowerUp2(p,pow2){
        powerup2 = true;
        pow2.kill();
        setTimeout(unablePowerUp2,10000);
    }
    function unablePowerUp1(){
        powerup1 = false;
    }
    function unablePowerUp2(){
        powerup2 = false;
    }

});


text:
{{ flash.message }}

Tell all your friends, they should join you! A link will be included.

        {% form_for face_tweet %}
        {% hidden_field_tag "face_tweet[page_id]", flash.page_id %}

{% error_messages_for face_tweet %}

          Tweet and Facebook Text:
          {% text_field "content", class:"face-tweet-content share-url text form-control input-md" %}
          ( chars left)

          Share on:

              {% check_box "is_twitter", class:"checkbox" %} Tweet

              {% check_box "is_facebook", class:"checkbox" %} Post on Facebook

              {% submit_tag "Post", class:"btn btn-mayday" %}

              No Thanks

        {% endform_for %}