<commit_before>'use strict';

/**
 * @ngdoc directive
 * @name generic-result-display
 * @restrict E
 * @scope
 * @description
 *  A UI control for displaying a search result.
 *
 * @param {expression} data - The result data.
 */
angular.module('searchApp')
  .directive('genericResultDisplay', [ '$log', 'SolrService', function ($log, SolrService) {
    return {
      templateUrl: 'views/generic-result-display.html',
      restrict: 'E',
      scope: {
          'data': '=ngModel',
      },
      link: function postLink(scope, element, attrs) {
          scope.showProvenance = false;
          scope.networkView = false;
          scope.imageSet = false;

          // determine the source url to use for the record
          if (scope.data.display_url !== undefined) {
              scope.data.reference = scope.data.display_url;
          } else {
              scope.data.reference = scope.data.id;
          }

          // is this a finding aid item with an image set attached?
          if (scope.data.type === 'Finding Aid Item' && scope.data.large_images !== undefined) {
            scope.imageSet = true;
            scope.imageCount = scope.data.small_images.length;
          }

          // is this an entity that can be visualised by connex?
          if (scope.data.data_type === 'OHRM' && scope.data.main_type === undefined) {
              if (_.has(SolrService.configuration.connexSites, scope.data.site_code)) scope.networkView = true;
          }

          scope.viewImageSet = function() {
              scope.imageSetData = scope.data;
          }
          scope.viewNetwork = function() {
              scope.networkData = scope.data;
          }
      }
    };
  }]);
<commit_msg>bugfix code to enable network view<commit_after>'use strict';

/**
 * @ngdoc directive
 * @name generic-result-display
 * @restrict E
 * @scope
 * @description
 *  A UI control for displaying a search result.
 *
 * @param {expression} data - The result data.
 */
angular.module('searchApp')
  .directive('genericResultDisplay', [ '$log', 'SolrService', function ($log, SolrService) {
    return {
      templateUrl: 'views/generic-result-display.html',
      restrict: 'E',
      scope: {
          'data': '=ngModel',
      },
      link: function postLink(scope, element, attrs) {
          scope.showProvenance = false;
          scope.networkView = false;
          scope.imageSet = false;

          // determine the source url to use for the record
          if (scope.data.display_url !== undefined) {
              scope.data.reference = scope.data.display_url;
          } else {
              scope.data.reference = scope.data.id;
          }

          // is this a finding aid item with an image set attached?
          if (scope.data.type === 'Finding Aid Item' && scope.data.large_images !== undefined) {
            scope.imageSet = true;
            scope.imageCount = scope.data.small_images.length;
          }

          // is this an entity that can be visualised by connex?
          if (scope.data.data_type === 'OHRM') {
            if (scope.data.main_type === undefined) {
              if (_.has(SolrService.configuration.connexSites, scope.data.site_code)) {
                if (scope.data.type !== 'Text') scope.networkView = true;
              }
            }
          }

          scope.viewImageSet = function() {
              scope.imageSetData = scope.data;
          }
          scope.viewNetwork = function() {
              scope.networkData = scope.data;
          }
      }
    };
  }]);
<|endoftext|>


<commit_before>function bookController($scope, $routeParams, $http)
{
    $scope.onLoad = onLoad;
    $scope.title={};
    $scope.session = {};
    $scope.bookInfo = {};
    $scope.addToCart = addToCart;

    var bookId = ($routeParams.id || "");
    console.log("bookId: " + bookId);
    console.log("in the client side controller");
    onLoad();

    function onLoad(){
        var text;
        var signed;
        console.log("in on load");

        $http.post('/userManage/getSessionInfo')
            .success(function(data){
                signed = data.signed;
                $scope.session = data.session;

                if(signed)
                {
                    document.getElementById("name").textContent = $scope.session.user.userName+" | ";

                }

                $http.get('/booksInfo/loadBookInfo/'+bookId)
                    .success(function (data) {
                        $scope.bookInfo = data;
                    })
                    .error(function (data) {
                        console.log("Error: "+data);

                    })

            })
            .error(function(data){
                console.log("Error: "+data);
            });
    }

    function addToCart(id)
    {
        console.log("in add to cart "+ id);
        $http.get('booksCatalog/addBookToCart/'+id)
            .success(function (data) {
                alert(data.msg);
            })
            .error(function (data) {
                console.log("Error: "+data);
            });
    }

}

<commit_msg>Update bookController.js<commit_after>function bookController($scope, $routeParams, $http)
{
    $scope.onLoad = onLoad;
    $scope.title={};
    $scope.session = {};
    $scope.bookInfo = {};
    $scope.addToCart = addToCart;

    var bookId = ($routeParams.id || "");
    console.log("bookId: " + bookId);
    console.log("in the client side controller");
    onLoad();

    function onLoad(){
        var text;
        var signed;
        console.log("in on load");

        $http.post('/userManage/getSessionInfo')
            .success(function(data){
                signed = data.signed;
                $scope.session = data.session;

                if(signed)
                {
                    document.getElementById("name").textContent = $scope.session.user.userName+" | ";

                }

                $http.get('/booksInfo/loadBookInfo/'+bookId)
                    .success(function (data) {
                        $scope.bookInfo = data;
                    })
                    .error(function (data) {
                        console.log("Error: "+data);

                    })

            })
            .error(function(data){
                console.log("Error: "+data);
            });
    }

    function addToCart(id)
    {
        console.log("in add to cart "+ id);
        $http.get('/booksCatalog/addBookToCart/'+id)
            .success(function (data) {
                alert(data.msg);
            })
            .error(function (data) {
                console.log("Error: "+data);
            });
    }

}

<|endoftext|>


<commit_before>var sqlDataBaseType = {
	mySql		: "mysql",
	postgreSql	: "postgres"
};

var config = require('./config.json');
var configSql = config["sql"];
var baseConnector = (sqlDataBaseType.mySql === configSql["type"]) ? require('./mySqlBaseConnector') : require('./postgreSqlBaseConnector');

var tableChanges = configSql["tableChanges"],
	tableCallbacks = configSql["tableCallbacks"],
	tableResult = configSql["tableResult"],
	tablePucker = configSql["tablePucker"];

var g_oCriticalSection = {}, lockTimeOut = 200;
var maxPacketSize = 1024 * 1024 - 400; // Размер по умолчанию для запроса в базу данных (вычли 400 на поля)

function getDataFromTable (tableId, data, getCondition, callback) {
	var table = getTableById(tableId);
	var sqlCommand = "SELECT " + data + " FROM " + table + " WHERE " + getCondition + ";";

	baseConnector.sqlQuery(sqlCommand, callback);
}
function deleteFromTable (tableId, deleteCondition) {
	var table = getTableById(tableId);
	var sqlCommand = "DELETE FROM " + table + " WHERE " + deleteCondition + ";";

	baseConnector.sqlQuery(sqlCommand);
}
var c_oTableId = {
	pucker		: 1,
	callbacks	: 2,
	changes		: 3
};
function getTableById (id) {
	var res;
	switch (id) {
		case c_oTableId.pucker:
			res = tablePucker;
			break;
		case c_oTableId.callbacks:
			res = tableCallbacks;
			break;
		case c_oTableId.changes:
			res = tableChanges;
			break;
	}
	return res;
}

exports.tableId = c_oTableId;
exports.loadTable = function (tableId, callbackFunction) {
	var table = getTableById(tableId);
	var sqlCommand = "SELECT * FROM " + table + ";";
	baseConnector.sqlQuery(sqlCommand, callbackFunction);
};
exports.insertInTable = function (tableId) {
	var table = getTableById(tableId);
	var sqlCommand = "INSERT INTO " + table + " VALUES (";
	for (var i = 1, l = arguments.length; i < l; ++i) {
		sqlCommand += "'" + arguments[i] + "'";
		if (i !== l - 1)
			sqlCommand += ",";
	}
	sqlCommand += ");";

	baseConnector.sqlQuery(sqlCommand);
};
exports.insertChanges = function (objChanges, docId, index, userId, userIdOriginal) {
	lockCriticalSection(docId, function () {_insertChanges(0, objChanges, docId, index, userId, userIdOriginal);});
};
function _getDateTime(nTime) {
	var oDate = new Date(nTime);
	return oDate.getUTCFullYear() + '-' + ('0' + (oDate.getUTCMonth() + 1)).slice(-2) + '-' + ('0' + oDate.getUTCDate()).slice(-2)
		+ ' ' + ('0' + oDate.getUTCHours()).slice(-2) + ':' + ('0' + oDate.getUTCMinutes()).slice(-2) + ':'
		+ ('0' + oDate.getUTCSeconds()).slice(-2);
}
function _insertChanges (startIndex, objChanges, docId, index, user) {
	var sqlCommand = "INSERT INTO " + tableChanges + " VALUES";
	for (var i = startIndex, l = objChanges.length; i < l; ++i, ++index) {
		sqlCommand += "('" + docId + "','" + index + "','" + user.id + "','" + user.idOriginal + "','"
			+ user.name + "','" + objChanges[i].change + "','" + _getDateTime(objChanges[i].time) + "')";
		if (i === l - 1)
			sqlCommand += ';';
		else if (sqlCommand.length + objChanges[i + 1].change.length >= maxPacketSize) {
			sqlCommand += ';';
			(function (tmpStart, tmpIndex) {
				baseConnector.sqlQuery(sqlCommand, function () {
					// lock не снимаем, а продолжаем добавлять
					_insertChanges(tmpStart, objChanges, docId, tmpIndex, user);
				});
			})(i + 1, index + 1);
			return;
		} else
			sqlCommand += ',';
	}
	baseConnector.sqlQuery(sqlCommand, function () {unLockCriticalSection(docId);});
}

exports.deleteChanges = function (docId, deleteIndex) {
	lockCriticalSection(docId, function () {_deleteChanges(docId, deleteIndex);});
};
function _deleteChanges (docId, deleteIndex) {
	var sqlCommand = "DELETE FROM " + tableChanges + " WHERE dc_key='" + docId + "'";
	if (null !== deleteIndex)
		sqlCommand += " AND dc_change_id >= " + deleteIndex;
	sqlCommand += ";";
	baseConnector.sqlQuery(sqlCommand, function () {unLockCriticalSection(docId);});
}
exports.deleteCallback = function (docId) {
	deleteFromTable(c_oTableId.callbacks, "dc_key='" + docId + "'");
};
exports.deletePucker = function (docId) {
	deleteFromTable(c_oTableId.pucker, "dp_key='" + docId + "'");
};

exports.getChanges = function (docId, callback) {
	lockCriticalSection(docId, function () {_getChanges(docId, callback);});
};
function _getChanges (docId, callback) {
	getDataFromTable(c_oTableId.changes, "*", "dc_key='" + docId + "'",
		function (error, result) {unLockCriticalSection(docId); if (callback) callback(error, result);});
}

exports.checkStatusFile = function (docId, callbackFunction) {
	var sqlCommand = "SELECT tr_status FROM " + tableResult + " WHERE tr_key='" + docId + "';";
	baseConnector.sqlQuery(sqlCommand, callbackFunction);
};
exports.updateStatusFile = function (docId) {
	// Статус OK = 1
	var sqlCommand = "UPDATE " + tableResult + " SET tr_status=1 WHERE tr_key='" + docId + "';";
	baseConnector.sqlQuery(sqlCommand);
};

exports.updateIndexUser = function (docId, indexUser) {
	var sqlCommand = "UPDATE " + tablePucker + " SET dp_indexUser=" + indexUser + " WHERE dp_key='" + docId + "' AND dp_indexUser<" + indexUser + ";";
	baseConnector.sqlQuery(sqlCommand);
};

// Критическая секция
function lockCriticalSection (id, callback) {
	if (g_oCriticalSection[id]) {
		// Ждем
		setTimeout(function () {lockCriticalSection(id, callback);}, lockTimeOut);
		return;
	}
	// Ставим lock
	g_oCriticalSection[id] = true;
	callback();
}
function unLockCriticalSection (id) {
	delete g_oCriticalSection[id];
}<commit_msg>Поправил export insertChanges<commit_after>var sqlDataBaseType = {
	mySql		: "mysql",
	postgreSql	: "postgres"
};

