<commit_before>'use strict';

angular.module('mage').controller('FormCtrl', function ($scope, $injector, appConstants, FormService, Layer, Form, $filter, $timeout, ObservationService) {

    // preview form mode
    $scope.previewMode = false;

    $scope.fs = FormService;
    $scope.saveTime = 0;

    $scope.form = FormService.editForm;

    $scope.fileUploadOptions = {
    };

    $scope.$watch('fs.editForm', function(newForm, oldForm){
        $scope.form = FormService.editForm;
        if ($scope.form) {
            angular.forEach($scope.form.fields, function(field) {
                if (field.name == 'type') {
                    $scope.typeField = field;
                }
            });
         }
    });

    // previewForm - for preview purposes, form will be copied into this
    // otherwise, actual form might get manipulated in preview mode
    $scope.previewForm = {};

    $scope.fieldTypes = FormService.fields;
    $scope.newField = {
        "title" : "New field",
        "type" : $scope.fieldTypes[0].name,
        "value" : "",
        "required" : true
    };

    // accordion settings
    $scope.accordion = {}
    $scope.accordion.oneAtATime = true;
    $scope.variants = [];

    $scope.deletableField = function(field) {
      return field.name.indexOf('field') != -1;
    }

    // create new field button click
    $scope.addNewField = function() {

        // put newField into fields array

        var id = $scope.form.fields[$scope.form.fields.length-1].id + 1;

        $scope.newField.id = id;
        $scope.newField.name = "field" + id;
        $scope.form.fields.push($scope.newField);

        $scope.newField = {
            "title" : "New field",
            "type" : $scope.fieldTypes[0].name,
            "value" : "",
            "required" : true
        };

        $scope.autoSave();
    }

    var debounceHideSave = _.debounce(function() {
      $scope.$apply(function() {
        $scope.saved = false;
      });
    }, 5000);

    var debouncedAutoSave = _.debounce(function() {
      $scope.$apply(function() {
        if ($scope.form.id) {
          $scope.form.$save({}, function() {
            $scope.saved = true;
            ObservationService.updateForm();
            $timeout(function() {
              debounceHideSave();
            });
            console.log($scope.form);
          });
        }
      });
    }, 1000);

    $scope.$on('uploadComplete', function(event, args) {
      $scope.savedTime = Date.now();
    });

    $scope.autoSave = function() {
      debouncedAutoSave();
    }

    $scope.populateVariants = function(doNotAutoSave) {
      if (!$scope.form) return;
      $scope.variantField = _.find($scope.form.fields, function(field) {
        return field.name == $scope.form.variantField;
      });
      if (!$scope.variantField) {
        // they do not want a variant
        $scope.variants = [];
        $scope.form.variantField = null;
        if (!doNotAutoSave) {
          $scope.autoSave();
        }
        return;
      }
      //$scope.form.variantField = $scope.variantField.name;
      if ($scope.variantField.type == 'dropdown') {
        $scope.variants = $filter('orderBy')($scope.variantField.choices, 'value');
        $scope.showNumberVariants = false;
      } else if ($scope.variantField.type == 'date') {
        $scope.variantField.choices = $scope.variantField.choices || [];
        $scope.variants = $filter('orderBy')($scope.variantField.choices, 'value');
        $scope.showNumberVariants = true;
      }
      if (!doNotAutoSave) {
        $scope.autoSave();
      }
    }

    $scope.$watch('form', function() {
      if (!$scope.form) return;

      $scope.populateVariants();
    });

    $scope.$watch('form.fields', function() {
      if (!$scope.form || !$scope.form.fields) return;
      angular.forEach($scope.form.fields, function(field) {
          if (field.name == 'type') {
              $scope.typeField = field;
          }
      });
    });

    $scope.$watch('form.variantField', function() {
      if (!$scope.form || !$scope.form.variantField) return;
      $scope.populateVariants()
    })

    // deletes particular field on button click
    $scope.deleteField = function (id) {
      var deletedField = _.find($scope.form.fields, function(field) { return id == field.id});
      if (deletedField) {
        deletedField.archived = true;
        $scope.populateVariants();
        $scope.autoSave();
      }
    }

    $scope.variantFilter = function(field) {
      return (field.type == 'dropdown' || field.type == 'date') && field.name != 'type';
    }

    // add new option to the field
    $scope.addOption = function (field, optionTitle) {
      field.choices = field.choices || new Array();
      field.choices.push({
          "id" : field.choices.length,
          "title" : optionTitle,
          "value" : field.choices.length
      });
      $scope.populateVariants();
      $scope.autoSave();
    }

    $scope.removeVariant = function(variant) {
      $scope.variantField.choices = _.without($scope.variantField.choices, variant);
      $scope.variants = $filter('orderBy')($scope.variantField.choices, 'value');
      $scope.autoSave();
    }

    $scope.addVariantOption = function(min, max) {
      var newOption = {
          "id" : $scope.variantField.choices.length,
          "title" : min,
          "value" : min
      };

      $scope.variantField.choices = $scope.variantField.choices || new Array();
      $scope.variantField.choices.push(newOption);
      $scope.variants = $filter('orderBy')($scope.variantField.choices, 'value');
      $scope.autoSave();
    }

    $scope.addType = function() {
        $scope.addOption($scope.typeField);
        if ($scope.form.id) { $scope.form.$save(); }
    }

    // delete particular option
    $scope.deleteOption = function (field, option){
        for(var i = 0; i < field.choices.length; i++){
            if(field.choices[i].id == option.id){
                field.choices.splice(i, 1);
                break;
            }
        }
        $scope.populateVariants();
        $scope.autoSave();
    }

    // preview form
    $scope.previewOn = function(){
        if($scope.form.fields == null || $scope.form.fields.length == 0) {
            var title = 'Error';
            var msg = 'No fields added yet, please add fields to the form before preview.';
            var btns = [{result:'ok', label: 'OK', cssCl***REMOVED***: 'btn-primary'}];

            //$modal.messageBox(title, msg, btns).open();

        }
        else {
            $scope.previewMode = true;
            angular.copy($scope.form, $scope.previewForm);
        }
    }

    // hide preview form, go back to create mode
    $scope.previewOff = function(){
        $scope.previewMode = false;
    }

    // decides whether field options block will be shown (true for dropdown and radio fields)
    $scope.showAddOptions = function (field){
        if(field.type == "radio" || field.type == "dropdown")
            return true;
        else
            return false;
    }

    // deletes all the fields
    $scope.reset = function (){
        $scope.form.fields.splice(0, $scope.form.fields.length);
    }

    $scope.saveForm = function() {
        $scope.form.$save();
    }

    $scope.useForm = function(form) {
      $scope.form.$save({}, function(savedForm) {
        $scope.setFeatureForm(form);
      });
    }

    $scope.deleteForm = function(layer) {
      var modalInstance = $injector.get('$modal').open({
        templateUrl: 'deleteForm.html',
        resolve: {
          form: function () {
            return $scope.form;
          }
        },
        controller: function ($scope, $modalInstance, form) {
          $scope.form = form;

          $scope.deleteForm = function(form, force) {
            console.info('delete form');
            form.$delete(function(success) {
              console.info('form delete success');
              $modalInstance.close(form);
            });
          }
          $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
          };
        }
      });

      modalInstance.result.then(function (form) {
        console.info('success');
        $scope.form = null;
        $scope.removeForm(form);
      }, function () {
        console.info('failure');
      });
      return;
    }

    $scope.setFeatureForm = function(form) {
      var layers = Layer.query(function(){
        angular.forEach(layers, function (layer) {
          if (layer.type == 'Feature') {
            layer.formId = form.id;
            layer.$save({}, function() {
              appConstants.formId = form.id;
              ObservationService.updateForm();
            });
          }
        });
      });
    }
});
<commit_msg>fix the case when choosing a no variant<commit_after>'use strict';

