<commit_before>function puts(){
  console.log.apply(console, arguments);
}

// global namespace
var Jdbcwb = {};

(function(){

  "use strict";

  var _g = Jdbcwb; // global namespace alias

  var COL_CONTENT_LENGTH_MAX = 32;

  ////////////////////////////////

  function snipLongContent(str){
    if(str == null){
      return null;
    }
    if(str.length > COL_CONTENT_LENGTH_MAX){
      var snip = "...";
      var half = Math.floor((COL_CONTENT_LENGTH_MAX - snip.length) / 2);
      var head = str.substring(0, half);
      var tail = str.substring(str.length - half, str.length);
      str = head + '' + snip + '' + tail;
    }
    return str;
  }

  function isPrimaryKey(colDefs, ci){
    var cn = ci + 1;
    var found = false;
    colDefs.forEach(function(colDef, i){
      if(colDef.no === cn && colDef.pk !== null){
        found = true;
      }
    });
    return found;
  }

  ////////////////////////////////
  // Table Utilities

  function makeHeaderRows(
    // colPNames,
    colDefs){
    var inner = "#	";
    _.each(colDefs, function(colDef){
      inner += '' + colDef.name + '	';
    });
    return '
' + inner + '
';
  }

  function makeDataRows(row, ri){
    var inner = '' + (ri + 1) + '	';
    _.each(row, function(col){
      var content = col;
      if(_g.appM.get("snipLongContent")){
        content = snipLongContent(col);
      }
      inner += ''+ content +'	';
    });
    return '
' + inner + '
';
  }

  ////////////////////////////////

  var Database = {

    singleQuery: function(mode, schema, tablePName, sql, fnOk, fnNg){
      this.multiQuery(mode, schema, tablePName, [sql], function(results){
        fnOk(results[0]);
      }, fnNg);
    },

    multiQuery: function(mode, schema, tablePName, sqls, fnOk, fnNg){
      $.post("/api/query", {
        mode: mode,
        schema: schema,
        table: tablePName,
        sqls: JSON.stringify(sqls)
      }).done(function(data){
        _g.appM.set("ajaxResponse", JSON.stringify(data));

        if(data.status === 'OK'){
          fnOk(data.results);
        }else{
          console.error(data.ex); // TODO
          fnNg(data);
        }
      });
    },

    update: function(sql, fnOk, fnNg){
      $.post("/api/update", {
        sql: sql
      }, function(data){
        _g.appM.set("ajaxResponse", JSON.stringify(data));

        if(data.status === 'OK'){
          fnOk(data);
        }else{
          console.error(data.ex); // TODO
          fnNg(data);
        }
      });
    }
  };

  ////////////////////////////////

  _g.AppM = Backbone.Model.extend({
    defaults: {
      ajaxResponse: "",
      snipLongContent: true
    },

    toggleSnipLongContent: function(){
      this.set("snipLongContent", ! this.get("snipLongContent") );
    }
  });

  _g.AppV = Backbone.View.extend({

    el: "body",

    events: {
      "click .snip_long_content": function(){
        this.model.toggleSnipLongContent();
      }
    },

    initialize: function(){
      this.listenTo(this.model, "change", this.render);
    },

    render: function(){
      $("#ajax_response").val(this.model.get("ajaxResponse"));
      this.$(".snip_long_content")
          .prop("checked", this.model.get("snipLongContent"));
    },

    guard:   function(){ this.$("#guard_layer").show(); },
    unguard: function(){ this.$("#guard_layer").hide(); }
  });

  ////////////////////////////////

  _g.GenericOperationM = Backbone.Model.extend({

    doQuery: function(sql, viewFnOk, viewFnNg){
      var resboxM = _g.genericOperationResultBoxM;
      Database.singleQuery('generic', null, null, sql, function(result){
        resboxM.setResult(result);
        viewFnOk();
      }, function(data){
        viewFnNg();
      });
    }
  });

  _g.GenericOperationV = Backbone.View.extend({

    el: "#_generic_operation",

    events: {
      "click .btn_query": "doQuery",
      "click .btn_update": "doUpdate"
    },

    doQuery: function(){
      var resboxM = _g.genericOperationResultBoxM;

      _g.appV.guard();
      resboxM.reset();

      var sql = this.$("textarea").val();

      this.model.doQuery(sql, function(){
        _g.appV.unguard();
      }, function(){
        _g.appV.unguard();
      });
    },

    doUpdate: function(){
      var resboxM = _g.genericOperationResultBoxM;
      _g.appV.guard();

      var sql = this.$("textarea").val();

      Database.update(sql, function(data){
        resboxM.set("numRows", data.count);
        _g.appV.unguard();
      }, function(data){
        _g.appV.unguard();
      });
    }
  });

  ////////////////////////////////

  _g.TableEditM = Backbone.Model.extend({

    doQuery: function(schema, tablePName, viewFnOk, viewFnNg){
      var resboxM = _g.tableEditResultBoxM;
      var sql = this.makeSql(tablePName);

      Database.singleQuery('single_table', schema, tablePName, sql, function(result){
        // OK
        resboxM.setResult(result);
        viewFnOk();
      }, function(data){
        // NG
        viewFnNg();
      });
    },

    makeSql: function(tablePName){
      return [
        "SELECT *",
        "FROM " + tablePName
      ].join("\n");
    }
  });

  _g.TableEditV = Backbone.View.extend({

    el: "#_table_edit",

    events: {
      "click .btn_query": "doQuery"
    },

    doQuery: function(ev){
      ev.preventDefault();
      var resboxM = _g.tableEditResultBoxM;

      _g.appV.guard();
      // _g.appV.hideMsg(); // TODO
      resboxM.reset();
      this.colDefs = null;

      var schema = this.$("[name=schema]").val();
      var tablePName = this.$("[name=table_pname]").val();

      this.model.doQuery(schema, tablePName, function(){
        _g.appV.unguard();
      }, function(){
        _g.appV.unguard();
      });
    }
  });

  ////////////////////////////////

  _g.ResultBoxM = Backbone.Model.extend({
    defaults: {
      numRows: null,
      rows: [],
      colDefs: []
    },

    reset: function(){
      this.set("data", {
        colDefs: [],
        rows: [],
        numRows: "-",
        numRowsAll: "-"
      });
      this.set("colDefs", [], {silent: true});
      this.set("rows", [], {silent: true});
      this.set("numRows", "-", {silent: true});
      this.set("numRowsAll", "-", {silent: true});
      this.trigger("change");
    },

    setResult: function(result){
      this.set("numRows", result.numRows, {silent: true});
      this.set("colDefs", result.colDefs, {silent: true});
      this.set("rows", result.rows, {silent: true});
      this.trigger("change");
    }
  });

  _g.ResultBoxV = Backbone.View.extend({
    initialize: function(){
      this.rowVs = [];
      this.listenTo(this.model, "change", this.render);
    },

    _renderNormalView: function(){
      var me = this;

      // header
      this.$(".result thead").append(makeHeaderRows(
        // colPNames,
        this.model.get("colDefs")
      ));

      // rows
      var $tbody = this.$(".result tbody");
      _.each(this.model.get("rows"), function(cols, ri){
        var $tr = $(makeDataRows(cols, ri));

        var rowV = new _g.RowV({
          el: $tr,
          model: new _g.RowM({ cols: cols })
        });
        me.rowVs.push(rowV);

        me.listenTo(rowV, "click", function(rowV, evTarget){
          me.onClickRow(rowV, evTarget);
        });
        $tbody.append($tr);
      });
    },

    render: function(){
      // clear
      this.$(".result thead").empty();
      this.$(".result tbody").empty();

      var numRows = this.model.get("numRows");
      this.$(".num_rows").text(numRows != null ? numRows : "-");

      this.rowVs = [];
      this._renderNormalView();
    },

    onClickRow: function(rowV, evTarget){
      // TODO th case
      var $td = $(evTarget).closest("td");
      var ci = rowV.tdToCi($td.get(0));
      if( ! this.isPrimaryKey(ci)){
        // 編集可能部分をクリックした場合
        this.editValue($td);
      }
    },

    editValue: function($td){
      puts("editValue", $td); // TODO
    },

    isPrimaryKey: function(ci){
      return isPrimaryKey(this.model.get("colDefs"), ci);
    }
  });

  _g.RowM = Backbone.Model.extend({

    defaults: {
      cols: []
    },

    getCol: function(ci){
      return this.get("cols")[ci];
    },

    setCol: function(ci, val){
      var cols = this.get("cols");
      cols[ci] = val;
      this.set("cols", null, {silent: true});
      this.set("cols", cols);
    }
  });

  _g.RowV = Backbone.View.extend({
    events: {
      "click": function(ev){
        this.trigger("click", this, ev.target);
      }
    },

    tdToCi: function(td){
      var ci;
      this.$el.find("td").each(function(i, _td){
        if(_td === td){
          ci = i;
          return false; // break
        }
      });
      return ci;
    }
  });

  _g.EditPrompt = Backbone.View.extend({

    el: "#_edit_prompt",

    show: function(preVal, fn){
      puts("edit prompt");
      var d = new Date();
      fn(d.getMinutes() + ":" + d.getSeconds()); // FIXME dummy value
    }
  });

  ////////////////////////////////

  _g.start = function(){

    _g.genericOperationResultBoxM = new _g.ResultBoxM();
    _g.genericOperationResultBoxV = new _g.ResultBoxV({
      el: $("#_generic_operation ._result_box"),
      model: _g.genericOperationResultBoxM
    });

    _g.tableEditResultBoxM = new _g.ResultBoxM();
    _g.tableEditResultBoxV = new _g.ResultBoxV({
      el: $("#_table_edit ._result_box"),
      model: _g.tableEditResultBoxM
    });

    _g.genericOperationM = new _g.GenericOperationM();
    _g.genericOperationV = new _g.GenericOperationV({
      model: _g.genericOperationM
    });

    _g.tableEditM = new _g.TableEditM();
    _g.tableEditV = new _g.TableEditV({
      model: _g.tableEditM
    });

    _g.editPrompt = new _g.EditPrompt();

    _g.appM = new _g.AppM();
    _g.appV = new _g.AppV({
      model: _g.appM
    });
  };

})();

////////////////////////////////

$(Jdbcwb.start);
<commit_msg>update column by edited value<commit_after>function puts(){
  console.log.apply(console, arguments);
}

// global namespace
var Jdbcwb = {};