var config = require('./config.json');
var configSql = config["sql"];
var baseConnector = (sqlDataBaseType.mySql === configSql["type"]) ? require('./mySqlBaseConnector') : require('./postgreSqlBaseConnector');

var tableChanges = configSql["tableChanges"],
	tableCallbacks = configSql["tableCallbacks"],
	tableResult = configSql["tableResult"],
	tablePucker = configSql["tablePucker"];

var g_oCriticalSection = {}, lockTimeOut = 200;
var maxPacketSize = 1024 * 1024 - 400; // Размер по умолчанию для запроса в базу данных (вычли 400 на поля)

function getDataFromTable (tableId, data, getCondition, callback) {
	var table = getTableById(tableId);
	var sqlCommand = "SELECT " + data + " FROM " + table + " WHERE " + getCondition + ";";

	baseConnector.sqlQuery(sqlCommand, callback);
}
function deleteFromTable (tableId, deleteCondition) {
	var table = getTableById(tableId);
	var sqlCommand = "DELETE FROM " + table + " WHERE " + deleteCondition + ";";

	baseConnector.sqlQuery(sqlCommand);
}
var c_oTableId = {
	pucker		: 1,
	callbacks	: 2,
	changes		: 3
};
function getTableById (id) {
	var res;
	switch (id) {
		case c_oTableId.pucker:
			res = tablePucker;
			break;
		case c_oTableId.callbacks:
			res = tableCallbacks;
			break;
		case c_oTableId.changes:
			res = tableChanges;
			break;
	}
	return res;
}

exports.tableId = c_oTableId;
exports.loadTable = function (tableId, callbackFunction) {
	var table = getTableById(tableId);
	var sqlCommand = "SELECT * FROM " + table + ";";
	baseConnector.sqlQuery(sqlCommand, callbackFunction);
};
exports.insertInTable = function (tableId) {
	var table = getTableById(tableId);
	var sqlCommand = "INSERT INTO " + table + " VALUES (";
	for (var i = 1, l = arguments.length; i < l; ++i) {
		sqlCommand += "'" + arguments[i] + "'";
		if (i !== l - 1)
			sqlCommand += ",";
	}
	sqlCommand += ");";

	baseConnector.sqlQuery(sqlCommand);
};
exports.insertChanges = function (objChanges, docId, index, user) {
	lockCriticalSection(docId, function () {_insertChanges(0, objChanges, docId, index, user);});
};
function _getDateTime(nTime) {
	var oDate = new Date(nTime);
	return oDate.getUTCFullYear() + '-' + ('0' + (oDate.getUTCMonth() + 1)).slice(-2) + '-' + ('0' + oDate.getUTCDate()).slice(-2)
		+ ' ' + ('0' + oDate.getUTCHours()).slice(-2) + ':' + ('0' + oDate.getUTCMinutes()).slice(-2) + ':'
		+ ('0' + oDate.getUTCSeconds()).slice(-2);
}
function _insertChanges (startIndex, objChanges, docId, index, user) {
	var sqlCommand = "INSERT INTO " + tableChanges + " VALUES";
	for (var i = startIndex, l = objChanges.length; i < l; ++i, ++index) {
		sqlCommand += "('" + docId + "','" + index + "','" + user.id + "','" + user.idOriginal + "','"
			+ user.name + "','" + objChanges[i].change + "','" + _getDateTime(objChanges[i].time) + "')";
		if (i === l - 1)
			sqlCommand += ';';
		else if (sqlCommand.length + objChanges[i + 1].change.length >= maxPacketSize) {
			sqlCommand += ';';
			(function (tmpStart, tmpIndex) {
				baseConnector.sqlQuery(sqlCommand, function () {
					// lock не снимаем, а продолжаем добавлять
					_insertChanges(tmpStart, objChanges, docId, tmpIndex, user);
				});
			})(i + 1, index + 1);
			return;
		} else
			sqlCommand += ',';
	}
	baseConnector.sqlQuery(sqlCommand, function () {unLockCriticalSection(docId);});
}

exports.deleteChanges = function (docId, deleteIndex) {
	lockCriticalSection(docId, function () {_deleteChanges(docId, deleteIndex);});
};
function _deleteChanges (docId, deleteIndex) {
	var sqlCommand = "DELETE FROM " + tableChanges + " WHERE dc_key='" + docId + "'";
	if (null !== deleteIndex)
		sqlCommand += " AND dc_change_id >= " + deleteIndex;
	sqlCommand += ";";
	baseConnector.sqlQuery(sqlCommand, function () {unLockCriticalSection(docId);});
}
exports.deleteCallback = function (docId) {
	deleteFromTable(c_oTableId.callbacks, "dc_key='" + docId + "'");
};
exports.deletePucker = function (docId) {
	deleteFromTable(c_oTableId.pucker, "dp_key='" + docId + "'");
};

exports.getChanges = function (docId, callback) {
	lockCriticalSection(docId, function () {_getChanges(docId, callback);});
};
function _getChanges (docId, callback) {
	getDataFromTable(c_oTableId.changes, "*", "dc_key='" + docId + "'",
		function (error, result) {unLockCriticalSection(docId); if (callback) callback(error, result);});
}

exports.checkStatusFile = function (docId, callbackFunction) {
	var sqlCommand = "SELECT tr_status FROM " + tableResult + " WHERE tr_key='" + docId + "';";
	baseConnector.sqlQuery(sqlCommand, callbackFunction);
};
exports.updateStatusFile = function (docId) {
	// Статус OK = 1
	var sqlCommand = "UPDATE " + tableResult + " SET tr_status=1 WHERE tr_key='" + docId + "';";
	baseConnector.sqlQuery(sqlCommand);
};

exports.updateIndexUser = function (docId, indexUser) {
	var sqlCommand = "UPDATE " + tablePucker + " SET dp_indexUser=" + indexUser + " WHERE dp_key='" + docId + "' AND dp_indexUser<" + indexUser + ";";
	baseConnector.sqlQuery(sqlCommand);
};

// Критическая секция
function lockCriticalSection (id, callback) {
	if (g_oCriticalSection[id]) {
		// Ждем
		setTimeout(function () {lockCriticalSection(id, callback);}, lockTimeOut);
		return;
	}
	// Ставим lock
	g_oCriticalSection[id] = true;
	callback();
}
function unLockCriticalSection (id) {
	delete g_oCriticalSection[id];
}<|endoftext|>


<commit_before>import angular from 'angular';
import FileSaver from 'file-saver';

class exportCtrl {

  constructor($filter, ajaxService) {
    'ngInject';

    this.$filter = $filter;
    this.ajaxService = ajaxService;

    this.exportDate = new Date();
    this.minDate = new Date(2016, 9, 1);
    this.maxDate = new Date();
    this.isProcessing = false;

    let csvExample = `
      The CSV file will include following columns:

      1. name
      2. platform
      3. location
      4. website
      5. dataset count
      6. tag count
      7. category count
      8. publisher count
      9. update date
    `;

    let jsonExample = [
      {
        name: 'data.gov',
        location: 'United States',
        dataset_count: 328421,
        update_date: '2016-10-21',
        tags: [
          { name: 'GIS', dataset_count: 23123, update_date: '2016-10-15' }
        ],
        categories: [
          { name: 'Economics', dataset_count: 5320, update_date: '2016-10-15' }
        ],
        organizations: [
          { "name": "NOAA", "dataset_count": 126900, "update_date": "2016-10-02" }
        ]
      }
    ];

    this.formats = [
      { name: 'JSON', ext: 'json', type: 'application/json', example: $filter('json')(jsonExample) },
      { name: 'CSV', ext: 'csv', type: 'text/plain', example: csvExample }
    ];
  }

  exportData() {
    this.isProcessing = true;

    this.ajaxService.exportData(this.exportDate, this.format.ext)
      .then(data => {
        if (this.format.name === 'JSON') {
          data = JSON.stringify(data);
        }

        let blob = new Blob([data], { type: this.format.type });
        FileSaver.saveAs(blob, `data.${this.format.ext}`);
      })
      .finally(() => {
        this.isProcessing = false;
      });
  }
}

exportCtrl.$inject = ['$filter', 'ajaxService'];

angular.module('OpenDataDiscovery').controller('exportCtrl', exportCtrl);

export default exportCtrl;
<commit_msg>set export min date<commit_after>import angular from 'angular';
import FileSaver from 'file-saver';

class exportCtrl {

  constructor($filter, ajaxService) {
    'ngInject';

    this.$filter = $filter;
    this.ajaxService = ajaxService;

    this.exportDate = new Date();
    this.minDate = new Date(2017, 1, 1);
    this.maxDate = new Date();
    this.isProcessing = false;

    let csvExample = `
      The CSV file will include following columns:

      1. name
      2. platform
      3. location
      4. website
      5. dataset count
      6. tag count
      7. category count
      8. publisher count
      9. update date
    `;

    let jsonExample = [
      {
        name: 'data.gov',
        location: 'United States',
        dataset_count: 328421,
        update_date: '2016-10-21',
        tags: [
          { name: 'GIS', dataset_count: 23123, update_date: '2016-10-15' }
        ],
        categories: [
          { name: 'Economics', dataset_count: 5320, update_date: '2016-10-15' }
        ],
        organizations: [
          { "name": "NOAA", "dataset_count": 126900, "update_date": "2016-10-02" }
        ]
      }
    ];

    this.formats = [
      { name: 'JSON', ext: 'json', type: 'application/json', example: $filter('json')(jsonExample) },
      { name: 'CSV', ext: 'csv', type: 'text/plain', example: csvExample }
    ];
  }

  exportData() {
    this.isProcessing = true;

    this.ajaxService.exportData(this.exportDate, this.format.ext)
      .then(data => {
        if (this.format.name === 'JSON') {
          data = JSON.stringify(data);
        }

        let blob = new Blob([data], { type: this.format.type });
        FileSaver.saveAs(blob, `data.${this.format.ext}`);
      })
      .finally(() => {
        this.isProcessing = false;
      });
  }
}

exportCtrl.$inject = ['$filter', 'ajaxService'];

angular.module('OpenDataDiscovery').controller('exportCtrl', exportCtrl);

export default exportCtrl;
<|endoftext|>