angular.module('mage').controller('FormCtrl', function ($scope, $injector, appConstants, FormService, Layer, Form, $filter, $timeout, ObservationService) {

    // preview form mode
    $scope.previewMode = false;

    $scope.fs = FormService;
    $scope.saveTime = 0;

    $scope.form = FormService.editForm;

    $scope.fileUploadOptions = {
    };

    $scope.$watch('fs.editForm', function(newForm, oldForm){
        $scope.form = FormService.editForm;
        if ($scope.form) {
            angular.forEach($scope.form.fields, function(field) {
                if (field.name == 'type') {
                    $scope.typeField = field;
                }
            });
         }
    });

    // previewForm - for preview purposes, form will be copied into this
    // otherwise, actual form might get manipulated in preview mode
    $scope.previewForm = {};

    $scope.fieldTypes = FormService.fields;
    $scope.newField = {
        "title" : "New field",
        "type" : $scope.fieldTypes[0].name,
        "value" : "",
        "required" : true
    };

    // accordion settings
    $scope.accordion = {}
    $scope.accordion.oneAtATime = true;
    $scope.variants = [];

    $scope.deletableField = function(field) {
      return field.name.indexOf('field') != -1;
    }

    // create new field button click
    $scope.addNewField = function() {

        // put newField into fields array

        var id = $scope.form.fields[$scope.form.fields.length-1].id + 1;

        $scope.newField.id = id;
        $scope.newField.name = "field" + id;
        $scope.form.fields.push($scope.newField);

        $scope.newField = {
            "title" : "New field",
            "type" : $scope.fieldTypes[0].name,
            "value" : "",
            "required" : true
        };

        $scope.autoSave();
    }

    var debounceHideSave = _.debounce(function() {
      $scope.$apply(function() {
        $scope.saved = false;
      });
    }, 5000);

    var debouncedAutoSave = _.debounce(function() {
      $scope.$apply(function() {
        if ($scope.form.id) {
          $scope.form.$save({}, function() {
            $scope.saved = true;
            ObservationService.updateForm();
            $timeout(function() {
              debounceHideSave();
            });
            console.log($scope.form);
          });
        }
      });
    }, 1000);

    $scope.$on('uploadComplete', function(event, args) {
      $scope.savedTime = Date.now();
    });

    $scope.autoSave = function() {
      debouncedAutoSave();
    }

    $scope.populateVariants = function(doNotAutoSave) {
      if (!$scope.form) return;
      $scope.variantField = _.find($scope.form.fields, function(field) {
        return field.name == $scope.form.variantField;
      });
      if (!$scope.variantField) {
        // they do not want a variant
        $scope.variants = [];
        $scope.form.variantField = null;
        if (!doNotAutoSave) {
          $scope.autoSave();
        }
        return;
      }
      //$scope.form.variantField = $scope.variantField.name;
      if ($scope.variantField.type == 'dropdown') {
        $scope.variants = $filter('orderBy')($scope.variantField.choices, 'value');
        $scope.showNumberVariants = false;
      } else if ($scope.variantField.type == 'date') {
        $scope.variantField.choices = $scope.variantField.choices || [];
        $scope.variants = $filter('orderBy')($scope.variantField.choices, 'value');
        $scope.showNumberVariants = true;
      }
      if (!doNotAutoSave) {
        $scope.autoSave();
      }
    }

    $scope.$watch('form', function() {
      if (!$scope.form) return;

      $scope.populateVariants();
    });

    $scope.$watch('form.fields', function() {
      if (!$scope.form || !$scope.form.fields) return;
      angular.forEach($scope.form.fields, function(field) {
          if (field.name == 'type') {
              $scope.typeField = field;
          }
      });
    });

    $scope.$watch('form.variantField', function(newValue, oldValue) {
      if (!$scope.form || newValue == oldValue) return;
      $scope.populateVariants()
    })

    // deletes particular field on button click
    $scope.deleteField = function (id) {
      var deletedField = _.find($scope.form.fields, function(field) { return id == field.id});
      if (deletedField) {
        deletedField.archived = true;
        $scope.populateVariants();
        $scope.autoSave();
      }
    }

    $scope.variantFilter = function(field) {
      return (field.type == 'dropdown' || field.type == 'date') && field.name != 'type';
    }

    // add new option to the field
    $scope.addOption = function (field, optionTitle) {
      field.choices = field.choices || new Array();
      field.choices.push({
          "id" : field.choices.length,
          "title" : optionTitle,
          "value" : field.choices.length
      });
      $scope.populateVariants();
      $scope.autoSave();
    }

    $scope.removeVariant = function(variant) {
      $scope.variantField.choices = _.without($scope.variantField.choices, variant);
      $scope.variants = $filter('orderBy')($scope.variantField.choices, 'value');
      $scope.autoSave();
    }

    $scope.addVariantOption = function(min, max) {
      var newOption = {
          "id" : $scope.variantField.choices.length,
          "title" : min,
          "value" : min
      };

      $scope.variantField.choices = $scope.variantField.choices || new Array();
      $scope.variantField.choices.push(newOption);
      $scope.variants = $filter('orderBy')($scope.variantField.choices, 'value');
      $scope.autoSave();
    }

    $scope.addType = function() {
        $scope.addOption($scope.typeField);
        if ($scope.form.id) { $scope.form.$save(); }
    }

    // delete particular option
    $scope.deleteOption = function (field, option){
        for(var i = 0; i < field.choices.length; i++){
            if(field.choices[i].id == option.id){
                field.choices.splice(i, 1);
                break;
            }
        }
        $scope.populateVariants();
        $scope.autoSave();
    }

    // preview form
    $scope.previewOn = function(){
        if($scope.form.fields == null || $scope.form.fields.length == 0) {
            var title = 'Error';
            var msg = 'No fields added yet, please add fields to the form before preview.';
            var btns = [{result:'ok', label: 'OK', cssCl***REMOVED***: 'btn-primary'}];

            //$modal.messageBox(title, msg, btns).open();

        }
        else {
            $scope.previewMode = true;
            angular.copy($scope.form, $scope.previewForm);
        }
    }

    // hide preview form, go back to create mode
    $scope.previewOff = function(){
        $scope.previewMode = false;
    }

    // decides whether field options block will be shown (true for dropdown and radio fields)
    $scope.showAddOptions = function (field){
        if(field.type == "radio" || field.type == "dropdown")
            return true;
        else
            return false;
    }

    // deletes all the fields
    $scope.reset = function (){
        $scope.form.fields.splice(0, $scope.form.fields.length);
    }

    $scope.saveForm = function() {
        $scope.form.$save();
    }

    $scope.useForm = function(form) {
      $scope.form.$save({}, function(savedForm) {
        $scope.setFeatureForm(form);
      });
    }

    $scope.deleteForm = function(layer) {
      var modalInstance = $injector.get('$modal').open({
        templateUrl: 'deleteForm.html',
        resolve: {
          form: function () {
            return $scope.form;
          }
        },
        controller: function ($scope, $modalInstance, form) {
          $scope.form = form;

          $scope.deleteForm = function(form, force) {
            console.info('delete form');
            form.$delete(function(success) {
              console.info('form delete success');
              $modalInstance.close(form);
            });
          }
          $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
          };
        }
      });

      modalInstance.result.then(function (form) {
        console.info('success');
        $scope.form = null;
        $scope.removeForm(form);
      }, function () {
        console.info('failure');
      });
      return;
    }

    $scope.setFeatureForm = function(form) {
      var layers = Layer.query(function(){
        angular.forEach(layers, function (layer) {
          if (layer.type == 'Feature') {
            layer.formId = form.id;
            layer.$save({}, function() {
              appConstants.formId = form.id;
              ObservationService.updateForm();
            });
          }
        });
      });
    }
});
<|endoftext|>


<commit_before>'use strict';

const EventEmitter = require('events').EventEmitter;
const Log          = require('ipfs-log');
const Index        = require('./Index');
const Cache        = require('./Cache');

class Store {
  constructor(ipfs, id, dbname, options) {
    this.id = id;
    this.dbname = dbname;
    this.events = new EventEmitter();

    if(!options) options = {};
    if(!options.Index) Object.assign(options, { Index: Index });
    if(!options.cacheFile) Object.assign(options, { cacheFile: null });

    this.options = options;
    this._index = new this.options.Index(this.id);
    this._oplog = null;
    this._ipfs = ipfs;
    this._lastWrite = null;
  }

  use() {
    this.events.emit('load', this.dbname);
    this._oplog = new Log(this._ipfs, this.id, this.dbname, this.options);
    return Cache.loadCache(this.options.cacheFile).then(() => {
      const cached = Cache.get(this.dbname);
      if(cached) {
        return Log.fromIpfsHash(this._ipfs, cached)
          .then((log) => this._oplog.join(log))
          .then((merged) => this._index.updateIndex(this._oplog, merged))
          .then(() => this.events.emit('ready', this.dbname))
          .then(() => this);
      }

      this.events.emit('ready', this.dbname)
      return Promise.resolve(this);
    });
  }

  close() {
    this.events.emit('close', this.dbname);
  }

  sync(hash) {
    if(!hash || hash === this._lastWrite)
      return Promise.resolve([]);

    const oldCount = this._oplog.items.length;
    let newItems = [];
    this.events.emit('sync', this.dbname);
    return Log.fromIpfsHash(this._ipfs, hash)
      .then((log) => this._oplog.join(log))
      .then((merged) => newItems = merged)
      .then(() => Cache.set(this.dbname, hash))
      .then(() => this._index.updateIndex(this._oplog, newItems))
      .then(() => {
        // if(newItems.length > 0)
          this.events.emit('updated', this.dbname, newItems);
      })
      .then(() => newItems)
  }

  delete() {
    this._index = new this.options.Index(this.id);
    if(this._oplog)
      this._oplog.clear();
  }

  _addOperation(data) {
    let result, logHash;
    if(this._oplog) {
      return this._oplog.add(data)
        .then((res) => result = res)
        .then(() => Log.getIpfsHash(this._ipfs, this._oplog))
        .then((hash) => logHash = hash)
        .then(() => this._lastWrite = logHash)
        .then(() => Cache.set(this.dbname, logHash))
        .then(() => this._index.updateIndex(this._oplog, [result]))
        .then(() => this.events.emit('data', this.dbname, logHash))
        .then(() => result.hash);
    }
  }
}

module.exports = Store;
<commit_msg>Fix startup loading problems<commit_after>'use strict';

const EventEmitter = require('events').EventEmitter;
const Log          = require('ipfs-log');
const Index        = require('./Index');
const Cache        = require('./Cache');

class Store {
  constructor(ipfs, id, dbname, options) {
    this.id = id;
    this.dbname = dbname;
    this.events = new EventEmitter();

    if(!options) options = {};
    if(!options.Index) Object.assign(options, { Index: Index });
    if(!options.cacheFile) Object.assign(options, { cacheFile: null });

    this.options = options;
    this._index = new this.options.Index(this.id);
    this._oplog = null;
    this._ipfs = ipfs;
    this._lastWrite = null;
  }

  use() {
    this.events.emit('load', this.dbname);
    this._oplog = new Log(this._ipfs, this.id, this.dbname, this.options);
    return Cache.loadCache(this.options.cacheFile).then(() => {
      const cached = Cache.get(this.dbname);
      if(cached) {
        this._lastWrite = cached;
        return Log.fromIpfsHash(this._ipfs, cached)
          .then((log) => this._oplog.join(log))
          .then((merged) => this._index.updateIndex(this._oplog, merged))
          .then(() => this.events.emit('ready', this.dbname))
          .then(() => this)
      }

      this.events.emit('ready', this.dbname)
      return Promise.resolve(this);
    });
  }

  close() {
    this.events.emit('close', this.dbname);
  }

  sync(hash) {
    if(!hash || hash === this._lastWrite) {
      this.events.emit('updated', this.dbname, []);
      return Promise.resolve([]);
    }

    const oldCount = this._oplog.items.length;
    let newItems = [];
    this.events.emit('sync', this.dbname);
    this._lastWrite = hash;
    return Log.fromIpfsHash(this._ipfs, hash)
      .then((log) => this._oplog.join(log))
      .then((merged) => newItems = merged)
      .then(() => Cache.set(this.dbname, hash))
      .then(() => this._index.updateIndex(this._oplog, newItems))
      .then(() => {
        // if(newItems.length > 0)
          this.events.emit('updated', this.dbname, newItems);
      })
      .then(() => newItems)
  }

  delete() {
    this._index = new this.options.Index(this.id);
    if(this._oplog)
      this._oplog.clear();
  }

  _addOperation(data) {
    let result, logHash;
    if(this._oplog) {
      return this._oplog.add(data)
        .then((res) => result = res)
        .then(() => Log.getIpfsHash(this._ipfs, this._oplog))
        .then((hash) => logHash = hash)
        .then(() => this._lastWrite = logHash)
        .then(() => Cache.set(this.dbname, logHash))
        .then(() => this._index.updateIndex(this._oplog, [result]))
        .then(() => this.events.emit('data', this.dbname, logHash))
        .then(() => result.hash);
    }
  }
}

