<commit_before>/*
  mustache.js — Logic-less templates in JavaScript

  See http://mustache.github.com/ for more info.
*/

var Mustache = function() {
  var Renderer = function() {};

  Renderer.prototype = {
    otag: "{{",
    ctag: "}}",
    pragmas: {},
    buffer: [],
    pragmas_implemented: {
      "IMPLICIT-ITERATOR": true
    },
    context: {},

    render: function(template, context, partials, in_recursion) {
      // reset buffer & set context
      if(!in_recursion) {
        this.context = context;
        this.buffer = []; // TODO: make this non-lazy
      }

      // fail fast
      if(!this.includes("", template)) {
        if(in_recursion) {
          return template;
        } else {
          this.send(template);
          return;
        }
      }

      template = this.render_pragmas(template);
      var html = this.render_section(template, context, partials);
      if(in_recursion) {
        return this.render_tags(html, context, partials, in_recursion);
      }

      this.render_tags(html, context, partials, in_recursion);
    },

    /*
      Sends parsed lines
    */
    send: function(line) {
      if(line != "") {
        this.buffer.push(line);
      }
    },

    /*
      Looks for %PRAGMAS
    */
    render_pragmas: function(template) {
      // no pragmas
      if(!this.includes("%", template)) {
        return template;
      }

      var that = this;
      var regex = new RegExp(this.otag + "%([\\w-]+) ?([\\w]+=[\\w]+)?" +
            this.ctag);
      return template.replace(regex, function(match, pragma, options) {
        if(!that.pragmas_implemented[pragma]) {
          throw({message:
            "This implementation of mustache doesn't understand the '" +
            pragma + "' pragma"});
        }
        that.pragmas[pragma] = {};
        if(options) {
          var opts = options.split("=");
          that.pragmas[pragma][opts[0]] = opts[1];
        }
        return "";
        // ignore unknown pragmas silently
      });
    },

    /*
      Tries to find a partial in the curent scope and render it
    */
    render_partial: function(name, context, partials) {
      name = this.trim(name);
      if(!partials || partials[name] === undefined) {
        throw({message: "unknown_partial '" + name + "'"});
      }
      if(typeof(context[name]) != "object") {
        return this.render(partials[name], context, partials, true);
      }
      return this.render(partials[name], context[name], partials, true);
    },

    /*
      Renders inverted (^) and normal (#) sections
    */
    render_section: function(template, context, partials) {
      if(!this.includes("#", template) && !this.includes("^", template)) {
        return template;
      }

      var that = this;
      // CSW - Added "+?" so it finds the tighest bound, not the widest
      var regex = new RegExp(this.otag + "(\\^|\\#)\\s*(.+)\\s*" + this.ctag +
              "\n*([\\s\\S]+?)" + this.otag + "\\/\\s*\\2\\s*" + this.ctag +
              "\\s*", "mg");

      // for each {{#foo}}{{/foo}} section do...
      return template.replace(regex, function(match, type, name, content) {
        var value = that.find(name, context);
        if(type == "^") { // inverted section
          if(!value || that.is_array(value) && value.length === 0) {
            // false or empty list, render it
            return that.render(content, context, partials, true);
          } else {
            return "";
          }
        } else if(type == "#") { // normal section
          if(that.is_array(value)) { // Enumerable, Let's loop!
            return that.map(value, function(row) {
              return that.render(content, that.create_context(row),
                partials, true);
            }).join("");
          } else if(that.is_object(value)) { // Object, Use it as subcontext!
            return that.render(content, that.create_context(value),
              partials, true);
          } else if(typeof value === "function") {
            // higher order section
            return value.call(context, content, function(text) {
              return that.render(text, context, partials, true);
            });
          } else if(value) { // boolean section
            return that.render(content, context, partials, true);
          } else {
            return "";
          }
        }
      });
    },

    /*
      Replace {{foo}} and friends with values from our view
    */
    render_tags: function(template, context, partials, in_recursion) {
      // tit for tat
      var that = this;

      var new_regex = function() {
        return new RegExp(that.otag + "(=|!|>|\\{|%)?([^\\/#\\^]+?)\\1?" +
          that.ctag + "+", "g");
      };

      var regex = new_regex();
      var tag_replace_callback = function(match, operator, name) {
        switch(operator) {
        case "!": // ignore comments
          return "";
        case "=": // set new delimiters, rebuild the replace regexp
          that.set_delimiters(name);
          regex = new_regex();
          return "";
        case ">": // render partial
          return that.render_partial(name, context, partials);
        case "{": // the triple mustache is unescaped
          return that.find(name, context);
        default: // escape the value
          return that.escape(that.find(name, context));
        }
      };
      var lines = template.split("\n");
      for(var i = 0; i < lines.length; i++) {
        lines[i] = lines[i].replace(regex, tag_replace_callback, this);
        if(!in_recursion) {
          this.send(lines[i]);
        }
      }

      if(in_recursion) {
        return lines.join("\n");
      }
    },

    set_delimiters: function(delimiters) {
      var dels = delimiters.split(" ");
      this.otag = this.escape_regex(dels[0]);
      this.ctag = this.escape_regex(dels[1]);
    },

    escape_regex: function(text) {
      // thank you Simon Willison
      if(!arguments.callee.sRE) {
        var specials = [
          '/', '.', '*', '+', '?', '|',
          '(', ')', '[', ']', '{', '}', '\\'
        ];
        arguments.callee.sRE = new RegExp(
          '(\\' + specials.join('|\\') + ')', 'g'
        );
      }
      return text.replace(arguments.callee.sRE, '\\$1');
    },

    /*
      find `name` in current `context`. That is find me a value
      from the view object
    */
    find: function(name, context) {
      name = this.trim(name);

      // Checks whether a value is thruthy or false or 0
      function is_kinda_truthy(bool) {
        return bool === false || bool === 0 || bool;
      }

      var value;
      if(is_kinda_truthy(context[name])) {
        value = context[name];
      } else if(is_kinda_truthy(this.context[name])) {
        value = this.context[name];
      }

      if(typeof value === "function") {
        return value.apply(context);
      }
      if(value !== undefined) {
        return value;
      }
      // silently ignore unkown variables
      return "";
    },

    // Utility methods

    /* includes tag */
    includes: function(needle, haystack) {
      return haystack.indexOf(this.otag + needle) != -1;
    },

    /*
      Does away with nasty characters
    */
    escape: function(s) {
      s = String(s === null ? "" : s);
      return s.replace(/&(?!\w+;)|["'<>\\]/g, function(s) {
        switch(s) {
        case "&": return "&";
        case "\\": return "\\\\";
        case '"': return '"';
        case "'": return ''';
        case "<": return "<";
        case ">": return ">";
        default: return s;
        }
      });
    },

    // by @langalex, support for arrays of strings
    create_context: function(_context) {
      if(this.is_object(_context)) {
        return _context;
      } else {
        var iterator = ".";
        if(this.pragmas["IMPLICIT-ITERATOR"]) {
          iterator = this.pragmas["IMPLICIT-ITERATOR"].iterator;
        }
        var ctx = {};
        ctx[iterator] = _context;
        return ctx;
      }
    },

    is_object: function(a) {
      return a && typeof a == "object";
    },

    is_array: function(a) {
      return Object.prototype.toString.call(a) === '[object Array]';
    },

    /*
      Gets rid of leading and trailing whitespace
    */
    trim: function(s) {
      return s.replace(/^\s*|\s*$/g, "");
    },

    /*
      Why, why, why? Because IE. Cry, cry cry.
    */
    map: function(array, fn) {
      if (typeof array.map == "function") {
        return array.map(fn);
      } else {
        var r = [];
        var l = array.length;
        for(var i = 0; i < l; i++) {
          r.push(fn(array[i]));
        }
        return r;
      }
    }
  };

  return({
    name: "mustache.js",
    version: "0.3.1-dev",

    /*
      Turns a template and view into HTML
    */
    to_html: function(template, view, partials, send_fun) {
      var renderer = new Renderer();
      if(send_fun) {
        renderer.send = send_fun;
      }
      renderer.render(template, view, partials);
      if(!send_fun) {
        return renderer.buffer.join("\n");
      }
    }
  });
}();
<commit_msg>Fixes issue 105<commit_after>/*
  mustache.js — Logic-less templates in JavaScript

  See http://mustache.github.com/ for more info.
*/

var Mustache = function() {
  var Renderer = function() {};

  Renderer.prototype = {
    otag: "{{",
    ctag: "}}",
    pragmas: {},
    buffer: [],
    pragmas_implemented: {
      "IMPLICIT-ITERATOR": true
    },
    context: {},

    render: function(template, context, partials, in_recursion) {
      // reset buffer & set context
      if(!in_recursion) {
        this.context = context;
        this.buffer = []; // TODO: make this non-lazy
      }

      // fail fast
      if(!this.includes("", template)) {
        if(in_recursion) {
          return template;
        } else {
          this.send(template);
          return;
        }
      }

      template = this.render_pragmas(template);
      var html = this.render_section(template, context, partials);
      if(in_recursion) {
        return this.render_tags(html, context, partials, in_recursion);
      }

      this.render_tags(html, context, partials, in_recursion);
    },

    /*
      Sends parsed lines
    */
    send: function(line) {
      if(line != "") {
        this.buffer.push(line);
      }
    },

    /*
      Looks for %PRAGMAS
    */
    render_pragmas: function(template) {
      // no pragmas
      if(!this.includes("%", template)) {
        return template;
      }

      var that = this;
      var regex = new RegExp(this.otag + "%([\\w-]+) ?([\\w]+=[\\w]+)?" +
            this.ctag, "g");
      return template.replace(regex, function(match, pragma, options) {
        if(!that.pragmas_implemented[pragma]) {
          throw({message:
            "This implementation of mustache doesn't understand the '" +
            pragma + "' pragma"});
        }
        that.pragmas[pragma] = {};
        if(options) {
          var opts = options.split("=");
          that.pragmas[pragma][opts[0]] = opts[1];
        }
        return "";
        // ignore unknown pragmas silently
      });
    },

    /*
      Tries to find a partial in the curent scope and render it
    */
    render_partial: function(name, context, partials) {
      name = this.trim(name);
      if(!partials || partials[name] === undefined) {
        throw({message: "unknown_partial '" + name + "'"});
      }
      if(typeof(context[name]) != "object") {
        return this.render(partials[name], context, partials, true);
      }
      return this.render(partials[name], context[name], partials, true);
    },

    /*
      Renders inverted (^) and normal (#) sections
    */
    render_section: function(template, context, partials) {
      if(!this.includes("#", template) && !this.includes("^", template)) {
        return template;
      }

      var that = this;
      // CSW - Added "+?" so it finds the tighest bound, not the widest
      var regex = new RegExp(this.otag + "(\\^|\\#)\\s*(.+)\\s*" + this.ctag +
              "\n*([\\s\\S]+?)" + this.otag + "\\/\\s*\\2\\s*" + this.ctag +
              "\\s*", "mg");

      // for each {{#foo}}{{/foo}} section do...
      return template.replace(regex, function(match, type, name, content) {
        var value = that.find(name, context);
        if(type == "^") { // inverted section
          if(!value || that.is_array(value) && value.length === 0) {
            // false or empty list, render it
            return that.render(content, context, partials, true);
          } else {
            return "";
          }
        } else if(type == "#") { // normal section
          if(that.is_array(value)) { // Enumerable, Let's loop!
            return that.map(value, function(row) {
              return that.render(content, that.create_context(row),
                partials, true);
            }).join("");
          } else if(that.is_object(value)) { // Object, Use it as subcontext!
            return that.render(content, that.create_context(value),
              partials, true);
          } else if(typeof value === "function") {
            // higher order section
            return value.call(context, content, function(text) {
              return that.render(text, context, partials, true);
            });
          } else if(value) { // boolean section
            return that.render(content, context, partials, true);
          } else {
            return "";
          }
        }
      });
    },

    /*
      Replace {{foo}} and friends with values from our view
    */
    render_tags: function(template, context, partials, in_recursion) {
      // tit for tat
      var that = this;

      var new_regex = function() {
        return new RegExp(that.otag + "(=|!|>|\\{|%)?([^\\/#\\^]+?)\\1?" +
          that.ctag + "+", "g");
      };

      var regex = new_regex();
      var tag_replace_callback = function(match, operator, name) {
        switch(operator) {
        case "!": // ignore comments
          return "";
        case "=": // set new delimiters, rebuild the replace regexp
          that.set_delimiters(name);
          regex = new_regex();
          return "";
        case ">": // render partial
          return that.render_partial(name, context, partials);
        case "{": // the triple mustache is unescaped
          return that.find(name, context);
        default: // escape the value
          return that.escape(that.find(name, context));
        }
      };
      var lines = template.split("\n");
      for(var i = 0; i < lines.length; i++) {
        lines[i] = lines[i].replace(regex, tag_replace_callback, this);
        if(!in_recursion) {
          this.send(lines[i]);
        }
      }

      if(in_recursion) {
        return lines.join("\n");
      }
    },

    set_delimiters: function(delimiters) {
      var dels = delimiters.split(" ");
      this.otag = this.escape_regex(dels[0]);
      this.ctag = this.escape_regex(dels[1]);
    },

    escape_regex: function(text) {
      // thank you Simon Willison
      if(!arguments.callee.sRE) {
        var specials = [
          '/', '.', '*', '+', '?', '|',
          '(', ')', '[', ']', '{', '}', '\\'
        ];
        arguments.callee.sRE = new RegExp(
          '(\\' + specials.join('|\\') + ')', 'g'
        );
      }
      return text.replace(arguments.callee.sRE, '\\$1');
    },

    /*
      find `name` in current `context`. That is find me a value
      from the view object
    */
    find: function(name, context) {
      name = this.trim(name);

      // Checks whether a value is thruthy or false or 0
      function is_kinda_truthy(bool) {
        return bool === false || bool === 0 || bool;
      }

      var value;
      if(is_kinda_truthy(context[name])) {
        value = context[name];
      } else if(is_kinda_truthy(this.context[name])) {
        value = this.context[name];
      }

      if(typeof value === "function") {
        return value.apply(context);
      }
      if(value !== undefined) {
        return value;
      }
      // silently ignore unkown variables
      return "";
    },

    // Utility methods

    /* includes tag */
    includes: function(needle, haystack) {
      return haystack.indexOf(this.otag + needle) != -1;
    },

    /*
      Does away with nasty characters
    */
    escape: function(s) {
      s = String(s === null ? "" : s);
      return s.replace(/&(?!\w+;)|["'<>\\]/g, function(s) {
        switch(s) {
        case "&": return "&";
        case "\\": return "\\\\";
        case '"': return '"';
        case "'": return ''';
        case "<": return "<";
        case ">": return ">";
        default: return s;
        }
      });
    },

    // by @langalex, support for arrays of strings
    create_context: function(_context) {
      if(this.is_object(_context)) {
        return _context;
      } else {
        var iterator = ".";
        if(this.pragmas["IMPLICIT-ITERATOR"]) {
          iterator = this.pragmas["IMPLICIT-ITERATOR"].iterator;
        }
        var ctx = {};
        ctx[iterator] = _context;
        return ctx;
      }
    },

    is_object: function(a) {
      return a && typeof a == "object";
    },

    is_array: function(a) {
      return Object.prototype.toString.call(a) === '[object Array]';
    },

    /*
      Gets rid of leading and trailing whitespace
    */
    trim: function(s) {
      return s.replace(/^\s*|\s*$/g, "");
    },

    /*
      Why, why, why? Because IE. Cry, cry cry.
    */
    map: function(array, fn) {
      if (typeof array.map == "function") {
        return array.map(fn);
      } else {
        var r = [];
        var l = array.length;
        for(var i = 0; i < l; i++) {
          r.push(fn(array[i]));
        }
        return r;
      }
    }
  };

  return({
    name: "mustache.js",
    version: "0.3.1-dev",

    /*
      Turns a template and view into HTML
    */
    to_html: function(template, view, partials, send_fun) {
      var renderer = new Renderer();
      if(send_fun) {
        renderer.send = send_fun;
      }
      renderer.render(template, view, partials);
      if(!send_fun) {
        return renderer.buffer.join("\n");
      }
    }
  });
}();
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import { FormGroup,ControlLabel,FormControl,HelpBlock,Row,Col, Checkbox,Panel,Button } from 'react-bootstrap';