<commit_before>$(function () {
    $p.apply = function () {
        $('.edit-form-tabs:not(.applied)').tabs({
            beforeActivate: function (event, ui) {
                if (ui.newPanel.attr('data-action')) {
                    $p.send(ui.newPanel);
                }
            }
        }).addClass('applied');
        $('.edit-form-tabs-max:not(.applied)').tabs().addClass('applied');
        $('.button-icon').each(function () {
            var $control = $(this);
            var icon = $control.attr('data-icon');
            $control.button({ icon: icon });
        });
        $('#ui-datepicker-div').remove();
        $('select[multiple]:not(.applied)').multiselect({
            selectedList: 100,
            checkAllText: $p.display('Displays_CheckAll'),
            uncheckAllText: $p.display('Displays_UncheckAll'),
            noneSelectedText: '',
            click: function () {
                $p.changeMultiSelect($(this))
            },
            checkAll: function () {
                $p.changeMultiSelect($(this))
            },
            uncheckAll: function () {
                $p.changeMultiSelect($(this))
            }
        }).addClass('applied');
        $('.datepicker').datepicker({
            showButtonPanel: true,
            onSelect: function (date) {
                $p.getDataByInnerElement($(this))[this.id] = date;
            }
        });
        $('.radio').buttonset();
        $('.control-selectable:not(.applied)').selectable({
            stop: function () {
                $p.onSelectableSelected($(this));
            }
        }).addClass('applied');
        $('.control-slider-ui').each(function () {
            var $control = $('#' + $(this).attr('id').split(',')[0]);
            $(this).slider({
                min: parseFloat($(this).attr('data-min')),
                max: parseFloat($(this).attr('data-max')),
                step: parseFloat($(this).attr('data-step')),
                value: parseFloat($control.text()),
                slide: function (event, ui) {
                    $control.text(ui.value);
                    $p.setData($control);
                }
            });
        });
        $('.control-spinner:not(.applied)').each(function () {
            var $control = $(this);
            $control.spinner({
                min: $control.attr('data-min'),
                max: $control.attr('data-max'),
                step: $control.attr('data-step')
            }).css('width', function () {
                return $control.attr('data-width');
            });
            $control.addClass('applied');
        });
        $('[class*="enclosed"] .legend').each(function (e) {
            if ($(this).find('[class^="ui-icon ui-icon-carat-1-"]').length === 0) {
                $(this).prepend($('<span/>').addClass('ui-icon ui-icon-carat-1-s'));
            }
        });
        $('.status').each(function () {
            $(this).addClass($(this).find('option:selected').attr('data-class'));
        });
        $('.control-markdown:not(.applied)').each(function () {
            var $control = $(this);
            var $viewer = $('[id="' + this.id + '.viewer"]');
            $viewer.html($p.markup($control.val()));
            $p.resizeEditor($control, $viewer);
            $control.addClass('applied');
        });
        $('.markup:not(.applied)').each(function () {
            var $control = $(this);
            $control.html($p.markup($control.html(), true));
            $control.addClass('applied');
        });
    }
    $p.apply();
});<commit_msg>Bug fixed: buttonメソッドが多重適用される問題を解消。<commit_after>$(function () {
    $p.apply = function () {
        $('.edit-form-tabs:not(.applied)').tabs({
            beforeActivate: function (event, ui) {
                if (ui.newPanel.attr('data-action')) {
                    $p.send(ui.newPanel);
                }
            }
        }).addClass('applied');
        $('.edit-form-tabs-max:not(.applied)').tabs().addClass('applied');
        $('.button-icon:not(.applied)').each(function () {
            var $control = $(this);
            var icon = $control.attr('data-icon');
            $control.button({ icon: icon });
        }).addClass('applied');
        $('#ui-datepicker-div').remove();
        $('select[multiple]:not(.applied)').multiselect({
            selectedList: 100,
            checkAllText: $p.display('Displays_CheckAll'),
            uncheckAllText: $p.display('Displays_UncheckAll'),
            noneSelectedText: '',
            click: function () {
                $p.changeMultiSelect($(this))
            },
            checkAll: function () {
                $p.changeMultiSelect($(this))
            },
            uncheckAll: function () {
                $p.changeMultiSelect($(this))
            }
        }).addClass('applied');
        $('.datepicker').datepicker({
            showButtonPanel: true,
            onSelect: function (date) {
                $p.getDataByInnerElement($(this))[this.id] = date;
            }
        });
        $('.radio').buttonset();
        $('.control-selectable:not(.applied)').selectable({
            stop: function () {
                $p.onSelectableSelected($(this));
            }
        }).addClass('applied');
        $('.control-slider-ui').each(function () {
            var $control = $('#' + $(this).attr('id').split(',')[0]);
            $(this).slider({
                min: parseFloat($(this).attr('data-min')),
                max: parseFloat($(this).attr('data-max')),
                step: parseFloat($(this).attr('data-step')),
                value: parseFloat($control.text()),
                slide: function (event, ui) {
                    $control.text(ui.value);
                    $p.setData($control);
                }
            });
        });
        $('.control-spinner:not(.applied)').each(function () {
            var $control = $(this);
            $control.spinner({
                min: $control.attr('data-min'),
                max: $control.attr('data-max'),
                step: $control.attr('data-step')
            }).css('width', function () {
                return $control.attr('data-width');
            });
            $control.addClass('applied');
        });
        $('[class*="enclosed"] .legend').each(function (e) {
            if ($(this).find('[class^="ui-icon ui-icon-carat-1-"]').length === 0) {
                $(this).prepend($('<span/>').addClass('ui-icon ui-icon-carat-1-s'));
            }
        });
        $('.status').each(function () {
            $(this).addClass($(this).find('option:selected').attr('data-class'));
        });
        $('.control-markdown:not(.applied)').each(function () {
            var $control = $(this);
            var $viewer = $('[id="' + this.id + '.viewer"]');
            $viewer.html($p.markup($control.val()));
            $p.resizeEditor($control, $viewer);
            $control.addClass('applied');
        });
        $('.markup:not(.applied)').each(function () {
            var $control = $(this);
            $control.html($p.markup($control.html(), true));
            $control.addClass('applied');
        });
    }
    $p.apply();
});<|endoftext|>


<commit_before>//NOTE from http://stackoverflow.com/a/1060034/477045
(function() {
    var hidden = "hidden";

    // Standards:
    if (hidden in document)
        document.addEventListener("visibilitychange", onVisibilityChange);
    else if ((hidden = "mozHidden") in document)
        document.addEventListener("mozvisibilitychange", onVisibilityChange);
    else if ((hidden = "webkitHidden") in document)
        document.addEventListener("webkitvisibilitychange", onVisibilityChange);
    else if ((hidden = "msHidden") in document)
        document.addEventListener("msvisibilitychange", onVisibilityChange);
    // IE 9 and lower:
    else if ('onfocusin' in document)
        document.onfocusin = document.onfocusout = onVisibilityChange;
    // All others:
    else
        window.onpageshow = window.onpagehide
            = window.onfocus = window.onblur = onVisibilityChange;

    function onVisibilityChange (evt) {
      var v = 'visible', h = 'hidden';
      var evtMap = {
        focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
      };

      evt = evt || window.event;
      if(evt.type == "focusout" || evt.type == "blur" || evt.type == "pagehige" || this[hidden]) {
        App.isPageActive = false;
      }
      else {
        App.isPageActive = true;
        document.title = "Mogo Chat";
      }
    }
})();

App.notifyBySound = function() {
  if(App.isPageActive)
    return

  document.title = "[+] " + document.title
  $audio = $("#app-audio")[0];
  $audio.load();
  $audio.play();
}<commit_msg>Indicate notification in title only if not already done<commit_after>//NOTE from http://stackoverflow.com/a/1060034/477045
(function() {
    var hidden = "hidden";

    // Standards:
    if (hidden in document)
        document.addEventListener("visibilitychange", onVisibilityChange);
    else if ((hidden = "mozHidden") in document)
        document.addEventListener("mozvisibilitychange", onVisibilityChange);
    else if ((hidden = "webkitHidden") in document)
        document.addEventListener("webkitvisibilitychange", onVisibilityChange);
    else if ((hidden = "msHidden") in document)
        document.addEventListener("msvisibilitychange", onVisibilityChange);
    // IE 9 and lower:
    else if ('onfocusin' in document)
        document.onfocusin = document.onfocusout = onVisibilityChange;
    // All others:
    else
        window.onpageshow = window.onpagehide
            = window.onfocus = window.onblur = onVisibilityChange;

    function onVisibilityChange (evt) {
      var v = 'visible', h = 'hidden';
      var evtMap = {
        focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
      };

      evt = evt || window.event;
      if(evt.type == "focusout" || evt.type == "blur" || evt.type == "pagehige" || this[hidden]) {
        App.isPageActive = false;
      }
      else {
        App.isPageActive = true;
        document.title = "Mogo Chat";
      }
    }
})();

App.notifyBySound = function() {
  if(App.isPageActive)
    return

  if(!document.title.match(/[\+]/g))
    document.title = "[+] " + document.title;

  $audio = $("#app-audio")[0];
  $audio.load();
  $audio.play();
};<|endoftext|>


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

/**
 * External dependencies
 */
import Card, { CardActions } from '@material/react-card';
import classnames from 'classnames';
import PropTypes from 'prop-types';

/**
 * Internal dependencies
 */
import { createIncrementalArrayBySize } from '../util/create-incremental-array-by-size';
import CloseIcon from '../../svg/icons/close.svg';
import Button from './Button';

export default function TourTooltip( {
	backProps,
	closeProps,
	index,
	primaryProps,
	size,
	step,
	tooltipProps,
} ) {
	const indicatorArray = size > 1 ? createIncrementalArrayBySize( size ) : [];
	const getIndicatorClassName = ( indicatorIndex ) =>
		classnames( 'googlesitekit-tooltip-indicator', {
			active: indicatorIndex === index,
		} );

	return (

			<Card className="googlesitekit-tooltip-card">

						{ step.title }

						{ step.content }

				<CardActions className="googlesitekit-tooltip-actions">

						{ indicatorArray.map( ( indicatorIndex ) => (
							<li
								key={ `indicator-${ indicatorIndex }` }
								className={ getIndicatorClassName(
									indicatorIndex
								) }
							/>
						) ) }

						{ index !== 0 && (
							<Button
								className="googlesitekit-tooltip-button"
								text
								{ ...backProps }
							>
								{ backProps.title }
							</Button>
						) }
						{ step.cta }
						{ primaryProps.title && (
							<Button
								className="googlesitekit-tooltip-button"
								text
								{ ...primaryProps }
							>
								{ primaryProps.title }
							</Button>
						) }

				</CardActions>
				<Button
					className="googlesitekit-tooltip-close"
					text
					icon={ <CloseIcon width="14" height="14" /> }
					{ ...closeProps }
				/>
			</Card>

	);
}

/**
 * All props are provided directly from `react-joyride`, intended for custom components.
 *
 * @since 1.28.0
 * @see {@link https://docs.react-joyride.com/custom-components#props-1}.
 */
TourTooltip.propTypes = {
	backProps: PropTypes.object.isRequired,
	closeProps: PropTypes.object.isRequired,
	index: PropTypes.number.isRequired,
	isLastStep: PropTypes.bool.isRequired,
	primaryProps: PropTypes.object.isRequired,
	size: PropTypes.number.isRequired,
	step: PropTypes.shape( {
		content: PropTypes.node,
		title: PropTypes.node.isRequired,
		cta: PropTypes.element,
		className: PropTypes.string,
	} ).isRequired,
	tooltipProps: PropTypes.object.isRequired,
};
<commit_msg>Fix failing tests.<commit_after>/**
 * TourTooltip component.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import Card, { CardActions } from '@material/react-card';
import classnames from 'classnames';
import PropTypes from 'prop-types';

/**
 * Internal dependencies
 */
import { createIncrementalArrayBySize } from '../util/create-incremental-array-by-size';
import CloseIcon from '../../svg/icons/close.svg';
import Button from './Button';

export default function TourTooltip( {
	backProps,
	closeProps,
	index,
	primaryProps,
	size,
	step,
	tooltipProps,
} ) {
	const indicatorArray = size > 1 ? createIncrementalArrayBySize( size ) : [];
	const getIndicatorClassName = ( indicatorIndex ) =>
		classnames( 'googlesitekit-tooltip-indicator', {
			active: indicatorIndex === index,
		} );

	return (

			<Card className="googlesitekit-tooltip-card">

						{ step.title }

						{ step.content }

				<CardActions className="googlesitekit-tooltip-actions">

						{ indicatorArray.map( ( indicatorIndex ) => (
							<li
								key={ `indicator-${ indicatorIndex }` }
								className={ getIndicatorClassName(
									indicatorIndex
								) }
							/>
						) ) }

						{ index !== 0 && (
							<Button
								className="googlesitekit-tooltip-button"
								text
								{ ...backProps }
							>
								{ backProps.title }
							</Button>
						) }
						{ step.cta }
						{ primaryProps.title && (
							<Button
								className="googlesitekit-tooltip-button"
								text
								{ ...primaryProps }
							>
								{ primaryProps.title }
							</Button>
						) }

				</CardActions>
				<Button
					className="googlesitekit-tooltip-close"
					text
					icon={ <CloseIcon width="14" height="14" /> }
					{ ...closeProps }
				/>
			</Card>

	);
}

/**
 * All props are provided directly from `react-joyride`, intended for custom components.
 *
 * @since 1.28.0
 * @see {@link https://docs.react-joyride.com/custom-components#props-1}.
 */