module.exports = Store;
<|endoftext|>


<commit_before><commit_msg>Sort governor contest higher<commit_after><|endoftext|>


<commit_before>"use strict";

/*jshint node:true strict: true */

var Rule = require(__dirname + '/rule.js');

/**
 * tld library
 *
 * Useable methods are those documented with an @api in JSDoc
 * See README.md for more explainations on how to use this stuff.
 */
function tld (){
  /*jshint validthis: true */
  this.rules = [];
}

tld.init = function init() {
  return new tld();
};

/**
 * Returns the best rule for a given host based on candidates
 *
 * @static
 * @param host {String} Hostname to check rules against
 * @param rules {Array} List of rules used to work on
 * @return {Object} Candidate object, with a normal and exception state
 */
tld.getCandidateRule = function getCandidateRule(host, rules) {
  var rule = {'normal': null, 'exception': null};

  rules.reverse().some(function(r){
    var pattern;

    //sld matching? escape the loop immediatly (except if it's an exception)
    if ('.'+host === r.getNormalXld()){
      if (r.exception === true){
        rule.normal = r;
      }

      return true;
    }

    //otherwise check as a complete host
    //if it's an exception, we want to loop a bit more to a normal rule
    pattern = '.+' + r.getNormalPattern() + '$';

    if ((new RegExp(pattern)).test(host)){
      rule[r.exception ? 'exception' : 'normal'] = r;
      return !r.exception;
    }

    return false;
  });

  //if there is an exception, we challenge its rules without changing pattern
  if (rule.normal && rule.exception) {
    rule.normal.wildcard = rule.exception.wildcard;
  }

  return rule.normal;
};

/**
 * Retrieve a subset of rules for a Top-Level-Domain string
 *
 * @param tld {String} Top-Level-Domain string
 * @return {Array} Rules subset
 */
tld.prototype.getRulesForTld = function getRulesForTld(tld){
  return this.rules
    .filter(function filterOutFirstLevel(rule){
      return rule.firstLevel === tld;
    })
    .map(function transformAsRule(rule){
      return new Rule(rule);
    });
};

/**
 * If no rules are available, it means we don't know the domain.
 * Mozilla Public Suffix list now considers the domain to be valid
 * We deal with it as if it was a ".com" domain
 *
 * @since 1.0.2
 * @see https://github.com/oncletom/tld.js/issues/7
 * @param {Array} rules Filtered rules for the given TLD
 * @param {String} tld TLD on which we candidate against
 * @return {Array} Updated set of rules
 */
tld.prototype.appendUnknownDomainRule = function appendUnknownDomainRule(rules, tld){
  if (rules.length === 0){
    rules.push(new Rule({
      "firstLevel": tld,
      "source": tld
    }));
  }

  return rules;
};

/**
 * Detects the domain based on rules and upon and a host string
 *
 * @api
 * @param {string} host
 * @return {String}
 */
tld.prototype.getDomain = function getDomain(host) {
  var pattern, hostTld, rules, rule;
  var domain = null;

  if (this.isValid(host) === false){
    return null;
  }

  host = host.toLowerCase();
  hostTld = host.split('.').pop();
  rules = this.getRulesForTld(hostTld);
  rules = this.appendUnknownDomainRule(rules, hostTld);
  rule = tld.getCandidateRule(host, rules);

  if (rule === null){
    return null;
  }

  pattern = rule.getPattern();

  return this.getDomainFromPattern(host, pattern);
};

tld.prototype.getDomainFromPattern = function getDomainFromPattern(host, pattern){
  var domain = null;
  host = (host+'');

  host.replace(new RegExp(pattern), function(m, d){
    domain = d;
  });

  return domain;
};

/**
 * Checking if a host is valid
 *
 * @api
 * @todo handle localhost, local etc.
 * @param host {String}
 * @return {Boolean}
 */
tld.prototype.isValid = function isValid(host){
  return !(typeof host !== 'string' || host.indexOf('.') === -1 || host[0] === '.');
};

module.exports = tld;
<commit_msg>Fixed domain case<commit_after>"use strict";

/*jshint node:true strict: true */

var Rule = require(__dirname + '/rule.js');

/**
 * tld library
 *
 * Useable methods are those documented with an @api in JSDoc
 * See README.md for more explainations on how to use this stuff.
 */
function tld (){
  /*jshint validthis: true */
  this.rules = [];
}

tld.init = function init() {
  return new tld();
};

/**
 * Returns the best rule for a given host based on candidates
 *
 * @static
 * @param host {String} Hostname to check rules against
 * @param rules {Array} List of rules used to work on
 * @return {Object} Candidate object, with a normal and exception state
 */
tld.getCandidateRule = function getCandidateRule(host, rules) {
  var rule = {'normal': null, 'exception': null};

  rules.reverse().some(function(r){
    var pattern;

    //sld matching? escape the loop immediatly (except if it's an exception)
    if ('.'+host === r.getNormalXld()){
      if (r.exception === true){
        rule.normal = r;
      }

      return true;
    }

    //otherwise check as a complete host
    //if it's an exception, we want to loop a bit more to a normal rule
    pattern = '.+' + r.getNormalPattern() + '$';

    if ((new RegExp(pattern)).test(host)){
      rule[r.exception ? 'exception' : 'normal'] = r;
      return !r.exception;
    }

    return false;
  });

  //if there is an exception, we challenge its rules without changing pattern
  if (rule.normal && rule.exception) {
    rule.normal.wildcard = rule.exception.wildcard;
  }

  return rule.normal;
};

/**
 * Retrieve a subset of rules for a Top-Level-Domain string
 *
 * @param tld {String} Top-Level-Domain string
 * @return {Array} Rules subset
 */
tld.prototype.getRulesForTld = function getRulesForTld(tld){
  return this.rules
    .filter(function filterOutFirstLevel(rule){
      return rule.firstLevel === tld;
    })
    .map(function transformAsRule(rule){
      return new Rule(rule);
    });
};

/**
 * If no rules are available, it means we don't know the domain.
 * Mozilla Public Suffix list now considers the domain to be valid
 * We deal with it as if it was a ".com" domain
 *
 * @since 1.0.2
 * @see https://github.com/oncletom/tld.js/issues/7
 * @param {Array} rules Filtered rules for the given TLD
 * @param {String} tld TLD on which we candidate against
 * @return {Array} Updated set of rules
 */
tld.prototype.appendUnknownDomainRule = function appendUnknownDomainRule(rules, tld){
  if (rules.length === 0){
    rules.push(new Rule({
      "firstLevel": tld,
      "source": tld
    }));
  }

  return rules;
};

/**
 * Detects the domain based on rules and upon and a host string
 *
 * @api
 * @param {string} host
 * @return {String}
 */
tld.prototype.getDomain = function getDomain(host) {
  var pattern, hostTld, rules, rule;
  var domain = null;

  if (this.isValid(host) === false){
    return null;
  }

  host = host.toLowerCase();
  hostTld = host.split('.').pop();
  rules = this.getRulesForTld(hostTld);
  rules = this.appendUnknownDomainRule(rules, hostTld);
  rule = tld.getCandidateRule(host, rules);

  if (rule === null){
    return null;
  }

  pattern = rule.getPattern();

  return this.getDomainFromPattern(host, pattern);
};

tld.prototype.getDomainFromPattern = function getDomainFromPattern(host, pattern){
  var domain = null;
  host = (host+'').toLowerCase();

  host.replace(new RegExp(pattern), function(m, d){
    domain = d;
  });

  return domain;
};

/**
 * Checking if a host is valid
 *
 * @api
 * @todo handle localhost, local etc.
 * @param host {String}
 * @return {Boolean}
 */
tld.prototype.isValid = function isValid(host){
  return !(typeof host !== 'string' || host.indexOf('.') === -1 || host[0] === '.');
};

module.exports = tld;
<|endoftext|>


<commit_before>import React from 'react';
import List from 'material-ui/lib/lists/list';
import ListItem from 'material-ui/lib/lists/list-item';
import Divider from 'material-ui/lib/divider';
import Colors from 'material-ui/lib/styles/colors';
import IconButton from 'material-ui/lib/icon-button';
import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/lib/menus/icon-menu';
import MenuItem from 'material-ui/lib/menus/menu-item';
import Avatar from 'material-ui/lib/avatar';
import TextField from 'material-ui/lib/text-field';
import injectTapEventPlugin from 'react-tap-event-plugin';
import FlatButton from 'material-ui/lib/flat-button';
import AboutActions from '../../actions/profile/AboutActions';
import AboutStore from '../../stores/AboutStore';

//tap-event-plugin
injectTapEventPlugin();

const iconButtonElement = (
  <IconButton
    touch={true}
    tooltip="more"
    tooltipPosition="bottom-left">
    <MoreVertIcon color={Colors.grey400} />
  </IconButton>
);

const rightIconMenu = (
  <IconMenu iconButtonElement={iconButtonElement}>
    <MenuItem>Reply</MenuItem>
    <MenuItem>Forward</MenuItem>
    <MenuItem>Delete</MenuItem>
  </IconMenu>
);

const textStyle = {
    marginLeft: "15"
}

