<commit_before>var _ = require('lodash'),
    utils =  require('../../../utils'),
    driver = utils.getDriver(),
    C = driver.constants;

module.exports = function(object, intent, roomObjects, roomTerrain, bulk, bulkUsers, roomController, stats, gameTime) {

    if(object.type != 'spawn') {
        return;
    }
    if(object.spawning) {
        return;
    }

    var target = roomObjects[intent.id];
    if(!target || target.type != 'creep' || target.user != object.user) {
        return;
    }
    if(Math.abs(target.x - object.x) > 1 || Math.abs(target.y - object.y) > 1) {
        return;
    }
    if(_.filter(target.body, (i) => i.type == C.CLAIM).length > 0) {
        return;
    }

    var effect = Math.floor(C.SPAWN_RENEW_RATIO * C.CREEP_LIFE_TIME / C.CREEP_SPAWN_TIME / target.body.length);
    if(target.ageTime + effect > gameTime + C.CREEP_LIFE_TIME) {
        return;
    }

    var cost = Math.ceil(C.SPAWN_RENEW_RATIO * utils.calcCreepCost(target.body) / C.CREEP_SPAWN_TIME / target.body.length);
    var result = require('./_charge-energy')(object, roomObjects, cost, bulk, roomController);

    if(!result) {
        return;
    }

    stats.inc('energyCreeps', object.user, cost);

    target.ageTime += effect;
    target.actionLog.healed = {x: object.x, y: object.y};
    bulk.update(target, {ageTime: target.ageTime});

    if(_.any(target.body, i => !!i.boost)) {
        target.body.forEach(i => {
            i.boost = null;
        });
        require('../creeps/_recalc-body')(target);
        bulk.update(target, {body: target.body, energyCapacity: target.energyCapacity});
    }

};<commit_msg>Use bulk.inc for renewCreep<commit_after>var _ = require('lodash'),
    utils =  require('../../../utils'),
    driver = utils.getDriver(),
    C = driver.constants;

module.exports = function(object, intent, roomObjects, roomTerrain, bulk, bulkUsers, roomController, stats, gameTime) {

    if(object.type != 'spawn') {
        return;
    }
    if(object.spawning) {
        return;
    }

    var target = roomObjects[intent.id];
    if(!target || target.type != 'creep' || target.user != object.user) {
        return;
    }
    if(Math.abs(target.x - object.x) > 1 || Math.abs(target.y - object.y) > 1) {
        return;
    }
    if(_.filter(target.body, (i) => i.type == C.CLAIM).length > 0) {
        return;
    }

    var effect = Math.floor(C.SPAWN_RENEW_RATIO * C.CREEP_LIFE_TIME / C.CREEP_SPAWN_TIME / target.body.length);
    if(target.ageTime + effect > gameTime + C.CREEP_LIFE_TIME) {
        return;
    }

    var cost = Math.ceil(C.SPAWN_RENEW_RATIO * utils.calcCreepCost(target.body) / C.CREEP_SPAWN_TIME / target.body.length);
    var result = require('./_charge-energy')(object, roomObjects, cost, bulk, roomController);

    if(!result) {
        return;
    }

    stats.inc('energyCreeps', object.user, cost);

    target.ageTime += effect;
    target.actionLog.healed = {x: object.x, y: object.y};
    bulk.inc(target, 'ageTime', effect);

    if(_.any(target.body, i => !!i.boost)) {
        target.body.forEach(i => {
            i.boost = null;
        });
        require('../creeps/_recalc-body')(target);
        bulk.update(target, {body: target.body, energyCapacity: target.energyCapacity});
    }

};
<|endoftext|>


<commit_before>export { UrlComposer };

/**
 * Compose a URL for downloading cells data (as JSON or .CSV format) from a Google Sheets by using Google Visualzation Table Query
 * API. The target spreadsheet should be shared by either "Public on the web" or "Anyone with the link".
 *
 * (GVizTQ = Google Visualzation Table Query)
 *
 * The follwoings are some composed examples:
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range=A:A&tqx=version:0.6
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range=A:A&tqx=version:0.6;responseHandler:SetData
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range=A:A&tqx=out:json;responseHandler:SetData
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range=A:A&tqx=out:csv
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range=A:A&tqx=out:html
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?gid=816353147&range=AH55:AK94&headers=0&tqx=out:csv
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?gid=1504323928&range=B17&headers=0&tqx=out:csv
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?sheet=Evolution.Param&range=B17&headers=0&tqx=out:csv
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range=Evolution.Param!B17&headers=0&tqx=out:csv
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range='Evolution.Param'!B17&headers=0&tqx=out:csv
 *
 */
class UrlComposer {

  /**
   * If sheetId is null, sheetName is null, and no sheet name in the range's A1 notation, the first (most left) visible sheet
   * inside the spreadsheet will be used.
   *
   * @param {string} spreadsheetId
   *   The identifier (the component after the "https://docs.google.com/spreadsheets/d/") of the spreadsheet to be accessed.
   *
   * @param {string} range
   *   The cells' A1 notation of the cells. It describes the (name and) range of the sheet inside the spreadsheet.
   *   - "A1" refers to one cell of the first (most left) visible sheet.
   *   - "B2:C5" refers to cells of a rectangle of the first (most left) visible sheet.
   *   - "Books!D8:D" refers to the column D of sheet named "Books" from rows 8 to the last rows.
   *   - "'Name has space'!7:10" refers to the rows 7 to 10 of sheet named "Name has space".
   *
   * @param {number} headers
   *   The component after the "headers=". It means how many header rows. It should be zero or a positive integer.
   *
   * @param {string} responseHandler
   *   The function name of JSON content handler. Only meaningful when the content is downloaded as JSONP format. This
   * responseHandler name will be prepended in front of the downloaded content.
   *
   * @param {number} sheetId
   *   The component after the "gid=". If the sheetName is used (or the sheet name in the range's A1 notation is specified),
   * keep this sheetId null (or undefined).
   *
   * @param {string} sheetName
   *   The component after the "sheet=". If the sheetId is used (or the sheet name in in the range's A1 notation is specified),
   * keep this sheetName null (or undefined).
   *
   * @see {@link https://developers.google.com/sheets/api/guides/concepts}
   * @see {@link https://developers.google.com/chart/interactive/docs/dev/implementing_data_source}
   * @see {@link https://developers.google.com/chart/interactive/docs/spreadsheets}
   * @see {@link https://developers.google.com/chart/interactive/docs/querylanguage}
   */
  constructor( spreadsheetId, range, headers = 0, responseHandler = null, sheetId = null, sheetName = null ) {
    this.spreadsheetId = spreadsheetId;
    this.range = range;
    this.headers = headers;
    this.responseHandler = responseHandler;
    this.sheetId = sheetId;
    this.sheetName = sheetName;
  }

  /**
   * Compose the URL (according this object's data members), download it as JSON format, extract data as a two dimension (column-major) array.
   *
   * @return {array[]}
   *   Return a two dimension (column-major) array. Return null if failed.
   */
  async fetch_JSON_ColumnMajorArray() {
    let url = this.getUrl_forJSON();
    try {
      let response = await fetch( url );
      if ( response.ok )
        return null;

      let text = await response.text();
      if ( !text )
        return null;

      let json = UrlComposer.evalJSONP( text );
      if ( !json )
        return null;

      let columnMajorArray = UrlComposer.dataTableToColumnMajorArray( json.table );
      return columnMajorArray;

    } catch ( e ) {
      return null;
    }
  }

  /**
   * @param {string} outputFormat
   *   Specify the data format when downloading the returned url. It should be null or "json" or "csv" or "html". If null, there
   * will be no format specified in the generated url (means default format, usually same as "json").
   *
   * @return {string} The url for downloading the target as specified format.
   */
  getUrl_forFormat( outputFormat ) {
    // Because sheetId could be 0, it should be checked by comparing to null directly (i.e. should not use ( !this.sheetId )).
    let url = `${UrlComposer.spreadsheetUrlPrefix}/${encodeURIComponent(this.spreadsheetId)}/${

      UrlComposer.GoogleVisualizationTableQueryUrlPostfix}?tqx=version:${
      UrlComposer.GoogleVisualizationTableQueryAPIVersion}${
      ( outputFormat != null ) ? `;out:${encodeURIComponent(outputFormat)}` : "" }${
      ( this.responseHandler != null ) ? `;responseHandler=${encodeURIComponent(this.responseHandler)}` : "" }${

      ( this.sheetId != null ) ? `&gid=${encodeURIComponent(this.sheetId)}` : `${
      ( this.sheetName != null ) ? `&sheet=${encodeURIComponent(this.sheetName)}` : "" }` }${
      ( this.range != null ) ? `&range=${encodeURIComponent(this.range)}` : "" }&headers=${encodeURIComponent(this.headers)}`
      ;

    return url;
  }

  /**
   * @return {string} The url for downloading the target as JSONP format.
   */
  getUrl_forJSON() {
    return this.getUrl_forFormat( null ); // Because default format is "json".
  }

  /**
   * @return {string} The url for downloading the target as CSV format.
   */
  getUrl_forCSV() {
    return this.getUrl_forFormat( "csv" );
  }

  /**
   * @return {string} The url for downloading the target as HTML format.
   */
  getUrl_forHTML() {
    return this.getUrl_forFormat( "html" );
  }

  /**
   * Evaluate JSONP string by JSON.parse().
   *
   * A JSONP string looks like:
   * @example
   *   Handler( ... );
   *
   * This method will find the position of the first "(" and the last ")". Extract the string between these two positions.
   * Parsing it by JSON.parse().
   *
   * @param {string} strJSONP
   *   The JSONP string to be parsed.
   *
   * @return {Object|value}
   *   Return the JSON parsed result. Return null, if left parenthesis or right parenthesis is not found.
   */
  static evalJSONP( strJSONP ) {
    let beginIndex = strJSONP.indexOf( "(" );
    if ( beginIndex < 0 )
      return null;  // left parenthesis is not found.

    let endIndex = strJSONP.lastIndexOf( ")" );
    if ( endIndex < 0 )
      return null;  // right parenthesis is not found.

    let strJSON = strJSONP.slice( beginIndex + 1, endIndex ); // "+ 1" for the next position of the left parenthesis.
    let result = JSON.parse( strJSON );
    return result;
  }

  /**
   * Collects gvizDataTable.rows[ n ].c[ m ].v into a two dimension (column-major) array. The outer array has m inner
   * sub-arrays (corresponding to m columns). Every inner sub-array has n elements (corresponding to n rows).
   *
   * @param {DataTable} gvizDataTable
   *   The DataTable object of Google Visualization API.
   *
   * @return {array[]}
   *   Return a two dimension (column-major) array. Return null if failed.
   */
  static dataTableToColumnMajorArray( gvizDataTable ) {
    if ( !gvizDataTable )
      return null;

    let columnArray = new Array( gvizDataTable.cols.length );
    for ( let columnNo = 0; columnNo < columnArray.length; ++columnNo ) {
      let rowArray = columnArray[ columnNo ] = new Array( gvizDataTable.rows.length );
      for ( let rowNo = 0; rowNo < rowArray.length; ++rowNo ) {
        rowArray[ rowNo ] = gvizDataTable.rows[ rowNo ].c[ columnNo ].v; // Always value (.v), ignore formatted value string (.f).
      }
    }

    return columnArray;
  }

}