TourTooltip.propTypes = {
	backProps: PropTypes.object.isRequired,
	closeProps: PropTypes.object.isRequired,
	index: PropTypes.number.isRequired,
	isLastStep: PropTypes.bool.isRequired,
	primaryProps: PropTypes.object.isRequired,
	size: PropTypes.number.isRequired,
	step: PropTypes.shape( {
		content: PropTypes.node,
		title: PropTypes.node.isRequired,
		cta: PropTypes.oneOfType( [ PropTypes.element, PropTypes.bool ] ),
		className: PropTypes.string,
	} ).isRequired,
	tooltipProps: PropTypes.object.isRequired,
};
<|endoftext|>


<commit_before>function clearTabContent(tab) {
    const content = tab;
    content.innerText = '';
}

function getJSON(url, callback) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = () => {
        const status = xhr.status;
        if (status === 200) {
            callback(null, xhr.response);
        } else {
            callback(status);
        }
    };
    xhr.send(null);
}

function insertVideo(title, videoLink) {
    let noRel;

    if (videoLink === 'https://www.youtube.com/embed/yf7B4UgraXg?list=PLNsL1D_GAczZ_0Ocddeic0uivx1u3lWPP') {
        noRel = '';
    } else {
        noRel = '?rel=0';
    }

    const outerContainer = document.createElement('div');
    const lineBreaks = '

';
    const endTag = '
';
    outerContainer.innerHTML = lineBreaks + title + endTag;

    const container = document.createElement('div');
    container.className = 'video-window';

    const videoTitle = document.createElement('span');
    videoTitle.innerText = title;
    videoTitle.className = 'product-title';
    container.appendChild(videoTitle);

    const videoWindow = document.createElement('iframe');
    videoWindow.className = 'youtube';
    videoWindow.src = videoLink + noRel;
    container.appendChild(videoWindow);
    outerContainer.appendChild(container);

    // return container;

    return outerContainer;
}

function insertGalleryVideo(videoSrc, thumbnail) {
    const noRel = '?rel=0&showinfo=0';
    // create the video modal

    const theContainer = document.querySelector('#Overview');

    const theModal = document.createElement('div');
    theModal.className = 'modal';
    theModal.setAttribute('id', 'modalVideo');
    theModal.setAttribute('data-reveal', '');

    const videoContainer = document.createElement('div');
    videoContainer.className = 'video-container';

    const xButton = document.createElement('a');
    xButton.className = 'modal-close';
    xButton.setAttribute('href', '#');
    xButton.setAttribute('aria-label', 'Close');
    xButton.setAttribute('role', 'button');

    const theX = document.createElement('span');
    theX.setAttribute('aria-hidden', 'true');
    theX.innerText = 'x';

    const theVideo = document.createElement('iframe');
    theVideo.style = 'background:none;border:none;';

    // This removes the recommended videos

    theVideo.src = videoSrc + noRel;

    xButton.appendChild(theX);
    videoContainer.appendChild(xButton);
    videoContainer.appendChild(theVideo);
    videoContainer.appendChild(theVideo);
    theModal.appendChild(videoContainer);
    theContainer.appendChild(theModal);

    // target dom

    const thumbnailGallary = document.querySelector('.productView-thumbnails');

    // set elements

    const thumbNailLi = document.createElement('li');
    const thumbNailOuter = document.createElement('a');
    const thumbNail = document.createElement('img');

    // setting the attributes in these elements.

    thumbNailLi.setAttribute('class', 'productView-thumbnail');

    thumbNailOuter.setAttribute('class', 'productView-thumbnail-link');
    thumbNailOuter.setAttribute('id', 'productView-thumbnail-video');
    thumbNailOuter.setAttribute('data-reveal-id', 'modalVideo');
    thumbNailOuter.setAttribute('href', '#modalVideo');

    thumbNail.setAttribute('src', thumbnail);

    thumbNailOuter.appendChild(thumbNail);
    thumbNailLi.appendChild(thumbNailOuter);
    thumbnailGallary.appendChild(thumbNailLi);
}

export default function () {
    const videoTabContent = document.querySelector('#Videos');
    //const overViewContent = document.querySelector('#Overview');

    if (videoTabContent) {
        let tabContent = videoTabContent.innerText.split('.')[1];
        tabContent = tabContent.split('%%')[0];
        const requestURL = 'https://www.aqlightinggroup.com/content/json/video-tab-videos.json';

        getJSON(requestURL, (error, data) => {
            if (error) {
                // console.log('This is the error', error);
            } else {
                for (let i = data.length - 1; i >= 0; i--) {
                    if (data[i].name === tabContent) {
                        clearTabContent(videoTabContent);
                        const newContent = insertVideo(data[i].title, data[i].url);
                        videoTabContent.insertAdjacentElement('beforeend', newContent);
                        insertGalleryVideo(data[i].url, data[i].thumbnail);
                    }
                }
            }
        });
    }
}
<commit_msg>Fixed Video Tab issue and re-ordered navmenu dropdown<commit_after>function clearTabContent(tab) {
    const content = tab;
    content.innerText = '';
}

function getJSON(url, callback) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = () => {
        const status = xhr.status;
        if (status === 200) {
            callback(null, xhr.response);
        } else {
            callback(status);
        }
    };
    xhr.send(null);
}

function insertVideo(title, videoLink) {
    let noRel;

    if (videoLink === 'https://www.youtube.com/embed/yf7B4UgraXg?list=PLNsL1D_GAczZ_0Ocddeic0uivx1u3lWPP') {
        noRel = '';
    } else {
        noRel = '?rel=0';
    }

    const outerContainer = document.createElement('div');
    const lineBreaks = '

';
    const endTag = '
';
    outerContainer.innerHTML = lineBreaks + title + endTag;

    const container = document.createElement('div');
    container.className = 'video-window';

    const videoTitle = document.createElement('span');
    videoTitle.innerText = title;
    videoTitle.className = 'product-title';
    container.appendChild(videoTitle);

    const videoWindow = document.createElement('iframe');
    videoWindow.className = 'youtube';
    videoWindow.src = videoLink + noRel;
    container.appendChild(videoWindow);
    outerContainer.appendChild(container);

    // return container;

    return outerContainer;
}

function insertGalleryVideo(videoSrc, thumbnail) {
    const noRel = '?rel=0&showinfo=0';
    // create the video modal

    const theContainer = document.querySelector('#Overview');

    const theModal = document.createElement('div');
    theModal.className = 'modal';
    theModal.setAttribute('id', 'modalVideo');
    theModal.setAttribute('data-reveal', '');

    const videoContainer = document.createElement('div');
    videoContainer.className = 'video-container';

    const xButton = document.createElement('a');
    xButton.className = 'modal-close';
    xButton.setAttribute('href', '#');
    xButton.setAttribute('aria-label', 'Close');
    xButton.setAttribute('role', 'button');

    const theX = document.createElement('span');
    theX.setAttribute('aria-hidden', 'true');
    theX.innerText = 'x';

    const theVideo = document.createElement('iframe');
    theVideo.style = 'background:none;border:none;';

    // This removes the recommended videos

    theVideo.src = videoSrc + noRel;

    xButton.appendChild(theX);
    videoContainer.appendChild(xButton);
    videoContainer.appendChild(theVideo);
    videoContainer.appendChild(theVideo);
    theModal.appendChild(videoContainer);
    theContainer.appendChild(theModal);

    // target dom

    const thumbnailGallary = document.querySelector('.productView-thumbnails');

    // set elements

    const thumbNailLi = document.createElement('li');
    const thumbNailOuter = document.createElement('a');
    const thumbNail = document.createElement('img');

    // setting the attributes in these elements.

    thumbNailLi.setAttribute('class', 'productView-thumbnail');

    thumbNailOuter.setAttribute('class', 'productView-thumbnail-link');
    thumbNailOuter.setAttribute('id', 'productView-thumbnail-video');
    thumbNailOuter.setAttribute('data-reveal-id', 'modalVideo');
    thumbNailOuter.setAttribute('href', '#modalVideo');

    thumbNail.setAttribute('src', thumbnail);

    thumbNailOuter.appendChild(thumbNail);
    thumbNailLi.appendChild(thumbNailOuter);
    thumbnailGallary.appendChild(thumbNailLi);
}

export default function () {
    const videoTabContent = document.querySelector('#Videos');

    if (videoTabContent) {
        let tabContent = videoTabContent.innerText.split('.')[1];
        tabContent = tabContent.split('%%')[0];
        const requestURL = 'https://www.aqlightinggroup.com/content/json/video-tab-videos.json';

        getJSON(requestURL, (error, data) => {
            if (error) {
                // console.log('This is the error', error);
            } else {
                for (let i = data.length - 1; i >= 0; i--) {
                    if (data[i].name === tabContent) {
                        clearTabContent(videoTabContent);
                        const newContent = insertVideo(data[i].title, data[i].url);
                        videoTabContent.insertAdjacentElement('beforeend', newContent);
                        insertGalleryVideo(data[i].url, data[i].thumbnail);
                    }
                }
            }
        });
    }
}
<|endoftext|>


<commit_before>/**
 * The app view for the map module.
 *
 * @class A Backbone view to handle the app.
 * @author Joakim Lundin
 * @author Lucien Bokouka
 * @author Björn Westlin
 * @type {Backbone.View}
 */
var AppView = Backbone.View.extend(
    /** @lends AppView */
    {

      /**
       * @constructs
       */
      initialize: function (options) {
        _.bindAll(this, "render");

        this.title = options.title;
        this.campuses = new Campuses();
        this.locations = new Locations();

        this.mapView = new MapView({
          el: $('#map_canvas')
        });

        this.searchView = new SearchView({
          el: $('#search-box'),
          mapView: this.mapView,
          placeholder: options.title
        });

        var self = this;
        this.locations.on("reset", function () {
          self.mapView.replacePoints(self.locations);
          self.searchView.render(self.locations);
        });

        this.updateLocations();

        // Display a menu button
        if (this.model.get('menu') == true) {
          this.menuPopupView = new MenuPopupView({
            el: $('#menupopup'),
            campuses: this.campuses,
            appModel: this.model
          });

          this.model.on('change:campus', this.changeCampus, this);
          this.campuses.on("reset", this.menuPopupView.updateCampuses, this);

          this.changeCampus();
          this.campuses.fetch();
        }
      },

      /**
       * Registers events.
       */
      events: {
        "click #menubutton": "showMenu"
      },

      /**
       * Render the app module.
       */
      render: function () {
        $('div[data-role="header"] > h1').text(this.title);

        if (this.model.get('menu') == true) {
          $('div[data-role="header"]').append(JST['map/menu/button']);
          $('#menubutton').button();

          this.delegateEvents();
          this.mapView.render();
        }
      },

      /**
       * Show the menu.
       */
      showMenu: function () {
        this.menuPopupView.render();
      },

      /**
       * Show all locations of a specific type.
       */
      updateLocations: function () {
        this.locations.fetch({
          data: {
            types: this.model.get('types')
          },
          error: function () {
            alert("ERROR! Failed to fetch locations.");
          }
        });
      },

      changeCampus: function () {
        var campus = this.model.get('campus');
        var lat = campus.getLat();
        var lng = campus.getLng();
        this.mapView.model.setMapPosition(lat, lng);

        var locations = this.locations.byCampus(campus.get('name'));
        this.mapView.replacePoints(locations);
      }
    });
<commit_msg>MOB-127 - Don't filter locations by campus on campus change.<commit_after>/**
 * The app view for the map module.
 *
 * @class A Backbone view to handle the app.
 * @author Joakim Lundin
 * @author Lucien Bokouka
 * @author Björn Westlin
 * @type {Backbone.View}
 */
