<commit_before>// (function(module) {
  function Brewery (opts) {
    Object.keys(opts).forEach(function(b, index, keys) {
      this[b] = opts[b];
    }, this);
  }

  Brewery.all = [];
  Brewery.ids = [];

  var FilterUniqueBreweryIds = function() {
    $.getJSON('/data/breweries.json', function(data) {
      data.forEach(function(b){
        if (Brewery.ids.indexOf(b.id) === -1) {
          Brewery.ids.push(b.id);
        }
      });
    });
  };

  Brewery.handleLocationEndpoint = function() {
    Brewery.ids.forEach(function(id) {
      $.get('/locations/' + id, function(data) {
        var breweryInstance = new Brewery(data.data[0]);
        breweryInstance.insertLocationRecord(id);
      });
    });
  };

  Brewery.handleNameEndpoint = function() {
    Brewery.ids.forEach(function(id) {
      $.get('/name/' + id, function(data) {
        var breweryInstance = new Brewery(data.data);
        breweryInstance.insertNameRecord();
      });
    });
  };

  Brewery.prototype.insertLocationRecord = function(id) {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO breweryLocation (breweryId, streetAddress, postalCode, phone, latitude, longitude, openToPublic, hoursOfOperation) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
          'data': [id, this.streetAddress, this.postalCode, this.phone, this.latitude, this.longitude, this.openToPublic, this.hoursOfOperation],
        }
      ]
    );
  };

  Brewery.prototype.insertNameRecord = function(callback) {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO breweryName (breweryId, name, description, website, established, isOrganic) VALUES (?, ?, ?, ?, ?, ?)',
          'data': [this.id, this.name, this.description, this.website, this.established, this.isOrganic],
        }
      ]
    );
  };

  Brewery.createLocationTable = function(callback) {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS breweryLocation (' +
        'id INTEGER PRIMARY KEY, ' +
        'breweryId, ' +
        'streetAddress VARCHAR(255), ' +
        'postalCode, ' +
        'phone VARCHAR(255), ' +
        'latitude FLOAT, ' +
        'longitude FLOAT, ' +
        'openToPublic BOOLEAN, ' +
        'hoursOfOperation VARCHAR(255));'
    );
  };

  Brewery.createNameTable = function(callback) {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS breweryName (' +
      'id INTEGER PRIMARY KEY, ' +
      'breweryId, ' +
      'name VARCHAR(255), ' +
      'description TEXT, ' +
      'website VARCHAR(255), ' +
      'established DATE, ' +
      'isOrganic BOOLEAN);'
    );
  };

  Brewery.joinTable = function(callback) {
    webDB.execute(
      [
        {
          'sql': 'SELECT * FROM breweryLocation JOIN breweryName ON breweryLocation.breweryId=breweryName.breweryId;'
        }
      ]
    );
  };

  Brewery.fetchAll = function(callback) {
    webDB.execute('SELECT * FROM breweries', function(rows) {
      if (rows.length) {
        Brewery.loadAll(rows);
        callback();
      } else {
        //TODO: refactor to build brewery table.
        // $getJSON('data/breweries.json', function(rawData) {
        //   rawData.forEach(function(breweryEle) {
        //     Brewery.insertRecord();
        //   });
        //   webDB.execute('SELECT * FROM breweries', function(rows) {
        //     Brewery.loadAll(rows);
        //     callback();
        //   });
        // });
      }
    });
  };

  Brewery.findWhere = function(field, value, callback) {
    webDB.execute(
      [
        {
          sql: 'SELECT * FROM breweries WHERE ' + field + ' = ?;',
          data: [value]
        }
      ],
      callback
    );
  };

  FilterUniqueBreweryIds();
  Brewery.createLocationTable();
  Brewery.createNameTable();
  Brewery.handleLocationEndpoint();
  Brewery.handleNameEndpoint();

  // module.Brewery = Brewery;
// })(window);
<commit_msg>add TODOS for tomorrow on view layer<commit_after>// (function(module) {
  function Brewery (opts) {
    Object.keys(opts).forEach(function(b, index, keys) {
      this[b] = opts[b];
    }, this);
  }

  Brewery.ids = [];

  var FilterUniqueBreweryIds = function() {
    $.getJSON('/data/breweries.json', function(data) {
      data.forEach(function(b){
        if (Brewery.ids.indexOf(b.id) === -1) {
          Brewery.ids.push(b.id);
        }
      });
    });
  };

  Brewery.handleLocationEndpoint = function() {
    Brewery.ids.forEach(function(id) {
      $.get('/locations/' + id, function(data) {
        var breweryInstance = new Brewery(data.data[0]);
        breweryInstance.insertLocationRecord(id);
      });
    });
  };

  Brewery.handleNameEndpoint = function() {
    Brewery.ids.forEach(function(id) {
      $.get('/name/' + id, function(data) {
        var breweryInstance = new Brewery(data.data);
        breweryInstance.insertNameRecord();
      });
    });
  };

  Brewery.prototype.insertLocationRecord = function(id) {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO breweryLocation (breweryId, streetAddress, postalCode, phone, latitude, longitude, openToPublic, hoursOfOperation) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
          'data': [id, this.streetAddress, this.postalCode, this.phone, this.latitude, this.longitude, this.openToPublic, this.hoursOfOperation],
        }
      ]
    );
  };

  Brewery.prototype.insertNameRecord = function(callback) {
    webDB.execute(
      [
        {
          'sql': 'INSERT INTO breweryName (breweryId, name, description, website, established, isOrganic) VALUES (?, ?, ?, ?, ?, ?)',
          'data': [this.id, this.name, this.description, this.website, this.established, this.isOrganic],
        }
      ]
    );
  };

  Brewery.createLocationTable = function(callback) {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS breweryLocation (' +
        'id INTEGER PRIMARY KEY, ' +
        'breweryId, ' +
        'streetAddress VARCHAR(255), ' +
        'postalCode, ' +
        'phone VARCHAR(255), ' +
        'latitude FLOAT, ' +
        'longitude FLOAT, ' +
        'openToPublic BOOLEAN, ' +
        'hoursOfOperation VARCHAR(255));'
    );
  };

  Brewery.createNameTable = function(callback) {
    webDB.execute(
      'CREATE TABLE IF NOT EXISTS breweryName (' +
      'id INTEGER PRIMARY KEY, ' +
      'breweryId, ' +
      'name VARCHAR(255), ' +
      'description TEXT, ' +
      'website VARCHAR(255), ' +
      'established DATE, ' +
      'isOrganic BOOLEAN);'
    );
  };

  //TODO: Refactor .joinTable and .findWhere into to one findWhere method that accepts an array of filter objects on different tables based on breweryId.
  //Set this up first in the view layer with checkbox inputs and values from DOM.
  // Brewery.joinTable = function(callback) {
  //   webDB.execute(
  //     [
  //       {
  //         'sql': 'SELECT * FROM breweryLocation JOIN breweryName ON breweryLocation.breweryId=breweryName.breweryId;'
  //       }
  //     ]
  //   );
  // };
  //
  // Brewery.findWhere = function(tableName, field, value, callback) {
  //   webDB.execute(
  //     [
  //       {
  //         sql: 'SELECT * FROM tableName WHERE ' + field + ' = ?;',
  //         data: [value]
  //       }
  //     ],
  //     callback
  //   );
  // };

  Brewery.initTables = function() {
    FilterUniqueBreweryIds();
    Brewery.createLocationTable();
    Brewery.createNameTable();
    Brewery.handleLocationEndpoint();
    Brewery.handleNameEndpoint();
  };
  // module.Brewery = Brewery;
// })(window);
<|endoftext|>


<commit_before>/*
 * This file is part of Invenio.
 * Copyright (C) 2009, 2010, 2011 CERN.
 *
 * Invenio is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * Invenio is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Invenio; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */

/*
 * This is the BibEdit Javascript for all functionality directly related to the
 * left hand side menu, including event handlers for most of the buttons.
 */

function initMenu(){
  /*
   * Initialize menu.
   */
  // Make sure the menu is in it's initial state.
  deactivateRecordMenu();
  $('#txtSearchPattern').val('');
  // Submit get request on enter.
  $('#txtSearchPattern, #sctSearchType').bind('keypress', function(event){
    if (event.keyCode == 13){
      $('#btnSearch').trigger('click');
      event.preventDefault();
    }
  });
  // Set the status.
  $('#cellIndicator').html(img('/img/circle_green'));
  $('#cellStatus').text('Ready');
  // Bind button event handlers.
  $('#imgNewRecord').bind('click', onNewRecordClick);
  $('#btnSearch').bind('click', onSearchClick);
  $('#btnSubmit').bind('click', onSubmitClick);
  $('#btnCancel').bind('click', onCancelClick);
  $('#btnDeleteRecord').bind('click', onDeleteRecordClick);
  $('#btnMARCTags').bind('click', onMARCTagsClick);
  $('#btnHumanTags').bind('click', onHumanTagsClick);
  $('#btnAddField').bind('click', onAddFieldClick);
  $('#btnDeleteSelected').bind('click', onDeleteClick);
  $('#bibEditMenu .bibEditImgCompressMenuSection').bind('click',
    compressMenuSection);
  // Focus on record selection box.
  $('#txtSearchPattern').focus();
  // Initialise the handlers for undo/redo buttons
  $('#bibEditURUndoListLayer').bind("mouseover", showUndoPreview);
  $('#bibEditURUndoListLayer').bind("mouseout", hideUndoPreview);
  $('#bibEditURRedoListLayer').bind("mouseover", showRedoPreview);
  $('#bibEditURRedoListLayer').bind("mouseout", hideRedoPreview);
  $('#btnUndo').bind('click', onUndo);
  $('#btnRedo').bind('click', onRedo);
  $('#lnkSpecSymbols').bind('click', onLnkSpecialSymbolsClick);
  $('#btnSwitchReadOnly').bind('click', onSwitchReadOnlyMode);
  collapseMenuSections();
}

function expandMenuSection(){
  /*
   * Expand a menu section.
   */
  var parent = $(this).parent();
  parent.closest('.bibEditMenuSection').find('.bibEditMenuMore').show();

  $(this).replaceWith(img('/img/bullet_toggle_minus.png', '',
			  'bibEditImgCompressMenuSection'));
  parent.find('.bibEditImgCompressMenuSection').bind('click',
						     compressMenuSection);
}

function compressMenuSection(){
  /*
   * Compress a menu section.
   */
  var parent = $(this).parent();
  parent.closest('.bibEditMenuSection').find('.bibEditMenuMore').hide();

  $(this).replaceWith(img('/img/bullet_toggle_plus.png', '',
			  'bibEditImgExpandMenuSection'));
  parent.find('.bibEditImgExpandMenuSection').bind('click', expandMenuSection);
}

function activateRecordMenu(){
  /*
   * Activate menu record controls.
   */
  $('#imgCloneRecord').bind('click', onCloneRecordClick).removeClass(
    'bibEditImgCtrlDisabled').addClass('bibEditImgCtrlEnabled');
  $('#btnCancel').removeAttr('disabled');
  $('#btnDeleteRecord').removeAttr('disabled');
  $('#btnAddField').removeAttr('disabled');
}

