<commit_before>var app = {
  init : function() {
    app.loading = false;
    app.current = null;
    app.autoplay = false;
    app.autoplay_timer = null;

    var opt = {
      center: new google.maps.LatLng(50.037643, 8.562409), zoom: 15,
      mapTypeId: google.maps.MapTypeId.SATELLITE,
      disableDefaultUI: true, mapTypeControl: false, navigationControl: false, disableDoubleClickZoom: false,
      draggable: false, scrollwheel: false, streetViewControl: false,
      backgroundColor: '#000000'};
    app.map = new google.maps.Map($('#map')[0],opt);

    app.static_airports = [
      new Airport(["EDDF","Frankfurt am Main International Airport","L","49.9984","8.49708","50.0458","8.58698","DE","Frankfurt-am-Main"]),
      new Airport(["OMDB","Dubai International Airport","L","25.2433","55.347","25.2665","55.3815","AE","Dubai"]),
      new Airport(["KSFO","San Francisco International Airport","L","37.6068","-122.393","37.6287","-122.357","US","San Francisco"])
    ];
    app.airports = [];
    $.get("data/data.csv", function(data) {
      var lines = data.split(/\r\n|\n/);
      for (var i=1; i<lines.length; i++)
      {
        var data = lines[i].split(',');
        if (data.length == 9)
        {
          app.airports.push(new Airport(data));
        }
      }
    });

    // setup event handlers
    google.maps.event.addListener(app.map, 'click', function(event) {
      app.track("map", "click");
      app.loadRandomAirport();
    });

    google.maps.event.addDomListener(window, 'resize', function() {
      google.maps.event.trigger(app.map, 'resize');
      app.fitMap();
    });

    $('#control-info').click(function() {
      app.track("control", "info");
      app.openInfoOverlay();
      });
    $('#control-google-maps').click(function() {
      app.openGoogleMaps();
      });
    $('#control-random').click(function() {
      app.track("control", "random");
      app.loadRandomAirport();
      });
    $('#control-play').click(function() {
      app.track("control", "play");
      app.toggleAutoPlay();
      });
    $('#info-overlay').click(function() {
      $('#info-overlay').fadeOut(1000);
      $('#controls').fadeIn(1000);
      $('#label').fadeIn(1000);
      });

    app.loadRandomAirport();
  },

  load : function(code) {
    for (var index = 0; index < app.airports.length; ++index) {
      if (app.airports[index].get_code() != code) {
        continue;
      }

      app.current = app.airports[index];
      app.updateLabel();
      app.fitMap();
      break;
    }
  },

  fitMap : function() {
    if (!app.current) {
      return;
    }
    app.map.setCenter(app.current.get_pos());
    if (app.current.get_bounds().getNorthEast().equals(app.current.get_bounds().getSouthWest())) {
      app.map.setZoom(app.current.get_zoom());
    } else {
      app.map.fitBounds(app.current.get_bounds());
    }
  },

  toggleAutoPlay : function () {
    if (app.autoplay) {
      clearInterval(app.autoplay_timer);
      app.autoplay = false;
      $('#control-play > i').removeClass('fa-pause').addClass('fa-play');
    } else {
      app.autoplay = true;
      $('#control-play > i').removeClass('fa-play').addClass('fa-pause');
      app.autoplay_interval = setInterval(function() {
        app.track("autoplay", "load");
        app.loadRandomAirport();
        }, 60 * 1000);
    }
  },

  openGoogleMaps : function() {
    app.track("control", "google-maps", "airport", app.current.get_label());
    window.open(app.current.get_google_maps_url(), '_blank');
  },

  openInfoOverlay : function() {
    $('#controls').fadeOut(1000);
    $('#label').fadeOut(1000);
    $('#info-overlay').fadeIn(1000);
    $('#info-overlay button').click(function(){
      app.closeInfoOverlay();
    });
  },

  closeInfoOverlay : function() {
    $('#info-overlay').fadeOut(1000);
    $('#controls').fadeIn(1000);
    $('#label').fadeIn(1000);
  },

  updateLabel : function() {
    $('#label').html(app.current.get_label());
    $('#location').html(app.current.get_location_name());
  },

  onStartLoading : function() {
    if (!app.loading) {
      return;
    }

    $('#control-random > i').addClass('fa-spin');
    $('#container').prepend($('#map').clone(false).attr('id','map-buffer'));
  },

  onFinishLoading : function() {
    if (!app.loading) {
      return;
    }

    var map_buffer = $('#map-buffer');
    if (map_buffer) {
      map_buffer.remove();
    }

    app.updateLabel();
    $('#control-random > i').removeClass('fa-spin');
    app.loading = false;
  },

  loadRandomAirport : function() {
    if (app.loading) {
      return;
    }
    app.loading = true;
    app.onStartLoading();

    if (app.airports.length > 0) {
      var index =  Math.floor(Math.random() * app.airports.length);
      app.current = app.airports[index];
    } else if (app.static_airports.length > 0) {
      var index =  Math.floor(Math.random() * app.static_airports.length);
      app.current = app.static_airports[index];
    } else {
      return;
    }

    google.maps.event.addListenerOnce(app.map, 'bounds_changed', function(){
      setTimeout(function(){
        $('#map-buffer').fadeOut(1000, function(){ app.onFinishLoading(); });
        }, 2000);
      });
    setTimeout(function(){ app.onFinishLoading(); }, 3000);

    app.fitMap();
  },

  track : function(category,action,label,value) {
    if(_gaq) _gaq.push(['_trackEvent', category, action, label, value]);
  }
};

var _gaq = _gaq || [];