var AppView = Backbone.View.extend(
    /** @lends AppView */
    {

      /**
       * @constructs
       */
      initialize: function (options) {
        _.bindAll(this, "render");

        this.title = options.title;
        this.campuses = new Campuses();
        this.locations = new Locations();

        this.mapView = new MapView({
          el: $('#map_canvas')
        });

        this.searchView = new SearchView({
          el: $('#search-box'),
          mapView: this.mapView,
          placeholder: options.title
        });

        var self = this;
        this.locations.on("reset", function () {
          self.mapView.replacePoints(self.locations);
          self.searchView.render(self.locations);
        });

        this.updateLocations();

        // Display a menu button
        if (this.model.get('menu') == true) {
          this.menuPopupView = new MenuPopupView({
            el: $('#menupopup'),
            campuses: this.campuses,
            appModel: this.model
          });

          this.model.on('change:campus', this.changeCampus, this);
          this.campuses.on("reset", this.menuPopupView.updateCampuses, this);

          this.changeCampus();
          this.campuses.fetch();
        }
      },

      /**
       * Registers events.
       */
      events: {
        "click #menubutton": "showMenu"
      },

      /**
       * Render the app module.
       */
      render: function () {
        $('div[data-role="header"] > h1').text(this.title);

        if (this.model.get('menu') == true) {
          $('div[data-role="header"]').append(JST['map/menu/button']);
          $('#menubutton').button();

          this.delegateEvents();
          this.mapView.render();
        }
      },

      /**
       * Show the menu.
       */
      showMenu: function () {
        this.menuPopupView.render();
      },

      /**
       * Show all locations of a specific type.
       */
      updateLocations: function () {
        this.locations.fetch({
          data: {
            types: this.model.get('types')
          },
          error: function () {
            alert("ERROR! Failed to fetch locations.");
          }
        });
      },

      changeCampus: function () {
        var campus = this.model.get('campus');
        var lat = campus.getLat();
        var lng = campus.getLng();
        this.mapView.model.setMapPosition(lat, lng);
        this.mapView.replacePoints(this.locations);
      }
    });
<|endoftext|>


<commit_before>'use strict';

var zucchiniModule = require('./module');

var Chartist = require('chartist');

zucchiniModule
  .component('tcPieChart', {
    template: require('../views/tc-feature-list.html'),
    bindings: {
      data: '<',
      total: '<',
      showLabel: '<',
      donutWidth: '<',
    },
    controller: function ($element) {

      this.chart = null;

      this.$postLink = function () {
        // Attach chart to current element
        this.chart = new Chartist.Pie($element[0]);
        this.updateChart();
      };

      this.$onChanges = function () {
        // Init selected features to bound features
        if (this.chart && this.data && _.isNumber(this.total)) {
          this.updateChart();
        }
      };

      this.$onDestroy = function () {
        // Release chart resources on directive destroy
        this.chart.detach();
      };

      this.updateChart = function () {
        if (this.chart) {
          this.chart.update(this.data, {
            total: this.total,
            donut: true,
            showLabel: this.showLabel,
            donutWidth: this.donutWidth,
          }, true);
        }
      };

    },
  });
<commit_msg>Removed useless template reference<commit_after>'use strict';

var zucchiniModule = require('./module');

var Chartist = require('chartist');

zucchiniModule
  .component('tcPieChart', {
    bindings: {
      data: '<',
      total: '<',
      showLabel: '<',
      donutWidth: '<',
    },
    controller: function ($element) {

      this.chart = null;

      this.$postLink = function () {
        // Attach chart to current element
        this.chart = new Chartist.Pie($element[0]);
        this.updateChart();
      };

      this.$onChanges = function () {
        // Init selected features to bound features
        if (this.chart && this.data && _.isNumber(this.total)) {
          this.updateChart();
        }
      };

      this.$onDestroy = function () {
        // Release chart resources on directive destroy
        this.chart.detach();
      };

      this.updateChart = function () {
        if (this.chart) {
          this.chart.update(this.data, {
            total: this.total,
            donut: true,
            showLabel: this.showLabel,
            donutWidth: this.donutWidth,
          }, true);
        }
      };

    },
  });
<|endoftext|>


<commit_before>var _ = require('../../../lib/alloy/underscore')._,
	U = require('../../../utils'),
	CU = require('../compilerUtils');

exports.parse = function(node, state) {
	return require('./base').parse(node, state, parse);
};

function parse(node, state, args) {
	var children = U.XML.getElementsFromNodes(node.childNodes),
		arrayName = CU.generateUniqueId(),
		code = 'var ' + arrayName + ' = [];\n',
		isSearchBar = false,
		hasRows = false,
		searchBarName;

	// iterate through all children
	for (var i = 0, l = children.length; i < l; i++) {
		var child = children[i],
			childArgs = CU.getParserArgs(child);

		// make sure we are dealing with rows and sections
		if (childArgs.fullname === 'Alloy.Require') {
			var inspect = CU.inspectRequireNode(child);
			_.each(inspect.names, function(name) {
				if (name === 'Ti.UI.TableViewRow' ||
					name === 'Ti.UI.TableViewSection') {
					isSearchBar = false;
				} else if (name === 'Ti.UI.SearchBar') {
					isSearchBar = true;
				} else {
					U.die('TableView <Require> child at position ' + i + ' has elements that are not rows, sections, or SearchBar');
				}
			});
		} else if (childArgs.fullname === 'Ti.UI.TableViewRow' ||
				   childArgs.fullname === 'Ti.UI.TableViewSection') {
			isSearchBar = false;
		} else if (childArgs.fullname === 'Ti.UI.SearchBar') {
			isSearchBar = true;
		} else {
			U.die('TableView child at position ' + i + ' is not a row or section, or a <Require> containing rows, sections, or SearchBar');
		}

		// generate code for the row/section/searchbar
		code += CU.generateNode(child, {
			parent: {},
			styles: state.styles,
			post: function(node, state, args) {
				if (isSearchBar) {
					searchBarName = state.parent.symbol;
				} else {
					hasRows = true;
					return arrayName + '.push(' + state.parent.symbol + ');\n';
				}
			}
		});
	}

	// Create the initial TableView code
	var extras = [];
	if (hasRows) { extras.push(['data', arrayName]); }
	if (searchBarName) { extras.push(['search', searchBarName]) }
	if (extras.length) { state.extraStyle = CU.createVariableStyle(extras); }

	var tableState = require('./default').parse(node, state);
	code += tableState.code;

	// Update the parsing state
	return {
		parent: {},
		styles: state.styles,
		code: code
	}
};<commit_msg>first pass at adding model-view binding to TableViews<commit_after>var _ = require('../../../lib/alloy/underscore')._,
	U = require('../../../utils'),
	CU = require('../compilerUtils'),
	CONST = require('../../../common/constants');

exports.parse = function(node, state) {
	return require('./base').parse(node, state, parse);
};

function parse(node, state, args) {
	var children = U.XML.getElementsFromNodes(node.childNodes),
		arrayName = CU.generateUniqueId(),
		code = '',
		isSearchBar = false,
		hasRows = false,
		searchBarName;

	if (args.collection) {
		var tableState = require('./default').parse(node, state);
		code += tableState.code;

		// iterate through all children
		var itemCode = '';
		for (var i = 0, l = children.length; i < l; i++) {
			var child = children[i],
				childArgs = CU.getParserArgs(child);

			// validate children of tableview

			itemCode += CU.generateNode(child, {
				parent: {},
				styles: state.styles,
				post: function(node, state, args) {
					return 'rows.push(' + state.parent.symbol + ');\n';
				}
			});
		}

		// create fetch handler
		var col = 'Alloy.Collections[\'' + args.collection + '\']';
		code += col + ".on('fetch', function(e) { ";
		code += "	var len = " + col + ".models.length;";
		code += "	var rows = [];";
		code += "	for (var i = 0; i < len; i++) {";
		code += "		var " + CONST.MODEL_VAR + " = " + col + ".models[i];";
		code += itemCode;
		code += "	}";
		code += tableState.parent.symbol + ".setData(rows);";
		code += "});";
	} else {
		code = 'var ' + arrayName + ' = [];\n';

		// iterate through all children
		for (var i = 0, l = children.length; i < l; i++) {
			var child = children[i],
				childArgs = CU.getParserArgs(child);

			// make sure we are dealing with rows and sections
			if (childArgs.fullname === 'Alloy.Require') {
				var inspect = CU.inspectRequireNode(child);
				_.each(inspect.names, function(name) {
					if (name === 'Ti.UI.TableViewRow' ||
						name === 'Ti.UI.TableViewSection') {
						isSearchBar = false;
					} else if (name === 'Ti.UI.SearchBar') {
						isSearchBar = true;
					} else {
						U.die('TableView <Require> child at position ' + i + ' has elements that are not rows, sections, or SearchBar');
					}
				});
			} else if (childArgs.fullname === 'Ti.UI.TableViewRow' ||
					   childArgs.fullname === 'Ti.UI.TableViewSection') {
				isSearchBar = false;
			} else if (childArgs.fullname === 'Ti.UI.SearchBar') {
				isSearchBar = true;
			} else {
				U.die('TableView child at position ' + i + ' is not a row or section, or a <Require> containing rows, sections, or SearchBar');
			}

			// generate code for the row/section/searchbar
			code += CU.generateNode(child, {
				parent: {},
				styles: state.styles,
				post: function(node, state, args) {
					if (isSearchBar) {
						searchBarName = state.parent.symbol;
					} else {
						hasRows = true;
						return arrayName + '.push(' + state.parent.symbol + ');\n';
					}
				}
			});
		}

		// Create the initial TableView code
		var extras = [];
		if (hasRows) { extras.push(['data', arrayName]); }
		if (searchBarName) { extras.push(['search', searchBarName]) }
		if (extras.length) { state.extraStyle = CU.createVariableStyle(extras); }

		var tableState = require('./default').parse(node, state);
		code += tableState.code;
	}

	// Update the parsing state
	return {
		parent: {},
		styles: state.styles,
		code: code
	}
};
<|endoftext|>


<commit_before>export { ConvBlockType };

import { Int } from "./ValueDesc_Base.js";

/** Describe id, range, name of ConvBlockType (Convolution Block Type).
 *
 * Convert number value into integer between [ 0, 6 ] representing operation:
 *   - 0: MOBILE_NET_V1                             (i.e. no-add-inut-to-output, pointwise1 is same size of pointwise21)
 *   - 1: MOBILE_NET_V1_PAD_VALID                   (i.e. no-add-inut-to-output, pointwise1 is same size of pointwise21, depthwise1 with ( pad = "valid" ))
 *   - 2: MOBILE_NET_V2_THIN                        (i.e. add-inut-to-output, pointwise1 is same size of pointwise21)
 *   - 3: MOBILE_NET_V2                             (i.e. add-inut-to-output, pointwise1 is tiwce size of pointwise21)
 *   - 4: SHUFFLE_NET_V2                            (i.e. by channel shuffler)
 *   - 5: SHUFFLE_NET_V2_BY_POINTWISE22             (i.e. by pointwise22)
 *   - 6: SHUFFLE_NET_V2_BY_MOBILE_NET_V1           (i.e. by integrated pointwise1, depthwise1, pointwise21)
 *   - 7: SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID (i.e. by depthwise1 with ( pad = "valid" ) )
 */
class ConvBlockType extends Int {

  constructor() {
    super( 0, 7, [
      "MOBILE_NET_V1",                             // (0)
      "MOBILE_NET_V1_PAD_VALID",                   // (1)
      "MOBILE_NET_V2_THIN",                        // (2)
      "MOBILE_NET_V2",                             // (3)
      "SHUFFLE_NET_V2",                            // (4)
      "SHUFFLE_NET_V2_BY_POINTWISE22",             // (5)
      "SHUFFLE_NET_V2_BY_MOBILE_NET_V1",           // (6)
      "SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID", // (7)
    ] );
  }

  /**
   * @param {number} nConvBlockType  The numeric identifier of ConvBlockType. (ConvBlockType.Singleton.Ids.Xxx)
   * @return {boolean} Return true, if it is MOBILE_NET_Xxx.
   */
  static isMobileNet( nConvBlockType ) {
    switch ( nConvBlockType ) {
      case ValueDesc.ConvBlockType.Ids.MOBILE_NET_V1: // (0)
      case ValueDesc.ConvBlockType.Ids.MOBILE_NET_V1_PAD_VALID: // (1)
      case ValueDesc.ConvBlockType.Ids.MOBILE_NET_V2_THIN: // (2)
      case ValueDesc.ConvBlockType.Ids.MOBILE_NET_V2: // (3)
        return true;
      default:
        return false;
    }
  }