/** The url prefix of Google Sheets. */
UrlComposer.spreadsheetUrlPrefix = "https://docs.google.com/spreadsheets/d";

/** The url postfix of Google Visualization Table Query. */
UrlComposer.GoogleVisualizationTableQueryUrlPostfix = "gviz/tq";

/** The version of Google Visualization Table Query API. */
UrlComposer.GoogleVisualizationTableQueryAPIVersion = "0.6";
<commit_msg>Update GVizTQ.js<commit_after>export { UrlComposer };

/**
 * Compose a URL for downloading cells data (as JSON or .CSV format) from a Google Sheets by using Google Visualzation Table Query
 * API. The target spreadsheet should be shared by either "Public on the web" or "Anyone with the link".
 *
 * (GVizTQ = Google Visualzation Table Query)
 *
 * The follwoings are some composed examples:
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range=A:A&tqx=version:0.6
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range=A:A&tqx=version:0.6;responseHandler:SetData
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range=A:A&tqx=out:json;responseHandler:SetData
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range=A:A&tqx=out:csv
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range=A:A&tqx=out:html
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?gid=816353147&range=AH55:AK94&headers=0&tqx=out:csv
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?gid=1504323928&range=B17&headers=0&tqx=out:csv
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?sheet=Evolution.Param&range=B17&headers=0&tqx=out:csv
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range=Evolution.Param!B17&headers=0&tqx=out:csv
 *
 * @example
 * https://docs.google.com/spreadsheets/d/18YyEoy-OfSkODfw8wqBRApSrRnBTZpjRpRiwIKy8a0M/gviz/tq?range='Evolution.Param'!B17&headers=0&tqx=out:csv
 *
 */
class UrlComposer {

  /**
   * If sheetId is null, sheetName is null, and no sheet name in the range's A1 notation, the first (most left) visible sheet
   * inside the spreadsheet will be used.
   *
   * @param {string} spreadsheetId
   *   The identifier (the component after the "https://docs.google.com/spreadsheets/d/") of the spreadsheet to be accessed.
   *
   * @param {string} range
   *   The cells' A1 notation of the cells. It describes the (name and) range of the sheet inside the spreadsheet.
   *   - "A1" refers to one cell of the first (most left) visible sheet.
   *   - "B2:C5" refers to cells of a rectangle of the first (most left) visible sheet.
   *   - "Books!D8:D" refers to the column D of sheet named "Books" from rows 8 to the last rows.
   *   - "'Name has space'!7:10" refers to the rows 7 to 10 of sheet named "Name has space".
   *
   * @param {number} headers
   *   The component after the "headers=". It means how many header rows. It should be zero or a positive integer.
   *
   * @param {string} responseHandler
   *   The function name of JSON content handler. Only meaningful when the content is downloaded as JSONP format. This
   * responseHandler name will be prepended in front of the downloaded content.
   *
   * @param {number} sheetId
   *   The component after the "gid=". If the sheetName is used (or the sheet name in the range's A1 notation is specified),
   * keep this sheetId null (or undefined).
   *
   * @param {string} sheetName
   *   The component after the "sheet=". If the sheetId is used (or the sheet name in in the range's A1 notation is specified),
   * keep this sheetName null (or undefined).
   *
   * @see {@link https://developers.google.com/sheets/api/guides/concepts}
   * @see {@link https://developers.google.com/chart/interactive/docs/dev/implementing_data_source}
   * @see {@link https://developers.google.com/chart/interactive/docs/spreadsheets}
   * @see {@link https://developers.google.com/chart/interactive/docs/querylanguage}
   */
  constructor( spreadsheetId, range, headers = 0, responseHandler = null, sheetId = null, sheetName = null ) {
    this.spreadsheetId = spreadsheetId;
    this.range = range;
    this.headers = headers;
    this.responseHandler = responseHandler;
    this.sheetId = sheetId;
    this.sheetName = sheetName;
  }

  /**
   * Compose the URL (according this object's data members), download it as JSON format, extract data as a two dimension (column-major) array.
   *
   * @return {array[]}
   *   Return a two dimension (column-major) array. Return null if failed.
   */
  async fetch_JSON_ColumnMajorArray() {
    let url = this.getUrl_forJSON();
    try {
      let response = await fetch( url );
      if ( !response.ok )
        return null;

      let text = await response.text();  // Google Visualization Table Query returns JSONP (not JSON).
      if ( !text )
        return null;

      let json = UrlComposer.evalJSONP( text );  // Try to evaluate is as JSON.
      if ( !json )
        return null;

      let columnMajorArray = UrlComposer.dataTableToColumnMajorArray( json.table ); // Collect into column-major array.
      return columnMajorArray;

    } catch ( e ) {
      return null;
    }
  }

  /**
   * @param {string} outputFormat
   *   Specify the data format when downloading the returned url. It should be null or "json" or "csv" or "html". If null, there
   * will be no format specified in the generated url (means default format, usually same as "json").
   *
   * @return {string} The url for downloading the target as specified format.
   */
  getUrl_forFormat( outputFormat ) {
    // Because sheetId could be 0, it should be checked by comparing to null directly (i.e. should not use ( !this.sheetId )).
    let url = `${UrlComposer.spreadsheetUrlPrefix}/${encodeURIComponent(this.spreadsheetId)}/${

      UrlComposer.GoogleVisualizationTableQueryUrlPostfix}?tqx=version:${
      UrlComposer.GoogleVisualizationTableQueryAPIVersion}${
      ( outputFormat != null ) ? `;out:${encodeURIComponent(outputFormat)}` : "" }${
      ( this.responseHandler != null ) ? `;responseHandler=${encodeURIComponent(this.responseHandler)}` : "" }${

      ( this.sheetId != null ) ? `&gid=${encodeURIComponent(this.sheetId)}` : `${
      ( this.sheetName != null ) ? `&sheet=${encodeURIComponent(this.sheetName)}` : "" }` }${
      ( this.range != null ) ? `&range=${encodeURIComponent(this.range)}` : "" }&headers=${encodeURIComponent(this.headers)}`
      ;

    return url;
  }

  /**
   * @return {string} The url for downloading the target as JSONP format.
   */
  getUrl_forJSON() {
    return this.getUrl_forFormat( null ); // Because default format is "json".
  }

  /**
   * @return {string} The url for downloading the target as CSV format.
   */
  getUrl_forCSV() {
    return this.getUrl_forFormat( "csv" );
  }

  /**
   * @return {string} The url for downloading the target as HTML format.
   */
  getUrl_forHTML() {
    return this.getUrl_forFormat( "html" );
  }

  /**
   * Evaluate JSONP string by JSON.parse().
   *
   * A JSONP string looks like:
   * @example
   *   Handler( ... );
   *
   * This method will find the position of the first "(" and the last ")". Extract the string between these two positions.
   * Parsing it by JSON.parse().
   *
   * @param {string} strJSONP
   *   The JSONP string to be parsed.
   *
   * @return {Object|value}
   *   Return the JSON parsed result. Return null, if left parenthesis or right parenthesis is not found.
   */
  static evalJSONP( strJSONP ) {
    let beginIndex = strJSONP.indexOf( "(" );
    if ( beginIndex < 0 )
      return null;  // left parenthesis is not found.

    let endIndex = strJSONP.lastIndexOf( ")" );
    if ( endIndex < 0 )
      return null;  // right parenthesis is not found.

    let strJSON = strJSONP.slice( beginIndex + 1, endIndex ); // "+ 1" for the next position of the left parenthesis.
    let result = JSON.parse( strJSON );
    return result;
  }

  /**
   * Collects gvizDataTable.rows[ n ].c[ m ].v into a two dimension (column-major) array. The outer array has m inner
   * sub-arrays (corresponding to m columns). Every inner sub-array has n elements (corresponding to n rows).
   *
   * @param {DataTable} gvizDataTable
   *   The DataTable object of Google Visualization API.
   *
   * @return {array[]}
   *   Return a two dimension (column-major) array. Return null if failed.
   */
  static dataTableToColumnMajorArray( gvizDataTable ) {
    if ( !gvizDataTable )
      return null;

    let columnArray = new Array( gvizDataTable.cols.length );
    for ( let columnNo = 0; columnNo < columnArray.length; ++columnNo ) {
      let rowArray = columnArray[ columnNo ] = new Array( gvizDataTable.rows.length );
      for ( let rowNo = 0; rowNo < rowArray.length; ++rowNo ) {
        rowArray[ rowNo ] = gvizDataTable.rows[ rowNo ].c[ columnNo ].v; // Always value (.v), ignore formatted value string (.f).
      }
    }

    return columnArray;
  }

}

/** The url prefix of Google Sheets. */
UrlComposer.spreadsheetUrlPrefix = "https://docs.google.com/spreadsheets/d";

/** The url postfix of Google Visualization Table Query. */
UrlComposer.GoogleVisualizationTableQueryUrlPostfix = "gviz/tq";

/** The version of Google Visualization Table Query API. */
UrlComposer.GoogleVisualizationTableQueryAPIVersion = "0.6";
<|endoftext|>


<commit_before>// Initialisation operations common to both the binarizer
// view and the segmentation view (and probably some others)

var sdviewer = null;
var presetmanager = null;
var pbuilder = null;

