<commit_before>'use strict';

var EventEmitter = require('./EventEmitter');
var FakeSnapshot = require('./FakeSnapshot');
var utils = require('./utils');

function FirebaseProxy(firebaseWrapper){
  this._wrapper = firebaseWrapper;
  this._data = {};
  this._listeners = {};
}

FirebaseProxy.prototype.on = function (path, eventType, callback, cancelCallback, context){
  var wrapper = this._wrapper;
  var listeners = this._listeners;
  var data = this._data;
  var initialized = listeners['.initialized'];
  var listening = listeners['.listening'];

  for(var i = 0, len = path.length; i < len; i++){
    var propName = path[i];
    listeners = listeners[propName] || (listeners[propName] = {});
    initialized = initialized || (listeners && listeners['.initialized']);
    listening = listening || (listeners && listeners['.listening']);
    data = (data || null) && data[propName];
  }

  if(!listening){
    listeners['.listening'] = true;
    wrapper.startWatching(path.join('/'));
  }
  var events = listeners['.events'] || (listeners['.events'] = new EventEmitter());
  events.on(eventType,callback);

  if(initialized){
    callback(new FakeSnapshot(path.join('/'),data));
  }
};

FirebaseProxy.prototype.off = function(path, eventType, callback, cancelCallback, context){
  var listeners = this._listeners;

  for(var i = 0, len = path.length; i < len; i++){
    var propName = path[i];
    if(!(listeners = listeners[propName])){
      return;
    }
  }

  var events = listeners['.events'];

  if(events){
    events.off(eventType,callback);
    if(!events.hasListeners()){
      this._wrapper.stopWatching(path.join('/'));
    }
  }
};

/*FirebaseProxy.prototype.on_value = function (path, value, priority){
  var listeners = this._listeners;
  var data = this._data;

  value = utils.mergePriority(value, priority);

  var propName;
  for(var i = 0, len = path.length -1; i <= len; i++){
    propName = path[i];
    listeners = listeners && listeners[propName];
    if(i !== len){
      data = data[propName] || (data[propName] =  {});
    }
  }
  var oldValue = data[propName];
  // data[propName] = value;
  var newValue = callListeners(path, value, oldValue, listeners);
  if(newValue !== oldValue){
    this._data = utils.mergeCopy(data,path,newValue)
  }
};/* */

FirebaseProxy.prototype.on_value = function(path, value, priority){
  var listeners = this._listeners;
  var data = this._data;
  value = utils.mergePriority(value, priority);
  var currentPath = [];
  path = path.slice();

  this._data = mergeValues(currentPath, path, data, value, listeners);

};/* */

function mergeValues(currentPath, remainingPath, oldValue, newValue, listeners){
  var newProp;
  if(remainingPath.length){

    var propName = remainingPath.shift();
    var propListeners = listeners && listeners[propName];
    var oldProp = (oldValue && oldValue.hasOwnProperty(propName)) ? oldValue[propName] : null;
    currentPath.push(propName);
    newProp = mergeValues(currentPath, remainingPath, oldProp, newValue, propListeners);
    currentPath.pop();
    if(oldProp === newProp){
      return oldValue;
    }

    var copy = {};
    for(var i in oldValue){
      if(oldValue.hasOwnProperty(i)){
        copy[i] = oldValue[i];
      }
    }
    /* jshint -W028 */
    // A labeled if statement. Yes it's a bit weird, but it works... and there are tests to prove it.
    loop: if(newProp === null){
      delete copy[propName];
      for(var j in copy){
        if(j !== '.priority'){
          break loop;
        }
      }
      copy = null;
    }
    else {
      copy[propName] = newProp;
    }
    var events = listeners && listeners['.events'];
    if(events){
      var pathString = currentPath.join('/');
      var childSnap = new FakeSnapshot(pathString + '/' + propName, newProp === null ? oldProp : newProp);
      var childEventType = newProp === null ? 'child_removed' : oldProp === null ? 'child_added' : 'child_changed';
      events.emit(childEventType,childSnap);
      events.emit('value', new FakeSnapshot(pathString,copy));
    }
    return copy;
  } else {
    newProp = callListeners(currentPath, newValue, oldValue, listeners);
    return utils.isEqualLeafValue(oldValue, newProp) ? oldValue : newProp;
  }
}

function callListeners(path, value, oldValue, listeners){
  var changed = !(value === oldValue || ((typeof value === 'object') && (typeof oldValue === 'object')));

  var keyCache = {};
  var i;

  var events = listeners && listeners['.events'];

  if(typeof value === 'object' && value !== null){
    for( i in value){
      if (value.hasOwnProperty(i) && i.charAt(0) !== '.'){
        keyCache[i] = true;
        path.push(i);

        var oldProp = oldValue && oldValue.hasOwnProperty(i) ? oldValue[i] : null;
        var newProp = value[i];
        var childChanged = (oldProp !== callListeners(
          path,
          newProp,
          oldProp,
          listeners && listeners[i]
        ));
        changed = childChanged || changed;

        if(events){
          if( !(oldValue && oldValue.hasOwnProperty(i))) {
            events.emit('child_added', new FakeSnapshot(path.join('/'), newProp));
          }
          else if(childChanged) {
            events.emit('child_changed', new FakeSnapshot(path.join('/'), newProp));
          }
        }

        path.pop();
      }
    }
    if(!changed && value.hasOwnProperty('.priority')){
      changed = !(oldValue && (value['.priority'] === oldValue['.priority']));
    }
    if(!changed && value.hasOwnProperty('.value')){
      changed = !(oldValue && (value['.value'] === oldValue['.value']));
    }
  }

  if(typeof oldValue === 'object' && oldValue !== null){
    for(i in oldValue){
      if (!keyCache[i] && oldValue.hasOwnProperty(i) && i.charAt(0) !== '.'){
        keyCache[i] = true;
        changed = true;
        path.push(i);

        callListeners(
          path,
          null, // we know the new value does not have this property
          oldValue[i],
          listeners && listeners[i]
        );

        if(events){
          events.emit('child_removed', new FakeSnapshot(path.join('/'), oldValue[i]));
        }

        path.pop();
      }
    }
    if(!changed && oldValue.hasOwnProperty('.priority')){
      changed = !(value && (value['.priority'] === oldValue['.priority']));
    }
  }

  if(listeners){
    for( i in listeners){
      if(!keyCache[i] && listeners.hasOwnProperty(i) && i.charAt(0) !== '.'){
        path.push(i);

        callListeners(path,null,null,listeners[i]);

        path.pop();
      }
    }
  }

  if(changed || (listeners && !listeners['.initialized'])){
    if(listeners) {
      (listeners['.initialized'] = true);
    }
    if(events){
      events.emit('value',new FakeSnapshot(path.join('/'),value));
    }
  }
  return changed ? value : oldValue;
}

FirebaseProxy.prototype.handleCallback = function(){
  throw new Error('handleCallback not implemented');
};

module.exports = FirebaseProxy;<commit_msg>remove unused method<commit_after>'use strict';

var EventEmitter = require('./EventEmitter');
var FakeSnapshot = require('./FakeSnapshot');
var utils = require('./utils');

function FirebaseProxy(firebaseWrapper){
  this._wrapper = firebaseWrapper;
  this._data = {};
  this._listeners = {};
}

FirebaseProxy.prototype.on = function (path, eventType, callback, cancelCallback, context){
  var wrapper = this._wrapper;
  var listeners = this._listeners;
  var data = this._data;
  var initialized = listeners['.initialized'];
  var listening = listeners['.listening'];

  for(var i = 0, len = path.length; i < len; i++){
    var propName = path[i];
    listeners = listeners[propName] || (listeners[propName] = {});
    initialized = initialized || (listeners && listeners['.initialized']);
    listening = listening || (listeners && listeners['.listening']);
    data = (data || null) && data[propName];
  }

  if(!listening){
    listeners['.listening'] = true;
    wrapper.startWatching(path.join('/'));
  }
  var events = listeners['.events'] || (listeners['.events'] = new EventEmitter());
  events.on(eventType,callback);

  if(initialized){
    callback(new FakeSnapshot(path.join('/'),data));
  }
};

FirebaseProxy.prototype.off = function(path, eventType, callback, cancelCallback, context){
  var listeners = this._listeners;

  for(var i = 0, len = path.length; i < len; i++){
    var propName = path[i];
    if(!(listeners = listeners[propName])){
      return;
    }
  }

  var events = listeners['.events'];

  if(events){
    events.off(eventType,callback);
    if(!events.hasListeners()){
      this._wrapper.stopWatching(path.join('/'));
    }
  }
};

/*FirebaseProxy.prototype.on_value = function (path, value, priority){
  var listeners = this._listeners;
  var data = this._data;

  value = utils.mergePriority(value, priority);

  var propName;
  for(var i = 0, len = path.length -1; i <= len; i++){
    propName = path[i];
    listeners = listeners && listeners[propName];
    if(i !== len){
      data = data[propName] || (data[propName] =  {});
    }
  }
  var oldValue = data[propName];
  // data[propName] = value;
  var newValue = callListeners(path, value, oldValue, listeners);
  if(newValue !== oldValue){
    this._data = utils.mergeCopy(data,path,newValue)
  }
};/* */

FirebaseProxy.prototype.on_value = function(path, value, priority){
  var listeners = this._listeners;
  var data = this._data;
  value = utils.mergePriority(value, priority);
  var currentPath = [];
  path = path.slice();

  this._data = mergeValues(currentPath, path, data, value, listeners);

};/* */

function mergeValues(currentPath, remainingPath, oldValue, newValue, listeners){
  var newProp;
  if(remainingPath.length){

    var propName = remainingPath.shift();
    var propListeners = listeners && listeners[propName];
    var oldProp = (oldValue && oldValue.hasOwnProperty(propName)) ? oldValue[propName] : null;
    currentPath.push(propName);
    newProp = mergeValues(currentPath, remainingPath, oldProp, newValue, propListeners);
    currentPath.pop();
    if(oldProp === newProp){
      return oldValue;
    }

    var copy = {};
    for(var i in oldValue){
      if(oldValue.hasOwnProperty(i)){
        copy[i] = oldValue[i];
      }
    }
    /* jshint -W028 */
    // A labeled if statement. Yes it's a bit weird, but it works... and there are tests to prove it.
    loop: if(newProp === null){
      delete copy[propName];
      for(var j in copy){
        if(j !== '.priority'){
          break loop;
        }
      }
      copy = null;
    }
    else {
      copy[propName] = newProp;
    }
    var events = listeners && listeners['.events'];
    if(events){
      var pathString = currentPath.join('/');
      var childSnap = new FakeSnapshot(pathString + '/' + propName, newProp === null ? oldProp : newProp);
      var childEventType = newProp === null ? 'child_removed' : oldProp === null ? 'child_added' : 'child_changed';
      events.emit(childEventType,childSnap);
      events.emit('value', new FakeSnapshot(pathString,copy));
    }
    return copy;
  } else {
    newProp = callListeners(currentPath, newValue, oldValue, listeners);
    return utils.isEqualLeafValue(oldValue, newProp) ? oldValue : newProp;
  }
}