function deactivateRecordMenu(){
  /*
   * Deactivate menu record controls.
   */
  $('#imgCloneRecord').unbind('click').removeClass(
    'bibEditImgCtrlEnabled').addClass('bibEditImgCtrlDisabled');
  $('#btnSubmit').attr('disabled', 'disabled');
  $('#btnSubmit').css('background-color', '');
  $('#btnCancel').attr('disabled', 'disabled');
  $('#btnDeleteRecord').attr('disabled', 'disabled');
  $('#btnMARCTags').attr('disabled', 'disabled');
  $('#btnHumanTags').attr('disabled', 'disabled');
  $('#btnAddField').attr('disabled', 'disabled');
  $('#btnDeleteSelected').attr('disabled', 'disabled');
}

function disableRecordBrowser(){
  /*
   * Disable and hide the menu record browser.
   */
  if ($('#rowRecordBrowser').css('display') != 'none'){
    $('#btnNext').unbind('click').attr('disabled', 'disabled');
    $('#btnPrev').unbind('click').attr('disabled', 'disabled');
    $('#rowRecordBrowser').hide();
  }
}

function onSearchClick(event){
  /*
   * Handle 'Search' button (search for records).
   */
  updateStatus('updating');
  var searchPattern = $('#txtSearchPattern').val();
  var searchType = $('#sctSearchType').val();
  if (searchType == 'recID'){
    // Record ID - do some basic validation.
    var searchPatternParts = searchPattern.split(".");
    var recID = parseInt(searchPatternParts[0]);
    var recRev = searchPatternParts[1];

    if (gRecID == recID && recRev == gRecRev){
      // We are already editing this record.
      updateStatus('ready');
      return;
    }
    if (gRecordDirty && gReadOnlyMode == false){
      // Warn of unsubmitted changes.
      if (!displayAlert('confirmLeavingChangedRecord')){
	updateStatus('ready');
	return;
      }
    }
    else if (gRecID && gReadOnlyMode == false)
      // If the record is unchanged, delete the cache.
      createReq({recID: gRecID, requestType: 'deleteRecordCache'});

    gNavigatingRecordSet = false;
    if (isNaN(recID)){
      // Invalid record ID.
      changeAndSerializeHash({state: 'edit', recid: searchPattern});
      cleanUp(true, null, null, true);
      updateStatus('error', gRESULT_CODES[102]);
      $('.headline').text('Record Editor: Record #' + searchPattern);
      updateToolbar(false);
      displayMessage(102);
    }
    else{
      // Get the record.
      if (recRev == undefined){
        $('#txtSearchPattern').val(recID);
        getRecord(recID);
      } else {
        recRev = recRev.replace(/\s+$/, '');
        $('#txtSearchPattern').val(recID + "." + recRev);
        getRecord(recID, recRev);
      }
    }
  }
  else if (searchPattern.replace(/\s*/g, '')){
    // Custom search.
    if (gRecordDirty){
      // Warn of unsubmitted changes.
      if (!displayAlert('confirmLeavingChangedRecord')){
	updateStatus('ready');
	return;
      }
    }
    else if (gRecID)
      // If the record is unchanged, delete the cache.
      createReq({recID: gRecID, requestType: 'deleteRecordCache'});
    gNavigatingRecordSet = false;
    createReq({requestType: 'searchForRecord', searchType: searchType,
      searchPattern: searchPattern}, onSearchForRecordSuccess);
  }
}

function onSearchForRecordSuccess(json){
  /*
   * Handle successfull 'searchForRecord' requests (custom search).
   */
  gResultSet = json['resultSet'];
  if (gResultSet.length == 0){
    // Search yielded no results.
    changeAndSerializeHash({state: 'edit'});
    cleanUp(true, null, null, true, true);
    updateStatus('report', gRESULT_CODES[json['resultCode']]);
    displayMessage(-1);
  }
  else{
    if (gResultSet.length > 1){
      // Multiple results. Show record browser.
      gNavigatingRecordSet = true;
      var recordCount = gResultSet.length;
      $('#cellRecordNo').text(1 + ' / ' + recordCount);
      $('#btnPrev').attr('disabled', 'disabled');
      $('#btnNext').bind('click', onNextRecordClick).removeAttr('disabled');
      $('#rowRecordBrowser').show();
    }
    gResultSetIndex = 0;
    getRecord(gResultSet[0]);
  }
}

function onNextRecordClick(){
  /*
   * Handle click on the 'Next' button in the record browser.
   */
  updateStatus('updating');
  if (gRecordDirty){
    if (!displayAlert('confirmLeavingChangedRecord')){
      updateStatus('ready');
      return;
    }
  }
  else
    // If the record is unchanged, erase the cache.
    createReq({recID: gRecID, requestType: 'deleteRecordCache'});
  var recordCount = gResultSet.length;
  var prevIndex = gResultSetIndex++;
  var currentIndex = prevIndex + 1;
  if (currentIndex == recordCount-1)
    $(this).unbind('click').attr('disabled', 'disabled');
  if (prevIndex == 0)
    $('#btnPrev').bind('click', onPrevRecordClick).removeAttr('disabled');
  $('#cellRecordNo').text((currentIndex+1) + ' / ' + recordCount);
  getRecord(gResultSet[currentIndex]);
}

function onPrevRecordClick(){
  /*
   * Handle click on the 'Previous' button in the record browser.
   */
  updateStatus('updating');
  if (gRecordDirty){
    if (!displayAlert('confirmLeavingChangedRecord')){
      updateStatus('ready');
      return;
    }
  }
  else
    // If the record is unchanged, erase the cache.
    createReq({recID: gRecID, requestType: 'deleteRecordCache'});
  var recordCount = gResultSet.length;
  var prevIndex = gResultSetIndex--;
  var currentIndex = prevIndex - 1;
  if (currentIndex == 0)
    $(this).unbind('click').attr('disabled', 'disabled');
  if (prevIndex == recordCount-1)
    $('#btnNext').bind('click', onNextRecordClick).removeAttr('disabled');
  $('#cellRecordNo').text((currentIndex+1) + ' / ' + recordCount);
  getRecord(gResultSet[currentIndex]);
}

function onGetTicketsSuccess(json){
/*
 * Handle successfull 'getTickets' requests.
 */
  var tickets = json['tickets'];
  if (json['resultCode'] == 31 && json['tickets'] && gRecID){
    $('#tickets').html(tickets);
    $('#lnkNewTicket').bind('click', function(event){
      setTimeout('createReq({recID: gRecID, requestType: "getTickets"},' +
		 'onGetTicketsSuccess)', gTICKET_REFRESH_DELAY);
    });
  }
}

function updateStatus(statusType, reporttext){
  /*
   * Update status (in the bottom of the menu).
   */
  var image, text;
	gCurrentStatus = statusType;
  switch (statusType){
    case 'ready':
      image = img('/img/circle_green.png');
      text = 'Ready';
      break;
    case 'updating':
      image = img('/img/indicator.gif');
      text = 'Updating...';
      break;
    // Generic report. Resets to 'Ready' after timeout.
    case 'report':
      image = img('/img/circle_green.png');
      text = reporttext;
      clearTimeout(updateStatus.statusResetTimerID);
      updateStatus.statusResetTimerID = setTimeout('updateStatus("ready")',
				  gSTATUS_INFO_TIME);
      break;
    case 'error':
      image = img('/img/circle_red.png');
      text = reporttext;
      clearTimeout(updateStatus.statusResetTimerID);
      updateStatus.statusResetTimerID = setTimeout('updateStatus("ready")',
				  gSTATUS_ERROR_TIME);
      break;
    default:
      image = '';
      text = '';
      break;
  }
  $('#cellIndicator').html(image);
  $('#cellStatus').html(text);
}

function collapseMenuSections() {
    $('#ImgHistoryMenu').trigger('click');
    $('#ImgViewMenu').trigger('click');
}<commit_msg>BibEdit: hide delete record button by default<commit_after>/*
 * This file is part of Invenio.
 * Copyright (C) 2009, 2010, 2011 CERN.
 *
 * Invenio is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * Invenio is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Invenio; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */

/*
 * This is the BibEdit Javascript for all functionality directly related to the
 * left hand side menu, including event handlers for most of the buttons.
 */

function initMenu(){
  /*
   * Initialize menu.
   */
  // Make sure the menu is in it's initial state.
  deactivateRecordMenu();
  $('#txtSearchPattern').val('');
  // Submit get request on enter.
  $('#txtSearchPattern, #sctSearchType').bind('keypress', function(event){
    if (event.keyCode == 13){
      $('#btnSearch').trigger('click');
      event.preventDefault();
    }
  });
  // Set the status.
  $('#cellIndicator').html(img('/img/circle_green'));
  $('#cellStatus').text('Ready');
  // Bind button event handlers.
  $('#imgNewRecord').bind('click', onNewRecordClick);
  $('#btnSearch').bind('click', onSearchClick);
  $('#btnSubmit').bind('click', onSubmitClick);
  $('#btnCancel').bind('click', onCancelClick);
  $('#btnDeleteRecord').bind('click', onDeleteRecordClick);
  $('#btnMARCTags').bind('click', onMARCTagsClick);
  $('#btnHumanTags').bind('click', onHumanTagsClick);
  $('#btnAddField').bind('click', onAddFieldClick);
  $('#btnDeleteSelected').bind('click', onDeleteClick);
  $('#bibEditMenu .bibEditImgCompressMenuSection').bind('click',
    compressMenuSection);
  // Focus on record selection box.
  $('#txtSearchPattern').focus();
  // Initialise the handlers for undo/redo buttons
  $('#bibEditURUndoListLayer').bind("mouseover", showUndoPreview);
  $('#bibEditURUndoListLayer').bind("mouseout", hideUndoPreview);
  $('#bibEditURRedoListLayer').bind("mouseover", showRedoPreview);
  $('#bibEditURRedoListLayer').bind("mouseout", hideRedoPreview);
  $('#btnUndo').bind('click', onUndo);
  $('#btnRedo').bind('click', onRedo);
  $('#lnkSpecSymbols').bind('click', onLnkSpecialSymbolsClick);
  $('#btnSwitchReadOnly').bind('click', onSwitchReadOnlyMode);
  collapseMenuSections();
}

function expandMenuSection(){
  /*
   * Expand a menu section.
   */
  var parent = $(this).parent();
  parent.closest('.bibEditMenuSection').find('.bibEditMenuMore').show();

  $(this).replaceWith(img('/img/bullet_toggle_minus.png', '',
			  'bibEditImgCompressMenuSection'));
  parent.find('.bibEditImgCompressMenuSection').bind('click',
						     compressMenuSection);
}

function compressMenuSection(){
  /*
   * Compress a menu section.
   */
  var parent = $(this).parent();
  parent.closest('.bibEditMenuSection').find('.bibEditMenuMore').hide();

  $(this).replaceWith(img('/img/bullet_toggle_plus.png', '',
			  'bibEditImgExpandMenuSection'));
  parent.find('.bibEditImgExpandMenuSection').bind('click', expandMenuSection);
}

function activateRecordMenu(){
  /*
   * Activate menu record controls.
   */
  $('#imgCloneRecord').bind('click', onCloneRecordClick).removeClass(
    'bibEditImgCtrlDisabled').addClass('bibEditImgCtrlEnabled');
  $('#btnCancel').removeAttr('disabled');
  $('#btnDeleteRecord').removeAttr('disabled');
  $('#btnAddField').removeAttr('disabled');
}