function DatasetList(props) {
  const listItems = props.datasets.map((dataset) =>

{dataset}

  );
  return (

      {listItems}

  )
}

function ExportRegionList(props) {
  const regions = props.regions;
  const listItems = regions.map((region) =>
    <Row key={region.name}>
      <Panel>
        <Col xs={2}>

{region.name}

        </Col>
        <Col xs={4}>
          <DatasetList datasets={region.datasets}/>
        </Col>
        <Col xs={4}>
          Last Run: 2017/03/27 00:00:00PM

          Next Run: none

          Schedule: Every Sunday at 1:00 UTC
        </Col>
        <Col xs={1}>
          <Button block>
            View
          </Button>
        </Col>
        <Col xs={1}>
          <Button block href="edit">
            Settings
          </Button>
        </Col>
      </Panel>
    </Row>
  );
  return (

      {listItems}

  );
}

export class HDXListForm extends Component {

    constructor(props) {
        super(props);
        this.state = {
        }
    }

    componentWillReceiveProps(nextProps) {
    }

    render() {
        const regions = [
          {'name':'hotosm_sen','datasets':['hotosm_sen_roads','hotosm_sen_buildings','hotosm_sen_admin_boundaries','hotosm_waterways','hotosm_points_of_interest']},
          {'name':'hotosm_sle','datasets':['hotosm_sle_roads','hotosm_sle_buildings']},
          {'name':'hotosm_mli','datasets':['hotosm_mli_roads','hotosm_mli_buildings']},
          {'name':'hotosm_lbr','datasets':['hotosm_lbr_roads','hotosm_lbr_buildings']},
          {'name':'hotosm_gin','datasets':['hotosm_lbr_roads','hotosm_lbr_buildings']},
        ];
        return (

HDX Export Regions

            <Button style={{'float':'right'}} bsStyle="primary" bsSize="large" href="create">
              Create New Export Region
            </Button>

            <ExportRegionList regions={regions}/>

        )
    }
}

function mapStateToProps(state) {
    return {
    };
}

function mapDispatchToProps(dispatch) {
    return {
    };
}

export default HDXListForm;

<commit_msg>responsive layout<commit_after>import React, {Component} from 'react';
import { FormGroup,ControlLabel,FormControl,HelpBlock,Row,Col, Checkbox,Panel,Button } from 'react-bootstrap';

function DatasetList(props) {
  const listItems = props.datasets.map((dataset) =>

{dataset}

  );
  return (

      {listItems}

  )
}

function ExportRegionList(props) {
  const regions = props.regions;
  const listItems = regions.map((region) =>
    <Row key={region.name}>
      <Panel>
        <Col lg={5}>
          <DatasetList datasets={region.datasets}/>
        </Col>
        <Col lg={5}>
          Last Run: 2017/03/27 00:00:00PM

          Next Run: none

          Schedule: Every Sunday at 1:00 UTC
        </Col>
        <Col lg={1} md={2}>
          <Button block>
            Map
          </Button>
        </Col>
        <Col lg={1} md={2}>
          <Button block href="edit">
            Settings
          </Button>
        </Col>
      </Panel>
    </Row>
  );
  return (

      {listItems}

  );
}

export class HDXListForm extends Component {

    constructor(props) {
        super(props);
        this.state = {
        }
    }

    componentWillReceiveProps(nextProps) {
    }

    render() {
        const regions = [
          {'name':'hotosm_sen','datasets':['hotosm_sen_roads','hotosm_sen_buildings','hotosm_sen_admin_boundaries','hotosm_waterways','hotosm_points_of_interest']},
          {'name':'hotosm_sle','datasets':['hotosm_sle_roads','hotosm_sle_buildings']},
          {'name':'hotosm_mli','datasets':['hotosm_mli_roads','hotosm_mli_buildings']},
          {'name':'hotosm_lbr','datasets':['hotosm_lbr_roads','hotosm_lbr_buildings']},
          {'name':'hotosm_gin','datasets':['hotosm_lbr_roads','hotosm_lbr_buildings']},
        ];
        return (

HDX Export Regions

            <Button style={{'float':'right'}} bsStyle="primary" bsSize="large" href="create">
              Create New Export Region
            </Button>

            <ExportRegionList regions={regions}/>

        )
    }
}

function mapStateToProps(state) {
    return {
    };
}

function mapDispatchToProps(dispatch) {
    return {
    };
}

export default HDXListForm;

<|endoftext|>


<commit_before>// return all leaf stories of a hard-coded PI object ID

