<commit_before>/**
 * Copyright (c) 2015-present, Viro, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 */

'use strict';

import React, { Platform } from 'react';
import {
  StyleSheet,
  ViroScene,
  ViroAmbientLight,
  ViroOmniLight,
  Viro360Image,
  ViroMaterials,
  ViroAnimations,
  ViroAnimatedComponent,
  ViroSkyBox,
  ViroSurface,
  Viro3DObject,
  ViroUtils,
  ViroDirectionalLight,
  ViroButton,
  ViroSphere,
  ViroImage,
  ViroNode
} from 'react-viro';

let polarToCartesian = ViroUtils.polarToCartesian;

var HomeMenuScene = React.createClass({
  getInitialState() {
    return {
      runSphereAnimation: false,
      moveForwardAnimation1: false,
      moveForwardAnimation2: false,
      button1Animation: "moveForward1",
      button2Animation: "moveForward2",
    };
  },
  render: function() {
    return (
      <ViroScene >
        <ViroAmbientLight color="#ffffff"/>

        <Viro360Image source={{uri:"https://s3-us-west-2.amazonaws.com/viro/Explorer/360_horseshoe.jpg"}}
        rotation={[0,180,0]}/>

        <Viro3DObject source={require("./res/home_logo_viro_top.obj")} position={polarToCartesian([6.5, 0, 30])}
        materials={["home_logo_viro"]} transformBehaviors={"billboardY"}/>

        <ViroSphere radius={1.7} position={polarToCartesian([6.5, -35, 9])} materials={["spherematerial1"]} />
        <ViroAnimatedComponent animation='animateSphere' run={this.state.runSphereAnimation}>
          <ViroSphere radius={1.7} position={polarToCartesian([6.5, 0, 9])} materials={["spherematerial2"]} onClick={this._onSphereClicked} facesOutward={false}/>
        </ViroAnimatedComponent>
        <ViroSphere radius={1.7} position={polarToCartesian([6.5, 35, 9])} materials={["spherematerial3"]} />

        <ViroAnimatedComponent animation={this.state.button1Animation} run={this.state.moveForwardAnimation1} onFinish={this._onAnimationFinished}>
          <ViroNode>
              <Viro3DObject source={require("./res/btn_home_a.obj")} position={polarToCartesian([6.1, -40, -20])}
              materials={["home_button_cameraroll"]} transformBehaviors={"billboardY"} onHover={this._cameraRollMoveForward}/>
              <Viro3DObject source={require("./res/home_cameraroll.obj")} position={polarToCartesian([5.8, -40, -20])}
              materials={["home_cameraroll"]} transformBehaviors={"billboardY"}/>
              <ViroImage source={require('./res/camera_roll_shadow.png')} transformBehaviors={"billboardY"} position={polarToCartesian([5.9, -41, -21])}/>
          </ViroNode>
        </ViroAnimatedComponent>
        <ViroAnimatedComponent animation={this.state.button2Animation} run={this.state.moveForwardAnimation2} onFinish={this._onAnimationFinished}>
          <ViroNode>
            <Viro3DObject source={require("./res/btn_home_a.obj")} position={polarToCartesian([6.1, -20, -20])}
            materials={["home_button_viro"]} transformBehaviors={"billboardY"} onHover={this._viroMoveForward}/>
            <Viro3DObject source={require("./res/btn_viro.obj")} position={polarToCartesian([5.8, -20, -14])}
            materials={["home_viro"]} transformBehaviors={"billboardY"} scale={[0.1,0.1,0.1]}/>
            <ViroImage source={require('./res/viro_shadow.png')} transformBehaviors={"billboardY"} position={polarToCartesian([5.9, -20.5, -20.5])}/>
          </ViroNode>
        </ViroAnimatedComponent>
        <Viro3DObject source={require("./res/btn_home_a.obj")} position={polarToCartesian([6.1, 0, -20])}
        materials={["home_button_flickr"]} transformBehaviors={"billboardY"}/>
        <Viro3DObject source={require("./res/home_global360.obj")} position={polarToCartesian([5.4, -2, -22])}
        materials={["home_flickr"]} transformBehaviors={"billboardY"} scale={[0.1,0.1,0.1]}/>
        <ViroImage source={require('./res/global360_shadow.jpg')} transformBehaviors={"billboardY"} position={polarToCartesian([5.9, 0, -20.5])} scale={[1.6,1.6,1.6]}/>

        <Viro3DObject source={require("./res/btn_home_a.obj")} position={polarToCartesian([6.1, 20, -20])}
        materials={["home_button_fblive"]} transformBehaviors={"billboardY"}/>
        <Viro3DObject source={require("./res/home_livevideo.obj")} position={polarToCartesian([5.7, 20, -20])}
        materials={["home_livevideo"]} transformBehaviors={"billboardY"}/>
        <ViroImage source={require('./res/fb_live_shadow.png')} transformBehaviors={"billboardY"} position={polarToCartesian([5.8, 20.5, -20.5])}/>

        <Viro3DObject source={require("./res/btn_home_a.obj")} position={polarToCartesian([6.1, 40, -20])}
        materials={["home_button_movie"]} transformBehaviors={"billboardY"}/>
        <Viro3DObject source={require("./res/home_movie.obj")} position={polarToCartesian([6, 40, -20])}
        materials={["home_movie"]} transformBehaviors={"billboardY"}/>
      </ViroScene>
    );
  },
  _onSphereClicked: function(source) {
      this.setState({
          runSphereAnimation: true
      });
  },
  _cameraRollMoveForward: function(source, isHovering) {
    if (isHovering) {
      this.setState({
        moveForwardAnimation1: true,
        button1Animation: 'moveForward1',
        moveForwardAnimation2: false,

      });
    } else if (!isHovering) {
      this.setState({
        moveForwardAnimation1: true,
        button1Animation: 'moveBack1',
        moveForwardAnimation2: false,
      });
    }
  },
  _viroMoveForward: function(source, isHovering) {
    if (isHovering) {
      this.setState({
        moveForwardAnimation2: true,
        button2Animation: 'moveForward2',
        moveForwardAnimation1: false,
      });
    } else if (!isHovering) {
      this.setState({
        moveForwardAnimation2: true,
        button2Animation: 'moveBack2',
        moveForwardAnimation1: false,
      });
    }
  },
  _onAnimationFinished: function() {
    this.setState({
        moveForwardAnimation1: false,
        moveForwardAnimation2: false,
      });
  }
});

ViroMaterials.createMaterials({
  home_logo_viro: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/home_logo_viro.png"),
  },
  home_cameraroll: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/camera_roll.jpg"),
  },
  home_button_cameraroll: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/button_bg_cameraroll.jpg"),
  },
  home_flickr: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/global360.jpg"),
  },
  home_button_flickr: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/button_bg_global360.jpg"),
  },
  home_viro: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/viro_logo.jpg"),
  },
  home_button_viro: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/button_bg_viro.jpg"),
  },
  home_livevideo: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/fb_live.jpg"),
  },
    home_button_fblive: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/button_bg_fblive.jpg"),
  },
  home_movie: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/fearless_train.jpg"),
  },
  home_button_movie: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/button_revoked.jpg"),
  },
  spherematerial1: {
    shininess:1.0,
    lightingModel: "Blinn",
    diffuseTexture: {uri:"http://s3-us-west-2.amazonaws.com/viro/Explorer/360_waikiki.jpg"},
  },
    spherematerial2: {
    shininess:1.0,
    lightingModel: "Blinn",
    diffuseTexture: {uri:"http://s3-us-west-2.amazonaws.com/viro/Explorer/360_wework.jpg"},
  },
  spherematerial3: {
    shininess:1.0,
    lightingModel: "Blinn",
    diffuseTexture: {uri:"http://s3-us-west-2.amazonaws.com/viro/Explorer/360_conference.jpg"},
  },

});

ViroAnimations.registerAnimations({
    animateSphere:{properties:{positionX:0.0, positionY:0.0, positionZ:0.0},
                  easing:"EaseOut",
                  duration: 700},
    moveForward1:{properties:{positionX:+0.5,positionY:+0.3,positionZ:+0.3},
                  easing:"EaseOut",
                  duration: 700},
    moveBack1:{properties:{positionX:-0.5,positionY:-0.3,positionZ:-0.3},
                  easing:"EaseOut",
                  duration: 700},
    moveForward2:{properties:{positionX:+0.5,positionY:+0.3,positionZ:+0.3},
                  easing:"EaseOut",
                  duration: 700},
    moveBack2:{properties:{positionX:-0.5,positionY:-0.3,positionZ:-0.3},
                  easing:"EaseOut",
                  duration: 700},

    cardIn:{properties:{scaleX:1, scaleY:.6, scaleZ:1, opacity: 1}, easing:"Bounce", duration: 2000},

    testLoopColorYellow:{properties:{material:"yellowColor"}, duration:3000},
    testLoopColorYellowMaterial:{properties:{material:"redColor"}, duration:3000},
    testLoopColorBlue:{properties:{material:"blueColor"}, duration:3000},
    testLoopColor:[
      ["testLoopColorYellow", "testLoopColorBlue"]
    ],
    testAnimateTexture:{properties:{material:"cardpetite"}, duration:3000},

    testMakeOpaque: {properties:{opacity:1.0}, duration: 1000},
    testMakeTransparent: {properties:{opacity:0}, duration: 1000},
    testLoopOpacity: [
      ["testMakeTransparent", "testMakeOpaque"]
    ]
});

module.exports = HomeMenuScene;<commit_msg>[Photo Viewer] Update animations to correctly use additive +=/-=<commit_after>/**
 * Copyright (c) 2015-present, Viro, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 */

'use strict';

import React, { Platform } from 'react';
import {
  StyleSheet,
  ViroScene,
  ViroAmbientLight,
  ViroOmniLight,
  Viro360Image,
  ViroMaterials,
  ViroAnimations,
  ViroAnimatedComponent,
  ViroSkyBox,
  ViroSurface,
  Viro3DObject,
  ViroUtils,
  ViroDirectionalLight,
  ViroButton,
  ViroSphere,
  ViroImage,
  ViroNode
} from 'react-viro';

let polarToCartesian = ViroUtils.polarToCartesian;