function callListeners(path, value, oldValue, listeners){
  var changed = !(value === oldValue || ((typeof value === 'object') && (typeof oldValue === 'object')));

  var keyCache = {};
  var i;

  var events = listeners && listeners['.events'];

  if(typeof value === 'object' && value !== null){
    for( i in value){
      if (value.hasOwnProperty(i) && i.charAt(0) !== '.'){
        keyCache[i] = true;
        path.push(i);

        var oldProp = oldValue && oldValue.hasOwnProperty(i) ? oldValue[i] : null;
        var newProp = value[i];
        var childChanged = (oldProp !== callListeners(
          path,
          newProp,
          oldProp,
          listeners && listeners[i]
        ));
        changed = childChanged || changed;

        if(events){
          if( !(oldValue && oldValue.hasOwnProperty(i))) {
            events.emit('child_added', new FakeSnapshot(path.join('/'), newProp));
          }
          else if(childChanged) {
            events.emit('child_changed', new FakeSnapshot(path.join('/'), newProp));
          }
        }

        path.pop();
      }
    }
    if(!changed && value.hasOwnProperty('.priority')){
      changed = !(oldValue && (value['.priority'] === oldValue['.priority']));
    }
    if(!changed && value.hasOwnProperty('.value')){
      changed = !(oldValue && (value['.value'] === oldValue['.value']));
    }
  }

  if(typeof oldValue === 'object' && oldValue !== null){
    for(i in oldValue){
      if (!keyCache[i] && oldValue.hasOwnProperty(i) && i.charAt(0) !== '.'){
        keyCache[i] = true;
        changed = true;
        path.push(i);

        callListeners(
          path,
          null, // we know the new value does not have this property
          oldValue[i],
          listeners && listeners[i]
        );

        if(events){
          events.emit('child_removed', new FakeSnapshot(path.join('/'), oldValue[i]));
        }

        path.pop();
      }
    }
    if(!changed && oldValue.hasOwnProperty('.priority')){
      changed = !(value && (value['.priority'] === oldValue['.priority']));
    }
  }

  if(listeners){
    for( i in listeners){
      if(!keyCache[i] && listeners.hasOwnProperty(i) && i.charAt(0) !== '.'){
        path.push(i);

        callListeners(path,null,null,listeners[i]);

        path.pop();
      }
    }
  }

  if(changed || (listeners && !listeners['.initialized'])){
    if(listeners) {
      (listeners['.initialized'] = true);
    }
    if(events){
      events.emit('value',new FakeSnapshot(path.join('/'),value));
    }
  }
  return changed ? value : oldValue;
}

module.exports = FirebaseProxy;<|endoftext|>


<commit_before>var map;