const About = React.createClass({
  getInitialState: function() {
    return {
        editing: false,
        editingLife: false,
        editingGoodat: false,
        editingThinkingof: false,
        editingFavs: false,
        summary: AboutStore.getsummary(),
        life: AboutStore.getlife(),
        goodat: AboutStore.getgoodat(),
        spendtime: AboutStore.getspendtime(),
        favs: AboutStore.getfavs()
    };
  },
    componentDidMount: function () {
        AboutActions.fetchAll();
        AboutStore.addChangeListener(this._onChange);
  },
    _onChange: function () {
        this.setState({
            summary: AboutStore.getsummary(),
            life: AboutStore.getlife(),
            goodat: AboutStore.getgoodat(),
            spendtime: AboutStore.getspendtime(),
            favs: AboutStore.getfavs()
    });
  },
    _toggle: function () {
        this.setState({
            editing: !this.state.editing
        });
    },
    _toggleLife: function () {
        this.setState({
            editingLife: !this.state.editingLife
        });
    },
    _toggleGoodat: function () {
        this.setState({
            editingGoodat: !this.state.editingGoodat
        });
    },
    _toggleThinkingof: function () {
        this.setState({
            editingThinkingof: !this.state.editingThinkingof
        });
    },
    _toggleFavs: function () {
        this.setState({
            editingFavs: !this.state.editingFavs
        });
    },
    _editSummary: function () {
        AboutActions.updatesummary(this.refs.summary.getValue());
        this.setState({
            editing: !this.state.editing
        });
    },
    _editLife: function () {
        AboutActions.updatelife(this.refs.life.getValue());
        this.setState({
            editingLife: !this.state.editingLife
        });
    },
    _editGoodat: function () {
        AboutActions.updategoodat(this.refs.goodat.getValue());
        this.setState({
            editingGoodat: !this.state.editingGoodat
        });
    },
    _editThinkingOf: function () {
        AboutActions.updatethinkingof(this.refs.thinkingof.getValue());
        this.setState({
            editingThinkingof: !this.state.editingThinkingof
        });
    },
    _editFavs: function () {
        AboutActions.updatefavs(this.refs.favs.getValue());
        this.setState({
            editingFavs: !this.state.editingFavs
        });
    },
  render: function() {
    return (

        <List>
            <ListItem key="Self summary"
                primaryText="Self summary"

                secondaryText={this.state.summary}
                rightIconButton={<IconMenu iconButtonElement={<IconButton>
                    <MoreVertIcon />
                </IconButton>}>
                    <MenuItem onTouchTap={this._toggle} primaryText="Edit"  />
                </IconMenu>}
                leftAvatar={<Avatar color={Colors.deepPurple500} backgroundColor={Colors.transparent}
                    style={{left: 8}}>S</Avatar>} />
            {this.state.editing ?

                <TextField
                    ref="summary"  style={textStyle} defaultValue={this.state.summary} />
                <FlatButton onClick={this._editSummary} label="Save changes" primary={true} />
                <FlatButton label="Cancel" onClick={this._editSummary}/>

 : ''}
            <ListItem key="What Im doing"
                primaryText="What I'm doing with my life ?"
                secondaryText={this.state.life}
                rightIconButton={<IconMenu iconButtonElement={<IconButton>
                    <MoreVertIcon />
                </IconButton>}>
                    <MenuItem onTouchTap={this._toggleLife} primaryText="Edit"  />
                </IconMenu>}
                leftAvatar={<Avatar color={Colors.deepPurple500} backgroundColor={Colors.transparent}
                    style={{left: 8}}>W</Avatar>} />
            {this.state.editingLife ?

                <TextField
                    ref="life"  style={textStyle} defaultValue={this.state.life} />
                <FlatButton onClick={this._editLife} label="Save changes" primary={true} />
                <FlatButton label="Cancel" onClick={this._editSummary}/>

 : ''}
            <ListItem key="Really good at"
                primaryText="I'm really good at"
                secondaryText={this.state.goodat}
                rightIconButton={<IconMenu iconButtonElement={<IconButton>
                    <MoreVertIcon />
                </IconButton>}>
                    <MenuItem onTouchTap={this._toggleGoodat} primaryText="Edit"  />
                </IconMenu>}
                leftAvatar={<Avatar color={Colors.deepPurple500} backgroundColor={Colors.transparent}
                    style={{left: 8}}>R</Avatar>} />
            {this.state.editingGoodat ?

                <TextField
                    ref="goodat"  style={textStyle} defaultValue={this.state.goodat} />
                <FlatButton onClick={this._editGoodat} label="Save changes" primary={true} />
                <FlatButton label="Cancel" onClick={this._editSummary}/>

 : ''}
            <ListItem key="I spend alot"
                primaryText="I spend a lot of time thinking about"
                secondaryText={this.state.spendtime}
                rightIconButton={<IconMenu iconButtonElement={<IconButton>
                    <MoreVertIcon />
                </IconButton>}>
                    <MenuItem onTouchTap={this._toggleThinkingof} primaryText="Edit"  />
                </IconMenu>}
                leftAvatar={<Avatar color={Colors.deepPurple500} backgroundColor={Colors.transparent}
                    style={{left: 8}}>I</Avatar>} />
            {this.state.editingThinkingof ?

                <TextField
                    ref="thinkingof"  style={textStyle} defaultValue={this.state.spendtime} />
                <FlatButton onClick={this._editThinkingOf} label="Save changes" primary={true} />
                <FlatButton label="Cancel" onClick={this._editSummary}/>

 : ''}
            <ListItem key="Books food movies"
                primaryText="Favourite Books, Movies, Food <3"
                secondaryText={this.state.favs}
                rightIconButton={<IconMenu iconButtonElement={<IconButton>
                    <MoreVertIcon />
                </IconButton>}>
                    <MenuItem onTouchTap={this._toggleFavs} primaryText="Edit"  />
                </IconMenu>}
                leftAvatar={<Avatar color={Colors.deepPurple500} backgroundColor={Colors.transparent}
                    style={{left: 8}}>F</Avatar>} />
            {this.state.editingFavs ?

                <TextField
                    ref="favs"  style={textStyle} defaultValue={this.state.favs} />
                <FlatButton onClick={this._editFavs} label="Save changes" primary={true} />
                <FlatButton label="Cancel" onClick={this._editSummary}/>

 : ''}
        </List>

    );
  }

});

export default About;<commit_msg>add fail handling api requests<commit_after>import React from 'react';
import List from 'material-ui/lib/lists/list';
import ListItem from 'material-ui/lib/lists/list-item';
import Divider from 'material-ui/lib/divider';
import Colors from 'material-ui/lib/styles/colors';
import IconButton from 'material-ui/lib/icon-button';
import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/lib/menus/icon-menu';
import MenuItem from 'material-ui/lib/menus/menu-item';
import Avatar from 'material-ui/lib/avatar';
import TextField from 'material-ui/lib/text-field';
import injectTapEventPlugin from 'react-tap-event-plugin';
import FlatButton from 'material-ui/lib/flat-button';
import AboutActions from '../../actions/profile/AboutActions';
import AboutStore from '../../stores/AboutStore';
import ErrorStore from '../../stores/ErrorStore';
import Snackbar from 'material-ui/lib/snackbar';

//tap-event-plugin
injectTapEventPlugin();

const iconButtonElement = (
  <IconButton
    touch={true}
    tooltip="more"
    tooltipPosition="bottom-left">
    <MoreVertIcon color={Colors.grey400} />
  </IconButton>
);

const rightIconMenu = (
  <IconMenu iconButtonElement={iconButtonElement}>
    <MenuItem>Reply</MenuItem>
    <MenuItem>Forward</MenuItem>
    <MenuItem>Delete</MenuItem>
  </IconMenu>
);

const textStyle = {
    marginLeft: "15"
}

const About = React.createClass({
  getInitialState: function() {
    return {
        editing: false,
        editingLife: false,
        editingGoodat: false,
        editingThinkingof: false,
        editingFavs: false,
        error: false,
        summary: AboutStore.getsummary(),
        life: AboutStore.getlife(),
        goodat: AboutStore.getgoodat(),
        spendtime: AboutStore.getspendtime(),
        favs: AboutStore.getfavs()
    };
  },
    componentDidMount: function () {
        AboutActions.fetchAll();
        AboutStore.addChangeListener(this._onChange);
        ErrorStore.addChangeListener(this._onChange);
  },
    _onChange: function () {
        this.setState({
            summary: AboutStore.getsummary(),
            life: AboutStore.getlife(),
            goodat: AboutStore.getgoodat(),
            spendtime: AboutStore.getspendtime(),
            favs: AboutStore.getfavs(),
            error: ErrorStore.getabouterr()
    });
  },
    _toggle: function () {
        this.setState({
            editing: !this.state.editing
        });
    },
    _toggleLife: function () {
        this.setState({
            editingLife: !this.state.editingLife
        });
    },
    _toggleGoodat: function () {
        this.setState({
            editingGoodat: !this.state.editingGoodat
        });
    },
    _toggleThinkingof: function () {
        this.setState({
            editingThinkingof: !this.state.editingThinkingof
        });
    },
    _toggleFavs: function () {
        this.setState({
            editingFavs: !this.state.editingFavs
        });
    },
    _editSummary: function () {
        AboutActions.updatesummary(this.refs.summary.getValue());
        this.setState({
            editing: !this.state.editing
        });
    },
    _editLife: function () {
        AboutActions.updatelife(this.refs.life.getValue());
        this.setState({
            editingLife: !this.state.editingLife
        });
    },
    _editGoodat: function () {
        AboutActions.updategoodat(this.refs.goodat.getValue());
        this.setState({
            editingGoodat: !this.state.editingGoodat
        });
    },
    _editThinkingOf: function () {
        AboutActions.updatethinkingof(this.refs.thinkingof.getValue());
        this.setState({
            editingThinkingof: !this.state.editingThinkingof
        });
    },
    _editFavs: function () {
        AboutActions.updatefavs(this.refs.favs.getValue());
        this.setState({
            editingFavs: !this.state.editingFavs
        });
    },
  render: function() {
    return (

        <List>
            <ListItem key="Self summary"
                primaryText="Self summary"

                secondaryText={this.state.summary}
                rightIconButton={<IconMenu iconButtonElement={<IconButton>
                    <MoreVertIcon />
                </IconButton>}>
                    <MenuItem onTouchTap={this._toggle} primaryText="Edit"  />
                </IconMenu>}
                leftAvatar={<Avatar color={Colors.deepPurple500} backgroundColor={Colors.transparent}
                    style={{left: 8}}>S</Avatar>} />
            {this.state.editing ?

                <TextField
                    ref="summary"  style={textStyle} defaultValue={this.state.summary} />
                <FlatButton onClick={this._editSummary} label="Save changes" primary={true} />
                <FlatButton label="Cancel" onClick={this._editSummary}/>

 : ''}
            <ListItem key="What Im doing"
                primaryText="What I'm doing with my life ?"
                secondaryText={this.state.life}
                rightIconButton={<IconMenu iconButtonElement={<IconButton>
                    <MoreVertIcon />
                </IconButton>}>
                    <MenuItem onTouchTap={this._toggleLife} primaryText="Edit"  />
                </IconMenu>}
                leftAvatar={<Avatar color={Colors.deepPurple500} backgroundColor={Colors.transparent}
                    style={{left: 8}}>W</Avatar>} />
            {this.state.editingLife ?

                <TextField
                    ref="life"  style={textStyle} defaultValue={this.state.life} />
                <FlatButton onClick={this._editLife} label="Save changes" primary={true} />
                <FlatButton label="Cancel" onClick={this._editSummary}/>

 : ''}
            <ListItem key="Really good at"
                primaryText="I'm really good at"
                secondaryText={this.state.goodat}
                rightIconButton={<IconMenu iconButtonElement={<IconButton>
                    <MoreVertIcon />
                </IconButton>}>
                    <MenuItem onTouchTap={this._toggleGoodat} primaryText="Edit"  />
                </IconMenu>}
                leftAvatar={<Avatar color={Colors.deepPurple500} backgroundColor={Colors.transparent}
                    style={{left: 8}}>R</Avatar>} />
            {this.state.editingGoodat ?

                <TextField
                    ref="goodat"  style={textStyle} defaultValue={this.state.goodat} />
                <FlatButton onClick={this._editGoodat} label="Save changes" primary={true} />
                <FlatButton label="Cancel" onClick={this._editSummary}/>

 : ''}
            <ListItem key="I spend alot"
                primaryText="I spend a lot of time thinking about"
                secondaryText={this.state.spendtime}
                rightIconButton={<IconMenu iconButtonElement={<IconButton>
                    <MoreVertIcon />
                </IconButton>}>
                    <MenuItem onTouchTap={this._toggleThinkingof} primaryText="Edit"  />
                </IconMenu>}
                leftAvatar={<Avatar color={Colors.deepPurple500} backgroundColor={Colors.transparent}
                    style={{left: 8}}>I</Avatar>} />
            {this.state.editingThinkingof ?

                <TextField
                    ref="thinkingof"  style={textStyle} defaultValue={this.state.spendtime} />
                <FlatButton onClick={this._editThinkingOf} label="Save changes" primary={true} />
                <FlatButton label="Cancel" onClick={this._editSummary}/>

 : ''}
            <ListItem key="Books food movies"
                primaryText="Favourite Books, Movies, Food <3"
                secondaryText={this.state.favs}
                rightIconButton={<IconMenu iconButtonElement={<IconButton>
                    <MoreVertIcon />
                </IconButton>}>
                    <MenuItem onTouchTap={this._toggleFavs} primaryText="Edit"  />
                </IconMenu>}
                leftAvatar={<Avatar color={Colors.deepPurple500} backgroundColor={Colors.transparent}
                    style={{left: 8}}>F</Avatar>} />
            {this.state.editingFavs ?

                <TextField
                    ref="favs"  style={textStyle} defaultValue={this.state.favs} />
                <FlatButton onClick={this._editFavs} label="Save changes" primary={true} />
                <FlatButton label="Cancel" onClick={this._editSummary}/>

 : ''}
        </List>
        <Snackbar
            open={this.state.error}
            message="Error occured, please try again later"
            autoHideDuration={4000}
            onRequestClose={this.handleRequestClose} />

    );
  }

});