var HomeMenuScene = React.createClass({
  getInitialState() {
    return {
      runSphereAnimation: false,
      moveForwardAnimation1: false,
      moveForwardAnimation2: false,
      button1Animation: "moveForward1",
      button2Animation: "moveForward2",
    };
  },
  render: function() {
    return (
      <ViroScene >
        <ViroAmbientLight color="#ffffff"/>

        <Viro360Image source={{uri:"https://s3-us-west-2.amazonaws.com/viro/Explorer/360_horseshoe.jpg"}}
        rotation={[0,180,0]}/>

        <Viro3DObject source={require("./res/home_logo_viro_top.obj")} position={polarToCartesian([6.5, 0, 30])}
        materials={["home_logo_viro"]} transformBehaviors={"billboardY"}/>

        <ViroSphere radius={1.7} position={polarToCartesian([6.5, -35, 9])} materials={["spherematerial1"]} />
        <ViroAnimatedComponent animation='animateSphere' run={this.state.runSphereAnimation}>
          <ViroSphere radius={1.7} position={polarToCartesian([6.5, 0, 9])} materials={["spherematerial2"]} onClick={this._onSphereClicked} facesOutward={false}/>
        </ViroAnimatedComponent>
        <ViroSphere radius={1.7} position={polarToCartesian([6.5, 35, 9])} materials={["spherematerial3"]} />

        <ViroAnimatedComponent animation={this.state.button1Animation} run={this.state.moveForwardAnimation1} onFinish={this._onAnimationFinished}>
          <ViroNode>
              <Viro3DObject source={require("./res/btn_home_a.obj")} position={polarToCartesian([6.1, -40, -20])}
              materials={["home_button_cameraroll"]} transformBehaviors={"billboardY"} onHover={this._cameraRollMoveForward}/>
              <Viro3DObject source={require("./res/home_cameraroll.obj")} position={polarToCartesian([5.8, -40, -20])}
              materials={["home_cameraroll"]} transformBehaviors={"billboardY"}/>
              <ViroImage source={require('./res/camera_roll_shadow.png')} transformBehaviors={"billboardY"} position={polarToCartesian([5.9, -41, -21])}/>
          </ViroNode>
        </ViroAnimatedComponent>
        <ViroAnimatedComponent animation={this.state.button2Animation} run={this.state.moveForwardAnimation2} onFinish={this._onAnimationFinished}>
          <ViroNode>
            <Viro3DObject source={require("./res/btn_home_a.obj")} position={polarToCartesian([6.1, -20, -20])}
            materials={["home_button_viro"]} transformBehaviors={"billboardY"} onHover={this._viroMoveForward}/>
            <Viro3DObject source={require("./res/btn_viro.obj")} position={polarToCartesian([5.8, -20, -14])}
            materials={["home_viro"]} transformBehaviors={"billboardY"} scale={[0.1,0.1,0.1]}/>
            <ViroImage source={require('./res/viro_shadow.png')} transformBehaviors={"billboardY"} position={polarToCartesian([5.9, -20.5, -20.5])}/>
          </ViroNode>
        </ViroAnimatedComponent>
        <Viro3DObject source={require("./res/btn_home_a.obj")} position={polarToCartesian([6.1, 0, -20])}
        materials={["home_button_flickr"]} transformBehaviors={"billboardY"}/>
        <Viro3DObject source={require("./res/home_global360.obj")} position={polarToCartesian([5.4, -2, -22])}
        materials={["home_flickr"]} transformBehaviors={"billboardY"} scale={[0.1,0.1,0.1]}/>
        <ViroImage source={require('./res/global360_shadow.jpg')} transformBehaviors={"billboardY"} position={polarToCartesian([5.9, 0, -20.5])} scale={[1.6,1.6,1.6]}/>

        <Viro3DObject source={require("./res/btn_home_a.obj")} position={polarToCartesian([6.1, 20, -20])}
        materials={["home_button_fblive"]} transformBehaviors={"billboardY"}/>
        <Viro3DObject source={require("./res/home_livevideo.obj")} position={polarToCartesian([5.7, 20, -20])}
        materials={["home_livevideo"]} transformBehaviors={"billboardY"}/>
        <ViroImage source={require('./res/fb_live_shadow.png')} transformBehaviors={"billboardY"} position={polarToCartesian([5.8, 20.5, -20.5])}/>

        <Viro3DObject source={require("./res/btn_home_a.obj")} position={polarToCartesian([6.1, 40, -20])}
        materials={["home_button_movie"]} transformBehaviors={"billboardY"}/>
        <Viro3DObject source={require("./res/home_movie.obj")} position={polarToCartesian([6, 40, -20])}
        materials={["home_movie"]} transformBehaviors={"billboardY"}/>
      </ViroScene>
    );
  },
  _onSphereClicked: function(source) {
      this.setState({
          runSphereAnimation: true
      });
  },
  _cameraRollMoveForward: function(source, isHovering) {
    if (isHovering) {
      this.setState({
        moveForwardAnimation1: true,
        button1Animation: 'moveForward1',
        moveForwardAnimation2: false,

      });
    } else if (!isHovering) {
      this.setState({
        moveForwardAnimation1: true,
        button1Animation: 'moveBack1',
        moveForwardAnimation2: false,
      });
    }
  },
  _viroMoveForward: function(source, isHovering) {
    if (isHovering) {
      this.setState({
        moveForwardAnimation2: true,
        button2Animation: 'moveForward2',
        moveForwardAnimation1: false,
      });
    } else if (!isHovering) {
      this.setState({
        moveForwardAnimation2: true,
        button2Animation: 'moveBack2',
        moveForwardAnimation1: false,
      });
    }
  },
  _onAnimationFinished: function() {
    this.setState({
        moveForwardAnimation1: false,
        moveForwardAnimation2: false,
      });
  }
});

ViroMaterials.createMaterials({
  home_logo_viro: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/home_logo_viro.png"),
  },
  home_cameraroll: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/camera_roll.jpg"),
  },
  home_button_cameraroll: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/button_bg_cameraroll.jpg"),
  },
  home_flickr: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/global360.jpg"),
  },
  home_button_flickr: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/button_bg_global360.jpg"),
  },
  home_viro: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/viro_logo.jpg"),
  },
  home_button_viro: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/button_bg_viro.jpg"),
  },
  home_livevideo: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/fb_live.jpg"),
  },
    home_button_fblive: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/button_bg_fblive.jpg"),
  },
  home_movie: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/fearless_train.jpg"),
  },
  home_button_movie: {
    shininess:1.0,
    lightingModel: "Lambert",
    diffuseTexture: require("./res/button_revoked.jpg"),
  },
  spherematerial1: {
    shininess:1.0,
    lightingModel: "Blinn",
    diffuseTexture: {uri:"http://s3-us-west-2.amazonaws.com/viro/Explorer/360_waikiki.jpg"},
  },
    spherematerial2: {
    shininess:1.0,
    lightingModel: "Blinn",
    diffuseTexture: {uri:"http://s3-us-west-2.amazonaws.com/viro/Explorer/360_wework.jpg"},
  },
  spherematerial3: {
    shininess:1.0,
    lightingModel: "Blinn",
    diffuseTexture: {uri:"http://s3-us-west-2.amazonaws.com/viro/Explorer/360_conference.jpg"},
  },

});

ViroAnimations.registerAnimations({
    animateSphere:{properties:{positionX:0.0, positionY:0.0, positionZ:0.0},
                  easing:"EaseOut",
                  duration: 700},
    moveForward1:{properties:{positionX:"+=0.5",positionY:"+=0.3",positionZ:"+=0.3"},
                  easing:"EaseOut",
                  duration: 700},
    moveBack1:{properties:{positionX:"-=0.5",positionY:"-=0.3",positionZ:"-=0.3"},
                  easing:"EaseOut",
                  duration: 700},
    moveForward2:{properties:{positionX:"+=0.5",positionY:"+=0.3",positionZ:"+=0.3"},
                  easing:"EaseOut",
                  duration: 700},
    moveBack2:{properties:{positionX:"-=0.5",positionY:"-=0.3",positionZ:"-=0.3"},
                  easing:"EaseOut",
                  duration: 700},

    cardIn:{properties:{scaleX:1, scaleY:.6, scaleZ:1, opacity: 1}, easing:"Bounce", duration: 2000},

    testLoopColorYellow:{properties:{material:"yellowColor"}, duration:3000},
    testLoopColorYellowMaterial:{properties:{material:"redColor"}, duration:3000},
    testLoopColorBlue:{properties:{material:"blueColor"}, duration:3000},
    testLoopColor:[
      ["testLoopColorYellow", "testLoopColorBlue"]
    ],
    testAnimateTexture:{properties:{material:"cardpetite"}, duration:3000},

    testMakeOpaque: {properties:{opacity:1.0}, duration: 1000},
    testMakeTransparent: {properties:{opacity:0}, duration: 1000},
    testLoopOpacity: [
      ["testMakeTransparent", "testMakeOpaque"]
    ]
});

module.exports = HomeMenuScene;<|endoftext|>


<commit_before>/**
 * Ontology chooser JavaScript class
 *
 * NCBO wrote it's own cross-site form completion utility
 * utilizing it's json webservice. However, the service is
 * no proper json service as it does not return proper json
 * objects (just a self designed string using | for value
 * breaks and ~!~ for line breaks. Also, their implementation
 * conflicts with the table editor. Therefore, I wrote this
 * cleaner implementation using jquery-ui's autocomplete
 * functionality.
 *
 * Usage:
 * ------
 * <input type="text" name="..." rel="ontology-all-name" />
 *
 * Where the 'rel' value is the similar as the 'class' value in
 * the NCBO documentation (bp_form_complete-all-name) but here
 * we use 'ontology' instead of 'bp_form_complete' to
 * identify ontology fields.
 *
 * @author      Jeroen Wesbeek
 * @since       20100312
 * @package     wizard
 * @requires    jquery, jquery-ui
 * @see         http://bioportal.bioontology.org/ontologies/
 * @see         http://bioportal.bioontology.org/search/json_search/?q=musculus
 *
 * Revision information:
 * $Rev$
 * $Author$
 * $Date$
 */
