<commit_before>import update from 'immutability-helper'

const LaneHelper = {
  initialiseLanes: (state, {lanes}) => {
    const newLanes = lanes.map(lane => {
      lane.currentPage = 1
      lane.cards && lane.cards.forEach(c => (c.laneId = lane.id))
      return lane
    })
    return update(state, {lanes: {$set: newLanes}})
  },

  paginateLane: (state, {laneId, newCards, nextPage}) => {
    const updatedLanes = LaneHelper.appendCardsToLane(state, {laneId: laneId, newCards: newCards})
    updatedLanes.find(lane => lane.id === laneId).currentPage = nextPage
    return update(state, {lanes: {$set: updatedLanes}})
  },

  appendCardsToLane: (state, {laneId, newCards, index}) => {
    newCards = newCards.map(c => update(c, {laneId: {$set: laneId}}))
    return state.lanes.map(lane => {
      if (lane.id === laneId) {
        if (index !== undefined) {
          return update(lane, {cards: {$splice: [[index, 0, ...newCards]]}})
        } else {
					const cardsToUpdate = [...lane.cards, ...newCards]
					return update(lane, {cards: {$set: cardsToUpdate}})
        }
      } else {
        return lane
      }
    })
  },

  appendCardToLane: (state, {laneId, card, index}) => {
    const newLanes = LaneHelper.appendCardsToLane(state, {laneId: laneId, newCards: [card], index})
    return update(state, {lanes: {$set: newLanes}})
  },

  removeCardFromLane: (state, {laneId, cardId}) => {
    const lanes = state.lanes.map(lane => {
      if (lane.id === laneId) {
        let newCards = lane.cards.filter(card => card.id !== cardId)
        return update(lane, {cards: {$set: newCards}})
      } else {
        return lane
      }
    })
    return update(state, {lanes: {$set: lanes}})
  },

  moveCardAcrossLanes: (state, {fromLaneId, toLaneId, cardId, index}) => {
    let cardToMove = null
    const interimLanes = state.lanes.map(lane => {
      if (lane.id === fromLaneId) {
        cardToMove = lane.cards.find(card => card.id === cardId)
        const newCards = lane.cards.filter(card => card.id !== cardId)
        return update(lane, {cards: {$set: newCards}})
      } else {
        return lane
      }
    })
    const updatedState = update(state, {lanes: {$set: interimLanes}})
    return LaneHelper.appendCardToLane(updatedState, {laneId: toLaneId, card: cardToMove, index: index})
  },

  updateCardsForLane: (state, {laneId, cards}) => {
    const lanes = state.lanes.map(lane => {
      if (lane.id === laneId) {
        return update(lane, {cards: {$set: cards}})
      } else {
        return lane
      }
    })
    return update(state, {lanes: {$set: lanes}})
  },

  updateLanes: (state, lanes) => {
    return {...state, ...{lanes: lanes}}
  }
}

export default LaneHelper
<commit_msg>filtering cards that are already available when adding new cards as this will lead to a react error<commit_after>import update from 'immutability-helper'

const LaneHelper = {
  initialiseLanes: (state, {lanes}) => {
    const newLanes = lanes.map(lane => {
      lane.currentPage = 1
      lane.cards && lane.cards.forEach(c => (c.laneId = lane.id))
      return lane
    })
    return update(state, {lanes: {$set: newLanes}})
  },

  paginateLane: (state, {laneId, newCards, nextPage}) => {
    const updatedLanes = LaneHelper.appendCardsToLane(state, {laneId: laneId, newCards: newCards})
    updatedLanes.find(lane => lane.id === laneId).currentPage = nextPage
    return update(state, {lanes: {$set: updatedLanes}})
  },

  appendCardsToLane: (state, {laneId, newCards, index}) => {
    const lane = state.lanes.find(lane => lane.id === laneId)
    newCards = newCards
      .map(c => update(c, {laneId: {$set: laneId}}))
      .filter(c => lane.cards.find(card => card.id === c.id) == null)
    return state.lanes.map(lane => {
      if (lane.id === laneId) {
        if (index !== undefined) {
          return update(lane, {cards: {$splice: [[index, 0, ...newCards]]}})
        } else {
          const cardsToUpdate = [...lane.cards, ...newCards]
          return update(lane, {cards: {$set: cardsToUpdate}})
        }
      } else {
        return lane
      }
    })
  },

  appendCardToLane: (state, {laneId, card, index}) => {
    const newLanes = LaneHelper.appendCardsToLane(state, {laneId: laneId, newCards: [card], index})
    return update(state, {lanes: {$set: newLanes}})
  },

  removeCardFromLane: (state, {laneId, cardId}) => {
    const lanes = state.lanes.map(lane => {
      if (lane.id === laneId) {
        let newCards = lane.cards.filter(card => card.id !== cardId)
        return update(lane, {cards: {$set: newCards}})
      } else {
        return lane
      }
    })
    return update(state, {lanes: {$set: lanes}})
  },

  moveCardAcrossLanes: (state, {fromLaneId, toLaneId, cardId, index}) => {
    let cardToMove = null
    const interimLanes = state.lanes.map(lane => {
      if (lane.id === fromLaneId) {
        cardToMove = lane.cards.find(card => card.id === cardId)
        const newCards = lane.cards.filter(card => card.id !== cardId)
        return update(lane, {cards: {$set: newCards}})
      } else {
        return lane
      }
    })
    const updatedState = update(state, {lanes: {$set: interimLanes}})
    return LaneHelper.appendCardToLane(updatedState, {laneId: toLaneId, card: cardToMove, index: index})
  },

  updateCardsForLane: (state, {laneId, cards}) => {
    const lanes = state.lanes.map(lane => {
      if (lane.id === laneId) {
        return update(lane, {cards: {$set: cards}})
      } else {
        return lane
      }
    })
    return update(state, {lanes: {$set: lanes}})
  },

  updateLanes: (state, lanes) => {
    return {...state, ...{lanes: lanes}}
  }
}

export default LaneHelper
<|endoftext|>


<commit_before>var findSide = require('./find-side');

// determine the intersection point of a line segment with a line
// original: http://paulbourke.net/geometry/pointlineplane/pdb.c
var EPS = 0.000001;

function segline(x1, y1, x2, y2, x3, y3, x4, y4) {
  var denom  = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);

  // never return NaN
  if ((denom === 0) || isNaN(denom)) {
    return;
  }

  var numera = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3);
  var numerb = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3);

  // are the line coincident?
  if (Math.abs(numera) < EPS && Math.abs(numerb) < EPS && Math.abs(denom) < EPS) {
    return [
      (x1 + x2) / 2,
      (y1 + y2) / 2
    ];
  }

  // are the line parallel?
  if (Math.abs(denom) < EPS) {
    return; // no intersection
  }

  // is the intersection along the the segment?
  var mua = numera / denom;
  var mub = numerb / denom;

  if ((mua < 0) && (mua > 1) || (mub < 0) || (mub > 1)) {
    return;
  }

  return [
    x1 + (mua) * (x2 - x1),
    y1 + (mua) * (y2 - y1)
  ]
}

function nick (poly, nickingPlanes) {
  poly.splice(0, 0, poly[poly.length - 1]);

  var result = [];
  for (var x = 0; x < poly.length - 1; x++) {
    var lastX = poly[x][0];
    var lastY = poly[x][1];
    var currentX = poly[x + 1][0];
    var currentY = poly[x + 1][1];

    var intersection = segline(nickingPlanes[0], nickingPlanes[1], nickingPlanes[2], nickingPlanes[3], currentX, currentY, lastX, lastY);

    if (Array.isArray(intersection)) {
      result.push([intersection[0], intersection[1], 'nicked']);
    }
    result.push([currentX, currentY]);
  }

  return result;
}

function clip (poly, cuttingPlane) {
  var left = [];
  var right = [];

  var lastPointSide;
  if (!poly || !poly[0]) return {left: undefined, right: undefined};

  // instead of trying to do circular access over the underlying array, just fake it
  // this might not be a great idea later on, if arbitrary precision arithmetic/computer algebra or DAG is used
  //
  //    [1, 2, 3, 4]
  //
  // [4, 1, 2, 3, 4]
  //
  // [4, 1]
  //    [1, 2]
  //       [2, 3]
  //          [3, 4]

  poly.splice(0, 0, poly[poly.length - 1]);

  for (var i = 0; i < poly.length - 1; i++) {
    var lastX = poly[i][0];
    var lastY = poly[i][1];
    var currentX = poly[i + 1][0];
    var currentY = poly[i + 1][1];

    var side = findSide(cuttingPlane[0], cuttingPlane[1], cuttingPlane[2], cuttingPlane[3], currentX, currentY);

    // does the current line segment intersect the cuttingPlane?
    if ((lastPointSide !== 0) && (side !== 0)) {
      var intersection = segline(cuttingPlane[0], cuttingPlane[1], cuttingPlane[2], cuttingPlane[3], currentX, currentY, lastX, lastY);

      if (Array.isArray(intersection)) {
        left.push([intersection[0], intersection[1]]);
        right.push([intersection[0], intersection[1]]);
      }
    }

    if (side < 0) {
      left.push([currentX, currentY]);
    }
    else if (side === 0) {
      left.push([currentX, currentY]);
      right.push([currentX, currentY]);
    }
    else {
      right.push([currentX, currentY]);
    }

    // set lastPointSide for next iteration
    lastPointSide = side;
  }

  return {
    left: left,
    right: right
  }
}

exports.nick = nick;
exports.clip = clip;
<commit_msg>replace splice with mod<commit_after>var findSide = require('./find-side');

// determine the intersection point of a line segment with a line
// original: http://paulbourke.net/geometry/pointlineplane/pdb.c
var EPS = 0.000001;

function segline(x1, y1, x2, y2, x3, y3, x4, y4) {
  var denom  = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);

  // never return NaN
  if ((denom === 0) || isNaN(denom)) {
    return;
  }

  var numera = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3);
  var numerb = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3);

  // are the line coincident?
  if (Math.abs(numera) < EPS && Math.abs(numerb) < EPS && Math.abs(denom) < EPS) {
    return [
      (x1 + x2) / 2,
      (y1 + y2) / 2
    ];
  }

  // are the line parallel?
  if (Math.abs(denom) < EPS) {
    return; // no intersection
  }

  // is the intersection along the the segment?
  var mua = numera / denom;
  var mub = numerb / denom;

  if ((mua < 0) && (mua > 1) || (mub < 0) || (mub > 1)) {
    return;
  }

  return [
    x1 + (mua) * (x2 - x1),
    y1 + (mua) * (y2 - y1)
  ]
}