Ext.define('CustomApp', {
    extend:'Rally.app.App',
    componentCls:'app',
    layout:{
        type:'vbox',
        align:'stretch'
    },
    items:[

        { // define a container to house the PI combo box selector
            xtype:'container',
            itemId:'piChooserContainer',
            padding:'15 15 15 15' // top ? bottom left
        },
        {
            // panel where we will place the grid
            xtype:'panel',
            itemId:'piLeafStoryGridContainer',
            layout:'fit',
            height:400
        },
        {
            // panel where we will place the grid
            xtype:'panel',
            itemId:'piReleaseGridContainer',
            layout:'fit',
            height:400
        }
    ],

    // --- App global variables ---
    //gPiStories:[], // array to capture the list of all leaf stories in the PI
    gPiReleases:[], // array to capture the list of all stories a PI is scheduled in

    //gStoryGrid:undefined,

    // --- end global variables ---

    launch:function () {

        Ext.create('Rally.ui.dialog.ChooserDialog',{
            artifactTypes:['PortfolioItem/Feature'],
            autoShow:true,
            title:'Choose Feature',
            listeners:{
                artifactChosen:function (selectedRecord) {
                    //Ext.Msg.alert('Chooser', selectedRecord.get('Name') + ' was chosen');
                    this._getLeafStoriesInPi(selectedRecord.get('ObjectID'));
                },
                scope:this
            }
        });

    }, // end launch

    // reset the page's controls
    _reset:function () {
        this.gPiStories = [];
        //this._outstandingQueries = 0;
        this.down('#piLeafStoryGridContainer').removeAll();
    },

    // after PI selected, query for all its leaf level stories
    _getLeafStoriesInPi:function (piObjectID) {

        this._reset();

        var query = {
            "__At":"current",
            "_TypeHierarchy":"HierarchicalRequirement",
            "Children":null,
            "_ItemHierarchy":piObjectID
        };

        // set query config info
        var find = ["ObjectID", "_UnformattedID", "Name", "Release", "ScheduleState", "PlanEstimate"];
        var queryString = Ext.JSON.encode(query);

        // set context to global across the workspace
        var context = this.getContext().getDataContext();
        context.project = undefined;

        // fetch the snapshot of all leaf level stories for the PI
        var ssPiLeafStories = Ext.create('Rally.data.lookback.SnapshotStore', {
            context:{
                workspace:this.context.getWorkspace(),
                project:this.context.getProject()
            },
            fetch:find,
            rawFind:query,
            hydrate: ["ScheduleState"],
            autoLoad:true,
            listeners:{
                scope:this,
                load:this._processPiStories
            }
        });

    }, // end _getStoriesInPi

    // bucket the PI's stories by RELEASE (and no release)
    _processPiStories:function (store, records) {

        // spit out all leaf stories into a grid
        var snapshotGrid = Ext.create('Rally.ui.grid.Grid', {
            title:'Snapshots',
            store:store,
            columnCfgs:[
                {
                    text:'ObjectID',
                    dataIndex:'ObjectID'
                },
                {
                    text:'Name',
                    dataIndex:'Name'
                },
                {
                    text:'Project',
                    dataIndex:'Project'
                },
                {
                    text:'_UnformattedID',
                    dataIndex:'_UnformattedID'
                },
                ,
                {
                    text:'Release',
                    dataIndex:'Release'
                }
            ],
            height:400
        });

        // render the grid of all of the PI's leaf stories
        var gridHolder = this.down('#piLeafStoryGridContainer');
        gridHolder.removeAll(true);
        gridHolder.add(snapshotGrid);

        // --- BUCKET TIME BABY ---
        var aStory;
        var aRelease;

        var nbrStories = records.length;
        console.log("nbrStories: " + nbrStories);

        var storyNdx;

        // loop through each of the PI's stories
        for (storyNdx = 0; storyNdx < nbrStories; storyNdx++){
            aStory = records[storyNdx];

            if (aStory !== null){

                console.dir(aStory);
                console.log("aStory" + aStory);
                console.log("aStory" + aStory.get("Name"));
                console.log("aStory.PlanEstimate: " + aStory.get("PlanEstimate"));
                console.log("aStory.Release: " + aStory.get("Release"));
                console.log("aStory.ScheduleState: " + aStory.get("ScheduleState"));

                aRelease = null;

                aRelease = this._findReleaseEntry(this.gPiReleases, aStory.Release);

                if (aRelease === null){

                    // populate initial entry for this release
                    aRelease = new Object();

                    aRelease.itsStoryCount = 0;
                    aRelease.itsStoryPlanEstimate = 0;
                    aRelease.itsStoryCountAccepted = 0;
                    aRelease.itsStoryPlanEstimateAccepted = 0;

                }

                if (!aStory.get("Release")){
                    aRelease.itsOID = "Not Scheduled";
                }
                else{
                    aRelease.itsOID = aStory.get("Release");
                }

                aRelease.itsStoryCount += 1;
                aRelease.itsStoryPlanEstimate += aStory.get("PlanEstimate")||0;

                if (aStory.get("ScheduleState") === "Accepted"){
                    aRelease.itsStoryCountAccepted += 1;
                    aRelease.itsStoryPlanEstimateAccepted += aStory.get("PlanEstimate")||0;
                }

                this.gPiReleases.push(aRelease);

            } // end process this story

        } // end loop through all stories

        // process the PI's releases data
        this._processPiReleases();

        // fetch release names (we need to convert Release OIDs from the LBAPI to logical Release names)
        this._fetchReleaseNames();

        // --- END BUCKET TIME BABY ---

    }, // end _processPiStories

    _processPiReleases: function() {

        var nbrReleases = this.gPiReleases.length;
        console.log("nbrReleases: " + nbrReleases);

        var releaseNdx;
        var aRelease;

        // loop through each of the PI's releases
        for (releaseNdx = 0; releaseNdx < nbrReleases; releaseNdx++){

            aRelease = this.gPiReleases[releaseNdx];

        } // end loop through each of the PI's releases

    }, // end _processPiReleases

    // fetch all release names (we may later have to scale this back and do this more efficiently)
    _fetchReleaseNames: function() {

        var store = Ext.create('Rally.data.WsapiDataStore', {
            model: 'Release',

            fetch: ["ObjectID","Name"],
            // scope globally
            context: {
                project: null
            },
            limit: Infinity,
            autoLoad:true,
            listeners: {
                load: function(store, data, success) {
                    console.log("data",data);

                    // map release OIDs to release NAMES
                    this._mapReleaseOIDsToNames(store, data);

                },
                scope: this
            }
        });

    }, // end _fetchReleaseNames

    _mapReleaseOIDsToNames: function(theStore, allReleaseRecords)
    {
        var releaseNamesByObjectId = {};

        // create a hash of all WSAPI release OIDs to their Name
        Ext.Array.each(allReleaseRecords,function(releaseRecord){
            releaseNamesByObjectId[releaseRecord.get("ObjectID")] = releaseRecord.get("Name");
        });

        // loop through each PI's release object and set its name from the OID/Name hash
        Ext.Array.each(this.gPiReleases,function(piRelease){
            piRelease.itsName = releaseNamesByObjectId[piRelease.itsOID];

            if(!piRelease.itsName){
                piRelease.itsName = "Unscheduled";
            }
        });

        // bucket PI's releases by name into the bucketReleaseByName object
        var summedPisByReleaseName = {};
//        itsName: "2012.2H"
//        itsOID: 6883901892
//        itsStoryCount: 1
//        itsStoryCountAccepted: 1
//        itsStoryPlanEstimate: 5
//        itsStoryPlanEstimateAccepted: 5
        Ext.Array.each(this.gPiReleases,function(piRelease){
            if(!Ext.isObject(summedPisByReleaseName[piRelease.itsName])){
                summedPisByReleaseName[piRelease.itsName] = piRelease;
            }
            //Pointer
            var summedRelease = summedPisByReleaseName[piRelease.itsName];
            summedRelease.itsStoryCount += piRelease.itsStoryCount;
            summedRelease.itsStoryCountAccepted += piRelease.itsStoryCountAccepted;
            summedRelease.itsStoryPlanEstimate += piRelease.itsStoryPlanEstimate;
            summedRelease.itsStoryPlanEstimateAccepted += piRelease.itsStoryPlanEstimateAccepted;
        });

        // chart PI's release meta data
        this._chartPiReleases(summedPisByReleaseName);

    }, // end _fetchReleaseNames

    // chart out the PI's bucketed by name releases
    _chartPiReleases:function (theBucketPiReleasesByName) {

        console.log(theBucketPiReleasesByName);

        // define a custom  model
        var aModel = Ext.define('CustomStoryModel', {
            extend: 'Ext.data.Model',
            fields: [
                {name: 'itsName',  type: 'string'},
                {name: 'itsOID',   type: 'int'},
                {name: 'itsStoryCount',   type: 'int'},
                {name: 'itsStoryCountAccepted',   type: 'int'},
                {name: 'itsPlanEstimate',   type: 'int'},
                {name: 'itsPlanEstimateAccepted',   type: 'int'}
            ]
        });

        // define a store built around the custom  model
        var aStore = Ext.create('Ext.data.Store', {
            storeId: 'piReleaseStore',
            model: aModel,
            data: theBucketPiReleasesByName
        });

        // define a rally grid to output the store's data in
        var aPiReleaseGrid = Ext.create('Rally.ui.grid.Grid', {
            itemId: 'piReleaseGrid',
            store: aStore,
            width: 470,
            columnCfgs: [
                {
                    text: 'Release', dataIndex: 'itsName', width: 80
                },
                {
                    text: 'Release ID', dataIndex: 'itsOID', width: 80
                },
                {
                    text: 'Story Count', dataIndex: 'itsStoryCount', width: 80
                },
                {
                    text: 'Accepted Story Count', dataIndex: 'itsStoryCountAccepted', width: 80
                },
                {
                    text: 'Plan Estimate', dataIndex: 'itsPlanEstimate', width: 80
                },
                {
                    text: 'Accepted Plan Estimate', dataIndex: 'itsPlanEstimateAccepted', width: 80
                }
            ] // end columnCfgs
        });

        // render the grid of all of the PI's leaf stories
        var aPiReleaseGridContainer = this.down('#piReleaseGridContainer');
        aPiReleaseGridContainer.removeAll(true);
        aPiReleaseGridContainer.add(aPiReleaseGrid);

    }, // end _chartPiReleases

    _findReleaseEntry:function (theArr, theReleaseOID) {

        // check if array is empty
        if (this.gReleaseArray === null)
            return null;

        arrLen = theArr.length;

        for (x = 0; x < arrLen; x++) {
            var anEntry = theArr[x];

            if (anEntry.itsOID == theReleaseOID) {
                return anEntry
            }
        }
        return null;
    } // end _findReleaseEntry

});
<commit_msg>Creating Summary Grid<commit_after>// return all leaf stories of a hard-coded PI object ID