function OntologyChooser() {
}
OntologyChooser.prototype = {
    minLength   : 3,    // minimum input length before launching Ajax request
    cache       : [],   // ontology cache

    /**
     * initialize object
     */
    init: function() {
        var that = this;

        // find all ontology elements
        $("input[rel*='ontology']").each(function() {
            that.initAutocomplete(this);
        });
    },

    /**
     * initialize the ontology autocompleter
     * @param element
     */
    initAutocomplete: function(element) {
        var that = this
        var inputElement = $(element);
        var selected = false;

        // determine what ontology to use
        var values = inputElement.attr('rel').split("-");
        var ontology_id = values[1];
        var target_property = values[2];
        if (ontology_id == "all") { ontology_id = ""; }

        // http://bioportal.bioontology.org/search/json_search/?q=musculus
        inputElement.autocomplete({
            minLength: that.minLength,
            delay: 300,
            search: function(event, ui) {
                selected = false;
            },
            source: function(request, response) {
                var q = $.trim(request.term);
                var url = "http://bioportal.bioontology.org/search/json_search/"+ontology_id+"?q=" + request.term + "&response=json&callback=?";

                // got cache?
                if (that.cache[ q ]) {
                    // yeah, lucky us! ;-P
                    response(that.cache[ q ]);
                } else {
                    // nope, fetch it from NCBO
                    $.getJSON(url, function(data) {
                        // parse result data
                        var result = that.parseData(data.data);

                        // cache results
                        that.cache[ q ] = result;

                        // response callback
                        response(that.parseData(data.data));
                    });
                }
            },
            select: function(event, ui) {
                // mark that the user selected a suggestion
                selected = true;

                // option selected, set hidden fields
                var element = inputElement;

                // set hidden fields
                that.setInputValue(element, 'concept_id', ui.item.concept_id);
                that.setInputValue(element, 'ontology_id', ui.item.ontology_id);
                that.setInputValue(element, 'full_id', ui.item.full_id);

                // remove error class (if present)
                element.removeClass('error');
            },
            close: function(event, ui) {
                // check if the user picked something from the ontology suggestions
                if (!selected) {
                    // no he didn't, clear the field(s)
                    var element = inputElement;

                    // set fields
                    inputElement.val('');
                    that.setInputValue(element, 'concept_id', '');
                    that.setInputValue(element, 'ontology_id', '');
                    that.setInputValue(element, 'full_id', '');

                    // add error class
                    element.addClass('error');
                }
            }

        });
    },

    /**
     * Set the value of a particular DOM element
     * @param inputElement
     * @param name
     * @param value
     */
    setInputValue: function(inputElement, name, value) {
        var elementName = inputElement.attr('name') + '-' + name;
        var searchElement = inputElement.parent().find("input[name='" + elementName + "']");

        // got a text/hidden field in the DOM?
        if (searchElement.size() > 0) {
            // yeah, set it
            $(searchElement[0]).val(value);
        } else {
            // no, dynamically insert it after the input elemtn
            inputElement.after('<input type="hidden" name="' + elementName + '" value="' + value + '"/>');
        }
    },

    /**
     * Parse the result data
     *
     * Data is in the following format:
     * Mus musculus musculus|birnlex_161|preferred name|29684|http://bioontology.org/projects/ontologies/birnlex#birnlex_161|Mus musculus musculus|Mus musculus musculus|BIRNLex~!~
     *
     * Where | codes for a column break, and ~!~ for
     * a line break
     *
     * @param data
     * @return array
     */
    parseData: function(data) {
        var parsed = [];
        var rows = data.split('~!~');

        for (var i=0; i<rows.length; i++) {
            var row = $.trim(rows[i]);
            if (row) {
                var cols = row.split('|');

                parsed[ parsed.length ] = {
                    value           : cols[0],
                    label           : cols[0] + ' (' + cols[2] + ') from: ' + cols[ (cols.length-1) ] + '',
                    preferred_name  : cols[0],  // e.g. Mus musculus musculus
                    concept_id      : cols[1],  // e.g. birnlex_161
                    ontology_id     : cols[3],  // e.g. 29684
                    full_id         : cols[4]   // e.g. http://bioontology.org/projects/ontologies/birnlex#birnlex_161
                }
            }
        }

        return parsed;
    }
}<commit_msg>- text error<commit_after>/**
 * Ontology chooser JavaScript class
 *
 * NCBO wrote it's own cross-site form completion utility
 * utilizing it's json webservice. However, the service is
 * no proper json service as it does not return proper json
 * objects (just a self designed string using | for value
 * breaks and ~!~ for line breaks. Also, their implementation
 * conflicts with the table editor. Therefore, I wrote this
 * cleaner implementation using jquery-ui's autocomplete
 * functionality.
 *
 * Usage:
 * ------
 * <input type="text" name="..." rel="ontology-all-name" />
 *
 * Where the 'rel' value is the similar as the 'class' value in
 * the NCBO documentation (bp_form_complete-all-name) but here
 * we use 'ontology' instead of 'bp_form_complete' to
 * identify ontology fields.
 *
 * @author      Jeroen Wesbeek
 * @since       20100312
 * @package     wizard
 * @requires    jquery, jquery-ui
 * @see         http://bioportal.bioontology.org/ontologies/
 * @see         http://bioportal.bioontology.org/search/json_search/?q=musculus
 *
 * Revision information:
 * $Rev$
 * $Author$
 * $Date$
 */
function OntologyChooser() {
}
OntologyChooser.prototype = {
    minLength   : 3,    // minimum input length before launching Ajax request
    cache       : [],   // ontology cache

    /**
     * initialize object
     */
    init: function() {
        var that = this;

        // find all ontology elements
        $("input[rel*='ontology']").each(function() {
            that.initAutocomplete(this);
        });
    },

    /**
     * initialize the ontology autocompleter
     * @param element
     */
    initAutocomplete: function(element) {
        var that = this
        var inputElement = $(element);
        var selected = false;

        // determine what ontology to use
        var values = inputElement.attr('rel').split("-");
        var ontology_id = values[1];
        var target_property = values[2];
        if (ontology_id == "all") { ontology_id = ""; }

        // http://bioportal.bioontology.org/search/json_search/?q=musculus
        inputElement.autocomplete({
            minLength: that.minLength,
            delay: 300,
            search: function(event, ui) {
                selected = false;
            },
            source: function(request, response) {
                var q = $.trim(request.term);
                var url = "http://bioportal.bioontology.org/search/json_search/"+ontology_id+"?q=" + request.term + "&response=json&callback=?";

                // got cache?
                if (that.cache[ q ]) {
                    // yeah, lucky us! ;-P
                    response(that.cache[ q ]);
                } else {
                    // nope, fetch it from NCBO
                    $.getJSON(url, function(data) {
                        // parse result data
                        var result = that.parseData(data.data);

                        // cache results
                        that.cache[ q ] = result;

                        // response callback
                        response(that.parseData(data.data));
                    });
                }
            },
            select: function(event, ui) {
                // mark that the user selected a suggestion
                selected = true;

                // option selected, set hidden fields
                var element = inputElement;

                // set hidden fields
                that.setInputValue(element, 'concept_id', ui.item.concept_id);
                that.setInputValue(element, 'ontology_id', ui.item.ontology_id);
                that.setInputValue(element, 'full_id', ui.item.full_id);

                // remove error class (if present)
                element.removeClass('error');
            },
            close: function(event, ui) {
                // check if the user picked something from the ontology suggestions
                if (!selected) {
                    // no he didn't, clear the field(s)
                    var element = inputElement;

                    // set fields
                    inputElement.val('');
                    that.setInputValue(element, 'concept_id', '');
                    that.setInputValue(element, 'ontology_id', '');
                    that.setInputValue(element, 'full_id', '');

                    // add error class
                    element.addClass('error');
                }
            }

        });
    },

    /**
     * Set the value of a particular DOM element
     * @param inputElement
     * @param name
     * @param value
     */
    setInputValue: function(inputElement, name, value) {
        var elementName = inputElement.attr('name') + '-' + name;
        var searchElement = inputElement.parent().find("input[name='" + elementName + "']");

        // got a text/hidden field in the DOM?
        if (searchElement.size() > 0) {
            // yeah, set it
            $(searchElement[0]).val(value);
        } else {
            // no, dynamically insert it after the input element
            inputElement.after('<input type="hidden" name="' + elementName + '" value="' + value + '"/>');
        }
    },

    /**
     * Parse the result data
     *
     * Data is in the following format:
     * Mus musculus musculus|birnlex_161|preferred name|29684|http://bioontology.org/projects/ontologies/birnlex#birnlex_161|Mus musculus musculus|Mus musculus musculus|BIRNLex~!~
     *
     * Where | codes for a column break, and ~!~ for
     * a line break
     *
     * @param data
     * @return array
     */
    parseData: function(data) {
        var parsed = [];
        var rows = data.split('~!~');

        for (var i=0; i<rows.length; i++) {
            var row = $.trim(rows[i]);
            if (row) {
                var cols = row.split('|');

                parsed[ parsed.length ] = {
                    value           : cols[0],
                    label           : cols[0] + ' (' + cols[2] + ') from: ' + cols[ (cols.length-1) ] + '',
                    preferred_name  : cols[0],  // e.g. Mus musculus musculus
                    concept_id      : cols[1],  // e.g. birnlex_161
                    ontology_id     : cols[3],  // e.g. 29684
                    full_id         : cols[4]   // e.g. http://bioontology.org/projects/ontologies/birnlex#birnlex_161
                }
            }
        }

        return parsed;
    }
}<|endoftext|>


<commit_before>casper.on('remote.message', function(message) {
    this.echo('Message: '+ JSON.stringify(message));
});

casper.on('page.error', function(message, trace) {
    this.echo('Page error: ' + message);
    this.echo(JSON.stringify(trace));
});

casper.on('page.initialized', function() {
    this.evaluate(function() {
        if (!Function.prototype.bind) {
            Function.prototype.bind = function(oThis) {
                if (typeof this !== 'function') {
                    // closest thing possible to the ECMAScript 5
                    // internal IsCallable function
                    throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
                }

                var aArgs   = Array.prototype.slice.call(arguments, 1),
                    fToBind = this,
                    fNOP    = function() {},
                    fBound  = function() {
                        return fToBind.apply(this instanceof fNOP
                                             ? this
                                             : oThis,
                                             aArgs.concat(Array.prototype.slice.call(arguments)));
                    };

                if (this.prototype) {
                    // native functions don't have a prototype
                    fNOP.prototype = this.prototype;
                }
                fBound.prototype = new fNOP();

                return fBound;
            };
        }
        console.log("RegExp.prototype.bind has been polyfilled");
    });
});