function deactivateRecordMenu(){
  /*
   * Deactivate menu record controls.
   */
  $('#imgCloneRecord').unbind('click').removeClass(
    'bibEditImgCtrlEnabled').addClass('bibEditImgCtrlDisabled');
  $('#btnSubmit').attr('disabled', 'disabled');
  $('#btnSubmit').css('background-color', '');
  $('#btnCancel').attr('disabled', 'disabled');
  $('#btnDeleteRecord').attr('disabled', 'disabled');
  $('#btnMARCTags').attr('disabled', 'disabled');
  $('#btnHumanTags').attr('disabled', 'disabled');
  $('#btnAddField').attr('disabled', 'disabled');
  $('#btnDeleteSelected').attr('disabled', 'disabled');
}

function disableRecordBrowser(){
  /*
   * Disable and hide the menu record browser.
   */
  if ($('#rowRecordBrowser').css('display') != 'none'){
    $('#btnNext').unbind('click').attr('disabled', 'disabled');
    $('#btnPrev').unbind('click').attr('disabled', 'disabled');
    $('#rowRecordBrowser').hide();
  }
}

function onSearchClick(event){
  /*
   * Handle 'Search' button (search for records).
   */
  updateStatus('updating');
  var searchPattern = $('#txtSearchPattern').val();
  var searchType = $('#sctSearchType').val();
  if (searchType == 'recID'){
    // Record ID - do some basic validation.
    var searchPatternParts = searchPattern.split(".");
    var recID = parseInt(searchPatternParts[0]);
    var recRev = searchPatternParts[1];

    if (gRecID == recID && recRev == gRecRev){
      // We are already editing this record.
      updateStatus('ready');
      return;
    }
    if (gRecordDirty && gReadOnlyMode == false){
      // Warn of unsubmitted changes.
      if (!displayAlert('confirmLeavingChangedRecord')){
	updateStatus('ready');
	return;
      }
    }
    else if (gRecID && gReadOnlyMode == false)
      // If the record is unchanged, delete the cache.
      createReq({recID: gRecID, requestType: 'deleteRecordCache'});

    gNavigatingRecordSet = false;
    if (isNaN(recID)){
      // Invalid record ID.
      changeAndSerializeHash({state: 'edit', recid: searchPattern});
      cleanUp(true, null, null, true);
      updateStatus('error', gRESULT_CODES[102]);
      $('.headline').text('Record Editor: Record #' + searchPattern);
      updateToolbar(false);
      displayMessage(102);
    }
    else{
      // Get the record.
      if (recRev == undefined){
        $('#txtSearchPattern').val(recID);
        getRecord(recID);
      } else {
        recRev = recRev.replace(/\s+$/, '');
        $('#txtSearchPattern').val(recID + "." + recRev);
        getRecord(recID, recRev);
      }
    }
  }
  else if (searchPattern.replace(/\s*/g, '')){
    // Custom search.
    if (gRecordDirty){
      // Warn of unsubmitted changes.
      if (!displayAlert('confirmLeavingChangedRecord')){
	updateStatus('ready');
	return;
      }
    }
    else if (gRecID)
      // If the record is unchanged, delete the cache.
      createReq({recID: gRecID, requestType: 'deleteRecordCache'});
    gNavigatingRecordSet = false;
    createReq({requestType: 'searchForRecord', searchType: searchType,
      searchPattern: searchPattern}, onSearchForRecordSuccess);
  }
}

function onSearchForRecordSuccess(json){
  /*
   * Handle successfull 'searchForRecord' requests (custom search).
   */
  gResultSet = json['resultSet'];
  if (gResultSet.length == 0){
    // Search yielded no results.
    changeAndSerializeHash({state: 'edit'});
    cleanUp(true, null, null, true, true);
    updateStatus('report', gRESULT_CODES[json['resultCode']]);
    displayMessage(-1);
  }
  else{
    if (gResultSet.length > 1){
      // Multiple results. Show record browser.
      gNavigatingRecordSet = true;
      var recordCount = gResultSet.length;
      $('#cellRecordNo').text(1 + ' / ' + recordCount);
      $('#btnPrev').attr('disabled', 'disabled');
      $('#btnNext').bind('click', onNextRecordClick).removeAttr('disabled');
      $('#rowRecordBrowser').show();
    }
    gResultSetIndex = 0;
    getRecord(gResultSet[0]);
  }
}

function onNextRecordClick(){
  /*
   * Handle click on the 'Next' button in the record browser.
   */
  updateStatus('updating');
  if (gRecordDirty){
    if (!displayAlert('confirmLeavingChangedRecord')){
      updateStatus('ready');
      return;
    }
  }
  else
    // If the record is unchanged, erase the cache.
    createReq({recID: gRecID, requestType: 'deleteRecordCache'});
  var recordCount = gResultSet.length;
  var prevIndex = gResultSetIndex++;
  var currentIndex = prevIndex + 1;
  if (currentIndex == recordCount-1)
    $(this).unbind('click').attr('disabled', 'disabled');
  if (prevIndex == 0)
    $('#btnPrev').bind('click', onPrevRecordClick).removeAttr('disabled');
  $('#cellRecordNo').text((currentIndex+1) + ' / ' + recordCount);
  getRecord(gResultSet[currentIndex]);
}

function onPrevRecordClick(){
  /*
   * Handle click on the 'Previous' button in the record browser.
   */
  updateStatus('updating');
  if (gRecordDirty){
    if (!displayAlert('confirmLeavingChangedRecord')){
      updateStatus('ready');
      return;
    }
  }
  else
    // If the record is unchanged, erase the cache.
    createReq({recID: gRecID, requestType: 'deleteRecordCache'});
  var recordCount = gResultSet.length;
  var prevIndex = gResultSetIndex--;
  var currentIndex = prevIndex - 1;
  if (currentIndex == 0)
    $(this).unbind('click').attr('disabled', 'disabled');
  if (prevIndex == recordCount-1)
    $('#btnNext').bind('click', onNextRecordClick).removeAttr('disabled');
  $('#cellRecordNo').text((currentIndex+1) + ' / ' + recordCount);
  getRecord(gResultSet[currentIndex]);
}

function onGetTicketsSuccess(json){
/*
 * Handle successfull 'getTickets' requests.
 */
  var tickets = json['tickets'];
  if (json['resultCode'] == 31 && json['tickets'] && gRecID){
    $('#tickets').html(tickets);
    $('#lnkNewTicket').bind('click', function(event){
      setTimeout('createReq({recID: gRecID, requestType: "getTickets"},' +
		 'onGetTicketsSuccess)', gTICKET_REFRESH_DELAY);
    });
  }
}

function updateStatus(statusType, reporttext){
  /*
   * Update status (in the bottom of the menu).
   */
  var image, text;
	gCurrentStatus = statusType;
  switch (statusType){
    case 'ready':
      image = img('/img/circle_green.png');
      text = 'Ready';
      break;
    case 'updating':
      image = img('/img/indicator.gif');
      text = 'Updating...';
      break;
    // Generic report. Resets to 'Ready' after timeout.
    case 'report':
      image = img('/img/circle_green.png');
      text = reporttext;
      clearTimeout(updateStatus.statusResetTimerID);
      updateStatus.statusResetTimerID = setTimeout('updateStatus("ready")',
				  gSTATUS_INFO_TIME);
      break;
    case 'error':
      image = img('/img/circle_red.png');
      text = reporttext;
      clearTimeout(updateStatus.statusResetTimerID);
      updateStatus.statusResetTimerID = setTimeout('updateStatus("ready")',
				  gSTATUS_ERROR_TIME);
      break;
    default:
      image = '';
      text = '';
      break;
  }
  $('#cellIndicator').html(image);
  $('#cellStatus').html(text);
}

function collapseMenuSections() {
    $('#ImgHistoryMenu').trigger('click');
    $('#ImgViewMenu').trigger('click');
    $('#ImgRecordMenu').trigger('click');
}<|endoftext|>


<commit_before>'use strict';

/* App Module */

var phonecatApp = angular.module('phonecatApp', [
  'ngRoute',
  'phonecatAnimations',

  'phonecatControllers',
  'phonecatFilters',
  'phonecatServices'
]);

phonecatApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/phones', {
        templateUrl: 'partials/phone-list.html',
        controller: 'PhoneListCtrl'
      }).
      when('/phones/:phoneId', {
        templateUrl: 'partials/phone-detail.html',
        controller: 'PhoneDetailCtrl'
      }).
      when('/modifier/:phoneId', {
          templateUrl:'partials/modifier.html',
          controller: 'PhoneDetailCtrl'
      }).
      otherwise({
        redirectTo: '/phones'
      });

  }]);
<commit_msg>testcommit<commit_after>'use strict';

/* App Module test*/

var phonecatApp = angular.module('phonecatApp', [
  'ngRoute',
  'phonecatAnimations',

  'phonecatControllers',
  'phonecatFilters',
  'phonecatServices'
]);

phonecatApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/phones', {
        templateUrl: 'partials/phone-list.html',
        controller: 'PhoneListCtrl'
      }).
      when('/phones/:phoneId', {
        templateUrl: 'partials/phone-detail.html',
        controller: 'PhoneDetailCtrl'
      }).
      when('/modifier/:phoneId', {
          templateUrl:'partials/modifier.html',
          controller: 'PhoneDetailCtrl'
      }).
      otherwise({
        redirectTo: '/phones'
      });

  }]);
<|endoftext|>


<commit_before>'use strict';

var adopteitorApp = angular.module('adopteitorApp', ['ui.router', 'ngResource', 'ui.bootstrap', 'config']);

adopteitorApp.config(function($stateProvider, $urlRouterProvider) {

    $stateProvider

        .state('home', {
            url: '/home',
            templateUrl: 'views/home.html'
        })
        .state('mision', {
            url: '/mision',
            templateUrl: 'views/mision.html'
        })
        .state('finales-felices', {
            controller: 'finales-felices',
            url: '/finales-felices',
            templateUrl: 'views/finales-felices.html'
        })
        .state('shop', {
            url: '/shop',
            templateUrl: 'views/shop.html'
        })
        .state('contacto', {
            url: '/contacto',
            controller: "contacto",
            templateUrl: 'views/contacto.html'
        })
        .state('donaciones', {
            url: '/donaciones',
            templateUrl: 'views/donaciones.html'
        })
        .state('perfilAnimal', {
            url: '/perfilAnimal/:id',
            controller: 'animalByID',
            templateUrl: 'views/perfilAnimal.html'
        });

        $urlRouterProvider.otherwise('/home');

});
<commit_msg>Added en-adopcion and transitos pages<commit_after>'use strict';

var adopteitorApp = angular.module('adopteitorApp', ['ui.router', 'ngResource', 'ui.bootstrap', 'config', 'angularUtils.directives.dirPagination']);

adopteitorApp.config(function($stateProvider, $urlRouterProvider) {

    $stateProvider

        .state('home', {
            url: '/home',
            templateUrl: 'views/home.html'
        })
        .state('en-adopcion', {
            url: '/en-adopcion',
            templateUrl: 'views/en-adopcion.html'
        })
        .state('mision', {
            url: '/mision',
            templateUrl: 'views/mision.html'
        })
        .state('transitos', {
            url: '/transitos',
            templateUrl: 'views/transitos.html'
        })
        .state('finales-felices', {
            controller: 'finales-felices',
            url: '/finales-felices',
            templateUrl: 'views/finales-felices.html'
        })
        .state('shop', {
            url: '/shop',
            templateUrl: 'views/shop.html'
        })
        .state('contacto', {
            url: '/contacto',
            controller: "contacto",
            templateUrl: 'views/contacto.html'
        })
        .state('donaciones', {
            url: '/donaciones',
            templateUrl: 'views/donaciones.html'
        })
        .state('perfilAnimal', {
            url: '/perfilAnimal/:id',
            controller: 'animalByID',
            templateUrl: 'views/perfilAnimal.html'
        });

        $urlRouterProvider.otherwise('/home');

});
<|endoftext|>