export default About;<|endoftext|>


<commit_before>import { dialog, app, shell, Menu } from 'electron';

const kernelspecs = require('kernelspecs');

import { launchFilename, launchNewNotebook } from './launch';

import * as path from 'path';

function send(focusedWindow, eventName, obj) {
  if (!focusedWindow) {
    console.error('renderer window not in focus (are your devtools open?)');
    return;
  }
  focusedWindow.webContents.send(eventName, obj);
}

function createSender(eventName, obj) {
  return (item, focusedWindow) => {
    send(focusedWindow, eventName, obj);
  };
}

export const fileSubMenus = {
  new: {
    label: '&New',
    accelerator: 'CmdOrCtrl+N',
  },
  open: {
    label: '&Open',
    click: () => {
      const opts = {
        title: 'Open a notebook',
        filters: [
          { name: 'Notebooks', extensions: ['ipynb'] },
        ],
        properties: [
          'openFile',
        ],
        // TODO: This should be based on the currently opened notebook
        defaultPath: process.cwd(),
      };
      dialog.showOpenDialog(opts, (fname) => {
        if (fname) {
          launchFilename(fname[0]);
        }
      });
    },
    accelerator: 'CmdOrCtrl+O',
  },
  save: {
    label: '&Save',
    click: createSender('menu:save'),
    accelerator: 'CmdOrCtrl+S',
  },
  saveAs: {
    label: 'Save &As',
    click: (item, focusedWindow) => {
      const opts = {
        title: 'Save Notebook As',
        filters: [{ name: 'Notebooks', extensions: ['ipynb'] }],
      };
      dialog.showSaveDialog(opts, (filename) => {
        if (!filename) {
          return;
        }

        const ext = path.extname(filename) === '' ? '.ipynb' : '';
        send(focusedWindow, 'menu:save-as', `${filename}${ext}`);
      });
    },
    accelerator: 'CmdOrCtrl+Shift+S',
  },
};

export const file = {
  label: '&File',
  submenu: [
    fileSubMenus.new,
    fileSubMenus.open,
    fileSubMenus.save,
    fileSubMenus.saveAs,
  ],
};

export const edit = {
  label: 'Edit',
  submenu: [
    {
      label: 'Undo',
      accelerator: 'CmdOrCtrl+Z',
      role: 'undo',
    },
    {
      label: 'Redo',
      accelerator: 'Shift+CmdOrCtrl+Z',
      role: 'redo',
    },
    {
      type: 'separator',
    },
    {
      label: 'Cut',
      accelerator: 'CmdOrCtrl+X',
      role: 'cut',
    },
    {
      label: 'Copy',
      accelerator: 'CmdOrCtrl+C',
      role: 'copy',
    },
    {
      label: 'Paste',
      accelerator: 'CmdOrCtrl+V',
      role: 'paste',
    },
    {
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
    },
  ],
};

export const cell = {
  label: 'Cell',
  submenu: [
    {
      label: 'Run All',
      click: createSender('menu:run-all'),
    },
  ],
};
const theme_menu = [
  {
    label: 'Light',
    click: createSender('menu:theme', 'light'),
  },
  {
    label: 'Dark',
    click: createSender('menu:theme', 'dark'),
  },
  {
    label: 'Classic',
    click: createSender('menu:theme', 'classic'),
  },
];

const today = new Date();
const day = today.getDate();
const month = today.getMonth() + 1;
if (month === 12) {
  theme_menu.push(
    {
      label: 'Hohoho',
      click: createSender('menu:theme', 'christmas'),
    });
} else if (month === 10 && day === 31) {
  theme_menu.push({
    label: 'Mwaaahahahhah',
    click: createSender('menu:theme', 'halloween'),
  });
}

export const view = {
  label: 'View',
  submenu: [
    {
      label: 'Reload',
      accelerator: 'CmdOrCtrl+R',
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.reload();
        }
      },
    },
    {
      label: 'Toggle Full Screen',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Ctrl+Command+F';
        }
        return 'F11';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
        }
      },
    },
    {
      label: 'Toggle Developer Tools',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Alt+Command+I';
        }
        return 'Ctrl+Shift+I';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.toggleDevTools();
        }
      },
    },
    {
      label: 'Zoom In',
      accelerator: 'CmdOrCtrl+=',
      click: createSender('menu:zoom-in'),
    },
    {
      label: 'Zoom Out',
      accelerator: 'CmdOrCtrl+-',
      click: createSender('menu:zoom-out'),
    },
    {
      label: 'Theme',
      submenu: theme_menu,
    },
  ],
};

export const publish = {
  label: 'Publish',
  submenu: [
    {
      label: 'to Gist...',
      click: createSender('menu:publish:gist'),
    },
  ],
};

const windowDraft = {
  label: 'Window',
  role: 'window',
  submenu: [
    {
      label: 'Minimize',
      accelerator: 'CmdOrCtrl+M',
      role: 'minimize',
    },
    {
      label: 'Close',
      accelerator: 'CmdOrCtrl+W',
      role: 'close',
    },
  ],
};

if (process.platform === 'darwin') {
  windowDraft.submenu.push(
    {
      type: 'separator',
    },
    {
      label: 'Bring All to Front',
      role: 'front',
    }
  );
}

export const window = windowDraft;

export const help = {
  label: 'Help',
  role: 'help',
  submenu: [
    {
      label: 'Learn More',
      click: () => { shell.openExternal('http://github.com/nteract/nteract'); },
    },
  ],
};

const name = 'nteract';
app.setName(name);

export const named = {
  label: name,
  submenu: [
    {
      label: `About ${name}`,
      role: 'about',
    },
    {
      type: 'separator',
    },
    {
      label: 'Services',
      role: 'services',
      submenu: [],
    },
    {
      type: 'separator',
    },
    {
      label: `Hide ${name}`,
      accelerator: 'Command+H',
      role: 'hide',
    },
    {
      label: 'Hide Others',
      accelerator: 'Command+Alt+H',
      role: 'hideothers',
    },
    {
      label: 'Show All',
      role: 'unhide',
    },
    {
      type: 'separator',
    },
    {
      label: 'Quit',
      accelerator: 'Command+Q',
      click: () => app.quit(),
    },
  ],
};

export function generateDefaultTemplate() {
  const template = [];

  if (process.platform === 'darwin') {
    template.push(named);
  }

  template.push(file);
  template.push(edit);
  template.push(view);
  template.push(publish);
  template.push(window);
  template.push(help);

  return template;
}

export const defaultMenu = Menu.buildFromTemplate(generateDefaultTemplate());

export function loadFullMenu() {
  return kernelspecs.findAll().then(kernelSpecs => {
    function generateSubMenu(kernelName) {
      return {
        label: kernelSpecs[kernelName].spec.display_name,
        click: createSender('menu:new-kernel', kernelName),
      };
    }

    const kernelMenuItems = Object.keys(kernelSpecs).map(generateSubMenu);

    const newNotebookItems = Object.keys(kernelSpecs).map(kernelName => {
      const kernelSpec = kernelSpecs[kernelName];
      return {
        label: kernelSpecs[kernelName].spec.display_name,
        click: () => launchNewNotebook(kernelSpec),
      };
    });

    const languageMenu = {
      label: '&Language',
      submenu: [
        {
          label: '&Kill Running Kernel',
          click: createSender('menu:kill-kernel'),
        },
        {
          type: 'separator',
        },
        // All the available kernels
        ...kernelMenuItems,
      ],
    };
    const template = [];

    if (process.platform === 'darwin') {
      template.push(named);
    }

    const fileWithNew = {
      label: '&File',
      submenu: [
        {
          label: '&New',
          submenu: [
            ...newNotebookItems,
          ],
        },
        fileSubMenus.open,
        fileSubMenus.save,
        fileSubMenus.saveAs,
      ],
    };

    template.push(fileWithNew);
    template.push(edit);
    template.push(cell);
    template.push(view);

    // Application specific functionality should go before window and help
    template.push(languageMenu);
    template.push(publish);
    template.push(window);
    template.push(help);

    const menu = Menu.buildFromTemplate(template);
    return menu;
  });
}
<commit_msg>Added restart kernel menu item<commit_after>import { dialog, app, shell, Menu } from 'electron';