casper.test.begin('Test the project-m-staging', 22, function suite(test) {
    var url = casper.cli.get("url")

    casper.start(url,function() {
        test.assertTitle("Pirate Party Membership");
        var js = this.evaluate(function() {
            return document;
        });
        this.echo('Here is the DOM: ' + js.all[0].outerHTML);
    });

    casper.then(function () {
        test.assertSelectorHasText('h1.form-title', 'Membership Type');  //find the title
    });

    casper.then(function () {
        //test for not enrolled Australian citizen to vote in Australia
        this.click('input[name="isEnrolled"][value="No"]');
        this.click('input[name="residentialStatus"][value="I am an Australian citizen."]');
        this.click('input[name="isMemberOfOtherParty"][value="Yes"]');

        test.assertExist('div.validationErrors');
    });

     // test for supporter membership type
    casper.then(function() {
        this.click('input[name="isEnrolled"][value="Yes"]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Supporter Membership.');
    });

    casper.then(function() {
        this.click('input[name="isEnrolled"][value="No"]');
        this.click('input[name="residentialStatus"][value="I have a Permanent Resident visa."]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Supporter Membership.');
    });

    //test for full membership type
    casper.then(function() {
        this.click('input[name="isEnrolled"][value="Yes"]');
        this.click('input[name="residentialStatus"][value="I am an Australian citizen."]');
        this.click('input[name="isMemberOfOtherParty"][value="No"]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Full Membership.');
    });

    //test for permanent resident membership type
    casper.then(function() {
       this.click('input[name="isEnrolled"][value="No"]');
       this.click('input[name="residentialStatus"][value="I have a Permanent Resident visa."]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to a Permanent Resident Membership.');
    });

    //test for international membership type
    casper.then(function() {
       this.click('input[name="residentialStatus"][value="I am an international citizen or have a Temporary visa."]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to an International Membership.');
    });

    casper.then(function() {
       this.click('input[name="isMemberOfOtherParty"][value="No"]');

       test.assertExist('div.info-box');
       test.assertSelectorHasText('h3', 'You are entitled to an International Membership.');
    });

    //test for jump to second page
    casper.then(function() {
        this.click('button');
        casper.then(function() {
            test.assertSelectorHasText('h1.form-title', 'Details');
        });
    });

// Details page tests

    //Residential Address = Postal Address

    casper.then(function() {
      this.sendKeys('input[id=firstName]', 'Connor');
      this.sendKeys('input[id=lastName]', 'Melbourne');
      this.sendKeys('input[id=dateOfBirth]', '12/08/2014');
      this.sendKeys('input[id="residentialAddress[address]"]', 'Laboriosam at inventore unde quo iure adipisicing ut voluptas sed soluta ut');
      this.sendKeys('input[id="residentialAddress[suburb]"]', 'Incidunt modi necessitatibus rem vitae modi eiusmod voluptatem numquam corporis laboriosam consequatur Eos reprehenderit');
      this.evaluate(function () {
        return document.getElementById("residentialAddress[country]").selectedIndex = 38;
      });

      this.evaluate(function () {
        return document.getElementById("residentialAddress[state]").selectedIndex = 1;
      });

      this.sendKeys('input[id="residentialAddress[postcode]"]', '35191');
      this.sendKeys('input[id=email]', 'qoku'+Math.random()+'@gmail.com');
      this.sendKeys('input[id=primaryPhoneNumber]', '0412345678');

      //jump to the Confirm page
      this.click('button');

      casper.then(function() {
          this.capture('screenshots/screenshot-click.png');
          test.assertSelectorHasText('h1.form-title', 'Confirm');
      });
    });
     //go back to the Details page

      casper.then(function() {
           this.click('a#go-back');
           test.assertSelectorHasText('h1.form-title', 'Details');
      });

    //check the postal address not same as residential address

    casper.then(function() {
           this.click('input[type="checkbox"]', 'Yes');
    });
    //fill in the postal address

    casper.then(function() {
      this.evaluate(function () {
        return document.getElementById("residentialAddress[country]").selectedIndex = 38;
      });

      this.evaluate(function () {
        return document.getElementById("residentialAddress[state]").selectedIndex = 1;
      });
      this.sendKeys('input[id="postalAddress"]', '1 Margaret Street');
      this.sendKeys('input[id="postalAddress[suburb]"]', 'Cambridge');
      this.evaluate(function () {
        return document.getElementById("postalAddress[country]").selectedIndex = 13;
      });
      this.evaluate(function () {
        return document.getElementById("postalAddress[state]").selectedIndex = 7;
      });
      this.sendKeys('input[id="postalAddress[postcode]"]', '3001');

      this.click('button');

      casper.then(function() {
          this.capture('screenshots/screenshot-click.png');
          test.assertSelectorHasText('h1.form-title', 'Confirm');
      });
    });

    // Confirm page tests

    casper.then(function() {
        this.click('input[type="checkbox"]', 'circumstance');

        this.click('button');

      casper.then(function() {
        this.wait(1000,function() {

        this.capture('screenshots/screenshot-click.png');
        test.assertSelectorHasText('h1.form-title', 'Pay What You Want');
        });
      });
    });

  //Pay What You Want page

      //     //no contribute----passed
      // casper.then(function() {
      //     this.click('input[name="paymentType"][value="noContribute"]');
      //
      //     this.click('button');
      //
      //   casper.then(function() {
      //     this.wait(2000,function() {
      //     this.capture('screenshots/screenshot-click.png');
      //     test.assertSelectorHasText('h1.form-title', 'Finish');
      //     });
      //   });
      // });

      //Direct Deposit----with $20 deposit
       casper.then(function() {
           this.click('input[name="paymentType"][value="deposit"]');
           this.sendKeys('input[id=totalAmount]','20');

           this.click('button');

          casper.then(function() {
              this.wait(2000,function() {
              this.capture('screenshots/screenshot-click.png');

              test.assertSelectorHasText('h1.form-title', 'Finish');
              });
          });
      });

     //Finish page
      casper.then(function() {

        this.click('button');

      casper.then(function() {
        this.wait(2000,function() {
        this.capture('screenshots/screenshot-click.png');

        test.assertTitle("Pirate Party Membership");
        });
      });
     });

    casper.run(function () {
        test.done();
    });
});
<commit_msg>Code styling<commit_after>casper.on('remote.message', function (message) {
    this.echo('Message: ' + JSON.stringify(message));
});

casper.on('page.error', function (message, trace) {
    this.echo('Page error: ' + message);
    this.echo(JSON.stringify(trace));
});

casper.on('page.initialized', function () {
    this.evaluate(function () {
        if (!Function.prototype.bind) {
            Function.prototype.bind = function (oThis) {
                if (typeof this !== 'function') {
                    // closest thing possible to the ECMAScript 5
                    // internal IsCallable function
                    throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
                }

                var aArgs = Array.prototype.slice.call(arguments, 1),
                    fToBind = this,
                    fNOP = function () {
                    },
                    fBound = function () {
                        return fToBind.apply(this instanceof fNOP
                                ? this
                                : oThis,
                            aArgs.concat(Array.prototype.slice.call(arguments)));
                    };

                if (this.prototype) {
                    // native functions don't have a prototype
                    fNOP.prototype = this.prototype;
                }
                fBound.prototype = new fNOP();

                return fBound;
            };
        }
        console.log("RegExp.prototype.bind has been polyfilled");
    });
});

casper.test.begin('Test the project-m-staging', 22, function suite(test) {
    var url = casper.cli.get("url");

    casper.start(url, function () {
        test.assertTitle("Pirate Party Membership");
        var js = this.evaluate(function () {
            return document;
        });
        this.echo('Here is the DOM: ' + js.all[0].outerHTML);
    });

    casper.then(function () {
        test.assertSelectorHasText('h1.form-title', 'Membership Type');  //find the title
    });

    casper.then(function () {
        //test for not enrolled Australian citizen to vote in Australia
        this.click('input[name="isEnrolled"][value="No"]');
        this.click('input[name="residentialStatus"][value="I am an Australian citizen."]');
        this.click('input[name="isMemberOfOtherParty"][value="Yes"]');

        test.assertExist('div.validationErrors');
    });

    // test for supporter membership type
    casper.then(function () {
        this.click('input[name="isEnrolled"][value="Yes"]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Supporter Membership.');
    });

    casper.then(function () {
        this.click('input[name="isEnrolled"][value="No"]');
        this.click('input[name="residentialStatus"][value="I have a Permanent Resident visa."]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Supporter Membership.');
    });

    //test for full membership type
    casper.then(function () {
        this.click('input[name="isEnrolled"][value="Yes"]');
        this.click('input[name="residentialStatus"][value="I am an Australian citizen."]');
        this.click('input[name="isMemberOfOtherParty"][value="No"]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Full Membership.');
    });

    //test for permanent resident membership type
    casper.then(function () {
        this.click('input[name="isEnrolled"][value="No"]');
        this.click('input[name="residentialStatus"][value="I have a Permanent Resident visa."]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to a Permanent Resident Membership.');
    });

    //test for international membership type
    casper.then(function () {
        this.click('input[name="residentialStatus"][value="I am an international citizen or have a Temporary visa."]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to an International Membership.');
    });

    casper.then(function () {
        this.click('input[name="isMemberOfOtherParty"][value="No"]');

        test.assertExist('div.info-box');
        test.assertSelectorHasText('h3', 'You are entitled to an International Membership.');
    });

    //test for jump to second page
    casper.then(function () {
        this.click('button');
        casper.then(function () {
            test.assertSelectorHasText('h1.form-title', 'Details');
        });
    });

// Details page tests

    //Residential Address = Postal Address

    casper.then(function () {
        this.sendKeys('input[id=firstName]', 'Connor');
        this.sendKeys('input[id=lastName]', 'Melbourne');
        this.sendKeys('input[id=dateOfBirth]', '12/08/2014');
        this.sendKeys('input[id="residentialAddress[address]"]', 'Laboriosam at inventore unde quo iure adipisicing ut voluptas sed soluta ut');
        this.sendKeys('input[id="residentialAddress[suburb]"]', 'Incidunt modi necessitatibus rem vitae modi eiusmod voluptatem numquam corporis laboriosam consequatur Eos reprehenderit');
        this.evaluate(function () {
            return document.getElementById("residentialAddress[country]").selectedIndex = 38;
        });

        this.evaluate(function () {
            return document.getElementById("residentialAddress[state]").selectedIndex = 1;
        });

        this.sendKeys('input[id="residentialAddress[postcode]"]', '35191');
        this.sendKeys('input[id=email]', 'qoku' + Math.random() + '@gmail.com');
        this.sendKeys('input[id=primaryPhoneNumber]', '0412345678');

        //jump to the Confirm page
        this.click('button');

        casper.then(function () {
            this.capture('screenshots/screenshot-click-details.png');
            test.assertSelectorHasText('h1.form-title', 'Confirm');
        });
    });

    //go back to the Details page
    casper.then(function () {
        this.click('a#go-back');
        test.assertSelectorHasText('h1.form-title', 'Details');
    });

    //check the postal address not same as residential address
    casper.then(function () {
        this.click('input[type="checkbox"]', 'Yes');
    });

    //fill in the postal address
    casper.then(function () {
        this.evaluate(function () {
            return document.getElementById("residentialAddress[country]").selectedIndex = 38;
        });

        this.evaluate(function () {
            return document.getElementById("residentialAddress[state]").selectedIndex = 1;
        });
        this.sendKeys('input[id="postalAddress"]', '1 Margaret Street');
        this.sendKeys('input[id="postalAddress[suburb]"]', 'Cambridge');
        this.evaluate(function () {
            return document.getElementById("postalAddress[country]").selectedIndex = 13;
        });
        this.evaluate(function () {
            return document.getElementById("postalAddress[state]").selectedIndex = 7;
        });
        this.sendKeys('input[id="postalAddress[postcode]"]', '3001');

        this.click('button');

        casper.then(function () {
            this.capture('screenshots/screenshot-click.png');
            test.assertSelectorHasText('h1.form-title', 'Confirm');
        });
    });

    // Confirm page tests
    casper.then(function () {
            this.click('input[type="checkbox"]', 'circumstance');
        })
        .then(function () {
            this.click('button');
        })
        .then(function () {
            this.wait(1000, function () {

                this.capture('screenshots/screenshot-click-confirm.png');
                test.assertSelectorHasText('h1.form-title', 'Pay What You Want');
            });
        });

    //Pay What You Want page
    //Direct Deposit----with $20 deposit
    casper.then(function () {
        this.click('input[name="paymentType"][value="deposit"]');
        this.sendKeys('input[id=totalAmount]', '20');

        this.click('button');

        casper.then(function () {
            this.wait(2000, function () {
                this.capture('screenshots/screenshot-click-payment.png');

                test.assertSelectorHasText('h1.form-title', 'Finish');
            });
        });
    });

    //Finish page
    casper.then(function () {

        this.click('button');

        casper.then(function () {
            this.wait(2000, function () {
                this.capture('screenshots/screenshot-click-final.png');

                test.assertTitle("Pirate Party Membership");
            });
        });
    });

    casper.run(function () {
        test.done();
    });
});
<|endoftext|>