<commit_before>/**
 * tiny
 * https://github.com/iMumuMua/tiny
 */

(function () {

  'use strict';

  /**
   * Tiny constructor
   * @return {Object}
   */
  var Tiny = function () {
    this._kind = 'init';
    this._flowTasks = [];
    this._parallelTasks = [];
    this._isDefaultErrorHandler = true;
    this._errorHandler = function (err) {
      console.log(err.stack || err);
    };
  };

  Tiny.prototype._createCell = function (args) {
    var fn, fnArgs, task, kind;

    var setKind = function (fn) {
      if (isPromise(fn)) {
        kind = 'promise';
      }
      else if (isFunction(fn)) {
        kind = 'function';
      }
      else {
        throw new Error('The first args must be a function or promise.');
      }
    };

    switch (args.length) {
      case 0:
        return;
      case 1:
        kind = 'single';
        task = args[0];
        break;
      case 2:
        fn = args[0];
        setKind(fn);
        task = args[1];
        break;
      default:
        fn = args[0];
        setKind(fn);
        fnArgs = [];
        for (var i = 1, argsLen = args.length; i < argsLen - 1; i++) {
          fnArgs.push(args[i]);
        }
        task = args[args.length - 1];
    }

    return {
      kind: kind,
      fn: fn,
      fnArgs: fnArgs,
      task: task
    };

  };

  Tiny.prototype.go = function () {
    if (this._kind === 'init') {
      this._kind = 'go';
    }
    if (this._kind !== 'init' && this._kind !== 'go') {
      throw new Error('Should not use method go in unflow control');
    }

    var cell = this._createCell(arguments);
    this._flowTasks.push(cell);
    return this;
  };

  Tiny.prototype.parallel = function () {
    if (this._kind === 'init') {
      this._kind = 'parallel';
    }
    if (this._kind !== 'init' && this._kind !== 'parallel') {
      throw new Error('Should not use method parallel in unparallel control');
    }

    var cell = this._createCell(arguments);
    this._parallelTasks.push(cell);
    return this;
  };

  /**
   * Run a task
   * @param {Object} task a cell task
   * @param {Array} args the task fn arguments
   * @param {Function} callback callback when the task has finished, the callback looks like function(err, result) {}, the result is value that the task return.
   */
  Tiny.prototype._runTask = function (task, callback) {
    try {
      var result;
      switch (task.kind) {
        case 'single':
          result = task.task();
          callback(null, result);
          break;
        case 'promise':
          task.fn.then(function () {
            try {
              result = task.task.apply(null, arguments);
              callback(null, result);
            }
            catch (e) {
              callback(e);
            }
          }, callback);
          break;
        case 'function':
          var fnCallback = function () {
            try {
              var err = arguments[0];
              if (err) {
                callback(err);
              }
              else {
                var resData = [];
                for (var i = 1, argumentsLen = arguments.length; i < argumentsLen; i++) {
                  resData.push(arguments[i]);
                }
                result = task.task.apply(null, resData);
                callback(null, result);
              }
            }
            catch (e) {
              callback(e);
            }
          };
          var fnArgs = (task.fnArgs || []).concat(fnCallback);
          task.fn.apply(null, fnArgs);
          break;
        default:
          callback(new Error('Unexpected kind of Tiny cell.'));
      }
    }
    catch (e) {
      callback(e);
    }
  };

  Tiny.prototype._runFlowTask = function (index) {
    try {
      var self = this;
      var task = self._flowTasks[index];
      if (!task) {
        if (self._finishCallback) {
          self._finishCallback();
        }
        return;
      }

      var next = function (err, result) {
        try {
          if (err) {
            self._errorHandler(err);
            return;
          }
          if (result instanceof Tiny) {
            if (result._isDefaultErrorHandler) {
              result.onError(self._errorHandler);
            }
            result.run(function () {
              self._runFlowTask(index + 1);
            });
          }
          else if (result === false) {
            if (self._finishCallback) {
              self._finishCallback();
            }
          }
          else {
            self._runFlowTask(index + 1);
          }
        }
        catch (e) {
          self._errorHandler(e);
        }
      };

      self._runTask(task, next);

    }
    catch (e) {
      self._errorHandler(e);
    }

  };

  Tiny.prototype._runParallelTasks = function () {
    try {
      var self = this;
      var finishCount = 0;
      var tasksLen = self._parallelTasks.length;

      var toFinish = function () {
        try {
          finishCount++;
          if (finishCount === tasksLen) {
            if (self._finishCallback) {
              self._finishCallback();
            }
          }
        }
        catch (e) {
          self._errorHandler(e);
        }
      };

      var runNestedTiny = function (result) {
        if (result instanceof Tiny) {
          if (result._isDefaultErrorHandler) {
            result.onError(self._errorHandler);
          }
          result.run(function () {
            toFinish();
          });
        }
        else {
          toFinish();
        }
      };

      self._parallelTasks.forEach(function (task) {
        self._runTask(task, function (err, result) {
          if (err) {
            self._errorHandler(err);
          }
          else {
            runNestedTiny(result);
          }
        });
      });
    }
    catch (e) {
      self._errorHandler(e);
    }
  };

  Tiny.prototype.onError = function (errCallback) {
    this._errorHandler = errCallback;
    this._isDefaultErrorHandler = false;
    return this;
  };

  Tiny.prototype.run = function (finishCallback) {
    if (finishCallback) {
      this._finishCallback = finishCallback;
    }
    switch (this._kind) {
      case 'go':
        this._runFlowTask(0);
        break;
      case 'parallel':
        this._runParallelTasks();
        break;
      default:
        throw new Error('Unexpected kind of Tiny');
    }
  };

  /**
   * Helper functions
   */

  /**
   * isPromise - Determine whether an object is a promise.
   *
   * @param  {Object} obj
   * @return {Boolean}     return true if obj is a promise.
   */
  function isPromise(obj) {
    return typeof obj.then === 'function';
  }

  /**
   * isFunction - Determine whether an object is a function.
   *
   * @param  {Object} obj
   * @return {Boolean}     return true if obj is a function.
   */
  function isFunction(obj) {
    return typeof obj === 'function';
  }

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = Tiny;
  }
  else if (typeof define !== 'undefined' && define.amd) {
    define([], function () {
      return Tiny;
    });
  }
  else {
    this.Tiny = Tiny;
  }

}());
<commit_msg>refactoring<commit_after>/**
 * tiny
 * https://github.com/iMumuMua/tiny
 */

(function () {

  'use strict';

  /**
   * Tiny constructor
   * @return {Object}
   */
  var Tiny = function () {
    this._kind = 'init';
    this._flowTasks = [];
    this._parallelTasks = [];
    this._isDefaultErrorHandler = true;
    this._errorHandler = function (err) {
      console.log(err.stack || err);
    };
  };

  Tiny.prototype._createCell = function (args) {
    var fn, fnArgs, task, kind;

    var setKind = function (fn) {
      if (isPromise(fn)) {
        kind = 'promise';
      }
      else if (isFunction(fn)) {
        kind = 'function';
      }
      else {
        throw new Error('The first args must be a function or promise.');
      }
    };

    switch (args.length) {
      case 0:
        return;
      case 1:
        kind = 'single';
        task = args[0];
        break;
      case 2:
        fn = args[0];
        setKind(fn);
        task = args[1];
        break;
      default:
        fn = args[0];
        setKind(fn);
        fnArgs = [];
        for (var i = 1, argsLen = args.length; i < argsLen - 1; i++) {
          fnArgs.push(args[i]);
        }
        task = args[args.length - 1];
    }

    return {
      kind: kind,
      fn: fn,
      fnArgs: fnArgs,
      task: task
    };

  };

  Tiny.prototype.go = function () {
    if (this._kind === 'init') {
      this._kind = 'go';
    }
    if (this._kind !== 'init' && this._kind !== 'go') {
      throw new Error('Should not use method go in unflow control');
    }

    var cell = this._createCell(arguments);
    this._flowTasks.push(cell);
    return this;
  };

  Tiny.prototype.parallel = function () {
    if (this._kind === 'init') {
      this._kind = 'parallel';
    }
    if (this._kind !== 'init' && this._kind !== 'parallel') {
      throw new Error('Should not use method parallel in unparallel control');
    }

    var cell = this._createCell(arguments);
    this._parallelTasks.push(cell);
    return this;
  };

  /**
   * Run a task
   * @param {Object} task a cell task
   * @param {Array} args the task fn arguments
   * @param {Function} callback callback when the task succeed, the callback looks like function(result) {}, the result is value that the task return.
   */
  Tiny.prototype._runTask = function (task, callback) {
    var self = this;
    var preCallback = function (err, result) {
      if (err) {
        self._errorHandler(err);
      }
      else {
        if (result instanceof Tiny) {
          if (result._isDefaultErrorHandler) {
            result.onError(self._errorHandler);
          }
          result.run(function () {
            callback(result);
          });
        }
        else {
          callback(result);
        }
      }
    };

    try {
      var result;
      switch (task.kind) {
        case 'single':
          result = task.task();
          preCallback(null, result);
          break;
        case 'promise':
          task.fn.then(function () {
            try {
              result = task.task.apply(null, arguments);
              preCallback(null, result);
            }
            catch (e) {
              preCallback(e);
            }
          }, preCallback);
          break;
        case 'function':
          var fnCallback = function () {
            try {
              var err = arguments[0];
              if (err) {
                preCallback(err);
              }
              else {
                var resData = [];
                for (var i = 1, argumentsLen = arguments.length; i < argumentsLen; i++) {
                  resData.push(arguments[i]);
                }
                result = task.task.apply(null, resData);
                preCallback(null, result);
              }
            }
            catch (e) {
              preCallback(e);
            }
          };
          var fnArgs = (task.fnArgs || []).concat(fnCallback);
          task.fn.apply(null, fnArgs);
          break;
        default:
          preCallback(new Error('Unexpected kind of Tiny cell.'));
      }
    }
    catch (e) {
      preCallback(e);
    }
  };

  Tiny.prototype._runFlowTask = function (index) {
    var self = this;
    var task = self._flowTasks[index];
    if (!task) {
      if (self._finishCallback) {
        self._finishCallback();
      }
      return;
    }

    self._runTask(task, function (result) {
      if (result === false) {
        if (self._finishCallback) {
          self._finishCallback();
        }
      }
      else {
        self._runFlowTask(index + 1);
      }
    });

  };

  Tiny.prototype._runFlowTasks = function () {
    this._runFlowTask(0);
  };

  Tiny.prototype._runParallelTasks = function () {
    var self = this;
    var finishCount = 0;
    var tasksLen = self._parallelTasks.length;

    var toFinish = function () {
      try {
        finishCount++;
        if (finishCount === tasksLen) {
          if (self._finishCallback) {
            self._finishCallback();
          }
        }
      }
      catch (e) {
        self._errorHandler(e);
      }
    };

    self._parallelTasks.forEach(function (task) {
      self._runTask(task, function () {
        toFinish();
      });
    });
  };

  Tiny.prototype.onError = function (errCallback) {
    this._errorHandler = errCallback;
    this._isDefaultErrorHandler = false;
    return this;
  };

  Tiny.prototype.run = function (finishCallback) {
    var self = this;
    if (finishCallback) {
      self._finishCallback = function () {
        try {
          finishCallback();
        }
        catch (e) {
          self._errorHandler(e);
        }
      };
    }
    switch (self._kind) {
      case 'go':
        self._runFlowTasks();
        break;
      case 'parallel':
        self._runParallelTasks();
        break;
      default:
        throw new Error('Unexpected kind of Tiny');
    }
  };

  /**
   * Helper functions
   */

  /**
   * isPromise - Determine whether an object is a promise.
   *
   * @param  {Object} obj
   * @return {Boolean}     return true if obj is a promise.
   */
  function isPromise(obj) {
    return typeof obj.then === 'function';
  }

  /**
   * isFunction - Determine whether an object is a function.
   *
   * @param  {Object} obj
   * @return {Boolean}     return true if obj is a function.
   */
  function isFunction(obj) {
    return typeof obj === 'function';
  }

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = Tiny;
  }
  else if (typeof define !== 'undefined' && define.amd) {
    define([], function () {
      return Tiny;
    });
  }
  else {
    this.Tiny = Tiny;
  }

}());
<|endoftext|>