Ext.define('CustomApp', {
    extend:'Rally.app.App',
    componentCls:'app',
    layout:{
        type:'vbox',
        align:'stretch'
    },
    items:[

        { // define a container to house the PI combo box selector
            xtype:'container',
            itemId:'piChooserContainer',
            padding:'15 15 15 15' // top ? bottom left
        },
        {
            // panel where we will place the grid
            xtype:'panel',
            itemId:'piLeafStoryGridContainer',
            layout:'fit',
            height:400
        },
        {
            // panel where we will place the grid
            xtype:'panel',
            itemId:'piReleaseGridContainer',
            layout:'fit',
            height:400
        }
    ],

    // --- App global variables ---
    //gPiStories:[], // array to capture the list of all leaf stories in the PI
    gPiReleases:[], // array to capture the list of all stories a PI is scheduled in

    //gStoryGrid:undefined,

    // --- end global variables ---

    launch:function () {

        Ext.create('Rally.ui.dialog.ChooserDialog',{
            artifactTypes:['PortfolioItem/Feature'],
            autoShow:true,
            title:'Choose Feature',
            listeners:{
                artifactChosen:function (selectedRecord) {
                    //Ext.Msg.alert('Chooser', selectedRecord.get('Name') + ' was chosen');
                    this._getLeafStoriesInPi(selectedRecord.get('ObjectID'));
                },
                scope:this
            }
        });

    }, // end launch

    // reset the page's controls
    _reset:function () {
        this.gPiStories = [];
        //this._outstandingQueries = 0;
        this.down('#piLeafStoryGridContainer').removeAll();
    },

    // after PI selected, query for all its leaf level stories
    _getLeafStoriesInPi:function (piObjectID) {

        this._reset();

        var query = {
            "__At":"current",
            "_TypeHierarchy":"HierarchicalRequirement",
            "Children":null,
            "_ItemHierarchy":piObjectID
        };

        // set query config info
        var find = ["ObjectID", "_UnformattedID", "Name", "Release", "ScheduleState", "PlanEstimate"];
        var queryString = Ext.JSON.encode(query);

        // set context to global across the workspace
        var context = this.getContext().getDataContext();
        context.project = undefined;

        // fetch the snapshot of all leaf level stories for the PI
        var ssPiLeafStories = Ext.create('Rally.data.lookback.SnapshotStore', {
            context:{
                workspace:this.context.getWorkspace(),
                project:this.context.getProject()
            },
            fetch:find,
            rawFind:query,
            hydrate: ["ScheduleState"],
            autoLoad:true,
            listeners:{
                scope:this,
                load:this._processPiStories
            }
        });

    }, // end _getStoriesInPi

    // bucket the PI's stories by RELEASE (and no release)
    _processPiStories:function (store, records) {

        // spit out all leaf stories into a grid
        var snapshotGrid = Ext.create('Rally.ui.grid.Grid', {
            title:'Snapshots',
            store:store,
            columnCfgs:[
                {
                    text:'ObjectID',
                    dataIndex:'ObjectID'
                },
                {
                    text:'Name',
                    dataIndex:'Name'
                },
                {
                    text:'Project',
                    dataIndex:'Project'
                },
                {
                    text:'_UnformattedID',
                    dataIndex:'_UnformattedID'
                },
                ,
                {
                    text:'Release',
                    dataIndex:'Release'
                },
                {
                    text:'PlanEstimate',
                    dataIndex:'PlanEstimate'
                },
                {
                    text:'ScheduleState',
                    dataIndex:'ScheduleState'
                }
            ],
            height:400
        });

        // render the grid of all of the PI's leaf stories
        var gridHolder = this.down('#piLeafStoryGridContainer');
        gridHolder.removeAll(true);
        gridHolder.add(snapshotGrid);

        // --- BUCKET TIME BABY ---
        var aStory;
        var aRelease;

        var nbrStories = records.length;
        //console.log("nbrStories: " + nbrStories);

        var storyNdx;

        // loop through each of the PI's stories
        for (storyNdx = 0; storyNdx < nbrStories; storyNdx++){
            aStory = records[storyNdx];

            if (aStory !== null){

//                console.dir(aStory);
//                console.log("aStory" + aStory);
//                console.log("aStory" + aStory.get("Name"));
//                console.log("aStory.PlanEstimate: " + aStory.get("PlanEstimate"));
//                console.log("aStory.Release: " + aStory.get("Release"));
//                console.log("aStory.ScheduleState: " + aStory.get("ScheduleState"));

                aRelease = null;

                aRelease = this._findReleaseEntry(this.gPiReleases, aStory.Release);

                if (aRelease === null){

                    // populate initial entry for this release
                    aRelease = new Object();

                    aRelease.itsStoryCount = 0;
                    aRelease.itsStoryPlanEstimate = 0;
                    aRelease.itsStoryCountAccepted = 0;
                    aRelease.itsStoryPlanEstimateAccepted = 0;

                }

                if (!aStory.get("Release")){
                    aRelease.itsOID = "Not Scheduled";
                }
                else{
                    aRelease.itsOID = aStory.get("Release");
                }

                aRelease.itsStoryCount += 1;
                aRelease.itsStoryPlanEstimate += aStory.get("PlanEstimate")||0;

                if (aStory.get("ScheduleState") === "Accepted"){
                    aRelease.itsStoryCountAccepted += 1;
                    aRelease.itsStoryPlanEstimateAccepted += aStory.get("PlanEstimate")||0;
                }

                this.gPiReleases.push(aRelease);

            } // end process this story

        } // end loop through all stories

        // process the PI's releases data
        this._processPiReleases();

        // fetch release names (we need to convert Release OIDs from the LBAPI to logical Release names)
        this._fetchReleaseNames();

        // --- END BUCKET TIME BABY ---

    }, // end _processPiStories

    _processPiReleases: function() {

        var nbrReleases = this.gPiReleases.length;
        console.log("nbrReleases: " + nbrReleases);

        var releaseNdx;
        var aRelease;

        // loop through each of the PI's releases
        for (releaseNdx = 0; releaseNdx < nbrReleases; releaseNdx++){

            aRelease = this.gPiReleases[releaseNdx];

        } // end loop through each of the PI's releases

    }, // end _processPiReleases

    // fetch all release names (we may later have to scale this back and do this more efficiently)
    _fetchReleaseNames: function() {

        var store = Ext.create('Rally.data.WsapiDataStore', {
            model: 'Release',

            fetch: ["ObjectID","Name"],
            // scope globally
            context: {
                project: null
            },
            limit: Infinity,
            autoLoad:true,
            listeners: {
                load: function(store, data, success) {
                    console.log("data",data);

                    // map release OIDs to release NAMES
                    this._mapReleaseOIDsToNames(store, data);

                },
                scope: this
            }
        });

    }, // end _fetchReleaseNames

    _mapReleaseOIDsToNames: function(theStore, allReleaseRecords)
    {
        var releaseNamesByObjectId = {};

        // create a hash of all WSAPI release OIDs to their Name
        Ext.Array.each(allReleaseRecords,function(releaseRecord){
            releaseNamesByObjectId[releaseRecord.get("ObjectID")] = releaseRecord.get("Name");
        });

        // loop through each PI's release object and set its name from the OID/Name hash
        Ext.Array.each(this.gPiReleases,function(piRelease){
            piRelease.itsName = releaseNamesByObjectId[piRelease.itsOID];

            if(!piRelease.itsName){
                piRelease.itsName = "Unscheduled";
            }
        });

        // bucket PI's releases by NAME (accounts for roll-up releases) into the summedPisByReleaseName object
        var summedPisByReleaseName = {};

        Ext.Array.each(this.gPiReleases,function(piRelease){
            if(!Ext.isObject(summedPisByReleaseName[piRelease.itsName])){
                summedPisByReleaseName[piRelease.itsName] = piRelease;

                // localize summed release entry
                var summedRelease = summedPisByReleaseName[piRelease.itsName];
            }
            else{
                // localize summed release entry
                var summedRelease = summedPisByReleaseName[piRelease.itsName];
                summedRelease.itsStoryCount += piRelease.itsStoryCount;
                summedRelease.itsStoryCountAccepted += piRelease.itsStoryCountAccepted;
                summedRelease.itsStoryPlanEstimate += piRelease.itsStoryPlanEstimate;
                summedRelease.itsStoryPlanEstimateAccepted += piRelease.itsStoryPlanEstimateAccepted;
            }

            //console.log(summedRelease);

        });

        var arrayOfStuff = Ext.Object.getValues(summedPisByReleaseName);

        // chart PI's release meta data
        this._chartPiReleases(arrayOfStuff);

    }, // end _fetchReleaseNames

    // chart out the PI's bucketed by name releases
    _chartPiReleases:function (piSummaryDatas) {

        console.log(piSummaryDatas);

        // define a custom  model
        var aModel = Ext.define('CustomStoryModel', {
            extend: 'Ext.data.Model',
            fields: [
                {name: 'itsName',  type: 'string'},
                {name: 'itsOID',   type: 'int'},
                {name: 'itsStoryCount',   type: 'int'},
                {name: 'itsStoryCountAccepted',   type: 'int'},
                {name: 'itsStoryPlanEstimate',   type: 'int'},
                {name: 'itsStoryPlanEstimateAccepted',   type: 'int'}
            ]
        });

        // define a store built around the custom  model
        var aStore = Ext.create('Ext.data.Store', {
            storeId: 'piReleaseStore',
            model: aModel,
            data: piSummaryDatas
        });

        // define a rally grid to output the store's data in
        var aPiReleaseGrid = Ext.create('Rally.ui.grid.Grid', {
            itemId: 'piReleaseGrid',
            store: aStore,
            width: 470,
            columnCfgs: [
                {
                    text: 'Release', dataIndex: 'itsName', width: 80
                },
                {
                    text: 'Release ID', dataIndex: 'itsOID', width: 80
                },
                {
                    text: 'Story Count', dataIndex: 'itsStoryCount', width: 80
                },
                {
                    text: 'Accepted Story Count', dataIndex: 'itsStoryCountAccepted', width: 80
                },
                {
                    text: 'Plan Estimate', dataIndex: 'itsStoryPlanEstimate', width: 80
                },
                {
                    text: 'Accepted Plan Estimate', dataIndex: 'itsStoryPlanEstimateAccepted', width: 80
                }
            ] // end columnCfgs
        });

        // render the grid of all of the PI's leaf stories
        var aPiReleaseGridContainer = this.down('#piReleaseGridContainer');
        aPiReleaseGridContainer.removeAll(true);
        aPiReleaseGridContainer.add(aPiReleaseGrid);

    }, // end _chartPiReleases

    _findReleaseEntry:function (theArr, theReleaseOID) {

        // check if array is empty
        if (this.gReleaseArray === null)
            return null;

        arrLen = theArr.length;

        for (x = 0; x < arrLen; x++) {
            var anEntry = theArr[x];

            if (anEntry.itsOID == theReleaseOID) {
                return anEntry
            }
        }
        return null;
    } // end _findReleaseEntry

});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2012, Robin Appelman <icewind1991@gmail.com>
 * This file is licensed under the Affero General Public License version 3 or later.
 * See the COPYING-README file.
 */