function saveState() {
    if (sdviewer) {
        var png = $(sdviewer).data("png");
        var src = $(sdviewer).data("src");
        var outa = $(sdviewer).data("outa");
        var outb = $(sdviewer).data("outb");

        if (outa && png) {
            var winprefix = window.location.pathname.replace(/\//g, "");
            $.cookie(winprefix + "_srcpng", png);
            $.cookie(winprefix + "_srcdzi", src);
            $.cookie(winprefix + "_outadzi", outa);
            $.cookie(winprefix + "_outbdzi", outb);
        }
    }
}

function loadState() {
    if (sdviewer) {
        var winprefix = window.location.pathname.replace(/\//g, "");
        var png = $.cookie(winprefix + "_srcpng");
        var src = $.cookie(winprefix + "_srcdzi");
        var outa = $.cookie(winprefix + "_outadzi");
        var outb = $.cookie(winprefix + "_outbdzi");

       /* if (png && outa) {
            sdviewer.setSource(src);
            sdviewer.setOutputA(outa);
            $("#viewerwindow").data("png", png);
            $("#viewerwindow").data("src", src);
            $("#viewerwindow").data("outa", outa);
            $(".interact_param").attr("disabled", false);

            if (outb) {
                sdviewer.setOutputB(outb);
                $("#viewerwindow").data("outb", outb);
            } else {
                $("#toggleab").attr("disabled", true);
            }
        }*/
    }
}

// save state on leaving the page... at least try to...
window.onbeforeunload = function(event) {
    saveState();
}

function refreshImage() {
    var params = "src=" + $(sdviewer).data("src")
        + "&png=" + $(sdviewer).data("png")
        + "&dst=" + sdviewer.bufferPath(1)
        + "&" + pbuilder.serializedData();

    // have to disable the params AFTER building the param
    // string!
    sdviewer.setWaiting(true);
    pbuilder.setWaiting(true);

    $.ajax({
        url: window.location.pathname,
        data: params,
        type: "POST",
        dataType: "json",
        beforeSend: function(data) {
        },
        success: function(data) {
            $(sdviewer).data("jobname", data[0].job_name);
            pollForResults($(sdviewer));
        },
        error: OCRJS.ajaxErrorHandler,
        complete: function(e) {
        }
    });
}

// convert a list of page-coordinate rectangles into
// a list of seadragon normalized rect objects
function getViewerCoordinateRects(bounds, pagerects) {
    var fw = bounds[2], fh = bounds[3];
    var x, y, w, h, box;
    var outrects = [];
    for (var i in pagerects) {
        box = pagerects[i];
        x = box[0]; y = box[1]; w = box[2]; h = box[3];
        outrects.push(
            new Seadragon.Rect(x / fw, (y - h) / fw, w / fw, h / fw));
    }
    return outrects;
}

// Process the data completed results data... in this case
// set the viewer source and output paths
function processData(element, data) {
    if (!data || !data.status || data.status == "PENDING") {
        setTimeout(function() {
            pollForResults(element);
        }, 500);
    } else if (data.error) {
        sdviewer.setWaiting(true);
        element
            .addClass("error")
            .html("
Error: " + data.error + "
")
            .append(
                $("

").addClass("traceback")
                    .append("
" + data.trace + "
")
            );
    } else if (data.status == "SUCCESS") {
        $(sdviewer).data("png", data.results.png);
        $(sdviewer).data("src", data.results.src);
        if (data.results.dst.search("_b.dzi") != -1) {
            $(sdviewer).data("outb", data.results.dst);
        } else {
            $(sdviewer).data("outa", data.results.dst);
        }
        sdviewer.setBufferPath(2, sdviewer.bufferPath(1));
        sdviewer.setBufferPath(1, data.results.dst);
        sdviewer.setBufferPath(0, data.results.src);
        sdviewer.setWaiting(false);
        pbuilder.setWaiting(false);

        var overlays = {};
        $.each(["lines", "paragraphs", "columns"], function(i, class) {
            if (data.results[class]) {
                overlays[class] = getViewerCoordinateRects(
                    data.results.box, data.results[class]);
            }
        });
        sdviewer.setBufferOverlays(sdviewer.bufferOverlays(1), 2);
        sdviewer.setBufferOverlays(overlays, 1);

        $(".tbbutton").button({disabled: false});
    } else {
        alert("Oops.  Task finished with bad status: " + data.status);
    }
}

// keep checking the server for the results of the jobname
// associated with the particular element
function pollForResults(element) {
    var jobname = element.data("jobname");
    $.ajax({
        url: "/ocr/results/" + jobname,
        dataType: "json",
        success: function(data) {
            processData(element, data);
        },
        error: OCRJS.ajaxErrorHandler,
    });
}

// process the INITIAL json data that arrives after the files
// have been uploaded but before it has been processed.
function onXHRLoad(event) {
    var xhr = event.target;
    if (!xhr.responseText) {
        return;
    }
    if (xhr.status != 200) {
        return alert("Error: " + xhr.responseText + "  Status: " + xhr.status);
    }
    var data = $.parseJSON(xhr.responseText);
    if (data.error) {
        alert("Error: " + data.error + "\n\n" + data.trace);
        $("#dropzone").text("Drop images here...").removeClass("waiting");
        return;
    }

    $.each(data, function(page, pageresults) {
        var pagename = pageresults.job_name.split("::")[0].replace(/\.[^\.]+$/, "");
        //sdviewer.setTitle(pagename);
        sdviewer.setWaiting(true);
        $("#viewer")
            .data("jobname", pageresults.job_name);
        pollForResults($("#viewer"));
    });
};

$(function() {

    // initialise the viewer
    sdviewer = new OCRJS.ImageViewer($("#viewer").get(0), {
        numBuffers: 3,
        log: false,
        dashboard: false,
    });
    sdviewer.setActiveBuffer(1);

    // build toolbar
    $(".tbbutton").button({});
    $("#output").buttonset();
    $("#zoomin").button({
        text: false,
        icons: {
            primary: "ui-icon-zoomin",
        }
    });
    $("#zoomout").button({
        text: false,
        icons: {
            primary: "ui-icon-zoomout",
        }
    });
    $("#centre").button({
        text: false,
        icons: {
            primary: "ui-icon-home",
        }
    });
    $("#fullscreen").button({
        text: false,
        icons: {
            primary: "ui-icon-arrow-4-diag",
        }
    });

    $("#refresh").button({
        text: false,
        icons: {
            primary: "ui-icon-refresh",
        }
    });

    // refresh on compparm enter
    $(".compparam > input").live("keydown", function(event) {
        if (event.keyCode == KC_RETURN) {
           refreshImage();
           return false;
        }
    });

    $("#hl_lines, #hl_paragraphs, #hl_columns").click(function(event) {
        var class = this.id.replace(/hl_/, "");
        $(".viewer_highlight." + class).globalcss(
            "display", $(this).attr("checked") ? "block" : "none");
    });

    // make interactive params disabled at the start
    $(".tbbutton").button({disabled: true});

    // toggle the source and binary images
    $("#togglesrc").click(function(event) {
        var active = sdviewer.activeBuffer();
        sdviewer.setActiveBuffer(active == 0 ? 1 : 0);
    });
    $("#toggleab").click(function(event) {
        var active = sdviewer.activeBuffer();
        sdviewer.setActiveBuffer(active == 1 ? 2 : 1);
    });

    // resubmit the form...
    $("#refresh").click(refreshImage);

    $("#output_s").click(function(event) {
        sdviewer.setActiveBuffer(0);
    });

    $("#output_a").click(function(event) {
        sdviewer.setActiveBuffer(1);
    });

    $("#output_b").click(function(event) {
        sdviewer.setActiveBuffer(2);
    });

    $("#zoomin").click(function(event) {
        sdviewer.zoomBy(2);
    });

    $("#zoomout").click(function(event) {
        sdviewer.zoomBy(0.5);
    });

    $("#centre").click(function(event) {
        sdviewer.goHome();
    });

    $("#fullscreen").click(function(event) {
        sdviewer.setFullPage(true);
    });

    // bind 1-2-3 and a-b-s to viewer outputs
    $("#viewer").bind("mouseenter mouseleave", function(mouseevent) {
        if (mouseevent.type == "mouseenter") {
            $(window).bind("keypress.viewer", function(event) {
                if (String.fromCharCode(event.which).toLowerCase().match(/[a]/)) {
                    $("#output_a").click().button("refresh");
                } else if (String.fromCharCode(event.which).toLowerCase().match(/[b]/)) {
                    $("#output_b").click().button("refresh");
                } else if (String.fromCharCode(event.which).toLowerCase().match(/[s]/)) {
                    $("#output_s").click().button("refresh");
                } else if (String.fromCharCode(event.which).toLowerCase().match(/[t]/)) {
                    if ($("#output_s").attr("checked")) {
                        $("#output_a").click().button("refresh");
                    } else {
                        $("#output_s").click().button("refresh");
                    }
                } else if (String.fromCharCode(event.which).toLowerCase().match(/[o]/)) {
                    if ($("#output_a").attr("checked")) {
                        $("#output_b").click().button("refresh");
                    } else {
                        $("#output_a").click().button("refresh");
                    }
                }
            });
        } else {
            $(window).unbind("keypress.viewer");
        }
    });

    // initialize the preset manager
    // this first bit's a hack
    var presettype = window.location.pathname.replace(/\/ocr\//g, "").replace(/\//g, "");

    presetmanager = new PresetManager(document.getElementById("preset_container"), presettype);
    presetmanager.onPresetLoadData = function(data) {
        pbuilder.loadData(data);
    };
    presetmanager.onPresetClear = function() {
        pbuilder.reinit();
    };

    // initialise the uploader...
    var uploader  = new OCRJS.AjaxUploader(
        $("#dropzone").get(0),
        window.location.pathname,
        { multi: false }
    );
    uploader.onXHRLoad = onXHRLoad;
    uploader.onUploadsStarted = function(e) {
        // close anything that's already open in the viewer
        sdviewer.close();
        pbuilder.setWaiting(true);
        $("#dropzone").text("Please wait...").addClass("waiting");
        // slurp up the parameters.  Since the params are build
        // dynamically this has to be done immediately before the
        // upload commences, hence in the onUploadsStarted handler
        $("#optionsform input[type='text'], #optionsform select").each(function(i, elem) {
            uploader.registerTextParameter(elem);
        });
    };
    uploader.onUploadsFinished = function(e) {
        pbuilder.setWaiting(false);
        $("#dropzone").text("Drop images here...").removeClass("waiting");
    };

    loadState();
});
<commit_msg>Make bin/seg viewer resizable<commit_after>// Initialisation operations common to both the binarizer
// view and the segmentation view (and probably some others)

var sdviewer = null;
var presetmanager = null;
var pbuilder = null;

function saveState() {
    if (sdviewer) {
        var png = $(sdviewer).data("png");
        var src = $(sdviewer).data("src");
        var outa = $(sdviewer).data("outa");
        var outb = $(sdviewer).data("outb");

        if (outa && png) {
            var winprefix = window.location.pathname.replace(/\//g, "");
            $.cookie(winprefix + "_srcpng", png);
            $.cookie(winprefix + "_srcdzi", src);
            $.cookie(winprefix + "_outadzi", outa);
            $.cookie(winprefix + "_outbdzi", outb);
        }
    }
}

function loadState() {
    if (sdviewer) {
        var winprefix = window.location.pathname.replace(/\//g, "");
        var png = $.cookie(winprefix + "_srcpng");
        var src = $.cookie(winprefix + "_srcdzi");
        var outa = $.cookie(winprefix + "_outadzi");
        var outb = $.cookie(winprefix + "_outbdzi");

       /* if (png && outa) {
            sdviewer.setSource(src);
            sdviewer.setOutputA(outa);
            $("#viewerwindow").data("png", png);
            $("#viewerwindow").data("src", src);
            $("#viewerwindow").data("outa", outa);
            $(".interact_param").attr("disabled", false);

            if (outb) {
                sdviewer.setOutputB(outb);
                $("#viewerwindow").data("outb", outb);
            } else {
                $("#toggleab").attr("disabled", true);
            }
        }*/
    }
}

// save state on leaving the page... at least try to...
window.onbeforeunload = function(event) {
    saveState();
}

function refreshImage() {
    var params = "src=" + $(sdviewer).data("src")
        + "&png=" + $(sdviewer).data("png")
        + "&dst=" + sdviewer.bufferPath(1)
        + "&" + pbuilder.serializedData();

    // have to disable the params AFTER building the param
    // string!
    sdviewer.setWaiting(true);
    pbuilder.setWaiting(true);

    $.ajax({
        url: window.location.pathname,
        data: params,
        type: "POST",
        dataType: "json",
        beforeSend: function(data) {
        },
        success: function(data) {
            $(sdviewer).data("jobname", data[0].job_name);
            pollForResults($(sdviewer));
        },
        error: OCRJS.ajaxErrorHandler,
        complete: function(e) {
        }
    });
}

// convert a list of page-coordinate rectangles into
// a list of seadragon normalized rect objects
function getViewerCoordinateRects(bounds, pagerects) {
    var fw = bounds[2], fh = bounds[3];
    var x, y, w, h, box;
    var outrects = [];
    for (var i in pagerects) {
        box = pagerects[i];
        x = box[0]; y = box[1]; w = box[2]; h = box[3];
        outrects.push(
            new Seadragon.Rect(x / fw, (y - h) / fw, w / fw, h / fw));
    }
    return outrects;
}

// Process the data completed results data... in this case
// set the viewer source and output paths
function processData(element, data) {
    if (!data || !data.status || data.status == "PENDING") {
        setTimeout(function() {
            pollForResults(element);
        }, 500);
    } else if (data.error) {
        sdviewer.setWaiting(true);
        element
            .addClass("error")
            .html("
Error: " + data.error + "
")
            .append(
                $("

").addClass("traceback")
                    .append("
" + data.trace + "
")
            );
    } else if (data.status == "SUCCESS") {
        $(sdviewer).data("png", data.results.png);
        $(sdviewer).data("src", data.results.src);
        if (data.results.dst.search("_b.dzi") != -1) {
            $(sdviewer).data("outb", data.results.dst);
        } else {
            $(sdviewer).data("outa", data.results.dst);
        }
        sdviewer.setBufferPath(2, sdviewer.bufferPath(1));
        sdviewer.setBufferPath(1, data.results.dst);
        sdviewer.setBufferPath(0, data.results.src);
        sdviewer.setWaiting(false);
        pbuilder.setWaiting(false);

        var overlays = {};
        $.each(["lines", "paragraphs", "columns"], function(i, class) {
            if (data.results[class]) {
                overlays[class] = getViewerCoordinateRects(
                    data.results.box, data.results[class]);
            }
        });
        sdviewer.setBufferOverlays(sdviewer.bufferOverlays(1), 2);
        sdviewer.setBufferOverlays(overlays, 1);

        $(".tbbutton").button({disabled: false});
    } else {
        alert("Oops.  Task finished with bad status: " + data.status);
    }
}

// keep checking the server for the results of the jobname
// associated with the particular element
function pollForResults(element) {
    var jobname = element.data("jobname");
    $.ajax({
        url: "/ocr/results/" + jobname,
        dataType: "json",
        success: function(data) {
            processData(element, data);
        },
        error: OCRJS.ajaxErrorHandler,
    });
}

// process the INITIAL json data that arrives after the files
// have been uploaded but before it has been processed.
function onXHRLoad(event) {
    var xhr = event.target;
    if (!xhr.responseText) {
        return;
    }
    if (xhr.status != 200) {
        return alert("Error: " + xhr.responseText + "  Status: " + xhr.status);
    }
    var data = $.parseJSON(xhr.responseText);
    if (data.error) {
        alert("Error: " + data.error + "\n\n" + data.trace);
        $("#dropzone").text("Drop images here...").removeClass("waiting");
        return;
    }

    $.each(data, function(page, pageresults) {
        var pagename = pageresults.job_name.split("::")[0].replace(/\.[^\.]+$/, "");
        //sdviewer.setTitle(pagename);
        sdviewer.setWaiting(true);
        $("#viewer")
            .data("jobname", pageresults.job_name);
        pollForResults($("#viewer"));
    });
};

$(function() {

    // initialise the viewer
    sdviewer = new OCRJS.ImageViewer($("#viewer").get(0), {
        numBuffers: 3,
        log: false,
        dashboard: false,
    });
    sdviewer.setActiveBuffer(1);

    // build toolbar
    $(".tbbutton").button({});
    $("#output").buttonset();
    $("#zoomin").button({
        text: false,
        icons: {
            primary: "ui-icon-zoomin",
        }
    });
    $("#zoomout").button({
        text: false,
        icons: {
            primary: "ui-icon-zoomout",
        }
    });
    $("#centre").button({
        text: false,
        icons: {
            primary: "ui-icon-home",
        }
    });
    $("#fullscreen").button({
        text: false,
        icons: {
            primary: "ui-icon-arrow-4-diag",
        }
    });

    $("#refresh").button({
        text: false,
        icons: {
            primary: "ui-icon-refresh",
        }
    });

    // refresh on compparm enter
    $(".compparam > input").live("keydown", function(event) {
        if (event.keyCode == KC_RETURN) {
           refreshImage();
           return false;
        }
    });

    $("#hl_lines, #hl_paragraphs, #hl_columns").click(function(event) {
        var class = this.id.replace(/hl_/, "");
        $(".viewer_highlight." + class).globalcss(
            "display", $(this).attr("checked") ? "block" : "none");
    });

    // make interactive params disabled at the start
    $(".tbbutton").button({disabled: true});

    // toggle the source and binary images
    $("#togglesrc").click(function(event) {
        var active = sdviewer.activeBuffer();
        sdviewer.setActiveBuffer(active == 0 ? 1 : 0);
    });
    $("#toggleab").click(function(event) {
        var active = sdviewer.activeBuffer();
        sdviewer.setActiveBuffer(active == 1 ? 2 : 1);
    });

    // resubmit the form...
    $("#refresh").click(refreshImage);

    $("#output_s").click(function(event) {
        sdviewer.setActiveBuffer(0);
    });

    $("#output_a").click(function(event) {
        sdviewer.setActiveBuffer(1);
    });

    $("#output_b").click(function(event) {
        sdviewer.setActiveBuffer(2);
    });

    $("#zoomin").click(function(event) {
        sdviewer.zoomBy(2);
    });

    $("#zoomout").click(function(event) {
        sdviewer.zoomBy(0.5);
    });

    $("#centre").click(function(event) {
        sdviewer.goHome();
    });

    $("#fullscreen").click(function(event) {
        sdviewer.setFullPage(true);
    });

    // make the viewer resizable
    $("#viewercontainer").resizable({
        resize: function(event, ui) {
            sdviewer.updateSize(
                $(this).width(),
                $(this).height() - $(".widget_header").outerHeight(true)
            );
        },
    });

    // bind 1-2-3 and a-b-s to viewer outputs
    $("#viewer").bind("mouseenter mouseleave", function(mouseevent) {
        if (mouseevent.type == "mouseenter") {
            $(window).bind("keypress.viewer", function(event) {
                if (String.fromCharCode(event.which).toLowerCase().match(/[a]/)) {
                    $("#output_a").click().button("refresh");
                } else if (String.fromCharCode(event.which).toLowerCase().match(/[b]/)) {
                    $("#output_b").click().button("refresh");
                } else if (String.fromCharCode(event.which).toLowerCase().match(/[s]/)) {
                    $("#output_s").click().button("refresh");
                } else if (String.fromCharCode(event.which).toLowerCase().match(/[t]/)) {
                    if ($("#output_s").attr("checked")) {
                        $("#output_a").click().button("refresh");
                    } else {
                        $("#output_s").click().button("refresh");
                    }
                } else if (String.fromCharCode(event.which).toLowerCase().match(/[o]/)) {
                    if ($("#output_a").attr("checked")) {
                        $("#output_b").click().button("refresh");
                    } else {
                        $("#output_a").click().button("refresh");
                    }
                }
            });
        } else {
            $(window).unbind("keypress.viewer");
        }
    });

    // initialize the preset manager
    // this first bit's a hack
    var presettype = window.location.pathname.replace(/\/ocr\//g, "").replace(/\//g, "");

    presetmanager = new PresetManager(document.getElementById("preset_container"), presettype);
    presetmanager.onPresetLoadData = function(data) {
        pbuilder.loadData(data);
    };
    presetmanager.onPresetClear = function() {
        pbuilder.reinit();
    };

    // initialise the uploader...
    var uploader  = new OCRJS.AjaxUploader(
        $("#dropzone").get(0),
        window.location.pathname,
        { multi: false }
    );
    uploader.onXHRLoad = onXHRLoad;
    uploader.onUploadsStarted = function(e) {
        // close anything that's already open in the viewer
        sdviewer.close();
        pbuilder.setWaiting(true);
        $("#dropzone").text("Please wait...").addClass("waiting");
        // slurp up the parameters.  Since the params are build
        // dynamically this has to be done immediately before the
        // upload commences, hence in the onUploadsStarted handler
        $("#optionsform input[type='text'], #optionsform select").each(function(i, elem) {
            uploader.registerTextParameter(elem);
        });
    };
    uploader.onUploadsFinished = function(e) {
        pbuilder.setWaiting(false);
        $("#dropzone").text("Drop images here...").removeClass("waiting");
    };

    loadState();
});
<|endoftext|>


<commit_before>brain.NeuralNet = (function(brain) {
  "use strict";

  function NeuralNet(params) {
    this.bias = params.bias;
    this.inputCount = params.inputCount;
    this.outputCount = params.outputCount;
    this.hiddenLayerCount = params.hiddenLayerCount;
    this.activationResponse = params.activationResponse;
    this.hiddenLayerNeuronCount = params.hiddenLayerNeuronCount;
    this.maxPerturbation = params.maxPerturbation;
    this.sense = params.sense;
    this.goal = params.goal;
    this.action = params.action;
    this.layers = [];
    this.wisdom = null;

    this
        .createNet()
        .createWisdom();
  }

  NeuralNet.prototype = {
    /**
     * this method builds the ANN. The weights are all initially set to
     * random values -1 < w < 1
     */
    createNet: function() {
      var max = this.hiddenLayerCount - 1,
          i = 0;

      //create the layers of the network
      if (this.hiddenLayerCount > 0) {
        //create first hidden layer
        this.layers.push(new brain.NeuronLayer(this.hiddenLayerNeuronCount, this.inputCount));
        for (; i < max; i++) {
          this.layers.push(new brain.NeuronLayer(this.hiddenLayerNeuronCount, this.hiddenLayerNeuronCount));
        }

        //create output layer
        this.layers.push(new brain.NeuronLayer(this.outputCount, this.hiddenLayerNeuronCount));
      } else {
        //create output layer
        this.layers.push(new brain.NeuronLayer(this.outputCount, this.inputCount));
      }

      return this;
    },

    createWisdom: function() {
        var weights = [],
            i = 0,
            max = this.getNumWeights();

        for (; i < max; i++) {
          weights.push(Math.random() - Math.random());
        }

        this.wisdom = new brain.Wisdom(weights, this.maxPerturbation);
        this.putWeights(weights);

        return this;
    },

    reward: function() {
      this.wisdom.reward();
      return this;
    },
    /**
     * returns weights
     * @returns {Array}
     */
    getWeights: function() {
      var weights = [],
          layer,
          neuron,
          i,
          j,
          k;

      //for each layer
      for (i = 0; i <= this.hiddenLayerCount; i++) {
        layer = this.layers[i];

        //for each neuron
        for (j = 0; j < layer.neurons.length; j++) {
          neuron = layer.neurons[j];

          //for each weight
          for (k = 0; k < neuron.weights.length; k++) {
            weights.push(neuron.weights[k]);
          }
        }
      }
      return weights;
    },

    /**
     * replaces the weights in the NN with the new values
     * @param weights
     */
    putWeights: function(weights) {
      var cWeight = 0,
          layer,
          neuron,
          i,
          j,
          k;

      //for each layer
      for (i = 0; i <= this.hiddenLayerCount; i++) {
        layer = this.layers[i];

        //for each neuron
        for (j = 0; j < layer.neurons.length; j++) {
          neuron = layer.neurons[j];

          //for each weight
          for (k = 0; k < neuron.weights.length; k++) {
            neuron.weights[k] = weights[cWeight++];
          }
        }
      }

      return this;
    },

    /**
     * returns the total number of weights needed for the net
     * @returns {number}
     */
    getNumWeights: function() {
      var weights = 0,
          layer,
          neuron,
          i,
          j,
          k;

      //for each layer
      for (i = 0; i < this.layers.length; i++) {
        layer = this.layers[i];

        //for each neuron
        for (j = 0; j < layer.neurons.length; j++) {
          neuron = layer.neurons[j];

          //for each weight
          for (k = 0; k < neuron.weights.length; k++) {
            weights++;
          }
        }
      }

      return weights;
    },

    think: function() {
      //stores the resultant outputs from each layer
      var inputs = this.sense ? this.sense() : [],
          outputs = [],
          layer,
          neurons,
          neuron,
          weight = 0,
          netInput,
          inputCount,
          i,
          j,
          k;

      //first check that we have the correct amount of inputs
      if (inputs.length != this.inputCount) {
        return null;
      }

      //For each layer....
      for (i = 0; i <= this.hiddenLayerCount; i++) {
        layer = this.layers[i];
        neurons = layer.neurons;
        //After the first layer, the inputs get set to the output of previous layer
        if (i > 0) {
          //we clone the output so it isn't cleared after this step
          inputs = outputs.slice(0);
        }

        while(outputs.length > 0) {outputs.pop()}

        weight = 0;

        /*
        for each neuron sum the (inputs * corresponding weights).Throw
        the total at our sigmoid function to get the output
        */
        for (j = 0; j < neurons.length; j++) {
          neuron = neurons[j];
          netInput = 0;

          inputCount = neuron.weights.length;

          //for each weight
          for (k = 0; k < inputCount - 1; k++) {

            //sum the weights x inputs
            netInput += neuron.weights[k] * inputs[weight++];
          }

          //add in the bias
          netInput += neuron.weights[inputCount - 1] * this.bias;

          /*
          we can store the outputs from each layer as we generate them.
          The combined activation is first filtered through the sigmoid
          function
          */
          outputs.push(this.sigmoid(netInput, this.activationResponse));

          weight = 0;
        }
      }

      if (this.goal !== undefined) {
        this.wisdom.rewards += this.goal();
      }

      if (this.action !== undefined) {
        this.action(outputs);
      }

      return this;
    },

    sigmoid: function(netInput, response) {
      return (1 / (1 + Math.exp(-netInput / response)));
    }
  };

  return NeuralNet;
})(brain);<commit_msg>switch goal after action<commit_after>brain.NeuralNet = (function(brain) {
  "use strict";

  function NeuralNet(params) {
    this.bias = params.bias;
    this.inputCount = params.inputCount;
    this.outputCount = params.outputCount;
    this.hiddenLayerCount = params.hiddenLayerCount;
    this.activationResponse = params.activationResponse;
    this.hiddenLayerNeuronCount = params.hiddenLayerNeuronCount;
    this.maxPerturbation = params.maxPerturbation;
    this.sense = params.sense;
    this.goal = params.goal;
    this.action = params.action;
    this.layers = [];
    this.wisdom = null;

    this
        .createNet()
        .createWisdom();
  }

  NeuralNet.prototype = {
    /**
     * this method builds the ANN. The weights are all initially set to
     * random values -1 < w < 1
     */
    createNet: function() {
      var max = this.hiddenLayerCount - 1,
          i = 0;

      //create the layers of the network
      if (this.hiddenLayerCount > 0) {
        //create first hidden layer
        this.layers.push(new brain.NeuronLayer(this.hiddenLayerNeuronCount, this.inputCount));
        for (; i < max; i++) {
          this.layers.push(new brain.NeuronLayer(this.hiddenLayerNeuronCount, this.hiddenLayerNeuronCount));
        }

        //create output layer
        this.layers.push(new brain.NeuronLayer(this.outputCount, this.hiddenLayerNeuronCount));
      } else {
        //create output layer
        this.layers.push(new brain.NeuronLayer(this.outputCount, this.inputCount));
      }

      return this;
    },

    createWisdom: function() {
        var weights = [],
            i = 0,
            max = this.getNumWeights();

        for (; i < max; i++) {
          weights.push(Math.random() - Math.random());
        }

        this.wisdom = new brain.Wisdom(weights, this.maxPerturbation);
        this.putWeights(weights);

        return this;
    },

    reward: function() {
      this.wisdom.reward();
      return this;
    },
    /**
     * returns weights
     * @returns {Array}
     */
    getWeights: function() {
      var weights = [],
          layer,
          neuron,
          i,
          j,
          k;

      //for each layer
      for (i = 0; i <= this.hiddenLayerCount; i++) {
        layer = this.layers[i];

        //for each neuron
        for (j = 0; j < layer.neurons.length; j++) {
          neuron = layer.neurons[j];

          //for each weight
          for (k = 0; k < neuron.weights.length; k++) {
            weights.push(neuron.weights[k]);
          }
        }
      }
      return weights;
    },

    /**
     * replaces the weights in the NN with the new values
     * @param weights
     */
    putWeights: function(weights) {
      var cWeight = 0,
          layer,
          neuron,
          i,
          j,
          k;

      //for each layer
      for (i = 0; i <= this.hiddenLayerCount; i++) {
        layer = this.layers[i];

        //for each neuron
        for (j = 0; j < layer.neurons.length; j++) {
          neuron = layer.neurons[j];

          //for each weight
          for (k = 0; k < neuron.weights.length; k++) {
            neuron.weights[k] = weights[cWeight++];
          }
        }
      }

      return this;
    },

    /**
     * returns the total number of weights needed for the net
     * @returns {number}
     */
    getNumWeights: function() {
      var weights = 0,
          layer,
          neuron,
          i,
          j,
          k;

      //for each layer
      for (i = 0; i < this.layers.length; i++) {
        layer = this.layers[i];

        //for each neuron
        for (j = 0; j < layer.neurons.length; j++) {
          neuron = layer.neurons[j];

          //for each weight
          for (k = 0; k < neuron.weights.length; k++) {
            weights++;
          }
        }
      }

      return weights;
    },

    think: function() {
      //stores the resultant outputs from each layer
      var inputs = this.sense ? this.sense() : [],
          outputs = [],
          layer,
          neurons,
          neuron,
          weight = 0,
          netInput,
          inputCount,
          i,
          j,
          k;

      //first check that we have the correct amount of inputs
      if (inputs.length != this.inputCount) {
        return null;
      }

      //For each layer....
      for (i = 0; i <= this.hiddenLayerCount; i++) {
        layer = this.layers[i];
        neurons = layer.neurons;
        //After the first layer, the inputs get set to the output of previous layer
        if (i > 0) {
          //we clone the output so it isn't cleared after this step
          inputs = outputs.slice(0);
        }

        while(outputs.length > 0) {outputs.pop()}

        weight = 0;

        /*
        for each neuron sum the (inputs * corresponding weights).Throw
        the total at our sigmoid function to get the output
        */
        for (j = 0; j < neurons.length; j++) {
          neuron = neurons[j];
          netInput = 0;

          inputCount = neuron.weights.length;

          //for each weight
          for (k = 0; k < inputCount - 1; k++) {

            //sum the weights x inputs
            netInput += neuron.weights[k] * inputs[weight++];
          }

          //add in the bias
          netInput += neuron.weights[inputCount - 1] * this.bias;

          /*
          we can store the outputs from each layer as we generate them.
          The combined activation is first filtered through the sigmoid
          function
          */
          outputs.push(this.sigmoid(netInput, this.activationResponse));

          weight = 0;
        }
      }

      if (this.action !== undefined) {
        this.action(outputs);
      }

      if (this.goal !== undefined) {
        this.wisdom.rewards += this.goal();
      }

      return this;
    },

    sigmoid: function(netInput, response) {
      return (1 / (1 + Math.exp(-netInput / response)));
    }
  };

  return NeuralNet;
})(brain);<|endoftext|>


<commit_before>import Ember from 'ember';
import PropertyBindings from 'ember-binding-macros/mixins/property-bindings';
import { bindProperties } from 'ember-binding-macros/mixins/property-bindings';
import { compute, readOnly } from '../utils/compute';
import { RSVP, makePromise, makePromiseObject } from '../utils/make-promise';

var a_slice = [].slice;

var Form = Ember.Object.extend(PropertyBindings, {
  propertyBindings: ['transformedValue > value', 'currentScope > scope', 'scope <> input'],

  rules: {},
  currentScope: Ember.computed('value', '_parentForm.currentScope', function() {
    return this.serialize(this.get('value'));
  }),
  isAtom: Ember.computed.equal('_children.length', 0),

  transform: function(input) {
    return input;
  },

  transformedValue: Ember.computed('validation.isFulfilled', function() {
    if (this.get('validation.isFulfilled')) {
      return this.transform(this.get('scope'));
    } else {
      return this.get('value');
    }
  }).readOnly(),

  serialize: function(value) {
    if (this.get('isAtom')) {
      return value;
    } else {
      var form = this;
      var attrs = this.get('_childKeys').reduce(function(current, key) {
        current[key] = form.get(key).get('value');
        return current;
      }, {});
      this.get('_readKeys').reduce(function(current, key) {
        current[key] = form.get(key);
      }, attrs);
      return Ember.Object.create(attrs);
    }
  },

  validation: Ember.computed('rules', '_children.@each.validation', function() {
    var rules = this.get('rules');
    var keys = Object.keys(rules);
    var dependentKeys = keys.concat('validations.@each.result');

    var result = compute(dependentKeys, function() {
      var properties = this.getProperties(keys);
      var form = this.get('form');
      var children = form.get('_childKeys').reduce(function(hash, key) {
        hash[key] = form.get(key).get('validation.result');
        return hash;
      }, {});

      Ember.merge(properties, {
        _children: RSVP.hash(children)
      });
      return makePromiseObject(RSVP.hash(properties));
    }).readOnly();
    if (keys.length === 0 && this.get('_childKeys.length') === 0) {
      result = Ember.computed('form.input', function() {
        return makePromiseObject(RSVP.resolve());
      });
    }
    return Validation.extend(rules, {
      form: this,

      validations: this.get('_children').mapBy('validation'),

      result: result
    }).create();
  }).readOnly(),

  __bindChildValues__: Ember.observer(function() {
    var childKeys = [];
    var children = [];
    var readKeys = [];
    this.constructor.eachComputedProperty(function(name, meta) {
      if (meta.isForm) {
        childKeys.push(name);
        children.push(this.get(name));
      } else if (meta.isFormRead) {
        readKeys.push(name);
      }
    }, this);
    this.set('_children', Ember.A(children));
    this.set('_childKeys', Ember.A(childKeys));
    this.set('_readKeys', Ember.A(readKeys));
    if (childKeys.length > 0) {
      childKeys.forEach(function(key) {
        bindProperties(this, key + ".currentScope", "currentScope." + key);
      }, this);
      readKeys.forEach(function(key) {
        bindProperties(this, key, "currentScope." + key, true).toString();
      }, this);
    }
  }).on('init'),

  willDestroy: function() {
    this.get('_children').forEach(function(child) {
      child.destroy();
    });
    this._super.apply(this, arguments);
  }
});

Form.rule = function(fn) {
  var args;
  if (arguments.length > 1) {
    args = a_slice.call(arguments);
    fn = args.pop();
    args = args.map(function(key) {
      return "form." + key;
    });
  }

  args.push(function thunk() {
    var form = this.get('form');
    return makePromise(function(resolve, reject) {
      if (fn.length === 2) {
        fn.call(form, resolve, reject);
      } else if (fn.length === 0){
        if (fn.call(form)) {
          resolve();
        } else {
          reject();
        }
      } else {
        Ember.assert("Form.rule should be called with either 0 or 2 arguments", false);
      }
    });
  });

  return Ember.computed.apply(Ember, args);
};

Form.hasOne = function(attrs) {
  attrs = attrs || {};
  return Ember.computed(function() {
    return Form.extend(attrs).create({
      _parentForm: this
    });
  }).meta({isForm: true});
};

Form.reads = function(dependentKey) {
  return Ember.computed(dependentKey, function() {
    return this.get(dependentKey);
  }).readOnly().meta({isFormRead: true});
};

var Validation = Ember.Object.extend({
  isPending: readOnly('result.isPending'),
  isSettled: readOnly('result.isSettled'),
  isRejected: readOnly('result.isRejected'),
  isFulfilled: readOnly('result.isFulfilled')
});

export default Form;
<commit_msg>make metadata keys private in validations.<commit_after>import Ember from 'ember';
import PropertyBindings from 'ember-binding-macros/mixins/property-bindings';
import { bindProperties } from 'ember-binding-macros/mixins/property-bindings';
import { compute, readOnly } from '../utils/compute';
import { RSVP, makePromise, makePromiseObject } from '../utils/make-promise';

var a_slice = [].slice;

var Form = Ember.Object.extend(PropertyBindings, {
  propertyBindings: ['transformedValue > value', 'currentScope > scope', 'scope <> input'],

  rules: {},
  currentScope: Ember.computed('value', '_parentForm.currentScope', function() {
    return this.serialize(this.get('value'));
  }),
  isAtom: Ember.computed.equal('_children.length', 0),

  transform: function(input) {
    return input;
  },

  transformedValue: Ember.computed('validation.isFulfilled', function() {
    if (this.get('validation.isFulfilled')) {
      return this.transform(this.get('scope'));
    } else {
      return this.get('value');
    }
  }).readOnly(),

  serialize: function(value) {
    if (this.get('isAtom')) {
      return value;
    } else {
      var form = this;
      var attrs = this.get('_childKeys').reduce(function(current, key) {
        current[key] = form.get(key).get('value');
        return current;
      }, {});
      this.get('_readKeys').reduce(function(current, key) {
        current[key] = form.get(key);
      }, attrs);
      return Ember.Object.create(attrs);
    }
  },

  validation: Ember.computed('rules', '_children.@each.validation', function() {
    var rules = this.get('rules');
    var keys = Object.keys(rules);
    var dependentKeys = keys.concat('_children.@each.result');

    var result = compute(dependentKeys, function() {
      var properties = this.getProperties(keys);
      var form = this.get('_form');
      var children = form.get('_childKeys').reduce(function(hash, key) {
        hash[key] = form.get(key).get('validation.result');
        return hash;
      }, {});

      Ember.merge(properties, {
        _children: RSVP.hash(children)
      });
      return makePromiseObject(RSVP.hash(properties));
    }).readOnly();
    if (keys.length === 0 && this.get('_childKeys.length') === 0) {
      result = Ember.computed('_form.scope', function() {
        return makePromiseObject(RSVP.resolve());
      });
    }
    return Validation.extend(rules, {
      _form: this,
      _children: Ember.computed.mapBy('_form._children', 'validation'),
      result: result
    }).create();
  }).readOnly(),

  __bindChildValues__: Ember.observer(function() {
    var childKeys = [];
    var children = [];
    var readKeys = [];
    this.constructor.eachComputedProperty(function(name, meta) {
      if (meta.isForm) {
        childKeys.push(name);
        children.push(this.get(name));
      } else if (meta.isFormRead) {
        readKeys.push(name);
      }
    }, this);
    this.set('_children', Ember.A(children));
    this.set('_childKeys', Ember.A(childKeys));
    this.set('_readKeys', Ember.A(readKeys));
    if (childKeys.length > 0) {
      childKeys.forEach(function(key) {
        bindProperties(this, key + ".currentScope", "currentScope." + key);
      }, this);
      readKeys.forEach(function(key) {
        bindProperties(this, key, "currentScope." + key, true).toString();
      }, this);
    }
  }).on('init'),

  willDestroy: function() {
    this.get('_children').forEach(function(child) {
      child.destroy();
    });
    this._super.apply(this, arguments);
  }
});

Form.rule = function(fn) {
  var args;
  if (arguments.length > 1) {
    args = a_slice.call(arguments);
    fn = args.pop();
    args = args.map(function(key) {
      return "_form." + key;
    });
  }

  args.push(function thunk() {
    var form = this.get('_form');
    return makePromise(function(resolve, reject) {
      if (fn.length === 2) {
        fn.call(form, resolve, reject);
      } else if (fn.length === 0){
        if (fn.call(form)) {
          resolve();
        } else {
          reject();
        }
      } else {
        Ember.assert("Form.rule should be called with either 0 or 2 arguments", false);
      }
    });
  });

  return Ember.computed.apply(Ember, args);
};

Form.hasOne = function(attrs) {
  attrs = attrs || {};
  return Ember.computed(function() {
    return Form.extend(attrs).create({
      _parentForm: this
    });
  }).meta({isForm: true});
};

Form.reads = function(dependentKey) {
  return Ember.computed(dependentKey, function() {
    return this.get(dependentKey);
  }).readOnly().meta({isFormRead: true});
};

var Validation = Ember.Object.extend({
  isPending: readOnly('result.isPending'),
  isSettled: readOnly('result.isSettled'),
  isRejected: readOnly('result.isRejected'),
  isFulfilled: readOnly('result.isFulfilled')
});

export default Form;
<|endoftext|>


<commit_before>angular.module('app').controller('dashEventCtrl', function($scope, $http, $filter, $route,$routeParams, ngNotifier,ngIdentity,$modal,$location,$log) {
$scope.contentloaded=false;
$scope.identity = ngIdentity;
$scope.continueNav = true;

//Prevent accidental leaving of dashboard event screen
$scope.$on('$locationChangeStart', function( event ) {
  if (!$scope.continueNav){
      var answer = confirm("Are you sure you want to leave this page?")
      if (!answer) {
          event.preventDefault();
      }
    }
});

$log.debug($routeParams.id);
$http.get('/api/events/id/'+$routeParams.id).then(function(res){
     if(res.data) {
     $log.debug(res.data[0]);
     $scope.eventdoc=res.data[0];
     $scope.contentloaded = true;
     } else {
         alert('no data received, assign new id');
     }
});

$scope.date = new Date().getTime();
$scope.activeTab="tab_0";

//hide categories from coordinator if incomplete
$scope.hideFromCoordinator = function(category) {
  return !($scope.identity.isAuthorized('levelTwo') &&  (category.statusCompleted==false));
};

//show tabs only the tabes assigned to logged in user
$scope.filterTabForAnalyst = function(category) {
  if($scope.identity.currentUser)
  {
    return ((category.userAssigned.id == $scope.identity.currentUser._id) || $scope.identity.currentUser.roles.levelTwo);
  }
};

$scope.returnToAnalyst = function(category) {
// set category statusCompleted flag back to false so analyst could access their assigned category
  category.statusCompleted = false;

  var data = { docId : $scope.eventdoc._id , categoryData : category};

  $http.post('/api/events/saveEventCategory',data).then(function(res) {
    if(res.data.success) {
      ngNotifier.notify(data.categoryData.name  + " has been returned to "+ data.categoryData.userAssigned.displayName);
    } else {
      alert('There was an error, failed to return to analyst.');
    }
  });

};

$scope.setActiveTab = function(tabId)
{
  $log.debug(tabId);
  $scope.activeTab=tabId;

};

    // $scope.addTopic = function(category) {
    //   $log.debug(category);
    //   // if ($scope.eventdoc.categories.indexOf(category).topics.length > 10) {
    //   //   window.alert('You can\'t add more than 10 topics!');
    //   //   return;
    //   // }
    //   //var topicName = document.getElementById('topicName').value;
    //   var topicName = $scope.topicValue[category.name];
    //   if (topicName.length > 0) {
    //     category.topics.push({
    //       name: topicName,
    //       type: 'topic',
    //       subTopics: [],
    //       sortOrder: category.topics.length
    //     });

    //   }
    //   $scope.topicValue={};
    // };

    // $scope.editTopic = function(topic) {
    //   topic.editing = true;
    // };

    // $scope.cancelEditingTopic = function(topic) {
    //   topic.editing = false;
    // };

    // $scope.saveTopic = function(topic) {
    //   // topic.save();
    //   topic.editing = false;
    // };

    // $scope.removeTopic = function(category, topic) {
    //   // if (window.confirm('Are you sure to remove this topic?')) {
    //   //   //topic.destroy();  //TODO
    //   // }
    //   $log.debug(category);
    //   $log.debug(topic);
    //   var index = category.topics.indexOf(topic);
    //    if (index > -1) {
    //      category.topics.splice(index, 1)[0];
    //    }
    // };

    $scope.saveTopics = function() {
      for (var i = $scope.eventdoc.categories[0].topics.length - 1; i >= 0; i--) {
        var topic = $scope.eventdoc.categories[0].topics[i];
        topic.sortOrder = i + 1;
         // topic.save();
      }
    };

    // $scope.addSubTopic = function(topic) {
    //   $log.debug(topic);
    //   if (!topic.newSubTopicName || topic.newSubTopicName.length === 0) {
    //     return;
    //   }
    //   topic.subTopics.push({
    //     name: topic.newSubTopicName,
    //     sortOrder: topic.subTopics.length,
    //     type: 'subTopic',
    //     bullets:[]
    //   });
    //   topic.newSubTopicName = '';
    //   // topic.save();
    // };

    // $scope.removeSubTopic = function(topic, subTopic) {
    //   //if (window.confirm('Are you sure to remove this subTopic?')) {
    //     var index = topic.subTopics.indexOf(subTopic);
    //     if (index > -1) {
    //       topic.subTopics.splice(index, 1)[0];
    //     }
    //     // topic.save();
    //   //}
    // };

    $scope.addBullet = function(subTopic,e) {
      $log.debug(subTopic);
      if (!subTopic.newBulletName || subTopic.newBulletName.length === 0) {
        return;
      }
      subTopic.bullets.push({
        name: subTopic.newBulletName,
        sortOrder: subTopic.bullets.length,
        type: 'bullet',
        editing:'',
        subBullets:[]
      });
      subTopic.newBulletName = '';
      e.preventDefault();
      // topic.save();
    };

    $scope.removeBullet = function(subTopic, bullet) {
      //if (window.confirm('Are you sure to remove this subTopic?')) {
        var index = subTopic.bullets.indexOf(bullet);
        if (index > -1) {
          subTopic.bullets.splice(index, 1)[0];
        }
        // topic.save();
      //}
    };

    $scope.editBullet = function(bullet) {
      bullet.editing=true;
    };

    $scope.saveBullet = function(bullet,e) {
      bullet.editing=false;
      e.preventDefault();
    };

    $scope.addSubBullet = function(bullet,e) {
      $log.debug(bullet);
      if (!bullet.newSubBulletName || bullet.newSubBulletName.length === 0) {
        return;
      }
      bullet.subBullets.push({
        name: bullet.newSubBulletName,
        sortOrder: bullet.subBullets.length,
        editing:'',
        type: 'subBullet'
      });
      bullet.newSubBulletName = '';
      e.preventDefault();
      // topic.save();
    };

    $scope.editSubBullet = function(subBullet) {
      subBullet.editing=true;
    };

    $scope.saveSubBullet = function(subBullet,e) {
      subBullet.editing=false;
      e.preventDefault();
    };

    $scope.removeSubBullet = function(bullet, subBullet) {
      //if (window.confirm('Are you sure to remove this subTopic?')) {
        var index = bullet.subBullets.indexOf(subBullet);
        if (index > -1) {
          bullet.subBullets.splice(index, 1)[0];
        }
        // topic.save();
      //}
     };

    $scope.editSubTopic = function(subTopic) {
      $log.debug("edit sub topic");
      subTopic.editing = true;
    };

    // $scope.cancelEditingSubTopic = function(topic) {
    //   topic.editing = false;
    // };

    $scope.saveSubTopic = function(subTopic) {
      // topic.save();
      subTopic.editing = false;
    };

      $scope.options = {
      accept: function(sourceNode, destNodes, destIndex) {
        var data = sourceNode.$modelValue;
        var destType = destNodes.$element.attr('data-type');
        return (data.type == destType); // only accept the same type
      },
      dropped: function(event) {
        $log.debug(event);
        var sourceNode = event.source.nodeScope;
        var destNodes = event.dest.nodesScope;
        // update changes to server
        if (destNodes.isParent(sourceNode)
          && destNodes.$element.attr('data-type') == 'subTopic') { // If it moves in the same topic, then only update topic
          var topic = destNodes.$nodeScope.$modelValue;
          // topic.save();
        } else { // save all
          $scope.saveTopics();
        }
      },
      beforeDrop: function(event) {
        // if (!window.confirm('Are you sure you want to drop it here?')) {
        //   event.source.nodeScope.$$apply = false;
        // }
      }
    };

$scope.saveCategory = function (status) {  // save data for the current tab

 var oneCategoryData;

 if (ngIdentity.isAuthorized('levelTwo'))
 { // coordinator save - save data from each category only if category statusCompleted flag = true
     $log.debug("i am in coordinator save");
     for(var i=0 ; i <$scope.eventdoc.categories.length; i++)
     {
       $log.debug($scope.eventdoc.categories[i]);
       if ($scope.eventdoc.categories[i].statusCompleted) {
            console.log
            oneCategoryData = $scope.eventdoc.categories[i];
            var data = { docId : $scope.eventdoc._id , categoryData : oneCategoryData };
            saveOneCategory(data);
       }
     }
 }
 else
 {  // analyst save
     for(var i=0 ; i <$scope.eventdoc.categories.length; i++)
     {
       if ($scope.eventdoc.categories[i].name == $scope.activeCategory) {
            oneCategoryData = $scope.eventdoc.categories[i];
            break;
       }
     }
      if (status === 'completed') {
        oneCategoryData.statusCompleted = true;
        oneCategoryData.dateCompleted = new Date().getTime();
      }
      else {
          oneCategoryData.statusCompleted = false;
      }
      var data = { docId : $scope.eventdoc._id , categoryData : oneCategoryData };

        $http.post('/api/events/saveEventCategory',data).then(function(res) {

            if(res.data.success) {
              if (oneCategoryData.statusCompleted === true) {
                ngNotifier.notify("Thank you. Your information has been submitted for review.");
                $location.path('/dashboard/');
              } else {
                ngNotifier.notify("Saved");
              }
            } else {
              alert('there was an error');
            }
          });
 }
 $scope.continueNav=true;
 var unregister=$scope.$watch('eventdoc', function(newVal, oldVal){
     $log.debug("watching");
      if(newVal!=oldVal)
      {
        $log.debug('changed');
        if(oldVal == undefined){
            //do nothing
        } else {
          $scope.continueNav=false;
          unregister();
        }

        $log.debug('oldVal: ', oldVal);
        $log.debug('newVal: ', newVal);
      }

    }, true);
};

function saveOneCategory(data) {
  // save category's data only
   $log.debug("i am in save one category" , data);
   $http.post('/api/events/saveEventCategory',data).then(function(res) {
              if(res.data.success) {
                ngNotifier.notify("Event category "+ data.categoryData.name  + " has been saved!");
              } else {
                alert('there was an error');
              }
            });

}

function getLatestInstance(partialId)
    {
      $log.debug(partialId);

       $http.get('/api/events/getAvailEventId/'+partialId).then(function(res){
        $log.debug(partialId);
         $log.debug(res.data);
         if(res.data) {
             if(res.data.length>0)
             {
                $log.debug("ID alreADy prsent");
                 return partialId+"xx";
             }
             else
             {
                $log.debug("id available to be used");
                $log.debug(partialId);
                return partialId;
             }

             } else {
                 alert('no data received, assign new id');
             }
        });

    }

    function genInstanceId(eventName)
    {
        var nameComponent = eventName.toUpperCase().split(' ');
        var instanceId;
        if (nameComponent.length > 1)
            instanceId = nameComponent[0].substr(0,2) + nameComponent[1].substr(0,2)+ '-'+ '01';
        else
            instanceId = nameComponent[0].substr(0,4)+ '-' + '01';
        return instanceId;
    }

$scope.showInfo = function() {
  // function to activate "moreinfomodal"
   var modalInstance = $modal.open({
      scope:$scope,
      templateUrl: '/partials/moreInfoModal',
      controller: infoModalInstanceCtrl,
      windowClass: 'center-modal',
      size: 'md',
      resolve: {
         instance: function () {
           return $scope.eventdoc;
         }
       }

    });
};

var infoModalInstanceCtrl = function ($scope, $modalInstance) {
// controller for More Information modal popup
$scope.instance = {};
$log.debug('instance in modal ',$scope.instance);
var categoryCount = 0;
var completedCount = 0;

for (var i = 0 ; i < $scope.eventdoc.categories.length; i++)

{
  var oneCategory =  $scope.eventdoc.categories[i];
  var topicCount=oneCategory.topics.length;
      var subTopicCount = 0;
      for (topic in oneCategory.topics) {
        $log.debug('topic object',topic);
        subTopicCount=oneCategory.topics[topic].subTopics.length+subTopicCount;
      }

 $scope.instance[oneCategory.name]={topicCount:topicCount,subTopicCount:subTopicCount,name:oneCategory.name,userAssigned:oneCategory.userAssigned.displayName,statusCompleted:oneCategory.statusCompleted,dateCompleted:oneCategory.dateCompleted};
}

$log.debug('eventdoc ',$scope.eventdoc);
  $scope.ok = function () {

    $modalInstance.close();

  };

  $scope.cancel = function () {

    $modalInstance.dismiss();

  };

  $log.debug('instance object:',$scope.instance);

};

function getNodeCount(document) {
  var nodeCount = 0;
  for (node in document) {
        nodeCount++;
  }
  return nodeCount;
};

$scope.setActiveCategory = function(category)
// retrieve category for the selected category tab
{
  $scope.activeCategory= category;
  $scope.activeTab="tab_0";
};

   var unregister=$scope.$watch('eventdoc', function(newVal, oldVal){
     $log.debug("watching");
      if(newVal!=oldVal)
      {
        $log.debug('changed');
        if(oldVal == undefined){
            //do nothing
        } else {
          $scope.continueNav=false;
          unregister();
        }

      }

    }, true);

});<commit_msg>Changed toastr<commit_after>angular.module('app').controller('dashEventCtrl', function($scope, $http, $filter, $route,$routeParams, ngNotifier,ngIdentity,$modal,$location,$log) {
$scope.contentloaded=false;
$scope.identity = ngIdentity;
$scope.continueNav = true;

//Prevent accidental leaving of dashboard event screen
$scope.$on('$locationChangeStart', function( event ) {
  if (!$scope.continueNav){
      var answer = confirm("Are you sure you want to leave this page?")
      if (!answer) {
          event.preventDefault();
      }
    }
});

$log.debug($routeParams.id);
$http.get('/api/events/id/'+$routeParams.id).then(function(res){
     if(res.data) {
     $log.debug(res.data[0]);
     $scope.eventdoc=res.data[0];
     $scope.contentloaded = true;
     } else {
         alert('no data received, assign new id');
     }
});

$scope.date = new Date().getTime();
$scope.activeTab="tab_0";

//hide categories from coordinator if incomplete
$scope.hideFromCoordinator = function(category) {
  return !($scope.identity.isAuthorized('levelTwo') &&  (category.statusCompleted==false));
};

//show tabs only the tabes assigned to logged in user
$scope.filterTabForAnalyst = function(category) {
  if($scope.identity.currentUser)
  {
    return ((category.userAssigned.id == $scope.identity.currentUser._id) || $scope.identity.currentUser.roles.levelTwo);
  }
};

$scope.returnToAnalyst = function(category) {
// set category statusCompleted flag back to false so analyst could access their assigned category
  category.statusCompleted = false;

  var data = { docId : $scope.eventdoc._id , categoryData : category};

  $http.post('/api/events/saveEventCategory',data).then(function(res) {
    if(res.data.success) {
      ngNotifier.notify(data.categoryData.name  + " has been returned to "+ data.categoryData.userAssigned.displayName);
    } else {
      alert('There was an error, failed to return to analyst.');
    }
  });

};

$scope.setActiveTab = function(tabId)
{
  $log.debug(tabId);
  $scope.activeTab=tabId;

};

    // $scope.addTopic = function(category) {
    //   $log.debug(category);
    //   // if ($scope.eventdoc.categories.indexOf(category).topics.length > 10) {
    //   //   window.alert('You can\'t add more than 10 topics!');
    //   //   return;
    //   // }
    //   //var topicName = document.getElementById('topicName').value;
    //   var topicName = $scope.topicValue[category.name];
    //   if (topicName.length > 0) {
    //     category.topics.push({
    //       name: topicName,
    //       type: 'topic',
    //       subTopics: [],
    //       sortOrder: category.topics.length
    //     });

    //   }
    //   $scope.topicValue={};
    // };

    // $scope.editTopic = function(topic) {
    //   topic.editing = true;
    // };

    // $scope.cancelEditingTopic = function(topic) {
    //   topic.editing = false;
    // };

    // $scope.saveTopic = function(topic) {
    //   // topic.save();
    //   topic.editing = false;
    // };

    // $scope.removeTopic = function(category, topic) {
    //   // if (window.confirm('Are you sure to remove this topic?')) {
    //   //   //topic.destroy();  //TODO
    //   // }
    //   $log.debug(category);
    //   $log.debug(topic);
    //   var index = category.topics.indexOf(topic);
    //    if (index > -1) {
    //      category.topics.splice(index, 1)[0];
    //    }
    // };

    $scope.saveTopics = function() {
      for (var i = $scope.eventdoc.categories[0].topics.length - 1; i >= 0; i--) {
        var topic = $scope.eventdoc.categories[0].topics[i];
        topic.sortOrder = i + 1;
         // topic.save();
      }
    };

    // $scope.addSubTopic = function(topic) {
    //   $log.debug(topic);
    //   if (!topic.newSubTopicName || topic.newSubTopicName.length === 0) {
    //     return;
    //   }
    //   topic.subTopics.push({
    //     name: topic.newSubTopicName,
    //     sortOrder: topic.subTopics.length,
    //     type: 'subTopic',
    //     bullets:[]
    //   });
    //   topic.newSubTopicName = '';
    //   // topic.save();
    // };

    // $scope.removeSubTopic = function(topic, subTopic) {
    //   //if (window.confirm('Are you sure to remove this subTopic?')) {
    //     var index = topic.subTopics.indexOf(subTopic);
    //     if (index > -1) {
    //       topic.subTopics.splice(index, 1)[0];
    //     }
    //     // topic.save();
    //   //}
    // };

    $scope.addBullet = function(subTopic,e) {
      $log.debug(subTopic);
      if (!subTopic.newBulletName || subTopic.newBulletName.length === 0) {
        return;
      }
      subTopic.bullets.push({
        name: subTopic.newBulletName,
        sortOrder: subTopic.bullets.length,
        type: 'bullet',
        editing:'',
        subBullets:[]
      });
      subTopic.newBulletName = '';
      e.preventDefault();
      // topic.save();
    };

    $scope.removeBullet = function(subTopic, bullet) {
      //if (window.confirm('Are you sure to remove this subTopic?')) {
        var index = subTopic.bullets.indexOf(bullet);
        if (index > -1) {
          subTopic.bullets.splice(index, 1)[0];
        }
        // topic.save();
      //}
    };

    $scope.editBullet = function(bullet) {
      bullet.editing=true;
    };

    $scope.saveBullet = function(bullet,e) {
      bullet.editing=false;
      e.preventDefault();
    };

    $scope.addSubBullet = function(bullet,e) {
      $log.debug(bullet);
      if (!bullet.newSubBulletName || bullet.newSubBulletName.length === 0) {
        return;
      }
      bullet.subBullets.push({
        name: bullet.newSubBulletName,
        sortOrder: bullet.subBullets.length,
        editing:'',
        type: 'subBullet'
      });
      bullet.newSubBulletName = '';
      e.preventDefault();
      // topic.save();
    };

    $scope.editSubBullet = function(subBullet) {
      subBullet.editing=true;
    };

    $scope.saveSubBullet = function(subBullet,e) {
      subBullet.editing=false;
      e.preventDefault();
    };

    $scope.removeSubBullet = function(bullet, subBullet) {
      //if (window.confirm('Are you sure to remove this subTopic?')) {
        var index = bullet.subBullets.indexOf(subBullet);
        if (index > -1) {
          bullet.subBullets.splice(index, 1)[0];
        }
        // topic.save();
      //}
     };

    $scope.editSubTopic = function(subTopic) {
      $log.debug("edit sub topic");
      subTopic.editing = true;
    };

    // $scope.cancelEditingSubTopic = function(topic) {
    //   topic.editing = false;
    // };

    $scope.saveSubTopic = function(subTopic) {
      // topic.save();
      subTopic.editing = false;
    };

      $scope.options = {
      accept: function(sourceNode, destNodes, destIndex) {
        var data = sourceNode.$modelValue;
        var destType = destNodes.$element.attr('data-type');
        return (data.type == destType); // only accept the same type
      },
      dropped: function(event) {
        $log.debug(event);
        var sourceNode = event.source.nodeScope;
        var destNodes = event.dest.nodesScope;
        // update changes to server
        if (destNodes.isParent(sourceNode)
          && destNodes.$element.attr('data-type') == 'subTopic') { // If it moves in the same topic, then only update topic
          var topic = destNodes.$nodeScope.$modelValue;
          // topic.save();
        } else { // save all
          $scope.saveTopics();
        }
      },
      beforeDrop: function(event) {
        // if (!window.confirm('Are you sure you want to drop it here?')) {
        //   event.source.nodeScope.$$apply = false;
        // }
      }
    };

$scope.saveCategory = function (status) {  // save data for the current tab

 var oneCategoryData;

 if (ngIdentity.isAuthorized('levelTwo'))
 { // coordinator save - save data from each category only if category statusCompleted flag = true
     $log.debug("i am in coordinator save");
     for(var i=0 ; i <$scope.eventdoc.categories.length; i++)
     {
       $log.debug($scope.eventdoc.categories[i]);
       if ($scope.eventdoc.categories[i].statusCompleted) {
            console.log
            oneCategoryData = $scope.eventdoc.categories[i];
            var data = { docId : $scope.eventdoc._id , categoryData : oneCategoryData };
            saveOneCategory(data);
       }
     }
     ngNotifier.notify("Event has been saved!");
 }
 else
 {  // analyst save
     for(var i=0 ; i <$scope.eventdoc.categories.length; i++)
     {
       if ($scope.eventdoc.categories[i].name == $scope.activeCategory) {
            oneCategoryData = $scope.eventdoc.categories[i];
            break;
       }
     }
      if (status === 'completed') {
        oneCategoryData.statusCompleted = true;
        oneCategoryData.dateCompleted = new Date().getTime();
      }
      else {
          oneCategoryData.statusCompleted = false;
      }
      var data = { docId : $scope.eventdoc._id , categoryData : oneCategoryData };

        $http.post('/api/events/saveEventCategory',data).then(function(res) {

            if(res.data.success) {
              if (oneCategoryData.statusCompleted === true) {
                ngNotifier.notify("Thank you. Your information has been submitted for review.");
                $location.path('/dashboard/');
              } else {
                ngNotifier.notify("Saved");
              }
            } else {
              alert('there was an error');
            }
          });
 }
 $scope.continueNav=true;
 var unregister=$scope.$watch('eventdoc', function(newVal, oldVal){
     $log.debug("watching");
      if(newVal!=oldVal)
      {
        $log.debug('changed');
        if(oldVal == undefined){
            //do nothing
        } else {
          $scope.continueNav=false;
          unregister();
        }

        $log.debug('oldVal: ', oldVal);
        $log.debug('newVal: ', newVal);
      }

    }, true);
};

function saveOneCategory(data) {
  // save category's data only
   $log.debug("i am in save one category" , data);
   $http.post('/api/events/saveEventCategory',data).then(function(res) {
              if(res.data.success) {

              } else {
                alert('there was an error');
              }
            });

}

function getLatestInstance(partialId)
    {
      $log.debug(partialId);

       $http.get('/api/events/getAvailEventId/'+partialId).then(function(res){
        $log.debug(partialId);
         $log.debug(res.data);
         if(res.data) {
             if(res.data.length>0)
             {
                $log.debug("ID alreADy prsent");
                 return partialId+"xx";
             }
             else
             {
                $log.debug("id available to be used");
                $log.debug(partialId);
                return partialId;
             }

             } else {
                 alert('no data received, assign new id');
             }
        });

    }

    function genInstanceId(eventName)
    {
        var nameComponent = eventName.toUpperCase().split(' ');
        var instanceId;
        if (nameComponent.length > 1)
            instanceId = nameComponent[0].substr(0,2) + nameComponent[1].substr(0,2)+ '-'+ '01';
        else
            instanceId = nameComponent[0].substr(0,4)+ '-' + '01';
        return instanceId;
    }

$scope.showInfo = function() {
  // function to activate "moreinfomodal"
   var modalInstance = $modal.open({
      scope:$scope,
      templateUrl: '/partials/moreInfoModal',
      controller: infoModalInstanceCtrl,
      windowClass: 'center-modal',
      size: 'md',
      resolve: {
         instance: function () {
           return $scope.eventdoc;
         }
       }

    });
};

var infoModalInstanceCtrl = function ($scope, $modalInstance) {
// controller for More Information modal popup
$scope.instance = {};
$log.debug('instance in modal ',$scope.instance);
var categoryCount = 0;
var completedCount = 0;

for (var i = 0 ; i < $scope.eventdoc.categories.length; i++)

{
  var oneCategory =  $scope.eventdoc.categories[i];
  var topicCount=oneCategory.topics.length;
      var subTopicCount = 0;
      for (topic in oneCategory.topics) {
        $log.debug('topic object',topic);
        subTopicCount=oneCategory.topics[topic].subTopics.length+subTopicCount;
      }

 $scope.instance[oneCategory.name]={topicCount:topicCount,subTopicCount:subTopicCount,name:oneCategory.name,userAssigned:oneCategory.userAssigned.displayName,statusCompleted:oneCategory.statusCompleted,dateCompleted:oneCategory.dateCompleted};
}

$log.debug('eventdoc ',$scope.eventdoc);
  $scope.ok = function () {

    $modalInstance.close();

  };

  $scope.cancel = function () {

    $modalInstance.dismiss();

  };

  $log.debug('instance object:',$scope.instance);

};

function getNodeCount(document) {
  var nodeCount = 0;
  for (node in document) {
        nodeCount++;
  }
  return nodeCount;
};

$scope.setActiveCategory = function(category)
// retrieve category for the selected category tab
{
  $scope.activeCategory= category;
  $scope.activeTab="tab_0";
};

   var unregister=$scope.$watch('eventdoc', function(newVal, oldVal){
     $log.debug("watching");
      if(newVal!=oldVal)
      {
        $log.debug('changed');
        if(oldVal == undefined){
            //do nothing
        } else {
          $scope.continueNav=false;
          unregister();
        }

      }

    }, true);

});<|endoftext|>