<commit_before>import { Template } from 'meteor/templating';

import { Tasks } from '../api/tasks.js';

import './body.html';

Template.body.helpers({
  tasks() {
    return Tasks.find({});
  },
});

Template.body.events({
  'submit .new-task'(event) {
    event.preventDefault();

    // get form text
    const target = event.target;
    const text = target.text.value;

    // Insert task
    // insecure -- will be fixed later
    Tasks.insert({
      text,
      createdAt: new Date(),
    });

    // clear form text
    target.text.value = '';
  },
});
<commit_msg>add sort to tasks; most recent first<commit_after>import { Template } from 'meteor/templating';

import { Tasks } from '../api/tasks.js';

import './body.html';

Template.body.helpers({
  tasks() {
    return Tasks.find({}, { sort: { createdAt: -1 } });
  },
});

Template.body.events({
  'submit .new-task'(event) {
    event.preventDefault();

    // get form text
    const target = event.target;
    const text = target.text.value;

    // Insert task
    // insecure -- will be fixed later
    Tasks.insert({
      text,
      createdAt: new Date(),
    });

    // clear form text
    target.text.value = '';
  },
});
<|endoftext|>


<commit_before>/** RESULT PAGE PART**/
function showResultsPage(data) {
    ResultResponse(data.data);
    $(".travel-container").fadeIn();

    // var addressFrom = $('#search-input-from').val();
    // var  addressTo = $('#search-input-to').val();
    // GetPosition(addressFrom,addressTo,'WALKING');
    // traitementAjax();
    // initMap();
    // var center = map.getCenter();
    // google.maps.event.trigger(map, "resize");
    // map.setCenter(center);

    /** Go to selected result **/

    $( "#walk" ).on( "click", function() {
        hideChoice();
        displayMap('WALKING');

  ;

    });
    $( "#bike" ).on( "click", function() {
        hideChoice();
        displayMap('BICYCLING');
    });
    $( "#car" ).on( "click", function() {
        hideChoice();
        displayMap('DRIVING');
    });

}

function displayMap(travelMode){
    var addressFrom = $('#search-input-from').val();
    var  addressTo = $('#search-input-to').val();
    GetPosition(addressFrom,addressTo,travelMode);
    initMap();
}

// hide other choice
function hideChoice(){
    $('.travel-container').fadeOut();
    $('.result-container').fadeIn();
}

// show/hide title
function showHideTitle(){
    if ($('#main-title').is(":visible")){
        $('#main-title').hide();
    }else{
        $('#main-title').show();
    }
}

<commit_msg>loader<commit_after>/** RESULT PAGE PART**/
function showResultsPage(data) {
    ResultResponse(data.data);
    $('#loader').fadeOut();
    $(".travel-container").fadeIn();

    // var addressFrom = $('#search-input-from').val();
    // var  addressTo = $('#search-input-to').val();
    // GetPosition(addressFrom,addressTo,'WALKING');
    // traitementAjax();
    // initMap();
    // var center = map.getCenter();
    // google.maps.event.trigger(map, "resize");
    // map.setCenter(center);

    /** Go to selected result **/

    $( "#walk" ).on( "click", function() {
        hideChoice();
        displayMap('WALKING');

  ;

    });
    $( "#bike" ).on( "click", function() {
        hideChoice();
        displayMap('BICYCLING');
    });
    $( "#car" ).on( "click", function() {
        hideChoice();
        displayMap('DRIVING');
    });

}

function displayMap(travelMode){
    var addressFrom = $('#search-input-from').val();
    var  addressTo = $('#search-input-to').val();
    GetPosition(addressFrom,addressTo,travelMode);
    initMap();
}

// hide other choice
function hideChoice(){
    $('.travel-container').fadeOut();
    $('.result-container').fadeIn();
}

// show/hide title
function showHideTitle(){
    if ($('#main-title').is(":visible")){
        $('#main-title').hide();
    }else{
        $('#main-title').show();
    }
}

<|endoftext|>


<commit_before>function isNumeric(n) {
    // thanks http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function prepareTemplates(templates){
    //take an array of template names, and load their inner html into a simmilarly keyed object.

    var i, guts = {};

    for(i=0; i<templates.length; i++){
        guts[templates[i]] = document.getElementById(templates[i]).import.getElementById(templates[i]).innerHTML
    }

    return guts
}

function deleteNode(id){
    //delete a dom node with id
    //thanks https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild

    var node = document.getElementById(id);
    if (node.parentNode) {
        node.parentNode.removeChild(node);
    }
}

function prettyNumber(val){
    //turn a number into a string with a sensible unit

    var pretty

    if(val>1000000){
        pretty = (val / 1000000).toFixed(3) + ' M'
    } else if(val>1000){
        pretty = (val / 1000000).toFixed(3) + ' k'
    }

    return pretty;
}

function selected(selectID, fetchText){
    //returns the value selected from a select element, or the inner html of the option if fetchText is set

    var select = document.getElementById(selectID),
        value = select.options[select.selectedIndex].value;

        if(fetchText)
            value = select.options[select.selectedIndex].innerHTML;

    return value;
}

function generateTickLabel(min, max, nTicks, n){
    //function to make a reasonable decision on how many decimal places to show, whether to to use
    //sci. notation on an axis tick mark, where <min> and <max> are the axis minimum and maximum,
    //<nTicks> is the number of tickmarks on the axis, and we are returning the label for the <n>th
    //tick mark

    var range = max - min,
        smallestPrecision = range / (nTicks-1),
        tickValue = min + (max-min)/(nTicks-1)*n;

    //tickmark needs to be labeled to enough precision to show the difference between subsequent ticks:
    smallestPrecision = Math.floor(Math.log(smallestPrecision) / Math.log(10));

    if(smallestPrecision < 0){
        return tickValue.toFixed(-smallestPrecision)
    }

    tickValue = Math.floor(tickValue/Math.pow(10, smallestPrecision)) * Math.pow(10, smallestPrecision);

    return tickValue+'';

}

Math.log10 = function(x){
    //base 10 log

    return Math.log(x) / Math.log(10);
}

function getPosition(element) {
    //modified from http://www.kirupa.com/html5/get_element_position_using_javascript.htm

    var xPosition = 0;
    var yPosition = 0;

    while(element) {
        xPosition += (element.offsetLeft + element.clientLeft);
        yPosition += (element.offsetTop + element.clientTop);
        element = element.offsetParent;
    }
    return { x: xPosition, y: yPosition };
}

function isNumeric(n) {
    // is n a number?

    return !Number.isNaN(parseFloat(n)) && Number.isFinite(n);
}

function fetchScript(url, id){
    // simple script hack fetch

    var script = document.createElement('script');

    script.setAttribute('src', url);
    script.onload = function(){
            deleteNode(id);
    }
    script.id = id;
    document.head.appendChild(script);

}

function pokeURL(url){
    // poke the requested URL, don't care about the response

    var req = new XMLHttpRequest();

    req.open('GET', url);
    // Make the request
    req.send();
}

function getParameterByName(name) {
    // get a parameter out of the query string
    // thanks http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function reloadPage(){
    document.location.reload();
}

///////////////////////////////
// daq requests & unpacking
///////////////////////////////

function fetchDAQ(payload){
    //parse the contents of the ODB DAQ directory.

    var i, key;

    dataStore.ODB.DAQ = payload;

    //extract hosts list
    dataStore.hosts = [];

    //master
    //dataStore.hosts.push(dataStore.ODB.DAQ.hosts.master);
    for(key in dataStore.ODB.DAQ.hosts){
        if(dataStore.ODB.DAQ.hosts[key].host){
            //collectors
            //dataStore.hosts.push(dataStore.ODB.DAQ.hosts[key].host);
            //digitizers
            for(i=0; i<dataStore.ODB.DAQ.hosts[key].digitizers.length; i++){
                if(dataStore.ODB.DAQ.hosts[key].digitizers[i])
                    dataStore.hosts.push(dataStore.ODB.DAQ.hosts[key].digitizers[i])
            }
        }
    }
}

function determineADCrequests(){
    // generate the URLs for rate and threshold requests, park them in the dataStore, and kick the heartbeat to start fetching.

    var i;
    //insert url queries into heartbeat polls:
    for(i=0; i<dataStore.hosts.length; i++){
        dataStore.heartbeat.URLqueries.push(['http://' + dataStore.hosts[i] + '/report', 'arraybuffer', unpackDAQdv])
    }

    //bump the heartbeat
    heartbeat();

}

function unpackDAQ(i, dv){
    //extract the ith block out of a dataview object constructed from the arraybuffer returned by a DAQ element:
    var blockLength = 14,
        thresholdPos = 10,
        trigAcptPos = 2,
        trigReqPos = 6,
        MSCPos = 0,
        unpacked = {};

    unpacked.threshold  = dv.getUint32(i*blockLength + thresholdPos, true);
    unpacked.trigAcpt   = dv.getFloat32(i*blockLength + trigAcptPos, true);
    unpacked.trigReq    = dv.getFloat32(i*blockLength + trigReqPos, true);
    unpacked.MSC        = dv.getUint16(i*blockLength + MSCPos, true);

    return unpacked;
}

function parseMSCindex(MSC){
    //decode an MSC index into [master channel, collector channel, digitizer channel]

    var masterChannel, collectorChannel, digitizerChannel;

    masterChannel = (MSC & 0xF000) >> 12;
    collectorChannel = (MSC & 0xF00) >> 8;
    digitizerChannel = (MSC & 0xFF);

    return [masterChannel, collectorChannel, digitizerChannel]
}

function findHVcrate(channel){
    //given an HV cell name, return the index of the HV crate it is powered by

    var i=0,
        match = false,
        crateID = -1;

    while(!match && dataStore.ODB.Equipment['HV-'+i]){
        if(dataStore.ODB.Equipment['HV-'+i].Settings.Names.indexOf(channel) != -1){
            match = true;
            crateID = i;
        }
        else
            i++;
    }

    if(match)
        return crateID;
    else
        return -1;
}

////////////////////////////
// tooltip management
////////////////////////////

function hideTooltip(){

    var tooltip = document.getElementById('tooltip');
    tooltip.setAttribute('style', 'display:none;');
}