  /**
   * @param {number} nConvBlockType  The numeric identifier of ConvBlockType. (ConvBlockType.Singleton.Ids.Xxx)
   * @return {boolean} Return true, if it is MOBILE_NET_V2_Xxx.
   */
  static isMobileNetV2( nConvBlockType ) {
    switch ( nConvBlockType ) {
      case ValueDesc.ConvBlockType.Ids.MOBILE_NET_V2_THIN: // (2)
      case ValueDesc.ConvBlockType.Ids.MOBILE_NET_V2: // (3)
        return true;
      default:
        return false;
    }
  }

  /**
   * @param {number} nConvBlockType  The numeric identifier of ConvBlockType. (ConvBlockType.Singleton.Ids.Xxx)
   * @return {boolean} Return true, if it is SHUFFLE_NET_Xxx.
   */
  static isShuffleNet( nConvBlockType ) {
    switch ( nConvBlockType ) {
      case ValueDesc.ConvBlockType.Ids.SHUFFLE_NET_V2: // (4)
      case ValueDesc.ConvBlockType.Ids.SHUFFLE_NET_V2_BY_POINTWISE22: // (5)
      case ValueDesc.ConvBlockType.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1: // (6)
      case ValueDesc.ConvBlockType.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID: // (7)
        return true;
      default:
        return false;
    }
  }

  /**
   * @param {number} nConvBlockType  The numeric identifier of ConvBlockType. (ConvBlockType.Singleton.Ids.Xxx)
   * @return {boolean} Return true, if it is Xxx_PAD_VALID.
   */
  static  isPadValid() {
    switch ( nConvBlockType ) {
      case ValueDesc.ConvBlockType.Ids.MOBILE_NET_V1_PAD_VALID: // (1)
      case ValueDesc.ConvBlockType.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID: // (7)
        return true;
      default:
        return false;
    }
  }

}

/** The only one ValueDesc.ConvBlockType instance. */
ConvBlockType.Singleton = new ConvBlockType;
<commit_msg>Update ValueDesc_ConvBlockType.js<commit_after>export { ConvBlockType };

import { Int } from "./ValueDesc_Base.js";

/** Describe id, range, name of ConvBlockType (Convolution Block Type).
 *
 * Convert number value into integer between [ 0, 6 ] representing operation:
 *   - 0: MOBILE_NET_V1                             (i.e. no-add-inut-to-output, pointwise1 is same size of pointwise21)
 *   - 1: MOBILE_NET_V1_PAD_VALID                   (i.e. no-add-inut-to-output, pointwise1 is same size of pointwise21, depthwise1 with ( pad = "valid" ))
 *   - 2: MOBILE_NET_V2_THIN                        (i.e. add-inut-to-output, pointwise1 is same size of pointwise21)
 *   - 3: MOBILE_NET_V2                             (i.e. add-inut-to-output, pointwise1 is tiwce size of pointwise21)
 *   - 4: SHUFFLE_NET_V2                            (i.e. by channel shuffler)
 *   - 5: SHUFFLE_NET_V2_BY_POINTWISE22             (i.e. by pointwise22)
 *   - 6: SHUFFLE_NET_V2_BY_MOBILE_NET_V1           (i.e. by integrated pointwise1, depthwise1, pointwise21)
 *   - 7: SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID (i.e. by depthwise1 with ( pad = "valid" ) )
 */
class ConvBlockType extends Int {

  constructor() {
    super( 0, 7, [
      "MOBILE_NET_V1",                             // (0)
      "MOBILE_NET_V1_PAD_VALID",                   // (1)
      "MOBILE_NET_V2_THIN",                        // (2)
      "MOBILE_NET_V2",                             // (3)
      "SHUFFLE_NET_V2",                            // (4)
      "SHUFFLE_NET_V2_BY_POINTWISE22",             // (5)
      "SHUFFLE_NET_V2_BY_MOBILE_NET_V1",           // (6)
      "SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID", // (7)
    ] );
  }

  /**
   * @param {number} nConvBlockType  The numeric identifier of ConvBlockType. (ConvBlockType.Singleton.Ids.Xxx)
   * @return {boolean} Return true, if it is MOBILE_NET_Xxx.
   */
  static isMobileNet( nConvBlockType ) {
    switch ( nConvBlockType ) {
      case ConvBlockType.Singleton.Ids.MOBILE_NET_V1: // (0)
      case ConvBlockType.Singleton.Ids.MOBILE_NET_V1_PAD_VALID: // (1)
      case ConvBlockType.Singleton.Ids.MOBILE_NET_V2_THIN: // (2)
      case ConvBlockType.Singleton.Ids.MOBILE_NET_V2: // (3)
        return true;
      default:
        return false;
    }
  }

  /**
   * @param {number} nConvBlockType  The numeric identifier of ConvBlockType. (ConvBlockType.Singleton.Ids.Xxx)
   * @return {boolean} Return true, if it is MOBILE_NET_V2_Xxx.
   */
  static isMobileNetV2( nConvBlockType ) {
    switch ( nConvBlockType ) {
      case ConvBlockType.Singleton.Ids.MOBILE_NET_V2_THIN: // (2)
      case ConvBlockType.Singleton.Ids.MOBILE_NET_V2: // (3)
        return true;
      default:
        return false;
    }
  }

  /**
   * @param {number} nConvBlockType  The numeric identifier of ConvBlockType. (ConvBlockType.Singleton.Ids.Xxx)
   * @return {boolean} Return true, if it is SHUFFLE_NET_Xxx.
   */
  static isShuffleNet( nConvBlockType ) {
    switch ( nConvBlockType ) {
      case ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2: // (4)
      case ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_POINTWISE22: // (5)
      case ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1: // (6)
      case ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID: // (7)
        return true;
      default:
        return false;
    }
  }

  /**
   * @param {number} nConvBlockType  The numeric identifier of ConvBlockType. (ConvBlockType.Singleton.Ids.Xxx)
   * @return {boolean} Return true, if it is Xxx_PAD_VALID.
   */
  static  isPadValid() {
    switch ( nConvBlockType ) {
      case ConvBlockType.Singleton.Ids.MOBILE_NET_V1_PAD_VALID: // (1)
      case ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID: // (7)
        return true;
      default:
        return false;
    }
  }

}

/** The only one ValueDesc.ConvBlockType instance. */
ConvBlockType.Singleton = new ConvBlockType;
<|endoftext|>


<commit_before>/* global _*/
'use strict';

angular.module('metadatamanagementApp').service('InstrumentBuilderService',
  function(InstrumentResource, CleanJSObjectService,
    InstrumentIdBuilderService, SurveyIdBuilderService, StudyIdBuilderService) {
    var buildInstrument = function(instrumentFromExcel,
      dataAcquisitionProjectId) {
      var instrument = {
        id: InstrumentIdBuilderService.buildInstrumentId(
          dataAcquisitionProjectId, instrumentFromExcel.number),
        dataAcquisitionProjectId: dataAcquisitionProjectId,
        studyId: StudyIdBuilderService.buildStudyId(dataAcquisitionProjectId),
        number: instrumentFromExcel.number,
        title: {
          en: instrumentFromExcel['title.en'],
          de: instrumentFromExcel['title.de']
        },
        description: {
          en: instrumentFromExcel['description.en'],
          de: instrumentFromExcel['description.de']
        },
        type: instrumentFromExcel.type,
        surveyNumbers: (instrumentFromExcel.surveyNumbers + '').split(
          ','),
        surveyIds: []
      };
      _.forEach(instrument.surveyNumbers, function(number) {
        instrument.surveyIds
          .push(SurveyIdBuilderService.buildSurveyId(
            instrument.dataAcquisitionProjectId, number.trim()));
      });
      var cleanedInstrument = CleanJSObjectService
        .removeEmptyJsonObjects(instrument);
      return new InstrumentResource(cleanedInstrument);
    };

    var buildInstrumentAttachmentMetadata = function(metadataFromExcel,
      dataAcquisitionProjectId, excelRowIndex) {
      var instrumentAttachmentMetadata = {
        instrumentId: InstrumentIdBuilderService.buildInstrumentId(
          dataAcquisitionProjectId, metadataFromExcel.instrumentNumber),
        instrumentNumber: metadataFromExcel.instrumentNumber,
        dataAcquisitionProjectId: dataAcquisitionProjectId,
        description: {
          en: metadataFromExcel['description.en'],
          de: metadataFromExcel['description.de']
        },
        type: {
          en: metadataFromExcel['type.en'],
          de: metadataFromExcel['type.de']
        },
        title: metadataFromExcel.title,
        language: metadataFromExcel.language,
        fileName: metadataFromExcel.filename,
        indexInInstrument: excelRowIndex
      };
      var cleanedMetadata = CleanJSObjectService
        .removeEmptyJsonObjects(instrumentAttachmentMetadata);
      return cleanedMetadata;
    };
    return {
      buildInstrument: buildInstrument,
      buildInstrumentAttachmentMetadata: buildInstrumentAttachmentMetadata
    };
  });
<commit_msg>#1115 added annotations field to instrument upload<commit_after>/* global _*/
'use strict';

angular.module('metadatamanagementApp').service('InstrumentBuilderService',
  function(InstrumentResource, CleanJSObjectService,
    InstrumentIdBuilderService, SurveyIdBuilderService, StudyIdBuilderService) {
    var buildInstrument = function(instrumentFromExcel,
      dataAcquisitionProjectId) {
      var instrument = {
        id: InstrumentIdBuilderService.buildInstrumentId(
          dataAcquisitionProjectId, instrumentFromExcel.number),
        dataAcquisitionProjectId: dataAcquisitionProjectId,
        studyId: StudyIdBuilderService.buildStudyId(dataAcquisitionProjectId),
        number: instrumentFromExcel.number,
        title: {
          en: instrumentFromExcel['title.en'],
          de: instrumentFromExcel['title.de']
        },
        description: {
          en: instrumentFromExcel['description.en'],
          de: instrumentFromExcel['description.de']
        },
        annotations: {
          en: instrumentFromExcel['annotations.en'],
          de: instrumentFromExcel['annotations.de']
        },
        type: instrumentFromExcel.type,
        surveyNumbers: (instrumentFromExcel.surveyNumbers + '').split(
          ','),
        surveyIds: []
      };
      _.forEach(instrument.surveyNumbers, function(number) {
        instrument.surveyIds
          .push(SurveyIdBuilderService.buildSurveyId(
            instrument.dataAcquisitionProjectId, number.trim()));
      });
      var cleanedInstrument = CleanJSObjectService
        .removeEmptyJsonObjects(instrument);
      return new InstrumentResource(cleanedInstrument);
    };

    var buildInstrumentAttachmentMetadata = function(metadataFromExcel,
      dataAcquisitionProjectId, excelRowIndex) {
      var instrumentAttachmentMetadata = {
        instrumentId: InstrumentIdBuilderService.buildInstrumentId(
          dataAcquisitionProjectId, metadataFromExcel.instrumentNumber),
        instrumentNumber: metadataFromExcel.instrumentNumber,
        dataAcquisitionProjectId: dataAcquisitionProjectId,
        description: {
          en: metadataFromExcel['description.en'],
          de: metadataFromExcel['description.de']
        },
        type: {
          en: metadataFromExcel['type.en'],
          de: metadataFromExcel['type.de']
        },
        title: metadataFromExcel.title,
        language: metadataFromExcel.language,
        fileName: metadataFromExcel.filename,
        indexInInstrument: excelRowIndex
      };
      var cleanedMetadata = CleanJSObjectService
        .removeEmptyJsonObjects(instrumentAttachmentMetadata);
      return cleanedMetadata;
    };
    return {
      buildInstrument: buildInstrument,
      buildInstrumentAttachmentMetadata: buildInstrumentAttachmentMetadata
    };
  });
<|endoftext|>


<commit_before>var path = require('path');
var Promise = require('bluebird');
var Retry = require('bluebird-retry');
var fs = Promise.promisifyAll(require('fs-extra'));
var ArduinoBuilder = require('/opt/openrov/cockpit/src/lib/ArduinoBuilder.js');