const kernelspecs = require('kernelspecs');

import { launchFilename, launchNewNotebook } from './launch';

import * as path from 'path';

function send(focusedWindow, eventName, obj) {
  if (!focusedWindow) {
    console.error('renderer window not in focus (are your devtools open?)');
    return;
  }
  focusedWindow.webContents.send(eventName, obj);
}

function createSender(eventName, obj) {
  return (item, focusedWindow) => {
    send(focusedWindow, eventName, obj);
  };
}

export const fileSubMenus = {
  new: {
    label: '&New',
    accelerator: 'CmdOrCtrl+N',
  },
  open: {
    label: '&Open',
    click: () => {
      const opts = {
        title: 'Open a notebook',
        filters: [
          { name: 'Notebooks', extensions: ['ipynb'] },
        ],
        properties: [
          'openFile',
        ],
        // TODO: This should be based on the currently opened notebook
        defaultPath: process.cwd(),
      };
      dialog.showOpenDialog(opts, (fname) => {
        if (fname) {
          launchFilename(fname[0]);
        }
      });
    },
    accelerator: 'CmdOrCtrl+O',
  },
  save: {
    label: '&Save',
    click: createSender('menu:save'),
    accelerator: 'CmdOrCtrl+S',
  },
  saveAs: {
    label: 'Save &As',
    click: (item, focusedWindow) => {
      const opts = {
        title: 'Save Notebook As',
        filters: [{ name: 'Notebooks', extensions: ['ipynb'] }],
      };
      dialog.showSaveDialog(opts, (filename) => {
        if (!filename) {
          return;
        }

        const ext = path.extname(filename) === '' ? '.ipynb' : '';
        send(focusedWindow, 'menu:save-as', `${filename}${ext}`);
      });
    },
    accelerator: 'CmdOrCtrl+Shift+S',
  },
};

export const file = {
  label: '&File',
  submenu: [
    fileSubMenus.new,
    fileSubMenus.open,
    fileSubMenus.save,
    fileSubMenus.saveAs,
  ],
};

export const edit = {
  label: 'Edit',
  submenu: [
    {
      label: 'Undo',
      accelerator: 'CmdOrCtrl+Z',
      role: 'undo',
    },
    {
      label: 'Redo',
      accelerator: 'Shift+CmdOrCtrl+Z',
      role: 'redo',
    },
    {
      type: 'separator',
    },
    {
      label: 'Cut',
      accelerator: 'CmdOrCtrl+X',
      role: 'cut',
    },
    {
      label: 'Copy',
      accelerator: 'CmdOrCtrl+C',
      role: 'copy',
    },
    {
      label: 'Paste',
      accelerator: 'CmdOrCtrl+V',
      role: 'paste',
    },
    {
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
    },
  ],
};

export const cell = {
  label: 'Cell',
  submenu: [
    {
      label: 'Run All',
      click: createSender('menu:run-all'),
    },
  ],
};
const theme_menu = [
  {
    label: 'Light',
    click: createSender('menu:theme', 'light'),
  },
  {
    label: 'Dark',
    click: createSender('menu:theme', 'dark'),
  },
  {
    label: 'Classic',
    click: createSender('menu:theme', 'classic'),
  },
];

const today = new Date();
const day = today.getDate();
const month = today.getMonth() + 1;
if (month === 12) {
  theme_menu.push(
    {
      label: 'Hohoho',
      click: createSender('menu:theme', 'christmas'),
    });
} else if (month === 10 && day === 31) {
  theme_menu.push({
    label: 'Mwaaahahahhah',
    click: createSender('menu:theme', 'halloween'),
  });
}

export const view = {
  label: 'View',
  submenu: [
    {
      label: 'Reload',
      accelerator: 'CmdOrCtrl+R',
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.reload();
        }
      },
    },
    {
      label: 'Toggle Full Screen',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Ctrl+Command+F';
        }
        return 'F11';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
        }
      },
    },
    {
      label: 'Toggle Developer Tools',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Alt+Command+I';
        }
        return 'Ctrl+Shift+I';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.toggleDevTools();
        }
      },
    },
    {
      label: 'Zoom In',
      accelerator: 'CmdOrCtrl+=',
      click: createSender('menu:zoom-in'),
    },
    {
      label: 'Zoom Out',
      accelerator: 'CmdOrCtrl+-',
      click: createSender('menu:zoom-out'),
    },
    {
      label: 'Theme',
      submenu: theme_menu,
    },
  ],
};

export const publish = {
  label: 'Publish',
  submenu: [
    {
      label: 'to Gist...',
      click: createSender('menu:publish:gist'),
    },
  ],
};

const windowDraft = {
  label: 'Window',
  role: 'window',
  submenu: [
    {
      label: 'Minimize',
      accelerator: 'CmdOrCtrl+M',
      role: 'minimize',
    },
    {
      label: 'Close',
      accelerator: 'CmdOrCtrl+W',
      role: 'close',
    },
  ],
};

if (process.platform === 'darwin') {
  windowDraft.submenu.push(
    {
      type: 'separator',
    },
    {
      label: 'Bring All to Front',
      role: 'front',
    }
  );
}

export const window = windowDraft;

export const help = {
  label: 'Help',
  role: 'help',
  submenu: [
    {
      label: 'Learn More',
      click: () => { shell.openExternal('http://github.com/nteract/nteract'); },
    },
  ],
};

const name = 'nteract';
app.setName(name);

export const named = {
  label: name,
  submenu: [
    {
      label: `About ${name}`,
      role: 'about',
    },
    {
      type: 'separator',
    },
    {
      label: 'Services',
      role: 'services',
      submenu: [],
    },
    {
      type: 'separator',
    },
    {
      label: `Hide ${name}`,
      accelerator: 'Command+H',
      role: 'hide',
    },
    {
      label: 'Hide Others',
      accelerator: 'Command+Alt+H',
      role: 'hideothers',
    },
    {
      label: 'Show All',
      role: 'unhide',
    },
    {
      type: 'separator',
    },
    {
      label: 'Quit',
      accelerator: 'Command+Q',
      click: () => app.quit(),
    },
  ],
};

export function generateDefaultTemplate() {
  const template = [];

  if (process.platform === 'darwin') {
    template.push(named);
  }

  template.push(file);
  template.push(edit);
  template.push(view);
  template.push(publish);
  template.push(window);
  template.push(help);

  return template;
}

export const defaultMenu = Menu.buildFromTemplate(generateDefaultTemplate());

export function loadFullMenu() {
  return kernelspecs.findAll().then(kernelSpecs => {
    function generateSubMenu(kernelName) {
      return {
        label: kernelSpecs[kernelName].spec.display_name,
        click: createSender('menu:new-kernel', kernelName),
      };
    }

    const kernelMenuItems = Object.keys(kernelSpecs).map(generateSubMenu);

    const newNotebookItems = Object.keys(kernelSpecs).map(kernelName => {
      const kernelSpec = kernelSpecs[kernelName];
      return {
        label: kernelSpecs[kernelName].spec.display_name,
        click: () => launchNewNotebook(kernelSpec),
      };
    });

    const languageMenu = {
      label: '&Language',
      submenu: [
        {
          label: '&Kill Running Kernel',
          click: createSender('menu:kill-kernel'),
        },
        {
          label: 'Restart Running Kernel',
          click: createSender('menu:restart-kernel'),
        },
        {
          type: 'separator',
        },
        // All the available kernels
        ...kernelMenuItems,
      ],
    };
    const template = [];

    if (process.platform === 'darwin') {
      template.push(named);
    }

    const fileWithNew = {
      label: '&File',
      submenu: [
        {
          label: '&New',
          submenu: [
            ...newNotebookItems,
          ],
        },
        fileSubMenus.open,
        fileSubMenus.save,
        fileSubMenus.saveAs,
      ],
    };

    template.push(fileWithNew);
    template.push(edit);
    template.push(cell);
    template.push(view);

    // Application specific functionality should go before window and help
    template.push(languageMenu);
    template.push(publish);
    template.push(window);
    template.push(help);

    const menu = Menu.buildFromTemplate(template);
    return menu;
  });
}
<|endoftext|>


<commit_before>// @author Taehoon Moon
require('../styles');

var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var Modifier = require('famous/core/Modifier');
var OptionsManager = require('famous/core/OptionsManager');
var ImageSurface = require('famous/surfaces/ImageSurface');
var ContainerSurface = require('famous/surfaces/ContainerSurface');
var SequentialLayout = require('famous/views/SequentialLayout');
var Utility = require('famous/utilities/Utility');

var PaperRipple = require('./PaperRipple');

function PaperButton(options) {
    ContainerSurface.apply(this, arguments);

    this.options = {
        flat: false,
        disabled: false,
        selected: false,
        label: {
            size: [true, 36],
            properties: {
                textAlign: 'left',
                lineHeight: '38px',
                fontSize: '18px',
                padding: '0 5px 0 5px'
            }
        },
        icon: {
            size: [36, 36]
        },
        ripple: {
        },
        properties: {
            backgroundColor: 'transparent',
            color: 'black'
        },
        disabledProperties: {
            backgroundColor: 'rgba(0, 0, 0, 0.2)',
            color: '#8d8d8d'
        },
        selectedProperties: {
            backgroundColor: '#639dee',// rgba(30, 30, 190, 0.2)',
            color: 'white'
        }
    };

    if (options)
        OptionsManager.patch(this.options, options);

    if (!this.options.flat)
        this.addClass('paper-shadow').addClass('paper-border');

    var w = 0;
    var h;
    if (this.options.label.content) {
        if (typeof this.options.label.size[0] === 'number')
            w += this.options.label.size[0];
        else
            w = this.options.label.size[0];

        h = this.options.label.size[1];
    }

    if (this.options.icon.content) {
        if (typeof this.options.icon.size[0] === 'number')
            w += this.options.icon.size[0];
        else
            w = this.options.icon.size[0];

        if (this.options.icon.size[1] > h)
            h = this.options.icon.size[1];
    }
    else {
        w = undefined;
        this.options.label.size[0] = undefined;
        this.options.label.properties.textAlign = 'center';
    }

    var rippleModifier = new Modifier({
        transform: Transform.translate(0, 0, 0.01)
    });

    this._ripple = new PaperRipple({ ripple: this.options.ripple });

    if (this.options.disabled)
        this.setDisabled(true);

    if (this.options.selected)
        this.setSelected(true);

    var layoutModifier = new Modifier({
        size: [w, h],
        origin: [0, 0.5],
        align: [0, 0.5]
    });

    if (this.options.icon.content)
        layoutModifier.transformFrom(Transform.translate(5, 0));

    var layout = new SequentialLayout({
        direction: Utility.Direction.X
    });

    var items = [];

    if (this.options.icon.content) {
        this._imageSurface = new ImageSurface(this.options.icon);
        items.push(this._imageSurface);
    }

    if (this.options.label.content) {
        this._labelSurface = new Surface(this.options.label);
        items.push(this._labelSurface);
    }

    layout.sequenceFrom(items);

    this.add(layoutModifier).add(layout);
    this.add(rippleModifier).add(this._ripple);
}