function nick (poly, nickingPlanes) {
  poly.splice(0, 0, poly[poly.length - 1]);

  var result = [];
  for (var x = 0; x < poly.length - 1; x++) {
    var lastX = poly[x][0];
    var lastY = poly[x][1];
    var currentX = poly[x + 1][0];
    var currentY = poly[x + 1][1];

    var intersection = segline(nickingPlanes[0], nickingPlanes[1], nickingPlanes[2], nickingPlanes[3], currentX, currentY, lastX, lastY);

    if (Array.isArray(intersection)) {
      result.push([intersection[0], intersection[1], 'nicked']);
    }
    result.push([currentX, currentY]);
  }

  return result;
}

function clip (poly, cuttingPlane) {
  var left = [];
  var right = [];

  var lastPointSide;
  if (!poly || !poly[0]) return {left: undefined, right: undefined};

  for (var i = 0; i < poly.length; i++) {
    var lastX = poly[i][0];
    var lastY = poly[i][1];
    var n = (i + 1) % poly.length;
    var currentX = poly[n][0];
    var currentY = poly[n][1];

    var side = findSide(cuttingPlane[0], cuttingPlane[1], cuttingPlane[2], cuttingPlane[3], currentX, currentY);

    // does the current line segment intersect the cuttingPlane?
    if ((lastPointSide !== 0) && (side !== 0)) {
      var intersection = segline(cuttingPlane[0], cuttingPlane[1], cuttingPlane[2], cuttingPlane[3], currentX, currentY, lastX, lastY);

      if (Array.isArray(intersection)) {
        left.push([intersection[0], intersection[1]]);
        right.push([intersection[0], intersection[1]]);
      }
    }

    if (side < 0) {
      left.push([currentX, currentY]);
    }
    else if (side === 0) {
      left.push([currentX, currentY]);
      right.push([currentX, currentY]);
    }
    else {
      right.push([currentX, currentY]);
    }

    // set lastPointSide for next iteration
    lastPointSide = side;
  }

  return {
    left: left,
    right: right
  }
}

exports.nick = nick;
exports.clip = clip;
<|endoftext|>


<commit_before>// Porting tests from Apache CouchDB bulk docs tests
// https://github.com/apache/couchdb/blob/master/share/www/script/test/bulk_docs.js

// Note: writing sync tests over an async api sucks, havent found a decent
// dataflow type library I like yet

// all_or_nothing is not implemented

module('all_docs', {
  setup : function () {
    this.name = 'test_suite_db';
  }
});

asyncTest('Testing all docs', function() {

  var db;
  var docs = [
    {_id:"0",a:1,b:1},
    {_id:"3",a:4,b:16},
    {_id:"1",a:2,b:4},
    {_id:"2",a:3,b:9}
  ];

  function writeDocs(callback) {
    if (!docs.length) {
      return callback();
    }
    var doc = docs.shift();
    db.put(doc, function(err, doc) {
      ok(doc.ok, 'docwrite returned ok');
      writeDocs(callback);
    });
  };

  initTestDB(this.name, function(err, _db) {
    db = _db;
    writeDocs(function() {
      db.allDocs(function(err, result) {
        var rows = result.rows;
        ok(result.total_rows === 4, 'correct number of results');
        for(var i=0; i < rows.length; i++) {
          ok(rows[i].id >= "0" && rows[i].id <= "4", 'correct ids');
        }
        db.allDocs({startkey:"2"}, function(err, all) {
          // TODO: implement offset
          //ok(all.offset == 2, 'offset correctly set');
          var opts = {startkey: "org.couchdb.user:", endkey: "org.couchdb.user;"};
          db.allDocs(opts, function(err, raw) {
            ok(raw.rows.length === 0, 'raw collation');
            var ids = ["0","3","1","2"];
            db.changes(function(err, changes) {
              changes.results.forEach(function(row, i) {
                ok(row.id === ids[i], 'seq order');
              });
              db.changes({
                descending: true,
                complete: function(err, changes) {
                  ids = ["2","1","3","0"];
                  changes.results.forEach(function(row, i) {
                    ok(row.id === ids[i], 'descending=true');
                  });
                  start();
                }
              });
            });
          });
        });
      });
    });
  });
});

asyncTest('Testing deleting in changes', function() {
  pouch.open(this.name, function(err, db) {
    db.get('1', function(err, doc) {
      db.remove(doc, function(err, deleted) {
        ok(deleted.ok, 'deleted');
        db.changes(function(err, changes) {
          ok(changes.results.length == 4);
          ok(changes.results[3].id == "1");
          ok(changes.results[3].deleted);
          start();
        });
      });
    });
  });
});

asyncTest('Testing updating in changes', function() {
  pouch.open(this.name, function(err, db) {
    db.get('3', function(err, doc) {
      doc.updated = 'totally';
      db.put(doc, function(err, doc) {
        db.changes(function(err, changes) {
          ok(changes.results.length === 4);
          ok(changes.results[3].id === "3");
          start();
        });
      });
    });
  });
});

asyncTest('Testing include docs', function() {
  pouch.open(this.name, function(err, db) {
    db.changes({include_docs: true}, function(err, changes) {
      ok(changes.results.length == 4);
      ok(changes.results[3].id == "3");
      ok(changes.results[3].doc.updated == "totally");
      ok(changes.results[2].doc);
      ok(changes.results[2].doc._deleted);
      start();
    });
  });
});
<commit_msg>finish implementing all docs tests<commit_after>// Porting tests from Apache CouchDB bulk docs tests
// https://github.com/apache/couchdb/blob/master/share/www/script/test/bulk_docs.js

// Note: writing sync tests over an async api sucks, havent found a decent
// dataflow type library I like yet

// all_or_nothing is not implemented

module('all_docs', {
  setup : function () {
    this.name = 'test_suite_db';
  }
});

asyncTest('Testing all docs', function() {

  var db;
  var docs = [
    {_id:"0",a:1,b:1},
    {_id:"3",a:4,b:16},
    {_id:"1",a:2,b:4},
    {_id:"2",a:3,b:9}
  ];

  function writeDocs(callback) {
    if (!docs.length) {
      return callback();
    }
    var doc = docs.shift();
    db.put(doc, function(err, doc) {
      ok(doc.ok, 'docwrite returned ok');
      writeDocs(callback);
    });
  };

  initTestDB(this.name, function(err, _db) {
    db = _db;
    writeDocs(function() {
      db.allDocs(function(err, result) {
        var rows = result.rows;
        ok(result.total_rows === 4, 'correct number of results');
        for(var i=0; i < rows.length; i++) {
          ok(rows[i].id >= "0" && rows[i].id <= "4", 'correct ids');
        }
        db.allDocs({startkey:"2"}, function(err, all) {
          // TODO: implement offset
          //ok(all.offset == 2, 'offset correctly set');
          var opts = {startkey: "org.couchdb.user:", endkey: "org.couchdb.user;"};
          db.allDocs(opts, function(err, raw) {
            ok(raw.rows.length === 0, 'raw collation');
            var ids = ["0","3","1","2"];
            db.changes(function(err, changes) {
              changes.results.forEach(function(row, i) {
                ok(row.id === ids[i], 'seq order');
              });
              db.changes({
                descending: true,
                complete: function(err, changes) {
                  ids = ["2","1","3","0"];
                  changes.results.forEach(function(row, i) {
                    ok(row.id === ids[i], 'descending=true');
                  });
                  start();
                }
              });
            });
          });
        });
      });
    });
  });
});

asyncTest('Testing deleting in changes', function() {
  pouch.open(this.name, function(err, db) {
    db.get('1', function(err, doc) {
      db.remove(doc, function(err, deleted) {
        ok(deleted.ok, 'deleted');
        db.changes(function(err, changes) {
          ok(changes.results.length == 4);
          ok(changes.results[3].id == "1");
          ok(changes.results[3].deleted);
          start();
        });
      });
    });
  });
});

asyncTest('Testing updating in changes', function() {
  pouch.open(this.name, function(err, db) {
    db.get('3', function(err, doc) {
      doc.updated = 'totally';
      db.put(doc, function(err, doc) {
        db.changes(function(err, changes) {
          ok(changes.results.length === 4);
          ok(changes.results[3].id === "3");
          start();
        });
      });
    });
  });
});

asyncTest('Testing include docs', function() {
  pouch.open(this.name, function(err, db) {
    db.changes({include_docs: true}, function(err, changes) {
      ok(changes.results.length == 4);
      ok(changes.results[3].id == "3");
      ok(changes.results[3].doc.updated == "totally");
      ok(changes.results[2].doc);
      ok(changes.results[2].doc._deleted);
      start();
    });
  });
});

asyncTest('Testing conflicts', function() {
  pouch.open(this.name, function(err, db) {
    // add conflicts
    var conflictDoc1 = {
      _id: "3", _rev: "2-aa01552213fafa022e6167113ed01087", value: "X"
    };
    var conflictDoc2 = {
      _id: "3", _rev: "2-ff01552213fafa022e6167113ed01087", value: "Z"
    };
    db.put(conflictDoc1, {new_edits: false}, function(err, doc) {
      db.put(conflictDoc2, {new_edits: false}, function(err, doc) {
        db.get('3', function(err, winRev) {
          var opts = {include_docs: true, conflicts: true, style: 'all_docs'};
          db.changes(opts, function(err, changes) {
            ok("3" === changes.results[3].id);
            ok(3 === changes.results[3].changes.length);
            ok(winRev._rev === changes.results[3].changes[0].rev);
            ok("3" === changes.results[3].doc._id);
            ok(winRev._rev === changes.results[3].doc._rev);
            ok(true === changes.results[3].doc._conflicts instanceof Array);
            ok(changes.results[3].doc._conflicts &&
               2 === changes.results[3].doc._conflicts.length);

            db.allDocs({include_docs: true, conflicts: true}, function(err, res) {
              ok(3 === res.rows.length);
              ok("3" === res.rows[2].key);
              ok("3" === res.rows[2].id);
              ok(winRev._rev === res.rows[2].value.rev);
              ok(winRev._rev === res.rows[2].doc._rev);
              ok("3" === res.rows[2].doc._id);
              ok(true === res.rows[2].doc._conflicts instanceof Array);
              ok(res.rows[2].doc._conflicts && 2 === res.rows[2].doc._conflicts.length);
              start();
            });
          });
        });
      });
    });
  });
});

asyncTest('Test basic collation', function() {
  pouch.open(this.name, function(err, db) {
    var docs = {docs: [{_id: "Z", foo: "Z"}, {_id: "a", foo: "a"}]};
    db.bulkDocs(docs, function(err, res) {
      db.allDocs({startkey: 'Z', endkey: 'Z'}, function(err, result) {
        ok(result.rows.length === 1);
        start();
      });
    });
  });
});<|endoftext|>


<commit_before>/*jslint node: true */
"use strict";

function mergeExports(anotherModule){
    for (var key in anotherModule)
        exports[key] = anotherModule[key];
}