var execAsync = require('child-process-promise').exec;

var buildOpts = {
    sketchDir: '/opt/openrov/firmware/sketches/ArduinoUSBLinker',
    installBaseDir: '/opt/openrov/firmware/bin',
    productID: '2x',
    cleanAfterBuild: true,
    fqbn: 'openrov:avr:mega:cpu=atmega2560',
    hardware: '/opt/openrov/arduino/hardware',
    tools: '/opt/openrov/arduino/hardware/tools',
    warnings: 'none',
    verbose: true,
    quiet: false,
    debug: 5,
    libs: ['/opt/openrov/arduino/hardware/openrov/avr/libraries'],
    preproc: [],
    generateCode: false
};

var mcuFlashArgs = [ '-P', '/dev/spidev1.0', '-c', 'linuxspi', '-vvv', '-p', 'm2560', '-U', 'flash:w:/opt/openrov/firmware/bin/2x/ArduinoUSBLinker.hex' ];

// Create promise for flashing the MCU
var mcuFlashPromise = execAsync('avrdude', mcuFlashArgs );
var mcuFlashChildProcess = mcuFlashPromise.childProcess;

// Create promise for flashing the ESCs themselves
var escFlashPromise = execAsync('sh', [ "/opt/openrov/system/scripts/FlashESCS.sh" ] );
var escFlashChildProcess = escFlashPromise.childProcess;

// Run build, flash, upload process
ArduinoBuilder.BuildSketch( buildOpts, function(data)
  {
      console.log(data.toString('utf8'));
  }, function(data) {
      console.log(data.toString('utf8'));
  })
.then(function()
{
  return mcuFlashPromise()
            .then( function( result )
            {
                var stdout = result.stdout;
                var stderr = result.stderr;
                console.log('ESC MCU FLASH: stdout: ', stdout);
                console.log('ESC MCU FLASH: stderr: ', stderr);
            });
})
.then( function()
{
  // Now, try five times to flash the ESCs, every 5 seconds
  return retry( escFlashPromise, { max_tries: 5, interval: 5000 })
            .then( function( result )
            {
                var stdout = result.stdout;
                var stderr = result.stderr;
                console.log('ESC FLASH: stdout: ', stdout);
                console.log('ESC FLASH: stderr: ', stderr);
            });
})
.then( function()
{
    console.log( "Success!" );
})<commit_msg>Fixed error with promise syntax<commit_after>var path = require('path');
var Promise = require('bluebird');
var Retry = require('bluebird-retry');
var fs = Promise.promisifyAll(require('fs-extra'));
var ArduinoBuilder = require('/opt/openrov/cockpit/src/lib/ArduinoBuilder.js');

var execAsync = require('child-process-promise').exec;

var buildOpts = {
    sketchDir: '/opt/openrov/firmware/sketches/ArduinoUSBLinker',
    installBaseDir: '/opt/openrov/firmware/bin',
    productID: '2x',
    cleanAfterBuild: true,
    fqbn: 'openrov:avr:mega:cpu=atmega2560',
    hardware: '/opt/openrov/arduino/hardware',
    tools: '/opt/openrov/arduino/hardware/tools',
    warnings: 'none',
    verbose: true,
    quiet: false,
    debug: 5,
    libs: ['/opt/openrov/arduino/hardware/openrov/avr/libraries'],
    preproc: [],
    generateCode: false
};

var mcuFlashArgs = [ '-P', '/dev/spidev1.0', '-c', 'linuxspi', '-vvv', '-p', 'm2560', '-U', 'flash:w:/opt/openrov/firmware/bin/2x/ArduinoUSBLinker.hex' ];

// Create promise for flashing the MCU
var mcuFlashPromise = execAsync('avrdude', mcuFlashArgs );
var mcuFlashChildProcess = mcuFlashPromise.childProcess;

// Create promise for flashing the ESCs themselves
var escFlashPromise = execAsync('sh', [ "/opt/openrov/system/scripts/FlashESCS.sh" ] );
var escFlashChildProcess = escFlashPromise.childProcess;

// Run build, flash, upload process
ArduinoBuilder.BuildSketch( buildOpts, function(data)
  {
      console.log(data.toString('utf8'));
  }, function(data) {
      console.log(data.toString('utf8'));
  })
.then(function()
{
  return mcuFlashPromise
            .then( function( result )
            {
                var stdout = result.stdout;
                var stderr = result.stderr;
                console.log('ESC MCU FLASH: stdout: ', stdout);
                console.log('ESC MCU FLASH: stderr: ', stderr);
            });
})
.then( function()
{
  // Now, try five times to flash the ESCs, every 5 seconds
  return retry( escFlashPromise, { max_tries: 5, interval: 5000 })
            .then( function( result )
            {
                var stdout = result.stdout;
                var stderr = result.stderr;
                console.log('ESC FLASH: stdout: ', stdout);
                console.log('ESC FLASH: stderr: ', stderr);
            });
})
.then( function()
{
    console.log( "Success!" );
})<|endoftext|>


<commit_before>/**
 * Created by idavis on 9/10/14.
 */

var page = RcmAdminService.getPage();
var sessionKeepAlive = false;
page.events.on(
    'editingStateChange',
    function (page) {
        if (page.editMode === true && !sessionKeepAlive) {
            //preventing from session keep alive on multiple pages
            sessionKeepAlive = true;
            setInterval(
                function () {
                    $.get('rcm-page-search/title');
                }, 300000
            );
        }
    }
);<commit_msg>po request fixes<commit_after>/**
 * Created by idavis on 9/10/14.
 */

    (function() {
        var page = RcmAdminService.getPage();
        var sessionKeepAlive = false;
        page.events.on(
            'editingStateChange',
            function (page) {
                if (page.editMode === true && !sessionKeepAlive) {
                    //preventing from session keep alive on multiple pages
                    sessionKeepAlive = true;
                    setInterval(
                        function () {
                            $.get('rcm-page-search/title');
                }, 300000
                    );
                }
            }
        );
    })();<|endoftext|>


<commit_before>//This constructor will return the window for the place detail when clicked from the table view.

function CreatePlacesDetailWindow(_place){
	//--Main Window--
	alert(_place.reviews.length);
	//Create the main window that will be returned by the constructor.
	var self = Ti.UI.createWindow({
		title: _place.name
	});

	var scrollView = Ti.UI.createScrollView({
		height: Ti.UI.FILL,
		width: Ti.UI.FILL,
		contentHeight: 'auto',
		contentWidth: 'auto',
		layout: 'vertical'
	});

	//This is a temporary lable to store the JSON parameters during development.

	var nameView = Ti.UI.createView({
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
	});

	scrollView.add(nameView);

	var imageView = Ti.UI.createImageView({
		width: Ti.UI.FILL,
		height: 100,
		width: 100,
		left: 5,
		top: 5,
		bottom: 5,
		image: _place.image_url
	});

	//Add the temporary label to the window!
	nameView.add(imageView);

	var placeLabel = Ti.UI.createLabel({
		left: 110,
		top: 5,
		width: Ti.UI.FILL,
		text: _place.name,
		font: {fontSize: '20dp'},
	});

	nameView.add(placeLabel);

	var locationLabel = Ti.UI.createLabel({
		left: 110,
		top: 30,
		width: Ti.UI.FILL,
		text: _place.location.display_address[0] + _place.location.display_address[1],
		font: {fontSize: '12dp'},
	});

	nameView.add(locationLabel);

	///////--ADD REVIEW DATA HERE---///////

	var reviewView = Ti.UI.createView({
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE
	});

	scrollView.add(reviewView);

	var headerLabel = Ti.UI.createLabel({
		top: 0,
		width: Ti.UI.FILL,
		height: '30dp',
		font:{
		},
		textAlign: Ti.UI.TEXT_ALIGNMENT_LEFT,
		text: '  Reviews',
		backgroundColor: 'red'
	});

	reviewView.add(headerLabel);

	var reviewImage = Ti.UI.createImageView({
		image: _place.reviews[0].user.image_url,
		width: 50,
		height: 50,
		left: 5,
		top: 35
	});

	reviewView.add(reviewImage);

	var reviewDescriptionLabel = Ti.UI.createLabel({
		text: _place.reviews[0].excerpt,
		left: 60,
		right: 5,
		top: 35,
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
		font:{ fontSize: '12dp'},
	});

	reviewView.add(reviewDescriptionLabel);

	var ratingImage = Ti.UI.createImageView({
		top: 90,
		image: _place.reviews[0].rating_image_small_url,
		width: 50,
		height: 10,
		left: 5,
	});

	reviewView.add(ratingImage);

	///
	//----Call Button---
	//Check if user is on an iPhone Device with dialer capabilities
	if(Ti.Platform.name === 'iPhone OS' || Ti.Platform.osname == 'android'){

		//Create Phone Dialer Button
		var callButton = Ti.UI.createButton({
			width : Ti.UI.SIZE,
			height : '45dp',
			title : 'Call Business'
		});
		//Add Button Click Event Listener
		callButton.addEventListener('click', function() {
			Ti.Platform.openURL('tel:' + _place.phone);
		});
		//Add Button to main window
		scrollView.add(callButton);

	}else{
		var phoneNumberLabel = Ti.UI.createLabel({
			text: _place.phone
		});
		scrollView.add(phoneNumberLabel);
	}
	// endof iPhone Check

	//--Web Site Button--
	//Create Website Button if website present
	if(_place.website != null){
		//Create Website Button
		var websiteButton = Ti.UI.createButton({
			width :Ti.UI.SIZE,
			height : '45dp',
			title : 'View Web Site'
		});
		//Add Website Button Event Listener
		websiteButton.addEventListener('click', function() {
			Ti.Platform.openURL('http://' + _place.website);
		});
		//Add Button to main window
		scrollView.add(websiteButton);

	}// endof Web Site Check

	//-- Directions Button --
	var directionsButton = Ti.UI.createButton({
		width: Ti.UI.SIZE,
		height: '45dp',
		title: 'Get Directions'
	});

	directionsButton.addEventListener('click',function(){
		var encodedDestination = Ti.Network.encodeURIComponent(_place.location.display_address);
		Ti.Platform.openURL((Ti.Platform.osname == 'android') ? 'http://maps.google.com/?daddr=':'http://maps.apple.com/?daddr=' + encodedDestination);
	});

	scrollView.add(directionsButton);

	//Remove label from memory once window is closed!
	self.addEventListener('close',function(){
		label = null;
	});

	self.add(scrollView);

	//return the label to caller.
	return self;

}

module.exports = CreatePlacesDetailWindow;
<commit_msg>Added new view (slider) and added phone label<commit_after>//This constructor will return the window for the place detail when clicked from the table view.