<commit_before>var etClass = "";
var academic = scoreaiacademic;
var rawWriting = bSttrRawWsScore;

// Require an ET score for everyone:

if (scoreet === null) {
    etClass = "XX-500";
}

// Handle eligibility for ET Fundamentals course:

else if (scoreet >= 0 && scoreet <= 13) {

    // Only require a Raw Writing score if the other two scores
    // are both in the danger zone:

    if (academic <= 2 && rawWriting === null) {
        etClass = "XX-520";
    }
    else if (academic === 0 && rawWriting <= 40) {
        etClass = "ET-110";
    }
    else if (scoreet <= 6 && academic === 1 && rawWriting <= 40) {
        etClass = "ET-110";
    }
    else if (scoreet <= 6 && academic === 2 && rawWriting <= 20) {
        etClass = "ET-110";
    }
    else if (academic === 1 && rawWriting <= 20) {
        etClass = "ET-110";
    }
    else {
        etClass = "ET-111";
    }
}

// Handle the regular ET placements:

else if (scoreet <= 16) {
    etClass = "ET-112";
}
else if (scoreet <= 19) {
    etClass = "ET-211";
}
else if (scoreet <= 22)
{
    etClass = "ET-212";
}

// Render the score:

if (coursenumberactive.join().search(etClass) > -1)
{
    "
"+etClass+": done.";
}
else
{
    "
"+etClass+": needed.";
}
<commit_msg>comment<commit_after>var etClass = "";
var academic = scoreaiacademic;
var rawWriting = bSttrRawWsScore;

// Require an ET score for everyone:

if (scoreet === null) {
    etClass = "XX-500";
}

// Handle eligibility for ET Fundamentals course:

else if (scoreet >= 0 && scoreet <= 13) {

    // Only require a Raw Writing score if the other two scores
    // are both in the danger zone:

    if (academic <= 2 && rawWriting === null) {
        etClass = "XX-520";
    }
    else if (academic === 0 && rawWriting <= 40) {
        etClass = "ET-110";
    }
    else if (scoreet <= 6 && academic === 1 && rawWriting <= 40) {
        etClass = "ET-110";
    }
    else if (scoreet <= 6 && academic === 2 && rawWriting <= 20) {
        etClass = "ET-110";
    }
    else if (academic === 1 && rawWriting <= 20) {
        etClass = "ET-110";
    }
    else {
        etClass = "ET-111";
    }
}

// Handle the regular ET placements:

else if (scoreet <= 16) {
    etClass = "ET-112";
}
else if (scoreet <= 19) {
    etClass = "ET-211";
}
else if (scoreet <= 22)
{
    etClass = "ET-212";
}

// Render the score:

if (coursenumberactive.join().search(etClass) > -1)
{
    "
"+etClass+": done.";
}
else
{
    "
"+etClass+": needed.";
}<|endoftext|>


<commit_before>'use strict';

var malApp = angular.module('malApp', [
    'ngRoute',
    'ngCookies',
    'ui.bootstrap',
    'ngTagsInput'
]);

malApp.config(function($routeProvider) {

    // Define the routes
    $routeProvider
        .when('/', {
            templateUrl: 'partials/index.html',
            controller: 'IndexController'
        })
        .when('/login', {
            templateUrl: 'partials/login-required.html',
            controller: 'LoginController'
        })
        .when('/logout', {
            templateUrl: 'partials/logout.html',
            controller: 'LogoutController'
        })
        .when('/test', {
            templateUrl: 'partials/test.html',
            controller: 'TestController'
        })
        .when('/bookmarks/:id', {
            templateUrl: 'partials/bookmark.html',
            controller: 'BookmarkController'
        })
        .when('/bookmarks', {
            templateUrl: 'partials/bookmarks.html',
            controller: 'BookmarksController'
        })
        .when('/bookmarks/group/:groupId', {
            templateUrl: 'partials/bookmarks.html',
            controller: 'BookmarksOfGroupController'
        })
        .when('/groups', {
            templateUrl: 'partials/groups.html',
            controller: 'GroupsController'
        })
        .when('/groups/:id', {
            templateUrl: 'partials/group.html',
            controller: 'GroupController'
        })
        .when('/tags', {
            templateUrl: 'partials/tags.html',
            controller: 'TagsController'
        })
        .when('/tags/:id', {
            templateUrl: 'partials/tag.html',
            controller: 'TagController'
        })
        .otherwise({
            redirectTo: '/'
        });

});

malApp.run(function($rootScope, $http, $location, $window, $cookies) {

    $rootScope.pageTitle = 'Bookmarkly';

    $rootScope.sessionUser = $cookies.getObject('bookmarklyLogin');

    if ($rootScope.sessionUser) {

        $http.post('/validatetoken', { token: $rootScope.sessionUser.token })
            .then(function() {
                console.log('Token %s is valid', $rootScope.sessionUser.token);
                console.log('Welcome back, %s', $rootScope.sessionUser.username);
                bootstrapApp($rootScope, $http);
            }, function(response) {
                $rootScope.sessionUser = null;
                $cookies.remove('bookmarklyLogin');
                console.log(JSON.stringify(response));
                //console.log('Redirecting you to the login page');
                //$window.location = '/login.html';
            });

    }

    $rootScope.$on('$locationChangeStart', function(event, next, current) {

        $rootScope.previousPage = current;

        if (!$rootScope.sessionUser) {
            $location.path('/login');
        }
    });

});

malApp.controller('IndexController', function($rootScope) {
});

malApp.controller('TestController', function($rootScope) {
});

malApp.controller('LoginController', function($rootScope, $window) {

    var delay = ($rootScope.config ? $rootScope.config.loginRedirectDelay : 5000);
    var location = ($rootScope.config ? $rootScope.config.baseUrl + $rootScope.config.loginAppPath : '/login.html');

    setTimeout(function() {
        $window.location = location;
    }, delay);

});

malApp.controller('LogoutController', function($rootScope, $cookies, $window) {

    $cookies.remove('bookmarklyLogin');
    $rootScope.sessionUser = null;

    if ($rootScope.config.logoutRedirectDelay > 0) {
        setTimeout(function() {
            $window.location = $rootScope.config.baseUrl + $rootScope.config.loginAppPath;
        }, $rootScope.config.logoutRedirectDelay);
    }

});

malApp.controller('BookmarksController', function($scope, $rootScope, $http, $window) {

    $http.get($rootScope.config.baseUrl + '/bookmarks?token=' + $rootScope.sessionUser.token)
        .success(function(data) {
            //console.log('bookmarks: ' + JSON.stringify(data));
            $scope.bookmarks = data;

            //$http.get($rootScope.config.baseUrl + '/groups/' + $routeParams.groupId + '?token=' + $rootScope.sessionUser.token)
            //    .success(function(data) {
            //        //console.log(data);
            //        $scope.group = data[0] || data;
            //    });
        });

    $scope.editBookmark = function(id) {
        $window.location = '#/bookmarks/' + id;
    };

});