OC.Log={
	reload:function(count){
		if(!count){
			count=OC.Log.loaded;
		}
		OC.Log.loaded=0;
		$('#log tbody').empty();
		OC.Log.getMore(count);
	},
	levels:['Debug','Info','Warning','Error','Fatal'],
	loaded:3,//are initially loaded
	getMore:function(count){
		if(!count){
			count=10;
		}
		$.get(OC.filePath('settings','ajax','getlog.php'),{offset:OC.Log.loaded,count:count},function(result){
			if(result.status=='success'){
				OC.Log.addEntries(result.data);
				$('html, body').animate({scrollTop: $(document).height()}, 800);
				if(!result.remain){
					$('#moreLog').css('display', 'none');
				}
				$('#lessLog').css('display', '');
			}
		});
	},
	showLess:function(count){
		count = count || 10;
		$('#moreLog').css('display', '');
		$('html, body').animate({scrollTop: $(document).height()}, 800);
		while(OC.Log.loaded > 3 && count){
			$('#log tr').last().remove()
			OC.Log.loaded -= 1;
			count--;
		}
		if(OC.Log.loaded <= 3)
			$('#lessLog').css('display', 'none');
	},
	addEntries:function(entries){
		for(var i=0;i<entries.length;i++){
			var entry=entries[i];
			var row=$('<tr/>');
			var levelTd=$('<td/>');
			levelTd.text(OC.Log.levels[entry.level]);
			row.append(levelTd);

			var appTd=$('<td/>');
			appTd.text(entry.app);
			row.append(appTd);

			var messageTd=$('<td/>');
			messageTd.text(entry.message);
			row.append(messageTd);

			var timeTd=$('<td/>');
			timeTd.text(formatDate(entry.time*1000));
			row.append(timeTd);
			$('#log').append(row);
		}
		OC.Log.loaded += entries.length;
	}
}

$(document).ready(function(){
	$('#moreLog').click(function(){
		OC.Log.getMore();
	})
	$('#lessLog').click(function(){
		OC.Log.showLess();
	})
});
<commit_msg>remove animation<commit_after>/**
 * Copyright (c) 2012, Robin Appelman <icewind1991@gmail.com>
 * This file is licensed under the Affero General Public License version 3 or later.
 * See the COPYING-README file.
 */

OC.Log={
	reload:function(count){
		if(!count){
			count=OC.Log.loaded;
		}
		OC.Log.loaded=0;
		$('#log tbody').empty();
		OC.Log.getMore(count);
	},
	levels:['Debug','Info','Warning','Error','Fatal'],
	loaded:3,//are initially loaded
	getMore:function(count){
		if(!count){
			count=10;
		}
		$.get(OC.filePath('settings','ajax','getlog.php'),{offset:OC.Log.loaded,count:count},function(result){
			if(result.status=='success'){
				OC.Log.addEntries(result.data);
				$('html, body').animate({scrollTop: $(document).height()}, 800);
				if(!result.remain){
					$('#moreLog').css('display', 'none');
				}
				$('#lessLog').css('display', '');
			}
		});
	},
	showLess:function(count){
		count = count || 10;
		$('#moreLog').css('display', '');
		while(OC.Log.loaded > 3 && count){
			$('#log tr').last().remove();
			OC.Log.loaded -= 1;
			count--;
		}
		if(OC.Log.loaded <= 3)
			$('#lessLog').css('display', 'none');
	},
	addEntries:function(entries){
		for(var i=0;i<entries.length;i++){
			var entry=entries[i];
			var row=$('<tr/>');
			var levelTd=$('<td/>');
			levelTd.text(OC.Log.levels[entry.level]);
			row.append(levelTd);

			var appTd=$('<td/>');
			appTd.text(entry.app);
			row.append(appTd);

			var messageTd=$('<td/>');
			messageTd.text(entry.message);
			row.append(messageTd);

			var timeTd=$('<td/>');
			timeTd.text(formatDate(entry.time*1000));
			row.append(timeTd);
			$('#log').append(row);
		}
		OC.Log.loaded += entries.length;
	}
}

$(document).ready(function(){
	$('#moreLog').click(function(){
		OC.Log.getMore();
	})
	$('#lessLog').click(function(){
		OC.Log.showLess();
	})
});
<|endoftext|>


<commit_before><commit_msg>ajax request for scroll event<commit_after><|endoftext|>


<commit_before>/**
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

goog.provide('org.apache.flex.html.beads.controllers.ItemRendererMouseController');

goog.require('goog.events.Event');
goog.require('goog.events.EventType');
goog.require('org.apache.flex.core.IBeadController');

/**
 * @constructor
 * @implements {org.apache.flex.core.IBeadController}
 */
org.apache.flex.html.beads.controllers.ItemRendererMouseController = function() {
};

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org.apache.flex.html.beads.controllers.ItemRendererMouseController.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'ItemRendererMouseController',
                qName: 'org.apache.flex.html.beads.controllers.ItemRendererMouseController' }],
      interfaces: [org.apache.flex.core.IBeadController] };

Object.defineProperties(org.apache.flex.html.beads.controllers.ItemRendererMouseController.prototype, {
    /** @export */
    strand: {
        /** @this {org.apache.flex.html.beads.controllers.ItemRendererMouseController} */
        set: function(value) {
            this.strand_ = value;

            goog.events.listen(this.strand_.element, goog.events.EventType.MOUSEOVER,
                goog.bind(this.handleMouseOver, this));

            goog.events.listen(this.strand_.element, goog.events.EventType.MOUSEOUT,
                goog.bind(this.handleMouseOut, this));

            goog.events.listen(this.strand_.element, goog.events.EventType.MOUSEDOWN,
                goog.bind(this.handleMouseDown, this));

            goog.events.listen(this.strand_.element, goog.events.EventType.MOUSEUP,
                goog.bind(this.handleMouseUp, this));
        }
    }
});

/**
 * @export
 * @param {Object} event The mouse event that triggered the hover.
 */
org.apache.flex.html.beads.controllers.ItemRendererMouseController.prototype.handleMouseOver = function(event) {

  this.strand_.hovered = true;

  var newEvent = new goog.events.Event('rollover');
  newEvent.target = this.strand_;
  this.strand_.itemRendererParent.dispatchEvent(newEvent);
};

/**
 * @export
 * @param {Object} event The mouse-out event.
 */
org.apache.flex.html.beads.controllers.ItemRendererMouseController.prototype.handleMouseOut = function(event) {

  this.strand_.hovered = false;

  var newEvent = new goog.events.Event('rollout');
  newEvent.target = this.strand_;
  this.strand_.itemRendererParent.dispatchEvent(newEvent);
};

/**
 * @export
 * @param {Object} event The mouse-down event.
 */
org.apache.flex.html.beads.controllers.ItemRendererMouseController.prototype.handleMouseDown = function(event) {

  // ??
};

/**
 * @export
 * @param {Object} event The mouse-up event that triggers the selection.
 */
org.apache.flex.html.beads.controllers.ItemRendererMouseController.prototype.handleMouseUp = function(event) {

  var newEvent = new goog.events.Event('selected');

  // normally you do not - and should not - change the target of an event,
  // but these events do not propagate nor bubble up the object tree, so
  // we have to force the event's target to be this item renderer instance.

  newEvent.target = this.strand_;

  // since the event is not going to up the chain, we also have to dispatch
  // it against its final destination.

  this.strand_.itemRendererParent.dispatchEvent(newEvent);
};
<commit_msg>use native event for rollover/rollout<commit_after>/**
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

goog.provide('org.apache.flex.html.beads.controllers.ItemRendererMouseController');

goog.require('goog.events.Event');
goog.require('goog.events.EventType');
goog.require('org.apache.flex.core.IBeadController');

/**
 * @constructor
 * @implements {org.apache.flex.core.IBeadController}
 */
org.apache.flex.html.beads.controllers.ItemRendererMouseController = function() {
};

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org.apache.flex.html.beads.controllers.ItemRendererMouseController.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'ItemRendererMouseController',
                qName: 'org.apache.flex.html.beads.controllers.ItemRendererMouseController' }],
      interfaces: [org.apache.flex.core.IBeadController] };

Object.defineProperties(org.apache.flex.html.beads.controllers.ItemRendererMouseController.prototype, {
    /** @export */
    strand: {
        /** @this {org.apache.flex.html.beads.controllers.ItemRendererMouseController} */
        set: function(value) {
            this.strand_ = value;

            goog.events.listen(this.strand_.element, goog.events.EventType.MOUSEOVER,
                goog.bind(this.handleMouseOver, this));

            goog.events.listen(this.strand_.element, goog.events.EventType.MOUSEOUT,
                goog.bind(this.handleMouseOut, this));

            goog.events.listen(this.strand_.element, goog.events.EventType.MOUSEDOWN,
                goog.bind(this.handleMouseDown, this));

            goog.events.listen(this.strand_.element, goog.events.EventType.MOUSEUP,
                goog.bind(this.handleMouseUp, this));
        }
    }
});

/**
 * @export
 * @param {Object} e The mouse event that triggered the hover.
 */
org.apache.flex.html.beads.controllers.ItemRendererMouseController.prototype.handleMouseOver = function(e) {

  this.strand_.hovered = true;

  var newEvent = new MouseEvent('rollover');
  newEvent.initMouseEvent('rollover', false, false,
    e.view, e.detail, e.screenX, e.screenY,
    e.clientX, e.clientY, e.ctrlKey, e.altKey,
    e.shiftKey, e.metaKey, e.button, e.relatedTarget);
  this.strand_.itemRendererParent.dispatchEvent(newEvent);
};

/**
 * @export
 * @param {Object} e The mouse-out event.
 */
org.apache.flex.html.beads.controllers.ItemRendererMouseController.prototype.handleMouseOut = function(e) {

  this.strand_.hovered = false;

  var newEvent = new MouseEvent('rollout');
  newEvent.initMouseEvent('rollout', false, false,
    e.view, e.detail, e.screenX, e.screenY,
    e.clientX, e.clientY, e.ctrlKey, e.altKey,
    e.shiftKey, e.metaKey, e.button, e.relatedTarget);
  this.strand_.itemRendererParent.dispatchEvent(newEvent);
};

/**
 * @export
 * @param {Object} event The mouse-down event.
 */
org.apache.flex.html.beads.controllers.ItemRendererMouseController.prototype.handleMouseDown = function(event) {

  // ??
};

/**
 * @export
 * @param {Object} event The mouse-up event that triggers the selection.
 */
org.apache.flex.html.beads.controllers.ItemRendererMouseController.prototype.handleMouseUp = function(event) {

  var newEvent = new goog.events.Event('selected');

  // normally you do not - and should not - change the target of an event,
  // but these events do not propagate nor bubble up the object tree, so
  // we have to force the event's target to be this item renderer instance.

  newEvent.target = this.strand_;

  // since the event is not going to up the chain, we also have to dispatch
  // it against its final destination.

  this.strand_.itemRendererParent.dispatchEvent(newEvent);
};
<|endoftext|>


<commit_before>'use strict';