(function(){

  "use strict";

  var _g = Jdbcwb; // global namespace alias

  var COL_CONTENT_LENGTH_MAX = 32;

  ////////////////////////////////

  function snipLongContent(str){
    if(str == null){
      return null;
    }
    if(str.length > COL_CONTENT_LENGTH_MAX){
      var snip = "...";
      var half = Math.floor((COL_CONTENT_LENGTH_MAX - snip.length) / 2);
      var head = str.substring(0, half);
      var tail = str.substring(str.length - half, str.length);
      str = head + '' + snip + '' + tail;
    }
    return str;
  }

  function isPrimaryKey(colDefs, ci){
    var cn = ci + 1;
    var found = false;
    colDefs.forEach(function(colDef, i){
      if(colDef.no === cn && colDef.pk !== null){
        found = true;
      }
    });
    return found;
  }

  function escapeForSql(val){
    if(val === null){
      return "NULL";
    }
    return "'" + ("" + val).replace( /'/g, "''") + "'";
  }

  ////////////////////////////////
  // Table Utilities

  function makeHeaderRows(
    // colPNames,
    colDefs){
    var inner = "#	";
    _.each(colDefs, function(colDef){
      inner += '' + colDef.name + '	';
    });
    return '
' + inner + '
';
  }

  function makeDataRows(row, ri){
    var inner = '' + (ri + 1) + '	';
    _.each(row, function(col){
      var content = col;
      if(_g.appM.get("snipLongContent")){
        content = snipLongContent(col);
      }
      inner += ''+ content +'	';
    });
    return '
' + inner + '
';
  }

  ////////////////////////////////

  var Database = {

    singleQuery: function(mode, schema, tablePName, sql, fnOk, fnNg){
      this.multiQuery(mode, schema, tablePName, [sql], function(results){
        fnOk(results[0]);
      }, fnNg);
    },

    multiQuery: function(mode, schema, tablePName, sqls, fnOk, fnNg){
      $.post("/api/query", {
        mode: mode,
        schema: schema,
        table: tablePName,
        sqls: JSON.stringify(sqls)
      }).done(function(data){
        _g.appM.set("ajaxResponse", JSON.stringify(data));

        if(data.status === 'OK'){
          fnOk(data.results);
        }else{
          console.error(data.ex); // TODO
          fnNg(data);
        }
      });
    },

    update: function(sql, fnOk, fnNg){
      $.post("/api/update", {
        sql: sql
      }, function(data){
        _g.appM.set("ajaxResponse", JSON.stringify(data));

        if(data.status === 'OK'){
          fnOk(data);
        }else{
          console.error(data.ex); // TODO
          fnNg(data);
        }
      });
    }
  };

  ////////////////////////////////

  _g.AppM = Backbone.Model.extend({
    defaults: {
      ajaxResponse: "",
      snipLongContent: true
    },

    toggleSnipLongContent: function(){
      this.set("snipLongContent", ! this.get("snipLongContent") );
    }
  });

  _g.AppV = Backbone.View.extend({

    el: "body",

    events: {
      "click .snip_long_content": function(){
        this.model.toggleSnipLongContent();
      }
    },

    initialize: function(){
      this.listenTo(this.model, "change", this.render);
    },

    render: function(){
      $("#ajax_response").val(this.model.get("ajaxResponse"));
      this.$(".snip_long_content")
          .prop("checked", this.model.get("snipLongContent"));
    },

    guard:   function(){ this.$("#guard_layer").show(); },
    unguard: function(){ this.$("#guard_layer").hide(); }
  });

  ////////////////////////////////

  _g.GenericOperationM = Backbone.Model.extend({

    doQuery: function(sql, viewFnOk, viewFnNg){
      var resboxM = _g.genericOperationResultBoxM;
      Database.singleQuery('generic', null, null, sql, function(result){
        resboxM.setResult(result);
        viewFnOk();
      }, function(data){
        viewFnNg();
      });
    }
  });

  _g.GenericOperationV = Backbone.View.extend({

    el: "#_generic_operation",

    events: {
      "click .btn_query": "doQuery",
      "click .btn_update": "doUpdate"
    },

    doQuery: function(){
      var resboxM = _g.genericOperationResultBoxM;

      _g.appV.guard();
      resboxM.reset();

      var sql = this.$("textarea").val();

      this.model.doQuery(sql, function(){
        _g.appV.unguard();
      }, function(){
        _g.appV.unguard();
      });
    },

    doUpdate: function(){
      var resboxM = _g.genericOperationResultBoxM;
      _g.appV.guard();

      var sql = this.$("textarea").val();

      Database.update(sql, function(data){
        resboxM.set("numRows", data.count);
        _g.appV.unguard();
      }, function(data){
        _g.appV.unguard();
      });
    }
  });

  ////////////////////////////////

  _g.TableEditM = Backbone.Model.extend({

    doQuery: function(schema, tablePName, viewFnOk, viewFnNg){
      var resboxM = _g.tableEditResultBoxM;
      var sql = this.makeSql(tablePName);

      Database.singleQuery('single_table', schema, tablePName, sql, function(result){
        // OK
        resboxM.setResult(result);
        viewFnOk();
      }, function(data){
        // NG
        viewFnNg();
      });
    },

    makeSql: function(tablePName){
      return [
        "SELECT *",
        "FROM " + tablePName
      ].join("\n");
    }
  });

  _g.TableEditV = Backbone.View.extend({

    el: "#_table_edit",

    events: {
      "click .btn_query": "doQuery"
    },

    doQuery: function(ev){
      ev.preventDefault();
      var resboxM = _g.tableEditResultBoxM;

      _g.appV.guard();
      // _g.appV.hideMsg(); // TODO
      resboxM.reset();
      this.colDefs = null;

      var schema = this.$("[name=schema]").val();
      var tablePName = this.$("[name=table_pname]").val();

      this.model.doQuery(schema, tablePName, function(){
        _g.appV.unguard();
      }, function(){
        _g.appV.unguard();
      });
    }
  });

  ////////////////////////////////

  _g.ResultBoxM = Backbone.Model.extend({
    defaults: {
      numRows: null,
      rows: [],
      colDefs: []
    },

    reset: function(){
      this.set("data", {
        colDefs: [],
        rows: [],
        numRows: "-",
        numRowsAll: "-"
      });
      this.set("colDefs", [], {silent: true});
      this.set("rows", [], {silent: true});
      this.set("numRows", "-", {silent: true});
      this.set("numRowsAll", "-", {silent: true});
      this.trigger("change");
    },

    setResult: function(result){
      this.set("numRows", result.numRows, {silent: true});
      this.set("colDefs", result.colDefs, {silent: true});
      this.set("rows", result.rows, {silent: true});
      this.trigger("change");
    },

    doUpdate: function(sql, fnOk, fnNg){
      Database.update(sql, fnOk, fnNg);
    }
  });

  _g.ResultBoxV = Backbone.View.extend({
    initialize: function(){
      this.rowVs = [];
      this.listenTo(this.model, "change", this.render);
    },

    _renderNormalView: function(){
      var me = this;

      // header
      this.$(".result thead").append(makeHeaderRows(
        // colPNames,
        this.model.get("colDefs")
      ));

      // rows
      var $tbody = this.$(".result tbody");
      _.each(this.model.get("rows"), function(cols, ri){
        var $tr = $(makeDataRows(cols, ri));

        var rowV = new _g.RowV({
          el: $tr,
          model: new _g.RowM({ cols: cols })
        });
        me.rowVs.push(rowV);

        me.listenTo(rowV, "click", function(rowV, evTarget){
          me.onClickRow(rowV, evTarget);
        });
        $tbody.append($tr);
      });
    },

    render: function(){
      // clear
      this.$(".result thead").empty();
      this.$(".result tbody").empty();

      var numRows = this.model.get("numRows");
      this.$(".num_rows").text(numRows != null ? numRows : "-");

      this.rowVs = [];
      this._renderNormalView();
    },

    onClickRow: function(rowV, evTarget){
      // TODO th case
      var $td = $(evTarget).closest("td");
      var ci = rowV.tdToCi($td.get(0));
      if( ! this.isPrimaryKey(ci)){
        // 編集可能部分をクリックした場合
        this.editValue($td, ci);
      }
    },

    editValue: function($td, ci){
      var me = this;
      // _g.appV.hideMsg(); // TODO

      var pname = this.getColDefByIdx(ci).name;

      var closestTr = $td.closest("tr").get(0);
      var ri;
      _.each(this.$("tbody tr"), function(tr, i){
        if(tr === closestTr){
          ri = i;
        }
      });
      var rowV = this.rowVs[ri];

      var preVal = rowV.model.getCol(ci);

      _g.editPrompt.show(preVal, function(postVal){
        rowV.model.setCol(ci, postVal);

        var pks = _.map(me.getPkDefs(), function(pkDef){
          return {
            pname: pkDef.name
            ,val: rowV.model.getCol(pkDef.no - 1)
          };
        });

        var sql = "UPDATE " + $("#_table_edit [name=table_pname]").val() // FIXME should get from resbox model
              + "\n" + "SET " + pname + " = " + escapeForSql(postVal)
              + "\n" + "WHERE 1=1"
              + "\n";

        pks.forEach(function(pk, i){
          var type = me.getColTypeByPName(pk.pname);
          sql += "  AND ";
          sql += pk.pname
          // + " /* "+ type +" */ "
              + " = " + escapeForSql(pk.val) + "\n";
        });
        // puts(sql);

        me.model.doUpdate(sql, function(data){
          // OK
        }, function(data){
          // NG
          // 変更前の値に戻す
          rowV.model.setCol(ci, preVal);
        });
      });
    },

    getColTypeByPName: function(pname){
      var type;
      this.model.get("colDefs").forEach(function(def){
        if(def.name === pname){
          type = def.type;
          return false;
        }
      });
      return type;
    },

    getPkDefs: function(){
      var pkDefs = _.filter(this.model.get("colDefs"), function(def){
        return def.pk != null;
      });
      return pkDefs;
    },

    getColDefByIdx: function(ci){
      var me = this;
      var cn = ci + 1;
      var def;
      _.each(this.model.get("colDefs"), function(it){
        if(it.no === cn){
          def = it;
          return false; // break
        }
      });
      return def;
    },

    isPrimaryKey: function(ci){
      return isPrimaryKey(this.model.get("colDefs"), ci);
    }
  });

  _g.RowM = Backbone.Model.extend({

    defaults: {
      cols: []
    },

    getCol: function(ci){
      return this.get("cols")[ci];
    },

    setCol: function(ci, val){
      var cols = this.get("cols");
      cols[ci] = val;
      this.set("cols", null, {silent: true});
      this.set("cols", cols);
    }
  });

  _g.RowV = Backbone.View.extend({
    events: {
      "click": function(ev){
        this.trigger("click", this, ev.target);
      }
    },

    tdToCi: function(td){
      var ci;
      this.$el.find("td").each(function(i, _td){
        if(_td === td){
          ci = i;
          return false; // break
        }
      });
      return ci;
    }
  });

  _g.EditPrompt = Backbone.View.extend({

    el: "#_edit_prompt",

    show: function(preVal, fn){
      puts("edit prompt");
      var d = new Date();
      fn(d.getMinutes() + ":" + d.getSeconds()); // FIXME dummy value
    }
  });

  ////////////////////////////////

  _g.start = function(){

    _g.genericOperationResultBoxM = new _g.ResultBoxM();
    _g.genericOperationResultBoxV = new _g.ResultBoxV({
      el: $("#_generic_operation ._result_box"),
      model: _g.genericOperationResultBoxM
    });

    _g.tableEditResultBoxM = new _g.ResultBoxM();
    _g.tableEditResultBoxV = new _g.ResultBoxV({
      el: $("#_table_edit ._result_box"),
      model: _g.tableEditResultBoxM
    });

    _g.genericOperationM = new _g.GenericOperationM();
    _g.genericOperationV = new _g.GenericOperationV({
      model: _g.genericOperationM
    });

    _g.tableEditM = new _g.TableEditM();
    _g.tableEditV = new _g.TableEditV({
      model: _g.tableEditM
    });

    _g.editPrompt = new _g.EditPrompt();

    _g.appM = new _g.AppM();
    _g.appV = new _g.AppV({
      model: _g.appM
    });
  };

})();

////////////////////////////////

$(Jdbcwb.start);
<|endoftext|>


<commit_before>// homeController.js
// Controller for the home page

app.controller('homeController', function ($scope, $http, $window, $location, localStorageService, localStorageSetGet) {
  $scope.saveRepo = function (repoPassed) {
    $scope.repoSet = true;
    $scope.repoName = repoPassed;
    $scope.getGitData('https://api.github.com/repos/' + $scope.repoName + '/milestones?state=all', 'getMilestones');
  }

  $scope.saveMilestone = function (milestonePassed, milestoneId) {
    $scope.milestoneSet = true;
    $scope.milestoneName = milestonePassed;
    $scope.milestoneId = milestoneId;
    $scope.getGitData('https://api.github.com/repos/' + $scope.repoName +
    '/issues?state=all&filter=all&milestone=' + $scope.milestoneId, 'getIssues');
  }

  $scope.getGitData = function (url, type) {
    $scope.loading = true;
    // The GET request for getting data from the repo
    var req = {
      method: 'GET',
      url: url,
      headers: {
        'Authorization': 'token ' + $scope.token
      }
    }
    $http(req).
    success(function (data, status, headers, config) {
      switch (type) {
        case 'getRepos':
          $scope.repoData = data;
          break;
        case 'getMilestones':
          $scope.milestonesData = data;
          break;
        case 'getIssues':
          $scope.results = data;
          break;
      }
      $scope.loading = false;
    }).
    error(function (data, status, headers, config) {
      $scope.errorMessage = 'Something went wrong: ' + data + ' - Status: ' + status
      + ' - headers: ' + headers + ' - Config: ' + config;
    });
  }

  // Setting up / clearing of the params
  $scope.setDefaults = function (pageLoaded) {
    $scope.token = localStorageSetGet.get('token');
    if($scope.token){
      $scope.tokenSet = true;
      $scope.getGitData('https://api.github.com/user/repos', 'getRepos');
    }else{
      $scope.tokenSet = false;
    }
    $scope.repoName = '';
    $scope.repoSet = false;
    $scope.milestoneName = '';
    $scope.milestoneSet = 'false';
    $scope.milestoneId = '';
    $scope.issues = '';
    $scope.results = '';
  }

  $location.search({});

  // Initial run
  $scope.setDefaults();

});
<commit_msg>Adjusted loading SVG sequence<commit_after>// homeController.js
// Controller for the home page

app.controller('homeController', function ($scope, $http, $window, $location, localStorageService, localStorageSetGet) {
  $scope.saveRepo = function (repoPassed) {
    $scope.repoSet = true;
    $scope.repoName = repoPassed;
    $scope.getGitData('https://api.github.com/repos/' + $scope.repoName + '/milestones?state=all', 'getMilestones');
  }

  $scope.saveMilestone = function (milestonePassed, milestoneId) {
    $scope.milestoneSet = true;
    $scope.milestoneName = milestonePassed;
    $scope.milestoneId = milestoneId;
    $scope.getGitData('https://api.github.com/repos/' + $scope.repoName +
    '/issues?state=all&filter=all&milestone=' + $scope.milestoneId, 'getIssues');
  }

  $scope.getGitData = function (url, type) {
    $scope.loading = true;
    // The GET request for getting data from the repo
    var req = {
      method: 'GET',
      url: url,
      headers: {
        'Authorization': 'token ' + $scope.token
      }
    }
    $http(req).
    success(function (data, status, headers, config) {
      switch (type) {
        case 'getRepos':
          $scope.repoData = data;
          break;
        case 'getMilestones':
          $scope.milestonesData = data;
          break;
        case 'getIssues':
          $scope.results = data;
          break;
      }
      $scope.loading = false;
    }).
    error(function (data, status, headers, config) {
      $scope.errorMessage = 'Something went wrong: ' + data + ' - Status: ' + status
      + ' - headers: ' + headers + ' - Config: ' + config;
      $scope.loading = false;
    });
  }

  // Setting up / clearing of the params
  $scope.setDefaults = function (pageLoaded) {
    $scope.token = localStorageSetGet.get('token');
    if($scope.token){
      $scope.tokenSet = true;
      $scope.getGitData('https://api.github.com/user/repos', 'getRepos');
    }else{
      $scope.tokenSet = false;
    }
    $scope.repoName = '';
    $scope.repoSet = false;
    $scope.milestoneName = '';
    $scope.milestoneSet = 'false';
    $scope.milestoneId = '';
    $scope.issues = '';
    $scope.results = '';
  }

  $location.search({});

  // Initial run
  $scope.setDefaults();
  $scope.loading = false;

});
<|endoftext|>


<commit_before>const _ = require('lodash');

const convert = require('./convert');

const mapActionObject = a => {
    if (a.effect === 'colorloop') {
        return {
            on: a.on,
            colorloop: true
        };
    }
    else if (a.colormode === 'ct') {
        return {
            on: a.on,
            colorTemp: convert.miredToTemp(a.ct)
        };
    }
    else if (a.colormode === 'hs' || a.colormode === 'xy') {
        return {
            on: a.on,
            color: convert.hueToRgbString([a.hue, a.sat, a.bri])
        };
    }
    return a;
};

module.exports = {
    mapActionObject: mapActionObject,
    mapStateObject: s => _.assign(mapActionObject(s), { reachable: s.reachable })
};
<commit_msg>assign to an empty object just in case<commit_after>const _ = require('lodash');

const convert = require('./convert');

const mapActionObject = a => {
    if (a.effect === 'colorloop') {
        return {
            on: a.on,
            colorloop: true
        };
    }
    else if (a.colormode === 'ct') {
        return {
            on: a.on,
            colorTemp: convert.miredToTemp(a.ct)
        };
    }
    else if (a.colormode === 'hs' || a.colormode === 'xy') {
        return {
            on: a.on,
            color: convert.hueToRgbString([a.hue, a.sat, a.bri])
        };
    }
    return a;
};

module.exports = {
    mapActionObject: mapActionObject,
    mapStateObject: s => _.assign({}, mapActionObject(s), { reachable: s.reachable })
};
<|endoftext|>


<commit_before>var _ = require('underscore');
var Backbone = require('backbone');
var d3 = require('d3');
var CategoryFilter = require('../../../windshaft/filters/category');
var RangeFilter = require('../../../windshaft/filters/range');

var GeoJSONDataProvider = function (vectorLayerView, layerIndex) {
  this._vectorLayerView = vectorLayerView;
  this._layerIndex = layerIndex;

  vectorLayerView._on('featuresChanged', function (features) {
    this.trigger('featuresChanged', features[this._layerIndex]);
  }.bind(this));
};

// TODO: We can extract each "generator" to an individual file so that this file doesn't get too BIG
GeoJSONDataProvider.prototype._dataGeneratorsForDataviews = {
  histogram: function (features, options) {
    var filter = this._vectorLayerView.getFilter(this._layerIndex);
    var columnName = options.column;
    var end, start, bins, width, values;
    var numberOfBins = options.bins || options.data.length;
    if (options.own_filter === 1) {
      end = filter.getMax(columnName);
      start = filter.getMin(columnName);
      values = filter.getValues();
      bins = d3.layout.histogram().bins(numberOfBins)(filter.getValues().map(function (f) {
        return f.properties[options.column];
      }));
      width = (end - start) / options.data.length;
    } else {
      end = options.end || filter.getMax(columnName);
      start = typeof options.start === 'number' ? options.start : filter.getMin(columnName);
      width = (end - start) / options.bins;
      values = filter.getValues(false, columnName);
      bins = d3.layout.histogram().bins(numberOfBins)(filter.getValues(false, columnName).map(function (f) {
        return f.properties[options.column];
      }));
    }
    bins = bins.map(function (bin, index) {
      return {
        bin: index,
        max: d3.max(bin),
        min: d3.min(bin),
        avg: d3.mean(bin),
        freq: bin.length
      };
    });
    var nulls = values.reduce(function (p, c) { return p + (c.properties[columnName] === null ? 1 : 0); }, 0);
    var average = bins.reduce(function (p, c) {
      return p + c.avg;
    }, 0) / bins.reduce(function (p, c) {
      return p + c.freq;
    }, 0);
    var histogram = {
      'bin_width': width,
      'bins_count': bins.length,
      'bins_start': start,
      'nulls': nulls,
      'avg': average,
      'bins': bins,
      'type': 'histogram'
    };
    return histogram;
  },
  category: function (features, options) {
    var columnName = options.column;
    var filterEnabled = options.filterEnabled;
    var numberOfCategories = 5;

    var sortedGroups;
    var count;
    if (filterEnabled) {
      // TODO: There's probably a more efficient way of doing this
      var groups = _.groupBy(features, function (feature) { return feature.properties[columnName]; });
      var groupCounts = _.map(Object.keys(groups), function (key) {
        return {
          key: key,
          value: groups[key].length
        };
      });
      sortedGroups = _.sortBy(groupCounts, function (group) {
        return group.value;
      }).reverse();
      count = features.length;
    } else {
      var filter = this._vectorLayerView.getFilter(this._layerIndex);
      sortedGroups = filter.getColumnValues(columnName);
      count = filter.getCount(columnName);
    }
    var nulls = filter.getValues(false, columnName).reduce(function (p, c) { return p + (c.properties[columnName] === null ? 1 : 0); }, 0);
    var data = {
      categories: [],
      categoriesCount: sortedGroups.length,
      count: count,
      max: sortedGroups[0].value,
      min: sortedGroups[sortedGroups.length - 1].value,
      nulls: nulls,
      type: 'aggregation'
    };

    _.each(sortedGroups.slice(0, numberOfCategories), function (category) {
      data.categories.push({
        category: category.key,
        value: category.value,
        agg: false
      });
    });

    if (!filterEnabled) {
      var lastCat = {
        category: 'Other',
        value: sortedGroups.slice(numberOfCategories).reduce(function (p, c) {
          return p + c.value;
        }, 0),
        agg: true
      };
      data.categories.push(lastCat);
    }
    return data;
  },

  formula: function (features, options) {
    var operation = options.operation;
    var columnName = options.column;
    var nulls = features.reduce(function (p, c) { return p + (c.properties[columnName] === null ? 1 : 0); }, 0);
    var result;
    if (operation === 'count') {
      result = features.length;
    } else if (operation === 'avg') {
      result = features.reduce(function (p, c) { return p + c.properties[columnName]; }, 0) / features.length;
    } else if (operation === 'sum') {
      result = features.reduce(function (p, c) { return p + c.properties[columnName]; }, 0);
    } else if (operation === 'min') {
      result = features.reduce(function (p, c) { return Math.min(p, c.properties[columnName]); }, Infinity);
    } else if (operation === 'max') {
      result = features.reduce(function (p, c) { return Math.max(p, c.properties[columnName]); }, 0);
    } else {
      throw new Error("Coudn't generate data for formula dataview and '" + operation + "' operation.");
    }
    var data = {
      'operation': operation,
      'result': result,
      'nulls': nulls,
      'type': 'formula'
    };
    return data;
  }
};

GeoJSONDataProvider.prototype.generateDataForDataview = function (dataview, features) {
  var generateData = this._dataGeneratorsForDataviews[dataview.get('type')].bind(this);
  if (!generateData) {
    throw new Error("Couldn't generate data for dataview of type: " + dataview.get('type'));
  }

  // TODO: Each generator needs different options show we should be more
  // explicit instead of passing dataview.attributes through.
  var data = generateData(features, dataview.attributes);
  return data;
};

GeoJSONDataProvider.prototype.applyFilter = function (columnName, filter) {
  var filterType;
  var filterOptions;
  if (filter instanceof CategoryFilter) {
    if (filter.isEmpty()) {
      filterType = 'accept';
      filterOptions = { column: columnName, values: 'all' };
    } else if (filter.get('rejectAll')) {
      filterType = 'reject';
      filterOptions = { column: columnName, values: 'all' };
    } else if (filter.acceptedCategories.size()) {
      filterType = 'accept';
      filterOptions = { column: columnName, values: filter.getAcceptedCategoryNames() };
    } else if (filter.rejectedCategories.size()) {
      filterType = 'reject';
      filterOptions = { column: columnName, values: filter.getRejectedCategoryNames() };
    }
  } else if (filter instanceof RangeFilter) {
    filterType = 'range';
    if (filter.isEmpty()) {
      filterOptions = { column: columnName, min: 0, max: Infinity };
    } else {
      filterOptions = { column: columnName, min: filter.get('min'), max: filter.get('max') };
    }
  } else {
    throw new Error('Filter on ' + columnName + " couldn't be applied. Filter type wasn't recognized.");
  }

  this._vectorLayerView.applyFilter(this._layerIndex, filterType, filterOptions);
};

GeoJSONDataProvider.prototype.getData = function () {
  return this._vectorLayerView.getFeatures()[this._layerIndex];
};

_.extend(GeoJSONDataProvider.prototype, Backbone.Events);

module.exports = GeoJSONDataProvider;
<commit_msg>doesn't add OTHER if there are no others<commit_after>var _ = require('underscore');
var Backbone = require('backbone');
var d3 = require('d3');
var CategoryFilter = require('../../../windshaft/filters/category');
var RangeFilter = require('../../../windshaft/filters/range');

var GeoJSONDataProvider = function (vectorLayerView, layerIndex) {
  this._vectorLayerView = vectorLayerView;
  this._layerIndex = layerIndex;

  vectorLayerView._on('featuresChanged', function (features) {
    this.trigger('featuresChanged', features[this._layerIndex]);
  }.bind(this));
};

// TODO: We can extract each "generator" to an individual file so that this file doesn't get too BIG
GeoJSONDataProvider.prototype._dataGeneratorsForDataviews = {
  histogram: function (features, options) {
    var filter = this._vectorLayerView.getFilter(this._layerIndex);
    var columnName = options.column;
    var end, start, bins, width, values;
    var numberOfBins = options.bins || options.data.length;
    if (options.own_filter === 1) {
      end = filter.getMax(columnName);
      start = filter.getMin(columnName);
      values = filter.getValues();
      bins = d3.layout.histogram().bins(numberOfBins)(filter.getValues().map(function (f) {
        return f.properties[options.column];
      }));
      width = (end - start) / options.data.length;
    } else {
      end = options.end || filter.getMax(columnName);
      start = typeof options.start === 'number' ? options.start : filter.getMin(columnName);
      width = (end - start) / options.bins;
      values = filter.getValues(false, columnName);
      bins = d3.layout.histogram().bins(numberOfBins)(filter.getValues(false, columnName).map(function (f) {
        return f.properties[options.column];
      }));
    }
    bins = bins.map(function (bin, index) {
      return {
        bin: index,
        max: d3.max(bin),
        min: d3.min(bin),
        avg: d3.mean(bin),
        freq: bin.length
      };
    });
    var nulls = values.reduce(function (p, c) { return p + (c.properties[columnName] === null ? 1 : 0); }, 0);
    var average = bins.reduce(function (p, c) {
      return p + c.avg;
    }, 0) / bins.reduce(function (p, c) {
      return p + c.freq;
    }, 0);
    var histogram = {
      'bin_width': width,
      'bins_count': bins.length,
      'bins_start': start,
      'nulls': nulls,
      'avg': average,
      'bins': bins,
      'type': 'histogram'
    };
    return histogram;
  },
  category: function (features, options) {
    var columnName = options.column;
    var filterEnabled = options.filterEnabled;
    var numberOfCategories = 5;

    var sortedGroups;
    var count;
    if (filterEnabled) {
      // TODO: There's probably a more efficient way of doing this
      var groups = _.groupBy(features, function (feature) { return feature.properties[columnName]; });
      var groupCounts = _.map(Object.keys(groups), function (key) {
        return {
          key: key,
          value: groups[key].length
        };
      });
      sortedGroups = _.sortBy(groupCounts, function (group) {
        return group.value;
      }).reverse();
      count = features.length;
    } else {
      var filter = this._vectorLayerView.getFilter(this._layerIndex);
      sortedGroups = filter.getColumnValues(columnName);
      count = filter.getCount(columnName);
    }
    var nulls = filter.getValues(false, columnName).reduce(function (p, c) { return p + (c.properties[columnName] === null ? 1 : 0); }, 0);
    var data = {
      categories: [],
      categoriesCount: sortedGroups.length,
      count: count,
      max: sortedGroups[0].value,
      min: sortedGroups[sortedGroups.length - 1].value,
      nulls: nulls,
      type: 'aggregation'
    };

    _.each(sortedGroups.slice(0, numberOfCategories), function (category) {
      data.categories.push({
        category: category.key,
        value: category.value,
        agg: false
      });
    });
    var remainingCategories = sortedGroups.slice(numberOfCategories);
    if (!filterEnabled && remainingCategories.length > 0) {
      var lastCat = {
        category: 'Other',
        value: remainingCategories.reduce(function (p, c) {
          return p + c.value;
        }, 0),
        agg: true
      };
      data.categories.push(lastCat);
    }
    return data;
  },

  formula: function (features, options) {
    var operation = options.operation;
    var columnName = options.column;
    var nulls = features.reduce(function (p, c) { return p + (c.properties[columnName] === null ? 1 : 0); }, 0);
    var result;
    if (operation === 'count') {
      result = features.length;
    } else if (operation === 'avg') {
      result = features.reduce(function (p, c) { return p + c.properties[columnName]; }, 0) / features.length;
    } else if (operation === 'sum') {
      result = features.reduce(function (p, c) { return p + c.properties[columnName]; }, 0);
    } else if (operation === 'min') {
      result = features.reduce(function (p, c) { return Math.min(p, c.properties[columnName]); }, Infinity);
    } else if (operation === 'max') {
      result = features.reduce(function (p, c) { return Math.max(p, c.properties[columnName]); }, 0);
    } else {
      throw new Error("Coudn't generate data for formula dataview and '" + operation + "' operation.");
    }
    var data = {
      'operation': operation,
      'result': result,
      'nulls': nulls,
      'type': 'formula'
    };
    return data;
  }
};

GeoJSONDataProvider.prototype.generateDataForDataview = function (dataview, features) {
  var generateData = this._dataGeneratorsForDataviews[dataview.get('type')].bind(this);
  if (!generateData) {
    throw new Error("Couldn't generate data for dataview of type: " + dataview.get('type'));
  }

  // TODO: Each generator needs different options show we should be more
  // explicit instead of passing dataview.attributes through.
  var data = generateData(features, dataview.attributes);
  return data;
};

GeoJSONDataProvider.prototype.applyFilter = function (columnName, filter) {
  var filterType;
  var filterOptions;
  if (filter instanceof CategoryFilter) {
    if (filter.isEmpty()) {
      filterType = 'accept';
      filterOptions = { column: columnName, values: 'all' };
    } else if (filter.get('rejectAll')) {
      filterType = 'reject';
      filterOptions = { column: columnName, values: 'all' };
    } else if (filter.acceptedCategories.size()) {
      filterType = 'accept';
      filterOptions = { column: columnName, values: filter.getAcceptedCategoryNames() };
    } else if (filter.rejectedCategories.size()) {
      filterType = 'reject';
      filterOptions = { column: columnName, values: filter.getRejectedCategoryNames() };
    }
  } else if (filter instanceof RangeFilter) {
    filterType = 'range';
    if (filter.isEmpty()) {
      filterOptions = { column: columnName, min: 0, max: Infinity };
    } else {
      filterOptions = { column: columnName, min: filter.get('min'), max: filter.get('max') };
    }
  } else {
    throw new Error('Filter on ' + columnName + " couldn't be applied. Filter type wasn't recognized.");
  }

  this._vectorLayerView.applyFilter(this._layerIndex, filterType, filterOptions);
};

GeoJSONDataProvider.prototype.getData = function () {
  return this._vectorLayerView.getFeatures()[this._layerIndex];
};

_.extend(GeoJSONDataProvider.prototype, Backbone.Events);

module.exports = GeoJSONDataProvider;
<|endoftext|>


<commit_before>// aurelia-i18n-loader
// an implementation of an i18next Backend that uses the aurelia loader to load the json translation files
// based on i18next-xhr-backend
//
// usage:
// aurelia.use.plugin('aurelia-i18n', (instance) => {
//    // register backend plugin
//    instance.i18next.use(Backend.with(aurelia.loader));

export class Backend {
  static loader = null; // static loader to support passing the aurelia-loader

  static with(loader) {
    this.loader = loader;
    return this;
  }

  constructor(services, options = {}) {
    this.init(services, options);
    this.type = 'backend';
  }

  init(services, options = {}) {
    this.services = services;
    this.options = defaults(options, this.options || {}, getDefaults());
  }

  readMulti(languages, namespaces, callback) {
    let loadPath = this.options.loadPath;

    if (typeof this.options.loadPath === 'function') {
      loadPath = this.options.loadPath(languages, namespaces);
    }

    let url = this.services.interpolator.interpolate(loadPath, { lng: languages.join('+'), ns: namespaces.join('+') });

    this.loadUrl(url, callback);
  }

  read(language, namespace, callback) {
    let loadPath = this.options.loadPath;

    if (typeof this.options.loadPath === 'function') {
      loadPath = this.options.loadPath([language], [namespace]);
    }

    let url = this.services.interpolator.interpolate(loadPath, { lng: language, ns: namespace });

    this.loadUrl(url, callback);
  }

  loadUrl(url, callback) {
    this.constructor.loader.loadText(url)
    .then(response=>{
      let ret;
      let err;
      try {
        ret = this.options.parse(response, url);
      } catch (e) {
        err = 'failed parsing ' + url + ' to json';
      }
      if (err) return callback(err, false);
      callback(null, ret);
    },
    response=>{
      return callback('failed loading ' + url, false /* no retry */);
    });
  }

  create(languages, namespace, key, fallbackValue) {
    // create is not (yet) supported
  }
}

Backend.type = 'backend';
export default Backend;

// helper functions
let arr = [];
let each = arr.forEach;
let slice = arr.slice;

function getDefaults() {
  return {
    loadPath: '/locales/{{lng}}/{{ns}}.json',
    addPath: 'locales/add/{{lng}}/{{ns}}',
    allowMultiLoading: false,
    parse: JSON.parse
  };
}

function defaults(obj) {
  each.call(slice.call(arguments, 1), function(source) {
    if (source) {
      for (let prop in source) {
        if (obj[prop] === undefined) obj[prop] = source[prop];
      }
    }
  });
  return obj;
}
<commit_msg>don't try to parse translation json if already parsed<commit_after>// aurelia-i18n-loader
// an implementation of an i18next Backend that uses the aurelia loader to load the json translation files
// based on i18next-xhr-backend
//
// usage:
// aurelia.use.plugin('aurelia-i18n', (instance) => {
//    // register backend plugin
//    instance.i18next.use(Backend.with(aurelia.loader));

export class Backend {
  static loader = null; // static loader to support passing the aurelia-loader

  static with(loader) {
    this.loader = loader;
    return this;
  }

  constructor(services, options = {}) {
    this.init(services, options);
    this.type = 'backend';
  }

  init(services, options = {}) {
    this.services = services;
    this.options = defaults(options, this.options || {}, getDefaults());
  }

  readMulti(languages, namespaces, callback) {
    let loadPath = this.options.loadPath;

    if (typeof this.options.loadPath === 'function') {
      loadPath = this.options.loadPath(languages, namespaces);
    }

    let url = this.services.interpolator.interpolate(loadPath, { lng: languages.join('+'), ns: namespaces.join('+') });

    this.loadUrl(url, callback);
  }

  read(language, namespace, callback) {
    let loadPath = this.options.loadPath;

    if (typeof this.options.loadPath === 'function') {
      loadPath = this.options.loadPath([language], [namespace]);
    }

    let url = this.services.interpolator.interpolate(loadPath, { lng: language, ns: namespace });

    this.loadUrl(url, callback);
  }

  loadUrl(url, callback) {
    this.constructor.loader.loadText(url)
    .then(response=>{
      let ret;
      let err;
      try {
        ret = (response instanceof Object) ? response : this.options.parse(response, url);
      } catch (e) {
        err = 'failed parsing ' + url + ' to json';
      }
      if (err) return callback(err, false);
      callback(null, ret);
    },
    response=>{
      return callback('failed loading ' + url, false /* no retry */);
    });
  }

  create(languages, namespace, key, fallbackValue) {
    // create is not (yet) supported
  }
}

Backend.type = 'backend';
export default Backend;

// helper functions
let arr = [];
let each = arr.forEach;
let slice = arr.slice;

function getDefaults() {
  return {
    loadPath: '/locales/{{lng}}/{{ns}}.json',
    addPath: 'locales/add/{{lng}}/{{ns}}',
    allowMultiLoading: false,
    parse: JSON.parse
  };
}

function defaults(obj) {
  each.call(slice.call(arguments, 1), function(source) {
    if (source) {
      for (let prop in source) {
        if (obj[prop] === undefined) obj[prop] = source[prop];
      }
    }
  });
  return obj;
}
<|endoftext|>


<commit_before>function ddg_spice_search_code(data) {
    if(data.results.length > 0) {

        var searchterm; // holds the search term
        var result; // holds the main result

        result = data.results[0];
        searchterm = data.query;

        var div = d.createElement('div');
        var div2 = d.createElement('div');
        YAHOO.util.Dom.addClass(div2,'zero_click_searchcode');

        div2.innerHTML = search_codeFormatZeroClick(result);

        div.appendChild(div2);

	if (DDG.isRelevant(result.name + ' ' + result.displayname + ' ' + result.namespace, '', 2)) {

	    items = [[]];
	    items[0]['a'] = div.innerHTML;
	    items[0]['h'] = search_codeFormatName(result);
	    items[0]['s'] = 'search[code]';
	    items[0]['u'] = 'http://searchco.de/?q='+encodeURIComponent(searchterm);

	    // DDG rendering function is nra.
	    nra(items);
	}
    }
}

function search_codeFormatName(result) {
    var formatted_name = result.name;

    if (result.displayname != '' || result.namespace != '') {
	formatted_name += ' (';

	if (result.displayname != '') formatted_name += result.displayname;

	if (result.namespace != '') formatted_name += (result.displayname ? ', ' : '') + result.namespace;

	formatted_name += ')';
    }

    return formatted_name;
}

function search_codeFormatZeroClick(result) {
    if(result.synopsis != '') {
        return '
' + result.synopsis + '
' + result.description + '
[Reference]';
    } else {
        return result.description + '
[Reference]';
    }
}

// This uses the browser to strip HTML, possibly YUI2 has better way to do this
function search_codeStrip(html) {
    var tmp = document.createElement("div");
    tmp.innerHTML = html;
    return tmp.textContent||tmp.innerText;
}<commit_msg>Move isrelevant check for searccode inside result array, so if first fails others could pick up.<commit_after>function ddg_spice_search_code(data) {
    if(data.results.length > 0) {

        var searchterm; // holds the search term
        var result; // holds the main result

	for (var i=0; i<data.results.length; i++) {
	    var tmp_result = data.results[i];
	    if (!DDG.isRelevant(tmp_result.name + ' ' + tmp_result.displayname + ' ' + tmp_result.namespace, '', 2)) continue;
	    result = tmp_result;
	}

	if (!result) return;

        searchterm = data.query;

        var div = d.createElement('div');
        var div2 = d.createElement('div');
        YAHOO.util.Dom.addClass(div2,'zero_click_searchcode');

        div2.innerHTML = search_codeFormatZeroClick(result);

        div.appendChild(div2);

	items = [[]];
	items[0]['a'] = div.innerHTML;
	items[0]['h'] = search_codeFormatName(result);
	items[0]['s'] = 'search[code]';
	items[0]['u'] = 'http://searchco.de/?q='+encodeURIComponent(searchterm);

	// DDG rendering function is nra.
	nra(items);
    }
}

function search_codeFormatName(result) {
    var formatted_name = result.name;

    if (result.displayname != '' || result.namespace != '') {
	formatted_name += ' (';

	if (result.displayname != '') formatted_name += result.displayname;

	if (result.namespace != '') formatted_name += (result.displayname ? ', ' : '') + result.namespace;

	formatted_name += ')';
    }

    return formatted_name;
}

function search_codeFormatZeroClick(result) {
    if(result.synopsis != '') {
        return '
' + result.synopsis + '
' + result.description + '
[Reference]';
    } else {
        return result.description + '
[Reference]';
    }
}

// This uses the browser to strip HTML, possibly YUI2 has better way to do this
function search_codeStrip(html) {
    var tmp = document.createElement("div");
    tmp.innerHTML = html;
    return tmp.textContent||tmp.innerText;
}<|endoftext|>


<commit_before>import './dropdown_emoji';
import './dropdown_hint';
import './dropdown_non_user';
import './dropdown_user';
import './dropdown_utils';
import './filtered_search_token_keys';
import './filtered_search_dropdown_manager';
import './filtered_search_dropdown';
import './filtered_search_manager';
import './filtered_search_tokenizer';
import './filtered_search_visual_tokens';
<commit_msg>Remove `FilteredSearchTokenKeys` import<commit_after>import './dropdown_emoji';
import './dropdown_hint';
import './dropdown_non_user';
import './dropdown_user';
import './dropdown_utils';
import './filtered_search_dropdown_manager';
import './filtered_search_dropdown';
import './filtered_search_manager';
import './filtered_search_tokenizer';
import './filtered_search_visual_tokens';
<|endoftext|>


<commit_before>function parseRoutes (config) {
  const __uniRoutes = []
  /* eslint-disable no-mixed-operators */
  const tabBarList = (config.tabBar && config.tabBar.list || []).map(item => item.pagePath)

  Object.keys(config.page).forEach(function (pagePath) {
    const isTabBar = tabBarList.indexOf(pagePath) !== -1
    const isQuit = isTabBar || (config.pages[0] === pagePath)
    const isNVue = !!config.page[pagePath].nvue
    const route = {
      path: '/' + pagePath,
      meta: {},
      window: config.page[pagePath].window || {}
    }
    if (isQuit) {
      route.meta.isQuit = true
    }
    if (isNVue) {
      route.meta.isNVue = true
    }
    if (isTabBar) {
      route.meta.isTabBar = true
    }
    __uniRoutes.push(route)
  })

  return __uniRoutes
}
module.exports = function definePages (appJson) {
  const __uniRoutes = parseRoutes(appJson)

  delete appJson.page
  delete appJson.usingComponents
  delete appJson.nvueCompiler
  delete appJson.renderer

  return {
    name: 'app-config-service.js',
    content: `
var isReady=false;var onReadyCallbacks=[];
var __uniConfig = ${JSON.stringify(appJson, null)};
var __uniRoutes = ${JSON.stringify(__uniRoutes)};
__uniConfig.onReady=function(callback){if(__uniConfig.ready){callback()}else{onReadyCallbacks.push(callback)}};Object.defineProperty(__uniConfig,"ready",{get:function(){return isReady},set:function(val){isReady=val;if(!isReady){return}const callbacks=onReadyCallbacks.slice(0);onReadyCallbacks.length=0;callbacks.forEach(function(callback){callback()})}});
service.register("uni-app-config",{create(a,b,c){if(!__uniConfig.viewport){var d=b.weex.config.env.scale,e=b.weex.config.env.deviceWidth,f=Math.ceil(e/d);Object.assign(__uniConfig,{viewport:f,defaultFontSize:Math.round(f/20)})}return{instance:{__uniConfig:__uniConfig,__uniRoutes:__uniRoutes}}}});
`
  }
}
<commit_msg>fix(v3): compatible with umd<commit_after>function parseRoutes (config) {
  const __uniRoutes = []
  /* eslint-disable no-mixed-operators */
  const tabBarList = (config.tabBar && config.tabBar.list || []).map(item => item.pagePath)

  Object.keys(config.page).forEach(function (pagePath) {
    const isTabBar = tabBarList.indexOf(pagePath) !== -1
    const isQuit = isTabBar || (config.pages[0] === pagePath)
    const isNVue = !!config.page[pagePath].nvue
    const route = {
      path: '/' + pagePath,
      meta: {},
      window: config.page[pagePath].window || {}
    }
    if (isQuit) {
      route.meta.isQuit = true
    }
    if (isNVue) {
      route.meta.isNVue = true
    }
    if (isTabBar) {
      route.meta.isTabBar = true
    }
    __uniRoutes.push(route)
  })

  return __uniRoutes
}
module.exports = function definePages (appJson) {
  const __uniRoutes = parseRoutes(appJson)

  delete appJson.page
  delete appJson.usingComponents
  delete appJson.nvueCompiler
  delete appJson.renderer

  return {
    name: 'app-config-service.js',
    content: `
var isReady=false;var onReadyCallbacks=[];
var __uniConfig = ${JSON.stringify(appJson, null)};
var __uniRoutes = ${JSON.stringify(__uniRoutes)};
__uniConfig.onReady=function(callback){if(__uniConfig.ready){callback()}else{onReadyCallbacks.push(callback)}};Object.defineProperty(__uniConfig,"ready",{get:function(){return isReady},set:function(val){isReady=val;if(!isReady){return}const callbacks=onReadyCallbacks.slice(0);onReadyCallbacks.length=0;callbacks.forEach(function(callback){callback()})}});
service.register("uni-app-config",{create(a,b,c){if(!__uniConfig.viewport){var d=b.weex.config.env.scale,e=b.weex.config.env.deviceWidth,f=Math.ceil(e/d);Object.assign(__uniConfig,{viewport:f,defaultFontSize:Math.round(f/20)})}return{instance:{__uniConfig:__uniConfig,__uniRoutes:__uniRoutes,window:void 0}}}});
`
  }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc directive
 *
 * @name solrSearch
 *
 * @description
 * Search input for solr
 */
(function() {

  angular
    .module('dhsniem')
    .directive('solrSearch', solrSearch);

  function solrSearch($location, $state, solrSearch, solrRequest) {
    return {
      restrict: 'E',
      templateUrl: 'app/components/solrSearch/solrSearch.directive.html',
      scope: {
        hasLabel: '='
      },
      link: link
    };

    /**
     *  Defines variables and functions within solrSearch scope
     */
    function link(scope, element, attrs) {

      scope.searchQuery = $location.search().q;

      scope.search = function search(taItem) {

        var domainParam = '';

        if (taItem && taItem.taDomain) {
          scope.searchQuery = taItem.query;
          if (taItem.taDomain !== 'all') {
            domainParam = 'domain:"' + taItem.taDomain + '"';
          }
        }

        var query = scope.searchQuery || '*';

        if (!$state.includes('main.results')) {
          $state.go('main.results', {q: query, selectedFacets: domainParam});
        } else {
          $location.search('q', query);
          solrSearch.clearAllFilters(domainParam);
        }

      };

      scope.getTypeaheadResults = function(query) {

        var params = {
          'q': 'name:*' + query + '*',
          'rows': 5,
          'wt': 'json',
          'json.wrf': 'JSON_CALLBACK',
          'json.nl': 'map'
        };

        var domainArray = [{'name': query + ' in All Domains', 'taDomain': 'all', 'query': query}, {'name': query + ' in NIEM Core', 'taDomain': 'NIEM Core', 'query': query}];

        return solrRequest.makeSolrRequest(params).then(function(data) {
          if (data.response.docs.length > 0) {
            var topNamespace = data.response.docs[0].namespace;
            var topNamespaceType = data.response.docs[0].namespaceType;
            domainArray.push({'name': query + ' in ' + topNamespace, 'taDomain': topNamespace, 'query': query});
            return domainArray.concat(data.response.docs);
          }
        });

      };

    }

  }

})();
<commit_msg>full implementation for typeahead and click on results<commit_after>'use strict';

/**
 * @ngdoc directive
 *
 * @name solrSearch
 *
 * @description
 * Search input for solr
 */
(function() {

  angular
    .module('dhsniem')
    .directive('solrSearch', solrSearch);

  function solrSearch($location, $state, solrSearch, solrRequest) {
    return {
      restrict: 'E',
      templateUrl: 'app/components/solrSearch/solrSearch.directive.html',
      scope: {
        hasLabel: '='
      },
      link: link
    };

    /**
     *  Defines variables and functions within solrSearch scope
     */
    function link(scope, element, attrs) {

      scope.searchQuery = $location.search().q;

      scope.search = function search(taItem) {

        var namespaceParam = '';

        if (taItem && taItem.taNS) {
          scope.searchQuery = taItem.query;
          if (taItem.taNS !== 'all') {
            namespaceParam = taItem.taNSType + ':"' + taItem.taNS + '"';
          }
        }

        var query = scope.searchQuery || '*';

        if (!$state.includes('main.results')) {
          $state.go('main.results', {q: query, selectedFacets: namespaceParam});
        } else {
          $location.search('q', query);
          solrSearch.clearAllFilters(namespaceParam);
        }

      };

      scope.getTypeaheadResults = function(query) {

        var params = {
          'q': 'name:*' + query + '*',
          'rows': 5,
          'wt': 'json',
          'json.wrf': 'JSON_CALLBACK',
          'json.nl': 'map'
        };

        var domainArray = [{'name': query + ' in All Domains', 'taNS': 'all', 'query': query}, {'name': query + ' in NIEM Core', 'taNS': 'NIEM Core', 'query': query, 'taNSType': 'domain'}];

        return solrRequest.makeSolrRequest(params).then(function(data) {
          if (data.response.docs.length > 0) {
            var topNamespace = data.response.docs[0].namespace;
            var topNamespaceType = data.response.docs[0].namespaceType;
            domainArray.push({'name': query + ' in ' + topNamespace, 'taNS': topNamespace, 'query': query, 'taNSType': topNamespaceType});
            return domainArray.concat(data.response.docs);
          }
        });

      };

    }

  }

})();
<|endoftext|>


<commit_before>// ==UserScript==
// @name           Add AWS region to title
// @namespace      curipha
// @description    Help to know where I am now
// @match          https://console.aws.amazon.com/*
// @match          https://*.console.aws.amazon.com/*
// @version        0.0.2
// @grant          none
// @noframes
// ==/UserScript==

(function() {
  'use strict';

  const regelem = document.getElementById('nav-regionMenu');
  if (regelem) {
    const region = regelem.textContent.trim();
    document.title += ` (${ region.length > 0 ? region : '???' })`;
  }
})();
<commit_msg>v0.0.3<commit_after>// ==UserScript==
// @name           Add AWS region to title
// @namespace      curipha
// @description    Help to know where I am now
// @match          https://console.aws.amazon.com/*
// @match          https://*.console.aws.amazon.com/*
// @version        0.0.3
// @grant          none
// @noframes
// ==/UserScript==

(function() {
  'use strict';

  const regelem = document.getElementById('nav-regionMenu');
  if (regelem) {
    const region = regelem.textContent.trim();
    document.title += ` (${ region.length > 0 ? region : '???' })`;
  }
})();
<|endoftext|>


<commit_before>const handlebars = require('handlebars');

module.exports = {
  commitFilesToBranch,
};

async function commitFilesToBranch(config) {
  const updatedFiles = config.updatedPackageFiles.concat(
    config.updatedLockFiles
  );
  if (updatedFiles.length) {
    logger.debug(`${updatedFiles.length} file(s) to commit`);
    let commitMessage = handlebars.compile(config.commitMessage)(config);
    if (config.semanticCommits) {
      const splitMessage = commitMessage.split('\n');
      splitMessage[0] = splitMessage[0].toLowerCase();
      let semanticPrefix = config.semanticCommitType;
      if (config.semanticCommitScope) {
        semanticPrefix += `(${config.semanticCommitScope})`;
      }
      commitMessage = `${semanticPrefix}: ${splitMessage.join('\n')}`;
    }
    if (config.commitBody) {
      commitMessage = `${commitMessage}\n\n${handlebars.compile(
        config.commitBody
      )(config)}`;
    }
    // API will know whether to create new branch or not
    await platform.commitFilesToBranch(
      config.branchName,
      updatedFiles,
      commitMessage,
      config.parentBranch || config.baseBranch || undefined,
      config.gitAuthor,
      config.gitPrivateKey
    );
  } else {
    logger.debug(`No files to commit`);
    return false;
  }
  return true;
}
<commit_msg>fix(semanticCommitScope): compile with handlebars<commit_after>const handlebars = require('handlebars');

module.exports = {
  commitFilesToBranch,
};

async function commitFilesToBranch(config) {
  const updatedFiles = config.updatedPackageFiles.concat(
    config.updatedLockFiles
  );
  if (updatedFiles.length) {
    logger.debug(`${updatedFiles.length} file(s) to commit`);
    let commitMessage = handlebars.compile(config.commitMessage)(config);
    if (config.semanticCommits) {
      const splitMessage = commitMessage.split('\n');
      splitMessage[0] = splitMessage[0].toLowerCase();
      let semanticPrefix = config.semanticCommitType;
      if (config.semanticCommitScope) {
        semanticPrefix += `(${handlebars.compile(config.semanticCommitScope)(
          config
        )})`;
      }
      commitMessage = `${semanticPrefix}: ${splitMessage.join('\n')}`;
    }
    if (config.commitBody) {
      commitMessage = `${commitMessage}\n\n${handlebars.compile(
        config.commitBody
      )(config)}`;
    }
    // API will know whether to create new branch or not
    await platform.commitFilesToBranch(
      config.branchName,
      updatedFiles,
      commitMessage,
      config.parentBranch || config.baseBranch || undefined,
      config.gitAuthor,
      config.gitPrivateKey
    );
  } else {
    logger.debug(`No files to commit`);
    return false;
  }
  return true;
}
<|endoftext|>


<commit_before>const { getBabelLoader } = require('./webpack.helpers');

// Karma configuration
module.exports = (config) => {
  config.set({
    basePath: __dirname,
    frameworks: ['mocha', 'sinon-chai'],
    files: [
      'source/**/*.spec.js',
    ],
    exclude: [],

    preprocessors: {
      'source/**/*.js': ['webpack', 'sourcemap'],
    },
    reporters: ['coverage', 'progress', 'coveralls'],
    coverageReporter: {
      type: 'lcov',
      dir: 'coverage/'
    },
    webpack: {
      resolve: {
        extensions: ['.js']
      },
      module: {
        rules: [
          {
            test: /\.js$/,
            use: getBabelLoader(['babel-plugin-istanbul']),
          },
        ]
      },
      devtool: 'inline-source-map',
    },
    webpackMiddleware: {
      noInfo: true,
      stats: {
        chunks: false,
        colors: true
      },
      stats: 'errors-only'
    },
    plugins: [
      require('karma-webpack'),
      require('karma-coverage'),
      require('karma-coveralls'),
      require('karma-firefox-launcher'),
      require('karma-sourcemap-loader'),
      require('karma-mocha'),
      require('karma-sinon-chai'),
    ],
    port: 9876,
    colors: true,
    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,
    browsers: ['Firefox'],
    //browsers: ['Chrome', 'IE', 'Firefox'],
    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true
  });
};
<commit_msg>exclude *.spec.js files from coverage reports<commit_after>const { getBabelLoader } = require('./webpack.helpers');

// Karma configuration
module.exports = (config) => {
  config.set({
    basePath: __dirname,
    frameworks: ['mocha', 'sinon-chai'],
    files: [
      'source/**/*.spec.js',
    ],
    exclude: [],

    preprocessors: {
      'source/**/*.js': ['webpack', 'sourcemap'],
    },
    reporters: ['coverage', 'progress', 'coveralls'],
    coverageReporter: {
      type: 'lcov',
      dir: 'coverage/'
    },
    webpack: {
      resolve: {
        extensions: ['.js']
      },
      module: {
        rules: [
          {
            test: /\.spec\.js$/,
            use: getBabelLoader(),
          },
          {
            test: /\.js$/,
            exclude: /\.spec\.js$/,
            use: getBabelLoader(['babel-plugin-istanbul']),
          },
        ],
      },
      devtool: 'inline-source-map',
    },
    webpackMiddleware: {
      noInfo: true,
      stats: {
        chunks: false,
        colors: true
      },
      stats: 'errors-only'
    },
    plugins: [
      require('karma-webpack'),
      require('karma-coverage'),
      require('karma-coveralls'),
      require('karma-firefox-launcher'),
      require('karma-sourcemap-loader'),
      require('karma-mocha'),
      require('karma-sinon-chai'),
    ],
    port: 9876,
    colors: true,
    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,
    browsers: ['Firefox'],
    //browsers: ['Chrome', 'IE', 'Firefox'],
    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true
  });
};
<|endoftext|>


<commit_before>
var _path       = require('path');

/** @class
  Functors are special handlers for data requests from the client.
  They are only used by the dataRoute xt route object and are loaded
  automatically at server start.
*/
XT.Functor = XT.Object.extend(
  /** @lends XT.Functor.prototype */ {

  /**
    When loaded by the data route handler it is auto-created
    and thus we want to auto-register to be selectable by
    the route.

    @private
  */
  init: function() {
    if(XT.none(XT.Functors)) XT.Functors = [];
    XT.Functors.push({ handles: this.get('handles'), target: this });
  },

  /**
    A functor must provide a handle method that takes
    a single parameter: the xt response obejct. From here
    it has access to the original response and request objects
    as well as the payload data. The session object will be
    attached to the xt response object by the time this
    method is executed when one can be present. If a functor
    requires a session but the sessionStore fails to retrieve
    the session this method will not be executed.

    @param {Object} xtr The xt response object.
  */
  handle: function(xtr) {},

  /**
    Each functor handles a specific request type from
    the client. This is a string representing the request
    type that it should be selected when this type is
    encountered by the server.

    @type {String}
    @property
  */
  handles: null,

  /**
    Almost all functors should require a session. If they do,
    they will automatically attempt to acquire the session before
    handling the request to ensure they can execute their
    functionality as the correct user. In the rare cases that
    a functor does not require an active session (such as a request
    for a new session) this boolean must be set to false but it
    defaults to true.

    @property
    @type Boolean
    @default true
  */
  needSession: true,

  /** @private */
  className: 'XT.Functor'

});

// make sure to grab and require all of the available functors
XT.run(function() {
  var files;
  var idx = 0;
  var file;
  var path;

  XT.log("Loading available functors from %@".f(
    XT.shorten(_path.join(__dirname, '../functors'), 5)));

  // change directories to path relatively
  process.chdir(__dirname);

  // collect any available javascript files in the directory
  files = XT.directoryFiles('../functors', 'js');

  // require each of them so they are available to any
  // routers that may require them
  for (; idx < files.length; ++idx) {
    file = files[idx];
    path = _path.join('../functors', file);
    require(path);
  }
});
<commit_msg>initialize functors more appropriately<commit_after>
var _path       = require('path');

/** @class
  Functors are special handlers for data requests from the client.
  They are only used by the dataRoute xt route object and are loaded
  automatically at server start.
*/
XT.Functor = XT.Object.extend(
  /** @lends XT.Functor.prototype */ {

  /**
    When loaded by the data route handler it is auto-created
    and thus we want to auto-register to be selectable by
    the route.

    @private
  */
  init: function() {
    XT.Functors.push({ handles: this.get('handles'), target: this });
  },

  /**
    A functor must provide a handle method that takes
    a single parameter: the xt response obejct. From here
    it has access to the original response and request objects
    as well as the payload data. The session object will be
    attached to the xt response object by the time this
    method is executed when one can be present. If a functor
    requires a session but the sessionStore fails to retrieve
    the session this method will not be executed.

    @param {Object} xtr The xt response object.
  */
  handle: function(xtr) {},

  /**
    Each functor handles a specific request type from
    the client. This is a string representing the request
    type that it should be selected when this type is
    encountered by the server.

    @type {String}
    @property
  */
  handles: null,

  /**
    Almost all functors should require a session. If they do,
    they will automatically attempt to acquire the session before
    handling the request to ensure they can execute their
    functionality as the correct user. In the rare cases that
    a functor does not require an active session (such as a request
    for a new session) this boolean must be set to false but it
    defaults to true.

    @property
    @type Boolean
    @default true
  */
  needSession: true,

  /** @private */
  className: 'XT.Functor'

});

// make sure to grab and require all of the available functors
XT.run(function() {
  var files;
  var idx = 0;
  var file;
  var path;

  XT.log("Loading available functors from %@".f(
    XT.shorten(_path.join(__dirname, '../functors'), 5)));

  // make sure to create the static container for the functors
  XT.Functors = [];

  // change directories to path relatively
  process.chdir(__dirname);

  // collect any available javascript files in the directory
  files = XT.directoryFiles('../functors', 'js');

  // require each of them so they are available to any
  // routers that may require them
  for (; idx < files.length; ++idx) {
    file = files[idx];
    path = _path.join('../functors', file);
    require(path);
  }
});
<|endoftext|>


<commit_before>module.exports = {
    createDummyMessage: function(fileName) {
        var protobuf = require('protocol-buffers')

        // pass a proto file as a buffer/string or pass a parsed protobuf-schema object
        var proto = protobuf(fs.readFileSync('../Messages/message.proto'))
        var buf = proto.Message.encode({
            Email: "lukasz.pyrzyk@gmail.com"
            //Photo: fs.readFileSync('/home/lukasz/Dev/iphone')
        });

        return buf;
    }
}<commit_msg>Removed old file<commit_after><|endoftext|>


<commit_before>import babelJest from 'babel-jest';

module.exports = babelJest.createTransformer({
  presets: [
    'react',
    ['es2015', { modules: false }],
    'stage-0',
  ],
  plugins: [
    'transform-runtime',
    'transform-es2015-modules-commonjs',
  ],
  babelrc: false,
});
<commit_msg>add babel transform decorators plugin to jest config<commit_after>import babelJest from 'babel-jest';

module.exports = babelJest.createTransformer({
  presets: [
    'react',
    ['es2015', { modules: false }],
    'stage-0',
  ],
  plugins: [
    'transform-decorators-legacy',
    'transform-runtime',
    'transform-es2015-modules-commonjs',
  ],
  babelrc: false,
});
<|endoftext|>


<commit_before>global.Panes.Query = global.Pane.extend({
  renderTab: function(rows) {
    if (this.content) return;

    window.CodeMirror.commands.autocomplete = function(cm) {
      window.CodeMirror.showHint(cm, window.CodeMirror.hint.sql);
    };

    this.renderViewToPane('query', 'query_tab');

    this.button = this.content.find('button');

    this.mime = 'text/x-pgsql';
    this.textarea = this.content.find('textarea.editor');

    this.editor = window.CodeMirror.fromTextArea(this.textarea[0], {
      mode: this.mime,
      indentWithTabs: false,
      smartIndent: true,
      lineNumbers: true,
      matchBrackets : true,
      autofocus: true,
      styleActiveLine: true,
      tabSize: 2,
      theme: 'mac-classic',
      extraKeys: {"Esc": "autocomplete"}
    });

    if (Model.LastQuery.load()) {
      this.editor.setValue(Model.LastQuery.load());
    }

    this.editor.on("cursorActivity", this.toggleButtonText.bind(this));
    this.editor.on("change", this.saveLastQuery.bind(this));

    this.setUnchangable();
    this.statusLine = this.content.find('.result .status');
  },

  saveLastQuery: function () {
    var value = this.editor.getValue();
    if (this.saveTimeout) {
      clearTimeout(this.saveTimeout);
    }

    this.saveTimeout = setTimeout(function () {
      Model.LastQuery.save(value);
      delete this.saveTimeout;
    }.bind(this), 700);

  },

  toggleButtonText: function () {
    var runLabel = "Run query";
    var selectedLabel = "Run selection";

    var selectedText = this.editor.getSelection();
    if (selectedText && selectedText != "") {
      this.button.text(selectedLabel);
    } else {
      this.button.text(runLabel);
    }
  },

  runQuery: function () {
    this.editor.save();
    this.statusLine.text('');

    var selectedText = this.editor.getSelection();

    var sql = selectedText || this.textarea.val();
    var tableRegex = /(create|drop)\s+((GLOBAL|LOCAL|TEMPORARY|TEMP|UNLOGGED|FOREIGN)\s+)*\s*(table|schema|view)/im;
    var needReloadTables = !!sql.match(tableRegex);

    this.handler.connection.query(sql, function (data, error) {
      if (error) {
        this.content.find('.result table, .result .JCLRgrips').remove();
        var message = error.message;
        if (message == "invalid message format") message += ". It can be if too many records, try add 'limit'";
        this.statusLine.text(message);
      } else {
        var node = App.renderView('db_rows_table', {data: data})[0];
        this.content.find('.result .JCLRgrips').remove();
        this.content.find('.result table').replaceWith(node);
        this.statusLine.text("Found rows: " + data.rowCount + ' in ' + data.time + 'ms.');
        this.initTables();
      }
      if (needReloadTables) {
        this.reloadTables();
      }
    }.bind(this));
  },

  reloadTables: function () {
    this.handler.fetchTablesAndSchemas();
  }
});
<commit_msg>Fix query tab: table didn't appear after error<commit_after>global.Panes.Query = global.Pane.extend({
  renderTab: function(rows) {
    if (this.content) return;

    window.CodeMirror.commands.autocomplete = function(cm) {
      window.CodeMirror.showHint(cm, window.CodeMirror.hint.sql);
    };

    this.renderViewToPane('query', 'query_tab');

    this.button = this.content.find('button');

    this.mime = 'text/x-pgsql';
    this.textarea = this.content.find('textarea.editor');

    this.editor = window.CodeMirror.fromTextArea(this.textarea[0], {
      mode: this.mime,
      indentWithTabs: false,
      smartIndent: true,
      lineNumbers: true,
      matchBrackets : true,
      autofocus: true,
      styleActiveLine: true,
      tabSize: 2,
      theme: 'mac-classic',
      extraKeys: {"Esc": "autocomplete"}
    });

    if (Model.LastQuery.load()) {
      this.editor.setValue(Model.LastQuery.load());
    }

    this.editor.on("cursorActivity", this.toggleButtonText.bind(this));
    this.editor.on("change", this.saveLastQuery.bind(this));

    this.setUnchangable();
    this.statusLine = this.content.find('.result .status');
  },

  saveLastQuery: function () {
    var value = this.editor.getValue();
    if (this.saveTimeout) {
      clearTimeout(this.saveTimeout);
    }

    this.saveTimeout = setTimeout(function () {
      Model.LastQuery.save(value);
      delete this.saveTimeout;
    }.bind(this), 700);

  },

  toggleButtonText: function () {
    var runLabel = "Run query";
    var selectedLabel = "Run selection";

    var selectedText = this.editor.getSelection();
    if (selectedText && selectedText != "") {
      this.button.text(selectedLabel);
    } else {
      this.button.text(runLabel);
    }
  },

  runQuery: function () {
    this.editor.save();
    this.statusLine.text('');

    var selectedText = this.editor.getSelection();

    var sql = selectedText || this.textarea.val();
    var tableRegex = /(create|drop)\s+((GLOBAL|LOCAL|TEMPORARY|TEMP|UNLOGGED|FOREIGN)\s+)*\s*(table|schema|view)/im;
    var needReloadTables = !!sql.match(tableRegex);

    this.handler.connection.query(sql, function (data, error) {
      if (error) {
        this.content.find('.result .JCLRgrips').remove();
        this.content.find('.result table').html("").hide();
        var message = error.message;
        if (message == "invalid message format") message += ". It can be if too many records, try add 'limit'";
        this.statusLine.text(message);
      } else {
        var node = App.renderView('db_rows_table', {data: data})[0];
        this.content.find('.result .JCLRgrips').remove();
        this.content.find('.result table').replaceWith(node);
        this.statusLine.text("Found rows: " + data.rowCount + ' in ' + data.time + 'ms.');
        this.initTables();
      }
      if (needReloadTables) {
        this.reloadTables();
      }
    }.bind(this));
  },

  reloadTables: function () {
    this.handler.fetchTablesAndSchemas();
  }
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ReactDOM from 'react-dom';

import {
	ReactiveBase,
	NumberBox,
	ResultList,
} from '@appbaseio/reactivesearch';

import './index.css';

class Main extends Component {
	render() {
		return (
			<ReactiveBase
				app="good-books-ds"
				credentials="nY6NNTZZ6:27b76b9f-18ea-456c-bc5e-3a5263ebc63d"
			>

						<NumberBox
							componentId="BookSensor"
							dataField="average_rating_rounded"
						/>

						<ResultList
							componentId="SearchResult"
							dataField="original_title"
							from={0}
							size={3}
							onData={this.booksList}
							className="result-list-container"
							pagination
							react={{
								and: 'BookSensor',
							}}
						/>

			</ReactiveBase>
		);
	}

	booksList(data) {
		return {
			title:
,
			description: (

by {data.authors}

								{
									Array(data.average_rating_rounded).fill('x')
										.map((item, index) => ) // eslint-disable-line
								}

							({data.average_rating} avg)

					Pub {data.original_publication_year}

			),
			image: data.image,
		};
	}
}

ReactDOM.render(, document.getElementById('root'));
<commit_msg>web: NumberBox example app update props<commit_after>import React, { Component } from 'react';
import ReactDOM from 'react-dom';

import {
	ReactiveBase,
	NumberBox,
	ResultList,
} from '@appbaseio/reactivesearch';

import './index.css';

class Main extends Component {
	render() {
		return (
			<ReactiveBase
				app="good-books-ds"
				credentials="nY6NNTZZ6:27b76b9f-18ea-456c-bc5e-3a5263ebc63d"
			>

						<NumberBox
							componentId="BookSensor"
							dataField="average_rating_rounded"
							defaultSelected={2}
							data={{
								label: "Book Rating",
								start: 2,
								end: 5
							}}
							labelPosition="left"
						/>

						<ResultList
							componentId="SearchResult"
							dataField="original_title"
							from={0}
							size={3}
							onData={this.booksList}
							className="result-list-container"
							pagination
							react={{
								and: 'BookSensor',
							}}
						/>

			</ReactiveBase>
		);
	}

	booksList(data) {
		return {
			title:
,
			description: (

by {data.authors}

								{
									Array(data.average_rating_rounded).fill('x')
										.map((item, index) => ) // eslint-disable-line
								}

							({data.average_rating} avg)

					Pub {data.original_publication_year}

			),
			image: data.image,
		};
	}
}

ReactDOM.render(, document.getElementById('root'));
<|endoftext|>


<commit_before>'use strict';

angular.module('app.services', [])
  // Messages service will return a map of callbacks that handle websocket
  // messages sent from the flashlight process.
  .service('Messages', function($rootScope, modelSrvc) {

    var model = modelSrvc.model;
    model.instanceStats = {
      allBytes: {
        rate: 0,
      },
    };
    model.peers = [];
    var flashlightPeers = {};
    var queuedFlashlightPeers = {};

    var connectedExpiration = 15000;
    function setConnected(peer) {
      // Consider peer connected if it's been fewer than x seconds since
      // lastConnected
      var lastConnected = Date.parse(peer.lastConnected);
      var delta = new Date().getTime() - Date.parse(peer.lastConnected);
      peer.connected = delta < connectedExpiration;
    }

    // Update last connected for all peers every 10 seconds
    setInterval(function() {
      $rootScope.$apply(function() {
        _.forEach(model.peers, setConnected);
      });
    }, connectedExpiration);

    function applyPeer(peer) {
      // Always set mode to give
      peer.mode = 'give';

      setConnected(peer);

      // Update bpsUpDn
      var peerid = peer.peerid;
      var oldPeer = flashlightPeers[peerid];

      var bpsUpDnDelta = peer.bpsUpDn;
      if (oldPeer) {
        // Adjust bpsUpDnDelta by old value
        bpsUpDnDelta -= oldPeer.bpsUpDn;
        // Copy over old peer so that Angular can detect the change
        angular.copy(peer, oldPeer);
      } else {
        // Add peer to model
        flashlightPeers[peerid] = peer;
        model.peers.push(peer);
      }
      model.instanceStats.allBytes.rate += bpsUpDnDelta;
    }

    var fnList = {
      'GeoLookup': function(data) {
        console.log('Got GeoLookup information: ', data);
        if (data && data.Location) {
            model.location = {};
            model.location.lon = data.Location.Longitude;
            model.location.lat = data.Location.Latitude;
            model.location.resolved = true;
        }
      },
      'Settings': function(data) {
        console.log('Got Lantern default settings: ', data);
        if (data && data.Version) {
            // configure settings
            // set default client to get-mode
            model.settings = {};
            model.settings.mode = 'get';
            model.settings.version = data.Version + " (" + data.RevisionDate + ")";
        }

        if (data.AutoReport) {
            model.settings.autoReport = true;
                $rootScope.trackPageView();
        }

        if (data.AutoLaunch) {
            model.settings.autoLaunch = true;
        }

        if (data.ProxyAll) {
            model.settings.proxyAll = true;
        }
      },
      'LocalDiscovery': function(data) {
        model.localLanterns = data;
      },
      'ProxiedSites': function(data) {
        if (!$rootScope.entries) {
          console.log("Initializing proxied sites entries", data.Additions);
          $rootScope.entries = data.Additions;
          $rootScope.originalList = data.Additions;
        } else {
          var entries = $rootScope.entries.slice(0);
          if (data.Additions) {
            entries = _.union(entries, data.Additions);
          }
          if (data.Deletions) {
            entries = _.difference(entries, data.Deletions)
          }
          entries = _.compact(entries);
          entries.sort();

          console.log("About to set entries", entries);
          $rootScope.$apply(function() {
            console.log("Setting entries", entries);
            $rootScope.entries = entries;
            $rootScope.originalList = entries;
          })
        }
      },
      'Stats': function(data) {
        if (data.type != "peer") {
          return;
        }

        if (!model.location) {
          console.log("No location for self yet, queuing peer")
          queuedFlashlightPeers[data.data.peerid] = data.data;
          return;
        }

        $rootScope.$apply(function() {
          if (queuedFlashlightPeers) {
            console.log("Applying queued flashlight peers")
            _.forEach(queuedFlashlightPeers, applyPeer);
            queuedFlashlightPeers = null;
          }

          applyPeer(data.data);
        });
      },
    };

    return fnList;
  })
  .service('modelSrvc', function($rootScope, apiSrvc, $window, MODEL_SYNC_CHANNEL) {
      var model = {},
        syncSubscriptionKey;

    $rootScope.validatedModel = false;

    // XXX use modelValidatorSrvc to validate update before accepting
    function handleSync(msg) {
      var patch = msg.data;
      // backend can send updates before model has been populated
      // https://github.com/getlantern/lantern/issues/587
      if (patch[0].path !== '' && _.isEmpty(model)) {
        //log.debug('ignoring', msg, 'while model has not yet been populated');
        return;
      }

      function updateModel() {
        var shouldUpdateInstanceStats = false;
        if (patch[0].path === '') {
            // XXX jsonpatch can't mutate root object https://github.com/dharmafly/jsonpatch.js/issues/10
            angular.copy(patch[0].value, model);
          } else {
            try {
                applyPatch(model, patch);
                for (var i=0; i<patch.length; i++) {
                    if (patch[i].path == "/instanceStats") {
                        shouldUpdateInstanceStats = true;
                        break;
                      }
                  }
                } catch (e) {
                  if (!(e instanceof PatchApplyError || e instanceof InvalidPatch)) throw e;
                  //log.error('Error applying patch', patch);
                  apiSrvc.exception({exception: e, patch: patch});
                }
            }
        }

        if (!$rootScope.validatedModel) {
            $rootScope.$apply(updateModel());
            $rootScope.validatedModel = true
        } else {
            updateModel();
        }
      }

    syncSubscriptionKey = {chan: MODEL_SYNC_CHANNEL, cb: handleSync};

    return {
      model: model,
      sane: true
    };
  })
  .service('gaMgr', function ($window, DataStream, GOOGLE_ANALYTICS_DISABLE_KEY, GOOGLE_ANALYTICS_WEBPROP_ID) {
    window.gaDidInit = false;

    // See: Under certain circumstances this "window.ga" function was not
    // available when loading Safari. See
    // https://github.com/getlantern/lantern/issues/3560
    var ga = function() {
      var ga = $window.ga;
      if (ga) {
        if (!window.gaDidInit) {
          $window.gaDidInit = true;
          ga('create', GOOGLE_ANALYTICS_WEBPROP_ID, {cookieDomain: 'none'});
          ga('set', {
            anonymizeIp: true,
            forceSSL: true,
            location: 'http://lantern-ui/',
            hostname: 'lantern-ui',
            title: 'lantern-ui'
          });
        }
        return ga;
      }
      return function() {
        console.log("ga is not defined.");
      }
    }

    var trackPageView = function() {
      ga()('send', 'pageview');
    };

    var trackSendLinkToMobile = function() {
      ga()('send', 'send-link-to-mobile');
    };

    var trackCopyLink = function() {
      ga()('send', 'send-link-to-mobile');
    };

    return {
      trackSendLinkToMobile: trackSendLinkToMobile,
      trackCopyLink: trackCopyLink,
      trackPageView: trackPageView
    };
  })
  .service('apiSrvc', function($http, API_URL_PREFIX) {
    return {
      exception: function(data) {
        return $http.post(API_URL_PREFIX+'/exception', data);
      },
      interaction: function(interactionid, data) {
        var url = API_URL_PREFIX+'/interaction/'+interactionid;
        return $http.post(url, data);
      }
    };
  });
<commit_msg>Fixing comment.<commit_after>'use strict';

angular.module('app.services', [])
  // Messages service will return a map of callbacks that handle websocket
  // messages sent from the flashlight process.
  .service('Messages', function($rootScope, modelSrvc) {

    var model = modelSrvc.model;
    model.instanceStats = {
      allBytes: {
        rate: 0,
      },
    };
    model.peers = [];
    var flashlightPeers = {};
    var queuedFlashlightPeers = {};

    var connectedExpiration = 15000;
    function setConnected(peer) {
      // Consider peer connected if it's been fewer than x seconds since
      // lastConnected
      var lastConnected = Date.parse(peer.lastConnected);
      var delta = new Date().getTime() - Date.parse(peer.lastConnected);
      peer.connected = delta < connectedExpiration;
    }

    // Update last connected for all peers every 10 seconds
    setInterval(function() {
      $rootScope.$apply(function() {
        _.forEach(model.peers, setConnected);
      });
    }, connectedExpiration);

    function applyPeer(peer) {
      // Always set mode to give
      peer.mode = 'give';

      setConnected(peer);

      // Update bpsUpDn
      var peerid = peer.peerid;
      var oldPeer = flashlightPeers[peerid];

      var bpsUpDnDelta = peer.bpsUpDn;
      if (oldPeer) {
        // Adjust bpsUpDnDelta by old value
        bpsUpDnDelta -= oldPeer.bpsUpDn;
        // Copy over old peer so that Angular can detect the change
        angular.copy(peer, oldPeer);
      } else {
        // Add peer to model
        flashlightPeers[peerid] = peer;
        model.peers.push(peer);
      }
      model.instanceStats.allBytes.rate += bpsUpDnDelta;
    }

    var fnList = {
      'GeoLookup': function(data) {
        console.log('Got GeoLookup information: ', data);
        if (data && data.Location) {
            model.location = {};
            model.location.lon = data.Location.Longitude;
            model.location.lat = data.Location.Latitude;
            model.location.resolved = true;
        }
      },
      'Settings': function(data) {
        console.log('Got Lantern default settings: ', data);
        if (data && data.Version) {
            // configure settings
            // set default client to get-mode
            model.settings = {};
            model.settings.mode = 'get';
            model.settings.version = data.Version + " (" + data.RevisionDate + ")";
        }

        if (data.AutoReport) {
            model.settings.autoReport = true;
                $rootScope.trackPageView();
        }

        if (data.AutoLaunch) {
            model.settings.autoLaunch = true;
        }

        if (data.ProxyAll) {
            model.settings.proxyAll = true;
        }
      },
      'LocalDiscovery': function(data) {
        model.localLanterns = data;
      },
      'ProxiedSites': function(data) {
        if (!$rootScope.entries) {
          console.log("Initializing proxied sites entries", data.Additions);
          $rootScope.entries = data.Additions;
          $rootScope.originalList = data.Additions;
        } else {
          var entries = $rootScope.entries.slice(0);
          if (data.Additions) {
            entries = _.union(entries, data.Additions);
          }
          if (data.Deletions) {
            entries = _.difference(entries, data.Deletions)
          }
          entries = _.compact(entries);
          entries.sort();

          console.log("About to set entries", entries);
          $rootScope.$apply(function() {
            console.log("Setting entries", entries);
            $rootScope.entries = entries;
            $rootScope.originalList = entries;
          })
        }
      },
      'Stats': function(data) {
        if (data.type != "peer") {
          return;
        }

        if (!model.location) {
          console.log("No location for self yet, queuing peer")
          queuedFlashlightPeers[data.data.peerid] = data.data;
          return;
        }

        $rootScope.$apply(function() {
          if (queuedFlashlightPeers) {
            console.log("Applying queued flashlight peers")
            _.forEach(queuedFlashlightPeers, applyPeer);
            queuedFlashlightPeers = null;
          }

          applyPeer(data.data);
        });
      },
    };

    return fnList;
  })
  .service('modelSrvc', function($rootScope, apiSrvc, $window, MODEL_SYNC_CHANNEL) {
      var model = {},
        syncSubscriptionKey;

    $rootScope.validatedModel = false;

    // XXX use modelValidatorSrvc to validate update before accepting
    function handleSync(msg) {
      var patch = msg.data;
      // backend can send updates before model has been populated
      // https://github.com/getlantern/lantern/issues/587
      if (patch[0].path !== '' && _.isEmpty(model)) {
        //log.debug('ignoring', msg, 'while model has not yet been populated');
        return;
      }

      function updateModel() {
        var shouldUpdateInstanceStats = false;
        if (patch[0].path === '') {
            // XXX jsonpatch can't mutate root object https://github.com/dharmafly/jsonpatch.js/issues/10
            angular.copy(patch[0].value, model);
          } else {
            try {
                applyPatch(model, patch);
                for (var i=0; i<patch.length; i++) {
                    if (patch[i].path == "/instanceStats") {
                        shouldUpdateInstanceStats = true;
                        break;
                      }
                  }
                } catch (e) {
                  if (!(e instanceof PatchApplyError || e instanceof InvalidPatch)) throw e;
                  //log.error('Error applying patch', patch);
                  apiSrvc.exception({exception: e, patch: patch});
                }
            }
        }

        if (!$rootScope.validatedModel) {
            $rootScope.$apply(updateModel());
            $rootScope.validatedModel = true
        } else {
            updateModel();
        }
      }

    syncSubscriptionKey = {chan: MODEL_SYNC_CHANNEL, cb: handleSync};

    return {
      model: model,
      sane: true
    };
  })
  .service('gaMgr', function ($window, DataStream, GOOGLE_ANALYTICS_DISABLE_KEY, GOOGLE_ANALYTICS_WEBPROP_ID) {
    window.gaDidInit = false;

    // Under certain circumstances this "window.ga" function was not available
    // when loading Safari. See
    // https://github.com/getlantern/lantern/issues/3560
    var ga = function() {
      var ga = $window.ga;
      if (ga) {
        if (!window.gaDidInit) {
          $window.gaDidInit = true;
          ga('create', GOOGLE_ANALYTICS_WEBPROP_ID, {cookieDomain: 'none'});
          ga('set', {
            anonymizeIp: true,
            forceSSL: true,
            location: 'http://lantern-ui/',
            hostname: 'lantern-ui',
            title: 'lantern-ui'
          });
        }
        return ga;
      }
      return function() {
        console.log("ga is not defined.");
      }
    }

    var trackPageView = function() {
      ga()('send', 'pageview');
    };

    var trackSendLinkToMobile = function() {
      ga()('send', 'send-link-to-mobile');
    };

    var trackCopyLink = function() {
      ga()('send', 'send-link-to-mobile');
    };

    return {
      trackSendLinkToMobile: trackSendLinkToMobile,
      trackCopyLink: trackCopyLink,
      trackPageView: trackPageView
    };
  })
  .service('apiSrvc', function($http, API_URL_PREFIX) {
    return {
      exception: function(data) {
        return $http.post(API_URL_PREFIX+'/exception', data);
      },
      interaction: function(interactionid, data) {
        var url = API_URL_PREFIX+'/interaction/'+interactionid;
        return $http.post(url, data);
      }
    };
  });
<|endoftext|>