// port we are listening on.  Set to null to disable accepting connections
exports.port = 6611;

// how peers connect to me
//exports.myUrl = 'wss://example.org/bb';

// if we are serving as hub.  Default is false
//exports.bServeAsHub = true;

// if we are a light client.  Default is full client
//exports.bLight = true;

// where to send bug reports to.  Usually, it is wallet vendor's server.
// By default, it is hub url
//exports.bug_sink_url = "wss://example.org/bb";

// this is used by wallet vendor only, to redirect bug reports to developers' email
//exports.bug_sink_email = 'admin@example.org';
//exports.bugs_from_email = 'bugs@example.org';

// WebSocket protocol prefixed to all hosts.  Must be wss:// on livenet, ws:// is allowed on testnet
exports.WS_PROTOCOL = "ws://";

// storage engine: mysql or sqlite
exports.storage = 'sqlite';
if (process.browser){
    exports.storage = 'sqlite';
    exports.bLight = true;
}
exports.database = {};

/*
merge confs from other modules that include us as lib.  The other module must place its custom_conf.js into its node_modules
Example paths:
byteball-hub
byteball-hub/*.js
byteball-hub/node_modules
byteball-hub/node_modules/byteballcore
byteball-hub/node_modules/byteballcore/conf.js  - it's me
byteball-hub/node_modules/custom_conf.js        - the custom conf
*/
/*
try{
    mergeExports(require('custom_conf.js'));
    console.log('merged custom conf');
}
catch(e){
}*/

/*
There are 3 ways to customize conf in modules that use byteballcore lib:
1. drop a custom conf.js into the project root.  The code below will find it and merge.  Will not work under browserify.
2. drop a custom conf.json into the app's data dir inside the user's home dir.  The code below will find it and merge.  Will not work under browserify.
3. require() this conf and modify it:
var conf = require('byteballcore/conf.js');
conf.custom_property = 'custom value';
You should do it as early as possible during your app's startup.
The later require()s of this conf will see the modified version.
This way is not recommended as the code becomes loading order dependent.
*/

if (typeof window === 'undefined' || !window.cordova){ // desktop
    var desktopApp = require('./desktop_app.js'+'');

    // merge conf from other modules that include us as lib.  The other module must place its custom conf.js into its root directory
    var appRootDir = desktopApp.getAppRootDir();
    if (appRootDir !== __dirname){
        try{
            mergeExports(require(appRootDir + '/conf.js'));
            console.log('merged app root conf from ' + appRootDir + '/conf.js');
        }
        catch(e){
            console.log("not using app root conf: "+e);
        }
    }
    else
        console.log("I'm already at the root");

    // merge conf from user home directory, if any.
    // Note that it is json rather than js to avoid code injection
    var appDataDir = desktopApp.getAppDataDir();
    try{
        mergeExports(require(appDataDir + '/conf.json'));
        console.log('merged user conf from ' + appDataDir + '/conf.json');
    }
    catch(e){
        console.log('not using user conf: '+e);
    }
}

// after merging the custom confs, set defaults if they are still not set
if (exports.storage === 'mysql'){
    exports.database.max_connections = exports.database.max_connections || 30;
    exports.database.host = exports.database.host || 'localhost';
    exports.database.name = exports.database.name || 'byteball';
    exports.database.user = exports.database.user || 'byteball';
}
else if (exports.storage === 'sqlite'){
    exports.database.max_connections = exports.database.max_connections || 1;
    exports.database.filename = exports.database.filename || (exports.bLight ? 'byteball-light.sqlite' : 'byteball.sqlite');
}

<commit_msg>wss://<commit_after>/*jslint node: true */
"use strict";

function mergeExports(anotherModule){
    for (var key in anotherModule)
        exports[key] = anotherModule[key];
}

// port we are listening on.  Set to null to disable accepting connections
exports.port = 6611;

// how peers connect to me
//exports.myUrl = 'wss://example.org/bb';

// if we are serving as hub.  Default is false
//exports.bServeAsHub = true;

// if we are a light client.  Default is full client
//exports.bLight = true;

// where to send bug reports to.  Usually, it is wallet vendor's server.
// By default, it is hub url
//exports.bug_sink_url = "wss://example.org/bb";

// this is used by wallet vendor only, to redirect bug reports to developers' email
//exports.bug_sink_email = 'admin@example.org';
//exports.bugs_from_email = 'bugs@example.org';

// WebSocket protocol prefixed to all hosts.  Must be wss:// on livenet, ws:// is allowed on testnet
exports.WS_PROTOCOL = "wss://";

// storage engine: mysql or sqlite
exports.storage = 'sqlite';
if (process.browser){
    exports.storage = 'sqlite';
    exports.bLight = true;
}
exports.database = {};

/*
merge confs from other modules that include us as lib.  The other module must place its custom_conf.js into its node_modules
Example paths:
byteball-hub
byteball-hub/*.js
byteball-hub/node_modules
byteball-hub/node_modules/byteballcore
byteball-hub/node_modules/byteballcore/conf.js  - it's me
byteball-hub/node_modules/custom_conf.js        - the custom conf
*/
/*
try{
    mergeExports(require('custom_conf.js'));
    console.log('merged custom conf');
}
catch(e){
}*/

/*
There are 3 ways to customize conf in modules that use byteballcore lib:
1. drop a custom conf.js into the project root.  The code below will find it and merge.  Will not work under browserify.
2. drop a custom conf.json into the app's data dir inside the user's home dir.  The code below will find it and merge.  Will not work under browserify.
3. require() this conf and modify it:
var conf = require('byteballcore/conf.js');
conf.custom_property = 'custom value';
You should do it as early as possible during your app's startup.
The later require()s of this conf will see the modified version.
This way is not recommended as the code becomes loading order dependent.
*/

if (typeof window === 'undefined' || !window.cordova){ // desktop
    var desktopApp = require('./desktop_app.js'+'');

    // merge conf from other modules that include us as lib.  The other module must place its custom conf.js into its root directory
    var appRootDir = desktopApp.getAppRootDir();
    if (appRootDir !== __dirname){
        try{
            mergeExports(require(appRootDir + '/conf.js'));
            console.log('merged app root conf from ' + appRootDir + '/conf.js');
        }
        catch(e){
            console.log("not using app root conf: "+e);
        }
    }
    else
        console.log("I'm already at the root");

    // merge conf from user home directory, if any.
    // Note that it is json rather than js to avoid code injection
    var appDataDir = desktopApp.getAppDataDir();
    try{
        mergeExports(require(appDataDir + '/conf.json'));
        console.log('merged user conf from ' + appDataDir + '/conf.json');
    }
    catch(e){
        console.log('not using user conf: '+e);
    }
}

// after merging the custom confs, set defaults if they are still not set
if (exports.storage === 'mysql'){
    exports.database.max_connections = exports.database.max_connections || 30;
    exports.database.host = exports.database.host || 'localhost';
    exports.database.name = exports.database.name || 'byteball';
    exports.database.user = exports.database.user || 'byteball';
}
else if (exports.storage === 'sqlite'){
    exports.database.max_connections = exports.database.max_connections || 1;
    exports.database.filename = exports.database.filename || (exports.bLight ? 'byteball-light.sqlite' : 'byteball.sqlite');
}

<|endoftext|>