// Committees controller
angular.module('committees').controller('CommitteesController', ['$rootScope', '$scope', '$stateParams', '$location', 'Authentication', 'Users', 'Committees', '$q', '$log',
	function($rootScope, $scope, $stateParams, $location, Authentication,Users, Committees, $q, $log) {
		$scope.authentication = Authentication;
		$scope.currentUser = Authentication.user;

		// Create new Committee
		$scope.create = function() {
			// Create new Committee object
			var committee = new Committees.Committees ({
				name: this.name,
				chair: this.chair
			});

			// Redirect after save
			committee.$save(function(response) {
				$location.path('committees/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Committee
		$scope.remove = function( committee ) {
			if ( committee ) { committee.$remove();

				for (var i in $scope.committees ) {
					if ($scope.committees [i] === committee ) {
						$scope.committees.splice(i, 1);
					}
				}
			} else {
				$scope.committee.$remove(function() {
					$location.path('committees');
				});
			}
		};

		// Update existing Committee
		$scope.update = function() {
			var committee = $scope.committee ;

			committee.$update(function() {
				$location.path('committees/' + committee._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		//Add member to committee
		$scope.addMember = function(user){
			var committee = $scope.committee;
			var passed = 1;
			angular.forEach(committee.members, function(members){
				if(members === user._id) passed = 0;
			});
			if(passed) Committees.Member.update({userId: user._id,committeeId: committee._id});

		};

		$scope.removeMember = function(member){
			var committee = $scope.committee;
			var passed = 0;
			angular.forEach(committee.members, function(members){
				if(members === member._id) passed = 1;
			});
			if(passed) Committees.Member.remove({userId: member._id,committeeId: committee._id});
		};

		$scope.getMembers = function(){
			var committee = $scope.committee;
			var Members = Committees.Members.query({committeeId: committee._id}).$promise.then(function(data) {
				console.log(data);
				$scope.members = data;
			});
		};

		$scope.removeChair = function(){
			var committee = $scope.committee;
			Committees.Chair.delete({committeeId: committee._id, chairId: committee.chair}).$promise.then(function(data) {
				console.log(data);
				$scope.committee = data;

			});
		};

		$scope.updateChair = function(user){
			var committee = $scope.committee;
			Committees.Chair.delete({committeeId: committee._id, chairId: user._id}).$promise.then(function(data) {
				console.log(data);
				$scope.committee = data;
			});
		};
		$scope.getChair = function(){
			var committee = $scope.committee;
			Committees.Chair.get({committeeId: committee._id, chairId: committee.chair}).$promise.then(function(data) {
				console.log(data);
				$scope.chair = data;
			});
		};

		// Find a list of Committees
		$scope.find = function() {
			// $scope.committees = Committees.query();

			Committees.Committees.query().$promise.then(function(data) {
				$scope.committees = data;

				// $log.debug('data: ');
				// $log.debug(data);

				// $log.debug('$scope.committees: ');
				// $log.debug($scope.committees);
			});

		};

		$scope.checkAdmin = function(){
			var user = new Users($scope.currentUser);
			if(user.role === 'Admin'){
				return true;
			}
			else{
				return false;
			}
		};

		$scope.checkLoggedIn = function(){
			var user = new Users($scope.currentUser);
			if(!$scope.currentUser){
				return false;
			}
			else{
				return true;
			}
		};

		$scope.checkOwner = function(committee){
		//	var user = new Users($scope.currentUser);
		//	var committee = $scope.committee;
			if($scope.currentUser.displayName===committee.user.displayName){
				return true;
			}
			else{
				return false;
			}
		};

		$scope.userInCommittee = function(committee){
			//console.log($scope.committee.members);
			//console.log($scope.committee._id);
			//console.log(user);

			if(typeof committee !== 'undefined'){
				for(var i = 0; i < committee.members.length; i++){
					if($scope.currentUser._id === committee.members[i]._id){
						return true;
					}
				}
				return false;
			}
			return false;

			/*for(var i = 0; i < committee.members.length; i++){
				var temp = committee.members[i]._id;
				console.log(temp);
				//console.log(Users.get({userId: $stateParams.userId});
				console.log(Users.get({
					 temp: $stateParams.userId
				}));
			}*/
		};

		// Find existing Committee
		$scope.findOne = function() {
			Committees.Committees.get({
				committeeId: $stateParams.committeeId
			}).$promise.then(function(data) {
				//TEMPORARY SOLUTION FOR SPRINT 1
				$rootScope.committee = data;

				// $log.debug('$scope.committee: ');
				// $log.debug($scope.committee);
				// $log.debug('$scope.committee._id');
				// $log.debug($scope.committee._id);
			});

			// $scope.test =

			// 	Committees.get({
			// 		committeeId: $stateParams.committeeId
			// 	}).$promise.then(function(data) {
			// 		$scope.committee = data;
			// 		return data;
			// 	});

			// test.then(function(data) {

			// 	// $log.debug( $state.href('edit', {data._id}) );

			// 	console.log("data:");
			// 	console.log(data);

			// 	console.log("$scope.committee:");
			// 	console.log($scope.committee);
			// 	console.log("$scope.committee.members:")
			// 	console.log($scope.committee.members);
			// 	console.log("$scope.committee.name:");
			// 	console.log($scope.committee.name);

			// });
		};

		// // Show edit button
		// $scope.showEdit = function($stateParams) {

		// 	$log.debug('$stateParams:');
		// 	$log.debug($stateParams.committeeId);
		// 	$log.debug('$scope.committee._id:');
		// 	$log.debug($scope.committee._id);

		// 	if($stateParams.committeeId === $scope.committee._id){
		// 		return true;
		// 	}

		// 	return false;

		// };
	}
]);<commit_msg>Update<commit_after>'use strict';

// Committees controller
angular.module('committees').controller('CommitteesController', ['$rootScope', '$scope', '$stateParams', '$location', 'Authentication', 'Users', 'Committees', '$q', '$log',
	function($rootScope, $scope, $stateParams, $location, Authentication,Users, Committees, $q, $log) {
		$scope.authentication = Authentication;
		$scope.currentUser = Authentication.user;

		// Create new Committee
		$scope.create = function() {
			// Create new Committee object
			var committee = new Committees.Committees ({
				name: this.name,
				chair: this.chair
			});

			// Redirect after save
			committee.$save(function(response) {
				$location.path('committees/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Committee
		$scope.remove = function( committee ) {
			if ( committee ) { committee.$remove();

				for (var i in $scope.committees ) {
					if ($scope.committees [i] === committee ) {
						$scope.committees.splice(i, 1);
					}
				}
			} else {
				$scope.committee.$remove(function() {
					$location.path('committees');
				});
			}
		};

		// Update existing Committee
		$scope.update = function() {
			var committee = $scope.committee ;

			committee.$update(function() {
				$location.path('committees/' + committee._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		//Add member to committee
		$scope.addMember = function(user){
			var committee = $scope.committee;
			var passed = 1;
			angular.forEach(committee.members, function(members){
				if(members === user._id) passed = 0;
			});
			if(passed) Committees.Member.update({userId: user._id,committeeId: committee._id});

		};

		$scope.removeMember = function(member){
			var committee = $scope.committee;
			var passed = 0;
			angular.forEach(committee.members, function(members){
				if(members === member._id) passed = 1;
			});
			if(passed) Committees.Member.remove({userId: member._id,committeeId: committee._id});
		};

		$scope.getMembers = function(){
			var committee = $scope.committee;
			var Members = Committees.Members.query({committeeId: committee._id}).$promise.then(function(data) {
				console.log(data);
				$scope.members = data;
			});
		};

		$scope.removeChair = function(){
			var committee = $scope.committee;
			Committees.Chair.delete({committeeId: committee._id, chairId: committee.chair}).$promise.then(function(data) {
				console.log(data);
				$scope.committee = data;

			});
		};

		$scope.updateChair = function(user){
			var committee = $scope.committee;
			Committees.Chair.delete({committeeId: committee._id, chairId: user._id}).$promise.then(function(data) {
				console.log(data);
				$scope.committee = data;
			});
		};
		$scope.getChair = function(){
			var committee = $scope.committee;
			Committees.Chair.get({committeeId: committee._id, chairId: committee.chair}).$promise.then(function(data) {
				console.log(data);
				$scope.committee = data;
			});
		};

		// Find a list of Committees
		$scope.find = function() {
			// $scope.committees = Committees.query();

			Committees.Committees.query().$promise.then(function(data) {
				$scope.committees = data;

				// $log.debug('data: ');
				// $log.debug(data);

				// $log.debug('$scope.committees: ');
				// $log.debug($scope.committees);
			});

		};

		$scope.checkAdmin = function(){
			var user = new Users($scope.currentUser);
			if(user.role === 'Admin'){
				return true;
			}
			else{
				return false;
			}
		};

		$scope.checkLoggedIn = function(){
			var user = new Users($scope.currentUser);
			if(!$scope.currentUser){
				return false;
			}
			else{
				return true;
			}
		};

		$scope.checkOwner = function(committee){
		//	var user = new Users($scope.currentUser);
		//	var committee = $scope.committee;
			if($scope.currentUser.displayName===committee.user.displayName){
				return true;
			}
			else{
				return false;
			}
		};

		$scope.userInCommittee = function(committee){
			//console.log($scope.committee.members);
			//console.log($scope.committee._id);
			//console.log(user);

			if(typeof committee !== 'undefined'){
				for(var i = 0; i < committee.members.length; i++){
					if($scope.currentUser._id === committee.members[i]._id){
						return true;
					}
				}
				return false;
			}
			return false;

			/*for(var i = 0; i < committee.members.length; i++){
				var temp = committee.members[i]._id;
				console.log(temp);
				//console.log(Users.get({userId: $stateParams.userId});
				console.log(Users.get({
					 temp: $stateParams.userId
				}));
			}*/
		};

		// Find existing Committee
		$scope.findOne = function() {
			Committees.Committees.get({
				committeeId: $stateParams.committeeId
			}).$promise.then(function(data) {
				//TEMPORARY SOLUTION FOR SPRINT 1
				$rootScope.committee = data;

				// $log.debug('$scope.committee: ');
				// $log.debug($scope.committee);
				// $log.debug('$scope.committee._id');
				// $log.debug($scope.committee._id);
			});

			// $scope.test =

			// 	Committees.get({
			// 		committeeId: $stateParams.committeeId
			// 	}).$promise.then(function(data) {
			// 		$scope.committee = data;
			// 		return data;
			// 	});

			// test.then(function(data) {

			// 	// $log.debug( $state.href('edit', {data._id}) );

			// 	console.log("data:");
			// 	console.log(data);

			// 	console.log("$scope.committee:");
			// 	console.log($scope.committee);
			// 	console.log("$scope.committee.members:")
			// 	console.log($scope.committee.members);
			// 	console.log("$scope.committee.name:");
			// 	console.log($scope.committee.name);

			// });
		};

		// // Show edit button
		// $scope.showEdit = function($stateParams) {

		// 	$log.debug('$stateParams:');
		// 	$log.debug($stateParams.committeeId);
		// 	$log.debug('$scope.committee._id:');
		// 	$log.debug($scope.committee._id);

		// 	if($stateParams.committeeId === $scope.committee._id){
		// 		return true;
		// 	}

		// 	return false;

		// };
	}
]);<|endoftext|>


<commit_before>'use strict';

var splatoonApp = angular.module('splatoonApp', []);

splatoonApp.controller('MainCtrl', function ($scope) {

	$scope.mains = [];

	//Load in datatables
	angular.module('splatoonApp').abilities($scope);
	angular.module('splatoonApp').gear($scope);
	angular.module('splatoonApp').weapons($scope);
	angular.module('splatoonApp').subweapons($scope);
	angular.module('splatoonApp').specials($scope);

	//Start main logic
	$scope.points = 0;
	$scope.subs = [];
	$scope.effectiveDamage = {};
	$scope.effectiveSubDamage = {};
	$scope.stateCode = "none";
	$scope.subweapon = false;
	$scope.effectiveSpecialDuration = 0;
	$scope.showModal = false;
	$scope.ErrorMessage= 'Testing';
	$scope.selectedCategory = $scope.weapons[0];
	$scope.selectedWeapon = $scope.selectedCategory.weapons[0];

	//init stats last
	angular.module('splatoonApp').stats($scope);

	calc();

	for(let category of $scope.weapons){
		for(let weapon of category.weapons){
			weapon.uname = weapon.name.replace(/ /g,'_').replace('.','').replace('\'','');
		 }
	 }
  $scope.toggleModal = function(){
        $scope.showModal = !$scope.showModal;
  };
  $scope.onCategoryChange = function(){
		$scope.selectedWeapon = $scope.selectedCategory.weapons[0];
		$scope.onWeaponChange();
  };
  $scope.onWeaponChange = function(){
        calc();
  };

  $scope.onCodeChange = function(){
		$scope.stateURL = generateURL($scope.stateCode)
  };

  function generateURL(code){
	  return window.location.href.split('?')[0] + "?b=" + $scope.stateCode
  }

  function loadFromURL(url){
	var arr = url.match(/b=([0-9a-fA-F]+)/)
	if(arr) {
		var code = arr[1];
	} else {
		console.log("no code to load")
		return;
	}
	var decoded = decode(code);
	if(decoded) {
	//check if all abilities and weapon are valid before loading
	//FIXME: doesn't allow for less than maxed abilities
		for(var i=0; i<decoded[1].length; i++) {
			if(!$scope.getAbilityById(decoded[1][i])) {
				console.log("code invalid: invalid ability")
				return;
			}
		}
		if(!$scope.getWeaponById(decoded[0])) {
			console.log("code invalid: invalid weapon")
			return;
		}
		for(var i=0; i<decoded[1].length; i++) {
			if($scope.getAbilityById(decoded[1][i])) {
				$scope.activate($scope.getAbilityById(decoded[1][i]))
			}
		}
		$scope.selectedWeapon = $scope.getWeaponById(decoded[0]);
		$scope.selectedCategory = $scope.getCategory($scope.selectedWeapon.type);

	} else {
		return;
	}

  }

  $scope.activate = function(ability){

		/*
		for(var i = 0; i < $scope.mains.length; i++){
			for(var j=0; j < $scope.gear.length; j++){

					if($scope.gear[j].ability === $scope.mains[i].name){
						abilitygear[i].push($scope.gear[j].type)
				}

			}
		}
		*/

		if ($scope.points >= 57) {
			//alert('Too Many Abilities!!');
			$scope.ErrorMessage = 'Too Many Abilities!!';
			$scope.toggleModal();
			return;
		}

		var i = $scope.abilities.indexOf(ability);
		if( $scope.mains.length<3 ){

			if($scope.abilities[i].stackable || $scope.mains.indexOf(ability) == -1){
				$scope.mains.push($scope.abilities[i]);
				$scope.points+=10;
				console.log($scope.mains.length);

				console.log($scope.mains[$scope.mains.length-1]);
				calc();
			}
			else {
				//alert('Cannot Stack This Ability!!');
				$scope.ErrorMessage = 'Cannot Stack This Ability!!';
				$scope.toggleModal();
				return;
			}
		}

		else if ( $scope.abilities[i].stackable ){
			$scope.subs.push($scope.abilities[i]);
			$scope.points+=3;
			calc();
		}
		else {
			//alert('Cannot Sub This Ability!!');
			$scope.ErrorMessage = 'Cannot Sub This Ability!!';
			$scope.toggleModal();		}
	};

	$scope.demain = function(main) {
		$scope.mains.splice($scope.mains.indexOf(main), 1);
		$scope.points-=10;
		calc();
	};
	$scope.desub = function(sub) {
		$scope.subs.splice($scope.subs.indexOf(sub), 1);
		$scope.points-=3;
		calc();
	};

	// Calc function for finding values
	function calc() {

		//Hide all gear and show what is selected.
		for(var i = 0; i < $scope.gear.length; i++){
				console.log('hiding gear');
				$scope.gear[i].show = false;
				$scope.gear[i].uname = $scope.gear[i].name.replace(/ /g,'_');
			}
			console.log($scope.gear[0].show);

		for(var i = 0; i < $scope.gear.length; i++){
				for(var j=0; j < $scope.mains.length; j++){

					if($scope.gear[i].ability === $scope.mains[j].name){
						console.log('showing ' + $scope.gear[i].name);

						$scope.gear[i].show = true;
						console.log('showing ' + $scope.gear[i].show);

					}
					for(var itm in $scope.gear[i]){
						if(itm === $scope.mains[j].name && $scope.gear[i][itm] === '1/3.3'){
							console.log('showing ' + $scope.gear[i].name);
							$scope.gear[i].show = true;
							console.log('showing ' + $scope.gear[i].show);
						}
					}
				}
			}

		for(var i=0; i < $scope.stats.length; i++){
			var name = $scope.stats[i].name;
			$scope.stats[i].apply(
				$scope.mains.count(name),
				$scope.subs.count(name)
			);
		}

		//TODO: refactor this
		$scope.effectiveDamage = {};
		for(var k in $scope.selectedWeapon.damageValues) $scope.effectiveDamage[k]=$scope.selectedWeapon.damageValues[k];
		for(var key in $scope.effectiveDamage) {
			var value = $scope.effectiveDamage[key];
			value = ((value*$scope.getStatByName("Damage").value)/100).toFixed(1)
			// splatoon caps main damage values at specific thresholds
			if(value>33.3 && $scope.selectedWeapon.damageValues[key]<33.3) value = 33.3;
			if(value>49.9 && $scope.selectedWeapon.damageValues[key]<49.9) value = 49.9;
			if(value>99.9 && $scope.selectedWeapon.damageValues[key]<99.9) value = 99.9;
			$scope.effectiveDamage[key]=value;
		}

		$scope.subweapon = $.grep($scope.subweapons, function(e){ return e.name == $scope.selectedWeapon.sub; })[0];
		$scope.effectiveSubDamage = {};
		for(var k in $scope.subweapon.damageValues) $scope.effectiveSubDamage[k]=$scope.subweapon.damageValues[k];
		for(var key in $scope.effectiveSubDamage) {
			var value = $scope.effectiveSubDamage[key];
			value = ((value*$scope.getStatByName("Damage").value)/100).toFixed(1)
			$scope.effectiveSubDamage[key]=value;
		}

		var special = $.grep($scope.specials, function(e){ return e.name == $scope.selectedWeapon.special; })[0];
		var specialDurationAbility = $scope.mains.count("Special Time")*10 + $scope.subs.count("Special Time")*3;
		if(special.durationCoeff != 1) {
		$scope.effectiveSpecialDuration =  (1+((0.99 * specialDurationAbility) - Math.pow((0.09 * specialDurationAbility),2)) / special.durationCoeff) * special.duration;
		} else {
			$scope.effectiveSpecialDuration = special.duration;
		}

		$scope.stateCode = encode($scope.selectedWeapon,$scope.mains,$scope.subs)
        $scope.stateURL = generateURL($scope.stateCode)
	}

	$scope.clear = function() {
		console.log('CLEARED');
		$scope.mains.length=0;
		$scope.subs.length=0;
		$scope.points = 0;
		calc();
	};

	loadFromURL(window.location.href)
});

splatoonApp.directive('modal', function () {
    return {
      template: '
' +
          '
' +
            '
' +
              '
' +
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
                '
{{ ErrorMessage }}
' +
								'
' +
								'
' +
									'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>' +
									'
' +
								'
' +
	            '
' +
	          '
' +
	        '
',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
});
<commit_msg>Fixed issue with loading weapon stats when loading from URL<commit_after>'use strict';

var splatoonApp = angular.module('splatoonApp', []);

splatoonApp.controller('MainCtrl', function ($scope) {

	$scope.mains = [];

	//Load in datatables
	angular.module('splatoonApp').abilities($scope);
	angular.module('splatoonApp').gear($scope);
	angular.module('splatoonApp').weapons($scope);
	angular.module('splatoonApp').subweapons($scope);
	angular.module('splatoonApp').specials($scope);

	//Start main logic
	$scope.points = 0;
	$scope.subs = [];
	$scope.effectiveDamage = {};
	$scope.effectiveSubDamage = {};
	$scope.stateCode = "none";
	$scope.subweapon = false;
	$scope.effectiveSpecialDuration = 0;
	$scope.showModal = false;
	$scope.ErrorMessage= 'Testing';
	$scope.selectedCategory = $scope.weapons[0];
	$scope.selectedWeapon = $scope.selectedCategory.weapons[0];

	//init stats last
	angular.module('splatoonApp').stats($scope);

	for(let category of $scope.weapons){
		for(let weapon of category.weapons){
			weapon.uname = weapon.name.replace(/ /g,'_').replace('.','').replace('\'','');
		 }
	 }
  $scope.toggleModal = function(){
        $scope.showModal = !$scope.showModal;
  };
  $scope.onCategoryChange = function(){
		$scope.selectedWeapon = $scope.selectedCategory.weapons[0];
		$scope.onWeaponChange();
  };
  $scope.onWeaponChange = function(){
        calc();
  };

  $scope.onCodeChange = function(){
		$scope.stateURL = generateURL($scope.stateCode)
  };

  function generateURL(code){
	  return window.location.href.split('?')[0] + "?b=" + $scope.stateCode
  }

  function loadFromURL(url){
	var arr = url.match(/b=([0-9a-fA-F]+)/)
	if(arr) {
		var code = arr[1];
	} else {
		console.log("no code to load")
		return;
	}
	var decoded = decode(code);
	if(decoded) {
	//check if all abilities and weapon are valid before loading
	//FIXME: doesn't allow for less than maxed abilities
		for(var i=0; i<decoded[1].length; i++) {
			if(!$scope.getAbilityById(decoded[1][i])) {
				console.log("code invalid: invalid ability")
				return;
			}
		}
		if(!$scope.getWeaponById(decoded[0])) {
			console.log("code invalid: invalid weapon")
			return;
		}
		for(var i=0; i<decoded[1].length; i++) {
			if($scope.getAbilityById(decoded[1][i])) {
				$scope.activate($scope.getAbilityById(decoded[1][i]))
			}
		}
		$scope.selectedWeapon = $scope.getWeaponById(decoded[0]);
		$scope.selectedCategory = $scope.getCategory($scope.selectedWeapon.type);

	} else {
		return;
	}

  }

  $scope.activate = function(ability){

		/*
		for(var i = 0; i < $scope.mains.length; i++){
			for(var j=0; j < $scope.gear.length; j++){

					if($scope.gear[j].ability === $scope.mains[i].name){
						abilitygear[i].push($scope.gear[j].type)
				}

			}
		}
		*/

		if ($scope.points >= 57) {
			//alert('Too Many Abilities!!');
			$scope.ErrorMessage = 'Too Many Abilities!!';
			$scope.toggleModal();
			return;
		}

		var i = $scope.abilities.indexOf(ability);
		if( $scope.mains.length<3 ){

			if($scope.abilities[i].stackable || $scope.mains.indexOf(ability) == -1){
				$scope.mains.push($scope.abilities[i]);
				$scope.points+=10;
				console.log($scope.mains.length);

				console.log($scope.mains[$scope.mains.length-1]);
				calc();
			}
			else {
				//alert('Cannot Stack This Ability!!');
				$scope.ErrorMessage = 'Cannot Stack This Ability!!';
				$scope.toggleModal();
				return;
			}
		}

		else if ( $scope.abilities[i].stackable ){
			$scope.subs.push($scope.abilities[i]);
			$scope.points+=3;
			calc();
		}
		else {
			//alert('Cannot Sub This Ability!!');
			$scope.ErrorMessage = 'Cannot Sub This Ability!!';
			$scope.toggleModal();		}
	};

	$scope.demain = function(main) {
		$scope.mains.splice($scope.mains.indexOf(main), 1);
		$scope.points-=10;
		calc();
	};
	$scope.desub = function(sub) {
		$scope.subs.splice($scope.subs.indexOf(sub), 1);
		$scope.points-=3;
		calc();
	};

	// Calc function for finding values
	function calc() {

		//Hide all gear and show what is selected.
		for(var i = 0; i < $scope.gear.length; i++){
				console.log('hiding gear');
				$scope.gear[i].show = false;
				$scope.gear[i].uname = $scope.gear[i].name.replace(/ /g,'_');
			}
			console.log($scope.gear[0].show);

		for(var i = 0; i < $scope.gear.length; i++){
				for(var j=0; j < $scope.mains.length; j++){

					if($scope.gear[i].ability === $scope.mains[j].name){
						console.log('showing ' + $scope.gear[i].name);

						$scope.gear[i].show = true;
						console.log('showing ' + $scope.gear[i].show);

					}
					for(var itm in $scope.gear[i]){
						if(itm === $scope.mains[j].name && $scope.gear[i][itm] === '1/3.3'){
							console.log('showing ' + $scope.gear[i].name);
							$scope.gear[i].show = true;
							console.log('showing ' + $scope.gear[i].show);
						}
					}
				}
			}

		for(var i=0; i < $scope.stats.length; i++){
			var name = $scope.stats[i].name;
			$scope.stats[i].apply(
				$scope.mains.count(name),
				$scope.subs.count(name)
			);
		}

		//TODO: refactor this
		$scope.effectiveDamage = {};
		for(var k in $scope.selectedWeapon.damageValues) $scope.effectiveDamage[k]=$scope.selectedWeapon.damageValues[k];
		for(var key in $scope.effectiveDamage) {
			var value = $scope.effectiveDamage[key];
			value = ((value*$scope.getStatByName("Damage").value)/100).toFixed(1)
			// splatoon caps main damage values at specific thresholds
			if(value>33.3 && $scope.selectedWeapon.damageValues[key]<33.3) value = 33.3;
			if(value>49.9 && $scope.selectedWeapon.damageValues[key]<49.9) value = 49.9;
			if(value>99.9 && $scope.selectedWeapon.damageValues[key]<99.9) value = 99.9;
			$scope.effectiveDamage[key]=value;
		}

		$scope.subweapon = $.grep($scope.subweapons, function(e){ return e.name == $scope.selectedWeapon.sub; })[0];
		$scope.effectiveSubDamage = {};
		for(var k in $scope.subweapon.damageValues) $scope.effectiveSubDamage[k]=$scope.subweapon.damageValues[k];
		for(var key in $scope.effectiveSubDamage) {
			var value = $scope.effectiveSubDamage[key];
			value = ((value*$scope.getStatByName("Damage").value)/100).toFixed(1)
			$scope.effectiveSubDamage[key]=value;
		}

		var special = $.grep($scope.specials, function(e){ return e.name == $scope.selectedWeapon.special; })[0];
		var specialDurationAbility = $scope.mains.count("Special Time")*10 + $scope.subs.count("Special Time")*3;
		if(special.durationCoeff != 1) {
		$scope.effectiveSpecialDuration =  (1+((0.99 * specialDurationAbility) - Math.pow((0.09 * specialDurationAbility),2)) / special.durationCoeff) * special.duration;
		} else {
			$scope.effectiveSpecialDuration = special.duration;
		}

		$scope.stateCode = encode($scope.selectedWeapon,$scope.mains,$scope.subs)
        $scope.stateURL = generateURL($scope.stateCode)
	}

	$scope.clear = function() {
		console.log('CLEARED');
		$scope.mains.length=0;
		$scope.subs.length=0;
		$scope.points = 0;
		calc();
	};
	//FIXME: move to onload function
	loadFromURL(window.location.href)
	calc();
});

splatoonApp.directive('modal', function () {
    return {
      template: '
' +
          '
' +
            '
' +
              '
' +
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
                '
{{ ErrorMessage }}
' +
								'
' +
								'
' +
									'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>' +
									'
' +
								'
' +
	            '
' +
	          '
' +
	        '
',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
});
<|endoftext|>


<commit_before>if (Meteor.isClient) {
  // counter starts at 0
  Session.setDefault("counter", 0);

  Template.hello.helpers({
    counter: function () {
      return Session.get("counter");
    }
  });

  Template.hello.events({
    'click button': function () {
      // increment the counter when button is clicked
      Session.set("counter", Session.get("counter") + 1);
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}
<commit_msg>Added random number to clicker<commit_after>if (Meteor.isClient) {
  // counter starts at 0
  Session.setDefault("counter", 0);

  Template.hello.helpers({
    counter: function () {
      return Session.get("counter");
    }
  });

  Template.hello.events({
    'click button': function () {
      // increment the counter when button is clicked
	var clicker = Math.floor((Math.random() * 10) + 1);
      Session.set("counter", Session.get("counter") + clicker);
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}
<|endoftext|>


<commit_before>//https://caniuse.com/#feat=history
if ((window.history && window.history.pushState)) {
    var startingHash = window.location.hash ? window.location.hash.replace('#', '') : null;

    // necessary to prevent browser from overriding our initial scroll
    // browser scroll is otherwise undefeatable
    history.pushState("", document.title, window.location.pathname);
    // necessary for chrome
    window.history.scrollRestoration = "manual";

    $(document).ready(function () {
        MathJax.Hub.Register.StartupHook("End", function () {
            var navHeight = $('nav').height();

            if (startingHash) {
                var elem = document.getElementById(startingHash);

                if (!elem) {
                    return;
                }

                // setTimeout is necessary for safari, but not firefox or chrome
                setTimeout(() => {
                    window.scrollTo(0, parseInt($(elem).offset().top, 10) - navHeight);
                    history.pushState({}, null, `#${startingHash}`);
                }, 0)
            }

            $(document).on('click', 'a', function (e) {
                var currentHref = location.href.split("#")[0];
                var hrefParts = this.href.split('#');

                if (hrefParts.length == 1 || hrefParts[0] !== currentHref) {
                    return;
                }

                var hash = hrefParts[1];
                var elem = document.getElementById(hash);

                if (!elem) {
                    console.warn(`Couldn't find element with id ${hash}`)
                    return;
                }

                e.preventDefault();
                window.scrollTo(0, parseInt($(elem).offset().top, 10) - navHeight);
                history.pushState({}, null, `#${hash}`);
            });
        });
    });
} else {
    console.warn("Histroy API unsupported. Please consider updating your browser");
}<commit_msg>support special characters in id (#7352)<commit_after>//https://caniuse.com/#feat=history
if ((window.history && window.history.pushState)) {
    var startingHash = window.location.hash ? decodeURIComponent(window.location.hash.replace('#', '')) : null;

    // necessary to prevent browser from overriding our initial scroll
    // browser scroll is otherwise undefeatable
    history.pushState("", document.title, window.location.pathname);
    // necessary for chrome
    window.history.scrollRestoration = "manual";

    $(document).ready(function () {
        MathJax.Hub.Register.StartupHook("End", function () {
            var navHeight = $('nav').height();

            if (startingHash) {
                var elem = document.getElementById(startingHash);

                if (!elem) {
                    return;
                }

                // setTimeout is necessary for safari, but not firefox or chrome
                setTimeout(() => {
                    window.scrollTo(0, parseInt($(elem).offset().top, 10) - navHeight);
                    history.pushState({}, null, `#${startingHash}`);
                }, 0)
            }

            $(document).on('click', 'a', function (e) {
                var currentHref = location.href.split("#")[0];
                var hrefParts = this.href.split('#');

                if (hrefParts.length == 1 || hrefParts[0] !== currentHref) {
                    return;
                }

                var hash = decodeURIComponent(hrefParts[1]);
                var elem = document.getElementById(hash);

                if (!elem) {
                    console.warn(`Couldn't find element with id ${hash}`)
                    return;
                }

                e.preventDefault();
                window.scrollTo(0, parseInt($(elem).offset().top, 10) - navHeight);
                history.pushState({}, null, `#${hash}`);
            });
        });
    });
} else {
    console.warn("Histroy API unsupported. Please consider updating your browser");
}<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

require('yargs')
  .commandDir('commands')
  .parserConfiguration({
    'populate--': true,
    'collect-unknown-options': true
  })
  .argv;

// Displays a message on the terminal if a new version of the package is available.
const updateNotifier = require('update-notifier');
const pkg = require('../package.json');
updateNotifier({
  pkg,
  updateCheckInterval: 1000 * 60 * 60 * 24 * 14, // 2 weeks
  boxenOpts: {
    padding: 1,
    margin: 1,
    align: 'center',
    borderColor: 'yellow',
    borderStyle: 'round'
  }
}).notify();
<commit_msg>convert to option unknown-options-as-args<commit_after>#!/usr/bin/env node
'use strict';

require('yargs')
  .commandDir('commands')
  .parserConfiguration({
    'populate--': true,
    'unknown-options-as-args': true
  })
  .argv;

// Displays a message on the terminal if a new version of the package is available.
const updateNotifier = require('update-notifier');
const pkg = require('../package.json');
updateNotifier({
  pkg,
  updateCheckInterval: 1000 * 60 * 60 * 24 * 14, // 2 weeks
  boxenOpts: {
    padding: 1,
    margin: 1,
    align: 'center',
    borderColor: 'yellow',
    borderStyle: 'round'
  }
}).notify();
<|endoftext|>