function CreatePlacesDetailWindow(_place){
	//--Main Window--
	alert(_place.reviews.length);
	//Create the main window that will be returned by the constructor.
	var self = Ti.UI.createWindow({
		title: _place.name
	});

	var scrollView = Ti.UI.createScrollView({
		height: Ti.UI.FILL,
		width: Ti.UI.FILL,
		contentHeight: 'auto',
		contentWidth: 'auto',
		layout: 'vertical'
	});

	//This is a temporary lable to store the JSON parameters during development.

	var nameView = Ti.UI.createView({
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
	});

	scrollView.add(nameView);

	var imageView = Ti.UI.createImageView({
		width: Ti.UI.FILL,
		height: 100,
		width: 100,
		left: 5,
		top: 5,
		bottom: 5,
		image: _place.image_url
	});

	//Add the temporary label to the window!
	nameView.add(imageView);

	var slider = Ti.UI.createView({
		top: 0,
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
		layout:'vertical'
	});

	nameView.add(slider);

	var placeLabel = Ti.UI.createLabel({
		left: 110,
		top: 2,
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
		text: _place.name,
		font: {fontSize: '17dp'},
	});

	slider.add(placeLabel);

	var locationLabel = Ti.UI.createLabel({
		left: 110,
		top: 2,
		height: Ti.UI.SIZE,
		width: Ti.UI.FILL,
		text: _place.location.display_address[0] + _place.location.display_address[1],
		font: {fontSize: '13dp'},
	});

	slider.add(locationLabel);

	var phoneLabel = Ti.UI.createLabel({
		left: 110,
		top: 2,
		height: Ti.UI.SIZE,
		width: Ti.UI.FILL,
		text: _place.phone,
		font: {fontSize: '13dp'},
	});

	slider.add(phoneLabel);
	///////--ADD REVIEW DATA HERE---///////

	var reviewView = Ti.UI.createView({
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE
	});

	scrollView.add(reviewView);

	var headerLabel = Ti.UI.createLabel({
		top: 0,
		width: Ti.UI.FILL,
		height: '30dp',
		font:{ fontSize: '16dp'
		},
		textAlign: Ti.UI.TEXT_ALIGNMENT_LEFT,
		text: '  Customer Reviews',
		backgroundColor: 'red'
	});

	reviewView.add(headerLabel);

	var reviewImage = Ti.UI.createImageView({
		image: _place.reviews[0].user.image_url,
		width: 50,
		height: 50,
		left: 5,
		top: 35
	});

	reviewView.add(reviewImage);

	var reviewDescriptionLabel = Ti.UI.createLabel({
		text: _place.reviews[0].excerpt,
		left: 60,
		right: 5,
		top: 35,
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
		font:{ fontSize: '12dp'},
	});

	reviewView.add(reviewDescriptionLabel);

	var ratingImage = Ti.UI.createImageView({
		top: 90,
		image: _place.reviews[0].rating_image_small_url,
		width: 50,
		height: 10,
		left: 5,
	});

	reviewView.add(ratingImage);

	///
	//----Call Button---
	//Check if user is on an iPhone Device with dialer capabilities
	if(Ti.Platform.name === 'iPhone OS' || Ti.Platform.osname == 'android'){

		//Create Phone Dialer Button
		var callButton = Ti.UI.createButton({
			width : Ti.UI.SIZE,
			height : '40dp',
			title : 'Call',
			left: 15,
		});
		//Add Button Click Event Listener
		callButton.addEventListener('click', function() {
			Ti.Platform.openURL('tel:' + _place.phone);
		});
		//Add Button to main window
		scrollView.add(callButton);

	}else{
		var phoneNumberLabel = Ti.UI.createLabel({
			text: _place.phone
		});
		scrollView.add(phoneNumberLabel);
	}
	// endof iPhone Check

	//--Web Site Button--
	//Create Website Button if website present
	if(_place.website != null){
		//Create Website Button
		var websiteButton = Ti.UI.createButton({
			width :Ti.UI.SIZE,
			height : '40dp',
			title : 'View Web Site',
		});
		//Add Website Button Event Listener
		websiteButton.addEventListener('click', function() {
			Ti.Platform.openURL('http://' + _place.website);
		});
		//Add Button to main window
		scrollView.add(websiteButton);

	}// endof Web Site Check

	//-- Directions Button --
	var directionsButton = Ti.UI.createButton({
		width: Ti.UI.SIZE,
		height: '40dp',
		title: 'Directions',
		right: 15,
	});

	directionsButton.addEventListener('click',function(){
		var encodedDestination = Ti.Network.encodeURIComponent(_place.location.display_address);
		Ti.Platform.openURL((Ti.Platform.osname == 'android') ? 'http://maps.google.com/?daddr=':'http://maps.apple.com/?daddr=' + encodedDestination);
	});

	scrollView.add(directionsButton);

	//Remove label from memory once window is closed!
	self.addEventListener('close',function(){
		label = null;
	});

	self.add(scrollView);

	//return the label to caller.
	return self;

}

module.exports = CreatePlacesDetailWindow;
<|endoftext|>


<commit_before>//SettingsView Component Constructor
function SettingsView() {
	self = Ti.UI.createView();

	//label using localization-ready strings from <app dir>/i18n/en/strings.xml
	var label = Ti.UI.createLabel({
		color:'#000000',
		text: 'This is the settings pane!',
		height:'auto',
		width:'auto'
	});
	self.add(label);

	return self;
}

module.exports = SettingsView;<commit_msg>Server URL can now be entered in SettingsView.<commit_after>//SettingsView Component Constructor
function SettingsView() {
	self = Ti.UI.createView({layout: 'vertical'});

	//label using localization-ready strings from <app dir>/i18n/en/strings.xml
	var label = Ti.UI.createLabel({
		color : '#000000',
		text : 'Server location',
		height : 'auto',
		width : 'auto',
		left: 5
	});
	self.add(label);

	var textField = Ti.UI.createTextField({
		borderStyle : Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
		color : '#336699',
		right: 5,
		left: 5,
		value: 'http://survey-web-staging.herokuapp.com/'
	});
	self.add(textField);

	return self;
}

module.exports = SettingsView; <|endoftext|>


<commit_before>(function () {
    "use strict";
    var MainController = function ($scope, HelperService, TrainViewFactory, $http) {
        var trainno = '1111'; //temp value
        $scope.ThisTrain = null;
        var lightOn = false;

        $scope.nowHour = moment().hour();
        $scope.today_dayOftheWeek = moment().day();
        $scope.IsWeekDay = (($scope.today_dayOftheWeek === 0) || ($scope.today_dayOftheWeek === 6)) ? false : true ;
        $scope.checkTimeSlot = moment($scope.nowHour).isBetween(8, 11) ? 'morning' : 'evening';

//        //NOTE :  doesn't need to be in init()
//        function init() {
//            $scope.ThisTrain = TrainViewFactory.getThisTrain(trainno);
//        }
//        init();

        if($scope.IsWeekDay){
            var myTrains_PromiseReturn = HelperService.getMyTrains();
            myTrains_PromiseReturn.then(function (data){
                $scope.myTrains = data;
//                console.log($scope.myTrains);

                $scope.TrainForNow = []; //Trains for THIS timeSlot accordingly
                for(var a=0, len=$scope.myTrains.data.length; a<len; a++){
                    if($scope.myTrains.data[a].timeSlot === $scope.checkTimeSlot){
                        $scope.TrainForNow.push($scope.myTrains.data[a].trainno);
                    }
                };

//                console.log($scope.TrainForNow);

                var Trains_PromiseReturn = HelperService.getSeptaTrains();
                Trains_PromiseReturn.then(function(data){
                    var Trains_data = data;
                    var Trains = Trains_data.data;
                    //console.log(Trains);

                    for(var b=0, l=$scope.TrainForNow.length; b<l; b++){
                        console.log(Trains);

                        trainno = $scope.TrainForNow[b];

                        $scope.ThisTrain = TrainViewFactory.getThisTrain(Trains, trainno);
                        console.log($scope.ThisTrain);

                        if($scope.ThisTrain){ //avoid nulls
                            if($scope.ThisTrain.late > 2){ //train late threshold (in minutes)
                                lightOn = true;
                                break;
                            };
                        };
                    };

                    //console.log(lightOn);
                    if(lightOn){
                      $http({
                          url : 'https://api-http.littlebitscloud.cc/devices/00e04c0340b5/output?percent=50&duration_ms=5000',
                          method : 'POST',
                          headers : {
                              'Authorization' : 'Bearer 75480d214b46ed685b139dc49ddaf7d1cbd0af94f585e31cd5f76ef5d7d908a4',
                              'Accept' : 'application/vnd.littlebits.v2+json',
                              'Content-Type' : 'application/json'
                          }
                        }).then(function SuccesFunc(response) { //handle success
                          console.log('This is a success ');
                        }, function ErrorFunc(response) { //handle error
                          console.log('This is an error ');
                      });
                    };
                });
            });
        };

//        console.log($scope.nowHour);
//        console.log($scope.checkTimeSlot);
//        console.log($scope.IsWeekDay);
//        console.log($scope.ThisTrain);
    };

    MainController.$inject = ['$scope', 'HelperService', 'TrainViewFactory', '$http'];

    angular.module('appSepta')
        .controller('MainController', MainController);

}());<commit_msg>making the Maker api call<commit_after>(function () {
    "use strict";
    var MainController = function ($scope, HelperService, TrainViewFactory, $http, $timeout) {
        var trainno = '1111'; //temp value
        $scope.ThisTrain = null;
        var TrainIsLate = false; //default value
        var lightOn = false;

        $scope.nowHour = moment().hour();
        $scope.today_dayOftheWeek = moment().day();
        $scope.IsWeekDay = (($scope.today_dayOftheWeek === 0) || ($scope.today_dayOftheWeek === 6)) ? false : true ;
        $scope.checkTimeSlot = moment($scope.nowHour).isBetween(8, 11) ? 'morning' : 'evening';

//        //NOTE :  doesn't need to be in init()
//        function init() {
//            $scope.ThisTrain = TrainViewFactory.getThisTrain(trainno);
//        }
//        init();

        if($scope.IsWeekDay){
            var myTrains_PromiseReturn = HelperService.getMyTrains();
            myTrains_PromiseReturn.then(function (data){
                $scope.myTrains = data;
//                console.log($scope.myTrains);

                $scope.TrainForNow = []; //Trains for THIS timeSlot accordingly
                for(var a=0, len=$scope.myTrains.data.length; a<len; a++){
                    if($scope.myTrains.data[a].timeSlot === $scope.checkTimeSlot){
                        $scope.TrainForNow.push($scope.myTrains.data[a].trainno);
                    }
                };

//                console.log($scope.TrainForNow);

                var Trains_PromiseReturn = HelperService.getSeptaTrains();
                Trains_PromiseReturn.then(function(data){
                    var Trains_data = data;
                    var Trains = Trains_data.data;
                    //console.log(Trains);

                    for(var b=0, l=$scope.TrainForNow.length; b<l; b++){
                        console.log(Trains);

                        trainno = $scope.TrainForNow[b];

                        $scope.ThisTrain = TrainViewFactory.getThisTrain(Trains, trainno);
                        console.log($scope.ThisTrain);

                        if($scope.ThisTrain){ //avoid nulls
                            if($scope.ThisTrain.late > 2){ //train late threshold (in minutes)
                                lightOn = true;
                                break;
                            };
                        };
                    };

                    //console.log(lightOn);
                    if(lightOn){
                      TrainIsLate = true;

//                      THIS IS GOOD
                        //Trigger LittleBits CloudBits
//                      $http({
//                          url : 'https://api-http.littlebitscloud.cc/devices/00e04c0340b5/output?percent=50&duration_ms=5000',
//                          method : 'POST',
//                          headers : {
//                              'Authorization' : 'Bearer 75480d214b46ed685b139dc49ddaf7d1cbd0af94f585e31cd5f76ef5d7d908a4',
//                              'Accept' : 'application/vnd.littlebits.v2+json',
//                              'Content-Type' : 'application/json'
//                          }
//                        }).then(function SuccesFunc(response) { //handle success
//                          console.log('This is a success ');
//                        }, function ErrorFunc(response) { //handle error
//                          console.log('This is an error ');
//                      });
//                      //Trigger IFTTT and Maker to send notification
//                      $http({
//                          url : 'https://maker.ifttt.com/trigger/TrainCheck/with/key/GJElXrQFbvHcF1OLmCK_S',
//                          method : 'POST',
//                          headers : {
//                              'Content-Type' : 'application/json'
//                          },
//                          data : {
//                              'value1' : '123', //$scope.ThisTrain.trainno,
//                              'value2' : '5' //$scope.ThisTrain.late
//                          }
//                        }).then(function SuccesFunc(response) { //handle success
//                          console.log('This is a success ');
//                        }, function ErrorFunc(response) { //handle error
//                          console.log('This is an error ');
//                      });
                    };

                    $timeout(function() {
                        $scope.isLate = TrainIsLate;
                    }, 2000);

//                    $scope.isLate = function(){
//                        return TrainIsLate;
//                    };

                });
            });
        };

//        console.log($scope.nowHour);
//        console.log($scope.checkTimeSlot);
//        console.log($scope.IsWeekDay);
//        console.log($scope.ThisTrain);
    };

    MainController.$inject = ['$scope', 'HelperService', 'TrainViewFactory', '$http', '$timeout'];

    angular.module('appSepta')
        .controller('MainController', MainController);

}());<|endoftext|>