function init() {

  var resolutions = [4000, 3750, 3500, 3250, 3000, 2750, 2500, 2250, 2000, 1750, 1500, 1250, 1000, 750, 650.0, 500.0, 250.0, 100.0, 50.0, 20.0, 10.0, 5.0, 2.5, 2.0, 1.5, 1.0, 0.5];
  var matrixIds = [
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26
  ];
  var template =
      '{Layer}/{Style}/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg';
  var urls = [
    'http://wmts5.geo.admin.ch/1.0.0/' + template,
    'http://wmts6.geo.admin.ch/1.0.0/' + template,
    'http://wmts7.geo.admin.ch/1.0.0/' + template,
    'http://wmts8.geo.admin.ch/1.0.0/' + template,
    'http://wmts9.geo.admin.ch/1.0.0/' + template
  ];

  var source = new ol.source.WMTS({
    extent: [420000, 30000, 900000, 350000],
    projection: 'EPSG:21781',
    dimensions: {
      'Time': '20130903'
    },
    layer: 'ch.swisstopo.pixelkarte-farbe-pk25.noscale',
    style: 'default',
    matrixSet: '21781',
    urls: urls,
    requestEncoding: /** @type {ol.source.WMTSRequestEncoding} */ ('REST'),
    tileGrid: new ol.tilegrid.WMTS({
      origin: [420000, 350000],
      resolutions: [650.0, 500.0, 250.0, 100.0, 50.0, 20.0, 10.0, 5.0, 2.5, 2.0, 1.5, 1.0, 0.5],
      matrixIds: [14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
    })
  });

  var old_wmts = new ol.layer.Tile({
    source: source
  });

  var new_wmts = ga.layer.create('ch.swisstopo.pixelkarte-farbe-pk25.noscale');
  new_wmts.setOpacity(1.0);

  map = new ga.Map({
    target: 'map',
    layers: [old_wmts, new_wmts],
    view: new ol.View2D({
      resolution: 5,
      center: [626456.6, 198890.8]
    })
  });

  initSlider(0.4);
  swipeLayer(new_wmts);
}
<commit_msg>Use 2.5 as resolution by default<commit_after>var map;

function init() {

  var resolutions = [4000, 3750, 3500, 3250, 3000, 2750, 2500, 2250, 2000, 1750, 1500, 1250, 1000, 750, 650.0, 500.0, 250.0, 100.0, 50.0, 20.0, 10.0, 5.0, 2.5, 2.0, 1.5, 1.0, 0.5];
  var matrixIds = [
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26
  ];
  var template =
      '{Layer}/{Style}/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}.jpeg';
  var urls = [
    'http://wmts5.geo.admin.ch/1.0.0/' + template,
    'http://wmts6.geo.admin.ch/1.0.0/' + template,
    'http://wmts7.geo.admin.ch/1.0.0/' + template,
    'http://wmts8.geo.admin.ch/1.0.0/' + template,
    'http://wmts9.geo.admin.ch/1.0.0/' + template
  ];

  var source = new ol.source.WMTS({
    extent: [420000, 30000, 900000, 350000],
    projection: 'EPSG:21781',
    dimensions: {
      'Time': '20130903'
    },
    layer: 'ch.swisstopo.pixelkarte-farbe-pk25.noscale',
    style: 'default',
    matrixSet: '21781',
    urls: urls,
    requestEncoding: /** @type {ol.source.WMTSRequestEncoding} */ ('REST'),
    tileGrid: new ol.tilegrid.WMTS({
      origin: [420000, 350000],
      resolutions: [650.0, 500.0, 250.0, 100.0, 50.0, 20.0, 10.0, 5.0, 2.5, 2.0, 1.5, 1.0, 0.5],
      matrixIds: [14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
    })
  });

  var old_wmts = new ol.layer.Tile({
    source: source
  });

  var new_wmts = ga.layer.create('ch.swisstopo.pixelkarte-farbe-pk25.noscale');
  new_wmts.setOpacity(1.0);

  map = new ga.Map({
    target: 'map',
    layers: [old_wmts, new_wmts],
    view: new ol.View2D({
      resolution: 2.5,
      center: [626456.6, 198890.8]
    })
  });

  initSlider(0.4);
  swipeLayer(new_wmts);
}
<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true */
/*global require, exports, Backbone, EJS, $, setTimeout, localStorage, ace, Storage, window, _ */
/*global arangoHelper*/

var queryView = Backbone.View.extend({
  el: '#content',

  initialize: function () {
    this.getAQL();
    this.getSystemQueries();
    localStorage.setItem("queryContent", "");
    localStorage.setItem("queryOutput", "");
  },

  events: {
    'click #submitQueryIcon'         : 'submitQuery',
    'click #submitQueryButton'       : 'submitQuery',
    'click #commentText'             : 'commentText',
    'click #undoText'                : 'undoText',
    'click #redoText'                : 'redoText',
    'click #smallOutput'             : 'smallOutput',
    'click #bigOutput'               : 'bigOutput',
    'click #clearOutput'             : 'clearOutput',
    'click #clearInput'              : 'clearInput',
    'click #addAQL'                  : 'addAQL',
    'click #editAQL'                 : 'editAQL',
    'click #save-new-query'          : 'saveAQL',
    'click #save-edit-query'         : 'saveAQL',
    'click #delete-edit-query'       : 'showDeleteField',
    'click #confirmDeleteQuery'      : 'deleteAQL',
    'click #abortDeleteQuery'        : 'hideDeleteField',
    'keydown #new-query-name'        : 'listenKey',
    'change #queryModalSelect'       : 'updateEditSelect',
    'change #querySelect'            : 'importSelected',
    'keypress #aqlEditor'            : 'aqlShortcuts'
  },

  listenKey: function (e) {
    if (e.keyCode === 13) {
      this.saveAQL(e);
    }
  },

  clearOutput: function() {
    var outputEditor = ace.edit("queryOutput");
    outputEditor.setValue('');
  },

  clearInput: function() {
    var inputEditor = ace.edit("aqlEditor");
    inputEditor.setValue('');
  },

  smallOutput: function() {
    var outputEditor = ace.edit("queryOutput");
    outputEditor.getSession().foldAll();
  },

  bigOutput: function() {
    var outputEditor = ace.edit("queryOutput");
    outputEditor.getSession().unfold();
  },

  aqlShortcuts: function (e) {
    if (e.ctrlKey && e.keyCode === 13) {
      this.submitQuery();
    }
    else if (e.metaKey && !e.ctrlKey && e.keyCode === 13) {
      this.submitQuery();
    }
    else if (e.ctrlKey && e.keyCode === 90) {
      this.undoText();
    }
    else if (e.ctrlKey && e.shiftKey && e.keyCode === 90) {
      this.redeText();
    }

  },

  queries: [
  ],

  customQueries: [],

  template: new EJS({url: 'js/templates/queryView.ejs'}),

  render: function() {
    var self = this;
    $(this.el).html(this.template.text);
    var inputEditor = ace.edit("aqlEditor");
    var outputEditor = ace.edit("queryOutput");

    outputEditor.setReadOnly(true);
    outputEditor.setHighlightActiveLine(false);

    inputEditor.getSession().setMode("ace/mode/aql");
    outputEditor.getSession().setMode("ace/mode/json");
    outputEditor.setValue('');

    $('#queryOutput').resizable({
      handles: "s",
      ghost: true,
      stop: function () {
        setTimeout(function (){
          var outputEditor = ace.edit("queryOutput");
          outputEditor.resize();
        },200);
      }
    });

    $('#aqlEditor').resizable({
      handles: "s",
      ghost: true,
      //helper: "resizable-helper",
      stop: function () {
        setTimeout(function (){
          var inputEditor = ace.edit("aqlEditor");
          inputEditor.resize();
        },200);
      }
    });

    $('.queryTooltips').tooltip({
      placement: "top"
    });

    $('#aqlEditor .ace_text-input').focus();
    $.gritter.removeAll();

    if(typeof Storage) {
      var queryContent = localStorage.getItem("queryContent");
      var queryOutput = localStorage.getItem("queryOutput");
      inputEditor.setValue(queryContent);
      outputEditor.setValue(queryOutput);
    }

    var windowHeight = $(window).height() - 250;
    $('#queryOutput').height(windowHeight/3);
    $('#aqlEditor').height(windowHeight/2);

    inputEditor.resize();
    outputEditor.resize();

    inputEditor.setTheme("ace/theme/merbivore_soft");

    this.renderSelectboxes();
    $('#queryDiv').show();

    return this;
  },

  deselect : function (editor) {
    var current = editor.getSelection();
    var currentRow = current.lead.row;
    var currentColumn = current.lead.column;

    current.setSelectionRange({
      start: {
        row: currentRow,
        column: currentColumn
      },
      end: {
        row: currentRow,
        column: currentColumn
      }
    });

    editor.focus();
  },

  addAQL: function () {
    //render options
    $('#new-query-name').val('');
    $('#new-aql-query').modal('show');
    setTimeout(function (){
      $('#new-query-name').focus();
    },500);
  },
  editAQL: function () {
    if (this.customQueries.length === 0) {
      arangoHelper.arangoNotification("No custom queries available");
      return;
    }

    this.hideDeleteField();
    $('#edit-aql-queries').modal('show');
    this.renderSelectboxes(true);
    this.updateEditSelect();
  },
  getAQL: function () {
    if (localStorage.getItem("customQueries")) {
      this.customQueries = JSON.parse(localStorage.getItem("customQueries"));
    }
  },
  showDeleteField: function () {
    $('#reallyDeleteQueryDiv').show();
  },
  hideDeleteField: function () {
    $('#reallyDeleteQueryDiv').hide();
  },
  deleteAQL: function () {
    var queryName = $('#queryModalSelect').val();
    var tempArray = [];

    $.each(this.customQueries, function(k,v) {
      if (queryName !== v.name) {
        tempArray.push({
          name: v.name,
          value: v.value
        });
      }
    });

    this.customQueries = tempArray;
    localStorage.setItem("customQueries", JSON.stringify(this.customQueries));
    $('#edit-aql-queries').modal('hide');
    arangoHelper.arangoNotification("Query deleted");
    this.renderSelectboxes();
  },
  saveAQL: function (e) {

    var self = this;
    var inputEditor = ace.edit("aqlEditor");
    var queryName = $('#new-query-name').val();
    var content = inputEditor.getValue();

    if (e) {
      if (e.target.id === 'save-edit-query') {
        content = $('#edit-aql-textarea').val();
        queryName = $('#queryModalSelect').val();
      }
    }

    if (queryName.trim() === '') {
      arangoHelper.arangoNotification("Illegal query name");
      return;
    }

    //check for already existing entry
    var tempArray = [];
    var quit = false;
    $.each(this.customQueries, function(k,v) {
      if (e.target.id !== 'save-edit-query') {
        if (v.name === queryName) {
          quit = true;
          return;
        }
      }
      if (v.name !== queryName) {
        tempArray.push({
          name: v.name,
          value: v.value
        });
      }
    });

    if (quit === true) {
      arangoHelper.arangoNotification("Name already taken!");
      return;
    }

    this.customQueries = tempArray;

    this.customQueries.push({
      name: queryName,
      value: content
    });

    $('#new-aql-query').modal('hide');
    $('#edit-aql-queries').modal('hide');

    localStorage.setItem("customQueries", JSON.stringify(this.customQueries));
    arangoHelper.arangoNotification("Query saved");
    this.renderSelectboxes();
  },
  updateEditSelect: function () {
    var value = this.getCustomQueryValueByName($('#queryModalSelect').val());
    $('#edit-aql-textarea').val(value);
    $('#edit-aql-textarea').focus();
  },
  getSystemQueries: function() {
    var self = this;
    $.ajax({
      type: "GET",
      cache: false,
      url: "js/arango/aqltemplates.json",
      contentType: "application/json",
      processData: false,
      async: false,
      success: function(data) {
        self.queries = data;
      },
      error: function(data) {
        arangoHelper.arangoNotification("Error while loading system templates");
      }
    });
  },
  getCustomQueryValueByName: function (qName) {
    var returnVal;
    $.each(this.customQueries, function(k,v) {
      if (qName === v.name) {
        returnVal = v.value;
      }
    });
    return returnVal;
  },
  importSelected: function(e) {
    var inputEditor = ace.edit("aqlEditor");
    $.each(this.queries, function(k,v) {
      if ($('#'+e.currentTarget.id).val() === v.name) {
        inputEditor.setValue(v.value);
      }
    });
    $.each(this.customQueries, function(k,v) {
      if ($('#'+e.currentTarget.id).val() === v.name) {
        inputEditor.setValue(v.value);
      }
    });

    this.deselect(ace.edit("aqlEditor"));
  },
  renderSelectboxes: function (modal) {
    this.sortQueries();
    var selector = '';
    if (modal === true) {
      selector = '#queryModalSelect';
      $(selector).empty();
      $.each(this.customQueries, function(k,v) {
        $(selector).append('<option id="'+v.name+'">'+v.name+'</option>');
      });
    }
    else {
      selector = '#querySelect';
      $(selector).empty();
      $(selector).append('<option id="emptyquery">(please select)</option>');

      $(selector).append('<optgroup label="Example queries">');
      $.each(this.queries, function(k,v) {
        $(selector).append('<option id="'+v.name+'">'+v.name+'</option>');
      });
      $(selector).append('</optgroup>');

      if (this.customQueries.length > 0) {
        $(selector).append('<optgroup label="Custom queries">');
        $.each(this.customQueries, function(k,v) {
          $(selector).append('<option id="'+v.name+'">'+v.name+'</option>');
        });
        $(selector).append('</optgroup>');
      }
    }
  },
  undoText: function () {
    var inputEditor = ace.edit("aqlEditor");
    inputEditor.undo();
  },
  redoText: function () {
    var inputEditor = ace.edit("aqlEditor");
    inputEditor.redo();
  },
  commentText: function() {
    var inputEditor = ace.edit("aqlEditor");
    var value;
    var newValue;
    var flag = false;
    var cursorPosition = inputEditor.getCursorPosition();
    var cursorRange = inputEditor.getSelection().getRange();

    var regExp = new RegExp(/\*\//);
    var regExp2 = new RegExp(/\/\*/);

    if (cursorRange.end.row === cursorRange.start.row) {
      //single line comment /* */
      value = inputEditor.getSession().getLine(cursorRange.start.row);
      if (value.search(regExp) === -1 && value.search(regExp2) === -1) {
        newValue = '/*' + value + '*/';
        flag = true;
      }
      else if (value.search(regExp) !== -1 && value.search(regExp2) !== -1) {
        newValue = value.replace(regExp, '').replace(regExp2, '');
        flag = true;
      }
      if (flag === true) {
        inputEditor.find(value, {
          range: cursorRange
        });
        inputEditor.replace(newValue);
      }
    }
    else {
      //multi line comment
      value = inputEditor.getSession().getLines(cursorRange.start.row, cursorRange.end.row);
      var arrayLength = value.length;
      var firstString = value[0];
      var lastString = value[value.length-1];
      var newFirstString;
      var newLastString;

      if (firstString.search(regExp2) === -1 && lastString.search(regExp) === -1) {
        newFirstString = '/*' + firstString;
        newLastString = lastString + '*/';
        flag = true;
      }
      else if (firstString.search(regExp2) !== -1 && lastString.search(regExp) !== -1) {
        newFirstString = firstString.replace(regExp2, '');
        newLastString = lastString.replace(regExp, '');
        flag = true;
      }
      if (flag === true) {
        inputEditor.find(firstString, {
          range: cursorRange
        });
        inputEditor.replace(newFirstString);
        inputEditor.find(lastString, {
          range: cursorRange
        });
        inputEditor.replace(newLastString);
      }
    }
    cursorRange.end.column = cursorRange.end.column + 2;
    inputEditor.getSelection().setSelectionRange(cursorRange, false);
  },
  sortQueries: function() {
    this.queries = _.sortBy(this.queries, 'name' );
    this.customQueries = _.sortBy(this.customQueries, 'name' );
  },
  submitQuery: function() {
    var self = this;
    var inputEditor = ace.edit("aqlEditor");
    var data = {query: inputEditor.getValue()};

    var outputEditor = ace.edit("queryOutput");

    $.ajax({
      type: "POST",
      url: "/_api/cursor",
      data: JSON.stringify(data),
      contentType: "application/json",
      processData: false,
      success: function(data) {
        outputEditor.setValue(arangoHelper.FormatJSON(data.result));
        if(typeof Storage) {
          localStorage.setItem("queryContent", inputEditor.getValue());
          localStorage.setItem("queryOutput", outputEditor.getValue());
        }
      },
      error: function(data) {
        try {
          var temp = JSON.parse(data.responseText);
          outputEditor.setValue('[' + temp.errorNum + '] ' + temp.errorMessage);

          if(typeof Storage) {
            localStorage.setItem("queryContent", inputEditor.getValue());
            localStorage.setItem("queryOutput", outputEditor.getValue());
          }
        }
        catch (e) {
          outputEditor.setValue('ERROR');
        }
      }
    });
    outputEditor.resize();

  }

});
<commit_msg>added deselect function after tabbing<commit_after>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true */
/*global require, exports, Backbone, EJS, $, setTimeout, localStorage, ace, Storage, window, _ */
/*global arangoHelper*/

var queryView = Backbone.View.extend({
  el: '#content',

  initialize: function () {
    this.getAQL();
    this.getSystemQueries();
    localStorage.setItem("queryContent", "");
    localStorage.setItem("queryOutput", "");
  },

  events: {
    'click #submitQueryIcon'         : 'submitQuery',
    'click #submitQueryButton'       : 'submitQuery',
    'click #commentText'             : 'commentText',
    'click #undoText'                : 'undoText',
    'click #redoText'                : 'redoText',
    'click #smallOutput'             : 'smallOutput',
    'click #bigOutput'               : 'bigOutput',
    'click #clearOutput'             : 'clearOutput',
    'click #clearInput'              : 'clearInput',
    'click #addAQL'                  : 'addAQL',
    'click #editAQL'                 : 'editAQL',
    'click #save-new-query'          : 'saveAQL',
    'click #save-edit-query'         : 'saveAQL',
    'click #delete-edit-query'       : 'showDeleteField',
    'click #confirmDeleteQuery'      : 'deleteAQL',
    'click #abortDeleteQuery'        : 'hideDeleteField',
    'keydown #new-query-name'        : 'listenKey',
    'change #queryModalSelect'       : 'updateEditSelect',
    'change #querySelect'            : 'importSelected',
    'keypress #aqlEditor'            : 'aqlShortcuts'
  },

  listenKey: function (e) {
    if (e.keyCode === 13) {
      this.saveAQL(e);
    }
  },

  clearOutput: function() {
    var outputEditor = ace.edit("queryOutput");
    outputEditor.setValue('');
  },

  clearInput: function() {
    var inputEditor = ace.edit("aqlEditor");
    inputEditor.setValue('');
  },

  smallOutput: function() {
    var outputEditor = ace.edit("queryOutput");
    outputEditor.getSession().foldAll();
  },

  bigOutput: function() {
    var outputEditor = ace.edit("queryOutput");
    outputEditor.getSession().unfold();
  },

  aqlShortcuts: function (e) {
    if (e.ctrlKey && e.keyCode === 13) {
      this.submitQuery();
    }
    else if (e.metaKey && !e.ctrlKey && e.keyCode === 13) {
      this.submitQuery();
    }
    else if (e.ctrlKey && e.keyCode === 90) {
      this.undoText();
    }
    else if (e.ctrlKey && e.shiftKey && e.keyCode === 90) {
      this.redeText();
    }

  },

  queries: [
  ],

  customQueries: [],

  template: new EJS({url: 'js/templates/queryView.ejs'}),

  render: function() {
    var self = this;
    $(this.el).html(this.template.text);
    var inputEditor = ace.edit("aqlEditor");
    var outputEditor = ace.edit("queryOutput");

    outputEditor.setReadOnly(true);
    outputEditor.setHighlightActiveLine(false);

    inputEditor.getSession().setMode("ace/mode/aql");
    outputEditor.getSession().setMode("ace/mode/json");
    outputEditor.setValue('');

    $('#queryOutput').resizable({
      handles: "s",
      ghost: true,
      stop: function () {
        setTimeout(function (){
          var outputEditor = ace.edit("queryOutput");
          outputEditor.resize();
        },200);
      }
    });

    $('#aqlEditor').resizable({
      handles: "s",
      ghost: true,
      //helper: "resizable-helper",
      stop: function () {
        setTimeout(function (){
          var inputEditor = ace.edit("aqlEditor");
          inputEditor.resize();
        },200);
      }
    });

    $('.queryTooltips').tooltip({
      placement: "top"
    });

    $('#aqlEditor .ace_text-input').focus();
    $.gritter.removeAll();

    if(typeof Storage) {
      var queryContent = localStorage.getItem("queryContent");
      var queryOutput = localStorage.getItem("queryOutput");
      inputEditor.setValue(queryContent);
      outputEditor.setValue(queryOutput);
    }

    var windowHeight = $(window).height() - 250;
    $('#queryOutput').height(windowHeight/3);
    $('#aqlEditor').height(windowHeight/2);

    inputEditor.resize();
    outputEditor.resize();

    inputEditor.setTheme("ace/theme/merbivore_soft");

    this.renderSelectboxes();
    this.deselect(outputEditor);
    this.deselect(inputEditor);
    $('#queryDiv').show();

    return this;
  },

  deselect : function (editor) {
    var current = editor.getSelection();
    var currentRow = current.lead.row;
    var currentColumn = current.lead.column;

    current.setSelectionRange({
      start: {
        row: currentRow,
        column: currentColumn
      },
      end: {
        row: currentRow,
        column: currentColumn
      }
    });

    editor.focus();
  },

  addAQL: function () {
    //render options
    $('#new-query-name').val('');
    $('#new-aql-query').modal('show');
    setTimeout(function (){
      $('#new-query-name').focus();
    },500);
  },
  editAQL: function () {
    if (this.customQueries.length === 0) {
      arangoHelper.arangoNotification("No custom queries available");
      return;
    }

    this.hideDeleteField();
    $('#edit-aql-queries').modal('show');
    this.renderSelectboxes(true);
    this.updateEditSelect();
  },
  getAQL: function () {
    if (localStorage.getItem("customQueries")) {
      this.customQueries = JSON.parse(localStorage.getItem("customQueries"));
    }
  },
  showDeleteField: function () {
    $('#reallyDeleteQueryDiv').show();
  },
  hideDeleteField: function () {
    $('#reallyDeleteQueryDiv').hide();
  },
  deleteAQL: function () {
    var queryName = $('#queryModalSelect').val();
    var tempArray = [];

    $.each(this.customQueries, function(k,v) {
      if (queryName !== v.name) {
        tempArray.push({
          name: v.name,
          value: v.value
        });
      }
    });

    this.customQueries = tempArray;
    localStorage.setItem("customQueries", JSON.stringify(this.customQueries));
    $('#edit-aql-queries').modal('hide');
    arangoHelper.arangoNotification("Query deleted");
    this.renderSelectboxes();
  },
  saveAQL: function (e) {

    var self = this;
    var inputEditor = ace.edit("aqlEditor");
    var queryName = $('#new-query-name').val();
    var content = inputEditor.getValue();

    if (e) {
      if (e.target.id === 'save-edit-query') {
        content = $('#edit-aql-textarea').val();
        queryName = $('#queryModalSelect').val();
      }
    }

    if (queryName.trim() === '') {
      arangoHelper.arangoNotification("Illegal query name");
      return;
    }

    //check for already existing entry
    var tempArray = [];
    var quit = false;
    $.each(this.customQueries, function(k,v) {
      if (e.target.id !== 'save-edit-query') {
        if (v.name === queryName) {
          quit = true;
          return;
        }
      }
      if (v.name !== queryName) {
        tempArray.push({
          name: v.name,
          value: v.value
        });
      }
    });

    if (quit === true) {
      arangoHelper.arangoNotification("Name already taken!");
      return;
    }

    this.customQueries = tempArray;

    this.customQueries.push({
      name: queryName,
      value: content
    });

    $('#new-aql-query').modal('hide');
    $('#edit-aql-queries').modal('hide');

    localStorage.setItem("customQueries", JSON.stringify(this.customQueries));
    arangoHelper.arangoNotification("Query saved");
    this.renderSelectboxes();
  },
  updateEditSelect: function () {
    var value = this.getCustomQueryValueByName($('#queryModalSelect').val());
    $('#edit-aql-textarea').val(value);
    $('#edit-aql-textarea').focus();
  },
  getSystemQueries: function() {
    var self = this;
    $.ajax({
      type: "GET",
      cache: false,
      url: "js/arango/aqltemplates.json",
      contentType: "application/json",
      processData: false,
      async: false,
      success: function(data) {
        self.queries = data;
      },
      error: function(data) {
        arangoHelper.arangoNotification("Error while loading system templates");
      }
    });
  },
  getCustomQueryValueByName: function (qName) {
    var returnVal;
    $.each(this.customQueries, function(k,v) {
      if (qName === v.name) {
        returnVal = v.value;
      }
    });
    return returnVal;
  },
  importSelected: function(e) {
    var inputEditor = ace.edit("aqlEditor");
    $.each(this.queries, function(k,v) {
      if ($('#'+e.currentTarget.id).val() === v.name) {
        inputEditor.setValue(v.value);
      }
    });
    $.each(this.customQueries, function(k,v) {
      if ($('#'+e.currentTarget.id).val() === v.name) {
        inputEditor.setValue(v.value);
      }
    });

    this.deselect(ace.edit("aqlEditor"));
  },
  renderSelectboxes: function (modal) {
    this.sortQueries();
    var selector = '';
    if (modal === true) {
      selector = '#queryModalSelect';
      $(selector).empty();
      $.each(this.customQueries, function(k,v) {
        $(selector).append('<option id="'+v.name+'">'+v.name+'</option>');
      });
    }
    else {
      selector = '#querySelect';
      $(selector).empty();
      $(selector).append('<option id="emptyquery">(please select)</option>');

      $(selector).append('<optgroup label="Example queries">');
      $.each(this.queries, function(k,v) {
        $(selector).append('<option id="'+v.name+'">'+v.name+'</option>');
      });
      $(selector).append('</optgroup>');

      if (this.customQueries.length > 0) {
        $(selector).append('<optgroup label="Custom queries">');
        $.each(this.customQueries, function(k,v) {
          $(selector).append('<option id="'+v.name+'">'+v.name+'</option>');
        });
        $(selector).append('</optgroup>');
      }
    }
  },
  undoText: function () {
    var inputEditor = ace.edit("aqlEditor");
    inputEditor.undo();
  },
  redoText: function () {
    var inputEditor = ace.edit("aqlEditor");
    inputEditor.redo();
  },
  commentText: function() {
    var inputEditor = ace.edit("aqlEditor");
    var value;
    var newValue;
    var flag = false;
    var cursorPosition = inputEditor.getCursorPosition();
    var cursorRange = inputEditor.getSelection().getRange();

    var regExp = new RegExp(/\*\//);
    var regExp2 = new RegExp(/\/\*/);

    if (cursorRange.end.row === cursorRange.start.row) {
      //single line comment /* */
      value = inputEditor.getSession().getLine(cursorRange.start.row);
      if (value.search(regExp) === -1 && value.search(regExp2) === -1) {
        newValue = '/*' + value + '*/';
        flag = true;
      }
      else if (value.search(regExp) !== -1 && value.search(regExp2) !== -1) {
        newValue = value.replace(regExp, '').replace(regExp2, '');
        flag = true;
      }
      if (flag === true) {
        inputEditor.find(value, {
          range: cursorRange
        });
        inputEditor.replace(newValue);
      }
    }
    else {
      //multi line comment
      value = inputEditor.getSession().getLines(cursorRange.start.row, cursorRange.end.row);
      var arrayLength = value.length;
      var firstString = value[0];
      var lastString = value[value.length-1];
      var newFirstString;
      var newLastString;

      if (firstString.search(regExp2) === -1 && lastString.search(regExp) === -1) {
        newFirstString = '/*' + firstString;
        newLastString = lastString + '*/';
        flag = true;
      }
      else if (firstString.search(regExp2) !== -1 && lastString.search(regExp) !== -1) {
        newFirstString = firstString.replace(regExp2, '');
        newLastString = lastString.replace(regExp, '');
        flag = true;
      }
      if (flag === true) {
        inputEditor.find(firstString, {
          range: cursorRange
        });
        inputEditor.replace(newFirstString);
        inputEditor.find(lastString, {
          range: cursorRange
        });
        inputEditor.replace(newLastString);
      }
    }
    cursorRange.end.column = cursorRange.end.column + 2;
    inputEditor.getSelection().setSelectionRange(cursorRange, false);
  },
  sortQueries: function() {
    this.queries = _.sortBy(this.queries, 'name' );
    this.customQueries = _.sortBy(this.customQueries, 'name' );
  },
  submitQuery: function() {
    var self = this;
    var inputEditor = ace.edit("aqlEditor");
    var data = {query: inputEditor.getValue()};
    var outputEditor = ace.edit("queryOutput");

    $.ajax({
      type: "POST",
      url: "/_api/cursor",
      data: JSON.stringify(data),
      contentType: "application/json",
      processData: false,
      success: function(data) {
        outputEditor.setValue(arangoHelper.FormatJSON(data.result));
        if(typeof Storage) {
          localStorage.setItem("queryContent", inputEditor.getValue());
          localStorage.setItem("queryOutput", outputEditor.getValue());
        }
        self.deselect(outputEditor);
      },
      error: function(data) {
        try {
          var temp = JSON.parse(data.responseText);
          outputEditor.setValue('[' + temp.errorNum + '] ' + temp.errorMessage);

          if(typeof Storage) {
            localStorage.setItem("queryContent", inputEditor.getValue());
            localStorage.setItem("queryOutput", outputEditor.getValue());
          }
        }
        catch (e) {
          outputEditor.setValue('ERROR');
        }
      }
    });
    outputEditor.resize();

  }

});
<|endoftext|>


<commit_before>//1 task
// Hoisting или "поднятие переменных"? - это когда интерпретатор JavaScript перемещает («поднимает») объявления функций
// и переменных в начало области видимости
myname = "global";
function func() {
    console.log(myname); // undefined
    var myname = "local";
    console.log(myname); // local
}
func();

//2 task
// - Какие языковые конструкции в javascript создают scope? Что произойдет при выполнении следующего куска кода?
//1) В javascript только функции создают новый scope
var a = 90100;
function someFunc(){
  if(false){
    var a = 1;
  } else {
    var b = 2;
  }
  console.log(b); // 2
  console.log(a); // undefined
}
someFunc();

//3 task
function test() {
  this;
}
test();// object window , undefined

//4 task
Что такое глобальные переменные ? - переменные которые не находятся внутри какой-то функции.
Как они создаются ? - через var
var a = 5; //объявление var создаёт свойство window.a
Какие проблемы связаны с использованием глобальных переменных? - при 'поднятии' переменных они равны undefined.

//5 task
//1 Создайте страницу на которой при запуске всплывает окно с полем для ввода имени,
//потом при закрытии окна сохраните имя в переменной и выведите его в консоль или на экран

var name = prompt('Введите имя');
console.log(name);

//2 С предыдущим примером проверьте будет ли имя больше чем ваше собственное,
//если да то выводите его в консоль если нет то выведите alert с сообщением что мое имя короче чем ваше

var myName = 'Sasha';
if (name.length > myName.length){
	console.log(name);
} alert ('мое имя дольше чем ваше');

// 6 task

for (var i = 1; i <= 10; i++){
	if (i == 5){
		alert(5);
}
	if (i == 9){
		break;
}
}
// 7 task
//Напишите функцию подсчета факториала числа, но каждый раз возвращая факториал умножайте его на 2 если число четное.
function factorial(number){
	if (number == 1){
	return 1;
	}
	var result = number;
	for (var i = 1; i < number; i++){
		result *= i;
	}
	if (result % 2 === 0){
		return result*2;
} else return result;
}
factorial(3);

// 8 task
5-10 min
<commit_msg>Delete functions.js<commit_after><|endoftext|>


<commit_before>
/*
 * Copyright (c) Burak Arslan (burak.arslan-qx@arskom.com.tr).
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Arskom Consultancy Ltd. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

qx.Class.define("soap.Parameters", {extend : qx.core.Object
    ,include : [qx.locale.MTranslation]
    ,construct : function() {
        this.__pl=new Object();
    }

    ,members : {
        __pl : null

        ,__decode_array : function(doc, parent, value, cache) {
            for (var i=0, l=value.length; i<l; ++i) {
                var p_ns = parent.parentNode.namespaceURI;
                var p_ln;

                if (qx.core.Variant.isSet("qx.client", "mshtml")) {
                    p_ln = parent.parentNode.baseName;
                }
                else {
                    p_ln = parent.parentNode.localName;
                }

                var type_name = cache.schema[p_ns].complex[p_ln].children[0].type
                var type_ns = cache.type_qname_to_ns(parent, type_name);
                var type_local = type_name.split(":")[1];
                var type_defn = cache.schema[type_ns].complex[type_local];
                var child_name = type_defn.children[0].name;

                var child = soap.Client.createSubElementNS(
                          doc,parent,child_name,parent.namespaceURI);

                this.__serialize(doc, child, value[i], cache);
            }
        }

        ,__serialize : function(doc, parent, value, cache) {
            var t = typeof(value);
            var child;
            var _ns_xsd = "http://www.w3.org/2001/XMLSchema"
            var _ns_xsi = "http://www.w3.org/2001/XMLSchema-instance"

            if (value == null) {
                soap.Client.setAttributeNS(doc, parent, "xsi:nil", _ns_xsi, 1);
            }
            else if (t == "string") {
                parent.appendChild(doc.createTextNode(value));
            }
            else if (t == "number" || t == "boolean") {
                parent.appendChild(doc.createTextNode(value.toString()));
            }
            else if (t == "object") {
                if (value instanceof qx.locale.LocalizedString) {
                    parent.appendChild(doc.createTextNode(value.toString()));
                }
                else if (value instanceof Date) {
                    var year = value.getFullYear().toString();
                    var month = (value.getMonth() + 1).toString();

                    month = (month.length == 1) ? "0" + month : month;

                    var date = value.getDate().toString();
                    date = (date.length == 1) ? "0" + date : date;

                    var hours = value.getHours().toString();
                    hours = (hours.length == 1) ? "0" + hours : hours;

                    var minutes = value.getMinutes().toString();
                    minutes = (minutes.length == 1) ? "0" + minutes : minutes;

                    var seconds = value.getSeconds().toString();
                    seconds = (seconds.length == 1) ? "0" + seconds : seconds;

                    var milliseconds = value.getMilliseconds().toString();
                    var tzminutes = Math.abs(value.getTimezoneOffset());
                    var tzhours = 0;

                    while(tzminutes >= 60) {
                        tzhours++;
                        tzminutes -= 60;
                    }
                    tzminutes = (tzminutes.toString().length == 1) ?
                              "0" + tzminutes.toString() : tzminutes.toString();
                    tzhours = (tzhours.toString().length == 1) ? "0" +
                                        tzhours.toString() : tzhours.toString();
                    var timezone = ((value.getTimezoneOffset() < 0) ? "+" : "-")
                                                    + tzhours + ":" + tzminutes;

                    value = year + "-" + month + "-" + date + "T"
                            + hours + ":" + minutes + ":" + seconds + "."
                            + milliseconds + timezone;

                    parent.appendChild(doc.createTextNode(value));
                }
                else if (value instanceof Number) {
                    parent.appendChild(doc.createTextNode(value.toString()));
                }
                // Array
                else if(value instanceof Array) {
                    for(var name in value) {
                        if (value.hasOwnProperty(name)) {
                            if(!isNaN(name)) { // contiguous array
                                this.__decode_array(doc, parent, value, cache);
                                break;
                            }
                            else { // associative array
                                child = soap.Client.createSubElementNS(doc,
                                             parent, name, parent.namespaceURI);
                                this.__serialize(doc, child, value[name], cache);
                            }
                        }
                    }
                }
                else if (qx.xml.Document.isXmlDocument(value)) {
                    parent.appendChild(value);
                }
                else { // Object or custom function
                    var props = qx.util.PropertyUtil.getProperties(
                                                             value.constructor);
                    for(var k in props) {
                        if (props.hasOwnProperty(k)) {
                            var getter = "get" + k;
                            var data = value[getter]();

                            var ns = eval(value.classname).TYPE_DEFINITION.ns;

                            var key = k.slice(1);
                            child = soap.Client.createSubElementNS(doc,
                                                               parent, key, ns);
                            this.__serialize(doc, child, data, cache);
                        }
                    }
                }
            }
        }

        ,add : function(name, value) {
            if (value == null || value + "" == "undefined") {
                return this;
            }

            this.__pl[name] = value;
            return this;
        }

        ,get_argument : function(name) {
            return this.__pl[name];
        }

        ,to_xml : function(doc, parent, cache) {
            for(var name in this.__pl) {
                if (this.__pl.hasOwnProperty(name)) {
                    var child = soap.Client.createSubElementNS(doc, parent,
                                            name, cache.get_target_namespace());
                    this.__serialize(doc, child, this.__pl[name], cache);
                }
            }
        }
    }
});
<commit_msg>miliseconds now get properly serialized.<commit_after>
/*
 * Copyright (c) Burak Arslan (burak.arslan-qx@arskom.com.tr).
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Arskom Consultancy Ltd. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

qx.Class.define("soap.Parameters", {extend : qx.core.Object
    ,include : [qx.locale.MTranslation]
    ,construct : function() {
        this.__pl=new Object();
    }

    ,members : {
        __pl : null

        ,__decode_array : function(doc, parent, value, cache) {
            for (var i=0, l=value.length; i<l; ++i) {
                var p_ns = parent.parentNode.namespaceURI;
                var p_ln;

                if (qx.core.Variant.isSet("qx.client", "mshtml")) {
                    p_ln = parent.parentNode.baseName;
                }
                else {
                    p_ln = parent.parentNode.localName;
                }

                var type_name = cache.schema[p_ns].complex[p_ln].children[0].type
                var type_ns = cache.type_qname_to_ns(parent, type_name);
                var type_local = type_name.split(":")[1];
                var type_defn = cache.schema[type_ns].complex[type_local];
                var child_name = type_defn.children[0].name;

                var child = soap.Client.createSubElementNS(
                          doc,parent,child_name,parent.namespaceURI);

                this.__serialize(doc, child, value[i], cache);
            }
        }

        ,__serialize : function(doc, parent, value, cache) {
            var t = typeof(value);
            var child;
            var _ns_xsd = "http://www.w3.org/2001/XMLSchema"
            var _ns_xsi = "http://www.w3.org/2001/XMLSchema-instance"

            if (value == null) {
                soap.Client.setAttributeNS(doc, parent, "xsi:nil", _ns_xsi, 1);
            }
            else if (t == "string") {
                parent.appendChild(doc.createTextNode(value));
            }
            else if (t == "number" || t == "boolean") {
                parent.appendChild(doc.createTextNode(value.toString()));
            }
            else if (t == "object") {
                if (value instanceof qx.locale.LocalizedString) {
                    parent.appendChild(doc.createTextNode(value.toString()));
                }
                else if (value instanceof Date) {
                    var year = value.getFullYear().toString();
                    var month = (value.getMonth() + 1).toString();

                    month = (month.length == 1) ? "0" + month : month;

                    var date = value.getDate().toString();
                    date = (date.length == 1) ? "0" + date : date;

                    var hours = value.getHours().toString();
                    hours = (hours.length == 1) ? "0" + hours : hours;

                    var minutes = value.getMinutes().toString();
                    minutes = (minutes.length == 1) ? "0" + minutes : minutes;

                    var seconds = value.getSeconds().toString();
                    seconds = (seconds.length == 1) ? "0" + seconds : seconds;

                    var miliseconds = value.getMilliseconds().toString();
                    while (miliseconds.length < 3) {
                        miliseconds = "0" + miliseconds;
                    }

                    var tzminutes = Math.abs(value.getTimezoneOffset());
                    var tzhours = 0;

                    while(tzminutes >= 60) {
                        tzhours++;
                        tzminutes -= 60;
                    }
                    tzminutes = (tzminutes.toString().length == 1) ?
                              "0" + tzminutes.toString() : tzminutes.toString();
                    tzhours = (tzhours.toString().length == 1) ? "0" +
                                        tzhours.toString() : tzhours.toString();
                    var timezone = ((value.getTimezoneOffset() < 0) ? "+" : "-")
                                                    + tzhours + ":" + tzminutes;

                    value = year + "-" + month + "-" + date + "T"
                            + hours + ":" + minutes + ":" + seconds + "."
                            + miliseconds + timezone;

                    parent.appendChild(doc.createTextNode(value));
                }
                else if (value instanceof Number) {
                    parent.appendChild(doc.createTextNode(value.toString()));
                }
                // Array
                else if(value instanceof Array) {
                    for(var name in value) {
                        if (value.hasOwnProperty(name)) {
                            if(!isNaN(name)) { // contiguous array
                                this.__decode_array(doc, parent, value, cache);
                                break;
                            }
                            else { // associative array
                                child = soap.Client.createSubElementNS(doc,
                                             parent, name, parent.namespaceURI);
                                this.__serialize(doc, child, value[name], cache);
                            }
                        }
                    }
                }
                else if (qx.xml.Document.isXmlDocument(value)) {
                    parent.appendChild(value);
                }
                else { // Object or custom function
                    var props = qx.util.PropertyUtil.getProperties(
                                                             value.constructor);
                    for(var k in props) {
                        if (props.hasOwnProperty(k)) {
                            var getter = "get" + k;
                            var data = value[getter]();

                            var ns = eval(value.classname).TYPE_DEFINITION.ns;

                            var key = k.slice(1);
                            child = soap.Client.createSubElementNS(doc,
                                                               parent, key, ns);
                            this.__serialize(doc, child, data, cache);
                        }
                    }
                }
            }
        }

        ,add : function(name, value) {
            if (value == null || value + "" == "undefined") {
                return this;
            }

            this.__pl[name] = value;
            return this;
        }

        ,get_argument : function(name) {
            return this.__pl[name];
        }

        ,to_xml : function(doc, parent, cache) {
            for(var name in this.__pl) {
                if (this.__pl.hasOwnProperty(name)) {
                    var child = soap.Client.createSubElementNS(doc, parent,
                                            name, cache.get_target_namespace());
                    this.__serialize(doc, child, this.__pl[name], cache);
                }
            }
        }
    }
});
<|endoftext|>


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

'use strict';

var util = require('util');

var profile = require('../../../util/profile');
var utils = require('../../../util/utils');

var $ = utils.getLocaleString;

exports.init = function (cli) {
    var log = cli.output;

    var usage = cli.category('usage')
      .description($('Command to view your aggregated Azure usage data'));

  usage.command('list [reportedStartTime] [reportedEndTime]')
      .description($('List the usage aggregates for a provided time range'))
      .option('--reportedStartTime <datetime>', $('The start of the time range to retrieve data for, in UTC format.'))
      .option('--reportedEndTime <datetime>', $('The end of the time range to retrieve data for, in UTC format.'))
      .option('--granularity <daily/hourly>', $('Value is either daily (default) or hourly to tell the API how to return the results grouped by day or hour.'))
      .option('--showDetails <bool>', $('When set to true (default), the aggregates are broken down into the instance metadata which is more granular.'))
      .option('--continuationToken <url>', $('Retrieved from previous calls, this is the bookmark used for progress when the responses are paged.'))
      .option('--subscription <subscription>', $('the subscription identifier'))
      .execute(function (reportedStartTime, reportedEndTime, options, _) {
    if (!reportedStartTime) {
	  reportedStartTime = cli.interaction.promptIfNotGiven($('reportedStartTime: '), reportedStartTime, _);
    }
    if (!reportedEndTime) {
	  reportedEndTime = cli.interaction.promptIfNotGiven($('reportedEndTime: '), reportedEndTime, _);
    }

    var subscription = profile.current.getSubscription(options.subscription);
    var client = utils.createUsageManagementClient(subscription);
    var progress = cli.interaction.progress($('Listing usage aggregates'));

    var result;
    try {
      result = client.usageAggregates.get(reportedStartTime, reportedEndTime, options.granularity, options.showDetails, options.continuationToken, _);
    } finally {
      progress.end();
    }

    cli.interaction.formatOutput(result.usageAggregations, function (data) {
      if (data.length > 0) {
        log.table(data, function (row, item) {
          row.cell($('Usage Start '), item.properties.usageStartTime);
          row.cell($('Usage End '), item.properties.usageEndTime);
          row.cell($('Meter Category '), item.properties.meterCategory);
          row.cell($('Meter Name '), item.properties.meterName);
          row.cell($('Quantity '), item.properties.quantity + ' ' + item.properties.unit);
        });
      }
      else {
        log.info(util.format($('No usage aggregates found for that time period.')));
      }
    });

    cli.interaction.formatOutput(result, function (data) {
      if (data.nextLink !== undefined) {
        log.info('continuationToken for continued results: ' + data.nextLink);
      }
    });

  });
};

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

'use strict';

var util = require('util');

var profile = require('../../../util/profile');
var utils = require('../../../util/utils');

var $ = utils.getLocaleString;

exports.init = function (cli) {
    var log = cli.output;

    var usage = cli.category('usage')
      .description($('Command to view your aggregated Azure usage data'));

  usage.command('list [reportedStartTime] [reportedEndTime]')
      .description($('List the usage aggregates for a provided time range'))
      .option('--reportedStartTime <datetime>', $('The start of the time range to retrieve data for, in \'yyyy-mm-dd\' format.'))
      .option('--reportedEndTime <datetime>', $('The end of the time range to retrieve data for, in \'yyyy-mm-dd\' format.'))
      .option('--granularity <daily/hourly>', $('Value is either daily (default) or hourly to tell the API how to return the results grouped by day or hour.'))
      .option('--showDetails <bool>', $('When set to true (default), the aggregates are broken down into the instance metadata which is more granular.'))
      .option('--continuationToken <url>', $('Retrieved from previous calls, this is the bookmark used for progress when the responses are paged.'))
      .option('--subscription <subscription>', $('the subscription identifier'))
      .execute(function (reportedStartTime, reportedEndTime, options, _) {
    if (!reportedStartTime) {
	  reportedStartTime = cli.interaction.promptIfNotGiven($('reportedStartTime: '), reportedStartTime, _);
    }
    if (!reportedEndTime) {
	  reportedEndTime = cli.interaction.promptIfNotGiven($('reportedEndTime: '), reportedEndTime, _);
    }

    var subscription = profile.current.getSubscription(options.subscription);
    var client = utils.createUsageManagementClient(subscription);
    var progress = cli.interaction.progress($('Listing usage aggregates'));

    var result;
    try {
      result = client.usageAggregates.get(reportedStartTime, reportedEndTime, options.granularity, options.showDetails, options.continuationToken, _);
    } finally {
      progress.end();
    }

    cli.interaction.formatOutput(result.usageAggregations, function (data) {
      if (data.length > 0) {
        log.table(data, function (row, item) {
          row.cell($('Usage Start '), item.properties.usageStartTime);
          row.cell($('Usage End '), item.properties.usageEndTime);
          row.cell($('Meter Category '), item.properties.meterCategory);
          row.cell($('Meter Name '), item.properties.meterName);
          row.cell($('Quantity '), item.properties.quantity + ' ' + item.properties.unit);
        });
      }
      else {
        log.info(util.format($('No usage aggregates found for that time period.')));
      }
    });

    cli.interaction.formatOutput(result, function (data) {
      if (data.nextLink !== undefined) {
        log.info('continuationToken for continued results: ' + data.nextLink);
      }
    });

  });
};

<|endoftext|>


<commit_before>const debug = require("debug")("compile:run"); // eslint-disable-line no-unused-vars
const OS = require("os");
const semver = require("semver");
const CompileError = require("./compileerror");
const CompilerSupplier = require("./compilerSupplier");

async function run(rawSources, options) {
  if (Object.keys(rawSources).length === 0) {
    return {
      contracts: [],
      sourceIndexes: [],
      compiler: {
        name: undefined,
        version: undefined
      }
    };
  }

  // Ensure sources have operating system independent paths
  // i.e., convert backslashes to forward slashes; things like C: are left intact.
  const { sources, targets, originalSourcePaths } = collectSources(
    rawSources,
    options.compilationTargets
  );

  // construct solc compiler input
  const compilerInput = prepareCompilerInput({
    sources,
    targets,
    settings: options.compilers.solc.settings
  });

  // perform compilation
  const { compilerOutput, solcVersion } = await invokeCompiler({
    compilerInput,
    options
  });

  // handle warnings as errors if options.strict
  // log if not options.quiet
  const { warnings, errors } = detectErrors({
    compilerOutput,
    options,
    solcVersion
  });
  if (warnings.length > 0) {
    options.events.emit("compile:warnings", { warnings });
  }

  if (errors.length > 0) {
    if (!options.quiet) {
      options.logger.log("");
    }

    throw new CompileError(errors);
  }

  // success case
  // returns Compilation - see @truffle/compile-common
  return {
    sourceIndexes: processSources({
      compilerOutput,
      originalSourcePaths
    }),
    contracts: processContracts({
      sources,
      compilerOutput,
      solcVersion,
      originalSourcePaths
    }),
    compiler: {
      name: "solc",
      version: solcVersion
    }
  };
}

function orderABI({ abi, contractName, ast }) {
  // AST can have multiple contract definitions, make sure we have the
  // one that matches our contract
  const contractDefinition = ast.nodes.find(
    ({ nodeType, name }) =>
      nodeType === "ContractDefinition" && name === contractName
  );

  if (!contractDefinition || !contractDefinition.nodes) {
    return abi;
  }

  // Find all function definitions
  const orderedFunctionNames = contractDefinition.nodes
    .filter(({ nodeType }) => nodeType === "FunctionDefinition")
    .map(({ name: functionName }) => functionName);

  // Put function names in a hash with their order, lowest first, for speed.
  const functionIndexes = orderedFunctionNames
    .map((functionName, index) => ({ [functionName]: index }))
    .reduce((a, b) => Object.assign({}, a, b), {});

  // Construct new ABI with functions at the end in source order
  return [
    ...abi.filter(({ name }) => functionIndexes[name] === undefined),

    // followed by the functions in the source order
    ...abi
      .filter(({ name }) => functionIndexes[name] !== undefined)
      .sort(
        ({ name: a }, { name: b }) => functionIndexes[a] - functionIndexes[b]
      )
  ];
}

/**
 * Collects sources, targets into collections with OS-independent paths,
 * along with a reverse mapping to the original path (for post-processing)
 *
 * @param originalSources - { [originalSourcePath]: contents }
 * @param originalTargets - originalSourcePath[]
 * @return { sources, targets, originalSourcePaths }
 */
function collectSources(originalSources, originalTargets = []) {
  const mappedResults = Object.entries(originalSources)
    .map(([originalSourcePath, contents]) => ({
      originalSourcePath,
      contents,
      sourcePath: getPortableSourcePath(originalSourcePath)
    }))
    .map(({ originalSourcePath, sourcePath, contents }) => ({
      sources: {
        [sourcePath]: contents
      },

      // include transformed form as target if original is a target
      targets: originalTargets.includes(originalSourcePath) ? [sourcePath] : [],

      originalSourcePaths: {
        [sourcePath]: originalSourcePath
      }
    }));

  const defaultAccumulator = {
    sources: {},
    targets: [],
    originalSourcePaths: {}
  };

  return mappedResults.reduce(
    (accumulator, result) => ({
      sources: Object.assign({}, accumulator.sources, result.sources),
      targets: [...accumulator.targets, ...result.targets],
      originalSourcePaths: Object.assign(
        {},
        accumulator.originalSourcePaths,
        result.originalSourcePaths
      )
    }),
    defaultAccumulator
  );
}

/**
 * @param sourcePath - string
 * @return string - operating system independent path
 * @private
 */
function getPortableSourcePath(sourcePath) {
  // Turn all backslashes into forward slashes
  var replacement = sourcePath.replace(/\\/g, "/");

  // Turn G:/.../ into /G/.../ for Windows
  if (replacement.length >= 2 && replacement[1] === ":") {
    replacement = "/" + replacement;
    replacement = replacement.replace(":", "");
  }

  return replacement;
}

/**
 * @param sources - { [sourcePath]: contents }
 * @param targets - sourcePath[]
 * @param setings - subset of Solidity settings
 * @return solc compiler input JSON
 */
function prepareCompilerInput({ sources, targets, settings }) {
  return {
    language: "Solidity",
    sources: prepareSources({ sources }),
    settings: {
      evmVersion: settings.evmVersion,
      optimizer: settings.optimizer,
      remappings: settings.remappings,
      debug: settings.debug,
      metadata: settings.metadata,
      libraries: settings.libraries,
      // Specify compilation targets. Each target uses defaultSelectors,
      // defaulting to single target `*` if targets are unspecified
      outputSelection: prepareOutputSelection({ targets })
    }
  };
}

/**
 * Convert sources into solc compiler input format
 * @param sources - { [sourcePath]: string }
 * @return { [sourcePath]: { content: string } }
 */
function prepareSources({ sources }) {
  return Object.entries(sources)
    .map(([sourcePath, content]) => ({ [sourcePath]: { content } }))
    .reduce((a, b) => Object.assign({}, a, b), {});
}

/**
 * If targets are specified, specify output selectors for each individually.
 * Otherwise, just use "*" selector
 * @param targets - sourcePath[] | undefined
 */
function prepareOutputSelection({ targets = [] }) {
  const defaultSelectors = {
    "": ["legacyAST", "ast"],
    "*": [
      "abi",
      "metadata",
      "evm.bytecode.object",
      "evm.bytecode.linkReferences",
      "evm.bytecode.sourceMap",
      "evm.deployedBytecode.object",
      "evm.deployedBytecode.linkReferences",
      "evm.deployedBytecode.sourceMap",
      "evm.deployedBytecode.immutableReferences",
      "userdoc",
      "devdoc"
    ]
  };

  if (!targets.length) {
    return {
      "*": defaultSelectors
    };
  }

  return targets
    .map(target => ({ [target]: defaultSelectors }))
    .reduce((a, b) => Object.assign({}, a, b), {});
}

/**
 * Load solc and perform compilation
 */
async function invokeCompiler({ compilerInput, options }) {
  const supplierOptions = {
    parser: options.parser,
    events: options.events,
    solcConfig: options.compilers.solc
  };
  const supplier = new CompilerSupplier(supplierOptions);
  const { solc } = await supplier.load();
  const solcVersion = solc.version();

  // perform compilation
  const inputString = JSON.stringify(compilerInput);
  const outputString = solc.compile(inputString);
  const compilerOutput = JSON.parse(outputString);

  return {
    compilerOutput,
    solcVersion
  };
}

/**
 * Extract errors/warnings from compiler output based on strict mode setting
 * @return { errors: string, warnings: string }
 */
function detectErrors({
  compilerOutput: { errors: outputErrors },
  options,
  solcVersion
}) {
  outputErrors = outputErrors || [];
  const rawErrors = options.strict
    ? outputErrors
    : outputErrors.filter(({ severity }) => severity !== "warning");

  const rawWarnings = options.strict
    ? [] // none of those in strict mode
    : outputErrors.filter(({ severity }) => severity === "warning");

  // extract messages
  let errors = rawErrors.map(({ formattedMessage }) => formattedMessage).join();
  const warnings = rawWarnings.map(({ formattedMessage }) => formattedMessage);

  if (errors.includes("requires different compiler version")) {
    const contractSolcVer = errors.match(/pragma solidity[^;]*/gm)[0];
    const configSolcVer =
      options.compilers.solc.version || semver.valid(solcVersion);

    errors = errors.concat(
      [
        OS.EOL,
        `Error: Truffle is currently using solc ${configSolcVer}, `,
        `but one or more of your contracts specify "${contractSolcVer}".`,
        OS.EOL,
        `Please update your truffle config or pragma statement(s).`,
        OS.EOL,
        `(See https://truffleframework.com/docs/truffle/reference/configuration#compiler-configuration `,
        `for information on`,
        OS.EOL,
        `configuring Truffle to use a specific solc compiler version.)`
      ].join("")
    );
  }

  return { warnings, errors };
}

/**
 * Aggregate list of sources based on reported source index
 * Returns list transformed to use original source paths
 */
function processSources({ compilerOutput, originalSourcePaths }) {
  let files = [];

  for (let [sourcePath, { id }] of Object.entries(compilerOutput.sources)) {
    files[id] = originalSourcePaths[sourcePath];
  }

  return files;
}

/**
 * Converts compiler-output contracts into @truffle/compile-solidity's return format
 * Uses compiler contract output plus other information.
 */
function processContracts({
  compilerOutput,
  sources,
  originalSourcePaths,
  solcVersion
}) {
  if (!compilerOutput.contracts) return [];
  return (
    Object.entries(compilerOutput.contracts)
      // map to [[{ source, contractName, contract }]]
      .map(([sourcePath, sourceContracts]) =>
        Object.entries(sourceContracts).map(([contractName, contract]) => ({
          contractName,
          contract,
          source: {
            ast: compilerOutput.sources[sourcePath].ast,
            legacyAST: compilerOutput.sources[sourcePath].legacyAST,
            contents: sources[sourcePath],
            sourcePath
          }
        }))
      )
      // and flatten
      .reduce((a, b) => [...a, ...b], [])

      // All source will have a key, but only the compiled source will have
      // the evm output.
      .filter(({ contract: { evm } }) => Object.keys(evm).length > 0)

      // convert to output format
      .map(
        ({
          contractName,
          contract: {
            evm: {
              bytecode: { sourceMap, linkReferences, object: bytecode },
              deployedBytecode: {
                sourceMap: deployedSourceMap,
                linkReferences: deployedLinkReferences,
                immutableReferences,
                object: deployedBytecode
              }
            },
            abi,
            metadata,
            devdoc,
            userdoc
          },
          source: {
            ast,
            legacyAST,
            sourcePath: transformedSourcePath,
            contents: source
          }
        }) => ({
          contractName,
          abi: orderABI({ abi, contractName, ast }),
          metadata,
          devdoc,
          userdoc,
          sourcePath: originalSourcePaths[transformedSourcePath],
          source,
          sourceMap,
          deployedSourceMap,
          ast,
          legacyAST,
          bytecode: zeroLinkReferences({
            bytes: bytecode,
            linkReferences: formatLinkReferences(linkReferences)
          }),
          deployedBytecode: zeroLinkReferences({
            bytes: deployedBytecode,
            linkReferences: formatLinkReferences(deployedLinkReferences)
          }),
          immutableReferences, //ideally this would be part of the deployedBytecode object,
          //but compatibility makes that impossible
          compiler: {
            name: "solc",
            version: solcVersion
          }
        })
      )
  );
}

function formatLinkReferences(linkReferences) {
  // convert to flat list
  const libraryLinkReferences = Object.values(linkReferences)
    .map(fileLinks =>
      Object.entries(fileLinks).map(([name, links]) => ({
        name,
        links
      }))
    )
    .reduce((a, b) => [...a, ...b], []);

  // convert to { offsets, length, name } format
  return libraryLinkReferences.map(({ name, links }) => ({
    offsets: links.map(({ start }) => start),
    length: links[0].length, // HACK just assume they're going to be the same
    name
  }));
}

// takes linkReferences in output format (not Solidity's format)
function zeroLinkReferences({ bytes, linkReferences }) {
  // inline link references - start by flattening the offsets
  const flattenedLinkReferences = linkReferences
    // map each link ref to array of link refs with only one offset
    .map(({ offsets, length, name }) =>
      offsets.map(offset => ({ offset, length, name }))
    )
    // flatten
    .reduce((a, b) => [...a, ...b], []);

  // then overwite bytes with zeroes
  bytes = flattenedLinkReferences.reduce((bytes, { offset, length }) => {
    // length is a byte offset
    const characterLength = length * 2;
    const start = offset * 2;

    const zeroes = "0".repeat(characterLength);

    return `${bytes.substring(0, start)}${zeroes}${bytes.substring(
      start + characterLength
    )}`;
  }, bytes);

  return { bytes, linkReferences };
}

module.exports = { run };
<commit_msg>Make run method return null when no sources are input<commit_after>const debug = require("debug")("compile:run"); // eslint-disable-line no-unused-vars
const OS = require("os");
const semver = require("semver");
const CompileError = require("./compileerror");
const CompilerSupplier = require("./compilerSupplier");

// this function returns a Compilation - legacy/index.js and ./index.js
// both check to make sure rawSources exist before calling this method
// however, there is a check here that returns null if no sources exist
async function run(rawSources, options) {
  if (Object.keys(rawSources).length === 0) {
    return null;
  }

  // Ensure sources have operating system independent paths
  // i.e., convert backslashes to forward slashes; things like C: are left intact.
  const { sources, targets, originalSourcePaths } = collectSources(
    rawSources,
    options.compilationTargets
  );

  // construct solc compiler input
  const compilerInput = prepareCompilerInput({
    sources,
    targets,
    settings: options.compilers.solc.settings
  });

  // perform compilation
  const { compilerOutput, solcVersion } = await invokeCompiler({
    compilerInput,
    options
  });

  // handle warnings as errors if options.strict
  // log if not options.quiet
  const { warnings, errors } = detectErrors({
    compilerOutput,
    options,
    solcVersion
  });
  if (warnings.length > 0) {
    options.events.emit("compile:warnings", { warnings });
  }

  if (errors.length > 0) {
    if (!options.quiet) {
      options.logger.log("");
    }

    throw new CompileError(errors);
  }

  // success case
  // returns Compilation - see @truffle/compile-common
  return {
    sourceIndexes: processSources({
      compilerOutput,
      originalSourcePaths
    }),
    contracts: processContracts({
      sources,
      compilerOutput,
      solcVersion,
      originalSourcePaths
    }),
    compiler: {
      name: "solc",
      version: solcVersion
    }
  };
}

function orderABI({ abi, contractName, ast }) {
  // AST can have multiple contract definitions, make sure we have the
  // one that matches our contract
  const contractDefinition = ast.nodes.find(
    ({ nodeType, name }) =>
      nodeType === "ContractDefinition" && name === contractName
  );

  if (!contractDefinition || !contractDefinition.nodes) {
    return abi;
  }

  // Find all function definitions
  const orderedFunctionNames = contractDefinition.nodes
    .filter(({ nodeType }) => nodeType === "FunctionDefinition")
    .map(({ name: functionName }) => functionName);

  // Put function names in a hash with their order, lowest first, for speed.
  const functionIndexes = orderedFunctionNames
    .map((functionName, index) => ({ [functionName]: index }))
    .reduce((a, b) => Object.assign({}, a, b), {});

  // Construct new ABI with functions at the end in source order
  return [
    ...abi.filter(({ name }) => functionIndexes[name] === undefined),

    // followed by the functions in the source order
    ...abi
      .filter(({ name }) => functionIndexes[name] !== undefined)
      .sort(
        ({ name: a }, { name: b }) => functionIndexes[a] - functionIndexes[b]
      )
  ];
}

/**
 * Collects sources, targets into collections with OS-independent paths,
 * along with a reverse mapping to the original path (for post-processing)
 *
 * @param originalSources - { [originalSourcePath]: contents }
 * @param originalTargets - originalSourcePath[]
 * @return { sources, targets, originalSourcePaths }
 */
function collectSources(originalSources, originalTargets = []) {
  const mappedResults = Object.entries(originalSources)
    .map(([originalSourcePath, contents]) => ({
      originalSourcePath,
      contents,
      sourcePath: getPortableSourcePath(originalSourcePath)
    }))
    .map(({ originalSourcePath, sourcePath, contents }) => ({
      sources: {
        [sourcePath]: contents
      },

      // include transformed form as target if original is a target
      targets: originalTargets.includes(originalSourcePath) ? [sourcePath] : [],

      originalSourcePaths: {
        [sourcePath]: originalSourcePath
      }
    }));

  const defaultAccumulator = {
    sources: {},
    targets: [],
    originalSourcePaths: {}
  };

  return mappedResults.reduce(
    (accumulator, result) => ({
      sources: Object.assign({}, accumulator.sources, result.sources),
      targets: [...accumulator.targets, ...result.targets],
      originalSourcePaths: Object.assign(
        {},
        accumulator.originalSourcePaths,
        result.originalSourcePaths
      )
    }),
    defaultAccumulator
  );
}

/**
 * @param sourcePath - string
 * @return string - operating system independent path
 * @private
 */
function getPortableSourcePath(sourcePath) {
  // Turn all backslashes into forward slashes
  var replacement = sourcePath.replace(/\\/g, "/");

  // Turn G:/.../ into /G/.../ for Windows
  if (replacement.length >= 2 && replacement[1] === ":") {
    replacement = "/" + replacement;
    replacement = replacement.replace(":", "");
  }

  return replacement;
}

/**
 * @param sources - { [sourcePath]: contents }
 * @param targets - sourcePath[]
 * @param setings - subset of Solidity settings
 * @return solc compiler input JSON
 */
function prepareCompilerInput({ sources, targets, settings }) {
  return {
    language: "Solidity",
    sources: prepareSources({ sources }),
    settings: {
      evmVersion: settings.evmVersion,
      optimizer: settings.optimizer,
      remappings: settings.remappings,
      debug: settings.debug,
      metadata: settings.metadata,
      libraries: settings.libraries,
      // Specify compilation targets. Each target uses defaultSelectors,
      // defaulting to single target `*` if targets are unspecified
      outputSelection: prepareOutputSelection({ targets })
    }
  };
}

/**
 * Convert sources into solc compiler input format
 * @param sources - { [sourcePath]: string }
 * @return { [sourcePath]: { content: string } }
 */
function prepareSources({ sources }) {
  return Object.entries(sources)
    .map(([sourcePath, content]) => ({ [sourcePath]: { content } }))
    .reduce((a, b) => Object.assign({}, a, b), {});
}

/**
 * If targets are specified, specify output selectors for each individually.
 * Otherwise, just use "*" selector
 * @param targets - sourcePath[] | undefined
 */
function prepareOutputSelection({ targets = [] }) {
  const defaultSelectors = {
    "": ["legacyAST", "ast"],
    "*": [
      "abi",
      "metadata",
      "evm.bytecode.object",
      "evm.bytecode.linkReferences",
      "evm.bytecode.sourceMap",
      "evm.deployedBytecode.object",
      "evm.deployedBytecode.linkReferences",
      "evm.deployedBytecode.sourceMap",
      "evm.deployedBytecode.immutableReferences",
      "userdoc",
      "devdoc"
    ]
  };

  if (!targets.length) {
    return {
      "*": defaultSelectors
    };
  }

  return targets
    .map(target => ({ [target]: defaultSelectors }))
    .reduce((a, b) => Object.assign({}, a, b), {});
}

/**
 * Load solc and perform compilation
 */
async function invokeCompiler({ compilerInput, options }) {
  const supplierOptions = {
    parser: options.parser,
    events: options.events,
    solcConfig: options.compilers.solc
  };
  const supplier = new CompilerSupplier(supplierOptions);
  const { solc } = await supplier.load();
  const solcVersion = solc.version();

  // perform compilation
  const inputString = JSON.stringify(compilerInput);
  const outputString = solc.compile(inputString);
  const compilerOutput = JSON.parse(outputString);

  return {
    compilerOutput,
    solcVersion
  };
}

/**
 * Extract errors/warnings from compiler output based on strict mode setting
 * @return { errors: string, warnings: string }
 */
function detectErrors({
  compilerOutput: { errors: outputErrors },
  options,
  solcVersion
}) {
  outputErrors = outputErrors || [];
  const rawErrors = options.strict
    ? outputErrors
    : outputErrors.filter(({ severity }) => severity !== "warning");

  const rawWarnings = options.strict
    ? [] // none of those in strict mode
    : outputErrors.filter(({ severity }) => severity === "warning");

  // extract messages
  let errors = rawErrors.map(({ formattedMessage }) => formattedMessage).join();
  const warnings = rawWarnings.map(({ formattedMessage }) => formattedMessage);

  if (errors.includes("requires different compiler version")) {
    const contractSolcVer = errors.match(/pragma solidity[^;]*/gm)[0];
    const configSolcVer =
      options.compilers.solc.version || semver.valid(solcVersion);

    errors = errors.concat(
      [
        OS.EOL,
        `Error: Truffle is currently using solc ${configSolcVer}, `,
        `but one or more of your contracts specify "${contractSolcVer}".`,
        OS.EOL,
        `Please update your truffle config or pragma statement(s).`,
        OS.EOL,
        `(See https://truffleframework.com/docs/truffle/reference/configuration#compiler-configuration `,
        `for information on`,
        OS.EOL,
        `configuring Truffle to use a specific solc compiler version.)`
      ].join("")
    );
  }

  return { warnings, errors };
}

/**
 * Aggregate list of sources based on reported source index
 * Returns list transformed to use original source paths
 */
function processSources({ compilerOutput, originalSourcePaths }) {
  let files = [];

  for (let [sourcePath, { id }] of Object.entries(compilerOutput.sources)) {
    files[id] = originalSourcePaths[sourcePath];
  }

  return files;
}

/**
 * Converts compiler-output contracts into @truffle/compile-solidity's return format
 * Uses compiler contract output plus other information.
 */
function processContracts({
  compilerOutput,
  sources,
  originalSourcePaths,
  solcVersion
}) {
  if (!compilerOutput.contracts) return [];
  return (
    Object.entries(compilerOutput.contracts)
      // map to [[{ source, contractName, contract }]]
      .map(([sourcePath, sourceContracts]) =>
        Object.entries(sourceContracts).map(([contractName, contract]) => ({
          contractName,
          contract,
          source: {
            ast: compilerOutput.sources[sourcePath].ast,
            legacyAST: compilerOutput.sources[sourcePath].legacyAST,
            contents: sources[sourcePath],
            sourcePath
          }
        }))
      )
      // and flatten
      .reduce((a, b) => [...a, ...b], [])

      // All source will have a key, but only the compiled source will have
      // the evm output.
      .filter(({ contract: { evm } }) => Object.keys(evm).length > 0)

      // convert to output format
      .map(
        ({
          contractName,
          contract: {
            evm: {
              bytecode: { sourceMap, linkReferences, object: bytecode },
              deployedBytecode: {
                sourceMap: deployedSourceMap,
                linkReferences: deployedLinkReferences,
                immutableReferences,
                object: deployedBytecode
              }
            },
            abi,
            metadata,
            devdoc,
            userdoc
          },
          source: {
            ast,
            legacyAST,
            sourcePath: transformedSourcePath,
            contents: source
          }
        }) => ({
          contractName,
          abi: orderABI({ abi, contractName, ast }),
          metadata,
          devdoc,
          userdoc,
          sourcePath: originalSourcePaths[transformedSourcePath],
          source,
          sourceMap,
          deployedSourceMap,
          ast,
          legacyAST,
          bytecode: zeroLinkReferences({
            bytes: bytecode,
            linkReferences: formatLinkReferences(linkReferences)
          }),
          deployedBytecode: zeroLinkReferences({
            bytes: deployedBytecode,
            linkReferences: formatLinkReferences(deployedLinkReferences)
          }),
          immutableReferences, //ideally this would be part of the deployedBytecode object,
          //but compatibility makes that impossible
          compiler: {
            name: "solc",
            version: solcVersion
          }
        })
      )
  );
}

function formatLinkReferences(linkReferences) {
  // convert to flat list
  const libraryLinkReferences = Object.values(linkReferences)
    .map(fileLinks =>
      Object.entries(fileLinks).map(([name, links]) => ({
        name,
        links
      }))
    )
    .reduce((a, b) => [...a, ...b], []);

  // convert to { offsets, length, name } format
  return libraryLinkReferences.map(({ name, links }) => ({
    offsets: links.map(({ start }) => start),
    length: links[0].length, // HACK just assume they're going to be the same
    name
  }));
}

// takes linkReferences in output format (not Solidity's format)
function zeroLinkReferences({ bytes, linkReferences }) {
  // inline link references - start by flattening the offsets
  const flattenedLinkReferences = linkReferences
    // map each link ref to array of link refs with only one offset
    .map(({ offsets, length, name }) =>
      offsets.map(offset => ({ offset, length, name }))
    )
    // flatten
    .reduce((a, b) => [...a, ...b], []);

  // then overwite bytes with zeroes
  bytes = flattenedLinkReferences.reduce((bytes, { offset, length }) => {
    // length is a byte offset
    const characterLength = length * 2;
    const start = offset * 2;

    const zeroes = "0".repeat(characterLength);

    return `${bytes.substring(0, start)}${zeroes}${bytes.substring(
      start + characterLength
    )}`;
  }, bytes);

  return { bytes, linkReferences };
}

module.exports = { run };
<|endoftext|>