function moveTooltip(event){

    var tooltip = document.getElementById('tooltip'),
        offset = getPosition(tooltip.parentElement),
        gap = 20;

    tooltip.setAttribute('style', 'display:inline-block; z-index:10; position: absolute; left:' + (event.pageX - offset.x + gap) + '; top:' + (event.pageY - offset.y + gap)  + ';');
}

///////////////////////////////
// cell click management
///////////////////////////////

function highlightCell(cell){
    // draw a big red border around the last cell clicked, and remove the previous big red border if it exists.

    if(dataStore.lastCellClick){
        dataStore.lastCellClick.setAttr('stroke', dataStore.frameColor);
        dataStore.lastCellClick.setAttr('strokeWidth', dataStore.frameLineWidth);
    }
    dataStore.lastCellClick = cell;
    cell.setAttr('stroke', '#FF0000');
    cell.setAttr('strokeWidth', 6);
    cell.moveToTop();

    repaint();
}

//////////////////////////////////
// prototype modifications
//////////////////////////////////

Array.prototype.unique = function(){
    // thanks http://jszen.com/best-way-to-get-unique-values-of-an-array-in-javascript.7.html
    var n = {},r=[];
    for(var i = 0; i < this.length; i++)
    {
        if (!n[this[i]])
        {
            n[this[i]] = true;
            r.push(this[i]);
        }
    }
    return r;
}<commit_msg>more sensible tickmarks on color scales<commit_after>function isNumeric(n) {
    // thanks http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function prepareTemplates(templates){
    //take an array of template names, and load their inner html into a simmilarly keyed object.

    var i, guts = {};

    for(i=0; i<templates.length; i++){
        guts[templates[i]] = document.getElementById(templates[i]).import.getElementById(templates[i]).innerHTML
    }

    return guts
}

function deleteNode(id){
    //delete a dom node with id
    //thanks https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild

    var node = document.getElementById(id);
    if (node.parentNode) {
        node.parentNode.removeChild(node);
    }
}

function prettyNumber(val){
    //turn a number into a string with a sensible unit

    var pretty

    if(val>1000000){
        pretty = (val / 1000000).toFixed(3) + ' M'
    } else if(val>1000){
        pretty = (val / 1000000).toFixed(3) + ' k'
    }

    return pretty;
}

function selected(selectID, fetchText){
    //returns the value selected from a select element, or the inner html of the option if fetchText is set

    var select = document.getElementById(selectID),
        value = select.options[select.selectedIndex].value;

        if(fetchText)
            value = select.options[select.selectedIndex].innerHTML;

    return value;
}

function generateTickLabel(min, max, nTicks, n){
    //function to make a reasonable decision on how many decimal places to show, whether to to use
    //sci. notation on an axis tick mark, where <min> and <max> are the axis minimum and maximum,
    //<nTicks> is the number of tickmarks on the axis, and we are returning the label for the <n>th
    //tick mark

    var range = max - min,
        smallestPrecision = range / (nTicks-1),
        tickValue = min + (max-min)/(nTicks-1)*n;

    //tickmark needs to be labeled to enough precision to show the difference between subsequent ticks:
    smallestPrecision = Math.min(0, Math.floor(Math.log(smallestPrecision) / Math.log(10)));

    if(smallestPrecision < 0){
        return tickValue.toFixed(-smallestPrecision)
    }

    tickValue = Math.floor(tickValue/Math.pow(10, smallestPrecision)) * Math.pow(10, smallestPrecision);

    return tickValue+'';

}

Math.log10 = function(x){
    //base 10 log

    return Math.log(x) / Math.log(10);
}

function getPosition(element) {
    //modified from http://www.kirupa.com/html5/get_element_position_using_javascript.htm

    var xPosition = 0;
    var yPosition = 0;

    while(element) {
        xPosition += (element.offsetLeft + element.clientLeft);
        yPosition += (element.offsetTop + element.clientTop);
        element = element.offsetParent;
    }
    return { x: xPosition, y: yPosition };
}

function isNumeric(n) {
    // is n a number?

    return !Number.isNaN(parseFloat(n)) && Number.isFinite(n);
}

function fetchScript(url, id){
    // simple script hack fetch

    var script = document.createElement('script');

    script.setAttribute('src', url);
    script.onload = function(){
            deleteNode(id);
    }
    script.id = id;
    document.head.appendChild(script);

}

function pokeURL(url){
    // poke the requested URL, don't care about the response

    var req = new XMLHttpRequest();

    req.open('GET', url);
    // Make the request
    req.send();
}