malApp.controller('BookmarkController', function($scope, $rootScope, $routeParams, $http, $window, $q) {

    $('#title').focus();

    $scope.groups = [];
    $scope.tags = [];

    $scope.loadGroups = function(query) {

        var deferred = $q.defer();

        $http.get($rootScope.config.baseUrl + '/groups?token=' + $rootScope.sessionUser.token + '&search=' + query)
            .success(function(data) {
                var retArray = [{text: query}];

                if (data && data.length > 0) {
                    data.forEach(function(item) {
                        retArray.push({text: item.name});
                    });

                }

                deferred.resolve(retArray);
            });

        return deferred.promise;
    };

    $scope.loadTags = function(query) {

        var deferred = $q.defer();

        $http.get($rootScope.config.baseUrl + '/tags?token=' + $rootScope.sessionUser.token + '&search=' + query)
            .success(function(data) {
                var retArray = [{text: query}];

                if (data && data.length > 0) {
                    data.forEach(function(item) {
                        retArray.push({text: item.name});
                    });

                }

                deferred.resolve(retArray);
            });

        return deferred.promise;
    };

    if ($routeParams.id === 'new') {
        $scope.bookmark = {
            rating: 1
        };
    } else {
        $http.get($rootScope.config.baseUrl + '/bookmarks/' + $routeParams.id + '?token=' + $rootScope.sessionUser.token)
            .success(function(data) {
                $scope.bookmark = data[0] || data;

                if ($scope.bookmark && $scope.bookmark.groups) {

                    var tmpGroupArray = [];

                    $scope.bookmark.groups.forEach(function(groupItem) {
                        tmpGroupArray.push(groupItem.name);
                    });

                    if (tmpGroupArray && tmpGroupArray.length > 0) {
                        $scope.groups = tmpGroupArray;
                    }
                }

                if ($scope.bookmark && $scope.bookmark.tags) {

                    var tmpTagArray = [];

                    $scope.bookmark.tags.forEach(function(tagItem) {
                        tmpTagArray.push(tagItem.name);
                    });

                    if (tmpTagArray && tmpTagArray.length > 0) {
                        $scope.tags = tmpTagArray;
                    }
                }
            });
    }

    $scope.save = function() {

        var bookmarkWrapper = {
            model: $scope.bookmark,
            groupNames: [],
            tagNames: []
        };

        delete bookmarkWrapper.model.groups;
        delete bookmarkWrapper.model.tags;

        if ($scope.groups && $scope.groups.length > 0) {
            $scope.groups.forEach(function(item) {
                bookmarkWrapper.groupNames.push(item.text);
            });
        }

        if ($scope.tags && $scope.tags.length > 0) {
            $scope.tags.forEach(function(item) {
                bookmarkWrapper.tagNames.push(item.text);
            });
        }

        if ($routeParams.id === 'new') {

            bookmarkWrapper.model.userId = $rootScope.sessionUser.userId;
            bookmarkWrapper.dateCreated = moment().format('YYYY-MM-DD HH:mm:ss');  // TODO: Get format from config

            $http.post($rootScope.config.baseUrl + '/bookmarks?token=' + $rootScope.sessionUser.token, bookmarkWrapper)
                .success(function() {
                    if ($rootScope.previousPage) {
                        $window.location = $rootScope.previousPage;
                    }
                }, function(err) {
                    console.log(err);
                });
        } else {

            $http.put($rootScope.config.baseUrl + '/bookmarks?token=' + $rootScope.sessionUser.token, bookmarkWrapper)
                .success(function() {
                    if ($rootScope.previousPage) {
                        $window.location = $rootScope.previousPage;
                    }
                }, function(err) {
                    console.log(err);
                });
        }
    }

});

malApp.controller('BookmarksOfGroupController', function($scope, $rootScope, $routeParams, $http, $window) {

    $http.get($rootScope.config.baseUrl + '/bookmarks/group/' + $routeParams.groupId + '?token=' + $rootScope.sessionUser.token)
        .then(function(data) {
            $scope.bookmarks = data.data;

            $http.get($rootScope.config.baseUrl + '/groups/' + $routeParams.groupId + '?token=' + $rootScope.sessionUser.token)
                .then(function(response) {
                    $scope.group = response.data[0] || response.data;
                }, function(response) {
                    console.log(JSON.stringify(response));
                });
        }, function(response) {
            console.log(JSON.stringify(response));
        });

    $scope.editBookmark = function(id) {
        $window.location = '#/bookmarks/' + id;
    };

});

malApp.controller('GroupsController', function($scope, $rootScope, $http, $window) {

    $http.get($rootScope.config.baseUrl + '/groups?token=' + $rootScope.sessionUser.token)
        .success(function(data) {
            $scope.groups = data;
        });

    $scope.editGroup = function(id) {
        $window.location = '#/groups/' + id;
    };

});

malApp.controller('GroupController', function($scope, $rootScope, $routeParams, $http, $window) {

    $('#name').focus();

    if ($routeParams.id === 'new') {
        $scope.group = {};
    } else {
        $http.get($rootScope.config.baseUrl + '/groups/' + $routeParams.id + '?token=' + $rootScope.sessionUser.token)
            .success(function(data) {
                $scope.group = data[0] || data;
            });
    }

    $scope.save = function() {

        if ($routeParams.id === 'new') {

            $scope.group.userId = $rootScope.sessionUser.userId;
            $scope.group.dateCreated = moment().format('YYYY-MM-DD HH:mm:ss');  // TODO: Get format from config

            $http.post($rootScope.config.baseUrl + '/groups?token=' + $rootScope.sessionUser.token, $scope.group)
                .success(function() {
                    if ($rootScope.previousPage) {
                        $window.location = '#/groups';
                    }
                }, function(err) {
                    console.log(err);
                });
        } else {
            $http.put($rootScope.config.baseUrl + '/groups?token=' + $rootScope.sessionUser.token, $scope.group)
                .success(function() {
                    if ($rootScope.previousPage) {
                        $window.location = '#/groups';
                    }
                }, function(err) {
                    console.log(err);
                });
        }
    }

});

malApp.controller('TagsController', function($scope, $rootScope, $http, $window) {

    $http.get($rootScope.config.baseUrl + '/tags?token=' + $rootScope.sessionUser.token)
        .success(function(data) {
            $scope.tags = data;
        });

    $scope.editTag = function(id) {
        $window.location = '#/tags/' + id;
    };

});

malApp.controller('TagController', function($scope, $rootScope, $routeParams, $http, $window) {

    $('#name').focus();

    if ($routeParams.id === 'new') {
        $scope.tag = {};
    } else {
        $http.get($rootScope.config.baseUrl + '/tags/' + $routeParams.id + '?token=' + $rootScope.sessionUser.token)
            .success(function(data) {
                $scope.tag = data[0] || data;
            });
    }

    $scope.save = function() {

        if ($routeParams.id === 'new') {

            $scope.tag.userId = $rootScope.sessionUser.userId;
            $scope.tag.dateCreated = moment().format('YYYY-MM-DD HH:mm:ss');  // TODO: Get format from config

            $http.post($rootScope.config.baseUrl + '/tags?token=' + $rootScope.sessionUser.token, $scope.tag)
                .success(function() {
                    if ($rootScope.previousPage) {
                        $window.location = '#/tags';
                    }
                }, function(err) {
                    console.log(err);
                });
        } else {
            $http.put($rootScope.config.baseUrl + '/tags?token=' + $rootScope.sessionUser.token, $scope.tag)
                .success(function() {
                    if ($rootScope.previousPage) {
                        $window.location = '#/tags';
                    }
                }, function(err) {
                    console.log(err);
                });
        }
    }

});

// -----------------------------------------------------------------------------
// Private functions
// -----------------------------------------------------------------------------

function bootstrapApp($rootScope, $http) {

    $http.get('/config')
        .success(function(data) {

            $rootScope.config = data;

            if ($rootScope.sessionUser) {
                $http.get($rootScope.config.baseUrl + '/groups?token=' + $rootScope.sessionUser.token)
                    .success(function(data) {
                        $rootScope.groups = data;
                    });
            }
        });

}
<commit_msg>Prevent unpleasantness when adding a duplicates to the arrays<commit_after>'use strict';

var malApp = angular.module('malApp', [
    'ngRoute',
    'ngCookies',
    'ui.bootstrap',
    'ngTagsInput'
]);

malApp.config(function($routeProvider) {

    // Define the routes
    $routeProvider
        .when('/', {
            templateUrl: 'partials/index.html',
            controller: 'IndexController'
        })
        .when('/login', {
            templateUrl: 'partials/login-required.html',
            controller: 'LoginController'
        })
        .when('/logout', {
            templateUrl: 'partials/logout.html',
            controller: 'LogoutController'
        })
        .when('/test', {
            templateUrl: 'partials/test.html',
            controller: 'TestController'
        })
        .when('/bookmarks/:id', {
            templateUrl: 'partials/bookmark.html',
            controller: 'BookmarkController'
        })
        .when('/bookmarks', {
            templateUrl: 'partials/bookmarks.html',
            controller: 'BookmarksController'
        })
        .when('/bookmarks/group/:groupId', {
            templateUrl: 'partials/bookmarks.html',
            controller: 'BookmarksOfGroupController'
        })
        .when('/groups', {
            templateUrl: 'partials/groups.html',
            controller: 'GroupsController'
        })
        .when('/groups/:id', {
            templateUrl: 'partials/group.html',
            controller: 'GroupController'
        })
        .when('/tags', {
            templateUrl: 'partials/tags.html',
            controller: 'TagsController'
        })
        .when('/tags/:id', {
            templateUrl: 'partials/tag.html',
            controller: 'TagController'
        })
        .otherwise({
            redirectTo: '/'
        });

});

malApp.run(function($rootScope, $http, $location, $window, $cookies) {

    $rootScope.pageTitle = 'Bookmarkly';

    $rootScope.sessionUser = $cookies.getObject('bookmarklyLogin');

    if ($rootScope.sessionUser) {

        $http.post('/validatetoken', { token: $rootScope.sessionUser.token })
            .then(function() {
                console.log('Token %s is valid', $rootScope.sessionUser.token);
                console.log('Welcome back, %s', $rootScope.sessionUser.username);
                bootstrapApp($rootScope, $http);
            }, function(response) {
                $rootScope.sessionUser = null;
                $cookies.remove('bookmarklyLogin');
                console.log(JSON.stringify(response));
                //console.log('Redirecting you to the login page');
                //$window.location = '/login.html';
            });

    }

    $rootScope.$on('$locationChangeStart', function(event, next, current) {

        $rootScope.previousPage = current;

        if (!$rootScope.sessionUser) {
            $location.path('/login');
        }
    });

});

malApp.controller('IndexController', function($rootScope) {
});

malApp.controller('TestController', function($rootScope) {
});

malApp.controller('LoginController', function($rootScope, $window) {

    var delay = ($rootScope.config ? $rootScope.config.loginRedirectDelay : 5000);
    var location = ($rootScope.config ? $rootScope.config.baseUrl + $rootScope.config.loginAppPath : '/login.html');

    setTimeout(function() {
        $window.location = location;
    }, delay);

});

malApp.controller('LogoutController', function($rootScope, $cookies, $window) {

    $cookies.remove('bookmarklyLogin');
    $rootScope.sessionUser = null;

    if ($rootScope.config.logoutRedirectDelay > 0) {
        setTimeout(function() {
            $window.location = $rootScope.config.baseUrl + $rootScope.config.loginAppPath;
        }, $rootScope.config.logoutRedirectDelay);
    }

});