PaperButton.prototype = Object.create(ContainerSurface.prototype);
PaperButton.prototype.constructor = PaperRipple;

PaperButton.prototype.setDisabled = function setDisabled(disabled) {
    this.options.disabled = disabled;
    this._ripple.setDisabled(disabled);
    if (disabled) {
        this.setProperties(this.options.disabledProperties);
        this.removeClass('paper-shadow');
    }
    else {
        this.setProperties(this.options.properties);
        if (!this.options.flat)
            this.addClass('paper-shadow');
    }
};

PaperButton.prototype.getSelected = function getSelected() {
    return this.options.selected;
};

PaperButton.prototype.setSelected = function setSelected(selected) {
    this.options.selected = selected;
    if (selected)
        this.setProperties(this.options.selectedProperties);
    else
        this.setProperties(this.options.properties);
};

PaperButton.prototype.getLabelContent = function getLabelContent() {
    if (!this._labelSurface)
        return undefined;

    return this.options.label.content;
};

PaperButton.prototype.setLabelContent = function setLabelContent(content) {
    if (!this._labelSurface)
        return;

    this.options.label.content = content;
    this._labelSurface.setContent(content);
};

module.exports = PaperButton;
<commit_msg>Updated PaperButton default disabled background color<commit_after>// @author Taehoon Moon
require('../styles');

var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var Modifier = require('famous/core/Modifier');
var OptionsManager = require('famous/core/OptionsManager');
var ImageSurface = require('famous/surfaces/ImageSurface');
var ContainerSurface = require('famous/surfaces/ContainerSurface');
var SequentialLayout = require('famous/views/SequentialLayout');
var Utility = require('famous/utilities/Utility');

var PaperRipple = require('./PaperRipple');

function PaperButton(options) {
    ContainerSurface.apply(this, arguments);

    this.options = {
        flat: false,
        disabled: false,
        selected: false,
        label: {
            size: [true, 36],
            properties: {
                textAlign: 'left',
                lineHeight: '38px',
                fontSize: '18px',
                padding: '0 5px 0 5px'
            }
        },
        icon: {
            size: [36, 36]
        },
        ripple: {
        },
        properties: {
            backgroundColor: 'transparent',
            color: 'black'
        },
        disabledProperties: {
            backgroundColor: 'rgba(0, 0, 0, 0.1)',
            color: '#8d8d8d'
        },
        selectedProperties: {
            backgroundColor: '#639dee',// rgba(30, 30, 190, 0.2)',
            color: 'white'
        }
    };

    if (options)
        OptionsManager.patch(this.options, options);

    if (!this.options.flat)
        this.addClass('paper-shadow').addClass('paper-border');

    var w = 0;
    var h;
    if (this.options.label.content) {
        if (typeof this.options.label.size[0] === 'number')
            w += this.options.label.size[0];
        else
            w = this.options.label.size[0];

        h = this.options.label.size[1];
    }

    if (this.options.icon.content) {
        if (typeof this.options.icon.size[0] === 'number')
            w += this.options.icon.size[0];
        else
            w = this.options.icon.size[0];

        if (this.options.icon.size[1] > h)
            h = this.options.icon.size[1];
    }
    else {
        w = undefined;
        this.options.label.size[0] = undefined;
        this.options.label.properties.textAlign = 'center';
    }

    var rippleModifier = new Modifier({
        transform: Transform.translate(0, 0, 0.01)
    });

    this._ripple = new PaperRipple({ ripple: this.options.ripple });

    if (this.options.disabled)
        this.setDisabled(true);

    if (this.options.selected)
        this.setSelected(true);

    var layoutModifier = new Modifier({
        size: [w, h],
        origin: [0, 0.5],
        align: [0, 0.5]
    });

    if (this.options.icon.content)
        layoutModifier.transformFrom(Transform.translate(5, 0));

    var layout = new SequentialLayout({
        direction: Utility.Direction.X
    });

    var items = [];

    if (this.options.icon.content) {
        this._imageSurface = new ImageSurface(this.options.icon);
        items.push(this._imageSurface);
    }

    if (this.options.label.content) {
        this._labelSurface = new Surface(this.options.label);
        items.push(this._labelSurface);
    }

    layout.sequenceFrom(items);

    this.add(layoutModifier).add(layout);
    this.add(rippleModifier).add(this._ripple);
}

PaperButton.prototype = Object.create(ContainerSurface.prototype);
PaperButton.prototype.constructor = PaperRipple;

PaperButton.prototype.setDisabled = function setDisabled(disabled) {
    this.options.disabled = disabled;
    this._ripple.setDisabled(disabled);
    if (disabled) {
        this.setProperties(this.options.disabledProperties);
        this.removeClass('paper-shadow');
    }
    else {
        this.setProperties(this.options.properties);
        if (!this.options.flat)
            this.addClass('paper-shadow');
    }
};

PaperButton.prototype.getSelected = function getSelected() {
    return this.options.selected;
};

PaperButton.prototype.setSelected = function setSelected(selected) {
    this.options.selected = selected;
    if (selected)
        this.setProperties(this.options.selectedProperties);
    else
        this.setProperties(this.options.properties);
};

PaperButton.prototype.getLabelContent = function getLabelContent() {
    if (!this._labelSurface)
        return undefined;

    return this.options.label.content;
};

PaperButton.prototype.setLabelContent = function setLabelContent(content) {
    if (!this._labelSurface)
        return;

    this.options.label.content = content;
    this._labelSurface.setContent(content);
};

module.exports = PaperButton;
<|endoftext|>


<commit_before>{
    doc_type: 'appshare',
    name: 'appEditorV2',version: 1,

    events: {
        "This will return the editor app": {
            on: "app",
            do:    function(args, returnfn) {
                is_app()

                var argAppName = args.appName

                Vue.component("app_editor",
                {
                  template: `

                    Okhay this AppShare app editor
                        Code ID: {{code_id}}

                        <component  is="editor_component" v-if="editor_loaded">
                                        <button slot-scope="editor_component"
                                                v-on:click='save(code_id, editor_component.text)'
                                                type="button" class="btn btn-primary">

                                                    Save
                                       </button>
                        </component>

                        <component  is="VueApp" v-if="app_loaded">
                        </component>

                            No app selected. Select one:

                            <select @change="chooseApp">
                                <option v-for="item in apps" v-bind:value="item">{{item}}</option>
                            </select>

                   `
                   ,
                   data: function() {
                       return {
                           editor_loaded: false,
                           app_loaded: false,
                           apps: [],
                           code_id: "..."
                       }
                   }
                   ,
                   methods: {
                       chooseApp: function(event) {
                        alert(event.target.value)
                       },
                       save: function(code_id, text) {
                           //alert("Saving " + code_id)
                           callDriverMethod(
                               "appEditor",  "saveCode",
                               {
                                   code: text,
                                   code_id: code_id
                               }
                               ,
                               function(results) {
                                   alert("Code saved")

                               })
                       }
                   },

                   mounted: function () {
                       var mm = this
                       mm.code_id = args.code_id
                       if (argAppName) {
                       callDriverMethod(
                           "systemFunctions",  "sql",
                           {
                               sql: "select  code  from  system_code  where  id = '" + args.code_id +  "' "
                           }
                           ,
                           function(results) {
                               if (results) {
                                   var code = results.value[0].code
                                   mm.code = code
                                   //alert(code)
                                   callDriverMethod(
                                       "editorComponent",  "component",  {text: code}
                                       ,
                                       function(result) {
                                           mm.editor_loaded = true })
                               }

                           })

                               callDriverMethod(
                                   argAppName,  "app",
                                   {
                                   }
                                   ,
                                   function(results) {
                                        mm.app_loaded = true
                                   })
                           } else {
                               callDriverMethod( "systemFunctions",
                                                 "get_apps_list"
                                                 ,{}
                                           ,
                                           function(result) {
                                             //  console.log("3) returned result: " + JSON.stringify(result,null,2))
                                               mm.apps = result.value
                                           })
                           }
                      }

                })

                returnfn({name: "app_editor"})

            }, end: null
        }

        ,

        "Save the editor code": {
            on: "saveCode"
            ,
            do: function(args,returnfn) {
                console.log("Saving in Sqlite: " + args.code_id)
                console.log("Saving in Sqlite: " + args.code)
                var stmtUpdateCode = dbsearch.prepare(" update   system_code   set code = ? where id = ?");
                    dbsearch.serialize(function() {
                    dbsearch.run("begin exclusive transaction");
                    stmtUpdateCode.run(
                          args.code,
                          args.code_id)

                    dbsearch.run("commit");
                    stmtUpdateCode.finalize();

                })
                returnfn({})
            }
            ,
            end: null

        }

    }

}
<commit_msg>refactor of editor<commit_after>{
    doc_type: 'appshare',
    name: 'appEditorV2',version: 1,

    events: {
        "This will return the editor app": {
            on: "app",
            do:    function(args, returnfn) {
                is_app()

                var argAppName = args.appName

                Vue.component("app_editor",
                {
                  template: `

                    Okhay this AppShare app editor
                        Code ID: {{code_id}}

                        <component  is="editor_component" v-if="editor_loaded">
                                        <button slot-scope="editor_component"
                                                v-on:click='save(code_id, editor_component.text)'
                                                type="button" class="btn btn-primary">

                                                    Save
                                       </button>
                        </component>

                        <component  is="VueApp" v-if="app_loaded">
                        </component>

                            No app selected. Select one:

                            <select @change="chooseApp">
                                <option v-for="item in apps" v-bind:value="item">{{item}}</option>
                            </select>

                   `
                   ,
                   data: function() {
                       return {
                           editor_loaded: false,
                           app_loaded: false,
                           apps: [],
                           code_id: "..."
                       }
                   }
                   ,
                   methods: {
                       chooseApp: function(event) {
                        alert(event.target.value)
                       },
                       save: function(code_id, text) {
                           //alert("Saving " + code_id)
                           callDriverMethod(
                               "appEditor",  "saveCode",
                               {
                                   code: text,
                                   code_id: code_id
                               }
                               ,
                               function(results) {
                                   alert("Code saved")

                               })
                       }
                   },

                   mounted: function () {
                       var mm = this
                       if (argAppName) {
                            this.load_app()
                        } else {
                            callDriverMethod( "systemFunctions",
                                              "get_apps_list"
                                              ,{}
                                        ,
                                        function(result) {
                                          //  console.log("3) returned result: " + JSON.stringify(result,null,2))
                                            mm.apps = result.value
                                        })
                        }
                   },

                   load_app: function () {
                       var mm = this
                       mm.code_id = args.code_id
                       callDriverMethod(
                           "systemFunctions",  "sql",
                           {
                               sql: "select  code  from  system_code  where  id = '" + args.code_id +  "' "
                           }
                           ,
                           function(results) {
                               if (results) {
                                   var code = results.value[0].code
                                   mm.code = code
                                   //alert(code)
                                   callDriverMethod(
                                       "editorComponent",  "component",  {text: code}
                                       ,
                                       function(result) {
                                           mm.editor_loaded = true })

                               callDriverMethod(
                                   argAppName,  "app",
                                   {
                                   }
                                   ,
                                   function(results) {
                                        mm.app_loaded = true
                                   })

                               }
                           })
                       }
                   })
                   returnfn({name: "app_editor"})

            }, end: null
        }

        ,

        "Save the editor code": {
            on: "saveCode"
            ,
            do: function(args,returnfn) {
                console.log("Saving in Sqlite: " + args.code_id)
                console.log("Saving in Sqlite: " + args.code)
                var stmtUpdateCode = dbsearch.prepare(" update   system_code   set code = ? where id = ?");
                    dbsearch.serialize(function() {
                    dbsearch.run("begin exclusive transaction");
                    stmtUpdateCode.run(
                          args.code,
                          args.code_id)

                    dbsearch.run("commit");
                    stmtUpdateCode.finalize();

                })
                returnfn({})
            }
            ,
            end: null

        }

    }

}
<|endoftext|>