<commit_before>!function(n){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=n();else if("function"==typeof define&&define.amd)define([],n);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.basicModal=n()}}(function(){return function n(t,e,o){function l(c,s){if(!e[c]){if(!t[c]){var i="function"==typeof require&&require;if(!s&&i)return i(c,!0);if(a)return a(c,!0);var r=new Error("Cannot find module '"+c+"'");throw r.code="MODULE_NOT_FOUND",r}var u=e[c]={exports:{}};t[c][0].call(u.exports,function(n){var e=t[c][1][n];return l(e?e:n)},u,u.exports,n,t,e,o)}return e[c].exports}for(var a="function"==typeof require&&require,c=0;c<o.length;c++)l(o[c]);return l}({1:[function(n,t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=null,l=(e.THEME={small:"basicModal__small",xclose:"basicModal__xclose"},function(){var n=arguments.length<=0||void 0===arguments[0]?"":arguments[0],t=arguments.length<=1||void 0===arguments[1]?!1:arguments[1];return t===!0?document.querySelectorAll(".basicModal "+n):document.querySelector(".basicModal "+n)}),a=function(n,t){return null==n?!1:n.constructor===Object?Array.prototype.forEach.call(Object.keys(n),function(e){return t(n[e],e,n)}):Array.prototype.forEach.call(n,function(e,o){return t(e,o,n)})},c=function(n){return null==n||0===Object.keys(n).length?(console.error("Missing or empty modal configuration object"),!1):(null==n.body&&(n.body=""),null==n["class"]&&(n["class"]=""),n.closable!==!1&&(n.closable=!0),null==n.buttons?(console.error("basicModal requires at least one button"),!1):null!=n.buttons.action&&(null==n.buttons.action["class"]&&(n.buttons.action["class"]=""),null==n.buttons.action.title&&(n.buttons.action.title="OK"),null==n.buttons.action.fn)?(console.error("Missing fn for action-button"),!1):null!=n.buttons.cancel&&(null==n.buttons.cancel["class"]&&(n.buttons.cancel["class"]=""),null==n.buttons.cancel.title&&(n.buttons.cancel.title="Cancel"),null==n.buttons.cancel.fn)?(console.error("Missing fn for cancel-button"),!1):!0)},s=function(n){var t='<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><path d="M405 136.798l-29.798-29.798-119.202 119.202-119.202-119.202-29.798 29.798 119.202 119.202-119.202 119.202 29.798 29.798 119.202-119.202 119.202 119.202 29.798-29.798-119.202-119.202z"/></svg>',e="";return e+="\n
\n
\n
\n	                    "+n.body+"\n
\n
\n	        ",null!=n.buttons.cancel&&(e+=-1===n.buttons.cancel["class"].indexOf("basicModal__xclose")?""+n.buttons.cancel.title+"":"
"+t+"
"),null!=n.buttons.action&&(e+=""+n.buttons.action.title+""),e+="\n
\n
\n
\n	        "},i=e.getValues=function(){var n={},t=l("input[name]",!0),e=l("select[name]",!0);return a(t,function(t){var e=t.getAttribute("name"),o=t.value;n[e]=o}),a(e,function(t){var e=t.getAttribute("name"),o=t.options[t.selectedIndex].value;n[e]=o}),0===Object.keys(n).length?null:n},r=function(n){return null!=n.buttons.cancel&&(l("#basicModal__cancel").onclick=function(){return this.classList.contains("basicModal__button--active")===!0?!1:(this.classList.add("basicModal__button--active"),void n.buttons.cancel.fn())}),null!=n.buttons.action&&(l("#basicModal__action").onclick=function(){return this.classList.contains("basicModal__button--active")===!0?!1:(this.classList.add("basicModal__button--active"),void n.buttons.action.fn(i()))}),a(l("input",!0),function(n){n.oninput=n.onblur=function(){this.classList.remove("error")}}),a(l("select",!0),function(n){n.onchange=n.onblur=function(){this.classList.remove("error")}}),!0},u=(e.show=function f(n){if(c(n)===!1)return!1;if(null!=l())return b(!0),setTimeout(function(){return f(n)},301),!1;o=document.activeElement;var t=s(n);document.body.insertAdjacentHTML("beforeend",t),r(n);var e=l("input");null!=e&&e.select();var a=l("select");return null==e&&null!=a&&a.focus(),null!=n.callback&&n.callback(n),!0},e.error=function(n){d();var t=l("input[name='"+n+"']")||l("select[name='"+n+"']");return null==t?!1:(t.classList.add("error"),"function"==typeof t.select?t.select():t.focus(),l().classList.remove("basicModal--fadeIn","basicModal--shake"),void setTimeout(function(){return l().classList.add("basicModal--shake")},1))},e.visible=function(){return null!=l()}),d=(e.action=function(){var n=l("#basicModal__action");return null!=n?(n.click(),!0):!1},e.cancel=function(){var n=l("#basicModal__cancel");return null!=n?(n.click(),!0):!1},e.reset=function(){var n=l(".basicModal__button",!0);a(n,function(n){return n.classList.remove("basicModal__button--active")});var t=l("input",!0);a(t,function(n){return n.classList.remove("error")});var e=l("select",!0);return a(e,function(n){return n.classList.remove("error")}),!0}),b=e.close=function(){var n=arguments.length<=0||void 0===arguments[0]?!1:arguments[0];if(u()===!1)return!1;var t=l().parentElement;return"false"===t.getAttribute("data-closable")&&n===!1?!1:(t.classList.remove("basicModalContainer--fadeIn"),t.classList.add("basicModalContainer--fadeOut"),setTimeout(function(){return null==t?!1:null==t.parentElement?!1:void t.parentElement.removeChild(t)},300),null!=o&&(o.focus(),o=null),!0)}},{}]},{},[1])(1)});<commit_msg>Rebuild<commit_after>!function(n){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=n();else if("function"==typeof define&&define.amd)define([],n);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.basicModal=n()}}(function(){return function n(t,e,o){function l(c,s){if(!e[c]){if(!t[c]){var i="function"==typeof require&&require;if(!s&&i)return i(c,!0);if(a)return a(c,!0);var r=new Error("Cannot find module '"+c+"'");throw r.code="MODULE_NOT_FOUND",r}var u=e[c]={exports:{}};t[c][0].call(u.exports,function(n){var e=t[c][1][n];return l(e?e:n)},u,u.exports,n,t,e,o)}return e[c].exports}for(var a="function"==typeof require&&require,c=0;c<o.length;c++)l(o[c]);return l}({1:[function(n,t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=null,l=(e.THEME={small:"basicModal__small",xclose:"basicModal__xclose"},function(){var n=arguments.length<=0||void 0===arguments[0]?"":arguments[0],t=!(arguments.length<=1||void 0===arguments[1])&&arguments[1];return t===!0?document.querySelectorAll(".basicModal "+n):document.querySelector(".basicModal "+n)}),a=function(n,t){return null!=n&&(n.constructor===Object?Array.prototype.forEach.call(Object.keys(n),function(e){return t(n[e],e,n)}):Array.prototype.forEach.call(n,function(e,o){return t(e,o,n)}))},c=function(n){return null==n||0===Object.keys(n).length?(console.error("Missing or empty modal configuration object"),!1):(null==n.body&&(n.body=""),null==n["class"]&&(n["class"]=""),n.closable!==!1&&(n.closable=!0),null==n.buttons?(console.error("basicModal requires at least one button"),!1):null!=n.buttons.action&&(null==n.buttons.action["class"]&&(n.buttons.action["class"]=""),null==n.buttons.action.title&&(n.buttons.action.title="OK"),null==n.buttons.action.fn)?(console.error("Missing fn for action-button"),!1):null==n.buttons.cancel||(null==n.buttons.cancel["class"]&&(n.buttons.cancel["class"]=""),null==n.buttons.cancel.title&&(n.buttons.cancel.title="Cancel"),null!=n.buttons.cancel.fn)||(console.error("Missing fn for cancel-button"),!1))},s=function(n){var t='<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><path d="M405 136.798l-29.798-29.798-119.202 119.202-119.202-119.202-29.798 29.798 119.202 119.202-119.202 119.202 29.798 29.798 119.202-119.202 119.202 119.202 29.798-29.798-119.202-119.202z"/></svg>',e="";return e+="\n\t
\n\t
\n\t
\n\t                    "+n.body+"\n\t
\n\t
\n\t        ",null!=n.buttons.cancel&&(e+=n.buttons.cancel["class"].indexOf("basicModal__xclose")===-1?""+n.buttons.cancel.title+"":"
"+t+"
"),null!=n.buttons.action&&(e+=""+n.buttons.action.title+""),e+="\n\t
\n\t
\n\t
\n\t        "},i=e.getValues=function(){var n={},t=l("input[name]",!0),e=l("select[name]",!0);return a(t,function(t){var e=t.getAttribute("name"),o=t.value;n[e]=o}),a(e,function(t){var e=t.getAttribute("name"),o=t.options[t.selectedIndex].value;n[e]=o}),0===Object.keys(n).length?null:n},r=function(n){return null!=n.buttons.cancel&&(l("#basicModal__cancel").onclick=function(){return this.classList.contains("basicModal__button--active")!==!0&&(this.classList.add("basicModal__button--active"),void n.buttons.cancel.fn())}),null!=n.buttons.action&&(l("#basicModal__action").onclick=function(){return this.classList.contains("basicModal__button--active")!==!0&&(this.classList.add("basicModal__button--active"),void n.buttons.action.fn(i()))}),a(l("input",!0),function(n){n.oninput=n.onblur=function(){this.classList.remove("error")}}),a(l("select",!0),function(n){n.onchange=n.onblur=function(){this.classList.remove("error")}}),!0},u=(e.show=function f(n){if(c(n)===!1)return!1;if(null!=l())return b(!0),setTimeout(function(){return f(n)},301),!1;o=document.activeElement;var t=s(n);document.body.insertAdjacentHTML("beforeend",t),r(n);var e=l("input");null!=e&&e.select();var a=l("select");return null==e&&null!=a&&a.focus(),null!=n.callback&&n.callback(n),!0},e.error=function(n){d();var t=l("input[name='"+n+"']")||l("select[name='"+n+"']");return null!=t&&(t.classList.add("error"),"function"==typeof t.select?t.select():t.focus(),l().classList.remove("basicModal--fadeIn","basicModal--shake"),void setTimeout(function(){return l().classList.add("basicModal--shake")},1))},e.visible=function(){return null!=l()}),d=(e.action=function(){var n=l("#basicModal__action");return null!=n&&(n.click(),!0)},e.cancel=function(){var n=l("#basicModal__cancel");return null!=n&&(n.click(),!0)},e.reset=function(){var n=l(".basicModal__button",!0);a(n,function(n){return n.classList.remove("basicModal__button--active")});var t=l("input",!0);a(t,function(n){return n.classList.remove("error")});var e=l("select",!0);return a(e,function(n){return n.classList.remove("error")}),!0}),b=e.close=function(){var n=!(arguments.length<=0||void 0===arguments[0])&&arguments[0];if(u()===!1)return!1;var t=l().parentElement;return("false"!==t.getAttribute("data-closable")||n!==!1)&&(t.classList.remove("basicModalContainer--fadeIn"),t.classList.add("basicModalContainer--fadeOut"),setTimeout(function(){return null!=t&&(null!=t.parentElement&&void t.parentElement.removeChild(t))},300),null!=o&&(o.focus(),o=null),!0)}},{}]},{},[1])(1)});<|endoftext|>


<commit_before>console.log("Protractor Config");
console.log(process.env.SELENIUM_URL);

var url = 'http://127.0.0.1:8000/'; // This should be local webserver
var capabilities = {
    'browserName': 'firefox'
};
if (process.env.TRAVIS) {
    url = 'https://b3ncr.github.io/angular-xeditable/'; // Change to your dev server
    capabilities.["tunnel-identifier"] = process.env.TRAVIS_JOB_NUMBER; // this is required by saucelabs
}

exports.config = {
  sauceUser: process.env.SAUCE_USERNAME,
  sauceKey: process.env.SAUCE_ACCESS_KEY,
    baseUrl: url,
    //seleniumAddress:   (process.env.SELENIUM_URL || 'http://localhost:4444/wd/hub'),
    capabilities: {
        "browserName": "firefox",
        "tunnel-identifier": process.env.TRAVIS_JOB_NUMBER
    },
    specs: ['docs/demos/text-simple/test-spec.js']
};
<commit_msg>Fixed syntax error in conf.js<commit_after>console.log("Protractor Config");
console.log(process.env.SELENIUM_URL);

var url = 'http://127.0.0.1:8000/'; // This should be local webserver
var capabilities = {
    'browserName': 'firefox'
};
if (process.env.TRAVIS) {
    url = 'https://b3ncr.github.io/angular-xeditable/'; // Change to your dev server
    capabilities["tunnel-identifier"] = process.env.TRAVIS_JOB_NUMBER; // this is required by saucelabs
}

exports.config = {
  sauceUser: process.env.SAUCE_USERNAME,
  sauceKey: process.env.SAUCE_ACCESS_KEY,
    baseUrl: url,
    //seleniumAddress:   (process.env.SELENIUM_URL || 'http://localhost:4444/wd/hub'),
    capabilities: {
        "browserName": "firefox",
        "tunnel-identifier": process.env.TRAVIS_JOB_NUMBER
    },
    specs: ['docs/demos/text-simple/test-spec.js']
};
<|endoftext|>


<commit_before>

/**
 * Basebuild migrate module, to prevent
 */
var MigrateModule = function(options, mergedOptions) {
  'use strict';

  var options       = options || null,
    utilsModule     = require('../' + mergedOptions.modulesData['utils'].uses)(options),
    mergedOptions   = mergedOptions || null,
    warnedAbout     = {},
    migrateWarnings = [],
    $               = mergedOptions.plugins;

  var migrateMessages = {
    soon      : 'and will be removed soon',
    soonTo    : 'and will be removed soon, use $newValue instead',
    removed   : 'and has been removed',
    removedTo : 'and has been removed, use $newValue instead',
  };

  function setup () {
  }

  function setMergedOptions(mergedOptions){
    mergedOptions = mergedOptions;
  }

  function migrate() {
    migrateGeneralOptions();
    migrateModulesOptions();
  }

  function migrateGeneralOptions(){

  }

  function migrateModulesOptions(){

    /**
     * Common settings
     */
    for(var moduleKey in mergedOptions.modulesData){

      /**
       * isEnabled has changed to "active"
       * @type {Boolean}
       */
      // migrateWarnProp({
      //   obj         : mergedOptions.modulesData[moduleKey],
      //   prop        : 'isEnabled',
      //   dotLocation : 'modulesData.' + moduleKey,
      //   msg         : getMessage({
      //     type        : 'soonTo',
      //     newValue    : 'active'
      //   })
      // });

    }

    /**
     * Proxy Module
     */

    /**
     * regexNext has changed to "nextTest"
     */
    migrateWarnProp({
      obj         : mergedOptions.modulesData['proxy'],
      prop        : 'regexNext',
      dotLocation : 'modulesData.proxy',
      value       : mergedOptions.modulesData['proxy'].regexNext,
      msg         : getMessage({
        type        : 'removedTo',
        newValue    : 'preventWhen'
      })
    });

    /**
     * next has changed to "preventWhen"
     */
    migrateWarnProp({
      obj         : mergedOptions.modulesData['proxy'],
      prop        : 'next',
      dotLocation : 'modulesData.proxy',
      value       : mergedOptions.modulesData['proxy'].next,
      msg         : getMessage({
        type        : 'removedTo',
        newValue    : 'preventWhen'
      })
    });

  }

  function getMessage (args) {
    args = args || {};
    var message = migrateMessages[args.type];

    for(key in args){
      message = message.replace('$' + key, $.chalk.red(args[key]) );
    }

    return message;
  }

  function migrateWarn(msg, prop, dotLocation) {
    if ( !warnedAbout[ msg ] ) {
      warnedAbout[ msg ] = true;
      migrateWarnings.push( msg );
      if ( console && console.warn ) {
        console.warn( utilsModule.getBaseBuildName() + $.chalk.yellow( "Migrate warning: property " + $.chalk.red(prop) + " of " + $.chalk.red(dotLocation) + " is deprecated " + msg) );
        if ( mergedOptions.migrate.trace && console.trace ) {
          console.trace();
        }
      }
    }
  }

  function migrateWarnProp( args ) {
    if ( Object.defineProperty ) {
      try {
        Object.defineProperty( args.obj, args.prop, {
          configurable: true,
          enumerable: true,
          get: function() {
            migrateWarn( args.msg, args.prop, args.dotLocation );
            return args.value;
          },
          set: function( newValue ) {
            migrateWarn( args.msg, args.prop, args.dotLocation );
            args.value = newValue;
          }
        });
        return;
      } catch( err ) {
        // IE8 is a dope about Object.defineProperty, can't warn there
      }
    }

    obj[ args.prop ] = args.value;
  }

  /**
   * API
   */
  return {
    setMergedOptions        : setMergedOptions,
    setup                   : setup,
    migrate                 : migrate,
    migrateWarn             : migrateWarn,
    migrateWarnProp         : migrateWarnProp,
    getMessage              : getMessage
  }
}

/**
 * Module exports
 */
module.exports = MigrateModule;<commit_msg>[Migrate] Fix description<commit_after>

/**
 * Basebuild migrate module, to manage deprecated syntax
 */
var MigrateModule = function(options, mergedOptions) {
  'use strict';

  var options       = options || null,
    utilsModule     = require('../' + mergedOptions.modulesData['utils'].uses)(options),
    mergedOptions   = mergedOptions || null,
    warnedAbout     = {},
    migrateWarnings = [],
    $               = mergedOptions.plugins;

  var migrateMessages = {
    soon      : 'and will be removed soon',
    soonTo    : 'and will be removed soon, use $newValue instead',
    removed   : 'and has been removed',
    removedTo : 'and has been removed, use $newValue instead',
  };

  function setup () {
  }

  function setMergedOptions(mergedOptions){
    mergedOptions = mergedOptions;
  }

  function migrate() {
    migrateGeneralOptions();
    migrateModulesOptions();
  }

  function migrateGeneralOptions(){

  }

  function migrateModulesOptions(){

    /**
     * Common settings
     */
    for(var moduleKey in mergedOptions.modulesData){

      /**
       * isEnabled has changed to "active"
       * @type {Boolean}
       */
      // migrateWarnProp({
      //   obj         : mergedOptions.modulesData[moduleKey],
      //   prop        : 'isEnabled',
      //   dotLocation : 'modulesData.' + moduleKey,
      //   msg         : getMessage({
      //     type        : 'soonTo',
      //     newValue    : 'active'
      //   })
      // });

    }

    /**
     * Proxy Module
     */

    /**
     * regexNext has changed to "nextTest"
     */
    migrateWarnProp({
      obj         : mergedOptions.modulesData['proxy'],
      prop        : 'regexNext',
      dotLocation : 'modulesData.proxy',
      value       : mergedOptions.modulesData['proxy'].regexNext,
      msg         : getMessage({
        type        : 'removedTo',
        newValue    : 'preventWhen'
      })
    });

    /**
     * next has changed to "preventWhen"
     */
    migrateWarnProp({
      obj         : mergedOptions.modulesData['proxy'],
      prop        : 'next',
      dotLocation : 'modulesData.proxy',
      value       : mergedOptions.modulesData['proxy'].next,
      msg         : getMessage({
        type        : 'removedTo',
        newValue    : 'preventWhen'
      })
    });

  }

  function getMessage (args) {
    args = args || {};
    var message = migrateMessages[args.type];

    for(key in args){
      message = message.replace('$' + key, $.chalk.red(args[key]) );
    }

    return message;
  }

  function migrateWarn(msg, prop, dotLocation) {
    if ( !warnedAbout[ msg ] ) {
      warnedAbout[ msg ] = true;
      migrateWarnings.push( msg );
      if ( console && console.warn ) {
        console.warn( utilsModule.getBaseBuildName() + $.chalk.yellow( "Migrate warning: property " + $.chalk.red(prop) + " of " + $.chalk.red(dotLocation) + " is deprecated " + msg) );
        if ( mergedOptions.migrate.trace && console.trace ) {
          console.trace();
        }
      }
    }
  }

  function migrateWarnProp( args ) {
    if ( Object.defineProperty ) {
      try {
        Object.defineProperty( args.obj, args.prop, {
          configurable: true,
          enumerable: true,
          get: function() {
            migrateWarn( args.msg, args.prop, args.dotLocation );
            return args.value;
          },
          set: function( newValue ) {
            migrateWarn( args.msg, args.prop, args.dotLocation );
            args.value = newValue;
          }
        });
        return;
      } catch( err ) {
        // IE8 is a dope about Object.defineProperty, can't warn there
      }
    }

    obj[ args.prop ] = args.value;
  }

  /**
   * API
   */
  return {
    setMergedOptions        : setMergedOptions,
    setup                   : setup,
    migrate                 : migrate,
    migrateWarn             : migrateWarn,
    migrateWarnProp         : migrateWarnProp,
    getMessage              : getMessage
  }
}

/**
 * Module exports
 */
module.exports = MigrateModule;<|endoftext|>


<commit_before>//the list of servers we can access
const serverPaths = [
  'http://malmo.lizenn.net:8080',
  'http://localhost:8080',
  'http://localhost:8081',
  'http://malmo.lizenn.net:8082',
]

//the adress used internally in the application to proxy
const proxyURL = '/proxiedOCCIServer';

//the adress of the initial backend Server
const backendURL = serverPaths[0];

//the prefix to append to categories queries
const backendCategoriesPrefix_erocci = '/categories/';
const backendCategoriesPrefix_mart = '/';

const initialState =  {
  currentPath: '/-/',
  currentJson: {},
  errorMessage: {
    simple: '',
    detailed: ''
  },
  okMessage: '',
  currentURLServer: backendURL,
  // readings (toolified), or write (edit)
  codeRights: 'read',
  schemes: {schemeName: [{title: '', term: ''}]}
};

//this const will be changed when deploying on standalone. Must be false by default
const integratedVersion = false;

module.exports = {initialState: initialState, proxyURL: proxyURL, backendURL: backendURL, serverPaths: serverPaths, integratedVersion: integratedVersion, backendCategoriesPrefix_erocci: backendCategoriesPrefix_erocci, backendCategoriesPrefix_mart: backendCategoriesPrefix_mart};
<commit_msg>Add martserver-linkeddata-1:8081 to default target servers<commit_after>//the list of servers we can access
const serverPaths = [
  'http://malmo.lizenn.net:8080',
  'http://localhost:8080',
  'http://localhost:8081',
  'http://malmo.lizenn.net:8082',
  'http://martserver-linkeddata-1:8081'
]

//the adress used internally in the application to proxy
const proxyURL = '/proxiedOCCIServer';

//the adress of the initial backend Server
const backendURL = serverPaths[0];

//the prefix to append to categories queries
const backendCategoriesPrefix_erocci = '/categories/';
const backendCategoriesPrefix_mart = '/';

const initialState =  {
  currentPath: '/-/',
  currentJson: {},
  errorMessage: {
    simple: '',
    detailed: ''
  },
  okMessage: '',
  currentURLServer: backendURL,
  // readings (toolified), or write (edit)
  codeRights: 'read',
  schemes: {schemeName: [{title: '', term: ''}]}
};

//this const will be changed when deploying on standalone. Must be false by default
const integratedVersion = false;

module.exports = {initialState: initialState, proxyURL: proxyURL, backendURL: backendURL, serverPaths: serverPaths, integratedVersion: integratedVersion, backendCategoriesPrefix_erocci: backendCategoriesPrefix_erocci, backendCategoriesPrefix_mart: backendCategoriesPrefix_mart};
<|endoftext|>


<commit_before>$(document).ready(function () {

  var connecter;
  var conn;
  var status = $('#status');

  function fmtDatetime(d) {
    function zero(n) {
      return ('0' + n).slice(-2);
    }

    return d.getFullYear() + "/" +
           zero(d.getMonth()) + "/" +
           zero(d.getDay()) + " " +
           zero(d.getHours()) + ":" +
           zero(d.getMinutes());
  }

  function alertsEnhance(data) {

    function lastTimeDesc(a,b) {
      if (a.LastTime < b.LastTime)
        return 1;
      if (a.LastTime > b.LastTime)
        return -1;
      return 0;
    }

    var res = [];
    $.each(data, function () {
      var alert = this;
      res.push(alert);
      // max() would do the trick, tbh
      if (alert.Type === "BAD")
        alert.LastTime = new Date(alert.BadTime);
      else
        alert.LastTime = new Date(alert.GoodTime);
    })
    res.sort(lastTimeDesc);
    console.log(res);
    return res;
  }

  function alertsBuild(alerts) {
    var root = $('#alerts');
    var rings = 0;
    root.empty();
    $.each(alerts, function () {
      var dAlert = $('<div/>').addClass('alert');
      var dDates = $('<div/>').addClass('dates').appendTo(dAlert);
      var dTitle = $('<div/>').addClass('title').appendTo(dAlert).text(this.Subject);

      var sStart = $('<span/>').addClass('start').appendTo(dDates);
      dDates.append(' ');
      var sEnd   = $('<span/>').addClass('end').appendTo(dDates);

      start = new Date(this.BadTime);
      sStart.text(fmtDatetime(start));
      if (this.Type === "GOOD") {
        dAlert.addClass('_good');
        end = new Date(this.GoodTime);
        sEnd.text(fmtDatetime(end));
      } else { // "BAD"
        rings++;
        $.each(this.Classes, function () {
          dAlert.addClass(""+this);
        });
        sEnd.text("--");
      }
      root.append(dAlert);
    });
    $('#count').text(rings);
  }

  function alertsRefresh() {
    var alerts = $.getJSON("/alerts", function (data) {
        alerts = alertsEnhance(data);
        alertsBuild(alerts);
    });
  }

  function wsConnect() {
    console.log("wsConnect");
    conn = new WebSocket("ws://" + document.location.host + "/ws");
    conn.onopen = function (evt) {
      status.text("Live").attr('class', 'ok');
      alertsRefresh();
    };
    conn.onclose = function (evt) {
      status.text("No connection").attr('class', 'ko');
    };
    conn.onmessage = function (evt) {
      if (evt.data === "updated") {
        alertsRefresh();
      }
    };
  }

  if (window["WebSocket"]) {
    wsConnect();
    setInterval(function() {
      if (conn.readyState == 3)
        wsConnect();
    }, 2000);
  } else {
    status.text("no WebSocket support").attr('class', '');
  }
});
<commit_msg>removing debug traces<commit_after>$(document).ready(function () {

  var connecter;
  var conn;
  var status = $('#status');

  function fmtDatetime(d) {
    function zero(n) {
      return ('0' + n).slice(-2);
    }

    return d.getFullYear() + "/" +
           zero(d.getMonth()) + "/" +
           zero(d.getDay()) + " " +
           zero(d.getHours()) + ":" +
           zero(d.getMinutes());
  }

  function alertsEnhance(data) {

    function lastTimeDesc(a,b) {
      if (a.LastTime < b.LastTime)
        return 1;
      if (a.LastTime > b.LastTime)
        return -1;
      return 0;
    }

    var res = [];
    $.each(data, function () {
      var alert = this;
      res.push(alert);
      // max() would do the trick, tbh
      if (alert.Type === "BAD")
        alert.LastTime = new Date(alert.BadTime);
      else
        alert.LastTime = new Date(alert.GoodTime);
    })
    res.sort(lastTimeDesc);
    return res;
  }

  function alertsBuild(alerts) {
    var root = $('#alerts');
    var rings = 0;
    root.empty();
    $.each(alerts, function () {
      var dAlert = $('<div/>').addClass('alert');
      var dDates = $('<div/>').addClass('dates').appendTo(dAlert);
      var dTitle = $('<div/>').addClass('title').appendTo(dAlert).text(this.Subject);

      var sStart = $('<span/>').addClass('start').appendTo(dDates);
      dDates.append(' ');
      var sEnd   = $('<span/>').addClass('end').appendTo(dDates);

      start = new Date(this.BadTime);
      sStart.text(fmtDatetime(start));
      if (this.Type === "GOOD") {
        dAlert.addClass('_good');
        end = new Date(this.GoodTime);
        sEnd.text(fmtDatetime(end));
      } else { // "BAD"
        rings++;
        $.each(this.Classes, function () {
          dAlert.addClass(""+this);
        });
        sEnd.text("--");
      }
      root.append(dAlert);
    });
    $('#count').text(rings);
  }

  function alertsRefresh() {
    var alerts = $.getJSON("/alerts", function (data) {
        alerts = alertsEnhance(data);
        alertsBuild(alerts);
    });
  }

  function wsConnect() {
    // console.log("wsConnect");
    conn = new WebSocket("ws://" + document.location.host + "/ws");
    conn.onopen = function (evt) {
      status.text("Live").attr('class', 'ok');
      alertsRefresh();
    };
    conn.onclose = function (evt) {
      status.text("No connection").attr('class', 'ko');
    };
    conn.onmessage = function (evt) {
      if (evt.data === "updated") {
        alertsRefresh();
      }
    };
  }

  if (window["WebSocket"]) {
    wsConnect();
    setInterval(function() {
      if (conn.readyState == 3)
        wsConnect();
    }, 2000);
  } else {
    status.text("no WebSocket support").attr('class', '');
  }
});
<|endoftext|>


<commit_before>
$.getJSON("/api/pheno/" + window.pheno + ".json").done(function(variants) {
    window.variant_bins = variants.variant_bins;
    window.unbinned_variants = variants.unbinned_variants;
    $(create_gwas_plot);
});

var get_chrom_offsets = _.memoize(function() {
    var chrom_padding = 2e7;
    var chrom_extents = {};

    var update_chrom_extents = function(variant) {
        if (!(variant.chrom in chrom_extents)) {
            chrom_extents[variant.chrom] = [variant.pos, variant.pos];
        } else if (variant.pos > chrom_extents[variant.chrom][1]) {
            chrom_extents[variant.chrom][1] = variant.pos;
        } else if (variant.pos < chrom_extents[variant.chrom][0]) {
            chrom_extents[variant.chrom][0] = variant.pos;
        }
    }
    window.variant_bins.forEach(update_chrom_extents);
    window.unbinned_variants.forEach(update_chrom_extents);

    var chroms = _.sortBy(Object.keys(chrom_extents), function(chrom) {
        return Number.parseInt(chrom);
    });
    // chrom_offsets are defined to be the numbers that make `get_genomic_position()` work.
    // ie, they leave a gap of `chrom_padding` between the last variant on one chromosome and the first on the next.
    var chrom_offsets = {};
    chrom_offsets[chroms[0]] = -chrom_extents[chroms[0]][0];
    for (var i=1; i<chroms.length; i++) {
        chrom_offsets[chroms[i]] = chrom_offsets[chroms[i-1]] + chrom_extents[chroms[i-1]][1] - chrom_extents[chroms[i]][0] + chrom_padding;
    }
    return {
        "chrom_offsets": chrom_offsets,
        "chroms": chroms,
    };
});

function get_genomic_position(variant) {
    var chrom_offsets = get_chrom_offsets().chrom_offsets;
    return chrom_offsets[variant.chrom] + variant.pos;
}

function create_gwas_plot() {
    var svg_width = $('#plot_container').width();
    var svg_height = 550;
    var plot_margin = {
        'left': 70,
        'right': 30,
        'top': 10,
        'bottom': 50,
    };
    var plot_width = svg_width - plot_margin.left - plot_margin.right;
    var plot_height = svg_height - plot_margin.top - plot_margin.bottom;

    var gwas_svg = d3.select('#plot_container').append("svg")
        .attr('id', 'gwas_svg')
        .attr("width", svg_width)
        .attr("height", svg_height)
        .style("display", "block")
        .style("margin", "auto");
    var gwas_plot = gwas_svg.append("g")
        .attr('id', 'gwas_plot')
        .attr("transform", fmt("translate({0},{1})", plot_margin.left, plot_margin.top));

    // Significance Threshold line
    var significance_threshold = 5e-8;
    var significance_threshold_tooltip = d3.tip()
        .attr('class', 'd3-tip')
        .html(function(d) {
            return 'Significance Threshold: 5E-8';
        })
        .offset([-8,0]);
    gwas_svg.call(significance_threshold_tooltip);

    var genomic_position_extent = (function() {
        var extent1 = d3.extent(window.variant_bins, function(d) {
            return get_genomic_position(d);
        });
        var extent2 = d3.extent(window.unbinned_variants, function(d) {
            return get_genomic_position(d);
        });
        return d3.extent(extent1.concat(extent2));
    })();

    var x_scale = d3.scale.linear()
        .domain(genomic_position_extent)
        .range([0, plot_width]);

    var max_neglog10_pval = (function() {
        if (window.unbinned_variants.length > 0) {
            return d3.max(window.unbinned_variants, function(d) {
                return -Math.log10(d.pval);
            });
        }
        return d3.max(window.variant_bins, function(bin) {
            return d3.max(bin, function(d) {
                return d.neglog10_pval;
            });
        });
    })();

    var y_scale = d3.scale.linear()
        .domain([Math.max(10, max_neglog10_pval), 0])
        .range([0, plot_height]);

    var color_by_chrom = d3.scale.ordinal()
        .domain(get_chrom_offsets().chroms)
        .range(['rgb(120,120,186)', 'rgb(0,0,66)']);
    //colors to maybe sample from later:
    //.range(['rgb(120,120,186)', 'rgb(0,0,66)', 'rgb(44,150,220)', 'rgb(40,60,80)', 'rgb(33,127,188)', 'rgb(143,76,176)']);

    gwas_plot.append('line')
        .attr('x1', 0)
        .attr('x2', plot_width)
        .attr('y1', y_scale(-Math.log10(significance_threshold)))
        .attr('y2', y_scale(-Math.log10(significance_threshold)))
        .attr('stroke-width', '5px')
        .attr('stroke', 'lightgray')
        .attr('stroke-dasharray', '10,10')
        .on('mouseover', significance_threshold_tooltip.show)
        .on('mouseout', significance_threshold_tooltip.hide);

    // Points & labels
    var tooltip_template = _.template($('#tooltip-template').html());
    var point_tooltip = d3.tip()
        .attr('class', 'd3-tip')
        .html(function(d) {
            return tooltip_template({d: d});
        })
        .offset([-6,0]);
    gwas_svg.call(point_tooltip);

    gwas_plot.selectAll('a.variant_big_point')
        .data(window.unbinned_variants)
        .enter()
        .append('a')
        .attr('class', 'variant_big_point')
        .attr('xlink:href', function(d) {
            return fmt('/variant/{0}-{1}-{2}-{3}', d.chrom, d.pos, d.ref, d.alt);
        })
        .append('circle')
        .attr('cx', function(d) {
            return x_scale(get_genomic_position(d));
        })
        .attr('cy', function(d) {
            return y_scale(-Math.log10(d.pval));
        })
        .attr('r', 7)
        .style('opacity', 0)
        .style('stroke-width', 1)
        .on('mouseover', function(d) {
            //Note: once a tooltip has been explicitly placed once, it must be explicitly placed forever after.
            var target_node = document.getElementById(fmt('little-point-{0}-{1}-{2}-{3}', d.chrom, d.pos, d.ref, d.alt));
            point_tooltip.show(d, target_node);
        })
        .on('mouseout', point_tooltip.hide);

    gwas_plot.selectAll('a.variant_little_point')
        .data(window.unbinned_variants)
        .enter()
        .append('a')
        .attr('class', 'variant_little_point')
        .attr('xlink:href', function(d) {
            return fmt('/variant/{0}-{1}-{2}-{3}', d.chrom, d.pos, d.ref, d.alt);
        })
        .append('circle')
        .attr('id', function(d) {
            return fmt('little-point-{0}-{1}-{2}-{3}', d.chrom, d.pos, d.ref, d.alt);
        })
        .attr('cx', function(d) {
            return x_scale(get_genomic_position(d));
        })
        .attr('cy', function(d) {
            return y_scale(-Math.log10(d.pval));
        })
        .attr('r', 2.3)
        .style('fill', function(d) {
            return color_by_chrom(d.chrom);
        })
        .on('mouseover', function(d) {
            //Note: once a tooltip has been explicitly placed once, it must be explicitly placed forever after.
            point_tooltip.show(d, this);
        })
        .on('mouseout', point_tooltip.hide);

    gwas_plot.selectAll('g.bin')
        .data(window.variant_bins)
        .enter()
        .append('g')
        .attr('class', 'bin')
        .selectAll('circle.binned_variant_little_point')
        .data(function(d) { return d.neglog10_pvals; })
        .enter()
        .append('circle')
        .attr('class', 'binned_variant_little_point')
        .attr('cx', function() {
            //return x_scale(get_genomic_position(d3.select(this.parentNode).datum()));
            return x_scale(get_genomic_position(this.parentNode.__data__));
        })
        .attr('cy', function(d) {
            return y_scale(d);
        })
        .attr('r', 2.3)
        .style('fill', function() {
            // return color_by_chrom(d3.select(this.parentNode).datum().chrom);
            return color_by_chrom(this.parentNode.__data__.chrom);
        });

    // Axes
    var yAxis = d3.svg.axis()
        .scale(y_scale)
        .orient("left")
        .tickFormat(d3.format("d"));
    gwas_plot.append("g")
        .attr("class", "y axis")
        .attr('transform', 'translate(-3,0)') // avoid letting points spill through the y axis.
        .call(yAxis);

    gwas_svg.append('text')
        .style('text-anchor', 'middle')
        .attr('transform', fmt('translate({0},{1})rotate(-90)',
                               plot_margin.left*.4,
                               plot_height/2 + plot_margin.top))
        .text('-log10(pvalue)');

    var xAxis = d3.svg.axis()
        .scale(x_scale)
        .orient("bottom");
    gwas_plot.append("g")
        .attr("class", "x axis")
        .attr("transform", fmt("translate(0,{0})", plot_height))
        .call(xAxis);

    gwas_svg.append('text')
        .style('text-anchor', 'middle')
        .attr('transform', fmt('translate({0},{1})',
                               plot_width/2 + plot_margin.left,
                               plot_height + plot_margin.top + plot_margin.bottom*.9))
        .text('Genomic Position');
}

function fmt(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function(match, number) {
        return (typeof args[number] != 'undefined') ? args[number] : match;
    });
}
<commit_msg>Add chromosome x-labels in a super gross way, please re-do this.<commit_after>
$.getJSON("/api/pheno/" + window.pheno + ".json").done(function(variants) {
    window.variant_bins = variants.variant_bins;
    window.unbinned_variants = variants.unbinned_variants;
    $(create_gwas_plot);
});

var get_chrom_offsets = _.memoize(function() {
    var chrom_padding = 2e7;
    var chrom_extents = {};

    var update_chrom_extents = function(variant) {
        if (!(variant.chrom in chrom_extents)) {
            chrom_extents[variant.chrom] = [variant.pos, variant.pos];
        } else if (variant.pos > chrom_extents[variant.chrom][1]) {
            chrom_extents[variant.chrom][1] = variant.pos;
        } else if (variant.pos < chrom_extents[variant.chrom][0]) {
            chrom_extents[variant.chrom][0] = variant.pos;
        }
    }
    window.variant_bins.forEach(update_chrom_extents);
    window.unbinned_variants.forEach(update_chrom_extents);

    var chroms = _.sortBy(Object.keys(chrom_extents), function(chrom) {
        return Number.parseInt(chrom);
    });

    var chrom_genomic_start_positions = {};
    chrom_genomic_start_positions[chroms[0]] = 0;
    for (var i=1; i<chroms.length; i++) {
        chrom_genomic_start_positions[chroms[i]] = chrom_genomic_start_positions[chroms[i-1]] + chrom_extents[chroms[i-1]][1] - chrom_extents[chroms[i-1]][0] + chrom_padding;
    }

    // chrom_offsets are defined to be the numbers that make `get_genomic_position()` work.
    // ie, they leave a gap of `chrom_padding` between the last variant on one chromosome and the first on the next.
    var chrom_offsets = {};
    Object.keys(chrom_genomic_start_positions).forEach(function(chrom) {
        chrom_offsets[chrom] = chrom_genomic_start_positions[chrom] - chrom_extents[chrom][0];
    });

    return {
        chrom_extents: chrom_extents,
        chroms: chroms,
        chrom_genomic_start_positions: chrom_genomic_start_positions,
        chrom_offsets: chrom_offsets,
    };
});

function get_genomic_position(variant) {
    var chrom_offsets = get_chrom_offsets().chrom_offsets;
    return chrom_offsets[variant.chrom] + variant.pos;
}

function create_gwas_plot() {
    var svg_width = $('#plot_container').width();
    var svg_height = 550;
    var plot_margin = {
        'left': 70,
        'right': 30,
        'top': 10,
        'bottom': 50,
    };
    var plot_width = svg_width - plot_margin.left - plot_margin.right;
    var plot_height = svg_height - plot_margin.top - plot_margin.bottom;

    var gwas_svg = d3.select('#plot_container').append("svg")
        .attr('id', 'gwas_svg')
        .attr("width", svg_width)
        .attr("height", svg_height)
        .style("display", "block")
        .style("margin", "auto");
    var gwas_plot = gwas_svg.append("g")
        .attr('id', 'gwas_plot')
        .attr("transform", fmt("translate({0},{1})", plot_margin.left, plot_margin.top));

    // Significance Threshold line
    var significance_threshold = 5e-8;
    var significance_threshold_tooltip = d3.tip()
        .attr('class', 'd3-tip')
        .html(function(d) {
            return 'Significance Threshold: 5E-8';
        })
        .offset([-8,0]);
    gwas_svg.call(significance_threshold_tooltip);

    var genomic_position_extent = (function() {
        var extent1 = d3.extent(window.variant_bins, function(d) {
            return get_genomic_position(d);
        });
        var extent2 = d3.extent(window.unbinned_variants, function(d) {
            return get_genomic_position(d);
        });
        return d3.extent(extent1.concat(extent2));
    })();

    var x_scale = d3.scale.linear()
        .domain(genomic_position_extent)
        .range([0, plot_width]);

    var max_neglog10_pval = (function() {
        if (window.unbinned_variants.length > 0) {
            return d3.max(window.unbinned_variants, function(d) {
                return -Math.log10(d.pval);
            });
        }
        return d3.max(window.variant_bins, function(bin) {
            return d3.max(bin, function(d) {
                return d.neglog10_pval;
            });
        });
    })();

    var y_scale = d3.scale.linear()
        .domain([Math.max(10, max_neglog10_pval), 0])
        .range([0, plot_height]);

    var color_by_chrom = d3.scale.ordinal()
        .domain(get_chrom_offsets().chroms)
        .range(['rgb(120,120,186)', 'rgb(0,0,66)']);
    //colors to maybe sample from later:
    //.range(['rgb(120,120,186)', 'rgb(0,0,66)', 'rgb(44,150,220)', 'rgb(40,60,80)', 'rgb(33,127,188)', 'rgb(143,76,176)']);

    gwas_plot.append('line')
        .attr('x1', 0)
        .attr('x2', plot_width)
        .attr('y1', y_scale(-Math.log10(significance_threshold)))
        .attr('y2', y_scale(-Math.log10(significance_threshold)))
        .attr('stroke-width', '5px')
        .attr('stroke', 'lightgray')
        .attr('stroke-dasharray', '10,10')
        .on('mouseover', significance_threshold_tooltip.show)
        .on('mouseout', significance_threshold_tooltip.hide);

    // Points & labels
    var tooltip_template = _.template($('#tooltip-template').html());
    var point_tooltip = d3.tip()
        .attr('class', 'd3-tip')
        .html(function(d) {
            return tooltip_template({d: d});
        })
        .offset([-6,0]);
    gwas_svg.call(point_tooltip);

    gwas_plot.append('g')
        .attr('class', 'variant_hover_rings')
        .selectAll('a.variant_hover_ring')
        .data(window.unbinned_variants)
        .enter()
        .append('a')
        .attr('class', 'variant_hover_ring')
        .attr('xlink:href', function(d) {
            return fmt('/variant/{0}-{1}-{2}-{3}', d.chrom, d.pos, d.ref, d.alt);
        })
        .append('circle')
        .attr('cx', function(d) {
            return x_scale(get_genomic_position(d));
        })
        .attr('cy', function(d) {
            return y_scale(-Math.log10(d.pval));
        })
        .attr('r', 7)
        .style('opacity', 0)
        .style('stroke-width', 1)
        .on('mouseover', function(d) {
            //Note: once a tooltip has been explicitly placed once, it must be explicitly placed forever after.
            var target_node = document.getElementById(fmt('variant-point-{0}-{1}-{2}-{3}', d.chrom, d.pos, d.ref, d.alt));
            point_tooltip.show(d, target_node);
        })
        .on('mouseout', point_tooltip.hide);

    gwas_plot.append('g')
        .attr('class', 'variant_points')
        .selectAll('a.variant_point')
        .data(window.unbinned_variants)
        .enter()
        .append('a')
        .attr('class', 'variant_point')
        .attr('xlink:href', function(d) {
            return fmt('/variant/{0}-{1}-{2}-{3}', d.chrom, d.pos, d.ref, d.alt);
        })
        .append('circle')
        .attr('id', function(d) {
            return fmt('variant-point-{0}-{1}-{2}-{3}', d.chrom, d.pos, d.ref, d.alt);
        })
        .attr('cx', function(d) {
            return x_scale(get_genomic_position(d));
        })
        .attr('cy', function(d) {
            return y_scale(-Math.log10(d.pval));
        })
        .attr('r', 2.3)
        .style('fill', function(d) {
            return color_by_chrom(d.chrom);
        })
        .on('mouseover', function(d) {
            //Note: once a tooltip has been explicitly placed once, it must be explicitly placed forever after.
            point_tooltip.show(d, this);
        })
        .on('mouseout', point_tooltip.hide);

    gwas_plot.append('g')
        .attr('class', 'bins')
        .selectAll('g.bin')
        .data(window.variant_bins)
        .enter()
        .append('g')
        .attr('class', 'bin')
        .selectAll('circle.binned_variant_little_point')
        .data(function(d) { return d.neglog10_pvals; })
        .enter()
        .append('circle')
        .attr('class', 'binned_variant_little_point')
        .attr('cx', function() {
            //return x_scale(get_genomic_position(d3.select(this.parentNode).datum()));
            return x_scale(get_genomic_position(this.parentNode.__data__));
        })
        .attr('cy', function(d) {
            return y_scale(d);
        })
        .attr('r', 2.3)
        .style('fill', function() {
            // return color_by_chrom(d3.select(this.parentNode).datum().chrom);
            return color_by_chrom(this.parentNode.__data__.chrom);
        });

    // Axes
    var yAxis = d3.svg.axis()
        .scale(y_scale)
        .orient("left")
        .tickFormat(d3.format("d"));
    gwas_plot.append("g")
        .attr("class", "y axis")
        .attr('transform', 'translate(-8,0)') // avoid letting points spill through the y axis.
        .call(yAxis);

    gwas_svg.append('text')
        .style('text-anchor', 'middle')
        .attr('transform', fmt('translate({0},{1})rotate(-90)',
                               plot_margin.left*.4,
                               plot_height/2 + plot_margin.top))
        .text('-log10(pvalue)');

    var chroms_and_midpoints = (function() {
        var v = get_chrom_offsets();
        return v.chroms.map(function(chrom) {
            return {
                chrom: chrom,
                midpoint: v.chrom_genomic_start_positions[chrom] + (v.chrom_extents[chrom][1] - v.chrom_extents[chrom][0]) / 2,
            };
        });
    })();
    console.log(chroms_and_midpoints);

    gwas_svg.selectAll('text.chrom_label')
        .data(chroms_and_midpoints)
        .enter()
        .append('text')
        .style('text-anchor', 'middle')
        .attr('transform', function(d) {
            return fmt('translate({0},{1})',
                       plot_margin.left + x_scale(d.midpoint),
                       plot_height + plot_margin.top + 20);
        })
        .text(function(d) {
            return d.chrom;
        })
        .style('fill', function(d) {
            return color_by_chrom(d.chrom);
        });

}

function fmt(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function(match, number) {
        return (typeof args[number] != 'undefined') ? args[number] : match;
    });
}
<|endoftext|>


<commit_before>// # document ready
$(document).ready(function() {
    if (!window.console) window.console = {};
    if (!window.console.log) window.console.log = function() {};

    console.log("ready");
    $(document).keydown(callback);
    updater.start();
});

// # updater
var updater = {
    socket: null,
    retry_attempts: 0,
    max_retry_attempts: 120,

    // * start
    start: function() {

        if (updater.socket == null) {
            var protocol = ("https:" == location.protocol) ? "wss:" : "ws:"
            var url = protocol + "//" + location.host + "/ws";
            updater.socket = new WebSocket(url);

            // * socket open
            updater.socket.onopen = function() {
                console.log("onopen");
            };

            // * socket onmessage
            updater.socket.onmessage = function(event) {
                var json = JSON.parse(event.data);
                console.log("onmessage: " + "{keyCode: " + json['keyCode'] + ", slidePage: " + json['slidePage'] + "}");

                // change page
                changePageTo(json["slidePage"]);
            };

            // * socket close
            updater.socket.onclose = function(event) {
                console.log("onclose. reason: %s", event.reason);

                var time = updater.generateInterval(updater.attempts);

                if (updater.retry_attempts < updater.max_retry_attempts) {
                    // Connection has closed so try to reconnect.
                    updater.socket = null;
                    updater.start();
                    updater.retry_attempts++;
                    console.log("retry_attempts: ", updater.retry_attempts);

                } else {
                    console.log("websocket closed by over max_retry_attempts: ", updater.retry_attempts);

                }
            };

            // * socket onerror
            updater.socket.onerror = function(event) {
                console.log("onerror");
            }
        }
    }
};

// # slide action from client
// * common changePageTo
function changePageTo(toPage) {
    currentHash = location.hash;

    if ("#" == currentHash.charAt(0)) {

      if ("p" == currentHash.charAt(1)) {
          pMode = true;

      } else {
          pMode = false;

      }

    } else {
        return false;

    };

    var nextPage = toPage;
    var nextHash  = "#" + (pMode ? "p" : "") + nextPage;

    if (nextHash) {
        console.log("change page from: " + currentHash + " to: " + nextHash);
        location.hash = nextHash;

    }

    return false;

}

// # slide action from self
// * callback
var callback = function(e) {
    console.log(e.type, e);

    var text = e.type;
    var keyCode = e.which ? e.which : e.keyCode;
    if (13 === keyCode) {
        text += ": ENTER";
    } else {
        text += ": keycode "+ keyCode;
    }

    console.log(text);

    currentHash = location.hash;

    if ("#" == currentHash.charAt(0)) {

      if ("p" == currentHash.charAt(1)) {
          currentPage = parseInt(hash.substring(2), 10);

      } else {
          currentPage = parseInt(hash.substring(1), 10);

      }

    } else {
        return false;

    };

    // send command
    var message = {keyCode: keyCode, slidePage: currentPage};
    updater.socket.send(JSON.stringify(message));

};
<commit_msg>remove wrong function<commit_after>// # document ready
$(document).ready(function() {
    if (!window.console) window.console = {};
    if (!window.console.log) window.console.log = function() {};

    console.log("ready");
    $(document).keydown(callback);
    updater.start();
});

// # updater
var updater = {
    socket: null,
    retry_attempts: 0,
    max_retry_attempts: 120,

    // * start
    start: function() {

        if (updater.socket == null) {
            var protocol = ("https:" == location.protocol) ? "wss:" : "ws:"
            var url = protocol + "//" + location.host + "/ws";
            updater.socket = new WebSocket(url);

            // * socket open
            updater.socket.onopen = function() {
                console.log("onopen");
            };

            // * socket onmessage
            updater.socket.onmessage = function(event) {
                var json = JSON.parse(event.data);
                console.log("onmessage: " + "{keyCode: " + json['keyCode'] + ", slidePage: " + json['slidePage'] + "}");

                // change page
                changePageTo(json["slidePage"]);
            };

            // * socket close
            updater.socket.onclose = function(event) {
                console.log("onclose. reason: %s", event.reason);

                if (updater.retry_attempts < updater.max_retry_attempts) {
                    // Connection has closed so try to reconnect.
                    updater.socket = null;
                    updater.start();
                    updater.retry_attempts++;
                    console.log("retry_attempts: ", updater.retry_attempts);

                } else {
                    console.log("websocket closed by over max_retry_attempts: ", updater.retry_attempts);

                }
            };

            // * socket onerror
            updater.socket.onerror = function(event) {
                console.log("onerror");
            }
        }
    }
};

// # slide action from client
// * common changePageTo
function changePageTo(toPage) {
    currentHash = location.hash;

    if ("#" == currentHash.charAt(0)) {

      if ("p" == currentHash.charAt(1)) {
          pMode = true;

      } else {
          pMode = false;

      }

    } else {
        return false;

    };

    var nextPage = toPage;
    var nextHash  = "#" + (pMode ? "p" : "") + nextPage;

    if (nextHash) {
        console.log("change page from: " + currentHash + " to: " + nextHash);
        location.hash = nextHash;

    }

    return false;

}

// # slide action from self
// * callback
var callback = function(e) {
    console.log(e.type, e);

    var text = e.type;
    var keyCode = e.which ? e.which : e.keyCode;
    if (13 === keyCode) {
        text += ": ENTER";
    } else {
        text += ": keycode "+ keyCode;
    }

    console.log(text);

    currentHash = location.hash;

    if ("#" == currentHash.charAt(0)) {

      if ("p" == currentHash.charAt(1)) {
          currentPage = parseInt(hash.substring(2), 10);

      } else {
          currentPage = parseInt(hash.substring(1), 10);

      }

    } else {
        return false;

    };

    // send command
    var message = {keyCode: keyCode, slidePage: currentPage};
    updater.socket.send(JSON.stringify(message));

};
<|endoftext|>


<commit_before>/*
	Let's get these stars up in here
*/

$(document).ready(function () {
  // user clicks on the star
  $('.star').click(function () {
    var data = {}
    data.name = $(this).data('name')
    data.isStarred = $(this).hasClass('star-starred')

    $.ajax({
      url: '/star'
    , data: JSON.stringify(data)
    , type: 'POST'
    })
    .done(function (resp) {
      console.log(data, resp)

      if (data.isStarred) {
        console.log('no more yellow :-(')
        $('.star').removeClass('star-starred')
      } else {
        console.log('make it into a star!!')
        $('.star').addClass('star-starred')
      }
    })
    .error(function (resp) {
      console.log('error: ', resp)
      window.location = '/login?done=/package/' + data.name
    })
  })

})<commit_msg>adds cookies to counter some caching issues<commit_after>/*
	Let's get these stars up in here
*/

function addExpiration () {
  var NUM_SECONDS = 60
  var d = new Date()
  d.setTime(d.getTime() + NUM_SECONDS*1000)
  return '; expires='+d.toGMTString()
}

function getPackages (name) {
  if (document.cookie.indexOf('packages') === -1) return name ? null : {}

  var cookies = document.cookie.split('; ')
  for (var i = 0; i < cookies.length; ++i) {
    if (cookies[i].indexOf('packages') > -1)
      var packages = JSON.parse(cookies[i].split('=')[1])
      if (name) return packages[name]
      return packages
  }

  return name ? null : {}
}

$(document).ready(function () {
  // check if there's already a cookie
  var packageName = $('.star').data('name')

  var starType = getPackages(packageName)
  if (starType) {
    if (starType === 'star') {
      $('.star').addClass('star-starred')
    } else {
      $('.star').removeClass('star-starred')
    }
  }

  // user clicks on the star
  $('.star').click(function (e) {
    // let's turn this into a checkbox eventually...
    e.preventDefault()
    var packages = getPackages()

    var data = {}
    data.name = $(this).data('name')
    data.isStarred = $(this).hasClass('star-starred')

    $.ajax({
      url: '/star'
    , data: JSON.stringify(data)
    , type: 'POST'
    })
    .done(function (resp) {

      if (data.isStarred) {
        // console.log('no more yellow :-(')
        $('.star').removeClass('star-starred')
        packages[data.name] = 'nostar'
        document.cookie =  'packages=' + JSON.stringify(packages) + addExpiration()
      } else {
        // console.log('make it into a star!!')
        $('.star').addClass('star-starred')
        packages[data.name] = 'star'
        document.cookie =  'packages=' + JSON.stringify(packages) + addExpiration()
      }

    })
    .error(function (resp) {
      // console.log('error: ', resp)
      window.location = '/login?done=/package/' + data.name
    })
  })

})<|endoftext|>