function getParameterByName(name) {
    // get a parameter out of the query string
    // thanks http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#901144
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function reloadPage(){
    document.location.reload();
}

///////////////////////////////
// daq requests & unpacking
///////////////////////////////

function fetchDAQ(payload){
    //parse the contents of the ODB DAQ directory.

    var i, key;

    dataStore.ODB.DAQ = payload;

    //extract hosts list
    dataStore.hosts = [];

    //master
    //dataStore.hosts.push(dataStore.ODB.DAQ.hosts.master);
    for(key in dataStore.ODB.DAQ.hosts){
        if(dataStore.ODB.DAQ.hosts[key].host){
            //collectors
            //dataStore.hosts.push(dataStore.ODB.DAQ.hosts[key].host);
            //digitizers
            for(i=0; i<dataStore.ODB.DAQ.hosts[key].digitizers.length; i++){
                if(dataStore.ODB.DAQ.hosts[key].digitizers[i])
                    dataStore.hosts.push(dataStore.ODB.DAQ.hosts[key].digitizers[i])
            }
        }
    }
}

function determineADCrequests(){
    // generate the URLs for rate and threshold requests, park them in the dataStore, and kick the heartbeat to start fetching.

    var i;
    //insert url queries into heartbeat polls:
    for(i=0; i<dataStore.hosts.length; i++){
        dataStore.heartbeat.URLqueries.push(['http://' + dataStore.hosts[i] + '/report', 'arraybuffer', unpackDAQdv])
    }

    //bump the heartbeat
    heartbeat();

}

function unpackDAQ(i, dv){
    //extract the ith block out of a dataview object constructed from the arraybuffer returned by a DAQ element:
    var blockLength = 14,
        thresholdPos = 10,
        trigAcptPos = 2,
        trigReqPos = 6,
        MSCPos = 0,
        unpacked = {};

    unpacked.threshold  = dv.getUint32(i*blockLength + thresholdPos, true);
    unpacked.trigAcpt   = dv.getFloat32(i*blockLength + trigAcptPos, true);
    unpacked.trigReq    = dv.getFloat32(i*blockLength + trigReqPos, true);
    unpacked.MSC        = dv.getUint16(i*blockLength + MSCPos, true);

    return unpacked;
}

function parseMSCindex(MSC){
    //decode an MSC index into [master channel, collector channel, digitizer channel]

    var masterChannel, collectorChannel, digitizerChannel;

    masterChannel = (MSC & 0xF000) >> 12;
    collectorChannel = (MSC & 0xF00) >> 8;
    digitizerChannel = (MSC & 0xFF);

    return [masterChannel, collectorChannel, digitizerChannel]
}

function findHVcrate(channel){
    //given an HV cell name, return the index of the HV crate it is powered by

    var i=0,
        match = false,
        crateID = -1;

    while(!match && dataStore.ODB.Equipment['HV-'+i]){
        if(dataStore.ODB.Equipment['HV-'+i].Settings.Names.indexOf(channel) != -1){
            match = true;
            crateID = i;
        }
        else
            i++;
    }

    if(match)
        return crateID;
    else
        return -1;
}

////////////////////////////
// tooltip management
////////////////////////////

function hideTooltip(){

    var tooltip = document.getElementById('tooltip');
    tooltip.setAttribute('style', 'display:none;');
}

function moveTooltip(event){

    var tooltip = document.getElementById('tooltip'),
        offset = getPosition(tooltip.parentElement),
        gap = 20;

    tooltip.setAttribute('style', 'display:inline-block; z-index:10; position: absolute; left:' + (event.pageX - offset.x + gap) + '; top:' + (event.pageY - offset.y + gap)  + ';');
}

///////////////////////////////
// cell click management
///////////////////////////////

function highlightCell(cell){
    // draw a big red border around the last cell clicked, and remove the previous big red border if it exists.

    if(dataStore.lastCellClick){
        dataStore.lastCellClick.setAttr('stroke', dataStore.frameColor);
        dataStore.lastCellClick.setAttr('strokeWidth', dataStore.frameLineWidth);
    }
    dataStore.lastCellClick = cell;
    cell.setAttr('stroke', '#FF0000');
    cell.setAttr('strokeWidth', 6);
    cell.moveToTop();

    repaint();
}

//////////////////////////////////
// prototype modifications
//////////////////////////////////

Array.prototype.unique = function(){
    // thanks http://jszen.com/best-way-to-get-unique-values-of-an-array-in-javascript.7.html
    var n = {},r=[];
    for(var i = 0; i < this.length; i++)
    {
        if (!n[this[i]])
        {
            n[this[i]] = true;
            r.push(this[i]);
        }
    }
    return r;
}<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const fs = require('fs');
const http = require('http');
const os = require('os');
const path = require('path');
const crypto = require('crypto');
const zlib = require('zlib');
const stream = require('stream');
const process = require('process');

const HttpsProxyAgent = require('https-proxy-agent');
const fetch = require('node-fetch');
const ProgressBar = require('progress');
const Proxy = require('proxy-from-env');
// NOTE: Can be dropped in favor of `fs.mkdirSync(path, { recursive: true })` once we stop supporting Node 8.x
const mkdirp = require('mkdirp');

const helper = require('../js/helper');
const pkgInfo = require('../package.json');

const CDN_URL =
  process.env.SENTRYCLI_LOCAL_CDNURL ||
  process.env.npm_config_sentrycli_cdnurl ||
  process.env.SENTRYCLI_CDNURL ||
  'https://downloads.sentry-cdn.com/sentry-cli';

function shouldRenderProgressBar() {
  const silentFlag = process.argv.some(v => v === '--silent');
  const silentConfig = process.env.npm_config_loglevel === 'silent';
  const silentEnv = process.env.SENTRY_NO_PROGRESS_BAR;
  // If any of possible options is set, skip rendering of progress bar
  return !(silentFlag || silentConfig || silentEnv);
}

function getDownloadUrl(platform, arch) {
  const releasesUrl = `${CDN_URL}/${pkgInfo.version}/sentry-cli`;
  let archString = '';
  switch (arch) {
    case 'x64':
      archString = 'x86_64';
      break;
    case 'x86':
      archString = 'i686';
      break;
    default:
      archString = arch;
  }
  switch (platform) {
    case 'darwin':
      return `${releasesUrl}-Darwin-x86_64`;
    case 'win32':
      return `${releasesUrl}-Windows-${archString}.exe`;
    case 'linux':
    case 'freebsd':
      return `${releasesUrl}-Linux-${archString}`;
    default:
      return null;
  }
}

function createProgressBar(name, total) {
  if (process.stdout.isTTY) {
    return new ProgressBar(`fetching ${name} :bar :percent :etas`, {
      complete: '█',
      incomplete: '░',
      width: 20,
      total,
    });
  }

  let pct = null;
  let current = 0;
  return {
    tick: length => {
      current += length;
      const next = Math.round((current / total) * 100);
      if (next > pct) {
        pct = next;
        process.stdout.write(`fetching ${name} ${pct}%\n`);
      }
    },
  };
}

function npmCache() {
  const env = process.env;
  return (
    env.npm_config_cache ||
    env.npm_config_yarn_offline_mirror ||
    (env.APPDATA ? path.join(env.APPDATA, 'npm-cache') : path.join(os.homedir(), '.npm'))
  );
}

function getCachedPath(url) {
  const digest = crypto
    .createHash('md5')
    .update(url)
    .digest('hex')
    .slice(0, 6);

  return path.join(
    npmCache(),
    'sentry-cli',
    `${digest}-${path.basename(url).replace(/[^a-zA-Z0-9.]+/g, '-')}`
  );
}

function getTempFile(cached) {
  return `${cached}.${process.pid}-${Math.random()
    .toString(16)
    .slice(2)}.tmp`;
}

function downloadBinary() {
  const arch = os.arch();
  const platform = os.platform();
  const outputPath = helper.getPath();

  const downloadUrl = getDownloadUrl(platform, arch);
  if (!downloadUrl) {
    return Promise.reject(new Error(`unsupported target ${platform}-${arch}`));
  }

  const cachedPath = getCachedPath(downloadUrl);
  if (fs.existsSync(cachedPath)) {
    fs.copyFileSync(cachedPath, outputPath);
    return Promise.resolve();
  }

  const proxyUrl = Proxy.getProxyForUrl(downloadUrl);
  const agent = proxyUrl ? new HttpsProxyAgent(proxyUrl) : null;

  return fetch(downloadUrl, {
    agent,
    compress: false,
    headers: {
      'accept-encoding': 'gzip, deflate, br',
    },
    redirect: 'follow',
  }).then(response => {
    if (!response.ok) {
      throw new Error(`Received ${response.status}: ${response.statusText}`);
    }

    const contentEncoding = response.headers.get('content-encoding');
    let decompressor;
    if (/\bgzip\b/.test(contentEncoding)) {
      decompressor = zlib.createGunzip();
    } else if (/\bdeflate\b/.test(contentEncoding)) {
      decompressor = zlib.createInflate();
    } else if (/\bbr\b/.test(contentEncoding)) {
      decompressor = zlib.createBrotliDecompress();
    } else {
      decompressor = new stream.PassThrough();
    }
    const name = downloadUrl.match(/.*\/(.*?)$/)[1];
    const total = parseInt(response.headers.get('content-length'), 10);
    const progressBar = createProgressBar(name, total);
    const tempPath = getTempFile(cachedPath);
    mkdirp.sync(path.dirname(tempPath));

    return new Promise((resolve, reject) => {
      response.body
        .on('error', e => reject(e))
        .on('data', chunk => shouldRenderProgressBar() && progressBar.tick(chunk.length))
        .pipe(decompressor)
        .pipe(fs.createWriteStream(tempPath, { mode: '0755' }))
        .on('error', e => reject(e))
        .on('close', () => resolve());
    }).then(() => {
      fs.copyFileSync(tempPath, cachedPath);
      fs.copyFileSync(tempPath, outputPath);
      fs.unlinkSync(tempPath);
    });
  });
}

function checkVersion() {
  return helper.execute(['--version']).then(output => {
    const version = output.replace('sentry-cli ', '').trim();
    const expected = process.env.SENTRYCLI_LOCAL_CDNURL ? 'DEV' : pkgInfo.version;
    if (version !== expected) {
      throw new Error(`Unexpected sentry-cli version "${version}", expected "${expected}"`);
    }
  });
}

if (process.env.SENTRYCLI_LOCAL_CDNURL) {
  // For testing, mock the CDN by spawning a local server
  const server = http.createServer((request, response) => {
    const contents = fs.readFileSync(path.join(__dirname, '../js/__mocks__/sentry-cli'));
    response.writeHead(200, {
      'Content-Type': 'application/octet-stream',
      'Content-Length': String(contents.byteLength),
    });
    response.end(contents);
  });

  server.listen(8999);
  process.on('exit', () => server.close());
}

downloadBinary()
  .then(() => checkVersion())
  .then(() => process.exit(0))
  .catch(e => {
    // eslint-disable-next-line no-console
    console.error(e.toString());
    process.exit(1);
  });
<commit_msg>fix: OS arch detection for IA32 (#824)<commit_after>#!/usr/bin/env node

'use strict';

const fs = require('fs');
const http = require('http');
const os = require('os');
const path = require('path');
const crypto = require('crypto');
const zlib = require('zlib');
const stream = require('stream');
const process = require('process');

const HttpsProxyAgent = require('https-proxy-agent');
const fetch = require('node-fetch');
const ProgressBar = require('progress');
const Proxy = require('proxy-from-env');
// NOTE: Can be dropped in favor of `fs.mkdirSync(path, { recursive: true })` once we stop supporting Node 8.x
const mkdirp = require('mkdirp');

const helper = require('../js/helper');
const pkgInfo = require('../package.json');

const CDN_URL =
  process.env.SENTRYCLI_LOCAL_CDNURL ||
  process.env.npm_config_sentrycli_cdnurl ||
  process.env.SENTRYCLI_CDNURL ||
  'https://downloads.sentry-cdn.com/sentry-cli';

function shouldRenderProgressBar() {
  const silentFlag = process.argv.some(v => v === '--silent');
  const silentConfig = process.env.npm_config_loglevel === 'silent';
  const silentEnv = process.env.SENTRY_NO_PROGRESS_BAR;
  // If any of possible options is set, skip rendering of progress bar
  return !(silentFlag || silentConfig || silentEnv);
}

function getDownloadUrl(platform, arch) {
  const releasesUrl = `${CDN_URL}/${pkgInfo.version}/sentry-cli`;
  let archString = '';
  switch (arch) {
    case 'x64':
      archString = 'x86_64';
      break;
    case 'x86':
    case 'ia32':
      archString = 'i686';
      break;
    default:
      archString = arch;
  }
  switch (platform) {
    case 'darwin':
      return `${releasesUrl}-Darwin-x86_64`;
    case 'win32':
      return `${releasesUrl}-Windows-${archString}.exe`;
    case 'linux':
    case 'freebsd':
      return `${releasesUrl}-Linux-${archString}`;
    default:
      return null;
  }
}

function createProgressBar(name, total) {
  if (process.stdout.isTTY) {
    return new ProgressBar(`fetching ${name} :bar :percent :etas`, {
      complete: '█',
      incomplete: '░',
      width: 20,
      total,
    });
  }

  let pct = null;
  let current = 0;
  return {
    tick: length => {
      current += length;
      const next = Math.round((current / total) * 100);
      if (next > pct) {
        pct = next;
        process.stdout.write(`fetching ${name} ${pct}%\n`);
      }
    },
  };
}

function npmCache() {
  const env = process.env;
  return (
    env.npm_config_cache ||
    env.npm_config_yarn_offline_mirror ||
    (env.APPDATA ? path.join(env.APPDATA, 'npm-cache') : path.join(os.homedir(), '.npm'))
  );
}

function getCachedPath(url) {
  const digest = crypto
    .createHash('md5')
    .update(url)
    .digest('hex')
    .slice(0, 6);

  return path.join(
    npmCache(),
    'sentry-cli',
    `${digest}-${path.basename(url).replace(/[^a-zA-Z0-9.]+/g, '-')}`
  );
}

function getTempFile(cached) {
  return `${cached}.${process.pid}-${Math.random()
    .toString(16)
    .slice(2)}.tmp`;
}

function downloadBinary() {
  const arch = os.arch();
  const platform = os.platform();
  const outputPath = helper.getPath();

  const downloadUrl = getDownloadUrl(platform, arch);
  if (!downloadUrl) {
    return Promise.reject(new Error(`unsupported target ${platform}-${arch}`));
  }

  const cachedPath = getCachedPath(downloadUrl);
  if (fs.existsSync(cachedPath)) {
    fs.copyFileSync(cachedPath, outputPath);
    return Promise.resolve();
  }

  const proxyUrl = Proxy.getProxyForUrl(downloadUrl);
  const agent = proxyUrl ? new HttpsProxyAgent(proxyUrl) : null;

  return fetch(downloadUrl, {
    agent,
    compress: false,
    headers: {
      'accept-encoding': 'gzip, deflate, br',
    },
    redirect: 'follow',
  }).then(response => {
    if (!response.ok) {
      throw new Error(`Received ${response.status}: ${response.statusText}`);
    }

    const contentEncoding = response.headers.get('content-encoding');
    let decompressor;
    if (/\bgzip\b/.test(contentEncoding)) {
      decompressor = zlib.createGunzip();
    } else if (/\bdeflate\b/.test(contentEncoding)) {
      decompressor = zlib.createInflate();
    } else if (/\bbr\b/.test(contentEncoding)) {
      decompressor = zlib.createBrotliDecompress();
    } else {
      decompressor = new stream.PassThrough();
    }
    const name = downloadUrl.match(/.*\/(.*?)$/)[1];
    const total = parseInt(response.headers.get('content-length'), 10);
    const progressBar = createProgressBar(name, total);
    const tempPath = getTempFile(cachedPath);
    mkdirp.sync(path.dirname(tempPath));

    return new Promise((resolve, reject) => {
      response.body
        .on('error', e => reject(e))
        .on('data', chunk => shouldRenderProgressBar() && progressBar.tick(chunk.length))
        .pipe(decompressor)
        .pipe(fs.createWriteStream(tempPath, { mode: '0755' }))
        .on('error', e => reject(e))
        .on('close', () => resolve());
    }).then(() => {
      fs.copyFileSync(tempPath, cachedPath);
      fs.copyFileSync(tempPath, outputPath);
      fs.unlinkSync(tempPath);
    });
  });
}

function checkVersion() {
  return helper.execute(['--version']).then(output => {
    const version = output.replace('sentry-cli ', '').trim();
    const expected = process.env.SENTRYCLI_LOCAL_CDNURL ? 'DEV' : pkgInfo.version;
    if (version !== expected) {
      throw new Error(`Unexpected sentry-cli version "${version}", expected "${expected}"`);
    }
  });
}

if (process.env.SENTRYCLI_LOCAL_CDNURL) {
  // For testing, mock the CDN by spawning a local server
  const server = http.createServer((request, response) => {
    const contents = fs.readFileSync(path.join(__dirname, '../js/__mocks__/sentry-cli'));
    response.writeHead(200, {
      'Content-Type': 'application/octet-stream',
      'Content-Length': String(contents.byteLength),
    });
    response.end(contents);
  });

  server.listen(8999);
  process.on('exit', () => server.close());
}

downloadBinary()
  .then(() => checkVersion())
  .then(() => process.exit(0))
  .catch(e => {
    // eslint-disable-next-line no-console
    console.error(e.toString());
    process.exit(1);
  });
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import purebem from 'purebem';

import { firebase } from 'app/firebase';
import { isString } from 'app/utils';
import { filter } from 'app/lodash';
import { Autocomplete, Button, FormGroup, InputField } from 'app/components';
import { ringsFormReset, ringsUpdate, ringsAutocompleteSelect } from 'app/redux/rings';

const block = purebem.of('rings-form');

const RingsForm = React.createClass({

    propTypes: {
        autocomplete: PropTypes.shape({
            expanded: PropTypes.bool,
            list: PropTypes.array
        }).isRequired,
        form: PropTypes.shape({
            size: PropTypes.string,
            serial: PropTypes.string
        }).isRequired,
        onAutocompleteUpdate: PropTypes.func.isRequired,
        onAutocompleteExpand: PropTypes.func.isRequired,
        onAutocompleteSelect: PropTypes.func.isRequired,
        onInput: PropTypes.func.isRequired,
        onReset: PropTypes.func.isRequired,
        projectId: PropTypes.string.isRequired,
        sizes: PropTypes.array.isRequired
    },

    componentWillMount() {
        const { projectId } = this.props;
        this.ringsRef = firebase.database().ref(`rings/${projectId}`);
    },

    getTrimmedValue(name, value) {
        switch (name) {
            case 'size':
                return value.trim().replace(',', '.');

            case 'serial':
                return value.trim().toUpperCase();
        }
    },

    handleInput(evt) {
        const { name, value } = evt.target;
        const trimmedValue = this.getTrimmedValue(name, value);

        this.props.onInput(name, trimmedValue);

        if (name === 'size') {
            this.handleAutocomplete(value);
        }
    },

    handleAutocomplete(value) {
        const pattern = new RegExp(`^${value}`);
        const matches = filter(this.props.sizes, (o) => {
            return value && pattern.test(o.size);
        });

        this.props.onAutocompleteUpdate(matches);
    },

    handleSubmit(evt) {
        evt.preventDefault();
        const { form } = this.props;

        if (!isString(form.size) || !isString(form.serial)) {
            // display error message…
            return;
        }

        const size = form.size.replace('.', '_');
        this.ringsRef.child(`${size}`).update({ serial: form.serial });
        this.ringsRef.child(`${size}/history/${form.serial}`).set(true);
        this.props.onReset();
    },

    render() {
        const { autocomplete, form } = this.props;

        return (
            <form className={ block() } onSubmit={ this.handleSubmit }>
                <FormGroup
                    label="Ring Size"
                    type="inline">
                    <Autocomplete
                        name="size"
                        expanded={ autocomplete.expanded }
                        onChange={ this.handleInput }
                        onClick={ (value) => this.props.onInput('size', value) }
                        onExpand={ this.props.onAutocompleteExpand }
                        onSelect={ this.props.onAutocompleteSelect }
                        list={ autocomplete.list }
                        value={ form.size } />
                </FormGroup>
                <FormGroup
                    label="Serial No."
                    type="inline">
                    <InputField
                        name="serial"
                        onChange={ this.handleInput }
                        value={ form.serial } />
                </FormGroup>
                <FormGroup
                    label=" "
                    type="inline">
                    <Button
                        style="success"
                        type="submit">Update</Button>
                </FormGroup>
            </form>
        );
    }

});

const mapStateToProps = (state) => {
    return {
        autocomplete: state.rings.autocomplete,
        form: state.rings.form,
        sizes: state.rings.sizes.list
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        onInput: (name, value) => dispatch(ringsUpdate('form', { [name]: value })),
        onReset: () => dispatch(ringsFormReset()),
        onAutocompleteUpdate: (list) => dispatch(ringsUpdate('autocomplete', { list, expanded: !!list.length })),
        onAutocompleteExpand: (expanded) => dispatch(ringsUpdate('autocomplete', { expanded })),
        onAutocompleteSelect: (index) => dispatch(ringsAutocompleteSelect(index, { selected: true }))
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(RingsForm);
<commit_msg>convert ring sizes to decimal number on save<commit_after>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import purebem from 'purebem';

import { firebase } from 'app/firebase';
import { isString } from 'app/utils';
import { filter } from 'app/lodash';
import { Autocomplete, Button, FormGroup, InputField } from 'app/components';
import { ringsFormReset, ringsUpdate, ringsAutocompleteSelect } from 'app/redux/rings';

const block = purebem.of('rings-form');

const RingsForm = React.createClass({

    propTypes: {
        autocomplete: PropTypes.shape({
            expanded: PropTypes.bool,
            list: PropTypes.array
        }).isRequired,
        form: PropTypes.shape({
            size: PropTypes.string,
            serial: PropTypes.string
        }).isRequired,
        onAutocompleteUpdate: PropTypes.func.isRequired,
        onAutocompleteExpand: PropTypes.func.isRequired,
        onAutocompleteSelect: PropTypes.func.isRequired,
        onInput: PropTypes.func.isRequired,
        onReset: PropTypes.func.isRequired,
        projectId: PropTypes.string.isRequired,
        sizes: PropTypes.array.isRequired
    },

    componentWillMount() {
        const { projectId } = this.props;
        this.ringsRef = firebase.database().ref(`rings/${projectId}`);
    },

    getTrimmedValue(name, value) {
        switch (name) {
            case 'size':
                return value.trim().replace(',', '.');

            case 'serial':
                return value.trim().toUpperCase();
        }
    },

    getDecimalValue(value) {
        const pattern = /\.[0-9]+/;
        return pattern.test(value) ? value : `${value}.0`;
    },

    handleInput(evt) {
        const { name, value } = evt.target;
        const trimmedValue = this.getTrimmedValue(name, value);

        this.props.onInput(name, trimmedValue);

        if (name === 'size') {
            this.handleAutocomplete(value);
        }
    },

    handleAutocomplete(value) {
        const pattern = new RegExp(`^${value}`);
        const matches = filter(this.props.sizes, (o) => {
            return value && pattern.test(o.size);
        });

        this.props.onAutocompleteUpdate(matches);
    },

    handleSubmit(evt) {
        evt.preventDefault();
        const { form } = this.props;

        if (!isString(form.size) || !isString(form.serial)) {
            // display error message…
            return;
        }

        const size = this.getDecimalValue(form.size).replace('.', '_');
        this.ringsRef.child(`${size}`).update({ serial: form.serial });
        this.ringsRef.child(`${size}/history/${form.serial}`).set(true);
        this.props.onReset();
    },

    render() {
        const { autocomplete, form } = this.props;

        return (
            <form className={ block() } onSubmit={ this.handleSubmit }>
                <FormGroup
                    label="Ring Size"
                    type="inline">
                    <Autocomplete
                        name="size"
                        expanded={ autocomplete.expanded }
                        onChange={ this.handleInput }
                        onClick={ (value) => this.props.onInput('size', value) }
                        onExpand={ this.props.onAutocompleteExpand }
                        onSelect={ this.props.onAutocompleteSelect }
                        list={ autocomplete.list }
                        value={ form.size } />
                </FormGroup>
                <FormGroup
                    label="Serial No."
                    type="inline">
                    <InputField
                        name="serial"
                        onChange={ this.handleInput }
                        value={ form.serial } />
                </FormGroup>
                <FormGroup
                    label=" "
                    type="inline">
                    <Button
                        style="success"
                        type="submit">Update</Button>
                </FormGroup>
            </form>
        );
    }

});

const mapStateToProps = (state) => {
    return {
        autocomplete: state.rings.autocomplete,
        form: state.rings.form,
        sizes: state.rings.sizes.list
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        onInput: (name, value) => dispatch(ringsUpdate('form', { [name]: value })),
        onReset: () => dispatch(ringsFormReset()),
        onAutocompleteUpdate: (list) => dispatch(ringsUpdate('autocomplete', { list, expanded: !!list.length })),
        onAutocompleteExpand: (expanded) => dispatch(ringsUpdate('autocomplete', { expanded })),
        onAutocompleteSelect: (index) => dispatch(ringsAutocompleteSelect(index, { selected: true }))
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(RingsForm);
<|endoftext|>


<commit_before>var git = require('../'),
    success = require('./utilities').success,
    events = require('events');

/**
 * Tree convenience class constructor.
 *
 * @param {git.raw.Repo} rawRepo
 * @param {git.raw.Tree|null} rawTree
 */
var Tree = function(rawRepo, rawTree) {
  if(!(rawRepo instanceof git.raw.Repo)) {
    throw git.error('First parameter for Tree must be a raw repo');
  }
  this.rawRepo = rawRepo;

  if(rawTree instanceof git.raw.Tree) {
    this.rawTree = rawTree;
  } else {
    this.rawTree = new git.raw.Tree(this.rawRepo);
  }
};

/**
 * Retrieve the entry by path.
 *
 * @param  {String}   path
 * @param  {Function} callback
 */
Tree.prototype.entry = function(path, callback) {
  var self = this;
  self.rawTree.entryByPath(path, function(error, rawEntry) {
    if (success(error, callback)) {
      callback(null, new git.entry(self.rawRepo, rawEntry));
    }
  });
};

Tree.prototype.walk = function() {
  var self = this,
      event = new events.EventEmitter(),
      entries = [];

  self.rawTree.walk(function treeWalkEntries(error, rawEntries) {
    rawEntries.forEach(function treeWalkEntryEmitter(rawEntry) {
      var entry = new git.entry(self.rawRepo, rawEntry);
      entries.push(entry);
      if (!error) {
        event.emit('entry', null, entry);
      }
    });
  }, function treeWalkEnd(error) {
    if (error) {
      event.emit('end', git.error(error), entries);
    }
    event.emit('end', null, entries);
  });

  return event;
};

exports.tree = Tree;
<commit_msg>Updated tree documentation<commit_after>var git = require('../'),
    success = require('./utilities').success,
    events = require('events');

/**
 * Tree convenience class constructor.
 *
 * @constructor
 * @param {git.raw.Repo} rawRepo Raw repository object.
 * @param {git.raw.Tree} [rawTree = new git.raw.Tree(rawRepo)] Raw tree object.
 */
var Tree = function(rawRepo, rawTree) {
  if(!(rawRepo instanceof git.raw.Repo)) {
    throw git.error('First parameter for Tree must be a raw repo');
  }
  this.rawRepo = rawRepo;

  if(rawTree instanceof git.raw.Tree) {
    this.rawTree = rawTree;
  } else {
    this.rawTree = new git.raw.Tree(rawRepo);
  }
};

/**
 * Retrieve the entry by path.
 *
 * @param  {String} path Path to the tree entry, relative to repository root.
 * @param  {Tree~entryCallback} callback
 */
Tree.prototype.entry = function(path, callback) {
  /**
   * @callback Tree~entryCallback Callback executed when an entry is retrieved.
   * @param {GitError|null} error An Error or null if successful.
   * @param {Entry|null} blob The tree entry object or null.
   */
  var self = this;
  self.rawTree.entryByPath(path, function(error, rawEntry) {
    if (success(error, callback)) {
      callback(null, new git.entry(self.rawRepo, rawEntry));
    }
  });
};

/**
 * Walk the tree.
 *
 * @fires Tree#entry
 * @fires Tree#end
 *
 * @return {EventEmitter}
 */
Tree.prototype.walk = function() {
  var self = this,
      event = new events.EventEmitter(),
      entries = [];

  self.rawTree.walk(function treeWalkEntries(error, rawEntries) {
    rawEntries.forEach(function treeWalkEntryEmitter(rawEntry) {
      var entry = new git.entry(self.rawRepo, rawEntry);
      entries.push(entry);
      if (!error) {
        /**
         * Entry event.
         *
         * @event Tree#entry
         *
         * @param {GitError|null} error An error object if there was an issue, null otherwise.
         * @param {Entry} entry The tree entry.
         */
        event.emit('entry', null, entry);
      }
    });
  }, function treeWalkEnd(error) {
    if (error) {
      event.emit('end', git.error(error), entries);
    }
    /**
     * End event.
     *
     * @event Tree#end
     *
     * @param {GitError|null} error An error object if there was an issue, null otherwise.
     * @param {Entry[]} entries The tree entries.
     */
    event.emit('end', null, entries);
  });

  return event;
};

exports.tree = Tree;
<|endoftext|>