$(document).ready(function(){
  app.init();

  _gaq.push(['_setAccount', 'UA-27729857-5']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
});
<commit_msg>fixed autoplay timer<commit_after>var app = {
  init : function() {
    app.loading = false;
    app.current = null;
    app.autoplay = false;
    app.autoplay_timer = null;

    var opt = {
      center: new google.maps.LatLng(50.037643, 8.562409), zoom: 15,
      mapTypeId: google.maps.MapTypeId.SATELLITE,
      disableDefaultUI: true, mapTypeControl: false, navigationControl: false, disableDoubleClickZoom: false,
      draggable: false, scrollwheel: false, streetViewControl: false,
      backgroundColor: '#000000'};
    app.map = new google.maps.Map($('#map')[0],opt);

    app.static_airports = [
      new Airport(["EDDF","Frankfurt am Main International Airport","L","49.9984","8.49708","50.0458","8.58698","DE","Frankfurt-am-Main"]),
      new Airport(["OMDB","Dubai International Airport","L","25.2433","55.347","25.2665","55.3815","AE","Dubai"]),
      new Airport(["KSFO","San Francisco International Airport","L","37.6068","-122.393","37.6287","-122.357","US","San Francisco"])
    ];
    app.airports = [];
    $.get("data/data.csv", function(data) {
      var lines = data.split(/\r\n|\n/);
      for (var i=1; i<lines.length; i++)
      {
        var data = lines[i].split(',');
        if (data.length == 9)
        {
          app.airports.push(new Airport(data));
        }
      }
    });

    // setup event handlers
    google.maps.event.addListener(app.map, 'click', function(event) {
      app.track("map", "click");
      app.loadRandomAirport();
    });

    google.maps.event.addDomListener(window, 'resize', function() {
      google.maps.event.trigger(app.map, 'resize');
      app.fitMap();
    });

    $('#control-info').click(function() {
      app.track("control", "info");
      app.openInfoOverlay();
      });
    $('#control-google-maps').click(function() {
      app.openGoogleMaps();
      });
    $('#control-random').click(function() {
      app.track("control", "random");
      app.loadRandomAirport();
      });
    $('#control-play').click(function() {
      app.track("control", "play");
      app.toggleAutoPlay();
      });
    $('#info-overlay').click(function() {
      $('#info-overlay').fadeOut(1000);
      $('#controls').fadeIn(1000);
      $('#label').fadeIn(1000);
      });

    app.loadRandomAirport();
  },

  load : function(code) {
    for (var index = 0; index < app.airports.length; ++index) {
      if (app.airports[index].get_code() != code) {
        continue;
      }

      app.current = app.airports[index];
      app.updateLabel();
      app.fitMap();
      break;
    }
  },

  fitMap : function() {
    if (!app.current) {
      return;
    }
    app.map.setCenter(app.current.get_pos());
    if (app.current.get_bounds().getNorthEast().equals(app.current.get_bounds().getSouthWest())) {
      app.map.setZoom(app.current.get_zoom());
    } else {
      app.map.fitBounds(app.current.get_bounds());
    }
  },

  toggleAutoPlay : function () {
    if (app.autoplay) {
      clearInterval(app.autoplay_timer);
      app.autoplay = false;
      $('#control-play > i').removeClass('fa-pause').addClass('fa-play');
    } else {
      app.autoplay = true;
      $('#control-play > i').removeClass('fa-play').addClass('fa-pause');
      app.autoplay_timer = setInterval(function() {
        app.track("autoplay", "load");
        app.loadRandomAirport();
        }, 60 * 1000);
    }
  },

  openGoogleMaps : function() {
    app.track("control", "google-maps", "airport", app.current.get_label());
    window.open(app.current.get_google_maps_url(), '_blank');
  },

  openInfoOverlay : function() {
    $('#controls').fadeOut(1000);
    $('#label').fadeOut(1000);
    $('#info-overlay').fadeIn(1000);
    $('#info-overlay button').click(function(){
      app.closeInfoOverlay();
    });
  },

  closeInfoOverlay : function() {
    $('#info-overlay').fadeOut(1000);
    $('#controls').fadeIn(1000);
    $('#label').fadeIn(1000);
  },

  updateLabel : function() {
    $('#label').html(app.current.get_label());
    $('#location').html(app.current.get_location_name());
  },

  onStartLoading : function() {
    if (!app.loading) {
      return;
    }

    $('#control-random > i').addClass('fa-spin');
    $('#container').prepend($('#map').clone(false).attr('id','map-buffer'));
  },

  onFinishLoading : function() {
    if (!app.loading) {
      return;
    }

    var map_buffer = $('#map-buffer');
    if (map_buffer) {
      map_buffer.remove();
    }

    app.updateLabel();
    $('#control-random > i').removeClass('fa-spin');
    app.loading = false;
  },

  loadRandomAirport : function() {
    if (app.loading) {
      return;
    }
    app.loading = true;
    app.onStartLoading();

    if (app.airports.length > 0) {
      var index =  Math.floor(Math.random() * app.airports.length);
      app.current = app.airports[index];
    } else if (app.static_airports.length > 0) {
      var index =  Math.floor(Math.random() * app.static_airports.length);
      app.current = app.static_airports[index];
    } else {
      return;
    }

    google.maps.event.addListenerOnce(app.map, 'bounds_changed', function(){
      setTimeout(function(){
        $('#map-buffer').fadeOut(1000, function(){ app.onFinishLoading(); });
        }, 2000);
      });
    setTimeout(function(){ app.onFinishLoading(); }, 3000);

    app.fitMap();
  },

  track : function(category,action,label,value) {
    if(_gaq) _gaq.push(['_trackEvent', category, action, label, value]);
  }
};

var _gaq = _gaq || [];

$(document).ready(function(){
  app.init();

  _gaq.push(['_setAccount', 'UA-27729857-5']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
});
<|endoftext|>


<commit_before>var exec = require('child_process').exec;

        //initialize
        exec("cd coloradodemography.github.io && git pull && jekyll build", {}, function(error, stdout, stderr) {

            console.log('-- jekyll: building _site folder --');
            console.log('error: ' + error);
            console.log('stdout: ' + stdout);
            console.log('stderr: ' + stderr);
            return res.send("_site folder has been built.  COMPLETE.");

            // now load control panel
            exec("cd coloradodemography.github.io/_site && git clone https://github.com/ColoradoDemography/Control-Panel.git", {}, function(error, stdout, stderr) {
              console.log('-- adding Control Panel repo --');
              console.log('error: ' + error);
              console.log('stdout: ' + stdout);
              console.log('stderr: ' + stderr);
              return res.send(stdout + "\n" + stderr + "\nDONE.");
            });

        });

var appRouter = function(app) {

    app.get("/update/jekyll-build", function(req, res) {
        var command = "cd coloradodemography.github.io && git pull && jekyll build";
        exec(command, {}, function(error, stdout, stderr) {
            console.log('-- jekyll: building _site folder --');
            console.log('error: ' + error);
            console.log('stdout: ' + stdout);
            console.log('stderr: ' + stderr);
            return res.send("_site folder has been built.  COMPLETE.");
        });
    });

    app.get("/update/load_repo", function(req, res) {
        var repo = req.query.repo;
        var command = "cd coloradodemography.github.io/_site && git clone https://github.com/ColoradoDemography/" + repo + ".git";
        exec(command, {}, function(error, stdout, stderr) {
            console.log('-- updating or adding ' + repo + ' repo --');
            console.log('error: ' + error);
            console.log('stdout: ' + stdout);
            console.log('stderr: ' + stderr);
            return res.send(stdout + "\n" + stderr + "\nDONE.");
        });
    });

    app.get("/update/update_repo", function(req, res) {
        var repo = req.query.repo;
        var command = "cd coloradodemography.github.io/_site/" + repo + " && git pull";
        exec(command, {}, function(error, stdout, stderr) {
            console.log('-- updating or adding ' + repo + ' repo --');
            console.log('error: ' + error);
            console.log('stdout: ' + stdout);
            console.log('stderr: ' + stderr);
            return res.send(stdout + "\n" + stderr + "\nDONE.");
        });
    });

    app.get("/update/update_repo", function(req, res) {
        var repo = req.query.repo;
        var command = "cd coloradodemography.github.io/_site/" + repo + " && git pull";
        exec(command, {}, function(error, stdout, stderr) {
            console.log('-- updating or adding ' + repo + ' repo --');
            console.log('error: ' + error);
            console.log('stdout: ' + stdout);
            console.log('stderr: ' + stderr);
            return res.send(stdout + "\n" + stderr + "\nDONE.");
        });
    });

}

module.exports = appRouter;<commit_msg>new setup<commit_after>var exec = require('child_process').exec;

        //initialize
        exec("cd coloradodemography.github.io && git pull && jekyll build", {}, function(error, stdout, stderr) {

            console.log('-- jekyll: building _site folder --');
            console.log('error: ' + error);
            console.log('stdout: ' + stdout);
            console.log('stderr: ' + stderr);

            // now load control panel
            exec("cd coloradodemography.github.io/_site && git clone https://github.com/ColoradoDemography/Control-Panel.git", {}, function(error, stdout, stderr) {
              console.log('-- adding Control Panel repo --');
              console.log('error: ' + error);
              console.log('stdout: ' + stdout);
              console.log('stderr: ' + stderr);
            });

        });

var appRouter = function(app) {

    app.get("/update/jekyll-build", function(req, res) {
        var command = "cd coloradodemography.github.io && git pull && jekyll build";
        exec(command, {}, function(error, stdout, stderr) {
            console.log('-- jekyll: building _site folder --');
            console.log('error: ' + error);
            console.log('stdout: ' + stdout);
            console.log('stderr: ' + stderr);
            return res.send("_site folder has been built.  COMPLETE.");
        });
    });

    app.get("/update/load_repo", function(req, res) {
        var repo = req.query.repo;
        var command = "cd coloradodemography.github.io/_site && git clone https://github.com/ColoradoDemography/" + repo + ".git";
        exec(command, {}, function(error, stdout, stderr) {
            console.log('-- updating or adding ' + repo + ' repo --');
            console.log('error: ' + error);
            console.log('stdout: ' + stdout);
            console.log('stderr: ' + stderr);
            return res.send(stdout + "\n" + stderr + "\nDONE.");
        });
    });

    app.get("/update/update_repo", function(req, res) {
        var repo = req.query.repo;
        var command = "cd coloradodemography.github.io/_site/" + repo + " && git pull";
        exec(command, {}, function(error, stdout, stderr) {
            console.log('-- updating or adding ' + repo + ' repo --');
            console.log('error: ' + error);
            console.log('stdout: ' + stdout);
            console.log('stderr: ' + stderr);
            return res.send(stdout + "\n" + stderr + "\nDONE.");
        });
    });

    app.get("/update/update_repo", function(req, res) {
        var repo = req.query.repo;
        var command = "cd coloradodemography.github.io/_site/" + repo + " && git pull";
        exec(command, {}, function(error, stdout, stderr) {
            console.log('-- updating or adding ' + repo + ' repo --');
            console.log('error: ' + error);
            console.log('stdout: ' + stdout);
            console.log('stderr: ' + stderr);
            return res.send(stdout + "\n" + stderr + "\nDONE.");
        });
    });

}

module.exports = appRouter;<|endoftext|>


<commit_before>require([ 'config' ], function() {
  var baseUrl = (window.staticUrl || '') + 'frontend' + (window.jsVersion || '') + '/';
  require.config({
    baseUrl : baseUrl,
    deps : [ 'js/app' ],
    paths : {
      'js/app' : 'app'
    }
  });
});
<commit_msg>Fixed wrong merge of js/main.js<commit_after>require([ 'config' ], function() {
  var baseUrl = (window.staticUrl || '') + 'frontend' + (window.jsVersion || '') + '/';
  require.config({
    baseUrl : baseUrl,
    deps : [ 'js/app' ]
  });
});
<|endoftext|>


<commit_before>!function() {
  /*Server side config*/
  var prefix = "si"; //Usefull to support several injections per page
  var siScriptId = "service-injector"; //Id of SCRIPT element which has in src this script
  var tabTemplate = sp("Click me!");
  var windowTemplate = sp("
"+
                          "
X
"+
                          "

"+
                          "

"+
                          "
");
  var injectorStyles = sp("#%prefix%-tab {background: white; border: 1px solid black; padding: 1em}"+
                          "#%prefix%-window {background: white; border: 1px solid black; min-width: 300px; min-height: 200px}"+
                          "#%prefix%-inner {height: 100%; width: 100%; position: relative}"+
                          "#%prefix%-header {height:1.5em; background: #aaa; text-align: right; padding: 0 .5em;cursor:move}"+
                          "#%prefix%-body {border: 1px solid #aaa; bottom: 0}"+
                          "#%prefix%-iframe {border: 0}"+
                          "#%prefix%-footer {position: absolute; bottom: 0; left:0; right:0}"+
                          "#%prefix%-resizer {width: 10px; height: 10px; float:right; position: relative; right: -2px; bottom: -2px; border-right: 3px solid black; border-bottom: 3px solid black; cursor: se-resize}"+
                          "#%prefix%-shadow {background: grey; z-index: 99999}");
  var saasUrl = "http://orienteer.org";

  var clientConfig = {
    p : "bottom",
    o : "80%",
    a : 300,
    ww : "440px",
    wh : "550px",
    wt : "100px",
    wb : null,
    wl : null,
    wc : 0,
    wr : null,
    d : true,
    r : true,
    ht : false
  };

/*Dictionary object to identify orientation for offset*/
  var offsetOrientation = {
    top: "left",
    bottom: "left",
    left: "top",
    right: "top"
  }

  /*Substitute prefix*/
  function sp(str) {
    return str.replace(/%prefix%/g, prefix);
  }

  var injector = {
    state : {
      win: null,
      winPosition: {
        top: 0,
        left: 0,
        width: 0,
        height: 0
      },
      tab: null,
      tabPosition : {
        top: 0,
        left: 0,
        width: 0,
        height: 0
      },
      shadow: null,
      shadowPosition : {
        top: 0,
        left: 0,
        width: 0,
        height: 0
      },
      inited: false,
      dragState: {
        x: 0,
        y: 0,
        top: 0,
        left: 0
      },
      drag: false,
      resize: false
    },
    conf : clientConfig,
    install : function() {

      var conf = injector.conf;

      var styleElm = document.createElement("style");
      styleElm.innerHTML = injectorStyles;
      document.getElementsByTagName('head')[0].appendChild(styleElm);

      var shadowElm = document.createElement('div');
      shadowElm.setAttribute("id", sp("%prefix%-shadow"));
      shadowElm.style.position = 'fixed';
      shadowElm.style.display = 'none';
      document.body.appendChild(shadowElm);
      injector.state.shadow = shadowElm;

      var tabElm = document.createElement('div');
      tabElm.setAttribute("id", sp("%prefix%-tab"));
      tabElm.innerHTML = tabTemplate;
      tabElm.style.position = 'fixed';
      tabElm.style[conf.p] = '0px';
      tabElm.style[offsetOrientation[conf.p]] = '80%';
      document.body.appendChild(tabElm);
      injector.state.tab = tabElm;

      var winElm = document.createElement('div');
      winElm.setAttribute("id", sp("%prefix%-window"));
      winElm.innerHTML = windowTemplate;
      winElm.style.position = 'fixed';

      winElm.style.top = "100px";
      // if( typeof conf.wc == 'undefined') winElm.style.display = 'none';
      if(conf.ww) winElm.style.width = conf.ww;
      if(conf.wh) winElm.style.height = conf.wh;
      if(conf.wt) winElm.style.top = conf.wt;
      if(conf.wb) winElm.style.bottom = conf.wb;
      if(conf.wl) winElm.style.left = conf.wl;
      if(conf.wr) winElm.style.right = conf.wr;
      document.body.appendChild(winElm);
      injector.state.win = winElm;
      if( typeof conf.wc != 'undefined') {
        winElm.style.left = ((screen.width - winElm.offsetWidth+conf.wc) / 2)+"px";
      }
      injector.dumpPositions();
      winElm.style.display = 'none';
      if(conf.d || conf.r) injector.initDragAndResize();
      injector.exp();
    },
    initDragAndResize : function () {
      var conf = injector.conf;
      var drag = injector.state.dragState;
      if(conf.d) {
        var header = document.getElementById(sp("%prefix%-header"));
        if(header) {
          header.addEventListener("mousedown", function(e){
            injector.state.drag = true;
            drag.x = document.all ? window.event.clientX : e.pageX;
            drag.y = document.all ? window.event.clientY : e.pageY;
            drag.left = drag.x - injector.state.win.offsetLeft;
            drag.top = drag.y - injector.state.win.offsetTop;
            e.stopPropagation();
          });
        }
      }
      if(conf.r) {
        var resizer = document.getElementById(sp("%prefix%-resizer"));
        if(resizer) {
          resizer.addEventListener("mousedown", function(e){
            injector.state.resize = true;
            drag.x = document.all ? window.event.clientX : e.pageX;
            drag.y = document.all ? window.event.clientY : e.pageY;
            drag.left = drag.x - injector.state.win.offsetLeft;
            drag.top = drag.y - injector.state.win.offsetTop;
            drag.width = drag.x - injector.state.win.offsetWidth;
            drag.height = drag.y - injector.state.win.offsetHeight;
            e.stopPropagation();
          });
        }
      }
      document.addEventListener("mousemove", function(e){
        if(injector.state.drag) {
          drag.x = document.all ? window.event.clientX : e.pageX;
          drag.y = document.all ? window.event.clientY : e.pageY;
          injector.state.win.style.left = (drag.x - drag.left)+"px";
          injector.state.win.style.top = (drag.y - drag.top)+"px";
        }
        if(injector.state.resize) {
          drag.x = document.all ? window.event.clientX : e.pageX;
          drag.y = document.all ? window.event.clientY : e.pageY;
          injector.state.win.style.width = (drag.x - drag.width)+"px";
          injector.state.win.style.height = (drag.y - drag.height)+"px";
          injector.adjustSizes();
        }
      });
      document.addEventListener("mouseup", function(e) {
        injector.state.drag = false;
        injector.state.resize = false;
      });
    },
    exp : function () {
      window[sp("%prefix%ToggleWindow")] = injector.toggleWindow;
    },
    adjustSizes : function (){
      var win = injector.state.win;
      var header = document.getElementById(sp("%prefix%-header"));
      var body = document.getElementById(sp("%prefix%-body"));
      var iframe = document.getElementById(sp("%prefix%-iframe"));
      body.style.height = (win.offsetHeight - header.offsetHeight-4)+"px";
      iframe.style.height = (win.offsetHeight - header.offsetHeight-15)+"px";
      iframe.style.width = (win.offsetWidth-3)+"px";
    },
    animate : function(opts) {
      if(opts.duration > 0) {
        if(opts.onStart) opts.onStart();
        var start = new Date();
        var id = setInterval(function() {
          var timePassed = new Date - start;
          var progress = timePassed / (opts.duration || 1000);
          if (progress > 1) progress = 1;
          var delta = (opts.delta || function(p) {return p;})(progress);
          opts.step(delta);
          if (progress == 1) {
            clearInterval(id);
            if(opts.onFinish) opts.onFinish();
          }
        }, opts.delay || 10);
      } else {
        if(opts.onStart) opts.onStart();
        if(opts.onFinish) opts.onFinish();
      }
    },
    shadowStep : function(delta) {
      var state = injector.state;
      var wp = state.winPosition;
      var tp = state.tabPosition;
      var sp = state.shadowPosition;
      sp.left = (wp.left-tp.left)*delta + tp.left;
      sp.top = (wp.top-tp.top)*delta + tp.top;
      sp.width = (wp.width-tp.width)*delta + tp.width;
      sp.height = (wp.height-tp.height)*delta + tp.height;
      var s = state.shadow;
      s.style.left = sp.left+"px";
      s.style.top = sp.top+"px";
      s.style.width = sp.width+"px";
      s.style.height = sp.height+"px";
    },
    initIframe : function () {
      var iframe = document.getElementById(sp("%prefix%-iframe"));
      iframe.src = saasUrl;
      injector.state.inited = true;
    },
    dumpPosition : function (elm, pos) {
      pos.left = elm.offsetLeft;
      pos.top = elm.offsetTop;
      pos.width = elm.offsetWidth;
      pos.height = elm.offsetHeight;
    },
    dumpPositions : function () {
      if(injector.state.win.style.display!='none')injector.dumpPosition(injector.state.win, injector.state.winPosition);
      if(injector.state.tab.style.display!='none')injector.dumpPosition(injector.state.tab, injector.state.tabPosition);
    },
    expandWindow : function () {
      injector.animate({
        duration: injector.conf.a,
        step: injector.shadowStep,
        onStart: function() {
          injector.dumpPositions();
          if(clientConfig.ht) injector.state.tab.style.display = 'none';
          injector.state.shadow.style.display='block';
          if(!injector.state.inited) {
            injector.initIframe();
          }
        },
        onFinish : function() {
          injector.state.shadow.style.display='none';
          injector.state.win.style.display = 'block';
          injector.adjustSizes();
          injector.dumpPositions();
        }
      });
      return false;
    },
    collapseWindow : function () {
      injector.animate({
        duration: injector.conf.a,
        step: injector.shadowStep,
        delta: function(p) {return 1-p},
        onStart: function() {
          injector.dumpPositions();
          injector.state.shadow.style.display='block';
          injector.state.win.style.display = 'none';
        },
        onFinish : function() {
          injector.state.shadow.style.display='none';
          injector.state.tab.style.display = 'block';
          injector.dumpPositions();
        }
      });
      return false;
    },
    toggleWindow : function () {
      if(injector.state.win.style.display == 'none') {
        return injector.expandWindow();
      } else {
        return injector.collapseWindow();
      }
    }
  };

  injector.install();
}();
<commit_msg>Prevent crossing boundaries and selection during d&d<commit_after>!function() {
  /*Server side config*/
  var prefix = "si"; //Usefull to support several injections per page
  var siScriptId = "service-injector"; //Id of SCRIPT element which has in src this script
  var tabTemplate = sp("Click me!");
  var windowTemplate = sp("
"+
                          "
X
"+
                          "

"+
                          "

"+
                          "
");
  var injectorStyles = sp("#%prefix%-tab {background: white; border: 1px solid black; padding: 1em}"+
                          "#%prefix%-window {background: white; border: 1px solid black; min-width: 300px; min-height: 200px}"+
                          "#%prefix%-inner {height: 100%; width: 100%; position: relative}"+
                          "#%prefix%-header {height:1.5em; background: #aaa; text-align: right; padding: 0 .5em;cursor:move}"+
                          "#%prefix%-body {border: 1px solid #aaa; bottom: 0}"+
                          "#%prefix%-iframe {border: 0}"+
                          "#%prefix%-footer {position: absolute; bottom: 0; left:0; right:0}"+
                          "#%prefix%-resizer {width: 10px; height: 10px; float:right; position: relative; right: -2px; bottom: -2px; border-right: 3px solid black; border-bottom: 3px solid black; cursor: se-resize}"+
                          "#%prefix%-shadow {background: grey; z-index: 99999}");
  var saasUrl = "http://orienteer.org";

  var clientConfig = {
    p : "bottom",
    o : "80%",
    a : 300,
    ww : "440px",
    wh : "550px",
    wt : "100px",
    wb : null,
    wl : null,
    wc : 0,
    wr : null,
    d : true,
    r : true,
    ht : false
  };

/*Dictionary object to identify orientation for offset*/
  var offsetOrientation = {
    top: "left",
    bottom: "left",
    left: "top",
    right: "top"
  }

  /*Substitute prefix*/
  function sp(str) {
    return str.replace(/%prefix%/g, prefix);
  }

  var injector = {
    state : {
      win: null,
      winPosition: {
        top: 0,
        left: 0,
        width: 0,
        height: 0
      },
      tab: null,
      tabPosition : {
        top: 0,
        left: 0,
        width: 0,
        height: 0
      },
      shadow: null,
      shadowPosition : {
        top: 0,
        left: 0,
        width: 0,
        height: 0
      },
      inited: false,
      dragState: {
        x: 0,
        y: 0,
        top: 0,
        left: 0
      },
      drag: false,
      resize: false
    },
    conf : clientConfig,
    install : function() {

      var conf = injector.conf;

      var styleElm = document.createElement("style");
      styleElm.innerHTML = injectorStyles;
      document.getElementsByTagName('head')[0].appendChild(styleElm);

      var shadowElm = document.createElement('div');
      shadowElm.setAttribute("id", sp("%prefix%-shadow"));
      shadowElm.style.position = 'fixed';
      shadowElm.style.display = 'none';
      document.body.appendChild(shadowElm);
      injector.state.shadow = shadowElm;

      var tabElm = document.createElement('div');
      tabElm.setAttribute("id", sp("%prefix%-tab"));
      tabElm.innerHTML = tabTemplate;
      tabElm.style.position = 'fixed';
      tabElm.style[conf.p] = '0px';
      tabElm.style[offsetOrientation[conf.p]] = '80%';
      document.body.appendChild(tabElm);
      injector.state.tab = tabElm;

      var winElm = document.createElement('div');
      winElm.setAttribute("id", sp("%prefix%-window"));
      winElm.innerHTML = windowTemplate;
      winElm.style.position = 'fixed';

      winElm.style.top = "100px";
      // if( typeof conf.wc == 'undefined') winElm.style.display = 'none';
      if(conf.ww) winElm.style.width = conf.ww;
      if(conf.wh) winElm.style.height = conf.wh;
      if(conf.wt) winElm.style.top = conf.wt;
      if(conf.wb) winElm.style.bottom = conf.wb;
      if(conf.wl) winElm.style.left = conf.wl;
      if(conf.wr) winElm.style.right = conf.wr;
      document.body.appendChild(winElm);
      injector.state.win = winElm;
      if( typeof conf.wc != 'undefined') {
        winElm.style.left = ((screen.width - winElm.offsetWidth+conf.wc) / 2)+"px";
      }
      injector.savePositions();
      winElm.style.display = 'none';
      if(conf.d || conf.r) injector.initDragAndResize();
      injector.exp();
    },
    initDragAndResize : function () {
      var conf = injector.conf;
      var drag = injector.state.dragState;
      if(conf.d) {
        var header = document.getElementById(sp("%prefix%-header"));
        if(header) {
          header.addEventListener("mousedown", function(e){
            injector.state.drag = true;
            drag.x = document.all ? window.event.clientX : e.pageX;
            drag.y = document.all ? window.event.clientY : e.pageY;
            drag.left = drag.x - injector.state.win.offsetLeft;
            drag.top = drag.y - injector.state.win.offsetTop;
            e.stopPropagation();
            e.preventDefault();
          });
        }
      }
      if(conf.r) {
        var resizer = document.getElementById(sp("%prefix%-resizer"));
        if(resizer) {
          resizer.addEventListener("mousedown", function(e){
            injector.state.resize = true;
            drag.x = document.all ? window.event.clientX : e.pageX;
            drag.y = document.all ? window.event.clientY : e.pageY;
            drag.left = drag.x - injector.state.win.offsetLeft;
            drag.top = drag.y - injector.state.win.offsetTop;
            drag.width = drag.x - injector.state.win.offsetWidth;
            drag.height = drag.y - injector.state.win.offsetHeight;
            e.stopPropagation();
            e.preventDefault();
          });
        }
      }
      document.addEventListener("mousemove", function(e){
        if(injector.state.drag) {
          drag.x = document.all ? window.event.clientX : e.pageX;
          drag.y = document.all ? window.event.clientY : e.pageY;
          injector.state.winPosition.left = drag.x - drag.left;
          injector.state.winPosition.top = drag.y - drag.top;
          injector.restorePosition(injector.state.win, injector.state.winPosition);
          e.stopPropagation();
          e.preventDefault();
        }
        if(injector.state.resize) {
          drag.x = document.all ? window.event.clientX : e.pageX;
          drag.y = document.all ? window.event.clientY : e.pageY;
          injector.state.winPosition.width = drag.x - drag.width;
          injector.state.winPosition.height = drag.y - drag.height;
          injector.restorePosition(injector.state.win, injector.state.winPosition);
          injector.adjustSizes();
          e.stopPropagation();
          e.preventDefault();
        }
      });
      document.addEventListener("mouseup", function(e) {
        if(injector.state.drag || injector.state.resize) {
          injector.state.drag = false;
          injector.state.resize = false;
          injector.savePositions();
          e.stopPropagation();
          e.preventDefault();
        }
      });
    },
    exp : function () {
      window[sp("%prefix%ToggleWindow")] = injector.toggleWindow;
    },
    adjustSizes : function (){
      var win = injector.state.win;
      var header = document.getElementById(sp("%prefix%-header"));
      var body = document.getElementById(sp("%prefix%-body"));
      var iframe = document.getElementById(sp("%prefix%-iframe"));
      body.style.height = (win.offsetHeight - header.offsetHeight-4)+"px";
      iframe.style.height = (win.offsetHeight - header.offsetHeight-15)+"px";
      iframe.style.width = (win.offsetWidth-3)+"px";
    },
    animate : function(opts) {
      if(opts.duration > 0) {
        if(opts.onStart) opts.onStart();
        var start = new Date();
        var id = setInterval(function() {
          var timePassed = new Date - start;
          var progress = timePassed / (opts.duration || 1000);
          if (progress > 1) progress = 1;
          var delta = (opts.delta || function(p) {return p;})(progress);
          opts.step(delta);
          if (progress == 1) {
            clearInterval(id);
            if(opts.onFinish) opts.onFinish();
          }
        }, opts.delay || 10);
      } else {
        if(opts.onStart) opts.onStart();
        if(opts.onFinish) opts.onFinish();
      }
    },
    shadowStep : function(delta) {
      var state = injector.state;
      var wp = state.winPosition;
      var tp = state.tabPosition;
      var sp = state.shadowPosition;
      sp.left = (wp.left-tp.left)*delta + tp.left;
      sp.top = (wp.top-tp.top)*delta + tp.top;
      sp.width = (wp.width-tp.width)*delta + tp.width;
      sp.height = (wp.height-tp.height)*delta + tp.height;
      var s = state.shadow;
      s.style.left = sp.left+"px";
      s.style.top = sp.top+"px";
      s.style.width = sp.width+"px";
      s.style.height = sp.height+"px";
      if(s.style.display!='block') s.style.display = 'block';
    },
    initIframe : function () {
      var iframe = document.getElementById(sp("%prefix%-iframe"));
      iframe.src = saasUrl;
      injector.state.inited = true;
    },
    restorePosition : function (elm, pos) {
      if(pos.left < 0 ) pos.left = 0;
      if(pos.top < 0 ) pos.top = 0;
      if(pos.left + pos.width > screen.availWidth) {
        pos.left = screen.availWidth - pos.width;
      }
      if(pos.top + pos.height > screen.availHeight) {
        pos.top = screen.availHeight - pos.height;
      }
      elm.style.left = pos.left + "px";
      elm.style.top = pos.top + "px";
      elm.style.width = pos.width + "px";
      elm.style.height = pos.height + "px";
    },
    savePosition : function (elm, pos) {
      pos.left = elm.offsetLeft;
      pos.top = elm.offsetTop;
      pos.width = elm.offsetWidth;
      pos.height = elm.offsetHeight;
    },
    savePositions : function () {
      if(injector.state.win.style.display!='none')injector.savePosition(injector.state.win, injector.state.winPosition);
      if(injector.state.tab.style.display!='none')injector.savePosition(injector.state.tab, injector.state.tabPosition);
    },
    expandWindow : function () {
      injector.animate({
        duration: injector.conf.a,
        step: injector.shadowStep,
        onStart: function() {
          injector.savePositions();
          if(clientConfig.ht) injector.state.tab.style.display = 'none';
        },
        onFinish : function() {
          if(!injector.state.inited) {
            injector.initIframe();
          }
          injector.state.shadow.style.display='none';
          injector.state.win.style.display = 'block';
          injector.adjustSizes();
          injector.savePositions();
        }
      });
      return false;
    },
    collapseWindow : function () {
      injector.animate({
        duration: injector.conf.a,
        step: injector.shadowStep,
        delta: function(p) {return 1-p},
        onStart: function() {
          injector.savePositions();
          injector.state.win.style.display = 'none';
        },
        onFinish : function() {
          injector.state.shadow.style.display='none';
          injector.state.tab.style.display = 'block';
          injector.savePositions();
        }
      });
      return false;
    },
    toggleWindow : function () {
      if(injector.state.win.style.display == 'none') {
        return injector.expandWindow();
      } else {
        return injector.collapseWindow();
      }
    }
  };

  injector.install();
}();
<|endoftext|>


<commit_before>/*
* ADR Reporting
* Copyright (C) 2017 Divay Prakash
* GNU Affero General Public License 3.0 (https://github.com/divayprakash/adr/blob/master/LICENSE)
*/
$(document).ready(function(){
  $('.button-collapse').sideNav();
  var helpOpen = false;
  $('#help-fab').click(function(e) {
    if (helpOpen) {
      $('#help-tap-target').tapTarget('close');
      helpOpen = false;
    }
    else {
      $('#help-tap-target').tapTarget('open');
      helpOpen = true;
    }
  });
  $('.chips').material_chip();
  $('.datepicker').pickadate({
    format: 'dd/mm/yyyy',
    selectMonths: true
  });
  $('.datepicker-year').pickadate({
    format: 'dd/mm/yyyy',
    selectMonths: true,
    selectYears: 7
  });
  $('#medication-add').modal();
  enableSpecFieldOnRadio('stop','#stop-reduced');
  enableSpecFieldOnRadio('reintro','#reintro-reduced');
});

function enableSpecFieldOnRadio(radioId, fieldSelector) {
  $('input[type=radio][name=' + radioId + ']').on('change', function() {
    switch($(this).val()) {
      case 'yes':
        $(fieldSelector).prop('disabled', false);
        break;
      case 'no':
      case 'unknown':
      case 'na':
        $(fieldSelector).val("");
        $(fieldSelector).removeClass('valid');
        $(fieldSelector).removeClass('invalid');
        $(fieldSelector).prop('disabled', true);
        break;
    }
  });
}

var medicationCount = 0;
function medicationAdd() {
  var name = $('#medication-name').val();
  var manufacturer = $('#manufacturer').val();
  var batch = $('#batch').val();
  var expiry = $('#expiry').pickadate().pickadate('picker').get();
  var dose = $('#dose').val();
  var route = $("input[type='radio'][name='route']:checked").val();
  var frequency = $('#freq').val();
  var therapyStart = $('#therapy-start').pickadate().pickadate('picker').get();
  var therapyEnd = $('#therapy-end').pickadate().pickadate('picker').get();
  var duration = $('#duration').val();
  var reason = $('#reason').val();
  var stop = $("input[type='radio'][name='stop']:checked").val();
  var stopReduced = 0;
  if (stop == "yes") stopReduced = $('#stop-reduced').val();
  var reintro = $("input[type='radio'][name='reintro']:checked").val();
  var reintroReduced = 0;
  if (reintro == "yes")  reintroReduced = $('reintro-reduced').val();
  formReset();
  $('#medication-add').modal('close');
  Materialize.toast('Medication added!', 4000, 'rounded');
  var divToAdd = "

"+ name +"
"+ manufacturer + " / " + expiry + "

<button class='waves-effect waves-light btn'>mode_editEdit</button><button class='waves-effect waves-light btn'>deleteDelete</button>

";
  $('#insert').before(divToAdd);
}

function formReset(){
  $('#medication-form').each(function(){
      this.reset();
  });
  $('#medication-add').scrollTop(0);
}
<commit_msg>WIP: Style medication div added on form submit<commit_after>/*
* ADR Reporting
* Copyright (C) 2017 Divay Prakash
* GNU Affero General Public License 3.0 (https://github.com/divayprakash/adr/blob/master/LICENSE)
*/
$(document).ready(function(){
  $('.button-collapse').sideNav();
  var helpOpen = false;
  $('#help-fab').click(function(e) {
    if (helpOpen) {
      $('#help-tap-target').tapTarget('close');
      helpOpen = false;
    }
    else {
      $('#help-tap-target').tapTarget('open');
      helpOpen = true;
    }
  });
  $('.chips').material_chip();
  $('.datepicker').pickadate({
    format: 'dd/mm/yyyy',
    selectMonths: true
  });
  $('.datepicker-year').pickadate({
    format: 'dd/mm/yyyy',
    selectMonths: true,
    selectYears: 7
  });
  $('#medication-add').modal();
  enableSpecFieldOnRadio('stop','#stop-reduced');
  enableSpecFieldOnRadio('reintro','#reintro-reduced');
});

function enableSpecFieldOnRadio(radioId, fieldSelector) {
  $('input[type=radio][name=' + radioId + ']').on('change', function() {
    switch($(this).val()) {
      case 'yes':
        $(fieldSelector).prop('disabled', false);
        break;
      case 'no':
      case 'unknown':
      case 'na':
        $(fieldSelector).val("");
        $(fieldSelector).removeClass('valid');
        $(fieldSelector).removeClass('invalid');
        $(fieldSelector).prop('disabled', true);
        break;
    }
  });
}

var medicationCount = 0;
function medicationAdd() {
  var name = $('#medication-name').val();
  var manufacturer = $('#manufacturer').val();
  var batch = $('#batch').val();
  var expiry = $('#expiry').pickadate().pickadate('picker').get();
  var dose = $('#dose').val();
  var route = $("input[type='radio'][name='route']:checked").val();
  var frequency = $('#freq').val();
  var therapyStart = $('#therapy-start').pickadate().pickadate('picker').get();
  var therapyEnd = $('#therapy-end').pickadate().pickadate('picker').get();
  var duration = $('#duration').val();
  var reason = $('#reason').val();
  var stop = $("input[type='radio'][name='stop']:checked").val();
  var stopReduced = 0;
  if (stop == "yes") stopReduced = $('#stop-reduced').val();
  var reintro = $("input[type='radio'][name='reintro']:checked").val();
  var reintroReduced = 0;
  if (reintro == "yes")  reintroReduced = $('reintro-reduced').val();
  formReset();
  $('#medication-add').modal('close');
  Materialize.toast('Medication added!', 4000, 'rounded');
  var divToAdd = "

"+ name +"
"+ manufacturer + "
" + expiry + "

<button class='waves-effect waves-light btn'>mode_editEdit</button><button class='waves-effect waves-light btn'>deleteDelete</button>

";
  $('#insert').before(divToAdd);
}

function formReset(){
  $('#medication-form').each(function(){
      this.reset();
  });
  $('#medication-add').scrollTop(0);
}
<|endoftext|>


<commit_before>define(function(require) {
    var init = require('init');

    var draw = require('./draw');
    var fill = require('./fill');
    var selectArea = require('./selectArea');
    var copy = require('./copy');
    var paste = require('./paste');
    var loadImage = require('./loadImage');
    var colors = require('./color');

    var canvas = init.getCanvas();
    var context = init.getContext();

    // canvasに対する操作
    // draw関係
    canvas.addEventListener('mousedown', function() {
        draw.mouseDown();
    });
    canvas.addEventListener('mousemove', function(e) {
        draw.mouseMove(e);
    });
    canvas.addEventListener('mouseup', function() {
        draw.mouseUp();
    });

    document.getElementById('draw').addEventListener('click', function(){
    });

    document.getElementById('erase').addEventListener('click', function(){

    });
    document.getElementById('fill').addEventListener('click', function(){
        fill.call();
    });
    document.getElementById('select-area').addEventListener('click', function(){
        selectArea.call();
    });
    document.getElementById('copy').addEventListener('click', function(){
        copy.call();
    });
    document.getElementById('paste').addEventListener('click', function(){
        paste.call();
    });
    document.getElementById('load-image').addEventListener('click', function(){
        loadImage.call();
    });
});
<commit_msg>edit main.js<commit_after>define(function(require) {
    var init = require('init');

    var draw = require('./draw');
    var fill = require('./fill');
    var selectArea = require('./selectArea');
    var copy = require('./copy');
    var paste = require('./paste');
    var loadImage = require('./loadImage');
    var colors = document.getElementById('colors').childNodes;
    for (var i = 0, color; color = colors[i]; i++) {
        if (color.nodeName.toLowerCase() != 'div') continue;
        color.addEventListener('click', function (e) {
            var style = e.target.getAttribute('style');
            var color = style.match(/background:(#......)/)[1];
            context.strokeStyle = color;
            context.fillStyle = color;
        },false);
    };

    var canvas = init.getCanvas();
    var context = init.getContext();

    // canvasに対する操作
    // draw関係
    canvas.addEventListener('mousedown', function() {
        draw.mouseDown();
    });
    canvas.addEventListener('mousemove', function(e) {
        draw.mouseMove(e);
    });
    canvas.addEventListener('mouseup', function() {
        draw.mouseUp();
    });

    document.getElementById('draw').addEventListener('click', function(){
    });

    document.getElementById('erase').addEventListener('click', function(){

    });
    document.getElementById('fill').addEventListener('click', function(){
        fill.call();
    });
    document.getElementById('select-area').addEventListener('click', function(){
        selectArea.call();
    });
    document.getElementById('copy').addEventListener('click', function(){
        copy.call();
    });
    document.getElementById('paste').addEventListener('click', function(){
        paste.call();
    });
    document.getElementById('load-image').addEventListener('click', function(){
        loadImage.call();
    });
});
<|endoftext|>


<commit_before>var hatchet = require('hatchet');
var url = process.env.SIGNUP;

module.exports = function(transaction) {
  hatchet.send("sign_up_for_mofo_newsletter", {
    url: url,
    json: true,
    form: {
      format: 'html',
      lang: transaction.locale,
      newsletters: 'mozilla-foundation',
      trigger_welcome: 'N',
      source_url: 'https://donate.mozilla.org/',
      email: transaction.email,
      country: transaction.country
    }
  });
};
<commit_msg>change hatchet event type for ExactTarget signup<commit_after>var hatchet = require('hatchet');
var url = process.env.SIGNUP;

module.exports = function(transaction) {
  hatchet.send("send_post_request", {
    url: url,
    json: true,
    form: {
      format: 'html',
      lang: transaction.locale,
      newsletters: 'mozilla-foundation',
      trigger_welcome: 'N',
      source_url: 'https://donate.mozilla.org/',
      email: transaction.email,
      country: transaction.country
    }
  });
};
<|endoftext|>


<commit_before>var _ = require("lodash");

var autocomplete = module.exports = {};

autocomplete.empty = {
  words: [],
  glob: false,
  files: false,
  directories: false
};

autocomplete.defaultCompleter = function() {
  return autocomplete.empty;
};

autocomplete.words = function(words) {
  var result = _.clone(autocomplete.empty);
  result.words = words;
  return result;
}

autocomplete.mappend = function(result1, result2) {
  return {
    words: result1.words.concat(result2.words),
    glob: result2.glob, // ToDo document
    files: result1.files || result2.files,
    directories: result1.directories || result2.directories
  };
};

autocomplete.mconcat = function(results) {
  return _.reduce(results, autocomplete.mappend, _.clone(autocomplete.empty));
};

autocomplete.compgen = function(results) {
  var wordlist = "-W $'" + results.words.join('\n') + "'";
  var globpat = results.glob ? 'compgen -G "' + results.glob + '"' : '';
  var files = results.files && !results.glob ? 'compgen -f' : '';
  var directories = results.directories && !results.files && !results.glob ? 'compgen -d' : '';

  return 'compgen ' + wordlist;
};
<commit_msg>helpers for autocomplete results<commit_after>var _ = require("lodash");

var autocomplete = module.exports = {};

autocomplete.empty = {
  words: [],
  glob: false,
  files: false,
  directories: false
};

autocomplete.defaultCompleter = function() {
  return autocomplete.empty;
};

autocomplete.words = function(words) {
  var result = _.clone(autocomplete.empty);
  result.words = words;
  return result;
}

autocomplete.glob = function(glob) {
  return {
    words: [],
    glob: glob,
    files: false,
    directories: false
  };
};

autocomplete.files = {
  words: [],
  glob: false,
  files: true,
  directories: false
}

autocomplete.directories = {
  words: [],
  glob: false,
  files: false,
  directories: true
}

autocomplete.mappend = function(result1, result2) {
  return {
    words: result1.words.concat(result2.words),
    glob: result2.glob, // ToDo document
    files: result1.files || result2.files,
    directories: result1.directories || result2.directories
  };
};

autocomplete.mconcat = function(results) {
  return _.reduce(results, autocomplete.mappend, _.clone(autocomplete.empty));
};

autocomplete.compgen = function(results) {
  var wordlist = "-W $'" + results.words.join('\n') + "'";
  var globpat = results.glob ? 'compgen -G "' + results.glob + '"' : '';
  var files = results.files && !results.glob ? 'compgen -f' : '';
  var directories = results.directories && !results.files && !results.glob ? 'compgen -d' : '';

  return 'compgen ' + wordlist;
};
<|endoftext|>


<commit_before>/* *****************************************************************************
 * Caleydo - Visualization for Molecular Biology - http://caleydo.org
 * Copyright (c) The Caleydo Team. All rights reserved.
 * Licensed under the new BSD license, available at http://caleydo.org/license
 **************************************************************************** */

//register all extensions in the registry following the given pattern
module.exports = function(registry) {
  //registry.push('extension-type', 'extension-id', function() { return System.import('./src/extension_impl'); }, {});
<%- extensions.map((d) => `  registry.push('${d.type}', '${d.id}', function() { return System.import('./src/${d.module}'); }, ${JSON.stringify(d.extras, null, ' ').replace(/"/g,'\'')});`).join(',\n') %>
};

<commit_msg>fix extension point generation<commit_after>/* *****************************************************************************
 * Caleydo - Visualization for Molecular Biology - http://caleydo.org
 * Copyright (c) The Caleydo Team. All rights reserved.
 * Licensed under the new BSD license, available at http://caleydo.org/license
 **************************************************************************** */

//register all extensions in the registry following the given pattern
module.exports = function(registry) {
  //registry.push('extension-type', 'extension-id', function() { return System.import('./src/extension_impl'); }, {});
<%- extensions.map((d) => `  registry.push('${d.type}', '${d.id}', function() { return System.import('./src/${d.module}'); }, ${JSON.stringify(d.extras, null, ' ').replace(/"/g,'\'')});`).join('\n\n') %>
};

<|endoftext|>


<commit_before>/**
 * Superstore synchronous library
 *
 * @author Matt Andrews <matthew.andrews@ft.com>
 * @copyright The Financial Times [All Rights Reserved]
 */

var keys = {};
var store = {};
var persist = true;

// Watch for changes from other tabs
window.addEventListener("storage", function(e) {
  if(keys[e.key]) {
    keys[e.key] = true;
    store[e.key] = JSON.parse(e.newValue);
  }
});

exports.get = function(key) {
  if (!keys[key] && persist) {
    var data = localStorage[key];

    // Slightly weird hack because JSON.parse of an undefined value throws
    // a weird exception "SyntaxError: Unexpected token u"
    if (data) data = JSON.parse(data);
    store[key] = data;
    keys[key] = true;
  }
  return store[key];
};

exports.set = function(key, value) {
  try {
    localStorage[key] = JSON.stringify(value);
  } catch(err) {

    // Known iOS Private Browsing Bug - fall back to non-persistent storage
    if (err.code === 22) {
      persist = false;
    } else {
      throw err;
    }
  }
  store[key] = value;
  keys[key] = true;
};

exports.unset = function(key) {
  delete store[key];
  delete keys[key];
  localStorage.removeItem(key);
};

/**
 * clear localstorage
 * @param clearPrefix will clear keys starting with `clearPrefix`
 * #clear(true) and #clear() clear cache and persistent layer, #clear(false) only clears cache
 *
 */
exports.clear = function(clearPrefix) {
  if(!clearPrefix) {
    if (persist) {
      localStorage.clear();
    }
    store = {};
    keys = {};
    return;
  }

  var clearKeyRegex = new RegExp("^" + clearPrefix);
  for (var key in keys) {
    if (key.match(clearKeyRegex)) {
      this.unset(key);
    }
  }
};
<commit_msg>Only use localStorage if `persist` is truthy<commit_after>/**
 * Superstore synchronous library
 *
 * @author Matt Andrews <matthew.andrews@ft.com>
 * @copyright The Financial Times [All Rights Reserved]
 */

var keys = {};
var store = {};
var persist = true;

// Watch for changes from other tabs
window.addEventListener("storage", function(e) {
  if(keys[e.key]) {
    keys[e.key] = true;
    store[e.key] = JSON.parse(e.newValue);
  }
});

exports.get = function(key) {
  if (!keys[key] && persist) {
    var data = localStorage[key];

    // Slightly weird hack because JSON.parse of an undefined value throws
    // a weird exception "SyntaxError: Unexpected token u"
    if (data) data = JSON.parse(data);
    store[key] = data;
    keys[key] = true;
  }
  return store[key];
};

exports.set = function(key, value) {
  if (persist) {
    try {
      localStorage[key] = JSON.stringify(value);
    } catch(err) {

      // Known iOS Private Browsing Bug - fall back to non-persistent storage
      if (err.code === 22) {
        persist = false;
      } else {
        throw err;
      }
    }
  }

  store[key] = value;
  keys[key] = true;
};

exports.unset = function(key) {
  delete store[key];
  delete keys[key];
  localStorage.removeItem(key);
};

/**
 * clear localstorage
 * @param clearPrefix will clear keys starting with `clearPrefix`
 * #clear(true) and #clear() clear cache and persistent layer, #clear(false) only clears cache
 *
 */
exports.clear = function(clearPrefix) {
  if(!clearPrefix) {
    if (persist) {
      localStorage.clear();
    }
    store = {};
    keys = {};
    return;
  }

  var clearKeyRegex = new RegExp("^" + clearPrefix);
  for (var key in keys) {
    if (key.match(clearKeyRegex)) {
      this.unset(key);
    }
  }
};
<|endoftext|>


<commit_before>'use strict';

var async = require('async');
var Chain = require('./chain');
var Block = require('./block');
var DB = require('./db');
var chainlib = require('chainlib');
var fs = require('fs');
var BaseNode = chainlib.Node;
var util = require('util');
var mkdirp = require('mkdirp');
var log = chainlib.log;
var bitcore = require('bitcore');
var Networks = bitcore.Networks;
var _ = bitcore.deps._;
var $ = bitcore.util.preconditions;
var genesis = require('./genesis.json');
var daemon = require('./daemon');
var Bus = require('./bus');

function Node(config) {
  BaseNode.call(this, config);
  this.testnet = config.testnet;
}

util.inherits(Node, BaseNode);

Node.prototype.openBus = function() {
  return new Bus({db: this.db});
};

Node.prototype.getAllAPIMethods = function() {
  var methods = this.db.getAPIMethods();
  for (var i = 0; i < this.db.modules.length; i++) {
    var mod = this.db.modules[i];
    methods = methods.concat(mod.getAPIMethods());
  }
  return methods;
};

Node.prototype.getAllPublishEvents = function() {
  var events = [];
  for (var i = 0; i < this.db.modules.length; i++) {
    var mod = this.db.modules[i];
    events = events.concat(mod.getPublishEvents());
  }
  return events;
};

Node.prototype._loadConfiguration = function(config) {
  var self = this;
  this._loadBitcoinConf(config);
  this._loadBitcoind(config);
  Node.super_.prototype._loadConfiguration.call(self, config);
};

Node.DEFAULT_DAEMON_CONFIG = 'whitelist=127.0.0.1\n' + 'txindex=1\n';

Node.prototype._loadBitcoinConf = function(config) {
  $.checkArgument(config.datadir, 'Please specify "datadir" in configuration options');
  var datadir = config.datadir.replace(/^~/, process.env.HOME);
  var configPath = datadir + '/bitcoin.conf';
  this.bitcoinConfiguration = {};

  if (!fs.existsSync(datadir)) {
    mkdirp.sync(datadir);
  }

  if (!fs.existsSync(configPath)) {
    fs.writeFileSync(configPath, Node.DEFAULT_DAEMON_CONFIG);
  }

  var file = fs.readFileSync(configPath);
  var unparsed = file.toString().split('\n');
  for(var i = 0; i < unparsed.length; i++) {
    var line = unparsed[i];
    if (!line.match(/^\#/) && line.match(/\=/)) {
      var option = line.split('=');
      var value;
      if (!Number.isNaN(Number(option[1]))) {
        value = Number(option[1]);
      } else {
        value = option[1];
      }
      this.bitcoinConfiguration[option[0]] = value;
    }
  }

};

Node.prototype._loadBitcoind = function(config) {
  var bitcoindConfig = {};
  bitcoindConfig.datadir = config.datadir;
  bitcoindConfig.network = config.network;

  // start the bitcoind daemon
  this.bitcoind = daemon(bitcoindConfig);

};

/**
 * This function will find the common ancestor between the current chain and a forked block,
 * by moving backwards from the forked block until it meets the current chain.
 * @param {Block} block - The new tip that forks the current chain.
 * @param {Function} done - A callback function that is called when complete.
 */
Node.prototype._syncBitcoindAncestor = function(block, done) {

  var self = this;

  // The current chain of hashes will likely already be available in a cache.
  self.chain.getHashes(self.chain.tip.hash, function(err, currentHashes) {
    if (err) {
      done(err);
    }

    // Create a hash map for faster lookups
    var currentHashesMap = {};
    var length = currentHashes.length;
    for (var i = 0; i < length; i++) {
      currentHashesMap[currentHashes[i]] = true;
    }

    var ancestorHash = block.prevHash;

    // We only need to go back until we meet the main chain for the forked block
    // and thus don't need to find the entire chain of hashes.

    async.whilst(function() {
      // Wait until the previous hash is in the current chain
      return ancestorHash && !currentHashesMap[ancestorHash];
    }, function(next) {
      self.bitcoind.getBlockIndex(ancestorHash, function(err, blockIndex) {
        if (err) {
          return next(err);
        }
        ancestorHash = blockIndex.prevHash;
        next();
      });
    }, function(err) {

      // Hash map is no-longer needed, quickly let
      // scavenging garbage collection know to cleanup
      currentHashesMap = null;

      if (err) {
        return done(err);
      } else if (!ancestorHash) {
        return done(new Error('Unknown common ancestor.'));
      }

      done(null, ancestorHash);
    });
  });
};

/**
 * This function will attempt to rewind the chain to the common ancestor
 * between the current chain and a forked block.
 * @param {Block} block - The new tip that forks the current chain.
 * @param {Function} done - A callback function that is called when complete.
 */
Node.prototype._syncBitcoindRewind = function(block, done) {

  var self = this;

  self._syncBitcoindAncestor(block, function(err, ancestorHash) {

    // Rewind the chain to the common ancestor
    async.whilst(
      function() {
        // Wait until the tip equals the ancestor hash
        return self.chain.tip.hash !== ancestorHash;
      },
      function(removeDone) {

        var tip = self.chain.tip;

        self.getBlock(tip.prevHash, function(err, previousTip) {
          if (err) {
            removeDone(err);
          }

          // Undo the related indexes for this block
          self.db._onChainRemoveBlock(tip, function(err) {
            if (err) {
              return removeDone(err);
            }

            // Set the new tip
            delete self.chain.tip.__transactions;
            previousTip.__height = self.chain.tip.__height - 1;
            self.chain.tip = previousTip;
            self.chain.saveMetadata();
            self.chain.emit('removeblock', tip);
            removeDone();
          });

        });

      }, done
    );
  });
};

/**
 * This function will synchronize additional indexes for the chain based on
 * the current active chain in the bitcoin daemon. In the event that there is
 * a reorganization in the daemon, the chain will rewind to the last common
 * ancestor and then resume syncing.
 */
Node.prototype._syncBitcoind = function() {
  var self = this;

  if (self.bitcoindSyncing) {
    return;
  }

  if (!self.chain.tip) {
    return;
  }

  self.bitcoindSyncing = true;

  log.info('Starting Bitcoind Sync');

  var height;

  async.whilst(function() {
    height = self.chain.tip.__height;
    return height < self.bitcoindHeight;
  }, function(done) {
    self.bitcoind.getBlock(height + 1, function(err, blockBuffer) {
      if (err) {
        return done(err);
      }
      var block = self.Block.fromBuffer(blockBuffer);
      if (block.prevHash === self.chain.tip.hash) {

        // This block appends to the current chain tip and we can
        // immediately add it to the chain and create indexes.

        // Populate height
        block.__height = self.chain.tip.__height + 1;

        // Update chain hashes
        self.chain.cache.hashes[block.hash] = block.prevHash;

        // Create indexes
        self.db._onChainAddBlock(block, function(err) {
          if (err) {
            return done(err);
          }
          delete self.chain.tip.__transactions;
          self.chain.tip = block;
          log.debug('Saving metadata');
          self.chain.saveMetadata();
          log.debug('Chain added block to main chain');
          self.chain.emit('addblock', block);
          done();
        });

      } else {

        // This block doesn't progress the current tip, so we'll attempt
        // to rewind the chain to the common ancestor of the block and
        // then we can resume syncing.
        self._syncBitcoindRewind(block, done);

      }
    });
  }, function(err) {
    log.info('Stopping Bitcoind Sync');
    self.bitcoindSyncing = false;
    if (err) {
      Error.captureStackTrace(err);
      return self.emit('error', err);
    }
    self.emit('synced');
  });

};

Node.prototype._loadNetwork = function(config) {
  if (config.network === 'testnet') {
    this.network = Networks.get('testnet');
  } else if (config.network === 'regtest') {
    Networks.remove(Networks.testnet);
    Networks.add({
      name: 'regtest',
      alias: 'regtest',
      pubkeyhash: 0x6f,
      privatekey: 0xef,
      scripthash: 0xc4,
      xpubkey: 0x043587cf,
      xprivkey: 0x04358394,
      networkMagic: 0xfabfb5da,
      port: 18444,
      dnsSeeds: [ ]
    });
    this.network = Networks.get('regtest');
  } else {
    this.network = Networks.get('livenet');
  }
  $.checkState(this.network, 'Unrecognized network');
};

Node.prototype._loadDB = function(config) {
  if (config.DB) {
    // Other modules can inherit from our DB and replace it with their own
    DB = config.DB;
  }

  if(!config.db) {
    config.db = {};
  }

  // Store the additional indexes in a new directory
  // based on the network configuration and the datadir
  $.checkArgument(config.datadir, 'Please specify "datadir" in configuration options');
  $.checkState(this.network, 'Network property not defined');
  var regtest = Networks.get('regtest');
  var datadir = config.datadir.replace(/^~/, process.env.HOME);
  if (this.network === Networks.livenet) {
    config.db.path = datadir + '/bitcore-node.db';
  } else if (this.network === Networks.testnet) {
    config.db.path = datadir + '/testnet3/bitcore-node.db';
  } else if (this.network === regtest) {
    config.db.path = datadir + '/regtest/bitcore-node.db';
  } else {
    throw new Error('Unknown network: ' + this.network);
  }
  config.db.network = this.network;

  if (!fs.existsSync(config.db.path)) {
    mkdirp.sync(config.db.path);
  }

  this.db = new DB(config.db);
};

Node.prototype._loadConsensus = function(config) {
  if (!config.consensus) {
    config.consensus = {};
  }

  this.Block = Block;

  var genesisBlock;
  if (config.genesis) {
    genesisBlock = config.genesis;
  } else if (config.network === 'testnet') {
    genesisBlock = genesis.testnet;
  } else {
    genesisBlock = genesis.livenet;
  }

  if (_.isString(genesisBlock)) {
    genesisBlock = this.Block.fromBuffer(new Buffer(genesisBlock, 'hex'));
  }

  // pass genesis to chain
  config.consensus.genesis = genesisBlock;
  this.chain = new Chain(config.consensus);
};

Node.prototype._initializeBitcoind = function() {
  var self = this;

  this.bitcoind.on('ready', function(status) {
    log.info('Bitcoin Daemon Ready');
    // Set the current chain height
    var info = self.bitcoind.getInfo();
    self.bitcoindHeight = info.blocks;
    self.db.initialize();
  });

  this.bitcoind.on('open', function(status) {
    log.info('Bitcoin Core Daemon Status:', status);
  });

  // Notify that there is a new tip
  this.bitcoind.on('tip', function(height) {
    log.info('Bitcoin Core Daemon New Height:', height);
    self.bitcoindHeight = height;
    self._syncBitcoind();
  });

  this.bitcoind.on('error', function(err) {
    Error.captureStackTrace(err);
    self.emit('error', err);
  });

};

Node.prototype._initializeDatabase = function() {
  var self = this;

  // Database
  this.db.on('ready', function() {
    log.info('Bitcoin Database Ready');
    self.chain.initialize();
  });

  this.db.on('error', function(err) {
    Error.captureStackTrace(err);
    self.emit('error', err);
  });
};

Node.prototype._initializeChain = function() {
  var self = this;

  // Chain
  this.chain.on('ready', function() {
    log.info('Bitcoin Chain Ready');
    self._syncBitcoind();
    self.emit('ready');
  });

  this.chain.on('error', function(err) {
    Error.captureStackTrace(err);
    self.emit('error', err);
  });
};

Node.prototype._initialize = function() {

  var self = this;

  // DB References
  this.db.chain = this.chain;
  this.db.Block = this.Block;
  this.db.bitcoind = this.bitcoind;

  // Chain References
  this.chain.db = this.db;

  // Setup Chain of Events
  this._initializeBitcoind();
  this._initializeDatabase();
  this._initializeChain();

};

module.exports = Node;
<commit_msg>Speed up syncing by delaying saving metadata every 30 seconds.<commit_after>'use strict';

var async = require('async');
var Chain = require('./chain');
var Block = require('./block');
var DB = require('./db');
var chainlib = require('chainlib');
var fs = require('fs');
var BaseNode = chainlib.Node;
var util = require('util');
var mkdirp = require('mkdirp');
var log = chainlib.log;
var bitcore = require('bitcore');
var Networks = bitcore.Networks;
var _ = bitcore.deps._;
var $ = bitcore.util.preconditions;
var genesis = require('./genesis.json');
var daemon = require('./daemon');
var Bus = require('./bus');

function Node(config) {
  BaseNode.call(this, config);
  this.testnet = config.testnet;
}

util.inherits(Node, BaseNode);

Node.prototype.openBus = function() {
  return new Bus({db: this.db});
};

Node.prototype.getAllAPIMethods = function() {
  var methods = this.db.getAPIMethods();
  for (var i = 0; i < this.db.modules.length; i++) {
    var mod = this.db.modules[i];
    methods = methods.concat(mod.getAPIMethods());
  }
  return methods;
};

Node.prototype.getAllPublishEvents = function() {
  var events = [];
  for (var i = 0; i < this.db.modules.length; i++) {
    var mod = this.db.modules[i];
    events = events.concat(mod.getPublishEvents());
  }
  return events;
};

Node.prototype._loadConfiguration = function(config) {
  var self = this;
  this._loadBitcoinConf(config);
  this._loadBitcoind(config);
  Node.super_.prototype._loadConfiguration.call(self, config);
};

Node.DEFAULT_DAEMON_CONFIG = 'whitelist=127.0.0.1\n' + 'txindex=1\n';

Node.prototype._loadBitcoinConf = function(config) {
  $.checkArgument(config.datadir, 'Please specify "datadir" in configuration options');
  var datadir = config.datadir.replace(/^~/, process.env.HOME);
  var configPath = datadir + '/bitcoin.conf';
  this.bitcoinConfiguration = {};

  if (!fs.existsSync(datadir)) {
    mkdirp.sync(datadir);
  }

  if (!fs.existsSync(configPath)) {
    fs.writeFileSync(configPath, Node.DEFAULT_DAEMON_CONFIG);
  }

  var file = fs.readFileSync(configPath);
  var unparsed = file.toString().split('\n');
  for(var i = 0; i < unparsed.length; i++) {
    var line = unparsed[i];
    if (!line.match(/^\#/) && line.match(/\=/)) {
      var option = line.split('=');
      var value;
      if (!Number.isNaN(Number(option[1]))) {
        value = Number(option[1]);
      } else {
        value = option[1];
      }
      this.bitcoinConfiguration[option[0]] = value;
    }
  }

};

Node.prototype._loadBitcoind = function(config) {
  var bitcoindConfig = {};
  bitcoindConfig.datadir = config.datadir;
  bitcoindConfig.network = config.network;

  // start the bitcoind daemon
  this.bitcoind = daemon(bitcoindConfig);

};

/**
 * This function will find the common ancestor between the current chain and a forked block,
 * by moving backwards from the forked block until it meets the current chain.
 * @param {Block} block - The new tip that forks the current chain.
 * @param {Function} done - A callback function that is called when complete.
 */
Node.prototype._syncBitcoindAncestor = function(block, done) {

  var self = this;

  // The current chain of hashes will likely already be available in a cache.
  self.chain.getHashes(self.chain.tip.hash, function(err, currentHashes) {
    if (err) {
      done(err);
    }

    // Create a hash map for faster lookups
    var currentHashesMap = {};
    var length = currentHashes.length;
    for (var i = 0; i < length; i++) {
      currentHashesMap[currentHashes[i]] = true;
    }

    var ancestorHash = block.prevHash;

    // We only need to go back until we meet the main chain for the forked block
    // and thus don't need to find the entire chain of hashes.

    async.whilst(function() {
      // Wait until the previous hash is in the current chain
      return ancestorHash && !currentHashesMap[ancestorHash];
    }, function(next) {
      self.bitcoind.getBlockIndex(ancestorHash, function(err, blockIndex) {
        if (err) {
          return next(err);
        }
        ancestorHash = blockIndex.prevHash;
        next();
      });
    }, function(err) {

      // Hash map is no-longer needed, quickly let
      // scavenging garbage collection know to cleanup
      currentHashesMap = null;

      if (err) {
        return done(err);
      } else if (!ancestorHash) {
        return done(new Error('Unknown common ancestor.'));
      }

      done(null, ancestorHash);
    });
  });
};

/**
 * This function will attempt to rewind the chain to the common ancestor
 * between the current chain and a forked block.
 * @param {Block} block - The new tip that forks the current chain.
 * @param {Function} done - A callback function that is called when complete.
 */
Node.prototype._syncBitcoindRewind = function(block, done) {

  var self = this;

  self._syncBitcoindAncestor(block, function(err, ancestorHash) {

    // Rewind the chain to the common ancestor
    async.whilst(
      function() {
        // Wait until the tip equals the ancestor hash
        return self.chain.tip.hash !== ancestorHash;
      },
      function(removeDone) {

        var tip = self.chain.tip;

        self.getBlock(tip.prevHash, function(err, previousTip) {
          if (err) {
            removeDone(err);
          }

          // Undo the related indexes for this block
          self.db._onChainRemoveBlock(tip, function(err) {
            if (err) {
              return removeDone(err);
            }

            // Set the new tip
            delete self.chain.tip.__transactions;
            previousTip.__height = self.chain.tip.__height - 1;
            self.chain.tip = previousTip;
            self.chain.saveMetadata();
            self.chain.emit('removeblock', tip);
            removeDone();
          });

        });

      }, done
    );
  });
};

/**
 * This function will synchronize additional indexes for the chain based on
 * the current active chain in the bitcoin daemon. In the event that there is
 * a reorganization in the daemon, the chain will rewind to the last common
 * ancestor and then resume syncing.
 */
Node.prototype._syncBitcoind = function() {
  var self = this;

  if (self.bitcoindSyncing) {
    return;
  }

  if (!self.chain.tip) {
    return;
  }

  self.bitcoindSyncing = true;
  self.chain.lastSavedMetadataThreshold = 30000;

  log.info('Starting Bitcoind Sync');

  var height;

  async.whilst(function() {
    height = self.chain.tip.__height;
    return height < self.bitcoindHeight;
  }, function(done) {
    self.bitcoind.getBlock(height + 1, function(err, blockBuffer) {
      if (err) {
        return done(err);
      }
      var block = self.Block.fromBuffer(blockBuffer);
      if (block.prevHash === self.chain.tip.hash) {

        // This block appends to the current chain tip and we can
        // immediately add it to the chain and create indexes.

        // Populate height
        block.__height = self.chain.tip.__height + 1;

        // Update chain hashes
        self.chain.cache.hashes[block.hash] = block.prevHash;

        // Create indexes
        self.db._onChainAddBlock(block, function(err) {
          if (err) {
            return done(err);
          }
          delete self.chain.tip.__transactions;
          self.chain.tip = block;
          log.debug('Saving metadata');
          self.chain.saveMetadata();
          log.debug('Chain added block to main chain');
          self.chain.emit('addblock', block);
          done();
        });

      } else {

        // This block doesn't progress the current tip, so we'll attempt
        // to rewind the chain to the common ancestor of the block and
        // then we can resume syncing.
        self._syncBitcoindRewind(block, done);

      }
    });
  }, function(err) {
    log.info('Stopping Bitcoind Sync');
    self.bitcoindSyncing = false;
    self.chain.lastSavedMetadataThreshold = 0;
    if (err) {
      Error.captureStackTrace(err);
      return self.emit('error', err);
    }
    self.emit('synced');
  });

};

Node.prototype._loadNetwork = function(config) {
  if (config.network === 'testnet') {
    this.network = Networks.get('testnet');
  } else if (config.network === 'regtest') {
    Networks.remove(Networks.testnet);
    Networks.add({
      name: 'regtest',
      alias: 'regtest',
      pubkeyhash: 0x6f,
      privatekey: 0xef,
      scripthash: 0xc4,
      xpubkey: 0x043587cf,
      xprivkey: 0x04358394,
      networkMagic: 0xfabfb5da,
      port: 18444,
      dnsSeeds: [ ]
    });
    this.network = Networks.get('regtest');
  } else {
    this.network = Networks.get('livenet');
  }
  $.checkState(this.network, 'Unrecognized network');
};

Node.prototype._loadDB = function(config) {
  if (config.DB) {
    // Other modules can inherit from our DB and replace it with their own
    DB = config.DB;
  }

  if(!config.db) {
    config.db = {};
  }

  // Store the additional indexes in a new directory
  // based on the network configuration and the datadir
  $.checkArgument(config.datadir, 'Please specify "datadir" in configuration options');
  $.checkState(this.network, 'Network property not defined');
  var regtest = Networks.get('regtest');
  var datadir = config.datadir.replace(/^~/, process.env.HOME);
  if (this.network === Networks.livenet) {
    config.db.path = datadir + '/bitcore-node.db';
  } else if (this.network === Networks.testnet) {
    config.db.path = datadir + '/testnet3/bitcore-node.db';
  } else if (this.network === regtest) {
    config.db.path = datadir + '/regtest/bitcore-node.db';
  } else {
    throw new Error('Unknown network: ' + this.network);
  }
  config.db.network = this.network;

  if (!fs.existsSync(config.db.path)) {
    mkdirp.sync(config.db.path);
  }

  this.db = new DB(config.db);
};

Node.prototype._loadConsensus = function(config) {
  if (!config.consensus) {
    config.consensus = {};
  }

  this.Block = Block;

  var genesisBlock;
  if (config.genesis) {
    genesisBlock = config.genesis;
  } else if (config.network === 'testnet') {
    genesisBlock = genesis.testnet;
  } else {
    genesisBlock = genesis.livenet;
  }

  if (_.isString(genesisBlock)) {
    genesisBlock = this.Block.fromBuffer(new Buffer(genesisBlock, 'hex'));
  }

  // pass genesis to chain
  config.consensus.genesis = genesisBlock;
  this.chain = new Chain(config.consensus);
};

Node.prototype._initializeBitcoind = function() {
  var self = this;

  this.bitcoind.on('ready', function(status) {
    log.info('Bitcoin Daemon Ready');
    // Set the current chain height
    var info = self.bitcoind.getInfo();
    self.bitcoindHeight = info.blocks;
    self.db.initialize();
  });

  this.bitcoind.on('open', function(status) {
    log.info('Bitcoin Core Daemon Status:', status);
  });

  // Notify that there is a new tip
  this.bitcoind.on('tip', function(height) {
    log.info('Bitcoin Core Daemon New Height:', height);
    self.bitcoindHeight = height;
    self._syncBitcoind();
  });

  this.bitcoind.on('error', function(err) {
    Error.captureStackTrace(err);
    self.emit('error', err);
  });

};

Node.prototype._initializeDatabase = function() {
  var self = this;

  // Database
  this.db.on('ready', function() {
    log.info('Bitcoin Database Ready');
    self.chain.initialize();
  });

  this.db.on('error', function(err) {
    Error.captureStackTrace(err);
    self.emit('error', err);
  });
};

Node.prototype._initializeChain = function() {
  var self = this;

  // Chain
  this.chain.on('ready', function() {
    log.info('Bitcoin Chain Ready');
    self._syncBitcoind();
    self.emit('ready');
  });

  this.chain.on('error', function(err) {
    Error.captureStackTrace(err);
    self.emit('error', err);
  });
};

Node.prototype._initialize = function() {

  var self = this;

  // DB References
  this.db.chain = this.chain;
  this.db.Block = this.Block;
  this.db.bitcoind = this.bitcoind;

  // Chain References
  this.chain.db = this.db;

  // Setup Chain of Events
  this._initializeBitcoind();
  this._initializeDatabase();
  this._initializeChain();

};

module.exports = Node;
<|endoftext|>


<commit_before>// This script is responsible for
// tests the HTTP routes.

const request = require('supertest');

describe('loading express', function() {

	// Instantiate the server
	var server;

	beforeEach(function() {
		// Remove cache
		delete require.cache[require.resolve('../server.js')];
		server = require('../server.js');
	});

	afterEach(function(done) {
		server.close(done);
	});

	it('responds to /', function testSlash(done) {
		request(server)
			.get('/')
			.expect(200, done);
	});

	it('404 everything else', function testPath(done) {
		console.log('test 404');
		request(server)
			.get('/foo/bar')
			.expect(404, done);
	});

});<commit_msg>Fixing indentation<commit_after>// This script is responsible for
// tests the HTTP routes.

const request = require('supertest');

describe('loading express', function() {

  // Instantiate the server
  var server;

  beforeEach(function() {
  	// Remove cache
  	delete require.cache[require.resolve('../server.js')];
  	server = require('../server.js');
  });

  afterEach(function(done) {
  	server.close(done);
  });

  it('responds to /', function testSlash(done) {
  	request(server)
  		.get('/')
  		.expect(200, done);
  });

  it('404 everything else', function testPath(done) {
  	console.log('test 404');
  	request(server)
  		.get('/foo/bar')
  		.expect(404, done);
  });

});<|endoftext|>


<commit_before>Main = function() {
  // Hello there
};

Main.prototype.run = function() {
  this.init();
  this.animate();
};

Main.prototype.init = function() {
  this.clock = new THREE.Clock();

  this.container = document.createElement('div');
  this.container.style.left = '0';
  this.container.style.right = '0';
  this.container.style.top = '0';
  this.container.style.bottom = '0';
  this.container.style.position = 'absolute';
  document.body.appendChild(this.container);

  this.renderer = new THREE.WebGLRenderer();
  this.container.appendChild(this.renderer.domElement);
  this.materials = new Materials(this.renderer);

  this.effect = new THREE.StereoEffect(this.renderer);

  this.camera = new THREE.PerspectiveCamera(90, 1, 0.001, 700);
  this.camera.position.set(0, 4, 0);
  this.camera.lookAt(new THREE.Vector3(30, 4, 0));

  // Controls

  this.controls = new DeviceOrientationController(this.camera, this.renderer.domElement);
  this.controls.connect();

  this.world = new World(this.camera);
  this.world.init();

  this.scene = new THREE.Scene();

  var light = new THREE.HemisphereLight(0x777777, 0x000000, 0.6);
  this.scene.add(light);

/*
  var ambientLight = new THREE.AmbientLight(0xaaaaaa);
  this.scene.add(ambientLight);

  var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
  directionalLight.position.set(1, 0.8, 0.5).normalize();
  this.scene.add(directionalLight);
*/

  var root = this.world.getRoot();
  this.scene.add(root);

  this.stats = new Stats();
  this.stats.domElement.style.position = 'absolute';
  this.stats.domElement.style.top = '0px';
  this.container.appendChild(this.stats.domElement);

  this.createFullscreenButton();

  this.animate_ = $.proxy(this.animate, this);

  window.addEventListener('resize', $.proxy(this.onWindowResize, this), false);
  setTimeout($.proxy(this.onWindowResize, this), 1);
};

Main.prototype.createFullscreenButton = function() {
  var fs = document.createElement('img');
  fs.style.left = '0';
  fs.style.bottom = '0';
  fs.style.position = 'absolute';
  fs.style.maxWidth = '20%';
  fs.style.maxHeight = '20%';
  fs.style.opacity = '0.5';
  fs.src = "textures/fullscreen.png";
  fs.alt = 'Fullscreen';
  fs.addEventListener('click', $.proxy(this.fullscreen, this), false);
  this.container.appendChild(fs);
};

Main.prototype.onWindowResize = function() {
  var width = this.container.offsetWidth;
  var height = this.container.offsetHeight;

  this.camera.aspect = width / height;
  this.camera.updateProjectionMatrix();

  this.renderer.setSize(width, height);
  this.effect.setSize(width, height);
};

Main.prototype.animate = function() {
  requestAnimationFrame(this.animate_);

  this.update(this.clock.getDelta());
  this.render(this.clock.getDelta());
};

Main.prototype.update = function(dt) {
  this.world.update(dt);
  this.camera.updateProjectionMatrix();
  this.controls.update(dt);
  this.stats.update();
};

Main.prototype.render = function(dt) {
  this.effect.render(this.scene, this.camera);
};

Main.prototype.fullscreen = function() {
  if (this.container.requestFullscreen) {
    this.container.requestFullscreen();
  } else if (this.container.msRequestFullscreen) {
    this.container.msRequestFullscreen();
  } else if (this.container.mozRequestFullScreen) {
    this.container.mozRequestFullScreen();
  } else if (this.container.webkitRequestFullscreen) {
    this.container.webkitRequestFullscreen();
  }
};

(function() {
  var m = new Main();
  m.run();
})();<commit_msg>Adding 0.6 separation<commit_after>Main = function() {
  // Hello there
};

Main.prototype.run = function() {
  this.init();
  this.animate();
};

Main.prototype.init = function() {
  this.clock = new THREE.Clock();

  this.container = document.createElement('div');
  this.container.style.left = '0';
  this.container.style.right = '0';
  this.container.style.top = '0';
  this.container.style.bottom = '0';
  this.container.style.position = 'absolute';
  document.body.appendChild(this.container);

  this.renderer = new THREE.WebGLRenderer();
  this.container.appendChild(this.renderer.domElement);
  this.materials = new Materials(this.renderer);

  this.effect = new THREE.StereoEffect(this.renderer);
  this.effect.separation = 0.6;

  this.camera = new THREE.PerspectiveCamera(90, 1, 0.001, 700);
  this.camera.position.set(0, 4, 0);
  this.camera.lookAt(new THREE.Vector3(30, 4, 0));

  // Controls

  this.controls = new DeviceOrientationController(this.camera, this.renderer.domElement);
  this.controls.connect();

  this.world = new World(this.camera);
  this.world.init();

  this.scene = new THREE.Scene();

  var light = new THREE.HemisphereLight(0x777777, 0x000000, 0.6);
  this.scene.add(light);

/*
  var ambientLight = new THREE.AmbientLight(0xaaaaaa);
  this.scene.add(ambientLight);

  var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
  directionalLight.position.set(1, 0.8, 0.5).normalize();
  this.scene.add(directionalLight);
*/

  var root = this.world.getRoot();
  this.scene.add(root);

  this.stats = new Stats();
  this.stats.domElement.style.position = 'absolute';
  this.stats.domElement.style.top = '0px';
  this.container.appendChild(this.stats.domElement);

  this.createFullscreenButton();

  this.animate_ = $.proxy(this.animate, this);

  window.addEventListener('resize', $.proxy(this.onWindowResize, this), false);
  setTimeout($.proxy(this.onWindowResize, this), 1);
};

Main.prototype.createFullscreenButton = function() {
  var fs = document.createElement('img');
  fs.style.left = '0';
  fs.style.bottom = '0';
  fs.style.position = 'absolute';
  fs.style.maxWidth = '20%';
  fs.style.maxHeight = '20%';
  fs.style.opacity = '0.5';
  fs.src = "textures/fullscreen.png";
  fs.alt = 'Fullscreen';
  fs.addEventListener('click', $.proxy(this.fullscreen, this), false);
  this.container.appendChild(fs);
};

Main.prototype.onWindowResize = function() {
  var width = this.container.offsetWidth;
  var height = this.container.offsetHeight;

  this.camera.aspect = width / height;
  this.camera.updateProjectionMatrix();

  this.renderer.setSize(width, height);
  this.effect.setSize(width, height);
};

Main.prototype.animate = function() {
  requestAnimationFrame(this.animate_);

  this.update(this.clock.getDelta());
  this.render(this.clock.getDelta());
};

Main.prototype.update = function(dt) {
  this.world.update(dt);
  this.camera.updateProjectionMatrix();
  this.controls.update(dt);
  this.stats.update();
};

Main.prototype.render = function(dt) {
  this.effect.render(this.scene, this.camera);
};

Main.prototype.fullscreen = function() {
  if (this.container.requestFullscreen) {
    this.container.requestFullscreen();
  } else if (this.container.msRequestFullscreen) {
    this.container.msRequestFullscreen();
  } else if (this.container.mozRequestFullScreen) {
    this.container.mozRequestFullScreen();
  } else if (this.container.webkitRequestFullscreen) {
    this.container.webkitRequestFullscreen();
  }
};

(function() {
  var m = new Main();
  m.run();
})();<|endoftext|>


<commit_before>/* global __dirname:true, process:true */

/**
 * Module dependencies
 */

var oidc             = require('../oidc')
  , settings         = require('../boot/settings')
  , mailer           = require('../boot/mailer')
  , passwordProvider = require('../providers').password
  , passport         = require('passport')
  , qs               = require('qs')
  , User             = require('../models/User')
  , nodemailer       = require('nodemailer')
  , path             = require('path')
  , url              = require('url')
  , templatesDir     = path.resolve(process.cwd(), 'email')
  , consolidate      = require('consolidate')
  , PasswordsDisabledError = require('../errors/PasswordsDisabledError')
  ;

/**
 * Signup Endpoint
 */

module.exports = function (server) {

  /**
   * Signup page
   */

  var getSignupHandler = [
    oidc.selectConnectParams,
    oidc.validateAuthorizationParams,
    oidc.verifyClient,
    function (req, res, next) {
      res.render('signup', {
        params:    qs.stringify(req.query),
        request:   req.query,
        providers: settings.providers
      });
    }
  ];

  /**
   * Password signup handler
   */

  function createUser(req, res, next) {
    User.insert(req.body, { private: true }, function (err, user) {
      if (err) {
        res.render('signup', {
          params:    qs.stringify(req.body),
          request:   req.body,
          providers: settings.providers,
          error:     err.message
        });
      } else {
        passport.authenticate('password', function (err, user, info) {
          if (!user) {
          } else {
            req.login(user, function (err) {
              next(err);
            });
          }
        })(req, res, next);
      }
    });
  }

  function sendVerificationEmail(req, res, next) {
    if (!passwordProvider.emailVerification.enable) {
      next();
    } else {

      var locals = {
        email: req.user.email,
        name: {
          first: req.user.givenName,
          last: req.user.familyName
        },
        verifyURL: url.resolve(settings.issuer, 'email/verify?token=' + req.user.emailVerifyToken)
      };

      mailer.sendMail('verifyEmail', locals, {

        from: mailer.from,
        to: locals.email,
        subject: 'Verify your e-mail address'

      }, function(err, responseStatus) {

        if (err) {
          return next(err);
        } else {
          next();
        }

      });
    }
  }

  var postSignupHandler = [
    oidc.selectConnectParams,
    oidc.validateAuthorizationParams,
    oidc.verifyClient,
    createUser,
    sendVerificationEmail,
    oidc.determineUserScope,
    oidc.promptToAuthorize,
    oidc.authorize
  ];

  if (oidc.beforeAuthorize) {
    postSignupHandler.splice(postSignupHandler.length - 1, 0, oidc.beforeAuthorize);
  }

  /**
   * Passwords Disabled Handler
   */

  function passwordsDisabledHandler (req, res, next) {
    next(new PasswordsDisabledError());
  }

  // Only register the password signup handlers
  // if the password protocol is enabled.
  if (settings.providers.password) {
    server.get('/signup', getSignupHandler);
    server.post('/signup', postSignupHandler);
  } else {
    server.get('/signup', passwordsDisabledHandler);
    server.post('/signup', passwordsDisabledHandler);
  }

};

<commit_msg>refactor(signup): Use user.sendVerificationEmail<commit_after>/* global __dirname:true, process:true */

/**
 * Module dependencies
 */

var oidc             = require('../oidc')
  , settings         = require('../boot/settings')
  , mailer           = require('../boot/mailer')
  , passwordProvider = require('../providers').password
  , passport         = require('passport')
  , qs               = require('qs')
  , User             = require('../models/User')
  , nodemailer       = require('nodemailer')
  , path             = require('path')
  , url              = require('url')
  , templatesDir     = path.resolve(process.cwd(), 'email')
  , consolidate      = require('consolidate')
  , PasswordsDisabledError = require('../errors/PasswordsDisabledError')
  ;

/**
 * Signup Endpoint
 */

module.exports = function (server) {

  /**
   * Signup page
   */

  var getSignupHandler = [
    oidc.selectConnectParams,
    oidc.validateAuthorizationParams,
    oidc.verifyClient,
    function (req, res, next) {
      res.render('signup', {
        params:    qs.stringify(req.query),
        request:   req.query,
        providers: settings.providers
      });
    }
  ];

  /**
   * Password signup handler
   */

  function createUser(req, res, next) {
    User.insert(req.body, { private: true }, function (err, user) {
      if (err) {
        res.render('signup', {
          params:    qs.stringify(req.body),
          request:   req.body,
          providers: settings.providers,
          error:     err.message
        });
      } else {
        passport.authenticate('password', function (err, user, info) {
          if (!user) {
          } else {
            req.login(user, function (err) {
              next(err);
            });
          }
        })(req, res, next);
      }
    });
  }

  function sendVerificationEmail(req, res, next) {
    if (!passwordProvider.emailVerification.enable) {
      next();
    } else {
      req.user.sendVerificationEmail(function (err, responseStatus) {
        next(err);
      });
    }
  }

  var postSignupHandler = [
    oidc.selectConnectParams,
    oidc.validateAuthorizationParams,
    oidc.verifyClient,
    createUser,
    sendVerificationEmail,
    oidc.determineUserScope,
    oidc.promptToAuthorize,
    oidc.authorize
  ];

  if (oidc.beforeAuthorize) {
    postSignupHandler.splice(postSignupHandler.length - 1, 0, oidc.beforeAuthorize);
  }

  /**
   * Passwords Disabled Handler
   */

  function passwordsDisabledHandler (req, res, next) {
    next(new PasswordsDisabledError());
  }

  // Only register the password signup handlers
  // if the password protocol is enabled.
  if (settings.providers.password) {
    server.get('/signup', getSignupHandler);
    server.post('/signup', postSignupHandler);
  } else {
    server.get('/signup', passwordsDisabledHandler);
    server.post('/signup', passwordsDisabledHandler);
  }

};

<|endoftext|>