<commit_before>/**
* Retrieve a column from a matrix
* @param {Matrix | Array} matrix
* @param {number} index    Zero based column index
* @return {Matrix | Array} Returns the column as a vector
*
* Taken from: https://github.com/josdejong/mathjs/issues/230
*/
function col(matrix, index) {
  var rows = math.size(matrix).valueOf()[0];
  return math.flatten(math.subset(matrix, math.index([0, rows], index)));
}

/**
* Retrieve a row from a matrix
* @param {Matrix | Array} matrix
* @param {number} index    Zero based row index
* @return {Matrix | Array} Returns the row as a vector
*
* Taken from: https://github.com/josdejong/mathjs/issues/230
*/
function row(matrix, index) {
  var rows = math.size(matrix).valueOf()[1];
  return math.flatten(math.subset(matrix, math.index(index, [0, rows])));
}

/**
* Computes forward probabilities for given parameters.
* @param {Matrix} initialProbabilities          Initial state probabilities for the HMM (1xN)
* @param {Matrix} transitionProbabilities       State transition probabilities (NxN)
* @param {HashTable} observationProbabilities   A hash table that contains a vector (1xN) that contains the observation probabilities
*                                               per state for each observation symbol
* @param {Array} observations                   An array of observations of which probability will be calculated according to the model
*/
function forward(initialProbabilities, transitionProbabilities, observationProbabilities, observations) {
    var numStates = initialProbabilities.size()[1];
    var alpha = math.zeros(observations.length, numStates);

     for(i = 0; i < numStates; i++) {
        alpha.set([0, i], initialProbabilities.get([0, i]) * observationProbabilities[observations[0]].get([0, i]));
     }

     for (t = 1; t < observations.length; t++) {
        for (j = 0; j < numStates; j++) {
            alpha.set([t, j], math.multiply(row(alpha, t - 1), col(transitionProbabilities, j)) *
                observationProbabilities[observations[t]].get([0, j]))
        }
     }

    return alpha
}<commit_msg>Implemented Viterbi algorithm.<commit_after>var initProbs = math.matrix([[0.5, 0.3, 0.2]]);
var obsProbs = new Object();
obsProbs['hello'] = math.matrix([[0.63, 0.33, 0.04]]);
obsProbs['world'] = math.matrix([[0.04, 0.33, 0.63]]);
var transProbs = math.matrix([[0.1, 0.6, 0.3], [0.4, 0.2, 0.4], [0.3, 0.5, 0.2]]);
obs = ['hello', 'hello', 'world', 'hello', 'world'];

/**
 * Retrieve a column from a matrix
 * @param {Matrix | Array} matrix
 * @param {number} index    Zero based column index
 * @return {Matrix | Array} Returns the column as a vector
 *
 * Taken from: https://github.com/josdejong/mathjs/issues/230
 */
function col(matrix, index) {
    var rows = math.size(matrix).valueOf()[0];
    return math.flatten(math.subset(matrix, math.index([0, rows], index)));
}

/**
 * Retrieve a row from a matrix
 * @param {Matrix | Array} matrix
 * @param {number} index    Zero based row index
 * @return {Matrix | Array} Returns the row as a vector
 *
 * Taken from: https://github.com/josdejong/mathjs/issues/230
 */
function row(matrix, index) {
    var rows = math.size(matrix).valueOf()[1];
    return math.flatten(math.subset(matrix, math.index(index, [0, rows])));
}

/**
 * A helper function for returning the largest index of a 1xN vector.
 *
 * @param {Matrix} 1xN vector, of which index with the greatest element will be returned
 */
function vectorArgmax(vector) {
    max = 0;
    argmax = -1;

    arr = math.squeeze(vector);

    for (k = 0; k < arr.size()[0]; k++) {
        curr = arr.get([k])
        if (curr > max) {
            max = curr;
            argmax = k;
        }
    }

    return argmax;
}

// Needs cleanup
function elementwiseMul(vector1, vector2) {
    arr1 = math.squeeze(vector1);
    arr2= math.squeeze(vector2);

    if (arr1.size()[0] != arr2.size()[0]) {
        throw "Vectors are not of the same shape!";
    } else {
        result = math.zeros(1, arr1.size()[0]);

        for (i = 0; i < arr1.size()[0]; i++) {
            result.set([0, i], vector1.get([i]) * vector2.get([i]));
        }

        return result
    }
}

/**
 * Computes forward probabilities for given parameters.
 * @param {Matrix} initialProbabilities          Initial state probabilities for the HMM (1xN)
 * @param {Matrix} transitionProbabilities       State transition probabilities (NxN)
 * @param {HashTable} observationProbabilities   A hash table that contains a vector (1xN) that contains the observation probabilities
 *                                               per state for each observation symbol
 * @param {Array} observations                   An array of observations of which probability will be calculated according to the model
 */
function forward(initialProbabilities, transitionProbabilities, observationProbabilities, observations) {
    var numStates = initialProbabilities.size()[1];
    var alpha = math.zeros(observations.length, numStates);

    // Fill the initial conditions
    for (i = 0; i < numStates; i++) {
        alpha.set([0, i], initialProbabilities.get([0, i]) * observationProbabilities[observations[0]].get([0, i]));
    }

    // Recursion step
    for (t = 1; t < observations.length; t++) {
        for (j = 0; j < numStates; j++) {
            alpha.set([t, j], math.multiply(row(alpha, t - 1), col(transitionProbabilities, j)) *
            observationProbabilities[observations[t]].get([0, j]))
        }
    }

    return alpha
}

/**
 * Runs Viterbi algorithm and decodes most likely state sequence for a given set of observations.
 * @param {Matrix} initialProbabilities          Initial state probabilities for the HMM (1xN)
 * @param {Matrix} transitionProbabilities       State transition probabilities (NxN)
 * @param {HashTable} observationProbabilities   A hash table that contains a vector (1xN) that contains the observation probabilities
 *                                               per state for each observation symbol
 * @param {Array} observations                   An array of observations of which probability will be calculated according to the model
 * @returns {*[]} an array containing best state sequence, its probability, delta and phi values.
 */
function viterbi(initialProbabilities, transitionProbabilities, observationProbabilities, observations) {
    var numStates = initialProbabilities.size()[1];

    var delta = math.zeros(observations.length, numStates);
    var phi = math.zeros(observations.length, numStates);

    // Fill the initial conditions
    for (i = 0; i < numStates; i++) {
        delta.set([0, i], initialProbabilities.get([0, i]) * observationProbabilities[observations[0]].get([0, i]));
        phi.set([0, i], 0)
    }

    /*
     Recursion step
     */
    for (t = 1; t < observations.length; t++) {
        for (j = 0; j < numStates; j++) {
            multiplication = elementwiseMul(row(delta, t - 1), col(transitionProbabilities, j));

            // Find the argmax
            argmax = vectorArgmax(multiplication);

            phi.set([t, j], argmax);
            delta.set([t, j], multiplication.get([0, argmax]) * observationProbabilities[observations[t]].get([0, j]))
        }
    }

    /*
     Decoding step.
     */
    stateSequence = math.zeros(observations.length, 1);

    // Set the last element to the most likely value
    mostLikelyState = vectorArgmax(row(delta, observations.length - 1));
    stateSequence.set([observations.length - 1, 0], mostLikelyState);

    // Start decoding backwards
    for (t = observations.length - 2; t >= 0; t--) {
        prevState = stateSequence.get([t + 1, 0]);
        stateSequence.set([t, 0], phi.get([t + 1, prevState]));
    }

    bestStateSequenceProbability = delta.get([observations.length - 1, mostLikelyState]);

    return [stateSequence, bestStateSequenceProbability, delta, phi]
}<|endoftext|>