malApp.controller('BookmarksController', function($scope, $rootScope, $http, $window) {

    $http.get($rootScope.config.baseUrl + '/bookmarks?token=' + $rootScope.sessionUser.token)
        .success(function(data) {
            //console.log('bookmarks: ' + JSON.stringify(data));
            $scope.bookmarks = data;

            //$http.get($rootScope.config.baseUrl + '/groups/' + $routeParams.groupId + '?token=' + $rootScope.sessionUser.token)
            //    .success(function(data) {
            //        //console.log(data);
            //        $scope.group = data[0] || data;
            //    });
        });

    $scope.editBookmark = function(id) {
        $window.location = '#/bookmarks/' + id;
    };

});

malApp.controller('BookmarkController', function($scope, $rootScope, $routeParams, $http, $window, $q) {

    $('#title').focus();

    $scope.groups = [];
    $scope.tags = [];

    $scope.loadGroups = function(query) {

        var deferred = $q.defer();

        $http.get($rootScope.config.baseUrl + '/groups?token=' + $rootScope.sessionUser.token + '&search=' + query)
            .success(function(data) {
                var retArray = [{text: query}];

                if (data && data.length > 0) {
                    data.forEach(function(item) {
                        if (item.name !== query) {
                            retArray.push({text: item.name});
                        }
                    });

                }

                deferred.resolve(retArray);
            });

        return deferred.promise;
    };

    $scope.loadTags = function(query) {

        var deferred = $q.defer();

        $http.get($rootScope.config.baseUrl + '/tags?token=' + $rootScope.sessionUser.token + '&search=' + query)
            .success(function(data) {
                var retArray = [{text: query}];

                if (data && data.length > 0) {
                    data.forEach(function(item) {
                        if (item.name !== query) {
                            retArray.push({text: item.name});
                        }
                    });

                }

                deferred.resolve(retArray);
            });

        return deferred.promise;
    };

    if ($routeParams.id === 'new') {
        $scope.bookmark = {
            rating: 1
        };
    } else {
        $http.get($rootScope.config.baseUrl + '/bookmarks/' + $routeParams.id + '?token=' + $rootScope.sessionUser.token)
            .success(function(data) {
                $scope.bookmark = data[0] || data;

                if ($scope.bookmark && $scope.bookmark.groups) {

                    var tmpGroupArray = [];

                    $scope.bookmark.groups.forEach(function(groupItem) {
                        tmpGroupArray.push(groupItem.name);
                    });

                    if (tmpGroupArray && tmpGroupArray.length > 0) {
                        $scope.groups = tmpGroupArray;
                    }
                }

                if ($scope.bookmark && $scope.bookmark.tags) {

                    var tmpTagArray = [];

                    $scope.bookmark.tags.forEach(function(tagItem) {
                        tmpTagArray.push(tagItem.name);
                    });

                    if (tmpTagArray && tmpTagArray.length > 0) {
                        $scope.tags = tmpTagArray;
                    }
                }
            });
    }

    $scope.save = function() {

        var bookmarkWrapper = {
            model: $scope.bookmark,
            groupNames: [],
            tagNames: []
        };

        delete bookmarkWrapper.model.groups;
        delete bookmarkWrapper.model.tags;

        if ($scope.groups && $scope.groups.length > 0) {
            $scope.groups.forEach(function(item) {
                bookmarkWrapper.groupNames.push(item.text);
            });
        }

        if ($scope.tags && $scope.tags.length > 0) {
            $scope.tags.forEach(function(item) {
                bookmarkWrapper.tagNames.push(item.text);
            });
        }

        if ($routeParams.id === 'new') {

            bookmarkWrapper.model.userId = $rootScope.sessionUser.userId;
            bookmarkWrapper.dateCreated = moment().format('YYYY-MM-DD HH:mm:ss');  // TODO: Get format from config

            $http.post($rootScope.config.baseUrl + '/bookmarks?token=' + $rootScope.sessionUser.token, bookmarkWrapper)
                .success(function() {
                    if ($rootScope.previousPage) {
                        $window.location = $rootScope.previousPage;
                    }
                }, function(err) {
                    console.log(err);
                });
        } else {

            $http.put($rootScope.config.baseUrl + '/bookmarks?token=' + $rootScope.sessionUser.token, bookmarkWrapper)
                .success(function() {
                    if ($rootScope.previousPage) {
                        $window.location = $rootScope.previousPage;
                    }
                }, function(err) {
                    console.log(err);
                });
        }
    }

});

malApp.controller('BookmarksOfGroupController', function($scope, $rootScope, $routeParams, $http, $window) {

    $http.get($rootScope.config.baseUrl + '/bookmarks/group/' + $routeParams.groupId + '?token=' + $rootScope.sessionUser.token)
        .then(function(data) {
            $scope.bookmarks = data.data;

            $http.get($rootScope.config.baseUrl + '/groups/' + $routeParams.groupId + '?token=' + $rootScope.sessionUser.token)
                .then(function(response) {
                    $scope.group = response.data[0] || response.data;
                }, function(response) {
                    console.log(JSON.stringify(response));
                });
        }, function(response) {
            console.log(JSON.stringify(response));
        });

    $scope.editBookmark = function(id) {
        $window.location = '#/bookmarks/' + id;
    };

});

malApp.controller('GroupsController', function($scope, $rootScope, $http, $window) {

    $http.get($rootScope.config.baseUrl + '/groups?token=' + $rootScope.sessionUser.token)
        .success(function(data) {
            $scope.groups = data;
        });

    $scope.editGroup = function(id) {
        $window.location = '#/groups/' + id;
    };

});

malApp.controller('GroupController', function($scope, $rootScope, $routeParams, $http, $window) {

    $('#name').focus();

    if ($routeParams.id === 'new') {
        $scope.group = {};
    } else {
        $http.get($rootScope.config.baseUrl + '/groups/' + $routeParams.id + '?token=' + $rootScope.sessionUser.token)
            .success(function(data) {
                $scope.group = data[0] || data;
            });
    }

    $scope.save = function() {

        if ($routeParams.id === 'new') {

            $scope.group.userId = $rootScope.sessionUser.userId;
            $scope.group.dateCreated = moment().format('YYYY-MM-DD HH:mm:ss');  // TODO: Get format from config

            $http.post($rootScope.config.baseUrl + '/groups?token=' + $rootScope.sessionUser.token, $scope.group)
                .success(function() {
                    if ($rootScope.previousPage) {
                        $window.location = '#/groups';
                    }
                }, function(err) {
                    console.log(err);
                });
        } else {
            $http.put($rootScope.config.baseUrl + '/groups?token=' + $rootScope.sessionUser.token, $scope.group)
                .success(function() {
                    if ($rootScope.previousPage) {
                        $window.location = '#/groups';
                    }
                }, function(err) {
                    console.log(err);
                });
        }
    }

});

malApp.controller('TagsController', function($scope, $rootScope, $http, $window) {

    $http.get($rootScope.config.baseUrl + '/tags?token=' + $rootScope.sessionUser.token)
        .success(function(data) {
            $scope.tags = data;
        });

    $scope.editTag = function(id) {
        $window.location = '#/tags/' + id;
    };

});

malApp.controller('TagController', function($scope, $rootScope, $routeParams, $http, $window) {

    $('#name').focus();

    if ($routeParams.id === 'new') {
        $scope.tag = {};
    } else {
        $http.get($rootScope.config.baseUrl + '/tags/' + $routeParams.id + '?token=' + $rootScope.sessionUser.token)
            .success(function(data) {
                $scope.tag = data[0] || data;
            });
    }

    $scope.save = function() {

        if ($routeParams.id === 'new') {

            $scope.tag.userId = $rootScope.sessionUser.userId;
            $scope.tag.dateCreated = moment().format('YYYY-MM-DD HH:mm:ss');  // TODO: Get format from config

            $http.post($rootScope.config.baseUrl + '/tags?token=' + $rootScope.sessionUser.token, $scope.tag)
                .success(function() {
                    if ($rootScope.previousPage) {
                        $window.location = '#/tags';
                    }
                }, function(err) {
                    console.log(err);
                });
        } else {
            $http.put($rootScope.config.baseUrl + '/tags?token=' + $rootScope.sessionUser.token, $scope.tag)
                .success(function() {
                    if ($rootScope.previousPage) {
                        $window.location = '#/tags';
                    }
                }, function(err) {
                    console.log(err);
                });
        }
    }

});

// -----------------------------------------------------------------------------
// Private functions
// -----------------------------------------------------------------------------

function bootstrapApp($rootScope, $http) {

    $http.get('/config')
        .success(function(data) {

            $rootScope.config = data;

            if ($rootScope.sessionUser) {
                $http.get($rootScope.config.baseUrl + '/groups?token=' + $rootScope.sessionUser.token)
                    .success(function(data) {
                        $rootScope.groups = data;
                    });
            }
        });

}
<|endoftext|>


<commit_before>'use strict';

var request = require('request');
var debug = require('../../util/debug')('capacity-http-simple');

function HttpSimpleCapacity(host, capacityEndpoint) {
    this.host = host;
    this.capacityEndpoint = capacityEndpoint;
}

module.exports = HttpSimpleCapacity;

HttpSimpleCapacity.prototype.getCapacity = function(callback) {
    this.getResponse(function(err, values) {
        var capacity = 1;

        if (err) {
            return callback(null, capacity);
        }

        var availableCores = parseInt(values.available_cores, 10);

        capacity = Math.max(availableCores, 1);
        capacity = Number.isFinite(capacity) ? capacity : 1;

        debug('host=%s, capacity=%s', this.host, capacity);
        return callback(null, capacity);
    }.bind(this));
};

HttpSimpleCapacity.prototype.getResponse = function(callback) {
    var requestParams = {
        method: 'POST',
        url: this.capacityEndpoint,
        json: true
    };
    debug('getCapacity(%s)', this.host);
    request.post(requestParams, function(err, res, jsonRes) {
        if (err) {
            return callback(err);
        }
        if (jsonRes && jsonRes.retcode === 0) {
            return callback(null, jsonRes.return_values || {});
        }
        return callback(new Error('Could not retrieve information from endpoint'));
    });
};
<commit_msg>Timeout for http capacity requests<commit_after>'use strict';

var request = require('request');
var debug = require('../../util/debug')('capacity-http-simple');

function HttpSimpleCapacity(host, capacityEndpoint) {
    this.host = host;
    this.capacityEndpoint = capacityEndpoint;
}

module.exports = HttpSimpleCapacity;

HttpSimpleCapacity.prototype.getCapacity = function(callback) {
    this.getResponse(function(err, values) {
        var capacity = 1;

        if (err) {
            return callback(null, capacity);
        }

        var availableCores = parseInt(values.available_cores, 10);

        capacity = Math.max(availableCores, 1);
        capacity = Number.isFinite(capacity) ? capacity : 1;

        debug('host=%s, capacity=%s', this.host, capacity);
        return callback(null, capacity);
    }.bind(this));
};

HttpSimpleCapacity.prototype.getResponse = function(callback) {
    var requestParams = {
        method: 'POST',
        url: this.capacityEndpoint,
        timeout: 2000,
        json: true
    };
    debug('getCapacity(%s)', this.host);
    request.post(requestParams, function(err, res, jsonRes) {
        if (err) {
            return callback(err);
        }
        if (jsonRes && jsonRes.retcode === 0) {
            return callback(null, jsonRes.return_values || {});
        }
        return callback(new Error('Could not retrieve information from endpoint'));
    });
};
<|endoftext|>


<commit_before>import Head from "next/head";
import Meta from "../components/Meta";
import Link from "next/link";
import {
  Container,
  SingleColumn,
  Section,
  IntraNav,
  getAllPosts,
  formatDate,
  generateDisplayDate,
} from "@urbit/foundation-design-system";
import Footer from "../components/Footer";
import Header from "../components/Header";
import BackgroundImage from "../components/BackgroundImage";
import { contact } from "../lib/constants";

export default function Blog({ posts, search }) {
  const post = {
    title: "Getting Started With Urbit",
    description:
      "Links to get started with Urbit.",
  };
  return (
    <Container>

        <title>Blog • urbit.org</title>
        {Meta(post)}

      <IntraNav ourSite="https://urbit.org" search={search} />
      <SingleColumn>

Getting Started With Urbit

	         • <Link href="https://developers.urbit.org/courses">Take a course on hoon</Link>

            • <Link href="/grants/proposals">Submit a grant proposal</Link>

            • <Link href="https://urbit.org/grants?type=Bounty#view-grants">Pick up an open bounty</Link>

      </SingleColumn>

    </Container>
  );
}

<commit_msg>Update getinvolved.js<commit_after>import Head from "next/head";
import Meta from "../components/Meta";
import Link from "next/link";
import {
  Container,
  SingleColumn,
  Section,
  IntraNav,
  getAllPosts,
  formatDate,
  generateDisplayDate,
} from "@urbit/foundation-design-system";
import Footer from "../components/Footer";
import Header from "../components/Header";
import BackgroundImage from "../components/BackgroundImage";
import { contact } from "../lib/constants";

export default function Blog({ posts, search }) {
  const post = {
    title: "Getting Started With Urbit",
    description:
      "Links to get started with Urbit.",
  };
  return (
    <Container>

        <title>Blog • urbit.org</title>
        {Meta(post)}

      <IntraNav ourSite="https://urbit.org" search={search} />
      <SingleColumn>

Getting Started With Urbit

	         • <Link href="https://developers.urbit.org/courses">Take a course on Hoon</Link>

            • <Link href="/grants/proposals">Submit a grant proposal</Link>

            • <Link href="https://urbit.org/grants?type=Bounty#view-grants">Pick up an open bounty</Link>

            • <Link href="https://developers.urbit.org/guides/quickstart/intro">Build an app</Link>

      </SingleColumn>

    </Container>
  );
}

<|endoftext|>


<commit_before>
var SortableCollectionBehavior;
(function ($, _, Backbone, Marionette) {
    SortableCollectionBehavior = Marionette.Behavior.extend({

    });
})(jQuery, _, Backbone, Marionette);
<commit_msg>Update SortableCollectionBehavior.js<commit_after>
var SortableCollectionBehavior;
(function ($, _, Backbone, Marionette) {
    SortableCollectionBehavior = Marionette.Behavior.extend({
        onRender: function(){
            this.view.$el.addClass('sortable-view');
            this.setComparator();
        },
        setPlacement: function (draggedModel, overModel) {
            var draggedModelPlacement = draggedModel.get('placement'),
                overModelPlacement = overModel.get('placement');

            var placement;
            if (draggedModelPlacement < overModelPlacement) {
                this.collection.each(function (item) {
                    var placement = item.get('placement');
                    if (placement <= overModelPlacement) {
                        var newPlacement = placement - 1;
                        item.set({placement: newPlacement});
                    }
                });

                draggedModel.set({placement: overModelPlacement});
            } else if (draggedModelPlacement > overModelPlacement) {
                this.collection.each(function (item) {
                    var placement = item.get('placement');
                    if (placement >= overModelPlacement) {
                        var newPlacement = placement + 1;
                        item.set({placement: newPlacement});
                    }
                });

                draggedModel.set({placement: overModelPlacement});
            }

            this.setComparator();
        },
        setComparator: function () {
            this.view.collection.comparator =
                function (model) {
                    return model.get('placement');
                };

            this.view.collection.sort();
        }
    });
})(jQuery, _, Backbone, Marionette);
<|endoftext|>


<commit_before>//index.js
//获取应用实例
const app = getApp();
const utils = require('../../utils/util.js');

const gaPath = '/wx/today-focus';
const gaTitle = '今日焦点';

Page({
  data: {
    articleList: []
  },
  //事件处理函数
  bindViewTap: function(e) {
    // wx.navigateTo({
    //   url: '../logs/logs'
    // })
    // Get the article's ID
  },

  onLoad: function () {
    console.log('onLoad');
    var that = this;
    //调用应用实例的方法获取全局数据
    // app.getUserInfo(function(userInfo){
    //   //更新数据
    //   that.setData({
    //     userInfo:userInfo
    //   })
    // })
    wx.showToast({
      title: '加载中...',
      icon: 'loading',
      duration: 1500,
    });

    app.checkNetwork((err, type) => {
// If wifi connection, always request to server
      this.fetchAndCacheData(wx.hideToast);

    }, (err, type) => {
// If data connection, try to get data from cache first. If failed, then asking server for data.
      app.retrieveData('articleList', (err, data) => {
        // If there is no error, data is retrieved from cache
        if (!err) {
          console.log('article list retrieved from cache');
          this.setData({
            articleList: data
          });
// Tracking
          app.ga(gaPath, gaTitle);

          return;
        }

// If there is error, request data to server
        this.fetchAndCacheData(wx.hideToast);

      });
    });
  },

  onShow: function() {
    console.log('onShow');
  },

  onPullDownRefresh: function() {
// Manually request data
    this.fetchAndCacheData(wx.stopPullDownRefresh);
  },

/**
 * `path` is the path of the js file. Lik `pages` in app.json but an start with `/`
 */
  onShareAppMessage: function() {
    return {
      title: 'FT今日焦点',
      desc: 'FT中文网今日焦点',
      path: '/pages/index/index'
    }
  },

/**
 * Page specific methods
 */
  fetchAndCacheData: function(cb) {
    app.fetchData('https://api.ftmailbox.com/index.php/jsapi/home', (err, data) => {
      if (err) {return err;}
      console.log(data);

// Get cover's article list. This is specific to the data structure returned from API.
      let items = data.sections.filter(section => {
          return section.name === 'Cover'
        }).map(section => {
          return section.lists.map(list => {
            return list.items;
          });
        })[0][0];

// Filter out everything whose type is not `story`
      items = items.filter(item => {
        return item.type === 'story';
      });

      const articleList = items.map(item => {
        return {
          id: item.id,
          image: utils.imageService(item.image),
          heading: item.headline,
          standfirst: item.longlead,
          publishDate: utils.formatTime(new Date(item.timeStamp * 1000)),
          tags: items.tag
        }
      });

      this.setData({
        articleList
      });

      typeof cb == 'function' && cb();

// Cache data
      app.cacheData('articleList', articleList);

// Tracking
      app.ga(gaPath, gaTitle);
    });
  }
});
<commit_msg>rm console<commit_after>//index.js
//获取应用实例
const app = getApp();
const utils = require('../../utils/util.js');

const gaPath = '/wx/today-focus';
const gaTitle = '今日焦点';

Page({
  data: {
    articleList: []
  },
  //事件处理函数
  bindViewTap: function(e) {
    // wx.navigateTo({
    //   url: '../logs/logs'
    // })
    // Get the article's ID
  },

  onLoad: function () {
    console.log('onLoad');
    var that = this;
    //调用应用实例的方法获取全局数据
    // app.getUserInfo(function(userInfo){
    //   //更新数据
    //   that.setData({
    //     userInfo:userInfo
    //   })
    // })
    wx.showToast({
      title: '加载中...',
      icon: 'loading',
      duration: 1500,
    });

    app.checkNetwork((err, type) => {
// If wifi connection, always request to server
      this.fetchAndCacheData(wx.hideToast);

    }, (err, type) => {
// If data connection, try to get data from cache first. If failed, then asking server for data.
      app.retrieveData('articleList', (err, data) => {
        // If there is no error, data is retrieved from cache
        if (!err) {
          console.log('article list retrieved from cache');
          this.setData({
            articleList: data
          });
// Tracking
          app.ga(gaPath, gaTitle);

          return;
        }

// If there is error, request data to server
        this.fetchAndCacheData(wx.hideToast);

      });
    });
  },

  onShow: function() {
    console.log('onShow');
  },

  onPullDownRefresh: function() {
// Manually request data
    this.fetchAndCacheData(wx.stopPullDownRefresh);
  },

/**
 * `path` is the path of the js file. Lik `pages` in app.json but an start with `/`
 */
  onShareAppMessage: function() {
    return {
      title: 'FT今日焦点',
      desc: 'FT中文网今日焦点',
      path: '/pages/index/index'
    }
  },

/**
 * Page specific methods
 */
  fetchAndCacheData: function(cb) {
    app.fetchData('https://api.ftmailbox.com/index.php/jsapi/home', (err, data) => {
      if (err) {return err;}

// Get cover's article list. This is specific to the data structure returned from API.
      let items = data.sections.filter(section => {
          return section.name === 'Cover'
        }).map(section => {
          return section.lists.map(list => {
            return list.items;
          });
        })[0][0];

// Filter out everything whose type is not `story`
      items = items.filter(item => {
        return item.type === 'story';
      });

      const articleList = items.map(item => {
        return {
          id: item.id,
          image: utils.imageService(item.image),
          heading: item.headline,
          standfirst: item.longlead,
          publishDate: utils.formatTime(new Date(item.timeStamp * 1000)),
          tags: items.tag
        }
      });

      this.setData({
        articleList
      });

      typeof cb == 'function' && cb();

// Cache data
      app.cacheData('articleList', articleList);

// Tracking
      app.ga(gaPath, gaTitle);
    });
  }
});
<|endoftext|>